Files
rosetta/tests/codecs/mpeg1.luau
T

510 lines
19 KiB
Luau

-- codecs/video/Mpeg1 tests, ported from mpeg1-luau tests/decode.luau and tests/robust.luau. Every frame bit-exact with
-- `ffmpeg -idct int` (the IDCT codecs/video/Dsp reproduces; frames with concealed macroblocks excepted). Against ffmpeg
-- (tools/fixtures/mpeg1.py): every stream decodes, one access unit at a time, to as many frames as ffmpeg's decode,
-- in display order; each frame's RGBA channel means within 1.5 of ffmpeg's; whole sampled frames within 2 MAE per
-- channel (IDCT and colour rounding) and, as yuv420p (frameImage), within a PSNR floor of ffmpeg -pix_fmt yuv420p;
-- the same stream written in random pieces through write() / decodeFrame() gives identical frames; a size change.
-- Robustness / API: bad arguments, pictures before the first sequence header, reset(), rgba = false, tags through
-- B-frame reordering, string input, truncated units, bit flips and garbage (never throws, recovers at an
-- I-picture), an oversized sequence header; frameImage; the fuzz no-throw pass.
local T = require("@tests/T")
local Mpeg1 = require("@formats/codecs/video/Mpeg1")
local Base64 = require("@formats/core/Base64")
local Deflate = require("@formats/codecs/compress/Deflate")
local Types = require("@formats/Types")
local Crc32 = require("@formats/core/Crc32")
local STREAMS = {
require("@tests/gen/mpeg1_qcif_200k"),
require("@tests/gen/mpeg1_main_450k"),
require("@tests/gen/mpeg1_zoom_150k"),
require("@tests/gen/mpeg1_zoom_1500k"),
require("@tests/gen/mpeg1_big_1000k"),
require("@tests/gen/mpeg1_odd_173x95"),
require("@tests/gen/mpeg1_matrix"),
require("@tests/gen/mpeg1_q1"),
require("@tests/gen/mpeg1_q31"),
require("@tests/gen/mpeg1_zeromv"),
require("@tests/gen/mpeg1_bframes"),
require("@tests/gen/mpeg1_bframes_zoom"),
}
local SizeChange = require("@tests/gen/mpeg1_sizechange")
local t = T.suite("codecs/mpeg1")
local rand = T.rng(7)
local function between(a: number, b: number): number
return a + rand(b - a + 1)
end
local function b64(s: string): buffer
return Base64.decode(s) :: buffer
end
local function z64(s: string): buffer
return Deflate.zlib(b64(s)) :: buffer
end
-- mean absolute error per channel (r, g, b) between two RGBA8 buffers of n pixels, and the largest difference
local function mae(a: buffer, b: buffer, n: number): (number, number, number, number)
local sr, sg, sb, mx = 0, 0, 0, 0
for i = 0, n - 1 do
local o = i * 4
local dr = math.abs(buffer.readu8(a, o) - buffer.readu8(b, o))
local dg = math.abs(buffer.readu8(a, o + 1) - buffer.readu8(b, o + 1))
local db = math.abs(buffer.readu8(a, o + 2) - buffer.readu8(b, o + 2))
sr += dr
sg += dg
sb += db
mx = math.max(mx, dr, dg, db)
end
return sr / n, sg / n, sb / n, mx
end
local function means(a: buffer, n: number): (number, number, number)
local r, g, b = 0, 0, 0
for i = 0, n - 1 do
local o = i * 4
r += buffer.readu8(a, o)
g += buffer.readu8(a, o + 1)
b += buffer.readu8(a, o + 2)
end
return r / n, g / n, b / n
end
local function psnr(a: buffer, ao: number, b: buffer, bo: number, n: number): number
local se = 0
for i = 0, n - 1 do
local d = buffer.readu8(a, ao + i) - buffer.readu8(b, bo + i)
se += d * d
end
if se == 0 then
return 99
end
return 10 * math.log10(255 * 255 * n / se)
end
local MAE_LIMIT = 2
local totalExact, totalConcealed = 0, 0
local MEAN_LIMIT = 1.5
-- 1. every stream against ffmpeg
local worst, worstY, worstC = 0, 99, 99
for _, fx in STREAMS do
local name = fx.name
local file = b64(fx.file)
local w, h = fx.width, fx.height
local n = w * h
local cw, ch = (w + 1) // 2, (h + 1) // 2
local rgbaRef, yuvRef = {}, {}
for _, s in fx.rgba do
rgbaRef[s.index] = z64(s.pixels)
end
for _, s in fx.yuv do
yuvRef[s.index] = z64(s.planes)
end
local hasB = string.find(name, "bframes") ~= nil
local dec = Mpeg1.new({ reorder = hasB })
local frames = 0
local exact, concealed = 0, 0
local maxMae, maxMeanErr = 0, 0
local sums = {}
local function onFrame(f: any)
frames += 1
t:check(f.width == w and f.height == h, string.format("%s: size %dx%d", name, f.width, f.height))
t:eq(f.index, frames, name .. ": frame index")
local px = f.pixels :: buffer
t:eq(buffer.len(px), n * 4, name .. ": pixels size")
local ref = fx.means[frames]
t:check(ref ~= nil, string.format("%s: more frames than ffmpeg (%d)", name, frames))
local r, g, b = means(px, n)
local me = math.max(math.abs(r - ref[1]), math.abs(g - ref[2]), math.abs(b - ref[3]))
maxMeanErr = math.max(maxMeanErr, me)
t:check(me <= MEAN_LIMIT, string.format("%s frame %d: channel means off by %.2f", name, frames, me))
local s = rgbaRef[frames]
if s then
local mr, mg, mb = mae(px, s, n)
local m = math.max(mr, mg, mb)
maxMae = math.max(maxMae, m)
t:check(m <= MAE_LIMIT, string.format("%s frame %d: MAE %.3f %.3f %.3f", name, frames, mr, mg, mb))
local again = Mpeg1.frameImage(f, true) :: Types.Image
t:check(again.format == "rgba8" and buffer.tostring(again.pixels) == buffer.tostring(px), name .. ": frameImage(f, true) = frame.pixels")
end
local y = yuvRef[frames]
if y then
local img = Mpeg1.frameImage(f) :: Types.Image
t:check(img.format == "yuv420p" and img.width == w and img.height == h and buffer.len(img.pixels) == n + 2 * cw * ch, name .. ": frameImage yuv420p")
t:check(img.meta.source.range == "limited" and img.meta.source.pictureType == f.pictureType, name .. ": frameImage meta")
local py = psnr(img.pixels, 0, y, 0, n)
local pc = psnr(img.pixels, n, y, n, 2 * cw * ch)
worstY, worstC = math.min(worstY, py), math.min(worstC, pc)
t:check(py > 50 and pc > 50, string.format("%s frame %d: yuv420p PSNR %.1f / %.1f dB against ffmpeg", name, frames, py, pc))
end
t:check(buffer.readu8(px, 3) == 255 and buffer.readu8(px, n * 4 - 1) == 255, "alpha 255")
sums[frames] = buffer.tostring(px)
-- bit-exact against ffmpeg -idct int (outside macroblocks the decoder had to conceal)
local ex = fx.exact[frames]
if ex then
local img = Mpeg1.frameImage(f) :: Types.Image
local yc = Crc32.of(img.pixels, 0, n)
local uc = Crc32.of(img.pixels, n, cw * ch)
local vc = Crc32.of(img.pixels, n + cw * ch, cw * ch)
if yc == ex[1] and uc == ex[2] and vc == ex[3] then
exact += 1
elseif next(f.concealed) ~= nil then
concealed += 1
else
t:check(false, string.format("%s frame %d (type %d): differs from ffmpeg -idct int", name, frames, f.pictureType))
end
end
end
local t0 = os.clock()
for _, u in fx.units do
local f = dec:decode(file, u[1], u[2])
if f then
onFrame(f)
end
end
while true do
local f = dec:flush()
if f == nil then
break
end
onFrame(f)
end
local dt = os.clock() - t0
t:eq(frames, fx.frames, name .. ": frames (ffmpeg's count)")
t:eq(dec.stats.errors, 0, name .. ": no bitstream errors")
worst = math.max(worst, maxMae)
t:note("%-13s %4dx%-4d %3d frames %3d bit-exact worst MAE %.3f means err %.3f %6.1f fps (with the checks)", name, w, h, frames, exact, maxMae, maxMeanErr, frames / dt)
t:eq(exact + concealed, frames, name .. ": frames equal to ffmpeg -idct int (or with concealed macroblocks)")
totalExact += exact
totalConcealed += concealed
-- streamed: random pieces through write / decodeFrame, then flush
local d2 = Mpeg1.new({ reorder = hasB })
local got = 0
local p, total = 0, buffer.len(file)
local function take(f: any)
got += 1
t:check(sums[got] == buffer.tostring(f.pixels :: buffer), string.format("%s streamed frame %d identical", name, got))
end
while p < total do
local k = math.min(total - p, between(1, 6000))
t:check(d2:write(file, p, k), "write")
p += k
while true do
local f = d2:decodeFrame()
if f == nil then
break
end
take(f)
end
end
while true do
local f = d2:flush()
if f == nil then
break
end
take(f)
end
t:eq(got, frames, name .. ": streamed frame count")
end
t:note("worst sampled-frame MAE %.3f (limit %d); worst yuv420p PSNR luma %.1f, chroma %.1f dB", worst, MAE_LIMIT, worstY, worstC)
t:note("%d frames bit-exact with ffmpeg -idct int, %d with concealed macroblocks (ffmpeg error concealment)", totalExact, totalConcealed)
-- 2. a size change mid-stream
do
local file = b64(SizeChange.file)
local dec = Mpeg1.new()
dec:write(file)
local list = {}
while true do
local f = dec:decodeFrame() or dec:flush()
if f == nil then
break
end
table.insert(list, { w = f.width, h = f.height, px = buffer.tostring(f.pixels :: buffer) })
end
local a, b = SizeChange.parts[1], SizeChange.parts[2]
t:eq(#list, a.frames + b.frames, "sizechange: frame count")
t:check(list[1].w == a.width and list[1].h == a.height, "sizechange: first size")
t:check(list[a.frames].w == a.width and list[a.frames + 1].w == b.width and list[#list].h == b.height, "sizechange: second size")
for k, part in { a, b } do
local last = list[if k == 1 then a.frames else #list]
local mr, mg, mb = mae(buffer.fromstring(last.px), z64(part.last), part.width * part.height)
t:check(math.max(mr, mg, mb) <= MAE_LIMIT, string.format("sizechange part %d MAE %.3f %.3f %.3f", k, mr, mg, mb))
end
end
-- 3. robustness and the API
local function slice(b: buffer, from: number, n: number): buffer
local out = buffer.create(n)
buffer.copy(out, 0, b, from, n)
return out
end
local main = STREAMS[2]
local mainFile = b64(main.file)
local W, H = main.width, main.height
local ref = {}
do
local dec = Mpeg1.new()
for _, u in main.units do
local f = dec:decode(mainFile, u[1], u[2])
table.insert(ref, buffer.tostring((f :: any).pixels))
end
t:eq(#ref, #main.units, "reference decode")
end
do -- bad arguments
local dec = Mpeg1.new()
t:check(dec:decode((nil :: any)) == nil, "decode(nil)")
t:check(dec:decode((42 :: any)) == nil, "decode(number)")
t:check(dec:write(buffer.create(4), 10) == false, "write offset past the end")
t:check(dec:write(buffer.create(4), 0, 9) == false, "write length past the end")
t:check(dec:write(buffer.create(4), -1) == false, "write negative offset")
t:check(dec:decodeFrame() == nil, "decodeFrame with no data")
t:check(dec:flush() == nil, "flush with no data")
t:check(Mpeg1.new((5 :: any)) ~= nil, "new(non-table)")
t:check(dec:decode(buffer.create(0)) == nil, "empty unit")
t:check(Mpeg1.frameImage(nil :: any) == nil and Mpeg1.frameImage({} :: any) == nil, "frameImage of a non-frame")
end
do -- string input; pictures before the first sequence header are skipped
local dec = Mpeg1.new()
local u2 = main.units[2]
t:check(dec:decode(buffer.tostring(slice(mainFile, u2[1], u2[2]))) == nil, "P picture before any sequence header")
local u1 = main.units[1]
local f = dec:decode(buffer.tostring(slice(mainFile, u1[1], u1[2])))
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "string unit decodes")
t:check(dec.width == W and dec.height == H and math.abs(dec.frameRate - 24) < 0.01, "sequence fields")
t:check(f.pictureType == Mpeg1.PICTURE_I and f.codedWidth == 320 and buffer.len(f.y) == 320 * 192, "frame fields")
t:eq(dec.stats.skipped, 1, "stats.skipped")
end
do -- rgba = false: planes only, frameImage still gives both
local dec = Mpeg1.new({ rgba = false })
local u1 = main.units[1]
local f = dec:decode(mainFile, u1[1], u1[2]) :: any
t:check(f ~= nil and f.pixels == nil and buffer.len(f.y) > 0 and buffer.len(f.cb) == buffer.len(f.y) // 4, "rgba = false")
local img = Mpeg1.frameImage(f, true) :: Types.Image
t:check(img and buffer.tostring(img.pixels) == ref[1], "frameImage(f, true) after rgba = false")
local y = Mpeg1.frameImage(f) :: Types.Image
t:check(y.format == "yuv420p" and buffer.readu8(y.pixels, W) == buffer.readu8(f.y, f.codedWidth), "frameImage crops the coded width")
end
do -- toRgba in bands (from bug tv's workers): whole, row bands into one buffer, bands of plane copies; odd sizes
local function bands(f: any, step: number): buffer
local w, h, cw = f.width, f.height, f.codedWidth
local out = buffer.create(w * h * 4)
for r0 = 0, h - 1, step do
local r1 = math.min(h, r0 + step)
-- copies holding only rows r0 .. r1 - 1 (planeRow0 = r0), converted into a band, then placed
local chw, c0, c1 = cw // 2, r0 // 2, (r1 + 1) // 2
local y = buffer.create((r1 - r0) * cw)
buffer.copy(y, 0, f.y, r0 * cw, (r1 - r0) * cw)
local cb, cr = buffer.create((c1 - c0) * chw), buffer.create((c1 - c0) * chw)
buffer.copy(cb, 0, f.cb, c0 * chw, (c1 - c0) * chw)
buffer.copy(cr, 0, f.cr, c0 * chw, (c1 - c0) * chw)
local band = buffer.create((r1 - r0) * w * 4)
assert(Mpeg1.toRgba(y, cb, cr, cw, w, h, band, r0, r1, 0, r0))
buffer.copy(out, r0 * w * 4, band)
end
return out
end
local dec = Mpeg1.new({ rgba = false })
local u1 = main.units[1]
local f = dec:decode(mainFile, u1[1], u1[2]) :: any
local whole = buffer.create(f.width * f.height * 4)
t:check(Mpeg1.toRgba(f.y, f.cb, f.cr, f.codedWidth, f.width, f.height, whole), "toRgba whole frame")
t:check(buffer.tostring(whole) == ref[1], "toRgba whole = the decoder's RGBA")
local into = buffer.create(f.width * f.height * 4)
for r0 = 0, f.height - 1, 32 do
Mpeg1.toRgba(f.y, f.cb, f.cr, f.codedWidth, f.width, f.height, into, r0, math.min(f.height, r0 + 32), r0 * f.width * 4)
end
t:check(buffer.tostring(into) == ref[1], "toRgba row bands into one buffer")
t:check(buffer.tostring(bands(f, 16)) == ref[1], "toRgba bands of plane copies (planeRow0)")
local fo = STREAMS[6] -- 173 x 95
local bo = b64(fo.file)
local odec = Mpeg1.new({ rgba = false })
local uo = fo.units[1]
local of = odec:decode(bo, uo[1], uo[2]) :: any
local oimg = Mpeg1.frameImage(of, true) :: Types.Image
t:check(of and buffer.tostring(bands(of, 10)) == buffer.tostring(oimg.pixels), "toRgba bands at an odd size")
t:check(Mpeg1.toRgba(f.y, f.cb, f.cr, f.codedWidth, f.width, f.height, buffer.create(4)) == false, "toRgba: out too small")
t:check(Mpeg1.toRgba(f.y, f.cb, f.cr, 7, f.width, f.height, whole) == false, "toRgba: odd coded width")
t:check(Mpeg1.toRgba(f.y, f.cb, f.cr, f.codedWidth, f.width, f.height, whole, 4, 2) == false, "toRgba: empty band")
t:check(Mpeg1.toRgba(f.y, f.cb, f.cr, f.codedWidth, f.width, f.height, whole, 0, nil, 2) == false, "toRgba: unaligned offset")
end
do -- the cooperative yield hook: after every slice and every 16 rows of conversion; output unchanged; errors ignored
local calls = 0
local dec = Mpeg1.new({ yield = function()
calls += 1
end })
local u1 = main.units[1]
local f = dec:decode(mainFile, u1[1], u1[2]) :: any
t:check(f ~= nil and buffer.tostring(f.pixels) == ref[1] and calls > 0, "yield hook runs, same frame")
local inCo = 0
local co = coroutine.create(function()
local d2 = Mpeg1.new()
d2:setYield(function()
coroutine.yield()
end)
return d2:decode(mainFile, u1[1], u1[2])
end)
local ok, res = coroutine.resume(co)
while ok and coroutine.status(co) == "suspended" do
inCo += 1
ok, res = coroutine.resume(co)
end
t:check(ok and inCo > 1 and res ~= nil and buffer.tostring((res :: any).pixels) == ref[1], "a decode suspended at the hook resumes to the same frame")
local bad = Mpeg1.new({ yield = function()
error("hook error")
end })
local g = bad:decode(mainFile, u1[1], u1[2]) :: any
t:check(g ~= nil and buffer.tostring(g.pixels) == ref[1], "an erroring hook is ignored")
end
do -- reset (seek): the next picture must be an I-picture again
local dec = Mpeg1.new()
for i = 1, 5 do
local u = main.units[i]
dec:decode(mainFile, u[1], u[2])
end
dec:reset()
local u = main.units[10]
t:check(dec:decode(mainFile, u[1], u[2]) == nil, "P after reset has no reference")
u = main.units[1]
local f = dec:decode(mainFile, u[1], u[2])
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "I after reset")
end
do -- tags (pts) follow pictures through reordering
local fx = STREAMS[11]
local b = b64(fx.file)
local dec = Mpeg1.new({ reorder = true, rgba = false })
local order = {}
for i, u in fx.units do
local f = dec:decode(b, u[1], u[2], i)
if f then
table.insert(order, f)
end
end
while true do
local f = dec:flush()
if f == nil then
break
end
table.insert(order, f)
end
t:eq(#order, #fx.units, "bframes: every picture out")
local sawB = false
for i = 2, #order do
local a, c = order[i - 1], order[i]
if c.temporalReference ~= 0 then
t:check(c.temporalReference == a.temporalReference + 1, "display order at " .. i)
end
if c.pictureType == Mpeg1.PICTURE_B then
sawB = true
t:check(c.tag == a.tag + 1 or a.pictureType ~= Mpeg1.PICTURE_B, "B tag order")
end
end
t:check(sawB, "the stream has B-frames")
local d2 = Mpeg1.new()
for i, u in fx.units do
local f = d2:decode(b, u[1], u[2], i)
t:check(f ~= nil and f.tag == i, "decode order tag " .. i)
end
end
do -- truncated units: every prefix length of a picture, then recovery
local dec = Mpeg1.new()
local u1 = main.units[1]
for k = 0, u1[2], 97 do
Mpeg1.new():decode(mainFile, u1[1], k)
end
for i = 1, 6 do
local u = main.units[i]
dec:decode(mainFile, u[1], u[2] // 2)
end
local f = dec:decode(mainFile, main.units[1][1], main.units[1][2])
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "recovers at an I-picture after truncation")
end
-- bit flips and byte garbage in every unit: no throw, sane frames
local rounds = 0
for _, k in { 2, 11, 8, 6 } do
local fx = STREAMS[k]
local b = b64(fx.file)
for round = 1, 6 do
local dec = Mpeg1.new({ reorder = round % 2 == 0 })
for _, u in fx.units do
local unit = slice(b, u[1], u[2])
local nflip = if round <= 3 then round * 3 else 40
for _ = 1, nflip do
local at = between(0, u[2] - 1)
if round == 6 then
buffer.writeu8(unit, at, between(0, 255))
else
buffer.writeu8(unit, at, bit32.bxor(buffer.readu8(unit, at), bit32.lshift(1, between(0, 7))))
end
end
local ok, f = pcall(dec.decode, dec, unit)
t:check(ok, fx.name .. ": corrupt unit threw " .. tostring(f))
if f then
t:check(buffer.len((f :: any).pixels) == f.width * f.height * 4, "frame size")
end
end
while dec:flush() do
end
rounds += 1
end
end
t:note("%d corrupted-stream rounds", rounds)
do -- streamed garbage and random units
local dec = Mpeg1.new()
for _ = 1, 300 do
local n = between(0, 3000)
local g = buffer.create(n)
for i = 0, n - 1 do
local r = between(0, 9)
buffer.writeu8(g, i, if r < 3 then 0 elseif r == 3 then 1 elseif r == 4 then 0xB3 else between(0, 255))
end
dec:write(g)
while dec:decodeFrame() do
end
dec:decode(g)
end
dec:reset()
local f = dec:decode(mainFile, main.units[1][1], main.units[1][2])
t:check(f ~= nil and buffer.tostring((f :: any).pixels) == ref[1], "clean after garbage")
end
do -- a hostile sequence header: a huge size is rejected
local b = buffer.create(16)
buffer.writestring(b, 0, "\0\0\1\xB3\xFF\xFF\xFF\x13\xFF\xFF\xE0\x18\0\0\1\xB8")
local dec = Mpeg1.new({ maxPixels = 1000 * 1000 })
dec:decode(b)
t:eq(dec.width, 0, "oversized sequence header rejected")
end
-- 4. the fuzz pass: whole elementary streams (cut, mutated, garbage) through one decoder each
do
local samples = {}
for _, k in { 1, 9 } do
local fx = STREAMS[k]
local b = b64(fx.file)
local u = fx.units
table.insert(samples, buffer.tostring(slice(b, 0, u[4][1] + u[4][2])))
end
t:fuzz("decode", function(b: buffer)
local dec = Mpeg1.new({ reorder = true })
local out = { dec:decode(b) }
while dec:flush() do
end
return table.unpack(out)
end, samples, { mutations = 12, keepHeader = 4 })
end
t:done()