annotate garage-resampler/Resampler.cpp @ 16:66abf86c864d

Add bandwidth, snr parameters
author Chris Cannam
date Fri, 18 Oct 2013 14:57:48 +0100
parents 381823e25b8a
children
rev   line source
Chris@0 1 /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */
Chris@0 2
Chris@0 3 #include "Resampler.h"
Chris@0 4
Chris@0 5 #include "qm-dsp/maths/MathUtilities.h"
Chris@0 6 #include "qm-dsp/base/KaiserWindow.h"
Chris@0 7 #include "qm-dsp/base/SincWindow.h"
Chris@9 8 #include "qm-dsp/thread/Thread.h"
Chris@0 9
Chris@0 10 #include <iostream>
Chris@1 11 #include <vector>
Chris@8 12 #include <map>
Chris@10 13 #include <cassert>
Chris@1 14
Chris@1 15 using std::vector;
Chris@8 16 using std::map;
Chris@0 17
Chris@4 18 //#define DEBUG_RESAMPLER 1
Chris@4 19
Chris@0 20 Resampler::Resampler(int sourceRate, int targetRate) :
Chris@0 21 m_sourceRate(sourceRate),
Chris@0 22 m_targetRate(targetRate)
Chris@0 23 {
Chris@16 24 initialise(100, 0.02);
Chris@16 25 }
Chris@16 26
Chris@16 27 Resampler::Resampler(int sourceRate, int targetRate,
Chris@16 28 double snr, double bandwidth) :
Chris@16 29 m_sourceRate(sourceRate),
Chris@16 30 m_targetRate(targetRate)
Chris@16 31 {
Chris@16 32 initialise(snr, bandwidth);
Chris@0 33 }
Chris@0 34
Chris@0 35 Resampler::~Resampler()
Chris@0 36 {
Chris@0 37 delete[] m_phaseData;
Chris@0 38 }
Chris@0 39
Chris@9 40 // peakToPole -> length -> beta -> window
Chris@9 41 static map<int, map<int, map<double, vector<double> > > >
Chris@9 42 knownFilters;
Chris@9 43
Chris@9 44 static Mutex
Chris@9 45 knownFilterMutex;
Chris@9 46
Chris@0 47 void
Chris@16 48 Resampler::initialise(double snr, double bandwidth)
Chris@0 49 {
Chris@0 50 int higher = std::max(m_sourceRate, m_targetRate);
Chris@0 51 int lower = std::min(m_sourceRate, m_targetRate);
Chris@0 52
Chris@0 53 m_gcd = MathUtilities::gcd(lower, higher);
Chris@0 54
Chris@0 55 int peakToPole = higher / m_gcd;
Chris@0 56
Chris@0 57 KaiserWindow::Parameters params =
Chris@16 58 KaiserWindow::parametersForBandwidth(snr, bandwidth, peakToPole);
Chris@0 59
Chris@0 60 params.length =
Chris@0 61 (params.length % 2 == 0 ? params.length + 1 : params.length);
Chris@0 62
Chris@10 63 params.length =
Chris@10 64 (params.length > 200001 ? 200001 : params.length);
Chris@10 65
Chris@0 66 m_filterLength = params.length;
Chris@8 67
Chris@9 68 vector<double> filter;
Chris@9 69 knownFilterMutex.lock();
Chris@0 70
Chris@9 71 if (knownFilters[peakToPole][m_filterLength].find(params.beta) ==
Chris@9 72 knownFilters[peakToPole][m_filterLength].end()) {
Chris@9 73
Chris@9 74 KaiserWindow kw(params);
Chris@9 75 SincWindow sw(m_filterLength, peakToPole * 2);
Chris@9 76
Chris@9 77 filter = vector<double>(m_filterLength, 0.0);
Chris@9 78 for (int i = 0; i < m_filterLength; ++i) filter[i] = 1.0;
Chris@9 79 sw.cut(filter.data());
Chris@9 80 kw.cut(filter.data());
Chris@9 81
Chris@9 82 knownFilters[peakToPole][m_filterLength][params.beta] = filter;
Chris@9 83 }
Chris@9 84
Chris@9 85 filter = knownFilters[peakToPole][m_filterLength][params.beta];
Chris@9 86 knownFilterMutex.unlock();
Chris@0 87
Chris@0 88 int inputSpacing = m_targetRate / m_gcd;
Chris@0 89 int outputSpacing = m_sourceRate / m_gcd;
Chris@0 90
Chris@4 91 #ifdef DEBUG_RESAMPLER
Chris@4 92 std::cerr << "resample " << m_sourceRate << " -> " << m_targetRate
Chris@4 93 << ": inputSpacing " << inputSpacing << ", outputSpacing "
Chris@4 94 << outputSpacing << ": filter length " << m_filterLength
Chris@4 95 << std::endl;
Chris@4 96 #endif
Chris@0 97
Chris@10 98 // Now we have a filter of (odd) length flen in which the lower
Chris@10 99 // sample rate corresponds to every n'th point and the higher rate
Chris@10 100 // to every m'th where n and m are higher and lower rates divided
Chris@10 101 // by their gcd respectively. So if x coordinates are on the same
Chris@10 102 // scale as our filter resolution, then source sample i is at i *
Chris@10 103 // (targetRate / gcd) and target sample j is at j * (sourceRate /
Chris@10 104 // gcd).
Chris@10 105
Chris@10 106 // To reconstruct a single target sample, we want a buffer (real
Chris@10 107 // or virtual) of flen values formed of source samples spaced at
Chris@10 108 // intervals of (targetRate / gcd), in our example case 3. This
Chris@10 109 // is initially formed with the first sample at the filter peak.
Chris@10 110 //
Chris@10 111 // 0 0 0 0 a 0 0 b 0
Chris@10 112 //
Chris@10 113 // and of course we have our filter
Chris@10 114 //
Chris@10 115 // f1 f2 f3 f4 f5 f6 f7 f8 f9
Chris@10 116 //
Chris@10 117 // We take the sum of products of non-zero values from this buffer
Chris@10 118 // with corresponding values in the filter
Chris@10 119 //
Chris@10 120 // a * f5 + b * f8
Chris@10 121 //
Chris@10 122 // Then we drop (sourceRate / gcd) values, in our example case 4,
Chris@10 123 // from the start of the buffer and fill until it has flen values
Chris@10 124 // again
Chris@10 125 //
Chris@10 126 // a 0 0 b 0 0 c 0 0
Chris@10 127 //
Chris@10 128 // repeat to reconstruct the next target sample
Chris@10 129 //
Chris@10 130 // a * f1 + b * f4 + c * f7
Chris@10 131 //
Chris@10 132 // and so on.
Chris@10 133 //
Chris@10 134 // Above I said the buffer could be "real or virtual" -- ours is
Chris@10 135 // virtual. We don't actually store all the zero spacing values,
Chris@10 136 // except for padding at the start; normally we store only the
Chris@10 137 // values that actually came from the source stream, along with a
Chris@10 138 // phase value that tells us how many virtual zeroes there are at
Chris@10 139 // the start of the virtual buffer. So the two examples above are
Chris@10 140 //
Chris@10 141 // 0 a b [ with phase 1 ]
Chris@10 142 // a b c [ with phase 0 ]
Chris@10 143 //
Chris@10 144 // Having thus broken down the buffer so that only the elements we
Chris@10 145 // need to multiply are present, we can also unzip the filter into
Chris@10 146 // every-nth-element subsets at each phase, allowing us to do the
Chris@10 147 // filter multiplication as a simply vector multiply. That is, rather
Chris@10 148 // than store
Chris@10 149 //
Chris@10 150 // f1 f2 f3 f4 f5 f6 f7 f8 f9
Chris@10 151 //
Chris@10 152 // we store separately
Chris@10 153 //
Chris@10 154 // f1 f4 f7
Chris@10 155 // f2 f5 f8
Chris@10 156 // f3 f6 f9
Chris@10 157 //
Chris@10 158 // Each time we complete a multiply-and-sum, we need to work out
Chris@10 159 // how many (real) samples to drop from the start of our buffer,
Chris@10 160 // and how many to add at the end of it for the next multiply. We
Chris@10 161 // know we want to drop enough real samples to move along by one
Chris@10 162 // computed output sample, which is our outputSpacing number of
Chris@10 163 // virtual buffer samples. Depending on the relationship between
Chris@10 164 // input and output spacings, this may mean dropping several real
Chris@10 165 // samples, one real sample, or none at all (and simply moving to
Chris@10 166 // a different "phase").
Chris@10 167
Chris@0 168 m_phaseData = new Phase[inputSpacing];
Chris@0 169
Chris@0 170 for (int phase = 0; phase < inputSpacing; ++phase) {
Chris@0 171
Chris@0 172 Phase p;
Chris@0 173
Chris@0 174 p.nextPhase = phase - outputSpacing;
Chris@0 175 while (p.nextPhase < 0) p.nextPhase += inputSpacing;
Chris@0 176 p.nextPhase %= inputSpacing;
Chris@0 177
Chris@4 178 p.drop = int(ceil(std::max(0.0, double(outputSpacing - phase))
Chris@4 179 / inputSpacing));
Chris@0 180
Chris@4 181 int filtZipLength = int(ceil(double(m_filterLength - phase)
Chris@4 182 / inputSpacing));
Chris@10 183
Chris@0 184 for (int i = 0; i < filtZipLength; ++i) {
Chris@0 185 p.filter.push_back(filter[i * inputSpacing + phase]);
Chris@0 186 }
Chris@0 187
Chris@0 188 m_phaseData[phase] = p;
Chris@0 189 }
Chris@0 190
Chris@0 191 // The May implementation of this uses a pull model -- we ask the
Chris@0 192 // resampler for a certain number of output samples, and it asks
Chris@0 193 // its source stream for as many as it needs to calculate
Chris@0 194 // those. This means (among other things) that the source stream
Chris@0 195 // can be asked for enough samples up-front to fill the buffer
Chris@0 196 // before the first output sample is generated.
Chris@0 197 //
Chris@0 198 // In this implementation we're using a push model in which a
Chris@0 199 // certain number of source samples is provided and we're asked
Chris@0 200 // for as many output samples as that makes available. But we
Chris@0 201 // can't return any samples from the beginning until half the
Chris@0 202 // filter length has been provided as input. This means we must
Chris@0 203 // either return a very variable number of samples (none at all
Chris@0 204 // until the filter fills, then half the filter length at once) or
Chris@0 205 // else have a lengthy declared latency on the output. We do the
Chris@0 206 // latter. (What do other implementations do?)
Chris@11 207 //
Chris@10 208 // We want to make sure the first "real" sample will eventually be
Chris@10 209 // aligned with the centre sample in the filter (it's tidier, and
Chris@10 210 // easier to do diagnostic calculations that way). So we need to
Chris@10 211 // pick the initial phase and buffer fill accordingly.
Chris@10 212 //
Chris@10 213 // Example: if the inputSpacing is 2, outputSpacing is 3, and
Chris@10 214 // filter length is 7,
Chris@10 215 //
Chris@10 216 // x x x x a b c ... input samples
Chris@10 217 // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ...
Chris@10 218 // i j k l ... output samples
Chris@10 219 // [--------|--------] <- filter with centre mark
Chris@10 220 //
Chris@10 221 // Let h be the index of the centre mark, here 3 (generally
Chris@10 222 // int(filterLength/2) for odd-length filters).
Chris@10 223 //
Chris@10 224 // The smallest n such that h + n * outputSpacing > filterLength
Chris@10 225 // is 2 (that is, ceil((filterLength - h) / outputSpacing)), and
Chris@10 226 // (h + 2 * outputSpacing) % inputSpacing == 1, so the initial
Chris@10 227 // phase is 1.
Chris@10 228 //
Chris@10 229 // To achieve our n, we need to pre-fill the "virtual" buffer with
Chris@10 230 // 4 zero samples: the x's above. This is int((h + n *
Chris@10 231 // outputSpacing) / inputSpacing). It's the phase that makes this
Chris@10 232 // buffer get dealt with in such a way as to give us an effective
Chris@10 233 // index for sample a of 9 rather than 8 or 10 or whatever.
Chris@10 234 //
Chris@10 235 // This gives us output latency of 2 (== n), i.e. output samples i
Chris@10 236 // and j will appear before the one in which input sample a is at
Chris@10 237 // the centre of the filter.
Chris@10 238
Chris@10 239 int h = int(m_filterLength / 2);
Chris@10 240 int n = ceil(double(m_filterLength - h) / outputSpacing);
Chris@4 241
Chris@10 242 m_phase = (h + n * outputSpacing) % inputSpacing;
Chris@10 243
Chris@10 244 int fill = (h + n * outputSpacing) / inputSpacing;
Chris@10 245
Chris@10 246 m_latency = n;
Chris@10 247
Chris@10 248 m_buffer = vector<double>(fill, 0);
Chris@8 249 m_bufferOrigin = 0;
Chris@4 250
Chris@4 251 #ifdef DEBUG_RESAMPLER
Chris@4 252 std::cerr << "initial phase " << m_phase << " (as " << (m_filterLength/2) << " % " << inputSpacing << ")"
Chris@4 253 << ", latency " << m_latency << std::endl;
Chris@4 254 #endif
Chris@0 255 }
Chris@0 256
Chris@0 257 double
Chris@4 258 Resampler::reconstructOne()
Chris@0 259 {
Chris@0 260 Phase &pd = m_phaseData[m_phase];
Chris@4 261 double v = 0.0;
Chris@0 262 int n = pd.filter.size();
Chris@10 263
Chris@11 264 assert(n + m_bufferOrigin <= (int)m_buffer.size());
Chris@10 265
Chris@8 266 const double *const __restrict__ buf = m_buffer.data() + m_bufferOrigin;
Chris@8 267 const double *const __restrict__ filt = pd.filter.data();
Chris@10 268
Chris@10 269 // std::cerr << "phase = " << m_phase << ", drop = " << pd.drop << ", buffer for reconstruction starts...";
Chris@10 270 // for (int i = 0; i < 20; ++i) {
Chris@10 271 // if (i % 5 == 0) std::cerr << "\n" << i << " ";
Chris@10 272 // std::cerr << buf[i] << " ";
Chris@10 273 // }
Chris@10 274 // std::cerr << std::endl;
Chris@10 275
Chris@0 276 for (int i = 0; i < n; ++i) {
Chris@8 277 // NB gcc can only vectorize this with -ffast-math
Chris@8 278 v += buf[i] * filt[i];
Chris@0 279 }
Chris@16 280
Chris@8 281 m_bufferOrigin += pd.drop;
Chris@4 282 m_phase = pd.nextPhase;
Chris@0 283 return v;
Chris@0 284 }
Chris@0 285
Chris@0 286 int
Chris@4 287 Resampler::process(const double *src, double *dst, int n)
Chris@0 288 {
Chris@4 289 for (int i = 0; i < n; ++i) {
Chris@4 290 m_buffer.push_back(src[i]);
Chris@0 291 }
Chris@0 292
Chris@4 293 int maxout = int(ceil(double(n) * m_targetRate / m_sourceRate));
Chris@4 294 int outidx = 0;
Chris@2 295
Chris@4 296 #ifdef DEBUG_RESAMPLER
Chris@4 297 std::cerr << "process: buf siz " << m_buffer.size() << " filt siz for phase " << m_phase << " " << m_phaseData[m_phase].filter.size() << std::endl;
Chris@4 298 #endif
Chris@4 299
Chris@5 300 double scaleFactor = 1.0;
Chris@5 301 if (m_targetRate < m_sourceRate) {
Chris@5 302 scaleFactor = double(m_targetRate) / double(m_sourceRate);
Chris@5 303 }
Chris@5 304
Chris@4 305 while (outidx < maxout &&
Chris@8 306 m_buffer.size() >= m_phaseData[m_phase].filter.size() + m_bufferOrigin) {
Chris@5 307 dst[outidx] = scaleFactor * reconstructOne();
Chris@4 308 outidx++;
Chris@2 309 }
Chris@8 310
Chris@8 311 m_buffer = vector<double>(m_buffer.begin() + m_bufferOrigin, m_buffer.end());
Chris@8 312 m_bufferOrigin = 0;
Chris@4 313
Chris@4 314 return outidx;
Chris@0 315 }
Chris@4 316
Chris@1 317 std::vector<double>
Chris@1 318 Resampler::resample(int sourceRate, int targetRate, const double *data, int n)
Chris@1 319 {
Chris@1 320 Resampler r(sourceRate, targetRate);
Chris@1 321
Chris@1 322 int latency = r.getLatency();
Chris@1 323
Chris@6 324 // latency is the output latency. We need to provide enough
Chris@6 325 // padding input samples at the end of input to guarantee at
Chris@6 326 // *least* the latency's worth of output samples. that is,
Chris@6 327
Chris@11 328 int inputPad = int(ceil((double(latency) * sourceRate) / targetRate));
Chris@6 329
Chris@6 330 // that means we are providing this much input in total:
Chris@6 331
Chris@6 332 int n1 = n + inputPad;
Chris@6 333
Chris@6 334 // and obtaining this much output in total:
Chris@6 335
Chris@11 336 int m1 = int(ceil((double(n1) * targetRate) / sourceRate));
Chris@6 337
Chris@6 338 // in order to return this much output to the user:
Chris@6 339
Chris@11 340 int m = int(ceil((double(n) * targetRate) / sourceRate));
Chris@6 341
Chris@11 342 // std::cerr << "n = " << n << ", sourceRate = " << sourceRate << ", targetRate = " << targetRate << ", m = " << m << ", latency = " << latency << ", inputPad = " << inputPad << ", m1 = " << m1 << ", n1 = " << n1 << ", n1 - n = " << n1 - n << std::endl;
Chris@1 343
Chris@1 344 vector<double> pad(n1 - n, 0.0);
Chris@6 345 vector<double> out(m1 + 1, 0.0);
Chris@1 346
Chris@1 347 int got = r.process(data, out.data(), n);
Chris@1 348 got += r.process(pad.data(), out.data() + got, pad.size());
Chris@1 349
Chris@4 350 #ifdef DEBUG_RESAMPLER
Chris@4 351 std::cerr << "resample: " << n << " in, " << got << " out" << std::endl;
Chris@10 352 std::cerr << "first 10 in:" << std::endl;
Chris@10 353 for (int i = 0; i < 10; ++i) {
Chris@10 354 std::cerr << data[i] << " ";
Chris@10 355 if (i == 5) std::cerr << std::endl;
Chris@4 356 }
Chris@10 357 std::cerr << std::endl;
Chris@4 358 #endif
Chris@4 359
Chris@6 360 int toReturn = got - latency;
Chris@6 361 if (toReturn > m) toReturn = m;
Chris@6 362
Chris@10 363 vector<double> sliced(out.begin() + latency,
Chris@6 364 out.begin() + latency + toReturn);
Chris@10 365
Chris@10 366 #ifdef DEBUG_RESAMPLER
Chris@10 367 std::cerr << "all out (after latency compensation), length " << sliced.size() << ":";
Chris@10 368 for (int i = 0; i < sliced.size(); ++i) {
Chris@10 369 if (i % 5 == 0) std::cerr << std::endl << i << "... ";
Chris@10 370 std::cerr << sliced[i] << " ";
Chris@10 371 }
Chris@10 372 std::cerr << std::endl;
Chris@10 373 #endif
Chris@10 374
Chris@10 375 return sliced;
Chris@1 376 }
Chris@1 377