volume-control.cpp 30 KB

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