adk-audio 3.0.0

Audio intelligence and pipeline orchestration for ADK-Rust agents
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
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
//! Dedicated inference thread that owns the MLX Whisper model.
//!
//! MLX arrays, the KV cache and the host scratch buffers live on one OS thread
//! (`adk-audio-mlx-whisper`); async callers hand it PCM over a bounded channel
//! (awaiting a free slot under load) and await the transcript on a oneshot.

use std::sync::mpsc;

use bytes::Bytes;
use mlx_rs::Array;
use tokenizers::Tokenizer;
use tokio::sync::{mpsc as async_mpsc, oneshot};

use super::decode::{DecodeScratch, KvCache, greedy};
use super::mel::{MelFrontend, N_SAMPLES};
use super::model::Whisper;
use super::stt_error;
use crate::error::{AudioError, AudioResult};
use crate::mlx::checkpoint::WhisperDims;
use crate::pcm::{pcm16_to_f32_mono_into, resample_to_16khz_into};
use crate::traits::Transcript;

/// Whisper input sample rate.
const SAMPLE_RATE: u32 = 16_000;
/// Requests queued for the worker; further callers wait for a free slot.
const QUEUE_DEPTH: usize = 32;
/// Language used when the caller gives none (and always, for English-only
/// models). Whisper's own language detection is not run; pass
/// `SttOptions::language` for non-English audio.
const DEFAULT_LANGUAGE: &str = "en";
/// Initial capacity of the joined transcript buffer.
const TEXT_CAPACITY: usize = 1024;

/// One transcription request.
struct Request {
    pcm: Bytes,
    sample_rate: u32,
    channels: u8,
    language: Option<Box<str>>,
    reply: oneshot::Sender<AudioResult<Transcript>>,
}

/// Message to the worker thread.
enum Job {
    Transcribe(Request),
    /// Test hook: kills the worker thread.
    #[cfg(test)]
    Panic,
}

/// Handle to the MLX Whisper inference thread. Dropping it stops the thread
/// once queued requests are done.
pub(crate) struct WhisperWorker {
    tx: async_mpsc::Sender<Job>,
}

/// Number of 30 s windows covering `len` 16 kHz samples.
fn window_count(len: usize) -> usize {
    len.div_ceil(N_SAMPLES)
}

#[cold]
fn worker_stopped() -> AudioError {
    stt_error("MLX worker stopped")
}

impl WhisperWorker {
    /// Starts the worker thread, runs `load` on it and blocks until the model,
    /// mel front end and buffers are ready (or loading failed). Call from a
    /// blocking context: loading a checkpoint takes seconds.
    pub fn spawn(
        load: impl FnOnce() -> AudioResult<(Whisper, Tokenizer)> + Send + 'static,
        max_duration_secs: u32,
    ) -> AudioResult<Self> {
        let (tx, mut rx) = async_mpsc::channel::<Job>(QUEUE_DEPTH);
        let (ready_tx, ready_rx) = mpsc::sync_channel::<AudioResult<()>>(1);
        std::thread::Builder::new()
            .name("adk-audio-mlx-whisper".into())
            .spawn(move || {
                let state = load().and_then(|(model, tokenizer)| {
                    Engine::new(model, tokenizer, max_duration_secs)
                });
                let mut engine = match state {
                    Ok(engine) => engine,
                    Err(e) => {
                        let _ = ready_tx.send(Err(e));
                        return;
                    }
                };
                let _ = ready_tx.send(Ok(()));
                drop(ready_tx);
                while let Some(job) = rx.blocking_recv() {
                    match job {
                        Job::Transcribe(request) => {
                            // Skip requests whose caller has already gone away.
                            if request.reply.is_closed() {
                                continue;
                            }
                            let result = engine.transcribe(&request);
                            let _ = request.reply.send(result);
                        }
                        #[cfg(test)]
                        Job::Panic => panic!("test hook: MLX worker panic"),
                    }
                }
            })
            .map_err(|e| stt_error(format!("failed to spawn the MLX worker thread: {e}")))?;
        match ready_rx.recv() {
            Ok(Ok(())) => Ok(Self { tx }),
            Ok(Err(e)) => Err(e),
            Err(_) => Err(stt_error("MLX worker panicked while loading the model")),
        }
    }

    /// Transcribes PCM-16 LE `pcm` (`channels` interleaved, `sample_rate` Hz).
    /// `language` is a Whisper language code such as `en`; `None` means `en`.
    ///
    /// Requests are served in arrival order. With [`QUEUE_DEPTH`] requests
    /// already queued, this awaits a free slot (async backpressure; it never
    /// blocks the runtime).
    pub async fn transcribe(
        &self,
        pcm: Bytes,
        sample_rate: u32,
        channels: u8,
        language: Option<Box<str>>,
    ) -> AudioResult<Transcript> {
        let (reply, rx) = oneshot::channel();
        let request = Request { pcm, sample_rate, channels, language, reply };
        self.tx.send(Job::Transcribe(request)).await.map_err(|_| worker_stopped())?;
        rx.await.map_err(|_| worker_stopped())?
    }
}

/// Worker-owned host buffers, reused across requests.
struct Scratch {
    /// Mono f32 input at the caller's rate (zero-padded in place at 16 kHz).
    pcm: Vec<f32>,
    /// 16 kHz resampled input, zero-padded to whole windows.
    resampled: Vec<f32>,
    /// Joined transcript.
    text: String,
    decode: DecodeScratch,
}

impl Scratch {
    fn new(dims: &WhisperDims, max_duration_secs: u32) -> Self {
        // Ten minutes are reserved up front; a higher limit grows the buffers with the audio
        // submitted, so the limit itself never sizes an allocation.
        let reserved_secs = max_duration_secs.min(PREALLOCATED_SECS);
        let max_samples = reserved_secs as usize * SAMPLE_RATE as usize;
        let capacity = window_count(max_samples).max(1) * N_SAMPLES;
        Self {
            pcm: Vec::with_capacity(capacity),
            resampled: Vec::with_capacity(capacity),
            text: String::with_capacity(TEXT_CAPACITY),
            decode: DecodeScratch::new(dims),
        }
    }
}

/// OpenAI's rule: multilingual Whisper vocabularies have at least 51 865
/// tokens; English-only (`*.en`) models have 51 864.
const fn is_multilingual(n_vocab: u32) -> bool {
    n_vocab >= 51_865
}

/// Longest prompt: `<|startoftranscript|>`, language, task, `<|notimestamps|>`.
const MAX_PROMPT: usize = 4;

/// Audio the worker's buffers hold without growing: the default `max_duration_secs`.
const PREALLOCATED_SECS: u32 = 600;

/// Root-mean-square level, about -80 dBFS, below which a window is silence and yields no
/// text: Whisper answers digital silence and zero padding with a stock word.
const SILENCE_RMS: f32 = 1e-4;

/// Language and task token ids of a multilingual vocabulary.
struct LanguageTokens {
    default_language: u32,
    translate: u32,
    transcribe: u32,
}

/// Special token ids, resolved once from the tokenizer.
struct Specials {
    eot: u32,
    sot: u32,
    notimestamps: u32,
    /// `None` for English-only models, which take no language or task token.
    multilingual: Option<LanguageTokens>,
}

