Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(audio): de-click the mid-sentence gap when a realtime provider pauses its audio stream

Personal Jarvis Maintainer97d8bd8a1c60
diff --git a/jarvis/audio/player.py b/jarvis/audio/player.py
index 5b891888b2..3af0039293 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -45,6 +45,19 @@ _PortAudioError: type[BaseException] = sd.PortAudioError if sd is not None else
TTS_SAMPLE_RATE = 24_000 # Gemini 3.1 Flash TTS output rate
TTS_WRITE_BUFFER_MS = 120
_MAX_REPORTED_OUTPUT_LATENCY_S = 5.0
+# Feed-dry stall de-click (live forensic 2026-07-21 08:40: the realtime
+# provider paused audio delivery 1850 ms mid-sentence; the device buffer
+# drained and PortAudio cut the waveform at speech amplitude — audible as a
+# choppy mid-sentence pause with a click/crackle at both edges). The missing
+# audio cannot be conjured locally, but the gap's EDGES can be smoothed:
+# when the chunk feed stays dry longer than FEED_STALL_FADE_S, append a
+# short ramp from the last written sample down to zero, and ramp the first
+# resumed block back in. The timeout must undercut the device-buffer drain
+# (a completed 120 ms write leaves at least ~that much buffered), so the
+# ramp reaches PortAudio before the buffer runs empty; a healthy burst-fed
+# stream never waits this long between chunks.
+FEED_STALL_FADE_S = 0.08
+STALL_EDGE_FADE_MS = 12.0
class _PlaybackSuperseded(RuntimeError):
@@ -142,6 +155,25 @@ def _apply_edge_fades(pcm: bytes, sample_rate: int, fade_ms: int = 5) -> bytes:
return arr.tobytes()
+def _fade_in_pcm16(pcm: bytes, sample_rate: int, fade_ms: float) -> bytes:
+ """Linear fade-in over the first ``fade_ms`` of int16 mono PCM.
+
+ Used when playback resumes after a feed-dry stall: the drained device
+ buffer was padded with OS silence, so the resumed block would otherwise
+ jump from zero to an arbitrary speech amplitude — an audible click at
+ the gap's trailing edge.
+ """
+ if not pcm:
+ return pcm
+ arr = np.frombuffer(pcm, dtype=np.int16).copy()
+ fade_samples = min(arr.size, max(1, int(sample_rate * fade_ms / 1000.0)))
+ ramp = np.linspace(0.0, 1.0, fade_samples, endpoint=False, dtype=np.float32)
+ arr[:fade_samples] = (
+ arr[:fade_samples].astype(np.float32) * ramp
+ ).astype(np.int16)
+ return arr.tobytes()
+
+
def _resample_int16(arr: np.ndarray, src_rate: int, dst_rate: int) -> np.ndarray:
"""Rational resampling of int16 PCM (mono or stereo, N×C array).
@@ -999,9 +1031,11 @@ class AudioPlayer:
pending = bytearray()
pending_rate: int | None = None
first_audio_published = False
+ last_flushed_sample = 0
async def _flush_pending(*, final: bool = False) -> bool:
nonlocal pending, pending_rate, first_audio_published
+ nonlocal last_flushed_sample
if not pending or pending_rate is None:
return True
min_bytes = int(pending_rate * TTS_WRITE_BUFFER_MS / 1000) * 2
@@ -1020,6 +1054,10 @@ class AudioPlayer:
pending.clear()
return False
arr = np.frombuffer(pcm, dtype=np.int16)
+ if arr.size:
+ # Where the written waveform ends — the stall fade-out
+ # ramps down from here when the feed later runs dry.
+ last_flushed_sample = int(arr[-1])
# Tell the UI how long this block will be audible BEFORE the
# blocking write below. _write_samples blocks for the whole
# playback with no further level, so the level tap alone makes
@@ -1062,22 +1100,88 @@ class AudioPlayer:
log.debug("AudioOutFirst publish failed: %s", exc)
return True
+ async def _write_stall_fade_out() -> bool:
+ """De-click a feed-dry gap's leading edge.
+
+ Appends a short ramp from the last written sample down to
+ zero so the OS silence that follows the drained buffer
+ continues the waveform instead of cutting it at speech
+ amplitude. A waveform already ending at zero needs none.
+ """
+ nonlocal pending
+ if pending_rate is None or last_flushed_sample == 0:
+ return True
+ ramp_len = max(
+ 2, int(pending_rate * STALL_EDGE_FADE_MS / 1000.0)
+ )
+ ramp = np.linspace(float(last_flushed_sample), 0.0, ramp_len)
+ pending.extend(ramp.astype(np.int16).tobytes())
+ return await _flush_pending(final=True)
+
# NOTE: no finally-close — the stream stays open across play_chunks
# calls and is only torn down by stop() (barge-in) or by the next
# _ensure_stream call that observes a sample-rate mismatch.
- async for chunk in _from_first():
- if not chunk.pcm:
- continue
- if pending_rate is not None and chunk.sample_rate != pending_rate:
- if not await _flush_pending(final=True):
+ #
+ # Chunks are pulled through a task so the wait can carry a
+ # timeout WITHOUT cancelling the producer: a timeout means the
+ # feed ran dry longer than the device buffer can hide (provider
+ # paused mid-reply — live forensic 2026-07-21 08:40), so the gap
+ # edges get de-clicked; the pull task keeps waiting and delivers
+ # the resumed chunk intact.
+ feed = _from_first().__aiter__()
+ next_pull: asyncio.Task[AudioChunk] | None = None
+ resume_fade_in = False
+ try:
+ while True:
+ if next_pull is None:
+ next_pull = asyncio.ensure_future(feed.__anext__())
+ done, _ = await asyncio.wait(
+ {next_pull},
+ timeout=(
+ None
+ if resume_fade_in or pending_rate is None
+ else FEED_STALL_FADE_S
+ ),
+ )
+ if not done:
+ # Feed-dry stall: get the partial batch audible now
+ # (holding it would lengthen the gap), then ramp the
+ # edge down and wait for the feed to resume.
+ if not await _flush_pending(final=True):
+ return False
+ if not await _write_stall_fade_out():
+ return False
+ resume_fade_in = True
+ continue
+ pull, next_pull = next_pull, None
+ try:
+ chunk = pull.result()
+ except StopAsyncIteration:
+ break
+ if not chunk.pcm:
+ continue
+ if (
+ pending_rate is not None
+ and chunk.sample_rate != pending_rate
+ ):
+ if not await _flush_pending(final=True):
+ return False
+ pending_rate = chunk.sample_rate
+ pcm_in = chunk.pcm
+ if resume_fade_in:
+ pcm_in = _fade_in_pcm16(
+ pcm_in, chunk.sample_rate, STALL_EDGE_FADE_MS
+ )
+ resume_fade_in = False
+ pending.extend(pcm_in)
+ if not await _flush_pending():
return False
- pending_rate = chunk.sample_rate
- pending.extend(chunk.pcm)
- if not await _flush_pending():
+ if not await _flush_pending(final=True):
return False
- if not await _flush_pending(final=True):
- return False
- return self.frames_written > 0
+ return self.frames_written > 0
+ finally:
+ if next_pull is not None:
+ next_pull.cancel()
def abort_active(self) -> None:
"""Force-abort the live OutputStream to unblock a wedged ``stream.write``.
diff --git a/tests/unit/audio/test_player_stall_declick.py b/tests/unit/audio/test_player_stall_declick.py
new file mode 100644
index 0000000000..7bea21b865
--- /dev/null
+++ b/tests/unit/audio/test_player_stall_declick.py
@@ -0,0 +1,140 @@
+"""Feed-dry stall de-click in ``AudioPlayer.play_chunks``.
+
+Live forensic 2026-07-21 08:40 (realtime session 43cb78d0, Gemini Live):
+the provider paused audio delivery 1850 ms mid-sentence. The device buffer
+drained, PortAudio underflowed, and the waveform was cut at speech
+amplitude — audible as a choppy mid-sentence pause with a click/crackle at
+both edges. The missing audio cannot be conjured locally; the fix smooths
+the gap's edges instead: after ``FEED_STALL_FADE_S`` of dry feed the player
+appends a short ramp from the last written sample to zero, and the first
+resumed block is faded back in.
+
+These tests drive ``play_chunks`` with a producer that stalls mid-stream
+and assert on the exact PCM handed to the writer.
+"""
+from __future__ import annotations
+
+import asyncio
+from collections.abc import AsyncIterator
+
+import numpy as np
+import pytest
+
+import jarvis.audio.player as player_module
+from jarvis.audio.player import AudioPlayer
+from jarvis.core.protocols import AudioChunk
+
+
+def _chunk(samples: np.ndarray, sample_rate: int = 24_000) -> AudioChunk:
+ return AudioChunk(
+ pcm=samples.astype(np.int16).tobytes(),
+ sample_rate=sample_rate,
+ timestamp_ns=0,
+ channels=1,
+ )
+
+
+def _make_player(monkeypatch) -> tuple[AudioPlayer, list[np.ndarray]]:
+ """AudioPlayer with stream IO faked; returns the arrays given to write."""
+ player = AudioPlayer.__new__(AudioPlayer)
+ player._device = None
+ player._sample_rate = 24_000
+ player._channels = 1
+ player._device_logged = True
+ player._bus = None
+ player._play_lock = None
+ player._active_stream = None
+ player._active_source_rate = None
+ player._active_device_rate = None
+ player._device_rate_cache = {}
+
+ written: list[np.ndarray] = []
+
+ def fake_open(needed_rate: int):
+ return (object(), needed_rate)
+
+ def fake_write(stream, arr, src_rate, dev_rate, **_kwargs):
+ written.append(np.array(arr, dtype=np.int16))
+
+ monkeypatch.setattr(player, "_open_output_stream", fake_open)
+ monkeypatch.setattr(player, "_close_output_stream", lambda stream: None)
+ monkeypatch.setattr(player, "_write_samples", fake_write)
+ # Fast stall detection so the test does not sleep for real buffer spans.
+ monkeypatch.setattr(player_module, "FEED_STALL_FADE_S", 0.02)
+ return player, written
+
+
+async def test_stall_gap_gets_fade_out_and_fade_in(monkeypatch) -> None:
+ """A mid-stream feed stall must ramp the edge down to zero and ramp the
+ resumed audio back in — never leave the waveform cut at speech amplitude.
+ """
+ player, written = _make_player(monkeypatch)
+ loud = np.full(4_000, 8_000, dtype=np.int16) # ~166 ms, ends loud
+
+ async def stalling_feed() -> AsyncIterator[AudioChunk]:
+ yield _chunk(loud)
+ await asyncio.sleep(0.15) # well past the patched 20 ms stall window
+ yield _chunk(loud)
+
+ await player.play_chunks(stalling_feed())
+
+ assert len(written) == 3, (
+ f"expected [audio, fade-out ramp, resumed audio], got {len(written)}"
+ )
+ ramp = written[1]
+ assert ramp[0] == pytest.approx(8_000, abs=200), (
+ "fade-out must continue from the last written sample"
+ )
+ assert ramp[-1] == 0, "fade-out must end at silence"
+ assert list(np.abs(ramp)) == sorted(np.abs(ramp), reverse=True), (
+ "fade-out must descend monotonically"
+ )
+ resumed = written[2]
+ assert abs(int(resumed[0])) < 300, (
+ "resumed audio must start near silence (fade-in), not at full "
+ f"speech amplitude — first sample was {int(resumed[0])}"
+ )
+ assert resumed[-1] == 8_000, "the fade-in must not touch the block's tail"
+
+
+async def test_continuous_feed_injects_nothing(monkeypatch) -> None:
+ """A healthy back-to-back feed must reach the device byte-identical —
+ no ramps, no inserted silence (the pre-fix contract stays intact).
+ """
+ player, written = _make_player(monkeypatch)
+ tone = np.full(4_000, 5_000, dtype=np.int16)
+
+ async def steady_feed() -> AsyncIterator[AudioChunk]:
+ for _ in range(3):
+ yield _chunk(tone)
+
+ await player.play_chunks(steady_feed())
+
+ joined = np.concatenate(written)
+ assert joined.tobytes() == np.tile(tone, 3).tobytes(), (
+ "continuous playback must remain byte-identical — de-click ramps "
+ "may only appear around a genuine feed-dry stall"
+ )
+
+
+async def test_stall_on_silent_tail_skips_the_ramp(monkeypatch) -> None:
+ """A waveform already ending at zero cannot click — no ramp is written."""
+ player, written = _make_player(monkeypatch)
+ fading = np.linspace(4_000, 0, 4_000).astype(np.int16) # ends at 0
+
+ async def stalling_feed() -> AsyncIterator[AudioChunk]:
+ yield _chunk(fading)
+ await asyncio.sleep(0.15)
+ yield _chunk(np.full(4_000, 5_000, dtype=np.int16))
+
+ await player.play_chunks(stalling_feed())
+
+ assert len(written) == 2, (
+ "no fade-out ramp may be injected when the tail is already silent"
+ )
+ assert abs(int(written[1][0])) < 300, (
+ "the resumed block is still faded in after any stall"
+ )
diff --git a/tests/unit/realtime/test_audio_stall_attribution.py b/tests/unit/realtime/test_audio_stall_attribution.py
new file mode 100644
index 0000000000..0a30f7d066
--- /dev/null
+++ b/tests/unit/realtime/test_audio_stall_attribution.py
@@ -0,0 +1,106 @@
+"""Mid-reply audio-stall attribution: silent provider vs. starved event loop.
+
+The stall diagnostic in ``RealtimeVoiceSession._note_audio_flow`` measures
+the gap between provider audio ARRIVALS — but arrival is when our event
+loop reads the socket. Heavy concurrent work in this process produces the
+identical "provider sent no audio" signature while the audio sits unread
+in the socket buffer (live run 2026-07-21 08:40: a 54 s wiki-consolidator
+Codex turn finished right as a 1850 ms stall began). The ``_LoopLagProbe``
+separates the two so the log names the actual producer.
+"""
+from __future__ import annotations
+
+import asyncio
+import logging
+import time
+
+import pytest
+
+from jarvis.realtime.session import (
+ RealtimeVoiceSession,
+ _LoopLagProbe,
+)
+
+
+class _IdleGate:
+ last_hold_ms = 0.0
+ pending_audio_ms = 0.0
+
+
+def _bare_session(loop_lag_ms: float) -> RealtimeVoiceSession:
+ """Session skeleton carrying only the fields _note_audio_flow reads."""
+ session = RealtimeVoiceSession.__new__(RealtimeVoiceSession)
+ session.session_id = "test-session"
+ session._turn_id = "turn-1"
+ session._last_audio_emit_turn = "turn-1"
+ session._output_samples_sent = 1
+ session._last_audio_emit_monotonic = time.monotonic() - 1.85
+ session._embedded_silence_ms = 0.0
+ session._gate = _IdleGate()
+
+ class _FixedProbe:
+ def max_lag_ms(self, window_s: float) -> float:
+ return loop_lag_ms
+
+ session._loop_lag = _FixedProbe()
+ return session
+
+
+def _stall_line(caplog) -> str:
+ lines = [
+ record.getMessage()
+ for record in caplog.records
+ if "mid-reply audio stalled" in record.getMessage()
+ ]
+ assert lines, "a 1850 ms arrival gap must emit the stall diagnostic"
+ return lines[0]
+
+
+def test_responsive_loop_blames_the_provider(caplog) -> None:
+ session = _bare_session(loop_lag_ms=12.0)
+ with caplog.at_level(logging.INFO, logger="jarvis.realtime.session"):
+ session._note_audio_flow(b"\x00\x10" * 480, _FakeChunk())
+ assert "the provider sent no audio" in _stall_line(caplog)
+
+
+def test_starved_loop_is_named_instead_of_the_provider(caplog) -> None:
+ session = _bare_session(loop_lag_ms=1_700.0)
+ with caplog.at_level(logging.INFO, logger="jarvis.realtime.session"):
+ session._note_audio_flow(b"\x00\x10" * 480, _FakeChunk())
+ line = _stall_line(caplog)
+ assert "event loop stalled" in line
+ assert "provider sent no audio" not in line
+
+
+class _FakeChunk:
+ sample_rate = 24_000
+
+
+async def test_loop_lag_probe_measures_a_blocked_loop() -> None:
+ probe = _LoopLagProbe()
+ probe.start()
+ try:
+ # Let the probe take at least one clean sample, then block the loop.
+ # The worst-phase measurable lag is block − interval (a sample can
+ # become due right at the block's start), so a 0.7 s block yields at
+ # least ~450 ms of recorded lag against the 0.25 s interval.
+ await asyncio.sleep(0.3)
+ # A synchronous sleep is the point of this test: it blocks the loop
+ # so the probe's own sleep cannot be serviced.
+ time.sleep(0.7) # noqa: ASYNC251
+ await asyncio.sleep(0.3) # one post-block sample records the lag
+ assert probe.max_lag_ms(window_s=5.0) >= 300.0
+ finally:
+ probe.stop()
+
+
+async def test_loop_lag_probe_stays_quiet_on_a_healthy_loop() -> None:
+ probe = _LoopLagProbe()
+ probe.start()
+ try:
+ await asyncio.sleep(0.6)
+ assert probe.max_lag_ms(window_s=5.0) < 200.0
+ finally:
+ probe.stop()