2026-10-31 13:45:55 -05:00

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.

About 76 formats across images, audio, video, 3D models, CAD, fonts, archives, data, vector graphics, layered images, subtitles, music and playlists: see docs/FORMATS.md (generated from the code) for the list and each format's capabilities, docs/API.md for the whole API, and the guide (docs/guide/README.md) for walkthroughs.

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.

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

-- images: PNG / APNG, JPEG, WebP, GIF, BMP, TGA, QOI, TIFF, ICO, PNM, HDR -> Image (rgba8 pixels in a buffer)
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 -> 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, Y4M (+ animated images) -> VideoDecoder
local v = F.video.open(mp4Bytes)                   -- v:nextFrame() -> frame (image yuv420p or rgba8, pts)

-- models: glTF / GLB, OBJ, STL, PLY, FBX, Collada, 3MF, USDA, OFF, VOX -> Scene
local scene = F.model.load(glbBytes)
local prim = F.ops.mesh.merge(scene)               -- one triangle primitive in world space

-- fonts, archives, data, vector, layered, subtitles, music, playlists
local font = F.font.load(ttfBytes)                 -- outlines, metrics, kerning
local zip = F.archive.load(zipBytes)               -- entries; F.archive.save writes zip / tar / gzip
local t = F.data.load('{"a": [1, 2]}', { format = "json" })   -- JSON, XML, YAML, TOML, CSV, INI, plist, msgpack, CBOR
local icon = F.ops.vector.rasterize(F.vector.load(svgText), 64, 64)
local flat = F.ops.layers.flatten(F.layered.load(psdBytes))
local subs = F.subtitle.load(srtText)
local tune = F.music.load(modBytes)                -- MOD / S3M / XM / IT / MIDI, rendered to audio on request

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.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.

Host notes

Host Files Bridges
Roblox none: pass buffers / strings F.host.toEditableImage(img)
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/                            Chunks, Riff, IsoBmff, Ebml, Ogg, Zip, Tar, Avi, MpegTs, MpegPs, ...
  codecs/compress/                       Deflate, Lzma, Zstd, Brotli, Bzip2, Lzw
  codecs/entropy/                        Huffman, RangeCoder
  codecs/image/                          Jpeg, Dct, Vp8, Vp8L, Pixels, Yuv, Quantize, Raster, Blend
  codecs/audio/                          Opus, Vorbis, Flac, Mpa (MP1-3), Aac, Alac, Mdct, Pcm, Stream, Resample,
                                         VorbisComment, Tracker, SoundFont
  codecs/video/                          H264, Mpeg1, Video (the codec registry)
  codecs/text/  codecs/font/  codecs/model/   Json, Xml, Text, Url / TrueType, Cff / Mat4, MeshFlatten
  host/                                  runtime adapters (only the api uses them)
  Types.luau                             the standard types + constructors
  core/                                  Bytes, Bits, Err, Crc32, Adler32, Base64, Md5, Input, 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.

Development

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, type baseline, headers, requires, native-throw, layers, deps, contract, DUP
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.

S
Description
No description provided
Readme
46 MiB
0 Stars 1 Watchers 0 Forks
Languages
Luau 64.9%
Lua 27.1%
Python 7.9%