Skip to content

fix(audio): volume not returning to zero when audio stops #2253

Closed

Description

@zackees

Origin

Reported by @ewowi in #2193 (comment)

Problem

When audio playback stops, the volume value does not return to zero. The low/mid/high frequency bands appear to behave correctly, but the volume metric retains a non-zero value even with no audio input.

Video

See the video in the original comment — the first 3 columns (low, mid, high) go to zero correctly when music stops, but the 5 yellow columns (volume, major peak, magnitude, normalizedBPM) do not fully drop to zero.

Side Note

@ewowi also reported flickering on ESP32-S3 with RMT in the same comment — that may be tracked separately.


@ewowi please continue the discussion here regarding the volume-not-zero issue. What board/setup are you using and which audio source?

Activity

  1. zackees commented on Apr 12, 2026

    @zackees
    MemberAuthor

    Root Cause Analysis

    I've traced through the audio pipeline to understand why volume doesn't return to zero when music stops. There are actually multiple interacting issues across different code paths.


    1. Vibe getVol() — Self-normalization converges back to 1.0

    Files: src/fl/audio/detector/vibe.cpp.hpp:82-93, vibe.h:84

    The MilkDrop v2.25c algorithm is self-normalizing by design. Relative levels (mImmRel) are computed as:

    mImmRel[i] = mImm[i] / mLongAvg[i];   // immediate / long-term-average
    

    When audio stops:

    1. mImm[i] drops to near-zero (ambient noise floor, not true zero on a mic)
    2. mAvg[i] decays at 50%/frame at 30fps → near-zero within ~1 second
    3. mLongAvg[i] decays at 0.992/frame → tau of ~4.2 seconds (very slow)
    4. Initially: mImmRel = tiny_noise / large_mLongAvg ≈ 0 ✓ looks correct briefly
    5. But as mLongAvg decays toward the noise floor, the ratio converges: noise / noise → 1.0
    6. And when mLongAvg < 0.001f (line 86), the code clamps: mImmRel[i] = 1.0f — hardcoded to 1.0!

    Result: getVol() returns (1.0 + 1.0 + 1.0) / 3 = 1.0 during silence. This is by design in MilkDrop (always self-normalizes to 1.0 for any steady-state signal) but is surprising for LED use cases where you expect zero = silence.

    2. Reactive getVolume() — EnergyAnalyzer adaptive normalization

    Files: src/fl/audio/detector/energy_analyzer.cpp.hpp:40-48

    float runningMax = mRunningMaxFilter.update(mCurrentRMS, dt);
    if (runningMax < 1.0f) { runningMax = 1.0f; }       // floor at 1.0
    mNormalizedRMS = min(1.0f, mCurrentRMS / runningMax);
    

    The runningMax floor of 1.0 means when audio is silence-level (RMS << 1.0), mNormalizedRMS ≈ 0. This should work correctly. However, the AttackDecayFilter with 2s decay means runningMax stays elevated for ~2 seconds after music stops, which could cause a brief period where volume appears non-zero if there's any mic noise.

    3. dominantFrequency — Never resets to zero

    File: src/fl/audio/audio_reactive.cpp.hpp:272-284, 452

    // Always finds SOME bin as "dominant", even in silence:
    if (frequencyBins[i] > maxMagnitude) { maxBin = i; }
    mCurrentData.dominantFrequency = mFFTBins.binToFreq(maxBin);
    
    // In smoothResults — no decay, direct copy:
    mSmoothedData.dominantFrequency = mCurrentData.dominantFrequency;
    

    During silence, FFT bins contain numerical noise → the algorithm always picks some bin as dominant. The frequency locks on whatever noise bin is highest, never returning to zero.

    4. magnitude — Depends on noise floor

    Magnitude is the raw value of the dominant bin. It should approach near-zero during silence, but won't be exactly zero if there's any mic noise or FFT numerical residue.

    5. BPM — Very slow hypothesis decay

    File: src/fl/audio/detector/tempo_analyzer.cpp.hpp

    BPM hypotheses decay at 5%/frame (score *= 0.95f). After music stops:

    • 30 frames (~1s): still 21% of original score
    • 60 frames (~2s): still 4.6%
    • Removed only when score < 0.1f
    • Plus a 21-tap median filter adds additional lag

    BPM can persist for 5-10+ seconds into silence.


    Why bass/mid/treb Show Correctly But Volume Doesn't

    @ewowi mentioned the first 3 columns (low, mid, high) work correctly. These likely come from the Reactive class's getBass()/getMid()/getTreble() which are simple averages of FFT frequency bins (no self-normalization):

    float getBass() const;    // Average of bins 0-1
    float getMid() const;     // Average of bins 6-7 
    float getTreble() const;  // Average of bins 14-15
    

    These are raw FFT values → go to zero when audio stops ✓

    But getVol() from Vibe (or getVolume() from Reactive) uses self-normalizing algorithms that don't converge to zero.


    Options

    Option A: Add silence detection to Vibe (recommended)

    Add a noise gate that detects when absolute energy (mImm) drops below a threshold and forces relative levels to 0:

    // In Vibe::update(), after computing mImmRel:
    float totalEnergy = mImm[0] + mImm[1] + mImm[2];
    if (totalEnergy < silenceThreshold) {
        for (int i = 0; i < 3; i++) {
            mImmRel[i] = 0.0f;
            mAvgRel[i] = 0.0f;
        }
    }
    

    Pro: Simple, preserves MilkDrop algorithm during playback, clean zero in silence.
    Con: Need to pick a good threshold; could suppress very quiet audio.

    Option B: Fix the 0.001f floor clamp

    Change line 87 from mImmRel[i] = 1.0f to mImmRel[i] = 0.0f:

    if (mLongAvg[i] < 0.001f) {
        mImmRel[i] = 0.0f;   // was 1.0f
        mAvgRel[i] = 0.0f;   // was 1.0f
    }
    

    Pro: Trivial fix, eliminates the "jump to 1.0" problem.
    Con: Changes MilkDrop semantics. During startup before any audio, levels would read 0 instead of 1.0 (may affect existing users who use Vibe levels as multipliers).

    Option C: Add volumeRaw or non-normalized volume API

    Expose the raw RMS-based volume more prominently alongside the self-normalizing one, and document the difference clearly.

    Option D: Add noise gate to dominantFrequency and BPM

    For dominantFrequency: set to 0 when max magnitude < threshold.
    For BPM: add faster decay or hard-reset when silence detected for N frames.

    Option E: Combination (A + D)

    Silence detection in Vibe + noise-gate for dominant frequency + faster BPM decay during silence. This gives the most complete fix across all metrics.


    My Recommendation

    Option E (combination) gives the best user experience. The self-normalization is valuable during playback but misleading during silence. A silence gate that forces outputs to zero when absolute energy is below a threshold solves the problem without breaking the MilkDrop algorithm's behavior during music.

    The silence threshold could be auto-calibrated from the noise floor tracker that already exists in the signal conditioner (ReactiveConfig::enableNoiseFloorTracking).

  2. added
    area: core
    status: triage
    on Apr 16, 2026
  3. zackees commented on Apr 18, 2026

    @zackees
    MemberAuthor

    Fix shipped

    Landed as four PRs on master:

    PR Scope
    #2306 Phase 1 foundations — Context::isSilent() flag populated from NoiseFloorTracker::isAboveFloor() in both Processor and Reactive; new reusable SilenceEnvelope helper class (exponential decay toward target during silence, pass-through during audio, zero-lag snap-back on re-attack). Plus design doc at docs/audio_silence_gate_design.md.
    #2309 Reactive spectral gate — dominantFrequency, magnitude, spectralFlux now decay to 0 in silence (tau=0.2s). Previously locked onto numerical FFT noise.
    #2311 TempoAnalyzer confidence fade — BPM confidence decays (tau=2.0s) in silence while the raw BPM estimate is preserved so re-entry is seamless.
    #2312 Vibe silence gate — getVol() / getBass() / getMid() / getTreb() + smoothed *Att() variants now decay to ~0 in silence (tau=0.3s). Fixes the original user-visible symptom @ewowi reported. The MilkDrop self-normalization algorithm is unchanged during audio.

    How it works

    NoiseFloorTracker (already in the codebase, previously orphaned) now publishes a per-frame silence boolean on Context. Detectors that want silence-aware outputs embed a SilenceEnvelope and call env.update(context->isSilent(), rawValue, dt) — during audio it's a pass-through; during silence it exponentially decays toward zero with a per-detector tau.

    Activation

    • Reactive: silence gate is live by default (ReactiveConfig::enableNoiseFloorTracking defaults to true).
    • Processor: opt-in via enableNoiseFloorTracker(true) — default remains off to preserve existing behavior for users who construct their own detector chains.

    Out of scope (not fixed by these PRs)

    • ESP32-S3 RMT flickering — @ewowi mentioned this as a side note in the original comment. That's a separate issue; if it's still reproducible, please open a new issue with board/driver details and a minimal sketch.
    • Unified AudioLevel value type — considered and documented in the design doc; rejected for this fix as too churn-heavy. Can be layered on later if demand emerges.

    Closing as completed. Please reopen if the volume-in-silence symptom returns under real-world conditions — we have test coverage for the synthetic case but would love hardware confirmation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: corestatus: triage

    Type

    No type

    Projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions