--!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/audio/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/audio/Pcm") local Resample = require("@formats/codecs/audio/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: { { number } } = table.create(to) :: any 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: { number }, r: { number } = 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 ~= nil and outIdx.FR ~= nil then local w = TO_STEREO[sp] or { 0, 0 } local fl, fr = outIdx.FL :: number, outIdx.FR :: number m[fl][i] += w[1] m[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/audio/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