dv-pipecat-ai 0.0.82.dev815__py3-none-any.whl → 0.0.82.dev857__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of dv-pipecat-ai might be problematic. Click here for more details.

Files changed (106) hide show
  1. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/METADATA +8 -3
  2. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/RECORD +106 -79
  3. pipecat/adapters/base_llm_adapter.py +44 -6
  4. pipecat/adapters/services/anthropic_adapter.py +302 -2
  5. pipecat/adapters/services/aws_nova_sonic_adapter.py +40 -2
  6. pipecat/adapters/services/bedrock_adapter.py +40 -2
  7. pipecat/adapters/services/gemini_adapter.py +276 -6
  8. pipecat/adapters/services/open_ai_adapter.py +88 -7
  9. pipecat/adapters/services/open_ai_realtime_adapter.py +39 -1
  10. pipecat/audio/dtmf/__init__.py +0 -0
  11. pipecat/audio/dtmf/types.py +47 -0
  12. pipecat/audio/dtmf/utils.py +70 -0
  13. pipecat/audio/filters/aic_filter.py +199 -0
  14. pipecat/audio/utils.py +9 -7
  15. pipecat/extensions/ivr/__init__.py +0 -0
  16. pipecat/extensions/ivr/ivr_navigator.py +452 -0
  17. pipecat/frames/frames.py +156 -43
  18. pipecat/pipeline/llm_switcher.py +76 -0
  19. pipecat/pipeline/parallel_pipeline.py +3 -3
  20. pipecat/pipeline/service_switcher.py +144 -0
  21. pipecat/pipeline/task.py +68 -28
  22. pipecat/pipeline/task_observer.py +10 -0
  23. pipecat/processors/aggregators/dtmf_aggregator.py +2 -2
  24. pipecat/processors/aggregators/llm_context.py +277 -0
  25. pipecat/processors/aggregators/llm_response.py +48 -15
  26. pipecat/processors/aggregators/llm_response_universal.py +840 -0
  27. pipecat/processors/aggregators/openai_llm_context.py +3 -3
  28. pipecat/processors/dtmf_aggregator.py +0 -2
  29. pipecat/processors/filters/stt_mute_filter.py +0 -2
  30. pipecat/processors/frame_processor.py +18 -11
  31. pipecat/processors/frameworks/rtvi.py +17 -10
  32. pipecat/processors/metrics/sentry.py +2 -0
  33. pipecat/runner/daily.py +137 -36
  34. pipecat/runner/run.py +1 -1
  35. pipecat/runner/utils.py +7 -7
  36. pipecat/serializers/asterisk.py +20 -4
  37. pipecat/serializers/exotel.py +1 -1
  38. pipecat/serializers/plivo.py +1 -1
  39. pipecat/serializers/telnyx.py +1 -1
  40. pipecat/serializers/twilio.py +1 -1
  41. pipecat/services/__init__.py +2 -2
  42. pipecat/services/anthropic/llm.py +113 -28
  43. pipecat/services/asyncai/tts.py +4 -0
  44. pipecat/services/aws/llm.py +82 -8
  45. pipecat/services/aws/tts.py +0 -10
  46. pipecat/services/aws_nova_sonic/aws.py +5 -0
  47. pipecat/services/cartesia/tts.py +28 -16
  48. pipecat/services/cerebras/llm.py +15 -10
  49. pipecat/services/deepgram/stt.py +8 -0
  50. pipecat/services/deepseek/llm.py +13 -8
  51. pipecat/services/fireworks/llm.py +13 -8
  52. pipecat/services/fish/tts.py +8 -6
  53. pipecat/services/gemini_multimodal_live/gemini.py +5 -0
  54. pipecat/services/gladia/config.py +7 -1
  55. pipecat/services/gladia/stt.py +23 -15
  56. pipecat/services/google/llm.py +159 -59
  57. pipecat/services/google/llm_openai.py +18 -3
  58. pipecat/services/grok/llm.py +2 -1
  59. pipecat/services/llm_service.py +38 -3
  60. pipecat/services/mem0/memory.py +2 -1
  61. pipecat/services/mistral/llm.py +5 -6
  62. pipecat/services/nim/llm.py +2 -1
  63. pipecat/services/openai/base_llm.py +88 -26
  64. pipecat/services/openai/image.py +6 -1
  65. pipecat/services/openai_realtime_beta/openai.py +5 -2
  66. pipecat/services/openpipe/llm.py +6 -8
  67. pipecat/services/perplexity/llm.py +13 -8
  68. pipecat/services/playht/tts.py +9 -6
  69. pipecat/services/rime/tts.py +1 -1
  70. pipecat/services/sambanova/llm.py +18 -13
  71. pipecat/services/sarvam/tts.py +415 -10
  72. pipecat/services/speechmatics/stt.py +2 -2
  73. pipecat/services/tavus/video.py +1 -1
  74. pipecat/services/tts_service.py +15 -5
  75. pipecat/services/vistaar/llm.py +2 -5
  76. pipecat/transports/base_input.py +32 -19
  77. pipecat/transports/base_output.py +39 -5
  78. pipecat/transports/daily/__init__.py +0 -0
  79. pipecat/transports/daily/transport.py +2371 -0
  80. pipecat/transports/daily/utils.py +410 -0
  81. pipecat/transports/livekit/__init__.py +0 -0
  82. pipecat/transports/livekit/transport.py +1042 -0
  83. pipecat/transports/network/fastapi_websocket.py +12 -546
  84. pipecat/transports/network/small_webrtc.py +12 -922
  85. pipecat/transports/network/webrtc_connection.py +9 -595
  86. pipecat/transports/network/websocket_client.py +12 -481
  87. pipecat/transports/network/websocket_server.py +12 -487
  88. pipecat/transports/services/daily.py +9 -2334
  89. pipecat/transports/services/helpers/daily_rest.py +12 -396
  90. pipecat/transports/services/livekit.py +12 -975
  91. pipecat/transports/services/tavus.py +12 -757
  92. pipecat/transports/smallwebrtc/__init__.py +0 -0
  93. pipecat/transports/smallwebrtc/connection.py +612 -0
  94. pipecat/transports/smallwebrtc/transport.py +936 -0
  95. pipecat/transports/tavus/__init__.py +0 -0
  96. pipecat/transports/tavus/transport.py +770 -0
  97. pipecat/transports/websocket/__init__.py +0 -0
  98. pipecat/transports/websocket/client.py +494 -0
  99. pipecat/transports/websocket/fastapi.py +559 -0
  100. pipecat/transports/websocket/server.py +500 -0
  101. pipecat/transports/whatsapp/__init__.py +0 -0
  102. pipecat/transports/whatsapp/api.py +345 -0
  103. pipecat/transports/whatsapp/client.py +364 -0
  104. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/WHEEL +0 -0
  105. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/licenses/LICENSE +0 -0
  106. {dv_pipecat_ai-0.0.82.dev815.dist-info → dv_pipecat_ai-0.0.82.dev857.dist-info}/top_level.txt +0 -0
