volume-control.cpp 30 KB

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