Skip to main content

weirdnet_agent/
speech.rs

1//! Speech out (text to speech): what a speaking model does, and what a request needs from it.
2//!
3//! A model whose catalog purpose is [`Purpose::Speak`](crate::remote::catalog::Purpose::Speak)
4//! turns text into audio (infer/2 `Speak`, see
5//! [`SpeakRequest`](crate::remote::infer::v2::SpeakRequest)). Each serving copy has a
6//! [`SpeechProfile`]: what it does (preset voices, designed voices, style instructions, cloned
7//! voices, multi-speaker scripts, raw engine input, speed, streaming), what it takes (languages,
8//! output formats, sample rate) and its limits. A request asks for one shape and the profile says
9//! whether the model can serve it ([`SpeechProfile::covers`]); nothing is faked: a request for a
10//! feature the model lacks is refused with a message that names it.
11//!
12//! **Profiles are reported or absent.** A bool is true only when the node knows the model does it;
13//! a list or limit is `None` (or, for [`formats`](SpeechProfile::formats), empty) when nobody
14//! reported it, never defaulted. Every field is left off the wire when unset.
15//!
16//! - [`SpeechProfile::tightest`] merges the copies of one model across nodes for the catalog: the
17//!   intersection of lists, the smallest limit, and a feature only when every copy has it.
18//! - [`SpeechProfile::narrowed_by`] applies an operator's overrides: fewer voices, a smaller limit,
19//!   a limit the engine doesn't report; anything that would widen what the engine reports is an
20//!   error.
21//!
22//! Since 0.5.11.
23
24use serde::{Deserialize, Serialize};
25
26/// An audio encoding for speech out: `wav`, `pcm16` (raw little-endian 16-bit samples), `mp3`,
27/// `opus` or `flac` on the wire.
28#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
29#[serde(rename_all = "snake_case")]
30#[non_exhaustive]
31pub enum AudioFormat {
32    #[default]
33    Wav,
34    Pcm16,
35    Mp3,
36    Opus,
37    Flac,
38}
39
40impl AudioFormat {
41    /// Every format, in wire order.
42    pub const ALL: [AudioFormat; 5] = [AudioFormat::Wav, AudioFormat::Pcm16, AudioFormat::Mp3, AudioFormat::Opus, AudioFormat::Flac];
43
44    /// The name on the wire: `wav`, `pcm16`, `mp3`, `opus`, `flac`.
45    pub fn as_str(&self) -> &'static str {
46        match self {
47            AudioFormat::Wav => "wav",
48            AudioFormat::Pcm16 => "pcm16",
49            AudioFormat::Mp3 => "mp3",
50            AudioFormat::Opus => "opus",
51            AudioFormat::Flac => "flac",
52        }
53    }
54
55    /// Parses [`as_str`](Self::as_str)'s names, and `pcm` (OpenAI's name for 16-bit PCM) as
56    /// [`Pcm16`](Self::Pcm16); `None` for anything else.
57    pub fn parse(name: &str) -> Option<Self> {
58        match name.trim().to_ascii_lowercase().as_str() {
59            "wav" => Some(AudioFormat::Wav),
60            "pcm16" | "pcm" => Some(AudioFormat::Pcm16),
61            "mp3" => Some(AudioFormat::Mp3),
62            "opus" => Some(AudioFormat::Opus),
63            "flac" => Some(AudioFormat::Flac),
64            _ => None,
65        }
66    }
67
68    /// The MIME type of a file in this format (`audio/pcm` for raw samples; add the rate as
69    /// `audio/pcm;rate=24000`).
70    pub fn mime(&self) -> &'static str {
71        match self {
72            AudioFormat::Wav => "audio/wav",
73            AudioFormat::Pcm16 => "audio/pcm",
74            AudioFormat::Mp3 => "audio/mpeg",
75            AudioFormat::Opus => "audio/ogg",
76            AudioFormat::Flac => "audio/flac",
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` (the clip and its transcript) on the wire.
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 ignored (and named in
95    /// [`Meta::ignored`](crate::remote::infer::v2::Meta::ignored)).
96    Audio,
97    /// The clip, with an optional transcript the model uses when given.
98    AudioAndText,
99    /// The clip and its transcript, both required.
100    AudioTextRequired,
101}
102
103impl CloneMode {
104    /// A transcript must come with the clip.
105    pub fn needs_text(&self) -> bool {
106        *self == CloneMode::AudioTextRequired
107    }
108
109    /// A transcript sent with the clip is used.
110    pub fn uses_text(&self) -> bool {
111        matches!(self, CloneMode::AudioAndText | CloneMode::AudioTextRequired)
112    }
113
114    /// What every copy of a model accepts when one copy does `self` and another `other`: a
115    /// transcript is required if either requires it, and counts as used only if both use it.
116    pub fn tightest(self, other: Self) -> Self {
117        use CloneMode::*;
118        match (self, other) {
119            (AudioTextRequired, _) | (_, AudioTextRequired) => AudioTextRequired,
120            (Audio, _) | (_, Audio) => Audio,
121            _ => AudioAndText,
122        }
123    }
124
125    fn rank(self) -> u8 {
126        // How much the mode asks of a request: narrowing may only ask more.
127        match self {
128            CloneMode::Audio | CloneMode::AudioAndText => 0,
129            CloneMode::AudioTextRequired => 1,
130        }
131    }
132}
133
134/// What one speaking model does, takes and allows. See the [module docs](self).
135#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
136#[non_exhaustive]
137pub struct SpeechProfile {
138    /// The named preset voices (`Voice::Preset`). `None`: the model takes no preset by name (or
139    /// none was reported); requests without a voice get the model's default.
140    #[serde(default, skip_serializing_if = "Option::is_none")]
141    pub presets: Option<Vec<String>>,
142    /// Designs a voice from a description (`Voice::Design`).
143    #[serde(default, skip_serializing_if = "is_false")]
144    pub design: bool,
145    /// Takes style or emotion instructions for the chosen voice.
146    #[serde(default, skip_serializing_if = "is_false")]
147    pub instructions: bool,
148    /// Clones a voice from a reference clip (`Voice::Clone`), and what the clip needs.
149    #[serde(default, skip_serializing_if = "Option::is_none")]
150    pub clone: Option<CloneMode>,
151    /// Speaks multi-speaker scripts with up to this many speakers (speaker numbers below it).
152    #[serde(default, skip_serializing_if = "Option::is_none")]
153    pub script_speakers: Option<u8>,
154    /// Most voices one request may set (the voice plus per-speaker voices).
155    #[serde(default, skip_serializing_if = "Option::is_none")]
156    pub max_voices: Option<u8>,
157    /// Takes raw engine input with no template (`SpeakInput::Raw`, such as phonemes).
158    #[serde(default, skip_serializing_if = "is_false")]
159    pub raw: bool,
160    /// Takes a speaking speed.
161    #[serde(default, skip_serializing_if = "is_false")]
162    pub speed: bool,
163    /// Streams audio as it is made (otherwise the finished file comes in chunks).
164    #[serde(default, skip_serializing_if = "is_false")]
165    pub streaming: bool,
166    /// The languages it speaks from text (ISO 639-1 or the engine's codes). `None`: not reported.
167    #[serde(default, skip_serializing_if = "Option::is_none")]
168    pub languages: Option<Vec<String>>,
169    /// The output formats it produces, the default first. Empty: not reported.
170    #[serde(default, skip_serializing_if = "Vec::is_empty")]
171    pub formats: Vec<AudioFormat>,
172    /// Its output sample rate in Hz.
173    #[serde(default, skip_serializing_if = "Option::is_none")]
174    pub sample_rate: Option<u32>,
175    /// Longest input in characters one request may carry.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub max_input_chars: Option<u32>,
178    /// Longest reference clip in seconds.
179    #[serde(default, skip_serializing_if = "Option::is_none")]
180    pub max_reference_seconds: Option<u32>,
181    /// Largest reference clip in bytes.
182    #[serde(default, skip_serializing_if = "Option::is_none")]
183    pub max_reference_bytes: Option<u64>,
184    /// Longest audio one request produces, in seconds.
185    #[serde(default, skip_serializing_if = "Option::is_none")]
186    pub max_output_seconds: Option<u32>,
187    /// The model's license (an SPDX id or a named license such as `fish-audio-community`) when it
188    /// restricts how speech may be served.
189    #[serde(default, skip_serializing_if = "Option::is_none")]
190    pub license: Option<String>,
191}
192
193fn is_false(b: &bool) -> bool {
194    !*b
195}
196
197fn min_known<T: Ord>(a: Option<T>, b: Option<T>) -> Option<T> {
198    match (a, b) {
199        (Some(a), Some(b)) => Some(a.min(b)),
200        (a, b) => a.or(b),
201    }
202}
203
204fn intersect<T: PartialEq + Clone>(a: &[T], b: &[T]) -> Vec<T> {
205    a.iter().filter(|x| b.contains(x)).cloned().collect()
206}
207
208impl SpeechProfile {
209    pub fn new() -> Self {
210        Self::default()
211    }
212
213    pub fn with_presets(mut self, presets: Vec<String>) -> Self {
214        self.presets = Some(presets);
215        self
216    }
217
218    pub fn with_design(mut self, design: bool) -> Self {
219        self.design = design;
220        self
221    }
222
223    pub fn with_instructions(mut self, instructions: bool) -> Self {
224        self.instructions = instructions;
225        self
226    }
227
228    pub fn with_clone(mut self, clone: CloneMode) -> Self {
229        self.clone = Some(clone);
230        self
231    }
232
233    pub fn with_script_speakers(mut self, speakers: u8) -> Self {
234        self.script_speakers = Some(speakers);
235        self
236    }
237
238    pub fn with_max_voices(mut self, voices: u8) -> Self {
239        self.max_voices = Some(voices);
240        self
241    }
242
243    pub fn with_raw(mut self, raw: bool) -> Self {
244        self.raw = raw;
245        self
246    }
247
248    pub fn with_speed(mut self, speed: bool) -> Self {
249        self.speed = speed;
250        self
251    }
252
253    pub fn with_streaming(mut self, streaming: bool) -> Self {
254        self.streaming = streaming;
255        self
256    }
257
258    pub fn with_languages(mut self, languages: Vec<String>) -> Self {
259        self.languages = Some(languages);
260        self
261    }
262
263    /// The output formats, the default first.
264    pub fn with_formats(mut self, formats: Vec<AudioFormat>) -> Self {
265        self.formats = formats;
266        self
267    }
268
269    pub fn with_sample_rate(mut self, hz: u32) -> Self {
270        self.sample_rate = Some(hz);
271        self
272    }
273
274    pub fn with_max_input_chars(mut self, chars: u32) -> Self {
275        self.max_input_chars = Some(chars);
276        self
277    }
278
279    pub fn with_max_reference_seconds(mut self, seconds: u32) -> Self {
280        self.max_reference_seconds = Some(seconds);
281        self
282    }
283
284    pub fn with_max_reference_bytes(mut self, bytes: u64) -> Self {
285        self.max_reference_bytes = Some(bytes);
286        self
287    }
288
289    pub fn with_max_output_seconds(mut self, seconds: u32) -> Self {
290        self.max_output_seconds = Some(seconds);
291        self
292    }
293
294    pub fn with_license(mut self, license: impl Into<String>) -> Self {
295        self.license = Some(license.into());
296        self
297    }
298
299    /// Nothing is reported (every field unset).
300    pub fn is_unknown(&self) -> bool {
301        *self == Self::default()
302    }
303
304    /// The format a request without one gets: the first reported.
305    pub fn default_format(&self) -> Option<AudioFormat> {
306        self.formats.first().copied()
307    }
308
309    /// What every copy of one model across nodes can do, for the catalog: features
310    /// (`design`, `instructions`, `raw`, `speed`, `streaming`, `presets`, `clone`,
311    /// `script_speakers`) only when both have them (preset lists intersected, the smaller speaker
312    /// count, the stricter clone mode); lists both report intersected and limits both report the
313    /// smaller, a list or limit only one reports kept; the sample rate only when they agree (or
314    /// one reports none); the license when they agree or one reports none.
315    pub fn tightest(a: &Self, b: &Self) -> Self {
316        let both = |x: &Option<Vec<String>>, y: &Option<Vec<String>>| match (x, y) {
317            (Some(x), Some(y)) => Some(intersect(x, y)),
318            _ => None,
319        };
320        let known = |x: &Option<Vec<String>>, y: &Option<Vec<String>>| match (x, y) {
321            (Some(x), Some(y)) => Some(intersect(x, y)),
322            (x, y) => x.clone().or_else(|| y.clone()),
323        };
324        Self {
325            presets: both(&a.presets, &b.presets),
326            design: a.design && b.design,
327            instructions: a.instructions && b.instructions,
328            clone: match (a.clone, b.clone) {
329                (Some(x), Some(y)) => Some(x.tightest(y)),
330                _ => None,
331            },
332            script_speakers: match (a.script_speakers, b.script_speakers) {
333                (Some(x), Some(y)) => Some(x.min(y)),
334                _ => None,
335            },
336            max_voices: min_known(a.max_voices, b.max_voices),
337            raw: a.raw && b.raw,
338            speed: a.speed && b.speed,
339            streaming: a.streaming && b.streaming,
340            languages: known(&a.languages, &b.languages),
341            formats: match (a.formats.is_empty(), b.formats.is_empty()) {
342                (false, false) => intersect(&a.formats, &b.formats),
343                (true, _) => b.formats.clone(),
344                (false, true) => a.formats.clone(),
345            },
346            sample_rate: match (a.sample_rate, b.sample_rate) {
347                (Some(x), Some(y)) if x != y => None,
348                (x, y) => x.or(y),
349            },
350            max_input_chars: min_known(a.max_input_chars, b.max_input_chars),
351            max_reference_seconds: min_known(a.max_reference_seconds, b.max_reference_seconds),
352            max_reference_bytes: min_known(a.max_reference_bytes, b.max_reference_bytes),
353            max_output_seconds: min_known(a.max_output_seconds, b.max_output_seconds),
354            license: match (&a.license, &b.license) {
355                (Some(x), Some(y)) if x != y => None,
356                (x, y) => x.clone().or_else(|| y.clone()),
357            },
358        }
359    }
360
361    /// This (engine-reported) profile with an operator's overrides applied, field by field: a set
362    /// field narrows (a subset of presets, languages or formats; a smaller limit, speaker or voice
363    /// count; a stricter clone mode) or fills a list or limit the engine doesn't report. An unset
364    /// field (`None`, `false`, empty) changes nothing. `Err` names the first field that would
365    /// widen what the engine reports: a preset, language or format it doesn't list, a feature it
366    /// lacks (a `true` bool, a clone mode, a speaker count), presets when it reports none, a
367    /// larger limit, or another license.
368    ///
369    /// Bools can't say "off" here; to turn a feature off (cloning on a node, say), clear the
370    /// field on the result.
371    pub fn narrowed_by(&self, operator: &SpeechProfile) -> Result<Self, String> {
372        fn subset(field: &str, engine: &Option<Vec<String>>, op: &Option<Vec<String>>, fill: bool) -> Result<Option<Vec<String>>, String> {
373            match (engine, op) {
374                (_, None) => Ok(engine.clone()),
375                (None, Some(o)) if fill => Ok(Some(o.clone())),
376                (None, Some(_)) => Err(format!("{field}: the engine reports none, so the operator can't add any")),
377                (Some(e), Some(o)) => match o.iter().find(|x| !e.contains(x)) {
378                    Some(x) => Err(format!("{field}: `{x}` is not one the engine reports ({})", e.join(", "))),
379                    None => Ok(Some(o.clone())),
380                },
381            }
382        }
383        fn feature(field: &str, engine: bool, op: bool) -> Result<bool, String> {
384            if op && !engine { Err(format!("{field}: the engine does not report it, so the operator can't turn it on")) } else { Ok(engine) }
385        }
386        fn limit<T: Ord + Copy + std::fmt::Display>(field: &str, engine: Option<T>, op: Option<T>) -> Result<Option<T>, String> {
387            match (engine, op) {
388                (Some(e), Some(o)) if o > e => Err(format!("{field}: {o} is over the engine's {e}")),
389                (e, o) => Ok(o.or(e)),
390            }
391        }
392        fn count(field: &str, engine: Option<u8>, op: Option<u8>) -> Result<Option<u8>, String> {
393            match (engine, op) {
394                (None, Some(_)) => Err(format!("{field}: the engine does not report it, so the operator can't set it")),
395                (e, o) => limit(field, e, o),
396            }
397        }
398        let formats = if operator.formats.is_empty() {
399            self.formats.clone()
400        } else if self.formats.is_empty() {
401            operator.formats.clone()
402        } else if let Some(f) = operator.formats.iter().find(|f| !self.formats.contains(f)) {
403            return Err(format!("formats: `{f}` is not one the engine produces ({})", join(&self.formats)));
404        } else {
405            operator.formats.clone()
406        };
407        let clone = match (self.clone, operator.clone) {
408            (e, None) => e,
409            (None, Some(_)) => return Err("clone: the engine does not clone voices, so the operator can't turn it on".into()),
410            (Some(e), Some(o)) if o.rank() < e.rank() => return Err(format!("clone: `{o:?}` asks less of a reference than the engine's `{e:?}`")),
411            (Some(e), Some(o)) => Some(if o.rank() == e.rank() { e } else { o }),
412        };
413        let sample_rate = match (self.sample_rate, operator.sample_rate) {
414            (Some(e), Some(o)) if e != o => return Err(format!("sample_rate: {o} Hz is not the engine's {e} Hz")),
415            (e, o) => e.or(o),
416        };
417        let license = match (&self.license, &operator.license) {
418            (Some(e), Some(o)) if e != o => return Err(format!("license: `{o}` is not the engine's `{e}`")),
419            (e, o) => e.clone().or_else(|| o.clone()),
420        };
421        Ok(Self {
422            presets: subset("presets", &self.presets, &operator.presets, false)?,
423            design: feature("design", self.design, operator.design)?,
424            instructions: feature("instructions", self.instructions, operator.instructions)?,
425            clone,
426            script_speakers: count("script_speakers", self.script_speakers, operator.script_speakers)?,
427            max_voices: limit("max_voices", self.max_voices, operator.max_voices)?,
428            raw: feature("raw", self.raw, operator.raw)?,
429            speed: feature("speed", self.speed, operator.speed)?,
430            streaming: feature("streaming", self.streaming, operator.streaming)?,
431            languages: subset("languages", &self.languages, &operator.languages, true)?,
432            formats,
433            sample_rate,
434            max_input_chars: limit("max_input_chars", self.max_input_chars, operator.max_input_chars)?,
435            max_reference_seconds: limit("max_reference_seconds", self.max_reference_seconds, operator.max_reference_seconds)?,
436            max_reference_bytes: limit("max_reference_bytes", self.max_reference_bytes, operator.max_reference_bytes)?,
437            max_output_seconds: limit("max_output_seconds", self.max_output_seconds, operator.max_output_seconds)?,
438            license,
439        })
440    }
441
442    /// Whether a request with these needs can be served by a model with this profile. `Err`
443    /// says what the model lacks (for a `BadRequest` that names the model in front of it), such
444    /// as `has no preset voice `alloy` (presets: vivian, ryan)` or `does not clone voices`.
445    pub fn covers(&self, needs: &SpeechNeeds) -> Result<(), String> {
446        for name in &needs.presets {
447            match &self.presets {
448                None => return Err(format!("has no preset voices (asked for `{name}`)")),
449                Some(p) if !p.contains(name) => {
450                    return Err(format!("has no preset voice `{name}` (presets: {})", if p.is_empty() { "none".into() } else { p.join(", ") }));
451                }
452                Some(_) => {}
453            }
454        }
455        if needs.design && !self.design {
456            return Err("does not design voices from a description".into());
457        }
458        if needs.instructions && !self.instructions {
459            return Err("does not take style instructions".into());
460        }
461        if let Some(has_text) = needs.clone {
462            match self.clone {
463                None => return Err("does not clone voices".into()),
464                Some(mode) if mode.needs_text() && !has_text => return Err("needs the reference clip's transcript to clone a voice".into()),
465                Some(_) => {}
466            }
467        }
468        if needs.speakers > 0 {
469            match self.script_speakers {
470                None => return Err("does not speak multi-speaker scripts".into()),
471                Some(n) if needs.speakers > n => {
472                    return Err(format!(
473                        "speaks scripts with at most {n} speakers (speakers 0 to {}); asked for speaker {}",
474                        n.saturating_sub(1),
475                        needs.speakers - 1
476                    ));
477                }
478                Some(_) => {}
479            }
480        }
481        if let Some(max) = self.max_voices
482            && needs.voices > max
483        {
484            return Err(format!("takes at most {max} voices per request; asked for {}", needs.voices));
485        }
486        if needs.raw && !self.raw {
487            return Err("does not take raw input".into());
488        }
489        if needs.speed && !self.speed {
490            return Err("does not take a speaking speed".into());
491        }
492        if let Some(f) = needs.format {
493            if self.formats.is_empty() {
494                return Err(format!("reports no output formats, so `{f}` can't be promised"));
495            }
496            if !self.formats.contains(&f) {
497                return Err(format!("does not produce `{f}` (formats: {})", join(&self.formats)));
498            }
499        }
500        if let Some(max) = self.max_input_chars
501            && needs.input_chars > max
502        {
503            return Err(format!("takes at most {max} characters per request; this one has {}", needs.input_chars));
504        }
505        if let (Some(max), Some(ms)) = (self.max_reference_seconds, needs.reference_ms)
506            && ms > u64::from(max) * 1000
507        {
508            return Err(format!("takes reference clips of at most {max} s; this one is {:.1} s", ms as f64 / 1000.0));
509        }
510        if let (Some(max), Some(bytes)) = (self.max_reference_bytes, needs.reference_bytes)
511            && bytes > max
512        {
513            return Err(format!("takes reference clips of at most {max} bytes; this one is {bytes}"));
514        }
515        Ok(())
516    }
517}
518
519fn join(formats: &[AudioFormat]) -> String {
520    formats.iter().map(AudioFormat::as_str).collect::<Vec<_>>().join(", ")
521}
522
523/// What one speech request needs from a model's [`SpeechProfile`]
524/// ([`SpeakRequest::needs`](crate::remote::infer::v2::SpeakRequest::needs)), for
525/// [`SpeechProfile::covers`] and
526/// [`Catalog::route_speak`](crate::remote::catalog::Catalog::route_speak).
527#[derive(Debug, Clone, PartialEq, Eq, Default)]
528#[non_exhaustive]
529pub struct SpeechNeeds {
530    /// Preset voices asked for by name (the voice and per-speaker voices), in order, once each.
531    pub presets: Vec<String>,
532    /// A designed voice.
533    pub design: bool,
534    /// Style instructions.
535    pub instructions: bool,
536    /// A cloned voice: `Some(true)` when every reference clip comes with its transcript.
537    pub clone: Option<bool>,
538    /// For a script: the highest speaker number plus one. 0 for plain or raw text.
539    pub speakers: u8,
540    /// Voices set (the voice plus per-speaker voices).
541    pub voices: u8,
542    /// Raw engine input.
543    pub raw: bool,
544    /// A speaking speed.
545    pub speed: bool,
546    /// The output format asked for (`None`: the model's default).
547    pub format: Option<AudioFormat>,
548    /// Characters of input (Unicode scalar values; for a script, the turns' text).
549    pub input_chars: u32,
550    /// The longest reference clip in milliseconds, when it can be read from the clip (WAV).
551    pub reference_ms: Option<u64>,
552    /// The largest reference clip in bytes.
553    pub reference_bytes: Option<u64>,
554}
555
556impl SpeechNeeds {
557    pub fn new() -> Self {
558        Self::default()
559    }
560
561    pub fn with_preset(mut self, name: impl Into<String>) -> Self {
562        let name = name.into();
563        if !self.presets.contains(&name) {
564            self.presets.push(name);
565        }
566        self.voices = self.voices.saturating_add(1);
567        self
568    }
569
570    pub fn with_design(mut self) -> Self {
571        self.design = true;
572        self.voices = self.voices.saturating_add(1);
573        self
574    }
575
576    pub fn with_instructions(mut self) -> Self {
577        self.instructions = true;
578        self
579    }
580
581    /// A cloned voice; `has_text`: its transcript comes with the clip.
582    pub fn with_clone(mut self, has_text: bool) -> Self {
583        self.clone = Some(self.clone.map_or(has_text, |t| t && has_text));
584        self.voices = self.voices.saturating_add(1);
585        self
586    }
587
588    /// A script whose highest speaker number is `highest`.
589    pub fn with_script(mut self, highest: u8) -> Self {
590        self.speakers = highest.saturating_add(1);
591        self
592    }
593
594    pub fn with_raw(mut self) -> Self {
595        self.raw = true;
596        self
597    }
598
599    pub fn with_speed(mut self) -> Self {
600        self.speed = true;
601        self
602    }
603
604    pub fn with_format(mut self, format: AudioFormat) -> Self {
605        self.format = Some(format);
606        self
607    }
608
609    pub fn with_input_chars(mut self, chars: u32) -> Self {
610        self.input_chars = chars;
611        self
612    }
613
614    pub fn with_reference(mut self, bytes: u64, ms: Option<u64>) -> Self {
615        self.reference_bytes = Some(self.reference_bytes.map_or(bytes, |b| b.max(bytes)));
616        if let Some(ms) = ms {
617            self.reference_ms = Some(self.reference_ms.map_or(ms, |m| m.max(ms)));
618        }
619        self
620    }
621}
622
623/// The length in milliseconds of a WAV file (RIFF, any sample format), from its `fmt ` byte
624/// rate and `data` size; `None` when the bytes are not a readable WAV. Used for the reference
625/// clip's length in [`SpeechNeeds::reference_ms`].
626pub fn wav_duration_ms(bytes: &[u8]) -> Option<u64> {
627    if bytes.len() < 12 || &bytes[0..4] != b"RIFF" || &bytes[8..12] != b"WAVE" {
628        return None;
629    }
630    let mut at = 12usize;
631    let mut byte_rate: Option<u32> = None;
632    while at.checked_add(8)? <= bytes.len() {
633        let id = &bytes[at..at + 4];
634        let size = u32::from_le_bytes(bytes[at + 4..at + 8].try_into().ok()?) as usize;
635        let body = at + 8;
636        if id == b"fmt " {
637            if size < 16 || body.checked_add(16)? > bytes.len() {
638                return None;
639            }
640            byte_rate = Some(u32::from_le_bytes(bytes[body + 8..body + 12].try_into().ok()?));
641        } else if id == b"data" {
642            let rate = byte_rate.filter(|r| *r > 0)?;
643            // A streamed WAV may say 0 or 0xFFFFFFFF; count what is there.
644            let len = if size == 0 || size == u32::MAX as usize || body.saturating_add(size) > bytes.len() { bytes.len() - body } else { size };
645            return Some(len as u64 * 1000 / u64::from(rate));
646        }
647        at = body.checked_add(size)?.checked_add(size & 1)?;
648    }
649    None
650}
651
652#[cfg(test)]
653mod tests {
654    use super::*;
655
656    fn s(v: &[&str]) -> Vec<String> {
657        v.iter().map(|x| x.to_string()).collect()
658    }
659
660    fn qwen_custom() -> SpeechProfile {
661        SpeechProfile::new()
662            .with_presets(s(&["vivian", "ryan", "serena"]))
663            .with_instructions(true)
664            .with_speed(true)
665            .with_streaming(true)
666            .with_languages(s(&["en", "zh", "de"]))
667            .with_formats(vec![AudioFormat::Wav, AudioFormat::Pcm16, AudioFormat::Mp3])
668            .with_sample_rate(24_000)
669            .with_max_input_chars(4000)
670            .with_max_output_seconds(300)
671    }
672
673    fn drama() -> SpeechProfile {
674        SpeechProfile::new()
675            .with_clone(CloneMode::AudioTextRequired)
676            .with_script_speakers(16)
677            .with_max_voices(1)
678            .with_formats(vec![AudioFormat::Wav, AudioFormat::Pcm16])
679            .with_sample_rate(44_100)
680            .with_max_reference_seconds(30)
681            .with_license("fish-audio-community")
682    }
683
684    #[test]
685    fn formats_and_clone_modes_have_wire_names() {
686        for f in AudioFormat::ALL {
687            assert_eq!(AudioFormat::parse(f.as_str()), Some(f));
688            assert_eq!(serde_json::to_value(f).unwrap(), serde_json::json!(f.as_str()));
689        }
690        assert_eq!(AudioFormat::parse("PCM"), Some(AudioFormat::Pcm16));
691        assert_eq!(AudioFormat::parse("aac"), None);
692        assert_eq!(AudioFormat::Pcm16.mime(), "audio/pcm");
693        let modes = [(CloneMode::Audio, "audio"), (CloneMode::AudioAndText, "audio_and_text"), (CloneMode::AudioTextRequired, "audio_text_required")];
694        for (m, name) in modes {
695            assert_eq!(serde_json::to_value(m).unwrap(), serde_json::json!(name));
696        }
697    }
698
699    #[test]
700    fn unset_fields_stay_off_the_wire() {
701        assert_eq!(serde_json::to_value(SpeechProfile::new()).unwrap(), serde_json::json!({}));
702        assert!(SpeechProfile::new().is_unknown());
703        let p = drama();
704        let v = serde_json::to_value(&p).unwrap();
705        assert_eq!(
706            v,
707            serde_json::json!({"clone": "audio_text_required", "script_speakers": 16, "max_voices": 1, "formats": ["wav", "pcm16"],
708                "sample_rate": 44100, "max_reference_seconds": 30, "license": "fish-audio-community"})
709        );
710        assert_eq!(serde_json::from_value::<SpeechProfile>(v).unwrap(), p);
711        assert_eq!(p.default_format(), Some(AudioFormat::Wav));
712    }
713
714    #[test]
715    fn tightest_keeps_what_every_copy_does() {
716        let a = qwen_custom();
717        let b = SpeechProfile::new()
718            .with_presets(s(&["ryan", "vivian", "aiden"]))
719            .with_instructions(false)
720            .with_speed(true)
721            .with_languages(s(&["en", "fr", "zh"]))
722            .with_formats(vec![AudioFormat::Pcm16, AudioFormat::Wav])
723            .with_sample_rate(24_000)
724            .with_max_input_chars(2000)
725            .with_max_reference_bytes(1 << 20);
726        let t = SpeechProfile::tightest(&a, &b);
727        assert_eq!(t.presets, Some(s(&["vivian", "ryan"])));
728        assert!(!t.instructions && t.speed && !t.streaming);
729        assert_eq!(t.languages, Some(s(&["en", "zh"])));
730        assert_eq!(t.formats, [AudioFormat::Wav, AudioFormat::Pcm16]);
731        assert_eq!(
732            (t.sample_rate, t.max_input_chars, t.max_output_seconds, t.max_reference_bytes),
733            (Some(24_000), Some(2000), Some(300), Some(1 << 20))
734        );
735
736        // Features need both; lists and limits one reports are kept.
737        let bare = SpeechProfile::new();
738        let t = SpeechProfile::tightest(&a, &bare);
739        assert_eq!((t.presets, t.speed, t.instructions), (None, false, false));
740        assert_eq!((t.languages, t.formats, t.max_input_chars), (a.languages.clone(), a.formats.clone(), Some(4000)));
741        assert_eq!(SpeechProfile::tightest(&bare, &a).formats, a.formats);
742
743        // Clone modes, speakers, rates and licenses.
744        let mut c = drama();
745        c.clone = Some(CloneMode::Audio);
746        c.script_speakers = Some(4);
747        c.sample_rate = Some(48_000);
748        let t = SpeechProfile::tightest(&drama(), &c);
749        assert_eq!(
750            (t.clone, t.script_speakers, t.sample_rate, t.license.as_deref()),
751            (Some(CloneMode::AudioTextRequired), Some(4), None, Some("fish-audio-community"))
752        );
753        assert_eq!(CloneMode::Audio.tightest(CloneMode::AudioAndText), CloneMode::Audio);
754        assert_eq!(CloneMode::AudioAndText.tightest(CloneMode::AudioAndText), CloneMode::AudioAndText);
755        assert_eq!(SpeechProfile::tightest(&drama(), &SpeechProfile::new()).clone, None);
756        c.license = Some("apache-2.0".into());
757        assert_eq!(SpeechProfile::tightest(&drama(), &c).license, None);
758        assert_eq!(SpeechProfile::tightest(&a, &a), a, "idempotent");
759    }
760
761    #[test]
762    fn operators_narrow_or_fill_but_never_widen() {
763        let engine = qwen_custom().with_max_voices(2);
764        let op = SpeechProfile::new()
765            .with_presets(s(&["vivian"]))
766            .with_languages(s(&["en"]))
767            .with_formats(vec![AudioFormat::Wav])
768            .with_max_input_chars(2000)
769            .with_max_reference_seconds(30)
770            .with_max_voices(1);
771        let n = engine.narrowed_by(&op).unwrap();
772        assert_eq!((n.presets, n.languages, n.formats.clone()), (Some(s(&["vivian"])), Some(s(&["en"])), vec![AudioFormat::Wav]));
773        assert_eq!((n.max_input_chars, n.max_reference_seconds, n.max_output_seconds, n.max_voices), (Some(2000), Some(30), Some(300), Some(1)));
774        assert!(n.instructions && n.speed && n.streaming, "unset operator bools change nothing");
775        assert_eq!(engine.narrowed_by(&SpeechProfile::new()).unwrap(), engine);
776
777        let widen = |op: SpeechProfile, field: &str| {
778            let e = engine.narrowed_by(&op).unwrap_err();
779            assert!(e.starts_with(field), "{e}");
780        };
781        widen(SpeechProfile::new().with_presets(s(&["alloy"])), "presets");
782        widen(SpeechProfile::new().with_languages(s(&["ja"])), "languages");
783        widen(SpeechProfile::new().with_formats(vec![AudioFormat::Opus]), "formats");
784        widen(SpeechProfile::new().with_max_input_chars(5000), "max_input_chars");
785        widen(SpeechProfile::new().with_design(true), "design");
786        widen(SpeechProfile::new().with_raw(true), "raw");
787        widen(SpeechProfile::new().with_clone(CloneMode::Audio), "clone");
788        widen(SpeechProfile::new().with_script_speakers(2), "script_speakers");
789        widen(SpeechProfile::new().with_sample_rate(48_000), "sample_rate");
790        widen(SpeechProfile::new().with_max_voices(3), "max_voices");
791
792        // Filling what the engine doesn't report (not presets: those come from the engine).
793        let quiet = SpeechProfile::new().with_clone(CloneMode::AudioAndText);
794        let n = quiet.narrowed_by(&SpeechProfile::new().with_languages(s(&["en"])).with_max_reference_seconds(30).with_sample_rate(24_000)).unwrap();
795        assert_eq!((n.languages, n.max_reference_seconds, n.sample_rate), (Some(s(&["en"])), Some(30), Some(24_000)));
796        assert!(quiet.narrowed_by(&SpeechProfile::new().with_presets(s(&["a"]))).unwrap_err().starts_with("presets"));
797        // A stricter clone mode narrows; a looser one widens.
798        assert_eq!(
799            quiet.narrowed_by(&SpeechProfile::new().with_clone(CloneMode::AudioTextRequired)).unwrap().clone,
800            Some(CloneMode::AudioTextRequired)
801        );
802        assert!(drama().narrowed_by(&SpeechProfile::new().with_clone(CloneMode::Audio)).unwrap_err().starts_with("clone"));
803        assert!(drama().narrowed_by(&SpeechProfile::new().with_license("mit")).unwrap_err().starts_with("license"));
804    }
805
806    #[test]
807    fn covers_names_what_a_model_lacks() {
808        let q = qwen_custom();
809        assert!(q.covers(&SpeechNeeds::new().with_input_chars(10)).is_ok());
810        assert!(q.covers(&SpeechNeeds::new().with_preset("vivian").with_instructions().with_speed().with_format(AudioFormat::Mp3)).is_ok());
811        let lack = |p: &SpeechProfile, n: SpeechNeeds, what: &str| {
812            let e = p.covers(&n).unwrap_err();
813            assert!(e.contains(what), "{e}");
814        };
815        lack(&q, SpeechNeeds::new().with_preset("alloy"), "no preset voice `alloy` (presets: vivian, ryan, serena)");
816        lack(&drama(), SpeechNeeds::new().with_preset("alloy"), "no preset voices");
817        lack(&q, SpeechNeeds::new().with_design(), "design");
818        lack(&drama(), SpeechNeeds::new().with_instructions(), "instructions");
819        lack(&q, SpeechNeeds::new().with_clone(true), "does not clone voices");
820        lack(&drama(), SpeechNeeds::new().with_clone(false), "transcript");
821        assert!(drama().covers(&SpeechNeeds::new().with_clone(true).with_script(15)).is_ok());
822        lack(&drama(), SpeechNeeds::new().with_script(16), "at most 16 speakers");
823        lack(&q, SpeechNeeds::new().with_script(0), "multi-speaker");
824        lack(&drama(), SpeechNeeds::new().with_clone(true).with_clone(true), "at most 1 voices");
825        lack(&q, SpeechNeeds::new().with_raw(), "raw");
826        lack(&drama(), SpeechNeeds::new().with_speed(), "speed");
827        lack(&q, SpeechNeeds::new().with_format(AudioFormat::Flac), "does not produce `flac` (formats: wav, pcm16, mp3)");
828        lack(&SpeechProfile::new(), SpeechNeeds::new().with_format(AudioFormat::Wav), "reports no output formats");
829        lack(&q, SpeechNeeds::new().with_input_chars(4001), "at most 4000 characters");
830        lack(&drama(), SpeechNeeds::new().with_clone(true).with_reference(10, Some(31_000)), "at most 30 s");
831        assert!(drama().covers(&SpeechNeeds::new().with_clone(true).with_reference(10, None)).is_ok(), "unknown length is the engine's call");
832        lack(&drama().with_max_reference_bytes(100), SpeechNeeds::new().with_clone(true).with_reference(101, None), "at most 100 bytes");
833        // A profile reporting nothing serves only the plainest request.
834        assert!(SpeechProfile::new().covers(&SpeechNeeds::new().with_input_chars(5)).is_ok());
835    }
836
837    #[test]
838    fn wav_lengths_come_from_the_header() {
839        fn wav(rate: u32, channels: u16, samples: u32) -> Vec<u8> {
840            let data = samples * u32::from(channels) * 2;
841            let mut b = b"RIFF".to_vec();
842            b.extend((36 + data).to_le_bytes());
843            b.extend(b"WAVEfmt ");
844            b.extend(16u32.to_le_bytes());
845            b.extend(1u16.to_le_bytes());
846            b.extend(channels.to_le_bytes());
847            b.extend(rate.to_le_bytes());
848            b.extend((rate * u32::from(channels) * 2).to_le_bytes());
849            b.extend((channels * 2).to_le_bytes());
850            b.extend(16u16.to_le_bytes());
851            b.extend(b"LIST");
852            b.extend(3u32.to_le_bytes());
853            b.extend(b"abc\0");
854            b.extend(b"data");
855            b.extend(data.to_le_bytes());
856            b.extend(vec![0u8; data as usize]);
857            b
858        }
859        assert_eq!(wav_duration_ms(&wav(16_000, 1, 24_000)), Some(1500));
860        assert_eq!(wav_duration_ms(&wav(24_000, 2, 12_000)), Some(500));
861        let mut streamed = wav(16_000, 1, 1600);
862        let at = streamed.len() - 3200 - 4;
863        streamed[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
864        assert_eq!(wav_duration_ms(&streamed), Some(100));
865        assert_eq!(wav_duration_ms(b"ID3\x04 not a wav"), None);
866        assert_eq!(wav_duration_ms(&wav(16_000, 1, 10)[..30]), None);
867        assert_eq!(wav_duration_ms(b"RIFF\x00\x00\x00\x00WAVEdata\x10\x00\x00\x00"), None, "data before fmt");
868    }
869}