volume-control.cpp 31 KB

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