1
0

volume-control.cpp 29 KB

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