DSPark 1.9.0
Header-only C++20 DSP for real-time and offline audio
Loading...
Searching...
No Matches
WavetableBank.h
1// DSPark - Professional Audio DSP Framework
2// Copyright (c) 2026 Cristian Moresi - MIT License
3
4#pragma once
5
72#include "DspMath.h"
73#include "FFT.h"
74#include "SimdOps.h"
75
76#include <algorithm>
77#include <array>
78#include <cmath>
79#include <cstddef>
80#include <cstdint>
81#include <type_traits>
82#include <vector>
83
84namespace dspark {
85
86namespace detail {
87
90inline constexpr std::array<double, 18> kWavetableNiemitalo = {
91 0.41496902959240894, 0.08343081932889224, 0.00160015038681571,
92 0.31625515004859783, 0.21197848565176958, 0.00956166668408054,
93 -0.203271896548875371, 0.17989908432249280, 0.02337283412161328,
94 -0.20209241069835732, 0.01760734419526000, 0.02985927012435252,
95 0.04100948858761910, -0.06147760875085254, 0.02046802954581191,
96 0.06607747864416924, -0.03255079211953620, 0.00628989632244913 };
97
100{
101 bool two = false;
102 bool same = true;
103 int numFrames = 0;
104 double sizeA = 0.0, sizeB = 0.0;
105 size_t strideA = 0, strideB = 0;
106 const float* baseA = nullptr;
107 const float* baseB = nullptr;
108};
109
113{
114 size_t f0 = 0;
115 size_t step = 0;
116 double t = 0.0;
117};
118
119[[nodiscard]] inline WavetableFrame wavetableFrame(double position, int numFrames) noexcept
120{
121 const double maxPos = static_cast<double>(numFrames - 1);
122 if (!(position > 0.0)) position = 0.0;
123 else if (position > maxPos) position = maxPos;
124 const int f0 = static_cast<int>(position);
126 p.f0 = static_cast<size_t>(f0);
127 p.step = (f0 < numFrames - 1) ? 1u : 0u;
128 p.t = position - static_cast<double>(f0);
129 return p;
130}
131
134
135} // namespace detail
136
137// The lane loops of the block kernels must be unrolled for the rows to stay in
138// registers; GCC does not always do it on its own at -O2.
139#if defined(__GNUC__)
140 #define DSPARK_WAVETABLE_UNROLL _Pragma("GCC unroll 8")
141#else
142 #define DSPARK_WAVETABLE_UNROLL
143#endif
144
145// Lane operations for the block kernels of detail/WavetableKernels.inl, one
146// pair of structs per instruction set: four float or two double lanes on SSE2
147// and NEON, eight or four with AVX2. The kernels are included once per set.
148#if defined(DSPARK_SIMD_SSE2) || defined(DSPARK_SIMD_NEON)
149 #define DSPARK_WAVETABLE_NARROW 1
150namespace detail {
151namespace wavetable_narrow {
152
153#if defined(DSPARK_SIMD_SSE2)
155struct FloatLanes
156{
157 using S = float;
158 using V = __m128;
159 static constexpr int N = 4;
160
161 struct Rows
162 {
163 V lo[4];
164 V hi[2];
165 };
166
167 static V add(V a, V b) noexcept { return _mm_add_ps(a, b); }
168 static V sub(V a, V b) noexcept { return _mm_sub_ps(a, b); }
169 static V mul(V a, V b) noexcept { return _mm_mul_ps(a, b); }
170 static V set1(float x) noexcept { return _mm_set1_ps(x); }
171 static void store(float* p, V v) noexcept { _mm_storeu_ps(p, v); }
172
175 static bool inRange(const double* ph) noexcept
176 {
177 const __m128 a = _mm_castpd_ps(_mm_loadu_pd(ph));
178 const __m128 b = _mm_castpd_ps(_mm_loadu_pd(ph + 2));
179 const __m128i hi = _mm_castps_si128(_mm_shuffle_ps(a, b, _MM_SHUFFLE(3, 1, 3, 1)));
180 const __m128i flip = _mm_set1_epi32(static_cast<int>(0x80000000u));
181 const __m128i bad = _mm_cmpgt_epi32(_mm_xor_si128(hi, flip),
182 _mm_set1_epi32(static_cast<int>(0x3FEFFFFFu ^ 0x80000000u)));
183 return _mm_movemask_epi8(bad) == 0;
184 }
185
188 static V grid(const double* ph, double size, uint32_t* idx) noexcept
189 {
190 const __m128d sz = _mm_set1_pd(size);
191 const __m128d p0 = _mm_mul_pd(_mm_loadu_pd(ph), sz);
192 const __m128d p1 = _mm_mul_pd(_mm_loadu_pd(ph + 2), sz);
193 const __m128i i0 = _mm_cvttpd_epi32(p0), i1 = _mm_cvttpd_epi32(p1);
194 _mm_storeu_si128(reinterpret_cast<__m128i*>(idx), _mm_unpacklo_epi64(i0, i1));
195 return _mm_movelh_ps(_mm_cvtpd_ps(_mm_sub_pd(p0, _mm_cvtepi32_pd(i0))),
196 _mm_cvtpd_ps(_mm_sub_pd(p1, _mm_cvtepi32_pd(i1))));
197 }
198
199 static void frames(const double* pos, double maxPos, int32_t* f0, float* t) noexcept
200 {
201 const __m128d mx = _mm_set1_pd(maxPos), zero = _mm_setzero_pd();
202 __m128 frac[2];
203 DSPARK_WAVETABLE_UNROLL
204 for (int h = 0; h < 2; ++h)
205 {
206 const __m128d p = _mm_loadu_pd(pos + 2 * h);
207 const __m128d c = _mm_and_pd(_mm_cmpgt_pd(p, zero), _mm_min_pd(p, mx));
208 const __m128i i = _mm_cvttpd_epi32(c);
209 f0[2 * h] = _mm_cvtsi128_si32(i);
210 f0[2 * h + 1] = _mm_cvtsi128_si32(_mm_srli_si128(i, 4));
211 frac[h] = _mm_cvtpd_ps(_mm_sub_pd(c, _mm_cvtepi32_pd(i)));
212 }
213 _mm_storeu_ps(t, _mm_movelh_ps(frac[0], frac[1]));
214 }
215
217 static V pair(const float* a, const float* b) noexcept
218 {
219 return _mm_castsi128_ps(_mm_unpacklo_epi64(_mm_loadl_epi64(reinterpret_cast<const __m128i*>(a)),
220 _mm_loadl_epi64(reinterpret_cast<const __m128i*>(b))));
221 }
222
223 static V lerp(V a, V b, V t) noexcept { return add(a, mul(t, sub(b, a))); }
224
225 // Each pair of lanes reads its row pointers and blends before its first
226 // store, so the stores cannot force them to be recomputed.
227 template <bool Blend, class At, class Step, class Tl>
228 static void gather(Rows& r, const At& at, const Step& step, const Tl& t) noexcept
229 {
230 DSPARK_WAVETABLE_UNROLL
231 for (int k = 0; k < 2; ++k)
232 {
233 const int l = 2 * k;
234 const float* const p0 = at(l);
235 const float* const p1 = at(l + 1);
236 if constexpr (Blend)
237 {
238 const float* const q0 = p0 + step(l);
239 const float* const q1 = p1 + step(l + 1);
240 const float t0 = t(l), t1 = t(l + 1);
241 r.lo[l] = lerp(_mm_loadu_ps(p0), _mm_loadu_ps(q0), _mm_set1_ps(t0));
242 r.lo[l + 1] = lerp(_mm_loadu_ps(p1), _mm_loadu_ps(q1), _mm_set1_ps(t1));
243 r.hi[k] = lerp(pair(p0 + 4, p1 + 4), pair(q0 + 4, q1 + 4), _mm_setr_ps(t0, t0, t1, t1));
244 }
245 else
246 {
247 r.lo[l] = _mm_loadu_ps(p0);
248 r.lo[l + 1] = _mm_loadu_ps(p1);
249 r.hi[k] = pair(p0 + 4, p1 + 4);
250 }
251 }
252 }
253
254 template <bool Blend, class AtA, class StepA, class AtB, class StepB, class Tl>
255 static void gatherMix(Rows& r, const AtA& atA, const StepA& stepA, const AtB& atB, const StepB& stepB,
256 const Tl& t, V w) noexcept
257 {
258 DSPARK_WAVETABLE_UNROLL
259 for (int k = 0; k < 2; ++k)
260 {
261 const int l = 2 * k;
262 const float* const pa0 = atA(l);
263 const float* const pa1 = atA(l + 1);
264 const float* const pb0 = atB(l);
265 const float* const pb1 = atB(l + 1);
266 V a0 = _mm_loadu_ps(pa0), a1 = _mm_loadu_ps(pa1), ah = pair(pa0 + 4, pa1 + 4);
267 V b0 = _mm_loadu_ps(pb0), b1 = _mm_loadu_ps(pb1), bh = pair(pb0 + 4, pb1 + 4);
268 if constexpr (Blend)
269 {
270 const float* const qa0 = pa0 + stepA(l);
271 const float* const qa1 = pa1 + stepA(l + 1);
272 const float* const qb0 = pb0 + stepB(l);
273 const float* const qb1 = pb1 + stepB(l + 1);
274 const float s0 = t(l), s1 = t(l + 1);
275 const V t0 = _mm_set1_ps(s0), t1 = _mm_set1_ps(s1);
276 const V th = _mm_setr_ps(s0, s0, s1, s1);
277 a0 = lerp(a0, _mm_loadu_ps(qa0), t0);
278 a1 = lerp(a1, _mm_loadu_ps(qa1), t1);
279 ah = lerp(ah, pair(qa0 + 4, qa1 + 4), th);
280 b0 = lerp(b0, _mm_loadu_ps(qb0), t0);
281 b1 = lerp(b1, _mm_loadu_ps(qb1), t1);
282 bh = lerp(bh, pair(qb0 + 4, qb1 + 4), th);
283 }
284 r.lo[l] = lerp(b0, a0, w);
285 r.lo[l + 1] = lerp(b1, a1, w);
286 r.hi[k] = lerp(bh, ah, w);
287 }
288 }
289
290 static void columns(const Rows& r, V* y) noexcept
291 {
292 __m128 a = r.lo[0], b = r.lo[1], c = r.lo[2], d = r.lo[3];
293 _MM_TRANSPOSE4_PS(a, b, c, d);
294 y[0] = a;
295 y[1] = b;
296 y[2] = c;
297 y[3] = d;
298 y[4] = _mm_shuffle_ps(r.hi[0], r.hi[1], _MM_SHUFFLE(2, 0, 2, 0));
299 y[5] = _mm_shuffle_ps(r.hi[0], r.hi[1], _MM_SHUFFLE(3, 1, 3, 1));
300 }
301};
302
304struct DoubleLanes
305{
306 using S = double;
307 using V = __m128d;
308 static constexpr int N = 2;
309
310 struct Rows
311 {
312 V r[2][3];
313 };
314
315 static V add(V a, V b) noexcept { return _mm_add_pd(a, b); }
316 static V sub(V a, V b) noexcept { return _mm_sub_pd(a, b); }
317 static V mul(V a, V b) noexcept { return _mm_mul_pd(a, b); }
318 static V set1(double x) noexcept { return _mm_set1_pd(x); }
319 static void store(double* p, V v) noexcept { _mm_storeu_pd(p, v); }
320
321 static bool inRange(const double* ph) noexcept
322 {
323 const __m128d v = _mm_loadu_pd(ph);
324 const __m128d ok = _mm_and_pd(_mm_cmpge_pd(v, _mm_setzero_pd()), _mm_cmplt_pd(v, _mm_set1_pd(1.0)));
325 return _mm_movemask_pd(ok) == 3;
326 }
327
328 static V grid(const double* ph, double size, uint32_t* idx) noexcept
329 {
330 const __m128d p = _mm_mul_pd(_mm_loadu_pd(ph), _mm_set1_pd(size));
331 const __m128i i = _mm_cvttpd_epi32(p);
332 _mm_storel_epi64(reinterpret_cast<__m128i*>(idx), i);
333 return _mm_sub_pd(p, _mm_cvtepi32_pd(i));
334 }
335
336 static void frames(const double* pos, double maxPos, int32_t* f0, double* t) noexcept
337 {
338 const __m128d p = _mm_loadu_pd(pos);
339 const __m128d c = _mm_and_pd(_mm_cmpgt_pd(p, _mm_setzero_pd()), _mm_min_pd(p, _mm_set1_pd(maxPos)));
340 const __m128i i = _mm_cvttpd_epi32(c);
341 f0[0] = _mm_cvtsi128_si32(i);
342 f0[1] = _mm_cvtsi128_si32(_mm_srli_si128(i, 4));
343 _mm_storeu_pd(t, _mm_sub_pd(c, _mm_cvtepi32_pd(i)));
344 }
345
347 static V pair(const float* p) noexcept
348 {
349 return _mm_cvtps_pd(_mm_castsi128_ps(_mm_loadl_epi64(reinterpret_cast<const __m128i*>(p))));
350 }
351
352 static V lerp(V a, V b, V t) noexcept { return add(a, mul(t, sub(b, a))); }
353
354 // Each lane's row pointers and blend are read before its first store, so
355 // the stores cannot force them to be recomputed.
356 template <bool Blend, class At, class Step, class Tl>
357 static void gather(Rows& r, const At& at, const Step& step, const Tl& t) noexcept
358 {
359 DSPARK_WAVETABLE_UNROLL
360 for (int l = 0; l < 2; ++l)
361 {
362 const float* const p = at(l);
363 if constexpr (Blend)
364 {
365 const float* const q = p + step(l);
366 const V tl = _mm_set1_pd(t(l));
367 for (int k = 0; k < 3; ++k) r.r[l][k] = lerp(pair(p + 2 * k), pair(q + 2 * k), tl);
368 }
369 else
370 {
371 for (int k = 0; k < 3; ++k) r.r[l][k] = pair(p + 2 * k);
372 }
373 }
374 }
375
376 template <bool Blend, class AtA, class StepA, class AtB, class StepB, class Tl>
377 static void gatherMix(Rows& r, const AtA& atA, const StepA& stepA, const AtB& atB, const StepB& stepB,
378 const Tl& t, V w) noexcept
379 {
380 DSPARK_WAVETABLE_UNROLL
381 for (int l = 0; l < 2; ++l)
382 {
383 const float* const pa = atA(l);
384 const float* const pb = atB(l);
385 if constexpr (Blend)
386 {
387 const float* const qa = pa + stepA(l);
388 const float* const qb = pb + stepB(l);
389 const V tl = _mm_set1_pd(t(l));
390 for (int k = 0; k < 3; ++k)
391 {
392 const V a = lerp(pair(pa + 2 * k), pair(qa + 2 * k), tl);
393 const V b = lerp(pair(pb + 2 * k), pair(qb + 2 * k), tl);
394 r.r[l][k] = lerp(b, a, w);
395 }
396 }
397 else
398 {
399 for (int k = 0; k < 3; ++k) r.r[l][k] = lerp(pair(pb + 2 * k), pair(pa + 2 * k), w);
400 }
401 }
402 }
403
404 static void columns(const Rows& r, V* y) noexcept
405 {
406 DSPARK_WAVETABLE_UNROLL
407 for (int k = 0; k < 3; ++k)
408 {
409 y[2 * k] = _mm_unpacklo_pd(r.r[0][k], r.r[1][k]);
410 y[2 * k + 1] = _mm_unpackhi_pd(r.r[0][k], r.r[1][k]);
411 }
412 }
413};
414#else // NEON
416struct FloatLanes
417{
418 using S = float;
419 using V = float32x4_t;
420 static constexpr int N = 4;
421
422 struct Rows
423 {
424 V lo[4];
425 V hi[2];
426 };
427
428 static V add(V a, V b) noexcept { return vaddq_f32(a, b); }
429 static V sub(V a, V b) noexcept { return vsubq_f32(a, b); }
430 static V mul(V a, V b) noexcept { return vmulq_f32(a, b); }
431 static V set1(float x) noexcept { return vdupq_n_f32(x); }
432 static void store(float* p, V v) noexcept { vst1q_f32(p, v); }
433
434 static bool inRange(const double* ph) noexcept
435 {
436 const float64x2_t one = vdupq_n_f64(1.0), zero = vdupq_n_f64(0.0);
437 const float64x2_t a = vld1q_f64(ph), b = vld1q_f64(ph + 2);
438 const uint64x2_t ok = vandq_u64(vandq_u64(vcgeq_f64(a, zero), vcltq_f64(a, one)),
439 vandq_u64(vcgeq_f64(b, zero), vcltq_f64(b, one)));
440 return vgetq_lane_u64(ok, 0) != 0 && vgetq_lane_u64(ok, 1) != 0;
441 }
442
443 static V grid(const double* ph, double size, uint32_t* idx) noexcept
444 {
445 const float64x2_t sz = vdupq_n_f64(size);
446 const float64x2_t p0 = vmulq_f64(vld1q_f64(ph), sz), p1 = vmulq_f64(vld1q_f64(ph + 2), sz);
447 const int64x2_t i0 = vcvtq_s64_f64(p0), i1 = vcvtq_s64_f64(p1); // toward zero, as the cast
448 idx[0] = static_cast<uint32_t>(vgetq_lane_s64(i0, 0));
449 idx[1] = static_cast<uint32_t>(vgetq_lane_s64(i0, 1));
450 idx[2] = static_cast<uint32_t>(vgetq_lane_s64(i1, 0));
451 idx[3] = static_cast<uint32_t>(vgetq_lane_s64(i1, 1));
452 return vcombine_f32(vcvt_f32_f64(vsubq_f64(p0, vcvtq_f64_s64(i0))),
453 vcvt_f32_f64(vsubq_f64(p1, vcvtq_f64_s64(i1))));
454 }
455
456 static void frames(const double* pos, double maxPos, int32_t* f0, float* t) noexcept
457 {
458 float32x2_t frac[2];
459 DSPARK_WAVETABLE_UNROLL
460 for (int h = 0; h < 2; ++h)
461 {
462 const float64x2_t p = vld1q_f64(pos + 2 * h);
463 // FMIN returns NaN for a NaN input; the mask clears it to 0, as read().
464 const uint64x2_t c = vandq_u64(vcgtq_f64(p, vdupq_n_f64(0.0)),
465 vreinterpretq_u64_f64(vminq_f64(p, vdupq_n_f64(maxPos))));
466 const float64x2_t cd = vreinterpretq_f64_u64(c);
467 const int64x2_t i = vcvtq_s64_f64(cd);
468 f0[2 * h] = static_cast<int32_t>(vgetq_lane_s64(i, 0));
469 f0[2 * h + 1] = static_cast<int32_t>(vgetq_lane_s64(i, 1));
470 frac[h] = vcvt_f32_f64(vsubq_f64(cd, vcvtq_f64_s64(i)));
471 }
472 vst1q_f32(t, vcombine_f32(frac[0], frac[1]));
473 }
474
475 static V pair(const float* a, const float* b) noexcept { return vcombine_f32(vld1_f32(a), vld1_f32(b)); }
476
477 static V lerp(V a, V b, V t) noexcept { return add(a, mul(t, sub(b, a))); }
478
479 template <bool Blend, class At, class Step, class Tl>
480 static void gather(Rows& r, const At& at, const Step& step, const Tl& t) noexcept
481 {
482 DSPARK_WAVETABLE_UNROLL
483 for (int k = 0; k < 2; ++k)
484 {
485 const int l = 2 * k;
486 r.lo[l] = vld1q_f32(at(l));
487 r.lo[l + 1] = vld1q_f32(at(l + 1));
488 r.hi[k] = pair(at(l) + 4, at(l + 1) + 4);
489 if constexpr (Blend)
490 {
491 r.lo[l] = lerp(r.lo[l], vld1q_f32((at(l) + step(l))), vdupq_n_f32(t(l)));
492 r.lo[l + 1] = lerp(r.lo[l + 1], vld1q_f32((at(l + 1) + step(l + 1))), vdupq_n_f32(t(l + 1)));
493 r.hi[k] = lerp(r.hi[k], pair((at(l) + step(l)) + 4, (at(l + 1) + step(l + 1)) + 4),
494 vcombine_f32(vdup_n_f32(t(l)), vdup_n_f32(t(l + 1))));
495 }
496 }
497 }
498
499 template <bool Blend, class AtA, class StepA, class AtB, class StepB, class Tl>
500 static void gatherMix(Rows& r, const AtA& atA, const StepA& stepA, const AtB& atB, const StepB& stepB,
501 const Tl& t, V w) noexcept
502 {
503 DSPARK_WAVETABLE_UNROLL
504 for (int k = 0; k < 2; ++k)
505 {
506 const int l = 2 * k;
507 V a0 = vld1q_f32(atA(l)), a1 = vld1q_f32(atA(l + 1)), ah = pair(atA(l) + 4, atA(l + 1) + 4);
508 V b0 = vld1q_f32(atB(l)), b1 = vld1q_f32(atB(l + 1)), bh = pair(atB(l) + 4, atB(l + 1) + 4);
509 if constexpr (Blend)
510 {
511 const V t0 = vdupq_n_f32(t(l)), t1 = vdupq_n_f32(t(l + 1));
512 const V th = vcombine_f32(vdup_n_f32(t(l)), vdup_n_f32(t(l + 1)));
513 a0 = lerp(a0, vld1q_f32((atA(l) + stepA(l))), t0);
514 a1 = lerp(a1, vld1q_f32((atA(l + 1) + stepA(l + 1))), t1);
515 ah = lerp(ah, pair((atA(l) + stepA(l)) + 4, (atA(l + 1) + stepA(l + 1)) + 4), th);
516 b0 = lerp(b0, vld1q_f32((atB(l) + stepB(l))), t0);
517 b1 = lerp(b1, vld1q_f32((atB(l + 1) + stepB(l + 1))), t1);
518 bh = lerp(bh, pair((atB(l) + stepB(l)) + 4, (atB(l + 1) + stepB(l + 1)) + 4), th);
519 }
520 r.lo[l] = lerp(b0, a0, w);
521 r.lo[l + 1] = lerp(b1, a1, w);
522 r.hi[k] = lerp(bh, ah, w);
523 }
524 }
525
526 static void columns(const Rows& r, V* y) noexcept
527 {
528 const float32x4x2_t t01 = vtrnq_f32(r.lo[0], r.lo[1]); // a0 b0 a2 b2 | a1 b1 a3 b3
529 const float32x4x2_t t23 = vtrnq_f32(r.lo[2], r.lo[3]); // c0 d0 c2 d2 | c1 d1 c3 d3
530 y[0] = vcombine_f32(vget_low_f32(t01.val[0]), vget_low_f32(t23.val[0]));
531 y[1] = vcombine_f32(vget_low_f32(t01.val[1]), vget_low_f32(t23.val[1]));
532 y[2] = vcombine_f32(vget_high_f32(t01.val[0]), vget_high_f32(t23.val[0]));
533 y[3] = vcombine_f32(vget_high_f32(t01.val[1]), vget_high_f32(t23.val[1]));
534 const float32x4x2_t h = vuzpq_f32(r.hi[0], r.hi[1]); // even | odd elements
535 y[4] = h.val[0];
536 y[5] = h.val[1];
537 }
538};
539
543struct DoubleLanes
544{
545 using S = double;
546 using V = float64x2_t;
547 static constexpr int N = 2;
548
549 struct Rows
550 {
551 V r[2][3];
552 };
553
554 static V add(V a, V b) noexcept { return vaddq_f64(a, b); }
555 static V sub(V a, V b) noexcept { return vsubq_f64(a, b); }
556 static V mul(V a, V b) noexcept { return vmulq_f64(a, b); }
557 static V set1(double x) noexcept { return vdupq_n_f64(x); }
558 static void store(double* p, V v) noexcept { vst1q_f64(p, v); }
559
560 static bool inRange(const double* ph) noexcept
561 {
562 const float64x2_t v = vld1q_f64(ph);
563 const uint64x2_t ok = vandq_u64(vcgeq_f64(v, vdupq_n_f64(0.0)), vcltq_f64(v, vdupq_n_f64(1.0)));
564 return vgetq_lane_u64(ok, 0) != 0 && vgetq_lane_u64(ok, 1) != 0;
565 }
566
567 static V grid(const double* ph, double size, uint32_t* idx) noexcept
568 {
569 const float64x2_t p = vmulq_f64(vld1q_f64(ph), vdupq_n_f64(size));
570 const int64x2_t i = vcvtq_s64_f64(p);
571 idx[0] = static_cast<uint32_t>(vgetq_lane_s64(i, 0));
572 idx[1] = static_cast<uint32_t>(vgetq_lane_s64(i, 1));
573 return vsubq_f64(p, vcvtq_f64_s64(i));
574 }
575
576 static void frames(const double* pos, double maxPos, int32_t* f0, double* t) noexcept
577 {
578 const float64x2_t p = vld1q_f64(pos);
579 const uint64x2_t c = vandq_u64(vcgtq_f64(p, vdupq_n_f64(0.0)),
580 vreinterpretq_u64_f64(vminq_f64(p, vdupq_n_f64(maxPos))));
581 const float64x2_t cd = vreinterpretq_f64_u64(c);
582 const int64x2_t i = vcvtq_s64_f64(cd);
583 f0[0] = static_cast<int32_t>(vgetq_lane_s64(i, 0));
584 f0[1] = static_cast<int32_t>(vgetq_lane_s64(i, 1));
585 vst1q_f64(t, vsubq_f64(cd, vcvtq_f64_s64(i)));
586 }
587
588 static V pair(const float* p) noexcept { return vcvt_f64_f32(vld1_f32(p)); }
589
590 static V lerp(V a, V b, V t) noexcept { return add(a, mul(t, sub(b, a))); }
591
592 template <bool Blend, class At, class Step, class Tl>
593 static void gather(Rows& r, const At& at, const Step& step, const Tl& t) noexcept
594 {
595 DSPARK_WAVETABLE_UNROLL
596 for (int l = 0; l < 2; ++l)
597 for (int k = 0; k < 3; ++k)
598 {
599 r.r[l][k] = pair(at(l) + 2 * k);
600 if constexpr (Blend) r.r[l][k] = lerp(r.r[l][k], pair((at(l) + step(l)) + 2 * k), vdupq_n_f64(t(l)));
601 }
602 }
603
604 template <bool Blend, class AtA, class StepA, class AtB, class StepB, class Tl>
605 static void gatherMix(Rows& r, const AtA& atA, const StepA& stepA, const AtB& atB, const StepB& stepB,
606 const Tl& t, V w) noexcept
607 {
608 DSPARK_WAVETABLE_UNROLL
609 for (int l = 0; l < 2; ++l)
610 for (int k = 0; k < 3; ++k)
611 {
612 V a = pair(atA(l) + 2 * k), b = pair(atB(l) + 2 * k);
613 if constexpr (Blend)
614 {
615 const V tl = vdupq_n_f64(t(l));
616 a = lerp(a, pair((atA(l) + stepA(l)) + 2 * k), tl);
617 b = lerp(b, pair((atB(l) + stepB(l)) + 2 * k), tl);
618 }
619 r.r[l][k] = lerp(b, a, w);
620 }
621 }
622
623 static void columns(const Rows& r, V* y) noexcept
624 {
625 DSPARK_WAVETABLE_UNROLL
626 for (int k = 0; k < 3; ++k)
627 {
628 y[2 * k] = vzip1q_f64(r.r[0][k], r.r[1][k]);
629 y[2 * k + 1] = vzip2q_f64(r.r[0][k], r.r[1][k]);
630 }
631 }
632};
633#endif
634
635#include "detail/WavetableKernels.inl"
636
637} // namespace wavetable_narrow
638} // namespace detail
639#endif
640
641// AVX2 lanes, used when the CPU has AVX2 (selected at run time in x86-64
642// baseline builds; always in AVX2 builds). They are built in SimdOps.h's
643// exact AVX2 region, without FMA, so they compute what read() computes,
644// operation for operation.
645#if defined(DSPARK_SIMD_EXACT_AVX2)
646DSPARK_SIMD_EXACT_AVX2_BEGIN
647namespace detail {
648namespace wavetable_avx2 {
649
651struct FloatLanes
652{
653 using S = float;
654 using V = __m256;
655 static constexpr int N = 8;
656
657 struct Rows
658 {
659 V r[8];
660 };
661
662 static V add(V a, V b) noexcept { return _mm256_add_ps(a, b); }
663 static V sub(V a, V b) noexcept { return _mm256_sub_ps(a, b); }
664 static V mul(V a, V b) noexcept { return _mm256_mul_ps(a, b); }
665 static V set1(float x) noexcept { return _mm256_set1_ps(x); }
666 static void store(float* p, V v) noexcept { _mm256_storeu_ps(p, v); }
667
668 static bool inRange(const double* ph) noexcept
669 {
670 const __m256d zero = _mm256_setzero_pd(), one = _mm256_set1_pd(1.0);
671 const __m256d a = _mm256_loadu_pd(ph), b = _mm256_loadu_pd(ph + 4);
672 const __m256d ok = _mm256_and_pd(_mm256_and_pd(_mm256_cmp_pd(a, zero, _CMP_GE_OQ), _mm256_cmp_pd(a, one, _CMP_LT_OQ)),
673 _mm256_and_pd(_mm256_cmp_pd(b, zero, _CMP_GE_OQ), _mm256_cmp_pd(b, one, _CMP_LT_OQ)));
674 return _mm256_movemask_pd(ok) == 0xF;
675 }
676
677 static V grid(const double* ph, double size, uint32_t* idx) noexcept
678 {
679 const __m256d sz = _mm256_set1_pd(size);
680 const __m256d p0 = _mm256_mul_pd(_mm256_loadu_pd(ph), sz);
681 const __m256d p1 = _mm256_mul_pd(_mm256_loadu_pd(ph + 4), sz);
682 const __m128i i0 = _mm256_cvttpd_epi32(p0), i1 = _mm256_cvttpd_epi32(p1);
683 _mm_storeu_si128(reinterpret_cast<__m128i*>(idx), i0);
684 _mm_storeu_si128(reinterpret_cast<__m128i*>(idx + 4), i1);
685 const __m128 x0 = _mm256_cvtpd_ps(_mm256_sub_pd(p0, _mm256_cvtepi32_pd(i0)));
686 const __m128 x1 = _mm256_cvtpd_ps(_mm256_sub_pd(p1, _mm256_cvtepi32_pd(i1)));
687 return _mm256_insertf128_ps(_mm256_castps128_ps256(x0), x1, 1);
688 }
689
690 static void frames(const double* pos, double maxPos, int32_t* f0, float* t) noexcept
691 {
692 const __m256d zero = _mm256_setzero_pd(), mx = _mm256_set1_pd(maxPos);
693 DSPARK_WAVETABLE_UNROLL
694 for (int h = 0; h < 2; ++h)
695 {
696 const __m256d p = _mm256_loadu_pd(pos + 4 * h);
697 const __m256d c = _mm256_and_pd(_mm256_cmp_pd(p, zero, _CMP_GT_OQ), _mm256_min_pd(p, mx));
698 const __m128i i = _mm256_cvttpd_epi32(c);
699 _mm_storeu_si128(reinterpret_cast<__m128i*>(f0 + 4 * h), i);
700 _mm_storeu_ps(t + 4 * h, _mm256_cvtpd_ps(_mm256_sub_pd(c, _mm256_cvtepi32_pd(i))));
701 }
702 }
703
704 static V lerp(V a, V b, V t) noexcept { return add(a, mul(t, sub(b, a))); }
705
706 template <bool Blend, class At, class Step, class Tl>
707 static void gather(Rows& r, const At& at, const Step& step, const Tl& t) noexcept
708 {
709 DSPARK_WAVETABLE_UNROLL
710 for (int l = 0; l < 8; ++l)
711 {
712 r.r[l] = _mm256_loadu_ps(at(l));
713 if constexpr (Blend) r.r[l] = lerp(r.r[l], _mm256_loadu_ps((at(l) + step(l))), _mm256_set1_ps(t(l)));
714 }
715 }
716
717 template <bool Blend, class AtA, class StepA, class AtB, class StepB, class Tl>
718 static void gatherMix(Rows& r, const AtA& atA, const StepA& stepA, const AtB& atB, const StepB& stepB,
719 const Tl& t, V w) noexcept
720 {
721 DSPARK_WAVETABLE_UNROLL
722 for (int l = 0; l < 8; ++l)
723 {
724 V a = _mm256_loadu_ps(atA(l)), b = _mm256_loadu_ps(atB(l));
725 if constexpr (Blend)
726 {
727 const V tl = _mm256_set1_ps(t(l));
728 a = lerp(a, _mm256_loadu_ps((atA(l) + stepA(l))), tl);
729 b = lerp(b, _mm256_loadu_ps((atB(l) + stepB(l))), tl);
730 }
731 r.r[l] = lerp(b, a, w);
732 }
733 }
734
735 static void columns(const Rows& rows, V* y) noexcept
736 {
737 const V* r = rows.r;
738 const V t0 = _mm256_unpacklo_ps(r[0], r[1]), t1 = _mm256_unpackhi_ps(r[0], r[1]);
739 const V t2 = _mm256_unpacklo_ps(r[2], r[3]), t3 = _mm256_unpackhi_ps(r[2], r[3]);
740 const V t4 = _mm256_unpacklo_ps(r[4], r[5]), t5 = _mm256_unpackhi_ps(r[4], r[5]);
741 const V t6 = _mm256_unpacklo_ps(r[6], r[7]), t7 = _mm256_unpackhi_ps(r[6], r[7]);
742 const V s0 = _mm256_shuffle_ps(t0, t2, 0x44), s1 = _mm256_shuffle_ps(t0, t2, 0xEE);
743 const V s2 = _mm256_shuffle_ps(t1, t3, 0x44), s3 = _mm256_shuffle_ps(t1, t3, 0xEE);
744 const V s4 = _mm256_shuffle_ps(t4, t6, 0x44), s5 = _mm256_shuffle_ps(t4, t6, 0xEE);
745 const V s6 = _mm256_shuffle_ps(t5, t7, 0x44), s7 = _mm256_shuffle_ps(t5, t7, 0xEE);
746 y[0] = _mm256_permute2f128_ps(s0, s4, 0x20);
747 y[1] = _mm256_permute2f128_ps(s1, s5, 0x20);
748 y[2] = _mm256_permute2f128_ps(s2, s6, 0x20);
749 y[3] = _mm256_permute2f128_ps(s3, s7, 0x20);
750 y[4] = _mm256_permute2f128_ps(s0, s4, 0x31);
751 y[5] = _mm256_permute2f128_ps(s1, s5, 0x31);
752 }
753};
754
756struct DoubleLanes
757{
758 using S = double;
759 using V = __m256d;
760 static constexpr int N = 4;
761
762 struct Rows
763 {
764 V lo[4];
765 __m128d hi[4];
766 };
767
768 static V add(V a, V b) noexcept { return _mm256_add_pd(a, b); }
769 static V sub(V a, V b) noexcept { return _mm256_sub_pd(a, b); }
770 static V mul(V a, V b) noexcept { return _mm256_mul_pd(a, b); }
771 static V set1(double x) noexcept { return _mm256_set1_pd(x); }
772 static void store(double* p, V v) noexcept { _mm256_storeu_pd(p, v); }
773
774 static bool inRange(const double* ph) noexcept
775 {
776 const __m256d a = _mm256_loadu_pd(ph);
777 const __m256d ok = _mm256_and_pd(_mm256_cmp_pd(a, _mm256_setzero_pd(), _CMP_GE_OQ),
778 _mm256_cmp_pd(a, _mm256_set1_pd(1.0), _CMP_LT_OQ));
779 return _mm256_movemask_pd(ok) == 0xF;
780 }
781
782 static V grid(const double* ph, double size, uint32_t* idx) noexcept
783 {
784 const __m256d p = _mm256_mul_pd(_mm256_loadu_pd(ph), _mm256_set1_pd(size));
785 const __m128i i = _mm256_cvttpd_epi32(p);
786 _mm_storeu_si128(reinterpret_cast<__m128i*>(idx), i);
787 return _mm256_sub_pd(p, _mm256_cvtepi32_pd(i));
788 }
789
790 static void frames(const double* pos, double maxPos, int32_t* f0, double* t) noexcept
791 {
792 const __m256d p = _mm256_loadu_pd(pos);
793 const __m256d c = _mm256_and_pd(_mm256_cmp_pd(p, _mm256_setzero_pd(), _CMP_GT_OQ),
794 _mm256_min_pd(p, _mm256_set1_pd(maxPos)));
795 const __m128i i = _mm256_cvttpd_epi32(c);
796 _mm_storeu_si128(reinterpret_cast<__m128i*>(f0), i);
797 _mm256_storeu_pd(t, _mm256_sub_pd(c, _mm256_cvtepi32_pd(i)));
798 }
799
800 static V lo4(const float* p) noexcept { return _mm256_cvtps_pd(_mm_loadu_ps(p)); }
801 static __m128d hi2(const float* p) noexcept
802 {
803 return _mm_cvtps_pd(_mm_castsi128_ps(_mm_loadl_epi64(reinterpret_cast<const __m128i*>(p + 4))));
804 }
805 static V lerp(V a, V b, V t) noexcept { return add(a, mul(t, sub(b, a))); }
806 static __m128d lerp(__m128d a, __m128d b, __m128d t) noexcept
807 {
808 return _mm_add_pd(a, _mm_mul_pd(t, _mm_sub_pd(b, a)));
809 }
810
811 template <bool Blend, class At, class Step, class Tl>
812 static void gather(Rows& r, const At& at, const Step& step, const Tl& t) noexcept
813 {
814 DSPARK_WAVETABLE_UNROLL
815 for (int l = 0; l < 4; ++l)
816 {
817 r.lo[l] = lo4(at(l));
818 r.hi[l] = hi2(at(l));
819 if constexpr (Blend)
820 {
821 r.lo[l] = lerp(r.lo[l], lo4((at(l) + step(l))), _mm256_set1_pd(t(l)));
822 r.hi[l] = lerp(r.hi[l], hi2((at(l) + step(l))), _mm_set1_pd(t(l)));
823 }
824 }
825 }
826
827 template <bool Blend, class AtA, class StepA, class AtB, class StepB, class Tl>
828 static void gatherMix(Rows& r, const AtA& atA, const StepA& stepA, const AtB& atB, const StepB& stepB,
829 const Tl& t, V w) noexcept
830 {
831 const __m128d w2 = _mm256_castpd256_pd128(w);
832 DSPARK_WAVETABLE_UNROLL
833 for (int l = 0; l < 4; ++l)
834 {
835 V a = lo4(atA(l)), b = lo4(atB(l));
836 __m128d ah = hi2(atA(l)), bh = hi2(atB(l));
837 if constexpr (Blend)
838 {
839 const V tl = _mm256_set1_pd(t(l));
840 const __m128d th = _mm_set1_pd(t(l));
841 a = lerp(a, lo4((atA(l) + stepA(l))), tl);
842 ah = lerp(ah, hi2((atA(l) + stepA(l))), th);
843 b = lerp(b, lo4((atB(l) + stepB(l))), tl);
844 bh = lerp(bh, hi2((atB(l) + stepB(l))), th);
845 }
846 r.lo[l] = lerp(b, a, w);
847 r.hi[l] = lerp(bh, ah, w2);
848 }
849 }
850
851 static void columns(const Rows& r, V* y) noexcept
852 {
853 const V t0 = _mm256_unpacklo_pd(r.lo[0], r.lo[1]), t1 = _mm256_unpackhi_pd(r.lo[0], r.lo[1]);
854 const V t2 = _mm256_unpacklo_pd(r.lo[2], r.lo[3]), t3 = _mm256_unpackhi_pd(r.lo[2], r.lo[3]);
855 y[0] = _mm256_permute2f128_pd(t0, t2, 0x20);
856 y[1] = _mm256_permute2f128_pd(t1, t3, 0x20);
857 y[2] = _mm256_permute2f128_pd(t0, t2, 0x31);
858 y[3] = _mm256_permute2f128_pd(t1, t3, 0x31);
859 const __m128d u0 = _mm_unpacklo_pd(r.hi[0], r.hi[1]), v0 = _mm_unpacklo_pd(r.hi[2], r.hi[3]);
860 const __m128d u1 = _mm_unpackhi_pd(r.hi[0], r.hi[1]), v1 = _mm_unpackhi_pd(r.hi[2], r.hi[3]);
861 y[4] = _mm256_insertf128_pd(_mm256_castpd128_pd256(u0), v0, 1);
862 y[5] = _mm256_insertf128_pd(_mm256_castpd128_pd256(u1), v1, 1);
863 }
864};
865
866#include "detail/WavetableKernels.inl"
867
868} // namespace wavetable_avx2
869} // namespace detail
870DSPARK_SIMD_EXACT_AVX2_END
871#endif
872
873#undef DSPARK_WAVETABLE_UNROLL
874
894{
895public:
897 static constexpr int kMipLevels = 20;
899 static constexpr int kMaxHarmonics = 1023;
901 static constexpr int kMaxFrames = 256;
903 static constexpr int kMaxFrameSize = 1 << 20;
904
906 enum class Builtin
907 {
908 Basic,
909 Harmonic,
910 Formant,
911 Fm
912 };
913 static constexpr int kNumBuiltins = 4;
914
916 enum class Normalization
917 {
918 PerFrame,
919 Bank
920 };
921
923 struct Harmonic
924 {
925 double cosine = 0.0;
926 double sine = 0.0;
927 };
928
930 struct Mip
931 {
932 int level = 0;
933 int next = 0;
934 float weight = 1.0f;
935 };
936
937 WavetableBank() = default;
938
939 // -- Building (setup thread; allocates) ------------------------------------
940
952 template <typename Coefficients>
953 bool buildFromHarmonics(int numFrames, int numHarmonics, Coefficients&& coefficients,
955 {
956 if (numFrames < 1 || numFrames > kMaxFrames || numHarmonics < 1)
957 return false;
958 numHarmonics = std::min(numHarmonics, kMaxHarmonics);
959
960 std::vector<Harmonic> coeffs(static_cast<size_t>(numFrames) * static_cast<size_t>(numHarmonics));
961 for (int f = 0; f < numFrames; ++f)
962 for (int h = 1; h <= numHarmonics; ++h)
963 {
964 const Harmonic c = coefficients(f, h);
965 if (!std::isfinite(c.cosine) || !std::isfinite(c.sine)) return false;
966 coeffs[static_cast<size_t>(f) * static_cast<size_t>(numHarmonics)
967 + static_cast<size_t>(h - 1)] = c;
968 }
969 return build(numFrames, numHarmonics, coeffs, normalization);
970 }
971
986 template <FloatType S>
987 bool loadFrames(const S* data, int frameSize, int numFrames,
988 Normalization normalization = Normalization::Bank)
989 {
990 if (data == nullptr || frameSize < 3 || frameSize > kMaxFrameSize
991 || numFrames < 1 || numFrames > kMaxFrames)
992 return false;
993 const int numHarmonics = std::min((frameSize - 1) / 2, kMaxHarmonics);
994 std::vector<Harmonic> coeffs(static_cast<size_t>(numFrames) * static_cast<size_t>(numHarmonics));
995 std::vector<double> cycle(static_cast<size_t>(frameSize));
996 const bool pow2 = (frameSize & (frameSize - 1)) == 0 && frameSize >= 4;
997 std::vector<double> spec(pow2 ? static_cast<size_t>(frameSize + 2) : 0);
998 FFTReal<double> fft(pow2 ? static_cast<size_t>(frameSize) : 4);
999
1000 for (int f = 0; f < numFrames; ++f)
1001 {
1002 const S* src = data + static_cast<size_t>(f) * static_cast<size_t>(frameSize);
1003 for (int i = 0; i < frameSize; ++i)
1004 cycle[static_cast<size_t>(i)] = std::isfinite(src[i]) ? static_cast<double>(src[i]) : 0.0;
1005 Harmonic* dst = coeffs.data() + static_cast<size_t>(f) * static_cast<size_t>(numHarmonics);
1006 const double scale = 2.0 / static_cast<double>(frameSize);
1007 if (pow2)
1008 {
1009 // X[h] = (N/2) (a_h - j b_h) for x = sum a_h cos + b_h sin.
1010 fft.forward(cycle.data(), spec.data());
1011 for (int h = 1; h <= numHarmonics; ++h)
1012 dst[h - 1] = { spec[static_cast<size_t>(2 * h)] * scale,
1013 -spec[static_cast<size_t>(2 * h + 1)] * scale };
1014 }
1015 else
1016 {
1017 for (int h = 1; h <= numHarmonics; ++h)
1018 {
1019 double sumCos = 0.0, sumSin = 0.0;
1020 for (int i = 0; i < frameSize; ++i)
1021 {
1022 // Integer phase reduction keeps the argument exact.
1023 const auto k = static_cast<long long>(h) * i % frameSize;
1024 const double ph = twoPi<double> * static_cast<double>(k)
1025 / static_cast<double>(frameSize);
1026 sumCos += cycle[static_cast<size_t>(i)] * std::cos(ph);
1027 sumSin += cycle[static_cast<size_t>(i)] * std::sin(ph);
1028 }
1029 dst[h - 1] = { sumCos * scale, sumSin * scale };
1030 }
1031 }
1032 }
1033 return build(numFrames, numHarmonics, coeffs, normalization);
1034 }
1035
1041 [[nodiscard]] static const WavetableBank& builtin(Builtin which)
1042 {
1043 switch (which)
1044 {
1045 case Builtin::Basic: { static const WavetableBank b = makeBasic(); return b; }
1046 case Builtin::Harmonic: { static const WavetableBank b = makeHarmonic(); return b; }
1047 case Builtin::Formant: { static const WavetableBank b = makeFormant(); return b; }
1048 case Builtin::Fm: { static const WavetableBank b = makeFm(); return b; }
1049 }
1050 static const WavetableBank empty;
1051 return empty;
1052 }
1053
1054 // -- Queries -----------------------------------------------------------------
1055
1057 [[nodiscard]] int getNumFrames() const noexcept { return numFrames_; }
1058
1060 [[nodiscard]] int getNumHarmonics() const noexcept { return levelHarmonics_[0]; }
1061
1063 [[nodiscard]] size_t getMemoryBytes() const noexcept { return data_.size() * sizeof(float); }
1064
1065 // -- Playback (real-time safe, any thread) ----------------------------------
1066
1074 [[nodiscard]] Mip selectMip(double frequencyHz, double sampleRate) const noexcept
1075 {
1076 Mip m;
1077 if (numFrames_ == 0 || !(sampleRate > 0.0)) return m;
1078 const double f = std::isfinite(frequencyHz) ? std::abs(frequencyHz) : 1e300;
1079 // Highest harmonic frequency whose alias still lands above 20 kHz
1080 // (never below Nyquist itself: at low rates there is no free band).
1081 const double fold = std::max(sampleRate * 0.5, sampleRate - 20000.0);
1082 const int last = kMipLevels - 1;
1083 int level = 0;
1084 while (level < last && f > fold / static_cast<double>(levelHarmonics_[static_cast<size_t>(level)]))
1085 ++level;
1086 m.level = level;
1087 m.next = std::min(level + 1, last);
1088 if (m.next == level) return m;
1089
1090 // Bottom of this level's range: the previous level's limit, or, for
1091 // level 0, one level-spacing below its own limit.
1092 const double hi = fold / static_cast<double>(levelHarmonics_[static_cast<size_t>(level)]);
1093 const double lo = (level > 0)
1094 ? fold / static_cast<double>(levelHarmonics_[static_cast<size_t>(level - 1)])
1095 : hi * static_cast<double>(levelHarmonics_[1]) / static_cast<double>(levelHarmonics_[0]);
1096 const double span = hi - lo;
1097 m.weight = (span > 0.0) ? static_cast<float>(std::clamp((hi - f) / span, 0.0, 1.0)) : 1.0f;
1098 return m;
1099 }
1100
1109 template <FloatType T>
1110 [[nodiscard]] T read(double phase, double position, const Mip& mip) const noexcept
1111 {
1112 if (numFrames_ == 0) return T(0);
1113 if (!(phase >= 0.0 && phase < 1.0))
1114 {
1115 phase -= std::floor(phase);
1116 if (!(phase >= 0.0 && phase < 1.0)) phase = 0.0;
1117 }
1118 const double maxPos = static_cast<double>(numFrames_ - 1);
1119 if (!(position > 0.0)) position = 0.0; // NaN included
1120 else if (position > maxPos) position = maxPos;
1121 const int f0 = static_cast<int>(position);
1122 const int f1 = (f0 < numFrames_ - 1) ? f0 + 1 : f0;
1123 const T t = static_cast<T>(position - static_cast<double>(f0));
1124
1125 const int a = std::clamp(mip.level, 0, kMipLevels - 1);
1126 const int b = std::clamp(mip.next, 0, kMipLevels - 1);
1127 const T w = static_cast<T>(std::clamp(mip.weight, 0.0f, 1.0f));
1128
1129 T ya[6];
1130 const T xa = gather<T>(a, f0, f1, t, phase, ya);
1131 if (a == b || w >= T(1))
1132 return interpolate(ya, xa);
1133
1134 T yb[6];
1135 if (levelSize_[static_cast<size_t>(a)] == levelSize_[static_cast<size_t>(b)] || hasGridCopy(a, b))
1136 {
1137 // Same grid (b itself or its copy on a's grid): blend the
1138 // samples, interpolate once.
1139 (void)gather<T>(b, f0, f1, t, phase, yb, levelSize_[static_cast<size_t>(a)]);
1140 for (int k = 0; k < 6; ++k) ya[k] = yb[k] + w * (ya[k] - yb[k]);
1141 return interpolate(ya, xa);
1142 }
1143 const T xb = gather<T>(b, f0, f1, t, phase, yb);
1144 const T sa = interpolate(ya, xa);
1145 const T sb = interpolate(yb, xb);
1146 return sb + w * (sa - sb);
1147 }
1148
1164 template <FloatType T>
1165 void readBlock(const double* phases, double position, const Mip& mip, T* out, int n) const noexcept
1166 {
1167 readBlockImpl<T>(phases, nullptr, position, mip, out, n);
1168 }
1169
1178 template <FloatType T>
1179 void readBlock(const double* phases, const double* positions, const Mip& mip,
1180 T* out, int n) const noexcept
1181 {
1182 readBlockImpl<T>(phases, positions, 0.0, mip, out, n);
1183 }
1184
1189 [[nodiscard]] static double interpolatorResponse(double cyclesPerSample) noexcept
1190 {
1191 // The kernel is even, so H(v) = sum_k int_0^1 f_k(x) cos(2 pi v (x - k)) dx,
1192 // f_k being the weight of sample k (offsets -2..3) at fraction x.
1193 // 16-point Gauss-Legendre on each unit piece: the integrand is a
1194 // degree-5 polynomial times a slow cosine.
1195 static constexpr std::array<double, 8> node = {
1196 0.0950125098376374, 0.2816035507792589, 0.4580167776572274, 0.6178762444026438,
1197 0.7554044083550030, 0.8656312023878318, 0.9445750230732326, 0.9894009349916499 };
1198 static constexpr std::array<double, 8> weight = {
1199 0.1894506104550685, 0.1826034150449236, 0.1691565193950025, 0.1495959888165767,
1200 0.1246289712555339, 0.0951585116824928, 0.0622535239386479, 0.0271524594117541 };
1201 double sum = 0.0;
1202 for (int k = -2; k <= 3; ++k)
1203 {
1204 double y[6] = { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 };
1205 y[k + 2] = 1.0;
1206 for (size_t q = 0; q < node.size(); ++q)
1207 for (const double s : { -1.0, 1.0 })
1208 {
1209 const double x = 0.5 + 0.5 * s * node[q];
1210 sum += 0.5 * weight[q] * interpolate(y, x)
1211 * std::cos(twoPi<double> * cyclesPerSample * (x - static_cast<double>(k)));
1212 }
1213 }
1214 return sum;
1215 }
1216
1217private:
1219 static constexpr int kMinTableSize = 2048;
1221 static constexpr int kGuard = 3;
1222
1225 static constexpr std::array<int, kMipLevels> kLevelHarmonics = {
1226 kMaxHarmonics, 724, 512, 362, 256, 181, 128, 90, 64, 45,
1227 32, 22, 16, 11, 8, 5, 4, 3, 2, 1 };
1228
1234 template <FloatType T>
1235 [[nodiscard]] static T interpolate(const T* y, T x) noexcept
1236 {
1237 const auto& k = kNiemitalo;
1238 const T z = x - T(0.5);
1239 const T even1 = y[3] + y[2], odd1 = y[3] - y[2];
1240 const T even2 = y[4] + y[1], odd2 = y[4] - y[1];
1241 const T even3 = y[5] + y[0], odd3 = y[5] - y[0];
1242 const T c0 = even1 * T(k[0]) + even2 * T(k[1]) + even3 * T(k[2]);
1243 const T c1 = odd1 * T(k[3]) + odd2 * T(k[4]) + odd3 * T(k[5]);
1244 const T c2 = even1 * T(k[6]) + even2 * T(k[7]) + even3 * T(k[8]);
1245 const T c3 = odd1 * T(k[9]) + odd2 * T(k[10]) + odd3 * T(k[11]);
1246 const T c4 = even1 * T(k[12]) + even2 * T(k[13]) + even3 * T(k[14]);
1247 const T c5 = odd1 * T(k[15]) + odd2 * T(k[16]) + odd3 * T(k[17]);
1248 return ((((c5 * z + c4) * z + c3) * z + c2) * z + c1) * z + c0;
1249 }
1250
1252 static constexpr const std::array<double, 18>& kNiemitalo = detail::kWavetableNiemitalo;
1253
1258 static constexpr size_t kTailPad = 2;
1259
1265 template <FloatType T>
1266 void readBlockImpl(const double* phases, const double* positions, double position,
1267 const Mip& mip, T* out, int n) const noexcept
1268 {
1269 if (n <= 0 || out == nullptr) return;
1270 if (numFrames_ == 0 || phases == nullptr)
1271 {
1272 std::fill_n(out, n, T(0));
1273 return;
1274 }
1275#if defined(DSPARK_WAVETABLE_NARROW)
1276 const auto w = static_cast<T>(std::clamp(mip.weight, 0.0f, 1.0f));
1277 const detail::WavetableRows s = blockSetup<T>(mip, w);
1278 const int layout = !s.two ? detail::kWavetableOneLevel
1280 const detail::WavetableFrame f = detail::wavetableFrame(position, numFrames_);
1281 #if defined(DSPARK_SIMD_EXACT_AVX2) && defined(DSPARK_SIMD_EXACT_AVX2_DISPATCHED)
1282 const bool wide = simd::isRuntimeDispatchActive();
1283 #elif defined(DSPARK_SIMD_EXACT_AVX2)
1284 constexpr bool wide = true;
1285 #endif
1286 // One narrow group: the most read() may have to take over at once.
1287 constexpr int kGroup = std::is_same_v<T, float> ? 4 : 2;
1288 int j = 0;
1289 while (j < n)
1290 {
1291 const double* pos = positions != nullptr ? positions + j : nullptr;
1292 #if defined(DSPARK_SIMD_EXACT_AVX2)
1293 if (wide)
1294 {
1295 j += detail::wavetable_avx2::readBlockKernel(s, layout, phases + j, pos, f, w, out + j, n - j);
1296 pos = positions != nullptr ? positions + j : nullptr;
1297 }
1298 #endif
1299 j += detail::wavetable_narrow::readBlockKernel(s, layout, phases + j, pos, f, w, out + j, n - j);
1300 for (const int stop = std::min(n, j + kGroup); j < stop; ++j)
1301 out[j] = read<T>(phases[j], positions != nullptr ? positions[j] : position, mip);
1302 }
1303#else
1304 for (int j = 0; j < n; ++j)
1305 out[j] = read<T>(phases[j], positions != nullptr ? positions[j] : position, mip);
1306#endif
1307 }
1308
1309#if defined(DSPARK_WAVETABLE_NARROW)
1311 template <FloatType T>
1312 [[nodiscard]] detail::WavetableRows blockSetup(const Mip& mip, T w) const noexcept
1313 {
1314 detail::WavetableRows s;
1315 s.numFrames = numFrames_;
1316 const int a = std::clamp(mip.level, 0, kMipLevels - 1);
1317 const int b = std::clamp(mip.next, 0, kMipLevels - 1);
1318 s.two = !(a == b || w >= T(1));
1319 const auto la = static_cast<size_t>(a), lb = static_cast<size_t>(b);
1320 const bool copy = levelSize_[la] != levelSize_[lb] && hasGridCopy(a, b);
1321 const int sizeB = copy ? copySize_[lb] : levelSize_[lb];
1322 s.same = levelSize_[la] == sizeB;
1323 s.sizeA = static_cast<double>(levelSize_[la]);
1324 s.sizeB = static_cast<double>(sizeB);
1325 s.strideA = static_cast<size_t>(levelSize_[la] + 2 * kGuard);
1326 s.strideB = static_cast<size_t>(sizeB + 2 * kGuard);
1327 s.baseA = data_.data() + levelOffset_[la] + static_cast<size_t>(kGuard - 2);
1328 s.baseB = data_.data() + (copy ? copyOffset_[lb] : levelOffset_[lb]) + static_cast<size_t>(kGuard - 2);
1329 return s;
1330 }
1331#endif
1332
1335 [[nodiscard]] bool hasGridCopy(int a, int b) const noexcept
1336 {
1337 return b == a + 1 && copySize_[static_cast<size_t>(b)] == levelSize_[static_cast<size_t>(a)];
1338 }
1339
1345 template <FloatType T>
1346 T gather(int level, int f0, int f1, T t, double phase, T* y, int grid = 0) const noexcept
1347 {
1348 const auto L = static_cast<size_t>(level);
1349 const bool copy = grid != 0 && grid != levelSize_[L];
1350 const int size = copy ? grid : levelSize_[L];
1351 const double p = phase * static_cast<double>(size);
1352 const int i = std::min(static_cast<int>(p), size - 1);
1353 const size_t stride = static_cast<size_t>(size + 2 * kGuard);
1354 const float* ta = data_.data() + (copy ? copyOffset_[L] : levelOffset_[L])
1355 + static_cast<size_t>(f0) * stride + static_cast<size_t>(kGuard + i - 2);
1356 if (t == T(0))
1357 {
1358 for (int k = 0; k < 6; ++k) y[k] = static_cast<T>(ta[k]);
1359 }
1360 else
1361 {
1362 const float* tb = ta + static_cast<size_t>(f1 - f0) * stride;
1363 for (int k = 0; k < 6; ++k)
1364 y[k] = static_cast<T>(ta[k]) + t * (static_cast<T>(tb[k]) - static_cast<T>(ta[k]));
1365 }
1366 return static_cast<T>(p - static_cast<double>(i));
1367 }
1368
1370 bool build(int numFrames, int numHarmonics, const std::vector<Harmonic>& coeffs,
1371 Normalization normalization)
1372 {
1373 std::array<int, kMipLevels> harmonics {};
1374 std::array<int, kMipLevels> sizes {};
1375 std::array<size_t, kMipLevels> offsets {};
1376 size_t total = 0;
1377 for (int L = 0; L < kMipLevels; ++L)
1378 {
1379 const auto l = static_cast<size_t>(L);
1380 harmonics[l] = std::max(1, std::min(kLevelHarmonics[l], numHarmonics));
1381 int size = kMinTableSize;
1382 while (size < 8 * harmonics[l]) size *= 2;
1383 sizes[l] = size;
1384 offsets[l] = total;
1385 total += static_cast<size_t>(numFrames) * static_cast<size_t>(size + 2 * kGuard);
1386 }
1387 // A level whose grid differs from the brighter level it is blended
1388 // with also gets a copy on that level's grid, so the pair blends its
1389 // samples and interpolates once (see read()).
1390 std::array<int, kMipLevels> copySizes {};
1391 std::array<size_t, kMipLevels> copyOffsets {};
1392 for (int L = 1; L < kMipLevels; ++L)
1393 {
1394 const auto l = static_cast<size_t>(L);
1395 if (sizes[l] == sizes[l - 1]) continue;
1396 copySizes[l] = sizes[l - 1];
1397 copyOffsets[l] = total;
1398 total += static_cast<size_t>(numFrames) * static_cast<size_t>(copySizes[l] + 2 * kGuard);
1399 }
1400
1401 // Pre-emphasis per (table size, harmonic): the inverse interpolator
1402 // response at h / size cycles per sample.
1403 std::vector<std::vector<double>> emphasis(static_cast<size_t>(kMipLevels));
1404 for (int L = 0; L < kMipLevels; ++L)
1405 {
1406 const auto l = static_cast<size_t>(L);
1407 int same = -1;
1408 for (int j = 0; j < L; ++j)
1409 if (sizes[static_cast<size_t>(j)] == sizes[l]
1410 && harmonics[static_cast<size_t>(j)] >= harmonics[l]) { same = j; break; }
1411 if (same >= 0) { emphasis[l] = emphasis[static_cast<size_t>(same)]; continue; }
1412 emphasis[l].resize(static_cast<size_t>(harmonics[l] + 1), 1.0);
1413 for (int h = 1; h <= harmonics[l]; ++h)
1414 emphasis[l][static_cast<size_t>(h)] =
1415 1.0 / interpolatorResponse(static_cast<double>(h) / static_cast<double>(sizes[l]));
1416 }
1417 // A copy sits on the grid of the level before it, which holds more
1418 // harmonics: that level's emphasis covers it.
1419 const auto emphasisOf = [&](size_t l, bool copy) -> const std::vector<double>& {
1420 return copy ? emphasis[l - 1] : emphasis[l];
1421 };
1422
1423 std::vector<double> spec, cycle;
1424 std::vector<FFTReal<double>> ffts;
1425 std::vector<int> fftSizes;
1426 auto fftFor = [&](int size) -> FFTReal<double>& {
1427 for (size_t j = 0; j < fftSizes.size(); ++j)
1428 if (fftSizes[j] == size) return ffts[j];
1429 fftSizes.push_back(size);
1430 ffts.emplace_back(static_cast<size_t>(size));
1431 return ffts.back();
1432 };
1433 for (int L = 0; L < kMipLevels; ++L) (void)fftFor(sizes[static_cast<size_t>(L)]);
1434
1435 // One level of one frame (or its copy) into `cycle`.
1436 auto synthesize = [&](int frame, int L, bool copy = false) {
1437 const auto l = static_cast<size_t>(L);
1438 const int size = copy ? copySizes[l] : sizes[l];
1439 const std::vector<double>& emph = emphasisOf(l, copy);
1440 spec.assign(static_cast<size_t>(size + 2), 0.0);
1441 cycle.resize(static_cast<size_t>(size));
1442 const double half = 0.5 * static_cast<double>(size);
1443 const Harmonic* c = coeffs.data() + static_cast<size_t>(frame) * static_cast<size_t>(numHarmonics);
1444 for (int h = 1; h <= harmonics[l] && h <= numHarmonics; ++h)
1445 {
1446 // x = sum a cos + b sin has X[h] = (N/2)(a - j b) under the
1447 // inverse transform's 1/N scaling.
1448 const double e = emph[static_cast<size_t>(h)];
1449 spec[static_cast<size_t>(2 * h)] = half * c[h - 1].cosine * e;
1450 spec[static_cast<size_t>(2 * h + 1)] = -half * c[h - 1].sine * e;
1451 }
1452 fftFor(size).inverse(spec.data(), cycle.data());
1453 };
1454
1455 // Pass 1: peak per frame over all its levels (in practice the
1456 // richest; the copies take their level's scale). Pass 2: write the
1457 // scaled tables with their guards.
1458 std::vector<double> peak(static_cast<size_t>(numFrames), 0.0);
1459 for (int f = 0; f < numFrames; ++f)
1460 for (int L = 0; L < kMipLevels; ++L)
1461 {
1462 synthesize(f, L);
1463 for (const double v : cycle)
1464 peak[static_cast<size_t>(f)] = std::max(peak[static_cast<size_t>(f)], std::abs(v));
1465 }
1466 double bankPeak = 0.0;
1467 for (const double p : peak) bankPeak = std::max(bankPeak, p);
1468 if (!(bankPeak > 0.0) || !std::isfinite(bankPeak)) return false;
1469
1470 std::vector<float> data(total + kTailPad, 0.0f);
1471 for (int f = 0; f < numFrames; ++f)
1472 {
1473 const double framePeak = peak[static_cast<size_t>(f)];
1474 const double gain = (normalization == Normalization::PerFrame)
1475 ? (framePeak > 0.0 ? 1.0 / framePeak : 0.0)
1476 : 1.0 / bankPeak;
1477 for (int L = 0; L < kMipLevels; ++L)
1478 for (const bool copy : { false, true })
1479 {
1480 const auto l = static_cast<size_t>(L);
1481 if (copy && copySizes[l] == 0) continue;
1482 synthesize(f, L, copy);
1483 const int size = copy ? copySizes[l] : sizes[l];
1484 float* dst = data.data() + (copy ? copyOffsets[l] : offsets[l])
1485 + static_cast<size_t>(f) * static_cast<size_t>(size + 2 * kGuard);
1486 for (int i = 0; i < size; ++i)
1487 {
1488 // No negative zeros: the block kernels blend frames with t = 0
1489 // arithmetically, and -0 + 0 would read back as +0.
1490 const float v = static_cast<float>(cycle[static_cast<size_t>(i)] * gain);
1491 dst[kGuard + i] = (v == 0.0f) ? 0.0f : v;
1492 }
1493 for (int g = 0; g < kGuard; ++g)
1494 {
1495 dst[g] = dst[size + g]; // wraps of the cycle's end
1496 dst[kGuard + size + g] = dst[kGuard + g]; // and of its start
1497 }
1498 }
1499 }
1500
1501 data_ = std::move(data);
1502 levelHarmonics_ = harmonics;
1503 levelSize_ = sizes;
1504 levelOffset_ = offsets;
1505 copySize_ = copySizes;
1506 copyOffset_ = copyOffsets;
1507 numFrames_ = numFrames;
1508 return true;
1509 }
1510
1511 // -- Built-in recipes ----------------------------------------------------------
1512
1514 [[nodiscard]] static Harmonic pulse(double w, int h) noexcept
1515 {
1516 const double theta = twoPi<double> * static_cast<double>(h) * w;
1517 const double k = 2.0 / (pi<double> * static_cast<double>(h));
1518 return { k * std::sin(theta), k * (1.0 - std::cos(theta)) };
1519 }
1520
1521 [[nodiscard]] static WavetableBank makeBasic()
1522 {
1523 WavetableBank b;
1524 b.buildFromHarmonics(6, kMaxHarmonics, [](int frame, int h) -> Harmonic {
1525 const double hd = static_cast<double>(h);
1526 switch (frame)
1527 {
1528 case 0: return { 0.0, h == 1 ? 1.0 : 0.0 };
1529 case 1:
1530 {
1531 if (h % 2 == 0) return {};
1532 const double sign = ((h / 2) % 2 == 0) ? 1.0 : -1.0;
1533 return { 0.0, sign / (hd * hd) };
1534 }
1535 case 2: return { 0.0, (h % 2 == 0) ? -1.0 / hd : 1.0 / hd };
1536 case 3: return pulse(0.5, h);
1537 case 4: return pulse(0.25, h);
1538 default: return pulse(0.125, h);
1539 }
1540 });
1541 return b;
1542 }
1543
1544 [[nodiscard]] static WavetableBank makeHarmonic()
1545 {
1546 WavetableBank b;
1547 b.buildFromHarmonics(8, kMaxHarmonics, [](int frame, int h) -> Harmonic {
1548 const double p = 3.0 - 2.5 * static_cast<double>(frame) / 7.0;
1549 return { 0.0, std::pow(static_cast<double>(h), -p) };
1550 });
1551 return b;
1552 }
1553
1554 [[nodiscard]] static WavetableBank makeFormant()
1555 {
1556 // Three formants (Hz) of the vowels A E I O U, placed on the harmonic
1557 // series of a 110 Hz cycle; odd frames sit halfway between vowels.
1558 static constexpr double vowels[5][3] = {
1559 { 730.0, 1090.0, 2440.0 }, { 530.0, 1840.0, 2480.0 }, { 270.0, 2290.0, 3010.0 },
1560 { 570.0, 840.0, 2410.0 }, { 300.0, 870.0, 2240.0 } };
1561 static constexpr double gains[3] = { 1.0, 0.5, 0.25 };
1562 static constexpr double widths[3] = { 90.0, 120.0, 160.0 };
1563 WavetableBank b;
1564 b.buildFromHarmonics(9, kMaxHarmonics, [](int frame, int h) -> Harmonic {
1565 const int v0 = frame / 2;
1566 const int v1 = std::min(v0 + (frame % 2), 4);
1567 const double f = 110.0 * static_cast<double>(h);
1568 double env = 0.01;
1569 for (int i = 0; i < 3; ++i)
1570 {
1571 const double fc = 0.5 * (vowels[v0][i] + vowels[v1][i]);
1572 const double d = (f - fc) / widths[i];
1573 env += gains[i] / (1.0 + d * d);
1574 }
1575 return { 0.0, env / static_cast<double>(h) };
1576 });
1577 return b;
1578 }
1579
1580 [[nodiscard]] static WavetableBank makeFm()
1581 {
1582 // sin(x + b sin x): a smooth cycle whose harmonics above about b + 12
1583 // are below -150 dB for b <= 6, so a dense numeric cycle analysed by
1584 // FFT gives its coefficients exactly.
1585 constexpr int n = 4096;
1586 std::vector<double> cycles(static_cast<size_t>(8 * n));
1587 for (int frame = 0; frame < 8; ++frame)
1588 {
1589 const double b = 6.0 * std::pow(static_cast<double>(frame) / 7.0, 1.5);
1590 for (int i = 0; i < n; ++i)
1591 {
1592 const double x = twoPi<double> * static_cast<double>(i) / static_cast<double>(n);
1593 cycles[static_cast<size_t>(frame * n + i)] = std::sin(x + b * std::sin(x));
1594 }
1595 }
1596 WavetableBank bank;
1597 bank.loadFrames(cycles.data(), n, 8, Normalization::PerFrame);
1598 return bank;
1599 }
1600
1601 int numFrames_ = 0;
1602 std::array<int, kMipLevels> levelHarmonics_ {};
1603 std::array<int, kMipLevels> levelSize_ {};
1604 std::array<size_t, kMipLevels> levelOffset_ {};
1605 std::array<int, kMipLevels> copySize_ {};
1606 std::array<size_t, kMipLevels> copyOffset_ {};
1607 std::vector<float> data_;
1608};
1609
1610} // namespace dspark
FFT optimised for real-valued input signals (the common audio case).
Definition FFT.h:1197
Mipmapped multi-frame wavetable storage and its morphing reader.
static constexpr int kMaxHarmonics
Harmonics of the richest level.
static constexpr int kNumBuiltins
Normalization
How a bank's frames are scaled.
@ PerFrame
Every frame peaks at 1 (equal peak level across a morph).
@ Bank
One factor for the whole bank: the frames keep their relative levels.
static const WavetableBank & builtin(Builtin which)
A built-in bank, built on the first call and shared by the process.
T read(double phase, double position, const Mip &mip) const noexcept
One sample of the bank.
int getNumFrames() const noexcept
Frames in the bank (0 before a successful build).
static constexpr int kMaxFrames
Most frames a bank holds.
static constexpr int kMipLevels
Mip levels, half an octave apart.
static constexpr int kMaxFrameSize
Largest single-cycle frame loadFrames() analyses.
void readBlock(const double *phases, double position, const Mip &mip, T *out, int n) const noexcept
A block of samples at one frame position: read() at each phase.
Builtin
Built-in banks (see builtin()).
@ Basic
6 frames: sine, triangle, saw, square, 25% and 12.5% pulse.
@ Harmonic
8 frames: 1/h^p spectra from p = 3 (near sine) to p = 0.5 (bright).
@ Formant
9 frames: vowels A, E, I, O, U and the four transitions between them.
@ Fm
8 frames: sin(x + b sin x) with the index b rising from 0 to 6.
int getNumHarmonics() const noexcept
Highest harmonic the frames hold (0 before a build).
bool loadFrames(const S *data, int frameSize, int numFrames, Normalization normalization=Normalization::Bank)
Builds the bank from consecutive single-cycle frames.
void readBlock(const double *phases, const double *positions, const Mip &mip, T *out, int n) const noexcept
A block of samples with one frame position per sample.
static double interpolatorResponse(double cyclesPerSample) noexcept
Amplitude response of the reader's interpolator at a frequency in cycles per table sample (the value ...
Mip selectMip(double frequencyHz, double sampleRate) const noexcept
Chooses the level pair and crossfade weight for a pitch.
size_t getMemoryBytes() const noexcept
Bytes of table storage.
bool buildFromHarmonics(int numFrames, int numHarmonics, Coefficients &&coefficients, Normalization normalization=Normalization::PerFrame)
Builds the bank from per-frame harmonic amplitudes.
constexpr int kWavetableOneLevel
Level layouts of a block: one level, two levels on one grid, two grids.
constexpr int kWavetableTwoGrids
constexpr int kWavetableSameGrid
WavetableFrame wavetableFrame(double position, int numFrames) noexcept
constexpr std::array< double, 18 > kWavetableNiemitalo
constexpr void copy(char *dst, std::string_view src, std::size_t dstCapacity) noexcept
Safe small string copy used only for compile-time-friendly name building.
bool isRuntimeDispatchActive() noexcept
Whether the AVX2+FMA kernels are selected now (see setRuntimeDispatch()).
Definition SimdOps.h:262
void add(float *DSPARK_RESTRICT dst, const float *DSPARK_RESTRICT src, int count) noexcept
Adds source samples into a destination buffer (no scaling).
Definition SimdOps.h:829
Main namespace for the DSPark framework.
One harmonic's cosine and sine amplitudes.
The level pair and crossfade weight for one pitch (selectMip()).
int next
Duller level it fades into.
float weight
Weight of level; 1 reads it alone.
int level
Brighter level.
double t
Blend toward the upper frame.
size_t step
1 to the upper frame, 0 on the last one.
One block's level pair, as WavetableBank's block readers see it.
const float * baseA
Frame 0 at table offset -2, level a.
bool two
Two levels are blended.
bool same
Both levels share a grid.