Repository navigation
feat(audio): silence gate foundations — Context::isSilent() + SilenceEnvelope (#2253) - #2306
Conversation
Two-layer design for fixing volume-not-zero-in-silence: 1. Context::isSilent() — boolean flag populated from NoiseFloorTracker 2. SilenceEnvelope — reusable decay-to-target helper detectors compose Phase 1 (parallelizable): Context plumbing + SilenceEnvelope class + tests. Phase 2 (parallelizable): Vibe / Reactive spectral / TempoAnalyzer adopt. No breaking changes; silence gating is strictly additive and opt-in via existing NoiseFloorTracker enable flag. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adds a frame-wide silence boolean on audio::Context that detectors can read to gate their outputs when audio stops. Populated from NoiseFloorTracker::isAboveFloor() by both Processor::update() and Reactive::processSample() after their existing NFT update call. Reset to false on setSample() so a stale claim can't survive a frame where NFT is disabled or the pipeline owner forgets to populate it. This is plumbing only — no detector consumes the flag yet. Default behavior is unchanged: NFT is off by default, so isSilent() returns false and detectors that check it simply won't gate. Users opt in via Processor::enableNoiseFloorTracker(true) or ReactiveConfig. Part of the fix for #2253 (volume not returning to zero). Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
New fl::audio::SilenceEnvelope composable helper that detectors embed to translate Context::isSilent() into smooth per-metric decay: - Pass-through during audio (isSilent=false returns currentValue). - Exponential decay toward Config::targetValue during silence; alpha = 1 - exp(-dt / decayTauSeconds) gives a proper first-order response independent of frame rate. - Snap-back on silence→audio transition: beats hit hard with zero attack lag, avoiding the classic compressor-release smear. - isGated(epsilon) for "fully decayed" queries; reset(initial) for explicit jumps. Registered in src/fl/audio/_build.cpp.hpp unity build. Unit tests at tests/fl/audio/silence_envelope.hpp cover pass-through, decay curve within 5% at 3*tau, snap-back, isGated threshold, non-zero targets, and degenerate zero-tau behavior. Ready for adoption by Vibe / Reactive spectral metrics / TempoAnalyzer in Phase 2 of #2253. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
📝 WalkthroughWalkthroughThis PR introduces audio silence-gating functionality to the audio processing pipeline. It adds a per-frame silence boolean to Changes
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 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 |
📊 Header Compilation PerformanceTotal Time: 988.61ms Top 5 Slowest Headers
Warnings
Full Report |
There was a problem hiding this comment.
Actionable comments posted: 4
🧹 Nitpick comments (4)
src/fl/audio/audio_reactive.cpp.hpp (1)
168-183: Minor: avoid computingprocessedSample.rms()twice.
rms()is called at L171 forNoiseFloorTracker::update()and again at L181 for the silence check. Depending on whetherSample::rms()is cached or recomputed per call, this could be wasteful. Caching locally also keeps the two NFT calls consistent ifrms()ever becomes non-idempotent.Proposed refactor
- // Step 2: Noise floor tracking (update tracker, but don't modify signal) - if (mConfig.enableNoiseFloorTracking) { - float rms = processedSample.rms(); - mNoiseFloorTracker.update(rms); - } - - // Set conditioned sample on shared Context (clears per-frame FFT cache) - mContext->setSample(processedSample); - - // Populate silence flag after setSample() resets it — detectors run via - // updateFromContext() below and will read context->isSilent(). - if (mConfig.enableNoiseFloorTracking) { - mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(processedSample.rms())); - } + // Step 2: Noise floor tracking (update tracker, but don't modify signal) + const bool nftEnabled = mConfig.enableNoiseFloorTracking; + float rms = 0.0f; + if (nftEnabled) { + rms = processedSample.rms(); + mNoiseFloorTracker.update(rms); + } + + // Set conditioned sample on shared Context (clears per-frame FFT cache) + mContext->setSample(processedSample); + + // Populate silence flag after setSample() resets it — detectors run via + // updateFromContext() below and will read context->isSilent(). + if (nftEnabled) { + mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(rms)); + }🤖 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 168 - 183, The code calls processedSample.rms() twice; compute it once and reuse it to avoid redundant work and ensure consistency: inside the block gated by mConfig.enableNoiseFloorTracking, call Sample::rms() once into a local float (e.g. rms), pass that to mNoiseFloorTracker.update(rms), then later use the same rms when calling mNoiseFloorTracker.isAboveFloor(...) to set mContext->setSilent(...); keep the conditional checks around mConfig.enableNoiseFloorTracking and preserve the call to mContext->setSample(processedSample).src/fl/audio/audio_context.cpp.hpp (1)
164-171: Consider resettingmIsSilentinclearCache()for consistency.
setSample()clears the silence flag butclearCache()does not. After a full reset the flag could retain a staletruevalue from a prior frame until the nextsetSample()call. Low-impact since the pipeline always callssetSample()each frame, but worth fixing for defensive consistency.Proposed tweak
void Context::clearCache() { mFFTCache.clear(); mFFTCacheMap.clear(); mRecyclePool.clear(); mFFTHistory.clear(); mFFTHistoryDepth = 0; mFFTHistoryIndex = 0; + mIsSilent = false; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@src/fl/audio/audio_context.cpp.hpp` around lines 164 - 171, The clearCache routine (Context::clearCache) currently clears FFT caches and history but does not reset the silence flag mIsSilent, which can leave a stale true value until setSample runs; update Context::clearCache to also set mIsSilent = false so the context is fully reset (mirror the behavior from setSample) ensuring defensive consistency after a full reset.src/fl/audio/audio_processor.cpp.hpp (1)
56-68: Minor: redundantconditioned.rms()call.Same pattern as in
Reactive::processSample:rms()is evaluated at L58 forNFT::update()and again at L67 for the silence gate. Cache the value locally to avoid the duplicate call and guarantee both NFT calls see the exact same value.Proposed refactor
- // Stage 3: Noise floor tracking (passive — updates estimate but doesn't modify signal) - if (mNoiseFloorTrackingEnabled && conditioned.isValid()) { - mNoiseFloorTracker.update(conditioned.rms()); - } - - mContext->setSample(conditioned); - - // 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. - if (mNoiseFloorTrackingEnabled && conditioned.isValid()) { - mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(conditioned.rms())); - } + // Stage 3: Noise floor tracking (passive — updates estimate but doesn't modify signal) + const bool nftActive = mNoiseFloorTrackingEnabled && conditioned.isValid(); + float condRms = 0.0f; + if (nftActive) { + condRms = conditioned.rms(); + mNoiseFloorTracker.update(condRms); + } + + mContext->setSample(conditioned); + + // 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. + if (nftActive) { + mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(condRms)); + }🤖 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 56 - 68, The code calls conditioned.rms() twice (once for mNoiseFloorTracker.update and again for mContext->setSilent), which is redundant and may yield slightly different values; compute float rms = conditioned.rms() once after verifying conditioned.isValid() and reuse it in mNoiseFloorTracker.update(rms) and mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(rms)), keeping the same guard (mNoiseFloorTrackingEnabled && conditioned.isValid()) and leaving mContext->setSample(conditioned) as-is.tests/fl/audio/silence_envelope.hpp (1)
19-41: Verify decay loop iteration counts.L33 runs 31 iterations × 0.016s ≈ 0.496s (just under 1·tau = 0.5s), and L39 runs another 63 × 0.016s ≈ 1.008s for a total of ~1.504s ≈ 3·tau. At 3·tau, expected value for start=1.0, target=0 is
exp(-3) ≈ 0.0498, which is right at the< 0.05threshold — flakey margin. Consider extending by a few frames (e.g. 70 iterations → ~1.12s total additional) to get comfortably below 0.05 (targetexp(-3.2) ≈ 0.041).🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@tests/fl/audio/silence_envelope.hpp` around lines 19 - 41, The decay test for audio::SilenceEnvelope uses iteration counts that make the total silent time hover on the flakey threshold (~exp(-3) ≈ 0.0498); update the loops that call audio::SilenceEnvelope::update(true, 0.0f, dt) so the envelope decays comfortably past 3*tau (for example make the first decay loop 32 iterations and the subsequent decay loop ~70 iterations) so the final env.value() falls well below 0.05; adjust the for loops that drive update(...) and leave the rest of the test (Config.decayTauSeconds, initial seed via update(false,...), checks against env.value()) unchanged.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/audio_silence_gate_design.md`:
- Line 142: The sentence fragment beginning "Can be layered on top later if
demand emerges." is missing a subject; update the sentence in
docs/audio_silence_gate_design.md (the line that follows the description of the
unified volume concept) to include an explicit subject such as "This change" or
"The unified volume concept" — e.g., "This change can be layered on top later if
demand emerges." — so the sentence reads as a complete thought.
- Around line 103-104: Update the documentation to reference the correct test
filename: change the path mentioning tests/fl/audio/silence_envelope.cpp to
tests/fl/audio/silence_envelope.hpp in the `audio::SilenceEnvelope` section
(docs entry that lists src/fl/audio/silence_envelope.{h,cpp.hpp} and unity
include in src/fl/audio/_build.cpp.hpp), so the doc points to the actual unit
test file.
In `@src/fl/audio/silence_envelope.cpp.hpp`:
- Around line 24-30: The code currently treats dt <= 0.0f as an immediate snap
to target; change the conditional so only negative dt (or non-positive decay
tau) triggers an immediate snap. Specifically, in the update function that uses
mConfig.decayTauSeconds, dt, mCurrent and mConfig.targetValue, replace the check
`mConfig.decayTauSeconds <= 0.0f || dt <= 0.0f` with a check that snaps only
when `mConfig.decayTauSeconds <= 0.0f || dt < 0.0f`, and ensure that when dt ==
0.0f the function simply returns the existing mCurrent without applying the
exponential step or modifying mCurrent.
In `@src/fl/audio/silence_envelope.h`:
- Around line 22-28: Rename the two fields in the simple struct
SilenceEnvelope::Config from decayTauSeconds and targetValue to snake_case
decay_tau_seconds and target_value everywhere (the struct definition, any
constructors/initializers, usages inside SilenceEnvelope methods, documentation
comments, tests, and any serialization/deserialization or default-value
references); update all call sites and tests to use the new names and run the
build/tests to ensure no remaining references to the old identifiers remain.
---
Nitpick comments:
In `@src/fl/audio/audio_context.cpp.hpp`:
- Around line 164-171: The clearCache routine (Context::clearCache) currently
clears FFT caches and history but does not reset the silence flag mIsSilent,
which can leave a stale true value until setSample runs; update
Context::clearCache to also set mIsSilent = false so the context is fully reset
(mirror the behavior from setSample) ensuring defensive consistency after a full
reset.
In `@src/fl/audio/audio_processor.cpp.hpp`:
- Around line 56-68: The code calls conditioned.rms() twice (once for
mNoiseFloorTracker.update and again for mContext->setSilent), which is redundant
and may yield slightly different values; compute float rms = conditioned.rms()
once after verifying conditioned.isValid() and reuse it in
mNoiseFloorTracker.update(rms) and
mContext->setSilent(!mNoiseFloorTracker.isAboveFloor(rms)), keeping the same
guard (mNoiseFloorTrackingEnabled && conditioned.isValid()) and leaving
mContext->setSample(conditioned) as-is.
In `@src/fl/audio/audio_reactive.cpp.hpp`:
- Around line 168-183: The code calls processedSample.rms() twice; compute it
once and reuse it to avoid redundant work and ensure consistency: inside the
block gated by mConfig.enableNoiseFloorTracking, call Sample::rms() once into a
local float (e.g. rms), pass that to mNoiseFloorTracker.update(rms), then later
use the same rms when calling mNoiseFloorTracker.isAboveFloor(...) to set
mContext->setSilent(...); keep the conditional checks around
mConfig.enableNoiseFloorTracking and preserve the call to
mContext->setSample(processedSample).
In `@tests/fl/audio/silence_envelope.hpp`:
- Around line 19-41: The decay test for audio::SilenceEnvelope uses iteration
counts that make the total silent time hover on the flakey threshold (~exp(-3) ≈
0.0498); update the loops that call audio::SilenceEnvelope::update(true, 0.0f,
dt) so the envelope decays comfortably past 3*tau (for example make the first
decay loop 32 iterations and the subsequent decay loop ~70 iterations) so the
final env.value() falls well below 0.05; adjust the for loops that drive
update(...) and leave the rest of the test (Config.decayTauSeconds, initial seed
via update(false,...), checks against env.value()) unchanged.
🪄 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: 654f6483-263b-45c6-9c88-708d5cee587a
📒 Files selected for processing (11)
docs/audio_silence_gate_design.mdsrc/fl/audio/_build.cpp.hppsrc/fl/audio/audio_context.cpp.hppsrc/fl/audio/audio_context.hsrc/fl/audio/audio_processor.cpp.hppsrc/fl/audio/audio_reactive.cpp.hppsrc/fl/audio/silence_envelope.cpp.hppsrc/fl/audio/silence_envelope.htests/fl/audio.cpptests/fl/audio/audio_context.hpptests/fl/audio/silence_envelope.hpp
| ### `audio::SilenceEnvelope` (new) | ||
| See Layer 2 above. Lives in `src/fl/audio/silence_envelope.{h,cpp.hpp}`. Added to `src/fl/audio/_build.cpp.hpp` unity include. Unit test at `tests/fl/audio/silence_envelope.cpp`. |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Verify the actual SilenceEnvelope test file name.
# Expect: Exactly one matching test file, then update the doc path to match it.
fd -i '^silence_envelope\.(hpp|cpp)$' testsRepository: FastLED/FastLED
Length of output: 94
Update documentation test path from .cpp to .hpp.
Line 104 references tests/fl/audio/silence_envelope.cpp, but the actual test file is tests/fl/audio/silence_envelope.hpp. Update the documented path accordingly.
Suggested fix
-See Layer 2 above. Lives in `src/fl/audio/silence_envelope.{h,cpp.hpp}`. Added to `src/fl/audio/_build.cpp.hpp` unity include. Unit test at `tests/fl/audio/silence_envelope.cpp`.
+See Layer 2 above. Lives in `src/fl/audio/silence_envelope.{h,cpp.hpp}`. Added to `src/fl/audio/_build.cpp.hpp` unity include. Unit test at `tests/fl/audio/silence_envelope.hpp`.📝 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.
| ### `audio::SilenceEnvelope` (new) | |
| See Layer 2 above. Lives in `src/fl/audio/silence_envelope.{h,cpp.hpp}`. Added to `src/fl/audio/_build.cpp.hpp` unity include. Unit test at `tests/fl/audio/silence_envelope.cpp`. | |
| ### `audio::SilenceEnvelope` (new) | |
| See Layer 2 above. Lives in `src/fl/audio/silence_envelope.{h,cpp.hpp}`. Added to `src/fl/audio/_build.cpp.hpp` unity include. Unit test at `tests/fl/audio/silence_envelope.hpp`. |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/audio_silence_gate_design.md` around lines 103 - 104, Update the
documentation to reference the correct test filename: change the path mentioning
tests/fl/audio/silence_envelope.cpp to tests/fl/audio/silence_envelope.hpp in
the `audio::SilenceEnvelope` section (docs entry that lists
src/fl/audio/silence_envelope.{h,cpp.hpp} and unity include in
src/fl/audio/_build.cpp.hpp), so the doc points to the actual unit test file.
|
|
||
| ## Out of scope | ||
|
|
||
| - Unified volume concept (`AudioLevel` struct replacing all volume getters) — considered and rejected as too churn-heavy; preserved as Option 2 in the discussion. Can be layered on top later if demand emerges. |
There was a problem hiding this comment.
Make this sentence complete.
Line 142 starts with “Can be layered...”; add the subject for clearer docs.
Proposed wording
-- Unified volume concept (`AudioLevel` struct replacing all volume getters) — considered and rejected as too churn-heavy; preserved as Option 2 in the discussion. Can be layered on top later if demand emerges.
+- Unified volume concept (`AudioLevel` struct replacing all volume getters) — considered and rejected as too churn-heavy; preserved as Option 2 in the discussion. It can be layered on top later if demand emerges.📝 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.
| - Unified volume concept (`AudioLevel` struct replacing all volume getters) — considered and rejected as too churn-heavy; preserved as Option 2 in the discussion. Can be layered on top later if demand emerges. | |
| - Unified volume concept (`AudioLevel` struct replacing all volume getters) — considered and rejected as too churn-heavy; preserved as Option 2 in the discussion. It can be layered on top later if demand emerges. |
🧰 Tools
🪛 LanguageTool
[style] ~142-~142: To form a complete sentence, be sure to include a subject.
Context: ...reserved as Option 2 in the discussion. Can be layered on top later if demand emerg...
(MISSING_IT_THERE)
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@docs/audio_silence_gate_design.md` at line 142, The sentence fragment
beginning "Can be layered on top later if demand emerges." is missing a subject;
update the sentence in docs/audio_silence_gate_design.md (the line that follows
the description of the unified volume concept) to include an explicit subject
such as "This change" or "The unified volume concept" — e.g., "This change can
be layered on top later if demand emerges." — so the sentence reads as a
complete thought.
| if (mConfig.decayTauSeconds <= 0.0f || dt <= 0.0f) { | ||
| // No decay time or zero dt → snap to target immediately. | ||
| mCurrent = mConfig.targetValue; | ||
| return mCurrent; | ||
| } | ||
| const float alpha = 1.0f - fl::expf(-dt / mConfig.decayTauSeconds); | ||
| mCurrent = mCurrent + (mConfig.targetValue - mCurrent) * alpha; |
There was a problem hiding this comment.
Do not snap the envelope when no time has elapsed.
Line 24 makes dt <= 0.0f jump straight to targetValue. For a first-order envelope, dt == 0 should hold the previous value; otherwise a duplicate timestamp or first-frame zero delta can hard-gate immediately instead of decaying smoothly.
Proposed fix
- if (mConfig.decayTauSeconds <= 0.0f || dt <= 0.0f) {
- // No decay time or zero dt → snap to target immediately.
+ if (mConfig.decayTauSeconds <= 0.0f) {
+ // No decay time: snap to target immediately.
mCurrent = mConfig.targetValue;
return mCurrent;
}
+ if (dt <= 0.0f) {
+ // No elapsed time: hold the previous envelope value.
+ return mCurrent;
+ }
const float alpha = 1.0f - fl::expf(-dt / mConfig.decayTauSeconds);📝 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.
| if (mConfig.decayTauSeconds <= 0.0f || dt <= 0.0f) { | |
| // No decay time or zero dt → snap to target immediately. | |
| mCurrent = mConfig.targetValue; | |
| return mCurrent; | |
| } | |
| const float alpha = 1.0f - fl::expf(-dt / mConfig.decayTauSeconds); | |
| mCurrent = mCurrent + (mConfig.targetValue - mCurrent) * alpha; | |
| if (mConfig.decayTauSeconds <= 0.0f) { | |
| // No decay time: snap to target immediately. | |
| mCurrent = mConfig.targetValue; | |
| return mCurrent; | |
| } | |
| if (dt <= 0.0f) { | |
| // No elapsed time: hold the previous envelope value. | |
| return mCurrent; | |
| } | |
| const float alpha = 1.0f - fl::expf(-dt / mConfig.decayTauSeconds); | |
| mCurrent = mCurrent + (mConfig.targetValue - mCurrent) * alpha; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/audio/silence_envelope.cpp.hpp` around lines 24 - 30, The code
currently treats dt <= 0.0f as an immediate snap to target; change the
conditional so only negative dt (or non-positive decay tau) triggers an
immediate snap. Specifically, in the update function that uses
mConfig.decayTauSeconds, dt, mCurrent and mConfig.targetValue, replace the check
`mConfig.decayTauSeconds <= 0.0f || dt <= 0.0f` with a check that snaps only
when `mConfig.decayTauSeconds <= 0.0f || dt < 0.0f`, and ensure that when dt ==
0.0f the function simply returns the existing mCurrent without applying the
exponential step or modifying mCurrent.
| struct Config { | ||
| // Time constant for exponential decay toward targetValue during silence. | ||
| // After ~3*decayTauSeconds the envelope is within 5% of target. | ||
| float decayTauSeconds = 0.5f; | ||
| // Value the envelope decays toward during silence (usually 0). | ||
| float targetValue = 0.0f; | ||
| }; |
There was a problem hiding this comment.
Use snake_case for Config fields before this becomes public API.
SilenceEnvelope::Config is a simple struct, so decayTauSeconds and targetValue should be decay_tau_seconds and target_value; update implementation, docs, and tests accordingly. As per coding guidelines, **/*.{h,hpp}: Use mVariableName format for member variables in complex classes, lowercase snake_case for simple structs.
Proposed API rename
struct Config {
// Time constant for exponential decay toward targetValue during silence.
// After ~3*decayTauSeconds the envelope is within 5% of target.
- float decayTauSeconds = 0.5f;
+ float decay_tau_seconds = 0.5f;
// Value the envelope decays toward during silence (usually 0).
- float targetValue = 0.0f;
+ float target_value = 0.0f;
};📝 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.
| struct Config { | |
| // Time constant for exponential decay toward targetValue during silence. | |
| // After ~3*decayTauSeconds the envelope is within 5% of target. | |
| float decayTauSeconds = 0.5f; | |
| // Value the envelope decays toward during silence (usually 0). | |
| float targetValue = 0.0f; | |
| }; | |
| struct Config { | |
| // Time constant for exponential decay toward targetValue during silence. | |
| // After ~3*decayTauSeconds the envelope is within 5% of target. | |
| float decay_tau_seconds = 0.5f; | |
| // Value the envelope decays toward during silence (usually 0). | |
| float target_value = 0.0f; | |
| }; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@src/fl/audio/silence_envelope.h` around lines 22 - 28, Rename the two fields
in the simple struct SilenceEnvelope::Config from decayTauSeconds and
targetValue to snake_case decay_tau_seconds and target_value everywhere (the
struct definition, any constructors/initializers, usages inside SilenceEnvelope
methods, documentation comments, tests, and any serialization/deserialization or
default-value references); update all call sites and tests to use the new names
and run the build/tests to ensure no remaining references to the old identifiers
remain.
Adopts SilenceEnvelope for three spectral Data fields on Reactive: dominantFrequency, magnitude, and spectralFlux. During silence the envelope (tau=0.2s) exponentially decays each metric toward zero, stopping the FFT noise-floor argmax from locking onto arbitrary bins and preventing false onset detections. During audio the envelope is strict pass-through, so existing users who have not enabled NoiseFloorTracker see no behavior change — gating is strictly opt-in. Tau=0.2s chosen because FFT noise is brittle and spectral metrics should snap to zero within ~1 second of silence onset. The existing argmax in mapFFTBinsToFrequencyChannels() is unchanged; envelopes post-process its output inside processSample() where dt is computed via computeAudioDt(pcm.size(), sampleRate) for frame-rate independence. Part 3/4 of #2253 silence-gate rollout. Builds on #2306. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Adopts SilenceEnvelope for three spectral Data fields on Reactive: dominantFrequency, magnitude, and spectralFlux. During silence the envelope (tau=0.2s) exponentially decays each metric toward zero, stopping the FFT noise-floor argmax from locking onto arbitrary bins and preventing false onset detections. During audio the envelope is strict pass-through, so existing users who have not enabled NoiseFloorTracker see no behavior change — gating is strictly opt-in. Tau=0.2s chosen because FFT noise is brittle and spectral metrics should snap to zero within ~1 second of silence onset. The existing argmax in mapFFTBinsToFrequencyChannels() is unchanged; envelopes post-process its output inside processSample() where dt is computed via computeAudioDt(pcm.size(), sampleRate) for frame-rate independence. Part 3/4 of #2253 silence-gate rollout. Builds on #2306. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Composes a fl::audio::SilenceEnvelope (tau=2.0s, target=0) into TempoAnalyzer so that the BPM confidence metric decays smoothly during silence instead of persisting on stale hypotheses. The raw BPM estimate itself is NOT gated — last-known tempo is preserved across silence so beat sync resumes seamlessly when audio returns. Tau=2s matches the natural persistence of musical tempo; snapping faster feels wrong. dt is derived from context timestamp deltas so the envelope's first-order response is frame-rate independent. When context->isSilent() is false the envelope is a strict pass-through, preserving existing tempo-detection behavior for users who haven't enabled NoiseFloorTracker. Adds two integration tests: one drives 15 beats of synthetic 120 BPM onsets and confirms confidence > 0.3, then asserts confidence < 0.05 after ~5s of silence while BPM is unchanged; the other verifies pass-through when isSilent=false. User-visible impact: LED effects keyed to BPM confidence (rhythmic-effect gating) stop driving rhythm when music stops, instead of staying "in rhythm" for 5-10+ seconds on stale onset hypotheses. Part 4/4 of #2253 silence-gate rollout. Builds on #2306. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Composes a fl::audio::SilenceEnvelope (tau=2.0s, target=0) into TempoAnalyzer so that the BPM confidence metric decays smoothly during silence instead of persisting on stale hypotheses. The raw BPM estimate itself is NOT gated — last-known tempo is preserved across silence so beat sync resumes seamlessly when audio returns. Tau=2s matches the natural persistence of musical tempo; snapping faster feels wrong. dt is derived from context timestamp deltas so the envelope's first-order response is frame-rate independent. When context->isSilent() is false the envelope is a strict pass-through, preserving existing tempo-detection behavior for users who haven't enabled NoiseFloorTracker. Adds two integration tests: one drives 15 beats of synthetic 120 BPM onsets and confirms confidence > 0.3, then asserts confidence < 0.05 after ~5s of silence while BPM is unchanged; the other verifies pass-through when isSilent=false. User-visible impact: LED effects keyed to BPM confidence (rhythmic-effect gating) stop driving rhythm when music stops, instead of staying "in rhythm" for 5-10+ seconds on stale onset hypotheses. Part 4/4 of #2253 silence-gate rollout. Builds on #2306. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Vibe's MilkDrop self-normalization (imm/longAvg) drove getVol() toward 1.0 during silence (noise/noise → 1.0, plus the <0.001f clamp pinning to 1.0). LED effects driven by getVol()/getBass()/getMid()/getTreb() never calmed down when music stopped. Route each band's mImmRel and mAvgRel through a SilenceEnvelope (tau=0.3s → ~1s to fully gate) so when Context::isSilent() is true the values exponentially decay toward 0.0. Pass-through during audio preserves MilkDrop dynamics exactly. The <0.001f startup clamp stays intact — envelope handles silence downstream. All 8 user-visible getters now decay to near-zero in silence: getBass, getMid, getTreb, getVol, getBassAtt, getMidAtt, getTrebAtt, getVolAtt. Part 2/4 of #2253 silence-gate rollout. Builds on the Context::isSilent() + SilenceEnvelope plumbing in #2306. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Vibe's MilkDrop self-normalization (imm/longAvg) drove getVol() toward 1.0 during silence (noise/noise → 1.0, plus the <0.001f clamp pinning to 1.0). LED effects driven by getVol()/getBass()/getMid()/getTreb() never calmed down when music stopped. Route each band's mImmRel and mAvgRel through a SilenceEnvelope (tau=0.3s → ~1s to fully gate) so when Context::isSilent() is true the values exponentially decay toward 0.0. Pass-through during audio preserves MilkDrop dynamics exactly. The <0.001f startup clamp stays intact — envelope handles silence downstream. All 8 user-visible getters now decay to near-zero in silence: getBass, getMid, getTreb, getVol, getBassAtt, getMidAtt, getTrebAtt, getVolAtt. Part 2/4 of #2253 silence-gate rollout. Builds on the Context::isSilent() + SilenceEnvelope plumbing in #2306. Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Phase 1 of the fix for #2253 (audio volume not returning to zero in silence). Lays the architectural groundwork; no user-visible behavior change yet — Phase 2 PRs will adopt this in Vibe, Reactive spectral metrics, and TempoAnalyzer.
See
docs/audio_silence_gate_design.mdfor the full design.Two commits, each a self-contained unit:
1.
Context::isSilent()plumbingsetSilent/isSilentonaudio::Context(defaultfalse, cleared onsetSample())Processor::update()andReactive::processSample()populate it fromNoiseFloorTracker::isAboveFloor()after the existing NFT updateisSilent()staysfalse2.
SilenceEnvelopehelper classalpha = 1 - exp(-dt/tau))isGatedthreshold, non-zero targets, degeneratetau=0Why architecture-first
The survey (see design doc §Problem) found
NoiseFloorTrackerwas already computing high-quality silence info but nothing read it. Phase 1 plugs that orphaned infrastructure into a shared bus (Context) and ships a reusable primitive so Phase 2 can be three small, parallelizable adoption PRs instead of three one-off patches.Test plan
bash test fl_audio --debug— 211 tests pass under ASAN/UBSANbash linton all touched files — cleanNon-goals (explicitly out of scope)
AudioLevelvalue type (considered — rejected as too churn-heavy for a bug fix; can layer on later)🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Tests
Documentation