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 message_command_deserializes_body() {
194        let command: Command = serde_json::from_value(serde_json::json!({
195            "command": "message",
196            "body": "customer_id=12345",
197            "contentType": "text/plain"
198        }))
199        .unwrap();
200
201        assert!(matches!(
202            command,
203            Command::Message {
204                body,
205                content_type: Some(content_type),
206                ..
207            } if body == "customer_id=12345" && content_type == "text/plain"
208        ));
209    }
210
211    #[test]
212    fn dtmf_command_deserializes() {
213        let command: Command = serde_json::from_value(serde_json::json!({
214            "command": "dtmf",
215            "digit": "#",
216            "durationMs": 80,
217            "playId": "notify"
218        }))
219        .unwrap();
220
221        assert!(matches!(
222            command,
223            Command::Dtmf {
224                digit: '#',
225                duration_ms: Some(80),
226                play_id: Some(play_id),
227            } if play_id == "notify"
228        ));
229
230        // Exactly one digit.
231        assert!(
232            serde_json::from_value::<Command>(serde_json::json!({
233                "command": "dtmf",
234                "digit": "12"
235            }))
236            .is_err()
237        );
238    }
239
240    #[test]
241    fn message_command_deserializes_legacy_text() {
242        let command: Command = serde_json::from_value(serde_json::json!({
243            "command": "message",
244            "body": "customer_id=12345"
245        }))
246        .unwrap();
247
248        assert!(matches!(
249            command,
250            Command::Message { body, .. } if body == "customer_id=12345"
251        ));
252    }
253
254    #[test]
255    fn message_command_serializes_body() {
256        let command = Command::Message {
257            body: "customer_id=12345".to_string(),
258            content_type: None,
259            headers: None,
260            refer: None,
261        };
262        let value = serde_json::to_value(command).unwrap();
263
264        assert_eq!(value["body"], "customer_id=12345");
265        assert!(value.get("text").is_none());
266    }
267}