Files
rosetta/src/Formats/codecs/video/H264/Bitstream.luau
T
4DBugandClaude Opus 5.5 434a304315 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]>
2026-10-31 12:25:03 -05:00

294 lines
8.0 KiB
Luau

--!strict
--!native
--!optimize 2
-- codecs/video/H264/Bitstream: NAL unit framing and the RBSP bit reader of ITU-T H.264 (7.3 / 7.4 / 9.1): Annex B start
-- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3)
-- parsing, emulation-prevention removal, and the u(n) / ue(v) / se(v) / te(v) readers. Written from the spec.
-- Never throws: reads past the end of an RBSP return zero bits (the buffer carries 8 zero bytes of padding and every
-- read is range-checked), and callers check `r.pos > r.size` once per syntax structure.
local Bitstream = {}
local readu8 = buffer.readu8
local band, lshift = bit32.band, bit32.lshift
export type Reader = {
buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes
pos: number, -- bit position
size: number, -- RBSP length in bits (up to the end of the data, trailing bits included)
stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none)
n: number, -- buffer length in bytes
}
-- ------------------------------------------------------------------------------------------------ framing
-- splitAnnexB(buf, off, len) -> { off1, len1, off2, len2, ... }: NAL unit payload ranges between start codes
-- (00 00 01, with any leading zero bytes); trailing zero bytes of a NAL are dropped.
function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number }
local out = {}
local e = off + len
local i = off
local start = -1
while i + 2 < e do
local b2 = readu8(buf, i + 2)
if b2 > 1 then
i += 3
elseif readu8(buf, i + 1) ~= 0 then
i += 2
elseif b2 == 1 and readu8(buf, i) == 0 then
if start >= 0 then
local j = i
while j > start and readu8(buf, j - 1) == 0 do
j -= 1
end
if j > start then
table.insert(out, start)
table.insert(out, j - start)
end
end
start = i + 3
i += 3
else
i += 1
end
end
if start >= 0 then
local j = e
while j > start and readu8(buf, j - 1) == 0 do
j -= 1
end
if j > start then
table.insert(out, start)
table.insert(out, j - start)
end
end
return out
end
-- isAnnexB(buf, off, len) -> true when the data starts with a start code (00 00 01 or 00 00 00 01)
function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean
if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then
local b2 = readu8(buf, off + 2)
if b2 == 1 then
return true
end
return b2 == 0 and len >= 4 and readu8(buf, off + 3) == 1
end
return false
end
-- splitLength(buf, off, len, size) -> NAL ranges of a length-prefixed (AVCC / MP4 sample) buffer, or nil when a
-- length runs past the end (the NALs before it are kept in the second result)
function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number })
local out = {}
local e = off + len
local p = off
while p + size <= e do
local n = 0
for k = 0, size - 1 do
n = n * 256 + readu8(buf, p + k)
end
p += size
if n > e - p then
return nil, out
end
if n > 0 then
table.insert(out, p)
table.insert(out, n)
end
p += n
end
return out, out
end
-- parseAvcC(buf, off, len) -> { lengthSize, profile, level, nals = { off, len, ... } (SPS then PPS, + SPS ext) } |
-- nil, message
function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?)
if len < 7 then
return nil, "truncated: avcC shorter than 7 bytes"
end
if readu8(buf, off) ~= 1 then
return nil, "avcC configurationVersion is not 1"
end
local cfg = {
profile = readu8(buf, off + 1),
compat = readu8(buf, off + 2),
level = readu8(buf, off + 3),
lengthSize = band(readu8(buf, off + 4), 3) + 1,
nals = {} :: { number },
}
local p = off + 5
local e = off + len
for pass = 1, 2 do
if p >= e then
return nil, "truncated: avcC parameter set count"
end
local count = if pass == 1 then band(readu8(buf, p), 31) else readu8(buf, p)
p += 1
for _ = 1, count do
if p + 2 > e then
return nil, "truncated: avcC parameter set length"
end
local n = readu8(buf, p) * 256 + readu8(buf, p + 1)
p += 2
if p + n > e then
return nil, "truncated: avcC parameter set"
end
table.insert(cfg.nals, p)
table.insert(cfg.nals, n)
p += n
end
end
return cfg, nil
end
-- ------------------------------------------------------------------------------------------------ rbsp
-- reader(buf, off, len, skip) -> Reader over the RBSP of a NAL unit's bytes [off, off + len), the first `skip`
-- bytes (the NAL header) left out; emulation_prevention_three_byte (00 00 03) removed.
function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader
local out = buffer.create(len + 8)
local o = 0
local zeros = 0
for i = off + skip, off + len - 1 do
local b = readu8(buf, i)
if zeros >= 2 and b == 3 then
zeros = 0
else
buffer.writeu8(out, o, b)
o += 1
if b == 0 then
zeros += 1
else
zeros = 0
end
end
end
-- the rbsp_stop_one_bit: the last set bit of the last non-zero byte
local stop = o * 8
local j = o - 1
while j >= 0 and readu8(out, j) == 0 do
j -= 1
end
if j >= 0 then
local b = readu8(out, j)
local k = 0
while band(b, lshift(1, k)) == 0 do
k += 1
end
stop = j * 8 + 7 - k
end
return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 }
end
-- ------------------------------------------------------------------------------------------------ bits
-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces).
local P2 = table.create(33, 1) -- P2[k + 1] = 2^k
for k = 0, 32 do
P2[k + 1] = 2 ^ k
end
Bitstream.P2 = P2
local LZ8 = table.create(256, 0) -- LZ8[x + 1] = leading zero bits of the byte x (8 for 0)
for x = 0, 255 do
local n, v = 0, x
while n < 8 and v < 128 do
v *= 2
n += 1
end
LZ8[x + 1] = n
end
Bitstream.LZ8 = LZ8
-- clz32(v) -> leading zero bits of a 32-bit value
local function clz32(v: number): number
if v >= 16777216 then
return LZ8[v // 16777216 + 1]
elseif v >= 65536 then
return 8 + LZ8[v // 65536 + 1]
elseif v >= 256 then
return 16 + LZ8[v // 256 + 1]
end
return 24 + LZ8[v + 1]
end
Bitstream.clz32 = clz32
-- peekAt(b, n, pos) -> the 32 bits at bit position pos of buffer b (n bytes), zeros past the end
local function peekAt(b: buffer, n: number, pos: number): number
local p = pos // 8
if p + 5 > n then
return 0
end
local s = pos - p * 8
local w = readu8(b, p) * 16777216 + readu8(b, p + 1) * 65536 + readu8(b, p + 2) * 256 + readu8(b, p + 3)
if s == 0 then
return w
end
return (w * P2[s + 1]) % 4294967296 + readu8(b, p + 4) // P2[9 - s]
end
Bitstream.peekAt = peekAt
-- peek32(r) -> the next 32 bits (zeros past the end)
local function peek32(r: Reader): number
return peekAt(r.buf, r.n, r.pos)
end
Bitstream.peek32 = peek32
-- u(r, n) -> n bits (n 1..32) as an unsigned number
function Bitstream.u(r: Reader, n: number): number
local v = peekAt(r.buf, r.n, r.pos)
r.pos += n
return v // P2[33 - n]
end
-- u1(r) -> one bit
function Bitstream.u1(r: Reader): number
local pos = r.pos
r.pos = pos + 1
local p = pos // 8
if p >= r.n then
return 0
end
return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2
end
-- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element)
local function ue(r: Reader): number
local v = peekAt(r.buf, r.n, r.pos)
if v == 0 then
r.pos += 32
return 4294967296
end
local lz = clz32(v)
if lz < 16 then
local n = 2 * lz + 1
r.pos += n
return v // P2[33 - n] - 1
end
r.pos += lz
v = peekAt(r.buf, r.n, r.pos)
r.pos += lz + 1
return v // P2[32 - lz] - 1
end
Bitstream.ue = ue
-- se(r) -> se(v)
function Bitstream.se(r: Reader): number
local k = ue(r)
if k % 2 == 1 then
return (k + 1) // 2
end
return -(k // 2)
end
-- te(r, range) -> te(v) with the given range (max value)
function Bitstream.te(r: Reader, range: number): number
if range == 1 then
return 1 - Bitstream.u1(r)
end
return ue(r)
end
-- moreData(r) -> more_rbsp_data()
function Bitstream.moreData(r: Reader): boolean
return r.pos < r.stop
end
return Bitstream