diff --git a/src/Formats/codecs/Video/Source.luau b/src/Formats/codecs/Video/Source.luau index f8065c6..2779bf5 100644 --- a/src/Formats/codecs/Video/Source.luau +++ b/src/Formats/codecs/Video/Source.luau @@ -232,6 +232,51 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E return out, nil end +-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond +function Source.rational(fps: number): (number, number) + if fps ~= fps or fps <= 0 then + return 25, 1 + end + if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then + return math.floor(fps + 0.5), 1 + end + local ntsc = fps * 1001 / 1000 + if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then + return math.floor(ntsc + 0.5) * 1000, 1001 + end + return math.floor(fps * 1000 + 0.5), 1000 +end + +-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the +-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet +-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps) +function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket }) + local fd = math.huge + for _, p in s.packets do + if p.duration and p.duration > 0 and p.duration < fd then + fd = p.duration + end + end + if fd == math.huge then + fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04 + end + fd = math.max(fd, 1 / (maxFps or 100)) + local num, den = Source.rational(1 / fd) + local step = den / num + local out: { OutPacket } = {} + local slots = 0 + local t0 = if s.packets[1] then s.packets[1].pts else 0 + for _, p in s.packets do + local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step) + local n = math.max(1, math.floor(stop / step + 0.5) - slots) + for _ = 1, n do + table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data }) + slots += 1 + end + end + return num, den, out +end + -- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its -- own order function Source.interleave(streams: { Stream }): { { any } } diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau index 20df8b8..80545df 100644 --- a/src/Formats/video/avi/init.luau +++ b/src/Formats/video/avi/init.luau @@ -223,17 +223,6 @@ function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode -local function rational(fps: number): (number, number) - if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then - return math.floor(fps + 0.5), 1 - end - local ntsc = fps * 1001 / 1000 - if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then - return math.floor(ntsc + 0.5) * 1000, 1001 - end - return math.floor(fps * 1000 + 0.5), 1000 -end - -- encode(video, opts?) -> buffer | nil, Err function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local o: any = table.clone(opts or {}) @@ -251,18 +240,8 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) for _, s in streams do if s.kind == "video" then -- a constant frame rate: the shortest frame duration (variable delays repeat frames) - local fd = math.huge - for _, p in s.packets do - if p.duration and p.duration > 0 and p.duration < fd then - fd = p.duration - end - end - local maxFps = o.maxFps or 100 - if fd == math.huge then - fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04 - end - fd = math.max(fd, 1 / maxFps) - local num, den = rational(1 / fd) + local num, den, packets = Source.constantRate(s, o.maxFps) + s.packets = packets frameDur = den / num width, height = s.width or 0, s.height or 0 usPerFrame = 1e6 * frameDur @@ -295,23 +274,10 @@ function AviFormat.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) table.insert(wstreams, { type = "auds", handler = "\0\0\0\0", scale = align, rate = rate * align, sampleSize = align, strf = wf:finish(), ckid = "wb" }) end end - -- chunks: video packets repeated to fill their duration at the constant rate - local order = Source.interleave(streams) + -- chunks in time order (the video packets already repeated to the constant rate) local chunks: { { any } } = {} - local vtime = 0 -- frames written so far (video slots) - for _, item in order do - local si, p = item[1], item[2] - local s = streams[si] - if s.kind == "video" then - local stop = p.pts + (if p.duration and p.duration > 0 then p.duration else frameDur) - local slots = math.max(1, math.floor(stop / frameDur + 0.5) - vtime) - for _ = 1, slots do - table.insert(chunks, { si, p.data, true }) - end - vtime += slots - else - table.insert(chunks, { si, p.data, true }) - end + for _, item in Source.interleave(streams) do + table.insert(chunks, { item[1], item[2].data, true }) end local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks) if not ok then diff --git a/src/Formats/video/y4m/init.luau b/src/Formats/video/y4m/init.luau index 99c3384..a5f4c06 100644 --- a/src/Formats/video/y4m/init.luau +++ b/src/Formats/video/y4m/init.luau @@ -4,7 +4,7 @@ -- with yuv420p frames (C420 / C420jpeg / C420mpeg2 / C420paldv as they are; C422 / C444 chroma averaged down; Cmono -- with neutral chroma; 9..16-bit samples (C420p10, ...) scaled to 8 bits). Y4m.demux(r) gives the Demuxer. -- Write: yuv420p 8-bit frames ("C420jpeg", as ffmpeg writes for yuv420p) from any video or animated image; rgba8 --- frames are converted (BT.601 limited range). Not supported: interlaced field handling (the I tag is kept in meta), +-- frames are converted (BT.601 limited range); uneven frame times (a GIF's) become a constant rate with repeated frames. Not supported: interlaced field handling (the I tag is kept in meta), -- alpha (C444alpha drops it). -- ------------------------------------------------------------------------------------------------ requires @@ -31,7 +31,9 @@ export type OpenOptions = { maxPixels: number?, -- default 2^26 } export type EncodeOptions = { - frameRate: { number }?, -- { num, den } for the F tag (default: from the source's frame rate) + frameRate: { number }?, -- { num, den } for the F tag, one frame per source frame (default: the constant rate of the + -- shortest frame, longer frames repeated) + maxFps: number?, -- the highest rate uneven frame times may need (default 100) } -- ------------------------------------------------------------------------------------------------ constants @@ -173,20 +175,6 @@ function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) end -- ------------------------------------------------------------------------------------------------ encode -local function rational(fps: number): (number, number) - if fps <= 0 or fps ~= fps then - return 25, 1 - end - if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then - return math.floor(fps + 0.5), 1 - end - local ntsc = fps * 1001 / 1000 - if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then - return math.floor(ntsc + 0.5) * 1000, 1001 - end - return math.floor(fps * 1000 + 0.5), 1000 -end - -- encode(video, opts?) -> buffer | nil, Err function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) local streams, err = Source.streams(value, { audio = false }, { video = { copy = nil, encode = "rawvideo" } }) @@ -194,12 +182,11 @@ function Y4m.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) return nil, err end local s = streams[1] - local fn, fd + local fn, fd, packets = Source.constantRate(s, opts and opts.maxFps) if opts and type(opts.frameRate) == "table" then - fn, fd = opts.frameRate[1], opts.frameRate[2] - else - fn, fd = rational(s.frameRate or 25) + fn, fd, packets = opts.frameRate[1], opts.frameRate[2], s.packets end + s.packets = packets local w = Bytes.writer(64 + #s.packets * (buffer.len(s.packets[1].data) + 6)) w:string(string.format("YUV4MPEG2 W%d H%d F%d:%d Ip A1:1 C420jpeg XYSCSS=420JPEG\n", s.width or 0, s.height or 0, fn, fd)) for _, p in s.packets do diff --git a/tests/video/encode.luau b/tests/video/encode.luau new file mode 100644 index 0000000..a81e4b0 --- /dev/null +++ b/tests/video/encode.luau @@ -0,0 +1,83 @@ +-- video writer tests: files our muxers wrote (tools/fixtures/_video_encode.luau: WebM remux, MJPEG Matroska / AVI +-- copied and re-encoded from VP8 / MPEG-1, an animated GIF with uneven delays to AVI / Matroska / Y4M, WebM to Y4M) +-- were probed by ffprobe and decoded by ffmpeg at fixture time; here our demuxers must see the same packets, our +-- decoders the same frames (CRC for VP8 / raw, PSNR for MJPEG) and audio; the writers are rerun and must give the same +-- bytes. Fixtures: tools/fixtures/videoenc.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Fx = require("@tests/gen/videoenc_cases") +local Src = require("@tests/gen/videoenc_src") + +local t = T.suite("video encode") + +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +for _, c in Fx do + local label = c.name + if c.err then + t:note("%s: not written at fixture time: %s", label, c.err) + else + local v, err = C.open(c.data) + t:check(v ~= nil, label .. ": opens: " .. tostring(err)) + if v then + t:eq(#v.demuxer.tracks, #c.streams, label .. ": track count (ffprobe)") + -- (ffmpeg's AVI demuxer cuts PCM chunks into 1024-sample packets: AVI audio is compared decoded) + local avi = string.sub(label, -4) == ".avi" + C.packets(t, v.demuxer, c, label, { skipStream = function(_: any, tr: any): boolean + return avi and tr ~= nil and tr.kind == "audio" + end }) + C.frames(t, v, c, label, 40) + local at = v.demuxer:track("audio") + if at then + C.audio(t, v, c, label, string.sub(at.codec, 1, 4) == "pcm_", 30) + end + end + end +end + +-- the GIF (100 / 50 / 200 / 100 ms) at a constant 20 fps: 2 + 1 + 4 + 2 frames +do + local c = byName["gif.avi"] + if c and c.frames then + t:eq(#c.frames, 9, "gif.avi: 9 frames at 20 fps (ffmpeg)") + local v = C.open(c.data) + t:eq(v.frameRate, 20, "gif.avi: 20 fps") + end + local y = byName["gif.y4m"] + if y and y.frames then + t:eq(#y.frames, 9, "gif.y4m: 9 frames (ffmpeg)") + end + -- F.video.open on the GIF itself: a frames-backed video + local g = F.video.open(buffer.fromstring(Src.gif)) + t:check(g ~= nil and g.codec == "frames" and g.frames == 4, "F.video.open(gif): 4 frames") + if g then + local f1 = g:nextFrame() + local f2 = g:nextFrame() + t:check(f1 and f1.image.format == "rgba8" and f1.duration == 0.1 and f2 and f2.pts == 0.1 and f2.duration == 0.05, "gif frames: rgba8 with the GIF's times") + g:seek(0.2) + local f3 = g:nextFrame() + t:check(f3 ~= nil and f3.index == 3, "gif seek: frame 3 at 0.15 s holds 0.2 s") + end +end + +-- the writers are deterministic: the same bytes again +do + local Mkv = require("@tests/gen/mkv_cases") + local remux = byName["remux.webm"] + for _, m in Mkv do + if m.name == "vp8_opus.webm" and remux and remux.data then + local out = F.convert(buffer.fromstring(m.data), "webm") + t:check(out ~= nil and buffer.tostring(out) == remux.data, "remux.webm: written again byte for byte") + end + end + local gifAvi = byName["gif.avi"] + if gifAvi and gifAvi.data then + local out = F.convert(buffer.fromstring(Src.gif), "avi", { quality = 95 }) + t:check(out ~= nil and buffer.tostring(out) == gifAvi.data, "gif.avi: F.convert(gif, 'avi') again byte for byte") + end +end +t:done() diff --git a/tools/fixtures/_video_encode.luau b/tools/fixtures/_video_encode.luau new file mode 100644 index 0000000..eb03284 --- /dev/null +++ b/tools/fixtures/_video_encode.luau @@ -0,0 +1,46 @@ +-- tools/fixtures/_video_encode: run by tools/fixtures/videoenc.py (luau, from the repo root) so ffprobe / ffmpeg can +-- check our video writers: remuxes and re-encodes the container fixtures (tests/gen/mkv_cases, avi_cases) and the +-- animated GIF of tests/gen/videoenc_src, and prints " " lines (or " ERR "). +local F = require("@formats") +local Mkv = require("@tests/gen/mkv_cases") +local Avi = require("@tests/gen/avi_cases") +local Src = require("@tests/gen/videoenc_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(list: any, name: string): string + for _, c in list do + if c.name == name then + return c.data + end + end + error("no fixture " .. name) +end + +local JOBS = { + { "remux.webm", find(Mkv, "vp8_opus.webm"), "webm", {} }, + { "copy.mkv", find(Mkv, "mjpeg_pcm.mkv"), "mkv", {} }, + { "vp8_mjpeg.mkv", find(Mkv, "vp8_opus.webm"), "mkv", { reencode = true, quality = 92 } }, + { "copy.avi", find(Avi, "mjpeg_pcm.avi"), "avi", {} }, + { "vp8_mjpeg.avi", find(Mkv, "vp8_opus.webm"), "avi", { quality = 92 } }, + { "mpeg1_mjpeg.avi", find(Mkv, "mpeg1_mp2.mkv"), "avi", { quality = 92 } }, + { "gif.avi", Src.gif, "avi", { quality = 95 } }, + { "gif.mkv", Src.gif, "mkv", { quality = 95 } }, + { "gif.y4m", Src.gif, "y4m", {} }, + { "webm.y4m", find(Mkv, "vp8_opus.webm"), "y4m", {} }, +} +for _, j in JOBS do + local name, data, fmt, opts = j[1], j[2], j[3], j[4] + local out, err = F.convert(buffer.fromstring(data), fmt, opts) + if out then + print(name .. " " .. hex(out)) + else + print(name .. " ERR " .. string.gsub(tostring(err), "%s", "_")) + end +end diff --git a/tools/fixtures/videoenc.py b/tools/fixtures/videoenc.py new file mode 100644 index 0000000..2557466 --- /dev/null +++ b/tools/fixtures/videoenc.py @@ -0,0 +1,62 @@ +# Our video writers checked by ffprobe / ffmpeg (tools/fixtures.py): tools/fixtures/_video_encode.luau remuxes / +# re-encodes the container fixtures (WebM remux, MJPEG Matroska / AVI from VP8 and MPEG-1, MJPEG copies, an animated +# GIF with uneven delays to AVI / Matroska / Y4M, WebM to Y4M); each output must probe in ffprobe and decode in +# ffmpeg. Emitted per file: our bytes, ffprobe's streams and packets, ffmpeg's frames (CRC-32; the first raw) and +# audio, so the test can decode our file with our decoders and compare. +# tests/gen/videoenc_src.luau { gif = } +# tests/gen/videoenc_cases.luau { { name, data, streams, packets, frames, yuv, 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/_video_encode.luau", "tools/fixtures/mkv.py", "tools/fixtures/avi.py", + "src/Formats/video", "src/Formats/codecs/Video", "src/Formats/containers/Ebml", "src/Formats/containers/Avi", + "src/Formats/codecs/Jpeg", "src/Formats/codecs/Vp8"] + +GIF = r""" +import io, sys +from PIL import Image, ImageDraw +frames = [] +for i, c in enumerate([(255, 0, 0), (0, 160, 0), (0, 0, 255), (240, 200, 0)]): + im = Image.new("RGB", (64, 48), (20, 20, 20)) + d = ImageDraw.Draw(im) + d.rectangle([4 + i * 10, 8, 24 + i * 10, 40], fill=c) + d.ellipse([40, 4 + i * 6, 60, 20 + i * 6], fill=(255, 255, 255)) + frames.append(im) +b = io.BytesIO() +frames[0].save(b, "GIF", save_all=True, append_images=frames[1:], duration=[100, 50, 200, 100], loop=0) +sys.stdout.buffer.write(b.getvalue()) +""" + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="videoenc_") + gif = ctx.python(["pillow"], GIF) + ctx.emit("videoenc_src", {"gif": gif}) + luau = os.environ.get("LUAU") or shutil.which("luau") + cmd = [luau, "tools/fixtures/_video_encode.luau"] if luau else ["nix", "shell", "nixpkgs#luau", "-c", "luau", "tools/fixtures/_video_encode.luau"] + out = subprocess.run(cmd, capture_output=True, check=True, cwd=ctx.root).stdout.decode() + cases = [] + for line in out.split("\n"): + if not line.strip(): + continue + name, rest = line.split(" ", 1) + if rest.startswith("ERR "): + cases.append({"name": name, "err": rest[4:]}) + continue + path = os.path.join(tmp, name) + open(path, "wb").write(bytes.fromhex(rest)) + 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: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"], codec=vs[0]["codec"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:3] + if any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm[:8192 * 4] + c["pcmBytes"] = len(pcm) + cases.append(c) + ctx.emit("videoenc_cases", cases)