374 lines
17 KiB
Markdown
374 lines
17 KiB
Markdown
# 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 |
|
|
| [Roblox](roblox.md) | `RbxTree` (`F.Rbx`), `Scene` | rbxm / rbxl, rbxmx / rbxlx, Roblox .mesh |
|
|
| [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 |
|
|
| [Minecraft and voxels](voxel.md) | typed values, `Scene` + `Voxels` | NBT, SNBT, `.schem` / `.schematic` / `.litematic`, Anvil `.mca`, Qubicle `.qb` |
|
|
| [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` (bits per second) for MP3 and Opus. 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 = 128000 }))
|
|
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)
|
|
```
|
|
|
|
Some conversions cross categories: an animated GIF converts to a video (`F.convert(gifBytes, "avi")`), and a
|
|
single-stream archive such as `.tar.gz` loads as the archive inside. A music file renders to audio through
|
|
`F.save(song:render(), nil, { format = "wav" })` ([Music](music.md)). 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)`, `F.host.meshPages(prim)` / `F.host.toEditableMesh(prim, page)` |
|
|
| 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
|
|
```
|
|
|
|
Meshes: one EditableMesh holds about 20k triangles and 60k vertices, and a client has only 8 growable ones at a time.
|
|
`F.host.meshPages(prim, opts?)` splits a triangle primitive (`F.ops.mesh.merge` output) into runs that fit;
|
|
`F.host.toEditableMesh(prim, page, opts?)` builds one page (positions relative to the returned centre, normals, uvs,
|
|
sRGB vertex colours from the linear `COLOR_0`) and returns `editableMesh, centre`. Freeze each page into what you keep
|
|
before building the next. Options: `scale` (number or `{ x, y, z }`), `doubleSided` (back faces, counted by
|
|
`meshPages` too), `texCoord`, `flipV`, `normals` / `uvs` / `colors = false`, `yield` (called every `yieldEvery` = 2000
|
|
triangles), `editableMesh` (append to an existing mesh). `F.host.pageData(prim, page, opts?)` is the same page as flat
|
|
number arrays, without engine calls. Roblox is y up like glTF: put z-up scenes (STL, VOX, CAD) through
|
|
`F.ops.mesh.setUp(scene, "y")` before merging.
|
|
|
|
<!-- doc:display needs Roblox -->
|
|
```luau
|
|
local AssetService = game:GetService("AssetService")
|
|
local scene = assert(F.model.load(glbBytes))
|
|
for _, prim in assert(F.ops.mesh.merge(scene, { byMaterial = true })) do
|
|
for _, page in assert(F.host.meshPages(prim)) do
|
|
local em, centre = assert(F.host.toEditableMesh(prim, page, { scale = 1 / 0.28 })) -- metres -> studs
|
|
local fixed = AssetService:CreateEditableMeshAsync(Content.fromObject(em), { FixedSize = true })
|
|
em:Destroy() -- frees the growable slot
|
|
local part = AssetService:CreateMeshPartAsync(Content.fromObject(fixed))
|
|
part.Position = Vector3.new(centre[1], centre[2], centre[3])
|
|
part.Anchored = true
|
|
part.Parent = workspace
|
|
end
|
|
end
|
|
```
|
|
|
|
**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.
|