VolumeMeter.cpp 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. bool forceUpdate = true;
  229. updateBackgroundCache(forceUpdate);
  230. }
  231. VolumeMeter::VolumeMeter(QWidget *parent, obs_source_t *source)
  232. : QWidget(parent),
  233. weakSource(OBSGetWeakRef(source)),
  234. obsVolumeMeter(obs_volmeter_create(OBS_FADER_LOG))
  235. {
  236. setAttribute(Qt::WA_OpaquePaintEvent, true);
  237. setAttribute(Qt::WA_TransparentForMouseEvents);
  238. setFocusPolicy(Qt::NoFocus);
  239. // Default meter settings, they only show if
  240. // there is no stylesheet, do not remove.
  241. backgroundNominalColor.setRgb(0x26, 0x7f, 0x26); // Dark green
  242. backgroundWarningColor.setRgb(0x7f, 0x7f, 0x26); // Dark yellow
  243. backgroundErrorColor.setRgb(0x7f, 0x26, 0x26); // Dark red
  244. foregroundNominalColor.setRgb(0x4c, 0xff, 0x4c); // Bright green
  245. foregroundWarningColor.setRgb(0xff, 0xff, 0x4c); // Bright yellow
  246. foregroundErrorColor.setRgb(0xff, 0x4c, 0x4c); // Bright red
  247. backgroundNominalColorDisabled.setRgb(90, 90, 90);
  248. backgroundWarningColorDisabled.setRgb(117, 117, 117);
  249. backgroundErrorColorDisabled.setRgb(65, 65, 65);
  250. foregroundNominalColorDisabled.setRgb(163, 163, 163);
  251. foregroundWarningColorDisabled.setRgb(217, 217, 217);
  252. foregroundErrorColorDisabled.setRgb(113, 113, 113);
  253. clipColor.setRgb(0xff, 0xff, 0xff); // Bright white
  254. magnitudeColor.setRgb(0x00, 0x00, 0x00); // Black
  255. majorTickColor.setRgb(0x00, 0x00, 0x00); // Black
  256. minorTickColor.setRgb(0x32, 0x32, 0x32); // Dark gray
  257. minimumLevel = -60.0; // -60 dB
  258. warningLevel = -20.0; // -20 dB
  259. errorLevel = -9.0; // -9 dB
  260. clipLevel = 0.0; // 0 dB
  261. minimumInputLevel = -50.0; // -50 dB
  262. peakDecayRate = 11.76; // 20 dB / 1.7 sec
  263. magnitudeIntegrationTime = 0.3; // 99% in 300 ms
  264. peakHoldDuration = 20.0; // 20 seconds
  265. inputPeakHoldDuration = 1.0; // 1 second
  266. meterThickness = 3; // Bar thickness in pixels
  267. meterFontScaling = 0.8; // Font size for numbers is 80% of Widget's font size
  268. channels = (int)audio_output_get_channels(obs_get_audio());
  269. obs_volmeter_add_callback(obsVolumeMeter, obsVolMeterChanged, this);
  270. obs_volmeter_attach_source(obsVolumeMeter, source);
  271. destroyedSignal =
  272. OBSSignal(obs_source_get_signal_handler(source), "destroy", &VolumeMeter::obsSourceDestroyed, this);
  273. doLayout();
  274. if (!updateTimer) {
  275. updateTimer = new QTimer(qApp);
  276. updateTimer->setTimerType(Qt::PreciseTimer);
  277. updateTimer->start(16);
  278. }
  279. connect(updateTimer, &QTimer::timeout, this, [this]() {
  280. if (needLayoutChange()) {
  281. doLayout();
  282. update();
  283. } else {
  284. update(getBarRect());
  285. }
  286. });
  287. connect(App(), &OBSApp::StyleChanged, this, &VolumeMeter::doLayout);
  288. }
  289. VolumeMeter::~VolumeMeter()
  290. {
  291. obs_volmeter_remove_callback(obsVolumeMeter, obsVolMeterChanged, this);
  292. obs_volmeter_detach_source(obsVolumeMeter);
  293. }
  294. void VolumeMeter::obsSourceDestroyed(void *data, calldata_t *)
  295. {
  296. VolumeMeter *self = static_cast<VolumeMeter *>(data);
  297. QMetaObject::invokeMethod(self, "handleSourceDestroyed", Qt::QueuedConnection);
  298. }
  299. void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS], const float peak[MAX_AUDIO_CHANNELS],
  300. const float inputPeak[MAX_AUDIO_CHANNELS])
  301. {
  302. uint64_t ts = os_gettime_ns();
  303. QMutexLocker locker(&dataMutex);
  304. currentLastUpdateTime = ts;
  305. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  306. currentMagnitude[channelNr] = magnitude[channelNr];
  307. currentPeak[channelNr] = peak[channelNr];
  308. currentInputPeak[channelNr] = inputPeak[channelNr];
  309. }
  310. // In case there are more updates then redraws we must make sure
  311. // that the ballistics of peak and hold are recalculated.
  312. locker.unlock();
  313. calculateBallistics(ts);
  314. }
  315. void VolumeMeter::obsVolMeterChanged(void *data, const float magnitude[MAX_AUDIO_CHANNELS],
  316. const float peak[MAX_AUDIO_CHANNELS], const float inputPeak[MAX_AUDIO_CHANNELS])
  317. {
  318. VolumeMeter *meter = static_cast<VolumeMeter *>(data);
  319. meter->setLevels(magnitude, peak, inputPeak);
  320. }
  321. inline void VolumeMeter::resetLevels()
  322. {
  323. currentLastUpdateTime = 0;
  324. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  325. currentMagnitude[channelNr] = -M_INFINITE;
  326. currentPeak[channelNr] = -M_INFINITE;
  327. currentInputPeak[channelNr] = -M_INFINITE;
  328. displayMagnitude[channelNr] = -M_INFINITE;
  329. displayPeak[channelNr] = -M_INFINITE;
  330. displayPeakHold[channelNr] = -M_INFINITE;
  331. displayPeakHoldLastUpdateTime[channelNr] = 0;
  332. displayInputPeakHold[channelNr] = -M_INFINITE;
  333. displayInputPeakHoldLastUpdateTime[channelNr] = 0;
  334. }
  335. }
  336. bool VolumeMeter::needLayoutChange()
  337. {
  338. int currentNrAudioChannels = obs_volmeter_get_nr_channels(obsVolumeMeter);
  339. if (!currentNrAudioChannels) {
  340. struct obs_audio_info oai;
  341. obs_get_audio_info(&oai);
  342. currentNrAudioChannels = (oai.speakers == SPEAKERS_MONO) ? 1 : 2;
  343. }
  344. if (displayNrAudioChannels != currentNrAudioChannels) {
  345. displayNrAudioChannels = currentNrAudioChannels;
  346. return true;
  347. }
  348. return false;
  349. }
  350. void VolumeMeter::setVertical(bool vertical_)
  351. {
  352. if (vertical == vertical_) {
  353. return;
  354. }
  355. vertical = vertical_;
  356. doLayout();
  357. }
  358. void VolumeMeter::setUseDisabledColors(bool enable)
  359. {
  360. if (useDisabledColors == enable) {
  361. return;
  362. }
  363. useDisabledColors = enable;
  364. bool forceUpdate = true;
  365. updateBackgroundCache(forceUpdate);
  366. }
  367. void VolumeMeter::setMuted(bool mute)
  368. {
  369. if (muted == mute) {
  370. return;
  371. }
  372. muted = mute;
  373. }
  374. void VolumeMeter::refreshColors()
  375. {
  376. setBackgroundNominalColor(getBackgroundNominalColor());
  377. setBackgroundWarningColor(getBackgroundWarningColor());
  378. setBackgroundErrorColor(getBackgroundErrorColor());
  379. setForegroundNominalColor(getForegroundNominalColor());
  380. setForegroundWarningColor(getForegroundWarningColor());
  381. setForegroundErrorColor(getForegroundErrorColor());
  382. bool forceUpdate = true;
  383. updateBackgroundCache(forceUpdate);
  384. }
  385. QRect VolumeMeter::getBarRect() const
  386. {
  387. QRect barRect = rect();
  388. if (vertical) {
  389. barRect.setWidth(displayNrAudioChannels * (meterThickness + 1) - 1);
  390. } else {
  391. barRect.setHeight(displayNrAudioChannels * (meterThickness + 1) - 1);
  392. }
  393. return barRect;
  394. }
  395. // When this is called from the constructor, obs_volmeter_get_nr_channels has not
  396. // yet been called and Q_PROPERTY settings have not yet been read from the
  397. // stylesheet.
  398. inline void VolumeMeter::doLayout()
  399. {
  400. QMutexLocker locker(&dataMutex);
  401. if (displayNrAudioChannels) {
  402. int meterSize = std::floor(22 / displayNrAudioChannels);
  403. meterThickness = std::clamp(meterSize, 3, 6);
  404. }
  405. tickFont = font();
  406. QFontInfo info(tickFont);
  407. tickFont.setPointSizeF(info.pointSizeF() * meterFontScaling);
  408. QFontMetrics metrics(tickFont);
  409. // This is a quick and naive assumption for widest potential tick label.
  410. tickTextTokenRect = metrics.boundingRect(" -88 ");
  411. updateBackgroundCache();
  412. resetLevels();
  413. updateGeometry();
  414. }
  415. inline bool VolumeMeter::detectIdle(uint64_t ts)
  416. {
  417. double secondsSinceLastUpdate = (ts - currentLastUpdateTime) * 0.000000001;
  418. if (secondsSinceLastUpdate > 0.5) {
  419. resetLevels();
  420. return true;
  421. } else {
  422. return false;
  423. }
  424. }
  425. inline void VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, qreal timeSinceLastRedraw)
  426. {
  427. if (currentPeak[channelNr] >= displayPeak[channelNr] || isnan(displayPeak[channelNr])) {
  428. // Attack of peak is immediate.
  429. displayPeak[channelNr] = currentPeak[channelNr];
  430. } else {
  431. // Decay of peak is 40 dB / 1.7 seconds for Fast Profile
  432. // 20 dB / 1.7 seconds for Medium Profile (Type I PPM)
  433. // 24 dB / 2.8 seconds for Slow Profile (Type II PPM)
  434. float decay = float(peakDecayRate * timeSinceLastRedraw);
  435. displayPeak[channelNr] =
  436. std::clamp(displayPeak[channelNr] - decay, std::min(currentPeak[channelNr], 0.f), 0.f);
  437. }
  438. if (currentPeak[channelNr] >= displayPeakHold[channelNr] || !isfinite(displayPeakHold[channelNr])) {
  439. // Attack of peak-hold is immediate, but keep track
  440. // when it was last updated.
  441. displayPeakHold[channelNr] = currentPeak[channelNr];
  442. displayPeakHoldLastUpdateTime[channelNr] = ts;
  443. } else {
  444. // The peak and hold falls back to peak
  445. // after 20 seconds.
  446. qreal timeSinceLastPeak = (uint64_t)(ts - displayPeakHoldLastUpdateTime[channelNr]) * 0.000000001;
  447. if (timeSinceLastPeak > peakHoldDuration) {
  448. displayPeakHold[channelNr] = currentPeak[channelNr];
  449. displayPeakHoldLastUpdateTime[channelNr] = ts;
  450. }
  451. }
  452. if (currentInputPeak[channelNr] >= displayInputPeakHold[channelNr] ||
  453. !isfinite(displayInputPeakHold[channelNr])) {
  454. // Attack of peak-hold is immediate, but keep track
  455. // when it was last updated.
  456. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  457. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  458. } else {
  459. // The peak and hold falls back to peak after 1 second.
  460. qreal timeSinceLastPeak = (uint64_t)(ts - displayInputPeakHoldLastUpdateTime[channelNr]) * 0.000000001;
  461. if (timeSinceLastPeak > inputPeakHoldDuration) {
  462. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  463. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  464. }
  465. }
  466. if (!isfinite(displayMagnitude[channelNr])) {
  467. // The statements in the else-leg do not work with
  468. // NaN and infinite displayMagnitude.
  469. displayMagnitude[channelNr] = currentMagnitude[channelNr];
  470. } else {
  471. // A VU meter will integrate to the new value to 99% in 300 ms.
  472. // The calculation here is very simplified and is more accurate
  473. // with higher frame-rate.
  474. float attack = float((currentMagnitude[channelNr] - displayMagnitude[channelNr]) *
  475. (timeSinceLastRedraw / magnitudeIntegrationTime) * 0.99);
  476. displayMagnitude[channelNr] =
  477. std::clamp(displayMagnitude[channelNr] + attack, (float)minimumLevel, 0.f);
  478. }
  479. }
  480. inline void VolumeMeter::calculateBallistics(uint64_t ts, qreal timeSinceLastRedraw)
  481. {
  482. QMutexLocker locker(&dataMutex);
  483. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  484. calculateBallisticsForChannel(channelNr, ts, timeSinceLastRedraw);
  485. }
  486. }
  487. QColor VolumeMeter::getPeakColor(float peakHold)
  488. {
  489. QColor color;
  490. if (peakHold < minimumInputLevel) {
  491. color = backgroundNominalColor;
  492. } else if (peakHold < warningLevel) {
  493. color = foregroundNominalColor;
  494. } else if (peakHold < errorLevel) {
  495. color = foregroundWarningColor;
  496. } else if (peakHold < clipLevel) {
  497. color = foregroundErrorColor;
  498. } else {
  499. color = clipColor;
  500. }
  501. return color;
  502. }
  503. void VolumeMeter::paintHTicks(QPainter &painter, int x, int y, int width)
  504. {
  505. qreal scale = width / minimumLevel;
  506. painter.setFont(tickFont);
  507. QFontMetrics metrics(tickFont);
  508. painter.setPen(majorTickColor);
  509. // Draw major tick lines and numeric indicators.
  510. for (int i = 0; i >= minimumLevel; i -= TICK_DB_INTERVAL) {
  511. int position = int(x + width - (i * scale) - 1);
  512. QString str = QString::number(i);
  513. // Center the number on the tick, but don't overflow
  514. QRect textBounds = metrics.boundingRect(str);
  515. int pos;
  516. if (i == 0) {
  517. pos = position - textBounds.width();
  518. } else {
  519. pos = position - (textBounds.width() / 2);
  520. if (pos < 0) {
  521. pos = 0;
  522. }
  523. }
  524. painter.drawText(pos, y + 4 + metrics.capHeight(), str);
  525. painter.drawLine(position, y, position, y + TICK_SIZE);
  526. }
  527. }
  528. void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height)
  529. {
  530. qreal scale = height / minimumLevel;
  531. painter.setFont(tickFont);
  532. QFontMetrics metrics(tickFont);
  533. painter.setPen(majorTickColor);
  534. // Draw major tick lines and numeric indicators.
  535. for (int i = 0; i >= minimumLevel; i -= TICK_DB_INTERVAL) {
  536. int position = y + int(i * scale);
  537. QString str = QString::number(i);
  538. // Center the number on the tick, but don't overflow
  539. if (i == 0) {
  540. painter.drawText(x + 10, position + metrics.capHeight(), str);
  541. } else {
  542. painter.drawText(x + 8, position + (metrics.capHeight() / 2), str);
  543. }
  544. painter.drawLine(x, position, x + TICK_SIZE, position);
  545. }
  546. }
  547. void VolumeMeter::updateBackgroundCache(bool force)
  548. {
  549. if (!force && !size().isValid()) {
  550. return;
  551. }
  552. if (!force && backgroundCache.size() == size() && !backgroundCache.isNull()) {
  553. return;
  554. }
  555. if (!force && displayNrAudioChannels <= 0) {
  556. return;
  557. }
  558. QColor backgroundColor = palette().color(QPalette::Window);
  559. backgroundCache = QPixmap(size() * devicePixelRatioF());
  560. backgroundCache.setDevicePixelRatio(devicePixelRatioF());
  561. backgroundCache.fill(backgroundColor);
  562. QPainter bg{&backgroundCache};
  563. QRect widgetRect = rect();
  564. // Draw ticks
  565. if (vertical) {
  566. paintVTicks(bg, displayNrAudioChannels * (meterThickness + 1) - 1, 0,
  567. widgetRect.height() - (INDICATOR_THICKNESS + 3));
  568. } else {
  569. paintHTicks(bg, INDICATOR_THICKNESS + 3, displayNrAudioChannels * (meterThickness + 1) - 1,
  570. widgetRect.width() - (INDICATOR_THICKNESS + 3));
  571. }
  572. // Draw meter backgrounds
  573. bool disabledColors = muted || useDisabledColors;
  574. QColor nominal = disabledColors ? backgroundNominalColorDisabled : backgroundNominalColor;
  575. QColor warning = disabledColors ? backgroundWarningColorDisabled : backgroundWarningColor;
  576. QColor error = disabledColors ? backgroundErrorColorDisabled : backgroundErrorColor;
  577. int meterStart = INDICATOR_THICKNESS + 2;
  578. int meterLength = vertical ? rect().height() - (INDICATOR_THICKNESS + 2)
  579. : rect().width() - (INDICATOR_THICKNESS + 2);
  580. qreal scale = meterLength / minimumLevel;
  581. int warningPosition = meterLength - convertToInt(warningLevel * scale);
  582. int errorPosition = meterLength - convertToInt(errorLevel * scale);
  583. int nominalLength = warningPosition;
  584. int warningLength = nominalLength + (errorPosition - warningPosition);
  585. for (int channelNr = 0; channelNr < displayNrAudioChannels; channelNr++) {
  586. int channelOffset = channelNr * (meterThickness + 1);
  587. if (vertical) {
  588. bg.fillRect(channelOffset, meterLength, meterThickness, -meterLength, error);
  589. bg.fillRect(channelOffset, meterLength, meterThickness, -warningLength, warning);
  590. bg.fillRect(channelOffset, meterLength, meterThickness, -nominalLength, nominal);
  591. } else {
  592. bg.fillRect(meterStart, channelOffset, meterLength, meterThickness, error);
  593. bg.fillRect(meterStart, channelOffset, warningLength, meterThickness, warning);
  594. bg.fillRect(meterStart, channelOffset, nominalLength, meterThickness, nominal);
  595. }
  596. }
  597. }
  598. inline int VolumeMeter::convertToInt(float number)
  599. {
  600. constexpr int min = std::numeric_limits<int>::min();
  601. constexpr int max = std::numeric_limits<int>::max();
  602. // NOTE: Conversion from 'const int' to 'float' changes max value from 2147483647 to 2147483648
  603. if (number >= (float)max) {
  604. return max;
  605. } else if (number < min) {
  606. return min;
  607. } else {
  608. return int(number);
  609. }
  610. }
  611. void VolumeMeter::paintEvent(QPaintEvent *)
  612. {
  613. uint64_t ts = os_gettime_ns();
  614. qreal timeSinceLastRedraw = (ts - lastRedrawTime) * 0.000000001;
  615. calculateBallistics(ts, timeSinceLastRedraw);
  616. bool idle = detectIdle(ts);
  617. QPainter painter(this);
  618. bool disabledColors = muted || useDisabledColors;
  619. QColor nominal = disabledColors ? foregroundNominalColorDisabled : foregroundNominalColor;
  620. QColor warning = disabledColors ? foregroundWarningColorDisabled : foregroundWarningColor;
  621. QColor error = disabledColors ? foregroundErrorColorDisabled : foregroundErrorColor;
  622. int meterStart = INDICATOR_THICKNESS + 2;
  623. int meterLength = vertical ? rect().height() - (INDICATOR_THICKNESS + 2)
  624. : rect().width() - (INDICATOR_THICKNESS + 2);
  625. const qreal scale = meterLength / minimumLevel;
  626. // Paint cached background pixmap
  627. painter.drawPixmap(0, 0, backgroundCache);
  628. // Draw dynamic audio meter bars
  629. int warningPosition = meterLength - convertToInt(warningLevel * scale);
  630. int errorPosition = meterLength - convertToInt(errorLevel * scale);
  631. int clipPosition = meterLength - convertToInt(clipLevel * scale);
  632. int nominalLength = warningPosition;
  633. int warningLength = nominalLength + (errorPosition - warningPosition);
  634. for (int channelNr = 0; channelNr < displayNrAudioChannels; channelNr++) {
  635. int channelNrFixed = (displayNrAudioChannels == 1 && channels > 2) ? 2 : channelNr;
  636. QMutexLocker locker(&dataMutex);
  637. float peak = displayPeak[channelNrFixed];
  638. float peakHold = displayPeakHold[channelNrFixed];
  639. float magnitude = displayMagnitude[channelNrFixed];
  640. int peakPosition = meterLength - convertToInt(peak * scale);
  641. int peakHoldPosition = meterLength - convertToInt(peakHold * scale);
  642. int magnitudePosition = meterLength - convertToInt(magnitude * scale);
  643. locker.unlock();
  644. if (clipping) {
  645. peakPosition = meterLength;
  646. }
  647. auto fill = [&](int pos, int length, const QColor &color) {
  648. if (vertical) {
  649. painter.fillRect(pos, meterLength, meterThickness, -length, color);
  650. } else {
  651. painter.fillRect(meterStart, pos, length, meterThickness, color);
  652. }
  653. };
  654. int channelOffset = channelNr * (meterThickness + 1);
  655. // Draw audio meter peak bars
  656. if (peakPosition >= clipPosition) {
  657. if (!clipping) {
  658. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, [&]() { clipping = false; });
  659. clipping = true;
  660. }
  661. fill(channelOffset, meterLength, error);
  662. } else {
  663. if (peakPosition > errorPosition) {
  664. fill(channelOffset, std::min(peakPosition, meterLength), error);
  665. }
  666. if (peakPosition > warningPosition) {
  667. fill(channelOffset, std::min(peakPosition, warningLength), warning);
  668. }
  669. if (peakPosition > meterStart) {
  670. fill(channelOffset, std::min(peakPosition, nominalLength), nominal);
  671. }
  672. }
  673. // Draw peak hold indicators
  674. QColor peakHoldColor = nominal;
  675. if (peakHoldPosition >= errorPosition) {
  676. peakHoldColor = error;
  677. } else if (peakHoldPosition >= warningPosition) {
  678. peakHoldColor = warning;
  679. }
  680. if (peakHoldPosition - 3 > 0) {
  681. if (vertical) {
  682. painter.fillRect(channelOffset, meterLength - peakHoldPosition - 3, meterThickness, 3,
  683. peakHoldColor);
  684. } else {
  685. painter.fillRect(meterStart + peakHoldPosition - 3, channelOffset, 3, meterThickness,
  686. peakHoldColor);
  687. }
  688. }
  689. // Draw magnitude indicator
  690. if (magnitudePosition - 3 >= 0) {
  691. if (vertical) {
  692. painter.fillRect(channelOffset, meterLength - magnitudePosition - 3, meterThickness, 3,
  693. magnitudeColor);
  694. } else {
  695. painter.fillRect(meterStart + magnitudePosition - 3, channelOffset, 3, meterThickness,
  696. magnitudeColor);
  697. }
  698. }
  699. if (idle) {
  700. continue;
  701. }
  702. // Draw audio input indicator
  703. if (vertical) {
  704. painter.fillRect(channelOffset, rect().height(), meterThickness, -INDICATOR_THICKNESS,
  705. getPeakColor(displayInputPeakHold[channelNrFixed]));
  706. } else {
  707. painter.fillRect(0, channelOffset, INDICATOR_THICKNESS, meterThickness,
  708. getPeakColor(displayInputPeakHold[channelNrFixed]));
  709. }
  710. }
  711. lastRedrawTime = ts;
  712. }
  713. void VolumeMeter::resizeEvent(QResizeEvent *event)
  714. {
  715. updateBackgroundCache();
  716. return QWidget::resizeEvent(event);
  717. }
  718. void VolumeMeter::mousePressEvent(QMouseEvent *event)
  719. {
  720. setFocus(Qt::MouseFocusReason);
  721. event->accept();
  722. }
  723. void VolumeMeter::wheelEvent(QWheelEvent *event)
  724. {
  725. QApplication::sendEvent(focusProxy(), event);
  726. }
  727. QSize VolumeMeter::minimumSizeHint() const
  728. {
  729. return sizeHint();
  730. }
  731. QSize VolumeMeter::sizeHint() const
  732. {
  733. QRect meterRect = getBarRect();
  734. int labelTotal = std::abs(minimumLevel / TICK_DB_INTERVAL) + 1;
  735. if (vertical) {
  736. int width = meterRect.width() + tickTextTokenRect.width() + TICK_SIZE + 10;
  737. int height = (labelTotal * tickTextTokenRect.height()) + INDICATOR_THICKNESS;
  738. return QSize(width, height * 1.1);
  739. } else {
  740. int width = (labelTotal * tickTextTokenRect.width()) + INDICATOR_THICKNESS;
  741. int height = meterRect.height() + tickTextTokenRect.height();
  742. return QSize(width * 1.1, height);
  743. }
  744. }