1use serde::{Deserialize, Serialize};
19
20use crate::gguf::GgufHeader;
21
22pub const FISH_AUDIO_COMMUNITY: &str = "fish-audio-community";
27
28const QWEN3_TTS_RATE: u32 = 24_000;
30const KOKORO_RATE: u32 = 24_000;
31const VOXCPM2_RATE: u32 = 48_000;
32const DRAMA3_RATE: u32 = 44_100;
33const LLAMA_REFERENCE_SECONDS: u32 = 30;
35const DRAMA3_SPEAKERS: u8 = 16;
37
38#[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 pub const ALL: [AudioFormat; 5] = [AudioFormat::Wav, AudioFormat::Pcm16, AudioFormat::Mp3, AudioFormat::Opus, AudioFormat::Flac];
55
56 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 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#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
91#[serde(rename_all = "snake_case")]
92#[non_exhaustive]
93pub enum CloneMode {
94 Audio,
96 AudioAndText,
98 AudioTextRequired,
100}
101
102#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
105#[non_exhaustive]
106pub struct SpeechProfile {
107 #[serde(default, skip_serializing_if = "Option::is_none")]
110 pub presets: Option<Vec<String>>,
111 #[serde(default, skip_serializing_if = "is_false")]
113 pub design: bool,
114 #[serde(default, skip_serializing_if = "is_false")]
116 pub instructions: bool,
117 #[serde(default, skip_serializing_if = "Option::is_none")]
119 pub clone: Option<CloneMode>,
120 #[serde(default, skip_serializing_if = "Option::is_none")]
122 pub script_speakers: Option<u8>,
123 #[serde(default, skip_serializing_if = "Option::is_none")]
125 pub max_voices: Option<u8>,
126 #[serde(default, skip_serializing_if = "is_false")]
128 pub raw: bool,
129 #[serde(default, skip_serializing_if = "is_false")]
131 pub speed: bool,
132 #[serde(default, skip_serializing_if = "is_false")]
134 pub streaming: bool,
135 #[serde(default, skip_serializing_if = "Option::is_none")]
137 pub languages: Option<Vec<String>>,
138 #[serde(default, skip_serializing_if = "Vec::is_empty")]
140 pub formats: Vec<AudioFormat>,
141 #[serde(default, skip_serializing_if = "Option::is_none")]
143 pub sample_rate: Option<u32>,
144 #[serde(default, skip_serializing_if = "Option::is_none")]
146 pub max_input_chars: Option<u32>,
147 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub max_reference_seconds: Option<u32>,
150 #[serde(default, skip_serializing_if = "Option::is_none")]
152 pub max_reference_bytes: Option<u64>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub max_output_seconds: Option<u32>,
156 #[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 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 pub fn is_unknown(&self) -> bool {
259 *self == Self::default()
260 }
261
262 pub fn default_format(&self) -> Option<AudioFormat> {
264 self.formats.first().copied()
265 }
266
267 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
294pub(crate) fn llama_server() -> SpeechProfile {
297 SpeechProfile::new().with_formats([AudioFormat::Wav, AudioFormat::Pcm16]).with_streaming(true)
298}
299
300pub(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
309pub(crate) const QWEN3_TTS_LANGUAGES: [&str; 10] = ["zh", "en", "de", "it", "pt", "es", "ja", "ko", "fr", "ru"];
311pub(crate) const KOKORO_LANGUAGES: [&str; 2] = ["en-us", "en-gb"];
313
314pub 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
389const 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
392pub 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 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 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 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 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 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 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 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 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 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 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 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}