codecs/video: comments to specs only

This commit is contained in:
4DBug committed 2026-11-01 01:54:40 -05:00
1 parent 0bd7b87d2b
commit 8e78869f0e
36 files changed
+219 -809

No files matched your search

+13 -57
View File
@@ -1,32 +1,8 @@
--!strict
-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau. A codec (layer 1): the
-- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the
-- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the
-- reference decoder (checked against ffmpeg per frame).
-- Supports: Annex B and AVCC (length-prefixed, with avcC extradata) input; SPS / PPS / slices; CAVLC and CABAC; I, P and
-- B slices; every intra mode (4x4, 8x8, 16x16, chroma), quarter-sample luma / eighth-sample chroma motion
-- compensation, explicit and implicit weighted prediction, direct spatial and temporal prediction; the 4x4 and 8x8
-- transforms with scaling matrices; the deblocking filter; multiple reference frames, long-term references, MMCO and
-- the sliding window, frame_num gaps; POC types 0 / 1 / 2 and output reordering; 8-bit 4:2:0 Constrained Baseline,
-- Main, Extended-without-SP/data-partitioning and High profiles; cropping. Corrupt slices are skipped and their
-- macroblocks concealed (copied from the latest reference picture).
-- Not supported (UNSUPPORTED): interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4, bit depths above 8,
-- lossless (transform bypass), FMO / ASO slice groups, SP / SI slices, data partitioning, SVC / MVC enhancement layers
-- (their NAL units are ignored).
--
-- local H264 = require("@rosetta/codecs/video/H264")
-- local dec = H264.newDecoder() -- or { avcC = buffer } for MP4 samples (length-prefixed)
-- for _, au in accessUnits do
-- local frames, err = dec:decode(au, pts) -- frames: { { image (yuv420p Types.Image), pts, poc, keyframe } }
-- end
-- local rest = dec:flush() -- the frames still held for reordering
--
-- Speed (one Zen 5 core, tools/bench.luau, libx264 crf 23 clips): Luau --codegen ~220-425 fps at 320x240 and ~75-135
-- fps at 640x360; LuaJIT with the api's trace limits (host/init.luau) about the same or faster, but with LuaJIT's default
-- limits (maxtrace=1000) the trace cache thrashes and it drops to ~30-190 fps. Real-time is comfortable at 320x240 and
-- feasible at 640x360 for typical bitrates; high-bitrate CIF conformance streams run ~100-150 fps (Luau).
-- Never throws: bad data returns nil, Err (core/Err codes ARG / UNSUPPORTED / LIMIT), or frames with the bad slices
-- concealed (dec.errors counts them, dec.lastError says why).
-- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg.
-- Clean-room from the spec; constant tables from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). 8-bit 4:2:0
-- Constrained Baseline, Main and High. UNSUPPORTED: interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4,
-- bit depths above 8, lossless, FMO / ASO, SP / SI slices, data partitioning, SVC / MVC (their NAL units are ignored).
local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
@@ -38,15 +14,15 @@ local H264 = {}
export type Options = {
avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed
lengthSize: number?, -- NAL length field size for length-prefixed input without avcC (1, 2 or 4)
maxPixels: number?, -- largest picture (default 2^22 luma samples)
lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering)
deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true
yield: (() -> ())?, -- a cooperative yield point (see Decoder Options.yield): pcall'ed every 16 macroblocks
maxPixels: number?,
lowDelay: boolean?,
deblock: boolean?,
yield: (() -> ())?,
}
export type Frame = {
image: Types.Image, -- yuv420p, cropped to the display size; image.meta.source = { format = "h264", poc, ... }
pts: number, -- the pts passed with the access unit holding the picture (default: its decoding index)
image: Types.Image,
pts: number,
duration: number,
poc: number,
keyframe: boolean,
@@ -83,7 +59,6 @@ local function status(self: H264Decoder): Err.Err?
return nil
end
-- newDecoder(opts?) -> H264Decoder | nil, Err
function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?)
local o = opts or {}
if type(o) ~= "table" then
@@ -100,8 +75,6 @@ function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?)
return self, nil
end
-- decoder:configure(avcC) -> true | nil, Err: reads an AVCDecoderConfigurationRecord (its SPS / PPS) and switches to
-- length-prefixed input
function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?)
local b = toBuffer(avcC)
if not b then
@@ -127,8 +100,6 @@ function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err
return true, nil
end
-- decoder:decode(data, pts?, off?, len?) -> { Frame } | nil, Err. data: an access unit or any run of NAL units:
-- length-prefixed (after configure / with opts.lengthSize), else Annex B (start codes) or one bare NAL unit.
function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?)
local b = toBuffer(data)
if not b then
@@ -165,14 +136,12 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num
return frames, nil
end
-- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering)
function DecoderMeta.flush(self: H264Decoder): { Frame }
Decoder.flush(self.state)
status(self)
return Decoder.take(self.state)
end
-- decodeAll(data, opts?) -> { Frame } | nil, Err: a whole Annex B (or length-prefixed with opts.avcC) stream
function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?)
local dec, err = H264.newDecoder(opts)
if not dec then
@@ -188,7 +157,6 @@ function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?)
return frames, nil
end
-- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err
function H264.parseAvcC(data: any): (any, Err.Err?)
local b = toBuffer(data)
if not b then
@@ -201,11 +169,6 @@ function H264.parseAvcC(data: any): (any, Err.Err?)
return cfg, nil
end
-- ------------------------------------------------------------------------------------------------ video layer
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video registry entry for "h264"):
-- track.config = avcC (MP4 / Matroska; packets length-prefixed) or nil (Annex B packets: MPEG-TS, AVI, raw .h264).
-- Pictures come out in display order with the packet timestamps sorted (display order); a track with
-- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead.
function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay,
yield = opts and opts.yield }
@@ -234,8 +197,7 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
pts = outIndex or 0
outIndex = pts + 1
elseif #pool > 0 then
-- pictures leave in display order: they take the packet timestamps in increasing order (right for
-- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times)
-- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times)
pts = table.remove(pool, 1)
end
table.insert(queue, { f.image, pts, f.keyframe })
@@ -285,9 +247,8 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
return self, nil
end
-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units
-- (7.4.1.2.3: a new unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0
-- after a slice). keyframe: the unit holds an IDR slice.
-- 7.4.1.2.3: a new access unit starts at an AUD, SPS, PPS or SEI after a slice, or at a slice with first_mb_in_slice 0
-- after a slice
function H264.accessUnits(data: any, off: number?, len: number?): { any }
local b = toBuffer(data)
local out = {}
@@ -312,7 +273,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any }
end
end
if boundary then
-- the unit ends where this NAL's start code begins
local s = p
while s > start and buffer.readu8(b, s - 1) ~= 1 do
s -= 1
@@ -341,8 +301,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any }
return out
end
-- toAnnexB(config, sample) -> buffer: a length-prefixed sample (MP4 / Matroska) as Annex B; with config (avcC) the
-- parameter sets are prepended (pass it for the first sample / keyframes). nil, Err on a bad avcC / sample
function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
local parts = {}
local lengthSize = 4
@@ -366,7 +324,6 @@ function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
return buffer.fromstring(table.concat(parts)), nil
end
-- info(data) -> { width, height, profile, level, frameRate?, ... } of the first SPS of an Annex B stream or avcC | nil
function H264.info(data: any): any
local b = toBuffer(data)
if not b then
@@ -405,7 +362,6 @@ function H264.info(data: any): any
return nil
end
-- planes(img) -> y, u, v offsets in img.pixels and the chroma width / height
function H264.planes(img: Types.Image): (number, number, number, number, number)
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
local ny = img.width * img.height