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

+11 -68
View File
@@ -1,24 +1,9 @@
--!strict
--!native
-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws).
-- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame
-- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion
-- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11;
-- linear and non-linear quantiser scales; Table B-15 intra VLCs; the alternate scan; custom (and chroma) quantiser
-- matrices; mismatch control; concealment motion vectors; sequence headers anywhere (size changes). Not supported:
-- 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
--
-- Grown from the MPEG-1 core absorbed from mpeg1-luau e2e2898 (same author; a port of jsmpeg's decoder, src/mpeg1.js
-- by Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt, with table-driven VLCs, B-pictures and SWAR motion
-- compensation). The IDCT and motion compensation are codecs/video/Dsp (the IDCT bit-exact with ffmpeg's -idct int),
-- and dequantisation follows ffmpeg's arithmetic, so the output planes equal `ffmpeg -idct int` decoding for valid
-- streams (tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Coefficients are saturated to -2048..2047 (13818-2
-- 7.4.3; ffmpeg omits it, valid streams never reach it) and motion vectors pointing outside the reference are
-- clamped (ffmpeg skips the prediction): both only matter for corrupt data.
--
-- Everything works on flat buffers allocated per sequence size: no allocation per block, macroblock or picture.
-- Every read position is checked against the data end (plus a zero pad that bounds the overrun of one macroblock),
-- motion vectors are clamped to the reference picture, and bad data ends the slice instead of raising.
-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile).
-- From mpeg1-luau e2e2898 (same author; a port of jsmpeg's src/mpeg1.js by Dominic Szablewski, MIT,
-- licenses/jsmpeg-MIT.txt). Dequantisation follows ffmpeg's arithmetic; coefficients are saturated to -2048..2047
-- (13818-2 7.4.3; ffmpeg omits it) and vectors outside the reference are clamped (ffmpeg skips the prediction).
local V = require("@rosetta/codecs/video/Mpeg2/Vlc")
local T = require("@rosetta/codecs/video/Mpeg2/Tables")
local Dsp = require("@rosetta/codecs/video/Dsp")
@@ -83,17 +68,13 @@ local RBIAS = COFF * 256 - 298 * 16 - 409 * 128 - 128
local GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160
local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72
-- clamp to 0..255 by lookup: RGB_CLAMP[v + COFF] = clamp(v, 0, 255) for v in [-COFF, COFF + 255] (the colour biases
-- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively
-- clamp by lookup: RGB_CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the colour biases include COFF * 256
local RGB_CLAMP = buffer.create(2 * COFF + 256)
for i = 0, 2 * COFF + 255 do
buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255))
end
-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path.
-- Rows row0 .. row1 - 1 of the planes (row0 even; default 0 .. h) into out from byte oo (default 0). hook (optional)
-- runs every 16 rows (a cooperative yield point; it is pcall'ed, so it can't throw through here). (From mpeg1-luau's
-- later banded conversion.)
-- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here)
local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?)
-- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four
local r0: number = row0 or 0
@@ -187,16 +168,10 @@ export type Store = {
}
export type Core = {
-- data
write: (src: buffer, off: number, n: number) -> (),
-- decodes the next picture; atEnd: the end of the data ends the picture. Returns the store decoded into (nil when
-- no picture is complete or it could not be decoded), and whether more data is needed. A frame coded as two field
-- pictures comes back once, after its second field.
nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean),
toRgba: (s: Store, out: buffer) -> (),
reset: () -> (),
-- a cooperative yield point (e.g. coroutine.yield when over a time budget), run after every slice and every 16
-- rows of colour conversion; nil = none. pcall'ed: it can't throw through the native code.
setYield: (hook: (() -> ())?) -> (),
state: {
width: number,
@@ -244,7 +219,6 @@ function D.new(maxPixels: number?): Core
refNew = nil :: Store?,
}
-- bitstream
local data = buffer.create(64 * 1024 + PAD)
local dataLen = 0
local readByte = 0 -- next byte to look at for a start code
@@ -252,7 +226,6 @@ function D.new(maxPixels: number?): Core
local pos = 0 -- bit position inside data
local err = false
-- sequence
local hasSeq = false
local mpeg2 = false
local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2
@@ -273,7 +246,6 @@ function D.new(maxPixels: number?): Core
-- the sequence header's values, applied (and the stores allocated) once its extension has been seen
local seqW, seqH = 0, 0
-- picture
local ptype = 0
local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t]
local fullPelFw, fullPelBw = false, false
@@ -299,7 +271,6 @@ function D.new(maxPixels: number?): Core
local pendingFw: Store? = nil
local pendingBw: Store? = nil
-- slice / macroblock
local qscale = 2
local mbAddr, mbRow, mbCol = 0, 0, 0
local dcY, dcCb, dcCr = 128, 128, 128
@@ -342,7 +313,6 @@ function D.new(maxPixels: number?): Core
return band(e, 0xFFFF) - 32768
end
-- byte offset of the next 00 00 01 xx at or after from (with xx before to), or -1
local function findStart(from: number, to: number): number
local i = from
while i + 3 < to do
@@ -396,7 +366,6 @@ function D.new(maxPixels: number?): Core
end
end
-- the sequence (header + extension) takes effect: sizes and stores
local function applySequence(): boolean
local w, h = seqW, seqH
if w == 0 or h == 0 or w * h > state.maxPixels then
@@ -428,7 +397,6 @@ function D.new(maxPixels: number?): Core
return true
end
-- sequence header at byte p (after the start code); false when invalid
local function sequenceHeader(p: number): boolean
pos = p * 8
local w = read(12)
@@ -545,11 +513,6 @@ function D.new(maxPixels: number?): Core
return (pred + d + range) % (2 * range) - range
end
-- ------------------------------------------------------------------------------------------------ prediction
-- One prediction of the current macroblock part from the reference planes rY / rCb / rCr: field-based (sp >= 0:
-- source field sp, destination field dp of the frame, line stride 2 * cw) or frame-based (sp < 0); rowY / h: the
-- first luma line of the part in those lines and its height; (mvx, mvy) in half samples; avg averages into the
-- first prediction.
local EDGE = buffer.create(Dsp.EDGE_SIZE)
local function mcPart(rY: buffer, rCb: buffer, rCr: buffer, sp: number, dp: number, rowY: number, h: number, mvx: number, mvy: number, avg: boolean)
local stride, sb, db, ph = cw, 0, 0, lumaH
@@ -558,7 +521,6 @@ function D.new(maxPixels: number?): Core
stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2
cs, csb, cdb = 2 * chw, sp * chw, dp * chw
end
-- luma
local hx, hy = band(mvx, 1), band(mvy, 1)
local sx = mbCol * 16 + (mvx - hx) // 2
local sy = rowY + (mvy - hy) // 2
@@ -623,7 +585,6 @@ function D.new(maxPixels: number?): Core
return (bwS or cur) :: Store
end
-- the prediction of direction d (0 forward, 1 backward); avg: the second one of a bidirectional macroblock
local function predictDir(d: number, avg: boolean)
local o = d * 8
if not fieldPic then
@@ -667,7 +628,6 @@ function D.new(maxPixels: number?): Core
end
end
-- the prediction of a non-intra macroblock from the current motion state
local function predictMb()
if ptype == 2 then
predictDir(0, false)
@@ -701,10 +661,8 @@ function D.new(maxPixels: number?): Core
end
end
-- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1
-- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do
-- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock
-- before the gap.
-- macroblocks no slice covers: ffmpeg's encoder skips a row's last macroblock at an MPEG-1 slice end and its decoder
-- conceals it as skipped; so do we (P / damaged I: zero-vector copy, B: the prediction before the gap)
local covered = 0
local gapFw, gapBw = false, false
local GAP = table.create(16, 0)
@@ -761,9 +719,7 @@ function D.new(maxPixels: number?): Core
FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4
end
-- ------------------------------------------------------------------------------------------------ blocks
-- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture.
-- False on a bitstream error.
-- block b: 0..3 luma, then Cb / Cr alternating
local function decodeBlock(b: number): boolean
local n = 0
local q: buffer
@@ -828,7 +784,6 @@ function D.new(maxPixels: number?): Core
local qs = qscale
local m2 = mpeg2
while true do
-- inline peek
local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp))
local s = band(pos, 7)
@@ -911,7 +866,7 @@ function D.new(maxPixels: number?): Core
if m2 then
parityOdd = bxor(parityOdd, band(m, 1))
end
-- saturate
-- saturation (13818-2 7.4.3)
if m > 2047 then
m = 2047
elseif m < -2048 then
@@ -929,7 +884,6 @@ function D.new(maxPixels: number?): Core
writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1)
onlyDc = false
end
-- reconstruction
local dst, off, stride
if luma then
dst = curY
@@ -973,7 +927,6 @@ function D.new(maxPixels: number?): Core
return true
end
-- ------------------------------------------------------------------------------------------------ macroblocks
local function getQscale(code: number): number
if qScaleType == 1 then
return readu8(NON_LINEAR, code)
@@ -1051,7 +1004,6 @@ function D.new(maxPixels: number?): Core
end
end
-- one macroblock (with the skipped ones before it). False on a bitstream error or the end of the slice data.
local function decodeMacroblock(first: boolean, endBits: number): boolean
local inc = 0
local t = vlc(MBAI, MBAI_BITS)
@@ -1253,7 +1205,6 @@ function D.new(maxPixels: number?): Core
end
end
-- ------------------------------------------------------------------------------------------------ pictures
-- the frame a picture completes becomes the newest reference (I / P)
local function finishFrame(s: Store)
if s.ptype ~= 3 then
@@ -1262,8 +1213,7 @@ function D.new(maxPixels: number?): Core
end
end
-- The picture header at byte p (after 00 00 01 00) and its extensions, up to stop: the byte of the first slice
-- start code (-1: none) and the temporal reference, or nil when the picture is skipped
-- the picture header (after 00 00 01 00) and its extensions
local function pictureHeader(p: number, stop: number): (number?, number)
pos = p * 8
local tref = read(10)
@@ -1316,7 +1266,6 @@ function D.new(maxPixels: number?): Core
return at, tref
end
-- the frame the picture decodes into (the pending one for a second field) and its references; false: skipped
local function selectTarget(tref: number, tag: any): boolean
fieldPic = picStruct ~= 3
parity = if picStruct == 2 then 1 else 0
@@ -1370,7 +1319,6 @@ function D.new(maxPixels: number?): Core
return true
end
-- plane addressing of the current picture
local function setAddressing()
local target = cur :: Store
curY, curCb, curCr = target.y, target.cb, target.cr
@@ -1390,15 +1338,12 @@ function D.new(maxPixels: number?): Core
mbIntra = false
end
-- The picture whose header starts at byte p (after 00 00 01 00) and ends at byte stop: the decoded frame, or nil
-- (skipped, or the first field of a frame).
local function decodePicture(p: number, stop: number, tag: any): Store?
local first, tref = pictureHeader(p, stop)
if first == nil or not selectTarget(tref, tag) then
return nil
end
setAddressing()
-- slices
local at = first :: number
while at >= 0 do
local code = readu8(data, at + 3)
@@ -1443,7 +1388,6 @@ function D.new(maxPixels: number?): Core
if n <= 0 then
return
end
-- drop consumed bytes, keeping the scan state relative
if readByte > 0 then
local keep = dataLen - readByte
if keep > 0 then
@@ -1468,7 +1412,6 @@ function D.new(maxPixels: number?): Core
buffer.fill(data, dataLen, 0, PAD)
end
-- the sequence header unit at byte at (up to stop): the header, then its extensions
local function sequenceUnit(at: number, stop: number)
local ok = sequenceHeader(at + 4)
local s = findStart(at + 4, stop)
+3 -4
View File
@@ -1,8 +1,7 @@
--!strict
-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables. Those of jsmpeg's MPEG-1 video decoder (https://github.com/phoboslab/jsmpeg,
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from
-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the
-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7.
-- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables.
-- MPEG-1: jsmpeg's (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), 0-based, via
-- mpeg1-luau e2e2898. MPEG-2 (DC sizes to 11, B-15, non-linear quantiser scale, alternate scan): ISO/IEC 13818-2 annex B / 7.
local T = {}
T.PICTURE_RATE = { [0] = 0.0,
23.976, 24.0, 25.0, 29.97, 30.0, 50.0, 59.94, 60.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+3 -11
View File
@@ -1,14 +1,8 @@
--!strict
-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau).
--
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level
-- (8 bits, then 8 more for the long codes) and hold len * 65536 + value, value = run * 256 + level, ESC = 0xFFFF,
-- EOB = 0xFFFE, or SUB + subtable for a long-code prefix. DCT_NEXT is the table for every coefficient after the
-- first one of a block, where "10" is end_of_block and "11" is run 0 / level 1 (jsmpeg reads this as "1" and one
-- more bit); DCT_FIRST keeps "1" as run 0 / level 1. DCT_B15 is MPEG-2's Table B-15 (intra_vlc_format = 1), DC_LUMA /
-- DC_CHROMA cover sizes up to 11. Absorbed from mpeg1-luau e2e2898 (same author, built from jsmpeg's binary trees);
-- the MPEG-2 tables are built from code lists.
-- Flat: indexed by the next K bits, len * 65536 + (value + 32768), len 0 = invalid. DCT: two-level (8 + 8 bits),
-- len * 65536 + run * 256 + level, ESC = 0xFFFF, EOB = 0xFFFE, or SUB + subtable for a long-code prefix.
-- DCT_NEXT: "10" = end_of_block, "11" = run 0 / level 1 (jsmpeg reads "1" + one bit); DCT_FIRST: "1" = run 0 / level 1.
local T = require("@rosetta/codecs/video/Mpeg2/Tables")
local V = {}
@@ -53,7 +47,6 @@ local function flat(tree: { [number]: number }): (buffer, number)
return flatLeaves(leaves(tree))
end
-- { { code, length } } indexed from 1 -> leaves with value = index - 1
local function codeLeaves(codes: { { number } }): { Leaf }
local out: { Leaf } = {}
for i, c in codes do
@@ -66,7 +59,6 @@ V.SUB = 0x1000000
V.ESC = 0xFFFF
V.EOB = 0xFFFE
-- two-level table: 256 first-level entries, then 256-entry subtables for prefixes of codes longer than 8 bits
local function twoLevel(ls: { Leaf }): buffer
local subs: { [number]: number } = {}
local nsub = 0
+13 -62
View File
@@ -1,23 +1,8 @@
--!strict
-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I /
-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes
-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from
-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this
-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines);
-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded.
-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
--
-- local dec = Mpeg2.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... }
-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2)
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
-- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top
-- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
local Types = require("@rosetta/Types")
local Err = require("@rosetta/core/Err")
local D = require("@rosetta/codecs/video/Mpeg2/Decoder")
@@ -34,10 +19,9 @@ export type Frame = {
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based)
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
-- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride
-- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2)
index: number,
tag: any,
-- luma stride codedWidth, chroma stride codedWidth / 2; chroma rows half the luma rows (4:2:0) or as many (4:2:2)
y: buffer,
cb: buffer,
cr: buffer,
@@ -45,23 +29,17 @@ export type Frame = {
chroma: number, -- 1 = 4:2:0, 2 = 4:2:2
mpeg2: boolean,
progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true)
fields: boolean, -- coded as two field pictures
fields: boolean,
topFieldFirst: boolean,
repeatFirstField: boolean,
clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated)
concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed)
clamped: number,
concealed: { [number]: boolean },
}
export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
-- display order for streams without B-frames.
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
-- a cooperative yield point, run after every slice and every 16 rows of colour conversion: e.g. a function that
-- calls coroutine.yield() when a time budget is spent, to spread a picture over several frames (the decode call
-- then runs inside a coroutine). Don't call this decoder again while a decode is suspended. Errors in it are
-- ignored. See dec:setYield.
reorder: boolean?,
rgba: boolean?,
maxPixels: number?,
yield: (() -> ())?,
}
@@ -154,7 +132,6 @@ local function sync(self: Decoder)
self.stats.skipped = st.skipped
end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s)
@@ -205,19 +182,14 @@ local function append(self: Decoder, data: any, offset: number?, len: number?):
return true
end
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then
return nil
@@ -225,8 +197,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, l
return run(self, true, tag)
end
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
-- for reordering. Call until it returns nil.
function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil)
if f then
@@ -240,24 +210,15 @@ function Decoder.flush(self: Decoder): Frame?
return nil
end
-- Sets (or clears, nil) the cooperative yield hook (Options.yield).
function Decoder.setYield(self: Decoder, hook: (() -> ())?)
self._core.setYield(if type(hook) == "function" then hook else nil)
end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- YCbCr 4:2:0 planes (a frame's y / cb / cr / codedWidth, or copies of them) -> RGBA8 rows row0 .. row1 - 1 of a
-- width x height picture, written to out from byte outOffset (default 0) as (row1 - row0) rows of width * 4 bytes.
-- row0 is rounded down to even (rows share chroma in pairs); defaults 0 and height. Lets the conversion run in
-- bands (on several threads) or only for the frames that are shown. The planes may hold only rows planeRow0 ..
-- (planeRow0 even, default 0; their row 0 is picture row planeRow0). hook: a cooperative yield point every 16 rows.
-- Returns false (writing nothing) when an argument is out of range. (4:2:0 only: a 4:2:2 frame's chroma has as many
-- rows as its luma; use frameImage(frame, true) for those.)
function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean
if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then
return false
@@ -274,7 +235,6 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid
if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then
return false
end
-- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band
local lumaRows = r1 - pr
local chromaRows = (r1 + 1) // 2 - pr // 2
if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then
@@ -283,15 +243,10 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid
if buffer.len(out) < oo + (r1 - r0) * w * 4 then
return false
end
-- rows relative to the planes' first row
D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil)
return true
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma
-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for
-- a value that is not a Frame.
function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil
@@ -360,10 +315,6 @@ function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
return img
end
-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder
-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in
-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of
-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream).
function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
@@ -382,7 +333,7 @@ function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecode
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
while f do -- more pictures in the packet
while f do
push(f)
f = dec:decode(packet.data, 0, 0, tag)
end