merge ws/video2

This commit is contained in:
4DBug committed 2026-10-31 15:31:56 -05:00
commit c5f27770fc
63 files changed
+12207 -1509

No files matched your search

+714
View File
@@ -0,0 +1,714 @@
--!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.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
-- 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
@@ -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("@formats/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("@formats/Types")
local Picture = require("@formats/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("@formats/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 formats-luau.
local Types = require("@formats/Types")
local Pixels = require("@formats/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("@formats/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("@formats/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("@formats/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 formats-luau, 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("@formats/core/Err")
local Types = require("@formats/Types")
local Picture = require("@formats/codecs/video/Legacy/Picture")
local Flic = require("@formats/codecs/video/Legacy/Flic")
local Cinepak = require("@formats/codecs/video/Legacy/Cinepak")
local Msvideo1 = require("@formats/codecs/video/Legacy/Msvideo1")
local QtRle = require("@formats/codecs/video/Legacy/QtRle")
local Smc = require("@formats/codecs/video/Legacy/Smc")
local Smacker = require("@formats/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
File diff suppressed because it is too large. Load diff
+8 -259
View File
@@ -1,262 +1,11 @@
--!strict
-- codecs/video/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from
-- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures,
-- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage.
-- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom
-- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display
-- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau).
-- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding.
--
-- local dec = Mpeg1.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg1.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, pictureType, ... }
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@formats/Types")
local D = require("@formats/codecs/video/Mpeg1/Decoder")
-- 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("@formats/codecs/video/Mpeg2")
local Mpeg1 = {}
export type Frame = Mpeg2.Frame
export type Options = Mpeg2.Options
export type Decoder = Mpeg2.Decoder
Mpeg1.PICTURE_I = 1
Mpeg1.PICTURE_P = 2
Mpeg1.PICTURE_B = 3
export type Frame = {
width: number,
height: number,
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based)
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
-- the decoded YCbCr 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth,
-- chroma stride codedWidth / 2
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
}
export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
-- display order for streams without B-frames.
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
_core: D.Core,
_reorder: boolean,
_rgba: boolean,
_held: D.Store?,
_pixels: buffer?,
_count: number,
width: number,
height: number,
frameRate: number,
bitRate: number,
stats: { pictures: number, errors: number, skipped: number },
},
Decoder
))
function Mpeg1.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local core = D.new(o.maxPixels)
return setmetatable({
_core = core,
_reorder = o.reorder == true,
_rgba = o.rgba ~= false,
_held = nil,
_pixels = nil,
_count = 0,
width = 0,
height = 0,
frameRate = 0,
bitRate = 0,
stats = { pictures = 0, errors = 0, skipped = 0 },
}, Decoder)
end
local function emit(self: Decoder, s: D.Store): Frame
local core = self._core
local pixels: buffer? = nil
if self._rgba then
local need = s.w * s.h * 4
local px = self._pixels
if px == nil or buffer.len(px) ~= need then
px = buffer.create(need)
self._pixels = px
end
core.toRgba(s, px :: buffer)
pixels = px
end
self._count += 1
return {
width = s.w,
height = s.h,
pixels = pixels,
pictureType = s.ptype,
temporalReference = s.tref,
index = self._count,
tag = s.tag,
y = s.y,
cb = s.cb,
cr = s.cr,
codedWidth = s.cw,
}
end
local function sync(self: Decoder)
local st = self._core.state
self.width = st.width
self.height = st.height
self.frameRate = st.frameRate
self.bitRate = st.bitRate
self.stats.pictures = st.pictures
self.stats.errors = st.errors
self.stats.skipped = st.skipped
end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s)
end
local prev = self._held
self._held = s
if prev then
return emit(self, prev)
end
return nil
end
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
local core = self._core
while true do
local s, needData = core.nextPicture(atEnd, tag)
sync(self)
if s then
local f = handle(self, s)
if f then
return f
end
elseif needData then
return nil
end
end
end
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
src = buffer.fromstring(data)
elseif type(data) == "buffer" then
src = data
else
return false
end
local total = buffer.len(src)
local off = math.floor(tonumber(offset) or 0)
if off < 0 or off > total then
return false
end
local n = math.floor(tonumber(len) or (total - off))
if n < 0 or off + n > total then
return false
end
self._core.write(src, off, n)
return true
end
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then
return nil
end
return run(self, true, tag)
end
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
-- for reordering. Call until it returns nil.
function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil)
if f then
return f
end
local held = self._held
if held then
self._held = nil
return emit(self, held)
end
return nil
end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"), or rgba8
-- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame.
function Mpeg1.frameImage(frame: Frame, rgba: boolean?): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil
end
local w, h, cw = frame.width, frame.height, frame.codedWidth
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
return nil
end
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
for y = 0, h - 1 do
buffer.copy(px, y * w, frame.y, y * cw, w)
end
local o = w * h
for y = 0, oh - 1 do
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
end
end
img.meta.source = {
format = "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
range = if rgba then nil else "limited",
}
return img
end
return Mpeg1
return Mpeg2
File diff suppressed because it is too large. Load diff
@@ -1,7 +1,8 @@
--!strict
-- codecs/video/Mpeg1/Tables: the constant tables of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
-- 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 are 0-based like the JS arrays.
-- 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,
@@ -74,16 +75,6 @@ T.MOTION = { [0] = 3,
0, 16, 0, 0, 13, 0, 0, 14, 0, 0, 11, 0, 0, 15, 0, 0, -16, 0, 0, -12, 0, 0, -14, 0,
0, -15, 0, 0, -11, 0, 0, -13,
}
T.DCT_DC_SIZE_LUMINANCE = { [0] = 6,
3, 0, 18, 15, 0, 9, 12, 0, 0, 0, 1, 0, 0, 2, 27, 24, 0, 21, 30, 0, 0, 0, 0, 36,
33, 0, 0, 0, 4, 0, 0, 3, 39, 42, 0, 0, 0, 5, 0, 0, 6, 48, 45, 0, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_DC_SIZE_CHROMINANCE = { [0] = 6,
3, 0, 12, 9, 0, 18, 15, 0, 24, 21, 0, 0, 0, 2, 0, 0, 1, 0, 0, 0, 30, 27, 0, 0,
0, 3, 36, 33, 0, 0, 0, 4, 42, 39, 0, 0, 0, 5, 48, 45, 0, 0, 0, 6, 51, -1, 0, 0,
0, 7, 0, 0, 8,
}
T.DCT_COEFF = { [0] = 3,
6, 0, 12, 9, 0, 0, 0, 1, 21, 24, 0, 18, 15, 0, 39, 27, 0, 33, 30, 0, 42, 36, 0, 0,
0, 257, 60, 66, 0, 54, 63, 0, 48, 57, 0, 0, 0, 513, 51, 45, 0, 0, 0, 2, 0, 0, 3, 81,
@@ -114,4 +105,34 @@ T.DCT_COEFF = { [0] = 3,
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
@@ -1,14 +1,15 @@
--!strict
-- codecs/video/Mpeg1/Vlc: lookup tables for the MPEG-1 variable-length codes, built at load time from jsmpeg's binary trees (Tables.luau).
-- 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. Absorbed from mpeg1-luau e2e2898 (same author), unchanged but
-- for this header and the require.
local T = require("@formats/codecs/video/Mpeg1/Tables")
-- 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("@formats/codecs/video/Mpeg2/Tables")
local V = {}
@@ -32,8 +33,7 @@ local function leaves(tree: { [number]: number }): { Leaf }
return out
end
local function flat(tree: { [number]: number }): (buffer, number)
local ls = leaves(tree)
local function flatLeaves(ls: { Leaf }): (buffer, number)
local k = 0
for _, l in ls do
k = math.max(k, l.len)
@@ -49,6 +49,19 @@ local function flat(tree: { [number]: number }): (buffer, number)
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
@@ -93,10 +106,16 @@ V.MBAI, V.MBAI_BITS = flat(T.MACROBLOCK_ADDRESS_INCREMENT) -- 34 = stuffing, 35
V.MBTYPE_I, V.MBTYPE_I_BITS = flat(T.MACROBLOCK_TYPE_INTRA)
V.MBTYPE_P, V.MBTYPE_P_BITS = flat(T.MACROBLOCK_TYPE_PREDICTIVE)
V.MBTYPE_B, V.MBTYPE_B_BITS = flat(T.MACROBLOCK_TYPE_B)
V.CBP, V.CBP_BITS = flat(T.CODE_BLOCK_PATTERN)
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 = flat(T.DCT_DC_SIZE_LUMINANCE)
V.DC_CHROMA, V.DC_CHROMA_BITS = flat(T.DCT_DC_SIZE_CHROMINANCE)
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)
@@ -113,4 +132,13 @@ do
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
+364
View File
@@ -0,0 +1,364 @@
--!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("@formats/Types")
local Err = require("@formats/core/Err")
local D = require("@formats/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)
}
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)
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
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 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("@formats/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("@formats/core/Err")
local Types = require("@formats/Types")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Header = require("@formats/codecs/video/Theora/Header")
local Decoder = require("@formats/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
+28 -48
View File
@@ -240,51 +240,10 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
return Jpeg.encode(src, { quality = opts and opts.quality or 90 })
end
-- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture)
local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
local function push(f: any)
local img = Mpeg1.frameImage(f)
if img then
img.meta.yuv = { range = "limited", matrix = "bt601" }
local tag = f.tag
table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 })
end
end
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts })
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
if f then
push(f)
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil, nil, nil
end
function self.flush(_: any)
for _ = 1, 4 do
local f = dec:flush()
if not f then
break
end
push(f)
end
end
function self.reset(_: any)
dec:reset()
table.clear(queue)
end
return self :: any, nil
-- 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("@formats/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);
@@ -294,21 +253,42 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec
return H264.newVideoDecoder(track, opts)
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("@formats/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("@formats/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 = mpeg1Decoder },
{ 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" }, matroska = { "V_MPEG2" } },
{ 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" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder },
{ 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 } = {}