merge ws/video2-flv

This commit is contained in:
4DBug committed 2026-10-31 15:59:44 -05:00
commit a02ece071b
18 files changed
+3088 -1

No files matched your search

+246
View File
@@ -0,0 +1,246 @@
-- codecs/video/H263 tests. Against `ffmpeg -idct int` (tools/fixtures/h263.py): H.263 streams (sub-QCIF .. 4CIF, GOB
-- headers, DQUANT, q 1 .. high quantisers), H.263+ PLUSPTYPE streams (custom sizes, sizes that are not a multiple of
-- 16, the rounding type, unrestricted vectors with reversible codes, slice structure) and Sorenson Spark streams (standard, 8-bit and
-- 16-bit custom sizes, 11-bit escapes, high motion, disposable inter pictures) decode one picture at a time to exactly
-- ffmpeg's planes, every frame; header info; frameImage; the registry's decoders (h263, flv1); unsupported options are
-- UNSUPPORTED; truncated and corrupted pictures never throw; the fuzz no-throw pass.
local T = require("@tests/T")
local H263 = require("@formats/codecs/video/H263")
local Video = require("@formats/codecs/video/Video")
local Err = require("@formats/core/Err")
local Base64 = require("@formats/core/Base64")
local Crc32 = require("@formats/core/Crc32")
local Deflate = require("@formats/codecs/compress/Deflate")
local STREAMS = {
require("@tests/gen/h263_qcif"),
require("@tests/gen/h263_cif_mandel"),
require("@tests/gen/h263_sqcif_scroll"),
require("@tests/gen/h263_qcif_q1"),
require("@tests/gen/h263_qcif_aq"),
require("@tests/gen/h263_cif_gob"),
require("@tests/gen/h263_4cif_gob"),
require("@tests/gen/h263_plus_custom"),
require("@tests/gen/h263_plus_odd"),
require("@tests/gen/h263_plus_umv"),
require("@tests/gen/h263_plus_slices"),
require("@tests/gen/h263_plus_slices_umv"),
require("@tests/gen/h263_flv_320"),
require("@tests/gen/h263_flv_odd"),
require("@tests/gen/h263_flv_wide"),
require("@tests/gen/h263_flv_q1"),
require("@tests/gen/h263_flv_scroll"),
require("@tests/gen/h263_flv_disposable"),
}
local BAD = require("@tests/gen/h263_bad")
local t = T.suite("codecs/h263")
local rand = T.rng(263)
local function b64(s: string): buffer
return Base64.decode(s) :: buffer
end
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
local function crcs(f: any): (number, number, number)
local w, h = f.width, f.height
local cw, ch = (w + 1) // 2, (h + 1) // 2
return planeCrc(f.y, f.stride, w, h), planeCrc(f.cb, f.stride // 2, cw, ch), planeCrc(f.cr, f.stride // 2, cw, ch)
end
-- differing luma samples against a reference frame (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.stride + 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
-- 1. every stream against ffmpeg, bit-exact
local total = 0
local disposables = 0
for _, fx in STREAMS do
local name = fx.name
local file = b64(fx.file)
local dec = H263.new({ flv = fx.flv })
local t0 = os.clock()
local bad, n, msg = 0, 0, ""
for k, u in fx.units do
local f, err = dec:decode(file, u[1], u[2])
if not f then
bad += 1
if bad == 1 then
msg = string.format(" (first: picture %d: %s)", k, tostring(err))
end
else
n += 1
if f.disposable then
disposables += 1
end
local y, cb, cr = crcs(f)
local ref = fx.crcs[k]
if not ref or y ~= ref[1] or cb ~= ref[2] or cr ~= ref[3] then
bad += 1
if bad == 1 then
local detail = ""
if k == 1 then
local nd, first = lumaDiff(f, Deflate.zlib(b64(fx.first)) :: buffer)
detail = string.format(", %d luma samples differ, first at %d,%d", nd, first % 65536, first // 65536)
end
msg = string.format(" (first: frame %d, type %d: y %s u %s v %s%s)", k, f.pictureType,
tostring(ref and y == ref[1]), tostring(ref and cb == ref[2]), tostring(ref and cr == ref[3]), detail)
end
end
end
end
local dt = os.clock() - t0
t:eq(n, fx.frames, name .. ": frame count")
t:eq(bad, 0, name .. ": frames differing from ffmpeg" .. msg)
t:eq(dec.stats.errors, 0, name .. ": no damaged pictures")
total += n
t:note(" %-16s %4dx%-4d %3d frames %6.1f fps (with the checks)", name, fx.width, fx.height, n, n / dt)
end
t:check(disposables > 0, "disposable Sorenson pictures decoded (" .. disposables .. ")")
-- 2. header info
do
local fx = STREAMS[8] -- plus_custom
local file = b64(fx.file)
local h = assert(H263.header(file, fx.units[1][1], fx.units[1][2]))
t:check(h.plus and h.width == 320 and h.height == 240 and h.ptype == 1, "plus_custom: PLUSPTYPE custom size, I picture")
local h2 = assert(H263.header(file, fx.units[2][1], fx.units[2][2]))
t:check(h2.ptype == 2, "plus_custom: second picture P")
fx = STREAMS[14] -- flv_odd
file = b64(fx.file)
h = assert(H263.header(file, fx.units[1][1], fx.units[1][2], true))
t:check(h.flv and h.width == 100 and h.height == 75 and h.version == 1, "flv_odd: Sorenson 8-bit custom size, version 1")
fx = STREAMS[1]
h = assert(H263.header(b64(fx.file), 0, fx.units[1][2]))
t:check(not h.plus and h.width == 176 and h.height == 144, "qcif: PTYPE QCIF")
local _, e = H263.header(buffer.create(16))
t:check(e ~= nil and e.code == Err.CORRUPT, "no start code: CORRUPT")
end
-- 3. unsupported H.263+ options
for name, data in BAD do
local dec = H263.new()
local f, e = dec:decode(b64(data))
t:check(f == nil and e ~= nil and e.code == Err.UNSUPPORTED, name .. ": UNSUPPORTED (" .. tostring(e) .. ")")
end
-- 4. frameImage
do
local fx = STREAMS[14]
local dec = H263.new({ flv = true })
local file = b64(fx.file)
local f = assert(dec:decode(file, fx.units[1][1], fx.units[1][2]))
local img = assert(H263.frameImage(f))
t:check(img.format == "yuv420p" and img.width == 100 and img.height == 75, "frameImage: yuv420p 100x75")
t:eq(buffer.len(img.pixels), 100 * 75 + 2 * 50 * 38, "frameImage: plane sizes")
t:eq(Crc32.of(img.pixels, 0, 100 * 75), fx.crcs[1][1], "frameImage: luma equals ffmpeg's")
t:eq(img.meta.yuv.range, "limited", "frameImage: limited range")
t:eq(img.meta.source.format, "flv1", "frameImage: meta.source.format")
t:check(H263.frameImage({} :: any) == nil, "frameImage of a non-frame is nil")
t:check(dec:decode(42 :: any) == nil, "decode of a non-buffer is nil")
end
-- 5. the registry's decoders
do
t:check(Video.fromFourcc("H263") == "h263" and Video.fromFourcc("s263") == "h263" and Video.fromFourcc("FLV1") == "flv1", "registry names")
t:check(Video.canDecode("h263") and Video.canDecode("flv1"), "registry decoders")
for _, idx in { 2, 15 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
local dec = assert(Video.decoder({ id = 1, kind = "video", codec = if fx.flv then "flv1" else "h263", timescale = 25, width = fx.width, height = fx.height } :: any))
local frames, same = 0, true
for i, u in fx.units do
local d = buffer.create(u[2])
buffer.copy(d, 0, file, u[1], u[2])
local e = dec:decode({ track = 1, pts = i, keyframe = i == 1, data = d } :: any)
t:check(e == nil, fx.name .. ": registry decode " .. tostring(e))
while true do
local img, pts = dec:receive()
if not img then
break
end
frames += 1
same = same and pts == i and img.meta.yuv ~= nil and Crc32.of(img.pixels, 0, fx.width * fx.height) == fx.crcs[frames][1]
end
end
t:eq(frames, fx.frames, fx.name .. ": registry frame count")
t:check(same, fx.name .. ": registry frames equal ffmpeg's")
dec:reset()
local p = buffer.create(fx.units[2][2])
buffer.copy(p, 0, file, fx.units[2][1], fx.units[2][2])
t:check(dec:decode({ track = 1, pts = 2, keyframe = false, data = p } :: any) ~= nil, fx.name .. ": a P picture after reset is an error")
end
end
-- 6. robustness: truncated and corrupted pictures, garbage (never throws), the fuzz pass
do
local samples = {}
for _, idx in { 1, 6, 8, 10, 11, 13, 16 } do
local fx = STREAMS[idx]
local file = b64(fx.file)
for k = 1, 2 do
local u = fx.units[k]
local b = buffer.create(u[2])
buffer.copy(b, 0, file, u[1], u[2])
table.insert(samples, { b, fx.flv })
end
end
local threw, damaged = 0, 0
for round = 1, 40 do
local s = samples[1 + round % #samples]
local src = s[1]
local n = if round % 3 == 0 then rand(buffer.len(src)) else buffer.len(src)
local b = buffer.create(n)
buffer.copy(b, 0, src, 0, n)
for _ = 1, 1 + round % 7 do
local i = 4 + rand(math.max(1, n - 4)) - 1
if i < n then
buffer.writeu8(b, i, bit32.bxor(buffer.readu8(b, i), bit32.lshift(1, rand(8) - 1)))
end
end
local ok = pcall(function()
local dec = H263.new({ flv = s[2] })
dec:decode(src)
dec:decode(b)
dec:decode(b)
damaged += dec.stats.errors
end)
if not ok then
threw += 1
end
end
t:eq(threw, 0, "corrupted pictures never throw")
t:check(damaged > 0, "corrupted pictures are counted (" .. damaged .. ")")
local fuzz = {}
for _, s in samples do
table.insert(fuzz, s[1])
end
t:fuzz("decode", function(b: buffer)
local dec = H263.new({ flv = buffer.len(b) > 2 and bit32.band(buffer.readu8(b, 2), 0x04) ~= 0 })
local f = dec:decode(b)
dec:decode(b)
return f
end, fuzz, { mutations = 40, garbage = 20 })
end
t:note(" %d frames bit-exact with ffmpeg -idct int", total)
t:done()
+235
View File
@@ -0,0 +1,235 @@
-- video/flv tests: FLV files from ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / ADPCM / Nellymoser / Speex /
-- A-law, H.264 with B-frames + AAC, Flash screen video, audio only): tracks and every packet against ffprobe
-- (composition times in the pts, keyframes), onMetaData, frames against ffmpeg (Sorenson bit-exact, H.264 PSNR), audio
-- through the api hook (PCM exact; ADPCM / Nellymoser / Speex known but UNSUPPORTED), seeking; crafted VP6 /
-- enhanced FourCC / encrypted / truncated files; our writer (FLV, MP4, Matroska sources) read back by ffprobe and
-- ffmpeg (tools/fixtures/flv.py) and by our demuxer with the source's packets; fuzz. Fixtures: tools/fixtures/flv.py.
local T = require("@tests/T")
local C = require("@tests/video/_common")
local F = require("@formats")
local Flv = require("@formats/video/flv")
local Video = require("@formats/codecs/video/Video")
local Bytes = require("@formats/core/Bytes")
local Crc32 = require("@formats/core/Crc32")
local Fx = require("@tests/gen/flv_cases")
local Mx = require("@tests/gen/flv_mux")
local Src = require("@tests/gen/flv_src")
local t = T.suite("flv")
t:eq(Flv.name, "flv", "name")
t:eq(Flv.category, "video", "category")
local EXACT_AUDIO = { pcm_s16le = true, pcm_u8 = true, pcm_alaw = true }
local NO_AUDIO_FORMAT = { adpcm_swf = true, nellymoser = true, speex = true }
local byName = {}
for _, c in Fx do
byName[c.name] = c
end
-- every frame's CRC against ffmpeg's (codecs we decode bit-exactly), else PSNR
local function frames(v: any, c: any, label: string)
if v.codec == "flv1" then
v:reset()
local n, bad = 0, 0
while true do
local f, err = v:nextFrame()
if not f then
t:check(err == nil, label .. ": decode error " .. tostring(err))
break
end
n += 1
if Crc32.of(f.image.pixels) ~= c.frames[n] then
bad += 1
end
end
t:eq(n, #c.frames, label .. ": frame count")
t:eq(bad, 0, label .. ": Sorenson frames bit-exact with ffmpeg")
else
C.frames(t, v, c, label, 38)
end
end
for _, c in Fx do
local label = c.name
t:check(Flv.sniff(Bytes.reader(buffer.fromstring(c.data))) == 1, label .. ": sniff")
local v, err = C.open(c.data)
t:check(v ~= nil, label .. ": open " .. tostring(err))
if v then
local dmx = v.demuxer
t:eq(#dmx.tracks, #c.streams, label .. ": track count")
C.packets(t, dmx, c, label)
for i, s in c.streams do
local tr = dmx.tracks[i]
if s.kind == "video" then
t:check(tr.width == s.width and tr.height == s.height, label .. ": video size " .. tostring(tr.width) .. "x" .. tostring(tr.height))
t:check(tr.codec == s.codec, label .. ": video codec " .. tr.codec .. " (" .. s.codec .. ")")
elseif s.rate then
t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": audio " .. tostring(tr.sampleRate) .. " Hz x " .. tostring(tr.channels))
end
end
local md = dmx.meta.metadata
t:check(md ~= nil and type(md.duration) == "number" and md.duration > 0, label .. ": onMetaData duration")
if c.frames then
frames(v, c, label)
C.seek(t, v, c, label, 0.5)
elseif dmx:track("video") then
local _, e = v:nextFrame()
t:check(e ~= nil and e.code == F.Err.UNSUPPORTED and not Video.canDecode(v.codec), label .. ": " .. v.codec .. " is known, decoding UNSUPPORTED")
end
local at = dmx:track("audio")
if at then
if NO_AUDIO_FORMAT[at.codec] then
t:check(v.audio == nil and v.audioError and v.audioError.code == F.Err.UNSUPPORTED, label .. ": " .. at.codec .. " audio UNSUPPORTED (" .. tostring(v.audioError) .. ")")
else
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
end
end
end
end
-- details: H.264 config and composition times, metadata, screen video size
do
local v = assert(C.open(byName["h264_aac.flv"].data))
local vt, at = v.demuxer:track("video"), v.demuxer:track("audio")
t:check(vt.config ~= nil and buffer.readu8(vt.config, 0) == 1, "h264: avcC in track.config")
t:check(at.config ~= nil and buffer.len(at.config) >= 2, "h264: AudioSpecificConfig in track.config")
local reordered = false
for k = 1, v.demuxer:count(vt.id) do
local p = v.demuxer:get(vt.id, k)
if p and p.pts ~= p.dts then
reordered = true
end
end
t:check(reordered, "h264: B-frame composition times in the pts")
t:eq(v.frameRate, 12, "h264: frame rate from onMetaData")
local md = v.demuxer.meta.metadata
t:check(md.width == 160 and md.height == 120 and md.videocodecid == 7 and md.audiocodecid == 10, "onMetaData: width, height, codec ids")
t:check(type(md.encoder) == "string", "onMetaData: encoder string")
local s = assert(C.open(byName["screen.flv"].data))
t:check(s.codec == "flashsv" and s.width == 64 and s.height == 48, "screen video: known codec, size from its first packet")
end
-- crafted files: VP6 (known, UNSUPPORTED, size from its key frame header), an enhanced FourCC tag, encrypted tags,
-- truncation, not FLV
local function flv(tags: { { any } }): buffer
local w = Bytes.writer(256)
w:string("FLV")
w:u8(1)
w:u8(1)
w:u32be(9)
w:u32be(0)
for _, tg in tags do
local body: string = tg[3]
w:u8(tg[1])
w:u24be(#body)
w:u24be(tg[2])
w:u8(0)
w:u24be(0)
w:string(body)
w:u32be(11 + #body)
end
return w:finish()
end
do
-- VP6: frame type 1 / codec 4, adjustment 0x00, key frame header (marker 0, profile 3: no offset), 2 x 3 MBs
local key = "\20\0" .. "\0\6" .. "\2\3\2\3" .. string.rep("\0", 8)
local inter = "\36\0" .. "\128" .. string.rep("\0", 8)
local b = flv({ { 9, 0, key }, { 9, 40, inter }, { 9, 80, key } })
local v = assert(F.video.open(b))
t:check(v.codec == "vp6f" and v.width == 48 and v.height == 32, "vp6: codec vp6f, " .. v.width .. "x" .. v.height .. " from its header")
t:check(v.track.config ~= nil and buffer.len(v.track.config) == 1, "vp6: the adjustment byte as config")
t:eq(v.demuxer:count(1), 3, "vp6: packets")
local p = assert(v.demuxer:get(1, 1))
t:check(buffer.len(p.data) == #key - 2 and p.keyframe, "vp6: packet after the adjustment byte, keyframe")
t:check(not assert(v.demuxer:get(1, 2)).keyframe, "vp6: inter frame")
local _, e = v:nextFrame()
t:check(e ~= nil and e.code == F.Err.UNSUPPORTED, "vp6: decoding UNSUPPORTED")
v.demuxer:seek(0.06)
t:eq(assert(v.demuxer:read(1)).pts, 0, "vp6: seek to the keyframe before")
-- remux of a copied VP6 track keeps the adjustment byte
local out = assert(F.save(v.demuxer, nil, { format = "flv" }))
local v2 = assert(F.video.open(out))
t:check(v2.codec == "vp6f" and v2.demuxer:count(1) == 3 and buffer.tostring(assert(v2.demuxer:get(1, 1)).data) == buffer.tostring(p.data), "vp6: remuxed")
-- enhanced FLV: an hvc1 sequence start and coded frames (with composition time)
local hv = flv({ { 9, 0, "\144hvc1" .. "\1\2\3" }, { 9, 0, "\145hvc1" .. "\0\0\40" .. "\9\9" }, { 9, 40, "\163hvc1" .. "\7\7\7" } })
local h = assert(Flv.demux(Bytes.reader(hv)))
local vt = assert(h:track("video"))
t:check(vt.codec == "hevc" and vt.config ~= nil and buffer.len(vt.config) == 3, "enhanced: hvc1 -> hevc, sequence start as config")
local p1, p2 = assert(h:get(1, 1)), assert(h:get(1, 2))
t:check(p1.pts == 40 and p1.dts == 0 and buffer.len(p1.data) == 2 and p1.keyframe, "enhanced: coded frames with composition time")
t:check(p2.pts == 40 and buffer.len(p2.data) == 3 and not p2.keyframe, "enhanced: coded frames X")
-- encrypted audio tags: the track says why
local enc = flv({ { 8 + 32, 0, "\47\1\2\3" } })
local d = assert(Flv.demux(Bytes.reader(enc)))
t:check(d:track("audio").unsupported ~= nil and d:count(2) == 0, "encrypted tags: dropped, track.unsupported")
-- truncated: the tags before the cut
local full = buffer.fromstring(byName["sorenson_mp3.flv"].data)
local cut = buffer.create(buffer.len(full) // 2)
buffer.copy(cut, 0, full, 0, buffer.len(cut))
local tr = assert(Flv.demux(Bytes.reader(cut)))
t:check(tr.meta.truncated == true and tr:count(1) > 0, "truncated file: meta.truncated, packets before the cut")
local _, e2 = Flv.demux(Bytes.reader(buffer.fromstring("RIFF0000AVI LIST")))
t:check(e2 ~= nil and e2.code == F.Err.CORRUPT, "not FLV: CORRUPT")
end
-- our writer: read back by ffprobe / ffmpeg (fixtures) and by our demuxer, packets equal to the source's
local SOURCES = { mp4 = Src.mp4, mkv = Src.mkv, ts = Src.ts }
for _, c in Mx do
local label = "write " .. c.name
if c.err then
t:check(c.source == "ts" and string.find(c.err, "UNSUPPORTED", 1, true) ~= nil, label .. ": " .. c.err)
else
local v = assert(C.open(c.data))
t:eq(#v.demuxer.tracks, #c.streams, label .. ": ffprobe sees the same tracks")
C.packets(t, v.demuxer, c, label)
if c.frames then
frames(v, c, label)
end
local at = v.demuxer:track("audio")
if at then
C.audio(t, v, c, label, EXACT_AUDIO[at.codec], 30)
end
-- the source's packets, byte for byte
local src = assert(C.open(SOURCES[c.source] or byName[c.source].data))
local a, b = src.demuxer, v.demuxer
local same = true
for _, kind in { "video", "audio" } do
local ta, tb = a:track(kind), b:track(kind)
if (ta == nil) ~= (tb == nil) then
same = false
elseif ta and tb then
if a:count(ta.id) ~= b:count(tb.id) then
same = false
else
for k = 1, a:count(ta.id) do
local p, q = assert(a:get(ta.id, k)), assert(b:get(tb.id, k))
if buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then
same = false
end
end
end
end
end
if c.name == "ts_aac.flv" then
-- MPEG-TS AAC: ADTS frames re-framed as raw frames with a made AudioSpecificConfig
local bt = assert(b:track("audio"))
t:check(bt.codec == "aac" and bt.config ~= nil and b:count(bt.id) > a:count(assert(a:track("audio")).id), label .. ": ADTS split into raw AAC frames")
else
t:check(same, label .. ": the source's packets (" .. c.source .. ")")
end
local md = b.meta.metadata
t:check(md and md.encoder == "formats-luau" and md.filesize == #c.data, label .. ": onMetaData encoder and file size")
end
end
-- fuzz
local samples = {}
for _, n in { "sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "screen.flv" } do
local d = byName[n].data
table.insert(samples, string.sub(d, 1, math.min(#d, 30000)))
end
t:fuzz("open", C.fuzzOpen(Flv), samples, { mutations = 6, garbage = 100 })
t:done()