From 9411cd97c688405fc08bdd270afaa66781c178b4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 09:41:22 -0500 Subject: [PATCH] ws-video: video/mkv tests (ffprobe packets, ffmpeg audio, lacing / zlib / unknown clusters / subtitles, WebM remux), zlib content compression, codec-delay trimming of non-Opus audio (AudioWrap.trim), video/y4m, containers/Avi + video/avi (WIP tests) --- docs/FORMATS.md | 4 +- src/Formats/Registry.luau | 26 +- src/Formats/codecs/Video/init.luau | 92 ++++- src/Formats/containers/AudioWrap.luau | 46 ++- src/Formats/containers/Avi/init.luau | 523 ++++++++++++++++++++++++++ src/Formats/init.luau | 6 +- src/Formats/video/avi/init.luau | 331 ++++++++++++++++ src/Formats/video/mkv/Parse.luau | 33 +- src/Formats/video/mkv/init.luau | 6 +- src/Formats/video/y4m/init.luau | 222 +++++++++++ tests/video/_common.luau | 214 +++++++++++ tests/video/mkv.luau | 128 +++++++ tools/fixtures/_video.py | 120 ++++++ tools/fixtures/mkv.py | 131 +++++++ 14 files changed, 1862 insertions(+), 20 deletions(-) create mode 100644 src/Formats/containers/Avi/init.luau create mode 100644 src/Formats/video/avi/init.luau create mode 100644 src/Formats/video/y4m/init.luau create mode 100644 tests/video/_common.luau create mode 100644 tests/video/mkv.luau create mode 100644 tools/fixtures/_video.py create mode 100644 tools/fixtures/mkv.py diff --git a/docs/FORMATS.md b/docs/FORMATS.md index aabd3e9..04eb210 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -20,7 +20,9 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | audio | mp3 | .mp3 .mp2 .mp1 .mpga | yes | - | streaming: true, seek: true, layers: 1, 2, 3, channels: 2 | `tests/audio/mp3.luau` | | audio | opus | .opus | yes | - | streaming: true, seek: true, lossy: true, channels: 255, rates: 48000 | `tests/audio/opus.luau` | | audio | wav | .wav .wave .rf64 .bw64 | yes | yes | streaming: true, depths: 8, 16, 24, 32, float: true, rf64: true | `tests/audio/wav.luau` | -| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | **missing** | +| video | avi | .avi | yes | yes | streaming: true, video: "mjpeg", "mpeg1", "rawvideo", audio: true, odml: true | **missing** | +| video | mkv | .mkv .webm .mka .mk3d | yes | yes | streaming: true, remux: true, video: "vp8", "mjpeg", "mpeg1", "rawvideo", audio: true, subtitles: true | `tests/video/mkv.luau` | +| video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | **missing** | | model | gltf | .gltf .glb | yes | yes | binary: true, materials: true, animation: true, skins: true, morphTargets: true, cameras: true, lights: true | `tests/model/gltf.luau` | | model | obj | .obj | yes | yes | materials: true, polygons: true, vertexColors: true | `tests/model/obj.luau` | | model | off | .off | yes | yes | polygons: true, points: true, colors: true, binary: false | `tests/model/off.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 2f6e7e8..5e2e97c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -194,18 +194,42 @@ local list: { Entry } = { return require("@formats/audio/wav") end, }, + { + name = "avi", + category = "video", + path = "video/avi", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, + load = function() + return require("@formats/video/avi") + end, + }, { name = "mkv", category = "video", path = "video/mkv", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, load = function() return require("@formats/video/mkv") end, }, + { + name = "y4m", + category = "video", + path = "video/y4m", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, + load = function() + return require("@formats/video/y4m") + end, + }, { name = "gltf", category = "model", diff --git a/src/Formats/codecs/Video/init.luau b/src/Formats/codecs/Video/init.luau index 718bd30..ea7789d 100644 --- a/src/Formats/codecs/Video/init.luau +++ b/src/Formats/codecs/Video/init.luau @@ -63,31 +63,107 @@ function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> return self :: any end --- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), rgb24 / bgr24 / bgra (bottom-up AVI DIBs: track.flip) +-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), yuv422p / yuv444p / yuva444p / gray (chroma averaged +-- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 / +-- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows) +local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image + local img = Types.Image.new(w, h, "yuv420p") + local px = img.pixels + local cw, ch = (w + 1) // 2, (h + 1) // 2 + local bps = if bits > 8 then 2 else 1 + local shift = 2 ^ (bits - 8) + local function sample(o: number): number + if bps == 1 then + return buffer.readu8(data, o) + end + return math.min(255, buffer.readu16(data, o) // shift) + end + for i = 0, w * h - 1 do + buffer.writeu8(px, i, sample(i * bps)) + end + local scw, sch = w, h -- source chroma plane size + if pf == "yuv420p" then + scw, sch = cw, ch + elseif pf == "yuv422p" then + scw, sch = cw, h + end + local uo, vo = w * h * bps, (w * h + scw * sch) * bps + for cy = 0, ch - 1 do + for cx = 0, cw - 1 do + local i = cy * cw + cx + local u, v + if pf == "gray" then + u, v = 128, 128 + elseif pf == "yuv420p" then + u, v = sample(uo + i * bps), sample(vo + i * bps) + elseif pf == "yuv422p" then + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2 + v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2 + else + local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1) + local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) + local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps + u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4 + v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4 + end + buffer.writeu8(px, w * h + i, u) + buffer.writeu8(px, w * h + cw * ch + i, v) + end + end + return img +end + +local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = { + yuv420p = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yv12 = function(w, h, cw, ch) + return w * h + 2 * cw * ch + end, + yuv422p = function(w, h, cw, _ch) + return w * h + 2 * cw * h + end, + yuv444p = function(w, h) + return w * h * 3 + end, + yuva444p = function(w, h) + return w * h * 4 + end, + gray = function(w, h) + return w * h + end, +} + local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local w, h = track.width or 0, track.height or 0 if w <= 0 or h <= 0 or w * h > 2 ^ 26 then return nil, Err.new(Err.CORRUPT, "raw video without a valid size") end local pf = track.pixelFormat or "yuv420p" + local bits = track.bitDepth or 8 local cw, ch = (w + 1) // 2, (h + 1) // 2 local flip = track.flip == true + local planar = PLANAR_SIZE[pf] return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) local n = buffer.len(data) - if pf == "yuv420p" or pf == "yv12" then - local need = w * h + 2 * cw * ch + if planar then + local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1) if n < need then return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") end - local img = Types.Image.new(w, h, "yuv420p") - if pf == "yv12" then + if pf == "yuv420p" and bits == 8 then + local img = Types.Image.new(w, h, "yuv420p") + buffer.copy(img.pixels, 0, data, 0, need) + return img + elseif pf == "yv12" then + local img = Types.Image.new(w, h, "yuv420p") buffer.copy(img.pixels, 0, data, 0, w * h) buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch) buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch) - else - buffer.copy(img.pixels, 0, data, 0, need) + return img end - return img + return rawPlanar(data, pf, bits, w, h) end local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 local stride = if track.stride then track.stride else w * bpp diff --git a/src/Formats/containers/AudioWrap.luau b/src/Formats/containers/AudioWrap.luau index b6a50f0..69640d0 100644 --- a/src/Formats/containers/AudioWrap.luau +++ b/src/Formats/containers/AudioWrap.luau @@ -263,6 +263,50 @@ local function adts(track: Types.Track, packets: { Types.Packet }): (buffer?, Er return w:finish(), nil end +-- ------------------------------------------------------------------------------------------------ trim +-- trim(decoder, frames) -> an audio Decoder that drops the first `frames` sample frames (a container's codec delay: +-- Matroska CodecDelay for MP2 / MP3 / AAC, which ffmpeg drops too; Opus handles its pre-skip itself) +function AudioWrap.trim(dec: any, skip: number): any + if skip <= 0 then + return dec + end + local rate = dec.sampleRate + local w: any = setmetatable({}, { __index = dec }) + w.frames = math.max(0, (dec.frames or 0) - skip) + w.duration = math.max(0, (dec.duration or 0) - skip / rate) + local function drop() + local left = skip + while left > 0 do + local _, n = dec:read(math.min(left, 4096)) + if not n or n <= 0 then + break + end + left -= n + end + end + local started = false + function w.read(_: any, n: number, out: buffer?): (buffer, number) + if not started then + started = true + drop() + end + return dec:read(n, out) + end + function w.seek(_: any, seconds: number) + started = true + if seconds <= 0 then + dec:seek(0) + drop() + else + dec:seek(seconds + skip / rate) + end + end + function w.position(_: any): number + return math.max(0, dec:position() - skip / rate) + end + return w +end + -- ------------------------------------------------------------------------------------------------ wrap -- wrap(demuxer, track) -> buffer, audio format name | nil, nil, Err function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Err?) @@ -277,7 +321,7 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er if #packets == 0 then return nil, nil, Err.new(Err.CORRUPT, "audio track without packets") end - if track.waveFormat and (PCM[codec] == nil or codec == "pcm_s16le" or codec == "pcm_u8") then + if track.waveFormat and string.sub(codec, 1, 6) == "adpcm_" then return wav(track.waveFormat, concat(packets)), "wav", nil end if PCM[codec] then diff --git a/src/Formats/containers/Avi/init.luau b/src/Formats/containers/Avi/init.luau new file mode 100644 index 0000000..521dbe9 --- /dev/null +++ b/src/Formats/containers/Avi/init.luau @@ -0,0 +1,523 @@ +--!strict +-- containers/Avi: the AVI RIFF form (Microsoft AVI 1.0 + the OpenDML 1.02 extensions). New in formats-luau. +-- Reading: hdrl (avih, strl: strh / strf / strn / indx), every RIFF piece (RIFF AVI + RIFF AVIX ...), and the chunk +-- index of every stream: from the OpenDML super index (indx -> ix## standard / field indexes), else idx1 (offsets +-- relative to the movi list or absolute, detected), else a linear scan of the movi lists (LIST rec included). +-- Writing: AVI 1.0 (avih, strl, LIST movi, idx1) with an OpenDML odml / dmlh header, chunks interleaved as given. +-- +-- local avi, err = Avi.read(buf, base, limit) +-- avi.streams[i] = { type = "vids" | "auds" | ..., handler, scale, rate, start, length, sampleSize, strf +-- (buffer), name, chunks = { { offset, size, key } } } -- offsets of the chunk data, absolute +-- local w = Avi.writer({ streams = {...}, avih = {...} }); w:chunk(streamIndex, data, key); local file = w:finish() +-- +-- Never throws: malformed data returns nil, Err (a damaged index falls back to scanning). +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") + +local readu8, readu16, readu32, readstring = buffer.readu8, buffer.readu16, buffer.readu32, buffer.readstring + +local Avi = {} + +export type Chunk = { offset: number, size: number, key: boolean } +export type Stream = { + index: number, -- 0-based stream number (the "##" of the chunk ids) + type: string, -- strh fccType: "vids", "auds", "txts", "mids" + handler: string, + flags: number, + scale: number, + rate: number, + start: number, + length: number, + suggestedBufferSize: number, + sampleSize: number, + frame: { number }, -- rcFrame left, top, right, bottom + strf: buffer, -- the format block (BITMAPINFOHEADER / WAVEFORMATEX ...) + name: string?, + chunks: { Chunk }, +} +export type File = { + avih: { microSecPerFrame: number, flags: number, totalFrames: number, streams: number, width: number, height: number }, + streams: { Stream }, + odml: { totalFrames: number }?, + info: { [string]: string }, + index: string, -- "odml" | "idx1" | "scan" +} + +local function u32(b: buffer, o: number): number + return readu32(b, o) +end + +-- chunk walker over [p, limit): calls fn(id, dataOffset, size, listType?) for each chunk (LIST bodies are not +-- entered); returns where it stopped +local function walk(b: buffer, p: number, limit: number, fn: (id: string, data: number, size: number, ltype: string?) -> boolean?): number + while p + 8 <= limit do + local id = readstring(b, p, 4) + local size = u32(b, p + 4) + local data = p + 8 + local ltype: string? = nil + if (id == "LIST" or id == "RIFF") and data + 4 <= limit then + ltype = readstring(b, data, 4) + end + if data + size > limit then + size = limit - data + end + if fn(id, data, size, ltype) == false then + return p + end + p = data + size + (size % 2) + end + return p +end + +local function streamNumber(id: string): number? + local a, b = string.byte(id, 1, 2) + if not a or not b then + return nil + end + local function hex(c: number): number? + if c >= 48 and c <= 57 then + return c - 48 + elseif c >= 65 and c <= 70 then + return c - 55 + elseif c >= 97 and c <= 102 then + return c - 87 + end + return nil + end + local h, l = hex(a), hex(b) + if h and l then + return h * 16 + l + end + return nil +end +Avi.streamNumber = streamNumber + +local function parseStrl(b: buffer, data: number, size: number, index: number): Stream + local s: Stream = { + index = index, + type = "", + handler = "", + flags = 0, + scale = 1, + rate = 1, + start = 0, + length = 0, + suggestedBufferSize = 0, + sampleSize = 0, + frame = { 0, 0, 0, 0 }, + strf = buffer.create(0), + chunks = {}, + } + local indx: { number }? = nil + walk(b, data + 4, data + size, function(id: string, d: number, n: number): boolean? + if id == "strh" and n >= 48 then + s.type = readstring(b, d, 4) + s.handler = readstring(b, d + 4, 4) + s.flags = u32(b, d + 8) + s.scale = u32(b, d + 20) + s.rate = u32(b, d + 24) + s.start = u32(b, d + 28) + s.length = u32(b, d + 32) + s.suggestedBufferSize = u32(b, d + 36) + s.sampleSize = u32(b, d + 44) + if n >= 56 then + s.frame = { buffer.readi16(b, d + 48), buffer.readi16(b, d + 50), buffer.readi16(b, d + 52), buffer.readi16(b, d + 54) } + end + elseif id == "strf" then + local f = buffer.create(n) + buffer.copy(f, 0, b, d, n) + s.strf = f + elseif id == "strn" then + local str = readstring(b, d, n) + s.name = string.match(str, "^[^%z]*") + elseif id == "indx" and n >= 24 then + indx = { d, n } + end + return nil + end) + ;(s :: any)._indx = indx + return s +end + +-- an OpenDML index chunk (indx super index or ix## standard index) at d with n bytes: appends chunks to s +local function readIndex(b: buffer, d: number, n: number, s: Stream, limit: number, depth: number): boolean + if n < 24 or depth > 2 then + return false + end + local longsPerEntry = readu16(b, d) + local subType = readu8(b, d + 2) + local indexType = readu8(b, d + 3) + local entries = u32(b, d + 4) + if indexType == 0 then -- AVI_INDEX_OF_INDEXES: { qwOffset, dwSize, dwDuration } + if longsPerEntry ~= 4 then + return false + end + local p = d + 24 + for _ = 1, entries do + if p + 16 > d + n then + break + end + local off = u32(b, p) + u32(b, p + 4) * 4294967296 + local size = u32(b, p + 8) + p += 16 + if off > 0 and off + 8 <= limit then + local sz = math.min(u32(b, off + 4), limit - off - 8) + readIndex(b, off + 8, if size > 0 then math.min(sz, size) else sz, s, limit, depth + 1) + end + end + return #s.chunks > 0 + elseif indexType == 1 then -- AVI_INDEX_OF_CHUNKS: base offset, { dwOffset, dwSize } (or field index: 3 longs) + if n < 24 then + return false + end + local base = u32(b, d + 12) + u32(b, d + 16) * 4294967296 + local per = if subType == 1 then 12 else 8 -- AVI_INDEX_2FIELD + local p = d + 24 + for _ = 1, entries do + if p + per > d + n then + break + end + local off = u32(b, p) + local size = u32(b, p + 4) + p += per + local key = size < 0x80000000 + size %= 0x80000000 + local at = base + off + if at >= 0 and at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = key }) + end + end + return true + end + return false +end + +-- read(buf, base, limit) -> File | nil, Err +function Avi.read(b: buffer, base: number, limit: number): (File?, Err.Err?) + if limit - base < 12 or readstring(b, base, 4) ~= "RIFF" or readstring(b, base + 8, 4) ~= "AVI " then + return nil, Err.new(Err.CORRUPT, "not an AVI file", base) + end + local file: File = { + avih = { microSecPerFrame = 0, flags = 0, totalFrames = 0, streams = 0, width = 0, height = 0 }, + streams = {}, + odml = nil, + info = {}, + index = "scan", + } + local movis: { { number } } = {} -- { data offset of the 'movi' fourcc, end } + local idx1: { number }? = nil + local hdrl = false + -- every RIFF piece (AVI, then AVIX for OpenDML files) + walk(b, base, limit, function(id: string, d: number, n: number, ltype: string?): boolean? + if id ~= "RIFF" then + return nil + end + walk(b, d + 4, d + n, function(cid: string, cd: number, cn: number, cltype: string?): boolean? + if cid == "LIST" and cltype == "hdrl" and not hdrl then + hdrl = true + local si = 0 + walk(b, cd + 4, cd + cn, function(hid: string, hd: number, hn: number, hltype: string?): boolean? + if hid == "avih" and hn >= 40 then + file.avih = { + microSecPerFrame = u32(b, hd), + flags = u32(b, hd + 12), + totalFrames = u32(b, hd + 16), + streams = u32(b, hd + 24), + width = u32(b, hd + 32), + height = u32(b, hd + 36), + } + elseif hid == "LIST" and hltype == "strl" then + table.insert(file.streams, parseStrl(b, hd, hn, si)) + si += 1 + elseif hid == "LIST" and hltype == "odml" then + walk(b, hd + 4, hd + hn, function(oid: string, od: number, on: number): boolean? + if oid == "dmlh" and on >= 4 then + file.odml = { totalFrames = u32(b, od) } + end + return nil + end) + end + return nil + end) + elseif cid == "LIST" and cltype == "movi" then + table.insert(movis, { cd, cd + cn }) + elseif cid == "LIST" and cltype == "INFO" then + walk(b, cd + 4, cd + cn, function(iid: string, idd: number, inn: number): boolean? + file.info[iid] = string.match(readstring(b, idd, inn), "^[^%z]*") or "" + return nil + end) + elseif cid == "idx1" and not idx1 then + idx1 = { cd, cn } + end + return nil + end) + return nil + end) + if not hdrl then + return nil, Err.new(Err.CORRUPT, "no hdrl list") + end + if #file.streams == 0 then + return nil, Err.new(Err.CORRUPT, "no streams") + end + -- 1. OpenDML indexes + local odml = true + for _, s in file.streams do + local ix = (s :: any)._indx + if not ix or not readIndex(b, ix[1], ix[2], s, limit, 0) then + odml = false + end + end + if odml then + file.index = "odml" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 2. idx1 + local ok = false + if idx1 and movis[1] then + local d, n = idx1[1], idx1[2] + local count = n // 16 + local moviBase = movis[1][1] -- the 'movi' fourcc + -- relative or absolute offsets: check the first entry that points at a chunk id + local rel = true + if count > 0 then + local off = u32(b, d + 8) + local ckid = readstring(b, d, 4) + local relAt, absAt = moviBase + off, base + off + if relAt + 4 <= limit and readstring(b, relAt, 4) == ckid then + rel = true + elseif absAt + 4 <= limit and readstring(b, absAt, 4) == ckid then + rel = false + end + end + for k = 0, count - 1 do + local e = d + k * 16 + local ckid = readstring(b, e, 4) + local flags = u32(b, e + 4) + local off = u32(b, e + 8) + local size = u32(b, e + 12) + local sn = streamNumber(ckid) + local s = sn and file.streams[sn + 1] + if s and string.sub(ckid, 3, 4) ~= "pc" then + local at = (if rel then moviBase else base) + off + 8 + if at + size <= limit then + table.insert(s.chunks, { offset = at, size = size, key = bit32.band(flags, 0x10) ~= 0 }) + ok = true + end + end + end + end + if ok then + file.index = "idx1" + else + for _, s in file.streams do + table.clear(s.chunks) + end + -- 3. scan the movi lists + local function scan(d0: number, e0: number) + walk(b, d0, e0, function(id: string, d: number, n: number, ltype: string?): boolean? + if id == "LIST" and ltype == "rec " then + scan(d + 4, d + n) + return nil + end + local sn = streamNumber(id) + local s = sn and file.streams[sn + 1] + if s and string.sub(id, 1, 2) ~= "ix" and string.sub(id, 3, 4) ~= "pc" then + table.insert(s.chunks, { offset = d, size = n, key = true }) + end + return nil + end) + end + for _, m in movis do + scan(m[1] + 4, m[2]) + end + file.index = "scan" + end + end + for _, s in file.streams do + (s :: any)._indx = nil + end + return file, nil +end + +-- ------------------------------------------------------------------------------------------------ writing +export type WStream = { + type: string, -- "vids" | "auds" + handler: string, -- fccHandler (4 chars) + scale: number, + rate: number, + sampleSize: number, -- 0 = every chunk one sample (video, VBR audio) + strf: buffer, + name: string?, + width: number?, + height: number?, + quality: number?, + ckid: string?, -- the chunk id suffix: "dc" (video), "wb" (audio) +} +export type WOptions = { + streams: { WStream }, + microSecPerFrame: number, + width: number, + height: number, + software: string?, +} + +-- write(opts, chunks) -> buffer: chunks = { { stream (1-based), data: buffer, key: boolean } } in file order +function Avi.write(opts: WOptions, chunks: { { any } }): buffer + local ns = #opts.streams + local lengths = table.create(ns, 0) + local maxChunk = table.create(ns, 0) + local bytes = table.create(ns, 0) + local total = 0 + for _, c in chunks do + local si, data = c[1], c[2] + local n = buffer.len(data) + local s = opts.streams[si] + if s.sampleSize > 0 then + lengths[si] += n // s.sampleSize + else + lengths[si] += 1 + end + bytes[si] += n + if n > maxChunk[si] then + maxChunk[si] = n + end + total += n + 8 + (n % 2) + end + local frames = 0 + for si, s in opts.streams do + if s.type == "vids" and frames == 0 then + frames = lengths[si] + end + end + local w = Bytes.writer(total + 4096 + #chunks * 16) + w:string("RIFF") + local riffSize = w:tell() + w:u32le(0) + w:string("AVI ") + -- hdrl + w:string("LIST") + local hdrlSize = w:tell() + w:u32le(0) + w:string("hdrl") + w:string("avih") + w:u32le(56) + local duration = if opts.microSecPerFrame > 0 then frames * opts.microSecPerFrame / 1e6 else 1 + local maxBytes = 0 + for si = 1, ns do + maxBytes += bytes[si] + end + w:u32le(math.floor(opts.microSecPerFrame + 0.5)) + w:u32le(if duration > 0 then math.floor(maxBytes / duration) else 0) + w:u32le(0) -- padding granularity + w:u32le(0x10 + 0x100) -- AVIF_HASINDEX | AVIF_ISINTERLEAVED + w:u32le(frames) + w:u32le(0) -- initial frames + w:u32le(ns) + local suggested = 0 + for si = 1, ns do + suggested = math.max(suggested, maxChunk[si] + 8) + end + w:u32le(suggested) + w:u32le(opts.width) + w:u32le(opts.height) + for _ = 1, 4 do + w:u32le(0) + end + for si, s in opts.streams do + w:string("LIST") + local strlSize = w:tell() + w:u32le(0) + w:string("strl") + w:string("strh") + w:u32le(56) + w:string(s.type) + w:string(s.handler) + w:u32le(0) -- flags + w:u16le(0) -- priority + w:u16le(0) -- language + w:u32le(0) -- initial frames + w:u32le(s.scale) + w:u32le(s.rate) + w:u32le(0) -- start + w:u32le(lengths[si]) + w:u32le(maxChunk[si]) + w:u32le(if s.quality then s.quality else 0xFFFFFFFF) + w:u32le(s.sampleSize) + w:u16le(0) + w:u16le(0) + w:u16le(s.width or 0) + w:u16le(s.height or 0) + w:string("strf") + w:u32le(buffer.len(s.strf)) + w:bytes(s.strf) + if buffer.len(s.strf) % 2 == 1 then + w:u8(0) + end + if s.name then + local nm = s.name .. "\0" + w:string("strn") + w:u32le(#nm) + w:string(nm) + if #nm % 2 == 1 then + w:u8(0) + end + end + w:setU32le(strlSize, w:tell() - strlSize - 4) + end + -- OpenDML extended header (total frames) + w:string("LIST") + w:u32le(16) + w:string("odml") + w:string("dmlh") + w:u32le(4) + w:u32le(frames) + w:setU32le(hdrlSize, w:tell() - hdrlSize - 4) + -- INFO + local sw = (opts.software or "formats-luau") .. "\0" + if #sw % 2 == 1 then + sw ..= "\0" + end + w:string("LIST") + w:u32le(4 + 8 + #sw) + w:string("INFO") + w:string("ISFT") + w:u32le(#sw) + w:string(sw) + -- movi + w:string("LIST") + local moviSize = w:tell() + w:u32le(0) + local moviBase = w:tell() + w:string("movi") + local index = table.create(#chunks) + for _, c in chunks do + local si, data, key = c[1], c[2], c[3] + local s = opts.streams[si] + local id = string.format("%02d", si - 1) .. (s.ckid or (if s.type == "vids" then "dc" else "wb")) + local at = w:tell() + local n = buffer.len(data) + w:string(id) + w:u32le(n) + w:bytes(data) + if n % 2 == 1 then + w:u8(0) + end + table.insert(index, { id, if key then 0x10 else 0, at - moviBase, n }) + end + w:setU32le(moviSize, w:tell() - moviSize - 4) + -- idx1 + w:string("idx1") + w:u32le(#index * 16) + for _, e in index do + w:string(e[1]) + w:u32le(e[2]) + w:u32le(e[3]) + w:u32le(e[4]) + end + w:setU32le(riffSize, w:tell() - 8) + return w:finish() +end + +return Avi diff --git a/src/Formats/init.luau b/src/Formats/init.luau index a87e3e8..42bb46c 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -268,7 +268,11 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?) if not buf then return nil, err end - return F.open(buf, { format = fmt, category = "audio" }) + local dec, oerr = F.open(buf, { format = fmt, category = "audio" }) + if dec and fmt ~= "opus" and type(track.codecDelay) == "number" and track.codecDelay > 0 then + dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5)) + end + return dec, oerr end local function withHooks(o: Options): Options diff --git a/src/Formats/video/avi/init.luau b/src/Formats/video/avi/init.luau new file mode 100644 index 0000000..5a368fa --- /dev/null +++ b/src/Formats/video/avi/init.luau @@ -0,0 +1,331 @@ +--!strict +-- video/avi: AVI (Microsoft RIFF AVI 1.0, OpenDML 1.02). New in formats-luau, on containers/Avi. +-- Read: open() indexes every stream (OpenDML super / standard indexes, else idx1, else a movi scan; RIFF AVIX pieces +-- of files over 1 GB) and returns a VideoDecoder: video through the codecs/Video registry by FourCC (MJPEG, MPEG-1, +-- uncompressed BI_RGB 24 / 32-bit bottom-up or top-down, I420 / YV12; H.264 and others when a decoder is +-- registered), audio through the api's opts.openAudio hook (PCM, A-law / mu-law, IMA / MS ADPCM with its WAVEFORMATEX, +-- MP3 / MP2, AAC). Dropped frames (empty video chunks) keep their time slot. Avi.demux(r) gives the Demuxer. +-- Write: MJPEG video (copied from an MJPEG source, else every frame encoded; variable frame delays such as a GIF's +-- become a constant rate with repeated frames) plus PCM s16 audio, AVI 1.0 with idx1 and an odml / dmlh header. +-- Not supported: writing files over 1 GB (no AVIX pieces), palette changes (##pc chunks are skipped), text streams. + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Avi = require("@formats/containers/Avi") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local AviFormat = { + name = "avi", + category = "video", + extensions = { "avi" }, + mime = { "video/x-msvideo", "video/avi" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Avi", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "mjpeg", "mpeg1", "rawvideo" }, audio = true, odml = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: the codec's native yuv420p; BI_RGB gives rgba8) + track: number?, -- the video track (stream index + 1) to decode + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + openAudio: any?, -- set by the api +} +export type EncodeOptions = { + quality: number?, -- MJPEG quality 1..100 (default 90) + reencode: boolean?, -- encode the frames even when the source is MJPEG + audio: boolean?, -- false: no audio (default: PCM s16 from the source's audio, when it has one) + video: boolean?, + maxFps: number?, -- the highest frame rate variable delays may need (default 100) +} + +-- ------------------------------------------------------------------------------------------------ constants +-- WAVEFORMATEX wFormatTag -> codec id +local AUDIO_TAGS: { [number]: string } = { + [0x0001] = "pcm", + [0x0002] = "adpcm_ms", + [0x0003] = "pcm_f", + [0x0006] = "pcm_alaw", + [0x0007] = "pcm_mulaw", + [0x0011] = "adpcm_ima_wav", + [0x0050] = "mp2", + [0x0055] = "mp3", + [0x00FF] = "aac", + [0x1610] = "aac", + [0x706D] = "aac", + [0x2000] = "ac3", + [0x2001] = "dts", + [0xF1AC] = "flac", +} + +-- ------------------------------------------------------------------------------------------------ sniff +function AviFormat.sniff(r: Bytes.Reader): number + if r:peek(4) == "RIFF" and r:peek(4, 8) == "AVI " then + return 1 + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function videoTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "video", + codec = "", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 25, + frameRate = if s.scale > 0 then s.rate / s.scale else 0, + default = true, + name = s.name, + frames = s.length, + } + if buffer.len(f) >= 40 then + local w = buffer.readi32(f, 4) + local h = buffer.readi32(f, 8) + local bits = buffer.readu16(f, 14) + local comp = buffer.readstring(f, 16, 4) + t.width = math.abs(w) + t.height = math.abs(h) + t.codecTag = comp + t.bitsPerPixel = bits + if comp == "\0\0\0\0" or comp == "DIB " or comp == "RGB " then + t.codec = "rawvideo" + t.pixelFormat = if bits == 32 then "bgra" else "bgr24" + t.flip = h > 0 + t.stride = ((math.abs(w) * bits + 31) // 32) * 4 + if bits ~= 24 and bits ~= 32 then + t.codec = "rawvideo_" .. bits + end + else + t.codec = Video.fromFourcc(comp) or Video.fromFourcc(s.handler) or string.lower((string.gsub(comp, "%z", ""))) + if comp == "YV12" then + t.pixelFormat = "yv12" + elseif t.codec == "rawvideo" then + t.pixelFormat = "yuv420p" + end + end + local size = buffer.readu32(f, 0) + if size > 40 and buffer.len(f) > 40 then + local c = buffer.create(buffer.len(f) - 40) + buffer.copy(c, 0, f, 40) + t.config = c + end + else + t.codec = Video.fromFourcc(s.handler) or string.lower(s.handler) + local fr = s.frame + t.width, t.height = fr[3] - fr[1], fr[4] - fr[2] + end + return t +end + +local function audioTrack(s: Avi.Stream, id: number): Types.Track + local f = s.strf + local t: any = { + id = id, + kind = "audio", + codec = "unknown", + codecTag = s.handler, + timescale = if s.scale > 0 then s.rate / s.scale else 1, + default = true, + name = s.name, + waveFormat = f, + } + if buffer.len(f) >= 16 then + local tag = buffer.readu16(f, 0) + t.channels = buffer.readu16(f, 2) + t.sampleRate = buffer.readu32(f, 4) + t.blockAlign = buffer.readu16(f, 12) + local bits = buffer.readu16(f, 14) + t.bitsPerSample = bits + if tag == 0xFFFE and buffer.len(f) >= 26 then + tag = buffer.readu16(f, 24) -- WAVE_FORMAT_EXTENSIBLE: the sub-format GUID's tag + end + t.formatTag = tag + local c = AUDIO_TAGS[tag] or string.format("wav_0x%04x", tag) + if c == "pcm" then + c = if bits == 8 then "pcm_u8" else "pcm_s" .. bits .. "le" + elseif c == "pcm_f" then + c = "pcm_f" .. bits .. "le" + end + t.codec = c + if buffer.len(f) >= 18 then + local cb = buffer.readu16(f, 16) + if cb > 0 and 18 + cb <= buffer.len(f) and c ~= "mp3" then + local cfg = buffer.create(cb) + buffer.copy(cfg, 0, f, 18, cb) + t.config = cfg + end + end + end + return t +end + +-- demux(r, opts?) -> the Demuxer | nil, Err +function AviFormat.demux(r: Bytes.Reader, _opts: OpenOptions?): (any, Err.Err?) + local ok, file, err = pcall(Avi.read, r.buf, r.base, r.limit) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(file)) + end + if not file then + return nil, err + end + local tracks: { Types.Track } = {} + local streams: { { any } } = {} + for i, s in file.streams do + local t: Types.Track? = nil + if s.type == "vids" then + t = videoTrack(s, i) + elseif s.type == "auds" then + t = audioTrack(s, i) + elseif s.type == "txts" then + t = { id = i, kind = "subtitle", codec = "text", timescale = if s.scale > 0 then s.rate / s.scale else 1 } + end + if t then + table.insert(tracks, t) + table.insert(streams, { s, t }) + end + end + local meta = { info = file.info, index = file.index, odml = file.odml ~= nil } + local dmx = Demux.new("avi", tracks, r.buf, meta) + -- packets in file order across streams: merge by offset + local items: { { number } } = {} + for k, st in streams do + local s: Avi.Stream, t: any = st[1], st[2] + local tick = s.start + for _, c in s.chunks do + local dur = if s.sampleSize > 0 then c.size / s.sampleSize else 1 + if t.kind == "audio" and s.sampleSize == 0 and (t.blockAlign or 0) > 0 and t.codec:sub(1, 3) == "pcm" then + dur = c.size / t.blockAlign + end + if c.size > 0 then + table.insert(items, { c.offset, k, tick, dur, if c.key then 1 else 0, c.size }) + end + tick += dur + end + end + table.sort(items, function(a: { number }, b: { number }): boolean + return a[1] < b[1] + end) + for _, it in items do + local t: any = streams[it[2]][2] + dmx:add(t.id, it[3], nil, it[4], it[5] == 1 or t.kind ~= "video" or t.codec == "mjpeg" or t.codec == "rawvideo", it[1], it[6]) + end + dmx:finish() + return dmx, nil +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 {}) + o.quality = o.quality or 90 + local streams, err = Source.streams(value, o, { + video = { copy = { mjpeg = true }, encode = "mjpeg" }, + audio = { copy = { pcm_s16le = true, pcm_u8 = true }, pcm = true }, + }) + if not streams then + return nil, err + end + local wstreams: { Avi.WStream } = {} + local width, height, usPerFrame = 0, 0, 0 + local frameDur = 0 + 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) + frameDur = den / num + width, height = s.width or 0, s.height or 0 + usPerFrame = 1e6 * frameDur + local bih = Bytes.writer(40) + bih:u32le(40) + bih:u32le(width) + bih:u32le(height) + bih:u16le(1) + bih:u16le(24) + bih:string("MJPG") + bih:u32le(width * height * 3) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + bih:u32le(0) + table.insert(wstreams, { type = "vids", handler = "MJPG", scale = den, rate = num, sampleSize = 0, strf = bih:finish(), width = width, height = height, ckid = "dc" }) + else + local ch = s.channels or 1 + local bits = if s.codec == "pcm_u8" then 8 else 16 + local align = ch * bits // 8 + local rate = math.floor((s.sampleRate or 44100) + 0.5) + local wf = Bytes.writer(18) + wf:u16le(1) + wf:u16le(ch) + wf:u32le(rate) + wf:u32le(rate * align) + wf:u16le(align) + wf:u16le(bits) + wf:u16le(0) + 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) + 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 + end + local ok, buf = pcall(Avi.write, { streams = wstreams, microSecPerFrame = usPerFrame, width = width, height = height }, chunks) + if not ok then + return nil, Err.new(Err.ARG, "internal error: " .. tostring(buf)) + end + return buf, nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function AviFormat.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = AviFormat.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return AviFormat diff --git a/src/Formats/video/mkv/Parse.luau b/src/Formats/video/mkv/Parse.luau index 4c8b0ce..ce5b489 100644 --- a/src/Formats/video/mkv/Parse.luau +++ b/src/Formats/video/mkv/Parse.luau @@ -9,6 +9,7 @@ local Types = require("@formats/Types") local Ebml = require("@formats/containers/Ebml") local Demux = require("@formats/containers/Demux") local Video = require("@formats/codecs/Video") +local Deflate = require("@formats/codecs/Deflate") local Parse = {} @@ -56,6 +57,7 @@ local ID = { ContentEncodings = 0x6D80, ContentEncoding = 0x6240, ContentEncodingType = 0x5033, + ContentEncodingScope = 0x5032, ContentCompression = 0x5034, ContentCompAlgo = 0x4254, ContentCompSettings = 0x4255, @@ -182,13 +184,17 @@ local function parseAudio(buf: buffer, off: number, len: number, t: any) end end --- ContentEncodings: header stripping (algo 3) is supported; zlib / bzip / lzo compression and encryption are not +-- ContentEncodings: header stripping (algo 3) and zlib (algo 0) are supported; bzip / lzo compression and encryption +-- are not local function parseEncodings(buf: buffer, off: number, len: number, t: any): string? for id, o, n in Ebml.children(buf, off, off + len) do if id == ID.ContentEncoding then local etype = 0 + local scope = 1 for id2, o2, n2 in Ebml.children(buf, o, o + n) do - if id2 == ID.ContentEncodingType then + if id2 == ID.ContentEncodingScope then + scope = Ebml.uint(buf, o2, n2) + elseif id2 == ID.ContentEncodingType then etype = Ebml.uint(buf, o2, n2) elseif id2 == ID.ContentCompression then local algo, settings = 0, nil @@ -201,6 +207,8 @@ local function parseEncodings(buf: buffer, off: number, len: number, t: any): st end if algo == 3 then t.strip = settings + elseif algo == 0 then + t.zlib = scope -- 1: frames, 2: CodecPrivate else return "content compression algorithm " .. algo end @@ -259,6 +267,14 @@ local function parseTracks(buf: buffer, off: number, len: number, scaleNs: numbe problem = parseEncodings(buf, o2, n2, t) end end + if t.zlib and bit32.band(t.zlib, 2) ~= 0 and t.config then + local c = Deflate.zlib(t.config) + if c then + t.config = c + else + problem = "bad zlib-compressed CodecPrivate" + end + end t.kind = if ttype == 1 then "video" elseif ttype == 2 then "audio" elseif ttype == 17 then "subtitle" else "data" t.codecTag = codecId t.codec = codecFor(codecId, t.kind, t.bitsPerSample) @@ -465,14 +481,21 @@ local function block(ctx: Ctx, off: number, len: number, clusterTime: number, si return end local d = if #sizes == 1 then durTicks else (if stepTicks > 0 then stepTicks else nil) + local kf = key and (k == 1 or t.kind ~= "video") local strip = t.strip - if strip then + local z = (t :: any).zlib + if z and bit32.band(z, 1) ~= 0 then + local out = Deflate.zlib(buf, p, s) + if out then + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, out) + end + elseif strip then local nb = buffer.create(buffer.len(strip) + s) buffer.copy(nb, 0, strip) buffer.copy(nb, buffer.len(strip), buf, p, s) - dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, key and k == 1, nb) + dmx:addData(tn, pts + (k - 1) * stepTicks, nil, d, kf, nb) else - dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, key and (k == 1 or t.kind ~= "video"), p, s) + dmx:add(tn, pts + (k - 1) * stepTicks, nil, d, kf, p, s) end if discardNs and k == #sizes then dmx:setExtra("discardPadding", discardNs / 1e9) diff --git a/src/Formats/video/mkv/init.luau b/src/Formats/video/mkv/init.luau index 18cd8c8..be9766a 100644 --- a/src/Formats/video/mkv/init.luau +++ b/src/Formats/video/mkv/init.luau @@ -2,14 +2,14 @@ -- video/mkv: Matroska and WebM (the Matroska specification / RFC 9559, the WebM container guidelines). New in -- formats-luau, on containers/Ebml. -- Read: open() demuxes the whole file into a packet index (SimpleBlock / BlockGroup, Xiph / EBML / fixed lacing, --- header-stripping compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video +-- header-stripping and zlib compression, unknown-size clusters, Cues and Tags in meta) and returns a VideoDecoder: video -- through the codecs/Video registry (VP8 with inter frames, MJPEG, MPEG-1, raw; H.264 when registered), audio -- through the api's opts.openAudio hook (Opus, Vorbis, FLAC, MP3, PCM, AAC, ... reach the audio formats), text -- subtitle tracks as cues (Mkv.subtitles). Mkv.demux(r) gives the Demuxer alone. -- Write: WebM (opts.format = "webm" or a .webm destination: VP8 / VP9 / AV1 video and Opus / Vorbis audio, copied -- from the source since VP8 is decode-only) and Matroska (any registered video codec copied, else MJPEG encoded from -- the frames; audio copied, else PCM s16), with SeekHead, Cues and Duration. --- Not supported: zlib / bzip2 / lzo content compression and encryption (the track's packets are left as stored, +-- Not supported: bzip2 / lzo content compression and encryption (the track's packets are left as stored, -- track.unsupported says why), chapters / attachments (skipped), writing subtitles. -- ------------------------------------------------------------------------------------------------ requires @@ -27,7 +27,7 @@ local Mkv = { category = "video", extensions = { "mkv", "webm", "mka", "mk3d" }, mime = { "video/x-matroska", "video/webm", "audio/x-matroska", "audio/webm" }, - deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ebml", "containers/Demux", "codecs/Deflate", "codecs/Video", "codecs/Video/Source" }, caps = { decode = true, encode = true, streaming = true, remux = true, video = { "vp8", "mjpeg", "mpeg1", "rawvideo" }, audio = true, subtitles = true }, } diff --git a/src/Formats/video/y4m/init.luau b/src/Formats/video/y4m/init.luau new file mode 100644 index 0000000..99c3384 --- /dev/null +++ b/src/Formats/video/y4m/init.luau @@ -0,0 +1,222 @@ +--!strict +-- video/y4m: YUV4MPEG2 (the mjpegtools / ffmpeg raw video stream). New in formats-luau. +-- Read: the stream header (W H F I A C X tags) and every FRAME into a raw-video Demuxer; open() returns a VideoDecoder +-- 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), +-- alpha (C444alpha drops it). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Demux = require("@formats/containers/Demux") +local Video = require("@formats/codecs/Video") +local Source = require("@formats/codecs/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Y4m = { + name = "y4m", + category = "video", + extensions = { "y4m" }, + mime = { "video/x-yuv4mpeg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Demux", "codecs/Video", "codecs/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, video = { "rawvideo" }, depths = { 8, 10, 12, 16 } }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 (default false: yuv420p) + maxPixels: number?, -- default 2^26 +} +export type EncodeOptions = { + frameRate: { number }?, -- { num, den } for the F tag (default: from the source's frame rate) +} + +-- ------------------------------------------------------------------------------------------------ constants +local MAGIC = "YUV4MPEG2 " +-- C tag -> pixel format, bits +local COLOR: { [string]: { any } } = { + ["420jpeg"] = { "yuv420p", 8 }, + ["420paldv"] = { "yuv420p", 8 }, + ["420mpeg2"] = { "yuv420p", 8 }, + ["420"] = { "yuv420p", 8 }, + ["422"] = { "yuv422p", 8 }, + ["444"] = { "yuv444p", 8 }, + ["444alpha"] = { "yuva444p", 8 }, + mono = { "gray", 8 }, +} +for _, b in { 9, 10, 12, 14, 16 } do + COLOR["420p" .. b] = { "yuv420p", b } + COLOR["422p" .. b] = { "yuv422p", b } + COLOR["444p" .. b] = { "yuv444p", b } + COLOR["mono" .. b] = { "gray", b } +end + +-- ------------------------------------------------------------------------------------------------ sniff +function Y4m.sniff(r: Bytes.Reader): number + return if r:peek(10) == MAGIC then 1 else 0 +end + +-- ------------------------------------------------------------------------------------------------ decode +local function frameSize(pf: string, bits: number, w: number, h: number): number + local bps = if bits > 8 then 2 else 1 + local cw, ch = (w + 1) // 2, (h + 1) // 2 + if pf == "yuv420p" then + return (w * h + 2 * cw * ch) * bps + elseif pf == "yuv422p" then + return (w * h + 2 * cw * h) * bps + elseif pf == "yuv444p" then + return w * h * 3 * bps + elseif pf == "yuva444p" then + return w * h * 4 * bps + end + return w * h * bps +end + +-- demux(r, opts?) -> the raw-video Demuxer | nil, Err +function Y4m.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local buf, base, limit = r.buf, r.base, r.limit + local nl = -1 + for i = base, math.min(limit, base + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + nl = i + break + end + end + if limit - base < 10 or buffer.readstring(buf, base, 10) ~= MAGIC then + return nil, Err.new(Err.CORRUPT, "not a YUV4MPEG2 stream", base) + end + if nl < 0 then + return nil, Err.new(Err.TRUNCATED, "no end of the stream header", base) + end + local header = buffer.readstring(buf, base + 10, nl - base - 10) + local w, h, fn, fd = 0, 0, 25, 1 + local ctag, itag, atag = "420jpeg", "p", "0:0" + local extra = {} + for tok in string.gmatch(header, "%S+") do + local k, v = string.sub(tok, 1, 1), string.sub(tok, 2) + if k == "W" then + w = tonumber(v) or 0 + elseif k == "H" then + h = tonumber(v) or 0 + elseif k == "F" then + local a, b = string.match(v, "^(%d+):(%d+)$") + if a and b and tonumber(a) > 0 and tonumber(b) > 0 then + fn, fd = tonumber(a) :: number, tonumber(b) :: number + end + elseif k == "C" then + ctag = v + elseif k == "I" then + itag = v + elseif k == "A" then + atag = v + elseif k == "X" then + table.insert(extra, v) + end + end + local color = COLOR[ctag] + if not color then + return nil, Err.new(Err.UNSUPPORTED, "colour space C" .. ctag) + end + if w <= 0 or h <= 0 or w > 65535 or h > 65535 then + return nil, Err.new(Err.CORRUPT, "bad frame size " .. w .. "x" .. h) + end + local maxPixels = opts and opts.maxPixels or 2 ^ 26 + if w * h > maxPixels then + return nil, Err.new(Err.LIMIT, "frame of " .. w .. "x" .. h .. " pixels") + end + local pf, bits = color[1], color[2] + local size = frameSize(pf, bits, w, h) + local track: Types.Track = { + id = 1, + kind = "video", + codec = "rawvideo", + codecTag = "C" .. ctag, + timescale = fn / fd, + width = w, + height = h, + frameRate = fn / fd, + pixelFormat = pf, + bitDepth = bits, + default = true, + } + local meta = { interlace = itag, aspect = atag, extra = extra, colorTag = ctag } + local dmx = Demux.new("y4m", { track }, buf, meta) + local pos = nl + 1 + local k = 0 + while pos + 5 <= limit do + if buffer.readstring(buf, pos, 5) ~= "FRAME" then + return nil, Err.new(Err.CORRUPT, "expected FRAME", pos) + end + local e = -1 + for i = pos + 5, math.min(limit, pos + 4096) - 1 do + if buffer.readu8(buf, i) == 10 then + e = i + break + end + end + if e < 0 then + break + end + local data = e + 1 + if data + size > limit then + break -- a truncated last frame is dropped + end + dmx:add(1, k, k, 1, true, data, size) + k += 1 + pos = data + size + end + dmx:finish() + return dmx, nil +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" } }) + if not streams then + return nil, err + end + local s = streams[1] + local fn, fd + if opts and type(opts.frameRate) == "table" then + fn, fd = opts.frameRate[1], opts.frameRate[2] + else + fn, fd = rational(s.frameRate or 25) + end + 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 + w:string("FRAME\n") + w:bytes(p.data) + end + return w:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- open(r, opts?) -> a VideoDecoder | nil, Err +function Y4m.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local dmx, err = Y4m.demux(r, opts) + if not dmx then + return nil, err + end + return Video.open(dmx, opts) +end + +return Y4m diff --git a/tests/video/_common.luau b/tests/video/_common.luau new file mode 100644 index 0000000..7da0caa --- /dev/null +++ b/tests/video/_common.luau @@ -0,0 +1,214 @@ +-- tests/video/_common: shared checks for the video container tests (mkv, avi, y4m, mpegts, mpegps, mp4): a demuxer's +-- tracks and packets against ffprobe's, decoded frames against ffmpeg's (CRC-32 for bit-exact codecs, PSNR for the +-- others), audio through the api's hook against ffmpeg's f32 decode, seeking. Not a test by itself. +local F = require("@formats") +local Bytes = require("@formats/core/Bytes") +local Crc32 = require("@formats/core/Crc32") +local Video = require("@formats/codecs/Video") + +local C = {} + +-- the codecs whose decode must equal ffmpeg's bit for bit +C.EXACT = { vp8 = true, rawvideo = true } + +-- psnr(a, b, off?, n?) -> dB between two byte strings / buffers (math.huge when equal) +function C.psnr(a: buffer, b: buffer, n: number?): number + local len = n or math.min(buffer.len(a), buffer.len(b)) + local se = 0 + for i = 0, len - 1 do + local d = buffer.readu8(a, i) - buffer.readu8(b, i) + se += d * d + end + if se == 0 then + return math.huge + end + return 10 * math.log10(255 * 255 * len / se) +end + +-- snr(ours f32 buffer, reference f32 string, n samples) -> dB +function C.snr(ours: buffer, ref: string, n: number): number + local rb = buffer.fromstring(ref) + local sig, err = 0, 0 + for i = 0, n - 1 do + local r = buffer.readf32(rb, i * 4) + local d = buffer.readf32(ours, i * 4) - r + sig += r * r + err += d * d + end + if err == 0 then + return math.huge + end + return 10 * math.log10(sig / err) +end + +-- packets(t, dmx, c, opts): every packet (file order) against ffprobe's: track, time, size, keyframe, CRC +function C.packets(t: any, dmx: any, c: any, label: string, opts: any?) + local o = opts or {} + local trackOf = {} -- ffprobe stream index -> our track + for i, s in c.streams do + trackOf[s.index] = o.trackFor and o.trackFor(dmx, s) or dmx.tracks[i] + end + dmx:rewind() + local k, bad = 0, 0 + local first = nil + for _, want in c.packets do + local tr = trackOf[want.stream] + if not (o.skipStream and o.skipStream(want, tr)) then + local p = dmx:read() + k += 1 + if not p then + t:check(false, label .. ": packet " .. k .. " missing") + return + end + local ok = tr ~= nil and p.track == tr.id and buffer.len(p.data) == want.size and Crc32.of(p.data) == want.crc + local s = c.streams[want.stream + 1] + if ok and want.pts and s and not o.noPts then + local ours = p.pts / tr.timescale - (tr.codecDelay or 0) -- ffmpeg shifts by Matroska's CodecDelay + local theirs = want.pts * s.tbn / s.tbd + ok = math.abs(ours - theirs) < 0.0015 + end + if ok and not o.noKey and tr and tr.kind == "video" then + ok = p.keyframe == want.key + end + if not ok then + bad += 1 + if not first then + first = string.format("packet %d: track %s/%s size %d/%d pts %s/%s key %s/%s crc %s", k, tostring(p.track), tostring(tr and tr.id), buffer.len(p.data), want.size, tostring(p.pts), tostring(want.pts), tostring(p.keyframe), tostring(want.key), tostring(Crc32.of(p.data) == want.crc)) + end + end + end + end + t:check(bad == 0, label .. ": " .. k .. " packets equal ffprobe's (" .. bad .. " differ" .. (if first then "; first: " .. first else "") .. ")") + t:check(dmx:read() == nil, label .. ": no extra packets") +end + +-- frames(t, v, c, label): every decoded frame against ffmpeg's (CRC for EXACT codecs, else PSNR of the raw ones) +function C.frames(t: any, v: any, c: any, label: string, minPsnr: number?) + if not c.frames then + return + end + if not Video.canDecode(v.codec) then + t:note("%s: no %s decoder, frames not checked", label, v.codec) + return + end + v:reset() + local n, bad, worst = 0, 0, math.huge + local firstBad = nil + while true do + local f, err = v:nextFrame() + if not f then + if err and err.code == F.Err.UNSUPPORTED and string.find(err.message, "inter frames", 1, true) then + t:note("%s: TODO inter frames not decodable yet", label) -- TEMP until ws/video-vp8 merges + return + end + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + local img = f.image + if img.format ~= "yuv420p" then + t:check(false, label .. ": frame " .. n .. " is " .. img.format) + break + end + if C.EXACT[v.codec] then + if Crc32.of(img.pixels) ~= c.frames[n] then + bad += 1 + firstBad = firstBad or n + end + elseif c.yuv and c.yuv[n] then + local p = C.psnr(img.pixels, buffer.fromstring(c.yuv[n])) + worst = math.min(worst, p) + end + end + t:eq(n, #c.frames, label .. ": frame count") + if C.EXACT[v.codec] then + t:check(bad == 0, label .. ": every frame bit-exact with ffmpeg (" .. bad .. " differ, first " .. tostring(firstBad) .. ")") + elseif c.yuv then + t:check(worst >= (minPsnr or 38), string.format("%s: PSNR vs ffmpeg %.1f dB", label, worst)) + end +end + +-- audio(t, v, c, label, exact?): the audio decoder (through the api hook) against ffmpeg's f32 +function C.audio(t: any, v: any, c: any, label: string, exact: boolean?, minSnr: number?) + if not c.pcm then + return + end + if not v.audio then + local code = v.audioError and v.audioError.code + t:check(code == F.Err.UNKNOWN_FORMAT or code == F.Err.UNSUPPORTED, label .. ": audio missing only for a missing audio format (" .. tostring(v.audioError) .. ")") + return + end + local a = v.audio + a:seek(0) + local want = #c.pcm // 4 + local out, got = a:read(want // a.channels) + local n = got * a.channels + t:check(n == want or n * 4 == c.pcmBytes, label .. ": " .. n .. " samples read of " .. want) + n = math.min(n, want) + if exact then + local same = true + local rb = buffer.fromstring(c.pcm) + for i = 0, n - 1 do + if math.abs(buffer.readf32(out, i * 4) - buffer.readf32(rb, i * 4)) > 1e-6 then + same = false + break + end + end + t:check(same, label .. ": PCM equal to ffmpeg's") + else + local s = C.snr(out, c.pcm, n) + t:check(s >= (minSnr or 30), string.format("%s: audio SNR vs ffmpeg %.1f dB", label, s)) + end +end + +-- seek(t, v, c, label, at): after seek(at) the next frame is the first at or after `at` +function C.seek(t: any, v: any, c: any, label: string, at: number) + if not c.frames or not Video.canDecode(v.codec) then + return + end + v:seek(at) + local f, ferr = v:nextFrame() + if not f and ferr and string.find(ferr.message, "inter frames", 1, true) then + v:reset() + return -- TEMP until ws/video-vp8 merges + end + t:check(f ~= nil and f.pts >= at - 1e-6 and f.pts < at + 0.2, label .. ": seek to " .. at .. " lands at " .. tostring(f and f.pts)) + if f and C.EXACT[v.codec] then + local idx = math.floor(f.pts * v.frameRate + 0.5) + 1 + t:eq(Crc32.of(f.image.pixels), c.frames[idx], label .. ": the frame after seeking equals ffmpeg's frame " .. idx) + end + v:reset() +end + +-- fuzzOpen(Fmt) -> a fuzz function: open, read every packet, decode up to 8 frames, read some audio +function C.fuzzOpen(Fmt: any): (buffer) -> any + return function(b: buffer): any + local v = Fmt.open(Bytes.reader(b), { openAudio = function(d: any, tr: any): any + local AudioWrap = require("@formats/containers/AudioWrap") + AudioWrap.wrap(d, tr) + return nil + end }) + if not v then + return nil + end + for _ = 1, 8 do + local f = v:nextFrame() + if not f then + break + end + end + if v.demuxer then + v.demuxer:rewind() + while v.demuxer:read() do + end + end + return v + end +end + +-- open(data, opts?) -> VideoDecoder through the api (category video) +function C.open(data: string, opts: any?): (any, any) + return F.video.open(buffer.fromstring(data), opts) +end + +return C diff --git a/tests/video/mkv.luau b/tests/video/mkv.luau new file mode 100644 index 0000000..560eb66 --- /dev/null +++ b/tests/video/mkv.luau @@ -0,0 +1,128 @@ +-- video/mkv tests: Matroska / WebM files from ffmpeg and mkvmerge (VP8 + Opus / Vorbis, MJPEG + PCM, MPEG-1 + MP2, +-- VP8 + FLAC, srt subtitles, Xiph / EBML / fixed lacing, zlib compression, unknown-size clusters, a truncated file): +-- tracks and every packet against ffprobe, frames against ffmpeg (bit-exact VP8, PSNR for MJPEG / MPEG-1), audio +-- through the api hook against ffmpeg, seeking, subtitles; our muxer's output (remux and MJPEG) read back. Fixtures: +-- tools/fixtures/mkv.py. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Mkv = require("@formats/video/mkv") +local Bytes = require("@formats/core/Bytes") +local Err = require("@formats/core/Err") +local Fx = require("@tests/gen/mkv_cases") + +local t = T.suite("mkv") + +-- 1. contract +t:eq(Mkv.name, "mkv", "name") +t:eq(Mkv.category, "video", "category") +t:check(table.find(Mkv.extensions, "webm") ~= nil, "webm extension") + +local EXACT_AUDIO = { pcm_s16le = true, flac = true } +local byName = {} +for _, c in Fx do + byName[c.name] = c +end + +-- 2. every fixture +for _, c in Fx do + local label = c.name + t:check(Mkv.sniff(Bytes.reader(buffer.fromstring(c.data))) > 0, label .. ": sniff") + if c.truncated then + local v, err = C.open(c.data) + t:check(v ~= nil or err ~= nil, label .. ": opens or fails cleanly") + if v then + local n = 0 + while v:nextFrame() do + n += 1 + end + t:note("%s: %d frames before the cut", label, n) + end + else + 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") + for i, s in c.streams do + local tr = dmx.tracks[i] + if tr then + t:eq(tr.kind, s.kind, label .. ": track " .. i .. " kind") + if s.width then + t:check(tr.width == s.width and tr.height == s.height, label .. ": track " .. i .. " size") + end + if s.rate then + t:check(tr.sampleRate == s.rate and tr.channels == s.channels, label .. ": track " .. i .. " rate / channels") + end + end + end + -- Vorbis frames inside a lace carry no time of their own (ffmpeg derives them from the Vorbis block sizes) + C.packets(t, dmx, c, label, { noPts = c.name == "laced_vorbis.mkv" or c.name == "zlib_vorbis.mka" }) + C.frames(t, v, c, label) + local at = dmx:track("audio") + if at then + C.audio(t, v, c, label, EXACT_AUDIO[at.codec], if at.codec == "vorbis" then 20 else 30) + end + C.seek(t, v, c, label, 0.6) + end + end +end + +-- 3. specific files +do + local v = C.open(byName["vp8_opus.webm"].data) + t:eq(v.format, "webm", "webm: format") + t:eq(v.codec, "vp8", "webm: codec") + t:eq(v.width, 160, "webm: width") + t:check(math.abs(v.duration - 1) < 0.1, "webm: duration " .. v.duration) + t:check(#v.demuxer.meta.cues > 0, "webm: cues read") + local subs = Mkv.subtitles(C.open(byName["subs.mkv"].data).demuxer) + t:check(subs ~= nil and #subs.cues == 2, "subtitles: two cues") + if subs then + t:eq(subs.cues[1].text, "Hello", "subtitles: text") + t:check(math.abs(subs.cues[1].start - 0.1) < 0.002 and math.abs(subs.cues[1].stop - 0.5) < 0.002, "subtitles: times") + end + local lv = C.open(byName["lacing.mka"].data) + t:eq(lv.demuxer:count(1), 10, "lacing: 10 frames from three laced blocks") + local _, _, _, _, len = lv.demuxer:info(1, 4) + t:eq(len, 160, "lacing: EBML-laced frame size") +end + +-- 4. our muxer: remux WebM (VP8 + Opus copied) and read it back packet for packet +do + local src = byName["vp8_opus.webm"] + local v = C.open(src.data) + local out, err = F.save(v, nil, { format = "webm" }) + t:check(out ~= nil, "remux webm: " .. tostring(err)) + if out then + local v2 = F.video.open(out) + t:check(v2 ~= nil and v2.format == "webm", "remux webm: reads back as webm") + if v2 then + local a, b = v.demuxer, v2.demuxer + t:eq(#b.tracks, 2, "remux webm: two tracks") + local same = a:count(1) == b:count(1) and a:count(2) == b:count(2) + for k = 1, a:count(1) do + local p, q = a:get(1, k), b:get(1, k) + if not q or p.pts ~= q.pts or buffer.tostring(p.data) ~= buffer.tostring(q.data) or p.keyframe ~= q.keyframe then + same = false + end + end + t:check(same, "remux webm: identical video packets") + C.frames(t, v2, src, "remux webm") + C.audio(t, v2, src, "remux webm", false, 30) + end + end + local bad, berr = F.save(C.open(byName["mjpeg_pcm.mkv"].data), nil, { format = "webm" }) + t:check(bad == nil and berr ~= nil and berr.code == Err.UNSUPPORTED, "webm refuses MJPEG: " .. tostring(berr)) +end + +-- 5. errors and the fuzz pass +local e1 = select(2, Mkv.open(Bytes.reader(buffer.fromstring("\26\69\223\163\128")))) +t:check(e1 ~= nil, "empty EBML header fails") +local samples = {} +for _, n in { "vp8_opus.webm", "mjpeg_pcm.mkv", "lacing.mka", "zlib_vorbis.mka", "subs.mkv" } do + local d = byName[n].data + table.insert(samples, string.sub(d, 1, math.min(#d, 60000))) +end +t:fuzz("open", C.fuzzOpen(Mkv), samples, { mutations = 6, garbage = 100 }) +t:done() diff --git a/tools/fixtures/_video.py b/tools/fixtures/_video.py new file mode 100644 index 0000000..7b0be75 --- /dev/null +++ b/tools/fixtures/_video.py @@ -0,0 +1,120 @@ +# Shared helpers for the video fixture generators (mkv.py, avi.py, y4m.py, mpegts.py, videoapi.py), loaded by path. +# ffmpeg / ffprobe come from PATH when present (a build with libvpx / libopus / libvorbis), else nix (ffmpeg-full). +import json, os, shutil, subprocess, zlib + +_FF = None + + +def ff_prefix(): + global _FF + if _FF is None: + if shutil.which("ffmpeg") and shutil.which("ffprobe"): + _FF = [] + else: + _FF = ["nix", "shell", "nixpkgs#ffmpeg-full", "-c"] + return _FF + + +def ffmpeg(args, cwd=None, input=None): + return subprocess.run(ff_prefix() + ["ffmpeg", "-v", "error", "-y"] + args, cwd=cwd, input=input, + capture_output=True, check=True).stdout + + +def ffprobe_json(path, extra): + out = subprocess.run(ff_prefix() + ["ffprobe", "-v", "error", "-of", "json"] + extra + [path], + capture_output=True, check=True).stdout + return json.loads(out) + + +def streams(path): + """ffprobe streams: [{index, kind, codec, width, height, rate, channels, time_base}]""" + d = ffprobe_json(path, ["-show_streams"]) + out = [] + for s in d.get("streams", []): + e = {"index": s["index"], "kind": s.get("codec_type", ""), "codec": s.get("codec_name", "")} + if "width" in s: + e["width"], e["height"] = s["width"], s["height"] + if "sample_rate" in s: + e["rate"] = int(s["sample_rate"]) + e["channels"] = s.get("channels", 0) + tb = s.get("time_base", "1/1").split("/") + e["tbn"], e["tbd"] = int(tb[0]), int(tb[1]) + out.append(e) + return out + + +def packets(path): + """ffprobe packets in file order: [{stream, pts, dur, key, size, crc}] (pts / dur in the stream time base)""" + d = ffprobe_json(path, ["-show_packets", "-show_data_hash", "crc32"]) + out = [] + for p in d.get("packets", []): + e = {"stream": p["stream_index"], "key": "K" in p.get("flags", ""), "size": int(p["size"]), + "crc": int(p["data_hash"].split(":")[1], 16)} + if p.get("pts") not in (None, "N/A"): + e["pts"] = int(p["pts"]) + if p.get("duration") not in (None, "N/A"): + e["dur"] = int(p["duration"]) + out.append(e) + return out + + +def yuv_frames(path, w, h, extra=None): + """the first video stream decoded by ffmpeg to yuv420p: a list of frame bytes""" + raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "yuv420p", "-"]) + n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2) + return [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)] + + +def pcm_f32(path, extra=None): + """the first audio stream decoded by ffmpeg to interleaved f32le""" + return ffmpeg(["-i", path] + (extra or []) + ["-map", "0:a:0", "-f", "f32le", "-"]) + + +def crc(b): + return zlib.crc32(b) & 0xffffffff + + +def ebml_vint(b, p): + """(value, length) of an EBML vint (marker removed; all ones -> -1)""" + first = b[p] + n = 1 + mask = 0x80 + while n <= 8 and not first & mask: + n += 1 + mask >>= 1 + v = first & (mask - 1) + ones = v == mask - 1 + for i in range(1, n): + v = (v << 8) | b[p + i] + ones = ones and b[p + i] == 255 + return (-1 if ones else v), n + + +def ebml_id(b, p): + first = b[p] + n = 1 if first >= 0x80 else 2 if first >= 0x40 else 3 if first >= 0x20 else 4 + return int.from_bytes(b[p:p + n], "big"), n + + +def mkv_unknown_clusters(data): + """the same Matroska file with every Cluster's size field rewritten to 'unknown' (same length)""" + b = bytearray(data) + p = 0 + # EBML header + i, n = ebml_id(b, p) + s, m = ebml_vint(b, p + n) + p += n + m + s + i, n = ebml_id(b, p) # Segment + s, m = ebml_vint(b, p + n) + p += n + m + while p < len(b): + i, n = ebml_id(b, p) + s, m = ebml_vint(b, p + n) + if i == 0x1F43B675: + b[p + n] = (0xFF >> (m - 1)) if m < 8 else 0x01 + for k in range(1, m): + b[p + n + k] = 0xFF + if m == 1: + b[p + n] = 0xFF + p += n + m + s + return bytes(b) diff --git a/tools/fixtures/mkv.py b/tools/fixtures/mkv.py new file mode 100644 index 0000000..7719663 --- /dev/null +++ b/tools/fixtures/mkv.py @@ -0,0 +1,131 @@ +# Matroska / WebM fixtures (tools/fixtures.py): files made by ffmpeg (libvpx VP8 + Opus / Vorbis WebM, MJPEG + PCM, +# MPEG-1 + MP3, srt subtitles) and mkvmerge (Xiph / EBML / fixed lacing, header-removal compression), plus edits made +# here (every cluster rewritten to an unknown size, a truncated file). For each file: ffprobe's streams and packets +# (pts, duration, keyframe flag, size, CRC-32 of the data), ffmpeg's yuv420p frames (CRC-32 each; the first frames +# raw for PSNR checks) and ffmpeg's decoded audio (f32). +# tests/gen/mkv_cases.luau { { name, data, streams, packets, frames = { crc }, yuv = { raw frame }, pcm, ... } } +import importlib.util, os, 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"] + +W, H = 160, 120 +SRC = ["-f", "lavfi", "-i", "testsrc2=size=%dx%d:rate=15" % (W, H)] +MOVE = ["-f", "lavfi", "-i", "mandelbrot=size=%dx%d:rate=15" % (W, H)] + + +def sine(rate, ch=1): + if ch == 1: + return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate] + return ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=%d" % rate, "-ac", str(ch)] + + +def case(ctx, tmp, name, raw_frames=2, audio=True, video=True, pcm_frames=8192): + path = os.path.join(tmp, name) + data = open(path, "rb").read() + c = {"name": name, "data": data, "streams": V.streams(path), "packets": V.packets(path)} + vs = [s for s in c["streams"] if s["kind"] == "video"] + if video and vs: + frames = V.yuv_frames(path, vs[0]["width"], vs[0]["height"]) + c["frames"] = [V.crc(f) for f in frames] + c["yuv"] = frames[:raw_frames] + if audio and any(s["kind"] == "audio" for s in c["streams"]): + pcm = V.pcm_f32(path) + c["pcm"] = pcm if pcm_frames is None else pcm[:pcm_frames * 4] + c["pcmBytes"] = len(pcm) + return c + + +def el(i, payload): + """an EBML element: id (int), payload bytes""" + n = len(payload) + size = bytes([0x01]) + n.to_bytes(7, "big") + return i.to_bytes((i.bit_length() + 7) // 8, "big") + size + payload + + +def uint(v): + return v.to_bytes(max(1, (v.bit_length() + 7) // 8), "big") + + +def lacing_file(ctx): + """A_PCM/INT/LIT mono 8 kHz s16 in three SimpleBlocks, Xiph-, EBML- and fixed-laced (DefaultDuration 10 ms)""" + rng = ctx.rng(7) + frames = [bytes(rng.randrange(256) for _ in range(2 * n)) for n in (80, 40, 120, 80, 80, 80, 80, 80, 80, 80)] + head = el(0x1A45DFA3, el(0x4282, b"matroska") + el(0x4287, uint(4)) + el(0x4285, uint(2))) + info = el(0x1549A966, el(0x2AD7B1, uint(1000000)) + el(0x4D80, b"fixture") + el(0x5741, b"fixture")) + track = el(0xAE, el(0xD7, uint(1)) + el(0x73C5, uint(1)) + el(0x83, uint(2)) + el(0x86, b"A_PCM/INT/LIT") + + el(0x23E383, uint(10000000)) + el(0xE1, el(0xB5, __import__("struct").pack(">d", 8000.0)) + + el(0x9F, uint(1)) + el(0x6264, uint(16)))) + tracks = el(0x1654AE6B, track) + + def xiph(sizes): + out = b"" + for s in sizes: + out += b"\xff" * (s // 255) + bytes([s % 255]) + return out + + def ebmlnum(v): + n = 1 + while v >= (1 << (7 * n)) - 1: + n += 1 + return ((1 << (7 * n)) | v).to_bytes(n, "big") + + def sebml(v, n=2): + return ((1 << (7 * n)) | (v + (1 << (7 * n - 1)) - 1)).to_bytes(n, "big") + + def block(rel, flags, body): + return el(0xA3, b"\x81" + rel.to_bytes(2, "big") + bytes([flags]) + body) + + f = frames + b1 = block(0, 0x80 | 0x02, bytes([2]) + xiph([len(f[0]), len(f[1])]) + f[0] + f[1] + f[2]) + sizes = [len(f[3]), len(f[4]), len(f[5])] + b2 = block(40, 0x80 | 0x06, bytes([2]) + ebmlnum(sizes[0]) + sebml(sizes[1] - sizes[0]) + f[3] + f[4] + f[5]) + b3 = block(70, 0x80 | 0x04, bytes([3]) + f[6] + f[7] + f[8] + f[9]) + cluster = el(0x1F43B675, el(0xE7, uint(0)) + b1 + b2 + b3) + return head + el(0x18538067, info + tracks + cluster) + + +def generate(ctx): + tmp = tempfile.mkdtemp(prefix="mkvfx_") + ff = lambda *a: V.ffmpeg(list(a), cwd=tmp) + ff(*SRC, *sine(48000), "-t", "1", "-c:v", "libvpx", "-g", "8", "-auto-alt-ref", "1", "-lag-in-frames", "8", + "-b:v", "300k", "-c:a", "libopus", "-b:a", "48k", "vp8_opus.webm") + ff(*MOVE, *sine(44100, 2), "-t", "1", "-c:v", "libvpx", "-g", "30", "-b:v", "200k", "-c:a", "libvorbis", + "vp8_vorbis.webm") + ff(*SRC, *sine(44100, 2), "-t", "1", "-c:v", "mjpeg", "-q:v", "3", "-c:a", "pcm_s16le", "mjpeg_pcm.mkv") + ff(*MOVE, *sine(44100), "-t", "1", "-r", "25", "-c:v", "mpeg1video", "-b:v", "400k", "-c:a", "mp2", "-b:a", "64k", + "mpeg1_mp2.mkv") + ff(*SRC, *sine(48000, 2), "-t", "1", "-c:v", "libvpx", "-g", "15", "-c:a", "flac", "vp8_flac.mkv") + open(os.path.join(tmp, "subs.srt"), "w").write( + "1\n00:00:00,100 --> 00:00:00,500\nHello\n\n2\n00:00:00,600 --> 00:00:00,900\nWorld bold\n\n") + ff(*SRC, "-i", "subs.srt", "-t", "1", "-c:v", "mjpeg", "-c:s", "srt", "subs.mkv") + # mkvmerge: Xiph lacing (Vorbis) and zlib content compression; a file crafted here with all three lacings + mk = lambda *a: subprocess.run(["nix", "shell", "nixpkgs#mkvtoolnix-cli", "-c", "mkvmerge", "-q"] + list(a), + cwd=tmp, check=False, capture_output=True) + mk("-o", "laced_vorbis.mkv", "vp8_vorbis.webm") + ff(*sine(44100), "-t", "1", "-c:a", "libvorbis", "v.ogg") + mk("-o", "zlib_vorbis.mka", "--compression", "0:zlib", "v.ogg") + open(os.path.join(tmp, "lacing.mka"), "wb").write(lacing_file(ctx)) + # unknown-size clusters, a truncated file + open(os.path.join(tmp, "unknown_clusters.webm"), "wb").write( + V.mkv_unknown_clusters(open(os.path.join(tmp, "vp8_opus.webm"), "rb").read())) + full = open(os.path.join(tmp, "mjpeg_pcm.mkv"), "rb").read() + + cases = [ + case(ctx, tmp, "vp8_opus.webm"), + case(ctx, tmp, "vp8_vorbis.webm"), + case(ctx, tmp, "mjpeg_pcm.mkv"), + case(ctx, tmp, "mpeg1_mp2.mkv"), + case(ctx, tmp, "vp8_flac.mkv"), + case(ctx, tmp, "subs.mkv", audio=False), + case(ctx, tmp, "unknown_clusters.webm"), + ] + for name in ("laced_vorbis.mkv", "zlib_vorbis.mka", "lacing.mka"): + if os.path.exists(os.path.join(tmp, name)): + cases.append(case(ctx, tmp, name)) + cut = full[: len(full) * 7 // 10] + cases.append({"name": "truncated.mkv", "data": cut, "truncated": True}) + ctx.emit("mkv_cases", cases)