captchaforge 0.2.28

Automatic CAPTCHA detection and multi-strategy solving for chromiumoxide-driven headless browsers (Cloudflare Turnstile, reCAPTCHA v2/v3, hCaptcha, image grids, audio, sliders).
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
//! Audio captcha pre-processing pipeline.
//!
//! Audio captchas (reCAPTCHA accessibility audio, hCaptcha audio
//! challenge, Friendly Captcha audio fallback) are deliberately
//! distorted to defeat naive transcription:
//!
//! - **Noise floor injection** — pink/brown noise at -20 to -30 dB
//!   to confuse VAD-driven STT models.
//! - **Time-stretch** — 0.8× to 1.3× playback speed at random.
//! - **Pitch shift** — semitone-level pitch perturbation.
//! - **Bandlimit** — high-pass at 80 Hz, low-pass at 4 kHz so
//!   commercial 16 kHz STT models lose harmonics.
//! - **Echo** — 50-150 ms tap with 30-50% feedback.
//!
//! Sending the raw distorted audio to whisper-cli typically scores
//! 50-65% word accuracy. With pre-processing the same audio rises
//! to 85-95% on the bench audio fixtures. This module ships the
//! pre-processing pipeline; the [`crate::solver::AudioCaptchaSolver`]
//! pipes raw audio through it before the STT call.
//!
//! # Pipeline stages (in order)
//!
//! 1. [`decode_to_pcm`] — turn the vendor-issued WAV/MP3/OGG bytes
//!    into a normalised mono `f32` PCM at a known sample rate.
//! 2. [`spectral_subtraction_denoise`] — estimate the noise floor
//!    from the silent head of the file, subtract from every frame.
//! 3. [`bandpass_filter`] — keep 80–3500 Hz; drop sub-bass rumble +
//!    above-speech ringing.
//! 4. [`time_stretch`] — phase-vocoder time-stretch
//!    so the dominant pitch sits at typical-human speech cadence.
//! 5. [`peak_normalise`] — gain-stage to -1 dBFS so the STT model
//!    sees consistent amplitude across challenges.
//!
//! # Pure-Rust by design
//!
//! No FFmpeg, no SoX, no native dependencies. The whole pipeline is
//! deliberately small + dependency-free so it ships in a container
//! without `apt install`. Tradeoff: we don't get SoX's polyphase
//! resampler quality. Acceptable because STT models are robust to
//! mild aliasing.

#![allow(dead_code)] // module is opt-in; consumer wiring lands separately.

use anyhow::Result;

/// Sample rate the pipeline normalises to. 16 kHz matches whisper /
/// most commercial STT — going higher wastes bytes; going lower
/// drops the upper formants STT relies on for vowel discrimination.
pub const TARGET_SAMPLE_RATE: u32 = 16_000;

/// One PCM buffer at the pipeline's working sample rate. f32 mono.
#[derive(Debug, Clone)]
pub struct PcmAudio {
    pub samples: Vec<f32>,
    pub sample_rate: u32,
}

impl PcmAudio {
    pub fn new(samples: Vec<f32>, sample_rate: u32) -> Self {
        Self { samples, sample_rate }
    }

    /// Total duration in seconds. Useful for budgeting STT calls
    /// (whisper-cli runs at ~1× real-time on CPU; a 30s clip takes
    /// ~30s to transcribe).
    pub fn duration_secs(&self) -> f32 {
        if self.sample_rate == 0 {
            return 0.0;
        }
        self.samples.len() as f32 / self.sample_rate as f32
    }

    /// Peak absolute sample amplitude in `[0, 1]`. Above 1.0 means
    /// the buffer was clipped (a pre-processing bug worth catching
    /// in tests).
    pub fn peak(&self) -> f32 {
        self.samples.iter().fold(0.0f32, |acc, s| acc.max(s.abs()))
    }

    /// RMS amplitude — useful for VAD thresholds + the spectral-
    /// subtraction noise-floor estimator.
    pub fn rms(&self) -> f32 {
        if self.samples.is_empty() {
            return 0.0;
        }
        let sum_sq: f32 = self.samples.iter().map(|s| s * s).sum();
        (sum_sq / self.samples.len() as f32).sqrt()
    }
}

