Files
rosetta/src/Rosetta/codecs/video/H264/init.luau
T
4DBug 7a6368242b video perf: MPEG-1/2, yuv -> rgba, H.264, VP8 faster in interpreted Luau (and native / LuaJIT), outputs unchanged
- codecs/video/Mpeg2/Decoder: coefficient loop keeps the bit position in a local and reads a 25-bit window with
  one readu32 (no fifth byte); MPEG-1 oddification with bor; dequant shifts; tracks the highest coefficient so the
  IDCT skips the zero rows; toRgba / toRgba422 through shifted-channel lookup tables (one rshift + one index per
  channel, the alpha folded in), two rows per chroma row without a per-pixel branch
- codecs/video/Dsp: idct(blk, dst, off, stride, add, last?): pass 1 only over the rows up to last's, pass 2 with
  the rows-4..7-zero branch tree when they are, fused with the put / add (rounding and the CLAMP offset in one
  division); mc: an unrolled whole-sample copy for 8 / 16 wide blocks, the 4-tap case a column at a time reusing
  each row's pair sums
- codecs/image/Yuv.toRgba: per-matrix luma table, shifted-channel clip tables, chroma once per 2x2
- codecs/video/H264: prediction scratch as buffers (put = u32 copy, bi-pred average four samples at a time),
  whole-sample single-list blocks copied straight from the reference, implicit / identity weights routed to the
  plain paths, 2-tap chroma when a fraction is 0 and the bilinear taps slide along the row, six-tap with two
  multiplies; deblocking skips the inner edges of macroblocks with one motion and no luma coefficients
  (S.flatTab) and finds equal motion before motionDiffers
- codecs/image/Vp8/Predict: six-tap filters with a sliding window (one read per sample)
- --!optimize 2 on every video codec / container module that lacked it (the bundles already force it)
- tools/bench_video.luau: the video fps lines on their own (sections, "once", "jitdefault"), more MPEG-1 clips
2026-11-01 20:54:46 -06:00

373 lines
10 KiB
Luau

