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