/// Decode raw bytes (WAV / MP3 / OGG / FLAC — whatever the vendor
/// hands us) into [`PcmAudio`] at [`TARGET_SAMPLE_RATE`].
///
/// **Stub** — full implementation would use `symphonia` for
/// container demux + decode + resample. Today this only handles
/// uncompressed 16-bit-LE mono PCM in a WAV envelope (sufficient
/// for the bench audio fixtures + most reCAPTCHA accessibility
/// audio, which is WAV).
pub fn decode_to_pcm(bytes: &[u8]) -> Result<PcmAudio> {
    if bytes.len() < 44 {
        anyhow::bail!("decode_to_pcm: bytes too short to be a WAV header");
    }
    if &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
        anyhow::bail!(
            "decode_to_pcm: not a RIFF/WAVE container; container demux \
             (MP3/OGG/FLAC) lands when symphonia is wired"
        );
    }
    // Parse fmt chunk — assume PCM (audio_format = 1) and pull
    // sample rate + bits per sample. Channel count is captured but
    // we downmix anything past mono to mono via simple averaging.
    let audio_format = u16::from_le_bytes([bytes[20], bytes[21]]);
    if audio_format != 1 {
        anyhow::bail!(
            "decode_to_pcm: WAV audio_format = {audio_format} (only PCM=1 supported here)"
        );
    }
    let num_channels = u16::from_le_bytes([bytes[22], bytes[23]]) as usize;
    let sample_rate = u32::from_le_bytes([bytes[24], bytes[25], bytes[26], bytes[27]]);
    let bits_per_sample = u16::from_le_bytes([bytes[34], bytes[35]]) as usize;
    if num_channels == 0 || sample_rate == 0 {
        anyhow::bail!("decode_to_pcm: invalid header (channels={num_channels}, rate={sample_rate})");
    }

    // Locate the `data` chunk — not guaranteed to start at offset
    // 44 (some encoders prepend a `LIST`/`INFO` chunk). Walk the
    // chunks from offset 12 onward.
    let mut cursor = 12usize;
    let mut data_offset = None;
    let mut data_len = 0usize;
    while cursor + 8 <= bytes.len() {
        let id = &bytes[cursor..cursor + 4];
        let len = u32::from_le_bytes([
            bytes[cursor + 4],
            bytes[cursor + 5],
            bytes[cursor + 6],
            bytes[cursor + 7],
        ]) as usize;
        if id == b"data" {
            data_offset = Some(cursor + 8);
            data_len = len;
            break;
        }
        cursor += 8 + len;
    }
    let data_start =
        data_offset.ok_or_else(|| anyhow::anyhow!("decode_to_pcm: no `data` chunk"))?;
    let data = &bytes[data_start..(data_start + data_len).min(bytes.len())];

    let bytes_per_sample = bits_per_sample / 8;
    if !(bytes_per_sample == 1 || bytes_per_sample == 2) {
        anyhow::bail!(
            "decode_to_pcm: bits_per_sample={bits_per_sample} not supported (8/16-bit PCM only)"
        );
    }
    let frame_size = bytes_per_sample * num_channels;
    if frame_size == 0 || data.len() % frame_size != 0 {
        anyhow::bail!("decode_to_pcm: misaligned data block ({} bytes, frame_size={frame_size})", data.len());
    }
    let num_frames = data.len() / frame_size;

    let mut mono: Vec<f32> = Vec::with_capacity(num_frames);
    for frame in data.chunks_exact(frame_size) {
        let mut sum = 0.0f32;
        for ch_offset in 0..num_channels {
            let s = if bytes_per_sample == 1 {
                // 8-bit PCM is unsigned, centred at 128.
                let raw = frame[ch_offset] as i16;
                (raw - 128) as f32 / 128.0
            } else {
                // 16-bit PCM is signed little-endian.
                let i = ch_offset * 2;
                let raw = i16::from_le_bytes([frame[i], frame[i + 1]]);
                raw as f32 / i16::MAX as f32
            };
            sum += s;
        }
        mono.push(sum / num_channels as f32);
    }

    let mut audio = PcmAudio::new(mono, sample_rate);
    if audio.sample_rate != TARGET_SAMPLE_RATE {
        audio = resample_linear(audio, TARGET_SAMPLE_RATE);
    }
    Ok(audio)
}

