Repository navigation
fix(audio): silence-gate uses absolute RMS threshold, not adaptive floor (#2253) - #2322
Conversation
…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]>
📝 WalkthroughWalkthroughThe 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
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🟡 MinorUpdate 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 | 🟡 MinorKeep 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.0fnow has to stay consistent betweenReactive,Processor, and existing audio modules such as auto-gain. A sharedconstexprwould avoid silent drift between pipeline owners.Proposed direction
- constexpr float kSilenceRmsThreshold = 10.0f; - mContext->setSilent(processedSample.rms() < kSilenceRmsThreshold); + mContext->setSilent(processedSample.rms() < kSilenceRmsThreshold);Define
kSilenceRmsThresholdonce in an audio-internal header and use it from bothaudio_reactive.cpp.hppandaudio_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
📒 Files selected for processing (5)
ci/util/fbuild_compiledb.pysrc/fl/audio/audio_processor.cpp.hppsrc/fl/audio/audio_reactive.cpp.hpptests/fl/audio/audio_reactive.cpptests/fl/audio/detector/tempo_analyzer.hpp
| from ci.util.global_interrupt_handler import handle_keyboard_interrupt | ||
|
|
||
| handle_keyboard_interrupt(ki) |
There was a problem hiding this comment.
🧩 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 -30Repository: 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 -100Repository: 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.pyRepository: 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.
| 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.
| // 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); |
There was a problem hiding this comment.
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.
CI statusThe only failing checks on this PR are the two This is a pre-existing CI infrastructure issue on All audio-specific checks pass:
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. |
Summary
Fixes a pre-existing regression where
Reactive::dominantFrequency/magnitude/spectralFluxdecayed to zero during loud audio.Root cause:
NoiseFloorTracker::update()initializesmCurrentFloor = combinedLevelon the first sample. For a steady loud signal the floor immediately matches the level, soisAboveFloor(level)stays false forever (level > floor + hysteresisMarginnever holds). Reactive (merged in #2309) and Processor wiredsetSilent(!isAboveFloor(rms))— so a loud 1 kHz tone was flagged as silent on every frame, andSilenceEnvelopedecayed 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_reactiveand one infl_audio_detectorswere failing on master:audio::Reactive - dominant frequency uses log-spaced bin centersaudio::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 preservedThe "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.pywas blocking this branch's lint gate; fixed in-place.Test plan
bash test fl_audio_audio_reactive --cpp— passesbash test fl_audio_detectors --cpp— passesbash test fl_audio_audio_reactive --debug— passes (ASAN/LSAN/UBSAN clean)bash test fl_audio_detectors --debug— passesbash lint— clean🤖 Generated with Claude Code
Summary by CodeRabbit
Release Notes
Bug Fixes
Tests
Chores