video: yield points in H.264 picture setup and VP8 rows, rgba / scale conversion; disposable packets and skipDisposable
- H264: picture and grid allocations split between yield calls (a 1080p picture's tables are 1.6 M slots) - Vp8: Decode.decodeFrame hook three times per macroblock row and once per loop filter row; Options.yield - Yuv.toRgba / Yuv.scale: optional hook every 16 rows; imageToRgba / imageScale take an out Image and the hook - Video.open passes opts.yield to the conversions, the VP8 and MPEG-1/2 decoders - codecs/video/Video/Disposable: H.264 nal_ref_idc 0 (avcC length-prefixed / Annex B), VP8 frames refreshing no reference; containers/Demux sets packet.disposable for h264 / vp8 tracks; Video.isDisposable(track, packet) - skipDisposable: H.264 keeps skipped pictures in output order (pts pool / POC bookkeeping), VP8 applies the header state then skips; receive() returns false for a skipped picture, VideoFrame.index counts it - Types: Packet.disposable, VideoCodecDecoder.receive may return false - tools/fixtures/videoctl.py: VP8 two temporal layers (IVF + WebM)
This commit is contained in:
1 parent
dde6be117c
commit
15e0dfcc86
12 files changed
+469
-74
No files matched your search
@@ -184,6 +184,7 @@ export type Packet = {
|
||||
duration: number?, -- ticks
|
||||
keyframe: boolean,
|
||||
data: buffer, -- the packet's bytes (its own buffer)
|
||||
disposable: boolean?, -- true: no later frame predicts from this one (H.264 nal_ref_idc 0, VP8 no reference refresh)
|
||||
}
|
||||
export type Demuxer = {
|
||||
kind: "demuxer",
|
||||
@@ -227,7 +228,8 @@ export type VideoDecoder = {
|
||||
-- a codec's decoder instance (codecs/video/Video registry entries create them): packets in, pictures out
|
||||
export type VideoCodecDecoder = {
|
||||
decode: (self: any, packet: Packet) -> Err?, -- feed one packet (decode order)
|
||||
receive: (self: any) -> (Image?, number?, boolean?), -- the next picture, the pts (ticks) it carries, keyframe | nil
|
||||
-- the next picture, the pts (ticks) it carries, keyframe | nil; false for a picture skipped (opts.skipDisposable)
|
||||
receive: (self: any) -> (Image? | false, number?, boolean?),
|
||||
flush: (self: any) -> (), -- end of stream: pictures held for reordering become available to receive()
|
||||
reset: (self: any) -> (), -- after a seek: drop references / held pictures
|
||||
}
|
||||
|
||||
@@ -1164,8 +1164,9 @@ end
|
||||
export type Frame = {
|
||||
width: number,
|
||||
height: number,
|
||||
ref: Ref,
|
||||
ref: Ref?, -- nil when skipped
|
||||
header: any,
|
||||
skipped: boolean?,
|
||||
}
|
||||
|
||||
local BORDER = Predict.BORDER
|
||||
@@ -1198,7 +1199,7 @@ local function freeRef(st: State): Ref
|
||||
end
|
||||
|
||||
function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number, dv: buffer, ov: number)
|
||||
local r = f.ref
|
||||
local r = f.ref :: Ref
|
||||
local w, h = f.width, f.height
|
||||
local cw, chh = (w + 1) // 2, (h + 1) // 2
|
||||
local Y, U, V, ys, uvs, yb, uvb = r.Y, r.U, r.V, r.ys, r.uvs, r.yb, r.uvb
|
||||
@@ -1211,7 +1212,12 @@ function Decode.cropTo(f: Frame, dy: buffer, oy: number, du: buffer, ou: number,
|
||||
end
|
||||
end
|
||||
|
||||
function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number): (Frame?, string?)
|
||||
-- hook: called (through pcall) three times per macroblock row (modes, residuals, reconstruction) and once per loop filter
|
||||
-- row, a cooperative yield point; the module
|
||||
-- scratch is per macroblock, so other VP8 decodes may run while one is suspended
|
||||
-- skip: a frame that refreshes no reference and no segment map comes back { skipped = true } after its header (the
|
||||
-- state the header carries is kept, the picture is not reconstructed)
|
||||
function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, maxPixels: number, hook: (() -> ())?, skip: boolean?): (Frame?, string?)
|
||||
local hdr, herr = Decode.header(buf, off, len)
|
||||
if not hdr then
|
||||
return nil, herr
|
||||
@@ -1427,6 +1433,12 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
if br.eof then
|
||||
return fail("truncated: frame header")
|
||||
end
|
||||
if skip and not key and not refreshGolden and not refreshAlt and copyToGolden == 0 and copyToAlt == 0 and not refreshLast and not st.updateMap then
|
||||
if saved then
|
||||
st.proba, st.ymodeProb, st.uvmodeProb, st.mvProb = saved[1], saved[2], saved[3], saved[4]
|
||||
end
|
||||
return { width = width, height = height, ref = nil, header = hdr, skipped = true }, nil
|
||||
end
|
||||
|
||||
-- loop filter levels [segment][reference][mode delta index] and, per level, the interior limit and hev threshold
|
||||
local lvlTab = table.create(64, 0)
|
||||
@@ -1532,6 +1544,9 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
local miMvR, miMvC, miSubR, miSubC = st.miMvR, st.miMvC, st.miSubR, st.miSubC
|
||||
|
||||
for mby = 0, mbh - 1 do
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local tbr = parts[band(mby, lastPart) + 1]
|
||||
-- modes of the row (first partition)
|
||||
for k = 1, 4 do
|
||||
@@ -1628,6 +1643,9 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
return fail("truncated: first partition (modes)")
|
||||
end
|
||||
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
-- residuals (token partition)
|
||||
local leftNz, leftNzDc = 0, 0
|
||||
for mbx = 0, mbw - 1 do
|
||||
@@ -1756,6 +1774,9 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
bfill(yuv, U_OFF - BPS - 1, 127, 8 + 1)
|
||||
bfill(yuv, V_OFF - BPS - 1, 127, 8 + 1)
|
||||
end
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
for mbx = 0, mbw - 1 do
|
||||
local x1 = mbx + 1
|
||||
local co = mbx * 768
|
||||
@@ -1865,6 +1886,9 @@ function Decode.decodeFrame(st: State, buf: buffer, off: number, len: number, ma
|
||||
-- loop filter over the whole frame, macroblocks in raster order (libwebp DoFilter)
|
||||
if filterType > 0 then
|
||||
for mby = 0, mbh - 1 do
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
for mbx = 0, mbw - 1 do
|
||||
local fi = mby * mbw + mbx + 1
|
||||
local limit = fLimit[fi]
|
||||
|
||||
@@ -14,6 +14,9 @@ local DEFAULT_MAX_PIXELS = 2 ^ 28
|
||||
|
||||
export type Options = {
|
||||
maxPixels: number?,
|
||||
yield: (() -> ())?, -- called through pcall a few times per macroblock row (decode and loop filter)
|
||||
-- decodeFrame returns nil, nil for an inter frame that refreshes no reference (its header still applies)
|
||||
skipDisposable: boolean?,
|
||||
}
|
||||
|
||||
local function fail(msg: string?, offset: number?): Err.Err
|
||||
@@ -60,9 +63,11 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
|
||||
return nil, Err.new(Err.ARG, "decodeFrame: expected a buffer")
|
||||
end
|
||||
local o, l = range(buf, off, len)
|
||||
local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS)
|
||||
local f, err = Decode.decodeFrame(self.state, buf, o, l, opts and opts.maxPixels or DEFAULT_MAX_PIXELS, opts and opts.yield, opts and opts.skipDisposable)
|
||||
if not f then
|
||||
return nil, fail(err, o)
|
||||
elseif f.skipped then
|
||||
return nil, nil
|
||||
end
|
||||
local img = Types.Image.new(f.width, f.height, "yuv420p")
|
||||
local ny = f.width * f.height
|
||||
|
||||
@@ -66,7 +66,8 @@ for i = 1, 2304 do
|
||||
CB[i] = v * 65536 + 0xff000000
|
||||
end
|
||||
|
||||
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?): buffer
|
||||
-- hook: called (through pcall) every 16 rows, a cooperative yield point
|
||||
function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, cw: number, range: string?, matrix: string?, out: buffer?, hook: (() -> ())?): buffer
|
||||
local dst = out or bcreate(w * h * 4)
|
||||
local c = coeffs(range, matrix)
|
||||
local crv, cgu, cgv, cbu = c.crv, c.cgu, c.cgv, c.cbu
|
||||
@@ -78,6 +79,9 @@ function Yuv.toRgba(src: buffer, w: number, h: number, uo: number, vo: number, c
|
||||
local w2 = w // 2
|
||||
local stride = w * 4
|
||||
for y = 0, h - 1, 2 do
|
||||
if hook and y % 16 == 0 and y > 0 then
|
||||
pcall(hook)
|
||||
end
|
||||
local yrow = y * w
|
||||
local ci = uo + (y // 2) * cw
|
||||
local dv = vo - uo
|
||||
@@ -212,7 +216,8 @@ function Yuv.toFullRange(img: Types.Image): Types.Image
|
||||
return out
|
||||
end
|
||||
|
||||
function Yuv.imageToRgba(img: Types.Image): Types.Image?
|
||||
-- out: an rgba8 Image of the same size to write into (else a new one)
|
||||
function Yuv.imageToRgba(img: Types.Image, out: Types.Image?, hook: (() -> ())?): Types.Image?
|
||||
if img.format == "rgba8" then
|
||||
return img
|
||||
end
|
||||
@@ -222,10 +227,13 @@ function Yuv.imageToRgba(img: Types.Image): Types.Image?
|
||||
local w, h = img.width, img.height
|
||||
local uo, vo, cw = Yuv.planes(w, h)
|
||||
local range, matrix = info(img)
|
||||
local out = Types.Image.new(w, h, "rgba8")
|
||||
Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, out.pixels)
|
||||
out.meta.source = img.meta.source
|
||||
return out
|
||||
if not out or out.format ~= "rgba8" or out.width ~= w or out.height ~= h or buffer.len(out.pixels) < w * h * 4 then
|
||||
out = Types.Image.new(w, h, "rgba8")
|
||||
end
|
||||
local o = out :: Types.Image
|
||||
Yuv.toRgba(img.pixels, w, h, uo, vo, cw, range, matrix, o.pixels, hook)
|
||||
o.meta.source = img.meta.source
|
||||
return o
|
||||
end
|
||||
|
||||
function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): Types.Image?
|
||||
@@ -242,9 +250,12 @@ function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): T
|
||||
return out
|
||||
end
|
||||
|
||||
local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number)
|
||||
local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number, hook: (() -> ())?)
|
||||
local fx, fy = sw / dw, sh / dh
|
||||
for y = 0, dh - 1 do
|
||||
if hook and y % 16 == 15 then
|
||||
pcall(hook)
|
||||
end
|
||||
local sy = (y + 0.5) * fy - 0.5
|
||||
if sy < 0 then
|
||||
sy = 0
|
||||
@@ -275,7 +286,7 @@ local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst:
|
||||
end
|
||||
end
|
||||
|
||||
function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer
|
||||
function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?, hook: (() -> ())?): buffer
|
||||
local dw: number = math.max(1, floor(width))
|
||||
local dh: number = math.max(1, floor(height))
|
||||
local cw: number = (w + 1) // 2
|
||||
@@ -287,17 +298,22 @@ function Yuv.scale(src: buffer, w: number, h: number, width: number, height: num
|
||||
if w < 1 or h < 1 or buffer.len(src) < w * h + 2 * cw * ch then
|
||||
return dst
|
||||
end
|
||||
scalePlane(src, 0, w, h, dst, 0, dw, dh)
|
||||
scalePlane(src, w * h, cw, ch, dst, dw * dh, dcw, dch)
|
||||
scalePlane(src, w * h + cw * ch, cw, ch, dst, dw * dh + dcw * dch, dcw, dch)
|
||||
scalePlane(src, 0, w, h, dst, 0, dw, dh, hook)
|
||||
scalePlane(src, w * h, cw, ch, dst, dw * dh, dcw, dch, hook)
|
||||
scalePlane(src, w * h + cw * ch, cw, ch, dst, dw * dh + dcw * dch, dcw, dch, hook)
|
||||
return dst
|
||||
end
|
||||
|
||||
function Yuv.imageScale(img: Types.Image, dw: number, dh: number): Types.Image
|
||||
local out = Types.Image.new(math.max(1, floor(dw)), math.max(1, floor(dh)), "yuv420p")
|
||||
Yuv.scale(img.pixels, img.width, img.height, out.width, out.height, out.pixels)
|
||||
out.meta = table.clone(img.meta or {})
|
||||
return out
|
||||
-- out: a yuv420p Image of the target size to write into (else a new one)
|
||||
function Yuv.imageScale(img: Types.Image, dw: number, dh: number, out: Types.Image?, hook: (() -> ())?): Types.Image
|
||||
local tw, th = math.max(1, floor(dw)), math.max(1, floor(dh))
|
||||
if not out or out.format ~= "yuv420p" or out.width ~= tw or out.height ~= th then
|
||||
out = Types.Image.new(tw, th, "yuv420p")
|
||||
end
|
||||
local o = out :: Types.Image
|
||||
Yuv.scale(img.pixels, img.width, img.height, tw, th, o.pixels, hook)
|
||||
o.meta = table.clone(img.meta or {})
|
||||
return o
|
||||
end
|
||||
|
||||
return Yuv
|
||||
@@ -27,6 +27,8 @@ export type Options = {
|
||||
-- yield is pcall'ed (it can't throw through native code); the entropy decoders keep state in module locals, so no
|
||||
-- other H.264 decode may run in the VM while one is suspended
|
||||
yield: (() -> ())?,
|
||||
-- pictures with nal_ref_idc 0 are not reconstructed: they keep their place in output order as { skipped = true }
|
||||
skipDisposable: boolean?,
|
||||
}
|
||||
|
||||
function Decoder.new(opts: Options?): any
|
||||
@@ -76,6 +78,26 @@ local function newPicture(self: any, sps: any): any
|
||||
local ys = w + 2 * PAD
|
||||
local cs = w // 2 + 2 * PADC
|
||||
local n4 = mbW * mbH * 16
|
||||
-- a 1080p picture's tables are 1.6 M slots: allocated in steps between yields
|
||||
local hook = self.opts.yield
|
||||
local y = buffer.create(ys * (h + 2 * PAD))
|
||||
local u, v = buffer.create(cs * (h // 2 + 2 * PADC)), buffer.create(cs * (h // 2 + 2 * PADC))
|
||||
local ref0, ref1 = table.create(n4, -1), table.create(n4, -1)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local uid0, uid1 = table.create(n4, -1), table.create(n4, -1)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local mv0 = table.create(n4 * 2, 0)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local mv1 = table.create(n4 * 2, 0)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
return {
|
||||
mbW = mbW,
|
||||
mbH = mbH,
|
||||
@@ -83,16 +105,16 @@ local function newPicture(self: any, sps: any): any
|
||||
cs = cs,
|
||||
yo = PAD * ys + PAD,
|
||||
co = PADC * cs + PADC,
|
||||
y = buffer.create(ys * (h + 2 * PAD)),
|
||||
u = buffer.create(cs * (h // 2 + 2 * PADC)),
|
||||
v = buffer.create(cs * (h // 2 + 2 * PADC)),
|
||||
y = y,
|
||||
u = u,
|
||||
v = v,
|
||||
mbIntra = table.create(mbW * mbH, true),
|
||||
ref0 = table.create(n4, -1),
|
||||
ref1 = table.create(n4, -1),
|
||||
uid0 = table.create(n4, -1),
|
||||
uid1 = table.create(n4, -1),
|
||||
mv0 = table.create(n4 * 2, 0),
|
||||
mv1 = table.create(n4 * 2, 0),
|
||||
ref0 = ref0,
|
||||
ref1 = ref1,
|
||||
uid0 = uid0,
|
||||
uid1 = uid1,
|
||||
mv0 = mv0,
|
||||
mv1 = mv1,
|
||||
uid = 0,
|
||||
poc = 0,
|
||||
frameNum = 0,
|
||||
@@ -100,12 +122,13 @@ local function newPicture(self: any, sps: any): any
|
||||
short = false,
|
||||
longIdx = 0,
|
||||
waiting = false,
|
||||
skipped = false,
|
||||
pts = 0,
|
||||
}
|
||||
end
|
||||
|
||||
local function release(self: any, p: any)
|
||||
if not p.short and not p.long and not p.waiting and p ~= self.cur and p ~= self.gray then
|
||||
if not p.short and not p.long and not p.waiting and p ~= self.cur and p ~= self.gray and not p.skipped then
|
||||
for _, q in self.pool do
|
||||
if q == p then
|
||||
return
|
||||
@@ -132,6 +155,10 @@ end
|
||||
|
||||
local function emit(self: any, p: any)
|
||||
p.waiting = false
|
||||
if p.skipped then
|
||||
table.insert(self.out, { image = nil, skipped = true, pts = p.pts, duration = 0, poc = p.poc, keyframe = false })
|
||||
return
|
||||
end
|
||||
local sps = p.sps
|
||||
local W, H = sps.width, sps.height
|
||||
local img = Types.Image.new(W, H, "yuv420p")
|
||||
@@ -571,7 +598,7 @@ local function setupGrids(self: any, sps: any)
|
||||
if self.S and self.S.mbW == mbW and self.S.mbH == mbH then
|
||||
return
|
||||
end
|
||||
local S = Mb.grids(mbW, mbH)
|
||||
local S = Mb.grids(mbW, mbH, self.opts.yield)
|
||||
S.mbW, S.mbH = mbW, mbH
|
||||
S.w4 = mbW * 4
|
||||
S.cw4 = mbW * 2
|
||||
@@ -643,7 +670,9 @@ local function startPicture(self: any, sh: any, pts: number?)
|
||||
fillGap(self, sh)
|
||||
end
|
||||
end
|
||||
local p = newPicture(self, sps)
|
||||
local skip = sh.nalRefIdc == 0 and self.opts.skipDisposable == true
|
||||
-- a skipped picture only carries what output order and POC need
|
||||
local p = if skip then { skipped = true, short = false, long = false, waiting = false } else newPicture(self, sps)
|
||||
self.uid += 1
|
||||
p.uid = self.uid
|
||||
p.sps = sps
|
||||
@@ -660,6 +689,10 @@ local function startPicture(self: any, sh: any, pts: number?)
|
||||
self.decoded = 0
|
||||
self.sliceNum = 0
|
||||
self.sliceParams = {}
|
||||
if skip then
|
||||
return
|
||||
end
|
||||
p.skipped = false
|
||||
local S = self.S
|
||||
local st = S.sliceTab
|
||||
for i = 1, #st do
|
||||
@@ -720,20 +753,22 @@ local function finishPicture(self: any)
|
||||
end
|
||||
local sh = self.curSh
|
||||
local S = self.S
|
||||
if self.decoded < S.mbW * S.mbH then
|
||||
conceal(self, p)
|
||||
if not p.skipped then
|
||||
if self.decoded < S.mbW * S.mbH then
|
||||
conceal(self, p)
|
||||
end
|
||||
local hook = self.opts.yield
|
||||
if self.opts.deblock ~= false then
|
||||
Deblock.picture(S, p, self.sliceParams)
|
||||
end
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local w, h = S.mbW * 16, S.mbH * 16
|
||||
Inter.extend(p.y, p.yo, p.ys, w, h, PAD)
|
||||
Inter.extend(p.u, p.co, p.cs, w // 2, h // 2, PADC)
|
||||
Inter.extend(p.v, p.co, p.cs, w // 2, h // 2, PADC)
|
||||
end
|
||||
local hook = self.opts.yield
|
||||
if self.opts.deblock ~= false then
|
||||
Deblock.picture(S, p, self.sliceParams)
|
||||
end
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local w, h = S.mbW * 16, S.mbH * 16
|
||||
Inter.extend(p.y, p.yo, p.ys, w, h, PAD)
|
||||
Inter.extend(p.u, p.co, p.cs, w // 2, h // 2, PADC)
|
||||
Inter.extend(p.v, p.co, p.cs, w // 2, h // 2, PADC)
|
||||
local mmco5 = false
|
||||
if sh.nalRefIdc ~= 0 then
|
||||
mmco5 = mark(self, p, sh)
|
||||
@@ -979,6 +1014,10 @@ function Decoder.nal(self: any, buf: buffer, off: number, len: number, pts: numb
|
||||
end
|
||||
startPicture(self, sh, pts)
|
||||
end
|
||||
if self.cur.skipped then
|
||||
self.decoded = 1
|
||||
return
|
||||
end
|
||||
decodeSlice(self, sh, r)
|
||||
if self.decoded >= self.S.mbW * self.S.mbH then
|
||||
finishPicture(self)
|
||||
@@ -994,6 +1033,13 @@ 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
|
||||
end
|
||||
|
||||
-- the end of a packet holding one access unit: a skipped picture is complete
|
||||
function Decoder.packetEnd(self: any)
|
||||
if self.cur and self.cur.skipped then
|
||||
finishPicture(self)
|
||||
end
|
||||
end
|
||||
|
||||
function Decoder.flush(self: any)
|
||||
finishPicture(self)
|
||||
bump(self, 0)
|
||||
|
||||
@@ -75,11 +75,11 @@ function Mb.new(): any
|
||||
}
|
||||
end
|
||||
|
||||
function Mb.grids(mbW: number, mbH: number): any
|
||||
function Mb.grids(mbW: number, mbH: number, hook: (() -> ())?): any
|
||||
local n = mbW * mbH
|
||||
local n4 = n * 16
|
||||
local nc = n * 4
|
||||
return {
|
||||
local S = {
|
||||
sliceTab = table.create(n, 0),
|
||||
kind = table.create(n, 0),
|
||||
cbpTab = table.create(n, 0),
|
||||
@@ -95,12 +95,27 @@ function Mb.grids(mbW: number, mbH: number): any
|
||||
nzcCb = table.create(nc, 0),
|
||||
nzcCr = table.create(nc, 0),
|
||||
nzDb = table.create(n4, 0),
|
||||
ipm = table.create(n4, 2),
|
||||
mvd0 = table.create(n4 * 2, 0),
|
||||
mvd1 = table.create(n4 * 2, 0),
|
||||
rgt0 = table.create(n4, 0),
|
||||
rgt1 = table.create(n4, 0),
|
||||
ipm = false :: any,
|
||||
mvd0 = false :: any,
|
||||
mvd1 = false :: any,
|
||||
rgt0 = false :: any,
|
||||
rgt1 = false :: any,
|
||||
}
|
||||
-- 1080p: 1.5 M slots, allocated in steps between yields (Decoder Options.yield)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
S.ipm = table.create(n4, 2)
|
||||
S.mvd0 = table.create(n4 * 2, 0)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
S.mvd1 = table.create(n4 * 2, 0)
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
S.rgt0, S.rgt1 = table.create(n4, 0), table.create(n4, 0)
|
||||
return S
|
||||
end
|
||||
|
||||
function Mb.start(S: any, M: any, addr: number)
|
||||
|
||||
@@ -19,14 +19,16 @@ export type Options = {
|
||||
lowDelay: boolean?,
|
||||
deblock: boolean?,
|
||||
yield: (() -> ())?,
|
||||
skipDisposable: boolean?, -- pictures with nal_ref_idc 0 come out as { skipped = true } frames without an image
|
||||
}
|
||||
|
||||
export type Frame = {
|
||||
image: Types.Image,
|
||||
image: Types.Image, -- (nil when skipped)
|
||||
pts: number,
|
||||
duration: number,
|
||||
poc: number,
|
||||
keyframe: boolean,
|
||||
skipped: boolean?,
|
||||
}
|
||||
|
||||
local DecoderMeta = {}
|
||||
@@ -129,6 +131,7 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num
|
||||
break
|
||||
end
|
||||
end
|
||||
Decoder.packetEnd(st)
|
||||
local frames = Decoder.take(st)
|
||||
local e = status(self)
|
||||
if e then
|
||||
@@ -172,7 +175,7 @@ end
|
||||
|
||||
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,
|
||||
yield = opts and opts.yield }
|
||||
yield = opts and opts.yield, skipDisposable = opts and opts.skipDisposable }
|
||||
local function make(): (H264Decoder?, Err.Err?)
|
||||
local d, err = H264.newDecoder(o)
|
||||
if d and track.config then
|
||||
@@ -190,7 +193,7 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
|
||||
local queue: { any } = {}
|
||||
local pool: { number } = {}
|
||||
local outIndex: number? = if track.ptsInOutputOrder then 0 else nil
|
||||
local self: any = {}
|
||||
local self: any = { skipped = 0 }
|
||||
local function push(frames: { Frame })
|
||||
for _, f in frames do
|
||||
local pts = f.pts
|
||||
@@ -201,7 +204,12 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
|
||||
-- pictures take the packet timestamps in increasing order (right for MP4 / MKV / TS pts and AVI's decode-order times)
|
||||
pts = table.remove(pool, 1)
|
||||
end
|
||||
table.insert(queue, { f.image, pts, f.keyframe })
|
||||
if f.skipped then
|
||||
self.skipped += 1
|
||||
table.insert(queue, { false, pts, false })
|
||||
else
|
||||
table.insert(queue, { f.image, pts, f.keyframe })
|
||||
end
|
||||
end
|
||||
end
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
@@ -225,7 +233,7 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
|
||||
push(frames)
|
||||
return nil
|
||||
end
|
||||
function self.receive(_: any): (Types.Image?, number?, boolean?)
|
||||
function self.receive(_: any): (Types.Image? | false, number?, boolean?)
|
||||
local q = table.remove(queue, 1)
|
||||
if q then
|
||||
return q[1], q[2], q[3]
|
||||
|
||||
@@ -317,7 +317,7 @@ function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
|
||||
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 dec = Mpeg2.new({ reorder = true, rgba = false, maxPixels = opts and opts.maxPixels, yield = opts and opts.yield })
|
||||
local queue: { any } = {}
|
||||
local function push(f: Frame)
|
||||
local img = Mpeg2.frameImage(f)
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
--!strict
|
||||
--!optimize 2
|
||||
-- codecs/video/Video/Disposable: packets whose frame no later frame predicts from (a player may skip decoding them).
|
||||
-- H.264: the first VCL NAL unit has nal_ref_idc 0 (7.4.1: then every slice of the picture has), and no parameter
|
||||
-- set comes before it; one access unit per packet, length-prefixed (avcC lengthSizeMinusOne) or Annex B.
|
||||
-- VP8 (RFC 6386 9.3-9.11, 19.2): an inter frame that refreshes no reference (last / golden / altref, no copies) and
|
||||
-- leaves the segment map; its header may still change decoder state (probabilities, loop filter deltas).
|
||||
local readu8 = buffer.readu8
|
||||
|
||||
local Disposable = {}
|
||||
|
||||
-- the offset of the first byte after the first start code at or after p, or -1
|
||||
local function nextStart(b: buffer, p: number, e: number): number
|
||||
local i = p
|
||||
while i + 2 < e do
|
||||
local b2 = readu8(b, i + 2)
|
||||
if b2 > 1 then
|
||||
i += 3
|
||||
elseif readu8(b, i + 1) ~= 0 then
|
||||
i += 2
|
||||
elseif b2 == 1 and readu8(b, i) == 0 then
|
||||
return i + 3
|
||||
else
|
||||
i += 1
|
||||
end
|
||||
end
|
||||
return -1
|
||||
end
|
||||
|
||||
-- nal_unit_type 1..5: slices (decided by nal_ref_idc); 7, 8, 13, 15: parameter sets (never dropped)
|
||||
local function nalVerdict(hdr: number): boolean?
|
||||
local t = hdr % 32
|
||||
if t >= 1 and t <= 5 then
|
||||
return hdr // 32 % 4 == 0
|
||||
elseif t == 7 or t == 8 or t == 13 or t == 15 then
|
||||
return false
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
function Disposable.h264(b: buffer, lengthSize: number?): boolean
|
||||
local n = buffer.len(b)
|
||||
if lengthSize then
|
||||
local p = 0
|
||||
while p + lengthSize < n do
|
||||
local len = 0
|
||||
for k = 0, lengthSize - 1 do
|
||||
len = len * 256 + readu8(b, p + k)
|
||||
end
|
||||
p += lengthSize
|
||||
if len > n - p then
|
||||
return false
|
||||
end
|
||||
if len > 0 then
|
||||
local v = nalVerdict(readu8(b, p))
|
||||
if v ~= nil then
|
||||
return v
|
||||
end
|
||||
end
|
||||
p += len
|
||||
end
|
||||
return false
|
||||
end
|
||||
if n >= 3 and readu8(b, 0) == 0 and readu8(b, 1) == 0 then
|
||||
local p = nextStart(b, 0, n)
|
||||
while p >= 0 and p < n do
|
||||
local v = nalVerdict(readu8(b, p))
|
||||
if v ~= nil then
|
||||
return v
|
||||
end
|
||||
p = nextStart(b, p, n)
|
||||
end
|
||||
return false
|
||||
end
|
||||
return n > 0 and nalVerdict(readu8(b, 0)) == true
|
||||
end
|
||||
|
||||
-- the boolean decoder of RFC 6386 7.3 (a 2-byte window), enough for the frame header
|
||||
type Bool = { b: buffer, p: number, e: number, value: number, range: number, count: number }
|
||||
|
||||
local function byteAt(d: Bool): number
|
||||
local p = d.p
|
||||
d.p = p + 1
|
||||
return if p < d.e then readu8(d.b, p) else 0
|
||||
end
|
||||
|
||||
local function boolNew(b: buffer, p: number, e: number): Bool
|
||||
local d: Bool = { b = b, p = p, e = e, value = 0, range = 255, count = 0 }
|
||||
d.value = byteAt(d) * 256 + byteAt(d)
|
||||
return d
|
||||
end
|
||||
|
||||
local function boolRead(d: Bool, prob: number): number
|
||||
local split = 1 + (d.range - 1) * prob // 256
|
||||
local big = split * 256
|
||||
local bit = 0
|
||||
if d.value >= big then
|
||||
bit = 1
|
||||
d.range -= split
|
||||
d.value -= big
|
||||
else
|
||||
d.range = split
|
||||
end
|
||||
while d.range < 128 do
|
||||
d.value *= 2
|
||||
d.range *= 2
|
||||
d.count += 1
|
||||
if d.count == 8 then
|
||||
d.count = 0
|
||||
d.value += byteAt(d)
|
||||
end
|
||||
end
|
||||
return bit
|
||||
end
|
||||
|
||||
local function lit(d: Bool, n: number): number
|
||||
local v = 0
|
||||
for _ = 1, n do
|
||||
v = v * 2 + boolRead(d, 128)
|
||||
end
|
||||
return v
|
||||
end
|
||||
|
||||
-- skips flag ? (n bits + sign) : nothing
|
||||
local function optSigned(d: Bool, n: number)
|
||||
if lit(d, 1) == 1 then
|
||||
lit(d, n + 1)
|
||||
end
|
||||
end
|
||||
|
||||
-- disposable: no reference refresh or copy and no segment map update; droppable: also no state the decoder keeps
|
||||
-- (refresh_entropy_probs 0, no segment feature or loop filter delta update)
|
||||
function Disposable.vp8(b: buffer): (boolean, boolean)
|
||||
local n = buffer.len(b)
|
||||
if n < 4 then
|
||||
return false, false
|
||||
end
|
||||
local tag = readu8(b, 0) + readu8(b, 1) * 256 + readu8(b, 2) * 65536
|
||||
if tag % 2 == 0 then
|
||||
return false, false -- key frame
|
||||
end
|
||||
local first = tag // 32
|
||||
if first > n - 3 then
|
||||
return false, false
|
||||
end
|
||||
local d = boolNew(b, 3, 3 + first)
|
||||
local keep = true
|
||||
if lit(d, 1) == 1 then -- segmentation_enabled
|
||||
local updateMap, updateData = lit(d, 1), lit(d, 1)
|
||||
if updateMap == 1 then
|
||||
return false, false
|
||||
end
|
||||
if updateData == 1 then
|
||||
keep = false
|
||||
lit(d, 1) -- segment_feature_mode
|
||||
for _ = 1, 4 do
|
||||
optSigned(d, 7)
|
||||
end
|
||||
for _ = 1, 4 do
|
||||
optSigned(d, 6)
|
||||
end
|
||||
end
|
||||
end
|
||||
lit(d, 1 + 6 + 3) -- filter_type, loop_filter_level, sharpness_level
|
||||
if lit(d, 1) == 1 and lit(d, 1) == 1 then -- loop_filter_adj_enable, mode_ref_lf_delta_update
|
||||
keep = false
|
||||
for _ = 1, 8 do
|
||||
optSigned(d, 6)
|
||||
end
|
||||
end
|
||||
lit(d, 2 + 7) -- log2_nbr_of_dct_partitions, y_ac_qi
|
||||
for _ = 1, 5 do
|
||||
optSigned(d, 4)
|
||||
end
|
||||
local refreshGolden, refreshAlt = lit(d, 1), lit(d, 1)
|
||||
if refreshGolden == 1 or refreshAlt == 1 then
|
||||
return false, false
|
||||
end
|
||||
if lit(d, 2) ~= 0 or lit(d, 2) ~= 0 then -- copy_buffer_to_golden, copy_buffer_to_alternate
|
||||
return false, false
|
||||
end
|
||||
lit(d, 2) -- sign_bias_golden, sign_bias_alternate
|
||||
local refreshEntropy, refreshLast = lit(d, 1), lit(d, 1)
|
||||
if refreshLast == 1 or d.p > d.e + 2 then
|
||||
return false, false
|
||||
end
|
||||
return true, keep and refreshEntropy == 0
|
||||
end
|
||||
|
||||
-- the avcC NAL length size of a track (nil: Annex B or one bare NAL unit per packet)
|
||||
function Disposable.lengthSize(config: buffer?): number?
|
||||
if config and buffer.len(config) >= 7 and readu8(config, 0) == 1 then
|
||||
return readu8(config, 4) % 4 + 1
|
||||
end
|
||||
return nil
|
||||
end
|
||||
|
||||
-- disposable: no later frame predicts from it; droppable: it can also be left out without telling the decoder
|
||||
function Disposable.check(codec: string?, data: buffer, config: buffer?): (boolean, boolean)
|
||||
if codec == "h264" then
|
||||
local v = Disposable.h264(data, Disposable.lengthSize(config))
|
||||
return v, v
|
||||
elseif codec == "vp8" then
|
||||
return Disposable.vp8(data)
|
||||
end
|
||||
return false, false
|
||||
end
|
||||
|
||||
return Disposable
|
||||
@@ -4,6 +4,7 @@
|
||||
local Err = require("@rosetta/core/Err")
|
||||
local Types = require("@rosetta/Types")
|
||||
local Yuv = require("@rosetta/codecs/image/Yuv")
|
||||
local Disposable = require("@rosetta/codecs/video/Video/Disposable")
|
||||
|
||||
local Video = {}
|
||||
|
||||
@@ -16,8 +17,8 @@ export type Entry = {
|
||||
[string]: any,
|
||||
}
|
||||
|
||||
-- decodeOne -> nil, nil: a packet with no picture to show (a hidden VP8 altref frame)
|
||||
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image?, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
|
||||
-- decodeOne -> nil, nil: a packet with no picture to show (a hidden VP8 altref frame); false: a picture skipped
|
||||
function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) -> (Types.Image? | false, Err.Err?), resetFn: (() -> ())?): Types.VideoCodecDecoder
|
||||
local queue: { any } = {}
|
||||
local self = {}
|
||||
function self.decode(_: any, packet: Types.Packet): Err.Err?
|
||||
@@ -25,12 +26,12 @@ function Video.simpleDecoder(decodeOne: (data: buffer, packet: Types.Packet) ->
|
||||
if not ok then
|
||||
return Err.new(Err.CORRUPT, "decoder threw: " .. tostring(img))
|
||||
end
|
||||
if img then
|
||||
if img ~= nil then
|
||||
table.insert(queue, { img, packet.pts, packet.keyframe })
|
||||
end
|
||||
return err
|
||||
end
|
||||
function self.receive(_: any): (Types.Image?, number?, boolean?)
|
||||
function self.receive(_: any): (Types.Image? | false, number?, boolean?)
|
||||
local q = table.remove(queue, 1)
|
||||
if q then
|
||||
return q[1], q[2], q[3]
|
||||
@@ -176,11 +177,17 @@ end
|
||||
local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDecoder?, Err.Err?)
|
||||
local Vp8 = require("@rosetta/codecs/image/Vp8")
|
||||
local dec = Vp8.newDecoder()
|
||||
local o = { maxPixels = opts and opts.maxPixels }
|
||||
return Video.simpleDecoder(function(data: buffer): (Types.Image?, Err.Err?)
|
||||
local o = { maxPixels = opts and opts.maxPixels, yield = opts and opts.yield, skipDisposable = opts and opts.skipDisposable }
|
||||
local self: any
|
||||
self = Video.simpleDecoder(function(data: buffer): (Types.Image? | false, Err.Err?)
|
||||
local img, err = dec:decodeFrame(data, 0, buffer.len(data), o)
|
||||
if not img then
|
||||
return nil, err
|
||||
if err then
|
||||
return nil, err
|
||||
end
|
||||
self.skipped += 1
|
||||
-- show_frame (RFC 6386 9.1): a shown frame keeps its place
|
||||
return if buffer.readu8(data, 0) // 16 % 2 == 1 then false else nil, nil
|
||||
end
|
||||
local src = img.meta.source
|
||||
if type(src) == "table" and src.show == false then
|
||||
@@ -194,7 +201,9 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec
|
||||
else
|
||||
dec = Vp8.newDecoder()
|
||||
end
|
||||
end), nil
|
||||
end)
|
||||
self.skipped = 0
|
||||
return self, nil
|
||||
end
|
||||
|
||||
-- Motion JPEG: yuv420p straight from the planes (full range) when the layout allows, else rgba8
|
||||
@@ -321,6 +330,18 @@ function Video.entry(id: string): Entry?
|
||||
return byId[id]
|
||||
end
|
||||
|
||||
-- disposable: no later frame predicts from the packet's; droppable: it may also be left out unread (VP8 headers can
|
||||
-- carry probability and loop filter updates, so a disposable VP8 frame is droppable only without them)
|
||||
function Video.isDisposable(track: Types.Track | string, packet: Types.Packet | buffer): (boolean, boolean)
|
||||
local codec = if type(track) == "table" then track.codec else track
|
||||
local config = if type(track) == "table" then track.config else nil
|
||||
local data = if type(packet) == "table" then packet.data else packet
|
||||
if type(data) ~= "buffer" or type(codec) ~= "string" then
|
||||
return false, false
|
||||
end
|
||||
return Disposable.check(codec, data, config)
|
||||
end
|
||||
|
||||
function Video.canDecode(id: string): boolean
|
||||
local e = byId[id]
|
||||
return e ~= nil and e.new ~= nil
|
||||
@@ -424,7 +445,12 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
|
||||
local dec = codec :: Types.VideoCodecDecoder
|
||||
while true do
|
||||
local img, pts, key = dec:receive()
|
||||
if img then
|
||||
if img == false then
|
||||
-- a picture skipped (skipDisposable): it keeps its place in output order
|
||||
if index >= 0 then
|
||||
index += 1
|
||||
end
|
||||
elseif img then
|
||||
local t = (pts or 0) / scale - start
|
||||
if t + 1e-9 >= skipUntil then
|
||||
if index < 0 then
|
||||
@@ -439,15 +465,11 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
|
||||
lastPts = t
|
||||
local maxSide = o.maxSide
|
||||
if maxSide and maxSide >= 1 and img.format == "yuv420p" and math.max(img.width, img.height) > maxSide then
|
||||
local hook: any = o.yield
|
||||
if hook then
|
||||
pcall(hook)
|
||||
end
|
||||
local s = maxSide / math.max(img.width, img.height)
|
||||
img = Yuv.imageScale(img, math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5)))
|
||||
img = Yuv.imageScale(img, math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5)), nil, o.yield)
|
||||
end
|
||||
if o.rgba then
|
||||
img = Yuv.imageToRgba(img) or img
|
||||
img = Yuv.imageToRgba(img, nil, o.yield) or img
|
||||
end
|
||||
return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil
|
||||
end
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
-- containers/Demux: the indexed Types.Demuxer every video container builds (Matroska, AVI, MPEG-TS / PS, Y4M, MP4).
|
||||
-- New in rosetta. Packets are offset + length into the source buffer (or own bytes); per-track cursors are independent.
|
||||
local Types = require("@rosetta/Types")
|
||||
local Disposable = require("@rosetta/codecs/video/Video/Disposable")
|
||||
|
||||
local Demux = {}
|
||||
local D = {}
|
||||
@@ -171,6 +172,16 @@ function D._packet(self: Demux, i: number): Types.Packet
|
||||
p[k] = v
|
||||
end
|
||||
end
|
||||
local tid = p.track
|
||||
for _, t in self.tracks do
|
||||
if t.id == tid then
|
||||
local c = t.codec
|
||||
if (c == "h264" or c == "vp8") and Disposable.check(c, data :: buffer, t.config) then
|
||||
p.disposable = true
|
||||
end
|
||||
break
|
||||
end
|
||||
end
|
||||
return p
|
||||
end
|
||||
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
# Decoder control fixtures (tools/fixtures.py, for tests/video/control.luau): VP8 with two temporal layers (ffmpeg's
|
||||
# libvpx, ts_layering_mode 2: every other inter frame refreshes no reference), as IVF and WebM, with and without error
|
||||
# resilience; ffmpeg's vp8 decode gives the CRC-32 of every shown yuv420p frame.
|
||||
# tests/gen/videoctl_vp8.luau { { name, ivf, webm, width, height, crcs } }
|
||||
import importlib.util, os, tempfile
|
||||
|
||||
_spec = importlib.util.spec_from_file_location("_video_helpers", os.path.join(os.path.dirname(os.path.abspath(__file__)), "_video.py"))
|
||||
V = importlib.util.module_from_spec(_spec)
|
||||
_spec.loader.exec_module(V)
|
||||
|
||||
INPUTS = ["tools/fixtures/_video.py"]
|
||||
|
||||
LAYERS = ["-ts-parameters", "ts_number_layers=2:ts_target_bitrate=150,300:ts_rate_decimator=2,1:ts_periodicity=2:"
|
||||
"ts_layer_id=0,1:ts_layering_mode=2"]
|
||||
|
||||
|
||||
def crcs(path):
|
||||
out = V.ffmpeg(["-c:v", "vp8", "-i", path, "-fps_mode", "passthrough", "-f", "framehash", "-hash", "crc32", "-"])
|
||||
res = []
|
||||
for line in out.decode().splitlines():
|
||||
if line and not line.startswith("#"):
|
||||
res.append(int(line.split(",")[5].strip(), 16))
|
||||
return res
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
tmp = tempfile.mkdtemp(prefix="videoctl_")
|
||||
out = []
|
||||
for name, extra in (("layers", []), ("layers_er", ["-error-resilient", "1"])):
|
||||
ivf = os.path.join(tmp, name + ".ivf")
|
||||
webm = os.path.join(tmp, name + ".webm")
|
||||
V.ffmpeg(["-f", "lavfi", "-i", "testsrc2=size=176x144:rate=25", "-frames:v", "20", "-pix_fmt", "yuv420p",
|
||||
"-c:v", "libvpx", "-b:v", "300k"] + extra + LAYERS + ["-f", "ivf", ivf])
|
||||
V.ffmpeg(["-i", ivf, "-c", "copy", webm])
|
||||
out.append({"name": name, "ivf": open(ivf, "rb").read(), "webm": open(webm, "rb").read(), "width": 176,
|
||||
"height": 144, "crcs": crcs(ivf)})
|
||||
ctx.emit("videoctl_vp8", out)
|
||||
Reference in new issue
Block a user