volume-control.cpp 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  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 &uuid, bool val) {
  128. OBSSourceAutoRelease source =
  129. obs_get_source_by_uuid(uuid.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. const char *uuid = obs_source_get_uuid(source);
  136. OBSBasic::Get()->undo_s.add_action(
  137. text.arg(name),
  138. std::bind(undo_redo, std::placeholders::_1, prev),
  139. std::bind(undo_redo, std::placeholders::_1, checked), uuid,
  140. uuid);
  141. }
  142. void VolControl::SliderChanged(int vol)
  143. {
  144. float prev = obs_source_get_volume(source);
  145. obs_fader_set_deflection(obs_fader, float(vol) / FADER_PRECISION);
  146. updateText();
  147. auto undo_redo = [](const std::string &uuid, float val) {
  148. OBSSourceAutoRelease source =
  149. obs_get_source_by_uuid(uuid.c_str());
  150. obs_source_set_volume(source, val);
  151. };
  152. float val = obs_source_get_volume(source);
  153. const char *name = obs_source_get_name(source);
  154. const char *uuid = obs_source_get_uuid(source);
  155. OBSBasic::Get()->undo_s.add_action(
  156. QTStr("Undo.Volume.Change").arg(name),
  157. std::bind(undo_redo, std::placeholders::_1, prev),
  158. std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid,
  159. true);
  160. }
  161. void VolControl::updateText()
  162. {
  163. QString text;
  164. float db = obs_fader_get_db(obs_fader);
  165. if (db < -96.0f)
  166. text = "-inf dB";
  167. else
  168. text = QString::number(db, 'f', 1).append(" dB");
  169. volLabel->setText(text);
  170. bool muted = obs_source_muted(source);
  171. const char *accTextLookup = muted ? "VolControl.SliderMuted"
  172. : "VolControl.SliderUnmuted";
  173. QString sourceName = obs_source_get_name(source);
  174. QString accText = QTStr(accTextLookup).arg(sourceName);
  175. slider->setAccessibleName(accText);
  176. }
  177. QString VolControl::GetName() const
  178. {
  179. return nameLabel->text();
  180. }
  181. void VolControl::SetName(const QString &newName)
  182. {
  183. nameLabel->setText(newName);
  184. }
  185. void VolControl::EmitConfigClicked()
  186. {
  187. emit ConfigClicked();
  188. }
  189. void VolControl::SetMeterDecayRate(qreal q)
  190. {
  191. volMeter->setPeakDecayRate(q);
  192. }
  193. void VolControl::setPeakMeterType(enum obs_peak_meter_type peakMeterType)
  194. {
  195. volMeter->setPeakMeterType(peakMeterType);
  196. }
  197. VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical)
  198. : source(std::move(source_)),
  199. levelTotal(0.0f),
  200. levelCount(0.0f),
  201. obs_fader(obs_fader_create(OBS_FADER_LOG)),
  202. obs_volmeter(obs_volmeter_create(OBS_FADER_LOG)),
  203. vertical(vertical),
  204. contextMenu(nullptr)
  205. {
  206. nameLabel = new QLabel();
  207. volLabel = new QLabel();
  208. mute = new MuteCheckBox();
  209. QString sourceName = obs_source_get_name(source);
  210. setObjectName(sourceName);
  211. if (showConfig) {
  212. config = new QPushButton(this);
  213. config->setProperty("themeID", "menuIconSmall");
  214. config->setSizePolicy(QSizePolicy::Maximum,
  215. QSizePolicy::Maximum);
  216. config->setMaximumSize(22, 22);
  217. config->setAutoDefault(false);
  218. config->setAccessibleName(
  219. QTStr("VolControl.Properties").arg(sourceName));
  220. connect(config, &QAbstractButton::clicked, this,
  221. &VolControl::EmitConfigClicked);
  222. }
  223. QVBoxLayout *mainLayout = new QVBoxLayout;
  224. mainLayout->setContentsMargins(4, 4, 4, 4);
  225. mainLayout->setSpacing(2);
  226. if (vertical) {
  227. QHBoxLayout *nameLayout = new QHBoxLayout;
  228. QHBoxLayout *controlLayout = new QHBoxLayout;
  229. QHBoxLayout *volLayout = new QHBoxLayout;
  230. QHBoxLayout *meterLayout = new QHBoxLayout;
  231. volMeter = new VolumeMeter(nullptr, obs_volmeter, true);
  232. slider = new VolumeSlider(obs_fader, Qt::Vertical);
  233. slider->setLayoutDirection(Qt::LeftToRight);
  234. nameLayout->setAlignment(Qt::AlignCenter);
  235. meterLayout->setAlignment(Qt::AlignCenter);
  236. controlLayout->setAlignment(Qt::AlignCenter);
  237. volLayout->setAlignment(Qt::AlignCenter);
  238. nameLayout->setContentsMargins(0, 0, 0, 0);
  239. nameLayout->setSpacing(0);
  240. nameLayout->addWidget(nameLabel);
  241. controlLayout->setContentsMargins(0, 0, 0, 0);
  242. controlLayout->setSpacing(0);
  243. if (showConfig)
  244. controlLayout->addWidget(config);
  245. controlLayout->addItem(new QSpacerItem(3, 0));
  246. // Add Headphone (audio monitoring) widget here
  247. controlLayout->addWidget(mute);
  248. meterLayout->setContentsMargins(0, 0, 0, 0);
  249. meterLayout->setSpacing(0);
  250. meterLayout->addWidget(volMeter);
  251. meterLayout->addWidget(slider);
  252. volLayout->setContentsMargins(0, 0, 0, 0);
  253. volLayout->setSpacing(0);
  254. volLayout->addWidget(volLabel);
  255. mainLayout->addItem(nameLayout);
  256. mainLayout->addItem(volLayout);
  257. mainLayout->addItem(meterLayout);
  258. mainLayout->addItem(controlLayout);
  259. volMeter->setFocusProxy(slider);
  260. // Default size can cause clipping of long names in vertical layout.
  261. QFont font = nameLabel->font();
  262. QFontInfo info(font);
  263. font.setPointSizeF(0.8 * info.pointSizeF());
  264. nameLabel->setFont(font);
  265. setMaximumWidth(110);
  266. } else {
  267. QHBoxLayout *textLayout = new QHBoxLayout;
  268. QHBoxLayout *botLayout = new QHBoxLayout;
  269. volMeter = new VolumeMeter(nullptr, obs_volmeter, false);
  270. slider = new VolumeSlider(obs_fader, Qt::Horizontal);
  271. slider->setLayoutDirection(Qt::LeftToRight);
  272. textLayout->setContentsMargins(0, 0, 0, 0);
  273. textLayout->addWidget(nameLabel);
  274. textLayout->addWidget(volLabel);
  275. textLayout->setAlignment(nameLabel, Qt::AlignLeft);
  276. textLayout->setAlignment(volLabel, Qt::AlignRight);
  277. botLayout->setContentsMargins(0, 0, 0, 0);
  278. botLayout->setSpacing(5);
  279. botLayout->addWidget(slider);
  280. botLayout->addWidget(mute);
  281. botLayout->setAlignment(slider, Qt::AlignVCenter);
  282. botLayout->setAlignment(mute, Qt::AlignVCenter);
  283. if (showConfig) {
  284. botLayout->addWidget(config);
  285. botLayout->setAlignment(config, Qt::AlignVCenter);
  286. }
  287. mainLayout->addItem(textLayout);
  288. mainLayout->addWidget(volMeter);
  289. mainLayout->addItem(botLayout);
  290. volMeter->setFocusProxy(slider);
  291. }
  292. setLayout(mainLayout);
  293. nameLabel->setText(sourceName);
  294. slider->setMinimum(0);
  295. slider->setMaximum(int(FADER_PRECISION));
  296. bool muted = obs_source_muted(source);
  297. bool unassigned = IsSourceUnassigned(source);
  298. mute->setCheckState(GetCheckState(muted, unassigned));
  299. volMeter->muted = muted || unassigned;
  300. mute->setAccessibleName(QTStr("VolControl.Mute").arg(sourceName));
  301. obs_fader_add_callback(obs_fader, OBSVolumeChanged, this);
  302. obs_volmeter_add_callback(obs_volmeter, OBSVolumeLevel, this);
  303. signal_handler_connect(obs_source_get_signal_handler(source), "mute",
  304. OBSVolumeMuted, this);
  305. signal_handler_connect(obs_source_get_signal_handler(source),
  306. "audio_mixers", OBSMixersOrMonitoringChanged,
  307. this);
  308. signal_handler_connect(obs_source_get_signal_handler(source),
  309. "audio_monitoring", OBSMixersOrMonitoringChanged,
  310. this);
  311. QWidget::connect(slider, &VolumeSlider::valueChanged, this,
  312. &VolControl::SliderChanged);
  313. QWidget::connect(mute, &MuteCheckBox::clicked, this,
  314. &VolControl::SetMuted);
  315. obs_fader_attach_source(obs_fader, source);
  316. obs_volmeter_attach_source(obs_volmeter, source);
  317. QString styleName = slider->style()->objectName();
  318. QStyle *style;
  319. style = QStyleFactory::create(styleName);
  320. if (!style) {
  321. style = new SliderAbsoluteSetStyle();
  322. } else {
  323. style = new SliderAbsoluteSetStyle(style);
  324. }
  325. style->setParent(slider);
  326. slider->setStyle(style);
  327. /* Call volume changed once to init the slider position and label */
  328. VolumeChanged();
  329. }
  330. void VolControl::EnableSlider(bool enable)
  331. {
  332. slider->setEnabled(enable);
  333. }
  334. VolControl::~VolControl()
  335. {
  336. obs_fader_remove_callback(obs_fader, OBSVolumeChanged, this);
  337. obs_volmeter_remove_callback(obs_volmeter, OBSVolumeLevel, this);
  338. signal_handler_disconnect(obs_source_get_signal_handler(source), "mute",
  339. OBSVolumeMuted, this);
  340. signal_handler_disconnect(obs_source_get_signal_handler(source),
  341. "audio_mixers", OBSMixersOrMonitoringChanged,
  342. this);
  343. signal_handler_disconnect(obs_source_get_signal_handler(source),
  344. "audio_monitoring",
  345. OBSMixersOrMonitoringChanged, this);
  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),
  674. obs_volmeter(obs_volmeter),
  675. vertical(vertical)
  676. {
  677. setAttribute(Qt::WA_OpaquePaintEvent, true);
  678. // Default meter settings, they only show if
  679. // there is no stylesheet, do not remove.
  680. backgroundNominalColor.setRgb(0x26, 0x7f, 0x26); // Dark green
  681. backgroundWarningColor.setRgb(0x7f, 0x7f, 0x26); // Dark yellow
  682. backgroundErrorColor.setRgb(0x7f, 0x26, 0x26); // Dark red
  683. foregroundNominalColor.setRgb(0x4c, 0xff, 0x4c); // Bright green
  684. foregroundWarningColor.setRgb(0xff, 0xff, 0x4c); // Bright yellow
  685. foregroundErrorColor.setRgb(0xff, 0x4c, 0x4c); // Bright red
  686. backgroundNominalColorDisabled.setRgb(90, 90, 90);
  687. backgroundWarningColorDisabled.setRgb(117, 117, 117);
  688. backgroundErrorColorDisabled.setRgb(65, 65, 65);
  689. foregroundNominalColorDisabled.setRgb(163, 163, 163);
  690. foregroundWarningColorDisabled.setRgb(217, 217, 217);
  691. foregroundErrorColorDisabled.setRgb(113, 113, 113);
  692. clipColor.setRgb(0xff, 0xff, 0xff); // Bright white
  693. magnitudeColor.setRgb(0x00, 0x00, 0x00); // Black
  694. majorTickColor.setRgb(0xff, 0xff, 0xff); // Black
  695. minorTickColor.setRgb(0xcc, 0xcc, 0xcc); // Black
  696. minimumLevel = -60.0; // -60 dB
  697. warningLevel = -20.0; // -20 dB
  698. errorLevel = -9.0; // -9 dB
  699. clipLevel = -0.5; // -0.5 dB
  700. minimumInputLevel = -50.0; // -50 dB
  701. peakDecayRate = 11.76; // 20 dB / 1.7 sec
  702. magnitudeIntegrationTime = 0.3; // 99% in 300 ms
  703. peakHoldDuration = 20.0; // 20 seconds
  704. inputPeakHoldDuration = 1.0; // 1 second
  705. meterThickness = 3; // Bar thickness in pixels
  706. meterFontScaling =
  707. 0.7; // Font size for numbers is 70% of Widget's font size
  708. channels = (int)audio_output_get_channels(obs_get_audio());
  709. doLayout();
  710. updateTimerRef = updateTimer.toStrongRef();
  711. if (!updateTimerRef) {
  712. updateTimerRef = QSharedPointer<VolumeMeterTimer>::create();
  713. updateTimerRef->setTimerType(Qt::PreciseTimer);
  714. updateTimerRef->start(16);
  715. updateTimer = updateTimerRef;
  716. }
  717. updateTimerRef->AddVolControl(this);
  718. }
  719. VolumeMeter::~VolumeMeter()
  720. {
  721. updateTimerRef->RemoveVolControl(this);
  722. }
  723. void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS],
  724. const float peak[MAX_AUDIO_CHANNELS],
  725. const float inputPeak[MAX_AUDIO_CHANNELS])
  726. {
  727. uint64_t ts = os_gettime_ns();
  728. QMutexLocker locker(&dataMutex);
  729. currentLastUpdateTime = ts;
  730. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  731. currentMagnitude[channelNr] = magnitude[channelNr];
  732. currentPeak[channelNr] = peak[channelNr];
  733. currentInputPeak[channelNr] = inputPeak[channelNr];
  734. }
  735. // In case there are more updates then redraws we must make sure
  736. // that the ballistics of peak and hold are recalculated.
  737. locker.unlock();
  738. calculateBallistics(ts);
  739. }
  740. inline void VolumeMeter::resetLevels()
  741. {
  742. currentLastUpdateTime = 0;
  743. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) {
  744. currentMagnitude[channelNr] = -M_INFINITE;
  745. currentPeak[channelNr] = -M_INFINITE;
  746. currentInputPeak[channelNr] = -M_INFINITE;
  747. displayMagnitude[channelNr] = -M_INFINITE;
  748. displayPeak[channelNr] = -M_INFINITE;
  749. displayPeakHold[channelNr] = -M_INFINITE;
  750. displayPeakHoldLastUpdateTime[channelNr] = 0;
  751. displayInputPeakHold[channelNr] = -M_INFINITE;
  752. displayInputPeakHoldLastUpdateTime[channelNr] = 0;
  753. }
  754. }
  755. bool VolumeMeter::needLayoutChange()
  756. {
  757. int currentNrAudioChannels = obs_volmeter_get_nr_channels(obs_volmeter);
  758. if (!currentNrAudioChannels) {
  759. struct obs_audio_info oai;
  760. obs_get_audio_info(&oai);
  761. currentNrAudioChannels = (oai.speakers == SPEAKERS_MONO) ? 1
  762. : 2;
  763. }
  764. if (displayNrAudioChannels != currentNrAudioChannels) {
  765. displayNrAudioChannels = currentNrAudioChannels;
  766. recalculateLayout = true;
  767. }
  768. return recalculateLayout;
  769. }
  770. // When this is called from the constructor, obs_volmeter_get_nr_channels has not
  771. // yet been called and Q_PROPERTY settings have not yet been read from the
  772. // stylesheet.
  773. inline void VolumeMeter::doLayout()
  774. {
  775. QMutexLocker locker(&dataMutex);
  776. recalculateLayout = false;
  777. tickFont = font();
  778. QFontInfo info(tickFont);
  779. tickFont.setPointSizeF(info.pointSizeF() * meterFontScaling);
  780. QFontMetrics metrics(tickFont);
  781. if (vertical) {
  782. // Each meter channel is meterThickness pixels wide, plus one pixel
  783. // between channels, but not after the last.
  784. // Add 4 pixels for ticks, space to hold our longest label in this font,
  785. // and a few pixels before the fader.
  786. QRect scaleBounds = metrics.boundingRect("-88");
  787. setMinimumSize(displayNrAudioChannels * (meterThickness + 1) -
  788. 1 + 4 + scaleBounds.width() + 2,
  789. 130);
  790. } else {
  791. // Each meter channel is meterThickness pixels high, plus one pixel
  792. // between channels, but not after the last.
  793. // Add 4 pixels for ticks, and space high enough to hold our label in
  794. // this font, presuming that digits don't have descenders.
  795. setMinimumSize(130,
  796. displayNrAudioChannels * (meterThickness + 1) -
  797. 1 + 4 + metrics.capHeight());
  798. }
  799. resetLevels();
  800. }
  801. inline bool VolumeMeter::detectIdle(uint64_t ts)
  802. {
  803. double timeSinceLastUpdate = (ts - currentLastUpdateTime) * 0.000000001;
  804. if (timeSinceLastUpdate > 0.5) {
  805. resetLevels();
  806. return true;
  807. } else {
  808. return false;
  809. }
  810. }
  811. inline void
  812. VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts,
  813. qreal timeSinceLastRedraw)
  814. {
  815. if (currentPeak[channelNr] >= displayPeak[channelNr] ||
  816. isnan(displayPeak[channelNr])) {
  817. // Attack of peak is immediate.
  818. displayPeak[channelNr] = currentPeak[channelNr];
  819. } else {
  820. // Decay of peak is 40 dB / 1.7 seconds for Fast Profile
  821. // 20 dB / 1.7 seconds for Medium Profile (Type I PPM)
  822. // 24 dB / 2.8 seconds for Slow Profile (Type II PPM)
  823. float decay = float(peakDecayRate * timeSinceLastRedraw);
  824. displayPeak[channelNr] = CLAMP(displayPeak[channelNr] - decay,
  825. currentPeak[channelNr], 0);
  826. }
  827. if (currentPeak[channelNr] >= displayPeakHold[channelNr] ||
  828. !isfinite(displayPeakHold[channelNr])) {
  829. // Attack of peak-hold is immediate, but keep track
  830. // when it was last updated.
  831. displayPeakHold[channelNr] = currentPeak[channelNr];
  832. displayPeakHoldLastUpdateTime[channelNr] = ts;
  833. } else {
  834. // The peak and hold falls back to peak
  835. // after 20 seconds.
  836. qreal timeSinceLastPeak =
  837. (uint64_t)(ts -
  838. displayPeakHoldLastUpdateTime[channelNr]) *
  839. 0.000000001;
  840. if (timeSinceLastPeak > peakHoldDuration) {
  841. displayPeakHold[channelNr] = currentPeak[channelNr];
  842. displayPeakHoldLastUpdateTime[channelNr] = ts;
  843. }
  844. }
  845. if (currentInputPeak[channelNr] >= displayInputPeakHold[channelNr] ||
  846. !isfinite(displayInputPeakHold[channelNr])) {
  847. // Attack of peak-hold is immediate, but keep track
  848. // when it was last updated.
  849. displayInputPeakHold[channelNr] = currentInputPeak[channelNr];
  850. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  851. } else {
  852. // The peak and hold falls back to peak after 1 second.
  853. qreal timeSinceLastPeak =
  854. (uint64_t)(ts -
  855. displayInputPeakHoldLastUpdateTime[channelNr]) *
  856. 0.000000001;
  857. if (timeSinceLastPeak > inputPeakHoldDuration) {
  858. displayInputPeakHold[channelNr] =
  859. currentInputPeak[channelNr];
  860. displayInputPeakHoldLastUpdateTime[channelNr] = ts;
  861. }
  862. }
  863. if (!isfinite(displayMagnitude[channelNr])) {
  864. // The statements in the else-leg do not work with
  865. // NaN and infinite displayMagnitude.
  866. displayMagnitude[channelNr] = currentMagnitude[channelNr];
  867. } else {
  868. // A VU meter will integrate to the new value to 99% in 300 ms.
  869. // The calculation here is very simplified and is more accurate
  870. // with higher frame-rate.
  871. float attack =
  872. float((currentMagnitude[channelNr] -
  873. displayMagnitude[channelNr]) *
  874. (timeSinceLastRedraw / magnitudeIntegrationTime) *
  875. 0.99);
  876. displayMagnitude[channelNr] =
  877. CLAMP(displayMagnitude[channelNr] + attack,
  878. (float)minimumLevel, 0);
  879. }
  880. }
  881. inline void VolumeMeter::calculateBallistics(uint64_t ts,
  882. qreal timeSinceLastRedraw)
  883. {
  884. QMutexLocker locker(&dataMutex);
  885. for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++)
  886. calculateBallisticsForChannel(channelNr, ts,
  887. timeSinceLastRedraw);
  888. }
  889. void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width,
  890. int height, float peakHold)
  891. {
  892. QMutexLocker locker(&dataMutex);
  893. QColor color;
  894. if (peakHold < minimumInputLevel)
  895. color = backgroundNominalColor;
  896. else if (peakHold < warningLevel)
  897. color = foregroundNominalColor;
  898. else if (peakHold < errorLevel)
  899. color = foregroundWarningColor;
  900. else if (peakHold <= clipLevel)
  901. color = foregroundErrorColor;
  902. else
  903. color = clipColor;
  904. painter.fillRect(x, y, width, height, color);
  905. }
  906. void VolumeMeter::paintHTicks(QPainter &painter, int x, int y, int width)
  907. {
  908. qreal scale = width / minimumLevel;
  909. painter.setFont(tickFont);
  910. QFontMetrics metrics(tickFont);
  911. painter.setPen(majorTickColor);
  912. // Draw major tick lines and numeric indicators.
  913. for (int i = 0; i >= minimumLevel; i -= 5) {
  914. int position = int(x + width - (i * scale) - 1);
  915. QString str = QString::number(i);
  916. // Center the number on the tick, but don't overflow
  917. QRect textBounds = metrics.boundingRect(str);
  918. int pos;
  919. if (i == 0) {
  920. pos = position - textBounds.width();
  921. } else {
  922. pos = position - (textBounds.width() / 2);
  923. if (pos < 0)
  924. pos = 0;
  925. }
  926. painter.drawText(pos, y + 4 + metrics.capHeight(), str);
  927. painter.drawLine(position, y, position, y + 2);
  928. }
  929. // Draw minor tick lines.
  930. painter.setPen(minorTickColor);
  931. for (int i = 0; i >= minimumLevel; i--) {
  932. int position = int(x + width - (i * scale) - 1);
  933. if (i % 5 != 0)
  934. painter.drawLine(position, y, position, y + 1);
  935. }
  936. }
  937. void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height)
  938. {
  939. qreal scale = height / minimumLevel;
  940. painter.setFont(tickFont);
  941. QFontMetrics metrics(tickFont);
  942. painter.setPen(majorTickColor);
  943. // Draw major tick lines and numeric indicators.
  944. for (int i = 0; i >= minimumLevel; i -= 5) {
  945. int position = y + int(i * scale) + METER_PADDING;
  946. QString str = QString::number(i);
  947. // Center the number on the tick, but don't overflow
  948. if (i == 0) {
  949. painter.drawText(x + 6, position + metrics.capHeight(),
  950. str);
  951. } else {
  952. painter.drawText(x + 4,
  953. position + (metrics.capHeight() / 2),
  954. str);
  955. }
  956. painter.drawLine(x, position, x + 2, position);
  957. }
  958. // Draw minor tick lines.
  959. painter.setPen(minorTickColor);
  960. for (int i = 0; i >= minimumLevel; i--) {
  961. int position = y + int(i * scale) + METER_PADDING;
  962. if (i % 5 != 0)
  963. painter.drawLine(x, position, x + 1, position);
  964. }
  965. }
  966. #define CLIP_FLASH_DURATION_MS 1000
  967. inline int VolumeMeter::convertToInt(float number)
  968. {
  969. constexpr int min = std::numeric_limits<int>::min();
  970. constexpr int max = std::numeric_limits<int>::max();
  971. // NOTE: Conversion from 'const int' to 'float' changes max value from 2147483647 to 2147483648
  972. if (number >= (float)max)
  973. return max;
  974. else if (number < min)
  975. return min;
  976. else
  977. return int(number);
  978. }
  979. void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width,
  980. int height, float magnitude, float peak,
  981. float peakHold)
  982. {
  983. qreal scale = width / minimumLevel;
  984. QMutexLocker locker(&dataMutex);
  985. int minimumPosition = x + 0;
  986. int maximumPosition = x + width;
  987. int magnitudePosition = x + width - convertToInt(magnitude * scale);
  988. int peakPosition = x + width - convertToInt(peak * scale);
  989. int peakHoldPosition = x + width - convertToInt(peakHold * scale);
  990. int warningPosition = x + width - convertToInt(warningLevel * scale);
  991. int errorPosition = x + width - convertToInt(errorLevel * scale);
  992. int nominalLength = warningPosition - minimumPosition;
  993. int warningLength = errorPosition - warningPosition;
  994. int errorLength = maximumPosition - errorPosition;
  995. locker.unlock();
  996. if (clipping) {
  997. peakPosition = maximumPosition;
  998. }
  999. if (peakPosition < minimumPosition) {
  1000. painter.fillRect(minimumPosition, y, nominalLength, height,
  1001. muted ? backgroundNominalColorDisabled
  1002. : backgroundNominalColor);
  1003. painter.fillRect(warningPosition, y, warningLength, height,
  1004. muted ? backgroundWarningColorDisabled
  1005. : backgroundWarningColor);
  1006. painter.fillRect(errorPosition, y, errorLength, height,
  1007. muted ? backgroundErrorColorDisabled
  1008. : backgroundErrorColor);
  1009. } else if (peakPosition < warningPosition) {
  1010. painter.fillRect(minimumPosition, y,
  1011. peakPosition - minimumPosition, height,
  1012. muted ? foregroundNominalColorDisabled
  1013. : foregroundNominalColor);
  1014. painter.fillRect(peakPosition, y,
  1015. warningPosition - peakPosition, height,
  1016. muted ? backgroundNominalColorDisabled
  1017. : backgroundNominalColor);
  1018. painter.fillRect(warningPosition, y, warningLength, height,
  1019. muted ? backgroundWarningColorDisabled
  1020. : backgroundWarningColor);
  1021. painter.fillRect(errorPosition, y, errorLength, height,
  1022. muted ? backgroundErrorColorDisabled
  1023. : backgroundErrorColor);
  1024. } else if (peakPosition < errorPosition) {
  1025. painter.fillRect(minimumPosition, y, nominalLength, height,
  1026. muted ? foregroundNominalColorDisabled
  1027. : foregroundNominalColor);
  1028. painter.fillRect(warningPosition, y,
  1029. peakPosition - warningPosition, height,
  1030. muted ? foregroundWarningColorDisabled
  1031. : foregroundWarningColor);
  1032. painter.fillRect(peakPosition, y, errorPosition - peakPosition,
  1033. height,
  1034. muted ? backgroundWarningColorDisabled
  1035. : backgroundWarningColor);
  1036. painter.fillRect(errorPosition, y, errorLength, height,
  1037. muted ? backgroundErrorColorDisabled
  1038. : backgroundErrorColor);
  1039. } else if (peakPosition < maximumPosition) {
  1040. painter.fillRect(minimumPosition, y, nominalLength, height,
  1041. muted ? foregroundNominalColorDisabled
  1042. : foregroundNominalColor);
  1043. painter.fillRect(warningPosition, y, warningLength, height,
  1044. muted ? foregroundWarningColorDisabled
  1045. : foregroundWarningColor);
  1046. painter.fillRect(errorPosition, y, peakPosition - errorPosition,
  1047. height,
  1048. muted ? foregroundErrorColorDisabled
  1049. : foregroundErrorColor);
  1050. painter.fillRect(peakPosition, y,
  1051. maximumPosition - peakPosition, height,
  1052. muted ? backgroundErrorColorDisabled
  1053. : backgroundErrorColor);
  1054. } else if (int(magnitude) != 0) {
  1055. if (!clipping) {
  1056. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  1057. [&]() { clipping = false; });
  1058. clipping = true;
  1059. }
  1060. int end = errorLength + warningLength + nominalLength;
  1061. painter.fillRect(minimumPosition, y, end, height,
  1062. QBrush(muted ? foregroundErrorColorDisabled
  1063. : foregroundErrorColor));
  1064. }
  1065. if (peakHoldPosition - 3 < minimumPosition)
  1066. ; // Peak-hold below minimum, no drawing.
  1067. else if (peakHoldPosition < warningPosition)
  1068. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  1069. muted ? foregroundNominalColorDisabled
  1070. : foregroundNominalColor);
  1071. else if (peakHoldPosition < errorPosition)
  1072. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  1073. muted ? foregroundWarningColorDisabled
  1074. : foregroundWarningColor);
  1075. else
  1076. painter.fillRect(peakHoldPosition - 3, y, 3, height,
  1077. muted ? foregroundErrorColorDisabled
  1078. : foregroundErrorColor);
  1079. if (magnitudePosition - 3 >= minimumPosition)
  1080. painter.fillRect(magnitudePosition - 3, y, 3, height,
  1081. magnitudeColor);
  1082. }
  1083. void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width,
  1084. int height, float magnitude, float peak,
  1085. float peakHold)
  1086. {
  1087. qreal scale = height / minimumLevel;
  1088. QMutexLocker locker(&dataMutex);
  1089. int minimumPosition = y + 0;
  1090. int maximumPosition = y + height;
  1091. int magnitudePosition = y + height - convertToInt(magnitude * scale);
  1092. int peakPosition = y + height - convertToInt(peak * scale);
  1093. int peakHoldPosition = y + height - convertToInt(peakHold * scale);
  1094. int warningPosition = y + height - convertToInt(warningLevel * scale);
  1095. int errorPosition = y + height - convertToInt(errorLevel * scale);
  1096. int nominalLength = warningPosition - minimumPosition;
  1097. int warningLength = errorPosition - warningPosition;
  1098. int errorLength = maximumPosition - errorPosition;
  1099. locker.unlock();
  1100. if (clipping) {
  1101. peakPosition = maximumPosition;
  1102. }
  1103. if (peakPosition < minimumPosition) {
  1104. painter.fillRect(x, minimumPosition, width, nominalLength,
  1105. muted ? backgroundNominalColorDisabled
  1106. : backgroundNominalColor);
  1107. painter.fillRect(x, warningPosition, width, warningLength,
  1108. muted ? backgroundWarningColorDisabled
  1109. : backgroundWarningColor);
  1110. painter.fillRect(x, errorPosition, width, errorLength,
  1111. muted ? backgroundErrorColorDisabled
  1112. : backgroundErrorColor);
  1113. } else if (peakPosition < warningPosition) {
  1114. painter.fillRect(x, minimumPosition, width,
  1115. peakPosition - minimumPosition,
  1116. muted ? foregroundNominalColorDisabled
  1117. : foregroundNominalColor);
  1118. painter.fillRect(x, peakPosition, width,
  1119. warningPosition - peakPosition,
  1120. muted ? backgroundNominalColorDisabled
  1121. : backgroundNominalColor);
  1122. painter.fillRect(x, warningPosition, width, warningLength,
  1123. muted ? backgroundWarningColorDisabled
  1124. : backgroundWarningColor);
  1125. painter.fillRect(x, errorPosition, width, errorLength,
  1126. muted ? backgroundErrorColorDisabled
  1127. : backgroundErrorColor);
  1128. } else if (peakPosition < errorPosition) {
  1129. painter.fillRect(x, minimumPosition, width, nominalLength,
  1130. muted ? foregroundNominalColorDisabled
  1131. : foregroundNominalColor);
  1132. painter.fillRect(x, warningPosition, width,
  1133. peakPosition - warningPosition,
  1134. muted ? foregroundWarningColorDisabled
  1135. : foregroundWarningColor);
  1136. painter.fillRect(x, peakPosition, width,
  1137. errorPosition - peakPosition,
  1138. muted ? backgroundWarningColorDisabled
  1139. : backgroundWarningColor);
  1140. painter.fillRect(x, errorPosition, width, errorLength,
  1141. muted ? backgroundErrorColorDisabled
  1142. : backgroundErrorColor);
  1143. } else if (peakPosition < maximumPosition) {
  1144. painter.fillRect(x, minimumPosition, width, nominalLength,
  1145. muted ? foregroundNominalColorDisabled
  1146. : foregroundNominalColor);
  1147. painter.fillRect(x, warningPosition, width, warningLength,
  1148. muted ? foregroundWarningColorDisabled
  1149. : foregroundWarningColor);
  1150. painter.fillRect(x, errorPosition, width,
  1151. peakPosition - errorPosition,
  1152. muted ? foregroundErrorColorDisabled
  1153. : foregroundErrorColor);
  1154. painter.fillRect(x, peakPosition, width,
  1155. maximumPosition - peakPosition,
  1156. muted ? backgroundErrorColorDisabled
  1157. : backgroundErrorColor);
  1158. } else {
  1159. if (!clipping) {
  1160. QTimer::singleShot(CLIP_FLASH_DURATION_MS, this,
  1161. [&]() { clipping = false; });
  1162. clipping = true;
  1163. }
  1164. int end = errorLength + warningLength + nominalLength;
  1165. painter.fillRect(x, minimumPosition, width, end,
  1166. QBrush(muted ? foregroundErrorColorDisabled
  1167. : foregroundErrorColor));
  1168. }
  1169. if (peakHoldPosition - 3 < minimumPosition)
  1170. ; // Peak-hold below minimum, no drawing.
  1171. else if (peakHoldPosition < warningPosition)
  1172. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  1173. muted ? foregroundNominalColorDisabled
  1174. : foregroundNominalColor);
  1175. else if (peakHoldPosition < errorPosition)
  1176. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  1177. muted ? foregroundWarningColorDisabled
  1178. : foregroundWarningColor);
  1179. else
  1180. painter.fillRect(x, peakHoldPosition - 3, width, 3,
  1181. muted ? foregroundErrorColorDisabled
  1182. : foregroundErrorColor);
  1183. if (magnitudePosition - 3 >= minimumPosition)
  1184. painter.fillRect(x, magnitudePosition - 3, width, 3,
  1185. magnitudeColor);
  1186. }
  1187. void VolumeMeter::paintEvent(QPaintEvent *event)
  1188. {
  1189. uint64_t ts = os_gettime_ns();
  1190. qreal timeSinceLastRedraw = (ts - lastRedrawTime) * 0.000000001;
  1191. calculateBallistics(ts, timeSinceLastRedraw);
  1192. bool idle = detectIdle(ts);
  1193. QRect widgetRect = rect();
  1194. int width = widgetRect.width();
  1195. int height = widgetRect.height();
  1196. QPainter painter(this);
  1197. if (vertical)
  1198. height -= METER_PADDING * 2;
  1199. // timerEvent requests update of the bar(s) only, so we can avoid the
  1200. // overhead of repainting the scale and labels.
  1201. if (event->region().boundingRect() != getBarRect()) {
  1202. if (needLayoutChange())
  1203. doLayout();
  1204. // Paint window background color (as widget is opaque)
  1205. QColor background =
  1206. palette().color(QPalette::ColorRole::Window);
  1207. painter.fillRect(widgetRect, background);
  1208. if (vertical) {
  1209. paintVTicks(painter,
  1210. displayNrAudioChannels *
  1211. (meterThickness + 1) -
  1212. 1,
  1213. 0, height - (INDICATOR_THICKNESS + 3));
  1214. } else {
  1215. paintHTicks(painter, INDICATOR_THICKNESS + 3,
  1216. displayNrAudioChannels *
  1217. (meterThickness + 1) -
  1218. 1,
  1219. width - (INDICATOR_THICKNESS + 3));
  1220. }
  1221. }
  1222. if (vertical) {
  1223. // Invert the Y axis to ease the math
  1224. painter.translate(0, height + METER_PADDING);
  1225. painter.scale(1, -1);
  1226. }
  1227. for (int channelNr = 0; channelNr < displayNrAudioChannels;
  1228. channelNr++) {
  1229. int channelNrFixed =
  1230. (displayNrAudioChannels == 1 && channels > 2)
  1231. ? 2
  1232. : channelNr;
  1233. if (vertical)
  1234. paintVMeter(painter, channelNr * (meterThickness + 1),
  1235. INDICATOR_THICKNESS + 2, meterThickness,
  1236. height - (INDICATOR_THICKNESS + 2),
  1237. displayMagnitude[channelNrFixed],
  1238. displayPeak[channelNrFixed],
  1239. displayPeakHold[channelNrFixed]);
  1240. else
  1241. paintHMeter(painter, INDICATOR_THICKNESS + 2,
  1242. channelNr * (meterThickness + 1),
  1243. width - (INDICATOR_THICKNESS + 2),
  1244. meterThickness,
  1245. displayMagnitude[channelNrFixed],
  1246. displayPeak[channelNrFixed],
  1247. displayPeakHold[channelNrFixed]);
  1248. if (idle)
  1249. continue;
  1250. // By not drawing the input meter boxes the user can
  1251. // see that the audio stream has been stopped, without
  1252. // having too much visual impact.
  1253. if (vertical)
  1254. paintInputMeter(painter,
  1255. channelNr * (meterThickness + 1), 0,
  1256. meterThickness, INDICATOR_THICKNESS,
  1257. displayInputPeakHold[channelNrFixed]);
  1258. else
  1259. paintInputMeter(painter, 0,
  1260. channelNr * (meterThickness + 1),
  1261. INDICATOR_THICKNESS, meterThickness,
  1262. displayInputPeakHold[channelNrFixed]);
  1263. }
  1264. lastRedrawTime = ts;
  1265. }
  1266. QRect VolumeMeter::getBarRect() const
  1267. {
  1268. QRect rec = rect();
  1269. if (vertical)
  1270. rec.setWidth(displayNrAudioChannels * (meterThickness + 1) - 1);
  1271. else
  1272. rec.setHeight(displayNrAudioChannels * (meterThickness + 1) -
  1273. 1);
  1274. return rec;
  1275. }
  1276. void VolumeMeter::changeEvent(QEvent *e)
  1277. {
  1278. if (e->type() == QEvent::StyleChange)
  1279. recalculateLayout = true;
  1280. QWidget::changeEvent(e);
  1281. }
  1282. void VolumeMeterTimer::AddVolControl(VolumeMeter *meter)
  1283. {
  1284. volumeMeters.push_back(meter);
  1285. }
  1286. void VolumeMeterTimer::RemoveVolControl(VolumeMeter *meter)
  1287. {
  1288. volumeMeters.removeOne(meter);
  1289. }
  1290. void VolumeMeterTimer::timerEvent(QTimerEvent *)
  1291. {
  1292. for (VolumeMeter *meter : volumeMeters) {
  1293. if (meter->needLayoutChange()) {
  1294. // Tell paintEvent to update layout and paint everything
  1295. meter->update();
  1296. } else {
  1297. // Tell paintEvent to paint only the bars
  1298. meter->update(meter->getBarRect());
  1299. }
  1300. }
  1301. }