1
0

volume-control.cpp 43 KB

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