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

+34
View File
@@ -1736,3 +1736,37 @@ do
end
print(string.format("%-8s %-30s %8.2f ms %7.1f x realtime", runtime, "render 669 / med", best * 1000, frames / 44100 / best))
end
-- ------------------------------------------------------------------------------------------- ws-video2-flv: fps
do
-- H.263 / Sorenson Spark (codecs/video/H263, tools/fixtures/h263.py): CIF mandelbrot zooms (1 Mbit/s, an I picture
-- every 12), one picture per decode, planes only (frameImage copies excluded) and with the yuv420p Image copies
local H263 = require("@formats/codecs/video/H263")
local Base64 = require("@formats/core/Base64")
local HB = require("@tests/gen/h263_bench")
local function run(tag: string)
for _, c in HB do
local file = Base64.decode(c.file) :: buffer
for _, images in { false, true } do
local n = #c.units
local dt = bench(string.format("%s %dx%d%s%s", c.name, c.width, c.height, if images then " +img" else "", tag), 3, c.width * c.height * 3 // 2 * n, function()
local dec = H263.new({ flv = c.flv })
for _, u in c.units do
if images then
dec:image(file, u[1], u[2])
else
dec:decode(file, u[1], u[2])
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. n .. " frames)", n / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
+43
View File
@@ -0,0 +1,43 @@
-- tools/fixtures/_flv_encode: run by tools/fixtures/flv.py (luau, from the repo root) so ffprobe / ffmpeg can check our
-- FLV writer: remuxes FLV fixtures (tests/gen/flv_cases) and the MP4 / Matroska / MPEG-TS sources (tests/gen/flv_src)
-- and prints "<name> <source> <hex>" lines (or "<name> <source> ERR <message>").
local F = require("@formats")
local Cases = require("@tests/gen/flv_cases")
local Src = require("@tests/gen/flv_src")
local function hex(b: buffer): string
local t = table.create(buffer.len(b))
for i = 0, buffer.len(b) - 1 do
t[i + 1] = string.format("%02x", buffer.readu8(b, i))
end
return table.concat(t)
end
local function find(name: string): string
for _, c in Cases do
if c.name == name then
return c.data
end
end
error("no fixture " .. name)
end
local JOBS = {
{ "remux_h264_aac.flv", "h264_aac.flv", find("h264_aac.flv") },
{ "remux_sorenson_mp3.flv", "sorenson_mp3.flv", find("sorenson_mp3.flv") },
{ "remux_pcm.flv", "sorenson_pcm.flv", find("sorenson_pcm.flv") },
{ "remux_screen.flv", "screen.flv", find("screen.flv") },
{ "mp4_h264_aac.flv", "mp4", Src.mp4 },
{ "mkv_h264_mp3.flv", "mkv", Src.mkv },
{ "ts_h264_aac.flv", "ts", Src.ts },
{ "ts_aac.flv", "ts", Src.ts, { video = false } }, -- ADTS AAC re-framed
}
for _, j in JOBS do
local name, source, data = j[1], j[2], j[3]
local out, err = F.convert(buffer.fromstring(data), "flv", j[4])
if out then
print(name .. " " .. source .. " " .. hex(out))
else
print(name .. " " .. source .. " ERR " .. tostring(err))
end
end
+29
View File
@@ -0,0 +1,29 @@
# Docs inputs for the FLV / H.263 sections of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them):
# tiny ffmpeg clips (testsrc 64x48, 10 frames at 10 fps, with a sine track): FLV with Sorenson Spark + MP3, a 3GP with
# H.263 (QCIF, the H.263 size closest to the clip) and AAC.
# tests/gen/docs_flv.luau { files = { [name] = bytes }, vars = { flvBytes = "clip.flv", h263Bytes = "clip.3gp" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_flv_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
files = {}
with tempfile.TemporaryDirectory() as d:
for name, size, codec in (
("clip.flv", "64x48", ["-c:v", "flv", "-g", "5", "-c:a", "libmp3lame", "-b:a", "64k"]),
("clip.3gp", "176x144", ["-c:v", "h263", "-g", "5", "-c:a", "aac", "-b:a", "32k", "-ar", "22050"]),
):
src = ["-f", "lavfi", "-i", "testsrc=size=%s:rate=10:duration=1" % size,
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1"]
out = os.path.join(d, name)
argv = ["-v", "error", "-y"] + src + codec + ["-shortest", out]
if shutil.which("ffmpeg"):
subprocess.run(["ffmpeg"] + argv, check=True, capture_output=True)
else:
ctx.nix("ffmpeg", ["ffmpeg"] + argv)
files[name] = open(out, "rb").read()
dc.emit_inputs(ctx, files, {"flvBytes": "clip.flv", "h263Bytes": "clip.3gp"})
+86
View File
@@ -0,0 +1,86 @@
# FLV fixtures (tools/fixtures.py): files made by ffmpeg (Sorenson Spark + MP3 / PCM s16 / PCM u8 / Flash ADPCM /
# Nellymoser / Speex / A-law, H.264 with B-frames + AAC, Flash screen video), with ffprobe's streams and packets,
# ffmpeg's frames (CRC-32 of `-flags +bitexact -idct int` decoding; the first two raw) and audio (f32); then our FLV
# writer (tools/fixtures/_flv_encode.luau) remuxes FLV, MP4, Matroska and MPEG-TS sources and each output is probed,
# decoded and emitted the same way, so the test can read our files with our demuxer and compare them with ffmpeg's view.
# tests/gen/flv_cases.luau { { name, data, streams, packets, frames, yuv, pcm, pcmBytes } }
# tests/gen/flv_src.luau { mp4 = H.264 + AAC MP4, mkv = H.264 + MP3 Matroska, ts = H.264 + AAC MPEG-TS }
# tests/gen/flv_mux.luau { { name, source, data, streams, packets, frames, pcm, pcmBytes } | { name, err } }
import importlib.util, os, shutil, subprocess, tempfile
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
V = importlib.util.module_from_spec(_spec)
_spec.loader.exec_module(V)
INPUTS = ["tools/fixtures/_video.py", "tools/fixtures/_flv_encode.luau", "src/Formats/video/flv", "src/Formats/codecs/video/Video"]
SRC = ["-f", "lavfi", "-i", "testsrc2=size=160x120:rate=12"]
def aud(rate, ch=1, freq=550):
return ["-f", "lavfi", "-i", "sine=frequency=%d:sample_rate=%d" % (freq, rate), "-ac", str(ch)]
def case(tmp, name, decode_audio=True):
path = os.path.join(tmp, name)
c = {"name": name, "data": open(path, "rb").read(), "streams": V.streams(path), "packets": V.packets(path)}
vs = [s for s in c["streams"] if s["kind"] == "video"]
if vs and vs[0]["codec"] in ("flv1", "h264"):
w, h = vs[0]["width"], vs[0]["height"]
raw = V.ffmpeg(["-flags", "+bitexact", "-idct", "int", "-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f",
"rawvideo", "-pix_fmt", "yuv420p", "-"])
n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
frames = [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)]
c["frames"] = [V.crc(f) for f in frames]
c["yuv"] = frames[:2]
if decode_audio and any(s["kind"] == "audio" for s in c["streams"]):
pcm = V.pcm_f32(path)
c["pcm"] = pcm[:8192 * 4]
c["pcmBytes"] = len(pcm)
return c
def generate(ctx):
tmp = tempfile.mkdtemp(prefix="flvfx_")
ff = lambda *a: V.ffmpeg(list(a), cwd=tmp)
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "flv", "-b:v", "300k", "-g", "6", "-c:a", "libmp3lame", "-b:a", "64k", "sorenson_mp3.flv")
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", "-b:a", "96k",
"h264_aac.flv")
ff(*SRC, *aud(22050, 2), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_s16le", "sorenson_pcm.flv")
ff(*SRC, *aud(11025), "-t", "1", "-c:v", "flv", "-g", "12", "-c:a", "pcm_u8", "sorenson_pcm8.flv")
ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "adpcm_swf", "sorenson_adpcm.flv")
ff(*SRC, *aud(22050), "-t", "0.5", "-c:v", "flv", "-c:a", "nellymoser", "sorenson_nelly.flv")
ff(*SRC, *aud(16000), "-t", "0.5", "-c:v", "flv", "-c:a", "libspeex", "sorenson_speex.flv")
ff(*SRC, *aud(8000), "-t", "0.5", "-c:v", "flv", "-c:a", "pcm_alaw", "sorenson_alaw.flv")
ff("-f", "lavfi", "-i", "testsrc2=size=64x48:rate=10", "-t", "0.5", "-c:v", "flashsv", "screen.flv")
ff(*aud(44100, 2), "-t", "0.5", "-c:a", "libmp3lame", "audio_only.flv")
names = ["sorenson_mp3.flv", "h264_aac.flv", "sorenson_pcm.flv", "sorenson_pcm8.flv", "sorenson_adpcm.flv",
"sorenson_nelly.flv", "sorenson_speex.flv", "sorenson_alaw.flv", "screen.flv", "audio_only.flv"]
cases = [case(tmp, n) for n in names]
ctx.emit("flv_cases", cases)
# sources for the writer
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "2", "-g", "6", "-c:a", "aac", "src.mp4")
ff(*SRC, *aud(44100, 2), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-bf", "0", "-g", "12", "-c:a", "libmp3lame",
"src.mkv")
ff(*SRC, *aud(44100), "-t", "1", "-c:v", "libx264", "-preset", "veryfast", "-c:a", "aac", "src.ts")
srcs = {k: open(os.path.join(tmp, "src." + k), "rb").read() for k in ("mp4", "mkv", "ts")}
ctx.emit("flv_src", srcs)
luau = os.environ.get("LUAU") or shutil.which("luau")
cmd = [luau, "tools/fixtures/_flv_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_flv_encode.luau"]
out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode()
mux = []
for line in out.split("\n"):
if not line.strip():
continue
name, source, rest = line.split(" ", 2)
if rest.startswith("ERR "):
mux.append({"name": name, "source": source, "err": rest[4:]})
continue
open(os.path.join(tmp, name), "wb").write(bytes.fromhex(rest))
c = case(tmp, name)
c["source"] = source
c.pop("yuv", None)
mux.append(c)
ctx.emit("flv_mux", mux)
+190
View File
@@ -0,0 +1,190 @@
# H.263 / Sorenson Spark fixtures for codecs/video/H263 (tools/fixtures.py): streams from ffmpeg's encoders (h263:
# sub-QCIF .. 4CIF, GOB headers, adaptive quantisation (DQUANT), low and high bitrates; h263p: PLUSPTYPE with custom
# sizes, the rounding type, unrestricted vectors, slice structure; flv: Sorenson Spark with its standard, 8-bit and 16-bit custom
# sizes, 11-bit escapes, disposable inter pictures patched in), high and low motion (testsrc2, mandelbrot, scroll),
# each with `ffmpeg -flags +bitexact -idct int` decoding as the reference (the integer IDCT codecs/video/Dsp
# reproduces; bitexact: ffmpeg's x86 half-sample averages without rounding are approximations otherwise).
# tests/gen/h263_<name>.luau { name, flv, width, height, frames, file (base64), units = { { offset, length } } (one
# picture each), crcs = { { y, u, v } } (CRC-32 of each frame's planes), first (the first
# yuv frame, base64 zlib) }
# tests/gen/h263_bad.luau { aic, obmc: one picture each with an unsupported H.263+ option (base64) }
# tests/gen/h263_bench.luau { { name, flv, width, height, file, units } }: CIF H.263 and Sorenson Spark
import base64, os, shutil, subprocess, tempfile, zlib
def b64(b):
return base64.b64encode(b).decode()
def z64(b):
return base64.b64encode(zlib.compress(b, 9)).decode()
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def src(kind, w, h, t, rate=25, vf=None):
s = "%s=size=%dx%d:rate=%d" % (kind, w, h, rate)
if vf:
s += "," + vf
return ["-f", "lavfi", "-i", s, "-t", str(t)]
H263 = ["-c:v", "h263", "-f", "h263"]
H263P = ["-threads", "1", "-c:v", "h263p", "-f", "rawvideo"]
FLV = ["-c:v", "flv", "-f", "flv"]
# name: (ffmpeg input + encoder args, flv)
CASES = {
"qcif": (src("testsrc2", 176, 144, 1.0) + ["-b:v", "200k", "-g", "12"] + H263, False),
"cif_mandel": (src("mandelbrot", 352, 288, 0.6) + ["-b:v", "800k", "-g", "8"] + H263, False),
"sqcif_scroll": (src("testsrc2", 128, 96, 1.0, vf="scroll=h=0.05:v=0.03") + ["-q:v", "4", "-g", "30"] + H263, False),
"qcif_q1": (src("mandelbrot", 176, 144, 0.4) + ["-qmin", "1", "-q:v", "1", "-g", "5"] + H263, False),
"qcif_aq": (src("testsrc2", 176, 144, 0.8, vf="scroll=h=0.01") + ["-b:v", "60k", "-lumi_mask", "0.3", "-dark_mask", "0.3",
"-p_mask", "0.2", "-g", "20"] + H263, False),
"cif_gob": (src("testsrc2", 352, 288, 0.6, vf="scroll=v=0.02") + ["-b:v", "500k", "-ps", "300", "-g", "10"] + H263, False),
"4cif_gob": (src("mandelbrot", 704, 576, 0.16) + ["-b:v", "2M", "-ps", "1200", "-g", "4"] + H263, False),
"plus_custom": (src("testsrc2", 320, 240, 0.8, vf="scroll=h=0.02:v=0.01") + ["-b:v", "300k", "-g", "15"] + H263P, False),
"plus_odd": (src("mandelbrot", 196, 148, 0.6) + ["-b:v", "250k", "-g", "8"] + H263P, False),
"plus_umv": (src("testsrc2", 200, 152, 0.8, vf="scroll=h=0.06:v=0.04") + ["-umv", "1", "-q:v", "5", "-g", "25"] + H263P, False),
"plus_slices": (src("mandelbrot", 352, 288, 0.48) + ["-b:v", "600k", "-g", "6"] + H263P + ["-threads", "4", "-slices", "4"], False),
"plus_slices_umv": (src("testsrc2", 176, 144, 0.8, vf="scroll=h=-0.04:v=0.05") + ["-umv", "1", "-q:v", "4", "-g", "20"] + H263P
+ ["-threads", "3", "-slices", "3", "-ps", "200"], False),
"flv_320": (src("testsrc2", 320, 240, 1.0) + ["-b:v", "300k", "-g", "12"] + FLV, True),
"flv_odd": (src("mandelbrot", 100, 75, 0.6) + ["-b:v", "150k", "-g", "8"] + FLV, True),
"flv_wide": (src("testsrc2", 400, 224, 0.4, vf="scroll=h=0.03") + ["-b:v", "400k", "-g", "6"] + FLV, True),
"flv_q1": (src("mandelbrot", 160, 120, 0.4) + ["-qmin", "1", "-q:v", "1", "-g", "4"] + FLV, True),
"flv_scroll": (src("testsrc2", 176, 144, 1.0, vf="scroll=h=0.05:v=-0.04") + ["-q:v", "6", "-g", "50"] + FLV, True),
}
def h263_units(es):
starts = []
i = 0
while True:
i = es.find(b"\x00\x00", i)
if i < 0 or i + 2 >= len(es):
break
if es[i + 2] & 0xFC == 0x80:
starts.append(i)
i += 3
else:
i += 1
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
def flv_tags(data):
"""the video tags of an FLV file: [(offset of the tag header, payload offset, payload length)]"""
p = int.from_bytes(data[5:9], "big") + 4
out = []
while p + 11 <= len(data):
kind = data[p] & 0x1F
size = int.from_bytes(data[p + 1:p + 4], "big")
if kind == 9 and size > 1:
out.append((p, p + 12, size - 1))
p += 11 + size + 4
return out
def flv_disposable(data):
"""every third inter picture of a Sorenson FLV marked disposable (tag frame type 3, picture type 2)"""
b = bytearray(data)
inter = 0
for tag, off, n in flv_tags(data):
if b[tag + 11] >> 4 != 2:
continue
inter += 1
if inter % 3 != 0:
continue
b[tag + 11] = (3 << 4) | (b[tag + 11] & 15)
# picture size field: bits 30..32 after the start of the picture
bits = int.from_bytes(b[off:off + 8], "big")
fmt = (bits >> (64 - 33)) & 7
p = 33 + (16 if fmt == 0 else 32 if fmt == 1 else 0) # the picture type's first bit
byte, bit = p // 8, p % 8
word = int.from_bytes(b[off + byte:off + byte + 2], "big")
shift = 16 - bit - 2
word = (word & ~(3 << shift)) | (2 << shift)
b[off + byte:off + byte + 2] = word.to_bytes(2, "big")
return bytes(b)
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
ffprobe = shutil.which("ffprobe") or os.path.join(os.path.dirname(ffmpeg), "ffprobe")
def ff(args):
subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True)
def size(path):
r = subprocess.run([ffprobe, "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height",
"-of", "csv=p=0", path], check=True, capture_output=True)
return tuple(int(x) for x in r.stdout.decode().strip().split(",")[:2])
def reference(path):
out = path + ".yuv"
ff(["-flags", "+bitexact", "-idct", "int", "-i", path, "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "yuv420p", out])
return open(out, "rb").read()
def emit(name, path, flv):
data = open(path, "rb").read()
if flv:
tags = flv_tags(data)
file = b"".join(data[o:o + n] for _, o, n in tags)
units, o = [], 0
for _, _, n in tags:
units.append([o, n])
o += n
else:
file, units = data, h263_units(data)
w, h = size(path)
yuv = reference(path)
cw, ch = (w + 1) // 2, (h + 1) // 2
fs = w * h + 2 * cw * ch
n = len(yuv) // fs
crcs = []
for k in range(n):
f = yuv[k * fs:(k + 1) * fs]
crcs.append([zlib.crc32(f[:w * h]), zlib.crc32(f[w * h:w * h + cw * ch]), zlib.crc32(f[w * h + cw * ch:])])
assert n == len(units), "h263 %s: %d frames for %d pictures" % (name, n, len(units))
ctx.emit("h263_" + name, {"name": name, "flv": flv, "width": w, "height": h, "frames": n, "file": b64(file),
"units": units, "crcs": crcs, "first": z64(yuv[:fs])})
return file, units
with tempfile.TemporaryDirectory(prefix="formats-h263-") as tmp:
for name, (args, flv) in CASES.items():
path = os.path.join(tmp, name + (".flv" if flv else ".h263"))
ff(args + [path])
emit(name, path, flv)
# Sorenson disposable inter pictures (ffmpeg's encoder writes none): patched into a stream; ffmpeg's decoder
# does not keep them as references either
path = os.path.join(tmp, "disp.flv")
ff(src("testsrc2", 160, 120, 1.0, vf="scroll=h=0.02") + ["-b:v", "200k", "-g", "20"] + FLV + [path])
patched = os.path.join(tmp, "disposable.flv")
open(patched, "wb").write(flv_disposable(open(path, "rb").read()))
emit("flv_disposable", patched, True)
# unsupported H.263+ options: one picture each
bad = {}
for name, extra in (("aic", ["-flags", "+aic"]), ("obmc", ["-obmc", "1"])):
path = os.path.join(tmp, name + ".h263")
ff(src("testsrc2", 176, 144, 0.04) + extra + H263P + [path])
bad[name] = b64(open(path, "rb").read())
ctx.emit("h263_bad", bad)
bench = []
for name, args, flv in (("h263", H263, False), ("flv1", FLV, True)):
path = os.path.join(tmp, "bench_" + name + (".flv" if flv else ".h263"))
ff(src("mandelbrot", 352, 288, 1.2) + ["-b:v", "1M", "-g", "12"] + args + [path])
data = open(path, "rb").read()
if flv:
tags = flv_tags(data)
file = b"".join(data[o:o + n] for _, o, n in tags)
units, o = [], 0
for _, _, n in tags:
units.append([o, n])
o += n
else:
file, units = data, h263_units(data)
bench.append({"name": name, "flv": flv, "width": 352, "height": 288, "file": b64(file), "units": units})
ctx.emit("h263_bench", bench)