From 9bd77e54943d954291b5faef287ccca5dcebd7a4 Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Tue, 17 Nov 2026 00:15:15 -0300 Subject: examples: micscope and spheres come home, as they were, building Both lived outside any repository, beside sketchbook, with manifests that pointed at ../01-drat-meout/lib/sketchbook, which no longer exists. They are copied into examples/micscope and examples/spheres (their sources, shaders, tests, test material and web icons; not their caches, builds, packages, state files or .gitignore, which the root's covers), their manifests depend on "../.." as the other examples do, and their READMEs link sketchbook there. Nothing else changed: both build against today's library and pass their own zig build test (micscope 62/62 steps, 11/11 tests, its transport, record, render and tuner scripts; spheres 75/75 steps, 3/3 tests, its play script). The originals are untouched. micscope's test/reference.flac (3.7 MiB, CC BY-SA 3.0, credited in its test/README.md) is the rendering reference its render script opens. The README lists both examples. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T --- examples/micscope/src/tuner.zig | 147 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 147 insertions(+) create mode 100644 examples/micscope/src/tuner.zig (limited to 'examples/micscope/src/tuner.zig') diff --git a/examples/micscope/src/tuner.zig b/examples/micscope/src/tuner.zig new file mode 100644 index 0000000..92a8482 --- /dev/null +++ b/examples/micscope/src/tuner.zig @@ -0,0 +1,147 @@ +//! From pitch estimates (tuner.comp's YIN, one per frame) to a steady note on +//! the 12-tone equal-tempered chromatic scale, for any instrument: notes are +//! MIDI numbers (69 is A4, at `a4` Hz), so the range is whatever the +//! detector finds, from a bass's low B to a piccolo's top. +//! +//! Raw estimates jitter and, at a note's attack or release, misfire. So: +//! unclear or quiet estimates are ignored; the median of the last few +//! clear ones is followed, smoothed; a jump of over a semitone restarts the +//! median, so a new note shows at once; and the note shown only changes +//! once the pitch is 60 cents from it, so a note held a quarter tone sharp +//! does not flicker between two names. +const std = @import("std"); +const layouts = @import("layouts"); + +pub const names = [12][]const u8{ "C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B" }; + +/// Estimates clearer than this are a note (YIN's threshold is 0.12, so +/// clarity 0.88 at least when its first dip was found). +pub const min_clarity = 0.85; +/// Quieter than this is silence, dBFS. +pub const min_level = -60.0; +/// How long the last note stays (shown as fading) after the sound stops. +pub const hold_seconds = 1.0; + +/// Fractional MIDI number of `freq`. +pub fn midi(freq: f32, a4: f32) f32 { + return 69 + 12 * std.math.log2(freq / a4); +} + +pub fn frequency(m: f32, a4: f32) f32 { + return a4 * std.math.pow(f32, 2, (m - 69) / 12); +} + +pub fn name(note: i32) []const u8 { + return names[@intCast(@mod(note, 12))]; +} + +pub fn octave(note: i32) i32 { + return @divFloor(note, 12) - 1; +} + +pub const Reading = struct { + /// The note it is nearest, as a MIDI number. + note: i32, + /// The pitch, as a fractional MIDI number. + pitch: f32, + /// Seconds since a clear estimate: 0 while the note sounds. + quiet: f32, + + pub fn cents(r: Reading) f32 { + return (r.pitch - @as(f32, @floatFromInt(r.note))) * 100; + } +}; + +pub const Tracker = struct { + recent: [5]f32 = @splat(0), + count: u32 = 0, + reading: ?Reading = null, + + pub fn feed(t: *Tracker, p: layouts.Pitch, a4: f32, dt: f32) void { + const clear = p.freq > 0 and p.clarity >= min_clarity and p.level >= min_level; + if (!clear) { + t.count = 0; + if (t.reading) |*r| { + r.quiet += dt; + if (r.quiet > hold_seconds) t.reading = null; + } + return; + } + const m = midi(p.freq, a4); + if (t.count > 0 and @abs(m - t.median()) > 1) t.count = 0; + if (t.count == t.recent.len) { + std.mem.copyForwards(f32, t.recent[0 .. t.recent.len - 1], t.recent[1..]); + t.count -= 1; + } + t.recent[t.count] = m; + t.count += 1; + const target = t.median(); + + const fresh = t.count == 1 or t.reading == null or t.reading.?.quiet > 0; + var r: Reading = if (fresh) .{ .note = @intFromFloat(@round(target)), .pitch = target, .quiet = 0 } else t.reading.?; + r.pitch += (target - r.pitch) * 0.4; + r.quiet = 0; + if (@abs(r.pitch - @as(f32, @floatFromInt(r.note))) > 0.6) r.note = @intFromFloat(@round(r.pitch)); + t.reading = r; + } + + fn median(t: *const Tracker) f32 { + var sorted = t.recent; + std.mem.sort(f32, sorted[0..t.count], {}, std.sort.asc(f32)); + return sorted[t.count / 2]; + } +}; + +fn pitchOf(freq: f32) layouts.Pitch { + return .{ .freq = freq, .clarity = 0.97, .level = -20, .period = 48_000 / freq }; +} + +test "notes and octaves on the chromatic scale" { + try std.testing.expectApproxEqAbs(@as(f32, 69), midi(440, 440), 1e-4); + try std.testing.expectApproxEqAbs(@as(f32, 40), midi(82.4069, 440), 1e-3); + try std.testing.expectEqualStrings("E", name(40)); + try std.testing.expectEqual(@as(i32, 2), octave(40)); + try std.testing.expectEqualStrings("B", name(23)); + try std.testing.expectEqual(@as(i32, 0), octave(23)); + try std.testing.expectApproxEqAbs(@as(f32, 261.626), frequency(60, 440), 1e-2); + // Another reference pitch moves every note with it. + try std.testing.expectApproxEqAbs(@as(f32, 69), midi(442, 442), 1e-4); +} + +test "a held note settles, in cents from it" { + var t: Tracker = .{}; + // A4, 12 cents sharp. + const sharp = frequency(69.12, 440); + for (0..20) |_| t.feed(pitchOf(sharp), 440, 1.0 / 60.0); + const r = t.reading.?; + try std.testing.expectEqual(@as(i32, 69), r.note); + try std.testing.expectApproxEqAbs(@as(f32, 12), r.cents(), 0.5); +} + +test "one wild estimate does not move the note" { + var t: Tracker = .{}; + for (0..10) |_| t.feed(pitchOf(110), 440, 1.0 / 60.0); + t.feed(pitchOf(220), 440, 1.0 / 60.0); + t.feed(pitchOf(110), 440, 1.0 / 60.0); + try std.testing.expectEqual(@as(i32, 45), t.reading.?.note); +} + +test "a new note shows at once, a quarter tone does not flicker" { + var t: Tracker = .{}; + for (0..10) |_| t.feed(pitchOf(110), 440, 1.0 / 60.0); + for (0..3) |_| t.feed(pitchOf(146.83), 440, 1.0 / 60.0); + try std.testing.expectEqual(@as(i32, 50), t.reading.?.note); + // 55 cents sharp of D3 stays D3. + for (0..30) |_| t.feed(pitchOf(frequency(50.55, 440)), 440, 1.0 / 60.0); + try std.testing.expectEqual(@as(i32, 50), t.reading.?.note); +} + +test "silence holds the note a while, then lets go" { + var t: Tracker = .{}; + for (0..10) |_| t.feed(pitchOf(330), 440, 1.0 / 60.0); + const quiet: layouts.Pitch = .{ .freq = 0, .clarity = 0, .level = -120, .period = 0 }; + for (0..30) |_| t.feed(quiet, 440, 1.0 / 60.0); + try std.testing.expect(t.reading != null); + for (0..60) |_| t.feed(quiet, 440, 1.0 / 60.0); + try std.testing.expect(t.reading == null); +} -- cgit v1.3