Repository navigation
feat: add signal detectors #168
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,102 @@ | ||
| # Signal Detectors | ||
|
|
||
| ## Overview & Motivation | ||
|
|
||
| Real-time signal monitoring requires lightweight, stateful primitives that track envelope, periodicity, and energy without buffering entire waveforms. Three composable detectors cover the most common needs: holding the peak magnitude for VU-style metering, counting sign reversals to estimate frequency, and smoothing instantaneous power to approximate RMS level. All three operate in O(1) time and O(1) memory per sample, making them suitable for tight interrupt service routines. | ||
|
|
||
| ## Mathematical Theory | ||
|
|
||
| ### Peak Hold | ||
|
|
||
| Let $m_n = |x_n|$. With a decay coefficient $d \in (0, 1]$, the held peak evolves as: | ||
|
|
||
| $$p_n = \max(m_n,\; d \cdot p_{n-1})$$ | ||
|
|
||
| When $d = 1$ the peak is infinite-hold; when $d < 1$ it releases exponentially toward zero between new maxima. | ||
|
|
||
| ### Zero-Crossing Detection | ||
|
|
||
| A zero crossing occurs at sample $n$ when the sign of $x_n$ differs from the sign of $x_{n-1}$ and $|x_n|$ exceeds a hysteresis threshold $h \geq 0$: | ||
|
|
||
| $$\text{crossed}_n = \bigl(\operatorname{sgn}(x_n) \neq \operatorname{sgn}(x_{n-1})\bigr) \land \bigl(|x_n| > h\bigr)$$ | ||
|
|
||
| The instantaneous fundamental frequency of a periodic signal can be estimated from the cumulative count $C$ over a window of $N$ samples at sampling period $T_s$: | ||
|
|
||
| $$f_0 \approx \frac{C}{2 \, N \, T_s}$$ | ||
|
|
||
| ### RMS Envelope | ||
|
|
||
| A one-pole IIR filter is applied to $x^2$, yielding an exponentially weighted mean-square: | ||
|
|
||
| $$E_n = E_{n-1} + \alpha\,(x_n^2 - E_{n-1}), \quad \alpha \in (0, 1)$$ | ||
|
|
||
| The RMS envelope is: | ||
|
|
||
| $$r_n = \sqrt{E_n}$$ | ||
|
|
||
| This is structurally identical to an exponential moving average applied to the squared signal. | ||
|
|
||
| ## Complexity Analysis | ||
|
|
||
| | Detector | Time per sample | State words | | ||
| |-----------------------|--------------------------------|---------------------| | ||
| | Peak Hold | O(1) — 1 mul, 1 compare, 1 abs | 1 scalar | | ||
| | Zero-Crossing Counter | O(1) — 1 compare, 1 abs | 1 scalar + 1 uint32 | | ||
| | RMS Envelope | O(1) — 1 MAC + 1 sqrt | 1 scalar | | ||
|
|
||
| No buffers, no windows, no dynamic allocation. | ||
|
|
||
| ## Step-by-Step Walkthrough | ||
|
|
||
| ### Peak Hold (decay = 0.5), input = [0.8, 0, 0, 0] | ||
|
|
||
| | n | $x_n$ | $m_n$ | $d \cdot p_{n-1}$ | $p_n$ | | ||
| |---|-------|-------|-------------------|-------| | ||
| | 0 | 0.8 | 0.8 | 0.0 | 0.8 | | ||
| | 1 | 0.0 | 0.0 | 0.4 | 0.4 | | ||
| | 2 | 0.0 | 0.0 | 0.2 | 0.2 | | ||
| | 3 | 0.0 | 0.0 | 0.1 | 0.1 | | ||
|
|
||
| ### Zero-Crossing Counter (h = 0), input = [1, -1, 1, -1] | ||
|
|
||
| | n | $x_n$ | prev sign | curr sign | crossed | C | | ||
| |---|-------|-----------|-----------|---------|---| | ||
| | 0 | +1 | 0 | + | no | 0 | | ||
| | 1 | -1 | + | - | yes | 1 | | ||
| | 2 | +1 | - | + | yes | 2 | | ||
| | 3 | -1 | + | - | yes | 3 | | ||
|
|
||
| ### RMS Envelope ($\alpha = 0.25$), DC input $x = 0.4$ | ||
|
|
||
| $E_0 = 0$; after $n$ steps, $E_n = 0.16\,(1-(1-0.25)^n)$. At $n = 20$: $E_{20} \approx 0.1599$, $r_{20} \approx 0.3999$. | ||
|
|
||
| ## Pitfalls & Edge Cases | ||
|
|
||
| - Decay = 0 collapses the peak hold to the instantaneous absolute value; decay must be in $(0, 1]$ for meaningful hold behavior. | ||
| - Zero-crossing sign comparison must treat $x = 0$ consistently; a sample at exactly zero with $h = 0$ can cause spurious double-counts if not handled. The hysteresis guard mitigates this. | ||
| - RMS Envelope with very small $\alpha$ responds slowly to changes in signal level; with $\alpha$ near 1 it approaches the instantaneous absolute value squared. | ||
| - The RMS detector returns 0 at initialization ($E_0 = 0$) and converges to the true RMS from below for positive-power signals. | ||
|
|
||
| ## Variants & Generalizations | ||
|
|
||
| - The peak hold decay parameter maps directly to a time constant: $\tau = -T_s / \ln(d)$, bridging the gap between digital and analog VU meter release times. | ||
| - A bilateral zero-crossing counter can distinguish positive-going from negative-going edges, enabling half-wave frequency estimation. | ||
| - The RMS envelope is the special case of an exponential moving average applied to $x^2$; replacing the squaring with $|x|$ yields a mean-absolute-value envelope. | ||
|
|
||
| ## Applications | ||
|
|
||
| - VU meters and compressor side-chains use peak hold with a configurable release time. | ||
| - Zero-crossing rate is a low-cost voiced/unvoiced classifier in speech processing. | ||
| - RMS envelope tracks AC signal levels in power monitoring, audio dynamic processing, and vibration analysis. | ||
| - All three detectors compose naturally into a signal statistics block for real-time diagnostics. | ||
|
|
||
| ## Connections to Other Algorithms | ||
|
|
||
| - RMS Envelope is structurally equivalent to the Exponential Moving Average (EMA) filter applied to $x^2$, sharing the same one-pole recurrence. | ||
| - Zero-crossing detection is a degenerate form of edge detection in discrete sequences, related to sign-change detection in root-finding algorithms. | ||
|
|
||
| ## References & Further Reading | ||
|
|
||
| - Zolzer, U., "DAFX: Digital Audio Effects", 2nd ed., Wiley, 2011 — Chapter 2 (dynamics processing, envelope followers). | ||
| - Proakis, J. & Manolakis, D., "Digital Signal Processing", 4th ed., Prentice Hall, 2007 — Section 1.4 (zero-crossing rate). | ||
| - Smith, J.O., "Introduction to Digital Filters with Audio Applications", W3K Publishing, 2007 — [online](https://ccrma.stanford.edu/~jos/filters/). |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| #include "numerical/analysis/SignalDetectors.hpp" | ||
|
|
||
| namespace analysis | ||
| { | ||
| template class PeakHold<float>; | ||
| template class ZeroCrossingCounter<float>; | ||
| template class RmsEnvelope<float>; | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,108 @@ | ||
| #pragma once | ||
|
|
||
| #if defined(__GNUC__) || defined(__clang__) | ||
| #pragma GCC optimize("O3", "fast-math") | ||
| #endif | ||
|
|
||
| #include "numerical/math/CompilerOptimizations.hpp" | ||
| #include <cmath> | ||
| #include <cstdint> | ||
| #include <type_traits> | ||
|
|
||
| namespace analysis | ||
| { | ||
| template<typename T> | ||
| class PeakHold | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "PeakHold supports floating-point types only"); | ||
|
|
||
| public: | ||
| explicit PeakHold(T decay = T{ 1 }) | ||
| : decay{ decay } | ||
| {} | ||
|
|
||
| OPTIMIZE_FOR_SPEED T Update(T x) | ||
| { | ||
| T m{ std::abs(x) }; | ||
| peak = (m > peak * decay) ? m : peak * decay; | ||
| return peak; | ||
| } | ||
|
|
||
| void Reset() | ||
| { | ||
| peak = T{ 0 }; | ||
| } | ||
|
|
||
| private: | ||
| T peak{ T{ 0 } }; | ||
| T decay; | ||
| }; | ||
|
|
||
| template<typename T> | ||
| class ZeroCrossingCounter | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "ZeroCrossingCounter supports floating-point types only"); | ||
|
|
||
| public: | ||
| explicit ZeroCrossingCounter(T hysteresis = T{ 0 }) | ||
| : hysteresis{ hysteresis } | ||
| {} | ||
|
|
||
| OPTIMIZE_FOR_SPEED bool Update(T x) | ||
| { | ||
| bool crossed{ (previous < T{ 0 } ? x > T{ 0 } : x < T{ 0 }) && (std::abs(x) > hysteresis) }; | ||
| if (crossed) | ||
| ++count; | ||
| previous = x; | ||
| return crossed; | ||
| } | ||
|
|
||
| uint32_t Count() const | ||
| { | ||
| return count; | ||
| } | ||
|
|
||
| void Reset() | ||
| { | ||
| previous = T{ 0 }; | ||
| count = 0; | ||
| } | ||
|
|
||
| private: | ||
| T previous{ T{ 0 } }; | ||
| uint32_t count{ 0 }; | ||
| T hysteresis; | ||
| }; | ||
|
|
||
| template<typename T> | ||
| class RmsEnvelope | ||
| { | ||
| static_assert(std::is_floating_point_v<T>, "RmsEnvelope supports floating-point types only"); | ||
|
|
||
| public: | ||
| explicit RmsEnvelope(T alpha) | ||
| : alpha{ alpha } | ||
| {} | ||
|
|
||
| OPTIMIZE_FOR_SPEED T Update(T x) | ||
| { | ||
| meanSquare += alpha * (x * x - meanSquare); | ||
| return std::sqrt(meanSquare); | ||
| } | ||
|
|
||
| void Reset(T value = T{ 0 }) | ||
| { | ||
| meanSquare = value; | ||
| } | ||
|
|
||
| private: | ||
| T alpha; | ||
| T meanSquare{ T{ 0 } }; | ||
| }; | ||
|
|
||
| #ifdef NUMERICAL_TOOLBOX_COVERAGE_BUILD | ||
| extern template class PeakHold<float>; | ||
| extern template class ZeroCrossingCounter<float>; | ||
| extern template class RmsEnvelope<float>; | ||
| #endif | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,98 @@ | ||
| #include "numerical/analysis/SignalDetectors.hpp" | ||
| #include "numerical/math/Tolerance.hpp" | ||
| #include "gmock/gmock.h" | ||
| #include <cmath> | ||
| #include <numbers> | ||
|
|
||
| namespace | ||
| { | ||
| class TestSignalDetectors : public ::testing::Test | ||
| { | ||
| public: | ||
| analysis::PeakHold<float> peak{ 1.0f }; | ||
| analysis::ZeroCrossingCounter<float> zc{ 0.0f }; | ||
| analysis::RmsEnvelope<float> rms{ 0.25f }; | ||
| }; | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, peak_hold_latches_maximum) | ||
| { | ||
| EXPECT_NEAR(peak.Update(0.2f), 0.2f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(peak.Update(0.5f), 0.5f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(peak.Update(0.3f), 0.5f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(peak.Update(0.1f), 0.5f, math::Tolerance<float>()); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, peak_hold_decays_when_leaky) | ||
| { | ||
| analysis::PeakHold<float> leaky{ 0.5f }; | ||
| EXPECT_NEAR(leaky.Update(0.8f), 0.8f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(leaky.Update(0.0f), 0.4f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(leaky.Update(0.0f), 0.2f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(leaky.Update(0.0f), 0.1f, math::Tolerance<float>()); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, peak_hold_tracks_magnitude_not_sign) | ||
| { | ||
| EXPECT_NEAR(peak.Update(-0.9f), 0.9f, math::Tolerance<float>()); | ||
| EXPECT_NEAR(peak.Update(0.1f), 0.9f, math::Tolerance<float>()); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, zero_crossing_counts_sign_changes) | ||
| { | ||
| zc.Update(1.0f); | ||
| zc.Update(-1.0f); | ||
| zc.Update(1.0f); | ||
| zc.Update(-1.0f); | ||
| EXPECT_EQ(zc.Count(), 3u); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, zero_crossing_hysteresis_rejects_noise) | ||
| { | ||
| analysis::ZeroCrossingCounter<float> noisy{ 0.1f }; | ||
| noisy.Update(0.02f); | ||
| noisy.Update(-0.02f); | ||
| noisy.Update(0.02f); | ||
| EXPECT_EQ(noisy.Count(), 0u); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, rms_envelope_converges_to_true_rms) | ||
| { | ||
| analysis::RmsEnvelope<float> r{ 0.1f }; | ||
| constexpr int fs{ 48000 }; | ||
| constexpr int freq{ 1000 }; | ||
| constexpr int period{ fs / freq }; | ||
| constexpr int warmup{ 5000 }; | ||
| constexpr float amplitude{ 0.5f * 1.41421356f }; | ||
| for (int i = 0; i < warmup; ++i) | ||
| r.Update(amplitude * std::sin(std::numbers::pi_v<float> * 2.0f * static_cast<float>(freq) * static_cast<float>(i) / static_cast<float>(fs))); | ||
| float sum{ 0.0f }; | ||
| for (int i = 0; i < period; ++i) | ||
| sum += r.Update(amplitude * std::sin(std::numbers::pi_v<float> * 2.0f * static_cast<float>(freq) * static_cast<float>(warmup + i) / static_cast<float>(fs))); | ||
| EXPECT_NEAR(sum / static_cast<float>(period), 0.5f, 1e-2f); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, rms_dc_input_returns_magnitude) | ||
| { | ||
| analysis::RmsEnvelope<float> r{ 0.25f }; | ||
| float result{ 0.0f }; | ||
| for (int i = 0; i < 200; ++i) | ||
| result = r.Update(0.4f); | ||
| EXPECT_NEAR(result, 0.4f, 1e-2f); | ||
| } | ||
|
|
||
| TEST_F(TestSignalDetectors, reset_clears_all_state) | ||
| { | ||
| peak.Update(1.0f); | ||
| zc.Update(1.0f); | ||
| zc.Update(-1.0f); | ||
| rms.Update(1.0f); | ||
|
|
||
| peak.Reset(); | ||
| zc.Reset(); | ||
| rms.Reset(); | ||
|
|
||
| EXPECT_NEAR(peak.Update(0.0f), 0.0f, math::Tolerance<float>()); | ||
| EXPECT_EQ(zc.Count(), 0u); | ||
| EXPECT_NEAR(rms.Update(0.0f), 0.0f, math::Tolerance<float>()); | ||
| } |
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[MegaLinter] reported by reviewdog 🐶
numerical-toolbox-cpp/README.md
Lines 17 to 23 in c2aa7d9