ws-video2-theora: codecs/video/Theora, a Theora decoder (port of libtheora 1.2.0, BSD)
Headers (identification, comment via VorbisComment, setup: loop-filter limits, quant ranges -> dequant tables, the 80 Huffman trees as collapsed lookup tables), intra / inter frames, coded SB / block flags, MB modes (8 alphabets), MVs (VLC / CLC, last / prior, 4MV with per-format chroma averages, half / quarter-pel), block qi, DCT tokens with EOB runs, DC prediction, the spec IDCT, loop filter, golden / previous refs, 4:2:0 / 4:2:2 / 4:4:4, picture-region crop, empty-packet dupes. Bit-exact with ffmpeg on every frame of 12 fixtures (tests/codecs/theora). Outside the folder: codecs/video/Video BUILTIN entry theora gets a decoder (track.config = Xiph-laced headers, as Matroska's CodecPrivate); licenses/libtheora-BSD.txt + NOTICE row.
This commit is contained in:
1 parent
de4f14a343
commit
8183f4d2d7
9 files changed
+2412
-1
No files matched your search
File diff suppressed because it is too large.
Load diff
@@ -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 = (i // 2 ^ (nb - 1 - d)) % 2
|
||||
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
|
||||
@@ -0,0 +1,270 @@
|
||||
--!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 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
|
||||
|
||||
-- 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 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))
|
||||
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))
|
||||
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,
|
||||
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
|
||||
@@ -294,6 +294,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 } = {
|
||||
@@ -307,7 +314,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" } },
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user