volume-control.cpp 29 KB

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