DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
Reverb.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
72#include "../Core/Convolver.h"
73#include "../Core/DryWetMixer.h"
74#include "../Core/RingBuffer.h"
75#include "../Core/AudioSpec.h"
76#include "../Core/AudioBuffer.h"
77#include "../Core/DspMath.h"
78#include "../Core/Resampler.h"
79#include "../Core/StateBlob.h"
80#include "../Core/TailShaper.h"
81#ifndef DSPARK_NO_FILE_IO
82#include "../IO/WavFile.h"
83#endif
84
85#include <algorithm>
86#include <array>
87#include <atomic>
88#include <cassert>
89#include <cmath>
90#include <cstddef>
91#include <cstdint>
92#include <initializer_list>
93#include <memory>
94#include <type_traits>
95#include <utility>
96#include <vector>
97
98namespace dspark {
99
100namespace detail {
101
104{
119
120 static constexpr void control(ControlPoint) noexcept {}
121 static constexpr void audioExchange() noexcept {}
122 static constexpr void audioAfterExchange(bool) noexcept {}
123 static constexpr void audioStateStore() noexcept {}
124 static constexpr void audioValidation(bool) noexcept {}
125 static constexpr void controlValidation(bool) noexcept {}
126 static constexpr void controlScan() noexcept {}
127};
128
136template <typename Bank,
137 typename Hooks = ReverbPublisherNoopHooks,
138 std::uint32_t GenerationMax = 134217727u>
140{
141public:
142 static_assert(std::atomic<std::uint32_t>::is_always_lock_free,
143 "Reverb publication requires lock-free 32-bit atomics");
144 static_assert(GenerationMax >= 1u && GenerationMax <= 134217727u,
145 "Generation must fit the 27-bit token encoding");
146
147 enum class Phase : std::uint32_t
148 {
149 free = 0u,
150 building = 1u,
151 published = 2u,
152 active = 3u,
153 retired = 4u,
154 exhausted = 5u
155 };
156
157 enum class PublishResult
158 {
159 published,
162 };
163
164 ReverbBankPublisher() noexcept = default;
165 ~ReverbBankPublisher() noexcept { shutdown(); }
166
171
173 template <typename Commit>
174 PublishResult publish(std::unique_ptr<Bank> candidate,
175 std::uint32_t latency,
176 Commit&& commit) noexcept
177 {
178 static_assert(std::is_nothrow_invocable_v<Commit&>,
179 "Reverb publication commit must be noexcept");
180 assert(candidate != nullptr);
181 Hooks::control(Hooks::ControlPoint::candidateReady);
182 Hooks::control(Hooks::ControlPoint::beforeFirstScan);
183
184 SlotChoice choice = scanOnce();
185 bool claimedPending = false;
186 if (!choice.valid)
187 {
188 const std::uint32_t observed =
189 pendingToken_.load(std::memory_order_acquire);
190 const bool exactPinnedPending = observed != emptyToken
191 && observed == pinnedToken_;
192 const bool generationLimitPending = observed != emptyToken
193 && tokenGeneration(observed) >= GenerationMax;
194 if (!exactPinnedPending && !generationLimitPending)
195 {
196 Hooks::control(Hooks::ControlPoint::beforePendingExchange);
197 const std::uint32_t old =
198 pendingToken_.exchange(emptyToken, std::memory_order_acq_rel);
199 Hooks::control(Hooks::ControlPoint::afterPendingExchange);
200 if (old != emptyToken)
201 {
202 const std::size_t index = tokenIndex(old);
203 const std::uint32_t generation = tokenGeneration(old);
204 const bool exactObserved = old == observed;
205 const bool reusable = exactObserved
206 && old != pinnedToken_ && generation < GenerationMax
207 && slots_[index].stateWord.load(std::memory_order_acquire)
208 == encodeState(generation, Phase::published);
209 Hooks::controlValidation(reusable);
210 assert(reusable);
211 if (!reusable)
212 {
213 // No slot or metadata has changed yet. Restore the exact
214 // token so even an injected invariant failure has the
215 // strong failure guarantee.
216 pendingToken_.store(old, std::memory_order_release);
218 }
219 choice = { index, generation + 1u, true, false };
220 claimedPending = true;
221 }
222 else
223 {
224 // Audio won the pending token. One read-only bounded rescan
225 // may observe the RETIRED slot it released; an empty-token
226 // exchange changed no externally visible state.
227 choice = scanOnce();
228 }
229 }
230 }
231
232 if (!choice.valid)
233 {
234 Hooks::control(Hooks::ControlPoint::noCapacity);
236 }
237
238 Hooks::control(Hooks::ControlPoint::afterSlotSelection);
239 auto& slot = slots_[choice.index];
240 if (claimedPending)
241 {
242 const std::uint32_t claimedGeneration = choice.generation - 1u;
243 const bool retired = retireControlOwned(
244 makeToken(claimedGeneration, choice.index));
245 assert(retired);
246 (void)retired;
247 }
248 nextGeneration_[choice.index] = choice.generation;
249 slot.stateWord.store(encodeState(choice.generation, Phase::building),
250 std::memory_order_relaxed);
251 if (choice.reclaimsRetired)
252 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
253 slot.bank = std::move(candidate);
254 slot.stateWord.store(encodeState(choice.generation, Phase::published),
255 std::memory_order_release);
256 Hooks::control(Hooks::ControlPoint::afterPublishedStore);
257
258 const std::uint32_t token = makeToken(choice.generation, choice.index);
259 Hooks::control(Hooks::ControlPoint::beforePendingExchange);
260 const std::uint32_t old =
261 pendingToken_.exchange(token, std::memory_order_acq_rel);
262 Hooks::control(Hooks::ControlPoint::afterPendingExchange);
263 if (old != emptyToken && !retireControlOwned(old))
264 {
265 // Once slot publication begins, the protocol is a no-fail commit.
266 // A token returned by this exchange is control-owned and must name
267 // PUBLISHED storage under the single-writer contract.
268 assert(false && "Reverb publication ownership invariant");
269 }
270
271 Hooks::control(Hooks::ControlPoint::beforeCommit);
272 commit();
273 latestToken_ = token;
274 publicationMetadata_.store(packMetadata(latency),
275 std::memory_order_release);
276 scanStart_ = (choice.index + 1u) & slotMask;
277 quarantineExhaustedRetired();
278 Hooks::control(Hooks::ControlPoint::afterCommit);
280 }
281
283 [[nodiscard]] Bank* adoptAtBoundary() noexcept
284 {
285 Hooks::audioExchange();
286 const std::uint32_t next =
287 pendingToken_.exchange(emptyToken, std::memory_order_acq_rel);
288 Hooks::audioAfterExchange(next != emptyToken);
289 if (next != emptyToken)
290 {
291 const std::size_t nextIndex = tokenIndex(next);
292 const std::uint32_t nextGeneration = tokenGeneration(next);
293 const bool nextValid =
294 slots_[nextIndex].stateWord.load(std::memory_order_acquire)
295 == encodeState(nextGeneration, Phase::published);
296 Hooks::audioValidation(nextValid);
297 assert(nextValid);
298 if (nextValid)
299 {
300 slots_[nextIndex].stateWord.store(
301 encodeState(nextGeneration, Phase::active),
302 std::memory_order_release);
303 Hooks::audioStateStore();
304
305 const std::uint32_t old = activeToken_;
306 activeToken_ = next;
307 if (old != emptyToken)
308 {
309 const std::size_t oldIndex = tokenIndex(old);
310 const std::uint32_t oldGeneration = tokenGeneration(old);
311 const bool oldValid =
312 slots_[oldIndex].stateWord.load(std::memory_order_acquire)
313 == encodeState(oldGeneration, Phase::active);
314 Hooks::audioValidation(oldValid);
315 assert(oldValid);
316 if (oldValid)
317 {
318 slots_[oldIndex].stateWord.store(
319 encodeState(oldGeneration, Phase::retired),
320 std::memory_order_release);
321 Hooks::audioStateStore();
322 }
323 }
324 }
325 }
326
327 return activeToken_ == emptyToken
328 ? nullptr
329 : slots_[tokenIndex(activeToken_)].bank.get();
330 }
331
334 [[nodiscard]] bool hasPending() const noexcept
335 {
336 return pendingToken_.load(std::memory_order_relaxed) != emptyToken;
337 }
338
340 [[nodiscard]] Bank* activeBank() const noexcept
341 {
342 return activeToken_ == emptyToken
343 ? nullptr
344 : slots_[tokenIndex(activeToken_)].bank.get();
345 }
346
348 [[nodiscard]] Bank* pinLatest() noexcept
349 {
350 const std::uint32_t previous = pinnedToken_;
351 pinnedToken_ = emptyToken;
352 const std::uint32_t latest = latestToken_;
353 if (previous != emptyToken && previous != latest)
354 reclaimIfRetired(previous);
355
356 if (latest == emptyToken) return nullptr;
357 const std::size_t index = tokenIndex(latest);
358 const std::uint32_t state =
359 slots_[index].stateWord.load(std::memory_order_acquire);
360 const Phase phase = statePhase(state);
361 const bool valid = stateGeneration(state) == tokenGeneration(latest)
362 && phase != Phase::free && phase != Phase::building
363 && phase != Phase::exhausted && slots_[index].bank != nullptr;
364 Hooks::controlValidation(valid);
365 assert(valid);
366 if (!valid) return nullptr;
367 pinnedToken_ = latest;
368 return slots_[index].bank.get();
369 }
370
371 [[nodiscard]] bool isLoaded() const noexcept
372 {
373 return (publicationMetadata_.load(std::memory_order_acquire)
374 & loadedMask) != 0u;
375 }
376
377 [[nodiscard]] int latency() const noexcept
378 {
379 return static_cast<int>(publicationMetadata_.load(
380 std::memory_order_acquire) & latencyMask);
381 }
382
384 void shutdown() noexcept
385 {
386 pendingToken_.exchange(emptyToken, std::memory_order_acq_rel);
387 activeToken_ = emptyToken;
388 latestToken_ = emptyToken;
389 pinnedToken_ = emptyToken;
390 publicationMetadata_.store(0u, std::memory_order_release);
391 for (auto& slot : slots_)
392 {
393 slot.bank.reset();
394 slot.stateWord.store(encodeState(0u, Phase::free),
395 std::memory_order_relaxed);
396 }
397 nextGeneration_.fill(0u);
398 scanStart_ = 0u;
399 }
400
401 // Deterministic detail-level observability used by the dedicated tests.
402 [[nodiscard]] std::uint32_t stateWordForTest(std::size_t index) const noexcept
403 {
404 return slots_[index].stateWord.load(std::memory_order_acquire);
405 }
406 [[nodiscard]] std::uint32_t pendingTokenForTest() const noexcept
407 {
408 return pendingToken_.load(std::memory_order_acquire);
409 }
410 [[nodiscard]] std::uint32_t activeTokenForTest() const noexcept { return activeToken_; }
411 [[nodiscard]] std::uint32_t latestTokenForTest() const noexcept { return latestToken_; }
412 [[nodiscard]] std::uint32_t pinnedTokenForTest() const noexcept { return pinnedToken_; }
413 [[nodiscard]] std::size_t residentBanksForTest() const noexcept
414 {
415 std::size_t count = 0;
416 for (const auto& slot : slots_) count += slot.bank != nullptr ? 1u : 0u;
417 return count;
418 }
419 [[nodiscard]] const void* atomicWordAddressForTest(
420 std::size_t index) const noexcept
421 {
422 if (index < slots_.size())
423 return static_cast<const void*>(&slots_[index].stateWord);
424 if (index == slots_.size())
425 return static_cast<const void*>(&pendingToken_);
426 return static_cast<const void*>(&publicationMetadata_);
427 }
428 [[nodiscard]] static constexpr std::size_t atomicWordCountForTest() noexcept
429 {
430 return 6u;
431 }
432 [[nodiscard]] static constexpr Phase phaseForTest(std::uint32_t state) noexcept
433 {
434 return statePhase(state);
435 }
436 [[nodiscard]] static constexpr std::uint32_t generationForTest(
437 std::uint32_t state) noexcept
438 {
439 return stateGeneration(state);
440 }
441
442private:
443 static constexpr std::uint32_t emptyToken = 0u;
444 static constexpr std::uint32_t slotMask = 3u;
445 static constexpr std::uint32_t phaseMask = 7u;
446 static constexpr std::uint32_t loadedMask = 0x80000000u;
447 static constexpr std::uint32_t latencyMask = 0x7fffffffu;
448
449 struct BankSlot
450 {
451 std::unique_ptr<Bank> bank;
452 std::atomic<std::uint32_t> stateWord { 0u };
453 };
454
455 struct SlotChoice
456 {
457 std::size_t index = 0;
458 std::uint32_t generation = 0;
459 bool valid = false;
460 bool reclaimsRetired = false;
461 };
462
463 [[nodiscard]] static constexpr std::uint32_t makeToken(
464 std::uint32_t generation, std::size_t index) noexcept
465 {
466 return (generation << 2u) | static_cast<std::uint32_t>(index);
467 }
468
469 [[nodiscard]] static constexpr std::size_t tokenIndex(
470 std::uint32_t token) noexcept
471 {
472 return static_cast<std::size_t>(token & slotMask);
473 }
474
475 [[nodiscard]] static constexpr std::uint32_t tokenGeneration(
476 std::uint32_t token) noexcept
477 {
478 return token >> 2u;
479 }
480
481 [[nodiscard]] static constexpr std::uint32_t encodeState(
482 std::uint32_t generation, Phase phase) noexcept
483 {
484 return (generation << 3u) | static_cast<std::uint32_t>(phase);
485 }
486
487 [[nodiscard]] static constexpr std::uint32_t stateGeneration(
488 std::uint32_t state) noexcept
489 {
490 return state >> 3u;
491 }
492
493 [[nodiscard]] static constexpr Phase statePhase(std::uint32_t state) noexcept
494 {
495 return static_cast<Phase>(state & phaseMask);
496 }
497
498 [[nodiscard]] static constexpr std::uint32_t packMetadata(
499 std::uint32_t latency) noexcept
500 {
501 return loadedMask | std::min(latency, latencyMask);
502 }
503
504 [[nodiscard]] SlotChoice scanOnce() noexcept
505 {
506 for (std::size_t offset = 0; offset < slots_.size(); ++offset)
507 {
508 Hooks::controlScan();
509 const std::size_t index = (scanStart_ + offset) & slotMask;
510 auto& slot = slots_[index];
511 const std::uint32_t state =
512 slot.stateWord.load(std::memory_order_acquire);
513 const Phase phase = statePhase(state);
514 const std::uint32_t generation = stateGeneration(state);
515 const std::uint32_t exactToken = makeToken(generation, index);
516
517 if (phase == Phase::free)
518 {
519 const bool pristine = generation == 0u
520 && nextGeneration_[index] == 0u && slot.bank == nullptr;
521 Hooks::controlValidation(pristine);
522 assert(pristine);
523 if (pristine) return { index, 1u, true, false };
524 continue;
525 }
526
527 if (phase != Phase::retired || exactToken == pinnedToken_)
528 continue;
529
530 const bool generationMatches =
531 nextGeneration_[index] == generation;
532 Hooks::controlValidation(generationMatches);
533 assert(generationMatches);
534 if (!generationMatches) continue;
535
536 if (generation >= GenerationMax) continue;
537 return { index, generation + 1u, true, true };
538 }
539 return {};
540 }
541
542 bool retireControlOwned(std::uint32_t token) noexcept
543 {
544 const std::size_t index = tokenIndex(token);
545 const std::uint32_t generation = tokenGeneration(token);
546 auto& slot = slots_[index];
547 const bool valid =
548 slot.stateWord.load(std::memory_order_acquire)
549 == encodeState(generation, Phase::published);
550 Hooks::controlValidation(valid);
551 assert(valid);
552 if (!valid) return false;
553
554 Hooks::control(Hooks::ControlPoint::beforeOldRetirement);
555 slot.stateWord.store(encodeState(generation, Phase::retired),
556 std::memory_order_release);
557 if (token != pinnedToken_)
558 {
559 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
560 slot.bank.reset();
561 }
562 return true;
563 }
564
565 void quarantineExhaustedRetired() noexcept
566 {
567 for (std::size_t index = 0; index < slots_.size(); ++index)
568 {
569 auto& slot = slots_[index];
570 const std::uint32_t state =
571 slot.stateWord.load(std::memory_order_acquire);
572 const std::uint32_t generation = stateGeneration(state);
573 if (statePhase(state) != Phase::retired
574 || generation < GenerationMax
575 || makeToken(generation, index) == pinnedToken_)
576 continue;
577 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
578 slot.bank.reset();
579 slot.stateWord.store(encodeState(generation, Phase::exhausted),
580 std::memory_order_release);
581 }
582 }
583
584 void reclaimIfRetired(std::uint32_t token) noexcept
585 {
586 auto& slot = slots_[tokenIndex(token)];
587 const std::uint32_t state =
588 slot.stateWord.load(std::memory_order_acquire);
589 if (state == encodeState(tokenGeneration(token), Phase::retired))
590 {
591 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
592 slot.bank.reset();
593 }
594 }
595
596 std::array<BankSlot, 4> slots_ {};
597 std::atomic<std::uint32_t> pendingToken_ { emptyToken };
598 std::atomic<std::uint32_t> publicationMetadata_ { 0u };
599 std::uint32_t activeToken_ = emptyToken; // Audio-owner only.
600 std::uint32_t latestToken_ = emptyToken; // Control-owner only.
601 std::uint32_t pinnedToken_ = emptyToken; // Control-owner only.
602 std::array<std::uint32_t, 4> nextGeneration_ {};
603 std::size_t scanStart_ = 0; // Control-owner only.
604};
605
606} // namespace detail
607
617template <FloatType T>
619{
620protected:
622 {
623 std::vector<Convolver<T>> convolvers;
627 int extraDelay = 0;
628 std::vector<RingBuffer<T>> dryDelay;
629 std::vector<T> dryScratch;
631 };
632
633#if defined(DSPARK_REVERB_TEST_GENERATION_MAX)
634 static constexpr std::uint32_t publisherGenerationMax =
635 DSPARK_REVERB_TEST_GENERATION_MAX;
636#else
637 static constexpr std::uint32_t publisherGenerationMax = 134217727u;
638#endif
641
642public:
643 Reverb() = default;
645
646 Reverb(const Reverb&) = delete;
647 Reverb& operator=(const Reverb&) = delete;
648 Reverb(Reverb&&) = delete;
649 Reverb& operator=(Reverb&&) = delete;
650
651 // -- Lifecycle --------------------------------------------------------------
652
664 void prepare(const AudioSpec& spec)
665 {
666 if (!spec.isValid()) return; // release-safe: keep previous state
667
668 // The convolution engine partitions at the next power of two of the
669 // max block size (>= 2, matching Convolver's own normalisation), and
670 // that is exactly its processing latency. Clamp before the round-up
671 // loop so an absurd block size cannot overflow the shift.
672 const int blockSize = std::clamp(spec.maxBlockSize, 1, 1 << 20);
673 int fftBlock = 2;
674 while (fftBlock < blockSize) fftBlock <<= 1;
675 // Build every potentially-throwing setup object locally. The stopped
676 // audio/setup ownership contract makes the final moves atomic as one
677 // logical transaction even though the members themselves are plain.
678 DryWetMixer<T> nextMixer;
679 nextMixer.prepare(spec);
680 nextMixer.setLatencyCompensation(fftBlock);
681
682 // Pre-delay ring buffers (one per channel, max 500ms)
683 const int maxDelaySamples = static_cast<int>(spec.sampleRate * 0.5) + 1;
684 std::vector<RingBuffer<T>> nextPreDelayBuffers(
685 static_cast<size_t>(spec.numChannels));
686 for (auto& rb : nextPreDelayBuffers)
687 rb.prepare(maxDelaySamples);
688 const int nextPreDelaySamples = calculatePreDelaySamples(spec);
689
690 const int nextSwapFade = std::max(1, static_cast<int>(spec.sampleRate * 0.01));
691 std::vector<T> nextLevels(static_cast<size_t>(blockSize), T(0));
692 tail_.prepare(spec.sampleRate);
693 if (irStorage_.empty())
694 {
695 spec_ = spec;
696 tailLevels_ = std::move(nextLevels);
697 swapFadeLength_ = nextSwapFade;
698 swapFadePos_ = nextSwapFade;
699 fftBlockSize_ = fftBlock;
700 mixer_ = std::move(nextMixer);
701 preDelayBuffers_ = std::move(nextPreDelayBuffers);
702 preDelaySamples_.store(nextPreDelaySamples,
703 std::memory_order_relaxed);
704 return;
705 }
706
707 auto candidate = buildBank(irStorage_, irLength_, irChannels_,
708 irSampleRate_, spec, fftBlock,
709 decayScale_.load(std::memory_order_relaxed),
710 stretch_.load(std::memory_order_relaxed));
711 const std::uint32_t latency = bankLatency(*candidate);
713 std::move(candidate), latency,
714 [&]() noexcept {
715 spec_ = spec;
716 tailLevels_ = std::move(nextLevels);
717 swapFadeLength_ = nextSwapFade;
718 swapFadePos_ = nextSwapFade;
719 fftBlockSize_ = fftBlock;
720 mixer_ = std::move(nextMixer);
721 preDelayBuffers_ = std::move(nextPreDelayBuffers);
722 preDelaySamples_.store(nextPreDelaySamples,
723 std::memory_order_relaxed);
724 });
725 }
726
744 void processBlock(AudioBufferView<T> buffer) noexcept
745 {
746 // A replacement bank waiting at this boundary: render this block on
747 // the current bank while its wet signal fades out, and adopt at its
748 // end, so the swap does not step (the new bank starts from silence).
750 const bool swapAfter = bank != nullptr && bankPublisher_.hasPending();
751 if (!swapAfter) bank = bankPublisher_.adoptAtBoundary();
752 if (!bank || bank->convolvers.empty()) return;
753
754 // The dry copies hold maxBlockSize samples: run a longer block as
755 // several conforming ones, with the same result.
756 const int nS = buffer.getNumSamples();
757 const int maxBlock = std::max(1, spec_.maxBlockSize);
758 for (int start = 0; start < nS; start += maxBlock)
759 processPart(*bank, buffer.getSubView(start, std::min(maxBlock, nS - start)),
760 swapAfter ? start : -1, nS);
761
762 if (swapAfter)
763 {
765 // Fade the adopted bank in from where its output starts: a fresh
766 // convolver is silent for its partition latency.
768 }
769 }
770
778 void reset() noexcept
779 {
780 // Reset the snapshot we can see; if a concurrent load publishes a
781 // replacement bank it arrives freshly zeroed anyway.
782 if (ConvolverBank* const bank = bankPublisher_.adoptAtBoundary())
783 {
784 for (auto& conv : bank->convolvers)
785 conv.reset();
786 for (auto& ring : bank->dryDelay)
787 ring.reset();
788 }
789 for (auto& rb : preDelayBuffers_)
790 rb.reset();
791 mixer_.reset();
793 }
794
795 // -- Level 1: Simple API ----------------------------------------------------
796
797#ifndef DSPARK_NO_FILE_IO
809 bool loadIR(const char* wavFilePath)
810 {
811 WavFile wav;
812 if (!wav.openRead(wavFilePath))
813 return false;
814
815 auto info = wav.getInfo();
816 if (info.numSamples <= 0 || info.numChannels <= 0
817 || info.numSamples > (static_cast<int64_t>(1) << 30)
818 || !(info.sampleRate > 0))
819 {
820 wav.close();
821 return false;
822 }
823
824 AudioBuffer<T> irBuf;
825 irBuf.resize(info.numChannels, static_cast<int>(info.numSamples));
826 wav.readSamples(irBuf.toView());
827 wav.close();
828
829 const int nextChannels = info.numChannels;
830 const int nextLength = static_cast<int>(info.numSamples);
831 std::vector<T> nextStorage(
832 static_cast<size_t>(nextChannels) * static_cast<size_t>(nextLength));
833 for (int ch = 0; ch < nextChannels; ++ch)
834 {
835 const T* src = irBuf.getChannel(ch);
836 T* dst = nextStorage.data()
837 + static_cast<size_t>(ch) * static_cast<size_t>(nextLength);
838 std::copy_n(src, nextLength, dst);
839 }
840 return commitImpulseResponse(std::move(nextStorage), nextLength,
841 nextChannels, info.sampleRate);
842 }
843#endif // DSPARK_NO_FILE_IO
844
850 void setMix(T dryWet) noexcept
851 {
852 if (!std::isfinite(dryWet)) return;
853 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
854 }
855
856 // -- Level 2: Intermediate API ----------------------------------------------
857
866 bool loadIR(const T* data, int length, double irSampleRate)
867 {
868 if (data == nullptr || length <= 0
869 || !std::isfinite(irSampleRate) || !(irSampleRate > 0.0))
870 return false;
871
872 std::vector<T> nextStorage(data, data + length);
873 return commitImpulseResponse(std::move(nextStorage), length, 1,
874 irSampleRate);
875 }
876
891 bool loadIR(AudioBufferView<const T> ir, double irSampleRate)
892 {
893 const int nextChannels = ir.getNumChannels();
894 const int nextLength = ir.getNumSamples();
895 if (nextChannels <= 0 || nextLength <= 0
896 || !std::isfinite(irSampleRate) || !(irSampleRate > 0.0))
897 return false;
898 for (int ch = 0; ch < nextChannels; ++ch)
899 if (ir.getChannel(ch) == nullptr) return false;
900
901 std::vector<T> nextStorage(
902 static_cast<size_t>(nextChannels) * static_cast<size_t>(nextLength));
903 for (int ch = 0; ch < nextChannels; ++ch)
904 std::copy_n(ir.getChannel(ch), nextLength,
905 nextStorage.data() + static_cast<size_t>(ch) * static_cast<size_t>(nextLength));
906 return commitImpulseResponse(std::move(nextStorage), nextLength,
907 nextChannels, irSampleRate);
908 }
909
920 void setPreDelay(T ms) noexcept
921 {
922 if (!std::isfinite(ms)) return;
923 preDelayMs_.store(std::clamp(ms, T(0), T(500)), std::memory_order_relaxed);
925 }
926
950 void setDecayScale(T scale)
951 {
952 if (!std::isfinite(scale)) return;
953 const T next = std::clamp(scale, T(0.25), T(2));
954 if (next == decayScale_.load(std::memory_order_relaxed)) return;
955 if (spec_.sampleRate <= 0 || irStorage_.empty())
956 {
957 decayScale_.store(next, std::memory_order_relaxed);
958 return;
959 }
960 auto candidate = buildBank(irStorage_, irLength_, irChannels_,
962 stretch_.load(std::memory_order_relaxed));
963 const std::uint32_t latency = bankLatency(*candidate);
965 std::move(candidate), latency,
966 [&]() noexcept { decayScale_.store(next, std::memory_order_relaxed); });
967 }
968
983 void setStretch(T ratio)
984 {
985 if (!std::isfinite(ratio)) return;
986 const T next = std::clamp(ratio, T(0.5), T(2));
987 if (next == stretch_.load(std::memory_order_relaxed)) return;
988 if (spec_.sampleRate <= 0 || irStorage_.empty())
989 {
990 stretch_.store(next, std::memory_order_relaxed);
991 return;
992 }
993 auto candidate = buildBank(irStorage_, irLength_, irChannels_,
995 decayScale_.load(std::memory_order_relaxed),
996 next);
997 const std::uint32_t latency = bankLatency(*candidate);
999 std::move(candidate), latency,
1000 [&]() noexcept { stretch_.store(next, std::memory_order_relaxed); });
1001 }
1002
1004 [[nodiscard]] T getDecayScale() const noexcept { return decayScale_.load(std::memory_order_relaxed); }
1005
1007 [[nodiscard]] T getStretch() const noexcept { return stretch_.load(std::memory_order_relaxed); }
1008
1014 void setDryDip(T dB) noexcept { tail_.setDryDip(dB); }
1015
1021 void setGate(T thresholdDb) noexcept { tail_.setGate(thresholdDb); }
1022
1024 void setGateHold(T ms) noexcept { tail_.setGateHold(ms); }
1025
1027 void setGateRelease(T ms) noexcept { tail_.setGateRelease(ms); }
1028
1029 [[nodiscard]] T getDryDip() const noexcept { return tail_.getDryDip(); }
1030 [[nodiscard]] T getGate() const noexcept { return tail_.getGate(); }
1031 [[nodiscard]] T getGateHold() const noexcept { return tail_.getGateHold(); }
1032 [[nodiscard]] T getGateRelease() const noexcept { return tail_.getGateRelease(); }
1033
1034 // -- Level 3: Expert API ----------------------------------------------------
1035
1062 Convolver<T>& getConvolver(int channel = 0)
1063 {
1064 ConvolverBank* const bank = bankPublisher_.pinLatest();
1065 if (!bank || bank->convolvers.empty())
1066 return fallbackConvolver_;
1067 const int n = static_cast<int>(bank->convolvers.size());
1068 channel = std::clamp(channel, 0, n - 1);
1069 return bank->convolvers[static_cast<size_t>(channel)];
1070 }
1071
1082
1084 [[nodiscard]] bool isLoaded() const noexcept
1085 {
1086 return bankPublisher_.isLoaded();
1087 }
1088
1090 [[nodiscard]] T getMix() const noexcept { return mix_.load(std::memory_order_relaxed); }
1091
1093 [[nodiscard]] T getPreDelay() const noexcept { return preDelayMs_.load(std::memory_order_relaxed); }
1094
1108 [[nodiscard]] int getLatency() const noexcept
1109 {
1110 return bankPublisher_.latency();
1111 }
1112
1113
1116 [[nodiscard]] std::vector<uint8_t> getState() const
1117 {
1118 StateWriter w(stateId("CRVB"), 1);
1119 w.write("mix", static_cast<float>(mix_.load(std::memory_order_relaxed)));
1120 w.write("preDelay", static_cast<float>(preDelayMs_.load(std::memory_order_relaxed)));
1121 w.write("decayScale", static_cast<float>(decayScale_.load(std::memory_order_relaxed)));
1122 w.write("stretch", static_cast<float>(stretch_.load(std::memory_order_relaxed)));
1123 w.write("dryDip", static_cast<float>(getDryDip()));
1124 w.write("gate", static_cast<float>(getGate()));
1125 w.write("gateHold", static_cast<float>(getGateHold()));
1126 w.write("gateRelease", static_cast<float>(getGateRelease()));
1127 return w.blob();
1128 }
1129
1131 bool setState(const uint8_t* data, size_t size)
1132 {
1133 StateReader r(data, size);
1134 if (!r.isValid() || r.processorId() != stateId("CRVB")) return false;
1135
1136 // Parse, validate and stage the complete requested state before the
1137 // first externally observable write. Non-finite blob values retain the
1138 // corresponding current value, matching the individual setter policy.
1139 T mix = static_cast<T>(r.read("mix", 0.3f));
1140 T preDelay = static_cast<T>(r.read("preDelay", 0.0f));
1141 T ds = static_cast<T>(r.read("decayScale", 1.0f));
1142 T st = static_cast<T>(r.read("stretch", 1.0f));
1143 const T duck = static_cast<T>(r.read("dryDip", 0.0f));
1144 const T gate = static_cast<T>(r.read("gate", -200.0f));
1145 const T gateHold = static_cast<T>(r.read("gateHold", 100.0f));
1146 const T gateRelease = static_cast<T>(r.read("gateRelease", 150.0f));
1147 if (!std::isfinite(mix)) mix = mix_.load(std::memory_order_relaxed);
1148 if (!std::isfinite(preDelay))
1149 preDelay = preDelayMs_.load(std::memory_order_relaxed);
1150 if (!std::isfinite(ds)) ds = decayScale_.load(std::memory_order_relaxed);
1151 if (!std::isfinite(st)) st = stretch_.load(std::memory_order_relaxed);
1152 mix = std::clamp(mix, T(0), T(1));
1153 preDelay = std::clamp(preDelay, T(0), T(500));
1154 ds = std::clamp(ds, T(0.25), T(2));
1155 st = std::clamp(st, T(0.5), T(2));
1156 const int preDelaySamples = calculatePreDelaySamples(spec_, preDelay);
1157 const bool shapeChanged =
1158 ds != decayScale_.load(std::memory_order_relaxed)
1159 || st != stretch_.load(std::memory_order_relaxed);
1160
1161 const auto commitParameters = [&]() noexcept {
1162 mix_.store(mix, std::memory_order_relaxed);
1163 preDelayMs_.store(preDelay, std::memory_order_relaxed);
1164 preDelaySamples_.store(preDelaySamples, std::memory_order_relaxed);
1165 decayScale_.store(ds, std::memory_order_relaxed);
1166 stretch_.store(st, std::memory_order_relaxed);
1167 tail_.setDryDip(duck);
1168 tail_.setGate(gate);
1169 tail_.setGateHold(gateHold);
1170 tail_.setGateRelease(gateRelease);
1171 };
1172
1173 if (!shapeChanged || spec_.sampleRate <= 0 || irStorage_.empty())
1174 {
1175 commitParameters();
1176 return true;
1177 }
1178
1179 // Candidate construction owns every throwing operation. Publisher
1180 // capacity is resolved before its first slot/scalar mutation; once the
1181 // commit begins, only unique_ptr moves and atomic/plain no-throw stores
1182 // remain.
1183 auto candidate = buildBank(irStorage_, irLength_, irChannels_,
1185 const std::uint32_t latency = bankLatency(*candidate);
1186 const auto result = bankPublisher_.publish(
1187 std::move(candidate), latency, commitParameters);
1188 if (result != Publisher::PublishResult::published) return false;
1189 return true;
1190 }
1191
1192protected:
1202 void processPart(ConvolverBank& bank, AudioBufferView<T> buffer, int fadeOutAt,
1203 int blockLength) noexcept
1204 {
1205 const int nCh = std::min(buffer.getNumChannels(),
1206 static_cast<int>(bank.convolvers.size()));
1207 const int nS = buffer.getNumSamples();
1208
1209 if (bank.extraDelay > 0 && nS <= bank.scratchLength)
1210 {
1211 // The dry path waits for the wet path's extra samples too. Only
1212 // the prepared channels have a dry path; further ones pass
1213 // through untouched.
1214 const int dCh = std::min({ buffer.getNumChannels(),
1215 static_cast<int>(bank.dryDelay.size()), 64 });
1216 std::array<T*, 64> ptrs {};
1217 for (int ch = 0; ch < dCh; ++ch)
1218 {
1219 auto& ring = bank.dryDelay[static_cast<size_t>(ch)];
1220 T* dst = bank.dryScratch.data()
1221 + static_cast<size_t>(ch) * static_cast<size_t>(bank.scratchLength);
1222 const T* src = buffer.getChannel(ch);
1223 for (int i = 0; i < nS; ++i)
1224 {
1225 ring.push(src[i]);
1226 dst[i] = ring.read(bank.extraDelay);
1227 }
1228 ptrs[static_cast<size_t>(ch)] = dst;
1229 }
1230 mixer_.pushDry(AudioBufferView<T>(ptrs.data(), dCh, nS));
1231 }
1232 else
1233 {
1234 mixer_.pushDry(buffer);
1235 }
1236
1237 int preDelSamp = preDelaySamples_.load(std::memory_order_relaxed);
1238 T mixVal = mix_.load(std::memory_order_relaxed);
1239
1240 // The dry level per frame for the dip and the gate, read before
1241 // the convolution overwrites the buffer.
1242 tail_.sync();
1243 const bool shaping = tail_.isActive() && nS <= static_cast<int>(tailLevels_.size());
1244 if (shaping)
1245 {
1246 std::fill(tailLevels_.begin(), tailLevels_.begin() + nS, T(0));
1247 for (int ch = 0; ch < nCh; ++ch)
1248 {
1249 const T* d = buffer.getChannel(ch);
1250 for (int i = 0; i < nS; ++i)
1251 tailLevels_[static_cast<size_t>(i)] = std::max(tailLevels_[static_cast<size_t>(i)], std::abs(d[i]));
1252 }
1253 }
1254
1255 for (int ch = 0; ch < nCh; ++ch)
1256 {
1257 T* data = buffer.getChannel(ch);
1258
1259 if (preDelSamp > 0)
1260 {
1261 auto& ring = preDelayBuffers_[static_cast<size_t>(ch)];
1262 for (int i = 0; i < nS; ++i)
1263 {
1264 ring.push(data[i]);
1265 data[i] = ring.read(preDelSamp);
1266 }
1267 }
1268
1269 bank.convolvers[static_cast<size_t>(ch)].processInPlace(data, nS);
1270 }
1271
1272 // Bank-swap fades of the wet signal (raised cosine).
1273 if (fadeOutAt >= 0)
1274 {
1275 const double scale = 3.141592653589793 / static_cast<double>(blockLength);
1276 for (int i = 0; i < nS; ++i)
1277 {
1278 const T g = static_cast<T>(0.5 + 0.5 * std::cos(scale * (fadeOutAt + i + 1)));
1279 for (int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= g;
1280 }
1281 }
1282 else if (swapFadePos_ < swapFadeLength_)
1283 {
1284 const double scale = 3.141592653589793 / static_cast<double>(swapFadeLength_);
1285 for (int i = 0; i < nS; ++i)
1286 {
1287 const int pos = std::clamp(swapFadePos_ + i + 1, 0, swapFadeLength_);
1288 const T g = static_cast<T>(0.5 - 0.5 * std::cos(scale * pos));
1289 for (int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= g;
1290 }
1291 swapFadePos_ = std::min(swapFadePos_ + nS, swapFadeLength_);
1292 }
1293
1294 if (shaping)
1295 for (int i = 0; i < nS; ++i)
1296 {
1297 const T g = tail_.next(tailLevels_[static_cast<size_t>(i)]);
1298 for (int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= g;
1299 }
1300
1301 mixer_.mixWet(buffer, mixVal);
1302 }
1303
1304 [[nodiscard]] int calculatePreDelaySamples(const AudioSpec& spec) const noexcept
1305 {
1307 spec, preDelayMs_.load(std::memory_order_relaxed));
1308 }
1309
1310 [[nodiscard]] static int calculatePreDelaySamples(
1311 const AudioSpec& spec, T preDelayMs) noexcept
1312 {
1313 if (!(spec.sampleRate > 0)) return 0;
1314 const int maxSamp = static_cast<int>(spec.sampleRate * 0.5);
1315 const int samp = static_cast<int>(
1316 static_cast<T>(spec.sampleRate)
1317 * preDelayMs / T(1000));
1318 return std::clamp(samp, 0, maxSamp);
1319 }
1320
1321 void updatePreDelay() noexcept
1322 {
1323 if (spec_.sampleRate > 0)
1324 {
1325 // The pre-delay ring buffers hold 500 ms; clamp so an over-range pre-delay
1326 // can't read past the buffer (RingBuffer::read would wrap to a wrong sample).
1328 std::memory_order_relaxed);
1329 }
1330 }
1331
1332 bool commitImpulseResponse(std::vector<T> nextStorage,
1333 int nextLength,
1334 int nextChannels,
1335 double nextSampleRate)
1336 {
1337 if (spec_.sampleRate <= 0 || fftBlockSize_ <= 0)
1338 {
1339 irStorage_.swap(nextStorage);
1340 irLength_ = nextLength;
1341 irChannels_ = nextChannels;
1342 irSampleRate_ = nextSampleRate;
1343 return true;
1344 }
1345
1346 auto candidate = buildBank(nextStorage, nextLength, nextChannels,
1347 nextSampleRate, spec_, fftBlockSize_,
1348 decayScale_.load(std::memory_order_relaxed),
1349 stretch_.load(std::memory_order_relaxed));
1350 const std::uint32_t latency = bankLatency(*candidate);
1351 const auto result = bankPublisher_.publish(
1352 std::move(candidate), latency,
1353 [&]() noexcept {
1354 irStorage_.swap(nextStorage);
1355 irLength_ = nextLength;
1356 irChannels_ = nextChannels;
1357 irSampleRate_ = nextSampleRate;
1358 });
1359 return result == Publisher::PublishResult::published;
1360 }
1361
1362 [[nodiscard]] std::unique_ptr<ConvolverBank> buildBank(
1363 const std::vector<T>& source,
1364 int sourceLength,
1365 int sourceChannels,
1366 double sourceSampleRate,
1367 const AudioSpec& processingSpec,
1368 int fftBlock,
1369 T decayScale,
1370 T stretchRatio) const
1371 {
1372 auto newBank = std::make_unique<ConvolverBank>();
1373 newBank->convolvers.resize(
1374 static_cast<size_t>(processingSpec.numChannels));
1375
1376 // IR shaping controls, always applied to the stored original.
1377 // Stretch works by declaring a scaled source rate and letting the
1378 // resampling stage do the time-scaling (tape-speed semantics).
1379 const double dScale = static_cast<double>(decayScale);
1380 const double stretch = static_cast<double>(stretchRatio);
1381 const bool doShape = std::abs(dScale - 1.0) > 1e-6;
1382 const double effIrRate = sourceSampleRate / std::max(stretch, 0.01);
1383
1384 std::vector<T> shaped; // lazy decay-shaped copy of one IR channel
1385 int shapedCh = -1;
1386 // One decay estimate for the whole IR, so every channel is reshaped
1387 // by the same envelope (per-channel fits differ with each channel's
1388 // direct sound and would pull the channels' decays apart).
1389 DecayEstimate decayFit {};
1390 if (doShape)
1391 decayFit = estimateDecay(source.data(), sourceLength, sourceChannels, sourceSampleRate);
1392
1393 // An IR at another rate (or stretched) is converted offline, time
1394 // aligned, over the whole span the kernel reaches, and scaled by the
1395 // rate ratio: a sampled impulse response scales with the sampling
1396 // period, so a response held at twice the rate carries half the
1397 // weight per sample. The span includes the kernel's ringing BEFORE
1398 // the IR's first sample, which an IR that starts at full level (a
1399 // trimmed recording, a unit impulse) needs: cut off, it takes a
1400 // share of the direct sound's gain with it. Those leading samples
1401 // are kept only where the IR's own leading silence cannot hold
1402 // them, and the dry path is delayed by as many, so dry and wet stay
1403 // aligned and the direct sound falls exactly at getLatency().
1404 const bool convert = std::abs(effIrRate - processingSpec.sampleRate) > 1e-9 * effIrRate;
1405 std::vector<std::vector<T>> converted(static_cast<size_t>(processingSpec.numChannels));
1406 std::vector<int> zeroIndex(static_cast<size_t>(processingSpec.numChannels), 0);
1407 int extra = 0;
1408
1409 for (int ch = 0; ch < processingSpec.numChannels; ++ch)
1410 {
1411 // Pick IR channel: use corresponding channel if available, else mono (ch 0)
1412 const int irCh = (ch < sourceChannels) ? ch : 0;
1413 const T* irData = source.data()
1414 + static_cast<size_t>(irCh)
1415 * static_cast<size_t>(sourceLength);
1416 int irLen = sourceLength;
1417
1418 if (doShape)
1419 {
1420 if (shapedCh != irCh)
1421 {
1422 shaped = shapeDecay(irData, sourceLength, dScale, decayFit);
1423 shapedCh = irCh;
1424 }
1425 if (!shaped.empty())
1426 {
1427 irData = shaped.data();
1428 irLen = static_cast<int>(shaped.size());
1429 }
1430 }
1431
1432 auto& out = converted[static_cast<size_t>(ch)];
1433 if (!convert)
1434 {
1435 out.assign(irData, irData + irLen);
1436 continue;
1437 }
1438 Resampler<T> resampler;
1439 resampler.prepare(effIrRate, processingSpec.sampleRate, Resampler<T>::Quality::High);
1440 const int64_t reach = resampler.getReach();
1441 const int64_t body = static_cast<int64_t>(
1442 std::ceil(static_cast<double>(irLen) * resampler.getRatio()));
1443 out = resampler.processRange(irData, irLen, -reach, body + 2 * reach);
1444 const T scale = static_cast<T>(effIrRate / processingSpec.sampleRate);
1445 for (auto& v : out) v *= scale;
1446 // Leading samples that are exactly zero carry nothing; the ones
1447 // before the IR's first instant that are not become extra delay.
1448 int first = 0;
1449 while (first < static_cast<int>(out.size()) && out[static_cast<size_t>(first)] == T(0)) ++first;
1450 zeroIndex[static_cast<size_t>(ch)] = static_cast<int>(reach);
1451 extra = std::max(extra, static_cast<int>(reach) - first);
1452 while (!out.empty() && out.back() == T(0)) out.pop_back();
1453 }
1454
1455 for (int ch = 0; ch < processingSpec.numChannels; ++ch)
1456 {
1457 auto& conv = newBank->convolvers[static_cast<size_t>(ch)];
1458 const auto& out = converted[static_cast<size_t>(ch)];
1459 const int start = convert ? zeroIndex[static_cast<size_t>(ch)] - extra : 0;
1460 const int len = static_cast<int>(out.size()) - start;
1461 if (len > 0)
1462 conv.prepare(fftBlock, out.data() + start, len,
1464 else
1465 {
1466 const T silence = T(0);
1467 conv.prepare(fftBlock, &silence, 1);
1468 }
1469 }
1470
1471 if (extra > 0)
1472 {
1473 newBank->extraDelay = extra;
1474 newBank->scratchLength = std::max(1, processingSpec.maxBlockSize);
1475 newBank->dryDelay.resize(static_cast<size_t>(processingSpec.numChannels));
1476 for (auto& ring : newBank->dryDelay) ring.prepare(extra + 1);
1477 newBank->dryScratch.assign(static_cast<size_t>(processingSpec.numChannels)
1478 * static_cast<size_t>(newBank->scratchLength), T(0));
1479 }
1480 return newBank;
1481 }
1482
1483 [[nodiscard]] static std::uint32_t bankLatency(
1484 const ConvolverBank& bank) noexcept
1485 {
1486 if (bank.convolvers.empty()) return 0u;
1487 return static_cast<std::uint32_t>(
1488 std::max(0, bank.convolvers.front().getLatency() + bank.extraDelay));
1489 }
1490
1493 {
1494 double beta = 0.0;
1495 int peak = 0;
1496 };
1497
1508 [[nodiscard]] static DecayEstimate estimateDecay(const T* source, int len, int channels,
1509 double rate)
1510 {
1511 DecayEstimate fit {};
1512 if (!source || len < 64 || channels <= 0) return fit;
1513 std::vector<double> energy(static_cast<size_t>(len), 0.0);
1514 double peakMag = 0.0;
1515 for (int ch = 0; ch < channels; ++ch)
1516 {
1517 const T* ir = source + static_cast<size_t>(ch) * static_cast<size_t>(len);
1518 for (int n = 0; n < len; ++n)
1519 {
1520 const double v = static_cast<double>(ir[n]);
1521 energy[static_cast<size_t>(n)] += v * v;
1522 if (std::abs(v) > peakMag) { peakMag = std::abs(v); fit.peak = n; }
1523 }
1524 }
1525 if (peakMag <= 0.0) return fit;
1526 const int start = std::min(len - 1, fit.peak + std::max(1, static_cast<int>(0.005 * rate)));
1527 double total = 0.0;
1528 for (int n = start; n < len; ++n) total += energy[static_cast<size_t>(n)];
1529 if (total <= 1e-30) return fit;
1530
1531 // Schroeder EDC crossings at -5 dB and -25 dB (energy ratios).
1532 constexpr double r5 = 0.31622776601683794; // 10^(-5/10)
1533 constexpr double r25 = 0.0031622776601683794; // 10^(-25/10)
1534 int t5 = -1, t25 = -1;
1535 double tail = total;
1536 for (int n = start; n < len; ++n)
1537 {
1538 const double ratio = tail / total;
1539 if (t5 < 0 && ratio <= r5) t5 = n;
1540 if (ratio <= r25) { t25 = n; break; }
1541 tail -= energy[static_cast<size_t>(n)];
1542 }
1543 if (t5 < 0 || t25 < 0 || t25 - t5 < 32) return fit; // no usable slope
1544
1545 // Amplitude decay rate: the EDC drops 20 dB over (t25 - t5) samples,
1546 // so exp(-beta * t) with beta = ln(10) / (t25 - t5).
1547 fit.beta = 2.302585092994046 / static_cast<double>(t25 - t5);
1548 return fit;
1549 }
1550
1559 [[nodiscard]] std::vector<T> shapeDecay(const T* ir, int len,
1560 double factor, const DecayEstimate& fit) const
1561 {
1562 if (!ir || len < 64 || !(fit.beta > 0.0)) return {};
1563 const int peak = std::min(fit.peak, len - 1);
1564 const double k = fit.beta * (1.0 / factor - 1.0);
1565
1566 std::vector<T> out(static_cast<size_t>(len));
1567 const double gStep = std::exp(-k);
1568 double g = 1.0;
1569 for (int n = 0; n < len; ++n)
1570 {
1571 out[static_cast<size_t>(n)] = (n <= peak)
1572 ? ir[n]
1573 : static_cast<T>(static_cast<double>(ir[n]) * g);
1574 if (n >= peak) g *= gStep;
1575 }
1576
1577 if (factor < 1.0)
1578 {
1579 // Trim where the shaped energy falls below -100 dB of its total:
1580 // the removed stretch is inaudible, and a shorter IR means fewer
1581 // convolution partitions (the CPU saving the shaping is for).
1582 double sTotal = 0.0;
1583 for (const T v : out) sTotal += static_cast<double>(v) * v;
1584 if (sTotal > 1e-30)
1585 {
1586 double sTail = sTotal;
1587 int cut = len;
1588 for (int n = 0; n < len; ++n)
1589 {
1590 if (sTail / sTotal <= 1e-10) { cut = n; break; }
1591 const double v = static_cast<double>(out[static_cast<size_t>(n)]);
1592 sTail -= v * v;
1593 }
1594 cut = std::max(cut, 64);
1595 if (cut < len) out.resize(static_cast<size_t>(cut));
1596 }
1597 }
1598 else if (factor > 1.0)
1599 {
1600 // A raised envelope would end in a cliff at the IR boundary:
1601 // fade the final stretch (up to 20 ms at 48 kHz) with a raised
1602 // cosine so the lengthened tail closes cleanly.
1603 const int fade = std::min(len / 8, 960);
1604 const int start = len - fade;
1605 for (int i = 0; i < fade; ++i)
1606 {
1607 const double w = 0.5 * (1.0 + std::cos(3.141592653589793
1608 * static_cast<double>(i + 1)
1609 / static_cast<double>(fade)));
1610 const size_t idx = static_cast<size_t>(start + i);
1611 out[idx] = static_cast<T>(static_cast<double>(out[idx]) * w);
1612 }
1613 }
1614 return out;
1615 }
1616
1620 int swapFadePos_ = 480;
1621 std::atomic<T> mix_ { T(0.3) };
1622 std::atomic<T> preDelayMs_ { T(0) };
1623 std::atomic<int> preDelaySamples_ { 0 };
1624 std::atomic<T> decayScale_ { T(1) };
1625 std::atomic<T> stretch_ { T(1) };
1626
1627 // IR storage (GUI-thread only: rebuild source of truth)
1628 std::vector<T> irStorage_;
1629 int irLength_ = 0;
1631 double irSampleRate_ = 0;
1632
1634 std::vector<RingBuffer<T>> preDelayBuffers_;
1637 std::vector<T> tailLevels_;
1639};
1640
1641} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
int getNumSamples() const noexcept
Returns the number of samples per channel.
int getNumChannels() const noexcept
Returns the number of channels in this view.
T * getChannel(int ch) const noexcept
Returns a pointer to the sample data for the given channel.
Owning audio buffer with contiguous, 32-byte aligned storage.
AudioBufferView< T, MaxChannels > toView() noexcept
Returns a non-owning mutable view of this buffer. The view's channel capacity is propagated from MaxC...
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.
Real-time partitioned convolution using overlap-save with FFT.
Definition Convolver.h:78
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
Definition DryWetMixer.h:83
void setLatencyCompensation(int samples)
Delays the captured dry signal to compensate for an effect's internal latency (e.g....
void prepare(const AudioSpec &spec)
Allocates the internal dry buffer for the given audio spec.
Windowed-sinc sample rate converter optimized for real-time DSP.
Definition Resampler.h:100
int64_t getReach() const noexcept
How far, in output samples, the kernel reaches before an input sample and after it: processRange() ov...
Definition Resampler.h:369
double getRatio() const noexcept
Returns the conversion ratio (targetRate / sourceRate).
Definition Resampler.h:440
std::vector< T > processRange(const T *input, int inputLength, int64_t firstOutput, int64_t count)
Offline, time-aligned conversion of any span of output samples.
Definition Resampler.h:322
void prepare(double sourceRate, double targetRate, Quality quality=Quality::Normal)
Prepares the resampler for a given rate conversion.
Definition Resampler.h:192
Convolution reverb with IR loading, dry/wet, and pre-delay.
Definition Reverb.h:619
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio through the reverb.
Definition Reverb.h:744
static int calculatePreDelaySamples(const AudioSpec &spec, T preDelayMs) noexcept
Definition Reverb.h:1310
int swapFadePos_
Audio owner: progress of that fade-in.
Definition Reverb.h:1620
DryWetMixer< T > & getMixer()
Direct access to the DryWetMixer (processing thread).
Definition Reverb.h:1081
bool commitImpulseResponse(std::vector< T > nextStorage, int nextLength, int nextChannels, double nextSampleRate)
Definition Reverb.h:1332
std::vector< T > tailLevels_
Audio owner: the dry level per frame of a part.
Definition Reverb.h:1637
void setGate(T thresholdDb) noexcept
Gate on the wet signal (see TailShaper): it closes once the dry signal has stayed thresholdDb under i...
Definition Reverb.h:1021
void setGateHold(T ms) noexcept
Hold of the gate, 0 to 4000 ms (default 100).
Definition Reverb.h:1024
~Reverb() noexcept
Definition Reverb.h:644
bool loadIR(AudioBufferView< const T > ir, double irSampleRate)
Loads a multi-channel IR from memory.
Definition Reverb.h:891
T getDryDip() const noexcept
Definition Reverb.h:1029
int swapFadeLength_
Fade-in after a bank swap (10 ms).
Definition Reverb.h:1619
T getMix() const noexcept
Returns the current mix value.
Definition Reverb.h:1090
std::atomic< int > preDelaySamples_
Definition Reverb.h:1623
static std::uint32_t bankLatency(const ConvolverBank &bank) noexcept
Definition Reverb.h:1483
bool isLoaded() const noexcept
Returns true if an IR has been loaded and applied.
Definition Reverb.h:1084
Reverb()=default
std::vector< T > irStorage_
Definition Reverb.h:1628
void setDryDip(T dB) noexcept
Dips the wet signal under the dry one while it plays (see TailShaper): by up to dB (0 to 48; 0,...
Definition Reverb.h:1014
Reverb(const Reverb &)=delete
void updatePreDelay() noexcept
Definition Reverb.h:1321
std::atomic< T > stretch_
Definition Reverb.h:1625
Reverb(Reverb &&)=delete
int fftBlockSize_
Convolver partition size = engine latency (set in prepare()).
Definition Reverb.h:1618
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
Definition Reverb.h:1131
int calculatePreDelaySamples(const AudioSpec &spec) const noexcept
Definition Reverb.h:1304
T getPreDelay() const noexcept
Returns the current pre-delay in ms.
Definition Reverb.h:1093
std::atomic< T > decayScale_
Definition Reverb.h:1624
T getGateHold() const noexcept
Definition Reverb.h:1031
bool loadIR(const char *wavFilePath)
Loads an impulse response from a WAV file.
Definition Reverb.h:809
std::atomic< T > preDelayMs_
Definition Reverb.h:1622
int getLatency() const noexcept
Returns the convolution latency in samples.
Definition Reverb.h:1108
AudioSpec spec_
Definition Reverb.h:1617
bool loadIR(const T *data, int length, double irSampleRate)
Loads an IR from raw sample data.
Definition Reverb.h:866
static constexpr std::uint32_t publisherGenerationMax
Definition Reverb.h:637
Convolver< T > fallbackConvolver_
Inert engine for getConvolver() with no bank.
Definition Reverb.h:1638
void setStretch(T ratio)
Stretches the loaded IR in time (tape-speed style).
Definition Reverb.h:983
void prepare(const AudioSpec &spec)
Prepares the reverb for processing.
Definition Reverb.h:664
Publisher bankPublisher_
Definition Reverb.h:1633
void setMix(T dryWet) noexcept
Sets the dry/wet mix.
Definition Reverb.h:850
std::vector< RingBuffer< T > > preDelayBuffers_
Definition Reverb.h:1634
std::vector< T > shapeDecay(const T *ir, int len, double factor, const DecayEstimate &fit) const
Returns a decay-scaled copy of one IR channel (see setDecayScale).
Definition Reverb.h:1559
std::vector< uint8_t > getState() const
Serializes the parameter state. The impulse response itself is content (load it with loadIR),...
Definition Reverb.h:1116
TailShaper< T > tail_
Dip and gate of the wet signal.
Definition Reverb.h:1636
Reverb & operator=(Reverb &&)=delete
DryWetMixer< T > mixer_
Definition Reverb.h:1635
std::atomic< T > mix_
Definition Reverb.h:1621
void processPart(ConvolverBank &bank, AudioBufferView< T > buffer, int fadeOutAt, int blockLength) noexcept
One conforming part (at most maxBlockSize samples) of a block.
Definition Reverb.h:1202
std::unique_ptr< ConvolverBank > buildBank(const std::vector< T > &source, int sourceLength, int sourceChannels, double sourceSampleRate, const AudioSpec &processingSpec, int fftBlock, T decayScale, T stretchRatio) const
Definition Reverb.h:1362
void setGateRelease(T ms) noexcept
Release of the gate, 5 to 4000 ms (default 150).
Definition Reverb.h:1027
Reverb & operator=(const Reverb &)=delete
Convolver< T > & getConvolver(int channel=0)
Direct access to a channel's Convolver (GUI thread only).
Definition Reverb.h:1062
T getGate() const noexcept
Definition Reverb.h:1030
static DecayEstimate estimateDecay(const T *source, int len, int channels, double rate)
Estimates the decay rate of a (multichannel) IR.
Definition Reverb.h:1508
void reset() noexcept
Resets the DSP state (convolver tails, pre-delay, mixer). RT-Safe.
Definition Reverb.h:778
T getDecayScale() const noexcept
Returns the current IR decay scale.
Definition Reverb.h:1004
void setDecayScale(T scale)
Scales the decay time (T60) of the loaded IR.
Definition Reverb.h:950
T getGateRelease() const noexcept
Definition Reverb.h:1032
double irSampleRate_
Definition Reverb.h:1631
T getStretch() const noexcept
Returns the current IR stretch ratio.
Definition Reverb.h:1007
void setPreDelay(T ms) noexcept
Sets the pre-delay time in milliseconds.
Definition Reverb.h:920
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
Definition StateBlob.h:171
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
Definition StateBlob.h:214
bool isValid() const noexcept
Definition StateBlob.h:209
uint32_t processorId() const noexcept
Definition StateBlob.h:210
Serializes key/value parameters into a versioned blob.
Definition StateBlob.h:53
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
Definition StateBlob.h:112
void write(const char *key, float value)
Writes a float parameter.
Definition StateBlob.h:71
A dip and a relative gate driven by the dry signal.
Definition TailShaper.h:50
Complete WAV file reader and writer in pure C++20.
Definition WavFile.h:97
AudioFileInfo getInfo() const override
Format of the open file.
Definition WavFile.h:214
bool readSamples(AudioBufferView< float > dest) override
Reads samples from the start of the file into the destination view.
Definition WavFile.h:219
bool openRead(const std::filesystem::path &path) override
Opens a WAV file for reading.
Definition WavFile.h:133
void close() override
Finalizes file headers and releases system handles.
Definition WavFile.h:313
const void * atomicWordAddressForTest(std::size_t index) const noexcept
Definition Reverb.h:419
bool isLoaded() const noexcept
Definition Reverb.h:371
std::uint32_t pinnedTokenForTest() const noexcept
Definition Reverb.h:412
bool hasPending() const noexcept
Definition Reverb.h:334
ReverbBankPublisher(const ReverbBankPublisher &)=delete
ReverbBankPublisher(ReverbBankPublisher &&)=delete
ReverbBankPublisher & operator=(ReverbBankPublisher &&)=delete
Bank * adoptAtBoundary() noexcept
Definition Reverb.h:283
static constexpr std::uint32_t generationForTest(std::uint32_t state) noexcept
Definition Reverb.h:436
std::uint32_t pendingTokenForTest() const noexcept
Definition Reverb.h:406
static constexpr Phase phaseForTest(std::uint32_t state) noexcept
Definition Reverb.h:432
std::uint32_t stateWordForTest(std::size_t index) const noexcept
Definition Reverb.h:402
ReverbBankPublisher & operator=(const ReverbBankPublisher &)=delete
std::size_t residentBanksForTest() const noexcept
Definition Reverb.h:413
std::uint32_t latestTokenForTest() const noexcept
Definition Reverb.h:411
int latency() const noexcept
Definition Reverb.h:377
PublishResult publish(std::unique_ptr< Bank > candidate, std::uint32_t latency, Commit &&commit) noexcept
Definition Reverb.h:174
std::uint32_t activeTokenForTest() const noexcept
Definition Reverb.h:410
Bank * activeBank() const noexcept
Definition Reverb.h:340
static constexpr std::size_t atomicWordCountForTest() noexcept
Definition Reverb.h:428
ReverbBankPublisher() noexcept=default
Main namespace for the DSPark framework.
constexpr uint32_t stateId(const char(&tag)[5]) noexcept
Builds a FOURCC processor id, e.g. dspark::stateId("COMP").
Definition StateBlob.h:672
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
int maxBlockSize
Maximum number of samples per processing block.
Definition AudioSpec.h:53
double sampleRate
Sample rate in Hz.
Definition AudioSpec.h:45
std::vector< RingBuffer< T > > dryDelay
Per channel, extraDelay deep.
Definition Reverb.h:628
std::vector< Convolver< T > > convolvers
Definition Reverb.h:623
std::vector< T > dryScratch
Channel-major, one block per channel.
Definition Reverb.h:629
double beta
0 when the IR has no usable exponential decay
Definition Reverb.h:1494
static constexpr void audioAfterExchange(bool) noexcept
Definition Reverb.h:122
static constexpr void controlScan() noexcept
Definition Reverb.h:126
static constexpr void audioExchange() noexcept
Definition Reverb.h:121
static constexpr void audioStateStore() noexcept
Definition Reverb.h:123
static constexpr void control(ControlPoint) noexcept
Definition Reverb.h:120
static constexpr void controlValidation(bool) noexcept
Definition Reverb.h:125
static constexpr void audioValidation(bool) noexcept
Definition Reverb.h:124