active-call 0.3.114

A SIP/WebRTC voice agent
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
use crate::{
    event::{EventSender, SessionEvent},
    media::AudioFrame,
    media::Samples,
    media::TrackId,
    media::{
        processor::{Processor, ProcessorChain},
        track::{Track, TrackConfig, TrackPacketSender},
    },
};
use anyhow::Result;
use async_trait::async_trait;
use audio_codec::{bytes_to_samples, resample, samples_to_bytes};
use bytes::{Bytes, BytesMut};
use futures::{SinkExt, StreamExt, stream::SplitSink};
use serde::{Deserialize, Serialize};
use std::{
    sync::Arc,
    sync::atomic::{AtomicU64, Ordering},
    time::Duration,
};
use tokio::{net::TcpStream, sync::Mutex};
use tokio_tungstenite::{MaybeTlsStream, WebSocketStream, tungstenite::Message};
use tokio_util::sync::CancellationToken;
use tracing::{error, info, warn};

type WsConn = WebSocketStream<MaybeTlsStream<TcpStream>>;
type WsSink = SplitSink<WsConn, Message>;

#[derive(Debug, Deserialize, Serialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MediaPassOption {
    url: String,             // websocket url, e.g. ws://localhost:8080/
    input_sample_rate: u32,  // sample rate of audio receiving from websocket
    output_sample_rate: u32, // sample rate of audio sending to websocket server
    /// Size in bytes of each binary frame sent to the websocket server (uplink
    /// send buffer). Defaults to [`DEFAULT_BUFFER_MS`] worth of audio at
    /// `output_sample_rate`.
    packet_size: Option<u32>,
    /// Fixed interval in milliseconds at which buffered websocket audio is
    /// re-emitted towards the call (downlink send buffer). Defaults to
    /// [`DEFAULT_BUFFER_MS`]; `Some(0)` disables buffering and emits every
    /// websocket message as it arrives.
    ptime: Option<u32>,
}

/// Default buffering window, in milliseconds, applied to **both** directions of
/// the media-pass bridge when the caller does not specify `packet_size` /
/// `ptime`: the uplink is chunked into this many milliseconds per websocket
/// frame and the downlink is re-emitted on this same interval.
pub const DEFAULT_BUFFER_MS: u32 = 100;

/// Bytes of 16-bit mono PCM covering [`DEFAULT_BUFFER_MS`] at `sample_rate`.
///
/// `sample_rate` samples/s * 0.1 s * 2 bytes/sample == `sample_rate / 5`.
fn default_buffer_bytes(sample_rate: u32) -> u32 {
    (sample_rate / 5).max(1)
}

#[cfg(test)]
mod default_buffer_tests {
    use super::*;

    #[test]
    fn default_buffer_is_100ms_of_pcm16_mono() {
        // 100 ms == sample_rate / 10 samples * 2 bytes.
        assert_eq!(default_buffer_bytes(8000), 1600);
        assert_eq!(default_buffer_bytes(16000), 3200);
        assert_eq!(default_buffer_bytes(48000), 9600);
        // Never zero, even for a degenerate rate.
        assert_eq!(default_buffer_bytes(0), 1);
    }

    #[test]
    fn explicit_packet_size_wins_and_zero_falls_back() {
        let opt = MediaPassOption::new("ws://x".into(), 16000, 16000, Some(640), Some(20));
        let track = MediaPassTrack::new("s".into(), 0, "t".into(), CancellationToken::new(), opt);
        assert_eq!(track.packet_size, 640);
        assert_eq!(track.config.ptime, Duration::from_millis(20));

        let opt = MediaPassOption::new("ws://x".into(), 16000, 16000, Some(0), None);
        let track = MediaPassTrack::new("s".into(), 0, "t".into(), CancellationToken::new(), opt);
        assert_eq!(track.packet_size, 3200, "0 falls back to the 100ms default");
        assert_eq!(track.config.ptime, Duration::from_millis(DEFAULT_BUFFER_MS as u64));
    }

    #[test]
    fn default_packet_size_tracks_output_sample_rate() {
        let opt = MediaPassOption::new("ws://x".into(), 8000, 8000, None, None);
        let track = MediaPassTrack::new("s".into(), 0, "t".into(), CancellationToken::new(), opt);
        assert_eq!(track.packet_size, 1600);
        assert_eq!(track.config.ptime, Duration::from_millis(100));
    }
}

