Debian Codegraph @

src/engine/platform/sound/c64_fp/resample/SincResampler.cpp

raw
1 /*
2 * This file is part of libsidplayfp, a SID player engine.
3 *
4 * Copyright 2011-2020 Leandro Nini <[email protected]>
5 * Copyright 2007-2010 Antti Lankila
6 * Copyright 2004 Dag Lem <[email protected]>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program; if not, write to the Free Software
20 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 */
22
23 #include "SincResampler.h"
24
25 #include <cassert>
26 #include <cstring>
27 #include <cmath>
28 #include <iostream>
29 #include <sstream>
30
31 #include "../siddefs-fp.h"
32
33 #ifdef HAVE_EMMINTRIN_H
34 # include <emmintrin.h>
35 #elif defined HAVE_MMINTRIN_H
36 # include <mmintrin.h>
37 #elif defined(HAVE_ARM_NEON_H)
38 # include <arm_neon.h>
39 #endif
40
41 namespace reSIDfp
42 {
43
44 typedef std::map<std::string, matrix_t> fir_cache_t;
45
46 /// Cache for the expensive FIR table computation results.
47 fir_cache_t FIR_CACHE;
48
49 /// Maximum error acceptable in I0 is 1e-6, or ~96 dB.
50 const double I0E = 1e-6;
51
52 const int BITS = 16;
53
54 /**
55 * Compute the 0th order modified Bessel function of the first kind.
56 * This function is originally from resample-1.5/filterkit.c by J. O. Smith.
57 * It is used to build the Kaiser window for resampling.
58 *
59 * @param x evaluate I0 at x
60 * @return value of I0 at x.
61 */
62 double I0(double x)
63 {
64 double sum = 1.;
65 double u = 1.;
66 double n = 1.;
67 const double halfx = x / 2.;
68
69 do
70 {
71 const double temp = halfx / n;
72 u *= temp * temp;
73 sum += u;
74 n += 1.;
75 }
76 while (u >= I0E * sum);
77
78 return sum;
79 }
80
81 /**
82 * Calculate convolution with sample and sinc.
83 *
84 * @param a sample buffer input
85 * @param b sinc buffer
86 * @param bLength length of the sinc buffer
87 * @return convolved result
88 */
89 int convolve(const short* a, const short* b, int bLength)
90 {
91 #ifdef HAVE_EMMINTRIN_H
92 int out = 0;
93
94 const uintptr_t offset = (uintptr_t)(a) & 0x0f;
95
96 // check for aligned accesses
97 if (offset == ((uintptr_t)(b) & 0x0f))
98 {
99 if (offset)
100 {
101 const int l = (0x10 - offset)/2;
102
103 for (int i = 0; i < l; i++)
104 {
105 out += *a++ * *b++;
106 }
107
108 bLength -= offset;
109 }
110
111 __m128i acc = _mm_setzero_si128();
112
113 const int n = bLength / 8;
114
115 for (int i = 0; i < n; i++)
116 {
117 const __m128i tmp = _mm_madd_epi16(*(__m128i*)a, *(__m128i*)b);
118 acc = _mm_add_epi16(acc, tmp);
119 a += 8;
120 b += 8;
121 }
122
123 __m128i vsum = _mm_add_epi32(acc, _mm_srli_si128(acc, 8));
124 vsum = _mm_add_epi32(vsum, _mm_srli_si128(vsum, 4));
125 out += _mm_cvtsi128_si32(vsum);
126
127 bLength &= 7;
128 }
129 #elif defined HAVE_MMINTRIN_H
130 __m64 acc = _mm_setzero_si64();
131
132 const int n = bLength / 4;
133
134 for (int i = 0; i < n; i++)
135 {
136 const __m64 tmp = _mm_madd_pi16(*(__m64*)a, *(__m64*)b);
137 acc = _mm_add_pi16(acc, tmp);
138 a += 4;
139 b += 4;
140 }
141
142 int out = _mm_cvtsi64_si32(acc) + _mm_cvtsi64_si32(_mm_srli_si64(acc, 32));
143 _mm_empty();
144
145 bLength &= 3;
146 #elif defined(HAVE_ARM_NEON_H)
147 #if (defined(__arm64__) && defined(__APPLE__)) || defined(__aarch64__)
148 int32x4_t acc1Low = vdupq_n_s32(0);
149 int32x4_t acc1High = vdupq_n_s32(0);
150 int32x4_t acc2Low = vdupq_n_s32(0);
151 int32x4_t acc2High = vdupq_n_s32(0);
152
153 const int n = bLength / 16;
154
155 for (int i = 0; i < n; i++)
156 {
157 int16x8_t v11 = vld1q_s16(a);
158 int16x8_t v12 = vld1q_s16(a + 8);
159 int16x8_t v21 = vld1q_s16(b);
160 int16x8_t v22 = vld1q_s16(b + 8);
161
162 acc1Low = vmlal_s16(acc1Low, vget_low_s16(v11), vget_low_s16(v21));
163 acc1High = vmlal_high_s16(acc1High, v11, v21);
164 acc2Low = vmlal_s16(acc2Low, vget_low_s16(v12), vget_low_s16(v22));
165 acc2High = vmlal_high_s16(acc2High, v12, v22);
166
167 a += 16;
168 b += 16;
169 }
170
171 bLength &= 15;
172
173 if (bLength >= 8)
174 {
175 int16x8_t v1 = vld1q_s16(a);
176 int16x8_t v2 = vld1q_s16(b);
177
178 acc1Low = vmlal_s16(acc1Low, vget_low_s16(v1), vget_low_s16(v2));
179 acc1High = vmlal_high_s16(acc1High, v1, v2);
180
181 a += 8;
182 b += 8;
183 }
184
185 bLength &= 7;
186
187 if (bLength >= 4)
188 {
189 int16x4_t v1 = vld1_s16(a);
190 int16x4_t v2 = vld1_s16(b);
191
192 acc1Low = vmlal_s16(acc1Low, v1, v2);
193
194 a += 4;
195 b += 4;
196 }
197
198 int32x4_t accSumsNeon = vaddq_s32(acc1Low, acc1High);
199 accSumsNeon = vaddq_s32(accSumsNeon, acc2Low);
200 accSumsNeon = vaddq_s32(accSumsNeon, acc2High);
201
202 int out = vaddvq_s32(accSumsNeon);
203
204 bLength &= 3;
205 #else
206 int32x4_t acc = vdupq_n_s32(0);
207
208 const int n = bLength / 4;
209
210 for (int i = 0; i < n; i++)
211 {
212 const int16x4_t h_vec = vld1_s16(a);
213 const int16x4_t x_vec = vld1_s16(b);
214 acc = vmlal_s16(acc, h_vec, x_vec);
215 a += 4;
216 b += 4;
217 }
218
219 int out = vgetq_lane_s32(acc, 0) +
220 vgetq_lane_s32(acc, 1) +
221 vgetq_lane_s32(acc, 2) +
222 vgetq_lane_s32(acc, 3);
223
224 bLength &= 3;
225 #endif
226 #else
227 int out = 0;
228 #endif
229
230 for (int i = 0; i < bLength; i++)
231 {
232 out += *a++ * *b++;
233 }
234
235 return (out + (1 << 14)) >> 15;
236 }
237
238 int SincResampler::fir(int subcycle)
239 {
240 // Find the first of the nearest fir tables close to the phase
241 int firTableFirst = (subcycle * firRES >> 10);
242 const int firTableOffset = (subcycle * firRES) & 0x3ff;
243
244 // Find firN most recent samples, plus one extra in case the FIR wraps.
245 int sampleStart = sampleIndex - firN + RINGSIZE - 1;
246
247 const int v1 = convolve(sample + sampleStart, (*firTable)[firTableFirst], firN);
248
249 // Use next FIR table, wrap around to first FIR table using
250 // previous sample.
251 if (unlikely(++firTableFirst == firRES))
252 {
253 firTableFirst = 0;
254 ++sampleStart;
255 }
256
257 const int v2 = convolve(sample + sampleStart, (*firTable)[firTableFirst], firN);
258
259 // Linear interpolation between the sinc tables yields good
260 // approximation for the exact value.
261 return v1 + (firTableOffset * (v2 - v1) >> 10);
262 }
263
264 SincResampler::SincResampler(double clockFrequency, double samplingFrequency, double highestAccurateFrequency) :
265 sampleIndex(0),
266 cyclesPerSample(static_cast<int>(clockFrequency / samplingFrequency * 1024.)),
267 sampleOffset(0),
268 outputValue(0)
269 {
270 // 16 bits -> -96dB stopband attenuation.
271 const double A = -20. * log10(1.0 / (1 << BITS));
272 // A fraction of the bandwidth is allocated to the transition band, which we double
273 // because we design the filter to transition halfway at nyquist.
274 const double dw = (1. - 2.*highestAccurateFrequency / samplingFrequency) * M_PI * 2.;
275
276 // For calculation of beta and N see the reference for the kaiserord
277 // function in the MATLAB Signal Processing Toolbox:
278 // http://www.mathworks.com/help/signal/ref/kaiserord.html
279 const double beta = 0.1102 * (A - 8.7);
280 const double I0beta = I0(beta);
281 const double cyclesPerSampleD = clockFrequency / samplingFrequency;
282
283 {
284 // The filter order will maximally be 124 with the current constraints.
285 // N >= (96.33 - 7.95)/(2 * pi * 2.285 * (maxfreq - passbandfreq) >= 123
286 // The filter order is equal to the number of zero crossings, i.e.
287 // it should be an even number (sinc is symmetric with respect to x = 0).
288 int N = static_cast<int>((A - 7.95) / (2.285 * dw) + 0.5);
289 N += N & 1;
290
291 // The filter length is equal to the filter order + 1.
292 // The filter length must be an odd number (sinc is symmetric with respect to
293 // x = 0).
294 firN = static_cast<int>(N * cyclesPerSampleD) + 1;
295 firN |= 1;
296
297 // Check whether the sample ring buffer would overflow.
298 assert(firN < RINGSIZE);
299
300 // Error is bounded by err < 1.234 / L^2, so L = sqrt(1.234 / (2^-16)) = sqrt(1.234 * 2^16).
301 firRES = static_cast<int>(ceil(sqrt(1.234 * (1 << BITS)) / cyclesPerSampleD));
302
303 // firN*firRES represent the total resolution of the sinc sampling. JOS
304 // recommends a length of 2^BITS, but we don't quite use that good a filter.
305 // The filter test program indicates that the filter performs well, though.
306 }
307
308 // Create the map key
309 std::ostringstream o;
310 o << firN << "," << firRES << "," << cyclesPerSampleD;
311 const std::string firKey = o.str();
312 fir_cache_t::iterator lb = FIR_CACHE.lower_bound(firKey);
313
314 // The FIR computation is expensive and we set sampling parameters often, but
315 // from a very small set of choices. Thus, caching is used to speed initialization.
316 if (lb != FIR_CACHE.end() && !(FIR_CACHE.key_comp()(firKey, lb->first)))
317 {
318 firTable = &(lb->second);
319 }
320 else
321 {
322 // Allocate memory for FIR tables.
323 matrix_t tempTable(firRES, firN);
324 #ifdef HAVE_CXX11
325 firTable = &(FIR_CACHE.emplace_hint(lb, fir_cache_t::value_type(firKey, tempTable))->second);
326 #else
327 firTable = &(FIR_CACHE.insert(lb, fir_cache_t::value_type(firKey, tempTable))->second);
328 #endif
329
330 // The cutoff frequency is midway through the transition band, in effect the same as nyquist.
331 const double wc = M_PI;
332
333 // Calculate the sinc tables.
334 const double scale = 32768.0 * wc / cyclesPerSampleD / M_PI;
335
336 // we're not interested in the fractional part
337 // so use int division before converting to double
338 const int tmp = firN / 2;
339 const double firN_2 = static_cast<double>(tmp);
340
341 for (int i = 0; i < firRES; i++)
342 {
343 const double jPhase = (double) i / firRES + firN_2;
344
345 for (int j = 0; j < firN; j++)
346 {
347 const double x = j - jPhase;
348
349 const double xt = x / firN_2;
350 const double kaiserXt = fabs(xt) < 1. ? I0(beta * sqrt(1. - xt * xt)) / I0beta : 0.;
351
352 const double wt = wc * x / cyclesPerSampleD;
353 const double sincWt = fabs(wt) >= 1e-8 ? sin(wt) / wt : 1.;
354
355 (*firTable)[i][j] = static_cast<short>(scale * sincWt * kaiserXt);
356 }
357 }
358 }
359 }
360
361 bool SincResampler::input(int input)
362 {
363 bool ready = false;
364
365 /*
366 * Clip the input as it may overflow the 16 bit range.
367 *
368 * Approximate measured input ranges:
369 * 6581: [-24262,+25080] (Kawasaki_Synthesizer_Demo)
370 * 8580: [-21514,+35232] (64_Forever, Drum_Fool)
371 */
372 sample[sampleIndex] = sample[sampleIndex + RINGSIZE] = softClip(input);
373 sampleIndex = (sampleIndex + 1) & (RINGSIZE - 1);
374
375 if (sampleOffset < 1024)
376 {
377 outputValue = fir(sampleOffset);
378 ready = true;
379 sampleOffset += cyclesPerSample;
380 }
381
382 sampleOffset -= 1024;
383
384 return ready;
385 }
386
387 void SincResampler::reset()
388 {
389 memset(sample, 0, sizeof(sample));
390 sampleOffset = 0;
391 }
392
393 } // namespace reSIDfp