DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SpectralFreeze.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
29#include "../Core/AudioBuffer.h"
30#include "../Core/AudioSpec.h"
31#include "../Core/DspMath.h"
32#include "../Core/SpectralProcessor.h"
33#include "../Core/StateBlob.h"
34
35#include <algorithm>
36#include <array>
37#include <atomic>
38#include <cmath>
39#include <cstddef>
40#include <cstdint>
41#include <limits>
42#include <numbers>
43#include <utility>
44#include <vector>
45
46#if !defined(DSPARK_NO_EXCEPTIONS)
47#include <stdexcept>
48#endif
49
50namespace dspark {
51
57template <FloatType T>
58class SpectralFreeze final
59{
60public:
62 enum class PhaseMode : std::uint8_t { Tonal, Diffuse };
63
72 void prepare(const AudioSpec& spec, int fftSize = 2048, int hopSize = 0)
73 {
74 if (!validSpec(spec)) return;
75
76 const int newFftSize = sanitizeFftSize(fftSize);
77 const int newHopSize = sanitizeHopSize(newFftSize, hopSize);
78 const int newBins = newFftSize / 2 + 1;
79 const int channels = spec.numChannels;
80
81 // Build the complete replacement off to the side. A valid prepare is
82 // setup-only; if an allocation throws, the prior running instance has
83 // not been partially resized.
84 SpectralProcessor<T> nextProcessor;
85 nextProcessor.prepare(spec, newFftSize, newHopSize);
86
87 const std::size_t channelBins = checkedProduct(
88 static_cast<std::size_t>(channels), static_cast<std::size_t>(newBins));
89 const std::size_t complexChannelBins = checkedProduct(channelBins, 2u);
90
91 std::vector<T> nextScratch(checkedProduct(
92 static_cast<std::size_t>(channels),
93 static_cast<std::size_t>(spec.maxBlockSize)), T(0));
94 std::vector<T> nextRaw(checkedProduct(complexChannelBins, 3u), T(0));
95 std::vector<T> nextMagnitude(channelBins, T(0));
96 std::vector<T> nextCapturedPhase(channelBins, T(0));
97 std::vector<T> nextFrozenPhase(channelBins, T(0));
98 std::vector<T> nextPower(static_cast<std::size_t>(newBins), T(0));
99 std::vector<T> nextOmega(static_cast<std::size_t>(newBins), T(0));
100 std::vector<T> nextOmegaImag(static_cast<std::size_t>(newBins), T(0));
101 std::vector<std::uint32_t> nextActive(
102 static_cast<std::size_t>(newBins), 0u);
103 std::vector<std::uint32_t> nextPeak(
104 static_cast<std::size_t>(newBins), 0u);
105 std::vector<std::uint32_t> nextRegion(
106 static_cast<std::size_t>(newBins), 0u);
107
108 processor_ = std::move(nextProcessor);
109 scratch_ = std::move(nextScratch);
110 rawSpectra_ = std::move(nextRaw);
111 capturedMagnitude_ = std::move(nextMagnitude);
112 capturedPhase_ = std::move(nextCapturedPhase);
113 frozenPhase_ = std::move(nextFrozenPhase);
114 binPower_ = std::move(nextPower);
115 omega_ = std::move(nextOmega);
116 omegaImag_ = std::move(nextOmegaImag);
117 active_ = std::move(nextActive);
118 peak_ = std::move(nextPeak);
119 regionPeak_ = std::move(nextRegion);
120
121 spec_ = spec;
122 fftSize_ = newFftSize;
123 hopSize_ = newHopSize;
124 numBins_ = newBins;
125 prepared_ = true;
126 rebuildScratchPointers();
127 clearStreamState(false);
128 }
129
134 void reset() noexcept
135 {
136 if (!prepared_) return;
137 clearStreamState(true);
138 }
139
141 void setFrozen(bool frozen) noexcept
142 {
143 if (frozen)
144 requested_.fetch_or(kFrozenBit, std::memory_order_relaxed);
145 else
146 requested_.fetch_and(~kFrozenBit, std::memory_order_relaxed);
147 }
148
150 [[nodiscard]] bool isFrozen() const noexcept
151 {
152 return (requested_.load(std::memory_order_relaxed) & kFrozenBit) != 0u;
153 }
154
159 void setPhaseMode(PhaseMode mode) noexcept
160 {
161 if (mode == PhaseMode::Diffuse)
162 requested_.fetch_or(kDiffuseBit, std::memory_order_relaxed);
163 else
164 requested_.fetch_and(~kDiffuseBit, std::memory_order_relaxed);
165 }
166
168 [[nodiscard]] PhaseMode getPhaseMode() const noexcept
169 {
170 return (requested_.load(std::memory_order_relaxed) & kDiffuseBit) != 0u
173 }
174
178 [[nodiscard]] std::vector<uint8_t> getState() const
179 {
180 StateWriter w(stateId("SFRZ"), 1);
181 w.write("frozen", isFrozen());
182 w.write("diffuse", getPhaseMode() == PhaseMode::Diffuse);
183 return w.blob();
184 }
185
189 bool setState(const uint8_t* data, size_t size)
190 {
191 StateReader r(data, size);
192 if (!r.isValid() || r.processorId() != stateId("SFRZ")) return false;
193 setFrozen(r.read("frozen", false));
194 setPhaseMode(r.read("diffuse", false) ? PhaseMode::Diffuse : PhaseMode::Tonal);
195 return true;
196 }
197
199 [[nodiscard]] int getLatency() const noexcept
200 {
201 return prepared_ ? fftSize_ : 0;
202 }
203
205 [[nodiscard]] int getFFTSize() const noexcept
206 {
207 return prepared_ ? fftSize_ : 0;
208 }
209
211 [[nodiscard]] int getHopSize() const noexcept
212 {
213 return prepared_ ? hopSize_ : 0;
214 }
215
217 [[nodiscard]] int getTransitionSamples() const noexcept
218 {
219 return prepared_ ? fftSize_ : 0;
220 }
221
229 void processBlock(AudioBufferView<T> buffer) noexcept
230 {
231 if (!prepared_ || buffer.getNumSamples() <= 0) return;
232
233 const int runtimeChannels = buffer.getNumChannels();
234 const int processedChannels = std::min(runtimeChannels, spec_.numChannels);
235 const int totalSamples = buffer.getNumSamples();
236
237 int offset = 0;
238 while (offset < totalSamples)
239 {
240 const int block = std::min(spec_.maxBlockSize, totalSamples - offset);
241
242 for (int ch = 0; ch < spec_.numChannels; ++ch)
243 {
244 T* const work = scratchChannels_[static_cast<std::size_t>(ch)];
245 if (ch < processedChannels && buffer.getChannel(ch) != nullptr)
246 {
247 const T* const source = buffer.getChannel(ch) + offset;
248 for (int i = 0; i < block; ++i)
249 work[i] = std::isfinite(source[i]) ? source[i] : T(0);
250 }
251 else
252 {
253 std::fill_n(work, block, T(0));
254 }
255 }
256
257 AudioBufferView<T> workView(scratchChannels_.data(),
258 spec_.numChannels, block);
259 auto callback = [this](T* spectrum, int bins) noexcept {
260 processSpectrum(spectrum, bins);
261 };
262 processor_.processBlock(workView, callback);
263
264 for (int ch = 0; ch < processedChannels; ++ch)
265 {
266 T* const destination = buffer.getChannel(ch);
267 if (destination == nullptr) continue;
268 const T* const work = scratchChannels_[static_cast<std::size_t>(ch)];
269 for (int i = 0; i < block; ++i)
270 destination[offset + i] = std::isfinite(work[i]) ? work[i] : T(0);
271 }
272
273 offset += block;
274 }
275 }
276
277private:
278 static constexpr std::uint32_t kFrozenBit = 1u;
279 static constexpr std::uint32_t kDiffuseBit = 2u;
280 static constexpr int kMinFftSize = 256;
281 static constexpr int kMaxFftSize = 32768;
282 static constexpr int kMaxBlockSize = 65536;
283 static constexpr int kMaxChannels = 16;
284 static_assert(std::atomic<std::uint32_t>::is_always_lock_free);
285
286 [[nodiscard]] static bool validSpec(const AudioSpec& spec) noexcept
287 {
288 return std::isfinite(spec.sampleRate) && spec.sampleRate > 0.0
289 && spec.maxBlockSize >= 1 && spec.maxBlockSize <= kMaxBlockSize
290 && spec.numChannels >= 1 && spec.numChannels <= kMaxChannels;
291 }
292
293 [[nodiscard]] static int sanitizeFftSize(int requested) noexcept
294 {
295 requested = std::clamp(requested, kMinFftSize, kMaxFftSize);
296 int result = kMinFftSize;
297 while (result < requested) result <<= 1;
298 return result;
299 }
300
301 [[nodiscard]] static int sanitizeHopSize(int fftSize, int requested) noexcept
302 {
303 if (requested == fftSize / 8 || requested == fftSize / 4
304 || requested == fftSize / 2)
305 return requested;
306 return fftSize / 4;
307 }
308
309 [[nodiscard]] static std::size_t checkedProduct(std::size_t a,
310 std::size_t b)
311 {
312 // All public dimensions are tightly capped; this guard documents the
313 // allocation arithmetic and remains valid if the caps later change.
314 if (a != 0u && b > std::numeric_limits<std::size_t>::max() / a)
315 {
316#if defined(DSPARK_NO_EXCEPTIONS)
317 return 0u;
318#else
319 throw std::length_error("SpectralFreeze allocation size overflow");
320#endif
321 }
322 return a * b;
323 }
324
325 void rebuildScratchPointers() noexcept
326 {
327 scratchChannels_.fill(nullptr);
328 for (int ch = 0; ch < spec_.numChannels; ++ch)
329 {
330 scratchChannels_[static_cast<std::size_t>(ch)] = scratch_.data()
331 + static_cast<std::size_t>(ch)
332 * static_cast<std::size_t>(spec_.maxBlockSize);
333 }
334 }
335
336 void clearStreamState(bool resetProcessor) noexcept
337 {
338 if (resetProcessor) processor_.reset();
339 std::fill(scratch_.begin(), scratch_.end(), T(0));
340 std::fill(rawSpectra_.begin(), rawSpectra_.end(), T(0));
341 std::fill(capturedMagnitude_.begin(), capturedMagnitude_.end(), T(0));
342 std::fill(capturedPhase_.begin(), capturedPhase_.end(), T(0));
343 std::fill(frozenPhase_.begin(), frozenPhase_.end(), T(0));
344 std::fill(binPower_.begin(), binPower_.end(), T(0));
345 std::fill(omega_.begin(), omega_.end(), T(0));
346 std::fill(omegaImag_.begin(), omegaImag_.end(), T(0));
347 std::fill(active_.begin(), active_.end(), 0u);
348 std::fill(peak_.begin(), peak_.end(), 0u);
349 std::fill(regionPeak_.begin(), regionPeak_.end(), 0u);
350
351 olderBank_ = 0;
352 latestBank_ = 1;
353 currentBank_ = 2;
354 completedFrames_ = 0;
355 callbackChannel_ = 0;
356 q_ = 0;
357 frameQ_ = 0;
358 frameRequestWord_ = 0u;
359 captured_ = false;
360 capturedMode_ = PhaseMode::Tonal;
361 magnitudeFloor_ = T(0);
362 nextDiffuseGeneration_ = 0u;
363 diffuseGeneration_ = 0u;
364 diffuseFrame_ = 0u;
365 tonalAdvanceCount_ = 0u;
366 }
367
368 [[nodiscard]] std::size_t rawOffset(int bank, int channel) const noexcept
369 {
370 return (static_cast<std::size_t>(bank)
371 * static_cast<std::size_t>(spec_.numChannels)
372 + static_cast<std::size_t>(channel))
373 * static_cast<std::size_t>(numBins_ * 2);
374 }
375
376 [[nodiscard]] std::size_t channelBinOffset(int channel) const noexcept
377 {
378 return static_cast<std::size_t>(channel)
379 * static_cast<std::size_t>(numBins_);
380 }
381
382 [[nodiscard]] static T principalArgument(T phase) noexcept
383 {
384 constexpr T p = std::numbers::pi_v<T>;
385 constexpr T tau = T(2) * p;
386 T wrapped = std::fmod(phase + p, tau);
387 if (wrapped < T(0)) wrapped += tau;
388 return wrapped - p;
389 }
390
391 [[nodiscard]] static T phaseOf(T real, T imag) noexcept
392 {
393 return std::atan2(imag, real);
394 }
395
396 [[nodiscard]] static T safeMagnitude(T real, T imag) noexcept
397 {
398 return std::hypot(real, imag);
399 }
400
401 void processSpectrum(T* spectrum, int bins) noexcept
402 {
403 if (callbackChannel_ == 0) beginFrame();
404
405 const int channel = callbackChannel_;
406 T* const raw = rawSpectra_.data() + rawOffset(currentBank_, channel);
407 const int usableBins = std::min(bins, numBins_);
408 for (int k = 0; k < usableBins; ++k)
409 {
410 T real = spectrum[2 * k];
411 T imag = spectrum[2 * k + 1];
412 if (!std::isfinite(real) || !std::isfinite(imag))
413 {
414 real = T(0);
415 imag = T(0);
416 spectrum[2 * k] = T(0);
417 spectrum[2 * k + 1] = T(0);
418 }
419 raw[2 * k] = real;
420 raw[2 * k + 1] = imag;
421 }
422
423 if (frameQ_ > 0 && captured_)
424 blendFrozenSpectrum(spectrum, channel);
425
426 ++callbackChannel_;
427 if (callbackChannel_ == spec_.numChannels)
428 {
429 callbackChannel_ = 0;
430 completeFrame();
431 }
432 }
433
434 void beginFrame() noexcept
435 {
436 // This is the audio owner's single requested-control load for the
437 // complete all-channel frame.
438 frameRequestWord_ = requested_.load(std::memory_order_relaxed);
439
440 if (q_ == 0)
441 {
442 if ((frameRequestWord_ & kFrozenBit) == 0u)
443 {
444 captured_ = false;
445 }
446 else if (!captured_ && completedFrames_ >= 2)
447 {
448 capturedMode_ = (frameRequestWord_ & kDiffuseBit) != 0u
450 : PhaseMode::Tonal;
451 captureLatestFrame();
452 captured_ = true;
453
454 if (capturedMode_ == PhaseMode::Tonal)
455 advanceTonalPhase();
456 else
457 diffuseFrame_ = 0u;
458 }
459 }
460
461 frameQ_ = q_;
462 if (frameQ_ > 0 && captured_
463 && capturedMode_ == PhaseMode::Diffuse)
464 prepareDiffuseFrame();
465 }
466
467 void completeFrame() noexcept
468 {
469 const int recycled = olderBank_;
470 olderBank_ = latestBank_;
471 latestBank_ = currentBank_;
472 currentBank_ = recycled;
473 completedFrames_ = std::min(2, completedFrames_ + 1);
474
475 if (!captured_) return;
476
477 if ((frameRequestWord_ & kFrozenBit) != 0u)
478 {
479 if (q_ < fftSize_ / hopSize_) ++q_;
480 }
481 else if (q_ > 0)
482 {
483 --q_;
484 }
485
486 if (q_ == 0 && (frameRequestWord_ & kFrozenBit) == 0u)
487 {
488 captured_ = false;
489 return;
490 }
491
492 if (capturedMode_ == PhaseMode::Tonal)
493 advanceTonalPhase();
494 else if (frameQ_ > 0)
495 ++diffuseFrame_;
496 }
497
498 void captureLatestFrame() noexcept
499 {
500 std::fill(active_.begin(), active_.end(), 0u);
501 std::fill(peak_.begin(), peak_.end(), 0u);
502 std::fill(regionPeak_.begin(), regionPeak_.end(), 0u);
503 std::fill(binPower_.begin(), binPower_.end(), T(0));
504 std::fill(omega_.begin(), omega_.end(), T(0));
505
506 long double globalScale = 0.0L;
507 for (int ch = 0; ch < spec_.numChannels; ++ch)
508 {
509 const T* const latest = rawSpectra_.data() + rawOffset(latestBank_, ch);
510 for (int k = 0; k < numBins_; ++k)
511 {
512 globalScale = std::max(globalScale,
513 std::abs(static_cast<long double>(latest[2 * k])));
514 globalScale = std::max(globalScale,
515 std::abs(static_cast<long double>(latest[2 * k + 1])));
516 }
517 }
518
519 long double maxPower = 0.0L;
520 if (globalScale > 0.0L)
521 {
522 for (int k = 0; k < numBins_; ++k)
523 {
524 long double power = 0.0L;
525 for (int ch = 0; ch < spec_.numChannels; ++ch)
526 {
527 const T* const latest = rawSpectra_.data()
528 + rawOffset(latestBank_, ch);
529 const long double real =
530 static_cast<long double>(latest[2 * k]) / globalScale;
531 const long double imag =
532 static_cast<long double>(latest[2 * k + 1]) / globalScale;
533 power += real * real + imag * imag;
534 }
535 binPower_[static_cast<std::size_t>(k)] = static_cast<T>(power);
536 maxPower = std::max(maxPower, power);
537 }
538 }
539
540 const long double epsilon =
541 static_cast<long double>(std::numeric_limits<T>::epsilon());
542 const long double minimumNormal =
543 static_cast<long double>(std::numeric_limits<T>::min());
544 const long double minimumMagnitude = std::sqrt(minimumNormal);
545 long double normalizedPowerFloor = 0.0L;
546 if (globalScale > 0.0L)
547 {
548 normalizedPowerFloor = 64.0L * epsilon * maxPower;
549 const long double relativeMagnitudeFloor = globalScale
550 * std::sqrt(normalizedPowerFloor);
551 magnitudeFloor_ = static_cast<T>(std::max(
552 relativeMagnitudeFloor, minimumMagnitude));
553 }
554 else
555 {
556 magnitudeFloor_ = static_cast<T>(minimumMagnitude);
557 }
558
559 const long double normalizedMagnitudeFloor =
560 std::sqrt(normalizedPowerFloor);
561 for (int k = 1; k < numBins_ - 1; ++k)
562 {
563 const long double normalizedMagnitude = std::sqrt(
564 static_cast<long double>(binPower_[static_cast<std::size_t>(k)]));
565 const long double rawMagnitude = globalScale * normalizedMagnitude;
566 active_[static_cast<std::size_t>(k)] =
567 normalizedMagnitude > normalizedMagnitudeFloor
568 && rawMagnitude > minimumMagnitude
569 ? 1u
570 : 0u;
571 }
572
573 for (int ch = 0; ch < spec_.numChannels; ++ch)
574 {
575 const T* const latest = rawSpectra_.data() + rawOffset(latestBank_, ch);
576 const std::size_t base = channelBinOffset(ch);
577 capturedMagnitude_[base] = latest[0];
578 capturedPhase_[base] = T(1);
579 frozenPhase_[base] = T(0);
580 const int nyquist = numBins_ - 1;
581 capturedMagnitude_[base + static_cast<std::size_t>(nyquist)] =
582 latest[2 * nyquist];
583 capturedPhase_[base + static_cast<std::size_t>(nyquist)] = T(1);
584 frozenPhase_[base + static_cast<std::size_t>(nyquist)] = T(0);
585
586 for (int k = 1; k < nyquist; ++k)
587 {
588 const std::size_t index = base + static_cast<std::size_t>(k);
589 const T magnitude = active_[static_cast<std::size_t>(k)] != 0u
590 ? safeMagnitude(latest[2 * k], latest[2 * k + 1])
591 : T(0);
592 capturedMagnitude_[index] = magnitude;
593 if (magnitude > T(0))
594 {
595 capturedPhase_[index] = latest[2 * k] / magnitude;
596 frozenPhase_[index] = latest[2 * k + 1] / magnitude;
597 }
598 else
599 {
600 capturedPhase_[index] = T(1);
601 frozenPhase_[index] = T(0);
602 }
603 }
604 }
605
606 if (capturedMode_ == PhaseMode::Tonal)
607 buildTonalRegions();
608
609 diffuseGeneration_ = nextDiffuseGeneration_++;
610 diffuseFrame_ = 0u;
611 tonalAdvanceCount_ = 0u;
612 }
613
614 void buildTonalRegions() noexcept
615 {
616 int peakCount = 0;
617 for (int k = 1; k < numBins_ - 1; ++k)
618 {
619 const std::size_t index = static_cast<std::size_t>(k);
620 if (active_[index] != 0u
621 && binPower_[index] > binPower_[index - 1u]
622 && binPower_[index] >= binPower_[index + 1u])
623 {
624 peak_[index] = 1u;
625 ++peakCount;
626 }
627 }
628
629 if (peakCount == 0)
630 {
631 for (int k = 1; k < numBins_ - 1; ++k)
632 {
633 const std::size_t index = static_cast<std::size_t>(k);
634 if (active_[index] != 0u)
635 {
636 peak_[index] = 1u;
637 regionPeak_[index] = static_cast<std::uint32_t>(k);
638 }
639 }
640 }
641 else
642 {
643 int currentPeak = -1;
644 int nextPeak = -1;
645 for (int k = 1; k < numBins_ - 1; ++k)
646 {
647 if (peak_[static_cast<std::size_t>(k)] != 0u)
648 {
649 currentPeak = k;
650 break;
651 }
652 }
653 for (int k = currentPeak + 1; k < numBins_ - 1; ++k)
654 {
655 if (peak_[static_cast<std::size_t>(k)] != 0u)
656 {
657 nextPeak = k;
658 break;
659 }
660 }
661
662 for (int k = 1; k < numBins_ - 1; ++k)
663 {
664 if (active_[static_cast<std::size_t>(k)] == 0u) continue;
665 while (nextPeak >= 0 && k > (currentPeak + nextPeak) / 2)
666 {
667 currentPeak = nextPeak;
668 nextPeak = -1;
669 for (int p = currentPeak + 1; p < numBins_ - 1; ++p)
670 {
671 if (peak_[static_cast<std::size_t>(p)] != 0u)
672 {
673 nextPeak = p;
674 break;
675 }
676 }
677 }
678 regionPeak_[static_cast<std::size_t>(k)] =
679 static_cast<std::uint32_t>(currentPeak);
680 }
681 }
682
683 for (int p = 1; p < numBins_ - 1; ++p)
684 {
685 if (peak_[static_cast<std::size_t>(p)] == 0u) continue;
686
687 long double binScale = 0.0L;
688 for (int ch = 0; ch < spec_.numChannels; ++ch)
689 {
690 const T* const latest = rawSpectra_.data()
691 + rawOffset(latestBank_, ch);
692 binScale = std::max(binScale,
693 std::abs(static_cast<long double>(latest[2 * p])));
694 binScale = std::max(binScale,
695 std::abs(static_cast<long double>(latest[2 * p + 1])));
696 }
697
698 long double sumWeight = 0.0L;
699 long double realResidual = 0.0L;
700 long double imagResidual = 0.0L;
701 const long double nominal = 2.0L * std::numbers::pi_v<long double>
702 * static_cast<long double>(p) * static_cast<long double>(hopSize_)
703 / static_cast<long double>(fftSize_);
704
705 if (binScale > 0.0L)
706 {
707 for (int ch = 0; ch < spec_.numChannels; ++ch)
708 {
709 const T* const latest = rawSpectra_.data()
710 + rawOffset(latestBank_, ch);
711 const T* const older = rawSpectra_.data()
712 + rawOffset(olderBank_, ch);
713 const long double real =
714 static_cast<long double>(latest[2 * p]) / binScale;
715 const long double imag =
716 static_cast<long double>(latest[2 * p + 1]) / binScale;
717 const long double weight = real * real + imag * imag;
718 const long double latestPhase = std::atan2(
719 static_cast<long double>(latest[2 * p + 1]),
720 static_cast<long double>(latest[2 * p]));
721 const long double olderPhase = std::atan2(
722 static_cast<long double>(older[2 * p + 1]),
723 static_cast<long double>(older[2 * p]));
724 const T residual = principalArgument(static_cast<T>(
725 latestPhase - olderPhase - nominal));
726 realResidual += weight
727 * std::cos(static_cast<long double>(residual));
728 imagResidual += weight
729 * std::sin(static_cast<long double>(residual));
730 sumWeight += weight;
731 }
732 }
733
734 long double rho = 0.0L;
735 const long double residualMagnitude =
736 std::hypot(realResidual, imagResidual);
737 if (residualMagnitude > 64.0L
738 * static_cast<long double>(std::numeric_limits<T>::epsilon())
739 * sumWeight)
740 rho = std::atan2(imagResidual, realResidual);
741
742 const T advance = principalArgument(static_cast<T>(nominal + rho));
743 omega_[static_cast<std::size_t>(p)] = std::cos(advance);
744 omegaImag_[static_cast<std::size_t>(p)] = std::sin(advance);
745 }
746
747 // The two phase banks are a compact unit-complex representation. Peak
748 // entries retain their captured absolute phase; non-peaks retain the
749 // captured phase relative to their region peak. This lets the held
750 // audio path use multiplies instead of transcendental functions.
751 for (int ch = 0; ch < spec_.numChannels; ++ch)
752 {
753 const std::size_t base = channelBinOffset(ch);
754 for (int k = 1; k < numBins_ - 1; ++k)
755 {
756 if (active_[static_cast<std::size_t>(k)] == 0u
757 || peak_[static_cast<std::size_t>(k)] != 0u)
758 continue;
759 const std::size_t index = base + static_cast<std::size_t>(k);
760 const std::size_t peakIndex = base + regionPeak_[
761 static_cast<std::size_t>(k)];
762 const T real = capturedPhase_[index];
763 const T imag = frozenPhase_[index];
764 const T peakReal = capturedPhase_[peakIndex];
765 const T peakImag = frozenPhase_[peakIndex];
766 capturedPhase_[index] = real * peakReal + imag * peakImag;
767 frozenPhase_[index] = imag * peakReal - real * peakImag;
768 }
769 }
770 }
771
772 void advanceTonalPhase() noexcept
773 {
774 ++tonalAdvanceCount_;
775 const bool renormalize = (tonalAdvanceCount_ & 255u) == 0u;
776 for (int ch = 0; ch < spec_.numChannels; ++ch)
777 {
778 const std::size_t base = channelBinOffset(ch);
779 for (int p = 1; p < numBins_ - 1; ++p)
780 {
781 if (peak_[static_cast<std::size_t>(p)] == 0u) continue;
782 const std::size_t index = base + static_cast<std::size_t>(p);
783 const T real = capturedPhase_[index];
784 const T imag = frozenPhase_[index];
785 const T advanceReal = omega_[static_cast<std::size_t>(p)];
786 const T advanceImag = omegaImag_[static_cast<std::size_t>(p)];
787 T nextReal = real * advanceReal - imag * advanceImag;
788 T nextImag = real * advanceImag + imag * advanceReal;
789 if (renormalize)
790 {
791 const T length = std::hypot(nextReal, nextImag);
792 if (length > T(0) && std::isfinite(length))
793 {
794 nextReal /= length;
795 nextImag /= length;
796 }
797 else
798 {
799 nextReal = T(1);
800 nextImag = T(0);
801 }
802 }
803 capturedPhase_[index] = nextReal;
804 frozenPhase_[index] = nextImag;
805 }
806 }
807 }
808
809 [[nodiscard]] static T diffuseAngle(std::uint64_t generation,
810 std::uint64_t frame,
811 std::uint64_t bin) noexcept
812 {
813 std::uint64_t x = UINT64_C(0xD1B54A32D192ED03)
814 ^ (generation * UINT64_C(0x9E3779B97F4A7C15))
815 ^ (frame * UINT64_C(0xBF58476D1CE4E5B9))
816 ^ (bin * UINT64_C(0x94D049BB133111EB));
817 x += UINT64_C(0x9E3779B97F4A7C15);
818 x = (x ^ (x >> 30u)) * UINT64_C(0xBF58476D1CE4E5B9);
819 x = (x ^ (x >> 27u)) * UINT64_C(0x94D049BB133111EB);
820 x ^= x >> 31u;
821 const double uniform = static_cast<double>(x >> 11u) * 0x1.0p-53;
822 return static_cast<T>(2.0 * std::numbers::pi_v<double> * uniform);
823 }
824
825 void prepareDiffuseFrame() noexcept
826 {
827 for (int k = 1; k < numBins_ - 1; ++k)
828 {
829 const T angle = diffuseAngle(diffuseGeneration_, diffuseFrame_,
830 static_cast<std::uint64_t>(k));
831 omega_[static_cast<std::size_t>(k)] = std::cos(angle);
832 omegaImag_[static_cast<std::size_t>(k)] = std::sin(angle);
833 }
834 }
835
836 void targetPhasor(int channel, int bin, T& real, T& imag) const noexcept
837 {
838 const std::size_t base = channelBinOffset(channel);
839 const std::size_t index = base + static_cast<std::size_t>(bin);
840 if (capturedMode_ == PhaseMode::Diffuse)
841 {
842 const T capturedReal = capturedPhase_[index];
843 const T capturedImag = frozenPhase_[index];
844 const T randomReal = omega_[static_cast<std::size_t>(bin)];
845 const T randomImag = omegaImag_[static_cast<std::size_t>(bin)];
846 real = capturedReal * randomReal - capturedImag * randomImag;
847 imag = capturedReal * randomImag + capturedImag * randomReal;
848 return;
849 }
850
851 if (peak_[static_cast<std::size_t>(bin)] != 0u)
852 {
853 real = capturedPhase_[index];
854 imag = frozenPhase_[index];
855 return;
856 }
857
858 const std::size_t peakIndex = base
859 + regionPeak_[static_cast<std::size_t>(bin)];
860 const T peakReal = capturedPhase_[peakIndex];
861 const T peakImag = frozenPhase_[peakIndex];
862 const T relativeReal = capturedPhase_[index];
863 const T relativeImag = frozenPhase_[index];
864 real = peakReal * relativeReal - peakImag * relativeImag;
865 imag = peakReal * relativeImag + peakImag * relativeReal;
866 }
867
868 void blendFrozenSpectrum(T* spectrum, int channel) noexcept
869 {
870 const int transitionSteps = fftSize_ / hopSize_;
871 const std::size_t base = channelBinOffset(channel);
872 const int nyquist = numBins_ - 1;
873 const T heldGain = capturedMode_ == PhaseMode::Diffuse
874 ? std::sqrt(static_cast<T>(transitionSteps))
875 : T(1);
876
877 if (frameQ_ == transitionSteps)
878 {
879 spectrum[0] = capturedMagnitude_[base];
880 spectrum[1] = T(0);
881 spectrum[2 * nyquist] =
882 capturedMagnitude_[base + static_cast<std::size_t>(nyquist)];
883 spectrum[2 * nyquist + 1] = T(0);
884 for (int k = 1; k < nyquist; ++k)
885 {
886 const std::size_t index = base + static_cast<std::size_t>(k);
887 const T liveMagnitude = safeMagnitude(spectrum[2 * k],
888 spectrum[2 * k + 1]);
889 const T frozenMagnitude = capturedMagnitude_[index] * heldGain;
890 const bool liveActive = liveMagnitude >= magnitudeFloor_;
891 const bool frozenActive = capturedMagnitude_[index] >= magnitudeFloor_;
892 if (!liveActive && !frozenActive)
893 {
894 spectrum[2 * k] = T(0);
895 spectrum[2 * k + 1] = T(0);
896 continue;
897 }
898 if (!frozenActive)
899 {
900 const T scale = frozenMagnitude / liveMagnitude;
901 spectrum[2 * k] *= scale;
902 spectrum[2 * k + 1] *= scale;
903 continue;
904 }
905 T targetReal = T(0);
906 T targetImag = T(0);
907 targetPhasor(channel, k, targetReal, targetImag);
908 spectrum[2 * k] = frozenMagnitude * targetReal;
909 spectrum[2 * k + 1] = frozenMagnitude * targetImag;
910 }
911 return;
912 }
913
914 const T phase = std::numbers::pi_v<T> * static_cast<T>(frameQ_)
915 / static_cast<T>(transitionSteps);
916 const T alpha = T(0.5) - T(0.5) * std::cos(phase);
917 const T oneMinusAlpha = T(1) - alpha;
918 spectrum[0] = oneMinusAlpha * spectrum[0]
919 + alpha * capturedMagnitude_[base];
920 spectrum[1] = T(0);
921 spectrum[2 * nyquist] = oneMinusAlpha * spectrum[2 * nyquist]
922 + alpha * capturedMagnitude_[base + static_cast<std::size_t>(nyquist)];
923 spectrum[2 * nyquist + 1] = T(0);
924
925 for (int k = 1; k < nyquist; ++k)
926 {
927 const std::size_t index = base + static_cast<std::size_t>(k);
928 const T liveMagnitude = safeMagnitude(spectrum[2 * k],
929 spectrum[2 * k + 1]);
930 const T frozenMagnitude = capturedMagnitude_[index] * heldGain;
931 const bool liveActive = liveMagnitude >= magnitudeFloor_;
932 const bool frozenActive = capturedMagnitude_[index] >= magnitudeFloor_;
933 if (!liveActive && !frozenActive)
934 {
935 spectrum[2 * k] = T(0);
936 spectrum[2 * k + 1] = T(0);
937 continue;
938 }
939
940 T targetReal = T(0);
941 T targetImag = T(0);
942 targetPhasor(channel, k, targetReal, targetImag);
943 T livePhase = phaseOf(spectrum[2 * k], spectrum[2 * k + 1]);
944 T targetPhase = phaseOf(targetReal, targetImag);
945 if (!liveActive) livePhase = targetPhase;
946 if (!frozenActive) targetPhase = livePhase;
947
948 const T magnitude = oneMinusAlpha * liveMagnitude
949 + alpha * frozenMagnitude;
950 const T outputPhase = principalArgument(livePhase
951 + alpha * principalArgument(targetPhase - livePhase));
952 spectrum[2 * k] = magnitude * std::cos(outputPhase);
953 spectrum[2 * k + 1] = magnitude * std::sin(outputPhase);
954 if (!std::isfinite(spectrum[2 * k])
955 || !std::isfinite(spectrum[2 * k + 1]))
956 {
957 spectrum[2 * k] = T(0);
958 spectrum[2 * k + 1] = T(0);
959 }
960 }
961 }
962
963 AudioSpec spec_ {};
964 bool prepared_ = false;
965 int fftSize_ = 0;
966 int hopSize_ = 0;
967 int numBins_ = 0;
968
969 SpectralProcessor<T> processor_;
970 std::vector<T> scratch_;
971 std::array<T*, kMaxChannels> scratchChannels_ {};
972
973 // Three raw banks are current, latest completed and the completed frame
974 // before it. Integer bank rotation avoids frame-sized copies.
975 std::vector<T> rawSpectra_;
976 int olderBank_ = 0;
977 int latestBank_ = 1;
978 int currentBank_ = 2;
979 int completedFrames_ = 0;
980 int callbackChannel_ = 0;
981
982 std::vector<T> capturedMagnitude_;
983 std::vector<T> capturedPhase_;
984 std::vector<T> frozenPhase_;
985 std::vector<T> binPower_;
986 std::vector<T> omega_;
987 std::vector<T> omegaImag_;
988 std::vector<std::uint32_t> active_;
989 std::vector<std::uint32_t> peak_;
990 std::vector<std::uint32_t> regionPeak_;
991
992 int q_ = 0;
993 int frameQ_ = 0;
994 std::uint32_t frameRequestWord_ = 0u;
995 bool captured_ = false;
996 PhaseMode capturedMode_ = PhaseMode::Tonal;
997 T magnitudeFloor_ = T(0);
998 std::uint64_t nextDiffuseGeneration_ = 0u;
999 std::uint64_t diffuseGeneration_ = 0u;
1000 std::uint64_t diffuseFrame_ = 0u;
1001 std::uint32_t tonalAdvanceCount_ = 0u;
1002
1003 std::atomic<std::uint32_t> requested_ { 0u };
1004};
1005
1006} // namespace dspark
Non-owning view over audio channel data.
Definition AudioBuffer.h:53
Frequency-domain hold with tonal and diffuse phase modes.
int getFFTSize() const noexcept
Returns the prepared FFT size, or zero before prepare.
bool isFrozen() const noexcept
Returns the requested freeze state, not transition completion.
void processBlock(AudioBufferView< T > buffer) noexcept
Processes an in-place block without allocation or locking.
int getHopSize() const noexcept
Returns the prepared hop size, or zero before prepare.
int getLatency() const noexcept
Returns the exact input-signal latency, or zero before prepare.
std::vector< uint8_t > getState() const
Serializes the requested freeze state and phase mode (setup/UI threads; allocates)....
void setPhaseMode(PhaseMode mode) noexcept
Publishes the requested phase mode with one atomic RMW. Any representation other than exactly Diffuse...
bool setState(const uint8_t *data, size_t size)
Restores the freeze request and phase mode from a blob (tolerant; rejects foreign ids)....
void setFrozen(bool frozen) noexcept
Publishes the requested freeze state with one atomic RMW.
int getTransitionSamples() const noexcept
Returns the N-sample transition duration, or zero unprepared.
PhaseMode getPhaseMode() const noexcept
Returns the requested phase mode.
PhaseMode
Phase evolution used by the captured spectrum.
void prepare(const AudioSpec &spec, int fftSize=2048, int hopSize=0)
Prepares the processor and allocates all audio-path storage.
void reset() noexcept
Clears WOLA, history, capture and transition state. Requested controls are intentionally preserved.
High-performance STFT analysis-modification-synthesis pipeline.
void prepare(const AudioSpec &spec, int fftSize=2048, int hopSize=0)
Allocates buffers and prepares the WOLA processing state.
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
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
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