VolumeMeter.cpp 25 KB

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