Audio plugin host https://kx.studio/carla
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

juce_BufferingAudioSource.cpp 11KB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2016 - ROLI Ltd.
  5. Permission is granted to use this software under the terms of the ISC license
  6. http://www.isc.org/downloads/software-support-policy/isc-license/
  7. Permission to use, copy, modify, and/or distribute this software for any
  8. purpose with or without fee is hereby granted, provided that the above
  9. copyright notice and this permission notice appear in all copies.
  10. THE SOFTWARE IS PROVIDED "AS IS" AND ISC DISCLAIMS ALL WARRANTIES WITH REGARD
  11. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  12. FITNESS. IN NO EVENT SHALL ISC BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT,
  13. OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF
  14. USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  15. TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE
  16. OF THIS SOFTWARE.
  17. -----------------------------------------------------------------------------
  18. To release a closed-source product which uses other parts of JUCE not
  19. licensed under the ISC terms, commercial licenses are available: visit
  20. www.juce.com for more information.
  21. ==============================================================================
  22. */
  23. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* s,
  24. TimeSliceThread& thread,
  25. const bool deleteSourceWhenDeleted,
  26. const int bufferSizeSamples,
  27. const int numChannels,
  28. bool prefillBufferOnPrepareToPlay)
  29. : source (s, deleteSourceWhenDeleted),
  30. backgroundThread (thread),
  31. numberOfSamplesToBuffer (jmax (1024, bufferSizeSamples)),
  32. numberOfChannels (numChannels),
  33. bufferValidStart (0),
  34. bufferValidEnd (0),
  35. nextPlayPos (0),
  36. sampleRate (0),
  37. wasSourceLooping (false),
  38. isPrepared (false),
  39. prefillBuffer (prefillBufferOnPrepareToPlay)
  40. {
  41. jassert (source != nullptr);
  42. jassert (numberOfSamplesToBuffer > 1024); // not much point using this class if you're
  43. // not using a larger buffer..
  44. }
  45. BufferingAudioSource::~BufferingAudioSource()
  46. {
  47. releaseResources();
  48. }
  49. //==============================================================================
  50. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double newSampleRate)
  51. {
  52. const int bufferSizeNeeded = jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer);
  53. if (newSampleRate != sampleRate
  54. || bufferSizeNeeded != buffer.getNumSamples()
  55. || ! isPrepared)
  56. {
  57. backgroundThread.removeTimeSliceClient (this);
  58. isPrepared = true;
  59. sampleRate = newSampleRate;
  60. source->prepareToPlay (samplesPerBlockExpected, newSampleRate);
  61. buffer.setSize (numberOfChannels, bufferSizeNeeded);
  62. buffer.clear();
  63. bufferValidStart = 0;
  64. bufferValidEnd = 0;
  65. backgroundThread.addTimeSliceClient (this);
  66. do
  67. {
  68. backgroundThread.moveToFrontOfQueue (this);
  69. Thread::sleep (5);
  70. }
  71. while (prefillBuffer
  72. && (bufferValidEnd - bufferValidStart < jmin (((int) newSampleRate) / 4, buffer.getNumSamples() / 2)));
  73. }
  74. }
  75. void BufferingAudioSource::releaseResources()
  76. {
  77. isPrepared = false;
  78. backgroundThread.removeTimeSliceClient (this);
  79. buffer.setSize (numberOfChannels, 0);
  80. // MSVC2015 seems to need this if statement to not generate a warning during linking.
  81. // As source is set in the constructor, there is no way that source could
  82. // ever equal this, but it seems to make MSVC2015 happy.
  83. if (source != this)
  84. source->releaseResources();
  85. }
  86. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  87. {
  88. const ScopedLock sl (bufferStartPosLock);
  89. const int validStart = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  90. const int validEnd = (int) (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  91. if (validStart == validEnd)
  92. {
  93. // total cache miss
  94. info.clearActiveBufferRegion();
  95. }
  96. else
  97. {
  98. if (validStart > 0)
  99. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  100. if (validEnd < info.numSamples)
  101. info.buffer->clear (info.startSample + validEnd,
  102. info.numSamples - validEnd); // partial cache miss at end
  103. if (validStart < validEnd)
  104. {
  105. for (int chan = jmin (numberOfChannels, info.buffer->getNumChannels()); --chan >= 0;)
  106. {
  107. jassert (buffer.getNumSamples() > 0);
  108. const int startBufferIndex = (int) ((validStart + nextPlayPos) % buffer.getNumSamples());
  109. const int endBufferIndex = (int) ((validEnd + nextPlayPos) % buffer.getNumSamples());
  110. if (startBufferIndex < endBufferIndex)
  111. {
  112. info.buffer->copyFrom (chan, info.startSample + validStart,
  113. buffer,
  114. chan, startBufferIndex,
  115. validEnd - validStart);
  116. }
  117. else
  118. {
  119. const int initialSize = buffer.getNumSamples() - startBufferIndex;
  120. info.buffer->copyFrom (chan, info.startSample + validStart,
  121. buffer,
  122. chan, startBufferIndex,
  123. initialSize);
  124. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  125. buffer,
  126. chan, 0,
  127. (validEnd - validStart) - initialSize);
  128. }
  129. }
  130. }
  131. nextPlayPos += info.numSamples;
  132. }
  133. }
  134. bool BufferingAudioSource::waitForNextAudioBlockReady (const AudioSourceChannelInfo& info, const uint32 timeout)
  135. {
  136. if (!source || source->getTotalLength() <= 0)
  137. return false;
  138. if (nextPlayPos + info.numSamples < 0)
  139. return true;
  140. if (! isLooping() && nextPlayPos > getTotalLength())
  141. return true;
  142. uint32 now = Time::getMillisecondCounter();
  143. const uint32 startTime = now;
  144. uint32 elapsed = (now >= startTime ? now - startTime
  145. : (std::numeric_limits<uint32>::max() - startTime) + now);
  146. while (elapsed <= timeout)
  147. {
  148. {
  149. const ScopedLock sl (bufferStartPosLock);
  150. const int validStart = static_cast<int> (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos) - nextPlayPos);
  151. const int validEnd = static_cast<int> (jlimit (bufferValidStart, bufferValidEnd, nextPlayPos + info.numSamples) - nextPlayPos);
  152. if (validStart <= 0 && validStart < validEnd && validEnd >= info.numSamples)
  153. return true;
  154. }
  155. if (elapsed < timeout && (! bufferReadyEvent.wait (static_cast<int> (timeout - elapsed))))
  156. return false;
  157. now = Time::getMillisecondCounter();
  158. elapsed = (now >= startTime ? now - startTime
  159. : (std::numeric_limits<uint32>::max() - startTime) + now);
  160. }
  161. return false;
  162. }
  163. int64 BufferingAudioSource::getNextReadPosition() const
  164. {
  165. jassert (source->getTotalLength() > 0);
  166. return (source->isLooping() && nextPlayPos > 0)
  167. ? nextPlayPos % source->getTotalLength()
  168. : nextPlayPos;
  169. }
  170. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  171. {
  172. const ScopedLock sl (bufferStartPosLock);
  173. nextPlayPos = newPosition;
  174. backgroundThread.moveToFrontOfQueue (this);
  175. }
  176. bool BufferingAudioSource::readNextBufferChunk()
  177. {
  178. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  179. {
  180. const ScopedLock sl (bufferStartPosLock);
  181. if (wasSourceLooping != isLooping())
  182. {
  183. wasSourceLooping = isLooping();
  184. bufferValidStart = 0;
  185. bufferValidEnd = 0;
  186. }
  187. newBVS = jmax ((int64) 0, nextPlayPos);
  188. newBVE = newBVS + buffer.getNumSamples() - 4;
  189. sectionToReadStart = 0;
  190. sectionToReadEnd = 0;
  191. const int maxChunkSize = 2048;
  192. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  193. {
  194. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  195. sectionToReadStart = newBVS;
  196. sectionToReadEnd = newBVE;
  197. bufferValidStart = 0;
  198. bufferValidEnd = 0;
  199. }
  200. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  201. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  202. {
  203. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  204. sectionToReadStart = bufferValidEnd;
  205. sectionToReadEnd = newBVE;
  206. bufferValidStart = newBVS;
  207. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  208. }
  209. }
  210. if (sectionToReadStart == sectionToReadEnd)
  211. return false;
  212. jassert (buffer.getNumSamples() > 0);
  213. const int bufferIndexStart = (int) (sectionToReadStart % buffer.getNumSamples());
  214. const int bufferIndexEnd = (int) (sectionToReadEnd % buffer.getNumSamples());
  215. if (bufferIndexStart < bufferIndexEnd)
  216. {
  217. readBufferSection (sectionToReadStart,
  218. (int) (sectionToReadEnd - sectionToReadStart),
  219. bufferIndexStart);
  220. }
  221. else
  222. {
  223. const int initialSize = buffer.getNumSamples() - bufferIndexStart;
  224. readBufferSection (sectionToReadStart,
  225. initialSize,
  226. bufferIndexStart);
  227. readBufferSection (sectionToReadStart + initialSize,
  228. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  229. 0);
  230. }
  231. {
  232. const ScopedLock sl2 (bufferStartPosLock);
  233. bufferValidStart = newBVS;
  234. bufferValidEnd = newBVE;
  235. }
  236. bufferReadyEvent.signal();
  237. return true;
  238. }
  239. void BufferingAudioSource::readBufferSection (const int64 start, const int length, const int bufferOffset)
  240. {
  241. if (source->getNextReadPosition() != start)
  242. source->setNextReadPosition (start);
  243. AudioSourceChannelInfo info (&buffer, bufferOffset, length);
  244. source->getNextAudioBlock (info);
  245. }
  246. int BufferingAudioSource::useTimeSlice()
  247. {
  248. return readNextBufferChunk() ? 1 : 100;
  249. }