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