volume-control.cpp 42 KB

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