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): make level indicators follow voice loudness

Ruben Lütkecf5e023fd1cc
diff --git a/docs/BUGS.md b/docs/BUGS.md
index 4f9123d377..61fc8fa055 100644
--- a/docs/BUGS.md
+++ b/docs/BUGS.md
@@ -6837,3 +6837,46 @@ Tool Model API credential.
auth/billing/quota failure retires its explicit credential family for that call
before recovery chooses another candidate; a UI health probe must never be
mistaken for evidence that the active voice transport died.
+
+---
+
+## BUG-099: Jarvis Bar barely reacts to loud speech and sometimes jumps on soft input (MEDIUM, FIXED IN CODE 2026-07-20; HARDWARE VALIDATION PENDING)
+
+**Symptom (desktop field report).** During an active voice session, the gold
+equalizer strokes can remain only slightly taller than their resting height
+even while the user speaks very loudly. At other times a much softer sound
+produces a disproportionately large swing. The field screenshot supplied with
+the report shows the loud-speech case: all strokes remain near minimum height.
+
+**Root cause.** The shared `LevelNormalizer` divided each noise-gated RMS frame
+by an adaptive peak. Any sample above the prior peak immediately became both
+the new numerator and denominator, so even a soft sound could redefine itself
+as `1.0`. Conversely, one click, clipped frame, or other transient could raise
+the denominator by an order of magnitude. Its `0.997` per-frame decay then
+held ordinary speech near the bottom of the meter for seconds. A reproduced
+sequence of one `0.5` RMS transient followed by `0.05` RMS speech still read
+about `0.10` after 30 speech frames. The renderer's additional easing correctly
+smoothed that faulty input; it was not the source of the inversion.
+
+**Fix.** The adaptive quiet-frame noise gate remains, but samples above it now
+map through a fixed logarithmic visual range of approximately -72 dBFS to
+-12 dBFS. A gentle response curve preserves useful movement on quiet laptop
+microphones while retaining a clear ordering between soft, normal, and loud
+speech. Fast attack and slower release still prevent flicker. The same mapping
+now drives the native microphone channel, TTS output, the standalone mascot
+listener, and browser-owned realtime capture, so no surface keeps the faulty
+peak behavior.
+
+**Guards and platform parity.** Regression tests require soft input to remain
+below full scale, normal and loud speech to occupy successively higher bands,
+and ordinary speech to recover within six frames after a clipped impulse. The
+Python mapper feeds the Windows and Linux Tk bar directly and crosses the
+existing companion IPC to the macOS Qt bar. The TypeScript port covers browser
+capture on remote and headless installations. No platform-specific capture API
+or device assumption changed. Physical voice validation is still required on
+all three desktop platforms before removing the pending qualifier.
+
+**Class rule.** A visual loudness meter may adapt its noise gate, but it must
+not normalize every newly observed peak to full scale. Peak auto-gain is useful
+for recognition input; it destroys the relative amplitude information that a
+user-facing level indicator exists to show.
diff --git a/jarvis/audio/level_tap.py b/jarvis/audio/level_tap.py
index 53738c7c0c..78b34c7256 100644
--- a/jarvis/audio/level_tap.py
+++ b/jarvis/audio/level_tap.py
@@ -6,6 +6,7 @@ jarvis-bar overlay registers a sink; the audio player publishes the per-flush
RMS. When no sink is registered, publishing is a cheap no-op (the player also
skips the RMS computation entirely via ``has_subscribers()``).
"""
+
from __future__ import annotations
import logging
@@ -27,9 +28,10 @@ _lock = threading.Lock()
_audible_until = 0.0
_subscribers: list[Callable[[float], None]] = []
-# Adaptive normalizer for the TTS output: raw speech RMS is only ~0.05-0.15, so
-# publishing it un-normalized made the bars reach barely 10% (looked static).
-# Same adaptive peak/gain as the mic path so Jarvis's voice drives full bars.
+# Shared logarithmic normalizer for TTS output: raw speech RMS is only
+# ~0.05-0.15, so publishing it un-normalized made the bars reach barely 10%.
+# The wide dB range also preserves sentence dynamics instead of flattening each
+# newly observed peak to full scale.
_norm = LevelNormalizer()
@@ -68,9 +70,9 @@ def publish(level: float) -> None:
def feed(rms: float) -> None:
"""Normalize a raw TTS output RMS into a reactive 0..1 level and publish it.
- This is what the player should call (not ``publish``): the adaptive
- normalizer maps Jarvis's speech to the full bar range, mirroring the mic
- path. ``publish`` stays for raw passthrough / tests.
+ This is what the player should call (not ``publish``): the logarithmic
+ normalizer maps Jarvis's speech across the full bar range, mirroring the
+ mic path. ``publish`` stays for raw passthrough / tests.
"""
publish(_norm.push(float(rms)))
diff --git a/jarvis/audio/mic_level.py b/jarvis/audio/mic_level.py
index 1e487476c6..a1b5267144 100644
--- a/jarvis/audio/mic_level.py
+++ b/jarvis/audio/mic_level.py
@@ -2,9 +2,9 @@
The VAD frame loop (which already reads every captured frame for STT) feeds the
raw per-frame RMS via :func:`feed`; a stateful normalizer — adaptive noise
-floor + peak auto-gain + attack/release smoothing — turns it into a reactive
-0..1 level. Subscribers (the orb / jarvis-bar, via ``OrbBusBridge``) render it
-as live bars that move with your voice.
+floor + logarithmic dB mapping + attack/release smoothing — turns it into a
+reactive 0..1 level. Subscribers (the orb / jarvis-bar, via ``OrbBusBridge``)
+render it as live bars that move with your voice.
Why this and not a second mic stream: the old path opened a SECOND
``sd.InputStream`` (on the default device) while the STT pipeline already had
@@ -16,9 +16,11 @@ Deliberately NOT the EventBus (same rationale as ``level_tap``): ~30 Hz level
samples would spam the flight-recorder. Zero-cost when nobody subscribes — the
caller gates on :func:`has_subscribers`.
"""
+
from __future__ import annotations
import logging
+import math
import threading
from collections.abc import Callable
@@ -26,46 +28,51 @@ _log = logging.getLogger("jarvis.audio.mic_level")
_lock = threading.Lock()
_subscribers: list[Callable[[float], None]] = []
-# Floors — prevent div-by-~0 and runaway gain on absolute silence (muted mic).
-# Sized for the QUIETEST real input path, not the maintainer's mic
-# (fresh-machine forensics Bug 17): a quiet laptop puts hiss at ~0.0005 and
-# real speech at ~0.002-0.006 rms — with the old floors (0.001 / 0.01) that
-# whole band rendered near-zero bars while STT/wake heard it fine. Digital
-# mute (~1e-5) still sits far below both floors, so a muted mic stays dark.
+# The adaptive floor prevents room noise from animating the meter. The visual
+# range below spans roughly -72 dBFS to -12 dBFS after gating. A logarithmic
+# range is wide enough for a quiet laptop mic (speech around 0.002-0.006 RMS)
+# and a high-gain headset without making either device load-bearing. Unlike an
+# adaptive peak, it preserves the difference between quiet and loud speech.
_MIN_NOISE_FLOOR = 0.0002
-_MIN_PEAK = 0.004
+_METER_FLOOR_RMS = 0.00025
+_METER_CEILING_RMS = 0.25
+_METER_LOG_SPAN = math.log(_METER_CEILING_RMS / _METER_FLOOR_RMS)
+_METER_CURVE = 1.15
class LevelNormalizer:
- """RMS → 0..1 level. Lifted from MicListener: adaptive noise floor (EMA on
- quiet frames), peak auto-gain (fast attack, slow decay), and attack-fast /
- release-slow output smoothing so the bars pulse naturally instead of
- flickering."""
+ """Map RMS to a stable, volume-faithful 0..1 display level.
+
+ Quiet frames adapt the noise gate to the current device and room. Samples
+ above that gate are mapped over a fixed logarithmic range, so a transient
+ cannot poison a peak reference and a soft sound cannot redefine itself as
+ full scale. Attack/release smoothing keeps the bars lively without flicker.
+ """
def __init__(self) -> None:
self._noise_floor = 0.005
- # Start the auto-gain reference AT the floor: the attack path raises it
- # to the true peak within one loud frame, while a high start (0.05)
- # would take ~800 decay frames (~27 s) to reach a quiet mic's speech
- # level — the bars would read near-dead for the whole first session.
- self._peak = _MIN_PEAK
self._smoothed = 0.0
def push(self, rms: float) -> float:
- if rms < self._noise_floor * 1.5:
- self._noise_floor = 0.95 * self._noise_floor + 0.05 * rms
+ value = float(rms)
+ if not math.isfinite(value) or value <= 0.0:
+ value = 0.0
+ else:
+ value = min(1.0, value)
+
+ if value < self._noise_floor * 1.5:
+ self._noise_floor = 0.95 * self._noise_floor + 0.05 * value
self._noise_floor = max(self._noise_floor, _MIN_NOISE_FLOOR)
speech_threshold = self._noise_floor * 3.0
- gated = max(0.0, rms - speech_threshold)
-
- if gated > self._peak:
- self._peak = gated
+ gated = max(0.0, value - speech_threshold)
+ if gated <= _METER_FLOOR_RMS:
+ raw = 0.0
+ elif gated >= _METER_CEILING_RMS:
+ raw = 1.0
else:
- self._peak *= 0.997
- self._peak = max(self._peak, _MIN_PEAK)
-
- raw = min(1.0, gated / self._peak)
+ position = math.log(gated / _METER_FLOOR_RMS) / _METER_LOG_SPAN
+ raw = position**_METER_CURVE
if raw > self._smoothed: # attack fast
self._smoothed = 0.4 * self._smoothed + 0.6 * raw
@@ -75,7 +82,6 @@ class LevelNormalizer:
def reset(self) -> None:
self._noise_floor = 0.005
- self._peak = _MIN_PEAK
self._smoothed = 0.0
diff --git a/jarvis/ui/web/frontend/src/lib/levelMeter.test.ts b/jarvis/ui/web/frontend/src/lib/levelMeter.test.ts
index f81c14a6e6..a355594553 100644
--- a/jarvis/ui/web/frontend/src/lib/levelMeter.test.ts
+++ b/jarvis/ui/web/frontend/src/lib/levelMeter.test.ts
@@ -2,6 +2,12 @@ import { describe, expect, it } from "vitest";
import { LevelMeter } from "./levelMeter";
+function pushFrames(meter: LevelMeter, rms: number, frames: number): number {
+ let level = 0;
+ for (let i = 0; i < frames; i++) level = meter.push(rms);
+ return level;
+}
+
describe("LevelMeter", () => {
it("stays near zero on silence", () => {
const meter = new LevelMeter();
@@ -19,6 +25,31 @@ describe("LevelMeter", () => {
expect(level).toBeGreaterThan(0.3);
});
+ it("preserves soft, normal, and loud input differences", () => {
+ const meter = new LevelMeter();
+ pushFrames(meter, 0.0008, 60);
+
+ const soft = pushFrames(meter, 0.02, 12);
+ const normal = pushFrames(meter, 0.06, 12);
+ const loud = pushFrames(meter, 0.2, 12);
+
+ expect(soft).toBeGreaterThan(0.3);
+ expect(soft).toBeLessThan(0.7);
+ expect(normal).toBeGreaterThan(soft + 0.12);
+ expect(loud).toBeGreaterThan(normal + 0.12);
+ expect(loud).toBeGreaterThan(0.9);
+ });
+
+ it("does not let one impulse suppress the following voice", () => {
+ const meter = new LevelMeter();
+ pushFrames(meter, 0.0008, 60);
+
+ meter.push(0.5);
+ const recovered = pushFrames(meter, 0.06, 6);
+
+ expect(recovered).toBeGreaterThan(0.65);
+ });
+
it("attacks faster than it releases", () => {
const meter = new LevelMeter();
for (let i = 0; i < 30; i++) meter.push(0.0005);
diff --git a/jarvis/ui/web/frontend/src/lib/levelMeter.ts b/jarvis/ui/web/frontend/src/lib/levelMeter.ts
index 0d17947a64..c75e1bb72a 100644
--- a/jarvis/ui/web/frontend/src/lib/levelMeter.ts
+++ b/jarvis/ui/web/frontend/src/lib/levelMeter.ts
@@ -1,18 +1,19 @@
// Client-side input-level normalizer for the browser realtime surface.
//
-// Simplified port of the backend LevelNormalizer (jarvis/audio/mic_level.py):
-// adaptive noise floor (EMA on quiet frames), peak auto-gain (fast attack,
-// slow decay), and attack-fast / release-slow output smoothing so the level
-// indicator pulses naturally instead of flickering. Raw RMS comes from the
-// capture worklet on float32 samples in [-1, 1], the same scale the backend
-// uses, so both surfaces behave alike.
+// Port of the backend LevelNormalizer (jarvis/audio/mic_level.py): adaptive
+// noise floor, a volume-faithful logarithmic range, and attack-fast /
+// release-slow output smoothing. Raw RMS comes from the capture worklet on
+// float32 samples in [-1, 1], the same scale the backend uses, so native and
+// browser surfaces behave alike.
const MIN_NOISE_FLOOR = 0.0002;
-const MIN_PEAK = 0.004;
+const METER_FLOOR_RMS = 0.00025;
+const METER_CEILING_RMS = 0.25;
+const METER_LOG_SPAN = Math.log(METER_CEILING_RMS / METER_FLOOR_RMS);
+const METER_CURVE = 1.15;
export class LevelMeter {
private noiseFloor = 0.005;
- private peak = MIN_PEAK;
private smoothed = 0;
/** Normalize one raw RMS sample to a reactive 0..1 level. */
@@ -26,12 +27,13 @@ export class LevelMeter {
const speechThreshold = this.noiseFloor * 3.0;
const gated = Math.max(0, value - speechThreshold);
-
- if (gated > this.peak) this.peak = gated;
- else this.peak *= 0.997;
- this.peak = Math.max(this.peak, MIN_PEAK);
-
- const raw = Math.min(1, gated / this.peak);
+ let raw = 0;
+ if (gated >= METER_CEILING_RMS) {
+ raw = 1;
+ } else if (gated > METER_FLOOR_RMS) {
+ const position = Math.log(gated / METER_FLOOR_RMS) / METER_LOG_SPAN;
+ raw = position ** METER_CURVE;
+ }
if (raw > this.smoothed) {
// attack fast
@@ -45,7 +47,6 @@ export class LevelMeter {
reset(): void {
this.noiseFloor = 0.005;
- this.peak = MIN_PEAK;
this.smoothed = 0;
}
}
diff --git a/tests/unit/audio/test_mic_level.py b/tests/unit/audio/test_mic_level.py
index 6f0d5543aa..72ec95ac6e 100644
--- a/tests/unit/audio/test_mic_level.py
+++ b/tests/unit/audio/test_mic_level.py
@@ -1,7 +1,16 @@
"""mic_level: normalize per-frame RMS into a reactive 0..1 level + pub/sub."""
+
from __future__ import annotations
from jarvis.audio import mic_level
+from jarvis.audio.mic_level import LevelNormalizer
+
+
+def _push_frames(meter: LevelNormalizer, rms: float, frames: int) -> float:
+ level = 0.0
+ for _ in range(frames):
+ level = meter.push(rms)
+ return level
def test_no_subscriber_is_noop_and_reports_empty():
@@ -29,7 +38,7 @@ def test_feed_publishes_and_reacts_to_loudness():
assert 0.0 <= quiet <= 1.0
assert 0.0 <= loud <= 1.0
assert loud > quiet # the bars must react to voice loudness
- assert loud > 0.3 # a clearly audible level, not stuck near zero
+ assert loud > 0.3 # a clearly audible level, not stuck near zero
unsub()
assert mic_level.has_subscribers() is False
@@ -63,12 +72,43 @@ def test_quiet_laptop_mic_speech_is_clearly_visible():
for _ in range(80):
mic_level.feed(0.0005) # quiet laptop hiss — floor settles here
for _ in range(15):
- mic_level.feed(0.004) # normal speech on that mic
+ mic_level.feed(0.004) # normal speech on that mic
assert got[-1] > 0.25, f"speech on a quiet mic reads near-dead: {got[-1]:.3f}"
mic_level.reset_for_tests()
+def test_meter_preserves_quiet_normal_and_loud_differences():
+ """The display must follow volume instead of auto-gaining every new peak.
+
+ The old adaptive-peak ratio made soft speech, normal speech, and loud speech
+ converge to 1.0. That produced false full swings and left no extra movement
+ when the user actually raised their voice.
+ """
+ meter = LevelNormalizer()
+ _push_frames(meter, 0.0008, 60)
+
+ soft = _push_frames(meter, 0.02, 12)
+ normal = _push_frames(meter, 0.06, 12)
+ loud = _push_frames(meter, 0.20, 12)
+
+ assert 0.3 < soft < 0.7
+ assert normal > soft + 0.12
+ assert loud > normal + 0.12
+ assert loud > 0.9
+
+
+def test_one_impulse_does_not_suppress_following_voice():
+ """A click or clipped frame must not poison the next seconds of metering."""
+ meter = LevelNormalizer()
+ _push_frames(meter, 0.0008, 60)
+
+ meter.push(0.5)
+ recovered = _push_frames(meter, 0.06, 6)
+
+ assert recovered > 0.65
+
+
def test_muted_mic_stays_dark():
"""Runaway-gain guard: digital near-silence (muted mic) must NOT produce
dancing bars even with the lowered floors."""
diff --git a/ui/orb/mic_listener.py b/ui/orb/mic_listener.py
index ea0392fed0..6ee152c7f4 100644
--- a/ui/orb/mic_listener.py
+++ b/ui/orb/mic_listener.py
@@ -1,16 +1,15 @@
-"""Microphone listener with RMS level + adaptive noise gating.
+"""Microphone listener with a noise-gated logarithmic RMS level.
Emits an audio level (0..1) to a callback, ~50 Hz. The level is
-normalized to an adaptive peak and cleared of background noise
-(fan, keyboard, coffee machine) via noise gating.
+mapped across a wide dB range and cleared of background noise via the shared
+desktop level normalizer.
Design decision — no silero-vad / webrtcvad:
For the pure "loud-enough-to-pulse" logic, a VAD library would be
- overkill (startup latency, extra model weight). Instead, adaptive
- noise-floor estimation via EMA: quiet frames slowly pull the floor
- down, the speech threshold is 3x the floor → self-calibrates within
- a few seconds to the room + mic gain. Peak tracking with auto-decay
- provides the amplitude normalization.
+ overkill (startup latency, extra model weight). Instead, the shared
+ normalizer estimates a quiet-frame noise floor and maps the remaining RMS
+ over a logarithmic range. This retains real quiet/loud differences while
+ covering microphones with very different gains.
If a hard speech/non-speech classification is needed later
(e.g. for a wake-word trigger), silero-vad can be added in a separate
@@ -26,20 +25,20 @@ Threading contract:
from __future__ import annotations
-from typing import Callable
+import logging
+from collections.abc import Callable
import numpy as np
import sounddevice as sd
+from jarvis.audio.mic_level import LevelNormalizer
+
+_log = logging.getLogger("jarvis.ui.orb.mic_listener")
+
SAMPLE_RATE = 16000
FRAME_MS = 20
FRAME_SAMPLES = SAMPLE_RATE * FRAME_MS // 1000 # 320
-# Minimum floor — prevents division by ~0 and unbounded runaway growth
-# on absolutely silent input (a muted mic).
-_MIN_NOISE_FLOOR = 0.001
-_MIN_PEAK = 0.01
-
class MicListener:
"""Non-blocking mic capture with a level callback."""
@@ -53,12 +52,7 @@ class MicListener:
self._device = device
self._stream: sd.InputStream | None = None
- # Adaptive noise floor: adjusts to the room's ambient loudness
- self._noise_floor: float = 0.005
- # Adaptive peak: normalizes loud words to 1.0
- self._peak: float = 0.05
- # Smoothed output level for a natural pulsing feel
- self._smoothed: float = 0.0
+ self._normalizer = LevelNormalizer()
def start(self) -> None:
self._stream = sd.InputStream(
@@ -77,7 +71,7 @@ class MicListener:
self._stream.stop()
self._stream.close()
except Exception:
- pass
+ _log.debug("Microphone level stream cleanup failed", exc_info=True)
self._stream = None
# --- PortAudio-Thread ----------------------------------------------
@@ -86,37 +80,8 @@ class MicListener:
# RMS of the 20ms frame. mono: indata.shape == (320, 1)
rms = float(np.sqrt(np.mean(np.square(indata))))
- # Only update the noise floor on quiet frames (EMA). This prevents
- # loud speech from pulling the floor up and then gating everything.
- if rms < self._noise_floor * 1.5:
- self._noise_floor = 0.95 * self._noise_floor + 0.05 * rms
- self._noise_floor = max(self._noise_floor, _MIN_NOISE_FLOOR)
-
- # Speech gate: below 3x the noise floor counts as "no speech".
- speech_threshold = self._noise_floor * 3.0
- gated = max(0.0, rms - speech_threshold)
-
- # Peak tracking: fast rise, slow decay → auto-gain.
- # 0.997^50 ≈ 0.86 decay per second, i.e. the peak halves in ~3 s
- # once nothing loud comes in anymore → subsequent normal
- # speech is quickly scaled back to a "full swing" again.
- if gated > self._peak:
- self._peak = gated
- else:
- self._peak *= 0.997
- self._peak = max(self._peak, _MIN_PEAK)
-
- raw_level = min(1.0, gated / self._peak)
-
- # Attack-fast, release-slow — feels like natural pulsing.
- # Without release smoothing the orb "flickers".
- if raw_level > self._smoothed:
- self._smoothed = 0.4 * self._smoothed + 0.6 * raw_level
- else:
- self._smoothed = 0.75 * self._smoothed + 0.25 * raw_level
-
try:
- self._on_level(self._smoothed)
+ self._on_level(self._normalizer.push(rms))
except Exception:
# Callback errors must not kill the audio stream
- pass
+ _log.debug("Microphone level callback failed", exc_info=True)