SoundTouch.cpp 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501
  1. //////////////////////////////////////////////////////////////////////////////
  2. ///
  3. /// SoundTouch - main class for tempo/pitch/rate adjusting routines.
  4. ///
  5. /// Notes:
  6. /// - Initialize the SoundTouch object instance by setting up the sound stream
  7. /// parameters with functions 'setSampleRate' and 'setChannels', then set
  8. /// desired tempo/pitch/rate settings with the corresponding functions.
  9. ///
  10. /// - The SoundTouch class behaves like a first-in-first-out pipeline: The
  11. /// samples that are to be processed are fed into one of the pipe by calling
  12. /// function 'putSamples', while the ready processed samples can be read
  13. /// from the other end of the pipeline with function 'receiveSamples'.
  14. ///
  15. /// - The SoundTouch processing classes require certain sized 'batches' of
  16. /// samples in order to process the sound. For this reason the classes buffer
  17. /// incoming samples until there are enough of samples available for
  18. /// processing, then they carry out the processing step and consequently
  19. /// make the processed samples available for outputting.
  20. ///
  21. /// - For the above reason, the processing routines introduce a certain
  22. /// 'latency' between the input and output, so that the samples input to
  23. /// SoundTouch may not be immediately available in the output, and neither
  24. /// the amount of outputtable samples may not immediately be in direct
  25. /// relationship with the amount of previously input samples.
  26. ///
  27. /// - The tempo/pitch/rate control parameters can be altered during processing.
  28. /// Please notice though that they aren't currently protected by semaphores,
  29. /// so in multi-thread application external semaphore protection may be
  30. /// required.
  31. ///
  32. /// - This class utilizes classes 'TDStretch' for tempo change (without modifying
  33. /// pitch) and 'RateTransposer' for changing the playback rate (that is, both
  34. /// tempo and pitch in the same ratio) of the sound. The third available control
  35. /// 'pitch' (change pitch but maintain tempo) is produced by a combination of
  36. /// combining the two other controls.
  37. ///
  38. /// Author : Copyright (c) Olli Parviainen
  39. /// Author e-mail : oparviai 'at' iki.fi
  40. /// SoundTouch WWW: http://www.surina.net/soundtouch
  41. ///
  42. ////////////////////////////////////////////////////////////////////////////////
  43. //
  44. // Last changed : $Date: 2012-06-13 22:29:53 +0300 (Wed, 13 Jun 2012) $
  45. // File revision : $Revision: 4 $
  46. //
  47. // $Id: SoundTouch.cpp 143 2012-06-13 19:29:53Z oparviai $
  48. //
  49. ////////////////////////////////////////////////////////////////////////////////
  50. //
  51. // License :
  52. //
  53. // SoundTouch audio processing library
  54. // Copyright (c) Olli Parviainen
  55. //
  56. // This library is free software; you can redistribute it and/or
  57. // modify it under the terms of the GNU Lesser General Public
  58. // License as published by the Free Software Foundation; either
  59. // version 2.1 of the License, or (at your option) any later version.
  60. //
  61. // This library is distributed in the hope that it will be useful,
  62. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  63. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  64. // Lesser General Public License for more details.
  65. //
  66. // You should have received a copy of the GNU Lesser General Public
  67. // License along with this library; if not, write to the Free Software
  68. // Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  69. //
  70. ////////////////////////////////////////////////////////////////////////////////
  71. #include <assert.h>
  72. #include <stdlib.h>
  73. #include <memory.h>
  74. #include <math.h>
  75. #include <stdio.h>
  76. #include "SoundTouch.h"
  77. #include "TDStretch.h"
  78. #include "RateTransposer.h"
  79. #include "cpu_detect.h"
  80. using namespace soundtouch;
  81. /// test if two floating point numbers are equal
  82. #define TEST_FLOAT_EQUAL(a, b) (fabs(a - b) < 1e-10)
  83. /// Print library version string for autoconf
  84. extern "C" void soundtouch_ac_test()
  85. {
  86. printf("SoundTouch Version: %s\n",SOUNDTOUCH_VERSION);
  87. }
  88. SoundTouch::SoundTouch()
  89. {
  90. // Initialize rate transposer and tempo changer instances
  91. pRateTransposer = RateTransposer::newInstance();
  92. pTDStretch = TDStretch::newInstance();
  93. setOutPipe(pTDStretch);
  94. rate = tempo = 0;
  95. virtualPitch =
  96. virtualRate =
  97. virtualTempo = 1.0;
  98. calcEffectiveRateAndTempo();
  99. channels = 0;
  100. bSrateSet = FALSE;
  101. }
  102. SoundTouch::~SoundTouch()
  103. {
  104. delete pRateTransposer;
  105. delete pTDStretch;
  106. }
  107. /// Get SoundTouch library version string
  108. const char *SoundTouch::getVersionString()
  109. {
  110. static const char *_version = SOUNDTOUCH_VERSION;
  111. return _version;
  112. }
  113. /// Get SoundTouch library version Id
  114. uint SoundTouch::getVersionId()
  115. {
  116. return SOUNDTOUCH_VERSION_ID;
  117. }
  118. // Sets the number of channels, 1 = mono, 2 = stereo
  119. void SoundTouch::setChannels(uint numChannels)
  120. {
  121. if (numChannels != 1 && numChannels != 2)
  122. {
  123. ST_THROW_RT_ERROR("Illegal number of channels");
  124. }
  125. channels = numChannels;
  126. pRateTransposer->setChannels((int)numChannels);
  127. pTDStretch->setChannels((int)numChannels);
  128. }
  129. // Sets new rate control value. Normal rate = 1.0, smaller values
  130. // represent slower rate, larger faster rates.
  131. void SoundTouch::setRate(float newRate)
  132. {
  133. virtualRate = newRate;
  134. calcEffectiveRateAndTempo();
  135. }
  136. // Sets new rate control value as a difference in percents compared
  137. // to the original rate (-50 .. +100 %)
  138. void SoundTouch::setRateChange(float newRate)
  139. {
  140. virtualRate = 1.0f + 0.01f * newRate;
  141. calcEffectiveRateAndTempo();
  142. }
  143. // Sets new tempo control value. Normal tempo = 1.0, smaller values
  144. // represent slower tempo, larger faster tempo.
  145. void SoundTouch::setTempo(float newTempo)
  146. {
  147. virtualTempo = newTempo;
  148. calcEffectiveRateAndTempo();
  149. }
  150. // Sets new tempo control value as a difference in percents compared
  151. // to the original tempo (-50 .. +100 %)
  152. void SoundTouch::setTempoChange(float newTempo)
  153. {
  154. virtualTempo = 1.0f + 0.01f * newTempo;
  155. calcEffectiveRateAndTempo();
  156. }
  157. // Sets new pitch control value. Original pitch = 1.0, smaller values
  158. // represent lower pitches, larger values higher pitch.
  159. void SoundTouch::setPitch(float newPitch)
  160. {
  161. virtualPitch = newPitch;
  162. calcEffectiveRateAndTempo();
  163. }
  164. // Sets pitch change in octaves compared to the original pitch
  165. // (-1.00 .. +1.00)
  166. void SoundTouch::setPitchOctaves(float newPitch)
  167. {
  168. virtualPitch = (float)exp(0.69314718056f * newPitch);
  169. calcEffectiveRateAndTempo();
  170. }
  171. // Sets pitch change in semi-tones compared to the original pitch
  172. // (-12 .. +12)
  173. void SoundTouch::setPitchSemiTones(int newPitch)
  174. {
  175. setPitchOctaves((float)newPitch / 12.0f);
  176. }
  177. void SoundTouch::setPitchSemiTones(float newPitch)
  178. {
  179. setPitchOctaves(newPitch / 12.0f);
  180. }
  181. // Calculates 'effective' rate and tempo values from the
  182. // nominal control values.
  183. void SoundTouch::calcEffectiveRateAndTempo()
  184. {
  185. float oldTempo = tempo;
  186. float oldRate = rate;
  187. tempo = virtualTempo / virtualPitch;
  188. rate = virtualPitch * virtualRate;
  189. if (!TEST_FLOAT_EQUAL(rate,oldRate)) pRateTransposer->setRate(rate);
  190. if (!TEST_FLOAT_EQUAL(tempo, oldTempo)) pTDStretch->setTempo(tempo);
  191. #ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER
  192. if (rate <= 1.0f)
  193. {
  194. if (output != pTDStretch)
  195. {
  196. FIFOSamplePipe *tempoOut;
  197. assert(output == pRateTransposer);
  198. // move samples in the current output buffer to the output of pTDStretch
  199. tempoOut = pTDStretch->getOutput();
  200. tempoOut->moveSamples(*output);
  201. // move samples in pitch transposer's store buffer to tempo changer's input
  202. pTDStretch->moveSamples(*pRateTransposer->getStore());
  203. output = pTDStretch;
  204. }
  205. }
  206. else
  207. #endif
  208. {
  209. if (output != pRateTransposer)
  210. {
  211. FIFOSamplePipe *transOut;
  212. assert(output == pTDStretch);
  213. // move samples in the current output buffer to the output of pRateTransposer
  214. transOut = pRateTransposer->getOutput();
  215. transOut->moveSamples(*output);
  216. // move samples in tempo changer's input to pitch transposer's input
  217. pRateTransposer->moveSamples(*pTDStretch->getInput());
  218. output = pRateTransposer;
  219. }
  220. }
  221. }
  222. // Sets sample rate.
  223. void SoundTouch::setSampleRate(uint srate)
  224. {
  225. bSrateSet = TRUE;
  226. // set sample rate, leave other tempo changer parameters as they are.
  227. pTDStretch->setParameters((int)srate);
  228. }
  229. // Adds 'numSamples' pcs of samples from the 'samples' memory position into
  230. // the input of the object.
  231. void SoundTouch::putSamples(const SAMPLETYPE *samples, uint nSamples)
  232. {
  233. if (bSrateSet == FALSE)
  234. {
  235. ST_THROW_RT_ERROR("SoundTouch : Sample rate not defined");
  236. }
  237. else if (channels == 0)
  238. {
  239. ST_THROW_RT_ERROR("SoundTouch : Number of channels not defined");
  240. }
  241. // Transpose the rate of the new samples if necessary
  242. /* Bypass the nominal setting - can introduce a click in sound when tempo/pitch control crosses the nominal value...
  243. if (rate == 1.0f)
  244. {
  245. // The rate value is same as the original, simply evaluate the tempo changer.
  246. assert(output == pTDStretch);
  247. if (pRateTransposer->isEmpty() == 0)
  248. {
  249. // yet flush the last samples in the pitch transposer buffer
  250. // (may happen if 'rate' changes from a non-zero value to zero)
  251. pTDStretch->moveSamples(*pRateTransposer);
  252. }
  253. pTDStretch->putSamples(samples, nSamples);
  254. }
  255. */
  256. #ifndef SOUNDTOUCH_PREVENT_CLICK_AT_RATE_CROSSOVER
  257. else if (rate <= 1.0f)
  258. {
  259. // transpose the rate down, output the transposed sound to tempo changer buffer
  260. assert(output == pTDStretch);
  261. pRateTransposer->putSamples(samples, nSamples);
  262. pTDStretch->moveSamples(*pRateTransposer);
  263. }
  264. else
  265. #endif
  266. {
  267. // evaluate the tempo changer, then transpose the rate up,
  268. assert(output == pRateTransposer);
  269. pTDStretch->putSamples(samples, nSamples);
  270. pRateTransposer->moveSamples(*pTDStretch);
  271. }
  272. }
  273. // Flushes the last samples from the processing pipeline to the output.
  274. // Clears also the internal processing buffers.
  275. //
  276. // Note: This function is meant for extracting the last samples of a sound
  277. // stream. This function may introduce additional blank samples in the end
  278. // of the sound stream, and thus it's not recommended to call this function
  279. // in the middle of a sound stream.
  280. void SoundTouch::flush()
  281. {
  282. int i;
  283. int nUnprocessed;
  284. int nOut;
  285. SAMPLETYPE buff[64*2]; // note: allocate 2*64 to cater 64 sample frames of stereo sound
  286. // check how many samples still await processing, and scale
  287. // that by tempo & rate to get expected output sample count
  288. nUnprocessed = numUnprocessedSamples();
  289. nUnprocessed = (int)((double)nUnprocessed / (tempo * rate) + 0.5);
  290. nOut = numSamples(); // ready samples currently in buffer ...
  291. nOut += nUnprocessed; // ... and how many we expect there to be in the end
  292. memset(buff, 0, 64 * channels * sizeof(SAMPLETYPE));
  293. // "Push" the last active samples out from the processing pipeline by
  294. // feeding blank samples into the processing pipeline until new,
  295. // processed samples appear in the output (not however, more than
  296. // 8ksamples in any case)
  297. for (i = 0; i < 128; i ++)
  298. {
  299. putSamples(buff, 64);
  300. if ((int)numSamples() >= nOut)
  301. {
  302. // Enough new samples have appeared into the output!
  303. // As samples come from processing with bigger chunks, now truncate it
  304. // back to maximum "nOut" samples to improve duration accuracy
  305. adjustAmountOfSamples(nOut);
  306. // finish
  307. break;
  308. }
  309. }
  310. // Clear working buffers
  311. pRateTransposer->clear();
  312. pTDStretch->clearInput();
  313. // yet leave the 'tempoChanger' output intouched as that's where the
  314. // flushed samples are!
  315. }
  316. // Changes a setting controlling the processing system behaviour. See the
  317. // 'SETTING_...' defines for available setting ID's.
  318. SBOOL SoundTouch::setSetting(int settingId, int value)
  319. {
  320. int sampleRate, sequenceMs, seekWindowMs, overlapMs;
  321. // read current tdstretch routine parameters
  322. pTDStretch->getParameters(&sampleRate, &sequenceMs, &seekWindowMs, &overlapMs);
  323. switch (settingId)
  324. {
  325. case SETTING_USE_AA_FILTER :
  326. // enables / disabless anti-alias filter
  327. pRateTransposer->enableAAFilter((value != 0) ? TRUE : FALSE);
  328. return TRUE;
  329. case SETTING_AA_FILTER_LENGTH :
  330. // sets anti-alias filter length
  331. pRateTransposer->getAAFilter()->setLength(value);
  332. return TRUE;
  333. case SETTING_USE_QUICKSEEK :
  334. // enables / disables tempo routine quick seeking algorithm
  335. pTDStretch->enableQuickSeek((value != 0) ? TRUE : FALSE);
  336. return TRUE;
  337. case SETTING_SEQUENCE_MS:
  338. // change time-stretch sequence duration parameter
  339. pTDStretch->setParameters(sampleRate, value, seekWindowMs, overlapMs);
  340. return TRUE;
  341. case SETTING_SEEKWINDOW_MS:
  342. // change time-stretch seek window length parameter
  343. pTDStretch->setParameters(sampleRate, sequenceMs, value, overlapMs);
  344. return TRUE;
  345. case SETTING_OVERLAP_MS:
  346. // change time-stretch overlap length parameter
  347. pTDStretch->setParameters(sampleRate, sequenceMs, seekWindowMs, value);
  348. return TRUE;
  349. default :
  350. return FALSE;
  351. }
  352. }
  353. // Reads a setting controlling the processing system behaviour. See the
  354. // 'SETTING_...' defines for available setting ID's.
  355. //
  356. // Returns the setting value.
  357. int SoundTouch::getSetting(int settingId) const
  358. {
  359. int temp;
  360. switch (settingId)
  361. {
  362. case SETTING_USE_AA_FILTER :
  363. return (uint)pRateTransposer->isAAFilterEnabled();
  364. case SETTING_AA_FILTER_LENGTH :
  365. return pRateTransposer->getAAFilter()->getLength();
  366. case SETTING_USE_QUICKSEEK :
  367. return (uint) pTDStretch->isQuickSeekEnabled();
  368. case SETTING_SEQUENCE_MS:
  369. pTDStretch->getParameters(NULL, &temp, NULL, NULL);
  370. return temp;
  371. case SETTING_SEEKWINDOW_MS:
  372. pTDStretch->getParameters(NULL, NULL, &temp, NULL);
  373. return temp;
  374. case SETTING_OVERLAP_MS:
  375. pTDStretch->getParameters(NULL, NULL, NULL, &temp);
  376. return temp;
  377. case SETTING_NOMINAL_INPUT_SEQUENCE :
  378. return pTDStretch->getInputSampleReq();
  379. case SETTING_NOMINAL_OUTPUT_SEQUENCE :
  380. return pTDStretch->getOutputBatchSize();
  381. default :
  382. return 0;
  383. }
  384. }
  385. // Clears all the samples in the object's output and internal processing
  386. // buffers.
  387. void SoundTouch::clear()
  388. {
  389. pRateTransposer->clear();
  390. pTDStretch->clear();
  391. }
  392. /// Returns number of samples currently unprocessed.
  393. uint SoundTouch::numUnprocessedSamples() const
  394. {
  395. FIFOSamplePipe * psp;
  396. if (pTDStretch)
  397. {
  398. psp = pTDStretch->getInput();
  399. if (psp)
  400. {
  401. return psp->numSamples();
  402. }
  403. }
  404. return 0;
  405. }