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.

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