volume-control.cpp 30 KB

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