Files
rosetta/examples/video.luau
T
2026-11-01 01:49:44 -05:00

51 lines
2.0 KiB
Luau

-- examples/video.luau: write frames as an MJPEG AVI, open it, walk packets and frames, seek, make a GIF (docs/guide/video.md).
local F = require("@rosetta")
local I = F.ops.image
-- 1. twelve 64 x 48 frames: a square moving across a dark background
local frames = {}
for i = 0, 11 do
local img = assert(I.new(64, 48))
I.fill(img, 20, 24, 40, 255)
local square = assert(I.new(12, 12))
I.fill(square, 255, 200, 40, 255)
I.blit(img, square, i * 4, 18)
frames[i + 1] = img
end
local clip = assert(F.video.fromFrames(frames, 1 / 12)) -- 12 fps
local avi = assert(F.save(clip, nil, { format = "avi", quality = 85 }))
print(string.format("avi: %d bytes", buffer.len(avi)))
-- 2. open it: the decoder, its demuxer and the video track
local v = assert(F.video.open(avi))
local track = v.track :: any
print(string.format("%s / %s %dx%d %.1f fps %d frames %.2f s", v.format, v.codec, v.width, v.height, v.frameRate,
v.frames, v.duration))
local packets = 0
for p in v.demuxer:packets(track.id) do
packets += 1
assert(p.keyframe) -- every MJPEG frame is a keyframe
end
v:reset()
-- 3. decode every frame (yuv420p), keep rgba8 copies, and check where the square ended up
local decoded = {}
while true do
local f = v:nextFrame()
if not f then break end
table.insert(decoded, v:toRGBA(f))
end
local last = decoded[#decoded]
local r, g = I.getPixel(last, 44 + 6, 18 + 6) -- the centre of the last square
print(string.format("%d packets, last frame centre pixel r=%d g=%d", packets, r, g))
assert(packets == 12 and r > 200 and g > 150)
-- 4. seek, then turn the decoded frames into an animated GIF (a video does not save to an image format directly)
v:seek(0.5)
local f = assert(v:nextFrame())
print(string.format("after seek(0.5): pts %.3f", f.pts))
local gif = assert(F.save(assert(I.fromFrames(decoded, 1 / v.frameRate)), nil, { format = "gif" }))
local anim = assert(F.image.load(gif))
print(string.format("gif: %d bytes, %d frames", buffer.len(gif), I.frameCount(anim)))
assert(I.frameCount(anim) == 12)