volume-control.cpp 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111
  1. #include "volume-control.hpp"
  2. #include "qt-wrappers.hpp"
  3. #include "obs-app.hpp"
  4. #include "mute-checkbox.hpp"
  5. #include "slider-ignorewheel.hpp"
  6. #include "slider-absoluteset-style.hpp"
  7. #include <QFontDatabase>
  8. #include <QHBoxLayout>
  9. #include <QPushButton>
  10. #include <QLabel>
  11. #include <QPainter>
  12. #include <QStyleFactory>
  13. using namespace std;
  14. #define CLAMP(x, min, max) ((x) < (min) ? (min) : ((x) > (max) ? (max) : (x)))
  15. #define FADER_PRECISION 4096.0
  16. QWeakPointer<VolumeMeterTimer> VolumeMeter::updateTimer;
  17. void VolControl::OBSVolumeChanged(void *data, float db)
  18. {
  19. Q_UNUSED(db);
  20. VolControl *volControl = static_cast<VolControl *>(data);
  21. QMetaObject::invokeMethod(volControl, "VolumeChanged");
  22. }
  23. void VolControl::OBSVolumeLevel(void *data,
  24. const float magnitude[MAX_AUDIO_CHANNELS],
  25. const float peak[MAX_AUDIO_CHANNELS],
  26. const float inputPeak[MAX_AUDIO_CHANNELS])
  27. {
  28. VolControl *volControl = static_cast<VolControl *>(data);
  29. volControl->volMeter->setLevels(magnitude, peak, inputPeak);
  30. }
  31. void VolControl::OBSVolumeMuted(void *data, calldata_t *calldata)
  32. {
  33. VolControl *volControl = static_cast<VolControl *>(data);
  34. bool muted = calldata_bool(calldata, "muted");
  35. QMetaObject::invokeMethod(volControl, "VolumeMuted",
  36. Q_ARG(bool, muted));
  37. }
  38. void VolControl::VolumeChanged()
  39. {
  40. slider->blockSignals(true);
  41. slider->setValue(
  42. (int)(obs_fader_get_deflection(obs_fader) * FADER_PRECISION));
  43. slider->blockSignals(false);
  44. updateText();
  45. }
  46. void VolControl::VolumeMuted(bool muted)
  47. {
  48. if (mute->isChecked() != muted)
  49. mute->setChecked(muted);
  50. }
  51. void VolControl::SetMuted(bool checked)
  52. {
  53. obs_source_set_muted(source, checked);
  54. }
  55. void VolControl::SliderChanged(int vol)
  56. {
  57. obs_fader_set_deflection(obs_fader, float(vol) / FADER_PRECISION);
  58. updateText();
  59. }
  60. void VolControl::updateText()
  61. {
  62. QString text;
  63. float db = obs_fader_get_db(obs_fader);
  64. if (db < -96.0f)
  65. text = "-inf dB";
  66. else
  67. text = QString::number(db, 'f', 1).append(" dB");
  68. volLabel->setText(text);
  69. bool muted = obs_source_muted(source);
  70. const char *accTextLookup = muted ? "VolControl.SliderMuted"
  71. : "VolControl.SliderUnmuted";
  72. QString sourceName = obs_source_get_name(source);
  73. QString accText = QTStr(accTextLookup).arg(sourceName, db);
  74. slider->setAccessibleName(accText);
  75. }
  76. QString VolControl::GetName() const
  77. {
  78. return nameLabel->text();
  79. }
  80. void VolControl::SetName(const QString &newName)
  81. {
  82. nameLabel->setText(newName);
  83. }
  84. void VolControl::EmitConfigClicked()
  85. {
  86. emit ConfigClicked();
  87. }
  88. void VolControl::SetMeterDecayRate(qreal q)
  89. {
  90. volMeter->setPeakDecayRate(q);
  91. }
  92. void VolControl::setPeakMeterType(enum obs_peak_meter_type peakMeterType)
  93. {
  94. volMeter->setPeakMeterType(peakMeterType);
  95. }
  96. VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical)
  97. : source(std::move(source_)),
  98. levelTotal(0.0f),
  99. levelCount(0.0f),
  100. obs_fader(obs_fader_create(OBS_FADER_LOG)),
  101. obs_volmeter(obs_volmeter_create(OBS_FADER_LOG)),
  102. vertical(vertical)
  103. {
  104. nameLabel = new QLabel();
  105. volLabel = new QLabel();
  106. mute = new MuteCheckBox();
  107. QString sourceName = obs_source_get_name(source);
  108. setObjectName(sourceName);
  109. if (showConfig) {
  110. config = new QPushButton(this);
  111. config->setProperty("themeID", "configIconSmall");
  112. config->setFlat(true);
  113. config->setSizePolicy(QSizePolicy::Maximum,
  114. QSizePolicy::Maximum);
  115. config->setMaximumSize(22, 22);
  116. config->setAutoDefault(false);
  117. config->setAccessibleName(
  118. QTStr("VolControl.Properties").arg(sourceName));
  119. connect(config, &QAbstractButton::clicked, this,
  120. &VolControl::EmitConfigClicked);
  121. }
  122. QVBoxLayout *mainLayout = new QVBoxLayout;
  123. mainLayout->setContentsMargins(4, 4, 4, 4);
  124. mainLayout->setSpacing(2);
  125. if (vertical) {
  126. QHBoxLayout *nameLayout = new QHBoxLayout;
  127. QHBoxLayout *controlLayout = new QHBoxLayout;
  128. QHBoxLayout *volLayout = new QHBoxLayout;
  129. QHBoxLayout *meterLayout = new QHBoxLayout;
  130. volMeter = new VolumeMeter(nullptr, obs_volmeter, true);
  131. slider = new SliderIgnoreScroll(Qt::Vertical);
  132. nameLayout->setAlignment(Qt::AlignCenter);
  133. meterLayout->setAlignment(Qt::AlignCenter);
  134. controlLayout->setAlignment(Qt::AlignCenter);
  135. volLayout->setAlignment(Qt::AlignCenter);
  136. nameLayout->setContentsMargins(0, 0, 0, 0);
  137. nameLayout->setSpacing(0);
  138. nameLayout->addWidget(nameLabel);
  139. controlLayout->setContentsMargins(0, 0, 0, 0);
  140. controlLayout->setSpacing(0);
  141. if (showConfig)
  142. controlLayout->addWidget(config);
  143. controlLayout->addItem(new QSpacerItem(3, 0));
  144. // Add Headphone (audio monitoring) widget here
  145. controlLayout->addWidget(mute);
  146. meterLayout->setContentsMargins(0, 0, 0, 0);
  147. meterLayout->setSpacing(0);
  148. meterLayout->addWidget(volMeter);
  149. meterLayout->addWidget(slider);
  150. volLayout->setContentsMargins(0, 0, 0, 0);
  151. volLayout->setSpacing(0);
  152. volLayout->addWidget(volLabel);
  153. mainLayout->addItem(nameLayout);
  154. mainLayout->addItem(volLayout);
  155. mainLayout->addItem(meterLayout);
  156. mainLayout->addItem(controlLayout);
  157. volMeter->setFocusProxy(slider);
  158. setMaximumWidth(110);
  159. } else {
  160. QHBoxLayout *volLayout = new QHBoxLayout;
  161. QHBoxLayout *textLayout = new QHBoxLayout;
  162. QHBoxLayout *botLayout = new QHBoxLayout;
  163. volMeter = new VolumeMeter(nullptr, obs_volmeter, false);
  164. slider = new SliderIgnoreScroll(Qt::Horizontal);
  165. textLayout->setContentsMargins(0, 0, 0, 0);
  166. textLayout->addWidget(nameLabel);
  167. textLayout->addWidget(volLabel);
  168. textLayout->setAlignment(nameLabel, Qt::AlignLeft);
  169. textLayout->setAlignment(volLabel, Qt::AlignRight);
  170. volLayout->addWidget(slider);
  171. volLayout->addWidget(mute);
  172. volLayout->setSpacing(5);
  173. botLayout->setContentsMargins(0, 0, 0, 0);
  174. botLayout->setSpacing(0);
  175. botLayout->addLayout(volLayout);
  176. if (showConfig)
  177. botLayout->addWidget(config);
  178. mainLayout->addItem(textLayout);
  179. mainLayout->addWidget(volMeter);
  180. mainLayout->addItem(botLayout);
  181. volMeter->setFocusProxy(slider);
  182. }
  183. setLayout(mainLayout);
  184. QFont font = nameLabel->font();
  185. font.setPointSize(font.pointSize() - 1);
  186. nameLabel->setText(sourceName);
  187. nameLabel->setFont(font);
  188. volLabel->setFont(font);
  189. slider->setMinimum(0);
  190. slider->setMaximum(int(FADER_PRECISION));
  191. bool muted = obs_source_muted(source);
  192. mute->setChecked(muted);
  193. mute->setAccessibleName(QTStr("VolControl.Mute").arg(sourceName));
  194. obs_fader_add_callback(obs_fader, OBSVolumeChanged, this);
  195. obs_volmeter_add_callback(obs_volmeter, OBSVolumeLevel, this);
  196. signal_handler_connect(obs_source_get_signal_handler(source), "mute",
  197. OBSVolumeMuted, this);
  198. QWidget::connect(slider, SIGNAL(valueChanged(int)), this,
  199. SLOT(SliderChanged(int)));
  200. QWidget::connect(mute, SIGNAL(clicked(bool)), this,
  201. SLOT(SetMuted(bool)));
  202. obs_fader_attach_source(obs_fader, source);
  203. obs_volmeter_attach_source(obs_volmeter, source);
  204. QString styleName = slider->style()->objectName();
  205. QStyle *style;
  206. style = QStyleFactory::create(styleName);
  207. if (!style) {
  208. style = new SliderAbsoluteSetStyle();
  209. } else {
  210. style = new SliderAbsoluteSetStyle(style);
  211. }
  212. style->setParent(slider);
  213. slider->setStyle(style);
  214. /* Call volume changed once to init the slider position and label */
  215. VolumeChanged();
  216. }
  217. void VolControl::EnableSlider(bool enable)
  218. {
  219. slider->setEnabled(enable);
  220. }
  221. VolControl::~VolControl()
  222. {
  223. obs_fader_remove_callback(obs_fader, OBSVolumeChanged, this);
  224. obs_volmeter_remove_callback(obs_volmeter, OBSVolumeLevel, this);
  225. signal_handler_disconnect(obs_source_get_signal_handler(source), "mute",
  226. OBSVolumeMuted, this);
  227. obs_fader_destroy(obs_fader);
  228. obs_volmeter_destroy(obs_volmeter);
  229. }
  230. QColor VolumeMeter::getBackgroundNominalColor() const
  231. {
  232. return backgroundNominalColor;
  233. }
  234. void VolumeMeter::setBackgroundNominalColor(QColor c)
  235. {
  236. backgroundNominalColor = std::move(c);
  237. }
  238. QColor VolumeMeter::getBackgroundWarningColor() const
  239. {
  240. return backgroundWarningColor;
  241. }
  242. void VolumeMeter::setBackgroundWarningColor(QColor c)
  243. {
  244. backgroundWarningColor = std::move(c);
  245. }
  246. QColor VolumeMeter::getBackgroundErrorColor() const
  247. {
  248. return backgroundErrorColor;
  249. }
  250. void VolumeMeter::setBackgroundErrorColor(QColor c)
  251. {
  252. backgroundErrorColor = std::move(c);
  253. }
  254. QColor VolumeMeter::getForegroundNominalColor() const
  255. {
  256. return foregroundNominalColor;
  257. }
  258. void VolumeMeter::setForegroundNominalColor(QColor c)
  259. {
  260. foregroundNominalColor = std::move(c);
  261. }
  262. QColor VolumeMeter::getForegroundWarningColor() const
  263. {
  264. return foregroundWarningColor;
  265. }
  266. void VolumeMeter::setForegroundWarningColor(QColor c)
  267. {
  268. foregroundWarningColor = std::move(c);
  269. }
  270. QColor VolumeMeter::getForegroundErrorColor() const
  271. {
  272. return foregroundErrorColor;
  273. }
  274. void VolumeMeter::setForegroundErrorColor(QColor c)
  275. {
  276. foregroundErrorColor = std::move(c);
  277. }
  278. QColor VolumeMeter::getClipColor() const
  279. {
  280. return clipColor;
  281. }
  282. void VolumeMeter::setClipColor(QColor c)
  283. {
  284. clipColor = std::move(c);
  285. }
  286. QColor VolumeMeter::getMagnitudeColor() const
  287. {
  288. return magnitudeColor;
  289. }
  290. void VolumeMeter::setMagnitudeColor(QColor c)
  291. {
  292. magnitudeColor = std::move(c);
  293. }
  294. QColor VolumeMeter::getMajorTickColor() const
  295. {
  296. return majorTickColor;
  297. }
  298. void VolumeMeter::setMajorTickColor(QColor c)
  299. {
  300. majorTickColor = std::move(c);
  301. }
  302. QColor VolumeMeter::getMinorTickColor() const
  303. {
  304. return minorTickColor;
  305. }
  306. void VolumeMeter::setMinorTickColor(QColor c)
  307. {
  308. minorTickColor = std::move(c);
  309. }
  310. qreal VolumeMeter::getMinimumLevel() const
  311. {
  312. return minimumLevel;
  313. }
  314. void VolumeMeter::setMinimumLevel(qreal v)
  315. {
  316. minimumLevel = v;
  317. }
  318. qreal VolumeMeter::getWarningLevel() const
  319. {
  320. return warningLevel;
  321. }
  322. void VolumeMeter::setWarningLevel(qreal v)
  323. {
  324. warningLevel = v;
  325. }
  326. qreal VolumeMeter::getErrorLevel() const
  327. {
  328. return errorLevel;
  329. }
  330. void VolumeMeter::setErrorLevel(qreal v)
  331. {
  332. errorLevel = v;
  333. }
  334. qreal VolumeMeter::getClipLevel() const
  335. {
  336. return clipLevel;
  337. }
  338. void VolumeMeter::setClipLevel(qreal v)
  339. {
  340. clipLevel = v;
  341. }
  342. qreal VolumeMeter::getMinimumInputLevel() const
  343. {
  344. return minimumInputLevel;
  345. }
  346. void VolumeMeter::setMinimumInputLevel(qreal v)
  347. {
  348. minimumInputLevel = v;
  349. }
  350. qreal VolumeMeter::getPeakDecayRate() const
  351. {
  352. return peakDecayRate;
  353. }
  354. void VolumeMeter::setPeakDecayRate(qreal v)
  355. {
  356. peakDecayRate = v;
  357. }
  358. qreal VolumeMeter::getMagnitudeIntegrationTime() const
  359. {
  360. return magnitudeIntegrationTime;
  361. }
  362. void VolumeMeter::setMagnitudeIntegrationTime(qreal v)
  363. {
  364. magnitudeIntegrationTime = v;
  365. }
  366. qreal VolumeMeter::getPeakHoldDuration() const
  367. {
  368. return peakHoldDuration;
  369. }
  370. void VolumeMeter::setPeakHoldDuration(qreal v)
  371. {
  372. peakHoldDuration = v;
  373. }
  374. qreal VolumeMeter::getInputPeakHoldDuration() const
  375. {
  376. return inputPeakHoldDuration;
  377. }
  378. void VolumeMeter::setInputPeakHoldDuration(qreal v)
  379. {
  380. inputPeakHoldDuration = v;
  381. }
  382. void VolumeMeter::setPeakMeterType(enum obs_peak_meter_type peakMeterType)
  383. {
  384. obs_volmeter_set_peak_meter_type(obs_volmeter, peakMeterType);
  385. switch (peakMeterType) {
  386. case TRUE_PEAK_METER:
  387. // For true-peak meters EBU has defined the Permitted Maximum,
  388. // taking into account the accuracy of the meter and further
  389. // processing required by lossy audio compression.
  390. //
  391. // The alignment level was not specified, but I've adjusted
  392. // it compared to a sample-peak meter. Incidentally Youtube
  393. // uses this new Alignment Level as the maximum integrated
  394. // loudness of a video.
  395. //
  396. // * Permitted Maximum Level (PML) = -2.0 dBTP
  397. // * Alignment Level (AL) = -13 dBTP
  398. setErrorLevel(-2.0);
  399. setWarningLevel(-13.0);
  400. break;
  401. case SAMPLE_PEAK_METER:
  402. default:
  403. // For a sample Peak Meter EBU has the following level
  404. // definitions, taking into account inaccuracies of this meter:
  405. //
  406. // * Permitted Maximum Level (PML) = -9.0 dBFS
  407. // * Alignment Level (AL) = -20.0 dBFS
  408. setErrorLevel(-9.0);
  409. setWarningLevel(-20.0);
  410. break;
  411. }
  412. }
  413. void VolumeMeter::mousePressEvent(QMouseEvent *event)
  414. {
  415. setFocus(Qt::MouseFocusReason);
  416. event->accept();
  417. }
  418. void VolumeMeter::wheelEvent(QWheelEvent *event)
  419. {
  420. QApplication::sendEvent(focusProxy(), event);
  421. }
  422. VolumeMeter::VolumeMeter(QWidget *parent, obs_volmeter_t *obs_volmeter,
  423. bool vertical)
  424. : QWidget(parent), obs_volmeter(obs_volmeter), vertical(vertical)
  425. {
  426. setAttribute(Qt::WA_OpaquePaintEvent, true);
  427. // Use a font that can be rendered small.
  428. tickFont = QFont("Arial");
  429. tickFont.setPixelSize(7);
  430. // Default meter color settings, they only show if
  431. // there is no stylesheet, do not remove.
  432. backgroundNominalColor.setRgb(0x26, 0x7f, 0x26); // Dark green
  433. backgroundWarningColor.setRgb(0x7f, 0x7f, 0x26); // Dark yellow
  434. backgroundErrorColor.setRgb(0x7f, 0x26, 0x26); // Dark red
  435. foregroundNominalColor.setRgb(0x4c, 0xff, 0x4c); // Bright green
  436. foregroundWarningColor.setRgb(0xff, 0xff, 0x4c); // Bright yellow
  437. foregroundErrorColor.setRgb(0xff, 0x4c, 0x4c); // Bright red
  438. clipColor.setRgb(0xff, 0xff, 0xff); // Bright white
  439. magnitudeColor.setRgb(0x00, 0x00, 0x00); // Black
  440. majorTickColor.setRgb(0xff, 0xff, 0xff); // Black
  441. minorTickColor.setRgb(0xcc, 0xcc, 0xcc); // Black
  442. minimumLevel = -60.0; // -60 dB
  443. warningLevel = -20.0; // -20 dB
  444. errorLevel = -9.0; // -9 dB
  445. clipLevel = -0.5; // -0.5 dB
  446. minimumInputLevel = -50.0; // -50 dB
  447. peakDecayRate = 11.76; // 20 dB / 1.7 sec
  448. magnitudeIntegrationTime = 0.3; // 99% in 300 ms
  449. peakHoldDuration = 20.0; // 20 seconds
  450. inputPeakHoldDuration = 1.0; // 1 second
  451. channels = (int)audio_output_get_channels(obs_get_audio());
  452. handleChannelCofigurationChange();
  453. updateTimerRef = updateTimer.toStrongRef();
  454. if (!updateTimerRef) {
  455. updateTimerRef = QSharedPointer<VolumeMeterTimer>::create();
  456. updateTimerRef->setTimerType(Qt::PreciseTimer);
  457. updateTimerRef->start(16);
  458. updateTimer = updateTimerRef;
  459. }
  460. updateTimerRef->AddVolControl(this);
  461. }
  462. VolumeMeter::~VolumeMeter()
  463. {
  464. updateTimerRef->RemoveVolControl(this);
  465. delete tickPaintCache;
  466. }
  467. void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS],
  468. const float peak[MAX_AUDIO_CHANNELS],
  469. const float inputPeak[MAX_AUDIO_CHANNELS])
  470. {
  471. uint64_t ts = os_gettime_ns();
  472. QMutexLocker locker(&dataMutex);
  473. currentLastUpdateTime = ts;
  474. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  475. currentMagnitude[channelNr] = magnitude[channelNr];
  476. currentPeak[channelNr] = peak[channelNr];
  477. currentInputPeak[channelNr] = inputPeak[channelNr];
  478. }
  479. // In case there are more updates then redraws we must make sure
  480. // that the ballistics of peak and hold are recalculated.
  481. locker.unlock();
  482. calculateBallistics(ts);
  483. }
  484. inline void VolumeMeter::resetLevels()
  485. {
  486. currentLastUpdateTime = 0;
  487. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  488. currentMagnitude[channelNr] = -M_INFINITE;
  489. currentPeak[channelNr] = -M_INFINITE;
  490. currentInputPeak[channelNr] = -M_INFINITE;
  491. displayMagnitude[channelNr] = -M_INFINITE;
  492. displayPeak[channelNr] = -M_INFINITE;
  493. displayPeakHold[channelNr] = -M_INFINITE;
  494. displayPeakHoldLastUpdateTime[channelNr] = 0;
  495. displayInputPeakHold[channelNr] = -M_INFINITE;
  496. displayInputPeakHoldLastUpdateTime[channelNr] = 0;
  497. }
  498. }
  499. inline void VolumeMeter::handleChannelCofigurationChange()
  500. {
  501. QMutexLocker locker(&dataMutex);
  502. int currentNrAudioChannels = obs_volmeter_get_nr_channels(obs_volmeter);
  503. if (displayNrAudioChannels != currentNrAudioChannels) {
  504. displayNrAudioChannels = currentNrAudioChannels;
  505. // Make room for 3 pixels meter, with one pixel between each.
  506. // Then 9/13 pixels for ticks and numbers.
  507. if (vertical)
  508. setMinimumSize(displayNrAudioChannels * 4 + 14, 130);
  509. else
  510. setMinimumSize(130, displayNrAudioChannels * 4 + 8);
  511. resetLevels();
  512. }
  513. }
  514. inline bool VolumeMeter::detectIdle(uint64_t ts)
  515. {
  516. double timeSinceLastUpdate = (ts - currentLastUpdateTime) * 0.000000001;
  517. if (timeSinceLastUpdate > 0.5) {
  518. resetLevels();
  519. return true;
  520. } else {
  521. return false;
  522. }
  523. }
  524. inline void
  525. VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts,
  526. qreal timeSinceLastRedraw)
  527. {
  528. if (currentPeak[channelNr] >= displayPeak[channelNr] ||
  529. isnan(displayPeak[channelNr])) {
  530. // Attack of peak is immediate.
  531. displayPeak[channelNr] = currentPeak[channelNr];
  532. } else {
  533. // Decay of peak is 40 dB / 1.7 seconds for Fast Profile
  534. // 20 dB / 1.7 seconds for Medium Profile (Type I PPM)
  535. // 24 dB / 2.8 seconds for Slow Profile (Type II PPM)
  536. float decay = float(peakDecayRate * timeSinceLastRedraw);
  537. displayPeak[channelNr] = CLAMP(displayPeak[channelNr] - decay,
  538. currentPeak[channelNr], 0);
  539. }
  540. if (currentPeak[channelNr] >= displayPeakHold[channelNr] ||
  541. !isfinite(displayPeakHold[channelNr])) {
  542. // Attack of peak-hold is immediate, but keep track
  543. // when it was last updated.
  544. displayPeakHold[channelNr] = currentPeak[channelNr];
  545. displayPeakHoldLastUpdateTime[channelNr] = ts;
  546. } else {
  547. // The peak and hold falls back to peak
  548. // after 20 seconds.
  549. qreal timeSinceLastPeak =
  550. (uint64_t)(ts -
  551. displayPeakHoldLastUpdateTime[channelNr]) *
  552. 0.000000001;
  553. if (timeSinceLastPeak > peakHoldDuration) {
  554. displayPeakHold[channelNr] = currentPeak[channelNr];
  555. displayPeakHoldLastUpdateTime[channelNr] = ts;
  556. }
  557. }
  558. if (currentInputPeak[channelNr] >= displayInputPeakHold[channelNr] ||
  559. !isfinite(displayInputPeakHold[channelNr])) {
  560. // Attack of peak-hold is immediate, but keep track
  561. // when it was last updated.
  562. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  563. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  564. } else {
  565. // The peak and hold falls back to peak after 1 second.
  566. qreal timeSinceLastPeak =
  567. (uint64_t)(
  568. ts -
  569. displayInputPeakHoldLastUpdateTime[channelNr]) *
  570. 0.000000001;
  571. if (timeSinceLastPeak > inputPeakHoldDuration) {
  572. displayInputPeakHold[channelNr] =
  573. currentInputPeak[channelNr];
  574. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  575. }
  576. }
  577. if (!isfinite(displayMagnitude[channelNr])) {
  578. // The statements in the else-leg do not work with
  579. // NaN and infinite displayMagnitude.
  580. displayMagnitude[channelNr] = currentMagnitude[channelNr];
  581. } else {
  582. // A VU meter will integrate to the new value to 99% in 300 ms.
  583. // The calculation here is very simplified and is more accurate
  584. // with higher frame-rate.
  585. float attack =
  586. float((currentMagnitude[channelNr] -
  587. displayMagnitude[channelNr]) *
  588. (timeSinceLastRedraw / magnitudeIntegrationTime) *
  589. 0.99);
  590. displayMagnitude[channelNr] =
  591. CLAMP(displayMagnitude[channelNr] + attack,
  592. (float)minimumLevel, 0);
  593. }
  594. }
  595. inline void VolumeMeter::calculateBallistics(uint64_t ts,
  596. qreal timeSinceLastRedraw)
  597. {
  598. QMutexLocker locker(&dataMutex);
  599. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++)
  600. calculateBallisticsForChannel(channelNr, ts,
  601. timeSinceLastRedraw);
  602. }
  603. void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width,
  604. int height, float peakHold)
  605. {
  606. QMutexLocker locker(&dataMutex);
  607. QColor color;
  608. if (peakHold < minimumInputLevel)
  609. color = backgroundNominalColor;
  610. else if (peakHold < warningLevel)
  611. color = foregroundNominalColor;
  612. else if (peakHold < errorLevel)
  613. color = foregroundWarningColor;
  614. else if (peakHold <= clipLevel)
  615. color = foregroundErrorColor;
  616. else
  617. color = clipColor;
  618. painter.fillRect(x, y, width, height, color);
  619. }
  620. void VolumeMeter::paintHTicks(QPainter &painter, int x, int y, int width,
  621. int height)
  622. {
  623. qreal scale = width / minimumLevel;
  624. painter.setFont(tickFont);
  625. painter.setPen(majorTickColor);
  626. // Draw major tick lines and numeric indicators.
  627. for (int i = 0; i >= minimumLevel; i -= 5) {
  628. int position = int(x + width - (i * scale) - 1);
  629. QString str = QString::number(i);
  630. if (i == 0 || i == -5)
  631. painter.drawText(position - 3, height, str);
  632. else
  633. painter.drawText(position - 5, height, str);
  634. painter.drawLine(position, y, position, y + 2);
  635. }
  636. // Draw minor tick lines.
  637. painter.setPen(minorTickColor);
  638. for (int i = 0; i >= minimumLevel; i--) {
  639. int position = int(x + width - (i * scale) - 1);
  640. if (i % 5 != 0)
  641. painter.drawLine(position, y, position, y + 1);
  642. }
  643. }
  644. void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height)
  645. {
  646. qreal scale = height / minimumLevel;
  647. painter.setFont(tickFont);
  648. painter.setPen(majorTickColor);
  649. // Draw major tick lines and numeric indicators.
  650. for (int i = 0; i >= minimumLevel; i -= 5) {
  651. int position = y + int((i * scale) - 1);
  652. QString str = QString::number(i);
  653. if (i == 0)
  654. painter.drawText(x + 5, position + 4, str);
  655. else if (i == -60)
  656. painter.drawText(x + 4, position, str);
  657. else
  658. painter.drawText(x + 4, position + 2, str);
  659. painter.drawLine(x, position, x + 2, position);
  660. }
  661. // Draw minor tick lines.
  662. painter.setPen(minorTickColor);
  663. for (int i = 0; i >= minimumLevel; i--) {
  664. int position = y + int((i * scale) - 1);
  665. if (i % 5 != 0)
  666. painter.drawLine(x, position, x + 1, position);
  667. }
  668. }
  669. #define CLIP_FLASH_DURATION_MS 1000
  670. void VolumeMeter::ClipEnding()
  671. {
  672. clipping = false;
  673. }
  674. void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width,
  675. int height, float magnitude, float peak,
  676. float peakHold)
  677. {
  678. qreal scale = width / minimumLevel;
  679. QMutexLocker locker(&dataMutex);
  680. int minimumPosition = x + 0;
  681. int maximumPosition = x + width;
  682. int magnitudePosition = int(x + width - (magnitude * scale));
  683. int peakPosition = int(x + width - (peak * scale));
  684. int peakHoldPosition = int(x + width - (peakHold * scale));
  685. int warningPosition = int(x + width - (warningLevel * scale));
  686. int errorPosition = int(x + width - (errorLevel * scale));
  687. int nominalLength = warningPosition - minimumPosition;
  688. int warningLength = errorPosition - warningPosition;
  689. int errorLength = maximumPosition - errorPosition;
  690. locker.unlock();
  691. if (clipping) {
  692. peakPosition = maximumPosition;
  693. }
  694. if (peakPosition < minimumPosition) {
  695. painter.fillRect(minimumPosition, y, nominalLength, height,
  696. backgroundNominalColor);
  697. painter.fillRect(warningPosition, y, warningLength, height,
  698. backgroundWarningColor);
  699. painter.fillRect(errorPosition, y, errorLength, height,
  700. backgroundErrorColor);
  701. } else if (peakPosition < warningPosition) {
  702. painter.fillRect(minimumPosition, y,
  703. peakPosition - minimumPosition, height,
  704. foregroundNominalColor);
  705. painter.fillRect(peakPosition, y,
  706. warningPosition - peakPosition, height,
  707. backgroundNominalColor);
  708. painter.fillRect(warningPosition, y, warningLength, height,
  709. backgroundWarningColor);
  710. painter.fillRect(errorPosition, y, errorLength, height,
  711. backgroundErrorColor);
  712. } else if (peakPosition < errorPosition) {
  713. painter.fillRect(minimumPosition, y, nominalLength, height,
  714. foregroundNominalColor);
  715. painter.fillRect(warningPosition, y,
  716. peakPosition - warningPosition, height,
  717. foregroundWarningColor);
  718. painter.fillRect(peakPosition, y, errorPosition - peakPosition,
  719. height, backgroundWarningColor);
  720. painter.fillRect(errorPosition, y, errorLength, height,
  721. backgroundErrorColor);
  722. } else if (peakPosition < maximumPosition) {
  723. painter.fillRect(minimumPosition, y, nominalLength, height,
  724. foregroundNominalColor);
  725. painter.fillRect(warningPosition, y, warningLength, height,
  726. foregroundWarningColor);
  727. painter.fillRect(errorPosition, y, peakPosition - errorPosition,
  728. height, foregroundErrorColor);
  729. painter.fillRect(peakPosition, y,
  730. maximumPosition - peakPosition, height,
  731. backgroundErrorColor);
  732. } else if (int(magnitude) != 0) {
  733. if (!clipping) {
  734. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  735. SLOT(ClipEnding()));
  736. clipping = true;
  737. }
  738. int end = errorLength + warningLength + nominalLength;
  739. painter.fillRect(minimumPosition, y, end, height,
  740. QBrush(foregroundErrorColor));
  741. }
  742. if (peakHoldPosition - 3 < minimumPosition)
  743. ; // Peak-hold below minimum, no drawing.
  744. else if (peakHoldPosition < warningPosition)
  745. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  746. foregroundNominalColor);
  747. else if (peakHoldPosition < errorPosition)
  748. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  749. foregroundWarningColor);
  750. else
  751. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  752. foregroundErrorColor);
  753. if (magnitudePosition - 3 >= minimumPosition)
  754. painter.fillRect(magnitudePosition - 3, y, 3, height,
  755. magnitudeColor);
  756. }
  757. void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width,
  758. int height, float magnitude, float peak,
  759. float peakHold)
  760. {
  761. qreal scale = height / minimumLevel;
  762. QMutexLocker locker(&dataMutex);
  763. int minimumPosition = y + 0;
  764. int maximumPosition = y + height;
  765. int magnitudePosition = int(y + height - (magnitude * scale));
  766. int peakPosition = int(y + height - (peak * scale));
  767. int peakHoldPosition = int(y + height - (peakHold * scale));
  768. int warningPosition = int(y + height - (warningLevel * scale));
  769. int errorPosition = int(y + height - (errorLevel * scale));
  770. int nominalLength = warningPosition - minimumPosition;
  771. int warningLength = errorPosition - warningPosition;
  772. int errorLength = maximumPosition - errorPosition;
  773. locker.unlock();
  774. if (clipping) {
  775. peakPosition = maximumPosition;
  776. }
  777. if (peakPosition < minimumPosition) {
  778. painter.fillRect(x, minimumPosition, width, nominalLength,
  779. backgroundNominalColor);
  780. painter.fillRect(x, warningPosition, width, warningLength,
  781. backgroundWarningColor);
  782. painter.fillRect(x, errorPosition, width, errorLength,
  783. backgroundErrorColor);
  784. } else if (peakPosition < warningPosition) {
  785. painter.fillRect(x, minimumPosition, width,
  786. peakPosition - minimumPosition,
  787. foregroundNominalColor);
  788. painter.fillRect(x, peakPosition, width,
  789. warningPosition - peakPosition,
  790. backgroundNominalColor);
  791. painter.fillRect(x, warningPosition, width, warningLength,
  792. backgroundWarningColor);
  793. painter.fillRect(x, errorPosition, width, errorLength,
  794. backgroundErrorColor);
  795. } else if (peakPosition < errorPosition) {
  796. painter.fillRect(x, minimumPosition, width, nominalLength,
  797. foregroundNominalColor);
  798. painter.fillRect(x, warningPosition, width,
  799. peakPosition - warningPosition,
  800. foregroundWarningColor);
  801. painter.fillRect(x, peakPosition, width,
  802. errorPosition - peakPosition,
  803. backgroundWarningColor);
  804. painter.fillRect(x, errorPosition, width, errorLength,
  805. backgroundErrorColor);
  806. } else if (peakPosition < maximumPosition) {
  807. painter.fillRect(x, minimumPosition, width, nominalLength,
  808. foregroundNominalColor);
  809. painter.fillRect(x, warningPosition, width, warningLength,
  810. foregroundWarningColor);
  811. painter.fillRect(x, errorPosition, width,
  812. peakPosition - errorPosition,
  813. foregroundErrorColor);
  814. painter.fillRect(x, peakPosition, width,
  815. maximumPosition - peakPosition,
  816. backgroundErrorColor);
  817. } else {
  818. if (!clipping) {
  819. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  820. SLOT(ClipEnding()));
  821. clipping = true;
  822. }
  823. int end = errorLength + warningLength + nominalLength;
  824. painter.fillRect(x, minimumPosition, width, end,
  825. QBrush(foregroundErrorColor));
  826. }
  827. if (peakHoldPosition - 3 < minimumPosition)
  828. ; // Peak-hold below minimum, no drawing.
  829. else if (peakHoldPosition < warningPosition)
  830. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  831. foregroundNominalColor);
  832. else if (peakHoldPosition < errorPosition)
  833. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  834. foregroundWarningColor);
  835. else
  836. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  837. foregroundErrorColor);
  838. if (magnitudePosition - 3 >= minimumPosition)
  839. painter.fillRect(x, magnitudePosition - 3, width, 3,
  840. magnitudeColor);
  841. }
  842. void VolumeMeter::paintEvent(QPaintEvent *event)
  843. {
  844. uint64_t ts = os_gettime_ns();
  845. qreal timeSinceLastRedraw = (ts - lastRedrawTime) * 0.000000001;
  846. const QRect rect = event->region().boundingRect();
  847. int width = rect.width();
  848. int height = rect.height();
  849. handleChannelCofigurationChange();
  850. calculateBallistics(ts, timeSinceLastRedraw);
  851. bool idle = detectIdle(ts);
  852. // Draw the ticks in a off-screen buffer when the widget changes size.
  853. QSize tickPaintCacheSize;
  854. if (vertical)
  855. tickPaintCacheSize = QSize(14, height);
  856. else
  857. tickPaintCacheSize = QSize(width, 9);
  858. if (tickPaintCache == nullptr ||
  859. tickPaintCache->size() != tickPaintCacheSize) {
  860. delete tickPaintCache;
  861. tickPaintCache = new QPixmap(tickPaintCacheSize);
  862. QColor clearColor(0, 0, 0, 0);
  863. tickPaintCache->fill(clearColor);
  864. QPainter tickPainter(tickPaintCache);
  865. if (vertical) {
  866. tickPainter.translate(0, height);
  867. tickPainter.scale(1, -1);
  868. paintVTicks(tickPainter, 0, 11,
  869. tickPaintCacheSize.height() - 11);
  870. } else {
  871. paintHTicks(tickPainter, 6, 0,
  872. tickPaintCacheSize.width() - 6,
  873. tickPaintCacheSize.height());
  874. }
  875. tickPainter.end();
  876. }
  877. // Actual painting of the widget starts here.
  878. QPainter painter(this);
  879. // Paint window background color (as widget is opaque)
  880. QColor background = palette().color(QPalette::ColorRole::Window);
  881. painter.fillRect(rect, background);
  882. if (vertical) {
  883. // Invert the Y axis to ease the math
  884. painter.translate(0, height);
  885. painter.scale(1, -1);
  886. painter.drawPixmap(displayNrAudioChannels * 4 - 1, 7,
  887. *tickPaintCache);
  888. } else {
  889. painter.drawPixmap(0, height - 9, *tickPaintCache);
  890. }
  891. for (int channelNr = 0; channelNr < displayNrAudioChannels;
  892. channelNr++) {
  893. int channelNrFixed =
  894. (displayNrAudioChannels == 1 && channels > 2)
  895. ? 2
  896. : channelNr;
  897. if (vertical)
  898. paintVMeter(painter, channelNr * 4, 8, 3, height - 10,
  899. displayMagnitude[channelNrFixed],
  900. displayPeak[channelNrFixed],
  901. displayPeakHold[channelNrFixed]);
  902. else
  903. paintHMeter(painter, 5, channelNr * 4, width - 5, 3,
  904. displayMagnitude[channelNrFixed],
  905. displayPeak[channelNrFixed],
  906. displayPeakHold[channelNrFixed]);
  907. if (idle)
  908. continue;
  909. // By not drawing the input meter boxes the user can
  910. // see that the audio stream has been stopped, without
  911. // having too much visual impact.
  912. if (vertical)
  913. paintInputMeter(painter, channelNr * 4, 3, 3, 3,
  914. displayInputPeakHold[channelNrFixed]);
  915. else
  916. paintInputMeter(painter, 0, channelNr * 4, 3, 3,
  917. displayInputPeakHold[channelNrFixed]);
  918. }
  919. lastRedrawTime = ts;
  920. }
  921. void VolumeMeterTimer::AddVolControl(VolumeMeter *meter)
  922. {
  923. volumeMeters.push_back(meter);
  924. }
  925. void VolumeMeterTimer::RemoveVolControl(VolumeMeter *meter)
  926. {
  927. volumeMeters.removeOne(meter);
  928. }
  929. void VolumeMeterTimer::timerEvent(QTimerEvent *)
  930. {
  931. for (VolumeMeter *meter : volumeMeters)
  932. meter->update();
  933. }