--!strict -- codecs/Mpeg1: an MPEG-1 video decoder (ISO/IEC 11172-2) for the MPEG-TS / MPEG-PS video formats. Absorbed from -- mpeg1-luau e2e2898 (same author; README, docs/api.md and docs/performance.md there), a port of jsmpeg's decoder -- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt) extended with B-pictures, -- an islow integer IDCT, table-driven VLC decoding and BT.601 RGBA8 output; added here: frameImage. -- Supports: I, P and B pictures (D-pictures skipped), half / full-pel motion vectors with any f_code, custom -- quantiser matrices, sequence headers anywhere (size changes), any size up to 4095 x 4095 (maxPixels), display -- reordering. Accuracy: within ~0.75 MAE per RGBA channel of ffmpeg's decode (tests/codecs/mpeg1.luau). -- Not supported: MPEG-2 streams (no picture coding extension parsing), field pictures, D-picture decoding. -- -- local dec = Mpeg1.new({ reorder = true, rgba = false }) -- local frame = dec:decode(packetData, 0, len, pts) -- one picture (+ sequence / GOP headers) -> Frame?, tag = pts -- local img = Mpeg1.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, pictureType, ... } -- -- Nothing here throws: bad arguments return nil / false, bad data is skipped (see Decoder.luau). local Types = require("@formats/Types") local D = require("@formats/codecs/Mpeg1/Decoder") local Mpeg1 = {} Mpeg1.PICTURE_I = 1 Mpeg1.PICTURE_P = 2 Mpeg1.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 4:2:0 planes (decoder-owned, valid until the next decode): luma stride codedWidth, -- chroma stride codedWidth / 2 y: buffer, cb: buffer, cr: buffer, codedWidth: number, } 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 Mpeg1.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, } 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"), or rgba8 -- (the decoder's BT.601 conversion) when rgba is true. nil for a value that is not a Frame. function Mpeg1.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 chw, ow, oh = cw // 2, (w + 1) // 2, (h + 1) // 2 if buffer.len(frame.y) < cw * h or buffer.len(frame.cb) < chw * oh or buffer.len(frame.cr) < chw * oh then return nil end local img if rgba then img = Types.Image.new(w, h) D.toRgba(frame.y, frame.cb, frame.cr, cw, w, h, img.pixels) 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 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 end img.meta.source = { format = "mpeg1", pictureType = frame.pictureType, temporalReference = frame.temporalReference, range = if rgba then nil else "limited", } return img end return Mpeg1