agentai-audio 0.7.1

Text-to-speech and voice cloning for AgentAI agents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
//! # Fish Audio speech API
//!
//! [`FishAudioProvider`] speaks text with `POST /v1/tts`, creates voices in the Fish Audio
//! account with `POST /model` and lists them with `GET /model`. The model (`s1`, `s2-pro`,
//! `drama-3`, ...) goes in the `model` header. It designs voices from a description with
//! `POST /v1/voice-design`; a preview is kept with `create_voice`, which saves it as a sample.
//!
//! A request may have several voices ([`SpeechRequest::with_voices`]), for models that speak a
//! dialogue (`drama-3` and the S2 family). Their order is the speaker index, and the text marks
//! who speaks with `<|speaker:0|>`, `<|speaker:1|>`, ...; writing those tags is up to you.
//!
//! A voice is the ID of a Fish Audio voice model or, with a [`VoiceStore`] set with
//! [`with_voice_store`](FishAudioProvider::with_voice_store), the ID of a voice in that store:
//! its sample and transcript are then sent with the request (`references`, as MessagePack).
//!
//! With [`SpeechRequest::with_timestamps`] the request goes to
//! `POST /v1/tts/stream/with-timestamp`: the streamed audio chunks are joined and the time of
//! every word is returned in [`SpeechResponse::timestamps`].
//!
//! Fields without an equivalent are not sent: `instructions` is ignored.

use super::{
    AudioError, AudioFormat, SpeechProvider, SpeechRequest, SpeechResponse, Voice, VoiceInfo,
    VoicePreview, VoiceSource, WordTimestamp, audio_media,
};
use crate::voice_store::{StoredVoice, VoiceStore};
use agentai_core::message::Media;
use agentai_core::{HttpClient, HttpRequest, Multipart, ReqwestClient};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
use std::sync::Arc;

/// The Fish Audio API endpoint.
pub const DEFAULT_BASE_URL: &str = "https://api.fish.audio";
/// Environment variable with the API key.
pub const API_KEY_ENV: &str = "FISH_API_KEY";
/// Environment variable with the base URL.
pub const BASE_URL_ENV: &str = "FISH_BASE_URL";

/// Sample rate of PCM audio from Fish Audio.
const PCM_SAMPLE_RATE: u32 = 44_100;

/// Provider for the Fish Audio API.
///
/// ```rust,no_run
/// # use agentai_audio::provider::fishaudio::FishAudioProvider;
/// # use agentai_audio::MemoryVoiceStore;
/// # fn main() -> Result<(), agentai_audio::AudioError> {
/// // From `FISH_API_KEY` and `FISH_BASE_URL`
/// let provider = FishAudioProvider::from_env("drama-3")?;
/// // Or everything in code, with local voice samples
/// let provider = FishAudioProvider::new("drama-3", "key", "https://api.fish.audio")
///     .with_voice_store(MemoryVoiceStore::new());
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct FishAudioProvider {
    model: String,
    api_key: String,
    base_url: String,
    client: Arc<dyn HttpClient>,
    store: Option<Arc<dyn VoiceStore>>,
}

impl std::fmt::Debug for FishAudioProvider {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("FishAudioProvider")
            .field("model", &self.model)
            .field("base_url", &self.base_url)
            .finish_non_exhaustive()
    }
}

impl FishAudioProvider {
    /// Creates a provider for `model` with the API key and base URL given in code, for example
    /// [`DEFAULT_BASE_URL`]. An empty key sends no `Authorization` header, for self-hosted
    /// servers without authentication.
    pub fn new(
        model: impl Into<String>,
        api_key: impl Into<String>,
        base_url: impl Into<String>,
    ) -> Self {
        Self {
            model: model.into(),
            api_key: api_key.into(),
            base_url: base_url.into().trim_end_matches('/').to_string(),
            client: Arc::new(ReqwestClient::new()),
            store: None,
        }
    }

    /// Creates a provider for `model` with the API key from `FISH_API_KEY` and the base URL
    /// from `FISH_BASE_URL`, or [`DEFAULT_BASE_URL`] when it is not set. The key is optional
    /// when `FISH_BASE_URL` is set, for self-hosted servers.
    pub fn from_env(model: impl Into<String>) -> Result<Self, AudioError> {
        Self::from_lookup(model, |name| std::env::var(name).ok())
    }

