1use super::{SynthesisClient, SynthesisEvent, SynthesisOption, SynthesisType};
2use anyhow::{Context, Result, bail, ensure};
3use async_trait::async_trait;
4use base64::{Engine, prelude::BASE64_STANDARD};
5use bytes::Bytes;
6use futures::{StreamExt, stream::BoxStream};
7use serde_json::{Value, json};
8use std::{io::Cursor, time::Duration};
9use tokio::sync::mpsc;
10
11const ENDPOINT: &str = "https://api.60db.ai/tts-synthesize";
12const MAX_RESPONSE_BYTES: usize = 32 * 1024 * 1024;
13type Command = (String, Option<usize>, SynthesisOption);
14
15pub struct SixtyDBTtsClient {
16 option: SynthesisOption,
17 streaming: bool,
18 client: reqwest::Client,
19 tx: Option<mpsc::UnboundedSender<Command>>,
20}
21
22impl SixtyDBTtsClient {
23 pub fn create(streaming: bool, option: &SynthesisOption) -> Result<Box<dyn SynthesisClient>> {
24 let mut option = option.clone();
25 option.check_default();
26 validate(&option)?;
27 let client = reqwest::Client::builder()
28 .timeout(Duration::from_secs(60))
29 .redirect(reqwest::redirect::Policy::none())
30 .build()?;
31 Ok(Box::new(Self {
32 option,
33 streaming,
34 client,
35 tx: None,
36 }))
37 }
38}
39
40fn validate(option: &SynthesisOption) -> Result<()> {
41 ensure!(
42 option
43 .secret_key
44 .as_deref()
45 .is_some_and(|s| !s.trim().is_empty()),
46 "60db TTS requires an API key"
47 );
48 let voice = option
49 .speaker
50 .as_deref()
51 .context("60db TTS requires a speaker from GET /voices")?;
52 uuid::Uuid::parse_str(voice).context("60db TTS speaker must be a voice UUID")?;
53 ensure!(
54 matches!(option.samplerate.unwrap_or(16000), 16000 | 24000 | 48000),
55 "60db TTS supports 16000, 24000 or 48000 Hz"
56 );
57 ensure!(
58 matches!(option.codec.as_deref().unwrap_or("pcm"), "pcm" | "linear16"),
59 "60db TTS requires PCM16 output"
60 );
61 let speed = option.speed.unwrap_or(1.0);
62 ensure!(
63 speed.is_finite() && (0.5..=2.0).contains(&speed),
64 "60db TTS speed must be between 0.5 and 2.0"
65 );
66 let url = reqwest::Url::parse(option.endpoint.as_deref().unwrap_or(ENDPOINT))
67 .context("Invalid 60db TTS endpoint")?;
68 ensure!(
69 matches!(url.scheme(), "http" | "https")
70 && url.username().is_empty()
71 && url.password().is_none(),
72 "Invalid 60db TTS endpoint"
73 );
74 Ok(())
75}
76
77fn decode_audio(encoded: &str, rate: i32) -> Result<Bytes> {
78 let mut bytes = BASE64_STANDARD
79 .decode(encoded)
80 .context("Invalid 60db audio base64")?;
81 if bytes.first() == Some(&b'{') {
82 let inner: Value = serde_json::from_slice(&bytes).context("Invalid 60db audio wrapper")?;
83 let audio = inner
84 .get("result")
85 .unwrap_or(&inner)
86 .get("audioContent")
87 .and_then(Value::as_str)
88 .context("Missing 60db wrapped audio")?;
89 bytes = BASE64_STANDARD
90 .decode(audio)
91 .context("Invalid 60db wrapped audio base64")?;
92 }
93 if bytes.starts_with(b"RIFF") {
94 ensure!(bytes.len() >= 12, "Invalid 60db WAV header");
95 let declared = u32::from_le_bytes(bytes[4..8].try_into()?) as usize;
96 ensure!(
97 declared.checked_add(8) == Some(bytes.len()),
98 "Invalid 60db WAV length"
99 );
100 let mut wav = hound::WavReader::new(Cursor::new(bytes)).context("Invalid 60db WAV")?;
101 let spec = wav.spec();
102 ensure!(
103 spec.channels == 1
104 && spec.bits_per_sample == 16
105 && spec.sample_format == hound::SampleFormat::Int
106 && spec.sample_rate == rate as u32,
107 "60db WAV must match mono PCM16 at the configured sample rate"
108 );
109 bytes = wav
110 .samples::<i16>()
111 .collect::<std::result::Result<Vec<_>, _>>()?
112 .into_iter()
113 .flat_map(i16::to_le_bytes)
114 .collect();
115 }
116 ensure!(
117 !bytes.is_empty() && bytes.len() % 2 == 0,
118 "60db returned invalid PCM16 audio"
119 );
120 ensure!(
121 !bytes.starts_with(b"ID3") && !bytes.starts_with(b"OggS") && !bytes.starts_with(b"fLaC"),
122 "60db returned compressed audio instead of PCM16"
123 );
124 Ok(Bytes::from(bytes))
125}
126
127fn parse_record(record: &[u8], rate: i32) -> Result<Option<Bytes>> {
128 let value: Value = serde_json::from_slice(record).context("Invalid 60db JSON response")?;
129 ensure!(
130 value.get("success") != Some(&Value::Bool(false))
131 && value.get("type").and_then(Value::as_str) != Some("error")
132 && value.get("error").is_none_or(Value::is_null),
133 "60db TTS synthesis failed"
134 );
135 let result = value
136 .get("backendResponse")
137 .or_else(|| value.get("result"))
138 .unwrap_or(&value);
139 ensure!(
140 result.get("success") != Some(&Value::Bool(false))
141 && result.get("error").is_none_or(Value::is_null),
142 "60db TTS synthesis failed"
143 );
144 for metadata in [&value, result] {
145 if let Some(actual) = metadata.get("sample_rate").and_then(Value::as_i64) {
146 ensure!(
147 actual == rate as i64,
148 "60db returned an unexpected sample rate"
149 );
150 }
151 for key in ["encoding", "output_format"] {
152 if let Some(encoding) = metadata.get(key).and_then(Value::as_str) {
153 ensure!(
154 matches!(
155 encoding.to_ascii_lowercase().as_str(),
156 "linear16" | "pcm" | "pcm16" | "wav"
157 ),
158 "60db returned an unsupported audio format"
159 );
160 }
161 }
162 }
163 match result
164 .get("audioContent")
165 .or_else(|| result.get("audio_base64"))
166 {
167 Some(Value::String(audio)) if !audio.is_empty() => Ok(Some(decode_audio(audio, rate)?)),
168 Some(Value::String(_)) | None => Ok(None),
169 _ => bail!("Invalid 60db audio field"),
170 }
171}
172
173fn check(condition: bool, message: &str) -> Result<()> {
174 ensure!(condition, "{}", message);
175 Ok(())
176}
177
178fn audio_stream(
179 client: reqwest::Client,
180 option: SynthesisOption,
181 text: String,
182) -> BoxStream<'static, Result<SynthesisEvent>> {
183 Box::pin(async_stream::try_stream! {
184 validate(&option)?;
185 check(!text.trim().is_empty() && text.chars().count() <= 5000, "60db TTS text must contain 1 to 5000 characters")?;
186 let rate = option.samplerate.unwrap_or(16000);
187 let mut payload = json!({
188 "text": text,
189 "voice_id": option.speaker,
190 "audio_config": {"audio_encoding": "LINEAR16", "sample_rate_hertz": rate},
191 "speed": option.speed.unwrap_or(1.0),
192 "timestamp_type": "NONE"
193 });
194 if let Some(language) = &option.language { payload["target_language"] = json!(language); }
195 let response = client.post(option.endpoint.as_deref().unwrap_or(ENDPOINT))
196 .bearer_auth(option.secret_key.as_deref().unwrap_or_default())
197 .json(&payload).send().await.map_err(|_| anyhow::anyhow!("60db TTS request failed"))?;
198 check(response.status().is_success(), &format!("60db TTS returned HTTP {}", response.status().as_u16()))?;
199 let content_type = response.headers().get(reqwest::header::CONTENT_TYPE)
200 .and_then(|v| v.to_str().ok()).unwrap_or("").to_ascii_lowercase();
201 let ndjson = content_type.contains("ndjson") || content_type.contains("jsonl");
202 let binary = content_type.contains("audio/wav") || content_type.contains("audio/x-wav") || content_type.contains("audio/pcm") || content_type.contains("application/octet-stream");
203 check(ndjson || binary || content_type.contains("json"), "60db TTS returned an unsupported content type")?;
204 let mut stream = response.bytes_stream();
205 let mut pending = Vec::new();
206 let mut total = 0usize;
207 let mut emitted = false;
208 while let Some(chunk) = stream.next().await {
209 let chunk = chunk.map_err(|_| anyhow::anyhow!("60db TTS response interrupted"))?;
210 total = total.checked_add(chunk.len()).context("60db response size overflow")?;
211 check(total <= MAX_RESPONSE_BYTES, "60db TTS response exceeds size limit")?;
212 pending.extend_from_slice(&chunk);
213 if ndjson {
214 while let Some(end) = pending.iter().position(|b| *b == b'\n') {
215 let record: Vec<_> = pending.drain(..=end).collect();
216 if record.iter().all(u8::is_ascii_whitespace) { continue; }
217 if let Some(audio) = parse_record(&record, rate)? {
218 emitted = true;
219 yield SynthesisEvent::AudioChunk(audio);
220 }
221 }
222 }
223 }
224 if binary {
225 check(!pending.is_empty(), "60db TTS returned no audio")?;
226 let audio = decode_audio(&BASE64_STANDARD.encode(&pending), rate)?;
227 emitted = true;
228 yield SynthesisEvent::AudioChunk(audio);
229 } else {
230 let audio = if pending.iter().all(u8::is_ascii_whitespace) {
231 None
232 } else {
233 parse_record(&pending, rate)?
234 };
235 if let Some(audio) = audio {
236 emitted = true;
237 yield SynthesisEvent::AudioChunk(audio);
238 }
239 }
240 check(emitted, "60db TTS returned no audio")?;
241 })
242}
243
244#[async_trait]
245impl SynthesisClient for SixtyDBTtsClient {
246 fn provider(&self) -> SynthesisType {
247 SynthesisType::SixtyDB
248 }
249
250 async fn start(
251 &mut self,
252 ) -> Result<BoxStream<'static, (Option<usize>, Result<SynthesisEvent>)>> {
253 ensure!(self.tx.is_none(), "60db TTS client is already started");
254 let (tx, mut rx) = mpsc::unbounded_channel::<Command>();
255 self.tx = Some(tx);
256 let client = self.client.clone();
257 let streaming = self.streaming;
258 Ok(Box::pin(async_stream::stream! {
259 let mut failed = false;
260 while let Some((text, seq, option)) = rx.recv().await {
261 let mut audio = audio_stream(client.clone(), option, text);
262 let mut command_failed = false;
263 while let Some(event) = audio.next().await {
264 if event.is_err() { command_failed = true; failed = true; }
265 yield (seq, event);
266 }
267 if !streaming && !command_failed { yield (seq, Ok(SynthesisEvent::Finished)); }
268 }
269 if streaming && !failed { yield (None, Ok(SynthesisEvent::Finished)); }
270 }))
271 }
272
273 async fn synthesize(
274 &mut self,
275 text: &str,
276 cmd_seq: Option<usize>,
277 option: Option<SynthesisOption>,
278 ) -> Result<()> {
279 let option = self.option.merge_with(option);
280 validate(&option)?;
281 ensure!(
282 option.samplerate.unwrap_or(16000) == self.option.samplerate.unwrap_or(16000),
283 "60db TTS sample rate cannot change within a track"
284 );
285 self.tx
286 .as_ref()
287 .context("60db TTS client is not started")?
288 .send((text.to_owned(), cmd_seq, option))
289 .map_err(|_| anyhow::anyhow!("60db TTS stream closed"))?;
290 Ok(())
291 }
292
293 async fn stop(&mut self) -> Result<()> {
294 self.tx.take();
296 Ok(())
297 }
298}
299
300#[cfg(test)]
301mod tests {
302 use super::*;
303 use wiremock::{
304 Mock, MockServer, ResponseTemplate,
305 matchers::{body_json, header, method, path},
306 };
307
308 const VOICE: &str = "038cf0d1-eef8-45a6-81b0-99c5e57a33d2";
309
310 fn option(endpoint: String) -> SynthesisOption {
311 SynthesisOption {
312 provider: Some(SynthesisType::SixtyDB),
313 secret_key: Some("local-test-token".into()),
314 speaker: Some(VOICE.into()),
315 endpoint: Some(endpoint),
316 ..Default::default()
317 }
318 }
319
320 #[tokio::test]
321 async fn http_contract_order_and_stream_completion() {
322 let server = MockServer::start().await;
323 for text in ["First.", "Second."] {
324 Mock::given(method("POST"))
325 .and(path("/tts-synthesize"))
326 .and(header("authorization", "Bearer local-test-token"))
327 .and(body_json(json!({"text": text, "voice_id": VOICE,
328 "audio_config": {"audio_encoding": "LINEAR16", "sample_rate_hertz": 16000},
329 "speed": 1.0, "timestamp_type": "NONE"})))
330 .respond_with(ResponseTemplate::new(200).set_body_json(json!({
331 "success": true, "audio_base64": BASE64_STANDARD.encode([1, 0, 2, 0]),
332 "sample_rate": 16000, "encoding": "LINEAR16"
333 })))
334 .expect(1)
335 .mount(&server)
336 .await;
337 }
338 let mut client =
339 SixtyDBTtsClient::create(true, &option(format!("{}/tts-synthesize", server.uri())))
340 .unwrap();
341 let mut events = client.start().await.unwrap();
342 client.synthesize("First.", None, None).await.unwrap();
343 client.synthesize("Second.", None, None).await.unwrap();
344 client.stop().await.unwrap();
345 let mut audio_count = 0;
346 let mut finish_count = 0;
347 while let Some((seq, event)) = events.next().await {
348 assert_eq!(seq, None);
349 match event.unwrap() {
350 SynthesisEvent::AudioChunk(bytes) => {
351 assert_eq!(bytes.as_ref(), &[1, 0, 2, 0]);
352 audio_count += 1;
353 }
354 SynthesisEvent::Finished => {
355 assert_eq!(audio_count, 2);
356 finish_count += 1;
357 }
358 _ => panic!("unexpected subtitles"),
359 }
360 }
361 assert_eq!((audio_count, finish_count), (2, 1));
362 }
363
364 #[tokio::test]
365 async fn ndjson_wrapped_audio_and_command_sequences() {
366 let server = MockServer::start().await;
367 let wrapped = BASE64_STANDARD.encode(
368 serde_json::to_vec(
369 &json!({"result": {"audioContent": BASE64_STANDARD.encode([1, 0])}}),
370 )
371 .unwrap(),
372 );
373 let body = format!(
374 "{}\n{}",
375 json!({"type":"meta"}),
376 json!({"result":{"audioContent":wrapped}})
377 );
378 Mock::given(method("POST"))
379 .respond_with(ResponseTemplate::new(200).set_body_raw(body, "application/x-ndjson"))
380 .expect(2)
381 .mount(&server)
382 .await;
383 let mut client = SixtyDBTtsClient::create(false, &option(server.uri())).unwrap();
384 let mut events = client.start().await.unwrap();
385 client.synthesize("First.", Some(0), None).await.unwrap();
386 client.synthesize("Second.", Some(1), None).await.unwrap();
387 client.stop().await.unwrap();
388 let mut completed = Vec::new();
389 let mut audio_count = 0;
390 while let Some((seq, event)) = events.next().await {
391 match event.unwrap() {
392 SynthesisEvent::AudioChunk(bytes) => {
393 assert_eq!(bytes.as_ref(), &[1, 0]);
394 assert_eq!(seq, Some(audio_count));
395 audio_count += 1;
396 }
397 SynthesisEvent::Finished => completed.push(seq),
398 _ => panic!("unexpected event"),
399 }
400 }
401 assert_eq!(completed, [Some(0), Some(1)]);
402 }
403
404 #[test]
405 fn reject_errors_invalid_audio_and_wrong_rate() {
406 for record in [
407 json!({"success":false,"message":"private text"}),
408 json!({"type":"error"}),
409 json!({"backendResponse":{"success":false}}),
410 json!({"audio_base64":"%%%"}),
411 json!({"audio_base64":BASE64_STANDARD.encode([1])}),
412 json!({"audio_base64":BASE64_STANDARD.encode([1,0]),"sample_rate":24000}),
413 json!({"audio_base64":BASE64_STANDARD.encode([1,0]),"encoding":"mp3"}),
414 ] {
415 let error = parse_record(&serde_json::to_vec(&record).unwrap(), 16000).unwrap_err();
416 assert!(!error.to_string().contains("private text"));
417 }
418 assert!(parse_record(b"not JSON", 16000).is_err());
419 }
420
421 #[test]
422 fn wav_decode_and_provider_serialization() {
423 let mut buffer = Cursor::new(Vec::new());
424 {
425 let mut writer = hound::WavWriter::new(
426 &mut buffer,
427 hound::WavSpec {
428 channels: 1,
429 sample_rate: 16000,
430 bits_per_sample: 16,
431 sample_format: hound::SampleFormat::Int,
432 },
433 )
434 .unwrap();
435 writer.write_sample(123i16).unwrap();
436 writer.write_sample(-456i16).unwrap();
437 writer.finalize().unwrap();
438 }
439 let encoded = BASE64_STANDARD.encode(buffer.into_inner());
440 assert_eq!(
441 decode_audio(&encoded, 16000).unwrap().as_ref(),
442 &[123, 0, 56, 254]
443 );
444 assert!(decode_audio(&encoded, 24000).is_err());
445 let mut trailing = BASE64_STANDARD.decode(&encoded).unwrap();
446 trailing.extend([0, 0]);
447 assert!(decode_audio(&BASE64_STANDARD.encode(trailing), 16000).is_err());
448 let provider: SynthesisType = serde_json::from_str("\"60db\"").unwrap();
449 assert_eq!(provider, SynthesisType::SixtyDB);
450 assert_eq!(serde_json::to_string(&provider).unwrap(), "\"60db\"");
451 }
452
453 #[tokio::test]
454 async fn engine_registration_and_validation() {
455 let server = MockServer::start().await;
456 let config = option(server.uri());
457 let mut client = crate::media::engine::StreamEngine::default()
458 .create_tts_client(false, &config)
459 .await
460 .unwrap();
461 assert_eq!(client.provider(), SynthesisType::SixtyDB);
462 let events = client.start().await.unwrap();
463 let mut invalid = config.clone();
464 invalid.samplerate = Some(24000);
465 assert!(
466 client
467 .synthesize("text", Some(0), Some(invalid))
468 .await
469 .is_err()
470 );
471 drop(events);
472 assert!(client.synthesize("text", Some(0), None).await.is_err());
473 for rate in [0, 8000, -1] {
474 let mut invalid = config.clone();
475 invalid.samplerate = Some(rate);
476 assert!(SixtyDBTtsClient::create(false, &invalid).is_err());
477 }
478 }
479}
480
481#[cfg(test)]
482mod transport_tests {
483 use super::*;
484 use wiremock::{Mock, MockServer, ResponseTemplate, matchers::method};
485
486 fn option(endpoint: String) -> SynthesisOption {
487 SynthesisOption {
488 provider: Some(SynthesisType::SixtyDB),
489 secret_key: Some("local-test-token".into()),
490 speaker: Some("038cf0d1-eef8-45a6-81b0-99c5e57a33d2".into()),
491 endpoint: Some(endpoint),
492 ..Default::default()
493 }
494 }
495
496 #[tokio::test]
497 async fn http_errors_and_empty_response_never_finish_successfully() {
498 for response in [
499 ResponseTemplate::new(401).set_body_string("local-test-token"),
500 ResponseTemplate::new(200).set_body_json(json!({"success":true})),
501 ResponseTemplate::new(200)
502 .set_body_raw("{\"type\":\"error\"}\n", "application/x-ndjson"),
503 ] {
504 let server = MockServer::start().await;
505 Mock::given(method("POST"))
506 .respond_with(response)
507 .expect(1)
508 .mount(&server)
509 .await;
510 let mut client = SixtyDBTtsClient::create(false, &option(server.uri())).unwrap();
511 let mut events = client.start().await.unwrap();
512 client.synthesize("text", Some(0), None).await.unwrap();
513 client.stop().await.unwrap();
514 let mut errors = 0;
515 while let Some((_, event)) = events.next().await {
516 let error = event.unwrap_err();
517 assert!(!error.to_string().contains("local-test-token"));
518 errors += 1;
519 }
520 assert_eq!(errors, 1);
521 }
522 }
523
524 #[tokio::test]
525 async fn fragmented_ndjson_and_inflight_cancellation_close_the_socket() {
526 use tokio::{
527 io::{AsyncReadExt, AsyncWriteExt},
528 net::TcpListener,
529 };
530 let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
531 let endpoint = format!("http://{}", listener.local_addr().unwrap());
532 let server = tokio::spawn(async move {
533 let (mut socket, _) = listener.accept().await.unwrap();
534 let mut request = Vec::new();
535 let mut buffer = [0; 1024];
536 loop {
537 let size = socket.read(&mut buffer).await.unwrap();
538 assert!(size > 0);
539 request.extend_from_slice(&buffer[..size]);
540 if let Some(end) = request.windows(4).position(|w| w == b"\r\n\r\n") {
541 let headers = String::from_utf8_lossy(&request[..end]).to_ascii_lowercase();
542 let length: usize = headers
543 .lines()
544 .find_map(|line| line.strip_prefix("content-length:"))
545 .unwrap()
546 .trim()
547 .parse()
548 .unwrap();
549 if request.len() >= end + 4 + length {
550 break;
551 }
552 }
553 }
554 socket.write_all(b"HTTP/1.1 200 OK\r\nContent-Type: application/x-ndjson\r\nContent-Length: 5000\r\n\r\n{\"result\":{\"audio").await.unwrap();
555 tokio::time::sleep(Duration::from_millis(20)).await;
556 socket
557 .write_all(b"Content\":\"AQACAA==\"}}\n")
558 .await
559 .unwrap();
560 let size = tokio::time::timeout(Duration::from_secs(3), socket.read(&mut buffer))
561 .await
562 .unwrap()
563 .unwrap();
564 assert_eq!(
565 size, 0,
566 "dropping the response must close its incomplete HTTP body"
567 );
568 });
569 let mut client = SixtyDBTtsClient::create(true, &option(endpoint)).unwrap();
570 let mut events = client.start().await.unwrap();
571 client.synthesize("text", None, None).await.unwrap();
572 client.stop().await.unwrap();
573 let event = tokio::time::timeout(Duration::from_secs(3), events.next())
574 .await
575 .unwrap()
576 .unwrap()
577 .1
578 .unwrap();
579 match event {
580 SynthesisEvent::AudioChunk(bytes) => assert_eq!(bytes.as_ref(), &[1, 0, 2, 0]),
581 _ => panic!("expected PCM"),
582 }
583 drop(events);
584 server.await.unwrap();
585 }
586
587 #[tokio::test]
588 async fn binary_pcm_response() {
589 let server = MockServer::start().await;
590 Mock::given(method("POST"))
591 .respond_with(ResponseTemplate::new(200).set_body_raw(vec![1, 0, 2, 0], "audio/pcm"))
592 .expect(1)
593 .mount(&server)
594 .await;
595 let mut client = SixtyDBTtsClient::create(false, &option(server.uri())).unwrap();
596 let mut events = client.start().await.unwrap();
597 client.synthesize("text", Some(0), None).await.unwrap();
598 client.stop().await.unwrap();
599 match events.next().await.unwrap().1.unwrap() {
600 SynthesisEvent::AudioChunk(bytes) => assert_eq!(bytes.as_ref(), &[1, 0, 2, 0]),
601 _ => panic!("expected PCM"),
602 }
603 assert!(matches!(
604 events.next().await.unwrap().1.unwrap(),
605 SynthesisEvent::Finished
606 ));
607 assert!(events.next().await.is_none());
608 }
609}