merge master

This commit is contained in:
4DBug committed 2026-10-31 14:25:41 -05:00
commit b5964d4afc
39 files changed
+1158 -73

No files matched your search

+13 -2
View File
@@ -12,6 +12,8 @@ string is a path only when `opts.path = true` or when it does not look like file
`opts.data = true` to force bytes. Roblox and the luau CLI have no file system: pass buffers or strings.
`F.save(value, dest?, opts?)` returns a `buffer`, or writes the file `dest` (extension = format) and returns `true`.
Formats that write extra files (`caps.extraFiles`: BMFont pages) put them next to `dest`; without a destination they
come back as a third value `{ [file name] = buffer }` (or in the caller's `opts.files` table).
## Loading and saving
@@ -19,16 +21,22 @@ string is a path only when `opts.path = true` or when it does not look like file
|---|---|
| `F.load(src, opts?)` | the category's standard value (`Image`, `Audio`, `Scene`, `Font`, `Archive`, `Vector`, `Layered`, `Subtitles`, `Module` / `Midi`, `Playlist`, data values, a `VideoDecoder`) |
| `F.open(src, opts?)` | a streaming decoder: audio `Decoder`, `VideoDecoder`, or a container `Demuxer` |
| `F.save(value, dest?, opts?)` | `buffer` / `true` |
| `F.save(value, dest?, opts?)` | `buffer` / `true` (+ the extra files, see above) |
| `F.saveString(value, opts?)` | the encoded bytes as a string |
| `F.convert(src, format, opts?)` | load + save (`opts` go to both; `opts.out = path` writes a file) |
| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension) |
| `F.detect(src, opts?)` | the format name (content sniffing first, then the extension); a format's optional `variant(r)` can name the flavour (`"webm"` for a WebM file read by mkv) |
| `F.formats(category?)` | `{ { name, category, extensions, mime, caps } }` without loading any format (also [FORMATS.md](FORMATS.md)) |
| `F.format(name)` | the format module itself (`sniff` / `decode` / `encode` / `open` and extras such as `png.info`) |
Common options: `format` (a name or extension: what to decode as / encode to; without it, saving uses the source
format), `category`, `name` (a file name hint for detection), `path` / `data`, size limits (`maxPixels`, `maxBytes`,
`maxFrames`, ...), and each format's own options (documented in its `init.luau`: `level`, `quality`, `bitrate`, ...).
`bitrate` is in bits per second for every encoder (values below 1000 are read as kbit/s).
Across categories: a Module or Midi saved to an audio format is rendered first (render options in `opts`:
`F.convert(modBytes, "wav", { sampleRate = 22050 })`), and `F.audio.open` / `F.audio.load` render music bytes; a
VideoDecoder saved to an image format (`gif`, `apng`, `webp`) becomes an animated Image of its frames (`frames`,
`fps`, `maxFrames` = 300, `maxPixels` = 2^25); an Image saves to a video format as a frames-backed video.
## Category facades
@@ -43,6 +51,8 @@ one category. Extras:
- `F.cad.toBodies`, `F.cad.fromBodies`, `F.cad.tessellate`: STEP B-rep calls through the injected kernel
(`F.plugins.brep`).
- `F.data.null`: the JSON / YAML / TOML / msgpack / CBOR null.
- `F.music.new`, `addPattern`, `setCell`, `getCell`, `addSample`, `addInstrument`, `note`: build and edit tracker
modules (`ops/MusicOps`, also `F.ops.music`): `F.music.new({ format = "mod", channels = 4 })`.
## Editing: `F.ops`
@@ -54,6 +64,7 @@ arguments.
| `F.ops.image` | `ops/ImageOps` | `convert` (pixel formats), `crop`, `resize` (nearest / bilinear / Lanczos-3), `flip`, `rotate90`, `rotate`, `blit`, `composite`, `premultiply` / `unpremultiply`, `getPixel` / `setPixel` / `fill`, `new` / `copy`, animations: `coalesce` (frames on full canvases), `fromFrames`, `frameCount`, `durations` |
| `F.ops.mesh` | `ops/MeshOps` | `triangulate`, `transform`, `computeNormals`, `computeTangents`, `weld` / `unweld`, `bounds`, `merge`, `scale` / `setUnit` / `setUp`, `voxelsToPrimitive`, `meshVoxels` |
| `F.ops.layers` | `ops/LayerOps` | `flatten(layered, { frame })`, `flattenFrames`, `leaves` |
| `F.ops.music` | `ops/MusicOps` | `new`, `addPattern`, `setCell` / `getCell`, `addSample` (from an Audio), `addInstrument`, `note` (`"C-4"` -> 49) |
| `F.ops.audio` | `ops/AudioOps` | `toAudio` (an Audio from an Audio or a Decoder), `gain`, `gainDb`, `normalize`, `peak`, `rms`, `mix`, `remix` / `downmix` / `upmix` (WAVE-layout matrices), `resample` (`codecs/audio/Resample`), `trim`, `concat`, `fade` |
| `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` |
+1 -1
View File
@@ -45,7 +45,7 @@ is tested under both runtimes (luau `--codegen -O2` and LuaJIT through the build
| model | usda | .usda .usd .usdz | yes | yes | materials: true, animation: true, cameras: true, lights: true, polygons: true, vertexColors: true, usdz: "read", usdc: false | `tests/model/usda.luau` |
| model | vox | .vox | yes | yes | voxels: true, sceneGraph: true, materials: true | `tests/model/vox.luau` |
| cad | step | .step .stp .p21 | yes | yes | complexEntities: true, sections: true, brep: "plugin", tessellate: "plugin" | `tests/cad/step.luau` |
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary" | `tests/font/bmfont.luau` |
| font | bmfont | .fnt | yes | yes | bitmap: true, variants: "text", "xml", "binary", extraFiles: true | `tests/font/bmfont.luau` |
| font | ttf | .ttf .otf .ttc .otc | yes | - | outlines: "truetype", "cff", collection: true, kerning: true | `tests/font/ttf.luau` |
| font | woff | .woff | yes | - | outlines: "truetype", "cff" | `tests/font/woff.luau` |
| font | woff2 | .woff2 | yes | - | outlines: "truetype", "cff", transforms: "glyf", "loca", "hmtx" | `tests/font/woff2.luau` |
+5 -2
View File
@@ -20,7 +20,7 @@ The reference implementation to copy is **PNG**:
src/Formats/
init.luau Registry.luau (generated) api (layer 6)
ops/ ops (layer 5.5) editing on the standard types (F.ops.image /
mesh / layers / audio; ImageOps, MeshOps, ...)
mesh / layers / audio / music; ImageOps, ...)
<category>/<fmt>/ formats (layer 5) image audio video model cad font archive data
vector layered subtitle music playlist
containers/ containers (layer 4) Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, ...
@@ -126,7 +126,10 @@ Rules:
- `open(r, opts)` (audio / video) returns the streaming Decoder / VideoDecoder / Demuxer from `Types.luau`. If a format
has `open` but no `decode`, `F.load` decodes the whole stream through it.
- Options are a typed table with defaults documented on each field (`level: number?, -- 0..9, default 6`).
- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module.
- Extra format-specific functions (`Png.info(r)`) are fine; `F.format("png")` returns the module. Two optional ones the
api calls: `variant(r) -> string?` (a more precise name for `F.detect`: video/mkv gives `"webm"`), and encoders
that write extra files into `opts.files` declare `caps.extraFiles = true` (the api then returns them from
`F.save` without a destination).
- No globals, no state between calls, no host access (no files, no `game`).
### Conventions shared by every format
+2 -2
View File
@@ -193,7 +193,7 @@ Every call takes an optional `opts` table. The options every format understands:
| `maxPixels`, `maxBytes`, `maxFrames`, ... | size limits; going over returns `LIMIT` |
Each format adds its own options, such as `quality` for JPEG, `lossless` for WebP, `level` for PNG and zip, or
`bitrate` for MP3. The type pages list them.
`bitrate` (bits per second) for MP3 and Opus. The type pages list them.
```luau
local img = assert(F.load(pngBytes))
@@ -252,7 +252,7 @@ file instead of returning a buffer.
```luau
local webp = assert(F.convert(pngBytes, "webp", { lossless = true }))
local mp3 = assert(F.convert(wavBytes, "mp3", { bitrate = 128 }))
local mp3 = assert(F.convert(wavBytes, "mp3", { bitrate = 128000 }))
assert(F.detect(webp) == "webp" and F.detect(mp3) == "mp3")
```
+8 -6
View File
@@ -10,7 +10,7 @@ local song = assert(F.audio.load(flacBytes)) -- Audio: the whole file
print(song.sampleRate, song.channels, song.frames) -- 44100 2 44100
print(song.tags.title, song.tags.artist) -- Docs Tone formats-luau
local quieter = F.ops.audio.gainDb(song, -6)
local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192 })) -- a buffer
local mp3 = assert(F.save(quieter, nil, { format = "mp3", bitrate = 192000 })) -- a buffer
assert(F.detect(mp3) == "mp3")
```
@@ -174,12 +174,15 @@ Encoder options:
|---|---|
| wav | `sampleFormat = "u8" \| "s16" \| "s24" \| "s32" \| "f32"` (default `"s16"`), `rf64`, `extensible`, `channelMask`, `tags` |
| flac | `level` 0..8 (default 5), `bits` 4..24 (default: the source depth, else 16), `blockSize`, `seekInterval`, `padding` |
| mp3 | `bitrate` **in kbps** (default 128), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` |
| mp3 | `bitrate` (default 128000; one of the layer's rates), `layer` 3 or 2 (MP2), `mode = "stereo" \| "joint" \| "mono"`, `sampleRate`, `id3`, `resampleQuality` |
| vorbis | `quality` -1..10 (default 3) |
| opus | `bitrate` **in bits per second** (default 64000 per channel); CELT only; resampled to 48 kHz |
| opus | `bitrate` (default 64000 per channel, 6000..510000); CELT only; resampled to 48 kHz |
| aiff, au, voc | `sampleFormat` (see each format's `init.luau`) |
| m4a, caf | ALAC (lossless); m4a and caf also keep tags |
`bitrate` is in **bits per second** for every encoder (`bitrate = 192000`), as the Decoder's `bitrate` field is. A
value below 1000 is read as kbit/s (`bitrate = 192` is 192000), so older code that passed kbit/s to MP3 still works.
Tags are written from `audio.tags`, or from the Decoder's `tags`, wherever the format has tags.
## Formats
@@ -242,7 +245,6 @@ visualisers.
## Gotchas
- **Bitrate units differ.** MP3 takes kbps (`bitrate = 192`); Opus takes bits per second (`bitrate = 96000`).
- `F.ops.audio.downmix(a)` defaults to **2** channels, so a stereo input stays stereo. Use `downmix(a, 1)` for mono.
- `read(n, out)` returns a new buffer when `out` is too small. Always use the buffer it returns.
- Opus always decodes at 48 kHz. Resample with `F.ops.audio.resample` if you need another rate.
@@ -250,5 +252,5 @@ visualisers.
number.
- `F.save(decoder)` without `opts.format` or a destination fails with `Err.ARG`, because a Decoder has no source
format.
- `F.audio.load` does not take music files (MOD, MIDI). Use `F.music.open(src)` for their audio
([music.md](music.md)).
- Music files (MOD, S3M, XM, IT, MIDI) are audio too: `F.audio.open` / `F.audio.load` render them, with the
render options in `opts` ([music.md](music.md)).
+12 -2
View File
@@ -219,8 +219,18 @@ local again = assert(F.font.load(bin, { pages = baked.pages }))
assert(again:advance(again:glyphIndex(string.byte("H"))) == baked:advance(baked:glyphIndex(string.byte("H"))))
```
`F.save(ttf, nil, { format = "bmfont", px = 16 })` bakes too, but returns only the descriptor: the page images are
not written anywhere. Use `bake` when you need the pages.
`F.save(ttf, dest, { format = "bmfont", px = 16, chars = ... })` bakes too, and writes the page PNGs next to the
`.fnt`, named after it (`ui.fnt` gets `ui_0.png`, ...; `file` sets another prefix). Without a destination it
returns the pages as a third value, `{ [page file name] = PNG buffer }` (the names the descriptor uses), or puts
them into your `opts.files` table when you pass one. A BMFont whose pages are loaded saves them the same way.
```luau
local ttf = assert(F.font.load(ttfBytes))
local fnt, _, pages = F.save(ttf, nil, { format = "bmfont", px = 16, chars = "Hi", file = "hud" })
assert(fnt and pages and F.detect(pages["hud_0.png"]) == "png")
local bm = assert(F.font.load(fnt, { loadPage = function(file) return pages[file] end }))
assert(bm:rasterize(bm:glyphIndex(string.byte("H"))))
```
## Formats
+2 -4
View File
@@ -58,7 +58,8 @@ assert(flat.width == 48 and F.detect(png) == "png")
**Groups.** A group with `blend = "passThrough"` blends its children straight onto what is below (as Photoshop's
pass-through and Aseprite's plain groups). Any other blend first composites the children on their own transparent
canvas, then blends that result with the group's mode and opacity.
canvas, then blends that result with the group's mode and opacity. A group's mask applies either way: on a
pass-through group it limits, pixel by pixel, how much of the children's effect reaches the canvas.
**Format extras.**
@@ -164,7 +165,6 @@ doc.layers = { L.layer("Paper", paper), L.group("Art", { inkLayer, shadeLayer })
local mask = assert(F.ops.image.new(32, 16, "gray8"))
F.ops.image.fill(mask, 255, 255, 255) -- show the top half
doc.layers[2].blend = "normal" -- an isolated group (masks need one, see Gotchas)
doc.layers[2].mask = { image = mask, x = 0, y = 0, default = 0 } -- hide the rest
local flat = assert(F.ops.layers.flatten(doc))
@@ -244,6 +244,4 @@ See [FORMATS.md](../FORMATS.md) for the capability matrix.
not rendered, so the result can differ from Photoshop's `meta.composite`.
- Linked Aseprite cels share one Image table between frames: copy it (`F.ops.image.copy`) before editing a single
frame.
- `flatten` ignores the mask of a `passThrough` group (Photoshop applies it). Give a masked group a real blend mode
such as `"normal"` to isolate it.
- Pixels are straight (not premultiplied) alpha, like every Image.
+72 -10
View File
@@ -142,8 +142,8 @@ end
| `F.music.load(src, opts?)` / `F.load` | a Module, a Midi or a SoundFont |
| `F.music.open(src, opts?)` / `F.open` | the rendered audio Decoder (decode and render options together) |
`F.audio.open` and `F.audio.load` do not take music files; use `F.music.open`, or `F.open`, which detects any
category.
Every music file that renders is also audio: `F.audio.open(src)` gives the same rendered Decoder as `F.music.open`,
and `F.audio.load(src)` the whole render as an Audio. Decode and render options go in the same `opts`.
| Option | Formats | Meaning |
|---|---|---|
@@ -157,6 +157,8 @@ assert(dec.sampleRate == 22050 and dec.channels == 2)
assert(math.abs(dec.duration - 3) < 0.01) -- 2 s of notes + the 1 s release tail
local d2 = assert(F.open(modBytes)) -- any category: a Decoder for a module
assert(d2.channels == 2)
local d3 = assert(F.audio.open(midiBytes, { sampleRate = 22050 })) -- music is audio too
assert(d3.sampleRate == 22050)
```
## Rendering
@@ -199,20 +201,20 @@ assert(first.frames == 22050)
A Midi is plain data: build one with `F.Types.Midi.new(division?)` and save it as `.mid`. Events need absolute
ticks; the writer sorts nothing, so keep each track's events in tick order. A track's `name` is read from its
track-name meta event (0x03); the writer writes events only, so put the name in an event.
track-name meta event (0x03); the writer writes `track.name` as one at tick 0 when the track has no 0x03 event of
its own.
```luau
local m = F.Types.Midi.new(480) -- 480 ticks per quarter note, SMF type 1
local events = {
{ tick = 0, type = "meta", meta = 0x51, data = { 0x07, 0xA1, 0x20 } }, -- tempo: 500000 us per quarter
{ tick = 0, type = "meta", meta = 0x03, data = { string.byte("Arpeggio", 1, -1) } }, -- the track name
{ tick = 0, type = "program", channel = 0, data = { 0 } },
}
for i, note in { 60, 64, 67, 72 } do
table.insert(events, { tick = (i - 1) * 240, type = "noteOn", channel = 0, data = { note, 100 } })
table.insert(events, { tick = i * 240, type = "noteOff", channel = 0, data = { note, 0 } })
end
table.insert(m.tracks, { events = events })
table.insert(m.tracks, { name = "Arpeggio", events = events }) -- written as a 0x03 event
local bytes = assert(F.save(m, nil, { format = "midi" }))
local back = assert(F.music.load(bytes))
assert(back.tracks[1].name == "Arpeggio" and back.meta.length == 1) -- 4 eighth notes at 120 BPM
@@ -232,6 +234,69 @@ local _, err = F.save(song, nil, { format = "it" })
assert(err.code == F.Err.UNSUPPORTED) -- read only
```
Saving a Module or a Midi to an **audio** format renders it first, with the render options (see
[Rendering](#rendering)) taken from the same `opts`; `F.convert` does the same from music bytes:
```luau
local song = assert(F.music.load(modBytes))
local wav = assert(F.save(song, nil, { format = "wav", sampleRate = 22050 }))
assert((assert(F.audio.load(wav))).sampleRate == 22050)
local flac = assert(F.convert(midiBytes, "flac", { soundfont = sf2Bytes, tail = 0.5 }))
assert(F.detect(flac) == "flac")
```
### Building a module
`F.music` has a small builder for tracker modules, so you never touch the pattern buffers or the sample tuning
fields yourself. Pattern numbers are 0-based (as the order list names them), rows 0-based, channels 1-based, and
sample and instrument numbers 1-based (0 = none in a cell). Every call returns `nil, Err.ARG` for bad arguments.
| Call | Returns |
|---|---|
| `F.music.new({ format?, channels?, title?, speed?, tempo? })` | an empty Module: `format` `"mod"` (default), `"xm"`, `"s3m"` or `"it"`; 4 channels by default |
| `F.music.addPattern(m, rows?, { order? }?)` | the new pattern's number; `rows` default 64 (MOD needs 64); appended to `m.order` unless `order = false` |
| `F.music.setCell(m, pattern, row, channel, cell)` | `true`; `cell = { note, instrument, volume, effect, param }`, missing fields 0 |
| `F.music.getCell(m, pattern, row, channel)` | the cell, with `note` as a number |
| `F.music.addSample(m, spec)` | the new sample's number |
| `F.music.addInstrument(m, spec)` | the new instrument's number (XM / IT only; MOD and S3M cells name samples) |
| `F.music.note(name)` | the note number: `"C-4"` = 49, `"C#4"` / `"Db4"` = 50, `"off"` 255, `"cut"` 254, `"fade"` 253 |
`addSample` takes `audio` (a mono or stereo Audio) or `data` (f32 frames) with `length` and `channels`; `rate`
(the Hz the sample plays at on C-4 for MOD / XM, C-5 for S3M / IT; default the Audio's rate, else 8363), `loop`
(`"none"`, `"forward"`, `"pingpong"`), `loopStart` / `loopEnd` (frames), `volume` 0..64, `pan` 0..256 and `bits`
(8 or 16, what a writer stores). MOD files keep only a finetune of -1..+7/8 semitone, so give MOD samples a rate
near 8363 Hz. `addInstrument` takes `name`, `sample` (every note) or `samples` (a `{ [note] = sample }` keymap),
`fadeout`, and a volume `envelope = { points = { { tick, 0..64 }, ... }, sustain?, loopStart?, loopEnd? }`.
```luau
local tone = F.Types.Audio.new(8363, 1, 8363) -- 1 s of a 440 Hz sine at MOD's C-4 rate
for i = 0, 8362 do
buffer.writef32(tone.samples, i * 4, 0.5 * math.sin(i / 8363 * 2 * math.pi * 440))
end
local song = assert(F.music.new({ format = "mod", channels = 4, title = "beeps" }))
local s = assert(F.music.addSample(song, { name = "sine", audio = tone, loop = "forward" }))
local p = assert(F.music.addPattern(song)) -- pattern 0, 64 rows, in the order list
for row = 0, 63, 8 do
assert(F.music.setCell(song, p, row, 1, { note = if row % 16 == 0 then "C-4" else "G-4", instrument = s }))
end
assert(F.music.setCell(song, p, 63, 2, { effect = 0xC, param = 0 })) -- effect C00: volume 0
assert(F.music.getCell(song, p, 8, 1).note == F.music.note("G-4"))
local mod = assert(F.save(song)) -- a .mod (the module's format)
local wav = assert(F.save(song, nil, { format = "wav" })) -- or rendered
assert(F.detect(mod) == "mod" and F.detect(wav) == "wav")
local xm = assert(F.music.new({ format = "xm", channels = 2 }))
local smp = assert(F.music.addSample(xm, { audio = tone }))
local lead = assert(F.music.addInstrument(xm, {
name = "lead", sample = smp, fadeout = 512,
envelope = { points = { { 0, 64 }, { 10, 40 }, { 40, 0 } }, sustain = 2 },
}))
local p2 = assert(F.music.addPattern(xm, 32))
assert(F.music.setCell(xm, p2, 0, 1, { note = "C-4", instrument = lead }))
assert(F.music.setCell(xm, p2, 16, 1, { note = "off" }))
assert(F.music.load(assert(F.save(xm))).instruments[1].name == "lead")
```
| Format | Encoder options |
|---|---|
| midi | `runningStatus` (default true: the bytes python's mido writes) |
@@ -252,11 +317,8 @@ See [FORMATS.md](../FORMATS.md) for each format's capabilities.
## Gotchas
- **Saving music as audio needs a render.** `F.save(song, nil, { format = "wav" })` and `F.convert(modBytes, "wav")`
fail with `UNKNOWN_FORMAT` ("no format named wav for music"). Render first:
`F.save(song:render(), nil, { format = "wav" })`.
- `F.audio.open(midiBytes)` fails with `UNKNOWN_FORMAT`; use `F.music.open` or `F.open`.
- `track.name` is not written: add a meta 0x03 event to name a track.
- Saving music to an audio format renders it with the options in `opts`: `F.save(song, nil, { format = "wav",
loop = true })` would render up to `maxDuration` (an hour by default), so leave `loop` off when saving.
- A Midi you build yourself has no `render` method; `F.format("midi").render(midi, opts)` renders it.
- MIDI event ticks are absolute, not the deltas stored in the file. Pitch bend `data` is `{ lsb, msb }`, not a
signed value: `(msb * 128 + lsb) - 8192`.
+1 -1
View File
@@ -112,7 +112,7 @@ end
`F.convert` streams audio: the encoder reads the decoder as it goes.
```luau
local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192 })) -- MP3 bit rates are in kbit/s
local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192000 })) -- bit rates are in bit/s
local dec = assert(F.audio.open(mp3))
assert(dec.sampleRate == 44100 and dec.channels == 2)
assert(math.abs(dec.duration - 1) < 0.1)
+33 -6
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
@@ -95,6 +95,7 @@ assert(r and g and b)
| `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.
@@ -142,7 +143,8 @@ v:reset()
assert(v:nextFrame().pts == 0)
```
The audio track is an ordinary audio Decoder: read it, or turn it into an Audio.
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.
```luau
local v = assert(F.video.open(webmBytes))
@@ -151,6 +153,8 @@ 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
@@ -192,7 +196,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 +208,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 +323,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.