volume-control.cpp 30 KB

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