rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings

This commit is contained in:
4DBug committed 2026-11-01 01:19:16 -05:00
1 parent 2956576d7f
commit 22ddcd78fa
941 files changed
+3364 -3364

No files matched your search

+743
View File
@@ -0,0 +1,743 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
-- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added
-- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never
-- throws (the caller keeps offsets in range).
--
-- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg
-- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then
-- columns, with every sparse-input special case of the original kept, because several of them use merged constants
-- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that
-- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order
-- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for
-- coefficients in the MPEG range), and the put / add clamping fused into the last pass.
--
-- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it
-- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3)
-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block
-- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+)
-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE)
local Dsp = {}
local readu8 = buffer.readu8
local writeu8 = buffer.writeu8
local readu32 = buffer.readu32
local writeu32 = buffer.writeu32
local readi32 = buffer.readi32
local writei32 = buffer.writei32
local band = bit32.band
local bor = bit32.bor
local bxor = bit32.bxor
local rshift = bit32.rshift
-- clamp to 0..255 by lookup: CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the IDCT output of MPEG-range
-- coefficients is bounded by 64 * 2048 / 8 * sqrt(2)^2 < COFF, plus a prediction of up to 255
local COFF = 40000
local CLAMP = buffer.create(2 * COFF + 256)
for i = 0, 2 * COFF + 255 do
buffer.writeu8(CLAMP, i, math.clamp(i - COFF, 0, 255))
end
Dsp.CLAMP = CLAMP
Dsp.COFF = COFF
-- ------------------------------------------------------------------------------------------------ IDCT
function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean)
local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0
local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0
local z1, z2, z3, z4, z5 = 0, 0, 0, 0, 0
-- pass 1: rows, scaled up by 2^PASS1_BITS
for r = 0, 224, 32 do
local d0 = readi32(blk, r)
local d1 = readi32(blk, r + 4)
local d2 = readi32(blk, r + 8)
local d3 = readi32(blk, r + 12)
local d4 = readi32(blk, r + 16)
local d5 = readi32(blk, r + 20)
local d6 = readi32(blk, r + 24)
local d7 = readi32(blk, r + 28)
if d1 == 0 and d2 == 0 and d3 == 0 and d4 == 0 and d5 == 0 and d6 == 0 and d7 == 0 then
if d0 ~= 0 then
local v = d0 * 4
writei32(blk, r, v)
writei32(blk, r + 4, v)
writei32(blk, r + 8, v)
writei32(blk, r + 12, v)
writei32(blk, r + 16, v)
writei32(blk, r + 20, v)
writei32(blk, r + 24, v)
writei32(blk, r + 28, v)
end
else
if d6 ~= 0 then
if d2 ~= 0 then
z1 = (d2 + d6) * 4433
tmp2 = z1 + (-d6) * 15137
tmp3 = z1 + (d2) * 6270
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp2 = (-d6) * 10703
tmp3 = (d6) * 4433
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
end
else
if d2 ~= 0 then
tmp2 = (d2) * 4433
tmp3 = (d2) * 10703
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp13 = (d0 + d4) * 8192
tmp10 = tmp13
tmp12 = (d0 - d4) * 8192
tmp11 = tmp12
end
end
if d7 ~= 0 then
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z2 = d5 + d3
z3 = d7 + d3
z4 = d5 + d1
z5 = (z3 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z3 = d7 + d3
z5 = (z3 + d5) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
z1 = (-d7) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-d5) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 = z1 + z4
end
else
if d1 ~= 0 then
z1 = d7 + d1
z4 = d5 + d1
z5 = (d7 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d5) * 20995
z3 = (-d7) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 = z2 + z3
tmp3 += z1 + z4
else
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
z3 = (-d7) * 16069
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (-d5) * 3196
z5 = (d5 + d7) * 9633
z3 += z5
z4 += z5
tmp0 += z3
tmp1 += z4
tmp2 = z2 + z3
tmp3 = z1 + z4
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z3 = d7 + d3
z5 = (z3 + d1) * 9633
tmp0 = (d7) * 2446
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d3) * 20995
z3 = (-z3) * 16069
z4 = (-d1) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 = z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z3 = d7 + d3
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
tmp2 = (d3) * 4176
z2 = (-d3) * 20995
z5 = (z3) * 9633
z3 = (-z3) * 6436
tmp0 += z3
tmp1 = z2 + z5
tmp2 += z3
tmp3 = z1 + z5
end
else
if d1 ~= 0 then
z1 = d7 + d1
z5 = (z1) * 9633
z1 = (z1) * 2260
z3 = (-d7) * 16069
tmp0 = (-d7) * 13623
z4 = (-d1) * 3196
tmp3 = (d1) * 9102
tmp0 += z1
tmp1 = z4 + z5
tmp2 = z3 + z5
tmp3 += z1
else
tmp0 = (-d7) * 11363
tmp1 = (d7) * 9633
tmp2 = (-d7) * 6436
tmp3 = (d7) * 2260
end
end
end
else
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z2 = d5 + d3
z4 = d5 + d1
z5 = (d3 + z4) * 9633
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-d1) * 7373
z2 = (-z2) * 20995
z3 = (-d3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 = z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z5 = (z2) * 9633
tmp1 = (d5) * 13623
z4 = (-d5) * 3196
z2 = (-z2) * 11363
tmp2 = (d3) * 9102
z3 = (-d3) * 16069
tmp0 = z3 + z5
tmp1 += z2
tmp2 += z2
tmp3 = z4 + z5
end
else
if d1 ~= 0 then
z4 = d5 + d1
z5 = (z4) * 9633
z1 = (-d1) * 7373
tmp3 = (d1) * 4926
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (z4) * 6436
tmp0 = z1 + z5
tmp1 += z4
tmp2 = z2 + z5
tmp3 += z4
else
tmp0 = (d5) * 9633
tmp1 = (d5) * 2260
tmp2 = (-d5) * 11363
tmp3 = (d5) * 6436
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z5 = d1 + d3
tmp3 = (d1) * 1730
tmp2 = (-d3) * 11893
z1 = (d1) * 8697
z2 = (-d3) * 17799
z4 = (z5) * 6436
z5 = (z5) * 9633
tmp0 = z1 - z4
tmp1 = z2 + z4
tmp2 += z5
tmp3 += z5
else
tmp0 = (-d3) * 6436
tmp1 = (-d3) * 11363
tmp2 = (-d3) * 2260
tmp3 = (d3) * 9633
end
else
if d1 ~= 0 then
tmp0 = (d1) * 2260
tmp1 = (d1) * 6436
tmp2 = (d1) * 9633
tmp3 = (d1) * 11363
else
tmp3 = 0
tmp0 = tmp3
tmp1 = tmp3
tmp2 = tmp3
end
end
end
end
writei32(blk, r, (tmp10 + tmp3 + 1024) // 2048)
writei32(blk, r + 28, (tmp10 - tmp3 + 1024) // 2048)
writei32(blk, r + 4, (tmp11 + tmp2 + 1024) // 2048)
writei32(blk, r + 24, (tmp11 - tmp2 + 1024) // 2048)
writei32(blk, r + 8, (tmp12 + tmp1 + 1024) // 2048)
writei32(blk, r + 20, (tmp12 - tmp1 + 1024) // 2048)
writei32(blk, r + 12, (tmp13 + tmp0 + 1024) // 2048)
writei32(blk, r + 16, (tmp13 - tmp0 + 1024) // 2048)
end
end
-- pass 2: columns, descaled by 2^(CONST_BITS + PASS1_BITS + 3)
for c = 0, 28, 4 do
local d0 = readi32(blk, c)
local d1 = readi32(blk, c + 32)
local d2 = readi32(blk, c + 64)
local d3 = readi32(blk, c + 96)
local d4 = readi32(blk, c + 128)
local d5 = readi32(blk, c + 160)
local d6 = readi32(blk, c + 192)
local d7 = readi32(blk, c + 224)
if d6 ~= 0 then
if d2 ~= 0 then
z1 = (d2 + d6) * 4433
tmp2 = z1 + (-d6) * 15137
tmp3 = z1 + (d2) * 6270
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp2 = (-d6) * 10703
tmp3 = (d6) * 4433
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
end
else
if d2 ~= 0 then
tmp2 = (d2) * 4433
tmp3 = (d2) * 10703
tmp0 = (d0 + d4) * 8192
tmp1 = (d0 - d4) * 8192
tmp10 = tmp0 + tmp3
tmp13 = tmp0 - tmp3
tmp11 = tmp1 + tmp2
tmp12 = tmp1 - tmp2
else
tmp13 = (d0 + d4) * 8192
tmp10 = tmp13
tmp12 = (d0 - d4) * 8192
tmp11 = tmp12
end
end
if d7 ~= 0 then
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z2 = d5 + d3
z3 = d7 + d3
z4 = d5 + d1
z5 = (z3 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z3 = d7 + d3
z5 = (z3 + d5) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
z1 = (-d7) * 7373
z2 = (-z2) * 20995
z3 = (-z3) * 16069
z4 = (-d5) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 = z1 + z4
end
else
if d1 ~= 0 then
z1 = d7 + d1
z3 = d7
z4 = d5 + d1
z5 = (z3 + z4) * 9633
tmp0 = (d7) * 2446
tmp1 = (d5) * 16819
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d5) * 20995
z3 = (-d7) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 += z2 + z4
tmp2 = z2 + z3
tmp3 += z1 + z4
else
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
z3 = (-d7) * 16069
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (-d5) * 3196
z5 = (d5 + d7) * 9633
z3 += z5
z4 += z5
tmp0 += z3
tmp1 += z4
tmp2 = z2 + z3
tmp3 = z1 + z4
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z1 = d7 + d1
z3 = d7 + d3
z5 = (z3 + d1) * 9633
tmp0 = (d7) * 2446
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-z1) * 7373
z2 = (-d3) * 20995
z3 = (-z3) * 16069
z4 = (-d1) * 3196
z3 += z5
z4 += z5
tmp0 += z1 + z3
tmp1 = z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z3 = d7 + d3
tmp0 = (-d7) * 4926
z1 = (-d7) * 7373
tmp2 = (d3) * 4176
z2 = (-d3) * 20995
z5 = (z3) * 9633
z3 = (-z3) * 6436
tmp0 += z3
tmp1 = z2 + z5
tmp2 += z3
tmp3 = z1 + z5
end
else
if d1 ~= 0 then
z1 = d7 + d1
z5 = (z1) * 9633
z1 = (z1) * 2260
z3 = (-d7) * 16069
tmp0 = (-d7) * 13623
z4 = (-d1) * 3196
tmp3 = (d1) * 9102
tmp0 += z1
tmp1 = z4 + z5
tmp2 = z3 + z5
tmp3 += z1
else
tmp0 = (-d7) * 11363
tmp1 = (d7) * 9633
tmp2 = (-d7) * 6436
tmp3 = (d7) * 2260
end
end
end
else
if d5 ~= 0 then
if d3 ~= 0 then
if d1 ~= 0 then
z2 = d5 + d3
z4 = d5 + d1
z5 = (d3 + z4) * 9633
tmp1 = (d5) * 16819
tmp2 = (d3) * 25172
tmp3 = (d1) * 12299
z1 = (-d1) * 7373
z2 = (-z2) * 20995
z3 = (-d3) * 16069
z4 = (-z4) * 3196
z3 += z5
z4 += z5
tmp0 = z1 + z3
tmp1 += z2 + z4
tmp2 += z2 + z3
tmp3 += z1 + z4
else
z2 = d5 + d3
z5 = (z2) * 9633
tmp1 = (d5) * 13623
z4 = (-d5) * 3196
z2 = (-z2) * 11363
tmp2 = (d3) * 9102
z3 = (-d3) * 16069
tmp0 = z3 + z5
tmp1 += z2
tmp2 += z2
tmp3 = z4 + z5
end
else
if d1 ~= 0 then
z4 = d5 + d1
z5 = (z4) * 9633
z1 = (-d1) * 7373
tmp3 = (d1) * 4926
tmp1 = (-d5) * 4176
z2 = (-d5) * 20995
z4 = (z4) * 6436
tmp0 = z1 + z5
tmp1 += z4
tmp2 = z2 + z5
tmp3 += z4
else
tmp0 = (d5) * 9633
tmp1 = (d5) * 2260
tmp2 = (-d5) * 11363
tmp3 = (d5) * 6436
end
end
else
if d3 ~= 0 then
if d1 ~= 0 then
z5 = d1 + d3
tmp3 = (d1) * 1730
tmp2 = (-d3) * 11893
z1 = (d1) * 8697
z2 = (-d3) * 17799
z4 = (z5) * 6436
z5 = (z5) * 9633
tmp0 = z1 - z4
tmp1 = z2 + z4
tmp2 += z5
tmp3 += z5
else
tmp0 = (-d3) * 6436
tmp1 = (-d3) * 11363
tmp2 = (-d3) * 2260
tmp3 = (d3) * 9633
end
else
if d1 ~= 0 then
tmp0 = (d1) * 2260
tmp1 = (d1) * 6436
tmp2 = (d1) * 9633
tmp3 = (d1) * 11363
else
tmp3 = 0
tmp0 = tmp3
tmp1 = tmp3
tmp2 = tmp3
end
end
end
end
writei32(blk, c, (tmp10 + tmp3 + 131072) // 262144)
writei32(blk, c + 224, (tmp10 - tmp3 + 131072) // 262144)
writei32(blk, c + 32, (tmp11 + tmp2 + 131072) // 262144)
writei32(blk, c + 192, (tmp11 - tmp2 + 131072) // 262144)
writei32(blk, c + 64, (tmp12 + tmp1 + 131072) // 262144)
writei32(blk, c + 160, (tmp12 - tmp1 + 131072) // 262144)
writei32(blk, c + 96, (tmp13 + tmp0 + 131072) // 262144)
writei32(blk, c + 128, (tmp13 - tmp0 + 131072) // 262144)
end
-- put / add, clamped
for r = 0, 224, 32 do
local p0 = readi32(blk, r) + COFF
local p1 = readi32(blk, r + 4) + COFF
local p2 = readi32(blk, r + 8) + COFF
local p3 = readi32(blk, r + 12) + COFF
local p4 = readi32(blk, r + 16) + COFF
local p5 = readi32(blk, r + 20) + COFF
local p6 = readi32(blk, r + 24) + COFF
local p7 = readi32(blk, r + 28) + COFF
if add then
p0 += readu8(dst, off)
p1 += readu8(dst, off + 1)
p2 += readu8(dst, off + 2)
p3 += readu8(dst, off + 3)
p4 += readu8(dst, off + 4)
p5 += readu8(dst, off + 5)
p6 += readu8(dst, off + 6)
p7 += readu8(dst, off + 7)
end
writeu32(dst, off, readu8(CLAMP, p0) + readu8(CLAMP, p1) * 256 + readu8(CLAMP, p2) * 65536 + readu8(CLAMP, p3) * 16777216)
writeu32(dst, off + 4, readu8(CLAMP, p4) + readu8(CLAMP, p5) * 256 + readu8(CLAMP, p6) * 65536 + readu8(CLAMP, p7) * 16777216)
off += stride
end
end
-- ------------------------------------------------------------------------------------------------ blocks
-- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT
-- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere)
function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean)
if not add then
local c = readu8(CLAMP, v + COFF) * 0x01010101
for _ = 1, 8 do
writeu32(dst, off, c)
writeu32(dst, off + 4, c)
off += stride
end
else
for _ = 1, 8 do
for i = off, off + 7 do
writeu8(dst, i, readu8(CLAMP, readu8(dst, i) + v + COFF))
end
off += stride
end
end
end
-- ------------------------------------------------------------------------------------------------ motion
-- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst
-- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what
-- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for
-- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits
-- each byte into its low 2 bits and high 6 bits so no lane overflows.
function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean)
for _ = 1, h do
for i = 0, w - 4, 4 do
local p
if hx == 0 then
if hy == 0 then
p = readu32(src, sOff + i)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + sStride)
p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
end
elseif hy == 0 then
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
p = bor(a, b) - rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1)
local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x02020202
local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2)
p = hi + band(rshift(l, 2), 0x0F0F0F0F)
end
if avg then
local q = readu32(dst, dOff + i)
p = bor(p, q) - rshift(band(bxor(p, q), 0xFEFEFEFE), 1)
end
writeu32(dst, dOff + i, p)
end
sOff += sStride
dOff += dStride
end
end
-- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1:
-- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst.
function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number)
if hx == 0 and hy == 0 then
Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false)
return
end
local dx = if hx == 0 then sStride else 1 -- the second sample of a two-tap average
for _ = 1, h do
for i = 0, w - 4, 4 do
local p
if hx == 0 or hy == 0 then
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + dx)
p = band(a, b) + rshift(band(bxor(a, b), 0xFEFEFEFE), 1)
else
local a, b = readu32(src, sOff + i), readu32(src, sOff + i + 1)
local c, d = readu32(src, sOff + i + sStride), readu32(src, sOff + i + sStride + 1)
local l = band(a, 0x03030303) + band(b, 0x03030303) + band(c, 0x03030303) + band(d, 0x03030303) + 0x01010101
local hi = rshift(band(a, 0xFCFCFCFC), 2) + rshift(band(b, 0xFCFCFCFC), 2) + rshift(band(c, 0xFCFCFCFC), 2) + rshift(band(d, 0xFCFCFCFC), 2)
p = hi + band(rshift(l, 2), 0x0F0F0F0F)
end
writeu32(dst, dOff + i, p)
end
sOff += sStride
dOff += dStride
end
end
-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to
-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture
-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes).
Dsp.EDGE_STRIDE = 32
Dsp.EDGE_SIZE = 32 * 34 + 4
function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer)
for j = 0, h do
local sy = y + j
sy = if sy < 0 then 0 elseif sy >= ph then ph - 1 else sy
local row = base + sy * stride
local o = j * 32
for i = 0, w do
local sx = x + i
sx = if sx < 0 then 0 elseif sx >= pw then pw - 1 else sx
writeu8(out, o + i, readu8(src, row + sx))
end
end
end
return Dsp
+894
View File
@@ -0,0 +1,894 @@
--!strict
--!native
--!optimize 2
-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T
-- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark).
--
-- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats,
-- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers
-- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion
-- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the
-- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular
-- slices) and the extended escape of Annex T. Sorenson Spark
-- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit
-- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message):
-- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures,
-- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced
-- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape).
--
-- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL|
-- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read
-- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int`
-- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors).
--
-- local core = D.new(flv, maxPixels)
-- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding)
-- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned)
-- core.reset() -- forget the reference (after a seek)
local Tb = require("@rosetta/codecs/video/H263/Tables")
local Dsp = require("@rosetta/codecs/video/Dsp")
local readu8 = buffer.readu8
local readu32 = buffer.readu32
local readi32 = buffer.readi32
local writei32 = buffer.writei32
local bfill = buffer.fill
local band = bit32.band
local bor = bit32.bor
local lshift = bit32.lshift
local rshift = bit32.rshift
local bswap = bit32.byteswap
local idct = Dsp.idct
local fillBlock = Dsp.fill
local mc = Dsp.mc
local mcNoRound = Dsp.mcNoRound
local edge = Dsp.edge
local MCBPC_I = Tb.MCBPC_I
local MCBPC_P = Tb.MCBPC_P
local CBPY = Tb.CBPY
local MVD = Tb.MVD
local TCOEF = Tb.TCOEF
local ZIGZAG = Tb.ZIGZAG
local DQUANT = Tb.DQUANT
local STUFFING = Tb.STUFFING
local ESCAPE = Tb.ESCAPE
local PAD = 4096 -- zero bytes after the data: a macroblock reads at most ~2.5 KB, the end check runs per macroblock
local D = {}
D.PICTURE_I = 1
D.PICTURE_P = 2
-- the PLUSPTYPE options that persist while UFEP = 0
export type Opp = {
format: number,
customPcf: boolean,
umv: boolean,
ss: boolean, -- slice structured (Annex K)
options: string?, -- the unsupported options set, or nil
width: number,
height: number,
}
export type Header = {
flv: boolean,
version: number, -- Sorenson Spark: 0 (H.263 escapes) or 1 (7 / 11-bit escapes)
tr: number, -- temporal reference
width: number,
height: number,
ptype: number, -- 1 I, 2 P
disposable: boolean, -- Sorenson: a P picture nothing predicts from
quant: number,
umv: boolean, -- unrestricted vectors, baseline form (long vectors)
umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form
rounding: number, -- RTYPE (0: half-sample averages round up)
plus: boolean, -- PLUSPTYPE
ss: boolean, -- slice structured (Annex K)
cpm: boolean,
deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg)
aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen)
aspectNum: number?,
aspectDen: number?,
opp: Opp?, -- the PLUSPTYPE options in force
bitPos: number, -- absolute bit position of the first macroblock
}
export type Store = {
y: buffer,
cb: buffer,
cr: buffer,
ls: number, -- luma stride (16 * macroblock columns); chroma stride ls / 2
w: number,
h: number,
ptype: number,
tr: number,
disposable: boolean,
}
-- ------------------------------------------------------------------------------------------------ header
-- the length of a slice's MBA field for a picture of n macroblocks (table K.2)
function D.mbaBits(n: number): number
return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14
end
-- n (<= 24) bits at bit position p of buf, zeros past endByte
local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number
local v = 0
for k = p, p + n - 1 do
local byte = rshift(k, 3)
local b = if byte < endByte then readu8(buf, byte) else 0
v = v * 2 + band(rshift(b, 7 - band(k, 7)), 1)
end
return v
end
-- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson:
-- 17 bits 0..01 and version 0 / 1), or -1
local function findStart(buf: buffer, off: number, len: number, flv: boolean): number
local mask = if flv then 0xF8 else 0xFC
for i = off, off + len - 3 do
if readu8(buf, i) == 0 and readu8(buf, i + 1) == 0 and band(readu8(buf, i + 2), mask) == 0x80 then
return i
end
end
return -1
end
-- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in
-- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them)
function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?)
if off < 0 or len < 0 or off + len > buffer.len(buf) then
return nil, "bad range"
end
local s = findStart(buf, off, len, flv)
if s < 0 then
return nil, "no picture start code"
end
local e = off + len
local p = s * 8
local function bits(n: number): number
local v = bitsAt(buf, e, p, n)
p += n
return v
end
local h: Header = {
flv = flv,
version = 0,
tr = 0,
width = 0,
height = 0,
ptype = 1,
disposable = false,
quant = 1,
umv = false,
umvPlus = false,
rounding = 0,
plus = false,
ss = false,
cpm = false,
deblock = false,
bitPos = 0,
}
if flv then
bits(17)
h.version = bits(5)
h.tr = bits(8)
local size = bits(3)
if size == 0 then
h.width, h.height = bits(8), bits(8)
elseif size == 1 then
h.width, h.height = bits(16), bits(16)
elseif size <= 6 then
local d = Tb.FLV_SIZES[size]
h.width, h.height = d[1], d[2]
else
return nil, "reserved picture size"
end
local t = bits(2)
if t == 3 then
return nil, "reserved picture type"
end
h.ptype = if t == 0 then 1 else 2
h.disposable = t == 2
h.deblock = bits(1) == 1
h.quant = bits(5)
else
bits(22)
h.tr = bits(8)
if bits(1) ~= 1 or bits(1) ~= 0 then
return nil, "bad PTYPE"
end
bits(3) -- split screen, document camera, freeze picture release
local format = bits(3)
if format >= 1 and format <= 5 then
local d = Tb.FORMATS[format]
h.width, h.height = d[1], d[2]
h.ptype = bits(1) + 1
h.umv = bits(1) == 1
local sac, ap, pb = bits(1), bits(1), bits(1)
if sac == 1 then
return nil, "unsupported: syntax-based arithmetic coding"
elseif ap == 1 then
return nil, "unsupported: advanced prediction mode"
elseif pb == 1 then
return nil, "unsupported: PB-frames"
end
h.quant = bits(5)
h.cpm = bits(1) == 1
if h.cpm then
bits(2)
end
elseif format == 7 then
h.plus = true
local ufep = bits(3)
local o: Opp
if ufep == 1 then
local f = bits(3)
local pcf, umv = bits(1) == 1, bits(1) == 1
local names: { string } = { "syntax-based arithmetic coding", "advanced prediction", "advanced intra coding",
"deblocking filter", "slice structure", "reference picture selection", "independent segment decoding",
"alternative inter VLC", "modified quantisation" }
local unsup: string? = nil
local ss = false
for i = 1, 9 do
if bits(1) == 1 then
if i == 5 then
ss = true
elseif not unsup then
unsup = names[i]
end
end
end
bits(4) -- 1 000
o = { format = f, customPcf = pcf, umv = umv, ss = ss, options = unsup, width = 0, height = 0 }
elseif ufep == 0 and opp then
o = opp
else
return nil, if ufep == 0 then "PLUSPTYPE without the options (UFEP 0 first)" else "bad UFEP"
end
local t = bits(3)
if t ~= 0 and t ~= 1 then
return nil, "unsupported: " .. ({ "", "improved PB-frames", "B-pictures", "EI-pictures", "EP-pictures", "reserved", "reserved" })[t] .. " picture type"
end
h.ptype = t + 1
local rpr, rru = bits(1), bits(1)
h.rounding = bits(1)
bits(3) -- 0 0 1
if rpr == 1 then
return nil, "unsupported: reference picture resampling"
elseif rru == 1 then
return nil, "unsupported: reduced-resolution update"
end
local unsupported = o.options
if unsupported ~= nil then
return nil, "unsupported: " .. unsupported
end
h.cpm = bits(1) == 1
if h.cpm then
bits(2)
end
if ufep == 1 then
if o.format == 6 then
local par = bits(4)
o.width = (bits(9) + 1) * 4
bits(1)
o.height = bits(9) * 4
h.aspect = par
if par == 15 then
h.aspectNum, h.aspectDen = bits(8), bits(8)
end
elseif o.format >= 1 and o.format <= 5 then
local d = Tb.FORMATS[o.format]
o.width, o.height = d[1], d[2]
else
return nil, "bad source format " .. o.format
end
if o.customPcf then
bits(8) -- clock conversion code, clock divisor
end
end
if o.customPcf then
bits(2) -- ETR
end
if ufep == 1 and o.umv then
if bits(1) == 0 then
bits(1)
end
end
if ufep == 1 and o.ss then
if bits(1) == 1 then
return nil, "unsupported: rectangular slices"
end
bits(1) -- arbitrary slice ordering (slices carry their address)
end
h.width, h.height = o.width, o.height
h.umvPlus = o.umv
h.ss = o.ss
h.opp = o
else
return nil, "bad source format " .. format
end
h.quant = if h.plus then bits(5) else h.quant
end
-- PEI / PSPARE
local guard = 0
while bits(1) == 1 do
bits(8)
guard += 1
if guard > 256 then
return nil, "PSPARE without end"
end
end
if h.quant == 0 then
return nil, "QUANT 0"
end
if h.width < 1 or h.height < 1 then
return nil, "empty picture size"
end
if h.ss then
-- the first slice's SEPB1, MBA and SEPB2
bits(1)
bits(D.mbaBits((h.width + 15) // 16 * ((h.height + 15) // 16)))
bits(1)
end
if p > e * 8 then
return nil, "truncated picture header"
end
h.bitPos = p
return h, nil
end
-- ------------------------------------------------------------------------------------------------ decoder
export type Core = {
decode: (buf: buffer, off: number, len: number) -> (Store?, string?),
reset: () -> (),
state: {
width: number,
height: number,
pictures: number,
errors: number,
header: Header?,
opp: Opp?,
maxPixels: number,
},
}
function D.new(flv: boolean, maxPixels: number?): Core
local state = {
width = 0,
height = 0,
pictures = 0,
errors = 0,
header = nil :: Header?,
opp = nil :: Opp?,
maxPixels = maxPixels or 4096 * 2304,
}
-- bitstream
local data = buffer.create(64 * 1024 + PAD)
local endBits = 0
local pos = 0
local err = false
-- picture
local W, H = 0, 0
local mbW, mbH = 0, 0
local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights
local stores: { Store } = {}
local ref: Store? = nil
local curY, curCb, curCr = data, data, data
local refY, refCb, refCr = data, data, data
local quant = 1
local escFlv = false -- Sorenson version 1 escapes
local longMv = false
local umvPlus = false
local mcf = mc
local mvX, mvY = {} :: { number }, {} :: { number } -- the current row's vectors (half samples)
local upX, upY = {} :: { number }, {} :: { number } -- the row above
local blk = buffer.create(256)
local EDGE = buffer.create(Dsp.EDGE_SIZE)
local function read(n: number): number
local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp))
local s = band(pos, 7)
if s ~= 0 then
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
end
pos += n
return rshift(w, 32 - n)
end
local function peek32(): number
local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp))
local s = band(pos, 7)
if s ~= 0 then
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
end
return w
end
local function vlc(lut: buffer, k: number): number
local e = readu32(lut, rshift(peek32(), 32 - k) * 4)
local l = rshift(e, 16)
if l == 0 then
err = true
return 0
end
pos += l
return band(e, 0xFFFF)
end
local function alloc(w: number, h: number)
W, H = w, h
mbW, mbH = (w + 15) // 16, (h + 15) // 16
ls, cs, lh, chh = mbW * 16, mbW * 8, mbH * 16, mbH * 8
stores = {}
for i = 1, 2 do
local y = buffer.create(ls * lh)
local cb = buffer.create(cs * chh)
local cr = buffer.create(cs * chh)
bfill(cb, 0, 128)
bfill(cr, 0, 128)
stores[i] = { y = y, cb = cb, cr = cr, ls = ls, w = w, h = h, ptype = 0, tr = 0, disposable = false }
end
mvX, mvY, upX, upY = table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0), table.create(mbW, 0)
ref = nil
state.width, state.height = w, h
end
-- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's
-- coefficients added to the prediction already in dst
local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean
local i = 0
local dcOnly = true
if intra then
local v = read(8)
if v == 255 then
v = 128
end
writei32(blk, 0, v * 8)
i = 1
end
if coded then
local q2 = quant * 2
local qadd = if quant % 2 == 1 then quant else quant - 1
while true do
local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp))
local s = band(pos, 7)
if s ~= 0 then
w = bor(lshift(w, s), rshift(readu8(data, bp + 4), 8 - s))
end
local e = readu32(TCOEF, rshift(w, 20) * 4)
local l = rshift(e, 16)
if l == 0 then
err = true
return false
end
local v = band(e, 0xFFFF)
local last, run, level
if v == ESCAPE then
-- the escape and the 25 (H.263) / 22 or 26 (Sorenson v1) bits after it, all inside w's next bits
if escFlv then
local is11 = band(rshift(w, 24), 1)
last = band(rshift(w, 23), 1)
run = band(rshift(w, 17), 63)
if is11 == 1 then
level = band(rshift(w, 6), 2047)
if level >= 1024 then
level -= 2048
end
pos += 7 + 1 + 7 + 11
else
level = band(rshift(w, 10), 127)
if level >= 64 then
level -= 128
end
pos += 7 + 1 + 7 + 7
end
else
last = band(rshift(w, 24), 1)
run = band(rshift(w, 18), 63)
level = band(rshift(w, 10), 255)
pos += 7 + 1 + 6 + 8
if level == 128 then
-- the extended escape (Annex T): 5 low bits, then 6 signed high bits
local x = read(11)
level = band(x, 31) + (rshift(x, 5) - (if x >= 1024 then 64 else 0)) * 32
elseif level > 128 then
level -= 256
end
end
if level == 0 then
err = true
return false
end
else
last = rshift(v, 10)
run = band(rshift(v, 4), 63)
level = band(v, 15)
if band(w, lshift(1, 31 - l)) ~= 0 then
level = -level
end
pos += l + 1
end
i += run
if i > 63 then
err = true
return false
end
local rec = if level > 0 then level * q2 + qadd else level * q2 - qadd
-- not the -2048..2047 saturation of H.263 6.2.1: ffmpeg does not saturate, and encoders write values
-- slightly past it (2055 = 68 * 30 + 15). +-2400 bounds the IDCT output to Dsp's clamp table.
if rec > 2400 then
rec = 2400
elseif rec < -2400 then
rec = -2400
end
local z = readu8(ZIGZAG, i)
if z ~= 0 then
dcOnly = false
end
writei32(blk, z * 4, rec)
i += 1
if last ~= 0 then
break
end
end
elseif not intra then
return true
end
if dcOnly then
local dc = readi32(blk, 0)
writei32(blk, 0, 0)
fillBlock(dst, off, stride, (dc + 4) // 8, not intra)
else
idct(blk, dst, off, stride, not intra)
bfill(blk, 0, 0, 256)
end
return true
end
-- one motion vector component from its prediction (half samples)
local function motion(pred: number): number
if umvPlus then
-- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign
if read(1) == 1 then
return pred
end
local code = 2 + read(1)
local guard = 0
while read(1) == 1 do
code = code * 2 + read(1)
guard += 1
if guard > 14 then
err = true
return pred
end
end
local mag = code // 2
return if code % 2 == 1 then pred - mag else pred + mag
end
local d = vlc(MVD, 12)
if d == 0 then
return pred
end
if read(1) == 1 then
d = -d
end
local v = pred + d
if longMv then
-- Annex D (baseline header): vectors up to +-31.5; the other value of a code pair only past +-16
if pred < -31 and v < -63 then
v += 64
elseif pred > 32 and v > 63 then
v -= 64
end
return v
end
return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5
end
-- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples
local function predict(col: number, row: number, mx: number, my: number)
local hx, hy = mx % 2, my % 2
local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2
local dOff = row * 16 * ls + col * 16
if sx < 0 or sy < 0 or sx + 16 + hx > ls or sy + 16 + hy > lh then
edge(refY, ls, 0, sx, sy, 16, 16, ls, lh, EDGE)
mcf(EDGE, 32, 0, curY, ls, dOff, 16, 16, hx, hy, false)
else
mcf(refY, ls, sy * ls + sx, curY, ls, dOff, 16, 16, hx, hy, false)
end
-- chroma: the luma position halved, half-sample flags from the quarter positions rounded to halves
local cx, cy = sx // 2, sy // 2
local chx = if hx == 1 or (mx // 2) % 2 == 1 then 1 else 0
local chy = if hy == 1 or (my // 2) % 2 == 1 then 1 else 0
local cOff = row * 8 * cs + col * 8
if cx < 0 or cy < 0 or cx + 8 + chx > cs or cy + 8 + chy > chh then
edge(refCb, cs, 0, cx, cy, 8, 8, cs, chh, EDGE)
mcf(EDGE, 32, 0, curCb, cs, cOff, 8, 8, chx, chy, false)
edge(refCr, cs, 0, cx, cy, 8, 8, cs, chh, EDGE)
mcf(EDGE, 32, 0, curCr, cs, cOff, 8, 8, chx, chy, false)
else
local so = cy * cs + cx
mcf(refCb, cs, so, curCb, cs, cOff, 8, 8, chx, chy, false)
mcf(refCr, cs, so, curCr, cs, cOff, 8, 8, chx, chy, false)
end
end
-- a macroblock copied from the reference (not coded, or concealed); mid-grey without one
local function copyMb(col: number, row: number)
local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8
if ref then
mc(refY, ls, yo, curY, ls, yo, 16, 16, 0, 0, false)
mc(refCb, cs, co, curCb, cs, co, 8, 8, 0, 0, false)
mc(refCr, cs, co, curCr, cs, co, 8, 8, 0, 0, false)
else
fillBlock(curY, yo, ls, 128, false)
fillBlock(curY, yo + 8, ls, 128, false)
fillBlock(curY, yo + 8 * ls, ls, 128, false)
fillBlock(curY, yo + 8 * ls + 8, ls, 128, false)
fillBlock(curCb, co, cs, 128, false)
fillBlock(curCr, co, cs, 128, false)
end
end
-- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of
-- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first
-- macroblock of a slice, whose left neighbour is outside). false on bad data.
local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean
if pos > endBits then
return false
end
if P and read(1) == 1 then
copyMb(col, row)
mvX[col + 1], mvY[col + 1] = 0, 0
return true
end
local lut = if P then MCBPC_P else MCBPC_I
local m = vlc(lut, 9)
while m == STUFFING and not err do
if P and read(1) == 1 then -- stuffing is followed by a new COD in P-pictures
copyMb(col, row)
mvX[col + 1], mvY[col + 1] = 0, 0
return pos <= endBits
end
if pos > endBits then
return false
end
m = vlc(lut, 9)
end
if err then
return false
end
local mtype, cbpc = m // 4, m % 4
if mtype == 2 then
err = true -- INTER4V needs advanced prediction (Annex F), which the header refused
return false
end
local intra = mtype >= 3
local cbpy = vlc(CBPY, 6)
if err then
return false
end
if mtype == 1 or mtype == 4 then
quant = math.clamp(quant + DQUANT[read(2)], 1, 31)
end
local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8
if intra then
mvX[col + 1], mvY[col + 1] = 0, 0
if not block(true, cbpy >= 8, curY, yo, ls) or not block(true, cbpy % 8 >= 4, curY, yo + 8, ls)
or not block(true, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(true, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls)
or not block(true, cbpc >= 2, curCb, co, cs) or not block(true, cbpc % 2 == 1, curCr, co, cs) then
return false
end
return pos <= endBits
end
cbpy = 15 - cbpy
-- the vector prediction: the median of left, above and above right (outside or past the right edge: 0; the
-- first row of a picture / GOB: the left vector)
local ax = if col > 0 and not first then mvX[col] else 0
local ay = if col > 0 and not first then mvY[col] else 0
local px, py = ax, ay
if not top then
local bx, by = upX[col + 1], upY[col + 1]
local cx = if col + 1 < mbW then upX[col + 2] else 0
local cy = if col + 1 < mbW then upY[col + 2] else 0
px = math.max(math.min(ax, bx), math.min(math.max(ax, bx), cx))
py = math.max(math.min(ay, by), math.min(math.max(ay, by), cy))
end
local mx = motion(px)
local my = motion(py)
if umvPlus and mx - px == 1 and my - py == 1 then
pos += 1 -- start code emulation prevention bit
end
if err then
return false
end
mvX[col + 1], mvY[col + 1] = mx, my
predict(col, row, mx, my)
if not block(false, cbpy >= 8, curY, yo, ls) or not block(false, cbpy % 8 >= 4, curY, yo + 8, ls)
or not block(false, cbpy % 4 >= 2, curY, yo + 8 * ls, ls) or not block(false, cbpy % 2 == 1, curY, yo + 8 * ls + 8, ls)
or not block(false, cbpc >= 2, curCb, co, cs) or not block(false, cbpc % 2 == 1, curCr, co, cs) then
return false
end
return pos <= endBits
end
-- a GBSC / SSC (17 bits 0..01) next, after zero stuffing to a byte boundary or not: consumed, true
local function startCode(): boolean
local w = peek32()
if rshift(w, 15) ~= 1 then
local s = (8 - pos % 8) % 8
if s == 0 or rshift(w, 32 - s) ~= 0 or rshift(lshift(w, s), 15) ~= 1 then
return false
end
pos += s
end
pos += 17
return true
end
-- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil
local function gobHeader(cpm: boolean): (number?, number?)
if not startCode() then
return nil, nil
end
local gn = read(5)
if cpm then
read(2)
end
read(2) -- GFID
return gn, read(5)
end
-- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil
local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?)
if not startCode() then
return nil, nil
end
read(1) -- SEPB1
if cpm then
read(2)
end
local mba = read(mbaBits)
if sepb2 then
read(1)
end
local q = read(5)
read(3) -- SEPB3, GFID
return mba, q
end
local function picture(hdr: Header): (Store?, string?)
if hdr.width ~= W or hdr.height ~= H then
if hdr.width * hdr.height > state.maxPixels then
return nil, "limit: picture size " .. hdr.width .. "x" .. hdr.height
end
alloc(hdr.width, hdr.height)
end
local P = hdr.ptype == 2
local r = ref
if P and not r then
return nil, "a P picture without a reference picture"
end
local cur = if stores[1] == r then stores[2] else stores[1]
curY, curCb, curCr = cur.y, cur.cb, cur.cr
if r then
refY, refCb, refCr = r.y, r.cb, r.cr
end
quant = hdr.quant
escFlv = hdr.flv and hdr.version == 1
longMv = hdr.umv
umvPlus = hdr.umvPlus
mcf = if hdr.rounding == 1 then mcNoRound :: any else mc
pos = hdr.bitPos
err = false
local gobRows = if hdr.flv then 0 elseif H <= 400 then 1 elseif H <= 800 then 2 else 4
local ss = hdr.ss
local total = mbW * mbH
local mbaBits = D.mbaBits(total)
local resync = 0 -- the first macroblock of the current GOB with a header / slice
local k = 0
local failAt = -1
mvX, upX = upX, mvX
mvY, upY = upY, mvY
while k < total do
local col, row = k % mbW, k // mbW
if k > 0 and (ss or (gobRows > 0 and col == 0 and row % gobRows == 0)) then
local at, q
if ss then
at, q = sliceHeader(hdr.cpm, mbaBits, total > 1584)
else
local gn, gq = gobHeader(hdr.cpm)
if gn then
at, q = if gn == 0 then -1 else gn * gobRows * mbW, gq
end
end
if at and q then
if at < k or at >= total or q == 0 then
failAt = k
break
end
while k < at do -- macroblocks missing in between: copied
copyMb(k % mbW, k // mbW)
mvX[k % mbW + 1], mvY[k % mbW + 1] = 0, 0
k += 1
if k % mbW == 0 then
mvX, upX = upX, mvX
mvY, upY = upY, mvY
end
end
col, row = k % mbW, k // mbW
resync, quant = k, q
end
end
-- above is outside for the slice's first mbW macroblocks (ffmpeg's first_slice_line: also the start of the
-- next row for a slice starting mid-row)
if not macroblock(col, row, P, k < resync + mbW, k == resync) then
failAt = k
break
end
k += 1
if k % mbW == 0 then
mvX, upX = upX, mvX
mvY, upY = upY, mvY
end
end
local msg: string? = nil
if failAt >= 0 then
state.errors += 1
msg = "bad macroblock data at macroblock " .. failAt
for k = failAt, mbW * mbH - 1 do
copyMb(k % mbW, k // mbW)
end
end
cur.ptype = hdr.ptype
cur.tr = hdr.tr
cur.disposable = hdr.disposable
if not hdr.disposable then
ref = cur
end
state.pictures += 1
return cur, msg
end
local core = {} :: Core
core.state = state
function core.decode(buf: buffer, off: number, len: number): (Store?, string?)
local hdr, herr = D.header(buf, off, len, flv, state.opp)
if not hdr then
state.errors += 1
return nil, herr
end
state.header = hdr
if hdr.opp then
state.opp = hdr.opp
end
-- the data from the header on, with zero padding
local need = len + PAD
if buffer.len(data) < need then
data = buffer.create(need)
else
bfill(data, len, 0, PAD)
end
buffer.copy(data, 0, buf, off, len)
endBits = len * 8
hdr.bitPos -= off * 8
local s, msg = picture(hdr)
hdr.bitPos += off * 8
return s, msg
end
function core.reset()
ref = nil
end
return core
end
return D
+206
View File
@@ -0,0 +1,206 @@
--!strict
-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures,
-- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of
-- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time.
--
-- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code).
-- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA,
-- 4 INTRA+Q), STUFFING for the stuffing code
-- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value)
-- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0)
-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code
local T = {}
T.STUFFING = 255
T.ESCAPE = 0xFFFF
-- builds a K-bit flat table from { bits, value } pairs
local function flat(codes: { { any } }, k: number): buffer
local lut = buffer.create(4 * 2 ^ k)
for _, c in codes do
local bits: string = c[1]
local len = #bits
local code = tonumber(bits, 2) :: number
local shift = k - len
local first = code * 2 ^ shift
for i = first, first + 2 ^ shift - 1 do
buffer.writeu32(lut, i * 4, len * 65536 + c[2])
end
end
return lut
end
-- table 7: MCBPC for I-pictures (type 3 INTRA, 4 INTRA+Q; CBPC = Cb Cr)
T.MCBPC_I = flat({
{ "1", 3 * 4 + 0 },
{ "001", 3 * 4 + 1 },
{ "010", 3 * 4 + 2 },
{ "011", 3 * 4 + 3 },
{ "0001", 4 * 4 + 0 },
{ "000001", 4 * 4 + 1 },
{ "000010", 4 * 4 + 2 },
{ "000011", 4 * 4 + 3 },
{ "000000001", T.STUFFING },
}, 9)
-- table 8: MCBPC for P-pictures
T.MCBPC_P = flat({
{ "1", 0 * 4 + 0 },
{ "0011", 0 * 4 + 1 },
{ "0010", 0 * 4 + 2 },
{ "000101", 0 * 4 + 3 },
{ "011", 1 * 4 + 0 },
{ "0000111", 1 * 4 + 1 },
{ "0000110", 1 * 4 + 2 },
{ "000000101", 1 * 4 + 3 },
{ "010", 2 * 4 + 0 },
{ "0000101", 2 * 4 + 1 },
{ "0000100", 2 * 4 + 2 },
{ "00000101", 2 * 4 + 3 },
{ "00011", 3 * 4 + 0 },
{ "00000100", 3 * 4 + 1 },
{ "00000011", 3 * 4 + 2 },
{ "0000011", 3 * 4 + 3 },
{ "000100", 4 * 4 + 0 },
{ "000000100", 4 * 4 + 1 },
{ "000000011", 4 * 4 + 2 },
{ "000000010", 4 * 4 + 3 },
{ "000000001", T.STUFFING },
}, 9)
-- table 13: CBPY (intra values 0..15)
do
local codes = { "0011", "00101", "00100", "1001", "00011", "0111", "000010", "1011", "00010", "000011", "0101",
"1010", "0100", "1000", "0110", "11" }
local list = {}
for i, c in codes do
list[i] = { c, i - 1 }
end
T.CBPY = flat(list, 6)
end
-- table 14: MVD magnitudes 0, 0.5, 1, ... 16 (in half samples 0..32); the sign bit is not part of these
do
local codes = { "1", "01", "001", "0001", "000011", "0000101", "0000100", "0000011", "000001011", "000001010",
"000001001", "0000010001", "0000010000", "0000001111", "0000001110", "0000001101", "0000001100", "0000001011",
"0000001010", "0000001001", "0000001000", "0000000111", "0000000110", "0000000101", "0000000100", "00000000111",
"00000000110", "00000000101", "00000000100", "00000000011", "00000000010", "000000000011", "000000000010" }
local list = {}
for i, c in codes do
list[i] = { c, i - 1 }
end
T.MVD = flat(list, 12)
end
-- table 16: TCOEF, per LAST and RUN the codes of levels 1, 2, ... (without the sign bit)
local TCOEF_LAST0: { [number]: { string } } = {
[0] = { "10", "1111", "010101", "0010111", "00011111", "000100101", "000100100", "0000100001", "0000100000",
"00000000111", "00000000110", "00000100000" },
[1] = { "110", "010100", "00011110", "0000001111", "00000100001", "000001010000" },
[2] = { "1110", "00011101", "0000001110", "000001010001" },
[3] = { "01101", "000100011", "0000001101" },
[4] = { "01100", "000100010", "000001010010" },
[5] = { "01011", "0000001100", "000001010011" },
[6] = { "010011", "0000001011", "000001010100" },
[7] = { "010010", "0000001010" },
[8] = { "010001", "0000001001" },
[9] = { "010000", "0000001000" },
[10] = { "0010110", "000001010101" },
[11] = { "0010101" },
[12] = { "0010100" },
[13] = { "00011100" },
[14] = { "00011011" },
[15] = { "000100001" },
[16] = { "000100000" },
[17] = { "000011111" },
[18] = { "000011110" },
[19] = { "000011101" },
[20] = { "000011100" },
[21] = { "000011011" },
[22] = { "000011010" },
[23] = { "00000100010" },
[24] = { "00000100011" },
[25] = { "000001010110" },
[26] = { "000001010111" },
}
local TCOEF_LAST1: { [number]: { string } } = {
[0] = { "0111", "000011001", "00000000101" },
[1] = { "001111", "00000000100" },
[2] = { "001110" },
[3] = { "001101" },
[4] = { "001100" },
[5] = { "0010011" },
[6] = { "0010010" },
[7] = { "0010001" },
[8] = { "0010000" },
[9] = { "00011010" },
[10] = { "00011001" },
[11] = { "00011000" },
[12] = { "00010111" },
[13] = { "00010110" },
[14] = { "00010101" },
[15] = { "00010100" },
[16] = { "00010011" },
[17] = { "000011000" },
[18] = { "000010111" },
[19] = { "000010110" },
[20] = { "000010101" },
[21] = { "000010100" },
[22] = { "000010011" },
[23] = { "000010010" },
[24] = { "000010001" },
[25] = { "0000000111" },
[26] = { "0000000110" },
[27] = { "0000000101" },
[28] = { "0000000100" },
[29] = { "00000100100" },
[30] = { "00000100101" },
[31] = { "00000100110" },
[32] = { "00000100111" },
[33] = { "000001011000" },
[34] = { "000001011001" },
[35] = { "000001011010" },
[36] = { "000001011011" },
[37] = { "000001011100" },
[38] = { "000001011101" },
[39] = { "000001011110" },
[40] = { "000001011111" },
}
do
local list = { { "0000011", T.ESCAPE } }
for last = 0, 1 do
local byRun = if last == 0 then TCOEF_LAST0 else TCOEF_LAST1
for run = 0, 40 do
local levels = byRun[run]
if levels then
for level, c in levels do
table.insert(list, { c, last * 1024 + run * 16 + level })
end
end
end
end
T.TCOEF = flat(list, 12)
T.TCOEF_COUNT = #list - 1
end
-- figure 14: the zigzag scan (scan index -> natural position)
T.ZIGZAG = buffer.create(64)
do
local zz = { 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 }
for i, v in zz do
buffer.writeu8(T.ZIGZAG, i - 1, v)
end
end
-- table 12: DQUANT (2 bits) -> the change of QUANT
T.DQUANT = { [0] = -1, -2, 1, 2 }
-- source formats 1..5 (sub-QCIF, QCIF, CIF, 4CIF, 16CIF): width, height
T.FORMATS = { { 128, 96 }, { 176, 144 }, { 352, 288 }, { 704, 576 }, { 1408, 1152 } }
-- Sorenson Spark picture sizes 2..6
T.FLV_SIZES = { [2] = { 352, 288 }, [3] = { 176, 144 }, [4] = { 128, 96 }, [5] = { 320, 240 }, [6] = { 160, 120 } }
return T
+176
View File
@@ -0,0 +1,176 @@
--!strict
-- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int.
-- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is
-- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal
-- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures,
-- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter
-- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP
-- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...).
--
-- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1)
-- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned)
-- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601)
-- local img, err = dec:image(packetData) -- both at once
-- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ...
-- dec:reset() -- after a seek: wait for the next I picture
--
-- Nothing here throws: bad arguments and bad data come back as nil, Err.
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local D = require("@rosetta/codecs/video/H263/Decoder")
local H263 = {}
H263.PICTURE_I = 1
H263.PICTURE_P = 2
export type Header = D.Header
export type Frame = {
width: number,
height: number,
-- decoder-owned planes, valid until the next decode: luma stride `stride`, chroma stride stride / 2
y: buffer,
cb: buffer,
cr: buffer,
stride: number,
pictureType: number, -- 1 I, 2 P
keyframe: boolean,
disposable: boolean, -- a Sorenson disposable inter picture (not used as a reference)
temporalReference: number,
index: number, -- pictures returned so far
flv: boolean,
}
export type Options = {
flv: boolean?, -- Sorenson Spark (FLV1) bitstreams (default false: H.263)
maxPixels: number?, -- larger pictures are refused (LIMIT; default 4096 * 2304)
}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable({} :: { _core: D.Core, _flv: boolean, _count: number, stats: { pictures: number, errors: number } }, Decoder))
function H263.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local flv = o.flv == true
local maxPixels = if type(o.maxPixels) == "number" and o.maxPixels > 0 then o.maxPixels else nil
return setmetatable({ _core = D.new(flv, maxPixels), _flv = flv, _count = 0, stats = { pictures = 0, errors = 0 } }, Decoder)
end
local function span(data: any, off: number?, len: number?): (buffer?, number, number)
local b: buffer
if type(data) == "string" then
b = buffer.fromstring(data)
elseif type(data) == "buffer" then
b = data
else
return nil, 0, 0
end
local total = buffer.len(b)
local o = math.floor(tonumber(off) or 0)
if o < 0 or o > total then
return nil, 0, 0
end
local n = math.floor(tonumber(len) or (total - o))
if n < 0 or o + n > total then
return nil, 0, 0
end
return b, o, n
end
-- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged
-- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them).
function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?)
local b, o, n = span(data, off, len)
if not b then
return nil, Err.new(Err.ARG, "decode: expected a buffer or string and a valid range")
end
local core = self._core
local s, msg = core.decode(b, o, n)
self.stats.pictures = core.state.pictures
self.stats.errors = core.state.errors
if not s then
return nil, Err.from(msg or "bad picture")
end
self._count += 1
return {
width = s.w,
height = s.h,
y = s.y,
cb = s.cb,
cr = s.cr,
stride = s.ls,
pictureType = s.ptype,
keyframe = s.ptype == 1,
disposable = s.disposable,
temporalReference = s.tr,
index = self._count,
flv = self._flv,
}, nil
end
-- decode + frameImage
function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?)
local f, err = self:decode(data, off, len)
if not f then
return nil, err
end
return H263.frameImage(f), nil
end
-- Forgets the reference picture (after a seek: P pictures fail until the next I picture).
function Decoder.reset(self: Decoder)
self._core.reset()
end
-- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x
-- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame
function H263.frameImage(frame: Frame): 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, ls = frame.width, frame.height, frame.stride
if type(w) ~= "number" or type(h) ~= "number" or type(ls) ~= "number" or w < 1 or h < 1 or ls < w then
return nil
end
local cw, ch, cs = (w + 1) // 2, (h + 1) // 2, ls // 2
if buffer.len(frame.y) < ls * h or buffer.len(frame.cb) < cs * ch or buffer.len(frame.cr) < cs * ch then
return nil
end
local 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 * ls, w)
end
local o = w * h
for y = 0, ch - 1 do
buffer.copy(px, o + y * cw, frame.cb, y * cs, cw)
buffer.copy(px, o + cw * ch + y * cw, frame.cr, y * cs, cw)
end
img.meta.yuv = { range = "limited", matrix = "bt601" }
img.meta.source = {
format = if frame.flv then "flv1" else "h263",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
disposable = frame.disposable,
}
return img
end
-- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err:
-- the first picture header in the data, without decoding (containers use it for the track size)
function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?)
local b, o, n = span(data, off, len)
if not b then
return nil, Err.new(Err.ARG, "header: expected a buffer or string and a valid range")
end
local h, msg = D.header(b, o, n, flv == true, nil)
if not h then
return nil, Err.from(msg or "bad picture header")
end
return h, nil
end
return H263
@@ -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
+777
View File
@@ -0,0 +1,777 @@
--!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("@rosetta/codecs/video/H264/Bitstream")
local Tables = require("@rosetta/codecs/video/H264/Tables")
local Mb = require("@rosetta/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
local hook = S.hook
local every = Mb.YIELD_MBS
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 hook and addr % every == 0 then
pcall(hook)
end
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
+264
View File
@@ -0,0 +1,264 @@
--!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("@rosetta/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
local hook = S.hook
for my = 0, mbH - 1 do
if hook and my > 0 then
pcall(hook)
end
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
+931
View File
@@ -0,0 +1,931 @@
--!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("@rosetta/codecs/video/H264/Intra")
local Transform = require("@rosetta/codecs/video/H264/Transform")
local Inter = require("@rosetta/codecs/video/H264/Inter")
local Mb = {}
Mb.YIELD_MBS = 16 -- macroblocks between calls of the cooperative yield hook (S.hook: Decoder Options.yield)
-- 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("@rosetta/codecs/video/H264/Bitstream")
local Tables = require("@rosetta/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("@rosetta/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
+415
View File
@@ -0,0 +1,415 @@
--!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("@rosetta/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("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
local Decoder = require("@rosetta/codecs/video/H264/Decoder")
local Params = require("@rosetta/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
yield: (() -> ())?, -- a cooperative yield point (see Decoder Options.yield): pcall'ed every 16 macroblocks
}
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,
yield = opts and opts.yield }
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
@@ -0,0 +1,303 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4
-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description
-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4
-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame
-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are
-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra
-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak
-- decoder. Never throws: every read is range-checked against its chunk.
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
local band = bit32.band
local Cinepak = {}
local MAX_STRIPS = 32
-- a codebook: 256 entries of 4 u32 rgba pixels (16 bytes); palettised streams use the low byte (the index)
local ENTRY = 16
local BOOK = 256 * ENTRY
export type State = {
books: buffer, -- MAX_STRIPS * 2 codebooks (V4 then V1 per strip)
filmSkip: number, -- Sega FILM extra header bytes (-1 = not known yet)
}
function Cinepak.state(): State
return { books = buffer.create(MAX_STRIPS * 2 * BOOK), filmSkip = -1 }
end
local function be16(d: buffer, o: number): number
return readu8(d, o) * 256 + readu8(d, o + 1)
end
local function be24(d: buffer, o: number): number
return readu8(d, o) * 65536 + readu8(d, o + 1) * 256 + readu8(d, o + 2)
end
local function be32(d: buffer, o: number): number
return readu8(d, o) * 16777216 + readu8(d, o + 1) * 65536 + readu8(d, o + 2) * 256 + readu8(d, o + 3)
end
local function clip(v: number): number
return if v < 0 then 0 elseif v > 255 then 255 else v
end
-- a codebook chunk (ids 0x20..0x27): entries of 4 or 6 bytes, all of them or those whose flag bit is set
local function codebook(books: buffer, book: number, id: number, d: buffer, p: number, stop: number)
local six = band(id, 4) == 0
local partial = band(id, 1) ~= 0
local size = if six then 6 else 4
local flag, mask = 0, 0
for i = 0, 255 do
if partial then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
end
if not partial or band(flag, mask) ~= 0 then
if p + size > stop then
return
end
local e = book + i * ENTRY
local y0, y1, y2, y3 = readu8(d, p), readu8(d, p + 1), readu8(d, p + 2), readu8(d, p + 3)
if six then
local u, v = readu8(d, p + 4), readu8(d, p + 5)
if u >= 128 then
u -= 256
end
if v >= 128 then
v -= 256
end
local uh = if u < 0 then -((-u) // 2) else u // 2 -- C division (towards zero)
local dr, dg, db = 2 * v, -uh - v, 2 * u
writeu32(books, e, clip(y0 + dr) + clip(y0 + dg) * 256 + clip(y0 + db) * 65536 + 0xFF000000)
writeu32(books, e + 4, clip(y1 + dr) + clip(y1 + dg) * 256 + clip(y1 + db) * 65536 + 0xFF000000)
writeu32(books, e + 8, clip(y2 + dr) + clip(y2 + dg) * 256 + clip(y2 + db) * 65536 + 0xFF000000)
writeu32(books, e + 12, clip(y3 + dr) + clip(y3 + dg) * 256 + clip(y3 + db) * 65536 + 0xFF000000)
else
writeu32(books, e, y0 * 0x10101 + 0xFF000000)
writeu32(books, e + 4, y1 * 0x10101 + 0xFF000000)
writeu32(books, e + 8, y2 * 0x10101 + 0xFF000000)
writeu32(books, e + 12, y3 * 0x10101 + 0xFF000000)
end
p += size
end
end
end
-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data
local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number,
stop: number, x1: number, y1: number, x2: number, y2: number): boolean
local stride = pic.stride
local pal = pic.idx
local px = (pal or pic.rgba) :: buffer
local flag, mask = 0, 0
local inter = band(id, 1) ~= 0
local v1only = band(id, 2) ~= 0
for y = y1, y2 - 1, 4 do
for x = x1, x2 - 1, 4 do
local paint = true
if inter then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return false
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
paint = band(flag, mask) ~= 0
end
if paint then
local useV1 = v1only
if not v1only then
mask //= 2
if mask == 0 then
if p + 4 > stop then
return false
end
flag = be32(d, p)
p += 4
mask = 0x80000000
end
useV1 = band(flag, mask) == 0
end
local o = y * stride + x
if useV1 then
if p >= stop then
return false
end
local e = v1 + readu8(d, p) * ENTRY
p += 1
-- each of the 4 entries fills a 2x2 square
local a, b, c, e4 = readu32(books, e), readu32(books, e + 4), readu32(books, e + 8), readu32(books, e + 12)
if pal then
a, b, c, e4 = a % 256, b % 256, c % 256, e4 % 256
writeu32(px, o, a * 0x0101 + b * 0x01010000)
writeu32(px, o + stride, a * 0x0101 + b * 0x01010000)
writeu32(px, o + 2 * stride, c * 0x0101 + e4 * 0x01010000)
writeu32(px, o + 3 * stride, c * 0x0101 + e4 * 0x01010000)
else
for r = 0, 3 do
local q = (o + r * stride) * 4
local l, rr = if r < 2 then a else c, if r < 2 then b else e4
writeu32(px, q, l)
writeu32(px, q + 4, l)
writeu32(px, q + 8, rr)
writeu32(px, q + 12, rr)
end
end
else
if p + 4 > stop then
return false
end
local e0 = v4 + readu8(d, p) * ENTRY
local e1 = v4 + readu8(d, p + 1) * ENTRY
local e2 = v4 + readu8(d, p + 2) * ENTRY
local e3 = v4 + readu8(d, p + 3) * ENTRY
p += 4
-- entry k covers the 2x2 square k (top-left, top-right, bottom-left, bottom-right)
if pal then
for r = 0, 3 do
local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3
local off = (r % 2) * 8
local q = o + r * stride
writeu8(px, q, readu8(books, l + off))
writeu8(px, q + 1, readu8(books, l + off + 4))
writeu8(px, q + 2, readu8(books, rr + off))
writeu8(px, q + 3, readu8(books, rr + off + 4))
end
else
for r = 0, 3 do
local l, rr = if r < 2 then e0 else e2, if r < 2 then e1 else e3
local off = (r % 2) * 8
local q = (o + r * stride) * 4
writeu32(px, q, readu32(books, l + off))
writeu32(px, q + 4, readu32(books, l + off + 4))
writeu32(px, q + 8, readu32(books, rr + off))
writeu32(px, q + 12, readu32(books, rr + off + 4))
end
end
end
end
end
end
return true
end
-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this
-- packet (an empty frame); false + message = an error
function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?)
local n = buffer.len(d)
if n < 10 then
return false, "frame too short"
end
local strips = be16(d, 8)
if strips == 0 and not (pic.idx and newPalette) then
return false, nil
end
local size = be24(d, 1)
if n < size * 5 // 100 then
return false, "frame shorter than its header says"
end
if st.filmSkip < 0 then
if size == 0 then
return false, "unsupported: a zero frame size"
end
if size ~= n and n % size ~= 0 then
if n >= 16 and readu8(d, 10) == 0xFE and readu8(d, 11) == 0 and readu8(d, 12) == 0 and readu8(d, 13) == 6
and readu8(d, 14) == 0 and readu8(d, 15) == 0 then
st.filmSkip = 6
else
st.filmSkip = 2
end
else
st.filmSkip = 0
end
end
local skip = st.filmSkip
if n < 10 + skip + strips * 12 then
return false, "truncated strip headers"
end
if strips > 0 then
local ss = be24(d, 10 + skip + 1)
if ss < 12 or ss > size then
return false, "bad strip size"
end
end
local flags = readu8(d, 0)
local p = 10 + skip
strips = math.min(strips, MAX_STRIPS)
local books = st.books
-- the coded area: the size rounded up to whole blocks (the picture's plane)
local cw, ch = pic.stride, pic.rows
local y0 = 0
for i = 0, strips - 1 do
if p + 12 > n then
return true, nil
end
local sy1 = be16(d, p + 4)
local sx1 = be16(d, p + 6)
local sy2, sx2 = be16(d, p + 8), be16(d, p + 10)
if sy1 == 0 then
sy1 = y0
sy2 = y0 + sy2
end
local ssize = be24(d, p + 1) - 12
if ssize < 0 then
return true, nil
end
p += 12
local stop = math.min(n, p + ssize)
local v4 = i * 2 * BOOK
local v1 = v4 + BOOK
if i > 0 and band(flags, 1) == 0 then
buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK)
end
-- the strip's chunks: codebooks, then one vector chunk
-- (strips start on block boundaries in every known stream: the plane holds whole blocks only)
if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then
return true, nil
end
local q = p
local done = false
while q + 4 <= stop do
local id = readu8(d, q)
local csize = be24(d, q + 1) - 4
if csize < 0 then
return true, nil
end
q += 4
local cstop = math.min(stop, q + csize)
if id == 0x20 or id == 0x21 or id == 0x24 or id == 0x25 then
codebook(books, v4, id, d, q, cstop)
elseif id == 0x22 or id == 0x23 or id == 0x26 or id == 0x27 then
codebook(books, v1, id, d, q, cstop)
elseif id == 0x30 or id == 0x31 or id == 0x32 then
if not vectors(pic, books, v4, v1, id, d, q, cstop, sx1, sy1, sx2, sy2) then
return true, nil
end
done = true
break
end
q = cstop
end
if not done then
return true, nil
end
p = stop
y0 = sy2
end
return true, nil
end
return Cinepak
+372
View File
@@ -0,0 +1,372 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is
-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's
-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit
-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK
-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX
-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26);
-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet
-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames.
-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture).
local Types = require("@rosetta/Types")
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local bfill = buffer.fill
local Flic = {}
-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette
export type State = {
pic: Picture.Picture,
depth: number, -- 8, 15, 16, 24
bpp: number, -- bytes per pixel
}
-- state(w, h, depth) -> State | nil, message
function Flic.state(w: number, h: number, depth: number): (State?, string?)
local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0
if bpp == 0 then
return nil, "unsupported: " .. depth .. "-bit FLIC"
end
local pic = Picture.new(w * bpp, h, true)
pic.w = w
return { pic = pic, depth = depth, bpp = bpp }, nil
end
local function s8(v: number): number
return if v >= 128 then v - 256 else v
end
-- decode(st, data) -> true | false, message
function Flic.decode(st: State, d: buffer): (boolean, string?)
local pic = st.pic
local px = pic.idx :: buffer
local pal = pic.pal
local w, h = pic.w, pic.h
local bpp = st.bpp
local deep = bpp > 1
local stride = pic.stride
local limit = stride * h
local n = buffer.len(d)
if n < 16 then
return false, "frame too short"
end
local p = 0
local function u8(): number
local v = if p < n then readu8(d, p) else 0
p += 1
return v
end
local function u16(): number
local a = u8()
return a + u8() * 256
end
local frameSize = math.min(readu32(d, 0), n)
local chunks = readu8(d, 6) + readu8(d, 7) * 256
if frameSize < 16 then
return false, "bad frame size"
end
frameSize -= 16
p = 16
while frameSize >= 6 and chunks > 0 and n - p >= 4 do
local size = readu32(d, p)
if size > frameSize then
size = frameSize
end
local after = p + size
p += 4
local typ = u16()
if typ == 4 or typ == 11 then
if not deep then
-- palette packets: skip count, change count (0 = 256), r g b
local shift = typ == 11
local packets = u16()
local at = 0
for _ = 1, packets do
at += u8()
local count = u8()
if count == 0 then
count = 256
end
if p + count * 3 > after then
break
end
for _ = 1, count do
if at >= 256 then
at = 0
end
local r, g, b = u8(), u8(), u8()
if shift then
-- 6-bit entries: v << 2 (kept to 8 bits), the top two bits repeated below
r, g, b = r * 4 % 256, g * 4 % 256, b * 4 % 256
r, g, b = r + r // 64, g + g // 64, b + b // 64
end
writeu32(pal, at * 4, r + g * 256 + b * 65536 + 0xFF000000)
at += 1
end
end
end
elseif typ == 7 or (deep and typ == 27) then
-- word-oriented delta: per line a count of packets (or a line skip / last-byte opcode)
local y = 0
local lines = u16()
while lines > 0 do
if p + 2 > after then
break
end
if y > limit then
return false, "delta past the picture"
end
local lp = u16()
if lp >= 0x8000 then
lp -= 0x10000
end
if deep then
if lp < 0 then
if -lp > h then
return false, "bad line skip"
end
y += -lp * stride
continue
end
elseif lp < 0 and lp >= -0x4000 then
-- 0xC000 .. 0xFFFF: skip lines
if -lp > h then
return false, "bad line skip"
end
y += -lp * stride
continue
elseif lp < 0 then
-- 0x8000 .. 0xBFFF: the low byte goes into the line's last pixel (ffmpeg writes the last byte of its
-- padded row instead: the same pixel when rows are not padded)
local q = y + w - 1
if q < 0 or q >= limit then
return false, "delta past the picture"
end
writeu8(px, q, lp % 256)
continue
elseif lp >= 0x4000 then
continue -- undefined opcode
end
lines -= 1
local q = y
for _ = 1, lp do
if p + 2 > after then
break
end
q += u8() * bpp
local run = s8(u8())
if deep then
local cnt = if run < 0 then -run else run
if q + cnt * bpp > limit then
return false, "delta past the picture"
end
if run < 0 then
local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0
for _ = 1, cnt do
writeu8(px, q, a)
writeu8(px, q + 1, b)
if bpp == 3 then
writeu8(px, q + 2, c)
end
q += bpp
end
else
if p + cnt * bpp > after then
break
end
buffer.copy(px, q, d, p, cnt * bpp)
p += cnt * bpp
q += cnt * bpp
end
elseif run < 0 then
local cnt = -run
local a, b = u8(), u8()
if q + cnt * 2 > limit then
return false, "delta past the picture"
end
for _ = 1, cnt do
writeu8(px, q, a)
writeu8(px, q + 1, b)
q += 2
end
else
if q + run * 2 > limit then
return false, "delta past the picture"
end
if p + run * 2 > after then
break
end
buffer.copy(px, q, d, p, run * 2)
p += run * 2
q += run * 2
end
end
y += stride
end
elseif typ == 12 and not deep then
-- byte-oriented delta (LC): first line, line count, per line packets of (skip, run)
local first = u16()
if first >= h then
return false, "bad first line"
end
local y = first * stride
local lines = u16()
while lines > 0 do
local q = y
if q > limit then
return false, "delta past the picture"
end
if p + 1 > after then
break
end
local packets = u8()
for _ = 1, packets do
if p + 1 > after then
break
end
q += u8()
local run = s8(u8())
if run > 0 then
if q + run > limit then
return false, "delta past the picture"
end
if p + run > after then
break
end
buffer.copy(px, q, d, p, run)
p += run
q += run
elseif run < 0 then
local v = u8()
if q - run > limit then
return false, "delta past the picture"
end
bfill(px, q, v, -run)
q -= run
end
end
y += stride
lines -= 1
end
elseif typ == 13 then
bfill(px, 0, 0, limit)
elseif typ == 15 or (deep and typ == 25) then
-- byte run (BRUN: bytes; DTA_BRUN: pixels of a deep FLIC): > 0 a run of one value, < 0 literals
local unit = if typ == 25 then bpp else 1
local y = 0
for _ = 1, h do
local q = y
p += 1 -- the packet count (unused)
local left = if typ == 25 then w else w * bpp
while left > 0 do
if p + 1 > after then
break
end
local run = s8(u8())
if run == 0 and not deep then
return false, "zero byte run"
end
if run > 0 then
if q + run * unit > limit then
return false, "run past the picture"
end
if unit == 1 then
bfill(px, q, u8(), run)
q += run
else
local a, b, c = u8(), u8(), if bpp == 3 then u8() else 0
for _ = 1, run do
writeu8(px, q, a)
writeu8(px, q + 1, b)
if bpp == 3 then
writeu8(px, q + 2, c)
end
q += bpp
end
end
left -= run
else
local cnt = -run
if q + cnt * unit > limit then
return false, "run past the picture"
end
if p + cnt * unit > after then
break
end
buffer.copy(px, q, d, p, cnt * unit)
p += cnt * unit
q += cnt * unit
left -= cnt
end
end
y += stride
end
elseif typ == 16 or (deep and typ == 26) then
-- uncompressed rows (8-bit rows padded to 4 bytes; deep rows of an odd width carry one pixel more)
local row = w * bpp
local padded = if deep then row + (w % 2) * bpp else ((w + 3) // 4) * 4
local ok = if deep then size - 6 <= ((w + 1) // 2) * 2 * h * bpp else size - 6 == padded * h
if ok then
if deep and n - p < row * h then
return false, "truncated copy chunk"
end
for y = 0, h - 1 do
local s = p + y * padded
local cnt = math.max(0, math.min(row, n - s))
if cnt > 0 then
buffer.copy(px, y * stride, d, s, cnt)
end
end
p += padded * h
end
end
-- typ 18 (PSTAMP) and unknown chunks are skipped
if after - p >= 0 then
p = after
else
break
end
frameSize -= size
chunks -= 1
end
return true, nil
end
-- image(st) -> a fresh rgba8 Image
function Flic.image(st: State): Types.Image
local pic = st.pic
if st.bpp == 1 then
return Picture.image(pic)
end
local w, h = pic.w, pic.h
local img = Types.Image.new(w, h, "rgba8")
local out = img.pixels
local px = pic.idx :: buffer
local stride = pic.stride
if st.bpp == 3 then
for y = 0, h - 1 do
local s, o = y * stride, y * w * 4
for x = 0, w - 1 do
local q = s + x * 3
writeu32(out, o + x * 4, readu8(px, q + 2) + readu8(px, q + 1) * 256 + readu8(px, q) * 65536 + 0xFF000000)
end
end
else
local lut = if st.depth == 15 then Picture.rgb555() else Picture.rgb565()
local mask = if st.depth == 15 then 32768 else 65536
for y = 0, h - 1 do
local s, o = y * stride, y * w * 4
for x = 0, w - 1 do
local q = s + x * 2
writeu32(out, o + x * 4, readu32(lut, ((readu8(px, q) + readu8(px, q + 1) * 256) % mask) * 4))
end
end
end
return img
end
return Flic
@@ -0,0 +1,121 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit
-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows
-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour
-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour
-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture.
-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there).
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
local band = bit32.band
local Msvideo1 = {}
-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1
-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)]
local function quadrant(x: number, y: number): number
return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0)
end
-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit)
function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?)
local n = buffer.len(d)
local bw, bh = pic.w // 4, pic.h // 4
if n < bw * bh // 512 then
return false, "frame too small"
end
local stride = pic.stride
local total = bw * bh
local skip = 0
local p = 0
local wide = bits ~= 8
local px = (if wide then pic.rgba else pic.idx) :: buffer
local lut = if wide then Picture.rgb555() else nil
local c = table.create(8, 0)
for by = bh - 1, 0, -1 do
for bx = 0, bw - 1 do
if skip ~= 0 then
skip -= 1
total -= 1
continue
end
if p + 2 > n then
return true, nil
end
local a, b = readu8(d, p), readu8(d, p + 1)
p += 2
if a == 0 and b == 0 and total == 0 then
return true, nil
end
-- the block's bottom-left pixel; its rows go up
local o = (by * 4 + 3) * stride + bx * 4
if band(b, 0xFC) == 0x84 then
skip = (b - 0x84) * 256 + a - 1
elseif b < 0x80 or (not wide and b >= 0x90) then
local flags = b * 256 + a
local eight
if wide then
if p + 4 > n then
return true, nil
end
c[1], c[2] = readu16(d, p), readu16(d, p + 2)
p += 4
eight = c[1] >= 0x8000
if eight then
if p + 12 > n then
return true, nil
end
for k = 3, 8 do
c[k] = readu16(d, p)
p += 2
end
end
else
eight = b >= 0x90
local cnt = if eight then 8 else 2
if p + cnt > n then
return true, nil
end
for k = 1, cnt do
c[k] = readu8(d, p)
p += 1
end
end
for y = 0, 3 do
local row = o - y * stride
for x = 0, 3 do
local k = (if band(flags, 1) == 1 then 1 else 2)
if eight then
k += quadrant(x, y)
end
flags = flags // 2
if lut then
writeu32(px, (row + x) * 4, readu32(lut, (c[k] % 32768) * 4))
else
writeu8(px, row + x, c[k])
end
end
end
else
local v = if wide then readu32(lut :: buffer, ((b * 256 + a) % 32768) * 4) else a
for y = 0, 3 do
local row = o - y * stride
if lut then
for x = 0, 3 do
writeu32(px, (row + x) * 4, v)
end
else
writeu32(px, row, v * 0x01010101)
end
end
end
total -= 1
end
end
return true, nil
end
return Msvideo1
@@ -0,0 +1,115 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame
-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette,
-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past
-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication
-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta.
local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels")
local readu32, writeu32 = buffer.readu32, buffer.writeu32
local Picture = {}
export type Picture = {
w: number,
h: number,
stride: number, -- index plane: bytes per row; rgba plane: pixels per row
rows: number,
idx: buffer?, -- u8 index plane, stride * rows bytes (palettised)
rgba: buffer?, -- u32 rgba8 plane, stride * rows * 4 bytes (direct colour)
pal: buffer, -- 256 u32 entries, bytes R, G, B, A
}
-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...)
function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture
local pw, ph = padW or 1, padH or 1
local stride = ((w + pw - 1) // pw) * pw
local rows = ((h + ph - 1) // ph) * ph
local pal = buffer.create(1024)
if palette and buffer.len(palette) >= 1024 then
buffer.copy(pal, 0, palette, 0, 1024)
end
local p: Picture = { w = w, h = h, stride = stride, rows = rows, pal = pal }
if palettised then
p.idx = buffer.create(stride * rows)
else
p.rgba = buffer.create(stride * rows * 4)
end
return p
end
-- image(p) -> a fresh rgba8 Image of the visible w x h
function Picture.image(p: Picture): Types.Image
local w, h = p.w, p.h
local img = Types.Image.new(w, h, "rgba8")
local idx, rgba = p.idx, p.rgba
if idx then
Pixels.indexed(idx, 0, p.stride, 8, img.pixels, w, h, true, p.pal)
elseif rgba then
if p.stride == w then
buffer.copy(img.pixels, 0, rgba, 0, w * h * 4)
else
for y = 0, h - 1 do
buffer.copy(img.pixels, y * w * 4, rgba, y * p.stride * 4, w * 4)
end
end
end
return img
end
-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track
function Picture.setPalette(p: Picture, src: buffer)
if buffer.len(src) >= 1024 then
buffer.copy(p.pal, 0, src, 0, 1024)
end
end
local lut555: buffer? = nil
local lut565: buffer? = nil
-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries
function Picture.rgb555(): buffer
local t = lut555
if t then
return t
end
local b = buffer.create(32768 * 4)
for v = 0, 32767 do
local r, g, bl = v // 1024, (v // 32) % 32, v % 32
r, g, bl = r * 8 + r // 4, g * 8 + g // 4, bl * 8 + bl // 4
writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000)
end
lut555 = b
return b
end
-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries
function Picture.rgb565(): buffer
local t = lut565
if t then
return t
end
local b = buffer.create(65536 * 4)
for v = 0, 65535 do
local r, g, bl = v // 2048, (v // 32) % 64, v % 32
r, g, bl = r * 8 + r // 4, g * 4 + g // 16, bl * 8 + bl // 4
writeu32(b, v * 4, r + g * 256 + bl * 65536 + 0xFF000000)
end
lut565 = b
return b
end
-- copy of a picture's plane (for decoders that read the previous picture while writing the next)
function Picture.clonePlane(p: Picture): buffer
local src = (p.idx or p.rgba) :: buffer
local c = buffer.create(buffer.len(src))
buffer.copy(c, 0, src, 0)
return c
end
local _ = readu32
return Picture
+276
View File
@@ -0,0 +1,276 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and
-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File
-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per
-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups).
-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its
-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames
-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read
-- and write is range-checked (a damaged frame stops where the damage is).
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local QtRle = {}
local function s8(v: number): number
return if v >= 128 then v - 256 else v
end
-- 1-bit: (skip, code) pairs; skip bit 7 = next line (the first one starts the first line)
local function decode1(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number)
row -= stride
local q = row
lines += 1
while lines > 0 do
if p + 2 > n then
return
end
local skip = readu8(d, p)
local code = s8(readu8(d, p + 1))
p += 2
if code == 0 then
return
end
if skip >= 128 then
lines -= 1
row += stride
q = row + 16 * (skip - 128)
else
q += 16 * skip
end
if q < 0 or q > limit then
return
end
if code ~= -1 then
if code < 0 then
local cnt = -code
if p + 2 > n or q + cnt * 16 > limit then
return
end
local a, b = readu8(d, p), readu8(d, p + 1)
p += 2
for _ = 1, cnt do
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(a, k), 1))
q += 1
end
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(b, k), 1))
q += 1
end
end
else
local cnt = code * 2
if p + cnt > n or q + cnt * 8 > limit then
return
end
for _ = 1, cnt do
local a = readu8(d, p)
p += 1
for k = 7, 0, -1 do
writeu8(px, q, band(rshift(a, k), 1))
q += 1
end
end
end
end
end
end
-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups
local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number)
local group = 32 // bpp -- pixels per 4 bytes
local per = 8 // bpp -- pixels per byte
local mask = 2 ^ bpp - 1
for _ = 1, lines do
if p >= n then
return
end
local q = row + group * (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
while true do
if p >= n then
return
end
local code = s8(readu8(d, p))
p += 1
if code == -1 then
break
end
if p >= n then
return
end
if code == 0 then
q += group * (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
elseif code < 0 then
local cnt = -code
if p + 4 > n or q + cnt * group > limit then
return
end
if bpp == 8 then
local v = readu32(d, p)
for _ = 1, cnt do
writeu32(px, q, v)
q += 4
end
else
local v0 = q
for b = 0, 3 do
local byte = readu8(d, p + b)
for k = per - 1, 0, -1 do
writeu8(px, q, band(rshift(byte, k * bpp), mask))
q += 1
end
end
for _ = 2, cnt do
buffer.copy(px, q, px, v0, group)
q += group
end
end
p += 4
else
local bytes = code * 4
if p + bytes > n or q + bytes * per > limit then
return
end
if bpp == 8 then
buffer.copy(px, q, d, p, bytes)
q += bytes
else
for b = 0, bytes - 1 do
local byte = readu8(d, p + b)
for k = per - 1, 0, -1 do
writeu8(px, q, band(rshift(byte, k * bpp), mask))
q += 1
end
end
end
p += bytes
end
end
row += stride
end
end
-- 16 / 24 / 32-bit: one pixel per group, into the rgba8 plane (stride in pixels)
local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, depth: number)
local bpp = depth // 8
local lut = if depth == 16 then Picture.rgb555() else nil
for _ = 1, lines do
if p >= n then
return
end
local q = row + (readu8(d, p) - 1)
p += 1
if q < 0 or q > limit then
return
end
while true do
if p >= n then
return
end
local code = s8(readu8(d, p))
p += 1
if code == -1 then
break
end
if p >= n then
return
end
if code == 0 then
q += readu8(d, p) - 1
p += 1
if q < 0 or q > limit then
return
end
else
local cnt = if code < 0 then -code else code
local need = if code < 0 then bpp else bpp * cnt
if p + need > n or q + cnt > limit then
return
end
for _ = 1, cnt do
local v
if lut then
v = readu32(lut, (readu8(d, p) * 256 + readu8(d, p + 1)) % 32768 * 4)
elseif bpp == 3 then
v = readu8(d, p) + readu8(d, p + 1) * 256 + readu8(d, p + 2) * 65536 + 0xFF000000
else
v = readu8(d, p + 1) + readu8(d, p + 2) * 256 + readu8(d, p + 3) * 65536 + readu8(d, p) * 16777216
end
writeu32(px, q * 4, v)
q += 1
if code > 0 then
p += bpp
end
end
if code < 0 then
p += bpp
end
end
end
row += stride
end
end
-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message
function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?)
local n = buffer.len(d)
if n < 8 then
return true, nil -- no change
end
local p = 4
local header = readu8(d, p) * 256 + readu8(d, p + 1)
p += 2
local h = pic.h
local start, lines = 0, h
if band(header, 8) ~= 0 then
if n < 14 then
return true, nil
end
start = readu8(d, p) * 256 + readu8(d, p + 1)
lines = readu8(d, p + 4) * 256 + readu8(d, p + 5)
p += 8
if lines > h - start then
return true, nil
end
end
local stride = pic.stride
local bits = if depth > 32 then depth - 32 else depth
local idx, rgba = pic.idx, pic.rgba
if idx and bits <= 8 then
local limit = stride * h
if bits == 1 then
decode1(idx, stride, limit, d, p, n, start * stride, lines)
else
decodeIdx(idx, stride, limit, d, p, n, start * stride, lines, bits)
end
elseif rgba and (bits == 16 or bits == 24 or bits == 32) then
decodeRgb(rgba, stride, stride * h, d, p, n, start * stride, lines, bits)
else
return false, "unsupported: depth " .. depth
end
return true, nil
end
-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs
function QtRle.palettised(depth: number): boolean
return depth <= 8 or depth > 32
end
function QtRle.pad(depth: number): number
local bits = if depth > 32 then depth - 32 else depth
return if bits <= 8 then 32 // math.max(1, bits) else 1
end
return QtRle
@@ -0,0 +1,405 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and
-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are
-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value);
-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte
-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a
-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header;
-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a
-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour).
-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads
-- 10 bits at a time through a lookup table into them.
-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give
-- zero bits, a frame whose codes run out of bits gives no picture.
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local Smacker = {}
local MAX_DEPTH8 = 27 -- 8-bit trees (3 x 9-bit lookups in the reference decoder)
local MAX_DEPTH16 = 500
-- block runs (TYPE code bits 2..7)
local RUNS = table.create(64, 0)
for i = 1, 59 do
RUNS[i] = i
end
RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048
-- a bit position over buf[0, nbits / 8)
export type Bits = { buf: buffer, pos: number, nbits: number }
function Smacker.bits(buf: buffer, offset: number, length: number): Bits
return { buf = buf, pos = offset * 8, nbits = (offset + length) * 8 }
end
local function bit(br: Bits): number
local p = br.pos
br.pos = p + 1
if p >= br.nbits then
return 0
end
return band(rshift(readu8(br.buf, rshift(p, 3)), band(p, 7)), 1)
end
Smacker.bit = bit
-- read(br, n) -> n bits (LSB first; zeros past the end)
function Smacker.read(br: Bits, n: number): number
local v, m = 0, 1
for _ = 1, n do
v += bit(br) * m
m *= 2
end
return v
end
local readBits = Smacker.read
-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups)
local function walk(tree: { number }, br: Bits): number
local i = 1
local e = tree[1]
while e < 0 do
if bit(br) == 1 then
i += -e - 1
end
i += 1
e = tree[i]
end
return e
end
Smacker.walk = walk
-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based)
local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?)
local vals: { number } = {}
local n = 0
local stack: { number } = {}
local state: { number } = {}
local sp = 0
while true do
if sp > maxDepth then
return nil, "tree too deep"
end
if n >= maxEntries then
return nil, "tree too big"
end
if bigChecks and br.pos >= br.nbits then
return nil, "truncated tree"
end
if bit(br) == 1 then
n += 1
vals[n] = -1
sp += 1
stack[sp], state[sp] = n, 0
else
local v, msg = leaf(n)
if not v then
return nil, msg
end
n += 1
vals[n] = v
local more = false
while sp > 0 do
if state[sp] == 0 then
local at = stack[sp]
vals[at] = -(n - at) - 1 -- the left subtree holds n - at entries
state[sp] = 1
more = true
break
end
sp -= 1
end
if not more then
return vals, nil
end
end
end
end
-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message
function Smacker.tree8(br: Bits): ({ number }?, string?)
local leaves = 0
return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?)
if leaves >= 256 then
return nil, "tree too big"
end
leaves += 1
if br.nbits - br.pos < 8 then
return nil, "truncated tree"
end
return readBits(br, 8), nil
end, false)
end
local tree8 = Smacker.tree8
export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based)
-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries)
local function bigTree(br: Bits, size: number): (BigTree?, string?)
if bit(br) == 0 then
return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0
end
local lohi: { { number } } = {}
for k = 1, 2 do
if bit(br) == 0 then
lohi[k] = { 0 }
else
local t, msg = tree8(br)
if not t then
return nil, msg
end
bit(br)
lohi[k] = t
end
end
local esc = { readBits(br, 16), readBits(br, 16), readBits(br, 16) }
local last = { -1, -1, -1 }
local lo, hi = lohi[1], lohi[2]
local vals, msg = build(br, MAX_DEPTH16, (size + 3) // 4, function(index: number): (number?, string?)
local v = walk(lo, br) + walk(hi, br) * 256
for k = 1, 3 do
if v == esc[k] then
last[k] = index + 1
return 0, nil
end
end
return v, nil
end, true)
if not vals then
return nil, msg
end
bit(br)
for k = 1, 3 do
if last[k] == -1 then
table.insert(vals, 0)
last[k] = #vals
end
end
return { vals = vals, last = last }, nil
end
export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree }
-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits
function Smacker.trees(config: buffer): (Trees?, string?)
local n = buffer.len(config)
if n <= 16 then
return nil, "no trees"
end
local br = Smacker.bits(config, 16, n - 16)
local out: { BigTree } = {}
local present = 0
for k = 1, 4 do
local size = buffer.readu32(config, (k - 1) * 4)
if size >= 2 ^ 28 then
return nil, "tree size too large"
end
local here = br.pos < br.nbits and band(rshift(readu8(config, rshift(br.pos, 3)), band(br.pos, 7)), 1) == 1
local t, msg = bigTree(br, size)
if not t then
return nil, msg
end
if here then
present += 1
end
out[k] = t
end
if present == 0 or br.pos > br.nbits then
return nil, "bad trees"
end
return { mmap = out[1], mclr = out[2], full = out[3], type = out[4] }, nil
end
local LUT_BITS = 10
-- the first LUT_BITS bits of a code -> (entry index * 32 + bits used): a leaf, or the node reached after LUT_BITS bits
local function lut(vals: { number }): buffer
local size = 2 ^ LUT_BITS
local t = buffer.create(size * 4)
for pat = 0, size - 1 do
local i, len = 1, 0
local e = vals[1]
while e < 0 and len < LUT_BITS do
if band(rshift(pat, len), 1) == 1 then
i += -e - 1
end
i += 1
len += 1
e = vals[i]
end
writeu32(t, pat * 4, i * 32 + len)
end
return t
end
local function reset(t: BigTree)
local vals, last = t.vals, t.last
vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0
end
-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4
function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?)
local px = pic.idx :: buffer
local stride = pic.stride
local mmap, mclr, full, typ = trees.mmap, trees.mclr, trees.full, trees.type
for _, t in { mmap, mclr, full, typ } do
reset(t)
if not t.lut then
t.lut = lut(t.vals)
end
end
local n = buffer.len(d)
local nbits = n * 8
local pos = 0
-- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree
local function code(t: BigTree): number
local vals = t.vals
local i, p
local byte = rshift(pos, 3)
if byte + 3 <= n then
local v = band(rshift(readu8(d, byte) + readu8(d, byte + 1) * 256 + readu8(d, byte + 2) * 65536, band(pos, 7)), 1023)
local ent = readu32(t.lut :: buffer, v * 4)
i = rshift(ent, 5)
p = pos + band(ent, 31)
else
i, p = 1, pos
end
local e = vals[i]
while e < 0 do
if p >= nbits then
return -1
end
if band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1) == 1 then
i += -e - 1
end
p += 1
i += 1
e = vals[i]
end
pos = p
local last = t.last
local l0 = last[1]
if e ~= vals[l0] then
local l1 = last[2]
vals[last[3]] = vals[l1]
vals[l1] = vals[l0]
vals[l0] = e
end
return e
end
local function bit(): number
local p = pos
pos = p + 1
if p >= nbits then
return 0
end
return band(rshift(readu8(d, rshift(p, 3)), band(p, 7)), 1)
end
local bw, bh = pic.w // 4, pic.h // 4
local blocks = bw * bh
local blk = 0
while blk < blocks do
local ty = code(typ)
if ty < 0 then
return false, "truncated frame"
end
local run = RUNS[band(rshift(ty, 2), 63) + 1]
local kind = band(ty, 3)
if kind == 2 then
blk = math.min(blocks, blk + run)
elseif kind == 3 then
local v = rshift(ty, 8) * 0x01010101
for _ = 1, run do
if blk >= blocks then
break
end
local o = (blk // bw) * stride * 4 + (blk % bw) * 4
writeu32(px, o, v)
writeu32(px, o + stride, v)
writeu32(px, o + 2 * stride, v)
writeu32(px, o + 3 * stride, v)
blk += 1
end
elseif kind == 0 then
for _ = 1, run do
if blk >= blocks then
break
end
local clr = code(mclr)
local map = code(mmap)
if clr < 0 or map < 0 then
return false, "truncated frame"
end
local hi, lo = rshift(clr, 8), band(clr, 255)
local o = (blk // bw) * stride * 4 + (blk % bw) * 4
for r = 0, 3 do
local q = o + r * stride
writeu8(px, q, if band(map, 1) ~= 0 then hi else lo)
writeu8(px, q + 1, if band(map, 2) ~= 0 then hi else lo)
writeu8(px, q + 2, if band(map, 4) ~= 0 then hi else lo)
writeu8(px, q + 3, if band(map, 8) ~= 0 then hi else lo)
map = rshift(map, 4)
end
blk += 1
end
else
local mode = 0
if v4 then
if pos >= nbits then
return false, "truncated frame"
end
if bit() == 1 then
mode = 1
elseif bit() == 1 then
mode = 2
end
end
for _ = 1, run do
if blk >= blocks then
break
end
local o = (blk // bw) * stride * 4 + (blk % bw) * 4
if mode == 0 then
for r = 0, 3 do
local a = code(full)
local b = code(full)
if a < 0 or b < 0 then
return false, "truncated frame"
end
-- the first code is the right pixel pair, the second the left one
writeu32(px, o + r * stride, b + a * 65536)
end
elseif mode == 1 then
for half = 0, 1 do
local a = code(full)
if a < 0 then
return false, "truncated frame"
end
local v = band(a, 255) * 0x0101 + rshift(a, 8) * 0x01010000
writeu32(px, o + half * 2 * stride, v)
writeu32(px, o + (half * 2 + 1) * stride, v)
end
else
for half = 0, 1 do
local p2 = code(full)
local p1 = code(full)
if p1 < 0 or p2 < 0 then
return false, "truncated frame"
end
local v = p1 + p2 * 65536
writeu32(px, o + half * 2 * stride, v)
writeu32(px, o + (half * 2 + 1) * stride, v)
end
end
blk += 1
end
end
end
return true, nil
end
return Smacker
+183
View File
@@ -0,0 +1,183 @@
--!strict
--!native
--!optimize 2
-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description
-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble
-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour
-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index:
-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc
-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row
-- above). Never throws: reads past the data give zeros, the block count bounds every write.
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
local band, rshift = bit32.band, bit32.rshift
local Smc = {}
-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames)
function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?)
local px = pic.idx :: buffer
local n = buffer.len(d)
local stride = pic.stride -- a multiple of 4: the plane holds whole blocks
local bh = pic.rows // 4
local total = ((pic.w + 3) // 4) * ((pic.h + 3) // 4)
if total // 1024 > n then
return false, "frame too small"
end
local blocksWide = (pic.w + 3) // 4
local p = 4 -- flags byte + 24-bit chunk size
-- block position: bx, by (blocks)
local bx, by = 0, 0
local pairI, quadI, octI = 0, 0, 0
-- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8)
local function u8(): number
if p < n then
local v = readu8(d, p)
p += 1
return v
end
return 0
end
local function advance()
bx += 1
if bx >= blocksWide then
bx = 0
by += 1
end
total -= 1
end
while total > 0 do
if p >= n then
return false, "truncated"
end
local op = readu8(d, p)
p += 1
local kind = rshift(op, 4)
local count: number
if kind < 8 then
count = if band(op, 0x10) ~= 0 then 1 + u8() else 1 + band(op, 15)
else
count = band(op, 15) + 1
end
if kind <= 1 then
for _ = 1, count do
if total <= 0 then
break
end
advance()
end
elseif kind <= 5 then
-- repeat the last block (2, 3) or the last pair of blocks (4, 5)
local pair = kind >= 4
local back = if pair then 2 else 1
local pos = by * blocksWide + bx
if pos < back then
return false, "repeat before any block"
end
local reps = if pair then count * 2 else count
local srcA = pos - back
local srcB = pos - 1
for k = 0, reps - 1 do
if total <= 0 or by >= bh then
break
end
local s = if pair and k % 2 == 1 then srcB else srcA
local sx, sy = (s % blocksWide) * 4, (s // blocksWide) * 4
local o, so = by * 4 * stride + bx * 4, sy * stride + sx
for r = 0, 3 do
writeu32(px, o + r * stride, readu32(px, so + r * stride))
end
advance()
end
elseif kind <= 7 then
local c = u8()
local v = c * 0x01010101
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
for r = 0, 3 do
writeu32(px, o + r * stride, v)
end
advance()
end
elseif kind <= 13 then
-- 2 / 4 / 8-colour blocks: a new colour group (even kinds) or one from the table (odd kinds)
local size = if kind <= 9 then 2 elseif kind <= 11 then 4 else 8
local base = if size == 2 then 0 elseif size == 4 then 512 else 1536
local entry: number
if kind % 2 == 0 then
local i = if size == 2 then pairI elseif size == 4 then quadI else octI
for k = 0, size - 1 do
writeu8(tables, base + i * size + k, u8())
end
entry = i
i = (i + 1) % 256
if size == 2 then
pairI = i
elseif size == 4 then
quadI = i
else
octI = i
end
else
entry = u8()
end
local t = base + entry * size
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
if size == 2 then
local f = u8() * 256 + u8()
for k = 0, 15 do
local bit = band(rshift(f, 15 - k), 1)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + bit))
end
elseif size == 4 then
local f = u8() * 16777216 + u8() * 65536 + u8() * 256 + u8()
for k = 0, 15 do
local i = band(rshift(f, 30 - 2 * k), 3)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i))
end
else
-- 6 bytes 01 23 45 67 89 AB -> rows 0-1 flags 012456, rows 2-3 flags 89A37B (3 bits per pixel)
local v1 = u8() * 256 + u8()
local v2 = u8() * 256 + u8()
local v3 = u8() * 256 + u8()
local fa = band(v1, 0xFFF0) * 256 + rshift(v2, 4)
local fb = band(v3, 0xFFF0) * 256 + band(v1, 15) * 256 + band(v2, 15) * 16 + band(v3, 15)
for k = 0, 15 do
local f = if k < 8 then fa else fb
local i = band(rshift(f, 21 - 3 * (k % 8)), 7)
writeu8(px, o + (k // 4) * stride + k % 4, readu8(tables, t + i))
end
end
advance()
end
else
-- 16-colour blocks
for _ = 1, count do
if total <= 0 or by >= bh then
break
end
local o = by * 4 * stride + bx * 4
for k = 0, 15 do
writeu8(px, o + (k // 4) * stride + k % 4, u8())
end
advance()
end
end
end
return true, nil
end
-- tables() -> the colour group scratch (pairs, quads, octets)
function Smc.tables(): buffer
return buffer.create(512 + 1024 + 2048)
end
return Smc
+214
View File
@@ -0,0 +1,214 @@
--!strict
-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk
-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak",
-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation
-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker
-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4).
-- New in rosetta, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's
-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns
-- a fresh copy.
--
-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the
-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that
-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth).
--
-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder
-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
--
-- Never throws: bad tracks return nil, Err; bad packets return Err from decode().
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local Flic = require("@rosetta/codecs/video/Legacy/Flic")
local Cinepak = require("@rosetta/codecs/video/Legacy/Cinepak")
local Msvideo1 = require("@rosetta/codecs/video/Legacy/Msvideo1")
local QtRle = require("@rosetta/codecs/video/Legacy/QtRle")
local Smc = require("@rosetta/codecs/video/Legacy/Smc")
local Smacker = require("@rosetta/codecs/video/Legacy/Smacker")
local Legacy = {}
Legacy.Picture = Picture
Legacy.Flic = Flic
Legacy.Cinepak = Cinepak
Legacy.Msvideo1 = Msvideo1
Legacy.QtRle = QtRle
Legacy.Smc = Smc
Legacy.Smacker = Smacker
Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
export type Options = {
maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26)
[string]: any,
}
-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err?
type Codec = {
make: (track: Types.Track) -> (any, string?),
step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?),
}
local function fail(msg: string?): Err.Err
return Err.from(msg or "corrupt frame")
end
local function packetPalette(pic: Picture.Picture, packet: Types.Packet): boolean
local pal = (packet :: any).palette
if type(pal) == "buffer" then
Picture.setPalette(pic, pal)
return true
end
return false
end
local CODECS: { [string]: Codec } = {
qtrle = {
make = function(t)
local depth = t.bitsPerPixel or 24
local bits = if depth > 32 then depth - 32 else depth
if not (bits == 1 or bits == 2 or bits == 4 or bits == 8 or bits == 16 or bits == 24 or bits == 32) then
return nil, "unsupported: depth " .. depth
end
return { pic = Picture.new(t.width :: number, t.height :: number, QtRle.palettised(depth), QtRle.pad(depth), 1, t.palette), depth = depth }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
local ok, msg = QtRle.decode(st.pic, data, st.depth)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
smc = {
make = function(t)
return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), tables = Smc.tables() }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
local ok, msg = Smc.decode(st.pic, data, st.tables)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
msvideo1 = {
make = function(t)
if (t.width :: number) < 4 or (t.height :: number) < 4 then
return nil, "smaller than one block"
end
local bits = if t.bitsPerPixel == 8 then 8 else 16
return { pic = Picture.new(t.width :: number, t.height :: number, bits == 8, 4, 4, t.palette), bits = bits }, nil
end,
step = function(st, data, packet)
if st.bits == 8 then
packetPalette(st.pic, packet)
end
local ok, msg = Msvideo1.decode(st.pic, data, st.bits)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
cinepak = {
make = function(t)
local pal = t.bitsPerPixel == 8
return { pic = Picture.new(t.width :: number, t.height :: number, pal, 4, 4, t.palette), cp = Cinepak.state() }, nil
end,
step = function(st, data, packet)
local newPal = st.pic.idx ~= nil and packetPalette(st.pic, packet)
local ok, msg = Cinepak.decode(st.pic, data, st.cp, newPal)
if not ok then
return nil, if msg then fail(msg) else nil
end
return Picture.image(st.pic), nil
end,
},
smackvid = {
make = function(t)
local cfg = t.config
if type(cfg) ~= "buffer" then
return nil, "no Smacker trees"
end
local trees, msg = Smacker.trees(cfg)
if not trees then
return nil, msg
end
return { pic = Picture.new(t.width :: number, t.height :: number, true, 4, 4, t.palette), trees = trees, v4 = t.codecTag == "SMK4" }, nil
end,
step = function(st, data, packet)
packetPalette(st.pic, packet)
if buffer.len(data) == 0 then
return nil, fail("empty frame")
end
local ok, msg = Smacker.decode(st.pic, data, st.trees, st.v4)
if not ok then
return nil, fail(msg)
end
return Picture.image(st.pic), nil
end,
},
flic = {
make = function(t)
return Flic.state(t.width :: number, t.height :: number, t.bitsPerPixel or 8)
end,
step = function(st, data, _packet)
local ok, msg = Flic.decode(st, data)
if not ok then
return nil, fail(msg)
end
return Flic.image(st), nil
end,
},
}
-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err
function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?)
local codec = CODECS[id]
if not codec then
return nil, Err.new(Err.UNSUPPORTED, "no legacy codec " .. tostring(id))
end
local w, h = track.width or 0, track.height or 0
if type(w) ~= "number" or type(h) ~= "number" or w <= 0 or h <= 0 or w ~= w // 1 or h ~= h // 1 then
return nil, Err.new(Err.CORRUPT, "video track without a valid size")
end
local max = (opts and opts.maxPixels) or 2 ^ 26
if w * h > max or w > 32768 or h > 32768 then
return nil, Err.new(Err.LIMIT, "picture of " .. w .. " x " .. h .. " over the limit")
end
local st, msg = codec.make(track)
if not st then
return nil, fail(msg)
end
-- Video.simpleDecoder, without requiring the registry (which requires this module)
local queue: { any } = {}
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, img, err = pcall(codec.step, st, packet.data, packet)
if not ok then
return Err.new(Err.CORRUPT, "decoder failed: " .. 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)
st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe)
end
return self :: any, nil
end
return Legacy
+11
View File
@@ -0,0 +1,11 @@
--!strict
-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder
-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame /
-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2.
local Mpeg2 = require("@rosetta/codecs/video/Mpeg2")
export type Frame = Mpeg2.Frame
export type Options = Mpeg2.Options
export type Decoder = Mpeg2.Decoder
return Mpeg2
File diff suppressed because it is too large. Load diff
+138
View File
@@ -0,0 +1,138 @@
--!strict
-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those 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 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the
-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7.
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_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,
}
-- dct_dc_size_luminance / chrominance (Tables B-12 / B-13, sizes 0..11): { code, length } per size
T.DC_SIZE_LUMA = { { 4, 3 }, { 0, 2 }, { 1, 2 }, { 5, 3 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 511, 9 } }
T.DC_SIZE_CHROMA = { { 0, 2 }, { 1, 2 }, { 2, 2 }, { 6, 3 }, { 14, 4 }, { 30, 5 }, { 62, 6 }, { 126, 7 }, { 254, 8 }, { 510, 9 }, { 1022, 10 }, { 1023, 10 } }
-- Table B-15 (intra_vlc_format = 1), ISO/IEC 13818-2: { code, length, run * 256 + level } (the sign bit follows)
T.DCT_COEFF_B15 = {
2,2,1, 6,3,2, 7,4,3, 28,5,4, 29,5,5, 5,6,6, 4,6,7, 123,7,8,
124,7,9, 35,8,10, 34,8,11, 250,8,12, 251,8,13, 254,8,14, 255,8,15, 31,14,16,
30,14,17, 29,14,18, 28,14,19, 27,14,20, 26,14,21, 25,14,22, 24,14,23, 23,14,24,
22,14,25, 21,14,26, 20,14,27, 19,14,28, 18,14,29, 17,14,30, 16,14,31, 24,15,32,
23,15,33, 22,15,34, 21,15,35, 20,15,36, 19,15,37, 18,15,38, 17,15,39, 16,15,40,
2,3,257, 6,5,258, 121,7,259, 39,8,260, 32,8,261, 22,13,262, 21,13,263, 31,15,264,
30,15,265, 29,15,266, 28,15,267, 27,15,268, 26,15,269, 25,15,270, 19,16,271, 18,16,272,
17,16,273, 16,16,274, 5,5,513, 7,7,514, 252,8,515, 12,10,516, 20,13,517, 7,5,769,
38,8,770, 28,12,771, 19,13,772, 6,6,1025, 253,8,1026, 18,12,1027, 7,6,1281, 4,9,1282,
18,13,1283, 6,7,1537, 30,12,1538, 20,16,1539, 4,7,1793, 21,12,1794, 5,7,2049, 17,12,2050,
120,7,2305, 17,13,2306, 122,7,2561, 16,13,2562, 33,8,2817, 26,16,2818, 37,8,3073, 25,16,3074,
36,8,3329, 24,16,3330, 5,9,3585, 23,16,3586, 7,9,3841, 22,16,3842, 13,10,4097, 21,16,4098,
31,12,4353, 26,12,4609, 25,12,4865, 23,12,5121, 22,12,5377, 31,13,5633, 30,13,5889, 29,13,6145,
28,13,6401, 27,13,6657, 31,16,6913, 30,16,7169, 29,16,7425, 28,16,7681, 27,16,7937,
}
-- quantiser_scale for q_scale_type = 1 (Table 7-6), indexed by quantiser_scale_code
T.NON_LINEAR_QSCALE = { [0] = 0,
1, 2, 3, 4, 5, 6, 7, 8, 10, 12, 14, 16, 18, 20, 22, 24, 28, 32, 36, 40, 44, 48, 52, 56, 64, 72, 80, 88, 96, 104, 112,
}
-- the alternate scan (Figure 7-3): scan index -> natural position
T.ALTERNATE_SCAN = { [0] = 0,
8, 16, 24, 1, 9, 2, 10, 17, 25, 32, 40, 48, 56, 57, 49, 41, 33, 26, 18, 3, 11, 4, 12, 19, 27, 34, 42, 50, 58,
35, 43, 51, 59, 20, 28, 5, 13, 6, 14, 21, 29, 36, 44, 52, 60, 37, 45, 53, 61, 22, 30, 7, 15, 23, 31, 38, 46,
54, 62, 39, 47, 55, 63,
}
return T
+144
View File
@@ -0,0 +1,144 @@
--!strict
-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (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. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA /
-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees);
-- the MPEG-2 tables are built from code lists.
local T = require("@rosetta/codecs/video/Mpeg2/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 flatLeaves(ls: { Leaf }): (buffer, number)
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
local function flat(tree: { [number]: number }): (buffer, number)
return flatLeaves(leaves(tree))
end
-- { { code, length } } indexed from 1 -> leaves with value = index - 1
local function codeLeaves(codes: { { number } }): { Leaf }
local out: { Leaf } = {}
for i, c in codes do
table.insert(out, { code = c[1], len = c[2], value = i - 1 })
end
return out
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)
do
-- MPEG-2 adds "0000 0000 1" = 0 (Table B-9: a 4:2:2 macroblock whose coded blocks are all in the extra chroma
-- pattern bits)
local ls = leaves(T.CODE_BLOCK_PATTERN)
table.insert(ls, { code = 1, len = 9, value = 0 })
V.CBP, V.CBP_BITS = flatLeaves(ls)
end
V.MOTION, V.MOTION_BITS = flat(T.MOTION)
V.DC_LUMA, V.DC_LUMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_LUMA))
V.DC_CHROMA, V.DC_CHROMA_BITS = flatLeaves(codeLeaves(T.DC_SIZE_CHROMA))
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
do
local ls: { Leaf } = { { code = 1, len = 6, value = V.ESC }, { code = 6, len = 4, value = V.EOB } }
local b = T.DCT_COEFF_B15
for i = 1, #b, 3 do
table.insert(ls, { code = b[i], len = b[i + 1], value = b[i + 2] })
end
V.DCT_B15 = twoLevel(ls)
end
return V
+414
View File
@@ -0,0 +1,414 @@
--!strict
-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I /
-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes
-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from
-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this
-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines);
-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded.
-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
--
-- local dec = Mpeg2.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg2.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, chroma, ... }
-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2)
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@rosetta/Types")
local Err = require("@rosetta/core/Err")
local D = require("@rosetta/codecs/video/Mpeg2/Decoder")
local Mpeg2 = {}
Mpeg2.PICTURE_I = 1
Mpeg2.PICTURE_P = 2
Mpeg2.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 planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride
-- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2)
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
chroma: number, -- 1 = 4:2:0, 2 = 4:2:2
mpeg2: boolean,
progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true)
fields: boolean, -- coded as two field pictures
topFieldFirst: boolean,
repeatFirstField: boolean,
clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated)
concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed)
}
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)
-- a cooperative yield point, run after every slice and every 16 rows of colour conversion: e.g. a function that
-- calls coroutine.yield() when a time budget is spent, to spread a picture over several frames (the decode call
-- then runs inside a coroutine). Don't call this decoder again while a decode is suspended. Errors in it are
-- ignored. See dec:setYield.
yield: (() -> ())?,
}
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 Mpeg2.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local core = D.new(o.maxPixels)
if type(o.yield) == "function" then
core.setYield(o.yield)
end
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,
chroma = s.chroma,
mpeg2 = s.mpeg2,
progressive = s.progressive,
fields = s.fields,
topFieldFirst = s.tff,
repeatFirstField = s.rff,
clamped = s.clamped,
concealed = s.concealed,
}
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
-- Sets (or clears, nil) the cooperative yield hook (Options.yield).
function Decoder.setYield(self: Decoder, hook: (() -> ())?)
self._core.setYield(if type(hook) == "function" then hook else 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
-- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a
-- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes.
-- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in
-- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 ..
-- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows.
-- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many
-- rows as its luma; use frameImage(frame, true) for those.)
function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean
if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then
return false
end
local cw, w, h = tonumber(codedWidth), tonumber(width), tonumber(height)
if not cw or not w or not h or cw % 2 ~= 0 or w < 1 or h < 1 or w > cw or cw ~= math.floor(cw) or w ~= math.floor(w) or h ~= math.floor(h) then
return false
end
local r0 = math.floor(tonumber(row0) or 0)
r0 -= r0 % 2
local r1 = math.floor(tonumber(row1) or h)
local pr = math.floor(tonumber(planeRow0) or 0)
local oo = math.floor(tonumber(outOffset) or 0)
if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then
return false
end
-- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band
local lumaRows = r1 - pr
local chromaRows = (r1 + 1) // 2 - pr // 2
if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then
return false
end
if buffer.len(out) < oo + (r1 - r0) * w * 4 then
return false
end
-- rows relative to the planes' first row
D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil)
return true
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"; 4:2:2 chroma
-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for
-- a value that is not a Frame.
function Mpeg2.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 c422 = frame.chroma == 2
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
local crows = if c422 then h else oh
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
if c422 then
D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
end
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
if not c422 then
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
else
-- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field
-- (4k + j and 4k + j + 2), so the fields do not mix
local inter = not frame.progressive
for y = 0, oh - 1 do
local a, b
if inter then
local base = (y // 2) * 4 + y % 2
a, b = base, base + 2
else
a, b = 2 * y, 2 * y + 1
end
if b >= h then
b = a
end
for x = 0, ow - 1 do
buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2)
buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2)
end
end
end
end
img.meta.source = {
format = if frame.mpeg2 then "mpeg2" else "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
chroma = if c422 then "422" else "420",
interlaced = not frame.progressive,
topFieldFirst = frame.topFieldFirst,
range = if rgba then nil else "limited",
}
return img
end
-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder
-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in
-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of
-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream).
function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
local function push(f: Frame)
local img = Mpeg2.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 tag = { packet.pts }
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag)
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
while f do -- more pictures in the packet
push(f)
f = dec:decode(packet.data, 0, 0, tag)
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, 8 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
return Mpeg2
File diff suppressed because it is too large. Load diff
+370
View File
@@ -0,0 +1,370 @@
--!strict
-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame /
-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis
-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the
-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman
-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause:
-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking;
-- the table layout here is simpler). Never throws: bad headers return nil, message.
local Bits = require("@rosetta/core/Bits")
local H = {}
export type Info = {
versionMajor: number,
versionMinor: number,
versionSub: number,
frameWidth: number, -- coded frame size (multiples of 16)
frameHeight: number,
picWidth: number, -- the picture region (the displayed part)
picHeight: number,
picX: number, -- from the left
picY: number, -- from the bottom, as stored
fpsNum: number,
fpsDen: number,
aspectNum: number,
aspectDen: number,
colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG
bitrate: number,
quality: number,
granuleShift: number,
pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved)
}
export type Setup = {
lflim: { number }, -- [qi + 1]: loop filter limit
dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora
huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable)
roots: { number }, -- [table + 1]: the root node offset in huff
}
-- the zig-zag scan: natural index of the coefficient at scan position zzi
H.ZIGZAG = {
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,
}
local function ilog(v: number): number
local n = 0
while v > 0 do
n += 1
v = v // 2
end
return n
end
-- ------------------------------------------------------------------------------------------------ identification
-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora"
function H.info(b: buffer, off: number, len: number): (Info?, string?)
if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora identification header"
end
local br = Bits.msbReader(b, off + 7, len - 7)
local info: Info = {
versionMajor = br:read(8),
versionMinor = br:read(8),
versionSub = br:read(8),
frameWidth = br:read(16) * 16,
frameHeight = br:read(16) * 16,
picWidth = br:read(24),
picHeight = br:read(24),
picX = br:read(8),
picY = br:read(8),
fpsNum = br:read(32),
fpsDen = br:read(32),
aspectNum = br:read(24),
aspectDen = br:read(24),
colorspace = br:read(8),
bitrate = br:read(24),
quality = br:read(6),
granuleShift = br:read(5),
pixelFormat = br:read(2),
}
local reserved = br:read(3)
if br.err then
return nil, "truncated identification header"
end
if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then
return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor
end
if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then
return nil, "bad frame / picture size"
end
if info.fpsNum == 0 or info.fpsDen == 0 then
return nil, "bad frame rate"
end
if info.pixelFormat == 1 or reserved ~= 0 then
return nil, "reserved pixel format"
end
return info, nil
end
-- ------------------------------------------------------------------------------------------------ comment
-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora"
function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, nil, "not a Theora comment header"
end
local p, e = off + 7, off + len
local function str(): string?
if p + 4 > e then
return nil
end
local n = buffer.readu32(b, p)
p += 4
if n > e - p then
return nil
end
local s = buffer.readstring(b, p, n)
p += n
return s
end
local vendor = str()
if not vendor or p + 4 > e then
return nil, nil, "truncated comment header"
end
local count = buffer.readu32(b, p)
p += 4
if count * 4 > e - p then
return nil, nil, "bad comment count"
end
local list: { string } = {}
for _ = 1, count do
local s = str()
if not s then
return nil, nil, "truncated comment header"
end
table.insert(list, s)
end
return vendor, list, nil
end
-- ------------------------------------------------------------------------------------------------ Huffman trees
-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in
-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf
-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits).
local MAXBITS = 8
local function readTree(br: any): ({ number }?, { number }?, { number }?)
-- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root)
local kid0, kid1, tok = { 0 }, { 0 }, { -1 }
-- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length
local code, len, nleaves = 0, 0, 0
while true do
local bit = br:read(1)
if br.err then
return nil, nil, nil
end
if bit == 0 then
len += 1
if len > 32 then
return nil, nil, nil
end
else
nleaves += 1
if nleaves > 32 then
return nil, nil, nil
end
local t = br:read(5)
-- insert the leaf
local n = 1
for d = 1, len do
local k = (code // 2 ^ (32 - d)) % 2
local kids = if k == 0 then kid0 else kid1
local nx = kids[n]
if nx == 0 then
nx = #tok + 1
kid0[nx], kid1[nx], tok[nx] = 0, 0, -1
kids[n] = nx
end
n = nx
end
tok[n] = t
if len <= 0 then
break
end
-- the next codeword: clear the trailing 1 bits, then set the last 0 bit
local cb = 2 ^ (32 - len)
while len > 0 and (code // cb) % 2 == 1 do
code -= cb
cb *= 2
len -= 1
end
if len <= 0 then
break
end
code += cb
end
end
return kid0, kid1, tok
end
local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number
local heights: { [number]: number } = {}
local function height(n: number): number
local h = heights[n]
if h then
return h
end
h = 0
if tok[n] < 0 then
local a = if kid0[n] ~= 0 then height(kid0[n]) else 0
local c = if kid1[n] ~= 0 then height(kid1[n]) else 0
h = 1 + math.max(a, c)
end
heights[n] = h
return h
end
local function node(n: number): number
local nb = math.clamp(height(n), 1, MAXBITS)
local off = #out + 1
out[off] = nb
local size = 2 ^ nb
for i = 1, size do
out[off + i] = 0
end
for i = 0, size - 1 do
local cur, d = n, 0
while d < nb and tok[cur] < 0 do
local bit = bit32.extract(i, nb - 1 - d, 1)
local nx = if bit == 0 then kid0[cur] else kid1[cur]
d += 1
cur = nx
if nx == 0 then
break
end
end
if cur == 0 then
out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0
elseif tok[cur] >= 0 then
out[off + 1 + i] = d * 64 + tok[cur]
else
out[off + 1 + i] = -node(cur)
end
end
return off
end
return node(1)
end
-- ------------------------------------------------------------------------------------------------ setup
local DC_MIN = { 16, 32 }
local AC_MIN = { 8, 16 }
-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora"
function H.setup(b: buffer, off: number, len: number): (Setup?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora setup header"
end
local br = Bits.msbReader(b, off + 7, len - 7)
-- loop filter limits, AC / DC scales
local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0)
local nb = br:read(3)
for qi = 1, 64 do
lflim[qi] = br:read(nb)
end
nb = br:read(4) + 1
for qi = 1, 64 do
acScale[qi] = br:read(nb)
end
nb = br:read(4) + 1
for qi = 1, 64 do
dcScale[qi] = br:read(nb)
end
local nbms = br:read(9) + 1
local bms: { { number } } = {}
for m = 1, nbms do
local mat = table.create(64, 0)
for ci = 1, 64 do
mat[ci] = br:read(8)
end
bms[m] = mat
end
if br.err then
return nil, "truncated setup header"
end
-- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based)
local ranges: { { sizes: { number }, idx: { number } } } = {}
local mb = ilog(nbms - 1)
for i = 0, 5 do
local qti, pli = i // 3, i % 3
local copy = false
if i > 0 and br:read(1) == 0 then
copy = true
local from = i - 1
if qti > 0 and br:read(1) == 1 then
from = pli -- the same plane of the intra set
end
ranges[i + 1] = ranges[from + 1]
end
if not copy then
local sizes, idx = {}, { br:read(mb) }
local qi = 0
while qi < 63 do
local s = br:read(ilog(62 - qi)) + 1
table.insert(sizes, s)
qi += s
table.insert(idx, br:read(mb))
end
if qi > 63 then
return nil, "bad quant ranges"
end
for _, m in idx do
if m >= nbms then
return nil, "bad base matrix index"
end
end
ranges[i + 1] = { sizes = sizes, idx = idx }
end
end
if br.err then
return nil, "truncated setup header"
end
-- the dequantisation tables (oc_dequant_tables_init)
local dequant = buffer.create(64 * 6 * 64 * 2)
local base = table.create(64, 0)
for qti = 0, 1 do
for pli = 0, 2 do
local r = ranges[qti * 3 + pli + 1]
local qi = 0
for qri = 0, #r.sizes do
local m0 = bms[r.idx[qri + 1] + 1]
table.move(m0, 1, 64, 1, base)
local qiStart = qi
local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1]
while true do
local o = ((qi * 3 + pli) * 2 + qti) * 64
local q = (dcScale[qi + 1] * base[1] // 100) * 4
buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096))
for zzi = 1, 63 do
q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4
buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096))
end
qi += 1
if qi >= qiEnd then
break
end
-- interpolate the next base matrix
local m1 = bms[r.idx[qri + 2] + 1]
local sz = r.sizes[qri + 1]
for ci = 1, 64 do
base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz)
end
end
end
end
end
-- the 80 Huffman trees
local huff: { number } = {}
local roots: { number } = {}
for t = 1, 80 do
local k0, k1, tk = readTree(br)
if not k0 or not k1 or not tk then
return nil, "bad Huffman tree " .. (t - 1)
end
roots[t] = buildTable(huff, k0, k1, tk)
end
return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil
end
return H
+289
View File
@@ -0,0 +1,289 @@
--!strict
-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau
-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames).
-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV
-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes,
-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau);
-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout).
-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too).
--
-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate
-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err
-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region
-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down
-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position
--
-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture).
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
local Header = require("@rosetta/codecs/video/Theora/Header")
local Decoder = require("@rosetta/codecs/video/Theora/Decoder")
local Theora = {}
export type Info = Header.Info
export type Options = {
maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304)
}
local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" }
-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil
function Theora.isHeader(b: buffer, off: number?, len: number?): number?
local o = off or 0
local n = len or (buffer.len(b) - o)
if n < 7 then
return nil
end
local t = buffer.readu8(b, o)
if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then
return t - 0x7F
end
return nil
end
-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil)
function Theora.splitConfig(c: buffer): { buffer }?
local n = buffer.len(c)
if n < 3 or buffer.readu8(c, 0) ~= 2 then
return nil
end
local p, lens = 1, {}
for k = 1, 2 do
local size = 0
repeat
if p >= n then
return nil
end
local b = buffer.readu8(c, p)
size += b
p += 1
until b < 255
lens[k] = size
end
lens[3] = n - p - lens[1] - lens[2]
if lens[3] < 0 then
return nil
end
local out = {}
for k = 1, 3 do
out[k] = buffer.create(lens[k])
buffer.copy(out[k], 0, c, p, lens[k])
p += lens[k]
end
return out
end
-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err
function Theora.info(h: buffer): (Header.Info?, Err.Err?)
local ok, info, err = pcall(Header.info, h, 0, buffer.len(h))
if not ok or not info then
return nil, Err.from(if ok then err else tostring(info))
end
return info, nil
end
-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err
function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?)
local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h))
if not ok or not vendor or not list then
return nil, nil, nil, Err.from(if ok then err else tostring(vendor))
end
return vendor, list, (VorbisComment.tags(list)), nil
end
-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none)
function Theora.granuleFrame(info: Header.Info, g: number): number
if g < 0 then
return -1
end
local shift = 2 ^ info.granuleShift
local key = g // shift
local f = key + g % shift
-- since bitstream 3.2.1 the first frame is granule 1
local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub
if v >= 0x030201 then
f -= 1
end
return f
end
-- ------------------------------------------------------------------------------------------------ decoder
local Dec = {}
Dec.__index = Dec
export type TheoraDecoder = typeof(setmetatable(
{} :: {
info: Header.Info,
vendor: string,
comments: { string },
tags: { [string]: string },
width: number, -- the picture region
height: number,
frameRate: number,
pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p"
aspect: number, -- pixel aspect ratio (1 when unknown)
frames: number, -- packets decoded (dupes included)
_st: Decoder.State,
_any: boolean, -- a frame was decoded
},
Dec
))
-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config
function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?)
local list: { buffer }? = nil
if type(headers) == "buffer" then
list = Theora.splitConfig(headers)
elseif type(headers) == "table" then
list = headers
end
if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then
return nil, Err.new(Err.CORRUPT, "missing Theora headers")
end
local info, ierr = Theora.info(list[1])
if not info then
return nil, ierr
end
local maxPixels = opts and opts.maxPixels or 4096 * 2304
if info.frameWidth * info.frameHeight > maxPixels then
return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels")
end
local vendor, comments, tags, cerr = Theora.comment(list[2])
if not vendor or not comments or not tags then
return nil, cerr
end
local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3]))
if not ok3 or not setup then
return nil, Err.from(if ok3 then serr else tostring(setup))
end
local st = Decoder.new(info, setup)
return setmetatable({
info = info,
vendor = vendor,
comments = comments,
tags = tags,
width = info.picWidth,
height = info.picHeight,
frameRate = info.fpsNum / info.fpsDen,
pixelFormat = PIXEL_FORMATS[info.pixelFormat],
aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1,
frames = 0,
_st = st,
_any = false,
}, Dec), nil
end
-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil).
function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?)
local o = off or 0
local n = len or (buffer.len(data) - o)
if o < 0 or n < 0 or o + n > buffer.len(data) then
return nil, Err.new(Err.ARG, "decode: range outside the buffer")
end
if n > 0 and buffer.readu8(data, o) >= 0x80 then
return nil, nil
end
local kind, msg = Decoder.decode(self._st, data, o, n)
if not kind then
return nil, Err.from(msg)
end
self.frames += 1
if kind ~= "dup" then
self._any = true
end
return kind, nil
end
-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data)
function Dec.reset(self: TheoraDecoder)
local st = self._st
st.shown = st.prev
end
local function window(self: TheoraDecoder): (number, number, number, number)
local info = self.info
-- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom)
return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight
end
-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width,
-- chroma height
function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number)
local st = self._st
local x0, y0, w, h = window(self)
local hd, vd = st.hdec, st.vdec
local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd
local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd
cw = math.min(cw, st.pw[2] - cx0)
ch = math.min(ch, st.ph[2] - cy0)
return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch
end
-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down)
function Dec.image(self: TheoraDecoder): Types.Image
local y, u, v, cw, ch = self:planes()
local w, h = self.width, self.height
local img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
local ow, oh = (w + 1) // 2, (h + 1) // 2
buffer.copy(px, 0, y, 0, w * h)
local st = self._st
if st.hdec == 1 and st.vdec == 1 then
for r = 0, oh - 1 do
local sr = math.min(r, ch - 1)
buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw))
buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw))
end
else
Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh)
Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh)
end
img.meta.yuv = { range = "limited", matrix = "bt601" }
img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace }
return img
end
-- ------------------------------------------------------------------------------------------------ registry
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config
-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat
function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
if not track.config then
return nil, Err.new(Err.CORRUPT, "Theora track without its headers")
end
local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels })
if not dec then
return nil, err
end
local d = dec :: TheoraDecoder
local pending: { any } = {}
local self: any = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local kind, e = d:decode(packet.data)
if not kind then
return e
end
if d._any then
table.insert(pending, { d:image(), packet.pts, kind == "key" })
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local p = table.remove(pending, 1)
if not p then
return nil, nil, nil
end
return p[1], p[2], p[3]
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(pending)
d:reset()
end
return self, nil
end
return Theora
+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 rosetta.
--
-- 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("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Yuv = require("@rosetta/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("@rosetta/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
+601
View File
@@ -0,0 +1,601 @@
--!strict
-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta.
--
-- 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("@rosetta/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("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Yuv = require("@rosetta/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("@rosetta/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("@rosetta/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("@rosetta/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 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display
local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Mpeg2 = require("@rosetta/codecs/video/Mpeg2")
return Mpeg2.newVideoDecoder(track, opts)
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("@rosetta/codecs/video/H264")
return H264.newVideoDecoder(track, opts)
end
-- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering
local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local H263 = require("@rosetta/codecs/video/H263")
local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels })
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
return dec:image(data)
end, function()
dec:reset()
end), nil
end
-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv
-- builds the same); one picture per packet, empty packets repeat the previous one
local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Theora = require("@rosetta/codecs/video/Theora")
return Theora.newVideoDecoder(track, opts)
end
-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy)
local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?)
return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
return require("@rosetta/codecs/video/Legacy").newDecoder(id, track, opts)
end
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 = mpeg2Decoder },
{ 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", "hdv1", "hdv2", "hdv3", "hdv5", "hdv6", "hdv7", "hdv8", "hdv9", "hdva", "xdv1", "xdv2", "xdv3", "xdv4", "xdv5", "xdv6", "xdv7", "xdv8", "xdv9", "xdva", "xdvb", "xdvc", "xdvd", "xdve", "xdvf", "xd54", "xd55", "xd59", "xd5a", "xd5b", "xd5c", "xd5d", "xd5e", "xd5f", "xdhd", "xdh2", "AVmp", "mx3n", "mx3p", "mx4n", "mx4p", "mx5n", "mx5p", "mmes", "MMES", "M701", "M702", "M703", "M704", "M705", "mpgv", "m2v1", "M2V1" }, matroska = { "V_MPEG2" }, new = mpeg2Decoder },
{ 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" }, new = theoraDecoder },
{ id = "h263", name = "H.263", fourcc = { "H263", "h263", "s263", "U263" }, new = h263Decoder },
{ id = "flv1", name = "Sorenson Spark (FLV1)", fourcc = { "FLV1" }, new = h263Decoder },
{ id = "vp6f", name = "On2 VP6 (Flash)", fourcc = { "VP6F", "FLV4" } },
{ id = "vp6a", name = "On2 VP6 with alpha (Flash)", fourcc = { "VP6A" } },
{ id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } },
{ id = "flashsv2", name = "Flash Screen Video 2" },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
-- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette)
{ id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") },
{ id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") },
{ id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") },
{ id = "smc", name = "QuickTime Graphics (SMC)", fourcc = { "smc " }, new = legacyDecoder("smc") },
{ id = "flic", name = "Autodesk Animator FLIC", fourcc = { "AFLC" }, new = legacyDecoder("flic") },
{ id = "smackvid", name = "Smacker video", fourcc = { "SMK2", "SMK4" }, new = legacyDecoder("smackvid") },
}
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
-- shrink yuv420p frames so the longer side is at most this many pixels (aspect kept; bilinear, Yuv.scale), before
-- any rgba conversion. v.width / v.height stay the source size; frame.image has the output size. Default: none
maxSide: number?,
-- passed to codecs that support a cooperative yield point (H.264: codecs/video/H264 Options.yield)
yield: (() -> ())?,
[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
if index < 0 then
-- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps);
-- without a frame rate, counted from the seek)
index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0
end
index += 1
local d = defaultDur
if lastPts and t > (lastPts :: number) and defaultDur == 0 then
d = t - (lastPts :: number)
end
lastPts = t
local maxSide = o.maxSide
if maxSide and maxSide >= 1 and img.format == "yuv420p" and math.max(img.width, img.height) > maxSide then
local hook: any = o.yield
if hook then
pcall(hook)
end
local s = maxSide / math.max(img.width, img.height)
img = Yuv.imageScale(img, math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5)))
end
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
index = -1 -- recomputed from the first frame's time
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