Something went wrong. Try again.
Sample-rate conversion for audio in Zig: any rate to any other, as a stream
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Sample-rate conversion for audio: any rate to any other, interleaved//! `f32`, as a stream.//!//! This is bandlimited interpolation as Julius O. Smith describes it. Each//! output sample is the input's value at a moment between its samples, found//! by weighting the input samples around that moment by a windowed sinc --//! the ideal lowpass filter, cut off at the lower of the two rates' Nyquist//! frequencies, and shaped by a Kaiser window so that it ends. Going down in//! rate, the filter is stretched by the ratio, so that what the new rate//! cannot carry is filtered out rather than folded back in.//!//! The filter is kept as a table, 512 values between each of its zero//! crossings, and read between them linearly. So there is one table//! whatever the ratio, and the ratio need not be a tidy fraction: 44 100 to//! 48 000 and 44 100 to 44 101 cost the same. Where the output falls//! between input samples is kept exactly, as a count in units of one output//! rate's worth of input, so a stream of any length never drifts.//!//! ```zig//! var r: Resampler = try .init(gpa, .{ .in_rate = 44100, .out_rate = 48000, .channels = 2 });//! defer r.deinit();//! const done = r.process(input, output); // frames consumed and produced//! // ... and at the end, until it gives no more://! const tail = r.flush(output);//! ```//!//! After `flush`, the output is exactly `outputFrames(input frames)` long,//! and aligned with the input: the first output sample is the input's value//! at its first sample. Equal rates are a copy.
const std = @import("std");const assert = std.debug.assert;
/// How much work to spend, and on what.pub const Quality = enum { /// Sixteen zero crossings each side; stopband about 70 dB down. fast, /// Thirty-two; about 90 dB down, and flat to 94% of the band. medium, /// Sixty-four; about 120 dB down, flat to 96% of the band. best,
const Params = struct { /// Zero crossings of the sinc on each side of its centre. zero_crossings: u32, /// The Kaiser window's β: its sidelobes fall about 8.7 + β / 0.1102 /// dB below the main lobe. beta: f64, /// Where the passband ends, as a fraction of the lower rate's /// Nyquist frequency: the transition band is what is left. rolloff: f64, };
fn params(q: Quality) Params { return switch (q) { .fast => .{ .zero_crossings = 16, .beta = 7.0, .rolloff = 0.90 }, .medium => .{ .zero_crossings = 32, .beta = 9.0, .rolloff = 0.94 }, .best => .{ .zero_crossings = 64, .beta = 12.0, .rolloff = 0.96 }, }; }};
/// Table entries between two zero crossings of the filter.pub const phases = 512;
pub const Options = struct { in_rate: u32, out_rate: u32, channels: u16, quality: Quality = .medium,};
pub const Error = error{ InvalidRate, InvalidChannels } || std.mem.Allocator.Error;
/// The highest rate accepted: far above any audio's, and low enough that/// every product of two rates and a frame count this does fits in 64 bits.pub const max_rate = 1 << 24;
pub const Resampler = struct { gpa: std.mem.Allocator, in_rate: u32, out_rate: u32, channels: u16,
/// The filter's right half, `sinc × Kaiser`, `phases` values a zero /// crossing, with a zero on the end so that reading between the last two /// needs no test. Empty for equal rates. table: []f32, /// The filter's cutoff, in cycles per input sample times two: it is /// stretched by 1 / `scale` in input samples. scale: f64, /// Input frames either side of an output's moment that the filter /// reaches. radius: usize,
/// Input not yet done with, interleaved: history the filter still /// reaches back to, and what is ahead of the next output. buf: []f32, /// Frames in `buf`. buf_frames: usize = 0, /// Where the next output falls, from the start of `buf`, in input /// frames times `out_rate`: the frame is `pos / out_rate` and what is /// left over is how far on towards the next. pos: u64 = 0,
/// Frames taken, and frames given, since the start or the last reset. in_total: u64 = 0, out_total: u64 = 0, flushing: bool = false,
pub const Done = struct { /// Input frames taken; the rest of the input is the caller's again. consumed: usize, /// Output frames written. produced: usize, };
pub fn init(gpa: std.mem.Allocator, options: Options) Error!Resampler { if (options.in_rate == 0 or options.out_rate == 0) return error.InvalidRate; if (options.in_rate > max_rate or options.out_rate > max_rate) return error.InvalidRate; if (options.channels == 0) return error.InvalidChannels;
var r: Resampler = .{ .gpa = gpa, .in_rate = options.in_rate, .out_rate = options.out_rate, .channels = options.channels, .table = &.{}, .scale = 1, .radius = 0, .buf = &.{}, }; if (options.in_rate == options.out_rate) return r;
const p = options.quality.params(); const ratio = @as(f64, @floatFromInt(options.out_rate)) / @as(f64, @floatFromInt(options.in_rate)); r.scale = p.rolloff * @min(1.0, ratio); r.radius = @intFromFloat(@ceil(@as(f64, @floatFromInt(p.zero_crossings)) / r.scale));
const len = p.zero_crossings * phases; r.table = try gpa.alloc(f32, len + 2); errdefer gpa.free(r.table); const bessel_beta = besselI0(p.beta); for (r.table[0 .. len + 1], 0..) |*t, n| { const x = @as(f64, @floatFromInt(n)) / phases; const w = x / @as(f64, @floatFromInt(p.zero_crossings)); const window = besselI0(p.beta * @sqrt(@max(0, 1 - w * w))) / bessel_beta; t.* = @floatCast(sinc(x) * window); } r.table[len + 1] = 0;
// Room for the filter's reach both ways and a block to work on. const frames = 2 * r.radius + block_frames; r.buf = try gpa.alloc(f32, frames * options.channels); r.reset(); return r; }
pub fn deinit(r: *Resampler) void { r.gpa.free(r.table); r.gpa.free(r.buf); r.* = undefined; }
/// Back to the start, as if nothing had gone in. pub fn reset(r: *Resampler) void { r.in_total = 0; r.out_total = 0; r.flushing = false; if (r.passthrough()) return; // The filter reaches back past the first sample: it finds silence. @memset(r.buf[0 .. r.radius * r.channels], 0); r.buf_frames = r.radius; r.pos = @as(u64, r.radius) * r.out_rate; }
fn passthrough(r: *const Resampler) bool { return r.in_rate == r.out_rate; }
/// How many output frames `frames` input frames make, all told. pub fn outputFrames(r: *const Resampler, frames: u64) u64 { return std.math.divCeil(u64, frames * r.out_rate, r.in_rate) catch unreachable; }
/// How far the output trails the input, in input frames: that much more /// has to go in before an output reaches a given input sample. pub fn delayFrames(r: *const Resampler) usize { return r.radius; }
/// Take what input it can and make what output it can, both /// interleaved, whole frames only. Returns how much of each; call again /// with the rest of the input when the output fills. pub fn process(r: *Resampler, input: []const f32, output: []f32) Done { assert(!r.flushing); const ch = r.channels; const in_frames = input.len / ch; const out_frames = output.len / ch; if (r.passthrough()) { const n = @min(in_frames, out_frames); @memcpy(output[0 .. n * ch], input[0 .. n * ch]); r.in_total += n; r.out_total += n; return .{ .consumed = n, .produced = n }; }
var consumed: usize = 0; var produced: usize = 0; while (true) { produced += r.produce(output[produced * ch .. out_frames * ch]); if (produced == out_frames) break; // Out of input ahead of the next output: take more. const took = r.take(input[consumed * ch .. in_frames * ch]); if (took == 0) break; consumed += took; } r.in_total += consumed; return .{ .consumed = consumed, .produced = produced }; }
/// The last of the output: what the input so far makes once the filter /// has run past its end on silence. Call until it returns 0; after it, /// `reset` before going on. pub fn flush(r: *Resampler, output: []f32) usize { r.flushing = true; if (r.passthrough()) return 0; const ch = r.channels; const want = r.outputFrames(r.in_total); const out_frames = @min(output.len / ch, want - r.out_total); var produced: usize = 0; while (produced < out_frames) { const made = r.produce(output[produced * ch .. out_frames * ch]); produced += made; if (produced == out_frames) break; if (made == 0) { // Silence after the end, so that the last outputs can be // reckoned; it is not input, and is not counted as any. // Room first, by dropping what is done with. _ = r.take(&.{}); const room = r.buf.len / ch - r.buf_frames; const n = @min(room, r.radius); @memset(r.buf[r.buf_frames * ch ..][0 .. n * ch], 0); r.buf_frames += n; } } return produced; }
/// Copy what fits of `input` into the buffer, first making room by /// dropping what the next output no longer reaches. Returns frames /// taken. fn take(r: *Resampler, input: []const f32) usize { const ch = r.channels; const next: usize = @intCast(r.pos / r.out_rate); const keep_from = (next + 1) -| r.radius; if (keep_from > 0) { const rest = r.buf_frames - keep_from; std.mem.copyForwards(f32, r.buf[0 .. rest * ch], r.buf[keep_from * ch .. r.buf_frames * ch]); r.buf_frames = rest; r.pos -= @as(u64, keep_from) * r.out_rate; } const room = r.buf.len / ch - r.buf_frames; const n = @min(room, input.len / ch); @memcpy(r.buf[r.buf_frames * ch ..][0 .. n * ch], input[0 .. n * ch]); r.buf_frames += n; return n; }
/// Make every output the buffer has the input for, up to `output`'s /// room. Returns frames made. fn produce(r: *Resampler, output: []f32) usize { const ch = r.channels; const room = output.len / ch; const in_rate: u64 = r.in_rate; const out_rate: u64 = r.out_rate; const zc_len: f64 = @floatFromInt(r.table.len - 2); var made: usize = 0; while (made < room) { const center: usize = @intCast(r.pos / out_rate); // The filter reaches `radius` frames past the centre. if (center + r.radius >= r.buf_frames) break; // A flush stops at the last output the input makes. if (r.flushing and r.out_total >= r.outputFrames(r.in_total)) break; const frac = @as(f64, @floatFromInt(r.pos % out_rate)) / @as(f64, @floatFromInt(out_rate));
const out = output[made * ch ..][0..ch]; @memset(out, 0); const first = center + 1 - r.radius; for (first..center + r.radius + 1) |j| { // How far this input sample is from the output's moment, // in the filter's own units. const d = @abs((@as(f64, @floatFromInt(j)) - @as(f64, @floatFromInt(center))) - frac) * r.scale; const x = d * phases; if (x >= zc_len) continue; const i: usize = @intFromFloat(x); const f: f32 = @floatCast(x - @as(f64, @floatFromInt(i))); const c = (r.table[i] + f * (r.table[i + 1] - r.table[i])) * @as(f32, @floatCast(r.scale)); const frame = r.buf[j * ch ..][0..ch]; for (out, frame) |*o, s| o.* += c * s; } made += 1; r.out_total += 1; r.pos += in_rate; } return made; }};
/// Input frames worked through between making room: small enough to stay/// in cache, large enough that moving the history is rare.const block_frames = 1024;
fn sinc(x: f64) f64 { if (x == 0) return 1; const px = std.math.pi * x; return @sin(px) / px;}
/// The modified Bessel function of the first kind, order zero, by its power/// series, which converges quickly for the arguments a Kaiser window uses.fn besselI0(x: f64) f64 { var sum: f64 = 1; var term: f64 = 1; const q = x * x / 4; var k: f64 = 1; while (k < 200) : (k += 1) { term *= q / (k * k); sum += term; if (term < sum * 1e-17) break; } return sum;}
// --- tests -------------------------------------------------------------------
const testing = std.testing;
/// Resample all of `input` in one go, flushed.fn resampleAll(gpa: std.mem.Allocator, options: Options, input: []const f32) ![]f32 { var r: Resampler = try .init(gpa, options); defer r.deinit(); const frames = input.len / options.channels; const total: usize = @intCast(r.outputFrames(frames)); const out = try gpa.alloc(f32, total * options.channels); errdefer gpa.free(out); var produced: usize = 0; var consumed: usize = 0; while (consumed < frames) { const d = r.process(input[consumed * options.channels ..], out[produced * options.channels ..]); consumed += d.consumed; produced += d.produced; if (d.consumed == 0 and d.produced == 0) return error.Stuck; } while (true) { const n = r.flush(out[produced * options.channels ..]); if (n == 0) break; produced += n; } try testing.expectEqual(total, produced); return out;}
fn sine(gpa: std.mem.Allocator, rate: u32, freq: f64, frames: usize, amplitude: f64) ![]f32 { const out = try gpa.alloc(f32, frames); for (out, 0..) |*s, n| s.* = @floatCast(amplitude * @sin(2 * std.math.pi * freq * @as(f64, @floatFromInt(n)) / @as(f64, @floatFromInt(rate)))); return out;}
/// The output's error against the sine it should be, in dB below its/// amplitude, away from the ends where the filter meets silence.fn errorDb(out: []const f32, rate: u32, freq: f64, amplitude: f64, margin: usize) f64 { var err: f64 = 0; for (out[margin .. out.len - margin], margin..) |s, n| { const want = amplitude * @sin(2 * std.math.pi * freq * @as(f64, @floatFromInt(n)) / @as(f64, @floatFromInt(rate))); err += (s - want) * (s - want); } const rms = @sqrt(err / @as(f64, @floatFromInt(out.len - 2 * margin))); return 20 * std.math.log10(rms / (amplitude / std.math.sqrt2));}
fn rmsDb(out: []const f32, margin: usize, amplitude: f64) f64 { var sum: f64 = 0; for (out[margin .. out.len - margin]) |s| sum += s * s; const rms = @sqrt(sum / @as(f64, @floatFromInt(out.len - 2 * margin))); return 20 * std.math.log10(rms / (amplitude / std.math.sqrt2));}
test "a tone goes from 44.1 to 48 kHz as the same tone" { const gpa = testing.allocator; const in = try sine(gpa, 44100, 1000, 44100, 0.5); defer gpa.free(in); inline for (.{ .{ Quality.fast, -60.0 }, .{ Quality.medium, -80.0 }, .{ Quality.best, -100.0 } }) |c| { const out = try resampleAll(gpa, .{ .in_rate = 44100, .out_rate = 48000, .channels = 1, .quality = c[0] }, in); defer gpa.free(out); try testing.expectEqual(@as(usize, 48000), out.len); try testing.expect(errorDb(out, 48000, 1000, 0.5, 4800) < c[1]); }}
test "going down, what the new rate cannot carry is filtered out, and what it can is kept" { const gpa = testing.allocator; // 6 kHz is past 8 kHz's Nyquist frequency: it must not fold back to 2. const high = try sine(gpa, 48000, 6000, 48000, 0.5); defer gpa.free(high); const gone = try resampleAll(gpa, .{ .in_rate = 48000, .out_rate = 8000, .channels = 1 }, high); defer gpa.free(gone); try testing.expectEqual(@as(usize, 8000), gone.len); try testing.expect(rmsDb(gone, 800, 0.5) < -80);
// 3 kHz is inside it, below the rolloff: kept, and as itself. const low = try sine(gpa, 48000, 3000, 48000, 0.5); defer gpa.free(low); const kept = try resampleAll(gpa, .{ .in_rate = 48000, .out_rate = 8000, .channels = 1 }, low); defer gpa.free(kept); try testing.expect(@abs(rmsDb(kept, 800, 0.5)) < 0.01); try testing.expect(errorDb(kept, 8000, 3000, 0.5, 800) < -60);}
test "channels are kept apart, and a ratio that is no tidy fraction costs nothing" { const gpa = testing.allocator; const frames = 22050; const left = try sine(gpa, 44100, 440, frames, 0.25); defer gpa.free(left); const right = try sine(gpa, 44100, 5000, frames, 0.5); defer gpa.free(right); const in = try gpa.alloc(f32, 2 * frames); defer gpa.free(in); for (0..frames) |n| { in[2 * n] = left[n]; in[2 * n + 1] = right[n]; } const out = try resampleAll(gpa, .{ .in_rate = 44100, .out_rate = 44101, .channels = 2 }, in); defer gpa.free(out); const out_frames = out.len / 2; try testing.expectEqual(@as(usize, 22051), out_frames); const l = try gpa.alloc(f32, out_frames); defer gpa.free(l); const r = try gpa.alloc(f32, out_frames); defer gpa.free(r); for (0..out_frames) |n| { l[n] = out[2 * n]; r[n] = out[2 * n + 1]; } try testing.expect(errorDb(l, 44101, 440, 0.25, 2205) < -80); try testing.expect(errorDb(r, 44101, 5000, 0.5, 2205) < -80);}
test "fed in any pieces, the output is the same, bit for bit" { const gpa = testing.allocator; const in = try sine(gpa, 48000, 997, 9000, 0.7); defer gpa.free(in); const options: Options = .{ .in_rate = 48000, .out_rate = 44100, .channels = 1, .quality = .fast }; const whole = try resampleAll(gpa, options, in); defer gpa.free(whole);
var r: Resampler = try .init(gpa, options); defer r.deinit(); const out = try gpa.alloc(f32, whole.len); defer gpa.free(out); var prng: std.Random.DefaultPrng = .init(1); const random = prng.random(); var consumed: usize = 0; var produced: usize = 0; while (consumed < in.len) { const give = @min(in.len - consumed, random.uintAtMost(usize, 700)); const room = @min(out.len - produced, random.uintAtMost(usize, 300)); const d = r.process(in[consumed..][0..give], out[produced..][0..room]); consumed += d.consumed; produced += d.produced; } while (true) { const n = r.flush(out[produced..][0..@min(out.len - produced, 7)]); if (n == 0) break; produced += n; } try testing.expectEqual(whole.len, produced); try testing.expectEqualSlices(f32, whole, out);}
test "equal rates are a copy; nothing in is nothing out" { const gpa = testing.allocator; const in = [_]f32{ 0.1, -0.2, 0.3, -0.4 }; const out = try resampleAll(gpa, .{ .in_rate = 48000, .out_rate = 48000, .channels = 2 }, &in); defer gpa.free(out); try testing.expectEqualSlices(f32, &in, out); const empty = try resampleAll(gpa, .{ .in_rate = 44100, .out_rate = 48000, .channels = 2 }, &.{}); defer gpa.free(empty); try testing.expectEqual(@as(usize, 0), empty.len);}
test "the first output is the input's first sample, not the filter's start" { const gpa = testing.allocator; // A step: the output reaches the step's level at the moment it steps, // give or take the filter's ringing, not a radius later. var in: [4800]f32 = @splat(0); for (in[2400..]) |*s| s.* = 1; const out = try resampleAll(gpa, .{ .in_rate = 48000, .out_rate = 96000, .channels = 1 }, &in); defer gpa.free(out); // The step is between input samples 2399 and 2400: halfway, at twice // the rate, is output 4799. try testing.expect(@abs(out[4799] - 0.5) < 0.01); try testing.expect(@abs(out[4700]) < 0.01); try testing.expect(@abs(out[4900] - 1) < 0.01);}
test "rates and channels it will not take" { try testing.expectError(error.InvalidRate, Resampler.init(testing.allocator, .{ .in_rate = 0, .out_rate = 48000, .channels = 1 })); try testing.expectError(error.InvalidRate, Resampler.init(testing.allocator, .{ .in_rate = 48000, .out_rate = max_rate + 1, .channels = 1 })); try testing.expectError(error.InvalidChannels, Resampler.init(testing.allocator, .{ .in_rate = 44100, .out_rate = 48000, .channels = 0 }));}