1use anyhow::Result;
2use rsipstack::dialog::{authenticate::Credential, invitation::InviteOption};
3use serde::{Deserialize, Serialize};
4use serde_with::skip_serializing_none;
5use std::collections::HashMap;
6
7use crate::{
8 media::{
9 agc::AGCOption, ambiance::AmbianceOption, recorder::RecorderOption,
10 track::media_pass::MediaPassOption, vad::VADOption,
11 },
12 synthesis::SynthesisOption,
13 transcription::TranscriptionOption,
14};
15
16pub mod app;
17pub mod call;
18pub mod callrecord;
19pub mod config;
20pub mod event;
21pub mod handler;
22pub mod locator;
23pub mod main_builder;
24pub mod media;
25pub mod net_tool;
26
27#[cfg(feature = "offline")]
28pub mod offline;
29
30pub mod playbook;
31pub mod sip_util;
32pub mod sipflow;
33pub mod synthesis;
34pub mod transcription;
35pub mod useragent;
36
37#[derive(Debug, Deserialize, Serialize, Default, Clone)]
38#[serde(default)]
39pub struct SipOption {
40 pub username: Option<String>,
41 pub password: Option<String>,
42 pub realm: Option<String>,
43 pub contact: Option<String>,
44 pub headers: Option<HashMap<String, String>>,
45 pub hangup_headers: Option<HashMap<String, String>>,
46 pub extract_headers: Option<Vec<String>>,
47 pub enable_srtp: Option<bool>,
48}
49
50#[skip_serializing_none]
51#[derive(Debug, Deserialize, Serialize, Clone)]
52#[serde(rename_all = "camelCase")]
53pub struct CallOption {
54 pub denoise: Option<bool>,
55 pub agc: Option<AGCOption>,
56 pub offer: Option<String>,
57 pub callee: Option<String>,
58 pub caller: Option<String>,
59 pub recorder: Option<RecorderOption>,
60 pub vad: Option<VADOption>,
61 pub asr: Option<TranscriptionOption>,
62 pub tts: Option<SynthesisOption>,
63 pub media_pass: Option<MediaPassOption>,
64 pub handshake_timeout: Option<u64>,
66 pub enable_ipv6: Option<bool>,
67 pub inactivity_timeout: Option<u64>, pub rtp_timeout: Option<u64>,
70 pub sip: Option<SipOption>,
71 pub extra: Option<HashMap<String, String>>,
72 pub codec: Option<String>, pub ambiance: Option<AmbianceOption>,
74 pub eou: Option<EouOption>,
75 pub realtime: Option<RealtimeOption>,
76 pub subscribe: Option<bool>,
77 pub enable_ice_lite: Option<bool>,
78 pub ringback_detection: Option<RingbackDetectionOption>,
79}
80
81impl Default for CallOption {
82 fn default() -> Self {
83 Self {
84 denoise: None,
85 agc: None,
86 offer: None,
87 callee: None,
88 caller: None,
89 recorder: None,
90 asr: None,
91 vad: None,
92 tts: None,
93 media_pass: None,
94 handshake_timeout: None,
95 inactivity_timeout: Some(50), rtp_timeout: None,
97 enable_ipv6: None,
98 sip: None,
99 extra: None,
100 codec: None,
101 ambiance: None,
102 eou: None,
103 realtime: None,
104 subscribe: None,
105 enable_ice_lite: None,
106 ringback_detection: None,
107 }
108 }
109}
110
111impl CallOption {
112 pub fn check_default(&mut self) {
113 if let Some(tts) = &mut self.tts {
114 tts.check_default();
115 }
116 if let Some(asr) = &mut self.asr {
117 asr.check_default();
118 }
119 if let Some(realtime) = &mut self.realtime {
120 realtime.check_default();
121 }
122 }
123
124 pub fn build_invite_option(&self) -> Result<InviteOption> {
125 let mut invite_option = InviteOption::default();
126 if let Some(offer) = &self.offer {
127 invite_option.offer = Some(offer.clone().into());
128 }
129 if let Some(callee) = &self.callee {
130 invite_option.callee = callee.clone().try_into()?;
131 }
132 let caller_uri = if let Some(caller) = &self.caller {
133 crate::sip_util::ensure_sip_scheme(caller.clone())
135 } else if let Some(username) = self.sip.as_ref().and_then(|sip| sip.username.as_ref()) {
136 let domain = self
139 .sip
140 .as_ref()
141 .and_then(|sip| sip.realm.as_ref())
142 .map(|s| s.as_str())
143 .unwrap_or("127.0.0.1");
144 format!("sip:{}@{}", username, domain)
145 } else {
146 "sip:active-call@127.0.0.1".to_string()
148 };
149 invite_option.caller = caller_uri.try_into()?;
150
151 if let Some(sip) = &self.sip {
152 invite_option.credential = Some(Credential {
153 username: sip.username.clone().unwrap_or_default(),
154 auth_username: None,
155 password: sip.password.clone().unwrap_or_default(),
156 realm: sip.realm.clone(),
157 });
158 invite_option.headers = sip
159 .headers
160 .as_ref()
161 .map(crate::sip_util::sip_headers_from_map);
162 sip.contact.as_ref().map(|c| match c.clone().try_into() {
163 Ok(u) => {
164 invite_option.contact = u;
165 }
166 Err(_) => {}
167 });
168 }
169 Ok(invite_option)
170 }
171}
172
173#[skip_serializing_none]
174#[derive(Debug, Deserialize, Serialize, Clone)]
175#[serde(rename_all = "camelCase")]
176pub struct ReferOption {
177 pub denoise: Option<bool>,
178 pub agc: Option<AGCOption>,
179 pub timeout: Option<u32>,
180 pub moh: Option<String>,
181 pub vad: Option<VADOption>,
182 pub asr: Option<TranscriptionOption>,
183 pub auto_hangup: Option<bool>,
185 pub sip: Option<SipOption>,
186 pub call_id: Option<String>,
187 pub pause_parent_asr: Option<bool>,
189 pub forward_dtmf: Option<bool>,
191 pub extra_headers: Option<HashMap<String, String>>,
194}
195
196#[skip_serializing_none]
197#[derive(Clone, Debug, Deserialize, Serialize, Default)]
198#[serde(rename_all = "camelCase")]
199pub struct EouOption {
200 pub r#type: Option<String>,
201 pub endpoint: Option<String>,
202 #[serde(alias = "apiKey")]
203 pub secret_key: Option<String>,
204 pub secret_id: Option<String>,
205 pub timeout: Option<u32>,
207 pub extra: Option<HashMap<String, String>>,
208}
209
210#[skip_serializing_none]
211#[derive(Clone, Debug, Deserialize, Serialize, Default)]
212#[serde(rename_all = "camelCase")]
213pub struct RingbackDetectionOption {
214 pub enabled: Option<bool>,
215 pub model_weights_path: Option<String>,
217 pub min_buffer_secs: Option<f32>,
219 pub detection_interval_secs: Option<f32>,
221 pub confidence_threshold: Option<f32>,
223 pub on_state_change_only: Option<bool>,
225 pub sliding_window_size: Option<usize>,
227 pub final_confidence_threshold: Option<f32>,
229}
230
231#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
232pub enum RealtimeType {
233 #[serde(rename = "openai")]
234 OpenAI,
235 #[serde(rename = "azure")]
236 Azure,
237 Other(String),
238}
239
240impl<'de> Deserialize<'de> for RealtimeType {
241 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
242 where
243 D: serde::Deserializer<'de>,
244 {
245 let value = String::deserialize(deserializer)?;
246 match value.as_str() {
247 "openai" => Ok(RealtimeType::OpenAI),
248 "azure" => Ok(RealtimeType::Azure),
249 _ => Ok(RealtimeType::Other(value)),
250 }
251 }
252}
253
254#[skip_serializing_none]
255#[derive(Clone, Debug, Deserialize, Serialize, Default)]
256#[serde(rename_all = "camelCase")]
257pub struct RealtimeOption {
258 pub provider: Option<RealtimeType>,
259 pub model: Option<String>,
260 #[serde(alias = "apiKey")]
261 pub secret_key: Option<String>,
262 pub secret_id: Option<String>,
263 pub endpoint: Option<String>,
264 pub turn_detection: Option<serde_json::Value>,
265 pub tools: Option<Vec<serde_json::Value>>,
266 pub extra: Option<HashMap<String, String>>,
267}
268
269impl RealtimeOption {
270 pub fn check_default(&mut self) {
271 if self.secret_key.is_none() {
272 self.secret_key = std::env::var("OPENAI_API_KEY").ok();
273 }
274 }
275}
276
277pub type Spawner = fn(
278 std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
279) -> tokio::task::JoinHandle<()>;
280static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
281
282pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
283 EXTERNAL_SPAWNER.set(spawner)
284}
285
286pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
287where
288 F: std::future::Future<Output = ()> + Send + 'static,
289{
290 if let Some(spawner) = EXTERNAL_SPAWNER.get() {
291 spawner(Box::pin(future))
292 } else {
293 tokio::spawn(future)
294 }
295}
296
297#[cfg(test)]
298mod rtp_timeout_tests {
299 use super::CallOption;
300 use crate::call::Command;
301
302 #[test]
303 fn rtp_timeout_is_optional_and_shared_by_invite_and_accept() {
304 assert_eq!(CallOption::default().rtp_timeout, None);
305 assert!(
306 serde_json::to_value(CallOption::default())
307 .unwrap()
308 .get("rtpTimeout")
309 .is_none()
310 );
311 for command in ["invite", "accept"] {
312 for (option, expected) in [
313 (serde_json::json!({}), None),
314 (serde_json::json!({"rtpTimeout": null}), None),
315 (serde_json::json!({"rtpTimeout": 0}), Some(0)),
316 (serde_json::json!({"rtpTimeout": 30}), Some(30)),
317 ] {
318 let parsed: Command = serde_json::from_value(serde_json::json!({
319 "command": command, "option": option,
320 }))
321 .unwrap();
322 match parsed {
323 Command::Invite { option } | Command::Accept { option } => {
324 assert_eq!(option.rtp_timeout, expected);
325 }
326 _ => unreachable!(),
327 }
328 }
329 }
330 }
331}