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