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, monitor::MonitorOption,
10 recorder::RecorderOption, 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 runtime;
32pub mod sip_util;
33pub mod sipflow;
34pub mod synthesis;
35pub mod transcription;
36pub mod useragent;
37
38#[derive(Deserialize, Serialize, Default, Clone)]
39#[serde(default)]
40pub struct SipOption {
41 pub username: Option<String>,
42 #[serde(skip_serializing)]
43 pub password: Option<String>,
44 pub realm: Option<String>,
45 pub contact: Option<String>,
46 pub headers: Option<HashMap<String, String>>,
47 pub hangup_headers: Option<HashMap<String, String>>,
48 pub extract_headers: Option<Vec<String>>,
49 pub enable_srtp: Option<bool>,
50}
51
52impl std::fmt::Debug for SipOption {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 f.debug_struct("SipOption")
55 .field("username", &self.username)
56 .field("password", &self.password.as_ref().map(|_| "***"))
57 .field("realm", &self.realm)
58 .field("contact", &self.contact)
59 .field("headers", &self.headers)
60 .field("hangup_headers", &self.hangup_headers)
61 .field("extract_headers", &self.extract_headers)
62 .field("enable_srtp", &self.enable_srtp)
63 .finish()
64 }
65}
66
67#[skip_serializing_none]
68#[derive(Debug, Deserialize, Serialize, Clone)]
69#[serde(rename_all = "camelCase")]
70pub struct CallOption {
71 pub denoise: Option<bool>,
72 pub agc: Option<AGCOption>,
73 pub offer: Option<String>,
74 pub callee: Option<String>,
75 pub caller: Option<String>,
76 pub recorder: Option<RecorderOption>,
77 pub vad: Option<VADOption>,
78 pub asr: Option<TranscriptionOption>,
79 pub tts: Option<SynthesisOption>,
80 pub media_pass: Option<MediaPassOption>,
81 pub handshake_timeout: Option<u64>,
83 pub enable_ipv6: Option<bool>,
84 pub inactivity_timeout: Option<u64>, pub rtp_timeout: Option<u64>,
87 pub jitter_buffer: Option<bool>,
92 pub sip: Option<SipOption>,
93 pub extra: Option<HashMap<String, String>>,
94 pub codec: Option<String>, pub ambiance: Option<AmbianceOption>,
96 pub eou: Option<EouOption>,
97 pub realtime: Option<RealtimeOption>,
98 pub subscribe: Option<bool>,
99 pub monitor: Option<MonitorOption>,
102 pub enable_ice_lite: Option<bool>,
103 pub ringback_detection: Option<RingbackDetectionOption>,
104}
105
106impl Default for CallOption {
107 fn default() -> Self {
108 Self {
109 denoise: None,
110 agc: None,
111 offer: None,
112 callee: None,
113 caller: None,
114 recorder: None,
115 asr: None,
116 vad: None,
117 tts: None,
118 media_pass: None,
119 handshake_timeout: None,
120 inactivity_timeout: Some(50), rtp_timeout: None,
122 jitter_buffer: None,
123 enable_ipv6: None,
124 sip: None,
125 extra: None,
126 codec: None,
127 ambiance: None,
128 eou: None,
129 realtime: None,
130 subscribe: None,
131 monitor: None,
132 enable_ice_lite: None,
133 ringback_detection: None,
134 }
135 }
136}
137
138impl CallOption {
139 pub fn check_default(&mut self) {
140 if let Some(tts) = &mut self.tts {
141 tts.check_default();
142 }
143 if let Some(asr) = &mut self.asr {
144 asr.check_default();
145 }
146 if let Some(realtime) = &mut self.realtime {
147 realtime.check_default();
148 }
149 }
150
151 pub fn build_invite_option(&self) -> Result<InviteOption> {
152 let mut invite_option = InviteOption::default();
153 if let Some(offer) = &self.offer {
154 invite_option.offer = Some(offer.clone().into());
155 }
156 if let Some(callee) = &self.callee {
157 invite_option.callee = callee.clone().try_into()?;
158 }
159 let caller_uri = if let Some(caller) = &self.caller {
160 crate::sip_util::ensure_sip_scheme(caller.clone())
162 } else if let Some(username) = self.sip.as_ref().and_then(|sip| sip.username.as_ref()) {
163 let domain = self
166 .sip
167 .as_ref()
168 .and_then(|sip| sip.realm.as_ref())
169 .map(|s| s.as_str())
170 .unwrap_or("127.0.0.1");
171 format!("sip:{}@{}", username, domain)
172 } else {
173 "sip:active-call@127.0.0.1".to_string()
175 };
176 invite_option.caller = caller_uri.try_into()?;
177
178 if let Some(sip) = &self.sip {
179 invite_option.credential = Some(Credential {
180 username: sip.username.clone().unwrap_or_default(),
181 auth_username: None,
182 password: sip.password.clone().unwrap_or_default(),
183 realm: sip.realm.clone(),
184 });
185 invite_option.headers = sip
186 .headers
187 .as_ref()
188 .map(crate::sip_util::sip_headers_from_map);
189 sip.contact.as_ref().map(|c| match c.clone().try_into() {
190 Ok(u) => {
191 invite_option.contact = u;
192 }
193 Err(_) => {}
194 });
195 }
196 Ok(invite_option)
197 }
198}
199
200#[skip_serializing_none]
201#[derive(Debug, Deserialize, Serialize, Clone)]
202#[serde(rename_all = "camelCase")]
203pub struct ReferOption {
204 pub denoise: Option<bool>,
205 pub agc: Option<AGCOption>,
206 pub timeout: Option<u32>,
207 pub moh: Option<String>,
208 pub vad: Option<VADOption>,
209 pub asr: Option<TranscriptionOption>,
210 pub auto_hangup: Option<bool>,
212 pub sip: Option<SipOption>,
213 pub call_id: Option<String>,
214 pub pause_parent_asr: Option<bool>,
216 pub forward_dtmf: Option<bool>,
218 pub extra_headers: Option<HashMap<String, String>>,
221 pub inactivity_timeout: Option<u64>,
226}
227
228#[skip_serializing_none]
229#[derive(Clone, Debug, Deserialize, Serialize, Default)]
230#[serde(rename_all = "camelCase")]
231pub struct EouOption {
232 pub r#type: Option<String>,
233 pub endpoint: Option<String>,
234 #[serde(alias = "apiKey")]
235 pub secret_key: Option<String>,
236 pub secret_id: Option<String>,
237 pub timeout: Option<u32>,
239 pub extra: Option<HashMap<String, String>>,
240}
241
242#[skip_serializing_none]
243#[derive(Clone, Debug, Deserialize, Serialize, Default)]
244#[serde(rename_all = "camelCase")]
245pub struct RingbackDetectionOption {
246 pub enabled: Option<bool>,
247 pub model_weights_path: Option<String>,
249 pub min_buffer_secs: Option<f32>,
251 pub detection_interval_secs: Option<f32>,
253 pub confidence_threshold: Option<f32>,
255 pub on_state_change_only: Option<bool>,
257 pub sliding_window_size: Option<usize>,
259 pub final_confidence_threshold: Option<f32>,
261 pub inference_threads: Option<usize>,
264}
265
266#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
267pub enum RealtimeType {
268 #[serde(rename = "openai")]
269 OpenAI,
270 #[serde(rename = "azure")]
271 Azure,
272 Other(String),
273}
274
275impl<'de> Deserialize<'de> for RealtimeType {
276 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
277 where
278 D: serde::Deserializer<'de>,
279 {
280 let value = String::deserialize(deserializer)?;
281 match value.as_str() {
282 "openai" => Ok(RealtimeType::OpenAI),
283 "azure" => Ok(RealtimeType::Azure),
284 _ => Ok(RealtimeType::Other(value)),
285 }
286 }
287}
288
289#[skip_serializing_none]
290#[derive(Clone, Debug, Deserialize, Serialize, Default)]
291#[serde(rename_all = "camelCase")]
292pub struct RealtimeOption {
293 pub provider: Option<RealtimeType>,
294 pub model: Option<String>,
295 #[serde(alias = "apiKey")]
296 pub secret_key: Option<String>,
297 pub secret_id: Option<String>,
298 pub endpoint: Option<String>,
299 pub turn_detection: Option<serde_json::Value>,
300 pub tools: Option<Vec<serde_json::Value>>,
301 pub extra: Option<HashMap<String, String>>,
302}
303
304impl RealtimeOption {
305 pub fn check_default(&mut self) {
306 if self.secret_key.is_none() {
307 self.secret_key = std::env::var("OPENAI_API_KEY").ok();
308 }
309 }
310}
311
312pub type Spawner = fn(
313 std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
314) -> tokio::task::JoinHandle<()>;
315static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
316
317pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
318 EXTERNAL_SPAWNER.set(spawner)
319}
320
321pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
322where
323 F: std::future::Future<Output = ()> + Send + 'static,
324{
325 if let Some(spawner) = EXTERNAL_SPAWNER.get() {
326 spawner(Box::pin(future))
327 } else {
328 tokio::spawn(future)
329 }
330}
331
332#[cfg(test)]
333mod rtp_timeout_tests {
334 use super::CallOption;
335 use crate::call::Command;
336
337 #[test]
338 fn rtp_timeout_is_optional_and_shared_by_invite_and_accept() {
339 assert_eq!(CallOption::default().rtp_timeout, None);
340 assert!(
341 serde_json::to_value(CallOption::default())
342 .unwrap()
343 .get("rtpTimeout")
344 .is_none()
345 );
346 for command in ["invite", "accept"] {
347 for (option, expected) in [
348 (serde_json::json!({}), None),
349 (serde_json::json!({"rtpTimeout": null}), None),
350 (serde_json::json!({"rtpTimeout": 0}), Some(0)),
351 (serde_json::json!({"rtpTimeout": 30}), Some(30)),
352 ] {
353 let parsed: Command = serde_json::from_value(serde_json::json!({
354 "command": command, "option": option,
355 }))
356 .unwrap();
357 match parsed {
358 Command::Invite { option } | Command::Accept { option } => {
359 assert_eq!(option.rtp_timeout, expected);
360 }
361 _ => unreachable!(),
362 }
363 }
364 }
365 }
366}
367
368#[cfg(test)]
369mod jitter_buffer_option_tests {
370 use crate::call::Command;
371
372 #[test]
373 fn jitter_buffer_is_set_per_call_by_invite_and_accept() {
374 for command in ["invite", "accept"] {
375 for (option, expected) in [
376 (serde_json::json!({}), None),
377 (serde_json::json!({"jitterBuffer": true}), Some(true)),
378 (serde_json::json!({"jitterBuffer": false}), Some(false)),
379 ] {
380 let parsed: Command = serde_json::from_value(serde_json::json!({
381 "command": command, "option": option,
382 }))
383 .unwrap();
384 match parsed {
385 Command::Invite { option } | Command::Accept { option } => {
386 assert_eq!(option.jitter_buffer, expected);
387 }
388 _ => unreachable!(),
389 }
390 }
391 }
392 }
393}