/external/pysoundtouch14/libsoundtouch/RateTransposer.cpp

http://echo-nest-remix.googlecode.com/ · C++ · 624 lines · 350 code · 127 blank · 147 comment · 42 complexity · f8e5f8acbeb7398469a036ec4b323baa MD5 · raw file

  1. ////////////////////////////////////////////////////////////////////////////////
  2. ///
  3. /// Sample rate transposer. Changes sample rate by using linear interpolation
  4. /// together with anti-alias filtering (first order interpolation with anti-
  5. /// alias filtering should be quite adequate for this application)
  6. ///
  7. /// Author : Copyright (c) Olli Parviainen
  8. /// Author e-mail : oparviai 'at' iki.fi
  9. /// SoundTouch WWW: http://www.surina.net/soundtouch
  10. ///
  11. ////////////////////////////////////////////////////////////////////////////////
  12. //
  13. // Last changed : $Date: 2009-01-11 13:34:24 +0200 (Sun, 11 Jan 2009) $
  14. // File revision : $Revision: 4 $
  15. //
  16. // $Id: RateTransposer.cpp 45 2009-01-11 11:34:24Z oparviai $
  17. //
  18. ////////////////////////////////////////////////////////////////////////////////
  19. //
  20. // License :
  21. //
  22. // SoundTouch audio processing library
  23. // Copyright (c) Olli Parviainen
  24. //
  25. // This library is free software; you can redistribute it and/or
  26. // modify it under the terms of the GNU Lesser General Public
  27. // License as published by the Free Software Foundation; either
  28. // version 2.1 of the License, or (at your option) any later version.
  29. //
  30. // This library is distributed in the hope that it will be useful,
  31. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  32. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  33. // Lesser General Public License for more details.
  34. //
  35. // You should have received a copy of the GNU Lesser General Public
  36. // License along with this library; if not, write to the Free Software
  37. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  38. //
  39. ////////////////////////////////////////////////////////////////////////////////
  40. #include <memory.h>
  41. #include <assert.h>
  42. #include <stdlib.h>
  43. #include <stdio.h>
  44. #include <stdexcept>
  45. #include "RateTransposer.h"
  46. #include "AAFilter.h"
  47. using namespace std;
  48. using namespace soundtouch;
  49. /// A linear samplerate transposer class that uses integer arithmetics.
  50. /// for the transposing.
  51. class RateTransposerInteger : public RateTransposer
  52. {
  53. protected:
  54. int iSlopeCount;
  55. int iRate;
  56. SAMPLETYPE sPrevSampleL, sPrevSampleR;
  57. virtual void resetRegisters();
  58. virtual uint transposeStereo(SAMPLETYPE *dest,
  59. const SAMPLETYPE *src,
  60. uint numSamples);
  61. virtual uint transposeMono(SAMPLETYPE *dest,
  62. const SAMPLETYPE *src,
  63. uint numSamples);
  64. public:
  65. RateTransposerInteger();
  66. virtual ~RateTransposerInteger();
  67. /// Sets new target rate. Normal rate = 1.0, smaller values represent slower
  68. /// rate, larger faster rates.
  69. virtual void setRate(float newRate);
  70. };
  71. /// A linear samplerate transposer class that uses floating point arithmetics
  72. /// for the transposing.
  73. class RateTransposerFloat : public RateTransposer
  74. {
  75. protected:
  76. float fSlopeCount;
  77. SAMPLETYPE sPrevSampleL, sPrevSampleR;
  78. virtual void resetRegisters();
  79. virtual uint transposeStereo(SAMPLETYPE *dest,
  80. const SAMPLETYPE *src,
  81. uint numSamples);
  82. virtual uint transposeMono(SAMPLETYPE *dest,
  83. const SAMPLETYPE *src,
  84. uint numSamples);
  85. public:
  86. RateTransposerFloat();
  87. virtual ~RateTransposerFloat();
  88. };
  89. // Operator 'new' is overloaded so that it automatically creates a suitable instance
  90. // depending on if we've a MMX/SSE/etc-capable CPU available or not.
  91. void * RateTransposer::operator new(size_t s)
  92. {
  93. throw runtime_error("Error in RateTransoser::new: don't use \"new TDStretch\" directly, use \"newInstance\" to create a new instance instead!");
  94. return NULL;
  95. }
  96. RateTransposer *RateTransposer::newInstance()
  97. {
  98. #ifdef INTEGER_SAMPLES
  99. return ::new RateTransposerInteger;
  100. #else
  101. return ::new RateTransposerFloat;
  102. #endif
  103. }
  104. // Constructor
  105. RateTransposer::RateTransposer() : FIFOProcessor(&outputBuffer)
  106. {
  107. numChannels = 2;
  108. bUseAAFilter = TRUE;
  109. fRate = 0;
  110. // Instantiates the anti-alias filter with default tap length
  111. // of 32
  112. pAAFilter = new AAFilter(32);
  113. }
  114. RateTransposer::~RateTransposer()
  115. {
  116. delete pAAFilter;
  117. }
  118. /// Enables/disables the anti-alias filter. Zero to disable, nonzero to enable
  119. void RateTransposer::enableAAFilter(BOOL newMode)
  120. {
  121. bUseAAFilter = newMode;
  122. }
  123. /// Returns nonzero if anti-alias filter is enabled.
  124. BOOL RateTransposer::isAAFilterEnabled() const
  125. {
  126. return bUseAAFilter;
  127. }
  128. AAFilter *RateTransposer::getAAFilter() const
  129. {
  130. return pAAFilter;
  131. }
  132. // Sets new target iRate. Normal iRate = 1.0, smaller values represent slower
  133. // iRate, larger faster iRates.
  134. void RateTransposer::setRate(float newRate)
  135. {
  136. double fCutoff;
  137. fRate = newRate;
  138. // design a new anti-alias filter
  139. if (newRate > 1.0f)
  140. {
  141. fCutoff = 0.5f / newRate;
  142. }
  143. else
  144. {
  145. fCutoff = 0.5f * newRate;
  146. }
  147. pAAFilter->setCutoffFreq(fCutoff);
  148. }
  149. // Outputs as many samples of the 'outputBuffer' as possible, and if there's
  150. // any room left, outputs also as many of the incoming samples as possible.
  151. // The goal is to drive the outputBuffer empty.
  152. //
  153. // It's allowed for 'output' and 'input' parameters to point to the same
  154. // memory position.
  155. /*
  156. void RateTransposer::flushStoreBuffer()
  157. {
  158. if (storeBuffer.isEmpty()) return;
  159. outputBuffer.moveSamples(storeBuffer);
  160. }
  161. */
  162. // Adds 'nSamples' pcs of samples from the 'samples' memory position into
  163. // the input of the object.
  164. void RateTransposer::putSamples(const SAMPLETYPE *samples, uint nSamples)
  165. {
  166. processSamples(samples, nSamples);
  167. }
  168. // Transposes up the sample rate, causing the observed playback 'rate' of the
  169. // sound to decrease
  170. void RateTransposer::upsample(const SAMPLETYPE *src, uint nSamples)
  171. {
  172. uint count, sizeTemp, num;
  173. // If the parameter 'uRate' value is smaller than 'SCALE', first transpose
  174. // the samples and then apply the anti-alias filter to remove aliasing.
  175. // First check that there's enough room in 'storeBuffer'
  176. // (+16 is to reserve some slack in the destination buffer)
  177. sizeTemp = (uint)((float)nSamples / fRate + 16.0f);
  178. // Transpose the samples, store the result into the end of "storeBuffer"
  179. count = transpose(storeBuffer.ptrEnd(sizeTemp), src, nSamples);
  180. storeBuffer.putSamples(count);
  181. // Apply the anti-alias filter to samples in "store output", output the
  182. // result to "dest"
  183. num = storeBuffer.numSamples();
  184. count = pAAFilter->evaluate(outputBuffer.ptrEnd(num),
  185. storeBuffer.ptrBegin(), num, (uint)numChannels);
  186. outputBuffer.putSamples(count);
  187. // Remove the processed samples from "storeBuffer"
  188. storeBuffer.receiveSamples(count);
  189. }
  190. // Transposes down the sample rate, causing the observed playback 'rate' of the
  191. // sound to increase
  192. void RateTransposer::downsample(const SAMPLETYPE *src, uint nSamples)
  193. {
  194. uint count, sizeTemp;
  195. // If the parameter 'uRate' value is larger than 'SCALE', first apply the
  196. // anti-alias filter to remove high frequencies (prevent them from folding
  197. // over the lover frequencies), then transpose. */
  198. // Add the new samples to the end of the storeBuffer */
  199. storeBuffer.putSamples(src, nSamples);
  200. // Anti-alias filter the samples to prevent folding and output the filtered
  201. // data to tempBuffer. Note : because of the FIR filter length, the
  202. // filtering routine takes in 'filter_length' more samples than it outputs.
  203. assert(tempBuffer.isEmpty());
  204. sizeTemp = storeBuffer.numSamples();
  205. count = pAAFilter->evaluate(tempBuffer.ptrEnd(sizeTemp),
  206. storeBuffer.ptrBegin(), sizeTemp, (uint)numChannels);
  207. // Remove the filtered samples from 'storeBuffer'
  208. storeBuffer.receiveSamples(count);
  209. // Transpose the samples (+16 is to reserve some slack in the destination buffer)
  210. sizeTemp = (uint)((float)nSamples / fRate + 16.0f);
  211. count = transpose(outputBuffer.ptrEnd(sizeTemp), tempBuffer.ptrBegin(), count);
  212. outputBuffer.putSamples(count);
  213. }
  214. // Transposes sample rate by applying anti-alias filter to prevent folding.
  215. // Returns amount of samples returned in the "dest" buffer.
  216. // The maximum amount of samples that can be returned at a time is set by
  217. // the 'set_returnBuffer_size' function.
  218. void RateTransposer::processSamples(const SAMPLETYPE *src, uint nSamples)
  219. {
  220. uint count;
  221. uint sizeReq;
  222. if (nSamples == 0) return;
  223. assert(pAAFilter);
  224. // If anti-alias filter is turned off, simply transpose without applying
  225. // the filter
  226. if (bUseAAFilter == FALSE)
  227. {
  228. sizeReq = (uint)((float)nSamples / fRate + 1.0f);
  229. count = transpose(outputBuffer.ptrEnd(sizeReq), src, nSamples);
  230. outputBuffer.putSamples(count);
  231. return;
  232. }
  233. // Transpose with anti-alias filter
  234. if (fRate < 1.0f)
  235. {
  236. upsample(src, nSamples);
  237. }
  238. else
  239. {
  240. downsample(src, nSamples);
  241. }
  242. }
  243. // Transposes the sample rate of the given samples using linear interpolation.
  244. // Returns the number of samples returned in the "dest" buffer
  245. inline uint RateTransposer::transpose(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples)
  246. {
  247. if (numChannels == 2)
  248. {
  249. return transposeStereo(dest, src, nSamples);
  250. }
  251. else
  252. {
  253. return transposeMono(dest, src, nSamples);
  254. }
  255. }
  256. // Sets the number of channels, 1 = mono, 2 = stereo
  257. void RateTransposer::setChannels(int nChannels)
  258. {
  259. assert(nChannels > 0);
  260. if (numChannels == nChannels) return;
  261. assert(nChannels == 1 || nChannels == 2);
  262. numChannels = nChannels;
  263. storeBuffer.setChannels(numChannels);
  264. tempBuffer.setChannels(numChannels);
  265. outputBuffer.setChannels(numChannels);
  266. // Inits the linear interpolation registers
  267. resetRegisters();
  268. }
  269. // Clears all the samples in the object
  270. void RateTransposer::clear()
  271. {
  272. outputBuffer.clear();
  273. storeBuffer.clear();
  274. }
  275. // Returns nonzero if there aren't any samples available for outputting.
  276. int RateTransposer::isEmpty() const
  277. {
  278. int res;
  279. res = FIFOProcessor::isEmpty();
  280. if (res == 0) return 0;
  281. return storeBuffer.isEmpty();
  282. }
  283. //////////////////////////////////////////////////////////////////////////////
  284. //
  285. // RateTransposerInteger - integer arithmetic implementation
  286. //
  287. /// fixed-point interpolation routine precision
  288. #define SCALE 65536
  289. // Constructor
  290. RateTransposerInteger::RateTransposerInteger() : RateTransposer()
  291. {
  292. // Notice: use local function calling syntax for sake of clarity,
  293. // to indicate the fact that C++ constructor can't call virtual functions.
  294. RateTransposerInteger::resetRegisters();
  295. RateTransposerInteger::setRate(1.0f);
  296. }
  297. RateTransposerInteger::~RateTransposerInteger()
  298. {
  299. }
  300. void RateTransposerInteger::resetRegisters()
  301. {
  302. iSlopeCount = 0;
  303. sPrevSampleL =
  304. sPrevSampleR = 0;
  305. }
  306. // Transposes the sample rate of the given samples using linear interpolation.
  307. // 'Mono' version of the routine. Returns the number of samples returned in
  308. // the "dest" buffer
  309. uint RateTransposerInteger::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples)
  310. {
  311. unsigned int i, used;
  312. LONG_SAMPLETYPE temp, vol1;
  313. used = 0;
  314. i = 0;
  315. // Process the last sample saved from the previous call first...
  316. while (iSlopeCount <= SCALE)
  317. {
  318. vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount);
  319. temp = vol1 * sPrevSampleL + iSlopeCount * src[0];
  320. dest[i] = (SAMPLETYPE)(temp / SCALE);
  321. i++;
  322. iSlopeCount += iRate;
  323. }
  324. // now always (iSlopeCount > SCALE)
  325. iSlopeCount -= SCALE;
  326. while (1)
  327. {
  328. while (iSlopeCount > SCALE)
  329. {
  330. iSlopeCount -= SCALE;
  331. used ++;
  332. if (used >= nSamples - 1) goto end;
  333. }
  334. vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount);
  335. temp = src[used] * vol1 + iSlopeCount * src[used + 1];
  336. dest[i] = (SAMPLETYPE)(temp / SCALE);
  337. i++;
  338. iSlopeCount += iRate;
  339. }
  340. end:
  341. // Store the last sample for the next round
  342. sPrevSampleL = src[nSamples - 1];
  343. return i;
  344. }
  345. // Transposes the sample rate of the given samples using linear interpolation.
  346. // 'Stereo' version of the routine. Returns the number of samples returned in
  347. // the "dest" buffer
  348. uint RateTransposerInteger::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples)
  349. {
  350. unsigned int srcPos, i, used;
  351. LONG_SAMPLETYPE temp, vol1;
  352. if (nSamples == 0) return 0; // no samples, no work
  353. used = 0;
  354. i = 0;
  355. // Process the last sample saved from the sPrevSampleLious call first...
  356. while (iSlopeCount <= SCALE)
  357. {
  358. vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount);
  359. temp = vol1 * sPrevSampleL + iSlopeCount * src[0];
  360. dest[2 * i] = (SAMPLETYPE)(temp / SCALE);
  361. temp = vol1 * sPrevSampleR + iSlopeCount * src[1];
  362. dest[2 * i + 1] = (SAMPLETYPE)(temp / SCALE);
  363. i++;
  364. iSlopeCount += iRate;
  365. }
  366. // now always (iSlopeCount > SCALE)
  367. iSlopeCount -= SCALE;
  368. while (1)
  369. {
  370. while (iSlopeCount > SCALE)
  371. {
  372. iSlopeCount -= SCALE;
  373. used ++;
  374. if (used >= nSamples - 1) goto end;
  375. }
  376. srcPos = 2 * used;
  377. vol1 = (LONG_SAMPLETYPE)(SCALE - iSlopeCount);
  378. temp = src[srcPos] * vol1 + iSlopeCount * src[srcPos + 2];
  379. dest[2 * i] = (SAMPLETYPE)(temp / SCALE);
  380. temp = src[srcPos + 1] * vol1 + iSlopeCount * src[srcPos + 3];
  381. dest[2 * i + 1] = (SAMPLETYPE)(temp / SCALE);
  382. i++;
  383. iSlopeCount += iRate;
  384. }
  385. end:
  386. // Store the last sample for the next round
  387. sPrevSampleL = src[2 * nSamples - 2];
  388. sPrevSampleR = src[2 * nSamples - 1];
  389. return i;
  390. }
  391. // Sets new target iRate. Normal iRate = 1.0, smaller values represent slower
  392. // iRate, larger faster iRates.
  393. void RateTransposerInteger::setRate(float newRate)
  394. {
  395. iRate = (int)(newRate * SCALE + 0.5f);
  396. RateTransposer::setRate(newRate);
  397. }
  398. //////////////////////////////////////////////////////////////////////////////
  399. //
  400. // RateTransposerFloat - floating point arithmetic implementation
  401. //
  402. //////////////////////////////////////////////////////////////////////////////
  403. // Constructor
  404. RateTransposerFloat::RateTransposerFloat() : RateTransposer()
  405. {
  406. // Notice: use local function calling syntax for sake of clarity,
  407. // to indicate the fact that C++ constructor can't call virtual functions.
  408. RateTransposerFloat::resetRegisters();
  409. RateTransposerFloat::setRate(1.0f);
  410. }
  411. RateTransposerFloat::~RateTransposerFloat()
  412. {
  413. }
  414. void RateTransposerFloat::resetRegisters()
  415. {
  416. fSlopeCount = 0;
  417. sPrevSampleL =
  418. sPrevSampleR = 0;
  419. }
  420. // Transposes the sample rate of the given samples using linear interpolation.
  421. // 'Mono' version of the routine. Returns the number of samples returned in
  422. // the "dest" buffer
  423. uint RateTransposerFloat::transposeMono(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples)
  424. {
  425. unsigned int i, used;
  426. used = 0;
  427. i = 0;
  428. // Process the last sample saved from the previous call first...
  429. while (fSlopeCount <= 1.0f )
  430. {
  431. dest[i] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleL + fSlopeCount * src[0]);
  432. i++;
  433. fSlopeCount += fRate;
  434. }
  435. fSlopeCount -= 1.0f;
  436. if (nSamples == 1) goto end;
  437. while (1)
  438. {
  439. while (fSlopeCount > 1.0f)
  440. {
  441. fSlopeCount -= 1.0f;
  442. used ++;
  443. if (used >= nSamples - 1) goto end;
  444. }
  445. //if(i>= nSamples -1) goto end;
  446. dest[i] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[used] + fSlopeCount * src[used + 1]);
  447. i++;
  448. fSlopeCount += fRate;
  449. }
  450. end:
  451. // Store the last sample for the next round
  452. sPrevSampleL = src[nSamples - 1];
  453. return i;
  454. }
  455. // Transposes the sample rate of the given samples using linear interpolation.
  456. // 'Mono' version of the routine. Returns the number of samples returned in
  457. // the "dest" buffer
  458. uint RateTransposerFloat::transposeStereo(SAMPLETYPE *dest, const SAMPLETYPE *src, uint nSamples)
  459. {
  460. unsigned int srcPos, i, used;
  461. if (nSamples == 0) return 0; // no samples, no work
  462. used = 0;
  463. i = 0;
  464. // Process the last sample saved from the sPrevSampleLious call first...
  465. while (fSlopeCount <= 1.0f)
  466. {
  467. dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleL + fSlopeCount * src[0]);
  468. dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * sPrevSampleR + fSlopeCount * src[1]);
  469. i++;
  470. fSlopeCount += fRate;
  471. }
  472. // now always (iSlopeCount > 1.0f)
  473. fSlopeCount -= 1.0f;
  474. if (nSamples == 1) goto end;
  475. while (1)
  476. {
  477. while (fSlopeCount > 1.0f)
  478. {
  479. fSlopeCount -= 1.0f;
  480. used ++;
  481. if (used >= nSamples - 1) goto end;
  482. }
  483. srcPos = 2 * used;
  484. dest[2 * i] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos]
  485. + fSlopeCount * src[srcPos + 2]);
  486. dest[2 * i + 1] = (SAMPLETYPE)((1.0f - fSlopeCount) * src[srcPos + 1]
  487. + fSlopeCount * src[srcPos + 3]);
  488. i++;
  489. fSlopeCount += fRate;
  490. }
  491. end:
  492. // Store the last sample for the next round
  493. sPrevSampleL = src[2 * nSamples - 2];
  494. sPrevSampleR = src[2 * nSamples - 1];
  495. return i;
  496. }