impl Specials {
    /// Resolves the ids and checks Whisper's vocabulary layout: text tokens,
    /// then `<|endoftext|>`, `<|startoftranscript|>`, languages,
    /// `<|translate|>`, `<|transcribe|>`, …, `<|notimestamps|>`, timestamps.
    fn resolve(tokenizer: &Tokenizer, n_vocab: u32) -> AudioResult<Self> {
        let id = |token: &str| {
            tokenizer.token_to_id(token).ok_or_else(|| {
                stt_error(format!("tokenizer has no {token} token; not a Whisper tokenizer"))
            })
        };
        let (sot, eot, notimestamps) =
            (id("<|startoftranscript|>")?, id("<|endoftext|>")?, id("<|notimestamps|>")?);
        let mut ordered = eot < sot && sot < notimestamps && notimestamps < n_vocab;
        let multilingual = if is_multilingual(n_vocab) {
            let m = LanguageTokens {
                default_language: id(&format!("<|{DEFAULT_LANGUAGE}|>"))?,
                translate: id("<|translate|>")?,
                transcribe: id("<|transcribe|>")?,
            };
            ordered &= sot < m.default_language
                && m.default_language < m.translate
                && m.translate < m.transcribe
                && m.transcribe < notimestamps;
            Some(m)
        } else {
            None
        };
        if !ordered {
            return Err(stt_error(format!(
                "unexpected Whisper special token ids (eot {eot}, sot {sot}, notimestamps \
                 {notimestamps}, n_vocab {n_vocab})"
            )));
        }
        Ok(Self { eot, sot, notimestamps, multilingual })
    }

    /// Prompt tokens as a stack array plus its length: `[sot, language,
    /// transcribe, notimestamps]` for multilingual models, `[sot,
    /// notimestamps]` for English-only ones (`language` is then ignored).
    fn prompt(&self, language: u32) -> ([u32; MAX_PROMPT], usize) {
        match &self.multilingual {
            Some(m) => ([self.sot, language, m.transcribe, self.notimestamps], 4),
            None => ([self.sot, self.notimestamps, 0, 0], 2),
        }
    }

    fn prompt_len(&self) -> usize {
        if self.multilingual.is_some() { 4 } else { 2 }
    }
}

/// Everything the worker thread owns.
struct Engine {
    model: Whisper,
    tokenizer: Tokenizer,
    mel: MelFrontend,
    cache: KvCache,
    specials: Specials,
    /// `[n_vocab]` f32 logit bias: `-inf` on every id from
    /// `<|startoftranscript|>` up (languages, task, no-speech, timestamps), so
    /// greedy decoding emits only text tokens and `<|endoftext|>`.
    suppress: Array,
    /// Generated-token budget per window (`n_text_ctx` minus the prompt).
    max_new: usize,
    max_duration_secs: u32,
    scratch: Scratch,
}

impl Engine {
    fn new(model: Whisper, tokenizer: Tokenizer, max_duration_secs: u32) -> AudioResult<Self> {
        let dims = *model.dims();
        let specials = Specials::resolve(&tokenizer, dims.n_vocab)?;
        let n_vocab = dims.n_vocab as usize;
        let mut bias = vec![0.0f32; n_vocab];
        bias[specials.sot as usize..].fill(f32::NEG_INFINITY);
        let suppress = Array::from_slice(&bias, &[dims.n_vocab as i32]);
        let max_new = (dims.n_text_ctx as usize)
            .checked_sub(specials.prompt_len())
            .filter(|&n| n > 0)
            .ok_or_else(|| {
                stt_error(format!("n_text_ctx {} leaves no room to decode", dims.n_text_ctx))
            })?;
        Ok(Self {
            mel: MelFrontend::new(dims.n_mels as usize)?,
            cache: KvCache::new(&model)?,
            scratch: Scratch::new(&dims, max_duration_secs),
            model,
            tokenizer,
            specials,
            suppress,
            max_new,
            max_duration_secs,
        })
    }

