|
| 1 | +import asyncio |
| 2 | +import websockets |
| 3 | +from typing import Optional, Tuple |
| 4 | +from .messages import ( |
| 5 | + LipsyncClientMessage, |
| 6 | + LipsyncServerMessage, |
| 7 | + LipsyncServerMessageAdapter, |
| 8 | + LipsyncConfigMessage, |
| 9 | + LipsyncConfigAckMessage, |
| 10 | + LipsyncAudioInputMessage, |
| 11 | + LipsyncVideoInputMessage, |
| 12 | + LipsyncInterruptAudioMessage, |
| 13 | + LipsyncSyncedOutputMessage, |
| 14 | + LipsyncErrorMessage, |
| 15 | +) |
| 16 | +import fractions |
| 17 | +import time |
| 18 | +import logging |
| 19 | +import cv2 |
| 20 | +import numpy as np |
| 21 | + |
| 22 | +logger = logging.getLogger(__name__) |
| 23 | + |
| 24 | + |
| 25 | +class RealtimeLipsyncClient: |
| 26 | + |
| 27 | + DECART_LIPSYNC_ENDPOINT = "/router/lipsync/ws" |
| 28 | + VIDEO_FPS = 25 |
| 29 | + |
| 30 | + def __init__( |
| 31 | + self, |
| 32 | + api_key: str, |
| 33 | + base_url: str = "https://api.decart.ai", |
| 34 | + audio_sample_rate: int = 16000, |
| 35 | + video_fps: int = VIDEO_FPS, |
| 36 | + sync_latency: float = 0.0, |
| 37 | + ): |
| 38 | + """ |
| 39 | + Args: |
| 40 | + api_key: The API key for the Decart Lipsync server |
| 41 | + url: The URL of the Decart Lipsync server |
| 42 | + audio_sample_rate: The sample rate of the audio |
| 43 | + video_fps: The FPS of the video |
| 44 | + sync_latency: Delay next frame up to this many seconds, to account for variable latency |
| 45 | + """ |
| 46 | + self._url = f"{base_url}{self.DECART_LIPSYNC_ENDPOINT}".replace( |
| 47 | + "https://", "wss://" |
| 48 | + ).replace("http://", "ws://") |
| 49 | + self._api_key = api_key |
| 50 | + self._audio_sample_rate = audio_sample_rate |
| 51 | + self._video_fps = video_fps |
| 52 | + self._sync_latency = sync_latency |
| 53 | + |
| 54 | + self._websocket: Optional[websockets.ClientConnection] = None |
| 55 | + self._out_queue = asyncio.Queue() |
| 56 | + self._response_handling_task: Optional[asyncio.Task] = None |
| 57 | + |
| 58 | + self._video_frame_interval = fractions.Fraction(1, video_fps) |
| 59 | + self._video_out_frame_index = 0 |
| 60 | + self._video_out_start_time = 0 |
| 61 | + |
| 62 | + async def _recv(self) -> LipsyncServerMessage: |
| 63 | + response = await self._websocket.recv() |
| 64 | + return LipsyncServerMessageAdapter.validate_json(response) |
| 65 | + |
| 66 | + async def _send(self, message: LipsyncClientMessage): |
| 67 | + msg = message.model_dump_json() |
| 68 | + await self._websocket.send(msg) |
| 69 | + |
| 70 | + async def _handle_server_responses(self): |
| 71 | + try: |
| 72 | + while self._websocket is not None: |
| 73 | + response = await self._recv() |
| 74 | + if isinstance(response, LipsyncSyncedOutputMessage): |
| 75 | + await self._out_queue.put(response) |
| 76 | + elif isinstance(response, LipsyncErrorMessage): |
| 77 | + logger.error(f"Lipsync server error: {response.message}") |
| 78 | + raise Exception(response.message) |
| 79 | + else: |
| 80 | + logger.error(f"Unknown response from lipsync server: {response}") |
| 81 | + except asyncio.CancelledError: |
| 82 | + pass |
| 83 | + except websockets.exceptions.ConnectionClosedOK: |
| 84 | + logger.debug("Connection closed by server") |
| 85 | + |
| 86 | + async def _decode_video_frame(self, video_frame: bytes) -> bytes: |
| 87 | + def _decode_video_frame_sync(video_frame: bytes) -> bytes: |
| 88 | + nparr = np.frombuffer(video_frame, np.uint8) |
| 89 | + video_frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR) |
| 90 | + return video_frame |
| 91 | + |
| 92 | + return await asyncio.to_thread(_decode_video_frame_sync, video_frame) |
| 93 | + |
| 94 | + async def _encode_video_frame(self, image: np.ndarray) -> bytes: |
| 95 | + def _encode_video_frame_sync(image: np.ndarray) -> bytes: |
| 96 | + success, encoded_image = cv2.imencode(".jpeg", image) |
| 97 | + if not success: |
| 98 | + raise Exception("Failed to encode video frame as JPEG") |
| 99 | + return encoded_image.tobytes() |
| 100 | + |
| 101 | + return await asyncio.to_thread(_encode_video_frame_sync, image) |
| 102 | + |
| 103 | + async def _decode_audio_frame(self, audio_frame: bytes) -> bytes: |
| 104 | + return audio_frame |
| 105 | + |
| 106 | + async def connect(self): |
| 107 | + logger.debug(f"Connecting to lipsync server at {self._url}") |
| 108 | + self._websocket = await websockets.connect(f"{self._url}?api_key={self._api_key}") |
| 109 | + logger.debug("WebSocket connected") |
| 110 | + # Initial handshake |
| 111 | + await self._send( |
| 112 | + LipsyncConfigMessage( |
| 113 | + video_fps=self._video_fps, |
| 114 | + audio_sample_rate=self._audio_sample_rate, |
| 115 | + ) |
| 116 | + ) |
| 117 | + logger.debug("Configuration sent") |
| 118 | + response = await self._recv() |
| 119 | + if not isinstance(response, LipsyncConfigAckMessage): |
| 120 | + raise Exception(f"Configuration not acknowledged by server: {response}") |
| 121 | + logger.debug("Configuration acknowledged") |
| 122 | + |
| 123 | + self._response_handling_task = asyncio.create_task(self._handle_server_responses()) |
| 124 | + |
| 125 | + logger.debug("Connected to lipsync server") |
| 126 | + |
| 127 | + async def disconnect(self): |
| 128 | + if self._websocket is not None: |
| 129 | + await self._websocket.close() |
| 130 | + self._websocket = None |
| 131 | + |
| 132 | + if self._response_handling_task is not None: |
| 133 | + self._response_handling_task.cancel() |
| 134 | + try: |
| 135 | + await self._response_handling_task |
| 136 | + except asyncio.CancelledError: |
| 137 | + pass |
| 138 | + self._response_handling_task = None |
| 139 | + |
| 140 | + async def send_audio(self, audio_data: bytes): |
| 141 | + await self._send(LipsyncAudioInputMessage(audio_data=audio_data)) |
| 142 | + |
| 143 | + async def send_video_frame_bytes(self, video_frame_bytes: bytes): |
| 144 | + await self._send(LipsyncVideoInputMessage(video_frame=video_frame_bytes)) |
| 145 | + |
| 146 | + async def send_video_frame(self, image: np.ndarray): |
| 147 | + encoded_image = await self._encode_video_frame(image) |
| 148 | + await self.send_video_frame_bytes(encoded_image) |
| 149 | + |
| 150 | + async def interrupt_audio(self): |
| 151 | + await self._send(LipsyncInterruptAudioMessage()) |
| 152 | + |
| 153 | + async def get_synced_output(self, timeout: Optional[float] = None) -> Tuple[bytes, bytes]: |
| 154 | + synced_output: LipsyncSyncedOutputMessage = await asyncio.wait_for( |
| 155 | + self._out_queue.get(), timeout=timeout |
| 156 | + ) |
| 157 | + |
| 158 | + video_frame = await self._decode_video_frame(synced_output.video_frame) |
| 159 | + audio_frame = await self._decode_audio_frame(synced_output.audio_frame) |
| 160 | + |
| 161 | + if self._video_out_frame_index == 0: |
| 162 | + self._video_out_start_time = time.time() + self._sync_latency |
| 163 | + |
| 164 | + time_til_frame = ( |
| 165 | + self._video_out_start_time |
| 166 | + + (self._video_out_frame_index * self._video_frame_interval) |
| 167 | + - time.time() |
| 168 | + ) |
| 169 | + if time_til_frame > 0: |
| 170 | + await asyncio.sleep(time_til_frame) |
| 171 | + |
| 172 | + return video_frame, audio_frame |
0 commit comments