Files
rosetta/docs/guide/video.md
T
4DBug 903507b23c ws-polish: guide index lists every format per page; category pages point to their new formats
Index table rows complete (from docs/FORMATS.md); scene / data Formats tables link the Roblox and
Minecraft pages; image / scene / archive / font / music intros name the wave-3 formats; video's
leftover merge markers removed and the FLI / Smacker rows moved into the table.
2026-10-31 17:17:31 -05:00

24 KiB

Video

A video file opens as a VideoDecoder: frames come out one at a time, as Images, with their presentation time. Underneath sits a Demuxer: the container's tracks and their compressed packets. Video tracks decode through a codec registry (H.264, VP8, MPEG-1, MPEG-2, Motion-JPEG, raw), and the first audio track opens as an audio Decoder. Animated GIF, APNG and WebP open as videos too. docs/video.md covers the internals and how to add a codec.

local v = assert(F.video.open(mp4Bytes))                -- H.264 + AAC
print(v.format, v.codec, v.width, v.height, v.frameRate, v.frames)   -- mp4  h264  64  48  10  10
local f = assert(v:nextFrame())                          -- the first frame
local rgba = v:toRGBA(f)                                 -- yuv420p -> rgba8 Image
local png = assert(F.save(rgba, nil, { format = "png" }))
local avi = assert(F.save(v, nil, { format = "avi" }))  -- re-encoded as Motion-JPEG + PCM
assert(F.detect(png) == "png" and F.detect(avi) == "avi")

The types

Times: VideoFrame.pts / duration, seek and every duration field are seconds. Packet pts / dts / duration are integer ticks of their track's timescale (exact, for remuxing): seconds = ticks / timescale.

VideoDecoder

F.video.open(src), F.open(src) and F.load(src) return one (F.load does not decode anything up front).

Member Meaning
kind "video"
format the container: "mp4", "mkv" / "webm", "avi", "mpegts", "y4m", "gif", ...
codec the video codec id: "h264", "vp8", "mjpeg", "mpeg1", "rawvideo"; "frames" for animated images and frame lists
width, height pixels
frameRate nominal frames per second
frames the frame count when known (0 = unknown)
duration seconds
track the video Track being decoded
audio the first audio track as an audio Decoder, or nil; audioError says why it is nil
demuxer the Demuxer (nil for animated images and frame lists)
meta container metadata (title, tags, ...)
v:nextFrame() the next VideoFrame in display order; nil, nil at the end, nil, err on a decode error
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

VideoFrame

Field Meaning
image an Image: yuv420p (what the codecs produce) or rgba8 (opts.rgba = true, animated images)
pts seconds from the start of the stream
duration seconds
keyframe true for frames that decode on their own
index 1-based position in output order; after seek it restarts at the frame's own position (round(pts * frameRate) + 1)

A yuv420p image holds three planes in one buffer: Y (width * height bytes, rows top down), then U and then V, each ceil(width / 2) * ceil(height / 2) bytes. image.meta.yuv gives the matrix ("bt601" / "bt709") and the range ("limited" / "full"); toRGBA and F.ops.image.convert(img, "rgba8") use it.

local v = assert(F.video.open(webmBytes))
local f = assert(v:nextFrame())
local img = f.image
assert(img.format == "yuv420p" and f.pts == 0 and f.keyframe)
local cw, ch = (img.width + 1) // 2, (img.height + 1) // 2
assert(buffer.len(img.pixels) == img.width * img.height + 2 * cw * ch)
local y = buffer.readu8(img.pixels, 10 * img.width + 20)                     -- luma at x = 20, y = 10
local u = buffer.readu8(img.pixels, img.width * img.height + 5 * cw + 10)    -- its chroma sample (U plane)
local _ = y + u
local r, g, b = F.ops.image.getPixel(v:toRGBA(f), 20, 10)
assert(r and g and b)

Demuxer, Track, Packet

v.demuxer (or F.format("mp4").demux(F.Bytes.reader(bytes)) for the container alone) has:

