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