Files
rosetta/docs/API.md
T

7.4 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. Formats that write extra files (caps.extraFiles: BMFont pages) put them next to dest; without a destination they come back as a third value { [file name] = buffer } (or in the caller's opts.files table).

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 (+ the extra files, see above)
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); a format's optional variant(r) can name the flavour ("webm" for a WebM file read by mkv)
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, ...). bitrate is in bits per second for every encoder (values below 1000 are read as kbit/s).

Across categories: a Module or Midi saved to an audio format is rendered first (render options in opts: F.convert(modBytes, "wav", { sampleRate = 22050 })), and F.audio.open / F.audio.load render music bytes; a VideoDecoder saved to an image format (gif, apng, webp) becomes an animated Image of its frames (frames, fps, maxFrames = 300, maxPixels = 2^25); an Image saves to a video format as a frames-backed video.

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.
  • F.music.new, addPattern, setCell, getCell, addSample, addInstrument, note: build and edit tracker modules (ops/MusicOps, also F.ops.music): F.music.new({ format = "mod", channels = 4 }).

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.music ops/MusicOps new, addPattern, setCell / getCell, addSample (from an Audio), addInstrument, note ("C-4" -> 49)
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.Rbx (the Roblox instance tree of rbxm / rbxmx: codecs/model/Rbx), F.null, F.version.