Files
rosetta/src/Formats/codecs/video/Mpeg2/init.luau
T
4DBug 29c8bd1a11 ws-video2: codecs/video/Mpeg2 (MPEG-1/2 core, Main profile, 4:2:2, field pictures, dual prime), bit-exact with ffmpeg -idct int
Mpeg1 is now the Mpeg2 module under its old name (core, tables and VLCs moved to Mpeg2/). Dsp.mc takes separate
source / destination strides; Dsp.edge emulates edges. containers/MpegEs: field-picture pairs are one access unit
(pictureStructure). Registry: mpeg1 and mpeg2 decode through Mpeg2.newVideoDecoder; more MPEG-2 FourCCs.
2026-10-31 14:25:51 -05:00

365 lines
12 KiB
Luau

--!strict
-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
-- Progressive and interlaced (frame and field pictures, field / dual-prime prediction, field DCT), 4:2:0 and 4:2:2, I /
-- P / B pictures with display reordering, every MPEG-2 coding tool of Main profile (Mpeg2/Decoder.luau). Output planes
-- are bit-exact with `ffmpeg -idct int` (codecs/video/Dsp; tests/codecs/mpeg2.luau, tests/codecs/mpeg1.luau). Grown from
-- the MPEG-1 decoder absorbed from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). codecs/video/Mpeg1 is this
-- module under its old name. Frames come out woven (both fields of an interlaced frame, top field on even lines);
-- frame.fields / topFieldFirst / repeatFirstField / progressive say how they were coded.
-- Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
--
-- local dec = Mpeg2.new({ reorder = true, rgba = false })
-- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts
-- local img = Mpeg2.frameImage(frame) -- a fresh yuv420p Types.Image (rgba8 with frameImage(f, true))
-- dec:write(bytes); local f = dec:decodeFrame() -- or an elementary stream in pieces
-- while true do local f = dec:flush(); if not f then break end end -- at the end; dec:reset() after a seek
-- -- frame = { width, height, pixels (RGBA8 or nil, decoder-owned), y / cb / cr / codedWidth, chroma, ... }
-- local vdec = Mpeg2.newVideoDecoder(track, opts) -- a Types.VideoCodecDecoder (codecs/video/Video: mpeg1, mpeg2)
--
-- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau).
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local D = require("@formats/codecs/video/Mpeg2/Decoder")
local Mpeg2 = {}
Mpeg2.PICTURE_I = 1
Mpeg2.PICTURE_P = 2
Mpeg2.PICTURE_B = 3
export type Frame = {
width: number,
height: number,
pixels: buffer?, -- RGBA8, width * height * 4 bytes, row-major, alpha 255; nil with { rgba = false }
pictureType: number, -- 1 I, 2 P, 3 B
temporalReference: number, -- the picture's 10-bit display index within its GOP
index: number, -- frames returned so far (1-based)
tag: any, -- the tag passed to decode() with this picture's data (follows the picture through reordering)
-- the decoded YCbCr planes (decoder-owned, valid until the next decode): luma stride codedWidth, chroma stride
-- codedWidth / 2, chroma rows half the luma rows (4:2:0) or as many (4:2:2)
y: buffer,
cb: buffer,
cr: buffer,
codedWidth: number,
chroma: number, -- 1 = 4:2:0, 2 = 4:2:2
mpeg2: boolean,
progressive: boolean, -- progressive_frame (MPEG-1 and progressive MPEG-2: true)
fields: boolean, -- coded as two field pictures
topFieldFirst: boolean,
repeatFirstField: boolean,
clamped: number, -- predictions from outside the reference picture (an invalid stream; edge samples repeated)
concealed: { [number]: boolean }, -- 16-line bands with macroblocks no slice covered (concealed)
}
export type Options = {
reorder: boolean?, -- true: return frames in display order (B-frame streams; one frame of delay, flush() at the
-- end). Default false: every picture is returned as soon as it is decoded (decode order, no delay), which is
-- display order for streams without B-frames.
rgba: boolean?, -- default true; false skips the RGBA conversion (use frame.y / cb / cr)
maxPixels: number?, -- larger sequence headers are rejected (default 4096 * 2304)
}
local Decoder = {}
Decoder.__index = Decoder
export type Decoder = typeof(setmetatable(
{} :: {
_core: D.Core,
_reorder: boolean,
_rgba: boolean,
_held: D.Store?,
_pixels: buffer?,
_count: number,
width: number,
height: number,
frameRate: number,
bitRate: number,
stats: { pictures: number, errors: number, skipped: number },
},
Decoder
))
function Mpeg2.new(opts: Options?): Decoder
local o: Options = if type(opts) == "table" then opts else {}
local core = D.new(o.maxPixels)
return setmetatable({
_core = core,
_reorder = o.reorder == true,
_rgba = o.rgba ~= false,
_held = nil,
_pixels = nil,
_count = 0,
width = 0,
height = 0,
frameRate = 0,
bitRate = 0,
stats = { pictures = 0, errors = 0, skipped = 0 },
}, Decoder)
end
local function emit(self: Decoder, s: D.Store): Frame
local core = self._core
local pixels: buffer? = nil
if self._rgba then
local need = s.w * s.h * 4
local px = self._pixels
if px == nil or buffer.len(px) ~= need then
px = buffer.create(need)
self._pixels = px
end
core.toRgba(s, px :: buffer)
pixels = px
end
self._count += 1
return {
width = s.w,
height = s.h,
pixels = pixels,
pictureType = s.ptype,
temporalReference = s.tref,
index = self._count,
tag = s.tag,
y = s.y,
cb = s.cb,
cr = s.cr,
codedWidth = s.cw,
chroma = s.chroma,
mpeg2 = s.mpeg2,
progressive = s.progressive,
fields = s.fields,
topFieldFirst = s.tff,
repeatFirstField = s.rff,
clamped = s.clamped,
concealed = s.concealed,
}
end
local function sync(self: Decoder)
local st = self._core.state
self.width = st.width
self.height = st.height
self.frameRate = st.frameRate
self.bitRate = st.bitRate
self.stats.pictures = st.pictures
self.stats.errors = st.errors
self.stats.skipped = st.skipped
end
-- a decoded picture -> the frame to return now (nil while reordering holds it)
local function handle(self: Decoder, s: D.Store): Frame?
if not self._reorder or s.ptype == D.PICTURE_B then
return emit(self, s)
end
local prev = self._held
self._held = s
if prev then
return emit(self, prev)
end
return nil
end
local function run(self: Decoder, atEnd: boolean, tag: any): Frame?
local core = self._core
while true do
local s, needData = core.nextPicture(atEnd, tag)
sync(self)
if s then
local f = handle(self, s)
if f then
return f
end
elseif needData then
return nil
end
end
end
local function append(self: Decoder, data: any, offset: number?, len: number?): boolean
local src: buffer
if type(data) == "string" then
src = buffer.fromstring(data)
elseif type(data) == "buffer" then
src = data
else
return false
end
local total = buffer.len(src)
local off = math.floor(tonumber(offset) or 0)
if off < 0 or off > total then
return false
end
local n = math.floor(tonumber(len) or (total - off))
if n < 0 or off + n > total then
return false
end
self._core.write(src, off, n)
return true
end
-- Appends elementary-stream bytes (buffer or string; offset / len select a part). False for a bad argument.
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
-- The next complete picture of the written stream as a frame, or nil when more data is needed (a picture is
-- complete once the next picture / sequence / GOP start code has been written; flush() ends the last one).
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
-- Decodes one access unit (a picture, optionally preceded by sequence / GOP headers: a TS video unit's data).
-- The end of the data ends the picture. tag (any value, e.g. the unit's pts) comes back as frame.tag.
function Decoder.decode(self: Decoder, data: buffer | string, offset: number?, len: number?, tag: any): Frame?
if not append(self, data, offset, len) then
return nil
end
return run(self, true, tag)
end
-- At the end of the stream: decodes what is left of the written data, then returns the reference picture held
-- for reordering. Call until it returns nil.
function Decoder.flush(self: Decoder): Frame?
local f = run(self, true, nil)
if f then
return f
end
local held = self._held
if held then
self._held = nil
return emit(self, held)
end
return nil
end
-- Forgets buffered data and references (after a seek: the next picture decoded is the next I-picture).
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
-- frameImage(frame, rgba?) -> Types.Image: a copy of a decoded frame (the decoder reuses its planes), cropped to
-- width x height: yuv420p from frame.y / cb / cr (BT.601 limited range, meta.source.range = "limited"; 4:2:2 chroma
-- averaged over line pairs of the same field), or rgba8 (the decoder's BT.601 conversion) when rgba is true. nil for
-- a value that is not a Frame.
function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
if type(frame) ~= "table" or type(frame.y) ~= "buffer" or type(frame.cb) ~= "buffer" or type(frame.cr) ~= "buffer" then
return nil
end
local w, h, cw = frame.width, frame.height, frame.codedWidth
if type(w) ~= "number" or type(h) ~= "number" or type(cw) ~= "number" or w < 1 or h < 1 or cw < w then
return nil
end
local c422 = frame.chroma == 2
local chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2
local crows = if c422 then h else oh
if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * crows or buffer.len(frame.cr) < chw * crows then
return nil
end
local img
if rgba then
img = Types.Image.new(w, h)
if c422 then
D.toRgba422(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
else
D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels)
end
else
img = Types.Image.new(w, h, "yuv420p")
local px = img.pixels
for y = 0, h - 1 do
buffer.copy(px, y * w, frame.y, y * cw, w)
end
local o = w * h
if not c422 then
for y = 0, oh - 1 do
buffer.copy(px, o + y * ow, frame.cb, y * chw, ow)
buffer.copy(px, o + ow * oh + y * ow, frame.cr, y * chw, ow)
end
else
-- 4:2:2 -> 4:2:0: progressive frames average lines 2k, 2k + 1; interlaced ones lines of the same field
-- (4k + j and 4k + j + 2), so the fields do not mix
local inter = not frame.progressive
for y = 0, oh - 1 do
local a, b
if inter then
local base = (y // 2) * 4 + y % 2
a, b = base, base + 2
else
a, b = 2 * y, 2 * y + 1
end
if b >= h then
b = a
end
for x = 0, ow - 1 do
buffer.writeu8(px, o + y * ow + x, (buffer.readu8(frame.cb, a * chw + x) + buffer.readu8(frame.cb, b * chw + x) + 1) // 2)
buffer.writeu8(px, o + ow * oh + y * ow + x, (buffer.readu8(frame.cr, a * chw + x) + buffer.readu8(frame.cr, b * chw + x) + 1) // 2)
end
end
end
end
img.meta.source = {
format = if frame.mpeg2 then "mpeg2" else "mpeg1",
pictureType = frame.pictureType,
temporalReference = frame.temporalReference,
chroma = if c422 then "422" else "420",
interlaced = not frame.progressive,
topFieldFirst = frame.topFieldFirst,
range = if rgba then nil else "limited",
}
return img
end
-- ------------------------------------------------------------------------------------------------ VideoCodecDecoder
-- newVideoDecoder(track, opts) -> a Types.VideoCodecDecoder (codecs/video/Video's mpeg1 and mpeg2 entries): pictures in
-- decode order, reordered for display; the packet's pts travels with its picture. A packet may hold any number of
-- pictures (MPEG-PS / TS units, AVI chunks) or part of one (written as a stream).
function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
local dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels })
local queue: { any } = {}
local function push(f: Frame)
local img = Mpeg2.frameImage(f)
if img then
img.meta.yuv = { range = "limited", matrix = "bt601" }
local tag = f.tag
table.insert(queue, { img, if type(tag) == "table" then tag[1] else nil, f.pictureType == 1 })
end
end
local self = {}
function self.decode(_: any, packet: Types.Packet): Err.Err?
local tag = { packet.pts }
local ok, f = pcall(dec.decode, dec, packet.data, 0, buffer.len(packet.data), tag)
if not ok then
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(f))
end
while f do -- more pictures in the packet
push(f)
f = dec:decode(packet.data, 0, 0, tag)
end
return nil
end
function self.receive(_: any): (Types.Image?, number?, boolean?)
local q = table.remove(queue, 1)
if q then
return q[1], q[2], q[3]
end
return nil, nil, nil
end
function self.flush(_: any)
for _ = 1, 8 do
local f = dec:flush()
if not f then
break
end
push(f)
end
end
function self.reset(_: any)
dec:reset()
table.clear(queue)
end
return self :: any, nil
end
return Mpeg2