impl MediaPassOption {
    pub fn new(
        url: String,
        input_sample_rate: u32,
        output_sample_rate: u32,
        packet_size: Option<u32>,
        ptime: Option<u32>,
    ) -> Self {
        Self {
            url,
            input_sample_rate,
            output_sample_rate,
            packet_size,
            ptime,
        }
    }
}

pub struct MediaPassTrack {
    session_id: String,
    track_id: TrackId,
    cancel_token: CancellationToken,
    config: TrackConfig, // input sample rate is here, it is 0 if the ptime is None
    url: String,
    output_sample_rate: u32, // output sample rate
    packet_size: u32,
    // buffer the rtp/webrtc packets, send to websocket server with packet size
    buffer: Mutex<BytesMut>,
    ws_sink: Arc<Mutex<Option<WsSink>>>,
    bytes_sent: Arc<AtomicU64>, // bytes sent to websocket
    ssrc: u32,
    processor_chain: ProcessorChain,
}

impl MediaPassTrack {
    pub fn new(
        session_id: String,
        ssrc: u32,
        track_id: TrackId,
        cancel_token: CancellationToken,
        option: MediaPassOption,
    ) -> Self {
        let sample_rate = option.output_sample_rate;
        // `inputSampleRate` is sometimes omitted as 0 when ptime is disabled.
        // A 0 here used to flow into the track's frames and make
        // `ProcessorChain` build a 0 Hz resampler, panicking inside the media
        // worker. Fall back to the output rate so the pipeline always has a
        // valid source rate.
        let input_sample_rate = if option.input_sample_rate > 0 {
            option.input_sample_rate
        } else {
            warn!(
                input_sample_rate = option.input_sample_rate,
                output_sample_rate = sample_rate,
                "media pass input sample rate is 0, falling back to output sample rate"
            );
            sample_rate
        };
        let mut config = TrackConfig::default();
        config = config.with_sample_rate(input_sample_rate);
        // Downlink send buffer: emit buffered websocket audio every `ptime`.
        // Default to a 100 ms window; `Some(0)` opts out (immediate pass-through).
        let ptime_ms = option.ptime.unwrap_or(DEFAULT_BUFFER_MS);
        config = config.with_ptime(Duration::from_millis(ptime_ms as u64));
        // Uplink send buffer: chunk websocket sends into `packet_size` bytes.
        // Default to a 100 ms window at the output rate (3200 bytes @16 kHz,
        // 1600 bytes @8 kHz); an explicit 0 falls back to the same default.
        let packet_size = match option.packet_size {
            Some(size) if size > 0 => size,
            _ => default_buffer_bytes(sample_rate),
        };
        let buffer: Mutex<BytesMut> = Mutex::new(BytesMut::with_capacity(packet_size as usize * 2));
        Self {
            session_id,
            track_id,
            cancel_token,
            config,
            url: option.url,
            output_sample_rate: sample_rate,
            packet_size,
            buffer,
            ssrc,
            ws_sink: Arc::new(Mutex::new(None)),
            bytes_sent: Arc::new(AtomicU64::new(0)),
            // dummy processor chain, will ignore processor
            processor_chain: ProcessorChain::new(sample_rate),
        }
    }
}

#[async_trait]
impl Track for MediaPassTrack {
    fn ssrc(&self) -> u32 {
        self.ssrc
    }
    fn id(&self) -> &TrackId {
        &self.track_id
    }
    fn config(&self) -> &TrackConfig {
        &self.config
    }
    fn processor_chain(&mut self) -> &mut ProcessorChain {
        // The chain is still used to process this track's own frames, and it
        // carries the recorder tap: `MediaStream` attaches the recorder through
        // this accessor so it bypasses the processor-ignoring overrides below.
        &mut self.processor_chain
    }
    fn insert_processor(&mut self, _: Box<dyn Processor>) {
        // Audio processors (denoise/VAD/ASR…) must not touch the passthrough
        // media; the recorder reaches the chain via `processor_chain()`.
        warn!(track_id = %self.track_id, "ignore processor for media pass track");
    }
    fn append_processor(&mut self, _: Box<dyn Processor>) {
        warn!(track_id = %self.track_id, "ignore processor for media pass track");
    }
    async fn handshake(&mut self, _: String, _: Option<Duration>) -> Result<String> {
        Ok("".to_string())
    }
    async fn update_remote_description(&mut self, _answer: &String) -> Result<()> {
        Ok(())
    }

