ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4

C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
4DBugandClaude Opus 5.5 committed 2026-10-31 12:25:03 -05:00
1 parent 9c553b9d1a
commit 434a304315
283 files changed
+1877 -1660

No files matched your search

@@ -0,0 +1,293 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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 = buffer.readu8
local band, lshift = bit32.band, bit32.lshift
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
-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces).
local P2 = table.create(33, 1) -- P2[k + 1] = 2^k
for k = 0, 32 do
P2[k + 1] = 2 ^ k
end
Bitstream.P2 = P2
local LZ8 = table.create(256, 0) -- LZ8[x + 1] = leading zero bits of the byte x (8 for 0)
for x = 0, 255 do
local n, v = 0, x
while n < 8 and v < 128 do
v *= 2
n += 1
end
LZ8[x + 1] = n
end
Bitstream.LZ8 = LZ8
-- clz32(v) -> leading zero bits of a 32-bit value
local function clz32(v: number): number
if v >= 16777216 then
return LZ8[v // 16777216 + 1]
elseif v >= 65536 then
return 8 + LZ8[v // 65536 + 1]
elseif v >= 256 then
return 16 + LZ8[v // 256 + 1]
end
return 24 + LZ8[v + 1]
end
Bitstream.clz32 = clz32
-- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end
local function peekAt(b: buffer, n: number, pos: number): number
local p = pos // 8
if p + 5 > n then
return 0
end
local s = pos - p * 8
local w = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
if s == 0 then
return w
end
return (w * P2[s + 1]) % 4294967296 + readu8(b, p + 4) // P2[9 - s]
end
Bitstream.peekAt = peekAt
-- peek32(r) -> the next 32 bits (zeros past the end)
local function peek32(r: Reader): number
return peekAt(r.buf, r.n, r.pos)
end
Bitstream.peek32 = peek32
-- u(r, n) -> n bits (n 1..32) as an unsigned number
function Bitstream.u(r: Reader, n: number): number
local v = peekAt(r.buf, r.n, r.pos)
r.pos += n
return v // P2[33 - n]
end
-- u1(r) -> one bit
function Bitstream.u1(r: Reader): number
local pos = r.pos
r.pos = pos + 1
local p = pos // 8
if p >= r.n then
return 0
end
return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2
end
-- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element)
local function ue(r: Reader): number
local v = peekAt(r.buf, r.n, r.pos)
if v == 0 then
r.pos += 32
return 4294967296
end
local lz = clz32(v)
if lz < 16 then
local n = 2 * lz + 1
r.pos += n
return v // P2[33 - n] - 1
end
r.pos += lz
v = peekAt(r.buf, r.n, r.pos)
r.pos += lz + 1
return v // P2[32 - 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
File diff suppressed because it is too large. Load diff
+772
View File
@@ -0,0 +1,772 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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/video/H264/Bitstream")
local Tables = require("@formats/codecs/video/H264/Tables")
local Mb = require("@formats/codecs/video/H264/Mb")
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 peek = Bitstream.peekAt
local clz32 = Bitstream.clz32
local P2 = Bitstream.P2
-- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to
-- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels)
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 = peek(b, n, pos) // 65536
local e = CT1[cls][v // 256 + 1]
if e < 0 then
e = CT2[cls][-e + v % 256]
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] = 1 - 2 * ((w // P2[32 - i]) % 2)
end
pos += t1
local suffixLength = ((tc > 10 and t1 < 3) and (1) or (0))
for i = t1, tc - 1 do
w = peek(b, n, pos)
local prefix = if w == 0 then 32 else clz32(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 = (((prefix < 15) and (prefix) or (15))) * 2 ^ suffixLength
if size > 0 then
levelCode += peek(b, n, pos) // P2[33 - 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 = ((level < 0) and (-level) or (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 = peek(b, n, pos) // 65536
local l1, l2
if maxCoeff == 4 then
l1, l2 = TZC1[tc], TZC2[tc]
else
l1, l2 = TZ1[tc], TZ2[tc]
end
e = l1[v // 256 + 1]
if e < 0 then
e = l2[-e + v % 256]
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 = ((zerosLeft > 7) and (7) or (zerosLeft))
v = peek(b, n, pos) // 65536
e = RB1[t][v // 256 + 1]
if e < 0 then
e = RB2[t][-e + v % 256]
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[((intra) and (1) or (4))][qp + 1]
if M.t8 == 1 then
local mul8 = dq.d8[((intra) and (1) or (2))][qp + 1]
local c8 = M.c8
for i8 = 0, 3 do
local bx0, by0 = (i8 % 2) * 2, (i8 // 2) * 2
local sum = 0
for i4 = 0, 3 do
local bx, by = bx0 + i4 % 2, by0 + i4 // 2
local tc = 0
if (cbp // P2[i8 + 1]) % 2 ~= 0 then
tc = residual(r, Mb.nC(S, M, bx, by), 16, c8, i8 * 64, ZZ8I[i4 + 1], mul8, 64)
if tc < 0 then
return false, "bad 8x8 luma residual"
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 (cbp // P2[i // 4 + 1]) % 2 ~= 0 then
if ac then
tc = residual(r, Mb.nC(S, M, bx, by), 15, c4, blk * 16, ZZAC, mul4, 16)
else
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 = ((plane == 0) and (nzcCb) or (nzcCr))
local mulc = dq.d4[(((intra) and (2) or (5))) + plane][(((plane == 0) and (M.qpc) or (M.qpc2))) + 1]
for blk = 0, 3 do
local bx, by = blk % 2, blk // 2
local tc = 0
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 = ((rem < pred) and (rem) or (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 = ((rem < pred) and (rem) or (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 + (((t >= 13) and (15) or (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 = ((t >= 3) and (3) or (t))
pf[1], pf[2], pf[3], pf[4] = 1, 1, 1, 1
if M.part == 3 then
for i = 1, 4 do
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 = ((t == 4) and (0) or (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 = ((M.part == 0) and (1) or (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 = ((t % 2 == 0) and (1) or (2))
local k = (t - 4) // 2 + 1
pf[1], pf[2] = BPAIR0[k], BPAIR1[k]
end
local n = ((M.part == 0) and (1) or (2))
for p = 1, n do
if pf[p] % 2 == 1 then
local v = refIdx(r, n0)
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 = ((l == 0) and (mvd0) or (mvd1))
for i = 0, 3 do
local uses = pf[i + 1] >= 2
if l == 0 then
uses = pf[i + 1] % 2 == 1
end
if uses and not dir[i + 1] then
for k = 0, SUB_N[sub[i + 1] + 1] - 1 do
local p = i * 4 + k + 1
mvd[2 * p - 1] = se(r)
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 = ((st == 1) and (K_BSKIP) or (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
+260
View File
@@ -0,0 +1,260 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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/video/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 min, max = math.min, math.max
local function clip3(lo: number, hi: number, v: number): number
return min(max(v, lo), hi)
end
local abs = math.abs
-- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1
-- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four
-- 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 + (((ap < beta) and (1) or (0))) + (((aq < beta) and (1) or (0)))
local delta = clip3(-tc, tc, ((q0 - p0) * 4 + (p1 - q1) + 4) // 8)
writeu8(b, q - across, clip3(0, 255, p0 + delta))
writeu8(b, q, clip3(0, 255, q0 - delta))
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 = (((pa >= 0) and (1) or (0))) + (((pb >= 0) and (1) or (0)))
local nq = (((qa >= 0) and (1) or (0))) + (((qb >= 0) and (1) or (0)))
if np ~= nq then
return true
end
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 = ((dir == 0) and (addr - 1) or (addr - mbW))
local edgeOk = my > 0
if dir == 0 then
edgeOk = mx > 0
end
if edgeOk and idc == 2 and sliceTab[nAddr] ~= sn then
edgeOk = false
end
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 = ((e == 0) and (4) or (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
File diff suppressed because it is too large. Load diff
+266
View File
@@ -0,0 +1,266 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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 min, max = math.min, math.max
local function clip(v: number): number
return min(max(v, 0), 255)
end
-- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns
local B1 = table.create(24 * 17, 0)
-- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each
-- sample once per row / column
local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number })
for r = 0, h - 1 do
local o = base + r * s
local d = r * 16 + 1
for c = 0, w - 1 do
P[d + c] = readu8(ref, o + c)
end
end
end
-- horizontal half sample b; avg 0: b, 1: (G + b + 1) >> 1, 2: (b + H + 1) >> 1
local function lumaH(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number)
for r = 0, h - 1 do
local o = base + r * s
local d = r * 16 + 1
local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2)
for c = 0, w - 1 do
local a5 = readu8(ref, o + c + 3)
local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
if avg == 1 then
v = (v + a2 + 1) // 2
elseif avg == 2 then
v = (v + a3 + 1) // 2
end
P[d + c] = v
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
end
end
end
-- vertical half sample h; avg 0: h, 1: (G + h + 1) >> 1, 2: (h + G below + 1) >> 1
local function lumaV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, avg: number)
for c = 0, w - 1 do
local o = base + c
local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s)
local d = c + 1
for r = 0, h - 1 do
local a5 = readu8(ref, o + (r + 3) * s)
local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
if avg == 1 then
v = (v + a2 + 1) // 2
elseif avg == 2 then
v = (v + a3 + 1) // 2
end
P[d + r * 16] = v
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
end
end
end
-- B1 rows -2 .. h + 2, columns 0 .. w (unrounded horizontal intermediates), stride 17
local function horizontal1(ref: buffer, s: number, base: number, w: number, h: number)
for r = -2, h + 2 do
local o = base + r * s
local d = (r + 2) * 17 + 1
local a0, a1, a2, a3, a4 = readu8(ref, o - 2), readu8(ref, o - 1), readu8(ref, o), readu8(ref, o + 1), readu8(ref, o + 2)
for c = 0, w do
local a5 = readu8(ref, o + c + 3)
B1[d + c] = a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
end
end
end
-- centre j; with = 0: j, 1: (b + j + 1) >> 1 (b of this row), 2: (s + j + 1) >> 1 (b of the next row)
local function lumaJ(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, with: number)
horizontal1(ref, s, base, w, h)
for c = 0, w - 1 do
local k = 2 * 17 + 1 + c
local a0, a1, a2, a3, a4 = B1[k - 34], B1[k - 17], B1[k], B1[k + 17], B1[k + 34]
for r = 0, h - 1 do
local a5 = B1[k + 51]
local v = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 512) // 1024, 0), 255)
if with == 1 then
v = (v + min(max((a2 + 16) // 32, 0), 255) + 1) // 2
elseif with == 2 then
v = (v + min(max((a3 + 16) // 32, 0), 255) + 1) // 2
end
P[r * 16 + c + 1] = v
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
k += 17
end
end
end
-- (j + h + 1) >> 1 with h at column c + co (co 0: i, 1: k)
local function lumaJV(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, co: number)
lumaJ(ref, s, base, w, h, P, 0)
for c = 0, w - 1 do
local o = base + c + co
local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s)
for r = 0, h - 1 do
local a5 = readu8(ref, o + (r + 3) * s)
local hv = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
local d = r * 16 + c + 1
P[d] = (P[d] + hv + 1) // 2
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
end
end
end
-- diagonal quarter samples e, g, p, r: (b or s) averaged with (h or m)
local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: number, P: { number }, ro: number, co: number)
lumaH(ref, s, base + ro, w, h, P, 0)
for c = 0, w - 1 do
local o = base + c + co
local a0, a1, a2, a3, a4 = readu8(ref, o - 2 * s), readu8(ref, o - s), readu8(ref, o), readu8(ref, o + s), readu8(ref, o + 2 * s)
for r = 0, h - 1 do
local a5 = readu8(ref, o + (r + 3) * s)
local vb = min(max((a0 - 5 * a1 + 20 * a2 + 20 * a3 - 5 * a4 + a5 + 16) // 32, 0), 255)
local d = r * 16 + c + 1
P[d] = (P[d] + vb + 1) // 2
a0, a1, a2, a3, a4 = a1, a2, a3, a4, a5
end
end
end
-- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at
-- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples
function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number })
if fy == 0 then
if fx == 0 then
lumaCopy(ref, s, base, w, h, P)
else
lumaH(ref, s, base, w, h, P, if fx == 2 then 0 elseif fx == 1 then 1 else 2)
end
elseif fx == 0 then
lumaV(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2)
elseif fx == 2 then
lumaJ(ref, s, base, w, h, P, if fy == 2 then 0 elseif fy == 1 then 1 else 2)
elseif fy == 2 then
lumaJV(ref, s, base, w, h, P, if fx == 3 then 1 else 0)
else
lumaDiag(ref, s, base, w, h, P, if fy == 3 then s else 0, if fx == 3 then 1 else 0)
end
end
-- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction
function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number })
if fx == 0 and fy == 0 then
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
+410
View File
@@ -0,0 +1,410 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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 min, max = math.min, math.max
local function clip(v: number): number
return min(max(v, 0), 255)
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
+930
View File
@@ -0,0 +1,930 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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/video/H264/Intra")
local Transform = require("@formats/codecs/video/H264/Transform")
local Inter = require("@formats/codecs/video/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 min, max = math.min, math.max
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 ((a < b) and (a) or (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
return max(min(a, b), min(max(a, b), c))
end
-- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference
-- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right
local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number)
local pic = S.pic
local refs = ((list == 0) and (pic.ref0) or (pic.ref1))
local mvs = ((list == 0) and (pic.mv0) or (pic.mv1))
local rA, ax, ay = neighbour(S, M, refs, mvs, x - 1, y)
local rB, bx, by = neighbour(S, M, refs, mvs, x, y - 1)
local rC, cx, cy = neighbour(S, M, refs, mvs, x + w, y - 1)
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 = ((r0 >= 0) and (S.uids0[r0 + 1] or -1) or (-1))
local u1 = ((r1 >= 0) and (S.uids1[r1 + 1] or -1) or (-1))
local w4 = S.w4
local done = M.done
for j = y, y + h - 1 do
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
return min(max(v, lo), hi)
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 = ((bx < 2) and (0) or (3))
by = ((by < 2) and (0) or (3))
end
if col.mbIntra[M.addr + 1] then
return -1, 0, 0, -1
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 ((a < b) and (a) or (b))
end
return ((a > b) and (a) or (b))
end
-- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M
local function spatialRefs(S: any, M: any)
local pic = S.pic
local r0, r1 = -1, -1
for l = 0, 1 do
local refs = ((l == 0) and (pic.ref0) or (pic.ref1))
local mvs = ((l == 0) and (pic.mv0) or (pic.mv1))
local rA = neighbour(S, M, refs, mvs, -1, 0)
local rB = neighbour(S, M, refs, mvs, 0, -1)
local rC = neighbour(S, M, refs, mvs, 4, -1)
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 = ((S.direct8x8) and (2) or (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 = ((part == 0) and (1) or (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 = ((r0 >= 0) and (refPic(list0, r0)) or (nil))
local ref1 = ((r1 >= 0) and (refPic(list1, r1)) or (nil))
if ref0 == nil and ref1 == nil then
ref0 = list0[1] or list1[1]
r0 = 0
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, ((plane == 1) and (ref0.u) or (ref0.v)), cx, cy, cw, ch, m0x, m0y)
end
end
if ref1 then
if plane == 0 then
predLuma(S, ref1, P1, px, py, lw, lh, m1x, m1y)
else
predChroma(S, ref1, P1, ((plane == 1) and (ref1.u) or (ref1.v)), cx, cy, cw, ch, m1x, m1y)
end
end
if wm == 2 and bi then
Inter.weight2(P0, P1, bw, bh, dst, o, s, 5, implicitW0, implicitW1, 0)
elseif explicit then
local logWD = ((plane == 0) and (S.lumaDenom) or (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[((intra) and (2) or (5))][M.qpc + 1][1], cc, 0)
Transform.chromaDc(M.dcC, 4, dq[((intra) and (3) or (6))][M.qpc2 + 1][1], cc, 64)
end
for plane = 0, 1 do
local b = ((plane == 0) and (pic.u) or (pic.v))
for blk = 0, 3 do
local base = (plane * 4 + blk) * 16
local q = o + (blk // 2) * 4 * s + (blk % 2) * 4
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
if bx < 3 then
tr = M.iT
else
tr = M.iTR
end
else
tr = not (bx == 3 or (bx == 1 and (by == 1 or by == 3)))
end
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] = ((kind == K_PCM) and (0) or (M.qp))
S.qpcTab[addr] = ((kind == K_PCM) and (S.qpcOf[1]) or (M.qpc))
S.qpc2Tab[addr] = ((kind == K_PCM) and (S.qpc2Of[1]) or (M.qpc2))
pic.mbIntra[addr] = kind <= K_PCM
local nzDb = S.nzDb
local g0 = M.g0
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 = ((nz[by * 4 + bx + 1] > 0) and (1) or (0))
local g = g0 + by * w4 + bx
nzDb[g], nzDb[g + 1], nzDb[g + w4], nzDb[g + w4 + 1] = v, v, v, v
end
else
for blk = 0, 15 do
nzDb[g0 + (blk // 4) * w4 + blk % 4] = ((nz[blk + 1] > 0) and (1) or (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
+453
View File
@@ -0,0 +1,453 @@
--!strict
--!native
-- codecs/video/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/video/H264/Bitstream")
local Tables = require("@formats/codecs/video/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
+251
View File
@@ -0,0 +1,251 @@
--!strict
--!native
-- codecs/video/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/video/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
+42
View File
@@ -0,0 +1,42 @@
--!strict
--!native
-- codecs/video/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, -Line truncated
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
@@ -0,0 +1,174 @@
--!strict
--!native
--!optimize 2
-- codecs/video/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 min, max = math.min, math.max
local function clip(v: number): number
return min(max(v, 0), 255)
end
-- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s)
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
+413
View File
@@ -0,0 +1,413 @@
--!strict
-- codecs/video/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/video/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
--
-- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135
-- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default
-- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and
-- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau).
-- 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/video/H264/Bitstream")
local Decoder = require("@formats/codecs/video/H264/Decoder")
local Params = require("@formats/codecs/video/H264/Params")
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:
-- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit.
function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?)
local b = toBuffer(data)
if not b then
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 self.lengthSize then
local all, partial = Bitstream.splitLength(b, o, l, self.lengthSize)
nals = all or partial
if not all then
st.errors += 1
st.lastError = "NAL length past the end of the sample"
end
elseif Bitstream.isAnnexB(b, o, l) then
nals = Bitstream.splitAnnexB(b, o, l)
else
nals = { o, l }
end
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
-- ------------------------------------------------------------------------------------------------ video layer
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"):
-- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264).
-- Pictures come out in display order with the packet timestamps sorted (display order); a track with
-- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead.
function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay }
local function make(): (H264Decoder?, Err.Err?)
local d, err = H264.newDecoder(o)
if d and track.config then
local ok, e = d:configure(track.config)
if not ok then
return nil, e
end
end
return d, err
end
local dec, err = make()
if not dec then
return nil, err
end
local queue: { any } = {}
local pool: { number } = {}
local outIndex: number? = if track.ptsInOutputOrder then 0 else nil
local self: any = {}
local function push(frames: { Frame })
for _, f in frames do
local pts = f.pts
if track.ptsInOutputOrder then
pts = outIndex or 0
outIndex = pts + 1
elseif #pool > 0 then
-- pictures leave in display order: they take the packet timestamps in increasing order (right for
-- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times)
pts = table.remove(pool, 1)
end
table.insert(queue, { f.image, pts, f.keyframe })
end
end
function self.decode(_: any, packet: Types.Packet): Err.Err?
if not dec then
return Err.new(Err.CORRUPT, "decoder not available")
end
if outIndex == nil and track.ptsInOutputOrder then
outIndex = packet.pts
end
if packet.pts ~= nil and not track.ptsInOutputOrder then
local i = #pool
while i > 0 and pool[i] > packet.pts do
i -= 1
end
table.insert(pool, i + 1, packet.pts)
end
local frames, e = (dec :: H264Decoder):decode(packet.data, packet.pts)
if not frames then
return e
end
push(frames)
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil
end
function self.flush(_: any)
if dec then
push((dec :: H264Decoder):flush())
end
end
function self.reset(_: any)
dec = make()
table.clear(queue)
table.clear(pool)
if track.ptsInOutputOrder then
outIndex = nil
end
end
return self, nil
end
-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units
-- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0
-- after a slice). keyframe: the unit holds an IDR slice.
function H264.accessUnits(data: any, off: number?, len: number?): { any }
local b = toBuffer(data)
local out = {}
if not b then
return out
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 nals = Bitstream.splitAnnexB(b, o, l)
local start, hasSlice, key = o, false, false
for i = 1, #nals, 2 do
local p, nl = nals[i], nals[i + 1]
local t = buffer.readu8(b, p) % 32
local isSlice = t == 1 or t == 5
local boundary = false
if hasSlice then
if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then
boundary = true
elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then
boundary = true
end
end
if boundary then
-- the unit ends where this NAL's start code begins
local s = p
while s > start and buffer.readu8(b, s - 1) ~= 1 do
s -= 1
end
s -= 1
while s > start and buffer.readu8(b, s - 1) == 0 do
s -= 1
end
table.insert(out, start)
table.insert(out, s - start)
table.insert(out, key)
start, hasSlice, key = s, false, false
end
if isSlice then
hasSlice = true
if t == 5 then
key = true
end
end
end
if hasSlice and o + l > start then
table.insert(out, start)
table.insert(out, o + l - start)
table.insert(out, key)
end
return out
end
-- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the
-- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample
function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
local parts = {}
local lengthSize = 4
if config then
local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config))
if not cfg then
return nil, Err.new(Err.CORRUPT, err or "bad avcC")
end
lengthSize = cfg.lengthSize
for i = 1, #cfg.nals, 2 do
table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1]))
end
end
local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize)
if not nals then
return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample")
end
for i = 1, #nals, 2 do
table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1]))
end
return buffer.fromstring(table.concat(parts)), nil
end
-- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil
function H264.info(data: any): any
local b = toBuffer(data)
if not b then
return nil
end
local nals
if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then
local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b))
nals = if cfg then cfg.nals else {}
else
nals = Bitstream.splitAnnexB(b, 0, buffer.len(b))
end
for i = 1, #nals, 2 do
if buffer.readu8(b, nals[i]) % 32 == 7 then
local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1))
if sps then
local fps = nil
if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then
fps = sps.timeScale / (2 * sps.unitsInTick)
end
return {
width = sps.width,
height = sps.height,
profile = sps.profile,
level = sps.level,
chromaFormat = sps.chromaFormat,
bitDepth = sps.bitDepth,
interlaced = not sps.frameMbsOnly,
frameRate = fps,
maxRefFrames = sps.maxRefFrames,
numReorderFrames = sps.numReorderFrames,
}
end
end
end
return 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
File diff suppressed because it is too large. Load diff
+117
View File
@@ -0,0 +1,117 @@
--!strict
-- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from
-- mpeg1-luau e2e2898). Lists are 0-based like the JS arrays.
local T = {}
T.PICTURE_RATE = { [0] = 0.0,
23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
}
T.ZIG_ZAG = { [0] = 0,
1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27,
20, 13, 6, 7, 14, 21, 28, 35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58,
59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
}
T.DEFAULT_INTRA_QUANT_MATRIX = { [0] = 8,
16, 19, 22, 26, 27, 29, 34, 16, 16, 22, 24, 27, 29, 34, 37, 19, 22, 26, 27, 29, 34, 34, 38, 22,
22, 26, 27, 29, 34, 37, 40, 22, 26, 27, 29, 32, 35, 40, 48, 26, 27, 29, 32, 35, 40, 48, 58, 26,
27, 29, 34, 38, 46, 56, 69, 27, 29, 35, 38, 46, 56, 69, 83,
}
T.DEFAULT_NON_INTRA_QUANT_MATRIX = { [0] = 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16,
}
T.MACROBLOCK_ADDRESS_INCREMENT = { [0] = 3,
6, 0, 9, 12, 0, 0, 0, 1, 15, 18, 0, 21, 24, 0, 27, 30, 0, 33, 36, 0, 0, 0, 3, 0,
0, 2, 39, 42, 0, 45, 48, 0, 0, 0, 5, 0, 0, 4, 51, 54, 0, 57, 60, 0, 0, 0, 7, 0,
0, 6, 63, 66, 0, 69, 72, 0, 75, 78, 0, 81, 84, 0, -1, 87, 0, -1, 90, 0, 93, 96, 0, 99,
102, 0, 105, 108, 0, 111, 114, 0, 0, 0, 9, 0, 0, 8, 117, 120, 0, 123, 126, 0, 129, 132, 0, 135,
138, 0, 0, 0, 15, 0, 0, 14, 0, 0, 13, 0, 0, 12, 0, 0, 11, 0, 0, 10, 141, -1, 0, -1,
144, 0, 147, 150, 0, 153, 156, 0, 159, 162, 0, 165, 168, 0, 171, 174, 0, 177, 180, 0, 183, -1, 0, -1,
186, 0, 189, 192, 0, 195, 198, 0, 201, 204, 0, 207, 210, 0, 213, 216, 0, 219, 222, 0, 0, 0, 21, 0,
0, 20, 0, 0, 19, 0, 0, 18, 0, 0, 17, 0, 0, 16, 0, 0, 35, 0, 0, 34, 0, 0, 33, 0,
0, 32, 0, 0, 31, 0, 0, 30, 0, 0, 29, 0, 0, 28, 0, 0, 27, 0, 0, 26, 0, 0, 25, 0,
0, 24, 0, 0, 23, 0, 0, 22,
}
T.MACROBLOCK_TYPE_INTRA = { [0] = 3,
6, 0, -1, 9, 0, 0, 0, 1, 0, 0, 17,
}
T.MACROBLOCK_TYPE_PREDICTIVE = { [0] = 3,
6, 0, 9, 12, 0, 0, 0, 10, 15, 18, 0, 0, 0, 2, 21, 24, 0, 0, 0, 8, 27, 30, 0, 33,
36, 0, -1, 39, 0, 0, 0, 18, 0, 0, 26, 0, 0, 1, 0, 0, 17,
}
T.MACROBLOCK_TYPE_B = { [0] = 3,
6, 0, 9, 15, 0, 12, 18, 0, 24, 21, 0, 0, 0, 12, 27, 30, 0, 0, 0, 14, 39, 42, 0, 36,
33, 0, 0, 0, 4, 0, 0, 6, 54, 48, 0, 45, 51, 0, 0, 0, 8, 0, 0, 10, -1, 57, 0, 0,
0, 1, 60, 63, 0, 0, 0, 30, 0, 0, 17, 0, 0, 22, 0, 0, 26,
}
T.CODE_BLOCK_PATTERN = { [0] = 6,
3, 0, 9, 18, 0, 12, 15, 0, 24, 33, 0, 36, 39, 0, 27, 21, 0, 30, 42, 0, 60, 57, 0, 54,
48, 0, 69, 51, 0, 81, 75, 0, 63, 84, 0, 45, 66, 0, 72, 78, 0, 0, 0, 60, 105, 120, 0, 132,
144, 0, 114, 108, 0, 126, 141, 0, 87, 93, 0, 117, 96, 0, 0, 0, 32, 135, 138, 0, 99, 123, 0, 129,
102, 0, 0, 0, 4, 90, 111, 0, 0, 0, 8, 0, 0, 16, 0, 0, 44, 150, 168, 0, 0, 0, 28, 0,
0, 52, 0, 0, 62, 183, 177, 0, 156, 180, 0, 0, 0, 1, 165, 162, 0, 0, 0, 61, 0, 0, 56, 171,
174, 0, 0, 0, 2, 0, 0, 40, 153, 186, 0, 0, 0, 48, 192, 189, 0, 147, 159, 0, 0, 0, 20, 0,
0, 12, 240, 249, 0, 0, 0, 63, 231, 225, 0, 195, 219, 0, 252, 198, 0, 0, 0, 24, 0, 0, 36, 0,
0, 3, 207, 261, 0, 243, 237, 0, 204, 213, 0, 210, 234, 0, 201, 228, 0, 216, 222, 0, 258, 255, 0, 264,
246, 0, -1, 282, 0, 285, 291, 0, 0, 0, 33, 0, 0, 9, 318, 330, 0, 306, 348, 0, 0, 0, 5, 0,
0, 10, 279, 267, 0, 0, 0, 6, 0, 0, 18, 0, 0, 17, 0, 0, 34, 339, 357, 0, 309, 312, 0, 270,
276, 0, 327, 321, 0, 351, 354, 0, 303, 297, 0, 294, 288, 0, 300, 273, 0, 342, 345, 0, 315, 324, 0, 336,
333, 0, 363, 375, 0, 0, 0, 41, 0, 0, 14, 0, 0, 21, 372, 366, 0, 360, 369, 0, 0, 0, 11, 0,
0, 19, 0, 0, 7, 0, 0, 35, 0, 0, 13, 0, 0, 50, 0, 0, 49, 0, 0, 58, 0, 0, 37, 0,
0, 25, 0, 0, 45, 0, 0, 57, 0, 0, 26, 0, 0, 29, 0, 0, 38, 0, 0, 53, 0, 0, 23, 0,
0, 43, 0, 0, 46, 0, 0, 42, 0, 0, 22, 0, 0, 54, 0, 0, 51, 0, 0, 15, 0, 0, 30, 0,
0, 39, 0, 0, 47, 0, 0, 55, 0, 0, 27, 0, 0, 59, 0, 0, 31,
}
T.MOTION = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 0, 18, 15, 0, 24, 21, 0, 0, 0, -1, 0, 0, 1, 27, 30, 0, 36,
33, 0, 0, 0, 2, 0, 0, -2, 42, 45, 0, 48, 39, 0, 60, 54, 0, 0, 0, 3, 0, 0, -3, 51,
57, 0, -1, 69, 0, 81, 75, 0, 78, 63, 0, 72, 66, 0, 96, 84, 0, 87, 93, 0, -1, 99, 0, 108,
105, 0, 0, 0, -4, 90, 102, 0, 0, 0, 4, 0, 0, -7, 0, 0, 5, 111, 123, 0, 0, 0, -5, 0,
0, 7, 114, 120, 0, 126, 117, 0, 0, 0, -6, 0, 0, 6, 153, 162, 0, 150, 147, 0, 135, 138, 0, 156,
141, 0, 129, 159, 0, 132, 144, 0, 0, 0, 10, 0, 0, 9, 0, 0, 8, 0, 0, -8, 171, 198, 0, 0,
0, -9, 180, 192, 0, 168, 183, 0, 165, 186, 0, 174, 189, 0, 0, 0, -10, 177, 195, 0, 0, 0, 12, 0,
0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0,
0, -15, 0, 0, -11, 0, 0, -13,
}
T.DCT_DC_SIZE_LUMINANCE = { [0] = 6,
3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36,
33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6,
3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0,
0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_COEFF = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0,
0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81,
75, 0, 87, 93, 0, 72, 78, 0, 96, 90, 0, 0, 0, 1025, 69, 84, 0, 0, 0, 769, 0, 0, 258, 0,
0, 1793, 0, 0, 65535, 0, 0, 1537, 111, 108, 0, 0, 0, 1281, 105, 102, 0, 117, 114, 0, 99, 126, 0, 120,
123, 0, 156, 150, 0, 162, 159, 0, 144, 147, 0, 129, 135, 0, 138, 132, 0, 0, 0, 2049, 0, 0, 4, 0,
0, 514, 0, 0, 2305, 153, 141, 0, 165, 171, 0, 180, 168, 0, 177, 174, 0, 183, 186, 0, 0, 0, 2561, 0,
0, 3329, 0, 0, 6, 0, 0, 259, 0, 0, 5, 0, 0, 770, 0, 0, 2817, 0, 0, 3073, 228, 225, 0, 201,
210, 0, 219, 213, 0, 234, 222, 0, 216, 231, 0, 207, 192, 0, 204, 189, 0, 198, 195, 0, 243, 261, 0, 273,
240, 0, 246, 237, 0, 249, 258, 0, 279, 276, 0, 252, 255, 0, 270, 282, 0, 264, 267, 0, 0, 0, 515, 0,
0, 260, 0, 0, 7, 0, 0, 1026, 0, 0, 1282, 0, 0, 4097, 0, 0, 3841, 0, 0, 3585, 315, 321, 0, 333,
342, 0, 312, 291, 0, 375, 357, 0, 288, 294, 0, -1, 369, 0, 285, 303, 0, 318, 363, 0, 297, 306, 0, 339,
309, 0, 336, 348, 0, 330, 300, 0, 372, 345, 0, 351, 366, 0, 327, 354, 0, 360, 324, 0, 381, 408, 0, 417,
420, 0, 390, 378, 0, 435, 438, 0, 384, 387, 0, 0, 0, 2050, 396, 402, 0, 465, 462, 0, 0, 0, 8, 411,
399, 0, 429, 432, 0, 453, 414, 0, 426, 423, 0, 0, 0, 10, 0, 0, 9, 0, 0, 11, 0, 0, 5377, 0,
0, 1538, 0, 0, 771, 0, 0, 5121, 0, 0, 1794, 0, 0, 4353, 0, 0, 4609, 0, 0, 4865, 444, 456, 0, 0,
0, 1027, 459, 450, 0, 0, 0, 261, 393, 405, 0, 0, 0, 516, 447, 441, 0, 516, 519, 0, 486, 474, 0, 510,
483, 0, 504, 498, 0, 471, 537, 0, 507, 501, 0, 522, 513, 0, 534, 531, 0, 468, 477, 0, 492, 495, 0, 549,
546, 0, 525, 528, 0, 0, 0, 263, 0, 0, 2562, 0, 0, 2306, 0, 0, 5633, 0, 0, 5889, 0, 0, 6401, 0,
0, 6145, 0, 0, 1283, 0, 0, 772, 0, 0, 13, 0, 0, 12, 0, 0, 14, 0, 0, 15, 0, 0, 517, 0,
0, 6657, 0, 0, 262, 540, 543, 0, 480, 489, 0, 588, 597, 0, 0, 0, 27, 609, 555, 0, 606, 603, 0, 0,
0, 19, 0, 0, 22, 591, 621, 0, 0, 0, 18, 573, 576, 0, 564, 570, 0, 0, 0, 20, 552, 582, 0, 0,
0, 21, 558, 579, 0, 0, 0, 23, 612, 594, 0, 0, 0, 25, 0, 0, 24, 600, 615, 0, 0, 0, 31, 0,
0, 30, 0, 0, 28, 0, 0, 29, 0, 0, 26, 0, 0, 17, 0, 0, 16, 567, 618, 0, 561, 585, 0, 654,
633, 0, 0, 0, 37, 645, 648, 0, 0, 0, 36, 630, 636, 0, 0, 0, 34, 639, 627, 0, 663, 666, 0, 657,
624, 0, 651, 642, 0, 669, 660, 0, 0, 0, 35, 0, 0, 267, 0, 0, 40, 0, 0, 268, 0, 0, 266, 0,
0, 32, 0, 0, 264, 0, 0, 265, 0, 0, 38, 0, 0, 269, 0, 0, 270, 0, 0, 33, 0, 0, 39, 0,
0, 7937, 0, 0, 6913, 0, 0, 7681, 0, 0, 4098, 0, 0, 7425, 0, 0, 7169, 0, 0, 271, 0, 0, 274, 0,
0, 273, 0, 0, 272, 0, 0, 1539, 0, 0, 2818, 0, 0, 3586, 0, 0, 3330, 0, 0, 3074, 0, 0, 3842,
}
return T
+116
View File
@@ -0,0 +1,116 @@
--!strict
-- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
--
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level
-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF,
-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the
-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but
-- for this header and the require.
local T = require("@formats/codecs/video/Mpeg1/Tables")
local V = {}
type Leaf = { code: number, len: number, value: number }
local function leaves(tree: { [number]: number }): { Leaf }
local out: { Leaf } = {}
local function walk(state: number, code: number, len: number)
if tree[state] == 0 and len > 0 then
table.insert(out, { code = code, len = len, value = tree[state + 2] })
return
end
for bit = 0, 1 do
local nxt = tree[state + bit]
if nxt ~= nil and nxt > 0 then
walk(nxt, code * 2 + bit, len + 1)
end
end
end
walk(0, 0, 0)
return out
end
local function flat(tree: { [number]: number }): (buffer, number)
local ls = leaves(tree)
local k = 0
for _, l in ls do
k = math.max(k, l.len)
end
local lut = buffer.create(4 * 2 ^ k)
for _, l in ls do
local shift = k - l.len
local first = l.code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value + 32768)
end
end
return lut, k
end
V.SUB = 0x1000000
V.ESC = 0xFFFF
V.EOB = 0xFFFE
-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits
local function twoLevel(ls: { Leaf }): buffer
local subs: { [number]: number } = {}
local nsub = 0
for _, l in ls do
if l.len > 8 then
local prefix = l.code // 2 ^ (l.len - 8)
if subs[prefix] == nil then
nsub += 1
subs[prefix] = nsub
end
end
end
local lut = buffer.create(4 * 256 * (1 + nsub))
for _, l in ls do
if l.len <= 8 then
local shift = 8 - l.len
local first = l.code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, l.len * 65536 + l.value)
end
else
local prefix = l.code // 2 ^ (l.len - 8)
local s = subs[prefix]
buffer.writeu32(lut, prefix * 4, V.SUB + s)
local rest = l.code % 2 ^ (l.len - 8)
local shift = 16 - l.len
local first = rest * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, (s * 256 + i) * 4, l.len * 65536 + l.value)
end
end
end
return lut
end
V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35 = escape
V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA)
V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE)
V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B)
V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN)
V.MOTION, V.MOTION_BITS = flat(T.MOTION)
V.DC_LUMA, V.DC_LUMA_BITS = flat(T.DCT_DC_SIZE_LUMINANCE)
V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE)
do
local ls = leaves(T.DCT_COEFF)
V.DCT_FIRST = twoLevel(ls)
local nextLs: { Leaf } = {}
for _, l in ls do
if l.len == 1 and l.code == 1 then
table.insert(nextLs, { code = 2, len = 2, value = V.EOB }) -- "10"
table.insert(nextLs, { code = 3, len = 2, value = 0x0001 }) -- "11"
else
table.insert(nextLs, l)
end
end
V.DCT_NEXT = twoLevel(nextLs)
end
return V
+262
View File
@@ -0,0 +1,262 @@
--!strict
-- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures,
-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage.
-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom
-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display
-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau).
-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding.
--
-- local dec = Mpeg1.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... }
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@formats/Types")
local D = require("@formats/codecs/video/Mpeg1/Decoder")
local Mpeg1 = {}
Mpeg1.PICTURE_I = 1
Mpeg1.PICTURE_P = 2
Mpeg1.PICTURE_B = 3
export type Frame = {
width: number,
height: number,
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based)
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
-- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth,
-- chroma stride codedWidth / 2
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
}
export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
-- display order for streams without B-frames.
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
_core: D.Core,
_reorder: boolean,
_rgba: boolean,
_held: D.Store?,
_pixels: buffer?,
_count: number,
width: number,
height: number,
frameRate: number,
bitRate: number,
stats: { pictures: number, errors: number, skipped: number },
},
Decoder
))
function Mpeg1.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local core = D.new(o.maxPixels)
return setmetatable({
_core = core,
_reorder = o.reorder == true,
_rgba = o.rgba ~= false,
_held = nil,
_pixels = nil,
_count = 0,
width = 0,
height = 0,
frameRate = 0,
bitRate = 0,
stats = { pictures = 0, errors = 0, skipped = 0 },
}, Decoder)
end
local function emit(self: Decoder, s: D.Store): Frame
local core = self._core
local pixels: buffer? = nil
if self._rgba then
local need = s.w * s.h * 4
local px = self._pixels
if px == nil or buffer.len(px) ~= need then
px = buffer.create(need)
self._pixels = px
end
core.toRgba(s, px :: buffer)
pixels = px
end
self._count += 1
return {
width = s.w,
height = s.h,
pixels = pixels,
pictureType = s.ptype,
temporalReference = s.tref,
index = self._count,
tag = s.tag,
y = s.y,
cb = s.cb,
cr = s.cr,
codedWidth = s.cw,
}
end
local function sync(self: Decoder)
local st = self._core.state
self.width = st.width
self.height = st.height
self.frameRate = st.frameRate
self.bitRate = st.bitRate
self.stats.pictures = st.pictures
self.stats.errors = st.errors
self.stats.skipped = st.skipped
end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s)
end
local prev = self._held
self._held = s
if prev then
return emit(self, prev)
end
return nil
end
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
local core = self._core
while true do
local s, needData = core.nextPicture(atEnd, tag)
sync(self)
if s then
local f = handle(self, s)
if f then
return f
end
elseif needData then
return nil
end
end
end
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
src = buffer.fromstring(data)
elseif type(data) == "buffer" then
src = data
else
return false
end
local total = buffer.len(src)
local off = math.floor(tonumber(offset) or 0)
if off < 0 or off > total then
return false
end
local n = math.floor(tonumber(len) or (total - off))
if n < 0 or off + n > total then
return false
end
self._core.write(src, off, n)
return true
end
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then
return nil
end
return run(self, true, tag)
end
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
-- for reordering. Call until it returns nil.
function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil)
if f then
return f
end
local held = self._held
if held then
self._held = nil
return emit(self, held)
end
return nil
end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8
-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame.
function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil
end
local w, h, cw = frame.width, frame.height, frame.codedWidth
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
return nil
end
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
for y = 0, h - 1 do
buffer.copy(px, y * w, frame.y, y * cw, w)
end
local o = w * h
for y = 0, oh - 1 do
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
end
end
img.meta.source = {
format = "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
range = if rgba then nil else "limited",
}
return img
end
return Mpeg1
+305
View File
@@ -0,0 +1,305 @@
--!strict
-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given:
-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either
-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM,
-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw
-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau.
--
-- local streams, err = Source.streams(value, opts, {
-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any)
-- audio = { copy = { opus = true, vorbis = true }, pcm = true },
-- })
-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config,
-- -- track, packets = { { pts, duration (seconds), keyframe, data } } }
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Yuv = require("@formats/codecs/image/Yuv")
local Source = {}
export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer }
export type Stream = {
kind: "video" | "audio",
codec: string,
copied: boolean,
width: number?,
height: number?,
frameRate: number?,
sampleRate: number?,
channels: number?,
bitsPerSample: number?,
config: buffer?,
track: Types.Track?,
packets: { OutPacket },
}
export type Want = {
video: { copy: { [string]: boolean }?, encode: string? }?,
audio: { copy: { [string]: boolean }?, pcm: boolean? }?,
}
local function allows(set: { [string]: boolean }?, codec: string): boolean
return set ~= nil and (set[codec] == true or set["*"] == true)
end
-- the packets of a source track, times in seconds
local function copyPackets(dmx: any, track: Types.Track): { OutPacket }
local out = {}
local scale = if track.timescale and track.timescale > 0 then track.timescale else 1
local n = dmx:count(track.id)
for k = 1, n do
local p = dmx:get(track.id, k)
if p then
table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data })
end
end
return out
end
local function trackStream(track: Types.Track, packets: { OutPacket }): Stream
return {
kind = track.kind :: any,
codec = track.codec,
copied = true,
width = track.width,
height = track.height,
frameRate = track.frameRate,
sampleRate = track.sampleRate,
channels = track.channels,
bitsPerSample = track.bitsPerSample,
config = track.config,
track = track,
packets = packets,
}
end
-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo":
-- yuv420p planes)
local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?)
local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil
if codec ~= "rawvideo" then
local Video = require("@formats/codecs/video/Video")
local e = Video.entry(codec)
encode = e and e.encode
if not encode then
return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder")
end
end
if type(v.reset) == "function" then
v:reset()
end
local packets: { OutPacket } = {}
local w, h = v.width, v.height
local maxFrames = opts.maxFrames or math.huge
while #packets < maxFrames do
local f, err = v:nextFrame()
if not f then
if err then
return nil, err
end
break
end
local img: Types.Image = f.image
if (w == 0 or h == 0) and #packets == 0 then
w, h = img.width, img.height
end
if img.width ~= w or img.height ~= h then
return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")")
end
local data: buffer?
if codec == "rawvideo" then
local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601")
if not y then
return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format)
end
data = y.pixels
else
local e2
data, e2 = (encode :: any)(img, opts)
if not data then
return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode")
end
end
table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer })
end
if #packets == 0 then
return nil, Err.new(Err.ARG, "no frames to write")
end
local fr = v.frameRate
if not fr or fr <= 0 then
local d = packets[1].duration
fr = if d > 0 then 1 / d else 25
end
return {
kind = "video",
codec = codec,
copied = false,
width = w,
height = h,
frameRate = fr,
packets = packets,
} :: Stream, nil
end
-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096)
local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
local ch, rate = dec.channels, dec.sampleRate
if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then
return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate")
end
pcall(dec.seek, dec, 0)
local chunk = opts.audioChunk or 4096
local packets: { OutPacket } = {}
local pos = 0
local tmp: buffer? = nil
while true do
local ok, out, n = pcall(dec.read, dec, chunk, tmp)
if not ok or not out or not n or n <= 0 then
break
end
tmp = out
local data = buffer.create(n * ch * 2)
for i = 0, n * ch - 1 do
local s = buffer.readf32(out, i * 4)
local v = math.floor(s * 32768 + 0.5)
if v > 32767 then
v = 32767
elseif v < -32768 then
v = -32768
elseif v ~= v then
v = 0
end
buffer.writei16(data, i * 2, v)
end
table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data })
pos += n
end
return {
kind = "audio",
codec = "pcm_s16le",
copied = false,
sampleRate = rate,
channels = ch,
bitsPerSample = 16,
packets = packets,
} :: Stream, nil
end
-- streams(value, opts, want) -> { Stream } | nil, Err
function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then
return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer")
end
local dmx = if value.kind == "demuxer" then value else value.demuxer
local out: { Stream } = {}
-- video
local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video"))
local wv = want.video
if wv and o.video ~= false then
if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then
table.insert(out, trackStream(vt, copyPackets(dmx, vt)))
elseif value.kind == "video" and wv.encode then
local s, err = encodeFrames(value, wv.encode, o)
if not s then
return nil, err
end
table.insert(out, s)
elseif vt then
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)"))
end
end
-- audio
local wa = want.audio
if wa and o.audio ~= false then
local at: Types.Track? = dmx and dmx:track("audio")
if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then
table.insert(out, trackStream(at, copyPackets(dmx, at)))
elseif wa.pcm and value.kind == "video" and value.audio then
local s, err = pcmFrom(value.audio, o)
if not s then
return nil, err
end
if #s.packets > 0 then
table.insert(out, s)
end
elseif at and o.audio == true then
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container")
end
end
if #out == 0 then
return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)")
end
return out, nil
end
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
function Source.rational(fps: number): (number, number)
if fps ~= fps or fps <= 0 then
return 25, 1
end
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
return math.floor(fps + 0.5), 1
end
local ntsc = fps * 1001 / 1000
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
return math.floor(ntsc + 0.5) * 1000, 1001
end
return math.floor(fps * 1000 + 0.5), 1000
end
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
local fd = math.huge
for _, p in s.packets do
if p.duration and p.duration > 0 and p.duration < fd then
fd = p.duration
end
end
if fd == math.huge then
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
end
fd = math.max(fd, 1 / (maxFps or 100))
local num, den = Source.rational(1 / fd)
local step = den / num
local out: { OutPacket } = {}
local slots = 0
local t0 = if s.packets[1] then s.packets[1].pts else 0
for _, p in s.packets do
local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step)
local n = math.max(1, math.floor(stop / step + 0.5) - slots)
for _ = 1, n do
table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data })
slots += 1
end
end
return num, den, out
end
-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its
-- own order
function Source.interleave(streams: { Stream }): { { any } }
local order = {}
local pos = table.create(#streams, 1)
while true do
local best, bt = 0, math.huge
for si, s in streams do
local p = s.packets[pos[si]]
if p then
local t = p.dts or p.pts
if best == 0 or t < bt then
best, bt = si, t
end
end
end
if best == 0 then
break
end
table.insert(order, { best, streams[best].packets[pos[best]] })
pos[best] += 1
end
return order
end
return Source
+584
View File
@@ -0,0 +1,584 @@
--!strict
-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
--
-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them
-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a
-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc /
-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs
-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry).
--
-- local Video = require("@formats/codecs/video/Video")
-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8"
-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder)
-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open())
-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP)
--
-- Never throws: bad data / missing codecs come back as nil, Err.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Yuv = require("@formats/codecs/image/Yuv")
local Video = {}
export type Entry = {
id: string, -- our codec id
name: string, -- a human name
fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs
matroska: { string }?, -- Matroska / WebM CodecIDs
-- new(track, opts) -> a decoder instance (nil = decode not supported)
new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?,
[string]: any,
}
-- ------------------------------------------------------------------------------------------------ simple decoders
-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no
-- picture to show, such as a hidden VP8 altref frame)
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
local queue: { any } = {}
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, img, err = pcall(decodeOne, packet.data, packet)
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img))
end
if img then
table.insert(queue, { img, packet.pts, packet.keyframe })
end
return err
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil, nil, nil
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(queue)
if resetFn then
resetFn()
end
end
return self :: any
end
-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged
-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 /
-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows)
local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image
local img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
local cw, ch = (w + 1) // 2, (h + 1) // 2
local bps = if bits > 8 then 2 else 1
local shift = 2 ^ (bits - 8)
local function sample(o: number): number
if bps == 1 then
return buffer.readu8(data, o)
end
return math.min(255, buffer.readu16(data, o) // shift)
end
for i = 0, w * h - 1 do
buffer.writeu8(px, i, sample(i * bps))
end
local scw, sch = w, h -- source chroma plane size
if pf == "yuv420p" then
scw, sch = cw, ch
elseif pf == "yuv422p" then
scw, sch = cw, h
end
local uo, vo = w * h * bps, (w * h + scw * sch) * bps
for cy = 0, ch - 1 do
for cx = 0, cw - 1 do
local i = cy * cw + cx
local u, v
if pf == "gray" then
u, v = 128, 128
elseif pf == "yuv420p" then
u, v = sample(uo + i * bps), sample(vo + i * bps) :: number
elseif pf == "yuv422p" then
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2
v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2
else
local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1)
local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1)
local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps
u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4
v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4
end
buffer.writeu8(px, w * h + i, u)
buffer.writeu8(px, w * h + cw * ch + i, v)
end
end
return img
end
local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = {
yuv420p = function(w, h, cw, ch)
return w * h + 2 * cw * ch
end,
yv12 = function(w, h, cw, ch)
return w * h + 2 * cw * ch
end,
yuv422p = function(w, h, cw, _ch)
return w * h + 2 * cw * h
end,
yuv444p = function(w, h)
return w * h * 3
end,
yuva444p = function(w, h)
return w * h * 4
end,
gray = function(w, h)
return w * h
end,
}
local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local w, h = track.width or 0, track.height or 0
if w <= 0 or h <= 0 or w * h > 2 ^ 26 then
return nil, Err.new(Err.CORRUPT, "raw video without a valid size")
end
local pf = track.pixelFormat or "yuv420p"
local bits = track.bitDepth or 8
local cw, ch = (w + 1) // 2, (h + 1) // 2
local flip = track.flip == true
local planar = PLANAR_SIZE[pf]
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local n = buffer.len(data)
if planar then
local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1)
if n < need then
return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes")
end
if pf == "yuv420p" and bits == 8 then
local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, need)
return img, nil
elseif pf == "yv12" then
local img = Types.Image.new(w, h, "yuv420p")
buffer.copy(img.pixels, 0, data, 0, w * h)
buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch)
buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch)
return img, nil
end
return rawPlanar(data, pf, bits, w, h), nil
end
local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3
local stride: number = track.stride or w * bpp
if n < stride * (h - 1) + w * bpp then
return nil, Err.new(Err.TRUNCATED, "raw frame too short")
end
local img = Types.Image.new(w, h, "rgba8")
local px = img.pixels
local bgr = pf == "bgr24" or pf == "bgra"
for y = 0, h - 1 do
local s = (if flip then h - 1 - y else y) * stride
local o = y * w * 4
for x = 0, w - 1 do
local p = s + x * bpp
local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2)
if bgr then
a, c = c, a
end
buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000)
end
end
return img, nil
end), nil
end
local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Vp8 = require("@formats/codecs/image/Vp8")
local dec = Vp8.newDecoder()
local o = { maxPixels = opts and opts.maxPixels }
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local img, err = dec:decodeFrame(data, 0, buffer.len(data), o)
if not img then
return nil, err
end
local src = img.meta.source
if type(src) == "table" and src.show == false then
return nil, nil
end
img.meta.yuv = { range = "limited", matrix = "bt601" }
return img, nil
end, function()
if dec.reset then
dec:reset()
else
dec = Vp8.newDecoder()
end
end), nil
end
-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout
-- allows, else rgba8
local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Jpeg = require("@formats/codecs/image/Jpeg")
local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels }
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
local img, err = Jpeg.decode(data, 0, buffer.len(data), o)
if img and img.format == "yuv420p" then
img.meta.yuv = { range = "full", matrix = "bt601" }
end
return img, err
end), nil
end
-- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first
local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
local Jpeg = require("@formats/codecs/image/Jpeg")
local src = img
if img.format == "yuv420p" then
local range = Yuv.info(img)
if range ~= "full" then
src = Yuv.toFullRange(img)
end
end
return Jpeg.encode(src, { quality = opts and opts.quality or 90 })
end
-- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture)
local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
local function push(f: any)
local img = Mpeg1.frameImage(f)
if img then
img.meta.yuv = { range = "limited", matrix = "bt601" }
local tag = f.tag
table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 })
end
end
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts })
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
if f then
push(f)
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil, nil, nil
end
function self.flush(_: any)
for _ = 1, 4 do
local f = dec:flush()
if not f then
break
end
push(f)
end
end
function self.reset(_: any)
dec:reset()
table.clear(queue)
end
return self :: any, nil
end
-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264);
-- pictures in display order with the pts of their packet
local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local H264 = require("@formats/codecs/video/H264")
return H264.newVideoDecoder(track, opts)
end
-- ------------------------------------------------------------------------------------------------ registry
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
local BUILTIN: { Entry } = {
{ id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder },
{ id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode },
{ id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder },
{ id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder },
{ id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } },
{ id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } },
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder },
{ id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } },
{ id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } },
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" } },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
}
local byId: { [string]: Entry } = {}
local byFourcc: { [string]: string } = {}
local byMatroska: { [string]: string } = {}
-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it
function Video.register(entry: Entry): (boolean, Err.Err?)
if type(entry) ~= "table" or type(entry.id) ~= "string" then
return false, Err.new(Err.ARG, "register: needs an entry with an id")
end
local old = byId[entry.id]
if old and entry.new == nil then
entry.new = old.new
end
byId[entry.id] = entry
for _, f in entry.fourcc or {} do
byFourcc[f] = entry.id
end
for _, m in entry.matroska or {} do
byMatroska[m] = entry.id
end
return true, nil
end
for _, e in BUILTIN do
Video.register(e)
end
-- the registry (read only by convention): id -> Entry
Video.codecs = byId
-- fromFourcc(fourcc) -> codec id | nil
function Video.fromFourcc(fcc: string): string?
return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)]
end
-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...)
function Video.fromMatroska(id: string): string?
return byMatroska[id]
end
-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil
function Video.entry(id: string): Entry?
return byId[id]
end
-- canDecode(codecId) -> boolean
function Video.canDecode(id: string): boolean
local e = byId[id]
return e ~= nil and e.new ~= nil
end
-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered)
function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local e = byId[track.codec]
if not e or not e.new then
return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec))
end
local ok, dec, err = pcall(e.new :: any, track, opts)
if not ok then
return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec))
end
return dec, err
end
-- ------------------------------------------------------------------------------------------------ VideoDecoder
local function toRGBA(_self: any, f: any): Types.Image
local img = if type(f) == "table" and f.image then f.image else f
local out = Yuv.imageToRgba(img)
return out or img
end
export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p)
track: number?, -- the video track id (default: the first video track)
maxPixels: number?,
openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook
audio: boolean?, -- false: do not open the audio track
[string]: any,
}
-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through
-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and
-- the demuxer (remuxing) and audio work.
function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local o: OpenOptions = opts or {}
local track: Types.Track? = nil
if o.track then
for _, t in demuxer.tracks do
if t.id == o.track then
track = t
end
end
if not track then
return nil, Err.new(Err.ARG, "no track " .. tostring(o.track))
end
else
track = demuxer:track("video")
end
local codec: Types.VideoCodecDecoder? = nil
local codecErr: Err.Err? = nil
if track then
codec, codecErr = Video.decoder(track, o)
else
codecErr = Err.new(Err.UNSUPPORTED, "no video track")
end
local v: any = {
kind = "video",
format = demuxer.format,
codec = if track then track.codec else "none",
width = if track then track.width or 0 else 0,
height = if track then track.height or 0 else 0,
frameRate = if track then track.frameRate or 0 else 0,
frames = if track then track.frames or 0 else 0,
duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration,
track = track,
demuxer = demuxer,
meta = demuxer.meta or {},
decodeError = codecErr,
toRGBA = toRGBA,
}
if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then
v.frames = math.floor(v.duration * v.frameRate + 0.5)
end
-- audio
if o.audio ~= false then
local at = demuxer:track("audio")
if at then
if o.openAudio then
local ok, dec, err = pcall(o.openAudio, demuxer, at)
if ok and dec then
v.audio = dec
else
v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec))
end
else
v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)")
end
end
end
local index, flushed, skipUntil = 0, false, -math.huge
local tid = if track then track.id else -1
local scale: number = if track and track.timescale and track.timescale > 0 then track.timescale else 1000
local start = demuxer.startTime or 0
v.startTime = start
local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0
local lastPts = nil :: number?
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
if not codec then
return nil, codecErr
end
local dec = codec :: Types.VideoCodecDecoder
while true do
local img, pts, key = dec:receive()
if img then
local t = (pts or 0) / scale - start
if t + 1e-9 >= skipUntil then
index += 1
local d = defaultDur
if lastPts and t > (lastPts :: number) and defaultDur == 0 then
d = t - (lastPts :: number)
end
lastPts = t
if o.rgba then
img = Yuv.imageToRgba(img) or img
end
return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil
end
else
local p = demuxer:read(tid)
if p == nil then
if flushed then
return nil, nil
end
flushed = true
dec:flush()
else
local err = dec:decode(p)
if err then
return nil, err
end
end
end
end
end
function v.seek(self: any, seconds: number)
demuxer:seek(seconds + start)
if codec then
codec:reset()
end
flushed = false
skipUntil = seconds
lastPts = nil
if self.audio then
pcall(self.audio.seek, self.audio, seconds)
end
end
function v.reset(self: any)
self:seek(0)
skipUntil = -math.huge
index = 0
end
return v, nil
end
-- ------------------------------------------------------------------------------------------------ frames-backed
-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after
-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded.
function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?)
if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then
return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images")
end
local w, h = images[1].width, images[1].height
local pts: { number } = {}
local durs: { number } = {}
local t = 0
for i, img in images do
if type(img) ~= "table" or img.width ~= w or img.height ~= h then
return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image")
end
local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1)
if type(d) ~= "number" or d ~= d or d < 0 then
d = 0.1
end
pts[i] = t
durs[i] = d
t += d
end
local n = #images
local o = opts or {}
local v: any = {
kind = "video",
format = o.format or "frames",
codec = "frames",
width = w,
height = h,
frameRate = if t > 0 then n / t else 10,
frames = n,
duration = t,
loops = o.loops,
meta = o.meta or {},
toRGBA = toRGBA,
images = images,
}
local i = 0
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
i += 1
if i > n then
i = n
return nil, nil
end
local img = images[i]
if o.rgba then
img = Yuv.imageToRgba(img) or img
end
return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil
end
function v.seek(self: any, seconds: number)
local k = 0
for j = 1, n do
if pts[j] <= seconds + 1e-9 then
k = j - 1
end
end
i = k
end
function v.reset(self: any)
i = 0
end
return v, nil
end
return Video