File size: 7,668 Bytes
c74e524
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
"""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