Skip to main content

active_call/call/
mod.rs

1use crate::{CallOption, ReferOption, media::recorder::RecorderOption, synthesis::SynthesisOption};
2use serde::{Deserialize, Serialize};
3use serde_with::skip_serializing_none;
4use std::{
5    collections::HashMap,
6    sync::{Arc, Mutex},
7};
8
9pub mod active_call;
10pub mod refer_headers;
11pub mod sip;
12pub mod state;
13pub mod tracks;
14pub use active_call::ActiveCall;
15pub use active_call::ActiveCallRef;
16pub use active_call::ActiveCallType;
17pub use refer_headers::{PassThroughReferHeaders, ReferHeaderContext, ReferHeaderResolver};
18
19pub type CommandSender = tokio::sync::broadcast::Sender<Command>;
20pub type CommandReceiver = tokio::sync::broadcast::Receiver<Command>;
21
22// WebSocket Commands
23#[skip_serializing_none]
24#[derive(Debug, Deserialize, Serialize, Clone)]
25#[serde(
26    tag = "command",
27    rename_all = "camelCase",
28    rename_all_fields = "camelCase"
29)]
30pub enum Command {
31    Invite {
32        option: CallOption,
33    },
34    Accept {
35        option: CallOption,
36    },
37    Reject {
38        reason: String,
39        code: Option<u32>,
40    },
41    Ringing {
42        recorder: Option<RecorderOption>,
43        early_media: Option<bool>,
44        ringtone: Option<String>,
45    },
46    Tts {
47        text: String,
48        speaker: Option<String>,
49        /// If the play_id is the same, it will not interrupt the previous playback
50        play_id: Option<String>,
51        /// If auto_hangup is true, it means the call will be hung up automatically after the TTS playback is finished
52        auto_hangup: Option<bool>,
53        /// If streaming is true, it means the input text is streaming text,
54        /// and end_of_stream needs to be used to determine if it's finished,
55        /// equivalent to LLM's streaming output to TTS synthesis
56        streaming: Option<bool>,
57        /// If end_of_stream is true, it means the input text is finished
58        end_of_stream: Option<bool>,
59        option: Option<SynthesisOption>,
60        wait_input_timeout: Option<u32>,
61        /// if true, the text is base64 encoded pcm samples
62        base64: Option<bool>,
63        /// Customizing cache key for TTS Result
64        cache_key: Option<String>,
65    },
66    Play {
67        url: String,
68        play_id: Option<String>,
69        auto_hangup: Option<bool>,
70        wait_input_timeout: Option<u32>,
71        offset_ms: Option<u32>,
72    },
73    /// Send one DTMF digit (0-9, *, #, A-D) to the remote party. RTP legs
74    /// emit an RFC 4733 telephone-event on the negotiated payload type;
75    /// outgoing audio is muted while the digit is on the wire. Runs on its
76    /// own track, so it neither interrupts playback nor is interrupted by it.
77    Dtmf {
78        digit: char,
79        /// Duration of the digit, default 100ms.
80        duration_ms: Option<u32>,
81        play_id: Option<String>,
82    },
83    Interrupt {
84        graceful: Option<bool>,
85        fade_out_ms: Option<u32>,
86    },
87    Pause {},
88    Resume {},
89    Hangup {
90        reason: Option<String>,
91        initiator: Option<String>,
92        headers: Option<HashMap<String, String>>,
93        refer: Option<bool>,
94    },
95    Refer {
96        caller: String,
97        /// aor of the calee, e.g., sip:bob@restsend.com
98        callee: String,
99        options: Option<ReferOption>,
100    },
101    Message {
102        /// MIME body to send in a SIP MESSAGE request.
103        body: String,
104        /// Defaults to text/plain;charset=utf-8.
105        content_type: Option<String>,
106        /// Additional SIP headers for the MESSAGE request.
107        headers: Option<HashMap<String, String>>,
108        /// If true, send on the active refer dialog instead of the main call dialog.
109        refer: Option<bool>,
110    },
111    /// Bridge audio with another established call.
112    /// This creates separate bridge tracks for the two sessions and patches
113    /// audio bidirectionally. It does not replace the server-side track and
114    /// does not control hangup; each call keeps its own session/event flow.
115    Bridge {
116        /// session_id of the other call to bridge audio with
117        target_session_id: String,
118    },
119    /// Remove audio bridge tracks with another established call.
120    Unbridge {
121        /// session_id of the other call to unbridge from
122        target_session_id: String,
123    },
124    Mute {
125        track_id: Option<String>,
126    },
127    Unmute {
128        track_id: Option<String>,
129    },
130    History {
131        speaker: String,
132        text: String,
133    },
134    Custom {
135        sender: Option<String>,
136        data: serde_json::Value,
137    },
138    /// Trickle ICE: feed a remote candidate into an already-established session.
139    AddIceCandidate {
140        candidate: String,
141        sdp_mid: Option<String>,
142        sdp_mline_index: Option<u32>,
143    },
144    /// Apply a new remote offer to the already-established WebRTC track
145    /// (e.g. an ICE restart after the caller's network changed). The new
146    /// answer is delivered as an `answer` event.
147    Renegotiate {
148        offer: String,
149    },
150}
151
152/// Routing state for managing stateful load balancing
153#[derive(Debug)]
154pub struct RoutingState {
155    /// Round-robin counters for each destination group
156    round_robin_counters: Arc<Mutex<HashMap<String, usize>>>,
157}
158
159impl Default for RoutingState {
160    fn default() -> Self {
161        Self::new()
162    }
163}
164
165impl RoutingState {
166    pub fn new() -> Self {
167        Self {
168            round_robin_counters: Arc::new(Mutex::new(HashMap::new())),
169        }
170    }
171
172    /// Get the next trunk index for round-robin selection
173    pub fn next_round_robin_index(&self, destination_key: &str, trunk_count: usize) -> usize {
174        if trunk_count == 0 {
175            return 0;
176        }
177
178        let mut counters = self.round_robin_counters.lock().unwrap();
179        let counter = counters
180            .entry(destination_key.to_string())
181            .or_insert_with(|| 0);
182        let r = *counter % trunk_count;
183        *counter += 1;
184        return r;
185    }
186}
187
188#[cfg(test)]
189mod tests {
190    use super::Command;
191
192    #[test]
193    fn diagnostic_commands_omit_sip_password() {
194        assert!(format!("{:?}", crate::SipOption::default()).contains("password: None"));
195        let sip = serde_json::json!({"username": "alice", "password": "dummy-sip-secret"});
196        for value in [
197            serde_json::json!({"command": "invite", "option": {"sip": sip}}),
198            serde_json::json!({"command": "accept", "option": {"sip": sip}}),
199            serde_json::json!({"command": "refer", "caller": "a", "callee": "b", "options": {"sip": sip}}),
200        ] {
201            let command: Command = serde_json::from_value(value).unwrap();
202            let debug = format!("{command:?}");
203            assert!(debug.contains("alice"));
204            assert!(debug.contains(r#"password: Some("***")"#));
205            assert!(!debug.contains("dummy-sip-secret"));
206            let serialized = serde_json::to_value(&command).unwrap();
207            let sip = match command {
208                Command::Invite { option } | Command::Accept { option } => option.sip.unwrap(),
209                Command::Refer { options, .. } => options.unwrap().sip.unwrap(),
210                _ => unreachable!(),
211            };
212            assert_eq!(sip.password.as_deref(), Some("dummy-sip-secret"));
213            let options = serialized.get("option").or_else(|| serialized.get("options")).unwrap();
214            assert!(options["sip"].get("password").is_none());
215            assert_eq!(options["sip"]["username"], "alice");
216        }
217    }
218
219    #[test]
220    fn message_command_deserializes_body() {
221        let command: Command = serde_json::from_value(serde_json::json!({
222            "command": "message",
223            "body": "customer_id=12345",
224            "contentType": "text/plain"
225        }))
226        .unwrap();
227
228        assert!(matches!(
229            command,
230            Command::Message {
231                body,
232                content_type: Some(content_type),
233                ..
234            } if body == "customer_id=12345" && content_type == "text/plain"
235        ));
236    }
237
238    #[test]
239    fn dtmf_command_deserializes() {
240        let command: Command = serde_json::from_value(serde_json::json!({
241            "command": "dtmf",
242            "digit": "#",
243            "durationMs": 80,
244            "playId": "notify"
245        }))
246        .unwrap();
247
248        assert!(matches!(
249            command,
250            Command::Dtmf {
251                digit: '#',
252                duration_ms: Some(80),
253                play_id: Some(play_id),
254            } if play_id == "notify"
255        ));
256
257        // Exactly one digit.
258        assert!(
259            serde_json::from_value::<Command>(serde_json::json!({
260                "command": "dtmf",
261                "digit": "12"
262            }))
263            .is_err()
264        );
265    }
266
267    #[test]
268    fn message_command_deserializes_legacy_text() {
269        let command: Command = serde_json::from_value(serde_json::json!({
270            "command": "message",
271            "body": "customer_id=12345"
272        }))
273        .unwrap();
274
275        assert!(matches!(
276            command,
277            Command::Message { body, .. } if body == "customer_id=12345"
278        ));
279    }
280
281    #[test]
282    fn message_command_serializes_body() {
283        let command = Command::Message {
284            body: "customer_id=12345".to_string(),
285            content_type: None,
286            headers: None,
287            refer: None,
288        };
289        let value = serde_json::to_value(command).unwrap();
290
291        assert_eq!(value["body"], "customer_id=12345");
292        assert!(value.get("text").is_none());
293    }
294}