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.

1151 lines
43KB

  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. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. namespace juce
  20. {
  21. namespace dsp
  22. {
  23. /** This class is the convolution engine itself, processing only one channel at
  24. a time of input signal.
  25. */
  26. struct ConvolutionEngine
  27. {
  28. ConvolutionEngine() = default;
  29. //==============================================================================
  30. struct ProcessingInformation
  31. {
  32. enum class SourceType
  33. {
  34. sourceBinaryData,
  35. sourceAudioFile,
  36. sourceAudioBuffer,
  37. sourceNone
  38. };
  39. SourceType sourceType = SourceType::sourceNone;
  40. const void* sourceData;
  41. size_t sourceDataSize;
  42. File fileImpulseResponse;
  43. double bufferSampleRate;
  44. AudioBuffer<float>* buffer;
  45. double sampleRate = 0;
  46. bool wantsStereo;
  47. bool wantsTrimming;
  48. size_t impulseResponseSize;
  49. size_t maximumBufferSize = 0;
  50. };
  51. //==============================================================================
  52. void reset()
  53. {
  54. bufferInput.clear();
  55. bufferOverlap.clear();
  56. bufferTempOutput.clear();
  57. for (auto i = 0; i < buffersInputSegments.size(); ++i)
  58. buffersInputSegments.getReference (i).clear();
  59. currentSegment = 0;
  60. inputDataPos = 0;
  61. }
  62. /** Initalize all the states and objects to perform the convolution. */
  63. void initializeConvolutionEngine (ProcessingInformation& info, int channel)
  64. {
  65. blockSize = (size_t) nextPowerOfTwo ((int) info.maximumBufferSize);
  66. FFTSize = blockSize > 128 ? 2 * blockSize
  67. : 4 * blockSize;
  68. numSegments = ((size_t) info.buffer->getNumSamples()) / (FFTSize - blockSize) + 1;
  69. numInputSegments = (blockSize > 128 ? numSegments : 3 * numSegments);
  70. FFTobject = new FFT (roundDoubleToInt (log2 (FFTSize)));
  71. bufferInput.setSize (1, static_cast<int> (FFTSize));
  72. bufferOutput.setSize (1, static_cast<int> (FFTSize * 2));
  73. bufferTempOutput.setSize (1, static_cast<int> (FFTSize * 2));
  74. bufferOverlap.setSize (1, static_cast<int> (FFTSize));
  75. buffersInputSegments.clear();
  76. buffersImpulseSegments.clear();
  77. for (size_t i = 0; i < numInputSegments; ++i)
  78. {
  79. AudioBuffer<float> newInputSegment;
  80. newInputSegment.setSize (1, static_cast<int> (FFTSize * 2));
  81. buffersInputSegments.add (newInputSegment);
  82. }
  83. for (auto i = 0u; i < numSegments; ++i)
  84. {
  85. AudioBuffer<float> newImpulseSegment;
  86. newImpulseSegment.setSize (1, static_cast<int> (FFTSize * 2));
  87. buffersImpulseSegments.add (newImpulseSegment);
  88. }
  89. ScopedPointer<FFT> FFTTempObject = new FFT (roundDoubleToInt (log2 (FFTSize)));
  90. auto numChannels = (info.wantsStereo && info.buffer->getNumChannels() >= 2 ? 2 : 1);
  91. if (channel < numChannels)
  92. {
  93. auto* channelData = info.buffer->getWritePointer (channel);
  94. for (size_t n = 0; n < numSegments; ++n)
  95. {
  96. buffersImpulseSegments.getReference (static_cast<int> (n)).clear();
  97. auto* impulseResponse = buffersImpulseSegments.getReference (static_cast<int> (n)).getWritePointer (0);
  98. if (n == 0)
  99. impulseResponse[0] = 1.0f;
  100. for (size_t i = 0; i < FFTSize - blockSize; ++i)
  101. if (i + n * (FFTSize - blockSize) < (size_t) info.buffer->getNumSamples())
  102. impulseResponse[i] = channelData[i + n * (FFTSize - blockSize)];
  103. FFTTempObject->performRealOnlyForwardTransform (impulseResponse);
  104. prepareForConvolution (impulseResponse);
  105. }
  106. }
  107. reset();
  108. isReady = true;
  109. }
  110. /** Copy the states of another engine. */
  111. void copyStateFromOtherEngine (const ConvolutionEngine& other)
  112. {
  113. if (FFTSize != other.FFTSize)
  114. {
  115. FFTobject = new FFT (roundDoubleToInt (log2 (other.FFTSize)));
  116. FFTSize = other.FFTSize;
  117. }
  118. currentSegment = other.currentSegment;
  119. numInputSegments = other.numInputSegments;
  120. numSegments = other.numSegments;
  121. blockSize = other.blockSize;
  122. inputDataPos = other.inputDataPos;
  123. bufferInput = other.bufferInput;
  124. bufferTempOutput = other.bufferTempOutput;
  125. bufferOutput = other.bufferOutput;
  126. buffersInputSegments = other.buffersInputSegments;
  127. buffersImpulseSegments = other.buffersImpulseSegments;
  128. bufferOverlap = other.bufferOverlap;
  129. isReady = true;
  130. }
  131. /** Performs the uniform partitioned convolution using FFT. */
  132. void processSamples (const float* input, float* output, size_t numSamples)
  133. {
  134. if (! isReady)
  135. return;
  136. // Overlap-add, zero latency convolution algorithm with uniform partitioning
  137. size_t numSamplesProcessed = 0;
  138. auto indexStep = numInputSegments / numSegments;
  139. auto* inputData = bufferInput.getWritePointer (0);
  140. auto* outputTempData = bufferTempOutput.getWritePointer (0);
  141. auto* outputData = bufferOutput.getWritePointer (0);
  142. auto* overlapData = bufferOverlap.getWritePointer (0);
  143. while (numSamplesProcessed < numSamples)
  144. {
  145. const bool inputDataWasEmpty = (inputDataPos == 0);
  146. auto numSamplesToProcess = jmin (numSamples - numSamplesProcessed, blockSize - inputDataPos);
  147. // copy the input samples
  148. FloatVectorOperations::copy (inputData + inputDataPos, input + numSamplesProcessed, static_cast<int> (numSamplesToProcess));
  149. auto* inputSegmentData = buffersInputSegments.getReference (static_cast<int> (currentSegment)).getWritePointer (0);
  150. FloatVectorOperations::copy (inputSegmentData, inputData, static_cast<int> (FFTSize));
  151. // Forward FFT
  152. FFTobject->performRealOnlyForwardTransform (inputSegmentData);
  153. prepareForConvolution (inputSegmentData);
  154. // Complex multiplication
  155. if (inputDataWasEmpty)
  156. {
  157. FloatVectorOperations::fill (outputTempData, 0, static_cast<int> (FFTSize + 1));
  158. auto index = currentSegment;
  159. for (size_t i = 1; i < numSegments; ++i)
  160. {
  161. index += indexStep;
  162. if (index >= numInputSegments)
  163. index -= numInputSegments;
  164. convolutionProcessingAndAccumulate (buffersInputSegments.getReference (static_cast<int> (index)).getWritePointer (0),
  165. buffersImpulseSegments.getReference (static_cast<int> (i)).getWritePointer (0),
  166. outputTempData);
  167. }
  168. }
  169. FloatVectorOperations::copy (outputData, outputTempData, static_cast<int> (FFTSize + 1));
  170. convolutionProcessingAndAccumulate (buffersInputSegments.getReference (static_cast<int> (currentSegment)).getWritePointer (0),
  171. buffersImpulseSegments.getReference (0).getWritePointer (0),
  172. outputData);
  173. // Inverse FFT
  174. updateSymmetricFrequencyDomainData (outputData);
  175. FFTobject->performRealOnlyInverseTransform (outputData);
  176. // Add overlap
  177. for (size_t i = 0; i < numSamplesToProcess; ++i)
  178. output[i + numSamplesProcessed] = outputData[inputDataPos + i] + overlapData[inputDataPos + i];
  179. // Input buffer full => Next block
  180. inputDataPos += numSamplesToProcess;
  181. if (inputDataPos == blockSize)
  182. {
  183. // Input buffer is empty again now
  184. FloatVectorOperations::fill (inputData, 0.0f, static_cast<int> (FFTSize));
  185. inputDataPos = 0;
  186. // Extra step for segSize > blockSize
  187. FloatVectorOperations::add (&(outputData[blockSize]), &(overlapData[blockSize]), static_cast<int> (FFTSize - 2 * blockSize));
  188. // Save the overlap
  189. FloatVectorOperations::copy (overlapData, &(outputData[blockSize]), static_cast<int> (FFTSize - blockSize));
  190. // Update current segment
  191. currentSegment = (currentSegment > 0) ? (currentSegment - 1) : (numInputSegments - 1);
  192. }
  193. numSamplesProcessed += numSamplesToProcess;
  194. }
  195. }
  196. /** After each FFT, this function is called to allow convolution to be performed with only 4 SIMD functions calls. */
  197. void prepareForConvolution (float *samples) noexcept
  198. {
  199. auto FFTSizeDiv2 = FFTSize / 2;
  200. for (size_t i = 0; i < FFTSizeDiv2; i++)
  201. samples[i] = samples[2 * i];
  202. samples[FFTSizeDiv2] = 0;
  203. for (size_t i = 1; i < FFTSizeDiv2; i++)
  204. samples[i + FFTSizeDiv2] = -samples[2 * (FFTSize - i) + 1];
  205. }
  206. /** Does the convolution operation itself only on half of the frequency domain samples. */
  207. void convolutionProcessingAndAccumulate (const float *input, const float *impulse, float *output)
  208. {
  209. auto FFTSizeDiv2 = FFTSize / 2;
  210. FloatVectorOperations::addWithMultiply (output, input, impulse, static_cast<int> (FFTSizeDiv2));
  211. FloatVectorOperations::subtractWithMultiply (output, &(input[FFTSizeDiv2]), &(impulse[FFTSizeDiv2]), static_cast<int> (FFTSizeDiv2));
  212. FloatVectorOperations::addWithMultiply (&(output[FFTSizeDiv2]), input, &(impulse[FFTSizeDiv2]), static_cast<int> (FFTSizeDiv2));
  213. FloatVectorOperations::addWithMultiply (&(output[FFTSizeDiv2]), &(input[FFTSizeDiv2]), impulse, static_cast<int> (FFTSizeDiv2));
  214. }
  215. /** Undo the re-organization of samples from the function prepareForConvolution.
  216. Then, takes the conjugate of the frequency domain first half of samples, to fill the
  217. second half, so that the inverse transform will return real samples in the time domain.
  218. */
  219. void updateSymmetricFrequencyDomainData (float* samples) noexcept
  220. {
  221. auto FFTSizeDiv2 = FFTSize / 2;
  222. for (size_t i = 1; i < FFTSizeDiv2; i++)
  223. {
  224. samples[2 * (FFTSize - i)] = samples[i];
  225. samples[2 * (FFTSize - i) + 1] = -samples[FFTSizeDiv2 + i];
  226. }
  227. samples[1] = 0.f;
  228. for (size_t i = 1; i < FFTSizeDiv2; i++)
  229. {
  230. samples[2 * i] = samples[2 * (FFTSize - i)];
  231. samples[2 * i + 1] = -samples[2 * (FFTSize - i) + 1];
  232. }
  233. }
  234. //==============================================================================
  235. ScopedPointer<FFT> FFTobject;
  236. size_t FFTSize = 0;
  237. size_t currentSegment = 0, numInputSegments = 0, numSegments = 0, blockSize = 0, inputDataPos = 0;
  238. AudioBuffer<float> bufferInput, bufferOutput, bufferTempOutput, bufferOverlap;
  239. Array<AudioBuffer<float>> buffersInputSegments, buffersImpulseSegments;
  240. bool isReady = false;
  241. //==============================================================================
  242. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ConvolutionEngine)
  243. };
  244. //==============================================================================
  245. /** Manages all the changes requested by the main convolution engine, to minimize
  246. the number of calls of the convolution engine initialization, and the potential
  247. consequences of multiple quick calls to the function Convolution::loadImpulseResponse.
  248. */
  249. struct Convolution::Pimpl : private Thread
  250. {
  251. public:
  252. enum class ChangeRequest
  253. {
  254. changeEngine = 0,
  255. changeSampleRate,
  256. changeMaximumBufferSize,
  257. changeSource,
  258. changeImpulseResponseSize,
  259. changeStereo,
  260. changeTrimming,
  261. numChangeRequestTypes
  262. };
  263. using SourceType = ConvolutionEngine::ProcessingInformation::SourceType;
  264. //==============================================================================
  265. Pimpl() : Thread ("Convolution"), abstractFifo (fifoSize)
  266. {
  267. abstractFifo.reset();
  268. requestsType.resize (fifoSize);
  269. requestsParameter.resize (fifoSize);
  270. for (auto i = 0u; i < 4; ++i)
  271. engines.add (new ConvolutionEngine());
  272. currentInfo.maximumBufferSize = 0;
  273. currentInfo.buffer = &impulseResponse;
  274. }
  275. ~Pimpl()
  276. {
  277. stopThread (10000);
  278. }
  279. //==============================================================================
  280. /** Adds a new change request. */
  281. void addToFifo (ChangeRequest type, juce::var parameter)
  282. {
  283. int start1, size1, start2, size2;
  284. abstractFifo.prepareToWrite (1, start1, size1, start2, size2);
  285. if (size1 > 0)
  286. {
  287. requestsType.setUnchecked (start1, type);
  288. requestsParameter.setUnchecked (start1, parameter);
  289. }
  290. if (size2 > 0)
  291. {
  292. requestsType.setUnchecked (start2, type);
  293. requestsParameter.setUnchecked (start2, parameter);
  294. }
  295. abstractFifo.finishedWrite (size1 + size2);
  296. }
  297. /** Adds a new array of change requests. */
  298. void addToFifo (ChangeRequest* types, juce::var* parameters, int numEntries)
  299. {
  300. int start1, size1, start2, size2;
  301. abstractFifo.prepareToWrite (numEntries, start1, size1, start2, size2);
  302. if (size1 > 0)
  303. {
  304. for (int i = 0; i < size1; ++i)
  305. {
  306. requestsType.setUnchecked (start1 + i, types[i]);
  307. requestsParameter.setUnchecked (start1 + i, parameters[i]);
  308. }
  309. }
  310. if (size2 > 0)
  311. {
  312. for (int i = 0; i < size2; ++i)
  313. {
  314. requestsType.setUnchecked (start2 + i, types[i + size1]);
  315. requestsParameter.setUnchecked (start2 + i, parameters[i + size1]);
  316. }
  317. }
  318. abstractFifo.finishedWrite (size1 + size2);
  319. }
  320. /** Reads requests from the fifo */
  321. void readFromFifo (ChangeRequest& type, juce::var& parameter)
  322. {
  323. int start1, size1, start2, size2;
  324. abstractFifo.prepareToRead (1, start1, size1, start2, size2);
  325. if (size1 > 0)
  326. {
  327. type = requestsType[start1];
  328. parameter = requestsParameter[start1];
  329. }
  330. if (size2 > 0)
  331. {
  332. type = requestsType[start2];
  333. parameter = requestsParameter[start2];
  334. }
  335. abstractFifo.finishedRead (size1 + size2);
  336. }
  337. /** Returns the number of requests that still need to be processed */
  338. int getNumRemainingEntries() const noexcept
  339. {
  340. return abstractFifo.getNumReady();
  341. }
  342. //==============================================================================
  343. /** This function processes all the change requests to remove all the the
  344. redundant ones, and to tell what kind of initialization must be done.
  345. Depending on the results, the convolution engines might be reset, or
  346. simply updated, or they might not need any change at all.
  347. */
  348. void processFifo()
  349. {
  350. if (getNumRemainingEntries() == 0 || isThreadRunning() || mustInterpolate)
  351. return;
  352. // retrieve the information from the FIFO for processing
  353. Array<ChangeRequest> requests;
  354. Array<juce::var> requestParameters;
  355. while (getNumRemainingEntries() > 0)
  356. {
  357. ChangeRequest type = ChangeRequest::changeEngine;
  358. juce::var parameter;
  359. readFromFifo (type, parameter);
  360. requests.add (type);
  361. requestParameters.add (parameter);
  362. }
  363. // remove any useless messages
  364. for (int i = 0; i < (int) ChangeRequest::numChangeRequestTypes; ++i)
  365. {
  366. bool exists = false;
  367. for (int n = requests.size(); --n >= 0;)
  368. {
  369. if (requests[n] == (ChangeRequest) i)
  370. {
  371. if (! exists)
  372. {
  373. exists = true;
  374. }
  375. else
  376. {
  377. requests.remove (n);
  378. requestParameters.remove (n);
  379. }
  380. }
  381. }
  382. }
  383. changeLevel = 0;
  384. for (int n = 0; n < requests.size(); ++n)
  385. {
  386. switch (requests[n])
  387. {
  388. case ChangeRequest::changeEngine:
  389. changeLevel = 3;
  390. break;
  391. case ChangeRequest::changeSampleRate:
  392. {
  393. double newSampleRate = requestParameters[n];
  394. if (currentInfo.sampleRate != newSampleRate)
  395. changeLevel = 3;
  396. currentInfo.sampleRate = newSampleRate;
  397. }
  398. break;
  399. case ChangeRequest::changeMaximumBufferSize:
  400. {
  401. int newMaximumBufferSize = requestParameters[n];
  402. if (currentInfo.maximumBufferSize != (size_t) newMaximumBufferSize)
  403. changeLevel = 3;
  404. currentInfo.maximumBufferSize = (size_t) newMaximumBufferSize;
  405. }
  406. break;
  407. case ChangeRequest::changeSource:
  408. {
  409. auto* arrayParameters = requestParameters[n].getArray();
  410. auto newSourceType = static_cast<SourceType> (static_cast<int> (arrayParameters->getUnchecked (0)));
  411. if (currentInfo.sourceType != newSourceType)
  412. changeLevel = jmax (2, changeLevel);
  413. if (newSourceType == SourceType::sourceBinaryData)
  414. {
  415. auto& prm = arrayParameters->getRawDataPointer()[1];
  416. auto* newMemoryBlock = prm.getBinaryData();
  417. auto* newPtr = newMemoryBlock->getData();
  418. auto newSize = newMemoryBlock->getSize();
  419. if (currentInfo.sourceData != newPtr || currentInfo.sourceDataSize != newSize)
  420. changeLevel = jmax (2, changeLevel);
  421. currentInfo.sourceType = SourceType::sourceBinaryData;
  422. currentInfo.sourceData = newPtr;
  423. currentInfo.sourceDataSize = newSize;
  424. currentInfo.fileImpulseResponse = File();
  425. }
  426. else if (newSourceType == SourceType::sourceAudioFile)
  427. {
  428. File newFile (arrayParameters->getUnchecked (1).toString());
  429. if (currentInfo.fileImpulseResponse != newFile)
  430. changeLevel = jmax (2, changeLevel);
  431. currentInfo.sourceType = SourceType::sourceAudioFile;
  432. currentInfo.fileImpulseResponse = newFile;
  433. currentInfo.sourceData = nullptr;
  434. currentInfo.sourceDataSize = 0;
  435. }
  436. else if (newSourceType == SourceType::sourceAudioBuffer)
  437. {
  438. double bufferSampleRate (arrayParameters->getUnchecked (1));
  439. changeLevel = jmax (2, changeLevel);
  440. currentInfo.sourceType = SourceType::sourceAudioBuffer;
  441. currentInfo.bufferSampleRate = bufferSampleRate;
  442. currentInfo.fileImpulseResponse = File();
  443. currentInfo.sourceData = nullptr;
  444. currentInfo.sourceDataSize = 0;
  445. }
  446. }
  447. break;
  448. case ChangeRequest::changeImpulseResponseSize:
  449. {
  450. int64 newSize = requestParameters[n];
  451. if (currentInfo.impulseResponseSize != (size_t) newSize)
  452. changeLevel = jmax (1, changeLevel);
  453. currentInfo.impulseResponseSize = (size_t) newSize;
  454. }
  455. break;
  456. case ChangeRequest::changeStereo:
  457. {
  458. bool newWantsStereo = requestParameters[n];
  459. if (currentInfo.wantsStereo != newWantsStereo)
  460. changeLevel = jmax (1, changeLevel);
  461. currentInfo.wantsStereo = newWantsStereo;
  462. }
  463. break;
  464. case ChangeRequest::changeTrimming:
  465. {
  466. bool newWantsTrimming = requestParameters[n];
  467. if (currentInfo.wantsTrimming != newWantsTrimming)
  468. changeLevel = jmax(1, changeLevel);
  469. currentInfo.wantsTrimming = newWantsTrimming;
  470. }
  471. break;
  472. default:
  473. jassertfalse;
  474. break;
  475. }
  476. }
  477. if (currentInfo.sourceType == SourceType::sourceNone)
  478. {
  479. currentInfo.sourceType = SourceType::sourceAudioBuffer;
  480. if (currentInfo.sampleRate == 0)
  481. currentInfo.sampleRate = 44100;
  482. if (currentInfo.maximumBufferSize == 0)
  483. currentInfo.maximumBufferSize = 128;
  484. currentInfo.bufferSampleRate = currentInfo.sampleRate;
  485. currentInfo.impulseResponseSize = 1;
  486. currentInfo.fileImpulseResponse = File();
  487. currentInfo.sourceData = nullptr;
  488. currentInfo.sourceDataSize = 0;
  489. AudioBuffer<float> newBuffer;
  490. newBuffer.setSize (1, 1);
  491. newBuffer.setSample (0, 0, 1.f);
  492. copyBufferToTemporaryLocation (newBuffer);
  493. }
  494. // action depending on the change level
  495. if (changeLevel == 3)
  496. {
  497. interpolationBuffer.setSize (2, static_cast<int> (currentInfo.maximumBufferSize));
  498. processImpulseResponse();
  499. initializeConvolutionEngines();
  500. }
  501. else if (changeLevel == 2)
  502. {
  503. startThread();
  504. }
  505. else if (changeLevel == 1)
  506. {
  507. startThread();
  508. }
  509. }
  510. //==============================================================================
  511. void copyBufferToTemporaryLocation (const AudioBuffer<float>& buffer)
  512. {
  513. const SpinLock::ScopedLockType sl (processLock);
  514. auto numChannels = buffer.getNumChannels() > 1 ? 2 : 1;
  515. temporaryBuffer.setSize (numChannels, buffer.getNumSamples(), false, false, true);
  516. for (auto channel = 0; channel < numChannels; ++channel)
  517. temporaryBuffer.copyFrom (channel, 0, buffer, channel, 0, buffer.getNumSamples());
  518. }
  519. /** Copies a buffer from a temporary location to the impulseResponseOriginal
  520. buffer for the sourceAudioBuffer. */
  521. void copyBufferFromTemporaryLocation()
  522. {
  523. const SpinLock::ScopedLockType sl (processLock);
  524. impulseResponseOriginal.setSize (2, temporaryBuffer.getNumSamples(), false, false, true);
  525. for (auto channel = 0; channel < temporaryBuffer.getNumChannels(); ++channel)
  526. impulseResponseOriginal.copyFrom (channel, 0, temporaryBuffer, channel, 0, temporaryBuffer.getNumSamples());
  527. }
  528. //==============================================================================
  529. void reset()
  530. {
  531. for (auto* e : engines)
  532. e->reset();
  533. }
  534. /** Convolution processing handling interpolation between previous and new states
  535. of the convolution engines.
  536. */
  537. void processSamples (const AudioBlock<float>& input, AudioBlock<float>& output)
  538. {
  539. processFifo();
  540. size_t numChannels = input.getNumChannels();
  541. size_t numSamples = jmin (input.getNumSamples(), output.getNumSamples());
  542. if (mustInterpolate == false)
  543. {
  544. for (size_t channel = 0; channel < numChannels; ++channel)
  545. engines[(int) channel]->processSamples (input.getChannelPointer (channel), output.getChannelPointer (channel), numSamples);
  546. }
  547. else
  548. {
  549. auto interpolated = AudioBlock<float> (interpolationBuffer).getSubBlock (0, numSamples);
  550. for (size_t channel = 0; channel < numChannels; ++channel)
  551. {
  552. auto&& buffer = output.getSingleChannelBlock (channel);
  553. interpolationBuffer.copyFrom ((int) channel, 0, input.getChannelPointer (channel), (int) numSamples);
  554. engines[(int) channel]->processSamples (input.getChannelPointer (channel), buffer.getChannelPointer (0), numSamples);
  555. changeVolumes[channel].applyGain (buffer.getChannelPointer (0), (int) numSamples);
  556. auto* interPtr = interpolationBuffer.getWritePointer ((int) channel);
  557. engines[(int) channel + 2]->processSamples (interPtr, interPtr, numSamples);
  558. changeVolumes[channel + 2].applyGain (interPtr, (int) numSamples);
  559. buffer += interpolated.getSingleChannelBlock (channel);
  560. }
  561. if (changeVolumes[0].isSmoothing() == false)
  562. {
  563. mustInterpolate = false;
  564. for (auto channel = 0; channel < 2; ++channel)
  565. engines[channel]->copyStateFromOtherEngine (*engines[channel + 2]);
  566. }
  567. }
  568. }
  569. private:
  570. //==============================================================================
  571. void run() override
  572. {
  573. if (changeLevel == 2)
  574. {
  575. processImpulseResponse();
  576. if (isThreadRunning() && threadShouldExit())
  577. return;
  578. initializeConvolutionEngines();
  579. }
  580. else if (changeLevel == 1)
  581. {
  582. initializeConvolutionEngines();
  583. }
  584. }
  585. void processImpulseResponse()
  586. {
  587. if (currentInfo.sourceType == SourceType::sourceBinaryData)
  588. {
  589. copyAudioStreamInAudioBuffer (new MemoryInputStream (currentInfo.sourceData, currentInfo.sourceDataSize, false));
  590. }
  591. else if (currentInfo.sourceType == SourceType::sourceAudioFile)
  592. {
  593. copyAudioStreamInAudioBuffer (new FileInputStream (currentInfo.fileImpulseResponse));
  594. }
  595. else if (currentInfo.sourceType == SourceType::sourceAudioBuffer)
  596. {
  597. copyBufferFromTemporaryLocation();
  598. trimAndResampleImpulseResponse (temporaryBuffer.getNumChannels(), currentInfo.bufferSampleRate, currentInfo.wantsTrimming);
  599. }
  600. if (isThreadRunning() && threadShouldExit())
  601. return;
  602. if (currentInfo.wantsStereo)
  603. {
  604. normalizeImpulseResponse (currentInfo.buffer->getWritePointer(0), currentInfo.buffer->getNumSamples(), 1.0);
  605. normalizeImpulseResponse (currentInfo.buffer->getWritePointer(1), currentInfo.buffer->getNumSamples(), 1.0);
  606. }
  607. else
  608. {
  609. normalizeImpulseResponse (currentInfo.buffer->getWritePointer (0), currentInfo.buffer->getNumSamples(), 1.0);
  610. }
  611. }
  612. /** Converts the data from an audio file into a stereo audio buffer of floats, and
  613. performs resampling if necessary.
  614. */
  615. double copyAudioStreamInAudioBuffer (InputStream* stream)
  616. {
  617. AudioFormatManager manager;
  618. manager.registerBasicFormats();
  619. if (ScopedPointer<AudioFormatReader> formatReader = manager.createReaderFor (stream))
  620. {
  621. auto maximumTimeInSeconds = 10.0;
  622. int64 maximumLength = static_cast<int64> (roundDoubleToInt (maximumTimeInSeconds * formatReader->sampleRate));
  623. auto numChannels = formatReader->numChannels > 1 ? 2 : 1;
  624. impulseResponseOriginal.setSize (2, static_cast<int> (jmin (maximumLength, formatReader->lengthInSamples)), false, false, true);
  625. impulseResponseOriginal.clear();
  626. formatReader->read (&(impulseResponseOriginal), 0, impulseResponseOriginal.getNumSamples(), 0, true, numChannels > 1);
  627. return trimAndResampleImpulseResponse (numChannels, formatReader->sampleRate, currentInfo.wantsTrimming);
  628. }
  629. else
  630. return 0.0;
  631. }
  632. double trimAndResampleImpulseResponse (int numChannels, double bufferSampleRate, bool mustTrim)
  633. {
  634. auto thresholdTrim = Decibels::decibelsToGain (-80.0f);
  635. auto indexStart = 0;
  636. auto indexEnd = impulseResponseOriginal.getNumSamples() - 1;
  637. if (mustTrim)
  638. {
  639. indexStart = impulseResponseOriginal.getNumSamples() - 1;
  640. indexEnd = 0;
  641. for (auto channel = 0; channel < numChannels; ++channel)
  642. {
  643. auto localIndexStart = 0;
  644. auto localIndexEnd = impulseResponseOriginal.getNumSamples() - 1;
  645. auto* channelData = impulseResponseOriginal.getReadPointer (channel);
  646. while (localIndexStart < impulseResponseOriginal.getNumSamples() - 1
  647. && channelData[localIndexStart] <= thresholdTrim
  648. && channelData[localIndexStart] >= -thresholdTrim)
  649. ++localIndexStart;
  650. while (localIndexEnd >= 0
  651. && channelData[localIndexEnd] <= thresholdTrim
  652. && channelData[localIndexEnd] >= -thresholdTrim)
  653. --localIndexEnd;
  654. indexStart = jmin (indexStart, localIndexStart);
  655. indexEnd = jmax (indexEnd, localIndexEnd);
  656. }
  657. if (indexStart > 0)
  658. {
  659. for (auto channel = 0; channel < numChannels; ++channel)
  660. {
  661. auto* channelData = impulseResponseOriginal.getWritePointer (channel);
  662. for (auto i = 0; i < indexEnd - indexStart + 1; ++i)
  663. channelData[i] = channelData[i + indexStart];
  664. for (auto i = indexEnd - indexStart + 1; i < impulseResponseOriginal.getNumSamples() - 1; ++i)
  665. channelData[i] = 0.0f;
  666. }
  667. }
  668. }
  669. double factorReading;
  670. if (currentInfo.sampleRate == bufferSampleRate)
  671. {
  672. // No resampling
  673. factorReading = 1.0;
  674. auto impulseSize = jmin (static_cast<int> (currentInfo.impulseResponseSize), indexEnd - indexStart + 1);
  675. impulseResponse.setSize (2, impulseSize);
  676. impulseResponse.clear();
  677. for (auto channel = 0; channel < numChannels; ++channel)
  678. impulseResponse.copyFrom (channel, 0, impulseResponseOriginal, channel, 0, impulseSize);
  679. }
  680. else
  681. {
  682. // Resampling
  683. factorReading = bufferSampleRate / currentInfo.sampleRate;
  684. auto impulseSize = jmin (static_cast<int> (currentInfo.impulseResponseSize), roundDoubleToInt ((indexEnd - indexStart + 1) / factorReading));
  685. impulseResponse.setSize (2, impulseSize);
  686. impulseResponse.clear();
  687. MemoryAudioSource memorySource (impulseResponseOriginal, false);
  688. ResamplingAudioSource resamplingSource (&memorySource, false, numChannels);
  689. resamplingSource.setResamplingRatio (factorReading);
  690. resamplingSource.prepareToPlay (impulseSize, currentInfo.sampleRate);
  691. AudioSourceChannelInfo info;
  692. info.startSample = 0;
  693. info.numSamples = impulseSize;
  694. info.buffer = &impulseResponse;
  695. resamplingSource.getNextAudioBlock (info);
  696. }
  697. // Filling the second channel with the first if necessary
  698. if (numChannels == 1)
  699. impulseResponse.copyFrom (1, 0, impulseResponse, 0, 0, impulseResponse.getNumSamples());
  700. return factorReading;
  701. }
  702. void normalizeImpulseResponse (float* samples, int numSamples, double factorResampling) const
  703. {
  704. auto magnitude = 0.0f;
  705. for (int i = 0; i < numSamples; ++i)
  706. magnitude += samples[i] * samples[i];
  707. auto magnitudeInv = 1.0f / (4.0f * std::sqrt (magnitude)) * 0.5f * static_cast <float> (factorResampling);
  708. for (int i = 0; i < numSamples; ++i)
  709. samples[i] *= magnitudeInv;
  710. }
  711. void initializeConvolutionEngines()
  712. {
  713. if (currentInfo.maximumBufferSize == 0)
  714. return;
  715. auto numChannels = (currentInfo.wantsStereo ? 2 : 1);
  716. if (changeLevel == 3)
  717. {
  718. for (int i = 0; i < numChannels; ++i)
  719. engines[i]->initializeConvolutionEngine (currentInfo, i);
  720. if (numChannels == 1)
  721. engines[1]->copyStateFromOtherEngine (*engines[0]);
  722. mustInterpolate = false;
  723. }
  724. else
  725. {
  726. for (int i = 0; i < numChannels; ++i)
  727. {
  728. engines[i + 2]->initializeConvolutionEngine (currentInfo, i);
  729. engines[i + 2]->reset();
  730. if (isThreadRunning() && threadShouldExit())
  731. return;
  732. }
  733. if (numChannels == 1)
  734. engines[3]->copyStateFromOtherEngine (*engines[2]);
  735. for (size_t i = 0; i < 2; ++i)
  736. {
  737. changeVolumes[i].setValue (1.0f);
  738. changeVolumes[i].reset (currentInfo.sampleRate, 0.05);
  739. changeVolumes[i].setValue (0.0f);
  740. changeVolumes[i + 2].setValue (0.0f);
  741. changeVolumes[i + 2].reset (currentInfo.sampleRate, 0.05);
  742. changeVolumes[i + 2].setValue (1.0f);
  743. }
  744. mustInterpolate = true;
  745. }
  746. }
  747. //==============================================================================
  748. static constexpr int fifoSize = 256; // the size of the fifo which handles all the change requests
  749. AbstractFifo abstractFifo; // the abstract fifo
  750. Array<ChangeRequest> requestsType; // an array of ChangeRequest
  751. Array<juce::var> requestsParameter; // an array of change parameters
  752. int changeLevel = 0; // the current level of requested change in the convolution engine
  753. //==============================================================================
  754. ConvolutionEngine::ProcessingInformation currentInfo; // the information about the impulse response to load
  755. AudioBuffer<float> temporaryBuffer; // a temporary buffer that is used when the function copyAndLoadImpulseResponse is called in the main API
  756. SpinLock processLock; // a necessary lock to use with this temporary buffer
  757. AudioBuffer<float> impulseResponseOriginal; // a buffer with the original impulse response
  758. AudioBuffer<float> impulseResponse; // a buffer with the impulse response trimmed, resampled, resized and normalized
  759. //==============================================================================
  760. OwnedArray<ConvolutionEngine> engines; // the 4 convolution engines being used
  761. AudioBuffer<float> interpolationBuffer; // a buffer to do the interpolation between the convolution engines 0-1 and 2-3
  762. LinearSmoothedValue<float> changeVolumes[4]; // the volumes for each convolution engine during interpolation
  763. bool mustInterpolate = false; // tells if the convolution engines outputs must be currently interpolated
  764. //==============================================================================
  765. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Pimpl)
  766. };
  767. //==============================================================================
  768. Convolution::Convolution()
  769. {
  770. pimpl = new Pimpl();
  771. pimpl->addToFifo (Convolution::Pimpl::ChangeRequest::changeEngine, juce::var (0));
  772. }
  773. Convolution::~Convolution()
  774. {
  775. }
  776. void Convolution::loadImpulseResponse (const void* sourceData, size_t sourceDataSize, bool wantsStereo, bool wantsTrimming, size_t size)
  777. {
  778. if (sourceData == nullptr)
  779. return;
  780. Pimpl::ChangeRequest types[] = { Pimpl::ChangeRequest::changeSource,
  781. Pimpl::ChangeRequest::changeImpulseResponseSize,
  782. Pimpl::ChangeRequest::changeStereo,
  783. Pimpl::ChangeRequest::changeTrimming };
  784. Array<juce::var> sourceParameter;
  785. sourceParameter.add (juce::var ((int) ConvolutionEngine::ProcessingInformation::SourceType::sourceBinaryData));
  786. sourceParameter.add (juce::var (sourceData, sourceDataSize));
  787. juce::var parameters[] = { juce::var (sourceParameter),
  788. juce::var (static_cast<int64> (size)),
  789. juce::var (wantsStereo),
  790. juce::var (wantsTrimming) };
  791. pimpl->addToFifo (types, parameters, 3);
  792. }
  793. void Convolution::loadImpulseResponse (const File& fileImpulseResponse, bool wantsStereo, bool wantsTrimming, size_t size)
  794. {
  795. if (! fileImpulseResponse.existsAsFile())
  796. return;
  797. Pimpl::ChangeRequest types[] = { Pimpl::ChangeRequest::changeSource,
  798. Pimpl::ChangeRequest::changeImpulseResponseSize,
  799. Pimpl::ChangeRequest::changeStereo,
  800. Pimpl::ChangeRequest::changeTrimming };
  801. Array<juce::var> sourceParameter;
  802. sourceParameter.add (juce::var ((int) ConvolutionEngine::ProcessingInformation::SourceType::sourceAudioFile));
  803. sourceParameter.add (juce::var (fileImpulseResponse.getFullPathName()));
  804. juce::var parameters[] = { juce::var (sourceParameter),
  805. juce::var (static_cast<int64> (size)),
  806. juce::var (wantsStereo),
  807. juce::var (wantsTrimming) };
  808. pimpl->addToFifo (types, parameters, 3);
  809. }
  810. void Convolution::copyAndLoadImpulseResponseFromBuffer (const AudioBuffer<float>& buffer,
  811. double bufferSampleRate, bool wantsStereo, bool wantsTrimming, size_t size)
  812. {
  813. jassert (bufferSampleRate > 0);
  814. if (buffer.getNumSamples() == 0)
  815. return;
  816. pimpl->copyBufferToTemporaryLocation (buffer);
  817. Pimpl::ChangeRequest types[] = { Pimpl::ChangeRequest::changeSource,
  818. Pimpl::ChangeRequest::changeImpulseResponseSize,
  819. Pimpl::ChangeRequest::changeStereo,
  820. Pimpl::ChangeRequest::changeTrimming };
  821. Array<juce::var> sourceParameter;
  822. sourceParameter.add (juce::var ((int) ConvolutionEngine::ProcessingInformation::SourceType::sourceAudioBuffer));
  823. sourceParameter.add (juce::var (bufferSampleRate));
  824. juce::var parameters[] = { juce::var (sourceParameter),
  825. juce::var (static_cast<int64> (size)),
  826. juce::var (wantsStereo),
  827. juce::var (wantsTrimming) };
  828. pimpl->addToFifo (types, parameters, 3);
  829. }
  830. void Convolution::prepare (const ProcessSpec& spec)
  831. {
  832. jassert (isPositiveAndBelow (spec.numChannels, static_cast<uint32> (3))); // only mono and stereo is supported
  833. Pimpl::ChangeRequest types[] = { Pimpl::ChangeRequest::changeSampleRate,
  834. Pimpl::ChangeRequest::changeMaximumBufferSize };
  835. juce::var parameters[] = { juce::var (spec.sampleRate),
  836. juce::var (static_cast<int> (spec.maximumBlockSize)) };
  837. pimpl->addToFifo (types, parameters, 2);
  838. for (size_t channel = 0; channel < spec.numChannels; ++channel)
  839. {
  840. volumeDry[channel].reset (spec.sampleRate, 0.05);
  841. volumeWet[channel].reset (spec.sampleRate, 0.05);
  842. }
  843. sampleRate = spec.sampleRate;
  844. dryBuffer = AudioBlock<float> (dryBufferStorage,
  845. jmin (spec.numChannels, 2u),
  846. spec.maximumBlockSize);
  847. }
  848. void Convolution::reset() noexcept
  849. {
  850. dryBuffer.clear();
  851. pimpl->reset();
  852. }
  853. void Convolution::processSamples (const AudioBlock<float>& input, AudioBlock<float>& output, bool isBypassed) noexcept
  854. {
  855. jassert (input.getNumChannels() == output.getNumChannels());
  856. jassert (isPositiveAndBelow (input.getNumChannels(), static_cast<size_t> (3))); // only mono and stereo is supported
  857. auto numChannels = input.getNumChannels();
  858. auto numSamples = jmin (input.getNumSamples(), output.getNumSamples());
  859. auto dry = dryBuffer.getSubsetChannelBlock (0, numChannels);
  860. if (volumeDry[0].isSmoothing())
  861. {
  862. dry.copy (input);
  863. for (size_t channel = 0; channel < numChannels; ++channel)
  864. volumeDry[channel].applyGain (dry.getChannelPointer (channel), (int) numSamples);
  865. pimpl->processSamples (input, output);
  866. for (size_t channel = 0; channel < numChannels; ++channel)
  867. volumeWet[channel].applyGain (output.getChannelPointer (channel), (int) numSamples);
  868. output += dry;
  869. }
  870. else
  871. {
  872. if (! currentIsBypassed)
  873. pimpl->processSamples (input, output);
  874. if (isBypassed != currentIsBypassed)
  875. {
  876. currentIsBypassed = isBypassed;
  877. for (size_t channel = 0; channel < numChannels; ++channel)
  878. {
  879. volumeDry[channel].setValue (isBypassed ? 0.0f : 1.0f);
  880. volumeDry[channel].reset (sampleRate, 0.05);
  881. volumeDry[channel].setValue (isBypassed ? 1.0f : 0.0f);
  882. volumeWet[channel].setValue (isBypassed ? 1.0f : 0.0f);
  883. volumeWet[channel].reset (sampleRate, 0.05);
  884. volumeWet[channel].setValue (isBypassed ? 0.0f : 1.0f);
  885. }
  886. }
  887. }
  888. }
  889. } // namespace dsp
  890. } // namespace juce