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
use std::sync::Arc;
use axum::extract::ws::{Message, WebSocket};
use tokio::sync::mpsc;
use crate::frames::{AudioRawData, Frame, FrameDirection, FrameInner, FrameProcessor, SystemFrame};
use crate::serializers::{FrameSerializer, SerializedInput, SerializedOutput};
use crate::transport::{BaseTransport, TransportParams};
use crate::transport::incoming::dispatch_text_message;
use crate::transport::output::OutputMessage;
// ---------------------------------------------------------------------------
// WebSocketParams
// ---------------------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct WebSocketParams {
pub transport: TransportParams,
}
impl Default for WebSocketParams {
fn default() -> Self {
Self {
transport: TransportParams {
audio_in_enabled: true,
audio_in_sample_rate: Some(16_000),
audio_in_channels: 1,
audio_in_passthrough: true,
audio_in_stream_on_start: true,
..TransportParams::default()
},
}
}
}
// ---------------------------------------------------------------------------
// WebSocketTransport
// ---------------------------------------------------------------------------
pub struct WebSocketTransport {
base: Arc<BaseTransport>,
audio_out_rx: std::sync::Mutex<Option<mpsc::Receiver<OutputMessage>>>,
/// Optional wire-protocol serializer (e.g. Twilio). When set, all socket
/// I/O is routed through it instead of the raw-PCM path.
serializer: std::sync::Mutex<Option<Box<dyn FrameSerializer>>>,
audio_in_sample_rate: u32,
audio_out_sample_rate: u32,
}
const AUDIO_OUT_CHANNEL_CAP: usize = 150;
impl WebSocketTransport {
pub fn new(name: &str, params: WebSocketParams) -> Self {
let audio_in_sample_rate = params.transport.audio_in_sample_rate.unwrap_or(16_000);
let audio_out_sample_rate =
params.transport.audio_out_sample_rate.unwrap_or(audio_in_sample_rate);
let base = Arc::new(BaseTransport::new(name, params.transport));
let (audio_out_tx, audio_out_rx) = mpsc::channel::<OutputMessage>(AUDIO_OUT_CHANNEL_CAP);
base.set_audio_out_tx(audio_out_tx);
Self {
base,
audio_out_rx: std::sync::Mutex::new(Some(audio_out_rx)),
serializer: std::sync::Mutex::new(None),
audio_in_sample_rate,
audio_out_sample_rate,
}
}
pub fn input(&self) -> FrameProcessor {
self.base.input()
}
pub fn output(&self) -> FrameProcessor {
self.base.output()
}
/// Install a wire-protocol serializer. Call before [`run_socket`](Self::run_socket).
///
/// With a serializer set, incoming provider messages are decoded via
/// [`FrameSerializer::deserialize`] and outgoing audio/interruptions are
/// encoded via [`FrameSerializer::serialize`]; without one, the transport
/// uses its raw 16 kHz-PCM path.
pub fn set_serializer(&self, serializer: Box<dyn FrameSerializer>) {
*self.serializer.lock().unwrap() = Some(serializer);
}
/// Drive the WebSocket connection until it closes.
///
/// Arm 1 — `socket.recv()`: incoming messages from the client.
///
/// - With a serializer: every Text/Binary message is passed to
/// `deserialize`; audio frames go to the input transport, other frames
/// (e.g. DTMF) are pushed downstream.
/// - Without a serializer: Binary → raw 16 kHz PCM; Text → RAVI/control
/// dispatch.
///
/// Arm 2 — `audio_out_rx.recv()`: outgoing pipeline messages.
///
/// - With a serializer: `Audio`/`Interruption` are re-framed and
/// `serialize`d (Twilio `media`/`clear` events).
/// - Without a serializer: `Audio` → binary frame, `Interruption` → JSON
/// clear marker.
///
/// On close, a serializer's `serialize(EndFrame)` is invoked to drive
/// provider-side teardown (e.g. Twilio auto hang-up).
pub async fn run_socket(
&self,
mut socket: WebSocket,
push_tx: mpsc::Sender<(Frame, FrameDirection)>,
) {
let mut audio_out_rx = self
.audio_out_rx
.lock()
.unwrap()
.take()
.expect("run_socket called more than once on the same WebSocketTransport");
let mut serializer = self.serializer.lock().unwrap().take();
let base = self.base.clone();
if let Some(ser) = serializer.as_mut() {
ser.setup(self.audio_in_sample_rate, self.audio_out_sample_rate).await;
}
loop {
tokio::select! {
// ----------------------------------------------------------------
// Arm 1: incoming messages → pipeline
// ----------------------------------------------------------------
msg = socket.recv() => {
match msg {
Some(Ok(Message::Binary(bytes))) => {
if let Some(ser) = serializer.as_mut() {
let input = SerializedInput::Binary(bytes.to_vec());
if let Some(frame) = ser.deserialize(&input).await {
Self::dispatch_incoming_frame(&base, &push_tx, frame).await;
}
} else {
let data = AudioRawData::new(bytes.to_vec(), 16_000, 1);
base.push_audio_frame(data).await;
}
}
Some(Ok(Message::Text(text))) => {
if let Some(ser) = serializer.as_mut() {
let input = SerializedInput::Text(text.to_string());
if let Some(frame) = ser.deserialize(&input).await {
Self::dispatch_incoming_frame(&base, &push_tx, frame).await;
}
} else {
dispatch_text_message(&text, &push_tx).await;
}
}
Some(Ok(Message::Close(_))) | None => {
log::debug!("WebSocketTransport: client closed connection");
break;
}
Some(Ok(_)) => {} // ping / pong — ignore
Some(Err(e)) => {
log::warn!("WebSocketTransport: socket error: {}", e);
break;
}
}
}
// ----------------------------------------------------------------
// Arm 2: outgoing pipeline messages → client
// ----------------------------------------------------------------
output_msg = audio_out_rx.recv() => {
match output_msg {
Some(OutputMessage::Audio(bytes)) => {
if let Some(ser) = serializer.as_mut() {
let frame =
Frame::output_audio(bytes, self.audio_out_sample_rate, 1);
if let Some(out) = ser.serialize(&frame).await {
if Self::send_serialized(&mut socket, out).await.is_err() {
log::warn!("WebSocketTransport: failed to send audio");
break;
}
}
} else if socket.send(Message::Binary(bytes.into())).await.is_err() {
log::warn!("WebSocketTransport: failed to send audio");
break;
}
}
Some(OutputMessage::Text(json)) => {
// RAVI protocol messages (bot-ready, transcriptions, etc.)
if socket.send(Message::Text(json.into())).await.is_err() {
log::warn!("WebSocketTransport: failed to send RAVI text message");
break;
}
}
Some(OutputMessage::Interruption) => {
// Drain stale audio chunks queued before the marker.
while let Ok(queued) = audio_out_rx.try_recv() {
match queued {
OutputMessage::Audio(_) => {} // discard
OutputMessage::Interruption => break,
OutputMessage::Text(_) => {} // discard (shouldn't queue during interruption)
}
}
let send_result = if let Some(ser) = serializer.as_mut() {
match ser.serialize(&Frame::interruption()).await {
Some(out) => Self::send_serialized(&mut socket, out).await,
None => Ok(()),
}
} else {
socket
.send(Message::Text(r#"{"type":"interruption"}"#.into()))
.await
};
if send_result.is_err() {
log::warn!("WebSocketTransport: failed to send interruption");
break;
}
log::debug!("WebSocketTransport: sent interruption to client");
}
None => break, // pipeline shut down
}
}
}
}
// Give the serializer a chance to tear down the provider session
// (e.g. Twilio auto hang-up on EndFrame). Any serialized output here is
// best-effort — the socket may already be closing.
if let Some(ser) = serializer.as_mut() {
if let Some(out) = ser.serialize(&Frame::end()).await {
let _ = Self::send_serialized(&mut socket, out).await;
}
}
let _ = push_tx
.send((Frame::end(), FrameDirection::Downstream))
.await;
}
/// Route a deserialized incoming frame: audio to the input transport,
/// everything else (DTMF, control) downstream into the pipeline.
async fn dispatch_incoming_frame(
base: &BaseTransport,
push_tx: &mpsc::Sender<(Frame, FrameDirection)>,
frame: Frame,
) {
match frame.inner {
FrameInner::System(SystemFrame::InputAudioRaw(data)) => {
base.push_audio_frame(data).await;
}
_ => {
let _ = push_tx.send((frame, FrameDirection::Downstream)).await;
}
}
}
/// Send a serializer's output over the socket as the matching frame type.
async fn send_serialized(
socket: &mut WebSocket,
out: SerializedOutput,
) -> Result<(), axum::Error> {
match out {
SerializedOutput::Text(t) => socket.send(Message::Text(t.into())).await,
SerializedOutput::Binary(b) => socket.send(Message::Binary(b.into())).await,
}
}
}