Files
rosetta/src/Rosetta/video/ogv/init.luau
T

394 lines
13 KiB
Luau

--!strict
-- video/ogv: Ogg Theora video (Theora I spec, RFC 3533 / 5334), on containers/Ogg: Theora (granule = keyframe << shift
-- | frames since; the headers Xiph-laced into track.config) and Vorbis / Opus / FLAC streams of the first group. Writes
-- copied Theora + audio. Not supported: chained files, Skeleton / Kate / Speex streams, encoding Theora.
-- ------------------------------------------------------------------------------------------------ requires
local Err = require("@rosetta/core/Err")
local Bytes = require("@rosetta/core/Bytes")
local Types = require("@rosetta/Types")
local Ogg = require("@rosetta/containers/Ogg")
local Demux = require("@rosetta/containers/Demux")
local AudioWrap = require("@rosetta/containers/AudioWrap")
local Theora = require("@rosetta/codecs/video/Theora")
local Video = require("@rosetta/codecs/video/Video")
local Source = require("@rosetta/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?, -- default false: yuv420p
track: number?, -- default: the first video track
audio: boolean?,
maxPixels: number?,
verify: boolean?, -- default true
openAudio: any?, -- set by the api: (demuxer, track) -> audio Decoder
}
export type EncodeOptions = {
audio: boolean?, -- true: fail when the audio cannot be copied (default: dropped)
}
-- ------------------------------------------------------------------------------------------------ constants
local AUDIO = { vorbis = true, opus = true, flac = true }
-- ------------------------------------------------------------------------------------------------ sniff
-- a Theora identification header in a bos page (plain Ogg audio is 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
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
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()
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 }
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
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
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