volume-control.cpp 34 KB

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