volume-control.cpp 32 KB

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