DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
ContinuousClip.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
14#include "ClipperShape.h"
15#include <algorithm>
16#include <array>
17#include <cmath>
18#include <limits>
19#include <vector>
20
22{
24using Moments = std::array<double, 4>;
25inline double choose(int n, int k)
26{
27 double v = 1;
28 for (int i = 1; i <= k; ++i)
29 v *= double(n - i + 1) / i;
30 return v;
31}
32template <int N> struct Gauss
33{
34 std::array<double, N> nodes{}, weights{};
36 {
37 for (int i = 0; i < (N + 1) / 2; ++i)
38 {
39 double x = std::cos(pi<double> * (i + .75) / (N + .5)), derivative = 0;
40 for (int it = 0; it < 30; ++it)
41 {
42 double p0 = 1, p1 = x;
43 for (int j = 2; j <= N; ++j)
44 {
45 const double p = ((2 * j - 1) * x * p1 - (j - 1) * p0) / j;
46 p0 = p1;
47 p1 = p;
48 }
49 derivative = N * (x * p1 - p0) / (x * x - 1);
50 const double step = p1 / derivative;
51 x -= step;
52 if (std::abs(step) < 2e-16)
53 break;
54 }
55 const double w = 1 / ((1 - x * x) * derivative * derivative);
56 nodes[i] = (1 - x) / 2;
57 nodes[N - 1 - i] = (1 + x) / 2;
58 weights[i] = weights[N - 1 - i] = w;
59 }
60 }
61};
62
63template <Curve C, int Degree, bool NativeSlope = false, bool SubtractLinear = true,
64 int MomentCount = 4> class Interval
65{
66 static_assert(Degree >= 1 && Degree <= 11 && Degree % 2 == 1);
67 static_assert(MomentCount >= 1 && MomentCount <= 8);
68 static_assert(Degree + MomentCount <= 16); // Eight-point exact polynomial quadrature.
69 using Moments = std::array<double, MomentCount>;
70 static constexpr bool rational =
71 C == Curve::GoldenRatio || C == Curve::SymmetricKnee || C == Curve::AsymmetricKnee;
72 static constexpr int count = Degree + 1;
73 static constexpr double referenceSlope = NativeSlope ? clipperSmallSignalSlope<C, double>() : 1.;
74 using Poly = std::array<double, count>;
75 std::array<Poly, count> matrix_{}, bernsteinMatrix_{};
76 Gauss<8> linearQuadrature_;
77 Gauss<16> nonlinearQuadrature_;
78 double ceiling_;
79 double reconstructionBound_ = 1;
80 double arithmeticBound_ = 1;
81 std::array<double, 11> levels_{};
82 int levelCount_ = 0;
83 static double value(const Poly &p, double t)
84 {
85 double v = p[Degree];
86 for (int i = Degree - 1; i >= 0; --i)
87 v = v * t + p[i];
88 return v;
89 }
90 static double slope(const Poly &p, double t)
91 {
92 double v = Degree * p[Degree];
93 for (int i = Degree - 1; i >= 1; --i)
94 v = v * t + i * p[i];
95 return v;
96 }
97 static void add(Moments &a, const Moments &b)
98 {
99 for (int i = 0; i < MomentCount; ++i)
100 a[i] += b[i];
101 }
102 // A simple real pole of the curve, at t = at outside the integration
103 // interval, with residue weight: weight / (t - at) is subtracted from the
104 // integrand (and integrated analytically by the caller). Weight 0: none.
105 struct Pole
106 {
107 double at = 0, weight = 0;
108 };
109 template <int N>
110 Moments quadrature(const Poly &p, double a, double b, const Gauss<N> &q, bool fixed = false,
111 double fixedValue = 0, Pole pole = {}) const
112 {
113 Moments out{};
114 for (int i = 0; i < N; ++i)
115 {
116 const double t = a + (b - a) * q.nodes[i], x = value(p, t);
117 const double reference = SubtractLinear ? referenceSlope * x : 0.;
118 double f = fixed ? fixedValue - reference : clipperShape<C>(x, ceiling_) - reference;
119 if (pole.weight != 0)
120 f -= pole.weight / (t - pole.at);
121 double v = (b - a) * q.weights[i] * f;
122 for (int j = 0; j < MomentCount; ++j)
123 {
124 out[j] += v;
125 v *= t;
126 }
127 }
128 return out;
129 }
130 std::array<Moments, 2> tanhQuadrature(const Poly &p, double a, double b) const
131 {
132 // Embedded G7/K15 rules reuse seven evaluations in the error estimate.
133 // Symmetric abscissae and weights are defined on [-1,1]. This changes
134 // neither the curve nor the adaptive tolerance below.
135 static constexpr std::array<double, 8> nodes{
136 .99145537112081263921, .94910791234275852453, .86486442335976907279,
137 .74153118559939443986, .58608723546769113029, .40584515137739716691,
138 .20778495500789846760, 0.};
139 static constexpr std::array<double, 8> fineWeights{
140 .02293532201052922496, .06309209262997855329, .10479001032225018384,
141 .14065325971552591875, .16900472663926790283, .19035057806478540991,
142 .20443294007529889241, .20948214108472782801};
143 static constexpr std::array<double, 4> coarseWeights{
144 .12948496616886969327, .27970539148927666790,
145 .38183005050511894495, .41795918367346938776};
146 std::array<Moments, 2> result{};
147 const double half = (b - a) * .5, center = a + half;
148 const auto accumulate = [&](double t, double fineWeight, double coarseWeight)
149 {
150 const double x = value(p, t);
151 const double reference = SubtractLinear ? referenceSlope * x : 0.;
152 double v = half * (clipperShape<C>(x, ceiling_) - reference);
153 for (int j = 0; j < MomentCount; ++j)
154 {
155 result[1][j] += fineWeight * v;
156 if (coarseWeight != 0.) result[0][j] += coarseWeight * v;
157 v *= t;
158 }
159 };
160 accumulate(center, fineWeights[7], coarseWeights[3]);
161 for (int i = 0; i < 7; ++i)
162 {
163 const double coarseWeight = i % 2 ? coarseWeights[i / 2] : 0.;
164 accumulate(center - half * nodes[i], fineWeights[i], coarseWeight);
165 accumulate(center + half * nodes[i], fineWeights[i], coarseWeight);
166 }
167 return result;
168 }
169 Moments adaptive(const Poly &p, double a, double b, int depth = 0, Pole pole = {}) const
170 {
171 const auto estimates = [&] {
172 if constexpr (C == Curve::Tanh) return tanhQuadrature(p, a, b);
173 else return std::array<Moments, 2>{quadrature(p, a, b, linearQuadrature_, false, 0, pole),
174 quadrature(p, a, b, nonlinearQuadrature_, false, 0, pole)};
175 }();
176 const auto &coarse = estimates[0], &fine = estimates[1];
177 const double scale =
178 1 + std::abs(value(p, a)) + std::abs(value(p, b)) + std::abs(value(p, (a + b) / 2));
179 const double tolerance = (b - a) * 1e-13 * scale;
180 double error = 0;
181 for (int i = 0; i < MomentCount; ++i)
182 error = std::max(error, std::abs(fine[i] - coarse[i]));
183 if (error <= tolerance)
184 return fine;
185 if (depth >= 24)
186 return {std::numeric_limits<double>::quiet_NaN()};
187 auto out = adaptive(p, a, (a + b) / 2, depth + 1, pole);
188 add(out, adaptive(p, (a + b) / 2, b, depth + 1, pole));
189 return out;
190 }
191 Moments linearMoments(const Poly &p, double a, double b) const
192 {
193 // Integrate a complete, provably linear interval algebraically. Retain
194 // the established four-moment arithmetic for existing callers.
195 if constexpr (MomentCount != 4)
196 {
197 if (a == 0 && b == 1)
198 {
199 static constexpr auto weights = [] {
200 std::array<Poly, MomentCount> result{};
201 for (int j = 0; j < MomentCount; ++j)
202 for (int k = 0; k < count; ++k)
203 result[j][k] = 1. / (j + k + 1);
204 return result;
205 }();
206 Moments out{};
207 for (int j = 0; j < MomentCount; ++j)
208 for (int k = 0; k < count; ++k)
209 out[j] += p[k] * weights[j][k];
210 return out;
211 }
212 }
213 return quadrature(p, a, b, linearQuadrature_);
214 }
215 // A rational knee beyond its knee is sign (c - R^2 / q(t)), with R = c - k
216 // and q = sign p - (2k - c): the curve has a pole where q vanishes. A
217 // segment that starts at a knee crossing has a real root of q just
218 // outside it, about R / |p'| away, so the Gauss rules converge slowly and
219 // the bisection descends toward it; on loud material that was most of the
220 // integration cost. The root t* is located by Newton from the tangent
221 // estimate, its simple-pole part -sign R^2 / (q'(t*) (t - t*)) is
222 // integrated in closed form, and the same rules and tolerance integrate the
223 // smooth remainder, usually without bisection. Segments without a nearby
224 // real root keep the plain bisection.
225 Moments rationalSegment(const Poly &p, double a, double b, double x) const
226 {
227 const auto limits = clipperLinearLimits<C>(ceiling_);
228 const double sign = x >= 0 ? 1. : -1.;
229 const double knee = x >= 0 ? limits[1] : -limits[0];
230 const double level = 2 * knee - ceiling_, range = ceiling_ - knee, width = b - a;
231 const double ra = sign * slope(p, a), rb = -sign * slope(p, b);
232 const double da = ra > 0 ? (sign * value(p, a) - level) / ra : std::numeric_limits<double>::infinity();
233 const double db = rb > 0 ? (sign * value(p, b) - level) / rb : std::numeric_limits<double>::infinity();
234 const bool fromA = da <= db;
235 const double d = fromA ? da : db;
236 if (!(d > 0) || !(d < .25 * width))
237 return adaptive(p, a, b);
238 const double end = fromA ? a : b, outward = fromA ? -1. : 1.;
239 double root = end + outward * d, derivative = 0;
240 bool converged = false;
241 for (int it = 0; it < 16 && !converged; ++it)
242 {
243 const double f = sign * value(p, root) - level;
244 derivative = sign * slope(p, root);
245 if (!(derivative != 0) || !std::isfinite(f))
246 break;
247 const double step = f / derivative;
248 root -= step;
249 converged = std::abs(step) <= 4 * std::numeric_limits<double>::epsilon() * (1 + std::abs(root));
250 }
251 derivative = sign * slope(p, root);
252 if (!converged || !(outward * (root - end) > 0) || !(outward * (root - end) < width) ||
253 !(std::abs(derivative) > 0) || !std::isfinite(derivative))
254 return adaptive(p, a, b);
255 const Pole pole{root, -sign * range * range / derivative};
256 auto out = adaptive(p, a, b, 0, pole);
257 // integral(t^j / (t - t*)) = sum_m t*^(j-1-m) (b^(m+1) - a^(m+1)) / (m+1)
258 // + t*^j ln((b - t*) / (a - t*)).
259 const double logarithm = std::log((b - root) / (a - root));
260 double rootPower = 1; // t*^j
261 std::array<double, MomentCount> powerSums{}; // (b^(m+1) - a^(m+1)) / (m+1)
262 double pa = a, pb = b;
263 for (int m = 0; m < MomentCount; ++m)
264 {
265 powerSums[m] = (pb - pa) / (m + 1);
266 pa *= a;
267 pb *= b;
268 }
269 for (int j = 0; j < MomentCount; ++j)
270 {
271 double polynomial = 0, rootFactor = 1; // t*^(j-1-m), m from j-1 down to 0
272 for (int m = j - 1; m >= 0; --m)
273 {
274 polynomial += rootFactor * powerSums[m];
275 rootFactor *= root;
276 }
277 out[j] += pole.weight * (polynomial + rootPower * logarithm);
278 rootPower *= root;
279 }
280 return out;
281 }
282 Moments segment(const Poly &p, double a, double b) const
283 {
284 const double x = value(p, (a + b) / 2);
285 if constexpr (C == Curve::Hard)
286 {
287 if (std::abs(x) <= ceiling_)
288 {
289 if constexpr (SubtractLinear) return {};
290 else return linearMoments(p, a, b);
291 }
292 return quadrature(p, a, b, linearQuadrature_, true, std::copysign(ceiling_, x));
293 }
294 else if constexpr (C == Curve::Sine)
295 {
296 if (std::abs(x) >= ceiling_ * halfPi<double>)
297 return quadrature(p, a, b, linearQuadrature_, true, clipperShape<C>(x, ceiling_));
298 }
299 else if constexpr (rational)
300 {
301 const auto limits = clipperLinearLimits<C>(ceiling_);
302 if (x >= limits[0] && x <= limits[1])
303 {
304 if constexpr (SubtractLinear) return {};
305 else return linearMoments(p, a, b);
306 }
307 }
308 else if constexpr (C == Curve::Tanh)
309 {
310 if (std::abs(x) >= 24 * ceiling_)
311 return quadrature(p, a, b, linearQuadrature_, true, std::copysign(ceiling_, x));
312 }
313 if constexpr (rational)
314 return rationalSegment(p, a, b, x);
315 else if constexpr (C == Curve::Tanh)
316 return adaptive(p, a, b);
317 else
318 return quadrature(p, a, b, nonlinearQuadrature_);
319 }
320 double root(const Poly &p, double a, double b, double target) const
321 {
322 double fa = value(p, a) - target, fb = value(p, b) - target;
323 if (fa == 0)
324 return a;
325 if (fb == 0)
326 return b;
327 if ((fa > 0) == (fb > 0))
328 return std::numeric_limits<double>::quiet_NaN();
329 double x = a + (b - a) * (-fa) / (fb - fa);
330 for (int i = 0; i < 64; ++i)
331 {
332 const double f = value(p, x) - target;
333 if (std::abs(f) <= 2e-15 || b - a < 2e-14)
334 return x;
335 if ((f > 0) == (fa > 0))
336 {
337 a = x;
338 fa = f;
339 }
340 else
341 {
342 b = x;
343 fb = f;
344 }
345 const double d = slope(p, x);
346 const double candidate = d != 0 ? x - f / d : (a + b) / 2;
347 x = candidate > a && candidate < b ? candidate : (a + b) / 2;
348 }
349 return std::numeric_limits<double>::quiet_NaN();
350 }
351 Moments recurse(const Poly &p, const Poly &bernstein, double a, double b, int depth) const
352 {
353 const auto bounds = std::minmax_element(bernstein.begin(), bernstein.end());
354 const double low = *bounds.first, high = *bounds.second;
355 if constexpr (C == Curve::Hard)
356 {
357 if (low >= -ceiling_ && high <= ceiling_)
358 {
359 if constexpr (SubtractLinear) return {};
360 else return linearMoments(p, a, b);
361 }
362 }
363 if constexpr (rational)
364 {
365 const auto limits = clipperLinearLimits<C>(ceiling_);
366 if (low >= limits[0] && high <= limits[1])
367 {
368 if constexpr (SubtractLinear) return {};
369 else return linearMoments(p, a, b);
370 }
371 }
372 bool crosses = false;
373 for (int i = 0; i < levelCount_; ++i)
374 crosses = crosses || (low < levels_[i] && levels_[i] < high);
375 if (!crosses)
376 return segment(p, a, b);
377 // Clipping curves are 1-Lipschitz; this branch's moment error is bounded
378 // by width*range. Its width-scaled bound also sums across all leaves.
379 if (high - low < 1e-13)
380 return quadrature(p, a, b, nonlinearQuadrature_);
381 bool increasing = true, decreasing = true;
382 for (int i = 1; i < count; ++i)
383 {
384 increasing = increasing && bernstein[i] >= bernstein[i - 1];
385 decreasing = decreasing && bernstein[i] <= bernstein[i - 1];
386 }
387 if (increasing || decreasing)
388 {
389 std::array<double, 13> edges{};
390 int n = 0;
391 edges[n++] = a;
392 const double va = value(p, a), vb = value(p, b);
393 for (int i = 0; i < levelCount_; ++i)
394 if (levels_[i] > std::min(va, vb) && levels_[i] < std::max(va, vb))
395 {
396 const double crossing = root(p, a, b, levels_[i]);
397 if (!std::isfinite(crossing))
398 return {std::numeric_limits<double>::quiet_NaN()};
399 edges[n++] = crossing;
400 }
401 edges[n++] = b;
402 // A handful of edges that arrive monotonic, whichever way the
403 // segment runs: insertion is the cheapest correct order here.
404 for (int i = 1; i < n; ++i)
405 {
406 const double edge = edges[i];
407 int j = i;
408 for (; j > 0 && edges[j - 1] > edge; --j)
409 edges[j] = edges[j - 1];
410 edges[j] = edge;
411 }
412 Moments out{};
413 for (int i = 0; i + 1 < n; ++i)
414 add(out, segment(p, edges[i], edges[i + 1]));
415 return out;
416 }
417 if (depth >= 32)
418 return {std::numeric_limits<double>::quiet_NaN()};
419 Poly work = bernstein, left{}, right{};
420 left[0] = work[0];
421 right[Degree] = work[Degree];
422 for (int level = 1; level < count; ++level)
423 {
424 for (int i = 0; i < count - level; ++i)
425 work[i] = (work[i] + work[i + 1]) * .5;
426 left[level] = work[0];
427 right[Degree - level] = work[Degree - level];
428 }
429 auto out = recurse(p, left, a, (a + b) / 2, depth + 1);
430 add(out, recurse(p, right, (a + b) / 2, b, depth + 1));
431 return out;
432 }
433
434 public:
435 std::vector<double> linearKernel() const
436 {
437 static_assert(MomentCount == 4); // Cubic B-spline synthesis below.
438 constexpr std::array<Moments, 4> kernels{
439 {{1, -3, 3, -1}, {4, 0, -6, 3}, {1, 3, 3, -3}, {0, 0, 0, 1}}};
440 std::vector<double> result(Degree + 4);
441 for (int i = 0; i < count; ++i)
442 {
443 Moments moments{};
444 for (int j = 0; j < 4; ++j)
445 for (int k = 0; k < count; ++k)
446 moments[j] += matrix_[i][k] / (k + j + 1);
447 for (int lag = 0; lag < 4; ++lag)
448 for (int j = 0; j < 4; ++j)
449 result[Degree - i + lag] += moments[j] * kernels[lag][j] / 6;
450 }
451 return result;
452 }
453 explicit Interval(double ceiling) : ceiling_(ceiling)
454 {
455 constexpr int begin = -(Degree - 1) / 2;
456 for (int node = 0; node < count; ++node)
457 {
458 std::array<long double, count> p{};
459 p[0] = 1;
460 int order = 0;
461 const int x = begin + node;
462 for (int other = 0; other < count; ++other)
463 if (other != node)
464 {
465 const int y = begin + other;
466 std::array<long double, count> next{};
467 for (int j = 0; j <= order; ++j)
468 {
469 next[j] -= p[j] * y / (x - y);
470 next[j + 1] += p[j] / (x - y);
471 }
472 p = next;
473 ++order;
474 }
475 for (int j = 0; j < count; ++j)
476 matrix_[node][j] = static_cast<double>(p[j]);
477 }
478 for (int i = 0; i < count; ++i)
479 for (int j = 0; j <= i; ++j)
480 bernsteinMatrix_[i][j] = choose(i, j) / choose(Degree, j);
481 // Convex-hull bound on the complete reconstructed interval. It permits
482 // exact linear-region bypass before the per-sample matrix products.
483 for (int row = 0; row < count; ++row)
484 {
485 long double norm = 0, arithmeticNorm = 0;
486 for (int node = 0; node < count; ++node)
487 {
488 long double coefficient = 0;
489 for (int column = 0; column <= row; ++column)
490 {
491 coefficient += static_cast<long double>(bernsteinMatrix_[row][column]) *
492 matrix_[node][column];
493 arithmeticNorm +=
494 std::abs(static_cast<long double>(bernsteinMatrix_[row][column]) *
495 matrix_[node][column]);
496 }
497 norm += std::abs(coefficient);
498 }
499 reconstructionBound_ = std::max(reconstructionBound_, static_cast<double>(norm));
500 arithmeticBound_ = std::max(arithmeticBound_, static_cast<double>(arithmeticNorm));
501 }
502 setCeiling(ceiling);
503 }
504 void setCeiling(double ceiling)
505 {
506 ceiling_ = ceiling;
507 if constexpr (C == Curve::Tanh)
508 {
509 levels_ = {-24 * ceiling, -12 * ceiling, -6 * ceiling, -3 * ceiling, -ceiling, 0,
510 ceiling, 3 * ceiling, 6 * ceiling, 12 * ceiling, 24 * ceiling};
511 levelCount_ = 11;
512 }
513 else if constexpr (rational)
514 {
515 const auto limits = clipperLinearLimits<C>(ceiling);
516 levels_[0] = limits[0];
517 levels_[1] = limits[1];
518 levelCount_ = 2;
519 }
520 else
521 {
522 const double limit = C == Curve::Sine ? ceiling * halfPi<double> : ceiling;
523 levels_[0] = -limit;
524 levels_[1] = limit;
525 levelCount_ = 2;
526 }
527 }
528 // Convex-hull norm for the complete interpolation interval. Offline
529 // callers can bound finite-source tails using the same reconstruction.
530 [[nodiscard]] double reconstructionBound() const noexcept
531 {
532 return reconstructionBound_;
533 }
540 [[nodiscard]] Moments polynomial(const Poly &power) const noexcept
541 {
542 Poly bernstein{};
543 for (double coefficient : power)
544 if (!std::isfinite(coefficient))
545 return {std::numeric_limits<double>::quiet_NaN()};
546 if (std::all_of(power.begin(), power.end(), [](double value) { return value == 0; }))
547 return {};
548 for (int i = 0; i < count; ++i)
549 for (int j = 0; j <= i; ++j)
550 bernstein[i] += power[j] * bernsteinMatrix_[i][j];
551 return recurse(power, bernstein, 0, 1, 0);
552 }
553 Moments operator()(const std::array<double, count> &samples) const noexcept
554 {
555 if (std::all_of(samples.begin(), samples.end(), [](double value) { return value == 0; }))
556 return {};
557 if constexpr (SubtractLinear && (C == Curve::Hard || rational))
558 {
559 double low = samples[0], high = samples[0];
560 for (double sample : samples)
561 {
562 if (!std::isfinite(sample))
563 return {std::numeric_limits<double>::quiet_NaN()};
564 low = std::min(low, sample);
565 high = std::max(high, sample);
566 }
567 const double center = 0.5 * low + 0.5 * high;
568 const double radius = (0.5 * high - 0.5 * low) * reconstructionBound_;
569 // Covers both dot-product reductions, the rounded basis and the
570 // midpoint/radius arithmetic; count is at most twelve.
571 const double margin = 128 * std::numeric_limits<double>::epsilon() * arithmeticBound_ *
572 (std::abs(center) + radius) +
573 256 * std::numeric_limits<double>::denorm_min();
574 const auto limits = [&] {
575 if constexpr (rational)
576 return clipperLinearLimits<C>(ceiling_);
577 else
578 return std::array<double, 2>{-ceiling_, ceiling_};
579 }();
580 if (center - radius - margin >= limits[0] && center + radius + margin <= limits[1])
581 return {};
582 }
583 Poly power{}, bernstein{};
584 for (int i = 0; i < count; ++i)
585 for (int j = 0; j < count; ++j)
586 power[j] += samples[i] * matrix_[i][j];
587 for (int i = 0; i < count; ++i)
588 for (int j = 0; j <= i; ++j)
589 bernstein[i] += power[j] * bernsteinMatrix_[i][j];
590 return recurse(power, bernstein, 0, 1, 0);
591 }
592};
593
594inline std::vector<double> inverseBoxPower(int order)
595{
596 // (asin(sqrt(s))/sqrt(s))^4, where s=(2-z-z^-1)/4. Restores the
597 // integrated cubic B-spline passband without an IIR pole near Nyquist.
598 std::vector<double> series(static_cast<std::size_t>(order + 1));
599 for (int k = 0; k <= order; ++k)
600 series[k] = choose(2 * k, k) / std::pow(4., k) / (2 * k + 1);
601 std::vector<double> combined(static_cast<std::size_t>(order + 1));
602 combined[0] = 1;
603 for (int power = 0; power < 4; ++power)
604 {
605 std::vector<double> next(combined.size());
606 for (int i = 0; i <= order; ++i)
607 for (int j = 0; i + j <= order; ++j)
608 next[i + j] += combined[i] * series[j];
609 combined = std::move(next);
610 }
611 std::vector<double> taps(static_cast<std::size_t>(2 * order + 1)), basis(taps.size());
612 basis[order] = 1;
613 for (int k = 0; k <= order; ++k)
614 {
615 for (std::size_t i = 0; i < taps.size(); ++i)
616 taps[i] += combined[k] * basis[i];
617 if (k == order)
618 break;
619 std::vector<double> next(taps.size());
620 for (int j = order - k; j <= order + k; ++j)
621 {
622 next[j - 1] -= .25 * basis[j];
623 next[j] += .5 * basis[j];
624 next[j + 1] -= .25 * basis[j];
625 }
626 basis = std::move(next);
627 }
628 return taps;
629}
630
643template <Curve C, int Degree = 11, bool NativeSlope = false, bool SubtractLinear = true> class Residual final
644{
645 static constexpr int degree = Degree;
647 std::array<double, degree + 1> samples_{};
648 std::array<Moments, 4> history_{};
649 int sampleWrite_ = 0, momentWrite_ = 0;
650
651 public:
653 void reset(double ceiling) noexcept
654 {
655 integral_.setCeiling(ceiling);
656 samples_.fill(0);
657 history_.fill({});
658 sampleWrite_ = momentWrite_ = 0;
659 }
661 [[nodiscard]] std::vector<double> linearKernel() const
662 {
663 return integral_.linearKernel();
664 }
666 double process(double x) noexcept
667 {
668 samples_[sampleWrite_] = x;
669 sampleWrite_ = (sampleWrite_ + 1) % (degree + 1);
670 std::array<double, degree + 1> ordered{};
671 for (int i = 0; i <= degree; ++i)
672 ordered[i] = samples_[(sampleWrite_ + i) % (degree + 1)];
673 history_[momentWrite_] = integral_(ordered);
674 const auto &a = history_[(momentWrite_ + 1) % 4];
675 const auto &b = history_[(momentWrite_ + 2) % 4];
676 const auto &c = history_[(momentWrite_ + 3) % 4];
677 const auto &d = history_[momentWrite_];
678 const double out = (a[3] + b[0] + 3 * b[1] + 3 * b[2] - 3 * b[3] + 4 * c[0] - 6 * c[2] +
679 3 * c[3] + d[0] - 3 * d[1] + 3 * d[2] - d[3]) /
680 6;
681 momentWrite_ = (momentWrite_ + 1) % 4;
682 return out;
683 }
684};
685} // namespace dspark::detail::continuous_clip
Moments operator()(const std::array< double, count > &samples) const noexcept
std::vector< double > linearKernel() const
Moments polynomial(const Poly &power) const noexcept
Integrates an already reconstructed power polynomial on [0,1]. Returns integral(t^j * shape(p(t)),...
Streaming cubic B-spline moments of a reconstructed clipping residual.
double process(double x) noexcept
Processes one high-rate sample, returning its integrated residual.
std::vector< double > linearKernel() const
Constructs the matching linear FIR during setup.
void reset(double ceiling) noexcept
Resets reconstruction history and sets the positive finite ceiling.
std::array< double, 4 > Moments
std::vector< double > inverseBoxPower(int order)