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"
92#include <initializer_list>
136template <
typename Bank,
137 typename Hooks = ReverbPublisherNoopHooks,
138 std::uint32_t GenerationMax = 134217727u>
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");
173 template <
typename Commit>
176 Commit&& commit)
noexcept
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);
184 SlotChoice choice = scanOnce();
185 bool claimedPending =
false;
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)
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)
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)
209 Hooks::controlValidation(reusable);
216 pendingToken_.store(old, std::memory_order_release);
219 choice = { index, generation + 1u,
true,
false };
220 claimedPending =
true;
234 Hooks::control(Hooks::ControlPoint::noCapacity);
238 Hooks::control(Hooks::ControlPoint::afterSlotSelection);
239 auto& slot = slots_[choice.index];
242 const std::uint32_t claimedGeneration = choice.generation - 1u;
243 const bool retired = retireControlOwned(
244 makeToken(claimedGeneration, choice.index));
248 nextGeneration_[choice.index] = choice.generation;
250 std::memory_order_relaxed);
251 if (choice.reclaimsRetired)
252 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
253 slot.bank = std::move(candidate);
255 std::memory_order_release);
256 Hooks::control(Hooks::ControlPoint::afterPublishedStore);
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))
268 assert(
false &&
"Reverb publication ownership invariant");
271 Hooks::control(Hooks::ControlPoint::beforeCommit);
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);
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)
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)
296 Hooks::audioValidation(nextValid);
300 slots_[nextIndex].stateWord.store(
302 std::memory_order_release);
303 Hooks::audioStateStore();
305 const std::uint32_t old = activeToken_;
307 if (old != emptyToken)
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)
314 Hooks::audioValidation(oldValid);
318 slots_[oldIndex].stateWord.store(
320 std::memory_order_release);
321 Hooks::audioStateStore();
327 return activeToken_ == emptyToken
329 : slots_[tokenIndex(activeToken_)].bank.get();
336 return pendingToken_.load(std::memory_order_relaxed) != emptyToken;
342 return activeToken_ == emptyToken
344 : slots_[tokenIndex(activeToken_)].bank.get();
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);
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)
364 Hooks::controlValidation(valid);
366 if (!valid)
return nullptr;
367 pinnedToken_ = latest;
368 return slots_[index].bank.get();
373 return (publicationMetadata_.load(std::memory_order_acquire)
379 return static_cast<int>(publicationMetadata_.load(
380 std::memory_order_acquire) & latencyMask);
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_)
395 std::memory_order_relaxed);
397 nextGeneration_.fill(0u);
404 return slots_[index].stateWord.load(std::memory_order_acquire);
408 return pendingToken_.load(std::memory_order_acquire);
415 std::size_t count = 0;
416 for (
const auto& slot : slots_) count += slot.bank !=
nullptr ? 1u : 0u;
420 std::size_t index)
const noexcept
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_);
434 return statePhase(state);
437 std::uint32_t state)
noexcept
439 return stateGeneration(state);
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;
451 std::unique_ptr<Bank> bank;
452 std::atomic<std::uint32_t> stateWord { 0u };
457 std::size_t index = 0;
458 std::uint32_t generation = 0;
460 bool reclaimsRetired =
false;
463 [[nodiscard]]
static constexpr std::uint32_t makeToken(
464 std::uint32_t generation, std::size_t index)
noexcept
466 return (generation << 2u) |
static_cast<std::uint32_t
>(index);
469 [[nodiscard]]
static constexpr std::size_t tokenIndex(
470 std::uint32_t token)
noexcept
472 return static_cast<std::size_t
>(token & slotMask);
475 [[nodiscard]]
static constexpr std::uint32_t tokenGeneration(
476 std::uint32_t token)
noexcept
481 [[nodiscard]]
static constexpr std::uint32_t encodeState(
482 std::uint32_t generation,
Phase phase)
noexcept
484 return (generation << 3u) |
static_cast<std::uint32_t
>(phase);
487 [[nodiscard]]
static constexpr std::uint32_t stateGeneration(
488 std::uint32_t state)
noexcept
493 [[nodiscard]]
static constexpr Phase statePhase(std::uint32_t state)
noexcept
495 return static_cast<Phase>(state & phaseMask);
498 [[nodiscard]]
static constexpr std::uint32_t packMetadata(
499 std::uint32_t
latency)
noexcept
501 return loadedMask | std::min(
latency, latencyMask);
504 [[nodiscard]] SlotChoice scanOnce() noexcept
506 for (std::size_t offset = 0; offset < slots_.size(); ++offset)
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);
519 const bool pristine = generation == 0u
520 && nextGeneration_[index] == 0u && slot.bank ==
nullptr;
521 Hooks::controlValidation(pristine);
523 if (pristine)
return { index, 1u,
true,
false };
530 const bool generationMatches =
531 nextGeneration_[index] == generation;
532 Hooks::controlValidation(generationMatches);
533 assert(generationMatches);
534 if (!generationMatches)
continue;
536 if (generation >= GenerationMax)
continue;
537 return { index, generation + 1u,
true,
true };
542 bool retireControlOwned(std::uint32_t token)
noexcept
544 const std::size_t index = tokenIndex(token);
545 const std::uint32_t generation = tokenGeneration(token);
546 auto& slot = slots_[index];
548 slot.stateWord.load(std::memory_order_acquire)
550 Hooks::controlValidation(valid);
552 if (!valid)
return false;
554 Hooks::control(Hooks::ControlPoint::beforeOldRetirement);
556 std::memory_order_release);
557 if (token != pinnedToken_)
559 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
565 void quarantineExhaustedRetired() noexcept
567 for (std::size_t index = 0; index < slots_.size(); ++index)
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);
574 || generation < GenerationMax
575 || makeToken(generation, index) == pinnedToken_)
577 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
580 std::memory_order_release);
584 void reclaimIfRetired(std::uint32_t token)
noexcept
586 auto& slot = slots_[tokenIndex(token)];
587 const std::uint32_t state =
588 slot.stateWord.load(std::memory_order_acquire);
591 Hooks::control(Hooks::ControlPoint::beforeOldReclaim);
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;
600 std::uint32_t latestToken_ = emptyToken;
601 std::uint32_t pinnedToken_ = emptyToken;
602 std::array<std::uint32_t, 4> nextGeneration_ {};
603 std::size_t scanStart_ = 0;
617template <FloatType T>
633#if defined(DSPARK_REVERB_TEST_GENERATION_MAX)
635 DSPARK_REVERB_TEST_GENERATION_MAX;
672 const int blockSize = std::clamp(spec.
maxBlockSize, 1, 1 << 20);
674 while (fftBlock < blockSize) fftBlock <<= 1;
683 const int maxDelaySamples =
static_cast<int>(spec.
sampleRate * 0.5) + 1;
684 std::vector<RingBuffer<T>> nextPreDelayBuffers(
686 for (
auto& rb : nextPreDelayBuffers)
687 rb.prepare(maxDelaySamples);
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));
700 mixer_ = std::move(nextMixer);
703 std::memory_order_relaxed);
710 stretch_.load(std::memory_order_relaxed));
711 const std::uint32_t latency =
bankLatency(*candidate);
713 std::move(candidate), latency,
720 mixer_ = std::move(nextMixer);
723 std::memory_order_relaxed);
752 if (!bank || bank->
convolvers.empty())
return;
756 const int nS = buffer.getNumSamples();
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);
784 for (
auto& conv : bank->convolvers)
786 for (
auto& ring : bank->dryDelay)
797#ifndef DSPARK_NO_FILE_IO
816 if (info.numSamples <= 0 || info.numChannels <= 0
817 || info.numSamples > (
static_cast<int64_t
>(1) << 30)
818 || !(info.sampleRate > 0))
825 irBuf.
resize(info.numChannels,
static_cast<int>(info.numSamples));
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)
836 T* dst = nextStorage.data()
837 +
static_cast<size_t>(ch) *
static_cast<size_t>(nextLength);
838 std::copy_n(src, nextLength, dst);
841 nextChannels, info.sampleRate);
852 if (!std::isfinite(dryWet))
return;
853 mix_.store(std::clamp(dryWet, T(0), T(1)), std::memory_order_relaxed);
866 bool loadIR(
const T* data,
int length,
double irSampleRate)
868 if (data ==
nullptr || length <= 0
869 || !std::isfinite(irSampleRate) || !(irSampleRate > 0.0))
872 std::vector<T> nextStorage(data, data + length);
895 if (nextChannels <= 0 || nextLength <= 0
896 || !std::isfinite(irSampleRate) || !(irSampleRate > 0.0))
898 for (
int ch = 0; ch < nextChannels; ++ch)
899 if (ir.
getChannel(ch) ==
nullptr)
return false;
901 std::vector<T> nextStorage(
902 static_cast<size_t>(nextChannels) *
static_cast<size_t>(nextLength));
903 for (
int ch = 0; ch < nextChannels; ++ch)
905 nextStorage.data() +
static_cast<size_t>(ch) *
static_cast<size_t>(nextLength));
907 nextChannels, irSampleRate);
922 if (!std::isfinite(ms))
return;
923 preDelayMs_.store(std::clamp(ms, T(0), T(500)), std::memory_order_relaxed);
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;
957 decayScale_.store(next, std::memory_order_relaxed);
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); });
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;
990 stretch_.store(next, std::memory_order_relaxed);
997 const std::uint32_t latency =
bankLatency(*candidate);
999 std::move(candidate), latency,
1000 [&]()
noexcept {
stretch_.store(next, std::memory_order_relaxed); });
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)];
1090 [[nodiscard]] T
getMix() const noexcept {
return mix_.load(std::memory_order_relaxed); }
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)));
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));
1157 const bool shapeChanged =
1159 || st !=
stretch_.load(std::memory_order_relaxed);
1161 const auto commitParameters = [&]()
noexcept {
1162 mix_.store(mix, std::memory_order_relaxed);
1163 preDelayMs_.store(preDelay, 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);
1185 const std::uint32_t latency =
bankLatency(*candidate);
1187 std::move(candidate), latency, commitParameters);
1188 if (result != Publisher::PublishResult::published)
return false;
1203 int blockLength)
noexcept
1205 const int nCh = std::min(buffer.getNumChannels(),
1206 static_cast<int>(bank.convolvers.size()));
1207 const int nS = buffer.getNumSamples();
1209 if (bank.extraDelay > 0 && nS <= bank.scratchLength)
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)
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)
1226 dst[i] = ring.read(bank.extraDelay);
1228 ptrs[
static_cast<size_t>(ch)] = dst;
1238 T mixVal =
mix_.load(std::memory_order_relaxed);
1243 const bool shaping =
tail_.isActive() && nS <= static_cast<int>(
tailLevels_.size());
1247 for (
int ch = 0; ch < nCh; ++ch)
1249 const T* d = buffer.getChannel(ch);
1250 for (
int i = 0; i < nS; ++i)
1255 for (
int ch = 0; ch < nCh; ++ch)
1257 T* data = buffer.getChannel(ch);
1262 for (
int i = 0; i < nS; ++i)
1265 data[i] = ring.read(preDelSamp);
1269 bank.convolvers[
static_cast<size_t>(ch)].processInPlace(data, nS);
1275 const double scale = 3.141592653589793 /
static_cast<double>(blockLength);
1276 for (
int i = 0; i < nS; ++i)
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;
1284 const double scale = 3.141592653589793 /
static_cast<double>(
swapFadeLength_);
1285 for (
int i = 0; i < nS; ++i)
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;
1295 for (
int i = 0; i < nS; ++i)
1298 for (
int ch = 0; ch < nCh; ++ch) buffer.getChannel(ch)[i] *= g;
1301 mixer_.mixWet(buffer, mixVal);
1307 spec,
preDelayMs_.load(std::memory_order_relaxed));
1311 const AudioSpec& spec, T preDelayMs)
noexcept
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);
1328 std::memory_order_relaxed);
1335 double nextSampleRate)
1346 auto candidate =
buildBank(nextStorage, nextLength, nextChannels,
1349 stretch_.load(std::memory_order_relaxed));
1350 const std::uint32_t latency =
bankLatency(*candidate);
1352 std::move(candidate), latency,
1359 return result == Publisher::PublishResult::published;
1363 const std::vector<T>& source,
1366 double sourceSampleRate,
1370 T stretchRatio)
const
1372 auto newBank = std::make_unique<ConvolverBank>();
1373 newBank->convolvers.resize(
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);
1384 std::vector<T> shaped;
1391 decayFit =
estimateDecay(source.data(), sourceLength, sourceChannels, sourceSampleRate);
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);
1409 for (
int ch = 0; ch < processingSpec.
numChannels; ++ch)
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;
1420 if (shapedCh != irCh)
1422 shaped =
shapeDecay(irData, sourceLength, dScale, decayFit);
1425 if (!shaped.empty())
1427 irData = shaped.data();
1428 irLen =
static_cast<int>(shaped.size());
1432 auto& out = converted[
static_cast<size_t>(ch)];
1435 out.assign(irData, irData + irLen);
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;
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();
1455 for (
int ch = 0; ch < processingSpec.
numChannels; ++ch)
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;
1462 conv.prepare(fftBlock, out.data() + start, len,
1466 const T silence = T(0);
1467 conv.prepare(fftBlock, &silence, 1);
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));
1486 if (bank.convolvers.empty())
return 0u;
1487 return static_cast<std::uint32_t
>(
1488 std::max(0, bank.convolvers.front().getLatency() + bank.extraDelay));
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)
1517 const T* ir = source +
static_cast<size_t>(ch) *
static_cast<size_t>(len);
1518 for (
int n = 0; n < len; ++n)
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; }
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)));
1528 for (
int n = start; n < len; ++n) total += energy[static_cast<size_t>(n)];
1529 if (total <= 1e-30)
return fit;
1532 constexpr double r5 = 0.31622776601683794;
1533 constexpr double r25 = 0.0031622776601683794;
1534 int t5 = -1, t25 = -1;
1535 double tail = total;
1536 for (
int n = start; n < len; ++n)
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)];
1543 if (t5 < 0 || t25 < 0 || t25 - t5 < 32)
return fit;
1547 fit.beta = 2.302585092994046 /
static_cast<double>(t25 - t5);
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);
1566 std::vector<T> out(
static_cast<size_t>(len));
1567 const double gStep = std::exp(-k);
1569 for (
int n = 0; n < len; ++n)
1571 out[
static_cast<size_t>(n)] = (n <= peak)
1573 :
static_cast<T
>(
static_cast<double>(ir[n]) * g);
1574 if (n >= peak) g *= gStep;
1582 double sTotal = 0.0;
1583 for (
const T v : out) sTotal +=
static_cast<double>(v) * v;
1586 double sTail = sTotal;
1588 for (
int n = 0; n < len; ++n)
1590 if (sTail / sTotal <= 1e-10) { cut = n;
break; }
1591 const double v =
static_cast<double>(out[
static_cast<size_t>(n)]);
1594 cut = std::max(cut, 64);
1595 if (cut < len) out.resize(
static_cast<size_t>(cut));
1598 else if (factor > 1.0)
1603 const int fade = std::min(len / 8, 960);
1604 const int start = len - fade;
1605 for (
int i = 0; i < fade; ++i)
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);
Non-owning view over audio channel data.
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.
Pre-allocated, SIMD-friendly dry/wet blender for real-time audio.
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.
int64_t getReach() const noexcept
How far, in output samples, the kernel reaches before an input sample and after it: processRange() ov...
double getRatio() const noexcept
Returns the conversion ratio (targetRate / sourceRate).
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.
void prepare(double sourceRate, double targetRate, Quality quality=Quality::Normal)
Prepares the resampler for a given rate conversion.
Convolution reverb with IR loading, dry/wet, and pre-delay.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes audio through the reverb.
static int calculatePreDelaySamples(const AudioSpec &spec, T preDelayMs) noexcept
int swapFadePos_
Audio owner: progress of that fade-in.
DryWetMixer< T > & getMixer()
Direct access to the DryWetMixer (processing thread).
bool commitImpulseResponse(std::vector< T > nextStorage, int nextLength, int nextChannels, double nextSampleRate)
std::vector< T > tailLevels_
Audio owner: the dry level per frame of a part.
void setGate(T thresholdDb) noexcept
Gate on the wet signal (see TailShaper): it closes once the dry signal has stayed thresholdDb under i...
void setGateHold(T ms) noexcept
Hold of the gate, 0 to 4000 ms (default 100).
bool loadIR(AudioBufferView< const T > ir, double irSampleRate)
Loads a multi-channel IR from memory.
T getDryDip() const noexcept
int swapFadeLength_
Fade-in after a bank swap (10 ms).
T getMix() const noexcept
Returns the current mix value.
std::atomic< int > preDelaySamples_
static std::uint32_t bankLatency(const ConvolverBank &bank) noexcept
bool isLoaded() const noexcept
Returns true if an IR has been loaded and applied.
std::vector< T > irStorage_
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,...
Reverb(const Reverb &)=delete
void updatePreDelay() noexcept
std::atomic< T > stretch_
int fftBlockSize_
Convolver partition size = engine latency (set in prepare()).
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
int calculatePreDelaySamples(const AudioSpec &spec) const noexcept
T getPreDelay() const noexcept
Returns the current pre-delay in ms.
std::atomic< T > decayScale_
T getGateHold() const noexcept
bool loadIR(const char *wavFilePath)
Loads an impulse response from a WAV file.
std::atomic< T > preDelayMs_
int getLatency() const noexcept
Returns the convolution latency in samples.
bool loadIR(const T *data, int length, double irSampleRate)
Loads an IR from raw sample data.
static constexpr std::uint32_t publisherGenerationMax
Convolver< T > fallbackConvolver_
Inert engine for getConvolver() with no bank.
void setStretch(T ratio)
Stretches the loaded IR in time (tape-speed style).
void prepare(const AudioSpec &spec)
Prepares the reverb for processing.
void setMix(T dryWet) noexcept
Sets the dry/wet mix.
std::vector< RingBuffer< T > > preDelayBuffers_
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).
std::vector< uint8_t > getState() const
Serializes the parameter state. The impulse response itself is content (load it with loadIR),...
TailShaper< T > tail_
Dip and gate of the wet signal.
Reverb & operator=(Reverb &&)=delete
void processPart(ConvolverBank &bank, AudioBufferView< T > buffer, int fadeOutAt, int blockLength) noexcept
One conforming part (at most maxBlockSize samples) of a block.
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
void setGateRelease(T ms) noexcept
Release of the gate, 5 to 4000 ms (default 150).
Reverb & operator=(const Reverb &)=delete
Convolver< T > & getConvolver(int channel=0)
Direct access to a channel's Convolver (GUI thread only).
T getGate() const noexcept
static DecayEstimate estimateDecay(const T *source, int len, int channels, double rate)
Estimates the decay rate of a (multichannel) IR.
void reset() noexcept
Resets the DSP state (convolver tails, pre-delay, mixer). RT-Safe.
T getDecayScale() const noexcept
Returns the current IR decay scale.
void setDecayScale(T scale)
Scales the decay time (T60) of the loaded IR.
T getGateRelease() const noexcept
T getStretch() const noexcept
Returns the current IR stretch ratio.
void setPreDelay(T ms) noexcept
Sets the pre-delay time in milliseconds.
Tolerant reader: missing keys yield defaults, unknown keys are skipped.
float read(const char *key, float defaultValue) const
Reads a float, or defaultValue when the key is absent.
bool isValid() const noexcept
uint32_t processorId() const noexcept
Serializes key/value parameters into a versioned blob.
std::vector< uint8_t > blob() const
Finalizes and returns the blob.
void write(const char *key, float value)
Writes a float parameter.
A dip and a relative gate driven by the dry signal.
Complete WAV file reader and writer in pure C++20.
AudioFileInfo getInfo() const override
Format of the open file.
bool readSamples(AudioBufferView< float > dest) override
Reads samples from the start of the file into the destination view.
bool openRead(const std::filesystem::path &path) override
Opens a WAV file for reading.
void close() override
Finalizes file headers and releases system handles.
const void * atomicWordAddressForTest(std::size_t index) const noexcept
bool isLoaded() const noexcept
Bank * pinLatest() noexcept
std::uint32_t pinnedTokenForTest() const noexcept
bool hasPending() const noexcept
ReverbBankPublisher(const ReverbBankPublisher &)=delete
ReverbBankPublisher(ReverbBankPublisher &&)=delete
ReverbBankPublisher & operator=(ReverbBankPublisher &&)=delete
Bank * adoptAtBoundary() noexcept
static constexpr std::uint32_t generationForTest(std::uint32_t state) noexcept
std::uint32_t pendingTokenForTest() const noexcept
static constexpr Phase phaseForTest(std::uint32_t state) noexcept
std::uint32_t stateWordForTest(std::size_t index) const noexcept
ReverbBankPublisher & operator=(const ReverbBankPublisher &)=delete
std::size_t residentBanksForTest() const noexcept
std::uint32_t latestTokenForTest() const noexcept
int latency() const noexcept
PublishResult publish(std::unique_ptr< Bank > candidate, std::uint32_t latency, Commit &&commit) noexcept
std::uint32_t activeTokenForTest() const noexcept
Bank * activeBank() const noexcept
static constexpr std::size_t atomicWordCountForTest() noexcept
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").
Describes the audio environment for a DSP processor.
constexpr bool isValid() const noexcept
Checks if the specification contains valid, processable parameters.
int numChannels
Number of audio channels (e.g., 1 = mono, 2 = stereo).
int maxBlockSize
Maximum number of samples per processing block.
double sampleRate
Sample rate in Hz.
std::vector< RingBuffer< T > > dryDelay
Per channel, extraDelay deep.
std::vector< Convolver< T > > convolvers
std::vector< T > dryScratch
Channel-major, one block per channel.
double beta
0 when the IR has no usable exponential decay
static constexpr void audioAfterExchange(bool) noexcept
static constexpr void controlScan() noexcept
static constexpr void audioExchange() noexcept
static constexpr void audioStateStore() noexcept
static constexpr void control(ControlPoint) noexcept
static constexpr void controlValidation(bool) noexcept
static constexpr void audioValidation(bool) noexcept