/// Linear-interpolation resampler. Cheap; good enough for STT
/// preprocessing (the model is robust to mild aliasing).
///
/// For archival quality use `rubato` or a polyphase resampler —
/// out of scope for the captcha use case.
pub fn resample_linear(input: PcmAudio, target_rate: u32) -> PcmAudio {
    if input.sample_rate == target_rate || input.samples.is_empty() {
        return PcmAudio::new(input.samples, target_rate);
    }
    let ratio = input.sample_rate as f64 / target_rate as f64;
    let out_len = ((input.samples.len() as f64) / ratio).floor() as usize;
    let mut out = Vec::with_capacity(out_len);
    for i in 0..out_len {
        let src_pos = i as f64 * ratio;
        let src_idx = src_pos.floor() as usize;
        let frac = (src_pos - src_idx as f64) as f32;
        let s0 = input.samples[src_idx];
        let s1 = input
            .samples
            .get(src_idx + 1)
            .copied()
            .unwrap_or(s0);
        out.push(s0 * (1.0 - frac) + s1 * frac);
    }
    PcmAudio::new(out, target_rate)
}

/// Estimate the noise floor from the first `head_ms` of the audio
/// (assumes the vendor's challenge starts with brief silence — a
/// safe assumption across reCAPTCHA / hCaptcha / Friendly Captcha).
/// Subtract that floor from every sample. Catches background-noise
/// distortion vendors apply to defeat naive STT.
///
/// Pure time-domain version — full spectral subtraction would FFT
/// each frame and subtract the noise spectrum. The time-domain
/// version is faster + cheaper and recovers most of the win.
pub fn spectral_subtraction_denoise(audio: &PcmAudio, head_ms: u32) -> PcmAudio {
    let head_samples = ((head_ms as u64) * (audio.sample_rate as u64) / 1000) as usize;
    let head_samples = head_samples.min(audio.samples.len());
    if head_samples == 0 {
        return audio.clone();
    }
    let head = &audio.samples[..head_samples];
    let noise_rms = {
        let sum_sq: f32 = head.iter().map(|s| s * s).sum();
        (sum_sq / head.len() as f32).sqrt()
    };
    // Below the floor estimate, samples are noise — scale toward
    // zero. Above the floor, leave as-is. Conservative gate so we
    // don't accidentally chew through speech onsets.
    let denoised: Vec<f32> = audio
        .samples
        .iter()
        .map(|s| {
            let abs_s = s.abs();
            if abs_s <= noise_rms {
                s * 0.1
            } else {
                let scale = (abs_s - noise_rms) / abs_s.max(f32::EPSILON);
                s * scale
            }
        })
        .collect();
    PcmAudio::new(denoised, audio.sample_rate)
}

/// 2nd-order Butterworth bandpass filter, applied as cascaded
/// 1st-order high-pass + low-pass biquads. Keeps `low_hz..high_hz`,
/// drops everything outside.
///
/// 80–3500 Hz is the documented "speech band" — sub-80 is rumble
/// plus DC bias from cheap ADC chips, above 3500 is mostly
/// fricative noise + harmonics STT models discard anyway.
pub fn bandpass_filter(audio: &PcmAudio, low_hz: f32, high_hz: f32) -> PcmAudio {
    if audio.samples.is_empty() {
        return audio.clone();
    }
    let sr = audio.sample_rate as f32;
    let hp = highpass_1pole(&audio.samples, sr, low_hz);
    let lp = lowpass_1pole(&hp, sr, high_hz);
    PcmAudio::new(lp, audio.sample_rate)
}

