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.

1239 lines
47KB

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