annotate constant-q-cpp/src/dsp/Resampler.cpp @ 372:af71cbdab621 tip

Update bqvec code
author Chris Cannam
date Tue, 19 Nov 2019 10:13:32 +0000
parents 5d0a2ebb4d17
children
rev   line source
Chris@366 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
Chris@366 2 /*
Chris@366 3 Constant-Q library
Chris@366 4 Copyright (c) 2013-2014 Queen Mary, University of London
Chris@366 5
Chris@366 6 Permission is hereby granted, free of charge, to any person
Chris@366 7 obtaining a copy of this software and associated documentation
Chris@366 8 files (the "Software"), to deal in the Software without
Chris@366 9 restriction, including without limitation the rights to use, copy,
Chris@366 10 modify, merge, publish, distribute, sublicense, and/or sell copies
Chris@366 11 of the Software, and to permit persons to whom the Software is
Chris@366 12 furnished to do so, subject to the following conditions:
Chris@366 13
Chris@366 14 The above copyright notice and this permission notice shall be
Chris@366 15 included in all copies or substantial portions of the Software.
Chris@366 16
Chris@366 17 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
Chris@366 18 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
Chris@366 19 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
Chris@366 20 NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
Chris@366 21 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
Chris@366 22 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
Chris@366 23 WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
Chris@366 24
Chris@366 25 Except as contained in this notice, the names of the Centre for
Chris@366 26 Digital Music; Queen Mary, University of London; and Chris Cannam
Chris@366 27 shall not be used in advertising or otherwise to promote the sale,
Chris@366 28 use or other dealings in this Software without prior written
Chris@366 29 authorization.
Chris@366 30 */
Chris@366 31
Chris@366 32 #include "Resampler.h"
Chris@366 33
Chris@366 34 #include "MathUtilities.h"
Chris@366 35 #include "KaiserWindow.h"
Chris@366 36 #include "SincWindow.h"
Chris@366 37
Chris@366 38 #include <iostream>
Chris@366 39 #include <vector>
Chris@366 40 #include <map>
Chris@366 41 #include <cassert>
Chris@366 42 #include <algorithm>
Chris@366 43
Chris@366 44 using std::vector;
Chris@366 45 using std::map;
Chris@366 46 using std::cerr;
Chris@366 47 using std::endl;
Chris@366 48
Chris@366 49 //#define DEBUG_RESAMPLER 1
Chris@366 50 //#define DEBUG_RESAMPLER_VERBOSE 1
Chris@366 51
Chris@366 52 Resampler::Resampler(int sourceRate, int targetRate) :
Chris@366 53 m_sourceRate(sourceRate),
Chris@366 54 m_targetRate(targetRate)
Chris@366 55 {
Chris@366 56 initialise(100, 0.02);
Chris@366 57 }
Chris@366 58
Chris@366 59 Resampler::Resampler(int sourceRate, int targetRate,
Chris@366 60 double snr, double bandwidth) :
Chris@366 61 m_sourceRate(sourceRate),
Chris@366 62 m_targetRate(targetRate)
Chris@366 63 {
Chris@366 64 initialise(snr, bandwidth);
Chris@366 65 }
Chris@366 66
Chris@366 67 Resampler::~Resampler()
Chris@366 68 {
Chris@366 69 delete[] m_phaseData;
Chris@366 70 }
Chris@366 71
Chris@366 72 void
Chris@366 73 Resampler::initialise(double snr, double bandwidth)
Chris@366 74 {
Chris@366 75 int higher = std::max(m_sourceRate, m_targetRate);
Chris@366 76 int lower = std::min(m_sourceRate, m_targetRate);
Chris@366 77
Chris@366 78 m_gcd = MathUtilities::gcd(lower, higher);
Chris@366 79 m_peakToPole = higher / m_gcd;
Chris@366 80
Chris@366 81 if (m_targetRate < m_sourceRate) {
Chris@366 82 // antialiasing filter, should be slightly below nyquist
Chris@366 83 m_peakToPole = m_peakToPole / (1.0 - bandwidth/2.0);
Chris@366 84 }
Chris@366 85
Chris@366 86 KaiserWindow::Parameters params =
Chris@366 87 KaiserWindow::parametersForBandwidth(snr, bandwidth, higher / m_gcd);
Chris@366 88
Chris@366 89 params.length =
Chris@366 90 (params.length % 2 == 0 ? params.length + 1 : params.length);
Chris@366 91
Chris@366 92 params.length =
Chris@366 93 (params.length > 200001 ? 200001 : params.length);
Chris@366 94
Chris@366 95 m_filterLength = params.length;
Chris@366 96
Chris@366 97 vector<double> filter;
Chris@366 98
Chris@366 99 KaiserWindow kw(params);
Chris@366 100 SincWindow sw(m_filterLength, m_peakToPole * 2);
Chris@366 101
Chris@366 102 filter = vector<double>(m_filterLength, 0.0);
Chris@366 103 for (int i = 0; i < m_filterLength; ++i) filter[i] = 1.0;
Chris@366 104 sw.cut(filter.data());
Chris@366 105 kw.cut(filter.data());
Chris@366 106
Chris@366 107 int inputSpacing = m_targetRate / m_gcd;
Chris@366 108 int outputSpacing = m_sourceRate / m_gcd;
Chris@366 109
Chris@366 110 #ifdef DEBUG_RESAMPLER
Chris@366 111 cerr << "resample " << m_sourceRate << " -> " << m_targetRate
Chris@366 112 << ": inputSpacing " << inputSpacing << ", outputSpacing "
Chris@366 113 << outputSpacing << ": filter length " << m_filterLength
Chris@366 114 << endl;
Chris@366 115 #endif
Chris@366 116
Chris@366 117 // Now we have a filter of (odd) length flen in which the lower
Chris@366 118 // sample rate corresponds to every n'th point and the higher rate
Chris@366 119 // to every m'th where n and m are higher and lower rates divided
Chris@366 120 // by their gcd respectively. So if x coordinates are on the same
Chris@366 121 // scale as our filter resolution, then source sample i is at i *
Chris@366 122 // (targetRate / gcd) and target sample j is at j * (sourceRate /
Chris@366 123 // gcd).
Chris@366 124
Chris@366 125 // To reconstruct a single target sample, we want a buffer (real
Chris@366 126 // or virtual) of flen values formed of source samples spaced at
Chris@366 127 // intervals of (targetRate / gcd), in our example case 3. This
Chris@366 128 // is initially formed with the first sample at the filter peak.
Chris@366 129 //
Chris@366 130 // 0 0 0 0 a 0 0 b 0
Chris@366 131 //
Chris@366 132 // and of course we have our filter
Chris@366 133 //
Chris@366 134 // f1 f2 f3 f4 f5 f6 f7 f8 f9
Chris@366 135 //
Chris@366 136 // We take the sum of products of non-zero values from this buffer
Chris@366 137 // with corresponding values in the filter
Chris@366 138 //
Chris@366 139 // a * f5 + b * f8
Chris@366 140 //
Chris@366 141 // Then we drop (sourceRate / gcd) values, in our example case 4,
Chris@366 142 // from the start of the buffer and fill until it has flen values
Chris@366 143 // again
Chris@366 144 //
Chris@366 145 // a 0 0 b 0 0 c 0 0
Chris@366 146 //
Chris@366 147 // repeat to reconstruct the next target sample
Chris@366 148 //
Chris@366 149 // a * f1 + b * f4 + c * f7
Chris@366 150 //
Chris@366 151 // and so on.
Chris@366 152 //
Chris@366 153 // Above I said the buffer could be "real or virtual" -- ours is
Chris@366 154 // virtual. We don't actually store all the zero spacing values,
Chris@366 155 // except for padding at the start; normally we store only the
Chris@366 156 // values that actually came from the source stream, along with a
Chris@366 157 // phase value that tells us how many virtual zeroes there are at
Chris@366 158 // the start of the virtual buffer. So the two examples above are
Chris@366 159 //
Chris@366 160 // 0 a b [ with phase 1 ]
Chris@366 161 // a b c [ with phase 0 ]
Chris@366 162 //
Chris@366 163 // Having thus broken down the buffer so that only the elements we
Chris@366 164 // need to multiply are present, we can also unzip the filter into
Chris@366 165 // every-nth-element subsets at each phase, allowing us to do the
Chris@366 166 // filter multiplication as a simply vector multiply. That is, rather
Chris@366 167 // than store
Chris@366 168 //
Chris@366 169 // f1 f2 f3 f4 f5 f6 f7 f8 f9
Chris@366 170 //
Chris@366 171 // we store separately
Chris@366 172 //
Chris@366 173 // f1 f4 f7
Chris@366 174 // f2 f5 f8
Chris@366 175 // f3 f6 f9
Chris@366 176 //
Chris@366 177 // Each time we complete a multiply-and-sum, we need to work out
Chris@366 178 // how many (real) samples to drop from the start of our buffer,
Chris@366 179 // and how many to add at the end of it for the next multiply. We
Chris@366 180 // know we want to drop enough real samples to move along by one
Chris@366 181 // computed output sample, which is our outputSpacing number of
Chris@366 182 // virtual buffer samples. Depending on the relationship between
Chris@366 183 // input and output spacings, this may mean dropping several real
Chris@366 184 // samples, one real sample, or none at all (and simply moving to
Chris@366 185 // a different "phase").
Chris@366 186
Chris@366 187 m_phaseData = new Phase[inputSpacing];
Chris@366 188
Chris@366 189 for (int phase = 0; phase < inputSpacing; ++phase) {
Chris@366 190
Chris@366 191 Phase p;
Chris@366 192
Chris@366 193 p.nextPhase = phase - outputSpacing;
Chris@366 194 while (p.nextPhase < 0) p.nextPhase += inputSpacing;
Chris@366 195 p.nextPhase %= inputSpacing;
Chris@366 196
Chris@366 197 p.drop = int(ceil(std::max(0.0, double(outputSpacing - phase))
Chris@366 198 / inputSpacing));
Chris@366 199
Chris@366 200 int filtZipLength = int(ceil(double(m_filterLength - phase)
Chris@366 201 / inputSpacing));
Chris@366 202
Chris@366 203 for (int i = 0; i < filtZipLength; ++i) {
Chris@366 204 p.filter.push_back(filter[i * inputSpacing + phase]);
Chris@366 205 }
Chris@366 206
Chris@366 207 m_phaseData[phase] = p;
Chris@366 208 }
Chris@366 209
Chris@366 210 #ifdef DEBUG_RESAMPLER
Chris@366 211 int cp = 0;
Chris@366 212 int totDrop = 0;
Chris@366 213 for (int i = 0; i < inputSpacing; ++i) {
Chris@366 214 cerr << "phase = " << cp << ", drop = " << m_phaseData[cp].drop
Chris@366 215 << ", filter length = " << m_phaseData[cp].filter.size()
Chris@366 216 << ", next phase = " << m_phaseData[cp].nextPhase << endl;
Chris@366 217 totDrop += m_phaseData[cp].drop;
Chris@366 218 cp = m_phaseData[cp].nextPhase;
Chris@366 219 }
Chris@366 220 cerr << "total drop = " << totDrop << endl;
Chris@366 221 #endif
Chris@366 222
Chris@366 223 // The May implementation of this uses a pull model -- we ask the
Chris@366 224 // resampler for a certain number of output samples, and it asks
Chris@366 225 // its source stream for as many as it needs to calculate
Chris@366 226 // those. This means (among other things) that the source stream
Chris@366 227 // can be asked for enough samples up-front to fill the buffer
Chris@366 228 // before the first output sample is generated.
Chris@366 229 //
Chris@366 230 // In this implementation we're using a push model in which a
Chris@366 231 // certain number of source samples is provided and we're asked
Chris@366 232 // for as many output samples as that makes available. But we
Chris@366 233 // can't return any samples from the beginning until half the
Chris@366 234 // filter length has been provided as input. This means we must
Chris@366 235 // either return a very variable number of samples (none at all
Chris@366 236 // until the filter fills, then half the filter length at once) or
Chris@366 237 // else have a lengthy declared latency on the output. We do the
Chris@366 238 // latter. (What do other implementations do?)
Chris@366 239 //
Chris@366 240 // We want to make sure the first "real" sample will eventually be
Chris@366 241 // aligned with the centre sample in the filter (it's tidier, and
Chris@366 242 // easier to do diagnostic calculations that way). So we need to
Chris@366 243 // pick the initial phase and buffer fill accordingly.
Chris@366 244 //
Chris@366 245 // Example: if the inputSpacing is 2, outputSpacing is 3, and
Chris@366 246 // filter length is 7,
Chris@366 247 //
Chris@366 248 // x x x x a b c ... input samples
Chris@366 249 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
Chris@366 250 // i j k l ... output samples
Chris@366 251 // [--------|--------] <- filter with centre mark
Chris@366 252 //
Chris@366 253 // Let h be the index of the centre mark, here 3 (generally
Chris@366 254 // int(filterLength/2) for odd-length filters).
Chris@366 255 //
Chris@366 256 // The smallest n such that h + n * outputSpacing > filterLength
Chris@366 257 // is 2 (that is, ceil((filterLength - h) / outputSpacing)), and
Chris@366 258 // (h + 2 * outputSpacing) % inputSpacing == 1, so the initial
Chris@366 259 // phase is 1.
Chris@366 260 //
Chris@366 261 // To achieve our n, we need to pre-fill the "virtual" buffer with
Chris@366 262 // 4 zero samples: the x's above. This is int((h + n *
Chris@366 263 // outputSpacing) / inputSpacing). It's the phase that makes this
Chris@366 264 // buffer get dealt with in such a way as to give us an effective
Chris@366 265 // index for sample a of 9 rather than 8 or 10 or whatever.
Chris@366 266 //
Chris@366 267 // This gives us output latency of 2 (== n), i.e. output samples i
Chris@366 268 // and j will appear before the one in which input sample a is at
Chris@366 269 // the centre of the filter.
Chris@366 270
Chris@366 271 int h = int(m_filterLength / 2);
Chris@366 272 int n = ceil(double(m_filterLength - h) / outputSpacing);
Chris@366 273
Chris@366 274 m_phase = (h + n * outputSpacing) % inputSpacing;
Chris@366 275
Chris@366 276 int fill = (h + n * outputSpacing) / inputSpacing;
Chris@366 277
Chris@366 278 m_latency = n;
Chris@366 279
Chris@366 280 m_buffer = vector<double>(fill, 0);
Chris@366 281 m_bufferOrigin = 0;
Chris@366 282
Chris@366 283 #ifdef DEBUG_RESAMPLER
Chris@366 284 cerr << "initial phase " << m_phase << " (as " << (m_filterLength/2) << " % " << inputSpacing << ")"
Chris@366 285 << ", latency " << m_latency << endl;
Chris@366 286 #endif
Chris@366 287 }
Chris@366 288
Chris@366 289 double
Chris@366 290 Resampler::reconstructOne()
Chris@366 291 {
Chris@366 292 Phase &pd = m_phaseData[m_phase];
Chris@366 293 double v = 0.0;
Chris@366 294 int n = pd.filter.size();
Chris@366 295
Chris@366 296 assert(n + m_bufferOrigin <= (int)m_buffer.size());
Chris@366 297
Chris@366 298 #if defined(__MSVC__)
Chris@366 299 #define R__ __restrict
Chris@366 300 #elif defined(__GNUC__)
Chris@366 301 #define R__ __restrict__
Chris@366 302 #else
Chris@366 303 #define R__
Chris@366 304 #endif
Chris@366 305
Chris@366 306 const double *const R__ buf(m_buffer.data() + m_bufferOrigin);
Chris@366 307 const double *const R__ filt(pd.filter.data());
Chris@366 308
Chris@366 309 for (int i = 0; i < n; ++i) {
Chris@366 310 // NB gcc can only vectorize this with -ffast-math
Chris@366 311 v += buf[i] * filt[i];
Chris@366 312 }
Chris@366 313
Chris@366 314 m_bufferOrigin += pd.drop;
Chris@366 315 m_phase = pd.nextPhase;
Chris@366 316 return v;
Chris@366 317 }
Chris@366 318
Chris@366 319 int
Chris@366 320 Resampler::process(const double *src, double *dst, int n)
Chris@366 321 {
Chris@366 322 m_buffer.insert(m_buffer.end(), src, src + n);
Chris@366 323
Chris@366 324 int maxout = int(ceil(double(n) * m_targetRate / m_sourceRate));
Chris@366 325 int outidx = 0;
Chris@366 326
Chris@366 327 #ifdef DEBUG_RESAMPLER
Chris@366 328 cerr << "process: buf siz " << m_buffer.size() << " filt siz for phase " << m_phase << " " << m_phaseData[m_phase].filter.size() << endl;
Chris@366 329 #endif
Chris@366 330
Chris@366 331 double scaleFactor = (double(m_targetRate) / m_gcd) / m_peakToPole;
Chris@366 332
Chris@366 333 while (outidx < maxout &&
Chris@366 334 m_buffer.size() >= m_phaseData[m_phase].filter.size() + m_bufferOrigin) {
Chris@366 335 dst[outidx] = scaleFactor * reconstructOne();
Chris@366 336 outidx++;
Chris@366 337 }
Chris@366 338
Chris@366 339 m_buffer = vector<double>(m_buffer.begin() + m_bufferOrigin, m_buffer.end());
Chris@366 340 m_bufferOrigin = 0;
Chris@366 341
Chris@366 342 return outidx;
Chris@366 343 }
Chris@366 344
Chris@366 345 vector<double>
Chris@366 346 Resampler::process(const double *src, int n)
Chris@366 347 {
Chris@366 348 int maxout = int(ceil(double(n) * m_targetRate / m_sourceRate));
Chris@366 349 vector<double> out(maxout, 0.0);
Chris@366 350 int got = process(src, out.data(), n);
Chris@366 351 assert(got <= maxout);
Chris@366 352 if (got < maxout) out.resize(got);
Chris@366 353 return out;
Chris@366 354 }
Chris@366 355
Chris@366 356 vector<double>
Chris@366 357 Resampler::resample(int sourceRate, int targetRate, const double *data, int n)
Chris@366 358 {
Chris@366 359 Resampler r(sourceRate, targetRate);
Chris@366 360
Chris@366 361 int latency = r.getLatency();
Chris@366 362
Chris@366 363 // latency is the output latency. We need to provide enough
Chris@366 364 // padding input samples at the end of input to guarantee at
Chris@366 365 // *least* the latency's worth of output samples. that is,
Chris@366 366
Chris@366 367 int inputPad = int(ceil((double(latency) * sourceRate) / targetRate));
Chris@366 368
Chris@366 369 // that means we are providing this much input in total:
Chris@366 370
Chris@366 371 int n1 = n + inputPad;
Chris@366 372
Chris@366 373 // and obtaining this much output in total:
Chris@366 374
Chris@366 375 int m1 = int(ceil((double(n1) * targetRate) / sourceRate));
Chris@366 376
Chris@366 377 // in order to return this much output to the user:
Chris@366 378
Chris@366 379 int m = int(ceil((double(n) * targetRate) / sourceRate));
Chris@366 380
Chris@366 381 #ifdef DEBUG_RESAMPLER
Chris@366 382 cerr << "n = " << n << ", sourceRate = " << sourceRate << ", targetRate = " << targetRate << ", m = " << m << ", latency = " << latency << ", inputPad = " << inputPad << ", m1 = " << m1 << ", n1 = " << n1 << ", n1 - n = " << n1 - n << endl;
Chris@366 383 #endif
Chris@366 384
Chris@366 385 vector<double> pad(n1 - n, 0.0);
Chris@366 386 vector<double> out(m1 + 1, 0.0);
Chris@366 387
Chris@366 388 int gotData = r.process(data, out.data(), n);
Chris@366 389 int gotPad = r.process(pad.data(), out.data() + gotData, pad.size());
Chris@366 390 int got = gotData + gotPad;
Chris@366 391
Chris@366 392 #ifdef DEBUG_RESAMPLER
Chris@366 393 cerr << "resample: " << n << " in, " << pad.size() << " padding, " << got << " out (" << gotData << " data, " << gotPad << " padding, latency = " << latency << ")" << endl;
Chris@366 394 #endif
Chris@366 395 #ifdef DEBUG_RESAMPLER_VERBOSE
Chris@366 396 int printN = 50;
Chris@366 397 cerr << "first " << printN << " in:" << endl;
Chris@366 398 for (int i = 0; i < printN && i < n; ++i) {
Chris@366 399 if (i % 5 == 0) cerr << endl << i << "... ";
Chris@366 400 cerr << data[i] << " ";
Chris@366 401 }
Chris@366 402 cerr << endl;
Chris@366 403 #endif
Chris@366 404
Chris@366 405 int toReturn = got - latency;
Chris@366 406 if (toReturn > m) toReturn = m;
Chris@366 407
Chris@366 408 vector<double> sliced(out.begin() + latency,
Chris@366 409 out.begin() + latency + toReturn);
Chris@366 410
Chris@366 411 #ifdef DEBUG_RESAMPLER_VERBOSE
Chris@366 412 cerr << "first " << printN << " out (after latency compensation), length " << sliced.size() << ":";
Chris@366 413 for (int i = 0; i < printN && i < sliced.size(); ++i) {
Chris@366 414 if (i % 5 == 0) cerr << endl << i << "... ";
Chris@366 415 cerr << sliced[i] << " ";
Chris@366 416 }
Chris@366 417 cerr << endl;
Chris@366 418 #endif
Chris@366 419
Chris@366 420 return sliced;
Chris@366 421 }
Chris@366 422