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