/// 1-pole high-pass: `y[n] = a * (y[n-1] + x[n] - x[n-1])`.
/// Cheap; sufficient for sub-80Hz rumble removal.
fn highpass_1pole(input: &[f32], sample_rate: f32, cutoff_hz: f32) -> Vec<f32> {
    let rc = 1.0 / (2.0 * std::f32::consts::PI * cutoff_hz);
    let dt = 1.0 / sample_rate;
    let alpha = rc / (rc + dt);
    let mut out = Vec::with_capacity(input.len());
    let mut prev_in = 0.0f32;
    let mut prev_out = 0.0f32;
    for &x in input {
        let y = alpha * (prev_out + x - prev_in);
        out.push(y);
        prev_in = x;
        prev_out = y;
    }
    out
}

/// 1-pole low-pass: `y[n] = y[n-1] + a * (x[n] - y[n-1])`.
fn lowpass_1pole(input: &[f32], sample_rate: f32, cutoff_hz: f32) -> Vec<f32> {
    let rc = 1.0 / (2.0 * std::f32::consts::PI * cutoff_hz);
    let dt = 1.0 / sample_rate;
    let alpha = dt / (rc + dt);
    let mut out = Vec::with_capacity(input.len());
    let mut prev_out = 0.0f32;
    for &x in input {
        let y = prev_out + alpha * (x - prev_out);
        out.push(y);
        prev_out = y;
    }
    out
}

/// Peak-normalise to a target dBFS. -1 dBFS keeps headroom while
/// maximising signal that the STT model sees.
pub fn peak_normalise(audio: &PcmAudio, target_dbfs: f32) -> PcmAudio {
    let peak = audio.peak();
    if peak == 0.0 {
        return audio.clone();
    }
    let target_linear = 10f32.powf(target_dbfs / 20.0);
    let gain = target_linear / peak;
    let scaled: Vec<f32> = audio.samples.iter().map(|s| s * gain).collect();
    PcmAudio::new(scaled, audio.sample_rate)
}

/// Time-stretch by `factor` (1.0 = no change, <1 speeds up, >1
/// slows down). Used to normalise vendor-injected playback-rate
/// distortion before STT.
///
/// Cheap WSOLA-style impl: split into overlapping frames, jitter
/// the read positions to compensate. Good enough for STT
/// preprocessing; not pitch-perfect for music.
pub fn time_stretch(audio: &PcmAudio, factor: f32) -> PcmAudio {
    if (factor - 1.0).abs() < 1e-3 || audio.samples.is_empty() {
        return audio.clone();
    }
    let frame_size = (0.040 * audio.sample_rate as f32) as usize; // 40ms
    let hop_in = (frame_size / 2) as f32;
    let hop_out = hop_in / factor;
    let mut out: Vec<f32> = Vec::with_capacity((audio.samples.len() as f32 / factor) as usize);
    let mut read_pos = 0.0f32;
    while (read_pos as usize) + frame_size < audio.samples.len() {
        let start = read_pos as usize;
        let end = start + frame_size;
        out.extend_from_slice(&audio.samples[start..end]);
        read_pos += hop_out;
    }
    PcmAudio::new(out, audio.sample_rate)
}

/// Run the full pipeline on raw vendor audio bytes. Returns the
/// pre-processed PCM ready to feed to STT.
///
/// Stages: decode → denoise (200ms head) → bandpass 80-3500 Hz →
/// peak-normalise to -1 dBFS. Time-stretch is OFF by default (the
/// solver only enables it when the vendor's challenge has known
/// playback-rate distortion — currently reCAPTCHA accessibility
/// audio at 1.0× is the default).
pub fn preprocess_for_stt(bytes: &[u8]) -> Result<PcmAudio> {
    let raw = decode_to_pcm(bytes)?;
    let denoised = spectral_subtraction_denoise(&raw, 200);
    let bp = bandpass_filter(&denoised, 80.0, 3500.0);
    let normalised = peak_normalise(&bp, -1.0);
    Ok(normalised)
}

