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