DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
OfflineClipProjection.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
12#include "OfflineSinc.h"
13#if DSPARK_HAS_OFFLINE
14#include "../FIRFilter.h"
15#include "../SimdOps.h"
16#include "ContinuousClip.h"
17#include "NativeClipCoefficients.h"
18#include <algorithm>
19#include <array>
20#include <atomic>
21#include <cmath>
22#include <cstdint>
23#include <limits>
24#include <memory>
25#include <numbers>
26#include <optional>
27#include <span>
28#include <utility>
29#include <vector>
30
32{
35
36enum class Exterior
37{
38 Linear,
40};
41
42// Source-rate (factor 1) clipping correction. A cubic B-spline average with
43// inverse compensation attenuates distortion above Nyquist by sinc^4 of its
44// frequency and restores the band by 1/sinc^4 of where it folds, so a
45// harmonic near fs folds back nearly intact: a 10 kHz sine clipped by 6 dB
46// at 48 kHz left its third harmonic at 18 kHz at -24 dB. Here the residual
47// shape(p) - slope * p of a windowed-sinc reconstruction p (32 samples, see
48// NativeClipCoefficients.h) is integrated against five polynomial moments
49// per sample interval, and five moment FIRs synthesize a continuous kernel
50// whose spectrum is flat within 0.01 dB to 0.40 fs, -54 dB at 0.46 fs and
51// below -65 dB from 0.47 fs across all of its images (to 12 fs). The output is slope * x plus that band-limited
52// residual: unclipped intervals contribute exactly zero (the Bernstein hull
53// test of the shared integral), so unclipped PCM stays exact, and so does the
54// source content near Nyquist. Distortion between 0.40 and 0.46 fs is
55// attenuated by the transition.
56template <ClipperCurve C> class NativeClipKernel final
57{
58 static constexpr int degree = 11, block = 256;
59 static constexpr int inputHistory = native_clip_coefficients::reconstructionTaps - 1;
60 static constexpr int frameHistory = native_clip_coefficients::projectionTaps - 1;
61 static constexpr int powers = native_clip_coefficients::powers;
62 static constexpr int moments = native_clip_coefficients::moments;
63 static constexpr bool linearRegion =
66 static_assert(powers == degree + 1);
68 // input_: history then one block; powers_: one block per coefficient;
69 // frames_: one row per moment, history then one block; scratch_: one block.
70 std::vector<double> input_, powers_, frames_, output_, scratch_, reference_;
71 std::array<double, 2> limits_{-1., 1.};
72
73 public:
74 static constexpr int delay = native_clip_coefficients::delay;
75 static constexpr int history = inputHistory + frameHistory;
77 [[nodiscard]] static constexpr std::size_t storage() noexcept
78 {
79 return static_cast<std::size_t>(inputHistory + block + powers * block +
80 (frameHistory + block) * moments + 2 * block + delay + block);
81 }
83 : input_(inputHistory + block), powers_(static_cast<std::size_t>(powers) * block),
84 frames_(static_cast<std::size_t>(frameHistory + block) * moments), output_(block), scratch_(block),
85 reference_(delay + block)
86 {
87 }
88 void reset(double ceiling) noexcept
89 {
90 integral_.setCeiling(ceiling);
91 if constexpr (C == ClipperCurve::Hard)
92 limits_ = {-ceiling, ceiling};
93 else if constexpr (linearRegion)
94 limits_ = clipperLinearLimits<C>(ceiling);
95 std::fill(input_.begin(), input_.end(), 0.);
96 std::fill(frames_.begin(), frames_.end(), 0.);
97 std::fill(reference_.begin(), reference_.end(), 0.);
98 }
99 // nonlinear: source samples in, band-limited residual out, delay samples
100 // later. reference: the per-sample correction in, delayed by delay.
101 void process(double *nonlinear, double *reference, int count)
102 {
103 namespace nc = native_clip_coefficients;
104 constexpr auto row = static_cast<std::size_t>(frameHistory + block);
105 for (int offset = 0; offset < count;)
106 {
107 const int size = std::min(block, count - offset);
108 std::copy_n(nonlinear + offset, size, input_.data() + inputHistory);
109 std::array<double *, powers> powerOut{};
110 for (int k = 0; k < powers; ++k)
111 powerOut[static_cast<std::size_t>(k)] = powers_.data() + static_cast<std::size_t>(k) * block;
112 simd::firCorrelateBank<double, powers>(input_.data(), nc::reconstruction.data(),
113 nc::reconstructionTaps, powerOut.data(), size);
114 std::copy_n(input_.data() + size, inputHistory, input_.data());
115 for (int i = 0; i < size; ++i)
116 {
117 std::array<double, powers> power{};
118 double radius = 0;
119 for (int k = 0; k < powers; ++k)
120 {
121 power[static_cast<std::size_t>(k)] = powerOut[static_cast<std::size_t>(k)][i];
122 if (k)
123 radius += std::abs(power[static_cast<std::size_t>(k)]);
124 }
125 std::array<double, moments> value{};
126 // |p(t) - p(0)| <= sum |p_k| on [0,1]: a polynomial inside the
127 // linear region has exactly zero residual; skip its integral.
128 const double margin = 64 * std::numeric_limits<double>::epsilon() *
129 (std::abs(power[0]) + radius);
130 if (!linearRegion || !(power[0] - radius - margin >= limits_[0] &&
131 power[0] + radius + margin <= limits_[1]))
132 value = integral_.polynomial(power);
133 for (int q = 0; q < moments; ++q)
134 {
135 if (!std::isfinite(value[static_cast<std::size_t>(q)]))
137 frames_[static_cast<std::size_t>(q) * row + frameHistory + static_cast<std::size_t>(i)] =
138 value[static_cast<std::size_t>(q)];
139 }
140 }
141 for (int q = 0; q < moments; ++q)
142 {
143 double *frames = frames_.data() + static_cast<std::size_t>(q) * row;
144 simd::firCorrelate(frames, nc::projection.data() + static_cast<std::size_t>(q) * nc::projectionTaps,
145 nc::projectionTaps, q ? scratch_.data() : output_.data(), size, 1.);
146 if (q)
147 for (int i = 0; i < size; ++i)
148 output_[static_cast<std::size_t>(i)] += scratch_[static_cast<std::size_t>(i)];
149 std::copy_n(frames + size, frameHistory, frames);
150 }
151 std::copy_n(output_.data(), size, nonlinear + offset);
152 std::copy_n(reference + offset, size, reference_.data() + delay);
153 std::copy_n(reference_.data(), size, reference + offset);
154 std::copy_n(reference_.data() + size, delay, reference_.data());
155 offset += size;
156 }
157 }
159 [[nodiscard]] static double reconstructionBound()
160 {
161 namespace nc = native_clip_coefficients;
162 long double worst = 1;
163 for (int row = 0; row < powers; ++row)
164 {
165 long double norm = 0;
166 for (int tap = 0; tap < nc::reconstructionTaps; ++tap)
167 {
168 long double coefficient = 0;
169 for (int column = 0; column <= row; ++column)
170 coefficient += static_cast<long double>(continuous_clip::choose(row, column) /
171 continuous_clip::choose(degree, column)) *
172 nc::reconstruction[static_cast<std::size_t>(tap) * powers +
173 static_cast<std::size_t>(column)];
174 norm += std::abs(coefficient);
175 }
176 worst = std::max(worst, norm);
177 }
178 return static_cast<double>(worst);
179 }
181 [[nodiscard]] static double kernelNorm()
182 {
183 namespace nc = native_clip_coefficients;
184 // Each tap is a quartic on its unit interval. On sixteen subintervals
185 // its Bernstein coefficients bound it, and every Bernstein basis
186 // polynomial integrates to width / moments.
187 constexpr int pieces = 16;
188 long double norm = 0;
189 for (int tap = 0; tap < nc::projectionTaps; ++tap)
190 for (int piece = 0; piece < pieces; ++piece)
191 {
192 const long double a = static_cast<long double>(piece) / pieces, w = 1.L / pieces;
193 std::array<long double, moments> shifted{};
194 for (int k = 0; k < moments; ++k)
195 for (int j = k; j < moments; ++j)
196 shifted[static_cast<std::size_t>(k)] +=
197 static_cast<long double>(nc::projection[static_cast<std::size_t>(j) * nc::projectionTaps +
198 static_cast<std::size_t>(tap)]) *
199 static_cast<long double>(continuous_clip::choose(j, k)) * std::pow(a, j - k) *
200 std::pow(w, k);
201 for (int i = 0; i < moments; ++i)
202 {
203 long double bernstein = 0;
204 for (int j = 0; j <= i; ++j)
205 bernstein += shifted[static_cast<std::size_t>(j)] *
206 static_cast<long double>(continuous_clip::choose(i, j) /
207 continuous_clip::choose(moments - 1, j));
208 norm += std::abs(bernstein) * w / moments;
209 }
210 }
211 return static_cast<double>(norm * (1 + 1e-9L));
212 }
213};
214
215// Shared reconstructed clipping stage. Both branches use the same interpolation,
216// B-spline moments and compensation; at factor 1 the linear exterior uses
217// NativeClipKernel instead. The source/projection boundary policy is supplied
218// by BoundedClip; this stage alone does not perform sample-rate conversion.
219template <ClipperCurve C> class ReconstructedStage final
220{
221 static constexpr int degree = 11;
224 FIRFilter<double> eq_, linear_;
225 std::optional<NativeClipKernel<C>> native_;
226 int order_, pad_, filterSize_;
227
228 public:
230 [[nodiscard]] static constexpr int orderFor(int factor) noexcept
231 {
232 return factor <= 2 ? 18 : 10;
233 }
235 [[nodiscard]] static constexpr int padFor(int factor) noexcept
236 {
237 return factor == 1 ? NativeClipKernel<C>::delay - ((degree + 1) / 2 + 1 + orderFor(1)) : 0;
238 }
240 [[nodiscard]] static constexpr int filterSizeFor(int factor) noexcept
241 {
242 return 2 * (orderFor(factor) + padFor(factor)) + degree + 4;
243 }
244 static_assert(filterSizeFor(1) == NativeClipKernel<C>::history + 1);
246 : order_(orderFor(factor)), pad_(padFor(factor)), filterSize_(filterSizeFor(factor))
247 {
248 const int tapsSize = 2 * (order_ + pad_) + 1, linearSize = degree + 4;
249 // Padding the compensation reallocates it (at most twice its final
250 // size in total); the native kernel owns fixed-size histories.
251 const int padTemporaries = pad_ ? 2 * tapsSize : 0;
252 job.charge(static_cast<std::size_t>(6 * (order_ + 1) + (order_ + 2) * (2 * order_ + 1) +
253 linearSize + filterSize_ + padTemporaries) *
254 sizeof(double) +
255 static_cast<std::size_t>(order_ + 24) * 64 +
256 static_cast<std::size_t>(tapsSize + filterSize_) *
257 (sizeof(std::atomic<double>) + 4 * sizeof(double)) +
258 (pad_ ? NativeClipKernel<C>::storage() * sizeof(double) + 5 * 64 : 0) +
259 3 * sizeof(int));
260 auto taps = continuous_clip::inverseBoxPower(order_);
261 const auto linear = residual_.linearKernel();
262 if (pad_)
263 {
264 native_.emplace();
265 // The matched branches keep the cubic B-spline compensation,
266 // delayed to the native kernel's centre.
267 taps.insert(taps.begin(), static_cast<std::size_t>(pad_), 0.);
268 taps.insert(taps.end(), static_cast<std::size_t>(pad_), 0.);
269 }
270 std::vector<double> h(taps.size() + linear.size() - 1);
271 for (std::size_t i = 0; i < taps.size(); ++i)
272 for (std::size_t j = 0; j < linear.size(); ++j)
273 h[i + j] += taps[i] * linear[j];
274 eq_.prepare(tapsSize, 1);
275 eq_.setCoefficients(taps);
276 linear_.prepare(filterSize_, 1);
277 linear_.setCoefficients(h);
278 }
279 void reset(double ceiling) noexcept
280 {
281 residual_.reset(ceiling);
282 direct_.reset(ceiling);
283 eq_.reset();
284 linear_.reset();
285 if (native_)
286 native_->reset(ceiling);
287 }
288 [[nodiscard]] int filterSize() const noexcept
289 {
290 return filterSize_;
291 }
292 [[nodiscard]] int delay() const noexcept
293 {
294 return (degree + 1) / 2 + 1 + order_ + pad_;
295 }
296 void process(double *nonlinear, double *reference, int count, Exterior exterior)
297 {
298 if (native_ && exterior == Exterior::Linear)
299 {
300 native_->process(nonlinear, reference, count);
301 return;
302 }
303 for (int i = 0; i < count; ++i)
304 {
305 nonlinear[i] = exterior == Exterior::Matched ? direct_.process(nonlinear[i])
306 : residual_.process(nonlinear[i]);
307 if (!std::isfinite(nonlinear[i]))
309 }
310 double *a[]{nonlinear}, *b[]{reference};
311 eq_.processBlock({a, 1, count});
312 linear_.processBlock({b, 1, count});
313 }
314};
315
316// The only duration-sized storage is the existing
317// coarse Cauchy tree. Upconverted PCM and shaped PCM use three-leaf caches.
318template <ClipperCurve C, class Reader> class BoundedClip
319{
320 static constexpr double slope = clipperSmallSignalSlope<C, double>();
321 OfflineSession &job_;
322 Reader source_;
323 std::int64_t frames_, pad_, extent_;
324 int factor_, block_, highBlock_, delay_ = 0, left_ = 0, filterSize_ = 0;
325 double ceiling_;
326 Exterior exterior_;
328 struct PaddedReader
329 {
330 BoundedClip *owner;
331 bool difference;
332 void operator()(std::int64_t first, int count, double *out)
333 {
334 owner->readPadded(first, count, out, difference);
335 }
336 } raw_{this, false}, difference_{this, true};
337 std::optional<OfflineHilbertMap> rawMap_, differenceMap_;
338 std::array<std::optional<SincPhase>, 16> phases_;
339 OfflineScratchArray<double> native_, up_, shaped_, scratchA_, scratchB_, phaseWork_, output_;
340 std::array<std::int64_t, 3> nativeLeaf_{-1, -1, -1};
341 std::array<std::int64_t, 3> upLeaf_{-1, -1, -1}, shapedLeaf_{-1, -1, -1};
343 std::uint64_t evaluations_ = 0;
344 struct ProjectedReader
345 {
346 BoundedClip *owner;
347 void operator()(std::int64_t first, int count, double *out)
348 {
349 owner->projectedSource(first, count, out);
350 }
351 };
352 std::optional<SincProjection<ProjectedReader>> projection_;
353
354 static std::int64_t checkedExtent(std::int64_t frames, std::int64_t pad, int factor, int block)
355 {
356 if (frames < 1 || pad < 64 || factor < 1 || factor > 16 || (factor & (factor - 1)) ||
357 block < 128 || block > 16384 || block * factor > 65536 || (block & (block - 1)))
359 constexpr auto maximum = std::numeric_limits<std::int64_t>::max();
360 if (pad > (maximum / factor - frames) / 2 || frames > maximum / factor)
362 return frames + 2 * pad;
363 }
364 void readPadded(std::int64_t first, int count, double *out, bool difference)
365 {
366 while (count > 0)
367 {
368 const auto leaf = first / block_;
369 const int offset = static_cast<int>(first % block_),
370 length = std::min(count, block_ - offset);
371 const auto slot = static_cast<std::size_t>(leaf % 3);
372 auto *data = native_.get() + slot * 2 * block_;
373 if (nativeLeaf_[slot] != leaf)
374 {
375 std::fill_n(data, 2 * block_, 0.);
376 const auto origin = leaf * block_;
377 const auto begin = std::max(origin, pad_),
378 end = std::min(origin + block_, pad_ + frames_);
379 if (begin < end)
380 {
381 const int at = static_cast<int>(begin - origin),
382 n = static_cast<int>(end - begin);
383 for (int done = 0; done < n;)
384 {
385 const int chunk = std::min(n - done, 4096);
386 source_(begin - pad_ + done, chunk, data + at + done);
387 done += chunk;
388 }
389 for (int i = at; i < at + n; ++i)
390 {
391 if (!std::isfinite(data[i]))
393 const double shaped = clipperShape<C>(data[i], ceiling_);
394 data[block_ + i] =
395 exterior_ == Exterior::Matched ? -shaped : slope * data[i] - shaped;
396 }
397 }
398 nativeLeaf_[slot] = leaf;
399 }
400 std::copy_n(data + (difference ? block_ : 0) + offset, length, out);
401 first += length;
402 count -= length;
403 out += length;
404 }
405 }
406 double *upsampled(std::int64_t leaf)
407 {
408 const auto slot = static_cast<std::size_t>(leaf % 3);
409 auto *data = up_.get() + slot * 2 * highBlock_;
410 if (upLeaf_[slot] == leaf)
411 return data;
412 for (int p = 0; p < factor_; ++p)
413 {
414 phases_[p]->evaluate(*rawMap_, static_cast<std::size_t>(leaf), raw_, phaseWork_.get());
415 for (int i = 0; i < block_; ++i)
416 data[i * factor_ + p] = phaseWork_[i];
417 phases_[p]->evaluate(*differenceMap_, static_cast<std::size_t>(leaf), difference_,
418 phaseWork_.get());
419 for (int i = 0; i < block_; ++i)
420 data[highBlock_ + i * factor_ + p] = phaseWork_[i];
421 }
422 upLeaf_[slot] = leaf;
423 return data;
424 }
425 void highInput(std::int64_t first, int count, double *a, double *b)
426 {
427 const auto highExtent = extent_ * factor_;
428 while (count > 0)
429 {
430 if (first < 0)
431 {
432 const int n = static_cast<int>(std::min<std::int64_t>(-first, count));
433 std::fill_n(a, n, 0.);
434 std::fill_n(b, n, 0.);
435 first += n;
436 count -= n;
437 a += n;
438 b += n;
439 continue;
440 }
441 if (first >= highExtent)
442 {
443 std::fill_n(a, count, 0.);
444 std::fill_n(b, count, 0.);
445 break;
446 }
447 const auto leaf = first / highBlock_;
448 const int offset = static_cast<int>(first % highBlock_);
449 const int n = static_cast<int>(
450 std::min<std::int64_t>(std::min(highBlock_ - offset, count), highExtent - first));
451 const auto *data = upsampled(leaf);
452 std::copy_n(data + offset, n, a);
453 std::copy_n(data + highBlock_ + offset, n, b);
454 first += n;
455 count -= n;
456 a += n;
457 b += n;
458 }
459 }
460 const double *stage(std::int64_t leaf)
461 {
462 const auto slot = static_cast<std::size_t>(leaf % 3);
463 auto *data = shaped_.get() + slot * 2 * highBlock_;
464 if (shapedLeaf_[slot] == leaf)
465 return data;
466 const auto first = leaf * highBlock_;
467 const int length = highBlock_ + filterSize_ - 1;
468 highInput(first - left_, length, scratchA_.get(), scratchB_.get());
469 stage_.reset(ceiling_);
470 stage_.process(scratchA_.get(), scratchB_.get(), length, exterior_);
471 std::copy_n(scratchA_.get() + filterSize_ - 1, highBlock_, data);
472 std::copy_n(scratchB_.get() + filterSize_ - 1, highBlock_, data + highBlock_);
473 shapedLeaf_[slot] = leaf;
474 ++evaluations_;
475 return data;
476 }
477 void projectedSource(std::int64_t first, int count, double *out)
478 {
479 while (count > 0)
480 {
481 const auto leaf = first / highBlock_;
482 const int offset = static_cast<int>(first % highBlock_);
483 const int n = std::min(highBlock_ - offset, count);
484 const auto *data = stage(leaf);
485 for (int i = 0; i < n; ++i)
486 out[i] = data[offset + i] +
487 (exterior_ == Exterior::Matched ? data[highBlock_ + offset + i] : 0.);
488 first += n;
489 count -= n;
490 out += n;
491 }
492 }
493
494 public:
495 BoundedClip(OfflineSession &job, Reader reader, std::int64_t frames, std::int64_t pad,
496 int factor, double ceiling, Exterior exterior, int block = 512)
497 : job_(job), source_(std::move(reader)), frames_(frames), pad_(pad),
498 extent_(checkedExtent(frames, pad, factor, block)), factor_(factor), block_(block),
499 highBlock_(block * factor), ceiling_(ceiling), exterior_(exterior),
500 work_(job, extent_, block, OfflineProductWorkspace::NearFields::External),
501 stage_(job, factor)
502 {
503 if (!(ceiling > 0) || !std::isfinite(ceiling))
505 native_ = job.allocateScratch<double>(6 * static_cast<std::uint64_t>(block_));
506 rawMap_.emplace(work_, raw_);
507 differenceMap_.emplace(work_, difference_);
508 for (int p = 0; p < factor; ++p)
509 phases_[p].emplace(work_, double(p) / factor);
510 filterSize_ = stage_.filterSize();
511 delay_ = stage_.delay();
512 left_ = filterSize_ - 1 - delay_;
513 up_ = job.allocateScratch<double>(6 * static_cast<std::uint64_t>(highBlock_));
514 shaped_ = job.allocateScratch<double>(6 * static_cast<std::uint64_t>(highBlock_));
515 scratchA_ = job.allocateScratch<double>(static_cast<std::uint64_t>(highBlock_) + filterSize_ - 1);
516 scratchB_ = job.allocateScratch<double>(static_cast<std::uint64_t>(highBlock_) + filterSize_ - 1);
517 phaseWork_ = job.allocateScratch<double>(block_);
518 output_ = job.allocateScratch<double>(block_);
519 }
520 BoundedClip(const BoundedClip &) = delete;
522 [[nodiscard]] bool hasGeometry(std::int64_t pad, int block) const noexcept
523 {
524 return pad_ == pad && block_ == block;
525 }
526 void reset(double ceiling, Exterior exterior)
527 {
528 if (!(ceiling > 0) || !std::isfinite(ceiling))
530 if (ceiling == ceiling_ && exterior == exterior_)
531 return;
532 ceiling_ = ceiling;
533 exterior_ = exterior;
534 nativeLeaf_.fill(-1);
535 upLeaf_.fill(-1);
536 shapedLeaf_.fill(-1);
537 differenceMap_->rebuild(work_, difference_);
538 if (projection_)
539 projection_->rebuild();
540 }
541 [[nodiscard]] std::uint64_t evaluations() const
542 {
543 return evaluations_;
544 }
545 // At factor 1 the projection onto the source band is the identity (its
546 // modulation sin(pi * j) is zero), so get() reads the stage directly and
547 // no Cauchy map of the stage output is built.
549 {
550 if (!projection_ && factor_ > 1)
551 projection_.emplace(job_, extent_ * factor_, factor_, ProjectedReader{this},
552 highBlock_);
553 }
554 [[nodiscard]] std::int64_t firstLeaf() const
555 {
556 return pad_ / block_;
557 }
558 [[nodiscard]] std::int64_t endLeaf() const
559 {
560 return (pad_ + frames_ - 1) / block_ + 1;
561 }
562 [[nodiscard]] std::int64_t leafOrigin(std::int64_t leaf) const
563 {
564 return std::max(leaf * block_, pad_) - pad_;
565 }
566 [[nodiscard]] std::span<const double> get(std::int64_t leaf)
567 {
568 if (leaf < firstLeaf() || leaf >= endLeaf())
571 const auto first = leaf * block_;
572 const auto values = projection_ ? projection_->get(static_cast<std::size_t>(leaf))
573 : std::span<const double>{};
574 const auto available =
575 projection_ ? static_cast<std::int64_t>(values.size())
576 : std::min<std::int64_t>(block_, extent_ - first);
577 const auto begin = std::max(first, pad_), end = std::min(first + available, pad_ + frames_);
578 const auto *filtered = stage(leaf), *raw = upsampled(leaf);
579 const int offset = static_cast<int>(begin - first), length = static_cast<int>(end - begin);
580 for (int i = 0; i < length; ++i)
581 {
582 const int at = offset + i;
583 const double projected =
584 projection_ ? values[at]
585 : filtered[at] + (exterior_ == Exterior::Matched ? filtered[highBlock_ + at] : 0.);
586 output_[i] = clipperShape<C>(raw[at * factor_], ceiling_) + projected +
587 (exterior_ == Exterior::Linear ? filtered[highBlock_ + at * factor_] : 0.);
588 if (!std::isfinite(output_[i]))
590 }
591 return {output_.get(), static_cast<std::size_t>(length)};
592 }
593 template <class Consumer> void render(Consumer consume)
594 {
596 for (auto leaf = firstLeaf(); leaf < endLeaf(); ++leaf)
597 {
598 const auto data = get(leaf);
599 consume(leafOrigin(leaf), static_cast<int>(data.size()), data.data());
600 }
601 }
602};
603// Outward-rounded positive arithmetic and signed prefix intervals. Abel
604// summation bounds a finite alternating Cauchy sum by (|total|+max|prefix|)/d.
605// This often avoids the duration-dependent sum-of-magnitudes bound, while
606// retaining that bound as the better fallback for a Nyquist-alternating input.
607inline double upper(double value)
608{
609 return std::nextafter(value, std::numeric_limits<double>::infinity());
610}
612{
613 double low_ = 0, high_ = 0, mass_ = 0, prefix_ = 0;
614 std::int64_t next_ = 0;
615
616 public:
617 void append(double x)
618 {
619 if (!std::isfinite(x))
621 const double a = next_ % 2 ? -x : x;
622 low_ = std::nextafter(low_ + a, -std::numeric_limits<double>::infinity());
623 high_ = upper(high_ + a);
624 mass_ = upper(mass_ + std::abs(x));
625 prefix_ = std::max(prefix_, std::max(std::abs(low_), std::abs(high_)));
626 ++next_;
627 }
628 [[nodiscard]] double cauchyEnvelope() const
629 {
630 const double total = std::max(std::abs(low_), std::abs(high_));
631 const double bound = std::min(mass_, upper(total + prefix_));
632 return upper(bound / std::nextafter(std::numbers::pi, 0.));
633 }
634 [[nodiscard]] double mass() const
635 {
636 return mass_;
637 }
638};
640{
641 std::int64_t padding = 0;
643 double bound = 0;
644};
645
646template <ClipperCurve C> class TailPolicy
647{
648 double l_ = 0, e_ = 0, eLinear_ = 0, radius_ = 0, cubic_ = 0, shapeMaximum_ = 1,
649 shapeGain_ = 1;
650 static constexpr int degree = 11;
651
652 public:
653 explicit TailPolicy(int factor)
654 {
655 if (factor < 1 || factor > 16 || (factor & (factor - 1)))
657 const int order = ReconstructedStage<C>::orderFor(factor);
659 double reconstruction = interval.reconstructionBound();
660 const auto compensation = continuous_clip::inverseBoxPower(order);
661 for (double v : compensation)
662 e_ = upper(e_ + std::abs(v));
663 // At factor 1 the linear exterior integrates the residual of the
664 // native reconstruction through the moment kernel (NativeClipKernel);
665 // the matched one keeps the cubic B-spline compensation.
666 if (factor == 1)
667 {
668 reconstruction = std::max(reconstruction, NativeClipKernel<C>::reconstructionBound());
670 (1 + 256 * std::numeric_limits<double>::epsilon()));
671 }
672 else
673 eLinear_ = e_;
674 l_ = upper(reconstruction * (1 + 256 * std::numeric_limits<double>::epsilon()));
675 radius_ = double(ReconstructedStage<C>::filterSizeFor(factor) + 2) / factor + 2;
676 if constexpr (C == ClipperCurve::Tanh)
677 cubic_ = upper(1. / 3);
678 if constexpr (C == ClipperCurve::Sine)
679 {
680 for (int i = 1; i < 5; ++i)
681 cubic_ = upper(cubic_ + std::abs(fastSinPolynomial<double>[i]));
682 shapeGain_ = shapeMaximum_ = 0;
683 const auto lower = [](double x)
684 { return std::nextafter(x, -std::numeric_limits<double>::infinity()); };
685 for (int part = 0; part < 256; ++part)
686 {
687 const double low = std::max(0., lower(halfPi<double> * part / 256)),
688 high = upper(halfPi<double> * (part + 1) / 256);
689 const double squareLow = std::max(0., lower(low * low)),
690 squareHigh = upper(high * high);
691 double a = fastSinPolynomial<double>[4], b = a;
692 for (int i = 3; i >= 0; --i)
693 {
694 const std::array<double, 4> products{a * squareLow, a * squareHigh,
695 b * squareLow, b * squareHigh};
696 a = lower(lower(*std::min_element(products.begin(), products.end())) +
697 fastSinPolynomial<double>[i]);
698 b = upper(upper(*std::max_element(products.begin(), products.end())) +
699 fastSinPolynomial<double>[i]);
700 }
701 const double gain = std::max(std::abs(a), std::abs(b));
702 shapeGain_ = std::max(shapeGain_, gain);
703 shapeMaximum_ = std::max(shapeMaximum_, upper(gain * high));
704 }
705 }
706 }
707 // Analytic omitted-tail bounds. Roundoff/continuous-kernel errors are
708 // separately tested; they are not silently included in this tail budget.
709 TailPlan choose(double c, const TailCertificate &source, const TailCertificate &shape,
710 double tolerance = 1e-10, std::int64_t maximumPadding = 1ll << 26) const
711 {
712 if (!(c > 0) || !std::isfinite(c) || !(tolerance > 0) || !std::isfinite(tolerance))
714 const double a = upper(l_ * source.cauchyEnvelope()),
715 af = upper(l_ * shape.cauchyEnvelope());
716 for (std::int64_t pad = 64; pad <= maximumPadding; pad *= 2)
717 {
718 const double p = static_cast<double>(pad) - radius_;
719 if (p <= 0)
720 continue;
721 const double amplitude = upper(a / p);
722 double bound = std::numeric_limits<double>::infinity();
723 if constexpr (C == ClipperCurve::Hard || C == ClipperCurve::GoldenRatio)
724 {
725 const double threshold = C == ClipperCurve::Hard
726 ? c
727 : clipperLinearLimits<ClipperCurve::GoldenRatio>(c)[1];
728 if (amplitude < threshold)
729 bound = 0;
730 }
731 else if constexpr (C == ClipperCurve::Tanh || C == ClipperCurve::Sine)
732 {
733 if (amplitude <= c)
734 {
735 const double ratio = upper(amplitude / c);
736 // Integral of d^-4; factor4 includes both ends and the
737 // altered boundary strip of the finite evaluation domain.
738 bound = upper(
739 upper(upper(4 * eLinear_ * cubic_ / (3 * std::numbers::pi)) * amplitude) *
740 upper(ratio * ratio));
741 }
742 }
743 if (bound <= tolerance)
744 return {pad, Exterior::Linear, bound};
745 const double shapeA = upper(a * shapeGain_), limit = upper(c * shapeMaximum_);
746 double shaped = upper(shapeA / p);
747 if (shaped > limit)
748 {
749 const double logarithm = std::log(shapeA) - std::log(limit) - std::log(p);
750 shaped = upper(limit * (1 + logarithm + 1e-12 * (1 + std::abs(logarithm))));
751 }
752 const double matched =
753 upper(upper(4 * e_ / std::numbers::pi) * upper(shaped + upper(af / p)));
754 if (matched <= tolerance)
755 return {pad, Exterior::Matched, matched};
756 if (pad > maximumPadding / 2)
757 break;
758 }
760 }
761};
762} // namespace dspark::detail::offline_clip
763#endif // DSPARK_HAS_OFFLINE
FIR filter using direct-form convolution with a mirrored delay line.
Definition FIRFilter.h:364
void reset() noexcept
Resets all delay lines to zero, clearing the filter's memory.
Definition FIRFilter.h:452
void processBlock(AudioBufferView< T > buffer) noexcept
Processes a full audio buffer in-place.
Definition FIRFilter.h:473
void prepare(int maxTaps, int numChannels)
Pre-allocates memory and initializes the delay lines.
Definition FIRFilter.h:376
void setCoefficients(std::span< const T > coeffs) noexcept
Sets the filter coefficients asynchronously.
Definition FIRFilter.h:418
void charge(std::size_t bytes)
OfflineScratchArray< U > allocateScratch(std::uint64_t count)
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.
BoundedClip(const BoundedClip &)=delete
BoundedClip(OfflineSession &job, Reader reader, std::int64_t frames, std::int64_t pad, int factor, double ceiling, Exterior exterior, int block=512)
std::int64_t leafOrigin(std::int64_t leaf) const
bool hasGeometry(std::int64_t pad, int block) const noexcept
std::span< const double > get(std::int64_t leaf)
void reset(double ceiling, Exterior exterior)
BoundedClip & operator=(const BoundedClip &)=delete
void process(double *nonlinear, double *reference, int count)
static constexpr std::size_t storage() noexcept
Heap payload of one kernel, in doubles.
static double reconstructionBound()
Bound on |p(t)| / max|x| over the reconstruction window (Bernstein hull).
static double kernelNorm()
Upper bound on the integral of |h| of the synthesized kernel.
static constexpr int padFor(int factor) noexcept
Zero padding that aligns the factor-1 matched branches with NativeClipKernel.
static constexpr int orderFor(int factor) noexcept
Compensation order at an oversampling factor.
void process(double *nonlinear, double *reference, int count, Exterior exterior)
static constexpr int filterSizeFor(int factor) noexcept
Input history plus one, in samples at the factor's rate.
TailPlan choose(double c, const TailCertificate &source, const TailCertificate &shape, double tolerance=1e-10, std::int64_t maximumPadding=1ll<< 26) const
std::vector< double > inverseBoxPower(int order)
constexpr int delay
Delay of the projected output behind the newest input, in samples.
void offlineFail(OfflineStatus status)
std::unique_ptr< T[], OfflineScratchDeleter< T > > OfflineScratchArray
void firCorrelate(const T *x, const T *h, int taps, T *DSPARK_RESTRICT y, int n, T gain) noexcept
Block FIR as a valid correlation: y[i] = gain * sum_j h[j] * x[i + j] for i in [0,...
Definition SimdOps.h:1496