volume-control.cpp 46 KB

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