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

+3 -3
View File
@@ -263,9 +263,9 @@ Codecs (layer 3, shared by formats; not loadable on their own), by domain:
- **video** - **video**
- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. - codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. - codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int.
- 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 - codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg.
- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. - codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder - codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2.
- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). - codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska - codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA).
- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. - codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta.
+10 -32
View File
@@ -2,23 +2,9 @@
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs. -- codecs/video/Dsp: the 8x8 IDCT (bit-exact with ffmpeg -idct int) and half-pel motion compensation of MPEG codecs.
-- Block DSP shared by the MPEG-style video codecs (MPEG-1 / MPEG-2, H.263 / Sorenson Spark): the IDCT put or added -- The IDCT is IJG's jrevdct.c (LL&M, CONST_BITS 13, PASS1_BITS 2) as ffmpeg ships it (libavcodec/jrevdct.c, IJG
-- into 8-bit planes, constant (DC-only) blocks, half-pel motion compensation four samples at a time. Native, never -- licence: licenses/libjpeg-README.ijg), translated mechanically: its sparse-input special cases stay because their
-- throws (the caller keeps offsets in range). -- merged constants round differently. Natural-order i32 coefficients, no int16 wrap, put / add clamping in pass 2.
--
-- The IDCT is the Independent JPEG Group's jrevdct.c (the LL&M integer IDCT, CONST_BITS 13, PASS1_BITS 2) as ffmpeg
-- ships it (libavcodec/jrevdct.c, IJG licence: licenses/libjpeg-README.ijg), translated mechanically: rows first, then
-- columns, with every sparse-input special case of the original kept, because several of them use merged constants
-- (FIX_1_306562965 for FIX_0_541196100 - FIX_1_847759065, ...) that round differently from the general case; that
-- is what makes ffmpeg's `-idct int` output reproducible here. Changes: Luau, i32 coefficients in natural order
-- (ffmpeg's LIBMPEG2 permutation is only a storage order), no int16 wrap of the intermediate values (identical for
-- coefficients in the MPEG range), and the put / add clamping fused into the last pass.
--
-- Dsp.idct(blk, dst, off, stride, add) -- blk: 64 i32 (256 bytes, row-major), left holding garbage: clear it
-- Dsp.fill(dst, off, stride, v, add) -- an 8x8 block of constant v (a DC-only block: v = (dc + 4) >> 3)
-- Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy, avg) -- half-pel prediction of a w x h block
-- Dsp.mcNoRound(src, sStride, sOff, dst, dStride, dOff, w, h, hx, hy) -- the same, averages rounded down (H.263+)
-- Dsp.edge(src, stride, base, x, y, w, h, pw, ph, out) -- a block with edge samples repeated (EDGE_STRIDE)
local Dsp = {} local Dsp = {}
local readu8 = buffer.readu8 local readu8 = buffer.readu8
@@ -42,7 +28,6 @@ end
Dsp.CLAMP = CLAMP Dsp.CLAMP = CLAMP
Dsp.COFF = COFF Dsp.COFF = COFF
-- ------------------------------------------------------------------------------------------------ IDCT
function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean) function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: boolean)
local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0 local tmp0, tmp1, tmp2, tmp3 = 0, 0, 0, 0
local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0 local tmp10, tmp11, tmp12, tmp13 = 0, 0, 0, 0
@@ -634,9 +619,7 @@ function Dsp.idct(blk: buffer, dst: buffer, off: number, stride: number, add: bo
end end
end end
-- ------------------------------------------------------------------------------------------------ blocks -- the IDCT of a lone DC coefficient dc is (dc + 4) >> 3 everywhere
-- an 8x8 block of the constant v put into dst (add = false) or added to it, clamped (a DC-only block: the IDCT
-- of a lone DC coefficient dc is (dc + 4) >> 3 everywhere)
function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean) function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: boolean)
if not add then if not add then
local c = readu8(CLAMP, v + COFF) * 0x01010101 local c = readu8(CLAMP, v + COFF) * 0x01010101
@@ -655,12 +638,9 @@ function Dsp.fill(dst: buffer, off: number, stride: number, v: number, add: bool
end end
end end
-- ------------------------------------------------------------------------------------------------ motion -- rounding up (MPEG-1 / 2, H.263 rounding_type 0); strides are twice the plane width for field prediction.
-- Motion-compensated prediction of a w x h block (w a multiple of 4) from src (rows sStride apart, from sOff) to dst -- Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits each byte into its
-- (dStride, dOff): half-pel flags hx / hy, rounding up (MPEG-1 / 2, H.263 rounding_type 0); avg averages into what -- low 2 bits and high 6 bits so no lane overflows.
-- dst holds (the second prediction of a bidirectional block, rounding up). Strides are twice the plane width for
-- field prediction. Four bytes at a time: avg(a, b) = (a | b) - ((a ^ b) & 0xFE..) >> 1; the 4-tap average splits
-- each byte into its low 2 bits and high 6 bits so no lane overflows.
function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean) function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number, avg: boolean)
for _ = 1, h do for _ = 1, h do
for i = 0, w - 4, 4 do for i = 0, w - 4, 4 do
@@ -693,8 +673,7 @@ function Dsp.mc(src: buffer, sStride: number, sOff: number, dst: buffer, dStride
end end
end end
-- Dsp.mc with the half-sample averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1: -- averages rounded down, (a + b) >> 1 and (a + b + c + d + 1) >> 2 (H.263 rounding type 1, MPEG-4 rounding_control)
-- RTYPE of an H.263+ picture header, MPEG-4 rounding_control). No averaging into dst.
function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number) function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer, dStride: number, dOff: number, w: number, h: number, hx: number, hy: number)
if hx == 0 and hy == 0 then if hx == 0 and hy == 0 then
Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false) Dsp.mc(src, sStride, sOff, dst, dStride, dOff, w, h, 0, 0, false)
@@ -721,9 +700,8 @@ function Dsp.mcNoRound(src: buffer, sStride: number, sOff: number, dst: buffer,
end end
end end
-- Edge emulation: the (w + 1) x (h + 1) samples at (x, y) of a pw x ph plane (row r at base + r * stride) copied to -- edge emulation: coordinates clamped into the plane, so a vector pointing outside the picture predicts from repeated
-- out (rows EDGE_STRIDE apart), coordinates clamped into the plane, so a vector pointing outside the picture -- edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33)
-- predicts from repeated edge samples (w + 1 <= EDGE_STRIDE, h + 1 <= 33; out holds EDGE_SIZE bytes).
Dsp.EDGE_STRIDE = 32 Dsp.EDGE_STRIDE = 32
Dsp.EDGE_SIZE = 32 * 34 + 4 Dsp.EDGE_SIZE = 32 * 34 + 4
function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer) function Dsp.edge(src: buffer, stride: number, base: number, x: number, y: number, w: number, h: number, pw: number, ph: number, out: buffer)
+10 -48
View File
@@ -1,30 +1,9 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core (native, never throws). Written from ITU-T -- codecs/video/H263/Decoder: the H.263 / Sorenson Spark decoding core, from ITU-T H.263 (01/2005) and Adobe's Video
-- H.263 (01/2005) and Adobe's Video File Format Specification v10 (the H.263VIDEOPACKET of Sorenson Spark). -- File Format Specification v10 (H.263VIDEOPACKET). Dequantiser |REC| = QUANT * (2 |LEVEL| + 1), minus 1 for an even
-- -- QUANT; vectors outside the reference read repeated edge samples of the macroblock-aligned picture, as ffmpeg.
-- H.263: picture headers with PTYPE (sub-QCIF .. 16CIF) and PLUSPTYPE (H.263+: standard and custom picture formats,
-- custom pixel aspect ratios and picture clock frequencies, the rounding type RTYPE), I and P pictures, GOB headers
-- (with or without stuffing), MCBPC / CBPY / MVD / TCOEF VLCs, DQUANT, the H.263 dequantiser, half-sample motion
-- compensation with the H.263 chroma vector rounding, unrestricted motion vectors (Annex D in both header forms, the
-- PLUSPTYPE form with its reversible MVD codes and unlimited range), slice structure (Annex K, without rectangular
-- slices) and the extended escape of Annex T. Sorenson Spark
-- (FLV1): its picture header (sizes, disposable inter pictures, which never become the reference), its 7 / 11-bit
-- escape codes (version 1), unrestricted vectors. Not supported (the picture is refused with an "unsupported:" message):
-- syntax-based arithmetic coding, advanced prediction (Annex F: four vectors and OBMC), PB / B / EI / EP pictures,
-- advanced intra coding, the deblocking filter, rectangular slices, reference picture selection / resampling, reduced
-- resolution update, independent segments, the alternative inter VLC, modified quantisation (other than the escape).
--
-- The IDCT and motion compensation are codecs/video/Dsp, the dequantiser is the H.263 one (|REC| = QUANT * (2 |LEVEL|
-- + 1), minus 1 for an even QUANT, as ffmpeg without the -2048..2047 saturation), and vectors pointing outside the reference read
-- repeated edge samples of the macroblock-aligned picture, so valid streams decode exactly as `ffmpeg -idct int`
-- (tests/codecs/h263.luau). Corrupt data ends the picture: the rest is copied from the reference (state.errors).
--
-- local core = D.new(flv, maxPixels)
-- local hdr, msg = D.header(buf, off, len, flv, core.state.opp) -- the picture header (no decoding)
-- local store, msg = core.decode(buf, off, len) -- one picture -> the Store decoded into (decoder-owned)
-- core.reset() -- forget the reference (after a seek)
local Tb = require("@rosetta/codecs/video/H263/Tables") local Tb = require("@rosetta/codecs/video/H263/Tables")
local Dsp = require("@rosetta/codecs/video/Dsp") local Dsp = require("@rosetta/codecs/video/Dsp")
@@ -67,7 +46,7 @@ export type Opp = {
customPcf: boolean, customPcf: boolean,
umv: boolean, umv: boolean,
ss: boolean, -- slice structured (Annex K) ss: boolean, -- slice structured (Annex K)
options: string?, -- the unsupported options set, or nil options: string?,
width: number, width: number,
height: number, height: number,
} }
@@ -84,15 +63,15 @@ export type Header = {
umv: boolean, -- unrestricted vectors, baseline form (long vectors) umv: boolean, -- unrestricted vectors, baseline form (long vectors)
umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form umvPlus: boolean, -- unrestricted vectors, PLUSPTYPE form
rounding: number, -- RTYPE (0: half-sample averages round up) rounding: number, -- RTYPE (0: half-sample averages round up)
plus: boolean, -- PLUSPTYPE plus: boolean,
ss: boolean, -- slice structured (Annex K) ss: boolean, -- slice structured (Annex K)
cpm: boolean, cpm: boolean,
deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg) deblock: boolean, -- Sorenson's deblocking hint (not applied, as ffmpeg)
aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen) aspect: number?, -- PLUSPTYPE pixel aspect ratio code (15: aspectNum / aspectDen)
aspectNum: number?, aspectNum: number?,
aspectDen: number?, aspectDen: number?,
opp: Opp?, -- the PLUSPTYPE options in force opp: Opp?,
bitPos: number, -- absolute bit position of the first macroblock bitPos: number,
} }
export type Store = { export type Store = {
@@ -107,13 +86,11 @@ export type Store = {
disposable: boolean, disposable: boolean,
} }
-- ------------------------------------------------------------------------------------------------ header
-- the length of a slice's MBA field for a picture of n macroblocks (table K.2) -- the length of a slice's MBA field for a picture of n macroblocks (table K.2)
function D.mbaBits(n: number): number function D.mbaBits(n: number): number
return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14 return if n <= 48 then 6 elseif n <= 99 then 7 elseif n <= 396 then 9 elseif n <= 1584 then 11 elseif n <= 6336 then 13 else 14
end end
-- n (<= 24) bits at bit position p of buf, zeros past endByte
local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number local function bitsAt(buf: buffer, endByte: number, p: number, n: number): number
local v = 0 local v = 0
for k = p, p + n - 1 do for k = p, p + n - 1 do
@@ -124,8 +101,7 @@ local function bitsAt(buf: buffer, endByte: number, p: number, n: number): numbe
return v return v
end end
-- the byte offset of the first picture start code in buf[off, off + len) (H.263: 22 bits 0..01 00000; Sorenson: -- picture start code: H.263 22 bits 0..01 00000; Sorenson 17 bits 0..01, then version 0 / 1
-- 17 bits 0..01 and version 0 / 1), or -1
local function findStart(buf: buffer, off: number, len: number, flv: boolean): number local function findStart(buf: buffer, off: number, len: number, flv: boolean): number
local mask = if flv then 0xF8 else 0xFC local mask = if flv then 0xF8 else 0xFC
for i = off, off + len - 3 do for i = off, off + len - 3 do
@@ -136,8 +112,7 @@ local function findStart(buf: buffer, off: number, len: number, flv: boolean): n
return -1 return -1
end end
-- header(buf, off, len, flv, opp?) -> Header | nil, message: the picture header of the first picture in -- pictures with UFEP = 0 keep the previous picture's PLUSPTYPE options (opp)
-- buf[off, off + len); opp: the PLUSPTYPE options of the previous picture (pictures with UFEP = 0 keep them)
function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?) function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?): (Header?, string?)
if off < 0 or len < 0 or off + len > buffer.len(buf) then if off < 0 or len < 0 or off + len > buffer.len(buf) then
return nil, "bad range" return nil, "bad range"
@@ -340,7 +315,6 @@ function D.header(buf: buffer, off: number, len: number, flv: boolean, opp: Opp?
return h, nil return h, nil
end end
-- ------------------------------------------------------------------------------------------------ decoder
export type Core = { export type Core = {
decode: (buf: buffer, off: number, len: number) -> (Store?, string?), decode: (buf: buffer, off: number, len: number) -> (Store?, string?),
reset: () -> (), reset: () -> (),
@@ -365,12 +339,10 @@ function D.new(flv: boolean, maxPixels: number?): Core
opp = nil :: Opp?, opp = nil :: Opp?,
maxPixels = maxPixels or 4096 * 2304, maxPixels = maxPixels or 4096 * 2304,
} }
-- bitstream
local data = buffer.create(64 * 1024 + PAD) local data = buffer.create(64 * 1024 + PAD)
local endBits = 0 local endBits = 0
local pos = 0 local pos = 0
local err = false local err = false
-- picture
local W, H = 0, 0 local W, H = 0, 0
local mbW, mbH = 0, 0 local mbW, mbH = 0, 0
local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights local ls, cs, lh, chh = 0, 0, 0, 0 -- luma / chroma strides, plane heights
@@ -438,8 +410,7 @@ function D.new(flv: boolean, maxPixels: number?): Core
state.width, state.height = w, h state.width, state.height = w, h
end end
-- one 8x8 block: intra (INTRADC, then the coded coefficients from position 1) put into dst, or an inter block's -- intra blocks: INTRADC, then the coded coefficients from position 1
-- coefficients added to the prediction already in dst
local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean local function block(intra: boolean, coded: boolean, dst: buffer, off: number, stride: number): boolean
local i = 0 local i = 0
local dcOnly = true local dcOnly = true
@@ -551,7 +522,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
return true return true
end end
-- one motion vector component from its prediction (half samples)
local function motion(pred: number): number local function motion(pred: number): number
if umvPlus then if umvPlus then
-- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign -- reversible codes (Annex D.2): "1" = 0, else 0 x0 (1 x)* 0, the last x the sign
@@ -591,7 +561,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5 return (v + 32) % 64 - 32 -- the code pair's value in -16 .. 15.5
end end
-- the prediction of macroblock (col, row) from the reference, vector (mx, my) in half samples
local function predict(col: number, row: number, mx: number, my: number) local function predict(col: number, row: number, mx: number, my: number)
local hx, hy = mx % 2, my % 2 local hx, hy = mx % 2, my % 2
local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2 local sx, sy = col * 16 + (mx - hx) // 2, row * 16 + (my - hy) // 2
@@ -619,7 +588,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
end end
end end
-- a macroblock copied from the reference (not coded, or concealed); mid-grey without one
local function copyMb(col: number, row: number) local function copyMb(col: number, row: number)
local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8 local yo, co = row * 16 * ls + col * 16, row * 8 * cs + col * 8
if ref then if ref then
@@ -636,9 +604,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
end end
end end
-- macroblock (col, row) of a picture (P: an inter picture; top: within the first macroblock columns' worth of
-- the picture / a GOB or slice with a header, whose vector predictions do not look up; first: the first
-- macroblock of a slice, whose left neighbour is outside). false on bad data.
local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean local function macroblock(col: number, row: number, P: boolean, top: boolean, first: boolean): boolean
if pos > endBits then if pos > endBits then
return false return false
@@ -732,7 +697,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
return true return true
end end
-- an optional GOB header at a GOB boundary: its GN and GQUANT, or nil
local function gobHeader(cpm: boolean): (number?, number?) local function gobHeader(cpm: boolean): (number?, number?)
if not startCode() then if not startCode() then
return nil, nil return nil, nil
@@ -745,7 +709,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
return gn, read(5) return gn, read(5)
end end
-- an optional slice header (Annex K, no rectangular slices): its MBA and SQUANT, or nil
local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?) local function sliceHeader(cpm: boolean, mbaBits: number, sepb2: boolean): (number?, number?)
if not startCode() then if not startCode() then
return nil, nil return nil, nil
@@ -869,7 +832,6 @@ function D.new(flv: boolean, maxPixels: number?): Core
if hdr.opp then if hdr.opp then
state.opp = hdr.opp state.opp = hdr.opp
end end
-- the data from the header on, with zero padding
local need = len + PAD local need = len + PAD
if buffer.len(data) < need then if buffer.len(data) < need then
data = buffer.create(need) data = buffer.create(need)
+6 -11
View File
@@ -1,20 +1,15 @@
--!strict --!strict
-- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005): table 7 MCBPC for I-pictures, -- codecs/video/H263/Tables: the H.263 variable-length codes (ITU-T H.263 (01/2005) tables 7 / 8 MCBPC, 12 DQUANT,
-- table 8 MCBPC for P-pictures, table 12 DQUANT, table 13 CBPY, table 14 MVD, table 16 TCOEF, the zigzag scan of -- 13 CBPY, 14 MVD, 16 TCOEF, figure 14 zigzag). Flat tables indexed by the next K bits: len * 65536 + value (len 0: none).
-- figure 14), written from the specification as bit strings and turned into flat lookup tables at load time. -- MCBPC_I / MCBPC_P (K = 9): type * 4 + CBPC (0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, 4 INTRA+Q), STUFFING
-- -- CBPY (K = 6): the intra CBPY, Y1 the MSB (inter macroblocks use 15 - value)
-- A flat table is indexed by the next K bits of the stream and holds len * 65536 + value (len 0: not a code). -- MVD (K = 12): magnitude 0..32 in half samples (a sign bit follows every code but "1")
-- MCBPC_I / MCBPC_P (K = 9): value = macroblock type * 4 + CBPC (types 0 INTER, 1 INTER+Q, 2 INTER4V, 3 INTRA, -- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE
-- 4 INTRA+Q), STUFFING for the stuffing code
-- CBPY (K = 6): the intra CBPY (Y1 the most significant bit; inter macroblocks use 15 - value)
-- MVD (K = 12): the magnitude 0..32 in half samples (a sign bit follows every code but "1", which is 0)
-- TCOEF (K = 12): last * 1024 + run * 16 + level (a sign bit follows), ESCAPE for the escape code
local T = {} local T = {}
T.STUFFING = 255 T.STUFFING = 255
T.ESCAPE = 0xFFFF T.ESCAPE = 0xFFFF
-- builds a K-bit flat table from { bits, value } pairs
local function flat(codes: { { any } }, k: number): buffer local function flat(codes: { { any } }, k: number): buffer
local lut = buffer.create(4 * 2 ^ k) local lut = buffer.create(4 * 2 ^ k)
for _, c in codes do for _, c in codes do
+6 -28
View File
@@ -1,20 +1,7 @@
--!strict --!strict
-- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int. -- codecs/video/H263: an H.263 / H.263+ and Sorenson Spark (FLV1) video decoder, bit-exact with ffmpeg -idct int.
-- ITU-T H.263 baseline and the H.263+ picture header. Written from ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10; the decoding core is -- From ITU-T H.263 (01/2005) and Adobe's Video File Format Specification v10. Annex D UMV, GOB headers and Sorenson
-- H263/Decoder.luau (native), the IDCT and motion compensation codecs/video/Dsp, so the output planes equal -- escapes are supported; arithmetic coding, advanced prediction, PB / B / EI / EP and other H.263+ options are not.
-- `ffmpeg -idct int` (tests/codecs/h263.luau). Supports sub-QCIF .. 16CIF and H.263+ custom sizes, I and P pictures,
-- GOB headers, the rounding type, unrestricted motion vectors (Annex D), Sorenson's escape codes and disposable inter
-- pictures. Not supported (UNSUPPORTED): arithmetic coding, advanced prediction / four vectors, PB / B / EI / EP
-- pictures and the other H.263+ coding options (advanced intra coding, deblocking filter, slices, ...).
--
-- local dec = H263.new({ flv = false }) -- flv = true: Sorenson Spark (FLV1)
-- local frame, err = dec:decode(packetData, off?, len?) -- one picture -> Frame (planes decoder-owned)
-- local img = H263.frameImage(frame) -- a fresh yuv420p Types.Image (limited range, BT.601)
-- local img, err = dec:image(packetData) -- both at once
-- local info = H263.header(data, off?, len?, flv?) -- the picture header: width, height, ptype, ...
-- dec:reset() -- after a seek: wait for the next I picture
--
-- Nothing here throws: bad arguments and bad data come back as nil, Err.
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local D = require("@rosetta/codecs/video/H263/Decoder") local D = require("@rosetta/codecs/video/H263/Decoder")
@@ -29,22 +16,21 @@ export type Header = D.Header
export type Frame = { export type Frame = {
width: number, width: number,
height: number, height: number,
-- decoder-owned planes, valid until the next decode: luma stride `stride`, chroma stride stride / 2
y: buffer, y: buffer,
cb: buffer, cb: buffer,
cr: buffer, cr: buffer,
stride: number, stride: number,
pictureType: number, -- 1 I, 2 P pictureType: number, -- 1 I, 2 P
keyframe: boolean, keyframe: boolean,
disposable: boolean, -- a Sorenson disposable inter picture (not used as a reference) disposable: boolean,
temporalReference: number, temporalReference: number,
index: number, -- pictures returned so far index: number,
flv: boolean, flv: boolean,
} }
export type Options = { export type Options = {
flv: boolean?, -- Sorenson Spark (FLV1) bitstreams (default false: H.263) flv: boolean?,
maxPixels: number?, -- larger pictures are refused (LIMIT; default 4096 * 2304) maxPixels: number?,
} }
local Decoder = {} local Decoder = {}
@@ -80,8 +66,6 @@ local function span(data: any, off: number?, len: number?): (buffer?, number, nu
return b, o, n return b, o, n
end end
-- Decodes one picture (a container packet or one picture of an elementary stream). A picture with damaged
-- macroblock data still comes back (the damaged part copied from the reference; stats.errors counts them).
function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?) function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len: number?): (Frame?, Err.Err?)
local b, o, n = span(data, off, len) local b, o, n = span(data, off, len)
if not b then if not b then
@@ -111,7 +95,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, off: number?, len:
}, nil }, nil
end end
-- decode + frameImage
function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?) function Decoder.image(self: Decoder, data: buffer | string, off: number?, len: number?): (Types.Image?, Err.Err?)
local f, err = self:decode(data, off, len) local f, err = self:decode(data, off, len)
if not f then if not f then
@@ -120,13 +103,10 @@ function Decoder.image(self: Decoder, data: buffer | string, off: number?, len:
return H263.frameImage(f), nil return H263.frameImage(f), nil
end end
-- Forgets the reference picture (after a seek: P pictures fail until the next I picture).
function Decoder.reset(self: Decoder) function Decoder.reset(self: Decoder)
self._core.reset() self._core.reset()
end end
-- frameImage(frame) -> a fresh yuv420p Types.Image of the frame, cropped to width x height (chroma ceil(w / 2) x
-- ceil(h / 2)), meta.yuv = limited range BT.601; nil for a value that is not a Frame
function H263.frameImage(frame: Frame): Types.Image? function H263.frameImage(frame: Frame): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil return nil
@@ -159,8 +139,6 @@ function H263.frameImage(frame: Frame): Types.Image?
return img return img
end end
-- header(data, off?, len?, flv?) -> Header (width, height, ptype 1 I / 2 P, quant, tr, plus, umv, ...) | nil, Err:
-- the first picture header in the data, without decoding (containers use it for the track size)
function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?) function H263.header(data: buffer | string, off: number?, len: number?, flv: boolean?): (Header?, Err.Err?)
local b, o, n = span(data, off, len) local b, o, n = span(data, off, len)
if not b then if not b then
+8 -28
View File
@@ -1,11 +1,8 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!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 -- 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,
-- code splitting, AVCC length-prefixed samples, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3) -- AVCC, avcC (AVCDecoderConfigurationRecord, ISO/IEC 14496-15 5.3.3), emulation prevention, u(n) / ue(v) / se(v) / te(v).
-- 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 Bitstream = {}
local readu8 = buffer.readu8 local readu8 = buffer.readu8
@@ -13,15 +10,13 @@ local band, lshift = bit32.band, bit32.lshift
export type Reader = { export type Reader = {
buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes buf: buffer, -- the RBSP (emulation prevention removed) followed by 8 zero bytes
pos: number, -- bit position pos: number,
size: number, -- RBSP length in bits (up to the end of the data, trailing bits included) 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) stop: number, -- bit position of the rbsp_stop_one_bit (size when there is none)
n: number, -- buffer length in bytes n: number,
} }
-- ------------------------------------------------------------------------------------------------ framing -- start codes are 00 00 01 with any leading zero bytes; trailing zero bytes of a NAL are dropped
-- 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 } function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number }
local out = {} local out = {}
local e = off + len local e = off + len
@@ -63,7 +58,6 @@ function Bitstream.splitAnnexB(buf: buffer, off: number, len: number): { number
return out return out
end 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 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 if len >= 3 and readu8(buf, off) == 0 and readu8(buf, off + 1) == 0 then
local b2 = readu8(buf, off + 2) local b2 = readu8(buf, off + 2)
@@ -75,8 +69,6 @@ function Bitstream.isAnnexB(buf: buffer, off: number, len: number): boolean
return false return false
end 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 }) function Bitstream.splitLength(buf: buffer, off: number, len: number, size: number): ({ number }?, { number })
local out = {} local out = {}
local e = off + len local e = off + len
@@ -99,8 +91,6 @@ function Bitstream.splitLength(buf: buffer, off: number, len: number, size: numb
return out, out return out, out
end 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?) function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, string?)
if len < 7 then if len < 7 then
return nil, "truncated: avcC shorter than 7 bytes" return nil, "truncated: avcC shorter than 7 bytes"
@@ -140,9 +130,7 @@ function Bitstream.parseAvcC(buf: buffer, off: number, len: number): (any, strin
return cfg, nil return cfg, nil
end end
-- ------------------------------------------------------------------------------------------------ rbsp -- emulation_prevention_three_byte (00 00 03) is removed
-- 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 function Bitstream.reader(buf: buffer, off: number, len: number, skip: number): Reader
local out = buffer.create(len + 8) local out = buffer.create(len + 8)
local o = 0 local o = 0
@@ -178,7 +166,6 @@ function Bitstream.reader(buf: buffer, off: number, len: number, skip: number):
return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 } return { buf = out, pos = 0, size = o * 8, stop = stop, n = o + 8 }
end end
-- ------------------------------------------------------------------------------------------------ bits
-- Plain arithmetic instead of bit32 (LuaJIT runs bit32 through compat wrappers whose sign fix-ups split traces). -- 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 local P2 = table.create(33, 1) -- P2[k + 1] = 2^k
for k = 0, 32 do for k = 0, 32 do
@@ -196,7 +183,6 @@ for x = 0, 255 do
end end
Bitstream.LZ8 = LZ8 Bitstream.LZ8 = LZ8
-- clz32(v) -> leading zero bits of a 32-bit value
local function clz32(v: number): number local function clz32(v: number): number
if v >= 16777216 then if v >= 16777216 then
return LZ8[v // 16777216 + 1] return LZ8[v // 16777216 + 1]
@@ -209,7 +195,6 @@ local function clz32(v: number): number
end end
Bitstream.clz32 = clz32 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 function peekAt(b: buffer, n: number, pos: number): number
local p = pos // 8 local p = pos // 8
if p + 5 > n then if p + 5 > n then
@@ -224,20 +209,17 @@ local function peekAt(b: buffer, n: number, pos: number): number
end end
Bitstream.peekAt = peekAt Bitstream.peekAt = peekAt
-- peek32(r) -> the next 32 bits (zeros past the end)
local function peek32(r: Reader): number local function peek32(r: Reader): number
return peekAt(r.buf, r.n, r.pos) return peekAt(r.buf, r.n, r.pos)
end end
Bitstream.peek32 = peek32 Bitstream.peek32 = peek32
-- u(r, n) -> n bits (n 1..32) as an unsigned number
function Bitstream.u(r: Reader, n: number): number function Bitstream.u(r: Reader, n: number): number
local v = peekAt(r.buf, r.n, r.pos) local v = peekAt(r.buf, r.n, r.pos)
r.pos += n r.pos += n
return v // P2[33 - n] return v // P2[33 - n]
end end
-- u1(r) -> one bit
function Bitstream.u1(r: Reader): number function Bitstream.u1(r: Reader): number
local pos = r.pos local pos = r.pos
r.pos = pos + 1 r.pos = pos + 1
@@ -248,7 +230,7 @@ function Bitstream.u1(r: Reader): number
return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2 return (readu8(r.buf, p) // P2[8 - (pos - p * 8)]) % 2
end end
-- ue(r) -> ue(v); a code with more than 31 leading zeros returns 2^32 (out of range for every syntax element) -- more than 31 leading zeros returns 2^32 (out of range for every syntax element)
local function ue(r: Reader): number local function ue(r: Reader): number
local v = peekAt(r.buf, r.n, r.pos) local v = peekAt(r.buf, r.n, r.pos)
if v == 0 then if v == 0 then
@@ -268,7 +250,6 @@ local function ue(r: Reader): number
end end
Bitstream.ue = ue Bitstream.ue = ue
-- se(r) -> se(v)
function Bitstream.se(r: Reader): number function Bitstream.se(r: Reader): number
local k = ue(r) local k = ue(r)
if k % 2 == 1 then if k % 2 == 1 then
@@ -277,7 +258,6 @@ function Bitstream.se(r: Reader): number
return -(k // 2) return -(k // 2)
end end
-- te(r, range) -> te(v) with the given range (max value)
function Bitstream.te(r: Reader, range: number): number function Bitstream.te(r: Reader, range: number): number
if range == 1 then if range == 1 then
return 1 - Bitstream.u1(r) return 1 - Bitstream.u1(r)
@@ -285,7 +265,7 @@ function Bitstream.te(r: Reader, range: number): number
return ue(r) return ue(r)
end end
-- moreData(r) -> more_rbsp_data() -- more_rbsp_data()
function Bitstream.moreData(r: Reader): boolean function Bitstream.moreData(r: Reader): boolean
return r.pos < r.stop return r.pos < r.stop
end end
+6 -20
View File
@@ -1,12 +1,9 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3): the -- codecs/video/H264/Cabac: slice data and macroblock layer with CABAC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.3):
-- arithmetic decoding engine (9.3.1.2 / 9.3.3.2), context initialisation (9.3.1.1), the binarizations and context -- engine (9.3.1.2 / 9.3.3.2), context init (9.3.1.1), binarizations and ctxIdxInc (9.3.2 / 9.3.3.1), residual_block_cabac.
-- index increments of every syntax element (9.3.2 / 9.3.3.1) and residual_block_cabac for 4x4, 8x8 and DC blocks. -- codIOffset is kept with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one multiply.
-- Coefficients are dequantised as they are placed. Written from the spec; tables from Tables.
-- The engine keeps codIOffset with `nb` look-ahead bits (low = offset * 2^nb + next bits), so renormalisation is one
-- multiply and bytes are fetched one at a time. Never throws: returns false, "message" on bad data.
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
local Tables = require("@rosetta/codecs/video/H264/Tables") local Tables = require("@rosetta/codecs/video/H264/Tables")
local Mb = require("@rosetta/codecs/video/H264/Mb") local Mb = require("@rosetta/codecs/video/H264/Mb")
@@ -19,7 +16,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y
local Cabac = {} local Cabac = {}
-- ------------------------------------------------------------------------------------------------ engine
local RANGE_LPS = Tables.RANGE_LPS local RANGE_LPS = Tables.RANGE_LPS
local TRANS = Tables.TRANS local TRANS = Tables.TRANS
local POW2 = table.create(40, 1) local POW2 = table.create(40, 1)
@@ -51,7 +47,6 @@ for st = 0, 127 do
end end
end end
-- the engine (one slice at a time)
local ebuf: buffer = buffer.create(1) local ebuf: buffer = buffer.create(1)
local epos, elimit = 0, 0 local epos, elimit = 0, 0
local erange, elow, enb = 510, 0, 0 local erange, elow, enb = 510, 0, 0
@@ -66,8 +61,7 @@ local function refill()
enb += 8 enb += 8
end end
-- decision(ctx) -> bin (9.3.3.2.1), branch-free apart from the byte refill: the LPS test is min(1, low // scaled) -- decision (9.3.3.2.1): the LPS test is min(1, low // scaled) (low < 2.5 * scaled always)
-- (low < 2.5 * scaled always), the state step and the bin come from tables
local function decision(ctx: number): number local function decision(ctx: number): number
local s = ST[ctx + 1] local s = ST[ctx + 1]
local range = erange local range = erange
@@ -117,7 +111,6 @@ local function terminate(): number
return 0 return 0
end end
-- start the engine at byte p of the rbsp
local function engineInit(b: buffer, p: number, limit: number) local function engineInit(b: buffer, p: number, limit: number)
ebuf, epos, elimit = b, p, limit ebuf, epos, elimit = b, p, limit
elow, enb = 0, -9 elow, enb = 0, -9
@@ -147,7 +140,6 @@ local function initContexts(sliceQp: number, model: number)
end end
end end
-- ------------------------------------------------------------------------------------------------ residual
local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8 local ZZ4, ZZ8 = Tables.ZIGZAG4, Tables.ZIGZAG8
local SIG8, LAST8 = Tables.SIG8, Tables.LAST8 local SIG8, LAST8 = Tables.SIG8, Tables.LAST8
local CAT_CBF = { 0, 4, 8, 12, 16 } local CAT_CBF = { 0, 4, 8, 12, 16 }
@@ -156,8 +148,7 @@ local CAT_ABS = { 0, 10, 20, 30, 39 }
local MAXC = { 16, 15, 16, 4, 15, 64 } local MAXC = { 16, 15, 16, 4, 15, 64 }
local SIGPOS = table.create(64, 0) local SIGPOS = table.create(64, 0)
-- block(cat, out, base, mul, div) -> number of coefficients (cat 0..5); coded_block_flag is decoded by the caller. -- positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag
-- Positions: cat 0 / 2 zig-zag, 1 / 4 zig-zag from 1, 3 raster 0..3, 5 the 8x8 zig-zag
local SCAN = {} local SCAN = {}
do do
local ac = table.create(15, 0) local ac = table.create(15, 0)
@@ -266,7 +257,6 @@ local function block(cat: number, out: { number }, base: number, mul: { number }
return n return n
end end
-- ------------------------------------------------------------------------------------------------ syntax elements
-- condition helpers on neighbouring macroblocks (addresses are 1-based here) -- condition helpers on neighbouring macroblocks (addresses are 1-based here)
local function leftAddr(S: any, M: any): number local function leftAddr(S: any, M: any): number
return ((M.aL) and (M.addr) or (0)) return ((M.aL) and (M.addr) or (0))
@@ -405,7 +395,6 @@ local function bSubType(): number
return t return t
end end
-- ref_idx for the partition whose top-left 4x4 is (x, y); rgt: the ref > 0 grid of the list
local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): number
local g = M.g0 + y * S.w4 + x local g = M.g0 + y * S.w4 + x
local inc = 0 local inc = 0
@@ -430,7 +419,7 @@ local function refIdx(S: any, M: any, rgt: { number }, x: number, y: number): nu
return v return v
end end
-- mvd component (comp 0 x, 1 y) for the partition at (x, y); grid holds |mvd| (2 per 4x4) -- the mvd grid holds |mvd| (2 per 4x4)
local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number local function mvd(S: any, M: any, grid: { number }, x: number, y: number, comp: number): number
local g = M.g0 + y * S.w4 + x local g = M.g0 + y * S.w4 + x
local sum = 0 local sum = 0
@@ -651,7 +640,6 @@ local function dcCond(S: any, M: any, bit: number, intra: boolean): (number, num
return ca, cb return ca, cb
end end
-- ------------------------------------------------------------------------------------------------ residual
local function residuals(S: any, M: any): boolean local function residuals(S: any, M: any): boolean
local kind = M.kind local kind = M.kind
local cbp = M.cbp local cbp = M.cbp
@@ -776,7 +764,6 @@ local function clearCounts(M: any)
end end
end end
-- ------------------------------------------------------------------------------------------------ macroblock
local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 }
local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 }
local SUB_N = { 1, 2, 2, 4 } local SUB_N = { 1, 2, 2, 4 }
@@ -1096,7 +1083,6 @@ local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string
return interMb(S, M, r, t, true) return interMb(S, M, r, t, true)
end end
-- slice(S, M, r) -> true | false, message
function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
local p = (r.pos + 7) // 8 local p = (r.pos + 7) // 8
local limit = r.size // 8 local limit = r.size // 8
+5 -16
View File
@@ -1,11 +1,8 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2): -- codecs/video/H264/Cavlc: slice data and macroblock layer with CAVLC entropy coding (ITU-T H.264 7.3.4, 7.3.5, 9.2),
-- mb_skip_run, mb_type / sub_mb_type, intra modes, ref_idx (te), mvd, coded_block_pattern (me), mb_qp_delta and -- residual_block_cavlc with the 8x8 interleaving; coefficients are dequantised as they are placed.
-- residual_block_cavlc (coeff_token, level_prefix / suffix, total_zeros, run_before) with the 8x8 interleaving.
-- Coefficients are dequantised as they are placed. Written from the spec; VLC tables from Tables.
-- Never throws: returns false, "message" on bad data.
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
local Tables = require("@rosetta/codecs/video/H264/Tables") local Tables = require("@rosetta/codecs/video/H264/Tables")
local Mb = require("@rosetta/codecs/video/H264/Mb") local Mb = require("@rosetta/codecs/video/H264/Mb")
@@ -17,7 +14,6 @@ local BLK_X, BLK_Y = Mb.BLK_X, Mb.BLK_Y
local Cavlc = {} local Cavlc = {}
-- ------------------------------------------------------------------------------------------------ vlc tables
-- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or -- build(entries) -> l1, l2: a two-level lookup on 16 peeked bits. l1[(v >> 8) + 1] = value * 32 + length, or
-- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code -- -(base) of a second-level block l2[base + (v & 255)]; 0 = no code
local function build(entries: { { number } }): ({ number }, { number }) local function build(entries: { { number } }): ({ number }, { number })
@@ -100,7 +96,6 @@ local IDENT = { 0, 1, 2, 3 }
local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP local INTRA_CBP, INTER_CBP = Tables.INTRA_CBP, Tables.INTER_CBP
-- ------------------------------------------------------------------------------------------------ residual
local LEVEL = table.create(16, 0) local LEVEL = table.create(16, 0)
local RUN = table.create(16, 0) local RUN = table.create(16, 0)
@@ -108,8 +103,7 @@ local peek = Bitstream.peekAt
local clz32 = Bitstream.clz32 local clz32 = Bitstream.clz32
local P2 = Bitstream.P2 local P2 = Bitstream.P2
-- residual(r, nC, maxCoeff, out, base, scan, mul, div) -> TotalCoeff, or -1 on a bad code. Levels go to -- levels go to out[base + scan[i] + 1] as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels)
-- out[base + scan[i] + 1] dequantised as (level * mul[pos + 1] + div / 2) // div (mul nil: raw levels)
local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out: { number }, base: number, scan: { number }, mul: { number }?, div: number): number
local b, n = r.buf, r.n local b, n = r.buf, r.n
local pos = r.pos local pos = r.pos
@@ -256,7 +250,6 @@ local function residual(r: Bitstream.Reader, nC: number, maxCoeff: number, out:
end end
Cavlc.residual = residual Cavlc.residual = residual
-- ------------------------------------------------------------------------------------------------ macroblock
local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 } local SUBB_PF = { 0, 1, 2, 3, 1, 1, 2, 2, 3, 3, 1, 2, 3 }
local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 } local SUBB_SHAPE = { 0, 0, 0, 0, 1, 2, 1, 2, 1, 2, 3, 3, 3 }
local SUB_N = { 1, 2, 2, 4 } local SUB_N = { 1, 2, 2, 4 }
@@ -279,7 +272,6 @@ local function refIdx(r: Bitstream.Reader, n: number): number
return v return v
end end
-- the residual of the parsed macroblock
local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local function residuals(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
local kind = M.kind local kind = M.kind
local cbp = M.cbp local cbp = M.cbp
@@ -404,7 +396,7 @@ local function clearLumaGrids(S: any, M: any, intra: boolean)
end end
end end
-- intra(S, M, r, t): the intra macroblock types 0..25 (table 7-11) -- intra macroblock types 0..25 (table 7-11)
local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?) local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean, string?)
local addr = M.addr + 1 local addr = M.addr + 1
if t == 25 then if t == 25 then
@@ -515,7 +507,7 @@ local function intraMb(S: any, M: any, r: Bitstream.Reader, t: number): (boolean
return true return true
end end
-- inter(S, M, r, t, isB): the P (0..4) and B (0..22) inter macroblock types -- the P (0..4) and B (0..22) inter macroblock types
local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?) local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: boolean): (boolean, string?)
clearLumaGrids(S, M, false) clearLumaGrids(S, M, false)
local n0, n1 = S.n0, S.n1 local n0, n1 = S.n0, S.n1
@@ -709,7 +701,6 @@ local function interMb(S: any, M: any, r: Bitstream.Reader, t: number, isB: bool
return true return true
end end
-- macroblock(S, M, r) -> true | false, message
local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
local t = ue(r) local t = ue(r)
local st = S.type local st = S.type
@@ -727,8 +718,6 @@ local function macroblock(S: any, M: any, r: Bitstream.Reader): (boolean, string
return interMb(S, M, r, t, true) return interMb(S, M, r, t, true)
end end
-- ------------------------------------------------------------------------------------------------ slice data
-- slice(S, M, r) -> true | false, message: decodes macroblocks from S.firstMb until the end of the slice data
function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?)
local addr = S.firstMb local addr = S.firstMb
local total = S.mbW * S.mbH local total = S.mbW * S.mbH
+5 -13
View File
@@ -1,12 +1,9 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0: -- codecs/video/H264/Deblock: the in-loop deblocking filter of ITU-T H.264 8.7 for frame macroblocks, 8-bit 4:2:0
-- boundary strengths (8.7.2.1, from the per-4x4 intra / coefficient / reference / motion grids), alpha / beta / tC0 -- (bS 8.7.2.1, alpha / beta / tC0 tables 8-16 / 8-17). Runs over the whole picture once its slices are decoded, which
-- (tables 8-16 / 8-17), the bS < 4 and bS = 4 luma and chroma filters, disable_deblocking_filter_idc 0 / 1 / 2 and the -- equals filtering each macroblock as it is decoded.
-- slice alpha / beta offsets. Written from the spec. Runs over the whole picture in macroblock order once all its
-- slices are decoded (the result equals filtering each macroblock as it is decoded).
-- Never throws.
local Tables = require("@rosetta/codecs/video/H264/Tables") local Tables = require("@rosetta/codecs/video/H264/Tables")
local readu8, writeu8 = buffer.readu8, buffer.writeu8 local readu8, writeu8 = buffer.readu8, buffer.writeu8
@@ -23,9 +20,6 @@ end
local abs = math.abs local abs = math.abs
-- luma(b, o, across, along, qp, aOff, bOff): filters the 16 samples of one luma edge; `across` steps from q0 to q1
-- (1 for vertical edges, the stride for horizontal ones), `along` to the next sample of the edge; BS holds the four
-- strengths
local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local function luma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number)
local indexA = clip3(0, 51, qp + aOff) local indexA = clip3(0, 51, qp + aOff)
local alpha = ALPHA[indexA + 13] local alpha = ALPHA[indexA + 13]
@@ -84,7 +78,7 @@ local function luma(b: buffer, o: number, across: number, along: number, qp: num
end end
end end
-- chroma(b, o, across, along, qp, aOff, bOff): the 8 samples of one chroma edge (bS of luma segment i // 2) -- chroma: bS of luma segment i // 2
local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number) local function chroma(b: buffer, o: number, across: number, along: number, qp: number, aOff: number, bOff: number)
local indexA = clip3(0, 51, qp + aOff) local indexA = clip3(0, 51, qp + aOff)
local alpha = ALPHA[indexA + 13] local alpha = ALPHA[indexA + 13]
@@ -115,7 +109,7 @@ local function chroma(b: buffer, o: number, across: number, along: number, qp: n
end end
end end
-- motionDiffers(pic, p, q) -> true when the 4x4 blocks p and q (grid indices) need bS 1 (8.7.2.1) -- the bS 1 motion test of 8.7.2.1
local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean local function mvDiff(mvA: { number }, a: number, mvB: { number }, b: number): boolean
return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4 return abs(mvA[2 * a - 1] - mvB[2 * b - 1]) >= 4 or abs(mvA[2 * a] - mvB[2 * b]) >= 4
end end
@@ -156,7 +150,6 @@ local function motionDiffers(pic: any, p: number, q: number): boolean
return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q)) return (mvDiff(mv0, p, mv0, q) or mvDiff(mv1, p, mv1, q)) and (mvDiff(mv0, p, mv1, q) or mvDiff(mv1, p, mv0, q))
end end
-- picture(S, pic, params): deblocks the whole picture. params[sliceNum] = { idc, alphaOffset, betaOffset }
function Deblock.picture(S: any, pic: any, params: { any }) function Deblock.picture(S: any, pic: any, params: { any })
local mbW, mbH = S.mbW, S.mbH local mbW, mbH = S.mbW, S.mbH
local w4 = S.w4 local w4 = S.w4
@@ -203,7 +196,6 @@ function Deblock.picture(S: any, pic: any, params: { any })
if t8 and (e == 1 or e == 3) then if t8 and (e == 1 or e == 3) then
continue continue
end end
-- strengths of the four segments
local intraP = intraQ local intraP = intraQ
local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q local qpP, qpcP, qpc2P = qpQ, qpcQ, qpc2Q
if e == 0 then if e == 0 then
+10 -27
View File
@@ -1,10 +1,7 @@
--!strict --!strict
-- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): NAL unit -- codecs/video/H264/Decoder: the decoding process above the macroblock layer (ITU-T H.264 8.1, 8.2, C.4): picture
-- dispatch, picture boundaries (7.4.1.2.4), picture order count types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), -- boundaries (7.4.1.2.4), POC types 0 / 1 / 2 (8.2.1), frame_num gaps (8.2.5.2), list modification (8.2.4), marking
-- reference picture lists with modification (8.2.4), sliding window and adaptive (MMCO 1-6) marking (8.2.5), output -- (8.2.5), output in POC order (num_reorder_frames, else the DPB size).
-- in POC order through a reorder buffer (num_reorder_frames, else the DPB size), concealment of lost macroblocks,
-- deblocking and border extension. Written from the spec.
-- Never throws: errors are returned (a corrupt slice is skipped and its macroblocks concealed).
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
local Params = require("@rosetta/codecs/video/H264/Params") local Params = require("@rosetta/codecs/video/H264/Params")
local Slice = require("@rosetta/codecs/video/H264/Slice") local Slice = require("@rosetta/codecs/video/H264/Slice")
@@ -23,17 +20,14 @@ local Decoder = {}
Decoder.__index = Decoder Decoder.__index = Decoder
export type Options = { export type Options = {
maxPixels: number?, -- largest picture accepted (default 2^22: 4096 x 1024) maxPixels: number?,
lowDelay: boolean?, -- output pictures in decoding order without reordering (only right for streams without B frames) lowDelay: boolean?,
deblock: boolean?, -- false skips the loop filter (not conformant: faster, for previews); default true deblock: boolean?,
-- a cooperative yield point, called (pcall'ed: it can't throw through the native code) every YIELD_MBS macroblocks -- yield is pcall'ed (it can't throw through native code); the entropy decoders keep state in module locals, so no
-- of slice data and every macroblock row of the loop filter: e.g. a function that calls coroutine.yield() once a time -- other H.264 decode may run in the VM while one is suspended
-- budget is spent, to spread one picture over several frames. While a decode is suspended, no other H.264 decode may
-- run in the same Luau VM (the entropy decoders keep their state in module locals); default nil (no calls)
yield: (() -> ())?, yield: (() -> ())?,
} }
-- new(opts) -> decoder state
function Decoder.new(opts: Options?): any function Decoder.new(opts: Options?): any
local o = opts or {} local o = opts or {}
return setmetatable({ return setmetatable({
@@ -58,7 +52,7 @@ function Decoder.new(opts: Options?): any
maxLongTermIdx = -1, maxLongTermIdx = -1,
pool = {}, pool = {},
gray = nil, gray = nil,
frames = 0, -- pictures decoded frames = 0,
errors = 0, errors = 0,
lastError = nil, lastError = nil,
fatal = nil, fatal = nil,
@@ -67,7 +61,6 @@ function Decoder.new(opts: Options?): any
}, Decoder) }, Decoder)
end end
-- ------------------------------------------------------------------------------------------------ pictures
local function newPicture(self: any, sps: any): any local function newPicture(self: any, sps: any): any
local mbW, mbH = sps.mbWidth, sps.mbHeight local mbW, mbH = sps.mbWidth, sps.mbHeight
local pool = self.pool local pool = self.pool
@@ -136,7 +129,6 @@ local function grayPicture(self: any, sps: any): any
return g return g
end end
-- ------------------------------------------------------------------------------------------------ output
local function emit(self: any, p: any) local function emit(self: any, p: any)
p.waiting = false p.waiting = false
local sps = p.sps local sps = p.sps
@@ -189,7 +181,6 @@ local function reorderDepth(self: any, sps: any): number
return sps.maxDecFrameBuffering or sps.maxDpbFrames return sps.maxDecFrameBuffering or sps.maxDpbFrames
end end
-- ------------------------------------------------------------------------------------------------ reference lists
local function shortRefs(self: any): { any } local function shortRefs(self: any): { any }
local t = {} local t = {}
for _, p in self.refs do for _, p in self.refs do
@@ -288,7 +279,6 @@ local function modify(self: any, list: { any }, ops: { number }, n: number, sh:
return true return true
end end
-- buildLists(self, sh, cur) -> list0, list1 (arrays of pictures, truncated to num_ref_idx_active)
local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, boolean) local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, boolean)
picNums(self, sh) picNums(self, sh)
local list0, list1 = {}, {} local list0, list1 = {}, {}
@@ -368,7 +358,6 @@ local function buildLists(self: any, sh: any, cur: any): ({ any }, { any }, bool
return list0, list1, ok return list0, list1, ok
end end
-- ------------------------------------------------------------------------------------------------ marking
local function unmark(self: any, p: any) local function unmark(self: any, p: any)
p.short = false p.short = false
p.long = false p.long = false
@@ -411,7 +400,7 @@ local function addRef(self: any, p: any)
table.insert(self.refs, p) table.insert(self.refs, p)
end end
-- mark(self, cur, sh): 8.2.5 after decoding the current (reference) picture; returns true when MMCO 5 was present -- 8.2.5 marking after a reference picture; true when MMCO 5 was present
local function mark(self: any, cur: any, sh: any): boolean local function mark(self: any, cur: any, sh: any): boolean
local sps = sh.sps local sps = sh.sps
if sh.idr then if sh.idr then
@@ -511,7 +500,6 @@ local function mark(self: any, cur: any, sh: any): boolean
return mmco5 return mmco5
end end
-- ------------------------------------------------------------------------------------------------ poc
local function computePoc(self: any, sh: any): (number, number) local function computePoc(self: any, sh: any): (number, number)
local sps = sh.sps local sps = sh.sps
local maxFrameNum = 2 ^ sps.log2MaxFrameNum local maxFrameNum = 2 ^ sps.log2MaxFrameNum
@@ -577,7 +565,6 @@ local function computePoc(self: any, sh: any): (number, number)
return t, t return t, t
end end
-- ------------------------------------------------------------------------------------------------ picture decode
local function setupGrids(self: any, sps: any) local function setupGrids(self: any, sps: any)
local mbW, mbH = sps.mbWidth, sps.mbHeight local mbW, mbH = sps.mbWidth, sps.mbHeight
if self.S and self.S.mbW == mbW and self.S.mbH == mbH then if self.S and self.S.mbW == mbW and self.S.mbH == mbH then
@@ -760,7 +747,6 @@ local function finishPicture(self: any)
p.poc = 0 p.poc = 0
p.frameNum = 0 p.frameNum = 0
end end
-- POC / frame_num state for the next pictures
if sh.nalRefIdc ~= 0 then if sh.nalRefIdc ~= 0 then
if mmco5 then if mmco5 then
self.prevPocMsb = 0 self.prevPocMsb = 0
@@ -917,7 +903,6 @@ local function decodeSlice(self: any, sh: any, r: Bitstream.Reader)
end end
end end
-- nal(self, buf, off, len, pts): one NAL unit (no start code)
function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: number?) function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: number?)
if len < 1 then if len < 1 then
return return
@@ -1008,13 +993,11 @@ function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: numb
-- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored -- SEI (6), filler (12), SPS extension (13), prefix / SVC / MVC (14, 15, 20) and reserved types are ignored
end end
-- flush(self): finish the current picture and output every waiting picture
function Decoder.flush(self: any) function Decoder.flush(self: any)
finishPicture(self) finishPicture(self)
bump(self, 0) bump(self, 0)
end end
-- take(self) -> the frames output since the last call
function Decoder.take(self: any): { any } function Decoder.take(self: any): { any }
local out = self.out local out = self.out
self.out = {} self.out = {}
+6 -20
View File
@@ -1,12 +1,8 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3): the 6-tap -- codecs/video/H264/Inter: inter prediction sample interpolation and weighting (ITU-T H.264 8.4.2.2 / 8.4.2.3).
-- quarter-sample luma filter, eighth-sample bilinear chroma, default / explicit / implicit weighted sample -- Reference planes carry a border of PAD / PADC replicated samples, so reads equal the clamped positions of 8.4.2.2.1.
-- prediction, and the picture border extension that makes out-of-picture reference reads equal to the clamped
-- sample positions of 8.4.2.2.1. Written from the spec.
-- Reference planes carry a border of PAD (luma) / PADC (chroma) replicated samples; callers clamp block positions
-- with Inter.clampLuma / clampChroma so every read is inside the buffer. Never throws.
local readu8, writeu8 = buffer.readu8, buffer.writeu8 local readu8, writeu8 = buffer.readu8, buffer.writeu8
local Inter = {} local Inter = {}
@@ -19,11 +15,9 @@ local function clip(v: number): number
return min(max(v, 0), 255) return min(max(v, 0), 255)
end end
-- scratch rows of horizontal 6-tap intermediates (unrounded), 21 rows x 16 (+1) columns
local B1 = table.create(24 * 17, 0) local B1 = table.create(24 * 17, 0)
-- the six-tap filter cases, each a small function (LuaJIT keeps small loops in one trace); sliding windows read each -- one small function per six-tap case: LuaJIT keeps each loop in one trace
-- sample once per row / column
local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number }) local function lumaCopy(ref: buffer, s: number, base: number, w: number, h: number, P: { number })
for r = 0, h - 1 do for r = 0, h - 1 do
local o = base + r * s local o = base + r * s
@@ -141,8 +135,6 @@ local function lumaDiag(ref: buffer, s: number, base: number, w: number, h: numb
end end
end end
-- luma(ref, s, base, fx, fy, w, h, P): the w x h luma prediction for a block whose integer sample (0, 0) is at
-- ref[base] and whose fractional offset is (fx, fy) quarter samples; P[r * 16 + c + 1] receives the samples
function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number })
if fy == 0 then if fy == 0 then
if fx == 0 then if fx == 0 then
@@ -161,7 +153,6 @@ function Inter.luma(ref: buffer, s: number, base: number, fx: number, fy: number
end end
end end
-- chroma(ref, s, base, fx, fy, w, h, P): eighth-sample bilinear chroma prediction
function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number }) function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: number, w: number, h: number, P: { number })
if fx == 0 and fy == 0 then if fx == 0 and fy == 0 then
for r = 0, h - 1 do for r = 0, h - 1 do
@@ -187,8 +178,6 @@ function Inter.chroma(ref: buffer, s: number, base: number, fx: number, fy: numb
end end
end end
-- ------------------------------------------------------------------------------------------------ weighting
-- put(P, w, h, b, o, s): P into the picture
function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number) function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s: number)
for r = 0, h - 1 do for r = 0, h - 1 do
local d = r * 16 + 1 local d = r * 16 + 1
@@ -199,7 +188,7 @@ function Inter.put(P: { number }, w: number, h: number, b: buffer, o: number, s:
end end
end end
-- avg(P0, P1, w, h, b, o, s): default bi-prediction (P0 + P1 + 1) >> 1 -- default bi-prediction (P0 + P1 + 1) >> 1
function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number) function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number)
for r = 0, h - 1 do for r = 0, h - 1 do
local d = r * 16 + 1 local d = r * 16 + 1
@@ -210,7 +199,7 @@ function Inter.avg(P0: { number }, P1: { number }, w: number, h: number, b: buff
end end
end end
-- weight1(P, w, h, b, o, s, logWD, wt, off): explicit single-list weighting (8-270 / 8-271) -- explicit single-list weighting (8-270 / 8-271)
function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number) function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, wt: number, off: number)
if logWD >= 1 then if logWD >= 1 then
local rnd = 2 ^ (logWD - 1) local rnd = 2 ^ (logWD - 1)
@@ -233,8 +222,7 @@ function Inter.weight1(P: { number }, w: number, h: number, b: buffer, o: number
end end
end end
-- weight2(P0, P1, w, h, b, o, s, logWD, w0, w1, off): explicit / implicit bi-prediction weighting (8-272); -- explicit / implicit bi-prediction weighting (8-272); off = (o0 + o1 + 1) >> 1
-- off = (o0 + o1 + 1) >> 1
function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number) function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b: buffer, o: number, s: number, logWD: number, w0: number, w1: number, off: number)
local rnd = 2 ^ logWD local rnd = 2 ^ logWD
local div = 2 ^ (logWD + 1) local div = 2 ^ (logWD + 1)
@@ -247,8 +235,6 @@ function Inter.weight2(P0: { number }, P1: { number }, w: number, h: number, b:
end end
end end
-- ------------------------------------------------------------------------------------------------ borders
-- extend(b, o, s, w, h, pad): replicate the edge samples of the w x h plane at b[o] (stride s) into its border
function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number) function Inter.extend(b: buffer, o: number, s: number, w: number, h: number, pad: number)
for y = 0, h - 1 do for y = 0, h - 1 do
local r = o + y * s local r = o + y * s
+4 -9
View File
@@ -1,10 +1,8 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (nine directional modes, with the -- codecs/video/H264/Intra: intra prediction (ITU-T H.264 8.3): Intra_4x4 and Intra_8x8 (with the 8x8 reference sample
-- 8x8 reference sample filter of 8.3.2.2.1), Intra_16x16 and chroma (DC / horizontal / vertical / plane), 8-bit. -- filter of 8.3.2.2.1), Intra_16x16 and chroma, 8-bit.
-- Written from the spec. Predictions are written straight into the picture plane (row stride `s`, block origin `o`).
-- Never throws: every sample read is inside the padded plane (callers pass availability for the edges).
local readu8, writeu8 = buffer.readu8, buffer.writeu8 local readu8, writeu8 = buffer.readu8, buffer.writeu8
local Intra = {} local Intra = {}
@@ -94,8 +92,7 @@ local function directional(R: { number }, N: number, mode: number, b: buffer, o:
end end
end end
-- pred4x4(b, o, s, mode, left, top, topRight, topLeft): Intra_4x4 at plane offset o. Unavailable top-right samples -- unavailable top-right samples repeat p[3, -1]
-- repeat p[3, -1].
function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean)
if mode == 0 then if mode == 0 then
local t = o - s local t = o - s
@@ -170,7 +167,6 @@ function Intra.pred4x4(b: buffer, o: number, s: number, mode: number, left: bool
directional(E, 4, mode, b, o, s) directional(E, 4, mode, b, o, s)
end end
-- pred8x8(b, o, s, mode, left, top, topRight, topLeft): Intra_8x8 with the reference sample filter
function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean) function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topRight: boolean, topLeft: boolean)
-- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1] -- unfiltered edges into E: E[1..8] = p[-1, 7..0], E[9] = p[-1, -1], E[10..25] = p[0..15, -1]
if left then if left then
@@ -277,7 +273,6 @@ function Intra.pred8x8(b: buffer, o: number, s: number, mode: number, left: bool
end end
end end
-- pred16x16(b, o, s, mode, left, top, topLeft)
function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) function Intra.pred16x16(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean)
if mode == 0 then if mode == 0 then
local t = o - s local t = o - s
@@ -343,7 +338,7 @@ local function fill4(b: buffer, o: number, s: number, v: number)
end end
end end
-- predChroma(b, o, s, mode, left, top, topLeft): 8x8 chroma (4:2:0); mode 0 DC, 1 horizontal, 2 vertical, 3 plane -- 8x8 chroma (4:2:0): mode 0 DC, 1 horizontal, 2 vertical, 3 plane
function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean) function Intra.predChroma(b: buffer, o: number, s: number, mode: number, left: boolean, top: boolean, topLeft: boolean)
if mode == 0 then if mode == 0 then
local t = o - s local t = o - s
+9 -36
View File
@@ -2,11 +2,8 @@
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5): -- codecs/video/H264/Mb: macroblock reconstruction shared by the CAVLC and CABAC parsers (ITU-T H.264 8.3 - 8.5):
-- neighbour availability (6.4.11), Intra4x4 / Intra8x8 mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction -- neighbour availability (6.4.11), intra mode prediction (8.3.1.1 / 8.3.2.1), motion vector prediction (8.4.1.3),
-- (8.4.1.3), P_Skip (8.4.1.1), B direct spatial and temporal (8.4.1.2), motion compensation with weighting, intra -- P_Skip (8.4.1.1), B direct (8.4.1.2). Reference indices past the list use the first entry.
-- prediction and the residual. Written from the spec; the per-4x4 motion / mode grids follow the usual decoder layout
-- (picture-wide arrays, one entry per 4x4 luma block, 1-based).
-- Never throws: every index is in range by construction; reference indices past the list use the first entry.
local Intra = require("@rosetta/codecs/video/H264/Intra") local Intra = require("@rosetta/codecs/video/H264/Intra")
local Transform = require("@rosetta/codecs/video/H264/Transform") local Transform = require("@rosetta/codecs/video/H264/Transform")
local Inter = require("@rosetta/codecs/video/H264/Inter") local Inter = require("@rosetta/codecs/video/H264/Inter")
@@ -29,7 +26,6 @@ local BLK_X = { 0, 1, 0, 1, 2, 3, 2, 3, 0, 1, 0, 1, 2, 3, 2, 3 }
local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 } local BLK_Y = { 0, 0, 1, 1, 0, 0, 1, 1, 2, 2, 3, 3, 2, 2, 3, 3 }
Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y Mb.BLK_X, Mb.BLK_Y = BLK_X, BLK_Y
-- new() -> M, the per-macroblock scratch state
function Mb.new(): any function Mb.new(): any
return { return {
addr = 0, addr = 0,
@@ -79,7 +75,6 @@ function Mb.new(): any
} }
end end
-- grids(mbW, mbH) -> the per-picture decoding grids (shared by the slices of one picture)
function Mb.grids(mbW: number, mbH: number): any function Mb.grids(mbW: number, mbH: number): any
local n = mbW * mbH local n = mbW * mbH
local n4 = n * 16 local n4 = n * 16
@@ -107,8 +102,6 @@ function Mb.grids(mbW: number, mbH: number): any
} }
end end
-- ------------------------------------------------------------------------------------------------ neighbours
-- start(S, M, addr): position and neighbour availability of macroblock addr
function Mb.start(S: any, M: any, addr: number) function Mb.start(S: any, M: any, addr: number)
local mbW = S.mbW local mbW = S.mbW
local x, y = addr % mbW, addr // mbW local x, y = addr % mbW, addr // mbW
@@ -141,7 +134,7 @@ function Mb.start(S: any, M: any, addr: number)
M.qpd = 0 M.qpd = 0
end end
-- nC(S, M, bx, by) -> nC of luma block (bx, by) (9.2.1) -- nC of luma block (bx, by) (9.2.1)
function Mb.nC(S: any, M: any, bx: number, by: number): number function Mb.nC(S: any, M: any, bx: number, by: number): number
local g = M.g0 + by * S.w4 + bx local g = M.g0 + by * S.w4 + bx
local nzc = S.nzc local nzc = S.nzc
@@ -157,7 +150,6 @@ function Mb.nC(S: any, M: any, bx: number, by: number): number
return 0 return 0
end end
-- nCc(S, M, tab, bx, by) -> nC of chroma AC block (bx, by) of the plane whose counts are in tab
function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number
local cw = S.cw4 local cw = S.cw4
local g = M.c0 + by * cw + bx local g = M.c0 + by * cw + bx
@@ -173,7 +165,7 @@ function Mb.nCc(S: any, M: any, tab: { number }, bx: number, by: number): number
return 0 return 0
end end
-- predMode(S, M, bx, by) -> predIntra4x4PredMode / predIntra8x8PredMode of the block whose top-left 4x4 is (bx, by) -- predIntra4x4PredMode / predIntra8x8PredMode (8.3.1.1 / 8.3.2.1)
function Mb.predMode(S: any, M: any, bx: number, by: number): number function Mb.predMode(S: any, M: any, bx: number, by: number): number
local la = bx > 0 or M.iL local la = bx > 0 or M.iL
local ta = by > 0 or M.iT local ta = by > 0 or M.iT
@@ -186,9 +178,6 @@ function Mb.predMode(S: any, M: any, bx: number, by: number): number
return ((a < b) and (a) or (b)) return ((a < b) and (a) or (b))
end end
-- ------------------------------------------------------------------------------------------------ motion vectors
-- neighbour(S, M, list, nx, ny) -> ref (UNAVAIL when not available), mvx, mvy of the 4x4 at (nx, ny) relative to the
-- macroblock (nx, ny in -1 .. 4)
local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number) local function neighbour(S: any, M: any, refs: { number }, mvs: { number }, nx: number, ny: number): (number, number, number)
local ok local ok
if ny < 0 then if ny < 0 then
@@ -221,8 +210,7 @@ local function median(a: number, b: number, c: number): number
return max(min(a, b), min(max(a, b), c)) return max(min(a, b), min(max(a, b), c))
end end
-- mvp(S, M, list, x, y, w, ref, shape) -> mvpLX for the partition at (x, y) (4x4 units) of width w with reference -- shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right (8.4.1.3)
-- index ref. shape: 0 generic, 1 = 16x8 upper, 2 = 16x8 lower, 3 = 8x16 left, 4 = 8x16 right
local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number) local function mvp(S: any, M: any, list: number, x: number, y: number, w: number, ref: number, shape: number): (number, number)
local pic = S.pic local pic = S.pic
local refs = ((list == 0) and (pic.ref0) or (pic.ref1)) local refs = ((list == 0) and (pic.ref0) or (pic.ref1))
@@ -275,7 +263,6 @@ local function mvp(S: any, M: any, list: number, x: number, y: number, w: number
end end
Mb.mvp = mvp Mb.mvp = mvp
-- set(S, M, x, y, w, h, r0, m0x, m0y, r1, m1x, m1y): motion data of a region into the picture grids
local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number) local function set(S: any, M: any, x: number, y: number, w: number, h: number, r0: number, m0x: number, m0y: number, r1: number, m1x: number, m1y: number)
local pic = S.pic local pic = S.pic
local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1 local ref0, ref1, mv0, mv1, uid0, uid1 = pic.ref0, pic.ref1, pic.mv0, pic.mv1, pic.uid0, pic.uid1
@@ -302,7 +289,6 @@ local function set(S: any, M: any, x: number, y: number, w: number, h: number, r
M.nreg += 1 M.nreg += 1
end end
-- clipping helpers
local function clip3(lo: number, hi: number, v: number): number local function clip3(lo: number, hi: number, v: number): number
return min(max(v, lo), hi) return min(max(v, lo), hi)
end end
@@ -315,7 +301,7 @@ local function tdiv(a: number, b: number): number
return -math.floor(-q) return -math.floor(-q)
end end
-- distScale(cur, poc0, poc1) -> DistScaleFactor (8-195 .. 8-198), or nil when td is 0 -- DistScaleFactor (8-195 .. 8-198), nil when td is 0
function Mb.distScale(cur: number, poc0: number, poc1: number): number? function Mb.distScale(cur: number, poc0: number, poc1: number): number?
local tb = clip3(-128, 127, cur - poc0) local tb = clip3(-128, 127, cur - poc0)
local td = clip3(-128, 127, poc1 - poc0) local td = clip3(-128, 127, poc1 - poc0)
@@ -326,7 +312,7 @@ function Mb.distScale(cur: number, poc0: number, poc1: number): number?
return clip3(-1024, 1023, (tb * tx + 32) // 64) return clip3(-1024, 1023, (tb * tx + 32) // 64)
end end
-- pskip(S, M): P_Skip motion (8.4.1.1) -- P_Skip motion (8.4.1.1)
local function pskip(S: any, M: any) local function pskip(S: any, M: any)
local mx, my = 0, 0 local mx, my = 0, 0
if M.aL and M.aT then if M.aL and M.aT then
@@ -340,7 +326,7 @@ local function pskip(S: any, M: any)
set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0) set(S, M, 0, 0, 4, 4, 0, mx, my, -1, 0, 0)
end end
-- colocated(S, M, bx, by) -> refIdxCol (-1: intra / none), mvCol x, y, uid of the referenced picture (8.4.1.2.1) -- refIdxCol (-1: intra / none), mvCol (8.4.1.2.1)
local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number) local function colocated(S: any, M: any, bx: number, by: number): (number, number, number, number)
local col = S.colPic local col = S.colPic
if S.direct8x8 then if S.direct8x8 then
@@ -369,7 +355,7 @@ local function minPositive(a: number, b: number): number
return ((a > b) and (a) or (b)) return ((a > b) and (a) or (b))
end end
-- spatialRefs(S, M): the macroblock-level references and predictors of spatial direct (8.4.1.2.2), cached in M -- spatial direct references and predictors (8.4.1.2.2)
local function spatialRefs(S: any, M: any) local function spatialRefs(S: any, M: any)
local pic = S.pic local pic = S.pic
local r0, r1 = -1, -1 local r0, r1 = -1, -1
@@ -410,7 +396,6 @@ local function spatialRefs(S: any, M: any)
M.dReady = true M.dReady = true
end end
-- direct8(S, M, i8): direct motion of 8x8 quadrant i8 (B_Skip, B_Direct_16x16, B_Direct_8x8)
local function direct8(S: any, M: any, i8: number) local function direct8(S: any, M: any, i8: number)
local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2 local x0, y0 = (i8 % 2) * 2, (i8 // 2) * 2
local step = ((S.direct8x8) and (2) or (1)) local step = ((S.direct8x8) and (2) or (1))
@@ -459,12 +444,10 @@ local function direct8(S: any, M: any, i8: number)
end end
end end
-- partition geometry (4x4 units) of the sub-macroblock shapes
local SUB_N = { 1, 2, 2, 4 } local SUB_N = { 1, 2, 2, 4 }
local SUB_W = { 2, 2, 1, 1 } local SUB_W = { 2, 2, 1, 1 }
local SUB_H = { 2, 1, 2, 1 } local SUB_H = { 2, 1, 2, 1 }
-- motion(S, M): motion vectors of an inter macroblock into the grids, and its MC regions
local function motion(S: any, M: any) local function motion(S: any, M: any)
local kind = M.kind local kind = M.kind
M.dReady = false M.dReady = false
@@ -551,8 +534,6 @@ local function motion(S: any, M: any)
end end
Mb.motion = motion Mb.motion = motion
-- ------------------------------------------------------------------------------------------------ motion compensation
-- predict(S, M, pic, P, list, x, y, w, h, mvx, mvy, plane): one list's prediction samples of a region into P
local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number) local function predLuma(S: any, ref: any, P: { number }, px: number, py: number, w: number, h: number, mvx: number, mvy: number)
local W, H = S.mbW * 16, S.mbH * 16 local W, H = S.mbW * 16, S.mbH * 16
local ix = px + mvx // 4 local ix = px + mvx // 4
@@ -577,7 +558,6 @@ local function refPic(list: { any }, r: number): any
return list[r + 1] or list[1] return list[r + 1] or list[1]
end end
-- mc(S, M): inter prediction of every region of the macroblock into the current picture
local function mc(S: any, M: any) local function mc(S: any, M: any)
local pic = S.pic local pic = S.pic
local reg = M.reg local reg = M.reg
@@ -604,7 +584,6 @@ local function mc(S: any, M: any)
local lo = pic.yo + py * ys + px local lo = pic.yo + py * ys + px
local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2 local cx, cy, cw, ch = M.x * 8 + x * 2, M.y * 8 + y * 2, w * 2, h * 2
local co = pic.co + cy * cs + cx local co = pic.co + cy * cs + cx
-- weights for this pair
local bi = ref0 ~= nil and ref1 ~= nil local bi = ref0 ~= nil and ref1 ~= nil
local explicit = wm == 1 local explicit = wm == 1
local implicitW0, implicitW1 = 32, 32 local implicitW0, implicitW1 = 32, 32
@@ -664,7 +643,6 @@ local function mc(S: any, M: any)
end end
end end
-- ------------------------------------------------------------------------------------------------ residual
local function lumaResidual(S: any, M: any) local function lumaResidual(S: any, M: any)
local pic = S.pic local pic = S.pic
local b, s = pic.y, pic.ys local b, s = pic.y, pic.ys
@@ -716,7 +694,6 @@ local function chromaResidual(S: any, M: any)
end end
end end
-- ------------------------------------------------------------------------------------------------ intra
local function intraLuma(S: any, M: any) local function intraLuma(S: any, M: any)
local pic = S.pic local pic = S.pic
local b, s = pic.y, pic.ys local b, s = pic.y, pic.ys
@@ -821,8 +798,6 @@ local function pcm(S: any, M: any)
end end
end end
-- ------------------------------------------------------------------------------------------------ macroblock
-- recon(S, M): reconstruct the parsed macroblock and store what later macroblocks / deblocking need
function Mb.recon(S: any, M: any) function Mb.recon(S: any, M: any)
local kind = M.kind local kind = M.kind
local addr = M.addr + 1 local addr = M.addr + 1
@@ -838,7 +813,6 @@ function Mb.recon(S: any, M: any)
local nzDb = S.nzDb local nzDb = S.nzDb
local g0 = M.g0 local g0 = M.g0
if kind <= K_PCM then if kind <= K_PCM then
-- intra: no motion
local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1 local ref0, ref1, uid0, uid1 = pic.ref0, pic.ref1, pic.uid0, pic.uid1
for j = 0, 3 do for j = 0, 3 do
local g = g0 + j * w4 local g = g0 + j * w4
@@ -888,7 +862,6 @@ function Mb.recon(S: any, M: any)
chromaResidual(S, M) chromaResidual(S, M)
end end
-- skip(S, M, kind): a P_Skip / B_Skip macroblock (no residual)
function Mb.skip(S: any, M: any, kind: number) function Mb.skip(S: any, M: any, kind: number)
M.kind = kind M.kind = kind
M.cbp = 0 M.cbp = 0
+5 -13
View File
@@ -1,9 +1,8 @@
--!strict --!strict
--!native --!native
-- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists with -- codecs/video/H264/Params: sequence and picture parameter sets (ITU-T H.264 7.3.2.1 / 7.3.2.2 / E.1), scaling lists
-- the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the -- with the fall-back rules A and B (7.4.2.1.1 / table 7-2), and the dequantisation tables built from them (8.5.9: the
-- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)). Written from the spec. -- LevelScale4x4 / LevelScale8x8 functions, premultiplied by 2^(qP / 6)).
-- Never throws: parse functions return nil, "message".
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
local Tables = require("@rosetta/codecs/video/H264/Tables") local Tables = require("@rosetta/codecs/video/H264/Tables")
@@ -18,7 +17,7 @@ local MAX_DPB_MBS = { [9] = 396, [10] = 396, [11] = 900, [12] = 2376, [13] = 237
local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8 local ZIGZAG4, ZIGZAG8 = Tables.ZIGZAG4, Tables.ZIGZAG8
-- scaling_list(): returns the list in raster order, or "default" (useDefaultScalingMatrixFlag) -- scaling_list(): raster order, or "default" (useDefaultScalingMatrixFlag)
local function scalingList(r: Bitstream.Reader, size: number): any local function scalingList(r: Bitstream.Reader, size: number): any
local list = table.create(size, 0) local list = table.create(size, 0)
local last, nxt = 8, 8 local last, nxt = 8, 8
@@ -74,7 +73,7 @@ end
local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16) local FLAT16, FLAT64 = table.create(16, 16), table.create(64, 16)
-- resolve(lists, fallback) -> 12 raster lists. fallback: nil = rule A (defaults), else the 12 lists of the SPS (rule B) -- fallback nil = rule A (defaults), else the SPS's 12 lists (rule B)
local function resolve(lists: { any }, fallback: { { number } }?): { { number } } local function resolve(lists: { any }, fallback: { { number } }?): { { number } }
local out = {} local out = {}
for i = 1, 12 do for i = 1, 12 do
@@ -94,7 +93,6 @@ local function resolve(lists: { any }, fallback: { { number } }?): { { number }
return out return out
end end
-- ------------------------------------------------------------------------------------------------ vui
local function hrd(r: Bitstream.Reader) local function hrd(r: Bitstream.Reader)
local cnt = ue(r) local cnt = ue(r)
if cnt > 31 then if cnt > 31 then
@@ -167,8 +165,6 @@ local function vui(r: Bitstream.Reader, sps: any)
end end
end end
-- ------------------------------------------------------------------------------------------------ sps
-- sps(r) -> the SPS table | nil, message. r is positioned after the NAL header.
function Params.sps(r: Bitstream.Reader): (any, string?) function Params.sps(r: Bitstream.Reader): (any, string?)
local sps: any = {} local sps: any = {}
sps.profile = u(r, 8) sps.profile = u(r, 8)
@@ -289,8 +285,6 @@ function Params.sps(r: Bitstream.Reader): (any, string?)
return sps, nil return sps, nil
end end
-- ------------------------------------------------------------------------------------------------ pps
-- pps(r, spsTable) -> the PPS | nil, message. spsTable: id -> SPS (needed for the scaling list count)
function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?) function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, string?)
local pps: any = {} local pps: any = {}
pps.id = ue(r) pps.id = ue(r)
@@ -351,7 +345,6 @@ function Params.pps(r: Bitstream.Reader, spsTable: { [number]: any }): (any, str
return pps, nil return pps, nil
end end
-- ------------------------------------------------------------------------------------------------ dequantisation
local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } } local V4 = { { 10, 16, 13 }, { 11, 18, 14 }, { 13, 20, 16 }, { 14, 23, 18 }, { 16, 25, 20 }, { 18, 29, 23 } }
local V8 = { local V8 = {
{ 20, 18, 32, 19, 25, 24 }, { 20, 18, 32, 19, 25, 24 },
@@ -424,7 +417,6 @@ local function build(lists: { { number } }): any
return { d4 = d4, d8 = d8 } return { d4 = d4, d8 = d8 }
end end
-- dequant(sps, pps, cache) -> the dequant tables for this pair (cache: a table kept by the decoder, by content)
function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any function Params.dequant(sps: any, pps: any, cache: { [string]: any }): any
local lists: { { number } } local lists: { { number } }
if pps.scalingLists then if pps.scalingLists then
+2 -4
View File
@@ -1,9 +1,8 @@
--!strict --!strict
--!native --!native
-- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and -- codecs/video/H264/Slice: the slice header (ITU-T H.264 7.3.3): ref_pic_list_modification, pred_weight_table and
-- dec_ref_pic_marking. Written from the spec. Frame coding only: field pictures (field_pic_flag = 1), MBAFF, -- dec_ref_pic_marking. Frame coding only: field pictures, MBAFF, SP / SI, separate colour planes and redundant
-- SP / SI slices, separate colour planes and redundant pictures return "unsupported: ...". -- pictures return "unsupported: ...".
-- Never throws: header() returns nil, "message".
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se local u, u1, ue, se = Bitstream.u, Bitstream.u1, Bitstream.ue, Bitstream.se
@@ -62,7 +61,6 @@ local function weights(r: Bitstream.Reader, n: number, lw: number, cw: number, c
return t return t
end end
-- header(r, nalType, nalRefIdc, spsTable, ppsTable) -> sh | nil, message
function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?) function Slice.header(r: Bitstream.Reader, nalType: number, nalRefIdc: number, spsTable: { [number]: any }, ppsTable: { [number]: any }): (any, string?)
local sh: any = {} local sh: any = {}
sh.nalType = nalType sh.nalType = nalType
+3 -6
View File
@@ -1,11 +1,8 @@
--!strict --!strict
--!native --!native
-- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC code tables 9-5, 9-7, 9-8, 9-9, 9-10; CABAC context -- codecs/video/H264/Tables: the constant tables of ITU-T H.264 (CAVLC 9-5, 9-7..9-10; CABAC init 9-12..9-24,
-- initialisation tables 9-12..9-24, rangeTabLPS 9-44 and the state transitions 9-45; the chroma QP table 8-15; the -- rangeTabLPS 9-44, transitions 9-45; chroma QP 8-15; me(v) CBP 9-4; scaling lists 7-3 / 7-4; zig-zag 8-12 / 8-13;
-- me(v) coded_block_pattern mapping 9-4; default scaling lists 7-3 / 7-4; zig-zag scans 8-12 / 8-13; table 9-43; the -- 9-43; deblocking 8-16 / 8-17). Values from openh264 2.x (BSD-2-Clause, licenses/openh264-LICENSE.txt).
-- deblocking alpha / beta / tC0 tables 8-16 / 8-17). Values extracted from openh264 2.x (BSD-2-Clause,
-- licenses/openh264-LICENSE.txt): encoder_data_tables.cpp, common_tables.cpp, decoder_data_tables.cpp,
-- wels_common_basis.h, deblocking.cpp. Flat 1-based arrays; the layouts are noted at each table.
local T = {} local T = {}
-- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff, -- coeff_token per nC class (0: 0<=nC<2, 1: 2<=nC<4, 2: 4<=nC<8, 3: 8<=nC, 4: nC=-1 chroma DC): { code, len, TotalCoeff,
+3 -14
View File
@@ -1,11 +1,8 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5: the 4x4 and 8x8 integer IDCTs with the residual -- codecs/video/H264/Transform: the inverse transforms of ITU-T H.264 8.5 (4x4 / 8x8 IDCT 8.5.12.2 / 8.5.13.2 / 8.5.14,
-- added to the prediction in the plane (8.5.12.2 / 8.5.13.2 / 8.5.14), the 4x4 luma DC and 2x2 chroma DC Hadamard -- luma DC / chroma DC Hadamard 8.5.10 / 8.5.11.2). Coefficients come dequantised, raster order, at base + 1; zeroed after use.
-- transforms with their scaling (8.5.10 / 8.5.11.2). Written from the spec. Coefficients are dequantised already
-- (Params.dequant), raster order, in a 1-based table at `base + 1 ...`; the functions zero what they read.
-- Never throws.
local readu8, writeu8 = buffer.readu8, buffer.writeu8 local readu8, writeu8 = buffer.readu8, buffer.writeu8
local Transform = {} local Transform = {}
@@ -15,9 +12,7 @@ local function clip(v: number): number
return min(max(v, 0), 255) return min(max(v, 0), 255)
end end
-- add4(c, base, b, o, s): inverse 4x4 transform of c[base + 1 .. base + 16], added to the 4x4 block at b[o] (stride s)
function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number) function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: number)
-- rows
for i = 0, 3 do for i = 0, 3 do
local k = base + i * 4 local k = base + i * 4
local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4] local d0, d1, d2, d3 = c[k + 1], c[k + 2], c[k + 3], c[k + 4]
@@ -30,7 +25,6 @@ function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: nu
c[k + 3] = f - g c[k + 3] = f - g
c[k + 4] = e - h c[k + 4] = e - h
end end
-- columns
for j = 0, 3 do for j = 0, 3 do
local k = base + j local k = base + j
local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13] local d0, d1, d2, d3 = c[k + 1], c[k + 5], c[k + 9], c[k + 13]
@@ -50,7 +44,6 @@ function Transform.add4(c: { number }, base: number, b: buffer, o: number, s: nu
end end
end end
-- addDc4(dc, b, o, s): a 4x4 block whose only coefficient is the (dequantised) DC
function Transform.addDc4(dc: number, b: buffer, o: number, s: number) function Transform.addDc4(dc: number, b: buffer, o: number, s: number)
local v = (dc + 32) // 64 local v = (dc + 32) // 64
if v == 0 then if v == 0 then
@@ -67,11 +60,9 @@ end
local T8 = table.create(64, 0) local T8 = table.create(64, 0)
-- add8(c, base, b, o, s): inverse 8x8 transform of c[base + 1 .. base + 64] added to the 8x8 block at b[o]
function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number) function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: number)
for pass = 0, 1 do for pass = 0, 1 do
for i = 0, 7 do for i = 0, 7 do
-- pass 0: rows of c into T8; pass 1: columns of T8
local d0, d1, d2, d3, d4, d5, d6, d7 local d0, d1, d2, d3, d4, d5, d6, d7
if pass == 0 then if pass == 0 then
local k = base + i * 8 local k = base + i * 8
@@ -128,8 +119,7 @@ function Transform.add8(c: { number }, base: number, b: buffer, o: number, s: nu
end end
end end
-- lumaDc(dc, m, c): the Intra_16x16 DC levels dc[1..16] (raster 4x4 matrix) -> inverse Hadamard, scaled with the -- m = LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)
-- DC multiplier m (LevelScale4x4(qP % 6, 0, 0) * 2^(qP / 6)), stored at c[blk * 16 + 1] (blk = raster block index)
function Transform.lumaDc(dc: { number }, m: number, c: { number }) function Transform.lumaDc(dc: { number }, m: number, c: { number })
for i = 0, 3 do for i = 0, 3 do
local k = i * 4 local k = i * 4
@@ -157,7 +147,6 @@ function Transform.lumaDc(dc: { number }, m: number, c: { number })
end end
end end
-- chromaDc(dc, base, m, c, cbase): the 2x2 chroma DC levels dc[base + 1 .. base + 4] -> c[cbase + blk * 16 + 1]
function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number) function Transform.chromaDc(dc: { number }, base: number, m: number, c: { number }, cbase: number)
local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] local c0, c1, c2, c3 = dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4]
dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0 dc[base + 1], dc[base + 2], dc[base + 3], dc[base + 4] = 0, 0, 0, 0
+13 -57
View File
@@ -1,32 +1,8 @@
--!strict --!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 -- codecs/video/H264: an H.264 / AVC (ITU-T H.264 | ISO/IEC 14496-10) video decoder in pure Luau, bit-exact with ffmpeg.
-- video/h264 format (raw Annex B streams) and the MP4 / MKV / AVI / TS video tracks use it. Clean-room, written from the -- Clean-room from the spec; constant tables from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). 8-bit 4:2:0
-- spec; constant tables taken from openh264 (BSD-2-Clause, licenses/openh264-LICENSE.txt). Bit-exact with the -- Constrained Baseline, Main and High. UNSUPPORTED: interlaced coding (field pictures, MBAFF), 4:0:0 / 4:2:2 / 4:4:4,
-- reference decoder (checked against ffmpeg per frame). -- bit depths above 8, lossless, FMO / ASO, SP / SI slices, data partitioning, SVC / MVC (their NAL units are ignored).
-- 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 Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Bitstream = require("@rosetta/codecs/video/H264/Bitstream") local Bitstream = require("@rosetta/codecs/video/H264/Bitstream")
@@ -38,15 +14,15 @@ local H264 = {}
export type Options = { export type Options = {
avcC: buffer?, -- AVCDecoderConfigurationRecord (MP4 'avcC', Matroska CodecPrivate): samples are length-prefixed 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) 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) maxPixels: number?,
lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering) lowDelay: boolean?,
deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true deblock: boolean?,
yield: (() -> ())?, -- a cooperative yield point (see Decoder Options.yield): pcall'ed every 16 macroblocks yield: (() -> ())?,
} }
export type Frame = { export type Frame = {
image: Types.Image, -- yuv420p, cropped to the display size; image.meta.source = { format = "h264", poc, ... } image: Types.Image,
pts: number, -- the pts passed with the access unit holding the picture (default: its decoding index) pts: number,
duration: number, duration: number,
poc: number, poc: number,
keyframe: boolean, keyframe: boolean,
@@ -83,7 +59,6 @@ local function status(self: H264Decoder): Err.Err?
return nil return nil
end end
-- newDecoder(opts?) -> H264Decoder | nil, Err
function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?) function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?)
local o = opts or {} local o = opts or {}
if type(o) ~= "table" then if type(o) ~= "table" then
@@ -100,8 +75,6 @@ function H264.newDecoder(opts: Options?): (H264Decoder?, Err.Err?)
return self, nil return self, nil
end 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?) function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err?)
local b = toBuffer(avcC) local b = toBuffer(avcC)
if not b then if not b then
@@ -127,8 +100,6 @@ function DecoderMeta.configure(self: H264Decoder, avcC: any): (boolean?, Err.Err
return true, nil return true, nil
end 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?) function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: number?, len: number?): ({ Frame }?, Err.Err?)
local b = toBuffer(data) local b = toBuffer(data)
if not b then if not b then
@@ -165,14 +136,12 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num
return frames, nil return frames, nil
end end
-- decoder:flush() -> { Frame }: ends the stream (the current picture and every picture held for reordering)
function DecoderMeta.flush(self: H264Decoder): { Frame } function DecoderMeta.flush(self: H264Decoder): { Frame }
Decoder.flush(self.state) Decoder.flush(self.state)
status(self) status(self)
return Decoder.take(self.state) return Decoder.take(self.state)
end 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?) function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?)
local dec, err = H264.newDecoder(opts) local dec, err = H264.newDecoder(opts)
if not dec then if not dec then
@@ -188,7 +157,6 @@ function H264.decodeAll(data: any, opts: Options?): ({ Frame }?, Err.Err?)
return frames, nil return frames, nil
end end
-- parseAvcC(buf) -> { lengthSize, profile, level, nals } | nil, Err
function H264.parseAvcC(data: any): (any, Err.Err?) function H264.parseAvcC(data: any): (any, Err.Err?)
local b = toBuffer(data) local b = toBuffer(data)
if not b then if not b then
@@ -201,11 +169,6 @@ function H264.parseAvcC(data: any): (any, Err.Err?)
return cfg, nil return cfg, nil
end 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?) 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, local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay,
yield = opts and opts.yield } yield = opts and opts.yield }
@@ -234,8 +197,7 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
pts = outIndex or 0 pts = outIndex or 0
outIndex = pts + 1 outIndex = pts + 1
elseif #pool > 0 then elseif #pool > 0 then
-- pictures leave in display order: they take the packet timestamps in increasing order (right for -- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times)
-- MP4 / MKV / TS pts, and for AVI whose packets only carry decode-order times)
pts = table.remove(pool, 1) pts = table.remove(pool, 1)
end end
table.insert(queue, { f.image, pts, f.keyframe }) 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 return self, nil
end end
-- accessUnits(buf, off?, len?) -> { off, len, keyframe, ... } (triples): an Annex B stream cut into access units -- 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
-- (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
-- after a slice). keyframe: the unit holds an IDR slice.
function H264.accessUnits(data: any, off: number?, len: number?): { any } function H264.accessUnits(data: any, off: number?, len: number?): { any }
local b = toBuffer(data) local b = toBuffer(data)
local out = {} local out = {}
@@ -312,7 +273,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any }
end end
end end
if boundary then if boundary then
-- the unit ends where this NAL's start code begins
local s = p local s = p
while s > start and buffer.readu8(b, s - 1) ~= 1 do while s > start and buffer.readu8(b, s - 1) ~= 1 do
s -= 1 s -= 1
@@ -341,8 +301,6 @@ function H264.accessUnits(data: any, off: number?, len: number?): { any }
return out return out
end 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?) function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
local parts = {} local parts = {}
local lengthSize = 4 local lengthSize = 4
@@ -366,7 +324,6 @@ function H264.toAnnexB(config: buffer?, sample: buffer): (buffer?, Err.Err?)
return buffer.fromstring(table.concat(parts)), nil return buffer.fromstring(table.concat(parts)), nil
end 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 function H264.info(data: any): any
local b = toBuffer(data) local b = toBuffer(data)
if not b then if not b then
@@ -405,7 +362,6 @@ function H264.info(data: any): any
return nil return nil
end 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) function H264.planes(img: Types.Image): (number, number, number, number, number)
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2 local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
local ny = img.width * img.height local ny = img.width * img.height
+5 -13
View File
@@ -1,14 +1,10 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames: 24-bit colour (codebook entries of 4 luma + 2 chroma, or 4 -- codecs/video/Legacy/Cinepak: Cinepak ('cvid') frames, 24-bit colour and 8-bit palettised.
-- luma for grey), and 8-bit palettised streams (entries are palette indexes). Written from the format description -- From MultimediaWiki "Cinepak", bit-exact with ffmpeg: a frame header (flags, size, width, height, strip count), strips
-- (MultimediaWiki "Cinepak"): a frame header (flags, size, width, height, strip count), strips with their own V1 / V4 -- with V1 / V4 codebooks (inherited from the strip above unless the flags say otherwise) and vector chunks.
-- codebooks (full or partial updates, kept per strip between frames, inherited from the strip above unless the frame -- Colour entries: r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped.
-- flags say otherwise) and the vector chunks (intra, inter with skip flags, V1-only). Colour codebook entries are
-- converted once with the Cinepak YUV formula (r = y + 2v, g = y - u/2 - v, b = y + 2u, clamped). Sega FILM's extra
-- header bytes are detected on the first frame. Paints over the previous picture. Bit-exact with ffmpeg's cinepak
-- decoder. Never throws: every read is range-checked against its chunk.
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8 local readu8, readu32, writeu32, writeu8 = buffer.readu8, buffer.readu32, buffer.writeu32, buffer.writeu8
@@ -93,7 +89,7 @@ local function codebook(books: buffer, book: number, id: number, d: buffer, p: n
end end
end end
-- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only); false on truncated data -- the vectors of a strip (ids 0x30 intra, 0x31 inter with skip flags, 0x32 V1 only)
local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number, local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: number, id: number, d: buffer, p: number,
stop: number, x1: number, y1: number, x2: number, y2: number): boolean stop: number, x1: number, y1: number, x2: number, y2: number): boolean
local stride = pic.stride local stride = pic.stride
@@ -194,8 +190,6 @@ local function vectors(pic: Picture.Picture, books: buffer, v4: number, v1: numb
return true return true
end end
-- decode(pic, data, state, hasPalette) -> picture?, message: true = a picture; false + nil = no picture for this
-- packet (an empty frame); false + message = an error
function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?) function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette: boolean): (boolean, string?)
local n = buffer.len(d) local n = buffer.len(d)
if n < 10 then if n < 10 then
@@ -238,7 +232,6 @@ function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette:
local p = 10 + skip local p = 10 + skip
strips = math.min(strips, MAX_STRIPS) strips = math.min(strips, MAX_STRIPS)
local books = st.books local books = st.books
-- the coded area: the size rounded up to whole blocks (the picture's plane)
local cw, ch = pic.stride, pic.rows local cw, ch = pic.stride, pic.rows
local y0 = 0 local y0 = 0
for i = 0, strips - 1 do for i = 0, strips - 1 do
@@ -263,7 +256,6 @@ function Cinepak.decode(pic: Picture.Picture, d: buffer, st: State, newPalette:
if i > 0 and band(flags, 1) == 0 then if i > 0 and band(flags, 1) == 0 then
buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK) buffer.copy(books, v4, books, v4 - 2 * BOOK, 2 * BOOK)
end end
-- the strip's chunks: codebooks, then one vector chunk
-- (strips start on block boundaries in every known stream: the plane holds whole blocks only) -- (strips start on block boundaries in every known stream: the plane holds whole blocks only)
if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then if sx2 > cw or sy2 > ch or sx1 >= sx2 or sy1 >= sy2 or band(sx1, 3) ~= 0 or band(sy1, 3) ~= 0 then
return true, nil return true, nil
+7 -14
View File
@@ -1,15 +1,12 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is -- codecs/video/Legacy/Flic: Autodesk Animator FLI / FLC frames (the F1FA frame chunks; the file format is video/fli).
-- video/fli). Written from the FLIC file format description (Jim Kent's "FLC - Animator Pro Flic Files", Dr. Dobb's -- From Jim Kent's "FLC - Animator Pro Flic Files" (Dr. Dobb's 1993) and MultimediaWiki "Flic Video", bit-exact with
-- 1993; MultimediaWiki "Flic Video"). 8-bit palettised: COLOR_256 (4), COLOR_64 (11, 6-bit entries widened by bit -- ffmpeg. 8-bit: COLOR_256 (4), COLOR_64 (11), DELTA_FLC / SS2 (7), DELTA_FLI / LC (12), BLACK (13), BYTE_RUN / BRUN
-- replication), DELTA_FLC / SS2 (7: word runs, line skips, last-byte opcode), DELTA_FLI / LC (12: byte runs), BLACK -- (15), FLI_COPY (16, rows padded to 4), PSTAMP (18). 15 / 16 / 24-bit FLC and FLX (DTA): DELTA / DTA_LC, BLACK, BRUN,
-- (13), BYTE_RUN / BRUN (15), FLI_COPY (16, rows padded to 4), PSTAMP (18, skipped). 15 / 16 / 24-bit FLC and FLX -- DTA_BRUN (25), COPY / DTA_COPY (16 / 26); 5-5-5 / 5-6-5 little-endian words or B, G, R bytes.
-- (DTA): DELTA / DTA_LC (pixel runs), BLACK, BRUN (byte runs), DTA_BRUN (25, pixel runs), COPY / DTA_COPY (16 / 26); -- Not supported: 1-bit FLICs, the Magic Carpet 6-bit COLOR_256 variant.
-- pixels are 5-5-5 / 5-6-5 little-endian words or B, G, R bytes. Not supported: 1-bit FLICs, the Magic Carpet
-- 6-bit COLOR_256 variant. Paints over the previous picture. Bit-exact with ffmpeg's flic decoder on valid frames.
-- Never throws: reads past the frame give zeros, every write is range-checked (a damaged frame gives no picture).
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
@@ -18,14 +15,12 @@ local bfill = buffer.fill
local Flic = {} local Flic = {}
-- the decoding state of one stream: a byte plane (stride = width * bytes per pixel) and the palette
export type State = { export type State = {
pic: Picture.Picture, pic: Picture.Picture,
depth: number, -- 8, 15, 16, 24 depth: number, -- 8, 15, 16, 24
bpp: number, -- bytes per pixel bpp: number,
} }
-- state(w, h, depth) -> State | nil, message
function Flic.state(w: number, h: number, depth: number): (State?, string?) function Flic.state(w: number, h: number, depth: number): (State?, string?)
local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0 local bpp = if depth == 8 then 1 elseif depth == 15 or depth == 16 then 2 elseif depth == 24 then 3 else 0
if bpp == 0 then if bpp == 0 then
@@ -40,7 +35,6 @@ local function s8(v: number): number
return if v >= 128 then v - 256 else v return if v >= 128 then v - 256 else v
end end
-- decode(st, data) -> true | false, message
function Flic.decode(st: State, d: buffer): (boolean, string?) function Flic.decode(st: State, d: buffer): (boolean, string?)
local pic = st.pic local pic = st.pic
local px = pic.idx :: buffer local px = pic.idx :: buffer
@@ -336,7 +330,6 @@ function Flic.decode(st: State, d: buffer): (boolean, string?)
return true, nil return true, nil
end end
-- image(st) -> a fresh rgba8 Image
function Flic.image(st: State): Types.Image function Flic.image(st: State): Types.Image
local pic = st.pic local pic = st.pic
if st.bpp == 1 then if st.bpp == 1 then
+5 -10
View File
@@ -1,12 +1,10 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM) frames, 8-bit palettised and 16-bit -- codecs/video/Legacy/Msvideo1: Microsoft Video 1 (CRAM / MSVC / WHAM), 8-bit palettised and 16-bit X-R-G-B 1-5-5-5.
-- X-R-G-B 1-5-5-5. Written from the format description (MultimediaWiki "Microsoft Video 1"): 4x4 blocks, block rows -- From MultimediaWiki "Microsoft Video 1", bit-exact with ffmpeg: 4x4 blocks, block rows (and rows in a block) bottom-up;
-- bottom-up (rows of a block bottom-up too), each block a 16-bit code: a skip count (0x84xx - 0x87xx), a 2-colour -- a 16-bit code per block: skip (0x84xx - 0x87xx), 2-colour (16 flag bits + 2 colours; at 16 bits c0 bit 15 set = 8-colour,
-- block (16 flag bits + 2 colours; at 16 bits a first colour with bit 15 set makes it an 8-colour block, one colour -- a pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), else 1-colour.
-- pair per quadrant; at 8 bits codes >= 0x9000 are 8-colour), or a 1-colour block. Paints over the previous picture.
-- Bit-exact with ffmpeg's msvideo1 decoder. Never throws: every read is range-checked (a damaged frame stops there).
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32 local readu8, readu16, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu16, buffer.readu32, buffer.writeu8, buffer.writeu32
@@ -14,13 +12,11 @@ local band = bit32.band
local Msvideo1 = {} local Msvideo1 = {}
-- the colour of pixel (x, y) of a block (y = 0 is the block's bottom row) for flag bit f: 2-colour c0 / c1 -- 2-colour: bit set = c0; 8-colour: colours[quadrant * 2 + (bit clear)]
-- (bit set = c0), 8-colour: colours[quadrant * 2 + (bit clear)]
local function quadrant(x: number, y: number): number local function quadrant(x: number, y: number): number
return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0) return (if y >= 2 then 4 else 0) + (if x >= 2 then 2 else 0)
end end
-- decode(pic, data, bits) -> true | false, message (bits = 8: palettised, else 16-bit)
function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?) function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolean, string?)
local n = buffer.len(d) local n = buffer.len(d)
local bw, bh = pic.w // 4, pic.h // 4 local bw, bh = pic.w // 4, pic.h // 4
@@ -50,7 +46,6 @@ function Msvideo1.decode(pic: Picture.Picture, d: buffer, bits: number): (boolea
if a == 0 and b == 0 and total == 0 then if a == 0 and b == 0 and total == 0 then
return true, nil return true, nil
end end
-- the block's bottom-left pixel; its rows go up
local o = (by * 4 + 3) * stride + bx * 4 local o = (by * 4 + 3) * stride + bx * 4
if band(b, 0xFC) == 0x84 then if band(b, 0xFC) == 0x84 then
skip = (b - 0x84) * 256 + a - 1 skip = (b - 0x84) * 256 + a - 1
+2 -11
View File
@@ -1,11 +1,8 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/Picture: the picture every legacy decoder keeps between frames (they are all inter-frame -- codecs/video/Legacy/Picture: the picture the legacy inter-frame decoders paint over (u8 index plane + palette or rgba8).
-- codecs: a packet paints over the previous picture). Palettised codecs keep a u8 index plane and a 256-entry palette, -- 5-5-5 / 5-6-5 widen by bit replication (c << 3 | c >> 2), as ffmpeg's swscale does.
-- direct-colour ones an rgba8 plane; both planes are padded (stride / rows) so the codecs' block and run writes past
-- the visible edge land in range. Also the 5-5-5 / 5-6-5 to 8-bit tables: channels are widened by bit replication
-- (c << 3 | c >> 2), as ffmpeg's swscale does, so the output equals ffmpeg's rgba conversion. New in rosetta.
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Pixels = require("@rosetta/codecs/image/Pixels") local Pixels = require("@rosetta/codecs/image/Pixels")
@@ -23,7 +20,6 @@ export type Picture = {
pal: buffer, -- 256 u32 entries, bytes R, G, B, A pal: buffer, -- 256 u32 entries, bytes R, G, B, A
} }
-- new(w, h, palettised, padW?, padH?, palette?) -> a black picture; padW / padH round the plane up (blocks of 4, ...)
function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture function Picture.new(w: number, h: number, palettised: boolean, padW: number?, padH: number?, palette: buffer?): Picture
local pw, ph = padW or 1, padH or 1 local pw, ph = padW or 1, padH or 1
local stride = ((w + pw - 1) // pw) * pw local stride = ((w + pw - 1) // pw) * pw
@@ -41,7 +37,6 @@ function Picture.new(w: number, h: number, palettised: boolean, padW: number?, p
return p return p
end end
-- image(p) -> a fresh rgba8 Image of the visible w x h
function Picture.image(p: Picture): Types.Image function Picture.image(p: Picture): Types.Image
local w, h = p.w, p.h local w, h = p.w, p.h
local img = Types.Image.new(w, h, "rgba8") local img = Types.Image.new(w, h, "rgba8")
@@ -60,7 +55,6 @@ function Picture.image(p: Picture): Types.Image
return img return img
end end
-- setPalette(p, src): a 1024-byte palette (u32 R, G, B, A entries) from a packet or the track
function Picture.setPalette(p: Picture, src: buffer) function Picture.setPalette(p: Picture, src: buffer)
if buffer.len(src) >= 1024 then if buffer.len(src) >= 1024 then
buffer.copy(p.pal, 0, src, 0, 1024) buffer.copy(p.pal, 0, src, 0, 1024)
@@ -70,7 +64,6 @@ end
local lut555: buffer? = nil local lut555: buffer? = nil
local lut565: buffer? = nil local lut565: buffer? = nil
-- rgb555() -> u32 table: X-R-G-B 1-5-5-5 value -> rgba8 pixel (opaque); 32768 entries
function Picture.rgb555(): buffer function Picture.rgb555(): buffer
local t = lut555 local t = lut555
if t then if t then
@@ -86,7 +79,6 @@ function Picture.rgb555(): buffer
return b return b
end end
-- rgb565() -> u32 table: R-G-B 5-6-5 value -> rgba8 pixel; 65536 entries
function Picture.rgb565(): buffer function Picture.rgb565(): buffer
local t = lut565 local t = lut565
if t then if t then
@@ -102,7 +94,6 @@ function Picture.rgb565(): buffer
return b return b
end end
-- copy of a picture's plane (for decoders that read the previous picture while writing the next)
function Picture.clonePlane(p: Picture): buffer function Picture.clonePlane(p: Picture): buffer
local src = (p.idx or p.rgba) :: buffer local src = (p.idx or p.rgba) :: buffer
local c = buffer.create(buffer.len(src)) local c = buffer.create(buffer.len(src))
+8 -13
View File
@@ -1,14 +1,11 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey) and -- codecs/video/Legacy/QtRle: QuickTime Animation ('rle ') frames, depths 1, 2, 4, 8 (palettised; 33..40 = grey),
-- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). Written from the format description (Apple QuickTime File -- 16 (X-R-G-B 1-5-5-5), 24 (R, G, B), 32 (A, R, G, B). From Apple QuickTime File Format and MultimediaWiki "Apple
-- Format; MultimediaWiki "Apple QuickTime RLE"): a chunk size, a header (0x0008: start line + line count), then per -- QuickTime RLE", bit-exact with ffmpeg on valid streams: chunk size, header (0x0008: start line + line count), per line
-- line a skip byte and run codes until -1 (0: another skip; < 0: one pixel group repeated; > 0: literal groups). -- a skip byte and codes until -1 (0: another skip; < 0: one group repeated; > 0: literal groups). Groups are 4 pixels at
-- Groups are 4 pixels at 8 bits, 8 at 4 bits, 16 at 2 bits, 1 pixel at 16 / 24 / 32 bits; the 1-bit layout has its -- 8 bits, 8 at 4, 16 at 2, 1 at 16 / 24 / 32. Frames shorter than 8 bytes repeat the picture.
-- own (skip, code) pairs where a skip with bit 7 set moves to the next line. Paints over the previous picture; frames
-- shorter than 8 bytes repeat it. Bit-exact with ffmpeg's qtrle decoder on valid streams. Never throws: every read
-- and write is range-checked (a damaged frame stops where the damage is).
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
@@ -83,8 +80,8 @@ end
-- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups -- 2 / 4 / 8-bit: groups of 16 / 8 / 4 indexes (4 bytes); skips count groups
local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number) local function decodeIdx(px: buffer, stride: number, limit: number, d: buffer, p: number, n: number, row: number, lines: number, bpp: number)
local group = 32 // bpp -- pixels per 4 bytes local group = 32 // bpp
local per = 8 // bpp -- pixels per byte local per = 8 // bpp
local mask = 2 ^ bpp - 1 local mask = 2 ^ bpp - 1
for _ = 1, lines do for _ = 1, lines do
if p >= n then if p >= n then
@@ -224,11 +221,10 @@ local function decodeRgb(px: buffer, stride: number, limit: number, d: buffer, p
end end
end end
-- decode(pic, data, depth) -> true (a picture, possibly the previous one again) | false, message
function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?) function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean, string?)
local n = buffer.len(d) local n = buffer.len(d)
if n < 8 then if n < 8 then
return true, nil -- no change return true, nil
end end
local p = 4 local p = 4
local header = readu8(d, p) * 256 + readu8(d, p + 1) local header = readu8(d, p) * 256 + readu8(d, p + 1)
@@ -264,7 +260,6 @@ function QtRle.decode(pic: Picture.Picture, d: buffer, depth: number): (boolean,
return true, nil return true, nil
end end
-- palettised(depth) -> whether the depth uses a palette; pad(depth) -> the row padding the plane needs
function QtRle.palettised(depth: number): boolean function QtRle.palettised(depth: number): boolean
return depth <= 8 or depth > 32 return depth <= 8 or depth > 32
end end
+8 -20
View File
@@ -2,17 +2,12 @@
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and -- codecs/video/Legacy/Smacker: RAD Game Tools' Smacker video (SMK2 / SMK4 frames; the file format is video/smk) and
-- the Huffman trees Smacker audio shares. Written from the format description (MultimediaWiki "Smacker"). Bits are -- the Huffman trees Smacker audio shares. From MultimediaWiki "Smacker", bit-exact with ffmpeg's smackvid.
-- read LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf with its value); -- Bits LSB first. A tree is a pre-order bit string (1 = node: left subtree then right; 0 = leaf). A big tree's 16-bit
-- an 8-bit tree's leaves hold bytes, a "big" tree's leaves hold 16-bit values made of a low-byte and a high-byte -- leaves pair a low-byte and a high-byte 8-bit tree; three escape leaves return the three most recently decoded values
-- 8-bit tree, three of them being escape leaves that return the three most recently decoded values instead (a -- (reset each frame). The header holds the MMAP, MCLR, FULL and TYPE big trees; a frame is 4x4 blocks in raster order,
-- per-frame cache, reset to 0 at each frame). The four big trees (MMAP, MCLR, FULL, TYPE) come from the file header; -- each TYPE code a block type and run length: MONO (two colours + 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds
-- a frame is 4x4 blocks in raster order, each TYPE code giving a block type and a run length: MONO (two colours and a -- 2x2- and 2x1-doubled modes), SKIP, FILL.
-- 16-bit mask), FULL (16 pixels as 8 codes; SMK4 adds a 2x2-doubled and a 2x1-doubled mode), SKIP, FILL (one colour).
-- Trees are flat arrays (a node stores the size of its left subtree, as a negative number); the frame decoder reads
-- 10 bits at a time through a lookup table into them.
-- Bit-exact with ffmpeg's smackvid decoder. Never throws: trees are bounded (depth, entries), reads past the data give
-- zero bits, a frame whose codes run out of bits gives no picture.
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32 local readu8, readu32, writeu8, writeu32 = buffer.readu8, buffer.readu32, buffer.writeu8, buffer.writeu32
@@ -30,7 +25,6 @@ for i = 1, 59 do
end end
RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048 RUNS[60], RUNS[61], RUNS[62], RUNS[63], RUNS[64] = 128, 256, 512, 1024, 2048
-- a bit position over buf[0, nbits / 8)
export type Bits = { buf: buffer, pos: number, nbits: number } export type Bits = { buf: buffer, pos: number, nbits: number }
function Smacker.bits(buf: buffer, offset: number, length: number): Bits function Smacker.bits(buf: buffer, offset: number, length: number): Bits
@@ -47,7 +41,6 @@ local function bit(br: Bits): number
end end
Smacker.bit = bit Smacker.bit = bit
-- read(br, n) -> n bits (LSB first; zeros past the end)
function Smacker.read(br: Bits, n: number): number function Smacker.read(br: Bits, n: number): number
local v, m = 0, 1 local v, m = 0, 1
for _ = 1, n do for _ = 1, n do
@@ -58,7 +51,7 @@ function Smacker.read(br: Bits, n: number): number
end end
local readBits = Smacker.read local readBits = Smacker.read
-- walk(tree, br) -> the leaf value (no end-of-data check: 8-bit trees, as the reference's table lookups) -- no end-of-data check for 8-bit trees, as the reference's table lookups
local function walk(tree: { number }, br: Bits): number local function walk(tree: { number }, br: Bits): number
local i = 1 local i = 1
local e = tree[1] local e = tree[1]
@@ -73,7 +66,6 @@ local function walk(tree: { number }, br: Bits): number
end end
Smacker.walk = walk Smacker.walk = walk
-- the pre-order tree reader: leaf(index) -> value | nil, message; returns the flat tree (1-based)
local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?) local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (number) -> (number?, string?), bigChecks: boolean): ({ number }?, string?)
local vals: { number } = {} local vals: { number } = {}
local n = 0 local n = 0
@@ -120,7 +112,6 @@ local function build(br: Bits, maxDepth: number, maxEntries: number, leaf: (numb
end end
end end
-- tree8(br) -> an 8-bit tree (leaves are bytes) | nil, message
function Smacker.tree8(br: Bits): ({ number }?, string?) function Smacker.tree8(br: Bits): ({ number }?, string?)
local leaves = 0 local leaves = 0
return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?) return build(br, MAX_DEPTH8, 511, function(_: number): (number?, string?)
@@ -138,7 +129,6 @@ local tree8 = Smacker.tree8
export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based) export type BigTree = { vals: { number }, last: { number }, lut: buffer? } -- last: the escape leaves' indexes (1-based)
-- bigTree(br, size) -> one of the header's trees | nil, message (size = its byte size from the header: bounds entries)
local function bigTree(br: Bits, size: number): (BigTree?, string?) local function bigTree(br: Bits, size: number): (BigTree?, string?)
if bit(br) == 0 then if bit(br) == 0 then
return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0 return { vals = { 0, 0 }, last = { 2, 2, 2 } }, nil -- no tree: every code is 0
@@ -184,7 +174,7 @@ end
export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree } export type Trees = { mmap: BigTree, mclr: BigTree, full: BigTree, type: BigTree }
-- trees(config) -> the four header trees | nil, message. config = the four u32 tree sizes then the tree bits -- config = the four u32 tree sizes, then the tree bits
function Smacker.trees(config: buffer): (Trees?, string?) function Smacker.trees(config: buffer): (Trees?, string?)
local n = buffer.len(config) local n = buffer.len(config)
if n <= 16 then if n <= 16 then
@@ -241,7 +231,6 @@ local function reset(t: BigTree)
vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0 vals[last[1]], vals[last[2]], vals[last[3]] = 0, 0, 0
end end
-- decode(pic, data, trees, v4) -> true | false, message. pic: palettised, padded to blocks of 4
function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?) function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boolean): (boolean, string?)
local px = pic.idx :: buffer local px = pic.idx :: buffer
local stride = pic.stride local stride = pic.stride
@@ -255,7 +244,6 @@ function Smacker.decode(pic: Picture.Picture, d: buffer, trees: Trees, v4: boole
local n = buffer.len(d) local n = buffer.len(d)
local nbits = n * 8 local nbits = n * 8
local pos = 0 local pos = 0
-- the next value of a tree (updating its recent-value cache) | -1 when the bits run out inside the tree
local function code(t: BigTree): number local function code(t: BigTree): number
local vals = t.vals local vals = t.vals
local i, p local i, p
+3 -11
View File
@@ -1,13 +1,9 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised. Written from the format description -- codecs/video/Legacy/Smc: QuickTime Graphics ('smc ') frames, 8-bit palettised; from MultimediaWiki "Apple SMC",
-- (MultimediaWiki "Apple SMC"): 4x4 blocks in raster order, opcodes in the high nibble with a block count (low nibble -- bit-exact with ffmpeg. 4x4 blocks in raster order; opcode in the high nibble, count = low nibble + 1 (bit 4: next
-- + 1, or the next byte + 1 when bit 4 is set): skip, repeat the last block, repeat the last pair of blocks, 1-colour -- byte + 1); the colour-group tables restart every frame. As ffmpeg: a row start's previous block ends the row above.
-- fill, 2 / 4 / 8-colour blocks (the colour groups go into 256-entry rotating tables, or come from them by index:
-- the tables restart every frame) and 16-colour blocks. Paints over the previous picture. Bit-exact with ffmpeg's smc
-- decoder (for widths whose rows are not padded: the previous block of a row start is the last block of the row
-- above). Never throws: reads past the data give zeros, the block count bounds every write.
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32 local readu8, writeu8, readu32, writeu32 = buffer.readu8, buffer.writeu8, buffer.readu32, buffer.writeu32
@@ -15,7 +11,6 @@ local band, rshift = bit32.band, bit32.rshift
local Smc = {} local Smc = {}
-- decode(pic, data, tables) -> true | false, message. tables = Smc.tables() (scratch, reused between frames)
function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?) function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean, string?)
local px = pic.idx :: buffer local px = pic.idx :: buffer
local n = buffer.len(d) local n = buffer.len(d)
@@ -27,7 +22,6 @@ function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean,
end end
local blocksWide = (pic.w + 3) // 4 local blocksWide = (pic.w + 3) // 4
local p = 4 -- flags byte + 24-bit chunk size local p = 4 -- flags byte + 24-bit chunk size
-- block position: bx, by (blocks)
local bx, by = 0, 0 local bx, by = 0, 0
local pairI, quadI, octI = 0, 0, 0 local pairI, quadI, octI = 0, 0, 0
-- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8) -- tables: pairs at 0 (256 * 2), quads at 512 (256 * 4), octets at 1536 (256 * 8)
@@ -159,7 +153,6 @@ function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean,
advance() advance()
end end
else else
-- 16-colour blocks
for _ = 1, count do for _ = 1, count do
if total <= 0 or by >= bh then if total <= 0 or by >= bh then
break break
@@ -175,7 +168,6 @@ function Smc.decode(pic: Picture.Picture, d: buffer, tables: buffer): (boolean,
return true, nil return true, nil
end end
-- tables() -> the colour group scratch (pairs, quads, octets)
function Smc.tables(): buffer function Smc.tables(): buffer
return buffer.create(512 + 1024 + 2048) return buffer.create(512 + 1024 + 2048)
end end
+4 -22
View File
@@ -1,22 +1,7 @@
--!strict --!strict
-- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders. -- codecs/video/Legacy: FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC and Smacker video decoders.
-- The 1990s inter-frame codecs as codecs/video/Video registry decoders (rgba8 pictures, one per packet): Autodesk -- From the format descriptions (see each submodule), bit-exact with ffmpeg. Palette: track.palette, replaced by a
-- FLI / FLC ("flic", the frames of video/fli), Cinepak ("cinepak", -- packet's palette (256 u32 entries R, G, B, A); depth: track.bitsPerPixel (AVI biBitCount, QuickTime depth).
-- 'cvid'), Microsoft Video 1 ("msvideo1": CRAM / MSVC / WHAM, 8-bit palettised and 16-bit), QuickTime Animation
-- ("qtrle", 'rle ': depths 1 / 2 / 4 / 8 / 16 / 24 / 32 and grey), QuickTime Graphics ("smc", 'smc ') and Smacker
-- video ("smackvid", the frames of video/smk: track.config = the header's tree sizes and trees, codecTag SMK2 / SMK4).
-- New in rosetta, written from the format descriptions (see each submodule); decoding is bit-exact with ffmpeg's
-- decoders (tests/codecs/legacy.luau). Every decoder keeps the previous picture (a packet paints over it) and returns
-- a fresh copy.
--
-- Palettes come from the Track: track.palette (256 u32 entries, bytes R, G, B, A: the AVI BITMAPINFO palette, the
-- QuickTime sample description's colour table, ...) and a packet's own `palette` (same layout) replaces it from that
-- packet on. Depths come from track.bitsPerPixel (AVI biBitCount, the QuickTime depth).
--
-- local dec, err = Legacy.newDecoder("cinepak", track, { maxPixels = 2^22 }) -- a Types.VideoCodecDecoder
-- Legacy.CODECS --> { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
--
-- Never throws: bad tracks return nil, Err; bad packets return Err from decode().
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Picture = require("@rosetta/codecs/video/Legacy/Picture") local Picture = require("@rosetta/codecs/video/Legacy/Picture")
@@ -39,11 +24,10 @@ Legacy.Smacker = Smacker
Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" } Legacy.CODECS = { "flic", "cinepak", "msvideo1", "qtrle", "smc", "smackvid" }
export type Options = { export type Options = {
maxPixels: number?, -- refuse bigger pictures (LIMIT; default 2^26) maxPixels: number?,
[string]: any, [string]: any,
} }
-- the per-codec pieces: make(track) -> state, step(state, data, packet) -> image? | nil, Err?
type Codec = { type Codec = {
make: (track: Types.Track) -> (any, string?), make: (track: Types.Track) -> (any, string?),
step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), step: (st: any, data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?),
@@ -165,7 +149,6 @@ local CODECS: { [string]: Codec } = {
}, },
} }
-- newDecoder(id, track, opts?) -> a Types.VideoCodecDecoder | nil, Err
function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?) function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Types.VideoCodecDecoder?, Err.Err?)
local codec = CODECS[id] local codec = CODECS[id]
if not codec then if not codec then
@@ -183,7 +166,6 @@ function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Typ
if not st then if not st then
return nil, fail(msg) return nil, fail(msg)
end end
-- Video.simpleDecoder, without requiring the registry (which requires this module)
local queue: { any } = {} local queue: { any } = {}
local self = {} local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err? function self.decode(_: any, packet: Types.Packet): Err.Err?
@@ -206,7 +188,7 @@ function Legacy.newDecoder(id: string, track: Types.Track, opts: Options?): (Typ
function self.flush(_: any) end function self.flush(_: any) end
function self.reset(_: any) function self.reset(_: any)
table.clear(queue) table.clear(queue)
st = codec.make(track) or st -- back to a black picture with the track's palette (decoding restarts at a keyframe) st = codec.make(track) or st
end end
return self :: any, nil return self :: any, nil
end end
+2 -3
View File
@@ -1,7 +1,6 @@
--!strict --!strict
-- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), which is codecs/video/Mpeg2 (an MPEG-2 decoder -- codecs/video/Mpeg1: the MPEG-1 video decoder (ISO/IEC 11172-2), the old name and API over codecs/video/Mpeg2.
-- decodes MPEG-1 streams): this module keeps the old name and API (Mpeg1.new, frameImage, PICTURE_*, the Frame / -- From mpeg1-luau e2e2898 (same author).
-- Options / Decoder types). Absorbed from mpeg1-luau e2e2898 (same author); see codecs/video/Mpeg2.
local Mpeg2 = require("@rosetta/codecs/video/Mpeg2") local Mpeg2 = require("@rosetta/codecs/video/Mpeg2")
export type Frame = Mpeg2.Frame export type Frame = Mpeg2.Frame
+11 -68
View File
@@ -1,24 +1,9 @@
--!strict --!strict
--!native --!native
-- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (native, never throws). -- codecs/video/Mpeg2/Decoder: the MPEG-1 / MPEG-2 video decoding core (ISO/IEC 11172-2, 13818-2 Main profile).
-- ISO/IEC 11172-2 and ISO/IEC 13818-2 Main profile: I, P and B pictures; progressive and interlaced sequences; frame -- From mpeg1-luau e2e2898 (same author; a port of jsmpeg's src/mpeg1.js by Dominic Szablewski, MIT,
-- pictures (frame / field motion compensation, frame / field DCT) and field pictures (field and 16x8 motion -- licenses/jsmpeg-MIT.txt). Dequantisation follows ffmpeg's arithmetic; coefficients are saturated to -2048..2047
-- compensation, the second field predicted from the first); dual-prime; 4:2:0 and 4:2:2; intra DC precision 8..11; -- (13818-2 7.4.3; ffmpeg omits it) and vectors outside the reference are clamped (ffmpeg skips the prediction).
-- 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.
local V = require("@rosetta/codecs/video/Mpeg2/Vlc") local V = require("@rosetta/codecs/video/Mpeg2/Vlc")
local T = require("@rosetta/codecs/video/Mpeg2/Tables") local T = require("@rosetta/codecs/video/Mpeg2/Tables")
local Dsp = require("@rosetta/codecs/video/Dsp") 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 GBIAS = COFF * 256 - 298 * 16 + 100 * 128 + 208 * 128 - 160
local BBIAS = COFF * 256 - 298 * 16 - 516 * 128 - 72 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 -- clamp by lookup: RGB_CLAMP[v + COFF] for v in [-COFF, COFF + 255]; the colour biases include COFF * 256
-- include COFF * 256, so the shifted sums below are indices): the same values as math.clamp, 2-3x faster natively
local RGB_CLAMP = buffer.create(2 * COFF + 256) local RGB_CLAMP = buffer.create(2 * COFF + 256)
for i = 0, 2 * COFF + 255 do for i = 0, 2 * COFF + 255 do
buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255)) buffer.writeu8(RGB_CLAMP, i, math.clamp(i - COFF, 0, 255))
end end
-- YCbCr 4:2:0 planes (coded strides) -> RGBA8 (alpha 255), w x h, nearest chroma like ffmpeg's default swscale path. -- 4:2:0 -> RGBA8 with nearest chroma, like ffmpeg's default swscale path; hook is pcall'ed (can't throw through here)
-- 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.)
local function toRgba(Y: buffer, Cb: buffer, Cr: buffer, cw: number, w: number, h: number, out: buffer, row0: number?, row1: number?, oo: number?, hook: (() -> ())?) 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 -- 2 x 2 pixels per chroma sample: the chroma terms are computed once per block of four
local r0: number = row0 or 0 local r0: number = row0 or 0
@@ -187,16 +168,10 @@ export type Store = {
} }
export type Core = { export type Core = {
-- data
write: (src: buffer, off: number, n: number) -> (), 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), nextPicture: (atEnd: boolean, tag: any) -> (Store?, boolean),
toRgba: (s: Store, out: buffer) -> (), toRgba: (s: Store, out: buffer) -> (),
reset: () -> (), 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: (() -> ())?) -> (), setYield: (hook: (() -> ())?) -> (),
state: { state: {
width: number, width: number,
@@ -244,7 +219,6 @@ function D.new(maxPixels: number?): Core
refNew = nil :: Store?, refNew = nil :: Store?,
} }
-- bitstream
local data = buffer.create(64 * 1024 + PAD) local data = buffer.create(64 * 1024 + PAD)
local dataLen = 0 local dataLen = 0
local readByte = 0 -- next byte to look at for a start code 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 pos = 0 -- bit position inside data
local err = false local err = false
-- sequence
local hasSeq = false local hasSeq = false
local mpeg2 = false local mpeg2 = false
local chroma = 1 -- 1 = 4:2:0, 2 = 4:2:2 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 -- the sequence header's values, applied (and the stores allocated) once its extension has been seen
local seqW, seqH = 0, 0 local seqW, seqH = 0, 0
-- picture
local ptype = 0 local ptype = 0
local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t] local fc00, fc01, fc10, fc11 = 1, 1, 1, 1 -- f_code[s][t]
local fullPelFw, fullPelBw = false, false local fullPelFw, fullPelBw = false, false
@@ -299,7 +271,6 @@ function D.new(maxPixels: number?): Core
local pendingFw: Store? = nil local pendingFw: Store? = nil
local pendingBw: Store? = nil local pendingBw: Store? = nil
-- slice / macroblock
local qscale = 2 local qscale = 2
local mbAddr, mbRow, mbCol = 0, 0, 0 local mbAddr, mbRow, mbCol = 0, 0, 0
local dcY, dcCb, dcCr = 128, 128, 128 local dcY, dcCb, dcCr = 128, 128, 128
@@ -342,7 +313,6 @@ function D.new(maxPixels: number?): Core
return band(e, 0xFFFF) - 32768 return band(e, 0xFFFF) - 32768
end 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 function findStart(from: number, to: number): number
local i = from local i = from
while i + 3 < to do while i + 3 < to do
@@ -396,7 +366,6 @@ function D.new(maxPixels: number?): Core
end end
end end
-- the sequence (header + extension) takes effect: sizes and stores
local function applySequence(): boolean local function applySequence(): boolean
local w, h = seqW, seqH local w, h = seqW, seqH
if w == 0 or h == 0 or w * h > state.maxPixels then if w == 0 or h == 0 or w * h > state.maxPixels then
@@ -428,7 +397,6 @@ function D.new(maxPixels: number?): Core
return true return true
end end
-- sequence header at byte p (after the start code); false when invalid
local function sequenceHeader(p: number): boolean local function sequenceHeader(p: number): boolean
pos = p * 8 pos = p * 8
local w = read(12) local w = read(12)
@@ -545,11 +513,6 @@ function D.new(maxPixels: number?): Core
return (pred + d + range) % (2 * range) - range return (pred + d + range) % (2 * range) - range
end 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 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 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 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 stride, sb, db, ph = 2 * cw, sp * cw, dp * cw, lumaH // 2
cs, csb, cdb = 2 * chw, sp * chw, dp * chw cs, csb, cdb = 2 * chw, sp * chw, dp * chw
end end
-- luma
local hx, hy = band(mvx, 1), band(mvy, 1) local hx, hy = band(mvx, 1), band(mvy, 1)
local sx = mbCol * 16 + (mvx - hx) // 2 local sx = mbCol * 16 + (mvx - hx) // 2
local sy = rowY + (mvy - hy) // 2 local sy = rowY + (mvy - hy) // 2
@@ -623,7 +585,6 @@ function D.new(maxPixels: number?): Core
return (bwS or cur) :: Store return (bwS or cur) :: Store
end 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 function predictDir(d: number, avg: boolean)
local o = d * 8 local o = d * 8
if not fieldPic then if not fieldPic then
@@ -667,7 +628,6 @@ function D.new(maxPixels: number?): Core
end end
end end
-- the prediction of a non-intra macroblock from the current motion state
local function predictMb() local function predictMb()
if ptype == 2 then if ptype == 2 then
predictDir(0, false) predictDir(0, false)
@@ -701,10 +661,8 @@ function D.new(maxPixels: number?): Core
end end
end end
-- Macroblocks no slice covers. ffmpeg's encoder skips the last macroblock of a row at the end of an MPEG-1 -- macroblocks no slice covers: ffmpeg's encoder skips a row's last macroblock at an MPEG-1 slice end and its decoder
-- slice (the next slice starts on the next row), and ffmpeg's decoder conceals it as a skipped macroblock; so do -- conceals it as skipped; so do we (P / damaged I: zero-vector copy, B: the prediction before the gap)
-- we: P (and a damaged I) copies the reference with a zero vector, B repeats the prediction of the macroblock
-- before the gap.
local covered = 0 local covered = 0
local gapFw, gapBw = false, false local gapFw, gapBw = false, false
local GAP = table.create(16, 0) 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 FSEL[1], FSEL[2], FSEL[3], FSEL[4] = f1, f2, f3, f4
end end
-- ------------------------------------------------------------------------------------------------ blocks -- block b: 0..3 luma, then Cb / Cr alternating
-- one 8x8 block b (0..3 luma, then Cb / Cr alternating): coefficients, dequantisation, IDCT into the picture.
-- False on a bitstream error.
local function decodeBlock(b: number): boolean local function decodeBlock(b: number): boolean
local n = 0 local n = 0
local q: buffer local q: buffer
@@ -828,7 +784,6 @@ function D.new(maxPixels: number?): Core
local qs = qscale local qs = qscale
local m2 = mpeg2 local m2 = mpeg2
while true do while true do
-- inline peek
local bp = rshift(pos, 3) local bp = rshift(pos, 3)
local w = bswap(readu32(data, bp)) local w = bswap(readu32(data, bp))
local s = band(pos, 7) local s = band(pos, 7)
@@ -911,7 +866,7 @@ function D.new(maxPixels: number?): Core
if m2 then if m2 then
parityOdd = bxor(parityOdd, band(m, 1)) parityOdd = bxor(parityOdd, band(m, 1))
end end
-- saturate -- saturation (13818-2 7.4.3)
if m > 2047 then if m > 2047 then
m = 2047 m = 2047
elseif m < -2048 then 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) writei32(blk, 252, if v % 2 ~= 0 then v - 1 else v + 1)
onlyDc = false onlyDc = false
end end
-- reconstruction
local dst, off, stride local dst, off, stride
if luma then if luma then
dst = curY dst = curY
@@ -973,7 +927,6 @@ function D.new(maxPixels: number?): Core
return true return true
end end
-- ------------------------------------------------------------------------------------------------ macroblocks
local function getQscale(code: number): number local function getQscale(code: number): number
if qScaleType == 1 then if qScaleType == 1 then
return readu8(NON_LINEAR, code) return readu8(NON_LINEAR, code)
@@ -1051,7 +1004,6 @@ function D.new(maxPixels: number?): Core
end end
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 function decodeMacroblock(first: boolean, endBits: number): boolean
local inc = 0 local inc = 0
local t = vlc(MBAI, MBAI_BITS) local t = vlc(MBAI, MBAI_BITS)
@@ -1253,7 +1205,6 @@ function D.new(maxPixels: number?): Core
end end
end end
-- ------------------------------------------------------------------------------------------------ pictures
-- the frame a picture completes becomes the newest reference (I / P) -- the frame a picture completes becomes the newest reference (I / P)
local function finishFrame(s: Store) local function finishFrame(s: Store)
if s.ptype ~= 3 then if s.ptype ~= 3 then
@@ -1262,8 +1213,7 @@ function D.new(maxPixels: number?): Core
end end
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 -- the picture header (after 00 00 01 00) and its extensions
-- start code (-1: none) and the temporal reference, or nil when the picture is skipped
local function pictureHeader(p: number, stop: number): (number?, number) local function pictureHeader(p: number, stop: number): (number?, number)
pos = p * 8 pos = p * 8
local tref = read(10) local tref = read(10)
@@ -1316,7 +1266,6 @@ function D.new(maxPixels: number?): Core
return at, tref return at, tref
end 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 local function selectTarget(tref: number, tag: any): boolean
fieldPic = picStruct ~= 3 fieldPic = picStruct ~= 3
parity = if picStruct == 2 then 1 else 0 parity = if picStruct == 2 then 1 else 0
@@ -1370,7 +1319,6 @@ function D.new(maxPixels: number?): Core
return true return true
end end
-- plane addressing of the current picture
local function setAddressing() local function setAddressing()
local target = cur :: Store local target = cur :: Store
curY, curCb, curCr = target.y, target.cb, target.cr curY, curCb, curCr = target.y, target.cb, target.cr
@@ -1390,15 +1338,12 @@ function D.new(maxPixels: number?): Core
mbIntra = false mbIntra = false
end 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 function decodePicture(p: number, stop: number, tag: any): Store?
local first, tref = pictureHeader(p, stop) local first, tref = pictureHeader(p, stop)
if first == nil or not selectTarget(tref, tag) then if first == nil or not selectTarget(tref, tag) then
return nil return nil
end end
setAddressing() setAddressing()
-- slices
local at = first :: number local at = first :: number
while at >= 0 do while at >= 0 do
local code = readu8(data, at + 3) local code = readu8(data, at + 3)
@@ -1443,7 +1388,6 @@ function D.new(maxPixels: number?): Core
if n <= 0 then if n <= 0 then
return return
end end
-- drop consumed bytes, keeping the scan state relative
if readByte > 0 then if readByte > 0 then
local keep = dataLen - readByte local keep = dataLen - readByte
if keep > 0 then if keep > 0 then
@@ -1468,7 +1412,6 @@ function D.new(maxPixels: number?): Core
buffer.fill(data, dataLen, 0, PAD) buffer.fill(data, dataLen, 0, PAD)
end end
-- the sequence header unit at byte at (up to stop): the header, then its extensions
local function sequenceUnit(at: number, stop: number) local function sequenceUnit(at: number, stop: number)
local ok = sequenceHeader(at + 4) local ok = sequenceHeader(at + 4)
local s = findStart(at + 4, stop) local s = findStart(at + 4, stop)
+3 -4
View File
@@ -1,8 +1,7 @@
--!strict --!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, -- codecs/video/Mpeg2/Tables: MPEG-1 / MPEG-2 video constant tables.
-- Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), generated by mpeg1-luau's tools/gen_tables.py (absorbed from -- MPEG-1: jsmpeg's (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT, licenses/jsmpeg-MIT.txt), 0-based, via
-- mpeg1-luau e2e2898), lists 0-based like the JS arrays; the MPEG-2 ones (DC sizes up to 11, Table B-15, the -- mpeg1-luau e2e2898. MPEG-2 (DC sizes to 11, B-15, non-linear quantiser scale, alternate scan): ISO/IEC 13818-2 annex B / 7.
-- non-linear quantiser scale, the alternate scan) are the tables of ISO/IEC 13818-2 annex B / section 7.
local T = {} local T = {}
T.PICTURE_RATE = { [0] = 0.0, 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, 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 --!strict
-- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau). -- codecs/video/Mpeg2/Vlc: lookup tables for the MPEG-1 / MPEG-2 variable-length codes, built at load time (Tables.luau).
-- -- Flat: indexed by the next K bits, len * 65536 + (value + 32768), len 0 = invalid. DCT: two-level (8 + 8 bits),
-- A flat table is indexed by the next K bits of the stream (K = the longest code) and holds -- len * 65536 + run * 256 + level, ESC = 0xFFFF, EOB = 0xFFFE, or SUB + subtable for a long-code prefix.
-- len * 65536 + (value + 32768) per entry; len = 0 marks an invalid code. The DCT coefficient tables are two-level -- DCT_NEXT: "10" = end_of_block, "11" = run 0 / level 1 (jsmpeg reads "1" + one bit); DCT_FIRST: "1" = run 0 / level 1.
-- (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.
local T = require("@rosetta/codecs/video/Mpeg2/Tables") local T = require("@rosetta/codecs/video/Mpeg2/Tables")
local V = {} local V = {}
@@ -53,7 +47,6 @@ local function flat(tree: { [number]: number }): (buffer, number)
return flatLeaves(leaves(tree)) return flatLeaves(leaves(tree))
end end
-- { { code, length } } indexed from 1 -> leaves with value = index - 1
local function codeLeaves(codes: { { number } }): { Leaf } local function codeLeaves(codes: { { number } }): { Leaf }
local out: { Leaf } = {} local out: { Leaf } = {}
for i, c in codes do for i, c in codes do
@@ -66,7 +59,6 @@ V.SUB = 0x1000000
V.ESC = 0xFFFF V.ESC = 0xFFFF
V.EOB = 0xFFFE 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 function twoLevel(ls: { Leaf }): buffer
local subs: { [number]: number } = {} local subs: { [number]: number } = {}
local nsub = 0 local nsub = 0
+13 -62
View File
@@ -1,23 +1,8 @@
--!strict --!strict
-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile). -- 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 / -- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes -- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top
-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from -- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
-- 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).
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
local D = require("@rosetta/codecs/video/Mpeg2/Decoder") 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 } pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based) index: number,
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering) tag: any,
-- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride -- luma stride codedWidth, chroma stride codedWidth / 2; chroma rows half the luma rows (4:2:0) or as many (4:2:2)
-- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2)
y: buffer, y: buffer,
cb: buffer, cb: buffer,
cr: buffer, cr: buffer,
@@ -45,23 +29,17 @@ export type Frame = {
chroma: number, -- 1 = 4:2:0, 2 = 4:2:2 chroma: number, -- 1 = 4:2:0, 2 = 4:2:2
mpeg2: boolean, mpeg2: boolean,
progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true) progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true)
fields: boolean, -- coded as two field pictures fields: boolean,
topFieldFirst: boolean, topFieldFirst: boolean,
repeatFirstField: boolean, repeatFirstField: boolean,
clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated) clamped: number,
concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed) concealed: { [number]: boolean },
} }
export type Options = { export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the reorder: boolean?,
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is rgba: boolean?,
-- display order for streams without B-frames. maxPixels: number?,
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.
yield: (() -> ())?, yield: (() -> ())?,
} }
@@ -154,7 +132,6 @@ local function sync(self: Decoder)
self.stats.skipped = st.skipped self.stats.skipped = st.skipped
end end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame? local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s) return emit(self, s)
@@ -205,19 +182,14 @@ local function append(self: Decoder, data: any, offset: number?, len: number?):
return true return true
end 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 function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len) return append(self, data, offset, len)
end 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? function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil) return run(self, false, nil)
end 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? function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then if not append(self, data, offset, len) then
return nil return nil
@@ -225,8 +197,6 @@ function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, l
return run(self, true, tag) return run(self, true, tag)
end 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? function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil) local f = run(self, true, nil)
if f then if f then
@@ -240,24 +210,15 @@ function Decoder.flush(self: Decoder): Frame?
return nil return nil
end end
-- Sets (or clears, nil) the cooperative yield hook (Options.yield).
function Decoder.setYield(self: Decoder, hook: (() -> ())?) function Decoder.setYield(self: Decoder, hook: (() -> ())?)
self._core.setYield(if type(hook) == "function" then hook else nil) self._core.setYield(if type(hook) == "function" then hook else nil)
end end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder) function Decoder.reset(self: Decoder)
self._core.reset() self._core.reset()
self._held = nil self._held = nil
end 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 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 if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then
return false 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 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 return false
end end
-- the planes must cover rows pr .. r1 - 1 (luma) and their chroma rows; out the band
local lumaRows = r1 - pr local lumaRows = r1 - pr
local chromaRows = (r1 + 1) // 2 - pr // 2 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 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 if buffer.len(out) < oo + (r1 - r0) * w * 4 then
return false return false
end 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) D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil)
return true return true
end 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? 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 if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil return nil
@@ -360,10 +315,6 @@ function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
return img return img
end 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?) 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 dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {} local queue: { any } = {}
@@ -382,7 +333,7 @@ function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecode
if not ok then if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f)) return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end end
while f do -- more pictures in the packet while f do
push(f) push(f)
f = dec:decode(packet.data, 0, 0, tag) f = dec:decode(packet.data, 0, 0, tag)
end end
+5 -31
View File
@@ -1,22 +1,10 @@
--!strict --!strict
--!native --!native
--!optimize 2 --!optimize 2
-- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7; native, never throws). A -- codecs/video/Theora/Decoder: the Theora frame decoder (Theora I specification, section 7). A Luau port of libtheora
-- Luau port of libtheora 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, -- 1.2.0's decoder (Xiph.Org, BSD 3-clause: licenses/libtheora-BSD.txt; decode.c, state.c, idct.c, fragment.c).
-- idct.c, fragment.c) with the bit-exact reconstruction of the specification: -- DC-only blocks as libtheora: (dc * q + 15) >> 5; IDCT sums are not wrapped to 16 bits (only out-of-range streams differ).
-- * frame header, coded super block / block flags (the run-length codes), macro block modes (the 8 mode -- Planes are in Theora's orientation (row 0 = bottom) with 16 (luma) / 8 (subsampled chroma) pixels of edge padding.
-- alphabets), motion vectors (VLC / fixed length, last / prior vectors, 4MV with the chroma averages of each pixel
-- format), per-block qi indices, DC / AC tokens with EOB runs across blocks, planes and coefficients;
-- * DC prediction, dequantisation, the spec's 16-bit integer IDCT (DC-only blocks as libtheora: (dc * q + 15) >> 5),
-- half-pel motion compensation (two-reference average toward zero), the loop filter, border extension for
-- unrestricted motion vectors, golden / previous reference frames;
-- * 4:2:0, 4:2:2 and 4:4:4; empty packets repeat the previous frame.
-- Differences from libtheora: coefficients are kept per fragment (64 i16 each) instead of libtheora's token lists,
-- the frame is reconstructed whole (no MCU pipelining, same result), there is no post-processing (libtheora's default),
-- and intermediate IDCT sums are not wrapped to 16 bits (only out-of-range streams differ).
--
-- Planes are stored in Theora's own orientation (row 0 is the bottom of the picture) with 16 (luma) / 8 (subsampled
-- chroma) pixels of edge padding; output() turns the picture region into top-down planes.
local Header = require("@rosetta/codecs/video/Theora/Header") local Header = require("@rosetta/codecs/video/Theora/Header")
local readu8 = buffer.readu8 local readu8 = buffer.readu8
@@ -211,7 +199,6 @@ export type State = {
keyframes: number, keyframes: number,
} }
-- new(info, setup) -> State
function D.new(info: Header.Info, setup: Header.Setup): State function D.new(info: Header.Info, setup: Header.Setup): State
local pf = info.pixelFormat local pf = info.pixelFormat
local hdec = if pf % 2 == 0 then 1 else 0 local hdec = if pf % 2 == 0 then 1 else 0
@@ -382,7 +369,6 @@ function D.new(info: Header.Info, setup: Header.Setup): State
return st :: State return st :: State
end end
-- ------------------------------------------------------------------------------------------------ reconstruction
-- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs -- the 8-point IDCT of libtheora's idct8 (the spec's), on 8 values; returns the 8 outputs
local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number) local function idct8(x0: number, x1: number, x2: number, x3: number, x4: number, x5: number, x6: number, x7: number): (number, number, number, number, number, number, number, number)
local t0 = (C4 * (x0 + x4)) // 65536 local t0 = (C4 * (x0 + x4)) // 65536
@@ -522,7 +508,6 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu
st.last[fi] = 0 st.last[fi] = 0
idctRows(blk, st.tmp) idctRows(blk, st.tmp)
end end
-- the prediction
if ri == SELF then if ri == SELF then
for y = 0, 7 do for y = 0, 7 do
bfill(dst, pos + y * stride, 128, 8) bfill(dst, pos + y * stride, 128, 8)
@@ -552,7 +537,6 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu
end end
end end
end end
-- the residual
if last ~= 0 then if last ~= 0 then
idctAdd(st.tmp, dst, pos, stride) idctAdd(st.tmp, dst, pos, stride)
elseif fv ~= 0 then elseif fv ~= 0 then
@@ -565,7 +549,6 @@ local function reconFrag(st: State, fi: number, qis: { number }, dstPlanes: { bu
end end
end end
-- ------------------------------------------------------------------------------------------------ loop filter
local function filterH(b: buffer, p: number, stride: number, bv: { number }) local function filterH(b: buffer, p: number, stride: number, bv: { number })
p -= 2 p -= 2
for _ = 0, 7 do for _ = 0, 7 do
@@ -735,14 +718,10 @@ local function dcPredict(st: State)
end end
end end
-- ------------------------------------------------------------------------------------------------ frame decode
-- decode(st, data, off, len) -> kind ("key" | "inter" | "dup") | nil, message. The picture is then in
-- st.refs[st.shown].
function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?) function D.decode(st: State, data: buffer, off: number, len: number): (string?, string?)
if len <= 0 then if len <= 0 then
return "dup", nil return "dup", nil
end end
-- a zero-padded copy: reads past the end give zero bits, every read site clamps pos to the end first
local bb = buffer.create(len + 24) local bb = buffer.create(len + 24)
bcopy(bb, 0, data, off, len) bcopy(bb, 0, data, off, len)
local maxp = len * 8 local maxp = len * 8
@@ -1216,7 +1195,6 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?,
dcPredict(st) dcPredict(st)
-- reconstruction into a free reference buffer
local self = 1 local self = 1
while self == st.gold or self == st.prev do while self == st.gold or self == st.prev do
self += 1 self += 1
@@ -1249,9 +1227,6 @@ function D.decode(st: State, data: buffer, off: number, len: number): (string?,
return if intra then "key" else "inter", nil return if intra then "key" else "inter", nil
end end
-- ------------------------------------------------------------------------------------------------ output
-- the picture region of the shown frame as top-down planes: plane(st, pli, x0, y0, w, h) copies a w x h window whose
-- top-left corner is (x0, y0) counted from the top of the plane
function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: number): buffer
local src = st.refs[st.shown][pli + 1] local src = st.refs[st.shown][pli + 1]
local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1] local stride, origin, ph = st.stride[pli + 1], st.origin[pli + 1], st.ph[pli + 1]
@@ -1263,8 +1238,7 @@ function D.plane(st: State, pli: number, x0: number, y0: number, w: number, h: n
return out return out
end end
-- downsample(src, cw, ch, hdec, dst, off, ow, oh): 4:2:2 (hdec 1: rows averaged in pairs) or 4:4:4 (hdec 0: 2x2 -- 4:2:2 (rows averaged in pairs) or 4:4:4 (2x2 averages) chroma down to 4:2:0
-- averages) chroma of cw x ch into ow x oh 4:2:0 chroma at dst[off]
function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number) function D.downsample(src: buffer, cw: number, ch: number, hdec: number, dst: buffer, off: number, ow: number, oh: number)
for r = 0, oh - 1 do for r = 0, oh - 1 do
local r0 = math.min(2 * r, ch - 1) local r0 = math.min(2 * r, ch - 1)
+7 -16
View File
@@ -1,11 +1,7 @@
--!strict --!strict
-- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6): identification (frame / -- codecs/video/Theora/Header: the three Theora headers (Theora I specification, section 6) and the dequantisation and
-- picture size and offsets, frame rate, aspect, colour space, pixel format, keyframe granule shift), comment (Vorbis -- Huffman lookup tables derived from them. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause,
-- comment layout) and setup (loop-filter limits, quantisation parameters, the 80 DCT token Huffman trees), and the -- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c.
-- tables derived from them: the dequantisation matrices of every qi / plane / intra-inter and the collapsed Huffman
-- lookup tables the frame decoder walks. A Luau port of libtheora 1.2.0 (Xiph.Org, BSD 3-clause:
-- licenses/libtheora-BSD.txt): decinfo.c, dequant.c, quant.c (oc_dequant_tables_init), huffdec.c (the tree unpacking;
-- the table layout here is simpler). Never throws: bad headers return nil, message.
local Bits = require("@rosetta/core/Bits") local Bits = require("@rosetta/core/Bits")
local H = {} local H = {}
@@ -18,7 +14,7 @@ export type Info = {
frameHeight: number, frameHeight: number,
picWidth: number, -- the picture region (the displayed part) picWidth: number, -- the picture region (the displayed part)
picHeight: number, picHeight: number,
picX: number, -- from the left picX: number,
picY: number, -- from the bottom, as stored picY: number, -- from the bottom, as stored
fpsNum: number, fpsNum: number,
fpsDen: number, fpsDen: number,
@@ -53,8 +49,7 @@ local function ilog(v: number): number
return n return n
end end
-- ------------------------------------------------------------------------------------------------ identification -- identification header: 0x80 "theora"
-- info(buf, off, len) -> Info | nil, message: the packet starting with 0x80 "theora"
function H.info(b: buffer, off: number, len: number): (Info?, string?) function H.info(b: buffer, off: number, len: number): (Info?, string?)
if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then if len < 42 or buffer.readu8(b, off) ~= 0x80 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora identification header" return nil, "not a Theora identification header"
@@ -99,8 +94,7 @@ function H.info(b: buffer, off: number, len: number): (Info?, string?)
return info, nil return info, nil
end end
-- ------------------------------------------------------------------------------------------------ comment -- comment header: 0x81 "theora"
-- comment(buf, off, len) -> vendor, { "KEY=value" } | nil, message: the packet starting with 0x81 "theora"
function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?) function H.comment(b: buffer, off: number, len: number): (string?, { string }?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then if len < 7 or buffer.readu8(b, off) ~= 0x81 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, nil, "not a Theora comment header" return nil, nil, "not a Theora comment header"
@@ -139,7 +133,6 @@ function H.comment(b: buffer, off: number, len: number): (string?, { string }?,
return vendor, list, nil return vendor, list, nil
end end
-- ------------------------------------------------------------------------------------------------ Huffman trees
-- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in -- A tree is read depth first (0: an internal node, 1 then 5 bits: a leaf with that token). It becomes lookup tables in
-- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf -- one flat array: a node is huff[o] = n (bits to peek) followed by 2^n entries, entry = length * 64 + token (a leaf
-- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits). -- reached after `length` <= n of the peeked bits) or -offset (another node, after all n bits).
@@ -166,7 +159,6 @@ local function readTree(br: any): ({ number }?, { number }?, { number }?)
return nil, nil, nil return nil, nil, nil
end end
local t = br:read(5) local t = br:read(5)
-- insert the leaf
local n = 1 local n = 1
for d = 1, len do for d = 1, len do
local k = (code // 2 ^ (32 - d)) % 2 local k = (code // 2 ^ (32 - d)) % 2
@@ -247,11 +239,10 @@ local function buildTable(out: { number }, kid0: { number }, kid1: { number }, t
return node(1) return node(1)
end end
-- ------------------------------------------------------------------------------------------------ setup
local DC_MIN = { 16, 32 } local DC_MIN = { 16, 32 }
local AC_MIN = { 8, 16 } local AC_MIN = { 8, 16 }
-- setup(buf, off, len) -> Setup | nil, message: the packet starting with 0x82 "theora" -- setup header: 0x82 "theora"
function H.setup(b: buffer, off: number, len: number): (Setup?, string?) function H.setup(b: buffer, off: number, len: number): (Setup?, string?)
if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then if len < 7 or buffer.readu8(b, off) ~= 0x82 or buffer.readstring(b, off + 1, 6) ~= "theora" then
return nil, "not a Theora setup header" return nil, "not a Theora setup header"
+6 -34
View File
@@ -1,20 +1,7 @@
--!strict --!strict
-- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg (video/ogv) and Matroska -- codecs/video/Theora: a Theora video decoder (the Theora I specification, Xiph.Org), for Ogg and Matroska (V_THEORA).
-- (V_THEORA). A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt): Header.luau -- A Luau port of the libtheora 1.2.0 decoder (BSD 3-clause, licenses/libtheora-BSD.txt), bit-exact with libtheora /
-- (identification / comment / setup headers, dequantisation tables, Huffman trees) and Decoder.luau (native frames). -- ffmpeg; libtheora's optional post-processing is not supported.
-- Supports: every Theora I stream (bitstream 3.2.x and older 3.x): intra and inter frames, golden frames, 4MV
-- macro blocks, all three pixel formats (4:2:0, 4:2:2, 4:4:4), picture regions smaller than the coded frame (odd sizes,
-- offsets), empty packets (a repeated frame). Output is bit-exact with libtheora / ffmpeg (tests/codecs/theora.luau);
-- yuv420p images average 4:2:2 / 4:4:4 chroma down (planes() keeps the native layout).
-- Not supported: libtheora's optional post-processing (deblocking / deringing, off by default there too).
--
-- local dec = Theora.new({ idHeader, commentHeader, setupHeader }) -- or the Xiph-laced Matroska CodecPrivate
-- local kind = dec:decode(packet) -- "key" | "inter" | "dup" (empty packet / no coded blocks) | nil, Err
-- local img = dec:image() -- a fresh yuv420p Types.Image of the picture region
-- local y, u, v, cw, ch = dec:planes() -- native planes (chroma cw x ch), top-down
-- Theora.granuleFrame(dec.info, granulepos) -- the 0-based frame index of an Ogg granule position
--
-- Never throws: bad headers / packets come back as nil, Err (a corrupt frame still updates the picture).
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local VorbisComment = require("@rosetta/codecs/audio/VorbisComment") local VorbisComment = require("@rosetta/codecs/audio/VorbisComment")
@@ -26,12 +13,11 @@ local Theora = {}
export type Info = Header.Info export type Info = Header.Info
export type Options = { export type Options = {
maxPixels: number?, -- larger coded frames are refused (default 4096 * 2304) maxPixels: number?,
} }
local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" } local PIXEL_FORMATS = { [0] = "yuv420p", "reserved", "yuv422p", "yuv444p" }
-- isHeader(buf, off?, len?) -> 1 / 2 / 3 for the identification / comment / setup header, else nil
function Theora.isHeader(b: buffer, off: number?, len: number?): number? function Theora.isHeader(b: buffer, off: number?, len: number?): number?
local o = off or 0 local o = off or 0
local n = len or (buffer.len(b) - o) local n = len or (buffer.len(b) - o)
@@ -45,7 +31,6 @@ function Theora.isHeader(b: buffer, off: number?, len: number?): number?
return nil return nil
end end
-- splitConfig(config) -> the three header packets from Matroska's Xiph-laced CodecPrivate (or nil)
function Theora.splitConfig(c: buffer): { buffer }? function Theora.splitConfig(c: buffer): { buffer }?
local n = buffer.len(c) local n = buffer.len(c)
if n < 3 or buffer.readu8(c, 0) ~= 2 then if n < 3 or buffer.readu8(c, 0) ~= 2 then
@@ -77,7 +62,6 @@ function Theora.splitConfig(c: buffer): { buffer }?
return out return out
end end
-- info(idHeader) -> Header.Info (frame / picture size, frame rate, granule shift, pixel format, ...) | nil, Err
function Theora.info(h: buffer): (Header.Info?, Err.Err?) function Theora.info(h: buffer): (Header.Info?, Err.Err?)
local ok, info, err = pcall(Header.info, h, 0, buffer.len(h)) local ok, info, err = pcall(Header.info, h, 0, buffer.len(h))
if not ok or not info then if not ok or not info then
@@ -86,7 +70,6 @@ function Theora.info(h: buffer): (Header.Info?, Err.Err?)
return info, nil return info, nil
end end
-- comment(commentHeader) -> vendor, { "KEY=value" }, tags (lower-case keys) | nil, nil, nil, Err
function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?) function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?, Err.Err?)
local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h)) local ok, vendor, list, err = pcall(Header.comment, h, 0, buffer.len(h))
if not ok or not vendor or not list then if not ok or not vendor or not list then
@@ -95,7 +78,6 @@ function Theora.comment(h: buffer): (string?, { string }?, { [string]: string }?
return vendor, list, (VorbisComment.tags(list)), nil return vendor, list, (VorbisComment.tags(list)), nil
end end
-- granuleFrame(info, granulepos) -> the 0-based index of the frame a granule position ends on (-1 for none)
function Theora.granuleFrame(info: Header.Info, g: number): number function Theora.granuleFrame(info: Header.Info, g: number): number
if g < 0 then if g < 0 then
return -1 return -1
@@ -111,7 +93,6 @@ function Theora.granuleFrame(info: Header.Info, g: number): number
return f return f
end end
-- ------------------------------------------------------------------------------------------------ decoder
local Dec = {} local Dec = {}
Dec.__index = Dec Dec.__index = Dec
@@ -126,14 +107,13 @@ export type TheoraDecoder = typeof(setmetatable(
frameRate: number, frameRate: number,
pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p" pixelFormat: string, -- "yuv420p" | "yuv422p" | "yuv444p"
aspect: number, -- pixel aspect ratio (1 when unknown) aspect: number, -- pixel aspect ratio (1 when unknown)
frames: number, -- packets decoded (dupes included) frames: number,
_st: Decoder.State, _st: Decoder.State,
_any: boolean, -- a frame was decoded _any: boolean,
}, },
Dec Dec
)) ))
-- new(headers, opts?) -> TheoraDecoder | nil, Err: headers = the three header packets, or the Xiph-laced config
function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?) function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecoder?, Err.Err?)
local list: { buffer }? = nil local list: { buffer }? = nil
if type(headers) == "buffer" then if type(headers) == "buffer" then
@@ -177,7 +157,6 @@ function Theora.new(headers: { buffer } | buffer, opts: Options?): (TheoraDecode
}, Dec), nil }, Dec), nil
end end
-- decode(data, off?, len?) -> "key" | "inter" | "dup" | nil, Err. Header packets are skipped (nil, nil).
function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?) function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number?): (string?, Err.Err?)
local o = off or 0 local o = off or 0
local n = len or (buffer.len(data) - o) local n = len or (buffer.len(data) - o)
@@ -198,7 +177,6 @@ function Dec.decode(self: TheoraDecoder, data: buffer, off: number?, len: number
return kind, nil return kind, nil
end end
-- reset(): after a seek (the next frame should be a keyframe; until then inter frames predict from grey / old data)
function Dec.reset(self: TheoraDecoder) function Dec.reset(self: TheoraDecoder)
local st = self._st local st = self._st
st.shown = st.prev st.shown = st.prev
@@ -210,8 +188,6 @@ local function window(self: TheoraDecoder): (number, number, number, number)
return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight return info.picX, info.frameHeight - info.picHeight - info.picY, info.picWidth, info.picHeight
end end
-- planes() -> y, u, v (fresh top-down buffers of the picture region, chroma in the native layout), chroma width,
-- chroma height
function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number) function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, number)
local st = self._st local st = self._st
local x0, y0, w, h = window(self) local x0, y0, w, h = window(self)
@@ -223,7 +199,6 @@ function Dec.planes(self: TheoraDecoder): (buffer, buffer, buffer, number, numbe
return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch return Decoder.plane(st, 0, x0, y0, w, h), Decoder.plane(st, 1, cx0, cy0, cw, ch), Decoder.plane(st, 2, cx0, cy0, cw, ch), cw, ch
end end
-- image() -> a fresh yuv420p Types.Image of the picture (4:2:2 / 4:4:4 chroma averaged down)
function Dec.image(self: TheoraDecoder): Types.Image function Dec.image(self: TheoraDecoder): Types.Image
local y, u, v, cw, ch = self:planes() local y, u, v, cw, ch = self:planes()
local w, h = self.width, self.height local w, h = self.width, self.height
@@ -247,9 +222,6 @@ function Dec.image(self: TheoraDecoder): Types.Image
return img return img
end end
-- ------------------------------------------------------------------------------------------------ registry
-- newVideoDecoder(track, opts?) -> a Types.VideoCodecDecoder (the codecs/video/Video entry "theora"): track.config
-- holds the three headers (Xiph-laced, as Matroska's CodecPrivate); one picture per packet, empty packets repeat
function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) function Theora.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
if not track.config then if not track.config then
return nil, Err.new(Err.CORRUPT, "Theora track without its headers") return nil, Err.new(Err.CORRUPT, "Theora track without its headers")
+3 -25
View File
@@ -1,16 +1,6 @@
--!strict --!strict
-- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from whatever it was given: -- codecs/video/Video/Source: what a video writer (Matroska / WebM, AVI, Y4M, MP4) gets to write, from a VideoDecoder
-- a VideoDecoder (F.load / F.video.open of any video or animated image) or a Demuxer. Each output stream is either -- or a Demuxer: each stream is copied (remuxed) or produced (decoded frames re-encoded, PCM audio).
-- copied (the source track's packets, when the target container takes that codec: remuxing, e.g. VP8 into WebM,
-- since VP8 is decode-only) or produced (decoded frames encoded with a registered encoder such as MJPEG, raw
-- yuv420p frames, PCM audio from the audio Decoder). New in rosetta.
--
-- local streams, err = Source.streams(value, opts, {
-- video = { copy = { vp8 = true }, encode = "mjpeg" }, -- copy: codec ids the container takes ("*" = any)
-- audio = { copy = { opus = true, vorbis = true }, pcm = true },
-- })
-- -- streams[i] = { kind, codec, copied, width, height, frameRate, sampleRate, channels, bitsPerSample, config,
-- -- track, packets = { { pts, duration (seconds), keyframe, data } } }
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Yuv = require("@rosetta/codecs/image/Yuv") local Yuv = require("@rosetta/codecs/image/Yuv")
@@ -41,7 +31,6 @@ local function allows(set: { [string]: boolean }?, codec: string): boolean
return set ~= nil and (set[codec] == true or set["*"] == true) return set ~= nil and (set[codec] == true or set["*"] == true)
end end
-- the packets of a source track, times in seconds
local function copyPackets(dmx: any, track: Types.Track): { OutPacket } local function copyPackets(dmx: any, track: Types.Track): { OutPacket }
local out = {} local out = {}
local scale = if track.timescale and track.timescale > 0 then track.timescale else 1 local scale = if track.timescale and track.timescale > 0 then track.timescale else 1
@@ -72,8 +61,6 @@ local function trackStream(track: Types.Track, packets: { OutPacket }): Stream
} }
end end
-- encodeFrames(video, codec, opts) -> the video's frames encoded with the registry's encoder for codec ("rawvideo":
-- yuv420p planes)
local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?) local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err?)
local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil local encode: ((img: Types.Image, opts: any) -> (buffer?, Err.Err?))? = nil
if codec ~= "rawvideo" then if codec ~= "rawvideo" then
@@ -140,7 +127,6 @@ local function encodeFrames(v: any, codec: string, opts: any): (Stream?, Err.Err
} :: Stream, nil } :: Stream, nil
end end
-- pcmFrom(decoder, opts) -> an s16le stream from an audio Decoder (chunks of opts.audioChunk frames, default 4096)
local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?) local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
local ch, rate = dec.channels, dec.sampleRate local ch, rate = dec.channels, dec.sampleRate
if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then if type(ch) ~= "number" or ch < 1 or type(rate) ~= "number" or rate <= 0 then
@@ -184,7 +170,6 @@ local function pcmFrom(dec: any, opts: any): (Stream?, Err.Err?)
} :: Stream, nil } :: Stream, nil
end end
-- streams(value, opts, want) -> { Stream } | nil, Err
function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?) function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.Err?)
local o = opts or {} local o = opts or {}
if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then if type(value) ~= "table" or (value.kind ~= "video" and value.kind ~= "demuxer") then
@@ -192,7 +177,6 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E
end end
local dmx = if value.kind == "demuxer" then value else value.demuxer local dmx = if value.kind == "demuxer" then value else value.demuxer
local out: { Stream } = {} local out: { Stream } = {}
-- video
local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video")) local vt: Types.Track? = if value.kind == "video" then value.track else (dmx and dmx:track("video"))
local wv = want.video local wv = want.video
if wv and o.video ~= false then if wv and o.video ~= false then
@@ -208,7 +192,6 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E
return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)")) return nil, Err.new(Err.UNSUPPORTED, "cannot write " .. vt.codec .. " video" .. (if wv.encode then "" else " (this container cannot take it and it cannot be re-encoded)"))
end end
end end
-- audio
local wa = want.audio local wa = want.audio
if wa and o.audio ~= false then if wa and o.audio ~= false then
local at: Types.Track? = dmx and dmx:track("audio") local at: Types.Track? = dmx and dmx:track("audio")
@@ -232,7 +215,7 @@ function Source.streams(value: any, opts: any?, want: Want): ({ Stream }?, Err.E
return out, nil return out, nil
end end
-- rational(fps) -> num, den: integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond -- integer rates as n / 1, NTSC rates as n * 1000 / 1001, else to a millisecond
function Source.rational(fps: number): (number, number) function Source.rational(fps: number): (number, number)
if fps ~= fps or fps <= 0 then if fps ~= fps or fps <= 0 then
return 25, 1 return 25, 1
@@ -247,9 +230,6 @@ function Source.rational(fps: number): (number, number)
return math.floor(fps * 1000 + 0.5), 1000 return math.floor(fps * 1000 + 0.5), 1000
end end
-- constantRate(stream, maxFps?) -> num, den, { OutPacket }: a video stream at a constant frame rate for the
-- containers that have one (AVI, Y4M): the rate of the shortest frame (at most maxFps, default 100), each packet
-- repeated to fill its duration (a GIF's 100 / 50 / 200 ms frames become 2, 1 and 4 frames at 20 fps)
function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket }) function Source.constantRate(s: Stream, maxFps: number?): (number, number, { OutPacket })
local fd = math.huge local fd = math.huge
for _, p in s.packets do for _, p in s.packets do
@@ -277,8 +257,6 @@ function Source.constantRate(s: Stream, maxFps: number?): (number, number, { Out
return num, den, out return num, den, out
end end
-- interleave(streams) -> { { stream index, packet } } merged by decode time (dts, else pts); each stream keeps its
-- own order
function Source.interleave(streams: { Stream }): { { any } } function Source.interleave(streams: { Stream }): { { any } }
local order = {} local order = {}
local pos = table.create(#streams, 1) local pos = table.create(#streams, 1)
+10 -56
View File
@@ -1,19 +1,5 @@
--!strict --!strict
-- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta. -- codecs/video/Video: the video codec registry and the generic VideoDecoder. New in rosetta.
--
-- Registry: our codec ids ("vp8", "mjpeg", "mpeg1", "h264", "rawvideo", ...) with the containers' names for them
-- (AVI / MOV FourCCs, Matroska CodecIDs, MPEG stream types) and, for the codecs we can decode, a constructor of a
-- Types.VideoCodecDecoder (packets in, pictures out). Containers map their own ids through Video.fromFourcc /
-- Video.fromMatroska so a track's codec is known even without a decoder (remuxing still works). Another codec plugs
-- in with one line in BUILTIN (static: Roblox has no dynamic require) or at run time with Video.register(entry).
--
-- local Video = require("@rosetta/codecs/video/Video")
-- Video.fromFourcc("MJPG") --> "mjpeg" Video.fromMatroska("V_VP8") --> "vp8"
-- local dec = Video.decoder(track, opts) -- a VideoCodecDecoder | nil, Err (UNSUPPORTED: no decoder)
-- local v = Video.open(demuxer, opts) -- a Types.VideoDecoder over a Types.Demuxer (formats' open())
-- local v = Video.fromFrames(images, delays) -- a frames-backed VideoDecoder (animated GIF / APNG / WebP)
--
-- Never throws: bad data / missing codecs come back as nil, Err.
local Err = require("@rosetta/core/Err") local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types") local Types = require("@rosetta/Types")
local Yuv = require("@rosetta/codecs/image/Yuv") local Yuv = require("@rosetta/codecs/image/Yuv")
@@ -21,18 +7,15 @@ local Yuv = require("@rosetta/codecs/image/Yuv")
local Video = {} local Video = {}
export type Entry = { export type Entry = {
id: string, -- our codec id id: string,
name: string, -- a human name name: string,
fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs fourcc: { string }?, -- AVI biCompression / MOV sample entry FourCCs
matroska: { string }?, -- Matroska / WebM CodecIDs matroska: { string }?, -- Matroska / WebM CodecIDs
-- new(track, opts) -> a decoder instance (nil = decode not supported)
new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?, new: ((track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?))?,
[string]: any, [string]: any,
} }
-- ------------------------------------------------------------------------------------------------ simple decoders -- decodeOne -> nil, nil: a packet with no picture to show (a hidden VP8 altref frame)
-- one picture per packet, no reordering: decodeOne(data, packet) -> Image | nil, Err (nil, nil: a packet with no
-- picture to show, such as a hidden VP8 altref frame)
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
local queue: { any } = {} local queue: { any } = {}
local self = {} local self = {}
@@ -213,8 +196,7 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec
end), nil end), nil
end end
-- Motion JPEG: every packet one JPEG (or two fields), yuv420p straight from the planes (full range) when the layout -- Motion JPEG: yuv420p straight from the planes (full range) when the layout allows, else rgba8
-- allows, else rgba8
local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function mjpegDecoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Jpeg = require("@rosetta/codecs/image/Jpeg") local Jpeg = require("@rosetta/codecs/image/Jpeg")
local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels } local o: Jpeg.DecodeOptions = { yuv = true, maxPixels = opts and opts.maxPixels }
@@ -240,20 +222,16 @@ local function mjpegEncode(img: Types.Image, opts: any?): (buffer?, Err.Err?)
return Jpeg.encode(src, { quality = opts and opts.quality or 90 }) return Jpeg.encode(src, { quality = opts and opts.quality or 90 })
end end
-- MPEG-1 / MPEG-2 video (codecs/video/Mpeg2): pictures in decode order, reordered for display
local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function mpeg2Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Mpeg2 = require("@rosetta/codecs/video/Mpeg2") local Mpeg2 = require("@rosetta/codecs/video/Mpeg2")
return Mpeg2.newVideoDecoder(track, opts) return Mpeg2.newVideoDecoder(track, opts)
end end
-- H.264 / AVC (codecs/video/H264): avcC from track.config (MP4 / Matroska) or Annex B packets (MPEG-TS, AVI, raw .h264);
-- pictures in display order with the pts of their packet
local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function h264Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local H264 = require("@rosetta/codecs/video/H264") local H264 = require("@rosetta/codecs/video/H264")
return H264.newVideoDecoder(track, opts) return H264.newVideoDecoder(track, opts)
end end
-- H.263 / Sorenson Spark (codecs/video/H263): one picture per packet, no reordering
local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local H263 = require("@rosetta/codecs/video/H263") local H263 = require("@rosetta/codecs/video/H263")
local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels }) local dec = H263.new({ flv = track.codec == "flv1", maxPixels = opts and opts.maxPixels })
@@ -264,22 +242,18 @@ local function h263Decoder(track: Types.Track, opts: any?): (Types.VideoCodecDec
end), nil end), nil
end end
-- Theora (codecs/video/Theora): track.config = the three headers, Xiph-laced (Matroska's CodecPrivate; video/ogv
-- builds the same); one picture per packet, empty packets repeat the previous one
local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) local function theoraDecoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local Theora = require("@rosetta/codecs/video/Theora") local Theora = require("@rosetta/codecs/video/Theora")
return Theora.newVideoDecoder(track, opts) return Theora.newVideoDecoder(track, opts)
end end
-- FLI / FLC, Cinepak, Microsoft Video 1, QuickTime RLE / SMC, Smacker (codecs/video/Legacy)
local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?) local function legacyDecoder(id: string): (track: Types.Track, opts: any?) -> (Types.VideoCodecDecoder?, Err.Err?)
return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) return function(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
return require("@rosetta/codecs/video/Legacy").newDecoder(id, track, opts) return require("@rosetta/codecs/video/Legacy").newDecoder(id, track, opts)
end end
end end
-- ------------------------------------------------------------------------------------------------ registry -- FourCCs compare case-sensitively first, then upper-cased
-- the codecs known by name (decoders where `new` is set). FourCCs compare case-sensitively first, then upper-cased.
local BUILTIN: { Entry } = { local BUILTIN: { Entry } = {
{ id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder }, { id = "vp8", name = "VP8", fourcc = { "VP80", "vp08" }, matroska = { "V_VP8" }, new = vp8Decoder },
{ id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode }, { id = "mjpeg", name = "Motion JPEG", fourcc = { "MJPG", "mjpa", "mjpb", "jpeg", "AVRn", "AVDJ", "dmb1", "LJPG", "JPGL", "MJLS", "ijpg" }, matroska = { "V_MJPEG" }, new = mjpegDecoder, encode = mjpegEncode },
@@ -299,7 +273,6 @@ local BUILTIN: { Entry } = {
{ id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } }, { id = "flashsv", name = "Flash Screen Video", fourcc = { "FSV1" } },
{ id = "flashsv2", name = "Flash Screen Video 2" }, { id = "flashsv2", name = "Flash Screen Video 2" },
{ id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } }, { id = "png", name = "PNG", fourcc = { "png ", "MPNG" }, matroska = { "V_PNG" } },
-- legacy inter-frame codecs (codecs/video/Legacy; rgba8 pictures, palettes from track.palette)
{ id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") }, { id = "cinepak", name = "Cinepak", fourcc = { "cvid" }, new = legacyDecoder("cinepak") },
{ id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") }, { id = "msvideo1", name = "Microsoft Video 1", fourcc = { "CRAM", "MSVC", "WHAM" }, new = legacyDecoder("msvideo1") },
{ id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") }, { id = "qtrle", name = "QuickTime Animation (RLE)", fourcc = { "rle " }, new = legacyDecoder("qtrle") },
@@ -312,7 +285,6 @@ local byId: { [string]: Entry } = {}
local byFourcc: { [string]: string } = {} local byFourcc: { [string]: string } = {}
local byMatroska: { [string]: string } = {} local byMatroska: { [string]: string } = {}
-- register(entry): adds or replaces a codec (by id); its fourcc / matroska names map to it
function Video.register(entry: Entry): (boolean, Err.Err?) function Video.register(entry: Entry): (boolean, Err.Err?)
if type(entry) ~= "table" or type(entry.id) ~= "string" then if type(entry) ~= "table" or type(entry.id) ~= "string" then
return false, Err.new(Err.ARG, "register: needs an entry with an id") return false, Err.new(Err.ARG, "register: needs an entry with an id")
@@ -334,31 +306,25 @@ for _, e in BUILTIN do
Video.register(e) Video.register(e)
end end
-- the registry (read only by convention): id -> Entry
Video.codecs = byId Video.codecs = byId
-- fromFourcc(fourcc) -> codec id | nil
function Video.fromFourcc(fcc: string): string? function Video.fromFourcc(fcc: string): string?
return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)] return byFourcc[fcc] or byFourcc[string.upper(fcc)] or byFourcc[string.lower(fcc)]
end end
-- fromMatroska(codecId) -> codec id | nil (V_MPEG4/ISO/AVC -> h264, ...)
function Video.fromMatroska(id: string): string? function Video.fromMatroska(id: string): string?
return byMatroska[id] return byMatroska[id]
end end
-- names(codecId) -> the Entry (FourCCs / Matroska ids for writers) | nil
function Video.entry(id: string): Entry? function Video.entry(id: string): Entry?
return byId[id] return byId[id]
end end
-- canDecode(codecId) -> boolean
function Video.canDecode(id: string): boolean function Video.canDecode(id: string): boolean
local e = byId[id] local e = byId[id]
return e ~= nil and e.new ~= nil return e ~= nil and e.new ~= nil
end end
-- decoder(track, opts?) -> a VideoCodecDecoder for the track's codec | nil, Err (UNSUPPORTED when none is registered)
function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?) function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local e = byId[track.codec] local e = byId[track.codec]
if not e or not e.new then if not e or not e.new then
@@ -371,7 +337,6 @@ function Video.decoder(track: Types.Track, opts: any?): (Types.VideoCodecDecoder
return dec, err return dec, err
end end
-- ------------------------------------------------------------------------------------------------ VideoDecoder
local function toRGBA(_self: any, f: any): Types.Image local function toRGBA(_self: any, f: any): Types.Image
local img = if type(f) == "table" and f.image then f.image else f local img = if type(f) == "table" and f.image then f.image else f
local out = Yuv.imageToRgba(img) local out = Yuv.imageToRgba(img)
@@ -379,22 +344,16 @@ local function toRGBA(_self: any, f: any): Types.Image
end end
export type OpenOptions = { export type OpenOptions = {
rgba: boolean?, -- nextFrame returns rgba8 images (default false: the codec's native yuv420p) rgba: boolean?,
track: number?, -- the video track id (default: the first video track) track: number?,
maxPixels: number?, maxPixels: number?,
openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?,
audio: boolean?, -- false: do not open the audio track audio: boolean?,
-- shrink yuv420p frames so the longer side is at most this many pixels (aspect kept; bilinear, Yuv.scale), before
-- any rgba conversion. v.width / v.height stay the source size; frame.image has the output size. Default: none
maxSide: number?, maxSide: number?,
-- passed to codecs that support a cooperative yield point (H.264: codecs/video/H264 Options.yield)
yield: (() -> ())?, yield: (() -> ())?,
[string]: any, [string]: any,
} }
-- open(demuxer, opts?) -> a Types.VideoDecoder over the demuxer's video track (and audio track through
-- opts.openAudio). A video track without a decoder still opens: nextFrame returns nil, Err.UNSUPPORTED, and
-- the demuxer (remuxing) and audio work.
function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?) function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDecoder?, Err.Err?)
local o: OpenOptions = opts or {} local o: OpenOptions = opts or {}
local track: Types.Track? = nil local track: Types.Track? = nil
@@ -435,7 +394,6 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then if v.frames == 0 and v.frameRate > 0 and v.duration > 0 then
v.frames = math.floor(v.duration * v.frameRate + 0.5) v.frames = math.floor(v.duration * v.frameRate + 0.5)
end end
-- audio
if o.audio ~= false then if o.audio ~= false then
local at = demuxer:track("audio") local at = demuxer:track("audio")
if at then if at then
@@ -469,8 +427,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
local t = (pts or 0) / scale - start local t = (pts or 0) / scale - start
if t + 1e-9 >= skipUntil then if t + 1e-9 >= skipUntil then
if index < 0 then if index < 0 then
-- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps); -- after a seek: constant-rate index = round(pts * fps), else counted from the seek
-- without a frame rate, counted from the seek)
index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0 index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0
end end
index += 1 index += 1
@@ -531,9 +488,6 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
return v, nil return v, nil
end end
-- ------------------------------------------------------------------------------------------------ frames-backed
-- fromFrames(images, delays, opts?) -> a VideoDecoder over full-canvas images (animated GIF / APNG / WebP after
-- coalescing): delays[i] seconds (a number = every frame). opts.format / opts.loops / opts.meta are recorded.
function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?) function Video.fromFrames(images: { Types.Image }, delays: (number | { number })?, opts: any?): (Types.VideoDecoder?, Err.Err?)
if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then if type(images) ~= "table" or #images == 0 or type(images[1]) ~= "table" then
return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images") return nil, Err.new(Err.ARG, "fromFrames: needs a list of Images")