volume-control.cpp 30 KB

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