DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
SampleReader.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
33#include "../DspMath.h"
34#include "../SampleZone.h"
35#include "../SimdOps.h"
36
37#include <algorithm>
38#include <array>
39#include <cmath>
40#include <cstdint>
41#include <cstdlib>
42#include <type_traits>
43#include <vector>
44
45namespace dspark::detail
46{
47
49template <FloatType T> struct SampleZoneData
50{
51 std::vector<T> audio;
52 std::vector<T> baked;
53 int channels = 0;
54 int64_t length = 0;
55 double sampleRate = 48000.0;
56 int rootKey = 60;
57 double tuneCents = 0.0;
58 int keyLow = 0, keyHigh = 127;
59 double velLow = 0.0, velHigh = 1.0;
60 double gain = 1.0;
61 double pan = 0.0;
62 int64_t start = 0;
64 int64_t loopStart = 0, loopEnd = 0, xfade = 0;
65};
66
72template <FloatType T>
74{
75 const int ch = z.audio.getNumChannels();
76 const int64_t len = z.audio.getNumSamples();
77 if (ch < 1 || len < 1 || !(z.sampleRate > 0.0) || !std::isfinite(z.sampleRate))
78 return false;
79 for (int c = 0; c < ch; ++c)
80 if (z.audio.getChannel(c) == nullptr) return false;
81 if (z.keyLow > z.keyHigh || z.velocityLow > z.velocityHigh
82 || !std::isfinite(z.tuneCents) || !std::isfinite(z.gainDb) || !std::isfinite(z.pan))
83 return false;
84
85 d.channels = ch;
86 d.length = len;
88 d.rootKey = z.rootKey;
89 d.tuneCents = z.tuneCents;
90 d.keyLow = std::clamp(z.keyLow, 0, 127);
91 d.keyHigh = std::clamp(z.keyHigh, 0, 127);
92 d.velLow = std::clamp(z.velocityLow, 0.0, 1.0);
93 d.velHigh = std::clamp(z.velocityHigh, 0.0, 1.0);
94 d.gain = std::pow(10.0, std::clamp(z.gainDb, -120.0, 24.0) / 20.0);
95 d.pan = std::clamp(z.pan, -1.0, 1.0);
96 d.start = std::clamp<int64_t>(z.startOffset, 0, len - 1);
97 d.audio.resize(static_cast<size_t>(ch) * static_cast<size_t>(len));
98 for (int c = 0; c < ch; ++c)
99 {
100 const T* src = z.audio.getChannel(c);
101 T* dst = d.audio.data() + static_cast<size_t>(c) * static_cast<size_t>(len);
102 for (int64_t i = 0; i < len; ++i)
103 dst[i] = std::isfinite(src[i]) ? src[i] : T(0);
104 }
105
106 d.loop = z.loopMode;
107 d.loopStart = std::clamp<int64_t>(z.loopStart, 0, len);
108 d.loopEnd = std::clamp<int64_t>(z.loopEnd, 0, len);
109 if (d.loop != SampleLoopMode::None && d.loopEnd - d.loopStart < 2)
111 if (d.loop == SampleLoopMode::None) return true;
112
113 d.xfade = std::clamp<int64_t>(z.loopCrossfade, 0,
114 std::min(d.loopStart, d.loopEnd - d.loopStart));
115 if (d.xfade > 0)
116 {
117 d.baked.resize(static_cast<size_t>(ch) * static_cast<size_t>(d.xfade));
118 for (int c = 0; c < ch; ++c)
119 {
120 const T* src = d.audio.data() + static_cast<size_t>(c) * static_cast<size_t>(len);
121 T* dst = d.baked.data() + static_cast<size_t>(c) * static_cast<size_t>(d.xfade);
122 for (int64_t i = 0; i < d.xfade; ++i)
123 {
124 // Fade the loop's tail out into the audio that precedes the
125 // loop start, so the jump lands on continuous material.
126 const double x = (static_cast<double>(i) + 0.5) / static_cast<double>(d.xfade);
127 const double fin = z.equalPowerCrossfade ? std::sin(0.5 * pi<double> * x) : x;
128 const double fout = z.equalPowerCrossfade ? std::cos(0.5 * pi<double> * x) : 1.0 - x;
129 const double tail = static_cast<double>(src[d.loopEnd - d.xfade + i]);
130 const double lead = static_cast<double>(src[d.loopStart - d.xfade + i]);
131 dst[i] = static_cast<T>(fout * tail + fin * lead);
132 }
133 }
134 }
135 return true;
136}
137
143inline void sampleZonePanGains(double pan, int channels, double gain,
144 double& left, double& right, double& mono) noexcept
145{
146 mono = gain;
147 if (channels == 1)
148 {
149 // cos on both sides (sin(a) = cos(pi/2 - a)): opposite pans get
150 // exactly mirrored gains, and a centred zone is exactly mono.
151 left = gain * std::cos(0.25 * pi<double> * (1.0 + pan)) * sqrt2<double>;
152 right = gain * std::cos(0.25 * pi<double> * (1.0 - pan)) * sqrt2<double>;
153 }
154 else
155 {
156 left = gain * std::min(1.0, 1.0 - pan);
157 right = gain * std::min(1.0, 1.0 + pan);
158 }
159}
160
163inline constexpr int kSampleGatherLanes = 8;
164
166template <FloatType T>
167inline T sampleGatherReduce(const T* lane) noexcept
168{
169 return ((lane[0] + lane[4]) + (lane[1] + lane[5])) + ((lane[2] + lane[6]) + (lane[3] + lane[7]));
170}
171
184template <int C, FloatType T>
185inline void sampleGatherNarrow(const T* r0, const T* r1, T g, const T* x0, const T* x1,
186 int taps, T* out) noexcept
187{
188 constexpr int W = std::is_same_v<T, float> ? simd::kVecFloatNarrow : simd::kVecDoubleNarrow;
189 using V = simd::Vec<T, W>;
190 using R = typename V::V;
191 constexpr int K = kSampleGatherLanes / W;
192 R acc0[K], acc1[K];
193 for (int k = 0; k < K; ++k) acc0[k] = acc1[k] = V::set1(T(0));
194 const R gv = V::set1(g);
195 for (int t = 0; t < taps; t += kSampleGatherLanes)
196 for (int k = 0; k < K; ++k)
197 {
198 const int o = t + k * W;
199 const R a = V::load(r0 + o);
200 const R w = V::add(a, V::mul(gv, V::sub(V::load(r1 + o), a)));
201 acc0[k] = V::add(acc0[k], V::mul(w, V::load(x0 + o)));
202 if constexpr (C == 2) acc1[k] = V::add(acc1[k], V::mul(w, V::load(x1 + o)));
203 }
204 T lane[kSampleGatherLanes];
205 for (int k = 0; k < K; ++k) V::store(lane + k * W, acc0[k]);
206 out[0] = sampleGatherReduce(lane);
207 if constexpr (C == 2)
208 {
209 for (int k = 0; k < K; ++k) V::store(lane + k * W, acc1[k]);
210 out[1] = sampleGatherReduce(lane);
211 }
212}
213
214#if defined(DSPARK_SIMD_EXACT_AVX2)
215DSPARK_SIMD_EXACT_AVX2_BEGIN
217inline float sampleGatherReduceAvx2(__m256 v) noexcept
218{
219 const __m128 q = _mm_add_ps(_mm256_castps256_ps128(v), _mm256_extractf128_ps(v, 1));
220 const __m128 pairs = _mm_add_ps(q, _mm_shuffle_ps(q, q, _MM_SHUFFLE(2, 3, 0, 1))); // q0 + q1, q2 + q3
221 return _mm_cvtss_f32(_mm_add_ss(pairs, _mm_movehl_ps(pairs, pairs)));
222}
223
225inline double sampleGatherReduceAvx2(__m256d l, __m256d h) noexcept
226{
227 const __m256d q = _mm256_add_pd(l, h);
228 const __m128d q01 = _mm256_castpd256_pd128(q), q23 = _mm256_extractf128_pd(q, 1);
229 const double s01 = _mm_cvtsd_f64(_mm_add_sd(q01, _mm_unpackhi_pd(q01, q01)));
230 const double s23 = _mm_cvtsd_f64(_mm_add_sd(q23, _mm_unpackhi_pd(q23, q23)));
231 return s01 + s23;
232}
233
235template <int C>
236inline void sampleGatherAvx2(const float* r0, const float* r1, float g, const float* x0,
237 const float* x1, int taps, float* out) noexcept
238{
239 __m256 acc0 = _mm256_setzero_ps(), acc1 = _mm256_setzero_ps();
240 const __m256 gv = _mm256_set1_ps(g);
241 for (int t = 0; t < taps; t += kSampleGatherLanes)
242 {
243 const __m256 a = _mm256_loadu_ps(r0 + t);
244 const __m256 w = _mm256_add_ps(a, _mm256_mul_ps(gv, _mm256_sub_ps(_mm256_loadu_ps(r1 + t), a)));
245 acc0 = _mm256_add_ps(acc0, _mm256_mul_ps(w, _mm256_loadu_ps(x0 + t)));
246 if constexpr (C == 2) acc1 = _mm256_add_ps(acc1, _mm256_mul_ps(w, _mm256_loadu_ps(x1 + t)));
247 }
248 out[0] = sampleGatherReduceAvx2(acc0);
249 if constexpr (C == 2) out[1] = sampleGatherReduceAvx2(acc1);
250}
251
253template <int C>
254inline void sampleGatherAvx2(const double* r0, const double* r1, double g, const double* x0,
255 const double* x1, int taps, double* out) noexcept
256{
257 __m256d a00 = _mm256_setzero_pd(), a01 = _mm256_setzero_pd();
258 __m256d a10 = _mm256_setzero_pd(), a11 = _mm256_setzero_pd();
259 const __m256d gv = _mm256_set1_pd(g);
260 for (int t = 0; t < taps; t += kSampleGatherLanes)
261 {
262 const __m256d lo = _mm256_loadu_pd(r0 + t), hi = _mm256_loadu_pd(r0 + t + 4);
263 const __m256d wl = _mm256_add_pd(lo, _mm256_mul_pd(gv, _mm256_sub_pd(_mm256_loadu_pd(r1 + t), lo)));
264 const __m256d wh = _mm256_add_pd(hi, _mm256_mul_pd(gv, _mm256_sub_pd(_mm256_loadu_pd(r1 + t + 4), hi)));
265 a00 = _mm256_add_pd(a00, _mm256_mul_pd(wl, _mm256_loadu_pd(x0 + t)));
266 a01 = _mm256_add_pd(a01, _mm256_mul_pd(wh, _mm256_loadu_pd(x0 + t + 4)));
267 if constexpr (C == 2)
268 {
269 a10 = _mm256_add_pd(a10, _mm256_mul_pd(wl, _mm256_loadu_pd(x1 + t)));
270 a11 = _mm256_add_pd(a11, _mm256_mul_pd(wh, _mm256_loadu_pd(x1 + t + 4)));
271 }
272 }
273 out[0] = sampleGatherReduceAvx2(a00, a01);
274 if constexpr (C == 2) out[1] = sampleGatherReduceAvx2(a10, a11);
275}
276DSPARK_SIMD_EXACT_AVX2_END
277#endif
278
283template <FloatType T>
285{
286public:
288 static constexpr int kHalfTaps = 32;
290 static constexpr int kTablePerUnit = 2048;
292 static constexpr double kMaxRate = 8.0;
294 static constexpr double kMinScatterRate = 1.0 / kMaxRate;
297 static constexpr double kMinGatherRate = 1.0 / 8192.0;
298 static constexpr int kMaxHalfTaps = static_cast<int>(kHalfTaps * kMaxRate);
301 static constexpr double kCutoff = 0.9;
302 static constexpr double kBeta = 10.06;
304 static constexpr int kPhases = 2048;
305 static constexpr int kTaps = 2 * kHalfTaps;
307 static constexpr int kWeightsLength = 2 * kMaxHalfTaps + 2;
310 static constexpr int kAccLength = 4 * kMaxHalfTaps + 256;
311
313 enum class Frame
314 {
315 Ended,
316 Produced,
317 Last
318 };
319
321 static const std::vector<double>& kernelTable()
322 {
323 static const std::vector<double> table = [] {
324 std::vector<double> t(static_cast<size_t>(kHalfTaps * kTablePerUnit + 2), 0.0);
325 auto i0 = [](double x) {
326 double sum = 1.0, term = 1.0;
327 for (int k = 1; k < 64; ++k)
328 {
329 term *= (x / (2.0 * k)) * (x / (2.0 * k));
330 sum += term;
331 if (term < sum * 1e-17) break;
332 }
333 return sum;
334 };
335 const double norm = i0(kBeta);
336 for (size_t j = 0; j + 1 < t.size(); ++j)
337 {
338 const double x = static_cast<double>(j) / kTablePerUnit;
339 if (x >= kHalfTaps) break;
340 const double arg = pi<double> * kCutoff * x;
341 const double sinc = (x == 0.0) ? 1.0 : std::sin(arg) / arg;
342 const double r = x / kHalfTaps;
343 t[j] = kCutoff * sinc * i0(kBeta * std::sqrt(std::max(0.0, 1.0 - r * r))) / norm;
344 }
345 return t;
346 }();
347 return table;
348 }
349
357 static const std::vector<T>& polyphaseTable()
358 {
359 static const std::vector<T> rows = [] {
360 const auto& h = kernelTable();
361 std::vector<T> r(static_cast<size_t>((kPhases + 1) * kTaps), T(0));
362 for (int q = 0; q <= kPhases; ++q)
363 for (int t = 0; t < kTaps; ++t)
364 {
365 // |k - frac| in table units, exactly: (t - 31) * P - q.
366 const long u = std::labs(static_cast<long>(t - (kHalfTaps - 1)) * kTablePerUnit - q);
367 r[static_cast<size_t>(q * kTaps + t)] =
368 (static_cast<size_t>(u) < h.size()) ? static_cast<T>(h[static_cast<size_t>(u)]) : T(0);
369 }
370 return r;
371 }();
372 return rows;
373 }
374
376 void allocate()
377 {
378 for (auto& a : acc_) a.assign(static_cast<size_t>(kAccLength), T(0));
379 }
380
386 void start(const SampleZoneData<T>& z, double ratio) noexcept
387 {
388 zone_ = &z;
389 pos_ = static_cast<double>(z.start);
390 scatter_ = ratio > 1.0;
391 wrapped_ = false;
392 justWrapped_ = false;
393 inputDone_ = false;
394 drainLeft_ = 0;
395 jIn_ = z.start;
396 tNext_ = 0.0;
397 accPos_ = 0;
398 if (scatter_)
399 for (auto& a : acc_) std::fill(a.begin(), a.end(), T(0));
400 loopEngaged_ = z.loop != SampleLoopMode::None;
401 releaseLoop_ = false;
402 }
403
405 void release() noexcept
406 {
407 if (zone_ != nullptr && zone_->loop == SampleLoopMode::Sustain) releaseLoop_ = true;
408 }
409
411 [[nodiscard]] bool scatters() const noexcept { return scatter_; }
412
414 [[nodiscard]] double minRate() const noexcept { return scatter_ ? kMinScatterRate : kMinGatherRate; }
415
417 [[nodiscard]] const SampleZoneData<T>* zone() const noexcept { return zone_; }
418
430 Frame next(double ratio, int outChannels, T* weights, double& a0, double& a1) noexcept
431 {
432 return scatter_ ? scatterFrame(ratio, outChannels, weights, a0, a1)
433 : gatherFrame(ratio, outChannels, weights, a0, a1);
434 }
435
436private:
440 [[nodiscard]] static double dot(const T* w, const T* x, int n) noexcept
441 {
442 T a[8] = { T(0), T(0), T(0), T(0), T(0), T(0), T(0), T(0) };
443 int t = 0;
444 for (; t + 8 <= n; t += 8)
445 for (int l = 0; l < 8; ++l)
446 a[l] += w[t + l] * x[t + l];
447 T sum = ((a[0] + a[4]) + (a[1] + a[5])) + ((a[2] + a[6]) + (a[3] + a[7]));
448 for (; t < n; ++t) sum += w[t] * x[t];
449 return static_cast<double>(sum);
450 }
451
454 [[nodiscard]] static double fetch(const SampleZoneData<T>& z, const T* chan, const T* baked,
455 int64_t j, bool loopEngaged, bool wrapped = false) noexcept
456 {
457 if (loopEngaged && j >= z.loopEnd)
458 j = z.loopStart + (j - z.loopEnd) % (z.loopEnd - z.loopStart);
459 else if (loopEngaged && wrapped && j < z.loopStart)
460 j = z.loopEnd - 1 - (z.loopStart - 1 - j) % (z.loopEnd - z.loopStart);
461 if (j < 0 || j >= z.length) return 0.0;
462 if (loopEngaged && baked != nullptr && j >= z.loopEnd - z.xfade && j < z.loopEnd)
463 return static_cast<double>(baked[j - (z.loopEnd - z.xfade)]);
464 return static_cast<double>(chan[j]);
465 }
466
469 static int kernelWeights(T* weights, double frac, double fc, int half) noexcept
470 {
471 if (fc >= 1.0)
472 {
473 const T* rows = polyphaseTable().data();
474 const double qf = frac * kPhases;
475 const int q = std::min(static_cast<int>(qf), kPhases - 1);
476 const T g = static_cast<T>(qf - static_cast<double>(q));
477 const T* r0 = rows + static_cast<size_t>(q) * kTaps;
478 const T* r1 = r0 + kTaps;
479 for (int t = 0; t < kTaps; ++t)
480 weights[t] = r0[t] + g * (r1[t] - r0[t]);
481 return kTaps;
482 }
483 // Stretched kernel: |k - frac| * fc in table units, one step of fc per tap.
484 const auto& table = kernelTable();
485 const double step = fc * kTablePerUnit;
486 double x = (static_cast<double>(-half + 1) - frac) * step;
487 const size_t last = table.size() - 1;
488 for (int t = 0; t < 2 * half; ++t, x += step)
489 {
490 const double u = std::abs(x);
491 const size_t iu = static_cast<size_t>(u);
492 double w = 0.0;
493 if (iu < last)
494 {
495 const double f = u - static_cast<double>(iu);
496 w = table[iu] + f * (table[iu + 1] - table[iu]);
497 }
498 weights[t] = static_cast<T>(w * fc);
499 }
500 return 2 * half;
501 }
502
504 static const T* unitRows(double frac, T& g) noexcept
505 {
506 const double qf = frac * kPhases;
507 const int q = std::min(static_cast<int>(qf), kPhases - 1);
508 g = static_cast<T>(qf - static_cast<double>(q));
509 return polyphaseTable().data() + static_cast<size_t>(q) * kTaps;
510 }
511
513 template <int C>
514 static void gatherRows(const T* r0, T g, const T* x0, const T* x1, T* out) noexcept
515 {
516#if defined(DSPARK_SIMD_EXACT_AVX2) && !defined(DSPARK_SIMD_EXACT_AVX2_DISPATCHED)
517 sampleGatherAvx2<C>(r0, r0 + kTaps, g, x0, x1, kTaps, out);
518#else
519 #if defined(DSPARK_SIMD_EXACT_AVX2_DISPATCHED)
521 {
522 sampleGatherAvx2<C>(r0, r0 + kTaps, g, x0, x1, kTaps, out);
523 return;
524 }
525 #endif
526 sampleGatherNarrow<C, T>(r0, r0 + kTaps, g, x0, x1, kTaps, out);
527#endif
528 }
529
536 Frame gatherFrame(double ratio, int nCh, T* weights, double& a0, double& a1) noexcept
537 {
538 const SampleZoneData<T>& z = *zone_;
539 const double fc = std::min(1.0, 1.0 / ratio);
540 const int half = static_cast<int>(std::ceil(kHalfTaps / fc));
541 const double loopLen = static_cast<double>(z.loopEnd - z.loopStart);
542 const int zc = z.channels;
543 const int used = (nCh == 1) ? zc : std::min(zc, 2);
544
545 // Sustain loop released: leave the loop once the kernel is clear
546 // of the crossfade region, so no read jumps sources. A loop with no
547 // such position leaves at its wrap, where the baked region starts on
548 // the recording itself.
549 if (releaseLoop_ && (pos_ + half < static_cast<double>(z.loopEnd - z.xfade) || justWrapped_))
550 {
551 loopEngaged_ = false;
552 releaseLoop_ = false;
553 wrapped_ = false;
554 }
555 justWrapped_ = false;
556 if (!loopEngaged_ && pos_ >= static_cast<double>(z.length)) return Frame::Ended;
557
558 const double fl = std::floor(pos_);
559 const int64_t ip = static_cast<int64_t>(fl);
560 const int taps = (fc >= 1.0) ? kTaps : 2 * half;
561
562 const int64_t first = ip - half + 1;
563 const bool direct = first >= 0 && first + taps <= z.length
564 && (!loopEngaged_ || (first + taps <= z.loopEnd - z.xfade
565 && (!wrapped_ || first >= z.loopStart)));
566 double acc[2] = { 0.0, 0.0 };
567 if (direct && fc >= 1.0)
568 {
569 // The blended weights and both channels' dot products in one pass.
570 T g = T(0);
571 const T* rows = unitRows(pos_ - fl, g);
572 for (int c0 = 0; c0 < used; c0 += 2)
573 {
574 const int pair = std::min(2, used - c0);
575 const T* x0 = z.audio.data() + static_cast<size_t>(c0) * static_cast<size_t>(z.length)
576 + static_cast<size_t>(first);
577 T sums[2] = { T(0), T(0) };
578 if (pair == 2)
579 gatherRows<2>(rows, g, x0, x0 + static_cast<size_t>(z.length), sums);
580 else
581 gatherRows<1>(rows, g, x0, nullptr, sums);
582 for (int c = 0; c < pair; ++c)
583 {
584 const auto sum = static_cast<double>(sums[c]);
585 if (nCh == 1) acc[0] += sum / zc;
586 else acc[c0 + c] = sum;
587 }
588 }
589 a0 = acc[0];
590 a1 = acc[1];
591 advanceGather(ratio, half, loopLen);
592 return Frame::Produced;
593 }
594 kernelWeights(weights, pos_ - fl, fc, half);
595 for (int c = 0; c < used; ++c)
596 {
597 const T* chan = z.audio.data() + static_cast<size_t>(c) * static_cast<size_t>(z.length);
598 const T* baked = z.baked.empty() ? nullptr
599 : z.baked.data() + static_cast<size_t>(c) * static_cast<size_t>(z.xfade);
600 double sum = 0.0;
601 if (direct)
602 sum = dot(weights, chan + first, taps);
603 else
604 for (int t = 0; t < taps; ++t)
605 sum += static_cast<double>(weights[t])
606 * fetch(z, chan, baked, first + t, loopEngaged_, wrapped_);
607 if (nCh == 1) acc[0] += sum / zc;
608 else acc[c] = sum;
609 }
610 a0 = acc[0];
611 a1 = acc[1];
612 advanceGather(ratio, half, loopLen);
613 return Frame::Produced;
614 }
615
617 void advanceGather(double ratio, int half, double loopLen) noexcept
618 {
619 const SampleZoneData<T>& z = *zone_;
620 pos_ += ratio;
621 if (loopEngaged_ && pos_ >= static_cast<double>(z.loopEnd))
622 {
623 pos_ -= loopLen;
624 wrapped_ = true;
625 justWrapped_ = z.loopEnd - z.xfade - half <= z.loopStart;
626 }
627 }
628
641 Frame scatterFrame(double ratio, int nCh, T* weights, double& a0, double& a1) noexcept
642 {
643 const SampleZoneData<T>& z = *zone_;
644 const double fc = std::min(1.0, ratio); // output-time kernel scale
645 const int half = static_cast<int>(std::ceil(kHalfTaps / fc));
646 const double spacing = 1.0 / ratio; // output samples per input sample
647 const int zc = z.channels;
648 const int used = (nCh == 1) ? zc : std::min(zc, 2);
649 const int rings = (nCh == 1 || zc == 1) ? 1 : 2;
650
651 // Spread every input whose support reaches this output sample.
652 while (!inputDone_ && tNext_ < static_cast<double>(half))
653 {
654 if (releaseLoop_ && (jIn_ < z.loopEnd - z.xfade || jIn_ == z.loopStart))
655 {
656 loopEngaged_ = false;
657 releaseLoop_ = false;
658 }
659 double x[2] = { 0.0, 0.0 };
660 for (int c = 0; c < used; ++c)
661 {
662 const T* chan = z.audio.data() + static_cast<size_t>(c) * static_cast<size_t>(z.length);
663 const T* baked = z.baked.empty() ? nullptr
664 : z.baked.data() + static_cast<size_t>(c) * static_cast<size_t>(z.xfade);
665 const double sample = fetch(z, chan, baked, jIn_, loopEngaged_);
666 if (rings == 1) x[0] += sample / used;
667 else x[c] = sample;
668 }
669 const double fl = std::floor(tNext_);
670 const int taps = kernelWeights(weights, tNext_ - fl, fc, half);
671 const int base = accPos_ + static_cast<int>(fl) - half + 1;
672 for (int r = 0; r < rings; ++r)
673 {
674 const T xs = static_cast<T>(x[r] * spacing);
675 T* acc = acc_[static_cast<size_t>(r)].data();
676 const T* w = weights;
677 // Taps before the current output are gone.
678 T* out = acc + base;
679 for (int t = std::max(accPos_ - base, 0); t < taps; ++t)
680 out[t] += w[t] * xs;
681 }
682 ++jIn_;
683 if (loopEngaged_ && jIn_ >= z.loopEnd) jIn_ = z.loopStart;
684 if (!loopEngaged_ && jIn_ >= z.length) { inputDone_ = true; drainLeft_ = 2 * half; }
685 tNext_ += spacing;
686 }
687
688 a0 = static_cast<double>(acc_[0][static_cast<size_t>(accPos_)]);
689 a1 = (rings == 2) ? static_cast<double>(acc_[1][static_cast<size_t>(accPos_)]) : a0;
690
691 // Advance the output: the accumulator slides once it nears its end.
692 for (int r = 0; r < rings; ++r) acc_[static_cast<size_t>(r)][static_cast<size_t>(accPos_)] = T(0);
693 ++accPos_;
694 tNext_ -= 1.0;
695 if (accPos_ + 2 * kMaxHalfTaps + 2 >= kAccLength)
696 {
697 const int keep = kAccLength - accPos_;
698 for (int r = 0; r < rings; ++r)
699 {
700 T* acc = acc_[static_cast<size_t>(r)].data();
701 std::copy(acc + accPos_, acc + kAccLength, acc);
702 std::fill(acc + keep, acc + kAccLength, T(0));
703 }
704 accPos_ = 0;
705 }
706 if (inputDone_ && --drainLeft_ <= 0) return Frame::Last;
707 return Frame::Produced;
708 }
709
710 const SampleZoneData<T>* zone_ = nullptr;
711 double pos_ = 0.0;
712 bool loopEngaged_ = false;
713 bool releaseLoop_ = false;
714 bool wrapped_ = false;
715 bool justWrapped_ = false;
716 // Scatter form: the next recording sample to spread, the output time it
717 // falls on (relative to the next output sample), and the output
718 // accumulators it is spread into.
719 bool scatter_ = false;
720 bool inputDone_ = false;
721 int drainLeft_ = 0;
722 int64_t jIn_ = 0;
723 double tNext_ = 0.0;
724 int accPos_ = 0;
725 std::array<std::vector<T>, 2> acc_;
726};
727
728} // namespace dspark::detail
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.
One voice's position in a zone and its band-limited read.
static constexpr int kTaps
static constexpr int kAccLength
void release() noexcept
The key is released: a Sustain loop plays on past its end.
double minRate() const noexcept
Lowest rate next() accepts for this reader.
static const std::vector< T > & polyphaseTable()
static constexpr int kMaxHalfTaps
static constexpr double kBeta
static constexpr double kMinScatterRate
Lowest rate of the scatter form, whose kernel widens as the rate falls.
static constexpr int kWeightsLength
Scratch weights a caller provides to next().
void allocate()
Allocates the scatter accumulators (setup thread).
Frame next(double ratio, int outChannels, T *weights, double &a0, double &a1) noexcept
One output frame at ratio recording samples per output sample.
Frame
What one call produced.
@ Ended
The zone ended before this sample: nothing produced.
@ Produced
A frame was produced.
@ Last
A frame was produced and it was the last one.
static constexpr double kMinGatherRate
static constexpr int kPhases
Phases of the unit-rate polyphase table (rows interpolated linearly).
static constexpr double kMaxRate
Highest playback rate; the kernel then spans 8 x 64 taps.
const SampleZoneData< T > * zone() const noexcept
The zone being read (null before start()).
bool scatters() const noexcept
True when this reader scatters (it started above the recording's rate).
void start(const SampleZoneData< T > &z, double ratio) noexcept
Starts reading a zone from its start offset. A reader that starts above the recording's rate (ratio >...
static constexpr int kHalfTaps
Zero crossings on each side of the kernel at unit rate: 64 taps.
static constexpr int kTablePerUnit
Table points per zero crossing (linear interpolation between them).
static const std::vector< double > & kernelTable()
static constexpr double kCutoff
bool buildSampleZone(const SampleZoneSpec< T > &z, SampleZoneData< T > &d)
Validates and copies a zone, clamping its loop and baking the loop crossfade. False (and d unspecifie...
constexpr int kSampleGatherLanes
void sampleZonePanGains(double pan, int channels, double gain, double &left, double &right, double &mono) noexcept
Output gains of a zone at gain: a mono zone pans with constant power (unity at centre),...
void sampleGatherNarrow(const T *r0, const T *r1, T g, const T *x0, const T *x1, int taps, T *out) noexcept
Unit-scale gather of C (1 or 2) channels: the weights are the rows r0 and r1 blended by g,...
T sampleGatherReduce(const T *lane) noexcept
The final reduction of the eight partial sums.
bool isRuntimeDispatchActive() noexcept
Whether the AVX2+FMA kernels are selected now (see setRuntimeDispatch()).
Definition SimdOps.h:262
SampleLoopMode
How a zone loops.
Definition SampleZone.h:30
@ None
Play once to the end of the recording.
@ Sustain
Loop while the key is held, then play on past the loop end.
One zone, as the caller describes it.
Definition SampleZone.h:39
int rootKey
MIDI key that plays it untransposed.
Definition SampleZone.h:42
double velocityHigh
Highest velocity it answers, 0..1 (inclusive).
Definition SampleZone.h:47
int64_t loopEnd
One past the last sample of the loop.
Definition SampleZone.h:53
AudioBufferView< const T > audio
The recording (1 or more channels).
Definition SampleZone.h:40
int64_t loopCrossfade
Crossfade length in samples (0 = hard loop).
Definition SampleZone.h:54
int64_t startOffset
First sample played.
Definition SampleZone.h:50
double gainDb
Zone gain.
Definition SampleZone.h:48
double pan
-1 left .. +1 right (balance for multichannel).
Definition SampleZone.h:49
int64_t loopStart
First sample of the loop.
Definition SampleZone.h:52
SampleLoopMode loopMode
Definition SampleZone.h:51
int keyLow
Lowest key it answers (inclusive).
Definition SampleZone.h:44
double tuneCents
Fine tuning added to every note.
Definition SampleZone.h:43
double sampleRate
Its sample rate.
Definition SampleZone.h:41
double velocityLow
Lowest velocity it answers, 0..1 (inclusive).
Definition SampleZone.h:46
int keyHigh
Highest key it answers (inclusive).
Definition SampleZone.h:45
One validated zone, its audio copied and its loop crossfade baked.
std::vector< T > audio
Channel-major, length per channel.
std::vector< T > baked
Crossfaded copy of [loopEnd - xfade, loopEnd).