Files
rosetta/docs/guide/recipes.md
T

11 KiB

Recipes

Short task-oriented snippets. Each one runs as a test (see the guide for how the inputs such as pngBytes are provided); the ones that read or write files run on hosts with a file system.

  • Images: thumbnail, format conversion, GIF to video and back, show an image in Roblox or LÖVE
  • Audio: transcode, tags, game-loop streaming, render a MIDI
  • 3D: glTF to OBJ with textures, voxels to a mesh
  • Other files: zip, CSV, SVG, fonts

Images

Make a thumbnail

Fit the image into a 32 x 32 box, keeping its aspect ratio, and save it as a JPEG:

local img = assert(F.image.load(pngBytes))
local scale = math.min(32 / img.width, 32 / img.height, 1)
local w, h = math.max(1, math.floor(img.width * scale + 0.5)), math.max(1, math.floor(img.height * scale + 0.5))
local thumb = assert(F.ops.image.resize(img, w, h, "lanczos"))
local jpg = assert(F.save(thumb, nil, { format = "jpeg", quality = 85 }))
assert(thumb.width == 32 and thumb.height == 24 and F.detect(jpg) == "jpeg")

JPEG has no alpha channel. To keep transparency, save as PNG or WebP instead.

Convert between image formats

local webp = assert(F.convert(pngBytes, "webp", { lossless = true }))
local back = assert(F.load(webp))
local orig = assert(F.load(pngBytes))
assert(buffer.tostring(back.pixels) == buffer.tostring(orig.pixels))   -- lossless: the same pixels

Animated GIF to video and back to frames

An animated image converts to a video directly. AVI and MP4 store Motion-JPEG frames.

local avi = assert(F.convert(gifBytes, "avi"))
local mp4 = assert(F.convert(gifBytes, "mp4", { quality = 90 }))
assert(F.detect(avi) == "avi" and F.detect(mp4) == "mp4")

local v = assert(F.video.open(avi))
local frames = {}
while true do
	local f = v:nextFrame()
	if not f then
		break
	end
	table.insert(frames, v:toRGBA(f))                   -- each frame as an rgba8 Image