    async fn start(
        &mut self,
        event_sender: EventSender,
        packet_sender: TrackPacketSender,
    ) -> Result<()> {
        let mut url = url::Url::parse(&self.url)?;
        {
            let mut query = url.query_pairs_mut();
            query.append_pair("sample_rate", self.output_sample_rate.to_string().as_str());
            query.append_pair("packet_size", self.packet_size.to_string().as_str());
        }
        info!(
            session_id = %self.session_id,
            track_id = %self.track_id,
            input_sample_rate = self.config.samplerate,
            output_sample_rate = self.output_sample_rate,
            packet_size = self.packet_size,
            ptime_ms = self.config.ptime.as_millis(),
            "Media pass track starting"
        );
        let input_sample_rate = self.config.samplerate;
        let output_sample_rate = self.output_sample_rate;
        let (ws_stream, _) = tokio_tungstenite::connect_async(url.as_str()).await?;
        let (ws_sink, mut ws_source) = ws_stream.split();
        *self.ws_sink.lock().await = Some(ws_sink);
        let ws_sink = self.ws_sink.clone();
        let bytes_sent = self.bytes_sent.clone();
        let session_id = self.session_id.clone();
        let ssrc = self.ssrc;
        let track_id = self.track_id.clone();
        let start_time = crate::media::get_timestamp();
        let cancel_token = self.cancel_token.clone();
        let ptime = self.config.ptime;
        let ptime_ms = ptime.as_millis() as u32;
        let channels = self.config.channels;
        let mut processor_chain = self.processor_chain.clone();
        crate::spawn(async move {
            let mut bytes_received = 0u64;
            let mut bytes_emitted = 0u64;

            // ptimer is polled only if ptime > 0
            let capacity = input_sample_rate as usize * ptime_ms as usize / 500;
            let (mut ptimer, mut samples, mut buffer) = if ptime_ms > 0 {
                (
                    tokio::time::interval(Duration::from_millis(ptime_ms as u64)),
                    vec![0u8; capacity],
                    BytesMut::with_capacity(8 * 1024),
                )
            } else {
                (
                    tokio::time::interval(Duration::MAX),
                    Vec::new(),
                    BytesMut::new(),
                )
            };

            loop {
                tokio::select! {
                    biased;
                    _ = cancel_token.cancelled() => {
                        info!(session_id, "Media pass track cancelled");
                        break;
                    }
                    _ = ptimer.tick(), if ptime_ms > 0 => {
                        // Fill samples buffer from audio buffer
                        samples.fill(0);
                        let mut i = 0;

                        // Fill samples until it's full or there's no more data
                        while i < capacity && buffer.len() > 0 {
                            let remaining = capacity - i;
                            let available = buffer.len();
                            let len = usize::min(remaining, available);
                            let cut = buffer.split_to(len);
                            samples[i..i+len].copy_from_slice(&cut);
                            i += len;
                        }

                        // Create frame (will have zeros if not enough data)
                        let samples_vec = bytes_to_samples(&samples[..]);
                        let mut frame = AudioFrame {
                            track_id: track_id.clone(),
                            samples: Samples::PCM { samples: samples_vec.clone() },
                            timestamp: crate::media::get_timestamp(),
                            sample_rate: input_sample_rate,
                            channels,
                            ..Default::default()
                        };

                        if let Err(e) = processor_chain.process_frame(&mut frame) {
                            warn!(track_id, "error processing frame: {}", e);
                        }

                        if let Ok(_) = packet_sender.send(frame) {
                            // only count the actual bytes filled from buffer
                            bytes_emitted += i as u64;
                        } else {
                            warn!(
                                track_id,
                                "packet sender closed, stopping emit loop"
                            );
                            break;
                        }
                    }
                    msg = ws_source.next() => {
                        match msg {
                            Some(Ok(Message::Binary(data))) => {
                                bytes_received += data.len() as u64;
                                if ptime_ms > 0 {
                                    // buffer if ptime was set
                                    buffer.reserve(data.len());
                                    buffer.extend_from_slice(&data);
                                } else {
                                    // send immediately if ptime was not set
                                    let samples_vec = bytes_to_samples(&data);
                                    let mut frame = AudioFrame {
                                        track_id: track_id.clone(),
                                        samples: Samples::PCM { samples: samples_vec.clone() },
                                        timestamp: crate::media::get_timestamp(),
                                        sample_rate: input_sample_rate,
                                        channels,
                            ..Default::default()
                                    };

                                    if let Err(e) = processor_chain.process_frame(&mut frame) {
                                        warn!(track_id, "error processing frame: {}", e);
                                    }

                                    if let Ok(_) = packet_sender.send(frame) {
                                        bytes_emitted += data.len() as u64;
                                    } else {
                                        warn!(
                                            track_id,
                                            "packet sender closed, stopping emit loop"
                                        );
                                        break;
                                    }
                                }
                            }
                            Some(Ok(Message::Close(res))) => {
                                warn!(
                                    track_id,
                                    close_reason = ?res,
                                    bytes_received,
                                    "Media pass track closed by remote"
                                );
                                break;
                            }
                            Some(Err(e)) => {
                                error!(
                                    track_id,
                                    error = %e,
                                    bytes_received,
                                    "Media pass track WebSocket error"
                                );
                                let error = SessionEvent::Error {
                                    track_id: track_id.clone(),
                                    timestamp: crate::media::get_timestamp(),
                                    sender: format!("media_pass: {}", url),
                                    error: format!("Media pass track error: {:?}", e),
                                    code: None,
                                };
                                event_sender.send(error).ok();
                                break;
                            }
                            None => {
                                info!(
                                    track_id,
                                    bytes_received,
                                    "Media pass track WebSocket stream ended"
                                );
                                break;
                            }
                            _ => {}
                        }
                    }
                }

                // Break if packet sender is closed
                if packet_sender.is_closed() {
                    break;
                }
            }

            if let Some(mut ws_sink) = ws_sink.lock().await.take() {
                ws_sink.close().await.ok();
            };

            let duration = crate::media::get_timestamp() - start_time;
            let bytes_sent_to_ws = bytes_sent.load(Ordering::Relaxed);
            info!(
                session_id,
                duration,
                input_sample_rate,
                output_sample_rate,
                bytes_received,
                bytes_emitted,
                bytes_sent_to_ws,
                "Media pass track ended"
            );

            event_sender
                .send(SessionEvent::TrackEnd {
                    track_id,
                    timestamp: crate::media::get_timestamp(),
                    duration,
                    ssrc,
                    play_id: None,
                    auto_hangup: None,
                })
                .ok();
        });
        Ok(())
    }

