Skip to main content

gemini_adk_fluent_rs/telephony/
twilio.rs

1//! Twilio Media Streams — a phone call as two channels of JSON text frames.
2//!
3//! Twilio's [Media Streams](https://www.twilio.com/docs/voice/media-streams)
4//! forks a live call's audio over a WebSocket: μ-law 8 kHz frames arrive as
5//! base64 inside JSON text messages, and JSON text messages you send play
6//! back to the caller. This module speaks that protocol and adapts it onto
7//! [`voice::pump`](crate::voice::pump) — so a governed Live session answers
8//! the phone with the same barge-in guarantees as a local microphone:
9//!
10//! - inbound `media` frames are μ-law-decoded to PCM16 @ 8 kHz and fed to the
11//!   pump, which resamples to the session's 16 kHz input;
12//! - session audio comes back from the pump at 8 kHz, is μ-law-encoded, and
13//!   sent as outbound `media` frames;
14//! - an interruption ([`Playback::Flush`](crate::voice::Playback)) becomes a
15//!   Twilio `clear` message, dropping every frame Twilio has buffered — the
16//!   telephone form of "stop talking the instant the caller does";
17//! - DTMF digits land in session state under [`KEY_DTMF`] / [`KEY_DTMF_HISTORY`],
18//!   where flow guards and watchers read them like any other fact.
19//!
20//! The bridge owns no socket. [`TwilioCall::attach`] returns a sender for the
21//! text frames Twilio delivers and a receiver of the text frames to forward
22//! back — wire them to any WebSocket server (see `examples/telephony` for an
23//! axum one). Raw SIP (no Twilio in the path) is out of scope here; that is
24//! the roadmap's `rsipstack` integration.
25
26use std::collections::HashMap;
27
28use base64::Engine as _;
29use serde::Deserialize;
30use tokio::sync::{mpsc, watch};
31use tokio::task::JoinHandle;
32
33use gemini_adk_rs::live::LiveHandle;
34
35use super::g711;
36use crate::voice::{Playback, VoicePump, pump};
37
38/// The sample rate of every Twilio Media Stream, both directions.
39pub const TWILIO_HZ: u32 = 8_000;
40
41// The state-key vocabulary is shared across every connector — see
42// [`super::bridge`]. Re-exported here so existing imports keep working.
43pub use super::bridge::{KEY_CALL_SID, KEY_DTMF, KEY_DTMF_HISTORY, KEY_STREAM_SID};
44
45// ── Inbound protocol (Twilio → us) ───────────────────────────────────────────
46
47/// Metadata delivered by Twilio's `start` frame when the stream opens.
48#[derive(Debug, Clone, Deserialize, Default, PartialEq)]
49#[serde(rename_all = "camelCase", default)]
50pub struct StartMeta {
51    /// The stream SID — required in every frame sent back to Twilio.
52    pub stream_sid: String,
53    /// The SID of the underlying voice call.
54    pub call_sid: String,
55    /// The Twilio account SID.
56    pub account_sid: String,
57    /// Which tracks are being forked (normally `["inbound"]`).
58    pub tracks: Vec<String>,
59    /// Audio format of the stream (normally `audio/x-mulaw` @ 8000 Hz mono).
60    pub media_format: MediaFormat,
61    /// `<Parameter>` values set on the `<Stream>` TwiML noun.
62    pub custom_parameters: HashMap<String, String>,
63}
64
65/// The audio encoding Twilio declares in the `start` frame.
66#[derive(Debug, Clone, Deserialize, Default, PartialEq)]
67#[serde(rename_all = "camelCase", default)]
68pub struct MediaFormat {
69    /// MIME-style encoding name, e.g. `audio/x-mulaw`.
70    pub encoding: String,
71    /// Sample rate in Hz (8000 for telephone audio).
72    pub sample_rate: u32,
73    /// Channel count (1 for a single forked track).
74    pub channels: u32,
75}
76
77#[derive(Debug, Clone, Deserialize)]
78#[serde(rename_all = "camelCase")]
79struct MediaPayload {
80    #[serde(default)]
81    track: String,
82    payload: String,
83}
84
85#[derive(Debug, Clone, Deserialize)]
86struct DtmfPayload {
87    digit: String,
88}
89
90#[derive(Debug, Clone, Deserialize)]
91struct MarkPayload {
92    name: String,
93}
94
95#[derive(Debug, Clone, Deserialize)]
96#[serde(tag = "event", rename_all = "lowercase")]
97enum RawInbound {
98    Connected {},
99    Start { start: StartMeta },
100    Media { media: MediaPayload },
101    Dtmf { dtmf: DtmfPayload },
102    Mark { mark: MarkPayload },
103    Stop {},
104}
105
106/// One decoded frame from Twilio, ready for application handling.
107#[derive(Debug, Clone, PartialEq)]
108pub enum Inbound {
109    /// The WebSocket handshake completed (`connected`). No stream SID yet.
110    Connected,
111    /// The stream opened; carries SIDs, tracks, format, and TwiML parameters.
112    Started(StartMeta),
113    /// One chunk of caller audio, μ-law-decoded to mono PCM16 @ 8 kHz.
114    Audio(Vec<i16>),
115    /// The caller pressed a DTMF key.
116    Dtmf(char),
117    /// Twilio confirms playback reached a `mark` we sent.
118    Mark(String),
119    /// The stream ended (call hung up or `<Stream>` stopped).
120    Stopped,
121    /// An event this version does not model (forward-compatible skip).
122    Ignored,
123}
124
125/// Parse one Twilio Media Streams text frame.
126///
127/// Unknown event types parse to [`Inbound::Ignored`] so a new Twilio event
128/// never breaks an existing bridge; malformed JSON is an error.
129pub fn parse_inbound(text: &str) -> Result<Inbound, TwilioError> {
130    let raw: RawInbound = match serde_json::from_str(text) {
131        Ok(raw) => raw,
132        Err(_) => {
133            // Distinguish "not JSON" from "JSON with an unknown event tag".
134            let value: serde_json::Value =
135                serde_json::from_str(text).map_err(TwilioError::Malformed)?;
136            return if value.get("event").is_some() {
137                Ok(Inbound::Ignored)
138            } else {
139                Err(TwilioError::NotAFrame)
140            };
141        }
142    };
143    Ok(match raw {
144        RawInbound::Connected {} => Inbound::Connected,
145        RawInbound::Start { start } => Inbound::Started(start),
146        RawInbound::Media { media } => {
147            // Only the caller's track feeds the session; if outbound audio is
148            // also forked (`tracks: ["both"]`), skip our own voice.
149            if !media.track.is_empty() && media.track != "inbound" {
150                return Ok(Inbound::Ignored);
151            }
152            let mulaw = base64::engine::general_purpose::STANDARD
153                .decode(media.payload.as_bytes())
154                .map_err(TwilioError::BadPayload)?;
155            Inbound::Audio(g711::decode_ulaw(&mulaw))
156        }
157        RawInbound::Dtmf { dtmf } => match dtmf.digit.chars().next() {
158            Some(digit) => Inbound::Dtmf(digit),
159            None => Inbound::Ignored,
160        },
161        RawInbound::Mark { mark } => Inbound::Mark(mark.name),
162        RawInbound::Stop {} => Inbound::Stopped,
163    })
164}
165
166/// Errors from parsing Twilio frames.
167#[derive(Debug)]
168pub enum TwilioError {
169    /// The text was not valid JSON.
170    Malformed(serde_json::Error),
171    /// The JSON carried no `event` field — not a Media Streams frame.
172    NotAFrame,
173    /// A `media` frame's payload was not valid base64.
174    BadPayload(base64::DecodeError),
175}
176
177impl std::fmt::Display for TwilioError {
178    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
179        match self {
180            Self::Malformed(e) => write!(f, "malformed Twilio frame: {e}"),
181            Self::NotAFrame => write!(f, "JSON without an event field"),
182            Self::BadPayload(e) => write!(f, "invalid base64 media payload: {e}"),
183        }
184    }
185}
186
187impl std::error::Error for TwilioError {}
188
189// ── Outbound protocol (us → Twilio) ──────────────────────────────────────────
190
191/// Build an outbound `media` frame from mono PCM16 samples @ 8 kHz.
192pub fn media_frame(stream_sid: &str, samples: &[i16]) -> String {
193    let payload = base64::engine::general_purpose::STANDARD.encode(g711::encode_ulaw(samples));
194    serde_json::json!({
195        "event": "media",
196        "streamSid": stream_sid,
197        "media": { "payload": payload },
198    })
199    .to_string()
200}
201
202/// Build a `clear` frame — Twilio drops all buffered outbound audio.
203/// This is barge-in on the telephone: send it on [`Playback::Flush`].
204pub fn clear_frame(stream_sid: &str) -> String {
205    serde_json::json!({ "event": "clear", "streamSid": stream_sid }).to_string()
206}
207
208/// Build a `mark` frame — Twilio echoes it back once playback reaches it.
209pub fn mark_frame(stream_sid: &str, name: &str) -> String {
210    serde_json::json!({
211        "event": "mark",
212        "streamSid": stream_sid,
213        "mark": { "name": name },
214    })
215    .to_string()
216}
217
218// ── Call bridge ──────────────────────────────────────────────────────────────
219
220/// 20 ms of audio at Twilio's 8 kHz: the frame size the network expects.
221const FRAME_SAMPLES: usize = 160;
222const FRAME_DURATION: std::time::Duration = std::time::Duration::from_millis(20);
223/// How long to wait for more audio before padding a partial frame.
224const TAIL_WAIT: std::time::Duration = std::time::Duration::from_millis(40);
225
226/// State key set on barge-in: how many milliseconds of agent audio had been
227/// sent but not yet played when the caller interrupted. The caller never
228/// heard that part of the reply.
229pub const KEY_UNPLAYED_MS: &str = "telephony:unplayed_ms";
230
231/// Cuts agent audio into 20 ms frames and keeps the line's playout clock.
232#[derive(Debug, Default)]
233struct Framer {
234    /// A partial frame waiting for the rest of its 20 ms.
235    pending: Vec<i16>,
236    /// When the audio sent so far finishes playing on the line.
237    plays_until: Option<std::time::Instant>,
238}
239
240impl Framer {
241    fn is_idle(&self) -> bool {
242        self.pending.is_empty()
243    }
244
245    /// Queue audio; returns the whole frames now ready to send.
246    fn push(&mut self, samples: &[i16], now: std::time::Instant) -> Vec<Vec<i16>> {
247        self.pending.extend_from_slice(samples);
248        let mut frames = Vec::new();
249        while self.pending.len() >= FRAME_SAMPLES {
250            frames.push(self.pending.drain(..FRAME_SAMPLES).collect());
251            let from = self.plays_until.map_or(now, |t| t.max(now));
252            self.plays_until = Some(from + FRAME_DURATION);
253        }
254        frames
255    }
256
257    /// Pad the partial frame with silence, so the next `push` sends it.
258    fn pad_tail(&mut self) {
259        if !self.pending.is_empty() {
260            self.pending.resize(FRAME_SAMPLES, 0);
261        }
262    }
263
264    /// Barge-in: drop what is queued; returns how much sent audio had not
265    /// played yet.
266    fn flush(&mut self, now: std::time::Instant) -> std::time::Duration {
267        self.pending.clear();
268        let unplayed = self.plays_until.map_or(std::time::Duration::ZERO, |t| {
269            t.saturating_duration_since(now)
270        });
271        self.plays_until = Some(now);
272        unplayed
273    }
274}
275
276/// Options for [`TwilioCall::attach_with`].
277#[derive(Clone, Default)]
278pub struct CallOptions {
279    /// Record the call in stereo (caller left, agent right), as heard.
280    pub recorder: Option<std::sync::Arc<super::recorder::CallRecorder>>,
281    /// Also detect keypresses in the audio. Twilio reports keypresses as
282    /// `dtmf` events, so this is off by default to avoid counting twice.
283    pub in_band_dtmf: bool,
284}
285
286/// A live phone call attached to a session — the telephone counterpart of
287/// `Talk::talk`.
288///
289/// [`attach`](TwilioCall::attach) wires the session's [`pump`] to a pair of
290/// text-frame channels speaking the Media Streams protocol. The caller owns
291/// the WebSocket: forward every text message Twilio delivers into
292/// [`from_twilio`](TwilioCall::from_twilio), and forward every message from
293/// [`to_twilio`](TwilioCall::to_twilio) back over the socket.
294///
295/// ```ignore
296/// // `ignore`: `ws` is the application's Twilio WebSocket (see examples/telephony).
297/// let session = Live::builder()
298///     .instruction("You are the front desk. Answer the call.")
299///     .greeting("Greet the caller.")
300///     .connect_from_env().await?;
301/// let mut call = TwilioCall::attach(&session);
302/// loop {
303///     tokio::select! {
304///         Some(msg) = ws.recv() => call.from_twilio.send(msg.into_text()?).await?,
305///         Some(out) = call.to_twilio.recv() => ws.send(Message::Text(out)).await?,
306///         else => break,
307///     }
308/// }
309/// ```
310pub struct TwilioCall {
311    /// Feed Twilio's inbound WebSocket text frames here.
312    pub from_twilio: mpsc::Sender<String>,
313    /// Text frames to send back to Twilio over the WebSocket.
314    pub to_twilio: mpsc::Receiver<String>,
315    pump: VoicePump,
316    inbound_task: JoinHandle<()>,
317    outbound_task: JoinHandle<()>,
318}
319
320impl TwilioCall {
321    /// Attach a Twilio Media Stream to a connected session, with the
322    /// default [`CallOptions`].
323    ///
324    /// Audio starts flowing once Twilio's `start` frame arrives (outbound
325    /// frames need its stream SID; audio generated before it is dropped —
326    /// there is no call to play it into yet). Stream metadata and DTMF
327    /// digits are written into session state under the `telephony:` keys.
328    pub fn attach(handle: &LiveHandle) -> TwilioCall {
329        Self::attach_with(handle, CallOptions::default())
330    }
331
332    /// Attach a Twilio Media Stream to a connected session.
333    ///
334    /// Beyond [`attach`](Self::attach):
335    /// - the caller's audio passes through a
336    ///   [`KeypadGuard`](super::bridge::KeypadGuard), so keypad tones never
337    ///   reach the model and a masked keypad silences the caller;
338    /// - the agent's audio goes out in 20 ms frames, as the network expects,
339    ///   with the last partial frame padded once the model pauses;
340    /// - on barge-in, [`KEY_UNPLAYED_MS`] records how much queued agent
341    ///   audio the caller never heard;
342    /// - with [`CallOptions::recorder`], the call is recorded in stereo as
343    ///   heard.
344    pub fn attach_with(handle: &LiveHandle, options: CallOptions) -> TwilioCall {
345        let (from_tx, mut from_rx) = mpsc::channel::<String>(64);
346        let (to_tx, to_rx) = mpsc::channel::<String>(64);
347        let (mic_tx, mic_rx) = mpsc::channel::<Vec<i16>>(64);
348        let (speaker_tx, mut speaker_rx) = mpsc::channel::<Playback>(64);
349        let (sid_tx, sid_rx) = watch::channel::<Option<String>>(None);
350
351        let voice_pump = pump(handle, mic_rx, TWILIO_HZ, speaker_tx, TWILIO_HZ);
352
353        let state = handle.state().clone();
354        let mut guard = super::bridge::KeypadGuard::new(state.clone(), TWILIO_HZ)
355            .record_in_band(options.in_band_dtmf);
356        let inbound_recorder = options.recorder.clone();
357        let inbound_task = tokio::spawn(async move {
358            use crate::voice::InputAudioProcessor as _;
359            while let Some(text) = from_rx.recv().await {
360                match parse_inbound(&text) {
361                    Ok(Inbound::Audio(mut samples)) => {
362                        guard.process_frame(&mut samples);
363                        if let Some(recorder) = &inbound_recorder {
364                            recorder.caller(&samples);
365                        }
366                        if mic_tx.send(samples).await.is_err() {
367                            break;
368                        }
369                    }
370                    Ok(Inbound::Started(meta)) => {
371                        let _ = state.set(KEY_CALL_SID, meta.call_sid.clone());
372                        let _ = state.set(KEY_STREAM_SID, meta.stream_sid.clone());
373                        let _ = sid_tx.send(Some(meta.stream_sid));
374                    }
375                    Ok(Inbound::Dtmf(digit)) => super::bridge::record_dtmf(&state, digit),
376                    Ok(Inbound::Stopped) => break,
377                    Ok(Inbound::Connected | Inbound::Mark(_) | Inbound::Ignored) => {}
378                    Err(err) => tracing::warn!("dropping unparseable Twilio frame: {err}"),
379                }
380            }
381        });
382
383        let out_state = handle.state().clone();
384        let outbound_recorder = options.recorder;
385        let outbound_task = tokio::spawn(async move {
386            let mut framer = Framer::default();
387            loop {
388                let next = if framer.is_idle() {
389                    speaker_rx.recv().await
390                } else {
391                    match tokio::time::timeout(TAIL_WAIT, speaker_rx.recv()).await {
392                        Ok(next) => next,
393                        // The model paused mid-frame: pad and send the tail.
394                        Err(_) => {
395                            framer.pad_tail();
396                            Some(Playback::Chunk(Vec::new()))
397                        }
398                    }
399                };
400                let Some(playback) = next else { break };
401                // Frames are unsendable until `start` delivers the SID.
402                let Some(sid) = sid_rx.borrow().clone() else {
403                    continue;
404                };
405                let now = std::time::Instant::now();
406                let mut frames = Vec::new();
407                match playback {
408                    Playback::Chunk(samples) => {
409                        for frame in framer.push(&samples, now) {
410                            if let Some(recorder) = &outbound_recorder {
411                                recorder.agent(&frame);
412                            }
413                            frames.push(media_frame(&sid, &frame));
414                        }
415                    }
416                    Playback::Flush => {
417                        let unplayed = framer.flush(now);
418                        let _ = out_state.set(KEY_UNPLAYED_MS, unplayed.as_millis() as u64);
419                        if let Some(recorder) = &outbound_recorder {
420                            recorder.flush();
421                        }
422                        frames.push(clear_frame(&sid));
423                    }
424                }
425                for frame in frames {
426                    if to_tx.send(frame).await.is_err() {
427                        return;
428                    }
429                }
430            }
431        });
432
433        TwilioCall {
434            from_twilio: from_tx,
435            to_twilio: to_rx,
436            pump: voice_pump,
437            inbound_task,
438            outbound_task,
439        }
440    }
441
442    /// Wait until the call ends (stream stopped, session closed, or the
443    /// WebSocket side dropped the channels).
444    pub async fn join(self) {
445        let _ = self.inbound_task.await;
446        let _ = self.outbound_task.await;
447        self.pump.join().await;
448    }
449
450    /// Tear the bridge down immediately.
451    pub fn abort(&self) {
452        self.inbound_task.abort();
453        self.outbound_task.abort();
454        self.pump.abort();
455    }
456}
457
458#[cfg(test)]
459mod tests {
460    use super::*;
461
462    #[test]
463    fn agent_audio_goes_out_in_20ms_frames_on_a_playout_clock() {
464        let t0 = std::time::Instant::now();
465        let mut framer = Framer::default();
466        // 50 ms of audio in one burst: two whole frames now, 10 ms pending.
467        let frames = framer.push(&[1; 400], t0);
468        assert_eq!(frames.len(), 2);
469        assert!(frames.iter().all(|f| f.len() == FRAME_SAMPLES));
470        assert!(!framer.is_idle());
471        // The model pauses: the tail is padded to a full frame.
472        framer.pad_tail();
473        let tail = framer.push(&[], t0);
474        assert_eq!(tail.len(), 1);
475        assert_eq!(&tail[0][..80], &[1; 80]);
476        assert_eq!(&tail[0][80..], &[0; 80]);
477        // 60 ms were sent at t0; a barge-in 25 ms later cuts 35 ms.
478        let unplayed = framer.flush(t0 + std::time::Duration::from_millis(25));
479        assert_eq!(unplayed, std::time::Duration::from_millis(35));
480        assert!(framer.is_idle());
481    }
482
483    #[test]
484    fn parses_the_start_frame() {
485        let text = r#"{
486            "event": "start", "sequenceNumber": "1", "streamSid": "MZxyz",
487            "start": {
488                "accountSid": "ACabc", "streamSid": "MZxyz", "callSid": "CAdef",
489                "tracks": ["inbound"],
490                "mediaFormat": {"encoding": "audio/x-mulaw", "sampleRate": 8000, "channels": 1},
491                "customParameters": {"agent": "front-desk"}
492            }
493        }"#;
494        match parse_inbound(text).unwrap() {
495            Inbound::Started(meta) => {
496                assert_eq!(meta.stream_sid, "MZxyz");
497                assert_eq!(meta.call_sid, "CAdef");
498                assert_eq!(meta.media_format.sample_rate, 8000);
499                assert_eq!(meta.custom_parameters["agent"], "front-desk");
500            }
501            other => panic!("expected Started, got {other:?}"),
502        }
503    }
504
505    #[test]
506    fn media_frames_decode_to_pcm() {
507        // 0xFF is μ-law silence; four bytes → four zero samples.
508        let payload = base64::engine::general_purpose::STANDARD.encode([0xFFu8; 4]);
509        let text = format!(
510            r#"{{"event":"media","streamSid":"MZ1","media":{{"track":"inbound","chunk":"1","timestamp":"5","payload":"{payload}"}}}}"#
511        );
512        assert_eq!(parse_inbound(&text).unwrap(), Inbound::Audio(vec![0i16; 4]));
513    }
514
515    #[test]
516    fn outbound_track_media_is_skipped() {
517        let payload = base64::engine::general_purpose::STANDARD.encode([0xFFu8; 4]);
518        let text = format!(
519            r#"{{"event":"media","streamSid":"MZ1","media":{{"track":"outbound","payload":"{payload}"}}}}"#
520        );
521        assert_eq!(parse_inbound(&text).unwrap(), Inbound::Ignored);
522    }
523
524    #[test]
525    fn dtmf_marks_stop_and_unknown_events() {
526        assert_eq!(
527            parse_inbound(
528                r#"{"event":"dtmf","streamSid":"MZ1","dtmf":{"track":"inbound_track","digit":"7"}}"#
529            )
530            .unwrap(),
531            Inbound::Dtmf('7')
532        );
533        assert_eq!(
534            parse_inbound(r#"{"event":"mark","streamSid":"MZ1","mark":{"name":"m1"}}"#).unwrap(),
535            Inbound::Mark("m1".into())
536        );
537        assert_eq!(
538            parse_inbound(r#"{"event":"stop","streamSid":"MZ1","stop":{}}"#).unwrap(),
539            Inbound::Stopped
540        );
541        assert_eq!(
542            parse_inbound(r#"{"event":"connected","protocol":"Call","version":"1.0.0"}"#).unwrap(),
543            Inbound::Connected
544        );
545        // Forward compatibility: an event we don't model is skipped, not fatal.
546        assert_eq!(
547            parse_inbound(r#"{"event":"totally-new-thing"}"#).unwrap(),
548            Inbound::Ignored
549        );
550        assert!(parse_inbound("not json").is_err());
551        assert!(parse_inbound(r#"{"no_event": true}"#).is_err());
552    }
553
554    #[test]
555    fn media_frame_round_trips_through_the_codec() {
556        let samples = vec![0i16, 1000, -1000, 8000];
557        let frame = media_frame("MZ1", &samples);
558        let value: serde_json::Value = serde_json::from_str(&frame).unwrap();
559        assert_eq!(value["event"], "media");
560        assert_eq!(value["streamSid"], "MZ1");
561        let mulaw = base64::engine::general_purpose::STANDARD
562            .decode(value["media"]["payload"].as_str().unwrap())
563            .unwrap();
564        let decoded = g711::decode_ulaw(&mulaw);
565        assert_eq!(decoded.len(), samples.len());
566        // Companded round-trip: close, not exact.
567        for (orig, rt) in samples.iter().zip(&decoded) {
568            assert!(((orig - rt) as i32).abs() <= (orig.unsigned_abs() as i32 / 16).max(16));
569        }
570    }
571
572    #[test]
573    fn clear_and_mark_frames_have_the_wire_shape() {
574        let clear: serde_json::Value = serde_json::from_str(&clear_frame("MZ9")).unwrap();
575        assert_eq!(
576            clear,
577            serde_json::json!({"event": "clear", "streamSid": "MZ9"})
578        );
579        let mark: serde_json::Value = serde_json::from_str(&mark_frame("MZ9", "done")).unwrap();
580        assert_eq!(
581            mark,
582            serde_json::json!({"event": "mark", "streamSid": "MZ9", "mark": {"name": "done"}})
583        );
584    }
585}