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
feat(tts): boost loudness so 100% carries as loud as music, on every OS
Ruben Lütkee8d3d24a20f8
diff --git a/jarvis/audio/gain.py b/jarvis/audio/gain.pynew file mode 100644index 0000000000..e4c90923e2--- /dev/null+++ b/jarvis/audio/gain.py@@ -0,0 +1,109 @@+"""Shared master-output-volume gain for EVERY TTS sink.++The user's ``[tts].volume`` is a single 0.0–1.0 knob. Raw TTS speech is far+quieter than mastered music (lots of dynamics + pauses → a low average/RMS+level), so a plain 1:1 copy sounds weak next to a music track at the same system+volume. We therefore scale the knob up to a *makeup gain* — 100% is a real+loudness boost, not just unity — and run the boosted signal through a soft-knee+limiter so it gets louder WITHOUT hard-clipping into distortion. Attenuation+(below the unity point) stays a plain multiply and can never clip.++One implementation, three call sites. The local float32 speaker path+(``AudioPlayer``), the browser-voice WebSocket int16 path, and the telephony+mu-law int16 path all route through these helpers, so loudness is identical on+every OS and every transport — including a headless VPS with no local audio+device, where the voice is carried by the browser/telephony sinks. ``numpy`` is+a base dependency (``pyproject``: ``numpy>=1.26``), so this is safe on a slim+server too.++Tuning lives here and nowhere else: change :data:`_MAKEUP_GAIN` /+:data:`_LIMIT_KNEE` once and every sink follows.+"""+from __future__ import annotations++import numpy as np++# 100% volume maps to this playback gain. Speech TTS typically sits well below+# mastered music in perceived loudness, so a generous makeup range with a soft+# limiter lets the user dial Jarvis up to (or past) music level from the slider+# alone — no code change, no config editing. The unity (1:1, byte-identical)+# point is therefore at ``volume = 1 / _MAKEUP_GAIN`` (25% for 4.0). Turning the+# slider down from 100% walks smoothly from "loudest" through unity to silence.+_MAKEUP_GAIN = 4.0++# Soft-knee limiter threshold. Samples whose magnitude is below this pass through+# UNTOUCHED (transparent) — that is the bulk of quiet speech, which is exactly+# what the boost is meant to lift. Only the range ABOVE the knee is compressed+# toward full-scale, so real peaks saturate gently instead of clipping. A global+# ``tanh`` (no knee) would soften the whole signal and dull the voice; the knee+# keeps quiet detail linear and shapes only what would otherwise clip.+_LIMIT_KNEE = 0.6+++def clamp_volume(volume: float) -> float:+ """Clamp the user volume knob into ``[0.0, 1.0]``.++ A value outside the range is pinned to the bounds; a non-numeric value falls+ back to full volume (1.0) rather than muting, so a corrupt config can never+ silence Jarvis.+ """+ try:+ return max(0.0, min(1.0, float(volume)))+ except (TypeError, ValueError):+ return 1.0+++def effective_gain(volume: float) -> float:+ """Playback gain for a 0.0–1.0 volume knob: ``0.0 … _MAKEUP_GAIN``."""+ return clamp_volume(volume) * _MAKEUP_GAIN+++def soft_limit(arr: np.ndarray) -> np.ndarray:+ """Soft-knee limiter on float32 samples.++ Below ``±_LIMIT_KNEE`` the signal is untouched (transparent). Above the knee+ the excess magnitude is compressed with ``tanh`` so the output asymptotes to+ ``±1.0`` — boosted peaks saturate gently instead of clipping. Returns a new+ array; the input is not mutated.+ """+ out = arr.astype(np.float32, copy=True)+ over = np.abs(arr) > _LIMIT_KNEE+ if over.any():+ sign = np.sign(arr[over])+ excess = np.abs(arr[over]) - _LIMIT_KNEE+ head = 1.0 - _LIMIT_KNEE+ out[over] = sign * (_LIMIT_KNEE + head * np.tanh(excess / head))+ return out+++def apply_output_gain(arr_f: np.ndarray, volume: float) -> np.ndarray:+ """Apply the master volume to float32 samples in ``[-1, 1]`` (local path).++ - unity knob → returns ``arr_f`` unchanged (no copy, byte-identical output),+ - attenuation (gain < 1) → a plain multiply that can never clip,+ - boost (gain > 1) → multiply then the soft-knee limiter.+ """+ gain = effective_gain(volume)+ if gain == 1.0:+ return arr_f+ scaled = arr_f * gain+ return soft_limit(scaled) if gain > 1.0 else scaled+++def apply_output_gain_pcm16(pcm: bytes, volume: float) -> bytes:+ """Apply the master volume to int16 mono PCM bytes (browser + telephony).++ ``int16 → float32 → gain (+ soft limiter on boost) → int16``, so a headless+ server's browser/telephony voice gets the SAME loudness as the local+ speaker. Empty input and a unity knob short-circuit to the input bytes, so+ the common path stays cheap.+ """+ gain = effective_gain(volume)+ if not pcm or gain == 1.0:+ return pcm+ arr = np.frombuffer(pcm, dtype=np.int16).astype(np.float32) / 32768.0+ out = apply_output_gain(arr, volume)+ # Back to int16: the soft limiter keeps |out| < 1, but clip as a hard guard+ # against a rounding/edge overshoot, then round-to-nearest.+ scaled = np.clip(out * 32768.0, -32768.0, 32767.0)+ return np.rint(scaled).astype(np.int16).tobytes()diff --git a/jarvis/audio/player.py b/jarvis/audio/player.pyindex 7758f7b230..4bf6989318 100644--- a/jarvis/audio/player.py+++ b/jarvis/audio/player.py@@ -27,6 +27,7 @@ else:sd = None # type: ignore[assignment]from jarvis.audio import level_tap+from jarvis.audio.gain import apply_output_gain, clamp_volumefrom jarvis.core.events import AudioOutFirstfrom jarvis.core.protocols import AudioChunk@@ -253,20 +254,6 @@ def _resolve_output_device(device: int | str | None) -> int | str | None:return None-def _clamp_volume(volume: float) -> float:- """Clamp a requested master gain into the safe attenuation range [0.0, 1.0].-- A value >1.0 would push samples past full-scale and clip; a negative value- would invert the waveform. Both are silently pinned to the bounds so no- caller (config, REST, runtime setter) can over-drive playback. A non-numeric- value falls back to full volume rather than muting.- """- try:- return max(0.0, min(1.0, float(volume)))- except (TypeError, ValueError):- return 1.0--class AudioPlayer:"""Thread-safe async player for int16 PCM audio."""@@ -283,10 +270,11 @@ class AudioPlayer:self._device = _resolve_output_device(device)self._sample_rate = sample_rateself._channels = channels- # Master output gain in [0.0, 1.0] (1.0 = full, historical behaviour).- # Applied per sub-block in _write_samples. Clamped so a stray config /- # runtime value can never over-drive (>1.0 would clip) or invert (<0).- self._volume = _clamp_volume(volume)+ # Master output volume knob in [0.0, 1.0]. Applied in _write_samples via+ # the shared gain helper (jarvis.audio.gain), which scales it to a makeup+ # boost + soft limiter so 100% is a real loudness lift, not just unity.+ # Clamped so a stray config/runtime value can never invert or over-range.+ self._volume = clamp_volume(volume)self._device_logged = False # logged once on the first play call# Optional bus reference. When set, play_chunks() publishes# AudioOutFirst on the first audible sample so UI subscribers@@ -394,14 +382,14 @@ class AudioPlayer:self.invalidate_device_cache()def set_volume(self, volume: float) -> None:- """Live-apply a new master output gain (0.0–1.0) — no stream restart.+ """Live-apply a new master output volume (0.0–1.0) — no stream restart.The value is read per sub-block in ``_write_samples``, so a change made- mid-utterance takes effect on the next ~60 ms block. Clamped to the safe- attenuation range; the open PortAudio stream is untouched (gain rides on- top of it, orthogonal to device/rate/lifecycle state).+ mid-utterance takes effect on the next ~60 ms block. Clamped to [0, 1];+ the open PortAudio stream is untouched (gain rides on top of it,+ orthogonal to device/rate/lifecycle state)."""- self._volume = _clamp_volume(volume)+ self._volume = clamp_volume(volume)def _log_device_once(self) -> None:"""Log the active output device once per AudioPlayer instance.@@ -587,18 +575,19 @@ class AudioPlayer:# write still provides back-pressure. ~60 ms blocks are large enough to# never starve the buffer.feed_level = level_tap.has_subscribers()- # Master output volume (0.0–1.0). ``gain >= 1.0`` is the fast path — no- # copy, so full-volume playback stays byte-identical to before. Below- # full we attenuate a per-block copy for the speaker but feed the- # PRE-gain RMS to the visualizer, so the orb/equalizer keeps showing- # that Jarvis is speaking even at a low volume (bars track speech, not- # loudness). ``getattr`` default keeps ``__new__``-built test/hot-reload- # instances (which skip ``__init__``) at full volume instead of crashing.- gain = getattr(self, "_volume", 1.0)+ # Master output volume: scale the whole buffer once via the shared gain+ # helper (makeup boost + soft limiter above unity, plain attenuation+ # below), then write it in sub-blocks. ``arr_out is arr_f`` when the knob+ # sits exactly at unity, so full playback stays byte-identical. The+ # visualizer is fed the PRE-gain RMS (arr_f), so the orb/equalizer keeps+ # tracking the speech itself — full bars even when the volume is low, and+ # not artificially pumped when it is boosted. ``getattr`` default keeps+ # ``__new__``-built test/hot-reload instances (which skip ``__init__``)+ # at unity instead of crashing.+ arr_out = apply_output_gain(arr_f, getattr(self, "_volume", 1.0))block = max(1, int(device_rate * 0.06))- for start in range(0, arr_f.shape[0], block):- chunk = arr_f[start:start + block]- out = chunk if gain >= 1.0 else chunk * gain+ for start in range(0, arr_out.shape[0], block):+ out = arr_out[start:start + block]underflowed = stream.write(out)# Playback progress for the pipeline stall watchdog: a healthy# ~60 ms sub-block returns well inside the watchdog's stall window;@@ -606,16 +595,18 @@ class AudioPlayer:# defaults keep this resilient for ``__new__``-built instances (test# fixtures / hot-reload) that skipped ``_init_progress`` — progress# telemetry must never be the thing that crashes playback.- self.frames_written = getattr(self, "frames_written", 0) + int(chunk.shape[0])+ self.frames_written = getattr(self, "frames_written", 0) + int(out.shape[0])self.last_write_ns = time.monotonic_ns()if underflowed:log.warning("PortAudio underflow during write (frames=%d, source=%dHz, ""device=%dHz) — buffer drained mid-stream, audible click/crackle",- chunk.shape[0], source_rate, device_rate,+ out.shape[0], source_rate, device_rate,)- if feed_level and chunk.size:- level_tap.feed(float(np.sqrt(np.mean(np.square(chunk)))))+ if feed_level:+ pre = arr_f[start:start + block] # PRE-gain RMS for the visualizer+ if pre.size:+ level_tap.feed(float(np.sqrt(np.mean(np.square(pre)))))def _close_output_stream(self, stream: sd.OutputStream) -> None:"""Flush and stop: ``stream.stop()`` blocks until the buffer is empty."""diff --git a/jarvis/browser_voice/route.py b/jarvis/browser_voice/route.pyindex 6fbf1e8892..2778327123 100644--- a/jarvis/browser_voice/route.py+++ b/jarvis/browser_voice/route.py@@ -74,6 +74,7 @@ def _build_browser_session(tts=tts,language_code=_resolve_language(cfg),bus=bus,+ config=cfg,)diff --git a/jarvis/browser_voice/session.py b/jarvis/browser_voice/session.pyindex 34067ae305..8de9b7c6d6 100644--- a/jarvis/browser_voice/session.py+++ b/jarvis/browser_voice/session.py@@ -75,6 +75,7 @@ class BrowserVoiceSession:language_code: str = "de-DE",max_session_seconds: int = 1800,bus: Any = None,+ config: Any = None,) -> None:self.session_id = session_idself._send_binary = send_binary@@ -82,6 +83,9 @@ class BrowserVoiceSession:self._stt = sttself._brain = brainself._tts = tts+ # Shared config reference so _speak can read [tts].volume per turn (a live+ # change lands on the next utterance). None in test factories → full.+ self._config = configself.browser_sample_rate = int(browser_sample_rate or STT_SAMPLE_RATE)self.language_code = language_code or "de-DE"self.max_session_seconds = max_session_seconds@@ -214,8 +218,16 @@ class BrowserVoiceSession:the number of binary frames sent. Cancellable: a barge-in cancels theunderlying task mid-stream."""+ from jarvis.audio.gain import (+ apply_output_gain_pcm16, # noqa: PLC0415 — lazy: keep cold-import light+ )from jarvis.browser_voice.audio import resample_pcm16 # noqa: PLC0415 — off-rate fallback+ # Master output volume (shared with the local speaker + telephony sinks)+ # so the setting works over the browser too — the only voice path on a+ # headless server. Read once per turn; a live change lands next utterance.+ vol = getattr(getattr(self._config, "tts", None), "volume", 1.0)+self._speaking = Truesent = 0try:@@ -227,6 +239,7 @@ class BrowserVoiceSession:continueif rate != TTS_SAMPLE_RATE:pcm = resample_pcm16(pcm, rate, TTS_SAMPLE_RATE)+ pcm = apply_output_gain_pcm16(pcm, vol)await self._send_binary(pcm)sent += 1await self._send_json({"type": "tts_end"})diff --git a/jarvis/core/config.py b/jarvis/core/config.pyindex 8e834c700f..bec27ca1dd 100644--- a/jarvis/core/config.py+++ b/jarvis/core/config.py@@ -309,12 +309,13 @@ class TTSConfig(BaseModel):style_prompt: str | None = Nonevoice_auto_switch: bool = Truespeed: float = 1.0- # Master output volume 0.0–1.0 (1.0 = full, unattenuated — the historical- # behaviour). Applied as a pure amplitude multiplier on the final PCM in the- # shared AudioPlayer, so it is provider-independent and can never clip (a- # 0–1 factor only attenuates). Editable live from the Settings "Volume"- # slider; on a headless host with no audio device it is simply never- # exercised (playback never opens a stream) — no crash.+ # Master output volume knob, 0.0–1.0 (1.0 = 100% = loudest). Consumed by the+ # shared gain helper (jarvis.audio.gain), which scales it to a makeup boost ++ # soft limiter so 100% is genuinely loud — raw TTS speech is far quieter than+ # mastered music — while below the unity point it plainly attenuates. Applied+ # to EVERY sink (local speaker, browser voice, telephony), so it works on+ # every OS and transport, including a headless server with no audio device.+ # Provider-independent; editable live from the Settings "Volume" slider.volume: float = Field(default=1.0, ge=0.0, le=1.0)streaming: bool = True# ElevenLabs-specific VoiceSettings (ignored by other providers).diff --git a/jarvis/telephony/session.py b/jarvis/telephony/session.pyindex dc794f030c..a7388b15fe 100644--- a/jarvis/telephony/session.py+++ b/jarvis/telephony/session.py@@ -432,6 +432,14 @@ class TelephonyCallSession:Returns the number of 20 ms outbound media frames sent. Cancellable:a barge-in cancels the underlying task mid-stream."""+ # Master output volume (shared with the local speaker + browser sinks) so+ # the setting works on a call too, not just at the desk. Read once per+ # turn so a live change lands on the next utterance. numpy import is lazy+ # to keep the telephony module's cold-import light.+ from jarvis.audio.gain import apply_output_gain_pcm16++ vol = getattr(getattr(self._config, "tts", None), "volume", 1.0)+self._speaking = Truesent = 0try:@@ -448,6 +456,7 @@ class TelephonyCallSession:pcm8 = resample_pcm16(pcm, rate, TWILIO_SAMPLE_RATE)else:pcm8 = self._out_resampler.process(pcm)+ pcm8 = apply_output_gain_pcm16(pcm8, vol)ulaw = pcm16_to_ulaw(pcm8)for frame in frame_ulaw(ulaw):await self._send_media(frame)diff --git a/jarvis/ui/web/frontend/src/i18n/locales/de.json b/jarvis/ui/web/frontend/src/i18n/locales/de.jsonindex 359d64b733..b989987a64 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/de.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/de.json@@ -918,7 +918,7 @@},"volume": {"title": "Lautstärke",- "description": "Wie laut {name} seine Antworten ausgibt. 100% ist volle Lautstärke; niedriger stellen, um {name} leiser zu machen. Wenn es bei 100% noch zu leise ist, die System- oder Lautsprecher-Lautstärke erhöhen.",+ "description": "Wie laut {name} seine Antworten ausgibt. 100% ist am lautesten — herunterregeln, wenn {name} zu laut ist. Die Sprache wird angehoben, damit sie so laut wie Musik trägt, ohne zu verzerren.","reset": "Auf Standard zurücksetzen (100%)","saved_toast": "Lautstärke auf {0} gesetzt.","restart_caption": "Gespeichert — wird beim nächsten Start aktiv."diff --git a/jarvis/ui/web/frontend/src/i18n/locales/en.json b/jarvis/ui/web/frontend/src/i18n/locales/en.jsonindex 21bf4dd7ae..b77a7f5d6e 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/en.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/en.json@@ -919,7 +919,7 @@},"volume": {"title": "Volume",- "description": "How loudly {name} speaks its answers. 100% is full volume; lower it to make {name} quieter. If it is still too quiet at 100%, raise your system or speaker volume.",+ "description": "How loudly {name} speaks its answers. 100% is the loudest — turn it down if {name} is too loud. Speech is boosted so it carries as loud as music, without distortion.","reset": "Reset to default (100%)","saved_toast": "Volume set to {0}.","restart_caption": "Saved — applies on next start."diff --git a/jarvis/ui/web/frontend/src/i18n/locales/es.json b/jarvis/ui/web/frontend/src/i18n/locales/es.jsonindex cd716dbe65..1800b26773 100644--- a/jarvis/ui/web/frontend/src/i18n/locales/es.json+++ b/jarvis/ui/web/frontend/src/i18n/locales/es.json@@ -918,7 +918,7 @@},"volume": {"title": "Volumen",- "description": "Qué tan alto habla {name} sus respuestas. 100% es el volumen máximo; bájalo para que {name} suene más bajo. Si sigue siendo demasiado bajo al 100%, sube el volumen del sistema o del altavoz.",+ "description": "Qué tan alto habla {name} sus respuestas. 100% es el máximo — bájalo si {name} suena demasiado alto. La voz se amplifica para sonar tan fuerte como la música, sin distorsión.","reset": "Restablecer al valor predeterminado (100%)","saved_toast": "Volumen fijado en {0}.","restart_caption": "Guardado — se aplica en el próximo inicio."diff --git a/tests/unit/audio/test_gain.py b/tests/unit/audio/test_gain.pynew file mode 100644index 0000000000..0c2191ecfc--- /dev/null+++ b/tests/unit/audio/test_gain.py@@ -0,0 +1,86 @@+"""Shared master-output-volume gain (jarvis.audio.gain).++Covers the loudness maths every TTS sink relies on: the 0.0-1.0 knob maps to a+makeup boost so 100% is genuinely louder than the raw signal, a soft-knee+limiter keeps the boost from clipping, the unity point is byte-identical, and+attenuation below unity is a plain linear multiply. The int16 wrapper (browser ++telephony) must match the float path and never overflow.+"""+from __future__ import annotations++import numpy as np++from jarvis.audio import gain+++def _rms(a) -> float:+ a = np.asarray(a, dtype=np.float64)+ return float(np.sqrt(np.mean(a * a))) if a.size else 0.0+++def test_clamp_volume_bounds_and_bad_input():+ assert gain.clamp_volume(1.5) == 1.0+ assert gain.clamp_volume(-0.3) == 0.0+ assert gain.clamp_volume(0.4) == 0.4+ assert gain.clamp_volume("nonsense") == 1.0 # non-numeric → full, never mute+++def test_effective_gain_scale():+ unity = 1.0 / gain._MAKEUP_GAIN+ assert gain.effective_gain(1.0) == gain._MAKEUP_GAIN # 100% = loudest+ assert gain.effective_gain(unity) == 1.0 # unity point+ assert gain.effective_gain(0.0) == 0.0 # silent+++def test_unity_is_byte_identical():+ unity = 1.0 / gain._MAKEUP_GAIN+ arr = np.linspace(-0.5, 0.5, 500, dtype=np.float32)+ out = gain.apply_output_gain(arr, unity)+ assert out is arr # exact same object → no copy, no change+++def test_boost_makes_quiet_speech_louder_without_clipping():+ # Quiet TTS-like signal: loud-ish peaks + a quiet body, all below full scale.+ sig = np.concatenate([+ np.full(1000, 0.30, np.float32),+ np.full(1000, 0.08, np.float32),+ ])+ boosted = gain.apply_output_gain(sig, 1.0) # 100%+ assert _rms(boosted) > _rms(sig) * 2 # clearly louder+ assert float(np.max(np.abs(boosted))) <= 1.0 # soft limiter → never clips+++def test_attenuation_below_unity_is_linear():+ unity = 1.0 / gain._MAKEUP_GAIN+ arr = np.full(200, 0.4, np.float32)+ out = gain.apply_output_gain(arr, unity / 2) # half of unity → 0.5x+ assert np.allclose(out, 0.2, atol=1e-4)+++def test_soft_limit_transparent_below_knee_and_bounded_above():+ below = np.full(100, gain._LIMIT_KNEE * 0.5, np.float32)+ assert np.allclose(gain.soft_limit(below), below) # transparent+ # A moderate over-knee value is compressed but stays strictly below 1.0.+ mod = np.full(100, 1.5, np.float32)+ assert float(np.max(np.abs(gain.soft_limit(mod)))) < 1.0+ # An extreme value asymptotes to (but never exceeds) full scale.+ huge = np.full(100, 50.0, np.float32)+ assert float(np.max(np.abs(gain.soft_limit(huge)))) <= 1.0+++def test_pcm16_boost_matches_float_and_never_overflows():+ # 0.2 full-scale int16 tone, boosted at 100%.+ sig = np.full(2000, 0.2, np.float32)+ pcm = (sig * 32768).astype(np.int16).tobytes()+ out = gain.apply_output_gain_pcm16(pcm, 1.0)+ arr = np.frombuffer(out, dtype=np.int16)+ assert arr.dtype == np.int16+ assert arr.max() <= 32767 and arr.min() >= -32768 # in range+ assert _rms(arr.astype(np.float32) / 32768.0) > _rms(sig) * 2 # louder+++def test_pcm16_unity_and_empty_short_circuit():+ unity = 1.0 / gain._MAKEUP_GAIN+ pcm = (np.full(100, 0.3, np.float32) * 32768).astype(np.int16).tobytes()+ assert gain.apply_output_gain_pcm16(pcm, unity) == pcm # unity → same bytes+ assert gain.apply_output_gain_pcm16(b"", 1.0) == b"" # empty → emptydiff --git a/tests/unit/audio/test_player_volume.py b/tests/unit/audio/test_player_volume.pyindex c06f187643..d057780e45 100644--- a/tests/unit/audio/test_player_volume.py+++ b/tests/unit/audio/test_player_volume.py@@ -1,19 +1,20 @@-"""AudioPlayer master output volume — a 0.0–1.0 gain applied in _write_samples.+"""AudioPlayer master output volume — applied in _write_samples via jarvis.audio.gain.Drives the REAL _write_samples with a capturing fake stream (no PortAudio), so-these assert the exact samples that would reach the speaker. Covers: full volume-is byte-identical (unattenuated), fractional volume scales the amplitude, zero is-silent, out-of-range is clamped, and — crucially — the visualizer (level_tap)-keeps seeing the PRE-gain loudness so the orb/equalizer still shows speech when-Jarvis is turned down.+these assert the exact samples that would reach the speaker. The 0.0-1.0 knob+maps through a makeup boost + soft limiter: unity (byte-identical) sits at+1/_MAKEUP_GAIN, 100% is a loud boost that never clips, below unity attenuates,+and the visualizer is fed the PRE-gain loudness so the orb still shows speech."""from __future__ import annotationsimport numpy as np-from jarvis.audio import level_tap+from jarvis.audio import gain, level_tapfrom jarvis.audio import player as P+_UNITY = 1.0 / gain._MAKEUP_GAIN # knob value that yields a 1:1 gain+class _CapturingStream:"""Stand-in for sd.OutputStream that records every written sub-block."""@@ -43,15 +44,24 @@ def _play(volume: float, amplitude: int, n: int = 4000) -> np.ndarray:return np.concatenate(stream.writes, axis=0)-def test_full_volume_is_unattenuated():+def test_unity_knob_is_unattenuated():level_tap.reset() # no subscriber → feed path off- out = _play(1.0, 20000)+ out = _play(_UNITY, 20000)assert np.allclose(out, 20000 / 32768.0, atol=1e-4)-def test_half_volume_halves_amplitude():+def test_full_volume_boosts_without_clipping():+ level_tap.reset()+ amp = 8000 # quiet-ish source (0.244 full-scale)+ out = _play(1.0, amp)+ raw = amp / 32768.0+ assert float(np.max(np.abs(out))) > raw * 1.5 # clearly louder+ assert float(np.max(np.abs(out))) <= 1.0 # soft limiter → never clips+++def test_below_unity_attenuates():level_tap.reset()- out = _play(0.5, 20000)+ out = _play(_UNITY / 2, 20000) # half of unity → 0.5xassert np.allclose(out, 0.5 * 20000 / 32768.0, atol=1e-4)@@ -61,26 +71,25 @@ def test_zero_volume_is_silent():assert np.allclose(out, 0.0, atol=1e-6)-def test_out_of_range_volume_is_clamped_to_full():- # A >1.0 gain would clip; the player clamps on construction, but even a- # raw over-driven value here must not amplify past the input.- level_tap.reset()+def test_out_of_range_volume_is_clamped():pl = P.AudioPlayer.__new__(P.AudioPlayer)- pl.set_volume(5.0) # clamped to 1.0+ pl.set_volume(5.0)assert pl._volume == 1.0---def test_low_volume_keeps_visualizer_full_scale():- """At 10% volume the audio is attenuated but the equalizer/orb still sees- the pre-gain RMS — so the user sees Jarvis is speaking even when quiet."""- level_tap.reset()- got: list[float] = []- level_tap.subscribe(got.append)- try:- out = _play(0.1, 30000)- finally:- level_tap.reset()- # Audio is attenuated to ~10%.- assert np.allclose(out, 0.1 * 30000 / 32768.0, atol=1e-4)- # But the visualizer saw near-full-scale loudness (30000/32768 ≈ 0.92).- assert got and max(got) > 0.5+ pl.set_volume(-2.0)+ assert pl._volume == 0.0+++def test_visualizer_sees_pre_gain_loudness_when_boosted(monkeypatch):+ """At any volume the equalizer/orb tracks the raw speech loudness (pre-gain),+ so the bars are not pumped up by the boost nor shrunk by attenuation.++ We capture the RAW value handed to level_tap.feed (before its normalizer) so+ the assertion is on the pre/post-gain choice, not on the normalizer's output.+ """+ fed: list[float] = []+ monkeypatch.setattr(level_tap, "has_subscribers", lambda: True)+ monkeypatch.setattr(level_tap, "feed", lambda v: fed.append(v))+ _play(1.0, 20000) # 100% → boosted output (~1.0 peak)+ raw_rms = 20000 / 32768.0 # ~0.61+ # Every fed value is the raw signal RMS, NOT the boosted/limited output.+ assert fed and all(abs(v - raw_rms) < 1e-3 for v in fed)