volume-control.cpp 45 KB

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