358 lines
10 KiB
Luau
358 lines
10 KiB
Luau
--!strict
|
|
--!native
|
|
--!optimize 2
|
|
-- codecs/audio/Resample: sample-rate conversion by band-limited (Kaiser-windowed sinc) polyphase interpolation.
|
|
-- New in rosetta.
|
|
--
|
|
-- The filter is a polyphase table: exact phases when to / gcd(from, to) <= 4096 (44100 <-> 48000: 160 phases),
|
|
-- else 4096 phases with linear interpolation between them. Each phase is normalised to unit DC gain. The cutoff is a
|
|
-- fraction (default 0.97) of the lower Nyquist frequency.
|
|
--
|
|
-- quality zero crossings per side Kaiser beta stop band
|
|
-- "low" 8 6 ~ -60 dB
|
|
-- "medium" 16 (default) 8 ~ -80 dB
|
|
-- "high" 32 10 ~ -100 dB
|
|
--
|
|
-- Output frame j sits at input time j * from / to (centred filter, zero outside the input); n input frames give
|
|
-- floor(n * to / from + 0.5) output frames.
|
|
local Resample = {}
|
|
|
|
export type Options = {
|
|
quality: ("low" | "medium" | "high")?,
|
|
cutoff: number?,
|
|
}
|
|
|
|
export type Resampler = {
|
|
from: number,
|
|
to: number,
|
|
channels: number,
|
|
process: (self: Resampler, src: buffer, frames: number, out: buffer?) -> (buffer, number),
|
|
flush: (self: Resampler, out: buffer?) -> (buffer, number),
|
|
}
|
|
|
|
local QUALITY = { low = { 8, 6 }, medium = { 16, 8 }, high = { 32, 10 } }
|
|
local MAX_EXACT = 4096
|
|
local INTERP_PHASES = 4096
|
|
|
|
local floor, sin, pi, sqrt, max, min = math.floor, math.sin, math.pi, math.sqrt, math.max, math.min
|
|
local readf32, writef32 = buffer.readf32, buffer.writef32
|
|
|
|
local function besselI0(x: number): number
|
|
local sum, term = 1, 1
|
|
for k = 1, 80 do
|
|
term *= (x / (2 * k)) ^ 2
|
|
sum += term
|
|
if term < sum * 1e-16 then
|
|
break
|
|
end
|
|
end
|
|
return sum
|
|
end
|
|
|
|
local function gcd(a: number, b: number): number
|
|
while b ~= 0 do
|
|
a, b = b, a % b
|
|
end
|
|
return a
|
|
end
|
|
|
|
type Filter = {
|
|
taps: number,
|
|
half: number,
|
|
phases: number,
|
|
exact: boolean,
|
|
h: { number }, -- phase p, tap k: h[p * taps + k + 1]
|
|
}
|
|
|
|
-- phase p: an output p / phases past an input sample; tap k multiplies input floor(t) - half + 1 + k
|
|
local function makeFilter(ratio: number, phases: number, exact: boolean, zc: number, beta: number, cut: number): Filter
|
|
local cutoff = cut * min(1, ratio)
|
|
local width = zc / cutoff -- in input samples, each side
|
|
local half = math.ceil(width)
|
|
local taps = 2 * half
|
|
local i0b = besselI0(beta)
|
|
local n = if exact then phases else phases + 1
|
|
local h = table.create(n * taps, 0)
|
|
for p = 0, n - 1 do
|
|
local frac = p / phases
|
|
local sum = 0
|
|
local base = p * taps
|
|
for k = 0, taps - 1 do
|
|
local d = (k - half + 1) - frac -- input position minus output position
|
|
local r = d / width
|
|
local v = 0
|
|
if r > -1 and r < 1 then
|
|
local x = d * cutoff
|
|
local s = if x == 0 then 1 else sin(pi * x) / (pi * x)
|
|
v = s * besselI0(beta * sqrt(1 - r * r)) / i0b
|
|
end
|
|
h[base + k + 1] = v
|
|
sum += v
|
|
end
|
|
if sum ~= 0 then
|
|
for k = 1, taps do
|
|
h[base + k] /= sum
|
|
end
|
|
end
|
|
end
|
|
return { taps = taps, half = half, phases = phases, exact = exact, h = h }
|
|
end
|
|
|
|
type State = {
|
|
from: number,
|
|
to: number,
|
|
channels: number,
|
|
f: Filter,
|
|
step: number, -- M = from / g: the input advance per output frame, in units of 1 / L
|
|
L: number, -- to / g
|
|
hist: { number },
|
|
histFrames: number,
|
|
base: number,
|
|
inFrames: number,
|
|
outPos: number,
|
|
done: boolean,
|
|
process: any,
|
|
flush: any,
|
|
}
|
|
|
|
local function run(st: State, limitOut: number, out: buffer?): (buffer, number)
|
|
local f = st.f
|
|
local taps, half, h = f.taps, f.half, f.h
|
|
local ch = st.channels
|
|
local hist, base, histFrames = st.hist, st.base, st.histFrames
|
|
local L, M = st.L, st.step
|
|
local j0 = st.outPos
|
|
-- outputs j with floor(j * M / L) - half + taps <= available frames (zero beyond the end after flush)
|
|
local avail = base + histFrames
|
|
local jmax = limitOut
|
|
if not st.done then
|
|
-- the last tap must be buffered: floor(j * M / L) + half <= avail - 1, i.e. j * M < (avail - half) * L
|
|
local lim = floor(((avail - half) * L - 1) / M)
|
|
if lim + 1 < jmax then
|
|
jmax = lim + 1
|
|
end
|
|
end
|
|
local n = jmax - j0
|
|
if n <= 0 then
|
|
return out or buffer.create(0), 0
|
|
end
|
|
local bytes = n * ch * 4
|
|
local b = if out and buffer.len(out) >= bytes then out else buffer.create(bytes)
|
|
local exact = f.exact
|
|
local phases = f.phases
|
|
local o = 0
|
|
for j = j0, jmax - 1 do
|
|
local num = j * M
|
|
local ip = num // L -- floor(t)
|
|
local first = ip - half + 1
|
|
local rel = first - base
|
|
local kLo = if rel < 0 then -rel else 0
|
|
local kHi = taps - 1
|
|
if rel + kHi >= histFrames then
|
|
kHi = histFrames - 1 - rel
|
|
end
|
|
if exact then
|
|
local hb = (num - ip * L) * taps + 1 -- phase * taps + 1
|
|
for c = 0, ch - 1 do
|
|
local acc = 0
|
|
local hi = (rel + kLo) * ch + c + 1
|
|
for k = kLo, kHi do
|
|
acc += hist[hi] * h[hb + k]
|
|
hi += ch
|
|
end
|
|
writef32(b, o, acc)
|
|
o += 4
|
|
end
|
|
else
|
|
local fp = (num - ip * L) / L * phases
|
|
local p = floor(fp)
|
|
local a = fp - p
|
|
local hb = p * taps + 1
|
|
local hb2 = hb + taps
|
|
for c = 0, ch - 1 do
|
|
local acc, acc2 = 0, 0
|
|
local hi = (rel + kLo) * ch + c + 1
|
|
for k = kLo, kHi do
|
|
local x = hist[hi]
|
|
acc += x * h[hb + k]
|
|
acc2 += x * h[hb2 + k]
|
|
hi += ch
|
|
end
|
|
writef32(b, o, acc + (acc2 - acc) * a)
|
|
o += 4
|
|
end
|
|
end
|
|
end
|
|
st.outPos = jmax
|
|
local keepFrom = (jmax * M) // L - half + 1
|
|
local drop = keepFrom - base
|
|
if drop > 0 then
|
|
if drop >= histFrames then
|
|
st.hist = {}
|
|
st.histFrames = 0
|
|
st.base = base + histFrames
|
|
else
|
|
local nh: { number } = table.create((histFrames - drop) * ch) :: any
|
|
table.move(hist, drop * ch + 1, histFrames * ch, 1, nh)
|
|
st.hist = nh
|
|
st.histFrames = histFrames - drop
|
|
st.base = base + drop
|
|
end
|
|
end
|
|
return b, n
|
|
end
|
|
|
|
local function process(self: State, src: buffer, frames: number, out: buffer?): (buffer, number)
|
|
if self.done or type(src) ~= "buffer" or type(frames) ~= "number" or frames <= 0 then
|
|
return out or buffer.create(0), 0
|
|
end
|
|
local ch = self.channels
|
|
frames = min(floor(frames), buffer.len(src) // (ch * 4))
|
|
local hist = self.hist
|
|
local p = self.histFrames * ch
|
|
for i = 0, frames * ch - 1 do
|
|
hist[p + i + 1] = readf32(src, i * 4)
|
|
end
|
|
self.histFrames += frames
|
|
self.inFrames += frames
|
|
return run(self, math.huge, out)
|
|
end
|
|
|
|
local function flush(self: State, out: buffer?): (buffer, number)
|
|
if self.done then
|
|
return out or buffer.create(0), 0
|
|
end
|
|
self.done = true
|
|
local total = floor(self.inFrames * self.to / self.from + 0.5)
|
|
return run(self, total, out)
|
|
end
|
|
|
|
function Resample.new(from: number, to: number, channels: number, opts: Options?): (Resampler?, string?)
|
|
if type(from) ~= "number" or type(to) ~= "number" or from ~= from or to ~= to or from <= 0 or to <= 0 or from > 2 ^ 24 or to > 2 ^ 24 then
|
|
return nil, "bad sample rates"
|
|
end
|
|
if type(channels) ~= "number" or channels < 1 or channels > 256 or channels ~= floor(channels) then
|
|
return nil, "bad channel count"
|
|
end
|
|
local q: { number }? = QUALITY[(opts and opts.quality) or "medium"]
|
|
if not q then
|
|
return nil, "quality must be low, medium or high"
|
|
end
|
|
local cut = (opts and opts.cutoff) or 0.97
|
|
if type(cut) ~= "number" or not (cut >= 0.5 and cut <= 1) then
|
|
return nil, "cutoff must be 0.5 .. 1"
|
|
end
|
|
-- positions are exact integers: output j sits at input j * M / L (non-integer rates: to 1 / 1000 Hz)
|
|
local scale = if from ~= floor(from) or to ~= floor(to) then 1000 else 1
|
|
local fi: number = floor(from * scale + 0.5)
|
|
local ti: number = floor(to * scale + 0.5)
|
|
local g: number = gcd(fi, ti)
|
|
local L: number, M: number = ti // g, fi // g
|
|
local exact = L <= MAX_EXACT
|
|
local phases = if exact then L else INTERP_PHASES
|
|
local st: State = {
|
|
from = from,
|
|
to = to,
|
|
channels = channels,
|
|
-- the same rate: a pass-through (tap 0 is the input frame itself)
|
|
f = if L == 1 and M == 1 then { taps = 2, half = 1, phases = 1, exact = true, h = { 1, 0 } } else makeFilter(to / from, phases, exact, q[1], q[2], cut),
|
|
step = M,
|
|
L = L,
|
|
hist = {},
|
|
histFrames = 0,
|
|
base = 0,
|
|
inFrames = 0,
|
|
outPos = 0,
|
|
done = false,
|
|
process = process,
|
|
flush = flush,
|
|
}
|
|
return st :: any, nil
|
|
end
|
|
|
|
function Resample.buffer(src: buffer, frames: number, channels: number, from: number, to: number, opts: Options?): (buffer?, number | string)
|
|
local rs, err = Resample.new(from, to, channels, opts)
|
|
if not rs then
|
|
return nil, err :: string
|
|
end
|
|
if type(src) ~= "buffer" or type(frames) ~= "number" or frames < 0 or buffer.len(src) < frames * channels * 4 then
|
|
return nil, "the buffer is shorter than frames * channels * 4"
|
|
end
|
|
local total = floor(frames * to / from + 0.5)
|
|
local out = buffer.create(total * channels * 4)
|
|
local got = 0
|
|
local chunk = 65536
|
|
local tmp: buffer? = nil
|
|
local pos = 0
|
|
while pos < frames do
|
|
local n = min(chunk, frames - pos)
|
|
local part = buffer.create(n * channels * 4)
|
|
buffer.copy(part, 0, src, pos * channels * 4, n * channels * 4)
|
|
local b, m = rs:process(part, n, tmp)
|
|
tmp = b
|
|
if m > 0 then
|
|
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
|
|
got += m
|
|
end
|
|
pos += n
|
|
end
|
|
local b, m = rs:flush(tmp)
|
|
if m > 0 then
|
|
buffer.copy(out, got * channels * 4, b, 0, m * channels * 4)
|
|
got += m
|
|
end
|
|
return out, got
|
|
end
|
|
|
|
function Resample.source(src: any, to: number, opts: Options?): (any, string?)
|
|
if type(src) ~= "table" or type(src.read) ~= "function" then
|
|
return nil, "needs a source"
|
|
end
|
|
local rs, err = Resample.new(src.sampleRate, to, src.channels, opts)
|
|
if not rs then
|
|
return nil, err
|
|
end
|
|
local ch = src.channels
|
|
local pending = buffer.create(0)
|
|
local pendingFrames, pendingPos = 0, 0
|
|
local ended = false
|
|
local out = {
|
|
sampleRate = to,
|
|
channels = ch,
|
|
frames = if src.frames > 0 then floor(src.frames * to / src.sampleRate + 0.5) else 0,
|
|
tags = src.tags,
|
|
err = nil :: any,
|
|
}
|
|
local inTmp: buffer? = nil
|
|
function out.read(self: any, n: number, dst: buffer?): (buffer, number)
|
|
n = floor(n)
|
|
while pendingFrames - pendingPos <= 0 and not ended do
|
|
local b: buffer, m: number = (src :: any):read(math.max(1024, floor(n * src.sampleRate / to) + 64), inTmp)
|
|
inTmp = b
|
|
local r: buffer, k: number
|
|
if m <= 0 then
|
|
ended = true
|
|
self.err = src.err
|
|
r, k = rs:flush()
|
|
else
|
|
r, k = rs:process(b, m)
|
|
end
|
|
if k > 0 then
|
|
pending, pendingFrames, pendingPos = r, k, 0
|
|
end
|
|
end
|
|
local k = min(n, pendingFrames - pendingPos)
|
|
if k <= 0 then
|
|
return dst or buffer.create(0), 0
|
|
end
|
|
local bytes = k * ch * 4
|
|
local b = if dst and buffer.len(dst) >= bytes then dst else buffer.create(bytes)
|
|
buffer.copy(b, 0, pending, pendingPos * ch * 4, bytes)
|
|
pendingPos += k
|
|
return b, k
|
|
end
|
|
return out, nil
|
|
end
|
|
|
|
return Resample
|