The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
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.

310 lines
11KB

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