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.

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