FastLED 3.9.15
Loading...
Searching...
No Matches
spectral_variance_impl.h
Go to the documentation of this file.
1#pragma once
2
3#include "fl/stl/span.h"
4#include "fl/stl/vector.h"
5
6namespace fl {
7namespace detail {
8
28template <typename T = float>
30 public:
31 explicit SpectralVarianceImpl(T alpha = T(0.2f), T floor = T(1e-4f))
32 : mAlpha(alpha), mFloor(floor), mVariance(T(0)) {}
33
37 const int n = static_cast<int>(bins.size());
38 if (n == 0) return T(0);
39
40 // Initialize on first call or if channel count changes
41 if (mSmoothed.size() != static_cast<fl::size>(n)) {
42 mSmoothed.resize(n);
43 for (int i = 0; i < n; ++i) {
44 mSmoothed[i] = bins[i];
45 }
46 mVariance = T(0);
47 return T(0);
48 }
49
50 T sumRelChange = T(0);
51 int activeCount = 0;
52
53 for (int i = 0; i < n; ++i) {
54 T smoothed = mSmoothed[i];
55 T denom = (smoothed > mFloor) ? smoothed : mFloor;
56
57 // Only count channels with meaningful energy
58 if (smoothed > mFloor) {
59 T diff = bins[i] - smoothed;
60 T absDiff = (diff >= T(0)) ? diff : -diff;
61 sumRelChange += absDiff / denom;
62 ++activeCount;
63 }
64
65 // Update EMA: smoothed = alpha * current + (1-alpha) * smoothed
66 mSmoothed[i] = mAlpha * bins[i] + (T(1) - mAlpha) * smoothed;
67 }
68
69 mVariance = (activeCount >= 2)
70 ? sumRelChange / static_cast<T>(activeCount)
71 : T(0);
72 return mVariance;
73 }
74
76 T value() const { return mVariance; }
77
79 void reset() {
80 mSmoothed.clear();
81 mVariance = T(0);
82 }
83
85 void setAlpha(T alpha) { mAlpha = alpha; }
86
88 void setFloor(T floor) { mFloor = floor; }
89
91 fl::size size() const { return mSmoothed.size(); }
92
93 private:
98};
99
100} // namespace detail
101} // namespace fl
void setAlpha(T alpha)
Change the EMA alpha (tracking speed).
T update(fl::span< const T > bins)
Feed a new frame of multi-channel data.
void reset()
Reset all internal state.
T value() const
Get the last computed variance without updating.
SpectralVarianceImpl(T alpha=T(0.2f), T floor=T(1e-4f))
fl::size size() const
Get the number of channels being tracked.
void setFloor(T floor)
Change the floor threshold for active channel detection.
constexpr fl::size size() const FL_NOEXCEPT
Definition span.h:458
Compile-time linker keep-alive hook for a single fl::Bus.
Definition bus_traits.h:48
constexpr enable_if< is_fixed_point< T >::value, T >::type floor(T x) FL_NOEXCEPT
Base definition for an LED controller.
Definition crgb.hpp:179