ws-video: video foundation: Types video section made concrete (Track / Packet / Demuxer / VideoFrame / VideoDecoder / VideoCodecDecoder), codecs/Video (codec registry by id / FourCC / Matroska id, generic VideoDecoder over a Demuxer, frames-backed videos, Source for writers), codecs/Yuv, containers/Demux (indexed demuxer), containers/Ebml, containers/AudioWrap; video/mkv (Matroska / WebM demux + mux, WIP: tests next)
api (init.luau, small, backward compatible): KIND_CATEGORY.video; withHooks adds opts.openAudio (audio tracks of video containers reach the audio formats through AudioWrap); F.load of a video format returns its VideoDecoder instead of draining it as audio; F.open passes the hooks and opens animated images as frames-backed videos (F.video.open(gif)); F.save of an Image to a video format wraps it (F.convert(gif, 'avi')); F.video.fromImage, F.video.codecs.
This commit is contained in:
1 parent
646d18f056
commit
967703a4d4
13 files changed
+3099
-19
No files matched your search
@@ -0,0 +1,425 @@
|
||||
--!strict
|
||||
-- codecs/Video: the video codec registry and the generic VideoDecoder. New in formats-luau.
|
||||
--
|
||||
-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them
|
||||
-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a
|
||||
-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc /
|
||||
-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs
|
||||
-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry).
|
||||
--
|
||||
-- local Video = require("@formats/codecs/Video")
|
||||
-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8"
|
||||
-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder)
|
||||
-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open())
|
||||
-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP)
|
||||
--
|
||||
-- Never throws: bad data / missing codecs come back as nil, Err.
|
||||
local Err = require("@formats/core/Err")
|
||||
local Types = require("@formats/Types")
|
||||
local Yuv = require("@formats/codecs/Yuv")
|
||||
|
||||
local Video = {}
|
||||
|
||||
export type Entry = {
|
||||
id: string, -- our codec id
|
||||
name: string, -- a human name
|
||||
fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs
|
||||
matroska: { string }?, -- Matroska / WebM CodecIDs
|
||||
-- new(track, opts) -> a decoder instance (nil = decode not supported)
|
||||
new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?,
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ simple decoders
|
||||
-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no
|
||||
-- picture to show, such as a hidden VP8 altref frame)
|
||||
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
|
||||
local queue: { any } = {}
|
||||
local self = {}
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
local ok, img, err = pcall(decodeOne, packet.data, packet)
|
||||
if not ok then
|
||||
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img))
|
||||
end
|
||||
if img then
|
||||
table.insert(queue, { img, packet.pts, packet.keyframe })
|
||||
end
|
||||
return err
|
||||
end
|
||||
function self.receive(_: any): (Types.Image?, number?, boolean?)
|
||||
local q = table.remove(queue, 1)
|
||||
if q then
|
||||
return q[1], q[2], q[3]
|
||||
end
|
||||
return nil
|
||||
end
|
||||
function self.flush(_: any) end
|
||||
function self.reset(_: any)
|
||||
table.clear(queue)
|
||||
if resetFn then
|
||||
resetFn()
|
||||
end
|
||||
end
|
||||
return self :: any
|
||||
end
|
||||
|
||||
-- raw video: yuv420p (I420 / IYUV / y4m), yv12 (V before U), rgb24 / bgr24 / bgra (bottom-up AVI DIBs: track.flip)
|
||||
local function rawDecoder(track: Types.Track, _opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local w, h = track.width or 0, track.height or 0
|
||||
if w <= 0 or h <= 0 or w * h > 2 ^ 26 then
|
||||
return nil, Err.new(Err.CORRUPT, "raw video without a valid size")
|
||||
end
|
||||
local pf = track.pixelFormat or "yuv420p"
|
||||
local cw, ch = (w + 1) // 2, (h + 1) // 2
|
||||
local flip = track.flip == true
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local n = buffer.len(data)
|
||||
if pf == "yuv420p" or pf == "yv12" then
|
||||
local need = w * h + 2 * cw * ch
|
||||
if n < need then
|
||||
return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes")
|
||||
end
|
||||
local img = Types.Image.new(w, h, "yuv420p")
|
||||
if pf == "yv12" then
|
||||
buffer.copy(img.pixels, 0, data, 0, w * h)
|
||||
buffer.copy(img.pixels, w * h, data, w * h + cw * ch, cw * ch)
|
||||
buffer.copy(img.pixels, w * h + cw * ch, data, w * h, cw * ch)
|
||||
else
|
||||
buffer.copy(img.pixels, 0, data, 0, need)
|
||||
end
|
||||
return img
|
||||
end
|
||||
local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3
|
||||
local stride = if track.stride then track.stride else w * bpp
|
||||
if n < stride * (h - 1) + w * bpp then
|
||||
return nil, Err.new(Err.TRUNCATED, "raw frame too short")
|
||||
end
|
||||
local img = Types.Image.new(w, h, "rgba8")
|
||||
local px = img.pixels
|
||||
local bgr = pf == "bgr24" or pf == "bgra"
|
||||
for y = 0, h - 1 do
|
||||
local s = (if flip then h - 1 - y else y) * stride
|
||||
local o = y * w * 4
|
||||
for x = 0, w - 1 do
|
||||
local p = s + x * bpp
|
||||
local a, b, c = buffer.readu8(data, p), buffer.readu8(data, p + 1), buffer.readu8(data, p + 2)
|
||||
if bgr then
|
||||
a, c = c, a
|
||||
end
|
||||
buffer.writeu32(px, o + x * 4, a + b * 256 + c * 65536 + 0xff000000)
|
||||
end
|
||||
end
|
||||
return img
|
||||
end)
|
||||
end
|
||||
|
||||
local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Vp8 = require("@formats/codecs/Vp8")
|
||||
local dec = Vp8.newDecoder()
|
||||
local o = { maxPixels = opts and opts.maxPixels }
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local img, err = dec:decodeFrame(data, 0, buffer.len(data), o)
|
||||
if not img then
|
||||
return nil, err
|
||||
end
|
||||
local src = img.meta.source
|
||||
if type(src) == "table" and src.show == false then
|
||||
return nil, nil
|
||||
end
|
||||
img.meta.yuv = { range = "limited", matrix = "bt601" }
|
||||
return img, nil
|
||||
end, function()
|
||||
if dec.reset then
|
||||
dec:reset()
|
||||
else
|
||||
dec = Vp8.newDecoder()
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ registry
|
||||
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
|
||||
local BUILTIN: { Entry } = {
|
||||
{ id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder },
|
||||
{ id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" } },
|
||||
{ id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" } },
|
||||
{ id = "rawvideo", name = "raw video", fourcc = { "\0\0\0\0", "I420", "IYUV", "YV12", "raw ", "DIB " }, matroska = { "V_UNCOMPRESSED" }, new = rawDecoder },
|
||||
{ id = "mpeg2", name = "MPEG-2 video", fourcc = { "mpg2", "MPG2", "MPEG", "mp2v" }, matroska = { "V_MPEG2" } },
|
||||
{ id = "mpeg4", name = "MPEG-4 part 2", fourcc = { "mp4v", "FMP4", "XVID", "DIVX", "DX50", "MP4V" }, matroska = { "V_MPEG4/ISO/SP", "V_MPEG4/ISO/ASP", "V_MPEG4/ISO/AP" } },
|
||||
{ id = "h264", name = "H.264 / AVC", fourcc = { "avc1", "avc3", "H264", "h264", "X264", "x264" }, matroska = { "V_MPEG4/ISO/AVC" } },
|
||||
{ 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 = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
|
||||
}
|
||||
|
||||
local byId: { [string]: Entry } = {}
|
||||
local byFourcc: { [string]: string } = {}
|
||||
local byMatroska: { [string]: string } = {}
|
||||
|
||||
-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it
|
||||
function Video.register(entry: Entry): (boolean, Err.Err?)
|
||||
if type(entry) ~= "table" or type(entry.id) ~= "string" then
|
||||
return false, Err.new(Err.ARG, "register: needs an entry with an id")
|
||||
end
|
||||
local old = byId[entry.id]
|
||||
if old and entry.new == nil then
|
||||
entry.new = old.new
|
||||
end
|
||||
byId[entry.id] = entry
|
||||
for _, f in entry.fourcc or {} do
|
||||
byFourcc[f] = entry.id
|
||||
end
|
||||
for _, m in entry.matroska or {} do
|
||||
byMatroska[m] = entry.id
|
||||
end
|
||||
return true
|
||||
end
|
||||
for _, e in BUILTIN do
|
||||
Video.register(e)
|
||||
end
|
||||
|
||||
-- the registry (read only by convention): id -> Entry
|
||||
Video.codecs = byId
|
||||
|
||||
-- fromFourcc(fourcc) -> codec id | nil
|
||||
function Video.fromFourcc(fcc: string): string?
|
||||
return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)]
|
||||
end
|
||||
|
||||
-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...)
|
||||
function Video.fromMatroska(id: string): string?
|
||||
return byMatroska[id]
|
||||
end
|
||||
|
||||
-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil
|
||||
function Video.entry(id: string): Entry?
|
||||
return byId[id]
|
||||
end
|
||||
|
||||
-- canDecode(codecId) -> boolean
|
||||
function Video.canDecode(id: string): boolean
|
||||
local e = byId[id]
|
||||
return e ~= nil and e.new ~= nil
|
||||
end
|
||||
|
||||
-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered)
|
||||
function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local e = byId[track.codec]
|
||||
if not e or not e.new then
|
||||
return nil, Err.new(Err.UNSUPPORTED, "no decoder for video codec " .. tostring(track.codec))
|
||||
end
|
||||
local ok, dec, err = pcall(e.new :: any, track, opts)
|
||||
if not ok then
|
||||
return nil, Err.new(Err.CORRUPT, "codec " .. track.codec .. " failed to start: " .. tostring(dec))
|
||||
end
|
||||
return dec, err
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ VideoDecoder
|
||||
local function toRGBA(_self: any, f: any): Types.Image
|
||||
local img = if type(f) == "table" and f.image then f.image else f
|
||||
local out = Yuv.imageToRgba(img)
|
||||
return out or img
|
||||
end
|
||||
|
||||
export type OpenOptions = {
|
||||
rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p)
|
||||
track: number?, -- the video track id (default: the first video track)
|
||||
maxPixels: number?,
|
||||
openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook
|
||||
audio: boolean?, -- false: do not open the audio track
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through
|
||||
-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and
|
||||
-- the demuxer (remuxing) and audio work.
|
||||
function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
|
||||
local o: OpenOptions = opts or {}
|
||||
local track: Types.Track? = nil
|
||||
if o.track then
|
||||
for _, t in demuxer.tracks do
|
||||
if t.id == o.track then
|
||||
track = t
|
||||
end
|
||||
end
|
||||
if not track then
|
||||
return nil, Err.new(Err.ARG, "no track " .. tostring(o.track))
|
||||
end
|
||||
else
|
||||
track = demuxer:track("video")
|
||||
end
|
||||
local codec: Types.VideoCodecDecoder? = nil
|
||||
local codecErr: Err.Err? = nil
|
||||
if track then
|
||||
codec, codecErr = Video.decoder(track, o)
|
||||
else
|
||||
codecErr = Err.new(Err.UNSUPPORTED, "no video track")
|
||||
end
|
||||
local v: any = {
|
||||
kind = "video",
|
||||
format = demuxer.format,
|
||||
codec = if track then track.codec else "none",
|
||||
width = if track then track.width or 0 else 0,
|
||||
height = if track then track.height or 0 else 0,
|
||||
frameRate = if track then track.frameRate or 0 else 0,
|
||||
frames = if track then track.frames or 0 else 0,
|
||||
duration = if track and track.duration and track.duration > 0 then track.duration else demuxer.duration,
|
||||
track = track,
|
||||
demuxer = demuxer,
|
||||
meta = demuxer.meta or {},
|
||||
decodeError = codecErr,
|
||||
toRGBA = toRGBA,
|
||||
}
|
||||
if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then
|
||||
v.frames = math.floor(v.duration * v.frameRate + 0.5)
|
||||
end
|
||||
-- audio
|
||||
if o.audio ~= false then
|
||||
local at = demuxer:track("audio")
|
||||
if at then
|
||||
if o.openAudio then
|
||||
local ok, dec, err = pcall(o.openAudio, demuxer, at)
|
||||
if ok and dec then
|
||||
v.audio = dec
|
||||
else
|
||||
v.audioError = if ok then err else Err.new(Err.CORRUPT, "audio: " .. tostring(dec))
|
||||
end
|
||||
else
|
||||
v.audioError = Err.new(Err.UNSUPPORTED, "no audio hook (open through the api: F.video.open)")
|
||||
end
|
||||
end
|
||||
end
|
||||
local index, flushed, skipUntil = 0, false, -math.huge
|
||||
local tid = if track then track.id else -1
|
||||
local scale = if track and track.timescale and track.timescale > 0 then track.timescale else 1000
|
||||
local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0
|
||||
local lastPts = nil :: number?
|
||||
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
|
||||
if not codec then
|
||||
return nil, codecErr
|
||||
end
|
||||
local dec = codec :: Types.VideoCodecDecoder
|
||||
while true do
|
||||
local img, pts, key = dec:receive()
|
||||
if img then
|
||||
local t = (pts or 0) / scale
|
||||
if t + 1e-9 >= skipUntil then
|
||||
index += 1
|
||||
local d = defaultDur
|
||||
if lastPts and t > lastPts and defaultDur == 0 then
|
||||
d = t - lastPts
|
||||
end
|
||||
lastPts = t
|
||||
if o.rgba then
|
||||
img = Yuv.imageToRgba(img) or img
|
||||
end
|
||||
return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil
|
||||
end
|
||||
else
|
||||
local p = demuxer:read(tid)
|
||||
if p == nil then
|
||||
if flushed then
|
||||
return nil, nil
|
||||
end
|
||||
flushed = true
|
||||
dec:flush()
|
||||
else
|
||||
local err = dec:decode(p)
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
function v.seek(self: any, seconds: number)
|
||||
demuxer:seek(seconds)
|
||||
if codec then
|
||||
codec:reset()
|
||||
end
|
||||
flushed = false
|
||||
skipUntil = seconds
|
||||
lastPts = nil
|
||||
if self.audio then
|
||||
pcall(self.audio.seek, self.audio, seconds)
|
||||
end
|
||||
end
|
||||
function v.reset(self: any)
|
||||
self:seek(0)
|
||||
skipUntil = -math.huge
|
||||
index = 0
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ frames-backed
|
||||
-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after
|
||||
-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded.
|
||||
function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?)
|
||||
if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then
|
||||
return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images")
|
||||
end
|
||||
local w, h = images[1].width, images[1].height
|
||||
local pts: { number } = {}
|
||||
local durs: { number } = {}
|
||||
local t = 0
|
||||
for i, img in images do
|
||||
if type(img) ~= "table" or img.width ~= w or img.height ~= h then
|
||||
return nil, Err.new(Err.ARG, "fromFrames: frame " .. i .. " is not a " .. w .. "x" .. h .. " Image")
|
||||
end
|
||||
local d = if type(delays) == "table" then delays[i] or 0.1 else (delays or 0.1)
|
||||
if type(d) ~= "number" or d ~= d or d < 0 then
|
||||
d = 0.1
|
||||
end
|
||||
pts[i] = t
|
||||
durs[i] = d
|
||||
t += d
|
||||
end
|
||||
local n = #images
|
||||
local o = opts or {}
|
||||
local v: any = {
|
||||
kind = "video",
|
||||
format = o.format or "frames",
|
||||
codec = "frames",
|
||||
width = w,
|
||||
height = h,
|
||||
frameRate = if t > 0 then n / t else 10,
|
||||
frames = n,
|
||||
duration = t,
|
||||
loops = o.loops,
|
||||
meta = o.meta or {},
|
||||
toRGBA = toRGBA,
|
||||
images = images,
|
||||
}
|
||||
local i = 0
|
||||
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
|
||||
i += 1
|
||||
if i > n then
|
||||
i = n
|
||||
return nil, nil
|
||||
end
|
||||
local img = images[i]
|
||||
if o.rgba then
|
||||
img = Yuv.imageToRgba(img) or img
|
||||
end
|
||||
return { image = img, pts = pts[i], duration = durs[i], keyframe = true, index = i }, nil
|
||||
end
|
||||
function v.seek(self: any, seconds: number)
|
||||
local k = 0
|
||||
for j = 1, n do
|
||||
if pts[j] <= seconds + 1e-9 then
|
||||
k = j - 1
|
||||
end
|
||||
end
|
||||
i = k
|
||||
end
|
||||
function v.reset(self: any)
|
||||
i = 0
|
||||
end
|
||||
return v, nil
|
||||
end
|
||||
|
||||
return Video
|
||||
Reference in new issue
Block a user