    async fn stop(&self) -> Result<()> {
        if let Some(mut ws_sink) = self.ws_sink.lock().await.take() {
            ws_sink.close().await.ok();
        }
        self.cancel_token.cancel();
        Ok(())
    }

    async fn send_packet(&mut self, packet: &AudioFrame) -> Result<()> {
        let mut packet = packet.clone();
        if let Err(e) = self.processor_chain.process_frame(&mut packet) {
            warn!(track_id=%self.track_id, "processor_chain process_frame error: {:?}", e);
        }

        if let Some(ws_sink) = self.ws_sink.lock().await.as_mut() {
            if let Samples::PCM { samples } = &packet.samples {
                let mut buffer = self.buffer.lock().await;
                let bytes = samples_to_bytes(samples.as_slice());
                buffer.reserve(bytes.len());
                buffer.extend_from_slice(bytes.as_slice());
                while buffer.len() >= self.packet_size as usize {
                    let bytes = buffer.split_to(self.packet_size as usize).freeze();
                    let bytes = if packet.sample_rate == self.output_sample_rate {
                        bytes
                    } else {
                        let samples = bytes_to_samples(&bytes);
                        let resample =
                            resample(&samples, packet.sample_rate, self.output_sample_rate);
                        let bytes = samples_to_bytes(resample.as_slice());
                        Bytes::copy_from_slice(bytes.as_slice())
                    };
                    let bytes_len = bytes.len();
                    ws_sink.send(Message::Binary(bytes)).await?;
                    self.bytes_sent
                        .fetch_add(bytes_len as u64, Ordering::Relaxed);
                }
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn new_track(input_sample_rate: u32, output_sample_rate: u32) -> MediaPassTrack {
        MediaPassTrack::new(
            "session".to_string(),
            1,
            "track".to_string(),
            CancellationToken::new(),
            MediaPassOption::new(
                "ws://localhost".to_string(),
                input_sample_rate,
                output_sample_rate,
                None,
                None,
            ),
        )
    }

    #[test]
    fn zero_input_sample_rate_falls_back_to_output() {
        assert_eq!(new_track(0, 16000).config.samplerate, 16000);
    }

    #[test]
    fn explicit_input_sample_rate_is_preserved() {
        assert_eq!(new_track(8000, 16000).config.samplerate, 8000);
    }
}