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