Skip to main content

weirdnet_model/
speech.rs

1//! Speech out (text to speech): what a speaking model ([`Purpose::Speak`](crate::hw::Purpose::Speak))
2//! does, takes and allows, as a [`SpeechProfile`].
3//!
4//! The profile has the same fields and the same wire form as `weirdnet_agent::speech::SpeechProfile`
5//! (since `weirdnet-agent` 0.5.11), so a record written here reads there; with the `agent` feature
6//! the two convert with `From` both ways. Without it this crate stays free of the agent.
7//!
8//! **Profiles are cited or absent.** A bool is true only when the model is known to do it; a list
9//! or limit is `None` (or, for [`formats`](SpeechProfile::formats), empty) when nobody reported
10//! it, never defaulted. Profiles come from:
11//!
12//! - the catalog ([`CatalogEntry::speech`](crate::hw::CatalogEntry::speech)), each cited to the
13//!   model's card and its engine's documentation;
14//! - a hand-placed GGUF's header ([`from_gguf`]), for the speech models llama.cpp documents;
15//! - the engine at load (`weirdnet-backends`), kept with the measured limits
16//!   ([`LimitsRecord::speech`](crate::LimitsRecord::speech)).
17
18use serde::{Deserialize, Serialize};
19
20use crate::gguf::GgufHeader;
21
22/// The license name of Fish Audio Drama 3 ([`FISH_AUDIO_DRAMA_3`](crate::hw::FISH_AUDIO_DRAMA_3)),
23/// the Fish Audio Community License: free for research and non-commercial use, commercial use
24/// limited (an annual revenue cap, and no hosted text-to-speech service). Downloads need the
25/// operator's explicit acceptance ([`Consent::accepting_license`](crate::Consent::accepting_license)).
26pub const FISH_AUDIO_COMMUNITY: &str = "fish-audio-community";
27
28/// Output sample rates llama.cpp documents for its speech models (`docs/multimodal/tts.md`).
29const QWEN3_TTS_RATE: u32 = 24_000;
30const KOKORO_RATE: u32 = 24_000;
31const VOXCPM2_RATE: u32 = 48_000;
32const DRAMA3_RATE: u32 = 44_100;
33/// llama.cpp keeps the first 30 seconds of a reference clip (VoxCPM2, Drama 3).
34const LLAMA_REFERENCE_SECONDS: u32 = 30;
35/// Drama 3's speaker tags, `<|speaker:0|>` to `<|speaker:15|>`.
36const DRAMA3_SPEAKERS: u8 = 16;
37
38/// An audio encoding for speech out: `wav`, `pcm16` (raw little-endian 16-bit samples), `mp3`,
39/// `opus` or `flac` on the wire, as `weirdnet_agent::speech::AudioFormat`.
40#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
41#[serde(rename_all = "snake_case")]
42#[non_exhaustive]
43pub enum AudioFormat {
44    #[default]
45    Wav,
46    Pcm16,
47    Mp3,
48    Opus,
49    Flac,
50}
51
52impl AudioFormat {
53    /// Every format, in wire order.
54    pub const ALL: [AudioFormat; 5] = [AudioFormat::Wav, AudioFormat::Pcm16, AudioFormat::Mp3, AudioFormat::Opus, AudioFormat::Flac];
55
56    /// The name on the wire: `wav`, `pcm16`, `mp3`, `opus`, `flac`.
57    pub fn as_str(&self) -> &'static str {
58        match self {
59            AudioFormat::Wav => "wav",
60            AudioFormat::Pcm16 => "pcm16",
61            AudioFormat::Mp3 => "mp3",
62            AudioFormat::Opus => "opus",
63            AudioFormat::Flac => "flac",
64        }
65    }
66
67    /// Parses [`as_str`](Self::as_str)'s names, and `pcm` (OpenAI's name for 16-bit PCM) as
68    /// [`Pcm16`](Self::Pcm16); `None` for anything else.
69    pub fn parse(name: &str) -> Option<Self> {
70        match name.trim().to_ascii_lowercase().as_str() {
71            "wav" => Some(AudioFormat::Wav),
72            "pcm16" | "pcm" => Some(AudioFormat::Pcm16),
73            "mp3" => Some(AudioFormat::Mp3),
74            "opus" => Some(AudioFormat::Opus),
75            "flac" => Some(AudioFormat::Flac),
76            _ => None,
77        }
78    }
79}
80
81impl std::fmt::Display for AudioFormat {
82    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
83        f.write_str(self.as_str())
84    }
85}
86
87/// What a voice-cloning model needs with the reference clip: `audio` (the clip; a transcript is
88/// not used), `audio_and_text` (the clip; its transcript helps but may be left out) or
89/// `audio_text_required` on the wire, as `weirdnet_agent::speech::CloneMode`.
90#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92#[non_exhaustive]
93pub enum CloneMode {
94    /// The reference clip only; a transcript sent with it is not used.
95    Audio,
96    /// The clip, with an optional transcript the model uses when given.
97    AudioAndText,
98    /// The clip and its transcript, both required.
99    AudioTextRequired,
100}
101
102/// What one speaking model does, takes and allows. See the [module docs](self); the fields are
103/// those of `weirdnet_agent::speech::SpeechProfile`, with the same names on the wire.
104#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
105#[non_exhaustive]
106pub struct SpeechProfile {
107    /// The named preset voices, the model's default first when known. `None`: the model takes no
108    /// preset by name (or none was reported).
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub presets: Option<Vec<String>>,
111    /// Designs a voice from a description.
112    #[serde(default, skip_serializing_if = "is_false")]
113    pub design: bool,
114    /// Takes style or emotion instructions for the chosen voice.
115    #[serde(default, skip_serializing_if = "is_false")]
116    pub instructions: bool,
117    /// Clones a voice from a reference clip, and what the clip needs.
118    #[serde(default, skip_serializing_if = "Option::is_none")]
119    pub clone: Option<CloneMode>,
120    /// Speaks multi-speaker scripts with up to this many speakers (speaker numbers below it).
121    #[serde(default, skip_serializing_if = "Option::is_none")]
122    pub script_speakers: Option<u8>,
123    /// Most voices one request may set (the voice plus per-speaker voices).
124    #[serde(default, skip_serializing_if = "Option::is_none")]
125    pub max_voices: Option<u8>,
126    /// Takes raw engine input with no template (such as Kokoro phonemes).
127    #[serde(default, skip_serializing_if = "is_false")]
128    pub raw: bool,
129    /// Takes a speaking speed.
130    #[serde(default, skip_serializing_if = "is_false")]
131    pub speed: bool,
132    /// Streams audio as it is made.
133    #[serde(default, skip_serializing_if = "is_false")]
134    pub streaming: bool,
135    /// The languages it speaks from text (ISO 639-1 or the engine's codes). `None`: not reported.
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub languages: Option<Vec<String>>,
138    /// The output formats it produces, the default first. Empty: not reported.
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub formats: Vec<AudioFormat>,
141    /// Its output sample rate in Hz.
142    #[serde(default, skip_serializing_if = "Option::is_none")]
143    pub sample_rate: Option<u32>,
144    /// Longest input in characters one request may carry.
145    #[serde(default, skip_serializing_if = "Option::is_none")]
146    pub max_input_chars: Option<u32>,
147    /// Longest reference clip in seconds (what the engine uses of a longer one).
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub max_reference_seconds: Option<u32>,
150    /// Largest reference clip in bytes.
151    #[serde(default, skip_serializing_if = "Option::is_none")]
152    pub max_reference_bytes: Option<u64>,
153    /// Longest audio one request produces, in seconds.
154    #[serde(default, skip_serializing_if = "Option::is_none")]
155    pub max_output_seconds: Option<u32>,
156    /// The model's license when it restricts how speech may be served, such as
157    /// [`FISH_AUDIO_COMMUNITY`].
158    #[serde(default, skip_serializing_if = "Option::is_none")]
159    pub license: Option<String>,
160}
161
162fn is_false(b: &bool) -> bool {
163    !*b
164}
165
166impl SpeechProfile {
167    pub fn new() -> Self {
168        Self::default()
169    }
170
171    pub fn with_presets<S: Into<String>>(mut self, presets: impl IntoIterator<Item = S>) -> Self {
172        self.presets = Some(presets.into_iter().map(Into::into).collect());
173        self
174    }
175
176    pub fn with_design(mut self, design: bool) -> Self {
177        self.design = design;
178        self
179    }
180
181    pub fn with_instructions(mut self, instructions: bool) -> Self {
182        self.instructions = instructions;
183        self
184    }
185
186    pub fn with_clone(mut self, clone: CloneMode) -> Self {
187        self.clone = Some(clone);
188        self
189    }
190
191    pub fn with_script_speakers(mut self, speakers: u8) -> Self {
192        self.script_speakers = Some(speakers);
193        self
194    }
195
196    pub fn with_max_voices(mut self, voices: u8) -> Self {
197        self.max_voices = Some(voices);
198        self
199    }
200
201    pub fn with_raw(mut self, raw: bool) -> Self {
202        self.raw = raw;
203        self
204    }
205
206    pub fn with_speed(mut self, speed: bool) -> Self {
207        self.speed = speed;
208        self
209    }
210
211    pub fn with_streaming(mut self, streaming: bool) -> Self {
212        self.streaming = streaming;
213        self
214    }
215
216    pub fn with_languages<S: Into<String>>(mut self, languages: impl IntoIterator<Item = S>) -> Self {
217        self.languages = Some(languages.into_iter().map(Into::into).collect());
218        self
219    }
220
221    /// The output formats, the default first.
222    pub fn with_formats(mut self, formats: impl IntoIterator<Item = AudioFormat>) -> Self {
223        self.formats = formats.into_iter().collect();
224        self
225    }
226
227    pub fn with_sample_rate(mut self, hz: u32) -> Self {
228        self.sample_rate = Some(hz);
229        self
230    }
231
232    pub fn with_max_input_chars(mut self, chars: u32) -> Self {
233        self.max_input_chars = Some(chars);
234        self
235    }
236
237    pub fn with_max_reference_seconds(mut self, seconds: u32) -> Self {
238        self.max_reference_seconds = Some(seconds);
239        self
240    }
241
242    pub fn with_max_reference_bytes(mut self, bytes: u64) -> Self {
243        self.max_reference_bytes = Some(bytes);
244        self
245    }
246
247    pub fn with_max_output_seconds(mut self, seconds: u32) -> Self {
248        self.max_output_seconds = Some(seconds);
249        self
250    }
251
252    pub fn with_license(mut self, license: impl Into<String>) -> Self {
253        self.license = Some(license.into());
254        self
255    }
256
257    /// Nothing is reported (every field unset).
258    pub fn is_unknown(&self) -> bool {
259        *self == Self::default()
260    }
261
262    /// The format a request without one gets: the first reported.
263    pub fn default_format(&self) -> Option<AudioFormat> {
264        self.formats.first().copied()
265    }
266
267    /// Each field from `self` when it is set, else from `fallback`: what an engine reports at
268    /// load over a catalog entry or a header (`reported.or(&cataloged)`). A bool is set when it is
269    /// true; empty formats count as unset. Nothing here narrows: operator overrides go through
270    /// `weirdnet_agent::speech::SpeechProfile::narrowed_by`.
271    pub fn or(&self, fallback: &Self) -> Self {
272        Self {
273            presets: self.presets.clone().or_else(|| fallback.presets.clone()),
274            design: self.design || fallback.design,
275            instructions: self.instructions || fallback.instructions,
276            clone: self.clone.or(fallback.clone),
277            script_speakers: self.script_speakers.or(fallback.script_speakers),
278            max_voices: self.max_voices.or(fallback.max_voices),
279            raw: self.raw || fallback.raw,
280            speed: self.speed || fallback.speed,
281            streaming: self.streaming || fallback.streaming,
282            languages: self.languages.clone().or_else(|| fallback.languages.clone()),
283            formats: if self.formats.is_empty() { fallback.formats.clone() } else { self.formats.clone() },
284            sample_rate: self.sample_rate.or(fallback.sample_rate),
285            max_input_chars: self.max_input_chars.or(fallback.max_input_chars),
286            max_reference_seconds: self.max_reference_seconds.or(fallback.max_reference_seconds),
287            max_reference_bytes: self.max_reference_bytes.or(fallback.max_reference_bytes),
288            max_output_seconds: self.max_output_seconds.or(fallback.max_output_seconds),
289            license: self.license.clone().or_else(|| fallback.license.clone()),
290        }
291    }
292}
293
294/// What llama-server's `/v1/audio/speech` produces for every speech model: `wav` (the default)
295/// and `pcm` (16-bit), streamed with `stream_format: "audio"`.
296pub(crate) fn llama_server() -> SpeechProfile {
297    SpeechProfile::new().with_formats([AudioFormat::Wav, AudioFormat::Pcm16]).with_streaming(true)
298}
299
300/// What vLLM-Omni's `/v1/audio/speech` produces: `wav`, `mp3`, `flac`, `pcm` and `opus`,
301/// streamed with `stream: true`, with a `speed`.
302pub(crate) fn vllm_omni() -> SpeechProfile {
303    SpeechProfile::new()
304        .with_formats([AudioFormat::Wav, AudioFormat::Mp3, AudioFormat::Flac, AudioFormat::Pcm16, AudioFormat::Opus])
305        .with_streaming(true)
306        .with_speed(true)
307}
308
309/// Qwen3-TTS's ten languages (its model card; llama.cpp's `--tts-lang` codes).
310pub(crate) const QWEN3_TTS_LANGUAGES: [&str; 10] = ["zh", "en", "de", "it", "pt", "es", "ja", "ko", "fr", "ru"];
311/// Kokoro speaks English from text (`en-us`, `en-gb`); other voices need phonemes (`raw`).
312pub(crate) const KOKORO_LANGUAGES: [&str; 2] = ["en-us", "en-gb"];
313
314/// The speech profile a hand-placed GGUF speech model's headers give, for llama-server (the
315/// engine that runs GGUF speech models): `None` unless the projector generates audio
316/// (`clip.has_gen_audio_encoder`), which is how llama.cpp marks a speech model's `mmproj`.
317///
318/// Per projector type (`clip.gen.audio.projector_type`), following llama.cpp's
319/// `docs/multimodal/tts.md` (2026-11):
320///
321/// - `qwen3tts_gen` (Qwen3-TTS): ten languages, 24 kHz; cloning from the clip when the projector
322///   has the speaker encoder (`clip.has_audio_encoder`). A transcript only helps with a speech
323///   tokenizer encoder the header doesn't name, so the clone mode is `audio`.
324/// - `kokoro` (Kokoro): the preset voices stored in the projector (`voice.*` tensors, the
325///   default `clip.gen.audio.default_voice` first), English from text, raw phonemes, speed,
326///   24 kHz.
327/// - `voxcpm2_gen` (VoxCPM2): voice design (a description in parentheses), cloning from the clip
328///   (its first 30 s; no transcript) with the AudioVAE encoder, 48 kHz.
329/// - `drama3_gen` (Fish Audio Drama 3): scripts of 16 speakers; cloning one voice from a clip
330///   and its transcript only with a projector that has the codec encoder
331///   (`clip.has_audio_encoder`), 44.1 kHz.
332/// - Any other type: what llama-server does for every speech model.
333///
334/// Every profile has llama-server's formats (`wav`, `pcm16`) and streaming, the languages in the
335/// model's `general.languages` when the list above has none, the presets stored in the
336/// projector, and the license when it restricts use (not a permissive SPDX id; Fish Audio's
337/// licenses as [`FISH_AUDIO_COMMUNITY`]).
338pub fn from_gguf(model: &GgufHeader, projector: &GgufHeader) -> Option<SpeechProfile> {
339    let p = projector.projector.as_ref().filter(|p| p.speech)?;
340    let mut s = llama_server();
341    let voices = || {
342        let mut v = p.voices.clone();
343        if let Some(d) = &p.default_voice
344            && let Some(i) = v.iter().position(|x| x == d)
345        {
346            let d = v.remove(i);
347            v.insert(0, d);
348        }
349        v
350    };
351    match p.speech_type() {
352        Some("qwen3tts_gen") => {
353            s = s.with_languages(QWEN3_TTS_LANGUAGES).with_sample_rate(QWEN3_TTS_RATE);
354            if p.audio {
355                s = s.with_clone(CloneMode::Audio);
356            }
357        }
358        Some("kokoro") => {
359            s = s.with_languages(KOKORO_LANGUAGES).with_raw(true).with_speed(true).with_sample_rate(KOKORO_RATE);
360        }
361        Some("voxcpm2_gen") => {
362            s = s.with_design(true).with_sample_rate(VOXCPM2_RATE);
363            if p.audio {
364                s = s.with_clone(CloneMode::Audio).with_max_reference_seconds(LLAMA_REFERENCE_SECONDS);
365            }
366        }
367        Some("drama3_gen") => {
368            s = s.with_script_speakers(DRAMA3_SPEAKERS).with_sample_rate(DRAMA3_RATE);
369            if p.audio {
370                s = s.with_clone(CloneMode::AudioTextRequired).with_max_voices(1).with_max_reference_seconds(LLAMA_REFERENCE_SECONDS);
371            }
372        }
373        _ => {}
374    }
375    let v = voices();
376    if !v.is_empty() {
377        s.presets = Some(v);
378    }
379    if s.languages.is_none() {
380        let langs = if model.languages.is_empty() { &projector.languages } else { &model.languages };
381        if !langs.is_empty() {
382            s.languages = Some(langs.clone());
383        }
384    }
385    s.license = restricting_license(model.license.as_deref()).or_else(|| restricting_license(projector.license.as_deref()));
386    Some(s)
387}
388
389/// Licenses that don't restrict how speech is served (lower-case SPDX ids).
390const PERMISSIVE: [&str; 9] = ["apache-2.0", "mit", "bsd-2-clause", "bsd-3-clause", "isc", "cc0-1.0", "cc-by-4.0", "unlicense", "mpl-2.0"];
391
392/// `license` (a header's or a card's) when it restricts use: anything but a permissive SPDX id,
393/// with Fish Audio's license names as [`FISH_AUDIO_COMMUNITY`]. `None` when absent or permissive.
394pub fn restricting_license(license: Option<&str>) -> Option<String> {
395    let l = license?.trim().to_ascii_lowercase();
396    if l.is_empty() || PERMISSIVE.contains(&l.as_str()) {
397        return None;
398    }
399    if l.starts_with("fish-audio") {
400        return Some(FISH_AUDIO_COMMUNITY.into());
401    }
402    Some(l)
403}
404
405#[cfg(feature = "agent")]
406mod agent_conv {
407    use super::*;
408    use weirdnet_agent::speech as a;
409
410    impl From<AudioFormat> for a::AudioFormat {
411        fn from(f: AudioFormat) -> Self {
412            match f {
413                AudioFormat::Wav => a::AudioFormat::Wav,
414                AudioFormat::Pcm16 => a::AudioFormat::Pcm16,
415                AudioFormat::Mp3 => a::AudioFormat::Mp3,
416                AudioFormat::Opus => a::AudioFormat::Opus,
417                AudioFormat::Flac => a::AudioFormat::Flac,
418            }
419        }
420    }
421
422    impl AudioFormat {
423        /// The agent's format, if this version knows it.
424        pub fn from_agent(f: a::AudioFormat) -> Option<Self> {
425            AudioFormat::parse(f.as_str())
426        }
427    }
428
429    impl From<CloneMode> for a::CloneMode {
430        fn from(c: CloneMode) -> Self {
431            match c {
432                CloneMode::Audio => a::CloneMode::Audio,
433                CloneMode::AudioAndText => a::CloneMode::AudioAndText,
434                CloneMode::AudioTextRequired => a::CloneMode::AudioTextRequired,
435            }
436        }
437    }
438
439    impl CloneMode {
440        /// The agent's clone mode, if this version knows it.
441        pub fn from_agent(c: a::CloneMode) -> Option<Self> {
442            match c {
443                a::CloneMode::Audio => Some(CloneMode::Audio),
444                a::CloneMode::AudioAndText => Some(CloneMode::AudioAndText),
445                a::CloneMode::AudioTextRequired => Some(CloneMode::AudioTextRequired),
446                _ => None,
447            }
448        }
449    }
450
451    impl SpeechProfile {
452        /// The same profile as `weirdnet_agent::speech::SpeechProfile`, which catalog entries and
453        /// `ModelStatus` carry.
454        pub fn to_agent(&self) -> a::SpeechProfile {
455            let mut p = a::SpeechProfile::new();
456            p.presets = self.presets.clone();
457            p.design = self.design;
458            p.instructions = self.instructions;
459            p.clone = self.clone.map(Into::into);
460            p.script_speakers = self.script_speakers;
461            p.max_voices = self.max_voices;
462            p.raw = self.raw;
463            p.speed = self.speed;
464            p.streaming = self.streaming;
465            p.languages = self.languages.clone();
466            p.formats = self.formats.iter().copied().map(Into::into).collect();
467            p.sample_rate = self.sample_rate;
468            p.max_input_chars = self.max_input_chars;
469            p.max_reference_seconds = self.max_reference_seconds;
470            p.max_reference_bytes = self.max_reference_bytes;
471            p.max_output_seconds = self.max_output_seconds;
472            p.license = self.license.clone();
473            p
474        }
475
476        /// An agent profile as this crate's. A clone mode or format this version doesn't know is
477        /// left out (the clone mode as no cloning), never guessed.
478        pub fn from_agent(p: &a::SpeechProfile) -> Self {
479            Self {
480                presets: p.presets.clone(),
481                design: p.design,
482                instructions: p.instructions,
483                clone: p.clone.and_then(CloneMode::from_agent),
484                script_speakers: p.script_speakers,
485                max_voices: p.max_voices,
486                raw: p.raw,
487                speed: p.speed,
488                streaming: p.streaming,
489                languages: p.languages.clone(),
490                formats: p.formats.iter().copied().filter_map(AudioFormat::from_agent).collect(),
491                sample_rate: p.sample_rate,
492                max_input_chars: p.max_input_chars,
493                max_reference_seconds: p.max_reference_seconds,
494                max_reference_bytes: p.max_reference_bytes,
495                max_output_seconds: p.max_output_seconds,
496                license: p.license.clone(),
497            }
498        }
499    }
500
501    impl From<SpeechProfile> for a::SpeechProfile {
502        fn from(p: SpeechProfile) -> Self {
503            p.to_agent()
504        }
505    }
506
507    impl From<a::SpeechProfile> for SpeechProfile {
508        fn from(p: a::SpeechProfile) -> Self {
509            Self::from_agent(&p)
510        }
511    }
512}
513
514#[cfg(test)]
515mod tests {
516    use super::*;
517    use crate::gguf::{header, read_header, speech_projector_header};
518    use serde_json::json;
519
520    fn model(arch: &str, extra: &[(&str, serde_json::Value)]) -> GgufHeader {
521        let mut kv = vec![("general.architecture", json!(arch))];
522        kv.extend_from_slice(extra);
523        read_header(&header(&kv)[..]).unwrap()
524    }
525
526    fn proj(which: &str) -> GgufHeader {
527        read_header(&speech_projector_header(which)[..]).unwrap()
528    }
529
530    #[test]
531    fn unknown_is_empty_on_the_wire_and_fields_round_trip() {
532        assert!(SpeechProfile::default().is_unknown());
533        assert_eq!(serde_json::to_string(&SpeechProfile::new()).unwrap(), "{}");
534        let p = SpeechProfile::new()
535            .with_presets(["vivian"])
536            .with_clone(CloneMode::AudioAndText)
537            .with_formats([AudioFormat::Wav, AudioFormat::Pcm16])
538            .with_sample_rate(24_000)
539            .with_streaming(true)
540            .with_license(FISH_AUDIO_COMMUNITY);
541        let j = serde_json::to_value(&p).unwrap();
542        assert_eq!(
543            j,
544            json!({"presets": ["vivian"], "clone": "audio_and_text", "streaming": true, "formats": ["wav", "pcm16"], "sample_rate": 24000, "license": "fish-audio-community"})
545        );
546        assert_eq!(serde_json::from_value::<SpeechProfile>(j).unwrap(), p);
547        assert_eq!(p.default_format(), Some(AudioFormat::Wav));
548        // Fields from a newer version are ignored.
549        let newer: SpeechProfile = serde_json::from_value(json!({"design": true, "emotions": ["happy"]})).unwrap();
550        assert_eq!(newer, SpeechProfile::new().with_design(true));
551        for f in AudioFormat::ALL {
552            assert_eq!(AudioFormat::parse(f.as_str()), Some(f));
553            assert_eq!(serde_json::to_value(f).unwrap(), json!(f.as_str()));
554        }
555        assert_eq!(AudioFormat::parse("PCM"), Some(AudioFormat::Pcm16));
556        assert_eq!(AudioFormat::parse("aac"), None);
557    }
558
559    #[test]
560    fn reported_over_cataloged() {
561        let catalog = SpeechProfile::new().with_presets(["a", "b"]).with_languages(["en"]).with_formats([AudioFormat::Wav]).with_speed(true);
562        let engine = SpeechProfile::new().with_presets(["a"]).with_sample_rate(24_000);
563        let both = engine.or(&catalog);
564        assert_eq!(both.presets, Some(vec!["a".to_string()]));
565        assert_eq!((both.languages.as_deref(), both.sample_rate, both.speed), (Some(&["en".to_string()][..]), Some(24_000), true));
566        assert_eq!(both.formats, [AudioFormat::Wav]);
567        assert_eq!(SpeechProfile::new().or(&catalog), catalog);
568    }
569
570    #[test]
571    fn licenses_that_restrict() {
572        assert_eq!(restricting_license(None), None);
573        assert_eq!(restricting_license(Some("Apache-2.0")), None);
574        assert_eq!(restricting_license(Some("mit")), None);
575        assert_eq!(restricting_license(Some("fish-audio-research-license")).as_deref(), Some(FISH_AUDIO_COMMUNITY));
576        assert_eq!(restricting_license(Some("fish-audio-community")).as_deref(), Some(FISH_AUDIO_COMMUNITY));
577        assert_eq!(restricting_license(Some("cc-by-nc-4.0")).as_deref(), Some("cc-by-nc-4.0"));
578    }
579
580    #[test]
581    fn hand_placed_gguf_speech_models() {
582        // Kokoro: the projector's voices, the default first; English from text, phonemes, speed.
583        let k = from_gguf(&model("kokoro", &[("general.license", json!("apache-2.0"))]), &proj("kokoro")).unwrap();
584        assert_eq!(k.presets.as_deref(), Some(&["af_heart".to_string(), "af_alloy".into(), "bm_george".into()][..]));
585        assert!(k.raw && k.speed && k.streaming && k.clone.is_none() && !k.design);
586        assert_eq!(
587            (k.languages.unwrap(), k.sample_rate, k.formats),
588            (vec!["en-us".to_string(), "en-gb".into()], Some(24_000), vec![AudioFormat::Wav, AudioFormat::Pcm16])
589        );
590        assert_eq!(k.license, None);
591        // Qwen3-TTS Base with the speaker encoder: clones from the clip alone.
592        let q = from_gguf(&model("qwen3tts", &[]), &proj("qwen3tts")).unwrap();
593        assert_eq!((q.clone, q.sample_rate, q.languages.as_ref().map(Vec::len)), (Some(CloneMode::Audio), Some(24_000), Some(10)));
594        assert!(!q.instructions && !q.speed && q.presets.is_none());
595        // VoxCPM2: design and cloning; languages from the header.
596        let v = from_gguf(&model("minicpm", &[("general.languages", json!(["zh", "en", "fr"]))]), &proj("voxcpm2")).unwrap();
597        assert!(v.design);
598        assert_eq!((v.clone, v.max_reference_seconds, v.sample_rate), (Some(CloneMode::Audio), Some(30), Some(48_000)));
599        assert_eq!(v.languages.unwrap(), ["zh", "en", "fr"]);
600        // Drama 3 as ggml-org publishes it: scripts, no cloning (no codec encoder), restricted.
601        let d = from_gguf(
602            &model("qwen35moe", &[("general.license", json!("other")), ("general.license.name", json!("fish-audio-research-license"))]),
603            &proj("drama3"),
604        )
605        .unwrap();
606        assert_eq!((d.script_speakers, d.clone, d.max_voices, d.sample_rate), (Some(16), None, None, Some(44_100)));
607        assert_eq!(d.license.as_deref(), Some(FISH_AUDIO_COMMUNITY));
608        // With the codec encoder: one cloned voice, its transcript required.
609        let dc = from_gguf(&model("qwen35moe", &[]), &proj("drama3-codec")).unwrap();
610        assert_eq!((dc.clone, dc.max_voices, dc.max_reference_seconds), (Some(CloneMode::AudioTextRequired), Some(1), Some(30)));
611        assert_eq!(dc.license.as_deref(), Some(FISH_AUDIO_COMMUNITY), "the projector's license counts too");
612        // Projectors that don't generate audio give no profile.
613        let voxtral = read_header(&crate::gguf::projector_header("voxtral")[..]).unwrap();
614        assert_eq!(from_gguf(&model("llama", &[]), &voxtral), None);
615    }
616
617    #[cfg(feature = "agent")]
618    #[test]
619    fn same_wire_form_as_the_agent() {
620        use weirdnet_agent::speech as a;
621        for e in crate::hw::by_purpose(crate::hw::Purpose::Speak) {
622            let p = e.speech().unwrap();
623            let agent = p.to_agent();
624            assert_eq!(serde_json::to_value(&p).unwrap(), serde_json::to_value(&agent).unwrap(), "{}", e.id());
625            let back: a::SpeechProfile = serde_json::from_value(serde_json::to_value(&p).unwrap()).unwrap();
626            assert_eq!(back, agent);
627            assert_eq!(SpeechProfile::from_agent(&agent), p);
628            assert_eq!(SpeechProfile::from(a::SpeechProfile::from(p.clone())), p);
629        }
630        let full = SpeechProfile::new()
631            .with_presets(["x"])
632            .with_design(true)
633            .with_instructions(true)
634            .with_clone(CloneMode::AudioTextRequired)
635            .with_script_speakers(4)
636            .with_max_voices(2)
637            .with_raw(true)
638            .with_speed(true)
639            .with_streaming(true)
640            .with_languages(["en"])
641            .with_formats(AudioFormat::ALL)
642            .with_sample_rate(44_100)
643            .with_max_input_chars(2000)
644            .with_max_reference_seconds(30)
645            .with_max_reference_bytes(1 << 20)
646            .with_max_output_seconds(180)
647            .with_license("x");
648        assert_eq!(serde_json::to_value(&full).unwrap(), serde_json::to_value(full.to_agent()).unwrap());
649        assert_eq!(SpeechProfile::from_agent(&full.to_agent()), full);
650        assert!(full.to_agent().covers(&a::SpeechNeeds::default()).is_ok());
651    }
652}