Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/actions/ci-verify/action.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
14 changes: 14 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 16 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -163,7 +163,20 @@ asyncio.run(main())

**Turns.** A turn is one spoken utterance. Open it with `start_turn()`, then push audio with `send_tts_audio(pcm, sample_rate, num_channels)` as many times as you like. The client buffers and plays the **original** audio you sent while a 16 kHz copy goes to the server for lip-sync — so the voice the user hears is always exactly yours. Because the original is what's played back, you can feed **higher-quality** TTS (e.g. 24 kHz) for better sound and lip-sync still works on the 16 kHz copy — just set your player to the `sample_rate` each `STVAudioFrame` reports.

**Input shaping.** Feed audio at whatever cadence your TTS produces — even tiny 40 ms fragments. The client takes care of the input shape to optimize latency and stability: it primes a ~1 s lead after each `start_turn()`, then combines your audio into **≥400 ms** chunks before forwarding it to the server, so the inference head never starves and lip-sync stays stable. It's automatic — tune it (or restore per-chunk sends) with the `server_feed_*` fields on [`STVConfig`](#configuration).
**Input shaping.** Feed audio at whatever cadence your TTS produces, including 40 ms fragments. By default, the client accumulates 1,000 ms after each `start_turn()` and uses a 400 ms minimum for subsequent batches. Once a threshold is met, it sends all available audio, subject to the transport's packet-size cap. A 1-second TTS burst stays together even at a 320 ms threshold.

Use `server_feed_fixed_chunk_size=True` only when you want exact packet sizes. The SDK rounds sizes up to complete PCM16 samples, retains overflow, and flushes short tails without padding.

For the Human Presence low-latency deployment, pass this configuration to `OjinSTVClient`:

```python
config = STVConfig(
server_feed_initial_chunk_ms=320,
server_feed_min_chunk_ms=200,
server_feed_send_gap_ms=100,
server_feed_fixed_chunk_size=False,
)
```

**Audio is the clock.** The playback loop emits **exactly one audio frame every tick** (real audio or silence so the consumer never starves) plus a video frame whenever one is ready, at `STVConfig.fps` (default 25 → a 40 ms tick). Video falls back to repeating the last frame rather than stalling.

Expand Down Expand Up @@ -382,6 +395,8 @@ avatar_token = (
| `server_feed_initial_chunk_ms` | `1000` | Initial lead accumulated after each `start_turn()` |
| `server_feed_min_chunk_ms` | `400` | Steady-state minimum send size |
| `server_feed_flush_idle_ms` | `200` | Quiet time before flushing a sub-threshold tail |
| `server_feed_fixed_chunk_size` | `False` | Emit exact sizes rounded up to complete PCM16 samples; otherwise send the whole batch |
| `server_feed_send_gap_ms` | `200` | Minimum wait after an audio write before the next write starts |

Video frames are emitted at the server's native resolution — read `STVVideoFrame.width`/`height` per frame rather than configuring an output size. Set `OJIN_MODE=dev` in the environment to attach the dev-mode query flag when connecting with the default transport.

Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -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"
Expand Down
61 changes: 44 additions & 17 deletions src/ojin/ojin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__()
Expand All @@ -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[
Expand All @@ -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.

Expand Down Expand Up @@ -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())

Expand All @@ -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)
Expand All @@ -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 = [
Expand All @@ -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
Expand All @@ -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",
Expand All @@ -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()
Expand Down
47 changes: 38 additions & 9 deletions src/ojin/stv/_outbound_feed.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
import asyncio
import contextlib
import logging
import math
from collections import deque
from typing import Optional

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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)

Expand Down Expand Up @@ -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).
Expand Down Expand Up @@ -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:
Expand Down
8 changes: 6 additions & 2 deletions src/ojin/stv/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
23 changes: 20 additions & 3 deletions src/ojin/stv/send_batcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -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.

Expand All @@ -39,13 +40,18 @@ 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__()
self._initial_chunk_bytes = initial_chunk_bytes
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()
Expand All @@ -59,21 +65,32 @@ 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
else self._min_chunk_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

Expand Down
Loading
Loading