DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Hilbert.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
25#include "DspMath.h"
26#include "DenormalGuard.h"
27#include "SimdOps.h" // SIMD dot product for the FIR convolution
28
29#include <algorithm>
30#include <array>
31#include <cassert>
32#include <cmath>
33#include <cstdint>
34#include <span>
35
36namespace dspark {
37
38namespace detail {
39// Unwindowed discrete Hilbert impulse, shared by finite-source operators and
40// the real-time windowed FIR. Keep the parity test in the integer source clock.
41[[nodiscard]] inline double hilbertIdealImpulse(std::int64_t index) noexcept
42{
43 constexpr double kPi = 3.14159265358979323846;
44 return index % 2 == 0 ? 0.0 : 2.0 / (kPi * static_cast<double>(index));
45}
46} // namespace detail
47
72template <FloatType T>
74{
75public:
76 struct Result
77 {
78 T real;
79 T imag;
80 };
81
88 void prepare(double sampleRate) noexcept
89 {
90 assert(sampleRate > 0.0);
91 if (!(sampleRate > 0.0)) return;
92
93 sampleRate_ = sampleRate;
94 reset();
95 isPrepared_ = true;
96 }
97
114 [[nodiscard]] inline Result process(T input) noexcept
115 {
116 const int side = parity_;
117 T* line = lines_[static_cast<size_t>(side)].data();
118 const int wp = writePos_[static_cast<size_t>(side)];
119 line[wp] = input;
120 line[wp + kNonZero] = input;
121
122 // window[m] = x[n - 2 * (kNonZero - 1 - m)], oldest first. The pointer
123 // is cached in a member so the hot path never touches the
124 // magic-static init guard.
125 const T imag = simd::dotProduct(kernelData_, line + wp + 1, kNonZero);
126 writePos_[static_cast<size_t>(side)] = (wp + 1 == kNonZero) ? 0 : (wp + 1);
127
128 // real = x[n - kCenter]. kCenter is odd, so it is in the other line,
129 // whose newest entry is x[n - 1]: (kCenter - 1) / 2 entries back.
130 const int other = side ^ 1;
131 const int op = writePos_[static_cast<size_t>(other)];
132 const T re = lines_[static_cast<size_t>(other)]
133 [static_cast<size_t>(op + kNonZero - 1 - (kCenter - 1) / 2)];
134 parity_ = other;
135 return { re, imag };
136 }
137
144 void processBlock(std::span<const T> input,
145 std::span<T> outReal,
146 std::span<T> outImag) noexcept
147 {
148 assert(isPrepared_);
149 assert(outReal.size() >= input.size() && outImag.size() >= input.size());
150 DenormalGuard dg;
151
152 const size_t numSamples =
153 std::min(input.size(), std::min(outReal.size(), outImag.size()));
154 for (size_t i = 0; i < numSamples; ++i)
155 {
156 const auto res = process(input[i]);
157 outReal[i] = res.real;
158 outImag[i] = res.imag;
159 }
160 }
161
163 void reset() noexcept
164 {
165 for (auto& l : lines_) l.fill(T(0));
166 writePos_ = { 0, 0 };
167 parity_ = 0;
168 }
169
171 [[nodiscard]] static constexpr int getLatencySamples() noexcept { return kCenter; }
172
173private:
174 // 191-tap FIR: < 0.1% analytic ripple above ~1 kHz at 48 kHz (< 2.5% at
175 // 500 Hz), 95-sample group delay. Odd length keeps a true integer center tap.
176 static constexpr int kTaps = 191;
177 static constexpr int kCenter = kTaps / 2;
178 static constexpr int kNonZero = (kTaps + 1) / 2;
179
183 [[nodiscard]] static const std::array<T, kNonZero>& nonZeroKernel() noexcept
184 {
185 static const std::array<T, kNonZero> kernel = []
186 {
187 std::array<T, kNonZero> k {};
188 constexpr double kPi = 3.14159265358979323846;
189 for (int m = 0; m < kNonZero; ++m)
190 {
191 // Ideal Hilbert kernel 2/(pi*n) at odd n = lag - kCenter,
192 // windowed with Blackman to control ripple / sideband leakage.
193 const int lag = 2 * (kNonZero - 1 - m);
194 const double ideal = detail::hilbertIdealImpulse(lag - kCenter);
195 const double w = 0.42
196 - 0.5 * std::cos(2.0 * kPi * static_cast<double>(lag) / static_cast<double>(kTaps - 1))
197 + 0.08 * std::cos(4.0 * kPi * static_cast<double>(lag) / static_cast<double>(kTaps - 1));
198 k[static_cast<size_t>(m)] = static_cast<T>(ideal * w);
199 }
200 return k;
201 }();
202 return kernel;
203 }
204
205 double sampleRate_ = 0.0;
206 bool isPrepared_ = false;
207 int parity_ = 0;
208 std::array<int, 2> writePos_ { 0, 0 };
209
210 // Cached at construction so process() skips the magic-static guard check
211 // (the static outlives every instance; copies stay valid).
212 const T* kernelData_ = nonZeroKernel().data();
213
214 // One mirrored delay line (double-write) per sample parity. No
215 // over-alignment: the window starts at a variable offset every sample, so
216 // the SIMD dot product uses unaligned loads regardless.
217 std::array<std::array<T, kNonZero * 2>, 2> lines_ {};
218};
219
243template <FloatType T>
245{
246public:
247 struct Result
248 {
251 };
252
254 void reset() noexcept
255 {
256 for (auto& s : sections_) s = {};
257 delayedImag_ = 0.0;
258 }
259
261 [[nodiscard]] inline Result process(T input) noexcept
262 {
263 double re = 0.0, im = 0.0;
264 step(static_cast<double>(input), re, im);
265 return { static_cast<T>(re), static_cast<T>(im) };
266 }
267
270 [[nodiscard]] inline T magnitude(T input) noexcept
271 {
272 double re = 0.0, im = 0.0;
273 step(static_cast<double>(input), re, im);
274 return static_cast<T>(std::sqrt(re * re + im * im));
275 }
276
285 void magnitudeBlock(const T* in, T* out, int numSamples) noexcept
286 {
287 constexpr int kChunk = 64;
288 double re[kChunk];
289 double im[kChunk];
290 for (int start = 0; start < numSamples; start += kChunk)
291 {
292 const int n = std::min(kChunk, numSamples - start);
293 for (int i = 0; i < n; ++i)
294 re[i] = im[i] = static_cast<double>(in[start + i]);
295 for (int k = 0; k < kSections; ++k)
296 Section::runPair(sections_[static_cast<size_t>(k)], re, kReal[k],
297 sections_[static_cast<size_t>(kSections + k)], im, kImag[k], n);
298 for (int i = 0; i < n; ++i)
299 {
300 const double imDelayed = delayedImag_;
301 delayedImag_ = im[i];
302 out[start + i] = static_cast<T>(std::sqrt(re[i] * re[i] + imDelayed * imDelayed));
303 }
304 }
305 }
306
307private:
308 static constexpr int kSections = 7;
309
310 inline void step(double input, double& re, double& im) noexcept
311 {
312 re = input;
313 double quad = input;
314 for (int k = 0; k < kSections; ++k)
315 {
316 re = sections_[static_cast<size_t>(k)].process(re, kReal[k]);
317 quad = sections_[static_cast<size_t>(kSections + k)].process(quad, kImag[k]);
318 }
319 im = delayedImag_;
320 delayedImag_ = quad;
321 }
322
324 struct Section
325 {
326 double x1 = 0.0, x2 = 0.0, y1 = 0.0, y2 = 0.0;
327
328 // y = (c x[n] - x[n-2]) + c y[n-2]: the recursive term enters last,
329 // so the loop-carried path is one multiply and one add.
330 inline double process(double x, double c) noexcept
331 {
332 const double y = (c * x - x2) + c * y2;
333 x2 = x1; x1 = x;
334 y2 = y1; y1 = y;
335 return y;
336 }
337
341 static inline void runPair(Section& p, double* dp, double cp,
342 Section& q, double* dq, double cq, int n) noexcept
343 {
344 double px1 = p.x1, px2 = p.x2, py1 = p.y1, py2 = p.y2;
345 double qx1 = q.x1, qx2 = q.x2, qy1 = q.y1, qy2 = q.y2;
346 for (int i = 0; i < n; ++i)
347 {
348 const double xp = dp[i];
349 const double xq = dq[i];
350 const double yp = (cp * xp - px2) + cp * py2;
351 const double yq = (cq * xq - qx2) + cq * qy2;
352 px2 = px1; px1 = xp; py2 = py1; py1 = yp;
353 qx2 = qx1; qx1 = xq; qy2 = qy1; qy1 = yq;
354 dp[i] = yp;
355 dq[i] = yq;
356 }
357 p.x1 = px1; p.x2 = px2; p.y1 = py1; p.y2 = py2;
358 q.x1 = qx1; q.x2 = qx2; q.y1 = qy1; q.y2 = qy2;
359 }
360 };
361
362 static constexpr double kReal[kSections] = {
363 0.0849750635881296, 0.5135957829646070, 0.8197816632773615, 0.9420612863757530,
364 0.9822486171863649, 0.9947076541867014, 0.9986500580725346 };
365 static constexpr double kImag[kSections] = { // followed by the one-sample delay
366 0.2887645620083060, 0.6955314021190576, 0.8968265992273647, 0.9678214299445055,
367 0.9902622348692460, 0.9971984927047717, 0.9995996402566010 };
368
369 std::array<Section, 2 * kSections> sections_ {};
370 double delayedImag_ = 0.0;
371};
372
373} // namespace dspark
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Zero-latency analytic pair from two allpass chains (a 90-degree phase-difference network).
Definition Hilbert.h:245
Result process(T input) noexcept
Processes one sample into the analytic pair. RT-safe.
Definition Hilbert.h:261
void reset() noexcept
Clears the allpass states. RT-safe.
Definition Hilbert.h:254
T magnitude(T input) noexcept
Processes one sample and returns the analytic magnitude sqrt(real^2 + imag^2): a ripple-free envelope...
Definition Hilbert.h:270
void magnitudeBlock(const T *in, T *out, int numSamples) noexcept
Analytic magnitude of a block: out[i] = |analytic(in[i])|.
Definition Hilbert.h:285
90-degree phase-differencing network (analytic-signal generator).
Definition Hilbert.h:74
static constexpr int getLatencySamples() noexcept
FIR group-delay latency applied to both outputs, in samples.
Definition Hilbert.h:171
void reset() noexcept
Resets the delay line. Mandatory when seeking or starting playback.
Definition Hilbert.h:163
void prepare(double sampleRate) noexcept
Prepares the transformer. The FIR kernel is sample-rate independent; sampleRate is accepted for API s...
Definition Hilbert.h:88
Result process(T input) noexcept
Processes one sample, returning the analytic signal {real, imag}.
Definition Hilbert.h:114
void processBlock(std::span< const T > input, std::span< T > outReal, std::span< T > outImag) noexcept
Processes a block of samples. Optimized for CPU cache.
Definition Hilbert.h:144
double hilbertIdealImpulse(std::int64_t index) noexcept
Definition Hilbert.h:41
float dotProduct(const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int count) noexcept
Computes the dot product of two arrays.
Definition SimdOps.h:644
Main namespace for the DSPark framework.
T real
In-phase component (allpass-filtered input).
Definition Hilbert.h:249
T imag
Quadrature component, 90 degrees behind real (like the Hilbert transform of a cosine).
Definition Hilbert.h:250
T real
In-phase component (input delayed by the FIR group delay).
Definition Hilbert.h:78
T imag
Quadrature component (90-deg shifted).
Definition Hilbert.h:79