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    pub sip: Option<SipOption>,
87    pub extra: Option<HashMap<String, String>>,
88    pub codec: Option<String>, // pcmu, pcma, g722, pcm, only for websocket call
89    pub ambiance: Option<AmbianceOption>,
90    pub eou: Option<EouOption>,
91    pub realtime: Option<RealtimeOption>,
92    pub subscribe: Option<bool>,
93    /// Side-path audio distribution: dial out to a websocket and mirror both
94    /// legs' audio (one-way tap, the media path is untouched).
95    pub monitor: Option<MonitorOption>,
96    pub enable_ice_lite: Option<bool>,
97    pub ringback_detection: Option<RingbackDetectionOption>,
98}
99
100impl Default for CallOption {
101    fn default() -> Self {
102        Self {
103            denoise: None,
104            agc: None,
105            offer: None,
106            callee: None,
107            caller: None,
108            recorder: None,
109            asr: None,
110            vad: None,
111            tts: None,
112            media_pass: None,
113            handshake_timeout: None,
114            inactivity_timeout: Some(50), // default 50 seconds
115            rtp_timeout: None,
116            enable_ipv6: None,
117            sip: None,
118            extra: None,
119            codec: None,
120            ambiance: None,
121            eou: None,
122            realtime: None,
123            subscribe: None,
124            monitor: None,
125            enable_ice_lite: None,
126            ringback_detection: None,
127        }
128    }
129}
130
131impl CallOption {
132    pub fn check_default(&mut self) {
133        if let Some(tts) = &mut self.tts {
134            tts.check_default();
135        }
136        if let Some(asr) = &mut self.asr {
137            asr.check_default();
138        }
139        if let Some(realtime) = &mut self.realtime {
140            realtime.check_default();
141        }
142    }
143
144    pub fn build_invite_option(&self) -> Result<InviteOption> {
145        let mut invite_option = InviteOption::default();
146        if let Some(offer) = &self.offer {
147            invite_option.offer = Some(offer.clone().into());
148        }
149        if let Some(callee) = &self.callee {
150            invite_option.callee = callee.clone().try_into()?;
151        }
152        let caller_uri = if let Some(caller) = &self.caller {
153            // Ensure caller URI has proper sip: scheme
154            crate::sip_util::ensure_sip_scheme(caller.clone())
155        } else if let Some(username) = self.sip.as_ref().and_then(|sip| sip.username.as_ref()) {
156            // If caller is not specified but we have SIP credentials, use username as caller
157            // If realm is available, use it, otherwise use local IP
158            let domain = self
159                .sip
160                .as_ref()
161                .and_then(|sip| sip.realm.as_ref())
162                .map(|s| s.as_str())
163                .unwrap_or("127.0.0.1");
164            format!("sip:{}@{}", username, domain)
165        } else {
166            // Default to a valid SIP URI if nothing is specified
167            "sip:active-call@127.0.0.1".to_string()
168        };
169        invite_option.caller = caller_uri.try_into()?;
170
171        if let Some(sip) = &self.sip {
172            invite_option.credential = Some(Credential {
173                username: sip.username.clone().unwrap_or_default(),
174                auth_username: None,
175                password: sip.password.clone().unwrap_or_default(),
176                realm: sip.realm.clone(),
177            });
178            invite_option.headers = sip
179                .headers
180                .as_ref()
181                .map(crate::sip_util::sip_headers_from_map);
182            sip.contact.as_ref().map(|c| match c.clone().try_into() {
183                Ok(u) => {
184                    invite_option.contact = u;
185                }
186                Err(_) => {}
187            });
188        }
189        Ok(invite_option)
190    }
191}
192
193#[skip_serializing_none]
194#[derive(Debug, Deserialize, Serialize, Clone)]
195#[serde(rename_all = "camelCase")]
196pub struct ReferOption {
197    pub denoise: Option<bool>,
198    pub agc: Option<AGCOption>,
199    pub timeout: Option<u32>,
200    pub moh: Option<String>,
201    pub vad: Option<VADOption>,
202    pub asr: Option<TranscriptionOption>,
203    /// hangup after the call is ended
204    pub auto_hangup: Option<bool>,
205    pub sip: Option<SipOption>,
206    pub call_id: Option<String>,
207    /// Pause parent call's ASR during refer call, will resume after refer ends (if auto_hangup is false)
208    pub pause_parent_asr: Option<bool>,
209    /// If false, DTMF RTP packets are not forwarded between the main call and the refer call
210    pub forward_dtmf: Option<bool>,
211    /// Custom headers blindly forwarded onto the transfer INVITE (e.g.
212    /// `User-to-User`, `X-ACC-Bizdata` received on an incoming REFER).
213    pub extra_headers: Option<HashMap<String, String>>,
214}
215
216#[skip_serializing_none]
217#[derive(Clone, Debug, Deserialize, Serialize, Default)]
218#[serde(rename_all = "camelCase")]
219pub struct EouOption {
220    pub r#type: Option<String>,
221    pub endpoint: Option<String>,
222    #[serde(alias = "apiKey")]
223    pub secret_key: Option<String>,
224    pub secret_id: Option<String>,
225    /// max timeout in milliseconds
226    pub timeout: Option<u32>,
227    pub extra: Option<HashMap<String, String>>,
228}
229
230#[skip_serializing_none]
231#[derive(Clone, Debug, Deserialize, Serialize, Default)]
232#[serde(rename_all = "camelCase")]
233pub struct RingbackDetectionOption {
234    pub enabled: Option<bool>,
235    /// Path to telcoclassifier_weights.bin (default: "./telcoclassifier_weights.bin")
236    pub model_weights_path: Option<String>,
237    /// Minimum audio accumulation (seconds) before first inference
238    pub min_buffer_secs: Option<f32>,
239    /// Seconds between consecutive inferences
240    pub detection_interval_secs: Option<f32>,
241    /// Confidence threshold for reporting a state
242    pub confidence_threshold: Option<f32>,
243    /// Only emit events on state change (ringing→human_voice etc.)
244    pub on_state_change_only: Option<bool>,
245    /// Sliding window size for result accumulation (default: 6, i.e. 4+2)
246    pub sliding_window_size: Option<usize>,
247    /// Confidence threshold for immediate finalization (default: 0.9)
248    pub final_confidence_threshold: Option<f32>,
249}
250
251#[derive(Debug, Clone, Serialize, Hash, Eq, PartialEq)]
252pub enum RealtimeType {
253    #[serde(rename = "openai")]
254    OpenAI,
255    #[serde(rename = "azure")]
256    Azure,
257    Other(String),
258}
259
260impl<'de> Deserialize<'de> for RealtimeType {
261    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
262    where
263        D: serde::Deserializer<'de>,
264    {
265        let value = String::deserialize(deserializer)?;
266        match value.as_str() {
267            "openai" => Ok(RealtimeType::OpenAI),
268            "azure" => Ok(RealtimeType::Azure),
269            _ => Ok(RealtimeType::Other(value)),
270        }
271    }
272}
273
274#[skip_serializing_none]
275#[derive(Clone, Debug, Deserialize, Serialize, Default)]
276#[serde(rename_all = "camelCase")]
277pub struct RealtimeOption {
278    pub provider: Option<RealtimeType>,
279    pub model: Option<String>,
280    #[serde(alias = "apiKey")]
281    pub secret_key: Option<String>,
282    pub secret_id: Option<String>,
283    pub endpoint: Option<String>,
284    pub turn_detection: Option<serde_json::Value>,
285    pub tools: Option<Vec<serde_json::Value>>,
286    pub extra: Option<HashMap<String, String>>,
287}
288
289impl RealtimeOption {
290    pub fn check_default(&mut self) {
291        if self.secret_key.is_none() {
292            self.secret_key = std::env::var("OPENAI_API_KEY").ok();
293        }
294    }
295}
296
297pub type Spawner = fn(
298    std::pin::Pin<Box<dyn std::future::Future<Output = ()> + Send>>,
299) -> tokio::task::JoinHandle<()>;
300static EXTERNAL_SPAWNER: std::sync::OnceLock<Spawner> = std::sync::OnceLock::new();
301
302pub fn set_spawner(spawner: Spawner) -> Result<(), Spawner> {
303    EXTERNAL_SPAWNER.set(spawner)
304}
305
306pub fn spawn<F>(future: F) -> tokio::task::JoinHandle<()>
307where
308    F: std::future::Future<Output = ()> + Send + 'static,
309{
310    if let Some(spawner) = EXTERNAL_SPAWNER.get() {
311        spawner(Box::pin(future))
312    } else {
313        tokio::spawn(future)
314    }
315}
316
317#[cfg(test)]
318mod rtp_timeout_tests {
319    use super::CallOption;
320    use crate::call::Command;
321
322    #[test]
323    fn rtp_timeout_is_optional_and_shared_by_invite_and_accept() {
324        assert_eq!(CallOption::default().rtp_timeout, None);
325        assert!(
326            serde_json::to_value(CallOption::default())
327                .unwrap()
328                .get("rtpTimeout")
329                .is_none()
330        );
331        for command in ["invite", "accept"] {
332            for (option, expected) in [
333                (serde_json::json!({}), None),
334                (serde_json::json!({"rtpTimeout": null}), None),
335                (serde_json::json!({"rtpTimeout": 0}), Some(0)),
336                (serde_json::json!({"rtpTimeout": 30}), Some(30)),
337            ] {
338                let parsed: Command = serde_json::from_value(serde_json::json!({
339                    "command": command, "option": option,
340                }))
341                .unwrap();
342                match parsed {
343                    Command::Invite { option } | Command::Accept { option } => {
344                        assert_eq!(option.rtp_timeout, expected);
345                    }
346                    _ => unreachable!(),
347                }
348            }
349        }
350    }
351}