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): end-of-speech survives dropped/lagged frames on weaker hardware

Ruben Lütke6a4f0b08fa92
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.py
index b8574816ef..64d1271cc1 100644
--- a/jarvis/audio/capture.py
+++ b/jarvis/audio/capture.py
@@ -34,6 +34,15 @@ CHANNELS = 1 # Mono is sufficient for speech
BLOCKSIZE = 1600 # 100 ms blocks — compromise between latency and CPU overhead
DTYPE = "int16"
+# Queue depth for a REAL-TIME detection consumer (VAD endpointing, wake, barge).
+# ~0.6 s: shallow enough that on a CPU which can't process every frame in real
+# time the drop-OLDEST overflow policy keeps the audio near-present (so
+# end-of-speech silence and the wake word are seen promptly, not seconds late),
+# yet deep enough to absorb normal scheduling jitter on a machine that keeps up
+# (which never fills it). Bulk recorders that must keep every frame
+# (push-to-talk, dictation) use the deeper default instead. See MicrophoneCapture.
+REALTIME_QUEUE_CHUNKS = 6
+
_BLOCKED_INPUT_SUBSTRINGS = (
"Stereo Mix",
"What U Hear",
@@ -270,14 +279,26 @@ class MicrophoneCapture:
sample_rate: int = SAMPLE_RATE,
blocksize: int = BLOCKSIZE,
channels: int = CHANNELS,
+ max_queue_chunks: int = 20,
) -> None:
self._device = _resolve_input_device(device)
self._sample_rate = sample_rate
self._blocksize = blocksize
self._channels = channels
- # Queue bridges PortAudio thread → asyncio. maxsize limits back-pressure
- # to ~2 seconds of audio (20 blocks of 100 ms each) before frames are dropped.
- self._queue: asyncio.Queue[AudioChunk] = asyncio.Queue(maxsize=20)
+ # Queue bridges PortAudio thread → asyncio. maxsize bounds how STALE the
+ # audio a consumer sees may get: with the drop-OLDEST policy in
+ # ``_safe_put`` a full queue always holds the most-recent
+ # ``max_queue_chunks`` blocks, so worst-case staleness ==
+ # max_queue_chunks x 100 ms. The default 20 (~2 s) is generous back-
+ # pressure for a bulk consumer (push-to-talk, which records every frame).
+ # A REAL-TIME detection consumer (VAD endpointing, wake) passes a SHALLOW
+ # depth (~0.6 s) so that on a CPU that can't keep up the end-of-speech
+ # silence and the wake word are seen near-present, not 2 s late — the
+ # "stuck listening / missed wake on a weaker laptop" bug. A machine that
+ # keeps up never fills the queue, so the depth is invisible there.
+ self._queue: asyncio.Queue[AudioChunk] = asyncio.Queue(
+ maxsize=max(1, int(max_queue_chunks))
+ )
self._stream: sd.InputStream | None = None
self._loop: asyncio.AbstractEventLoop | None = None
self._drops = 0
@@ -315,7 +336,7 @@ class MicrophoneCapture:
self._drops += 1
def _safe_put(self, chunk: AudioChunk) -> None:
- """Runs in the event loop — safe put with drop-on-full."""
+ """Runs in the event loop — safe put with drop-OLDEST on full."""
# Heartbeat update for the stall watchdog. Even if the queue is full,
# the stream is considered alive — we update the timestamp before the
# put; otherwise drops would corrupt the stall signal.
@@ -323,6 +344,24 @@ class MicrophoneCapture:
try:
self._queue.put_nowait(chunk)
except asyncio.QueueFull:
+ # A consumer that cannot keep up in real time (a weaker CPU running
+ # the per-frame VAD / wake inference) backs the queue up. Drop the
+ # OLDEST chunk and enqueue the newest so the consumer always processes
+ # near-PRESENT audio (staleness bounded to the queue depth) instead of
+ # a growing stale backlog — the wake detector then scores fresh frames
+ # and the VAD sees the current end-of-speech silence promptly, not a
+ # 2 s-old snapshot. Mirrors the wake fanout's existing drop-oldest
+ # policy (``_run_parallel_wake``). Still counted as a drop; the VAD's
+ # timestamp gap-credit accounts for the dropped time so end-of-speech
+ # stays anchored to real wall-clock, not delivered-frame count.
+ try:
+ self._queue.get_nowait()
+ except asyncio.QueueEmpty:
+ pass
+ try:
+ self._queue.put_nowait(chunk)
+ except asyncio.QueueFull:
+ pass
self._drops += 1
async def _try_open_stream(self) -> None:
diff --git a/jarvis/audio/vad.py b/jarvis/audio/vad.py
index 146df7a160..01e321bb2b 100644
--- a/jarvis/audio/vad.py
+++ b/jarvis/audio/vad.py
@@ -305,8 +305,40 @@ class SileroEndpointer:
# ``silence`` so the consumer flushes its carry.
tail_pending = False
tail_silent_run = 0
+ # Wall-clock anchor for the silence timer (real-time gap credit). The
+ # endpoint decision counts silent FRAMES and treats each as 32 ms of
+ # elapsed time — which silently assumes frames arrive in lockstep with
+ # real time. On hardware that cannot consume the mic stream in real time
+ # the capture queue overflows and whole chunks are DROPPED (and delivery
+ # lags), so the frame count runs slow or stalls and the turn ends far too
+ # late or never (the "stuck listening / never advances" bug on weaker
+ # laptops). The surviving chunks still carry the true capture wall-clock
+ # in ``timestamp_ns``; ``prev_chunk_ts`` lets us detect a jump larger than
+ # a chunk's own audio duration (= dropped/lagged time) and credit it to
+ # the silence timer below, so end-of-speech stays anchored to real time,
+ # not to how many frames happened to survive.
+ prev_chunk_ts: int = 0
async for chunk in chunks:
+ # Real-time gap in frames: how much silent time to credit if this
+ # chunk arrives after a capture drop/lag. Inert (<= 0) when timestamps
+ # are absent / unrealistic (tests use tiny counters) or contiguous (a
+ # machine that keeps up), and capped so one huge gap cannot overshoot
+ # the window. Applied only inside an active end-of-speech silence run
+ # (see the silence branch), never to speech or a fresh utterance.
+ gap_frames = 0
+ ts = int(getattr(chunk, "timestamp_ns", 0) or 0)
+ n_samples = len(chunk.pcm) // 2 # int16 mono
+ nominal_ms = (n_samples / VAD_SAMPLE_RATE * 1000.0) if n_samples else 0.0
+ if prev_chunk_ts and ts > prev_chunk_ts and nominal_ms > 0.0:
+ missing_ms = (ts - prev_chunk_ts) / 1e6 - nominal_ms
+ if missing_ms >= 16.0: # at least ~half a VAD frame went missing
+ gap_frames = min(
+ int(missing_ms // 32), self._effective_silence_frames
+ )
+ prev_chunk_ts = ts
+ pending_gap_frames = gap_frames
+
samples = pcm_bytes_to_np(chunk.pcm)
buf = np.concatenate([residual, samples])
@@ -375,6 +407,10 @@ class SileroEndpointer:
active_frames.append(frame)
total_frames += 1
if is_speech:
+ # Speech resumed inside this chunk — a capture gap here
+ # was (at least partly) real speech, so do NOT credit it
+ # as silence. Drop the pending credit.
+ pending_gap_frames = 0
speech_frames += 1
# Probe-independent patience: a long active-speech run is
# a long dictation — widen the natural silence window so a
@@ -418,6 +454,17 @@ class SileroEndpointer:
peak_speech_rms,
)
silent_run += 1
+ # Real-time gap credit: this chunk arrived after a capture
+ # drop/lag and its frames are silence, so the missing time
+ # was almost certainly more end-of-speech silence. Credit
+ # it ONCE (on the first silent frame of the chunk) so the
+ # silence timer tracks real wall-clock instead of stalling
+ # on the frames a slow machine failed to deliver — the fix
+ # for "the turn never ends on a weaker laptop". Capped at
+ # construction; harmless (0) on a machine that keeps up.
+ if pending_gap_frames:
+ silent_run += pending_gap_frames
+ pending_gap_frames = 0
# Probe hook: hand only the *tail* of the active buffer
# (last `probe_tail_frames`) to the external stability
diff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.py
index 2e24b0d635..049682dd97 100644
--- a/jarvis/speech/pipeline.py
+++ b/jarvis/speech/pipeline.py
@@ -32,7 +32,11 @@ from uuid import uuid4
import numpy as np
from jarvis.audio import mic_level
-from jarvis.audio.capture import MicrophoneCapture, pcm_bytes_to_np
+from jarvis.audio.capture import (
+ REALTIME_QUEUE_CHUNKS,
+ MicrophoneCapture,
+ pcm_bytes_to_np,
+)
from jarvis.audio.chime import CHIME_PCM, CHIME_SAMPLE_RATE, DISCONNECT_PCM, READY_PCM
from jarvis.audio.device_init import wait_for_stable_audio_devices
from jarvis.audio.player import AudioPlayer
@@ -4317,6 +4321,15 @@ class SpeechPipeline:
return f"whisper:{kw}"
return ""
+ # NOTE: the wake mic keeps the DEEP default queue on purpose. Its
+ # detectors offload inference (openWakeWord ``to_thread``; whisper-wake
+ # ``await transcribe_pcm``), so the event loop stays free and the cheap
+ # ``_fanout`` drains this queue near-instantly — it never fills, so a
+ # shallow depth would be inert here anyway. The wake path's real staleness
+ # lever is the per-detector queues below (``oww_queue`` / ``whisper_queue``),
+ # which belong to the wake layer; this change deliberately does not touch
+ # them. The drop-OLDEST overflow policy (capture ``_safe_put``) still
+ # applies and is safe here.
async with MicrophoneCapture(device=self._input_device) as mic:
fanout_task = asyncio.create_task(_fanout(mic), name="fanout")
oww_task = (
@@ -4644,7 +4657,9 @@ class SpeechPipeline:
self._last_answer_floor_monotonic = None
if self._ptt_mode:
return await self._ptt_session()
- async with MicrophoneCapture(device=self._input_device) as mic:
+ async with MicrophoneCapture(
+ device=self._input_device, max_queue_chunks=REALTIME_QUEUE_CHUNKS
+ ) as mic:
vad_iter = self._vad.utterances(
self._session_input_stream(mic.stream())
).__aiter__()
@@ -7904,7 +7919,9 @@ class SpeechPipeline:
detector._ensure_model()
try:
- async with MicrophoneCapture(device=self._input_device) as mic:
+ async with MicrophoneCapture(
+ device=self._input_device, max_queue_chunks=REALTIME_QUEUE_CHUNKS
+ ) as mic:
residual = np.empty(0, dtype=np.float32)
speech_run = 0
async for chunk in mic.stream():
diff --git a/tests/unit/audio/test_capture_overflow.py b/tests/unit/audio/test_capture_overflow.py
new file mode 100644
index 0000000000..6a9b0ea037
--- /dev/null
+++ b/tests/unit/audio/test_capture_overflow.py
@@ -0,0 +1,53 @@
+"""Capture queue overflow keeps the FRESHEST audio (drop-oldest).
+
+Regression for the weak-laptop root cause: a consumer that cannot run the inline
+per-frame VAD inference in real time backs the capture queue up. The old policy
+dropped the NEWEST chunk, so the consumer processed a growing STALE backlog and
+saw the current end-of-speech silence (and the wake word) seconds late. The queue
+now drops the OLDEST chunk, bounding staleness to the queue depth, and a
+real-time detection consumer uses a shallow depth so the bound is small.
+"""
+from __future__ import annotations
+
+from jarvis.audio.capture import REALTIME_QUEUE_CHUNKS, MicrophoneCapture
+from jarvis.core.protocols import AudioChunk
+
+
+def _chunk(tag: int) -> AudioChunk:
+ return AudioChunk(
+ pcm=bytes([tag & 0xFF]) * 4,
+ sample_rate=16_000,
+ timestamp_ns=tag,
+ channels=1,
+ )
+
+
+def test_realtime_depth_is_shallower_than_the_bulk_default() -> None:
+ assert MicrophoneCapture()._queue.maxsize == 20
+ assert (
+ MicrophoneCapture(max_queue_chunks=REALTIME_QUEUE_CHUNKS)._queue.maxsize
+ == REALTIME_QUEUE_CHUNKS
+ )
+ assert 1 <= REALTIME_QUEUE_CHUNKS < 20
+
+
+def test_safe_put_drops_oldest_and_keeps_newest_on_overflow() -> None:
+ mic = MicrophoneCapture(max_queue_chunks=3)
+ for tag in (1, 2, 3):
+ mic._safe_put(_chunk(tag)) # fill to capacity
+ mic._safe_put(_chunk(4)) # overflow → drop the oldest (1), keep newest
+
+ drained = []
+ while not mic._queue.empty():
+ drained.append(mic._queue.get_nowait().timestamp_ns)
+
+ assert drained == [2, 3, 4], drained # oldest (1) dropped, present preserved
+ assert mic.dropped_frames == 1
+
+
+def test_safe_put_no_drop_when_not_full() -> None:
+ mic = MicrophoneCapture(max_queue_chunks=8)
+ for tag in range(5):
+ mic._safe_put(_chunk(tag))
+ assert mic.dropped_frames == 0
+ assert mic._queue.qsize() == 5
diff --git a/tests/unit/audio/test_vad_realtime_gap_credit.py b/tests/unit/audio/test_vad_realtime_gap_credit.py
new file mode 100644
index 0000000000..8c9fae8d41
--- /dev/null
+++ b/tests/unit/audio/test_vad_realtime_gap_credit.py
@@ -0,0 +1,107 @@
+"""End-of-speech must survive dropped/lagged frames on a slow machine.
+
+Regression for the "stuck listening / the turn never ends on a weaker laptop"
+bug: the VAD silence timer counted delivered 32 ms frames and treated each as
+32 ms of elapsed time. On hardware that cannot run the inline per-frame VAD
+inference in real time the capture queue overflows and whole chunks are DROPPED,
+so the frame count runs slow or stalls and the turn ends far too late or never.
+
+The surviving chunks still carry the true capture wall-clock in ``timestamp_ns``;
+``SileroEndpointer.utterances`` now credits a real-time gap to the silence timer
+during an active end-of-speech silence. These tests pin (1) that a turn ends when
+real silence exceeds the window even though most silent frames were dropped, and
+(2) that the credit is INERT on a contiguous stream (never shortens a normal
+turn).
+"""
+from __future__ import annotations
+
+from collections.abc import AsyncIterator
+
+import numpy as np
+import pytest
+
+from jarvis.audio.vad import VAD_FRAME_SAMPLES, SileroEndpointer
+from jarvis.audio.vad_reasons import VAD_REASON_SILENCE
+from jarvis.core.protocols import AudioChunk
+
+
+def _pcm_frame(amplitude: float) -> bytes:
+ samples = np.full(VAD_FRAME_SAMPLES, amplitude, dtype=np.float32)
+ return (np.clip(samples, -1.0, 1.0) * 32767.0).astype(np.int16).tobytes()
+
+
+def _stub_vad(vad: SileroEndpointer, probs: list[float]) -> None:
+ vad._ensure_model = lambda: None # type: ignore[method-assign]
+ iterator = iter(probs)
+ vad._prob = lambda _frame: next(iterator, 0.0) # type: ignore[method-assign]
+
+
+async def _chunks(
+ frames: list[bytes], timestamps_ms: list[float]
+) -> AsyncIterator[AudioChunk]:
+ for pcm, ts_ms in zip(frames, timestamps_ms, strict=True):
+ yield AudioChunk(
+ pcm=pcm,
+ sample_rate=16_000,
+ timestamp_ns=int(ts_ms * 1e6),
+ channels=1,
+ )
+
+
+async def _collect(
+ vad: SileroEndpointer, frames: list[bytes], timestamps_ms: list[float]
+) -> list[bytes]:
+ out: list[bytes] = []
+ async for utterance in vad.utterances(_chunks(frames, timestamps_ms)):
+ out.append(utterance)
+ return out
+
+
+async def test_dropped_silence_frames_still_end_turn_via_gap_credit() -> None:
+ reasons: list[str] = []
+ vad = SileroEndpointer(
+ silence_ms=320, # window == 10 silent frames
+ min_speech_ms=96,
+ min_speech_rms=0.002,
+ on_endpoint=lambda reason: reasons.append(reason),
+ )
+ # 5 contiguous speech frames, then only THREE silent frames delivered — but
+ # each lands 200 ms after the previous, i.e. ~5 silent frames were dropped in
+ # the capture-queue overflow between every delivered one. By delivered-frame
+ # COUNT that is 3 < 10, so a purely count-based timer would never endpoint;
+ # the timestamps show ~560 ms of real silence, so the turn must end.
+ probs = [0.9] * 5 + [0.0] * 3
+ _stub_vad(vad, probs)
+ frames = [_pcm_frame(0.08)] * 5 + [_pcm_frame(0.0004)] * 3
+ ts_ms = [0.0, 32.0, 64.0, 96.0, 128.0] # contiguous speech
+ ts_ms += [160.0, 360.0, 560.0] # silent frames 200 ms apart (drops between)
+
+ utterances = await _collect(vad, frames, ts_ms)
+
+ assert utterances, "the turn never ended despite ~560 ms of real silence"
+ assert reasons[-1] == VAD_REASON_SILENCE, reasons
+
+
+async def test_gap_credit_is_inert_on_a_contiguous_stream() -> None:
+ """A machine that keeps up delivers 32 ms-spaced frames with no gap, so the
+ credit is 0 and the silence timer still requires the FULL window — gap credit
+ must never shorten a normal turn. Nine contiguous silent frames stay below the
+ 10-frame (320 ms) window, so no endpoint fires."""
+ reasons: list[str] = []
+ vad = SileroEndpointer(
+ silence_ms=320,
+ min_speech_ms=96,
+ min_speech_rms=0.002,
+ on_endpoint=lambda reason: reasons.append(reason),
+ )
+ probs = [0.9] * 5 + [0.0] * 9
+ _stub_vad(vad, probs)
+ frames = [_pcm_frame(0.08)] * 5 + [_pcm_frame(0.0004)] * 9
+ ts_ms = [i * 32.0 for i in range(len(frames))] # perfectly contiguous
+
+ utterances = await _collect(vad, frames, ts_ms)
+
+ assert utterances == [], "gap credit shortened a normal, contiguous turn"
+ assert reasons == [], reasons
diff --git a/tests/unit/speech/test_idle_keeps_session_during_cu.py b/tests/unit/speech/test_idle_keeps_session_during_cu.py
index c48763e614..bfa8c6f873 100644
--- a/tests/unit/speech/test_idle_keeps_session_during_cu.py
+++ b/tests/unit/speech/test_idle_keeps_session_during_cu.py
@@ -137,7 +137,7 @@ async def test_active_session_survives_idle_windows_while_cu_runs(
return gen()
monkeypatch.setattr(
- pipeline_mod, "MicrophoneCapture", lambda device=None: FakeMic(),
+ pipeline_mod, "MicrophoneCapture", lambda device=None, **kwargs: FakeMic(),
)
pipe._vad = FakeVAD()
@@ -227,7 +227,7 @@ async def test_session_survives_idle_window_after_mission_readback(
return gen()
monkeypatch.setattr(
- pipeline_mod, "MicrophoneCapture", lambda device=None: FakeMic(),
+ pipeline_mod, "MicrophoneCapture", lambda device=None, **kwargs: FakeMic(),
)
pipe._vad = FakeVAD()
diff --git a/tests/unit/speech/test_idle_spawn_inflight.py b/tests/unit/speech/test_idle_spawn_inflight.py
index 5060fd0628..8a593a6152 100644
--- a/tests/unit/speech/test_idle_spawn_inflight.py
+++ b/tests/unit/speech/test_idle_spawn_inflight.py
@@ -96,7 +96,7 @@ async def test_idle_timeout_extended_while_background_mission_in_flight(
pipe._spawn_watchdog_tasks = [watchdog]
monkeypatch.setattr(
- pipeline_mod, "MicrophoneCapture", lambda device=None: _FakeMic()
+ pipeline_mod, "MicrophoneCapture", lambda device=None, **kwargs: _FakeMic()
)
task = asyncio.create_task(pipe._active_session())
@@ -130,7 +130,7 @@ async def test_idle_timeout_still_hangs_up_without_inflight_mission(
pipe = _make_active_session_pipeline(idle_timeout_s=0.02)
monkeypatch.setattr(
- pipeline_mod, "MicrophoneCapture", lambda device=None: _FakeMic()
+ pipeline_mod, "MicrophoneCapture", lambda device=None, **kwargs: _FakeMic()
)
reason = await asyncio.wait_for(pipe._active_session(), timeout=2.0)
diff --git a/tests/unit/speech/test_idle_timeout_disabled.py b/tests/unit/speech/test_idle_timeout_disabled.py
index 33f92b07fe..56136f3863 100644
--- a/tests/unit/speech/test_idle_timeout_disabled.py
+++ b/tests/unit/speech/test_idle_timeout_disabled.py
@@ -109,7 +109,7 @@ async def test_active_session_never_idle_hangs_up_when_disabled(
fired immediately and returned ``HANGUP_IDLE_TIMEOUT``."""
pipe = _pipeline(0)
monkeypatch.setattr(
- pipeline_mod, "MicrophoneCapture", lambda device=None: _FakeMic(),
+ pipeline_mod, "MicrophoneCapture", lambda device=None, **kwargs: _FakeMic(),
)
pipe._vad = _FakeVAD()
@@ -135,7 +135,7 @@ async def test_active_session_still_idle_hangs_up_when_enabled(
the default behaviour (and every downloader) is unchanged."""
pipe = _pipeline(0.05) # tiny positive window → fast test
monkeypatch.setattr(
- pipeline_mod, "MicrophoneCapture", lambda device=None: _FakeMic(),
+ pipeline_mod, "MicrophoneCapture", lambda device=None, **kwargs: _FakeMic(),
)
pipe._vad = _FakeVAD()