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.

build(web): rebuild the bundle for the Jarvis chat surface

rubenluetke10-beepf93dab693224
diff --git a/jarvis/audio/gain.py b/jarvis/audio/gain.py
index 1625030c5b..e4c90923e2 100644
--- a/jarvis/audio/gain.py
+++ b/jarvis/audio/gain.py
@@ -1,69 +1,43 @@
"""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
+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 hold the boosted signal under full scale
-with a look-ahead peak limiter, so it gets louder WITHOUT distorting.
-Attenuation (below the unity point) stays a plain multiply and can never clip.
-
-Why a limiter and not a curve. Until 2026-08-25 the boost was bounded by a
-static ``tanh`` transfer curve above a 0.6 knee. A fixed curve is a waveshaper:
-it bends every half-wave it touches, and the bend IS harmonic distortion.
-Measured on that curve at 100% volume: an input peak of 0.3 produced ~8% THD,
-0.5 produced ~22%, and everything above 0.5 collapsed onto full scale -- audible
-as a short rasp on the loud syllables of an otherwise clean voice (user report
-2026-08-25). :class:`PeakLimiter` instead lowers the GAIN for the few
-milliseconds around a peak and leaves the waveform's shape alone, so the same
-loudness arrives without added harmonics.
+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
+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_CEILING` once and every sink follows.
+:data:`_LIMIT_KNEE` once and every sink follows.
"""
from __future__ import annotations
-import time
-
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
+# 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)
+# 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
-# Peak the limiter aims for. Slightly under full scale so int16 rounding and the
-# gain ramp's own overshoot at a buffer seam still land inside range.
-_LIMIT_CEILING = 0.97
-
-# How often the limiter recomputes its gain. One control block is also the
-# look-ahead distance: the gain reaches its new value exactly when the block that
-# needs it begins.
-_CONTROL_MS = 1.0
-# Gain reduction is held this long before it starts recovering, so a run of loud
-# syllables is ridden at one steady level instead of pumping between them.
-_HOLD_MS = 60.0
-# Time to walk the gain back to unity once the hold expires. Long enough that the
-# recovery hides under speech rather than breathing audibly in the pauses.
-_RELEASE_MS = 250.0
-# A gap longer than this means the sink went quiet (utterance finished, barge-in,
-# a call between turns). The next buffer is a fresh start, so the gain state is
-# dropped -- otherwise a sentence could open mid-duck and audibly swell.
-_IDLE_RESET_S = 0.4
-# Fallback rate for callers that do not name one. Every TTS sink in this repo
-# runs at 24 kHz; the value only scales the limiter's time constants.
-_DEFAULT_SAMPLE_RATE = 24_000
+# 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:
@@ -80,165 +54,46 @@ def clamp_volume(volume: float) -> float:
def effective_gain(volume: float) -> float:
- """Playback gain for a 0.0-1.0 volume knob: ``0.0 ... _MAKEUP_GAIN``."""
+ """Playback gain for a 0.0–1.0 volume knob: ``0.0 … _MAKEUP_GAIN``."""
return clamp_volume(volume) * _MAKEUP_GAIN
-class PeakLimiter:
- """Streaming look-ahead peak limiter with a per-sample gain ramp.
-
- Holds one gain value across calls, so a stream fed in successive buffers is
- limited as ONE continuous signal -- a gain that jumped at every buffer seam
- would itself be an audible click. Instances are cheap; give each sink
- (speaker, browser session, call) its own.
-
- How it works, per buffer:
-
- 1. Split the samples into ``_CONTROL_MS`` control blocks and take each
- block's peak (channel-linked, so stereo never drifts apart).
- 2. Turn each peak into the gain that would put it exactly on the ceiling.
- 3. Look one block ahead -- a block's gain is the lower of its own and its
- successor's, so the gain is already down when the loud block starts.
- 4. Ride that with a hold and a slow release, then interpolate the gain
- linearly across each block's samples.
+def soft_limit(arr: np.ndarray) -> np.ndarray:
+ """Soft-knee limiter on float32 samples.
- The result is a smooth gain CURVE multiplied onto the samples, so the
- waveform keeps its shape: loudness changes, harmonics do not appear. The
- control loop is sequential but runs ~1 iteration per millisecond of audio,
- which is nothing next to the playback it feeds.
+ 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
- __slots__ = ("_ceiling", "_gain", "_hold", "_last_call", "_primed")
-
- def __init__(self, ceiling: float = _LIMIT_CEILING) -> None:
- self._ceiling = float(ceiling)
- self._gain = 1.0
- self._hold = 0
- self._last_call = 0.0
- self._primed = False
-
- def reset(self) -> None:
- """Forget the gain state: the next buffer opens at unity."""
- self._gain = 1.0
- self._hold = 0
- self._last_call = 0.0
- self._primed = False
-
- def process(
- self, arr: np.ndarray, sample_rate: int = _DEFAULT_SAMPLE_RATE
- ) -> np.ndarray:
- """Limit float32 samples (1-D mono or 2-D ``N x channels``)."""
- if arr.size == 0:
- return arr
- now = time.monotonic()
- if self._last_call and now - self._last_call > _IDLE_RESET_S:
- self.reset()
- self._last_call = now
-
- rate = int(sample_rate) if sample_rate else _DEFAULT_SAMPLE_RATE
- hop = max(1, int(rate * _CONTROL_MS / 1000.0))
- frames = arr.shape[0]
- magnitude = np.abs(arr) if arr.ndim == 1 else np.abs(arr).max(axis=1)
-
- # Block peaks. The tail is zero-padded so the final partial block is
- # judged on the samples it actually has.
- blocks = -(-frames // hop) # ceil
- padding = blocks * hop - frames
- if padding:
- magnitude = np.concatenate(
- [magnitude, np.zeros(padding, dtype=magnitude.dtype)]
- )
- peaks = magnitude.reshape(blocks, hop).max(axis=1).astype(np.float64)
-
- # The gain each block needs, then one block of look-ahead.
- needed = np.ones(blocks, dtype=np.float64)
- loud = peaks > self._ceiling
- if loud.any():
- needed[loud] = self._ceiling / peaks[loud]
- target = np.minimum(needed, np.concatenate([needed[1:], needed[-1:]]))
-
- # Ride it: instant duck (the look-ahead already paid for it), hold, then
- # a slow release. ``ramp_from`` is where the previous buffer left the
- # gain, which makes the curve continuous across the seam. The FIRST
- # buffer after a reset has no seam -- silence preceded it -- so it opens
- # already ducked instead of spending its first millisecond ramping down
- # over audio that is allowed to be loud from sample zero.
- ramp_from = self._gain if self._primed else min(self._gain, float(target[0]))
- self._primed = True
- hold_blocks = max(1, int(_HOLD_MS / _CONTROL_MS))
- release_step = (hop / rate) / (_RELEASE_MS / 1000.0)
- gains = np.empty(blocks, dtype=np.float64)
- gain = self._gain
- hold = self._hold
- for index in range(blocks):
- wanted = float(target[index])
- if wanted < gain:
- gain = wanted
- hold = hold_blocks
- elif hold > 0:
- hold -= 1
- elif gain < wanted:
- gain = min(wanted, gain + release_step)
- gains[index] = gain
- self._gain = gain
- self._hold = hold
-
- # Per-sample ramp: each block walks from the previous block's gain to its
- # own, so the curve is continuous everywhere.
- starts = np.concatenate([[ramp_from], gains[:-1]])
- step = np.arange(hop, dtype=np.float64) / hop
- curve = (
- np.repeat(starts, hop)
- + np.repeat(gains - starts, hop) * np.tile(step, blocks)
- )[:frames].astype(np.float32)
-
- out = arr * (curve if arr.ndim == 1 else curve[:, None])
- return out.astype(np.float32, copy=False)
-
-
-def apply_output_gain(
- arr_f: np.ndarray,
- volume: float,
- *,
- sample_rate: int = _DEFAULT_SAMPLE_RATE,
- limiter: PeakLimiter | None = None,
-) -> 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 look-ahead peak limiter.
+def apply_output_gain(arr_f: np.ndarray, volume: float) -> np.ndarray:
+ """Apply the master volume to float32 samples in ``[-1, 1]`` (local path).
- Pass the sink's own ``limiter`` so successive buffers are limited as one
- continuous stream; without one, each call is limited in isolation, which is
- what a single self-contained buffer wants.
+ - 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
- if gain < 1.0:
- return scaled
- limiter = limiter if limiter is not None else PeakLimiter()
- limited = limiter.process(scaled, sample_rate)
- # The limiter holds the ceiling on its own; this only catches a sample that
- # slipped past its ramp (a peak in the first millisecond after a seam). One
- # cheap comparison, and the clip itself is skipped when nothing escaped.
- if limited.size and float(np.max(np.abs(limited))) > 1.0:
- limited = np.clip(limited, -1.0, 1.0)
- return limited
-
-
-def apply_output_gain_pcm16(
- pcm: bytes,
- volume: float,
- *,
- sample_rate: int = _DEFAULT_SAMPLE_RATE,
- limiter: PeakLimiter | None = None,
-) -> bytes:
+ 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 (+ limiter on boost) -> int16``, so a headless
+ ``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.
@@ -247,8 +102,8 @@ def apply_output_gain_pcm16(
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, sample_rate=sample_rate, limiter=limiter)
- # Back to int16: the limiter keeps the signal under full scale, but clip as a
- # hard guard against a rounding/edge overshoot, then round-to-nearest.
+ 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.py
index d8bd0ec2ce..db2c5f5d8d 100644
--- a/jarvis/audio/player.py
+++ b/jarvis/audio/player.py
@@ -30,7 +30,7 @@ else:
from jarvis.audio import echo_reference, level_tap, topology
from jarvis.audio.device_select import is_legacy_primary_mapper
-from jarvis.audio.gain import PeakLimiter, apply_output_gain, clamp_volume
+from jarvis.audio.gain import apply_output_gain, clamp_volume
from jarvis.core.events import AudioOutFirst
from jarvis.core.protocols import AudioChunk
@@ -1159,29 +1159,15 @@ class AudioPlayer:
# bounded, benign contention, deliberately not per sub-block.
level_delay_s = self.output_latency_s if feed_level else 0.0
# Master output volume: scale the whole buffer once via the shared gain
- # helper (makeup boost + look-ahead peak 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`` defaults keep ``__new__``-built test/hot-reload instances
- # (which skip ``__init__``) at unity instead of crashing.
- #
- # The limiter is per-player and lives across writes: a sentence reaches
- # here as a train of ~120 ms buffers, and limiting each one in isolation
- # would restart its gain ramp at every seam. It re-arms itself after a
- # silent gap, so an utterance never opens mid-duck.
- limiter = getattr(self, "_output_limiter", None)
- if limiter is None:
- limiter = PeakLimiter()
- self._output_limiter = limiter
- arr_out = apply_output_gain(
- arr_f,
- getattr(self, "_volume", 1.0),
- sample_rate=device_rate,
- limiter=limiter,
- )
+ # 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_out.shape[0], block):
out = arr_out[start:start + block]
@@ -1584,12 +1570,6 @@ class AudioPlayer:
(PortAudio abort behaves identically on Windows/macOS/Linux).
"""
level_tap.reset_playing()
- # The waveform this limiter was riding is discarded, so its gain state
- # is stale. Without this, an answer starting inside the limiter's own
- # release window would open quiet and audibly swell.
- limiter = getattr(self, "_output_limiter", None)
- if limiter is not None:
- limiter.reset()
with self._get_stream_state_lock():
self._playback_generation = (
getattr(self, "_playback_generation", 0) + 1
@@ -1627,12 +1607,6 @@ class AudioPlayer:
# Barge-in discards the buffered tail, so the UI must stop showing the
# speaking equalizer for audio that will never play.
level_tap.reset_playing()
- # The waveform this limiter was riding is discarded, so its gain state
- # is stale. Without this, an answer starting inside the limiter's own
- # release window would open quiet and audibly swell.
- limiter = getattr(self, "_output_limiter", None)
- if limiter is not None:
- limiter.reset()
with self._get_stream_state_lock():
self._playback_generation = (
getattr(self, "_playback_generation", 0) + 1
diff --git a/jarvis/browser_voice/session.py b/jarvis/browser_voice/session.py
index 49693066b1..c39d68c423 100644
--- a/jarvis/browser_voice/session.py
+++ b/jarvis/browser_voice/session.py
@@ -105,11 +105,6 @@ class BrowserVoiceSession:
self._started_at = time.time()
self._turns = 0
- # Master-volume limiter for this socket, built on first use so importing
- # browser_voice still costs no numpy. Stateful across chunks, so an
- # utterance streamed as many frames is limited as one continuous signal
- # instead of restarting its gain ramp at every frame boundary.
- self._out_limiter: Any | None = None
self._speaking = False
self._processing = False
self._tts_task: asyncio.Task[None] | None = None
@@ -259,9 +254,8 @@ class BrowserVoiceSession:
the number of binary frames sent. Cancellable: a barge-in cancels the
underlying task mid-stream.
"""
- from jarvis.audio.gain import ( # noqa: PLC0415 — lazy: keep cold-import light
- PeakLimiter,
- apply_output_gain_pcm16,
+ 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
@@ -269,8 +263,6 @@ class BrowserVoiceSession:
# 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)
- if self._out_limiter is None:
- self._out_limiter = PeakLimiter()
self._speaking = True
sent = 0
@@ -311,12 +303,7 @@ class BrowserVoiceSession:
)
if rate != TTS_SAMPLE_RATE:
pcm = resample_pcm16(pcm, rate, TTS_SAMPLE_RATE)
- pcm = apply_output_gain_pcm16(
- pcm,
- vol,
- sample_rate=TTS_SAMPLE_RATE,
- limiter=self._out_limiter,
- )
+ pcm = apply_output_gain_pcm16(pcm, vol)
await self._send_binary(pcm)
sent += 1
@@ -375,10 +362,6 @@ class BrowserVoiceSession:
self._tts_task.cancel()
if self._browser_tts_done is not None:
self._browser_tts_done.set()
- if self._out_limiter is not None:
- # The cancelled audio's gain state must not carry into the reply
- # that follows, or it would open quiet and audibly swell.
- self._out_limiter.reset()
self._speaking = False
try:
await self._send_json({"type": "tts_cancel"})
diff --git a/jarvis/telephony/session.py b/jarvis/telephony/session.py
index 4adbe32df8..bc29629602 100644
--- a/jarvis/telephony/session.py
+++ b/jarvis/telephony/session.py
@@ -143,11 +143,6 @@ class TelephonyCallSession:
self._in_resampler = Resampler(TWILIO_SAMPLE_RATE, STT_SAMPLE_RATE)
self._out_resampler = Resampler(TTS_SAMPLE_RATE, TWILIO_SAMPLE_RATE)
- # Master-volume limiter for this call, built on first use so importing
- # telephony still costs no numpy. Like the resampler it is stateful
- # across frames, so an utterance sent as many 20 ms frames is limited as
- # one continuous signal instead of restarting at every frame boundary.
- self._out_limiter: Any | None = None
self._endpointer = EnergyEndpointer(sample_rate=STT_SAMPLE_RATE)
self._started_at = time.time()
@@ -453,11 +448,9 @@ class TelephonyCallSession:
# 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 PeakLimiter, apply_output_gain_pcm16
+ from jarvis.audio.gain import apply_output_gain_pcm16
vol = getattr(getattr(self._config, "tts", None), "volume", 1.0)
- if self._out_limiter is None:
- self._out_limiter = PeakLimiter()
self._speaking = True
sent = 0
@@ -475,12 +468,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,
- sample_rate=TWILIO_SAMPLE_RATE,
- limiter=self._out_limiter,
- )
+ pcm8 = apply_output_gain_pcm16(pcm8, vol)
ulaw = pcm16_to_ulaw(pcm8)
for frame in frame_ulaw(ulaw):
await self._send_media(frame)
@@ -536,10 +524,6 @@ class TelephonyCallSession:
if self._tts_task is not None and not self._tts_task.done():
self._tts_task.cancel()
self._out_resampler.reset()
- if self._out_limiter is not None:
- # Same reason as the resampler: the discarded audio's gain state
- # must not carry into the next utterance.
- self._out_limiter.reset()
self._speaking = False
# -- outbound primitives ----------------------------------------------
diff --git a/tests/unit/audio/test_gain.py b/tests/unit/audio/test_gain.py
index 87c3a3e443..0c2191ecfc 100644
--- a/tests/unit/audio/test_gain.py
+++ b/tests/unit/audio/test_gain.py
@@ -1,16 +1,10 @@
"""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 look-ahead peak
-limiter keeps the boost under full scale WITHOUT distorting it, 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.
-
-The distortion tests are the reason this module was rewritten on 2026-08-25: the
-previous static ``tanh`` curve measured ~22% THD on a 0.5 peak at 100% volume,
-heard as a rasp on loud syllables. A limiter rides the gain instead of bending
-the wave, so the same loudness must now arrive essentially harmonic-free.
+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
@@ -63,86 +57,15 @@ def test_attenuation_below_unity_is_linear():
assert np.allclose(out, 0.2, atol=1e-4)
-def _thd_percent(signal, sample_rate: int, freq: float) -> float:
- """Total harmonic distortion of a limited tone, in percent."""
- spectrum = np.abs(np.fft.rfft(np.asarray(signal, dtype=np.float64) * np.hanning(len(signal))))
-
- def _bin_energy(harmonic: int) -> float:
- index = int(round(harmonic * freq * len(signal) / sample_rate))
- return float(spectrum[index - 2:index + 3].sum()) if index + 3 < len(spectrum) else 0.0
-
- fundamental = _bin_energy(1)
- harmonics = sum(_bin_energy(n) ** 2 for n in range(2, 12))
- return float(np.sqrt(harmonics) / fundamental * 100.0) if fundamental else 0.0
-
-
-def _tone(peak: float, sample_rate: int = 24_000, freq: float = 220.0, seconds: float = 1.0):
- t = np.arange(int(sample_rate * seconds)) / sample_rate
- return (np.sin(2 * np.pi * freq * t) * peak).astype(np.float32)
-
-
-def test_boost_adds_no_audible_distortion():
- """The whole point of the rewrite: loud input stays harmonic-free.
-
- The retired tanh curve produced 8% THD here at peak 0.3 and 22% at 0.5.
- """
- for peak in (0.3, 0.5, 0.9):
- out = gain.apply_output_gain(
- _tone(peak), 1.0, sample_rate=24_000, limiter=gain.PeakLimiter()
- )
- assert _thd_percent(out, 24_000, 220.0) < 1.0, f"distortion at peak {peak}"
-
-
-def test_limiter_holds_the_ceiling_from_the_first_sample():
- for peak in (0.3, 0.5, 0.9, 4.0):
- out = gain.apply_output_gain(
- _tone(peak), 1.0, sample_rate=24_000, limiter=gain.PeakLimiter()
- )
- assert float(np.max(np.abs(out))) <= 1.0
- if peak * gain._MAKEUP_GAIN > 1.0:
- # Loud enough to be limited: it should sit ON the ceiling, not under
- # it — a limiter that overshoots its target is just an attenuator.
- assert float(np.max(np.abs(out))) >= gain._LIMIT_CEILING - 1e-3
-
-
-def test_streamed_buffers_limit_exactly_like_one_pass():
- """A stateful limiter must make buffer seams invisible.
-
- Feeding the same signal as many buffers has to yield the identical waveform,
- or the seams themselves would be audible as level steps.
- """
- signal = _tone(0.6)
- streaming = gain.PeakLimiter()
- chunk = int(24_000 * 0.12)
- streamed = np.concatenate([
- gain.apply_output_gain(
- signal[i:i + chunk], 1.0, sample_rate=24_000, limiter=streaming
- )
- for i in range(0, len(signal), chunk)
- ])
- one_pass = gain.apply_output_gain(
- signal, 1.0, sample_rate=24_000, limiter=gain.PeakLimiter()
- )
- assert np.array_equal(streamed, one_pass)
-
-
-def test_limiter_reset_reopens_at_unity():
- limiter = gain.PeakLimiter()
- limiter.process(_tone(0.9, seconds=0.2) * 4.0, 24_000)
- assert limiter._gain < 1.0 # ducked by the loud pass
- limiter.reset()
- quiet = _tone(0.1, seconds=0.05)
- assert np.allclose(limiter.process(quiet, 24_000), quiet) # untouched again
-
-
-def test_limiter_accepts_stereo_and_links_the_channels():
- mono = _tone(0.5, seconds=0.2) * 4.0
- stereo = np.column_stack((mono, mono * 0.25)).astype(np.float32)
- out = gain.PeakLimiter().process(stereo, 24_000)
- assert out.shape == stereo.shape
- assert float(np.max(np.abs(out))) <= 1.0
- # One shared gain curve: the quiet channel keeps its exact 1:4 ratio.
- assert np.allclose(out[:, 1] * 4.0, out[:, 0], atol=1e-6)
+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():