From 086b0a7ffdcaabee5741904f1b2ce656fb7f36d2 Mon Sep 17 00:00:00 2001 From: 4DBug Date: Sat, 31 Oct 2026 11:06:04 -0500 Subject: [PATCH] ws-cleanup: F.ops facade (image / mesh / layers / audio / vector.rasterize) and ops/AudioOps - F.ops in init.luau, loaded on first use: F.ops.image (ImageOps), F.ops.mesh (MeshOps), F.ops.layers (LayerOps), F.ops.audio (new ops/AudioOps), F.ops.vector.rasterize (the vector/svg renderer for any Vector, through F.format). - ops/AudioOps: toAudio / fromDecoder (Audio from a Decoder via codecs/Pcm), gain / gainDb / normalize, peak / rms, remix / downmix / upmix (WAVE-layout matrices, BS.775 coefficients normalised against clipping), resample (codecs/Resample), trim, concat and mix (inputs converted to the first one's rate and channels), fade. - tests/ops/audioops (39 checks, both runtimes); docs/API.md (new): the F.* API, F.ops, hooks, host. Co-Authored-By: Claude Opus 5.5 --- docs/API.md | 96 +++++++ src/Formats/init.luau | 53 ++++ src/Formats/ops/AudioOps.luau | 481 ++++++++++++++++++++++++++++++++++ tests/ops/audioops.luau | 151 +++++++++++ 4 files changed, 781 insertions(+) create mode 100644 docs/API.md create mode 100644 src/Formats/ops/AudioOps.luau create mode 100644 tests/ops/audioops.luau diff --git a/docs/API.md b/docs/API.md new file mode 100644 index 0000000..5e6b861 --- /dev/null +++ b/docs/API.md @@ -0,0 +1,96 @@ +# 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](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`). +- `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/Resample`), `trim`, `concat`, `fade` | +| `F.ops.vector` | `vector/svg` | `rasterize(vector, w?, h?, opts?)`: any `Vector` to an rgba8 `Image` | + +```luau +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`. diff --git a/src/Formats/init.luau b/src/Formats/init.luau index 57d5dcc..8cc3fb3 100644 --- a/src/Formats/init.luau +++ b/src/Formats/init.luau @@ -12,6 +12,7 @@ -- local s = F.saveString(img, { format = "png" }) -- local buf = F.convert(src, "png", opts?) -- load + save -- F.formats() -- the capability list (also docs/FORMATS.md) +-- F.ops.image.resize(img, 64, 64) -- editing: F.ops.image / mesh / layers / audio / vector.rasterize -- -- Never throws on bad data or bad arguments: every function returns nil, Err (Err.code, Err.message, tostring(err)). local Err = require("@formats/core/Err") @@ -679,4 +680,56 @@ F.model.loadTextures = function(scene: any, opts: Options?): (any, { [number]: E return scene, errs end +-- ------------------------------------------------------------------------------------------------ ops +-- F.ops: editing on the standard types, loaded on first use. +-- F.ops.image ops/ImageOps convert, crop, resize, flip, rotate, blit / composite, coalesce, ... +-- F.ops.mesh ops/MeshOps triangulate, transform, computeNormals / Tangents, weld, merge, meshVoxels, ... +-- F.ops.layers ops/LayerOps flatten / flattenFrames a Layered (PSD, Aseprite), leaves +-- F.ops.audio ops/AudioOps toAudio, gain / gainDb / normalize, mix, remix / downmix / upmix, resample, trim, +-- concat, fade, peak, rms +-- F.ops.vector.rasterize(vector, w?, h?, opts?) -> rgba8 Image: the SVG renderer (vector/svg) for any Vector +local OPS: { [string]: () -> any } = { + image = function() + return ImageOps + end, + mesh = function() + return require("@formats/ops/MeshOps") + end, + layers = function() + return require("@formats/ops/LayerOps") + end, + audio = function() + return require("@formats/ops/AudioOps") + end, + vector = function() + return { + rasterize = function(v: any, w: number?, h: number?, opts: any?): (any, Err.Err?) + local svg, err = F.format("svg") + if not svg then + return nil, err + end + local ok, img, rerr = pcall(svg.rasterize, v, w, h, opts) + if not ok then + return nil, Err.wrap(Err.new(Err.CORRUPT, "rasterize threw: " .. tostring(img)), "svg") + end + if img == nil and rerr then + return nil, Err.wrap(rerr, "svg") + end + return img, rerr + end, + } + end, +} +F.ops = setmetatable({}, { + __index = function(t: any, k: string): any + local make = OPS[k] + if not make then + return nil + end + local m = make() + rawset(t, k, m) + return m + end, +}) :: any + return F diff --git a/src/Formats/ops/AudioOps.luau b/src/Formats/ops/AudioOps.luau new file mode 100644 index 0000000..c1a5d53 --- /dev/null +++ b/src/Formats/ops/AudioOps.luau @@ -0,0 +1,481 @@ +--!strict +-- ops/AudioOps: editing on the standard Audio (layer 5.5: core, Types and codecs only): a Decoder collected into an +-- Audio, gain (linear or dB), normalize, mix, channel remixing (downmix / upmix with the usual WAVE-layout matrices), +-- resampling (codecs/Resample), trim, concat, fades, peak / RMS. New code. +-- +-- local AudioOps = require("@formats/ops/AudioOps") -- F.ops.audio in the api +-- local a = AudioOps.toAudio(F.audio.open(src)) -- an Audio from an Audio or a streaming Decoder +-- local louder = AudioOps.gainDb(a, 6) -- every call returns a new Audio | nil, Err (never throws) +-- local mono = AudioOps.downmix(a) -- or AudioOps.remix(a, 1); upmix(a, 6) +-- local a48 = AudioOps.resample(a, 48000, { quality = "high" }) +-- local mixed = AudioOps.mix({ a, b }, { 0.5, 0.5 }) -- other rates / channel counts are converted to a's +-- local clip = AudioOps.trim(a, 1.5, 4) -- seconds [1.5, 4) +-- local both = AudioOps.concat({ a, b }) +-- local peak, perChannel = AudioOps.peak(a) -- max |sample|; AudioOps.rms(a) the same shape +-- +-- Conventions: samples are the Audio's interleaved f32 (no clipping is applied: values past +-1 are kept, encoders +-- clip). Channels are in WAVE order (FL FR C LFE BL BR SL SR, as every decoder returns them). Downmixes follow the +-- ITU-R BS.775 coefficients (centre and surrounds at -3 dB, LFE dropped), scaled so a full-scale input cannot +-- exceed full scale; upmixes copy mono to FL / FR and stereo to FL / FR (other channels silent). Tags and meta are +-- copied from the (first) input. +local Err = require("@formats/core/Err") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Resample = require("@formats/codecs/Resample") + +local AudioOps = {} + +local readf32, writef32 = buffer.readf32, buffer.writef32 +local floor, max, min, abs, sqrt = math.floor, math.max, math.min, math.abs, math.sqrt + +-- ------------------------------------------------------------------------------------------------ validation +local function isAudio(a: any): boolean + return type(a) == "table" + and a.kind == "audio" + and type(a.samples) == "buffer" + and type(a.frames) == "number" + and type(a.channels) == "number" + and a.channels >= 1 + and type(a.sampleRate) == "number" + and a.sampleRate > 0 + and buffer.len(a.samples) >= a.frames * a.channels * 4 +end + +local function bad(what: string): (nil, Err.Err) + return nil, Err.new(Err.ARG, what) +end + +-- a new Audio with a's rate / tags / meta and the given layout +local function like(a: Types.Audio, channels: number, frames: number, rate: number?): Types.Audio + local out = Types.Audio.new(rate or a.sampleRate, channels, frames) + out.tags = table.clone(a.tags or {}) + out.meta = table.clone(a.meta or {}) + return out +end + +-- ------------------------------------------------------------------------------------------------ conversion +-- toAudio(audioOrDecoder, opts?) -> Audio: an Audio as it is, a Decoder read to its end (opts.maxFrames: Err.LIMIT +-- past it; default 2^31) +function AudioOps.toAudio(v: any, opts: { maxFrames: number? }?): (Types.Audio?, Err.Err?) + if isAudio(v) then + return v, nil + end + local src, err = Pcm.source(v) + if not src then + return nil, err + end + return Pcm.collect(src, opts and opts.maxFrames) +end +AudioOps.fromDecoder = AudioOps.toAudio + +-- ------------------------------------------------------------------------------------------------ levels +-- gain(a, factor) -> Audio with every sample times factor +function AudioOps.gain(a: Types.Audio, factor: number): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("gain: expected an Audio") + end + if type(factor) ~= "number" or factor ~= factor then + return bad("gain: factor must be a number") + end + local n = a.frames * a.channels + local out = like(a, a.channels, a.frames) + local s, d = a.samples, out.samples + for i = 0, n - 1 do + writef32(d, i * 4, readf32(s, i * 4) * factor) + end + return out, nil +end + +-- gainDb(a, dB) -> Audio scaled by 10^(dB / 20) +function AudioOps.gainDb(a: Types.Audio, db: number): (Types.Audio?, Err.Err?) + if type(db) ~= "number" or db ~= db then + return bad("gainDb: dB must be a number") + end + return AudioOps.gain(a, 10 ^ (db / 20)) +end + +-- peak(a) -> the largest |sample|, { per channel } +function AudioOps.peak(a: Types.Audio): (number?, { number } | Err.Err) + if not isAudio(a) then + return nil, Err.new(Err.ARG, "peak: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = abs(readf32(s, p + (c - 1) * 4)) + if v > per[c] then + per[c] = v + end + end + end + local m = 0 + for c = 1, ch do + m = max(m, per[c]) + end + return m, per +end + +-- rms(a) -> the root mean square over every sample, { per channel } (0 for no frames) +function AudioOps.rms(a: Types.Audio): (number?, { number } | Err.Err) + if not isAudio(a) then + return nil, Err.new(Err.ARG, "rms: expected an Audio") + end + local ch = a.channels + local per = table.create(ch, 0) + local s = a.samples + for f = 0, a.frames - 1 do + local p = f * ch * 4 + for c = 1, ch do + local v = readf32(s, p + (c - 1) * 4) + per[c] += v * v + end + end + local total = 0 + local n = max(1, a.frames) + for c = 1, ch do + total += per[c] + per[c] = sqrt(per[c] / n) + end + return sqrt(total / (n * ch)), per +end + +-- normalize(a, target?) -> Audio scaled so its peak is target (default 1; silence is returned unchanged) +function AudioOps.normalize(a: Types.Audio, target: number?): (Types.Audio?, Err.Err?) + local p, perr = AudioOps.peak(a) + if not p then + return nil, perr :: Err.Err + end + local t = target or 1 + if type(t) ~= "number" or t ~= t or t < 0 then + return bad("normalize: target must be a number >= 0") + end + return AudioOps.gain(a, if p > 0 then t / p else 1) +end + +-- fade(a, inSeconds?, outSeconds?) -> Audio with linear fade-in / fade-out ramps +function AudioOps.fade(a: Types.Audio, inSec: number?, outSec: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("fade: expected an Audio") + end + local fi = floor(max(0, (inSec or 0) * a.sampleRate) + 0.5) + local fo = floor(max(0, (outSec or 0) * a.sampleRate) + 0.5) + if fi ~= fi or fo ~= fo then + return bad("fade: bad duration") + end + local out = like(a, a.channels, a.frames) + buffer.copy(out.samples, 0, a.samples, 0, a.frames * a.channels * 4) + local ch, d, n = a.channels, out.samples, a.frames + for f = 0, min(fi, n) - 1 do + local g = f / fi + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + for k = 0, min(fo, n) - 1 do + local f = n - 1 - k + local g = k / fo + for c = 0, ch - 1 do + local p = (f * ch + c) * 4 + writef32(d, p, readf32(d, p) * g) + end + end + return out, nil +end + +-- ------------------------------------------------------------------------------------------------ channels +-- the WAVE-order speakers of 1 .. 8 channel layouts (as FFmpeg's default layouts) +local LAYOUT: { { string } } = { + { "C" }, + { "FL", "FR" }, + { "FL", "FR", "C" }, + { "FL", "FR", "BL", "BR" }, + { "FL", "FR", "C", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BL", "BR" }, + { "FL", "FR", "C", "LFE", "BC", "SL", "SR" }, + { "FL", "FR", "C", "LFE", "BL", "BR", "SL", "SR" }, +} +local H = sqrt(0.5) -- -3 dB +-- speaker -> its contribution to (left, right) in a stereo downmix +local TO_STEREO: { [string]: { number } } = { + FL = { 1, 0 }, FR = { 0, 1 }, C = { H, H }, LFE = { 0, 0 }, BL = { H, 0 }, BR = { 0, H }, SL = { H, 0 }, + SR = { 0, H }, BC = { 0.5, 0.5 }, +} + +-- matrix(from, to) -> m[o][i]: output channel o = sum m[o][i] * input i +local function matrix(from: number, to: number): { { number } } + local m = table.create(to) + for o = 1, to do + m[o] = table.create(from, 0) + end + if from == to then + for c = 1, to do + m[c][c] = 1 + end + return m + end + local inL, outL = LAYOUT[from], LAYOUT[to] + if to < from and inL and outL and to <= 2 then + -- down to stereo (then mono = the average of the two) + local l, r = table.create(from, 0), table.create(from, 0) + local sl, sr = 0, 0 + for i, sp in inL do + local w = TO_STEREO[sp] or { 0, 0 } + l[i], r[i] = w[1], w[2] + sl += w[1] + sr += w[2] + end + local norm = 1 / max(sl, sr, 1) + for i = 1, from do + if to == 2 then + m[1][i], m[2][i] = l[i] * norm, r[i] * norm + else + m[1][i] = (l[i] + r[i]) * norm * 0.5 + end + end + return m + end + if from == 1 then + -- mono up: FL and FR (or the only channel) + if outL then + local placed = false + for o, sp in outL do + if sp == "FL" or sp == "FR" then + m[o][1] = 1 + placed = true + end + end + if not placed then + m[1][1] = 1 + end + else + m[1][1] = 1 + end + return m + end + if inL and outL then + -- same-named speakers carry over; down: missing speakers fold into the stereo pair at their weights + local outIdx: { [string]: number } = {} + for o, sp in outL do + outIdx[sp] = o + end + for i, sp in inL do + local o = outIdx[sp] + if o then + m[o][i] = 1 + elseif to < from and outIdx.FL and outIdx.FR then + local w = TO_STEREO[sp] or { 0, 0 } + m[outIdx.FL][i] += w[1] + m[outIdx.FR][i] += w[2] + end + end + if to < from then + for o = 1, to do + local s = 0 + for i = 1, from do + s += m[o][i] + end + if s > 1 then + for i = 1, from do + m[o][i] /= s + end + end + end + end + return m + end + -- unknown layouts: channel i -> i, extra outputs silent, extra inputs dropped + for c = 1, min(from, to) do + m[c][c] = 1 + end + return m +end +AudioOps.matrix = matrix + +-- remix(a, channels, m?) -> Audio with that many channels (m: an explicit m[out][in] matrix; default matrix(...)) +function AudioOps.remix(a: Types.Audio, channels: number, m: { { number } }?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("remix: expected an Audio") + end + if type(channels) ~= "number" or channels < 1 or channels > 256 or channels % 1 ~= 0 then + return bad("remix: channels must be 1 .. 256") + end + local from = a.channels + local mm = m or matrix(from, channels) + if type(mm) ~= "table" or #mm ~= channels then + return bad("remix: the matrix needs one row per output channel") + end + for o = 1, channels do + if type(mm[o]) ~= "table" then + return bad("remix: matrix row " .. o .. " is not a table") + end + end + local out = like(a, channels, a.frames) + local s, d = a.samples, out.samples + local x = table.create(from, 0) + for f = 0, a.frames - 1 do + local p = f * from * 4 + for i = 1, from do + x[i] = readf32(s, p + (i - 1) * 4) + end + local q = f * channels * 4 + for o = 1, channels do + local row = mm[o] + local v = 0 + for i = 1, from do + local w = row[i] + if w and w ~= 0 then + v += w * x[i] + end + end + writef32(d, q + (o - 1) * 4, v) + end + end + return out, nil +end + +-- downmix(a, channels?) -> Audio with fewer channels (default 2; mono input stays mono) +function AudioOps.downmix(a: Types.Audio, channels: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("downmix: expected an Audio") + end + local n = channels or min(2, a.channels) + if n > a.channels then + return bad("downmix: more output channels than input") + end + return AudioOps.remix(a, n) +end + +-- upmix(a, channels) -> Audio with more channels +function AudioOps.upmix(a: Types.Audio, channels: number): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("upmix: expected an Audio") + end + if type(channels) ~= "number" or channels < a.channels then + return bad("upmix: fewer output channels than input") + end + return AudioOps.remix(a, channels) +end + +-- ------------------------------------------------------------------------------------------------ time +-- resample(a, rate, opts?) -> Audio at the new rate (codecs/Resample: opts.quality "low" | "medium" | "high") +function AudioOps.resample(a: Types.Audio, rate: number, opts: Resample.Options?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("resample: expected an Audio") + end + local samples, frames = Resample.buffer(a.samples, a.frames, a.channels, a.sampleRate, rate, opts) + if not samples then + return bad("resample: " .. tostring(frames)) + end + local out = like(a, a.channels, 0, rate) + out.samples = samples + out.frames = frames :: number + return out, nil +end + +-- trim(a, start, stop?) -> Audio of the seconds [start, stop) (clamped to the audio; stop default the end) +function AudioOps.trim(a: Types.Audio, start: number, stop: number?): (Types.Audio?, Err.Err?) + if not isAudio(a) then + return bad("trim: expected an Audio") + end + if type(start) ~= "number" or start ~= start or (stop ~= nil and (type(stop) ~= "number" or stop ~= stop)) then + return bad("trim: start / stop must be numbers (seconds)") + end + local f0 = math.clamp(floor(start * a.sampleRate + 0.5), 0, a.frames) + local f1 = if stop then math.clamp(floor(stop * a.sampleRate + 0.5), f0, a.frames) else a.frames + local ch = a.channels + local out = like(a, ch, f1 - f0) + buffer.copy(out.samples, 0, a.samples, f0 * ch * 4, (f1 - f0) * ch * 4) + return out, nil +end + +-- conform(list, what) -> the audios converted to the first one's rate and channel count | nil, Err +local function conform(list: { Types.Audio }, what: string): ({ Types.Audio }?, Err.Err?) + if type(list) ~= "table" or #list == 0 then + return nil, Err.new(Err.ARG, what .. ": expected a non-empty list of Audio") + end + local first = list[1] + if not isAudio(first) then + return nil, Err.new(Err.ARG, what .. ": item 1 is not an Audio") + end + local out = { first } + for i = 2, #list do + local a = list[i] + if not isAudio(a) then + return nil, Err.new(Err.ARG, what .. ": item " .. i .. " is not an Audio") + end + if a.sampleRate ~= first.sampleRate then + local r, err = AudioOps.resample(a, first.sampleRate) + if not r then + return nil, err + end + a = r + end + if a.channels ~= first.channels then + local r, err = AudioOps.remix(a, first.channels) + if not r then + return nil, err + end + a = r + end + out[i] = a + end + return out, nil +end + +-- concat(list) -> Audio: the audios one after the other (at the first one's rate and channel count) +function AudioOps.concat(list: { Types.Audio }): (Types.Audio?, Err.Err?) + local items, err = conform(list, "concat") + if not items then + return nil, err + end + local first = items[1] + local ch = first.channels + local total = 0 + for _, a in items do + total += a.frames + end + local out = like(first, ch, total) + local at = 0 + for _, a in items do + buffer.copy(out.samples, at * ch * 4, a.samples, 0, a.frames * ch * 4) + at += a.frames + end + return out, nil +end + +-- mix(list, weights?) -> Audio: the sum of the audios (times weights[i], default 1 each), as long as the longest, at +-- the first one's rate and channel count +function AudioOps.mix(list: { Types.Audio }, weights: { number }?): (Types.Audio?, Err.Err?) + local items, err = conform(list, "mix") + if not items then + return nil, err + end + if weights ~= nil and type(weights) ~= "table" then + return bad("mix: weights must be a list of numbers") + end + local first = items[1] + local ch = first.channels + local frames = 0 + for _, a in items do + frames = max(frames, a.frames) + end + local out = like(first, ch, frames) + local d = out.samples + for i, a in items do + local w = if weights then weights[i] or 1 else 1 + if type(w) ~= "number" then + return bad("mix: weight " .. i .. " is not a number") + end + local s = a.samples + for k = 0, a.frames * ch - 1 do + writef32(d, k * 4, readf32(d, k * 4) + readf32(s, k * 4) * w) + end + end + return out, nil +end + +return AudioOps diff --git a/tests/ops/audioops.luau b/tests/ops/audioops.luau new file mode 100644 index 0000000..1966ae1 --- /dev/null +++ b/tests/ops/audioops.luau @@ -0,0 +1,151 @@ +-- ops/AudioOps tests: toAudio from a Decoder, gain / gainDb / normalize, peak / RMS of known signals, remix matrices +-- (5.1 -> stereo -> mono, mono -> stereo / 5.1), resample through codecs/Resample, trim, concat and mix with rate / +-- channel conversion, fades, bad arguments (Err.ARG, never a throw), and the F.ops facade. +local T = require("@tests/T") +local AudioOps = require("@formats/ops/AudioOps") +local Types = require("@formats/Types") +local Pcm = require("@formats/codecs/Pcm") +local Err = require("@formats/core/Err") +local F = require("@formats") + +local t = T.suite("audioops") + +local function audio(rate: number, ch: number, frames: number, fn: (f: number, c: number) -> number): Types.Audio + local a = Types.Audio.new(rate, ch, frames) + for f = 0, frames - 1 do + for c = 0, ch - 1 do + buffer.writef32(a.samples, (f * ch + c) * 4, fn(f, c)) + end + end + a.tags = { title = "x" } + return a +end +local function at(a: Types.Audio, f: number, c: number): number + return buffer.readf32(a.samples, (f * a.channels + c) * 4) +end +local function near(x: number, y: number, eps: number?): boolean + return math.abs(x - y) <= (eps or 1e-6) +end + +local sine = audio(8000, 2, 8000, function(f, c) + return (if c == 0 then 0.5 else 0.25) * math.sin(2 * math.pi * 440 * f / 8000) +end) + +-- toAudio +do + local dec = Pcm.audioDecoder(sine) + local a = AudioOps.toAudio(dec) :: Types.Audio + t:check(a and a.frames == 8000 and a.channels == 2 and buffer.tostring(a.samples) == buffer.tostring(sine.samples), "toAudio(Decoder)") + t:check(AudioOps.toAudio(sine) == sine, "toAudio(Audio) is the Audio") + local _, e2 = AudioOps.toAudio(Pcm.audioDecoder(sine), { maxFrames = 10 }) + t:check(e2 and e2.code == Err.LIMIT, "maxFrames -> LIMIT") +end + +-- levels +do + local p, per = AudioOps.peak(sine) + t:check(near(p :: number, 0.5, 1e-3) and near((per :: any)[2], 0.25, 1e-3), "peak") + local r, rper = AudioOps.rms(sine) + t:check(near((rper :: any)[1], 0.5 / math.sqrt(2), 1e-3) and near((rper :: any)[2], 0.25 / math.sqrt(2), 1e-3), "rms per channel") + t:check(near(r :: number, math.sqrt((0.125 + 0.03125) / 2), 1e-3), "rms") + local g = AudioOps.gainDb(sine, -6.0206) :: Types.Audio + t:check(near(at(g, 100, 0), at(sine, 100, 0) / 2, 1e-4), "gainDb -6 dB halves") + t:eq(g.tags.title, "x", "tags copied") + local n = AudioOps.normalize(sine) :: Types.Audio + t:check(near((AudioOps.peak(n)) :: number, 1, 1e-5), "normalize to 1") + local z = AudioOps.normalize(Types.Audio.new(8000, 1, 10)) :: Types.Audio + t:check(z and z.frames == 10, "normalize silence") +end + +-- channels +do + -- 5.1 (WAVE order FL FR C LFE BL BR) with distinct constants + local five = audio(8000, 6, 4, function(_, c) + return ({ 0.1, 0.2, 0.3, 0.4, 0.5, 0.6 })[c + 1] + end) + local st = AudioOps.downmix(five) :: Types.Audio + t:check(st and st.channels == 2, "5.1 -> stereo") + local h = math.sqrt(0.5) + local norm = 1 / (1 + 2 * h) + t:check(near(at(st, 0, 0), (0.1 + h * 0.3 + h * 0.5) * norm, 1e-6), "stereo L = FL + C / sqrt2 + BL / sqrt2 (normalised)") + t:check(near(at(st, 0, 1), (0.2 + h * 0.3 + h * 0.6) * norm, 1e-6), "stereo R (LFE dropped)") + local mono = AudioOps.downmix(sine, 1) :: Types.Audio + t:check(near(at(mono, 100, 0), (at(sine, 100, 0) + at(sine, 100, 1)) / 2, 1e-6), "stereo -> mono averages") + local up = AudioOps.upmix(mono, 2) :: Types.Audio + t:check(up.channels == 2 and at(up, 100, 0) == at(mono, 100, 0) and at(up, 100, 1) == at(mono, 100, 0), "mono -> stereo copies") + local up6 = AudioOps.upmix(sine, 6) :: Types.Audio + t:check(up6.channels == 6 and at(up6, 7, 0) == at(sine, 7, 0) and at(up6, 7, 1) == at(sine, 7, 1) and at(up6, 7, 2) == 0, "stereo -> 5.1 keeps FL / FR") + local swapped = AudioOps.remix(sine, 2, { { 0, 1 }, { 1, 0 } }) :: Types.Audio + t:check(at(swapped, 9, 0) == at(sine, 9, 1), "explicit matrix") + local _, e = AudioOps.downmix(mono, 2) + t:check(e and e.code == Err.ARG, "downmix to more channels: ARG") +end + +-- time +do + local r = AudioOps.resample(sine, 16000) :: Types.Audio + t:check(r.sampleRate == 16000 and r.frames == 16000, "resample 8 -> 16 kHz") + local err = 0 + for f = 2000, 14000 do + err = math.max(err, math.abs(at(r, f, 0) - 0.5 * math.sin(2 * math.pi * 440 * f / 16000))) + end + t:check(err < 1e-3, string.format("resampled sine (max err %.1e)", err)) + local c = AudioOps.trim(sine, 0.25, 0.5) :: Types.Audio + t:check(c.frames == 2000 and at(c, 0, 0) == at(sine, 2000, 0), "trim [0.25, 0.5) s") + t:eq((AudioOps.trim(sine, 0.9, 5) :: Types.Audio).frames, 800, "trim clamps") + local cat = AudioOps.concat({ sine, c }) :: Types.Audio + t:check(cat.frames == 10000 and at(cat, 8000, 1) == at(c, 0, 1), "concat") + local monoHi = audio(16000, 1, 1600, function() + return 0.1 + end) + local cat2 = AudioOps.concat({ sine, monoHi }) :: Types.Audio + t:check(cat2.channels == 2 and cat2.sampleRate == 8000 and math.abs(cat2.frames - 8800) <= 1, "concat converts rate and channels") + local m = AudioOps.mix({ sine, sine }, { 0.5, 0.25 }) :: Types.Audio + t:check(near(at(m, 50, 0), at(sine, 50, 0) * 0.75, 1e-6), "mix with weights") + local m2 = AudioOps.mix({ c, sine }) :: Types.Audio + t:check(m2.frames == 8000, "mix is as long as the longest") + local fd = AudioOps.fade(sine, 0.5, 0.5) :: Types.Audio + t:check(at(fd, 0, 0) == 0 and near(at(fd, 2000, 0), at(sine, 2000, 0) * 0.5, 1e-6) and near(at(fd, 7999, 0), 0), "fades") +end + +-- bad arguments: Err.ARG, never a throw +do + local junk: { any } = { nil, 5, "x", {}, { kind = "audio" }, Types.Image.new(2, 2) } + local calls = { + function(v: any) return AudioOps.gain(v, 2) end, + function(v: any) return AudioOps.remix(v, 2) end, + function(v: any) return AudioOps.resample(v, 44100) end, + function(v: any) return AudioOps.trim(v, 0) end, + function(v: any) return AudioOps.concat({ v }) end, + function(v: any) return AudioOps.mix(v) end, + function(v: any) return AudioOps.peak(v) end, + function(v: any) return AudioOps.fade(v, 1) end, + } + local ok = true + for _, fn in calls do + for i = 1, #junk + 1 do + local s, r, e = pcall(fn, junk[i]) + ok = ok and s and r == nil and type(e) == "table" and e.code ~= nil + end + end + t:check(ok, "bad values return nil, Err") + t:check(AudioOps.gain(sine, 0 / 0) == nil, "NaN gain") + t:check(AudioOps.resample(sine, 0) == nil, "zero rate") + t:check(AudioOps.remix(sine, 0) == nil, "zero channels") +end + +-- the F.ops facade +do + t:check(F.ops.audio == AudioOps, "F.ops.audio") + t:check(F.ops.image ~= nil and type(F.ops.image.resize) == "function", "F.ops.image") + t:check(type(F.ops.mesh.merge) == "function", "F.ops.mesh") + t:check(type(F.ops.layers.flatten) == "function", "F.ops.layers") + local v, err = F.load('') + t:check(v, "svg loads: " .. tostring(err)) + local img, rerr = F.ops.vector.rasterize(v, 8, 8) + t:check(img and img.width == 8 and buffer.readu8(img.pixels, 0) == 255 and buffer.readu8(img.pixels, 1) == 0, "F.ops.vector.rasterize: " .. tostring(rerr)) + t:check(F.ops.nothing == nil, "unknown ops: nil") +end + +-- (no decoder here: the no-throw pass is the bad-arguments block above) +t:done()