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}
191
192#[skip_serializing_none]
193#[derive(Clone, Debug, Deserialize, Serialize, Default)]
194#[serde(rename_all = "camelCase")]
195pub struct EouOption {
196 pub r#type: Option<String>,
197 pub endpoint: Option<String>,
198 #[serde(alias = "apiKey")]
199 pub secret_key: Option<String>,
200 pub secret_id: Option<String>,
201 pub timeout: Option<u32>,
203 pub extra: Option<HashMap<String, String>>,
204}
205
206#[skip_serializing_none]
207#[derive(Clone, Debug, Deserialize, Serialize, Default)]
208#[serde(rename_all = "camelCase")]
209pub struct RingbackDetectionOption {
210 pub enabled: Option<bool>,
211 pub model_weights_path: Option<String>,
213 pub min_buffer_secs: Option<f32>,
215 pub detection_interval_secs: Option<f32>,
217 pub confidence_threshold: Option<f32>,
219 pub on_state_change_only: Option<bool>,
221 pub sliding_window_size: Option<usize>,
223 pub final_confidence_threshold: Option<f32>,
225}
226
227#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
228pub enum RealtimeType {
229 #[serde(rename = "openai")]
230 OpenAI,
231 #[serde(rename = "azure")]
232 Azure,
233 Other(String),
234}
235
236impl<'de> Deserialize<'de> for RealtimeType {
237 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
238 where
239 D: serde::Deserializer<'de>,
240 {
241 let value = String::deserialize(deserializer)?;
242 match value.as_str() {
243 "openai" => Ok(RealtimeType::OpenAI),
244 "azure" => Ok(RealtimeType::Azure),
245 _ => Ok(RealtimeType::Other(value)),
246 }
247 }
248}
249
250#[skip_serializing_none]
251#[derive(Clone, Debug, Deserialize, Serialize, Default)]
252#[serde(rename_all = "camelCase")]
253pub struct RealtimeOption {
254 pub provider: Option<RealtimeType>,
255 pub model: Option<String>,
256 #[serde(alias = "apiKey")]
257 pub secret_key: Option<String>,
258 pub secret_id: Option<String>,
259 pub endpoint: Option<String>,
260 pub turn_detection: Option<serde_json::Value>,
261 pub tools: Option<Vec<serde_json::Value>>,
262 pub extra: Option<HashMap<String, String>>,
263}
264
265impl RealtimeOption {
266 pub fn check_default(&mut self) {
267 if self.secret_key.is_none() {
268 self.secret_key = std::env::var("OPENAI_API_KEY").ok();
269 }
270 }
271}
272
273pub type Spawner = fn(
274 std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
275) -> tokio::task::JoinHandle<()>;
276static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
277
278pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
279 EXTERNAL_SPAWNER.set(spawner)
280}
281
282pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
283where
284 F: std::future::Future<Output = ()> + Send + 'static,
285{
286 if let Some(spawner) = EXTERNAL_SPAWNER.get() {
287 spawner(Box::pin(future))
288 } else {
289 tokio::spawn(future)
290 }
291}
292
293#[cfg(test)]
294mod rtp_timeout_tests {
295 use super::CallOption;
296 use crate::call::Command;
297
298 #[test]
299 fn rtp_timeout_is_optional_and_shared_by_invite_and_accept() {
300 assert_eq!(CallOption::default().rtp_timeout, None);
301 assert!(
302 serde_json::to_value(CallOption::default())
303 .unwrap()
304 .get("rtpTimeout")
305 .is_none()
306 );
307 for command in ["invite", "accept"] {
308 for (option, expected) in [
309 (serde_json::json!({}), None),
310 (serde_json::json!({"rtpTimeout": null}), None),
311 (serde_json::json!({"rtpTimeout": 0}), Some(0)),
312 (serde_json::json!({"rtpTimeout": 30}), Some(30)),
313 ] {
314 let parsed: Command = serde_json::from_value(serde_json::json!({
315 "command": command, "option": option,
316 }))
317 .unwrap();
318 match parsed {
319 Command::Invite { option } | Command::Accept { option } => {
320 assert_eq!(option.rtp_timeout, expected);
321 }
322 _ => unreachable!(),
323 }
324 }
325 }
326 }
327}