volume-control.cpp 31 KB

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