volume-control.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239
  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. delete tickPaintCache;
  553. }
  554. void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS],
  555. const float peak[MAX_AUDIO_CHANNELS],
  556. const float inputPeak[MAX_AUDIO_CHANNELS])
  557. {
  558. uint64_t ts = os_gettime_ns();
  559. QMutexLocker locker(&dataMutex);
  560. currentLastUpdateTime = ts;
  561. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  562. currentMagnitude[channelNr] = magnitude[channelNr];
  563. currentPeak[channelNr] = peak[channelNr];
  564. currentInputPeak[channelNr] = inputPeak[channelNr];
  565. }
  566. // In case there are more updates then redraws we must make sure
  567. // that the ballistics of peak and hold are recalculated.
  568. locker.unlock();
  569. calculateBallistics(ts);
  570. }
  571. inline void VolumeMeter::resetLevels()
  572. {
  573. currentLastUpdateTime = 0;
  574. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  575. currentMagnitude[channelNr] = -M_INFINITE;
  576. currentPeak[channelNr] = -M_INFINITE;
  577. currentInputPeak[channelNr] = -M_INFINITE;
  578. displayMagnitude[channelNr] = -M_INFINITE;
  579. displayPeak[channelNr] = -M_INFINITE;
  580. displayPeakHold[channelNr] = -M_INFINITE;
  581. displayPeakHoldLastUpdateTime[channelNr] = 0;
  582. displayInputPeakHold[channelNr] = -M_INFINITE;
  583. displayInputPeakHoldLastUpdateTime[channelNr] = 0;
  584. }
  585. }
  586. inline void VolumeMeter::handleChannelCofigurationChange()
  587. {
  588. QMutexLocker locker(&dataMutex);
  589. int currentNrAudioChannels = obs_volmeter_get_nr_channels(obs_volmeter);
  590. if (displayNrAudioChannels != currentNrAudioChannels) {
  591. displayNrAudioChannels = currentNrAudioChannels;
  592. // Make room for 3 pixels meter, with one pixel between each.
  593. // Then 9/13 pixels for ticks and numbers.
  594. if (vertical)
  595. setMinimumSize(displayNrAudioChannels * 4 + 14, 130);
  596. else
  597. setMinimumSize(130, displayNrAudioChannels * 4 + 8);
  598. resetLevels();
  599. }
  600. }
  601. inline bool VolumeMeter::detectIdle(uint64_t ts)
  602. {
  603. double timeSinceLastUpdate = (ts - currentLastUpdateTime) * 0.000000001;
  604. if (timeSinceLastUpdate > 0.5) {
  605. resetLevels();
  606. return true;
  607. } else {
  608. return false;
  609. }
  610. }
  611. inline void
  612. VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts,
  613. qreal timeSinceLastRedraw)
  614. {
  615. if (currentPeak[channelNr] >= displayPeak[channelNr] ||
  616. isnan(displayPeak[channelNr])) {
  617. // Attack of peak is immediate.
  618. displayPeak[channelNr] = currentPeak[channelNr];
  619. } else {
  620. // Decay of peak is 40 dB / 1.7 seconds for Fast Profile
  621. // 20 dB / 1.7 seconds for Medium Profile (Type I PPM)
  622. // 24 dB / 2.8 seconds for Slow Profile (Type II PPM)
  623. float decay = float(peakDecayRate * timeSinceLastRedraw);
  624. displayPeak[channelNr] = CLAMP(displayPeak[channelNr] - decay,
  625. currentPeak[channelNr], 0);
  626. }
  627. if (currentPeak[channelNr] >= displayPeakHold[channelNr] ||
  628. !isfinite(displayPeakHold[channelNr])) {
  629. // Attack of peak-hold is immediate, but keep track
  630. // when it was last updated.
  631. displayPeakHold[channelNr] = currentPeak[channelNr];
  632. displayPeakHoldLastUpdateTime[channelNr] = ts;
  633. } else {
  634. // The peak and hold falls back to peak
  635. // after 20 seconds.
  636. qreal timeSinceLastPeak =
  637. (uint64_t)(ts -
  638. displayPeakHoldLastUpdateTime[channelNr]) *
  639. 0.000000001;
  640. if (timeSinceLastPeak > peakHoldDuration) {
  641. displayPeakHold[channelNr] = currentPeak[channelNr];
  642. displayPeakHoldLastUpdateTime[channelNr] = ts;
  643. }
  644. }
  645. if (currentInputPeak[channelNr] >= displayInputPeakHold[channelNr] ||
  646. !isfinite(displayInputPeakHold[channelNr])) {
  647. // Attack of peak-hold is immediate, but keep track
  648. // when it was last updated.
  649. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  650. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  651. } else {
  652. // The peak and hold falls back to peak after 1 second.
  653. qreal timeSinceLastPeak =
  654. (uint64_t)(ts -
  655. displayInputPeakHoldLastUpdateTime[channelNr]) *
  656. 0.000000001;
  657. if (timeSinceLastPeak > inputPeakHoldDuration) {
  658. displayInputPeakHold[channelNr] =
  659. currentInputPeak[channelNr];
  660. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  661. }
  662. }
  663. if (!isfinite(displayMagnitude[channelNr])) {
  664. // The statements in the else-leg do not work with
  665. // NaN and infinite displayMagnitude.
  666. displayMagnitude[channelNr] = currentMagnitude[channelNr];
  667. } else {
  668. // A VU meter will integrate to the new value to 99% in 300 ms.
  669. // The calculation here is very simplified and is more accurate
  670. // with higher frame-rate.
  671. float attack =
  672. float((currentMagnitude[channelNr] -
  673. displayMagnitude[channelNr]) *
  674. (timeSinceLastRedraw / magnitudeIntegrationTime) *
  675. 0.99);
  676. displayMagnitude[channelNr] =
  677. CLAMP(displayMagnitude[channelNr] + attack,
  678. (float)minimumLevel, 0);
  679. }
  680. }
  681. inline void VolumeMeter::calculateBallistics(uint64_t ts,
  682. qreal timeSinceLastRedraw)
  683. {
  684. QMutexLocker locker(&dataMutex);
  685. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++)
  686. calculateBallisticsForChannel(channelNr, ts,
  687. timeSinceLastRedraw);
  688. }
  689. void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width,
  690. int height, float peakHold)
  691. {
  692. QMutexLocker locker(&dataMutex);
  693. QColor color;
  694. if (peakHold < minimumInputLevel)
  695. color = backgroundNominalColor;
  696. else if (peakHold < warningLevel)
  697. color = foregroundNominalColor;
  698. else if (peakHold < errorLevel)
  699. color = foregroundWarningColor;
  700. else if (peakHold <= clipLevel)
  701. color = foregroundErrorColor;
  702. else
  703. color = clipColor;
  704. painter.fillRect(x, y, width, height, color);
  705. }
  706. void VolumeMeter::paintHTicks(QPainter &painter, int x, int y, int width,
  707. int height)
  708. {
  709. qreal scale = width / minimumLevel;
  710. painter.setFont(tickFont);
  711. painter.setPen(majorTickColor);
  712. // Draw major tick lines and numeric indicators.
  713. for (int i = 0; i >= minimumLevel; i -= 5) {
  714. int position = int(x + width - (i * scale) - 1);
  715. QString str = QString::number(i);
  716. if (i == 0 || i == -5)
  717. painter.drawText(position - 3, height, str);
  718. else
  719. painter.drawText(position - 5, height, str);
  720. painter.drawLine(position, y, position, y + 2);
  721. }
  722. // Draw minor tick lines.
  723. painter.setPen(minorTickColor);
  724. for (int i = 0; i >= minimumLevel; i--) {
  725. int position = int(x + width - (i * scale) - 1);
  726. if (i % 5 != 0)
  727. painter.drawLine(position, y, position, y + 1);
  728. }
  729. }
  730. void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height)
  731. {
  732. qreal scale = height / minimumLevel;
  733. painter.setFont(tickFont);
  734. painter.setPen(majorTickColor);
  735. // Draw major tick lines and numeric indicators.
  736. for (int i = 0; i >= minimumLevel; i -= 5) {
  737. int position = y + int((i * scale) - 1);
  738. QString str = QString::number(i);
  739. if (i == 0)
  740. painter.drawText(x + 5, position + 4, str);
  741. else if (i == -60)
  742. painter.drawText(x + 4, position, str);
  743. else
  744. painter.drawText(x + 4, position + 2, str);
  745. painter.drawLine(x, position, x + 2, position);
  746. }
  747. // Draw minor tick lines.
  748. painter.setPen(minorTickColor);
  749. for (int i = 0; i >= minimumLevel; i--) {
  750. int position = y + int((i * scale) - 1);
  751. if (i % 5 != 0)
  752. painter.drawLine(x, position, x + 1, position);
  753. }
  754. }
  755. #define CLIP_FLASH_DURATION_MS 1000
  756. void VolumeMeter::ClipEnding()
  757. {
  758. clipping = false;
  759. }
  760. void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width,
  761. int height, float magnitude, float peak,
  762. float peakHold)
  763. {
  764. qreal scale = width / minimumLevel;
  765. QMutexLocker locker(&dataMutex);
  766. int minimumPosition = x + 0;
  767. int maximumPosition = x + width;
  768. int magnitudePosition = int(x + width - (magnitude * scale));
  769. int peakPosition = int(x + width - (peak * scale));
  770. int peakHoldPosition = int(x + width - (peakHold * scale));
  771. int warningPosition = int(x + width - (warningLevel * scale));
  772. int errorPosition = int(x + width - (errorLevel * scale));
  773. int nominalLength = warningPosition - minimumPosition;
  774. int warningLength = errorPosition - warningPosition;
  775. int errorLength = maximumPosition - errorPosition;
  776. locker.unlock();
  777. if (clipping) {
  778. peakPosition = maximumPosition;
  779. }
  780. if (peakPosition < minimumPosition) {
  781. painter.fillRect(minimumPosition, y, nominalLength, height,
  782. muted ? backgroundNominalColorDisabled
  783. : backgroundNominalColor);
  784. painter.fillRect(warningPosition, y, warningLength, height,
  785. muted ? backgroundWarningColorDisabled
  786. : backgroundWarningColor);
  787. painter.fillRect(errorPosition, y, errorLength, height,
  788. muted ? backgroundErrorColorDisabled
  789. : backgroundErrorColor);
  790. } else if (peakPosition < warningPosition) {
  791. painter.fillRect(minimumPosition, y,
  792. peakPosition - minimumPosition, height,
  793. muted ? foregroundNominalColorDisabled
  794. : foregroundNominalColor);
  795. painter.fillRect(peakPosition, y,
  796. warningPosition - peakPosition, height,
  797. muted ? backgroundNominalColorDisabled
  798. : backgroundNominalColor);
  799. painter.fillRect(warningPosition, y, warningLength, height,
  800. muted ? backgroundWarningColorDisabled
  801. : backgroundWarningColor);
  802. painter.fillRect(errorPosition, y, errorLength, height,
  803. muted ? backgroundErrorColorDisabled
  804. : backgroundErrorColor);
  805. } else if (peakPosition < errorPosition) {
  806. painter.fillRect(minimumPosition, y, nominalLength, height,
  807. muted ? foregroundNominalColorDisabled
  808. : foregroundNominalColor);
  809. painter.fillRect(warningPosition, y,
  810. peakPosition - warningPosition, height,
  811. muted ? foregroundWarningColorDisabled
  812. : foregroundWarningColor);
  813. painter.fillRect(peakPosition, y, errorPosition - peakPosition,
  814. height,
  815. muted ? backgroundWarningColorDisabled
  816. : backgroundWarningColor);
  817. painter.fillRect(errorPosition, y, errorLength, height,
  818. muted ? backgroundErrorColorDisabled
  819. : backgroundErrorColor);
  820. } else if (peakPosition < maximumPosition) {
  821. painter.fillRect(minimumPosition, y, nominalLength, height,
  822. muted ? foregroundNominalColorDisabled
  823. : foregroundNominalColor);
  824. painter.fillRect(warningPosition, y, warningLength, height,
  825. muted ? foregroundWarningColorDisabled
  826. : foregroundWarningColor);
  827. painter.fillRect(errorPosition, y, peakPosition - errorPosition,
  828. height,
  829. muted ? foregroundErrorColorDisabled
  830. : foregroundErrorColor);
  831. painter.fillRect(peakPosition, y,
  832. maximumPosition - peakPosition, height,
  833. muted ? backgroundErrorColorDisabled
  834. : backgroundErrorColor);
  835. } else if (int(magnitude) != 0) {
  836. if (!clipping) {
  837. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  838. SLOT(ClipEnding()));
  839. clipping = true;
  840. }
  841. int end = errorLength + warningLength + nominalLength;
  842. painter.fillRect(minimumPosition, y, end, height,
  843. QBrush(muted ? foregroundErrorColorDisabled
  844. : foregroundErrorColor));
  845. }
  846. if (peakHoldPosition - 3 < minimumPosition)
  847. ; // Peak-hold below minimum, no drawing.
  848. else if (peakHoldPosition < warningPosition)
  849. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  850. muted ? foregroundNominalColorDisabled
  851. : foregroundNominalColor);
  852. else if (peakHoldPosition < errorPosition)
  853. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  854. muted ? foregroundWarningColorDisabled
  855. : foregroundWarningColor);
  856. else
  857. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  858. muted ? foregroundErrorColorDisabled
  859. : foregroundErrorColor);
  860. if (magnitudePosition - 3 >= minimumPosition)
  861. painter.fillRect(magnitudePosition - 3, y, 3, height,
  862. magnitudeColor);
  863. }
  864. void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width,
  865. int height, float magnitude, float peak,
  866. float peakHold)
  867. {
  868. qreal scale = height / minimumLevel;
  869. QMutexLocker locker(&dataMutex);
  870. int minimumPosition = y + 0;
  871. int maximumPosition = y + height;
  872. int magnitudePosition = int(y + height - (magnitude * scale));
  873. int peakPosition = int(y + height - (peak * scale));
  874. int peakHoldPosition = int(y + height - (peakHold * scale));
  875. int warningPosition = int(y + height - (warningLevel * scale));
  876. int errorPosition = int(y + height - (errorLevel * scale));
  877. int nominalLength = warningPosition - minimumPosition;
  878. int warningLength = errorPosition - warningPosition;
  879. int errorLength = maximumPosition - errorPosition;
  880. locker.unlock();
  881. if (clipping) {
  882. peakPosition = maximumPosition;
  883. }
  884. if (peakPosition < minimumPosition) {
  885. painter.fillRect(x, minimumPosition, width, nominalLength,
  886. backgroundNominalColor);
  887. painter.fillRect(x, warningPosition, width, warningLength,
  888. backgroundWarningColor);
  889. painter.fillRect(x, errorPosition, width, errorLength,
  890. backgroundErrorColor);
  891. } else if (peakPosition < warningPosition) {
  892. painter.fillRect(x, minimumPosition, width,
  893. peakPosition - minimumPosition,
  894. foregroundNominalColor);
  895. painter.fillRect(x, peakPosition, width,
  896. warningPosition - peakPosition,
  897. backgroundNominalColor);
  898. painter.fillRect(x, warningPosition, width, warningLength,
  899. backgroundWarningColor);
  900. painter.fillRect(x, errorPosition, width, errorLength,
  901. backgroundErrorColor);
  902. } else if (peakPosition < errorPosition) {
  903. painter.fillRect(x, minimumPosition, width, nominalLength,
  904. foregroundNominalColor);
  905. painter.fillRect(x, warningPosition, width,
  906. peakPosition - warningPosition,
  907. foregroundWarningColor);
  908. painter.fillRect(x, peakPosition, width,
  909. errorPosition - peakPosition,
  910. backgroundWarningColor);
  911. painter.fillRect(x, errorPosition, width, errorLength,
  912. backgroundErrorColor);
  913. } else if (peakPosition < maximumPosition) {
  914. painter.fillRect(x, minimumPosition, width, nominalLength,
  915. foregroundNominalColor);
  916. painter.fillRect(x, warningPosition, width, warningLength,
  917. foregroundWarningColor);
  918. painter.fillRect(x, errorPosition, width,
  919. peakPosition - errorPosition,
  920. foregroundErrorColor);
  921. painter.fillRect(x, peakPosition, width,
  922. maximumPosition - peakPosition,
  923. backgroundErrorColor);
  924. } else {
  925. if (!clipping) {
  926. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  927. SLOT(ClipEnding()));
  928. clipping = true;
  929. }
  930. int end = errorLength + warningLength + nominalLength;
  931. painter.fillRect(x, minimumPosition, width, end,
  932. QBrush(foregroundErrorColor));
  933. }
  934. if (peakHoldPosition - 3 < minimumPosition)
  935. ; // Peak-hold below minimum, no drawing.
  936. else if (peakHoldPosition < warningPosition)
  937. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  938. foregroundNominalColor);
  939. else if (peakHoldPosition < errorPosition)
  940. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  941. foregroundWarningColor);
  942. else
  943. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  944. foregroundErrorColor);
  945. if (magnitudePosition - 3 >= minimumPosition)
  946. painter.fillRect(x, magnitudePosition - 3, width, 3,
  947. magnitudeColor);
  948. }
  949. void VolumeMeter::paintEvent(QPaintEvent *event)
  950. {
  951. uint64_t ts = os_gettime_ns();
  952. qreal timeSinceLastRedraw = (ts - lastRedrawTime) * 0.000000001;
  953. const QRect rect = event->region().boundingRect();
  954. int width = rect.width();
  955. int height = rect.height();
  956. handleChannelCofigurationChange();
  957. calculateBallistics(ts, timeSinceLastRedraw);
  958. bool idle = detectIdle(ts);
  959. // Draw the ticks in a off-screen buffer when the widget changes size.
  960. QSize tickPaintCacheSize;
  961. if (vertical)
  962. tickPaintCacheSize = QSize(14, height);
  963. else
  964. tickPaintCacheSize = QSize(width, 9);
  965. if (tickPaintCache == nullptr ||
  966. tickPaintCache->size() != tickPaintCacheSize) {
  967. delete tickPaintCache;
  968. tickPaintCache = new QPixmap(tickPaintCacheSize);
  969. QColor clearColor(0, 0, 0, 0);
  970. tickPaintCache->fill(clearColor);
  971. QPainter tickPainter(tickPaintCache);
  972. if (vertical) {
  973. tickPainter.translate(0, height);
  974. tickPainter.scale(1, -1);
  975. paintVTicks(tickPainter, 0, 11,
  976. tickPaintCacheSize.height() - 11);
  977. } else {
  978. paintHTicks(tickPainter, 6, 0,
  979. tickPaintCacheSize.width() - 6,
  980. tickPaintCacheSize.height());
  981. }
  982. tickPainter.end();
  983. }
  984. // Actual painting of the widget starts here.
  985. QPainter painter(this);
  986. // Paint window background color (as widget is opaque)
  987. QColor background = palette().color(QPalette::ColorRole::Window);
  988. painter.fillRect(rect, background);
  989. if (vertical) {
  990. // Invert the Y axis to ease the math
  991. painter.translate(0, height);
  992. painter.scale(1, -1);
  993. painter.drawPixmap(displayNrAudioChannels * 4 - 1, 7,
  994. *tickPaintCache);
  995. } else {
  996. painter.drawPixmap(0, height - 9, *tickPaintCache);
  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, 8, 3, height - 10,
  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, 3, 3, 3,
  1021. displayInputPeakHold[channelNrFixed]);
  1022. else
  1023. paintInputMeter(painter, 0, channelNr * 4, 3, 3,
  1024. displayInputPeakHold[channelNrFixed]);
  1025. }
  1026. lastRedrawTime = ts;
  1027. }
  1028. void VolumeMeterTimer::AddVolControl(VolumeMeter *meter)
  1029. {
  1030. volumeMeters.push_back(meter);
  1031. }
  1032. void VolumeMeterTimer::RemoveVolControl(VolumeMeter *meter)
  1033. {
  1034. volumeMeters.removeOne(meter);
  1035. }
  1036. void VolumeMeterTimer::timerEvent(QTimerEvent *)
  1037. {
  1038. for (VolumeMeter *meter : volumeMeters)
  1039. meter->update();
  1040. }