ws-docs: docs/guide/README.md (installing, inputs, detection, errors, options, saving, converting, hosts); LÖVE example: SVG tile, GIF played as a video with a per-update decode budget

This commit is contained in:
4DBug committed 2026-10-31 13:09:04 -05:00
1 parent cdcbd76b9e
commit 001e746305
2 files changed
+398 -2

No files matched your search

+344
View File
@@ -0,0 +1,344 @@
# formats-luau guide
formats-luau reads, writes and converts file formats in pure Luau. One source tree runs on Roblox, on LuaJIT / LÖVE
and in the luau CLI. Each format maps onto the standard type of its category, so a PNG and a WebP both load as the
same `Image`, and every audio format opens as the same streaming `Decoder`.
This page covers what every category shares: installing, inputs, detection, errors, options, saving and converting,
and the host notes. Each standard type has its own page:
| Page | Type(s) | Formats |
|---|---|---|
| [Images](image.md) | `Image`, `Frame` (animation) | PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR |
| [Audio](audio.md) | `Audio`, `Decoder` | WAV, FLAC, MP3, Ogg Vorbis, Opus, AAC, M4A, AIFF, AU, CAF, VOC |
| [Music](music.md) | `Module`, `Midi` | MOD, S3M, XM, IT, MIDI, SoundFont 2 |
| [Video](video.md) | `VideoDecoder`, `Demuxer`, `Track`, `Packet` | MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Y4M, H.264 |
| [3D scenes](scene.md) | `Scene`, `Voxels` | glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX |
| [CAD](cad.md) | `Cad` (STEP) | STEP (B-rep through a plug-in) |
| [Fonts](font.md) | `Font` | TTF / OTF, WOFF, WOFF2, BMFont |
| [Archives](archive.md) | `Archive` | zip, tar, gzip, 7z, xz, zstd, Brotli, bzip2 |
| [Data](data.md) | plain values, `XmlNode`, `Date` | JSON, XML, YAML, TOML, CSV, INI, MessagePack, CBOR, plist |
| [Vector](vector.md) | `Vector` | SVG |
| [Layered images](layered.md) | `Layered` | PSD, Aseprite |
| [Tile maps](tilemap.md) | `TileMap` | Tiled TMX / TMJ |
| [Subtitles](subtitles.md) | `Subtitles`, `Cue` | SRT, WebVTT, ASS / SSA |
| [Playlists](playlist.md) | `Playlist` | M3U / M3U8 (HLS), PLS, XSPF |
[Recipes](recipes.md) has short task-oriented snippets. [FORMATS.md](../FORMATS.md) lists every format with its
read and write capabilities, and [API.md](../API.md) is the API reference.
```luau
local img = assert(F.load(pngBytes)) -- PNG -> Image
local small = assert(F.ops.image.resize(img, 32, 24, "lanczos"))
local webp = assert(F.save(small, nil, { format = "webp" })) -- Image -> WebP bytes (a buffer)
assert(F.detect(webp) == "webp")
```
Every snippet in this guide runs as a test under both runtimes (`bash tools/test.sh`). A snippet sees the library
as `F`, and its input files as variables such as `pngBytes` (a buffer) or `srtText` (a string).
## Installing
**Roblox (Rojo).** Build the Roblox tree, then let Rojo turn it into a model or sync it into Studio:
```sh
python3 -I tools/build.py roblox # writes build/roblox/Formats (requires become instance paths)
rojo build -o Formats.rbxm # default.project.json mounts build/roblox/Formats; or: rojo serve
```
Put the `Formats` ModuleScript somewhere both client and server can see it, for example ReplicatedStorage:
<!-- doc:display needs Roblox -->
```luau
local F = require(game:GetService("ReplicatedStorage").Formats)
```
Roblox has no file system: pass buffers or strings, for example from `HttpService:GetAsync` or a `buffer` you built.
**LuaJIT and LÖVE.** Build the Lua 5.1 tree:
```sh
python3 -I tools/build.py luajit # writes build/luajit/formats/ (plain Lua 5.1 + the LuaJIT FFI)
```
Then either copy `build/luajit/formats` into your game, or put the build on `package.path`:
<!-- doc:display plain LuaJIT code -->
```lua
package.path = "build/luajit/?.lua;build/luajit/?/init.lua;" .. package.path
local F = require("formats")
```
The library carries its own copy of the Luau standard library pieces it uses (`buffer`, `bit32`, `utf8`, ...).
Your own code gets them as globals with `require("formats._compat").install()`, which is useful when you read the
pixel buffers yourself. [examples/love](../../examples/love/main.lua) is a runnable LÖVE example.
**luau CLI.** The repository's `.luaurc` defines the alias `@formats` for `src/Formats`, so a script run from the
repository root can require the sources directly. The CLI has no file system.
<!-- doc:display a top-level require -->
```luau
local F = require("@formats")
```
The runnable programs in [examples/](../../examples) work this way: `luau examples/image.luau`.
## Inputs
Every `load`, `open` and `detect` takes a source `src`:
| `src` | Meaning |
|---|---|
| `buffer` | the file's bytes |
| `string` | the file's bytes; on hosts with a file system, a path when the string looks like one (under 4 KB, no NUL or newline) and the file exists |
| path | a file name (LuaJIT, LÖVE): read through `io.open`, or `love.filesystem` first under LÖVE |
`opts.path = true` forces a path and `opts.data = true` forces bytes. A string is copied into a buffer once.
```luau
local a = assert(F.load(pngBytes)) -- a buffer
local b = assert(F.load(buffer.tostring(pngBytes))) -- the same bytes as a string
assert(a.width == b.width and a.height == b.height)
```
<!-- doc:files -->
```luau
local img = assert(F.load("assets/photo.png")) -- a path (LuaJIT / LÖVE)
assert(img.width == 64)
local data = assert(F.host.readFile("assets/photo.png")) -- or read the bytes yourself
assert(buffer.len(data) > 0)
```
## Detection
`F.load` finds the format by content first: each format scores the first bytes (its magic numbers). It falls back
to the extension of the path or of `opts.name`. `opts.format` (a format name or an extension) skips detection, and
`opts.category` (`"image"`, `"audio"`, ...) limits it, which is what the category facades `F.image`, `F.audio`, ...
do.
```luau
assert(F.detect(pngBytes) == "png")
assert(F.detect(gifBytes) == "gif")
assert(F.detect("a,b\n1,2\n", { name = "table.csv" }) == "csv") -- text without magic: the name decides
local img = assert(F.image.load(jpegBytes)) -- only image formats are tried
local same = assert(F.load(jpegBytes, { format = "jpg" })) -- no detection at all
assert(img.width == same.width)
```
`F.formats(category?)` lists the formats and their capabilities without loading any format code.
`F.format(name)` returns the format module itself, for format-specific extras.
```luau
local writable = {}
for _, info in F.formats("image") do
if info.caps.encode then
table.insert(writable, info.name)
end
end
assert(table.find(writable, "png") and table.find(writable, "webp"))
local png = assert(F.format("png"))
assert(png.name == "png" and png.category == "image")
```
## Errors
Nothing in the library throws on bad data or bad arguments. A failing call returns `nil, err`:
| Field | Meaning |
|---|---|
| `err.code` | one of the `F.Err` codes below |
| `err.message` | what went wrong, in words |
| `err.offset` | the byte offset in the input, when known |
| `err.format` | the format that failed, when known |
`tostring(err)` prints all of it, for example `png: CORRUPT at 0x21: bad filter type 7`.
| Code | Meaning |
|---|---|
| `TRUNCATED` | the data ends early |
| `CORRUPT` | the data is malformed |
| `CHECKSUM` | a CRC, Adler or hash does not match |
| `UNSUPPORTED` | valid data using a feature the library does not implement, or a format without an encoder |
| `UNKNOWN_FORMAT` | no format recognised the data, name or extension |
| `LIMIT` | a size limit was exceeded (`opts.maxPixels`, `opts.maxBytes`, ...) |
| `ARG` | a bad argument |
| `IO` | reading or writing a file failed, or the host has no file system |
```luau
local img, err = F.load("definitely not an image")
assert(img == nil and err.code == F.Err.UNKNOWN_FORMAT)
local cut = buffer.create(40)
buffer.copy(cut, 0, pngBytes, 0, 40) -- the first 40 bytes of a PNG
local bad, perr = F.load(cut)
assert(bad == nil and perr.format == "png")
print(tostring(perr)) -- "png: TRUNCATED ..."
local ok, serr = F.save(F.Types.Image.new(4, 4), nil, { format = "ttf" })
assert(ok == nil and serr.code == F.Err.UNKNOWN_FORMAT) -- no image format called ttf
```
`assert(F.load(src))` turns an error into a thrown error with the message, which is handy in scripts and tests.
## Options
Every call takes an optional `opts` table. The options every format understands:
| Option | Meaning |
|---|---|
| `format` | the format to decode as or encode to (a name such as `"jpeg"`, or an extension such as `"jpg"`) |
| `category` | limit detection to one category |
| `name` | a file name hint for detection, and for formats that store names |
| `path` / `data` | force `src` to be a path / bytes |
| `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.
```luau
local img = assert(F.load(pngBytes))
local q90 = assert(F.save(img, nil, { format = "jpeg", quality = 90 }))
local q30 = assert(F.save(img, nil, { format = "jpeg", quality = 30 }))
assert(buffer.len(q30) < buffer.len(q90))
local big, err = F.load(pngBytes, { maxPixels = 100 })
assert(big == nil and err.code == F.Err.LIMIT)
```
## Saving
`F.save(value, dest?, opts?)` encodes any standard value. The format comes from, in order: `opts.format`, the
extension of `dest`, then the format the value was loaded from (`value.meta.source.format`).
| Call | Returns |
|---|---|
| `F.save(value, nil, opts)` | a `buffer` |
| `F.save(value, "out.png", opts)` | `true` after writing the file (hosts with a file system) |
| `F.saveString(value, opts)` | the encoded bytes as a `string` |
```luau
local img = assert(F.load(gifBytes))
local again = assert(F.save(img)) -- no format given: GIF again (the source format)
assert(F.detect(again) == "gif")
local qoi = assert(F.save(img, nil, { format = "qoi" }))
local s = assert(F.saveString(img, { format = "png" }))
assert(type(s) == "string" and string.sub(s, 2, 4) == "PNG")
local _, err = F.save(F.load(flacBytes), nil, { format = "aac" }) -- AAC is read-only
assert(err.code == F.Err.UNSUPPORTED)
print(tostring(err)) -- names a writable format to try instead
local _ = qoi
```
<!-- doc:files -->
```luau
local img = assert(F.load("assets/photo.png"))
assert(F.save(img, "out/photo.webp")) -- the extension picks WebP
assert(F.save(img, "out/photo.bin", { format = "bmp" })) -- opts.format wins over the extension
assert(F.detect("out/photo.bin") == "bmp")
```
Values you build yourself have no source format, so pass `opts.format` or a destination with an extension:
```luau
local img = F.Types.Image.new(2, 2) -- 2 x 2 rgba8, all zero
local _, err = F.save(img)
assert(err.code == F.Err.ARG) -- "save: no format ..."
assert(F.save(img, nil, { format = "png" }))
```
## Converting
`F.convert(src, format, opts?)` is a load followed by a save. `opts` go to both, and `opts.out = path` writes a
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 }))
assert(F.detect(webp) == "webp" and F.detect(mp3) == "mp3")
```
<!-- doc:files -->
```luau
assert(F.convert("assets/tone.wav", "flac", { out = "out/tone.flac" }))
local a = assert(F.load("out/tone.flac"))
assert(a.sampleRate == 44100 and a.channels == 2)
```
Conversions cross categories where it makes sense: an animated GIF converts to a video (`F.convert(gifBytes,
"avi")`), a music module renders to audio, and a single-stream archive such as `.tar.gz` loads as the archive inside.
The type pages show these.
## Hosts
`F.host.name` is `"roblox"`, `"love"`, `"luajit"` or `"luau"`, detected when the library loads.
| Host | Files | Bridges |
|---|---|---|
| Roblox | none: pass buffers or strings | `F.host.toEditableImage(img)` |
| LÖVE | `love.filesystem` (the game folder and the save directory), then `io` | `F.host.toImageData(img)`, `F.host.fromImageData(imageData)`, `F.host.toSoundData(audioOrDecoder)` |
| LuaJIT | `io.open` | |
| luau CLI | none | |
```luau
assert(table.find({ "roblox", "love", "luajit", "luau" }, F.host.name))
if not F.host.hasFiles then
local _, err = F.host.readFile("photo.png")
assert(err.code == F.Err.IO)
end
```
Every host has `F.host.readFile(path)`, `F.host.writeFile(path, buffer)` and `F.host.exists(path)`; without a file
system they fail with `IO`. Under LÖVE, relative paths are written to the save directory.
**Roblox.** `toEditableImage` needs an `rgba8` image (convert others with `F.ops.image.convert(img, "rgba8")`) and
the EditableImage API enabled for the experience:
<!-- doc:display needs Roblox -->
```luau
local img = assert(F.image.load(pngBytes))
local editable = assert(F.host.toEditableImage(img))
local label = Instance.new("ImageLabel")
label.Size = UDim2.fromOffset(img.width, img.height)
label.ImageContent = Content.fromObject(editable)
label.Parent = script.Parent -- a ScreenGui
```
**LÖVE.** `toImageData` copies an `rgba8` image into an `ImageData` (through the FFI), `fromImageData` copies back,
and `toSoundData` turns an `Audio` or a `Decoder` (read to its end) into 16-bit `SoundData`:
<!-- doc:display needs LÖVE -->
```lua
local F = require("formats")
local img = assert(F.load("sprite.png")) -- love.filesystem path
local texture = love.graphics.newImage(F.host.toImageData(img))
local music = love.audio.newSource(F.host.toSoundData(F.audio.open("music.ogg")), "static")
music:play()
local shot = F.host.fromImageData(love.graphics.newCanvas(64, 64):newImageData())
F.save(shot, "shot.png") -- to the save directory
```
**LuaJIT trace limits.** When the library loads on LuaJIT it raises the JIT's trace limits
(`jit.opt.start("maxtrace=8000", "maxmcode=65536")`). The big decoders (Opus CELT, VP8, H.264, MPEG-1) outgrow the
defaults and fall back to the interpreter, which is 2x or more slower. Set `FORMATS_NO_JIT_TUNE` before the first
`require` to leave the JIT settings alone:
<!-- doc:display plain LuaJIT code -->
```lua
FORMATS_NO_JIT_TUNE = true -- a global, read once when the library loads
local F = require("formats")
```
## Conventions
- **Values.** Every top-level value has a `kind` (`"image"`, `"audio"`, `"scene"`, ...), so `F.save` knows its
category, and a `meta` table. `meta.source.format` records the format it was loaded from.
- **Constructors.** `F.Types` has constructors for values you build yourself: `F.Types.Image.new(w, h, format?)`,
`F.Types.Audio.new(rate, channels, frames)`, `F.Types.Scene.new()`, `F.Types.Vector.new(w, h)`,
`F.Types.Layered.new(w, h)`, `F.Types.Subtitles.new()`, `F.Types.Midi.new(division?)`, `F.Types.TileMap.new(...)`.
- **Buffers.** Buffers are tightly packed: image rows top to bottom with no padding, audio samples interleaved,
3D accessors without stride. Indices into lists (nodes, meshes, materials, frames) are 1-based; byte offsets and
pixel coordinates are 0-based.
- **Times.** Times and durations are in seconds, except container packet timestamps (ticks of the track's
timescale) and MIDI events (ticks).
- **Editing.** `F.ops.image`, `F.ops.audio`, `F.ops.mesh`, `F.ops.layers` and `F.ops.vector` hold the editing
functions. They return new values unless they say they edit in place, and they return `nil, err` for bad
arguments.
+54 -2
View File
@@ -3,8 +3,9 @@
-- FORMATS_SMOKE=1 xvfb-run love examples/love (headless: checks, a screenshot, then quits; exit code 1 on -- FORMATS_SMOKE=1 xvfb-run love examples/love (headless: checks, a screenshot, then quits; exit code 1 on
-- failure) -- failure)
-- It decodes repo fixtures (PNG suite, a MagicaVoxel model, a glTF box), round-trips an image through PNG / JPEG / -- It decodes repo fixtures (PNG suite, a MagicaVoxel model, a glTF box), round-trips an image through PNG / JPEG /
-- WebP / GIF / QOI / BMP and a tone through FLAC / WAV / Vorbis / MP3, and shows them with love.graphics / love.audio -- WebP / GIF / QOI / BMP and a tone through FLAC / WAV / Vorbis / MP3, rasterizes an SVG, plays an animated GIF as a
-- through the host's toImageData / toSoundData. -- video (decoded in love.update with a time budget per frame), and shows them with love.graphics / love.audio through
-- the host's toImageData / toSoundData. docs/guide/README.md explains the API.
local root = (love.filesystem.getSource():gsub("/examples/love/?$", "")) local root = (love.filesystem.getSource():gsub("/examples/love/?$", ""))
package.path = root .. "/build/luajit/?.lua;" .. root .. "/build/luajit/?/init.lua;" .. package.path package.path = root .. "/build/luajit/?.lua;" .. root .. "/build/luajit/?/init.lua;" .. package.path
local F = require("formats") local F = require("formats")
@@ -28,6 +29,8 @@ end
local function errstr(e) return e and (type(e) == "table" and (tostring(e.code) .. ": " .. tostring(e.message)) or tostring(e)) or "" end local function errstr(e) return e and (type(e) == "table" and (tostring(e.code) .. ": " .. tostring(e.message)) or tostring(e)) or "" end
local tiles, sound, voxelInfo = {}, nil, "" local tiles, sound, voxelInfo = {}, nil, ""
local video, videoImage, videoClock, videoFrames = nil, nil, 0, 0 -- the animated GIF, played as a video
local BUDGET = 0.004 -- seconds of decoding per love.update
local function tile(name, img) local function tile(name, img)
local data = F.host.toImageData(img) local data = F.host.toImageData(img)
@@ -62,6 +65,31 @@ function love.load()
end end
end end
-- an SVG, rasterized to an rgba8 Image
local svg = [[<svg xmlns="http://www.w3.org/2000/svg" width="96" height="96" viewBox="0 0 24 24">
<circle cx="12" cy="12" r="10" fill="#f4b400" stroke="#333" stroke-width="1"/>
<path d="M7 14 Q12 19 17 14" fill="none" stroke="#333" stroke-width="1.5" stroke-linecap="round"/>
<circle cx="9" cy="9.5" r="1.5" fill="#333"/><circle cx="15" cy="9.5" r="1.5" fill="#333"/></svg>]]
local vec, sve = F.load(svg, { format = "svg" })
local icon, re = vec and F.ops.vector.rasterize(vec, 96, 96)
if check(icon ~= nil and icon.width == 96, "svg rasterize", errstr(sve or re)) then tile("svg", icon) end
-- an animated GIF made from frames, reopened as a video and played in love.update
local frameList = {}
for i = 0, 7 do
local f = F.ops.image.new(48, 48)
F.ops.image.fill(f, 30, 30, 40, 255)
local block = F.ops.image.new(12, 12)
F.ops.image.fill(block, 255, 120 + i * 16, 40, 255)
F.ops.image.blit(f, block, i * 5, 18)
frameList[#frameList + 1] = f
end
local anim = F.ops.image.fromFrames(frameList, 0.08)
local gif, ge2 = anim and F.save(anim, nil, { format = "gif" })
local ve2
video, ve2 = gif and F.video.open(gif)
check(video ~= nil and video.frames == 8, "gif as video", errstr(ge2 or ve2))
-- a voxel model: decode, mesh it, report -- a voxel model: decode, mesh it, report
local vox, ve = F.load(root .. "/tests/fixtures/vox/chr_knight.vox") local vox, ve = F.load(root .. "/tests/fixtures/vox/chr_knight.vox")
if check(vox ~= nil and vox.kind == "scene", "vox fixture", errstr(ve)) then if check(vox ~= nil and vox.kind == "scene", "vox fixture", errstr(ve)) then
@@ -95,6 +123,25 @@ function love.load()
end end
end end
-- decode the next video frame when it is due, spending at most BUDGET seconds per update (the game-loop pattern:
-- a big frame never stalls the game for long, the video just runs late)
function love.update(dt)
if not video then return end
videoClock = videoClock + dt
local t0 = love.timer.getTime()
while love.timer.getTime() - t0 < BUDGET do
local f = video:nextFrame()
if not f then video:reset() break end -- loop
if f.pts + f.duration >= videoClock or f.index == video.frames then
local data = F.host.toImageData(video:toRGBA(f))
if videoImage then videoImage:replacePixels(data) else videoImage = love.graphics.newImage(data) end
videoFrames = videoFrames + 1
if f.index == video.frames then videoClock = 0 end
break
end
end
end
local frames = 0 local frames = 0
function love.draw() function love.draw()
love.graphics.clear(0.12, 0.12, 0.14) love.graphics.clear(0.12, 0.12, 0.14)
@@ -106,11 +153,16 @@ function love.draw()
if x > 680 then x, y = 8, y + 124 end if x > 680 then x, y = 8, y + 124 end
end end
love.graphics.print(voxelInfo, 8, 300) love.graphics.print(voxelInfo, 8, 300)
if videoImage then
love.graphics.draw(videoImage, 228, 132, 0, 2)
love.graphics.print("gif as video", 228, 232)
end
for i, line in ipairs(results) do for i, line in ipairs(results) do
love.graphics.print(line, 8, 320 + i * 14) love.graphics.print(line, 8, 320 + i * 14)
end end
frames = frames + 1 frames = frames + 1
if SMOKE and frames == 3 then if SMOKE and frames == 3 then
check(videoFrames > 0, "video frames shown", videoFrames)
love.graphics.captureScreenshot(function(data) love.graphics.captureScreenshot(function(data)
data:encode("png", "formats_smoke.png") data:encode("png", "formats_smoke.png")
print("screenshot: " .. love.filesystem.getSaveDirectory() .. "/formats_smoke.png") print("screenshot: " .. love.filesystem.getSaveDirectory() .. "/formats_smoke.png")