    /// Language code used and its token id (`0` for English-only models,
    /// whose prompt has no language token).
    fn language<'a>(&self, requested: Option<&'a str>) -> AudioResult<(&'a str, u32)> {
        let s = &self.specials;
        let Some(m) = &s.multilingual else {
            return Ok((DEFAULT_LANGUAGE, 0));
        };
        let Some(code) = requested else {
            return Ok((DEFAULT_LANGUAGE, m.default_language));
        };
        self.tokenizer
            .token_to_id(&format!("<|{code}|>"))
            .filter(|&id| id > s.sot && id < m.translate)
            .map(|id| (code, id))
            .ok_or_else(|| stt_error(format!("unknown Whisper language {code}")))
    }

    fn transcribe(&mut self, req: &Request) -> AudioResult<Transcript> {
        if req.sample_rate == 0 {
            return Err(stt_error("invalid sample rate 0 Hz"));
        }
        if req.channels == 0 {
            return Err(stt_error("invalid channel count 0"));
        }
        let frames = req.pcm.len() / (2 * req.channels as usize);
        if frames == 0 {
            return Err(stt_error("empty audio input"));
        }
        let secs = frames as f64 / req.sample_rate as f64;
        if secs > self.max_duration_secs as f64 {
            return Err(stt_error(format!(
                "audio is {secs:.1} s, over the {} s limit",
                self.max_duration_secs
            )));
        }
        let (code, language) = self.language(req.language.as_deref())?;
        let sp = &self.specials;
        let (prompt, prompt_len) = sp.prompt(language);
        let prompt = &prompt[..prompt_len];

        let scratch = &mut self.scratch;
        pcm16_to_f32_mono_into(&req.pcm, req.channels, &mut scratch.pcm);
        let samples = if req.sample_rate == SAMPLE_RATE {
            &mut scratch.pcm
        } else {
            resample_to_16khz_into(&scratch.pcm, req.sample_rate, &mut scratch.resampled);
            &mut scratch.resampled
        };
        if samples.is_empty() {
            return Err(stt_error("empty audio input"));
        }
        let windows = window_count(samples.len());
        samples.resize(windows * N_SAMPLES, 0.0);

        scratch.text.clear();
        let mut generated = 0;
        for window in samples.chunks_exact(N_SAMPLES) {
            // The caller dropped the request: the remaining windows are not decoded.
            if req.reply.is_closed() {
                return Err(stt_error("the transcription was cancelled"));
            }
            let energy: f32 = window.iter().map(|sample| sample * sample).sum();
            if (energy / N_SAMPLES as f32).sqrt() < SILENCE_RMS {
                continue;
            }
            let pcm = Array::from_slice(window, &[N_SAMPLES as i32]);
            let mel = self.mel.log_mel(&pcm)?;
            let audio = self.model.encode(&mel)?;
            greedy(
                &self.model,
                &audio,
                prompt,
                sp.eot,
                &self.suppress,
                &mut self.cache,
                &mut scratch.decode,
            )?;
            generated += scratch.decode.tokens.len();
            let text = self
                .tokenizer
                .decode(&scratch.decode.tokens, true)
                .map_err(|e| stt_error(format!("tokenizer decode failed: {e}")))?;
            let text = text.trim();
            if !text.is_empty() {
                if !scratch.text.is_empty() {
                    scratch.text.push(' ');
                }
                scratch.text.push_str(text);
            }
        }

        // Same heuristic as the ONNX Whisper backend: the less of the decode
        // budget used, the more confident (no per-token probabilities yet).
        let confidence = if generated == 0 {
            0.0
        } else {
            (1.0 - generated as f32 / (windows * self.max_new) as f32).max(0.1)
        };
        Ok(Transcript {
            text: scratch.text.clone(),
            confidence,
            language_detected: Some(code.to_owned()),
            ..Default::default()
        })
    }
}

#[cfg(test)]
pub(crate) mod tests {
    use std::sync::Arc;
    use std::time::Duration;

    use super::*;

    /// Tiny model that still takes real 30 s mel windows (`n_audio_ctx = 1500`)
    /// and has a multilingual-sized vocabulary (51 865; see `is_multilingual`).
    pub(crate) fn test_dims() -> WhisperDims {
        WhisperDims {
            n_mels: 80,
            n_audio_ctx: 1500,
            n_audio_state: 32,
            n_audio_head: 2,
            n_audio_layer: 1,
            n_vocab: 51_865,
            n_text_ctx: 16,
            n_text_state: 32,
            n_text_head: 2,
            n_text_layer: 1,
        }
    }

