video: frame reuse (opts.reuse, v:release, decoder:release) and the control tests

- codecs/video/Video/Pool: Images a decoder made, handed back and reused (only its own; fresh meta)
- H264 / Vp8 / Mpeg2 output Images come from a Pool; H264 / Vp8 decoder:release, VideoCodecDecoder.release
- Video.open: opts.reuse recycles the previous frame's Image at the next nextFrame; v:release(frame); the yuv Image
  under an rgba / scaled frame (never seen by the caller) goes back to the codec at once
- tests/video/control.luau: yield hook (identical frames, H.264 / VP8 / MPEG-1, conversions), disposable packets in
  every container, skipDisposable bit-exact at the right index, reuse identical and recycled, fuzz
- docs/guide/video.md: Skipping and reusing frames; docs/API.md
This commit is contained in:
4DBug committed 2026-11-02 21:46:59 -06:00
1 parent 15e0dfcc86
commit 0b2d8774b9
10 files changed
+463 -27

No files matched your search

+3 -1
View File
@@ -45,7 +45,9 @@ VideoDecoder saved to an image format (`gif`, `apng`, `webp`) becomes an animate
one category. Extras:
- `F.video.open(src, opts?)`: `opts.maxSide` shrinks the frames (longer side at most n pixels), `opts.yield` is a
cooperative yield point for slow codecs (H.264; see the video guide), `opts.audio = false` skips the audio track, `opts.sbr = false` decodes only the AAC-LC core of an HE-AAC track.
cooperative yield point for slow codecs (H.264, VP8, MPEG-1 / MPEG-2 and the conversions; see the video guide), `opts.audio = false` skips the audio track, `opts.sbr = false` decodes only the AAC-LC core of an HE-AAC track,
`opts.skipDisposable` skips the frames nothing depends on (`packet.disposable`), `opts.reuse` decodes each frame
into the previous frame's Image (`v:release(frame)` hands one back).
It also opens animated images (GIF / APNG / WebP) as videos; `F.video.fromImage(img)`,
`F.video.fromFrames(images, delays?)` (an image sequence: `F.save(F.video.fromFrames(list, 1 / 25), "out.avi")`),
`F.video.codecs` (the codec registry `codecs/video/Video`).
+47 -7
View File
@@ -42,6 +42,7 @@ Times: `VideoFrame.pts` / `duration`, `seek` and every `duration` field are **se
| `v:toRGBA(frameOrImage)` | an rgba8 Image (the frame's own image when it already is rgba8) |
| `v:seek(seconds)` | the next frame is the first at or after that time (decoded from the keyframe before it) |
| `v:reset()` | back to the start |
| `v:release(frame)` | hands a frame's Image back: a later frame may be decoded into it (see [Skipping and reusing frames](#skipping-and-reusing-frames)) |
### VideoFrame
@@ -98,7 +99,8 @@ assert(r and g and b)
| `codecDelay`, `playDuration` | audio: seconds of encoder priming to drop, and seconds to play after it (an MP4 edit list; Matroska `CodecDelay`) |
| `duration`, `language`, `name`, `default` | when the container has them |
A Packet is `{ track, pts, dts?, duration?, keyframe, data }`: `data` is a buffer of the compressed bytes.
A Packet is `{ track, pts, dts?, duration?, keyframe, data, disposable? }`: `data` is a buffer of the compressed
bytes; `disposable = true` marks an H.264 or VP8 frame that no later frame predicts from.
```luau
local v = assert(F.video.open(mp4Bytes))
@@ -247,7 +249,9 @@ assert(C.entry("h264").name == "H.264 / AVC")
```
`C.register(entry)` adds or replaces a codec at run time. `new(track, opts)` returns a decoder instance with
`decode(self, packet) -> err?`, `receive(self) -> image?, pts?, keyframe?`, `flush(self)` and `reset(self)`.
`decode(self, packet) -> err?`, `receive(self) -> image?, pts?, keyframe?`, `flush(self)` and `reset(self)`, and
optionally `release(self, image) -> boolean` (an Image from `receive` to reuse). With `opts.skipDisposable`, `receive`
returns `false` (and the pts) for a picture it skipped.
`C.simpleDecoder(decodeOne)` builds one for codecs with one picture per packet and no reordering:
```luau
@@ -386,11 +390,14 @@ editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels)
### Slow codecs: a yield hook and smaller frames
One H.264 picture can take longer than a game frame. `F.video.open(src, { yield = fn })` hands the codec a cooperative
yield point: H.264 calls `fn` (through `pcall`) every 16 macroblocks and every macroblock row of the loop filter, so
decoding inside a coroutine whose `fn` calls `coroutine.yield()` once a time budget is spent spreads a picture over
several frames (a game's worker Actor, or the main thread). While a decode is suspended, run no other H.264 decode in
the same Luau VM. `maxSide = n` shrinks the yuv420p frames (bilinear, aspect kept) so the longer side is at most `n`
pixels, before any rgba conversion; `v.width` / `v.height` stay the source size.
yield point, called through `pcall`: H.264 every 16 macroblocks, every macroblock row of the loop filter and between
the allocations of a new picture; VP8 three times per macroblock row and once per loop filter row; MPEG-1 / MPEG-2
per slice; the `maxSide` scaling and the `rgba` conversion every 16 rows. Decoding inside a coroutine whose `fn`
calls `coroutine.yield()` once a time budget is spent spreads a picture over several frames (a game's worker Actor,
or the main thread); at 1080p no stretch between calls is longer than about 3 ms (`luau -O2`). While a decode is
suspended, run no other H.264 decode in the same Luau VM (VP8 decodes may interleave). `maxSide = n` shrinks the
yuv420p frames (bilinear, aspect kept) so the longer side is at most `n` pixels, before any rgba conversion;
`v.width` / `v.height` stay the source size.
```luau
local deadline = 0
@@ -412,6 +419,39 @@ end
assert(frames > 0)
```
### Skipping and reusing frames
A player that falls behind can skip the frames nothing else depends on: H.264 pictures with `nal_ref_idc` 0 (most B
pictures) and VP8 frames that refresh no reference (temporal layers). `skipDisposable = true` decodes only their
headers; the skipped frames keep their place, so the next frame's `pts` and `index` are what a full decode gives, and
every frame that comes out is bit-exact. `packet.disposable` (set by the MP4, Matroska / WebM, MPEG-TS, AVI, FLV and
H.264 demuxers) and `F.video.codecs.isDisposable(track, packet)` tell them apart without decoding; prefer
`skipDisposable` to leaving the packets out, as a VP8 frame header can still carry probability updates.
Every frame is a new Image, and a 720p decode makes megabytes of garbage per frame. `reuse = true` lets `nextFrame`
write into the Image of the frame it returned before (be done with the previous frame by then: draw it, or copy it);
`v:release(frame)` hands one back explicitly. Reference pictures are never handed out: Images are copies of them.
```luau
local v = assert(F.video.open(mp4Bytes, { audio = false, rgba = true, reuse = true, skipDisposable = true }))
local d = v.demuxer
local disposable = 0
for p in d:packets(v.track.id) do
if p.disposable then disposable += 1 end
assert(F.video.codecs.isDisposable(v.track, p) == (p.disposable == true))
end
v:reset() -- back to the first packet
local frames, last = 0, nil
while true do
local f = v:nextFrame() -- reuses the previous frame's rgba8 Image
if not f then break end
frames += 1
assert(f.image.format == "rgba8" and (last == nil or f.index > last))
last = f.index
end
assert(frames + disposable == v.frames)
```
## Formats
| Format | Read | Write | Video codecs (decode) |
+2
View File
@@ -232,6 +232,8 @@ export type VideoCodecDecoder = {
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
-- an Image from receive() handed back for reuse (the caller is done with it); false if it was not this decoder's
release: ((self: any, image: Image) -> boolean)?,
}
-- Indices are 1-based everywhere (node, mesh, material, texture, ...). Accessor data is tightly packed (no stride, no
+9 -3
View File
@@ -7,6 +7,7 @@ local Err = require("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Decode = require("@rosetta/codecs/image/Vp8/Decode")
local Yuv = require("@rosetta/codecs/image/Vp8/Yuv")
local Pool = require("@rosetta/codecs/video/Video/Pool")
local Vp8 = {}
@@ -52,10 +53,10 @@ end
local DecoderMeta = {}
DecoderMeta.__index = DecoderMeta
export type Decoder = typeof(setmetatable({} :: { state: Decode.State }, DecoderMeta))
export type Decoder = typeof(setmetatable({} :: { state: Decode.State, images: Pool.Pool }, DecoderMeta))
function Vp8.newDecoder(): Decoder
return setmetatable({ state = Decode.new() }, DecoderMeta)
return setmetatable({ state = Decode.new(), images = Pool.new() }, DecoderMeta)
end
function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len: number?, opts: Options?): (Types.Image?, Err.Err?)
@@ -69,7 +70,7 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
elseif f.skipped then
return nil, nil
end
local img = Types.Image.new(f.width, f.height, "yuv420p")
local img = self.images:take(f.width, f.height, "yuv420p")
local ny = f.width * f.height
local nc = ((f.width + 1) // 2) * ((f.height + 1) // 2)
Decode.cropTo(f, img.pixels, 0, img.pixels, ny, img.pixels, ny + nc)
@@ -78,6 +79,11 @@ function DecoderMeta.decodeFrame(self: Decoder, buf: buffer, off: number?, len:
return img, nil
end
-- hands a decoded Image back for reuse by a later frame (the caller is done with it); false if it was not this decoder's
function DecoderMeta.release(self: Decoder, image: Types.Image): boolean
return self.images:give(image)
end
function DecoderMeta.reset(self: Decoder)
Decode.reset(self.state)
end
+15 -8
View File
@@ -12,6 +12,7 @@ local Cavlc = require("@rosetta/codecs/video/H264/Cavlc")
local Cabac = require("@rosetta/codecs/video/H264/Cabac")
local Deblock = require("@rosetta/codecs/video/H264/Deblock")
local Inter = require("@rosetta/codecs/video/H264/Inter")
local Pool = require("@rosetta/codecs/video/Video/Pool")
local Types = require("@rosetta/Types")
local PAD, PADC = Inter.PAD, Inter.PADC
@@ -54,6 +55,7 @@ function Decoder.new(opts: Options?): any
prevFrameNum = 0,
maxLongTermIdx = -1,
pool = {},
images = Pool.new(), -- output Images given back (H264 decoder:release)
gray = nil,
frames = 0,
errors = 0,
@@ -153,15 +155,11 @@ local function grayPicture(self: any, sps: any): any
return g
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
-- the cropped output copy of a decoded picture
local function toImage(self: any, p: any): Types.Image
local sps = p.sps
local W, H = sps.width, sps.height
local img = Types.Image.new(W, H, "yuv420p")
local img = self.images:take(W, H, "yuv420p")
local px = img.pixels
local cx, cy = sps.cropX, sps.cropY
for y = 0, H - 1 do
@@ -178,7 +176,16 @@ local function emit(self: any, p: any)
img.meta.sar = { sps.sarW, sps.sarH }
end
img.meta.yuv = { range = if sps.fullRange then "full" else "limited", matrix = if sps.matrix == 1 then "bt709" else "bt601" }
table.insert(self.out, { image = img, pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr })
return img
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
table.insert(self.out, { image = toImage(self, p), pts = p.pts, duration = 0, poc = p.poc, keyframe = p.idr })
release(self, p)
end
+8
View File
@@ -140,6 +140,11 @@ function DecoderMeta.decode(self: H264Decoder, data: any, pts: number?, off: num
return frames, nil
end
-- hands a frame's Image back for reuse by a later frame (the caller is done with it); false if it was not this decoder's
function DecoderMeta.release(self: H264Decoder, image: Types.Image): boolean
return self.state.images:give(image)
end
function DecoderMeta.flush(self: H264Decoder): { Frame }
Decoder.flush(self.state)
status(self)
@@ -245,6 +250,9 @@ function H264.newVideoDecoder(track: Types.Track, opts: any?): (Types.VideoCodec
push((dec :: H264Decoder):flush())
end
end
function self.release(_: any, image: Types.Image): boolean
return dec ~= nil and (dec :: H264Decoder):release(image)
end
function self.reset(_: any)
dec = make()
table.clear(queue)
+10 -4
View File
@@ -7,6 +7,7 @@
local Types = require("@rosetta/Types")
local Err = require("@rosetta/core/Err")
local D = require("@rosetta/codecs/video/Mpeg2/Decoder")
local Pool = require("@rosetta/codecs/video/Video/Pool")
local Mpeg2 = {}
@@ -248,7 +249,8 @@ function Mpeg2.toRgba(y: buffer, cb: buffer, cr: buffer, codedWidth: number, wid
return true
end
function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
-- pool: where the Image comes from (a recycled one when the caller released one of the right size)
function Mpeg2.frameImage(frame: Frame, rgba: boolean?, pool: Pool.Pool?): 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
@@ -264,14 +266,14 @@ function Mpeg2.frameImage(frame: Frame, rgba: boolean?): Types.Image?
end
local img
if rgba then
img = Types.Image.new(w, h)
img = if pool then pool:take(w, h, "rgba8") else 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")
img = if pool then pool:take(w, h, "yuv420p") else 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)
@@ -319,8 +321,9 @@ 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, yield = opts and opts.yield })
local queue: { any } = {}
local images = Pool.new()
local function push(f: Frame)
local img = Mpeg2.frameImage(f)
local img = Mpeg2.frameImage(f, false, images)
if img then
img.meta.yuv = { range = "limited", matrix = "bt601" }
local tag = f.tag
@@ -360,6 +363,9 @@ function Mpeg2.newVideoDecoder(_track: any, opts: any?): (Types.VideoCodecDecode
dec:reset()
table.clear(queue)
end
function self.release(_: any, image: Types.Image): boolean
return images:give(image)
end
return self :: any, nil
end
+50
View File
@@ -0,0 +1,50 @@
--!strict
--!optimize 2
-- codecs/video/Video/Pool: output Images handed back by the caller (decoder:release), reused for later frames. Only
-- Images this pool made are taken back; a reused Image gets a fresh meta table.
local Types = require("@rosetta/Types")
local Pool = {}
Pool.__index = Pool
export type Pool = typeof(setmetatable({} :: { free: { Types.Image }, made: { [Types.Image]: boolean }, max: number }, Pool))
function Pool.new(max: number?): Pool
return setmetatable({ free = {}, made = setmetatable({}, { __mode = "k" }) :: any, max = max or 3 }, Pool)
end
function Pool.take(self: Pool, w: number, h: number, format: Types.PixelFormat): Types.Image
local free = self.free
for i = #free, 1, -1 do
local img = free[i]
if img.width == w and img.height == h and img.format == format then
table.remove(free, i)
img.meta = {}
return img
end
end
local img = Types.Image.new(w, h, format)
self.made[img] = true
return img
end
-- true when the Image was this pool's (it is kept for reuse, or dropped when the pool is full)
function Pool.give(self: Pool, img: any): boolean
if type(img) ~= "table" or not self.made[img] then
return false
end
local free = self.free
for _, q in free do
if q == img then
return true
end
end
if #free < self.max then
table.insert(free, img)
else
self.made[img] = nil
end
return true
end
return Pool
+35 -4
View File
@@ -5,6 +5,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 Pool = require("@rosetta/codecs/video/Video/Pool")
local Video = {}
@@ -203,6 +204,9 @@ local function vp8Decoder(_track: Types.Track, opts: any?): (Types.VideoCodecDec
end
end)
self.skipped = 0
function self.release(_: any, image: Types.Image): boolean
return dec:release(image)
end
return self, nil
end
@@ -373,6 +377,8 @@ export type OpenOptions = {
audio: boolean?,
maxSide: number?,
yield: (() -> ())?,
skipDisposable: boolean?,
reuse: boolean?, -- nextFrame may overwrite the Image of the frame it returned before
[string]: any,
}
@@ -438,10 +444,25 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
v.startTime = start
local defaultDur = if v.frameRate > 0 then 1 / v.frameRate else 0
local lastPts = nil :: number?
-- rgba8 / scaled Images made here; the codec's own go back through codec:release
local own = Pool.new(2)
local function recycle(img: any)
if img and not own:give(img) and codec and codec.release then
codec:release(img)
end
end
local lastFrame: any = nil
function v.release(self: any, frame: any)
recycle(if type(frame) == "table" and frame.kind == "image" then frame else type(frame) == "table" and frame.image)
end
function v.nextFrame(self: any): (Types.VideoFrame?, Err.Err?)
if not codec then
return nil, codecErr
end
if lastFrame then
recycle(lastFrame.image)
lastFrame = nil
end
local dec = codec :: Types.VideoCodecDecoder
while true do
local img, pts, key = dec:receive()
@@ -466,12 +487,21 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
local maxSide = o.maxSide
if maxSide and maxSide >= 1 and img.format == "yuv420p" and math.max(img.width, img.height) > maxSide then
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)), nil, o.yield)
local dw, dh = math.max(1, math.floor(img.width * s + 0.5)), math.max(1, math.floor(img.height * s + 0.5))
local src = img
img = Yuv.imageScale(src, dw, dh, own:take(dw, dh, "yuv420p"), o.yield)
recycle(src) -- (never seen by the caller)
end
if o.rgba then
img = Yuv.imageToRgba(img, nil, o.yield) or img
if o.rgba and img.format == "yuv420p" then
local src = img
img = Yuv.imageToRgba(src, own:take(src.width, src.height, "rgba8"), o.yield) or src
recycle(src)
end
return { image = img, pts = t, duration = d, keyframe = key, index = index }, nil
local frame = { image = img, pts = t, duration = d, keyframe = key, index = index }
if o.reuse then
lastFrame = frame
end
return frame, nil
end
else
local p = demuxer:read(tid)
@@ -491,6 +521,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
end
end
function v.seek(self: any, seconds: number)
lastFrame = nil
demuxer:seek(seconds + start)
if codec then
codec:reset()
+284
View File
@@ -0,0 +1,284 @@
-- video decoder control tests: the cooperative yield hook (H.264, VP8, MPEG-1, rgba / scale conversions), disposable
-- packets and skipDisposable, frame reuse (opts.reuse, v:release, decoder:release); outputs against ffmpeg's CRCs.
-- Fixtures: tools/fixtures/h264.py (h264_containers), tools/fixtures/videoctl.py, tools/fixtures/videobench.py.
local T = require("@tests/T")
local F = require("@rosetta")
local Crc32 = require("@rosetta/core/Crc32")
local Video = require("@rosetta/codecs/video/Video")
local Disposable = require("@rosetta/codecs/video/Video/Disposable")
local H264 = require("@rosetta/codecs/video/H264")
local Vp8 = require("@rosetta/codecs/image/Vp8")
local Yuv = require("@rosetta/codecs/image/Yuv")
local H264Cases = require("@tests/gen/h264_containers")
local Vp8Cases = require("@tests/gen/videoctl_vp8")
local Bench = require("@tests/gen/videobench")
local t = T.suite("video/control")
local function crcs(v: any, rgba: boolean?): ({ number }, { number }, any)
local out, idx = {}, {}
while true do
local f, err = v:nextFrame()
if not f then
return out, idx, err
end
table.insert(out, Crc32.of(f.image.pixels))
table.insert(idx, f.index)
end
end
local function same(a: { number }, b: { number }): boolean
if #a ~= #b then
return false
end
for i = 1, #a do
if a[i] ~= b[i] then
return false
end
end
return true
end
local function ivfFrames(b: buffer): { buffer }
local out = {}
local p = buffer.readu16(b, 6)
while p + 12 <= buffer.len(b) do
local n = buffer.readu32(b, p)
if p + 12 + n > buffer.len(b) then
break
end
local f = buffer.create(n)
buffer.copy(f, 0, b, p + 12, n)
table.insert(out, f)
p += 12 + n
end
return out
end
-- yield: the hook suspends a coroutine at every call; frames stay identical
local function stepped(data: any, opts: { [string]: any }): ({ number }, number, number)
local calls = 0
local o = table.clone(opts)
o.audio = false
o.yield = function()
calls += 1
coroutine.yield()
end
local v = assert(F.video.open(data, o))
local got: { number } = {}
local co = coroutine.create(function()
got = crcs(v)
end)
local steps = 0
while coroutine.status(co) ~= "dead" do
local ok, err = coroutine.resume(co)
assert(ok, err)
steps += 1
end
return got, calls, steps
end
local yieldInputs = {
{ "h264 mp4", H264Cases[2].data },
{ "vp8 webm", Vp8Cases[1].webm },
}
for _, c in Bench do
if c.size == "320x240" and (c.name == "mpeg1.ts" or c.name == "vp8.webm") then
table.insert(yieldInputs, { c.name, c.data })
end
end
for _, c in yieldInputs do
for _, opts in { {}, { rgba = true }, { maxSide = 64 }, { maxSide = 64, rgba = true } } do
local tag = string.format("%s rgba=%s maxSide=%s", c[1], tostring(opts.rgba), tostring(opts.maxSide))
local o = table.clone(opts)
o.audio = false
local want = crcs(assert(F.video.open(c[2], o)))
local got, calls, steps = stepped(c[2], opts)
t:check(#want > 0 and same(got, want), tag .. ": frames identical under the yield hook")
t:check(calls > #want and steps == calls + 1, string.format("%s: hook called %d times for %d frames, %d steps", tag, calls, #want, steps))
end
end
do -- Yuv.toRgba: the hook every 16 rows, same pixels
local img = F.Types.Image.new(40, 70, "yuv420p")
for i = 0, buffer.len(img.pixels) - 1 do
buffer.writeu8(img.pixels, i, (i * 7) % 256)
end
local calls = 0
local a = assert(Yuv.imageToRgba(img))
local out = F.Types.Image.new(40, 70, "rgba8")
local b = assert(Yuv.imageToRgba(img, out, function()
calls += 1
end))
t:check(b == out and buffer.tostring(a.pixels) == buffer.tostring(b.pixels), "imageToRgba into an out Image, with a hook")
t:eq(calls, 4, "toRgba hook calls (rows 16, 32, 48, 64)")
local s1 = Yuv.imageScale(img, 20, 30)
calls = 0
local s2 = Yuv.imageScale(img, 20, 30, F.Types.Image.new(20, 30, "yuv420p"), function()
calls += 1
end)
t:check(buffer.tostring(s1.pixels) == buffer.tostring(s2.pixels) and calls > 0, "imageScale into an out Image, with a hook")
end
-- disposable packets: H.264 (nal_ref_idc 0) in every container, and skipDisposable keeps the rest bit-exact
for _, c in H264Cases do
local v = assert(F.video.open(c.data, { audio = false }))
local d = v.demuxer
local n, nd, agree = 0, 0, true
for p in d:packets(v.track.id) do
n += 1
if p.disposable then
nd += 1
end
if (p.disposable == true) ~= (Video.isDisposable(v.track, p)) then
agree = false
end
end
local want = if string.sub(c.name, 1, 7) == "cabac_b" then 9 else 0
t:eq(nd, want, c.name .. ": disposable packets")
t:check(agree, c.name .. ": packet.disposable == Video.isDisposable")
local v2 = assert(F.video.open(c.data, { audio = false, skipDisposable = true }))
local got, idx, err = crcs(v2)
local good = 0
for i, crc in got do
if c.frames[idx[i]] == crc then
good += 1
end
end
t:check(err == nil and #got == #c.frames - nd and good == #got, string.format("%s: skipDisposable %d frames shown of %d, %d bit-exact at their index", c.name, #got, #c.frames, good))
end
do -- H.264 decoder API: skipped frames keep their place
local c = H264Cases[1]
assert(c.name == "cabac_b.h264")
local all = assert(H264.decodeAll(c.data))
local some = assert(H264.decodeAll(c.data, { skipDisposable = true }))
local skipped, good = 0, 0
for i, f in some do
if f.skipped then
skipped += 1
t:check(f.image == nil and f.pts == all[i].pts, "skipped frame " .. i .. ": no image, its pts")
elseif Crc32.of(f.image.pixels) == c.frames[i] then
good += 1
end
end
t:check(#some == #all and skipped == 9 and good == #all - 9, string.format("decodeAll skipDisposable: %d skipped, %d / %d bit-exact", skipped, good, #all - 9))
local au = H264.accessUnits(c.data)
local hits = 0
for i = 1, #au, 3 do
local b = buffer.create(au[i + 1])
buffer.copy(b, 0, buffer.fromstring(c.data), au[i], au[i + 1])
if Video.isDisposable("h264", b) then
hits += 1
end
end
t:eq(hits, 9, "Annex B access units: disposable")
end
-- VP8: frames refreshing no reference (two temporal layers)
for _, c in Vp8Cases do
local frames = ivfFrames(buffer.fromstring(c.ivf))
local nd, ndrop = 0, 0
local dec, skipDec = Vp8.newDecoder(), Vp8.newDecoder()
local exact, skipped, wrong = 0, 0, 0
for i, f in frames do
local disp, drop = Disposable.vp8(f)
nd += if disp then 1 else 0
ndrop += if drop then 1 else 0
local full = assert(dec:decodeFrame(f))
local img, err = skipDec:decodeFrame(f, nil, nil, { skipDisposable = true })
if img then
exact += if Crc32.of(img.pixels) == Crc32.of(full.pixels) and Crc32.of(full.pixels) == c.crcs[i] then 1 else 0
elseif err == nil then
skipped += 1
wrong += if disp then 0 else 1
end
end
t:check(nd >= 8 and ndrop == 0, string.format("%s: %d of %d frames disposable, %d droppable", c.name, nd, #frames, ndrop))
t:check(skipped == nd and wrong == 0 and exact == #frames - nd, string.format("%s: decodeFrame skipDisposable skipped %d, %d others bit-exact", c.name, skipped, exact))
local v = assert(F.video.open(c.webm, { audio = false }))
local pd = 0
for p in v.demuxer:packets(v.track.id) do
pd += if p.disposable then 1 else 0
end
t:eq(pd, nd, c.name .. ": webm packet.disposable")
local got, idx = crcs(assert(F.video.open(c.webm, { audio = false, skipDisposable = true })))
local good = 0
for i, crc in got do
good += if c.crcs[idx[i]] == crc then 1 else 0
end
t:check(#got == #frames - nd and good == #got, string.format("%s: webm skipDisposable %d shown, %d bit-exact at their index", c.name, #got, good))
end
-- reuse: frames identical, Images recycled
local reuseInputs = {
{ "h264 mp4", H264Cases[2].data },
{ "h264 ts", H264Cases[4].data },
{ "vp8 webm", Vp8Cases[1].webm },
}
for _, c in Bench do
if c.size == "320x240" and c.name ~= "raw.y4m" then
table.insert(reuseInputs, { c.name, c.data })
end
end
for _, c in reuseInputs do
for _, opts in { {}, { rgba = true }, { maxSide = 64 } } do
local tag = string.format("%s rgba=%s maxSide=%s", c[1], tostring(opts.rgba), tostring(opts.maxSide))
local o = table.clone(opts)
o.audio = false
local want = crcs(assert(F.video.open(c[2], o)))
o.reuse = true
local v = assert(F.video.open(c[2], o))
local got, seen, again = {}, {}, 0
while true do
local f = v:nextFrame()
if not f then
break
end
table.insert(got, Crc32.of(f.image.pixels))
if seen[f.image.pixels] then
again += 1
end
seen[f.image.pixels] = true
end
t:check(same(got, want), tag .. ": reuse frames identical")
local recycles = c[1] ~= "mjpeg.avi" or opts.rgba or opts.maxSide
t:check(not recycles or again > 0, string.format("%s: %d of %d frames in a recycled buffer", tag, again, #got))
end
end
do -- v:release and decoder:release
local c = H264Cases[2]
local v = assert(F.video.open(c.data, { audio = false }))
local a = assert(v:nextFrame())
local ca = Crc32.of(a.image.pixels)
v:release(a)
local b = assert(v:nextFrame())
t:check(b.image == a.image and Crc32.of(b.image.pixels) == c.frames[2] and ca == c.frames[1], "v:release: the next frame reuses the Image")
local dec = assert(H264.newDecoder())
t:check(not dec:release(F.Types.Image.new(176, 144, "yuv420p")), "H264 decoder:release refuses a foreign Image")
local vd = Vp8.newDecoder()
local f1 = ivfFrames(buffer.fromstring(Vp8Cases[1].ivf))
local i1 = assert(vd:decodeFrame(f1[1]))
local k1 = Crc32.of(i1.pixels)
t:check(vd:release(i1), "Vp8 decoder:release")
local i2 = assert(vd:decodeFrame(f1[2]))
t:check(i2 == i1 and k1 == Vp8Cases[1].crcs[1] and Crc32.of(i2.pixels) == Vp8Cases[1].crcs[2], "Vp8: the released Image holds the next frame")
end
local samples = {}
for _, c in H264Cases do
table.insert(samples, buffer.fromstring(string.sub(c.data, 1, 4000)))
end
for _, f in ivfFrames(buffer.fromstring(Vp8Cases[1].ivf)) do
if #samples < 12 then
table.insert(samples, f)
end
end
t:fuzz("Disposable.check", function(b: buffer)
Disposable.check("h264", b, nil)
Disposable.check("h264", b, buffer.fromstring("\1\100\0\31\255\225\0"))
return Disposable.check("vp8", b)
end, samples)
t:done()