# 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, Motion-JPEG, raw), and the first audio track opens as an audio [Decoder](audio.md#decoder). Animated GIF, APNG and WebP open as videos too. [docs/video.md](../video.md) covers the internals and how to add a codec. ```luau 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, counted in output order since the decoder was opened | 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. ```luau 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, ...) | | `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. ```luau 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`) | ```luau 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. ```luau 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") ``` 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). ```luau 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 | | 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 | | 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. ```luau 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) == "mkv") -- WebM is 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. ## 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. ```luau 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: ```luau 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")) ``` ## 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. ```luau 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](../../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: ```luau 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, MJPEG, MPEG-1 | | mkv / webm | yes | yes | VP8, MJPEG, MPEG-1, raw (+ H.264) | | avi | yes | yes | MJPEG, MPEG-1, raw (+ H.264) | | mpegts, mpegps | yes | - | MPEG-1, H.264 | | y4m | yes | yes | raw | | h264 (Annex B) | yes | yes (copy) | H.264 | | gif, png (APNG), webp | as video | as video via the image writers | frames | See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as cues by `F.format("mkv").subtitles`. ## 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. - `frame.index` keeps counting after `seek`; use `frame.pts` to know where you are. - A video does not save to an image format: `F.save(v, nil, { format = "gif" })` and `F.convert(aviBytes, "gif")` fail with `UNKNOWN_FORMAT`. Collect `v:toRGBA(frame)` images and save `F.ops.image.fromFrames(images, delay)`. - 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`.