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