volume-control.cpp 30 KB

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