"""Bridge Aiden's TTS into the local IMTalker avatar as a continuous real-time stream. IMTalker is a streaming model: it expects 24 kHz PCM in 80 ms frames *all the time*. Silence is a valid input and is what closes the mouth. So this sink runs a wall-clock feeder from process start: it sends queued reply audio when there is any, and zeros otherwise. Replies append to the queue; a barge-in drops the queue but keeps the stream alive, so the mouth closes on the next chunk instead of the session dying. Video comes back as AV01 packets (44-byte header: 'AV01', frame, chunk, gen_ms, sr, jpeg_len, pcm_len, text_len, chunks_done, reserved). Each packet is forwarded to the browser as b"ADAV" + uint32 epoch + AV01 so stale-epoch frames can be dropped. The returned PCM is the playback clock for the played-text ledger. """ from __future__ import annotations import asyncio import base64 import io import json import struct import wave import aiohttp HEADER = struct.Struct('<4s10I') RATE = 24000 FRAME = 3840 # 80 ms mono PCM16 FRAME_S = FRAME / (RATE * 2) FIFO_CAP = 20 * RATE * 2 # 20 s of queued speech max def wav_to_pcm(b64wav: str) -> bytes: with wave.open(io.BytesIO(base64.b64decode(b64wav))) as w: if w.getnchannels() != 1 or w.getsampwidth() != 2 or w.getframerate() != RATE: raise ValueError('TTS must be mono PCM16 at 24 kHz') return w.readframes(w.getnframes()) def parse_av(packet: bytes): if len(packet) < HEADER.size or packet[:4] != b'AV01': return None _, ver, frame, chunk, gen_ms, sr, jl, pl, tl, done, _ = HEADER.unpack(packet[:HEADER.size]) if ver != 1 or HEADER.size + jl + pl + tl > len(packet): return None return {'frame': frame, 'chunk': chunk, 'gen_ms': gen_ms, 'sr': sr, 'pcm': packet[HEADER.size + jl:HEADER.size + jl + pl], 'done': done} class AvatarSink: def __init__(self, origin, relay, played): self.origin = origin.rstrip('/') self.relay = relay # async (packet, epoch) -> None self.played = played # async (seq) -> None self.session = None self.conv = None self.video = None self.tasks = [] self.lock = asyncio.Lock() self.fifo = bytearray() self.epoch = 0 self.started = False self.sent = 0 # bytes written to the avatar (speech + silence) self.returned = 0 # bytes the avatar has emitted (playback clock) self.segments = [] # (end_position, seq) self.frames = 0 self.starved = 0 # ---------------- transport async def start(self): """Connect once and begin streaming; safe to call repeatedly.""" if self.started and self.conv is not None and not self.conv.closed: return async with self.lock: await self._close_sockets() self.session = aiohttp.ClientSession() self.conv = await self.session.ws_connect( self.origin + '/ws/conversation', max_msg_size=0, heartbeat=None) first = await asyncio.wait_for(self.conv.receive(), 30) sid = json.loads(first.data)['session_id'] self.video = await self.session.ws_connect( f'{self.origin}/ws/video?session_id={sid}', max_msg_size=0, heartbeat=None) await self.conv.send_json({'type': 'start', 'sample_rate': RATE}) self.started = True self.tasks = [asyncio.create_task(self._feed()), asyncio.create_task(self._read_conv()), asyncio.create_task(self._read_video())] async def _read_conv(self): try: async for msg in self.conv: if msg.type == aiohttp.WSMsgType.ERROR: break except Exception: pass finally: self.started = False async def _read_video(self): try: async for msg in self.video: if msg.type != aiohttp.WSMsgType.BINARY: if msg.type == aiohttp.WSMsgType.ERROR: break continue av = parse_av(msg.data) if av is None: continue self.returned += len(av['pcm']) self.frames += 1 while self.segments and self.returned >= self.segments[0][0]: _, seq = self.segments.pop(0) await self.played(seq) await self.relay(msg.data, self.epoch) except asyncio.CancelledError: raise except Exception: pass finally: self.started = False async def _feed(self): """Wall-clock 80 ms cadence: queue audio, else silence.""" loop = asyncio.get_running_loop() next_t = loop.time() while True: if self.conv is None or self.conv.closed: await asyncio.sleep(0.05) next_t = loop.time() continue now = loop.time() if next_t > now: await asyncio.sleep(next_t - now) if len(self.fifo) >= FRAME: frame = bytes(self.fifo[:FRAME]) del self.fifo[:FRAME] else: take = bytes(self.fifo) self.fifo.clear() frame = take + b'\x00' * (FRAME - len(take)) self.starved += 1 try: await self.conv.send_bytes(frame) except Exception: self.started = False await asyncio.sleep(0.05) next_t = loop.time() continue self.sent += FRAME next_t += FRAME_S if next_t < loop.time() - 0.5: next_t = loop.time() async def _close_sockets(self): for t in self.tasks: t.cancel() self.tasks = [] for ws in (self.video, self.conv): if ws is not None and not ws.closed: try: await ws.close() except Exception: pass if self.session is not None and not self.session.closed: await self.session.close() self.session = self.conv = self.video = None self.sent = self.returned = 0 self.segments.clear() self.fifo.clear() # ---------------- public API async def speak_wav(self, b64wav: str, epoch: int, seq: int): pcm = wav_to_pcm(b64wav) await self.start() self.epoch = epoch async with self.lock: if len(self.fifo) + len(pcm) > FIFO_CAP: # keep the stream live; drop the oldest queued speech drop = len(self.fifo) + len(pcm) - FIFO_CAP del self.fifo[:drop] self.segments = [(max(end - drop, self.sent), s) for end, s in self.segments] self.fifo.extend(pcm) self.segments.append((self.sent + len(self.fifo), seq)) async def end_reply(self): """No flush needed: the feeder emits silence as soon as the queue drains.""" return async def cancel(self): """Drop unplayed speech but keep the real-time stream running.""" async with self.lock: self.fifo.clear() self.segments.clear() self.frames = 0 # Let the browser render the closing mouth: frames after this epoch are # accepted even though the cancelled reply's frames are dropped. self.epoch += 1