ws-video: merge ws/video-codecs (codecs/Jpeg, codecs/Mpeg1)
This commit is contained in:
commit
dac404aa52
22 files changed
+3540
-236
No files matched your search
@@ -773,4 +773,54 @@ do
|
||||
end
|
||||
realtime("tracker 32 ch (mod)", song("mod", false), 32)
|
||||
realtime("tracker 32 ch + NNA, filters", song("it", true), 64)
|
||||
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
|
||||
do
|
||||
local Jpeg = require("@formats/codecs/Jpeg")
|
||||
local Mpeg1 = require("@formats/codecs/Mpeg1")
|
||||
local Base64 = require("@formats/core/Base64")
|
||||
local Types = require("@formats/Types")
|
||||
local MB = require("@tests/gen/mjpeg_bench")
|
||||
local M1 = require("@tests/gen/mpeg1_bench")
|
||||
-- best of n runs of f (which handles `frames` frames): ms per frame and frames per second
|
||||
local function fps(label: string, n: number, frames: number, f: () -> ())
|
||||
f()
|
||||
local dt = math.huge
|
||||
for _ = 1, n do
|
||||
local t0 = os.clock()
|
||||
f()
|
||||
dt = math.min(dt, os.clock() - t0)
|
||||
end
|
||||
print(string.format("%-8s %-30s %8.2f ms %7.1f fps", runtime, label, dt * 1000 / frames, frames / dt))
|
||||
end
|
||||
for _, c in MB.frames do
|
||||
local b = Base64.decode(c.data) :: buffer
|
||||
local img = assert(Jpeg.decode(b, 0, nil, { yuv = true }))
|
||||
assert(Crc32.of(img.pixels) == c.yuv, "mjpeg bench: " .. c.name .. " does not match TurboJPEG")
|
||||
fps("mjpeg decode yuv " .. c.name, 10, 1, function()
|
||||
Jpeg.decode(b, 0, nil, { yuv = true })
|
||||
end)
|
||||
fps("mjpeg decode rgba " .. c.name, 10, 1, function()
|
||||
Jpeg.decode(b)
|
||||
end)
|
||||
end
|
||||
for _, s in MB.sources do
|
||||
local img = Types.Image.new(s.width, s.height, "yuv420p")
|
||||
img.pixels = assert(Deflate.zlib(Base64.decode(s.yuv) :: buffer))
|
||||
fps(string.format("mjpeg encode yuv %dx%d q85", s.width, s.height), 5, 1, function()
|
||||
Jpeg.encode(img, { quality = 85 })
|
||||
end)
|
||||
end
|
||||
for _, s in M1 do
|
||||
local file = Base64.decode(s.file) :: buffer
|
||||
for _, rgba in { false, true } do
|
||||
fps(string.format("mpeg1 decode %s %dx%d", if rgba then "rgba" else "yuv", s.width, s.height), 3, #s.units, function()
|
||||
local dec = Mpeg1.new({ reorder = true, rgba = rgba })
|
||||
for i, u in s.units do
|
||||
dec:decode(file, u[1], u[2], i)
|
||||
end
|
||||
while dec:flush() do
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -0,0 +1,317 @@
|
||||
# Motion-JPEG fixtures for codecs/Jpeg (tools/fixtures.py): ffmpeg's mjpeg encoder (testsrc2 / mandelbrot sources,
|
||||
# yuvj420p / yuvj422p / yuvj444p, odd sizes) split into its JPEG frames, and references for each frame:
|
||||
# yuv CRC-32 of the yuv420p planes codecs/Jpeg must produce with { yuv = true }: libjpeg-turbo's own IDCT planes
|
||||
# (TurboJPEG tj3DecompressToYUV8 through ctypes, the islow IDCT), cropped, 4:2:2 chroma row pairs averaged
|
||||
# ((a + b + 1) >> 1), 4:4:4 chroma 2 x 2 averaged ((a + b + c + d + 2) >> 2): bit-exact
|
||||
# rgba CRC-32 of djpeg -dct int (bit-exact)
|
||||
# ff for the first frame of each stream: ffmpeg's own decode as yuvj420p and rgba (PSNR thresholds: ffmpeg's
|
||||
# IDCT and its swscale conversions differ from libjpeg's; rgba for the small streams and one 320x240)
|
||||
# Variants: frames written with ffmpeg's default (annex K) Huffman tables and their DHT segments stripped, as
|
||||
# Motion-JPEG in AVI leaves them out; an AVI1 APP0 segment and junk after EOI; an interlaced frame (two fields,
|
||||
# each its own half-height JPEG with an AVI1 segment of polarity 1, back to back).
|
||||
# tests/gen/mjpeg_cases.luau { streams = { { name, width, height, sampling, frames = { { data, yuv, rgba } },
|
||||
# ff = { yuv, rgba? } } }, fields = { data, width, height, yuv, rgba, src } }
|
||||
# tests/gen/mjpeg_enc.luau yuv420p sources and what tj3CompressFromYUV8 writes for them at a quality (our
|
||||
# encoder must write the same bytes), with djpeg's CRC and ffmpeg's PSNR of that file
|
||||
# tests/gen/mjpeg_bench.luau 320x240 and 640x480 frames (4:2:0, 4:2:2) and yuv420p sources
|
||||
# Binary fields are base64 (JPEG data) or base64 of zlib data (raw planes / pixels, inflated with codecs/Deflate):
|
||||
# Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33.
|
||||
import base64, ctypes, math, os, shutil, subprocess, tempfile, zlib
|
||||
|
||||
FF = ["-hide_banner", "-loglevel", "error", "-y"]
|
||||
|
||||
|
||||
def b64(b):
|
||||
return base64.b64encode(b).decode()
|
||||
|
||||
|
||||
def z64(b):
|
||||
return base64.b64encode(zlib.compress(b, 9)).decode()
|
||||
|
||||
|
||||
def tool(ctx, pkg, name):
|
||||
p = shutil.which(name)
|
||||
if p:
|
||||
return p
|
||||
return ctx.nix(pkg, ["sh", "-c", "command -v " + name]).decode().strip()
|
||||
|
||||
|
||||
def store(attr):
|
||||
return subprocess.run(["nix", "build", "nixpkgs#" + attr, "--no-link", "--print-out-paths"], check=True,
|
||||
capture_output=True, text=True).stdout.strip().split("\n")[0]
|
||||
|
||||
|
||||
class TurboJpeg:
|
||||
"""the TurboJPEG 3 API (libjpeg-turbo) through ctypes: raw YUV planes in and out"""
|
||||
|
||||
def __init__(self):
|
||||
lib = ctypes.CDLL(os.path.join(store("libjpeg_turbo.out"), "lib", "libturbojpeg.so"))
|
||||
lib.tj3Init.restype = ctypes.c_void_p
|
||||
lib.tj3Init.argtypes = [ctypes.c_int]
|
||||
lib.tj3Set.argtypes = [ctypes.c_void_p, ctypes.c_int, ctypes.c_int]
|
||||
lib.tj3Get.argtypes = [ctypes.c_void_p, ctypes.c_int]
|
||||
lib.tj3DecompressHeader.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t]
|
||||
lib.tj3DecompressToYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, ctypes.c_int]
|
||||
lib.tj3CompressFromYUV8.argtypes = [ctypes.c_void_p, ctypes.c_char_p, ctypes.c_int, ctypes.c_int, ctypes.c_int,
|
||||
ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t)]
|
||||
lib.tj3Free.argtypes = [ctypes.c_void_p]
|
||||
self.lib = lib
|
||||
self.dec = lib.tj3Init(1)
|
||||
self.enc = lib.tj3Init(0)
|
||||
|
||||
def planes(self, jpeg):
|
||||
"""-> w, h, subsamp (0 444, 1 422, 2 420), Y, Cb, Cr (TurboJPEG's unpadded-alignment plane layout)"""
|
||||
L = self.lib
|
||||
assert L.tj3DecompressHeader(self.dec, jpeg, len(jpeg)) == 0
|
||||
w, h, ss = L.tj3Get(self.dec, 5), L.tj3Get(self.dec, 6), L.tj3Get(self.dec, 4)
|
||||
mw, mh = {0: (1, 1), 1: (2, 1), 2: (2, 2)}[ss]
|
||||
pw, ph = -(-w // mw) * mw, -(-h // mh) * mh
|
||||
cw, ch = pw // mw, ph // mh
|
||||
out = ctypes.create_string_buffer(pw * ph + 2 * cw * ch)
|
||||
assert L.tj3DecompressToYUV8(self.dec, jpeg, len(jpeg), out, 1) == 0
|
||||
raw = out.raw
|
||||
return w, h, ss, (raw[:pw * ph], pw), (raw[pw * ph:pw * ph + cw * ch], cw, ch), (raw[pw * ph + cw * ch:], cw, ch)
|
||||
|
||||
def yuv420(self, jpeg):
|
||||
"""what codecs/Jpeg { yuv = true } must produce for this frame"""
|
||||
w, h, ss, (Y, pw), cb, cr = self.planes(jpeg)
|
||||
out = bytearray()
|
||||
for y in range(h):
|
||||
out += Y[y * pw:y * pw + w]
|
||||
ow, oh = (w + 1) // 2, (h + 1) // 2
|
||||
for P, cw, ch in (cb, cr):
|
||||
for y in range(oh):
|
||||
if ss == 2:
|
||||
out += P[y * cw:y * cw + ow]
|
||||
elif ss == 1:
|
||||
a = P[2 * y * cw:2 * y * cw + ow]
|
||||
b = P[(2 * y + 1) * cw:(2 * y + 1) * cw + ow] if 2 * y + 1 < ch else a
|
||||
out += bytes((p + q + 1) >> 1 for p, q in zip(a, b))
|
||||
else:
|
||||
r0 = P[2 * y * cw:2 * y * cw + cw]
|
||||
r1 = P[(2 * y + 1) * cw:(2 * y + 1) * cw + cw] if 2 * y + 1 < ch else r0
|
||||
row = bytearray()
|
||||
for x in range(ow):
|
||||
x1 = min(2 * x + 1, w - 1)
|
||||
row.append((r0[2 * x] + r0[x1] + r1[2 * x] + r1[x1] + 2) >> 2)
|
||||
out += row
|
||||
return bytes(out)
|
||||
|
||||
def compress420(self, yuv, w, h, quality):
|
||||
"""yuv420p (w x h luma) -> tj3CompressFromYUV8's JPEG; TurboJPEG wants the luma plane padded to even sizes"""
|
||||
pw, ph = w + (w & 1), h + (h & 1)
|
||||
Y = yuv[:w * h]
|
||||
buf = bytearray()
|
||||
for y in range(ph):
|
||||
r = Y[min(y, h - 1) * w:min(y, h - 1) * w + w]
|
||||
buf += r + r[-1:] * (pw - w)
|
||||
buf += yuv[w * h:]
|
||||
L = self.lib
|
||||
L.tj3Set(self.enc, 3, quality)
|
||||
L.tj3Set(self.enc, 4, 2)
|
||||
p, n = ctypes.c_void_p(), ctypes.c_size_t(0)
|
||||
assert L.tj3CompressFromYUV8(self.enc, bytes(buf), w, 1, h, ctypes.byref(p), ctypes.byref(n)) == 0
|
||||
data = ctypes.string_at(p, n.value)
|
||||
L.tj3Free(p)
|
||||
return data
|
||||
|
||||
|
||||
def split(stream):
|
||||
"""a Motion-JPEG elementary stream -> its JPEG frames (SOI .. EOI)"""
|
||||
frames, pos = [], 0
|
||||
while True:
|
||||
s = stream.find(b"\xff\xd8", pos)
|
||||
if s < 0:
|
||||
return frames
|
||||
p = s + 2
|
||||
while True:
|
||||
m = stream[p + 1]
|
||||
if m == 0xD9:
|
||||
p += 2
|
||||
break
|
||||
ln = (stream[p + 2] << 8) | stream[p + 3]
|
||||
p += 2 + ln
|
||||
if m == 0xDA:
|
||||
while not (stream[p] == 0xFF and stream[p + 1] not in (0,) and not 0xD0 <= stream[p + 1] <= 0xD7):
|
||||
p += 1
|
||||
frames.append(stream[s:p])
|
||||
pos = p
|
||||
|
||||
|
||||
def strip_dht(jpeg):
|
||||
out, pos = bytearray(jpeg[:2]), 2
|
||||
while pos < len(jpeg):
|
||||
m = jpeg[pos + 1]
|
||||
if m == 0xDA:
|
||||
out += jpeg[pos:]
|
||||
break
|
||||
ln = (jpeg[pos + 2] << 8) | jpeg[pos + 3]
|
||||
if m != 0xC4:
|
||||
out += jpeg[pos:pos + 2 + ln]
|
||||
pos += 2 + ln
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def avi1(jpeg, polarity):
|
||||
"""an AVI1 APP0 segment right after SOI (polarity, 0, field size, field size less padding)"""
|
||||
n = len(jpeg) + 18
|
||||
body = b"AVI1" + bytes([polarity, 0]) + n.to_bytes(4, "big") + n.to_bytes(4, "big")
|
||||
return jpeg[:2] + b"\xff\xe0" + (len(body) + 2).to_bytes(2, "big") + body + jpeg[2:]
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
work = tempfile.mkdtemp(prefix="formats-mjpeg-")
|
||||
try:
|
||||
_generate(ctx, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, work):
|
||||
ffmpeg = tool(ctx, "ffmpeg", "ffmpeg")
|
||||
djpeg = os.path.join(os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v djpeg"]).decode().strip()), "djpeg")
|
||||
tj = TurboJpeg()
|
||||
W = lambda n: os.path.join(work, n)
|
||||
|
||||
def ff(*args):
|
||||
subprocess.run([ffmpeg] + FF + list(args), check=True, capture_output=True)
|
||||
|
||||
def source(src, w, h, frames, extra=()):
|
||||
# a raw yuv420p / yuv444p source scaled to w x h (ffmpeg's lavfi sources only make even sizes)
|
||||
sw, sh = w + (w & 1), h + (h & 1)
|
||||
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=25" % (src, sw, sh), "-frames:v", str(frames),
|
||||
"-vf", "scale=%d:%d" % (w, h)] + list(extra)
|
||||
|
||||
def rgba_crc(jpeg):
|
||||
p = W("f.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
r = subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout
|
||||
return zlib.crc32(rgba_of_pnm(r))
|
||||
|
||||
def rgba_of_pnm(d):
|
||||
# djpeg's "P6\n<w> <h>\n255\n" + RGB -> RGBA
|
||||
parts = d.split(maxsplit=3)
|
||||
w, h = int(parts[1]), int(parts[2])
|
||||
rgb = d[len(d) - w * h * 3:]
|
||||
out = bytearray(w * h * 4)
|
||||
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
|
||||
out[3::4] = b"\xff" * (w * h)
|
||||
return bytes(out)
|
||||
|
||||
def ffdecode(jpeg, fmt):
|
||||
p = W("ff.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
o = W("ff.raw")
|
||||
ff("-f", "mjpeg", "-i", p, "-f", "rawvideo", "-pix_fmt", fmt, o)
|
||||
return open(o, "rb").read()
|
||||
|
||||
streams = []
|
||||
|
||||
def stream(name, src, w, h, pix, nframes, encargs=(), mutate=None):
|
||||
out = W(name + ".mjpeg")
|
||||
ff(*source(src, w, h, nframes), "-pix_fmt", pix, "-c:v", "mjpeg", *encargs, "-f", "mjpeg", out)
|
||||
frames = split(open(out, "rb").read())
|
||||
assert len(frames) == nframes, (name, len(frames))
|
||||
entries = []
|
||||
for fr in frames:
|
||||
ref = fr
|
||||
data = mutate(fr) if mutate else fr
|
||||
entries.append({"data": b64(data), "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)})
|
||||
ref = {"yuv": z64(ffdecode(frames[0], "yuvj420p"))}
|
||||
if w * h <= 30000 or name == "testsrc_420": # keep tests/gen small: rgba for the small ones and one 320x240
|
||||
ref["rgba"] = z64(ffdecode(frames[0], "rgba"))
|
||||
streams.append({"name": name, "width": w, "height": h, "sampling": pix[4:7], "frames": entries, "ff": ref})
|
||||
|
||||
stream("testsrc_420", "testsrc2", 320, 240, "yuvj420p", 4, ("-q:v", "3"))
|
||||
stream("testsrc_422", "testsrc2", 320, 240, "yuvj422p", 4, ("-q:v", "3"))
|
||||
stream("mandel_444", "mandelbrot", 176, 144, "yuvj444p", 2, ("-q:v", "4"))
|
||||
stream("odd_420", "mandelbrot", 173, 97, "yuvj420p", 3, ("-q:v", "6"))
|
||||
stream("odd_422", "testsrc2", 97, 61, "yuvj422p", 3, ("-q:v", "2"))
|
||||
stream("odd_444", "testsrc2", 33, 17, "yuvj444p", 2, ("-q:v", "2"))
|
||||
stream("q31_420", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "31"))
|
||||
# Motion-JPEG as AVI stores it: the annex K tables left out
|
||||
stream("nodht_420", "mandelbrot", 320, 240, "yuvj420p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
|
||||
stream("nodht_422", "testsrc2", 176, 144, "yuvj422p", 3, ("-q:v", "4", "-huffman", "default"), strip_dht)
|
||||
# an AVI1 segment (progressive, polarity 0) and padding / junk after EOI
|
||||
stream("avi1_junk", "testsrc2", 160, 120, "yuvj420p", 2, ("-q:v", "5"),
|
||||
lambda f: avi1(f, 0) + b"\0\0\0\0\xff\xd9junk after the image\xff\xd8")
|
||||
|
||||
# an interlaced frame: two fields of 320 x 120, each its own JPEG with AVI1 polarity 1, back to back
|
||||
full = W("full.yuv")
|
||||
ff(*source("testsrc2", 320, 240, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", full)
|
||||
fy = open(full, "rb").read()
|
||||
fw, fh = 320, 240
|
||||
fields, fsrc = [], []
|
||||
for k in range(2):
|
||||
rows = b"".join(fy[y * fw:(y + 1) * fw] for y in range(k, fh, 2))
|
||||
cw = fw // 2
|
||||
chroma = b""
|
||||
for pl in range(2):
|
||||
base = fw * fh + pl * cw * (fh // 2)
|
||||
chroma += b"".join(fy[base + y * cw:base + (y + 1) * cw] for y in range(k, fh // 2, 2))
|
||||
p = W("field%d.yuv" % k)
|
||||
open(p, "wb").write(rows + chroma)
|
||||
o = W("field%d.jpg" % k)
|
||||
ff("-f", "rawvideo", "-pix_fmt", "yuvj420p", "-s", "%dx%d" % (fw, fh // 2), "-i", p, "-pix_fmt", "yuvj420p",
|
||||
"-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
|
||||
fields.append(open(o, "rb").read())
|
||||
data = avi1(fields[0], 1) + b"\0" * 7 + avi1(fields[1], 1)
|
||||
|
||||
def weave(a, b, w, hf, bpp):
|
||||
out = bytearray()
|
||||
for y in range(2 * hf):
|
||||
src, k = (a, y // 2) if y % 2 == 0 else (b, y // 2)
|
||||
out += src[k * w * bpp:(k + 1) * w * bpp]
|
||||
return bytes(out)
|
||||
|
||||
ya, yb = tj.yuv420(fields[0]), tj.yuv420(fields[1])
|
||||
hf, cw, chf = fh // 2, fw // 2, fh // 4
|
||||
wy = weave(ya[:fw * hf], yb[:fw * hf], fw, hf, 1)
|
||||
for pl in range(2):
|
||||
o = fw * hf + pl * cw * chf
|
||||
wy += weave(ya[o:o + cw * chf], yb[o:o + cw * chf], cw, chf, 1)
|
||||
|
||||
def rgba_raw(jpeg):
|
||||
p = W("f.jpg")
|
||||
open(p, "wb").write(jpeg)
|
||||
return rgba_of_pnm(subprocess.run([djpeg, "-dct", "int", "-pnm", p], check=True, capture_output=True).stdout)
|
||||
|
||||
wr = weave(rgba_raw(fields[0]), rgba_raw(fields[1]), fw, hf, 4)
|
||||
ctx.emit("mjpeg_cases", {"streams": streams, "fields": {"data": b64(data), "width": fw, "height": fh,
|
||||
"yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": z64(fy)}})
|
||||
|
||||
# the encoder: yuv420p sources, byte-identical with tj3CompressFromYUV8
|
||||
enc = []
|
||||
for name, src, w, h, qs in (("testsrc_320x240", "testsrc2", 320, 240, (50, 75, 90)),
|
||||
("mandel_176x144", "mandelbrot", 176, 144, (30, 95)),
|
||||
("odd_97x61", "testsrc2", 97, 61, (75,)), ("tiny_7x5", "mandelbrot", 7, 5, (90,)),
|
||||
("one_1x1", "testsrc2", 1, 1, (90,))):
|
||||
p = W(name + ".yuv")
|
||||
ff(*source(src, max(w, 2), max(h, 2), 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("s.yuv"))
|
||||
raw = open(W("s.yuv"), "rb").read()
|
||||
if (w, h) == (1, 1):
|
||||
raw = raw[:1] + raw[4:5] + raw[5:6] # the top-left luma and chroma samples of a 2x2 source
|
||||
open(p, "wb").write(raw)
|
||||
for q in qs:
|
||||
want = tj.compress420(raw, w, h, q)
|
||||
got = ffdecode(want, "yuvj420p") if w > 1 else None
|
||||
psnr = 99.0
|
||||
if got:
|
||||
se = sum((a - b) ** 2 for a, b in zip(got[:w * h], raw[:w * h]))
|
||||
psnr = 99.0 if se == 0 else 10 * math.log10(255 * 255 * w * h / se)
|
||||
enc.append({"name": "%s_q%d" % (name, q), "width": w, "height": h, "quality": q, "yuv": z64(raw),
|
||||
"want": b64(want), "rgba": rgba_crc(want), "ffpsnr": round(psnr, 3)})
|
||||
ctx.emit("mjpeg_enc", enc)
|
||||
|
||||
bench = []
|
||||
for name, w, h, pix in (("320x240 4:2:0", 320, 240, "yuvj420p"), ("640x480 4:2:0", 640, 480, "yuvj420p"),
|
||||
("640x480 4:2:2", 640, 480, "yuvj422p")):
|
||||
o = W("bench.mjpeg")
|
||||
ff(*source("testsrc2", w, h, 1), "-pix_fmt", pix, "-c:v", "mjpeg", "-q:v", "3", "-f", "mjpeg", o)
|
||||
fr = split(open(o, "rb").read())[0]
|
||||
bench.append({"name": name, "width": w, "height": h, "data": b64(fr), "yuv": zlib.crc32(tj.yuv420(fr))})
|
||||
srcs = []
|
||||
for w, h in ((320, 240), (640, 480)):
|
||||
ff(*source("testsrc2", w, h, 1), "-pix_fmt", "yuv420p", "-f", "rawvideo", W("b.yuv"))
|
||||
srcs.append({"width": w, "height": h, "yuv": z64(open(W("b.yuv"), "rb").read())})
|
||||
ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs})
|
||||
@@ -0,0 +1,170 @@
|
||||
# MPEG-1 video fixtures for codecs/Mpeg1 (tools/fixtures.py), ported from mpeg1-luau tools/fixtures.py: elementary
|
||||
# streams made by ffmpeg's mpeg1video encoder (testsrc2 / mandelbrot, several bit rates, odd sizes, custom matrices,
|
||||
# B-frames, a size change), their access units, and ffmpeg's own decode of each as references:
|
||||
# tests/gen/mpeg1_<name>.luau { name, width, height, frames, file (base64), units = { { offset, length } },
|
||||
# means = { { r, g, b } } (every frame, display order, ffmpeg's RGBA),
|
||||
# rgba = { { index, pixels } } (two whole RGBA frames, base64 zlib),
|
||||
# yuv = { { index, planes } } (three whole frames as ffmpeg -pix_fmt yuv420p, base64 zlib) }
|
||||
# tests/gen/mpeg1_sizechange.luau { file (base64), parts = { { width, height, frames, last (RGBA, base64 zlib) } } }
|
||||
# tests/gen/mpeg1_bench.luau { { width, height, file (base64), units } }: 320x240 and 640x480 streams (with
|
||||
# B-frames) for tools/bench.luau
|
||||
# Binary fields are base64 (file, units' data) or base64 of zlib data (frames: the test inflates them with
|
||||
# codecs/Deflate): Luau string literals of binary data cost ~3.7 bytes per byte, base64 1.33. With short streams and
|
||||
# few whole frames the set stays near 10 MB.
|
||||
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"]
|
||||
ENC = ["-c:v", "mpeg1video", "-f", "mpeg1video"]
|
||||
# a non-default intra matrix (steeper) and inter matrix (rising), 64 values in natural order
|
||||
INTRA = ",".join(str(8 + (i // 8 + i % 8) * 3) for i in range(64))
|
||||
INTER = ",".join(str(16 + (i // 8 + i % 8)) for i in range(64))
|
||||
|
||||
|
||||
def src(kind, w, h, rate, t):
|
||||
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
|
||||
|
||||
|
||||
# name: (ffmpeg input + encoder args, size patched into the sequence headers or None, rgba sample picks, yuv picks)
|
||||
CASES = {
|
||||
"qcif_200k": (src("testsrc2", 176, 144, 25, 1.2) + ["-b:v", "200k", "-bf", "0", "-g", "50"], None),
|
||||
"main_450k": (src("testsrc2", 320, 180, 24, 1.5) + ["-b:v", "450k", "-bf", "0", "-g", "48"], None),
|
||||
"zoom_150k": (src("mandelbrot", 320, 180, 24, 1.5) + ["-b:v", "150k", "-bf", "0", "-g", "48"], None),
|
||||
"zoom_1500k": (src("mandelbrot", 320, 180, 24, 1) + ["-b:v", "1500k", "-bf", "0", "-g", "48"], None),
|
||||
"big_1000k": (src("testsrc2", 640, 360, 24, 0.5) + ["-b:v", "1000k", "-bf", "0", "-g", "36"], None),
|
||||
# odd sizes: ffmpeg's encoder only writes even ones, so the size in the sequence headers is patched; the
|
||||
# reference is ffmpeg's decode of the unpatched stream, cropped (swscale's odd-size RGBA path interpolates
|
||||
# chroma differently from its even-size one, which is what the decoder matches)
|
||||
"odd_173x95": (src("mandelbrot", 174, 96, 24, 1) + ["-b:v", "300k", "-bf", "0", "-g", "24"], (173, 95)),
|
||||
"bframes": (src("testsrc2", 320, 180, 24, 1) + ["-b:v", "600k", "-bf", "2", "-g", "24"], None),
|
||||
"bframes_zoom": (src("mandelbrot", 176, 144, 24, 1.5) + ["-b:v", "250k", "-bf", "3", "-g", "16"], None),
|
||||
"matrix": (src("testsrc2", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "12",
|
||||
"-intra_matrix", INTRA, "-inter_matrix", INTER], None),
|
||||
"q1": (src("mandelbrot", 176, 144, 25, 0.6) + ["-q:v", "1", "-bf", "0", "-g", "8"], None),
|
||||
"q31": (src("testsrc2", 176, 144, 25, 1) + ["-q:v", "31", "-bf", "0", "-g", "25"], None),
|
||||
"zeromv": (src("mandelbrot", 176, 144, 25, 1) + ["-b:v", "300k", "-bf", "0", "-g", "25", "-me_method", "zero"], None),
|
||||
}
|
||||
|
||||
|
||||
def patch_size(es, w, h):
|
||||
# every sequence header (00 00 01 B3): 12-bit width, 12-bit height
|
||||
b = bytearray(es)
|
||||
i = 0
|
||||
while True:
|
||||
i = b.find(b"\x00\x00\x01\xb3", i)
|
||||
if i < 0:
|
||||
return bytes(b)
|
||||
b[i + 4] = w >> 4
|
||||
b[i + 5] = ((w & 15) << 4) | (h >> 8)
|
||||
b[i + 6] = h & 255
|
||||
i += 4
|
||||
|
||||
|
||||
def access_units(es):
|
||||
# one unit per picture: from the first header byte before it (sequence / GOP) to the next unit start
|
||||
starts = []
|
||||
i = 0
|
||||
pending = None
|
||||
while True:
|
||||
i = es.find(b"\x00\x00\x01", i)
|
||||
if i < 0 or i + 3 >= len(es):
|
||||
break
|
||||
code = es[i + 3]
|
||||
if code in (0xB3, 0xB8) and pending is None:
|
||||
pending = i
|
||||
elif code == 0x00:
|
||||
starts.append(pending if pending is not None else i)
|
||||
pending = None
|
||||
i += 3
|
||||
return [[s, (starts[k + 1] if k + 1 < len(starts) else len(es)) - s] for k, s in enumerate(starts)]
|
||||
|
||||
|
||||
def crop(frames, w, h, cw, ch, bpp):
|
||||
fs = w * h * bpp
|
||||
out = bytearray()
|
||||
for k in range(len(frames) // fs):
|
||||
for y in range(ch):
|
||||
o = k * fs + y * w * bpp
|
||||
out += frames[o:o + cw * bpp]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def crop_yuv(frames, w, h, cw, ch):
|
||||
fs = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
out = bytearray()
|
||||
for k in range(len(frames) // fs):
|
||||
f = frames[k * fs:(k + 1) * fs]
|
||||
out += crop(f[:w * h], w, h, cw, ch, 1)
|
||||
c = ((w + 1) // 2) * ((h + 1) // 2)
|
||||
for pl in range(2):
|
||||
out += crop(f[w * h + pl * c:w * h + (pl + 1) * c], (w + 1) // 2, (h + 1) // 2, (cw + 1) // 2, (ch + 1) // 2, 1)
|
||||
return bytes(out)
|
||||
|
||||
|
||||
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)
|
||||
|
||||
with tempfile.TemporaryDirectory(prefix="formats-mpeg1-") as tmp:
|
||||
def encode(name, args, size):
|
||||
path = os.path.join(tmp, name + ".m1v")
|
||||
ff(args + ENC + [path])
|
||||
es = open(path, "rb").read()
|
||||
return (patch_size(es, *size) if size else es), path
|
||||
|
||||
def reference(path, fmt):
|
||||
out = path + "." + fmt
|
||||
ff(["-i", path, "-f", "rawvideo", "-pix_fmt", fmt, out])
|
||||
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)
|
||||
w, h = (int(x) for x in r.stdout.decode().strip().split(",")[:2])
|
||||
return open(out, "rb").read(), w, h
|
||||
|
||||
for name, (args, size) in CASES.items():
|
||||
es, path = encode(name, args, size)
|
||||
rgba, w, h = reference(path, "rgba")
|
||||
yuv, _, _ = reference(path, "yuv420p")
|
||||
if size:
|
||||
rgba, yuv = crop(rgba, w, h, size[0], size[1], 4), crop_yuv(yuv, w, h, size[0], size[1])
|
||||
w, h = size
|
||||
fs, ys = w * h * 4, w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
|
||||
n = len(rgba) // fs
|
||||
means = []
|
||||
for k in range(n):
|
||||
fr = rgba[k * fs:(k + 1) * fs]
|
||||
means.append([round(sum(fr[c::4]) / (w * h), 4) for c in range(3)])
|
||||
# whole frames: the first P-picture and the last one (the most drift) as RGBA, three as yuv420p
|
||||
picks = sorted({1, n - 1}) if n > 2 else list(range(n))
|
||||
ypicks = sorted({0, n // 2, n - 1})
|
||||
ctx.emit("mpeg1_" + name, {
|
||||
"name": name, "width": w, "height": h, "frames": n, "file": b64(es), "units": access_units(es),
|
||||
"means": means,
|
||||
"rgba": [{"index": k + 1, "pixels": z64(rgba[k * fs:(k + 1) * fs])} for k in picks],
|
||||
"yuv": [{"index": k + 1, "planes": z64(yuv[k * ys:(k + 1) * ys])} for k in ypicks],
|
||||
})
|
||||
|
||||
# a size change mid-stream: 176x144 then 320x180 (each part decoded by ffmpeg on its own)
|
||||
a, pa = encode("sc_a", src("testsrc2", 176, 144, 24, 0.5) + ["-b:v", "200k", "-bf", "0", "-g", "6"], None)
|
||||
b, pb = encode("sc_b", src("mandelbrot", 320, 180, 24, 0.5) + ["-b:v", "400k", "-bf", "0", "-g", "6"], None)
|
||||
parts = []
|
||||
for path in (pa, pb):
|
||||
rg, w, h = reference(path, "rgba")
|
||||
n = len(rg) // (w * h * 4)
|
||||
parts.append({"width": w, "height": h, "frames": n, "last": z64(rg[(n - 1) * w * h * 4:])})
|
||||
ctx.emit("mpeg1_sizechange", {"file": b64(a + b), "parts": parts})
|
||||
|
||||
bench = []
|
||||
for w, h, rate in ((320, 240, "600k"), (640, 480, "1500k")):
|
||||
es, _ = encode("bench", src("testsrc2", w, h, 25, 2) + ["-b:v", rate, "-bf", "2", "-g", "25"], None)
|
||||
bench.append({"width": w, "height": h, "file": b64(es), "units": access_units(es)})
|
||||
ctx.emit("mpeg1_bench", bench)
|
||||
Reference in new issue
Block a user