Skip to main content

active_call/
lib.rs

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    // handshake timeout in seconds
81    pub handshake_timeout: Option<u64>,
82    pub enable_ipv6: Option<bool>,
83    pub inactivity_timeout: Option<u64>, // inactivity timeout in seconds
84    /// Incoming RTC sample timeout in seconds; None or zero disables notifications.
85    pub rtp_timeout: Option<u64>,
86    /// Jitter buffer and loss concealment on this leg's inbound audio (see
87    /// rustrtc's `JitterBuffer::tick`). None: `[jitter_buffer]` in the
88    /// config, by default on for WebRTC, off for SIP. Worth turning on for SIP endpoints on the
89    /// open internet, such as softphones, rather than carrier trunks.
90    pub jitter_buffer: Option<bool>,
91    pub sip: Option<SipOption>,
92    pub extra: Option<HashMap<String, String>>,
93    pub codec: Option<String>, // pcmu, pcma, g722, pcm, only for websocket call
94    pub ambiance: Option<AmbianceOption>,
95    pub eou: Option<EouOption>,
96    pub realtime: Option<RealtimeOption>,
97    pub subscribe: Option<bool>,
98    /// Side-path audio distribution: dial out to a websocket and mirror both
99    /// legs' audio (one-way tap, the media path is untouched).
100    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), // default 50 seconds
120            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            // Ensure caller URI has proper sip: scheme
160            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            // If caller is not specified but we have SIP credentials, use username as caller
163            // If realm is available, use it, otherwise use local IP
164            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            // Default to a valid SIP URI if nothing is specified
173            "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    /// hangup after the call is ended
210    pub auto_hangup: Option<bool>,
211    pub sip: Option<SipOption>,
212    pub call_id: Option<String>,
213    /// Pause parent call's ASR during refer call, will resume after refer ends (if auto_hangup is false)
214    pub pause_parent_asr: Option<bool>,
215    /// If false, DTMF RTP packets are not forwarded between the main call and the refer call
216    pub forward_dtmf: Option<bool>,
217    /// Custom headers blindly forwarded onto the transfer INVITE (e.g.
218    /// `User-to-User`, `X-ACC-Bizdata` received on an incoming REFER).
219    pub extra_headers: Option<HashMap<String, String>>,
220    /// Inactivity timeout (seconds) for the refer/bridge legs. When the leg
221    /// receives no media frames for this long it fires
222    /// `SessionEvent::Inactivity`, which ends the call. Defaults to
223    /// `CallOption::default()` (50s); `0` disables the watchdog.
224    pub inactivity_timeout: Option<u64>,
225}
226
227#[skip_serializing_none]
228#[derive(Clone, Debug, Deserialize, Serialize, Default)]
229#[serde(rename_all = "camelCase")]
230pub struct EouOption {
231    pub r#type: Option<String>,
232    pub endpoint: Option<String>,
233    #[serde(alias = "apiKey")]
234    pub secret_key: Option<String>,
235    pub secret_id: Option<String>,
236    /// max timeout in milliseconds
237    pub timeout: Option<u32>,
238    pub extra: Option<HashMap<String, String>>,
239}
240
241#[skip_serializing_none]
242#[derive(Clone, Debug, Deserialize, Serialize, Default)]
243#[serde(rename_all = "camelCase")]
244pub struct RingbackDetectionOption {
245    pub enabled: Option<bool>,
246    /// Path to telcoclassifier_weights.bin (default: "./telcoclassifier_weights.bin")
247    pub model_weights_path: Option<String>,
248    /// Minimum audio accumulation (seconds) before first inference
249    pub min_buffer_secs: Option<f32>,
250    /// Seconds between consecutive inferences
251    pub detection_interval_secs: Option<f32>,
252    /// Confidence threshold for reporting a state
253    pub confidence_threshold: Option<f32>,
254    /// Only emit events on state change (ringing→human_voice etc.)
255    pub on_state_change_only: Option<bool>,
256    /// Sliding window size for result accumulation (default: 6, i.e. 4+2)
257    pub sliding_window_size: Option<usize>,
258    /// Confidence threshold for immediate finalization (default: 0.9)
259    pub final_confidence_threshold: Option<f32>,
260}
261
262#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
263pub enum RealtimeType {
264    #[serde(rename = "openai")]
265    OpenAI,
266    #[serde(rename = "azure")]
267    Azure,
268    Other(String),
269}
270
271impl<'de> Deserialize<'de> for RealtimeType {
272    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
273    where
274        D: serde::Deserializer<'de>,
275    {
276        let value = String::deserialize(deserializer)?;
277        match value.as_str() {
278            "openai" => Ok(RealtimeType::OpenAI),
279            "azure" => Ok(RealtimeType::Azure),
280            _ => Ok(RealtimeType::Other(value)),
281        }
282    }
283}
284
285#[skip_serializing_none]
286#[derive(Clone, Debug, Deserialize, Serialize, Default)]
287#[serde(rename_all = "camelCase")]
288pub struct RealtimeOption {
289    pub provider: Option<RealtimeType>,
290    pub model: Option<String>,
291    #[serde(alias = "apiKey")]
292    pub secret_key: Option<String>,
293    pub secret_id: Option<String>,
294    pub endpoint: Option<String>,
295    pub turn_detection: Option<serde_json::Value>,
296    pub tools: Option<Vec<serde_json::Value>>,
297    pub extra: Option<HashMap<String, String>>,
298}
299
300impl RealtimeOption {
301    pub fn check_default(&mut self) {
302        if self.secret_key.is_none() {
303            self.secret_key = std::env::var("OPENAI_API_KEY").ok();
304        }
305    }
306}
307
308pub type Spawner = fn(
309    std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
310) -> tokio::task::JoinHandle<()>;
311static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
312
313pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
314    EXTERNAL_SPAWNER.set(spawner)
315}
316
317pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
318where
319    F: std::future::Future<Output = ()> + Send + 'static,
320{
321    if let Some(spawner) = EXTERNAL_SPAWNER.get() {
322        spawner(Box::pin(future))
323    } else {
324        tokio::spawn(future)
325    }
326}
327
328#[cfg(test)]
329mod rtp_timeout_tests {
330    use super::CallOption;
331    use crate::call::Command;
332
333    #[test]
334    fn rtp_timeout_is_optional_and_shared_by_invite_and_accept() {
335        assert_eq!(CallOption::default().rtp_timeout, None);
336        assert!(
337            serde_json::to_value(CallOption::default())
338                .unwrap()
339                .get("rtpTimeout")
340                .is_none()
341        );
342        for command in ["invite", "accept"] {
343            for (option, expected) in [
344                (serde_json::json!({}), None),
345                (serde_json::json!({"rtpTimeout": null}), None),
346                (serde_json::json!({"rtpTimeout": 0}), Some(0)),
347                (serde_json::json!({"rtpTimeout": 30}), Some(30)),
348            ] {
349                let parsed: Command = serde_json::from_value(serde_json::json!({
350                    "command": command, "option": option,
351                }))
352                .unwrap();
353                match parsed {
354                    Command::Invite { option } | Command::Accept { option } => {
355                        assert_eq!(option.rtp_timeout, expected);
356                    }
357                    _ => unreachable!(),
358                }
359            }
360        }
361    }
362}
363
364#[cfg(test)]
365mod jitter_buffer_option_tests {
366    use crate::call::Command;
367
368    #[test]
369    fn jitter_buffer_is_set_per_call_by_invite_and_accept() {
370        for command in ["invite", "accept"] {
371            for (option, expected) in [
372                (serde_json::json!({}), None),
373                (serde_json::json!({"jitterBuffer": true}), Some(true)),
374                (serde_json::json!({"jitterBuffer": false}), Some(false)),
375            ] {
376                let parsed: Command = serde_json::from_value(serde_json::json!({
377                    "command": command, "option": option,
378                }))
379                .unwrap();
380                match parsed {
381                    Command::Invite { option } | Command::Accept { option } => {
382                        assert_eq!(option.jitter_buffer, expected);
383                    }
384                    _ => unreachable!(),
385                }
386            }
387        }
388    }
389}