From 7dd4d54546967a4c1628c1e85bb37dae9b1fb2d4 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 14:22:39 -0500 Subject: [PATCH] ws-video2-theora: video/ogv, Ogg video (Theora + Vorbis / Opus / FLAC) Demuxes every logical stream of the first Ogg group into containers/Demux: Theora (frame times from granules, Xiph-laced headers as track.config, comment tags in meta.tags), Vorbis / Opus / FLAC audio (headers in track.config) for the api's openAudio hook; open = Video.open. Sniff claims only Ogg files with a Theora BOS page. encode remuxes Theora (+ Vorbis / Opus pages from AudioWrap, interleaved by time). codecs/video/Theora gains info / comment helpers. Co-Authored-By: Claude Opus 5.5 --- docs/FORMATS.md | 1 + src/Formats/Registry.luau | 12 + src/Formats/codecs/video/Theora/init.luau | 33 +- src/Formats/video/ogv/init.luau | 407 ++++++++++++++++++++++ tests/video/ogv.luau | 211 +++++++++++ tools/fixtures/theora.py | 10 + 6 files changed, 667 insertions(+), 7 deletions(-) create mode 100644 src/Formats/video/ogv/init.luau create mode 100644 tests/video/ogv.luau diff --git a/docs/FORMATS.md b/docs/FORMATS.md index 5f34e95..d1c5a0e 100644 --- a/docs/FORMATS.md +++ b/docs/FORMATS.md @@ -33,6 +33,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build | video | mp4 | .mp4 .m4v .mov .qt .3gp .3g2 .mj2 | yes | yes | streaming: true, remux: true, video: "mjpeg", "mpeg1", "h264", audio: true, fragments: true | `tests/video/mp4.luau` | | video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", audio: true | `tests/video/mpegps.luau` | | video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "h264", audio: true | `tests/video/mpegts.luau` | +| video | ogv | .ogv .ogg | yes | yes | streaming: true, remux: true, video: "theora", audio: true | `tests/video/ogv.luau` | | video | y4m | .y4m | yes | yes | streaming: true, video: "rawvideo", depths: 8, 10, 12, 16 | `tests/video/y4m.luau` | | model | 3mf | .3mf | yes | yes | materials: true, vertexColors: true, textures: true, units: true | `tests/model/3mf.luau` | | model | dae | .dae .zae | yes | yes | materials: true, polygons: true, skins: true, morphTargets: true, animation: true, cameras: true, lights: true, zae: true | `tests/model/dae.luau` | diff --git a/src/Formats/Registry.luau b/src/Formats/Registry.luau index 6c0344c..206913c 100644 --- a/src/Formats/Registry.luau +++ b/src/Formats/Registry.luau @@ -350,6 +350,18 @@ local list: { Entry } = { return require("@formats/video/mpegts") end, }, + { + name = "ogv", + category = "video", + path = "video/ogv", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, + load = function() + return require("@formats/video/ogv") + end, + }, { name = "y4m", category = "video", diff --git a/src/Formats/codecs/video/Theora/init.luau b/src/Formats/codecs/video/Theora/init.luau index dd99346..c607c0e 100644 --- a/src/Formats/codecs/video/Theora/init.luau +++ b/src/Formats/codecs/video/Theora/init.luau @@ -23,6 +23,8 @@ local Decoder = require("@formats/codecs/video/Theora/Decoder") local Theora = {} +export type Info = Header.Info + export type Options = { maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) } @@ -75,6 +77,24 @@ function Theora.splitConfig(c: buffer): { buffer }? return out end +-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err +function Theora.info(h: buffer): (Header.Info?, Err.Err?) + local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) + if not ok or not info then + return nil, Err.from(if ok then err else tostring(info)) + end + return info, nil +end + +-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err +function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) + local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) + if not ok or not vendor or not list then + return nil, nil, nil, Err.from(if ok then err else tostring(vendor)) + end + return vendor, list, (VorbisComment.tags(list)), nil +end + -- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none) function Theora.granuleFrame(info: Header.Info, g: number): number if g < 0 then @@ -124,24 +144,23 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode if not list or #list < 3 or type(list[1]) ~= "buffer" or type(list[2]) ~= "buffer" or type(list[3]) ~= "buffer" then return nil, Err.new(Err.CORRUPT, "missing Theora headers") end - local ok, info, ierr = pcall(Header.info, list[1], 0, buffer.len(list[1])) - if not ok or not info then - return nil, Err.from(if ok then ierr else tostring(info)) + local info, ierr = Theora.info(list[1]) + if not info then + return nil, ierr end local maxPixels = opts and opts.maxPixels or 4096 * 2304 if info.frameWidth * info.frameHeight > maxPixels then return nil, Err.new(Err.LIMIT, "frame of " .. info.frameWidth .. "x" .. info.frameHeight .. " is over maxPixels") end - local ok2, vendor, comments, cerr = pcall(Header.comment, list[2], 0, buffer.len(list[2])) - if not ok2 or not vendor or not comments then - return nil, Err.from(if ok2 then cerr else tostring(vendor)) + local vendor, comments, tags, cerr = Theora.comment(list[2]) + if not vendor or not comments or not tags then + return nil, cerr end local ok3, setup, serr = pcall(Header.setup, list[3], 0, buffer.len(list[3])) if not ok3 or not setup then return nil, Err.from(if ok3 then serr else tostring(setup)) end local st = Decoder.new(info, setup) - local tags = VorbisComment.tags(comments) return setmetatable({ info = info, vendor = vendor, diff --git a/src/Formats/video/ogv/init.luau b/src/Formats/video/ogv/init.luau new file mode 100644 index 0000000..0750440 --- /dev/null +++ b/src/Formats/video/ogv/init.luau @@ -0,0 +1,407 @@ +--!strict +-- video/ogv: Ogg video (.ogv, or .ogg with a Theora stream: the Ogg Theora mapping of the Theora I specification, +-- RFC 3533 / 5334). New in formats-luau, on containers/Ogg and containers/Demux. +-- Read: open() demuxes every logical stream of the first Ogg group into a packet index: Theora video (frame times from +-- the granule positions: keyframe number << shift | frames since it; the three headers become track.config, +-- Xiph-laced as in Matroska, so codecs/video/Theora decodes it through the codecs/video/Video registry), Vorbis / +-- Opus / FLAC audio (headers in track.config, times from the granules) reaching the audio formats through the api's +-- opts.openAudio hook; the Theora comment header's tags go to meta.tags. Ogv.demux(r) gives the Demuxer alone. +-- Write: remux (encode): a Theora video track copied from the source (ogv / mkv), plus its Vorbis / Opus audio copied +-- (the audio pages come from containers/AudioWrap and are interleaved by time). +-- Not supported: chained Ogg files (only the first group of streams), Skeleton / Kate / Speex streams (skipped), +-- encoding Theora (there is no encoder: other sources cannot be written). + +-- ------------------------------------------------------------------------------------------------ requires +local Err = require("@formats/core/Err") +local Bytes = require("@formats/core/Bytes") +local Types = require("@formats/Types") +local Ogg = require("@formats/containers/Ogg") +local Demux = require("@formats/containers/Demux") +local AudioWrap = require("@formats/containers/AudioWrap") +local Theora = require("@formats/codecs/video/Theora") +local Video = require("@formats/codecs/video/Video") +local Source = require("@formats/codecs/video/Video/Source") + +-- ------------------------------------------------------------------------------------------------ contract +local Ogv = { + name = "ogv", + category = "video", + extensions = { "ogv", "ogg" }, + mime = { "video/ogg" }, + deps = { "core/Err", "core/Bytes", "Types", "containers/Ogg", "containers/Demux", "containers/AudioWrap", "codecs/video/Theora", "codecs/video/Video", "codecs/video/Video/Source" }, + caps = { decode = true, encode = true, streaming = true, remux = true, video = { "theora" }, audio = true }, +} + +-- ------------------------------------------------------------------------------------------------ types +export type OpenOptions = { + rgba: boolean?, -- nextFrame returns rgba8 images (default false: yuv420p from the codec) + track: number?, -- the video track id to decode (default: the first video track) + audio: boolean?, -- false: do not open the audio track + maxPixels: number?, + verify: boolean?, -- false: skip the page CRC checks (default true) + openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder +} +export type EncodeOptions = { + audio: boolean?, -- false: no audio; true: fail when the audio cannot be copied (default: dropped) +} + +-- ------------------------------------------------------------------------------------------------ constants +local AUDIO = { vorbis = true, opus = true, flac = true } + +-- ------------------------------------------------------------------------------------------------ sniff +-- 1 when one of the beginning-of-stream pages at the start of an Ogg file is a Theora identification header (plain +-- Ogg Vorbis / Opus / FLAC files are left to the audio formats) +function Ogv.sniff(r: Bytes.Reader): number + if r:peek(4) ~= "OggS" then + return 0 + end + local b, p, lim = r.buf, r.pos, r.limit + for _ = 1, 8 do + if p + 27 > lim or buffer.readstring(b, p, 4) ~= "OggS" or buffer.readu8(b, p + 5) % 4 < 2 then + return 0 + end + local nseg = buffer.readu8(b, p + 26) + local d = p + 27 + nseg + if d + 7 <= lim and buffer.readu8(b, d) == 0x80 and buffer.readstring(b, d + 1, 6) == "theora" then + return 1 + end + if d > lim then + return 0 + end + local size = 0 + for i = 0, nseg - 1 do + size += buffer.readu8(b, p + 27 + i) + end + p = d + size + end + return 0 +end + +-- ------------------------------------------------------------------------------------------------ encode +-- the pages of an Ogg buffer: { offset, size, serial, granule, bos } +local function pages(b: buffer): { { number } } + local out = {} + local pos = 0 + while true do + local p = Ogg.Page.find(b, pos, nil, false) + if not p then + break + end + table.insert(out, { p.offset, p.size, p.granule, if p.bos then 1 else 0, if p.continued then 1 else 0 }) + pos = p.offset + p.size + end + return out +end + +-- encode(video, opts?) -> an Ogg file | nil, Err: a VideoDecoder or Demuxer whose video track is Theora (ogv, mkv) +function Ogv.encode(value: any, opts: EncodeOptions?): (buffer?, Err.Err?) + local o: any = opts or {} + local streams, err = Source.streams(value, o, { video = { copy = { theora = true } }, audio = { copy = { vorbis = true, opus = true } } }) + if not streams then + return nil, err + end + local vs: Source.Stream? = nil + local as: Source.Stream? = nil + for _, s in streams do + if s.kind == "video" and s.codec == "theora" and not vs then + vs = s + elseif s.kind == "audio" and s.copied and not as then + as = s + end + end + if not vs or not vs.config then + return nil, Err.new(Err.UNSUPPORTED, "only Theora video can be written (no Theora encoder)") + end + local v = vs :: Source.Stream + local headers = Theora.splitConfig(v.config :: buffer) + local info = headers and Theora.info(headers[1]) + if not headers or not info then + return nil, Err.new(Err.CORRUPT, "Theora track without its three headers") + end + local fps = info.fpsNum / info.fpsDen + local scale = 2 ^ info.granuleShift + local bias = if info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub >= 0x030201 then 1 else 0 + -- video pages (serial 0x7468656F), granules from the frame numbers + local mux = Ogg.muxer({ pageSize = 4096 }) + local s = mux:stream(0x7468656F) + s:packet(headers[1], 0, { flush = true }) + s:packet(headers[2], 0) + s:packet(headers[3], 0, { flush = true }) + local key = 0 + local start = if #v.packets > 0 then v.packets[1].pts else 0 + for i, p in v.packets do + local frame = math.floor((p.pts - start) * fps + 0.5) + if buffer.len(p.data) > 0 and buffer.readu8(p.data, 0) // 64 == 0 then + key = frame + bias + end + s:packet(p.data, key * scale + (frame + bias - key), { eos = i == #v.packets }) + end + local video = mux:finish() + -- audio pages: the audio track as its own Ogg stream (containers/AudioWrap), interleaved by time + local audio: buffer? = nil + local arate, askip = 1, 0 + if as and o.audio ~= false then + local a = as :: Source.Stream + local track: any = { id = 1, kind = "audio", codec = a.codec, timescale = 1, config = a.config, sampleRate = a.sampleRate, channels = a.channels } + local shim = { + count = function(_: any, _t: number): number + return #a.packets + end, + get = function(_: any, _t: number, k: number): any + local p = a.packets[k] + return p and { track = 1, pts = p.pts, duration = p.duration, keyframe = true, data = p.data } + end, + } + local buf, _, aerr = AudioWrap.wrap(shim, track) + if not buf and o.audio == true then + return nil, aerr + end + audio = buf + if a.codec == "opus" then + arate = 48000 + local c = a.config + askip = if c and buffer.len(c) >= 12 then buffer.readu16(c, 10) else 0 + else + arate = a.sampleRate or 44100 + end + elseif o.audio == true and not as then + return nil, Err.new(Err.UNSUPPORTED, "the audio track is not Vorbis / Opus") + end + local vp = pages(video) + local ap = if audio then pages(audio) else {} + local out = Bytes.writer(buffer.len(video) + (if audio then buffer.len(audio) else 0)) + local function put(b: buffer, pg: { number }) + out:bytes(b, pg[1], pg[2]) + end + -- bos pages first (video, then audio), then the other header pages, then data by time + put(video, vp[1]) + if audio and ap[1] then + put(audio :: buffer, ap[1]) + end + local vi, ai = 2, 2 + local function headerPage(list: { { number } }, i: number): boolean + local pg = list[i] + return pg ~= nil and pg[3] == 0 + end + while headerPage(vp, vi) do + put(video, vp[vi]) + vi += 1 + end + while audio and headerPage(ap, ai) do + put(audio :: buffer, ap[ai]) + ai += 1 + end + local vt, at = 0, 0 + while vi <= #vp or ai <= #ap do + local nv, na = vp[vi], ap[ai] + if nv and nv[3] >= 0 then + vt = Theora.granuleFrame(info, nv[3]) / fps + end + if na and na[3] >= 0 then + at = (na[3] - askip) / arate + end + if nv and (not na or vt <= at) then + put(video, nv) + vi += 1 + else + put(audio :: buffer, na) + ai += 1 + end + end + return out:finish(), nil +end + +-- ------------------------------------------------------------------------------------------------ open +-- Xiph lacing of header packets (Matroska's CodecPrivate layout): count - 1, the sizes but the last, the packets +local function xiphLace(list: { buffer }): buffer + local w = Bytes.writer(64) + w:u8(#list - 1) + for i = 1, #list - 1 do + local n = buffer.len(list[i]) + while n >= 255 do + w:u8(255) + n -= 255 + end + w:u8(n) + end + for _, h in list do + w:bytes(h) + end + return w:finish() +end + +type Pending = { track: number, pts: number, key: boolean, page: number, data: buffer, off: number, len: number, own: boolean } + +-- demux(r, opts?) -> the Demuxer (containers/Demux) | nil, Err +function Ogv.demux(r: Bytes.Reader, opts: OpenOptions?): (any, Err.Err?) + local ogg, err = Ogg.open(r, { verify = not (opts and opts.verify == false) }) + if not ogg then + return nil, err + end + local src: buffer = ogg.buf + local tracks: { Types.Track } = {} + local all: { Pending } = {} + local meta: { [string]: any } = {} + local function add(track: number, pts: number, key: boolean, p: any) + table.insert(all, { + track = track, + pts = pts, + key = key, + page = p.pageOffset, + data = p.data, + off = p.offset, + len = p.size, + own = p.data ~= src, + }) + end + for _, st in ogg:streams() do + local codec = st.codec + if codec ~= "theora" and not AUDIO[codec] then + continue + end + local rd = ogg:reader(st.serial) + local headers: { buffer } = {} + local nh = if codec == "theora" or codec == "vorbis" then 3 elseif codec == "opus" then 2 else 1 + while #headers < nh do + local p = rd:nextPacket() + if not p then + break + end + table.insert(headers, Ogg.copy(p)) + if codec == "flac" and #headers == 1 and p.size >= 9 then + nh = 1 + buffer.readu16(p.data, p.offset + 7) // 256 + (buffer.readu16(p.data, p.offset + 7) % 256) * 256 + if nh > 64 then + nh = 1 + end + end + end + if #headers < nh then + continue + end + local id = #tracks + 1 + local track: any = { id = id, kind = "audio", codec = codec, codecTag = codec, timescale = 1, default = true, serial = st.serial } + if codec == "theora" then + local info = Theora.info(headers[1]) + if not info then + continue + end + track.kind = "video" + track.width, track.height = info.picWidth, info.picHeight + track.timescale = info.fpsNum + track.frameRate = info.fpsNum / info.fpsDen + track.config = xiphLace(headers) + local _, _, tags = Theora.comment(headers[2]) + meta.tags = tags + -- frame k of the stream: granule = keyframe << shift | frames since; bitstream 3.2.1 counts from 1 + local packets = {} + local base: number? = nil + while true do + local p = rd:nextPacket() + if not p then + break + end + if p.size > 0 and buffer.readu8(p.data, p.offset) >= 0x80 then + continue -- a stray header + end + table.insert(packets, p) + if base == nil and p.granule >= 0 then + base = Theora.granuleFrame(info, p.granule) - (#packets - 1) + end + end + local b0 = base or 0 + for k, p in packets do + local key = p.size > 0 and buffer.readu8(p.data, p.offset) // 64 == 0 + add(id, (b0 + k - 1) * info.fpsDen, key, p) + end + track.duration = (b0 + #packets) / track.frameRate + else + local h = headers[1] + local rate, channels, skip = 0, 0, 0 + if codec == "vorbis" and buffer.len(h) >= 16 then + channels, rate = buffer.readu8(h, 11), buffer.readu32(h, 12) + track.config = xiphLace(headers) + elseif codec == "opus" and buffer.len(h) >= 19 then + channels, rate, skip = buffer.readu8(h, 9), 48000, buffer.readu16(h, 10) + track.config = h + track.codecDelay = skip / 48000 + elseif codec == "flac" and buffer.len(h) >= 9 + 4 + 4 + 18 then + local o = 9 + 4 + 4 + 10 -- "fLaC", the block header, STREAMINFO's sample rate field + rate = buffer.readu8(h, o) * 4096 + buffer.readu8(h, o + 1) * 16 + buffer.readu8(h, o + 2) // 16 + channels = (buffer.readu8(h, o + 2) // 2) % 8 + 1 + local parts = { buffer.create(buffer.len(h) - 9) } + buffer.copy(parts[1], 0, h, 9) + for i = 2, #headers do + table.insert(parts, headers[i]) + end + local total = 0 + for _, x in parts do + total += buffer.len(x) + end + local cfg = buffer.create(total) + local o2 = 0 + for _, x in parts do + buffer.copy(cfg, o2, x) + o2 += buffer.len(x) + end + track.config = cfg + end + if rate <= 0 or channels <= 0 then + continue + end + track.sampleRate, track.channels, track.timescale = rate, channels, rate + local last = 0 + while true do + local p = rd:nextPacket() + if not p then + break + end + add(id, math.max(0, last - skip), true, p) + if p.granule >= 0 then + last = p.granule + end + end + track.duration = math.max(0, last - skip) / rate + end + table.insert(tracks, track) + end + if #tracks == 0 then + return nil, Err.new(Err.UNSUPPORTED, "no Theora / Vorbis / Opus / FLAC stream") + end + -- the index in file order (by the page each packet ends on) + local order = table.create(#all, 0) + for i = 1, #all do + order[i] = i + end + table.sort(order, function(a: number, c: number): boolean + local pa, pc = all[a].page, all[c].page + if pa ~= pc then + return pa < pc + end + return a < c + end) + local dmx = Demux.new("ogv", tracks, src, meta) + for _, i in order do + local e = all[i] + if e.own then + dmx:addData(e.track, e.pts, e.pts, nil, e.key, e.data) + else + dmx:add(e.track, e.pts, e.pts, nil, e.key, e.off, e.len) + end + end + dmx:finish() + return dmx, nil +end + +-- open(r, opts?) -> a VideoDecoder (kind "video": nextFrame / seek / audio / demuxer) | nil, Err +function Ogv.open(r: Bytes.Reader, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) + local ok, dmx, err = pcall(Ogv.demux, r, opts) + if not ok then + return nil, Err.new(Err.CORRUPT, "internal error: " .. tostring(dmx)) + end + if not dmx then + return nil, err + end + return Video.open(dmx, opts :: Video.OpenOptions?) +end + +return Ogv diff --git a/tests/video/ogv.luau b/tests/video/ogv.luau new file mode 100644 index 0000000..d1e0093 --- /dev/null +++ b/tests/video/ogv.luau @@ -0,0 +1,211 @@ +-- video/ogv tests: Ogg Theora files from ffmpeg (libtheora + libvorbis; tools/fixtures/theora.py): sniffing (Theora +-- BOS pages, plain Ogg Vorbis left to the audio formats), tracks, granule times, every frame through F.video.open +-- bit-exact with ffmpeg's (Adler-32 of yuv420p, its framecrc), an empty packet (a repeated frame), the Vorbis track +-- through the api's audio hook against ffmpeg's decode, tags, seeking, remuxing (ogv -> ogv, mkv -> ogv, ogv -> mkv) +-- read back, errors and the fuzz no-throw pass. +local T = require("@tests/T") +local C = require("@tests/video/_common") +local F = require("@formats") +local Ogv = require("@formats/video/ogv") +local Theora = require("@formats/codecs/video/Theora") +local AudioWrap = require("@formats/containers/AudioWrap") +local Bytes = require("@formats/core/Bytes") +local Base64 = require("@formats/core/Base64") +local Adler32 = require("@formats/core/Adler32") +local Err = require("@formats/core/Err") + +local t = T.suite("ogv") + +local AV = require("@tests/gen/theora_av") :: any +local Q0 = require("@tests/gen/theora_q0") :: any +local DUPE = require("@tests/gen/theora_dupe") :: any +local MKV = require("@tests/gen/theora_mkv") :: any +local OPUS = require("@tests/gen/theora_opus") :: any +local FLAC = require("@tests/gen/theora_flac") :: any + +local function file(fx: any): buffer + return Base64.decode(fx.file) :: buffer +end + +-- every frame of a VideoDecoder against ffmpeg's framecrc (yuv420p, keyed by frame number); frames ffmpeg does not +-- show (empty packets) must repeat the previous one +local function frames(v: any, fx: any, label: string, fps: number) + local want: { [number]: number } = {} + for _, f in fx.frames do + want[f[1]] = f[2] + end + local n, bad, shown, prev = 0, 0, 0, nil :: number? + while true do + local f, err = v:nextFrame() + if not f then + t:check(err == nil, label .. ": decode error " .. tostring(err)) + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + local w = want[math.floor(f.pts * fps + 0.5)] + if w then + shown += 1 + if c ~= w then + bad += 1 + end + elseif c ~= prev then + bad += 1 + end + prev = c + end + t:eq(bad, 0, label .. ": frames equal to ffmpeg's (" .. n .. " frames)") + t:eq(shown, #fx.frames, label .. ": every frame ffmpeg shows") + return n +end + +-- 1. contract and sniffing +t:eq(Ogv.name, "ogv", "name") +t:eq(Ogv.category, "video", "category") +t:check(table.find(Ogv.extensions, "ogv") ~= nil, "ogv extension") +t:eq(Ogv.sniff(Bytes.reader(file(AV))), 1, "sniff: Theora + Vorbis") +t:eq(Ogv.sniff(Bytes.reader(file(Q0))), 1, "sniff: Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("OggS\0\2" .. string.rep("\0", 40)))), 0, "sniff: an Ogg page without Theora") +t:eq(Ogv.sniff(Bytes.reader(buffer.fromstring("RIFF"))), 0, "sniff: not Ogg") + +-- 2. Theora + Vorbis through the api +local v, err = F.video.open(file(AV)) +t:check(v ~= nil, "open: " .. tostring(err)) +if v then + t:eq(v.format, "ogv", "format") + t:eq(v.codec, "theora", "codec") + t:eq(v.width * 1000 + v.height, 160120, "size") + t:eq(v.frameRate, 25, "frame rate") + local dmx = v.demuxer :: any + t:eq(#dmx.tracks, 2, "two tracks") + local vt, at = dmx:track("video"), dmx:track("audio") + t:check(vt and vt.codec == "theora" and vt.timescale == 25, "video track") + t:check(at and at.codec == "vorbis" and at.sampleRate == 44100 and at.channels == 2, "audio track") + t:check(vt and vt.config and #(Theora.splitConfig(vt.config) or {}) == 3, "video config: three Xiph-laced headers") + t:check(math.abs(v.duration - 1) < 0.05, "duration " .. v.duration) + t:check(v.meta.tags and v.meta.tags.encoder ~= nil, "tags from the comment header") + local first = dmx:get(vt.id, 1) + t:check(first and first.keyframe and first.pts == 0, "first packet: a keyframe at 0") + t:check(not dmx:get(vt.id, 2).keyframe, "second packet: an inter frame") + frames(v, AV, "av", 25) + local pcm = Base64.decode(AV.pcm) :: buffer + C.audio(t, v, { pcm = buffer.tostring(pcm) }, "av", false, 20) + -- seeking + v:seek(0.5) + local f = v:nextFrame() + t:check(f ~= nil and f.pts >= 0.5 - 1e-6 and f.pts < 0.6, "seek 0.5 -> " .. tostring(f and f.pts)) + if f then + local want = nil + for _, w in AV.frames do + if w[1] == math.floor(f.pts * 25 + 0.5) then + want = w[2] + end + end + t:eq(Adler32.of(f.image.pixels, nil, nil, 0), want, "the frame after seeking equals ffmpeg's") + end + -- remux ogv -> ogv + v:reset() + local out, rerr = F.save(v, nil, { format = "ogv" }) + t:check(out ~= nil, "remux: " .. tostring(rerr)) + if out then + t:eq(Ogv.sniff(Bytes.reader(out)), 1, "remux: sniff") + local v2 = F.video.open(out) :: any + t:check(v2 ~= nil and #v2.demuxer.tracks == 2, "remux: two tracks") + if v2 then + frames(v2, AV, "remux", 25) + C.audio(t, v2, { pcm = buffer.tostring(pcm) }, "remux", false, 20) + end + end + -- remux ogv -> mkv (V_THEORA) + v:reset() + local mk, merr = F.save(v, nil, { format = "mkv" }) + t:check(mk ~= nil, "to mkv: " .. tostring(merr)) + if mk then + local v3 = F.video.open(mk) :: any + t:check(v3 ~= nil and v3.codec == "theora", "to mkv: Theora track") + if v3 then + frames(v3, AV, "to mkv", 25) + end + end +end + +-- 3. Opus and FLAC audio tracks (FLAC: exact) +for _, c in { { OPUS, "opus", 48000 }, { FLAC, "flac", 22050 } } do + local fx, codec, rate = c[1], c[2], c[3] + local vd, e = F.video.open(file(fx)) + t:check(vd ~= nil, codec .. ": open: " .. tostring(e)) + if vd then + local at = (vd.demuxer :: any):track("audio") + t:check(at and at.codec == codec and at.sampleRate == rate and at.channels == 1, codec .. ": audio track") + frames(vd, fx, codec, 25) + C.audio(t, vd, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, codec, codec == "flac", 20) + if codec == "opus" then + vd:reset() + local out = F.save(vd, nil, { format = "ogv" }) + local v2 = out and F.video.open(out) :: any + t:check(v2 ~= nil and v2.audio ~= nil, "opus: remux keeps the audio") + if v2 then + C.audio(t, v2, { pcm = buffer.tostring(Base64.decode(fx.pcm) :: buffer) }, "opus remux", false, 20) + end + end + end +end + +-- 4. an empty packet: a repeated frame with its own time +do + local vd = Ogv.open(Bytes.reader(file(DUPE))) :: any + local n = 0 + local prev, dupAt = nil, nil + while true do + local f = vd:nextFrame() + if not f then + break + end + n += 1 + local c = Adler32.of(f.image.pixels, nil, nil, 0) + if n == 6 then + dupAt = f.pts + t:eq(c, prev, "dupe: frame 6 repeats frame 5") + end + prev = c + end + t:eq(n, #DUPE.frames + 1, "dupe: one frame per packet") + t:check(dupAt ~= nil and math.abs((dupAt :: number) - 0.2) < 1e-6, "dupe: its time slot (0.2 s)") + t:check(vd.audio == nil and vd.audioError == nil, "no audio track, no audio error") +end + +-- 5. Theora in Matroska -> ogv +do + local mv = F.video.open(file(MKV)) :: any + local out, e = F.save(mv, nil, { format = "ogv" }) + t:check(out ~= nil, "mkv -> ogv: " .. tostring(e)) + if out then + local v2 = Ogv.open(Bytes.reader(out)) :: any + frames(v2, MKV, "mkv -> ogv", 25) + end +end + +-- 6. not Theora: plain Ogg Vorbis goes to the audio format, writing other codecs fails +do + local vd = Ogv.open(Bytes.reader(file(AV))) :: any + local at = vd.demuxer:track("audio") + local ogg = AudioWrap.wrap(vd.demuxer, at) :: buffer + t:eq(Ogv.sniff(Bytes.reader(ogg)), 0, "sniff: Ogg Vorbis is not ogv") + local a = F.load(ogg, { name = "x.ogg" }) + t:check(a ~= nil and a.kind == "audio", "F.load of Ogg Vorbis named .ogg: audio") + local v4, e4 = Ogv.open(Bytes.reader(ogg)) + t:check(v4 ~= nil and v4.decodeError ~= nil, "an Ogg without video: opens, frames UNSUPPORTED (" .. tostring(e4) .. ")") + local _, ee = Ogv.encode(Ogv.open(Bytes.reader(ogg)) :: any) + t:check(ee ~= nil and ee.code == Err.UNSUPPORTED, "encode without Theora: UNSUPPORTED") + local _, eg = Ogv.open(Bytes.reader(buffer.fromstring("OggS garbage"))) + t:check(eg ~= nil, "garbage: an error") + local cut = buffer.create(5000) + buffer.copy(cut, 0, file(Q0), 0, 5000) + local vc = Ogv.open(Bytes.reader(cut)) + t:check(vc ~= nil, "a truncated file opens") +end + +-- 7. fuzz +t:fuzz("open", C.fuzzOpen(Ogv), { buffer.tostring(file(Q0)) }, { mutations = 16, garbage = 50 }) + +t:done() diff --git a/tools/fixtures/theora.py b/tools/fixtures/theora.py index 4395444..7d05299 100644 --- a/tools/fixtures/theora.py +++ b/tools/fixtures/theora.py @@ -8,6 +8,7 @@ # tests/gen/theora_dupe.luau the same, file with an empty packet after the 5th frame (frames: of the original) # tests/gen/theora_av.luau { file (base64 .ogv with Vorbis), frames, pcm (f32le of ffmpeg's audio decode, base64), # rate, channels } +# tests/gen/theora_opus.luau, theora_flac.luau the same with mono Opus / FLAC audio # tests/gen/theora_mkv.luau { file (base64 .mkv), frames } # tests/gen/theora_bench.luau { file (base64 .ogv, 320x240) } for tools/bench.luau import base64, os, shutil, struct, subprocess, tempfile, zlib @@ -184,6 +185,15 @@ def generate(ctx): pcm = ff(["-i", av, "-map", "0:a", "-f", "f32le", "-"]) ctx.emit("theora_av", {"file": b64(open(av, "rb").read()), "frames": framecrc(av, "yuv420p"), "width": 160, "height": 120, "pcm": b64(pcm), "rate": 44100, "channels": 2}) + # Theora + Opus, Theora + FLAC (mono, 0.5 s) + for name, aenc, rate in (("opus", ["-c:a", "libopus", "-b:a", "48k"], 48000), ("flac", ["-c:a", "flac"], 22050)): + path = os.path.join(tmp, "a_" + name + ".ogv") + ff(src("testsrc2", 96, 64, 25, 0.5) + ["-f", "lavfi", "-i", "sine=frequency=330:sample_rate=%d" % rate, + "-t", "0.5", "-ac", "1", "-c:v", "libtheora", "-q:v", "4"] + aenc + + ["-shortest", path]) + pcm = ff(["-i", path, "-map", "0:a", "-f", "f32le", "-"]) + ctx.emit("theora_" + name, {"file": b64(open(path, "rb").read()), "frames": framecrc(path, "yuv420p"), + "width": 96, "height": 64, "pcm": b64(pcm), "rate": rate, "channels": 1}) # Theora in Matroska (CodecPrivate: the three headers, Xiph-laced) mkv = os.path.join(tmp, "t.mkv") ff(["-i", os.path.join(tmp, "odd.ogv"), "-c", "copy", mkv])