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.

851 lines
29KB

  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. struct FFT::Instance
  24. {
  25. virtual ~Instance() {}
  26. virtual void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept = 0;
  27. virtual void performRealOnlyForwardTransform (float*, bool) const noexcept = 0;
  28. virtual void performRealOnlyInverseTransform (float*) const noexcept = 0;
  29. };
  30. struct FFT::Engine
  31. {
  32. Engine (int priorityToUse) : enginePriority (priorityToUse)
  33. {
  34. auto& list = getEngines();
  35. list.add (this);
  36. std::sort (list.begin(), list.end(), [] (Engine* a, Engine* b) { return b->enginePriority < a->enginePriority; });
  37. }
  38. virtual ~Engine() {}
  39. virtual FFT::Instance* create (int order) const = 0;
  40. //==============================================================================
  41. static FFT::Instance* createBestEngineForPlatform (int order)
  42. {
  43. for (auto* engine : getEngines())
  44. if (auto* instance = engine->create (order))
  45. return instance;
  46. jassertfalse; // This should never happen as the fallback engine should always work!
  47. return nullptr;
  48. }
  49. private:
  50. static Array<Engine*>& getEngines()
  51. {
  52. static Array<Engine*> engines;
  53. return engines;
  54. }
  55. int enginePriority; // used so that faster engines have priority over slower ones
  56. };
  57. template <typename InstanceToUse>
  58. struct FFT::EngineImpl : public FFT::Engine
  59. {
  60. EngineImpl() : FFT::Engine (InstanceToUse::priority) {}
  61. FFT::Instance* create (int order) const override { return InstanceToUse::create (order); }
  62. };
  63. //==============================================================================
  64. //==============================================================================
  65. struct FFTFallback : public FFT::Instance
  66. {
  67. // this should have the least priority of all engines
  68. static constexpr int priority = -1;
  69. static FFTFallback* create (int order)
  70. {
  71. return new FFTFallback (order);
  72. }
  73. FFTFallback (int order)
  74. {
  75. configForward.reset (new FFTConfig (1 << order, false));
  76. configInverse.reset (new FFTConfig (1 << order, true));
  77. size = 1 << order;
  78. }
  79. void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
  80. {
  81. if (size == 1)
  82. {
  83. *output = *input;
  84. return;
  85. }
  86. const SpinLock::ScopedLockType sl(processLock);
  87. jassert (configForward != nullptr);
  88. if (inverse)
  89. {
  90. configInverse->perform (input, output);
  91. const float scaleFactor = 1.0f / size;
  92. for (int i = 0; i < size; ++i)
  93. output[i] *= scaleFactor;
  94. }
  95. else
  96. {
  97. configForward->perform (input, output);
  98. }
  99. }
  100. const size_t maxFFTScratchSpaceToAlloca = 256 * 1024;
  101. void performRealOnlyForwardTransform (float* d, bool) const noexcept override
  102. {
  103. if (size == 1)
  104. return;
  105. const size_t scratchSize = 16 + sizeof (Complex<float>) * (size_t) size;
  106. if (scratchSize < maxFFTScratchSpaceToAlloca)
  107. {
  108. performRealOnlyForwardTransform (static_cast<Complex<float>*> (alloca (scratchSize)), d);
  109. }
  110. else
  111. {
  112. HeapBlock<char> heapSpace (scratchSize);
  113. performRealOnlyForwardTransform (reinterpret_cast<Complex<float>*> (heapSpace.getData()), d);
  114. }
  115. }
  116. void performRealOnlyInverseTransform (float* d) const noexcept override
  117. {
  118. if (size == 1)
  119. return;
  120. const size_t scratchSize = 16 + sizeof (Complex<float>) * (size_t) size;
  121. if (scratchSize < maxFFTScratchSpaceToAlloca)
  122. {
  123. performRealOnlyInverseTransform (static_cast<Complex<float>*> (alloca (scratchSize)), d);
  124. }
  125. else
  126. {
  127. HeapBlock<char> heapSpace (scratchSize);
  128. performRealOnlyInverseTransform (reinterpret_cast<Complex<float>*> (heapSpace.getData()), d);
  129. }
  130. }
  131. void performRealOnlyForwardTransform (Complex<float>* scratch, float* d) const noexcept
  132. {
  133. for (int i = 0; i < size; ++i)
  134. scratch[i] = { d[i], 0 };
  135. perform (scratch, reinterpret_cast<Complex<float>*> (d), false);
  136. }
  137. void performRealOnlyInverseTransform (Complex<float>* scratch, float* d) const noexcept
  138. {
  139. auto* input = reinterpret_cast<Complex<float>*> (d);
  140. for (auto i = size >> 1; i < size; ++i)
  141. input[i] = std::conj (input[size - i]);
  142. perform (input, scratch, true);
  143. for (int i = 0; i < size; ++i)
  144. {
  145. d[i] = scratch[i].real();
  146. d[i + size] = scratch[i].imag();
  147. }
  148. }
  149. //==============================================================================
  150. struct FFTConfig
  151. {
  152. FFTConfig (int sizeOfFFT, bool isInverse)
  153. : fftSize (sizeOfFFT), inverse (isInverse), twiddleTable ((size_t) sizeOfFFT)
  154. {
  155. auto inverseFactor = (inverse ? 2.0 : -2.0) * MathConstants<double>::pi / (double) fftSize;
  156. if (fftSize <= 4)
  157. {
  158. for (int i = 0; i < fftSize; ++i)
  159. {
  160. auto phase = i * inverseFactor;
  161. twiddleTable[i] = { (float) std::cos (phase),
  162. (float) std::sin (phase) };
  163. }
  164. }
  165. else
  166. {
  167. for (int i = 0; i < fftSize / 4; ++i)
  168. {
  169. auto phase = i * inverseFactor;
  170. twiddleTable[i] = { (float) std::cos (phase),
  171. (float) std::sin (phase) };
  172. }
  173. for (int i = fftSize / 4; i < fftSize / 2; ++i)
  174. {
  175. auto other = twiddleTable[i - fftSize / 4];
  176. twiddleTable[i] = { inverse ? -other.imag() : other.imag(),
  177. inverse ? other.real() : -other.real() };
  178. }
  179. twiddleTable[fftSize / 2].real (-1.0f);
  180. twiddleTable[fftSize / 2].imag (0.0f);
  181. for (int i = fftSize / 2; i < fftSize; ++i)
  182. {
  183. auto index = fftSize / 2 - (i - fftSize / 2);
  184. twiddleTable[i] = conj(twiddleTable[index]);
  185. }
  186. }
  187. auto root = (int) std::sqrt ((double) fftSize);
  188. int divisor = 4, n = fftSize;
  189. for (int i = 0; i < numElementsInArray (factors); ++i)
  190. {
  191. while ((n % divisor) != 0)
  192. {
  193. if (divisor == 2) divisor = 3;
  194. else if (divisor == 4) divisor = 2;
  195. else divisor += 2;
  196. if (divisor > root)
  197. divisor = n;
  198. }
  199. n /= divisor;
  200. jassert (divisor == 1 || divisor == 2 || divisor == 4);
  201. factors[i].radix = divisor;
  202. factors[i].length = n;
  203. }
  204. }
  205. void perform (const Complex<float>* input, Complex<float>* output) const noexcept
  206. {
  207. perform (input, output, 1, 1, factors);
  208. }
  209. const int fftSize;
  210. const bool inverse;
  211. struct Factor { int radix, length; };
  212. Factor factors[32];
  213. HeapBlock<Complex<float>> twiddleTable;
  214. void perform (const Complex<float>* input, Complex<float>* output, int stride, int strideIn, const Factor* facs) const noexcept
  215. {
  216. auto factor = *facs++;
  217. auto* originalOutput = output;
  218. auto* outputEnd = output + factor.radix * factor.length;
  219. if (stride == 1 && factor.radix <= 5)
  220. {
  221. for (int i = 0; i < factor.radix; ++i)
  222. perform (input + stride * strideIn * i, output + i * factor.length, stride * factor.radix, strideIn, facs);
  223. butterfly (factor, output, stride);
  224. return;
  225. }
  226. if (factor.length == 1)
  227. {
  228. do
  229. {
  230. *output++ = *input;
  231. input += stride * strideIn;
  232. }
  233. while (output < outputEnd);
  234. }
  235. else
  236. {
  237. do
  238. {
  239. perform (input, output, stride * factor.radix, strideIn, facs);
  240. input += stride * strideIn;
  241. output += factor.length;
  242. }
  243. while (output < outputEnd);
  244. }
  245. butterfly (factor, originalOutput, stride);
  246. }
  247. void butterfly (const Factor factor, Complex<float>* data, int stride) const noexcept
  248. {
  249. switch (factor.radix)
  250. {
  251. case 1: break;
  252. case 2: butterfly2 (data, stride, factor.length); return;
  253. case 4: butterfly4 (data, stride, factor.length); return;
  254. default: jassertfalse; break;
  255. }
  256. auto* scratch = static_cast<Complex<float>*> (alloca (sizeof (Complex<float>) * (size_t) factor.radix));
  257. for (int i = 0; i < factor.length; ++i)
  258. {
  259. for (int k = i, q1 = 0; q1 < factor.radix; ++q1)
  260. {
  261. scratch[q1] = data[k];
  262. k += factor.length;
  263. }
  264. for (int k = i, q1 = 0; q1 < factor.radix; ++q1)
  265. {
  266. int twiddleIndex = 0;
  267. data[k] = scratch[0];
  268. for (int q = 1; q < factor.radix; ++q)
  269. {
  270. twiddleIndex += stride * k;
  271. if (twiddleIndex >= fftSize)
  272. twiddleIndex -= fftSize;
  273. data[k] += scratch[q] * twiddleTable[twiddleIndex];
  274. }
  275. k += factor.length;
  276. }
  277. }
  278. }
  279. void butterfly2 (Complex<float>* data, const int stride, const int length) const noexcept
  280. {
  281. auto* dataEnd = data + length;
  282. auto* tw = twiddleTable.getData();
  283. for (int i = length; --i >= 0;)
  284. {
  285. auto s = *dataEnd;
  286. s *= (*tw);
  287. tw += stride;
  288. *dataEnd++ = *data - s;
  289. *data++ += s;
  290. }
  291. }
  292. void butterfly4 (Complex<float>* data, const int stride, const int length) const noexcept
  293. {
  294. auto lengthX2 = length * 2;
  295. auto lengthX3 = length * 3;
  296. auto strideX2 = stride * 2;
  297. auto strideX3 = stride * 3;
  298. auto* twiddle1 = twiddleTable.getData();
  299. auto* twiddle2 = twiddle1;
  300. auto* twiddle3 = twiddle1;
  301. for (int i = length; --i >= 0;)
  302. {
  303. auto s0 = data[length] * *twiddle1;
  304. auto s1 = data[lengthX2] * *twiddle2;
  305. auto s2 = data[lengthX3] * *twiddle3;
  306. auto s3 = s0; s3 += s2;
  307. auto s4 = s0; s4 -= s2;
  308. auto s5 = *data; s5 -= s1;
  309. *data += s1;
  310. data[lengthX2] = *data;
  311. data[lengthX2] -= s3;
  312. twiddle1 += stride;
  313. twiddle2 += strideX2;
  314. twiddle3 += strideX3;
  315. *data += s3;
  316. if (inverse)
  317. {
  318. data[length] = { s5.real() - s4.imag(),
  319. s5.imag() + s4.real() };
  320. data[lengthX3] = { s5.real() + s4.imag(),
  321. s5.imag() - s4.real() };
  322. }
  323. else
  324. {
  325. data[length] = { s5.real() + s4.imag(),
  326. s5.imag() - s4.real() };
  327. data[lengthX3] = { s5.real() - s4.imag(),
  328. s5.imag() + s4.real() };
  329. }
  330. ++data;
  331. }
  332. }
  333. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (FFTConfig)
  334. };
  335. //==============================================================================
  336. SpinLock processLock;
  337. std::unique_ptr<FFTConfig> configForward, configInverse;
  338. int size;
  339. };
  340. FFT::EngineImpl<FFTFallback> fftFallback;
  341. //==============================================================================
  342. //==============================================================================
  343. #if (JUCE_MAC || JUCE_IOS) && JUCE_USE_VDSP_FRAMEWORK
  344. struct AppleFFT : public FFT::Instance
  345. {
  346. static constexpr int priority = 5;
  347. static AppleFFT* create (int order)
  348. {
  349. return new AppleFFT (order);
  350. }
  351. AppleFFT (int orderToUse)
  352. : order (static_cast<vDSP_Length> (orderToUse)),
  353. fftSetup (vDSP_create_fftsetup (order, 2)),
  354. forwardNormalisation (0.5f),
  355. inverseNormalisation (1.0f / static_cast<float> (1 << order))
  356. {}
  357. ~AppleFFT() override
  358. {
  359. if (fftSetup != nullptr)
  360. {
  361. vDSP_destroy_fftsetup (fftSetup);
  362. fftSetup = nullptr;
  363. }
  364. }
  365. void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
  366. {
  367. auto size = (1 << order);
  368. DSPSplitComplex splitInput (toSplitComplex (const_cast<Complex<float>*> (input)));
  369. DSPSplitComplex splitOutput (toSplitComplex (output));
  370. vDSP_fft_zop (fftSetup, &splitInput, 2, &splitOutput, 2,
  371. order, inverse ? kFFTDirection_Inverse : kFFTDirection_Forward);
  372. float factor = (inverse ? inverseNormalisation : forwardNormalisation * 2.0f);
  373. vDSP_vsmul ((float*) output, 1, &factor, (float*) output, 1, static_cast<size_t> (size << 1));
  374. }
  375. void performRealOnlyForwardTransform (float* inoutData, bool ignoreNegativeFreqs) const noexcept override
  376. {
  377. auto size = (1 << order);
  378. auto* inout = reinterpret_cast<Complex<float>*> (inoutData);
  379. auto splitInOut (toSplitComplex (inout));
  380. inoutData[size] = 0.0f;
  381. vDSP_fft_zrip (fftSetup, &splitInOut, 2, order, kFFTDirection_Forward);
  382. vDSP_vsmul (inoutData, 1, &forwardNormalisation, inoutData, 1, static_cast<size_t> (size << 1));
  383. mirrorResult (inout, ignoreNegativeFreqs);
  384. }
  385. void performRealOnlyInverseTransform (float* inoutData) const noexcept override
  386. {
  387. auto* inout = reinterpret_cast<Complex<float>*> (inoutData);
  388. auto size = (1 << order);
  389. auto splitInOut (toSplitComplex (inout));
  390. // Imaginary part of nyquist and DC frequencies are always zero
  391. // so Apple uses the imaginary part of the DC frequency to store
  392. // the real part of the nyquist frequency
  393. if (size != 1)
  394. inout[0] = Complex<float> (inout[0].real(), inout[size >> 1].real());
  395. vDSP_fft_zrip (fftSetup, &splitInOut, 2, order, kFFTDirection_Inverse);
  396. vDSP_vsmul (inoutData, 1, &inverseNormalisation, inoutData, 1, static_cast<size_t> (size << 1));
  397. vDSP_vclr (inoutData + size, 1, static_cast<size_t> (size));
  398. }
  399. private:
  400. //==============================================================================
  401. void mirrorResult (Complex<float>* out, bool ignoreNegativeFreqs) const noexcept
  402. {
  403. auto size = (1 << order);
  404. auto i = size >> 1;
  405. // Imaginary part of nyquist and DC frequencies are always zero
  406. // so Apple uses the imaginary part of the DC frequency to store
  407. // the real part of the nyquist frequency
  408. out[i++] = { out[0].imag(), 0.0 };
  409. out[0] = { out[0].real(), 0.0 };
  410. if (! ignoreNegativeFreqs)
  411. for (; i < size; ++i)
  412. out[i] = std::conj (out[size - i]);
  413. }
  414. static DSPSplitComplex toSplitComplex (Complex<float>* data) noexcept
  415. {
  416. // this assumes that Complex interleaves real and imaginary parts
  417. // and is tightly packed.
  418. return { reinterpret_cast<float*> (data),
  419. reinterpret_cast<float*> (data) + 1};
  420. }
  421. //==============================================================================
  422. vDSP_Length order;
  423. FFTSetup fftSetup;
  424. float forwardNormalisation, inverseNormalisation;
  425. };
  426. FFT::EngineImpl<AppleFFT> appleFFT;
  427. #endif
  428. //==============================================================================
  429. //==============================================================================
  430. #if JUCE_DSP_USE_SHARED_FFTW || JUCE_DSP_USE_STATIC_FFTW
  431. #if JUCE_DSP_USE_STATIC_FFTW
  432. extern "C"
  433. {
  434. void* fftwf_plan_dft_1d (int, void*, void*, int, int);
  435. void* fftwf_plan_dft_r2c_1d (int, void*, void*, int);
  436. void* fftwf_plan_dft_c2r_1d (int, void*, void*, int);
  437. void fftwf_destroy_plan (void*);
  438. void fftwf_execute_dft (void*, void*, void*);
  439. void fftwf_execute_dft_r2c (void*, void*, void*);
  440. void fftwf_execute_dft_c2r (void*, void*, void*);
  441. }
  442. #endif
  443. struct FFTWImpl : public FFT::Instance
  444. {
  445. #if JUCE_DSP_USE_STATIC_FFTW
  446. // if the JUCE developer has gone through the hassle of statically
  447. // linking in fftw, they probably want to use it
  448. static constexpr int priority = 10;
  449. #else
  450. static constexpr int priority = 3;
  451. #endif
  452. struct FFTWPlan;
  453. using FFTWPlanRef = FFTWPlan*;
  454. enum
  455. {
  456. measure = 0,
  457. unaligned = (1 << 1),
  458. estimate = (1 << 6)
  459. };
  460. struct Symbols
  461. {
  462. FFTWPlanRef (*plan_dft_fftw) (unsigned, Complex<float>*, Complex<float>*, int, unsigned);
  463. FFTWPlanRef (*plan_r2c_fftw) (unsigned, float*, Complex<float>*, unsigned);
  464. FFTWPlanRef (*plan_c2r_fftw) (unsigned, Complex<float>*, float*, unsigned);
  465. void (*destroy_fftw) (FFTWPlanRef);
  466. void (*execute_dft_fftw) (FFTWPlanRef, const Complex<float>*, Complex<float>*);
  467. void (*execute_r2c_fftw) (FFTWPlanRef, float*, Complex<float>*);
  468. void (*execute_c2r_fftw) (FFTWPlanRef, Complex<float>*, float*);
  469. #if JUCE_DSP_USE_STATIC_FFTW
  470. template <typename FuncPtr, typename ActualSymbolType>
  471. static bool symbol (FuncPtr& dst, ActualSymbolType sym)
  472. {
  473. dst = reinterpret_cast<FuncPtr> (sym);
  474. return true;
  475. }
  476. #else
  477. template <typename FuncPtr>
  478. static bool symbol (DynamicLibrary& lib, FuncPtr& dst, const char* name)
  479. {
  480. dst = reinterpret_cast<FuncPtr> (lib.getFunction (name));
  481. return (dst != nullptr);
  482. }
  483. #endif
  484. };
  485. static FFTWImpl* create (int order)
  486. {
  487. DynamicLibrary lib;
  488. #if ! JUCE_DSP_USE_STATIC_FFTW
  489. #if JUCE_MAC
  490. auto libName = "libfftw3f.dylib";
  491. #elif JUCE_WINDOWS
  492. auto libName = "libfftw3f.dll";
  493. #else
  494. auto libName = "libfftw3f.so";
  495. #endif
  496. if (lib.open (libName))
  497. #endif
  498. {
  499. Symbols symbols;
  500. #if JUCE_DSP_USE_STATIC_FFTW
  501. if (! Symbols::symbol (symbols.plan_dft_fftw, fftwf_plan_dft_1d)) return nullptr;
  502. if (! Symbols::symbol (symbols.plan_r2c_fftw, fftwf_plan_dft_r2c_1d)) return nullptr;
  503. if (! Symbols::symbol (symbols.plan_c2r_fftw, fftwf_plan_dft_c2r_1d)) return nullptr;
  504. if (! Symbols::symbol (symbols.destroy_fftw, fftwf_destroy_plan)) return nullptr;
  505. if (! Symbols::symbol (symbols.execute_dft_fftw, fftwf_execute_dft)) return nullptr;
  506. if (! Symbols::symbol (symbols.execute_r2c_fftw, fftwf_execute_dft_r2c)) return nullptr;
  507. if (! Symbols::symbol (symbols.execute_c2r_fftw, fftwf_execute_dft_c2r)) return nullptr;
  508. #else
  509. if (! Symbols::symbol (lib, symbols.plan_dft_fftw, "fftwf_plan_dft_1d")) return nullptr;
  510. if (! Symbols::symbol (lib, symbols.plan_r2c_fftw, "fftwf_plan_dft_r2c_1d")) return nullptr;
  511. if (! Symbols::symbol (lib, symbols.plan_c2r_fftw, "fftwf_plan_dft_c2r_1d")) return nullptr;
  512. if (! Symbols::symbol (lib, symbols.destroy_fftw, "fftwf_destroy_plan")) return nullptr;
  513. if (! Symbols::symbol (lib, symbols.execute_dft_fftw, "fftwf_execute_dft")) return nullptr;
  514. if (! Symbols::symbol (lib, symbols.execute_r2c_fftw, "fftwf_execute_dft_r2c")) return nullptr;
  515. if (! Symbols::symbol (lib, symbols.execute_c2r_fftw, "fftwf_execute_dft_c2r")) return nullptr;
  516. #endif
  517. return new FFTWImpl (static_cast<size_t> (order), std::move (lib), symbols);
  518. }
  519. return nullptr;
  520. }
  521. FFTWImpl (size_t orderToUse, DynamicLibrary&& libraryToUse, const Symbols& symbols)
  522. : fftwLibrary (std::move (libraryToUse)), fftw (symbols), order (static_cast<size_t> (orderToUse))
  523. {
  524. ScopedLock lock (getFFTWPlanLock());
  525. auto n = (1u << order);
  526. HeapBlock<Complex<float>> in (n), out (n);
  527. c2cForward = fftw.plan_dft_fftw (n, in.getData(), out.getData(), -1, unaligned | estimate);
  528. c2cInverse = fftw.plan_dft_fftw (n, in.getData(), out.getData(), +1, unaligned | estimate);
  529. r2c = fftw.plan_r2c_fftw (n, (float*) in.getData(), in.getData(), unaligned | estimate);
  530. c2r = fftw.plan_c2r_fftw (n, in.getData(), (float*) in.getData(), unaligned | estimate);
  531. }
  532. ~FFTWImpl() override
  533. {
  534. ScopedLock lock (getFFTWPlanLock());
  535. fftw.destroy_fftw (c2cForward);
  536. fftw.destroy_fftw (c2cInverse);
  537. fftw.destroy_fftw (r2c);
  538. fftw.destroy_fftw (c2r);
  539. }
  540. void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
  541. {
  542. if (inverse)
  543. {
  544. auto n = (1u << order);
  545. fftw.execute_dft_fftw (c2cInverse, input, output);
  546. FloatVectorOperations::multiply ((float*) output, 1.0f / static_cast<float> (n), (int) n << 1);
  547. }
  548. else
  549. {
  550. fftw.execute_dft_fftw (c2cForward, input, output);
  551. }
  552. }
  553. void performRealOnlyForwardTransform (float* inputOutputData, bool ignoreNegativeFreqs) const noexcept override
  554. {
  555. if (order == 0)
  556. return;
  557. auto* out = reinterpret_cast<Complex<float>*> (inputOutputData);
  558. fftw.execute_r2c_fftw (r2c, inputOutputData, out);
  559. auto size = (1 << order);
  560. if (! ignoreNegativeFreqs)
  561. for (auto i = size >> 1; i < size; ++i)
  562. out[i] = std::conj (out[size - i]);
  563. }
  564. void performRealOnlyInverseTransform (float* inputOutputData) const noexcept override
  565. {
  566. auto n = (1u << order);
  567. fftw.execute_c2r_fftw (c2r, (Complex<float>*) inputOutputData, inputOutputData);
  568. FloatVectorOperations::multiply ((float*) inputOutputData, 1.0f / static_cast<float> (n), (int) n);
  569. }
  570. //==============================================================================
  571. // fftw's plan_* and destroy_* methods are NOT thread safe. So we need to share
  572. // a lock between all instances of FFTWImpl
  573. static CriticalSection& getFFTWPlanLock() noexcept
  574. {
  575. static CriticalSection cs;
  576. return cs;
  577. }
  578. //==============================================================================
  579. DynamicLibrary fftwLibrary;
  580. Symbols fftw;
  581. size_t order;
  582. FFTWPlanRef c2cForward, c2cInverse, r2c, c2r;
  583. };
  584. FFT::EngineImpl<FFTWImpl> fftwEngine;
  585. #endif
  586. //==============================================================================
  587. //==============================================================================
  588. #if JUCE_DSP_USE_INTEL_MKL
  589. struct IntelFFT : public FFT::Instance
  590. {
  591. static constexpr int priority = 8;
  592. static bool succeeded (MKL_LONG status) noexcept { return status == 0; }
  593. static IntelFFT* create (int orderToUse)
  594. {
  595. DFTI_DESCRIPTOR_HANDLE mklc2c, mklc2r;
  596. if (DftiCreateDescriptor (&mklc2c, DFTI_SINGLE, DFTI_COMPLEX, 1, 1 << orderToUse) == 0)
  597. {
  598. if (succeeded (DftiSetValue (mklc2c, DFTI_PLACEMENT, DFTI_NOT_INPLACE))
  599. && succeeded (DftiSetValue (mklc2c, DFTI_BACKWARD_SCALE, 1.0f / static_cast<float> (1 << orderToUse)))
  600. && succeeded (DftiCommitDescriptor (mklc2c)))
  601. {
  602. if (succeeded (DftiCreateDescriptor (&mklc2r, DFTI_SINGLE, DFTI_REAL, 1, 1 << orderToUse)))
  603. {
  604. if (succeeded (DftiSetValue (mklc2r, DFTI_PLACEMENT, DFTI_INPLACE))
  605. && succeeded (DftiSetValue (mklc2r, DFTI_BACKWARD_SCALE, 1.0f / static_cast<float> (1 << orderToUse)))
  606. && succeeded (DftiCommitDescriptor (mklc2r)))
  607. {
  608. return new IntelFFT (static_cast<size_t> (orderToUse), mklc2c, mklc2r);
  609. }
  610. DftiFreeDescriptor (&mklc2r);
  611. }
  612. }
  613. DftiFreeDescriptor (&mklc2c);
  614. }
  615. return {};
  616. }
  617. IntelFFT (size_t orderToUse, DFTI_DESCRIPTOR_HANDLE c2cToUse, DFTI_DESCRIPTOR_HANDLE cr2ToUse)
  618. : order (orderToUse), c2c (c2cToUse), c2r (cr2ToUse)
  619. {}
  620. ~IntelFFT()
  621. {
  622. DftiFreeDescriptor (&c2c);
  623. DftiFreeDescriptor (&c2r);
  624. }
  625. void perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept override
  626. {
  627. if (inverse)
  628. DftiComputeBackward (c2c, (void*) input, output);
  629. else
  630. DftiComputeForward (c2c, (void*) input, output);
  631. }
  632. void performRealOnlyForwardTransform (float* inputOutputData, bool ignoreNegativeFreqs) const noexcept override
  633. {
  634. if (order == 0)
  635. return;
  636. DftiComputeForward (c2r, inputOutputData);
  637. auto* out = reinterpret_cast<Complex<float>*> (inputOutputData);
  638. auto size = (1 << order);
  639. if (! ignoreNegativeFreqs)
  640. for (auto i = size >> 1; i < size; ++i)
  641. out[i] = std::conj (out[size - i]);
  642. }
  643. void performRealOnlyInverseTransform (float* inputOutputData) const noexcept override
  644. {
  645. DftiComputeBackward (c2r, inputOutputData);
  646. }
  647. size_t order;
  648. DFTI_DESCRIPTOR_HANDLE c2c, c2r;
  649. };
  650. FFT::EngineImpl<IntelFFT> fftwEngine;
  651. #endif
  652. //==============================================================================
  653. //==============================================================================
  654. FFT::FFT (int order)
  655. : engine (FFT::Engine::createBestEngineForPlatform (order)),
  656. size (1 << order)
  657. {
  658. }
  659. FFT::~FFT() {}
  660. void FFT::perform (const Complex<float>* input, Complex<float>* output, bool inverse) const noexcept
  661. {
  662. if (engine != nullptr)
  663. engine->perform (input, output, inverse);
  664. }
  665. void FFT::performRealOnlyForwardTransform (float* inputOutputData, bool ignoreNeagtiveFreqs) const noexcept
  666. {
  667. if (engine != nullptr)
  668. engine->performRealOnlyForwardTransform (inputOutputData, ignoreNeagtiveFreqs);
  669. }
  670. void FFT::performRealOnlyInverseTransform (float* inputOutputData) const noexcept
  671. {
  672. if (engine != nullptr)
  673. engine->performRealOnlyInverseTransform (inputOutputData);
  674. }
  675. void FFT::performFrequencyOnlyForwardTransform (float* inputOutputData) const noexcept
  676. {
  677. if (size == 1)
  678. return;
  679. performRealOnlyForwardTransform (inputOutputData);
  680. auto* out = reinterpret_cast<Complex<float>*> (inputOutputData);
  681. for (auto i = 0; i < size; ++i)
  682. inputOutputData[i] = std::abs (out[i]);
  683. zeromem (&inputOutputData[size], sizeof (float) * static_cast<size_t> (size));
  684. }
  685. } // namespace dsp
  686. } // namespace juce