Files
rosetta/docs/API.md
T
4DBug 51b08575c4 ws-cleanup: codecs/ grouped by domain; containers/Chunks, codecs/audio/Stream, codecs/image/Pixels, codecs/model/Mat4
C2, the hierarchy (tools/move.py, every reference rewritten mechanically):
- codecs/compress: Deflate Lzma Zstd Brotli Bzip2 Lzw; codecs/entropy: Huffman (from core) RangeCoder;
  codecs/image: Jpeg Dct Vp8 Vp8L Yuv Quantize Raster Blend Pixels; codecs/audio: Mdct Aac Alac Pcm Resample
  VorbisComment Tracker SoundFont Stream; codecs/video: H264 Mpeg1 Video; codecs/text: Json Xml Text Url;
  codecs/font: TrueType Cff; codecs/model: MeshFlatten Mat4. containers/ stays flat; core/ keeps Bytes Bits Err
  Crc32 Adler32 Base64 Md5 Input Sniff.
- LAYERS lint: codecs must sit in a domain folder; gen_registry lists codecs by domain (docs/FORMATS.md).
- Checked: build.py both targets, rojo build of build/roblox, the full suite on both runtimes.

C3, generic code out of format folders:
- containers/Chunks (new): the chunked-file walker (RIFF / RIFX / IFF / PNG / CAF layouts: endianness, size first,
  trailer, padding, lenient missing pad, open-ended ids, size hooks). containers/Riff walks with it (RF64 ds64
  through the resize hook); image/png, audio/aiff and audio/caf list their chunk handlers over it.
- codecs/audio/Stream (new): Stream.packets, the packet-decoder Decoder (read / seek with pre-roll / position,
  priming and end trimming) that aac, caf and m4a each carried (~70 lines each).
- codecs/image/Pixels: image/bmp/Pixels promoted (+ rgb555); image/ico's DIB decoder uses its row loops instead of
  its own (the AND mask / alpha rule stay ICO's).
- codecs/model/Mat4 (new): matrices / quaternions / TRS shared by FBX (Xform keeps only the FBX transform model),
  Collada (Math keeps only <lookat> / <skew>) and USD (its matrix helpers and general 4x4 inverse); Mat4.mul is
  Types.Scene.mul. The Collada normal matrix is now the inverse transpose (it was the inverse; same result for the
  fixtures' bind shapes).
- README rewritten (install for Rojo and LÖVE / LuaJIT, quick start per category, F.* and F.ops, host notes:
  FORMATS_NO_JIT_TUNE, paths, layout); docs/STYLE.md: the codec domains, "what belongs in a format folder" with the
  shared building blocks and the DUP rule, conventions (WAVE order, lower-case tags, loops, the api hooks
  decodeImage / encodeImage / openAudio / plugins / resolve, the codecs/video/Video registry), Err.from, the type
  baseline. New tests: tests/containers/chunks, tests/codecs/mat4. Type baseline 93.
2026-10-31 12:25:03 -05:00

6.1 KiB

formats-luau API

local F = require(Formats) (Roblox: the ModuleScript; LuaJIT / LÖVE: require("formats"); luau CLI: require("@formats")). Everything below is src/Formats/init.luau unless noted. Nothing throws on bad data or bad arguments: a failing call returns nil, err where err is a core/Err value (err.code, err.message, err.offset, err.format; tostring(err) prints png: CORRUPT at 0x21: bad filter type 7).

Sources and destinations

A source src is a buffer, a string of bytes, or a file path on hosts with a file system (LuaJIT, LÖVE). A string is a path only when opts.path = true or when it does not look like file data and the file exists; pass 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.

Loading and saving

Call Returns
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.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.formats(category?) { { name, category, extensions, mime, caps } } without loading any format (also 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, ...).

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 each have load, open, save and formats: the calls above restricted to one category. Extras:

  • F.video.open(src) also opens animated images (GIF / APNG / WebP) as videos; F.video.fromImage(img), F.video.fromFrames(images, delays?) (an image sequence: F.save(F.video.fromFrames(list, 1 / 25), "out.avi")), F.video.codecs (the codec registry codecs/video/Video).
  • F.model.loadTextures(scene, opts?): decodes embedded / referenced textures into texture.image.
  • 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.

Editing: F.ops

Loaded on first use; every function returns a new value (or edits in place where it says so) and nil, Err for bad arguments.

Table Module Functions
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.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
local img = F.load(png)
local thumb = F.ops.image.resize(img, 128, 128, "lanczos")
local music = F.ops.audio.toAudio(F.audio.open(mp3))
local quiet = F.ops.audio.gainDb(F.ops.audio.resample(music, 48000), -6)
F.save(quiet, "out.flac")
local icon = F.ops.vector.rasterize(F.load(svgText), 64, 64)

Hooks and plug-ins

A format never requires another format, so the api passes these to decoders / encoders in opts (callers of F.format(name).decode directly may pass their own; without them the embedded parts return Err.UNSUPPORTED):

  • opts.decodeImage(buf) -> Image | nil, Err and opts.encodeImage(img, format) -> buffer | nil, Err: images inside other files (ICO PNG entries, PSD / glTF / 3MF textures, MJPEG frames, ...).
  • opts.openAudio(demuxer, track) -> Decoder | nil, Err: audio tracks of video containers (wrapped by containers/AudioWrap and opened as the matching audio format).
  • opts.plugins (default F.plugins): injected optional dependencies, e.g. F.plugins.brep (a B-rep kernel for cad/step).
  • opts.resolve(uri) -> buffer?: files referenced by a model (OBJ .mtl, glTF .bin); filled in for paths on hosts with files. opts.loadPage(file, page) for bitmap-font pages.

Host

F.host (src/Formats/host): name ("roblox", "love", "luajit", "luau"), hasFiles, readFile, writeFile, exists; Roblox toEditableImage(img); LÖVE toImageData(img), fromImageData(imageData), toSoundData(audioOrDecoder).

On LuaJIT the host raises the trace limits at load (jit.opt.start("maxtrace=8000", "maxmcode=65536")): the big decoders (CELT, VP8, H.264, MPEG-1) outgrow the defaults and fall back to the interpreter. Set _G.FORMATS_NO_JIT_TUNE = true before requiring the library to leave the JIT settings alone.

Also exported

F.Err (codes TRUNCATED, CORRUPT, CHECKSUM, UNSUPPORTED, LIMIT, ARG, IO, UNKNOWN_FORMAT), F.Types (the standard types and their constructors), F.Bytes (core/Bytes Reader / Writer), F.null, F.version.