VolumeMeter.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954
  1. #include "VolumeMeter.hpp"
  2. #include <OBSApp.hpp>
  3. #include <utility/VolumeMeterTimer.hpp>
  4. #include <QEvent>
  5. #include <QMouseEvent>
  6. #include <QPainter>
  7. #include "moc_VolumeMeter.cpp"
  8. // Size of the audio indicator in pixels
  9. #define INDICATOR_THICKNESS 3
  10. // Padding on top and bottom of vertical meters
  11. #define METER_PADDING 1
  12. std::weak_ptr<VolumeMeterTimer> VolumeMeter::updateTimer;
  13. static inline QColor color_from_int(long long val)
  14. {
  15. QColor color(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff);
  16. color.setAlpha(255);
  17. return color;
  18. }
  19. QColor VolumeMeter::getBackgroundNominalColor() const
  20. {
  21. return p_backgroundNominalColor;
  22. }
  23. QColor VolumeMeter::getBackgroundNominalColorDisabled() const
  24. {
  25. return backgroundNominalColorDisabled;
  26. }
  27. void VolumeMeter::setBackgroundNominalColor(QColor c)
  28. {
  29. p_backgroundNominalColor = std::move(c);
  30. if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) {
  31. backgroundNominalColor =
  32. color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerGreen"));
  33. } else {
  34. backgroundNominalColor = p_backgroundNominalColor;
  35. }
  36. }
  37. void VolumeMeter::setBackgroundNominalColorDisabled(QColor c)
  38. {
  39. backgroundNominalColorDisabled = std::move(c);
  40. }
  41. QColor VolumeMeter::getBackgroundWarningColor() const
  42. {
  43. return p_backgroundWarningColor;
  44. }
  45. QColor VolumeMeter::getBackgroundWarningColorDisabled() const
  46. {
  47. return backgroundWarningColorDisabled;
  48. }
  49. void VolumeMeter::setBackgroundWarningColor(QColor c)
  50. {
  51. p_backgroundWarningColor = std::move(c);
  52. if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) {
  53. backgroundWarningColor =
  54. color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerYellow"));
  55. } else {
  56. backgroundWarningColor = p_backgroundWarningColor;
  57. }
  58. }
  59. void VolumeMeter::setBackgroundWarningColorDisabled(QColor c)
  60. {
  61. backgroundWarningColorDisabled = std::move(c);
  62. }
  63. QColor VolumeMeter::getBackgroundErrorColor() const
  64. {
  65. return p_backgroundErrorColor;
  66. }
  67. QColor VolumeMeter::getBackgroundErrorColorDisabled() const
  68. {
  69. return backgroundErrorColorDisabled;
  70. }
  71. void VolumeMeter::setBackgroundErrorColor(QColor c)
  72. {
  73. p_backgroundErrorColor = std::move(c);
  74. if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) {
  75. backgroundErrorColor =
  76. color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerRed"));
  77. } else {
  78. backgroundErrorColor = p_backgroundErrorColor;
  79. }
  80. }
  81. void VolumeMeter::setBackgroundErrorColorDisabled(QColor c)
  82. {
  83. backgroundErrorColorDisabled = std::move(c);
  84. }
  85. QColor VolumeMeter::getForegroundNominalColor() const
  86. {
  87. return p_foregroundNominalColor;
  88. }
  89. QColor VolumeMeter::getForegroundNominalColorDisabled() const
  90. {
  91. return foregroundNominalColorDisabled;
  92. }
  93. void VolumeMeter::setForegroundNominalColor(QColor c)
  94. {
  95. p_foregroundNominalColor = std::move(c);
  96. if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) {
  97. foregroundNominalColor =
  98. color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerGreenActive"));
  99. } else {
  100. foregroundNominalColor = p_foregroundNominalColor;
  101. }
  102. }
  103. void VolumeMeter::setForegroundNominalColorDisabled(QColor c)
  104. {
  105. foregroundNominalColorDisabled = std::move(c);
  106. }
  107. QColor VolumeMeter::getForegroundWarningColor() const
  108. {
  109. return p_foregroundWarningColor;
  110. }
  111. QColor VolumeMeter::getForegroundWarningColorDisabled() const
  112. {
  113. return foregroundWarningColorDisabled;
  114. }
  115. void VolumeMeter::setForegroundWarningColor(QColor c)
  116. {
  117. p_foregroundWarningColor = std::move(c);
  118. if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) {
  119. foregroundWarningColor =
  120. color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerYellowActive"));
  121. } else {
  122. foregroundWarningColor = p_foregroundWarningColor;
  123. }
  124. }
  125. void VolumeMeter::setForegroundWarningColorDisabled(QColor c)
  126. {
  127. foregroundWarningColorDisabled = std::move(c);
  128. }
  129. QColor VolumeMeter::getForegroundErrorColor() const
  130. {
  131. return p_foregroundErrorColor;
  132. }
  133. QColor VolumeMeter::getForegroundErrorColorDisabled() const
  134. {
  135. return foregroundErrorColorDisabled;
  136. }
  137. void VolumeMeter::setForegroundErrorColor(QColor c)
  138. {
  139. p_foregroundErrorColor = std::move(c);
  140. if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) {
  141. foregroundErrorColor =
  142. color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerRedActive"));
  143. } else {
  144. foregroundErrorColor = p_foregroundErrorColor;
  145. }
  146. }
  147. void VolumeMeter::setForegroundErrorColorDisabled(QColor c)
  148. {
  149. foregroundErrorColorDisabled = std::move(c);
  150. }
  151. QColor VolumeMeter::getClipColor() const
  152. {
  153. return clipColor;
  154. }
  155. void VolumeMeter::setClipColor(QColor c)
  156. {
  157. clipColor = std::move(c);
  158. }
  159. QColor VolumeMeter::getMagnitudeColor() const
  160. {
  161. return magnitudeColor;
  162. }
  163. void VolumeMeter::setMagnitudeColor(QColor c)
  164. {
  165. magnitudeColor = std::move(c);
  166. }
  167. QColor VolumeMeter::getMajorTickColor() const
  168. {
  169. return majorTickColor;
  170. }
  171. void VolumeMeter::setMajorTickColor(QColor c)
  172. {
  173. majorTickColor = std::move(c);
  174. }
  175. QColor VolumeMeter::getMinorTickColor() const
  176. {
  177. return minorTickColor;
  178. }
  179. void VolumeMeter::setMinorTickColor(QColor c)
  180. {
  181. minorTickColor = std::move(c);
  182. }
  183. int VolumeMeter::getMeterThickness() const
  184. {
  185. return meterThickness;
  186. }
  187. void VolumeMeter::setMeterThickness(int v)
  188. {
  189. meterThickness = v;
  190. recalculateLayout = true;
  191. }
  192. qreal VolumeMeter::getMeterFontScaling() const
  193. {
  194. return meterFontScaling;
  195. }
  196. void VolumeMeter::setMeterFontScaling(qreal v)
  197. {
  198. meterFontScaling = v;
  199. recalculateLayout = true;
  200. }
  201. qreal VolumeMeter::getMinimumLevel() const
  202. {
  203. return minimumLevel;
  204. }
  205. void VolumeMeter::setMinimumLevel(qreal v)
  206. {
  207. minimumLevel = v;
  208. }
  209. qreal VolumeMeter::getWarningLevel() const
  210. {
  211. return warningLevel;
  212. }
  213. void VolumeMeter::setWarningLevel(qreal v)
  214. {
  215. warningLevel = v;
  216. }
  217. qreal VolumeMeter::getErrorLevel() const
  218. {
  219. return errorLevel;
  220. }
  221. void VolumeMeter::setErrorLevel(qreal v)
  222. {
  223. errorLevel = v;
  224. }
  225. qreal VolumeMeter::getClipLevel() const
  226. {
  227. return clipLevel;
  228. }
  229. void VolumeMeter::setClipLevel(qreal v)
  230. {
  231. clipLevel = v;
  232. }
  233. qreal VolumeMeter::getMinimumInputLevel() const
  234. {
  235. return minimumInputLevel;
  236. }
  237. void VolumeMeter::setMinimumInputLevel(qreal v)
  238. {
  239. minimumInputLevel = v;
  240. }
  241. qreal VolumeMeter::getPeakDecayRate() const
  242. {
  243. return peakDecayRate;
  244. }
  245. void VolumeMeter::setPeakDecayRate(qreal v)
  246. {
  247. peakDecayRate = v;
  248. }
  249. qreal VolumeMeter::getMagnitudeIntegrationTime() const
  250. {
  251. return magnitudeIntegrationTime;
  252. }
  253. void VolumeMeter::setMagnitudeIntegrationTime(qreal v)
  254. {
  255. magnitudeIntegrationTime = v;
  256. }
  257. qreal VolumeMeter::getPeakHoldDuration() const
  258. {
  259. return peakHoldDuration;
  260. }
  261. void VolumeMeter::setPeakHoldDuration(qreal v)
  262. {
  263. peakHoldDuration = v;
  264. }
  265. qreal VolumeMeter::getInputPeakHoldDuration() const
  266. {
  267. return inputPeakHoldDuration;
  268. }
  269. void VolumeMeter::setInputPeakHoldDuration(qreal v)
  270. {
  271. inputPeakHoldDuration = v;
  272. }
  273. void VolumeMeter::setPeakMeterType(enum obs_peak_meter_type peakMeterType)
  274. {
  275. obs_volmeter_set_peak_meter_type(obs_volmeter, peakMeterType);
  276. switch (peakMeterType) {
  277. case TRUE_PEAK_METER:
  278. // For true-peak meters EBU has defined the Permitted Maximum,
  279. // taking into account the accuracy of the meter and further
  280. // processing required by lossy audio compression.
  281. //
  282. // The alignment level was not specified, but I've adjusted
  283. // it compared to a sample-peak meter. Incidentally Youtube
  284. // uses this new Alignment Level as the maximum integrated
  285. // loudness of a video.
  286. //
  287. // * Permitted Maximum Level (PML) = -2.0 dBTP
  288. // * Alignment Level (AL) = -13 dBTP
  289. setErrorLevel(-2.0);
  290. setWarningLevel(-13.0);
  291. break;
  292. case SAMPLE_PEAK_METER:
  293. default:
  294. // For a sample Peak Meter EBU has the following level
  295. // definitions, taking into account inaccuracies of this meter:
  296. //
  297. // * Permitted Maximum Level (PML) = -9.0 dBFS
  298. // * Alignment Level (AL) = -20.0 dBFS
  299. setErrorLevel(-9.0);
  300. setWarningLevel(-20.0);
  301. break;
  302. }
  303. }
  304. void VolumeMeter::mousePressEvent(QMouseEvent *event)
  305. {
  306. setFocus(Qt::MouseFocusReason);
  307. event->accept();
  308. }
  309. void VolumeMeter::wheelEvent(QWheelEvent *event)
  310. {
  311. QApplication::sendEvent(focusProxy(), event);
  312. }
  313. VolumeMeter::VolumeMeter(QWidget *parent, obs_volmeter_t *obs_volmeter, bool vertical)
  314. : QWidget(parent),
  315. obs_volmeter(obs_volmeter),
  316. vertical(vertical)
  317. {
  318. setAttribute(Qt::WA_OpaquePaintEvent, true);
  319. // Default meter settings, they only show if
  320. // there is no stylesheet, do not remove.
  321. backgroundNominalColor.setRgb(0x26, 0x7f, 0x26); // Dark green
  322. backgroundWarningColor.setRgb(0x7f, 0x7f, 0x26); // Dark yellow
  323. backgroundErrorColor.setRgb(0x7f, 0x26, 0x26); // Dark red
  324. foregroundNominalColor.setRgb(0x4c, 0xff, 0x4c); // Bright green
  325. foregroundWarningColor.setRgb(0xff, 0xff, 0x4c); // Bright yellow
  326. foregroundErrorColor.setRgb(0xff, 0x4c, 0x4c); // Bright red
  327. backgroundNominalColorDisabled.setRgb(90, 90, 90);
  328. backgroundWarningColorDisabled.setRgb(117, 117, 117);
  329. backgroundErrorColorDisabled.setRgb(65, 65, 65);
  330. foregroundNominalColorDisabled.setRgb(163, 163, 163);
  331. foregroundWarningColorDisabled.setRgb(217, 217, 217);
  332. foregroundErrorColorDisabled.setRgb(113, 113, 113);
  333. clipColor.setRgb(0xff, 0xff, 0xff); // Bright white
  334. magnitudeColor.setRgb(0x00, 0x00, 0x00); // Black
  335. majorTickColor.setRgb(0x00, 0x00, 0x00); // Black
  336. minorTickColor.setRgb(0x32, 0x32, 0x32); // Dark gray
  337. minimumLevel = -60.0; // -60 dB
  338. warningLevel = -20.0; // -20 dB
  339. errorLevel = -9.0; // -9 dB
  340. clipLevel = -0.5; // -0.5 dB
  341. minimumInputLevel = -50.0; // -50 dB
  342. peakDecayRate = 11.76; // 20 dB / 1.7 sec
  343. magnitudeIntegrationTime = 0.3; // 99% in 300 ms
  344. peakHoldDuration = 20.0; // 20 seconds
  345. inputPeakHoldDuration = 1.0; // 1 second
  346. meterThickness = 3; // Bar thickness in pixels
  347. meterFontScaling = 0.7; // Font size for numbers is 70% of Widget's font size
  348. channels = (int)audio_output_get_channels(obs_get_audio());
  349. doLayout();
  350. updateTimerRef = updateTimer.lock();
  351. if (!updateTimerRef) {
  352. updateTimerRef = std::make_shared<VolumeMeterTimer>();
  353. updateTimerRef->setTimerType(Qt::PreciseTimer);
  354. updateTimerRef->start(16);
  355. updateTimer = updateTimerRef;
  356. }
  357. updateTimerRef->AddVolControl(this);
  358. }
  359. VolumeMeter::~VolumeMeter()
  360. {
  361. updateTimerRef->RemoveVolControl(this);
  362. }
  363. void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS], const float peak[MAX_AUDIO_CHANNELS],
  364. const float inputPeak[MAX_AUDIO_CHANNELS])
  365. {
  366. uint64_t ts = os_gettime_ns();
  367. QMutexLocker locker(&dataMutex);
  368. currentLastUpdateTime = ts;
  369. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  370. currentMagnitude[channelNr] = magnitude[channelNr];
  371. currentPeak[channelNr] = peak[channelNr];
  372. currentInputPeak[channelNr] = inputPeak[channelNr];
  373. }
  374. // In case there are more updates then redraws we must make sure
  375. // that the ballistics of peak and hold are recalculated.
  376. locker.unlock();
  377. calculateBallistics(ts);
  378. }
  379. inline void VolumeMeter::resetLevels()
  380. {
  381. currentLastUpdateTime = 0;
  382. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  383. currentMagnitude[channelNr] = -M_INFINITE;
  384. currentPeak[channelNr] = -M_INFINITE;
  385. currentInputPeak[channelNr] = -M_INFINITE;
  386. displayMagnitude[channelNr] = -M_INFINITE;
  387. displayPeak[channelNr] = -M_INFINITE;
  388. displayPeakHold[channelNr] = -M_INFINITE;
  389. displayPeakHoldLastUpdateTime[channelNr] = 0;
  390. displayInputPeakHold[channelNr] = -M_INFINITE;
  391. displayInputPeakHoldLastUpdateTime[channelNr] = 0;
  392. }
  393. }
  394. bool VolumeMeter::needLayoutChange()
  395. {
  396. int currentNrAudioChannels = obs_volmeter_get_nr_channels(obs_volmeter);
  397. if (!currentNrAudioChannels) {
  398. struct obs_audio_info oai;
  399. obs_get_audio_info(&oai);
  400. currentNrAudioChannels = (oai.speakers == SPEAKERS_MONO) ? 1 : 2;
  401. }
  402. if (displayNrAudioChannels != currentNrAudioChannels) {
  403. displayNrAudioChannels = currentNrAudioChannels;
  404. recalculateLayout = true;
  405. }
  406. return recalculateLayout;
  407. }
  408. // When this is called from the constructor, obs_volmeter_get_nr_channels has not
  409. // yet been called and Q_PROPERTY settings have not yet been read from the
  410. // stylesheet.
  411. inline void VolumeMeter::doLayout()
  412. {
  413. QMutexLocker locker(&dataMutex);
  414. if (displayNrAudioChannels) {
  415. int meterSize = std::floor(22 / displayNrAudioChannels);
  416. setMeterThickness(std::clamp(meterSize, 3, 7));
  417. }
  418. recalculateLayout = false;
  419. tickFont = font();
  420. QFontInfo info(tickFont);
  421. tickFont.setPointSizeF(info.pointSizeF() * meterFontScaling);
  422. QFontMetrics metrics(tickFont);
  423. if (vertical) {
  424. // Each meter channel is meterThickness pixels wide, plus one pixel
  425. // between channels, but not after the last.
  426. // Add 4 pixels for ticks, space to hold our longest label in this font,
  427. // and a few pixels before the fader.
  428. QRect scaleBounds = metrics.boundingRect("-88");
  429. setMinimumSize(displayNrAudioChannels * (meterThickness + 1) - 1 + 10 + scaleBounds.width() + 2, 100);
  430. } else {
  431. // Each meter channel is meterThickness pixels high, plus one pixel
  432. // between channels, but not after the last.
  433. // Add 4 pixels for ticks, and space high enough to hold our label in
  434. // this font, presuming that digits don't have descenders.
  435. setMinimumSize(100, displayNrAudioChannels * (meterThickness + 1) - 1 + 4 + metrics.capHeight());
  436. }
  437. resetLevels();
  438. }
  439. inline bool VolumeMeter::detectIdle(uint64_t ts)
  440. {
  441. double timeSinceLastUpdate = (ts - currentLastUpdateTime) * 0.000000001;
  442. if (timeSinceLastUpdate > 0.5) {
  443. resetLevels();
  444. return true;
  445. } else {
  446. return false;
  447. }
  448. }
  449. inline void VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, qreal timeSinceLastRedraw)
  450. {
  451. if (currentPeak[channelNr] >= displayPeak[channelNr] || isnan(displayPeak[channelNr])) {
  452. // Attack of peak is immediate.
  453. displayPeak[channelNr] = currentPeak[channelNr];
  454. } else {
  455. // Decay of peak is 40 dB / 1.7 seconds for Fast Profile
  456. // 20 dB / 1.7 seconds for Medium Profile (Type I PPM)
  457. // 24 dB / 2.8 seconds for Slow Profile (Type II PPM)
  458. float decay = float(peakDecayRate * timeSinceLastRedraw);
  459. displayPeak[channelNr] =
  460. std::clamp(displayPeak[channelNr] - decay, std::min(currentPeak[channelNr], 0.f), 0.f);
  461. }
  462. if (currentPeak[channelNr] >= displayPeakHold[channelNr] || !isfinite(displayPeakHold[channelNr])) {
  463. // Attack of peak-hold is immediate, but keep track
  464. // when it was last updated.
  465. displayPeakHold[channelNr] = currentPeak[channelNr];
  466. displayPeakHoldLastUpdateTime[channelNr] = ts;
  467. } else {
  468. // The peak and hold falls back to peak
  469. // after 20 seconds.
  470. qreal timeSinceLastPeak = (uint64_t)(ts - displayPeakHoldLastUpdateTime[channelNr]) * 0.000000001;
  471. if (timeSinceLastPeak > peakHoldDuration) {
  472. displayPeakHold[channelNr] = currentPeak[channelNr];
  473. displayPeakHoldLastUpdateTime[channelNr] = ts;
  474. }
  475. }
  476. if (currentInputPeak[channelNr] >= displayInputPeakHold[channelNr] ||
  477. !isfinite(displayInputPeakHold[channelNr])) {
  478. // Attack of peak-hold is immediate, but keep track
  479. // when it was last updated.
  480. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  481. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  482. } else {
  483. // The peak and hold falls back to peak after 1 second.
  484. qreal timeSinceLastPeak = (uint64_t)(ts - displayInputPeakHoldLastUpdateTime[channelNr]) * 0.000000001;
  485. if (timeSinceLastPeak > inputPeakHoldDuration) {
  486. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  487. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  488. }
  489. }
  490. if (!isfinite(displayMagnitude[channelNr])) {
  491. // The statements in the else-leg do not work with
  492. // NaN and infinite displayMagnitude.
  493. displayMagnitude[channelNr] = currentMagnitude[channelNr];
  494. } else {
  495. // A VU meter will integrate to the new value to 99% in 300 ms.
  496. // The calculation here is very simplified and is more accurate
  497. // with higher frame-rate.
  498. float attack = float((currentMagnitude[channelNr] - displayMagnitude[channelNr]) *
  499. (timeSinceLastRedraw / magnitudeIntegrationTime) * 0.99);
  500. displayMagnitude[channelNr] =
  501. std::clamp(displayMagnitude[channelNr] + attack, (float)minimumLevel, 0.f);
  502. }
  503. }
  504. inline void VolumeMeter::calculateBallistics(uint64_t ts, qreal timeSinceLastRedraw)
  505. {
  506. QMutexLocker locker(&dataMutex);
  507. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++)
  508. calculateBallisticsForChannel(channelNr, ts, timeSinceLastRedraw);
  509. }
  510. void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width, int height, float peakHold)
  511. {
  512. QMutexLocker locker(&dataMutex);
  513. QColor color;
  514. if (peakHold < minimumInputLevel)
  515. color = backgroundNominalColor;
  516. else if (peakHold < warningLevel)
  517. color = foregroundNominalColor;
  518. else if (peakHold < errorLevel)
  519. color = foregroundWarningColor;
  520. else if (peakHold <= clipLevel)
  521. color = foregroundErrorColor;
  522. else
  523. color = clipColor;
  524. painter.fillRect(x, y, width, height, color);
  525. }
  526. void VolumeMeter::paintHTicks(QPainter &painter, int x, int y, int width)
  527. {
  528. qreal scale = width / minimumLevel;
  529. painter.setFont(tickFont);
  530. QFontMetrics metrics(tickFont);
  531. painter.setPen(majorTickColor);
  532. // Draw major tick lines and numeric indicators.
  533. for (int i = 0; i >= minimumLevel; i -= 5) {
  534. int position = int(x + width - (i * scale) - 1);
  535. QString str = QString::number(i);
  536. // Center the number on the tick, but don't overflow
  537. QRect textBounds = metrics.boundingRect(str);
  538. int pos;
  539. if (i == 0) {
  540. pos = position - textBounds.width();
  541. } else {
  542. pos = position - (textBounds.width() / 2);
  543. if (pos < 0)
  544. pos = 0;
  545. }
  546. painter.drawText(pos, y + 4 + metrics.capHeight(), str);
  547. painter.drawLine(position, y, position, y + 2);
  548. }
  549. }
  550. void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height)
  551. {
  552. qreal scale = height / minimumLevel;
  553. painter.setFont(tickFont);
  554. QFontMetrics metrics(tickFont);
  555. painter.setPen(majorTickColor);
  556. // Draw major tick lines and numeric indicators.
  557. for (int i = 0; i >= minimumLevel; i -= 5) {
  558. int position = y + int(i * scale) + METER_PADDING;
  559. QString str = QString::number(i);
  560. // Center the number on the tick, but don't overflow
  561. if (i == 0) {
  562. painter.drawText(x + 10, position + metrics.capHeight(), str);
  563. } else {
  564. painter.drawText(x + 8, position + (metrics.capHeight() / 2), str);
  565. }
  566. painter.drawLine(x, position, x + 2, position);
  567. }
  568. }
  569. #define CLIP_FLASH_DURATION_MS 1000
  570. inline int VolumeMeter::convertToInt(float number)
  571. {
  572. constexpr int min = std::numeric_limits<int>::min();
  573. constexpr int max = std::numeric_limits<int>::max();
  574. // NOTE: Conversion from 'const int' to 'float' changes max value from 2147483647 to 2147483648
  575. if (number >= (float)max)
  576. return max;
  577. else if (number < min)
  578. return min;
  579. else
  580. return int(number);
  581. }
  582. void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width, int height, float magnitude, float peak,
  583. float peakHold)
  584. {
  585. qreal scale = width / minimumLevel;
  586. QMutexLocker locker(&dataMutex);
  587. int minimumPosition = x + 0;
  588. int maximumPosition = x + width;
  589. int magnitudePosition = x + width - convertToInt(magnitude * scale);
  590. int peakPosition = x + width - convertToInt(peak * scale);
  591. int peakHoldPosition = x + width - convertToInt(peakHold * scale);
  592. int warningPosition = x + width - convertToInt(warningLevel * scale);
  593. int errorPosition = x + width - convertToInt(errorLevel * scale);
  594. int nominalLength = warningPosition - minimumPosition;
  595. int warningLength = errorPosition - warningPosition;
  596. int errorLength = maximumPosition - errorPosition;
  597. locker.unlock();
  598. if (clipping) {
  599. peakPosition = maximumPosition;
  600. }
  601. if (peakPosition < minimumPosition) {
  602. painter.fillRect(minimumPosition, y, nominalLength, height,
  603. muted ? backgroundNominalColorDisabled : backgroundNominalColor);
  604. painter.fillRect(warningPosition, y, warningLength, height,
  605. muted ? backgroundWarningColorDisabled : backgroundWarningColor);
  606. painter.fillRect(errorPosition, y, errorLength, height,
  607. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  608. } else if (peakPosition < warningPosition) {
  609. painter.fillRect(minimumPosition, y, peakPosition - minimumPosition, height,
  610. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  611. painter.fillRect(peakPosition, y, warningPosition - peakPosition, height,
  612. muted ? backgroundNominalColorDisabled : backgroundNominalColor);
  613. painter.fillRect(warningPosition, y, warningLength, height,
  614. muted ? backgroundWarningColorDisabled : backgroundWarningColor);
  615. painter.fillRect(errorPosition, y, errorLength, height,
  616. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  617. } else if (peakPosition < errorPosition) {
  618. painter.fillRect(minimumPosition, y, nominalLength, height,
  619. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  620. painter.fillRect(warningPosition, y, peakPosition - warningPosition, height,
  621. muted ? foregroundWarningColorDisabled : foregroundWarningColor);
  622. painter.fillRect(peakPosition, y, errorPosition - peakPosition, height,
  623. muted ? backgroundWarningColorDisabled : backgroundWarningColor);
  624. painter.fillRect(errorPosition, y, errorLength, height,
  625. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  626. } else if (peakPosition < maximumPosition) {
  627. painter.fillRect(minimumPosition, y, nominalLength, height,
  628. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  629. painter.fillRect(warningPosition, y, warningLength, height,
  630. muted ? foregroundWarningColorDisabled : foregroundWarningColor);
  631. painter.fillRect(errorPosition, y, peakPosition - errorPosition, height,
  632. muted ? foregroundErrorColorDisabled : foregroundErrorColor);
  633. painter.fillRect(peakPosition, y, maximumPosition - peakPosition, height,
  634. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  635. } else {
  636. if (!clipping) {
  637. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, [&]() { clipping = false; });
  638. clipping = true;
  639. }
  640. int end = errorLength + warningLength + nominalLength;
  641. painter.fillRect(minimumPosition, y, end, height,
  642. QBrush(muted ? foregroundErrorColorDisabled : foregroundErrorColor));
  643. }
  644. if (peakHoldPosition - 3 < minimumPosition)
  645. ; // Peak-hold below minimum, no drawing.
  646. else if (peakHoldPosition < warningPosition)
  647. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  648. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  649. else if (peakHoldPosition < errorPosition)
  650. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  651. muted ? foregroundWarningColorDisabled : foregroundWarningColor);
  652. else
  653. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  654. muted ? foregroundErrorColorDisabled : foregroundErrorColor);
  655. if (magnitudePosition - 3 >= minimumPosition)
  656. painter.fillRect(magnitudePosition - 3, y, 3, height, magnitudeColor);
  657. }
  658. void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width, int height, float magnitude, float peak,
  659. float peakHold)
  660. {
  661. qreal scale = height / minimumLevel;
  662. QMutexLocker locker(&dataMutex);
  663. int minimumPosition = y + 0;
  664. int maximumPosition = y + height;
  665. int magnitudePosition = y + height - convertToInt(magnitude * scale);
  666. int peakPosition = y + height - convertToInt(peak * scale);
  667. int peakHoldPosition = y + height - convertToInt(peakHold * scale);
  668. int warningPosition = y + height - convertToInt(warningLevel * scale);
  669. int errorPosition = y + height - convertToInt(errorLevel * scale);
  670. int nominalLength = warningPosition - minimumPosition;
  671. int warningLength = errorPosition - warningPosition;
  672. int errorLength = maximumPosition - errorPosition;
  673. locker.unlock();
  674. if (clipping) {
  675. peakPosition = maximumPosition;
  676. }
  677. if (peakPosition < minimumPosition) {
  678. painter.fillRect(x, minimumPosition, width, nominalLength,
  679. muted ? backgroundNominalColorDisabled : backgroundNominalColor);
  680. painter.fillRect(x, warningPosition, width, warningLength,
  681. muted ? backgroundWarningColorDisabled : backgroundWarningColor);
  682. painter.fillRect(x, errorPosition, width, errorLength,
  683. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  684. } else if (peakPosition < warningPosition) {
  685. painter.fillRect(x, minimumPosition, width, peakPosition - minimumPosition,
  686. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  687. painter.fillRect(x, peakPosition, width, warningPosition - peakPosition,
  688. muted ? backgroundNominalColorDisabled : backgroundNominalColor);
  689. painter.fillRect(x, warningPosition, width, warningLength,
  690. muted ? backgroundWarningColorDisabled : backgroundWarningColor);
  691. painter.fillRect(x, errorPosition, width, errorLength,
  692. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  693. } else if (peakPosition < errorPosition) {
  694. painter.fillRect(x, minimumPosition, width, nominalLength,
  695. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  696. painter.fillRect(x, warningPosition, width, peakPosition - warningPosition,
  697. muted ? foregroundWarningColorDisabled : foregroundWarningColor);
  698. painter.fillRect(x, peakPosition, width, errorPosition - peakPosition,
  699. muted ? backgroundWarningColorDisabled : backgroundWarningColor);
  700. painter.fillRect(x, errorPosition, width, errorLength,
  701. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  702. } else if (peakPosition < maximumPosition) {
  703. painter.fillRect(x, minimumPosition, width, nominalLength,
  704. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  705. painter.fillRect(x, warningPosition, width, warningLength,
  706. muted ? foregroundWarningColorDisabled : foregroundWarningColor);
  707. painter.fillRect(x, errorPosition, width, peakPosition - errorPosition,
  708. muted ? foregroundErrorColorDisabled : foregroundErrorColor);
  709. painter.fillRect(x, peakPosition, width, maximumPosition - peakPosition,
  710. muted ? backgroundErrorColorDisabled : backgroundErrorColor);
  711. } else {
  712. if (!clipping) {
  713. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, [&]() { clipping = false; });
  714. clipping = true;
  715. }
  716. int end = errorLength + warningLength + nominalLength;
  717. painter.fillRect(x, minimumPosition, width, end,
  718. QBrush(muted ? foregroundErrorColorDisabled : foregroundErrorColor));
  719. }
  720. if (peakHoldPosition - 3 < minimumPosition)
  721. ; // Peak-hold below minimum, no drawing.
  722. else if (peakHoldPosition < warningPosition)
  723. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  724. muted ? foregroundNominalColorDisabled : foregroundNominalColor);
  725. else if (peakHoldPosition < errorPosition)
  726. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  727. muted ? foregroundWarningColorDisabled : foregroundWarningColor);
  728. else
  729. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  730. muted ? foregroundErrorColorDisabled : foregroundErrorColor);
  731. if (magnitudePosition - 3 >= minimumPosition)
  732. painter.fillRect(x, magnitudePosition - 3, width, 3, magnitudeColor);
  733. }
  734. void VolumeMeter::paintEvent(QPaintEvent *event)
  735. {
  736. uint64_t ts = os_gettime_ns();
  737. qreal timeSinceLastRedraw = (ts - lastRedrawTime) * 0.000000001;
  738. calculateBallistics(ts, timeSinceLastRedraw);
  739. bool idle = detectIdle(ts);
  740. QRect widgetRect = rect();
  741. int width = widgetRect.width();
  742. int height = widgetRect.height();
  743. QPainter painter(this);
  744. // Paint window background color (as widget is opaque)
  745. QColor background = palette().color(QPalette::ColorRole::Window);
  746. painter.fillRect(event->region().boundingRect(), background);
  747. if (vertical)
  748. height -= METER_PADDING * 2;
  749. // timerEvent requests update of the bar(s) only, so we can avoid the
  750. // overhead of repainting the scale and labels.
  751. if (event->region().boundingRect() != getBarRect()) {
  752. if (needLayoutChange())
  753. doLayout();
  754. if (vertical) {
  755. paintVTicks(painter, displayNrAudioChannels * (meterThickness + 1) - 1, 0,
  756. height - (INDICATOR_THICKNESS + 3));
  757. } else {
  758. paintHTicks(painter, INDICATOR_THICKNESS + 3, displayNrAudioChannels * (meterThickness + 1) - 1,
  759. width - (INDICATOR_THICKNESS + 3));
  760. }
  761. }
  762. if (vertical) {
  763. // Invert the Y axis to ease the math
  764. painter.translate(0, height + METER_PADDING);
  765. painter.scale(1, -1);
  766. }
  767. for (int channelNr = 0; channelNr < displayNrAudioChannels; channelNr++) {
  768. int channelNrFixed = (displayNrAudioChannels == 1 && channels > 2) ? 2 : channelNr;
  769. if (vertical)
  770. paintVMeter(painter, channelNr * (meterThickness + 1), INDICATOR_THICKNESS + 2, meterThickness,
  771. height - (INDICATOR_THICKNESS + 2), displayMagnitude[channelNrFixed],
  772. displayPeak[channelNrFixed], displayPeakHold[channelNrFixed]);
  773. else
  774. paintHMeter(painter, INDICATOR_THICKNESS + 2, channelNr * (meterThickness + 1),
  775. width - (INDICATOR_THICKNESS + 2), meterThickness, displayMagnitude[channelNrFixed],
  776. displayPeak[channelNrFixed], displayPeakHold[channelNrFixed]);
  777. if (idle)
  778. continue;
  779. // By not drawing the input meter boxes the user can
  780. // see that the audio stream has been stopped, without
  781. // having too much visual impact.
  782. if (vertical)
  783. paintInputMeter(painter, channelNr * (meterThickness + 1), 0, meterThickness,
  784. INDICATOR_THICKNESS, displayInputPeakHold[channelNrFixed]);
  785. else
  786. paintInputMeter(painter, 0, channelNr * (meterThickness + 1), INDICATOR_THICKNESS,
  787. meterThickness, displayInputPeakHold[channelNrFixed]);
  788. }
  789. lastRedrawTime = ts;
  790. }
  791. QRect VolumeMeter::getBarRect() const
  792. {
  793. QRect rec = rect();
  794. if (vertical)
  795. rec.setWidth(displayNrAudioChannels * (meterThickness + 1) - 1);
  796. else
  797. rec.setHeight(displayNrAudioChannels * (meterThickness + 1) - 1);
  798. return rec;
  799. }
  800. void VolumeMeter::changeEvent(QEvent *e)
  801. {
  802. if (e->type() == QEvent::StyleChange)
  803. recalculateLayout = true;
  804. QWidget::changeEvent(e);
  805. }