ws-video-codecs: codecs/Jpeg: 4:2:2 / 4:4:4 as ffmpeg writes them (2x2/1x2, 1x2) for yuv output; tests/codecs/jpeg.luau + tools/fixtures/mjpeg.py (ffmpeg mjpeg frames bit-exact vs TurboJPEG planes / djpeg, PSNR vs ffmpeg, stripped DHT, AVI1, fields, yuv420p encode byte-identical with tj3CompressFromYUV8)

This commit is contained in:
4DBug committed 2026-10-31 09:35:34 -05:00
1 parent 2ca0d1f10a
commit c0e8a89050
3 files changed
+575 -11

No files matched your search

+18 -11
View File
@@ -675,9 +675,10 @@ end
-- outputYuv(st) -> width, height, yuv420p pixels, sampling | nil when the frame has no direct yuv420p form (the
-- caller falls back to output). The IDCT output planes as they are, cropped to the image, without colour conversion
-- or upsampling: 8-bit YCbCr with 2x2 luma and 1x1 chroma sampling ("420"); 2x1 luma ("422": each pair of chroma
-- rows averaged, rounding up); 1x1 everywhere ("444": each 2 x 2 chroma block averaged, rounding to nearest); grey
-- ("gray": chroma 128). Full scale only (opts.scale = 1).
-- or upsampling: 8-bit YCbCr whose chroma is sampled at half the luma rate both ways ("420", 2x2 / 1x1); half
-- horizontally ("422", 2x1 / 1x1 or ffmpeg's 2x2 / 1x2: each pair of chroma rows averaged, rounding up); at the luma
-- rate ("444", 1x1 or ffmpeg's 1x2 everywhere: each 2 x 2 chroma block averaged, rounding to nearest); grey ("gray":
-- chroma 128). Full scale only (opts.scale = 1).
function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
local f: Frame = st.frame
if st.scale ~= 1 or f.precision ~= 8 then
@@ -688,14 +689,20 @@ function Decode.outputYuv(st: State): (number?, number?, buffer?, string?)
local mode = nil
if space == "gray" then
mode = "gray"
elseif space == "ycbcr" and comps[2].h == 1 and comps[2].v == 1 and comps[3].h == 1 and comps[3].v == 1 then
local l = comps[1]
if l.h == 2 and l.v == 2 then
mode = "420"
elseif l.h == 2 and l.v == 1 then
mode = "422"
elseif l.h == 1 and l.v == 1 then
mode = "444"
elseif space == "ycbcr" then
-- the ratios of luma to chroma sampling (ffmpeg writes 4:2:2 as 2x2 / 1x2 and 4:4:4 as 1x2 everywhere)
local l, cb, cr = comps[1], comps[2], comps[3]
if l.h == f.hmax and l.v == f.vmax and cb.h == cr.h and cb.v == cr.v then
local rh, rv = f.hmax // cb.h, f.vmax // cb.v
if rh * cb.h ~= f.hmax or rv * cb.v ~= f.vmax then
mode = nil
elseif rh == 2 and rv == 2 then
mode = "420"
elseif rh == 2 and rv == 1 then
mode = "422"
elseif rh == 1 and rv == 1 then
mode = "444"
end
end
end
if not mode then
+250
View File
@@ -0,0 +1,250 @@
-- codecs/Jpeg tests (the Motion-JPEG side; tests/image/jpeg.luau covers the still-image decoder and encoder through
-- image/jpeg): ffmpeg mjpeg frames (4:2:0, 4:2:2, 4:4:4, odd sizes, stripped DHT, AVI1 + junk after EOI) decoded
-- to yuv420p bit-exact with libjpeg-turbo's IDCT planes (TurboJPEG) and to rgba8 bit-exact with djpeg, and within
-- PSNR thresholds of ffmpeg's own decode; an interlaced AVI1 frame (two fields) woven; the yuv420p encoder
-- byte-identical to TurboJPEG's tj3CompressFromYUV8, read back by djpeg (exact) and ffmpeg (PSNR); the API's
-- arguments; the fuzz no-throw pass. Fixtures: tools/fixtures/mjpeg.py.
local T = require("@tests/T")
local Jpeg = require("@formats/codecs/Jpeg")
local Crc32 = require("@formats/core/Crc32")
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Fx = require("@tests/gen/mjpeg_cases")
local Enc = require("@tests/gen/mjpeg_enc")
local t = T.suite("codecs/jpeg")
-- PSNR of n bytes of a at ao against b at bo
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
-- PSNR of the RGB channels of two rgba8 buffers of n pixels
local function psnrRgb(a: buffer, b: buffer, n: number): number
local se = 0
for i = 0, n - 1 do
for k = 0, 2 do
local d = buffer.readu8(a, i * 4 + k) - buffer.readu8(b, i * 4 + k)
se += d * d
end
end
if se == 0 then
return 99
end
return 10 * math.log10(255 * 255 * n * 3 / se)
end
local function hasDht(s: string): boolean
local at = string.find(s, "\255\196", 1, true)
local sos = string.find(s, "\255\218", 1, true)
return at ~= nil and sos ~= nil and at < sos
end
-- 1. ffmpeg's frames: yuv420p (TurboJPEG planes) and rgba8 (djpeg) bit-exact, PSNR against ffmpeg's decode
do
local frames, worstY, worstC, worstRgb = 0, 99, 99, 99
for _, s in Fx.streams do
local w, h = s.width, s.height
local cw, ch = (w + 1) // 2, (h + 1) // 2
for i, f in s.frames do
local label = string.format("%s frame %d", s.name, i)
local b = buffer.fromstring(f.data)
local img, err = Jpeg.decode(b, 0, buffer.len(b), { yuv = true })
t:check(img, label .. ": " .. tostring(err))
t:check(img.format == "yuv420p" and img.width == w and img.height == h, label .. ": a yuv420p " .. w .. "x" .. h .. " Image")
t:eq(buffer.len(img.pixels), w * h + 2 * cw * ch, label .. ": plane sizes")
t:check(img.meta.source.yuv == s.sampling and img.meta.source.range == "full", label .. ": meta.source.yuv " .. tostring(img.meta.source.yuv))
t:check(not img.meta.truncated, label .. ": not truncated")
t:eq(Crc32.of(img.pixels), f.yuv, label .. ": yuv420p planes = TurboJPEG's")
local rgba = Jpeg.decode(b) :: Types.Image
t:check(rgba and rgba.format == "rgba8", label .. ": rgba8")
t:eq(Crc32.of(rgba.pixels), f.rgba, label .. ": rgba8 = djpeg")
if i == 1 then
local ref = buffer.fromstring(s.ff.yuv)
local py = psnr(img.pixels, 0, ref, 0, w * h)
local pc = math.min(psnr(img.pixels, w * h, ref, w * h, cw * ch), psnr(img.pixels, w * h + cw * ch, ref, w * h + cw * ch, cw * ch))
-- ffmpeg's IDCT differs from libjpeg's islow by rounding only; its 4:2:2 / 4:4:4 -> 4:2:0 is a filter
t:check(py > 55, string.format("%s: luma PSNR %.1f dB against ffmpeg", s.name, py))
t:check(pc > (if s.sampling == "420" then 55 else 20), string.format("%s: chroma PSNR %.1f dB against ffmpeg", s.name, pc))
worstY, worstC = math.min(worstY, py), math.min(worstC, pc)
if s.ff.rgba then
local pr = psnrRgb(rgba.pixels, buffer.fromstring(s.ff.rgba), w * h)
-- swscale upsamples chroma differently from libjpeg (fancy): testsrc2's sharp colour edges cost ~10 dB
t:check(pr > 25, string.format("%s: rgba PSNR %.1f dB against ffmpeg", s.name, pr))
worstRgb = math.min(worstRgb, pr)
end
end
if string.find(s.name, "nodht") then
t:check(not hasDht(f.data), label .. ": no DHT segment")
end
if s.name == "avi1_junk" then
t:eq(img.meta.source.avi1, 0, label .. ": AVI1 polarity")
t:eq(Jpeg.info(b).avi1, 0, label .. ": info.avi1")
end
frames += 1
end
end
t:note("%d ffmpeg mjpeg frames bit-exact (yuv420p: TurboJPEG, rgba8: djpeg); worst PSNR against ffmpeg: luma %.1f, chroma %.1f, rgba %.1f dB", frames, worstY, worstC, worstRgb)
end
-- 2. an interlaced frame: two fields (AVI1 polarity 1) woven, field 1 on the even rows
do
local F = Fx.fields
local b = buffer.fromstring(F.data)
local img = Jpeg.decode(b, 0, nil, { yuv = true }) :: Types.Image
t:check(img and img.width == F.width and img.height == F.height and img.format == "yuv420p", "fields: one 320x240 yuv420p frame")
t:eq(img.meta.source.fields, 2, "fields: meta.source.fields")
t:eq(Crc32.of(img.pixels), F.yuv, "fields: woven yuv420p planes = TurboJPEG's fields woven")
local src = buffer.fromstring(F.src)
local p = psnr(img.pixels, 0, src, 0, F.width * F.height)
t:check(p > 35, string.format("fields: luma PSNR %.1f dB against the source frame", p))
local rgba = Jpeg.decode(b) :: Types.Image
t:check(rgba.height == F.height and Crc32.of(rgba.pixels) == F.rgba, "fields: woven rgba8 = djpeg's fields woven")
local one = Jpeg.decode(b, 0, nil, { yuv = true, fields = false }) :: Types.Image
t:check(one.height == F.height // 2 and one.meta.source.fields == 1, "fields = false: the first field only")
-- the first field alone (no second JPEG): a half-height frame, not an error
local first = string.find(F.data, "\255\217", 1, true) :: number
local half = Jpeg.decode(buffer.fromstring(string.sub(F.data, 1, first + 1)), 0, nil, { yuv = true }) :: Types.Image
t:check(half and half.height == F.height // 2 and half.meta.source.fields == 1, "a missing second field leaves the first")
t:check(Jpeg.info(b).avi1 == 1, "fields: info.avi1")
end
-- 3. the yuv420p encoder: byte-identical with TurboJPEG, read back by djpeg (exact) and ffmpeg (PSNR)
do
local exact = 0
for _, c in Enc do
local img = Types.Image.new(c.width, c.height, "yuv420p")
img.pixels = buffer.fromstring(c.yuv)
local out, err = Jpeg.encode(img, { quality = c.quality })
t:check(out, c.name .. ": " .. tostring(err))
local s = buffer.tostring(out :: buffer)
if s ~= c.want then
local at = 0
for i = 1, math.min(#s, #c.want) do
if string.byte(s, i) ~= string.byte(c.want, i) then
at = i
break
end
end
t:check(false, string.format("%s: differs from tj3CompressFromYUV8 at byte %d (ours %d bytes, TurboJPEG %d)", c.name, at, #s, #c.want))
end
exact += 1
local back = Jpeg.decode(out :: buffer) :: Types.Image
t:eq(Crc32.of(back.pixels), c.rgba, c.name .. ": our decode of it = djpeg's")
local floor = if c.quality >= 75 then 30 else 26
if c.width * c.height >= 1000 then
t:check(c.ffpsnr > floor, string.format("%s: ffmpeg reads it at %.1f dB luma PSNR", c.name, c.ffpsnr))
local y = Jpeg.decode(out :: buffer, 0, nil, { yuv = true }) :: Types.Image
local p = psnr(y.pixels, 0, img.pixels, 0, c.width * c.height)
t:check(p > floor, string.format("%s: yuv round trip %.1f dB", c.name, p))
end
end
t:note("%d yuv420p encodes byte-identical with tj3CompressFromYUV8", exact)
-- grey from yuv420p: the luma plane only
local c = Enc[1]
local img = Types.Image.new(c.width, c.height, "yuv420p")
img.pixels = buffer.fromstring(c.yuv)
local g = Jpeg.encode(img, { quality = 80, gray = true }) :: buffer
local gi = Jpeg.info(g)
t:check(gi and gi.components == 1, "yuv420p with gray = true: one component")
local gy = Jpeg.decode(g, 0, nil, { yuv = true }) :: Types.Image
t:check(gy.format == "yuv420p" and gy.meta.source.yuv == "gray" and buffer.readu8(gy.pixels, c.width * c.height) == 128, "grey decodes to yuv420p with chroma 128")
local p = Jpeg.encode(img, { quality = 80, progressive = true, restart = 2 }) :: buffer
local pi = Jpeg.info(p)
t:check(pi and pi.progressive and pi.sampling[1][1] == 2 and pi.sampling[1][2] == 2, "yuv420p progressive")
local pd = Jpeg.decode(p, 0, nil, { yuv = true }) :: Types.Image
t:check(psnr(pd.pixels, 0, img.pixels, 0, c.width * c.height) > 30, "yuv420p progressive round trip")
local s4 = Jpeg.encode(img, { subsampling = "444" }) :: buffer
t:eq(Jpeg.info(s4).sampling[1][1], 2, "yuv420p input is always 4:2:0")
-- extra segments and density
local seg = Jpeg.encode(img, { segments = { { marker = 0xFE, data = buffer.fromstring("hello") } }, density = { unit = 1, x = 72, y = 72 } }) :: buffer
local sd = Jpeg.decode(seg) :: Types.Image
t:check(sd.meta.text and sd.meta.text.comment == "hello" and sd.meta.dpi and sd.meta.dpi.x == 72, "segments and density")
end
-- 4. the API: ranges, options, fallbacks, errors
do
local s = Fx.streams[1]
local data = s.frames[1].data
local big = buffer.create(#data + 30)
buffer.writestring(big, 17, data)
local a = Jpeg.decode(big, 17, #data, { yuv = true }) :: Types.Image
t:eq(Crc32.of(a.pixels), s.frames[1].yuv, "decode from a sub-range")
local i = Jpeg.info(big, 17, #data)
t:check(i and i.width == s.width and i.colorSpace == "ycbcr" and i.sampling[1][2] == 2, "info from a sub-range")
local sc = Jpeg.decode(buffer.fromstring(data), 0, nil, { yuv = true, scale = 2 }) :: Types.Image
t:check(sc.format == "rgba8" and sc.width == s.width // 2, "yuv with scale 2 falls back to rgba8")
local _, e1 = Jpeg.decode("nope" :: any)
t:check(e1 and e1.code == Err.ARG, "decode(string)")
local _, e2 = Jpeg.decode(buffer.fromstring("nope"))
t:check(e2 and e2.code == Err.CORRUPT, "junk")
local _, e3 = Jpeg.decode(buffer.fromstring(data), 0, nil, { maxPixels = 100, yuv = true })
t:check(e3 and e3.code == Err.LIMIT, "maxPixels")
local _, e4 = Jpeg.decode(buffer.fromstring(data), 0, nil, 5 :: any)
t:check(e4 and e4.code == Err.ARG, "non-table options")
local _, e5 = Jpeg.encode(Types.Image.new(4, 4, "rgba16"))
t:check(e5 and e5.code == Err.ARG, "rgba16 is refused")
local short = Types.Image.new(8, 8, "yuv420p")
short.pixels = buffer.create(70)
local _, e6 = Jpeg.encode(short)
t:check(e6 and e6.code == Err.ARG, "a short yuv420p buffer")
local _, e7 = Jpeg.encode(Types.Image.new(8, 8), { segments = { { marker = 0xC4, data = buffer.create(1) } } })
t:check(e7 and e7.code == Err.ARG, "a bad segment marker")
local _, e8 = Jpeg.info(buffer.create(0))
t:check(e8 and Err.is(e8), "info of nothing")
-- truncated frames decode as far as they go or fail with an Err
local cuts, partial = 0, 0
for cut = 0, #data - 1, #data // 37 do
local img, err = Jpeg.decode(buffer.fromstring(string.sub(data, 1, cut)), 0, nil, { yuv = true })
t:check(img or Err.is(err), "cut at " .. cut .. ": no image and no Err")
if img then
partial += 1
t:check(img.meta.truncated, "cut at " .. cut .. ": flagged truncated")
end
cuts += 1
end
t:note("%d truncated frames, %d decoded partially", cuts, partial)
end
-- 5. speed (a note; tools/bench.luau has the real numbers)
do
local s = Fx.streams[1]
local frames = {}
for _, f in s.frames do
table.insert(frames, buffer.fromstring(f.data))
end
local t0, n = os.clock(), 0
while os.clock() - t0 < 0.3 do
for _, b in frames do
Jpeg.decode(b, 0, nil, { yuv = true })
n += 1
end
end
t:note("%dx%d yuv420p decode: %.0f fps", s.width, s.height, n / (os.clock() - t0))
end
-- 6. fuzz
do
local samples = {}
for k, s in Fx.streams do
if k % 2 == 1 then
table.insert(samples, s.frames[1].data)
end
end
t:fuzz("decode yuv", function(b: buffer)
return Jpeg.decode(b, 0, nil, { yuv = true })
end, samples, { mutations = 4, keepHeader = 2 })
t:fuzz("decode fields", function(b: buffer)
return Jpeg.decode(b, 0, nil, { fields = true })
end, { Fx.fields.data }, { mutations = 3, garbage = 10 })
end
t:done()
+307
View File
@@ -0,0 +1,307 @@
# 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 a 640x480 yuv420p source
import ctypes, math, os, shutil, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
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": data, "yuv": zlib.crc32(tj.yuv420(ref)), "rgba": rgba_crc(ref)})
ref = {"yuv": 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"] = 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": data, "width": fw, "height": fh,
"yuv": zlib.crc32(wy), "rgba": zlib.crc32(wr), "src": 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": raw,
"want": 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": 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": open(W("b.yuv"), "rb").read()})
ctx.emit("mjpeg_bench", {"frames": bench, "sources": srcs})