SaProcessor.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572
  1. /* SaProcessor.cpp - implementation of SaProcessor class.
  2. *
  3. * Copyright (c) 2019 Martin Pavelek <he29/dot/HS/at/gmail/dot/com>
  4. *
  5. * Based partially on Eq plugin code,
  6. * Copyright (c) 2014-2017, David French <dave/dot/french3/at/googlemail/dot/com>
  7. *
  8. * This file is part of LMMS - https://lmms.io
  9. * This program is free software; you can redistribute it and/or
  10. * modify it under the terms of the GNU General Public
  11. * License as published by the Free Software Foundation; either
  12. * version 2 of the License, or (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  17. * General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public
  20. * License along with this program (see COPYING); if not, write to the
  21. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  22. * Boston, MA 02110-1301 USA.
  23. *
  24. */
  25. #include "SaProcessor.h"
  26. #include <algorithm>
  27. #include <cmath>
  28. #include <iostream>
  29. #include <QMutexLocker>
  30. #include "lmms_math.h"
  31. SaProcessor::SaProcessor(SaControls *controls) :
  32. m_controls(controls),
  33. m_inBlockSize(FFT_BLOCK_SIZES[0]),
  34. m_fftBlockSize(FFT_BLOCK_SIZES[0]),
  35. m_sampleRate(Engine::mixer()->processingSampleRate()),
  36. m_framesFilledUp(0),
  37. m_spectrumActive(false),
  38. m_waterfallActive(false),
  39. m_waterfallNotEmpty(0),
  40. m_reallocating(false)
  41. {
  42. m_fftWindow.resize(m_inBlockSize, 1.0);
  43. precomputeWindow(m_fftWindow.data(), m_inBlockSize, BLACKMAN_HARRIS);
  44. m_bufferL.resize(m_fftBlockSize, 0);
  45. m_bufferR.resize(m_fftBlockSize, 0);
  46. m_spectrumL = (fftwf_complex *) fftwf_malloc(binCount() * sizeof (fftwf_complex));
  47. m_spectrumR = (fftwf_complex *) fftwf_malloc(binCount() * sizeof (fftwf_complex));
  48. m_fftPlanL = fftwf_plan_dft_r2c_1d(m_fftBlockSize, m_bufferL.data(), m_spectrumL, FFTW_MEASURE);
  49. m_fftPlanR = fftwf_plan_dft_r2c_1d(m_fftBlockSize, m_bufferR.data(), m_spectrumR, FFTW_MEASURE);
  50. m_absSpectrumL.resize(binCount(), 0);
  51. m_absSpectrumR.resize(binCount(), 0);
  52. m_normSpectrumL.resize(binCount(), 0);
  53. m_normSpectrumR.resize(binCount(), 0);
  54. m_history.resize(binCount() * m_waterfallHeight * sizeof qRgb(0,0,0), 0);
  55. clear();
  56. }
  57. SaProcessor::~SaProcessor()
  58. {
  59. if (m_fftPlanL != NULL) {fftwf_destroy_plan(m_fftPlanL);}
  60. if (m_fftPlanR != NULL) {fftwf_destroy_plan(m_fftPlanR);}
  61. if (m_spectrumL != NULL) {fftwf_free(m_spectrumL);}
  62. if (m_spectrumR != NULL) {fftwf_free(m_spectrumR);}
  63. m_fftPlanL = NULL;
  64. m_fftPlanR = NULL;
  65. m_spectrumL = NULL;
  66. m_spectrumR = NULL;
  67. }
  68. // Load a batch of data from LMMS; run FFT analysis if buffer is full enough.
  69. void SaProcessor::analyse(sampleFrame *in_buffer, const fpp_t frame_count)
  70. {
  71. #ifdef SA_DEBUG
  72. int start_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
  73. #endif
  74. // only take in data if any view is visible and not paused
  75. if ((m_spectrumActive || m_waterfallActive) && !m_controls->m_pauseModel.value())
  76. {
  77. const bool stereo = m_controls->m_stereoModel.value();
  78. fpp_t in_frame = 0;
  79. while (in_frame < frame_count)
  80. {
  81. // fill sample buffers and check for zero input
  82. bool block_empty = true;
  83. for (; in_frame < frame_count && m_framesFilledUp < m_inBlockSize; in_frame++, m_framesFilledUp++)
  84. {
  85. if (stereo)
  86. {
  87. m_bufferL[m_framesFilledUp] = in_buffer[in_frame][0];
  88. m_bufferR[m_framesFilledUp] = in_buffer[in_frame][1];
  89. }
  90. else
  91. {
  92. m_bufferL[m_framesFilledUp] =
  93. m_bufferR[m_framesFilledUp] = (in_buffer[in_frame][0] + in_buffer[in_frame][1]) * 0.5f;
  94. }
  95. if (in_buffer[in_frame][0] != 0.f || in_buffer[in_frame][1] != 0.f)
  96. {
  97. block_empty = false;
  98. }
  99. }
  100. // Run analysis only if buffers contain enough data.
  101. // Also, to prevent audio interruption and a momentary GUI freeze,
  102. // skip analysis if buffers are being reallocated.
  103. if (m_framesFilledUp < m_inBlockSize || m_reallocating) {return;}
  104. // update sample rate
  105. m_sampleRate = Engine::mixer()->processingSampleRate();
  106. // apply FFT window
  107. for (unsigned int i = 0; i < m_inBlockSize; i++)
  108. {
  109. m_bufferL[i] = m_bufferL[i] * m_fftWindow[i];
  110. m_bufferR[i] = m_bufferR[i] * m_fftWindow[i];
  111. }
  112. // lock data shared with SaSpectrumView and SaWaterfallView
  113. QMutexLocker lock(&m_dataAccess);
  114. // Run FFT on left channel, convert the result to absolute magnitude
  115. // spectrum and normalize it.
  116. fftwf_execute(m_fftPlanL);
  117. absspec(m_spectrumL, m_absSpectrumL.data(), binCount());
  118. normalize(m_absSpectrumL, m_normSpectrumL, m_inBlockSize);
  119. // repeat analysis for right channel if stereo processing is enabled
  120. if (stereo)
  121. {
  122. fftwf_execute(m_fftPlanR);
  123. absspec(m_spectrumR, m_absSpectrumR.data(), binCount());
  124. normalize(m_absSpectrumR, m_normSpectrumR, m_inBlockSize);
  125. }
  126. // count empty lines so that empty history does not have to update
  127. if (block_empty && m_waterfallNotEmpty)
  128. {
  129. m_waterfallNotEmpty -= 1;
  130. }
  131. else if (!block_empty)
  132. {
  133. m_waterfallNotEmpty = m_waterfallHeight + 2;
  134. }
  135. if (m_waterfallActive && m_waterfallNotEmpty)
  136. {
  137. // move waterfall history one line down and clear the top line
  138. QRgb *pixel = (QRgb *)m_history.data();
  139. std::copy(pixel,
  140. pixel + binCount() * m_waterfallHeight - binCount(),
  141. pixel + binCount());
  142. memset(pixel, 0, binCount() * sizeof (QRgb));
  143. // add newest result on top
  144. int target; // pixel being constructed
  145. float accL = 0; // accumulators for merging multiple bins
  146. float accR = 0;
  147. for (unsigned int i = 0; i < binCount(); i++)
  148. {
  149. // Every frequency bin spans a frequency range that must be
  150. // partially or fully mapped to a pixel. Any inconsistency
  151. // may be seen in the spectrogram as dark or white lines --
  152. // play white noise to confirm your change did not break it.
  153. float band_start = freqToXPixel(binToFreq(i) - binBandwidth() / 2.0, binCount());
  154. float band_end = freqToXPixel(binToFreq(i + 1) - binBandwidth() / 2.0, binCount());
  155. if (m_controls->m_logXModel.value())
  156. {
  157. // Logarithmic scale
  158. if (band_end - band_start > 1.0)
  159. {
  160. // band spans multiple pixels: draw all pixels it covers
  161. for (target = (int)band_start; target < (int)band_end; target++)
  162. {
  163. if (target >= 0 && target < binCount())
  164. {
  165. pixel[target] = makePixel(m_normSpectrumL[i], m_normSpectrumR[i]);
  166. }
  167. }
  168. // save remaining portion of the band for the following band / pixel
  169. // (in case the next band uses sub-pixel drawing)
  170. accL = (band_end - (int)band_end) * m_normSpectrumL[i];
  171. accR = (band_end - (int)band_end) * m_normSpectrumR[i];
  172. }
  173. else
  174. {
  175. // sub-pixel drawing; add contribution of current band
  176. target = (int)band_start;
  177. if ((int)band_start == (int)band_end)
  178. {
  179. // band ends within current target pixel, accumulate
  180. accL += (band_end - band_start) * m_normSpectrumL[i];
  181. accR += (band_end - band_start) * m_normSpectrumR[i];
  182. }
  183. else
  184. {
  185. // Band ends in the next pixel -- finalize the current pixel.
  186. // Make sure contribution is split correctly on pixel boundary.
  187. accL += ((int)band_end - band_start) * m_normSpectrumL[i];
  188. accR += ((int)band_end - band_start) * m_normSpectrumR[i];
  189. if (target >= 0 && target < binCount()) {pixel[target] = makePixel(accL, accR);}
  190. // save remaining portion of the band for the following band / pixel
  191. accL = (band_end - (int)band_end) * m_normSpectrumL[i];
  192. accR = (band_end - (int)band_end) * m_normSpectrumR[i];
  193. }
  194. }
  195. }
  196. else
  197. {
  198. // Linear: always draws one or more pixels per band
  199. for (target = (int)band_start; target < band_end; target++)
  200. {
  201. if (target >= 0 && target < binCount())
  202. {
  203. pixel[target] = makePixel(m_normSpectrumL[i], m_normSpectrumR[i]);
  204. }
  205. }
  206. }
  207. }
  208. }
  209. #ifdef SA_DEBUG
  210. // report FFT processing speed
  211. start_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - start_time;
  212. std::cout << "Processed " << m_framesFilledUp << " samples in " << start_time / 1000000.0 << " ms" << std::endl;
  213. #endif
  214. // clean up before checking for more data from input buffer
  215. m_framesFilledUp = 0;
  216. }
  217. }
  218. }
  219. // Produce a spectrogram pixel from normalized spectrum data.
  220. // Values over 1.0 will cause the color components to overflow: this is left
  221. // intentionally untreated as it clearly indicates which frequency is clipping.
  222. // Gamma correction is applied to make small values more visible and to make
  223. // a linear gradient actually appear roughly linear. The correction should be
  224. // around 0.42 to 0.45 for sRGB displays (or lower for bigger visibility boost).
  225. QRgb SaProcessor::makePixel(float left, float right, float gamma_correction) const
  226. {
  227. if (m_controls->m_stereoModel.value())
  228. {
  229. float ampL = pow(left, gamma_correction);
  230. float ampR = pow(right, gamma_correction);
  231. return qRgb(m_controls->m_colorL.red() * ampL + m_controls->m_colorR.red() * ampR,
  232. m_controls->m_colorL.green() * ampL + m_controls->m_colorR.green() * ampR,
  233. m_controls->m_colorL.blue() * ampL + m_controls->m_colorR.blue() * ampR);
  234. }
  235. else
  236. {
  237. float ampL = pow(left, gamma_correction);
  238. // make mono color brighter to compensate for the fact it is not summed
  239. return qRgb(m_controls->m_colorMono.lighter().red() * ampL,
  240. m_controls->m_colorMono.lighter().green() * ampL,
  241. m_controls->m_colorMono.lighter().blue() * ampL);
  242. }
  243. }
  244. // Inform the processor whether any display widgets actually need it.
  245. void SaProcessor::setSpectrumActive(bool active)
  246. {
  247. m_spectrumActive = active;
  248. }
  249. void SaProcessor::setWaterfallActive(bool active)
  250. {
  251. m_waterfallActive = active;
  252. }
  253. // Reallocate data buffers according to newly set block size.
  254. void SaProcessor::reallocateBuffers()
  255. {
  256. unsigned int new_size_index = m_controls->m_blockSizeModel.value();
  257. unsigned int new_in_size, new_fft_size;
  258. unsigned int new_bins;
  259. // get new block sizes and bin count based on selected index
  260. if (new_size_index < FFT_BLOCK_SIZES.size())
  261. {
  262. new_in_size = FFT_BLOCK_SIZES[new_size_index];
  263. }
  264. else
  265. {
  266. new_in_size = FFT_BLOCK_SIZES.back();
  267. }
  268. if (new_size_index + m_zeroPadFactor < FFT_BLOCK_SIZES.size())
  269. {
  270. new_fft_size = FFT_BLOCK_SIZES[new_size_index + m_zeroPadFactor];
  271. }
  272. else
  273. {
  274. new_fft_size = FFT_BLOCK_SIZES.back();
  275. }
  276. new_bins = new_fft_size / 2 +1;
  277. // Lock data shared with SaSpectrumView and SaWaterfallView.
  278. // The m_reallocating is here to tell analyse() to avoid asking for the
  279. // lock, since fftw3 can take a while to find the fastest FFT algorithm
  280. // for given machine, which would produce interruption in the audio stream.
  281. m_reallocating = true;
  282. QMutexLocker lock(&m_dataAccess);
  283. // destroy old FFT plan and free the result buffer
  284. if (m_fftPlanL != NULL) {fftwf_destroy_plan(m_fftPlanL);}
  285. if (m_fftPlanR != NULL) {fftwf_destroy_plan(m_fftPlanR);}
  286. if (m_spectrumL != NULL) {fftwf_free(m_spectrumL);}
  287. if (m_spectrumR != NULL) {fftwf_free(m_spectrumR);}
  288. // allocate new space, create new plan and resize containers
  289. m_fftWindow.resize(new_in_size, 1.0);
  290. precomputeWindow(m_fftWindow.data(), new_in_size, (FFT_WINDOWS) m_controls->m_windowModel.value());
  291. m_bufferL.resize(new_fft_size, 0);
  292. m_bufferR.resize(new_fft_size, 0);
  293. m_spectrumL = (fftwf_complex *) fftwf_malloc(new_bins * sizeof (fftwf_complex));
  294. m_spectrumR = (fftwf_complex *) fftwf_malloc(new_bins * sizeof (fftwf_complex));
  295. m_fftPlanL = fftwf_plan_dft_r2c_1d(new_fft_size, m_bufferL.data(), m_spectrumL, FFTW_MEASURE);
  296. m_fftPlanR = fftwf_plan_dft_r2c_1d(new_fft_size, m_bufferR.data(), m_spectrumR, FFTW_MEASURE);
  297. if (m_fftPlanL == NULL || m_fftPlanR == NULL)
  298. {
  299. std::cerr << "Failed to create new FFT plan!" << std::endl;
  300. }
  301. m_absSpectrumL.resize(new_bins, 0);
  302. m_absSpectrumR.resize(new_bins, 0);
  303. m_normSpectrumL.resize(new_bins, 0);
  304. m_normSpectrumR.resize(new_bins, 0);
  305. m_history.resize(new_bins * m_waterfallHeight * sizeof qRgb(0,0,0), 0);
  306. // done; publish new sizes and clean up
  307. m_inBlockSize = new_in_size;
  308. m_fftBlockSize = new_fft_size;
  309. lock.unlock();
  310. m_reallocating = false;
  311. clear();
  312. }
  313. // Precompute a new FFT window based on currently selected type.
  314. void SaProcessor::rebuildWindow()
  315. {
  316. // computation is done in fft_helpers
  317. QMutexLocker lock(&m_dataAccess);
  318. precomputeWindow(m_fftWindow.data(), m_inBlockSize, (FFT_WINDOWS) m_controls->m_windowModel.value());
  319. }
  320. // Clear all data buffers and replace contents with zeros.
  321. // Note: may take a few milliseconds, do not call in a loop!
  322. void SaProcessor::clear()
  323. {
  324. QMutexLocker lock(&m_dataAccess);
  325. m_framesFilledUp = 0;
  326. std::fill(m_bufferL.begin(), m_bufferL.end(), 0);
  327. std::fill(m_bufferR.begin(), m_bufferR.end(), 0);
  328. std::fill(m_absSpectrumL.begin(), m_absSpectrumL.end(), 0);
  329. std::fill(m_absSpectrumR.begin(), m_absSpectrumR.end(), 0);
  330. std::fill(m_normSpectrumL.begin(), m_normSpectrumL.end(), 0);
  331. std::fill(m_normSpectrumR.begin(), m_normSpectrumR.end(), 0);
  332. std::fill(m_history.begin(), m_history.end(), 0);
  333. }
  334. // --------------------------------------
  335. // Frequency conversion helpers
  336. //
  337. // Get sample rate value that is valid for currently stored results.
  338. unsigned int SaProcessor::getSampleRate() const
  339. {
  340. return m_sampleRate;
  341. }
  342. // Maximum frequency of a sampled signal is equal to half of its sample rate.
  343. float SaProcessor::getNyquistFreq() const
  344. {
  345. return getSampleRate() / 2.0f;
  346. }
  347. // FFTW automatically discards upper half of the symmetric FFT output, so
  348. // the useful bin count is the transform size divided by 2, plus zero.
  349. unsigned int SaProcessor::binCount() const
  350. {
  351. return m_fftBlockSize / 2 + 1;
  352. }
  353. // Return the center frequency of given frequency bin.
  354. float SaProcessor::binToFreq(unsigned int bin_index) const
  355. {
  356. return getNyquistFreq() * bin_index / binCount();
  357. }
  358. // Return width of the frequency range that falls into one bin.
  359. // The binCount is lowered by one since half of the first and last bin is
  360. // actually outside the frequency range.
  361. float SaProcessor::binBandwidth() const
  362. {
  363. return getNyquistFreq() / (binCount() - 1);
  364. }
  365. float SaProcessor::getFreqRangeMin(bool linear) const
  366. {
  367. switch (m_controls->m_freqRangeModel.value())
  368. {
  369. case FRANGE_AUDIBLE: return FRANGE_AUDIBLE_START;
  370. case FRANGE_BASS: return FRANGE_BASS_START;
  371. case FRANGE_MIDS: return FRANGE_MIDS_START;
  372. case FRANGE_HIGH: return FRANGE_HIGH_START;
  373. default:
  374. case FRANGE_FULL: return linear ? 0 : LOWEST_LOG_FREQ;
  375. }
  376. }
  377. float SaProcessor::getFreqRangeMax() const
  378. {
  379. switch (m_controls->m_freqRangeModel.value())
  380. {
  381. case FRANGE_AUDIBLE: return FRANGE_AUDIBLE_END;
  382. case FRANGE_BASS: return FRANGE_BASS_END;
  383. case FRANGE_MIDS: return FRANGE_MIDS_END;
  384. case FRANGE_HIGH: return FRANGE_HIGH_END;
  385. default:
  386. case FRANGE_FULL: return getNyquistFreq();
  387. }
  388. }
  389. // Map frequency to pixel x position on a display of given width.
  390. float SaProcessor::freqToXPixel(float freq, unsigned int width) const
  391. {
  392. if (m_controls->m_logXModel.value())
  393. {
  394. if (freq <= 1) {return 0;}
  395. float min = log10(getFreqRangeMin());
  396. float range = log10(getFreqRangeMax()) - min;
  397. return (log10(freq) - min) / range * width;
  398. }
  399. else
  400. {
  401. float min = getFreqRangeMin();
  402. float range = getFreqRangeMax() - min;
  403. return (freq - min) / range * width;
  404. }
  405. }
  406. // Map pixel x position on display of given width back to frequency.
  407. float SaProcessor::xPixelToFreq(float x, unsigned int width) const
  408. {
  409. if (m_controls->m_logXModel.value())
  410. {
  411. float min = log10(getFreqRangeMin());
  412. float max = log10(getFreqRangeMax());
  413. float range = max - min;
  414. return pow(10, min + x / width * range);
  415. }
  416. else
  417. {
  418. float min = getFreqRangeMin();
  419. float range = getFreqRangeMax() - min;
  420. return min + x / width * range;
  421. }
  422. }
  423. // --------------------------------------
  424. // Amplitude conversion helpers
  425. //
  426. float SaProcessor::getAmpRangeMin(bool linear) const
  427. {
  428. // return very low limit to make sure zero gets included at linear grid
  429. if (linear) {return -900;}
  430. switch (m_controls->m_ampRangeModel.value())
  431. {
  432. case ARANGE_EXTENDED: return ARANGE_EXTENDED_START;
  433. case ARANGE_AUDIBLE: return ARANGE_AUDIBLE_START;
  434. case ARANGE_NOISE: return ARANGE_NOISE_START;
  435. default:
  436. case ARANGE_DEFAULT: return ARANGE_DEFAULT_START;
  437. }
  438. }
  439. float SaProcessor::getAmpRangeMax() const
  440. {
  441. switch (m_controls->m_ampRangeModel.value())
  442. {
  443. case ARANGE_EXTENDED: return ARANGE_EXTENDED_END;
  444. case ARANGE_AUDIBLE: return ARANGE_AUDIBLE_END;
  445. case ARANGE_NOISE: return ARANGE_NOISE_END;
  446. default:
  447. case ARANGE_DEFAULT: return ARANGE_DEFAULT_END;
  448. }
  449. }
  450. // Map linear amplitude to pixel y position on a display of given height.
  451. // Note that display coordinates are flipped: amplitude grows from [height] to zero.
  452. float SaProcessor::ampToYPixel(float amplitude, unsigned int height) const
  453. {
  454. if (m_controls->m_logYModel.value())
  455. {
  456. // logarithmic scale: convert linear amplitude to dB (relative to 1.0)
  457. float amplitude_dB = 10 * log10(amplitude);
  458. if (amplitude_dB < getAmpRangeMin())
  459. {
  460. return height;
  461. }
  462. else
  463. {
  464. float max = getAmpRangeMax();
  465. float range = getAmpRangeMin() - max;
  466. return (amplitude_dB - max) / range * height;
  467. }
  468. }
  469. else
  470. {
  471. // linear scale: convert returned ranges from dB to linear scale
  472. float max = pow(10, getAmpRangeMax() / 10);
  473. float range = pow(10, getAmpRangeMin() / 10) - max;
  474. return (amplitude - max) / range * height;
  475. }
  476. }
  477. // Map pixel y position on display of given height back to amplitude.
  478. // Note that display coordinates are flipped: amplitude grows from [height] to zero.
  479. // Also note that in logarithmic Y mode the returned amplitude is in dB, not linear.
  480. float SaProcessor::yPixelToAmp(float y, unsigned int height) const
  481. {
  482. if (m_controls->m_logYModel.value())
  483. {
  484. float max = getAmpRangeMax();
  485. float range = getAmpRangeMin() - max;
  486. return max + range * (y / height);
  487. }
  488. else
  489. {
  490. // linear scale: convert returned ranges from dB to linear scale
  491. float max = pow(10, getAmpRangeMax() / 10);
  492. float range = pow(10, getAmpRangeMin() / 10) - max;
  493. return max + range * (y / height);
  494. }
  495. }