loqui 0.4.0

Local speech for Rust: Kokoro text-to-speech and Whisper speech-to-text, in process, with no network listener.
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
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
//! Local speech for Rust: Kokoro text-to-speech and Whisper speech-to-text.
//!
//! An [`Engine`] runs both models in process. It opens no sockets and
//! listens on nothing; the only network access is fetching model weights,
//! pinned to commit revisions, and that can be switched off with
//! [`Downloads::Deny`]. To serve speech to other processes, see the
//! `loqui-server` crate, which puts an authenticated, explicitly exposed
//! HTTP API in front of an `Engine`.
//!
//! ```no_run
//! use loqui::{Engine, SpeakRequest};
//!
//! let engine = Engine::builder().build()?;
//! let speech = engine.speak(&SpeakRequest::new("Hello from loqui."))?;
//! std::fs::write("hello.wav", &speech.audio)?;
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```
//!
//! Models load on first use and, if given an idle timeout, unload when
//! unused. Everything is synchronous; call it from `spawn_blocking` in async
//! code.
//!
//! Before shipping an embedded engine, read
//! [Embedding loqui safely](https://github.com/Awakened-Labs/loqui/blob/main/docs/embedding.md): downloads, cache permissions, limits on
//! untrusted input, and the licensing each feature brings (leave `mp3` off in
//! proprietary programs).

mod blend_match;
mod models;
mod slot;
mod speaker;

use std::collections::{BTreeMap, BTreeSet};
use std::path::PathBuf;
use std::sync::{Arc, Weak};
use std::time::Duration;

// The error types `Error` wraps, so callers can match on the cause.
pub use blend_match::{Accent, BlendMatch, MAX_EVALUATIONS, MAX_VOICES, MIN_MATCH_SECS, MatchProgress, MatchRequest};
pub use loqui_audio::{Error as AudioError, Format};
pub use loqui_g2p::OovFallback;
pub use loqui_kokoro::{Blend, Error as TtsError};
pub use models::{Downloads, KokoroVariant, WHISPER_MODELS, WhisperModel, default_cache_dir, whisper_model};
pub use speaker::{MIN_EMBED_SECS, SpeakerEmbedding};

use loqui_kokoro::{Kokoro, KokoroModel};
use slot::Slot;

/// The id `/v1/models` lists for the Kokoro model.
pub const TTS_MODEL_ID: &str = "kokoro";

/// The id [`Engine::models`] lists for the speaker-embedding model.
pub const SPEAKER_MODEL_ID: &str = "wespeaker-resnet34-lm";

/// Non-exhaustive because `Stt` exists only with the `whisper` feature.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
    /// The request itself is invalid (empty text, unknown voice, bad speed).
    #[error("{0}")]
    Invalid(String),
    #[error("input is {chars} characters; the limit is {limit}")]
    InputTooLong { chars: usize, limit: usize },
    /// The engine was built without this capability.
    #[error("{0} is not enabled in this engine")]
    Disabled(&'static str),
    #[error("configuration: {0}")]
    Config(String),
    #[error("model unavailable: {0}")]
    Unavailable(String),
    #[error("weights missing: {0}")]
    Missing(String),
    #[error("download failed: {0}")]
    Download(String),
    #[error("integrity check failed: {0}")]
    Integrity(String),
    #[error("{0}")]
    Io(String),
    #[error("audio: {0}")]
    Audio(#[from] loqui_audio::Error),
    #[error("speech synthesis: {0}")]
    Tts(#[from] loqui_kokoro::Error),
    #[error("speaker embedding: {0}")]
    Speaker(#[from] loqui_speaker::Error),
    /// The caller stopped a long operation from its progress callback.
    #[error("cancelled")]
    Cancelled,
    #[cfg(feature = "whisper")]
    #[error("transcription: {0}")]
    Stt(#[from] loqui_whisper::Error),
}

impl Error {
    /// Whether the caller's input caused this, as opposed to the engine.
    /// Servers map this to 4xx rather than 5xx.
    pub fn is_client_error(&self) -> bool {
        matches!(self, Self::Invalid(_) | Self::InputTooLong { .. } | Self::Disabled(_) | Self::Cancelled)
            || matches!(self, Self::Speaker(loqui_speaker::Error::TooShort { .. }))
            || matches!(
                self,
                Self::Audio(
                    loqui_audio::Error::Decode(_) | loqui_audio::Error::TooLong { .. } | loqui_audio::Error::UnsupportedFormat { .. }
                )
            )
            || matches!(self, Self::Tts(loqui_kokoro::Error::Voice(_) | loqui_kokoro::Error::Speed(_)))
            || self.is_unsupported_language()
    }

    #[cfg(feature = "whisper")]
    fn is_unsupported_language(&self) -> bool {
        matches!(self, Self::Stt(loqui_whisper::Error::Language(_)))
    }

    #[cfg(not(feature = "whisper"))]
    fn is_unsupported_language(&self) -> bool {
        false
    }
}

pub use loqui_kokoro::Device as TtsDevice;

/// Text-to-speech settings.
#[derive(Debug, Clone)]
pub struct TtsConfig {
    pub variant: KokoroVariant,
    pub device: TtsDevice,
    /// CPU threads for ONNX Runtime; `None` means one per CPU this process
    /// may use, counting its affinity mask, cpuset and CPU quota.
    pub threads: Option<usize>,
    pub fallback: OovFallback,
    /// Unload after this long unused; `None` keeps the model resident.
    /// Kokoro is small (about 330 MB on CPU), so resident is the default.
    pub idle_ttl: Option<Duration>,
}

impl Default for TtsConfig {
    fn default() -> Self {
        Self { variant: KokoroVariant::Fp32, device: TtsDevice::Cpu, threads: None, fallback: OovFallback::Neural, idle_ttl: None }
    }
}

/// Speaker-embedding settings: [`Engine::speaker_embedding`] and
/// [`Engine::match_voice`].
#[derive(Debug, Clone, Default)]
pub struct SpeakerConfig {
    /// CPU threads for ONNX Runtime; `None` means one per CPU this process
    /// may use, counting its affinity mask, cpuset and CPU quota.
    pub threads: Option<usize>,
    /// Unload after this long unused; `None` keeps the model (26 MB)
    /// resident.
    pub idle_ttl: Option<Duration>,
}

/// Speech-to-text settings.
#[cfg(feature = "whisper")]
#[derive(Debug, Clone)]
pub struct SttConfig {
    /// A name from [`WHISPER_MODELS`], e.g. `"large-v3-turbo"`.
    pub model: String,
    pub device: loqui_whisper::Device,
    /// CPU threads for whisper.cpp, in every transcription whose
    /// [`TranscribeRequest::threads`] is unset or 0; `None` means its default
    /// of four, or fewer when this process may use fewer CPUs.
    pub threads: Option<u16>,
    /// Unload after this long unused; `None` keeps it resident. Whisper
    /// large is 1.6 GB, so the default frees it after ten idle minutes.
    pub idle_ttl: Option<Duration>,
}

#[cfg(feature = "whisper")]
impl Default for SttConfig {
    fn default() -> Self {
        Self { model: "large-v3-turbo".into(), device: loqui_whisper::Device::Cpu, threads: None, idle_ttl: Some(Duration::from_secs(600)) }
    }
}

pub struct EngineBuilder {
    cache_dir: Option<PathBuf>,
    downloads: Downloads,
    tts: Option<TtsConfig>,
    #[cfg(feature = "whisper")]
    stt: Option<SttConfig>,
    speaker: Option<SpeakerConfig>,
    max_input_chars: usize,
    max_audio_secs: u64,
    preload: bool,
    voices: Vec<(String, String)>,
}

impl EngineBuilder {
    /// Where weights are cached. Defaults to [`default_cache_dir`].
    pub fn cache_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.cache_dir = Some(dir.into());
        self
    }

    pub fn downloads(mut self, downloads: Downloads) -> Self {
        self.downloads = downloads;
        self
    }

    /// Text-to-speech settings; `None` disables it.
    pub fn tts(mut self, config: Option<TtsConfig>) -> Self {
        self.tts = config;
        self
    }

    /// Speech-to-text settings; `None` (the default) disables it.
    #[cfg(feature = "whisper")]
    pub fn stt(mut self, config: Option<SttConfig>) -> Self {
        self.stt = config;
        self
    }

    /// Speaker-embedding settings; `None` (the default) disables
    /// [`Engine::speaker_embedding`] and [`Engine::match_voice`], and keeps
    /// their model out of [`Engine::missing`] and [`Engine::fetch`].
    pub fn speaker(mut self, config: Option<SpeakerConfig>) -> Self {
        self.speaker = config;
        self
    }

    /// The longest text [`Engine::speak`] accepts, in characters. 4096 by
    /// default, OpenAI's limit.
    pub fn max_input_chars(mut self, chars: usize) -> Self {
        self.max_input_chars = chars;
        self
    }

    /// The longest audio [`Engine::transcribe`] accepts. Enforced while
    /// decoding, so a small compressed upload cannot expand without bound.
    pub fn max_audio_secs(mut self, secs: u64) -> Self {
        self.max_audio_secs = secs;
        self
    }

    /// Load every enabled model during [`EngineBuilder::build`] instead of
    /// on first use.
    pub fn preload(mut self, preload: bool) -> Self {
        self.preload = preload;
        self
    }

    /// Names a voice: afterwards `name` may be spoken in, alone or inside a
    /// blend, as if it were a built-in voice. `spec` is a blend of built-in
    /// voices, such as `am_puck(1)+am_liam(1)+am_onyx(0.5)`.
    ///
    /// Names are lowercase ASCII letters, digits and `_`. A name may take
    /// over an OpenAI name (`nova`), so clients that offer only OpenAI's
    /// voices can reach it, but not a Kokoro-shaped one (`af_custom`), which
    /// stays reserved for Kokoro's own voices. [`EngineBuilder::build`]
    /// checks every name and spec.
    pub fn voice(mut self, name: impl Into<String>, spec: impl Into<String>) -> Self {
        self.voices.push((name.into(), spec.into()));
        self
    }

    pub fn build(self) -> Result<Engine, Error> {
        let names = named_voices(self.voices)?;
        let cache = match self.cache_dir {
            Some(dir) => dir,
            None => {
                default_cache_dir().ok_or_else(|| Error::Config("no cache directory: set HOME or XDG_CACHE_HOME, or pass one".into()))?
            }
        };
        let downloads = self.downloads;
        let tts_variant = self.tts.as_ref().map(|cfg| cfg.variant);

        let tts = self.tts.map(|cfg| {
            let cache = cache.clone();
            let ttl = cfg.idle_ttl;
            Slot::new(ttl, Box::new(move || load_kokoro(&cache, &cfg, downloads)))
        });
        #[cfg(feature = "whisper")]
        if let Some(cfg) = &self.stt {
            models::whisper_file(&cfg.model)?;
        }
        #[cfg(feature = "whisper")]
        let stt_model = self.stt.as_ref().map(|cfg| cfg.model.clone());
        #[cfg(not(feature = "whisper"))]
        let stt_model = None;
        #[cfg(feature = "whisper")]
        let stt_threads = self.stt.as_ref().and_then(|cfg| cfg.threads);
        #[cfg(feature = "whisper")]
        let stt = self.stt.map(|cfg| {
            let cache = cache.clone();
            let ttl = cfg.idle_ttl;
            Slot::new(ttl, Box::new(move || load_whisper(&cache, &cfg, downloads)))
        });
        let speaker = self.speaker.map(|cfg| {
            let cache = cache.clone();
            let ttl = cfg.idle_ttl;
            Slot::new(ttl, Box::new(move || load_speaker(&cache, &cfg, downloads)))
        });

        let inner = Arc::new(Inner {
            cache,
            downloads,
            tts,
            tts_variant,
            #[cfg(feature = "whisper")]
            stt,
            stt_model,
            #[cfg(feature = "whisper")]
            stt_threads,
            speaker,
            names,
            max_input_chars: self.max_input_chars,
            max_audio_secs: self.max_audio_secs,
        });
        if inner.has_ttl() {
            start_reaper(Arc::downgrade(&inner));
        }
        let engine = Engine { inner };
        if self.preload {
            engine.preload()?;
        }
        Ok(engine)
    }
}

struct Inner {
    cache: PathBuf,
    downloads: Downloads,
    tts: Option<Slot<Kokoro>>,
    tts_variant: Option<KokoroVariant>,
    #[cfg(feature = "whisper")]
    stt: Option<Slot<loqui_whisper::Whisper>>,
    stt_model: Option<String>,
    /// [`SttConfig::threads`], for requests that leave theirs unset.
    #[cfg(feature = "whisper")]
    stt_threads: Option<u16>,
    speaker: Option<Slot<loqui_speaker::SpeakerEncoder>>,
    names: BTreeMap<String, Named>,
    max_input_chars: usize,
    /// The longest upload decoded, for transcription and speaker embeddings.
    max_audio_secs: u64,
}

impl Inner {
    fn has_ttl(&self) -> bool {
        let tts = self.tts.as_ref().is_some_and(|s| s.ttl().is_some());
        #[cfg(feature = "whisper")]
        let stt = self.stt.as_ref().is_some_and(|s| s.ttl().is_some());
        #[cfg(not(feature = "whisper"))]
        let stt = false;
        let speaker = self.speaker.as_ref().is_some_and(|s| s.ttl().is_some());
        tts || stt || speaker
    }

    fn reap(&self) {
        if let Some(slot) = &self.tts
            && slot.reap()
        {
            tracing::info!(kind = "tts", "idle model unloaded");
        }
        #[cfg(feature = "whisper")]
        if let Some(slot) = &self.stt
            && slot.reap()
        {
            tracing::info!(kind = "stt", "idle model unloaded");
        }
        if let Some(slot) = &self.speaker
            && slot.reap()
        {
            tracing::info!(kind = "speaker", "idle model unloaded");
        }
    }
}

/// A voice an application has named: its spec as written, and what that
/// resolves to.
struct Named {
    spec: String,
    blend: Blend,
}

/// Checks named voices. They are made only of built-in voices, never of
/// each other, so there are no cycles and their order does not matter.
/// Errors name the voice: it is the operator's configuration, not a
/// caller's input.
fn named_voices(voices: Vec<(String, String)>) -> Result<BTreeMap<String, Named>, Error> {
    let defined: Vec<String> = voices.iter().map(|(name, _)| name.clone()).collect();
    let mut names = BTreeMap::new();
    for (name, spec) in voices {
        let bad = |why: &str| Error::Config(format!("voice {name:?}: {why}"));
        if name.is_empty() || !name.bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'_') {
            return Err(bad("names may contain only lowercase ASCII letters, digits and _"));
        }
        if is_kokoro_shaped(&name) {
            return Err(bad("names shaped like Kokoro's (af_, bm_, ...) are reserved for its own voices"));
        }
        let blend = Blend::parse(&spec, |_| None).map_err(|e| bad(&e.to_string()))?;
        if let Some((id, _)) = blend.parts().iter().find(|(id, _)| !loqui_kokoro::ENGLISH_VOICES.contains(&id.as_str())) {
            return Err(bad(&if defined.contains(id) {
                format!("{id} is a named voice; named voices are made of built-in voices only")
            } else {
                format!("{id} is not a built-in voice")
            }));
        }
        if names.insert(name.clone(), Named { spec: spec.trim().to_owned(), blend }).is_some() {
            return Err(bad("named twice"));
        }
    }
    Ok(names)
}

/// A letter, `f` or `m`, then `_`: how every Kokoro voice is named.
fn is_kokoro_shaped(name: &str) -> bool {
    matches!(name.as_bytes(), [lang, b'f' | b'm', b'_', ..] if lang.is_ascii_lowercase())
}

/// A voice [`Engine::speak`] accepts, as open-speech's `/v1/audio/voices`
/// describes one.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct VoiceInfo {
    /// What to pass as [`SpeakRequest::voice`].
    pub id: String,
    /// `Heart` for `af_heart`; a named voice's own name.
    pub name: String,
    /// The accent it speaks with: `en-us` or `en-gb`.
    pub language: &'static str,
    /// `female` or `male`, or `unknown` for a blend of both.
    pub gender: &'static str,
    /// A named voice's spec, as configured; `None` for a built-in voice.
    pub blend: Option<String>,
}

impl VoiceInfo {
    fn builtin(id: &str) -> Self {
        let mut name = id.get(3..).unwrap_or(id).to_owned();
        if let Some(initial) = name.get_mut(..1) {
            initial.make_ascii_uppercase();
        }
        Self { id: id.to_owned(), name, language: language(id), gender: gender(id), blend: None }
    }

    fn named(name: &str, voice: &Named) -> Self {
        let mut genders = voice.blend.audible().map(|(id, _)| gender(id));
        let first = genders.next().unwrap_or("unknown");
        let gender = if genders.all(|g| g == first) { first } else { "unknown" };
        Self { id: name.to_owned(), name: name.to_owned(), language: language(voice.blend.lead()), gender, blend: Some(voice.spec.clone()) }
    }
}

fn language(id: &str) -> &'static str {
    if id.starts_with('b') { "en-gb" } else { "en-us" }
}

fn gender(id: &str) -> &'static str {
    match id.as_bytes().get(1) {
        Some(b'f') => "female",
        Some(b'm') => "male",
        _ => "unknown",
    }
}

/// A background thread that unloads idle models. It holds only a weak
/// reference and exits once the engine is dropped.
fn start_reaper(inner: Weak<Inner>) {
    let spawned = std::thread::Builder::new().name("loqui-reaper".into()).spawn(move || {
        loop {
            std::thread::sleep(Duration::from_secs(15));
            match inner.upgrade() {
                Some(inner) => inner.reap(),
                None => return,
            }
        }
    });
    if let Err(e) = spawned {
        tracing::warn!("could not start the idle-unload thread, models will stay resident: {e}");
    }
}

fn load_kokoro(cache: &std::path::Path, cfg: &TtsConfig, downloads: Downloads) -> Result<Kokoro, Error> {
    let pinned = cfg.variant.file();
    let onnx = models::fetch(cache, &models::KOKORO_REPO, pinned.file, Some(pinned.sha256), downloads)?;
    // Fetching the default voice also tells us where voices live.
    let default_voice = models::fetch(cache, &models::KOKORO_REPO, &voice_file(loqui_kokoro::DEFAULT_VOICE), None, downloads)?;
    let voices_dir = default_voice.parent().map(PathBuf::from).ok_or_else(|| Error::Io("voice path has no parent".into()))?;
    let model = KokoroModel::load(&onnx, cfg.device, cfg.threads)?;
    tracing::info!(variant = ?cfg.variant, device = ?cfg.device, "Kokoro loaded");
    Ok(Kokoro::new(model, voices_dir, cfg.fallback))
}

fn load_speaker(cache: &std::path::Path, cfg: &SpeakerConfig, downloads: Downloads) -> Result<loqui_speaker::SpeakerEncoder, Error> {
    let pinned = &models::SPEAKER_FILE;
    let path = models::fetch(cache, &models::SPEAKER_REPO, pinned.file, Some(pinned.sha256), downloads)?;
    let encoder = loqui_speaker::SpeakerEncoder::load(&path, cfg.threads)?;
    tracing::info!(model = SPEAKER_MODEL_ID, "speaker model loaded");
    Ok(encoder)
}

#[cfg(feature = "whisper")]
fn load_whisper(cache: &std::path::Path, cfg: &SttConfig, downloads: Downloads) -> Result<loqui_whisper::Whisper, Error> {
    let model = models::whisper_file(&cfg.model)?;
    let path = models::fetch(cache, &models::WHISPER_REPO, model.file, Some(model.sha256), downloads)?;
    let whisper = loqui_whisper::Whisper::load(&path, cfg.device)?;
    tracing::info!(model = cfg.model, device = ?cfg.device, "Whisper loaded");
    Ok(whisper)
}

fn voice_file(id: &str) -> String {
    format!("voices/{id}.bin")
}

/// A text-to-speech request.
#[derive(Debug, Clone)]
pub struct SpeakRequest {
    pub text: String,
    /// A voice spec: `af_heart`, an OpenAI name (`alloy`), or a blend
    /// (`af_bella(2)+af_sky(1)`; see [`Blend`]).
    pub voice: String,
    /// 0.25 to 4.0.
    pub speed: f32,
    pub format: Format,
}

impl SpeakRequest {
    pub fn new(text: impl Into<String>) -> Self {
        Self { text: text.into(), voice: loqui_kokoro::DEFAULT_VOICE.into(), speed: 1.0, format: Format::Wav }
    }
}

/// Encoded speech.
#[derive(Debug, Clone)]
pub struct Speech {
    pub audio: Vec<u8>,
    pub format: Format,
    pub duration_secs: f64,
}

#[cfg(feature = "whisper")]
pub use loqui_whisper::{Device as SttDevice, Error as SttError, Segment, Task, Transcription};

/// A speech-to-text request.
#[cfg(feature = "whisper")]
#[derive(Debug, Clone, Default)]
pub struct TranscribeRequest {
    /// The uploaded file, in any container loqui-audio decodes.
    pub audio: Vec<u8>,
    pub language: Option<String>,
    pub prompt: Option<String>,
    pub task: Task,
    pub temperature: f32,
    /// CPU threads for whisper.cpp; `None` (or 0) means the engine's
    /// [`SttConfig::threads`], else whisper.cpp's default of four, or fewer
    /// when this process may use fewer CPUs.
    pub threads: Option<u16>,
}

/// Which model a [`ModelInfo`] or [`ModelFile`] is about. Non-exhaustive:
/// loqui may run more kinds of model.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ModelKind {
    Tts,
    Stt,
    /// The speaker-embedding model.
    Speaker,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ModelInfo {
    pub id: String,
    pub kind: ModelKind,
    pub loaded: bool,
}

/// A weights file an engine needs, as [`Engine::missing`] reports it.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct ModelFile {
    /// The model that needs it.
    pub kind: ModelKind,
    /// The Hugging Face repository it comes from.
    pub repo: &'static str,
    /// Its path in that repository, such as `voices/af_heart.bin`.
    pub file: String,
    /// Where it will be in the cache once fetched.
    pub path: PathBuf,
    /// Its size: what fetching it will download.
    pub bytes: u64,
}

/// A file the engine's configuration needs, and how to check it.
struct Required {
    kind: ModelKind,
    pinned: &'static models::Pinned,
    file: String,
    sha256: Option<&'static str>,
    bytes: u64,
}

/// Kokoro and Whisper, in process. Cheap to clone; clones share models.
#[derive(Clone)]
pub struct Engine {
    inner: Arc<Inner>,
}

impl std::fmt::Debug for Engine {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Engine").field("cache", &self.inner.cache).field("models", &self.models()).finish()
    }
}

impl Engine {
    pub fn builder() -> EngineBuilder {
        EngineBuilder {
            cache_dir: None,
            downloads: Downloads::Allow,
            tts: Some(TtsConfig::default()),
            #[cfg(feature = "whisper")]
            stt: None,
            speaker: None,
            max_input_chars: 4096,
            max_audio_secs: 1800,
            preload: false,
            voices: Vec::new(),
        }
    }

    /// Loads every enabled model now, and fetches the voices that named
    /// voices are made of, so a host running with [`Downloads::Deny`] finds
    /// a missing one at startup rather than on the first request.
    pub fn preload(&self) -> Result<(), Error> {
        if let Some(slot) = &self.inner.tts {
            slot.get()?;
            for named in self.inner.names.values() {
                named.blend.audible().try_for_each(|(id, _)| self.fetch_voice(id))?;
            }
        }
        #[cfg(feature = "whisper")]
        if let Some(slot) = &self.inner.stt {
            slot.get()?;
        }
        if let Some(slot) = &self.inner.speaker {
            slot.get()?;
        }
        Ok(())
    }

    /// Unloads idle models now, whatever their TTL.
    pub fn unload(&self) {
        if let Some(slot) = &self.inner.tts {
            slot.unload();
        }
        #[cfg(feature = "whisper")]
        if let Some(slot) = &self.inner.stt {
            slot.unload();
        }
        if let Some(slot) = &self.inner.speaker {
            slot.unload();
        }
    }

    pub fn models(&self) -> Vec<ModelInfo> {
        let mut out = Vec::new();
        if let Some(slot) = &self.inner.tts {
            out.push(ModelInfo { id: TTS_MODEL_ID.into(), kind: ModelKind::Tts, loaded: slot.is_loaded() });
        }
        #[cfg(feature = "whisper")]
        if let (Some(slot), Some(id)) = (&self.inner.stt, &self.inner.stt_model) {
            out.push(ModelInfo { id: id.clone(), kind: ModelKind::Stt, loaded: slot.is_loaded() });
        }
        if let Some(slot) = &self.inner.speaker {
            out.push(ModelInfo { id: SPEAKER_MODEL_ID.into(), kind: ModelKind::Speaker, loaded: slot.is_loaded() });
        }
        out
    }

    /// The configured Whisper model's name, if speech-to-text is enabled.
    pub fn stt_model_id(&self) -> Option<&str> {
        self.inner.stt_model.as_deref()
    }

    /// The voices [`Engine::speak`] accepts by name: the built-in English
    /// voices, then any named with [`EngineBuilder::voice`]. Any blend of
    /// these is accepted too.
    pub fn voices(&self) -> Result<Vec<VoiceInfo>, Error> {
        self.inner.tts.as_ref().ok_or(Error::Disabled("text-to-speech"))?;
        let builtin = loqui_kokoro::ENGLISH_VOICES.iter().map(|id| VoiceInfo::builtin(id));
        Ok(builtin.chain(self.inner.names.iter().map(|(name, voice)| VoiceInfo::named(name, voice))).collect())
    }

    /// The files this engine needs that are not in its cache: each enabled
    /// model, the default voice, and the voices named voices are made of.
    ///
    /// It only looks. Nothing is loaded, hashed or downloaded, and the cache
    /// directory is not created, so it is cheap enough for a health check.
    /// An empty list means an engine running with [`Downloads::Deny`] has
    /// every file it needs; digests are still checked when a model loads.
    pub fn missing(&self) -> Vec<ModelFile> {
        self.required()
            .into_iter()
            .filter(|r| models::cached(&self.inner.cache, r.pinned, &r.file).is_none())
            .map(|r| ModelFile {
                kind: r.kind,
                repo: r.pinned.repo,
                path: models::expected_path(&self.inner.cache, r.pinned, &r.file),
                file: r.file,
                bytes: r.bytes,
            })
            .collect()
    }

    /// Fetches and verifies the files [`Engine::missing`] would list,
    /// without loading any model. Run it where downloads are allowed to fill
    /// a cache for [`Downloads::Deny`]; with downloads off, it checks that
    /// the cache is complete and its weights intact. For every other voice
    /// pack too, add [`Engine::fetch_voices`].
    pub fn fetch(&self) -> Result<(), Error> {
        self.required()
            .iter()
            .try_for_each(|r| models::fetch(&self.inner.cache, r.pinned, &r.file, r.sha256, self.inner.downloads).map(drop))
    }

    fn required(&self) -> Vec<Required> {
        let mut out = Vec::new();
        if let Some(variant) = self.inner.tts_variant {
            let model = variant.file();
            out.push(Required {
                kind: ModelKind::Tts,
                pinned: &models::KOKORO_REPO,
                file: model.file.to_owned(),
                sha256: Some(model.sha256),
                bytes: model.bytes,
            });
            let named = self.inner.names.values().flat_map(|named| named.blend.audible().map(|(id, _)| id.to_owned()));
            let voices: BTreeSet<String> = std::iter::once(loqui_kokoro::DEFAULT_VOICE.to_owned()).chain(named).collect();
            out.extend(voices.into_iter().map(|id| Required {
                kind: ModelKind::Tts,
                pinned: &models::KOKORO_REPO,
                file: voice_file(&id),
                sha256: None,
                bytes: models::VOICE_PACK_BYTES,
            }));
        }
        #[cfg(feature = "whisper")]
        if let Some(model) = self.inner.stt_model.as_deref().and_then(whisper_model) {
            let pinned = model.pinned();
            out.push(Required {
                kind: ModelKind::Stt,
                pinned: &models::WHISPER_REPO,
                file: pinned.file.to_owned(),
                sha256: Some(pinned.sha256),
                bytes: pinned.bytes,
            });
        }
        if self.inner.speaker.is_some() {
            let pinned = &models::SPEAKER_FILE;
            out.push(Required {
                kind: ModelKind::Speaker,
                pinned: &models::SPEAKER_REPO,
                file: pinned.file.to_owned(),
                sha256: Some(pinned.sha256),
                bytes: pinned.bytes,
            });
        }
        out
    }

    /// Downloads every voice pack on the roster now (about 15 MB), so any
    /// voice or blend can be spoken on a host that later runs with
    /// [`Downloads::Deny`].
    pub fn fetch_voices(&self) -> Result<(), Error> {
        self.inner.tts.as_ref().ok_or(Error::Disabled("text-to-speech"))?;
        loqui_kokoro::ENGLISH_VOICES.iter().try_for_each(|id| self.fetch_voice(id))
    }

    /// A voice spec as this engine reads it: named voices first, then
    /// OpenAI's names, then pack ids.
    fn resolve(&self, spec: &str) -> Result<Blend, Error> {
        Ok(Blend::parse(spec, |id| self.inner.names.get(id).map(|named| &named.blend))?)
    }

    fn fetch_voice(&self, id: &str) -> Result<(), Error> {
        models::fetch(&self.inner.cache, &models::KOKORO_REPO, &voice_file(id), None, self.inner.downloads).map(drop)
    }

    pub fn speak(&self, request: &SpeakRequest) -> Result<Speech, Error> {
        let slot = self.inner.tts.as_ref().ok_or(Error::Disabled("text-to-speech"))?;
        let chars = request.text.chars().count();
        if request.text.trim().is_empty() {
            return Err(Error::Invalid("input text is empty".into()));
        }
        if chars > self.inner.max_input_chars {
            return Err(Error::InputTooLong { chars, limit: self.inner.max_input_chars });
        }
        if !(0.25..=4.0).contains(&request.speed) {
            return Err(Error::Invalid(format!("speed {} is outside 0.25 to 4.0", request.speed)));
        }
        // Every part is checked before any is fetched, and only voices on
        // the roster are fetched, so a request cannot make the engine
        // download arbitrary files, nor anything at all for a bad voice.
        let voice = self.resolve(&request.voice)?;
        if voice.parts().iter().any(|(id, _)| !loqui_kokoro::ENGLISH_VOICES.contains(&id.as_str())) {
            // The id is not echoed: it is caller input that failed validation.
            return Err(Error::Invalid("unknown voice".into()));
        }
        voice.audible().try_for_each(|(id, _)| self.fetch_voice(id))?;
        let kokoro = slot.get()?;
        let samples = kokoro.speak(&request.text, &voice, request.speed)?;
        let pcm = loqui_audio::Pcm { samples, rate: loqui_kokoro::SAMPLE_RATE };
        let duration_secs = pcm.duration_secs();
        let audio = loqui_audio::encode(&pcm, request.format)?;
        Ok(Speech { audio, format: request.format, duration_secs })
    }

    /// The speaker embedding of a recording: decoded, trimmed to its speech
    /// (at least [`MIN_EMBED_SECS`] of it), and embedded from its first 30 s.
    /// Needs [`EngineBuilder::speaker`].
    ///
    /// An embedding measures how alike voices sound. It is not evidence of
    /// who is speaking: do not use it to authenticate anyone.
    pub fn speaker_embedding(&self, audio: &[u8]) -> Result<SpeakerEmbedding, Error> {
        let slot = self.inner.speaker.as_ref().ok_or(Error::Disabled("speaker embeddings"))?;
        let pcm = loqui_audio::decode_mono_16k(audio, Some(self.inner.max_audio_secs))?;
        let encoder = slot.get()?;
        speaker::embed(&encoder, &pcm.samples, MIN_EMBED_SECS)
    }

    #[cfg(feature = "whisper")]
    pub fn transcribe(&self, request: &TranscribeRequest) -> Result<Transcription, Error> {
        let slot = self.inner.stt.as_ref().ok_or(Error::Disabled("speech-to-text"))?;
        let pcm = loqui_audio::decode_mono_16k(&request.audio, Some(self.inner.max_audio_secs))?;
        let whisper = slot.get()?;
        let options = loqui_whisper::Options {
            language: request.language.clone(),
            prompt: request.prompt.clone(),
            task: request.task,
            temperature: request.temperature,
            threads: whisper_threads(request.threads, self.inner.stt_threads),
        };
        Ok(whisper.transcribe(&pcm.samples, &options)?)
    }
}

/// Whisper's threads for one request: the request's count if above 0, else
/// the engine's. `None` leaves loqui-whisper's default.
#[cfg(feature = "whisper")]
fn whisper_threads(request: Option<u16>, engine: Option<u16>) -> Option<u16> {
    request.filter(|&t| t > 0).or(engine)
}

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

    /// An engine that loads nothing: building is lazy until something
    /// is spoken.
    fn engine(voices: &[(&str, &str)]) -> Result<Engine, Error> {
        let builder = Engine::builder().cache_dir(std::env::temp_dir().join("loqui-unused-cache")).downloads(Downloads::Deny);
        voices.iter().fold(builder, |b, (name, spec)| b.voice(*name, *spec)).build()
    }

    fn close(blend: &Blend, expected: &[(&str, f32)]) -> bool {
        let parts = blend.parts();
        parts.len() == expected.len() && parts.iter().zip(expected).all(|((a, x), (b, y))| a == b && (x - y).abs() < 1e-6)
    }

    #[test]
    fn named_voices_are_checked_when_the_engine_is_built() {
        let refused = [
            ("Will", "am_puck"),
            ("will smith", "am_puck"),
            ("", "am_puck"),
            ("af_custom", "am_puck"),
            ("jf_alpha", "am_puck"),
            ("will", "am_puck(x)"),
            ("will", "zz_nobody"),
            ("will", "jf_alpha"),
        ];
        for (name, spec) in refused {
            let err = engine(&[(name, spec)]).expect_err(&format!("{name:?} = {spec:?}"));
            assert!(matches!(err, Error::Config(_)), "{name:?} = {spec:?}: {err}");
        }
        assert!(matches!(engine(&[("will", "am_puck"), ("will", "am_liam")]), Err(Error::Config(_))));
        let err = engine(&[("will", "am_puck"), ("bill", "will(2)+am_liam")]).unwrap_err().to_string();
        assert!(err.contains("built-in voices only"), "{err}");
    }

    #[test]
    fn named_voices_resolve_alone_and_inside_blends() {
        let engine = engine(&[("will", "am_puck(1)+am_liam(1)+am_onyx(0.5)")]).unwrap();
        assert!(close(&engine.resolve("will").unwrap(), &[("am_puck", 0.4), ("am_liam", 0.4), ("am_onyx", 0.2)]));
        let blend = engine.resolve("will(2)+af_sky(1)").unwrap();
        assert!(close(&blend, &[("am_puck", 0.8 / 3.0), ("am_liam", 0.8 / 3.0), ("am_onyx", 0.4 / 3.0), ("af_sky", 1.0 / 3.0)]));
    }

    #[test]
    fn a_name_can_take_over_an_openai_name_and_use_it() {
        let engine = engine(&[("nova", "nova(3)+af_sky(1)")]).unwrap();
        assert!(close(&engine.resolve("nova").unwrap(), &[("af_nova", 0.75), ("af_sky", 0.25)]));
        assert!(close(&engine.resolve("alloy").unwrap(), &[("af_heart", 1.0)]));
    }

    #[test]
    fn unknown_voices_are_refused_without_echoing_them() {
        let engine = engine(&[]).unwrap();
        let err = engine.speak(&SpeakRequest { voice: "af_heart+zz_secret".into(), ..SpeakRequest::new("hello") }).unwrap_err();
        assert!(matches!(err, Error::Invalid(_)), "{err}");
        assert!(!err.to_string().contains("secret"), "{err}");
    }

    #[test]
    fn voices_lists_the_roster_then_named_voices() {
        let engine = engine(&[("will", "am_puck(1)+am_liam(1)"), ("duo", " af_sky + am_adam "), ("lady", "bf_emma(0)+af_sky")]).unwrap();
        let voices = engine.voices().unwrap();
        assert_eq!(voices.len(), loqui_kokoro::ENGLISH_VOICES.len() + 3);
        let heart = voices.iter().find(|v| v.id == "af_heart").unwrap();
        assert_eq!((heart.name.as_str(), heart.language, heart.gender, heart.blend.as_deref()), ("Heart", "en-us", "female", None));
        let george = voices.iter().find(|v| v.id == "bm_george").unwrap();
        assert_eq!((george.name.as_str(), george.language, george.gender), ("George", "en-gb", "male"));
        let named: Vec<_> = voices[loqui_kokoro::ENGLISH_VOICES.len()..].iter().map(|v| (v.id.as_str(), v.language, v.gender)).collect();
        // Sorted by name; a weightless lead sets the accent but not the gender.
        assert_eq!(named, [("duo", "en-us", "unknown"), ("lady", "en-gb", "female"), ("will", "en-us", "male")]);
        assert_eq!(voices.last().unwrap().blend.as_deref(), Some("am_puck(1)+am_liam(1)"));
    }

    fn scratch(name: &str) -> PathBuf {
        let dir = std::env::temp_dir().join(format!("loqui-{name}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&dir);
        dir
    }

    /// Lays `files` out in `cache` the way hf-hub's cache stores a pinned
    /// revision: a ref naming the commit, and the files under its snapshot.
    fn populate(cache: &std::path::Path, pinned: &models::Pinned, files: &[&str]) {
        let repo = cache.join(format!("models--{}", pinned.repo.replace('/', "--")));
        std::fs::create_dir_all(repo.join("refs")).unwrap();
        std::fs::write(repo.join("refs").join(pinned.revision), pinned.revision).unwrap();
        for file in files {
            let path = repo.join("snapshots").join(pinned.revision).join(file);
            std::fs::create_dir_all(path.parent().unwrap()).unwrap();
            std::fs::write(path, b"weights").unwrap();
        }
    }

    #[test]
    fn missing_lists_what_the_configuration_needs_without_touching_the_cache() {
        let cache = scratch("missing");
        let engine = Engine::builder().cache_dir(&cache).voice("will", "am_puck(1)+am_liam(1)+af_heart(0)").build().unwrap();
        let missing = engine.missing();
        let files: Vec<_> = missing.iter().map(|f| (f.kind, f.file.as_str(), f.bytes)).collect();
        assert_eq!(
            files,
            [
                (ModelKind::Tts, "onnx/model.onnx", 325_532_232),
                (ModelKind::Tts, "voices/af_heart.bin", models::VOICE_PACK_BYTES),
                (ModelKind::Tts, "voices/am_liam.bin", models::VOICE_PACK_BYTES),
                (ModelKind::Tts, "voices/am_puck.bin", models::VOICE_PACK_BYTES),
            ],
            "the model, the default voice, and the audible parts of named voices, once each"
        );
        assert!(missing.iter().all(|f| f.repo == models::KOKORO_REPO.repo && f.path.starts_with(&cache) && f.path.ends_with(&f.file)));
        assert!(!cache.exists(), "missing() must not create the cache");
    }

    #[test]
    fn cached_files_are_not_missing() {
        let cache = scratch("cached");
        populate(&cache, &models::KOKORO_REPO, &["onnx/model_quantized.onnx", "voices/af_heart.bin"]);
        let tts = TtsConfig { variant: KokoroVariant::Quantized, ..TtsConfig::default() };
        let engine = Engine::builder().cache_dir(&cache).tts(Some(tts)).build().unwrap();
        assert_eq!(engine.missing(), []);
        let with_named = Engine::builder().cache_dir(&cache).voice("sky", "af_sky").build().unwrap();
        let files: Vec<_> = with_named.missing().into_iter().map(|f| f.file).collect();
        assert_eq!(files, ["onnx/model.onnx", "voices/af_sky.bin"], "only what is absent");
        std::fs::remove_dir_all(&cache).unwrap();
    }

    #[test]
    fn fetch_with_downloads_off_reports_what_is_missing() {
        let cache = scratch("fetch-deny");
        let engine = Engine::builder().cache_dir(&cache).downloads(Downloads::Deny).build().unwrap();
        assert!(matches!(engine.fetch(), Err(Error::Missing(_))));
        assert!(Engine::builder().cache_dir(&cache).tts(None).build().unwrap().fetch().is_ok(), "an engine with no models needs nothing");
        std::fs::remove_dir_all(&cache).unwrap();
    }

    #[cfg(feature = "whisper")]
    #[test]
    fn missing_includes_the_whisper_model() {
        let cache = scratch("missing-stt");
        let stt = SttConfig { model: "tiny.en".into(), ..SttConfig::default() };
        let engine = Engine::builder().cache_dir(&cache).tts(None).stt(Some(stt)).build().unwrap();
        let files: Vec<_> = engine.missing().into_iter().map(|f| (f.kind, f.repo, f.file, f.bytes)).collect();
        assert_eq!(files, [(ModelKind::Stt, models::WHISPER_REPO.repo, "ggml-tiny.en.bin".to_owned(), 77_704_715)]);
    }

    #[cfg(feature = "whisper")]
    #[test]
    fn a_requests_threads_beat_the_engines() {
        assert_eq!(whisper_threads(Some(2), Some(6)), Some(2));
        assert_eq!(whisper_threads(Some(0), Some(6)), Some(6), "0 is unset, as everywhere else");
        assert_eq!(whisper_threads(None, Some(6)), Some(6));
        assert_eq!(whisper_threads(None, None), None, "loqui-whisper's default");
    }

    #[cfg(feature = "whisper")]
    #[test]
    fn an_unsupported_language_is_the_callers_error() {
        assert!(Error::Stt(loqui_whisper::Error::Language("fr".into())).is_client_error());
        assert!(!Error::Stt(loqui_whisper::Error::Inference("boom".into())).is_client_error());
    }

    #[test]
    fn voices_needs_text_to_speech() {
        let engine = Engine::builder().cache_dir(std::env::temp_dir()).tts(None).build().unwrap();
        assert!(matches!(engine.voices(), Err(Error::Disabled(_))));
    }

    /// Two seconds of a tone, as a WAV upload.
    fn tone_wav() -> Vec<u8> {
        let samples = (0..32_000).map(|i| 0.3 * (i as f32 * 0.05).sin()).collect();
        loqui_audio::encode(&loqui_audio::Pcm { samples, rate: 16_000 }, Format::Wav).unwrap()
    }

    /// An engine that did not ask for speaker embeddings neither needs nor
    /// fetches their model; one that did lists it, unloaded, and needs it.
    #[test]
    fn the_speaker_model_is_needed_only_when_enabled() {
        let cache = scratch("missing-speaker");
        let without = Engine::builder().cache_dir(&cache).tts(None).build().unwrap();
        assert!(without.missing().is_empty());
        assert!(without.models().is_empty());
        let with = Engine::builder().cache_dir(&cache).tts(None).speaker(Some(SpeakerConfig::default())).build().unwrap();
        let files: Vec<_> = with.missing().into_iter().map(|f| (f.kind, f.repo, f.file, f.bytes)).collect();
        assert_eq!(
            files,
            [(ModelKind::Speaker, models::SPEAKER_REPO.repo, "wespeaker_en_voxceleb_resnet34_LM.onnx".to_owned(), 26_530_550)]
        );
        assert_eq!(with.models(), [ModelInfo { id: SPEAKER_MODEL_ID.into(), kind: ModelKind::Speaker, loaded: false }]);
    }

    #[test]
    fn speaker_embeddings_need_the_speaker_model_enabled() {
        let engine = Engine::builder().cache_dir(std::env::temp_dir()).tts(None).build().unwrap();
        assert!(matches!(engine.speaker_embedding(&tone_wav()), Err(Error::Disabled("speaker embeddings"))));
    }

    /// With downloads off, absent weights are reported, not fetched.
    #[test]
    fn missing_speaker_weights_are_reported_with_downloads_off() {
        let cache = scratch("speaker-deny");
        let engine = Engine::builder()
            .cache_dir(&cache)
            .downloads(Downloads::Deny)
            .tts(None)
            .speaker(Some(SpeakerConfig::default()))
            .build()
            .unwrap();
        assert!(matches!(engine.speaker_embedding(&tone_wav()), Err(Error::Missing(_))));
        let _ = std::fs::remove_dir_all(&cache);
    }

    #[test]
    fn a_short_recording_and_a_cancelled_match_are_the_callers() {
        assert!(Error::Speaker(loqui_speaker::Error::TooShort { secs: 0.2, min_secs: 0.5 }).is_client_error());
        assert!(!Error::Speaker(loqui_speaker::Error::Model("boom".into())).is_client_error());
        assert!(Error::Cancelled.is_client_error());
    }
}