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.

1253 lines
48KB

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