    fn from_lookup(
        model: impl Into<String>,
        lookup: impl Fn(&str) -> Option<String>,
    ) -> Result<Self, AudioError> {
        let (api_key, base_url) = match (lookup(API_KEY_ENV), lookup(BASE_URL_ENV)) {
            (Some(key), base_url) => (key, base_url),
            (None, Some(base_url)) => (String::new(), Some(base_url)),
            (None, None) => return Err(AudioError::MissingApiKey(API_KEY_ENV)),
        };
        let base_url = base_url.unwrap_or_else(|| DEFAULT_BASE_URL.to_string());
        Ok(Self::new(model, api_key, base_url))
    }

    /// Sets the store of voice samples. A voice ID found in it is sent as its sample and
    /// transcript; other IDs are Fish Audio voice models.
    pub fn with_voice_store(mut self, store: impl VoiceStore) -> Self {
        self.store = Some(Arc::new(store));
        self
    }

    #[cfg(test)]
    pub(crate) fn with_client(mut self, client: Arc<dyn HttpClient>) -> Self {
        self.client = client;
        self
    }

    fn request(&self, request: HttpRequest) -> HttpRequest {
        request.with_bearer_token(&self.api_key)
    }

    /// The voices of a request: its voices, else the default voice.
    async fn speakers(&self, request: &SpeechRequest) -> Result<Vec<Speaker>, AudioError> {
        let voices = match (&request.voices[..], &request.default_voice) {
            ([], Some(voice)) => std::slice::from_ref(voice),
            (voices, _) => voices,
        };
        let mut speakers = Vec::with_capacity(voices.len());
        for voice in voices {
            let Voice::Id(id) = voice;
            let stored = match &self.store {
                Some(store) => store.get(id).await?,
                None => None,
            };
            let reference = match stored {
                Some(voice) => Some(self.reference(voice).await?),
                None => None,
            };
            speakers.push(Speaker {
                id: id.clone(),
                reference,
            });
        }
        Ok(speakers)
    }

    async fn reference(&self, voice: StoredVoice) -> Result<Reference, AudioError> {
        Ok(Reference {
            audio: voice.sample.bytes(&*self.client).await?,
            text: voice.transcript,
        })
    }
}

/// A voice of a request: the ID and, for a voice of the store, its sample.
struct Speaker {
    id: String,
    reference: Option<Reference>,
}

#[derive(Serialize)]
struct Reference {
    #[serde(with = "serde_bytes")]
    audio: Vec<u8>,
    #[serde(skip_serializing_if = "Option::is_none")]
    text: Option<String>,
}

#[derive(Serialize)]
#[serde(untagged)]
enum ReferenceId {
    One(String),
    Many(Vec<String>),
}

#[derive(Serialize)]
#[serde(untagged)]
enum References {
    One(Vec<Reference>),
    Many(Vec<Vec<Reference>>),
}

#[derive(Serialize)]
struct Prosody {
    speed: f64,
}

#[derive(Serialize)]
struct SpeechBody<'a> {
    text: &'a str,
    #[serde(skip_serializing_if = "Option::is_none")]
    reference_id: Option<ReferenceId>,
    #[serde(skip_serializing_if = "Option::is_none")]
    references: Option<References>,
    #[serde(skip_serializing_if = "Option::is_none")]
    format: Option<&'static str>,
    #[serde(skip_serializing_if = "Option::is_none")]
    prosody: Option<Prosody>,
    #[serde(skip_serializing_if = "Option::is_none")]
    language: Option<&'a str>,
}

/// `reference_id` and `references` for the voices of a request.
fn voice_fields(mut speakers: Vec<Speaker>) -> (Option<ReferenceId>, Option<References>) {
    match speakers.len() {
        0 => (None, None),
        1 => {
            let speaker = speakers.remove(0);
            match speaker.reference {
                Some(reference) => (None, Some(References::One(vec![reference]))),
                None => (Some(ReferenceId::One(speaker.id)), None),
            }
        }
        _ => {
            let has_samples = speakers.iter().any(|s| s.reference.is_some());
            let mut ids = Vec::with_capacity(speakers.len());
            let mut references = Vec::with_capacity(speakers.len());
            for speaker in speakers {
                ids.push(speaker.id);
                references.push(speaker.reference.into_iter().collect());
            }
            let references = has_samples.then_some(References::Many(references));
            (Some(ReferenceId::Many(ids)), references)
        }
    }
}

fn format_name(format: AudioFormat) -> Result<&'static str, AudioError> {
    match format {
        AudioFormat::Mp3 => Ok("mp3"),
        AudioFormat::Wav => Ok("wav"),
        AudioFormat::Opus => Ok("opus"),
        AudioFormat::Pcm => Ok("pcm"),
        AudioFormat::Flac => Err(AudioError::Unsupported("FLAC output with Fish Audio")),
        AudioFormat::Aac => Err(AudioError::Unsupported("AAC output with Fish Audio")),
    }
}

#[async_trait]
impl SpeechProvider for FishAudioProvider {
    fn model(&self) -> Option<&str> {
        Some(&self.model)
    }

    async fn generate(&self, request: SpeechRequest) -> Result<SpeechResponse, AudioError> {
        let format = request.format.map(format_name).transpose()?;
        let (reference_id, references) = voice_fields(self.speakers(&request).await?);
        let inline = references.is_some();
        let body = SpeechBody {
            text: &request.text,
            reference_id,
            references,
            format,
            prosody: request.speed.map(|speed| Prosody { speed }),
            language: request.language.as_deref(),
        };
        let path = if request.timestamps {
            "/v1/tts/stream/with-timestamp"
        } else {
            "/v1/tts"
        };
        let mut http = HttpRequest::post(format!("{}{path}", self.base_url));
        if !self.model.is_empty() {
            http = http.with_header("model", self.model.as_str());
        }
        // Samples are sent as binary, which only the MessagePack body takes
        http = if inline {
            let bytes = rmp_serde::to_vec_named(&body)
                .map_err(|e| AudioError::InvalidRequest(e.to_string()))?;
            http.with_header("Content-Type", "application/msgpack")
                .with_body(bytes)
        } else {
            http.with_json(&body)?
        };
        let response = self
            .client
            .send(self.request(http))
            .await?
            .error_for_status()?;
        let format = request.format.unwrap_or(AudioFormat::Mp3);
        let (mut audio, timestamps) = if request.timestamps {
            let (bytes, timestamps) = parse_timestamp_stream(&response.body)?;
            if bytes.is_empty() {
                return Err(AudioError::InvalidResponse(
                    "the response has no audio".to_string(),
                ));
            }
            (
                Media::from_bytes(format.content_type(), bytes),
                Some(timestamps),
            )
        } else {
            (audio_media(&response, format.content_type())?, None)
        };
        audio.name = request.name;
        let mut result = SpeechResponse::new(audio);
        if format == AudioFormat::Pcm {
            result = result.with_sample_rate(PCM_SAMPLE_RATE);
        }
        if let Some(timestamps) = timestamps {
            result = result.with_timestamps(timestamps);
        }
        Ok(result)
    }

    fn supports_voice_cloning(&self) -> bool {
        true
    }

    /// Creates a voice model in the Fish Audio account with `POST /model` (fast training, so
    /// it can speak at once) and returns its ID. Without `transcript` Fish Audio transcribes
    /// the samples itself.
    async fn create_voice(
        &self,
        name: &str,
        source: VoiceSource,
        description: Option<&str>,
    ) -> Result<String, AudioError> {
        let VoiceSource::Samples {
            samples,
            transcript,
        } = source
        else {
            return Err(AudioError::Unsupported("saving a designed voice"));
        };
        let transcript = transcript.as_deref();
        if samples.is_empty() {
            return Err(AudioError::InvalidRequest(
                "voice cloning needs at least one sample".to_string(),
            ));
        }
        let mut form = Multipart::new()
            .with_text("type", "tts")
            .with_text("train_mode", "fast")
            .with_text("title", name);
        if let Some(description) = description {
            form = form.with_text("description", description);
        }
        if let Some(transcript) = transcript {
            form = form.with_text("texts", transcript);
        }
        for (index, sample) in samples.iter().enumerate() {
            let bytes = sample.bytes(&*self.client).await?;
            let filename = sample.file_name(&format!("sample-{}", index + 1));
            form = form.with_file("voices", filename, sample.content_type.as_str(), bytes);
        }
        let http = HttpRequest::post(format!("{}/model", self.base_url)).with_multipart(form);
        let response = self
            .client
            .send(self.request(http))
            .await?
            .error_for_status()?;
        let created: ModelEntry = response
            .json()
            .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
        Ok(created.id)
    }

    fn supports_voice_design(&self) -> bool {
        true
    }

    /// Designs voices with `POST /v1/voice-design` (model `voice-design-1`). The previews have
    /// no ID: keep one by sending its audio to `create_voice`.
    async fn design_voice(
        &self,
        description: &str,
        text: Option<&str>,
        count: usize,
    ) -> Result<Vec<VoicePreview>, AudioError> {
        let body = VoiceDesignBody {
            instruction: description,
            reference_text: text,
            n: count,
        };
        let http = HttpRequest::post(format!("{}/v1/voice-design", self.base_url))
            .with_header("model", "voice-design-1")
            .with_json(&body)?;
        let response = self
            .client
            .send(self.request(http))
            .await?
            .error_for_status()?;
        let designed: VoiceDesignResponse = response
            .json()
            .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
        designed
            .candidates
            .into_iter()
            .map(|candidate| {
                let bytes = agentai_core::base64::decode(&candidate.audio_base64)
                    .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
                let audio = Media::from_bytes(audio_type(&bytes), &bytes);
                let preview = VoicePreview::new(audio).with_sample_rate(candidate.sample_rate);
                Ok(match candidate.text.as_deref().or(text) {
                    Some(text) => preview.with_text(text),
                    None => preview,
                })
            })
            .collect()
    }

    /// Lists the voice models of the account with `GET /model?self=true`, page by page, and
    /// then the voices of the voice store, if one is set.
    async fn list_voices(&self) -> Result<Vec<VoiceInfo>, AudioError> {
        let mut voices = Vec::new();
        for page_number in 1.. {
            let url = format!(
                "{}/model?self=true&page_size=100&page_number={page_number}",
                self.base_url
            );
            let response = self
                .client
                .send(self.request(HttpRequest::get(url)))
                .await?
                .error_for_status()?;
            let page: ModelPage = response
                .json()
                .map_err(|e| AudioError::InvalidResponse(e.to_string()))?;
            let empty = page.items.is_empty();
            voices.extend(page.items.into_iter().map(|model| {
                let info = VoiceInfo::new(model.id, model.title).with_cloned(true);
                match model.description.filter(|d| !d.is_empty()) {
                    Some(description) => info.with_description(description),
                    None => info,
                }
            }));
            let done = empty
                || page.has_more == Some(false)
                || page.total.is_some_and(|total| voices.len() >= total);
            if done {
                break;
            }
        }
        if let Some(store) = &self.store {
            voices.extend(store.list().await?.into_iter().map(|(id, voice)| {
                let mut info = VoiceInfo::new(id, voice.name).with_cloned(true);
                info.description = voice.description;
                info
            }));
        }
        Ok(voices)
    }
}

/// The body of `POST /v1/voice-design`.
#[derive(Serialize)]
struct VoiceDesignBody<'a> {
    instruction: &'a str,
    reference_text: Option<&'a str>,
    n: usize,
}

#[derive(Deserialize)]
struct VoiceDesignResponse {
    candidates: Vec<Candidate>,
}

#[derive(Deserialize)]
struct Candidate {
    audio_base64: String,
    sample_rate: u32,
    text: Option<String>,
}

/// The response names no audio type, so it is read from the first bytes (WAV or MP3).
fn audio_type(bytes: &[u8]) -> &'static str {
    let mp3 = bytes.starts_with(b"ID3")
        || (bytes.first() == Some(&0xFF) && bytes.get(1).is_some_and(|b| b & 0xE0 == 0xE0));
    if mp3 { "audio/mpeg" } else { "audio/wav" }
}

/// An event of `/v1/tts/stream/with-timestamp`.
#[derive(Deserialize)]
struct TimestampEvent {
    #[serde(default)]
    audio_base64: String,
    alignment: Option<Alignment>,
    #[serde(default)]
    chunk_seq: u64,
    #[serde(default)]
    chunk_audio_offset_sec: f64,
}

#[derive(Deserialize)]
struct Alignment {
    #[serde(default)]
    segments: Vec<Segment>,
}

#[derive(Deserialize)]
struct Segment {
    text: String,
    start: f64,
    end: f64,
}

/// The audio and word times of a `/v1/tts/stream/with-timestamp` response (server-sent
/// events). Audio chunks are joined in order; the alignment of a text chunk is a snapshot that
/// a later one replaces, with times relative to the chunk's offset.
fn parse_timestamp_stream(body: &[u8]) -> Result<(Vec<u8>, Vec<WordTimestamp>), AudioError> {
    let invalid = |message: String| AudioError::InvalidResponse(message);
    let body = std::str::from_utf8(body).map_err(|e| invalid(e.to_string()))?;
    let mut audio = Vec::new();
    let mut alignments = BTreeMap::new();
    for line in body.lines() {
        let Some(data) = line.strip_prefix("data:") else {
            continue;
        };
        // Only JSON objects are events; skip anything else, such as a `[DONE]` sentinel
        let Ok(serde_json::Value::Object(object)) = serde_json::from_str(data.trim()) else {
            continue;
        };
        if !object.contains_key("audio_base64")
            && let Some(message) = object.get("message").or(object.get("error"))
        {
            let message = message
                .as_str()
                .map_or_else(|| message.to_string(), String::from);
            return Err(invalid(format!("error event in the stream: {message}")));
        }
        let event: TimestampEvent =
            serde_json::from_value(object.into()).map_err(|e| invalid(e.to_string()))?;
        audio.extend(
            agentai_core::base64::decode(&event.audio_base64)
                .map_err(|e| invalid(e.to_string()))?,
        );
        if let Some(alignment) = event.alignment {
            alignments.insert(event.chunk_seq, (event.chunk_audio_offset_sec, alignment));
        }
    }
    let timestamps = alignments
        .into_values()
        .flat_map(|(offset, alignment)| {
            alignment.segments.into_iter().map(move |segment| {
                WordTimestamp::new(segment.text, segment.start + offset, segment.end + offset)
            })
        })
        .collect();
    Ok((audio, timestamps))
}

#[derive(Deserialize)]
struct ModelPage {
    #[serde(default)]
    items: Vec<ModelEntry>,
    total: Option<usize>,
    has_more: Option<bool>,
}

#[derive(Deserialize)]
struct ModelEntry {
    #[serde(rename = "_id")]
    id: String,
    #[serde(default)]
    title: String,
    description: Option<String>,
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::MemoryVoiceStore;
    use agentai_core::HttpResponse;
    use agentai_core::mock::{MockHttp, body_json, json_response};
    use serde_json::{Value, json};

    fn provider(http: &MockHttp) -> FishAudioProvider {
        FishAudioProvider::new("drama-3", "key", "https://api.test/")
            .with_client(Arc::new(http.clone()))
    }

    fn audio() -> HttpResponse {
        HttpResponse::new(200, b"audio".to_vec())
    }

    async fn store_with_sample() -> MemoryVoiceStore {
        let store = MemoryVoiceStore::new();
        let voice = StoredVoice::new("Ala", Media::from_bytes("audio/wav", b"WAV"))
            .with_transcript("Hello there.");
        assert_eq!(store.save(voice).await.unwrap(), "voice-1");
        store
    }

    /// The MessagePack body as JSON, with `bin` as `{"bin": [bytes]}`.
    fn msgpack(request: &HttpRequest) -> Value {
        fn to_json(value: rmpv::Value) -> Value {
            match value {
                rmpv::Value::Binary(data) => json!({ "bin": data }),
                rmpv::Value::Array(items) => items.into_iter().map(to_json).collect(),
                rmpv::Value::Map(entries) => entries
                    .into_iter()
                    .map(|(k, v)| (k.as_str().unwrap().to_string(), to_json(v)))
                    .collect::<serde_json::Map<_, _>>()
                    .into(),
                rmpv::Value::String(s) => json!(s.as_str().unwrap()),
                other => panic!("unexpected MessagePack value {other}"),
            }
        }
        assert_eq!(request.header("content-type"), Some("application/msgpack"));
        let mut body = request.body.as_deref().unwrap();
        to_json(rmpv::decode::read_value(&mut body).unwrap())
    }

    fn bytes(data: &[u8]) -> Value {
        json!({ "bin": data })
    }

    #[tokio::test]
    async fn a_sample_id_is_unsupported() {
        let http = MockHttp::new(vec![]);
        let err = provider(&http)
            .create_voice("a", VoiceSource::SampleId("g1".into()), None)
            .await
            .unwrap_err();
        assert!(matches!(err, AudioError::Unsupported(_)));
        assert_eq!(http.request_count(), 0);
    }

    #[tokio::test]
    async fn generate_sends_one_model_voice_as_json() {
        let http = MockHttp::new(vec![audio()]);
        let r = provider(&http)
            .generate(
                SpeechRequest::new("hi")
                    .with_voice(Voice::id("abc"))
                    .with_format(AudioFormat::Pcm)
                    .with_speed(1.2)
                    .with_language("pl")
                    .with_instructions("ignored")
                    .with_name("hi.pcm"),
            )
            .await
            .unwrap();
        let req = http.request(0);
        assert_eq!(req.url, "https://api.test/v1/tts");
        assert_eq!(req.header("authorization"), Some("Bearer key"));
        assert_eq!(req.header("model"), Some("drama-3"));
        assert_eq!(
            body_json(&req),
            json!({
                "text": "hi", "reference_id": "abc", "format": "pcm",
                "prosody": {"speed": 1.2}, "language": "pl"
            })
        );
        assert_eq!(r.audio.content_type, "audio/pcm");
        assert_eq!(r.audio.name.as_deref(), Some("hi.pcm"));
        assert_eq!(r.sample_rate, Some(44_100));
    }

    #[tokio::test]
    async fn timestamps_join_the_audio_and_offset_the_words() {
        let event = |audio: &[u8], seq: u64, offset: f64, alignment: Value| {
            let audio = agentai_core::base64::encode(audio);
            let event = json!({
                "audio_base64": audio, "content": "x", "alignment": alignment,
                "chunk_seq": seq, "chunk_audio_offset_sec": offset
            });
            format!("data: {event}\n\n")
        };
        let words = |list: &[(&str, f64, f64)]| {
            let segments: Vec<Value> = list
                .iter()
                .map(|(text, start, end)| json!({"text": text, "start": start, "end": end}))
                .collect();
            json!({"audio_duration": 1.0, "segments": segments})
        };
        let body = [
            ": keep-alive\n\n".to_string(),
            event(b"AB", 0, 0.0, Value::Null),
            event(b"CD", 0, 0.0, words(&[("Hi", 0.0, 0.25)])),
            event(b"", 0, 0.0, words(&[("Hi", 0.0, 0.5), ("there", 0.5, 1.0)])),
            event(b"EF", 1, 1.5, Value::Null),
            event(b"", 1, 1.5, words(&[("Bye", 0.25, 0.75)])),
            "data: [DONE]\n\n".to_string(),
        ]
        .concat();
        let http = MockHttp::new(vec![HttpResponse::new(200, body)]);
        let r = provider(&http)
            .generate(
                SpeechRequest::new("Hi there. Bye")
                    .with_voice(Voice::id("abc"))
                    .with_format(AudioFormat::Opus)
                    .with_timestamps(true),
            )
            .await
            .unwrap();
        let req = http.request(0);
        assert_eq!(req.url, "https://api.test/v1/tts/stream/with-timestamp");
        assert_eq!(body_json(&req)["reference_id"], "abc");
        assert_eq!(r.audio, Media::from_bytes("audio/ogg", b"ABCDEF"));
        assert_eq!(
            r.timestamps.unwrap(),
            [
                WordTimestamp::new("Hi", 0.0, 0.5),
                WordTimestamp::new("there", 0.5, 1.0),
                WordTimestamp::new("Bye", 1.75, 2.25),
            ]
        );
    }

    #[tokio::test]
    async fn an_error_event_fails_the_timestamp_stream() {
        let body = "data: {\"audio_base64\": \"QUI=\", \"chunk_seq\": 0}\n\n\
                    data: {\"status\": 503, \"message\": \"server overloaded\"}\n\n";
        let http = MockHttp::new(vec![HttpResponse::new(200, body)]);
        let err = provider(&http)
            .generate(SpeechRequest::new("hi").with_timestamps(true))
            .await
            .unwrap_err();
        assert!(
            matches!(&err, AudioError::InvalidResponse(m) if m.contains("server overloaded")),
            "{err}"
        );
    }

    #[tokio::test]
    async fn the_default_voice_is_used_without_voices() {
        let http = MockHttp::new(vec![audio(), audio()]);
        let p = provider(&http);
        p.generate(SpeechRequest::new("hi").with_default_voice(Voice::id("d")))
            .await
            .unwrap();
        assert_eq!(body_json(&http.request(0))["reference_id"], "d");
        p.generate(SpeechRequest::new("hi")).await.unwrap();
        assert_eq!(body_json(&http.request(1)), json!({"text": "hi"}));
    }

    #[tokio::test]
    async fn several_model_voices_are_a_list_in_order() {
        let http = MockHttp::new(vec![audio()]);
        provider(&http)
            .generate(
                SpeechRequest::new("<|speaker:0|>Hi<|speaker:1|>Hello")
                    .with_default_voice(Voice::id("unused"))
                    .with_voices(vec![Voice::id("b"), Voice::id("a")]),
            )
            .await
            .unwrap();
        assert_eq!(
            body_json(&http.request(0)),
            json!({"text": "<|speaker:0|>Hi<|speaker:1|>Hello", "reference_id": ["b", "a"]})
        );
    }

    #[tokio::test]
    async fn one_stored_voice_is_sent_as_its_sample() {
        let http = MockHttp::new(vec![audio()]);
        provider(&http)
            .with_voice_store(store_with_sample().await)
            .generate(SpeechRequest::new("hi").with_voice(Voice::id("voice-1")))
            .await
            .unwrap();
        assert_eq!(
            msgpack(&http.request(0)),
            json!({
                "text": "hi",
                "references": [{"audio": bytes(b"WAV"), "text": "Hello there."}]
            })
        );
    }

    #[tokio::test]
    async fn stored_and_model_voices_are_one_speaker_each() {
        let http = MockHttp::new(vec![audio()]);
        provider(&http)
            .with_voice_store(store_with_sample().await)
            .generate(
                SpeechRequest::new("dialogue")
                    .with_voice(Voice::id("model-a"))
                    .with_voice(Voice::id("voice-1")),
            )
            .await
            .unwrap();
        assert_eq!(
            msgpack(&http.request(0)),
            json!({
                "text": "dialogue",
                "reference_id": ["model-a", "voice-1"],
                "references": [[], [{"audio": bytes(b"WAV"), "text": "Hello there."}]]
            })
        );
    }

    #[tokio::test]
    async fn unsupported_formats_send_nothing() {
        let http = MockHttp::new(vec![]);
        let p = provider(&http);
        for format in [AudioFormat::Flac, AudioFormat::Aac] {
            let err = p
                .generate(SpeechRequest::new("hi").with_format(format))
                .await
                .unwrap_err();
            assert!(matches!(err, AudioError::Unsupported(_)));
        }
        assert_eq!(http.request_count(), 0);
    }

    #[tokio::test]
    async fn create_voice_creates_a_model() {
        let http = MockHttp::new(vec![json_response(
            201,
            json!({"_id": "m1", "title": "Adam", "state": "trained"}),
        )]);
        let samples = vec![
            Media::from_bytes("audio/wav", b"ONE").with_name("a.wav"),
            Media::from_bytes("audio/mpeg", b"TWO"),
        ];
        let id = provider(&http)
            .create_voice(
                "Adam",
                VoiceSource::samples(samples.clone(), Some("Said text.")),
                Some("my voice"),
            )
            .await
            .unwrap();
        assert_eq!(id, "m1");

        let request = http.request(0);
        assert_eq!(request.url, "https://api.test/model");
        assert_eq!(request.header("authorization"), Some("Bearer key"));
        let boundary = request
            .header("content-type")
            .unwrap()
            .strip_prefix("multipart/form-data; boundary=")
            .unwrap();
        let body = String::from_utf8(request.body.clone().unwrap()).unwrap();
        let field = |name: &str, value: &str| {
            format!("Content-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n")
        };
        let file = |filename: &str, content_type: &str, data: &str| {
            format!(
                "Content-Disposition: form-data; name=\"voices\"; filename=\"{filename}\"\r\n\
                 Content-Type: {content_type}\r\n\r\n{data}\r\n"
            )
        };
        let parts: Vec<&str> = body
            .split(&format!("--{boundary}"))
            .map(|part| part.trim_start_matches("\r\n"))
            .collect();
        assert_eq!(
            parts,
            [
                "",
                &field("type", "tts"),
                &field("train_mode", "fast"),
                &field("title", "Adam"),
                &field("description", "my voice"),
                &field("texts", "Said text."),
                &file("a.wav", "audio/wav", "ONE"),
                &file("sample-2.mp3", "audio/mpeg", "TWO"),
                "--\r\n",
            ]
        );
    }

    #[tokio::test]
    async fn list_voices_reads_every_page_and_the_store() {
        let http = MockHttp::new(vec![
            json_response(
                200,
                json!({"total": 2, "has_more": true,
                       "items": [{"_id": "m1", "title": "A", "description": ""}]}),
            ),
            json_response(
                200,
                json!({"total": 2, "items": [{"_id": "m2", "title": "B", "description": "d"}]}),
            ),
        ]);
        let voices = provider(&http)
            .with_voice_store(store_with_sample().await)
            .list_voices()
            .await
            .unwrap();
        assert_eq!(
            http.request(0).url,
            "https://api.test/model?self=true&page_size=100&page_number=1"
        );
        assert!(http.request(1).url.ends_with("&page_number=2"));
        assert_eq!(
            voices,
            [
                VoiceInfo::new("m1", "A").with_cloned(true),
                VoiceInfo::new("m2", "B")
                    .with_description("d")
                    .with_cloned(true),
                VoiceInfo::new("voice-1", "Ala").with_cloned(true),
            ]
        );
    }

    #[tokio::test]
    async fn design_voice_posts_the_instruction() {
        let enc = |b: &[u8]| agentai_core::base64::encode(b);
        let http = MockHttp::new(vec![json_response(
            200,
            json!({"candidates": [
                {"id": "c1", "index": 0, "audio_base64": enc(b"RIFF\0\0\0\0WAVEfmt "),
                 "sample_rate": 44100, "duration_ms": 900, "text": "Hello"},
                {"id": "c2", "index": 1, "audio_base64": enc(b"ID3\x04rest"),
                 "sample_rate": 44100, "duration_ms": 800}
            ]}),
        )]);
        let previews = provider(&http)
            .design_voice("warm low voice", Some("Hello"), 2)
            .await
            .unwrap();
        let req = http.request(0);
        assert_eq!(req.url, "https://api.test/v1/voice-design");
        assert_eq!(req.header("model"), Some("voice-design-1"));
        assert_eq!(req.header("authorization"), Some("Bearer key"));
        assert_eq!(
            body_json(&req),
            json!({"instruction": "warm low voice", "reference_text": "Hello", "n": 2})
        );
        assert_eq!(previews[0].audio.content_type, "audio/wav");
        assert_eq!(
            previews[0].audio.bytes(&http).await.unwrap(),
            b"RIFF\0\0\0\0WAVEfmt "
        );
        assert_eq!(previews[0].text.as_deref(), Some("Hello"));
        assert_eq!(previews[0].sample_rate, Some(44_100));
        assert_eq!(previews[0].sample_id, None);
        assert_eq!(previews[1].audio.content_type, "audio/mpeg");
        assert_eq!(previews[1].text.as_deref(), Some("Hello"));
    }

    #[tokio::test]
    async fn design_voice_detects_the_audio_type() {
        let enc = |b: &[u8]| agentai_core::base64::encode(b);
        let http = MockHttp::new(vec![json_response(
            200,
            json!({"candidates": [
                {"audio_base64": enc(b"\xff\xfb\x90\x00"), "sample_rate": 24000},
                {"audio_base64": enc(b"OggS\0\0\0\0\0\0\0\0"), "sample_rate": 24000}
            ]}),
        )]);
        let previews = provider(&http).design_voice("x", None, 1).await.unwrap();
        assert_eq!(
            body_json(&http.request(0)),
            json!({"instruction": "x", "reference_text": null, "n": 1})
        );
        assert_eq!(previews[0].audio.content_type, "audio/mpeg");
        assert_eq!(previews[1].audio.content_type, "audio/wav");
        assert_eq!(previews[1].sample_rate, Some(24_000));
        assert_eq!(previews[1].text, None);
    }
}