Files
rosetta/src/Rosetta/codecs/video/Mpeg2/init.luau
T

366 lines
10 KiB
Luau

--!strict
-- codecs/video/Mpeg2: an MPEG-1 / MPEG-2 video decoder (ISO/IEC 11172-2, ISO/IEC 13818-2 Main profile).
-- Bit-exact with `ffmpeg -idct int`. Grown from mpeg1-luau e2e2898 (same author), a port of jsmpeg's decoder
-- (https://github.com/phoboslab/jsmpeg, Dominic Szablewski, MIT: licenses/jsmpeg-MIT.txt). Frames come out woven (top
-- field on even lines). Not supported: 4:4:4, the scalable / multiview extensions, D-pictures (skipped).
local Types = require("@rosetta/Types")
local Err = require("@rosetta/core/Err")
local D = require("@rosetta/codecs/video/Mpeg2/Decoder")
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,
tag: any,
-- luma stride codedWidth, chroma stride codedWidth / 2; chroma rows half the luma rows (4:2:0) or as many (4:2:2)
y: buffer,
cb: buffer,
cr: buffer,
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,
topFieldFirst: boolean,
repeatFirstField: boolean,
clamped: number,
concealed: { [number]: boolean },
}
export type Options = {
reorder: boolean?,
rgba: boolean?,
maxPixels: number?,
yield: (() -> ())?,
}
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)
if type(o.yield) == "function" then
core.setYield(o.yield)
end
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
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
function Decoder.write(self: Decoder, data: buffer | string, offset: number?, len: number?): boolean
return append(self, data, offset, len)
end
function Decoder.decodeFrame(self: Decoder): Frame?
return run(self, false, nil)
end
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
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
function Decoder.setYield(self: Decoder, hook: (() -> ())?)
self._core.setYield(if type(hook) == "function" then hook else nil)
end
function Decoder.reset(self: Decoder)
self._core.reset()
self._held = nil
end
function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, width: number, height: number, out: buffer, row0: number?, row1: number?, outOffset: number?, planeRow0: number?, hook: (() -> ())?): boolean
if type(y) ~= "buffer" or type(cb) ~= "buffer" or type(cr) ~= "buffer" or type(out) ~= "buffer" then
return false
end
local cw, w, h = tonumber(codedWidth), tonumber(width), tonumber(height)
if not cw or not w or not h or cw % 2 ~= 0 or w < 1 or h < 1 or w > cw or cw ~= math.floor(cw) or w ~= math.floor(w) or h ~= math.floor(h) then
return false
end
local r0 = math.floor(tonumber(row0) or 0)
r0 -= r0 % 2
local r1 = math.floor(tonumber(row1) or h)
local pr = math.floor(tonumber(planeRow0) or 0)
local oo = math.floor(tonumber(outOffset) or 0)
if r0 < 0 or r1 > h or r1 <= r0 or pr < 0 or pr % 2 ~= 0 or pr > r0 or oo < 0 or oo % 4 ~= 0 then
return false
end
local lumaRows = r1 - pr
local chromaRows = (r1 + 1) // 2 - pr // 2
if buffer.len(y) < lumaRows * cw or buffer.len(cb) < chromaRows * (cw // 2) or buffer.len(cr) < chromaRows * (cw // 2) then
return false
end
if buffer.len(out) < oo + (r1 - r0) * w * 4 then
return false
end
D.toRgba(y, cb, cr, cw, w, h, out, r0 - pr, r1 - pr, oo, if type(hook) == "function" then hook else nil)
return true
end
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
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
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