DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
PhaseCorrelation.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
51#include "../Core/AudioBuffer.h"
52#include "../Core/AudioSpec.h"
53#include "../Core/AuditoryBands.h"
54#include "../Core/DspMath.h"
55
56#include <algorithm>
57#include <array>
58#include <atomic>
59#include <bit>
60#include <cmath>
61#include <cstddef>
62#include <cstdint>
63#include <type_traits>
64
65namespace dspark {
66
73template <FloatType T>
75{
76public:
79 {
80 float mid;
81 float side;
82 };
83
84 static constexpr int kGonioSize = 1024;
85
86 // -- Lifecycle ---------------------------------------------------------------
87
97 void prepare(const AudioSpec& spec, double windowMs = 300.0) noexcept
98 {
99 if (!spec.isValid() || !std::isfinite(spec.sampleRate)) return;
100 if (!std::isfinite(windowMs)) windowMs = 300.0;
101 const double fs = spec.sampleRate;
102 windowMs_ = std::clamp(windowMs, 1.0, 600000.0);
103 alpha_ = 1.0 - std::exp(-1.0 / (windowMs_ * 0.001 * fs));
104 // Decimate the goniometer feed to ~24k points/s - plenty for displays.
105 gonioDecim_ = std::max(1, static_cast<int>(std::llround(std::min(fs / 24000.0, 65536.0))));
106 prepared_.store(true, std::memory_order_relaxed);
107 reset();
108 }
109
117 void reset() noexcept
118 {
119 lr_ = ll_ = rr_ = 0.0;
120 decimCount_ = 0;
121 for (auto& p : gonio_)
122 p.store(0u, std::memory_order_relaxed);
123 gonioWrite_.store(0, std::memory_order_relaxed);
124 correlation_.store(T(0), std::memory_order_relaxed);
125 balance_.store(T(0), std::memory_order_relaxed);
126 dominantDb_.store(T(-200), std::memory_order_relaxed);
127 }
128
129 // -- Processing -------------------------------------------------------------------
130
139 {
140 if (!prepared_.load(std::memory_order_relaxed)) return;
141
142 const int nS = buffer.getNumSamples();
143 const int nCh = buffer.getNumChannels();
144 if (nS <= 0 || nCh <= 0) return;
145
146 const T* L = buffer.getChannel(0);
147 const T* R = (nCh >= 2) ? buffer.getChannel(1) : L;
148
149 const double alpha = alpha_;
150 double lr = lr_, ll = ll_, rr = rr_;
151 int wp = gonioWrite_.load(std::memory_order_relaxed);
152
153 for (int i = 0; i < nS; ++i)
154 {
155 const double l = static_cast<double>(L[i]);
156 const double r = static_cast<double>(R[i]);
157 lr += alpha * (l * r - lr);
158 ll += alpha * (l * l - ll);
159 rr += alpha * (r * r - rr);
160
161 if (++decimCount_ >= gonioDecim_)
162 {
163 decimCount_ = 0;
164 if (std::isfinite(l) && std::isfinite(r))
165 {
166 GonioPoint p;
167 p.mid = static_cast<float>((l + r) * 0.7071067811865476);
168 p.side = static_cast<float>((l - r) * 0.7071067811865476);
169 gonio_[static_cast<size_t>(wp)].store(std::bit_cast<std::uint64_t>(p),
170 std::memory_order_relaxed);
171 wp = (wp + 1) & (kGonioSize - 1);
172 }
173 }
174 }
175
176 gonioWrite_.store(wp, std::memory_order_release);
177
178 // A non-finite sample would park NaN in the recursive averages for
179 // good (the one-pole never drains it). Discard the poisoned window
180 // and hold the last published readings; the accumulators restart
181 // from zero, so measurement resumes on the next clean block (the
182 // correlation is a ratio - it re-converges immediately once real
183 // signal flows again).
184 if (!std::isfinite(lr + ll + rr))
185 {
186 lr_ = ll_ = rr_ = 0.0;
187 return;
188 }
189
190 // Flush fully decayed averages to true zero: long silences would
191 // otherwise walk the one-pole into double denormals and tax hosts
192 // that do not enable FTZ. Well below any audible floor.
193 if (ll < 1e-100) ll = 0.0;
194 if (rr < 1e-100) rr = 0.0;
195 if (std::abs(lr) < 1e-100) lr = 0.0;
196
197 lr_ = lr;
198 ll_ = ll;
199 rr_ = rr;
200
201 const double denom = std::sqrt(ll * rr);
202 const double corr = (denom > 1e-12) ? std::clamp(lr / denom, -1.0, 1.0) : 0.0;
203 correlation_.store(static_cast<T>(corr), std::memory_order_relaxed);
204
205 const double total = ll + rr;
206 const double bal = (total > 1e-12) ? (rr - ll) / total : 0.0;
207 balance_.store(static_cast<T>(bal), std::memory_order_relaxed);
208 const double dom = AuditoryScale::dominantPower(ll, rr, lr);
209 dominantDb_.store(static_cast<T>(dom > 1e-20 ? 10.0 * std::log10(dom) : -200.0), std::memory_order_relaxed);
210 }
211
212 // -- Readout (lock-free, any thread) ------------------------------------------------
213
215 [[nodiscard]] T getCorrelation() const noexcept
216 {
217 return correlation_.load(std::memory_order_relaxed);
218 }
219
221 [[nodiscard]] T getBalance() const noexcept
222 {
223 return balance_.load(std::memory_order_relaxed);
224 }
225
227 [[nodiscard]] T getDominantLevelDb() const noexcept
228 {
229 return dominantDb_.load(std::memory_order_relaxed);
230 }
231
238 int getGonioPoints(GonioPoint* dest, int maxCount) const noexcept
239 {
240 if (dest == nullptr) return 0;
241 const int count = std::clamp(maxCount, 0, kGonioSize);
242 const int wp = gonioWrite_.load(std::memory_order_acquire);
243 for (int i = 0; i < count; ++i)
244 {
245 const auto idx = static_cast<size_t>((wp - count + i) & (kGonioSize - 1));
246 dest[i] = std::bit_cast<GonioPoint>(gonio_[idx].load(std::memory_order_relaxed));
247 }
248 return count;
249 }
250
252 [[nodiscard]] double getWindowMs() const noexcept { return windowMs_; }
253
254private:
255 static_assert(sizeof(GonioPoint) == sizeof(std::uint64_t),
256 "GonioPoint must pack into one 64-bit atomic");
257 static_assert(std::is_trivially_copyable_v<GonioPoint>);
258
259 double windowMs_ = 300.0;
260 double alpha_ = 0.001;
261 std::atomic<bool> prepared_ { false };
262
263 double lr_ = 0.0, ll_ = 0.0, rr_ = 0.0;
264 std::atomic<T> dominantDb_ { T(-200) };
265
266 int gonioDecim_ = 2;
267 int decimCount_ = 0;
268 std::array<std::atomic<std::uint64_t>, kGonioSize> gonio_ {};
269 std::atomic<int> gonioWrite_ { 0 };
270
271 std::atomic<T> correlation_ { T(0) };
272 std::atomic<T> balance_ { T(0) };
273};
274
275} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Correlation/balance meter and goniometer data source.
void processBlock(AudioBufferView< const T > buffer) noexcept
Analyzes a block (read-only; the audio is not modified).
int getGonioPoints(GonioPoint *dest, int maxCount) const noexcept
Copies the newest goniometer points (oldest first).
T getDominantLevelDb() const noexcept
double getWindowMs() const noexcept
void reset() noexcept
Clears the averages, the readouts and the goniometer ring.
T getBalance() const noexcept
T getCorrelation() const noexcept
void prepare(const AudioSpec &spec, double windowMs=300.0) noexcept
Prepares the meter. Allocation-free.
static constexpr int kGonioSize
Goniometer ring length.
Main namespace for the DSPark framework.
Describes the audio environment for a DSP processor.
Definition AudioSpec.h:37
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
Definition AudioSpec.h:71
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
static double dominantPower(double ll, double rr, double lr) noexcept
One mid/side point for goniometer displays.