--!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, nil, 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), yuv422p / yuv444p / yuva444p / gray (chroma averaged -- down to 4:2:0, alpha dropped), track.bitDepth 9..16 (little-endian 16-bit samples scaled to 8 bits), rgb24 / bgr24 / -- bgra / rgba (AVI DIBs: track.flip = bottom-up rows, track.stride = padded rows) local function rawPlanar(data: buffer, pf: string, bits: number, w: number, h: number): Types.Image local img = Types.Image.new(w, h, "yuv420p") local px = img.pixels local cw, ch = (w + 1) // 2, (h + 1) // 2 local bps = if bits > 8 then 2 else 1 local shift = 2 ^ (bits - 8) local function sample(o: number): number if bps == 1 then return buffer.readu8(data, o) end return math.min(255, buffer.readu16(data, o) // shift) end for i = 0, w * h - 1 do buffer.writeu8(px, i, sample(i * bps)) end local scw, sch = w, h -- source chroma plane size if pf == "yuv420p" then scw, sch = cw, ch elseif pf == "yuv422p" then scw, sch = cw, h end local uo, vo = w * h * bps, (w * h + scw * sch) * bps for cy = 0, ch - 1 do for cx = 0, cw - 1 do local i = cy * cw + cx local u, v if pf == "gray" then u, v = 128, 128 elseif pf == "yuv420p" then u, v = sample(uo + i * bps), sample(vo + i * bps) :: number elseif pf == "yuv422p" then local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) u = (sample(uo + (y0 * scw + cx) * bps) + sample(uo + (y1 * scw + cx) * bps) + 1) // 2 v = (sample(vo + (y0 * scw + cx) * bps) + sample(vo + (y1 * scw + cx) * bps) + 1) // 2 else local x0, x1 = cx * 2, math.min(cx * 2 + 1, w - 1) local y0, y1 = cy * 2, math.min(cy * 2 + 1, h - 1) local a, b, c, d = (y0 * w + x0) * bps, (y0 * w + x1) * bps, (y1 * w + x0) * bps, (y1 * w + x1) * bps u = (sample(uo + a) + sample(uo + b) + sample(uo + c) + sample(uo + d) + 2) // 4 v = (sample(vo + a) + sample(vo + b) + sample(vo + c) + sample(vo + d) + 2) // 4 end buffer.writeu8(px, w * h + i, u) buffer.writeu8(px, w * h + cw * ch + i, v) end end return img end local PLANAR_SIZE: { [string]: (w: number, h: number, cw: number, ch: number) -> number } = { yuv420p = function(w, h, cw, ch) return w * h + 2 * cw * ch end, yv12 = function(w, h, cw, ch) return w * h + 2 * cw * ch end, yuv422p = function(w, h, cw, _ch) return w * h + 2 * cw * h end, yuv444p = function(w, h) return w * h * 3 end, yuva444p = function(w, h) return w * h * 4 end, gray = function(w, h) return w * h end, } 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 bits = track.bitDepth or 8 local cw, ch = (w + 1) // 2, (h + 1) // 2 local flip = track.flip == true local planar = PLANAR_SIZE[pf] return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) local n = buffer.len(data) if planar then local need = planar(w, h, cw, ch) * (if bits > 8 then 2 else 1) if n < need then return nil, Err.new(Err.TRUNCATED, "raw frame: " .. n .. " of " .. need .. " bytes") end if pf == "yuv420p" and bits == 8 then local img = Types.Image.new(w, h, "yuv420p") buffer.copy(img.pixels, 0, data, 0, need) return img, nil elseif pf == "yv12" then local img = Types.Image.new(w, h, "yuv420p") 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) return img, nil end return rawPlanar(data, pf, bits, w, h), nil end local bpp = if pf == "bgra" or pf == "rgba" then 4 else 3 local stride: number = track.stride or 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, nil end), nil 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), nil end -- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout -- allows, else rgba8 local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Jpeg = require("@formats/codecs/Jpeg") local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?) local img, err = Jpeg.decode(data, 0, buffer.len(data), o) if img and img.format == "yuv420p" then img.meta.yuv = { range = "full", matrix = "bt601" } end return img, err end), nil end -- the MJPEG encoder (writers): JPEG is full-range, so limited-range yuv420p frames are remapped first local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?) local Jpeg = require("@formats/codecs/Jpeg") local src = img if img.format == "yuv420p" then local range = Yuv.info(img) if range ~= "full" then src = Yuv.toFullRange(img) end end return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) end -- MPEG-1 video: pictures in decode order, reordered for display (the packet's pts travels with its picture) local function mpeg1Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local Mpeg1 = require("@formats/codecs/Mpeg1") local dec = Mpeg1.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels }) local queue: { any } = {} local function push(f: any) local img = Mpeg1.frameImage(f) if img then img.meta.yuv = { range = "limited", matrix = "bt601" } local tag = f.tag table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 }) end end local self = {} function self.decode(_: any, packet: Types.Packet): Err.Err? local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), { packet.pts }) if not ok then return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) end if f then push(f) end return nil 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, nil, nil end function self.flush(_: any) for _ = 1, 4 do local f = dec:flush() if not f then break end push(f) end end function self.reset(_: any) dec:reset() table.clear(queue) end return self :: any, nil end -- H.264 / AVC (codecs/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264); -- pictures in display order with the pts of their packet local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local H264 = require("@formats/codecs/H264") return H264.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 } = { { 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" }, new = mjpegDecoder, encode = mjpegEncode }, { id = "mpeg1", name = "MPEG-1 video", fourcc = { "mpg1", "MPG1", "PIM1", "m1v " }, matroska = { "V_MPEG1" }, new = mpeg1Decoder }, { 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", "AVC1", "DAVC", "VSSH" }, matroska = { "V_MPEG4/ISO/AVC" }, new = h264Decoder }, { 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, nil 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: number = if track and track.timescale and track.timescale > 0 then track.timescale else 1000 local start = demuxer.startTime or 0 v.startTime = start 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 - start if t + 1e-9 >= skipUntil then index += 1 local d = defaultDur if lastPts and t > (lastPts :: number) and defaultDur == 0 then d = t - (lastPts :: number) 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 + start) 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