DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
TimeStretch.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
278#include "../Core/AudioBuffer.h"
279#include "../Core/AudioSpec.h"
280#include "../Core/DenormalGuard.h"
281#include "../Core/DspMath.h"
282#include "../Core/StateBlob.h"
283#include "detail/PhaseVocoderEngine.h"
284#include "detail/StudioVocoder.h"
285
286#include <algorithm>
287#include <atomic>
288#include <cmath>
289#include <cstddef>
290#include <cstdint>
291#include <vector>
292
293namespace dspark {
294
301template <FloatType T>
302class TimeStretch final
303{
304public:
305 // The published parameter words must never make the audio thread take a
306 // lock to read them.
307 static_assert(std::atomic<bool>::is_always_lock_free,
308 "audio-thread stores must not lock");
309
311 static constexpr T kMinRatio = T(0.5);
312 static constexpr T kMaxRatio = T(2);
313
331 enum class Quality { Standard, Studio };
332
334 void setQuality(Quality q) noexcept
335 {
337 std::memory_order_relaxed);
338 }
339
341 [[nodiscard]] Quality getQuality() const noexcept
342 {
343 return quality_.load(std::memory_order_relaxed);
344 }
345
346 // -- Lifecycle ---------------------------------------------------------------
347
365 void prepare(const AudioSpec& spec, int fftSize = 0)
366 {
367 if (!spec.isValid()) return;
368 if (fftSize != 0 && ((fftSize & (fftSize - 1)) != 0
369 || fftSize < 256 || fftSize > (1 << 20)))
370 return;
371
372 prepared_.store(false, std::memory_order_relaxed);
373
374 numChannels_ = std::max(1, spec.numChannels);
375 // 0 selects each engine's own default frame: 2048 for Standard (its
376 // published rendering) and about 85 ms for Studio (4096 at 44.1 and
377 // 48 kHz, 8192 at 88.2 and 96 kHz), the span its measurements use.
378 fftStandard_ = fftSize != 0 ? fftSize : 2048;
379 fftStudio_ = fftSize != 0 ? fftSize : studioDefaultFrame(spec.sampleRate);
380
381 // The input queue holds what the stretch has not consumed yet. It
382 // needs room for one whole analysis hop (which can be as long as a
383 // frame, and for Studio as long as a frame plus its lookahead), for
384 // one host block, and for the surplus a ratio above 1 accumulates
385 // until the caller stops or the queue refuses more.
386 const int widest = std::max(fftStandard_, fftStudio_);
387 int capacity = 4 * widest + 4 * studioDefaultFrame(spec.sampleRate) + std::max(1, spec.maxBlockSize);
388 queueSize_ = 1;
389 while (queueSize_ < capacity) queueSize_ <<= 1;
390 queueMask_ = queueSize_ - 1;
391
392 // No resample-back stage and no harmonic/percussive split; the
393 // locked analysis hop and the spectral-flux onset detector are both
394 // asked for, because this owner reads the synthesis stream directly
395 // and its hop schedule has to act on strikes the frame-energy test
396 // cannot see over sustained material.
397 engine_.prepare(spec.sampleRate, numChannels_, fftStandard_, false, false, true, true);
398 studio_.prepare(spec.sampleRate, numChannels_, fftStudio_, false);
399
400 queue_.assign(static_cast<size_t>(numChannels_), {});
401 for (int ch = 0; ch < numChannels_; ++ch)
402 queue_[static_cast<size_t>(ch)].assign(static_cast<size_t>(queueSize_), T(0));
403 feed_.assign(static_cast<size_t>(capacity), T(0));
404
405 publishEngineParams();
406 prepared_.store(true, std::memory_order_relaxed);
407 reset();
408 }
409
412 void reset() noexcept
413 {
414 if (!prepared_.load(std::memory_order_relaxed)) return;
415 studioActive_ = quality_.load(std::memory_order_relaxed) == Quality::Studio;
416 engine_.reset();
417 studio_.reset();
418 int latency = fftStandard_;
419 if (studioActive_)
420 {
421 fftSize_ = fftStudio_;
422 // One frame of analysis-synthesis delay plus the onset
423 // detector's lookahead.
424 latency = fftStudio_ + studio_.lookahead();
425 accumMask_ = studio_.olaMask();
426 }
427 else
428 {
429 fftSize_ = fftStandard_;
430 // The reader trails the completed frontier of the synthesis
431 // stream by one synthesis hop. The analysis-synthesis chain
432 // itself accounts for fftSize - synthHop samples of delay, so
433 // that trailing distance puts the reported latency at exactly
434 // one frame.
435 accumMask_ = engine_.olaMask();
436 }
437 latency_.store(latency, std::memory_order_relaxed);
438 synthHop_ = fftSize_ / 4;
439 for (auto& q : queue_) std::fill(q.begin(), q.end(), T(0));
440
441 queueWrite_ = 0;
442 queueRead_ = 0;
443 queued_ = 0;
444 discarded_ = 0;
445 path_ = Path::None;
446 // Start one synthesis hop behind the write head: those cells are
447 // still silent, which is the latency the class reports, and from
448 // there the reader stays exactly that far behind.
449 readPos_ = eWriteHead() - static_cast<int64_t>(latency - fftSize_ + synthHop_);
450 openIntake();
451 }
452
453 // -- Parameters ---------------------------------------------------------------
454
463 void setTimeRatio(T ratio) noexcept
464 {
465 if (!std::isfinite(ratio)) return;
466 timeRatio_.store(std::clamp(ratio, kMinRatio, kMaxRatio),
467 std::memory_order_relaxed);
468 publishEngineParams();
469 }
470
479 void setTempoChangePercent(T pct) noexcept
480 {
481 if (!std::isfinite(pct)) return;
482 const T denom = T(1) + pct / T(100);
483 if (!(denom > T(0))) { setTimeRatio(kMaxRatio); return; }
484 setTimeRatio(T(1) / denom);
485 }
486
490 void setTransientPreserve(bool on) noexcept
491 {
492 transientPreserve_.store(on, std::memory_order_relaxed);
493 publishEngineParams();
494 }
495
506 void setPhaseLock(bool on) noexcept
507 {
508 phaseLock_.store(on, std::memory_order_relaxed);
509 publishEngineParams();
510 }
511
513 [[nodiscard]] T getTimeRatio() const noexcept
514 {
515 return timeRatio_.load(std::memory_order_relaxed);
516 }
517
519 [[nodiscard]] bool getTransientPreserve() const noexcept
520 {
521 return transientPreserve_.load(std::memory_order_relaxed);
522 }
523
525 [[nodiscard]] bool getPhaseLock() const noexcept
526 {
527 return phaseLock_.load(std::memory_order_relaxed);
528 }
529
537 [[nodiscard]] int getLatency() const noexcept
538 {
539 return prepared_.load(std::memory_order_relaxed)
540 ? latency_.load(std::memory_order_relaxed)
541 : 0;
542 }
543
551 [[nodiscard]] static int64_t stretchedLength(int64_t inputSamples, double ratio) noexcept
552 {
553 return std::llround(static_cast<double>(inputSamples) * ratio);
554 }
555
557 [[nodiscard]] int getQueuedInputSamples() const noexcept { return queued_; }
558
559 // -- Rate-changing streaming: the correct path at any ratio -------------
560
569 [[nodiscard]] int getInputCapacity() const noexcept
570 {
571 if (!prepared_.load(std::memory_order_relaxed) || path_ == Path::Adaptor)
572 return 0;
573 return queueSize_ - queued_;
574 }
575
583 [[nodiscard]] int getAvailableOutput() const noexcept
584 {
585 if (!prepared_.load(std::memory_order_relaxed) || path_ != Path::Pull)
586 return 0;
587 return static_cast<int>(std::max<int64_t>(0, eWriteHead() - readPos_));
588 }
589
605 {
606 if (!prepared_.load(std::memory_order_relaxed) || !claimPullPath()) return 0;
607 DenormalGuard guard;
608
609 const int nCh = std::min(in.getNumChannels(), numChannels_);
610 const int count = std::min(std::max(0, in.getNumSamples()), queueSize_ - queued_);
611 int wp = queueWrite_;
612 for (int k = 0; k < count; ++k)
613 {
614 for (int ch = 0; ch < nCh; ++ch)
615 queue_[static_cast<size_t>(ch)][static_cast<size_t>(wp)]
616 = in.getChannel(ch)[k];
617 for (int ch = nCh; ch < numChannels_; ++ch)
618 queue_[static_cast<size_t>(ch)][static_cast<size_t>(wp)] = T(0);
619 wp = (wp + 1) & queueMask_;
620 }
621 queueWrite_ = wp;
622 queued_ += count;
623
624 runReadyFrames();
625 return count;
626 }
627
642 {
643 if (!prepared_.load(std::memory_order_relaxed) || !claimPullPath()) return 0;
644 DenormalGuard guard;
645
646 const int nCh = std::min(out.getNumChannels(), numChannels_);
647 const int count = std::min(std::max(0, out.getNumSamples()),
648 static_cast<int>(std::max<int64_t>(0, eWriteHead() - readPos_)));
649 if (count > 0)
650 {
651 readSynthesis(out, nCh, 0, count);
652 readPos_ += count;
653 }
654 // Reading frees room in the synthesis ring, which may be what was
655 // holding the next analysis frame back.
656 runReadyFrames();
657 return std::max(0, count);
658 }
659
670 [[nodiscard]] int64_t getDiscardedInput() const noexcept { return discarded_; }
671
673 [[nodiscard]] std::vector<uint8_t> getState() const
674 {
675 StateWriter w(stateId("TSTR"), 1);
676 w.write("ratio", static_cast<float>(timeRatio_.load(std::memory_order_relaxed)));
677 w.write("transient", transientPreserve_.load(std::memory_order_relaxed));
678 w.write("phaselock", phaseLock_.load(std::memory_order_relaxed));
679 w.write("quality", static_cast<int32_t>(quality_.load(std::memory_order_relaxed)));
680 return w.blob();
681 }
682
684 bool setState(const uint8_t* data, size_t size)
685 {
686 StateReader r(data, size);
687 if (!r.isValid() || r.processorId() != stateId("TSTR")) return false;
688 setTimeRatio(static_cast<T>(r.read("ratio", 1.0f)));
689 setTransientPreserve(r.read("transient", true));
690 setPhaseLock(r.read("phaselock", true));
691 // A blob written before the quality field existed was rendered by the
692 // Standard engine, so that is what it restores.
693 setQuality(static_cast<Quality>(std::clamp(r.read("quality", 0), 0, 1)));
694 return true;
695 }
696
697 // -- Processing ----------------------------------------------------------------
698
713 void processBlock(AudioBufferView<T> buffer) noexcept
714 {
715 if (!prepared_.load(std::memory_order_relaxed)) return;
716 if (path_ == Path::Pull) return;
717 path_ = Path::Adaptor;
718 DenormalGuard guard;
719
720 const int nCh = std::min(buffer.getNumChannels(), numChannels_);
721 const int nS = buffer.getNumSamples();
722 if (nS <= 0) return;
723
724 // Input is taken into the queue in step with the output leaving it,
725 // never a whole block ahead. That is what the device physically is -
726 // one sample in for every sample out - and it is also what makes the
727 // result independent of the host's block size: every decision below
728 // is taken at a position in the stream where the queue holds exactly
729 // the input the stream has delivered by then, whether the host sends
730 // one sample at a time or four thousand.
731 int taken = 0; // samples of this block already queued
732 int i = 0; // output samples already written
733 while (i < nS)
734 {
735 takeInput(buffer, nCh, taken, i);
736
737 const int64_t avail = eWriteHead() - readPos_;
738 if (avail > 0)
739 {
740 const int take = static_cast<int>(
741 std::min<int64_t>(avail, static_cast<int64_t>(nS - i)));
742 takeInput(buffer, nCh, taken, i + take);
743 readSynthesis(buffer, nCh, i, take);
744 readPos_ += take;
745 i += take;
746 continue;
747 }
748
749 // More synthesis is needed: run one analysis frame. Below a ratio
750 // of 1 the stretch wants more input than the stream has brought,
751 // and no amount of buffering invents it: the output waits, in
752 // silence, for exactly as many samples as are missing, and picks
753 // up where it left off.
754 const int need = eSamplesToNextHop();
755 if (need > queued_)
756 {
757 const int silence = std::min(need - queued_, nS - i);
758 // Take the matching input FIRST: the block is about to be
759 // overwritten with silence, and a sample the stream delivered
760 // must be queued whether or not anything came out against it.
761 takeInput(buffer, nCh, taken, i + silence);
762 for (int ch = 0; ch < nCh; ++ch)
763 std::fill(buffer.getChannel(ch) + i, buffer.getChannel(ch) + i + silence, T(0));
764 i += silence;
765 continue;
766 }
767
768 for (int ch = 0; ch < nCh; ++ch)
769 {
770 dequeueInto(ch, need);
771 ePushInput(ch, feed_.data(), need);
772 }
773 eCommitInput(need, nCh);
774 queueRead_ = (queueRead_ + need) & queueMask_;
775 queued_ -= need;
776 openIntake();
777 }
778 }
779
795 {
796 const int inLen = in.getNumSamples();
797 const int inCh = in.getNumChannels();
798
799 if (!prepared_.load(std::memory_order_relaxed) || inLen <= 0 || inCh <= 0)
800 {
801 out.resize(std::max(0, inCh), std::max(0, inLen));
802 for (int ch = 0; ch < inCh; ++ch)
803 std::copy(in.getChannel(ch), in.getChannel(ch) + inLen, out.getChannel(ch));
804 return;
805 }
806
807 const int nCh = std::min(inCh, numChannels_);
808 beginOffline(nCh);
809 pushOffline(in.getSubView(0, inLen));
811 const int outLen = static_cast<int>(offlineStop_ - offlineSkip_);
812 out.resize(inCh, std::max(0, outLen));
813 if (outLen > 0)
814 {
815 std::vector<T*> ptrs(static_cast<size_t>(nCh));
816 for (int ch = 0; ch < nCh; ++ch) ptrs[static_cast<size_t>(ch)] = out.getChannel(ch);
817 (void)pullOffline(AudioBufferView<T>(ptrs.data(), nCh, outLen));
818 }
819 offlineOpen_ = false;
820
821 // Channels the stretch does not cover would otherwise be left at the
822 // zero resize() gives them; carry them through instead, truncated or
823 // silence-padded to the stretched length.
824 for (int ch = nCh; ch < inCh; ++ch)
825 {
826 const T* src = in.getChannel(ch);
827 T* dst = out.getChannel(ch);
828 const int n = std::min(outLen, inLen);
829 std::copy(src, src + n, dst);
830 std::fill(dst + n, dst + outLen, T(0));
831 }
832 }
833
850 void beginOffline(int numChannels)
851 {
852 offlineOpen_ = false;
853 if (!prepared_.load(std::memory_order_relaxed)) return;
854 reset();
855 path_ = Path::Adaptor; // this path drives the same reader as the adaptor
856 offlineChannels_ = std::clamp(numChannels, 1, numChannels_);
857 offlineRatio_ = studioActive_ ? studio_.activeRatio() : engine_.activeRatio();
858 // A frame carries its content at its centre, so the first output
859 // sample that lines up with input sample 0 sits half an input frame
860 // plus half a stretched frame into the synthesis stream.
861 offlineSkip_ = studioActive_
862 ? std::llround(studio_.streamPositionOf(0.0)) - readPos_
863 : std::llround(0.5 * static_cast<double>(fftSize_) * (1.0 + offlineRatio_));
864 offlineStreamPos_ = 0;
865 offlineReceived_ = 0;
866 offlineStop_ = offlineSkip_;
867 offlineFinished_ = false;
868 offlineStaged_.assign(static_cast<size_t>(offlineChannels_), std::vector<T> {});
869 offlineStagedHead_ = 0;
870 offlineOut_.assign(static_cast<size_t>(offlineChannels_), std::vector<T> {});
871 offlineOutHead_ = 0;
872 offlineOpen_ = true;
873 }
874
877 {
878 if (!offlineOpen_ || offlineFinished_) return;
879 const int n = in.getNumSamples();
880 if (n <= 0) return;
881 for (int ch = 0; ch < offlineChannels_; ++ch)
882 {
883 auto& q = offlineStaged_[static_cast<size_t>(ch)];
884 if (ch < in.getNumChannels())
885 q.insert(q.end(), in.getChannel(ch), in.getChannel(ch) + n);
886 else
887 q.insert(q.end(), static_cast<size_t>(n), T(0));
888 }
889 offlineReceived_ += n;
890 runOffline();
891 }
892
896 {
897 if (!offlineOpen_ || offlineFinished_) return;
898 offlineFinished_ = true;
899 offlineStop_ = offlineSkip_ + stretchedLength(offlineReceived_, offlineRatio_);
900 runOffline();
901 }
902
904 [[nodiscard]] int getOfflineAvailable() const noexcept
905 {
906 if (!offlineOpen_ || offlineOut_.empty()) return 0;
907 return static_cast<int>(offlineOut_[0].size() - offlineOutHead_);
908 }
909
916 {
917 const int n = std::min(out.getNumSamples(), getOfflineAvailable());
918 if (n <= 0) return 0;
919 for (int ch = 0; ch < offlineChannels_ && ch < out.getNumChannels(); ++ch)
920 {
921 const T* src = offlineOut_[static_cast<size_t>(ch)].data() + offlineOutHead_;
922 std::copy(src, src + n, out.getChannel(ch));
923 }
924 offlineOutHead_ += static_cast<size_t>(n);
925 if (offlineOutHead_ > 65536 && offlineOutHead_ * 2 > offlineOut_[0].size())
926 {
927 for (auto& q : offlineOut_)
928 q.erase(q.begin(), q.begin() + static_cast<std::ptrdiff_t>(offlineOutHead_));
929 offlineOutHead_ = 0;
930 }
931 return n;
932 }
933
934private:
945 void runOffline()
946 {
947 const int nCh = offlineChannels_;
948 for (;;)
949 {
950 if (offlineFinished_ && offlineStreamPos_ >= offlineStop_) break;
951 const int64_t avail = eWriteHead() - readPos_;
952 if (avail <= 0)
953 {
954 const int need = eSamplesToNextHop();
955 const int64_t staged = static_cast<int64_t>(offlineStaged_[0].size() - offlineStagedHead_);
956 if (!offlineFinished_ && staged < need) break; // wait for input
957 // Past the input's end the engine is flushed with silence.
958 for (int ch = 0; ch < nCh; ++ch)
959 {
960 const auto& q = offlineStaged_[static_cast<size_t>(ch)];
961 for (int k = 0; k < need; ++k)
962 {
963 const size_t idx = offlineStagedHead_ + static_cast<size_t>(k);
964 feed_[static_cast<size_t>(k)] = (idx < q.size()) ? q[idx] : T(0);
965 }
966 ePushInput(ch, feed_.data(), need);
967 }
968 eCommitInput(need, nCh);
969 offlineStagedHead_ = std::min(offlineStagedHead_ + static_cast<size_t>(need),
970 offlineStaged_[0].size());
971 if (offlineStagedHead_ > 65536)
972 {
973 for (auto& q : offlineStaged_)
974 q.erase(q.begin(), q.begin() + static_cast<std::ptrdiff_t>(offlineStagedHead_));
975 offlineStagedHead_ = 0;
976 }
977 continue;
978 }
979
980 const int64_t limit = offlineFinished_
981 ? offlineStop_
982 : offlineSkip_ + stretchedLength(offlineReceived_, offlineRatio_);
983 const int64_t take = std::min(avail, limit - offlineStreamPos_);
984 if (take <= 0) break;
985 const int64_t from = std::max(offlineStreamPos_, offlineSkip_);
986 const int64_t count = offlineStreamPos_ + take - from;
987 if (count > 0)
988 {
989 for (int ch = 0; ch < nCh; ++ch)
990 {
991 const T* acc = eOla(ch);
992 auto& q = offlineOut_[static_cast<size_t>(ch)];
993 const int64_t rp = readPos_ + (from - offlineStreamPos_);
994 for (int64_t k = 0; k < count; ++k)
995 q.push_back(acc[static_cast<size_t>((rp + k) & accumMask_)]);
996 }
997 }
998 readPos_ += take;
999 offlineStreamPos_ += take;
1000 }
1001 }
1002
1003private:
1005 void publishEngineParams() noexcept
1006 {
1007 typename detail::PhaseVocoderEngine<T>::Params p;
1008 // The engine carries its stretch target logarithmically, because the
1009 // same core drives a pitch shifter where semitones are the natural
1010 // unit. Ratio and semitones are the same number in two spellings.
1011 p.targetSemitones = 12.0 * std::log2(static_cast<double>(
1012 timeRatio_.load(std::memory_order_relaxed)));
1013 p.transientPreserve = transientPreserve_.load(std::memory_order_relaxed);
1014 p.formantPreserve = false; // nothing resamples the output here
1015 p.phaseLock = phaseLock_.load(std::memory_order_relaxed);
1016 p.percussiveSplit = false; // no public switch selects the split here
1017 engine_.publishParams(p);
1018
1019 typename detail::StudioVocoder<T>::Params q;
1020 q.targetSemitones = p.targetSemitones;
1021 q.transientPreserve = p.transientPreserve;
1022 q.formantPreserve = false;
1023 studio_.publishParams(q);
1024 }
1025
1047 void openIntake() noexcept
1048 {
1049 intakeSpan_ = std::max(1, synthHop_);
1050 const double ratio = studioActive_ ? studio_.activeRatio() : engine_.activeRatio();
1051 // Never wider than the queue: above unity the window is bounded by
1052 // one analysis hop and the queue holds several frames, so this
1053 // cannot bind there, and stating it is what keeps the loop below
1054 // total.
1055 intakeWant_ = ratio <= 1.0
1056 ? queueSize_ - queued_
1057 : std::clamp(eSamplesToNextHop() - queued_, 0, queueSize_ - queued_);
1058 intakeTaken_ = 0;
1059 intakeErr_ = 0;
1060 }
1061
1063 [[nodiscard]] bool acceptOffered() noexcept
1064 {
1065 if (intakeTaken_ >= intakeWant_) return false;
1066 if (intakeWant_ < intakeSpan_)
1067 {
1068 intakeErr_ += intakeWant_;
1069 if (intakeErr_ < intakeSpan_) return false;
1070 intakeErr_ -= intakeSpan_;
1071 }
1072 ++intakeTaken_;
1073 return true;
1074 }
1075
1086 void takeInput(AudioBufferView<T> buffer, int nCh, int& taken, int upTo) noexcept
1087 {
1088 if (upTo <= taken) return;
1089 int wp = queueWrite_;
1090 int held = queued_;
1091 for (int k = taken; k < upTo; ++k)
1092 {
1093 if (!acceptOffered()) { ++discarded_; continue; }
1094 for (int ch = 0; ch < nCh; ++ch)
1095 queue_[static_cast<size_t>(ch)][static_cast<size_t>(wp)]
1096 = buffer.getChannel(ch)[k];
1097 wp = (wp + 1) & queueMask_;
1098 ++held;
1099 }
1100 queueWrite_ = wp;
1101 queued_ = held;
1102 taken = upTo;
1103 }
1104
1107 [[nodiscard]] bool claimPullPath() noexcept
1108 {
1109 if (path_ == Path::Pull) return true;
1110 if (path_ != Path::None) return false;
1111 path_ = Path::Pull;
1112 // This path's output is the stretched timeline itself, so it starts
1113 // where input sample 0 lands: a frame carries its content at its
1114 // centre, half an input frame plus half a stretched frame past the
1115 // adaptor's reader, the same place the offline path skips to.
1116 readPos_ = studioActive_
1117 ? static_cast<int64_t>(std::llround(studio_.streamPositionOf(0.0)))
1118 : eWriteHead() - static_cast<int64_t>(synthHop_) + std::llround(
1119 0.5 * static_cast<double>(fftSize_) * (1.0 + engine_.activeRatio()));
1120 return true;
1121 }
1122
1125 void runReadyFrames() noexcept
1126 {
1127 for (;;)
1128 {
1129 const int need = eSamplesToNextHop();
1130 if (queued_ < need) return;
1131 // A frame writes one whole window ahead of the head; stop before
1132 // it would reach unread output.
1133 if (eWriteHead() + static_cast<int64_t>(fftSize_) - readPos_
1134 > static_cast<int64_t>(accumMask_) + 1)
1135 return;
1136
1137 for (int ch = 0; ch < numChannels_; ++ch)
1138 {
1139 dequeueInto(ch, need);
1140 ePushInput(ch, feed_.data(), need);
1141 }
1142 eCommitInput(need, numChannels_);
1143 queueRead_ = (queueRead_ + need) & queueMask_;
1144 queued_ -= need;
1145 }
1146 }
1147
1151 void dequeueInto(int ch, int count) noexcept
1152 {
1153 const auto& q = queue_[static_cast<size_t>(ch)];
1154 int rp = queueRead_;
1155 for (int k = 0; k < count; ++k)
1156 {
1157 feed_[static_cast<size_t>(k)] = q[static_cast<size_t>(rp)];
1158 rp = (rp + 1) & queueMask_;
1159 }
1160 }
1161
1163 void readSynthesis(AudioBufferView<T> buffer, int nCh, int offset, int count) noexcept
1164 {
1165 for (int ch = 0; ch < nCh; ++ch)
1166 {
1167 const T* acc = eOla(ch);
1168 T* dst = buffer.getChannel(ch) + offset;
1169 const int64_t rp = readPos_;
1170 for (int k = 0; k < count; ++k)
1171 dst[k] = acc[static_cast<size_t>((rp + k) & accumMask_)];
1172 }
1173 }
1174
1175 // -- Engine dispatch (the engine in force is chosen at reset()) ---------------
1176
1177 [[nodiscard]] int64_t eWriteHead() const noexcept
1178 {
1179 return studioActive_ ? studio_.writeHead() : engine_.writeHead();
1180 }
1181 [[nodiscard]] int eSamplesToNextHop() const noexcept
1182 {
1183 return studioActive_ ? studio_.samplesToNextHop() : engine_.samplesToNextHop();
1184 }
1185 void ePushInput(int ch, const T* src, int count) noexcept
1186 {
1187 if (studioActive_) studio_.pushInput(ch, src, count);
1188 else engine_.pushInput(ch, src, count);
1189 }
1190 void eCommitInput(int count, int nCh) noexcept
1191 {
1192 if (studioActive_) studio_.commitInput(count, nCh);
1193 else engine_.commitInput(count, nCh);
1194 }
1195 [[nodiscard]] const T* eOla(int ch) const noexcept
1196 {
1197 return studioActive_ ? studio_.olaData(ch) : engine_.olaData(ch);
1198 }
1199
1201 [[nodiscard]] static int studioDefaultFrame(double sampleRate) noexcept
1202 {
1203 int n = 256;
1204 while (n < (1 << 16) && static_cast<double>(n) * 1.5 < 0.085 * sampleRate) n <<= 1;
1205 return n;
1206 }
1207
1208 // -- Members -------------------------------------------------------------------
1209 int numChannels_ = 0;
1210 std::atomic<bool> prepared_ { false };
1211
1212 int fftSize_ = 2048;
1213 int synthHop_ = 512;
1214 std::atomic<int> latency_ { 2048 };
1215 int64_t accumMask_ = 8191;
1216
1217 detail::PhaseVocoderEngine<T> engine_;
1218 detail::StudioVocoder<T> studio_;
1219 bool studioActive_ = true;
1220 int fftStandard_ = 2048;
1221 int fftStudio_ = 4096;
1222
1223 std::vector<std::vector<T>> queue_;
1224 std::vector<T> feed_;
1225 int queueSize_ = 0;
1226 int queueMask_ = 0;
1227 int queueWrite_ = 0;
1228 int queueRead_ = 0;
1229 int queued_ = 0;
1230
1232 enum class Path { None, Adaptor, Pull };
1233 Path path_ = Path::None;
1234
1235 int64_t discarded_ = 0;
1236 int intakeSpan_ = 0;
1237 int intakeWant_ = 0;
1238 int intakeTaken_ = 0;
1239 int intakeErr_ = 0;
1240
1241 int64_t readPos_ = 0;
1242
1243 std::atomic<Quality> quality_ { Quality::Studio };
1244 std::atomic<T> timeRatio_ { T(1) };
1245 std::atomic<bool> transientPreserve_ { true };
1246 std::atomic<bool> phaseLock_ { true };
1247
1248 // Offline session (beginOffline() .. finishOffline(), pullOffline()).
1249 bool offlineOpen_ = false;
1250 bool offlineFinished_ = false;
1251 int offlineChannels_ = 0;
1252 double offlineRatio_ = 1.0;
1253 int64_t offlineSkip_ = 0;
1254 int64_t offlineStop_ = 0;
1255 int64_t offlineStreamPos_ = 0;
1256 int64_t offlineReceived_ = 0;
1257 std::vector<std::vector<T>> offlineStaged_;
1258 size_t offlineStagedHead_ = 0;
1259 std::vector<std::vector<T>> offlineOut_;
1260 size_t offlineOutHead_ = 0;
1261};
1262
1263} // 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.
AudioBufferView getSubView(int startSample, int length) const noexcept
Returns a zero-copy sub-view starting at an offset.
Owning audio buffer with contiguous, 32-byte aligned storage.
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.
RAII scope guard to disable denormalised (subnormal) floating-point numbers.
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
Real-time and offline time stretching, 0.5x to 2x, pitch unchanged.
static int64_t stretchedLength(int64_t inputSamples, double ratio) noexcept
Length in samples of inputSamples stretched by ratio, which is what process() and an offline session ...
int getInputCapacity() const noexcept
Room for input right now, in samples (stream owner).
void setTimeRatio(T ratio) noexcept
Sets the stretch as an output/input length ratio.
int getAvailableOutput() const noexcept
Stretched output ready right now, in samples (stream owner).
void processBlock(AudioBufferView< T > buffer) noexcept
Fixed-rate playback adaptor: streaming, in-place, real-time safe.
void prepare(const AudioSpec &spec, int fftSize=0)
Allocates every buffer this class will ever use.
T getTimeRatio() const noexcept
void process(AudioBufferView< const T > in, AudioBuffer< T > &out)
Offline whole-signal stretch (setup thread; allocates out).
Quality
The engine that renders the stretch (see the file overview).
std::vector< uint8_t > getState() const
Serializes the parameter state (setup/UI threads; allocates).
int feedInput(AudioBufferView< const T > in) noexcept
Hands input to the stretch; real-time safe (stream owner).
int getQueuedInputSamples() const noexcept
Input samples accepted but not yet consumed by the stretch.
int64_t getDiscardedInput() const noexcept
Input samples the fixed-rate adaptor refused, cumulative since prepare() or reset() (stream owner).
void setTempoChangePercent(T pct) noexcept
Sets the stretch as a tempo change in percent.
void finishOffline()
Ends the input of an offline session; everything left becomes available to pullOffline().
int getLatency() const noexcept
Latency of the fixed-rate processBlock() path in samples for the engine in force: one frame for Stand...
static constexpr T kMinRatio
Smallest and largest stretch this class accepts.
Quality getQuality() const noexcept
int pullOffline(AudioBufferView< T > out)
Writes up to out.getNumSamples() stretched samples of an offline session and returns how many it wrot...
bool getTransientPreserve() const noexcept
bool setState(const uint8_t *data, size_t size)
Restores parameters from a blob (tolerant; rejects foreign ids).
int pullOutput(AudioBufferView< T > out) noexcept
Takes stretched output; real-time safe (stream owner).
int getOfflineAvailable() const noexcept
Stretched samples ready to pull in an offline session.
static constexpr T kMaxRatio
void setQuality(Quality q) noexcept
Selects the engine (applied at the next prepare()/reset()).
void beginOffline(int numChannels)
Opens an offline stretch fed in blocks (setup thread; allocates).
void pushOffline(AudioBufferView< const T > in)
Feeds the next block of an offline session. No-op outside one.
bool getPhaseLock() const noexcept
void setTransientPreserve(bool on) noexcept
Enables phase reset on detected transients (default on). Without it, attacks are stretched along with...
void setPhaseLock(bool on) noexcept
Enables identity phase locking in the Standard engine (default on). Studio has no such switch: its ph...
void reset() noexcept
Clears all signal state and empties the input queue (keeps parameters). Belongs to the owner of the s...
Main namespace for the DSPark framework.
@ None
The curve as drawn: a brief move plays at part of its depth.
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