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:
4DBug committed 2026-10-31 09:31:21 -05:00
1 parent 646d18f056
commit 967703a4d4
13 files changed
+3099 -19

No files matched your search

+260
View File
@@ -0,0 +1,260 @@
--!strict
-- codecs/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given:
-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either
-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM,
-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw
-- yuv420p frames, PCM audio from the audio Decoder). New in formats-luau.
--
-- local streams, err = Source.streams(value, opts, {
-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any)
-- audio = { copy = { opus = true, vorbis = true }, pcm = true },
-- })
-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config,
-- -- track, packets = { { pts, duration (seconds), keyframe, data } } }
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local Yuv = require("@formats/codecs/Yuv")
local Source = {}
export type OutPacket = { pts: number, dts: number?, duration: number, keyframe: boolean, data: buffer }
export type Stream = {
kind: "video" | "audio",
codec: string,
copied: boolean,
width: number?,
height: number?,
frameRate: number?,
sampleRate: number?,
channels: number?,
bitsPerSample: number?,
config: buffer?,
track: Types.Track?,
packets: { OutPacket },
}
export type Want = {
video: { copy: { [string]: boolean }?, encode: string? }?,
audio: { copy: { [string]: boolean }?, pcm: boolean? }?,
}
local function allows(set: { [string]: boolean }?, codec: string): boolean
return set ~= nil and (set[codec] == true or set["*"] == true)
end
-- the packets of a source track, times in seconds
local function copyPackets(dmx: any, track: Types.Track): { OutPacket }
local out = {}
local scale = if track.timescale and track.timescale > 0 then track.timescale else 1
local n = dmx:count(track.id)
for k = 1, n do
local p = dmx:get(track.id, k)
if p then
table.insert(out, { pts = p.pts / scale, dts = (p.dts or p.pts) / scale, duration = (p.duration or 0) / scale, keyframe = p.keyframe, data = p.data })
end
end
return out
end
local function trackStream(track: Types.Track, packets: { OutPacket }): Stream
return {
kind = track.kind :: any,
codec = track.codec,
copied = true,
width = track.width,
height = track.height,
frameRate = track.frameRate,
sampleRate = track.sampleRate,
channels = track.channels,
bitsPerSample = track.bitsPerSample,
config = track.config,
track = track,
packets = packets,
}
end
-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo":
-- yuv420p planes)
local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?)
local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil
if codec ~= "rawvideo" then
local Video = require("@formats/codecs/Video")
local e = Video.entry(codec)
encode = e and e.encode
if not encode then
return nil, Err.new(Err.UNSUPPORTED, "no " .. codec .. " encoder")
end
end
if type(v.reset) == "function" then
v:reset()
end
local packets: { OutPacket } = {}
local w, h = v.width, v.height
local maxFrames = opts.maxFrames or math.huge
while #packets < maxFrames do
local f, err = v:nextFrame()
if not f then
if err then
return nil, err
end
break
end
local img: Types.Image = f.image
if (w == 0 or h == 0) and #packets == 0 then
w, h = img.width, img.height
end
if img.width ~= w or img.height ~= h then
return nil, Err.new(Err.UNSUPPORTED, "frame size changes mid-stream (" .. img.width .. "x" .. img.height .. ")")
end
local data: buffer?
if codec == "rawvideo" then
local y = if img.format == "yuv420p" then img else Yuv.imageFromRgba(img, "limited", "bt601")
if not y then
return nil, Err.new(Err.UNSUPPORTED, "frame format " .. img.format)
end
data = y.pixels
else
local e2
data, e2 = (encode :: any)(img, opts)
if not data then
return nil, e2 or Err.new(Err.ARG, "frame " .. f.index .. " failed to encode")
end
end
table.insert(packets, { pts = f.pts, duration = f.duration, keyframe = true, data = data :: buffer })
end
if #packets == 0 then
return nil, Err.new(Err.ARG, "no frames to write")
end
local fr = v.frameRate
if not fr or fr <= 0 then
local d = packets[1].duration
fr = if d > 0 then 1 / d else 25
end
return {
kind = "video",
codec = codec,
copied = false,
width = w,
height = h,
frameRate = fr,
packets = packets,
} :: Stream, nil
end
-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096)
local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
local ch, rate = dec.channels, dec.sampleRate
if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then
return nil, Err.new(Err.ARG, "audio decoder without channels / sample rate")
end
pcall(dec.seek, dec, 0)
local chunk = opts.audioChunk or 4096
local packets: { OutPacket } = {}
local pos = 0
local tmp: buffer? = nil
while true do
local ok, out, n = pcall(dec.read, dec, chunk, tmp)
if not ok or not out or not n or n <= 0 then
break
end
tmp = out
local data = buffer.create(n * ch * 2)
for i = 0, n * ch - 1 do
local s = buffer.readf32(out, i * 4)
local v = math.floor(s * 32768 + 0.5)
if v > 32767 then
v = 32767
elseif v < -32768 then
v = -32768
elseif v ~= v then
v = 0
end
buffer.writei16(data, i * 2, v)
end
table.insert(packets, { pts = pos / rate, duration = n / rate, keyframe = true, data = data })
pos += n
end
return {
kind = "audio",
codec = "pcm_s16le",
copied = false,
sampleRate = rate,
channels = ch,
bitsPerSample = 16,
packets = packets,
} :: Stream, nil
end
-- streams(value, opts, want) -> { Stream } | nil, Err
function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?)
local o = opts or {}
if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then
return nil, Err.new(Err.ARG, "expected a video (VideoDecoder) or a Demuxer")
end
local dmx = if value.kind == "demuxer" then value else value.demuxer
local out: { Stream } = {}
-- video
local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video"))
local wv = want.video
if wv and o.video ~= false then
if vt and dmx and allows(wv.copy, vt.codec) and not o.reencode then
table.insert(out, trackStream(vt, copyPackets(dmx, vt)))
elseif value.kind == "video" and wv.encode then
local s, err = encodeFrames(value, wv.encode, o)
if not s then
return nil, err
end
table.insert(out, s)
elseif vt then
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)"))
end
end
-- audio
local wa = want.audio
if wa and o.audio ~= false then
local at: Types.Track? = dmx and dmx:track("audio")
if at and dmx and allows(wa.copy, at.codec) and not o.reencodeAudio then
table.insert(out, trackStream(at, copyPackets(dmx, at)))
elseif wa.pcm and value.kind == "video" and value.audio then
local s, err = pcmFrom(value.audio, o)
if not s then
return nil, err
end
if #s.packets > 0 then
table.insert(out, s)
end
elseif at and o.audio == true then
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. at.codec .. " audio to this container")
end
end
if #out == 0 then
return nil, Err.new(Err.ARG, "nothing to write (no video or audio stream)")
end
return out, nil
end
-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its
-- own order
function Source.interleave(streams: { Stream }): { { any } }
local order = {}
local pos = table.create(#streams, 1)
while true do
local best, bt = 0, math.huge
for si, s in streams do
local p = s.packets[pos[si]]
if p then
local t = p.dts or p.pts
if best == 0 or t < bt then
best, bt = si, t
end
end
end
if best == 0 then
break
end
table.insert(order, { best, streams[best].packets[pos[best]] })
pos[best] += 1
end
return order
end
return Source
+425
View File
@@ -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
+191
View File
@@ -0,0 +1,191 @@
--!strict
--!native
--!optimize 2
-- codecs/Yuv: planar 4:2:0 Y'CbCr <-> rgba8 for the video codecs and writers (native; never throws). BT.601 or
-- BT.709 matrices, limited ("tv", 16..235 / 16..240: VP8, MPEG-1, H.264) or full ("pc", 0..255: MJPEG / JPEG) range.
-- yuv -> rgb uses nearest chroma and 16-bit fixed point with swscale's default (non-accurate) coefficients, so the
-- result is within about one level of `ffmpeg -pix_fmt rgba`; rgb -> yuv averages each 2x2 block for the chroma
-- (ffmpeg's default rgb -> yuv420p chroma siting is close to this).
--
-- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255)
-- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2))
-- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image
local Types = require("@formats/Types")
local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32
local bcreate = buffer.create
local floor = math.floor
local Yuv = {}
-- coefficients (x 65536): r = y' + crv * v; g = y' - cgu * u - cgv * v; b = y' + cbu * u
-- limited: y' = (y - 16) * 255 / 219, chroma scaled by 255 / 224
local MATRIX = {
bt601 = { kr = 0.299, kb = 0.114 },
bt709 = { kr = 0.2126, kb = 0.0722 },
}
type Coeffs = { ys: number, yo: number, crv: number, cgu: number, cgv: number, cbu: number, cs: number }
local cache: { [string]: Coeffs } = {}
local function coeffs(range: string?, matrix: string?): Coeffs
local key = (range or "limited") .. (matrix or "bt601")
local c = cache[key]
if c then
return c
end
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
local kr, kb = m.kr, m.kb
local kg = 1 - kr - kb
local full = range == "full"
local ys = if full then 1 else 255 / 219
local cs = if full then 1 else 255 / 224
c = {
ys = floor(ys * 65536 + 0.5),
yo = if full then 0 else 16,
crv = floor(2 * (1 - kr) * cs * 65536 + 0.5),
cbu = floor(2 * (1 - kb) * cs * 65536 + 0.5),
cgu = floor(2 * (1 - kb) * kb / kg * cs * 65536 + 0.5),
cgv = floor(2 * (1 - kr) * kr / kg * cs * 65536 + 0.5),
cs = cs,
}
cache[key] = c
return c
end
-- CLIP[v + 1024] = clamp(v, 0, 255) for v in -1024..1279
local CLIP = bcreate(2304)
for i = 0, 2303 do
writeu8(CLIP, i, math.clamp(i - 1024, 0, 255))
end
-- toRgba(src, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 (w * h * 4) from planes in one buffer: Y at 0 with
-- stride w, U at uo and V at vo with stride cw (ceil(w/2) rows of ceil(h/2))
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer
local dst = out or bcreate(w * h * 4)
local c = coeffs(range, matrix)
local ys, yo, crv, cgu, cgv, cbu = c.ys, c.yo, c.crv, c.cgu, c.cgv, c.cbu
local ch = (h + 1) // 2
if buffer.len(src) < vo + cw * ch or buffer.len(dst) < w * h * 4 or uo + cw * ch > buffer.len(src) then
return dst
end
for y = 0, h - 1 do
local yrow = y * w
local crow = (y // 2) * cw
local o = yrow * 4
for x = 0, w - 1, 2 do
local ci = crow + (x // 2)
local u = readu8(src, uo + ci) - 128
local v = readu8(src, vo + ci) - 128
local rv = (crv * v + 32768) // 65536
local gv = (cgu * u + cgv * v + 32768) // 65536
local bu = (cbu * u + 32768) // 65536
local yy = (ys * (readu8(src, yrow + x) - yo) + 32768) // 65536 + 1024
writeu32(dst, o, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
if x + 1 < w then
yy = (ys * (readu8(src, yrow + x + 1) - yo) + 32768) // 65536 + 1024
writeu32(dst, o + 4, readu8(CLIP, yy + rv) + readu8(CLIP, yy - gv) * 256 + readu8(CLIP, yy + bu) * 65536 + 0xff000000)
end
o += 8
end
end
return dst
end
-- fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p
function Yuv.fromRgba(src: buffer, w: number, h: number, range: string?, matrix: string?, out: buffer?): buffer
local cw, ch = (w + 1) // 2, (h + 1) // 2
local uo, vo = w * h, w * h + cw * ch
local dst = out or bcreate(w * h + 2 * cw * ch)
if buffer.len(src) < w * h * 4 or buffer.len(dst) < w * h + 2 * cw * ch then
return dst
end
local m = MATRIX[matrix or "bt601"] or MATRIX.bt601
local kr, kb = m.kr, m.kb
local kg = 1 - kr - kb
local full = range == "full"
local ysc = if full then 1 else 219 / 255
local csc = if full then 1 else 224 / 255
local yof = if full then 0.5 else 16.5
-- fixed point x 65536
local yr, yg, yb = floor(kr * ysc * 65536 + 0.5), floor(kg * ysc * 65536 + 0.5), floor(kb * ysc * 65536 + 0.5)
local yoff = floor(yof * 65536)
local ur = floor(-kr / (2 * (1 - kb)) * csc * 65536 + 0.5)
local ug = floor(-kg / (2 * (1 - kb)) * csc * 65536 + 0.5)
local ub = floor(0.5 * csc * 65536 + 0.5)
local vr = ub
local vg = floor(-kg / (2 * (1 - kr)) * csc * 65536 + 0.5)
local vb = floor(-kb / (2 * (1 - kr)) * csc * 65536 + 0.5)
local coff4 = floor(128.5 * 65536) * 4
for i = 0, w * h - 1 do
local o = i * 4
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
writeu8(dst, i, readu8(CLIP, (yr * r + yg * g + yb * b + yoff) // 65536 + 1024))
end
for cy = 0, ch - 1 do
local y0 = cy * 2
local y1 = if y0 + 1 < h then y0 + 1 else y0
for cx = 0, cw - 1 do
local x0 = cx * 2
local x1 = if x0 + 1 < w then x0 + 1 else x0
local a, b2, c2, d = (y0 * w + x0) * 4, (y0 * w + x1) * 4, (y1 * w + x0) * 4, (y1 * w + x1) * 4
local r = readu8(src, a) + readu8(src, b2) + readu8(src, c2) + readu8(src, d)
local g = readu8(src, a + 1) + readu8(src, b2 + 1) + readu8(src, c2 + 1) + readu8(src, d + 1)
local b = readu8(src, a + 2) + readu8(src, b2 + 2) + readu8(src, c2 + 2) + readu8(src, d + 2)
local i = cy * cw + cx
writeu8(dst, uo + i, readu8(CLIP, (ur * r + ug * g + ub * b + coff4) // 262144 + 1024))
writeu8(dst, vo + i, readu8(CLIP, (vr * r + vg * g + vb * b + coff4) // 262144 + 1024))
end
end
return dst
end
-- the range / matrix an Image's meta records (meta.yuv = { range, matrix }); limited BT.601 when absent
local function info(img: Types.Image): (string, string)
local y = img.meta and img.meta.yuv
if type(y) == "table" then
return y.range or "limited", y.matrix or "bt601"
end
return "limited", "bt601"
end
Yuv.info = info
-- planes(w, h) -> uo, vo, cw, ch of a yuv420p buffer
function Yuv.planes(w: number, h: number): (number, number, number, number)
local cw, ch = (w + 1) // 2, (h + 1) // 2
return w * h, w * h + cw * ch, cw, ch
end
-- imageToRgba(img) -> an rgba8 Image (yuv420p converted; rgba8 returned as is; nil for other formats)
function Yuv.imageToRgba(img: Types.Image): Types.Image?
if img.format == "rgba8" then
return img
end
if img.format ~= "yuv420p" then
return nil
end
local w, h = img.width, img.height
local uo, vo, cw = Yuv.planes(w, h)
local range, matrix = info(img)
local out = Types.Image.new(w, h, "rgba8")
Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels)
out.meta.source = img.meta.source
return out
end
-- imageFromRgba(img, range?, matrix?) -> a yuv420p Image (meta.yuv records the range / matrix)
function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image?
if img.format == "yuv420p" then
return img
end
if img.format ~= "rgba8" then
return nil
end
local out = Types.Image.new(img.width, img.height, "yuv420p")
Yuv.fromRgba(img.pixels, img.width, img.height, range, matrix, out.pixels)
out.meta.yuv = { range = range or "limited", matrix = matrix or "bt601" }
out.meta.source = img.meta.source
return out
end
return Yuv