// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! What a resampler must do with whatever it is handed. //! //! A resampler is handed rates from configuration and devices, channel //! counts from files, and audio in whatever pieces a program happens to //! read it in. So the target is a property rather than an example: for any //! pair of rates, any channel count and quality, and any samples, fed in any //! pieces, //! //! - it takes all the input and, flushed, makes exactly `outputFrames` of //! output; //! - every output sample is finite, and no larger than the filter can make //! from the input's largest; //! - fed in pieces, it makes the same output, bit for bit, as fed whole; //! - it frees what it allocated. //! //! The target is an ordinary test as well: without `--fuzz` it runs the //! seeds below, so `zig build test` checks the property at the rates audio //! comes in. `zig build fuzz --fuzz` mutates those seeds with Zig's //! fuzzer, and `zig build fuzz-run` with the loop in `tools/fuzz.zig`. const std = @import("std"); const builtin = @import("builtin"); const testing = std.testing; const Allocator = std.mem.Allocator; const Smith = std.testing.Smith; const resample = @import("resample"); const Resampler = resample.Resampler; /// Where the target allocates: the test allocator under `zig build test`, /// and one `tools/fuzz.zig` checks for leaks after every input otherwise. pub var backing: Allocator = if (builtin.is_test) testing.allocator else undefined; /// The most output a single input may ask for: rates far apart make a great /// deal of it from a little input, and the property is the same at any /// length. const max_output_frames = 1 << 16; const max_channels = 8; /// Input: the input rate and the output rate as little-endian `u32`s, each /// taken from 1 to 384 000; a byte of channels, 1 to 8; a byte of quality; /// a `u64` seeding the pieces it is fed in; and the rest as little-endian /// `i16` samples, interleaved. fn streamProperty(input: []const u8) !void { if (input.len < 4 + 4 + 1 + 1 + 8) return; const in_rate = 1 + std.mem.readInt(u32, input[0..4], .little) % 384_000; const out_rate = 1 + std.mem.readInt(u32, input[4..8], .little) % 384_000; const channels: u16 = 1 + input[8] % max_channels; const quality: resample.Quality = @fromBackingInt(@intCast(input[9] % 3)); const seed = std.mem.readInt(u64, input[10..18], .little); const data = input[18..]; var frames = data.len / (2 * channels); // No more input than makes `max_output_frames`. frames = @min(frames, max_output_frames * @as(u64, in_rate) / out_rate); const options: resample.Options = .{ .in_rate = in_rate, .out_rate = out_rate, .channels = channels, .quality = quality }; const samples = try backing.alloc(f32, frames * channels); defer backing.free(samples); var largest: f32 = 0; for (samples, 0..) |*s, i| { s.* = @as(f32, @floatFromInt(std.mem.readInt(i16, data[2 * i ..][0..2], .little))) / 32768; largest = @max(largest, @abs(s.*)); } var whole: Resampler = try .init(backing, options); defer whole.deinit(); const total: usize = @intCast(whole.outputFrames(frames)); const once = try backing.alloc(f32, total * channels); defer backing.free(once); try feed(&whole, samples, once, null); // The windowed sinc's taps sum, in magnitude, to well under 4 times // its centre's, whatever the ratio. for (once) |y| { try testing.expect(std.math.isFinite(y)); try testing.expect(@abs(y) <= 4 * largest + 1e-6); } var pieces: Resampler = try .init(backing, options); defer pieces.deinit(); const again = try backing.alloc(f32, total * channels); defer backing.free(again); var prng: std.Random.DefaultPrng = .init(seed); try feed(&pieces, samples, again, prng.random()); try testing.expectEqualSlices(f32, once, again); } /// Resample `samples` into `out`, which must be exactly the right length, /// whole or -- given a source of randomness -- in random pieces with random /// room. fn feed(r: *Resampler, samples: []const f32, out: []f32, random: ?std.Random) !void { const ch = r.channels; const frames = samples.len / ch; const out_frames = out.len / ch; var consumed: usize = 0; var produced: usize = 0; var stalls: usize = 0; while (consumed < frames) { const give = if (random) |rnd| @min(frames - consumed, rnd.uintAtMost(usize, 2048)) else frames - consumed; const room = if (random) |rnd| @min(out_frames - produced, rnd.uintAtMost(usize, 2048)) else out_frames - produced; const d = r.process(samples[consumed * ch ..][0 .. give * ch], out[produced * ch ..][0 .. room * ch]); consumed += d.consumed; produced += d.produced; // Nothing taken or made, with room for both, is stuck. if (d.consumed == 0 and d.produced == 0 and give > 0 and room > 0) return error.Stuck; stalls = if (d.consumed == 0 and d.produced == 0) stalls + 1 else 0; if (stalls > 10_000) return error.Stuck; } while (true) { const room = if (random) |rnd| @min(out_frames - produced, 1 + rnd.uintAtMost(usize, 2048)) else out_frames - produced; const n = r.flush(out[produced * ch ..][0 .. room * ch]); produced += n; if (produced == out_frames) break; if (n == 0 and room > 0) return error.FlushedShort; } // And nothing more after it. var spare: [max_channels]f32 = undefined; try testing.expectEqual(@as(usize, 0), r.flush(spare[0..ch])); try testing.expectEqual(out_frames, produced); } /// A seed: rates, channels, quality, a piece seed, and a stereo-or-more /// tone at a third of the lower Nyquist frequency. fn seedFor(comptime in_rate: u32, comptime out_rate: u32, comptime channels: u8, comptime quality: u8) [18 + 2 * 600]u8 { var out: [18 + 2 * 600]u8 = undefined; std.mem.writeInt(u32, out[0..4], in_rate - 1, .little); std.mem.writeInt(u32, out[4..8], out_rate - 1, .little); out[8] = channels - 1; out[9] = quality; std.mem.writeInt(u64, out[10..18], in_rate ^ out_rate, .little); @setEvalBranchQuota(100_000); for (0..600) |i| { const phase = @as(f64, @floatFromInt(i / channels)) * std.math.pi / 3; const v: i16 = @intFromFloat(@sin(phase) * 20000); std.mem.writeInt(i16, out[18 + 2 * i ..][0..2], v, .little); } return out; } pub const seeds = [_][]const u8{ &seedFor(44100, 48000, 2, 1), &seedFor(48000, 44100, 2, 0), &seedFor(48000, 8000, 1, 2), &seedFor(8000, 48000, 1, 1), &seedFor(96000, 44100, 6, 1), &seedFor(44100, 44101, 2, 1), &seedFor(22050, 192000, 1, 0), &seedFor(48000, 48000, 8, 1), }; test "fuzz streams" { for (seeds) |seed| try streamProperty(seed); try testing.fuzz({}, fuzzStreams, .{}); } fn fuzzStreams(_: void, smith: *Smith) !void { var buffer: [16384]u8 = undefined; try streamProperty(buffer[0..smith.slice(&buffer)]); } // -- the table ----------------------------------------------------------------- /// A target, as `tools/fuzz.zig` drives it. pub const Target = struct { name: []const u8, run: *const fn (input: []const u8) anyerror!void, /// Inputs worth mutating, which stand in for the coverage feedback a /// real fuzzer would have. corpus: []const []const u8, /// The buffer this target reads its input into. `Smith.slice` yields /// an *empty* slice for a length larger than that, not a truncated /// one, so a generator that does not know it feeds the target nothing. content_max: usize, }; fn Driven(comptime one: fn (void, *Smith) anyerror!void) type { return struct { fn run(input: []const u8) anyerror!void { var smith: Smith = .{ .in = input }; return one({}, &smith); } }; } pub const all = [_]Target{ .{ .name = "streams", .run = Driven(fuzzStreams).run, .corpus = &seeds, .content_max = 16384 }, };