ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically): - codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder; codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url; codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err Crc32 Adler32 Base64 Md5 Input Sniff. - LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md). - Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes. C3, generic code out of format folders: - containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first, trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64 through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it. - codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position, priming and end trimming) that aac, caf and m4a each carried (~70 lines each). - codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of its own (the AND mask / alpha rule stay ICO's). - codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model), Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the fixtures' bind shapes). - README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes: FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
1 parent
9c553b9d1a
commit
434a304315
283 files changed
+1877
-1660
No files matched your search
@@ -0,0 +1,305 @@
|
||||
--!strict
|
||||
-- codecs/video/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/image/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/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
|
||||
|
||||
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
|
||||
function Source.rational(fps: number): (number, number)
|
||||
if fps ~= fps or fps <= 0 then
|
||||
return 25, 1
|
||||
end
|
||||
if math.abs(fps - math.floor(fps + 0.5)) < 1e-6 then
|
||||
return math.floor(fps + 0.5), 1
|
||||
end
|
||||
local ntsc = fps * 1001 / 1000
|
||||
if math.abs(ntsc - math.floor(ntsc + 0.5)) < 1e-4 then
|
||||
return math.floor(ntsc + 0.5) * 1000, 1001
|
||||
end
|
||||
return math.floor(fps * 1000 + 0.5), 1000
|
||||
end
|
||||
|
||||
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
|
||||
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
|
||||
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
|
||||
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
|
||||
local fd = math.huge
|
||||
for _, p in s.packets do
|
||||
if p.duration and p.duration > 0 and p.duration < fd then
|
||||
fd = p.duration
|
||||
end
|
||||
end
|
||||
if fd == math.huge then
|
||||
fd = if s.frameRate and s.frameRate > 0 then 1 / s.frameRate else 0.04
|
||||
end
|
||||
fd = math.max(fd, 1 / (maxFps or 100))
|
||||
local num, den = Source.rational(1 / fd)
|
||||
local step = den / num
|
||||
local out: { OutPacket } = {}
|
||||
local slots = 0
|
||||
local t0 = if s.packets[1] then s.packets[1].pts else 0
|
||||
for _, p in s.packets do
|
||||
local stop = p.pts - t0 + (if p.duration and p.duration > 0 then p.duration else step)
|
||||
local n = math.max(1, math.floor(stop / step + 0.5) - slots)
|
||||
for _ = 1, n do
|
||||
table.insert(out, { pts = t0 + slots * step, duration = step, keyframe = p.keyframe, data = p.data })
|
||||
slots += 1
|
||||
end
|
||||
end
|
||||
return num, den, out
|
||||
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
|
||||
@@ -0,0 +1,584 @@
|
||||
--!strict
|
||||
-- codecs/video/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")
|
||||
-- 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/image/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/image/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/image/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/image/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/video/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/video/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/video/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
|
||||
Reference in new issue
Block a user