@@ -0,0 +1,936 @@
1
+ #
2
+ # Copyright (c) 2024–2025, Daily
3
+ #
4
+ # SPDX-License-Identifier: BSD 2-Clause License
5
+ #
6
+
7
+ """Small WebRTC transport implementation for Pipecat.
8
+
9
+ This module provides a WebRTC transport implementation using aiortc for
10
+ real-time audio and video communication. It supports bidirectional media
11
+ streaming, application messaging, and client connection management.
12
+ """
13
+
14
+ import asyncio
15
+ import fractions
16
+ import time
17
+ from collections import deque
18
+ from typing import Any, Awaitable, Callable, Optional
19
+
20
+ import numpy as np
21
+ from loguru import logger
22
+ from pydantic import BaseModel
23
+
24
+ from pipecat.frames.frames import (
25
+ CancelFrame,
26
+ EndFrame,
27
+ Frame,
28
+ InputAudioRawFrame,
29
+ InputTransportMessageUrgentFrame,
30
+ OutputAudioRawFrame,
31
+ OutputImageRawFrame,
32
+ SpriteFrame,
33
+ StartFrame,
34
+ TransportMessageFrame,
35
+ TransportMessageUrgentFrame,
36
+ UserImageRawFrame,
37
+ UserImageRequestFrame,
38
+ )
39
+ from pipecat.processors.frame_processor import FrameDirection
40
+ from pipecat.transports.base_input import BaseInputTransport
41
+ from pipecat.transports.base_output import BaseOutputTransport
42
+ from pipecat.transports.base_transport import BaseTransport, TransportParams
43
+ from pipecat.transports.smallwebrtc.connection import SmallWebRTCConnection
44
+
45
+ try:
46
+ import cv2
47
+ from aiortc import VideoStreamTrack
48
+ from aiortc.mediastreams import AudioStreamTrack, MediaStreamError
49
+ from av import AudioFrame, AudioResampler, VideoFrame
50
+ except ModuleNotFoundError as e:
51
+ logger.error(f"Exception: {e}")
52
+ logger.error("In order to use the SmallWebRTC, you need to `pip install pipecat-ai[webrtc]`.")
53
+ raise Exception(f"Missing module: {e}")
54
+
55
+ CAM_VIDEO_SOURCE = "camera"
56
+ SCREEN_VIDEO_SOURCE = "screenVideo"
57
+ MIC_AUDIO_SOURCE = "microphone"
58
+
59
+
60
+ class SmallWebRTCCallbacks(BaseModel):
61
+ """Callback handlers for SmallWebRTC events.
62
+
63
+ Parameters:
64
+ on_app_message: Called when an application message is received.
65
+ on_client_connected: Called when a client establishes connection.
66
+ on_client_disconnected: Called when a client disconnects.
67
+ """
68
+
69
+ on_app_message: Callable[[Any], Awaitable[None]]
70
+ on_client_connected: Callable[[SmallWebRTCConnection], Awaitable[None]]
71
+ on_client_disconnected: Callable[[SmallWebRTCConnection], Awaitable[None]]
72
+
73
+
74
+ class RawAudioTrack(AudioStreamTrack):
75
+ """Custom audio stream track for WebRTC output.
76
+
77
+ Handles audio frame generation and timing for WebRTC transmission,
78
+ supporting queued audio data with proper synchronization.
79
+ """
80
+
81
+ def __init__(self, sample_rate):
82
+ """Initialize the raw audio track.
83
+
84
+ Args:
85
+ sample_rate: The audio sample rate in Hz.
86
+ """
87
+ super().__init__()
88
+ self._sample_rate = sample_rate
89
+ self._samples_per_10ms = sample_rate * 10 // 1000
90
+ self._bytes_per_10ms = self._samples_per_10ms * 2 # 16-bit (2 bytes per sample)
91
+ self._timestamp = 0
92
+ self._start = time.time()
93
+ # Queue of (bytes, future), broken into 10ms sub chunks as needed
94
+ self._chunk_queue = deque()
95
+
96
+ def add_audio_bytes(self, audio_bytes: bytes):
97
+ """Add audio bytes to the buffer for transmission.
98
+
99
+ Args:
100
+ audio_bytes: Raw audio data to queue for transmission.
101
+
102
+ Returns:
103
+ A Future that completes when the data is processed.
104
+
105
+ Raises:
106
+ ValueError: If audio bytes are not a multiple of 10ms size.
107
+ """
108
+ if len(audio_bytes) % self._bytes_per_10ms != 0:
109
+ raise ValueError("Audio bytes must be a multiple of 10ms size.")
110
+ future = asyncio.get_running_loop().create_future()
111
+
112
+ # Break input into 10ms chunks
113
+ for i in range(0, len(audio_bytes), self._bytes_per_10ms):
114
+ chunk = audio_bytes[i : i + self._bytes_per_10ms]
115
+ # Only the last chunk carries the future to be resolved once fully consumed
116
+ fut = future if i + self._bytes_per_10ms >= len(audio_bytes) else None
117
+ self._chunk_queue.append((chunk, fut))
118
+
119
+ return future
120
+
121
+ async def recv(self):
122
+ """Return the next audio frame for WebRTC transmission.
123
+
124
+ Returns:
125
+ An AudioFrame containing the next audio data or silence.
126
+ """
127
+ # Compute required wait time for synchronization
128
+ if self._timestamp > 0:
129
+ wait = self._start + (self._timestamp / self._sample_rate) - time.time()
130
+ if wait > 0:
131
+ await asyncio.sleep(wait)
132
+
133
+ if self._chunk_queue:
134
+ chunk, future = self._chunk_queue.popleft()
135
+ if future and not future.done():
136
+ future.set_result(True)
137
+ else:
138
+ chunk = bytes(self._bytes_per_10ms) # silence
139
+
140
+ # Convert the byte data to an ndarray of int16 samples
141
+ samples = np.frombuffer(chunk, dtype=np.int16)
142
+
143
+ # Create AudioFrame
144
+ frame = AudioFrame.from_ndarray(samples[None, :], layout="mono")
145
+ frame.sample_rate = self._sample_rate
146
+ frame.pts = self._timestamp
147
+ frame.time_base = fractions.Fraction(1, self._sample_rate)
148
+ self._timestamp += self._samples_per_10ms
149
+ return frame
150
+
151
+
152
+ class RawVideoTrack(VideoStreamTrack):
153
+ """Custom video stream track for WebRTC output.
154
+
155
+ Handles video frame queuing and conversion for WebRTC transmission.
156
+ """
157
+
158
+ def __init__(self, width, height):
159
+ """Initialize the raw video track.
160
+
161
+ Args:
162
+ width: Video frame width in pixels.
163
+ height: Video frame height in pixels.
164
+ """
165
+ super().__init__()
166
+ self._width = width
167
+ self._height = height
168
+ self._video_buffer = asyncio.Queue()
169
+
170
+ def add_video_frame(self, frame):
171
+ """Add a video frame to the transmission buffer.
172
+
173
+ Args:
174
+ frame: The video frame to queue for transmission.
175
+ """
176
+ self._video_buffer.put_nowait(frame)
177
+
178
+ async def recv(self):
179
+ """Return the next video frame for WebRTC transmission.
180
+
181
+ Returns:
182
+ A VideoFrame ready for WebRTC transmission.
183
+ """
184
+ raw_frame = await self._video_buffer.get()
185
+
186
+ # Convert bytes to NumPy array
187
+ frame_data = np.frombuffer(raw_frame.image, dtype=np.uint8).reshape(
188
+ (self._height, self._width, 3)
189
+ )
190
+
191
+ frame = VideoFrame.from_ndarray(frame_data, format="rgb24")
192
+
193
+ # Assign timestamp
194
+ frame.pts, frame.time_base = await self.next_timestamp()
195
+
196
+ return frame
197
+
198
+
199
+ class SmallWebRTCClient:
200
+ """WebRTC client implementation for handling connections and media streams.
201
+
202
+ Manages WebRTC peer connections, audio/video streaming, and application
203
+ messaging through the SmallWebRTCConnection interface.
204
+ """
205
+
206
+ FORMAT_CONVERSIONS = {
207
+ "yuv420p": cv2.COLOR_YUV2RGB_I420,
208
+ "yuvj420p": cv2.COLOR_YUV2RGB_I420, # OpenCV treats both the same
209
+ "nv12": cv2.COLOR_YUV2RGB_NV12,
210
+ "gray": cv2.COLOR_GRAY2RGB,
211
+ }
212
+
213
+ def __init__(self, webrtc_connection: SmallWebRTCConnection, callbacks: SmallWebRTCCallbacks):
214
+ """Initialize the WebRTC client.
215
+
216
+ Args:
217
+ webrtc_connection: The underlying WebRTC connection handler.
218
+ callbacks: Event callbacks for connection and message handling.
219
+ """
220
+ self._webrtc_connection = webrtc_connection
221
+ self._closing = False
222
+ self._callbacks = callbacks
223
+
224
+ self._audio_output_track = None
225
+ self._video_output_track = None
226
+ self._audio_input_track: Optional[AudioStreamTrack] = None
227
+ self._video_input_track: Optional[VideoStreamTrack] = None
228
+ self._screen_video_track: Optional[VideoStreamTrack] = None
229
+
230
+ self._params = None
231
+ self._audio_in_channels = None
232
+ self._in_sample_rate = None
233
+ self._out_sample_rate = None
234
+ self._leave_counter = 0
235
+
236
+ # We are always resampling it for 16000 if the sample_rate that we receive is bigger than that.
237
+ # otherwise we face issues with Silero VAD
238
+ self._pipecat_resampler = AudioResampler("s16", "mono", 16000)
239
+
240
+ @self._webrtc_connection.event_handler("connected")
241
+ async def on_connected(connection: SmallWebRTCConnection):
242
+ logger.debug("Peer connection established.")
243
+ await self._handle_client_connected()
244
+
245
+ @self._webrtc_connection.event_handler("disconnected")
246
+ async def on_disconnected(connection: SmallWebRTCConnection):
247
+ logger.debug("Peer connection lost.")
248
+ await self._handle_peer_disconnected()
249
+
250
+ @self._webrtc_connection.event_handler("closed")
251
+ async def on_closed(connection: SmallWebRTCConnection):
252
+ logger.debug("Client connection closed.")
253
+ await self._handle_client_closed()
254
+
255
+ @self._webrtc_connection.event_handler("app-message")
256
+ async def on_app_message(connection: SmallWebRTCConnection, message: Any):
257
+ await self._handle_app_message(message)
258
+
259
+ def _convert_frame(self, frame_array: np.ndarray, format_name: str) -> np.ndarray:
260
+ """Convert a video frame to RGB format based on the input format.
261
+
262
+ Args:
263
+ frame_array: The input frame as a NumPy array.
264
+ format_name: The format of the input frame.
265
+
266
+ Returns:
267
+ The converted RGB frame as a NumPy array.
268
+
269
+ Raises:
270
+ ValueError: If the format is unsupported.
271
+ """
272
+ if format_name.startswith("rgb"): # Already in RGB, no conversion needed
273
+ return frame_array
274
+
275
+ conversion_code = SmallWebRTCClient.FORMAT_CONVERSIONS.get(format_name)
276
+
277
+ if conversion_code is None:
278
+ raise ValueError(f"Unsupported format: {format_name}")
279
+
280
+ return cv2.cvtColor(frame_array, conversion_code)
281
+
282
+ async def read_video_frame(self, video_source: str):
283
+ """Read video frames from the WebRTC connection.
284
+
285
+ Reads a video frame from the given MediaStreamTrack, converts it to RGB,
286
+ and creates an InputImageRawFrame.
287
+
288
+ Args:
289
+ video_source: Video source to capture ("camera" or "screenVideo").
290
+
291
+ Yields:
292
+ UserImageRawFrame objects containing video data from the peer.
293
+ """
294
+ while True:
295
+ video_track = (
296
+ self._video_input_track
297
+ if video_source == CAM_VIDEO_SOURCE
298
+ else self._screen_video_track
299
+ )
300
+ if video_track is None:
301
+ await asyncio.sleep(0.01)
302
+ continue
303
+
304
+ try:
305
+ frame = await asyncio.wait_for(video_track.recv(), timeout=2.0)
306
+ except asyncio.TimeoutError:
307
+ if self._webrtc_connection.is_connected():
308
+ logger.warning("Timeout: No video frame received within the specified time.")
309
+ # self._webrtc_connection.ask_to_renegotiate()
310
+ frame = None
311
+ except MediaStreamError:
312
+ logger.warning("Received an unexpected media stream error while reading the audio.")
313
+ frame = None
314
+
315
+ if frame is None or not isinstance(frame, VideoFrame):
316
+ # If no valid frame, sleep for a bit
317
+ await asyncio.sleep(0.01)
318
+ continue
319
+
320
+ format_name = frame.format.name
321
+ # Convert frame to NumPy array in its native format
322
+ frame_array = frame.to_ndarray(format=format_name)
323
+ frame_rgb = self._convert_frame(frame_array, format_name)
324
+
325
+ image_frame = UserImageRawFrame(
326
+ user_id=self._webrtc_connection.pc_id,
327
+ image=frame_rgb.tobytes(),
328
+ size=(frame.width, frame.height),
329
+ format="RGB",
330
+ )
331
+ image_frame.transport_source = video_source
332
+
333
+ yield image_frame
334
+
335
+ async def read_audio_frame(self):
336
+ """Read audio frames from the WebRTC connection.
337
+
338
+ Reads 20ms of audio from the given MediaStreamTrack and creates an InputAudioRawFrame.
339
+
340
+ Yields:
341
+ InputAudioRawFrame objects containing audio data from the peer.
342
+ """
343
+ while True:
344
+ if self._audio_input_track is None:
345
+ await asyncio.sleep(0.01)
346
+ continue
347
+
348
+ try:
349
+ frame = await asyncio.wait_for(self._audio_input_track.recv(), timeout=2.0)
350
+ except asyncio.TimeoutError:
351
+ if self._webrtc_connection.is_connected():
352
+ logger.warning("Timeout: No audio frame received within the specified time.")
353
+ frame = None
354
+ except MediaStreamError:
355
+ logger.warning("Received an unexpected media stream error while reading the audio.")
356
+ frame = None
357
+
358
+ if frame is None or not isinstance(frame, AudioFrame):
359
+ # If we don't read any audio let's sleep for a little bit (i.e. busy wait).
360
+ await asyncio.sleep(0.01)
361
+ continue
362
+
363
+ if frame.sample_rate > self._in_sample_rate:
364
+ resampled_frames = self._pipecat_resampler.resample(frame)
365
+ for resampled_frame in resampled_frames:
366
+ # 16-bit PCM bytes
367
+ pcm_bytes = resampled_frame.to_ndarray().astype(np.int16).tobytes()
368
+ audio_frame = InputAudioRawFrame(
369
+ audio=pcm_bytes,
370
+ sample_rate=resampled_frame.sample_rate,
371
+ num_channels=self._audio_in_channels,
372
+ )
373
+ yield audio_frame
374
+ else:
375
+ # 16-bit PCM bytes
376
+ pcm_bytes = frame.to_ndarray().astype(np.int16).tobytes()
377
+ audio_frame = InputAudioRawFrame(
378
+ audio=pcm_bytes,
379
+ sample_rate=frame.sample_rate,
380
+ num_channels=self._audio_in_channels,
381
+ )
382
+ yield audio_frame
383
+
384
+ async def write_audio_frame(self, frame: OutputAudioRawFrame):
385
+ """Write an audio frame to the WebRTC connection.
386
+
387
+ Args:
388
+ frame: The audio frame to transmit.
389
+ """
390
+ if self._can_send() and self._audio_output_track:
391
+ await self._audio_output_track.add_audio_bytes(frame.audio)
392
+
393
+ async def write_video_frame(self, frame: OutputImageRawFrame):
394
+ """Write a video frame to the WebRTC connection.
395
+
396
+ Args:
397
+ frame: The video frame to transmit.
398
+ """
399
+ if self._can_send() and self._video_output_track:
400
+ self._video_output_track.add_video_frame(frame)
401
+
402
+ async def setup(self, _params: TransportParams, frame):
403
+ """Set up the client with transport parameters.
404
+
405
+ Args:
406
+ _params: Transport configuration parameters.
407
+ frame: The initialization frame containing setup data.
408
+ """
409
+ self._audio_in_channels = _params.audio_in_channels
410
+ self._in_sample_rate = _params.audio_in_sample_rate or frame.audio_in_sample_rate
411
+ self._out_sample_rate = _params.audio_out_sample_rate or frame.audio_out_sample_rate
412
+ self._params = _params
413
+ self._leave_counter += 1
414
+
415
+ async def connect(self):
416
+ """Establish the WebRTC connection."""
417
+ if self._webrtc_connection.is_connected():
418
+ # already initialized
419
+ return
420
+
421
+ logger.info(f"Connecting to Small WebRTC")
422
+ await self._webrtc_connection.connect()
423
+
424
+ async def disconnect(self):
425
+ """Disconnect from the WebRTC peer."""
426
+ self._leave_counter -= 1
427
+ if self._leave_counter > 0:
428
+ return
429
+
430
+ if self.is_connected and not self.is_closing:
431
+ logger.info(f"Disconnecting to Small WebRTC")
432
+ self._closing = True
433
+ await self._webrtc_connection.disconnect()
434
+ await self._handle_peer_disconnected()
435
+
436
+ async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
437
+ """Send an application message through the WebRTC connection.
438
+
439
+ Args:
440
+ frame: The message frame to send.
441
+ """
442
+ if self._can_send():
443
+ self._webrtc_connection.send_app_message(frame.message)
444
+
445
+ async def _handle_client_connected(self):
446
+ """Handle client connection establishment."""
447
+ # There is nothing to do here yet, the pipeline is still not ready
448
+ if not self._params:
449
+ return
450
+
451
+ self._audio_input_track = self._webrtc_connection.audio_input_track()
452
+ self._video_input_track = self._webrtc_connection.video_input_track()
453
+ self._screen_video_track = self._webrtc_connection.screen_video_input_track()
454
+ if self._params.audio_out_enabled:
455
+ self._audio_output_track = RawAudioTrack(sample_rate=self._out_sample_rate)
456
+ self._webrtc_connection.replace_audio_track(self._audio_output_track)
457
+
458
+ if self._params.video_out_enabled:
459
+ self._video_output_track = RawVideoTrack(
460
+ width=self._params.video_out_width, height=self._params.video_out_height
461
+ )
462
+ self._webrtc_connection.replace_video_track(self._video_output_track)
463
+
464
+ await self._callbacks.on_client_connected(self._webrtc_connection)
465
+
466
+ async def _handle_peer_disconnected(self):
467
+ """Handle peer disconnection cleanup."""
468
+ self._audio_input_track = None
469
+ self._video_input_track = None
470
+ self._screen_video_track = None
471
+ self._audio_output_track = None
472
+ self._video_output_track = None
473
+
474
+ async def _handle_client_closed(self):
475
+ """Handle client connection closure."""
476
+ self._audio_input_track = None
477
+ self._video_input_track = None
478
+ self._screen_video_track = None
479
+ self._audio_output_track = None
480
+ self._video_output_track = None
481
+ await self._callbacks.on_client_disconnected(self._webrtc_connection)
482
+
483
+ async def _handle_app_message(self, message: Any):
484
+ """Handle incoming application messages."""
485
+ await self._callbacks.on_app_message(message)
486
+
487
+ def _can_send(self):
488
+ """Check if the connection is ready for sending data."""
489
+ return self.is_connected and not self.is_closing
490
+
491
+ @property
492
+ def is_connected(self) -> bool:
493
+ """Check if the WebRTC connection is established.
494
+
495
+ Returns:
496
+ True if connected to the peer.
497
+ """
498
+ return self._webrtc_connection.is_connected()
499
+
500
+ @property
501
+ def is_closing(self) -> bool:
502
+ """Check if the connection is in the process of closing.
503
+
504
+ Returns:
505
+ True if the connection is closing.
506
+ """
507
+ return self._closing
508
+
509
+
510
+ class SmallWebRTCInputTransport(BaseInputTransport):
511
+ """Input transport implementation for SmallWebRTC.
512
+
513
+ Handles incoming audio and video streams from WebRTC peers,
514
+ including user image requests and application message handling.
515
+ """
516
+
517
+ def __init__(
518
+ self,
519
+ client: SmallWebRTCClient,
520
+ params: TransportParams,
521
+ **kwargs,
522
+ ):
523
+ """Initialize the WebRTC input transport.
524
+
525
+ Args:
526
+ client: The WebRTC client instance.
527
+ params: Transport configuration parameters.
528
+ **kwargs: Additional arguments passed to parent class.
529
+ """
530
+ super().__init__(params, **kwargs)
531
+ self._client = client
532
+ self._params = params
533
+ self._receive_audio_task = None
534
+ self._receive_video_task = None
535
+ self._receive_screen_video_task = None
536
+ self._image_requests = {}
537
+
538
+ # Whether we have seen a StartFrame already.
539
+ self._initialized = False
540
+
541
+ async def process_frame(self, frame: Frame, direction: FrameDirection):
542
+ """Process incoming frames including user image requests.
543
+
544
+ Args:
545
+ frame: The frame to process.
546
+ direction: The direction of frame flow in the pipeline.
547
+ """
548
+ await super().process_frame(frame, direction)
549
+
550
+ if isinstance(frame, UserImageRequestFrame):
551
+ await self.request_participant_image(frame)
552
+
553
+ async def start(self, frame: StartFrame):
554
+ """Start the input transport and establish WebRTC connection.
555
+
556
+ Args:
557
+ frame: The start frame containing initialization parameters.
558
+ """
559
+ await super().start(frame)
560
+
561
+ if self._initialized:
562
+ return
563
+
564
+ self._initialized = True
565
+
566
+ await self._client.setup(self._params, frame)
567
+ await self._client.connect()
568
+ await self.set_transport_ready(frame)
569
+ if not self._receive_audio_task and self._params.audio_in_enabled:
570
+ self._receive_audio_task = self.create_task(self._receive_audio())
571
+ if not self._receive_video_task and self._params.video_in_enabled:
572
+ self._receive_video_task = self.create_task(self._receive_video(CAM_VIDEO_SOURCE))
573
+
574
+ async def _stop_tasks(self):
575
+ """Stop all background tasks."""
576
+ if self._receive_audio_task:
577
+ await self.cancel_task(self._receive_audio_task)
578
+ self._receive_audio_task = None
579
+ if self._receive_video_task:
580
+ await self.cancel_task(self._receive_video_task)
581
+ self._receive_video_task = None
582
+
583
+ async def stop(self, frame: EndFrame):
584
+ """Stop the input transport and disconnect from WebRTC.
585
+
586
+ Args:
587
+ frame: The end frame signaling transport shutdown.
588
+ """
589
+ await super().stop(frame)
590
+ await self._stop_tasks()
591
+ await self._client.disconnect()
592
+
593
+ async def cancel(self, frame: CancelFrame):
594
+ """Cancel the input transport and disconnect immediately.
595
+
596
+ Args:
597
+ frame: The cancel frame signaling immediate cancellation.
598
+ """
599
+ await super().cancel(frame)
600
+ await self._stop_tasks()
601
+ await self._client.disconnect()
602
+
603
+ async def _receive_audio(self):
604
+ """Background task for receiving audio frames from WebRTC."""
605
+ try:
606
+ audio_iterator = self._client.read_audio_frame()
607
+ async for audio_frame in audio_iterator:
608
+ if audio_frame:
609
+ await self.push_audio_frame(audio_frame)
610
+
611
+ except Exception as e:
612
+ logger.error(f"{self} exception receiving data: {e.__class__.__name__} ({e})")
613
+
614
+ async def _receive_video(self, video_source: str):
615
+ """Background task for receiving video frames from WebRTC.
616
+
617
+ Args:
618
+ video_source: Video source to capture ("camera" or "screenVideo").
619
+ """
620
+ try:
621
+ video_iterator = self._client.read_video_frame(video_source)
622
+ async for video_frame in video_iterator:
623
+ if video_frame:
624
+ await self.push_video_frame(video_frame)
625
+
626
+ # Check if there are any pending image requests and create UserImageRawFrame
627
+ if self._image_requests:
628
+ for req_id, request_frame in list(self._image_requests.items()):
629
+ if request_frame.video_source == video_source:
630
+ # Create UserImageRawFrame using the current video frame
631
+ image_frame = UserImageRawFrame(
632
+ user_id=request_frame.user_id,
633
+ request=request_frame,
634
+ image=video_frame.image,
635
+ size=video_frame.size,
636
+ format=video_frame.format,
637
+ )
638
+ image_frame.transport_source = video_source
639
+ # Push the frame to the pipeline
640
+ await self.push_video_frame(image_frame)
641
+ # Remove from pending requests
642
+ del self._image_requests[req_id]
643
+
644
+ except Exception as e:
645
+ logger.error(f"{self} exception receiving data: {e.__class__.__name__} ({e})")
646
+
647
+ async def push_app_message(self, message: Any):
648
+ """Push an application message into the pipeline.
649
+
650
+ Args:
651
+ message: The application message to process.
652
+ """
653
+ logger.debug(f"Received app message inside SmallWebRTCInputTransport {message}")
654
+ frame = InputTransportMessageUrgentFrame(message=message)
655
+ await self.push_frame(frame)
656
+
657
+ # Add this method similar to DailyInputTransport.request_participant_image
658
+ async def request_participant_image(self, frame: UserImageRequestFrame):
659
+ """Request an image frame from the participant's video stream.
660
+
661
+ When a UserImageRequestFrame is received, this method will store the request
662
+ and the next video frame received will be converted to a UserImageRawFrame.
663
+
664
+ Args:
665
+ frame: The user image request frame.
666
+ """
667
+ logger.debug(f"Requesting image from participant: {frame.user_id}")
668
+
669
+ # Store the request
670
+ request_id = f"{frame.function_name}:{frame.tool_call_id}"
671
+ self._image_requests[request_id] = frame
672
+
673
+ # Default to camera if no source specified
674
+ if frame.video_source is None:
675
+ frame.video_source = CAM_VIDEO_SOURCE
676
+ # If we're not already receiving video, try to get a frame now
677
+ if (
678
+ frame.video_source == CAM_VIDEO_SOURCE
679
+ and not self._receive_video_task
680
+ and self._params.video_in_enabled
681
+ ):
682
+ # Start video reception if it's not already running
683
+ self._receive_video_task = self.create_task(self._receive_video(CAM_VIDEO_SOURCE))
684
+ elif (
685
+ frame.video_source == SCREEN_VIDEO_SOURCE
686
+ and not self._receive_screen_video_task
687
+ and self._params.video_in_enabled
688
+ ):
689
+ # Start screen video reception if it's not already running
690
+ self._receive_screen_video_task = self.create_task(
691
+ self._receive_video(SCREEN_VIDEO_SOURCE)
692
+ )
693
+
694
+ async def capture_participant_media(
695
+ self,
696
+ source: str = CAM_VIDEO_SOURCE,
697
+ ):
698
+ """Capture media from a specific participant.
699
+
700
+ Args:
701
+ source: Media source to capture from. ("camera", "microphone", or "screenVideo")
702
+ """
703
+ # If we're not already receiving video, try to get a frame now
704
+ if (
705
+ source == MIC_AUDIO_SOURCE
706
+ and not self._receive_audio_task
707
+ and self._params.audio_in_enabled
708
+ ):
709
+ # Start audio reception if it's not already running
710
+ self._receive_audio_task = self.create_task(self._receive_audio())
711
+ elif (
712
+ source == CAM_VIDEO_SOURCE
713
+ and not self._receive_video_task
714
+ and self._params.video_in_enabled
715
+ ):
716
+ # Start video reception if it's not already running
717
+ self._receive_video_task = self.create_task(self._receive_video(CAM_VIDEO_SOURCE))
718
+ elif (
719
+ source == SCREEN_VIDEO_SOURCE
720
+ and not self._receive_screen_video_task
721
+ and self._params.video_in_enabled
722
+ ):
723
+ # Start screen video reception if it's not already running
724
+ self._receive_screen_video_task = self.create_task(
725
+ self._receive_video(SCREEN_VIDEO_SOURCE)
726
+ )
727
+
728
+
729
+ class SmallWebRTCOutputTransport(BaseOutputTransport):
730
+ """Output transport implementation for SmallWebRTC.
731
+
732
+ Handles outgoing audio and video streams to WebRTC peers,
733
+ including transport message sending.
734
+ """
735
+
736
+ def __init__(
737
+ self,
738
+ client: SmallWebRTCClient,
739
+ params: TransportParams,
740
+ **kwargs,
741
+ ):
742
+ """Initialize the WebRTC output transport.
743
+
744
+ Args:
745
+ client: The WebRTC client instance.
746
+ params: Transport configuration parameters.
747
+ **kwargs: Additional arguments passed to parent class.
748
+ """
749
+ super().__init__(params, **kwargs)
750
+ self._client = client
751
+ self._params = params
752
+
753
+ # Whether we have seen a StartFrame already.
754
+ self._initialized = False
755
+
756
+ async def start(self, frame: StartFrame):
757
+ """Start the output transport and establish WebRTC connection.
758
+
759
+ Args:
760
+ frame: The start frame containing initialization parameters.
761
+ """
762
+ await super().start(frame)
763
+
764
+ if self._initialized:
765
+ return
766
+
767
+ self._initialized = True
768
+
769
+ await self._client.setup(self._params, frame)
770
+ await self._client.connect()
771
+ await self.set_transport_ready(frame)
772
+
773
+ async def stop(self, frame: EndFrame):
774
+ """Stop the output transport and disconnect from WebRTC.
775
+
776
+ Args:
777
+ frame: The end frame signaling transport shutdown.
778
+ """
779
+ await super().stop(frame)
780
+ await self._client.disconnect()
781
+
782
+ async def cancel(self, frame: CancelFrame):
783
+ """Cancel the output transport and disconnect immediately.
784
+
785
+ Args:
786
+ frame: The cancel frame signaling immediate cancellation.
787
+ """
788
+ await super().cancel(frame)
789
+ await self._client.disconnect()
790
+
791
+ async def send_message(self, frame: TransportMessageFrame | TransportMessageUrgentFrame):
792
+ """Send a transport message through the WebRTC connection.
793
+
794
+ Args:
795
+ frame: The transport message frame to send.
796
+ """
797
+ await self._client.send_message(frame)
798
+
799
+ async def write_audio_frame(self, frame: OutputAudioRawFrame):
800
+ """Write an audio frame to the WebRTC connection.
801
+
802
+ Args:
803
+ frame: The output audio frame to transmit.
804
+ """
805
+ await self._client.write_audio_frame(frame)
806
+
807
+ async def write_video_frame(self, frame: OutputImageRawFrame):
808
+ """Write a video frame to the WebRTC connection.
809
+
810
+ Args:
811
+ frame: The output video frame to transmit.
812
+ """
813
+ await self._client.write_video_frame(frame)
814
+
815
+
816
+ class SmallWebRTCTransport(BaseTransport):
817
+ """WebRTC transport implementation for real-time communication.
818
+
819
+ Provides bidirectional audio and video streaming over WebRTC connections
820
+ with support for application messaging and connection event handling.
821
+ """
822
+
823
+ def __init__(
824
+ self,
825
+ webrtc_connection: SmallWebRTCConnection,
826
+ params: TransportParams,
827
+ input_name: Optional[str] = None,
828
+ output_name: Optional[str] = None,
829
+ ):
830
+ """Initialize the WebRTC transport.
831
+
832
+ Args:
833
+ webrtc_connection: The underlying WebRTC connection handler.
834
+ params: Transport configuration parameters.
835
+ input_name: Optional name for the input processor.
836
+ output_name: Optional name for the output processor.
837
+ """
838
+ super().__init__(input_name=input_name, output_name=output_name)
839
+ self._params = params
840
+
841
+ self._callbacks = SmallWebRTCCallbacks(
842
+ on_app_message=self._on_app_message,
843
+ on_client_connected=self._on_client_connected,
844
+ on_client_disconnected=self._on_client_disconnected,
845
+ )
846
+
847
+ self._client = SmallWebRTCClient(webrtc_connection, self._callbacks)
848
+
849
+ self._input: Optional[SmallWebRTCInputTransport] = None
850
+ self._output: Optional[SmallWebRTCOutputTransport] = None
851
+
852
+ # Register supported handlers. The user will only be able to register
853
+ # these handlers.
854
+ self._register_event_handler("on_app_message")
855
+ self._register_event_handler("on_client_connected")
856
+ self._register_event_handler("on_client_disconnected")
857
+
858
+ def input(self) -> SmallWebRTCInputTransport:
859
+ """Get the input transport processor.
860
+
861
+ Returns:
862
+ The input transport for handling incoming media streams.
863
+ """
864
+ if not self._input:
865
+ self._input = SmallWebRTCInputTransport(
866
+ self._client, self._params, name=self._input_name
867
+ )
868
+ return self._input
869
+
870
+ def output(self) -> SmallWebRTCOutputTransport:
871
+ """Get the output transport processor.
872
+
873
+ Returns:
874
+ The output transport for handling outgoing media streams.
875
+ """
876
+ if not self._output:
877
+ self._output = SmallWebRTCOutputTransport(
878
+ self._client, self._params, name=self._input_name
879
+ )
880
+ return self._output
881
+
882
+ async def send_image(self, frame: OutputImageRawFrame | SpriteFrame):
883
+ """Send an image frame through the transport.
884
+
885
+ Args:
886
+ frame: The image frame to send.
887
+ """
888
+ if self._output:
889
+ await self._output.queue_frame(frame, FrameDirection.DOWNSTREAM)
890
+
891
+ async def send_audio(self, frame: OutputAudioRawFrame):
892
+ """Send an audio frame through the transport.
893
+
894
+ Args:
895
+ frame: The audio frame to send.
896
+ """
897
+ if self._output:
898
+ await self._output.queue_frame(frame, FrameDirection.DOWNSTREAM)
899
+
900
+ async def _on_app_message(self, message: Any):
901
+ """Handle incoming application messages."""
902
+ if self._input:
903
+ await self._input.push_app_message(message)
904
+ await self._call_event_handler("on_app_message", message)
905
+
906
+ async def _on_client_connected(self, webrtc_connection):
907
+ """Handle client connection events."""
908
+ await self._call_event_handler("on_client_connected", webrtc_connection)
909
+
910
+ async def _on_client_disconnected(self, webrtc_connection):
911
+ """Handle client disconnection events."""
912
+ await self._call_event_handler("on_client_disconnected", webrtc_connection)
913
+
914
+ async def capture_participant_video(
915
+ self,
916
+ video_source: str = CAM_VIDEO_SOURCE,
917
+ ):
918
+ """Capture video from a specific participant.
919
+
920
+ Args:
921
+ video_source: Video source to capture from ("camera" or "screenVideo").
922
+ """
923
+ if self._input:
924
+ await self._input.capture_participant_media(source=video_source)
925
+
926
+ async def capture_participant_audio(
927
+ self,
928
+ audio_source: str = MIC_AUDIO_SOURCE,
929
+ ):
930
+ """Capture audio from a specific participant.
931
+
932
+ Args:
933
+ audio_source: Audio source to capture from. (currently, "microphone" is the only supported option)
934
+ """
935
+ if self._input:
936
+ await self._input.capture_participant_media(source=audio_source)