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
18 changes: 18 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,24 @@ All notable changes to `ojin-client` are documented here. The format follows

## Unreleased

## 0.12.2 - 2026-10-15

### Added
- `STVEvent.SESSION_STARTING` (args `phase`, `elapsed_ms`): the service's startup
status, emitted in direct-WebRTC mode for each `sessionPing` it sends while
the session is still starting. `OjinSessionReadyPing` now carries `phase` and
`elapsed_ms`; a ping whose fields have unexpected types parses with them unset
and can never end the session.
- `WebRTCSettings.startup_inactivity_timeout_s` (default 20 s).

### Changed
- The direct-WebRTC start is no longer bounded by a blind total once the service
reports progress. From the first `sessionPing` the fixed `webrtc_join_timeout_s`
timer is replaced by a watchdog that fails (`WEBRTC_JOIN_TIMEOUT`, naming the
last phase reported) only after `startup_inactivity_timeout_s` of silence; the
service's own deadlines bound the total. A service that sends no status is
handled as before.

## 0.12.1 - 2026-10-01

### Changed
Expand Down
7 changes: 4 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -202,6 +202,7 @@ Register handlers with `@client.on(STVEvent.X)` or `client.add_listener(STVEvent

| Event | Fires when | Handler kwargs |
|---|---|---|
| `SESSION_STARTING` | Direct WebRTC only: the service is still starting the session and reported its progress (every few seconds until `SESSION_READY`) | `phase: str \| None`, `elapsed_ms: int \| None` |
| `SESSION_READY` | The session is live and ready for audio | `session_data: dict \| None` |
| `WEBRTC_CONNECTED` | Direct WebRTC only: the avatar has joined your room | `participant_id: str \| None` |
| `FIRST_FRAME` | The avatar's first video frame is out (emitted to your output, or published to the room) | `frame_type: int` |
Expand Down Expand Up @@ -380,7 +381,7 @@ avatar_token = (
| `WEBRTC_AUTH_FAILED` | The room rejected the avatar's token |
| `WEBRTC_NETWORK_FAILED` | Ojin couldn't reach the room |
| `WEBRTC_INVALID_SETTINGS` | The room URL or provider was unusable |
| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready within `webrtc_join_timeout_s` (default 90 s — it covers the model's cold start too, which alone can take more than 30 s) |
| `WEBRTC_JOIN_TIMEOUT` | The session wasn't ready in time: within `webrtc_join_timeout_s` (default 90 s) on a service that sends no startup status, or after `startup_inactivity_timeout_s` (default 20 s) of silence from one that does |
| `WEBRTC_ROOM_LOST` | The avatar dropped out of the room mid-session |
| `WEBRTC_NOT_SUPPORTED` | The server returned no room result for this session |
| `WEBRTC_JOIN_FAILED` | Fallback: the join failed with a code this SDK doesn't recognise |
Expand Down Expand Up @@ -412,7 +413,7 @@ avatar_token = (

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.

For direct WebRTC, `WebRTCSettings` takes `provider`, `room_url`, `token`, `audio_sample_rate` (default `16000`) and `webrtc_join_timeout_s` (default `90.0`); the playback fields above don't apply because the media goes to the room.
For direct WebRTC, `WebRTCSettings` takes `provider`, `room_url`, `token`, `audio_sample_rate` (default `16000`), `webrtc_join_timeout_s` (default `90.0`) and `startup_inactivity_timeout_s` (default `20.0`); the playback fields above don't apply because the media goes to the room.

---

Expand Down Expand Up @@ -491,7 +492,7 @@ async def main(pcm_16k_mono: bytes) -> None:
- **Choppy playback** — keep the event loop free; the SDK already decodes JPEG off-loop, but heavy synchronous work in your frame handlers will stall the 40 ms tick. Enable `STVConfig(lipsync_trace_enabled=True)` to inspect per-tick timing.
- **Latency higher than expected** — the WebSocket transport is built for **server-to-server** use over a stable connection. Run the client on a backend (not an end-user device), ideally in **US East**, close to Ojin's inference; deliver the final media to end users over a realtime transport such as WebRTC — or publish straight into their room with [direct WebRTC](#direct-webrtc-livekit--daily). The client keeps a small video buffer (`initial_buffer_frames`) to absorb network jitter, since the server delivers at realtime 25 fps.
- **`WEBRTC_AUTH_FAILED`** — the token doesn't grant the avatar access to that room. On LiveKit, check the token's identity is exactly `ojin-avatar` and it allows publishing; on Daily, check the meeting token is for the same room as `room_url`.
- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready within `webrtc_join_timeout_s` (default 90 s). It covers the model's cold start as well as the room join, and a cold start alone can take more than 30 s, so don't lower it below that. Retrying usually succeeds: the server keeps starting after the client gives up.
- **`WEBRTC_JOIN_TIMEOUT`** — the session didn't become ready in time. A service that reports its startup progress (`SESSION_STARTING` events) bounds the start itself, and the client fails only after `startup_inactivity_timeout_s` (default 20 s) without a report; the message names the last phase reported. On a service that sends no reports, `webrtc_join_timeout_s` (default 90 s) applies; it covers the model's cold start as well as the room join, and a cold start alone can take more than 30 s, so don't lower it below that. Retrying usually succeeds: the server keeps starting after the client gives up.
- **`CONNECTION_CLOSED`** — the connection ended before the session was ready and the server sent no error of its own. The message carries the WebSocket close code and reason (for example `1008: Insufficient funds`).
- **Your bot hears the avatar** — it's subscribed to the `ojin-avatar` participant's microphone. Detect it with `is_avatar_participant()` / `is_avatar_identity()` and unsubscribe.

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.12.1"
version = "0.12.2"
description = "Ojin platform services"
readme = "README.md"
requires-python = ">=3.10"
Expand Down
6 changes: 4 additions & 2 deletions skills/ojin-stv-integration/SKILL.md
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,7 @@ Handlers may be sync or async; one failing handler never breaks the loops.

| Event | Fires when | Kwargs |
|---|---|---|
| `SESSION_STARTING` | direct WebRTC only: the service reported startup progress (every few seconds until ready) | `phase`, `elapsed_ms` |
| `SESSION_READY` | session is live (safe to send audio) | `session_data` |
| `WEBRTC_CONNECTED` | direct WebRTC only: the avatar joined your room | `participant_id` |
| `FIRST_FRAME` | the avatar's first video frame is out (to your output, or into the room) | `frame_type` |
Expand Down Expand Up @@ -205,8 +206,9 @@ client = OjinSTVClient(
ends at close. Don't build a render path in this mode.
- `WEBRTC_CONNECTED` fires when the avatar is in the room; `FIRST_FRAME` and the
speaking events still fire.
- **No fallback.** A failed join, a `webrtc_join_timeout_s` expiry (default 90 s,
includes cold start — don't lower it below ~60 s) or an unsupporting server is a fatal
- **No fallback.** A failed join, a startup that times out (`webrtc_join_timeout_s`, default
90 s, on a service that sends no startup status; `startup_inactivity_timeout_s`
of silence, default 20 s, on one that does) or an unsupporting server is a fatal
`ERROR` naming the cause (`WEBRTC_AUTH_FAILED`, `WEBRTC_NETWORK_FAILED`,
`WEBRTC_INVALID_SETTINGS`, `WEBRTC_JOIN_TIMEOUT`, `WEBRTC_ROOM_LOST` or
`WEBRTC_NOT_SUPPORTED`) and the session closes.
Expand Down
30 changes: 26 additions & 4 deletions src/ojin/ojin_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -118,6 +118,27 @@ def _read_tcp_info(sock: socket.socket) -> dict[str, int]:
return {}


def _parse_session_ping(data: dict) -> OjinSessionReadyPing:
"""Read the startup status out of a ``sessionPing`` (bare on older services).

Never raises: a status message must not be able to end the session, so a
field of the wrong type is simply left unset.
"""
payload = data.get("payload")
if not isinstance(payload, dict):
return OjinSessionReadyPing()
phase = payload.get("phase")
elapsed = payload.get("elapsed_ms")
elapsed_ms: int | None = None
if isinstance(elapsed, (int, float)) and not isinstance(elapsed, bool):
# json.loads admits NaN and Infinity, which int() refuses.
with contextlib.suppress(ValueError, OverflowError):
elapsed_ms = int(elapsed)
return OjinSessionReadyPing(
phase=phase if isinstance(phase, str) else None, elapsed_ms=elapsed_ms
)


class OjinClient(IOjinClient):
"""WebSocket client for communicating with the OJIN STV service.

Expand Down Expand Up @@ -507,16 +528,17 @@ async def _handle_server_message(self, message: str | bytes) -> None:
await self._available_response_messages_queue.put(session_ready)
return

msg = msg_class(**data)
msg = (
_parse_session_ping(data)
if msg_type == "sessionPing"
else msg_class(**data)
)
await self._available_response_messages_queue.put(msg)

if isinstance(msg, ErrorResponseMessage):
self._error_reported = True
raise RuntimeError(f"Error in Inference Server received: {msg}")

if isinstance(msg, OjinSessionReadyPing):
# Discard session pings
pass
else:
logger.warning("Unknown message type: %s", msg_type)

Expand Down
12 changes: 11 additions & 1 deletion src/ojin/ojin_client_messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,17 @@ class OjinSessionReadyMessage(OjinMessage):


class OjinSessionReadyPing(OjinMessage):
"""Ping message used to check session readiness with the Ojin backend."""
"""Startup status from the service while the session is still starting.

Sent every few seconds before ``sessionReady`` by a service that bounds
the start itself. ``phase`` names what it is waiting on (for example
``waiting_for_container`` or ``setting_up_session``) and ``elapsed_ms``
is the time since the start was requested; both are absent on an older
service, which sends the bare ping.
"""

phase: str | None = None
elapsed_ms: int | None = None


class OjinInteractionResponseMessage(OjinMessage):
Expand Down
21 changes: 16 additions & 5 deletions src/ojin/stv/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,8 +46,11 @@ class WebRTCSettings:
Set ``audio_sample_rate`` to the rate your TTS emits to avoid resampling.
``webrtc_join_timeout_s`` bounds the whole wait for the session to become
ready — the room join *and* a model cold start, which alone can take more
than 30 s. It is a backstop: a start the service itself gives up on is
reported sooner, as the server's own error.
than 30 s — on a service that sends no startup status. A service that
reports its startup progress (``sessionPing`` messages every few seconds)
bounds the start itself; from the first such message the client waits as
long as the reports keep coming and fails only after
``startup_inactivity_timeout_s`` of silence instead.

The settings are declared in the WebSocket **upgrade request** (DR-006 as
amended 2026-07-24): the non-secret fields ride ``webrtc_*`` query params
Expand All @@ -58,7 +61,8 @@ class WebRTCSettings:
the ``sessionSetup`` it authors.

``token`` is excluded from ``repr``, must never be logged, and never
appears in a URL. ``webrtc_join_timeout_s`` is client-local and is never
appears in a URL. ``webrtc_join_timeout_s`` and
``startup_inactivity_timeout_s`` are client-local and are never
serialized.
"""

Expand All @@ -67,15 +71,17 @@ class WebRTCSettings:
provider: WebRTCProvider | str = WebRTCProvider.DAILY
audio_sample_rate: int = 16000
webrtc_join_timeout_s: float = 90.0
startup_inactivity_timeout_s: float = 20.0
version: int = 2

def to_connect_query_params(self) -> dict:
"""Return the non-secret ``webrtc_*`` query params for the connect URL.

Values are strings ready for URL-encoding. The ``token`` is
deliberately absent — a URL lands in access logs; the token travels
via :meth:`to_connect_headers` instead. ``webrtc_join_timeout_s`` is
likewise absent (client-local, never serialized).
via :meth:`to_connect_headers` instead. ``webrtc_join_timeout_s`` and
``startup_inactivity_timeout_s`` are likewise absent (client-local,
never serialized).
"""
return {
"webrtc_version": str(self.version),
Expand Down Expand Up @@ -114,6 +120,11 @@ def __post_init__(self) -> None:
raise ValueError(
f"webrtc_join_timeout_s must be > 0, got {self.webrtc_join_timeout_s}"
)
if self.startup_inactivity_timeout_s <= 0:
raise ValueError(
"startup_inactivity_timeout_s must be > 0, got "
f"{self.startup_inactivity_timeout_s}"
)
rate = self.audio_sample_rate
if not _MIN_AUDIO_SAMPLE_RATE <= rate <= _MAX_AUDIO_SAMPLE_RATE or (
rate % _FRAMES_PER_SECOND
Expand Down
1 change: 1 addition & 0 deletions src/ojin/stv/events.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
class STVEvent(Enum):
"""Lifecycle/state events emitted by :class:`OjinSTVClient`."""

SESSION_STARTING = "session_starting" # args: phase, elapsed_ms
SESSION_READY = "session_ready" # args: session_data
WEBRTC_CONNECTED = "webrtc_connected" # args: participant_id
FIRST_FRAME = "first_frame" # args: frame_type
Expand Down
75 changes: 72 additions & 3 deletions src/ojin/stv/ojin_stv_webrtc_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@
OjinCancelInteractionMessage,
OjinInteractionResponseMessage,
OjinSessionReadyMessage,
OjinSessionReadyPing,
OjinWebRTCStatusMessage,
)
from ojin.stv._outbound_feed import OutboundFeedMixin
Expand All @@ -77,6 +78,7 @@
_MS_PER_METADATA_FRAME = 40.0 # metadata frames are paced at 25/s
_METADATA_WATCHDOG_S = 5.0
_WATCHDOG_POLL_S = 1.0
_STARTUP_WATCHDOG_POLL_S = 0.5
_SPEECH_TYPES = (int(FrameType.SPEECH), int(FrameType.START_OF_SPEECH))
_SILENCE_TYPES = (int(FrameType.IDLE), int(FrameType.FADE_OUT))

Expand Down Expand Up @@ -180,6 +182,10 @@ def __init__( # noqa: PLR0913 — injectable deps + flat field init
self._closed = False
self._close_task: Optional[asyncio.Task] = None
self._request_sent_at = 0.0
# Startup status from the service: once it reports progress, the
# fixed join timer gives way to a silence watchdog.
self._last_startup_status_at: Optional[float] = None
self._last_startup_phase: Optional[str] = None
self._last_metadata_at = 0.0
self._first_frame_pending = False
self._last_frame_type: Optional[int] = None
Expand Down Expand Up @@ -284,7 +290,9 @@ async def start(self) -> None:
The webrtc request rides the connect exchange itself (declared on the
transport at construction), so once the connection is up the
negotiation is already in flight: the join timer armed here governs
the whole ``sessionReady`` wait (``webrtc_join_timeout_s``).
the ``sessionReady`` wait (``webrtc_join_timeout_s``) until the
service's first startup status report hands it to the silence
watchdog (see :meth:`_on_startup_status`).
"""
self._tr_session_start = self._tracer.mark()
self._tr_connect_start = self._tr_session_start
Expand Down Expand Up @@ -324,7 +332,8 @@ async def close(self) -> None:
was_initialized = self._initialized
self._initialized = False
self._preinit_inputs.clear()
self._cancel_join_timer()
join_timer, self._join_timer_task = self._join_timer_task, None
await self._cancel_task(join_timer)
await self._cancel_task(self._watchdog_task)
self._watchdog_task = None
if was_initialized:
Expand Down Expand Up @@ -478,6 +487,8 @@ async def _handle_message(self, message: BaseModel) -> None:
"""Route one server message (session ready / interaction / error)."""
if isinstance(message, OjinSessionReadyMessage):
await self._on_session_ready(message)
elif isinstance(message, OjinSessionReadyPing):
await self._on_startup_status(message)
elif isinstance(message, OjinInteractionResponseMessage):
was_interrupting = self._interruption_ongoing
await self._on_interaction_response(message)
Expand All @@ -493,6 +504,9 @@ async def _handle_message(self, message: BaseModel) -> None:
self._tracer.instant(
"lifecycle", "server_error", args={"code": code, "message": text}
)
# The server's verdict ends the start; no startup timer may add a
# second ERROR behind it.
self._cancel_join_timer()
await self._events.emit(STVEvent.ERROR, message=text, code=code, fatal=True)
self._schedule_close()

Expand Down Expand Up @@ -658,11 +672,66 @@ async def _join_timer(self) -> None:
await asyncio.sleep(self._webrtc_settings.webrtc_join_timeout_s)
await self._handle_join_timeout()

async def _on_startup_status(self, ping: OjinSessionReadyPing) -> None:
"""Note that the service is still starting the session.

The service sends these while it waits on its own bounded steps, so
from the first one the total is its responsibility, not ours: the
fixed join timer is replaced by a watchdog that fails only when the
reports stop.
"""
if self._state is not _DirectState.PENDING or self._initialized or self._closed:
return
first = self._last_startup_status_at is None
self._last_startup_status_at = self._clock()
self._last_startup_phase = ping.phase
self._tracer.instant(
"webrtc",
"startup_status",
args={"phase": ping.phase or "", "elapsed_ms": ping.elapsed_ms or 0},
)
if first:
self._cancel_join_timer()
self._join_timer_task = asyncio.create_task(self._startup_watchdog())
await self._events.emit(
STVEvent.SESSION_STARTING, phase=ping.phase, elapsed_ms=ping.elapsed_ms
)

async def _startup_watchdog(self) -> None:
"""Fail the start once the service's status reports fall silent.

Polled every ``_STARTUP_WATCHDOG_POLL_S``, so the failure lands up to
that much after ``startup_inactivity_timeout_s`` of silence, never
before it.
"""
limit = self._webrtc_settings.startup_inactivity_timeout_s
while True:
await asyncio.sleep(_STARTUP_WATCHDOG_POLL_S)
last = self._last_startup_status_at
if last is None or self._clock() - last < limit:
continue
if (
self._state is not _DirectState.PENDING
or self._initialized
or self._closed
):
return
self._tracer.instant("webrtc", "startup_stalled")
phase = self._last_startup_phase or "unknown"
await self._fail(
WEBRTC_JOIN_TIMEOUT,
"Timed out: the service stopped reporting progress for "
f"{limit:g} s while the session was starting (last phase: {phase})",
{"outcome": "timeout", "last_phase": phase},
)
return

async def _handle_join_timeout(self) -> None:
"""Fail the session if no sessionReady arrived within the join timeout.

In v2 the server joins the room during setup, so
``webrtc_join_timeout_s`` governs the whole ``sessionReady`` wait.
``webrtc_join_timeout_s`` governs the ``sessionReady`` wait on a
service that sends no startup status.
"""
if self._state is not _DirectState.PENDING or self._initialized:
return
Expand Down
2 changes: 2 additions & 0 deletions tests/stv/test_frames_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,8 @@ def test_webrtc_provider_str_is_wire_value() -> None:
{"token": ""},
{"webrtc_join_timeout_s": 0},
{"webrtc_join_timeout_s": -1.0},
{"startup_inactivity_timeout_s": 0},
{"startup_inactivity_timeout_s": -5.0},
],
)
def test_webrtc_settings_rejects_invalid_fields(overrides: dict) -> None:
Expand Down
Loading
Loading