Files
rosetta/tests/codecs/mpeg2.luau
T
4DBugandClaude Opus 5.5 c33ffa7343 ws-video2: codecs/video/Mpeg2 (MPEG-1/2 core, Main profile, 4:2:2, field pictures, dual prime), bit-exact with ffmpeg -idct int
Mpeg1 is now the Mpeg2 module under its old name (core, tables and VLCs moved to Mpeg2/). Dsp.mc takes separate
source / destination strides; Dsp.edge emulates edges. containers/MpegEs: field-picture pairs are one access unit
(pictureStructure). Registry: mpeg1 and mpeg2 decode through Mpeg2.newVideoDecoder; more MPEG-2 FourCCs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-31 14:25:51 -05:00

303 lines
10 KiB
Luau

-- codecs/video/Mpeg2 tests. Against `ffmpeg -idct int` (tools/fixtures/mpeg2.py): every stream (progressive and
-- interlaced frame pictures with field prediction and field DCT, top / bottom field first, 4:2:2, the alternate scan,
-- Table B-15, the non-linear quantiser scale, DC precision 9..11, custom luma / chroma matrices, f_code > 1, an odd
-- size, B-frames, dual prime) decodes one access unit at a time to exactly ffmpeg's planes, every frame, in display
-- order; the same stream written in random pieces gives the same frames; frame flags (mpeg2, chroma, progressive,
-- topFieldFirst); frameImage (4:2:2 -> yuv420p, rgba8); the registry's VideoCodecDecoder; truncated and corrupted
-- streams never throw; the fuzz no-throw pass.
local T = require("@tests/T")
local Mpeg2 = require("@formats/codecs/video/Mpeg2")
local Video = require("@formats/codecs/video/Video")
local Base64 = require("@formats/core/Base64")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/compress/Deflate")
local STREAMS = {
require("@tests/gen/mpeg2_prog"),
require("@tests/gen/mpeg2_tff"),
require("@tests/gen/mpeg2_bff_alt"),
require("@tests/gen/mpeg2_tools"),
require("@tests/gen/mpeg2_dc9_matrix"),
require("@tests/gen/mpeg2_dc11_q1"),
require("@tests/gen/mpeg2_motion"),
require("@tests/gen/mpeg2_odd_ilace"),
require("@tests/gen/mpeg2_c422"),
require("@tests/gen/mpeg2_c422_ilace"),
require("@tests/gen/mpeg2_dualprime"),
}
local t = T.suite("codecs/mpeg2")
local rand = T.rng(11)
local function b64(s: string): buffer
return Base64.decode(s) :: buffer
end
-- CRC-32 of a plane cropped to w x h from a buffer with stride
local function planeCrc(b: buffer, stride: number, w: number, h: number): number
local row = buffer.create(w * h)
for y = 0, h - 1 do
buffer.copy(row, y * w, b, y * stride, w)
end
return Crc32.of(row)
end
-- the cropped planes of a frame, as ffmpeg writes them (w x h luma, ceil(w / 2) x (h or ceil(h / 2)) chroma)
local function crcs(f: any): (number, number, number)
local w, h = f.width, f.height
local cw = (w + 1) // 2
local ch = if f.chroma == 2 then h else (h + 1) // 2
local chw = f.codedWidth // 2
return planeCrc(f.y, f.codedWidth, w, h), planeCrc(f.cb, chw, cw, ch), planeCrc(f.cr, chw, cw, ch)
end
-- differing samples between a frame's luma and a reference yuv frame (debug detail on a mismatch)
local function lumaDiff(f: any, ref: buffer): (number, number)
local n, first = 0, -1
for y = 0, f.height - 1 do
for x = 0, f.width - 1 do
if buffer.readu8(f.y, y * f.codedWidth + x) ~= buffer.readu8(ref, y * f.width + x) then
n += 1
if first < 0 then
first = y * 65536 + x
end
end
end
end
return n, first
end
local function decodeUnits(fx: any, file: buffer): { any }
local dec = Mpeg2.new({ reorder = true, rgba = false })
local out = {}
local function take(f: any)
local y, u, v = crcs(f)
-- the 16-line luma bands now: the planes belong to the decoder
local bands = {}
for b = 0, (f.height + 15) // 16 - 1 do
local rows = math.min(16, f.height - b * 16)
local buf = buffer.create(f.width * rows)
for r = 0, rows - 1 do
buffer.copy(buf, r * f.width, f.y, (b * 16 + r) * f.codedWidth, f.width)
end
bands[b] = Crc32.of(buf)
end
table.insert(out, { y, u, v, f, bands })
end
for i, u in fx.units do
local f = dec:decode(file, u[1], u[2], i)
while f do
take(f)
f = dec:decode(file, 0, 0, i)
end
end
while true do
local f = dec:flush()
if not f then
break
end
take(f)
end
return out
end
-- 1. every stream against ffmpeg, bit-exact. ffmpeg's encoder sometimes ends a B-picture slice before the row's last
-- macroblock (invalid MPEG-2); both decoders conceal the gap, ffmpeg with its error-resilience guesses and deblocking.
-- Frames with concealed macroblocks compare every 16-line luma band but those and their neighbours.
local total, concealedFrames = 0, 0
for _, fx in STREAMS do
local name = fx.name
local file = b64(fx.file)
local t0 = os.clock()
local got = decodeUnits(fx, file)
local dt = os.clock() - t0
t:eq(#got, fx.frames, name .. ": frame count")
local bad, msg = 0, ""
for k, ref in fx.crcs do
local g = got[k]
if g and (g[1] ~= ref[1] or g[2] ~= ref[2] or g[3] ~= ref[3]) then
local f = g[4]
local ok = next(f.concealed) ~= nil
if ok then
concealedFrames += 1
for band, crc in fx.bands[k] do
local b = band - 1
if not (f.concealed[b] or f.concealed[b - 1] or f.concealed[b + 1]) then
ok = ok and g[5][b] == crc
end
end
end
if not ok then
bad += 1
if bad == 1 then
local detail = ""
if k == 1 and #got == 1 then
local n, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer)
detail = string.format(" (%d luma samples differ, first at %d,%d)", n, first % 65536, first // 65536)
end
msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType,
tostring(g[1] == ref[1]), tostring(g[2] == ref[2]), tostring(g[3] == ref[3]), detail)
end
end
end
end
t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg)
local f1 = got[1] and got[1][4]
if f1 then
t:check(f1.mpeg2 == true, name .. ": mpeg2 flag")
t:eq(f1.chroma, fx.chroma, name .. ": chroma format")
end
total += #got
t:note(" %-12s %4dx%-4d %s %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height,
if fx.chroma == 2 then "4:2:2" else "4:2:0", #got, #got / dt)
end
-- 2. interlace flags
do
local got = decodeUnits(STREAMS[2], b64(STREAMS[2].file))
t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == true, "tff: interlaced, top field first")
got = decodeUnits(STREAMS[3], b64(STREAMS[3].file))
t:check(got[1][4].progressive == false and got[1][4].topFieldFirst == false, "bff_alt: bottom field first")
got = decodeUnits(STREAMS[1], b64(STREAMS[1].file))
t:check(got[1][4].progressive == true, "prog: progressive")
end
-- 3. the same stream written in random pieces (decodeFrame) gives the same frames as unit by unit
for _, idx in { 2, 9 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local want = decodeUnits(fx, file)
local dec = Mpeg2.new({ reorder = true, rgba = false })
local p, k, ok = 0, 0, true
local n = buffer.len(file)
local function check(f: any)
k += 1
local y, u, v = crcs(f)
local ref = want[k]
ok = ok and ref ~= nil and y == ref[1] and u == ref[2] and v == ref[3]
end
while p < n do
local len = math.min(n - p, 1 + rand(5000))
dec:write(file, p, len)
p += len
while true do
local f = dec:decodeFrame()
if not f then
break
end
check(f)
end
end
while true do
local f = dec:flush()
if not f then
break
end
check(f)
end
t:check(ok and k == fx.frames, string.format("%s: random pieces give the same %d frames (%d)", fx.name, fx.frames, k))
end
-- 4. frameImage: yuv420p (4:2:2 converted), rgba8
do
local fx = STREAMS[9]
local dec = Mpeg2.new({ reorder = false, rgba = true })
local file = b64(fx.file)
local f = dec:decode(file, fx.units[1][1], fx.units[1][2])
t:check(f ~= nil and f.pixels ~= nil, "c422: rgba frame")
if f then
local img = Mpeg2.frameImage(f)
t:check(img ~= nil and img.format == "yuv420p" and img.width == fx.width, "c422: frameImage yuv420p")
if img then
local cw, ch = (fx.width + 1) // 2, (fx.height + 1) // 2
t:eq(buffer.len(img.pixels), fx.width * fx.height + 2 * cw * ch, "c422: yuv420p size")
t:eq(img.meta.source.format, "mpeg2", "c422: meta.source.format")
t:eq(img.meta.source.chroma, "422", "c422: meta.source.chroma")
end
local rgba = Mpeg2.frameImage(f, true)
t:check(rgba ~= nil and rgba.format == "rgba8", "c422: frameImage rgba8")
end
t:check(Mpeg2.frameImage({} :: any) == nil, "frameImage of a non-frame is nil")
end
-- 5. the registry's decoder (packets = access units), display order with pts
do
t:check(Video.fromFourcc("mpg2") == "mpeg2" and Video.fromMatroska("V_MPEG2") == "mpeg2", "registry names")
t:check(Video.canDecode("mpeg2") and Video.canDecode("mpeg1"), "registry decoders")
local fx = STREAMS[1]
local file = b64(fx.file)
local want = decodeUnits(fx, file)
local dec = assert(Video.decoder({ id = 1, kind = "video", codec = "mpeg2", timescale = 25 } :: any))
local frames, order = 0, true
local last = -1
for i, u in fx.units do
local d = buffer.create(u[2])
buffer.copy(d, 0, file, u[1], u[2])
dec:decode({ track = 1, pts = i, keyframe = false, data = d } :: any)
while true do
local img, pts = dec:receive()
if not img then
break
end
frames += 1
local ref = want[frames]
local w, h = fx.width, fx.height
order = order and ref ~= nil and Crc32.of(img.pixels, 0, w * h) == ref[1] and img.meta.yuv ~= nil
last = pts or last
end
end
dec:flush()
while dec:receive() do
frames += 1
end
t:eq(frames, fx.frames, "registry decoder: frame count")
t:check(order, "registry decoder: frames in display order, equal to the codec's")
end
-- 6. robustness: truncated units, bit flips, garbage (never throws), and the fuzz pass
do
local samples = {}
for _, idx in { 1, 2, 9, 11 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local n = math.min(buffer.len(file), 60000)
local b = buffer.create(n)
buffer.copy(b, 0, file, 0, n)
table.insert(samples, b)
end
local threw = 0
for round = 1, 12 do
local src = samples[1 + round % #samples]
local b = buffer.create(buffer.len(src))
buffer.copy(b, 0, src)
for _ = 1, 20 do
local i = rand(buffer.len(b))
buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8))))
end
local ok = pcall(function()
local dec = Mpeg2.new({ reorder = true })
dec:write(b)
while dec:decodeFrame() do
end
while dec:flush() do
end
end)
if not ok then
threw += 1
end
end
t:eq(threw, 0, "corrupted streams never throw")
t:fuzz("decode", function(b: buffer)
local dec = Mpeg2.new({ reorder = true })
dec:write(b)
local f = dec:decodeFrame()
while f do
f = dec:decodeFrame()
end
return dec:flush()
end, samples, { mutations = 60, garbage = 10 })
end
t:note(" %d frames bit-exact with ffmpeg -idct int (%d with concealed macroblocks: compared outside them)", total, concealedFrames)
t:done()