pipecat-facemode 0.1.0__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.
- pipecat_facemode/__init__.py +28 -0
- pipecat_facemode/exceptions.py +21 -0
- pipecat_facemode/models.py +238 -0
- pipecat_facemode/service.py +1458 -0
- pipecat_facemode/version.py +3 -0
- pipecat_facemode-0.1.0.dist-info/METADATA +257 -0
- pipecat_facemode-0.1.0.dist-info/RECORD +10 -0
- pipecat_facemode-0.1.0.dist-info/WHEEL +5 -0
- pipecat_facemode-0.1.0.dist-info/licenses/LICENSE +13 -0
- pipecat_facemode-0.1.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,1458 @@
|
|
|
1
|
+
"""Pipecat FrameProcessor for FaceMode LiveKit avatar sessions."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import asyncio
|
|
6
|
+
import contextlib
|
|
7
|
+
import json
|
|
8
|
+
import logging
|
|
9
|
+
import time
|
|
10
|
+
from collections.abc import Mapping
|
|
11
|
+
from typing import Any
|
|
12
|
+
|
|
13
|
+
import aiohttp
|
|
14
|
+
import numpy as np
|
|
15
|
+
import websockets
|
|
16
|
+
from livekit import rtc
|
|
17
|
+
from pipecat.frames.frames import (
|
|
18
|
+
CancelFrame,
|
|
19
|
+
EndFrame,
|
|
20
|
+
Frame,
|
|
21
|
+
ImageRawFrame,
|
|
22
|
+
OutputAudioRawFrame,
|
|
23
|
+
StartFrame,
|
|
24
|
+
TTSAudioRawFrame,
|
|
25
|
+
)
|
|
26
|
+
from pipecat.frames.frames import InterruptionFrame
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
from pipecat.frames.frames import StartInterruptionFrame
|
|
30
|
+
except ImportError: # Pipecat 1.7 uses InterruptionFrame for this event
|
|
31
|
+
StartInterruptionFrame = None # type: ignore[assignment,misc]
|
|
32
|
+
|
|
33
|
+
try:
|
|
34
|
+
from pipecat.frames.frames import StopInterruptionFrame
|
|
35
|
+
except ImportError: # Pipecat 1.7 has no separate stop event
|
|
36
|
+
StopInterruptionFrame = None # type: ignore[assignment,misc]
|
|
37
|
+
from pipecat.processors.frame_processor import FrameDirection, FrameProcessor
|
|
38
|
+
|
|
39
|
+
from .exceptions import (
|
|
40
|
+
FaceModeAPIError,
|
|
41
|
+
FaceModeConfigurationError,
|
|
42
|
+
FaceModeError,
|
|
43
|
+
FaceModeNotReadyError,
|
|
44
|
+
FaceModeProtocolError,
|
|
45
|
+
)
|
|
46
|
+
from .models import LiveKitRoom, SessionDetails, SessionRequest
|
|
47
|
+
|
|
48
|
+
try:
|
|
49
|
+
from pipecat.frames.frames import OutputImageRawFrame
|
|
50
|
+
except ImportError: # pragma: no cover - depends on the installed Pipecat release
|
|
51
|
+
OutputImageRawFrame = None # type: ignore[assignment,misc]
|
|
52
|
+
|
|
53
|
+
try:
|
|
54
|
+
from pipecat.frames.frames import OutputVideoRawFrame
|
|
55
|
+
except ImportError: # pragma: no cover - kept for older Pipecat releases
|
|
56
|
+
OutputVideoRawFrame = None # type: ignore[assignment,misc]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
logger = logging.getLogger("pipecat_facemode")
|
|
60
|
+
|
|
61
|
+
_MIN_INPUT_SAMPLE_RATE = 8_000
|
|
62
|
+
_MAX_INPUT_SAMPLE_RATE = 48_000
|
|
63
|
+
_INGESTION_READY_TIMEOUT_SECONDS = 240.0
|
|
64
|
+
_INGESTION_INITIAL_RETRY_SECONDS = 0.25
|
|
65
|
+
_INGESTION_MAX_RETRY_SECONDS = 2.0
|
|
66
|
+
_END_ACK_TIMEOUT_SECONDS = 3.0
|
|
67
|
+
_WS_OPEN_TIMEOUT_SECONDS = 240.0
|
|
68
|
+
_WS_CLOSE_TIMEOUT = 2.0
|
|
69
|
+
_RECONNECT_MAX_ATTEMPTS = 2
|
|
70
|
+
_RECONNECT_INITIAL_BACKOFF_SECONDS = 0.5
|
|
71
|
+
_RECONNECT_MAX_BACKOFF_SECONDS = 2.0
|
|
72
|
+
_PREFERRED_SAMPLE_RATES = frozenset(
|
|
73
|
+
{8_000, 11_025, 12_000, 16_000, 22_050, 24_000, 32_000, 44_100, 48_000}
|
|
74
|
+
)
|
|
75
|
+
_SUPPORTED_CHANNELS = frozenset({1, 2})
|
|
76
|
+
_SUPPORTED_INPUT_PROVIDERS = frozenset(
|
|
77
|
+
{
|
|
78
|
+
"deepgram",
|
|
79
|
+
"gemini",
|
|
80
|
+
"gnani",
|
|
81
|
+
"elevenlabs",
|
|
82
|
+
"openai",
|
|
83
|
+
"cartesia",
|
|
84
|
+
"sarvam",
|
|
85
|
+
"custom",
|
|
86
|
+
}
|
|
87
|
+
)
|
|
88
|
+
|
|
89
|
+
|
|
90
|
+
class FaceModeVideoService(FrameProcessor):
|
|
91
|
+
"""Bridge Pipecat TTS audio to a FaceMode avatar and LiveKit output.
|
|
92
|
+
|
|
93
|
+
The processor creates a FaceMode session when the pipeline receives its
|
|
94
|
+
``StartFrame``. TTS PCM is sent through FaceMode's canonical WebSocket, while
|
|
95
|
+
the avatar's LiveKit audio and video tracks are converted back into Pipecat
|
|
96
|
+
output frames. TTS frames are consumed by default so a pipeline does not send
|
|
97
|
+
the source TTS audio and the avatar audio twice.
|
|
98
|
+
|
|
99
|
+
``room.token`` is the server-side worker token sent to FaceMode. A separate
|
|
100
|
+
``livekit_subscriber_token`` can be supplied for this processor's LiveKit
|
|
101
|
+
connection. If it is omitted, the worker room token is also used for
|
|
102
|
+
subscribing. Supplying separate tokens is recommended because LiveKit
|
|
103
|
+
participant identities should not be reused by the avatar worker and the
|
|
104
|
+
Pipecat process.
|
|
105
|
+
"""
|
|
106
|
+
|
|
107
|
+
def __init__(
|
|
108
|
+
self,
|
|
109
|
+
*,
|
|
110
|
+
api_key: str,
|
|
111
|
+
room: LiveKitRoom | Mapping[str, Any],
|
|
112
|
+
avatar_id: str = "",
|
|
113
|
+
api_url: str = "https://api.facemode.io/api",
|
|
114
|
+
room_name: str | None = None,
|
|
115
|
+
livekit_subscriber_token: str | None = None,
|
|
116
|
+
avatar_participant_identity: str | None = None,
|
|
117
|
+
input_provider: str | None = None,
|
|
118
|
+
forward_tts_audio: bool = False,
|
|
119
|
+
utterance_idle_timeout: float = 0.35,
|
|
120
|
+
protocol_timeout: float = 15.0,
|
|
121
|
+
api_timeout: float = 30.0,
|
|
122
|
+
http_session: aiohttp.ClientSession | None = None,
|
|
123
|
+
name: str | None = None,
|
|
124
|
+
**kwargs: Any,
|
|
125
|
+
) -> None:
|
|
126
|
+
"""Create a FaceMode Pipecat processor.
|
|
127
|
+
|
|
128
|
+
Args:
|
|
129
|
+
api_key: FaceMode REST API key.
|
|
130
|
+
room: Customer room object with ``type``, ``url``, and server-side
|
|
131
|
+
``token`` fields. The token is sent to FaceMode for the worker.
|
|
132
|
+
avatar_id: Optional FaceMode avatar identifier.
|
|
133
|
+
api_url: FaceMode API root. Defaults to the hosted API.
|
|
134
|
+
room_name: LiveKit room name. If omitted, it is read from the connected room.
|
|
135
|
+
livekit_subscriber_token: Optional token for this process to subscribe.
|
|
136
|
+
avatar_participant_identity: Optional identity filter for avatar tracks;
|
|
137
|
+
defaults to ``facemode-avatar`` when omitted.
|
|
138
|
+
input_provider: Optional speech input provider for the session. One of
|
|
139
|
+
``deepgram``, ``gemini``, ``gnani``, ``elevenlabs``, ``openai``,
|
|
140
|
+
``cartesia``, ``sarvam``, or ``custom``. The backend persists the
|
|
141
|
+
value for the session lifetime; reconnects reuse it.
|
|
142
|
+
forward_tts_audio: Also pass source TTS frames downstream when true.
|
|
143
|
+
utterance_idle_timeout: Seconds of silence after which an utterance ends.
|
|
144
|
+
protocol_timeout: WebSocket start acknowledgement timeout.
|
|
145
|
+
api_timeout: REST request timeout in seconds.
|
|
146
|
+
http_session: Optional caller-owned aiohttp session.
|
|
147
|
+
name: Optional Pipecat processor name.
|
|
148
|
+
**kwargs: Additional arguments accepted by ``FrameProcessor``.
|
|
149
|
+
"""
|
|
150
|
+
super().__init__(name=name or "FaceModeVideoService", **kwargs)
|
|
151
|
+
|
|
152
|
+
if not api_key:
|
|
153
|
+
raise FaceModeConfigurationError("api_key is required")
|
|
154
|
+
try:
|
|
155
|
+
room_config = LiveKitRoom.from_value(room)
|
|
156
|
+
except ValueError as error:
|
|
157
|
+
raise FaceModeConfigurationError(str(error)) from error
|
|
158
|
+
if not api_url:
|
|
159
|
+
raise FaceModeConfigurationError("api_url is required")
|
|
160
|
+
if utterance_idle_timeout <= 0:
|
|
161
|
+
raise FaceModeConfigurationError("utterance_idle_timeout must be positive")
|
|
162
|
+
if protocol_timeout <= 0:
|
|
163
|
+
raise FaceModeConfigurationError("protocol_timeout must be positive")
|
|
164
|
+
if api_timeout <= 0:
|
|
165
|
+
raise FaceModeConfigurationError("api_timeout must be positive")
|
|
166
|
+
if input_provider is not None:
|
|
167
|
+
if not isinstance(input_provider, str) or not input_provider.strip():
|
|
168
|
+
raise FaceModeConfigurationError(
|
|
169
|
+
"input_provider must be a non-empty string"
|
|
170
|
+
)
|
|
171
|
+
input_provider = input_provider.strip().lower()
|
|
172
|
+
if input_provider not in _SUPPORTED_INPUT_PROVIDERS:
|
|
173
|
+
raise FaceModeConfigurationError(
|
|
174
|
+
"input_provider must be one of "
|
|
175
|
+
f"{sorted(_SUPPORTED_INPUT_PROVIDERS)}"
|
|
176
|
+
)
|
|
177
|
+
|
|
178
|
+
self.api_key = api_key
|
|
179
|
+
self.avatar_id = avatar_id
|
|
180
|
+
self.api_url = api_url.rstrip("/")
|
|
181
|
+
self.room_config = room_config
|
|
182
|
+
self.livekit_subscriber_token = livekit_subscriber_token or room_config.token
|
|
183
|
+
self.room_name = room_name
|
|
184
|
+
self.avatar_participant_identity = avatar_participant_identity
|
|
185
|
+
self.input_provider = input_provider
|
|
186
|
+
self.forward_tts_audio = forward_tts_audio
|
|
187
|
+
self.utterance_idle_timeout = utterance_idle_timeout
|
|
188
|
+
self.protocol_timeout = protocol_timeout
|
|
189
|
+
self.api_timeout = api_timeout
|
|
190
|
+
self._http_session = http_session
|
|
191
|
+
|
|
192
|
+
self.session: SessionDetails | None = None
|
|
193
|
+
self.room: rtc.Room | None = None
|
|
194
|
+
self.websocket: Any = None
|
|
195
|
+
|
|
196
|
+
self._lifecycle_lock = asyncio.Lock()
|
|
197
|
+
self._send_lock = asyncio.Lock()
|
|
198
|
+
self._reconnect_lock = asyncio.Lock()
|
|
199
|
+
self._protocol_started_event = asyncio.Event()
|
|
200
|
+
self._session_ended_event = asyncio.Event()
|
|
201
|
+
self._avatar_ready_event = asyncio.Event()
|
|
202
|
+
self._transport_ready_event = asyncio.Event()
|
|
203
|
+
self._transport_terminal = False
|
|
204
|
+
self._protocol_started = False
|
|
205
|
+
self._protocol_start_sent = False
|
|
206
|
+
self._protocol_error: FaceModeProtocolError | None = None
|
|
207
|
+
self._sequence = 0
|
|
208
|
+
self._audio_sample_rate: int | None = None
|
|
209
|
+
self._audio_channels: int | None = None
|
|
210
|
+
self._session_log_marker: str | None = None
|
|
211
|
+
self._utterance_active = False
|
|
212
|
+
self._utterance_context_id: str | None = None
|
|
213
|
+
self._utterance_generation = 0
|
|
214
|
+
self._interrupted = False
|
|
215
|
+
self._started = False
|
|
216
|
+
self._stopping = False
|
|
217
|
+
self._accept_tracks = False
|
|
218
|
+
|
|
219
|
+
self._receiver_task: asyncio.Task[Any] | None = None
|
|
220
|
+
self._keepalive_task: asyncio.Task[Any] | None = None
|
|
221
|
+
self._utterance_end_task: asyncio.Task[Any] | None = None
|
|
222
|
+
self._track_tasks: dict[str, asyncio.Task[Any]] = {}
|
|
223
|
+
self._track_streams: dict[str, Any] = {}
|
|
224
|
+
self._track_kinds: dict[str, Any] = {}
|
|
225
|
+
|
|
226
|
+
@property
|
|
227
|
+
def session_id(self) -> str | None:
|
|
228
|
+
"""Return the active FaceMode session ID, if a session exists."""
|
|
229
|
+
return self.session.session_id if self.session else None
|
|
230
|
+
|
|
231
|
+
@property
|
|
232
|
+
def is_started(self) -> bool:
|
|
233
|
+
"""Return whether the FaceMode and LiveKit resources are active."""
|
|
234
|
+
return self._started and not self._stopping
|
|
235
|
+
|
|
236
|
+
@property
|
|
237
|
+
def avatar_ready(self) -> bool:
|
|
238
|
+
"""Return whether FaceMode or LiveKit has reported avatar media readiness."""
|
|
239
|
+
return self._avatar_ready_event.is_set()
|
|
240
|
+
|
|
241
|
+
async def wait_for_avatar(self, timeout: float | None = 30.0) -> None:
|
|
242
|
+
"""Wait until FaceMode reports ``audio_ready`` or a video frame arrives."""
|
|
243
|
+
try:
|
|
244
|
+
if timeout is None:
|
|
245
|
+
await self._avatar_ready_event.wait()
|
|
246
|
+
else:
|
|
247
|
+
await asyncio.wait_for(
|
|
248
|
+
self._avatar_ready_event.wait(), timeout=timeout
|
|
249
|
+
)
|
|
250
|
+
except asyncio.TimeoutError as error:
|
|
251
|
+
raise FaceModeNotReadyError(
|
|
252
|
+
"Timed out waiting for FaceMode avatar media"
|
|
253
|
+
) from error
|
|
254
|
+
|
|
255
|
+
async def process_frame(self, frame: Frame, direction: FrameDirection) -> None:
|
|
256
|
+
"""Handle lifecycle, TTS, and interruption frames.
|
|
257
|
+
|
|
258
|
+
The base implementation is deliberately called first, as required by the
|
|
259
|
+
Pipecat custom ``FrameProcessor`` contract. Frames that this integration does
|
|
260
|
+
not consume are always pushed in their original direction.
|
|
261
|
+
"""
|
|
262
|
+
await super().process_frame(frame, direction)
|
|
263
|
+
|
|
264
|
+
if isinstance(frame, StartFrame):
|
|
265
|
+
await self._start_session(frame)
|
|
266
|
+
try:
|
|
267
|
+
await self.push_frame(frame, direction)
|
|
268
|
+
self._accept_tracks = True
|
|
269
|
+
self._subscribe_to_existing_tracks()
|
|
270
|
+
except BaseException:
|
|
271
|
+
await self._shutdown(send_end_session=False)
|
|
272
|
+
raise
|
|
273
|
+
return
|
|
274
|
+
|
|
275
|
+
if isinstance(frame, EndFrame):
|
|
276
|
+
await self._shutdown(send_end_session=True)
|
|
277
|
+
await self.push_frame(frame, direction)
|
|
278
|
+
return
|
|
279
|
+
|
|
280
|
+
if isinstance(frame, CancelFrame):
|
|
281
|
+
await self._shutdown(send_end_session=False)
|
|
282
|
+
await self.push_frame(frame, direction)
|
|
283
|
+
return
|
|
284
|
+
|
|
285
|
+
stop_interruption_types = _frame_types(StopInterruptionFrame)
|
|
286
|
+
if stop_interruption_types and isinstance(frame, stop_interruption_types):
|
|
287
|
+
self._interrupted = False
|
|
288
|
+
await self.push_frame(frame, direction)
|
|
289
|
+
return
|
|
290
|
+
|
|
291
|
+
start_interruption_types = _frame_types(StartInterruptionFrame, InterruptionFrame)
|
|
292
|
+
if isinstance(frame, start_interruption_types):
|
|
293
|
+
self._interrupted = True
|
|
294
|
+
with contextlib.suppress(FaceModeError):
|
|
295
|
+
await self._cancel_utterance()
|
|
296
|
+
await self.push_frame(frame, direction)
|
|
297
|
+
return
|
|
298
|
+
|
|
299
|
+
if isinstance(frame, TTSAudioRawFrame):
|
|
300
|
+
if self._started and not self._interrupted:
|
|
301
|
+
await self._send_tts_frame(frame)
|
|
302
|
+
if self.forward_tts_audio:
|
|
303
|
+
await self.push_frame(frame, direction)
|
|
304
|
+
return
|
|
305
|
+
|
|
306
|
+
# Pipecat 1.7 emits TTSStoppedFrame after an utterance. Use a class-name
|
|
307
|
+
# check so this package remains importable with versions that do not expose
|
|
308
|
+
# that frame, while the required frames above stay explicit and typed.
|
|
309
|
+
if frame.__class__.__name__ in {"TTSStoppedFrame", "BotStoppedSpeakingFrame"}:
|
|
310
|
+
await self._end_utterance()
|
|
311
|
+
await self.push_frame(frame, direction)
|
|
312
|
+
return
|
|
313
|
+
|
|
314
|
+
await self.push_frame(frame, direction)
|
|
315
|
+
|
|
316
|
+
async def cleanup(self) -> None:
|
|
317
|
+
"""Release WebSocket, LiveKit, and receive-task resources."""
|
|
318
|
+
await self._shutdown(send_end_session=True)
|
|
319
|
+
await super().cleanup()
|
|
320
|
+
|
|
321
|
+
async def stop(self) -> None:
|
|
322
|
+
"""Stop an active FaceMode session outside normal frame processing."""
|
|
323
|
+
await self._shutdown(send_end_session=True)
|
|
324
|
+
|
|
325
|
+
async def aclose(self) -> None:
|
|
326
|
+
"""Async-close alias for applications that manage the processor directly."""
|
|
327
|
+
await self.stop()
|
|
328
|
+
|
|
329
|
+
async def _start_session(self, frame: StartFrame) -> None:
|
|
330
|
+
async with self._lifecycle_lock:
|
|
331
|
+
if self._started:
|
|
332
|
+
return
|
|
333
|
+
|
|
334
|
+
self._stopping = False
|
|
335
|
+
self._interrupted = False
|
|
336
|
+
self._protocol_started = False
|
|
337
|
+
self._protocol_start_sent = False
|
|
338
|
+
self._protocol_error = None
|
|
339
|
+
self._transport_terminal = False
|
|
340
|
+
self._protocol_started_event = asyncio.Event()
|
|
341
|
+
self._session_ended_event = asyncio.Event()
|
|
342
|
+
self._avatar_ready_event = asyncio.Event()
|
|
343
|
+
self._transport_ready_event = asyncio.Event()
|
|
344
|
+
self._sequence = 0
|
|
345
|
+
self._audio_sample_rate = _optional_int(
|
|
346
|
+
getattr(frame, "audio_out_sample_rate", None)
|
|
347
|
+
)
|
|
348
|
+
self._audio_channels = None
|
|
349
|
+
|
|
350
|
+
try:
|
|
351
|
+
await self._connect_livekit()
|
|
352
|
+
current_room_name = (
|
|
353
|
+
self.room_name
|
|
354
|
+
or self.room_config.name
|
|
355
|
+
or (self.room.name if self.room else "")
|
|
356
|
+
)
|
|
357
|
+
if not current_room_name:
|
|
358
|
+
raise FaceModeConfigurationError(
|
|
359
|
+
"room_name is required when LiveKit does not provide a room name"
|
|
360
|
+
)
|
|
361
|
+
self.session = await self._create_session(current_room_name)
|
|
362
|
+
self.session = await self._wait_for_ingestion(self.session)
|
|
363
|
+
self._session_log_marker = _sanitize_session_marker(self.session.session_id)
|
|
364
|
+
await self._open_protocol_socket()
|
|
365
|
+
self._started = True
|
|
366
|
+
logger.info("FaceMode Pipecat session started session=%s", self._session_log_marker)
|
|
367
|
+
except BaseException:
|
|
368
|
+
# The lifecycle lock is already held here, so run the teardown
|
|
369
|
+
# body directly; re-entering _shutdown would deadlock on it.
|
|
370
|
+
await self._shutdown_locked(send_end_session=False)
|
|
371
|
+
raise
|
|
372
|
+
|
|
373
|
+
async def _connect_livekit(self) -> None:
|
|
374
|
+
room = rtc.Room()
|
|
375
|
+
self.room = room
|
|
376
|
+
room.on("track_subscribed", self._on_track_subscribed)
|
|
377
|
+
room.on("track_unsubscribed", self._on_track_unsubscribed)
|
|
378
|
+
try:
|
|
379
|
+
# LiveKit defaults to auto-subscribe. Pass the option explicitly when
|
|
380
|
+
# supported, and keep a two-argument fallback for older SDKs.
|
|
381
|
+
room_options_type = getattr(rtc, "RoomOptions", None)
|
|
382
|
+
if room_options_type is not None:
|
|
383
|
+
try:
|
|
384
|
+
options = room_options_type(auto_subscribe=True)
|
|
385
|
+
await room.connect(
|
|
386
|
+
self.room_config.url,
|
|
387
|
+
self.livekit_subscriber_token,
|
|
388
|
+
options=options,
|
|
389
|
+
)
|
|
390
|
+
except TypeError:
|
|
391
|
+
await room.connect(self.room_config.url, self.livekit_subscriber_token)
|
|
392
|
+
else:
|
|
393
|
+
await room.connect(self.room_config.url, self.livekit_subscriber_token)
|
|
394
|
+
except Exception as error:
|
|
395
|
+
raise FaceModeNotReadyError(
|
|
396
|
+
f"Unable to connect to the LiveKit room: {_safe_error(error, self.livekit_subscriber_token)}"
|
|
397
|
+
) from error
|
|
398
|
+
|
|
399
|
+
def _subscribe_to_existing_tracks(self) -> None:
|
|
400
|
+
room = self.room
|
|
401
|
+
if room is None:
|
|
402
|
+
return
|
|
403
|
+
for participant in room.remote_participants.values():
|
|
404
|
+
for publication in participant.track_publications.values():
|
|
405
|
+
track = getattr(publication, "track", None)
|
|
406
|
+
if track is not None:
|
|
407
|
+
self._on_track_subscribed(track, publication, participant)
|
|
408
|
+
|
|
409
|
+
async def _create_session(self, room_name: str) -> SessionDetails:
|
|
410
|
+
request = SessionRequest(
|
|
411
|
+
avatar_id=self.avatar_id,
|
|
412
|
+
room=self.room_config,
|
|
413
|
+
room_name=room_name,
|
|
414
|
+
input_provider=self.input_provider,
|
|
415
|
+
)
|
|
416
|
+
payload = request.to_payload()
|
|
417
|
+
headers = {
|
|
418
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
419
|
+
"Content-Type": "application/json",
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
async def post(client: aiohttp.ClientSession) -> SessionDetails:
|
|
423
|
+
try:
|
|
424
|
+
async with client.post(
|
|
425
|
+
f"{self.api_url}/sessions", json=payload, headers=headers
|
|
426
|
+
) as response:
|
|
427
|
+
body = await response.text()
|
|
428
|
+
if response.status >= 400:
|
|
429
|
+
raise FaceModeAPIError(
|
|
430
|
+
f"FaceMode session creation failed (HTTP {response.status})"
|
|
431
|
+
)
|
|
432
|
+
except FaceModeAPIError:
|
|
433
|
+
raise
|
|
434
|
+
except Exception as error:
|
|
435
|
+
raise FaceModeAPIError(
|
|
436
|
+
f"FaceMode session request failed: {_safe_error(error, self.api_key, self.room_config.token)}"
|
|
437
|
+
) from error
|
|
438
|
+
|
|
439
|
+
try:
|
|
440
|
+
response_payload = json.loads(body)
|
|
441
|
+
except json.JSONDecodeError as error:
|
|
442
|
+
raise FaceModeAPIError("FaceMode session response was not JSON") from error
|
|
443
|
+
if not isinstance(response_payload, Mapping):
|
|
444
|
+
raise FaceModeAPIError("FaceMode session response was not an object")
|
|
445
|
+
try:
|
|
446
|
+
return SessionDetails.from_api(response_payload)
|
|
447
|
+
except ValueError as error:
|
|
448
|
+
raise FaceModeAPIError("FaceMode session response is incomplete") from error
|
|
449
|
+
|
|
450
|
+
timeout = aiohttp.ClientTimeout(total=self.api_timeout)
|
|
451
|
+
if self._http_session is not None:
|
|
452
|
+
return await post(self._http_session)
|
|
453
|
+
async with aiohttp.ClientSession(timeout=timeout) as client:
|
|
454
|
+
return await post(client)
|
|
455
|
+
|
|
456
|
+
async def _wait_for_ingestion(self, initial_session: SessionDetails) -> SessionDetails:
|
|
457
|
+
"""Poll the session resource until the canonical WebSocket is assigned."""
|
|
458
|
+
session = initial_session
|
|
459
|
+
deadline = asyncio.get_running_loop().time() + _INGESTION_READY_TIMEOUT_SECONDS
|
|
460
|
+
delay = _INGESTION_INITIAL_RETRY_SECONDS
|
|
461
|
+
headers = {"Authorization": f"Bearer {self.api_key}"}
|
|
462
|
+
|
|
463
|
+
async def get_status(client: aiohttp.ClientSession) -> SessionDetails:
|
|
464
|
+
try:
|
|
465
|
+
async with client.get(
|
|
466
|
+
f"{self.api_url}/sessions/{session.session_id}", headers=headers
|
|
467
|
+
) as response:
|
|
468
|
+
body = await response.text()
|
|
469
|
+
if response.status >= 400:
|
|
470
|
+
raise FaceModeAPIError(
|
|
471
|
+
f"FaceMode ingestion status failed (HTTP {response.status})"
|
|
472
|
+
)
|
|
473
|
+
except FaceModeAPIError:
|
|
474
|
+
raise
|
|
475
|
+
except Exception as error:
|
|
476
|
+
raise FaceModeAPIError(
|
|
477
|
+
"FaceMode ingestion status request failed: "
|
|
478
|
+
f"{_safe_error(error, self.api_key)}"
|
|
479
|
+
) from error
|
|
480
|
+
try:
|
|
481
|
+
payload = json.loads(body)
|
|
482
|
+
except json.JSONDecodeError as error:
|
|
483
|
+
raise FaceModeAPIError("FaceMode ingestion status response was not JSON") from error
|
|
484
|
+
if not isinstance(payload, Mapping):
|
|
485
|
+
raise FaceModeAPIError("FaceMode ingestion status response was not an object")
|
|
486
|
+
try:
|
|
487
|
+
return SessionDetails.from_api(payload, fallback=session)
|
|
488
|
+
except ValueError as error:
|
|
489
|
+
raise FaceModeAPIError("FaceMode ingestion status response is incomplete") from error
|
|
490
|
+
|
|
491
|
+
timeout = aiohttp.ClientTimeout(total=self.api_timeout)
|
|
492
|
+
owned_session: aiohttp.ClientSession | None = None
|
|
493
|
+
client = self._http_session
|
|
494
|
+
if client is None:
|
|
495
|
+
owned_session = aiohttp.ClientSession(timeout=timeout)
|
|
496
|
+
client = owned_session
|
|
497
|
+
try:
|
|
498
|
+
while not session.ingestion.ready:
|
|
499
|
+
if asyncio.get_running_loop().time() >= deadline:
|
|
500
|
+
raise FaceModeAPIError("Timed out waiting for FaceMode ingestion assignment")
|
|
501
|
+
await asyncio.sleep(delay)
|
|
502
|
+
delay = min(delay * 1.5, _INGESTION_MAX_RETRY_SECONDS)
|
|
503
|
+
session = await get_status(client)
|
|
504
|
+
if session.worker_status in {"FAILED", "ENDED"}:
|
|
505
|
+
raise FaceModeAPIError(
|
|
506
|
+
f"FaceMode ingestion worker entered {session.worker_status.lower()} state"
|
|
507
|
+
)
|
|
508
|
+
finally:
|
|
509
|
+
if owned_session is not None:
|
|
510
|
+
await owned_session.close()
|
|
511
|
+
|
|
512
|
+
if not session.ingestion.url or not session.ingestion.ws_token:
|
|
513
|
+
raise FaceModeAPIError(
|
|
514
|
+
"FaceMode ingestion assignment is missing WebSocket credentials"
|
|
515
|
+
)
|
|
516
|
+
return session
|
|
517
|
+
|
|
518
|
+
async def _connect_websocket(self) -> None:
|
|
519
|
+
if self.session is None:
|
|
520
|
+
raise FaceModeProtocolError("FaceMode session has not been created")
|
|
521
|
+
ingestion = self.session.ingestion
|
|
522
|
+
if not ingestion.ready or not ingestion.url or not ingestion.ws_token:
|
|
523
|
+
raise FaceModeProtocolError(
|
|
524
|
+
"FaceMode ingestion assignment is not ready"
|
|
525
|
+
)
|
|
526
|
+
subprotocols = [f"facemode.{ingestion.ws_token}"]
|
|
527
|
+
try:
|
|
528
|
+
# pyproject.toml requires websockets>=14, where additional_headers is
|
|
529
|
+
# the supported custom-handshake API. Do not retry without the headers:
|
|
530
|
+
# they may contain the backend-issued strict worker affinity directive.
|
|
531
|
+
self.websocket = await websockets.connect(
|
|
532
|
+
ingestion.url,
|
|
533
|
+
subprotocols=subprotocols,
|
|
534
|
+
additional_headers=dict(ingestion.headers),
|
|
535
|
+
max_size=2**20,
|
|
536
|
+
ping_interval=None,
|
|
537
|
+
compression=None,
|
|
538
|
+
open_timeout=_WS_OPEN_TIMEOUT_SECONDS,
|
|
539
|
+
)
|
|
540
|
+
except Exception as error:
|
|
541
|
+
raise FaceModeProtocolError(
|
|
542
|
+
f"Unable to connect to FaceMode WebSocket: {_safe_error(error, ingestion.ws_token)}"
|
|
543
|
+
) from error
|
|
544
|
+
self._transport_ready_event.set()
|
|
545
|
+
|
|
546
|
+
async def _open_protocol_socket(self) -> None:
|
|
547
|
+
"""Open the canonical socket and run the start handshake on it."""
|
|
548
|
+
await self._connect_websocket()
|
|
549
|
+
if self._stopping:
|
|
550
|
+
websocket = self.websocket
|
|
551
|
+
self.websocket = None
|
|
552
|
+
if websocket is not None:
|
|
553
|
+
with contextlib.suppress(Exception):
|
|
554
|
+
await asyncio.wait_for(
|
|
555
|
+
websocket.close(), timeout=_WS_CLOSE_TIMEOUT
|
|
556
|
+
)
|
|
557
|
+
raise FaceModeProtocolError("FaceMode session is stopping")
|
|
558
|
+
self._receiver_task = asyncio.create_task(
|
|
559
|
+
self._receive_events(), name="facemode-ws-receiver"
|
|
560
|
+
)
|
|
561
|
+
self._keepalive_task = asyncio.create_task(
|
|
562
|
+
self._keepalive_loop(), name="facemode-ws-keepalive"
|
|
563
|
+
)
|
|
564
|
+
await self._ensure_protocol_started(
|
|
565
|
+
self._audio_sample_rate or 24_000, self._audio_channels or 1
|
|
566
|
+
)
|
|
567
|
+
|
|
568
|
+
def _reconnect_blocked(self) -> bool:
|
|
569
|
+
"""Return whether transport recovery is currently disallowed."""
|
|
570
|
+
return (
|
|
571
|
+
self._stopping
|
|
572
|
+
or not self._started
|
|
573
|
+
or self.session is None
|
|
574
|
+
or self._transport_terminal
|
|
575
|
+
or self._session_ended_event.is_set()
|
|
576
|
+
)
|
|
577
|
+
|
|
578
|
+
async def _await_transport(self) -> None:
|
|
579
|
+
"""Block a send while a dropped socket is being reconnected."""
|
|
580
|
+
if self.websocket is not None:
|
|
581
|
+
return
|
|
582
|
+
if self._reconnect_blocked():
|
|
583
|
+
if self._protocol_error is not None:
|
|
584
|
+
raise self._protocol_error
|
|
585
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
586
|
+
try:
|
|
587
|
+
await asyncio.wait_for(
|
|
588
|
+
self._transport_ready_event.wait(), timeout=self.protocol_timeout
|
|
589
|
+
)
|
|
590
|
+
except asyncio.TimeoutError as error:
|
|
591
|
+
raise FaceModeProtocolError(
|
|
592
|
+
"Timed out waiting for FaceMode WebSocket reconnect"
|
|
593
|
+
) from error
|
|
594
|
+
if self.websocket is not None:
|
|
595
|
+
return
|
|
596
|
+
if self._protocol_error is not None:
|
|
597
|
+
raise self._protocol_error
|
|
598
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
599
|
+
|
|
600
|
+
async def _maybe_recover_transport(self, websocket: Any) -> bool:
|
|
601
|
+
"""Single-flight reconnect after the canonical socket dropped.
|
|
602
|
+
|
|
603
|
+
Only runs when the session was fully started and the loss was not an
|
|
604
|
+
intentional close, a server-terminal state, or an ``ended`` frame. At
|
|
605
|
+
most ``_RECONNECT_MAX_ATTEMPTS`` reconnects are tried with backoff, and
|
|
606
|
+
each attempt fetches a fresh one-time WebSocket token. Returns True when
|
|
607
|
+
a new socket negotiated ``started`` and the session resumed.
|
|
608
|
+
"""
|
|
609
|
+
if self.websocket is not None and self.websocket is not websocket:
|
|
610
|
+
return True # a concurrent flight already reconnected
|
|
611
|
+
if self._reconnect_blocked():
|
|
612
|
+
return False
|
|
613
|
+
async with self._reconnect_lock:
|
|
614
|
+
if self.websocket is not None and self.websocket is not websocket:
|
|
615
|
+
return True
|
|
616
|
+
if self._reconnect_blocked():
|
|
617
|
+
return False
|
|
618
|
+
delay = _RECONNECT_INITIAL_BACKOFF_SECONDS
|
|
619
|
+
last_error: FaceModeError | None = None
|
|
620
|
+
for attempt in range(1, _RECONNECT_MAX_ATTEMPTS + 1):
|
|
621
|
+
try:
|
|
622
|
+
await self._reconnect_once()
|
|
623
|
+
except asyncio.CancelledError:
|
|
624
|
+
# A cancelled flight must not leave a half-open socket or
|
|
625
|
+
# orphaned receiver/keepalive tasks behind.
|
|
626
|
+
with contextlib.suppress(Exception):
|
|
627
|
+
await self._drop_connection_attempt()
|
|
628
|
+
raise
|
|
629
|
+
except Exception as error:
|
|
630
|
+
await self._drop_connection_attempt()
|
|
631
|
+
last_error = (
|
|
632
|
+
error
|
|
633
|
+
if isinstance(error, FaceModeError)
|
|
634
|
+
else FaceModeProtocolError(
|
|
635
|
+
"FaceMode reconnect attempt failed: "
|
|
636
|
+
f"{_safe_error(error)}"
|
|
637
|
+
)
|
|
638
|
+
)
|
|
639
|
+
logger.warning(
|
|
640
|
+
"FaceMode reconnect attempt %s/%s failed session=%s: %s",
|
|
641
|
+
attempt,
|
|
642
|
+
_RECONNECT_MAX_ATTEMPTS,
|
|
643
|
+
self._session_log_marker,
|
|
644
|
+
_safe_error(last_error),
|
|
645
|
+
)
|
|
646
|
+
if self._reconnect_blocked():
|
|
647
|
+
break
|
|
648
|
+
if attempt < _RECONNECT_MAX_ATTEMPTS:
|
|
649
|
+
await asyncio.sleep(delay)
|
|
650
|
+
delay = min(delay * 2.0, _RECONNECT_MAX_BACKOFF_SECONDS)
|
|
651
|
+
continue
|
|
652
|
+
logger.info(
|
|
653
|
+
"FaceMode WebSocket reconnected session=%s",
|
|
654
|
+
self._session_log_marker,
|
|
655
|
+
)
|
|
656
|
+
return True
|
|
657
|
+
if not self._started or self.session is None:
|
|
658
|
+
return False # the session was torn down while reconnecting
|
|
659
|
+
self._transport_terminal = True
|
|
660
|
+
detail = ""
|
|
661
|
+
if last_error is not None:
|
|
662
|
+
detail = ": " + _safe_error(
|
|
663
|
+
last_error,
|
|
664
|
+
self.session.ingestion.ws_token if self.session else None,
|
|
665
|
+
)
|
|
666
|
+
self._set_protocol_error(
|
|
667
|
+
FaceModeProtocolError(
|
|
668
|
+
"FaceMode WebSocket reconnect failed after "
|
|
669
|
+
f"{_RECONNECT_MAX_ATTEMPTS} attempts{detail}"
|
|
670
|
+
)
|
|
671
|
+
)
|
|
672
|
+
self._transport_ready_event.set()
|
|
673
|
+
return False
|
|
674
|
+
|
|
675
|
+
async def _reconnect_once(self) -> None:
|
|
676
|
+
"""Run one reconnect attempt against a clean per-connection slate."""
|
|
677
|
+
await self._drop_connection_attempt()
|
|
678
|
+
session = self.session
|
|
679
|
+
if session is None:
|
|
680
|
+
raise FaceModeProtocolError("FaceMode session is not initialized")
|
|
681
|
+
if self._stopping or self._transport_terminal:
|
|
682
|
+
raise FaceModeProtocolError("FaceMode session stopped during reconnect")
|
|
683
|
+
refreshed = await self._request_session_reconnect(session)
|
|
684
|
+
if self._stopping or self._transport_terminal:
|
|
685
|
+
raise FaceModeProtocolError("FaceMode session stopped during reconnect")
|
|
686
|
+
if refreshed.session_id != session.session_id:
|
|
687
|
+
raise FaceModeProtocolError(
|
|
688
|
+
"FaceMode reconnect returned a different session"
|
|
689
|
+
)
|
|
690
|
+
if refreshed.worker_status in {"FAILED", "ENDED"}:
|
|
691
|
+
raise FaceModeAPIError(
|
|
692
|
+
"FaceMode worker entered "
|
|
693
|
+
f"{refreshed.worker_status.lower()} state during reconnect"
|
|
694
|
+
)
|
|
695
|
+
ingestion = refreshed.ingestion
|
|
696
|
+
if not ingestion.ready or not ingestion.url or not ingestion.ws_token:
|
|
697
|
+
raise FaceModeAPIError(
|
|
698
|
+
"FaceMode reconnect response is missing WebSocket credentials"
|
|
699
|
+
)
|
|
700
|
+
self.session = refreshed
|
|
701
|
+
self._session_ended_event.clear()
|
|
702
|
+
self._utterance_context_id = None
|
|
703
|
+
self._cancel_utterance_timer()
|
|
704
|
+
await self._open_protocol_socket()
|
|
705
|
+
if self._stopping or self._transport_terminal:
|
|
706
|
+
raise FaceModeProtocolError("FaceMode session stopped during reconnect")
|
|
707
|
+
if self._utterance_active:
|
|
708
|
+
# The fresh socket has no utterance state. Re-declare the open
|
|
709
|
+
# utterance so following audio stays inside it without replaying.
|
|
710
|
+
await self._send_control("start_utterance")
|
|
711
|
+
self._arm_utterance_end_timer()
|
|
712
|
+
|
|
713
|
+
async def _drop_connection_attempt(self) -> None:
|
|
714
|
+
"""Cancel per-connection tasks and close the current socket."""
|
|
715
|
+
current = asyncio.current_task()
|
|
716
|
+
keepalive = self._keepalive_task
|
|
717
|
+
self._keepalive_task = None
|
|
718
|
+
receiver = self._receiver_task
|
|
719
|
+
if receiver is not current:
|
|
720
|
+
self._receiver_task = None
|
|
721
|
+
for task in (keepalive, receiver):
|
|
722
|
+
if task is not None and task is not current and not task.done():
|
|
723
|
+
task.cancel()
|
|
724
|
+
for task in (keepalive, receiver):
|
|
725
|
+
if task is not None and task is not current:
|
|
726
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
727
|
+
await task
|
|
728
|
+
websocket = self.websocket
|
|
729
|
+
self.websocket = None
|
|
730
|
+
self._transport_ready_event.clear()
|
|
731
|
+
if websocket is not None:
|
|
732
|
+
with contextlib.suppress(Exception):
|
|
733
|
+
await asyncio.wait_for(websocket.close(), timeout=_WS_CLOSE_TIMEOUT)
|
|
734
|
+
self._protocol_started = False
|
|
735
|
+
self._protocol_start_sent = False
|
|
736
|
+
self._protocol_error = None
|
|
737
|
+
self._protocol_started_event.clear()
|
|
738
|
+
|
|
739
|
+
async def _request_session_reconnect(self, session: SessionDetails) -> SessionDetails:
|
|
740
|
+
"""Ask the API for a fresh one-time WebSocket credential.
|
|
741
|
+
|
|
742
|
+
The reconnect body carries only the original room object plus the
|
|
743
|
+
persisted ``inputProvider`` when one was configured; the backend rejects
|
|
744
|
+
any other field and any attempt to change the provider.
|
|
745
|
+
"""
|
|
746
|
+
payload: dict[str, Any] = {"room": self.room_config.to_payload()}
|
|
747
|
+
if self.input_provider:
|
|
748
|
+
payload["inputProvider"] = self.input_provider
|
|
749
|
+
headers = {
|
|
750
|
+
"Authorization": f"Bearer {self.api_key}",
|
|
751
|
+
"Content-Type": "application/json",
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
async def post(client: aiohttp.ClientSession) -> SessionDetails:
|
|
755
|
+
try:
|
|
756
|
+
async with client.post(
|
|
757
|
+
f"{self.api_url}/sessions/{session.session_id}/reconnect",
|
|
758
|
+
json=payload,
|
|
759
|
+
headers=headers,
|
|
760
|
+
) as response:
|
|
761
|
+
body = await response.text()
|
|
762
|
+
if response.status >= 400:
|
|
763
|
+
raise FaceModeAPIError(
|
|
764
|
+
"FaceMode session reconnect failed "
|
|
765
|
+
f"(HTTP {response.status})"
|
|
766
|
+
)
|
|
767
|
+
except FaceModeAPIError:
|
|
768
|
+
raise
|
|
769
|
+
except Exception as error:
|
|
770
|
+
raise FaceModeAPIError(
|
|
771
|
+
"FaceMode session reconnect request failed: "
|
|
772
|
+
f"{_safe_error(error, self.api_key, self.room_config.token)}"
|
|
773
|
+
) from error
|
|
774
|
+
|
|
775
|
+
try:
|
|
776
|
+
response_payload = json.loads(body)
|
|
777
|
+
except json.JSONDecodeError as error:
|
|
778
|
+
raise FaceModeAPIError(
|
|
779
|
+
"FaceMode reconnect response was not JSON"
|
|
780
|
+
) from error
|
|
781
|
+
if not isinstance(response_payload, Mapping):
|
|
782
|
+
raise FaceModeAPIError(
|
|
783
|
+
"FaceMode reconnect response was not an object"
|
|
784
|
+
)
|
|
785
|
+
try:
|
|
786
|
+
return SessionDetails.from_api(response_payload, fallback=session)
|
|
787
|
+
except ValueError as error:
|
|
788
|
+
raise FaceModeAPIError(
|
|
789
|
+
"FaceMode reconnect response is incomplete"
|
|
790
|
+
) from error
|
|
791
|
+
|
|
792
|
+
timeout = aiohttp.ClientTimeout(total=self.api_timeout)
|
|
793
|
+
if self._http_session is not None:
|
|
794
|
+
return await post(self._http_session)
|
|
795
|
+
async with aiohttp.ClientSession(timeout=timeout) as client:
|
|
796
|
+
return await post(client)
|
|
797
|
+
|
|
798
|
+
async def _send_tts_frame(self, frame: TTSAudioRawFrame) -> None:
|
|
799
|
+
sample_rate = _optional_int(getattr(frame, "sample_rate", None))
|
|
800
|
+
channels = _optional_int(getattr(frame, "num_channels", None))
|
|
801
|
+
if sample_rate is None or channels is None:
|
|
802
|
+
raise FaceModeProtocolError("TTS audio is missing sample rate or channel count")
|
|
803
|
+
await self._ensure_protocol_started(sample_rate, channels)
|
|
804
|
+
|
|
805
|
+
context_id = getattr(frame, "context_id", None)
|
|
806
|
+
context_id = str(context_id) if context_id is not None else None
|
|
807
|
+
if self._utterance_active and context_id and self._utterance_context_id:
|
|
808
|
+
if context_id != self._utterance_context_id:
|
|
809
|
+
await self._end_utterance()
|
|
810
|
+
if not self._utterance_active:
|
|
811
|
+
await self._send_control("start_utterance")
|
|
812
|
+
self._utterance_active = True
|
|
813
|
+
self._utterance_context_id = context_id
|
|
814
|
+
|
|
815
|
+
audio = bytes(getattr(frame, "audio", b""))
|
|
816
|
+
if not audio:
|
|
817
|
+
return
|
|
818
|
+
if len(audio) % (2 * channels):
|
|
819
|
+
raise FaceModeProtocolError("TTS PCM payload is not channel aligned")
|
|
820
|
+
await self._send_binary(audio)
|
|
821
|
+
self._arm_utterance_end_timer()
|
|
822
|
+
|
|
823
|
+
async def _ensure_protocol_started(self, sample_rate: int, channels: int) -> None:
|
|
824
|
+
if self._protocol_error is not None:
|
|
825
|
+
raise self._protocol_error
|
|
826
|
+
if isinstance(sample_rate, bool) or not isinstance(sample_rate, int):
|
|
827
|
+
raise FaceModeProtocolError("TTS sample rate for FaceMode must be an integer")
|
|
828
|
+
if not _MIN_INPUT_SAMPLE_RATE <= sample_rate <= _MAX_INPUT_SAMPLE_RATE:
|
|
829
|
+
raise FaceModeProtocolError(
|
|
830
|
+
f"TTS sample rate for FaceMode must be between {_MIN_INPUT_SAMPLE_RATE} "
|
|
831
|
+
f"and {_MAX_INPUT_SAMPLE_RATE}: {sample_rate}"
|
|
832
|
+
)
|
|
833
|
+
if sample_rate not in _PREFERRED_SAMPLE_RATES:
|
|
834
|
+
logger.info("Using uncommon Pipecat TTS sample rate: %s", sample_rate)
|
|
835
|
+
if channels not in _SUPPORTED_CHANNELS:
|
|
836
|
+
raise FaceModeProtocolError(
|
|
837
|
+
f"Unsupported TTS channel count for FaceMode: {channels}"
|
|
838
|
+
)
|
|
839
|
+
if self.websocket is None:
|
|
840
|
+
await self._await_transport()
|
|
841
|
+
if self.websocket is None or self.session is None:
|
|
842
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
843
|
+
|
|
844
|
+
if self._protocol_started or self._protocol_start_sent:
|
|
845
|
+
if self._audio_sample_rate != sample_rate or self._audio_channels != channels:
|
|
846
|
+
raise FaceModeProtocolError(
|
|
847
|
+
"TTS audio format changed during the FaceMode session"
|
|
848
|
+
)
|
|
849
|
+
if self._protocol_started:
|
|
850
|
+
return
|
|
851
|
+
|
|
852
|
+
async with self._send_lock:
|
|
853
|
+
if self._protocol_started:
|
|
854
|
+
return
|
|
855
|
+
if self._protocol_start_sent:
|
|
856
|
+
start_already_sent = True
|
|
857
|
+
else:
|
|
858
|
+
start_already_sent = False
|
|
859
|
+
self._protocol_start_sent = True
|
|
860
|
+
self._audio_sample_rate = sample_rate
|
|
861
|
+
self._audio_channels = channels
|
|
862
|
+
if not start_already_sent:
|
|
863
|
+
await self._send_json(
|
|
864
|
+
{
|
|
865
|
+
"type": "start",
|
|
866
|
+
"session_id": self.session.session_id,
|
|
867
|
+
"audio_encoding": "pcm_s16le",
|
|
868
|
+
"sample_rate": sample_rate,
|
|
869
|
+
"channels": channels,
|
|
870
|
+
"avatar_id": self.avatar_id,
|
|
871
|
+
"metadata": {"source": "pipecat-facemode"},
|
|
872
|
+
},
|
|
873
|
+
assume_lock=True,
|
|
874
|
+
)
|
|
875
|
+
|
|
876
|
+
try:
|
|
877
|
+
await asyncio.wait_for(
|
|
878
|
+
self._protocol_started_event.wait(), timeout=self.protocol_timeout
|
|
879
|
+
)
|
|
880
|
+
except asyncio.TimeoutError as error:
|
|
881
|
+
raise FaceModeProtocolError(
|
|
882
|
+
"FaceMode did not acknowledge protocol negotiation"
|
|
883
|
+
) from error
|
|
884
|
+
if self._protocol_error is not None:
|
|
885
|
+
raise self._protocol_error
|
|
886
|
+
if not self._protocol_started:
|
|
887
|
+
raise FaceModeProtocolError("FaceMode protocol negotiation did not start")
|
|
888
|
+
|
|
889
|
+
async def _send_control(self, message_type: str) -> None:
|
|
890
|
+
if message_type == "ping":
|
|
891
|
+
await self._send_json({"type": "ping", "ts": int(time.time() * 1000)})
|
|
892
|
+
return
|
|
893
|
+
await self._send_json({"type": message_type, "seq": self._next_sequence()})
|
|
894
|
+
|
|
895
|
+
async def _send_binary(self, audio: bytes) -> None:
|
|
896
|
+
if self._protocol_error is not None:
|
|
897
|
+
raise self._protocol_error
|
|
898
|
+
await self._await_transport()
|
|
899
|
+
# Audio may only flow after the start handshake, so a frame that arrives
|
|
900
|
+
# while a reconnect renegotiates waits for the fresh ``started`` first.
|
|
901
|
+
await self._ensure_protocol_started(
|
|
902
|
+
self._audio_sample_rate or 24_000, self._audio_channels or 1
|
|
903
|
+
)
|
|
904
|
+
async with self._send_lock:
|
|
905
|
+
websocket = self.websocket
|
|
906
|
+
if websocket is None:
|
|
907
|
+
raise FaceModeProtocolError("FaceMode WebSocket is not connected")
|
|
908
|
+
try:
|
|
909
|
+
await websocket.send(audio)
|
|
910
|
+
except Exception as error:
|
|
911
|
+
raise FaceModeProtocolError(
|
|
912
|
+
f"Unable to send audio to FaceMode: {_safe_error(error, self.session.ingestion.ws_token if self.session else None)}"
|
|
913
|
+
) from error
|
|
914
|
+
|
|
915
|
+
async def _send_json(self, message: dict[str, Any], *, assume_lock: bool = False) -> None:
|
|
916
|
+
if assume_lock:
|
|
917
|
+
await self._send_json_locked(message)
|
|
918
|
+
return
|
|
919
|
+
await self._await_transport()
|
|
920
|
+
async with self._send_lock:
|
|
921
|
+
await self._send_json_locked(message)
|
|
922
|
+
|
|
923
|
+
async def _send_json_locked(self, message: dict[str, Any]) -> None:
|
|
924
|
+
websocket = self.websocket
|
|
925
|
+
if websocket is None:
|
|
926
|
+
return
|
|
927
|
+
try:
|
|
928
|
+
await websocket.send(json.dumps(message, separators=(",", ":")))
|
|
929
|
+
except Exception as error:
|
|
930
|
+
protocol_error = FaceModeProtocolError(
|
|
931
|
+
f"Unable to send FaceMode protocol message: {_safe_error(error)}"
|
|
932
|
+
)
|
|
933
|
+
self._set_protocol_error(protocol_error)
|
|
934
|
+
raise protocol_error from error
|
|
935
|
+
|
|
936
|
+
async def _receive_events(self) -> None:
|
|
937
|
+
websocket = self.websocket
|
|
938
|
+
if websocket is None:
|
|
939
|
+
return
|
|
940
|
+
try:
|
|
941
|
+
async for raw in websocket:
|
|
942
|
+
if isinstance(raw, (bytes, bytearray, memoryview)):
|
|
943
|
+
continue
|
|
944
|
+
try:
|
|
945
|
+
message = json.loads(raw)
|
|
946
|
+
except (TypeError, json.JSONDecodeError) as error:
|
|
947
|
+
raise FaceModeProtocolError(
|
|
948
|
+
"FaceMode WebSocket message was not JSON"
|
|
949
|
+
) from error
|
|
950
|
+
if not isinstance(message, Mapping):
|
|
951
|
+
raise FaceModeProtocolError(
|
|
952
|
+
"FaceMode WebSocket message was not an object"
|
|
953
|
+
)
|
|
954
|
+
message_type = str(message.get("type", ""))
|
|
955
|
+
if message_type == "started":
|
|
956
|
+
if self.session is None:
|
|
957
|
+
raise FaceModeProtocolError("FaceMode session is not initialized")
|
|
958
|
+
if str(message.get("session_id", "")) != self.session.session_id:
|
|
959
|
+
raise FaceModeProtocolError(
|
|
960
|
+
"FaceMode started response session ID did not match"
|
|
961
|
+
)
|
|
962
|
+
if (
|
|
963
|
+
message.get("server_sample_rate") != 48_000
|
|
964
|
+
or message.get("server_channels") != 1
|
|
965
|
+
):
|
|
966
|
+
raise FaceModeProtocolError(
|
|
967
|
+
"FaceMode server reported an unsupported canonical audio format"
|
|
968
|
+
)
|
|
969
|
+
self._protocol_started = True
|
|
970
|
+
self._protocol_started_event.set()
|
|
971
|
+
logger.info("FaceMode protocol started session=%s", self._session_log_marker)
|
|
972
|
+
elif message_type == "audio_ready":
|
|
973
|
+
self._avatar_ready_event.set()
|
|
974
|
+
elif message_type == "utterance_ended":
|
|
975
|
+
logger.debug(
|
|
976
|
+
"FaceMode utterance ended seq=%s cycles=%s",
|
|
977
|
+
message.get("seq"),
|
|
978
|
+
message.get("cycles"),
|
|
979
|
+
)
|
|
980
|
+
elif message_type == "pong":
|
|
981
|
+
logger.debug("FaceMode keepalive acknowledged")
|
|
982
|
+
elif message_type == "session_ending":
|
|
983
|
+
self._transport_terminal = True
|
|
984
|
+
raise FaceModeProtocolError(
|
|
985
|
+
f"FaceMode session is ending: {_safe_text(message.get('reason'), 'unknown')}"
|
|
986
|
+
)
|
|
987
|
+
elif message_type == "ended":
|
|
988
|
+
self._transport_terminal = True
|
|
989
|
+
self._session_ended_event.set()
|
|
990
|
+
break
|
|
991
|
+
elif message_type == "error":
|
|
992
|
+
code = _safe_text(message.get("code"), "INTERNAL_ERROR")
|
|
993
|
+
detail = _safe_text(message.get("message"), "FaceMode protocol error")
|
|
994
|
+
protocol_error = FaceModeProtocolError(f"{code}: {detail}")
|
|
995
|
+
self._set_protocol_error(protocol_error)
|
|
996
|
+
logger.error("FaceMode protocol error code=%s", code)
|
|
997
|
+
if bool(message.get("fatal", False)):
|
|
998
|
+
self._transport_terminal = True
|
|
999
|
+
if bool(message.get("fatal", False)) or not self._protocol_started:
|
|
1000
|
+
break
|
|
1001
|
+
else:
|
|
1002
|
+
logger.debug("FaceMode WebSocket unhandled message type: %s", message_type)
|
|
1003
|
+
except asyncio.CancelledError:
|
|
1004
|
+
raise
|
|
1005
|
+
except Exception as error:
|
|
1006
|
+
if not self._stopping:
|
|
1007
|
+
# Transport faults are recoverable after a successful start;
|
|
1008
|
+
# protocol violations are authoritative and are not retried.
|
|
1009
|
+
if not isinstance(error, FaceModeProtocolError) and (
|
|
1010
|
+
await self._maybe_recover_transport(websocket)
|
|
1011
|
+
):
|
|
1012
|
+
return
|
|
1013
|
+
protocol_error = (
|
|
1014
|
+
error
|
|
1015
|
+
if isinstance(error, FaceModeProtocolError)
|
|
1016
|
+
else FaceModeProtocolError(
|
|
1017
|
+
"FaceMode WebSocket receiver stopped: "
|
|
1018
|
+
f"{_safe_error(error)}{_websocket_close_details(error)}"
|
|
1019
|
+
)
|
|
1020
|
+
)
|
|
1021
|
+
self._set_protocol_error(protocol_error)
|
|
1022
|
+
logger.warning("%s", protocol_error)
|
|
1023
|
+
else:
|
|
1024
|
+
if not self._stopping:
|
|
1025
|
+
if await self._maybe_recover_transport(websocket):
|
|
1026
|
+
return
|
|
1027
|
+
if self._protocol_error is None:
|
|
1028
|
+
self._set_protocol_error(
|
|
1029
|
+
FaceModeProtocolError(
|
|
1030
|
+
"FaceMode WebSocket closed unexpectedly"
|
|
1031
|
+
f"{_websocket_close_details(websocket)}"
|
|
1032
|
+
)
|
|
1033
|
+
)
|
|
1034
|
+
|
|
1035
|
+
async def _keepalive_loop(self) -> None:
|
|
1036
|
+
try:
|
|
1037
|
+
await self._protocol_started_event.wait()
|
|
1038
|
+
if not self._protocol_started or self._protocol_error is not None:
|
|
1039
|
+
return
|
|
1040
|
+
while not self._stopping:
|
|
1041
|
+
await asyncio.sleep(15.0)
|
|
1042
|
+
if self.websocket is None or self._stopping:
|
|
1043
|
+
return
|
|
1044
|
+
try:
|
|
1045
|
+
await self._send_control("ping")
|
|
1046
|
+
except FaceModeError as error:
|
|
1047
|
+
if not self._stopping:
|
|
1048
|
+
self._set_protocol_error(error)
|
|
1049
|
+
logger.warning("FaceMode keepalive stopped: %s", _safe_error(error))
|
|
1050
|
+
return
|
|
1051
|
+
except asyncio.CancelledError:
|
|
1052
|
+
raise
|
|
1053
|
+
|
|
1054
|
+
async def _end_utterance(self) -> None:
|
|
1055
|
+
self._cancel_utterance_timer()
|
|
1056
|
+
if not self._utterance_active:
|
|
1057
|
+
return
|
|
1058
|
+
self._utterance_active = False
|
|
1059
|
+
self._utterance_context_id = None
|
|
1060
|
+
if self._protocol_started and self.websocket is not None and not self._stopping:
|
|
1061
|
+
await self._send_control("end_utterance")
|
|
1062
|
+
|
|
1063
|
+
async def _cancel_utterance(self) -> None:
|
|
1064
|
+
self._cancel_utterance_timer()
|
|
1065
|
+
was_active = self._utterance_active
|
|
1066
|
+
self._utterance_active = False
|
|
1067
|
+
self._utterance_context_id = None
|
|
1068
|
+
if was_active and self._protocol_started and self.websocket is not None:
|
|
1069
|
+
await self._send_control("cancel_utterance")
|
|
1070
|
+
|
|
1071
|
+
def _arm_utterance_end_timer(self) -> None:
|
|
1072
|
+
self._cancel_utterance_timer()
|
|
1073
|
+
self._utterance_generation += 1
|
|
1074
|
+
generation = self._utterance_generation
|
|
1075
|
+
self._utterance_end_task = asyncio.create_task(
|
|
1076
|
+
self._end_utterance_after_idle(generation), name="facemode-utterance-end"
|
|
1077
|
+
)
|
|
1078
|
+
|
|
1079
|
+
async def _end_utterance_after_idle(self, generation: int) -> None:
|
|
1080
|
+
try:
|
|
1081
|
+
await asyncio.sleep(self.utterance_idle_timeout)
|
|
1082
|
+
if generation == self._utterance_generation and not self._stopping:
|
|
1083
|
+
self._utterance_end_task = None
|
|
1084
|
+
await self._end_utterance()
|
|
1085
|
+
except asyncio.CancelledError:
|
|
1086
|
+
raise
|
|
1087
|
+
except FaceModeError as error:
|
|
1088
|
+
if not self._stopping:
|
|
1089
|
+
logger.warning("Unable to end FaceMode utterance: %s", _safe_error(error))
|
|
1090
|
+
|
|
1091
|
+
def _cancel_utterance_timer(self) -> None:
|
|
1092
|
+
task = self._utterance_end_task
|
|
1093
|
+
self._utterance_end_task = None
|
|
1094
|
+
if (
|
|
1095
|
+
task is not None
|
|
1096
|
+
and task is not asyncio.current_task()
|
|
1097
|
+
and not task.done()
|
|
1098
|
+
):
|
|
1099
|
+
task.cancel()
|
|
1100
|
+
|
|
1101
|
+
def _on_track_subscribed(
|
|
1102
|
+
self,
|
|
1103
|
+
track: Any,
|
|
1104
|
+
publication: Any,
|
|
1105
|
+
participant: Any,
|
|
1106
|
+
) -> None:
|
|
1107
|
+
if (
|
|
1108
|
+
self._stopping
|
|
1109
|
+
or not self._accept_tracks
|
|
1110
|
+
or not self._is_avatar_participant(participant)
|
|
1111
|
+
):
|
|
1112
|
+
return
|
|
1113
|
+
kind = getattr(track, "kind", None)
|
|
1114
|
+
if not _is_audio_track_kind(kind) and not _is_video_track_kind(kind):
|
|
1115
|
+
return
|
|
1116
|
+
key = str(
|
|
1117
|
+
getattr(publication, "sid", None)
|
|
1118
|
+
or getattr(track, "sid", None)
|
|
1119
|
+
or id(track)
|
|
1120
|
+
)
|
|
1121
|
+
self._cancel_track_task(key)
|
|
1122
|
+
self._track_kinds[key] = kind
|
|
1123
|
+
if _is_video_track_kind(kind):
|
|
1124
|
+
task = asyncio.create_task(
|
|
1125
|
+
self._consume_video_track(key, track), name="facemode-livekit-video"
|
|
1126
|
+
)
|
|
1127
|
+
else:
|
|
1128
|
+
task = asyncio.create_task(
|
|
1129
|
+
self._consume_audio_track(key, track), name="facemode-livekit-audio"
|
|
1130
|
+
)
|
|
1131
|
+
self._track_tasks[key] = task
|
|
1132
|
+
|
|
1133
|
+
def _on_track_unsubscribed(self, track: Any, publication: Any, participant: Any) -> None:
|
|
1134
|
+
del track, participant
|
|
1135
|
+
key = str(getattr(publication, "sid", None) or "")
|
|
1136
|
+
if key:
|
|
1137
|
+
self._cancel_track_task(key)
|
|
1138
|
+
|
|
1139
|
+
def _is_avatar_participant(self, participant: Any) -> bool:
|
|
1140
|
+
identity = str(getattr(participant, "identity", ""))
|
|
1141
|
+
local_identity = ""
|
|
1142
|
+
if self.room is not None:
|
|
1143
|
+
local_participant = getattr(self.room, "local_participant", None)
|
|
1144
|
+
local_identity = str(getattr(local_participant, "identity", ""))
|
|
1145
|
+
if identity and identity == local_identity:
|
|
1146
|
+
return False
|
|
1147
|
+
expected = self.avatar_participant_identity or (
|
|
1148
|
+
self.session.avatar_participant_identity if self.session else None
|
|
1149
|
+
) or "facemode-avatar"
|
|
1150
|
+
return identity == expected
|
|
1151
|
+
|
|
1152
|
+
async def _consume_audio_track(self, key: str, track: Any) -> None:
|
|
1153
|
+
stream = None
|
|
1154
|
+
try:
|
|
1155
|
+
try:
|
|
1156
|
+
stream = rtc.AudioStream(track, capacity=8)
|
|
1157
|
+
except TypeError:
|
|
1158
|
+
stream = rtc.AudioStream(track)
|
|
1159
|
+
self._track_streams[key] = stream
|
|
1160
|
+
async for event in stream:
|
|
1161
|
+
if self._stopping:
|
|
1162
|
+
break
|
|
1163
|
+
audio_frame = getattr(event, "frame", event)
|
|
1164
|
+
audio = bytes(getattr(audio_frame, "data", b""))
|
|
1165
|
+
if not audio:
|
|
1166
|
+
continue
|
|
1167
|
+
output = OutputAudioRawFrame(
|
|
1168
|
+
audio=audio,
|
|
1169
|
+
sample_rate=_optional_int(getattr(audio_frame, "sample_rate", None)) or 48_000,
|
|
1170
|
+
num_channels=_optional_int(getattr(audio_frame, "num_channels", None)) or 1,
|
|
1171
|
+
)
|
|
1172
|
+
await self.push_frame(output, FrameDirection.DOWNSTREAM)
|
|
1173
|
+
except asyncio.CancelledError:
|
|
1174
|
+
raise
|
|
1175
|
+
except Exception as error:
|
|
1176
|
+
if not self._stopping:
|
|
1177
|
+
logger.warning(
|
|
1178
|
+
"FaceMode LiveKit audio receiver stopped: %s", _safe_error(error)
|
|
1179
|
+
)
|
|
1180
|
+
finally:
|
|
1181
|
+
await _close_async_resource(stream)
|
|
1182
|
+
if self._track_streams.get(key) is stream:
|
|
1183
|
+
self._track_streams.pop(key, None)
|
|
1184
|
+
|
|
1185
|
+
async def _consume_video_track(self, key: str, track: Any) -> None:
|
|
1186
|
+
stream = None
|
|
1187
|
+
try:
|
|
1188
|
+
stream = _make_video_stream(track)
|
|
1189
|
+
self._track_streams[key] = stream
|
|
1190
|
+
async for event in stream:
|
|
1191
|
+
if self._stopping:
|
|
1192
|
+
break
|
|
1193
|
+
video_frame = getattr(event, "frame", event)
|
|
1194
|
+
output = _video_frame_to_pipecat(video_frame)
|
|
1195
|
+
if output is not None:
|
|
1196
|
+
self._avatar_ready_event.set()
|
|
1197
|
+
await self.push_frame(output, FrameDirection.DOWNSTREAM)
|
|
1198
|
+
except asyncio.CancelledError:
|
|
1199
|
+
raise
|
|
1200
|
+
except Exception as error:
|
|
1201
|
+
if not self._stopping:
|
|
1202
|
+
logger.warning(
|
|
1203
|
+
"FaceMode LiveKit video receiver stopped: %s", _safe_error(error)
|
|
1204
|
+
)
|
|
1205
|
+
finally:
|
|
1206
|
+
await _close_async_resource(stream)
|
|
1207
|
+
if self._track_streams.get(key) is stream:
|
|
1208
|
+
self._track_streams.pop(key, None)
|
|
1209
|
+
|
|
1210
|
+
def _cancel_track_task(self, key: str) -> None:
|
|
1211
|
+
task = self._track_tasks.pop(key, None)
|
|
1212
|
+
self._track_kinds.pop(key, None)
|
|
1213
|
+
if task is not None and not task.done():
|
|
1214
|
+
task.cancel()
|
|
1215
|
+
|
|
1216
|
+
async def _shutdown(self, *, send_end_session: bool) -> None:
|
|
1217
|
+
async with self._lifecycle_lock:
|
|
1218
|
+
await self._shutdown_locked(send_end_session=send_end_session)
|
|
1219
|
+
|
|
1220
|
+
async def _shutdown_locked(self, *, send_end_session: bool) -> None:
|
|
1221
|
+
"""Tear down session resources; caller must hold ``_lifecycle_lock``."""
|
|
1222
|
+
if self._stopping and not self._started and self.websocket is None and self.room is None:
|
|
1223
|
+
return
|
|
1224
|
+
self._stopping = True
|
|
1225
|
+
self._transport_terminal = True
|
|
1226
|
+
self._transport_ready_event.set()
|
|
1227
|
+
self._accept_tracks = False
|
|
1228
|
+
self._cancel_utterance_timer()
|
|
1229
|
+
|
|
1230
|
+
websocket = self.websocket
|
|
1231
|
+
if send_end_session and websocket is not None and self._protocol_started:
|
|
1232
|
+
# wait_for raises builtin TimeoutError when the server never sends
|
|
1233
|
+
# "ended"; it must not escape or the teardown below is skipped.
|
|
1234
|
+
with contextlib.suppress(FaceModeError, asyncio.TimeoutError):
|
|
1235
|
+
if self._utterance_active:
|
|
1236
|
+
await self._send_control("end_utterance")
|
|
1237
|
+
await self._send_control("end_session")
|
|
1238
|
+
await asyncio.wait_for(
|
|
1239
|
+
self._session_ended_event.wait(),
|
|
1240
|
+
timeout=_END_ACK_TIMEOUT_SECONDS,
|
|
1241
|
+
)
|
|
1242
|
+
self._utterance_active = False
|
|
1243
|
+
self._utterance_context_id = None
|
|
1244
|
+
|
|
1245
|
+
current = asyncio.current_task()
|
|
1246
|
+
tasks = [
|
|
1247
|
+
self._keepalive_task,
|
|
1248
|
+
self._receiver_task,
|
|
1249
|
+
*self._track_tasks.values(),
|
|
1250
|
+
]
|
|
1251
|
+
self._keepalive_task = None
|
|
1252
|
+
self._receiver_task = None
|
|
1253
|
+
self._track_tasks.clear()
|
|
1254
|
+
self._track_kinds.clear()
|
|
1255
|
+
for task in tasks:
|
|
1256
|
+
if task is not None and task is not current and not task.done():
|
|
1257
|
+
task.cancel()
|
|
1258
|
+
for task in tasks:
|
|
1259
|
+
if task is not None and task is not current:
|
|
1260
|
+
with contextlib.suppress(asyncio.CancelledError, Exception):
|
|
1261
|
+
await task
|
|
1262
|
+
|
|
1263
|
+
for stream in list(self._track_streams.values()):
|
|
1264
|
+
await _close_async_resource(stream)
|
|
1265
|
+
self._track_streams.clear()
|
|
1266
|
+
|
|
1267
|
+
self.websocket = None
|
|
1268
|
+
if websocket is not None:
|
|
1269
|
+
with contextlib.suppress(Exception):
|
|
1270
|
+
await asyncio.wait_for(websocket.close(), timeout=_WS_CLOSE_TIMEOUT)
|
|
1271
|
+
|
|
1272
|
+
room = self.room
|
|
1273
|
+
self.room = None
|
|
1274
|
+
await _disconnect_room(room)
|
|
1275
|
+
|
|
1276
|
+
self.session = None
|
|
1277
|
+
self._session_log_marker = None
|
|
1278
|
+
self._protocol_started = False
|
|
1279
|
+
self._protocol_start_sent = False
|
|
1280
|
+
self._protocol_error = None
|
|
1281
|
+
self._protocol_started_event.set()
|
|
1282
|
+
self._avatar_ready_event.clear()
|
|
1283
|
+
self._started = False
|
|
1284
|
+
self._stopping = False
|
|
1285
|
+
|
|
1286
|
+
def _set_protocol_error(self, error: FaceModeProtocolError) -> None:
|
|
1287
|
+
self._protocol_error = error
|
|
1288
|
+
self._protocol_started_event.set()
|
|
1289
|
+
|
|
1290
|
+
def _next_sequence(self) -> int:
|
|
1291
|
+
sequence = self._sequence
|
|
1292
|
+
self._sequence += 1
|
|
1293
|
+
return sequence
|
|
1294
|
+
|
|
1295
|
+
|
|
1296
|
+
# Short aliases are useful for applications that do not use the video-specific name.
|
|
1297
|
+
FaceModeService = FaceModeVideoService
|
|
1298
|
+
FaceModeProcessor = FaceModeVideoService
|
|
1299
|
+
|
|
1300
|
+
|
|
1301
|
+
def _is_audio_track_kind(kind: Any) -> bool:
|
|
1302
|
+
track_kind = getattr(rtc, "TrackKind", None)
|
|
1303
|
+
return kind == getattr(track_kind, "KIND_AUDIO", object()) or str(kind).lower() in {
|
|
1304
|
+
"audio",
|
|
1305
|
+
"kind_audio",
|
|
1306
|
+
}
|
|
1307
|
+
|
|
1308
|
+
|
|
1309
|
+
def _is_video_track_kind(kind: Any) -> bool:
|
|
1310
|
+
track_kind = getattr(rtc, "TrackKind", None)
|
|
1311
|
+
return kind == getattr(track_kind, "KIND_VIDEO", object()) or str(kind).lower() in {
|
|
1312
|
+
"video",
|
|
1313
|
+
"kind_video",
|
|
1314
|
+
}
|
|
1315
|
+
|
|
1316
|
+
|
|
1317
|
+
def _make_video_stream(track: Any) -> Any:
|
|
1318
|
+
video_buffer_type = getattr(rtc, "VideoBufferType", None)
|
|
1319
|
+
rgb24 = getattr(video_buffer_type, "RGB24", None) if video_buffer_type else None
|
|
1320
|
+
try:
|
|
1321
|
+
if rgb24 is not None:
|
|
1322
|
+
return rtc.VideoStream(track, format=rgb24, capacity=1)
|
|
1323
|
+
return rtc.VideoStream(track, capacity=1)
|
|
1324
|
+
except TypeError:
|
|
1325
|
+
return rtc.VideoStream(track)
|
|
1326
|
+
|
|
1327
|
+
|
|
1328
|
+
def _video_frame_to_pipecat(video_frame: Any) -> Frame | None:
|
|
1329
|
+
width = _optional_int(getattr(video_frame, "width", None)) or 0
|
|
1330
|
+
height = _optional_int(getattr(video_frame, "height", None)) or 0
|
|
1331
|
+
if width <= 0 or height <= 0:
|
|
1332
|
+
return None
|
|
1333
|
+
|
|
1334
|
+
data = getattr(video_frame, "data", b"")
|
|
1335
|
+
try:
|
|
1336
|
+
pixels = np.frombuffer(data, dtype=np.uint8)
|
|
1337
|
+
except (TypeError, ValueError):
|
|
1338
|
+
pixels = np.asarray(data, dtype=np.uint8)
|
|
1339
|
+
expected_pixels = width * height
|
|
1340
|
+
if pixels.size >= expected_pixels * 4:
|
|
1341
|
+
channels = 4
|
|
1342
|
+
pixel_format = "RGBA"
|
|
1343
|
+
elif pixels.size >= expected_pixels * 3:
|
|
1344
|
+
channels = 3
|
|
1345
|
+
pixel_format = "RGB"
|
|
1346
|
+
else:
|
|
1347
|
+
return None
|
|
1348
|
+
image = pixels[: expected_pixels * channels].reshape((height, width, channels)).tobytes()
|
|
1349
|
+
return _make_output_video_frame(image, (width, height), pixel_format)
|
|
1350
|
+
|
|
1351
|
+
|
|
1352
|
+
def _make_output_video_frame(
|
|
1353
|
+
image: bytes,
|
|
1354
|
+
size: tuple[int, int],
|
|
1355
|
+
pixel_format: str,
|
|
1356
|
+
) -> Frame:
|
|
1357
|
+
constructors = []
|
|
1358
|
+
if OutputVideoRawFrame is not None:
|
|
1359
|
+
constructors.append(OutputVideoRawFrame)
|
|
1360
|
+
if OutputImageRawFrame is not None:
|
|
1361
|
+
constructors.append(OutputImageRawFrame)
|
|
1362
|
+
constructors.append(ImageRawFrame)
|
|
1363
|
+
|
|
1364
|
+
for constructor in constructors:
|
|
1365
|
+
try:
|
|
1366
|
+
return constructor(image=image, size=size, format=pixel_format)
|
|
1367
|
+
except TypeError:
|
|
1368
|
+
with contextlib.suppress(TypeError):
|
|
1369
|
+
return constructor(image, size, pixel_format)
|
|
1370
|
+
raise FaceModeNotReadyError("Installed Pipecat version cannot construct a video output frame")
|
|
1371
|
+
|
|
1372
|
+
|
|
1373
|
+
async def _disconnect_room(room: Any) -> None:
|
|
1374
|
+
if room is None:
|
|
1375
|
+
return
|
|
1376
|
+
disconnect = getattr(room, "disconnect", None)
|
|
1377
|
+
if disconnect is None:
|
|
1378
|
+
return
|
|
1379
|
+
try:
|
|
1380
|
+
result = disconnect()
|
|
1381
|
+
except Exception:
|
|
1382
|
+
return
|
|
1383
|
+
if hasattr(result, "__await__"):
|
|
1384
|
+
with contextlib.suppress(Exception):
|
|
1385
|
+
await result
|
|
1386
|
+
|
|
1387
|
+
|
|
1388
|
+
async def _close_async_resource(resource: Any) -> None:
|
|
1389
|
+
if resource is None:
|
|
1390
|
+
return
|
|
1391
|
+
close = getattr(resource, "aclose", None)
|
|
1392
|
+
if close is None:
|
|
1393
|
+
close = getattr(resource, "close", None)
|
|
1394
|
+
if close is None:
|
|
1395
|
+
return
|
|
1396
|
+
try:
|
|
1397
|
+
result = close()
|
|
1398
|
+
except Exception:
|
|
1399
|
+
return
|
|
1400
|
+
if hasattr(result, "__await__"):
|
|
1401
|
+
with contextlib.suppress(Exception):
|
|
1402
|
+
await result
|
|
1403
|
+
|
|
1404
|
+
|
|
1405
|
+
def _frame_types(*candidates: Any) -> tuple[type, ...]:
|
|
1406
|
+
return tuple(candidate for candidate in candidates if isinstance(candidate, type))
|
|
1407
|
+
|
|
1408
|
+
|
|
1409
|
+
def _optional_int(value: Any) -> int | None:
|
|
1410
|
+
try:
|
|
1411
|
+
return int(value) if value is not None else None
|
|
1412
|
+
except (TypeError, ValueError):
|
|
1413
|
+
return None
|
|
1414
|
+
|
|
1415
|
+
|
|
1416
|
+
def _safe_text(value: Any, fallback: str) -> str:
|
|
1417
|
+
text = str(value) if value is not None else ""
|
|
1418
|
+
return text[:300] or fallback
|
|
1419
|
+
|
|
1420
|
+
|
|
1421
|
+
def _sanitize_session_marker(session_id: str) -> str:
|
|
1422
|
+
return "".join(
|
|
1423
|
+
char if char.isascii() and (char.isalnum() or char in "_-") else "_"
|
|
1424
|
+
for char in session_id
|
|
1425
|
+
)[:96]
|
|
1426
|
+
|
|
1427
|
+
|
|
1428
|
+
def _websocket_close_details(value: Any) -> str:
|
|
1429
|
+
received = getattr(value, "rcvd", None)
|
|
1430
|
+
code = getattr(value, "close_code", None) or getattr(value, "code", None)
|
|
1431
|
+
reason = getattr(value, "close_reason", None) or getattr(value, "reason", None)
|
|
1432
|
+
if received is not None:
|
|
1433
|
+
code = code or getattr(received, "code", None)
|
|
1434
|
+
reason = reason or getattr(received, "reason", None)
|
|
1435
|
+
reason_text = str(reason or "").strip()[:160]
|
|
1436
|
+
suffix = f", reason={reason_text}" if reason_text else ""
|
|
1437
|
+
return f" (code={code if code is not None else 'unknown'}{suffix})"
|
|
1438
|
+
|
|
1439
|
+
|
|
1440
|
+
def _safe_error(error: BaseException, *secrets: str | None) -> str:
|
|
1441
|
+
"""Return an exception string without common credential-shaped values."""
|
|
1442
|
+
text = str(error)
|
|
1443
|
+
for secret in secrets:
|
|
1444
|
+
if secret:
|
|
1445
|
+
text = text.replace(secret, "<redacted>")
|
|
1446
|
+
for marker in ("Bearer ", "aivatar.", "facemode."):
|
|
1447
|
+
cursor = 0
|
|
1448
|
+
while True:
|
|
1449
|
+
found = text.find(marker, cursor)
|
|
1450
|
+
if found < 0:
|
|
1451
|
+
break
|
|
1452
|
+
start = found + len(marker)
|
|
1453
|
+
end = text.find(" ", start)
|
|
1454
|
+
if end < 0:
|
|
1455
|
+
end = len(text)
|
|
1456
|
+
text = f"{text[:start]}<redacted>{text[end:]}"
|
|
1457
|
+
cursor = start + len("<redacted>")
|
|
1458
|
+
return text[:300] or error.__class__.__name__
|