tools/lint_rules.py DOCS: the README and STYLE layout blocks must name every codecs/<domain>/<Name>, containers/ and core/ module; README's format counts must match docs/FORMATS.md; the guide index must link every guide page. STYLE's 'use what exists' table lists the wave-3 shared modules.
163 lines
11 KiB
Markdown
163 lines
11 KiB
Markdown
# formats-luau
|
|
|
|
Read, write and convert file formats in pure Luau, from one source tree that runs on **Roblox** (Luau, native code
|
|
generation) and on **LuaJIT / LÖVE** (through `tools/build.py`). Every format of a category maps onto one standard type
|
|
(`src/Formats/Types.luau`): a PNG and a WebP both load as an `Image`, every audio format opens as the same streaming
|
|
`Decoder`, every model format loads as a `Scene`.
|
|
|
|
174 formats: images (25), audio (21), video (11), 3D models (32), CAD (1), fonts (11), archives (31), data (11),
|
|
vector graphics and tile maps (2), layered images (3), subtitles (3), music (20) and playlists (3). See
|
|
[docs/FORMATS.md](docs/FORMATS.md) (generated from the code) for the list and each format's capabilities,
|
|
[docs/API.md](docs/API.md) for the whole API, and the guide ([docs/guide/README.md](docs/guide/README.md)) for
|
|
walkthroughs. `tools/lint.sh` checks these counts against the registry.
|
|
|
|
```luau
|
|
local F = require(Formats) -- LuaJIT: require("formats"); luau CLI: require("@formats")
|
|
local img, err = F.load(src) -- src: buffer | string | path (hosts with files)
|
|
if not img then print(tostring(err)) end -- errors are values: "png: CORRUPT at 0x21: bad filter type 7"
|
|
local buf = F.save(img, nil, { format = "webp" }) -- a buffer; F.save(img, "out.webp") writes a file
|
|
local out = F.convert(src, "png", { level = 9 })
|
|
local small = F.ops.image.resize(img, 64, 64, "lanczos")
|
|
```
|
|
|
|
Nothing throws on bad data or bad arguments: every call returns `nil, err` (`err.code` is one of the `F.Err` codes).
|
|
|
|
## Install
|
|
|
|
**Roblox (Rojo).** `python3 -I tools/build.py roblox` writes `build/roblox/Formats` (requires turned into instance
|
|
paths); `default.project.json` mounts it, so `rojo build -o Formats.rbxm` (or `rojo serve`) gives a `Formats`
|
|
ModuleScript to put in ReplicatedStorage: `local F = require(game.ReplicatedStorage.Formats)`. There is no file system:
|
|
pass buffers or strings. `F.host.toEditableImage(img)` makes an EditableImage, `F.host.toEditableMesh(prim, page)` an
|
|
EditableMesh (a merged triangle primitive split by `F.host.meshPages`).
|
|
|
|
**LuaJIT / LÖVE.** `python3 -I tools/build.py luajit` writes `build/luajit/formats/` (Lua 5.1 + LuaJIT FFI; the Luau
|
|
standard library pieces come from `formats/_compat.lua`). Copy the `formats` folder into the game (or put
|
|
`build/luajit/?.lua;build/luajit/?/init.lua` on `package.path`) and `local F = require("formats")`. Files load by path
|
|
(`love.filesystem` under LÖVE, else `io.open`); `F.host.toImageData(img)`, `F.host.fromImageData(imageData)` and
|
|
`F.host.toSoundData(audioOrDecoder)` bridge to LÖVE. `examples/love` is a runnable example and smoke test
|
|
(`love examples/love` from the repo root after building).
|
|
|
|
**luau CLI.** `luau` with the `.luaurc` alias `@formats` runs `src/` directly (no file system).
|
|
|
|
## Quick start
|
|
|
|
```luau
|
|
-- images: PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR, EXR, DDS, KTX, PCX, ... -> Image
|
|
local img = F.image.load(pngBytes)
|
|
print(img.width, img.height, #(img.frames or {}), img.loops) -- animations: frames; loops = play count, 0 forever
|
|
local jpg = F.save(img, nil, { format = "jpeg", quality = 85 })
|
|
|
|
-- audio: WAV, FLAC, MP3 / MP2, Ogg Vorbis, Opus, AAC, M4A, AIFF, AU, CAF, VOC, WavPack, APE, TTA, Musepack, AC-3,
|
|
-- QOA, ADPCM (ADX, VAG, BRSTM, ...) -> streaming Decoder or Audio
|
|
local dec = F.audio.open(flacBytes) -- dec:read(n) -> interleaved f32 buffer, frames; dec:seek(s)
|
|
local song = F.audio.load(mp3Bytes) -- Audio { sampleRate, channels, frames, samples, tags }
|
|
local mono = F.ops.audio.downmix(song, 1) -- channels are in WAVE order; tags keys are lower case
|
|
local opus = F.save(F.ops.audio.resample(mono, 48000), nil, { format = "opus", bitrate = 64000 })
|
|
|
|
-- video: MP4 / MOV, MKV / WebM, AVI, MPEG-TS / PS, Ogg Theora, FLV, FLI, Smacker, Y4M (+ animated images)
|
|
-- -> VideoDecoder
|
|
local v = F.video.open(mp4Bytes) -- v:nextFrame() -> frame (image yuv420p or rgba8, pts)
|
|
|
|
-- models: glTF / GLB (+ Draco), OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX, 3DS, MS3D, LWO, .x, IQM, B3D,
|
|
-- PMX / PMD, VRML, X3D, LDraw, MD2 / MD3 / MDL / MD5, BSP, SMD, Roblox (rbxm / rbxmx / .mesh),
|
|
-- Minecraft (.schem, .mca), Qubicle -> Scene
|
|
local scene = F.model.load(glbBytes)
|
|
local prim = F.ops.mesh.merge(scene) -- one triangle primitive in world space
|
|
|
|
-- CAD, fonts, archives, data, vector, tile maps, layered, subtitles, music, playlists
|
|
local font = F.font.load(ttfBytes) -- TTF / OTF, WOFF / WOFF2, BMFont, bitmap fonts: outlines, kerning
|
|
local zip = F.archive.load(zipBytes) -- zip, tar, 7z, gzip, cab, iso, ...; saves zip / tar / gzip
|
|
local t = F.data.load('{"a": [1, 2]}', { format = "json" }) -- JSON, XML, YAML, TOML, CSV, INI, plist, CBOR, NBT, ...
|
|
local icon = F.ops.vector.rasterize(F.vector.load(svgText), 64, 64) -- SVG; Tiled maps load as a TileMap
|
|
local flat = F.ops.layers.flatten(F.layered.load(psdBytes)) -- PSD, Aseprite, OpenRaster
|
|
local subs = F.subtitle.load(srtText) -- SRT, WebVTT, ASS / SSA
|
|
local tune = F.music.load(modBytes) -- MOD / S3M / XM / IT / AHX / MIDI, ...: rendered to audio
|
|
local step = F.cad.load(stepText) -- STEP entity graph (B-rep through a plug-in)
|
|
local list = F.playlist.load(m3uText) -- M3U / M3U8, PLS, XSPF
|
|
```
|
|
|
|
## The API in short
|
|
|
|
`F.load`, `F.open`, `F.save`, `F.saveString`, `F.convert`, `F.detect`, `F.formats`, `F.format(name)`; the category
|
|
facades `F.image`, `F.audio`, `F.video`, `F.model`, `F.cad`, `F.font`, `F.archive`, `F.data`, `F.vector`,
|
|
`F.layered`, `F.subtitle`, `F.music`, `F.playlist`; editing in `F.ops.image`, `F.ops.mesh`, `F.ops.layers`,
|
|
`F.ops.audio`, `F.ops.music` (also `F.music.new` / `addPattern` / `setCell` / ...), `F.ops.vector.rasterize`; `F.host`, `F.plugins`, `F.Err`, `F.Types`. Options and the hooks the api
|
|
hands to formats (decodeImage / encodeImage / openAudio / plugins): [docs/API.md](docs/API.md).
|
|
|
|
## Host notes
|
|
|
|
| Host | Files | Bridges |
|
|
|---|---|---|
|
|
| Roblox | none: pass buffers / strings | `F.host.toEditableImage(img)`, `meshPages` / `toEditableMesh(prim, page)` |
|
|
| LÖVE | `love.filesystem`, then `io` | `toImageData`, `fromImageData`, `toSoundData` |
|
|
| LuaJIT | `io.open` | |
|
|
| luau CLI | none | |
|
|
|
|
- **Paths.** A string is read as a path only on hosts with files, when it looks like one (short, no NUL / newline)
|
|
and the file exists, or when `opts.path = true`; `opts.data = true` forces bytes. Files next to a loaded model
|
|
(OBJ `.mtl`, glTF `.bin` and textures) are found through `opts.resolve`, which the api fills in for paths.
|
|
- **LuaJIT trace tuning.** On load the host raises LuaJIT'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 (2x or more slower). Set `_G.FORMATS_NO_JIT_TUNE = true` before requiring the library to leave the
|
|
JIT settings alone.
|
|
|
|
## Layout
|
|
|
|
```
|
|
src/Formats/
|
|
init.luau Registry.luau (generated) api: F.*
|
|
ops/ editing on the standard types (ImageOps, MeshOps, LayerOps, AudioOps, ...)
|
|
<category>/<fmt>/ formats: only what is specific to the format (parsing, mapping, writing)
|
|
containers/ Archive AudioWrap Avi Chunks Cpio Demux Ebml Fat Iso9660 IsoBmff MacFile
|
|
MpegEs MpegPs MpegTs Ogg Riff Tar Zip
|
|
codecs/compress/ Brotli Bzip2 Deflate Explode Lz4 Lzh Lzma Lzw Lzx PackBits Quantum
|
|
UnixCompress Xxh32 Zstd
|
|
codecs/entropy/ Huffman RangeCoder
|
|
codecs/image/ Bcn Blend Dct Etc Half Jpeg Pixels Quantize Raster Texel Texture Vp8 Vp8L Yuv
|
|
codecs/audio/ Aac Ac3 Adpcm Alac Ape ApeTag Flac Hively Mdct MidiRender Mpa (MP1-3)
|
|
Musepack Opus Pcm Qoa Resample SoundFont Stream Tracker Tta Vorbis
|
|
VorbisComment WavPack
|
|
codecs/video/ Dsp H263 H264 Legacy (FLI, Cinepak, MSV1, QT RLE, SMC, Smacker) Mpeg1 Mpeg2
|
|
Theora Video (the codec registry)
|
|
codecs/text/ Json Nbt Text Url Xml
|
|
codecs/font/ Bitmap Cff GlyphNames TrueType
|
|
codecs/model/ Draco Mat4 MeshFlatten Minecraft Polygon Rbx Rig Sampler Vrml
|
|
host/ runtime adapters (only the api uses them)
|
|
Types.luau the standard types + constructors
|
|
core/ Adler32 Base64 Bits Bytes Crc16 Crc32 Err Input Md5 Sniff
|
|
compat/luajit.lua tools/ tests/ (T.luau, <category>/<fmt>.luau, codecs/, containers/, gen/) docs/ licenses/
|
|
examples/love/
|
|
```
|
|
|
|
How the layers fit, the format contract, and what belongs in a format folder: [docs/STYLE.md](docs/STYLE.md).
|
|
|
|
## Development
|
|
|
|
```sh
|
|
bash tools/test.sh # fixtures, registry, build, every test under luau --codegen -O2 and LuaJIT, lint
|
|
bash tools/test.sh png # one test (both runtimes), no lint
|
|
bash tools/lint.sh # globals, types, headers, requires, native-throw, layers, deps, contract, DUP, docs
|
|
bash tools/bench.sh # throughput on both runtimes (pin it: taskset -c 2 bash tools/bench.sh)
|
|
python3 -I tools/build.py # build/roblox + build/luajit
|
|
python3 -I tools/gen_registry.py # src/Formats/Registry.luau + docs/FORMATS.md from the format folders
|
|
python3 -I tools/fixtures.py # tests/gen/*.luau from tools/fixtures/*.py (reference tools through nix)
|
|
python3 -I tools/move.py codecs/image/Foo=codecs/video/Foo # move a module, rewriting every reference
|
|
```
|
|
|
|
Tools: python3, and through nix: `luau` (+ `luau-analyze`), `luajit`, `darklua` 0.19, `rojo` (each script finds them
|
|
on PATH or runs them with `nix shell nixpkgs#<tool>`); the fixture generators run ffmpeg, ImageMagick, libwebp, flac,
|
|
lame, opus-tools, vorbis-tools, assimp, fontTools and others through nix.
|
|
|
|
The type checker's diagnostics may only go down: `tools/lint.sh` fails when their count passes
|
|
`tools/lint_types_baseline.txt` (`LINT_TYPES=1` lists them, `LINT_TYPES_UPDATE=1` lowers the baseline).
|
|
|
|
## Performance
|
|
|
|
`tools/bench.luau` prints throughput per codec on both runtimes; run it pinned to one core
|
|
(`taskset -c 2 bash tools/bench.sh`: on hybrid CPUs the core types differ 2x). LuaJIT numbers vary between runs (its
|
|
trace recorder is randomised).
|
|
|
|
## Licence
|
|
|
|
See [licenses/NOTICE.md](licenses/NOTICE.md).
|