Member Meaning
kind, format "demuxer", the container name
tracks { Track }
duration, startTime seconds; frame times count from startTime
d:packets(trackId?) an iterator over the Packets of one track (or all), in file order, from the current position
d:read(trackId?) the next Packet, or nil at the end
d:seek(seconds) every track to its last keyframe at or before the time
d:track(kind) the first Track of a kind ("video", "audio", ...)
Track field Meaning
id the container's track number (Matroska track number, AVI stream index + 1, MPEG-TS PID, ...)
kind "video", "audio", "subtitle" or "data"
codec our codec id ("h264", "vp8", "aac", "vorbis", "pcm_s16le", ...)
codecTag the container's own id ("avc1", "V_VP8", "MJPG", ...)
timescale ticks per second for this track's packets
width, height, frameRate video tracks
sampleRate, channels, bitsPerSample audio tracks
config codec configuration bytes (avcC, CodecPrivate, Vorbis headers, ...)
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.

local v = assert(F.video.open(mp4Bytes))
local d = v.demuxer
local vt, at = d:track("video"), d:track("audio")
assert(vt.codec == "h264" and at.codec == "aac" and at.sampleRate == 44100)
local count, bytes, keys = 0, 0, 0
for p in d:packets(vt.id) do
	count += 1
	bytes += buffer.len(p.data)
	if p.keyframe then keys += 1 end
	local seconds = p.pts / vt.timescale                -- ticks -> seconds
	local _ = seconds
end
assert(count == 10 and keys >= 2)
print(string.format("%d packets, %.1f kbit/s", count, bytes * 8 / d.duration / 1000))

Loading and playing