    /// Word-level tokenizer over ids 0..64: `w0`..`w55` plus Whisper's special
    /// tokens at 56..64 in their real relative order. Higher model ids have no
    /// token and are suppressed (they sit above `<|startoftranscript|>`).
    pub(crate) fn test_tokenizer() -> Tokenizer {
        const SPECIALS: [&str; 8] = [
            "<|endoftext|>",
            "<|startoftranscript|>",
            "<|en|>",
            "<|de|>",
            "<|translate|>",
            "<|transcribe|>",
            "<|nospeech|>",
            "<|notimestamps|>",
        ];
        let n_words = 64 - SPECIALS.len();
        let vocab: serde_json::Map<String, serde_json::Value> =
            (0..n_words).map(|i| (format!("w{i}"), serde_json::json!(i))).collect();
        let added: Vec<_> = SPECIALS
            .iter()
            .enumerate()
            .map(|(i, content)| {
                serde_json::json!({
                    "id": n_words + i, "content": content, "single_word": false,
                    "lstrip": false, "rstrip": false, "normalized": false, "special": true
                })
            })
            .collect();
        let json = serde_json::json!({
            "version": "1.0", "truncation": null, "padding": null,
            "added_tokens": added, "normalizer": null,
            "pre_tokenizer": { "type": "Whitespace" },
            "post_processor": null, "decoder": null,
            "model": { "type": "WordLevel", "vocab": vocab, "unk_token": "w0" }
        });
        Tokenizer::from_bytes(json.to_string().as_bytes()).unwrap()
    }

    fn spawn_random(max_duration_secs: u32) -> WhisperWorker {
        WhisperWorker::spawn(
            || Ok((Whisper::random(test_dims(), 11)?, test_tokenizer())),
            max_duration_secs,
        )
        .unwrap()
    }

    /// `secs` of a deterministic chirp at 16 kHz as mono f32.
    fn chirp(secs: f32) -> Vec<f32> {
        let n = (secs * SAMPLE_RATE as f32) as usize;
        (0..n)
            .map(|i| {
                let t = i as f32 / SAMPLE_RATE as f32;
                0.4 * (2.0 * std::f32::consts::PI * (200.0 + 300.0 * t) * t).sin()
            })
            .collect()
    }

    fn pcm16(samples: impl IntoIterator<Item = f32>) -> Bytes {
        samples
            .into_iter()
            .flat_map(|s| ((s * 32767.0) as i16).to_le_bytes())
            .collect::<Vec<u8>>()
            .into()
    }

    fn assert_stt_error(result: AudioResult<Transcript>, expected: &str) {
        match result {
            Err(AudioError::Stt { provider, message }) => {
                assert_eq!(provider, "MLX");
                assert_eq!(message, expected);
            }
            Err(e) => panic!("unexpected error {e}"),
            Ok(t) => panic!("expected error {expected:?}, got {t:?}"),
        }
    }

    #[test]
    fn a_duration_limit_above_ten_minutes_reserves_ten_minutes() {
        let reserved = (PREALLOCATED_SECS as usize * SAMPLE_RATE as usize).div_ceil(N_SAMPLES);
        for limit in [3_600, u32::MAX] {
            let scratch = Scratch::new(&test_dims(), limit);
            assert_eq!(scratch.pcm.capacity(), reserved * N_SAMPLES);
            assert_eq!(scratch.resampled.capacity(), reserved * N_SAMPLES);
        }
        assert_eq!(Scratch::new(&test_dims(), 30).pcm.capacity(), N_SAMPLES);
    }

    #[test]
    fn window_count_exact_30s() {
        assert_eq!(window_count(480_000), 1);
    }

