volume-control.cpp 43 KB

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