volume-control.cpp 40 KB

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