DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
DetailFilter.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
83#include "AudioBuffer.h"
84#include "AudioSpec.h"
85#include "DenormalGuard.h"
86#include "DspMath.h"
87#include "FFT.h"
88#include "FIRFilter.h"
89#include "SimdOps.h"
90#include "SpectralFilter.h"
91#include "SpinLock.h"
92
93#include <algorithm>
94#include <array>
95#include <atomic>
96#include <cmath>
97#include <cstddef>
98#include <cstdint>
99#include <memory>
100#include <mutex>
101#include <numbers>
102#include <thread>
103#include <type_traits>
104#include <vector>
105
106namespace dspark {
107
112{
113 Frame,
114 Block
115};
116
121enum class DetailHold
122{
123 Largest,
124 Reach,
125 None
126};
127
128namespace detail {
129
156template <FloatType T, DetailLatency L>
158{
159public:
161 using S = std::conditional_t<L == DetailLatency::Block, double, T>;
162
172 void prepare(double sampleRate, int channels, int window, int padding, int block, int steps)
173 {
174 prepared_ = false;
175 fs_ = sampleRate;
176 channels_ = std::max(channels, 0);
177 size_ = window * padding;
178 hop_ = window / 2;
179 block_ = std::clamp(block, std::max(1, window / 4), std::max(1, window));
180 steps_ = std::max(steps, 1);
181 bins_ = size_ / 2 + 1;
182 length_ = size_ - window + 1;
183 partitions_ = (length_ + block_ - 1) / block_;
184 stride_ = 2 * (block_ + 1);
185
186 design_ = std::make_unique<FFTReal<double>>(static_cast<std::size_t>(size_));
187 transform_ = std::make_unique<FFTReal<S>>(static_cast<std::size_t>(2 * block_));
188 minimumPhase_.prepare(bins_);
189 logGain_.assign(static_cast<std::size_t>(bins_), T(0));
190 spectrum_.assign(static_cast<std::size_t>(size_ + 2), 0.0);
191 kernel_.assign(static_cast<std::size_t>(size_ + 2), 0.0);
192 taper_.assign(static_cast<std::size_t>(length_), 1.0);
193 const int tail = std::max(1, length_ / 4);
194 for (int i = 0; i < tail; ++i)
195 taper_[static_cast<std::size_t>(length_ - tail + i)] = 0.5 + 0.5 * std::cos(std::numbers::pi * (i + 1) / (tail + 1));
196 // The short kernel: a window at most, tapered over its whole length.
197 shortLength_ = std::min(length_, window);
198 shortTaper_.resize(static_cast<std::size_t>(shortLength_));
199 for (int i = 0; i < shortLength_; ++i)
200 shortTaper_[static_cast<std::size_t>(i)] = 0.5 + 0.5 * std::cos(std::numbers::pi * i / shortLength_);
201 const int fade = steps_ * block_;
202 for (auto* v : { &older_, &newer_ }) v->resize(static_cast<std::size_t>(fade));
203 for (int i = 0; i < fade; ++i)
204 {
205 const double u = static_cast<double>(i + 1) / fade, turn = 0.5 * std::numbers::pi * u;
206 older_[static_cast<std::size_t>(i)] = static_cast<S>(kByFour ? -0.25 * std::cos(turn) : 0.5 * (1.0 - u) * (1.0 - u));
207 newer_[static_cast<std::size_t>(i)] = static_cast<S>(kByFour ? 0.25 * std::sin(turn) : 0.5 * u * u);
208 }
209
210 time_.assign(static_cast<std::size_t>(2 * block_ + 2), S(0));
211 sum_.assign(static_cast<std::size_t>(stride_), S(0));
212 for (auto* v : { &oldest_, &newest_ }) v->assign(static_cast<std::size_t>(block_), S(0));
213 const auto spectra = static_cast<std::size_t>(partitions_) * static_cast<std::size_t>(stride_);
214 channel_.resize(static_cast<std::size_t>(channels_));
215 slot_.resize(static_cast<std::size_t>(channels_));
216 for (auto& c : channel_)
217 {
218 for (auto* v : { &c.in, &c.before, &c.out }) v->assign(static_cast<std::size_t>(block_), S(0));
219 c.past.assign(spectra, S(0));
220 }
221 for (auto& s : slot_)
222 {
223 for (auto& k : s.partition) k.assign(spectra, S(0));
224 if constexpr (kByFour)
225 for (auto* v : { &s.mean, &s.even, &s.odd }) v->assign(spectra, S(0));
226 s.kept.assign(static_cast<std::size_t>(length_), 0.0);
227 }
228 prepared_ = true;
229 reset();
230 }
231
233 void reset() noexcept
234 {
235 if (!prepared_) return;
236 for (auto& c : channel_)
237 for (auto* v : { &c.in, &c.before, &c.out, &c.past }) std::fill(v->begin(), v->end(), S(0));
238 for (auto& s : slot_)
239 {
240 s.flat.fill(true);
241 s.newest = 0;
242 }
243 at_ = head_ = count_ = 0;
244 fading_ = steps_;
245 }
246
248 void setLinked(bool on) noexcept { linked_ = on; }
250 void setShortKernel(bool on) noexcept { short_ = on; }
251
253 [[nodiscard]] int getLatency() const noexcept { return block_; }
255 [[nodiscard]] int getHopSize() const noexcept { return hop_; }
257 [[nodiscard]] int getNumBins() const noexcept { return bins_; }
259 [[nodiscard]] int getTransformSize() const noexcept { return size_; }
261 [[nodiscard]] int getKernelLength() const noexcept { return length_; }
263 [[nodiscard]] double getBinHz() const noexcept { return fs_ / static_cast<double>(size_); }
265 [[nodiscard]] const double* getKeptKernel(int channel) const noexcept
266 {
267 if (channel < 0 || channel >= static_cast<int>(slot_.size())) return nullptr;
268 const Slot& s = slot_[static_cast<std::size_t>(channel)];
269 return s.flat[static_cast<std::size_t>(s.newest)] ? nullptr : s.kept.data();
270 }
271
280 template <typename Design>
281 void processBlock(AudioBufferView<T> buffer, Design&& design) noexcept
282 {
283 if (!prepared_) return;
284 DenormalGuard guard;
285 const int channels = std::min(buffer.getNumChannels(), channels_);
286 for (int done = 0; done < buffer.getNumSamples();)
287 {
288 const int count = std::min(buffer.getNumSamples() - done, block_ - at_);
289 for (int ch = 0; ch < channels; ++ch)
290 {
291 Channel& c = channel_[static_cast<std::size_t>(ch)];
292 T* x = buffer.getChannel(ch) + done;
293 std::copy_n(x, count, c.in.data() + at_);
294 const S* from = c.out.data() + at_;
295 for (int i = 0; i < count; ++i) x[i] = static_cast<T>(from[i]);
296 }
297 done += count;
298 at_ += count;
299 if (at_ < block_) continue;
300 at_ = 0;
301 step(channels, design);
302 }
303 }
304
305private:
306 static constexpr bool kByFour = L == DetailLatency::Frame;
307 static constexpr int kKernels = kByFour ? 4 : 3;
308
309 struct Channel
310 {
311 std::vector<S> in, before, out;
312 std::vector<S> past;
313 };
314
315 struct Slot
316 {
317 std::array<std::vector<S>, kKernels> partition;
318 std::vector<double> kept;
319 std::array<bool, kKernels> flat {};
320 std::vector<S> mean, even, odd;
321 int newest = 0;
322 };
323
324 template <typename Design>
325 void step(int channels, Design& design) noexcept
326 {
327 if (++count_ == steps_)
328 {
329 count_ = 0;
330 fading_ = 0;
331 const bool one = linked_ && channels > 1;
332 for (int s = 0; s < (one ? 1 : channels); ++s)
333 {
334 std::fill(logGain_.begin(), logGain_.end(), T(0));
335 design(one ? -1 : s, static_cast<const T*>(nullptr), logGain_.data(), bins_);
336 build(slot_[static_cast<std::size_t>(s)]);
337 }
338 }
339 head_ = head_ + 1 == partitions_ ? 0 : head_ + 1;
340 for (int ch = 0; ch < channels; ++ch)
341 convolve(channel_[static_cast<std::size_t>(ch)], slot_[static_cast<std::size_t>(linked_ ? 0 : ch)]);
342 if (fading_ < steps_) ++fading_;
343 }
344
345 void build(Slot& s) noexcept
346 {
347 s.newest = (s.newest + 1) % kKernels;
348 const auto newest = static_cast<std::size_t>(s.newest);
349 bool flat = true;
350 for (int k = 0; k < bins_ && flat; ++k) flat = logGain_[static_cast<std::size_t>(k)] == T(0);
351 s.flat[newest] = flat;
352 if (flat)
353 {
354 if constexpr (kByFour)
355 {
356 // The sums read a flat kernel as a spectrum: ones in the first partition.
357 std::fill(s.partition[newest].begin(), s.partition[newest].end(), S(0));
358 for (int k = 0; k <= block_; ++k) s.partition[newest][static_cast<std::size_t>(2 * k)] = S(1);
359 combine(s);
360 }
361 return;
362 }
363 double* h = spectrum_.data();
364 double* c = kernel_.data();
365 for (int k = 0; k < bins_; ++k)
366 {
367 h[2 * k] = std::max(static_cast<double>(logGain_[static_cast<std::size_t>(k)]), MinimumPhase::kLeastLogGain);
368 h[2 * k + 1] = 0.0;
369 }
370 minimumPhase_.build(*design_, h, c, size_, short_ ? shortTaper_.data() : taper_.data(), short_ ? shortLength_ : length_);
371 std::copy_n(c, length_, s.kept.data());
372 S* to = s.partition[newest].data();
373 for (int p = 0; p < partitions_; ++p)
374 {
375 std::fill(time_.begin(), time_.end(), S(0));
376 const int from = p * block_, count = std::min(block_, length_ - from);
377 for (int i = 0; i < count; ++i) time_[static_cast<std::size_t>(i)] = static_cast<S>(c[from + i]);
378 transform_->forward(time_.data(), to + p * stride_);
379 }
380 if constexpr (kByFour) combine(s);
381 }
382
384 void combine(Slot& s) noexcept
385 {
386 if (allFlat(s)) return;
387 const auto at = [&s](int age) { return s.partition[static_cast<std::size_t>((s.newest + kKernels - age) % kKernels)].data(); };
388 const S* h0 = at(0);
389 const S* h1 = at(1);
390 const S* h2 = at(2);
391 const S* h3 = at(3);
392 S* mean = s.mean.data();
393 S* even = s.even.data();
394 S* odd = s.odd.data();
395 const int count = partitions_ * stride_;
396 for (int i = 0; i < count; ++i) mean[i] = S(0.25) * ((h0[i] + h2[i]) + (h1[i] + h3[i]));
397 for (int i = 0; i < count; ++i) even[i] = h0[i] - h2[i];
398 for (int i = 0; i < count; ++i) odd[i] = h1[i] - h3[i];
399 }
400
401 [[nodiscard]] static bool allFlat(const Slot& s) noexcept
402 {
403 for (const bool flat : s.flat)
404 if (!flat) return false;
405 return true;
406 }
407
409 void play(const Channel& c, const Slot& s, int which, S* to) noexcept
410 {
411 const auto w = static_cast<std::size_t>(which);
412 if (s.flat[w])
413 {
414 std::copy_n(c.in.data(), block_, to);
415 return;
416 }
417 playSpectra(c, s.partition[w].data(), to);
418 }
419
421 void playSpectra(const Channel& c, const S* kernel, S* to) noexcept
422 {
423 std::fill(sum_.begin(), sum_.end(), S(0));
424 // The ring of spectra in its two runs, newest first.
425 for (int p = 0; p <= head_; ++p)
426 simd::complexMulAccum(sum_.data(), c.past.data() + (head_ - p) * stride_, kernel + p * stride_, block_ + 1);
427 for (int p = head_ + 1; p < partitions_; ++p)
428 simd::complexMulAccum(sum_.data(), c.past.data() + (head_ - p + partitions_) * stride_, kernel + p * stride_, block_ + 1);
429 transform_->inverse(sum_.data(), time_.data());
430 std::copy_n(time_.data() + block_, block_, to);
431 }
432
433 void convolve(Channel& c, const Slot& s) noexcept
434 {
435 std::copy_n(c.before.data(), block_, time_.data());
436 std::copy_n(c.in.data(), block_, time_.data() + block_);
437 transform_->forward(time_.data(), c.past.data() + head_ * stride_);
438 if constexpr (kByFour) playFour(c, s);
439 else playThree(c, s);
440 std::copy_n(c.in.data(), block_, c.before.data());
441 }
442
443 void playFour(Channel& c, const Slot& s) noexcept
444 {
445 S* out = c.out.data();
446 if (fading_ >= steps_ || allFlat(s))
447 {
448 std::copy_n(c.in.data(), block_, out); // nothing designed yet, or nothing but flat
449 return;
450 }
451 playSpectra(c, s.mean.data(), out);
452 playSpectra(c, s.even.data(), oldest_.data());
453 playSpectra(c, s.odd.data(), newest_.data());
454 const S* evenShare = older_.data() + fading_ * block_;
455 const S* oddShare = newer_.data() + fading_ * block_;
456 const S* even = oldest_.data();
457 const S* odd = newest_.data();
458 for (int i = 0; i < block_; ++i) out[i] += evenShare[i] * even[i] + oddShare[i] * odd[i];
459 }
460
461 void playThree(Channel& c, const Slot& s) noexcept
462 {
463 // The middle one, and what the two others differ from it by: flat or
464 // equal kernels play exactly as one.
465 play(c, s, (s.newest + kKernels - 1) % kKernels, c.out.data());
466 if (fading_ < steps_ && !allFlat(s))
467 {
468 play(c, s, (s.newest + 1) % kKernels, oldest_.data());
469 play(c, s, s.newest, newest_.data());
470 const S* older = older_.data() + fading_ * block_;
471 const S* newer = newer_.data() + fading_ * block_;
472 const S* first = oldest_.data();
473 const S* last = newest_.data();
474 S* out = c.out.data();
475 for (int i = 0; i < block_; ++i)
476 {
477 const S middle = out[i];
478 out[i] = middle + older[i] * (first[i] - middle) + newer[i] * (last[i] - middle);
479 }
480 }
481 }
482
483 double fs_ = 48000.0;
484 int channels_ = 0, size_ = 0, hop_ = 0, block_ = 1, steps_ = 2, bins_ = 0, length_ = 0, partitions_ = 1, stride_ = 4;
485 int shortLength_ = 0;
486 bool short_ = false;
487 int at_ = 0, head_ = 0, count_ = 0, fading_ = 2;
488 bool prepared_ = false, linked_ = false;
489 std::unique_ptr<FFTReal<double>> design_;
490 std::unique_ptr<FFTReal<S>> transform_;
491 MinimumPhase minimumPhase_;
492 std::vector<T> logGain_;
493 std::vector<S> time_, sum_, oldest_, newest_, older_, newer_;
494 std::vector<double> spectrum_, kernel_, taper_, shortTaper_;
495 std::vector<Channel> channel_;
496 std::vector<Slot> slot_;
497};
498
499} // namespace detail
500
509template <FloatType T, DetailLatency L = DetailLatency::Frame>
511{
512 static constexpr bool kByBlock = L == DetailLatency::Block;
514
515public:
516 static constexpr int kPoints = SpectralReadout<T>::kPoints;
517 static constexpr int kMaxChannels = 16;
518
520 [[nodiscard]] static double frequency(int point) noexcept { return SpectralReadout<T>::frequency(point); }
521
527 void prepare(const AudioSpec& spec)
528 {
529 if (!spec.isValid()) return;
530 prepared_ = false;
531 fs_ = spec.sampleRate;
532 channels_ = std::min(spec.numChannels, kMaxChannels);
533 const int octaves = std::clamp(static_cast<int>(std::lround(std::log2(std::max(fs_, 44100.0) / 44100.0))), 0, 3);
534 const int scale = 1 << octaves;
535
536 // Everything grows with the rate; the factor stops at 16, and the
537 // slow windows grow from there. By the block it shrinks with the rate
538 // as well, to two octaves down, at the same hertz a bin.
539 const int down = kByBlock ? std::clamp(-static_cast<int>(std::lround(std::log2(fs_ / 48000.0))), 0, 2) : 0;
540 const int factor = kFactor >> down;
541 factor_ = std::min(16, factor * scale);
542 const int slowScale = scale * factor / factor_;
543 quantum_ = kSlowQuantum * factor_;
544 const double slowRate = fs_ / static_cast<double>(factor_);
545
546 rate_.prepare(channels_, factor_);
547 const int slowWindow = kSlowWindow * slowScale, window = (kWindow >> down) * scale;
548 low_.prepare(slowRate, channels_, slowWindow, kSlowPadding, slowWindow / (kByBlock ? 4 : 1), kSlowSteps);
549 high_.prepare(fs_, channels_, window, kPadding, window / 4, kSteps);
550
551 const int lowSpan = low_.getLatency() * factor_;
552 correctionDelay_ = 2 * rate_.half_ + lowSpan;
553 const int needed = quantum_ + correctionDelay_ + high_.getLatency();
554 // By the block, what is over the engine's own delay is lead for the high part.
555 latency_ = kByBlock ? std::max(needed, (kBlockLatency * scale) >> down) : std::max(kLatency * scale, needed);
556
557 align_.prepare(channels_, latency_ - needed);
558 programme_.prepare(channels_, correctionDelay_);
559 slowDry_.prepare(channels_, low_.getLatency());
560 removed_.prepare(channels_, latency_ - quantum_); // the output waits a quantum more in out_
561 slow_.resize(channels_, kSlowQuantum);
562 before_.resize(channels_, kSlowQuantum);
563 original_.resize(channels_, quantum_);
564 change_.resize(channels_, quantum_);
565 in_.resize(channels_, quantum_);
566 out_.resize(channels_, quantum_);
567
568 // By the frame a curve is drawn once a kernel: between them nothing reads it.
569 hopQuanta_ = std::max(1, low_.getHopSize() * factor_ / quantum_ * (kByBlock ? 1 : 2));
570
571 // The high part takes the curve as it is drawn: held back to the low
572 // part's, every move of the broad curve would come later than the
573 // latency allows it.
574 curvesKept_ = 1;
575 const auto kept = static_cast<std::size_t>(curvesKept_) * static_cast<std::size_t>(kPoints);
576 curve_.assign(static_cast<std::size_t>(channels_), std::vector<T>(static_cast<std::size_t>(kPoints), T(0)));
577 past_.assign(static_cast<std::size_t>(channels_), std::vector<T>(kept, T(0)));
578 recent_.assign(kByBlock ? 0u : static_cast<std::size_t>(channels_), std::vector<T>(static_cast<std::size_t>(kHoldCurves * kPoints), T(0)));
579 held_.assign(kByBlock ? 0u : static_cast<std::size_t>(channels_), std::vector<T>(static_cast<std::size_t>(kPoints), T(0)));
580 heldAge_.assign(kByBlock ? 0u : static_cast<std::size_t>(channels_), std::vector<std::uint8_t>(static_cast<std::size_t>(kPoints), kHoldCurves));
581
582 // The crossover: well inside what the decimator keeps at any rate.
583 const double upper = std::min(1800.0, 0.3 * slowRate);
584 lowMap_.prepare(low_.getBinHz(), low_.getNumBins(), upper, true);
585 highMap_.prepare(high_.getBinHz(), high_.getNumBins(), upper, false);
586 split_.prepare(upper / (Split::kStep * high_.getBinHz()), low_.getNumBins(), (high_.getNumBins() - 1) / Split::kStep + 1);
587 fine_.assign(static_cast<std::size_t>(channels_), std::vector<T>(static_cast<std::size_t>(split_.fineBins_), T(0)));
588 pastBroad_.assign(static_cast<std::size_t>(channels_),
589 std::vector<T>(static_cast<std::size_t>(curvesKept_ * split_.broadBins_), T(0)));
590 for (std::size_t ch = 0; ch < 2; ++ch)
591 {
592 playedLow_[ch] = std::vector<std::atomic<float>>(static_cast<std::size_t>(low_.getKernelLength()));
593 playedHigh_[ch] = std::vector<std::atomic<float>>(static_cast<std::size_t>(high_.getKernelLength()));
594 readLow_[ch].assign(static_cast<std::size_t>(low_.getKernelLength()), 0.0);
595 readHigh_[ch].assign(static_cast<std::size_t>(high_.getKernelLength()), 0.0);
596 }
597 readCurve_.assign(static_cast<std::size_t>(kPoints), T(0));
598 lowResponse_.prepare(low_.getTransformSize(), low_.getKernelLength(), low_.getBinHz(),
599 static_cast<double>(split_.fineBins_ - 1) * low_.getBinHz());
600 highResponse_.prepare(high_.getTransformSize(), high_.getKernelLength(), high_.getBinHz(), 0.5 * fs_);
601 prepared_ = true;
602 reset();
603 }
604
606 void reset() noexcept
607 {
608 if (!prepared_) return;
609 rate_.reset();
610 low_.reset();
611 high_.reset();
612 align_.reset();
613 programme_.reset();
614 slowDry_.reset();
615 removed_.reset();
616 in_.clear();
617 out_.clear();
618 for (auto& c : curve_) std::fill(c.begin(), c.end(), T(0));
619 for (auto& p : past_) std::fill(p.begin(), p.end(), T(0));
620 for (auto& p : recent_) std::fill(p.begin(), p.end(), T(0));
621 recentAt_ = 0;
622 for (auto& p : held_) std::fill(p.begin(), p.end(), T(0));
623 for (auto& a : heldAge_) std::fill(a.begin(), a.end(), static_cast<std::uint8_t>(kHoldCurves));
624 for (auto& f : fine_) std::fill(f.begin(), f.end(), T(0));
625 for (auto& b : pastBroad_) std::fill(b.begin(), b.end(), T(0));
626 filled_ = 0;
627 quanta_ = 0;
628 newest_ = 0;
629 curveCount_ = 0;
631 }
632
634 void setLinked(bool on) noexcept
635 {
636 linked_ = on;
637 low_.setLinked(on);
638 high_.setLinked(on);
639 }
641 [[nodiscard]] bool isLinked() const noexcept { return linked_; }
642
651 void setShortKernel(bool on) noexcept
652 {
653 shortKernel_ = on;
654 high_.setShortKernel(on);
655 }
657 [[nodiscard]] bool isShortKernel() const noexcept { return shortKernel_; }
658
664 void setHold(DetailHold hold) noexcept { hold_ = hold; }
666 [[nodiscard]] DetailHold getHold() const noexcept { return hold_; }
667
669 void setRemovalListen(bool on) noexcept { removalListen_ = on; }
671 [[nodiscard]] bool isRemovalListen() const noexcept { return removalListen_; }
672
674 [[nodiscard]] int getLatency() const noexcept { return latency_; }
676 [[nodiscard]] int getHopSize() const noexcept { return hopQuanta_ * quantum_; }
677
679 [[nodiscard]] int getCurveCount() const noexcept { return curveCount_; }
686 [[nodiscard]] bool isDisplayDue(int shownAt) const noexcept { return ((curveCount_ - shownAt) & 0x3FFFFFFF) >= (kByBlock ? kDisplayCurves : kDisplayCurves / 2); }
687
693 void publishPlayed(int channels = 2) noexcept
694 {
695 if (!prepared_) return;
696 const unsigned version = playedVersion_.load(std::memory_order_relaxed);
697 playedVersion_.store(version + 1u, std::memory_order_relaxed);
698 std::atomic_thread_fence(std::memory_order_release);
699 const bool one = linked_ || std::min(channels, channels_) < 2;
700 playedOne_.store(one, std::memory_order_relaxed);
701 handOverChannel<0>();
702 if (!one) handOverChannel<1>();
703 playedVersion_.store(version + 2u, std::memory_order_release);
704 }
705
711 [[nodiscard]] T playedValue(int channel, int point) const noexcept
712 {
713 refreshPlayed();
714 return played_.value(channel, point);
715 }
716
718 [[nodiscard]] T playedExtreme() const noexcept
719 {
720 refreshPlayed();
721 return played_.extreme();
722 }
723
730 void getPlayedCurve(int channel, T* played) noexcept
731 {
732 std::fill_n(played, kPoints, T(0));
733 if (!prepared_ || channel < 0 || channel >= 2) return;
735 for (int i = 0; i < kPoints; ++i) played[i] = playedValue(channel, i);
736 }
737
745 template <typename Design>
746 void processBlock(AudioBufferView<T> buffer, Design&& design) noexcept
747 {
748 processBlock(buffer, [](int, int) noexcept {}, design);
749 }
750
765 template <typename Feed, typename Design>
766 void processBlock(AudioBufferView<T> buffer, Feed&& feed, Design&& design) noexcept
767 {
768 if (!prepared_) return;
769 DenormalGuard guard;
770 const int channels = std::min(buffer.getNumChannels(), channels_);
771 const int samples = buffer.getNumSamples();
772 if (channels <= 0) return;
773 int done = 0;
774 while (done < samples)
775 {
776 const int count = std::min(samples - done, quantum_ - filled_);
777 feed(done, count);
778 for (int ch = 0; ch < channels; ++ch)
779 {
780 T* x = buffer.getChannel(ch) + done;
781 std::copy_n(x, count, in_.getChannel(ch) + filled_);
782 std::copy_n(out_.getChannel(ch) + filled_, count, x);
783 }
784 filled_ += count;
785 done += count;
786 if (filled_ == quantum_)
787 {
788 filled_ = 0;
789 runQuantum(channels, design);
790 }
791 }
792 }
793
794private:
796 struct Line
797 {
798 void prepare(int channels, int length)
799 {
800 length_ = std::max(0, length);
801 data_.assign(static_cast<std::size_t>(channels), std::vector<T>(static_cast<std::size_t>(length_), T(0)));
802 at_.assign(static_cast<std::size_t>(channels), 0);
803 }
804
805 void reset() noexcept
806 {
807 for (auto& d : data_) std::fill(d.begin(), d.end(), T(0));
808 std::fill(at_.begin(), at_.end(), 0);
809 }
810
811 void process(int channel, T* x, int count) noexcept
812 {
813 if (length_ == 0) return;
814 const auto c = static_cast<std::size_t>(channel);
815 T* d = data_[c].data();
816 int at = at_[c];
817 // By spans of the ring: each sample out is the one in `length_` ago.
818 while (count > 0)
819 {
820 const int run = std::min(count, length_ - at);
821 std::swap_ranges(x, x + run, d + at);
822 x += run;
823 count -= run;
824 at += run;
825 if (at == length_) at = 0;
826 }
827 at_[c] = at;
828 }
829
830 std::vector<std::vector<T>> data_;
831 std::vector<int> at_;
832 int length_ = 0;
833 };
834
837 struct RateChange
838 {
839 void prepare(int channels, int factor)
840 {
841 constexpr double depth = 100.0, passEdge = 0.35; // of the slow rate
842 factor_ = factor;
843 const double transition = (0.5 - passEdge) / factor;
844 half_ = static_cast<int>(std::ceil(0.5 * (depth - 7.95) / (14.36 * transition)));
845 length_ = 2 * half_ + 1;
846 perPhase_ = (length_ + factor_ - 1) / factor_;
847 const auto h = FIRDesign<double>::lowPass(1.0, 0.5 * (0.5 + passEdge) / factor, length_,
849 taps_.resize(static_cast<std::size_t>(length_));
850 for (int i = 0; i < length_; ++i)
851 taps_[static_cast<std::size_t>(i)] = static_cast<T>(h[static_cast<std::size_t>(i)]);
852 // Each phase of the interpolator, oldest sample first.
853 phases_.assign(static_cast<std::size_t>(perPhase_ * factor_), T(0));
854 for (int r = 0; r < factor_; ++r)
855 for (int i = 0; i < perPhase_; ++i)
856 {
857 const int n = (perPhase_ - 1 - i) * factor_ + r;
858 if (n < length_)
859 phases_[static_cast<std::size_t>(r * perPhase_ + i)] = static_cast<T>(factor_ * h[static_cast<std::size_t>(n)]);
860 }
861 const auto count = static_cast<std::size_t>(channels);
862 down_.assign(count, std::vector<T>(static_cast<std::size_t>(length_ - 1 + factor_ * kSlowQuantum), T(0)));
863 up_.assign(count, std::vector<T>(static_cast<std::size_t>(perPhase_ - 1 + kSlowQuantum), T(0)));
864 }
865
866 void reset() noexcept
867 {
868 for (auto& d : down_) std::fill(d.begin(), d.end(), T(0));
869 for (auto& u : up_) std::fill(u.begin(), u.end(), T(0));
870 }
871
872 void decimate(int channel, const T* fast, T* slow) noexcept
873 {
874 T* past = down_[static_cast<std::size_t>(channel)].data();
875 const int count = factor_ * kSlowQuantum;
876 std::copy_n(fast, count, past + length_ - 1);
877 // The kernel is symmetric, so it correlates as it is.
878 for (int j = 0; j < kSlowQuantum; ++j)
879 slow[j] = simd::dotProductT(past + j * factor_, taps_.data(), length_);
880 std::copy(past + count, past + count + length_ - 1, past);
881 }
882
883 void interpolate(int channel, const T* slow, T* fast) noexcept
884 {
885 T* past = up_[static_cast<std::size_t>(channel)].data();
886 std::copy_n(slow, kSlowQuantum, past + perPhase_ - 1);
887 for (int j = 0; j < kSlowQuantum; ++j)
888 for (int r = 0; r < factor_; ++r)
889 fast[j * factor_ + r] = simd::dotProductT(past + j, phases_.data() + r * perPhase_, perPhase_);
890 std::copy(past + kSlowQuantum, past + kSlowQuantum + perPhase_ - 1, past);
891 }
892
893 std::vector<T> taps_, phases_;
894 std::vector<std::vector<T>> down_, up_;
895 int factor_ = kFactor, half_ = 0, length_ = 1, perPhase_ = 1;
896 };
897
902 struct Response
903 {
904 void prepare(int transform, int length, double binHz, double limitHz)
905 {
906 length_ = length;
907 size_ = 2 * transform;
908 fft_ = std::make_unique<FFTReal<T>>(static_cast<std::size_t>(size_));
909 time_.assign(static_cast<std::size_t>(size_), T(0));
910 spectrum_.assign(static_cast<std::size_t>(size_ + 2), T(0));
911 places_.clear();
912 // Kaiser: flat to 0.001 over what the centred kernel holds (a quarter of the band).
913 const double half = 0.5 * kTaps;
914 const auto bessel = [](double x) {
915 double sum = 1.0, term = 1.0;
916 for (int k = 1; k < 20; ++k)
917 {
918 term *= 0.25 * x * x / static_cast<double>(k * k);
919 sum += term;
920 }
921 return sum;
922 };
923 for (int i = 0; i < kPoints; ++i)
924 {
925 const double hz = frequency(i);
926 if (hz > limitHz) break;
927 const double at = std::min(2.0 * hz / binHz, static_cast<double>(size_ / 2 - kTaps / 2 - 1));
928 Place p;
929 const int under = static_cast<int>(at);
930 p.first = under - kTaps / 2 + 1;
931 double weight[kTaps] {}, sum = 0.0;
932 for (int j = 0; j < kTaps; ++j)
933 {
934 const double away = static_cast<double>(p.first + j) - at, x = std::numbers::pi * away;
935 const double window = bessel(5.5 * std::sqrt(std::max(0.0, 1.0 - away * away / (half * half))));
936 weight[j] = window * (std::abs(x) < 1e-9 ? 1.0 : std::sin(x) / x);
937 sum += weight[j];
938 }
939 for (int j = 0; j < kTaps; ++j) p.weight[j] = static_cast<T>(weight[j] / sum);
940 places_.push_back(p);
941 }
942 }
943
945 void add(const double* kernel, T* db) noexcept
946 {
947 if (kernel == nullptr) return;
948 const int middle = length_ / 2;
949 T* time = time_.data();
950 for (int i = middle; i < length_; ++i) time[i - middle] = static_cast<T>(kernel[i]);
951 std::fill(time + (length_ - middle), time + (size_ - middle), T(0));
952 for (int i = 0; i < middle; ++i) time[size_ - middle + i] = static_cast<T>(kernel[i]);
953 fft_->forward(time, spectrum_.data());
954 const T* s = spectrum_.data();
955 const std::size_t count = places_.size();
956 std::size_t i = 0;
957 // By DC the taps reach below bin 0 and read its mirror (the conjugate).
958 for (; i < count && places_[i].first < 0; ++i)
959 {
960 const Place& p = places_[i];
961 T re = T(0), im = T(0);
962 for (int j = 0; j < kTaps; ++j)
963 {
964 const int bin = p.first + j;
965 const int k = bin < 0 ? -bin : bin;
966 re += p.weight[j] * s[2 * k];
967 im += (bin < 0 ? -p.weight[j] : p.weight[j]) * s[2 * k + 1];
968 }
969 db[i] += T(4.3429448190325183) * std::log(std::max(re * re + im * im, T(1e-12)));
970 }
971 for (; i < count; ++i)
972 {
973 const Place& p = places_[i];
974 const T* bins = s + 2 * p.first;
975 T re = T(0), im = T(0);
976 for (int j = 0; j < kTaps; ++j)
977 {
978 re += p.weight[j] * bins[2 * j];
979 im += p.weight[j] * bins[2 * j + 1];
980 }
981 db[i] += T(4.3429448190325183) * std::log(std::max(re * re + im * im, T(1e-12)));
982 }
983 }
984
985 static constexpr int kTaps = 8;
986
987 struct Place
988 {
989 T weight[kTaps] {};
990 int first = 0;
991 };
992
993 std::unique_ptr<FFTReal<T>> fft_;
994 std::vector<T> time_, spectrum_;
995 std::vector<Place> places_;
996 int length_ = 0, size_ = 0;
997 };
998
1000 struct BinMap
1001 {
1002 void prepare(double binHz, int bins, double upper, bool isLow)
1003 {
1004 const auto size = static_cast<std::size_t>(bins);
1005 point_.assign(size, 0);
1006 part_.assign(size, T(0));
1007 share_.assign(size, T(0));
1008 const double lastPoint = static_cast<double>(kPoints - 1), span = std::log(1000.0);
1009 for (std::size_t k = 0; k < size; ++k)
1010 {
1011 const double hz = std::max(static_cast<double>(k) * binHz, 1.0);
1012 const double at = std::clamp(lastPoint * std::log(hz / 20.0) / span, 0.0, lastPoint);
1013 const int under = std::min(static_cast<int>(at), kPoints - 2);
1014 point_[k] = under;
1015 part_[k] = static_cast<T>(at - static_cast<double>(under));
1016 // All low under half the upper edge, none from the edge on.
1017 const double over = std::clamp(1.0 + std::log2(hz / upper), 0.0, 1.0);
1018 const double low = 0.5 + 0.5 * std::cos(std::numbers::pi * over);
1019 share_[k] = static_cast<T>(isLow ? low : 1.0 - low);
1020 }
1021 }
1022
1024 void write(const T* curveDb, T* logGain, int bins) const noexcept
1025 {
1026 constexpr T perDb = T(0.11512925464970229); // ln(10) / 20
1027 const int count = std::min(bins, static_cast<int>(share_.size()));
1028 for (int k = 0; k < count; ++k)
1029 {
1030 const auto u = static_cast<std::size_t>(k);
1031 const auto p = static_cast<std::size_t>(point_[u]);
1032 logGain[k] = perDb * share_[u] * (curveDb[p] + part_[u] * (curveDb[p + 1] - curveDb[p]));
1033 }
1034 }
1035
1036 std::vector<int> point_;
1037 std::vector<T> part_, share_;
1038 };
1039
1042 struct Split
1043 {
1044 void prepare(double upperBin, int lowBins, int highBins)
1045 {
1046 broadBins_ = std::min(highBins, static_cast<int>(std::ceil(upperBin)) + kReach + 1);
1047 fineBins_ = std::min(lowBins, kRatio * (broadBins_ + 1) + 1);
1048 binned_.assign(static_cast<std::size_t>(broadBins_ + 2 * kReach), 0.0);
1049 around_.assign(static_cast<std::size_t>(broadBins_ + 4), 0.0);
1050 // Three boxes of five bins, over their whole weight.
1051 double box[kWidth] { 1.0 };
1052 for (int pass = 0, length = 1; pass < 3; ++pass, length += 4)
1053 for (int i = length + 3; i >= 0; --i)
1054 {
1055 double sum = 0.0;
1056 for (int j = std::max(0, i - 4); j <= std::min(i, length - 1); ++j) sum += box[j];
1057 box[i] = sum;
1058 }
1059 for (int i = 0; i < kWidth; ++i) kernel_[i] = box[i] / 125.0;
1060 // Catmull-Rom between two bins of the high part.
1061 for (int i = 0; i < kRatio; ++i)
1062 {
1063 const double t = static_cast<double>(i) / kRatio;
1064 between_[i][0] = 0.5 * t * ((2.0 - t) * t - 1.0);
1065 between_[i][1] = 0.5 * (t * t * (3.0 * t - 5.0) + 2.0);
1066 between_[i][2] = 0.5 * t * ((4.0 - 3.0 * t) * t + 1.0);
1067 between_[i][3] = 0.5 * t * t * (t - 1.0);
1068 }
1069 }
1070
1073 void addBroad(const T* broad, T* gain, int bins) const noexcept
1074 {
1075 const auto at = [&](int j) noexcept {
1076 const int k = j < 0 ? -j : j;
1077 return k < broadBins_ ? static_cast<double>(broad[k]) : 0.0;
1078 };
1079 const int count = std::min(bins, kStep * (broadBins_ + 1));
1080 for (int k = 0; k < count; ++k)
1081 {
1082 const int j = k / kStep;
1083 const double* w = between_[(k % kStep) * (kRatio / kStep)];
1084 gain[k] += static_cast<T>(w[0] * at(j - 1) + w[1] * at(j) + w[2] * at(j + 1) + w[3] * at(j + 2));
1085 }
1086 }
1087
1089 void run(T* fine, T* broad) noexcept
1090 {
1091 // Onto the high part's bins by areas, with the spectrum's mirror at zero.
1092 double* binned = binned_.data() + kReach;
1093 for (int k = 0; k < broadBins_ + kReach; ++k)
1094 {
1095 double sum = 0.0;
1096 for (int j = -kRatio / 2; j <= kRatio / 2; ++j)
1097 {
1098 const int from = kRatio * k + j, at = from < 0 ? -from : from;
1099 if (at < fineBins_) sum += (j == -kRatio / 2 || j == kRatio / 2 ? 0.5 : 1.0) * static_cast<double>(fine[at]);
1100 }
1101 binned[k] = sum / kRatio;
1102 }
1103 for (int k = 1; k <= kReach; ++k) binned[-k] = binned[k];
1104
1105 double* smooth = around_.data() + 1;
1106 for (int k = 0; k < broadBins_; ++k)
1107 {
1108 double sum = 0.0;
1109 for (int i = 0; i < kWidth; ++i) sum += kernel_[i] * binned[k + i - kReach];
1110 smooth[k] = sum;
1111 broad[k] = static_cast<T>(sum);
1112 }
1113 smooth[-1] = smooth[1];
1114 for (int k = broadBins_; k < broadBins_ + 3; ++k) smooth[k] = 0.0;
1115
1116 for (int j = 0; j < fineBins_; ++j)
1117 {
1118 const double* s = smooth + std::min(j / kRatio, broadBins_);
1119 const double* w = between_[j % kRatio];
1120 fine[j] -= static_cast<T>(w[0] * s[-1] + w[1] * s[0] + w[2] * s[1] + w[3] * s[2]);
1121 }
1122 }
1123
1124 static constexpr int kRatio = 8;
1125 static constexpr int kStep = 2;
1126 static constexpr int kReach = 6;
1127 static constexpr int kWidth = 2 * kReach + 1;
1128
1129 int broadBins_ = 0, fineBins_ = 0;
1130 double kernel_[kWidth] {};
1131 double between_[kRatio][4] {};
1132 std::vector<double> binned_, around_;
1133 };
1134
1140 void holdMoves(std::size_t c) noexcept
1141 {
1142 T* now = curve_[c].data();
1143 T* past = recent_[c].data();
1144 T* held = held_[c].data();
1145 std::uint8_t* age = heldAge_[c].data();
1146 std::copy_n(now, kPoints, past + recentAt_ * kPoints);
1147 if (hold_ != DetailHold::Reach)
1148 {
1149 if (hold_ == DetailHold::Largest)
1150 for (int h = 0; h < kHoldCurves; ++h)
1151 for (int i = 0; i < kPoints; ++i)
1152 if (std::abs(past[h * kPoints + i]) > std::abs(now[i])) now[i] = past[h * kPoints + i];
1153 std::copy_n(now, kPoints, held);
1154 std::fill_n(age, kPoints, kHoldCurves);
1155 return;
1156 }
1157 for (int i = 0; i < kPoints; ++i)
1158 {
1159 const T size = std::abs(now[i]), kept = std::abs(held[i]);
1160 if (size > kept)
1161 {
1162 if (size > kept + T(kHoldStep)) age[i] = 0;
1163 held[i] = now[i];
1164 }
1165 if (age[i] < kHoldCurves)
1166 {
1167 now[i] = held[i];
1168 ++age[i];
1169 }
1170 else
1171 held[i] = now[i];
1172 }
1173 }
1174
1175 template <typename Design>
1176 void runQuantum(int channels, Design& design) noexcept
1177 {
1178 // The last quantum of a hop: the low filter takes its frame in it.
1179 if (quanta_ == hopQuanta_ - 1)
1180 {
1181 if constexpr (!kByBlock) recentAt_ = (recentAt_ + 1) % kHoldCurves;
1182 newest_ = (newest_ + 1) % curvesKept_;
1183 curveCount_ = (curveCount_ + 1) & 0x3FFFFFFF;
1184 const int curves = linked_ ? 1 : channels;
1185 for (int ch = 0; ch < curves; ++ch)
1186 {
1187 const auto c = static_cast<std::size_t>(ch);
1188 design(ch, curve_[c].data());
1189 if constexpr (!kByBlock) holdMoves(c);
1190 std::copy_n(curve_[c].data(), kPoints, past_[c].data() + newest_ * kPoints);
1191 lowMap_.write(curve_[c].data(), fine_[c].data(), split_.fineBins_);
1192 split_.run(fine_[c].data(), pastBroad_[c].data() + newest_ * split_.broadBins_);
1193 }
1194 }
1195 quanta_ = (quanta_ + 1) % hopQuanta_;
1196
1197 T* slow[kMaxChannels] {};
1198 T* out[kMaxChannels] {};
1199 for (int ch = 0; ch < channels; ++ch)
1200 {
1201 T* in = in_.getChannel(ch);
1202 slow[ch] = slow_.getChannel(ch);
1203 out[ch] = out_.getChannel(ch);
1204 std::copy_n(in, quantum_, original_.getChannel(ch));
1205 removed_.process(ch, original_.getChannel(ch), quantum_);
1206 align_.process(ch, in, quantum_);
1207 rate_.decimate(ch, in, slow[ch]);
1208 std::copy_n(slow[ch], kSlowQuantum, before_.getChannel(ch));
1209 slowDry_.process(ch, before_.getChannel(ch), kSlowQuantum);
1210 }
1211
1212 // The low filter and what it changed.
1213 low_.processBlock(AudioBufferView<T>(slow, channels, kSlowQuantum), [this](int ch, const T*, T* gain, int bins) noexcept {
1214 std::copy_n(fine_[curveIndex(ch)].data(), std::min(bins, split_.fineBins_), gain);
1215 });
1216
1217 // That change onto the programme, then the high filter.
1218 for (int ch = 0; ch < channels; ++ch)
1219 {
1220 T* in = in_.getChannel(ch);
1221 const T* before = before_.getChannel(ch);
1222 for (int i = 0; i < kSlowQuantum; ++i) slow[ch][i] -= before[i];
1223 T* added = change_.getChannel(ch);
1224 rate_.interpolate(ch, slow[ch], added);
1225 programme_.process(ch, in, quantum_);
1226 for (int i = 0; i < quantum_; ++i) out[ch][i] = in[i] + added[i];
1227 }
1228 high_.processBlock(AudioBufferView<T>(out, channels, quantum_), [this](int ch, const T*, T* gain, int bins) noexcept {
1229 const int oldest = (newest_ + 1) % curvesKept_;
1230 const auto c = curveIndex(ch);
1231 highMap_.write(past_[c].data() + oldest * kPoints, gain, bins);
1232 split_.addBroad(pastBroad_[c].data() + oldest * split_.broadBins_, gain, bins);
1233 });
1234
1235 if (removalListen_)
1236 for (int ch = 0; ch < channels; ++ch)
1237 {
1238 const T* original = original_.getChannel(ch);
1239 for (int i = 0; i < quantum_; ++i) out[ch][i] = original[i] - out[ch][i];
1240 }
1241 }
1242
1244 static void handOver(const double* kernel, std::vector<std::atomic<float>>& to, std::atomic<bool>& flat) noexcept
1245 {
1246 flat.store(kernel == nullptr, std::memory_order_relaxed);
1247 if (kernel == nullptr) return;
1248 for (std::size_t i = 0; i < to.size(); ++i) to[i].store(static_cast<float>(kernel[i]), std::memory_order_relaxed);
1249 }
1250
1252 template <std::size_t Channel>
1253 void handOverChannel() noexcept
1254 {
1255 static_assert(Channel < 2);
1256 handOver(low_.getKeptKernel(static_cast<int>(Channel)), playedLow_[Channel], playedLowFlat_[Channel]);
1257 handOver(high_.getKeptKernel(static_cast<int>(Channel)), playedHigh_[Channel], playedHighFlat_[Channel]);
1258 }
1259
1261 void refreshPlayed() const noexcept
1262 {
1263 const unsigned now = playedVersion_.load(std::memory_order_acquire);
1264 if ((now & 1u) == 0 && now == shownVersion_.load(std::memory_order_acquire)) return;
1265 std::lock_guard<SpinLock> lock(readerLock_);
1266 for (;;)
1267 {
1268 const unsigned version = playedVersion_.load(std::memory_order_acquire);
1269 if ((version & 1u) != 0)
1270 {
1271 std::this_thread::yield();
1272 continue;
1273 }
1274 if (version == shownVersion_.load(std::memory_order_relaxed)) return;
1275 const bool one = playedOne_.load(std::memory_order_relaxed);
1276 bool lowFlat[2] {}, highFlat[2] {};
1277 for (std::size_t ch = 0; ch < (one ? 1u : 2u); ++ch)
1278 {
1279 lowFlat[ch] = playedLowFlat_[ch].load(std::memory_order_relaxed);
1280 highFlat[ch] = playedHighFlat_[ch].load(std::memory_order_relaxed);
1281 if (!lowFlat[ch])
1282 for (std::size_t i = 0; i < readLow_[ch].size(); ++i) readLow_[ch][i] = static_cast<double>(playedLow_[ch][i].load(std::memory_order_relaxed));
1283 if (!highFlat[ch])
1284 for (std::size_t i = 0; i < readHigh_[ch].size(); ++i) readHigh_[ch][i] = static_cast<double>(playedHigh_[ch][i].load(std::memory_order_relaxed));
1285 }
1286 std::atomic_thread_fence(std::memory_order_acquire);
1287 if (playedVersion_.load(std::memory_order_relaxed) != version) continue;
1288 for (std::size_t ch = 0; ch < 2; ++ch)
1289 {
1290 const std::size_t from = one ? 0u : ch;
1291 T* curve = readCurve_.data();
1292 std::fill_n(curve, kPoints, T(0));
1293 lowResponse_.add(lowFlat[from] ? nullptr : readLow_[from].data(), curve);
1294 highResponse_.add(highFlat[from] ? nullptr : readHigh_[from].data(), curve);
1295 played_.publishPoints(static_cast<int>(ch), curve);
1296 }
1297 shownVersion_.store(version, std::memory_order_release);
1298 return;
1299 }
1300 }
1301
1302 [[nodiscard]] std::size_t curveIndex(int channel) const noexcept
1303 {
1304 return static_cast<std::size_t>(linked_ ? 0 : std::max(channel, 0));
1305 }
1306
1307 static constexpr int kFactor = 8;
1308 static constexpr int kSlowQuantum = 4;
1309 static constexpr int kSlowWindow = 64;
1310 static constexpr int kSlowPadding = 32;
1311 static constexpr int kWindow = 1024;
1312 static constexpr int kSlowSteps = kByBlock ? 4 : 1;
1313 static constexpr int kSteps = kByBlock ? 1 : 2;
1314 static constexpr int kBlockLatency = 774;
1315 static constexpr std::uint8_t kHoldCurves = 3;
1316 static constexpr double kHoldStep = 0.5;
1317 static constexpr int kPadding = 4;
1318 static constexpr int kLatency = 2048;
1319 static constexpr int kDisplayCurves = 4;
1320
1321 double fs_ = 48000.0;
1322 int channels_ = 0, factor_ = kFactor, quantum_ = kFactor * kSlowQuantum, latency_ = 0;
1323 int correctionDelay_ = 0, hopQuanta_ = 1, quanta_ = 0, filled_ = 0;
1324 int curvesKept_ = 1, newest_ = 0, curveCount_ = 0;
1325 bool prepared_ = false, linked_ = false, removalListen_ = false, shortKernel_ = false;
1326 RateChange rate_;
1327 Part low_, high_;
1328 std::vector<std::vector<T>> recent_;
1329 int recentAt_ = 0;
1330 std::vector<std::vector<T>> held_;
1331 std::vector<std::vector<std::uint8_t>> heldAge_;
1333 BinMap lowMap_, highMap_;
1334 // The display: kernels handed over by the audio thread, and what its reader makes of them.
1335 std::atomic<unsigned> playedVersion_ { 0 };
1336 std::atomic<bool> playedOne_ { true };
1337 std::array<std::vector<std::atomic<float>>, 2> playedLow_, playedHigh_;
1338 std::array<std::atomic<bool>, 2> playedLowFlat_ { true, true }, playedHighFlat_ { true, true };
1339 mutable SpinLock readerLock_;
1340 mutable std::atomic<unsigned> shownVersion_ { ~0u };
1341 mutable std::array<std::vector<double>, 2> readLow_, readHigh_;
1342 mutable std::vector<T> readCurve_;
1343 mutable Response lowResponse_, highResponse_;
1344 mutable SpectralReadout<T> played_;
1345 Split split_;
1346 std::vector<std::vector<T>> fine_, pastBroad_;
1347 Line align_, programme_, slowDry_, removed_;
1348 AudioBuffer<T, kMaxChannels> slow_, before_, original_, change_, in_, out_;
1349 std::vector<std::vector<T>> curve_;
1350 std::vector<std::vector<T>> past_;
1351};
1352
1353} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
T * getChannel(int ch) noexcept
Returns a pointer to the sample data.
void resize(int numChannels, int numSamples)
Allocates the buffer for the given dimensions.
void clear() noexcept
Clears all channels, including SIMD alignment padding. Ensures any SIMD over-read will consume pure z...
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
Minimum-phase filtering by a curve on a log-frequency grid, fine in the low end.
DetailHold getHold() const noexcept
void prepare(const AudioSpec &spec)
Allocates for a layout (an invalid spec is ignored; channels over kMaxChannels pass through).
void setHold(DetailHold hold) noexcept
By the frame, how each point holds its moves before the kernels are designed (DetailHold::Largest by ...
void setShortKernel(bool on) noexcept
Cuts the kernels of the high part (all but the fine detail of the low end) to its window and tapers t...
int getHopSize() const noexcept
void setLinked(bool on) noexcept
One curve and one filter for every channel.
void setRemovalListen(bool on) noexcept
Outputs what is taken out: the programme, delayed, less the filtered one.
void publishPlayed(int channels=2) noexcept
Hands the last kernels of both parts to a display (audio thread): a copy of them, for playedValue() a...
static double frequency(int point) noexcept
bool isRemovalListen() const noexcept
bool isDisplayDue(int shownAt) const noexcept
bool isLinked() const noexcept
void getPlayedCurve(int channel, T *played) noexcept
The response being applied now: publishPlayed() and the points of a channel (for the owner's thread,...
void processBlock(AudioBufferView< T > buffer, Design &&design) noexcept
Filters a block in place by curves that do not read the signal.
static constexpr int kPoints
Points of a curve.
bool isShortKernel() const noexcept
int getLatency() const noexcept
void reset() noexcept
Clears the signal and the curves.
int getCurveCount() const noexcept
T playedValue(int channel, int point) const noexcept
void processBlock(AudioBufferView< T > buffer, Feed &&feed, Design &&design) noexcept
Filters a block in place.
static constexpr int kMaxChannels
Channels filtered at most.
T playedExtreme() const noexcept
static std::vector< T > lowPass(double sampleRate, double cutoffHz, int numTaps, T beta=T(5))
Designs a low-pass FIR filter.
Definition FIRFilter.h:89
static T estimateKaiserBeta(double attenuationDb) noexcept
Estimates the Kaiser beta parameter for a desired attenuation.
Definition FIRFilter.h:207
A per-bin quantity of the last frame (a gain curve, a reduction), read at fixed points for a display ...
static double frequency(int point) noexcept
A part of a DetailFilter: minimum-phase kernels designed as a SpectralFilter designs its own (detail:...
std::conditional_t< L==DetailLatency::Block, double, T > S
What the signal runs in: double by the block, where it costs little; T by the frame.
void prepare(double sampleRate, int channels, int window, int padding, int block, int steps)
Allocates.
int getLatency() const noexcept
int getKernelLength() const noexcept
int getHopSize() const noexcept
void processBlock(AudioBufferView< T > buffer, Design &&design) noexcept
Filters a block in place.
int getNumBins() const noexcept
double getBinHz() const noexcept
int getTransformSize() const noexcept
void setLinked(bool on) noexcept
One kernel for every channel.
void reset() noexcept
Clears the signal and the kernels (every one is then flat).
const double * getKeptKernel(int channel) const noexcept
void setShortKernel(bool on) noexcept
Kernels a window long, tapered over their whole length, from the next one designed.
void prepare(int bins) noexcept
Takes the size of the design (allocates nothing).
static constexpr double kLeastLogGain
A log gain is taken no lower: -120 dB.
void build(FFTReal< double > &fft, double *h, double *c, int size, const double *taper, int length) noexcept
The kernel, cut and tapered.
T dotProductT(const T *DSPARK_RESTRICT a, const T *DSPARK_RESTRICT b, int count) noexcept
Definition SimdOps.h:1426
void complexMulAccum(float *DSPARK_RESTRICT accum, const float *DSPARK_RESTRICT a, const float *DSPARK_RESTRICT b, int bins) noexcept
Complex multiply-accumulate over interleaved [re, im, ...] spectra.
Definition SimdOps.h:1234
void add(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, int count) noexcept
Adds source samples into a destination buffer (no scaling).
Definition SimdOps.h:829
Main namespace for the DSPark framework.
DetailHold
How a DetailFilter by the frame holds the moves of each point of its curve, over the three curves tha...
@ None
The curve as drawn: a brief move plays at part of its depth.
@ Reach
A new move for the three, then the curve as drawn: a move ends when it is drawn.
@ Largest
Its largest move of the three: the steadiest; a move ends two curves late.
DetailLatency
When a part of a DetailFilter hands its samples back.
@ Frame
After a window of 2048: the curve leads the programme and moves as smoothly as overlapped frames of i...
@ Block
After a quarter of a frame, by partitioned convolution: the same kernels, at 774 samples.
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
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
Definition AudioSpec.h:58
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45