diff --git a/docs/API.md b/docs/API.md index 22b51c0..15bccbb 100644 --- a/docs/API.md +++ b/docs/API.md @@ -44,7 +44,9 @@ VideoDecoder saved to an image format (`gif`, `apng`, `webp`) becomes an animate `F.subtitle`, `F.music`, `F.playlist` each have `load`, `open`, `save` and `formats`: the calls above restricted to one category. Extras: -- `F.video.open(src)` also opens animated images (GIF / APNG / WebP) as videos; `F.video.fromImage(img)`, +- `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. + 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`). - `F.model.loadTextures(scene, opts?)`: decodes embedded / referenced textures into `texture.image`. diff --git a/docs/guide/video.md b/docs/guide/video.md index 50a4fd6..01e6f69 100644 --- a/docs/guide/video.md +++ b/docs/guide/video.md @@ -383,6 +383,35 @@ local editable = assert(F.host.toEditableImage(v:toRGBA(first))) 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. + +```luau +local deadline = 0 +local v = assert(F.video.open(mp4Bytes, { audio = false, maxSide = 32, yield = function() + if os.clock() >= deadline then + coroutine.yield() + end +end })) +local frames = 0 +local job = coroutine.create(function() + while v:nextFrame() do + frames += 1 + end +end) +while coroutine.status(job) ~= "dead" do -- one step per game frame + deadline = os.clock() + 0.002 + assert(coroutine.resume(job)) +end +assert(frames > 0) +``` + ## Formats | Format | Read | Write | Video codecs (decode) | diff --git a/src/Formats/codecs/image/Yuv.luau b/src/Formats/codecs/image/Yuv.luau index fe331ee..f518ae3 100644 --- a/src/Formats/codecs/image/Yuv.luau +++ b/src/Formats/codecs/image/Yuv.luau @@ -10,6 +10,8 @@ -- Yuv.toRgba(planes, w, h, uo, vo, cw, range?, matrix?, out?) -> rgba8 buffer (alpha 255) -- Yuv.fromRgba(rgba, w, h, range?, matrix?, out?) -> yuv420p buffer (Y, then U, then V; ceil(w/2) x ceil(h/2)) -- Yuv.imageToRgba(img) / Yuv.imageFromRgba(img, range?, matrix?) -> Types.Image +-- Yuv.scale(src, w, h, dw, dh, out?) -> yuv420p buffer of dw x dh (each plane bilinear; for shrinking by up to 2x per +-- axis, larger factors skip source samples); Yuv.imageScale(img, dw, dh) -> Types.Image (yuv420p in and out) local Types = require("@formats/Types") local readu8, writeu8, writeu32 = buffer.readu8, buffer.writeu8, buffer.writeu32 @@ -222,4 +224,65 @@ function Yuv.imageFromRgba(img: Types.Image, range: string?, matrix: string?): T return out end +-- one plane (sw x sh bytes at so) -> (dw x dh at do), bilinear in 8-bit fixed point (source sample centres) +local function scalePlane(src: buffer, so: number, sw: number, sh: number, dst: buffer, d0: number, dw: number, dh: number) + local fx, fy = sw / dw, sh / dh + for y = 0, dh - 1 do + local sy = (y + 0.5) * fy - 0.5 + if sy < 0 then + sy = 0 + end + local y0 = floor(sy) + if y0 > sh - 1 then + y0 = sh - 1 + end + local y1 = if y0 < sh - 1 then y0 + 1 else y0 + local wy = floor((sy - y0) * 256) + local r0, r1 = so + y0 * sw, so + y1 * sw + local o = d0 + y * dw + for x = 0, dw - 1 do + local sx = (x + 0.5) * fx - 0.5 + if sx < 0 then + sx = 0 + end + local x0 = floor(sx) + if x0 > sw - 1 then + x0 = sw - 1 + end + local x1 = if x0 < sw - 1 then x0 + 1 else x0 + local wx = floor((sx - x0) * 256) + local a = readu8(src, r0 + x0) * (256 - wx) + readu8(src, r0 + x1) * wx + local b = readu8(src, r1 + x0) * (256 - wx) + readu8(src, r1 + x1) * wx + writeu8(dst, o + x, (a * (256 - wy) + b * wy + 32768) // 65536) + end + end +end + +-- scale(src, w, h, dw, dh, out?) -> a yuv420p buffer of dw x dh (planes Y, U, V; chroma ceil(dw / 2) x ceil(dh / 2)). +-- src must hold w x h yuv420p (checked: a short buffer or bad sizes return a zero-filled result of the right size). +function Yuv.scale(src: buffer, w: number, h: number, width: number, height: number, out: buffer?): buffer + local dw: number = math.max(1, floor(width)) + local dh: number = math.max(1, floor(height)) + local cw: number = (w + 1) // 2 + local ch: number = (h + 1) // 2 + local dcw: number = (dw + 1) // 2 + local dch: number = (dh + 1) // 2 + local size = dw * dh + 2 * dcw * dch + local dst = if out and buffer.len(out) >= size then out else bcreate(size) + 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) + 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 +end + return Yuv diff --git a/src/Formats/codecs/video/H264/Cabac.luau b/src/Formats/codecs/video/H264/Cabac.luau index 910ffa8..f6739e2 100644 --- a/src/Formats/codecs/video/H264/Cabac.luau +++ b/src/Formats/codecs/video/H264/Cabac.luau @@ -1110,6 +1110,8 @@ function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local total = S.mbW * S.mbH local st = S.type local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) + local hook = S.hook + local every = Mb.YIELD_MBS while true do if addr >= total then return false, "slice data past the end of the picture" @@ -1125,6 +1127,9 @@ function Cabac.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) end end addr += 1 + if hook and addr % every == 0 then + pcall(hook) -- (may yield: the engine state lives in this module's locals, see Decoder Options.yield) + end if epos > elimit + 8 then return false, "truncated: slice data" end diff --git a/src/Formats/codecs/video/H264/Cavlc.luau b/src/Formats/codecs/video/H264/Cavlc.luau index 9a6ecdb..49e697e 100644 --- a/src/Formats/codecs/video/H264/Cavlc.luau +++ b/src/Formats/codecs/video/H264/Cavlc.luau @@ -735,6 +735,8 @@ function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) local st = S.type local skipKind = ((st == 1) and (K_BSKIP) or (K_PSKIP)) local more = true + local hook = S.hook + local every = Mb.YIELD_MBS repeat if st ~= 2 then local run = ue(r) @@ -760,6 +762,9 @@ function Cavlc.slice(S: any, M: any, r: Bitstream.Reader): (boolean, string?) return false, err end addr += 1 + if hook and addr % every == 0 then + pcall(hook) + end if r.pos > r.size then return false, "truncated: slice data" end diff --git a/src/Formats/codecs/video/H264/Deblock.luau b/src/Formats/codecs/video/H264/Deblock.luau index 519c0a2..2a3ad94 100644 --- a/src/Formats/codecs/video/H264/Deblock.luau +++ b/src/Formats/codecs/video/H264/Deblock.luau @@ -164,7 +164,11 @@ function Deblock.picture(S: any, pic: any, params: { any }) local nzDb = S.nzDb local ys, cs = pic.ys, pic.cs local Y, U, V = pic.y, pic.u, pic.v + local hook = S.hook for my = 0, mbH - 1 do + if hook and my > 0 then + pcall(hook) + end for mx = 0, mbW - 1 do local addr = my * mbW + mx + 1 local sn = sliceTab[addr] diff --git a/src/Formats/codecs/video/H264/Decoder.luau b/src/Formats/codecs/video/H264/Decoder.luau index fb099fb..9e9b60a 100644 --- a/src/Formats/codecs/video/H264/Decoder.luau +++ b/src/Formats/codecs/video/H264/Decoder.luau @@ -26,6 +26,11 @@ export type Options = { maxPixels: number?, -- largest picture accepted (default 2^22: 4096 x 1024) lowDelay: boolean?, -- output pictures in decoding order without reordering (only right for streams without B frames) deblock: boolean?, -- false skips the loop filter (not conformant: faster, for previews); default true + -- a cooperative yield point, called (pcall'ed: it can't throw through the native code) every YIELD_MBS macroblocks + -- of slice data and every macroblock row of the loop filter: e.g. a function that calls coroutine.yield() once a time + -- budget is spent, to spread one picture over several frames. While a decode is suspended, no other H.264 decode may + -- run in the same Luau VM (the entropy decoders keep their state in module locals); default nil (no calls) + yield: (() -> ())?, } -- new(opts) -> decoder state @@ -673,6 +678,7 @@ local function startPicture(self: any, sh: any, pts: number?) st[i] = 0 end S.pic = p + S.hook = self.opts.yield end local function conceal(self: any, p: any) @@ -729,9 +735,13 @@ local function finishPicture(self: any) 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) diff --git a/src/Formats/codecs/video/H264/Mb.luau b/src/Formats/codecs/video/H264/Mb.luau index ac6d983..40ec59b 100644 --- a/src/Formats/codecs/video/H264/Mb.luau +++ b/src/Formats/codecs/video/H264/Mb.luau @@ -12,6 +12,7 @@ local Transform = require("@formats/codecs/video/H264/Transform") local Inter = require("@formats/codecs/video/H264/Inter") local Mb = {} +Mb.YIELD_MBS = 16 -- macroblocks between calls of the cooperative yield hook (S.hook: Decoder Options.yield) -- macroblock kinds (S.kind per macroblock) local K_I4, K_I8, K_I16, K_PCM, K_P, K_PSKIP, K_B, K_BSKIP, K_BDIRECT = 1, 2, 3, 4, 5, 6, 7, 8, 9 diff --git a/src/Formats/codecs/video/H264/init.luau b/src/Formats/codecs/video/H264/init.luau index 501652f..05c0d73 100644 --- a/src/Formats/codecs/video/H264/init.luau +++ b/src/Formats/codecs/video/H264/init.luau @@ -41,6 +41,7 @@ export type Options = { maxPixels: number?, -- largest picture (default 2^22 luma samples) lowDelay: boolean?, -- output in decoding order, no reordering delay (streams without B frames / reordering) deblock: boolean?, -- false skips the deblocking filter (faster, not conformant); default true + yield: (() -> ())?, -- a cooperative yield point (see Decoder Options.yield): pcall'ed every 16 macroblocks } export type Frame = { @@ -206,7 +207,8 @@ end -- Pictures come out in display order with the packet timestamps sorted (display order); a track with -- `ptsInOutputOrder` (raw Annex B, no timestamps) numbers them in output order instead. 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 } + local o: Options = { maxPixels = opts and opts.maxPixels, deblock = opts and opts.deblock, lowDelay = opts and opts.lowDelay, + yield = opts and opts.yield } local function make(): (H264Decoder?, Err.Err?) local d, err = H264.newDecoder(o) if d and track.config then diff --git a/src/Formats/codecs/video/Video/init.luau b/src/Formats/codecs/video/Video/init.luau index 335d7e5..11d6d3d 100644 --- a/src/Formats/codecs/video/Video/init.luau +++ b/src/Formats/codecs/video/Video/init.luau @@ -384,6 +384,11 @@ export type OpenOptions = { maxPixels: number?, openAudio: ((demuxer: Types.Demuxer, track: Types.Track) -> (Types.Decoder?, Err.Err?))?, -- the api's audio hook audio: boolean?, -- false: do not open the audio track + -- shrink yuv420p frames so the longer side is at most this many pixels (aspect kept; bilinear, Yuv.scale), before + -- any rgba conversion. v.width / v.height stay the source size; frame.image has the output size. Default: none + maxSide: number?, + -- passed to codecs that support a cooperative yield point (H.264: codecs/video/H264 Options.yield) + yield: (() -> ())?, [string]: any, } @@ -474,6 +479,15 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec d = t - (lastPts :: number) end 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))) + end if o.rgba then img = Yuv.imageToRgba(img) or img end diff --git a/tests/codecs/yuv.luau b/tests/codecs/yuv.luau new file mode 100644 index 0000000..84baa6a --- /dev/null +++ b/tests/codecs/yuv.luau @@ -0,0 +1,69 @@ +-- codecs/image/Yuv tests: scale (yuv420p planes resized bilinear: flat planes stay flat, a horizontal ramp stays a +-- monotonic ramp, output sizes with odd dimensions, identity size, short input), imageScale, and a toRgba round trip. +local T = require("@tests/T") +local Yuv = require("@formats/codecs/image/Yuv") +local Types = require("@formats/Types") + +local t = T.suite("yuv") + +local function planes(w: number, h: number): (number, number) + local cw, ch = (w + 1) // 2, (h + 1) // 2 + return w * h, cw * ch +end + +-- a w x h yuv420p picture: Y = horizontal ramp, U = 90, V = 200 +local function picture(w: number, h: number): buffer + local ny, nc = planes(w, h) + local b = buffer.create(ny + 2 * nc) + for y = 0, h - 1 do + for x = 0, w - 1 do + buffer.writeu8(b, y * w + x, math.floor(x * 255 / math.max(w - 1, 1))) + end + end + buffer.fill(b, ny, 90, nc) + buffer.fill(b, ny + nc, 200, nc) + return b +end + +for _, c in { { 64, 48, 32, 24 }, { 800, 600, 480, 360 }, { 33, 17, 13, 9 }, { 20, 20, 20, 20 } } do + local w, h, dw, dh = c[1], c[2], c[3], c[4] + local out = Yuv.scale(picture(w, h), w, h, dw, dh) + local ny, nc = planes(dw, dh) + local label = ("%dx%d -> %dx%d"):format(w, h, dw, dh) + t:eq(buffer.len(out), ny + 2 * nc, label .. ": size") + local mono, flat = true, true + for y = 0, dh - 1 do + local prev = -1 + for x = 0, dw - 1 do + local v = buffer.readu8(out, y * dw + x) + mono = mono and v >= prev + prev = v + end + end + for i = 0, nc - 1 do + flat = flat and buffer.readu8(out, ny + i) == 90 and buffer.readu8(out, ny + nc + i) == 200 + end + t:check(mono, label .. ": the ramp stays monotonic") + t:check(flat, label .. ": flat chroma stays flat") + t:check(buffer.readu8(out, 0) <= 16 and buffer.readu8(out, dw - 1) >= 239, label .. ": ramp ends") +end + +-- the same size copies +local src = picture(20, 20) +t:eq(buffer.tostring(Yuv.scale(src, 20, 20, 20, 20)), buffer.tostring(src), "identity") +-- a short source gives a zero picture of the right size, no throw +local short = Yuv.scale(buffer.create(10), 64, 48, 32, 24) +t:eq(buffer.len(short), 32 * 24 + 2 * 16 * 12, "short source: size") +-- out reused when big enough +local reuse = buffer.create(32 * 24 + 2 * 16 * 12) +t:check(Yuv.scale(picture(64, 48), 64, 48, 32, 24, reuse) == reuse, "out reused") + +local img = Types.Image.new(64, 48, "yuv420p") +img.pixels = picture(64, 48) +img.meta.yuv = { range = "limited", matrix = "bt601" } +local small = Yuv.imageScale(img, 32, 24) +t:check(small.format == "yuv420p" and small.width == 32 and small.height == 24, "imageScale") +t:check(small.meta.yuv and small.meta.yuv.range == "limited", "imageScale keeps meta") +local rgba = Yuv.imageToRgba(small) +t:check(rgba and rgba.width == 32 and rgba.format == "rgba8", "imageScale -> rgba") +t:done() diff --git a/tests/video/mp4.luau b/tests/video/mp4.luau index fa314a5..50094de 100644 --- a/tests/video/mp4.luau +++ b/tests/video/mp4.luau @@ -1,7 +1,7 @@ -- video/mp4 tests: MP4 / MOV files from ffmpeg (MJPEG + AAC / PCM / FLAC / MP2, H.264 with B-frames and edit lists + -- AAC, fragmented MP4, MPEG-1 + Opus): tracks and every packet against ffprobe (pts moved by the edit lists, as ffmpeg), -- frames against ffmpeg (PSNR), audio through the api hook (AAC priming dropped), seeking, our MP4 / MOV writer read --- back, fuzz. Fixtures: tools/fixtures/mp4.py. +-- back, the H.264 yield hook and maxSide, fuzz. Fixtures: tools/fixtures/mp4.py. local T = require("@tests/T") local C = require("@tests/video/_common") local F = require("@formats") @@ -76,6 +76,51 @@ for _, job in { { "mjpeg_aac.mp4", "mp4" }, { "mjpeg_pcm.mov", "mov" }, { "h264_ end end +-- H.264 with the cooperative yield hook (decoding inside a coroutine that yields at every hook call: the same pictures) +-- and maxSide (frames shrunk to the longer side, aspect kept) +do + local Crc32 = require("@formats/core/Crc32") + local data = byName["h264_aac.mp4"].data + local function crcs(opts: any, inCoroutine: boolean): ({ number }, number, number, number) + local v = assert(F.video.open(data, opts)) + local list, calls, w, h = {}, 0, 0, 0 + local function body() + while true do + local f = v:nextFrame() + if not f then + break + end + w, h = f.image.width, f.image.height + table.insert(list, Crc32.of(f.image.pixels)) + end + end + if inCoroutine then + local co = coroutine.create(body) + while coroutine.status(co) ~= "dead" do + local ok, err = coroutine.resume(co) + t:check(ok, "yield: resume " .. tostring(err)) + calls += 1 + end + else + body() + end + return list, calls, w, h + end + local plain, _, w0, h0 = crcs({ audio = false }, false) + local hooked, resumes = crcs({ audio = false, yield = function() + coroutine.yield() + end }, true) + t:check(#plain > 0, "h264: frames") + t:check(resumes > #plain, "h264 yield: the hook ran inside pictures (" .. resumes .. " resumes)") + local same = #plain == #hooked + for i, c in plain do + same = same and hooked[i] == c + end + t:check(same, "h264 yield: the same pictures as without the hook") + local _, _, w1, h1 = crcs({ audio = false, maxSide = 32 }, false) + t:check(math.max(w1, h1) == 32 and math.abs(w1 / h1 - w0 / h0) < 0.1, ("maxSide: %dx%d -> %dx%d"):format(w0, h0, w1, h1)) +end + local samples = {} for _, n in { "mjpeg_aac.mp4", "fragmented.mp4", "h264_aac.mp4" } do table.insert(samples, string.sub(byName[n].data, 1, 30000))