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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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. namespace juce
  18. {
  19. BufferingAudioSource::BufferingAudioSource (PositionableAudioSource* s,
  20. TimeSliceThread& thread,
  21. bool deleteSourceWhenDeleted,
  22. int bufferSizeSamples,
  23. int numChannels,
  24. bool prefillBufferOnPrepareToPlay)
  25. : source (s, deleteSourceWhenDeleted),
  26. backgroundThread (thread),
  27. numberOfSamplesToBuffer (jmax (1024, bufferSizeSamples)),
  28. numberOfChannels (numChannels),
  29. prefillBuffer (prefillBufferOnPrepareToPlay)
  30. {
  31. jassert (source != nullptr);
  32. jassert (numberOfSamplesToBuffer > 1024); // not much point using this class if you're
  33. // not using a larger buffer..
  34. }
  35. BufferingAudioSource::~BufferingAudioSource()
  36. {
  37. releaseResources();
  38. }
  39. //==============================================================================
  40. void BufferingAudioSource::prepareToPlay (int samplesPerBlockExpected, double newSampleRate)
  41. {
  42. auto bufferSizeNeeded = jmax (samplesPerBlockExpected * 2, numberOfSamplesToBuffer);
  43. if (newSampleRate != sampleRate
  44. || bufferSizeNeeded != buffer.getNumSamples()
  45. || ! isPrepared)
  46. {
  47. backgroundThread.removeTimeSliceClient (this);
  48. isPrepared = true;
  49. sampleRate = newSampleRate;
  50. source->prepareToPlay (samplesPerBlockExpected, newSampleRate);
  51. buffer.setSize (numberOfChannels, bufferSizeNeeded);
  52. buffer.clear();
  53. const ScopedLock sl (bufferRangeLock);
  54. bufferValidStart = 0;
  55. bufferValidEnd = 0;
  56. backgroundThread.addTimeSliceClient (this);
  57. do
  58. {
  59. const ScopedUnlock ul (bufferRangeLock);
  60. backgroundThread.moveToFrontOfQueue (this);
  61. Thread::sleep (5);
  62. }
  63. while (prefillBuffer
  64. && (bufferValidEnd - bufferValidStart < jmin (((int) newSampleRate) / 4, buffer.getNumSamples() / 2)));
  65. }
  66. }
  67. void BufferingAudioSource::releaseResources()
  68. {
  69. isPrepared = false;
  70. backgroundThread.removeTimeSliceClient (this);
  71. buffer.setSize (numberOfChannels, 0);
  72. // MSVC2015 seems to need this if statement to not generate a warning during linking.
  73. // As source is set in the constructor, there is no way that source could
  74. // ever equal this, but it seems to make MSVC2015 happy.
  75. if (source != this)
  76. source->releaseResources();
  77. }
  78. void BufferingAudioSource::getNextAudioBlock (const AudioSourceChannelInfo& info)
  79. {
  80. const auto bufferRange = getValidBufferRange (info.numSamples);
  81. if (bufferRange.isEmpty())
  82. {
  83. // total cache miss
  84. info.clearActiveBufferRegion();
  85. return;
  86. }
  87. const auto validStart = bufferRange.getStart();
  88. const auto validEnd = bufferRange.getEnd();
  89. const ScopedLock sl (callbackLock);
  90. if (validStart > 0)
  91. info.buffer->clear (info.startSample, validStart); // partial cache miss at start
  92. if (validEnd < info.numSamples)
  93. info.buffer->clear (info.startSample + validEnd,
  94. info.numSamples - validEnd); // partial cache miss at end
  95. if (validStart < validEnd)
  96. {
  97. for (int chan = jmin (numberOfChannels, info.buffer->getNumChannels()); --chan >= 0;)
  98. {
  99. jassert (buffer.getNumSamples() > 0);
  100. const auto startBufferIndex = (int) ((validStart + nextPlayPos) % buffer.getNumSamples());
  101. const auto endBufferIndex = (int) ((validEnd + nextPlayPos) % buffer.getNumSamples());
  102. if (startBufferIndex < endBufferIndex)
  103. {
  104. info.buffer->copyFrom (chan, info.startSample + validStart,
  105. buffer,
  106. chan, startBufferIndex,
  107. validEnd - validStart);
  108. }
  109. else
  110. {
  111. const auto initialSize = buffer.getNumSamples() - startBufferIndex;
  112. info.buffer->copyFrom (chan, info.startSample + validStart,
  113. buffer,
  114. chan, startBufferIndex,
  115. initialSize);
  116. info.buffer->copyFrom (chan, info.startSample + validStart + initialSize,
  117. buffer,
  118. chan, 0,
  119. (validEnd - validStart) - initialSize);
  120. }
  121. }
  122. }
  123. nextPlayPos += info.numSamples;
  124. }
  125. bool BufferingAudioSource::waitForNextAudioBlockReady (const AudioSourceChannelInfo& info, uint32 timeout)
  126. {
  127. if (source == nullptr || source->getTotalLength() <= 0)
  128. return false;
  129. if ((nextPlayPos + info.numSamples < 0)
  130. || (! isLooping() && nextPlayPos > getTotalLength()))
  131. return true;
  132. const auto startTime = Time::getMillisecondCounter();
  133. auto now = startTime;
  134. auto elapsed = (now >= startTime ? now - startTime
  135. : (std::numeric_limits<uint32>::max() - startTime) + now);
  136. while (elapsed <= timeout)
  137. {
  138. const auto bufferRange = getValidBufferRange (info.numSamples);
  139. const auto validStart = bufferRange.getStart();
  140. const auto validEnd = bufferRange.getEnd();
  141. if (validStart <= 0
  142. && validStart < validEnd
  143. && validEnd >= info.numSamples)
  144. {
  145. return true;
  146. }
  147. if (elapsed < timeout
  148. && ! bufferReadyEvent.wait (static_cast<int> (timeout - elapsed)))
  149. {
  150. return false;
  151. }
  152. now = Time::getMillisecondCounter();
  153. elapsed = (now >= startTime ? now - startTime
  154. : (std::numeric_limits<uint32>::max() - startTime) + now);
  155. }
  156. return false;
  157. }
  158. int64 BufferingAudioSource::getNextReadPosition() const
  159. {
  160. jassert (source->getTotalLength() > 0);
  161. const auto pos = nextPlayPos.load();
  162. return (source->isLooping() && nextPlayPos > 0)
  163. ? pos % source->getTotalLength()
  164. : pos;
  165. }
  166. void BufferingAudioSource::setNextReadPosition (int64 newPosition)
  167. {
  168. const ScopedLock sl (bufferRangeLock);
  169. nextPlayPos = newPosition;
  170. backgroundThread.moveToFrontOfQueue (this);
  171. }
  172. Range<int> BufferingAudioSource::getValidBufferRange (int numSamples) const
  173. {
  174. const ScopedLock sl (bufferRangeLock);
  175. const auto pos = nextPlayPos.load();
  176. return { (int) (jlimit (bufferValidStart, bufferValidEnd, pos) - pos),
  177. (int) (jlimit (bufferValidStart, bufferValidEnd, pos + numSamples) - pos) };
  178. }
  179. bool BufferingAudioSource::readNextBufferChunk()
  180. {
  181. int64 newBVS, newBVE, sectionToReadStart, sectionToReadEnd;
  182. {
  183. const ScopedLock sl (bufferRangeLock);
  184. if (wasSourceLooping != isLooping())
  185. {
  186. wasSourceLooping = isLooping();
  187. bufferValidStart = 0;
  188. bufferValidEnd = 0;
  189. }
  190. newBVS = jmax ((int64) 0, nextPlayPos.load());
  191. newBVE = newBVS + buffer.getNumSamples() - 4;
  192. sectionToReadStart = 0;
  193. sectionToReadEnd = 0;
  194. constexpr int maxChunkSize = 2048;
  195. if (newBVS < bufferValidStart || newBVS >= bufferValidEnd)
  196. {
  197. newBVE = jmin (newBVE, newBVS + maxChunkSize);
  198. sectionToReadStart = newBVS;
  199. sectionToReadEnd = newBVE;
  200. bufferValidStart = 0;
  201. bufferValidEnd = 0;
  202. }
  203. else if (std::abs ((int) (newBVS - bufferValidStart)) > 512
  204. || std::abs ((int) (newBVE - bufferValidEnd)) > 512)
  205. {
  206. newBVE = jmin (newBVE, bufferValidEnd + maxChunkSize);
  207. sectionToReadStart = bufferValidEnd;
  208. sectionToReadEnd = newBVE;
  209. bufferValidStart = newBVS;
  210. bufferValidEnd = jmin (bufferValidEnd, newBVE);
  211. }
  212. }
  213. if (sectionToReadStart == sectionToReadEnd)
  214. return false;
  215. jassert (buffer.getNumSamples() > 0);
  216. const auto bufferIndexStart = (int) (sectionToReadStart % buffer.getNumSamples());
  217. const auto bufferIndexEnd = (int) (sectionToReadEnd % buffer.getNumSamples());
  218. if (bufferIndexStart < bufferIndexEnd)
  219. {
  220. readBufferSection (sectionToReadStart,
  221. (int) (sectionToReadEnd - sectionToReadStart),
  222. bufferIndexStart);
  223. }
  224. else
  225. {
  226. const auto initialSize = buffer.getNumSamples() - bufferIndexStart;
  227. readBufferSection (sectionToReadStart,
  228. initialSize,
  229. bufferIndexStart);
  230. readBufferSection (sectionToReadStart + initialSize,
  231. (int) (sectionToReadEnd - sectionToReadStart) - initialSize,
  232. 0);
  233. }
  234. {
  235. const ScopedLock sl2 (bufferRangeLock);
  236. bufferValidStart = newBVS;
  237. bufferValidEnd = newBVE;
  238. }
  239. bufferReadyEvent.signal();
  240. return true;
  241. }
  242. void BufferingAudioSource::readBufferSection (int64 start, int length, int bufferOffset)
  243. {
  244. if (source->getNextReadPosition() != start)
  245. source->setNextReadPosition (start);
  246. AudioSourceChannelInfo info (&buffer, bufferOffset, length);
  247. const ScopedLock sl (callbackLock);
  248. source->getNextAudioBlock (info);
  249. }
  250. int BufferingAudioSource::useTimeSlice()
  251. {
  252. return readNextBufferChunk() ? 1 : 100;
  253. }
  254. } // namespace juce