Files
rosetta/src/Rosetta/ops/AudioOps.luau
T

477 lines
13 KiB
Luau

--!strict
--!optimize 2
-- ops/AudioOps: editing on the standard Audio: collect, gain, normalize, mix, remix, resample (codecs/audio/Resample),
-- trim, concat, fades, peak / RMS. New code.
-- 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("@rosetta/core/Err")
local Types = require("@rosetta/Types")
local Pcm = require("@rosetta/codecs/audio/Pcm")
local Resample = require("@rosetta/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
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
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
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
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 o = 0, n * 4 - 4, 4 do
writef32(d, o, readf32(s, o) * factor)
end
return out, nil
end
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
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
local last, step = (a.frames - 1) * ch * 4, ch * 4
for c = 1, ch do
local pk = 0
for p = (c - 1) * 4, last + (c - 1) * 4, step do
local v = abs(readf32(s, p))
if v > pk then
pk = v
end
end
per[c] = pk
end
local m = 0
for c = 1, ch do
m = max(m, per[c])
end
return m, per
end
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
local last, step = (a.frames - 1) * ch * 4, ch * 4
for c = 1, ch do
local acc = 0
for p = (c - 1) * 4, last + (c - 1) * 4, step do
local v = readf32(s, p)
acc += v * v
end
per[c] = acc
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
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
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
-- 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 },
}
-- 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
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 frames = a.frames
local inStep, outStep = from * 4, channels * 4
for o = 1, channels do
-- the row's non-zero weights, in input order: v = sum w * x[i]
local row = mm[o]
local ws, offs = {}, {}
for i = 1, from do
local w = row[i]
if w and w ~= 0 then
table.insert(ws, w)
table.insert(offs, (i - 1) * 4)
end
end
local q = (o - 1) * 4
local nt = #ws
if nt == 0 then
for _ = 1, frames do
writef32(d, q, 0)
q += outStep
end
elseif nt == 1 then
local w0, o0 = ws[1], offs[1]
for p = 0, (frames - 1) * inStep, inStep do
writef32(d, q, 0 + w0 * readf32(s, p + o0))
q += outStep
end
elseif nt == 2 then
local w0, o0, w1, o1 = ws[1], offs[1], ws[2], offs[2]
for p = 0, (frames - 1) * inStep, inStep do
writef32(d, q, 0 + w0 * readf32(s, p + o0) + w1 * readf32(s, p + o1))
q += outStep
end
else
for p = 0, (frames - 1) * inStep, inStep do
local v = 0
for t = 1, nt do
v += ws[t] * readf32(s, p + offs[t])
end
writef32(d, q, v)
q += outStep
end
end
end
return out, nil
end
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
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
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
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
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
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
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 o = 0, a.frames * ch * 4 - 4, 4 do
writef32(d, o, readf32(d, o) + readf32(s, o) * w)
end
end
return out, nil
end
return AudioOps