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.

316 lines
10KB

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