Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / library / ml / src / main / rust / examples / check_gate_audio.rs

check_gate_audio.rs752 lines · 29.9 KiBRaw
1//! Measures what the music gate scores on music, speech, noise and silence — offline, no device.
2//!
3//! ```text
4//! cargo run --offline --release -p modelrunner --example check_gate_audio
5//! cargo run --offline --release -p modelrunner --example check_gate_audio -- song.wav ...
6//! ```
7//!
8//! # What this answers
9//!
10//! Every other check on `gate.rs` is a *layout* check: 8,200 weights in the order the graph
11//! declares them, a forward pass bit-exact against `scripts/ml/gate_reference.py`, a front end
12//! bit-exact against numpy. All of that can pass while the detector is useless, because a
13//! network that has been transcribed correctly and *scaled* wrongly still produces a number
14//! between zero and one for every frame. The unanswered question is empirical: does the score
15//! rise on music and stay down on everything else?
16//!
17//! # Why speech is the control that matters
18//!
19//! Noise and silence are trivial negatives — anything that responds to spectral structure at all
20//! will reject them. Speech is harmonic, band-limited to roughly the same 60–3800 Hz the front
21//! end keeps, and temporally structured, so it is the input that separates a music detector from
22//! an "is there sound" detector. If speech scores where music scores, the reported separation is
23//! not evidence of a working port.
24//!
25//! # Why every signal is RMS-matched
26//!
27//! The front end is a log-mel bank with no per-utterance normalisation, so level walks straight
28//! into the features. Comparing loud synthetic music against quiet synthetic speech would
29//! measure the level difference and report it as discrimination. Everything here is normalised
30//! to the same RMS, and `music_chords` is additionally swept across three levels so the level
31//! sensitivity is visible rather than hidden.
32//!
33//! Synthetic audio is a real limitation and is not the same as recordings; pass WAV paths on the
34//! command line to add real material. 16-bit PCM only, any rate, mono or stereo.
35//!
36//! # What it measured, 2026-09-05
37//!
38//! Run over 12 real recordings (Windows Media ringtones, alarms and chimes), real speech from two
39//! Windows SAPI voices, the ASI APK's audio assets, and a synthetic set, all resampled to 16 kHz
40//! mono and RMS-matched.
41//!
42//! **The gate fires on music and rejects speech, decisively.** Median raw score: real ringtones
43//! 0.69–0.96, real speech 0.0033–0.0048. Under a debounced latch at threshold 0.90 the real music
44//! clips hold the positive state 67–99% of the time and the speech clips hold it 0%. Speech is the
45//! hard negative and the separation there is about as clean as it could be.
46//!
47//! **It does not reject broadband noise.** Pink noise holds 87% duty at threshold 0.58 and still
48//! 80% at 0.98, and 47 s of real keyboard clicks holds 89%. Dropping the noise to −50 dBFS barely
49//! moves it, so this is not an artefact of testing noise at music's level. No threshold separates
50//! music from noise, because the noise score distribution has a long tail into 1.0 rather than a
51//! shifted mean.
52//!
53//! **The shipped latch parameters are unusable as-is**, independent of the threshold.
54//! [`Hysteresis::negative_frames_before_event`] is 1, so at 100 Hz the state drops on a single
55//! dipping frame and immediately re-arms: every input, including silence-adjacent ones, produces
56//! 100–200 positive events per minute. That is why `sweep` reports duty cycle and not event rate.
57//!
58//! # Two earlier conclusions that were wrong, recorded so they are not re-derived
59//!
60//! Against synthetic music alone this harness said the gate ranked pink noise *above* music and
61//! that the port therefore had a weight-layout or scale bug. Both were artefacts of the
62//! synthesiser: `music_chords` scores 0.44 where real ringtones score 0.75–0.96, and
63//! `music_harmonics` — a sustained, perfectly stationary chord — scores 0.04, lower than anything
64//! but silence. Real music is none of those things. Synthetic positives are not a substitute here
65//! and a negative result from them alone should not be trusted.
66//!
67//! The front end is not implicated either way: `features()` shows a flat bank for noise, a
68//! structured one for chords, nothing pinned at the ceiling. And `scripts/ml/gate_reference.py`
69//! cannot arbitrate any of this — the forward pass is already bit-exact against it, so both sides
70//! would reproduce a shared misreading of the flatbuffer identically.
71
72use modelrunner::gate::{probability, Gate, Hysteresis, Latch, CHANNELS, HOP_SAMPLES};
73use modelrunner::microfrontend::{Frontend, NOW_PLAYING};
74
75const RATE: usize = 16_000;
76const SECONDS: usize = 12;
77const SAMPLES: usize = RATE * SECONDS;
78
79/// Full-scale fraction every generated signal is normalised to before quantisation.
80const TARGET_RMS: f32 = 0.1;
81
82fn main() {
83 let mut signals: Vec<(String, Vec<i16>)> = Vec::new();
84
85 for (name, samples) in [
86 ("silence", silence()),
87 ("white_noise", white_noise()),
88 ("pink_noise", pink_noise()),
89 ("noise_low_band", band_noise(60.0, 500.0)),
90 ("noise_high_band", band_noise(2000.0, 3800.0)),
91 ("tone_440", tone()),
92 ("music_harmonics", harmonic_stack()),
93 ("music_chords", chords()),
94 ("music_melody", melody()),
95 ("music_full_mix", full_mix()),
96 ("speech_male", speech(112.0, true)),
97 ("speech_female", speech(196.0, true)),
98 ("speech_continuous", speech(120.0, false)),
99 ("babble_two_voices", babble()),
100 ("am_noise", am_noise()),
101 ] {
102 signals.push((name.to_string(), quantize(&samples, TARGET_RMS)));
103 }
104
105 // The same music at three levels, to show whether the score is tracking loudness.
106 for level in [0.02f32, 0.05, 0.30] {
107 signals.push((format!("music_chords@rms{level:.2}"), quantize(&chords(), level)));
108 }
109
110 // Pink noise at four levels. Everything above is matched at -20 dBFS, which is loud for room
111 // noise and quiet for music, so a noise false-accept measured there may not be one in a real
112 // room. This is the control that says whether the noise problem survives realistic levels.
113 for level in [0.003f32, 0.01, 0.03, 0.10] {
114 signals.push((format!("noise_pink@rms{level:.3}"), quantize(&pink_noise(), level)));
115 }
116
117 for path in std::env::args().skip(1) {
118 // The label drives the grouping in `summarise`, so real files are named with the same
119 // `music_` / `speech_` / `noise_` prefixes the synthetic ones use.
120 let label = std::path::Path::new(&path)
121 .file_stem()
122 .map(|stem| stem.to_string_lossy().into_owned())
123 .unwrap_or_else(|| path.clone());
124 match read_wav(&path) {
125 Ok(samples) => signals.push((label, samples)),
126 Err(error) => println!("skipping {path}: {error}"),
127 }
128 }
129
130 println!(
131 "{:<26} {:>6} {:>7} {:>7} {:>7} {:>7} {:>7} {:>7} {:>7} {:>6} {:>7}",
132 "input", "hops", "min", "mean", "p50", "p90", "max", "sd", "d/hop", "rail%", "events"
133 );
134 println!("{}", "-".repeat(110));
135
136 let mut rows = Vec::new();
137 for (name, pcm) in &signals {
138 let Some(row) = run(pcm) else {
139 println!("{name:<26} too short to warm the gate up");
140 continue;
141 };
142 println!(
143 "{:<26} {:>6} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>7.4} {:>5.1}% {:>7}",
144 name,
145 row.hops,
146 row.min,
147 row.mean,
148 row.p50,
149 row.p90,
150 row.max,
151 row.sd,
152 row.step,
153 row.rail * 100.0,
154 row.events
155 );
156 rows.push((name.clone(), row));
157 }
158
159 println!();
160 summarise(&rows);
161 println!();
162 sweep(&rows);
163 println!();
164 features(&signals);
165 println!();
166 trajectory(&signals);
167}
168
169/// Fraction of time the latch holds the positive state, at a range of positive thresholds.
170///
171/// This is the decision-relevant view, and it is deliberately *not* an event count. The shipped
172/// [`Hysteresis::negative_frames_before_event`] is 1, so at 100 Hz the state drops on a single
173/// dipping frame and re-arms immediately; event rates then land at 100–200 per minute for almost
174/// every input and measure the latch's chatter rather than the threshold. Duty cycle — how much
175/// of the clip the app would believe music is playing — is monotone in the threshold and is what
176/// a caller actually consumes.
177///
178/// `DEBOUNCED` is the same sweep with a hold time, to separate "the threshold is wrong" from
179/// "the latch parameters are wrong".
180fn sweep(rows: &[(String, Row)]) {
181 for (label, hold, band) in [("SHIPPED latch", 1u32, 0.01f32), ("DEBOUNCED latch", 50, 0.05)] {
182 println!("active duty cycle %, {label} (hold {hold} frames, band {band:.2})");
183 let thresholds = [0.50f32, 0.58, 0.70, 0.80, 0.90, 0.95, 0.98];
184 print!("{:<26}", "");
185 for threshold in thresholds {
186 print!("{threshold:>8.2}");
187 }
188 println!();
189 println!("{}", "-".repeat(26 + 8 * thresholds.len()));
190
191 let mut totals = vec![(0.0f32, 0.0f32); thresholds.len()];
192 for (name, row) in rows {
193 print!("{name:<26}");
194 for (column, threshold) in thresholds.iter().enumerate() {
195 let duty = replay(&row.scores, *threshold, hold, band);
196 print!("{:>8.1}", duty * 100.0);
197 // Everything not named `music_` counts against the false-accept budget.
198 let slot = &mut totals[column];
199 if name.starts_with("music_") {
200 slot.0 += duty;
201 } else {
202 slot.1 += duty;
203 }
204 }
205 println!();
206 }
207
208 let music = rows.iter().filter(|(n, _)| n.starts_with("music_")).count() as f32;
209 let other = rows.len() as f32 - music;
210 for (heading, pick) in
211 [("MEAN music (want high)", 0usize), ("MEAN non-music (want low)", 1)]
212 {
213 print!("{heading:<26}");
214 for total in &totals {
215 let (sum, count) = if pick == 0 { (total.0, music) } else { (total.1, other) };
216 print!("{:>8.1}", 100.0 * sum / count);
217 }
218 println!();
219 }
220 println!();
221 }
222}
223
224/// Re-run the latch over an already-computed score stream, returning the active duty cycle.
225fn replay(scores: &[i16], positive_threshold: f32, hold: u32, band: f32) -> f32 {
226 let mut latch = Latch::new(Hysteresis {
227 positive_threshold,
228 negative_threshold: positive_threshold - band,
229 negative_frames_before_event: hold,
230 ..Hysteresis::SHIPPED
231 });
232 let active = scores.iter().filter(|&&score| latch.push(score).active).count();
233 active as f32 / scores.len() as f32
234}
235
236/// The first 40 reported hops of a few inputs, because a distribution hides whether the score is
237/// tracking anything or just rattling. At 100 Hz these forty numbers are 400 ms.
238fn trajectory(signals: &[(String, Vec<i16>)]) {
239 println!("first 40 reported hops (400 ms)");
240 for (name, pcm) in signals {
241 if !matches!(name.as_str(), "white_noise" | "music_chords" | "music_harmonics") {
242 continue;
243 }
244 let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");
245 let mut gate = Gate::new();
246 let mut frames = Vec::new();
247 frontend.process(pcm, &mut frames);
248 let scores: Vec<String> = (0..frames.len() / CHANNELS)
249 .filter_map(|frame| gate.push(&frames[frame * CHANNELS..(frame + 1) * CHANNELS]))
250 .take(40)
251 .map(|score| format!("{:.2}", probability(score)))
252 .collect();
253 println!(" {name:<18} {}", scores.join(" "));
254 }
255}
256
257/// Mean log-mel per channel, so a nonsense score can be attributed to the trunk rather than to
258/// the front end feeding it. A bank pinned at the ceiling or flat across every channel would mean
259/// the harness is wrong, not the gate.
260fn features(signals: &[(String, Vec<i16>)]) {
261 println!("mean log-mel by channel (front-end sanity; ceiling is 15.0)");
262 for (name, pcm) in signals {
263 if !matches!(
264 name.as_str(),
265 "white_noise" | "music_chords" | "music_harmonics" | "speech_male"
266 ) {
267 continue;
268 }
269 let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");
270 let mut frames = Vec::new();
271 frontend.process(pcm, &mut frames);
272 let count = frames.len() / CHANNELS;
273 let mut mean = [0.0f32; CHANNELS];
274 for frame in 0..count {
275 for (channel, slot) in mean.iter_mut().enumerate() {
276 *slot += frames[frame * CHANNELS + channel];
277 }
278 }
279 let line: Vec<String> =
280 mean.iter().step_by(4).map(|total| format!("{:>5.1}", total / count as f32)).collect();
281 println!(" {name:<18} {}", line.join(" "));
282 }
283}
284
285struct Row {
286 hops: usize,
287 min: f32,
288 mean: f32,
289 p50: f32,
290 p90: f32,
291 max: f32,
292 /// Fraction of hops whose raw probability is at or above the shipped positive threshold.
293 above: f32,
294 /// Standard deviation of the raw probability.
295 sd: f32,
296 /// Mean absolute change in probability between consecutive 10 ms hops.
297 step: f32,
298 /// Fraction of hops where the int8 logit hit a rail, i.e. the classifier saturated.
299 rail: f32,
300 /// Positive events the shipped `SmoothedLatchingClassifier` fired.
301 events: usize,
302 /// Every reported int16 score, kept so `sweep` can re-latch without re-running the gate.
303 scores: Vec<i16>,
304}
305
306/// PCM in, one raw probability per hop out, plus what the shipped latch did with the scores.
307///
308/// `None` when the clip is shorter than the gate's 230 ms receptive field, which real recordings
309/// of UI blips easily are.
310fn run(pcm: &[i16]) -> Option<Row> {
311 let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");
312 let mut gate = Gate::new();
313 let mut latch = Latch::new(Hysteresis::SHIPPED);
314
315 let mut probabilities = Vec::new();
316 let mut scores = Vec::new();
317 let mut events = 0usize;
318 let mut frames = Vec::new();
319
320 for chunk in pcm.chunks(HOP_SAMPLES) {
321 frames.clear();
322 let produced = frontend.process(chunk, &mut frames);
323 for frame in 0..produced {
324 let logmel = &frames[frame * CHANNELS..(frame + 1) * CHANNELS];
325 if let Some(score) = gate.push(logmel) {
326 probabilities.push(probability(score));
327 scores.push(score);
328 if latch.push(score).positive_event {
329 events += 1;
330 }
331 }
332 }
333 }
334
335 let mut sorted = probabilities.clone();
336 sorted.sort_by(|a, b| a.partial_cmp(b).expect("scores are finite"));
337 let hops = sorted.len();
338 if hops < 2 {
339 return None;
340 }
341 let threshold = Hysteresis::SHIPPED.positive_threshold;
342 let mean = probabilities.iter().sum::<f32>() / hops as f32;
343 let variance = probabilities.iter().map(|p| (p - mean) * (p - mean)).sum::<f32>() / hops as f32;
344 let step = probabilities.windows(2).map(|w| (w[1] - w[0]).abs()).sum::<f32>()
345 / (hops - 1).max(1) as f32;
346 // The int8 logit spans +-10 through a scale of 0.0784, so a probability outside this band can
347 // only come from the quantized logit clamping at 127 or -128.
348 let rail = probabilities.iter().filter(|&&p| !(0.001..=0.999).contains(&p)).count() as f32
349 / hops as f32;
350 Some(Row {
351 hops,
352 min: sorted[0],
353 mean,
354 p50: sorted[hops / 2],
355 p90: sorted[hops * 9 / 10],
356 max: sorted[hops - 1],
357 above: probabilities.iter().filter(|&&p| p >= threshold).count() as f32 / hops as f32,
358 sd: variance.sqrt(),
359 step,
360 rail,
361 events,
362 scores,
363 })
364}
365
366/// The separation statement, stated in terms of the measured distributions rather than a verdict.
367fn summarise(rows: &[(String, Row)]) {
368 let pick = |prefix: &str| -> Vec<&(String, Row)> {
369 rows.iter().filter(|(name, _)| name.starts_with(prefix)).collect()
370 };
371 let music = pick("music_");
372 let speech: Vec<_> = pick("speech_").into_iter().chain(pick("babble_")).collect();
373 let noise: Vec<_> = pick("white_")
374 .into_iter()
375 .chain(pick("pink_"))
376 .chain(pick("noise_"))
377 .chain(pick("silence"))
378 .collect();
379
380 let span = |group: &[&(String, Row)]| -> (f32, f32) {
381 let low = group.iter().map(|(_, r)| r.p50).fold(f32::MAX, f32::min);
382 let high = group.iter().map(|(_, r)| r.p50).fold(f32::MIN, f32::max);
383 (low, high)
384 };
385
386 let (music_low, music_high) = span(&music);
387 let (speech_low, speech_high) = span(&speech);
388 let (noise_low, noise_high) = span(&noise);
389
390 println!("median raw score by group");
391 println!(" music {music_low:.4} .. {music_high:.4}");
392 println!(" speech {speech_low:.4} .. {speech_high:.4}");
393 println!(" noise {noise_low:.4} .. {noise_high:.4}");
394 println!();
395 println!(
396 "music vs speech gap: {:+.4} music vs noise gap: {:+.4}",
397 music_low - speech_high,
398 music_low - noise_high
399 );
400 println!(
401 "shipped positive threshold {:.2}; total positive events across all inputs: {}",
402 Hysteresis::SHIPPED.positive_threshold,
403 rows.iter().map(|(_, r)| r.events).sum::<usize>()
404 );
405 println!(
406 "fraction of hops at or above threshold: music {:.1}%, speech {:.1}%, noise {:.1}%",
407 100.0 * music.iter().map(|(_, r)| r.above).sum::<f32>() / music.len() as f32,
408 100.0 * speech.iter().map(|(_, r)| r.above).sum::<f32>() / speech.len() as f32,
409 100.0 * noise.iter().map(|(_, r)| r.above).sum::<f32>() / noise.len() as f32,
410 );
411}
412
413// --- signal generation -------------------------------------------------------------------
414//
415// Deterministic, so a run is reproducible and a regression is attributable.
416
417struct Random(u32);
418
419impl Random {
420 fn new() -> Random {
421 Random(0x2545_F491)
422 }
423
424 /// Uniform in `[-1, 1)`.
425 fn signed(&mut self) -> f32 {
426 self.0 = self.0.wrapping_mul(1103515245).wrapping_add(12345) & 0x7FFF_FFFF;
427 (self.0 >> 11) as f32 / (1u32 << 19) as f32 - 1.0
428 }
429}
430
431/// Scale to `rms` of full scale and round to i16. Silence is passed through untouched.
432fn quantize(samples: &[f32], rms: f32) -> Vec<i16> {
433 let energy = samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32;
434 if energy <= 0.0 {
435 return vec![0i16; samples.len()];
436 }
437 let gain = rms / energy.sqrt();
438 samples.iter().map(|s| (s * gain * 32767.0).clamp(-32768.0, 32767.0) as i16).collect()
439}
440
441fn silence() -> Vec<f32> {
442 vec![0.0; SAMPLES]
443}
444
445fn white_noise() -> Vec<f32> {
446 let mut random = Random::new();
447 (0..SAMPLES).map(|_| random.signed()).collect()
448}
449
450/// Voss-McCartney: octave-spaced random holds summed, giving a 1/f slope.
451fn pink_noise() -> Vec<f32> {
452 let mut random = Random::new();
453 let mut rows = [0.0f32; 12];
454 (0..SAMPLES)
455 .map(|n| {
456 for (octave, row) in rows.iter_mut().enumerate() {
457 if n % (1 << octave) == 0 {
458 *row = random.signed();
459 }
460 }
461 rows.iter().sum::<f32>() / rows.len() as f32
462 })
463 .collect()
464}
465
466/// White noise through a band-pass, to see which part of the 60–3800 Hz band drives the score.
467fn band_noise(low: f32, high: f32) -> Vec<f32> {
468 let mut out = white_noise();
469 let centre = (low * high).sqrt();
470 resonate(&mut out, centre, high - low);
471 out
472}
473
474fn tone() -> Vec<f32> {
475 (0..SAMPLES)
476 .map(|n| (2.0 * std::f32::consts::PI * 440.0 * n as f32 / RATE as f32).sin())
477 .collect()
478}
479
480/// One sustained chord: three notes, eight harmonics each, slight detune, slow tremolo.
481fn harmonic_stack() -> Vec<f32> {
482 let roots = [220.0f32, 277.18, 329.63];
483 (0..SAMPLES)
484 .map(|n| {
485 let t = n as f32 / RATE as f32;
486 let mut sum = 0.0;
487 for (voice, root) in roots.iter().enumerate() {
488 let detune = 1.0 + 0.0015 * voice as f32;
489 for harmonic in 1..=8 {
490 let f = root * detune * harmonic as f32;
491 if f < 7800.0 {
492 sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;
493 }
494 }
495 }
496 sum * (1.0 + 0.08 * (2.0 * std::f32::consts::PI * 4.5 * t).sin())
497 })
498 .collect()
499}
500
501/// A note with a plucked envelope and a 1/k harmonic series.
502fn note(out: &mut [f32], start: usize, length: usize, hz: f32, gain: f32) {
503 for n in 0..length.min(out.len().saturating_sub(start)) {
504 let t = n as f32 / RATE as f32;
505 let envelope = (1.0 - (-t * 60.0).exp()) * (-t * 1.6).exp();
506 let mut sum = 0.0;
507 for harmonic in 1..=10 {
508 let f = hz * harmonic as f32;
509 if f < 7800.0 {
510 sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;
511 }
512 }
513 out[start + n] += sum * envelope * gain;
514 }
515}
516
517/// I–V–vi–IV in C, three times, each chord struck twice.
518fn chords() -> Vec<f32> {
519 let progression: [[f32; 3]; 4] = [
520 [261.63, 329.63, 392.00],
521 [392.00, 493.88, 587.33],
522 [220.00, 261.63, 329.63],
523 [174.61, 220.00, 261.63],
524 ];
525 let mut out = vec![0.0f32; SAMPLES];
526 let beat = RATE / 2;
527 for bar in 0..(SAMPLES / (beat * 2)) {
528 let chord = progression[bar % progression.len()];
529 for pitch in chord {
530 note(&mut out, bar * beat * 2, beat * 2, pitch, 1.0);
531 note(&mut out, bar * beat * 2 + beat, beat, pitch, 0.6);
532 }
533 note(&mut out, bar * beat * 2, beat * 2, chord[0] / 2.0, 1.2);
534 }
535 out
536}
537
538/// A monophonic line with vibrato over a held bass note.
539fn melody() -> Vec<f32> {
540 let scale = [261.63f32, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25];
541 let order = [0usize, 2, 4, 7, 5, 4, 2, 0, 3, 5, 7, 5, 4, 2, 1, 0];
542 let mut out = vec![0.0f32; SAMPLES];
543 let step = RATE / 4;
544 for index in 0..(SAMPLES / step) {
545 let hz = scale[order[index % order.len()]];
546 let start = index * step;
547 for n in 0..step.min(SAMPLES - start) {
548 let t = n as f32 / RATE as f32;
549 let vibrato = 1.0 + 0.006 * (2.0 * std::f32::consts::PI * 5.5 * t).sin();
550 let envelope = (1.0 - (-t * 40.0).exp()) * (-t * 1.2).exp();
551 let mut sum = 0.0;
552 for harmonic in 1..=9 {
553 let f = hz * vibrato * harmonic as f32;
554 if f < 7800.0 {
555 sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;
556 }
557 }
558 out[start + n] += sum * envelope;
559 }
560 note(&mut out, start, step, scale[0] / 2.0, 0.8);
561 }
562 out
563}
564
565/// Chords plus a kick on every beat and a hat on every off-beat: the closest thing here to a mix.
566fn full_mix() -> Vec<f32> {
567 let mut out = chords();
568 let mut random = Random::new();
569 let beat = RATE / 2;
570 for hit in 0..(SAMPLES / beat) {
571 let start = hit * beat;
572 for n in 0..(RATE / 8).min(SAMPLES - start) {
573 let t = n as f32 / RATE as f32;
574 let sweep = 120.0 * (-t * 30.0).exp() + 45.0;
575 out[start + n] +=
576 (2.0 * std::f32::consts::PI * sweep * t).sin() * (-t * 22.0).exp() * 2.0;
577 }
578 let hat = start + beat / 2;
579 for n in 0..(RATE / 40).min(SAMPLES.saturating_sub(hat)) {
580 let t = n as f32 / RATE as f32;
581 out[hat + n] += random.signed() * (-t * 180.0).exp() * 0.5;
582 }
583 }
584 out
585}
586
587/// A two-pole resonator, applied in place. `bandwidth` is in Hz.
588fn resonate(buffer: &mut [f32], hz: f32, bandwidth: f32) {
589 let r = (-std::f32::consts::PI * bandwidth / RATE as f32).exp();
590 let theta = 2.0 * std::f32::consts::PI * hz / RATE as f32;
591 let (a1, a2) = (2.0 * r * theta.cos(), -r * r);
592 let (mut y1, mut y2) = (0.0f32, 0.0f32);
593 for sample in buffer.iter_mut() {
594 let y = *sample * (1.0 - r) + a1 * y1 + a2 * y2;
595 y2 = y1;
596 y1 = y;
597 *sample = y;
598 }
599}
600
601/// Source-filter speech: a jittered glottal pulse train through three moving formants, with
602/// syllable-rate amplitude modulation, fricative bursts and, when `pauses`, inter-phrase silence.
603///
604/// Not a recording, and does not claim to be one. What it does carry is the properties that make
605/// speech the hard negative: a harmonic source, formant structure inside the gate's band, and a
606/// 4–5 Hz envelope — everything music has except a stable pitch and a metrical grid.
607///
608/// `pauses` exists because RMS is measured over the whole signal, so a speech clip full of gaps is
609/// louder than music during its voiced parts and quieter on average. The pause-free variant
610/// removes that confound.
611fn speech(f0: f32, pauses: bool) -> Vec<f32> {
612 // Five vowels, as (F1, F2, F3) in Hz.
613 let vowels = [
614 (700.0f32, 1220.0f32, 2600.0f32),
615 (400.0, 2000.0, 2550.0),
616 (300.0, 2300.0, 3000.0),
617 (600.0, 900.0, 2400.0),
618 (500.0, 1500.0, 2500.0),
619 ];
620 let mut random = Random::new();
621 let mut out = vec![0.0f32; SAMPLES];
622 let phoneme = RATE * 13 / 100;
623 let mut index = 0usize;
624 let mut position = 0usize;
625 let mut phase = 0.0f32;
626
627 while position < SAMPLES {
628 let length = phoneme.min(SAMPLES - position);
629 // Every seventh segment is a pause; every third is a fricative rather than a vowel.
630 let kind = index % 7;
631 let mut segment = vec![0.0f32; length];
632 if kind == 6 && pauses {
633 // Silence between phrases.
634 } else if kind == 2 || kind == 5 {
635 for sample in segment.iter_mut() {
636 *sample = random.signed() * 0.35;
637 }
638 resonate(&mut segment, 4200.0, 1400.0);
639 } else {
640 // Declining pitch contour across the phrase, plus per-period jitter.
641 let base = f0 * (1.0 + 0.18 * (index as f32 * 0.9).sin() - 0.02 * (index % 7) as f32);
642 for sample in segment.iter_mut() {
643 phase += base * (1.0 + 0.01 * random.signed()) / RATE as f32;
644 // A glottal pulse: one impulse per period, not a sine.
645 *sample = if phase >= 1.0 {
646 phase -= 1.0;
647 1.0
648 } else {
649 0.0
650 };
651 }
652 let (f1, f2, f3) = vowels[index % vowels.len()];
653 resonate(&mut segment, f1, 80.0);
654 resonate(&mut segment, f2, 110.0);
655 resonate(&mut segment, f3, 170.0);
656 }
657 // Syllable-rate envelope with onset and offset ramps.
658 for (n, sample) in segment.iter_mut().enumerate() {
659 let t = n as f32 / length as f32;
660 *sample *= (std::f32::consts::PI * t).sin().powf(0.6);
661 }
662 out[position..position + length].copy_from_slice(&segment);
663 position += length;
664 index += 1;
665 }
666 out
667}
668
669/// Two speakers at once — no pauses, denser harmonic content, closer to a room with people in it.
670fn babble() -> Vec<f32> {
671 let a = speech(104.0, true);
672 let b = speech(188.0, true);
673 let offset = RATE * 3 / 10;
674 (0..SAMPLES).map(|n| a[n] + b[(n + offset) % SAMPLES] * 0.8).collect()
675}
676
677/// White noise wearing speech's envelope: structureless, but modulated. Separates a detector that
678/// keys on spectral structure from one that keys on the shape of the level over time.
679fn am_noise() -> Vec<f32> {
680 let envelope = speech(112.0, true);
681 let mut random = Random::new();
682 let window = 160usize;
683 let mut out = vec![0.0f32; SAMPLES];
684 for start in (0..SAMPLES).step_by(window) {
685 let end = (start + window).min(SAMPLES);
686 let level =
687 envelope[start..end].iter().map(|s| s.abs()).sum::<f32>() / (end - start) as f32;
688 for sample in out[start..end].iter_mut() {
689 *sample = random.signed() * level;
690 }
691 }
692 out
693}
694
695// --- WAV ---------------------------------------------------------------------------------
696
697/// Minimal 16-bit PCM WAV reader: downmixes to mono and resamples to 16 kHz linearly.
698fn read_wav(path: &str) -> Result<Vec<i16>, String> {
699 let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
700 if bytes.len() < 44 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
701 return Err("not a RIFF/WAVE file".into());
702 }
703 let word = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]) as usize;
704 let long = |at: usize| {
705 u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize
706 };
707
708 let (mut channels, mut rate, mut bits) = (0usize, 0usize, 0usize);
709 let mut data: Option<(usize, usize)> = None;
710 let mut at = 12usize;
711 while at + 8 <= bytes.len() {
712 let id = &bytes[at..at + 4];
713 let size = long(at + 4);
714 let body = at + 8;
715 if id == b"fmt " && body + 16 <= bytes.len() {
716 channels = word(body + 2);
717 rate = long(body + 4);
718 bits = word(body + 14);
719 } else if id == b"data" {
720 data = Some((body, size.min(bytes.len() - body)));
721 }
722 at = body + size + (size & 1);
723 }
724
725 let (body, size) = data.ok_or("no data chunk")?;
726 if bits != 16 || channels == 0 || rate == 0 {
727 return Err(format!("need 16-bit PCM; got {bits}-bit, {channels}ch, {rate}Hz"));
728 }
729
730 let mono: Vec<f32> = bytes[body..body + size]
731 .chunks_exact(2)
732 .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32)
733 .collect::<Vec<_>>()
734 .chunks(channels)
735 .map(|frame| frame.iter().sum::<f32>() / channels as f32)
736 .collect();
737
738 let length = mono.len() * RATE / rate;
739 let resampled: Vec<f32> = (0..length)
740 .map(|n| {
741 let source = n as f32 * rate as f32 / RATE as f32;
742 let index = source as usize;
743 let frac = source - index as f32;
744 let a = mono[index.min(mono.len() - 1)];
745 let b = mono[(index + 1).min(mono.len() - 1)];
746 a + (b - a) * frac
747 })
748 .collect();
749
750 // Same RMS normalisation as the synthetic signals, so the table stays comparable.
751 Ok(quantize(&resampled, TARGET_RMS))
752}