volume-control.cpp 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447
  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. // Size of the audio indicator in pixels
  18. #define INDICATOR_THICKNESS 3
  19. // Padding on top and bottom of vertical meters
  20. #define METER_PADDING 1
  21. QWeakPointer<VolumeMeterTimer> VolumeMeter::updateTimer;
  22. void VolControl::OBSVolumeChanged(void *data, float db)
  23. {
  24. Q_UNUSED(db);
  25. VolControl *volControl = static_cast<VolControl *>(data);
  26. QMetaObject::invokeMethod(volControl, "VolumeChanged");
  27. }
  28. void VolControl::OBSVolumeLevel(void *data,
  29. const float magnitude[MAX_AUDIO_CHANNELS],
  30. const float peak[MAX_AUDIO_CHANNELS],
  31. const float inputPeak[MAX_AUDIO_CHANNELS])
  32. {
  33. VolControl *volControl = static_cast<VolControl *>(data);
  34. volControl->volMeter->setLevels(magnitude, peak, inputPeak);
  35. }
  36. void VolControl::OBSVolumeMuted(void *data, calldata_t *calldata)
  37. {
  38. VolControl *volControl = static_cast<VolControl *>(data);
  39. bool muted = calldata_bool(calldata, "muted");
  40. QMetaObject::invokeMethod(volControl, "VolumeMuted",
  41. Q_ARG(bool, muted));
  42. }
  43. void VolControl::VolumeChanged()
  44. {
  45. slider->blockSignals(true);
  46. slider->setValue(
  47. (int)(obs_fader_get_deflection(obs_fader) * FADER_PRECISION));
  48. slider->blockSignals(false);
  49. updateText();
  50. }
  51. void VolControl::VolumeMuted(bool muted)
  52. {
  53. if (mute->isChecked() != muted)
  54. mute->setChecked(muted);
  55. volMeter->muted = muted;
  56. }
  57. void VolControl::SetMuted(bool checked)
  58. {
  59. bool prev = obs_source_muted(source);
  60. obs_source_set_muted(source, checked);
  61. auto undo_redo = [](const std::string &name, bool val) {
  62. OBSSourceAutoRelease source =
  63. obs_get_source_by_name(name.c_str());
  64. obs_source_set_muted(source, val);
  65. };
  66. QString text =
  67. QTStr(checked ? "Undo.Volume.Mute" : "Undo.Volume.Unmute");
  68. const char *name = obs_source_get_name(source);
  69. OBSBasic::Get()->undo_s.add_action(
  70. text.arg(name),
  71. std::bind(undo_redo, std::placeholders::_1, prev),
  72. std::bind(undo_redo, std::placeholders::_1, checked), name,
  73. name);
  74. }
  75. void VolControl::SliderChanged(int vol)
  76. {
  77. float prev = obs_source_get_volume(source);
  78. obs_fader_set_deflection(obs_fader, float(vol) / FADER_PRECISION);
  79. updateText();
  80. auto undo_redo = [](const std::string &name, float val) {
  81. OBSSourceAutoRelease source =
  82. obs_get_source_by_name(name.c_str());
  83. obs_source_set_volume(source, val);
  84. };
  85. float val = obs_source_get_volume(source);
  86. const char *name = obs_source_get_name(source);
  87. OBSBasic::Get()->undo_s.add_action(
  88. QTStr("Undo.Volume.Change").arg(name),
  89. std::bind(undo_redo, std::placeholders::_1, prev),
  90. std::bind(undo_redo, std::placeholders::_1, val), name, name,
  91. true);
  92. }
  93. void VolControl::updateText()
  94. {
  95. QString text;
  96. float db = obs_fader_get_db(obs_fader);
  97. if (db < -96.0f)
  98. text = "-inf dB";
  99. else
  100. text = QString::number(db, 'f', 1).append(" dB");
  101. volLabel->setText(text);
  102. bool muted = obs_source_muted(source);
  103. const char *accTextLookup = muted ? "VolControl.SliderMuted"
  104. : "VolControl.SliderUnmuted";
  105. QString sourceName = obs_source_get_name(source);
  106. QString accText = QTStr(accTextLookup).arg(sourceName);
  107. slider->setAccessibleName(accText);
  108. }
  109. QString VolControl::GetName() const
  110. {
  111. return nameLabel->text();
  112. }
  113. void VolControl::SetName(const QString &newName)
  114. {
  115. nameLabel->setText(newName);
  116. }
  117. void VolControl::EmitConfigClicked()
  118. {
  119. emit ConfigClicked();
  120. }
  121. void VolControl::SetMeterDecayRate(qreal q)
  122. {
  123. volMeter->setPeakDecayRate(q);
  124. }
  125. void VolControl::setPeakMeterType(enum obs_peak_meter_type peakMeterType)
  126. {
  127. volMeter->setPeakMeterType(peakMeterType);
  128. }
  129. VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical)
  130. : source(std::move(source_)),
  131. levelTotal(0.0f),
  132. levelCount(0.0f),
  133. obs_fader(obs_fader_create(OBS_FADER_LOG)),
  134. obs_volmeter(obs_volmeter_create(OBS_FADER_LOG)),
  135. vertical(vertical),
  136. contextMenu(nullptr)
  137. {
  138. nameLabel = new QLabel();
  139. volLabel = new QLabel();
  140. mute = new MuteCheckBox();
  141. QString sourceName = obs_source_get_name(source);
  142. setObjectName(sourceName);
  143. if (showConfig) {
  144. config = new QPushButton(this);
  145. config->setProperty("themeID", "menuIconSmall");
  146. config->setSizePolicy(QSizePolicy::Maximum,
  147. QSizePolicy::Maximum);
  148. config->setMaximumSize(22, 22);
  149. config->setAutoDefault(false);
  150. config->setAccessibleName(
  151. QTStr("VolControl.Properties").arg(sourceName));
  152. connect(config, &QAbstractButton::clicked, this,
  153. &VolControl::EmitConfigClicked);
  154. }
  155. QVBoxLayout *mainLayout = new QVBoxLayout;
  156. mainLayout->setContentsMargins(4, 4, 4, 4);
  157. mainLayout->setSpacing(2);
  158. if (vertical) {
  159. QHBoxLayout *nameLayout = new QHBoxLayout;
  160. QHBoxLayout *controlLayout = new QHBoxLayout;
  161. QHBoxLayout *volLayout = new QHBoxLayout;
  162. QHBoxLayout *meterLayout = new QHBoxLayout;
  163. volMeter = new VolumeMeter(nullptr, obs_volmeter, true);
  164. slider = new VolumeSlider(obs_fader, Qt::Vertical);
  165. slider->setLayoutDirection(Qt::LeftToRight);
  166. nameLayout->setAlignment(Qt::AlignCenter);
  167. meterLayout->setAlignment(Qt::AlignCenter);
  168. controlLayout->setAlignment(Qt::AlignCenter);
  169. volLayout->setAlignment(Qt::AlignCenter);
  170. nameLayout->setContentsMargins(0, 0, 0, 0);
  171. nameLayout->setSpacing(0);
  172. nameLayout->addWidget(nameLabel);
  173. controlLayout->setContentsMargins(0, 0, 0, 0);
  174. controlLayout->setSpacing(0);
  175. if (showConfig)
  176. controlLayout->addWidget(config);
  177. controlLayout->addItem(new QSpacerItem(3, 0));
  178. // Add Headphone (audio monitoring) widget here
  179. controlLayout->addWidget(mute);
  180. meterLayout->setContentsMargins(0, 0, 0, 0);
  181. meterLayout->setSpacing(0);
  182. meterLayout->addWidget(volMeter);
  183. meterLayout->addWidget(slider);
  184. volLayout->setContentsMargins(0, 0, 0, 0);
  185. volLayout->setSpacing(0);
  186. volLayout->addWidget(volLabel);
  187. mainLayout->addItem(nameLayout);
  188. mainLayout->addItem(volLayout);
  189. mainLayout->addItem(meterLayout);
  190. mainLayout->addItem(controlLayout);
  191. volMeter->setFocusProxy(slider);
  192. // Default size can cause clipping of long names in vertical layout.
  193. QFont font = nameLabel->font();
  194. QFontInfo info(font);
  195. font.setPointSizeF(0.8 * info.pointSizeF());
  196. nameLabel->setFont(font);
  197. setMaximumWidth(110);
  198. } else {
  199. QHBoxLayout *textLayout = new QHBoxLayout;
  200. QHBoxLayout *botLayout = new QHBoxLayout;
  201. volMeter = new VolumeMeter(nullptr, obs_volmeter, false);
  202. slider = new VolumeSlider(obs_fader, Qt::Horizontal);
  203. slider->setLayoutDirection(Qt::LeftToRight);
  204. textLayout->setContentsMargins(0, 0, 0, 0);
  205. textLayout->addWidget(nameLabel);
  206. textLayout->addWidget(volLabel);
  207. textLayout->setAlignment(nameLabel, Qt::AlignLeft);
  208. textLayout->setAlignment(volLabel, Qt::AlignRight);
  209. botLayout->setContentsMargins(0, 0, 0, 0);
  210. botLayout->setSpacing(5);
  211. botLayout->addWidget(slider);
  212. botLayout->addWidget(mute);
  213. botLayout->setAlignment(slider, Qt::AlignVCenter);
  214. botLayout->setAlignment(mute, Qt::AlignVCenter);
  215. if (showConfig) {
  216. botLayout->addWidget(config);
  217. botLayout->setAlignment(config, Qt::AlignVCenter);
  218. }
  219. mainLayout->addItem(textLayout);
  220. mainLayout->addWidget(volMeter);
  221. mainLayout->addItem(botLayout);
  222. volMeter->setFocusProxy(slider);
  223. }
  224. setLayout(mainLayout);
  225. nameLabel->setText(sourceName);
  226. slider->setMinimum(0);
  227. slider->setMaximum(int(FADER_PRECISION));
  228. bool muted = obs_source_muted(source);
  229. mute->setChecked(muted);
  230. volMeter->muted = muted;
  231. mute->setAccessibleName(QTStr("VolControl.Mute").arg(sourceName));
  232. obs_fader_add_callback(obs_fader, OBSVolumeChanged, this);
  233. obs_volmeter_add_callback(obs_volmeter, OBSVolumeLevel, this);
  234. signal_handler_connect(obs_source_get_signal_handler(source), "mute",
  235. OBSVolumeMuted, this);
  236. QWidget::connect(slider, SIGNAL(valueChanged(int)), this,
  237. SLOT(SliderChanged(int)));
  238. QWidget::connect(mute, SIGNAL(clicked(bool)), this,
  239. SLOT(SetMuted(bool)));
  240. obs_fader_attach_source(obs_fader, source);
  241. obs_volmeter_attach_source(obs_volmeter, source);
  242. QString styleName = slider->style()->objectName();
  243. QStyle *style;
  244. style = QStyleFactory::create(styleName);
  245. if (!style) {
  246. style = new SliderAbsoluteSetStyle();
  247. } else {
  248. style = new SliderAbsoluteSetStyle(style);
  249. }
  250. style->setParent(slider);
  251. slider->setStyle(style);
  252. /* Call volume changed once to init the slider position and label */
  253. VolumeChanged();
  254. }
  255. void VolControl::EnableSlider(bool enable)
  256. {
  257. slider->setEnabled(enable);
  258. }
  259. VolControl::~VolControl()
  260. {
  261. obs_fader_remove_callback(obs_fader, OBSVolumeChanged, this);
  262. obs_volmeter_remove_callback(obs_volmeter, OBSVolumeLevel, this);
  263. signal_handler_disconnect(obs_source_get_signal_handler(source), "mute",
  264. OBSVolumeMuted, this);
  265. obs_fader_destroy(obs_fader);
  266. obs_volmeter_destroy(obs_volmeter);
  267. if (contextMenu)
  268. contextMenu->close();
  269. }
  270. static inline QColor color_from_int(long long val)
  271. {
  272. QColor color(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff,
  273. (val >> 24) & 0xff);
  274. color.setAlpha(255);
  275. return color;
  276. }
  277. QColor VolumeMeter::getBackgroundNominalColor() const
  278. {
  279. return p_backgroundNominalColor;
  280. }
  281. QColor VolumeMeter::getBackgroundNominalColorDisabled() const
  282. {
  283. return backgroundNominalColorDisabled;
  284. }
  285. void VolumeMeter::setBackgroundNominalColor(QColor c)
  286. {
  287. p_backgroundNominalColor = std::move(c);
  288. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  289. "OverrideColors")) {
  290. backgroundNominalColor = color_from_int(config_get_int(
  291. GetGlobalConfig(), "Accessibility", "MixerGreen"));
  292. } else {
  293. backgroundNominalColor = p_backgroundNominalColor;
  294. }
  295. }
  296. void VolumeMeter::setBackgroundNominalColorDisabled(QColor c)
  297. {
  298. backgroundNominalColorDisabled = std::move(c);
  299. }
  300. QColor VolumeMeter::getBackgroundWarningColor() const
  301. {
  302. return p_backgroundWarningColor;
  303. }
  304. QColor VolumeMeter::getBackgroundWarningColorDisabled() const
  305. {
  306. return backgroundWarningColorDisabled;
  307. }
  308. void VolumeMeter::setBackgroundWarningColor(QColor c)
  309. {
  310. p_backgroundWarningColor = std::move(c);
  311. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  312. "OverrideColors")) {
  313. backgroundWarningColor = color_from_int(config_get_int(
  314. GetGlobalConfig(), "Accessibility", "MixerYellow"));
  315. } else {
  316. backgroundWarningColor = p_backgroundWarningColor;
  317. }
  318. }
  319. void VolumeMeter::setBackgroundWarningColorDisabled(QColor c)
  320. {
  321. backgroundWarningColorDisabled = std::move(c);
  322. }
  323. QColor VolumeMeter::getBackgroundErrorColor() const
  324. {
  325. return p_backgroundErrorColor;
  326. }
  327. QColor VolumeMeter::getBackgroundErrorColorDisabled() const
  328. {
  329. return backgroundErrorColorDisabled;
  330. }
  331. void VolumeMeter::setBackgroundErrorColor(QColor c)
  332. {
  333. p_backgroundErrorColor = std::move(c);
  334. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  335. "OverrideColors")) {
  336. backgroundErrorColor = color_from_int(config_get_int(
  337. GetGlobalConfig(), "Accessibility", "MixerRed"));
  338. } else {
  339. backgroundErrorColor = p_backgroundErrorColor;
  340. }
  341. }
  342. void VolumeMeter::setBackgroundErrorColorDisabled(QColor c)
  343. {
  344. backgroundErrorColorDisabled = std::move(c);
  345. }
  346. QColor VolumeMeter::getForegroundNominalColor() const
  347. {
  348. return p_foregroundNominalColor;
  349. }
  350. QColor VolumeMeter::getForegroundNominalColorDisabled() const
  351. {
  352. return foregroundNominalColorDisabled;
  353. }
  354. void VolumeMeter::setForegroundNominalColor(QColor c)
  355. {
  356. p_foregroundNominalColor = std::move(c);
  357. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  358. "OverrideColors")) {
  359. foregroundNominalColor = color_from_int(
  360. config_get_int(GetGlobalConfig(), "Accessibility",
  361. "MixerGreenActive"));
  362. } else {
  363. foregroundNominalColor = p_foregroundNominalColor;
  364. }
  365. }
  366. void VolumeMeter::setForegroundNominalColorDisabled(QColor c)
  367. {
  368. foregroundNominalColorDisabled = std::move(c);
  369. }
  370. QColor VolumeMeter::getForegroundWarningColor() const
  371. {
  372. return p_foregroundWarningColor;
  373. }
  374. QColor VolumeMeter::getForegroundWarningColorDisabled() const
  375. {
  376. return foregroundWarningColorDisabled;
  377. }
  378. void VolumeMeter::setForegroundWarningColor(QColor c)
  379. {
  380. p_foregroundWarningColor = std::move(c);
  381. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  382. "OverrideColors")) {
  383. foregroundWarningColor = color_from_int(
  384. config_get_int(GetGlobalConfig(), "Accessibility",
  385. "MixerYellowActive"));
  386. } else {
  387. foregroundWarningColor = p_foregroundWarningColor;
  388. }
  389. }
  390. void VolumeMeter::setForegroundWarningColorDisabled(QColor c)
  391. {
  392. foregroundWarningColorDisabled = std::move(c);
  393. }
  394. QColor VolumeMeter::getForegroundErrorColor() const
  395. {
  396. return p_foregroundErrorColor;
  397. }
  398. QColor VolumeMeter::getForegroundErrorColorDisabled() const
  399. {
  400. return foregroundErrorColorDisabled;
  401. }
  402. void VolumeMeter::setForegroundErrorColor(QColor c)
  403. {
  404. p_foregroundErrorColor = std::move(c);
  405. if (config_get_bool(GetGlobalConfig(), "Accessibility",
  406. "OverrideColors")) {
  407. foregroundErrorColor = color_from_int(config_get_int(
  408. GetGlobalConfig(), "Accessibility", "MixerRedActive"));
  409. } else {
  410. foregroundErrorColor = p_foregroundErrorColor;
  411. }
  412. }
  413. void VolumeMeter::setForegroundErrorColorDisabled(QColor c)
  414. {
  415. foregroundErrorColorDisabled = std::move(c);
  416. }
  417. QColor VolumeMeter::getClipColor() const
  418. {
  419. return clipColor;
  420. }
  421. void VolumeMeter::setClipColor(QColor c)
  422. {
  423. clipColor = std::move(c);
  424. }
  425. QColor VolumeMeter::getMagnitudeColor() const
  426. {
  427. return magnitudeColor;
  428. }
  429. void VolumeMeter::setMagnitudeColor(QColor c)
  430. {
  431. magnitudeColor = std::move(c);
  432. }
  433. QColor VolumeMeter::getMajorTickColor() const
  434. {
  435. return majorTickColor;
  436. }
  437. void VolumeMeter::setMajorTickColor(QColor c)
  438. {
  439. majorTickColor = std::move(c);
  440. }
  441. QColor VolumeMeter::getMinorTickColor() const
  442. {
  443. return minorTickColor;
  444. }
  445. void VolumeMeter::setMinorTickColor(QColor c)
  446. {
  447. minorTickColor = std::move(c);
  448. }
  449. int VolumeMeter::getMeterThickness() const
  450. {
  451. return meterThickness;
  452. }
  453. void VolumeMeter::setMeterThickness(int v)
  454. {
  455. meterThickness = v;
  456. recalculateLayout = true;
  457. }
  458. qreal VolumeMeter::getMeterFontScaling() const
  459. {
  460. return meterFontScaling;
  461. }
  462. void VolumeMeter::setMeterFontScaling(qreal v)
  463. {
  464. meterFontScaling = v;
  465. recalculateLayout = true;
  466. }
  467. void VolControl::refreshColors()
  468. {
  469. volMeter->setBackgroundNominalColor(
  470. volMeter->getBackgroundNominalColor());
  471. volMeter->setBackgroundWarningColor(
  472. volMeter->getBackgroundWarningColor());
  473. volMeter->setBackgroundErrorColor(volMeter->getBackgroundErrorColor());
  474. volMeter->setForegroundNominalColor(
  475. volMeter->getForegroundNominalColor());
  476. volMeter->setForegroundWarningColor(
  477. volMeter->getForegroundWarningColor());
  478. volMeter->setForegroundErrorColor(volMeter->getForegroundErrorColor());
  479. }
  480. qreal VolumeMeter::getMinimumLevel() const
  481. {
  482. return minimumLevel;
  483. }
  484. void VolumeMeter::setMinimumLevel(qreal v)
  485. {
  486. minimumLevel = v;
  487. }
  488. qreal VolumeMeter::getWarningLevel() const
  489. {
  490. return warningLevel;
  491. }
  492. void VolumeMeter::setWarningLevel(qreal v)
  493. {
  494. warningLevel = v;
  495. }
  496. qreal VolumeMeter::getErrorLevel() const
  497. {
  498. return errorLevel;
  499. }
  500. void VolumeMeter::setErrorLevel(qreal v)
  501. {
  502. errorLevel = v;
  503. }
  504. qreal VolumeMeter::getClipLevel() const
  505. {
  506. return clipLevel;
  507. }
  508. void VolumeMeter::setClipLevel(qreal v)
  509. {
  510. clipLevel = v;
  511. }
  512. qreal VolumeMeter::getMinimumInputLevel() const
  513. {
  514. return minimumInputLevel;
  515. }
  516. void VolumeMeter::setMinimumInputLevel(qreal v)
  517. {
  518. minimumInputLevel = v;
  519. }
  520. qreal VolumeMeter::getPeakDecayRate() const
  521. {
  522. return peakDecayRate;
  523. }
  524. void VolumeMeter::setPeakDecayRate(qreal v)
  525. {
  526. peakDecayRate = v;
  527. }
  528. qreal VolumeMeter::getMagnitudeIntegrationTime() const
  529. {
  530. return magnitudeIntegrationTime;
  531. }
  532. void VolumeMeter::setMagnitudeIntegrationTime(qreal v)
  533. {
  534. magnitudeIntegrationTime = v;
  535. }
  536. qreal VolumeMeter::getPeakHoldDuration() const
  537. {
  538. return peakHoldDuration;
  539. }
  540. void VolumeMeter::setPeakHoldDuration(qreal v)
  541. {
  542. peakHoldDuration = v;
  543. }
  544. qreal VolumeMeter::getInputPeakHoldDuration() const
  545. {
  546. return inputPeakHoldDuration;
  547. }
  548. void VolumeMeter::setInputPeakHoldDuration(qreal v)
  549. {
  550. inputPeakHoldDuration = v;
  551. }
  552. void VolumeMeter::setPeakMeterType(enum obs_peak_meter_type peakMeterType)
  553. {
  554. obs_volmeter_set_peak_meter_type(obs_volmeter, peakMeterType);
  555. switch (peakMeterType) {
  556. case TRUE_PEAK_METER:
  557. // For true-peak meters EBU has defined the Permitted Maximum,
  558. // taking into account the accuracy of the meter and further
  559. // processing required by lossy audio compression.
  560. //
  561. // The alignment level was not specified, but I've adjusted
  562. // it compared to a sample-peak meter. Incidentally Youtube
  563. // uses this new Alignment Level as the maximum integrated
  564. // loudness of a video.
  565. //
  566. // * Permitted Maximum Level (PML) = -2.0 dBTP
  567. // * Alignment Level (AL) = -13 dBTP
  568. setErrorLevel(-2.0);
  569. setWarningLevel(-13.0);
  570. break;
  571. case SAMPLE_PEAK_METER:
  572. default:
  573. // For a sample Peak Meter EBU has the following level
  574. // definitions, taking into account inaccuracies of this meter:
  575. //
  576. // * Permitted Maximum Level (PML) = -9.0 dBFS
  577. // * Alignment Level (AL) = -20.0 dBFS
  578. setErrorLevel(-9.0);
  579. setWarningLevel(-20.0);
  580. break;
  581. }
  582. }
  583. void VolumeMeter::mousePressEvent(QMouseEvent *event)
  584. {
  585. setFocus(Qt::MouseFocusReason);
  586. event->accept();
  587. }
  588. void VolumeMeter::wheelEvent(QWheelEvent *event)
  589. {
  590. QApplication::sendEvent(focusProxy(), event);
  591. }
  592. VolumeMeter::VolumeMeter(QWidget *parent, obs_volmeter_t *obs_volmeter,
  593. bool vertical)
  594. : QWidget(parent), obs_volmeter(obs_volmeter), vertical(vertical)
  595. {
  596. setAttribute(Qt::WA_OpaquePaintEvent, true);
  597. // Default meter settings, they only show if
  598. // there is no stylesheet, do not remove.
  599. backgroundNominalColor.setRgb(0x26, 0x7f, 0x26); // Dark green
  600. backgroundWarningColor.setRgb(0x7f, 0x7f, 0x26); // Dark yellow
  601. backgroundErrorColor.setRgb(0x7f, 0x26, 0x26); // Dark red
  602. foregroundNominalColor.setRgb(0x4c, 0xff, 0x4c); // Bright green
  603. foregroundWarningColor.setRgb(0xff, 0xff, 0x4c); // Bright yellow
  604. foregroundErrorColor.setRgb(0xff, 0x4c, 0x4c); // Bright red
  605. backgroundNominalColorDisabled.setRgb(90, 90, 90);
  606. backgroundWarningColorDisabled.setRgb(117, 117, 117);
  607. backgroundErrorColorDisabled.setRgb(65, 65, 65);
  608. foregroundNominalColorDisabled.setRgb(163, 163, 163);
  609. foregroundWarningColorDisabled.setRgb(217, 217, 217);
  610. foregroundErrorColorDisabled.setRgb(113, 113, 113);
  611. clipColor.setRgb(0xff, 0xff, 0xff); // Bright white
  612. magnitudeColor.setRgb(0x00, 0x00, 0x00); // Black
  613. majorTickColor.setRgb(0xff, 0xff, 0xff); // Black
  614. minorTickColor.setRgb(0xcc, 0xcc, 0xcc); // Black
  615. minimumLevel = -60.0; // -60 dB
  616. warningLevel = -20.0; // -20 dB
  617. errorLevel = -9.0; // -9 dB
  618. clipLevel = -0.5; // -0.5 dB
  619. minimumInputLevel = -50.0; // -50 dB
  620. peakDecayRate = 11.76; // 20 dB / 1.7 sec
  621. magnitudeIntegrationTime = 0.3; // 99% in 300 ms
  622. peakHoldDuration = 20.0; // 20 seconds
  623. inputPeakHoldDuration = 1.0; // 1 second
  624. meterThickness = 3; // Bar thickness in pixels
  625. meterFontScaling =
  626. 0.7; // Font size for numbers is 70% of Widget's font size
  627. channels = (int)audio_output_get_channels(obs_get_audio());
  628. doLayout();
  629. updateTimerRef = updateTimer.toStrongRef();
  630. if (!updateTimerRef) {
  631. updateTimerRef = QSharedPointer<VolumeMeterTimer>::create();
  632. updateTimerRef->setTimerType(Qt::PreciseTimer);
  633. updateTimerRef->start(16);
  634. updateTimer = updateTimerRef;
  635. }
  636. updateTimerRef->AddVolControl(this);
  637. }
  638. VolumeMeter::~VolumeMeter()
  639. {
  640. updateTimerRef->RemoveVolControl(this);
  641. }
  642. void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS],
  643. const float peak[MAX_AUDIO_CHANNELS],
  644. const float inputPeak[MAX_AUDIO_CHANNELS])
  645. {
  646. uint64_t ts = os_gettime_ns();
  647. QMutexLocker locker(&dataMutex);
  648. currentLastUpdateTime = ts;
  649. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  650. currentMagnitude[channelNr] = magnitude[channelNr];
  651. currentPeak[channelNr] = peak[channelNr];
  652. currentInputPeak[channelNr] = inputPeak[channelNr];
  653. }
  654. // In case there are more updates then redraws we must make sure
  655. // that the ballistics of peak and hold are recalculated.
  656. locker.unlock();
  657. calculateBallistics(ts);
  658. }
  659. inline void VolumeMeter::resetLevels()
  660. {
  661. currentLastUpdateTime = 0;
  662. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  663. currentMagnitude[channelNr] = -M_INFINITE;
  664. currentPeak[channelNr] = -M_INFINITE;
  665. currentInputPeak[channelNr] = -M_INFINITE;
  666. displayMagnitude[channelNr] = -M_INFINITE;
  667. displayPeak[channelNr] = -M_INFINITE;
  668. displayPeakHold[channelNr] = -M_INFINITE;
  669. displayPeakHoldLastUpdateTime[channelNr] = 0;
  670. displayInputPeakHold[channelNr] = -M_INFINITE;
  671. displayInputPeakHoldLastUpdateTime[channelNr] = 0;
  672. }
  673. }
  674. bool VolumeMeter::needLayoutChange()
  675. {
  676. int currentNrAudioChannels = obs_volmeter_get_nr_channels(obs_volmeter);
  677. if (!currentNrAudioChannels) {
  678. struct obs_audio_info oai;
  679. obs_get_audio_info(&oai);
  680. currentNrAudioChannels = (oai.speakers == SPEAKERS_MONO) ? 1
  681. : 2;
  682. }
  683. if (displayNrAudioChannels != currentNrAudioChannels) {
  684. displayNrAudioChannels = currentNrAudioChannels;
  685. recalculateLayout = true;
  686. }
  687. return recalculateLayout;
  688. }
  689. // When this is called from the constructor, obs_volmeter_get_nr_channels has not
  690. // yet been called and Q_PROPERTY settings have not yet been read from the
  691. // stylesheet.
  692. inline void VolumeMeter::doLayout()
  693. {
  694. QMutexLocker locker(&dataMutex);
  695. recalculateLayout = false;
  696. tickFont = font();
  697. QFontInfo info(tickFont);
  698. tickFont.setPointSizeF(info.pointSizeF() * meterFontScaling);
  699. QFontMetrics metrics(tickFont);
  700. if (vertical) {
  701. // Each meter channel is meterThickness pixels wide, plus one pixel
  702. // between channels, but not after the last.
  703. // Add 4 pixels for ticks, space to hold our longest label in this font,
  704. // and a few pixels before the fader.
  705. QRect scaleBounds = metrics.boundingRect("-88");
  706. setMinimumSize(displayNrAudioChannels * (meterThickness + 1) -
  707. 1 + 4 + scaleBounds.width() + 2,
  708. 130);
  709. } else {
  710. // Each meter channel is meterThickness pixels high, plus one pixel
  711. // between channels, but not after the last.
  712. // Add 4 pixels for ticks, and space high enough to hold our label in
  713. // this font, presuming that digits don't have descenders.
  714. setMinimumSize(130,
  715. displayNrAudioChannels * (meterThickness + 1) -
  716. 1 + 4 + metrics.capHeight());
  717. }
  718. resetLevels();
  719. }
  720. inline bool VolumeMeter::detectIdle(uint64_t ts)
  721. {
  722. double timeSinceLastUpdate = (ts - currentLastUpdateTime) * 0.000000001;
  723. if (timeSinceLastUpdate > 0.5) {
  724. resetLevels();
  725. return true;
  726. } else {
  727. return false;
  728. }
  729. }
  730. inline void
  731. VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts,
  732. qreal timeSinceLastRedraw)
  733. {
  734. if (currentPeak[channelNr] >= displayPeak[channelNr] ||
  735. isnan(displayPeak[channelNr])) {
  736. // Attack of peak is immediate.
  737. displayPeak[channelNr] = currentPeak[channelNr];
  738. } else {
  739. // Decay of peak is 40 dB / 1.7 seconds for Fast Profile
  740. // 20 dB / 1.7 seconds for Medium Profile (Type I PPM)
  741. // 24 dB / 2.8 seconds for Slow Profile (Type II PPM)
  742. float decay = float(peakDecayRate * timeSinceLastRedraw);
  743. displayPeak[channelNr] = CLAMP(displayPeak[channelNr] - decay,
  744. currentPeak[channelNr], 0);
  745. }
  746. if (currentPeak[channelNr] >= displayPeakHold[channelNr] ||
  747. !isfinite(displayPeakHold[channelNr])) {
  748. // Attack of peak-hold is immediate, but keep track
  749. // when it was last updated.
  750. displayPeakHold[channelNr] = currentPeak[channelNr];
  751. displayPeakHoldLastUpdateTime[channelNr] = ts;
  752. } else {
  753. // The peak and hold falls back to peak
  754. // after 20 seconds.
  755. qreal timeSinceLastPeak =
  756. (uint64_t)(ts -
  757. displayPeakHoldLastUpdateTime[channelNr]) *
  758. 0.000000001;
  759. if (timeSinceLastPeak > peakHoldDuration) {
  760. displayPeakHold[channelNr] = currentPeak[channelNr];
  761. displayPeakHoldLastUpdateTime[channelNr] = ts;
  762. }
  763. }
  764. if (currentInputPeak[channelNr] >= displayInputPeakHold[channelNr] ||
  765. !isfinite(displayInputPeakHold[channelNr])) {
  766. // Attack of peak-hold is immediate, but keep track
  767. // when it was last updated.
  768. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  769. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  770. } else {
  771. // The peak and hold falls back to peak after 1 second.
  772. qreal timeSinceLastPeak =
  773. (uint64_t)(ts -
  774. displayInputPeakHoldLastUpdateTime[channelNr]) *
  775. 0.000000001;
  776. if (timeSinceLastPeak > inputPeakHoldDuration) {
  777. displayInputPeakHold[channelNr] =
  778. currentInputPeak[channelNr];
  779. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  780. }
  781. }
  782. if (!isfinite(displayMagnitude[channelNr])) {
  783. // The statements in the else-leg do not work with
  784. // NaN and infinite displayMagnitude.
  785. displayMagnitude[channelNr] = currentMagnitude[channelNr];
  786. } else {
  787. // A VU meter will integrate to the new value to 99% in 300 ms.
  788. // The calculation here is very simplified and is more accurate
  789. // with higher frame-rate.
  790. float attack =
  791. float((currentMagnitude[channelNr] -
  792. displayMagnitude[channelNr]) *
  793. (timeSinceLastRedraw / magnitudeIntegrationTime) *
  794. 0.99);
  795. displayMagnitude[channelNr] =
  796. CLAMP(displayMagnitude[channelNr] + attack,
  797. (float)minimumLevel, 0);
  798. }
  799. }
  800. inline void VolumeMeter::calculateBallistics(uint64_t ts,
  801. qreal timeSinceLastRedraw)
  802. {
  803. QMutexLocker locker(&dataMutex);
  804. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++)
  805. calculateBallisticsForChannel(channelNr, ts,
  806. timeSinceLastRedraw);
  807. }
  808. void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width,
  809. int height, float peakHold)
  810. {
  811. QMutexLocker locker(&dataMutex);
  812. QColor color;
  813. if (peakHold < minimumInputLevel)
  814. color = backgroundNominalColor;
  815. else if (peakHold < warningLevel)
  816. color = foregroundNominalColor;
  817. else if (peakHold < errorLevel)
  818. color = foregroundWarningColor;
  819. else if (peakHold <= clipLevel)
  820. color = foregroundErrorColor;
  821. else
  822. color = clipColor;
  823. painter.fillRect(x, y, width, height, color);
  824. }
  825. void VolumeMeter::paintHTicks(QPainter &painter, int x, int y, int width)
  826. {
  827. qreal scale = width / minimumLevel;
  828. painter.setFont(tickFont);
  829. QFontMetrics metrics(tickFont);
  830. painter.setPen(majorTickColor);
  831. // Draw major tick lines and numeric indicators.
  832. for (int i = 0; i >= minimumLevel; i -= 5) {
  833. int position = int(x + width - (i * scale) - 1);
  834. QString str = QString::number(i);
  835. // Center the number on the tick, but don't overflow
  836. QRect textBounds = metrics.boundingRect(str);
  837. int pos;
  838. if (i == 0) {
  839. pos = position - textBounds.width();
  840. } else {
  841. pos = position - (textBounds.width() / 2);
  842. if (pos < 0)
  843. pos = 0;
  844. }
  845. painter.drawText(pos, y + 4 + metrics.capHeight(), str);
  846. painter.drawLine(position, y, position, y + 2);
  847. }
  848. // Draw minor tick lines.
  849. painter.setPen(minorTickColor);
  850. for (int i = 0; i >= minimumLevel; i--) {
  851. int position = int(x + width - (i * scale) - 1);
  852. if (i % 5 != 0)
  853. painter.drawLine(position, y, position, y + 1);
  854. }
  855. }
  856. void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height)
  857. {
  858. qreal scale = height / minimumLevel;
  859. painter.setFont(tickFont);
  860. QFontMetrics metrics(tickFont);
  861. painter.setPen(majorTickColor);
  862. // Draw major tick lines and numeric indicators.
  863. for (int i = 0; i >= minimumLevel; i -= 5) {
  864. int position = y + int(i * scale) + METER_PADDING;
  865. QString str = QString::number(i);
  866. // Center the number on the tick, but don't overflow
  867. if (i == 0) {
  868. painter.drawText(x + 6, position + metrics.capHeight(),
  869. str);
  870. } else {
  871. painter.drawText(x + 4,
  872. position + (metrics.capHeight() / 2),
  873. str);
  874. }
  875. painter.drawLine(x, position, x + 2, position);
  876. }
  877. // Draw minor tick lines.
  878. painter.setPen(minorTickColor);
  879. for (int i = 0; i >= minimumLevel; i--) {
  880. int position = y + int(i * scale) + METER_PADDING;
  881. if (i % 5 != 0)
  882. painter.drawLine(x, position, x + 1, position);
  883. }
  884. }
  885. #define CLIP_FLASH_DURATION_MS 1000
  886. void VolumeMeter::ClipEnding()
  887. {
  888. clipping = false;
  889. }
  890. inline int VolumeMeter::convertToInt(float number)
  891. {
  892. constexpr int min = std::numeric_limits<int>::min();
  893. constexpr int max = std::numeric_limits<int>::max();
  894. // NOTE: Conversion from 'const int' to 'float' changes max value from 2147483647 to 2147483648
  895. if (number >= (float)max)
  896. return max;
  897. else if (number < min)
  898. return min;
  899. else
  900. return int(number);
  901. }
  902. void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width,
  903. int height, float magnitude, float peak,
  904. float peakHold)
  905. {
  906. qreal scale = width / minimumLevel;
  907. QMutexLocker locker(&dataMutex);
  908. int minimumPosition = x + 0;
  909. int maximumPosition = x + width;
  910. int magnitudePosition = x + width - convertToInt(magnitude * scale);
  911. int peakPosition = x + width - convertToInt(peak * scale);
  912. int peakHoldPosition = x + width - convertToInt(peakHold * scale);
  913. int warningPosition = x + width - convertToInt(warningLevel * scale);
  914. int errorPosition = x + width - convertToInt(errorLevel * scale);
  915. int nominalLength = warningPosition - minimumPosition;
  916. int warningLength = errorPosition - warningPosition;
  917. int errorLength = maximumPosition - errorPosition;
  918. locker.unlock();
  919. if (clipping) {
  920. peakPosition = maximumPosition;
  921. }
  922. if (peakPosition < minimumPosition) {
  923. painter.fillRect(minimumPosition, y, nominalLength, height,
  924. muted ? backgroundNominalColorDisabled
  925. : backgroundNominalColor);
  926. painter.fillRect(warningPosition, y, warningLength, height,
  927. muted ? backgroundWarningColorDisabled
  928. : backgroundWarningColor);
  929. painter.fillRect(errorPosition, y, errorLength, height,
  930. muted ? backgroundErrorColorDisabled
  931. : backgroundErrorColor);
  932. } else if (peakPosition < warningPosition) {
  933. painter.fillRect(minimumPosition, y,
  934. peakPosition - minimumPosition, height,
  935. muted ? foregroundNominalColorDisabled
  936. : foregroundNominalColor);
  937. painter.fillRect(peakPosition, y,
  938. warningPosition - peakPosition, height,
  939. muted ? backgroundNominalColorDisabled
  940. : backgroundNominalColor);
  941. painter.fillRect(warningPosition, y, warningLength, height,
  942. muted ? backgroundWarningColorDisabled
  943. : backgroundWarningColor);
  944. painter.fillRect(errorPosition, y, errorLength, height,
  945. muted ? backgroundErrorColorDisabled
  946. : backgroundErrorColor);
  947. } else if (peakPosition < errorPosition) {
  948. painter.fillRect(minimumPosition, y, nominalLength, height,
  949. muted ? foregroundNominalColorDisabled
  950. : foregroundNominalColor);
  951. painter.fillRect(warningPosition, y,
  952. peakPosition - warningPosition, height,
  953. muted ? foregroundWarningColorDisabled
  954. : foregroundWarningColor);
  955. painter.fillRect(peakPosition, y, errorPosition - peakPosition,
  956. height,
  957. muted ? backgroundWarningColorDisabled
  958. : backgroundWarningColor);
  959. painter.fillRect(errorPosition, y, errorLength, height,
  960. muted ? backgroundErrorColorDisabled
  961. : backgroundErrorColor);
  962. } else if (peakPosition < maximumPosition) {
  963. painter.fillRect(minimumPosition, y, nominalLength, height,
  964. muted ? foregroundNominalColorDisabled
  965. : foregroundNominalColor);
  966. painter.fillRect(warningPosition, y, warningLength, height,
  967. muted ? foregroundWarningColorDisabled
  968. : foregroundWarningColor);
  969. painter.fillRect(errorPosition, y, peakPosition - errorPosition,
  970. height,
  971. muted ? foregroundErrorColorDisabled
  972. : foregroundErrorColor);
  973. painter.fillRect(peakPosition, y,
  974. maximumPosition - peakPosition, height,
  975. muted ? backgroundErrorColorDisabled
  976. : backgroundErrorColor);
  977. } else if (int(magnitude) != 0) {
  978. if (!clipping) {
  979. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  980. SLOT(ClipEnding()));
  981. clipping = true;
  982. }
  983. int end = errorLength + warningLength + nominalLength;
  984. painter.fillRect(minimumPosition, y, end, height,
  985. QBrush(muted ? foregroundErrorColorDisabled
  986. : foregroundErrorColor));
  987. }
  988. if (peakHoldPosition - 3 < minimumPosition)
  989. ; // Peak-hold below minimum, no drawing.
  990. else if (peakHoldPosition < warningPosition)
  991. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  992. muted ? foregroundNominalColorDisabled
  993. : foregroundNominalColor);
  994. else if (peakHoldPosition < errorPosition)
  995. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  996. muted ? foregroundWarningColorDisabled
  997. : foregroundWarningColor);
  998. else
  999. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  1000. muted ? foregroundErrorColorDisabled
  1001. : foregroundErrorColor);
  1002. if (magnitudePosition - 3 >= minimumPosition)
  1003. painter.fillRect(magnitudePosition - 3, y, 3, height,
  1004. magnitudeColor);
  1005. }
  1006. void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width,
  1007. int height, float magnitude, float peak,
  1008. float peakHold)
  1009. {
  1010. qreal scale = height / minimumLevel;
  1011. QMutexLocker locker(&dataMutex);
  1012. int minimumPosition = y + 0;
  1013. int maximumPosition = y + height;
  1014. int magnitudePosition = y + height - convertToInt(magnitude * scale);
  1015. int peakPosition = y + height - convertToInt(peak * scale);
  1016. int peakHoldPosition = y + height - convertToInt(peakHold * scale);
  1017. int warningPosition = y + height - convertToInt(warningLevel * scale);
  1018. int errorPosition = y + height - convertToInt(errorLevel * scale);
  1019. int nominalLength = warningPosition - minimumPosition;
  1020. int warningLength = errorPosition - warningPosition;
  1021. int errorLength = maximumPosition - errorPosition;
  1022. locker.unlock();
  1023. if (clipping) {
  1024. peakPosition = maximumPosition;
  1025. }
  1026. if (peakPosition < minimumPosition) {
  1027. painter.fillRect(x, minimumPosition, width, nominalLength,
  1028. muted ? backgroundNominalColorDisabled
  1029. : backgroundNominalColor);
  1030. painter.fillRect(x, warningPosition, width, warningLength,
  1031. muted ? backgroundWarningColorDisabled
  1032. : backgroundWarningColor);
  1033. painter.fillRect(x, errorPosition, width, errorLength,
  1034. muted ? backgroundErrorColorDisabled
  1035. : backgroundErrorColor);
  1036. } else if (peakPosition < warningPosition) {
  1037. painter.fillRect(x, minimumPosition, width,
  1038. peakPosition - minimumPosition,
  1039. muted ? foregroundNominalColorDisabled
  1040. : foregroundNominalColor);
  1041. painter.fillRect(x, peakPosition, width,
  1042. warningPosition - peakPosition,
  1043. muted ? backgroundNominalColorDisabled
  1044. : backgroundNominalColor);
  1045. painter.fillRect(x, warningPosition, width, warningLength,
  1046. muted ? backgroundWarningColorDisabled
  1047. : backgroundWarningColor);
  1048. painter.fillRect(x, errorPosition, width, errorLength,
  1049. muted ? backgroundErrorColorDisabled
  1050. : backgroundErrorColor);
  1051. } else if (peakPosition < errorPosition) {
  1052. painter.fillRect(x, minimumPosition, width, nominalLength,
  1053. muted ? foregroundNominalColorDisabled
  1054. : foregroundNominalColor);
  1055. painter.fillRect(x, warningPosition, width,
  1056. peakPosition - warningPosition,
  1057. muted ? foregroundWarningColorDisabled
  1058. : foregroundWarningColor);
  1059. painter.fillRect(x, peakPosition, width,
  1060. errorPosition - peakPosition,
  1061. muted ? backgroundWarningColorDisabled
  1062. : backgroundWarningColor);
  1063. painter.fillRect(x, errorPosition, width, errorLength,
  1064. muted ? backgroundErrorColorDisabled
  1065. : backgroundErrorColor);
  1066. } else if (peakPosition < maximumPosition) {
  1067. painter.fillRect(x, minimumPosition, width, nominalLength,
  1068. muted ? foregroundNominalColorDisabled
  1069. : foregroundNominalColor);
  1070. painter.fillRect(x, warningPosition, width, warningLength,
  1071. muted ? foregroundWarningColorDisabled
  1072. : foregroundWarningColor);
  1073. painter.fillRect(x, errorPosition, width,
  1074. peakPosition - errorPosition,
  1075. muted ? foregroundErrorColorDisabled
  1076. : foregroundErrorColor);
  1077. painter.fillRect(x, peakPosition, width,
  1078. maximumPosition - peakPosition,
  1079. muted ? backgroundErrorColorDisabled
  1080. : backgroundErrorColor);
  1081. } else {
  1082. if (!clipping) {
  1083. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  1084. SLOT(ClipEnding()));
  1085. clipping = true;
  1086. }
  1087. int end = errorLength + warningLength + nominalLength;
  1088. painter.fillRect(x, minimumPosition, width, end,
  1089. QBrush(muted ? foregroundErrorColorDisabled
  1090. : foregroundErrorColor));
  1091. }
  1092. if (peakHoldPosition - 3 < minimumPosition)
  1093. ; // Peak-hold below minimum, no drawing.
  1094. else if (peakHoldPosition < warningPosition)
  1095. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  1096. muted ? foregroundNominalColorDisabled
  1097. : foregroundNominalColor);
  1098. else if (peakHoldPosition < errorPosition)
  1099. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  1100. muted ? foregroundWarningColorDisabled
  1101. : foregroundWarningColor);
  1102. else
  1103. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  1104. muted ? foregroundErrorColorDisabled
  1105. : foregroundErrorColor);
  1106. if (magnitudePosition - 3 >= minimumPosition)
  1107. painter.fillRect(x, magnitudePosition - 3, width, 3,
  1108. magnitudeColor);
  1109. }
  1110. void VolumeMeter::paintEvent(QPaintEvent *event)
  1111. {
  1112. uint64_t ts = os_gettime_ns();
  1113. qreal timeSinceLastRedraw = (ts - lastRedrawTime) * 0.000000001;
  1114. calculateBallistics(ts, timeSinceLastRedraw);
  1115. bool idle = detectIdle(ts);
  1116. QRect widgetRect = rect();
  1117. int width = widgetRect.width();
  1118. int height = widgetRect.height();
  1119. QPainter painter(this);
  1120. if (vertical)
  1121. height -= METER_PADDING * 2;
  1122. // timerEvent requests update of the bar(s) only, so we can avoid the
  1123. // overhead of repainting the scale and labels.
  1124. if (event->region().boundingRect() != getBarRect()) {
  1125. if (needLayoutChange())
  1126. doLayout();
  1127. // Paint window background color (as widget is opaque)
  1128. QColor background =
  1129. palette().color(QPalette::ColorRole::Window);
  1130. painter.fillRect(widgetRect, background);
  1131. if (vertical) {
  1132. paintVTicks(painter,
  1133. displayNrAudioChannels *
  1134. (meterThickness + 1) -
  1135. 1,
  1136. 0, height - (INDICATOR_THICKNESS + 3));
  1137. } else {
  1138. paintHTicks(painter, INDICATOR_THICKNESS + 3,
  1139. displayNrAudioChannels *
  1140. (meterThickness + 1) -
  1141. 1,
  1142. width - (INDICATOR_THICKNESS + 3));
  1143. }
  1144. }
  1145. if (vertical) {
  1146. // Invert the Y axis to ease the math
  1147. painter.translate(0, height + METER_PADDING);
  1148. painter.scale(1, -1);
  1149. }
  1150. for (int channelNr = 0; channelNr < displayNrAudioChannels;
  1151. channelNr++) {
  1152. int channelNrFixed =
  1153. (displayNrAudioChannels == 1 && channels > 2)
  1154. ? 2
  1155. : channelNr;
  1156. if (vertical)
  1157. paintVMeter(painter, channelNr * (meterThickness + 1),
  1158. INDICATOR_THICKNESS + 2, meterThickness,
  1159. height - (INDICATOR_THICKNESS + 2),
  1160. displayMagnitude[channelNrFixed],
  1161. displayPeak[channelNrFixed],
  1162. displayPeakHold[channelNrFixed]);
  1163. else
  1164. paintHMeter(painter, INDICATOR_THICKNESS + 2,
  1165. channelNr * (meterThickness + 1),
  1166. width - (INDICATOR_THICKNESS + 2),
  1167. meterThickness,
  1168. displayMagnitude[channelNrFixed],
  1169. displayPeak[channelNrFixed],
  1170. displayPeakHold[channelNrFixed]);
  1171. if (idle)
  1172. continue;
  1173. // By not drawing the input meter boxes the user can
  1174. // see that the audio stream has been stopped, without
  1175. // having too much visual impact.
  1176. if (vertical)
  1177. paintInputMeter(painter,
  1178. channelNr * (meterThickness + 1), 0,
  1179. meterThickness, INDICATOR_THICKNESS,
  1180. displayInputPeakHold[channelNrFixed]);
  1181. else
  1182. paintInputMeter(painter, 0,
  1183. channelNr * (meterThickness + 1),
  1184. INDICATOR_THICKNESS, meterThickness,
  1185. displayInputPeakHold[channelNrFixed]);
  1186. }
  1187. lastRedrawTime = ts;
  1188. }
  1189. QRect VolumeMeter::getBarRect() const
  1190. {
  1191. QRect rec = rect();
  1192. if (vertical)
  1193. rec.setWidth(displayNrAudioChannels * (meterThickness + 1) - 1);
  1194. else
  1195. rec.setHeight(displayNrAudioChannels * (meterThickness + 1) -
  1196. 1);
  1197. return rec;
  1198. }
  1199. void VolumeMeter::changeEvent(QEvent *e)
  1200. {
  1201. if (e->type() == QEvent::StyleChange)
  1202. recalculateLayout = true;
  1203. QWidget::changeEvent(e);
  1204. }
  1205. void VolumeMeterTimer::AddVolControl(VolumeMeter *meter)
  1206. {
  1207. volumeMeters.push_back(meter);
  1208. }
  1209. void VolumeMeterTimer::RemoveVolControl(VolumeMeter *meter)
  1210. {
  1211. volumeMeters.removeOne(meter);
  1212. }
  1213. void VolumeMeterTimer::timerEvent(QTimerEvent *)
  1214. {
  1215. for (VolumeMeter *meter : volumeMeters) {
  1216. if (meter->needLayoutChange()) {
  1217. // Tell paintEvent to update layout and paint everything
  1218. meter->update();
  1219. } else {
  1220. // Tell paintEvent to paint only the bars
  1221. meter->update(meter->getBarRect());
  1222. }
  1223. }
  1224. }