    #[test]
    fn window_count_30s_plus_one() {
        assert_eq!(window_count(480_001), 2);
    }

    #[test]
    fn spawn_reports_load_error() {
        let result = WhisperWorker::spawn(|| Err(stt_error("boom")), 30);
        match result {
            Err(AudioError::Stt { message, .. }) => assert_eq!(message, "boom"),
            Err(e) => panic!("unexpected error {e}"),
            Ok(_) => panic!("load error swallowed"),
        }
    }

    #[test]
    fn spawn_rejects_tokenizer_without_whisper_specials() {
        let result = WhisperWorker::spawn(
            || {
                let tok = Tokenizer::new(tokenizers::models::bpe::BPE::default());
                Ok((Whisper::random(test_dims(), 11)?, tok))
            },
            30,
        );
        match result {
            Err(AudioError::Stt { message, .. }) => {
                assert!(message.contains("<|startoftranscript|>"), "{message}")
            }
            Err(e) => panic!("unexpected error {e}"),
            Ok(_) => panic!("tokenizer without special tokens accepted"),
        }
    }

    #[tokio::test]
    async fn transcribe_over_limit_errors() {
        let worker = spawn_random(1);
        let pcm = pcm16(chirp(1.5));
        let result = worker.transcribe(pcm, SAMPLE_RATE, 1, None).await;
        assert_stt_error(result, "audio is 1.5 s, over the 1 s limit");
    }

    #[tokio::test]
    async fn transcribe_short_clip_ok() {
        let worker = spawn_random(30);
        let transcript = worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 1, None).await.unwrap();
        assert_eq!(transcript.language_detected.as_deref(), Some("en"));
        assert!(transcript.words.is_empty() && transcript.speakers.is_empty());
        assert!((0.0..=1.0).contains(&transcript.confidence));
        assert!(!transcript.text.contains("<|"), "special tokens leaked: {:?}", transcript.text);
        assert_eq!(transcript.text, transcript.text.trim());