Option Meaning
rgba nextFrame returns rgba8 images (default: the codec's yuv420p)
track the video track id to decode (default: the first video track)
audio false: do not open the audio track
maxPixels refuse bigger frames (LIMIT)
local v = assert(F.video.open(aviBytes, { rgba = true }))     -- Motion-JPEG + PCM
local frames = 0
while true do
	local f, err = v:nextFrame()
	assert(not err, tostring(err))
	if not f then break end
	assert(f.image.format == "rgba8")
	frames += 1
end
assert(frames == v.frames)
v:seek(0.5)                                              -- jump: decodes from the keyframe before 0.5 s
assert(v:nextFrame().pts == 0.5)
v:reset()
assert(v:nextFrame().pts == 0)

The audio track is an ordinary audio Decoder: read it, or turn it into an Audio. Encoder priming and an MP4 edit list's end padding are cut as ffmpeg cuts them, so a 1 s AAC track decodes to 1 s of samples.

local v = assert(F.video.open(webmBytes))
local a = assert(v.audio, tostring(v.audioError))
assert(a.sampleRate == 44100 and a.channels == 1)
local sound = assert(F.ops.audio.toAudio(a))
local ogg = assert(F.save(sound, nil, { format = "vorbis" }))  -- the soundtrack on its own
assert(F.detect(ogg) == "vorbis")
local aac = assert(F.ops.audio.toAudio(assert(F.video.open(mp4Bytes)).audio))
assert(aac.frames == 44100)                              -- 1 s: the AAC priming and padding cut by the edit list

Animated images open as videos (codec = "frames", rgba8 frames, no demuxer). F.video.fromImage(img) does the same for an Image you already have, and F.video.fromFrames(images, delays?) makes a video from a list of same-size images (delays in seconds: one number for all, or one per frame; default 0.1).

local g = assert(F.video.open(gifBytes))
assert(g.codec == "frames" and g.frames == 3 and g.demuxer == nil)
local imgs = {}
for i = 1, 5 do
	local im = assert(F.ops.image.new(32, 16))
	F.ops.image.fill(im, i * 50, 0, 0, 255)
	imgs[i] = im
end
local v = assert(F.video.fromFrames(imgs, 1 / 5))        -- 5 frames at 5 fps
assert(v.frames == 5 and v.duration == 1)

Saving and converting

F.save(video, dest?, opts?) writes a container. Packets the destination can hold are copied as they are (remuxing); otherwise frames are decoded and re-encoded as Motion-JPEG (the one video encoder), and audio as PCM. Images and animated images save as videos too.

Destination Video Audio
webm VP8 / VP9 / AV1 copied (VP8 is decode only, so the source must be WebM-compatible) Opus / Vorbis copied
ogv Theora copied (the source must be Theora: ogv or mkv) Vorbis / Opus copied
mkv any codec copied, else MJPEG copied, else PCM s16
mp4, mov H.264 / HEVC / AV1 / MJPEG / MPEG-4 copied, else MJPEG AAC / ALAC / Opus / FLAC / MP3 copied; PCM in MOV only
flv H.264 (with its avcC) / Sorenson Spark / VP6 / screen video copied; nothing else (no FLV encoder) AAC / MP3 / PCM / G.711 copied, else PCM s16 at 5512 / 11025 / 22050 / 44100 Hz
avi MJPEG copied, else MJPEG encoded (quality) PCM s16
y4m raw yuv420p none
h264 an H.264 track copied as an Annex B stream none

MPEG-TS and MPEG-PS are read only.

local mkv = assert(F.save(assert(F.video.open(mp4Bytes)), nil, { format = "mkv" }))   -- remux: H.264 + AAC copied
local back = assert(F.video.open(mkv))
assert(back.codec == "h264" and back.audio ~= nil)
local webm = assert(F.save(assert(F.video.open(webmBytes)), nil, { format = "webm" }))
assert(F.detect(webm) == "webm" and F.format("webm").name == "mkv")   -- WebM: the mkv format
local avi = assert(F.convert(mp4Bytes, "avi", { quality = 80 }))   -- decoded, re-encoded as MJPEG
assert(F.video.open(avi).codec == "mjpeg")
local y4m = assert(F.save(assert(F.video.fromFrames({ F.Types.Image.new(16, 16) }, 0.04)), nil, { format = "y4m" }))
assert(F.detect(y4m) == "y4m")
local gifAvi = assert(F.convert(gifBytes, "avi"))       -- an animated image as a video
assert(F.detect(gifAvi) == "avi")

A VideoDecoder is consumed as it is saved: open the source again to save it twice. Uneven frame delays (a GIF's) become a constant frame rate with repeated frames.

As an animated image

Saving a video to an image format (gif, apng, webp) collects its frames, from the decoder's current position, into an animated Image and writes that. Each frame keeps its own duration as its delay.

Option Default Meaning
frames all (up to the cap) how many frames to keep
fps the source's timing the output frame rate: frames are picked at 1 / fps steps; a source frame that covers several steps is held longer instead of repeated
maxFrames 300 the cap on frames written
maxPixels 2^25 a cap on frames * width * height (memory: 4 bytes per pixel and frame)

Past a cap the rest of the video is left unread (no error).

local gif = assert(F.convert(aviBytes, "gif", { fps = 5 }))   -- every other frame of a 10 fps clip, 0.2 s each
local anim = assert(F.image.load(gif))
assert(F.detect(gif) == "gif" and #anim.frames > 1 and math.abs(anim.frames[1].delay - 0.2) < 1e-9)
local v = assert(F.video.open(aviBytes))
v:seek(0.5)                                              -- start half a second in
local apng = assert(F.save(v, nil, { format = "apng", frames = 3 }))
assert(#F.image.load(apng).frames == 3)

The codec registry

F.video.codecs maps codec ids to entries { id, name, fourcc?, matroska?, new?, encode? }. Containers use it to name a track's codec from its FourCC or Matroska CodecID, so tracks of unknown codecs still remux.

local C = F.video.codecs
assert(C.fromFourcc("MJPG") == "mjpeg" and C.fromMatroska("V_VP8") == "vp8")
assert(C.canDecode("h264") and not C.canDecode("vp9"))  -- vp9 is known (remuxable) but has no decoder
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). C.simpleDecoder(decodeOne) builds one for codecs with one picture per packet and no reordering:

local C = F.video.codecs
assert(C.register({
	id = "solid", name = "Solid colour test codec", fourcc = { "SLID" },
	new = function(track)
		return C.simpleDecoder(function(data: buffer)       -- one packet -> one Image
			local img = assert(F.ops.image.new(track.width, track.height))
			F.ops.image.fill(img, buffer.readu8(data, 0), 0, 0, 255)
			return img
		end)
	end,
}))
assert(C.fromFourcc("SLID") == "solid" and C.canDecode("solid"))

MPEG-2 (DVD, broadcast TS)

MPEG-1 and MPEG-2 video decode through one decoder (codecs/video/Mpeg2; codecs/video/Mpeg1 is the same module): Main profile, progressive and interlaced, frame and field pictures, 4:2:0 and 4:2:2. It reads .mpg / .vob program streams, transport streams (stream type 0x02, or a private type such as 0x80 carrying a video PES), raw .m2v elementary streams, and MPEG-2 tracks of MP4 / MOV, Matroska and AVI. The output equals ffmpeg -idct int sample for sample (the integer IDCT of the IJG; ffmpeg's default IDCT differs from it by at most a level or two).

local v = assert(F.video.open(tsBytes))                  -- MPEG-TS: interlaced MPEG-2 + MP2
assert(v.format == "mpegts" and v.codec == "mpeg2")
local f = assert(v:nextFrame())
local src = f.image.meta.source
assert(src.format == "mpeg2" and src.interlaced and src.topFieldFirst)
assert(f.image.format == "yuv420p")                     -- both fields woven: the top field on the even lines
local a = assert(v.audio, tostring(v.audioError))      -- the MP2 track through the audio hook
assert(a.sampleRate == 44100)

Interlaced frames come out woven, as they were coded: deinterlace them yourself if needed (src.interlaced, src.topFieldFirst). 4:2:2 streams (studio / XDCAM) are converted to 4:2:0 for the frame Image, averaging chroma lines of the same field. A 720x576 interlaced stream decodes at about 130 frames per second in Luau on one desktop core (tools/bench.luau): real time with room to spare on a PC, less so on phones.

Ogg Theora

Ogg video (.ogv, or .ogg with a Theora stream) opens like any other container: the ogv format demuxes every Ogg stream, Theora video decodes bit-exactly (as libtheora / ffmpeg) in all three pixel formats (4:2:2 and 4:4:4 chroma is averaged down to yuv420p), and a Vorbis, Opus or FLAC track becomes v.audio. Plain Ogg Vorbis / Opus / FLAC files stay audio. Theora in Matroska (V_THEORA) decodes too, and an Ogg Theora video remuxes to ogv or mkv (there is no Theora encoder).

local v = assert(F.video.open(ogvBytes))                 -- Theora + Vorbis
assert(v.format == "ogv" and v.codec == "theora" and v.width == 64 and v.height == 48)
assert(v.frameRate == 10 and v.audio ~= nil)
local n = 0
while v:nextFrame() do n += 1 end                        -- dropped frames repeat the previous picture
assert(n == 10)
local Theora = F.format("ogv")                           -- the format module: sniff / demux / open / encode
local d = assert(Theora.demux(F.Bytes.reader(ogvBytes)))
local vt = d:track("video")
assert(vt.codec == "theora" and vt.timescale == 10)     -- packet times are frame numbers here
v:reset()
local mkv = assert(F.save(v, nil, { format = "mkv" }))   -- Theora + Vorbis copied into Matroska
assert(F.video.open(mkv).codec == "theora")

FLV and H.263

FLV (Flash Video) opens like any other container. Its onMetaData script tag is v.meta.metadata (duration, width, height, framerate, codec ids, encoder, ...). Sorenson Spark (FLV1) and H.263 (in 3GP / MP4 s263, AVI H263) decode bit-exactly as ffmpeg decodes them; H.264 tracks carry their avcC in track.config and their B-frame composition times in the pts. Flash ADPCM audio decodes (bit-exact with ffmpeg's adpcm_swf) next to MP3, AAC and PCM. VP6, screen video, Nellymoser and Speex tracks are known (and remuxable) but not decoded: nextFrame / v.audioError say UNSUPPORTED. Writing FLV copies H.264 + AAC / MP3 from MP4, Matroska or FLV sources (FLV has no codec here that encodes).

local v = assert(F.video.open(flvBytes))                 -- Sorenson Spark + MP3
assert(v.format == "flv" and v.codec == "flv1" and v.width == 64 and v.height == 48)
local md = v.meta.metadata                               -- onMetaData (AMF0)
assert(md.duration > 0 and md.framerate == 10 and md.videocodecid == 2)
local f = assert(v:nextFrame())                          -- yuv420p (BT.601, limited range)
assert(f.keyframe and f.image.format == "yuv420p")
local sound = assert(F.ops.audio.toAudio(assert(v.audio, tostring(v.audioError))))
assert(sound.sampleRate == 44100)
local h = assert(F.video.open(h263Bytes))                -- H.263 (QCIF) + AAC in 3GP
assert(h.codec == "h263" and h.width == 176 and h:nextFrame() ~= nil)
local flv = assert(F.convert(mp4Bytes, "flv"))           -- remux: H.264 + AAC copied, onMetaData written
local back = assert(F.video.open(flv))
assert(F.detect(flv) == "flv" and back.codec == "h264" and back.demuxer:track("audio").codec == "aac")

The H.263 decoder covers baseline H.263 (sub-QCIF .. 16CIF, GOB headers, unrestricted vectors) and the H.263+ picture header ffmpeg's h263p encoder writes (custom sizes, the rounding type, unrestricted vectors, slice structure); advanced prediction, PB-frames, advanced intra coding, the deblocking filter and the other H.263+ options are UNSUPPORTED.

Playing in a game loop

Decode only the frames that are due, and stop when this frame's time budget is used up; a slow frame then makes the video late instead of stalling the game.

local v = assert(F.video.open(webmBytes))
local clock, shown, pending = 0, 0, nil

local function update(dt: number, budget: number)       -- call once per game frame
	clock += dt
	local t0 = os.clock()
	while os.clock() - t0 < budget do
		pending = pending or v:nextFrame()
		if not pending or pending.pts > clock then
			return                                       -- finished, or the next frame is not due yet
		end
		shown += 1                                       -- draw v:toRGBA(pending) (EditableImage / ImageData)
		pending = nil
	end
end

for _ = 1, 120 do                                        -- two seconds at 60 fps
	update(1 / 60, 0.004)
end
assert(shown == 10)

On LÖVE, F.host.toImageData(v:toRGBA(frame)) gives the ImageData for a texture (Image:replacePixels updates it each frame); examples/love/main.lua plays a GIF this way. On Roblox, F.host.toEditableImage makes an EditableImage; for later frames write the pixels into the same one:

local editable = assert(F.host.toEditableImage(v:toRGBA(first)))
-- each new frame:
editable:WritePixelsBuffer(Vector2.zero, editable.Size, v:toRGBA(frame).pixels)

Formats

Format Read Write Video codecs (decode)
mp4 / mov / m4v / 3gp yes yes H.264, H.263, MJPEG, MPEG-1, MPEG-2
mkv / webm yes yes VP8, MJPEG, MPEG-1, MPEG-2, raw, Theora (+ H.264)
ogv (Ogg Theora) yes yes (Theora + Vorbis / Opus copied) Theora
flv yes yes (copy) Sorenson Spark, H.264 (VP6, screen video: known, not decoded)
avi yes yes MJPEG, MPEG-1, MPEG-2, raw (+ H.264)
mpegts, mpegps yes - MPEG-1, MPEG-2, H.264
y4m yes yes raw
h264 (Annex B) yes yes (copy) H.264
fli / flc / flx yes - FLIC (8-bit palettised, 15 / 16 / 24-bit): see Legacy video
smk yes - Smacker video (SMK2 / SMK4) + Smacker audio / PCM: see Legacy video
gif, png (APNG), webp as video as video via the image writers frames

See FORMATS.md. Subtitle tracks of Matroska files are read as cues by F.format("mkv").subtitles.

AVI, MOV / MP4 and MKV (V_MS/VFW/FOURCC, V_QUICKTIME) also decode the legacy codecs: Cinepak, Microsoft Video 1, QuickTime Animation (RLE) and QuickTime Graphics (SMC). See Legacy video.

Legacy video

The 1990s formats and codecs decode to rgba8 frames (they are palettised or RGB, not YUV), each frame painted over the previous one, as the codecs define. Decoding is bit-exact with ffmpeg's.

Codec id Name Containers Depths
flic Autodesk FLI / FLC fli 8-bit palettised, 15 / 16 / 24-bit
smackvid Smacker video smk 8-bit palettised
cinepak Cinepak (cvid) avi, mov, mkv 24-bit, grey, 8-bit palettised
msvideo1 Microsoft Video 1 (CRAM, MSVC, WHAM) avi, mov, mkv 16-bit (5-5-5), 8-bit palettised
qtrle QuickTime Animation (rle ) mov, mkv 1, 2, 4, 8 (palettised or grey), 16, 24, 32 (alpha)
smc QuickTime Graphics (smc ) mov, mkv 8-bit palettised

Palettes come from the container: track.palette (256 entries, 4 bytes each: R, G, B, A) holds the AVI BITMAPINFO palette or the QuickTime colour table (or the Macintosh default table it refers to); FLIC and Smacker frames carry their own palette changes.

local v = assert(F.video.open(cinepakBytes))            -- Cinepak in a QuickTime movie
assert(v.format == "mov" and v.codec == "cinepak")
local frames = 0
while true do
	local f = v:nextFrame()
	if not f then break end
	assert(f.image.format == "rgba8" and f.image.width == 64)
	frames += 1
end
assert(frames == v.frames)

FLIC files (.fli at 70 Hz ticks, .flc / .flx in milliseconds) open as videos; the ring frame (an extra frame leading back to the first, for looping) is not shown unless you ask for it.

local v = assert(F.video.open(flcBytes))
print(v.format, v.codec, v.width, v.height, v.frameRate)  -- fli  flic  64  48  10
assert(v.track.bitsPerPixel == 8 and v.frames == 10)
local f = assert(v:nextFrame())
local r, g, b, a = F.ops.image.getPixel(f.image, 0, 0)  -- palette colours, opaque
assert(r and g and b and a == 255)
local all = assert(F.format("fli").open(F.Bytes.reader(flcBytes), { ringFrame = true }))
assert(all.codec == "flic")

Smacker files carry up to seven audio tracks. The format decodes Smacker's packed audio (and raw PCM tracks) itself: v.audio is the first track, F.format("smk").openAudio(demuxer, track) opens any of them.

local v = assert(F.video.open(smkBytes))
assert(v.format == "smk" and v.codec == "smackvid")
local a = assert(v.audio, tostring(v.audioError))         -- packed 16-bit stereo, 22050 Hz
assert(a.sampleRate == 22050 and a.channels == 2)
local Smk = F.format("smk")
for _, t in v.demuxer.tracks do
	if t.kind == "audio" then
		local dec = assert(Smk.openAudio(v.demuxer, t))   -- smackaudio, pcm_u8 or pcm_s16le
		local pcm, n = dec:read(1000)
		assert(n == 1000 and buffer.len(pcm) == n * dec.channels * 4)
	end
end

Gotchas

  • Pure-Luau decoding is CPU-bound: H.264 and VP8 are practical at low resolutions. Measure with tools/bench.luau and use the budget pattern above.
  • The only video encoder is Motion-JPEG. H.264, VP8 and the others are copied (remuxed) or decoded, never encoded; F.save(v, nil, { format = "webm" }) needs a WebM-compatible source.
  • Saving consumes the decoder, and so does iterating v.demuxer:packets(): they share the read position.
  • Saving a video as GIF / APNG / WebP holds every collected frame in memory as rgba8: keep maxFrames / maxPixels low for big videos, or pick fewer frames with fps.
  • Packet times are ticks, frame times are seconds. Divide by track.timescale.
  • nextFrame returns yuv420p by default. Convert with v:toRGBA(frame) or open with { rgba = true } before handing pixels to F.host.toEditableImage / toImageData, which need rgba8.
  • Calling a video format's open directly (through F.format(name)) leaves v.audio = nil; the audio hook is set by F.video.open / F.open / F.load.