diff --git a/.github/actions/ci-verify/action.yml b/.github/actions/ci-verify/action.yml index faa9e98..ff32e14 100644 --- a/.github/actions/ci-verify/action.yml +++ b/.github/actions/ci-verify/action.yml @@ -19,7 +19,7 @@ runs: shell: bash - run: uv run ruff check src tests shell: bash - - run: uv run pytest tests/stv # hermetic unit suite; skips live integration + - run: uv run pytest tests --ignore=tests/integration # hermetic unit suite shell: bash # Advisory only: src/ojin carries known pyright type debt (untyped params, missing # super().__init__ calls). Surfaced for cleanup but never blocks — composite steps diff --git a/CHANGELOG.md b/CHANGELOG.md index c117efc..ffbf300 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,20 @@ All notable changes to `ojin-client` are documented here. The format follows [Keep a Changelog](https://keepachangelog.com/), and the project adheres to [Semantic Versioning](https://semver.org/) (pre-1.0 — see CONTRIBUTING.md). +## 0.11.1 - 2026-09-28 + +### Added +- `STVConfig.server_feed_fixed_chunk_size` opts into exact initial and steady + audio packet sizes. Oversized TTS inputs split without padding; short tails + still flush after the idle timeout or at a turn boundary. Default batching + continues to send all available audio once its minimum threshold is reached. +- Server-feed traces distinguish queued audio from completed WebSocket writes, + including audio duration, queue wait, and socket write time. + +### Fixed +- Cancellation retires an in-flight audio payload even when the cancel finishes + during its pacing delay or socket write, preserving the next reply. + ## 0.11.0 - 2026-09-14 ### Added diff --git a/README.md b/README.md index b4a2725..360e2f2 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,20 @@ asyncio.run(main()) **Turns.** A turn is one spoken utterance. Open it with `start_turn()`, then push audio with `send_tts_audio(pcm, sample_rate, num_channels)` as many times as you like. The client buffers and plays the **original** audio you sent while a 16 kHz copy goes to the server for lip-sync — so the voice the user hears is always exactly yours. Because the original is what's played back, you can feed **higher-quality** TTS (e.g. 24 kHz) for better sound and lip-sync still works on the 16 kHz copy — just set your player to the `sample_rate` each `STVAudioFrame` reports. -**Input shaping.** Feed audio at whatever cadence your TTS produces — even tiny 40 ms fragments. The client takes care of the input shape to optimize latency and stability: it primes a ~1 s lead after each `start_turn()`, then combines your audio into **≥400 ms** chunks before forwarding it to the server, so the inference head never starves and lip-sync stays stable. It's automatic — tune it (or restore per-chunk sends) with the `server_feed_*` fields on [`STVConfig`](#configuration). +**Input shaping.** Feed audio at whatever cadence your TTS produces, including 40 ms fragments. By default, the client accumulates 1,000 ms after each `start_turn()` and uses a 400 ms minimum for subsequent batches. Once a threshold is met, it sends all available audio, subject to the transport's packet-size cap. A 1-second TTS burst stays together even at a 320 ms threshold. + +Use `server_feed_fixed_chunk_size=True` only when you want exact packet sizes. The SDK rounds sizes up to complete PCM16 samples, retains overflow, and flushes short tails without padding. + +For the Human Presence low-latency deployment, pass this configuration to `OjinSTVClient`: + +```python +config = STVConfig( + server_feed_initial_chunk_ms=320, + server_feed_min_chunk_ms=200, + server_feed_send_gap_ms=100, + server_feed_fixed_chunk_size=False, +) +``` **Audio is the clock.** The playback loop emits **exactly one audio frame every tick** (real audio or silence so the consumer never starves) plus a video frame whenever one is ready, at `STVConfig.fps` (default 25 → a 40 ms tick). Video falls back to repeating the last frame rather than stalling. @@ -382,6 +395,8 @@ avatar_token = ( | `server_feed_initial_chunk_ms` | `1000` | Initial lead accumulated after each `start_turn()` | | `server_feed_min_chunk_ms` | `400` | Steady-state minimum send size | | `server_feed_flush_idle_ms` | `200` | Quiet time before flushing a sub-threshold tail | +| `server_feed_fixed_chunk_size` | `False` | Emit exact sizes rounded up to complete PCM16 samples; otherwise send the whole batch | +| `server_feed_send_gap_ms` | `200` | Minimum wait after an audio write before the next write starts | Video frames are emitted at the server's native resolution — read `STVVideoFrame.width`/`height` per frame rather than configuring an output size. Set `OJIN_MODE=dev` in the environment to attach the dev-mode query flag when connecting with the default transport. diff --git a/pyproject.toml b/pyproject.toml index aa3b0fe..890548c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ojin-client" -version = "0.11.0" +version = "0.11.1" description = "Ojin platform services" readme = "README.md" requires-python = ">=3.10" diff --git a/src/ojin/ojin_client.py b/src/ojin/ojin_client.py index fbe4ad2..c1543f0 100644 --- a/src/ojin/ojin_client.py +++ b/src/ojin/ojin_client.py @@ -150,12 +150,9 @@ def __init__( # noqa: PLR0913 max_input_chunk_bytes: Cap on a single audio send; larger ``OjinAudioInputMessage`` payloads are split into this many bytes per WebSocket frame. - send_chunk_gap_s: Minimum gap between consecutive audio sends while a - backlog remains (split chunks of one message, or a queue of pending - messages). Keeps a buffered burst from flooding the server; steady - realtime (one message at a time, queue drains empty) is never - delayed. Defaults to 0 (no pacing); ``OjinSTVClient`` passes its - configured value. + send_chunk_gap_s: Minimum gap between consecutive audio sends, + including split payloads. Sends after a longer idle need no wait. + Defaults to 0 (no pacing); ``OjinSTVClient`` passes its value. """ super().__init__() @@ -181,11 +178,13 @@ def __init__( # noqa: PLR0913 self._ingress_bytes_total: int = 0 self._inference_server_ready: bool = False self._cancelled: bool = False + self._outbound_generation: int = 0 self._active_interaction_id: str | None = None self._process_messages_task: Optional[asyncio.Task] = None - self._pending_client_messages_queue: asyncio.Queue[OjinMessage] = ( - asyncio.Queue() - ) + self._pending_client_messages_queue: asyncio.Queue[ + tuple[OjinMessage, float] + ] = asyncio.Queue() + self._audio_sent_callback: Callable[[int, float, float], None] | None = None self._mode: str | None = mode self._pending_first_input: bool = False self._webrtc_status_callback: Optional[ @@ -197,6 +196,26 @@ def __init__( # noqa: PLR0913 # header. Carries a secret — never log it. self._webrtc_settings: Optional["WebRTCSettings"] = None + def set_audio_sent_callback( + self, callback: Callable[[int, float, float], None] + ) -> None: + """Observe completed audio writes with bytes, queue wait ms, and send ms. + + Called synchronously after each WebSocket write, including split + payloads. Queue wait includes pacing; send time covers the socket write. + Keep the observer nonblocking. This is not a server acknowledgement. + """ + self._audio_sent_callback = callback + + def _notify_audio_sent( + self, byte_count: int, queue_wait_ms: float, send_ms: float + ) -> None: + if self._audio_sent_callback is not None: + try: + self._audio_sent_callback(byte_count, queue_wait_ms, send_ms) + except Exception: + logger.exception("audio send observer failed") + def set_webrtc_connect_settings(self, settings: "WebRTCSettings") -> None: """Declare direct-WebRTC settings for the connection's upgrade request. @@ -520,11 +539,11 @@ async def send_message(self, message: BaseModel) -> None: raise ConnectionError("Inference Server is not ready to receive messages") if isinstance(message, OjinCancelInteractionMessage): + self._outbound_generation += 1 self._cancelled = True # Drop any audio still queued to be sent for the turn being cancelled: - # the server discards post-cancel input, so forwarding it would only - # desync the next turn. (The in-flight send loop also bails on - # ``_cancelled`` between chunks — see _process_client_messages.) + # the generation also retires the sender's current message when a + # cancel finishes before its pacing sleep or socket send returns. self._drain_client_messages() cancel_input = CancelInteractionMessage(payload=message.to_proxy_message()) @@ -544,7 +563,7 @@ async def send_message(self, message: BaseModel) -> None: message, (OjinAudioInputMessage, OjinTextInputMessage, OjinEndInteractionMessage), ): - await self._pending_client_messages_queue.put(message) + await self._pending_client_messages_queue.put((message, time.monotonic())) return logger.error("The message %s is Unknown", message) @@ -569,7 +588,8 @@ async def _process_client_messages(self) -> None: await asyncio.sleep(1.0) continue - message: OjinMessage = await self._pending_client_messages_queue.get() + message, queued_at = await self._pending_client_messages_queue.get() + generation = self._outbound_generation if isinstance(message, OjinAudioInputMessage): max_chunk_size = self._max_input_chunk_bytes audio_chunks = [ @@ -582,7 +602,7 @@ async def _process_client_messages(self) -> None: audio_chunks.append(bytes()) for chunk in audio_chunks: - if self._cancelled: + if self._cancelled or generation != self._outbound_generation: # A cancel landed mid-send: abandon the rest of this (now # cancelled) turn's audio instead of finishing the burst. break @@ -600,7 +620,7 @@ async def _process_client_messages(self) -> None: elapsed = time.monotonic() - self._last_audio_send_t if elapsed < self._send_chunk_gap_s: await asyncio.sleep(self._send_chunk_gap_s - elapsed) - if self._cancelled: + if self._cancelled or generation != self._outbound_generation: break # a cancel landed during the pacing sleep interaction_input = InteractionInput( payload_type="audio", @@ -610,8 +630,15 @@ async def _process_client_messages(self) -> None: ) proxy_message = InteractionInputMessage(payload=interaction_input) - await self._ws.send(proxy_message.to_bytes()) + wire_message = proxy_message.to_bytes() + send_started = time.monotonic() + await self._ws.send(wire_message) self._last_audio_send_t = time.monotonic() + self._notify_audio_sent( + len(chunk), + (send_started - queued_at) * 1000.0, + (self._last_audio_send_t - send_started) * 1000.0, + ) elif isinstance(message, OjinTextInputMessage): text_message = message.to_proxy_message() diff --git a/src/ojin/stv/_outbound_feed.py b/src/ojin/stv/_outbound_feed.py index 121eb88..059950f 100644 --- a/src/ojin/stv/_outbound_feed.py +++ b/src/ojin/stv/_outbound_feed.py @@ -17,6 +17,7 @@ import asyncio import contextlib import logging +import math from collections import deque from typing import Optional @@ -60,14 +61,20 @@ def _init_outbound_feed( # ms = bytes / _bytes_per_ms, for the batcher thresholds and the lead # clock. Derived from the feed rate so both clients share one formula. self._bytes_per_ms = feed_sample_rate * 2 / 1000.0 + initial_ms = self._config.server_feed_initial_chunk_ms + steady_ms = self._config.server_feed_min_chunk_ms + if self._config.server_feed_fixed_chunk_size: + # Round up to whole PCM16 samples so packets never split a sample. + initial_bytes = math.ceil(initial_ms * feed_sample_rate / 1000) * 2 + steady_bytes = math.ceil(steady_ms * feed_sample_rate / 1000) * 2 + else: + initial_bytes = int(initial_ms * self._bytes_per_ms) + steady_bytes = int(steady_ms * self._bytes_per_ms) self._batcher = SendBatcher( - initial_chunk_bytes=int( - self._config.server_feed_initial_chunk_ms * self._bytes_per_ms - ), - min_chunk_bytes=int( - self._config.server_feed_min_chunk_ms * self._bytes_per_ms - ), + initial_chunk_bytes=initial_bytes, + min_chunk_bytes=steady_bytes, flush_idle_s=self._config.server_feed_flush_idle_ms / 1000.0, + fixed_chunk_size=self._config.server_feed_fixed_chunk_size, ) self._batch_added = asyncio.Event() self._batch_flush_task: Optional[asyncio.Task] = None @@ -244,8 +251,9 @@ async def _feed_resampled_audio(self, resampled: bytes) -> None: if self._config.server_feed_batching_enabled: to_send = self._batcher.add(resampled) self._batch_added.set() # any arrival resets the idle-flush timer - if to_send is not None: + while to_send is not None: await self._send_audio_message(to_send) + to_send = self._batcher.pop_ready() else: await self._send_audio_message(resampled) @@ -289,10 +297,28 @@ async def _send_audio_message(self, pcm: bytes) -> None: ) async def _send_audio_now(self, pcm: bytes) -> None: - """Send one server-bound audio payload and record the to_server trace.""" + """Queue one server-bound audio payload and record its audio duration.""" await self._client.send_message(OjinAudioInputMessage(audio_int16_bytes=pcm)) self._server_fed_ms += len(pcm) / self._bytes_per_ms - self._tracer.instant("to_server", "audio_sent", args={"bytes": len(pcm)}) + self._tracer.instant( + "to_server", + "audio_queued", + args={"bytes": len(pcm), "duration_ms": len(pcm) / self._bytes_per_ms}, + ) + + def _record_audio_sent( + self, byte_count: int, queue_wait_ms: float, send_ms: float + ) -> None: + self._tracer.instant( + "to_server", + "audio_sent", + args={ + "bytes": byte_count, + "duration_ms": byte_count / self._bytes_per_ms, + "queue_wait_ms": round(queue_wait_ms, 3), + "send_ms": round(send_ms, 3), + }, + ) async def _server_feed_loop(self) -> None: """Release lead-gated payloads as playback advances (lead cap only). @@ -364,6 +390,9 @@ async def _batch_flush_loop(self) -> None: def _start_feed_tasks(self) -> None: """Start the batch-flush and lead-gate feeder tasks (idempotent).""" + register = getattr(self._client, "set_audio_sent_callback", None) + if callable(register): + register(self._record_audio_sent) if self._config.server_feed_batching_enabled and self._batch_flush_task is None: self._batch_flush_task = asyncio.create_task(self._batch_flush_loop()) if self._server_feed_max_lead_ms > 0 and self._feed_task is None: diff --git a/src/ojin/stv/config.py b/src/ojin/stv/config.py index 5259a97..330061a 100644 --- a/src/ojin/stv/config.py +++ b/src/ojin/stv/config.py @@ -164,13 +164,17 @@ class STVConfig: server_feed_initial_chunk_ms: int = 1000 server_feed_min_chunk_ms: int = 400 server_feed_flush_idle_ms: int = 200 + # Emit exact initial/steady sizes, retaining overflow for the next packet. + # Quiet tails still flush without padding; False keeps legacy whole batches. + server_feed_fixed_chunk_size: bool = False # Server-feed send pacing (enforced by the transport, OjinClient). A backlog can # build when input is buffered (e.g. TTS deferred during a barge-in, then # replayed) or a large payload lands at once. To avoid flooding the inference # server, OjinClient caps a single send at ``server_feed_max_chunk_bytes`` (larger # payloads are split) and spaces consecutive sends ``server_feed_send_gap_ms`` - # apart — but ONLY while a backlog remains, so steady-state realtime streaming is - # never delayed. Both are passed to OjinClient at construction. + # apart whenever sends would otherwise be closer together. Choose a gap no + # longer than a steady packet's duration to avoid falling behind realtime. + # Both are passed to OjinClient at construction. server_feed_max_chunk_bytes: int = 1024 * 200 server_feed_send_gap_ms: int = 200 # Server-feed lead cap: never ship audio more than this far ahead of local diff --git a/src/ojin/stv/send_batcher.py b/src/ojin/stv/send_batcher.py index 308cbe0..69cfd39 100644 --- a/src/ojin/stv/send_batcher.py +++ b/src/ojin/stv/send_batcher.py @@ -29,6 +29,7 @@ def __init__( min_chunk_bytes: int, flush_idle_s: float, clock: Callable[[], float] = time.monotonic, + fixed_chunk_size: bool = False, ) -> None: """Create an empty batcher armed for an initial-threshold emit. @@ -39,6 +40,8 @@ def __init__( flush_idle_s: quiet seconds after the last add before a tail is flush-due. clock: monotonic seconds source (injectable for deterministic tests). + fixed_chunk_size: emit exactly the active threshold, retaining any + overflow for subsequent :meth:`pop_ready` calls. """ super().__init__() @@ -46,6 +49,9 @@ def __init__( self._min_chunk_bytes = min_chunk_bytes self._flush_idle_s = flush_idle_s self._clock = clock + self._fixed_chunk_size = fixed_chunk_size + if fixed_chunk_size and min(initial_chunk_bytes, min_chunk_bytes) <= 0: + raise ValueError("Fixed audio chunk sizes must be positive") self._buf = bytearray() self._next_is_initial = True self._last_add_ts = clock() @@ -59,14 +65,21 @@ def add(self, pcm16k: bytes) -> Optional[bytes]: """Append bytes; return a batch to send when the size threshold is met. The threshold is ``initial_chunk_bytes`` until the first emit after each - (re)arm, then ``min_chunk_bytes``. On reaching it, drains and returns ALL - buffered bytes (the threshold is a minimum, not a quantum) and clears the - initial flag. Returns ``None`` below threshold. Empty input is a no-op. + (re)arm, then ``min_chunk_bytes``. By default it returns all buffered + bytes when the threshold is reached. In fixed-size mode it returns + exactly the threshold; call :meth:`pop_ready` until it returns ``None`` + to release any other complete packets. Empty input is a no-op. """ if not pcm16k: return None self._buf.extend(pcm16k) self._last_add_ts = self._clock() + return self.pop_ready() + + def pop_ready(self) -> Optional[bytes]: + """Return the next complete packet without resetting the idle timer.""" + if not self._buf: + return None threshold = ( self._initial_chunk_bytes if self._next_is_initial @@ -74,6 +87,10 @@ def add(self, pcm16k: bytes) -> Optional[bytes]: ) if len(self._buf) >= threshold: self._next_is_initial = False + if self._fixed_chunk_size: + out = bytes(self._buf[:threshold]) + del self._buf[:threshold] + return out return self._take() return None diff --git a/tests/stv/test_fixed_audio_feed.py b/tests/stv/test_fixed_audio_feed.py new file mode 100644 index 0000000..a08b42d --- /dev/null +++ b/tests/stv/test_fixed_audio_feed.py @@ -0,0 +1,295 @@ +"""Fixed audio packets preserve PCM across batching, pacing, and cancellation.""" + +import asyncio +from types import SimpleNamespace + +import pytest + +import ojin.ojin_client as transport_module +from ojin.entities.interaction_messages import InteractionInputMessage +from ojin.ojin_client import OjinClient +from ojin.ojin_client_messages import ( + FrameType, + OjinAudioInputMessage, + OjinSessionReadyMessage, +) +from ojin.stv import OjinSTVClient, STVConfig, WebRTCSettings +from ojin.stv.synchronizer import AudioBuffer +from tests.stv.fakes import FakeOjinClient, RecordingTracer +from tests.stv.test_webrtc_client import _frame +from tests.stv.test_webrtc_negotiation import READY_CONNECTED_PARAMETERS + + +def _config() -> STVConfig: + return STVConfig( + server_feed_initial_chunk_ms=500, + server_feed_min_chunk_ms=200, + server_feed_fixed_chunk_size=True, + server_feed_send_gap_ms=100, + server_feed_flush_idle_ms=10000, + server_feed_max_lead_ms=0, + ) + + +def _client(transport, tracer, direct: bool, rate: int): + return OjinSTVClient( + client=transport, + tracer=tracer, + config=_config(), + webrtc=( + WebRTCSettings( + room_url="https://ojin.daily.co/fixed-feed", + token="test-token", + audio_sample_rate=rate, + ) + if direct + else None + ), + ) + + +def _audio(transport: FakeOjinClient) -> list[bytes]: + return [ + message.audio_int16_bytes + for message in transport.sent + if isinstance(message, OjinAudioInputMessage) and any(message.audio_int16_bytes) + ] + + +async def _wait_for_writes(sent, count: int) -> None: + for _ in range(100): + if len(sent) == count: + return + await asyncio.sleep(0) + assert len(sent) == count + + +@pytest.mark.parametrize("direct", [False, True]) +async def test_presence_threshold_sends_whole_burst_then_rearms(direct: bool) -> None: + """A 320 ms startup threshold preserves larger TTS bursts across turns.""" + transport = FakeOjinClient() + config = _config() + config.server_feed_initial_chunk_ms = 320 + config.server_feed_fixed_chunk_size = False + client = OjinSTVClient( + client=transport, + config=config, + webrtc=( + WebRTCSettings( + room_url="https://ojin.daily.co/presence-feed", token="test-token" + ) + if direct + else None + ), + ) + engine = client._webrtc or client + pcm = b"\x01\x02" * 16000 + try: + await engine._handle_message( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + await client.start_turn() + await client.send_tts_audio(pcm[:3200], 16000, 1) + assert not _audio(transport) + await client.send_tts_audio(pcm[3200:], 16000, 1) + assert _audio(transport) == [pcm] + + await client.start_turn() + initial = pcm[: 320 * 32] + await client.send_tts_audio(initial[:-2], 16000, 1) + assert _audio(transport) == [pcm] + await client.send_tts_audio(initial[-2:], 16000, 1) + assert _audio(transport) == [pcm, initial] + finally: + await client.close() + + +@pytest.mark.parametrize("direct,rate", [(False, 16000), (True, 24000), (True, 44100)]) +async def test_oversized_input_preserves_exact_packets_tail_and_cancel_rearm( + direct: bool, rate: int +) -> None: + """TTS packet boundaries do not affect output bytes or the next turn's lead.""" + transport = FakeOjinClient() + client = _client(transport, RecordingTracer(), direct, rate) + engine = client._webrtc or client + ready = OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + pcm = b"\x01\x02" * (rate * 23 // 20) + initial_bytes, steady_bytes = rate, rate * 2 // 5 + try: + await engine._handle_message(ready) + await client.start_turn() + await client.send_tts_audio(pcm[: rate // 5], rate, 1) + assert not _audio(transport) + await client.send_tts_audio(pcm[rate // 5 :], rate, 1) + packets = _audio(transport) + assert [len(packet) for packet in packets] == [ + initial_bytes, + steady_bytes, + steady_bytes, + steady_bytes, + ] + assert b"".join(packets) == pcm[: rate * 22 // 10] + + await client.start_turn() + assert b"".join(_audio(transport)) == pcm + assert len(_audio(transport)[-1]) == rate // 10 + await client.send_tts_audio(b"\x03\x04" * (rate * 2 // 5), rate, 1) + assert len(_audio(transport)) == 5 + if not direct: + engine._synchronizer.current_buffer = AudioBuffer(sample_rate=rate) + engine._synchronizer.current_buffer.bytes_.extend(pcm) + assert await client.interrupt() + await client.start_turn() + fresh = b"\x05\x06" * (rate // 2) + await client.send_tts_audio(fresh, rate, 1) + assert len(_audio(transport)) == 5 + await engine._handle_message(_frame(FrameType.IDLE)) + assert _audio(transport)[-1] == fresh + assert len(_audio(transport)) == 6 + finally: + await client.close() + + +async def test_exact_packets_are_paced_on_wire_and_traced_after_write(monkeypatch): + """A 950 ms burst becomes 500/200/200 ms writes and a real 50 ms idle tail.""" + rate = 24000 + now = [100.0] + tracer = RecordingTracer() + transport = OjinClient( + ws_url="ws://test", api_key="test", config_id="test", send_chunk_gap_s=0.1 + ) + transport._running = True + transport._inference_server_ready = True + sent = [] + + class RecordingSocket: + async def send(self, data): + sent.append((now[0], data)) + now[0] += 0.002 + + async def close(self): + pass + + transport._ws = RecordingSocket() + client = _client(transport, tracer, True, rate) + engine = client._webrtc + await engine._handle_message( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + real_sleep = asyncio.sleep + + async def paced_sleep(delay): + now[0] += delay + await real_sleep(0) + + monkeypatch.setattr( + transport_module, + "asyncio", + SimpleNamespace(sleep=paced_sleep, CancelledError=asyncio.CancelledError), + ) + monkeypatch.setattr( + transport_module, "time", SimpleNamespace(monotonic=lambda: now[0]) + ) + pcm = b"\x01\x02" * (rate * 19 // 20) + try: + await client.start_turn() + await client.send_tts_audio(pcm, rate, 1) + assert sent == [] + queued = [args for _, name, args in tracer.instants if name == "audio_queued"] + assert [args["duration_ms"] for args in queued] == [500, 200, 200] + assert not any(name == "audio_sent" for _, name, _ in tracer.instants) + transport._process_messages_task = asyncio.create_task( + transport._process_client_messages() + ) + await _wait_for_writes(sent, 3) + assert [timestamp for timestamp, _ in sent] == pytest.approx( + [100.0, 100.102, 100.204] + ) + assert [ + len(InteractionInputMessage.from_bytes(data).payload.payload) + for _, data in sent + ] == [24000, 9600, 9600] + wire = [args for _, name, args in tracer.instants if name == "audio_sent"] + assert [args["duration_ms"] for args in wire] == [500, 200, 200] + assert [args["queue_wait_ms"] for args in wire] == [0, 102, 204] + assert [args["send_ms"] for args in wire] == [2, 2, 2] + + engine._batch_added.clear() + engine._batcher._clock = lambda: engine._batcher._last_add_ts + 11 + now[0] += 1 + await engine._batch_flush_tick(0.0001) + await _wait_for_writes(sent, 4) + audio = [ + InteractionInputMessage.from_bytes(data).payload.payload for _, data in sent + ] + assert len(audio) == 4 + assert len(audio[-1]) == 2400 + assert b"".join(audio) == pcm + await engine._batch_flush_tick(0.0001) + await real_sleep(0) + assert len(sent) == 4 + finally: + await client.close() + + +async def test_short_utterance_idle_flushes_without_padding() -> None: + """An utterance shorter than the startup lead still reaches the server.""" + transport = FakeOjinClient() + client = _client(transport, RecordingTracer(), True, 24000) + engine = client._webrtc + pcm = b"\x01\x02" * 3600 + try: + await engine._handle_message( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + await client.start_turn() + await client.send_tts_audio(pcm, 24000, 1) + assert not _audio(transport) + engine._batch_added.clear() + engine._batcher._clock = lambda: engine._batcher._last_add_ts + 11 + await engine._batch_flush_tick(0.0001) + assert _audio(transport) == [pcm] + await engine._batch_flush_tick(0.0001) + assert _audio(transport) == [pcm] + finally: + await client.close() + + +@pytest.mark.parametrize("fixed", [False, True]) +async def test_fractional_sample_thresholds_preserve_complete_pcm_samples( + fixed: bool, +) -> None: + """Fixed packets round up to whole samples; default mode keeps the burst.""" + rate = 44100 + transport = FakeOjinClient() + config = _config() + config.server_feed_initial_chunk_ms = 329 + config.server_feed_min_chunk_ms = 201 + config.server_feed_fixed_chunk_size = fixed + client = OjinSTVClient( + client=transport, + tracer=RecordingTracer(), + config=config, + webrtc=WebRTCSettings( + room_url="https://ojin.daily.co/fixed-feed", + token="test-token", + audio_sample_rate=rate, + ), + ) + engine = client._webrtc + pcm = b"\x01\x02" * rate + try: + await engine._handle_message( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + await client.start_turn() + await client.send_tts_audio(pcm, rate, 1) + assert [len(packet) for packet in _audio(transport)] == ( + [29018, 17730, 17730, 17730] if fixed else [len(pcm)] + ) + await client.start_turn() + packets = _audio(transport) + assert all(len(packet) % 2 == 0 for packet in packets) + assert b"".join(packets) == pcm + finally: + await client.close() diff --git a/tests/test_ojin_client.py b/tests/test_ojin_client.py index 8dc3a72..3be9ca3 100644 --- a/tests/test_ojin_client.py +++ b/tests/test_ojin_client.py @@ -6,7 +6,10 @@ import pytest -from ojin.entities.interaction_messages import ErrorResponseMessage +from ojin.entities.interaction_messages import ( + ErrorResponseMessage, + InteractionInputMessage, +) from ojin.entities.session_messages import SessionUpdateMessage, SessionUpdatePayload from ojin.ojin_client import OjinClient from ojin.ojin_client_messages import ( @@ -97,6 +100,118 @@ async def test_cancel_drops_pending_client_messages() -> None: assert len(client._ws.sent) == 1 # only the cancel frame reached the wire +@pytest.mark.parametrize("blocked_at", ["pacing", "send"]) +@pytest.mark.parametrize("cancel_count", [1, 2]) +async def test_cancel_retires_inflight_audio_and_preserves_fresh_reply( + monkeypatch, blocked_at: str, cancel_count: int +) -> None: + """Cancel split audio across an await while keeping the next reply intact.""" + blocked = asyncio.Event() + release = asyncio.Event() + fresh_sent = asyncio.Event() + real_sleep = asyncio.sleep + fresh_audio = b"\x03\x04" * 640 + + class PausedWS(_FakeWS): + async def send(self, data) -> None: + await super().send(data) + if isinstance(data, bytes): + audio = InteractionInputMessage.from_bytes(data).payload.payload + if audio == fresh_audio: + fresh_sent.set() + elif blocked_at == "send" and not blocked.is_set(): + blocked.set() + await release.wait() + + async def paced_sleep(delay): + if blocked_at == "pacing" and delay > 0 and not blocked.is_set(): + blocked.set() + await release.wait() + else: + await real_sleep(0) + + monkeypatch.setattr(asyncio, "sleep", paced_sleep) + client = OjinClient( + ws_url="ws://test/realtime", + api_key="k", + config_id="c", + max_input_chunk_bytes=204800, + send_chunk_gap_s=0.2, + ) + client._running = True + client._inference_server_ready = True + client._ws = PausedWS() # type: ignore[assignment] + await client.send_message(_audio_msg(b"\x01\x02" * 279014)) + await client.send_message(_audio_msg(b"\x05\x06" * 640)) + task = asyncio.create_task(client._process_client_messages()) + try: + await asyncio.wait_for(blocked.wait(), 1) + assert client._pending_client_messages_queue.qsize() == 1 + for _ in range(cancel_count): + await client.send_message(OjinCancelInteractionMessage()) + assert client._pending_client_messages_queue.empty() + await client.send_message(_audio_msg(fresh_audio)) + release.set() + await asyncio.wait_for(fresh_sent.wait(), 1) + finally: + client._running = False + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + sent = client._ws.sent + assert [ + len(InteractionInputMessage.from_bytes(message).payload.payload) + for message in sent + if isinstance(message, bytes) + ] == [204800, len(fresh_audio)] + assert len(sent) == cancel_count + 2 + assert all( + json.loads(message)["type"] == "cancelInteraction" for message in sent[1:-1] + ) + + +async def test_reply_after_cancel_survives_sender_waiting_on_empty_queue() -> None: + """A sender awaiting its next message must use that message's generation.""" + waiting = asyncio.Event() + sent = asyncio.Event() + + class WaitingQueue(asyncio.Queue): + async def get(self): + waiting.set() + return await super().get() + + class NotifyingWS(_FakeWS): + async def send(self, data) -> None: + await super().send(data) + if isinstance(data, bytes): + sent.set() + + client = _client() + client._running = True + client._inference_server_ready = True + client._ws = NotifyingWS() # type: ignore[assignment] + client._pending_client_messages_queue = WaitingQueue() + task = asyncio.create_task(client._process_client_messages()) + fresh_audio = b"\x03\x04" * 640 + try: + await asyncio.wait_for(waiting.wait(), 1) + await client.send_message(OjinCancelInteractionMessage()) + await client.send_message(_audio_msg(fresh_audio)) + await asyncio.wait_for(sent.wait(), 1) + finally: + client._running = False + task.cancel() + with contextlib.suppress(asyncio.CancelledError): + await task + + assert len(client._ws.sent) == 2 + assert ( + InteractionInputMessage.from_bytes(client._ws.sent[1]).payload.payload + == fresh_audio + ) + + async def test_large_audio_split_into_max_chunks_and_paced(monkeypatch) -> None: """A payload larger than the cap is split, and split chunks are gapped.""" real_sleep = asyncio.sleep @@ -116,8 +231,9 @@ async def fake_sleep(delay): send_chunk_gap_s=0.2, ) client._running = True + client._inference_server_ready = True client._ws = _FakeWS() # type: ignore[assignment] - await client._pending_client_messages_queue.put(_audio_msg(b"\x01\x02\x03\x04" * 3)) + await client.send_message(_audio_msg(b"\x01\x02\x03\x04" * 3)) await _drain_send_loop(client, expected_sends=3, real_sleep=real_sleep) @@ -143,8 +259,9 @@ async def fake_sleep(delay): ws_url="ws://t", api_key="k", config_id="c", send_chunk_gap_s=0.2 ) client._running = True + client._inference_server_ready = True client._ws = _FakeWS() # type: ignore[assignment] - await client._pending_client_messages_queue.put(_audio_msg(b"\x01\x02" * 10)) + await client.send_message(_audio_msg(b"\x01\x02" * 10)) await _drain_send_loop(client, expected_sends=1, real_sleep=real_sleep) @@ -167,9 +284,10 @@ async def fake_sleep(delay): ws_url="ws://t", api_key="k", config_id="c", send_chunk_gap_s=0.2 ) client._running = True + client._inference_server_ready = True client._ws = _FakeWS() # type: ignore[assignment] for _ in range(3): - await client._pending_client_messages_queue.put(_audio_msg(b"\x01\x02" * 10)) + await client.send_message(_audio_msg(b"\x01\x02" * 10)) await _drain_send_loop(client, expected_sends=3, real_sleep=real_sleep) @@ -202,14 +320,13 @@ async def fake_sleep(delay): ws_url="ws://t", api_key="k", config_id="c", send_chunk_gap_s=0.2 ) client._running = True + client._inference_server_ready = True client._ws = _FakeWS() # type: ignore[assignment] task = asyncio.create_task(client._process_client_messages()) try: for i in range(3): - await client._pending_client_messages_queue.put( - _audio_msg(b"\x01\x02" * 10) - ) + await client.send_message(_audio_msg(b"\x01\x02" * 10)) # Wait for THIS message to hit the wire before enqueueing the next — # the queue is empty at every gap decision, mimicking the replay race. for _ in range(200): diff --git a/uv.lock b/uv.lock index e625e6f..176bcd2 100644 --- a/uv.lock +++ b/uv.lock @@ -825,7 +825,7 @@ wheels = [ [[package]] name = "ojin-client" -version = "0.11.0" +version = "0.11.1" source = { editable = "." } dependencies = [ { name = "async-lru" },