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