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

+2
View File
@@ -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", "mpeg2", "h264", audio: true, fragments: true | `tests/video/mp4.luau` |
| video | mpegps | .mpg .mpeg .vob .m1v .mpv .dat | yes | - | streaming: true, video: "mpeg1", "mpeg2", audio: true | `tests/video/mpegps.luau` |
| video | mpegts | .ts .m2ts .mts .tsv | yes | - | streaming: true, video: "mpeg1", "mpeg2", "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` |
@@ -136,4 +137,5 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder
- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska
- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
+27 -1
View File
@@ -183,6 +183,7 @@ Images and animated images save as videos too.
| Destination | Video | Audio |
|---|---|---|
| webm | VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) | Opus / Vorbis copied |
| ogv | Theora copied (the source must be Theora: ogv or mkv) | Vorbis / Opus copied |
| mkv | any codec copied, else MJPEG | copied, else PCM s16 |
| mp4, mov | H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG | AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only |
| avi | MJPEG copied, else MJPEG encoded (`quality`) | PCM s16 |
@@ -287,6 +288,30 @@ Interlaced frames come out woven, as they were coded: deinterlace them yourself
lines of the same field. A 720x576 interlaced stream decodes at about 130 frames per second in Luau on one desktop
core (`tools/bench.luau`): real time with room to spare on a PC, less so on phones.
## Ogg Theora
Ogg video (`.ogv`, or `.ogg` with a Theora stream) opens like any other container: the `ogv` format demuxes every
Ogg stream, Theora video decodes bit-exactly (as libtheora / ffmpeg) in all three pixel formats (4:2:2 and 4:4:4
chroma is averaged down to yuv420p), and a Vorbis, Opus or FLAC track becomes `v.audio`. Plain Ogg Vorbis / Opus /
FLAC files stay audio. Theora in Matroska (`V_THEORA`) decodes too, and an Ogg Theora video remuxes to ogv or mkv
(there is no Theora encoder).
```luau
local v = assert(F.video.open(ogvBytes)) -- Theora + Vorbis
assert(v.format == "ogv" and v.codec == "theora" and v.width == 64 and v.height == 48)
assert(v.frameRate == 10 and v.audio ~= nil)
local n = 0
while v:nextFrame() do n += 1 end -- dropped frames repeat the previous picture
assert(n == 10)
local Theora = F.format("ogv") -- the format module: sniff / demux / open / encode
local d = assert(Theora.demux(F.Bytes.reader(ogvBytes)))
local vt = d:track("video")
assert(vt.codec == "theora" and vt.timescale == 10) -- packet times are frame numbers here
v:reset()
local mkv = assert(F.save(v, nil, { format = "mkv" })) -- Theora + Vorbis copied into Matroska
assert(F.video.open(mkv).codec == "theora")
```
## Playing in a game loop
Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes
@@ -331,7 +356,8 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels)
| Format | Read | Write | Video codecs (decode) |
|---|---|---|---|
| mp4 / mov / m4v / 3gp | yes | yes | H.264, MJPEG, MPEG-1, MPEG-2 |
| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw (+ H.264) |
| mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, MPEG-2, raw, Theora (+ H.264) |
| ogv (Ogg Theora) | yes | yes (Theora + Vorbis / Opus copied) | Theora |
| avi | yes | yes | MJPEG, MPEG-1, MPEG-2, raw (+ H.264) |
| mpegts, mpegps | yes | - | MPEG-1, MPEG-2, H.264 |
| y4m | yes | yes | raw |
+1
View File
@@ -39,6 +39,7 @@
| `src/Formats/codecs/H264/` (Tables: CAVLC / CABAC / deblocking / scaling constant tables of ITU-T H.264, extracted from openh264 sources; the decoder itself is written from the spec) | openh264 2.x (Cisco) | BSD-2-Clause: [openh264-LICENSE.txt](openh264-LICENSE.txt) |
| `src/Formats/codecs/video/Dsp.luau` (the 8x8 IDCT: jrevdct.c translated to Luau, branch tree and constants unchanged) | IJG jrevdct.c as shipped in ffmpeg (libavcodec/jrevdct.c; IJG-licensed, not LGPL: ffmpeg's LICENSE.md) | IJG: [libjpeg-README.ijg](libjpeg-README.ijg). This software is based in part on the work of the Independent JPEG Group. |
| `tests/gen/h264_jvt` (downloaded at fixture time, not committed) | ITU-T H.264.1 / JVT conformance bitstreams (itu.int) | ITU-T test data |
| `src/Formats/codecs/video/Theora/` (Header, Decoder) | a Luau port of the libtheora 1.2.0 decoder (Xiph.Org; decinfo.c, dequant.c, quant.c, huffdec.c, decode.c, state.c, idct.c, fragment.c) checked against the Theora I specification; the token storage is simplified (coefficients per fragment) and the post-processing is not ported | BSD 3-clause: [libtheora-BSD.txt](libtheora-BSD.txt) |
Ports of third-party code (minimp3, stb_vorbis, libopus, ...) add a row here and their upstream licence text in this
folder (see docs/STYLE.md, "Absorbing an existing repo").
+28
View File
@@ -0,0 +1,28 @@
Copyright (C) 2002-2009 Xiph.org Foundation
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
- Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
- Neither the name of the Xiph.org Foundation nor the names of its
contributors may be used to endorse or promote products derived from
this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE FOUNDATION
OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+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
+285
View File
@@ -0,0 +1,285 @@
-- codecs/video/Theora tests. Against ffmpeg (tools/fixtures/theora.py, its vp3 decoder = libtheora's output): every
-- frame of every stream, bit-exact (Adler-32 of the native planes of the picture region, as ffmpeg's framecrc): 4:2:0 /
-- 4:2:2 / 4:4:4, qualities 0..10, a 300 kbit/s high-motion stream (4MV, golden frames, multiple qi), picture regions
-- smaller than the coded frame (even sizes from the encoder, odd sizes at offsets patched into the header), frames
-- the encoder dropped (empty packets: ffmpeg outputs nothing, we repeat the previous picture) and one spliced in;
-- image() as yuv420p (4:2:2 / 4:4:4 chroma averaged); Theora in Matroska through the codecs/video/Video registry.
-- Errors: missing / bad headers, maxPixels, header packets in the data, garbage packets; the fuzz no-throw passes
-- (headers, key and inter frames).
local T = require("@tests/T")
local Theora = require("@formats/codecs/video/Theora")
local Video = require("@formats/codecs/video/Video")
local Ogg = require("@formats/containers/Ogg")
local Mkv = require("@formats/video/mkv")
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("theora")
local CASES = { "q6", "q0", "q10", "motion", "odd", "static", "yuv422", "yuv444", "odd444", "crop", "crop422" }
local FIXTURES: { [string]: any } = {
q6 = require("@tests/gen/theora_q6"),
q0 = require("@tests/gen/theora_q0"),
q10 = require("@tests/gen/theora_q10"),
motion = require("@tests/gen/theora_motion"),
odd = require("@tests/gen/theora_odd"),
static = require("@tests/gen/theora_static"),
yuv422 = require("@tests/gen/theora_yuv422"),
yuv444 = require("@tests/gen/theora_yuv444"),
odd444 = require("@tests/gen/theora_odd444"),
crop = require("@tests/gen/theora_crop"),
crop422 = require("@tests/gen/theora_crop422"),
}
-- the Theora packets of an Ogg file: headers, data packets
local function packets(file: buffer): ({ buffer }, { buffer })
local d = Ogg.open(file)
local serial = d:find("theora")
local hdrs, data = {}, {}
for p in d:packets(serial) do
if #hdrs < 3 then
table.insert(hdrs, Ogg.copy(p))
else
table.insert(data, Ogg.copy(p))
end
end
return hdrs, data
end
-- ffmpeg's framecrc: Adler-32 started at 0 over the packed planes
local function crc(y: buffer, u: buffer, v: buffer): number
local a = Adler32.of(y, nil, nil, 0)
a = Adler32.of(u, nil, nil, a)
return Adler32.of(v, nil, nil, a)
end
local samples: { buffer } = {}
local headerSets: { { buffer } } = {}
-- 1. every fixture, every frame
for _, name in CASES do
local fx = FIXTURES[name]
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
table.insert(headerSets, hdrs)
local dec, err = Theora.new(hdrs)
t:check(dec ~= nil, name .. ": headers: " .. tostring(err))
if dec then
t:eq(dec.width, fx.width, name .. ": width")
t:eq(dec.height, fx.height, name .. ": height")
t:eq(dec.pixelFormat, fx.pixfmt, name .. ": pixel format")
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
local bad, dupes, prev = 0, 0, nil :: number?
for k, p in data do
local kind, e = dec:decode(p)
if not kind then
bad += 1
t:check(false, name .. ": frame " .. (k - 1) .. ": " .. tostring(e))
continue
end
local y, u, v = dec:planes()
local c = crc(y, u, v)
local w = want[k - 1]
if kind == "dup" then
dupes += 1
t:check(w == nil, name .. ": ffmpeg shows no frame for empty packet " .. (k - 1))
if c ~= prev then
bad += 1
end
elseif w ~= c then
bad += 1
end
prev = c
end
t:eq(bad, 0, name .. ": frames different from ffmpeg's (of " .. #data .. ", " .. dupes .. " repeated)")
t:eq(#data - dupes, #fx.frames, name .. ": as many shown frames as ffmpeg")
table.insert(samples, data[1])
if data[2] then
table.insert(samples, data[2])
end
end
end
-- 2. an empty packet spliced in after the 5th frame repeats it; the rest follows
do
local fx = require("@tests/gen/theora_dupe") :: any
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
local bad, prev = 0, nil :: number?
for k, p in data do
local kind = dec:decode(p)
local y, u, v = dec:planes()
local c = crc(y, u, v)
if k == 6 then
t:eq(kind, "dup", "dupe: the empty packet")
t:eq(buffer.len(p), 0, "dupe: it is empty")
t:eq(c, prev, "dupe: repeats the previous picture")
elseif c ~= fx.frames[if k > 6 then k - 1 else k][2] then
bad += 1
end
prev = c
end
t:eq(bad, 0, "dupe: the other frames")
end
-- 3. image(): yuv420p, the planes as they are (4:2:0) or averaged (4:2:2 / 4:4:4)
for _, name in { "q6", "crop", "yuv422", "crop422", "odd444" } do
local fx = FIXTURES[name]
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
dec:decode(data[1])
dec:decode(data[2])
local img = dec:image()
local y, u, v, cw, ch = dec:planes()
local w, h = dec.width, dec.height
local ow, oh = (w + 1) // 2, (h + 1) // 2
t:eq(img.format, "yuv420p", name .. ": image format")
t:eq(img.width * 1000 + img.height, w * 1000 + h, name .. ": image size")
t:eq(buffer.len(img.pixels), w * h + 2 * ow * oh, name .. ": image bytes")
t:eq(Adler32.of(img.pixels, 0, w * h), Adler32.of(y), name .. ": luma")
local bad = 0
for r = 0, oh - 1 do
for c = 0, ow - 1 do
local want
if fx.pixfmt == "yuv420p" then
want = buffer.readu8(u, math.min(r, ch - 1) * cw + c)
elseif fx.pixfmt == "yuv422p" then
want = (buffer.readu8(u, math.min(2 * r, ch - 1) * cw + c) + buffer.readu8(u, math.min(2 * r + 1, ch - 1) * cw + c) + 1) // 2
else
local r0, r1 = math.min(2 * r, ch - 1), math.min(2 * r + 1, ch - 1)
local c0, c1 = math.min(2 * c, cw - 1), math.min(2 * c + 1, cw - 1)
want = (buffer.readu8(u, r0 * cw + c0) + buffer.readu8(u, r0 * cw + c1) + buffer.readu8(u, r1 * cw + c0) + buffer.readu8(u, r1 * cw + c1) + 2) // 4
end
if buffer.readu8(img.pixels, w * h + r * ow + c) ~= want then
bad += 1
end
end
end
t:eq(bad, 0, name .. ": U downsampled")
local _ = v
t:eq(img.meta.yuv and img.meta.yuv.matrix, "bt601", name .. ": colour matrix")
end
-- 4. Theora in Matroska: the registry entry (V_THEORA, Xiph-laced CodecPrivate) through video/mkv
do
t:eq(Video.fromMatroska("V_THEORA"), "theora", "registry: V_THEORA")
t:check(Video.canDecode("theora"), "registry: theora decodes")
local fx = require("@tests/gen/theora_mkv") :: any
local v, err = Mkv.open(Bytes.reader(Base64.decode(fx.file) :: buffer))
t:check(v ~= nil, "mkv: open: " .. tostring(err))
if v then
t:eq(v.codec, "theora", "mkv: codec")
local n, bad, shown = 0, 0, 0
local want: { [number]: number } = {}
for _, f in fx.frames do
want[f[1]] = f[2]
end
while true do
local f, e = v:nextFrame()
if not f then
t:check(e == nil, "mkv: frames: " .. tostring(e))
break
end
local img = f.image
local w = want[math.floor(f.pts * 25 + 0.5)]
if w then
shown += 1
if Adler32.of(img.pixels, nil, nil, 0) ~= w then
bad += 1
end
end
n += 1
end
t:eq(bad, 0, "mkv: frames as ffmpeg's")
t:eq(shown, #fx.frames, "mkv: every frame ffmpeg shows")
end
end
-- 5. API details and errors
do
local fx = FIXTURES.q6
local hdrs, data = packets(Base64.decode(fx.file) :: buffer)
local dec = Theora.new(hdrs) :: Theora.TheoraDecoder
t:eq(dec.frameRate, 25, "frame rate")
t:check(dec.vendor ~= "" and dec.tags.encoder ~= nil, "comment header: vendor and ENCODER tag")
t:eq(Theora.isHeader(hdrs[1]), 1, "isHeader: identification")
t:eq(Theora.isHeader(hdrs[3]), 3, "isHeader: setup")
t:eq(Theora.isHeader(data[1]), nil, "isHeader: data")
local kind, e = dec:decode(hdrs[2])
t:check(kind == nil and e == nil, "a header packet in the data is skipped")
t:eq(Theora.granuleFrame(dec.info, 0), -1, "granule 0 (3.2.1 numbering)")
t:eq(Theora.granuleFrame(dec.info, 2 ^ dec.info.granuleShift * 12 + 3), 14, "granule: keyframe 12 + 3")
-- the Xiph-laced config Matroska uses
local lens = { buffer.len(hdrs[1]), buffer.len(hdrs[2]) }
local w = Bytes.writer(64)
w:u8(2)
for _, l in lens do
local x = l
while x >= 255 do
w:u8(255)
x -= 255
end
w:u8(x)
end
for _, h in hdrs do
w:bytes(h)
end
local cfg = w:finish()
local parts = Theora.splitConfig(cfg)
t:check(parts ~= nil and #parts == 3 and buffer.len(parts[3]) == buffer.len(hdrs[3]), "splitConfig")
t:check(Theora.new(cfg) ~= nil, "new(config)")
local d2, e2 = Theora.new({ hdrs[1], hdrs[2] })
t:check(d2 == nil and e2 ~= nil and e2.code == Err.CORRUPT, "missing setup header: CORRUPT")
local _, e3 = Theora.new({ hdrs[2], hdrs[1], hdrs[3] })
t:check(e3 ~= nil and e3.code == Err.CORRUPT, "headers out of order: CORRUPT")
local cut = buffer.create(100)
buffer.copy(cut, 0, hdrs[3], 0, 100)
local _, e4 = Theora.new({ hdrs[1], hdrs[2], cut })
t:check(e4 ~= nil, "truncated setup header: " .. tostring(e4))
local _, e5 = Theora.new(hdrs, { maxPixels = 1000 })
t:check(e5 ~= nil and e5.code == Err.LIMIT, "maxPixels: LIMIT")
local _, e6 = dec:decode(data[1], 5, buffer.len(data[1]))
t:check(e6 ~= nil and e6.code == Err.ARG, "decode: range outside the buffer")
-- an inter frame before any keyframe decodes over grey
local fresh = Theora.new(hdrs) :: Theora.TheoraDecoder
t:check(fresh:decode(data[2]) == "inter", "an inter frame first")
local track: any = { id = 1, kind = "video", codec = "theora", timescale = 25, config = cfg }
local vd = Theora.newVideoDecoder(track)
t:check(vd ~= nil, "newVideoDecoder")
if vd then
vd:decode({ track = 1, pts = 0, keyframe = true, data = data[1] })
local img, pts, key = vd:receive()
t:check(img ~= nil and pts == 0 and key == true, "newVideoDecoder: a keyframe picture")
vd:reset()
t:check(vd:receive() == nil, "newVideoDecoder: reset drops pending pictures")
end
local nv, nerr = Theora.newVideoDecoder({ id = 1, kind = "video", codec = "theora", timescale = 25 } :: any)
t:check(nv == nil and nerr ~= nil, "newVideoDecoder without config")
end
-- 6. fuzz: headers, keyframes and inter frames (a decoder primed with a keyframe, fed mutated packets)
do
local hdrs = headerSets[1]
t:fuzz("headers", function(b: buffer)
return Theora.new({ hdrs[1], hdrs[2], b })
end, { hdrs[3] }, { mutations = 24, garbage = 50 })
t:fuzz("identification", function(b: buffer)
return Theora.new({ b, hdrs[2], hdrs[3] })
end, { hdrs[1] }, { mutations = 24, garbage = 20 })
for i, h in headerSets do
local dec = Theora.new(h) :: Theora.TheoraDecoder
local s = { samples[2 * i - 1], samples[2 * i] }
dec:decode(s[1])
t:fuzz("frames " .. CASES[i], function(b: buffer)
local kind = dec:decode(b)
dec:planes()
return kind
end, s, { mutations = 12, garbage = 20, seed = i })
end
end
t:done()
+211
View File
@@ -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()
+39
View File
@@ -1095,3 +1095,42 @@ do
jitTune(false)
end
end
do
-- ------------------------------------------------------------------------------------- ws-video2-theora: fps
-- Theora (codecs/video/Theora): 320x240 clips, 50 frames, keyframe every 25: testsrc2 at 600 kbit/s (mostly static:
-- few coded blocks) and a mandelbrot zoom at 1200 kbit/s (every block coded, moving); decode alone and decode +
-- image() (the yuv420p copy every VideoDecoder frame makes)
local Theora = require("@formats/codecs/video/Theora")
local Ogg = require("@formats/containers/Ogg")
local Base64 = require("@formats/core/Base64")
local TB = require("@tests/gen/theora_bench")
local function run(tag: string)
for _, c in TB do
local d = Ogg.open(Base64.decode(c.file) :: buffer)
local hdrs, data = {}, {}
for p in d:packets(d:find("theora")) do
table.insert(if #hdrs < 3 then hdrs else data, Ogg.copy(p))
end
for _, image in { false, true } do
local n = c.width * c.height * 3 // 2 * #data
local dt = bench(string.format("theora %s %dx%d%s%s", c.name, c.width, c.height, if image then " +img" else "", tag), 3, n, function()
local dec = Theora.new(hdrs) :: any
for _, p in data do
dec:decode(p)
if image then
dec:image()
end
end
end)
print(string.format("%-8s %-30s %8.1f fps", runtime, " (" .. #data .. " frames)", #data / dt))
end
end
end
jitTune(false)
run("")
if runtime == "luajit" then
jitTune(true)
run(" (jit tuned)")
jitTune(false)
end
end
+20
View File
@@ -0,0 +1,20 @@
# Docs inputs for the Ogg Theora section of docs/guide/video.md (tools/fixtures.py; tools/docs_check.py reads them): a
# tiny ffmpeg clip (testsrc 64x48, 10 frames at 10 fps, libtheora + a libvorbis sine track) as Ogg video.
# tests/gen/docs_theora.luau { files = { ["clip.ogv"] = bytes }, vars = { ogvBytes = "clip.ogv" } }
import importlib.util, os, shutil, subprocess, tempfile
INPUTS = ["tools/docs_check.py"]
def generate(ctx):
spec = importlib.util.spec_from_file_location("docs_theora_check", os.path.join(ctx.root, "tools", "docs_check.py"))
dc = importlib.util.module_from_spec(spec)
spec.loader.exec_module(dc)
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
with tempfile.TemporaryDirectory() as d:
out = os.path.join(d, "clip.ogv")
subprocess.run([ffmpeg, "-v", "error", "-y", "-f", "lavfi", "-i", "testsrc=size=64x48:rate=10:duration=1",
"-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100:duration=1", "-c:v", "libtheora",
"-q:v", "6", "-g", "5", "-c:a", "libvorbis", "-q:a", "2", out], check=True, capture_output=True)
files = {"clip.ogv": open(out, "rb").read()}
dc.emit_inputs(ctx, files, {"ogvBytes": "clip.ogv"})
+208
View File
@@ -0,0 +1,208 @@
# Theora fixtures for codecs/video/Theora and video/ogv (tools/fixtures.py): Ogg Theora files made by ffmpeg's
# libtheora encoder (testsrc2 / mandelbrot / static bars, several qualities and bit rates, odd sizes = picture regions
# smaller than the coded frame (the encoder keeps even sizes; two cases patch odd ones at offsets), 4:2:2 and 4:4:4, short and long keyframe intervals), one with an empty packet (a
# repeated frame) spliced in, an Ogg with Vorbis audio, and Theora in Matroska. The reference is ffmpeg's own decode
# (its vp3 decoder, bit-exact with libtheora): `-f framecrc` in the stream's native pixel format, one Adler-32 per
# frame over the packed planes of the picture region, with the frame's pts.
# tests/gen/theora_<name>.luau { name, width, height, pixfmt, file (base64 .ogv), frames = { { pts, adler } } }
# 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 { { name, file (base64 .ogv, 320x240), width, height } } for tools/bench.luau
import base64, os, shutil, struct, subprocess, tempfile, zlib
FF = ["-hide_banner", "-loglevel", "error", "-y"]
def b64(b):
return base64.b64encode(b).decode()
def src(kind, w, h, rate, t):
return ["-f", "lavfi", "-i", "%s=size=%dx%d:rate=%s" % (kind, w, h, rate), "-t", str(t)]
# name: (input args, encoder args, pixel format)
CASES = {
"q6": (src("testsrc2", 320, 240, 25, 1.2), ["-q:v", "6", "-g", "12"], "yuv420p"),
"q0": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "0", "-g", "30"], "yuv420p"),
"q10": (src("mandelbrot", 176, 144, 25, 0.6), ["-q:v", "10", "-g", "8"], "yuv420p"),
"motion": (src("mandelbrot", 240, 160, 30, 1.5), ["-b:v", "300k", "-g", "64"], "yuv420p"),
"odd": (src("testsrc2", 174, 98, 25, 1), ["-q:v", "5", "-g", "10"], "yuv420p"),
"static": (src("smptebars", 160, 120, 25, 1.2), ["-q:v", "4", "-g", "100"], "yuv420p"),
"yuv422": (src("testsrc2", 176, 144, 25, 1), ["-q:v", "6", "-g", "12"], "yuv422p"),
"yuv444": (src("mandelbrot", 144, 112, 25, 1), ["-q:v", "6", "-g", "12"], "yuv444p"),
"odd444": (src("testsrc2", 98, 62, 25, 0.6), ["-q:v", "7", "-g", "6"], "yuv444p"),
}
# ffmpeg's encoder writes even picture sizes at offset 0: these cases patch the identification header to an odd
# picture region at an offset (width, height, x, y from the bottom); the reference is ffmpeg's decode of the patched
# file (-flags unaligned: the exact crop)
PATCH = {
"crop": (src("testsrc2", 176, 112, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv420p", (171, 97, 3, 5)),
"crop422": (src("mandelbrot", 128, 96, 25, 0.6), ["-q:v", "6", "-g", "8"], "yuv422p", (117, 81, 5, 2)),
}
def crc32(b):
return zlib.crc32(b) & 0xFFFFFFFF
def ogg_pages(data):
"""yield (header fields, segment table, body) of each Ogg page"""
i = 0
while i + 27 <= len(data):
assert data[i:i + 4] == b"OggS"
flags, granule, serial, seq = data[i + 5], struct.unpack_from("<q", data, i + 6)[0], \
struct.unpack_from("<I", data, i + 14)[0], struct.unpack_from("<I", data, i + 18)[0]
n = data[i + 26]
segs = list(data[i + 27:i + 27 + n])
body = data[i + 27 + n:i + 27 + n + sum(segs)]
yield flags, granule, serial, seq, segs, body
i += 27 + n + sum(segs)
OGG_CRC = []
for _i in range(256):
r = _i << 24
for _ in range(8):
r = ((r << 1) ^ 0x04C11DB7) if r & 0x80000000 else (r << 1)
OGG_CRC.append(r & 0xFFFFFFFF)
def ogg_crc(b):
c = 0
for x in b:
c = ((c << 8) ^ OGG_CRC[((c >> 24) ^ x) & 0xFF]) & 0xFFFFFFFF
return c
def page(flags, granule, serial, seq, packets_segs, body):
head = b"OggS" + bytes([0, flags]) + struct.pack("<qII", granule, serial, seq) + b"\0\0\0\0" + \
bytes([len(packets_segs)]) + bytes(packets_segs)
p = bytearray(head + body)
struct.pack_into("<I", p, 22, ogg_crc(p))
return bytes(p)
def splice_empty(data, after):
"""rewrite a single-stream Ogg Theora file with one page per packet and an empty packet after data packet
`after` (1-based); granules are recomputed as frame counts since the last keyframe (bitstream 3.2.1 numbering)"""
packets, cur = [], b""
shift = None
for flags, granule, serial, seq, segs, body in ogg_pages(data):
o = 0
for s in segs:
cur += body[o:o + s]
o += s
if s < 255:
packets.append(cur)
cur = b""
sid = serial
shift = (packets[0][40] & 0x03) << 3 | packets[0][41] >> 5
out = []
seq = 0
frames = []
data_packets = packets[3:]
data_packets = data_packets[:after] + [b""] + data_packets[after:]
key = 0
for k, p in enumerate(packets[:3]):
segs = [255] * (len(p) // 255) + [len(p) % 255]
out.append(page(2 if k == 0 else 0, 0, sid, seq, segs, p))
seq += 1
for k, p in enumerate(data_packets):
n = k + 1
if len(p) > 0 and not (p[0] & 0x40):
key = n
segs = [255] * (len(p) // 255) + [len(p) % 255]
g = (key << shift) | (n - key)
out.append(page(4 if k == len(data_packets) - 1 else 0, g, sid, seq, segs, p))
seq += 1
return b"".join(out)
def patch_picture(data, w, h, x, y):
"""rewrite the first page (the identification header) with another picture region"""
out = bytearray(data)
n = out[26]
o = 27 + n # the packet starts here
assert out[o:o + 7] == b"\x80theora"
out[o + 14:o + 17] = w.to_bytes(3, "big")
out[o + 17:o + 20] = h.to_bytes(3, "big")
out[o + 20] = x
out[o + 21] = y
plen = 27 + n + sum(out[27:27 + n])
out[22:26] = b"\0\0\0\0"
struct.pack_into("<I", out, 22, ogg_crc(bytes(out[:plen])))
return bytes(out)
def generate(ctx):
ffmpeg = shutil.which("ffmpeg") or ctx.nix("ffmpeg-full", ["sh", "-c", "command -v ffmpeg"]).decode().strip()
def ff(args):
return subprocess.run([ffmpeg] + FF + args, check=True, capture_output=True).stdout
def framecrc(path, pixfmt, extra=None):
out = ff(["-flags", "unaligned", "-i", path] + (extra or []) + ["-map", "0:v", "-fps_mode", "passthrough", "-pix_fmt", pixfmt,
"-f", "framecrc", "-"]).decode()
frames = []
for line in out.splitlines():
if line.startswith("#"):
continue
parts = [x.strip() for x in line.split(",")]
frames.append([int(parts[1]), int(parts[5], 16)])
return frames
with tempfile.TemporaryDirectory(prefix="formats-theora-") as tmp:
for name, (inp, enc, pixfmt) in CASES.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = open(path, "rb").read()
w, h = [int(x) for x in inp[3].split("=")[2].split(":")[0].split("x")]
ctx.emit("theora_" + name, {"name": name, "width": w, "height": h, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
if name == "q6":
# an empty packet (a dropped / repeated frame) after the 5th frame
dupe = splice_empty(data, 5)
dpath = os.path.join(tmp, "dupe.ogv")
open(dpath, "wb").write(dupe)
ctx.emit("theora_dupe", {"name": "dupe", "width": w, "height": h, "pixfmt": pixfmt, "file": b64(dupe),
"frames": framecrc(path, pixfmt)})
for name, (inp, enc, pixfmt, (pw, ph, px, py)) in PATCH.items():
path = os.path.join(tmp, name + ".ogv")
ff(inp + ["-pix_fmt", pixfmt, "-c:v", "libtheora"] + enc + [path])
data = patch_picture(open(path, "rb").read(), pw, ph, px, py)
open(path, "wb").write(data)
ctx.emit("theora_" + name, {"name": name, "width": pw, "height": ph, "pixfmt": pixfmt, "file": b64(data),
"frames": framecrc(path, pixfmt)})
# Theora + Vorbis (stereo 44.1 kHz)
av = os.path.join(tmp, "av.ogv")
ff(src("testsrc2", 160, 120, 25, 1) + ["-f", "lavfi", "-i", "sine=frequency=440:sample_rate=44100", "-t", "1",
"-ac", "2", "-c:v", "libtheora", "-q:v", "5", "-c:a", "libvorbis",
"-q:a", "3", "-shortest", av])
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])
ctx.emit("theora_mkv", {"file": b64(open(mkv, "rb").read()), "frames": framecrc(mkv, "yuv420p"),
"width": 174, "height": 98})
# the bench streams: an easy clip (testsrc2, mostly static) and a hard one (a mandelbrot zoom: every block moves)
bench = []
for kind, rate in (("testsrc2", "600k"), ("mandelbrot", "1200k")):
path = os.path.join(tmp, "bench_" + kind + ".ogv")
ff(src(kind, 320, 240, 25, 2) + ["-c:v", "libtheora", "-b:v", rate, "-g", "25", path])
bench.append({"name": kind, "file": b64(open(path, "rb").read()), "width": 320, "height": 240})
ctx.emit("theora_bench", bench)