1use serde::{Deserialize, Serialize};
25
26#[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 pub const ALL: [AudioFormat; 5] = [AudioFormat::Wav, AudioFormat::Pcm16, AudioFormat::Mp3, AudioFormat::Opus, AudioFormat::Flac];
43
44 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 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92#[non_exhaustive]
93pub enum CloneMode {
94 Audio,
97 AudioAndText,
99 AudioTextRequired,
101}
102
103impl CloneMode {
104 pub fn needs_text(&self) -> bool {
106 *self == CloneMode::AudioTextRequired
107 }
108
109 pub fn uses_text(&self) -> bool {
111 matches!(self, CloneMode::AudioAndText | CloneMode::AudioTextRequired)
112 }
113
114 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 match self {
128 CloneMode::Audio | CloneMode::AudioAndText => 0,
129 CloneMode::AudioTextRequired => 1,
130 }
131 }
132}
133
134#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
136#[non_exhaustive]
137pub struct SpeechProfile {
138 #[serde(default, skip_serializing_if = "Option::is_none")]
141 pub presets: Option<Vec<String>>,
142 #[serde(default, skip_serializing_if = "is_false")]
144 pub design: bool,
145 #[serde(default, skip_serializing_if = "is_false")]
147 pub instructions: bool,
148 #[serde(default, skip_serializing_if = "Option::is_none")]
150 pub clone: Option<CloneMode>,
151 #[serde(default, skip_serializing_if = "Option::is_none")]
153 pub script_speakers: Option<u8>,
154 #[serde(default, skip_serializing_if = "Option::is_none")]
156 pub max_voices: Option<u8>,
157 #[serde(default, skip_serializing_if = "is_false")]
159 pub raw: bool,
160 #[serde(default, skip_serializing_if = "is_false")]
162 pub speed: bool,
163 #[serde(default, skip_serializing_if = "is_false")]
165 pub streaming: bool,
166 #[serde(default, skip_serializing_if = "Option::is_none")]
168 pub languages: Option<Vec<String>>,
169 #[serde(default, skip_serializing_if = "Vec::is_empty")]
171 pub formats: Vec<AudioFormat>,
172 #[serde(default, skip_serializing_if = "Option::is_none")]
174 pub sample_rate: Option<u32>,
175 #[serde(default, skip_serializing_if = "Option::is_none")]
177 pub max_input_chars: Option<u32>,
178 #[serde(default, skip_serializing_if = "Option::is_none")]
180 pub max_reference_seconds: Option<u32>,
181 #[serde(default, skip_serializing_if = "Option::is_none")]
183 pub max_reference_bytes: Option<u64>,
184 #[serde(default, skip_serializing_if = "Option::is_none")]
186 pub max_output_seconds: Option<u32>,
187 #[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 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 pub fn is_unknown(&self) -> bool {
301 *self == Self::default()
302 }
303
304 pub fn default_format(&self) -> Option<AudioFormat> {
306 self.formats.first().copied()
307 }
308
309 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 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 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#[derive(Debug, Clone, PartialEq, Eq, Default)]
528#[non_exhaustive]
529pub struct SpeechNeeds {
530 pub presets: Vec<String>,
532 pub design: bool,
534 pub instructions: bool,
536 pub clone: Option<bool>,
538 pub speakers: u8,
540 pub voices: u8,
542 pub raw: bool,
544 pub speed: bool,
546 pub format: Option<AudioFormat>,
548 pub input_chars: u32,
550 pub reference_ms: Option<u64>,
552 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 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 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
623pub 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 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 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 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 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 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 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}