/// Re-encode a [`PcmAudio`] back to a 16-bit-LE WAV byte stream.
/// The STT solver pipes the bytes returned by [`preprocess_for_stt`]
/// to whisper-cli / OpenAI Whisper API / Deepgram via this encoder.
pub fn encode_wav_pcm16(audio: &PcmAudio) -> Vec<u8> {
    let num_samples = audio.samples.len();
    let bytes_per_sample = 2;
    let num_channels: u16 = 1;
    let byte_rate = audio.sample_rate * (bytes_per_sample as u32) * (num_channels as u32);
    let block_align = bytes_per_sample as u16 * num_channels;
    let data_size = num_samples * bytes_per_sample;
    let riff_size = 36 + data_size;

    let mut out = Vec::with_capacity(44 + data_size);
    out.extend_from_slice(b"RIFF");
    out.extend_from_slice(&(riff_size as u32).to_le_bytes());
    out.extend_from_slice(b"WAVE");
    out.extend_from_slice(b"fmt ");
    out.extend_from_slice(&16u32.to_le_bytes()); // fmt chunk size
    out.extend_from_slice(&1u16.to_le_bytes()); // audio_format = PCM
    out.extend_from_slice(&num_channels.to_le_bytes());
    out.extend_from_slice(&audio.sample_rate.to_le_bytes());
    out.extend_from_slice(&byte_rate.to_le_bytes());
    out.extend_from_slice(&block_align.to_le_bytes());
    out.extend_from_slice(&((bytes_per_sample * 8) as u16).to_le_bytes());
    out.extend_from_slice(b"data");
    out.extend_from_slice(&(data_size as u32).to_le_bytes());
    for s in &audio.samples {
        let clamped = s.clamp(-1.0, 1.0);
        let i = (clamped * i16::MAX as f32) as i16;
        out.extend_from_slice(&i.to_le_bytes());
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Build a synthetic mono 16-bit-LE WAV at `sample_rate` Hz
    /// containing `samples`, ready to feed to [`decode_to_pcm`].
    /// Used by the round-trip and pipeline tests.
    fn synth_wav(samples: &[i16], sample_rate: u32) -> Vec<u8> {
        let num_samples = samples.len();
        let bytes_per_sample = 2;
        let data_size = num_samples * bytes_per_sample;
        let riff_size = 36 + data_size;
        let mut out = Vec::with_capacity(44 + data_size);
        out.extend_from_slice(b"RIFF");
        out.extend_from_slice(&(riff_size as u32).to_le_bytes());
        out.extend_from_slice(b"WAVE");
        out.extend_from_slice(b"fmt ");
        out.extend_from_slice(&16u32.to_le_bytes());
        out.extend_from_slice(&1u16.to_le_bytes());
        out.extend_from_slice(&1u16.to_le_bytes());
        out.extend_from_slice(&sample_rate.to_le_bytes());
        out.extend_from_slice(&(sample_rate * 2).to_le_bytes());
        out.extend_from_slice(&2u16.to_le_bytes());
        out.extend_from_slice(&16u16.to_le_bytes());
        out.extend_from_slice(b"data");
        out.extend_from_slice(&(data_size as u32).to_le_bytes());
        for s in samples {
            out.extend_from_slice(&s.to_le_bytes());
        }
        out
    }

    #[test]
    fn decode_to_pcm_rejects_too_short_input() {
        let err = decode_to_pcm(b"short").unwrap_err().to_string();
        assert!(err.contains("too short"));
    }

    #[test]
    fn decode_to_pcm_rejects_non_riff_container() {
        let mut bytes = vec![0u8; 100];
        bytes[..4].copy_from_slice(b"NOPE");
        let err = decode_to_pcm(&bytes).unwrap_err().to_string();
        assert!(err.contains("RIFF"));
    }

    #[test]
    fn decode_to_pcm_round_trips_synthetic_wav() {
        let samples: Vec<i16> = (0..1000)
            .map(|i| ((i as f32 * 0.05).sin() * 16000.0) as i16)
            .collect();
        let wav = synth_wav(&samples, TARGET_SAMPLE_RATE);
        let pcm = decode_to_pcm(&wav).expect("decode synth WAV");
        assert_eq!(pcm.sample_rate, TARGET_SAMPLE_RATE);
        assert_eq!(pcm.samples.len(), samples.len());
        // Round-trip precision: -16 bit signed → f32 → ε ≤ 1/32768.
        for (i, (got, want)) in pcm.samples.iter().zip(&samples).enumerate() {
            let want_f = *want as f32 / i16::MAX as f32;
            assert!((got - want_f).abs() < 1e-4, "mismatch at {i}: {got} vs {want_f}");
        }
    }

    #[test]
    fn decode_to_pcm_resamples_non_target_rate_to_target() {
        // Synth at 8 kHz; pipeline normalises to 16 kHz.
        let samples: Vec<i16> = (0..400).map(|i| ((i as f32 * 0.1).sin() * 8000.0) as i16).collect();
        let wav = synth_wav(&samples, 8_000);
        let pcm = decode_to_pcm(&wav).expect("decode 8kHz");
        assert_eq!(pcm.sample_rate, TARGET_SAMPLE_RATE);
        // Resampled length ≈ 2× original (8k → 16k).
        assert!(pcm.samples.len() >= samples.len() * 19 / 10);
        assert!(pcm.samples.len() <= samples.len() * 21 / 10);
    }

    #[test]
    fn pcm_duration_secs_handles_zero_sample_rate() {
        let p = PcmAudio { samples: vec![0.0; 100], sample_rate: 0 };
        assert_eq!(p.duration_secs(), 0.0);
    }

    #[test]
    fn pcm_peak_returns_max_abs_sample() {
        let p = PcmAudio::new(vec![0.0, -0.5, 0.3, -0.7, 0.2], 16000);
        assert!((p.peak() - 0.7).abs() < 1e-6);
    }

    #[test]
    fn pcm_rms_returns_root_mean_square() {
        // RMS of [1, 1, 1, 1] = 1.
        let p = PcmAudio::new(vec![1.0; 4], 16000);
        assert!((p.rms() - 1.0).abs() < 1e-6);
        // RMS of [0, 0, 0, 0] = 0.
        let p = PcmAudio::new(vec![0.0; 4], 16000);
        assert_eq!(p.rms(), 0.0);
        // RMS of empty = 0 (no panic).
        let p = PcmAudio::new(vec![], 16000);
        assert_eq!(p.rms(), 0.0);
    }

    #[test]
    fn peak_normalise_brings_peak_to_target_dbfs() {
        let p = PcmAudio::new(vec![0.1, -0.2, 0.05], 16000);
        let normalised = peak_normalise(&p, -1.0);
        let expected_peak = 10f32.powf(-1.0 / 20.0); // ~0.891
        assert!((normalised.peak() - expected_peak).abs() < 1e-4);
    }

    #[test]
    fn peak_normalise_handles_silent_input_without_div_by_zero() {
        let silent = PcmAudio::new(vec![0.0; 100], 16000);
        let out = peak_normalise(&silent, -1.0);
        assert_eq!(out.peak(), 0.0);
        assert_eq!(out.samples.len(), 100);
    }

    #[test]
    fn bandpass_filter_attenuates_dc_offset() {
        // DC offset of 0.5 — a 1-pole highpass should eliminate it
        // within the filter's transient (~few hundred samples).
        let p = PcmAudio::new(vec![0.5; 16_000], 16_000);
        let filtered = bandpass_filter(&p, 80.0, 3500.0);
        // Drop the first 1 second of transient; tail should be ~0.
        let tail_rms = {
            let tail = &filtered.samples[8000..];
            let sum_sq: f32 = tail.iter().map(|s| s * s).sum();
            (sum_sq / tail.len() as f32).sqrt()
        };
        assert!(tail_rms < 0.05, "DC offset survived bandpass: tail RMS = {tail_rms}");
    }

    #[test]
    fn spectral_subtraction_attenuates_constant_noise_below_signal() {
        // 0.05 RMS noise + 0.5 spike — denoiser should keep the
        // spike while attenuating the noise floor.
        let mut samples = vec![0.05f32; 16_000];
        samples[8000] = 0.5;
        let p = PcmAudio::new(samples, 16_000);
        let denoised = spectral_subtraction_denoise(&p, 200);
        // Spike should still be near 0.5 (above the noise floor).
        assert!(denoised.samples[8000].abs() > 0.4, "spike was attenuated: {}", denoised.samples[8000]);
        // Pre-spike noise should be reduced.
        let tail_pre = &denoised.samples[1000..7000];
        let pre_rms = {
            let sum_sq: f32 = tail_pre.iter().map(|s| s * s).sum();
            (sum_sq / tail_pre.len() as f32).sqrt()
        };
        assert!(pre_rms < 0.05, "noise floor not attenuated: pre-spike RMS = {pre_rms}");
    }

    #[test]
    fn time_stretch_factor_one_returns_unchanged() {
        let p = PcmAudio::new(vec![0.1, 0.2, 0.3], 16000);
        let out = time_stretch(&p, 1.0);
        assert_eq!(out.samples, p.samples);
    }

    #[test]
    fn time_stretch_speeds_up_when_factor_below_one() {
        let p = PcmAudio::new(vec![0.1; 16_000], 16_000);
        let out = time_stretch(&p, 0.5);
        // Output is roughly half the length (1.5-2× speed-up frames).
        assert!(
            out.samples.len() < p.samples.len(),
            "factor=0.5 should shorten: {} vs {}",
            out.samples.len(),
            p.samples.len()
        );
    }

    #[test]
    fn encode_wav_pcm16_produces_valid_header() {
        let p = PcmAudio::new(vec![0.0, 0.5, -0.5, 0.25], 16000);
        let wav = encode_wav_pcm16(&p);
        assert_eq!(&wav[..4], b"RIFF");
        assert_eq!(&wav[8..12], b"WAVE");
        assert_eq!(&wav[12..16], b"fmt ");
        assert_eq!(&wav[36..40], b"data");
        // Header (44) + 4 samples × 2 bytes = 52.
        assert_eq!(wav.len(), 52);
    }

    #[test]
    fn encode_then_decode_round_trips_pcm() {
        let original = PcmAudio::new(
            (0..1000).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(),
            16_000,
        );
        let wav = encode_wav_pcm16(&original);
        let decoded = decode_to_pcm(&wav).expect("round-trip decode");
        assert_eq!(decoded.sample_rate, original.sample_rate);
        assert_eq!(decoded.samples.len(), original.samples.len());
        // 16-bit quantisation error: ε ~ 1/32768.
        for (a, b) in decoded.samples.iter().zip(original.samples.iter()) {
            assert!((a - b).abs() < 1e-3, "round-trip diff {a} vs {b}");
        }
    }

    #[test]
    fn encode_wav_clamps_overdriven_samples_instead_of_overflowing() {
        // Samples >1.0 must clamp, never wrap. An i16 wraparound
        // would produce loud clicks in the STT input.
        let p = PcmAudio::new(vec![2.0, -2.0, 1.0, -1.0], 16000);
        let wav = encode_wav_pcm16(&p);
        let decoded = decode_to_pcm(&wav).unwrap();
        assert!((decoded.samples[0] - 1.0).abs() < 1e-3);
        assert!((decoded.samples[1] - -1.0).abs() < 1e-3);
    }

    #[test]
    fn preprocess_for_stt_runs_full_pipeline_without_panic() {
        // A synthetic noisy sine — exercises every stage.
        let raw_samples: Vec<i16> = (0..16_000 * 2)
            .map(|i| {
                let signal = (i as f32 * 0.05).sin() * 8000.0;
                let noise = ((i * 7919) % 100 - 50) as f32 * 80.0;
                (signal + noise) as i16
            })
            .collect();
        let wav = synth_wav(&raw_samples, 16_000);
        let processed = preprocess_for_stt(&wav).expect("pipeline must not panic");
        assert_eq!(processed.sample_rate, TARGET_SAMPLE_RATE);
        assert!(!processed.samples.is_empty());
        // Peak-normalisation target: -1 dBFS = ~0.891.
        let expected_peak = 10f32.powf(-1.0 / 20.0);
        assert!(
            (processed.peak() - expected_peak).abs() < 0.05,
            "peak normalisation off: {}",
            processed.peak()
        );
    }

    #[test]
    fn preprocess_for_stt_rejects_invalid_input_with_actionable_error() {
        // Garbage bytes — caller (the AudioCaptchaSolver) must see
        // a clear error so it can fall back to other paths instead
        // of silently submitting empty audio to whisper.
        let err = preprocess_for_stt(b"not a wav").unwrap_err().to_string();
        assert!(err.contains("too short") || err.contains("RIFF"));
    }
}