        let de =
            worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 1, Some("de".into())).await.unwrap();
        assert_eq!(de.language_detected.as_deref(), Some("de"));
    }

    #[tokio::test]
    async fn transcribe_unknown_language_errors() {
        let worker = spawn_random(30);
        let result = worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 1, Some("xx".into())).await;
        assert_stt_error(result, "unknown Whisper language xx");
        // Special tokens that are not languages are rejected too.
        let result =
            worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 1, Some("transcribe".into())).await;
        assert_stt_error(result, "unknown Whisper language transcribe");
    }

    #[tokio::test]
    async fn transcribe_empty_errors() {
        let worker = spawn_random(30);
        let result = worker.transcribe(Bytes::new(), SAMPLE_RATE, 1, None).await;
        assert_stt_error(result, "empty audio input");
        let result = worker.transcribe(pcm16(chirp(0.2)), 0, 1, None).await;
        assert_stt_error(result, "invalid sample rate 0 Hz");
        let result = worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 0, None).await;
        assert_stt_error(result, "invalid channel count 0");
    }

    #[tokio::test]
    async fn a_silent_window_yields_no_text() {
        let worker = spawn_random(60);
        // The random model emits tokens for any window it decodes, so empty text means
        // the window was skipped.
        let silence = pcm16(vec![0.0; SAMPLE_RATE as usize * 2]);
        let transcript = worker.transcribe(silence, SAMPLE_RATE, 1, None).await.unwrap();
        assert_eq!(transcript.text, "");
        assert_eq!(transcript.confidence, 0.0);
    }

    #[tokio::test]
    async fn transcribe_two_windows() {
        let worker = spawn_random(60);
        let mut samples = chirp(30.0);
        samples.push(0.1);
        let transcript = worker.transcribe(pcm16(samples), SAMPLE_RATE, 1, None).await.unwrap();
        assert!(!transcript.text.contains("  "), "double space: {:?}", transcript.text);
    }

    #[tokio::test]
    async fn transcribe_resamples_48k_stereo() {
        let worker = spawn_random(30);
        let mono = chirp(1.0);
        // Every third 48 kHz frame is the 16 kHz sample (L = R), so linear
        // resampling and downmixing reproduce the 16 kHz input exactly.
        let stereo_48k = mono.iter().flat_map(|&s| [s, s, s, s, s, s]);
        let a = worker.transcribe(pcm16(mono.iter().copied()), SAMPLE_RATE, 1, None).await.unwrap();
        let b = worker.transcribe(pcm16(stereo_48k), 48_000, 2, None).await.unwrap();
        assert_eq!(a.text, b.text);
        assert_eq!(a.confidence, b.confidence);
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn concurrent_transcribes_complete() {
        let worker = Arc::new(spawn_random(30));
        let pcm = pcm16(chirp(0.2));
        let tasks: Vec<_> = (0..16)
            .map(|_| {
                let worker = Arc::clone(&worker);
                let pcm = pcm.clone();
                tokio::spawn(async move { worker.transcribe(pcm, SAMPLE_RATE, 1, None).await })
            })
            .collect();
        let mut texts = Vec::with_capacity(tasks.len());
        for task in tasks {
            texts.push(task.await.unwrap().unwrap().text);
        }
        assert!(texts.windows(2).all(|w| w[0] == w[1]), "nondeterministic: {texts:?}");
    }

    #[test]
    fn prompt_matches_openai_sot_sequence() {
        let tok = test_tokenizer();
        let id = |t: &str| tok.token_to_id(t).unwrap();
        let (sot, en, de, transcribe, notimestamps) = (
            id("<|startoftranscript|>"),
            id("<|en|>"),
            id("<|de|>"),
            id("<|transcribe|>"),
            id("<|notimestamps|>"),
        );

        let multi = Specials::resolve(&tok, 51_865).unwrap();
        let (prompt, len) = multi.prompt(de);
        assert_eq!(&prompt[..len], [sot, de, transcribe, notimestamps]);
        assert_eq!(multi.prompt_len(), 4);
        assert_eq!(multi.multilingual.as_ref().unwrap().default_language, en);

        let english = Specials::resolve(&tok, 51_864).unwrap();
        let (prompt, len) = english.prompt(de);
        assert_eq!(&prompt[..len], [sot, notimestamps]);
        assert_eq!(english.prompt_len(), 2);
    }

    #[tokio::test]
    async fn english_only_model_ignores_language() {
        let dims = WhisperDims { n_vocab: 51_864, ..test_dims() };
        let worker =
            WhisperWorker::spawn(move || Ok((Whisper::random(dims, 11)?, test_tokenizer())), 30)
                .unwrap();
        let transcript =
            worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 1, Some("de".into())).await.unwrap();
        assert_eq!(transcript.language_detected.as_deref(), Some("en"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 4)]
    async fn requests_beyond_queue_depth_wait_instead_of_failing() {
        let worker = Arc::new(spawn_random(30));
        let pcm = pcm16(chirp(0.2));
        let tasks: Vec<_> = (0..2 * QUEUE_DEPTH)
            .map(|_| {
                let worker = Arc::clone(&worker);
                let pcm = pcm.clone();
                tokio::spawn(async move { worker.transcribe(pcm, SAMPLE_RATE, 1, None).await })
            })
            .collect();
        for task in tasks {
            task.await.unwrap().expect("queued request must complete");
        }
    }

    #[tokio::test]
    async fn worker_gone_returns_error() {
        let worker = spawn_random(30);
        worker.tx.send(Job::Panic).await.unwrap();
        for _ in 0..2 {
            let result = tokio::time::timeout(
                Duration::from_secs(5),
                worker.transcribe(pcm16(chirp(0.2)), SAMPLE_RATE, 1, None),
            )
            .await
            .expect("transcribe hung after the worker died");
            assert_stt_error(result, "MLX worker stopped");
        }
    }
}