From caa48ca60339ea5a47c0b9fd611a6e5aa04f97ce Mon Sep 17 00:00:00 2001 From: Faris Rahman Date: Mon, 21 Sep 2026 12:57:26 +0200 Subject: [PATCH 1/5] fix(client): stop sending cancelled audio chunks --- CHANGELOG.md | 8 +++ src/ojin/ojin_client.py | 12 ++-- tests/test_ojin_client.py | 117 +++++++++++++++++++++++++++++++++++++- 3 files changed, 131 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c117efc..f182bf1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,14 @@ 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). +## Unreleased + +### Fixed + +- Cancelling speech now discards the unsent remainder of a split audio message + even when cancellation finishes during a pacing delay or socket send. Fresh + replies continue normally after cancellation. + ## 0.11.0 - 2026-09-14 ### Added diff --git a/src/ojin/ojin_client.py b/src/ojin/ojin_client.py index fbe4ad2..aa86e0a 100644 --- a/src/ojin/ojin_client.py +++ b/src/ojin/ojin_client.py @@ -181,6 +181,7 @@ 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] = ( @@ -520,11 +521,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()) @@ -570,6 +571,7 @@ async def _process_client_messages(self) -> None: continue message: OjinMessage = 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 +584,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 +602,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", diff --git a/tests/test_ojin_client.py b/tests/test_ojin_client.py index 8dc3a72..fd4d2a4 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 From 83d499ff30a29862432886a1574aefdc0de5447a Mon Sep 17 00:00:00 2001 From: Faris Rahman Date: Mon, 21 Sep 2026 13:41:53 +0200 Subject: [PATCH 2/5] feat(stv): honor server audio lead hints and trace socket timing --- CHANGELOG.md | 18 +++ pyproject.toml | 2 +- src/ojin/ojin_client.py | 25 ++++- src/ojin/stv/_outbound_feed.py | 37 ++++++- src/ojin/stv/config.py | 4 +- src/ojin/stv/ojin_stv_client.py | 1 + src/ojin/stv/ojin_stv_webrtc_client.py | 4 +- src/ojin/stv/send_batcher.py | 4 + tests/stv/test_audio_send_timing.py | 113 +++++++++++++++++++ tests/stv/test_server_feed_hint.py | 148 +++++++++++++++++++++++++ tests/test_ojin_client.py | 25 +++++ uv.lock | 2 +- 12 files changed, 374 insertions(+), 9 deletions(-) create mode 100644 tests/stv/test_audio_send_timing.py create mode 100644 tests/stv/test_server_feed_hint.py diff --git a/CHANGELOG.md b/CHANGELOG.md index f182bf1..ded0eea 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,24 @@ All notable changes to `ojin-client` are documented here. The format follows ## Unreleased +## 0.12.0 - 2026-09-21 + +### Added + +- STV clients accept the server's recommended initial audio batch size before + replaying queued TTS. Human Portrait 2 servers can request 500 ms; servers + without a valid hint retain 1000 ms. Explicit `server_feed_initial_chunk_ms` + settings still take precedence; the default `None` selects automatic tuning. +- Audio traces record `audio_send_start` and `audio_send_complete` around each + WebSocket send. `OjinClient.set_audio_send_callback()` exposes the same events + with PCM byte counts; send completion does not acknowledge server receipt. + +### Changed + +- Renamed the STV trace marker `audio_sent` to `audio_enqueued` to describe its + actual timing. Direct WebRTC receive-latency metadata now identifies local + speech-metadata receipt, which precedes browser media playback. + ### Fixed - Cancelling speech now discards the unsent remainder of a split audio message diff --git a/pyproject.toml b/pyproject.toml index aa3b0fe..bda8a93 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ojin-client" -version = "0.11.0" +version = "0.12.0" 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 aa86e0a..3e46f88 100644 --- a/src/ojin/ojin_client.py +++ b/src/ojin/ojin_client.py @@ -182,6 +182,7 @@ def __init__( # noqa: PLR0913 self._inference_server_ready: bool = False self._cancelled: bool = False self._outbound_generation: int = 0 + self._audio_send_callback: Callable[[str, int], None] | None = None self._active_interaction_id: str | None = None self._process_messages_task: Optional[asyncio.Task] = None self._pending_client_messages_queue: asyncio.Queue[OjinMessage] = ( @@ -198,6 +199,25 @@ def __init__( # noqa: PLR0913 # header. Carries a secret — never log it. self._webrtc_settings: Optional["WebRTCSettings"] = None + def set_audio_send_callback( + self, callback: Callable[[str, int], None] | None + ) -> None: + """Observe audio socket-call start/completion with PCM byte counts. + + The synchronous callback runs after pacing, immediately before + ``ws.send`` and after it returns. Completion includes socket flow-control + waits; neither event acknowledges server receipt. Exceptions are logged + without interrupting audio delivery. Pass ``None`` to remove the observer. + """ + self._audio_send_callback = callback + + def _record_audio_send(self, event: str, byte_count: int) -> None: + if self._audio_send_callback is not None: + try: + self._audio_send_callback(event, byte_count) + 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. @@ -612,7 +632,10 @@ async def _process_client_messages(self) -> None: ) proxy_message = InteractionInputMessage(payload=interaction_input) - await self._ws.send(proxy_message.to_bytes()) + payload = proxy_message.to_bytes() + self._record_audio_send("audio_send_start", len(chunk)) + await self._ws.send(payload) + self._record_audio_send("audio_send_complete", len(chunk)) self._last_audio_send_t = time.monotonic() elif isinstance(message, OjinTextInputMessage): diff --git a/src/ojin/stv/_outbound_feed.py b/src/ojin/stv/_outbound_feed.py index 121eb88..30ca853 100644 --- a/src/ojin/stv/_outbound_feed.py +++ b/src/ojin/stv/_outbound_feed.py @@ -33,6 +33,8 @@ # conversion is an instance value (`_bytes_per_ms`) derived from the feed rate; # 16 kHz stays the default so the legacy client is byte-identical. FEED_SAMPLE_RATE = 16_000 +_DEFAULT_INITIAL_CHUNK_MS = 1000 +_MAX_SERVER_INITIAL_CHUNK_MS = 8000 class OutboundFeedMixin: @@ -60,10 +62,14 @@ 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 + observe_send = getattr(self._client, "set_audio_send_callback", None) + if callable(observe_send): + observe_send(self._trace_audio_send) + initial_ms = self._config.server_feed_initial_chunk_ms + if initial_ms is None: + initial_ms = _DEFAULT_INITIAL_CHUNK_MS self._batcher = SendBatcher( - initial_chunk_bytes=int( - self._config.server_feed_initial_chunk_ms * self._bytes_per_ms - ), + initial_chunk_bytes=int(initial_ms * self._bytes_per_ms), min_chunk_bytes=int( self._config.server_feed_min_chunk_ms * self._bytes_per_ms ), @@ -108,6 +114,26 @@ def _init_outbound_feed( self._interrupt_deferred: list[tuple] = [] self._deferring_input = False + def _configure_server_feed(self, parameters: dict | None) -> None: + initial_ms = self._config.server_feed_initial_chunk_ms + source = "explicit" + if initial_ms is None: + hint = (parameters or {}).get("server_feed_initial_chunk_ms") + if ( + isinstance(hint, int) + and not isinstance(hint, bool) + and 0 < hint <= _MAX_SERVER_INITIAL_CHUNK_MS + ): + initial_ms, source = hint, "server" + else: + initial_ms, source = _DEFAULT_INITIAL_CHUNK_MS, "fallback" + self._batcher.set_initial_chunk_bytes(int(initial_ms * self._bytes_per_ms)) + self._tracer.instant( + "to_server", + "server_feed_config", + args={"initial_chunk_ms": initial_ms, "source": source}, + ) + # ------------------------------------------------------------------ # Host seams # ------------------------------------------------------------------ @@ -288,11 +314,14 @@ async def _send_audio_message(self, pcm: bytes) -> None: args={"bytes": len(pcm), "lead_ms": round(self._server_lead_ms())}, ) + def _trace_audio_send(self, event: str, byte_count: int) -> None: + self._tracer.instant("to_server", event, args={"bytes": byte_count}) + async def _send_audio_now(self, pcm: bytes) -> None: """Send one server-bound audio payload and record the to_server trace.""" 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_enqueued", args={"bytes": len(pcm)}) async def _server_feed_loop(self) -> None: """Release lead-gated payloads as playback advances (lead cap only). diff --git a/src/ojin/stv/config.py b/src/ojin/stv/config.py index 5259a97..3e0853e 100644 --- a/src/ojin/stv/config.py +++ b/src/ojin/stv/config.py @@ -161,7 +161,9 @@ class STVConfig: # chunk per turn, then a steady-state minimum. Disable to restore per-chunk # sends. (Playback of the original audio is unaffected.) server_feed_batching_enabled: bool = True - server_feed_initial_chunk_ms: int = 1000 + # None accepts the server's startup recommendation, or 1000 ms without one. + # An explicit value preserves application tuning across server upgrades. + server_feed_initial_chunk_ms: int | None = None server_feed_min_chunk_ms: int = 400 server_feed_flush_idle_ms: int = 200 # Server-feed send pacing (enforced by the transport, OjinClient). A backlog can diff --git a/src/ojin/stv/ojin_stv_client.py b/src/ojin/stv/ojin_stv_client.py index ac06c24..33cdcf1 100644 --- a/src/ojin/stv/ojin_stv_client.py +++ b/src/ojin/stv/ojin_stv_client.py @@ -536,6 +536,7 @@ async def _handle_message(self, message: BaseModel) -> None: if isinstance(message, OjinSessionReadyMessage): if message.parameters is not None: self._session_data = message.parameters + self._configure_server_feed(message.parameters) self._initialized = True self._tracer.span("lifecycle", "connect", self._tr_connect_start) if self._playback_task is None: diff --git a/src/ojin/stv/ojin_stv_webrtc_client.py b/src/ojin/stv/ojin_stv_webrtc_client.py index 36dbb38..3b58fce 100644 --- a/src/ojin/stv/ojin_stv_webrtc_client.py +++ b/src/ojin/stv/ojin_stv_webrtc_client.py @@ -202,7 +202,8 @@ def __init__( # noqa: PLR0913 — injectable deps + flat field init self._set_trace_other("producer", "ojin_stv_webrtc_client") self._set_trace_other( "recv_latency_semantics", - "recv marks server publish time of the metadata frame, not media arrival", + "recv marks local receipt of speech metadata over WebSocket, " + "not server publication or browser media playback", ) register = getattr(self._client, "set_webrtc_status_callback", None) if callable(register): @@ -511,6 +512,7 @@ async def _on_session_ready(self, message: OjinSessionReadyMessage) -> None: self._cancel_join_timer() if message.parameters is not None: self._session_data = message.parameters + self._configure_server_feed(message.parameters) self._initialized = True self._tracer.span("lifecycle", "connect", self._tr_connect_start) await self._events.emit(STVEvent.SESSION_READY, session_data=self._session_data) diff --git a/src/ojin/stv/send_batcher.py b/src/ojin/stv/send_batcher.py index 308cbe0..b91793f 100644 --- a/src/ojin/stv/send_batcher.py +++ b/src/ojin/stv/send_batcher.py @@ -98,6 +98,10 @@ def rearm_initial(self) -> None: """Make the next emit use the initial (lead) threshold again.""" self._next_is_initial = True + def set_initial_chunk_bytes(self, byte_count: int) -> None: + """Change the initial threshold without losing pending audio or rearming.""" + self._initial_chunk_bytes = byte_count + def reset(self) -> None: """Discard buffered bytes and re-arm the initial threshold (barge-in).""" self._buf.clear() diff --git a/tests/stv/test_audio_send_timing.py b/tests/stv/test_audio_send_timing.py new file mode 100644 index 0000000..379927a --- /dev/null +++ b/tests/stv/test_audio_send_timing.py @@ -0,0 +1,113 @@ +"""Separate queued audio, socket submission, and received speech timestamps.""" + +import asyncio +import contextlib + +import pytest + +from ojin.ojin_client import OjinClient +from ojin.ojin_client_messages import ( + FrameType, + OjinInteractionResponseMessage, + OjinSessionReadyMessage, +) +from ojin.stv import OjinSessionTrace, OjinSTVClient, STVConfig, WebRTCSettings +from tests.stv.test_webrtc_negotiation import READY_CONNECTED_PARAMETERS + + +@pytest.mark.parametrize("direct_webrtc", [False, True]) +async def test_audio_trace_distinguishes_queue_socket_and_receipt(direct_webrtc): + """A blocked socket must not look sent when the SDK merely queues audio.""" + now = [0.0] + trace = OjinSessionTrace(clock=lambda: now[0]) + submitted, release, completed = asyncio.Event(), asyncio.Event(), asyncio.Event() + + class PausedSocket: + async def send(self, _data): + submitted.set() + await release.wait() + completed.set() + + transport = OjinClient("ws://localhost:8000/realtime", "timing-test", "portrait") + transport._running = True + transport._inference_server_ready = True + transport._ws = PausedSocket() + client = OjinSTVClient( + client=transport, + tracer=trace, + config=STVConfig( + server_feed_batching_enabled=False, + server_feed_max_lead_ms=0, + loop_stall_watchdog_ms=0, + stall_probe_ms=0, + ), + webrtc=( + WebRTCSettings( + room_url="https://ojin.daily.co/timing-test", token="timing-test" + ) + if direct_webrtc + else None + ), + ) + engine = client._webrtc or client + if direct_webrtc: + await engine._handle_message( + OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) + ) + else: + engine._initialized = True + now[0] = 1.0 + await client.start_turn() + await client.send_tts_audio(b"\x01\x02" * 3200, 16000, 1) + before_send = trace.build()["traceEvents"] + assert [ + event["name"] for event in before_send if event["name"].startswith("audio_") + ] == ["audio_enqueued"] + + now[0] = 2.0 + sender = asyncio.create_task(transport._process_client_messages()) + try: + await asyncio.wait_for(submitted.wait(), 1) + assert not any( + event["name"] == "audio_send_complete" + for event in trace.build()["traceEvents"] + ) + now[0] = 2.1 + release.set() + await asyncio.wait_for(completed.wait(), 1) + now[0] = 3.0 + await engine._handle_message( + OjinInteractionResponseMessage( + interaction_id="timing-test", + video_frame_bytes=b"", + audio_frame_bytes=b"", + is_final_response=False, + index=5, + frame_type=FrameType.SPEECH, + ) + ) + finally: + transport._running = False + sender.cancel() + with contextlib.suppress(asyncio.CancelledError): + await sender + + result = trace.build() + audio_events = [ + event for event in result["traceEvents"] if event["name"].startswith("audio_") + ] + assert [event["name"] for event in audio_events] == [ + "audio_enqueued", + "audio_send_start", + "audio_send_complete", + ] + assert [event["ts"] for event in audio_events] == pytest.approx( + [1_000_000, 2_000_000, 2_100_000] + ) + assert [event["args"] for event in audio_events] == [{"bytes": 6400}] * 3 + assert result["otherData"]["response_latency_ms"]["recv"]["last_ms"] == 2000.0 + if direct_webrtc: + assert result["otherData"]["recv_latency_semantics"] == ( + "recv marks local receipt of speech metadata over WebSocket, " + "not server publication or browser media playback" + ) diff --git a/tests/stv/test_server_feed_hint.py b/tests/stv/test_server_feed_hint.py new file mode 100644 index 0000000..b117751 --- /dev/null +++ b/tests/stv/test_server_feed_hint.py @@ -0,0 +1,148 @@ +"""Server feed hints apply before audio replay without changing explicit settings.""" + +import pytest + +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 _client(direct: bool, initial: int | None = None, rate: int = 16000): + transport = FakeOjinClient() + trace = RecordingTracer() + config = STVConfig( + server_feed_flush_idle_ms=10000, + server_feed_max_lead_ms=0, + ) + if initial is not None: + config.server_feed_initial_chunk_ms = initial + client = OjinSTVClient( + client=transport, + tracer=trace, + config=config, + webrtc=( + WebRTCSettings( + room_url="https://ojin.daily.co/feed-hint", + token="feed-hint-test", + audio_sample_rate=rate, + ) + if direct + else None + ), + ) + return client, client._webrtc or client, transport, trace + + +def _ready(hint: object = None) -> OjinSessionReadyMessage: + parameters = dict(READY_CONNECTED_PARAMETERS) + if hint is not None: + parameters["server_feed_initial_chunk_ms"] = hint + return OjinSessionReadyMessage(parameters=parameters) + + +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) + ] + + +@pytest.mark.parametrize("direct,rate", [(False, 16000), (True, 16000), (True, 44100)]) +async def test_hint_releases_preinit_audio_and_rearms_after_cancel( + direct: bool, rate: int +) -> None: + """A 500 ms first batch reaches the server both before and after barge-in.""" + client, engine, transport, trace = _client(direct, rate=rate) + pcm = b"\x01\x02" * (rate // 2) + try: + await client.start_turn() + await client.send_tts_audio(pcm, rate, 1) + assert not _audio(transport) + await engine._handle_message(_ready(500)) + assert _audio(transport) == [pcm] + assert ( + "to_server", + "server_feed_config", + {"initial_chunk_ms": 500, "source": "server"}, + ) in trace.instants + + 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() + split_at = rate * 2 * 400 // 1000 + await client.send_tts_audio(pcm[:split_at], rate, 1) + await engine._handle_message(_frame(FrameType.IDLE)) + assert len(_audio(transport)) == 1 + await client.send_tts_audio(pcm[split_at:], rate, 1) + assert _audio(transport) == [pcm, pcm] + finally: + await client.close() + + +@pytest.mark.parametrize("direct", [False, True]) +@pytest.mark.parametrize("hint", [None, False, True, 0, -1, 500.0, "500", 8001, {}, []]) +async def test_missing_or_invalid_hint_keeps_legacy_threshold( + direct: bool, hint: object +) -> None: + """Untrusted hint shapes cannot silently change the legacy initial batch.""" + client, engine, transport, _trace = _client(direct) + pcm = b"\x01\x02" * 8000 + try: + await engine._handle_message(_ready(hint)) + await client.start_turn() + await client.send_tts_audio(pcm, 16000, 1) + assert not _audio(transport) + await client.send_tts_audio(pcm, 16000, 1) + assert _audio(transport) == [pcm * 2] + finally: + await client.close() + + +@pytest.mark.parametrize("direct", [False, True]) +async def test_explicit_threshold_overrides_server_hint(direct: bool) -> None: + """A caller's configured startup lead wins over the server recommendation.""" + client, engine, transport, _trace = _client(direct, initial=1200) + try: + await engine._handle_message(_ready(500)) + await client.start_turn() + await client.send_tts_audio(b"\x01\x02" * 16000, 16000, 1) + assert not _audio(transport) + await client.send_tts_audio(b"\x01\x02" * 3200, 16000, 1) + assert _audio(transport) == [b"\x01\x02" * 19200] + finally: + await client.close() + + +@pytest.mark.parametrize("direct", [False, True]) +async def test_later_handshake_restores_fallback_without_losing_pending( + direct: bool, +) -> None: + """Another ready event updates the lead while retaining unsent PCM.""" + client, engine, transport, _trace = _client(direct) + pcm = b"\x01\x02" * 6400 + try: + await engine._handle_message(_ready(500)) + await client.start_turn() + await client.send_tts_audio(pcm, 16000, 1) + assert not _audio(transport) + await engine._handle_message(_ready()) + await client.send_tts_audio(pcm, 16000, 1) + assert not _audio(transport) + await client.send_tts_audio(pcm[:6400], 16000, 1) + assert _audio(transport) == [pcm * 2 + pcm[:6400]] + await client.send_tts_audio(pcm[:6400], 16000, 1) + await engine._handle_message(_ready(500)) + await client.send_tts_audio(pcm[:6400], 16000, 1) + assert _audio(transport)[1] == pcm + finally: + await client.close() diff --git a/tests/test_ojin_client.py b/tests/test_ojin_client.py index fd4d2a4..985cb19 100644 --- a/tests/test_ojin_client.py +++ b/tests/test_ojin_client.py @@ -141,6 +141,10 @@ async def paced_sleep(delay): client._running = True client._inference_server_ready = True client._ws = PausedWS() # type: ignore[assignment] + send_events = [] + client.set_audio_send_callback( + lambda event, size: send_events.append((event, size)) + ) 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()) @@ -169,6 +173,27 @@ async def paced_sleep(delay): assert all( json.loads(message)["type"] == "cancelInteraction" for message in sent[1:-1] ) + assert send_events == [ + ("audio_send_start", 204800), + ("audio_send_complete", 204800), + ("audio_send_start", len(fresh_audio)), + ("audio_send_complete", len(fresh_audio)), + ] + + +async def test_audio_send_callback_failure_does_not_stop_sending(): + """Trace observers cannot interrupt audio delivery or its sender task.""" + client = _client() + client._running = True + client._ws = _FakeWS() + + def fail_observer(_event, _size): + raise RuntimeError("trace collector unavailable") + + client.set_audio_send_callback(fail_observer) + await client._pending_client_messages_queue.put(_audio_msg(b"\x01\x02" * 3200)) + await _drain_send_loop(client, expected_sends=1, real_sleep=asyncio.sleep) + assert len(client._ws.sent) == 1 async def test_reply_after_cancel_survives_sender_waiting_on_empty_queue() -> None: diff --git a/uv.lock b/uv.lock index e625e6f..f4ce1bc 100644 --- a/uv.lock +++ b/uv.lock @@ -825,7 +825,7 @@ wheels = [ [[package]] name = "ojin-client" -version = "0.11.0" +version = "0.12.0" source = { editable = "." } dependencies = [ { name = "async-lru" }, From cf2a484a88d1276be2e2ad4eecf95f78f0951837 Mon Sep 17 00:00:00 2001 From: Faris Rahman Date: Mon, 21 Sep 2026 13:49:37 +0200 Subject: [PATCH 3/5] chore(stv): keep response improvements without analytics changes --- CHANGELOG.md | 9 -- src/ojin/ojin_client.py | 25 +----- src/ojin/stv/_outbound_feed.py | 18 +--- src/ojin/stv/ojin_stv_webrtc_client.py | 3 +- tests/stv/test_audio_send_timing.py | 113 ------------------------- tests/stv/test_server_feed_hint.py | 8 +- tests/test_ojin_client.py | 25 ------ 7 files changed, 6 insertions(+), 195 deletions(-) delete mode 100644 tests/stv/test_audio_send_timing.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ded0eea..fbbf23a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,15 +14,6 @@ All notable changes to `ojin-client` are documented here. The format follows replaying queued TTS. Human Portrait 2 servers can request 500 ms; servers without a valid hint retain 1000 ms. Explicit `server_feed_initial_chunk_ms` settings still take precedence; the default `None` selects automatic tuning. -- Audio traces record `audio_send_start` and `audio_send_complete` around each - WebSocket send. `OjinClient.set_audio_send_callback()` exposes the same events - with PCM byte counts; send completion does not acknowledge server receipt. - -### Changed - -- Renamed the STV trace marker `audio_sent` to `audio_enqueued` to describe its - actual timing. Direct WebRTC receive-latency metadata now identifies local - speech-metadata receipt, which precedes browser media playback. ### Fixed diff --git a/src/ojin/ojin_client.py b/src/ojin/ojin_client.py index 3e46f88..aa86e0a 100644 --- a/src/ojin/ojin_client.py +++ b/src/ojin/ojin_client.py @@ -182,7 +182,6 @@ def __init__( # noqa: PLR0913 self._inference_server_ready: bool = False self._cancelled: bool = False self._outbound_generation: int = 0 - self._audio_send_callback: Callable[[str, int], None] | None = None self._active_interaction_id: str | None = None self._process_messages_task: Optional[asyncio.Task] = None self._pending_client_messages_queue: asyncio.Queue[OjinMessage] = ( @@ -199,25 +198,6 @@ def __init__( # noqa: PLR0913 # header. Carries a secret — never log it. self._webrtc_settings: Optional["WebRTCSettings"] = None - def set_audio_send_callback( - self, callback: Callable[[str, int], None] | None - ) -> None: - """Observe audio socket-call start/completion with PCM byte counts. - - The synchronous callback runs after pacing, immediately before - ``ws.send`` and after it returns. Completion includes socket flow-control - waits; neither event acknowledges server receipt. Exceptions are logged - without interrupting audio delivery. Pass ``None`` to remove the observer. - """ - self._audio_send_callback = callback - - def _record_audio_send(self, event: str, byte_count: int) -> None: - if self._audio_send_callback is not None: - try: - self._audio_send_callback(event, byte_count) - 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. @@ -632,10 +612,7 @@ async def _process_client_messages(self) -> None: ) proxy_message = InteractionInputMessage(payload=interaction_input) - payload = proxy_message.to_bytes() - self._record_audio_send("audio_send_start", len(chunk)) - await self._ws.send(payload) - self._record_audio_send("audio_send_complete", len(chunk)) + await self._ws.send(proxy_message.to_bytes()) self._last_audio_send_t = time.monotonic() elif isinstance(message, OjinTextInputMessage): diff --git a/src/ojin/stv/_outbound_feed.py b/src/ojin/stv/_outbound_feed.py index 30ca853..e4f503f 100644 --- a/src/ojin/stv/_outbound_feed.py +++ b/src/ojin/stv/_outbound_feed.py @@ -62,9 +62,6 @@ 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 - observe_send = getattr(self._client, "set_audio_send_callback", None) - if callable(observe_send): - observe_send(self._trace_audio_send) initial_ms = self._config.server_feed_initial_chunk_ms if initial_ms is None: initial_ms = _DEFAULT_INITIAL_CHUNK_MS @@ -116,7 +113,6 @@ def _init_outbound_feed( def _configure_server_feed(self, parameters: dict | None) -> None: initial_ms = self._config.server_feed_initial_chunk_ms - source = "explicit" if initial_ms is None: hint = (parameters or {}).get("server_feed_initial_chunk_ms") if ( @@ -124,15 +120,10 @@ def _configure_server_feed(self, parameters: dict | None) -> None: and not isinstance(hint, bool) and 0 < hint <= _MAX_SERVER_INITIAL_CHUNK_MS ): - initial_ms, source = hint, "server" + initial_ms = hint else: - initial_ms, source = _DEFAULT_INITIAL_CHUNK_MS, "fallback" + initial_ms = _DEFAULT_INITIAL_CHUNK_MS self._batcher.set_initial_chunk_bytes(int(initial_ms * self._bytes_per_ms)) - self._tracer.instant( - "to_server", - "server_feed_config", - args={"initial_chunk_ms": initial_ms, "source": source}, - ) # ------------------------------------------------------------------ # Host seams @@ -314,14 +305,11 @@ async def _send_audio_message(self, pcm: bytes) -> None: args={"bytes": len(pcm), "lead_ms": round(self._server_lead_ms())}, ) - def _trace_audio_send(self, event: str, byte_count: int) -> None: - self._tracer.instant("to_server", event, args={"bytes": byte_count}) - async def _send_audio_now(self, pcm: bytes) -> None: """Send one server-bound audio payload and record the to_server trace.""" 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_enqueued", args={"bytes": len(pcm)}) + self._tracer.instant("to_server", "audio_sent", args={"bytes": len(pcm)}) async def _server_feed_loop(self) -> None: """Release lead-gated payloads as playback advances (lead cap only). diff --git a/src/ojin/stv/ojin_stv_webrtc_client.py b/src/ojin/stv/ojin_stv_webrtc_client.py index 3b58fce..2fb41f0 100644 --- a/src/ojin/stv/ojin_stv_webrtc_client.py +++ b/src/ojin/stv/ojin_stv_webrtc_client.py @@ -202,8 +202,7 @@ def __init__( # noqa: PLR0913 — injectable deps + flat field init self._set_trace_other("producer", "ojin_stv_webrtc_client") self._set_trace_other( "recv_latency_semantics", - "recv marks local receipt of speech metadata over WebSocket, " - "not server publication or browser media playback", + "recv marks server publish time of the metadata frame, not media arrival", ) register = getattr(self._client, "set_webrtc_status_callback", None) if callable(register): diff --git a/tests/stv/test_audio_send_timing.py b/tests/stv/test_audio_send_timing.py deleted file mode 100644 index 379927a..0000000 --- a/tests/stv/test_audio_send_timing.py +++ /dev/null @@ -1,113 +0,0 @@ -"""Separate queued audio, socket submission, and received speech timestamps.""" - -import asyncio -import contextlib - -import pytest - -from ojin.ojin_client import OjinClient -from ojin.ojin_client_messages import ( - FrameType, - OjinInteractionResponseMessage, - OjinSessionReadyMessage, -) -from ojin.stv import OjinSessionTrace, OjinSTVClient, STVConfig, WebRTCSettings -from tests.stv.test_webrtc_negotiation import READY_CONNECTED_PARAMETERS - - -@pytest.mark.parametrize("direct_webrtc", [False, True]) -async def test_audio_trace_distinguishes_queue_socket_and_receipt(direct_webrtc): - """A blocked socket must not look sent when the SDK merely queues audio.""" - now = [0.0] - trace = OjinSessionTrace(clock=lambda: now[0]) - submitted, release, completed = asyncio.Event(), asyncio.Event(), asyncio.Event() - - class PausedSocket: - async def send(self, _data): - submitted.set() - await release.wait() - completed.set() - - transport = OjinClient("ws://localhost:8000/realtime", "timing-test", "portrait") - transport._running = True - transport._inference_server_ready = True - transport._ws = PausedSocket() - client = OjinSTVClient( - client=transport, - tracer=trace, - config=STVConfig( - server_feed_batching_enabled=False, - server_feed_max_lead_ms=0, - loop_stall_watchdog_ms=0, - stall_probe_ms=0, - ), - webrtc=( - WebRTCSettings( - room_url="https://ojin.daily.co/timing-test", token="timing-test" - ) - if direct_webrtc - else None - ), - ) - engine = client._webrtc or client - if direct_webrtc: - await engine._handle_message( - OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) - ) - else: - engine._initialized = True - now[0] = 1.0 - await client.start_turn() - await client.send_tts_audio(b"\x01\x02" * 3200, 16000, 1) - before_send = trace.build()["traceEvents"] - assert [ - event["name"] for event in before_send if event["name"].startswith("audio_") - ] == ["audio_enqueued"] - - now[0] = 2.0 - sender = asyncio.create_task(transport._process_client_messages()) - try: - await asyncio.wait_for(submitted.wait(), 1) - assert not any( - event["name"] == "audio_send_complete" - for event in trace.build()["traceEvents"] - ) - now[0] = 2.1 - release.set() - await asyncio.wait_for(completed.wait(), 1) - now[0] = 3.0 - await engine._handle_message( - OjinInteractionResponseMessage( - interaction_id="timing-test", - video_frame_bytes=b"", - audio_frame_bytes=b"", - is_final_response=False, - index=5, - frame_type=FrameType.SPEECH, - ) - ) - finally: - transport._running = False - sender.cancel() - with contextlib.suppress(asyncio.CancelledError): - await sender - - result = trace.build() - audio_events = [ - event for event in result["traceEvents"] if event["name"].startswith("audio_") - ] - assert [event["name"] for event in audio_events] == [ - "audio_enqueued", - "audio_send_start", - "audio_send_complete", - ] - assert [event["ts"] for event in audio_events] == pytest.approx( - [1_000_000, 2_000_000, 2_100_000] - ) - assert [event["args"] for event in audio_events] == [{"bytes": 6400}] * 3 - assert result["otherData"]["response_latency_ms"]["recv"]["last_ms"] == 2000.0 - if direct_webrtc: - assert result["otherData"]["recv_latency_semantics"] == ( - "recv marks local receipt of speech metadata over WebSocket, " - "not server publication or browser media playback" - ) diff --git a/tests/stv/test_server_feed_hint.py b/tests/stv/test_server_feed_hint.py index b117751..ae69f0f 100644 --- a/tests/stv/test_server_feed_hint.py +++ b/tests/stv/test_server_feed_hint.py @@ -60,7 +60,7 @@ async def test_hint_releases_preinit_audio_and_rearms_after_cancel( direct: bool, rate: int ) -> None: """A 500 ms first batch reaches the server both before and after barge-in.""" - client, engine, transport, trace = _client(direct, rate=rate) + client, engine, transport, _trace = _client(direct, rate=rate) pcm = b"\x01\x02" * (rate // 2) try: await client.start_turn() @@ -68,12 +68,6 @@ async def test_hint_releases_preinit_audio_and_rearms_after_cancel( assert not _audio(transport) await engine._handle_message(_ready(500)) assert _audio(transport) == [pcm] - assert ( - "to_server", - "server_feed_config", - {"initial_chunk_ms": 500, "source": "server"}, - ) in trace.instants - if not direct: engine._synchronizer.current_buffer = AudioBuffer(sample_rate=rate) engine._synchronizer.current_buffer.bytes_.extend(pcm) diff --git a/tests/test_ojin_client.py b/tests/test_ojin_client.py index 985cb19..fd4d2a4 100644 --- a/tests/test_ojin_client.py +++ b/tests/test_ojin_client.py @@ -141,10 +141,6 @@ async def paced_sleep(delay): client._running = True client._inference_server_ready = True client._ws = PausedWS() # type: ignore[assignment] - send_events = [] - client.set_audio_send_callback( - lambda event, size: send_events.append((event, size)) - ) 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()) @@ -173,27 +169,6 @@ async def paced_sleep(delay): assert all( json.loads(message)["type"] == "cancelInteraction" for message in sent[1:-1] ) - assert send_events == [ - ("audio_send_start", 204800), - ("audio_send_complete", 204800), - ("audio_send_start", len(fresh_audio)), - ("audio_send_complete", len(fresh_audio)), - ] - - -async def test_audio_send_callback_failure_does_not_stop_sending(): - """Trace observers cannot interrupt audio delivery or its sender task.""" - client = _client() - client._running = True - client._ws = _FakeWS() - - def fail_observer(_event, _size): - raise RuntimeError("trace collector unavailable") - - client.set_audio_send_callback(fail_observer) - await client._pending_client_messages_queue.put(_audio_msg(b"\x01\x02" * 3200)) - await _drain_send_loop(client, expected_sends=1, real_sleep=asyncio.sleep) - assert len(client._ws.sent) == 1 async def test_reply_after_cancel_survives_sender_waiting_on_empty_queue() -> None: From 103543a0be0b568228b8b645adf96739b6200fa9 Mon Sep 17 00:00:00 2001 From: Faris Rahman Date: Mon, 28 Sep 2026 13:32:31 +0200 Subject: [PATCH 4/5] feat(stv): support precise audio batching and send timing Clients can opt into small audio packets without losing PCM samples or short tails, while retaining the existing batching defaults. Traces now distinguish queued audio from completed writes, and cancellation retires old in-flight audio without discarding the next reply. --- .github/actions/ci-verify/action.yml | 2 +- CHANGELOG.md | 14 ++ pyproject.toml | 2 +- src/ojin/ojin_client.py | 61 +++++-- src/ojin/stv/_outbound_feed.py | 47 ++++- src/ojin/stv/config.py | 8 +- src/ojin/stv/send_batcher.py | 23 ++- tests/stv/test_fixed_audio_feed.py | 255 +++++++++++++++++++++++++++ tests/test_ojin_client.py | 131 +++++++++++++- uv.lock | 2 +- 10 files changed, 504 insertions(+), 41 deletions(-) create mode 100644 tests/stv/test_fixed_audio_feed.py 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/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..d398841 --- /dev/null +++ b/tests/stv/test_fixed_audio_feed.py @@ -0,0 +1,255 @@ +"""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,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" }, From 7a90942d8e48bfed790f049b65e069043ce94ad8 Mon Sep 17 00:00:00 2001 From: Faris Rahman Date: Mon, 28 Sep 2026 14:52:55 +0200 Subject: [PATCH 5/5] chore(stv): keep Presence audio changes independent Separate the Presence batching, send timing, and cancellation work from Portrait server hints. Verify the 320 ms profile sends larger TTS bursts intact and rearms for each turn. --- CHANGELOG.md | 6 +- README.md | 19 ++- pyproject.toml | 2 +- src/ojin/stv/_outbound_feed.py | 39 ++---- src/ojin/stv/config.py | 4 +- src/ojin/stv/ojin_stv_client.py | 1 - src/ojin/stv/ojin_stv_webrtc_client.py | 1 - src/ojin/stv/send_batcher.py | 4 - tests/stv/test_fixed_audio_feed.py | 40 ++++++ tests/stv/test_server_feed_hint.py | 171 ------------------------- uv.lock | 2 +- 11 files changed, 69 insertions(+), 220 deletions(-) delete mode 100644 tests/stv/test_server_feed_hint.py diff --git a/CHANGELOG.md b/CHANGELOG.md index 43fbd51..ffbf300 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,13 +4,9 @@ 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.12.0 - 2026-09-28 +## 0.11.1 - 2026-09-28 ### Added -- STV clients accept the server's recommended initial audio batch size before - replaying queued TTS. Human Portrait 2 servers can request 500 ms; servers - without a valid hint retain 1000 ms. Explicit `server_feed_initial_chunk_ms` - settings still take precedence; the default `None` selects automatic tuning. - `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 diff --git a/README.md b/README.md index 382c4dc..360e2f2 100644 --- a/README.md +++ b/README.md @@ -163,9 +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, including 40 ms fragments. After each `start_turn()`, the client accumulates the server's recommended initial audio duration, or 1,000 ms if no valid recommendation is available. An explicit `server_feed_initial_chunk_ms` overrides the recommendation. Subsequent batches use a 400 ms minimum by default. Once a threshold is met, the client sends all available audio, subject to the transport's packet-size cap. A 1-second TTS packet stays together even if the initial threshold is 500 ms. +**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 initial and subsequent packet sizes. The SDK rounds those sizes up to complete PCM16 samples, retains overflow for the next packet, and flushes short tails without padding. Tune batching and send spacing with the `server_feed_*` fields on [`STVConfig`](#configuration). +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. @@ -381,10 +392,10 @@ avatar_token = ( | `interrupt_audio_fade_s` | `0.75` | Fade length applied on barge-in | | `lipsync_trace_enabled` | `False` | Emit the per-tick A/V-sync diagnostics | | `server_feed_batching_enabled` | `True` | Prime + combine the server-bound audio feed (`False` = send each chunk as-is) | -| `server_feed_initial_chunk_ms` | `None` | Accept the server's initial-batch recommendation (1,000 ms fallback); an explicit duration overrides it | +| `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 batch sizes rounded up to complete PCM16 samples; otherwise send the whole available batch | +| `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 bda8a93..890548c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ojin-client" -version = "0.12.0" +version = "0.11.1" description = "Ojin platform services" readme = "README.md" requires-python = ">=3.10" diff --git a/src/ojin/stv/_outbound_feed.py b/src/ojin/stv/_outbound_feed.py index b2e434f..059950f 100644 --- a/src/ojin/stv/_outbound_feed.py +++ b/src/ojin/stv/_outbound_feed.py @@ -34,8 +34,6 @@ # conversion is an instance value (`_bytes_per_ms`) derived from the feed rate; # 16 kHz stays the default so the legacy client is byte-identical. FEED_SAMPLE_RATE = 16_000 -_DEFAULT_INITIAL_CHUNK_MS = 1000 -_MAX_SERVER_INITIAL_CHUNK_MS = 8000 class OutboundFeedMixin: @@ -62,16 +60,19 @@ 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._feed_sample_rate = feed_sample_rate self._bytes_per_ms = feed_sample_rate * 2 / 1000.0 initial_ms = self._config.server_feed_initial_chunk_ms - if initial_ms is None: - initial_ms = _DEFAULT_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=self._batch_threshold_bytes(initial_ms), - min_chunk_bytes=self._batch_threshold_bytes( - self._config.server_feed_min_chunk_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, ) @@ -114,26 +115,6 @@ def _init_outbound_feed( self._interrupt_deferred: list[tuple] = [] self._deferring_input = False - def _batch_threshold_bytes(self, duration_ms: int) -> int: - if self._config.server_feed_fixed_chunk_size: - # Round up to whole PCM16 samples so packets never split a sample. - return math.ceil(duration_ms * self._feed_sample_rate / 1000) * 2 - return int(duration_ms * self._bytes_per_ms) - - def _configure_server_feed(self, parameters: dict | None) -> None: - initial_ms = self._config.server_feed_initial_chunk_ms - if initial_ms is None: - hint = (parameters or {}).get("server_feed_initial_chunk_ms") - if ( - isinstance(hint, int) - and not isinstance(hint, bool) - and 0 < hint <= _MAX_SERVER_INITIAL_CHUNK_MS - ): - initial_ms = hint - else: - initial_ms = _DEFAULT_INITIAL_CHUNK_MS - self._batcher.set_initial_chunk_bytes(self._batch_threshold_bytes(initial_ms)) - # ------------------------------------------------------------------ # Host seams # ------------------------------------------------------------------ diff --git a/src/ojin/stv/config.py b/src/ojin/stv/config.py index d13f19e..330061a 100644 --- a/src/ojin/stv/config.py +++ b/src/ojin/stv/config.py @@ -161,9 +161,7 @@ class STVConfig: # chunk per turn, then a steady-state minimum. Disable to restore per-chunk # sends. (Playback of the original audio is unaffected.) server_feed_batching_enabled: bool = True - # None accepts the server's startup recommendation, or 1000 ms without one. - # An explicit value preserves application tuning across server upgrades. - server_feed_initial_chunk_ms: int | None = None + 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. diff --git a/src/ojin/stv/ojin_stv_client.py b/src/ojin/stv/ojin_stv_client.py index 33cdcf1..ac06c24 100644 --- a/src/ojin/stv/ojin_stv_client.py +++ b/src/ojin/stv/ojin_stv_client.py @@ -536,7 +536,6 @@ async def _handle_message(self, message: BaseModel) -> None: if isinstance(message, OjinSessionReadyMessage): if message.parameters is not None: self._session_data = message.parameters - self._configure_server_feed(message.parameters) self._initialized = True self._tracer.span("lifecycle", "connect", self._tr_connect_start) if self._playback_task is None: diff --git a/src/ojin/stv/ojin_stv_webrtc_client.py b/src/ojin/stv/ojin_stv_webrtc_client.py index 2fb41f0..36dbb38 100644 --- a/src/ojin/stv/ojin_stv_webrtc_client.py +++ b/src/ojin/stv/ojin_stv_webrtc_client.py @@ -511,7 +511,6 @@ async def _on_session_ready(self, message: OjinSessionReadyMessage) -> None: self._cancel_join_timer() if message.parameters is not None: self._session_data = message.parameters - self._configure_server_feed(message.parameters) self._initialized = True self._tracer.span("lifecycle", "connect", self._tr_connect_start) await self._events.emit(STVEvent.SESSION_READY, session_data=self._session_data) diff --git a/src/ojin/stv/send_batcher.py b/src/ojin/stv/send_batcher.py index 472d2d5..69cfd39 100644 --- a/src/ojin/stv/send_batcher.py +++ b/src/ojin/stv/send_batcher.py @@ -115,10 +115,6 @@ def rearm_initial(self) -> None: """Make the next emit use the initial (lead) threshold again.""" self._next_is_initial = True - def set_initial_chunk_bytes(self, byte_count: int) -> None: - """Change the initial threshold without losing pending audio or rearming.""" - self._initial_chunk_bytes = byte_count - def reset(self) -> None: """Discard buffered bytes and re-arm the initial threshold (barge-in).""" self._buf.clear() diff --git a/tests/stv/test_fixed_audio_feed.py b/tests/stv/test_fixed_audio_feed.py index d398841..a08b42d 100644 --- a/tests/stv/test_fixed_audio_feed.py +++ b/tests/stv/test_fixed_audio_feed.py @@ -64,6 +64,46 @@ async def _wait_for_writes(sent, count: int) -> None: 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 diff --git a/tests/stv/test_server_feed_hint.py b/tests/stv/test_server_feed_hint.py deleted file mode 100644 index 713ab88..0000000 --- a/tests/stv/test_server_feed_hint.py +++ /dev/null @@ -1,171 +0,0 @@ -"""Server feed hints apply before audio replay without changing explicit settings.""" - -import pytest - -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 _client( - direct: bool, - initial: int | None = None, - rate: int = 16000, - fixed: bool = False, -): - transport = FakeOjinClient() - trace = RecordingTracer() - config = STVConfig( - server_feed_flush_idle_ms=10000, - server_feed_max_lead_ms=0, - server_feed_fixed_chunk_size=fixed, - ) - if initial is not None: - config.server_feed_initial_chunk_ms = initial - client = OjinSTVClient( - client=transport, - tracer=trace, - config=config, - webrtc=( - WebRTCSettings( - room_url="https://ojin.daily.co/feed-hint", - token="feed-hint-test", - audio_sample_rate=rate, - ) - if direct - else None - ), - ) - return client, client._webrtc or client, transport, trace - - -def _ready(hint: object = None) -> OjinSessionReadyMessage: - parameters = dict(READY_CONNECTED_PARAMETERS) - if hint is not None: - parameters["server_feed_initial_chunk_ms"] = hint - return OjinSessionReadyMessage(parameters=parameters) - - -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) - ] - - -@pytest.mark.parametrize("direct,rate", [(False, 16000), (True, 16000), (True, 44100)]) -async def test_hint_releases_preinit_audio_and_rearms_after_cancel( - direct: bool, rate: int -) -> None: - """A 500 ms first batch reaches the server both before and after barge-in.""" - client, engine, transport, _trace = _client(direct, rate=rate) - pcm = b"\x01\x02" * (rate // 2) - try: - await client.start_turn() - await client.send_tts_audio(pcm, rate, 1) - assert not _audio(transport) - await engine._handle_message(_ready(500)) - assert _audio(transport) == [pcm] - 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() - split_at = rate * 2 * 400 // 1000 - await client.send_tts_audio(pcm[:split_at], rate, 1) - await engine._handle_message(_frame(FrameType.IDLE)) - assert len(_audio(transport)) == 1 - await client.send_tts_audio(pcm[split_at:], rate, 1) - assert _audio(transport) == [pcm, pcm] - finally: - await client.close() - - -@pytest.mark.parametrize("direct", [False, True]) -@pytest.mark.parametrize("fixed", [False, True]) -@pytest.mark.parametrize("hint", [None, False, True, 0, -1, 500.0, "500", 8001, {}, []]) -async def test_missing_or_invalid_hint_keeps_legacy_threshold( - direct: bool, fixed: bool, hint: object -) -> None: - """Untrusted hint shapes cannot silently change the legacy initial batch.""" - client, engine, transport, _trace = _client(direct, fixed=fixed) - pcm = b"\x01\x02" * 8000 - try: - await engine._handle_message(_ready(hint)) - await client.start_turn() - await client.send_tts_audio(pcm, 16000, 1) - assert not _audio(transport) - await client.send_tts_audio(pcm, 16000, 1) - assert _audio(transport) == [pcm * 2] - finally: - await client.close() - - -@pytest.mark.parametrize("fixed", [False, True]) -async def test_fractional_sample_hint_preserves_preinit_audio(fixed: bool) -> None: - """Apply the hint before replay, with sample-aligned packets and no loss.""" - rate = 44100 - client, engine, transport, _trace = _client(True, rate=rate, fixed=fixed) - pcm = b"\x01\x02" * rate - try: - await client.start_turn() - await client.send_tts_audio(pcm, rate, 1) - assert not _audio(transport) - await engine._handle_message(_ready(329)) - assert [len(packet) for packet in _audio(transport)] == ( - [29018, 35280] 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() - - -@pytest.mark.parametrize("direct", [False, True]) -async def test_explicit_threshold_overrides_server_hint(direct: bool) -> None: - """A caller's configured startup lead wins over the server recommendation.""" - client, engine, transport, _trace = _client(direct, initial=1200) - try: - await engine._handle_message(_ready(500)) - await client.start_turn() - await client.send_tts_audio(b"\x01\x02" * 16000, 16000, 1) - assert not _audio(transport) - await client.send_tts_audio(b"\x01\x02" * 3200, 16000, 1) - assert _audio(transport) == [b"\x01\x02" * 19200] - finally: - await client.close() - - -@pytest.mark.parametrize("direct", [False, True]) -async def test_later_handshake_restores_fallback_without_losing_pending( - direct: bool, -) -> None: - """Another ready event updates the lead while retaining unsent PCM.""" - client, engine, transport, _trace = _client(direct) - pcm = b"\x01\x02" * 6400 - try: - await engine._handle_message(_ready(500)) - await client.start_turn() - await client.send_tts_audio(pcm, 16000, 1) - assert not _audio(transport) - await engine._handle_message(_ready()) - await client.send_tts_audio(pcm, 16000, 1) - assert not _audio(transport) - await client.send_tts_audio(pcm[:6400], 16000, 1) - assert _audio(transport) == [pcm * 2 + pcm[:6400]] - await client.send_tts_audio(pcm[:6400], 16000, 1) - await engine._handle_message(_ready(500)) - await client.send_tts_audio(pcm[:6400], 16000, 1) - assert _audio(transport)[1] == pcm - finally: - await client.close() diff --git a/uv.lock b/uv.lock index f4ce1bc..176bcd2 100644 --- a/uv.lock +++ b/uv.lock @@ -825,7 +825,7 @@ wheels = [ [[package]] name = "ojin-client" -version = "0.12.0" +version = "0.11.1" source = { editable = "." } dependencies = [ { name = "async-lru" },