Chris@366: /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ Chris@366: /* Chris@366: Constant-Q library Chris@366: Copyright (c) 2013-2014 Queen Mary, University of London Chris@366: Chris@366: Permission is hereby granted, free of charge, to any person Chris@366: obtaining a copy of this software and associated documentation Chris@366: files (the "Software"), to deal in the Software without Chris@366: restriction, including without limitation the rights to use, copy, Chris@366: modify, merge, publish, distribute, sublicense, and/or sell copies Chris@366: of the Software, and to permit persons to whom the Software is Chris@366: furnished to do so, subject to the following conditions: Chris@366: Chris@366: The above copyright notice and this permission notice shall be Chris@366: included in all copies or substantial portions of the Software. Chris@366: Chris@366: THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, Chris@366: EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF Chris@366: MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND Chris@366: NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY Chris@366: CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF Chris@366: CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION Chris@366: WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Chris@366: Chris@366: Except as contained in this notice, the names of the Centre for Chris@366: Digital Music; Queen Mary, University of London; and Chris Cannam Chris@366: shall not be used in advertising or otherwise to promote the sale, Chris@366: use or other dealings in this Software without prior written Chris@366: authorization. Chris@366: */ Chris@366: Chris@366: #include "Resampler.h" Chris@366: Chris@366: #include "MathUtilities.h" Chris@366: #include "KaiserWindow.h" Chris@366: #include "SincWindow.h" Chris@366: Chris@366: #include Chris@366: #include Chris@366: #include Chris@366: #include Chris@366: #include Chris@366: Chris@366: using std::vector; Chris@366: using std::map; Chris@366: using std::cerr; Chris@366: using std::endl; Chris@366: Chris@366: //#define DEBUG_RESAMPLER 1 Chris@366: //#define DEBUG_RESAMPLER_VERBOSE 1 Chris@366: Chris@366: Resampler::Resampler(int sourceRate, int targetRate) : Chris@366: m_sourceRate(sourceRate), Chris@366: m_targetRate(targetRate) Chris@366: { Chris@366: initialise(100, 0.02); Chris@366: } Chris@366: Chris@366: Resampler::Resampler(int sourceRate, int targetRate, Chris@366: double snr, double bandwidth) : Chris@366: m_sourceRate(sourceRate), Chris@366: m_targetRate(targetRate) Chris@366: { Chris@366: initialise(snr, bandwidth); Chris@366: } Chris@366: Chris@366: Resampler::~Resampler() Chris@366: { Chris@366: delete[] m_phaseData; Chris@366: } Chris@366: Chris@366: void Chris@366: Resampler::initialise(double snr, double bandwidth) Chris@366: { Chris@366: int higher = std::max(m_sourceRate, m_targetRate); Chris@366: int lower = std::min(m_sourceRate, m_targetRate); Chris@366: Chris@366: m_gcd = MathUtilities::gcd(lower, higher); Chris@366: m_peakToPole = higher / m_gcd; Chris@366: Chris@366: if (m_targetRate < m_sourceRate) { Chris@366: // antialiasing filter, should be slightly below nyquist Chris@366: m_peakToPole = m_peakToPole / (1.0 - bandwidth/2.0); Chris@366: } Chris@366: Chris@366: KaiserWindow::Parameters params = Chris@366: KaiserWindow::parametersForBandwidth(snr, bandwidth, higher / m_gcd); Chris@366: Chris@366: params.length = Chris@366: (params.length % 2 == 0 ? params.length + 1 : params.length); Chris@366: Chris@366: params.length = Chris@366: (params.length > 200001 ? 200001 : params.length); Chris@366: Chris@366: m_filterLength = params.length; Chris@366: Chris@366: vector filter; Chris@366: Chris@366: KaiserWindow kw(params); Chris@366: SincWindow sw(m_filterLength, m_peakToPole * 2); Chris@366: Chris@366: filter = vector(m_filterLength, 0.0); Chris@366: for (int i = 0; i < m_filterLength; ++i) filter[i] = 1.0; Chris@366: sw.cut(filter.data()); Chris@366: kw.cut(filter.data()); Chris@366: Chris@366: int inputSpacing = m_targetRate / m_gcd; Chris@366: int outputSpacing = m_sourceRate / m_gcd; Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER Chris@366: cerr << "resample " << m_sourceRate << " -> " << m_targetRate Chris@366: << ": inputSpacing " << inputSpacing << ", outputSpacing " Chris@366: << outputSpacing << ": filter length " << m_filterLength Chris@366: << endl; Chris@366: #endif Chris@366: Chris@366: // Now we have a filter of (odd) length flen in which the lower Chris@366: // sample rate corresponds to every n'th point and the higher rate Chris@366: // to every m'th where n and m are higher and lower rates divided Chris@366: // by their gcd respectively. So if x coordinates are on the same Chris@366: // scale as our filter resolution, then source sample i is at i * Chris@366: // (targetRate / gcd) and target sample j is at j * (sourceRate / Chris@366: // gcd). Chris@366: Chris@366: // To reconstruct a single target sample, we want a buffer (real Chris@366: // or virtual) of flen values formed of source samples spaced at Chris@366: // intervals of (targetRate / gcd), in our example case 3. This Chris@366: // is initially formed with the first sample at the filter peak. Chris@366: // Chris@366: // 0 0 0 0 a 0 0 b 0 Chris@366: // Chris@366: // and of course we have our filter Chris@366: // Chris@366: // f1 f2 f3 f4 f5 f6 f7 f8 f9 Chris@366: // Chris@366: // We take the sum of products of non-zero values from this buffer Chris@366: // with corresponding values in the filter Chris@366: // Chris@366: // a * f5 + b * f8 Chris@366: // Chris@366: // Then we drop (sourceRate / gcd) values, in our example case 4, Chris@366: // from the start of the buffer and fill until it has flen values Chris@366: // again Chris@366: // Chris@366: // a 0 0 b 0 0 c 0 0 Chris@366: // Chris@366: // repeat to reconstruct the next target sample Chris@366: // Chris@366: // a * f1 + b * f4 + c * f7 Chris@366: // Chris@366: // and so on. Chris@366: // Chris@366: // Above I said the buffer could be "real or virtual" -- ours is Chris@366: // virtual. We don't actually store all the zero spacing values, Chris@366: // except for padding at the start; normally we store only the Chris@366: // values that actually came from the source stream, along with a Chris@366: // phase value that tells us how many virtual zeroes there are at Chris@366: // the start of the virtual buffer. So the two examples above are Chris@366: // Chris@366: // 0 a b [ with phase 1 ] Chris@366: // a b c [ with phase 0 ] Chris@366: // Chris@366: // Having thus broken down the buffer so that only the elements we Chris@366: // need to multiply are present, we can also unzip the filter into Chris@366: // every-nth-element subsets at each phase, allowing us to do the Chris@366: // filter multiplication as a simply vector multiply. That is, rather Chris@366: // than store Chris@366: // Chris@366: // f1 f2 f3 f4 f5 f6 f7 f8 f9 Chris@366: // Chris@366: // we store separately Chris@366: // Chris@366: // f1 f4 f7 Chris@366: // f2 f5 f8 Chris@366: // f3 f6 f9 Chris@366: // Chris@366: // Each time we complete a multiply-and-sum, we need to work out Chris@366: // how many (real) samples to drop from the start of our buffer, Chris@366: // and how many to add at the end of it for the next multiply. We Chris@366: // know we want to drop enough real samples to move along by one Chris@366: // computed output sample, which is our outputSpacing number of Chris@366: // virtual buffer samples. Depending on the relationship between Chris@366: // input and output spacings, this may mean dropping several real Chris@366: // samples, one real sample, or none at all (and simply moving to Chris@366: // a different "phase"). Chris@366: Chris@366: m_phaseData = new Phase[inputSpacing]; Chris@366: Chris@366: for (int phase = 0; phase < inputSpacing; ++phase) { Chris@366: Chris@366: Phase p; Chris@366: Chris@366: p.nextPhase = phase - outputSpacing; Chris@366: while (p.nextPhase < 0) p.nextPhase += inputSpacing; Chris@366: p.nextPhase %= inputSpacing; Chris@366: Chris@366: p.drop = int(ceil(std::max(0.0, double(outputSpacing - phase)) Chris@366: / inputSpacing)); Chris@366: Chris@366: int filtZipLength = int(ceil(double(m_filterLength - phase) Chris@366: / inputSpacing)); Chris@366: Chris@366: for (int i = 0; i < filtZipLength; ++i) { Chris@366: p.filter.push_back(filter[i * inputSpacing + phase]); Chris@366: } Chris@366: Chris@366: m_phaseData[phase] = p; Chris@366: } Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER Chris@366: int cp = 0; Chris@366: int totDrop = 0; Chris@366: for (int i = 0; i < inputSpacing; ++i) { Chris@366: cerr << "phase = " << cp << ", drop = " << m_phaseData[cp].drop Chris@366: << ", filter length = " << m_phaseData[cp].filter.size() Chris@366: << ", next phase = " << m_phaseData[cp].nextPhase << endl; Chris@366: totDrop += m_phaseData[cp].drop; Chris@366: cp = m_phaseData[cp].nextPhase; Chris@366: } Chris@366: cerr << "total drop = " << totDrop << endl; Chris@366: #endif Chris@366: Chris@366: // The May implementation of this uses a pull model -- we ask the Chris@366: // resampler for a certain number of output samples, and it asks Chris@366: // its source stream for as many as it needs to calculate Chris@366: // those. This means (among other things) that the source stream Chris@366: // can be asked for enough samples up-front to fill the buffer Chris@366: // before the first output sample is generated. Chris@366: // Chris@366: // In this implementation we're using a push model in which a Chris@366: // certain number of source samples is provided and we're asked Chris@366: // for as many output samples as that makes available. But we Chris@366: // can't return any samples from the beginning until half the Chris@366: // filter length has been provided as input. This means we must Chris@366: // either return a very variable number of samples (none at all Chris@366: // until the filter fills, then half the filter length at once) or Chris@366: // else have a lengthy declared latency on the output. We do the Chris@366: // latter. (What do other implementations do?) Chris@366: // Chris@366: // We want to make sure the first "real" sample will eventually be Chris@366: // aligned with the centre sample in the filter (it's tidier, and Chris@366: // easier to do diagnostic calculations that way). So we need to Chris@366: // pick the initial phase and buffer fill accordingly. Chris@366: // Chris@366: // Example: if the inputSpacing is 2, outputSpacing is 3, and Chris@366: // filter length is 7, Chris@366: // Chris@366: // x x x x a b c ... input samples Chris@366: // 0 1 2 3 4 5 6 7 8 9 10 11 12 13 ... Chris@366: // i j k l ... output samples Chris@366: // [--------|--------] <- filter with centre mark Chris@366: // Chris@366: // Let h be the index of the centre mark, here 3 (generally Chris@366: // int(filterLength/2) for odd-length filters). Chris@366: // Chris@366: // The smallest n such that h + n * outputSpacing > filterLength Chris@366: // is 2 (that is, ceil((filterLength - h) / outputSpacing)), and Chris@366: // (h + 2 * outputSpacing) % inputSpacing == 1, so the initial Chris@366: // phase is 1. Chris@366: // Chris@366: // To achieve our n, we need to pre-fill the "virtual" buffer with Chris@366: // 4 zero samples: the x's above. This is int((h + n * Chris@366: // outputSpacing) / inputSpacing). It's the phase that makes this Chris@366: // buffer get dealt with in such a way as to give us an effective Chris@366: // index for sample a of 9 rather than 8 or 10 or whatever. Chris@366: // Chris@366: // This gives us output latency of 2 (== n), i.e. output samples i Chris@366: // and j will appear before the one in which input sample a is at Chris@366: // the centre of the filter. Chris@366: Chris@366: int h = int(m_filterLength / 2); Chris@366: int n = ceil(double(m_filterLength - h) / outputSpacing); Chris@366: Chris@366: m_phase = (h + n * outputSpacing) % inputSpacing; Chris@366: Chris@366: int fill = (h + n * outputSpacing) / inputSpacing; Chris@366: Chris@366: m_latency = n; Chris@366: Chris@366: m_buffer = vector(fill, 0); Chris@366: m_bufferOrigin = 0; Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER Chris@366: cerr << "initial phase " << m_phase << " (as " << (m_filterLength/2) << " % " << inputSpacing << ")" Chris@366: << ", latency " << m_latency << endl; Chris@366: #endif Chris@366: } Chris@366: Chris@366: double Chris@366: Resampler::reconstructOne() Chris@366: { Chris@366: Phase &pd = m_phaseData[m_phase]; Chris@366: double v = 0.0; Chris@366: int n = pd.filter.size(); Chris@366: Chris@366: assert(n + m_bufferOrigin <= (int)m_buffer.size()); Chris@366: Chris@366: #if defined(__MSVC__) Chris@366: #define R__ __restrict Chris@366: #elif defined(__GNUC__) Chris@366: #define R__ __restrict__ Chris@366: #else Chris@366: #define R__ Chris@366: #endif Chris@366: Chris@366: const double *const R__ buf(m_buffer.data() + m_bufferOrigin); Chris@366: const double *const R__ filt(pd.filter.data()); Chris@366: Chris@366: for (int i = 0; i < n; ++i) { Chris@366: // NB gcc can only vectorize this with -ffast-math Chris@366: v += buf[i] * filt[i]; Chris@366: } Chris@366: Chris@366: m_bufferOrigin += pd.drop; Chris@366: m_phase = pd.nextPhase; Chris@366: return v; Chris@366: } Chris@366: Chris@366: int Chris@366: Resampler::process(const double *src, double *dst, int n) Chris@366: { Chris@366: m_buffer.insert(m_buffer.end(), src, src + n); Chris@366: Chris@366: int maxout = int(ceil(double(n) * m_targetRate / m_sourceRate)); Chris@366: int outidx = 0; Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER Chris@366: cerr << "process: buf siz " << m_buffer.size() << " filt siz for phase " << m_phase << " " << m_phaseData[m_phase].filter.size() << endl; Chris@366: #endif Chris@366: Chris@366: double scaleFactor = (double(m_targetRate) / m_gcd) / m_peakToPole; Chris@366: Chris@366: while (outidx < maxout && Chris@366: m_buffer.size() >= m_phaseData[m_phase].filter.size() + m_bufferOrigin) { Chris@366: dst[outidx] = scaleFactor * reconstructOne(); Chris@366: outidx++; Chris@366: } Chris@366: Chris@366: m_buffer = vector(m_buffer.begin() + m_bufferOrigin, m_buffer.end()); Chris@366: m_bufferOrigin = 0; Chris@366: Chris@366: return outidx; Chris@366: } Chris@366: Chris@366: vector Chris@366: Resampler::process(const double *src, int n) Chris@366: { Chris@366: int maxout = int(ceil(double(n) * m_targetRate / m_sourceRate)); Chris@366: vector out(maxout, 0.0); Chris@366: int got = process(src, out.data(), n); Chris@366: assert(got <= maxout); Chris@366: if (got < maxout) out.resize(got); Chris@366: return out; Chris@366: } Chris@366: Chris@366: vector Chris@366: Resampler::resample(int sourceRate, int targetRate, const double *data, int n) Chris@366: { Chris@366: Resampler r(sourceRate, targetRate); Chris@366: Chris@366: int latency = r.getLatency(); Chris@366: Chris@366: // latency is the output latency. We need to provide enough Chris@366: // padding input samples at the end of input to guarantee at Chris@366: // *least* the latency's worth of output samples. that is, Chris@366: Chris@366: int inputPad = int(ceil((double(latency) * sourceRate) / targetRate)); Chris@366: Chris@366: // that means we are providing this much input in total: Chris@366: Chris@366: int n1 = n + inputPad; Chris@366: Chris@366: // and obtaining this much output in total: Chris@366: Chris@366: int m1 = int(ceil((double(n1) * targetRate) / sourceRate)); Chris@366: Chris@366: // in order to return this much output to the user: Chris@366: Chris@366: int m = int(ceil((double(n) * targetRate) / sourceRate)); Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER Chris@366: cerr << "n = " << n << ", sourceRate = " << sourceRate << ", targetRate = " << targetRate << ", m = " << m << ", latency = " << latency << ", inputPad = " << inputPad << ", m1 = " << m1 << ", n1 = " << n1 << ", n1 - n = " << n1 - n << endl; Chris@366: #endif Chris@366: Chris@366: vector pad(n1 - n, 0.0); Chris@366: vector out(m1 + 1, 0.0); Chris@366: Chris@366: int gotData = r.process(data, out.data(), n); Chris@366: int gotPad = r.process(pad.data(), out.data() + gotData, pad.size()); Chris@366: int got = gotData + gotPad; Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER Chris@366: cerr << "resample: " << n << " in, " << pad.size() << " padding, " << got << " out (" << gotData << " data, " << gotPad << " padding, latency = " << latency << ")" << endl; Chris@366: #endif Chris@366: #ifdef DEBUG_RESAMPLER_VERBOSE Chris@366: int printN = 50; Chris@366: cerr << "first " << printN << " in:" << endl; Chris@366: for (int i = 0; i < printN && i < n; ++i) { Chris@366: if (i % 5 == 0) cerr << endl << i << "... "; Chris@366: cerr << data[i] << " "; Chris@366: } Chris@366: cerr << endl; Chris@366: #endif Chris@366: Chris@366: int toReturn = got - latency; Chris@366: if (toReturn > m) toReturn = m; Chris@366: Chris@366: vector sliced(out.begin() + latency, Chris@366: out.begin() + latency + toReturn); Chris@366: Chris@366: #ifdef DEBUG_RESAMPLER_VERBOSE Chris@366: cerr << "first " << printN << " out (after latency compensation), length " << sliced.size() << ":"; Chris@366: for (int i = 0; i < printN && i < sliced.size(); ++i) { Chris@366: if (i % 5 == 0) cerr << endl << i << "... "; Chris@366: cerr << sliced[i] << " "; Chris@366: } Chris@366: cerr << endl; Chris@366: #endif Chris@366: Chris@366: return sliced; Chris@366: } Chris@366: