volume-control.cpp 29 KB

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