rename: src/Formats -> src/Rosetta, @formats -> @rosetta requires, build/luajit/rosetta + rosetta._compat, build/roblox/Rosetta, ROSETTA_* env/globals, writer vendor strings
This commit is contained in:
1 parent
2956576d7f
commit
22ddcd78fa
941 files changed
+3364
-3364
No files matched your search
@@ -0,0 +1,415 @@
|
||||
--!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).
|
||||
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?, -- 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
|
||||
}
|
||||
|
||||
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)
|
||||
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
|
||||
|
||||
-- newDecoder(opts?) -> H264Decoder | nil, Err
|
||||
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
|
||||
|
||||
-- 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
|
||||
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
|
||||
|
||||
-- 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
|
||||
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
|
||||
|
||||
-- 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
|
||||
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
|
||||
|
||||
-- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err
|
||||
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
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ 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 }
|
||||
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 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)
|
||||
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
|
||||
|
||||
-- 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.
|
||||
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
|
||||
-- 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
|
||||
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
|
||||
|
||||
-- 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
|
||||
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
|
||||
|
||||
-- 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
|
||||
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
|
||||
|
||||
-- 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
|
||||
return 0, ny, ny + cw * ch, cw, ch
|
||||
end
|
||||
|
||||
return H264
|
||||
Reference in new issue
Block a user