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.
290 lines
10 KiB
Luau
290 lines
10 KiB
Luau
--!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
|