merge ws/video2-theora (Theora codec, ogv)

This commit is contained in:
4DBug committed 2026-10-31 15:22:40 -05:00
commit 77479b6a2f
15 files changed
+3195 -2

No files matched your search

+12
View File
@@ -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",
File diff suppressed because it is too large. Load diff
+370
View File
@@ -0,0 +1,370 @@
--!strict
-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame /
-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis
-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the
-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman
-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause:
-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking;
-- the table layout here is simpler). Never throws: bad headers return nil, message.
local Bits = require("@formats/core/Bits")
local H = {}
export type Info = {
versionMajor: number,
versionMinor: number,
versionSub: number,
frameWidth: number, -- coded frame size (multiples of 16)
frameHeight: number,
picWidth: number, -- the picture region (the displayed part)
picHeight: number,
picX: number, -- from the left
picY: number, -- from the bottom, as stored
fpsNum: number,
fpsDen: number,
aspectNum: number,
aspectDen: number,
colorspace: number, -- 0 unspecified, 1 Rec. 470M, 2 Rec. 470BG
bitrate: number,
quality: number,
granuleShift: number,
pixelFormat: number, -- 0 4:2:0, 2 4:2:2, 3 4:4:4 (1 is reserved)
}
export type Setup = {
lflim: { number }, -- [qi + 1]: loop filter limit
dequant: buffer, -- u16 [((qi * 3 + pli) * 2 + qti) * 64 + zzi], zig-zag order, scaled by 4 like libtheora
huff: { number }, -- the 80 collapsed trees, one flat array (see buildTable)
roots: { number }, -- [table + 1]: the root node offset in huff
}
-- the zig-zag scan: natural index of the coefficient at scan position zzi
H.ZIGZAG = {
0, 1, 8, 16, 9, 2, 3, 10, 17, 24, 32, 25, 18, 11, 4, 5, 12, 19, 26, 33, 40, 48, 41, 34, 27, 20, 13, 6, 7, 14, 21, 28,
35, 42, 49, 56, 57, 50, 43, 36, 29, 22, 15, 23, 30, 37, 44, 51, 58, 59, 52, 45, 38, 31, 39, 46, 53, 60, 61, 54, 47, 55, 62, 63,
}
local function ilog(v: number): number
local n = 0
while v > 0 do
n += 1
v = v // 2
end
return n
end
-- ------------------------------------------------------------------------------------------------ identification
-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora"
function H.info(b: buffer, off: number, len: number): (Info?, string?)
if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora identification header"
end
local br = Bits.msbReader(b, off + 7, len - 7)
local info: Info = {
versionMajor = br:read(8),
versionMinor = br:read(8),
versionSub = br:read(8),
frameWidth = br:read(16) * 16,
frameHeight = br:read(16) * 16,
picWidth = br:read(24),
picHeight = br:read(24),
picX = br:read(8),
picY = br:read(8),
fpsNum = br:read(32),
fpsDen = br:read(32),
aspectNum = br:read(24),
aspectDen = br:read(24),
colorspace = br:read(8),
bitrate = br:read(24),
quality = br:read(6),
granuleShift = br:read(5),
pixelFormat = br:read(2),
}
local reserved = br:read(3)
if br.err then
return nil, "truncated identification header"
end
if info.versionMajor > 3 or (info.versionMajor == 3 and info.versionMinor > 2) then
return nil, "unsupported: Theora bitstream version " .. info.versionMajor .. "." .. info.versionMinor
end
if info.frameWidth == 0 or info.frameHeight == 0 or info.picWidth + info.picX > info.frameWidth or info.picHeight + info.picY > info.frameHeight then
return nil, "bad frame / picture size"
end
if info.fpsNum == 0 or info.fpsDen == 0 then
return nil, "bad frame rate"
end
if info.pixelFormat == 1 or reserved ~= 0 then
return nil, "reserved pixel format"
end
return info, nil
end
-- ------------------------------------------------------------------------------------------------ comment
-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora"
function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, nil, "not a Theora comment header"
end
local p, e = off + 7, off + len
local function str(): string?
if p + 4 > e then
return nil
end
local n = buffer.readu32(b, p)
p += 4
if n > e - p then
return nil
end
local s = buffer.readstring(b, p, n)
p += n
return s
end
local vendor = str()
if not vendor or p + 4 > e then
return nil, nil, "truncated comment header"
end
local count = buffer.readu32(b, p)
p += 4
if count * 4 > e - p then
return nil, nil, "bad comment count"
end
local list: { string } = {}
for _ = 1, count do
local s = str()
if not s then
return nil, nil, "truncated comment header"
end
table.insert(list, s)
end
return vendor, list, nil
end
-- ------------------------------------------------------------------------------------------------ Huffman trees
-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in
-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf
-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits).
local MAXBITS = 8
local function readTree(br: any): ({ number }?, { number }?, { number }?)
-- the trie: kid0 / kid1 child ids (0 = none), tok = token or -1 (node 1 is the root)
local kid0, kid1, tok = { 0 }, { 0 }, { -1 }
-- as libtheora's oc_huff_tree_unpack: code is the current codeword left-aligned in 32 bits, len its length
local code, len, nleaves = 0, 0, 0
while true do
local bit = br:read(1)
if br.err then
return nil, nil, nil
end
if bit == 0 then
len += 1
if len > 32 then
return nil, nil, nil
end
else
nleaves += 1
if nleaves > 32 then
return nil, nil, nil
end
local t = br:read(5)
-- insert the leaf
local n = 1
for d = 1, len do
local k = (code // 2 ^ (32 - d)) % 2
local kids = if k == 0 then kid0 else kid1
local nx = kids[n]
if nx == 0 then
nx = #tok + 1
kid0[nx], kid1[nx], tok[nx] = 0, 0, -1
kids[n] = nx
end
n = nx
end
tok[n] = t
if len <= 0 then
break
end
-- the next codeword: clear the trailing 1 bits, then set the last 0 bit
local cb = 2 ^ (32 - len)
while len > 0 and (code // cb) % 2 == 1 do
code -= cb
cb *= 2
len -= 1
end
if len <= 0 then
break
end
code += cb
end
end
return kid0, kid1, tok
end
local function buildTable(out: { number }, kid0: { number }, kid1: { number }, tok: { number }): number
local heights: { [number]: number } = {}
local function height(n: number): number
local h = heights[n]
if h then
return h
end
h = 0
if tok[n] < 0 then
local a = if kid0[n] ~= 0 then height(kid0[n]) else 0
local c = if kid1[n] ~= 0 then height(kid1[n]) else 0
h = 1 + math.max(a, c)
end
heights[n] = h
return h
end
local function node(n: number): number
local nb = math.clamp(height(n), 1, MAXBITS)
local off = #out + 1
out[off] = nb
local size = 2 ^ nb
for i = 1, size do
out[off + i] = 0
end
for i = 0, size - 1 do
local cur, d = n, 0
while d < nb and tok[cur] < 0 do
local bit = bit32.extract(i, nb - 1 - d, 1)
local nx = if bit == 0 then kid0[cur] else kid1[cur]
d += 1
cur = nx
if nx == 0 then
break
end
end
if cur == 0 then
out[off + 1 + i] = d * 64 -- no code here (a corrupt tree): token 0
elseif tok[cur] >= 0 then
out[off + 1 + i] = d * 64 + tok[cur]
else
out[off + 1 + i] = -node(cur)
end
end
return off
end
return node(1)
end
-- ------------------------------------------------------------------------------------------------ setup
local DC_MIN = { 16, 32 }
local AC_MIN = { 8, 16 }
-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora"
function H.setup(b: buffer, off: number, len: number): (Setup?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora setup header"
end
local br = Bits.msbReader(b, off + 7, len - 7)
-- loop filter limits, AC / DC scales
local lflim, acScale, dcScale = table.create(64, 0), table.create(64, 0), table.create(64, 0)
local nb = br:read(3)
for qi = 1, 64 do
lflim[qi] = br:read(nb)
end
nb = br:read(4) + 1
for qi = 1, 64 do
acScale[qi] = br:read(nb)
end
nb = br:read(4) + 1
for qi = 1, 64 do
dcScale[qi] = br:read(nb)
end
local nbms = br:read(9) + 1
local bms: { { number } } = {}
for m = 1, nbms do
local mat = table.create(64, 0)
for ci = 1, 64 do
mat[ci] = br:read(8)
end
bms[m] = mat
end
if br.err then
return nil, "truncated setup header"
end
-- the quant ranges of the 6 (qti, pli) pairs: sizes and base matrix indices (0-based)
local ranges: { { sizes: { number }, idx: { number } } } = {}
local mb = ilog(nbms - 1)
for i = 0, 5 do
local qti, pli = i // 3, i % 3
local copy = false
if i > 0 and br:read(1) == 0 then
copy = true
local from = i - 1
if qti > 0 and br:read(1) == 1 then
from = pli -- the same plane of the intra set
end
ranges[i + 1] = ranges[from + 1]
end
if not copy then
local sizes, idx = {}, { br:read(mb) }
local qi = 0
while qi < 63 do
local s = br:read(ilog(62 - qi)) + 1
table.insert(sizes, s)
qi += s
table.insert(idx, br:read(mb))
end
if qi > 63 then
return nil, "bad quant ranges"
end
for _, m in idx do
if m >= nbms then
return nil, "bad base matrix index"
end
end
ranges[i + 1] = { sizes = sizes, idx = idx }
end
end
if br.err then
return nil, "truncated setup header"
end
-- the dequantisation tables (oc_dequant_tables_init)
local dequant = buffer.create(64 * 6 * 64 * 2)
local base = table.create(64, 0)
for qti = 0, 1 do
for pli = 0, 2 do
local r = ranges[qti * 3 + pli + 1]
local qi = 0
for qri = 0, #r.sizes do
local m0 = bms[r.idx[qri + 1] + 1]
table.move(m0, 1, 64, 1, base)
local qiStart = qi
local qiEnd = if qri == #r.sizes then qi + 1 else qi + r.sizes[qri + 1]
while true do
local o = ((qi * 3 + pli) * 2 + qti) * 64
local q = (dcScale[qi + 1] * base[1] // 100) * 4
buffer.writeu16(dequant, o * 2, math.clamp(q, DC_MIN[qti + 1], 4096))
for zzi = 1, 63 do
q = (acScale[qi + 1] * base[H.ZIGZAG[zzi + 1] + 1] // 100) * 4
buffer.writeu16(dequant, (o + zzi) * 2, math.clamp(q, AC_MIN[qti + 1], 4096))
end
qi += 1
if qi >= qiEnd then
break
end
-- interpolate the next base matrix
local m1 = bms[r.idx[qri + 2] + 1]
local sz = r.sizes[qri + 1]
for ci = 1, 64 do
base[ci] = (2 * ((qiEnd - qi) * m0[ci] + (qi - qiStart) * m1[ci]) + sz) // (2 * sz)
end
end
end
end
end
-- the 80 Huffman trees
local huff: { number } = {}
local roots: { number } = {}
for t = 1, 80 do
local k0, k1, tk = readTree(br)
if not k0 or not k1 or not tk then
return nil, "bad Huffman tree " .. (t - 1)
end
roots[t] = buildTable(huff, k0, k1, tk)
end
return { lflim = lflim, dequant = dequant, huff = huff, roots = roots }, nil
end
return H
+289
View File
@@ -0,0 +1,289 @@
--!strict
-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau
-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames).
-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV
-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes,
-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau);
-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout).
-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too).
--
-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate
-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err
-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region
-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down
-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position
--
-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture).
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local VorbisComment = require("@formats/codecs/audio/VorbisComment")
local Header = require("@formats/codecs/video/Theora/Header")
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)
}
local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" }
-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil
function Theora.isHeader(b: buffer, off: number?, len: number?): number?
local o = off or 0
local n = len or (buffer.len(b) - o)
if n < 7 then
return nil
end
local t = buffer.readu8(b, o)
if t >= 0x80 and t <= 0x82 and buffer.readstring(b, o + 1, 6) == "theora" then
return t - 0x7F
end
return nil
end
-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil)
function Theora.splitConfig(c: buffer): { buffer }?
local n = buffer.len(c)
if n < 3 or buffer.readu8(c, 0) ~= 2 then
return nil
end
local p, lens = 1, {}
for k = 1, 2 do
local size = 0
repeat
if p >= n then
return nil
end
local b = buffer.readu8(c, p)
size += b
p += 1
until b < 255
lens[k] = size
end
lens[3] = n - p - lens[1] - lens[2]
if lens[3] < 0 then
return nil
end
local out = {}
for k = 1, 3 do
out[k] = buffer.create(lens[k])
buffer.copy(out[k], 0, c, p, lens[k])
p += lens[k]
end
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
return -1
end
local shift = 2 ^ info.granuleShift
local key = g // shift
local f = key + g % shift
-- since bitstream 3.2.1 the first frame is granule 1
local v = info.versionMajor * 65536 + info.versionMinor * 256 + info.versionSub
if v >= 0x030201 then
f -= 1
end
return f
end
-- ------------------------------------------------------------------------------------------------ decoder
local Dec = {}
Dec.__index = Dec
export type TheoraDecoder = typeof(setmetatable(
{} :: {
info: Header.Info,
vendor: string,
comments: { string },
tags: { [string]: string },
width: number, -- the picture region
height: number,
frameRate: number,
pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p"
aspect: number, -- pixel aspect ratio (1 when unknown)
frames: number, -- packets decoded (dupes included)
_st: Decoder.State,
_any: boolean, -- a frame was decoded
},
Dec
))
-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config
function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?)
local list: { buffer }? = nil
if type(headers) == "buffer" then
list = Theora.splitConfig(headers)
elseif type(headers) == "table" then
list = headers
end
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 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 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)
return setmetatable({
info = info,
vendor = vendor,
comments = comments,
tags = tags,
width = info.picWidth,
height = info.picHeight,
frameRate = info.fpsNum / info.fpsDen,
pixelFormat = PIXEL_FORMATS[info.pixelFormat],
aspect = if info.aspectNum > 0 and info.aspectDen > 0 then info.aspectNum / info.aspectDen else 1,
frames = 0,
_st = st,
_any = false,
}, Dec), nil
end
-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil).
function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?)
local o = off or 0
local n = len or (buffer.len(data) - o)
if o < 0 or n < 0 or o + n > buffer.len(data) then
return nil, Err.new(Err.ARG, "decode: range outside the buffer")
end
if n > 0 and buffer.readu8(data, o) >= 0x80 then
return nil, nil
end
local kind, msg = Decoder.decode(self._st, data, o, n)
if not kind then
return nil, Err.from(msg)
end
self.frames += 1
if kind ~= "dup" then
self._any = true
end
return kind, nil
end
-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data)
function Dec.reset(self: TheoraDecoder)
local st = self._st
st.shown = st.prev
end
local function window(self: TheoraDecoder): (number, number, number, number)
local info = self.info
-- the picture's top-left corner counted from the top of the frame (the header counts y from the bottom)
return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight
end
-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width,
-- chroma height
function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number)
local st = self._st
local x0, y0, w, h = window(self)
local hd, vd = st.hdec, st.vdec
local cx0, cy0 = x0 // 2 ^ hd, y0 // 2 ^ vd
local cw, ch = (w + hd) // 2 ^ hd, (h + vd) // 2 ^ vd
cw = math.min(cw, st.pw[2] - cx0)
ch = math.min(ch, st.ph[2] - cy0)
return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch
end
-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down)
function Dec.image(self: TheoraDecoder): Types.Image
local y, u, v, cw, ch = self:planes()
local w, h = self.width, self.height
local img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
local ow, oh = (w + 1) // 2, (h + 1) // 2
buffer.copy(px, 0, y, 0, w * h)
local st = self._st
if st.hdec == 1 and st.vdec == 1 then
for r = 0, oh - 1 do
local sr = math.min(r, ch - 1)
buffer.copy(px, w * h + r * ow, u, sr * cw, math.min(ow, cw))
buffer.copy(px, w * h + ow * oh + r * ow, v, sr * cw, math.min(ow, cw))
end
else
Decoder.downsample(u, cw, ch, st.hdec, px, w * h, ow, oh)
Decoder.downsample(v, cw, ch, st.hdec, px, w * h + ow * oh, ow, oh)
end
img.meta.yuv = { range = "limited", matrix = "bt601" }
img.meta.source = { format = "theora", pixelFormat = self.pixelFormat, colorspace = self.info.colorspace }
return img
end
-- ------------------------------------------------------------------------------------------------ registry
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config
-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat
function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
if not track.config then
return nil, Err.new(Err.CORRUPT, "Theora track without its headers")
end
local dec, err = Theora.new(track.config :: buffer, { maxPixels = opts and opts.maxPixels })
if not dec then
return nil, err
end
local d = dec :: TheoraDecoder
local pending: { any } = {}
local self: any = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local kind, e = d:decode(packet.data)
if not kind then
return e
end
if d._any then
table.insert(pending, { d:image(), packet.pts, kind == "key" })
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local p = table.remove(pending, 1)
if not p then
return nil, nil, nil
end
return p[1], p[2], p[3]
end
function self.flush(_: any) end
function self.reset(_: any)
table.clear(pending)
d:reset()
end
return self, nil
end
return Theora
+8 -1
View File
@@ -253,6 +253,13 @@ local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec
return H264.newVideoDecoder(track, opts)
end
-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv
-- builds the same); one picture per packet, empty packets repeat the previous one
local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Theora = require("@formats/codecs/video/Theora")
return Theora.newVideoDecoder(track, opts)
end
-- ------------------------------------------------------------------------------------------------ registry
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
local BUILTIN: { Entry } = {
@@ -266,7 +273,7 @@ local BUILTIN: { Entry } = {
{ id = "hevc", name = "H.265 / HEVC", fourcc = { "hvc1", "hev1", "HEVC", "H265" }, matroska = { "V_MPEGH/ISO/HEVC" } },
{ id = "vp9", name = "VP9", fourcc = { "VP90", "vp09" }, matroska = { "V_VP9" } },
{ id = "av1", name = "AV1", fourcc = { "AV01", "av01" }, matroska = { "V_AV1" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" } },
{ id = "theora", name = "Theora", matroska = { "V_THEORA" }, new = theoraDecoder },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
}
+407
View File
@@ -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