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

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

check_gate_audio.rs756 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),
212 ("MEAN non-music (want low)", 1),
213 ] {
214 print!("{heading:<26}");
215 for total in &totals {
216 let (sum, count) = if pick == 0 { (total.0, music) } else { (total.1, other) };
217 print!("{:>8.1}", 100.0 * sum / count);
218 }
219 println!();
220 }
221 println!();
222 }
223}
224
225/// Re-run the latch over an already-computed score stream, returning the active duty cycle.
226fn replay(scores: &[i16], positive_threshold: f32, hold: u32, band: f32) -> f32 {
227 let mut latch = Latch::new(Hysteresis {
228 positive_threshold,
229 negative_threshold: positive_threshold - band,
230 negative_frames_before_event: hold,
231 ..Hysteresis::SHIPPED
232 });
233 let active = scores.iter().filter(|&&score| latch.push(score).active).count();
234 active as f32 / scores.len() as f32
235}
236
237/// The first 40 reported hops of a few inputs, because a distribution hides whether the score is
238/// tracking anything or just rattling. At 100 Hz these forty numbers are 400 ms.
239fn trajectory(signals: &[(String, Vec<i16>)]) {
240 println!("first 40 reported hops (400 ms)");
241 for (name, pcm) in signals {
242 if !matches!(name.as_str(), "white_noise" | "music_chords" | "music_harmonics") {
243 continue;
244 }
245 let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");
246 let mut gate = Gate::new();
247 let mut frames = Vec::new();
248 frontend.process(pcm, &mut frames);
249 let scores: Vec<String> = (0..frames.len() / CHANNELS)
250 .filter_map(|frame| gate.push(&frames[frame * CHANNELS..(frame + 1) * CHANNELS]))
251 .take(40)
252 .map(|score| format!("{:.2}", probability(score)))
253 .collect();
254 println!(" {name:<18} {}", scores.join(" "));
255 }
256}
257
258/// Mean log-mel per channel, so a nonsense score can be attributed to the trunk rather than to
259/// the front end feeding it. A bank pinned at the ceiling or flat across every channel would mean
260/// the harness is wrong, not the gate.
261fn features(signals: &[(String, Vec<i16>)]) {
262 println!("mean log-mel by channel (front-end sanity; ceiling is 15.0)");
263 for (name, pcm) in signals {
264 if !matches!(name.as_str(), "white_noise" | "music_chords" | "music_harmonics" | "speech_male")
265 {
266 continue;
267 }
268 let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");
269 let mut frames = Vec::new();
270 frontend.process(pcm, &mut frames);
271 let count = frames.len() / CHANNELS;
272 let mut mean = vec![0.0f32; CHANNELS];
273 for frame in 0..count {
274 for (channel, slot) in mean.iter_mut().enumerate() {
275 *slot += frames[frame * CHANNELS + channel];
276 }
277 }
278 let line: Vec<String> = mean
279 .iter()
280 .step_by(4)
281 .map(|total| format!("{:>5.1}", total / count as f32))
282 .collect();
283 println!(" {name:<18} {}", line.join(" "));
284 }
285}
286
287struct Row {
288 hops: usize,
289 min: f32,
290 mean: f32,
291 p50: f32,
292 p90: f32,
293 max: f32,
294 /// Fraction of hops whose raw probability is at or above the shipped positive threshold.
295 above: f32,
296 /// Standard deviation of the raw probability.
297 sd: f32,
298 /// Mean absolute change in probability between consecutive 10 ms hops.
299 step: f32,
300 /// Fraction of hops where the int8 logit hit a rail, i.e. the classifier saturated.
301 rail: f32,
302 /// Positive events the shipped `SmoothedLatchingClassifier` fired.
303 events: usize,
304 /// Every reported int16 score, kept so `sweep` can re-latch without re-running the gate.
305 scores: Vec<i16>,
306}
307
308/// PCM in, one raw probability per hop out, plus what the shipped latch did with the scores.
309///
310/// `None` when the clip is shorter than the gate's 230 ms receptive field, which real recordings
311/// of UI blips easily are.
312fn run(pcm: &[i16]) -> Option<Row> {
313 let mut frontend = Frontend::new(NOW_PLAYING).expect("the front end builds");
314 let mut gate = Gate::new();
315 let mut latch = Latch::new(Hysteresis::SHIPPED);
316
317 let mut probabilities = Vec::new();
318 let mut scores = Vec::new();
319 let mut events = 0usize;
320 let mut frames = Vec::new();
321
322 for chunk in pcm.chunks(HOP_SAMPLES) {
323 frames.clear();
324 let produced = frontend.process(chunk, &mut frames);
325 for frame in 0..produced {
326 let logmel = &frames[frame * CHANNELS..(frame + 1) * CHANNELS];
327 if let Some(score) = gate.push(logmel) {
328 probabilities.push(probability(score));
329 scores.push(score);
330 if latch.push(score).positive_event {
331 events += 1;
332 }
333 }
334 }
335 }
336
337 let mut sorted = probabilities.clone();
338 sorted.sort_by(|a, b| a.partial_cmp(b).expect("scores are finite"));
339 let hops = sorted.len();
340 if hops < 2 {
341 return None;
342 }
343 let threshold = Hysteresis::SHIPPED.positive_threshold;
344 let mean = probabilities.iter().sum::<f32>() / hops as f32;
345 let variance = probabilities.iter().map(|p| (p - mean) * (p - mean)).sum::<f32>() / hops as f32;
346 let step = probabilities.windows(2).map(|w| (w[1] - w[0]).abs()).sum::<f32>()
347 / (hops - 1).max(1) as f32;
348 // The int8 logit spans +-10 through a scale of 0.0784, so a probability outside this band can
349 // only come from the quantized logit clamping at 127 or -128.
350 let rail = probabilities.iter().filter(|&&p| !(0.001..=0.999).contains(&p)).count() as f32
351 / hops as f32;
352 Some(Row {
353 hops,
354 min: sorted[0],
355 mean,
356 p50: sorted[hops / 2],
357 p90: sorted[hops * 9 / 10],
358 max: sorted[hops - 1],
359 above: probabilities.iter().filter(|&&p| p >= threshold).count() as f32 / hops as f32,
360 sd: variance.sqrt(),
361 step,
362 rail,
363 events,
364 scores,
365 })
366}
367
368/// The separation statement, stated in terms of the measured distributions rather than a verdict.
369fn summarise(rows: &[(String, Row)]) {
370 let pick = |prefix: &str| -> Vec<&(String, Row)> {
371 rows.iter().filter(|(name, _)| name.starts_with(prefix)).collect()
372 };
373 let music = pick("music_");
374 let speech: Vec<_> = pick("speech_").into_iter().chain(pick("babble_")).collect();
375 let noise: Vec<_> = pick("white_")
376 .into_iter()
377 .chain(pick("pink_"))
378 .chain(pick("noise_"))
379 .chain(pick("silence"))
380 .collect();
381
382 let span = |group: &[&(String, Row)]| -> (f32, f32) {
383 let low = group.iter().map(|(_, r)| r.p50).fold(f32::MAX, f32::min);
384 let high = group.iter().map(|(_, r)| r.p50).fold(f32::MIN, f32::max);
385 (low, high)
386 };
387
388 let (music_low, music_high) = span(&music);
389 let (speech_low, speech_high) = span(&speech);
390 let (noise_low, noise_high) = span(&noise);
391
392 println!("median raw score by group");
393 println!(" music {music_low:.4} .. {music_high:.4}");
394 println!(" speech {speech_low:.4} .. {speech_high:.4}");
395 println!(" noise {noise_low:.4} .. {noise_high:.4}");
396 println!();
397 println!(
398 "music vs speech gap: {:+.4} music vs noise gap: {:+.4}",
399 music_low - speech_high,
400 music_low - noise_high
401 );
402 println!(
403 "shipped positive threshold {:.2}; total positive events across all inputs: {}",
404 Hysteresis::SHIPPED.positive_threshold,
405 rows.iter().map(|(_, r)| r.events).sum::<usize>()
406 );
407 println!(
408 "fraction of hops at or above threshold: music {:.1}%, speech {:.1}%, noise {:.1}%",
409 100.0 * music.iter().map(|(_, r)| r.above).sum::<f32>() / music.len() as f32,
410 100.0 * speech.iter().map(|(_, r)| r.above).sum::<f32>() / speech.len() as f32,
411 100.0 * noise.iter().map(|(_, r)| r.above).sum::<f32>() / noise.len() as f32,
412 );
413}
414
415// --- signal generation -------------------------------------------------------------------
416//
417// Deterministic, so a run is reproducible and a regression is attributable.
418
419struct Random(u32);
420
421impl Random {
422 fn new() -> Random {
423 Random(0x2545_F491)
424 }
425
426 /// Uniform in `[-1, 1)`.
427 fn signed(&mut self) -> f32 {
428 self.0 = self.0.wrapping_mul(1103515245).wrapping_add(12345) & 0x7FFF_FFFF;
429 (self.0 >> 11) as f32 / (1u32 << 19) as f32 - 1.0
430 }
431}
432
433/// Scale to `rms` of full scale and round to i16. Silence is passed through untouched.
434fn quantize(samples: &[f32], rms: f32) -> Vec<i16> {
435 let energy = samples.iter().map(|s| s * s).sum::<f32>() / samples.len() as f32;
436 if energy <= 0.0 {
437 return vec![0i16; samples.len()];
438 }
439 let gain = rms / energy.sqrt();
440 samples
441 .iter()
442 .map(|s| (s * gain * 32767.0).clamp(-32768.0, 32767.0) as i16)
443 .collect()
444}
445
446fn silence() -> Vec<f32> {
447 vec![0.0; SAMPLES]
448}
449
450fn white_noise() -> Vec<f32> {
451 let mut random = Random::new();
452 (0..SAMPLES).map(|_| random.signed()).collect()
453}
454
455/// Voss-McCartney: octave-spaced random holds summed, giving a 1/f slope.
456fn pink_noise() -> Vec<f32> {
457 let mut random = Random::new();
458 let mut rows = [0.0f32; 12];
459 (0..SAMPLES)
460 .map(|n| {
461 for (octave, row) in rows.iter_mut().enumerate() {
462 if n % (1 << octave) == 0 {
463 *row = random.signed();
464 }
465 }
466 rows.iter().sum::<f32>() / rows.len() as f32
467 })
468 .collect()
469}
470
471/// White noise through a band-pass, to see which part of the 60–3800 Hz band drives the score.
472fn band_noise(low: f32, high: f32) -> Vec<f32> {
473 let mut out = white_noise();
474 let centre = (low * high).sqrt();
475 resonate(&mut out, centre, high - low);
476 out
477}
478
479fn tone() -> Vec<f32> {
480 (0..SAMPLES)
481 .map(|n| (2.0 * std::f32::consts::PI * 440.0 * n as f32 / RATE as f32).sin())
482 .collect()
483}
484
485/// One sustained chord: three notes, eight harmonics each, slight detune, slow tremolo.
486fn harmonic_stack() -> Vec<f32> {
487 let roots = [220.0f32, 277.18, 329.63];
488 (0..SAMPLES)
489 .map(|n| {
490 let t = n as f32 / RATE as f32;
491 let mut sum = 0.0;
492 for (voice, root) in roots.iter().enumerate() {
493 let detune = 1.0 + 0.0015 * voice as f32;
494 for harmonic in 1..=8 {
495 let f = root * detune * harmonic as f32;
496 if f < 7800.0 {
497 sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;
498 }
499 }
500 }
501 sum * (1.0 + 0.08 * (2.0 * std::f32::consts::PI * 4.5 * t).sin())
502 })
503 .collect()
504}
505
506/// A note with a plucked envelope and a 1/k harmonic series.
507fn note(out: &mut [f32], start: usize, length: usize, hz: f32, gain: f32) {
508 for n in 0..length.min(out.len().saturating_sub(start)) {
509 let t = n as f32 / RATE as f32;
510 let envelope = (1.0 - (-t * 60.0).exp()) * (-t * 1.6).exp();
511 let mut sum = 0.0;
512 for harmonic in 1..=10 {
513 let f = hz * harmonic as f32;
514 if f < 7800.0 {
515 sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;
516 }
517 }
518 out[start + n] += sum * envelope * gain;
519 }
520}
521
522/// I–V–vi–IV in C, three times, each chord struck twice.
523fn chords() -> Vec<f32> {
524 let progression: [[f32; 3]; 4] = [
525 [261.63, 329.63, 392.00],
526 [392.00, 493.88, 587.33],
527 [220.00, 261.63, 329.63],
528 [174.61, 220.00, 261.63],
529 ];
530 let mut out = vec![0.0f32; SAMPLES];
531 let beat = RATE / 2;
532 for bar in 0..(SAMPLES / (beat * 2)) {
533 let chord = progression[bar % progression.len()];
534 for pitch in chord {
535 note(&mut out, bar * beat * 2, beat * 2, pitch, 1.0);
536 note(&mut out, bar * beat * 2 + beat, beat, pitch, 0.6);
537 }
538 note(&mut out, bar * beat * 2, beat * 2, chord[0] / 2.0, 1.2);
539 }
540 out
541}
542
543/// A monophonic line with vibrato over a held bass note.
544fn melody() -> Vec<f32> {
545 let scale = [261.63f32, 293.66, 329.63, 349.23, 392.00, 440.00, 493.88, 523.25];
546 let order = [0usize, 2, 4, 7, 5, 4, 2, 0, 3, 5, 7, 5, 4, 2, 1, 0];
547 let mut out = vec![0.0f32; SAMPLES];
548 let step = RATE / 4;
549 for index in 0..(SAMPLES / step) {
550 let hz = scale[order[index % order.len()]];
551 let start = index * step;
552 for n in 0..step.min(SAMPLES - start) {
553 let t = n as f32 / RATE as f32;
554 let vibrato = 1.0 + 0.006 * (2.0 * std::f32::consts::PI * 5.5 * t).sin();
555 let envelope = (1.0 - (-t * 40.0).exp()) * (-t * 1.2).exp();
556 let mut sum = 0.0;
557 for harmonic in 1..=9 {
558 let f = hz * vibrato * harmonic as f32;
559 if f < 7800.0 {
560 sum += (2.0 * std::f32::consts::PI * f * t).sin() / harmonic as f32;
561 }
562 }
563 out[start + n] += sum * envelope;
564 }
565 note(&mut out, start, step, scale[0] / 2.0, 0.8);
566 }
567 out
568}
569
570/// Chords plus a kick on every beat and a hat on every off-beat: the closest thing here to a mix.
571fn full_mix() -> Vec<f32> {
572 let mut out = chords();
573 let mut random = Random::new();
574 let beat = RATE / 2;
575 for hit in 0..(SAMPLES / beat) {
576 let start = hit * beat;
577 for n in 0..(RATE / 8).min(SAMPLES - start) {
578 let t = n as f32 / RATE as f32;
579 let sweep = 120.0 * (-t * 30.0).exp() + 45.0;
580 out[start + n] += (2.0 * std::f32::consts::PI * sweep * t).sin() * (-t * 22.0).exp() * 2.0;
581 }
582 let hat = start + beat / 2;
583 for n in 0..(RATE / 40).min(SAMPLES.saturating_sub(hat)) {
584 let t = n as f32 / RATE as f32;
585 out[hat + n] += random.signed() * (-t * 180.0).exp() * 0.5;
586 }
587 }
588 out
589}
590
591/// A two-pole resonator, applied in place. `bandwidth` is in Hz.
592fn resonate(buffer: &mut [f32], hz: f32, bandwidth: f32) {
593 let r = (-std::f32::consts::PI * bandwidth / RATE as f32).exp();
594 let theta = 2.0 * std::f32::consts::PI * hz / RATE as f32;
595 let (a1, a2) = (2.0 * r * theta.cos(), -r * r);
596 let (mut y1, mut y2) = (0.0f32, 0.0f32);
597 for sample in buffer.iter_mut() {
598 let y = *sample * (1.0 - r) + a1 * y1 + a2 * y2;
599 y2 = y1;
600 y1 = y;
601 *sample = y;
602 }
603}
604
605/// Source-filter speech: a jittered glottal pulse train through three moving formants, with
606/// syllable-rate amplitude modulation, fricative bursts and, when `pauses`, inter-phrase silence.
607///
608/// Not a recording, and does not claim to be one. What it does carry is the properties that make
609/// speech the hard negative: a harmonic source, formant structure inside the gate's band, and a
610/// 4–5 Hz envelope — everything music has except a stable pitch and a metrical grid.
611///
612/// `pauses` exists because RMS is measured over the whole signal, so a speech clip full of gaps is
613/// louder than music during its voiced parts and quieter on average. The pause-free variant
614/// removes that confound.
615fn speech(f0: f32, pauses: bool) -> Vec<f32> {
616 // Five vowels, as (F1, F2, F3) in Hz.
617 let vowels = [
618 (700.0f32, 1220.0f32, 2600.0f32),
619 (400.0, 2000.0, 2550.0),
620 (300.0, 2300.0, 3000.0),
621 (600.0, 900.0, 2400.0),
622 (500.0, 1500.0, 2500.0),
623 ];
624 let mut random = Random::new();
625 let mut out = vec![0.0f32; SAMPLES];
626 let phoneme = RATE * 13 / 100;
627 let mut index = 0usize;
628 let mut position = 0usize;
629 let mut phase = 0.0f32;
630
631 while position < SAMPLES {
632 let length = phoneme.min(SAMPLES - position);
633 // Every seventh segment is a pause; every third is a fricative rather than a vowel.
634 let kind = index % 7;
635 let mut segment = vec![0.0f32; length];
636 if kind == 6 && pauses {
637 // Silence between phrases.
638 } else if kind == 2 || kind == 5 {
639 for sample in segment.iter_mut() {
640 *sample = random.signed() * 0.35;
641 }
642 resonate(&mut segment, 4200.0, 1400.0);
643 } else {
644 // Declining pitch contour across the phrase, plus per-period jitter.
645 let base = f0 * (1.0 + 0.18 * (index as f32 * 0.9).sin() - 0.02 * (index % 7) as f32);
646 for sample in segment.iter_mut() {
647 phase += base * (1.0 + 0.01 * random.signed()) / RATE as f32;
648 // A glottal pulse: one impulse per period, not a sine.
649 *sample = if phase >= 1.0 {
650 phase -= 1.0;
651 1.0
652 } else {
653 0.0
654 };
655 }
656 let (f1, f2, f3) = vowels[index % vowels.len()];
657 resonate(&mut segment, f1, 80.0);
658 resonate(&mut segment, f2, 110.0);
659 resonate(&mut segment, f3, 170.0);
660 }
661 // Syllable-rate envelope with onset and offset ramps.
662 for (n, sample) in segment.iter_mut().enumerate() {
663 let t = n as f32 / length as f32;
664 *sample *= (std::f32::consts::PI * t).sin().powf(0.6);
665 }
666 out[position..position + length].copy_from_slice(&segment);
667 position += length;
668 index += 1;
669 }
670 out
671}
672
673/// Two speakers at once — no pauses, denser harmonic content, closer to a room with people in it.
674fn babble() -> Vec<f32> {
675 let a = speech(104.0, true);
676 let b = speech(188.0, true);
677 let offset = RATE * 3 / 10;
678 (0..SAMPLES)
679 .map(|n| a[n] + b[(n + offset) % SAMPLES] * 0.8)
680 .collect()
681}
682
683/// White noise wearing speech's envelope: structureless, but modulated. Separates a detector that
684/// keys on spectral structure from one that keys on the shape of the level over time.
685fn am_noise() -> Vec<f32> {
686 let envelope = speech(112.0, true);
687 let mut random = Random::new();
688 let window = 160usize;
689 let mut out = vec![0.0f32; SAMPLES];
690 for start in (0..SAMPLES).step_by(window) {
691 let end = (start + window).min(SAMPLES);
692 let level = envelope[start..end].iter().map(|s| s.abs()).sum::<f32>() / (end - start) as f32;
693 for sample in out[start..end].iter_mut() {
694 *sample = random.signed() * level;
695 }
696 }
697 out
698}
699
700// --- WAV ---------------------------------------------------------------------------------
701
702/// Minimal 16-bit PCM WAV reader: downmixes to mono and resamples to 16 kHz linearly.
703fn read_wav(path: &str) -> Result<Vec<i16>, String> {
704 let bytes = std::fs::read(path).map_err(|e| e.to_string())?;
705 if bytes.len() < 44 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
706 return Err("not a RIFF/WAVE file".into());
707 }
708 let word = |at: usize| u16::from_le_bytes([bytes[at], bytes[at + 1]]) as usize;
709 let long =
710 |at: usize| u32::from_le_bytes([bytes[at], bytes[at + 1], bytes[at + 2], bytes[at + 3]]) as usize;
711
712 let (mut channels, mut rate, mut bits) = (0usize, 0usize, 0usize);
713 let mut data: Option<(usize, usize)> = None;
714 let mut at = 12usize;
715 while at + 8 <= bytes.len() {
716 let id = &bytes[at..at + 4];
717 let size = long(at + 4);
718 let body = at + 8;
719 if id == b"fmt " && body + 16 <= bytes.len() {
720 channels = word(body + 2);
721 rate = long(body + 4);
722 bits = word(body + 14);
723 } else if id == b"data" {
724 data = Some((body, size.min(bytes.len() - body)));
725 }
726 at = body + size + (size & 1);
727 }
728
729 let (body, size) = data.ok_or("no data chunk")?;
730 if bits != 16 || channels == 0 || rate == 0 {
731 return Err(format!("need 16-bit PCM; got {bits}-bit, {channels}ch, {rate}Hz"));
732 }
733
734 let mono: Vec<f32> = bytes[body..body + size]
735 .chunks_exact(2)
736 .map(|c| i16::from_le_bytes([c[0], c[1]]) as f32)
737 .collect::<Vec<_>>()
738 .chunks(channels)
739 .map(|frame| frame.iter().sum::<f32>() / channels as f32)
740 .collect();
741
742 let length = mono.len() * RATE / rate;
743 let resampled: Vec<f32> = (0..length)
744 .map(|n| {
745 let source = n as f32 * rate as f32 / RATE as f32;
746 let index = source as usize;
747 let frac = source - index as f32;
748 let a = mono[index.min(mono.len() - 1)];
749 let b = mono[(index + 1).min(mono.len() - 1)];
750 a + (b - a) * frac
751 })
752 .collect();
753
754 // Same RMS normalisation as the synthetic signals, so the table stays comparable.
755 Ok(quantize(&resampled, TARGET_RMS))
756}