openMSX
ResampleHQ.cc
Go to the documentation of this file.
1// Based on libsamplerate-0.1.2 (aka Secret Rabbit Code)
2//
3// simplified code in several ways:
4// - resample algorithm is no longer switchable, we took this variant:
5// Band limited sinc interpolation, fastest, 97dB SNR, 80% BW
6// - don't allow to change sample rate on-the-fly
7// - assume input (and thus also output) signals have infinite length, so
8// there is no special code to handle the ending of the signal
9// - changed/simplified API to better match openmsx use model
10// (e.g. remove all error checking)
11
12#include "ResampleHQ.hh"
13
15
16#include "FixedPoint.hh"
17#include "MemBuffer.hh"
18#include "aligned.hh"
19#include "narrow.hh"
20#include "ranges.hh"
21#include "stl.hh"
22#include "vla.hh"
23#include "xrange.hh"
24
25#include <array>
26#include <bit>
27#include <cmath>
28#include <cstddef>
29#include <cassert>
30#include <iterator>
31#include <vector>
32#ifdef __SSE2__
33#include <emmintrin.h>
34#endif
35
36namespace openmsx {
37
38// Letting the compiler deduce the (type and) size of the std::array works fine
39// with gcc, msvc and clang-11 but is broken from clang-12 onwards. More
40// specifically it only works for sizes upto 256. For more details see:
41// https://www.mail-archive.com/llvm-bugs@lists.llvm.org/msg50598.html
42// https://reviews.llvm.org/D86936
43// As a workaround we do hardcode the (type and) size here:
44//static constexpr std::array coeffs = {
45static constexpr std::array<float, 2464> coeffs = {
46 #include "ResampleCoeffs.ii"
47};
48
50
51static constexpr int INDEX_INC = 128;
52static constexpr int COEFF_LEN = int(std::size(coeffs));
53static constexpr int COEFF_HALF_LEN = COEFF_LEN - 1;
54static constexpr size_t TAB_LEN = ResampleHQ<1>::TAB_LEN;
55static constexpr size_t HALF_TAB_LEN = ResampleHQ<1>::HALF_TAB_LEN;
56
58{
59public:
62
63 static ResampleCoeffs& instance();
64 void getCoeffs(double ratio, std::span<const int16_t, HALF_TAB_LEN>& permute, float*& table, unsigned& filterLen);
65 void releaseCoeffs(double ratio);
66
67private:
69 using PermuteTable = MemBuffer<int16_t>; // array<int16_t, HALF_TAB_LEN>
70
71 ResampleCoeffs() = default;
73
74 static Table calcTable(double ratio, std::span<int16_t, HALF_TAB_LEN> permute, unsigned& filterLen);
75
76 struct Element {
77 double ratio;
78 PermuteTable permute; // need stable address (can't directly use std::array)
79 Table table;
80 unsigned filterLen;
81 unsigned count;
82 };
83 std::vector<Element> cache; // typically 1-4 entries -> unsorted vector
84};
85
86ResampleCoeffs::~ResampleCoeffs()
87{
88 assert(cache.empty());
89}
90
92{
93 static ResampleCoeffs resampleCoeffs;
94 return resampleCoeffs;
95}
96
98 double ratio, std::span<const int16_t, HALF_TAB_LEN>& permute, float*& table, unsigned& filterLen)
99{
100 if (auto it = ranges::find(cache, ratio, &Element::ratio);
101 it != end(cache)) {
102 permute = std::span<int16_t, HALF_TAB_LEN>{it->permute.data(), HALF_TAB_LEN};
103 table = it->table.data();
104 filterLen = it->filterLen;
105 it->count++;
106 return;
107 }
108 Element elem;
109 elem.ratio = ratio;
110 elem.count = 1;
111 elem.permute = PermuteTable(HALF_TAB_LEN);
112 auto perm = std::span<int16_t, HALF_TAB_LEN>{elem.permute.data(), HALF_TAB_LEN};
113 elem.table = calcTable(ratio, perm, elem.filterLen);
114 permute = perm;
115 table = elem.table.data();
116 filterLen = elem.filterLen;
117 cache.push_back(std::move(elem));
118}
119
121{
122 auto it = rfind_unguarded(cache, ratio, &Element::ratio);
123 it->count--;
124 if (it->count == 0) {
125 move_pop_back(cache, it);
126 }
127}
128
129// -- Permutation stuff --
130//
131// The rows in the resample coefficient table are not visited sequentially.
132// Instead, depending on the resample-ratio, we take fixed non-integer jumps
133// from one row to the next.
134//
135// In reality the table has 4096 rows (of which only 2048 are actually stored).
136// But for simplicity I'll here work out examples for a table with only 16 rows
137// (of which 8 are stored).
138//
139// Let's first assume a jump of '5.2'. This means that after we've used row
140// 'r', the next row we need is 'r + 5.2'. Of course row numbers must be
141// integers, so a jump of 5.2 actually means that 80% of the time we advance 5
142// rows and 20% of the time we advance 6 rows.
143//
144// The rows in the (full) table are circular. This means that once we're past
145// row 15 (in this example) we restart at row 0. So rows 'wrap' past the end
146// (modulo arithmetic). We also only store the 1st half of the table, the
147// entries for the 2nd half are 'folded' back to the 1st half according to the
148// formula: y = 15 - x.
149//
150// Let's now calculate the possible transitions. If we're currently on row '0',
151// the next row will be either '5' (80% chance) or row '6' (20% chance). When
152// we're on row '5' the next most likely row will be '10', but after folding
153// '10' becomes '15-10 = 5' (so 5 goes to itself (80% chance)). Row '10' most
154// likely goes to '15', after folding we get that '5' goes to '0'. Row '15'
155// most likely goes to '20', and after wrapping and folding that becomes '0'
156// goes to '4'. Calculating this for all rows gives:
157// 0 -> 5 or 4 (80%) 0 -> 6 or 5 (20%)
158// 1 -> 6 or 3 1 -> 7 or 4
159// 2 -> 7 or 2 2 -> 7 or 3
160// 3 -> 7 or 1 3 -> 6 or 2
161// 4 -> 6 or 0 4 -> 5 or 1
162// 5 -> 5 or 0 5 -> 4 or 0
163// 6 -> 4 or 1 6 -> 3 or 0
164// 7 -> 3 or 2 7 -> 2 or 1
165// So every row has 4 possible successors (2 more and 2 less likely). Possibly
166// some of these 4 are the same, or even the same as the starting row. Note
167// that if row x goes to row y (x->y) then also y->x, this turns out to be true
168// in general.
169//
170// For cache efficiency it's best if rows that are needed after each other in
171// time are also stored sequentially in memory (both before or after is fine).
172// Clearly storing the rows in numeric order will not read the memory
173// sequentially. For this specific example we could stores the rows in the
174// order:
175// 2, 7, 3, 1, 6, 4, 0, 5
176// With this order all likely transitions are sequential. The less likely
177// transitions are not. But I don't believe there exists an order that's good
178// for both the likely and the unlikely transitions. Do let me know if I'm
179// wrong.
180//
181// In this example the transitions form a single chain (it turns out this is
182// often the case). But for example for a step-size of 4.3 we get
183// 0 -> 4 or 3 (70%) 0 -> 5 or 4 (30%)
184// 1 -> 5 or 2 1 -> 6 or 3
185// 2 -> 6 or 1 2 -> 7 or 2
186// 3 -> 7 or 0 3 -> 7 or 1
187// 4 -> 7 or 0 4 -> 6 or 0
188// 5 -> 6 or 1 5 -> 5 or 0
189// 6 -> 5 or 2 6 -> 4 or 1
190// 7 -> 4 or 3 7 -> 3 or 2
191// Only looking at the more likely transitions, we get 2 cycles of length 4:
192// 0, 4, 7, 3
193// 1, 5, 6, 2
194//
195// So the previous example gave a single chain with 2 clear end-points. Now we
196// have 2 separate cycles. It turns out that for any possible step-size we
197// either get a single chain or k cycles of size N/k. (So e.g. a chain of
198// length 5 plus a cycle of length 3 is impossible. Also 1 cycle of length 4
199// plus 2 cycles of length 2 is impossible). To be honest I've only partially
200// mathematically proven this, but at least I've verified it for N=16 and
201// N=4096 for all possible step-sizes.
202//
203// To linearize a chain in memory there are only 2 (good) possibilities: start
204// at either end-point. But to store a cycle any point is as good as any other.
205// Also the order in which to store the cycles themselves can still be chosen.
206//
207// Let's come back to the example with step-size 4.3. If we linearize this as
208// | 0, 4, 7, 3 | 1, 5, 6, 2 |
209// then most of the more likely transitions are sequential. The exceptions are
210// 0 <-> 3 and 1 <-> 2
211// but those are unavoidable with cycles. In return 2 of the less likely
212// transitions '3 <-> 1' are now sequential. I believe this is the best
213// possible linearization (better said: there are other linearizations that are
214// equally good, but none is better). But do let me know if you find a better
215// one!
216//
217// For step-size '8.4' an optimal(?) linearization seems to be
218// | 0, 7 | 1, 6 | 2, 5 | 3, 4 |
219// For step-size '7.9' the order is:
220// | 7, 0 | 6, 1 | 5, 2 | 4, 3 |
221// And for step-size '3.8':
222// | 7, 4, 0, 3 | 6, 5, 1, 2 |
223//
224// I've again not (fully) mathematically proven it, but it seems we can
225// optimally(?) linearize cycles by:
226// * if likely step < unlikely step:
227// pick unassigned rows from 0 to N/2-1, and complete each cycle
228// * if likely step > unlikely step:
229// pick unassigned rows from N/2-1 to 0, and complete each cycle
230//
231// The routine calcPermute() below calculates these optimal(?) linearizations.
232// More in detail it calculates a permutation table: the i-th element in this
233// table tells where in memory the i-th logical row of the original (half)
234// resample coefficient table is physically stored.
235
236static constexpr unsigned N = TAB_LEN;
237static constexpr unsigned N1 = N - 1;
238static constexpr unsigned N2 = N / 2;
239
240static constexpr unsigned mapIdx(unsigned x)
241{
242 unsigned t = x & N1; // first wrap
243 return (t < N2) ? t : N1 - t; // then fold
244}
245
246static constexpr std::pair<unsigned, unsigned> next(unsigned x, unsigned step)
247{
248 return {mapIdx(x + step), mapIdx(N1 - x + step)};
249}
250
251static void calcPermute(double ratio, std::span<int16_t, HALF_TAB_LEN> permute)
252{
253 double r2 = ratio * N;
254 double fract = r2 - floor(r2);
255 auto step = narrow_cast<unsigned>(floor(r2));
256 bool incr = [&] {
257 if (fract > 0.5) {
258 // mostly (> 50%) take steps of 'floor(r2) + 1'
259 step += 1;
260 return false; // assign from high to low
261 } else {
262 // mostly take steps of 'floor(r2)'
263 return true; // assign from low to high
264 }
265 }();
266
267 // initially set all as unassigned
268 ranges::fill(permute, -1);
269
270 unsigned restart = incr ? 0 : N2 - 1;
271 unsigned curr = restart;
272 // check for chain (instead of cycles)
273 if (incr) {
274 for (auto i : xrange(N2)) {
275 auto [nxt1, nxt2] = next(i, step);
276 if ((nxt1 == i) || (nxt2 == i)) { curr = i; break; }
277 }
278 } else {
279 for (unsigned i = N2 - 1; int(i) >= 0; --i) {
280 auto [nxt1, nxt2] = next(i, step);
281 if ((nxt1 == i) || (nxt2 == i)) { curr = i; break; }
282 }
283 }
284
285 // assign all rows (in chain of cycle(s))
286 unsigned cnt = 0;
287 while (true) {
288 assert(permute[curr] == -1);
289 assert(cnt < N2);
290 permute[curr] = narrow<int16_t>(cnt++);
291
292 auto [nxt1, nxt2] = next(curr, step);
293 if (permute[nxt1] == -1) {
294 curr = nxt1;
295 continue;
296 } else if (permute[nxt2] == -1) {
297 curr = nxt2;
298 continue;
299 }
300
301 // finished chain or cycle
302 if (cnt == N2) break; // done
303
304 // continue with next cycle
305 while (permute[restart] != -1) {
306 if (incr) {
307 ++restart;
308 assert(restart != N2);
309 } else {
310 assert(restart != 0);
311 --restart;
312 }
313 }
314 curr = restart;
315 }
316
317#ifdef DEBUG
318 std::array<int16_t, N2> testPerm;
319 ranges::iota(testPerm, int16_t(0));
320 assert(std::is_permutation(permute.begin(), permute.end(), testPerm.begin()));
321#endif
322}
323
324static constexpr double getCoeff(FilterIndex index)
325{
326 double fraction = index.fractionAsDouble();
327 int indx = index.toInt();
328 return double(coeffs[indx]) +
329 fraction * (double(coeffs[indx + 1]) - double(coeffs[indx]));
330}
331
332ResampleCoeffs::Table ResampleCoeffs::calcTable(
333 double ratio, std::span<int16_t, HALF_TAB_LEN> permute, unsigned& filterLen)
334{
335 calcPermute(ratio, permute);
336
337 double floatIncr = (ratio > 1.0) ? INDEX_INC / ratio : INDEX_INC;
338 double normFactor = floatIncr / INDEX_INC;
339 auto increment = FilterIndex(floatIncr);
340 FilterIndex maxFilterIndex(COEFF_HALF_LEN);
341
342 int min_idx = -maxFilterIndex.divAsInt(increment);
343 int max_idx = 1 + (maxFilterIndex - (increment - FilterIndex(floatIncr))).divAsInt(increment);
344 int idx_cnt = max_idx - min_idx + 1;
345 filterLen = (idx_cnt + 3) & ~3; // round up to multiple of 4
346 min_idx -= (narrow<int>(filterLen) - idx_cnt) / 2;
347 Table table(HALF_TAB_LEN * filterLen);
348 ranges::fill(std::span{table.data(), HALF_TAB_LEN * filterLen}, 0);
349
350 for (auto t : xrange(HALF_TAB_LEN)) {
351 float* tab = &table[permute[t] * filterLen];
352 double lastPos = (double(t) + 0.5) / TAB_LEN;
353 FilterIndex startFilterIndex(lastPos * floatIncr);
354
355 FilterIndex filterIndex(startFilterIndex);
356 int coeffCount = (maxFilterIndex - filterIndex).divAsInt(increment);
357 filterIndex += increment * coeffCount;
358 int bufIndex = -coeffCount;
359 do {
360 tab[bufIndex - min_idx] =
361 float(getCoeff(filterIndex) * normFactor);
362 filterIndex -= increment;
363 bufIndex += 1;
364 } while (filterIndex >= FilterIndex(0));
365
366 filterIndex = increment - startFilterIndex;
367 coeffCount = (maxFilterIndex - filterIndex).divAsInt(increment);
368 filterIndex += increment * coeffCount;
369 bufIndex = 1 + coeffCount;
370 do {
371 tab[bufIndex - min_idx] =
372 float(getCoeff(filterIndex) * normFactor);
373 filterIndex -= increment;
374 bufIndex -= 1;
375 } while (filterIndex > FilterIndex(0));
376 }
377 return table;
378}
379
380static const std::array<int16_t, HALF_TAB_LEN> dummyPermute = {};
381
382template<unsigned CHANNELS>
384 ResampledSoundDevice& input_, const DynamicClock& hostClock_)
385 : ResampleAlgo(input_)
386 , hostClock(hostClock_)
387 , ratio(float(hostClock.getPeriod().toDouble() / getEmuClock().getPeriod().toDouble()))
388 , permute(dummyPermute) // Any better way to do this? (that also works with debug-STL)
389{
390 ResampleCoeffs::instance().getCoeffs(double(ratio), permute, table, filterLen);
391
392 // fill buffer with 'enough' zero's
393 unsigned extra = filterLen + 1 + narrow_cast<int>(ratio) + 1;
394 bufStart = 0;
395 bufEnd = extra;
396 size_t initialSize = 4000; // buffer grows dynamically if this is too small
397 buffer.resize((initialSize + extra) * CHANNELS); // zero-initialized
398}
399
400template<unsigned CHANNELS>
405
406#ifdef __SSE2__
407template<bool REVERSE>
408static inline void calcSseMono(const float* buf_, const float* tab_, size_t len, float* out)
409{
410 assert((len % 4) == 0);
411 assert((uintptr_t(tab_) % 16) == 0);
412
413 auto x = narrow<ptrdiff_t>((len & ~7) * sizeof(float));
414 assert((x % 32) == 0);
415 const char* buf = std::bit_cast<const char*>(buf_) + x;
416 const char* tab = std::bit_cast<const char*>(tab_) + (REVERSE ? -x : x);
417 x = -x;
418
419 __m128 a0 = _mm_setzero_ps();
420 __m128 a1 = _mm_setzero_ps();
421 do {
422 __m128 b0 = _mm_loadu_ps(std::bit_cast<const float*>(buf + x + 0));
423 __m128 b1 = _mm_loadu_ps(std::bit_cast<const float*>(buf + x + 16));
424 __m128 t0, t1;
425 if constexpr (REVERSE) {
426 t0 = _mm_loadr_ps(std::bit_cast<const float*>(tab - x - 16));
427 t1 = _mm_loadr_ps(std::bit_cast<const float*>(tab - x - 32));
428 } else {
429 t0 = _mm_load_ps (std::bit_cast<const float*>(tab + x + 0));
430 t1 = _mm_load_ps (std::bit_cast<const float*>(tab + x + 16));
431 }
432 __m128 m0 = _mm_mul_ps(b0, t0);
433 __m128 m1 = _mm_mul_ps(b1, t1);
434 a0 = _mm_add_ps(a0, m0);
435 a1 = _mm_add_ps(a1, m1);
436 x += 2 * sizeof(__m128);
437 } while (x < 0);
438 if (len & 4) {
439 __m128 b0 = _mm_loadu_ps(std::bit_cast<const float*>(buf));
440 __m128 t0;
441 if constexpr (REVERSE) {
442 t0 = _mm_loadr_ps(std::bit_cast<const float*>(tab - 16));
443 } else {
444 t0 = _mm_load_ps (std::bit_cast<const float*>(tab));
445 }
446 __m128 m0 = _mm_mul_ps(b0, t0);
447 a0 = _mm_add_ps(a0, m0);
448 }
449
450 __m128 a = _mm_add_ps(a0, a1);
451 // The following can be _slightly_ faster by using the SSE3 _mm_hadd_ps()
452 // intrinsic, but not worth the trouble.
453 __m128 t = _mm_add_ps(a, _mm_movehl_ps(a, a));
454 __m128 s = _mm_add_ss(t, _mm_shuffle_ps(t, t, 1));
455
456 _mm_store_ss(out, s);
457}
458
459template<int N> static inline __m128 shuffle(__m128 x)
460{
461 return _mm_castsi128_ps(_mm_shuffle_epi32(_mm_castps_si128(x), N));
462}
463template<bool REVERSE>
464static inline void calcSseStereo(const float* buf_, const float* tab_, size_t len, float* out)
465{
466 assert((len % 4) == 0);
467 assert((uintptr_t(tab_) % 16) == 0);
468
469 auto x = narrow<ptrdiff_t>(2 * (len & ~7) * sizeof(float));
470 const auto* buf = std::bit_cast<const char*>(buf_) + x;
471 const auto* tab = std::bit_cast<const char*>(tab_);
472 x = -x;
473
474 __m128 a0 = _mm_setzero_ps();
475 __m128 a1 = _mm_setzero_ps();
476 __m128 a2 = _mm_setzero_ps();
477 __m128 a3 = _mm_setzero_ps();
478 do {
479 __m128 b0 = _mm_loadu_ps(std::bit_cast<const float*>(buf + x + 0));
480 __m128 b1 = _mm_loadu_ps(std::bit_cast<const float*>(buf + x + 16));
481 __m128 b2 = _mm_loadu_ps(std::bit_cast<const float*>(buf + x + 32));
482 __m128 b3 = _mm_loadu_ps(std::bit_cast<const float*>(buf + x + 48));
483 __m128 ta, tb;
484 if constexpr (REVERSE) {
485 ta = _mm_loadr_ps(std::bit_cast<const float*>(tab - 16));
486 tb = _mm_loadr_ps(std::bit_cast<const float*>(tab - 32));
487 tab -= 2 * sizeof(__m128);
488 } else {
489 ta = _mm_load_ps (std::bit_cast<const float*>(tab + 0));
490 tb = _mm_load_ps (std::bit_cast<const float*>(tab + 16));
491 tab += 2 * sizeof(__m128);
492 }
493 __m128 t0 = shuffle<0x50>(ta);
494 __m128 t1 = shuffle<0xFA>(ta);
495 __m128 t2 = shuffle<0x50>(tb);
496 __m128 t3 = shuffle<0xFA>(tb);
497 __m128 m0 = _mm_mul_ps(b0, t0);
498 __m128 m1 = _mm_mul_ps(b1, t1);
499 __m128 m2 = _mm_mul_ps(b2, t2);
500 __m128 m3 = _mm_mul_ps(b3, t3);
501 a0 = _mm_add_ps(a0, m0);
502 a1 = _mm_add_ps(a1, m1);
503 a2 = _mm_add_ps(a2, m2);
504 a3 = _mm_add_ps(a3, m3);
505 x += 4 * sizeof(__m128);
506 } while (x < 0);
507 if (len & 4) {
508 __m128 b0 = _mm_loadu_ps(std::bit_cast<const float*>(buf + 0));
509 __m128 b1 = _mm_loadu_ps(std::bit_cast<const float*>(buf + 16));
510 __m128 ta;
511 if constexpr (REVERSE) {
512 ta = _mm_loadr_ps(std::bit_cast<const float*>(tab - 16));
513 } else {
514 ta = _mm_load_ps (std::bit_cast<const float*>(tab + 0));
515 }
516 __m128 t0 = shuffle<0x50>(ta);
517 __m128 t1 = shuffle<0xFA>(ta);
518 __m128 m0 = _mm_mul_ps(b0, t0);
519 __m128 m1 = _mm_mul_ps(b1, t1);
520 a0 = _mm_add_ps(a0, m0);
521 a1 = _mm_add_ps(a1, m1);
522 }
523
524 __m128 a01 = _mm_add_ps(a0, a1);
525 __m128 a23 = _mm_add_ps(a2, a3);
526 __m128 a = _mm_add_ps(a01, a23);
527 // Can faster with SSE3, but (like above) not worth the trouble.
528 __m128 s = _mm_add_ps(a, _mm_movehl_ps(a, a));
529 _mm_store_ss(&out[0], s);
530 _mm_store_ss(&out[1], shuffle<0x55>(s));
531}
532
533#endif
534
535template<unsigned CHANNELS>
536void ResampleHQ<CHANNELS>::calcOutput(
537 float pos, float* __restrict output)
538{
539 assert((filterLen & 3) == 0);
540
541 int bufIdx = int(pos) + bufStart;
542 assert((bufIdx + filterLen) <= bufEnd);
543 bufIdx *= CHANNELS;
544 const float* buf = &buffer[bufIdx];
545
546 auto t = size_t(lrintf(pos * TAB_LEN)) % TAB_LEN;
547 if (!(t & HALF_TAB_LEN)) {
548 // first half, begin of row 't'
549 t = permute[t];
550 const float* tab = &table[t * filterLen];
551
552#ifdef __SSE2__
553 if constexpr (CHANNELS == 1) {
554 calcSseMono <false>(buf, tab, filterLen, output);
555 } else {
556 calcSseStereo<false>(buf, tab, filterLen, output);
557 }
558 return;
559#endif
560
561 // c++ version, both mono and stereo
562 for (auto ch : xrange(CHANNELS)) {
563 float r0 = 0.0f;
564 float r1 = 0.0f;
565 float r2 = 0.0f;
566 float r3 = 0.0f;
567 for (unsigned i = 0; i < filterLen; i += 4) {
568 r0 += tab[i + 0] * buf[CHANNELS * (i + 0)];
569 r1 += tab[i + 1] * buf[CHANNELS * (i + 1)];
570 r2 += tab[i + 2] * buf[CHANNELS * (i + 2)];
571 r3 += tab[i + 3] * buf[CHANNELS * (i + 3)];
572 }
573 output[ch] = r0 + r1 + r2 + r3;
574 ++buf;
575 }
576 } else {
577 // 2nd half, end of row 'TAB_LEN - 1 - t'
578 t = permute[TAB_LEN - 1 - t];
579 const float* tab = &table[(t + 1) * filterLen];
580
581#ifdef __SSE2__
582 if constexpr (CHANNELS == 1) {
583 calcSseMono <true>(buf, tab, filterLen, output);
584 } else {
585 calcSseStereo<true>(buf, tab, filterLen, output);
586 }
587 return;
588#endif
589
590 // c++ version, both mono and stereo
591 for (auto ch : xrange(CHANNELS)) {
592 float r0 = 0.0f;
593 float r1 = 0.0f;
594 float r2 = 0.0f;
595 float r3 = 0.0f;
596 for (int i = 0; i < int(filterLen); i += 4) {
597 r0 += tab[-i - 1] * buf[CHANNELS * (i + 0)];
598 r1 += tab[-i - 2] * buf[CHANNELS * (i + 1)];
599 r2 += tab[-i - 3] * buf[CHANNELS * (i + 2)];
600 r3 += tab[-i - 4] * buf[CHANNELS * (i + 3)];
601 }
602 output[ch] = r0 + r1 + r2 + r3;
603 ++buf;
604 }
605 }
606}
607
608template<unsigned CHANNELS>
609void ResampleHQ<CHANNELS>::prepareData(unsigned emuNum)
610{
611 // Still enough free space at end of buffer?
612 unsigned free = unsigned(buffer.size() / CHANNELS) - bufEnd;
613 if (free < emuNum) {
614 // No, then move everything to the start
615 // (data needs to be in a contiguous memory block)
616 unsigned available = bufEnd - bufStart;
617 memmove(&buffer[0], &buffer[bufStart * size_t(CHANNELS)],
618 available * size_t(CHANNELS) * sizeof(float));
619 bufStart = 0;
620 bufEnd = available;
621
622 free = unsigned(buffer.size() / CHANNELS) - bufEnd;
623 auto missing = narrow_cast<int>(emuNum - free);
624 if (missing > 0) [[unlikely]] {
625 // Still not enough room: grow the buffer.
626 // TODO an alternative is to instead of using a large
627 // buffer, chop the work in multiple smaller pieces.
628 // That may have the advantage that the data fits in
629 // the CPU's data cache. OTOH too small chunks have
630 // more overhead. (Not yet implemented because it's
631 // more complex).
632 buffer.resize(buffer.size() + missing * size_t(CHANNELS));
633 }
634 }
635 VLA_SSE_ALIGNED(float, tmpBufExtra, emuNum * CHANNELS + 3);
636 auto tmpBuf = tmpBufExtra.subspan(0, emuNum * CHANNELS);
637 if (input.generateInput(tmpBufExtra.data(), emuNum)) {
638 ranges::copy(tmpBuf,
639 subspan(buffer, bufEnd * CHANNELS));
640 bufEnd += emuNum;
641 nonzeroSamples = bufEnd - bufStart;
642 } else {
643 ranges::fill(subspan(buffer, bufEnd * CHANNELS, emuNum * CHANNELS), 0);
644 bufEnd += emuNum;
645 }
646
647 assert(bufStart <= bufEnd);
648 assert(bufEnd <= (buffer.size() / CHANNELS));
649}
650
651template<unsigned CHANNELS>
653 float* __restrict dataOut, size_t hostNum, EmuTime::param time)
654{
655 auto& emuClk = getEmuClock();
656 unsigned emuNum = emuClk.getTicksTill(time);
657 if (emuNum > 0) {
658 prepareData(emuNum);
659 }
660
661 bool notMuted = nonzeroSamples > 0;
662 if (notMuted) {
663 // main processing loop
664 EmuTime host1 = hostClock.getFastAdd(1);
665 assert(host1 > emuClk.getTime());
666 float pos = narrow_cast<float>(emuClk.getTicksTillDouble(host1));
667 assert(pos <= (ratio + 2));
668 for (auto i : xrange(hostNum)) {
669 calcOutput(pos, &dataOut[i * CHANNELS]);
670 pos += ratio;
671 }
672 }
673 emuClk += emuNum;
674 bufStart += emuNum;
675 nonzeroSamples = std::max<int>(0, nonzeroSamples - emuNum);
676
677 assert(bufStart <= bufEnd);
678 unsigned available = bufEnd - bufStart;
679 unsigned extra = filterLen + 1 + narrow_cast<int>(ratio) + 1;
680 assert(available == extra); (void)available; (void)extra;
681
682 return notMuted;
683}
684
685// Force template instantiation.
686template class ResampleHQ<1>;
687template class ResampleHQ<2>;
688
689} // namespace openmsx
TclObject t
Represents a clock with a variable frequency.
static ResampleCoeffs & instance()
Definition ResampleHQ.cc:91
ResampleCoeffs(const ResampleCoeffs &)=delete
void getCoeffs(double ratio, std::span< const int16_t, HALF_TAB_LEN > &permute, float *&table, unsigned &filterLen)
Definition ResampleHQ.cc:97
ResampleCoeffs & operator=(const ResampleCoeffs &)=delete
void releaseCoeffs(double ratio)
ResampleHQ(ResampledSoundDevice &input, const DynamicClock &hostClock)
~ResampleHQ() override
bool generateOutputImpl(float *dataOut, size_t num, EmuTime::param time) override
This file implemented 3 utility functions:
Definition Autofire.cc:11
FixedPoint< 16 > FilterIndex
Definition ResampleHQ.cc:49
constexpr void fill(ForwardRange &&range, const T &value)
Definition ranges.hh:305
auto copy(InputRange &&range, OutputIter out)
Definition ranges.hh:250
constexpr void iota(ForwardIt first, ForwardIt last, T value)
Definition ranges.hh:312
auto find(InputRange &&range, const T &value)
Definition ranges.hh:160
constexpr auto subspan(Range &&range, size_t offset, size_t count=std::dynamic_extent)
Definition ranges.hh:471
void move_pop_back(VECTOR &v, typename VECTOR::iterator it)
Erase the pointed to element from the given vector.
Definition stl.hh:134
auto rfind_unguarded(RANGE &range, const VAL &val, Proj proj={})
Similar to the find(_if)_unguarded functions above, but searches from the back to front.
Definition stl.hh:109
#define VLA_SSE_ALIGNED(TYPE, NAME, LENGTH)
Definition vla.hh:50
constexpr auto xrange(T e)
Definition xrange.hh:132
constexpr auto end(const zstring_view &x)