--!strict
--!optimize 2
-- 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")
local Decoder = require("@rosetta/codecs/video/H264/Decoder")
local Params = require("@rosetta/codecs/video/H264/Params")
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?,
lowDelay: boolean?,
deblock: boolean?,
yield: (() -> ())?,
}
export type Frame = {
image: Types.Image,
pts: number,
duration: number,
poc: number,
keyframe: boolean,
}
local DecoderMeta = {}
DecoderMeta.__index = DecoderMeta
export type H264Decoder = typeof(setmetatable({} :: { state: any, lengthSize: number?, errors: number, lastError: string? }, DecoderMeta))
local function toBuffer(data: any): buffer?
if type(data) == "buffer" then
return data
elseif type(data) == "string" then
return buffer.fromstring(data)
end
return nil
end
local function status(self: H264Decoder): Err.Err?
local st = self.state
self.errors = st.errors
self.lastError = st.lastError
if st.fatal then
local m = st.fatal
if string.sub(m, 1, 7) == "limit: " then
return Err.new(Err.LIMIT, string.sub(m, 8))
end
return Err.new(Err.CORRUPT, m)
end
if st.unsupported then
return Err.new(Err.UNSUPPORTED, st.unsupported)
end
return nil
end
function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?)
local o = opts or {}
if type(o) ~= "table" then
return nil, Err.new(Err.ARG, "newDecoder: options must be a table")
end
local st = Decoder.new(o :: any)
local self = setmetatable({ state = st, lengthSize = o.lengthSize, errors = 0, lastError = nil :: string? }, DecoderMeta)
if o.avcC then
local ok, err = self:configure(o.avcC)
if not ok then
return nil, err
end
end
return self, nil
end
function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?)
local b = toBuffer(avcC)
if not b then
return nil, Err.new(Err.ARG, "configure: expected a buffer or string")
end
local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b))
if not cfg then
local m = err or "bad avcC"
if string.sub(m, 1, 11) == "truncated: " then
return nil, Err.new(Err.TRUNCATED, string.sub(m, 12))
end
return nil, Err.new(Err.CORRUPT, m)
end
self.lengthSize = cfg.lengthSize
local nals = cfg.nals
for i = 1, #nals, 2 do
Decoder.nal(self.state, b, nals[i], nals[i + 1], nil)
end
local e = status(self)
if e and e.code ~= Err.CORRUPT then
return nil, e
end
return true, nil
end
function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?)
local b = toBuffer(data)
if not b then
return nil, Err.new(Err.ARG, "decode: expected a buffer or string")
end
local n = buffer.len(b)
local o = math.clamp(off or 0, 0, n)
local l = math.clamp(len or (n - o), 0, n - o)
local st = self.state
local nals
if self.lengthSize then
local all, partial = Bitstream.splitLength(b, o, l, self.lengthSize)
nals = all or partial
if not all then
st.errors += 1
st.lastError = "NAL length past the end of the sample"
end
elseif Bitstream.isAnnexB(b, o, l) then
nals = Bitstream.splitAnnexB(b, o, l)
else
nals = { o, l }
end
for i = 1, #nals, 2 do
Decoder.nal(st, b, nals[i], nals[i + 1], pts)
if st.fatal or st.unsupported then
break
end
end
local frames = Decoder.take(st)
local e = status(self)
if e then
return nil, e
end
return frames, nil
end
function DecoderMeta.flush(self: H264Decoder): { Frame }
Decoder.flush(self.state)
status(self)
return Decoder.take(self.state)
end
function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?)
local dec, err = H264.newDecoder(opts)
if not dec then
return nil, err
end
local frames, e = dec:decode(data)
if not frames then
return nil, e
end
for _, f in dec:flush() do
table.insert(frames, f)
end
return frames, nil
end
function H264.parseAvcC(data: any): (any, Err.Err?)
local b = toBuffer(data)
if not b then
return nil, Err.new(Err.ARG, "parseAvcC: expected a buffer or string")
end
local cfg, err = Bitstream.parseAvcC(b, 0, buffer.len(b))
if not cfg then
return nil, Err.new(Err.CORRUPT, err or "bad avcC")
end
return cfg, nil
end
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 }
local function make(): (H264Decoder?, Err.Err?)
local d, err = H264.newDecoder(o)
if d and track.config then
local ok, e = d:configure(track.config)
if not ok then
return nil, e
end
end
return d, err
end
local dec, err = make()
if not dec then
return nil, err
end
local queue: { any } = {}
local pool: { number } = {}
local outIndex: number? = if track.ptsInOutputOrder then 0 else nil
local self: any = {}
local function push(frames: { Frame })
for _, f in frames do
local pts = f.pts
if track.ptsInOutputOrder then
pts = outIndex or 0
outIndex = pts + 1
elseif #pool > 0 then
-- 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 })
end
end
function self.decode(_: any, packet: Types.Packet): Err.Err?
if not dec then
return Err.new(Err.CORRUPT, "decoder not available")
end
if outIndex == nil and track.ptsInOutputOrder then
outIndex = packet.pts
end
if packet.pts ~= nil and not track.ptsInOutputOrder then
local i = #pool
while i > 0 and pool[i] > packet.pts do
i -= 1
end
table.insert(pool, i + 1, packet.pts)
end
local frames, e = (dec :: H264Decoder):decode(packet.data, packet.pts)
if not frames then
return e
end
push(frames)
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)
if dec then
push((dec :: H264Decoder):flush())
end
end
function self.reset(_: any)
dec = make()
table.clear(queue)
table.clear(pool)
if track.ptsInOutputOrder then
outIndex = nil
end
end
return self, nil
end
-- 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 = {}
if not b then
return out
end
local n = buffer.len(b)
local o = math.clamp(off or 0, 0, n)
local l = math.clamp(len or (n - o), 0, n - o)
local nals = Bitstream.splitAnnexB(b, o, l)
local start, hasSlice, key = o, false, false
for i = 1, #nals, 2 do
local p, nl = nals[i], nals[i + 1]
local t = buffer.readu8(b, p) % 32
local isSlice = t == 1 or t == 5
local boundary = false
if hasSlice then
if t == 9 or t == 7 or t == 8 or t == 6 or (t >= 14 and t <= 18) then
boundary = true
elseif isSlice and nl > 1 and buffer.readu8(b, p + 1) >= 128 then
boundary = true
end
end
if boundary then
local s = p
while s > start and buffer.readu8(b, s - 1) ~= 1 do
s -= 1
end
s -= 1
while s > start and buffer.readu8(b, s - 1) == 0 do
s -= 1
end
table.insert(out, start)
table.insert(out, s - start)
table.insert(out, key)
start, hasSlice, key = s, false, false
end
if isSlice then
hasSlice = true
if t == 5 then
key = true
end
end
end
if hasSlice and o + l > start then
table.insert(out, start)
table.insert(out, o + l - start)
table.insert(out, key)
end
return out
end
function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
local parts = {}
local lengthSize = 4
if config then
local cfg, err = Bitstream.parseAvcC(config, 0, buffer.len(config))
if not cfg then
return nil, Err.new(Err.CORRUPT, err or "bad avcC")
end
lengthSize = cfg.lengthSize
for i = 1, #cfg.nals, 2 do
table.insert(parts, "\0\0\0\1" .. buffer.readstring(config, cfg.nals[i], cfg.nals[i + 1]))
end
end
local nals = Bitstream.splitLength(sample, 0, buffer.len(sample), lengthSize)
if not nals then
return nil, Err.new(Err.CORRUPT, "NAL length past the end of the sample")
end
for i = 1, #nals, 2 do
table.insert(parts, "\0\0\0\1" .. buffer.readstring(sample, nals[i], nals[i + 1]))
end
return buffer.fromstring(table.concat(parts)), nil
end
function H264.info(data: any): any
local b = toBuffer(data)
if not b then
return nil
end
local nals
if buffer.len(b) > 6 and buffer.readu8(b, 0) == 1 then
local cfg = Bitstream.parseAvcC(b, 0, buffer.len(b))
nals = if cfg then cfg.nals else {}
else
nals = Bitstream.splitAnnexB(b, 0, buffer.len(b))
end
for i = 1, #nals, 2 do
if buffer.readu8(b, nals[i]) % 32 == 7 then
local sps = Params.sps(Bitstream.reader(b, nals[i], nals[i + 1], 1))
if sps then
local fps = nil
if sps.unitsInTick and sps.timeScale and sps.unitsInTick > 0 then
fps = sps.timeScale / (2 * sps.unitsInTick)
end
return {
width = sps.width,
height = sps.height,
profile = sps.profile,
level = sps.level,
chromaFormat = sps.chromaFormat,
bitDepth = sps.bitDepth,
interlaced = not sps.frameMbsOnly,
frameRate = fps,
maxRefFrames = sps.maxRefFrames,
numReorderFrames = sps.numReorderFrames,
}
end
end
end
return nil
end
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
return 0, ny, ny + cw * ch, cw, ch
end
return H264