end
assert(#frames >= 3 and frames[1].width == 32)
local gif = assert(F.save(assert(F.ops.image.fromFrames(frames, 1 / v.frameRate)), nil, { format = "gif" }))
assert(F.detect(gif) == "gif")

The GIF frames of gifBytes are full-canvas, so the frames you get back match the GIF's. GIF delays that are not a whole number of video frames become repeated frames.

Every frame of an animation as a full image

local gif = assert(F.image.load(gifBytes))
local canvases = assert(F.ops.image.coalesce(gif))       -- frames composited onto full canvases
local delays = F.ops.image.durations(gif)                -- seconds per frame
assert(#canvases == F.ops.image.frameCount(gif) and #delays == #canvases)
for i, frame in canvases do
	local png = assert(F.save(frame, nil, { format = "png" }))
	local _ = png, i                                     -- e.g. F.save(frame, "frame" .. i .. ".png")
end

Show an image in Roblox

local F = require(game:GetService("ReplicatedStorage").Formats)
local bytes = game:GetService("HttpService"):GetAsync("https://example.com/cat.webp")
local img = assert(F.image.load(bytes))
if img.format ~= "rgba8" then
	img = assert(F.ops.image.convert(img, "rgba8"))
end
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 = game:GetService("Players").LocalPlayer.PlayerGui:WaitForChild("ScreenGui")

Show an image in LÖVE

local F = require("formats")
local image
function love.load()
	local img = assert(F.load("cat.webp"))             -- a love.filesystem path
	image = love.graphics.newImage(F.host.toImageData(img))
end
function love.draw()
	love.graphics.draw(image, 0, 0)
end

Audio

Transcode FLAC to MP3

F.convert streams audio: the encoder reads the decoder as it goes.

local mp3 = assert(F.convert(flacBytes, "mp3", { bitrate = 192 }))   -- MP3 bit rates are in kbit/s
local dec = assert(F.audio.open(mp3))
assert(dec.sampleRate == 44100 and dec.channels == 2)
assert(math.abs(dec.duration - 1) < 0.1)

Render a MIDI file with a SoundFont

A MIDI file loads as a Midi; render turns it into an audio Decoder. Pass an SF2 SoundFont (bytes or a loaded one); without it the built-in waveforms play.

local song = assert(F.music.load(midiBytes))
local dec = song:render({ soundfont = sf2Bytes, sampleRate = 44100 })
assert(dec.channels == 2 and dec.duration > 0)
local wav = assert(F.save(assert(F.ops.audio.toAudio(dec)), nil, { format = "wav" }))
assert(F.detect(wav) == "wav")

F.convert(midiBytes, "ogg") does the same with the built-in waveforms.

Read the tags of any audio file

Tag keys are lower case (title, artist, album, date, genre, track, comment, ...), whatever the container calls them.

for _, bytes in { flacBytes, mp3Bytes, oggBytes } do
	local dec = assert(F.audio.open(bytes))           -- open reads the headers only
	assert(dec.tags.title == "Docs Tone" and dec.tags.artist == "formats-luau")
	print(string.format("%s - %s (%.1f s, %d Hz)", dec.tags.artist, dec.tags.title, dec.duration, dec.sampleRate))
end

Stream decode with a CPU budget per frame

In a game loop, decode a little each frame instead of everything at once. Read in small blocks, stop when the time budget for this frame is used up, and continue next frame. os.clock() works on every host, Roblox included.

local dec = assert(F.audio.open(oggBytes))
local block = buffer.create(1024 * dec.channels * 4)    -- reused for every read
local decoded = 0

local function step(budget: number): boolean            -- call once per frame; false when finished
	local t0 = os.clock()
	while os.clock() - t0 < budget do
		local out, n = dec:read(1024, block)
		if n == 0 then
			return false
		end
		decoded += n                                     -- hand out[0 .. n * channels * 4) to the mixer here
		local _ = out
	end
	return true
end

while step(0.002) do end                                 -- in a game: RunService.Heartbeat / love.update
assert(decoded == dec.frames)

The same pattern works for video: call v:nextFrame() until the budget is used up or the next frame's pts is in the future.

3D

glTF to OBJ with textures

A glTF's textures stay encoded (PNG / JPEG bytes in texture.data). The OBJ writer puts the .mtl and the texture files into opts.files; with a destination path F.save writes them next to the .obj.

local scene = assert(F.model.load(texturedGltfText))           -- a glTF with an embedded PNG texture
local files = {}
local obj = assert(F.save(scene, nil, { format = "obj", name = "box.obj", files = files }))
assert(files["box.mtl"])                                       -- the material library
local back = assert(F.model.load(obj, { format = "obj", files = files }))
assert(#back.materials >= 1 and back.textures[1] and back.textures[1].data)
assert(F.convert("assets/BoxTextured.gltf", "obj", { out = "out/box.obj" }))   -- .bin and .png read next to it
assert(F.host.exists("out/box.mtl"))

MagicaVoxel .vox to a greedy mesh

local scene = assert(F.model.load(voxBytes))                   -- nodes reference voxel grids (scene.voxels)
assert(F.ops.mesh.meshVoxels(scene, { scale = 0.1 }))          -- one greedy mesh per grid, colours per vertex
local prim = assert(F.ops.mesh.merge(scene))                   -- everything in world space, one primitive
assert(prim.attributes.POSITION.count > 0 and prim.attributes.COLOR_0)
local glb = assert(F.save(scene, nil, { format = "glb" }))
assert(F.detect(glb) == "gltf")

Greedy meshing merges coplanar faces of the same colour into rectangles, so a 20 x 20 wall is two triangles instead of 800.

Other files

Extract a zip and re-zip it

local zip = assert(F.archive.load(zipBytes))
local files = {}
for _, e in zip:list() do
	if not e.dir then
		files[e.name] = assert(zip:read(e.name))                -- a buffer per file
	end
end
local new = assert(F.archive.load(assert(F.save(zip, nil, { format = "tar" }))))   -- any archive -> tar
new:add("extra/hello.txt", "hi")
local rezipped = assert(F.save(new, nil, { format = "zip", level = 9 }))
local check = assert(F.archive.load(rezipped))
for name, data in files do
	assert(buffer.tostring(assert(check:read(name))) == buffer.tostring(data))
end
local zip = assert(F.archive.load("assets/files.zip"))
for _, e in zip:list() do
	if not e.dir then
		assert(F.host.writeFile("out/" .. string.gsub(e.name, "/", "_"), assert(zip:read(e.name))))
	end
end

Read a CSV into rows

local rows = assert(F.data.load(csvText, { format = "csv" }))                  -- { { "name", "score" }, { ... } }
local recs = assert(F.data.load(csvText, { format = "csv", header = true, numbers = true }))
assert(#rows == #recs + 1)
for _, r in recs do
	print(r.name, r.score)                                                      -- records keyed by the header
end

SVG to PNG

local icon = assert(F.vector.load(svgText))
local img = assert(F.ops.vector.rasterize(icon, 128, 128))                     -- rgba8, antialiased
local png = assert(F.save(img, nil, { format = "png" }))
assert(img.width == 128 and F.detect(png) == "png")

Bake a TTF to a BMFont

bake renders the glyphs into packed page images. Save the descriptor and each page:

local font = assert(F.font.load(ttfBytes))
local bmfont = F.format("bmfont")
local baked = assert(bmfont.bake(font, { px = 24, chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789" }))
local fnt = assert(F.saveString(baked, { format = "bmfont" }))                  -- the text descriptor
local pages = {}
for i, page in baked.pages do
	pages[baked.meta.pageFiles[i]] = assert(F.save(page, nil, { format = "png" }))
end
local back = assert(F.font.load(fnt, { format = "bmfont", loadPage = function(file) return pages[file] end }))
assert(back:glyphIndex(string.byte("A")) ~= 0)

Measure and draw a string with a TTF

local font = assert(F.font.load(ttfBytes))
local px = 20
local scale = px / font.unitsPerEm
local canvas = assert(F.ops.image.new(200, 32))
local baseline = math.ceil(font.ascent * scale) + 2                             -- y of the baseline, pixels down
local x, prev = 2, nil
for _, cp in utf8.codes("Hello") do
	local g = font:glyphIndex(cp)
	if prev then
		x += font:kern(prev, g) * scale
	end
	local glyph = font:rasterize(g, px)                                         -- alpha8 coverage
	if glyph and glyph.width > 0 then
		-- meta.left / meta.top: the bitmap's offset from the pen; top counts up from the baseline
		F.ops.image.blit(canvas, glyph, math.floor(x + glyph.meta.left), baseline - glyph.meta.top)
	end
	x += font:advance(g) * scale                                                -- advance is in font units
	prev = g
end
assert(x > 20)
local png = assert(F.save(canvas, nil, { format = "png" }))                     -- white text, transparent background

alpha8 images blit as white with that alpha; tint the canvas afterwards, or blit onto a coloured background.