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.
Python agent-orchestrationai-agentai-coding-assistantclaude-codecoding-agentcomputer-usedesktop-applocal-firstmcppersonal-jarvisvoice-assistantvoice-coding
perf: reduce voice capture buffering latency
Ruben Lütkec3b77044b78e
diff --git a/jarvis/audio/capture.py b/jarvis/audio/capture.pyindex a34b2f3302..d1c2361413 100644--- a/jarvis/audio/capture.py+++ b/jarvis/audio/capture.py@@ -12,6 +12,7 @@ and performs a stateful CPU resample before yielding each chunk.from __future__ import annotationsimport asyncio+import mathimport sysimport timefrom collections.abc import AsyncIterator, Callable, Iterator, Sequence@@ -36,9 +37,26 @@ from jarvis.core.protocols import AudioChunkSAMPLE_RATE = 16_000 # Whisper native rateCHANNELS = 1 # Mono is sufficient for speech-BLOCKSIZE = 1600 # 100 ms blocks — compromise between latency and CPU overhead+# One native Silero frame. The previous 1,600-frame / 100 ms callback made+# every capture consumer wait up to 100 ms before it could see speech, silence,+# or a barge-in edge; the VAD split that block back into 512-frame pieces anyway.+# Delivering the model's native 32 ms unit removes that fixed batching delay+# without increasing inference work or changing the PCM presented downstream.+BLOCKSIZE = 512DTYPE = "int16"+CAPTURE_BLOCK_DURATION_S = BLOCKSIZE / SAMPLE_RATE+++def capture_chunks_for_duration(seconds: float) -> int:+ """Return the default-size chunk count covering at least ``seconds``."""+ return max(1, math.ceil(max(0.0, float(seconds)) / CAPTURE_BLOCK_DURATION_S))+++# Preserve the old bulk-queue duration after reducing the callback block size.+# Queue bounds are time budgets, not magic chunk counts.+DEFAULT_QUEUE_CHUNKS = capture_chunks_for_duration(2.0)+class MicrophoneAccessError(PermissionError):"""The current process is not allowed to open the local microphone."""@@ -79,7 +97,7 @@ def _macos_microphone_access_gate() -> Callable[[], bool] | None:# 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+REALTIME_QUEUE_CHUNKS = capture_chunks_for_duration(0.6)# Input NAMES we never open as a microphone: playback/loopback/monitor sources# (opening one feeds constant hiss or TTS echo into the wake path) and GPU-HDMI@@ -654,7 +672,7 @@ class MicrophoneCapture:sample_rate: int = SAMPLE_RATE,blocksize: int = BLOCKSIZE,channels: int = CHANNELS,- max_queue_chunks: int = 20,+ max_queue_chunks: int = DEFAULT_QUEUE_CHUNKS,device_priority: Sequence[str] | None = None,access_gate: Callable[[], bool] | None = None,) -> None:@@ -699,8 +717,9 @@ class MicrophoneCapture:# 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-+ # ``max_queue_chunks`` blocks, so worst-case staleness is the queue+ # depth times the configured block duration. The default stays at ~2 s+ # after the low-latency 32 ms block change and 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-speechdiff --git a/jarvis/speech/pipeline.py b/jarvis/speech/pipeline.pyindex aab286516e..e66e1f7380 100644--- a/jarvis/speech/pipeline.py+++ b/jarvis/speech/pipeline.py@@ -34,6 +34,7 @@ from jarvis.audio import level_tap, mic_levelfrom jarvis.audio.capture import (REALTIME_QUEUE_CHUNKS,MicrophoneCapture,+ capture_chunks_for_duration,pcm_bytes_to_np,)from jarvis.audio.chime import CHIME_PCM, CHIME_SAMPLE_RATE, DISCONNECT_PCM, READY_PCM@@ -979,8 +980,9 @@ _DICTATION_ERROR_BACKOFF_MAX_S = 12.0# drops the OLDEST chunk when it overflows — correct for wake/VAD, where stale# audio is worse than missing audio, and exactly wrong here: for a dictation# every frame is the user's words. ~10 s of slack absorbs a provider stall-# without deleting speech (the default 20 chunks is 2 s).-_DICTATION_CAPTURE_QUEUE_CHUNKS = 100+# without deleting speech. Express it as time so capture-block tuning never+# silently shrinks the safety margin.+_DICTATION_CAPTURE_QUEUE_CHUNKS = capture_chunks_for_duration(10.0)class _SessionInputBuffer:@@ -6378,8 +6380,14 @@ class SpeechPipeline:async def _run_parallel_wake(self) -> None:"""Fan one wake microphone into all detectors until the first hit."""- oww_queue: asyncio.Queue = asyncio.Queue(maxsize=50)- whisper_queue: asyncio.Queue = asyncio.Queue(maxsize=100)+ # Detector backlogs are latency budgets, not arbitrary chunk counts.+ # Keep OWW within ~0.6 s and the slower Whisper consumer within ~1.2 s;+ # both queues drop oldest on overflow, so an overloaded host evaluates+ # recent audio instead of a wake word heard several seconds ago.+ oww_queue: asyncio.Queue = asyncio.Queue(maxsize=REALTIME_QUEUE_CHUNKS)+ whisper_queue: asyncio.Queue = asyncio.Queue(+ maxsize=REALTIME_QUEUE_CHUNKS * 2+ )detector_queues = [oww_queue] if self._openwakeword_enabled else []if self._whisper_wake_enabled and self._whisper_wake is not None:detector_queues.append(whisper_queue)@@ -6395,7 +6403,9 @@ class SpeechPipeline:# needs to re-arm fanout.ring_bytes = bytearray()RING_MAX = 16_000 * 2 * 3 # ~3 s- recent_chunks: deque[AudioChunk] = deque(maxlen=2) # ~200 ms overlap+ recent_chunks: deque[AudioChunk] = deque(+ maxlen=capture_chunks_for_duration(0.2)+ ) # ~200 ms overlapwake_confirmed = Falsehandoff_buffer: _SessionInputBuffer | None = None@@ -6483,7 +6493,7 @@ class SpeechPipeline:async def _run_oww() -> str:# Capability-gated catch-up: a detector that can consume variable- # chunk sizes (vosk_kws) advertises how many backlogged 100 ms+ # chunk sizes (vosk_kws) advertises how many backlogged capture# blocks may be coalesced into one catch-up batch, so a busy CPU# never leaves it grinding through seconds-stale audio (the# inconsistent multi-second wake delay, live 2026-07-21).diff --git a/tests/unit/audio/test_capture_native_rate.py b/tests/unit/audio/test_capture_native_rate.pyindex 1ef4308d9d..55876f2fc5 100644--- a/tests/unit/audio/test_capture_native_rate.py+++ b/tests/unit/audio/test_capture_native_rate.py@@ -48,20 +48,21 @@ async def test_native_rate_fallback_resamples_to_16khz_contract(await mic._try_open_stream()assert [call["samplerate"] for call in open_calls] == [16_000, native_rate]- assert open_calls[-1]["blocksize"] == native_rate // 10+ expected_native_block = round(capture.BLOCKSIZE * native_rate / capture.SAMPLE_RATE)+ assert open_calls[-1]["blocksize"] == expected_native_blockassert mic._capture_sample_rate == native_rateassert mic._capture_resampler is not None- # One 100 ms native-rate callback must remain one approximately 100 ms+ # One low-latency native-rate callback must remain one approximately 32 ms# downstream chunk while advertising the unchanged 16 kHz contract.- native_frames = np.arange(native_rate // 10, dtype="<i2").reshape(-1, 1)+ native_frames = np.arange(expected_native_block, dtype="<i2").reshape(-1, 1)mic._callback(native_frames, native_frames.shape[0], None, None)await asyncio.sleep(0)chunk = mic._queue.get_nowait()assert chunk.sample_rate == 16_000assert chunk.channels == 1- assert len(chunk.pcm) // 2 == 1_600+ assert len(chunk.pcm) // 2 == pytest.approx(capture.BLOCKSIZE, abs=1)@pytest.mark.asynciodiff --git a/tests/unit/audio/test_capture_overflow.py b/tests/unit/audio/test_capture_overflow.pyindex 6a9b0ea037..ba841d1750 100644--- a/tests/unit/audio/test_capture_overflow.py+++ b/tests/unit/audio/test_capture_overflow.py@@ -9,7 +9,13 @@ 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.audio.capture import (+ BLOCKSIZE,+ DEFAULT_QUEUE_CHUNKS,+ REALTIME_QUEUE_CHUNKS,+ SAMPLE_RATE,+ MicrophoneCapture,+)from jarvis.core.protocols import AudioChunk@@ -23,12 +29,19 @@ def _chunk(tag: int) -> AudioChunk:def test_realtime_depth_is_shallower_than_the_bulk_default() -> None:- assert MicrophoneCapture()._queue.maxsize == 20+ assert MicrophoneCapture()._queue.maxsize == DEFAULT_QUEUE_CHUNKSassert (MicrophoneCapture(max_queue_chunks=REALTIME_QUEUE_CHUNKS)._queue.maxsize== REALTIME_QUEUE_CHUNKS)- assert 1 <= REALTIME_QUEUE_CHUNKS < 20+ assert 1 <= REALTIME_QUEUE_CHUNKS < DEFAULT_QUEUE_CHUNKS+ assert DEFAULT_QUEUE_CHUNKS * BLOCKSIZE / SAMPLE_RATE >= 2.0+ assert REALTIME_QUEUE_CHUNKS * BLOCKSIZE / SAMPLE_RATE >= 0.6+++def test_capture_block_matches_the_native_vad_frame_budget() -> None:+ assert BLOCKSIZE == 512+ assert BLOCKSIZE / SAMPLE_RATE == 0.032def test_safe_put_drops_oldest_and_keeps_newest_on_overflow() -> None: