Skip to content

fix(audio): silence-gate uses absolute RMS threshold, not adaptive floor (#2253) - #2322

Merged
zackees merged 1 commit into
masterfrom
fix-silence-gate-absolute-rms-2253
Apr 18, 2026
Merged

zackees merged 1 commit into
masterfrom
fix-silence-gate-absolute-rms-2253

Conversation

@zackees

@zackees zackees commented Apr 18, 2026 •

Copy link
Copy Markdown
Member

Summary

Fixes a pre-existing regression where Reactive::dominantFrequency / magnitude / spectralFlux decayed to zero during loud audio.

Root cause: NoiseFloorTracker::update() initializes mCurrentFloor = combinedLevel on the first sample. For a steady loud signal the floor immediately matches the level, so isAboveFloor(level) stays false forever (level > floor + hysteresisMargin never holds). Reactive (merged in #2309) and Processor wired setSilent(!isAboveFloor(rms)) — so a loud 1 kHz tone was flagged as silent on every frame, and SilenceEnvelope decayed all three spectral metrics to 0.

Fix: gate silence on an absolute RMS threshold (10.0, matching NoiseFloorTrackerConfig::minFloor). The noise floor is still tracked for detector internals, but "no signal present" is an absolute-level concept, not an adaptive-floor one.

Tests restored

Three tests in fl_audio_audio_reactive and one in fl_audio_detectors were failing on master:

  • audio::Reactive - dominant frequency uses log-spaced bin centers
  • audio::Reactive - spectral metrics decay to zero on silence (FastLED#2253)
  • audio::Reactive - spectral metrics are pass-through during loud audio (FastLED#2253)
  • audio::detector::TempoAnalyzer - confidence fades in silence, BPM preserved

The "decay to zero" tests were only passing by accident of the buggy silent-during-loud shortcut; with the fix they now rely on actual exponential decay, so phase 2 was extended to 3s (audio_reactive, tau=0.2s → 15 taus) and 8s (tempo_analyzer, tau=2s → 4 taus) so the assertions hold on the clean math.

Also

Pre-existing KBI003 lint in ci/util/fbuild_compiledb.py was blocking this branch's lint gate; fixed in-place.

Test plan

  • bash test fl_audio_audio_reactive --cpp — passes
  • bash test fl_audio_detectors --cpp — passes
  • bash test fl_audio_audio_reactive --debug — passes (ASAN/LSAN/UBSAN clean)
  • bash test fl_audio_detectors --debug — passes
  • bash lint — clean

🤖 Generated with Claude Code

Summary by CodeRabbit

Release Notes

  • Bug Fixes

    • Updated audio silence detection to use a fixed RMS threshold instead of adaptive tracking, improving consistency in signal classification.
  • Tests

    • Adjusted audio reactive and tempo analyzer test expectations to reflect updated silence detection behavior.
  • Chores

    • Enhanced interrupt handling in the build system.

…oor (#2253)

NoiseFloorTracker.update() initializes its floor to the first observed
level on the first sample. For a steady loud signal, that makes
isAboveFloor() stuck at false — floor catches up to level, so
level > floor+hysteresisMargin never holds. Reactive (PR #2309) and
Processor wired setSilent() to !isAboveFloor(), which caused a LOUD
1 kHz tone to be flagged as silent, then decayed dominantFrequency
and magnitude to zero via SilenceEnvelope.

Fix: gate silence on an absolute RMS threshold (10.0, matching
NoiseFloorTrackerConfig::minFloor default). The noise-floor estimate
is still tracked for detector internals but is no longer the silence
primitive. "No signal present" is an absolute-level concept.

Tests:
- audio_reactive.cpp: extend phase 2 silence to 3s (~15 taus) so
  pure-exponential decay reaches the < 0.01 assertion instead of
  depending on the now-fixed buggy silent-during-loud shortcut.
- tempo_analyzer.hpp: extend phase 2 silence to 8s (tau=2s → 4 taus)
  so exp(-4) ≈ 0.018 decay is well under 0.05 even when
  liveConfidence comes in high; prior 5s was flaky at the threshold.

Also fix pre-existing KBI003 lint in ci/util/fbuild_compiledb.py
that was blocking this branch's lint gate.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@coderabbitai

coderabbitai Bot commented Apr 18, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

The pull request modifies silence detection logic in the audio processing pipeline by replacing adaptive noise-floor tracking with a fixed RMS threshold (10.0f), updates corresponding tests to extend silence durations and adjust decay expectations, and enhances keyboard interrupt handling in the build system with an explicit handler invocation.

Changes

Cohort / File(s) Summary
Silence Detection Logic
src/fl/audio/audio_processor.cpp.hpp, src/fl/audio/audio_reactive.cpp.hpp
Replaced adaptive noise-floor tracker-based silence detection with fixed RMS threshold (conditioned.rms() < 10.0f and processedSample.rms() < 10.0f respectively) in Processor::update() and Reactive::processSample().
Audio Test Updates
tests/fl/audio/audio_reactive.cpp, tests/fl/audio/detector/tempo_analyzer.hpp
Extended silence durations (3 seconds and ~8 seconds respectively) and updated decay expectations and comments in silence-related tests to reflect longer stabilization periods.
Build System
ci/util/fbuild_compiledb.py
Added explicit invocation of global interrupt handler within KeyboardInterrupt exception handling while preserving exception re-raising behavior.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 Hops forth with glee
Adaptive whispers fade away,
A steadfast threshold takes the stage—
Ten point zero hushes true,
Tests extend their patient wait,
Keyboard bows with grace!

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately summarizes the main change: replacing adaptive noise-floor logic with an absolute RMS threshold (10.0) for silence detection across audio processing components.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix-silence-gate-absolute-rms-2253

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (2)
tests/fl/audio/detector/tempo_analyzer.hpp (1)

273-333: ⚠️ Potential issue | 🟡 Minor

Update the test preamble to match the new 8-second silence window.

Line 277 still says the silence phase runs for ~3s, but Line 333 now runs 350 frames, which is ~8s at 23 ms/frame.

Proposed comment cleanup
-    // 3. Switch to silence with context->setSilent(true) for ~3s.
+    // 3. Switch to silence with context->setSilent(true) for ~8s.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/fl/audio/detector/tempo_analyzer.hpp` around lines 273 - 333, The test
preamble comment about the silence phase duration is out of date: change the
text that currently says "~3s" to reflect the actual ~8s window used in the test
(silenceFrames = 350 at frameIntervalMs = 23ms → ~8s); update any nearby
explanatory lines referencing tau/duration so they match the
silenceFrames/frameIntervalMs calculation and ensure the comment mentions the
context->setSilent(true) silence phase driven by silenceFrames. Use symbols:
frameIntervalMs, silenceFrames, and context->setSilent(true) /
analyzer.update(...) to locate the relevant comment to edit.
tests/fl/audio/audio_reactive.cpp (1)

2069-2113: ⚠️ Potential issue | 🟡 Minor

Keep the decay-duration comments consistent with the 3-second loop.

Line 2106 runs 3 seconds, but Line 2105 still says 2.5s/~11 taus, and Line 2073 still says 1 second/5 taus.

Proposed comment cleanup
-    // snap the three fields to ~0 within 1 second (5 * tau).
+    // snap the three fields to ~0 within about 3 seconds (15 * tau).
...
-    // about exp(-t/0.2) < 1e-5 → t ≳ 2.3s. Run 2.5s of silence (~11 taus).
+    // about exp(-t/0.2) < 1e-5 → t ≳ 2.3s. Run 3s of silence (~15 taus).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@tests/fl/audio/audio_reactive.cpp` around lines 2069 - 2113, The comments
about silence duration are inconsistent with the actual loop using
kSilenceSeconds = 3; update the descriptive comments that mention "2.5s/~11
taus" and "After ~15 taus" to reflect the 3-second run (tau=0.2s → 3s ≈ 15 taus)
and ensure the earlier Phase 1 comment about "1 second (5 * tau)" remains
correct; look for references to kSilenceSeconds, the tau=0.2s note, and the
trailing comment after the silence loop near audio::Reactive /
reactive.processSample and change the wording so all durations and tau counts
consistently state 3s (~15 taus).
🧹 Nitpick comments (1)
src/fl/audio/audio_reactive.cpp.hpp (1)

201-203: Keep the absolute silence threshold in one shared definition.

10.0f now has to stay consistent between Reactive, Processor, and existing audio modules such as auto-gain. A shared constexpr would avoid silent drift between pipeline owners.

Proposed direction
-        constexpr float kSilenceRmsThreshold = 10.0f;
-        mContext->setSilent(processedSample.rms() < kSilenceRmsThreshold);
+        mContext->setSilent(processedSample.rms() < kSilenceRmsThreshold);

Define kSilenceRmsThreshold once in an audio-internal header and use it from both audio_reactive.cpp.hpp and audio_processor.cpp.hpp.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fl/audio/audio_reactive.cpp.hpp` around lines 201 - 203, The literal
silence threshold (kSilenceRmsThreshold = 10.0f) is duplicated; extract it to a
single shared constexpr in an audio-internal header (e.g., declare constexpr
float kSilenceRmsThreshold in a new or existing audio/internal header inside the
audio namespace) and replace the local literal in audio_reactive.cpp.hpp (where
mConfig.enableNoiseFloorTracking, mContext->setSilent, processedSample.rms() are
used) and in audio_processor.cpp.hpp / auto-gain modules to include that header
and reference the shared constant so all pipeline owners use the same value.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@ci/util/fbuild_compiledb.py`:
- Around line 87-89: The local import of handle_keyboard_interrupt currently
inside the except KeyboardInterrupt block should be moved to the module-level
imports at the top of the file to satisfy import ordering; locate the import
statement for handle_keyboard_interrupt and hoist it along with the other
imports, leaving the except KeyboardInterrupt block to simply call
handle_keyboard_interrupt(ki) without performing the import there.

In `@src/fl/audio/audio_processor.cpp.hpp`:
- Around line 63-73: The documentation for Context::isSilent() is out of date:
code now sets the silence flag via an absolute RMS check (in the block guarded
by mNoiseFloorTrackingEnabled where conditioned.isValid() is true) using
conditioned.rms() < kSilenceRmsThreshold and Context::setSilent(...), not via
NoiseFloorTracker::isAboveFloor(); update the comment/API doc in audio_context.h
to describe the new predicate (absolute RMS threshold behavior, mention
kSilenceRmsThreshold and that setSilent() is driven by conditioned.rms() when
NFT is enabled) so detector authors see the correct contract.

---

Outside diff comments:
In `@tests/fl/audio/audio_reactive.cpp`:
- Around line 2069-2113: The comments about silence duration are inconsistent
with the actual loop using kSilenceSeconds = 3; update the descriptive comments
that mention "2.5s/~11 taus" and "After ~15 taus" to reflect the 3-second run
(tau=0.2s → 3s ≈ 15 taus) and ensure the earlier Phase 1 comment about "1 second
(5 * tau)" remains correct; look for references to kSilenceSeconds, the tau=0.2s
note, and the trailing comment after the silence loop near audio::Reactive /
reactive.processSample and change the wording so all durations and tau counts
consistently state 3s (~15 taus).

In `@tests/fl/audio/detector/tempo_analyzer.hpp`:
- Around line 273-333: The test preamble comment about the silence phase
duration is out of date: change the text that currently says "~3s" to reflect
the actual ~8s window used in the test (silenceFrames = 350 at frameIntervalMs =
23ms → ~8s); update any nearby explanatory lines referencing tau/duration so
they match the silenceFrames/frameIntervalMs calculation and ensure the comment
mentions the context->setSilent(true) silence phase driven by silenceFrames. Use
symbols: frameIntervalMs, silenceFrames, and context->setSilent(true) /
analyzer.update(...) to locate the relevant comment to edit.

---

Nitpick comments:
In `@src/fl/audio/audio_reactive.cpp.hpp`:
- Around line 201-203: The literal silence threshold (kSilenceRmsThreshold =
10.0f) is duplicated; extract it to a single shared constexpr in an
audio-internal header (e.g., declare constexpr float kSilenceRmsThreshold in a
new or existing audio/internal header inside the audio namespace) and replace
the local literal in audio_reactive.cpp.hpp (where
mConfig.enableNoiseFloorTracking, mContext->setSilent, processedSample.rms() are
used) and in audio_processor.cpp.hpp / auto-gain modules to include that header
and reference the shared constant so all pipeline owners use the same value.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: f04c9d40-a880-4717-928f-46c24569b154

📥 Commits

Reviewing files that changed from the base of the PR and between 5e6783e and 4074db7.

📒 Files selected for processing (5)
  • ci/util/fbuild_compiledb.py
  • src/fl/audio/audio_processor.cpp.hpp
  • src/fl/audio/audio_reactive.cpp.hpp
  • tests/fl/audio/audio_reactive.cpp
  • tests/fl/audio/detector/tempo_analyzer.hpp

Comment on lines +87 to +89
from ci.util.global_interrupt_handler import handle_keyboard_interrupt

handle_keyboard_interrupt(ki)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Check for potential circular import between fbuild_compiledb and global_interrupt_handler
rg -n -C2 'fbuild_compiledb|from ci\.util\.fbuild_compiledb' ci/util/global_interrupt_handler.py 2>/dev/null
rg -n 'import' ci/util/global_interrupt_handler.py | head -30

Repository: FastLED/FastLED

Length of output: 274


🏁 Script executed:

# Get the full fbuild_compiledb.py file to understand context
wc -l ci/util/fbuild_compiledb.py
cat -n ci/util/fbuild_compiledb.py | head -100

Repository: FastLED/FastLED

Length of output: 4522


🏁 Script executed:

# Check if handle_keyboard_interrupt is used elsewhere in the file
rg -n "handle_keyboard_interrupt" ci/util/fbuild_compiledb.py

Repository: FastLED/FastLED

Length of output: 181


Move handle_keyboard_interrupt import to the top of the file.

The import on line 87 is used only in the except KeyboardInterrupt block and violates the import ordering guideline, which requires all imports (standard library, third-party, local) to be at the top of the file. There is no circular-import dependency blocking this move, so hoist it alongside the other imports.

Proposed change
 import subprocess
 import sys
 from pathlib import Path
+
+from ci.util.global_interrupt_handler import handle_keyboard_interrupt
     except KeyboardInterrupt as ki:
         # Per project guideline: all try/except blocks must handle
         # KeyboardInterrupt before broader exceptions so Ctrl-C is never
         # swallowed.
-        from ci.util.global_interrupt_handler import handle_keyboard_interrupt
-
         handle_keyboard_interrupt(ki)
         raise
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
from ci.util.global_interrupt_handler import handle_keyboard_interrupt
handle_keyboard_interrupt(ki)
handle_keyboard_interrupt(ki)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@ci/util/fbuild_compiledb.py` around lines 87 - 89, The local import of
handle_keyboard_interrupt currently inside the except KeyboardInterrupt block
should be moved to the module-level imports at the top of the file to satisfy
import ordering; locate the import statement for handle_keyboard_interrupt and
hoist it along with the other imports, leaving the except KeyboardInterrupt
block to simply call handle_keyboard_interrupt(ki) without performing the import
there.

Comment on lines 63 to +73
// Stage 4: Silence flag — detectors use this to gate outputs when audio stops.
// Only populated when NFT is enabled; otherwise silence is unknowable and
// stays at its default (false) after setSample() above.
//
// Uses an absolute RMS threshold rather than NFT.isAboveFloor(): the
// adaptive floor's first-sample init matches the current level, so
// isAboveFloor() stays false for any steady signal. Absolute RMS is the
// right silence primitive — a loud constant tone has large RMS.
if (mNoiseFloorTrackingEnabled && conditioned.isValid()) {
mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(conditioned.rms()));
constexpr float kSilenceRmsThreshold = 10.0f;
mContext->setSilent(conditioned.rms() < kSilenceRmsThreshold);

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Update Context::isSilent() documentation for the new predicate.

src/fl/audio/audio_context.h still says this flag is populated from NoiseFloorTracker::isAboveFloor(), but Lines 67-73 now use an absolute RMS threshold. Detector authors will otherwise read the wrong contract.

Proposed documentation update
-    // Populated per-frame by the pipeline owner (Processor / Reactive) from
-    // NoiseFloorTracker::isAboveFloor(). Detectors read this to gate their
+    // Populated per-frame by the pipeline owner (Processor / Reactive) from
+    // an absolute RMS silence threshold. Detectors read this to gate their
     // outputs during silence. Default false — detectors that check this flag
     // simply won't gate if the pipeline hasn't enabled noise-floor tracking.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@src/fl/audio/audio_processor.cpp.hpp` around lines 63 - 73, The documentation
for Context::isSilent() is out of date: code now sets the silence flag via an
absolute RMS check (in the block guarded by mNoiseFloorTrackingEnabled where
conditioned.isValid() is true) using conditioned.rms() < kSilenceRmsThreshold
and Context::setSilent(...), not via NoiseFloorTracker::isAboveFloor(); update
the comment/API doc in audio_context.h to describe the new predicate (absolute
RMS threshold behavior, mention kSilenceRmsThreshold and that setSilent() is
driven by conditioned.rms() when NFT is enabled) so detector authors see the
correct contract.

@zackees

zackees commented Apr 18, 2026

Copy link
Copy Markdown
Member Author

CI status

The only failing checks on this PR are the two wasm / wasm_compile_test builds with esbuild errors:

✘ [ERROR] Could not resolve "./vendor/three/three.module.js" (originally "three")

This is a pre-existing CI infrastructure issue on master — run 9272 (ci(project): drift-sync also sets Status=Triage on no-status items) on master also failed for the same esbuild/vendor reason. Unrelated to this PR's source changes.

All audio-specific checks pass:

  • bash test fl_audio_audio_reactive --cpp ✅
  • bash test fl_audio_audio_reactive --debug ✅ (ASAN/LSAN/UBSAN clean)
  • bash test fl_audio_detectors --cpp ✅
  • bash test fl_audio_detectors --debug ✅

Open PRs #2318 and #2321 are currently blocked by the same 4 audio-test regressions that this PR fixes. Merging this PR should unblock them.

@zackees
zackees merged commit fe5e40c into master Apr 18, 2026
6 of 82 checks passed
@zackees
zackees deleted the fix-silence-gate-absolute-rms-2253 branch August 30, 2026 22:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant