ws-video: MJPEG (codecs/Jpeg, yuv420p full range; encoder remaps limited-range frames) and MPEG-1 (codecs/Mpeg1, display reordering with the packet pts as tag) in the codec registry; VideoFrame times count from the demuxer's startTime (TS starts at 1.4 s); Matroska Vorbis keeps its codec delay; fixtures decode with -fps_mode passthrough

This commit is contained in:
4DBug committed 2026-10-31 09:57:26 -05:00
1 parent dac404aa52
commit 1cd0fdfc24
9 files changed
+136 -11

No files matched your search

+3 -2
View File
@@ -205,6 +205,7 @@ export type Demuxer = {
format: string, -- the container format name
tracks: { Track },
duration: number, -- seconds (0 = unknown)
startTime: number, -- seconds: the first video / audio packet's presentation time (VideoFrame times count from it)
meta: { [string]: any }, -- title, tags, ...
-- packets(trackId?) -> iterator of Packets in file order (one track, or all), from the current position
packets: (self: any, track: number?) -> () -> Packet?,
@@ -216,7 +217,7 @@ export type Demuxer = {
}
export type VideoFrame = {
image: Image, -- yuv420p (the codecs' native output) or rgba8 (opts.rgba = true, MJPEG without yuv, frames-backed)
pts: number, -- seconds
pts: number, -- seconds from the start of the stream (the demuxer's startTime)
duration: number, -- seconds
keyframe: boolean?,
index: number, -- 1-based, in output order
@@ -233,7 +234,7 @@ export type VideoDecoder = {
track: Track?, -- the video track decoded
nextFrame: (self: any) -> (VideoFrame?, Err?), -- nil, nil at the end
toRGBA: (self: any, frame: VideoFrame | Image) -> Image, -- an rgba8 Image (the frame's own image if already rgba8)
seek: (self: any, seconds: number) -> (), -- to the last keyframe at or before the time (frames before it skipped)
seek: (self: any, seconds: number) -> (), -- the next frame is the first at or after the time (decoded from the keyframe before it)
reset: (self: any) -> (), -- back to the start
audio: Decoder?, -- the first audio track, decoded (nil if none or its codec is unavailable: see audioError)
audioError: Err?,
+80 -4
View File
@@ -213,12 +213,86 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec
end)
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 = { 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)
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
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
-- ------------------------------------------------------------------------------------------------ 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 = "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" } },
@@ -371,6 +445,8 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
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 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?)
@@ -381,7 +457,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
while true do
local img, pts, key = dec:receive()
if img then
local t = (pts or 0) / scale
local t = (pts or 0) / scale - start
if t + 1e-9 >= skipUntil then
index += 1
local d = defaultDur
@@ -412,7 +488,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
end
end
function v.seek(self: any, seconds: number)
demuxer:seek(seconds)
demuxer:seek(seconds + start)
if codec then
codec:reset()
end
+35 -1
View File
@@ -142,10 +142,15 @@ 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
local m = img.meta
local y = m and m.yuv
if type(y) == "table" then
return y.range or "limited", y.matrix or "bt601"
end
local src = m and m.source
if type(src) == "table" and src.range == "full" then
return "full", "bt601"
end
return "limited", "bt601"
end
Yuv.info = info
@@ -156,6 +161,35 @@ function Yuv.planes(w: number, h: number): (number, number, number, number)
return w * h, w * h + cw * ch, cw, ch
end
-- FULL_Y / FULL_C: limited -> full range sample maps
local FULL_Y = bcreate(256)
local FULL_C = bcreate(256)
for v = 0, 255 do
writeu8(FULL_Y, v, math.clamp(floor((v - 16) * 255 / 219 + 0.5), 0, 255))
writeu8(FULL_C, v, math.clamp(floor((v - 128) * 255 / 224 + 128.5), 0, 255))
end
-- toFullRange(img) -> a yuv420p Image in full range (a limited-range one remapped; a full-range one returned)
function Yuv.toFullRange(img: Types.Image): Types.Image
if img.format ~= "yuv420p" or info(img) == "full" then
return img
end
local w, h = img.width, img.height
local out = Types.Image.new(w, h, "yuv420p")
local src, dst = img.pixels, out.pixels
local ny = w * h
local n = math.min(buffer.len(src), buffer.len(dst))
for i = 0, math.min(ny, n) - 1 do
writeu8(dst, i, readu8(FULL_Y, readu8(src, i)))
end
for i = ny, n - 1 do
writeu8(dst, i, readu8(FULL_C, readu8(src, i)))
end
out.meta.yuv = { range = "full", matrix = select(2, info(img)) }
out.meta.source = img.meta.source
return out
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
+3 -1
View File
@@ -442,7 +442,9 @@ function AudioWrap.wrap(dmx: any, track: Types.Track): (buffer?, string?, Err.Er
end
local m = if mb > 0 and buffer.len(d) * 8 > mb then bits(d, 1, mb) else 0
local cur = sizes[if modes[m + 1] then 2 else 1]
granule += ((prev or cur) + cur) // 4 -- the first packet counts as if after a block of its own size (ffmpeg)
if prev then
granule += (prev + cur) // 4
end
prev = cur
return granule
end)
+9
View File
@@ -22,6 +22,7 @@ export type Demux = typeof(setmetatable(
format: string,
tracks: { Types.Track },
duration: number,
startTime: number,
meta: { [string]: any },
src: buffer,
n: number,
@@ -48,6 +49,7 @@ function Demux.new(format: string, tracks: { Types.Track }, src: buffer, meta: {
format = format,
tracks = tracks,
duration = 0,
startTime = 0,
meta = meta or {},
src = src,
n = 0,
@@ -110,6 +112,7 @@ function D.finish(self: Demux)
end
self.byTrack = byTrack
local total = self.duration
local start = math.huge
for _, t in self.tracks do
local list = byTrack[t.id]
local scale = if t.timescale and t.timescale > 0 then t.timescale else 1
@@ -135,6 +138,9 @@ function D.finish(self: Demux)
end
end
local first, last = order[1], order[#order]
if t.kind == "video" or t.kind == "audio" then
start = math.min(start, self.pts[first] / scale)
end
local d = (self.pts[last] + self.dur[last] - math.min(0, self.pts[first])) / scale
if not t.duration or t.duration <= 0 then
t.duration = d
@@ -147,6 +153,9 @@ function D.finish(self: Demux)
self.cur[t.id] = 1
end
self.duration = total
-- the presentation time of the first video / audio packet (MPEG-TS streams start at ~1.4 s): VideoDecoders count
-- frame times from it
self.startTime = if start ~= math.huge and start > 0 then start else 0
end
-- the Packet for index entry i (a copy of its bytes)
+3 -1
View File
@@ -269,7 +269,9 @@ local function openAudio(demuxer: any, track: any): (any, Err.Err?)
return nil, err
end
local dec, oerr = F.open(buf, { format = fmt, category = "audio" })
if dec and fmt ~= "opus" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
-- Matroska CodecDelay: ffmpeg drops it for MPEG audio / AAC; Opus has its own pre-skip and Vorbis's delay is
-- already the decoder's own (its first packet returns nothing)
if dec and fmt ~= "opus" and fmt ~= "vorbis" and type(track.codecDelay) == "number" and track.codecDelay > 0 then
dec = AudioWrap.trim(dec, math.floor(track.codecDelay * dec.sampleRate + 0.5))
end
return dec, oerr
+1
View File
@@ -773,6 +773,7 @@ do
end
realtime("tracker 32 ch (mod)", song("mod", false), 32)
realtime("tracker 32 ch + NNA, filters", song("it", true), 64)
end
-- ------------------------------------------------------------------------------------------- ws-video-codecs: fps
do
local Jpeg = require("@formats/codecs/Jpeg")
+1 -1
View File
@@ -62,7 +62,7 @@ def yuv_frames(path, w, h, extra=None, codec=None):
"""the first video stream decoded by ffmpeg to yuv420p (yuvj420p for MJPEG: full range, no conversion): a list of
frame bytes"""
pix = "yuvj420p" if codec == "mjpeg" else "yuv420p"
raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", pix, "-"])
raw = ffmpeg(["-i", path] + (extra or []) + ["-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", pix, "-"])
n = w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
return [raw[i:i + n] for i in range(0, len(raw) - n + 1, n)]
+1 -1
View File
@@ -115,7 +115,7 @@ def case(tmp, name, rgba=False, raw_frames=2, pcm_frames=8192):
if vs:
w, h = vs[0]["width"], vs[0]["height"]
if rgba:
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
raw = V.ffmpeg(["-i", path, "-map", "0:v:0", "-fps_mode", "passthrough", "-f", "rawvideo", "-pix_fmt", "rgba", "-"])
n = w * h * 4
c["rgba"] = [V.crc(raw[i:i + n]) for i in range(0, len(raw) - n + 1, n)]
else: