1use anyhow::Result;
2use async_trait::async_trait;
3use bytes::Bytes;
4use futures::stream::BoxStream;
5use serde::{Deserialize, Serialize};
6use std::collections::HashMap;
7use tokio::sync::mpsc;
8
9mod aliyun;
10mod deepgram;
11mod tencent_cloud;
12mod tencent_cloud_basic;
13
14#[cfg(feature = "offline")]
15mod supertonic;
16
17pub use aliyun::AliyunTtsClient;
18pub use deepgram::DeepegramTtsClient;
19pub use tencent_cloud::TencentCloudTtsClient;
20pub use tencent_cloud_basic::TencentCloudTtsBasicClient;
21
22#[cfg(feature = "offline")]
23pub use supertonic::SupertonicTtsClient;
24
25#[derive(Clone, Default)]
26pub struct SynthesisCommand {
27 pub text: String,
28 pub speaker: Option<String>,
29 pub play_id: Option<String>,
30 pub streaming: bool,
31 pub end_of_stream: bool,
32 pub option: SynthesisOption,
33 pub base64: bool,
34 pub cache_key: Option<String>,
35}
36pub type SynthesisCommandSender = mpsc::UnboundedSender<SynthesisCommand>;
37pub type SynthesisCommandReceiver = mpsc::UnboundedReceiver<SynthesisCommand>;
38
39#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
40pub enum SynthesisType {
41 #[serde(rename = "tencent")]
42 TencentCloud,
43 #[serde(rename = "aliyun")]
44 Aliyun,
45 #[serde(rename = "deepgram")]
46 Deepgram,
47 #[cfg(feature = "offline")]
48 #[serde(rename = "supertonic")]
49 Supertonic,
50 #[serde(rename = "other")]
51 Other(String),
52}
53
54impl std::fmt::Display for SynthesisType {
55 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
56 match self {
57 SynthesisType::TencentCloud => write!(f, "tencent"),
58 SynthesisType::Aliyun => write!(f, "aliyun"),
59 SynthesisType::Deepgram => write!(f, "deepgram"),
60 #[cfg(feature = "offline")]
61 SynthesisType::Supertonic => write!(f, "supertonic"),
62 SynthesisType::Other(provider) => write!(f, "{}", provider),
63 }
64 }
65}
66
67impl<'de> Deserialize<'de> for SynthesisType {
68 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
69 where
70 D: serde::Deserializer<'de>,
71 {
72 let value = String::deserialize(deserializer)?;
73 match value.as_str() {
74 "tencent" => Ok(SynthesisType::TencentCloud),
75 "aliyun" => Ok(SynthesisType::Aliyun),
76 "deepgram" => Ok(SynthesisType::Deepgram),
77 #[cfg(feature = "offline")]
78 "supertonic" => Ok(SynthesisType::Supertonic),
79 _ => Ok(SynthesisType::Other(value)),
80 }
81 }
82}
83
84#[cfg(test)]
85mod tests;
86#[derive(Debug, Clone, Deserialize, Serialize)]
87#[serde(rename_all = "camelCase")]
88#[serde(default)]
89pub struct SynthesisOption {
90 pub samplerate: Option<i32>,
91 pub provider: Option<SynthesisType>,
92 pub speed: Option<f32>,
93 pub app_id: Option<String>,
94 pub secret_id: Option<String>,
95 #[serde(alias = "apiKey")]
96 pub secret_key: Option<String>,
97 pub volume: Option<i32>,
98 pub speaker: Option<String>,
99 pub codec: Option<String>,
100 pub subtitle: Option<bool>,
101 #[serde(alias = "voice")]
102 pub model: Option<String>,
103 pub language: Option<String>,
104 pub emotion: Option<String>,
107 pub endpoint: Option<String>,
108 pub extra: Option<HashMap<String, String>>,
109 pub max_concurrent_tasks: Option<usize>,
110 pub session_id: Option<String>,
111}
112
113impl SynthesisOption {
114 pub fn merge_with(&self, option: Option<SynthesisOption>) -> Self {
115 if let Some(other) = option {
116 Self {
117 samplerate: other.samplerate.or(self.samplerate),
118 provider: other.provider.or(self.provider.clone()),
119 speed: other.speed.or(self.speed),
120 app_id: other.app_id.or(self.app_id.clone()),
121 secret_id: other.secret_id.or(self.secret_id.clone()),
122 secret_key: other.secret_key.or(self.secret_key.clone()),
123 volume: other.volume.or(self.volume),
124 speaker: other.speaker.or(self.speaker.clone()),
125 codec: other.codec.or(self.codec.clone()),
126 subtitle: other.subtitle.or(self.subtitle),
127 model: other.model.or(self.model.clone()),
128 language: other.language.or(self.language.clone()),
129 emotion: other.emotion.or(self.emotion.clone()),
130 endpoint: other.endpoint.or(self.endpoint.clone()),
131 extra: other.extra.or(self.extra.clone()),
132 max_concurrent_tasks: other.max_concurrent_tasks.or(self.max_concurrent_tasks),
133 session_id: other.session_id.or(self.session_id.clone()),
134 }
135 } else {
136 self.clone()
137 }
138 }
139}
140
141#[derive(Debug)]
142pub enum SynthesisEvent {
143 AudioChunk(Bytes),
145 Subtitles(Vec<Subtitle>),
147 Finished,
148}
149
150#[derive(Debug, Clone)]
151pub struct Subtitle {
152 pub text: String,
153 pub begin_time: u32,
154 pub end_time: u32,
155 pub begin_index: u32,
156 pub end_index: u32,
157}
158
159impl Subtitle {
160 pub fn new(
161 text: String,
162 begin_time: u32,
163 end_time: u32,
164 begin_index: u32,
165 end_index: u32,
166 ) -> Self {
167 Self {
168 text,
169 begin_time,
170 end_time,
171 begin_index,
172 end_index,
173 }
174 }
175}
176
177pub fn bytes_size_to_duration(bytes: usize, sample_rate: u32) -> u32 {
179 (500.0 * bytes as f32 / sample_rate as f32) as u32
180}
181
182#[async_trait]
183pub trait SynthesisClient: Send {
184 fn provider(&self) -> SynthesisType;
186
187 async fn start(
190 &mut self,
191 ) -> Result<BoxStream<'static, (Option<usize>, Result<SynthesisEvent>)>>;
192
193 async fn synthesize(
197 &mut self,
198 text: &str,
199 cmd_seq: Option<usize>,
200 option: Option<SynthesisOption>,
201 ) -> Result<()>;
202
203 async fn stop(&mut self) -> Result<()>;
204}
205
206impl Default for SynthesisOption {
207 fn default() -> Self {
208 Self {
209 samplerate: Some(16000),
210 provider: None,
211 speed: Some(1.0),
212 app_id: None,
213 secret_id: None,
214 secret_key: None,
215 volume: Some(5), speaker: None,
217 codec: Some("pcm".to_string()),
218 subtitle: None,
219 model: None,
220 language: None,
221 emotion: None,
222 endpoint: None,
223 extra: None,
224 max_concurrent_tasks: None,
225 session_id: None,
226 }
227 }
228}
229
230impl SynthesisOption {
231 pub fn check_default(&mut self) {
232 if let Some(provider) = &self.provider {
233 match provider.to_string().as_str() {
234 "tencent" | "tencent_basic" => {
235 if self.app_id.is_none() {
236 self.app_id = std::env::var("TENCENT_APPID").ok();
237 }
238 if self.secret_id.is_none() {
239 self.secret_id = std::env::var("TENCENT_SECRET_ID").ok();
240 }
241 if self.secret_key.is_none() {
242 self.secret_key = std::env::var("TENCENT_SECRET_KEY").ok();
243 }
244 }
245 "voiceapi" => {
246 if self.endpoint.is_none() {
248 self.endpoint = std::env::var("VOICEAPI_ENDPOINT")
249 .ok()
250 .or_else(|| Some("http://localhost:8000".to_string()));
251 }
252 if self.speaker.is_none() {
254 self.speaker = std::env::var("VOICEAPI_SPEAKER_ID")
255 .ok()
256 .or_else(|| Some("0".to_string()));
257 }
258 }
259 "aliyun" => {
260 if self.secret_key.is_none() {
261 self.secret_key = std::env::var("DASHSCOPE_API_KEY").ok();
262 }
263 }
264 "deepgram" => {
265 if self.secret_key.is_none() {
266 self.secret_key = std::env::var("DEEPGRAM_API_KEY").ok();
267 }
268 }
269 _ => {}
270 }
271 }
272 }
273}