SaSpectrumView.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814
  1. /* SaSpectrumView.cpp - implementation of SaSpectrumView 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. *
  10. * This program is free software; you can redistribute it and/or
  11. * modify it under the terms of the GNU General Public
  12. * License as published by the Free Software Foundation; either
  13. * version 2 of the License, or (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  18. * General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public
  21. * License along with this program (see COPYING); if not, write to the
  22. * Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  23. * Boston, MA 02110-1301 USA.
  24. *
  25. */
  26. #include "SaSpectrumView.h"
  27. #include <algorithm>
  28. #include <cmath>
  29. #include <QMouseEvent>
  30. #include <QMutexLocker>
  31. #include <QPainter>
  32. #include <QString>
  33. #include "GuiApplication.h"
  34. #include "MainWindow.h"
  35. #include "SaProcessor.h"
  36. #ifdef SA_DEBUG
  37. #include <chrono>
  38. #endif
  39. SaSpectrumView::SaSpectrumView(SaControls *controls, SaProcessor *processor, QWidget *_parent) :
  40. QWidget(_parent),
  41. m_controls(controls),
  42. m_processor(processor),
  43. m_freezeRequest(false),
  44. m_frozen(false)
  45. {
  46. setMinimumSize(360, 170);
  47. setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Minimum);
  48. connect(gui->mainWindow(), SIGNAL(periodicUpdate()), this, SLOT(periodicUpdate()));
  49. m_displayBufferL.resize(m_processor->binCount(), 0);
  50. m_displayBufferR.resize(m_processor->binCount(), 0);
  51. m_peakBufferL.resize(m_processor->binCount(), 0);
  52. m_peakBufferR.resize(m_processor->binCount(), 0);
  53. m_freqRangeIndex = m_controls->m_freqRangeModel.value();
  54. m_ampRangeIndex = m_controls->m_ampRangeModel.value();
  55. m_logFreqTics = makeLogFreqTics(m_processor->getFreqRangeMin(), m_processor->getFreqRangeMax());
  56. m_linearFreqTics = makeLinearFreqTics(m_processor->getFreqRangeMin(), m_processor->getFreqRangeMax());
  57. m_logAmpTics = makeLogAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
  58. m_linearAmpTics = makeLinearAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
  59. m_cursor = QPointF(0, 0);
  60. #ifdef SA_DEBUG
  61. m_execution_avg = m_path_avg = m_draw_avg = 0;
  62. #endif
  63. }
  64. // Compose and draw all the content; periodically called by Qt.
  65. // NOTE: Performance sensitive! If the drawing takes too long, it will drag
  66. // the FPS down for the entire program! Use SA_DEBUG to display timings.
  67. void SaSpectrumView::paintEvent(QPaintEvent *event)
  68. {
  69. #ifdef SA_DEBUG
  70. int total_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
  71. #endif
  72. // 0) Constants and init
  73. QPainter painter(this);
  74. painter.setRenderHint(QPainter::Antialiasing, true);
  75. // drawing and path-making are split into multiple methods for clarity;
  76. // display boundaries are updated here and shared as member variables
  77. m_displayTop = 1;
  78. m_displayBottom = height() -20;
  79. m_displayLeft = 26;
  80. m_displayRight = width() -26;
  81. m_displayWidth = m_displayRight - m_displayLeft;
  82. // recompute range labels if needed
  83. if (m_freqRangeIndex != m_controls->m_freqRangeModel.value())
  84. {
  85. m_logFreqTics = makeLogFreqTics(m_processor->getFreqRangeMin(), m_processor->getFreqRangeMax());
  86. m_linearFreqTics = makeLinearFreqTics(m_processor->getFreqRangeMin(true), m_processor->getFreqRangeMax());
  87. m_freqRangeIndex = m_controls->m_freqRangeModel.value();
  88. }
  89. if (m_ampRangeIndex != m_controls->m_ampRangeModel.value())
  90. {
  91. m_logAmpTics = makeLogAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
  92. m_linearAmpTics = makeLinearAmpTics(m_processor->getAmpRangeMin(true), m_processor->getAmpRangeMax());
  93. m_ampRangeIndex = m_controls->m_ampRangeModel.value();
  94. }
  95. // generate freeze request or clear "frozen" status based on freeze button
  96. if (!m_frozen && m_controls->m_refFreezeModel.value())
  97. {
  98. m_freezeRequest = true;
  99. }
  100. else if (!m_controls->m_refFreezeModel.value())
  101. {
  102. m_frozen = false;
  103. }
  104. // 1) Background, grid and labels
  105. drawGrid(painter);
  106. // 2) Spectrum display
  107. drawSpectrum(painter);
  108. // 3) Overlays
  109. // draw cursor (if it is within bounds)
  110. drawCursor(painter);
  111. // always draw the display outline
  112. painter.setPen(QPen(m_controls->m_colorGrid, 2, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  113. painter.drawRoundedRect(m_displayLeft, 1,
  114. m_displayWidth, m_displayBottom,
  115. 2.0, 2.0);
  116. #ifdef SA_DEBUG
  117. // display performance measurements if enabled
  118. total_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - total_time;
  119. m_execution_avg = 0.95 * m_execution_avg + 0.05 * total_time / 1000000.0;
  120. painter.setPen(QPen(m_controls->m_colorLabels, 1,
  121. Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  122. painter.drawText(m_displayRight -150, 10, 130, 16, Qt::AlignLeft,
  123. QString("Exec avg.: ").append(std::to_string(m_execution_avg).substr(0, 5).c_str()).append(" ms"));
  124. painter.drawText(m_displayRight -150, 30, 130, 16, Qt::AlignLeft,
  125. QString("Buff. upd. avg: ").append(std::to_string(m_refresh_avg).substr(0, 5).c_str()).append(" ms"));
  126. painter.drawText(m_displayRight -150, 50, 130, 16, Qt::AlignLeft,
  127. QString("Path build avg: ").append(std::to_string(m_path_avg).substr(0, 5).c_str()).append(" ms"));
  128. painter.drawText(m_displayRight -150, 70, 130, 16, Qt::AlignLeft,
  129. QString("Path draw avg: ").append(std::to_string(m_draw_avg).substr(0, 5).c_str()).append(" ms"));
  130. #endif
  131. }
  132. // Refresh data and draw the spectrum.
  133. void SaSpectrumView::drawSpectrum(QPainter &painter)
  134. {
  135. #ifdef SA_DEBUG
  136. int draw_time = 0;
  137. #endif
  138. // draw the graph only if there is any input, averaging residue or peaks
  139. if (m_decaySum > 0 || m_processor->spectrumNotEmpty())
  140. {
  141. // update data buffers and reconstruct paths
  142. refreshPaths();
  143. // draw stored paths
  144. #ifdef SA_DEBUG
  145. draw_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
  146. #endif
  147. // in case stereo is disabled, mono data are stored in left channel structures
  148. if (m_controls->m_stereoModel.value())
  149. {
  150. painter.fillPath(m_pathR, QBrush(m_controls->m_colorR));
  151. painter.fillPath(m_pathL, QBrush(m_controls->m_colorL));
  152. }
  153. else
  154. {
  155. painter.fillPath(m_pathL, QBrush(m_controls->m_colorMono));
  156. }
  157. // draw the peakBuffer only if peak hold or reference freeze is active
  158. if (m_controls->m_peakHoldModel.value() || m_controls->m_refFreezeModel.value())
  159. {
  160. if (m_controls->m_stereoModel.value())
  161. {
  162. painter.setPen(QPen(m_controls->m_colorR, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  163. painter.drawPath(m_pathPeakR);
  164. painter.setPen(QPen(m_controls->m_colorL, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  165. painter.drawPath(m_pathPeakL);
  166. }
  167. else
  168. {
  169. painter.setPen(QPen(m_controls->m_colorL, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  170. painter.drawPath(m_pathPeakL);
  171. }
  172. }
  173. #ifdef SA_DEBUG
  174. draw_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - draw_time;
  175. #endif
  176. }
  177. #ifdef SA_DEBUG
  178. // save performance measurement result
  179. m_draw_avg = 0.95 * m_draw_avg + 0.05 * draw_time / 1000000.0;
  180. #endif
  181. }
  182. // Read newest FFT results from SaProcessor, update local display buffers
  183. // and build QPainter paths.
  184. void SaSpectrumView::refreshPaths()
  185. {
  186. // Reallocation lock is required for the entire function, to keep display
  187. // buffer size consistent with block size.
  188. QMutexLocker reloc_lock(&m_processor->m_reallocationAccess);
  189. // check if bin count changed and reallocate display buffers accordingly
  190. if (m_processor->binCount() != m_displayBufferL.size())
  191. {
  192. m_displayBufferL.clear();
  193. m_displayBufferR.clear();
  194. m_peakBufferL.clear();
  195. m_peakBufferR.clear();
  196. m_displayBufferL.resize(m_processor->binCount(), 0);
  197. m_displayBufferR.resize(m_processor->binCount(), 0);
  198. m_peakBufferL.resize(m_processor->binCount(), 0);
  199. m_peakBufferR.resize(m_processor->binCount(), 0);
  200. }
  201. // update display buffers for left and right channel
  202. #ifdef SA_DEBUG
  203. int refresh_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
  204. #endif
  205. m_decaySum = 0;
  206. updateBuffers(m_processor->getSpectrumL(), m_displayBufferL.data(), m_peakBufferL.data());
  207. updateBuffers(m_processor->getSpectrumR(), m_displayBufferR.data(), m_peakBufferR.data());
  208. #ifdef SA_DEBUG
  209. refresh_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - refresh_time;
  210. #endif
  211. // if there was a freeze request, it was taken care of during the update
  212. if (m_controls->m_refFreezeModel.value() && m_freezeRequest)
  213. {
  214. m_freezeRequest = false;
  215. m_frozen = true;
  216. }
  217. #ifdef SA_DEBUG
  218. int path_time = std::chrono::high_resolution_clock::now().time_since_epoch().count();
  219. #endif
  220. // Use updated display buffers to prepare new paths for QPainter.
  221. // This is the second slowest action (first is the subsequent drawing); use
  222. // the resolution parameter to balance display quality and performance.
  223. m_pathL = makePath(m_displayBufferL, m_controls->m_spectrumResolutionModel.value());
  224. if (m_controls->m_stereoModel.value())
  225. {
  226. m_pathR = makePath(m_displayBufferR, m_controls->m_spectrumResolutionModel.value());
  227. }
  228. if (m_controls->m_peakHoldModel.value() || m_controls->m_refFreezeModel.value())
  229. {
  230. m_pathPeakL = makePath(m_peakBufferL, m_controls->m_envelopeResolutionModel.value());
  231. if (m_controls->m_stereoModel.value())
  232. {
  233. m_pathPeakR = makePath(m_peakBufferR, m_controls->m_envelopeResolutionModel.value());
  234. }
  235. }
  236. #ifdef SA_DEBUG
  237. path_time = std::chrono::high_resolution_clock::now().time_since_epoch().count() - path_time;
  238. #endif
  239. #ifdef SA_DEBUG
  240. // save performance measurement results
  241. m_refresh_avg = 0.95 * m_refresh_avg + 0.05 * refresh_time / 1000000.0;
  242. m_path_avg = .95f * m_path_avg + .05f * path_time / 1000000.f;
  243. #endif
  244. }
  245. // Update display buffers: add new data, update average and peaks / reference.
  246. // Output the sum of all displayed values -- draw only if it is non-zero.
  247. // NOTE: The calling function is responsible for acquiring SaProcessor
  248. // reallocation access lock! Data access lock is not needed: the final result
  249. // buffer is updated very quickly and the worst case is that one frame will be
  250. // part new, part old. At reasonable frame rate, such difference is invisible..
  251. void SaSpectrumView::updateBuffers(const float *spectrum, float *displayBuffer, float *peakBuffer)
  252. {
  253. for (int n = 0; n < m_processor->binCount(); n++)
  254. {
  255. // Update the exponential average if enabled, or simply copy the value.
  256. if (!m_controls->m_pauseModel.value())
  257. {
  258. if (m_controls->m_smoothModel.value())
  259. {
  260. const float smoothFactor = m_controls->m_averagingWeightModel.value();
  261. displayBuffer[n] = spectrum[n] * smoothFactor + displayBuffer[n] * (1 - smoothFactor);
  262. }
  263. else
  264. {
  265. displayBuffer[n] = spectrum[n];
  266. }
  267. }
  268. // Update peak-hold and reference freeze data (using a shared curve).
  269. // Peak hold and freeze can be combined: decay only if not frozen.
  270. // Ref. freeze operates on the (possibly averaged) display buffer.
  271. if (m_controls->m_refFreezeModel.value() && m_freezeRequest)
  272. {
  273. peakBuffer[n] = displayBuffer[n];
  274. }
  275. else if (m_controls->m_peakHoldModel.value() && !m_controls->m_pauseModel.value())
  276. {
  277. if (spectrum[n] > peakBuffer[n])
  278. {
  279. peakBuffer[n] = spectrum[n];
  280. }
  281. else if (!m_controls->m_refFreezeModel.value())
  282. {
  283. peakBuffer[n] = peakBuffer[n] * m_controls->m_peakDecayFactorModel.value();
  284. }
  285. }
  286. else if (!m_controls->m_refFreezeModel.value() && !m_controls->m_peakHoldModel.value())
  287. {
  288. peakBuffer[n] = 0;
  289. }
  290. // take note if there was actually anything to display
  291. m_decaySum += displayBuffer[n] + peakBuffer[n];
  292. }
  293. }
  294. // Use display buffer to build a path that can be drawn or filled by QPainter.
  295. // Resolution controls the performance / quality tradeoff; the value specifies
  296. // number of points in x axis per device pixel. Values over 1.0 still
  297. // contribute to quality and accuracy thanks to anti-aliasing.
  298. QPainterPath SaSpectrumView::makePath(std::vector<float> &displayBuffer, float resolution = 1.0)
  299. {
  300. // convert resolution to number of path points per logical pixel
  301. float pixel_limit = resolution * window()->devicePixelRatio();
  302. QPainterPath path;
  303. path.moveTo(m_displayLeft, m_displayBottom);
  304. // Translate frequency bins to path points.
  305. // Display is flipped: y values grow towards zero, initial max is bottom.
  306. // Bins falling to interval [x_start, x_next) contribute to a single point.
  307. float max = m_displayBottom;
  308. float x_start = -1; // lower bound of currently constructed point
  309. for (unsigned int n = 0; n < m_processor->binCount(); n++)
  310. {
  311. float x = freqToXPixel(binToFreq(n), m_displayWidth);
  312. float x_next = freqToXPixel(binToFreq(n + 1), m_displayWidth);
  313. float y = ampToYPixel(displayBuffer[n], m_displayBottom);
  314. // consider making a point only if x falls within display bounds
  315. if (0 < x && x < m_displayWidth)
  316. {
  317. if (x_start == -1)
  318. {
  319. x_start = x;
  320. // the first displayed bin is stretched to the left edge to prevent
  321. // creating a misleading slope leading to zero (at log. scale)
  322. path.lineTo(m_displayLeft, y + m_displayTop);
  323. }
  324. // Opt.: QPainter is very slow -- draw at most [pixel_limit] points
  325. // per logical pixel. As opposed to limiting the bin count, this
  326. // allows high resolution display if user resizes the analyzer.
  327. // Look at bins that share the pixel and use the highest value:
  328. max = y < max ? y : max;
  329. // And make the final point in the middle of current interval.
  330. if ((int)(x * pixel_limit) != (int)(x_next * pixel_limit))
  331. {
  332. x = (x + x_start) / 2;
  333. path.lineTo(x + m_displayLeft, max + m_displayTop);
  334. max = m_displayBottom;
  335. x_start = x_next;
  336. }
  337. }
  338. else
  339. {
  340. // stop processing after a bin falls outside right edge
  341. // and align it to the edge to prevent a gap
  342. if (n > 0 && x > 0)
  343. {
  344. path.lineTo(m_displayRight, y + m_displayTop);
  345. break;
  346. }
  347. }
  348. }
  349. path.lineTo(m_displayRight, m_displayBottom);
  350. path.closeSubpath();
  351. return path;
  352. }
  353. // Draw background, grid and associated frequency and amplitude labels.
  354. void SaSpectrumView::drawGrid(QPainter &painter)
  355. {
  356. std::vector<std::pair<int, std::string>> *freqTics = NULL;
  357. std::vector<std::pair<float, std::string>> *ampTics = NULL;
  358. float pos = 0;
  359. float label_width = 24;
  360. float label_height = 15;
  361. float margin = 5;
  362. // always draw the background
  363. painter.fillRect(m_displayLeft, m_displayTop,
  364. m_displayWidth, m_displayBottom,
  365. m_controls->m_colorBG);
  366. // select logarithmic or linear frequency grid and draw it
  367. if (m_controls->m_logXModel.value())
  368. {
  369. freqTics = &m_logFreqTics;
  370. }
  371. else
  372. {
  373. freqTics = &m_linearFreqTics;
  374. }
  375. // draw frequency grid (line.first is display position)
  376. painter.setPen(QPen(m_controls->m_colorGrid, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  377. for (auto &line: *freqTics)
  378. {
  379. painter.drawLine(m_displayLeft + freqToXPixel(line.first, m_displayWidth),
  380. 2,
  381. m_displayLeft + freqToXPixel(line.first, m_displayWidth),
  382. m_displayBottom);
  383. }
  384. // print frequency labels (line.second is label)
  385. painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  386. for (auto & line: *freqTics)
  387. {
  388. pos = m_displayLeft + freqToXPixel(line.first, m_displayWidth);
  389. // align first and last label to the edge if needed, otherwise center them
  390. if (line == freqTics->front() && pos - label_width / 2 < m_displayLeft)
  391. {
  392. painter.drawText(m_displayLeft, m_displayBottom + margin,
  393. label_width, label_height, Qt::AlignLeft | Qt::TextDontClip,
  394. QString(line.second.c_str()));
  395. }
  396. else if (line == freqTics->back() && pos + label_width / 2 > m_displayRight)
  397. {
  398. painter.drawText(m_displayRight - label_width, m_displayBottom + margin,
  399. label_width, label_height, Qt::AlignRight | Qt::TextDontClip,
  400. QString(line.second.c_str()));
  401. }
  402. else
  403. {
  404. painter.drawText(pos - label_width / 2, m_displayBottom + margin,
  405. label_width, label_height, Qt::AlignHCenter | Qt::TextDontClip,
  406. QString(line.second.c_str()));
  407. }
  408. }
  409. margin = 2;
  410. // select logarithmic or linear amplitude grid and draw it
  411. if (m_controls->m_logYModel.value())
  412. {
  413. ampTics = &m_logAmpTics;
  414. }
  415. else
  416. {
  417. ampTics = &m_linearAmpTics;
  418. }
  419. // draw amplitude grid
  420. painter.setPen(QPen(m_controls->m_colorGrid, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  421. for (auto & line: *ampTics)
  422. {
  423. painter.drawLine(m_displayLeft + 1,
  424. ampToYPixel(line.first, m_displayBottom),
  425. m_displayRight - 1,
  426. ampToYPixel(line.first, m_displayBottom));
  427. }
  428. // print amplitude labels
  429. painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  430. bool stereo = m_controls->m_stereoModel.value();
  431. for (auto & line: *ampTics)
  432. {
  433. pos = ampToYPixel(line.first, m_displayBottom);
  434. // align first and last labels to edge if needed, otherwise center them
  435. if (line == ampTics->back() && pos < 8)
  436. {
  437. if (stereo)
  438. {
  439. painter.setPen(QPen(m_controls->m_colorL.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  440. }
  441. painter.drawText(m_displayLeft - label_width - margin, m_displayTop - 2,
  442. label_width, label_height, Qt::AlignRight | Qt::AlignTop | Qt::TextDontClip,
  443. QString(line.second.c_str()));
  444. if (stereo)
  445. {
  446. painter.setPen(QPen(m_controls->m_colorR.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  447. }
  448. painter.drawText(m_displayRight + margin, m_displayTop - 2,
  449. label_width, label_height, Qt::AlignLeft | Qt::AlignTop | Qt::TextDontClip,
  450. QString(line.second.c_str()));
  451. }
  452. else if (line == ampTics->front() && pos > m_displayBottom - label_height)
  453. {
  454. if (stereo)
  455. {
  456. painter.setPen(QPen(m_controls->m_colorL.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  457. }
  458. painter.drawText(m_displayLeft - label_width - margin, m_displayBottom - label_height + 2,
  459. label_width, label_height, Qt::AlignRight | Qt::AlignBottom | Qt::TextDontClip,
  460. QString(line.second.c_str()));
  461. if (stereo)
  462. {
  463. painter.setPen(QPen(m_controls->m_colorR.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  464. }
  465. painter.drawText(m_displayRight + margin, m_displayBottom - label_height + 2,
  466. label_width, label_height, Qt::AlignLeft | Qt::AlignBottom | Qt::TextDontClip,
  467. QString(line.second.c_str()));
  468. }
  469. else
  470. {
  471. if (stereo)
  472. {
  473. painter.setPen(QPen(m_controls->m_colorL.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  474. }
  475. painter.drawText(m_displayLeft - label_width - margin, pos - label_height / 2,
  476. label_width, label_height, Qt::AlignRight | Qt::AlignVCenter | Qt::TextDontClip,
  477. QString(line.second.c_str()));
  478. if (stereo)
  479. {
  480. painter.setPen(QPen(m_controls->m_colorR.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  481. }
  482. painter.drawText(m_displayRight + margin, pos - label_height / 2,
  483. label_width, label_height, Qt::AlignLeft | Qt::AlignVCenter | Qt::TextDontClip,
  484. QString(line.second.c_str()));
  485. }
  486. }
  487. }
  488. // Draw cursor and its coordinates if it is within display bounds.
  489. void SaSpectrumView::drawCursor(QPainter &painter)
  490. {
  491. if ( m_cursor.x() >= m_displayLeft
  492. && m_cursor.x() <= m_displayRight
  493. && m_cursor.y() >= m_displayTop
  494. && m_cursor.y() <= m_displayBottom)
  495. {
  496. // cursor lines
  497. painter.setPen(QPen(m_controls->m_colorGrid.lighter(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  498. painter.drawLine(QPointF(m_cursor.x(), m_displayTop), QPointF(m_cursor.x(), m_displayBottom));
  499. painter.drawLine(QPointF(m_displayLeft, m_cursor.y()), QPointF(m_displayRight, m_cursor.y()));
  500. // coordinates: background box
  501. QFontMetrics fontMetrics = painter.fontMetrics();
  502. unsigned int const box_left = 5;
  503. unsigned int const box_top = 5;
  504. unsigned int const box_margin = 3;
  505. unsigned int const box_height = 2*(fontMetrics.size(Qt::TextSingleLine, "0 HzdBFS").height() + box_margin);
  506. unsigned int const box_width = fontMetrics.size(Qt::TextSingleLine, "-99.9 dBFS").width() + 2*box_margin;
  507. painter.setPen(QPen(m_controls->m_colorLabels.darker(), 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  508. painter.fillRect(m_displayLeft + box_left, m_displayTop + box_top,
  509. box_width, box_height, QColor(0, 0, 0, 64));
  510. // coordinates: text
  511. painter.setPen(QPen(m_controls->m_colorLabels, 1, Qt::SolidLine, Qt::RoundCap, Qt::BevelJoin));
  512. QString tmps;
  513. // frequency
  514. int xFreq = (int)m_processor->xPixelToFreq(m_cursor.x() - m_displayLeft, m_displayWidth);
  515. tmps = QString("%1 Hz").arg(xFreq);
  516. painter.drawText(m_displayLeft + box_left + box_margin,
  517. m_displayTop + box_top + box_margin,
  518. box_width, box_height / 2, Qt::AlignLeft, tmps);
  519. // amplitude
  520. float yAmp = m_processor->yPixelToAmp(m_cursor.y(), m_displayBottom);
  521. if (m_controls->m_logYModel.value())
  522. {
  523. tmps = QString(std::to_string(yAmp).substr(0, 5).c_str()).append(" dBFS");
  524. }
  525. else
  526. {
  527. // add 0.0005 to get proper rounding to 3 decimal places
  528. tmps = QString(std::to_string(0.0005f + yAmp).substr(0, 5).c_str());
  529. }
  530. painter.drawText(m_displayLeft + box_left + box_margin,
  531. m_displayTop + box_top + box_height / 2,
  532. box_width, box_height / 2, Qt::AlignLeft, tmps);
  533. }
  534. }
  535. // Wrappers for most used SaProcessor helpers (to make local code more compact).
  536. float SaSpectrumView::binToFreq(unsigned int bin_index)
  537. {
  538. return m_processor->binToFreq(bin_index);
  539. }
  540. float SaSpectrumView::freqToXPixel(float frequency, unsigned int width)
  541. {
  542. return m_processor->freqToXPixel(frequency, width);
  543. }
  544. float SaSpectrumView::ampToYPixel(float amplitude, unsigned int height)
  545. {
  546. return m_processor->ampToYPixel(amplitude, height);
  547. }
  548. // Generate labels suitable for logarithmic frequency scale.
  549. // Low / high limits are in Hz. Lowest possible label is 10 Hz.
  550. std::vector<std::pair<int, std::string>> SaSpectrumView::makeLogFreqTics(int low, int high)
  551. {
  552. std::vector<std::pair<int, std::string>> result;
  553. int i, j;
  554. int a[] = {10, 20, 50}; // sparse series multipliers
  555. int b[] = {14, 30, 70}; // additional (denser) series
  556. // generate main steps (powers of 10); use the series to specify smaller steps
  557. for (i = 1; i <= high; i *= 10)
  558. {
  559. for (j = 0; j < 3; j++)
  560. {
  561. // insert a label from sparse series if it falls within bounds
  562. if (i * a[j] >= low && i * a[j] <= high)
  563. {
  564. if (i * a[j] < 1000)
  565. {
  566. result.emplace_back(i * a[j], std::to_string(i * a[j]));
  567. }
  568. else
  569. {
  570. result.emplace_back(i * a[j], std::to_string(i * a[j] / 1000) + "k");
  571. }
  572. }
  573. // also insert denser series if high and low values are close
  574. if ((log10(high) - log10(low) < 2) && (i * b[j] >= low && i * b[j] <= high))
  575. {
  576. if (i * b[j] < 1500)
  577. {
  578. result.emplace_back(i * b[j], std::to_string(i * b[j]));
  579. }
  580. else
  581. {
  582. result.emplace_back(i * b[j], std::to_string(i * b[j] / 1000) + "k");
  583. }
  584. }
  585. }
  586. }
  587. return result;
  588. }
  589. // Generate labels suitable for linear frequency scale.
  590. // Low / high limits are in Hz.
  591. std::vector<std::pair<int, std::string>> SaSpectrumView::makeLinearFreqTics(int low, int high)
  592. {
  593. std::vector<std::pair<int, std::string>> result;
  594. int i, increment;
  595. // select a suitable increment based on zoom level
  596. if (high - low < 500) {increment = 50;}
  597. else if (high - low < 1000) {increment = 100;}
  598. else if (high - low < 5000) {increment = 1000;}
  599. else {increment = 2000;}
  600. // generate steps based on increment, starting at 0
  601. for (i = 0; i <= high; i += increment)
  602. {
  603. if (i >= low)
  604. {
  605. if (i < 1000)
  606. {
  607. result.emplace_back(i, std::to_string(i));
  608. }
  609. else
  610. {
  611. result.emplace_back(i, std::to_string(i/1000) + "k");
  612. }
  613. }
  614. }
  615. return result;
  616. }
  617. // Generate labels suitable for logarithmic (dB) amplitude scale.
  618. // Low / high limits are in dB; 0 dB amplitude = 1.0 linear.
  619. // Treating results as power ratio, i.e., 3 dB should be about twice as loud.
  620. std::vector<std::pair<float, std::string>> SaSpectrumView::makeLogAmpTics(int low, int high)
  621. {
  622. std::vector<std::pair<float, std::string>> result;
  623. float i;
  624. double increment;
  625. // Base zoom level on selected range and how close is the current height
  626. // to the sizeHint() (denser scale for bigger window).
  627. if ((high - low) < 20 * ((float)height() / sizeHint().height()))
  628. {
  629. increment = pow(10, 0.3); // 3 dB steps when really zoomed in
  630. }
  631. else if (high - low < 45 * ((float)height() / sizeHint().height()))
  632. {
  633. increment = pow(10, 0.6); // 6 dB steps when sufficiently zoomed in
  634. }
  635. else
  636. {
  637. increment = 10; // 10 dB steps otherwise
  638. }
  639. // Generate n dB increments, start checking at -90 dB. Limits are tweaked
  640. // just a little bit to make sure float comparisons do not miss edges.
  641. for (i = 0.000000001; 10 * log10(i) <= (high + 0.001); i *= increment)
  642. {
  643. if (10 * log10(i) >= (low - 0.001))
  644. {
  645. result.emplace_back(i, std::to_string((int)std::round(10 * log10(i))));
  646. }
  647. }
  648. return result;
  649. }
  650. // Generate labels suitable for linear amplitude scale.
  651. // Low / high limits are in dB; 0 dB amplitude = 1.0 linear.
  652. // Smallest possible label is 0.001, largest is 999. This includes the majority
  653. // of useful labels; going lower or higher would require increasing margin size
  654. // so that the text can fit. That would be a waste of space -- the linear scale
  655. // would only make the experience worse for the main, logarithmic (dB) scale.
  656. std::vector<std::pair<float, std::string>> SaSpectrumView::makeLinearAmpTics(int low, int high)
  657. {
  658. std::vector<std::pair<float, std::string>> result;
  659. double i, nearest;
  660. // make about 5 labels when window is small, 10 if it is big
  661. float split = (float)height() / sizeHint().height() >= 1.5 ? 10.0 : 5.0;
  662. // convert limits to linear scale
  663. float lin_low = pow(10, low / 10.0);
  664. float lin_high = pow(10, high / 10.0);
  665. // Linear scale will vary widely, so instead of trying to craft extra nice
  666. // multiples, just generate a few evenly spaced increments across the range,
  667. // paying attention only to the decimal places to keep labels short.
  668. // Limits are shifted a bit so that float comparisons do not miss edges.
  669. for (i = 0; i <= (lin_high + 0.0001); i += (lin_high - lin_low) / split)
  670. {
  671. if (i >= (lin_low - 0.0001))
  672. {
  673. if (i >= 9.99 && i < 99.9)
  674. {
  675. nearest = std::round(i);
  676. result.emplace_back(nearest, std::to_string(nearest).substr(0, 2));
  677. }
  678. else if (i >= 0.099)
  679. { // also covers numbers above 100
  680. nearest = std::round(i * 10) / 10;
  681. result.emplace_back(nearest, std::to_string(nearest).substr(0, 3));
  682. }
  683. else if (i >= 0.0099)
  684. {
  685. nearest = std::round(i * 1000) / 1000;
  686. result.emplace_back(nearest, std::to_string(nearest).substr(0, 4));
  687. }
  688. else if (i >= 0.00099)
  689. {
  690. nearest = std::round(i * 10000) / 10000;
  691. result.emplace_back(nearest, std::to_string(nearest).substr(1, 4));
  692. }
  693. else if (i > -0.01 && i < 0.01)
  694. {
  695. result.emplace_back(i, "0"); // an exception, zero is short..
  696. }
  697. }
  698. }
  699. return result;
  700. }
  701. // Periodic update is called by LMMS.
  702. void SaSpectrumView::periodicUpdate()
  703. {
  704. // check if the widget is visible; if it is not, processing can be paused
  705. m_processor->setSpectrumActive(isVisible());
  706. // tell Qt it is time for repaint
  707. update();
  708. }
  709. // Handle mouse input: set new cursor position.
  710. // For some reason (a bug?), localPos() only returns integers. As a workaround
  711. // the fractional part is taken from windowPos() (which works correctly).
  712. void SaSpectrumView::mouseMoveEvent(QMouseEvent *event)
  713. {
  714. m_cursor = QPointF( event->localPos().x() - (event->windowPos().x() - (long)event->windowPos().x()),
  715. event->localPos().y() - (event->windowPos().y() - (long)event->windowPos().y()));
  716. }
  717. void SaSpectrumView::mousePressEvent(QMouseEvent *event)
  718. {
  719. m_cursor = QPointF( event->localPos().x() - (event->windowPos().x() - (long)event->windowPos().x()),
  720. event->localPos().y() - (event->windowPos().y() - (long)event->windowPos().y()));
  721. }
  722. // Handle resize event: rebuild grid and labels
  723. void SaSpectrumView::resizeEvent(QResizeEvent *event)
  724. {
  725. // frequency does not change density with size
  726. // amplitude does: rebuild labels
  727. m_logAmpTics = makeLogAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
  728. m_linearAmpTics = makeLinearAmpTics(m_processor->getAmpRangeMin(), m_processor->getAmpRangeMax());
  729. }