diff --git a/CHANGELOG.md b/CHANGELOG.md index ffbf300..92dd0a0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,24 @@ 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 + +## 0.12.0 - 2026-09-29 + +### Added + +- STV clients accept the server's recommended initial audio batch size before + replaying queued TTS. Servers without a valid hint retain 1000 ms. Explicit + `server_feed_initial_chunk_ms` settings still take precedence; the default + `None` selects automatic tuning. The Human Portrait low-latency profile uses + an explicit 200 ms threshold, overriding older 500 ms hints while preserving + larger TTS bursts in full. + +### Fixed + +- Startup recommendations preserve whole PCM16 samples in fixed-size batching, + including durations that fall between samples at 44.1 kHz. + ## 0.11.1 - 2026-09-28 ### Added diff --git a/README.md b/README.md index 360e2f2..dd62b6e 100644 --- a/README.md +++ b/README.md @@ -163,7 +163,19 @@ 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. 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. +**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 burst stays together even at a 200 ms threshold. + +For the Human Portrait low-latency deployment, pass this configuration to `OjinSTVClient`: + +```python +config = STVConfig( + server_feed_initial_chunk_ms=200, + server_feed_min_chunk_ms=200, + server_feed_send_gap_ms=100, +) +``` + +The explicit 200 ms setting takes precedence over an older server recommendation of 500 ms. 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. @@ -392,7 +404,7 @@ 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` | `1000` | Initial lead accumulated after each `start_turn()` | +| `server_feed_initial_chunk_ms` | `None` | Accept the server recommendation (1,000 ms fallback); an explicit duration overrides it | | `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 | diff --git a/pyproject.toml b/pyproject.toml index 890548c..bda8a93 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "ojin-client" -version = "0.11.1" +version = "0.12.0" 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 059950f..afbda31 100644 --- a/src/ojin/stv/_outbound_feed.py +++ b/src/ojin/stv/_outbound_feed.py @@ -34,6 +34,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,19 +62,16 @@ 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 - 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) + if initial_ms is None: + initial_ms = _DEFAULT_INITIAL_CHUNK_MS self._batcher = SendBatcher( - initial_chunk_bytes=initial_bytes, - min_chunk_bytes=steady_bytes, + initial_chunk_bytes=self._feed_chunk_bytes(initial_ms), + min_chunk_bytes=self._feed_chunk_bytes( + self._config.server_feed_min_chunk_ms + ), flush_idle_s=self._config.server_feed_flush_idle_ms / 1000.0, fixed_chunk_size=self._config.server_feed_fixed_chunk_size, ) @@ -115,6 +114,26 @@ def _init_outbound_feed( self._interrupt_deferred: list[tuple] = [] self._deferring_input = False + def _feed_chunk_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._feed_chunk_bytes(initial_ms)) + # ------------------------------------------------------------------ # Host seams # ------------------------------------------------------------------ diff --git a/src/ojin/stv/config.py b/src/ojin/stv/config.py index 330061a..d13f19e 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 # 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 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..2fb41f0 100644 --- a/src/ojin/stv/ojin_stv_webrtc_client.py +++ b/src/ojin/stv/ojin_stv_webrtc_client.py @@ -511,6 +511,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 69cfd39..472d2d5 100644 --- a/src/ojin/stv/send_batcher.py +++ b/src/ojin/stv/send_batcher.py @@ -115,6 +115,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_fixed_audio_feed.py b/tests/stv/test_fixed_audio_feed.py index a08b42d..c16cc2c 100644 --- a/tests/stv/test_fixed_audio_feed.py +++ b/tests/stv/test_fixed_audio_feed.py @@ -256,14 +256,16 @@ async def test_short_utterance_idle_flushes_without_padding() -> None: @pytest.mark.parametrize("fixed", [False, True]) +@pytest.mark.parametrize("initial_source", ["explicit", "hint"]) async def test_fractional_sample_thresholds_preserve_complete_pcm_samples( fixed: bool, + initial_source: str, ) -> 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_initial_chunk_ms = 329 if initial_source == "explicit" else None config.server_feed_min_chunk_ms = 201 config.server_feed_fixed_chunk_size = fixed client = OjinSTVClient( @@ -278,12 +280,15 @@ async def test_fractional_sample_thresholds_preserve_complete_pcm_samples( ) engine = client._webrtc pcm = b"\x01\x02" * rate + parameters = dict(READY_CONNECTED_PARAMETERS) + parameters["server_feed_initial_chunk_ms"] = ( + 500 if initial_source == "explicit" else 329 + ) try: - await engine._handle_message( - OjinSessionReadyMessage(parameters=READY_CONNECTED_PARAMETERS) - ) await client.start_turn() await client.send_tts_audio(pcm, rate, 1) + assert not _audio(transport) + await engine._handle_message(OjinSessionReadyMessage(parameters=parameters)) assert [len(packet) for packet in _audio(transport)] == ( [29018, 17730, 17730, 17730] if fixed else [len(pcm)] ) diff --git a/tests/stv/test_server_feed_hint.py b/tests/stv/test_server_feed_hint.py new file mode 100644 index 0000000..a5bcb1b --- /dev/null +++ b/tests/stv/test_server_feed_hint.py @@ -0,0 +1,165 @@ +"""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] + 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_portrait_threshold_sends_whole_burst_then_rearms(direct: bool) -> None: + """An explicit 200 ms lead overrides older hints and preserves TTS bursts.""" + client, engine, transport, _trace = _client(direct, initial=200) + pcm = b"\x01\x02" * 16000 + try: + await engine._handle_message(_ready(500)) + 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[: 200 * 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", [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 176bcd2..f4ce1bc 100644 --- a/uv.lock +++ b/uv.lock @@ -825,7 +825,7 @@ wheels = [ [[package]] name = "ojin-client" -version = "0.11.1" +version = "0.12.0" source = { editable = "." } dependencies = [ { name = "async-lru" },