ws-apifix: videos save as animated images (F.save(video, gif | apng | webp), F.convert(avi, "gif"): frames / fps / maxFrames (300) / maxPixels (2^25)); VideoFrame.index restarts at the seek position; F.detect names WebM files "webm"

api: encoderFor finds image formats for a VideoDecoder, videoToImage() collects the frames; F.detect asks a
format's optional variant(r) for a more precise name (video/mkv: Mkv.variant, from Parse.docType).
codecs/video/Video: index after seek = round(pts * frameRate) + 1.
This commit is contained in:
4DBug committed 2026-10-31 14:00:36 -05:00
1 parent 10bd6b021f
commit d73b93c740
8 files changed
+207 -6

No files matched your search

+28 -5
View File
@@ -51,7 +51,7 @@ Times: `VideoFrame.pts` / `duration`, `seek` and every `duration` field are **se
| `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 |
| `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
@@ -192,7 +192,7 @@ local mkv = assert(F.save(assert(F.video.open(mp4Bytes)), nil, { format = "mkv"
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
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" }))
@@ -204,6 +204,30 @@ 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).
```luau
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
@@ -295,9 +319,8 @@ See [FORMATS.md](../FORMATS.md). Subtitle tracks of Matroska files are read as c
- 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)`.
- 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.
+6
View File
@@ -466,6 +466,11 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
if img then
local t = (pts or 0) / scale - start
if t + 1e-9 >= skipUntil then
if index < 0 then
-- the first frame after a seek: its position in the stream (constant-rate: round(pts * fps);
-- without a frame rate, counted from the seek)
index = if v.frameRate > 0 then math.max(0, math.floor(t * v.frameRate + 0.5)) else 0
end
index += 1
local d = defaultDur
if lastPts and t > (lastPts :: number) and defaultDur == 0 then
@@ -502,6 +507,7 @@ function Video.open(demuxer: Types.Demuxer, opts: OpenOptions?): (Types.VideoDec
flushed = false
skipUntil = seconds
lastPts = nil
index = -1 -- recomputed from the first frame's time
if self.audio then
pcall(self.audio.seek, self.audio, seconds)
end
+80
View File
@@ -412,6 +412,68 @@ end
local encodeTextures: (scene: any) -> Err.Err?
-- videoToImage(v, opts) -> an animated rgba8 Image of the video's frames (for the GIF / APNG / WebP writers) | nil,
-- Err. opts.frames: how many frames to keep (default all, up to the cap); opts.fps: the output frame rate (frames are
-- picked at 1 / fps steps, each held as long as it covers; default the source's own timing); opts.maxFrames: the cap
-- (default 300); opts.maxPixels: a cap on frames * width * height (default 2^25). Reads the decoder from where it is.
local function videoToImage(v: any, o: Options): (any, Err.Err?)
if type(v.nextFrame) ~= "function" or type(v.toRGBA) ~= "function" then
return nil, Err.new(Err.ARG, "save: not a VideoDecoder")
end
local cap = o.maxFrames or 300
local want = o.frames
local fps = o.fps
if type(cap) ~= "number" or cap < 1 or (want ~= nil and (type(want) ~= "number" or want < 1)) or (fps ~= nil and (type(fps) ~= "number" or fps <= 0 or fps > 1000)) then
return nil, Err.new(Err.ARG, "save: frames / maxFrames must be >= 1 and fps 0..1000")
end
local limit = math.floor(if want then math.min(want, cap) else cap)
local w, h = math.max(1, tonumber(v.width) or 1), math.max(1, tonumber(v.height) or 1)
limit = math.max(1, math.min(limit, math.floor((o.maxPixels or 2 ^ 25) / (w * h))))
local defaultDur = if type(v.frameRate) == "number" and v.frameRate > 0 then 1 / v.frameRate else 0.1
local images, delays = {}, {}
local t0: number? = nil
local taken = 0 -- output slots used (fps mode)
while #images < limit do
local ok, f, ferr = pcall(v.nextFrame, v)
if not ok then
return nil, Err.new(Err.CORRUPT, "video decoder threw: " .. tostring(f))
end
if f == nil then
if ferr then
return nil, ferr
end
break
end
local dur = if type(f.duration) == "number" and f.duration > 0 then f.duration else defaultDur
local delay = dur
if fps then
local start: number = t0 or f.pts
t0 = start
local slots = math.ceil((f.pts - start + dur) * fps - 1e-6) - taken
delay = slots / fps
taken += math.max(0, slots)
end
if delay > 0 then
local rok, img = pcall(v.toRGBA, v, f)
if not rok or type(img) ~= "table" then
return nil, Err.new(Err.CORRUPT, "frame " .. tostring(f.index) .. " did not convert to rgba8")
end
table.insert(images, img)
table.insert(delays, delay)
end
end
if #images == 0 then
return nil, Err.new(Err.ARG, "save: the video has no frames")
end
local img, ierr = ImageOps.fromFrames(images, delays)
if not img then
return nil, ierr
end
img.loops = if type(v.loops) == "number" then v.loops else 0
img.meta.source = { format = v.format }
return img, nil
end
-- renderMusic(value, opts) -> the audio Decoder of a Module (codecs/audio/Tracker) or a Midi (music/midi render) |
-- nil, Err. opts are the render options: sampleRate, soundfont, gain, tail, interpolation, stereoSeparation, ...
local function renderMusic(value: any, o: Options): (any, Err.Err?)
@@ -452,6 +514,9 @@ local function encoderFor(value: any, dest: string?, o: Options): (Registry.Entr
if not entry and category == "image" and type(value) == "table" and value.kind == "image" then
entry = find(key, "video") -- an (animated) image written as a video: F.convert(gif, "avi")
end
if not entry and category == "video" and type(value) == "table" and value.kind == "video" then
entry = find(key, "image") -- a video written as an animated image (F.save): F.convert(avi, "gif")
end
if not entry and category == "music" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then
entry = find(key, "audio") -- a Module / Midi saved as audio is rendered first (F.save): F.convert(mod, "wav")
end
@@ -516,6 +581,13 @@ function F.save(value: any, dest: string?, opts: Options?): (any, Err.Err?)
end
value = v
end
if entry.category == "image" and type(value) == "table" and value.kind == "video" then
local img, ierr = videoToImage(value, o)
if not img then
return nil, ierr
end
value = img
end
if entry.category == "audio" and type(value) == "table" and (value.kind == "music" or value.kind == "midi") then
local dec, rerr = renderMusic(value, o) -- the render options (sampleRate, soundfont, loop, ...) come from opts
if not dec then
@@ -588,6 +660,14 @@ function F.detect(src: any, opts: Options?): (string?, Err.Err?)
if not entry then
return nil, err
end
-- a format may name the file's flavour more precisely (video/mkv: "webm" for DocType webm)
local m = module(entry)
if m and type(m.variant) == "function" then
local ok, v = pcall(m.variant, Bytes.reader(buf))
if ok and type(v) == "string" then
return v, nil
end
end
return entry.name, nil
end
+11 -1
View File
@@ -553,7 +553,9 @@ end
export type Options = { maxPackets: number? }
-- parse(buf, base, limit, opts) -> a Demux | nil, Err
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
-- docType(buf, base, limit) -> the EBML header's DocType ("matroska" when it has none), the header's size and data
-- offset | nil, Err
function Parse.docType(buf: buffer, base: number, limit: number): (string?, any, number?)
local id, size, data = Ebml.header(buf, base, limit)
if id ~= ID.EBML or not size or not data then
return nil, Err.new(Err.CORRUPT, "not an EBML file", base)
@@ -567,6 +569,14 @@ function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?):
docType = Ebml.string(buf, o, n)
end
end
return docType, size, data
end
function Parse.parse(buf: buffer, base: number, limit: number, opts: Options?): (any, Err.Err?)
local docType, size, data = Parse.docType(buf, base, limit)
if not docType then
return nil, size
end
if docType ~= "matroska" and docType ~= "webm" then
return nil, Err.new(Err.UNSUPPORTED, "EBML document type " .. docType)
end
+9
View File
@@ -67,6 +67,15 @@ function Mkv.sniff(r: Bytes.Reader): number
return 0.5
end
-- variant(r) -> "webm" for a WebM file (DocType webm), else nil: the name F.detect reports (never throws)
function Mkv.variant(r: Bytes.Reader): string?
local ok, docType = pcall(Parse.docType, r.buf, r.pos, r.limit)
if ok and docType == "webm" then
return "webm"
end
return nil
end
-- ------------------------------------------------------------------------------------------------ encode
-- encode(video, opts?) -> buffer | nil, Err: a VideoDecoder (F.load / F.video.open of any video or animated image)
-- or a Demuxer
+6
View File
@@ -180,6 +180,12 @@ function C.seek(t: any, v: any, c: any, label: string, at: number)
v:seek(at)
local f = v:nextFrame()
t:check(f ~= nil and f.pts >= at - 1e-6 and f.pts < at + 0.2, label .. ": seek to " .. at .. " lands at " .. tostring(f and f.pts))
if f and v.frameRate > 0 then
-- frame.index restarts at the seek position (not counted on from before the seek)
t:eq(f.index, math.floor(f.pts * v.frameRate + 0.5) + 1, label .. ": frame index after seeking")
local g = v:nextFrame()
t:check(g == nil or g.index == f.index + 1, label .. ": index counts on after the seek")
end
if f and C.EXACT[v.codec] and c.frames then
local idx = math.floor(f.pts * v.frameRate + 0.5) + 1
t:eq(Crc32.of(f.image.pixels), c.frames[idx], label .. ": the frame after seeking equals ffmpeg's frame " .. idx)
+57
View File
@@ -113,4 +113,61 @@ do
t:check(out ~= nil and buffer.tostring(out) == gifAvi.data, "gif.avi: F.convert(gif, 'avi') again byte for byte")
end
end
-- frame.index after seek on a demuxed video (MJPEG AVI at 10 fps): the frame's own position, then counting on
local function gradient(n: number): { any }
local imgs = {}
for i = 1, n do
local im = assert(F.ops.image.new(16, 8))
F.ops.image.fill(im, i * 12, 0, 255 - i * 12)
imgs[i] = im
end
return imgs
end
local avi = assert(F.save(assert(F.video.fromFrames(gradient(20), 0.1)), nil, { format = "avi", quality = 90 }))
do
local v = assert(F.video.open(avi))
for i = 1, 3 do
t:eq((v:nextFrame() :: any).index, i, "index before seeking " .. i)
end
v:seek(1.0)
local f = v:nextFrame() :: any
t:check(f.index == 11 and math.abs(f.pts - 1.0) < 1e-6, "seek(1.0): frame 11")
t:eq((v:nextFrame() :: any).index, 12, "then 12")
v:seek(0.25)
t:eq((v:nextFrame() :: any).index, 4, "seek back to 0.25: frame 4 (0.3 s)")
v:reset()
t:eq((v:nextFrame() :: any).index, 1, "reset: frame 1")
end
-- a video saved as an animated image (GIF / APNG / WebP): every frame with its timing, or frames / fps / maxFrames
do
local gif = assert(F.convert(avi, "gif"))
t:eq(F.detect(gif), "gif", "convert(avi, gif)")
local g = assert(F.image.load(gif))
t:check(#g.frames == 20 and math.abs(g.frames[1].delay - 0.1) < 1e-9 and g.width == 16 and g.height == 8, "gif: 20 frames of 0.1 s")
local g2 = assert(F.image.load(assert(F.convert(avi, "gif", { fps = 5 }))))
t:check(#g2.frames == 10 and math.abs(g2.frames[1].delay - 0.2) < 1e-9, "fps = 5: 10 frames of 0.2 s")
local g3 = assert(F.image.load(assert(F.convert(avi, "gif", { fps = 20 }))))
local total = 0
for _, fr in g3.frames do
total += fr.delay
end
t:check(#g3.frames == 20 and math.abs(total - 2) < 0.02, "fps above the source: frames held, total 2 s")
t:eq(#(assert(F.image.load(assert(F.convert(avi, "gif", { frames = 4 })))) :: any).frames, 4, "frames = 4")
t:eq(#(assert(F.image.load(assert(F.convert(avi, "gif", { maxFrames = 7 })))) :: any).frames, 7, "maxFrames = 7")
t:eq(#(assert(F.image.load(assert(F.convert(avi, "gif", { maxPixels = 16 * 8 * 5 })))) :: any).frames, 5, "maxPixels caps the frames")
local apng = assert(F.save(assert(F.video.open(avi)), nil, { format = "apng" }))
local a = assert(F.image.load(apng))
t:check(F.detect(apng) == "png" and #a.frames == 20, "save(video, apng)")
local webp = assert(F.save(assert(F.video.open(avi)), nil, { format = "webp" }))
t:check(F.detect(webp) == "webp" and #(assert(F.image.load(webp)) :: any).frames == 20, "save(video, webp)")
-- the frames are the decoded pictures: the GIF's first frame is the MJPEG frame (lossy, palette)
local v = assert(F.video.open(avi))
local first = v:toRGBA(v:nextFrame())
local r1 = buffer.readu8(first.pixels, 0)
t:check(math.abs(buffer.readu8(g.pixels, 0) - r1) <= 8, "gif frame 1 matches the decoded frame")
local _, e = F.save(assert(F.video.open(avi)), nil, { format = "gif", fps = -1 })
t:check(e and e.code == F.Err.ARG, "bad fps")
end
t:done()
+10
View File
@@ -88,6 +88,16 @@ do
t:eq(len, 160, "lacing: EBML-laced frame size")
end
-- F.detect names WebM files (DocType webm) "webm", Matroska files "mkv"; both open through the mkv format
do
t:eq(F.detect(byName["vp8_opus.webm"].data), "webm", "detect: webm")
t:eq(F.detect(byName["mjpeg_pcm.mkv"].data), "mkv", "detect: mkv")
t:eq(Mkv.variant(Bytes.reader(buffer.fromstring(byName["vp8_opus.webm"].data))), "webm", "variant: webm")
t:eq(Mkv.variant(Bytes.reader(buffer.fromstring(byName["mjpeg_pcm.mkv"].data))), nil, "variant: matroska")
t:eq(Mkv.variant(Bytes.reader(buffer.fromstring("\26\69\223\163"))), nil, "variant: truncated")
t:eq(F.format("webm").name, "mkv", "format(webm) is mkv")
end
-- 4. our muxer: remux WebM (VP8 + Opus copied) and read it back packet for packet
do
local src = byName["vp8_opus.webm"]