annotate dsp/rateconversion/Resampler.cpp @ 147:c1e98c18628a

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