volume-control.cpp 30 KB

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