diff --git a/.clang-format b/.clang-format index 3abb4e62e..a10cf9586 100644 --- a/.clang-format +++ b/.clang-format @@ -44,7 +44,7 @@ BreakBeforeBraces: Custom BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeColon BreakStringLiterals: false # apparently unpredictable -ColumnLimit: 80 +ColumnLimit: 120 CompactNamespaces: false ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 8 diff --git a/UI/absolute-slider.cpp b/UI/absolute-slider.cpp index c3fad5d34..8aedba825 100644 --- a/UI/absolute-slider.cpp +++ b/UI/absolute-slider.cpp @@ -6,8 +6,7 @@ AbsoluteSlider::AbsoluteSlider(QWidget *parent) : SliderIgnoreScroll(parent) setMouseTracking(true); } -AbsoluteSlider::AbsoluteSlider(Qt::Orientation orientation, QWidget *parent) - : SliderIgnoreScroll(orientation, parent) +AbsoluteSlider::AbsoluteSlider(Qt::Orientation orientation, QWidget *parent) : SliderIgnoreScroll(orientation, parent) { installEventFilter(this); setMouseTracking(true); @@ -15,8 +14,7 @@ AbsoluteSlider::AbsoluteSlider(Qt::Orientation orientation, QWidget *parent) void AbsoluteSlider::mousePressEvent(QMouseEvent *event) { - dragging = (event->buttons() & Qt::LeftButton || - event->buttons() & Qt::MiddleButton); + dragging = (event->buttons() & Qt::LeftButton || event->buttons() & Qt::MiddleButton); if (dragging) { setSliderDown(true); @@ -59,8 +57,7 @@ bool AbsoluteSlider::eventFilter(QObject *obj, QEvent *event) if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Up || - keyEvent->key() == Qt::Key_Down) { + if (keyEvent->key() == Qt::Key_Up || keyEvent->key() == Qt::Key_Down) { return true; } } @@ -78,10 +75,8 @@ int AbsoluteSlider::posToRangeValue(QMouseEvent *event) int sliderMax; int handleLength; - const QRect groove = style()->subControlRect( - QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); - const QRect handle = style()->subControlRect( - QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); + const QRect groove = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); + const QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); if (orientation() == Qt::Horizontal) { pos = event->pos().x(); @@ -95,9 +90,8 @@ int AbsoluteSlider::posToRangeValue(QMouseEvent *event) sliderMax = groove.bottom() - (handleLength / 2) + 1; } - int sliderValue = style()->sliderValueFromPosition( - minimum(), maximum(), pos - sliderMin, sliderMax - sliderMin, - opt.upsideDown); + int sliderValue = style()->sliderValueFromPosition(minimum(), maximum(), pos - sliderMin, sliderMax - sliderMin, + opt.upsideDown); return sliderValue; } diff --git a/UI/adv-audio-control.cpp b/UI/adv-audio-control.cpp index a964eccdd..80c0a5c1c 100644 --- a/UI/adv-audio-control.cpp +++ b/UI/adv-audio-control.cpp @@ -16,11 +16,9 @@ #define MIN_DB -96.0 #define MAX_DB 26.0 -static inline void setMixer(obs_source_t *source, const int mixerIdx, - const bool checked); +static inline void setMixer(obs_source_t *source, const int mixerIdx, const bool checked); -OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) - : source(source_) +OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source(source_) { QHBoxLayout *hlayout; signal_handler_t *handler = obs_source_get_signal_handler(source); @@ -54,18 +52,14 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) sigs.emplace_back(handler, "activate", OBSSourceActivated, this); sigs.emplace_back(handler, "deactivate", OBSSourceDeactivated, this); sigs.emplace_back(handler, "audio_activate", OBSSourceActivated, this); - sigs.emplace_back(handler, "audio_deactivate", OBSSourceDeactivated, - this); + sigs.emplace_back(handler, "audio_deactivate", OBSSourceDeactivated, this); sigs.emplace_back(handler, "volume", OBSSourceVolumeChanged, this); sigs.emplace_back(handler, "audio_sync", OBSSourceSyncChanged, this); sigs.emplace_back(handler, "update_flags", OBSSourceFlagsChanged, this); if (obs_audio_monitoring_available()) - sigs.emplace_back(handler, "audio_monitoring", - OBSSourceMonitoringTypeChanged, this); - sigs.emplace_back(handler, "audio_mixers", OBSSourceMixersChanged, - this); - sigs.emplace_back(handler, "audio_balance", OBSSourceBalanceChanged, - this); + sigs.emplace_back(handler, "audio_monitoring", OBSSourceMonitoringTypeChanged, this); + sigs.emplace_back(handler, "audio_mixers", OBSSourceMixersChanged, this); + sigs.emplace_back(handler, "audio_balance", OBSSourceBalanceChanged, this); sigs.emplace_back(handler, "rename", OBSSourceRenamed, this); hlayout = new QHBoxLayout(); @@ -90,10 +84,8 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) SetSourceName(sourceName); nameLabel->setAlignment(Qt::AlignVCenter); - bool isActive = obs_source_active(source) && - obs_source_audio_active(source); - active->setText(isActive ? QTStr("Basic.Stats.Status.Active") - : QTStr("Basic.Stats.Status.Inactive")); + bool isActive = obs_source_active(source) && obs_source_audio_active(source); + active->setText(isActive ? QTStr("Basic.Stats.Status.Active") : QTStr("Basic.Stats.Status.Inactive")); if (isActive) setClasses(active, "text-danger"); active->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); @@ -104,8 +96,7 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) volume->setDecimals(1); volume->setSuffix(" dB"); volume->setValue(obs_mul_to_db(vol)); - volume->setAccessibleName( - QTStr("Basic.AdvAudio.VolumeSource").arg(sourceName)); + volume->setAccessibleName(QTStr("Basic.AdvAudio.VolumeSource").arg(sourceName)); if (volume->value() < MIN_DB) { volume->setSpecialValueText("-inf dB"); @@ -116,34 +107,29 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) percent->setMaximum(2000); percent->setSuffix("%"); percent->setValue((int)(obs_source_get_volume(source) * 100.0f)); - percent->setAccessibleName( - QTStr("Basic.AdvAudio.VolumeSource").arg(sourceName)); + percent->setAccessibleName(QTStr("Basic.AdvAudio.VolumeSource").arg(sourceName)); stackedWidget->setSizePolicy(QSizePolicy::Minimum, QSizePolicy::Fixed); stackedWidget->setFixedWidth(100); stackedWidget->addWidget(volume); stackedWidget->addWidget(percent); - VolumeType volType = (VolumeType)config_get_int( - App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType"); + VolumeType volType = (VolumeType)config_get_int(App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType"); SetVolumeWidget(volType); forceMono->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); forceMono->setChecked((flags & OBS_SOURCE_FLAG_FORCE_MONO) != 0); - forceMono->setAccessibleName( - QTStr("Basic.AdvAudio.MonoSource").arg(sourceName)); + forceMono->setAccessibleName(QTStr("Basic.AdvAudio.MonoSource").arg(sourceName)); balance->setOrientation(Qt::Horizontal); balance->setMinimum(0); balance->setMaximum(100); balance->setTickPosition(QSlider::TicksAbove); balance->setTickInterval(50); - balance->setAccessibleName( - QTStr("Basic.AdvAudio.BalanceSource").arg(sourceName)); + balance->setAccessibleName(QTStr("Basic.AdvAudio.BalanceSource").arg(sourceName)); - const char *speakers = - config_get_string(main->Config(), "Audio", "ChannelSetup"); + const char *speakers = config_get_string(main->Config(), "Audio", "ChannelSetup"); if (strcmp(speakers, "Mono") == 0) balance->setEnabled(false); @@ -159,53 +145,40 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) syncOffset->setSuffix(" ms"); syncOffset->setValue(int(cur_sync / NSEC_PER_MSEC)); syncOffset->setFixedWidth(100); - syncOffset->setAccessibleName( - QTStr("Basic.AdvAudio.SyncOffsetSource").arg(sourceName)); + syncOffset->setAccessibleName(QTStr("Basic.AdvAudio.SyncOffsetSource").arg(sourceName)); int idx; if (obs_audio_monitoring_available()) { - monitoringType->addItem(QTStr("Basic.AdvAudio.Monitoring.None"), - (int)OBS_MONITORING_TYPE_NONE); - monitoringType->addItem( - QTStr("Basic.AdvAudio.Monitoring.MonitorOnly"), - (int)OBS_MONITORING_TYPE_MONITOR_ONLY); - monitoringType->addItem( - QTStr("Basic.AdvAudio.Monitoring.Both"), - (int)OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT); + monitoringType->addItem(QTStr("Basic.AdvAudio.Monitoring.None"), (int)OBS_MONITORING_TYPE_NONE); + monitoringType->addItem(QTStr("Basic.AdvAudio.Monitoring.MonitorOnly"), + (int)OBS_MONITORING_TYPE_MONITOR_ONLY); + monitoringType->addItem(QTStr("Basic.AdvAudio.Monitoring.Both"), + (int)OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT); int mt = (int)obs_source_get_monitoring_type(source); idx = monitoringType->findData(mt); monitoringType->setCurrentIndex(idx); - monitoringType->setAccessibleName( - QTStr("Basic.AdvAudio.MonitoringSource") - .arg(sourceName)); - monitoringType->setSizePolicy(QSizePolicy::Maximum, - QSizePolicy::Fixed); + monitoringType->setAccessibleName(QTStr("Basic.AdvAudio.MonitoringSource").arg(sourceName)); + monitoringType->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); } mixer1->setText("1"); mixer1->setChecked(mixers & (1 << 0)); - mixer1->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track1")); + mixer1->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track1")); mixer2->setText("2"); mixer2->setChecked(mixers & (1 << 1)); - mixer2->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track2")); + mixer2->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track2")); mixer3->setText("3"); mixer3->setChecked(mixers & (1 << 2)); - mixer3->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track3")); + mixer3->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track3")); mixer4->setText("4"); mixer4->setChecked(mixers & (1 << 3)); - mixer4->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track4")); + mixer4->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track4")); mixer5->setText("5"); mixer5->setChecked(mixers & (1 << 4)); - mixer5->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track5")); + mixer5->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track5")); mixer6->setText("6"); mixer6->setChecked(mixers & (1 << 5)); - mixer6->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track6")); + mixer6->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track6")); balanceContainer->layout()->addWidget(labelL); balanceContainer->layout()->addWidget(balance); @@ -224,26 +197,17 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) mixerContainer->layout()->addWidget(mixer6); mixerContainer->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); - connect(volume, &QDoubleSpinBox::valueChanged, this, - &OBSAdvAudioCtrl::volumeChanged); - connect(percent, &QSpinBox::valueChanged, this, - &OBSAdvAudioCtrl::percentChanged); - connect(forceMono, &QCheckBox::clicked, this, - &OBSAdvAudioCtrl::downmixMonoChanged); - connect(balance, &BalanceSlider::valueChanged, this, - &OBSAdvAudioCtrl::balanceChanged); - connect(balance, &BalanceSlider::doubleClicked, this, - &OBSAdvAudioCtrl::ResetBalance); - connect(syncOffset, &QSpinBox::valueChanged, this, - &OBSAdvAudioCtrl::syncOffsetChanged); + connect(volume, &QDoubleSpinBox::valueChanged, this, &OBSAdvAudioCtrl::volumeChanged); + connect(percent, &QSpinBox::valueChanged, this, &OBSAdvAudioCtrl::percentChanged); + connect(forceMono, &QCheckBox::clicked, this, &OBSAdvAudioCtrl::downmixMonoChanged); + connect(balance, &BalanceSlider::valueChanged, this, &OBSAdvAudioCtrl::balanceChanged); + connect(balance, &BalanceSlider::doubleClicked, this, &OBSAdvAudioCtrl::ResetBalance); + connect(syncOffset, &QSpinBox::valueChanged, this, &OBSAdvAudioCtrl::syncOffsetChanged); if (obs_audio_monitoring_available()) - connect(monitoringType, &QComboBox::currentIndexChanged, this, - &OBSAdvAudioCtrl::monitoringTypeChanged); + connect(monitoringType, &QComboBox::currentIndexChanged, this, &OBSAdvAudioCtrl::monitoringTypeChanged); auto connectMixer = [this](QCheckBox *mixer, int num) { - connect(mixer, &QCheckBox::clicked, [this, num](bool checked) { - setMixer(source, num, checked); - }); + connect(mixer, &QCheckBox::clicked, [this, num](bool checked) { setMixer(source, num, checked); }); }; connectMixer(mixer1, 0); connectMixer(mixer2, 1); @@ -293,67 +257,62 @@ void OBSAdvAudioCtrl::ShowAudioControl(QGridLayout *layout) void OBSAdvAudioCtrl::OBSSourceActivated(void *param, calldata_t *) { - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceActiveChanged", Q_ARG(bool, true)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceActiveChanged", Q_ARG(bool, true)); } void OBSAdvAudioCtrl::OBSSourceDeactivated(void *param, calldata_t *) { - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceActiveChanged", Q_ARG(bool, false)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceActiveChanged", + Q_ARG(bool, false)); } void OBSAdvAudioCtrl::OBSSourceFlagsChanged(void *param, calldata_t *calldata) { uint32_t flags = (uint32_t)calldata_int(calldata, "flags"); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceFlagsChanged", Q_ARG(uint32_t, flags)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceFlagsChanged", + Q_ARG(uint32_t, flags)); } void OBSAdvAudioCtrl::OBSSourceVolumeChanged(void *param, calldata_t *calldata) { float volume = (float)calldata_float(calldata, "volume"); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceVolumeChanged", Q_ARG(float, volume)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceVolumeChanged", + Q_ARG(float, volume)); } void OBSAdvAudioCtrl::OBSSourceSyncChanged(void *param, calldata_t *calldata) { int64_t offset = calldata_int(calldata, "offset"); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceSyncChanged", Q_ARG(int64_t, offset)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceSyncChanged", + Q_ARG(int64_t, offset)); } -void OBSAdvAudioCtrl::OBSSourceMonitoringTypeChanged(void *param, - calldata_t *calldata) +void OBSAdvAudioCtrl::OBSSourceMonitoringTypeChanged(void *param, calldata_t *calldata) { int type = calldata_int(calldata, "type"); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceMonitoringTypeChanged", + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceMonitoringTypeChanged", Q_ARG(int, type)); } void OBSAdvAudioCtrl::OBSSourceMixersChanged(void *param, calldata_t *calldata) { uint32_t mixers = (uint32_t)calldata_int(calldata, "mixers"); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceMixersChanged", + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceMixersChanged", Q_ARG(uint32_t, mixers)); } void OBSAdvAudioCtrl::OBSSourceBalanceChanged(void *param, calldata_t *calldata) { int balance = (float)calldata_float(calldata, "balance") * 100.0f; - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceBalanceChanged", Q_ARG(int, balance)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceBalanceChanged", + Q_ARG(int, balance)); } void OBSAdvAudioCtrl::OBSSourceRenamed(void *param, calldata_t *calldata) { QString newName = QT_UTF8(calldata_string(calldata, "new_name")); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SetSourceName", Q_ARG(QString, newName)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SetSourceName", Q_ARG(QString, newName)); } /* ------------------------------------------------------------------------- */ @@ -441,19 +400,16 @@ void OBSAdvAudioCtrl::volumeChanged(double db) obs_source_set_volume(source, val); auto undo_redo = [](const std::string &uuid, float val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_volume(source, val); }; const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); OBSBasic *main = OBSBasic::Get(); - main->undo_s.add_action( - QTStr("Undo.Volume.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, - true); + main->undo_s.add_action(QTStr("Undo.Volume.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, true); } void OBSAdvAudioCtrl::percentChanged(int percent) @@ -464,18 +420,15 @@ void OBSAdvAudioCtrl::percentChanged(int percent) obs_source_set_volume(source, val); auto undo_redo = [](const std::string &uuid, float val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_volume(source, val); }; const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - QTStr("Undo.Volume.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, - true); + OBSBasic::Get()->undo_s.add_action(QTStr("Undo.Volume.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, true); } static inline void set_mono(obs_source_t *source, bool mono) @@ -504,8 +457,7 @@ void OBSAdvAudioCtrl::downmixMonoChanged(bool val) obs_source_set_flags(source, flags); auto undo_redo = [](const std::string &uuid, bool val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); set_mono(source, val); }; @@ -513,10 +465,8 @@ void OBSAdvAudioCtrl::downmixMonoChanged(bool val) const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - text.arg(name), - std::bind(undo_redo, std::placeholders::_1, !val), - std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid); + OBSBasic::Get()->undo_s.add_action(text.arg(name), std::bind(undo_redo, std::placeholders::_1, !val), + std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid); } void OBSAdvAudioCtrl::balanceChanged(int val) @@ -534,18 +484,15 @@ void OBSAdvAudioCtrl::balanceChanged(int val) obs_source_set_balance_value(source, bal); auto undo_redo = [](const std::string &uuid, float val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_balance_value(source, val); }; const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - QTStr("Undo.Balance.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, bal), uuid, uuid, - true); + OBSBasic::Get()->undo_s.add_action(QTStr("Undo.Balance.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, bal), uuid, uuid, true); } void OBSAdvAudioCtrl::ResetBalance() @@ -564,26 +511,22 @@ void OBSAdvAudioCtrl::syncOffsetChanged(int milliseconds) obs_source_set_sync_offset(source, val); auto undo_redo = [](const std::string &uuid, int64_t val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_sync_offset(source, val); }; const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - QTStr("Undo.SyncOffset.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, - true); + OBSBasic::Get()->undo_s.add_action(QTStr("Undo.SyncOffset.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, true); } void OBSAdvAudioCtrl::monitoringTypeChanged(int index) { obs_monitoring_type prev = obs_source_get_monitoring_type(source); - obs_monitoring_type mt = - (obs_monitoring_type)monitoringType->itemData(index).toInt(); + obs_monitoring_type mt = (obs_monitoring_type)monitoringType->itemData(index).toInt(); obs_source_set_monitoring_type(source, mt); const char *type = nullptr; @@ -601,24 +544,20 @@ void OBSAdvAudioCtrl::monitoringTypeChanged(int index) } const char *name = obs_source_get_name(source); - blog(LOG_INFO, "User changed audio monitoring for source '%s' to: %s", - name ? name : "(null)", type); + blog(LOG_INFO, "User changed audio monitoring for source '%s' to: %s", name ? name : "(null)", type); auto undo_redo = [](const std::string &uuid, obs_monitoring_type val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_monitoring_type(source, val); }; const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - QTStr("Undo.MonitoringType.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, mt), uuid, uuid); + OBSBasic::Get()->undo_s.add_action(QTStr("Undo.MonitoringType.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, mt), uuid, uuid); } -static inline void setMixer(obs_source_t *source, const int mixerIdx, - const bool checked) +static inline void setMixer(obs_source_t *source, const int mixerIdx, const bool checked) { uint32_t mixers = obs_source_get_audio_mixers(source); uint32_t new_mixers = mixers; @@ -631,18 +570,15 @@ static inline void setMixer(obs_source_t *source, const int mixerIdx, obs_source_set_audio_mixers(source, new_mixers); auto undo_redo = [](const std::string &uuid, uint32_t mixers) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_audio_mixers(source, mixers); }; const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - QTStr("Undo.Mixers.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, mixers), - std::bind(undo_redo, std::placeholders::_1, new_mixers), uuid, - uuid); + OBSBasic::Get()->undo_s.add_action(QTStr("Undo.Mixers.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, mixers), + std::bind(undo_redo, std::placeholders::_1, new_mixers), uuid, uuid); } void OBSAdvAudioCtrl::SetVolumeWidget(VolumeType type) diff --git a/UI/adv-audio-control.hpp b/UI/adv-audio-control.hpp index 1d13e7c66..143b66222 100644 --- a/UI/adv-audio-control.hpp +++ b/UI/adv-audio-control.hpp @@ -53,8 +53,7 @@ private: static void OBSSourceFlagsChanged(void *param, calldata_t *calldata); static void OBSSourceVolumeChanged(void *param, calldata_t *calldata); static void OBSSourceSyncChanged(void *param, calldata_t *calldata); - static void OBSSourceMonitoringTypeChanged(void *param, - calldata_t *calldata); + static void OBSSourceMonitoringTypeChanged(void *param, calldata_t *calldata); static void OBSSourceMixersChanged(void *param, calldata_t *calldata); static void OBSSourceBalanceChanged(void *param, calldata_t *calldata); static void OBSSourceRenamed(void *param, calldata_t *calldata); diff --git a/UI/api-interface.cpp b/UI/api-interface.cpp index 82b5d16a1..bb3715017 100644 --- a/UI/api-interface.cpp +++ b/UI/api-interface.cpp @@ -28,19 +28,15 @@ template struct OBSStudioCallback { T callback; void *private_data; - inline OBSStudioCallback(T cb, void *p) : callback(cb), private_data(p) - { - } + inline OBSStudioCallback(T cb, void *p) : callback(cb), private_data(p) {} }; template -inline size_t GetCallbackIdx(vector> &callbacks, - T callback, void *private_data) +inline size_t GetCallbackIdx(vector> &callbacks, T callback, void *private_data) { for (size_t i = 0; i < callbacks.size(); i++) { OBSStudioCallback curCB = callbacks[i]; - if (curCB.callback == callback && - curCB.private_data == private_data) + if (curCB.callback == callback && curCB.private_data == private_data) return i; } @@ -55,23 +51,13 @@ struct OBSStudioAPI : obs_frontend_callbacks { inline OBSStudioAPI(OBSBasic *main_) : main(main_) {} - void *obs_frontend_get_main_window(void) override - { - return (void *)main; - } + void *obs_frontend_get_main_window(void) override { return (void *)main; } - void *obs_frontend_get_main_window_handle(void) override - { - return (void *)main->winId(); - } + void *obs_frontend_get_main_window_handle(void) override { return (void *)main->winId(); } - void *obs_frontend_get_system_tray(void) override - { - return (void *)main->trayIcon.data(); - } + void *obs_frontend_get_system_tray(void) override { return (void *)main->trayIcon.data(); } - void obs_frontend_get_scenes( - struct obs_frontend_source_list *sources) override + void obs_frontend_get_scenes(struct obs_frontend_source_list *sources) override { for (int i = 0; i < main->ui->scenes->count(); i++) { QListWidgetItem *item = main->ui->scenes->item(i); @@ -96,23 +82,18 @@ struct OBSStudioAPI : obs_frontend_callbacks { void obs_frontend_set_current_scene(obs_source_t *scene) override { if (main->IsPreviewProgramMode()) { - QMetaObject::invokeMethod( - main, "TransitionToScene", WaitConnection(), - Q_ARG(OBSSource, OBSSource(scene))); + QMetaObject::invokeMethod(main, "TransitionToScene", WaitConnection(), + Q_ARG(OBSSource, OBSSource(scene))); } else { - QMetaObject::invokeMethod( - main, "SetCurrentScene", WaitConnection(), - Q_ARG(OBSSource, OBSSource(scene)), - Q_ARG(bool, false)); + QMetaObject::invokeMethod(main, "SetCurrentScene", WaitConnection(), + Q_ARG(OBSSource, OBSSource(scene)), Q_ARG(bool, false)); } } - void obs_frontend_get_transitions( - struct obs_frontend_source_list *sources) override + void obs_frontend_get_transitions(struct obs_frontend_source_list *sources) override { for (int i = 0; i < main->ui->transitions->count(); i++) { - OBSSource tr = main->ui->transitions->itemData(i) - .value(); + OBSSource tr = main->ui->transitions->itemData(i).value(); if (!tr) continue; @@ -128,62 +109,43 @@ struct OBSStudioAPI : obs_frontend_callbacks { return obs_source_get_ref(tr); } - void - obs_frontend_set_current_transition(obs_source_t *transition) override + void obs_frontend_set_current_transition(obs_source_t *transition) override { - QMetaObject::invokeMethod(main, "SetTransition", - Q_ARG(OBSSource, - OBSSource(transition))); + QMetaObject::invokeMethod(main, "SetTransition", Q_ARG(OBSSource, OBSSource(transition))); } - int obs_frontend_get_transition_duration(void) override - { - return main->ui->transitionDuration->value(); - } + int obs_frontend_get_transition_duration(void) override { return main->ui->transitionDuration->value(); } void obs_frontend_set_transition_duration(int duration) override { - QMetaObject::invokeMethod(main->ui->transitionDuration, - "setValue", Q_ARG(int, duration)); + QMetaObject::invokeMethod(main->ui->transitionDuration, "setValue", Q_ARG(int, duration)); } - void obs_frontend_release_tbar(void) override - { - QMetaObject::invokeMethod(main, "TBarReleased"); - } + void obs_frontend_release_tbar(void) override { QMetaObject::invokeMethod(main, "TBarReleased"); } void obs_frontend_set_tbar_position(int position) override { - QMetaObject::invokeMethod(main, "TBarChanged", - Q_ARG(int, position)); + QMetaObject::invokeMethod(main, "TBarChanged", Q_ARG(int, position)); } - int obs_frontend_get_tbar_position(void) override - { - return main->tBar->value(); - } + int obs_frontend_get_tbar_position(void) override { return main->tBar->value(); } - void obs_frontend_get_scene_collections( - std::vector &strings) override + void obs_frontend_get_scene_collections(std::vector &strings) override { - for (auto &[collectionName, collection] : - main->GetSceneCollectionCache()) { + for (auto &[collectionName, collection] : main->GetSceneCollectionCache()) { strings.emplace_back(collectionName); } } char *obs_frontend_get_current_scene_collection(void) override { - const OBSSceneCollection ¤tCollection = - main->GetCurrentSceneCollection(); + const OBSSceneCollection ¤tCollection = main->GetCurrentSceneCollection(); return bstrdup(currentCollection.name.c_str()); } - void obs_frontend_set_current_scene_collection( - const char *collection) override + void obs_frontend_set_current_scene_collection(const char *collection) override { - QList menuActions = - main->ui->sceneCollectionMenu->actions(); + QList menuActions = main->ui->sceneCollectionMenu->actions(); QString qstrCollection = QT_UTF8(collection); for (int i = 0; i < menuActions.count(); i++) { @@ -202,15 +164,12 @@ struct OBSStudioAPI : obs_frontend_callbacks { bool obs_frontend_add_scene_collection(const char *name) override { bool success = false; - QMetaObject::invokeMethod(main, "CreateNewSceneCollection", - WaitConnection(), - Q_RETURN_ARG(bool, success), - Q_ARG(QString, QT_UTF8(name))); + QMetaObject::invokeMethod(main, "CreateNewSceneCollection", WaitConnection(), + Q_RETURN_ARG(bool, success), Q_ARG(QString, QT_UTF8(name))); return success; } - void - obs_frontend_get_profiles(std::vector &strings) override + void obs_frontend_get_profiles(std::vector &strings) override { const OBSProfileCache &profiles = main->GetProfileCache(); @@ -252,69 +211,42 @@ struct OBSStudioAPI : obs_frontend_callbacks { void obs_frontend_create_profile(const char *name) override { - QMetaObject::invokeMethod(main, "CreateNewProfile", - Q_ARG(QString, name)); + QMetaObject::invokeMethod(main, "CreateNewProfile", Q_ARG(QString, name)); } void obs_frontend_duplicate_profile(const char *name) override { - QMetaObject::invokeMethod(main, "CreateDuplicateProfile", - Q_ARG(QString, name)); + QMetaObject::invokeMethod(main, "CreateDuplicateProfile", Q_ARG(QString, name)); } void obs_frontend_delete_profile(const char *profile) override { - QMetaObject::invokeMethod(main, "DeleteProfile", - Q_ARG(QString, profile)); + QMetaObject::invokeMethod(main, "DeleteProfile", Q_ARG(QString, profile)); } - void obs_frontend_streaming_start(void) override - { - QMetaObject::invokeMethod(main, "StartStreaming"); - } + void obs_frontend_streaming_start(void) override { QMetaObject::invokeMethod(main, "StartStreaming"); } - void obs_frontend_streaming_stop(void) override - { - QMetaObject::invokeMethod(main, "StopStreaming"); - } + void obs_frontend_streaming_stop(void) override { QMetaObject::invokeMethod(main, "StopStreaming"); } - bool obs_frontend_streaming_active(void) override - { - return os_atomic_load_bool(&streaming_active); - } + bool obs_frontend_streaming_active(void) override { return os_atomic_load_bool(&streaming_active); } - void obs_frontend_recording_start(void) override - { - QMetaObject::invokeMethod(main, "StartRecording"); - } + void obs_frontend_recording_start(void) override { QMetaObject::invokeMethod(main, "StartRecording"); } - void obs_frontend_recording_stop(void) override - { - QMetaObject::invokeMethod(main, "StopRecording"); - } + void obs_frontend_recording_stop(void) override { QMetaObject::invokeMethod(main, "StopRecording"); } - bool obs_frontend_recording_active(void) override - { - return os_atomic_load_bool(&recording_active); - } + bool obs_frontend_recording_active(void) override { return os_atomic_load_bool(&recording_active); } void obs_frontend_recording_pause(bool pause) override { - QMetaObject::invokeMethod(main, pause ? "PauseRecording" - : "UnpauseRecording"); + QMetaObject::invokeMethod(main, pause ? "PauseRecording" : "UnpauseRecording"); } - bool obs_frontend_recording_paused(void) override - { - return os_atomic_load_bool(&recording_paused); - } + bool obs_frontend_recording_paused(void) override { return os_atomic_load_bool(&recording_paused); } bool obs_frontend_recording_split_file(void) override { - if (os_atomic_load_bool(&recording_active) && - !os_atomic_load_bool(&recording_paused)) { - proc_handler_t *ph = obs_output_get_proc_handler( - main->outputHandler->fileOutput); + if (os_atomic_load_bool(&recording_active) && !os_atomic_load_bool(&recording_paused)) { + proc_handler_t *ph = obs_output_get_proc_handler(main->outputHandler->fileOutput); uint8_t stack[128]; calldata cd; calldata_init_fixed(&cd, stack, sizeof(stack)); @@ -328,12 +260,10 @@ struct OBSStudioAPI : obs_frontend_callbacks { bool obs_frontend_recording_add_chapter(const char *name) override { - if (!os_atomic_load_bool(&recording_active) || - os_atomic_load_bool(&recording_paused)) + if (!os_atomic_load_bool(&recording_active) || os_atomic_load_bool(&recording_paused)) return false; - proc_handler_t *ph = obs_output_get_proc_handler( - main->outputHandler->fileOutput); + proc_handler_t *ph = obs_output_get_proc_handler(main->outputHandler->fileOutput); calldata cd; calldata_init(&cd); @@ -343,25 +273,13 @@ struct OBSStudioAPI : obs_frontend_callbacks { return result; } - void obs_frontend_replay_buffer_start(void) override - { - QMetaObject::invokeMethod(main, "StartReplayBuffer"); - } + void obs_frontend_replay_buffer_start(void) override { QMetaObject::invokeMethod(main, "StartReplayBuffer"); } - void obs_frontend_replay_buffer_save(void) override - { - QMetaObject::invokeMethod(main, "ReplayBufferSave"); - } + void obs_frontend_replay_buffer_save(void) override { QMetaObject::invokeMethod(main, "ReplayBufferSave"); } - void obs_frontend_replay_buffer_stop(void) override - { - QMetaObject::invokeMethod(main, "StopReplayBuffer"); - } + void obs_frontend_replay_buffer_stop(void) override { QMetaObject::invokeMethod(main, "StopReplayBuffer"); } - bool obs_frontend_replay_buffer_active(void) override - { - return os_atomic_load_bool(&replaybuf_active); - } + bool obs_frontend_replay_buffer_active(void) override { return os_atomic_load_bool(&replaybuf_active); } void *obs_frontend_add_tools_menu_qaction(const char *name) override { @@ -369,9 +287,7 @@ struct OBSStudioAPI : obs_frontend_callbacks { return (void *)main->ui->menuTools->addAction(QT_UTF8(name)); } - void obs_frontend_add_tools_menu_item(const char *name, - obs_frontend_cb callback, - void *private_data) override + void obs_frontend_add_tools_menu_item(const char *name, obs_frontend_cb callback, void *private_data) override { main->ui->menuTools->setEnabled(true); @@ -389,9 +305,8 @@ struct OBSStudioAPI : obs_frontend_callbacks { QString name = d->objectName(); if (name.isEmpty() || main->IsDockObjectNameUsed(name)) { - blog(LOG_WARNING, - "The object name of the added dock is empty or already used," - " a temporary one will be set to avoid conflicts"); + blog(LOG_WARNING, "The object name of the added dock is empty or already used," + " a temporary one will be set to avoid conflicts"); char *uuid = os_generate_uuid(); name = QT_UTF8(uuid); @@ -404,8 +319,7 @@ struct OBSStudioAPI : obs_frontend_callbacks { return (void *)main->AddDockWidget(d); } - bool obs_frontend_add_dock_by_id(const char *id, const char *title, - void *widget) override + bool obs_frontend_add_dock_by_id(const char *id, const char *title, void *widget) override { if (main->IsDockObjectNameUsed(QT_UTF8(id))) { blog(LOG_WARNING, @@ -428,10 +342,7 @@ struct OBSStudioAPI : obs_frontend_callbacks { return true; } - void obs_frontend_remove_dock(const char *id) override - { - main->RemoveDockWidget(QT_UTF8(id)); - } + void obs_frontend_remove_dock(const char *id) override { main->RemoveDockWidget(QT_UTF8(id)); } bool obs_frontend_add_custom_qdock(const char *id, void *dock) override { @@ -451,16 +362,14 @@ struct OBSStudioAPI : obs_frontend_callbacks { return true; } - void obs_frontend_add_event_callback(obs_frontend_event_cb callback, - void *private_data) override + void obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(callbacks, callback, private_data); if (idx == (size_t)-1) callbacks.emplace_back(callback, private_data); } - void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, - void *private_data) override + void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, void *private_data) override { size_t idx = GetCallbackIdx(callbacks, callback, private_data); if (idx == (size_t)-1) @@ -471,13 +380,8 @@ struct OBSStudioAPI : obs_frontend_callbacks { obs_output_t *obs_frontend_get_streaming_output(void) override { - auto multitrackVideo = - main->outputHandler->multitrackVideo.get(); - auto mtvOutput = - multitrackVideo - ? obs_output_get_ref( - multitrackVideo->StreamingOutput()) - : nullptr; + auto multitrackVideo = main->outputHandler->multitrackVideo.get(); + auto mtvOutput = multitrackVideo ? obs_output_get_ref(multitrackVideo->StreamingOutput()) : nullptr; if (mtvOutput) return mtvOutput; @@ -497,10 +401,7 @@ struct OBSStudioAPI : obs_frontend_callbacks { return obs_output_get_ref(out); } - config_t *obs_frontend_get_profile_config(void) override - { - return main->activeConfiguration; - } + config_t *obs_frontend_get_profile_config(void) override { return main->activeConfiguration; } config_t *obs_frontend_get_global_config(void) override { @@ -509,19 +410,11 @@ struct OBSStudioAPI : obs_frontend_callbacks { return App()->GetAppConfig(); } - config_t *obs_frontend_get_app_config(void) override - { - return App()->GetAppConfig(); - } + config_t *obs_frontend_get_app_config(void) override { return App()->GetAppConfig(); } - config_t *obs_frontend_get_user_config(void) override - { - return App()->GetUserConfig(); - } + config_t *obs_frontend_get_user_config(void) override { return App()->GetUserConfig(); } - void obs_frontend_open_projector(const char *type, int monitor, - const char *geometry, - const char *name) override + void obs_frontend_open_projector(const char *type, int monitor, const char *geometry, const char *name) override { SavedProjectorInfo proj = { ProjectorType::Preview, @@ -539,108 +432,71 @@ struct OBSStudioAPI : obs_frontend_callbacks { else if (astrcmpi(type, "Multiview") == 0) proj.type = ProjectorType::Multiview; } - QMetaObject::invokeMethod(main, "OpenSavedProjector", - WaitConnection(), + QMetaObject::invokeMethod(main, "OpenSavedProjector", WaitConnection(), Q_ARG(SavedProjectorInfo *, &proj)); } void obs_frontend_save(void) override { main->SaveProject(); } - void obs_frontend_defer_save_begin(void) override - { - QMetaObject::invokeMethod(main, "DeferSaveBegin"); - } + void obs_frontend_defer_save_begin(void) override { QMetaObject::invokeMethod(main, "DeferSaveBegin"); } - void obs_frontend_defer_save_end(void) override - { - QMetaObject::invokeMethod(main, "DeferSaveEnd"); - } + void obs_frontend_defer_save_end(void) override { QMetaObject::invokeMethod(main, "DeferSaveEnd"); } - void obs_frontend_add_save_callback(obs_frontend_save_cb callback, - void *private_data) override + void obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data) override { - size_t idx = - GetCallbackIdx(saveCallbacks, callback, private_data); + size_t idx = GetCallbackIdx(saveCallbacks, callback, private_data); if (idx == (size_t)-1) saveCallbacks.emplace_back(callback, private_data); } - void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, - void *private_data) override + void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, void *private_data) override { - size_t idx = - GetCallbackIdx(saveCallbacks, callback, private_data); + size_t idx = GetCallbackIdx(saveCallbacks, callback, private_data); if (idx == (size_t)-1) return; saveCallbacks.erase(saveCallbacks.begin() + idx); } - void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, - void *private_data) override + void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, void *private_data) override { - size_t idx = GetCallbackIdx(preloadCallbacks, callback, - private_data); + size_t idx = GetCallbackIdx(preloadCallbacks, callback, private_data); if (idx == (size_t)-1) preloadCallbacks.emplace_back(callback, private_data); } - void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, - void *private_data) override + void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, void *private_data) override { - size_t idx = GetCallbackIdx(preloadCallbacks, callback, - private_data); + size_t idx = GetCallbackIdx(preloadCallbacks, callback, private_data); if (idx == (size_t)-1) return; preloadCallbacks.erase(preloadCallbacks.begin() + idx); } - void obs_frontend_push_ui_translation( - obs_frontend_translate_ui_cb translate) override + void obs_frontend_push_ui_translation(obs_frontend_translate_ui_cb translate) override { App()->PushUITranslation(translate); } - void obs_frontend_pop_ui_translation(void) override - { - App()->PopUITranslation(); - } + void obs_frontend_pop_ui_translation(void) override { App()->PopUITranslation(); } - void obs_frontend_set_streaming_service(obs_service_t *service) override - { - main->SetService(service); - } + void obs_frontend_set_streaming_service(obs_service_t *service) override { main->SetService(service); } - obs_service_t *obs_frontend_get_streaming_service(void) override - { - return main->GetService(); - } + obs_service_t *obs_frontend_get_streaming_service(void) override { return main->GetService(); } - void obs_frontend_save_streaming_service(void) override - { - main->SaveService(); - } + void obs_frontend_save_streaming_service(void) override { main->SaveService(); } - bool obs_frontend_preview_program_mode_active(void) override - { - return main->IsPreviewProgramMode(); - } + bool obs_frontend_preview_program_mode_active(void) override { return main->IsPreviewProgramMode(); } - void obs_frontend_set_preview_program_mode(bool enable) override - { - main->SetPreviewProgramMode(enable); - } + void obs_frontend_set_preview_program_mode(bool enable) override { main->SetPreviewProgramMode(enable); } void obs_frontend_preview_program_trigger_transition(void) override { QMetaObject::invokeMethod(main, "TransitionClicked"); } - bool obs_frontend_preview_enabled(void) override - { - return main->previewEnabled; - } + bool obs_frontend_preview_enabled(void) override { return main->previewEnabled; } void obs_frontend_set_preview_enabled(bool enable) override { @@ -658,26 +514,19 @@ struct OBSStudioAPI : obs_frontend_callbacks { return nullptr; } - void - obs_frontend_set_current_preview_scene(obs_source_t *scene) override + void obs_frontend_set_current_preview_scene(obs_source_t *scene) override { if (main->IsPreviewProgramMode()) { - QMetaObject::invokeMethod(main, "SetCurrentScene", - Q_ARG(OBSSource, - OBSSource(scene)), + QMetaObject::invokeMethod(main, "SetCurrentScene", Q_ARG(OBSSource, OBSSource(scene)), Q_ARG(bool, false)); } } - void obs_frontend_take_screenshot(void) override - { - QMetaObject::invokeMethod(main, "Screenshot"); - } + void obs_frontend_take_screenshot(void) override { QMetaObject::invokeMethod(main, "Screenshot"); } void obs_frontend_take_source_screenshot(obs_source_t *source) override { - QMetaObject::invokeMethod(main, "Screenshot", - Q_ARG(OBSSource, OBSSource(source))); + QMetaObject::invokeMethod(main, "Screenshot", Q_ARG(OBSSource, OBSSource(source))); } obs_output_t *obs_frontend_get_virtualcam_output(void) override @@ -686,47 +535,32 @@ struct OBSStudioAPI : obs_frontend_callbacks { return obs_output_get_ref(output); } - void obs_frontend_start_virtualcam(void) override - { - QMetaObject::invokeMethod(main, "StartVirtualCam"); - } + void obs_frontend_start_virtualcam(void) override { QMetaObject::invokeMethod(main, "StartVirtualCam"); } - void obs_frontend_stop_virtualcam(void) override - { - QMetaObject::invokeMethod(main, "StopVirtualCam"); - } + void obs_frontend_stop_virtualcam(void) override { QMetaObject::invokeMethod(main, "StopVirtualCam"); } - bool obs_frontend_virtualcam_active(void) override - { - return os_atomic_load_bool(&virtualcam_active); - } + bool obs_frontend_virtualcam_active(void) override { return os_atomic_load_bool(&virtualcam_active); } void obs_frontend_reset_video(void) override { main->ResetVideo(); } void obs_frontend_open_source_properties(obs_source_t *source) override { - QMetaObject::invokeMethod(main, "OpenProperties", - Q_ARG(OBSSource, OBSSource(source))); + QMetaObject::invokeMethod(main, "OpenProperties", Q_ARG(OBSSource, OBSSource(source))); } void obs_frontend_open_source_filters(obs_source_t *source) override { - QMetaObject::invokeMethod(main, "OpenFilters", - Q_ARG(OBSSource, OBSSource(source))); + QMetaObject::invokeMethod(main, "OpenFilters", Q_ARG(OBSSource, OBSSource(source))); } void obs_frontend_open_source_interaction(obs_source_t *source) override { - QMetaObject::invokeMethod(main, "OpenInteraction", - Q_ARG(OBSSource, OBSSource(source))); + QMetaObject::invokeMethod(main, "OpenInteraction", Q_ARG(OBSSource, OBSSource(source))); } - void obs_frontend_open_sceneitem_edit_transform( - obs_sceneitem_t *item) override + void obs_frontend_open_sceneitem_edit_transform(obs_sceneitem_t *item) override { - QMetaObject::invokeMethod(main, "OpenEditTransform", - Q_ARG(OBSSceneItem, - OBSSceneItem(item))); + QMetaObject::invokeMethod(main, "OpenEditTransform", Q_ARG(OBSSceneItem, OBSSceneItem(item))); } char *obs_frontend_get_current_record_output_path(void) override @@ -736,43 +570,25 @@ struct OBSStudioAPI : obs_frontend_callbacks { return bstrdup(recordOutputPath); } - const char *obs_frontend_get_locale_string(const char *string) override - { - return Str(string); - } + const char *obs_frontend_get_locale_string(const char *string) override { return Str(string); } - bool obs_frontend_is_theme_dark(void) override - { - return App()->IsThemeDark(); - } + bool obs_frontend_is_theme_dark(void) override { return App()->IsThemeDark(); } char *obs_frontend_get_last_recording(void) override { return bstrdup(main->outputHandler->lastRecordingPath.c_str()); } - char *obs_frontend_get_last_screenshot(void) override - { - return bstrdup(main->lastScreenshot.c_str()); - } + char *obs_frontend_get_last_screenshot(void) override { return bstrdup(main->lastScreenshot.c_str()); } - char *obs_frontend_get_last_replay(void) override - { - return bstrdup(main->lastReplay.c_str()); - } + char *obs_frontend_get_last_replay(void) override { return bstrdup(main->lastReplay.c_str()); } - void obs_frontend_add_undo_redo_action(const char *name, - const undo_redo_cb undo, - const undo_redo_cb redo, - const char *undo_data, - const char *redo_data, - bool repeatable) override + void obs_frontend_add_undo_redo_action(const char *name, const undo_redo_cb undo, const undo_redo_cb redo, + const char *undo_data, const char *redo_data, bool repeatable) override { main->undo_s.add_action( - name, - [undo](const std::string &data) { undo(data.c_str()); }, - [redo](const std::string &data) { redo(data.c_str()); }, - undo_data, redo_data, repeatable); + name, [undo](const std::string &data) { undo(data.c_str()); }, + [redo](const std::string &data) { redo(data.c_str()); }, undo_data, redo_data, repeatable); } void on_load(obs_data_t *settings) override @@ -801,8 +617,7 @@ struct OBSStudioAPI : obs_frontend_callbacks { void on_event(enum obs_frontend_event event) override { - if (main->disableSaving && - event != OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP && + if (main->disableSaving && event != OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP && event != OBS_FRONTEND_EVENT_EXIT) return; diff --git a/UI/audio-encoders.cpp b/UI/audio-encoders.cpp index e1a0c4cb5..692f25719 100644 --- a/UI/audio-encoders.cpp +++ b/UI/audio-encoders.cpp @@ -32,8 +32,7 @@ static void HandleIntProperty(obs_property_t *prop, std::vector &bitrates) bitrates.push_back(i); } -static void HandleListProperty(obs_property_t *prop, const char *id, - std::vector &bitrates) +static void HandleListProperty(obs_property_t *prop, const char *id, std::vector &bitrates) { obs_combo_format format = obs_property_list_format(prop); if (format != OBS_COMBO_FORMAT_INT) { @@ -50,8 +49,7 @@ static void HandleListProperty(obs_property_t *prop, const char *id, if (obs_property_list_item_disabled(prop, i)) continue; - int bitrate = - static_cast(obs_property_list_item_int(prop, i)); + int bitrate = static_cast(obs_property_list_item_int(prop, i)); bitrates.push_back(bitrate); } } @@ -61,8 +59,7 @@ static void HandleSampleRate(obs_property_t *prop, const char *id) auto ReleaseData = [](obs_data_t *data) { obs_data_release(data); }; - std::unique_ptr data{ - obs_encoder_defaults(id), ReleaseData}; + std::unique_ptr data{obs_encoder_defaults(id), ReleaseData}; if (!data) { blog(LOG_ERROR, @@ -79,8 +76,7 @@ static void HandleSampleRate(obs_property_t *prop, const char *id) return; } - uint32_t sampleRate = - config_get_uint(main->Config(), "Audio", "SampleRate"); + uint32_t sampleRate = config_get_uint(main->Config(), "Audio", "SampleRate"); obs_data_set_int(data.get(), "samplerate", sampleRate); @@ -92,8 +88,8 @@ static void HandleEncoderProperties(const char *id, std::vector &bitrates) auto DestroyProperties = [](obs_properties_t *props) { obs_properties_destroy(props); }; - std::unique_ptr props{ - obs_get_encoder_properties(id), DestroyProperties}; + std::unique_ptr props{obs_get_encoder_properties(id), + DestroyProperties}; if (!props) { blog(LOG_ERROR, @@ -103,8 +99,7 @@ static void HandleEncoderProperties(const char *id, std::vector &bitrates) return; } - obs_property_t *samplerate = - obs_properties_get(props.get(), "samplerate"); + obs_property_t *samplerate = obs_properties_get(props.get(), "samplerate"); if (samplerate) HandleSampleRate(samplerate, id); @@ -156,16 +151,14 @@ static void PopulateBitrateLists() for (auto &bitrate : fallbackBitrates) ss << "\n " << setw(3) << bitrate << " kbit/s:"; - blog(LOG_DEBUG, "Fallback encoder bitrates:%s", - ss.str().c_str()); + blog(LOG_DEBUG, "Fallback encoder bitrates:%s", ss.str().c_str()); const char *id = nullptr; for (size_t i = 0; obs_enum_encoder_types(i, &id); i++) { if (obs_get_encoder_type(id) != OBS_ENCODER_AUDIO) continue; - if (strcmp(id, "ffmpeg_aac") == 0 || - strcmp(id, "ffmpeg_opus") == 0) + if (strcmp(id, "ffmpeg_aac") == 0 || strcmp(id, "ffmpeg_opus") == 0) continue; std::string encoder = id; @@ -180,11 +173,9 @@ static void PopulateBitrateLists() ostringstream ss; for (auto &bitrate : encoderBitrates[encoder]) - ss << "\n " << setw(3) << bitrate - << " kbit/s"; + ss << "\n " << setw(3) << bitrate << " kbit/s"; - blog(LOG_DEBUG, "%s (%s) encoder bitrates:%s", - EncoderName(id), id, ss.str().c_str()); + blog(LOG_DEBUG, "%s (%s) encoder bitrates:%s", EncoderName(id), id, ss.str().c_str()); } if (encoderBitrates.empty() && fallbackBitrates.empty()) @@ -222,8 +213,7 @@ static void PopulateSimpleAACBitrateMap() return val == NullToEmpty(id); }; - if (find_if(begin(encoders), end(encoders), Compare) != - end(encoders)) + if (find_if(begin(encoders), end(encoders), Compare) != end(encoders)) continue; if (strcmp(GetCodec(id), "aac") != 0) @@ -256,12 +246,10 @@ static void PopulateSimpleAACBitrateMap() ostringstream ss; for (auto &entry : simpleAACBitrateMap) - ss << "\n " << setw(3) << entry.first - << " kbit/s: '" << EncoderName(entry.second) << "' (" - << entry.second << ')'; + ss << "\n " << setw(3) << entry.first << " kbit/s: '" << EncoderName(entry.second) + << "' (" << entry.second << ')'; - blog(LOG_DEBUG, "AAC simple encoder bitrate mapping:%s", - ss.str().c_str()); + blog(LOG_DEBUG, "AAC simple encoder bitrate mapping:%s", ss.str().c_str()); }); } @@ -301,12 +289,10 @@ static void PopulateSimpleOpusBitrateMap() ostringstream ss; for (auto &entry : simpleOpusBitrateMap) - ss << "\n " << setw(3) << entry.first - << " kbit/s: '" << EncoderName(entry.second) << "' (" - << entry.second << ')'; + ss << "\n " << setw(3) << entry.first << " kbit/s: '" << EncoderName(entry.second) + << "' (" << entry.second << ')'; - blog(LOG_DEBUG, "Opus simple encoder bitrate mapping:%s", - ss.str().c_str()); + blog(LOG_DEBUG, "Opus simple encoder bitrate mapping:%s", ss.str().c_str()); }); } @@ -342,8 +328,7 @@ const char *GetSimpleOpusEncoderForBitrate(int bitrate) #define INVALID_BITRATE 10000 -static int FindClosestAvailableSimpleBitrate(int bitrate, - const map &map) +static int FindClosestAvailableSimpleBitrate(int bitrate, const map &map) { int prev = 0; int next = INVALID_BITRATE; @@ -369,14 +354,12 @@ static int FindClosestAvailableSimpleBitrate(int bitrate, int FindClosestAvailableSimpleAACBitrate(int bitrate) { - return FindClosestAvailableSimpleBitrate( - bitrate, GetSimpleAACEncoderBitrateMap()); + return FindClosestAvailableSimpleBitrate(bitrate, GetSimpleAACEncoderBitrateMap()); } int FindClosestAvailableSimpleOpusBitrate(int bitrate) { - return FindClosestAvailableSimpleBitrate( - bitrate, GetSimpleOpusEncoderBitrateMap()); + return FindClosestAvailableSimpleBitrate(bitrate, GetSimpleOpusEncoderBitrateMap()); } const std::vector &GetAudioEncoderBitrates(const char *id) @@ -396,9 +379,7 @@ int FindClosestAvailableAudioBitrate(const char *id, int bitrate) int next = INVALID_BITRATE; std::string encoder = id; - for (auto val : encoderBitrates[encoder].empty() - ? fallbackBitrates - : encoderBitrates[encoder]) { + for (auto val : encoderBitrates[encoder].empty() ? fallbackBitrates : encoderBitrates[encoder]) { if (next > val) { if (val == bitrate) return bitrate; diff --git a/UI/auth-base.cpp b/UI/auth-base.cpp index 157164b48..1f0999fe0 100644 --- a/UI/auth-base.cpp +++ b/UI/auth-base.cpp @@ -61,8 +61,7 @@ void Auth::Load() if (main->auth) { if (main->auth->LoadInternal()) { main->auth->LoadUI(); - main->SetBroadcastFlowEnabled( - main->auth->broadcastFlow()); + main->SetBroadcastFlowEnabled(main->auth->broadcastFlow()); } } else { main->SetBroadcastFlowEnabled(false); diff --git a/UI/auth-base.hpp b/UI/auth-base.hpp index 8d727f6cf..9745f63fe 100644 --- a/UI/auth-base.hpp +++ b/UI/auth-base.hpp @@ -17,11 +17,7 @@ protected: std::string message; std::string error; - ErrorInfo(std::string message_, std::string error_) - : message(message_), - error(error_) - { - } + ErrorInfo(std::string message_, std::string error_) : message(message_), error(error_) {} }; public: diff --git a/UI/auth-listener.cpp b/UI/auth-listener.cpp index efd637bf2..e652da4d3 100644 --- a/UI/auth-listener.cpp +++ b/UI/auth-listener.cpp @@ -10,33 +10,29 @@ #define LOGO_URL "https://obsproject.com/assets/images/new_icon_small-r.png" -static const QString serverResponseHeader = - QStringLiteral("HTTP/1.0 200 OK\n" - "Connection: close\n" - "Content-Type: text/html; charset=UTF-8\n" - "Server: OBS Studio\n" - "\n" - "OBS Studio" - ""); +static const QString serverResponseHeader = QStringLiteral("HTTP/1.0 200 OK\n" + "Connection: close\n" + "Content-Type: text/html; charset=UTF-8\n" + "Server: OBS Studio\n" + "\n" + "OBS Studio" + ""); -static const QString responseTemplate = - "
" - "\"OBS\"" - "
" - "

%1

"; +static const QString responseTemplate = "
" + "\"OBS\"" + "
" + "

%1

"; AuthListener::AuthListener(QObject *parent) : QObject(parent) { server = new QTcpServer(this); - connect(server, &QTcpServer::newConnection, this, - &AuthListener::NewConnection); + connect(server, &QTcpServer::newConnection, this, &AuthListener::NewConnection); if (!server->listen(QHostAddress::LocalHost, 0)) { blog(LOG_DEBUG, "Server could not start"); emit fail(); } else { - blog(LOG_DEBUG, "Server started at port %d", - server->serverPort()); + blog(LOG_DEBUG, "Server started at port %d", server->serverPort()); } } @@ -54,8 +50,7 @@ void AuthListener::NewConnection() { QTcpSocket *socket = server->nextPendingConnection(); if (socket) { - connect(socket, &QTcpSocket::disconnected, socket, - &QTcpSocket::deleteLater); + connect(socket, &QTcpSocket::disconnected, socket, &QTcpSocket::deleteLater); connect(socket, &QTcpSocket::readyRead, socket, [&, socket]() { QByteArray buffer; while (socket->bytesAvailable() > 0) { @@ -65,13 +60,10 @@ void AuthListener::NewConnection() QString redirect = QString::fromLatin1(buffer); blog(LOG_DEBUG, "redirect: %s", QT_TO_UTF8(redirect)); - QRegularExpression re_state( - "(&|\\?)state=(?[^&]+)"); - QRegularExpression re_code( - "(&|\\?)code=(?[^&]+)"); + QRegularExpression re_state("(&|\\?)state=(?[^&]+)"); + QRegularExpression re_code("(&|\\?)code=(?[^&]+)"); - QRegularExpressionMatch match = - re_state.match(redirect); + QRegularExpressionMatch match = re_state.match(redirect); QString code; @@ -95,13 +87,11 @@ void AuthListener::NewConnection() } if (code.isEmpty()) { - auto data = responseTemplate.arg( - QTStr("YouTube.Auth.NoCode")); + auto data = responseTemplate.arg(QTStr("YouTube.Auth.NoCode")); socket->write(QT_TO_UTF8(data)); emit fail(); } else { - auto data = responseTemplate.arg( - QTStr("YouTube.Auth.Ok")); + auto data = responseTemplate.arg(QTStr("YouTube.Auth.Ok")); socket->write(QT_TO_UTF8(data)); emit ok(code); } diff --git a/UI/auth-oauth.cpp b/UI/auth-oauth.cpp index 0053b7863..04458c9c5 100644 --- a/UI/auth-oauth.cpp +++ b/UI/auth-oauth.cpp @@ -26,9 +26,7 @@ extern QCefCookieManager *panel_cookies; /* ------------------------------------------------------------------------- */ -OAuthLogin::OAuthLogin(QWidget *parent, const std::string &url, bool token) - : QDialog(parent), - get_token(token) +OAuthLogin::OAuthLogin(QWidget *parent, const std::string &url, bool token) : QDialog(parent), get_token(token) { #ifdef BROWSER_AVAILABLE if (!cef) { @@ -51,10 +49,8 @@ OAuthLogin::OAuthLogin(QWidget *parent, const std::string &url, bool token) return; } - connect(cefWidget, &QCefWidget::titleChanged, this, - &OAuthLogin::setWindowTitle); - connect(cefWidget, &QCefWidget::urlChanged, this, - &OAuthLogin::urlChanged); + connect(cefWidget, &QCefWidget::titleChanged, this, &OAuthLogin::setWindowTitle); + connect(cefWidget, &QCefWidget::urlChanged, this, &OAuthLogin::urlChanged); QPushButton *close = new QPushButton(QTStr("Cancel")); connect(close, &QAbstractButton::clicked, this, &QDialog::reject); @@ -131,8 +127,7 @@ struct OAuthInfo { static std::vector loginCBs; -void OAuth::RegisterOAuth(const Def &d, create_cb create, login_cb login, - delete_cookies_cb delete_cookies) +void OAuth::RegisterOAuth(const Def &d, create_cb create, login_cb login, delete_cookies_cb delete_cookies) { OAuthInfo info = {d, login, delete_cookies}; loginCBs.push_back(info); @@ -162,15 +157,13 @@ void OAuth::DeleteCookies(const std::string &service) void OAuth::SaveInternal() { OBSBasic *main = OBSBasic::Get(); - config_set_string(main->Config(), service(), "RefreshToken", - refresh_token.c_str()); + config_set_string(main->Config(), service(), "RefreshToken", refresh_token.c_str()); config_set_string(main->Config(), service(), "Token", token.c_str()); config_set_uint(main->Config(), service(), "ExpireTime", expire_time); config_set_int(main->Config(), service(), "ScopeVer", currentScopeVer); } -static inline std::string get_config_str(OBSBasic *main, const char *section, - const char *name) +static inline std::string get_config_str(OBSBasic *main, const char *section, const char *name) { const char *val = config_get_string(main->Config(), section, name); return val ? val : ""; @@ -182,8 +175,7 @@ bool OAuth::LoadInternal() refresh_token = get_config_str(main, service(), "RefreshToken"); token = get_config_str(main, service(), "Token"); expire_time = config_get_uint(main->Config(), service(), "ExpireTime"); - currentScopeVer = - (int)config_get_int(main->Config(), service(), "ScopeVer"); + currentScopeVer = (int)config_get_int(main->Config(), service(), "ScopeVer"); return implicit ? !token.empty() : !refresh_token.empty(); } @@ -196,25 +188,20 @@ bool OAuth::TokenExpired() return false; } -bool OAuth::GetToken(const char *url, const std::string &client_id, - const std::string &secret, const std::string &redirect_uri, - int scope_ver, const std::string &auth_code, bool retry) +bool OAuth::GetToken(const char *url, const std::string &client_id, const std::string &secret, + const std::string &redirect_uri, int scope_ver, const std::string &auth_code, bool retry) { - return GetTokenInternal(url, client_id, secret, redirect_uri, scope_ver, - auth_code, retry); + return GetTokenInternal(url, client_id, secret, redirect_uri, scope_ver, auth_code, retry); } -bool OAuth::GetToken(const char *url, const std::string &client_id, - int scope_ver, const std::string &auth_code, bool retry) +bool OAuth::GetToken(const char *url, const std::string &client_id, int scope_ver, const std::string &auth_code, + bool retry) { - return GetTokenInternal(url, client_id, {}, {}, scope_ver, auth_code, - retry); + return GetTokenInternal(url, client_id, {}, {}, scope_ver, auth_code, retry); } -bool OAuth::GetTokenInternal(const char *url, const std::string &client_id, - const std::string &secret, - const std::string &redirect_uri, int scope_ver, - const std::string &auth_code, bool retry) +bool OAuth::GetTokenInternal(const char *url, const std::string &client_id, const std::string &secret, + const std::string &redirect_uri, int scope_ver, const std::string &auth_code, bool retry) try { std::string output; std::string error; @@ -225,8 +212,7 @@ try { return true; } else { QString title = QTStr("Auth.InvalidScope.Title"); - QString text = - QTStr("Auth.InvalidScope.Text").arg(service()); + QString text = QTStr("Auth.InvalidScope.Text").arg(service()); QMessageBox::warning(OBSBasic::Get(), title, text); } @@ -259,14 +245,11 @@ try { bool success = false; auto func = [&]() { - success = GetRemoteFile(url, output, error, nullptr, - "application/x-www-form-urlencoded", "", - post_data.c_str(), - std::vector(), nullptr, 5); + success = GetRemoteFile(url, output, error, nullptr, "application/x-www-form-urlencoded", "", + post_data.c_str(), std::vector(), nullptr, 5); }; - ExecThreadedWithoutBlocking(func, QTStr("Auth.Authing.Title"), - QTStr("Auth.Authing.Text").arg(service())); + ExecThreadedWithoutBlocking(func, QTStr("Auth.Authing.Title"), QTStr("Auth.Authing.Text").arg(service())); if (!success || output.empty()) throw ErrorInfo("Failed to get token from remote", error); @@ -284,8 +267,7 @@ try { } } if (!error.empty()) - throw ErrorInfo(error, - json["error_description"].string_value()); + throw ErrorInfo(error, json["error_description"].string_value()); /* -------------------------- */ /* success! */ @@ -310,15 +292,12 @@ try { } catch (ErrorInfo &info) { if (!retry) { QString title = QTStr("Auth.AuthFailure.Title"); - QString text = QTStr("Auth.AuthFailure.Text") - .arg(service(), info.message.c_str(), - info.error.c_str()); + QString text = QTStr("Auth.AuthFailure.Text").arg(service(), info.message.c_str(), info.error.c_str()); QMessageBox::warning(OBSBasic::Get(), title, text); } - blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), - info.error.c_str()); + blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), info.error.c_str()); return false; } @@ -335,8 +314,7 @@ void OAuthStreamKey::OnStreamConfig() bool bwtest = obs_data_get_bool(settings, "bwtest"); if (bwtest && strcmp(this->service(), "Twitch") == 0) - obs_data_set_string(settings, "key", - (key_ + "?bandwidthtest=true").c_str()); + obs_data_set_string(settings, "key", (key_ + "?bandwidthtest=true").c_str()); else obs_data_set_string(settings, "key", key_.c_str()); diff --git a/UI/auth-oauth.hpp b/UI/auth-oauth.hpp index 364dccdc4..b6602e815 100644 --- a/UI/auth-oauth.hpp +++ b/UI/auth-oauth.hpp @@ -37,18 +37,13 @@ class OAuth : public Auth { public: inline OAuth(const Def &d) : Auth(d) {} - typedef std::function( - QWidget *, const std::string &service_name)> - login_cb; + typedef std::function(QWidget *, const std::string &service_name)> login_cb; typedef std::function delete_cookies_cb; - static std::shared_ptr Login(QWidget *parent, - const std::string &service); + static std::shared_ptr Login(QWidget *parent, const std::string &service); static void DeleteCookies(const std::string &service); - static void RegisterOAuth(const Def &d, create_cb create, - login_cb login, - delete_cookies_cb delete_cookies); + static void RegisterOAuth(const Def &d, create_cb create, login_cb login, delete_cookies_cb delete_cookies); protected: std::string refresh_token; @@ -62,20 +57,14 @@ protected: virtual bool RetryLogin() = 0; bool TokenExpired(); - bool GetToken(const char *url, const std::string &client_id, - int scope_ver, - const std::string &auth_code = std::string(), - bool retry = false); - bool GetToken(const char *url, const std::string &client_id, - const std::string &secret, - const std::string &redirect_uri, int scope_ver, - const std::string &auth_code, bool retry); + bool GetToken(const char *url, const std::string &client_id, int scope_ver, + const std::string &auth_code = std::string(), bool retry = false); + bool GetToken(const char *url, const std::string &client_id, const std::string &secret, + const std::string &redirect_uri, int scope_ver, const std::string &auth_code, bool retry); private: - bool GetTokenInternal(const char *url, const std::string &client_id, - const std::string &secret, - const std::string &redirect_uri, int scope_ver, - const std::string &auth_code, bool retry); + bool GetTokenInternal(const char *url, const std::string &client_id, const std::string &secret, + const std::string &redirect_uri, int scope_ver, const std::string &auth_code, bool retry); }; class OAuthStreamKey : public OAuth { diff --git a/UI/auth-restream.cpp b/UI/auth-restream.cpp index f091016f3..bffe14070 100644 --- a/UI/auth-restream.cpp +++ b/UI/auth-restream.cpp @@ -72,14 +72,12 @@ try { bool success; auto func = [&]() { - success = GetRemoteFile(RESTREAM_STREAMKEY_URL, output, error, - nullptr, "application/json", "", - nullptr, headers, nullptr, 5); + success = GetRemoteFile(RESTREAM_STREAMKEY_URL, output, error, nullptr, "application/json", "", nullptr, + headers, nullptr, 5); }; - ExecThreadedWithoutBlocking( - func, QTStr("Auth.LoadingChannel.Title"), - QTStr("Auth.LoadingChannel.Text").arg(service())); + ExecThreadedWithoutBlocking(func, QTStr("Auth.LoadingChannel.Title"), + QTStr("Auth.LoadingChannel.Text").arg(service())); if (!success || output.empty()) throw ErrorInfo("Failed to get stream key from remote", error); @@ -89,35 +87,29 @@ try { error = json["error"].string_value(); if (!error.empty()) - throw ErrorInfo(error, - json["error_description"].string_value()); + throw ErrorInfo(error, json["error_description"].string_value()); key_ = json["streamKey"].string_value(); return true; } catch (ErrorInfo info) { QString title = QTStr("Auth.ChannelFailure.Title"); - QString text = QTStr("Auth.ChannelFailure.Text") - .arg(service(), info.message.c_str(), - info.error.c_str()); + QString text = QTStr("Auth.ChannelFailure.Text").arg(service(), info.message.c_str(), info.error.c_str()); QMessageBox::warning(OBSBasic::Get(), title, text); - blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), - info.error.c_str()); + blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), info.error.c_str()); return false; } void RestreamAuth::SaveInternal() { OBSBasic *main = OBSBasic::Get(); - config_set_string(main->Config(), service(), "DockState", - main->saveState().toBase64().constData()); + config_set_string(main->Config(), service(), "DockState", main->saveState().toBase64().constData()); OAuthStreamKey::SaveInternal(); } -static inline std::string get_config_str(OBSBasic *main, const char *section, - const char *name) +static inline std::string get_config_str(OBSBasic *main, const char *section, const char *name) { const char *val = config_get_string(main->Config(), section, name); return val ? val : ""; @@ -209,10 +201,8 @@ void RestreamAuth::LoadUI() info->setVisible(true); channels->setVisible(true); } else { - const char *dockStateStr = config_get_string( - main->Config(), service(), "DockState"); - QByteArray dockState = - QByteArray::fromBase64(QByteArray(dockStateStr)); + const char *dockStateStr = config_get_string(main->Config(), service(), "DockState"); + QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); if (main->isVisible() || !main->isMaximized()) main->restoreState(dockState); @@ -229,14 +219,12 @@ bool RestreamAuth::RetryLogin() return false; } - std::shared_ptr auth = - std::make_shared(restreamDef); + std::shared_ptr auth = std::make_shared(restreamDef); std::string client_id = RESTREAM_CLIENTID; deobfuscate_str(&client_id[0], RESTREAM_HASH); - return GetToken(RESTREAM_TOKEN_URL, client_id, RESTREAM_SCOPE_VERSION, - QT_TO_UTF8(login.GetCode()), true); + return GetToken(RESTREAM_TOKEN_URL, client_id, RESTREAM_SCOPE_VERSION, QT_TO_UTF8(login.GetCode()), true); } std::shared_ptr RestreamAuth::Login(QWidget *parent, const std::string &) @@ -248,15 +236,12 @@ std::shared_ptr RestreamAuth::Login(QWidget *parent, const std::string &) return nullptr; } - std::shared_ptr auth = - std::make_shared(restreamDef); + std::shared_ptr auth = std::make_shared(restreamDef); std::string client_id = RESTREAM_CLIENTID; deobfuscate_str(&client_id[0], RESTREAM_HASH); - if (!auth->GetToken(RESTREAM_TOKEN_URL, client_id, - RESTREAM_SCOPE_VERSION, - QT_TO_UTF8(login.GetCode()))) { + if (!auth->GetToken(RESTREAM_TOKEN_URL, client_id, RESTREAM_SCOPE_VERSION, QT_TO_UTF8(login.GetCode()))) { return nullptr; } @@ -287,6 +272,5 @@ void RegisterRestreamAuth() return; #endif - OAuth::RegisterOAuth(restreamDef, CreateRestreamAuth, - RestreamAuth::Login, DeleteCookies); + OAuth::RegisterOAuth(restreamDef, CreateRestreamAuth, RestreamAuth::Login, DeleteCookies); } diff --git a/UI/auth-restream.hpp b/UI/auth-restream.hpp index 334906c42..16c77e813 100644 --- a/UI/auth-restream.hpp +++ b/UI/auth-restream.hpp @@ -22,6 +22,5 @@ public: RestreamAuth(const Def &d); ~RestreamAuth(); - static std::shared_ptr Login(QWidget *parent, - const std::string &service_name); + static std::shared_ptr Login(QWidget *parent, const std::string &service_name); }; diff --git a/UI/auth-twitch.cpp b/UI/auth-twitch.cpp index 7ec2bdd75..6ab5cce7b 100644 --- a/UI/auth-twitch.cpp +++ b/UI/auth-twitch.cpp @@ -41,17 +41,14 @@ TwitchAuth::TwitchAuth(const Def &d) : OAuthStreamKey(d) if (!cef) return; - cef->add_popup_whitelist_url( - "https://twitch.tv/popout/frankerfacez/chat?ffz-settings", - this); + cef->add_popup_whitelist_url("https://twitch.tv/popout/frankerfacez/chat?ffz-settings", this); /* enables javascript-based popups. basically bttv popups */ cef->add_popup_whitelist_url("about:blank#blocked", this); uiLoadTimer.setSingleShot(true); uiLoadTimer.setInterval(500); - connect(&uiLoadTimer, &QTimer::timeout, this, - &TwitchAuth::TryLoadSecondaryUIPanes); + connect(&uiLoadTimer, &QTimer::timeout, this, &TwitchAuth::TryLoadSecondaryUIPanes); } TwitchAuth::~TwitchAuth() @@ -86,19 +83,15 @@ bool TwitchAuth::MakeApiRequest(const char *path, Json &json_out) bool success = false; auto func = [&]() { - success = GetRemoteFile(url.c_str(), output, error, &error_code, - "application/json", "", nullptr, + success = GetRemoteFile(url.c_str(), output, error, &error_code, "application/json", "", nullptr, headers, nullptr, 5); }; - ExecThreadedWithoutBlocking( - func, QTStr("Auth.LoadingChannel.Title"), - QTStr("Auth.LoadingChannel.Text").arg(service())); + ExecThreadedWithoutBlocking(func, QTStr("Auth.LoadingChannel.Title"), + QTStr("Auth.LoadingChannel.Text").arg(service())); if (error_code == 403) { - OBSMessageBox::warning(OBSBasic::Get(), - Str("TwitchAuth.TwoFactorFail.Title"), - Str("TwitchAuth.TwoFactorFail.Text"), - true); + OBSMessageBox::warning(OBSBasic::Get(), Str("TwitchAuth.TwoFactorFail.Title"), + Str("TwitchAuth.TwoFactorFail.Text"), true); blog(LOG_WARNING, "%s: %s", __FUNCTION__, "Got 403 from Twitch, user probably does not " "have two-factor authentication enabled on " @@ -140,8 +133,7 @@ try { name = json["data"][0]["login"].string_value(); - std::string path = "streams/key?broadcaster_id=" + - json["data"][0]["id"].string_value(); + std::string path = "streams/key?broadcaster_id=" + json["data"][0]["id"].string_value(); success = MakeApiRequest(path.c_str(), json); if (!success) return false; @@ -151,14 +143,11 @@ try { return true; } catch (ErrorInfo info) { QString title = QTStr("Auth.ChannelFailure.Title"); - QString text = QTStr("Auth.ChannelFailure.Text") - .arg(service(), info.message.c_str(), - info.error.c_str()); + QString text = QTStr("Auth.ChannelFailure.Text").arg(service(), info.message.c_str(), info.error.c_str()); QMessageBox::warning(OBSBasic::Get(), title, text); - blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), - info.error.c_str()); + blog(LOG_WARNING, "%s: %s: %s", __FUNCTION__, info.message.c_str(), info.error.c_str()); return false; } @@ -169,14 +158,12 @@ void TwitchAuth::SaveInternal() config_set_string(main->Config(), service(), "UUID", uuid.c_str()); if (uiLoaded) { - config_set_string(main->Config(), service(), "DockState", - main->saveState().toBase64().constData()); + config_set_string(main->Config(), service(), "DockState", main->saveState().toBase64().constData()); } OAuthStreamKey::SaveInternal(); } -static inline std::string get_config_str(OBSBasic *main, const char *section, - const char *name) +static inline std::string get_config_str(OBSBasic *main, const char *section, const char *name) { const char *val = config_get_string(main->Config(), section, name); return val ? val : ""; @@ -268,8 +255,7 @@ void TwitchAuth::LoadUI() script = "localStorage.setItem('twilight.theme', 0);"; } - const int twAddonChoice = - config_get_int(main->Config(), service(), "AddonChoice"); + const int twAddonChoice = config_get_int(main->Config(), service(), "AddonChoice"); if (twAddonChoice) { if (twAddonChoice & 0x1) script += bttv_script; @@ -289,10 +275,8 @@ void TwitchAuth::LoadUI() if (firstLoad) { chat->setVisible(true); } else { - const char *dockStateStr = config_get_string( - main->Config(), service(), "DockState"); - QByteArray dockState = - QByteArray::fromBase64(QByteArray(dockStateStr)); + const char *dockStateStr = config_get_string(main->Config(), service(), "DockState"); + QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); if (main->isVisible() || !main->isMaximized()) main->restoreState(dockState); @@ -325,8 +309,7 @@ void TwitchAuth::LoadSecondaryUIPanes() script += "/dashboard/live"; script += referrer_script2; - const int twAddonChoice = - config_get_int(main->Config(), service(), "AddonChoice"); + const int twAddonChoice = config_get_int(main->Config(), service(), "AddonChoice"); if (twAddonChoice) { if (twAddonChoice & 0x1) script += bttv_script; @@ -410,17 +393,14 @@ void TwitchAuth::LoadSecondaryUIPanes() stats->setVisible(false); feed->setVisible(false); } else { - uint32_t lastVersion = config_get_int(App()->GetAppConfig(), - "General", "LastVersion"); + uint32_t lastVersion = config_get_int(App()->GetAppConfig(), "General", "LastVersion"); if (lastVersion <= MAKE_SEMANTIC_VERSION(23, 0, 2)) { feed->setVisible(false); } - const char *dockStateStr = config_get_string( - main->Config(), service(), "DockState"); - QByteArray dockState = - QByteArray::fromBase64(QByteArray(dockStateStr)); + const char *dockStateStr = config_get_string(main->Config(), service(), "DockState"); + QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); if (main->isVisible() || !main->isMaximized()) main->restoreState(dockState); @@ -449,13 +429,11 @@ void TwitchAuth::TryLoadSecondaryUIPanes() if (!found) { QMetaObject::invokeMethod(&this_->uiLoadTimer, "start"); } else { - QMetaObject::invokeMethod(this_, - "LoadSecondaryUIPanes"); + QMetaObject::invokeMethod(this_, "LoadSecondaryUIPanes"); } }; - panel_cookies->CheckForCookie("https://www.twitch.tv", "auth-token", - cb); + panel_cookies->CheckForCookie("https://www.twitch.tv", "auth-token", cb); } bool TwitchAuth::RetryLogin() @@ -465,13 +443,11 @@ bool TwitchAuth::RetryLogin() return false; } - std::shared_ptr auth = - std::make_shared(twitchDef); + std::shared_ptr auth = std::make_shared(twitchDef); std::string client_id = TWITCH_CLIENTID; deobfuscate_str(&client_id[0], TWITCH_HASH); - return GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION, - QT_TO_UTF8(login.GetCode()), true); + return GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION, QT_TO_UTF8(login.GetCode()), true); } std::shared_ptr TwitchAuth::Login(QWidget *parent, const std::string &) @@ -481,14 +457,12 @@ std::shared_ptr TwitchAuth::Login(QWidget *parent, const std::string &) return nullptr; } - std::shared_ptr auth = - std::make_shared(twitchDef); + std::shared_ptr auth = std::make_shared(twitchDef); std::string client_id = TWITCH_CLIENTID; deobfuscate_str(&client_id[0], TWITCH_HASH); - if (!auth->GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION, - QT_TO_UTF8(login.GetCode()))) { + if (!auth->GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION, QT_TO_UTF8(login.GetCode()))) { return nullptr; } @@ -517,6 +491,5 @@ void RegisterTwitchAuth() return; #endif - OAuth::RegisterOAuth(twitchDef, CreateTwitchAuth, TwitchAuth::Login, - DeleteCookies); + OAuth::RegisterOAuth(twitchDef, CreateTwitchAuth, TwitchAuth::Login, DeleteCookies); } diff --git a/UI/auth-twitch.hpp b/UI/auth-twitch.hpp index 21d964d2b..9fb3ba773 100644 --- a/UI/auth-twitch.hpp +++ b/UI/auth-twitch.hpp @@ -32,8 +32,7 @@ public: TwitchAuth(const Def &d); ~TwitchAuth(); - static std::shared_ptr Login(QWidget *parent, - const std::string &service_name); + static std::shared_ptr Login(QWidget *parent, const std::string &service_name); QTimer uiLoadTimer; diff --git a/UI/auth-youtube.cpp b/UI/auth-youtube.cpp index 2a2d2be34..48a55976c 100644 --- a/UI/auth-youtube.cpp +++ b/UI/auth-youtube.cpp @@ -37,15 +37,12 @@ using namespace json11; #define YOUTUBE_API_STATE_LENGTH 32 #define SECTION_NAME "YouTube" -#define YOUTUBE_CHAT_PLACEHOLDER_URL \ - "https://obsproject.com/placeholders/youtube-chat" -#define YOUTUBE_CHAT_POPOUT_URL \ - "https://www.youtube.com/live_chat?is_popout=1&dark_theme=1&v=%1" +#define YOUTUBE_CHAT_PLACEHOLDER_URL "https://obsproject.com/placeholders/youtube-chat" +#define YOUTUBE_CHAT_POPOUT_URL "https://www.youtube.com/live_chat?is_popout=1&dark_theme=1&v=%1" #define YOUTUBE_CHAT_DOCK_NAME "ytChat" -static const char allowedChars[] = - "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; +static const char allowedChars[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; static const int allowedCount = static_cast(sizeof(allowedChars) - 1); /* ------------------------------------------------------------------------- */ @@ -67,20 +64,12 @@ void RegisterYoutubeAuth() { for (auto &service : youtubeServices) { OAuth::RegisterOAuth( - service, - [service]() { - return std::make_shared( - service); - }, + service, [service]() { return std::make_shared(service); }, YoutubeAuth::Login, DeleteCookies); } } -YoutubeAuth::YoutubeAuth(const Def &d) - : OAuthStreamKey(d), - section(SECTION_NAME) -{ -} +YoutubeAuth::YoutubeAuth(const Def &d) : OAuthStreamKey(d), section(SECTION_NAME) {} YoutubeAuth::~YoutubeAuth() { @@ -103,21 +92,16 @@ bool YoutubeAuth::RetryLogin() void YoutubeAuth::SaveInternal() { OBSBasic *main = OBSBasic::Get(); - config_set_string(main->Config(), service(), "DockState", - main->saveState().toBase64().constData()); + config_set_string(main->Config(), service(), "DockState", main->saveState().toBase64().constData()); const char *section_name = section.c_str(); - config_set_string(main->Config(), section_name, "RefreshToken", - refresh_token.c_str()); + config_set_string(main->Config(), section_name, "RefreshToken", refresh_token.c_str()); config_set_string(main->Config(), section_name, "Token", token.c_str()); - config_set_uint(main->Config(), section_name, "ExpireTime", - expire_time); - config_set_int(main->Config(), section_name, "ScopeVer", - currentScopeVer); + config_set_uint(main->Config(), section_name, "ExpireTime", expire_time); + config_set_int(main->Config(), section_name, "ScopeVer", currentScopeVer); } -static inline std::string get_config_str(OBSBasic *main, const char *section, - const char *name) +static inline std::string get_config_str(OBSBasic *main, const char *section, const char *name) { const char *val = config_get_string(main->Config(), section, name); return val ? val : ""; @@ -130,10 +114,8 @@ bool YoutubeAuth::LoadInternal() const char *section_name = section.c_str(); refresh_token = get_config_str(main, section_name, "RefreshToken"); token = get_config_str(main, section_name, "Token"); - expire_time = - config_get_uint(main->Config(), section_name, "ExpireTime"); - currentScopeVer = - (int)config_get_int(main->Config(), section_name, "ScopeVer"); + expire_time = config_get_uint(main->Config(), section_name, "ExpireTime"); + currentScopeVer = (int)config_get_int(main->Config(), section_name, "ScopeVer"); firstLoad = false; return implicit ? !token.empty() : !refresh_token.empty(); } @@ -161,8 +143,7 @@ void YoutubeAuth::LoadUI() chat->setMinimumSize(200, 300); chat->setAllowedAreas(Qt::AllDockWidgetAreas); - browser = cef->create_widget(chat, YOUTUBE_CHAT_PLACEHOLDER_URL, - panel_cookies); + browser = cef->create_widget(chat, YOUTUBE_CHAT_PLACEHOLDER_URL, panel_cookies); chat->SetWidget(browser); main->AddDockWidget(chat, Qt::RightDockWidgetArea); @@ -178,10 +159,8 @@ void YoutubeAuth::LoadUI() main->NewYouTubeAppDock(); if (!firstLoad) { - const char *dockStateStr = config_get_string( - main->Config(), service(), "DockState"); - QByteArray dockState = - QByteArray::fromBase64(QByteArray(dockStateStr)); + const char *dockStateStr = config_get_string(main->Config(), service(), "DockState"); + QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); if (main->isVisible() || !main->isMaximized()) main->restoreState(dockState); @@ -190,8 +169,7 @@ void YoutubeAuth::LoadUI() uiLoaded = true; } -void YoutubeAuth::SetChatId(const QString &chat_id, - const std::string &api_chat_id) +void YoutubeAuth::SetChatId(const QString &chat_id, const std::string &api_chat_id) { #ifdef BROWSER_AVAILABLE QString chat_url = QString(YOUTUBE_CHAT_POPOUT_URL).arg(chat_id); @@ -239,23 +217,19 @@ QString YoutubeAuth::GenerateState() } // Static. -std::shared_ptr YoutubeAuth::Login(QWidget *owner, - const std::string &service) +std::shared_ptr YoutubeAuth::Login(QWidget *owner, const std::string &service) { QString auth_code; AuthListener server; auto it = std::find_if(youtubeServices.begin(), youtubeServices.end(), - [service](auto &item) { - return service == item.service; - }); + [service](auto &item) { return service == item.service; }); if (it == youtubeServices.end()) { return nullptr; } const auto auth = std::make_shared(*it); - QString redirect_uri = - QString("http://127.0.0.1:%1").arg(server.GetPort()); + QString redirect_uri = QString("http://127.0.0.1:%1").arg(server.GetPort()); QMessageBox dlg(owner); dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint); @@ -277,12 +251,10 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, url_template += "&redirect_uri=%3"; url_template += "&state=%4"; url_template += "&scope=https://www.googleapis.com/auth/youtube"; - QString url = url_template.arg(YOUTUBE_AUTH_URL, clientid.c_str(), - redirect_uri, state); + QString url = url_template.arg(YOUTUBE_AUTH_URL, clientid.c_str(), redirect_uri, state); QString text = QTStr("YouTube.Auth.WaitingAuth.Text"); - text = text.arg( - QString("Google OAuth Service").arg(url)); + text = text.arg(QString("Google OAuth Service").arg(url)); dlg.setText(text); dlg.setTextFormat(Qt::RichText); @@ -293,25 +265,22 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, dlg.setOption(QMessageBox::Option::DontUseNativeDialog); #endif - connect(&dlg, &QMessageBox::buttonClicked, &dlg, - [&](QAbstractButton *) { + connect(&dlg, &QMessageBox::buttonClicked, &dlg, [&](QAbstractButton *) { #ifdef _DEBUG - blog(LOG_DEBUG, "Action Cancelled."); + blog(LOG_DEBUG, "Action Cancelled."); #endif - // TODO: Stop server. - dlg.reject(); - }); + // TODO: Stop server. + dlg.reject(); + }); // Async Login. - connect(&server, &AuthListener::ok, &dlg, - [&dlg, &auth_code](QString code) { + connect(&server, &AuthListener::ok, &dlg, [&dlg, &auth_code](QString code) { #ifdef _DEBUG - blog(LOG_DEBUG, "Got youtube redirected answer: %s", - QT_TO_UTF8(code)); + blog(LOG_DEBUG, "Got youtube redirected answer: %s", QT_TO_UTF8(code)); #endif - auth_code = code; - dlg.accept(); - }); + auth_code = code; + dlg.accept(); + }); connect(&server, &AuthListener::fail, &dlg, [&dlg]() { #ifdef _DEBUG blog(LOG_DEBUG, "No access granted"); @@ -325,10 +294,8 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, QScopedPointer thread(CreateQThread(open_external_browser)); thread->start(); -#if defined(__APPLE__) && QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) && \ - QT_VERSION < QT_VERSION_CHECK(6, 6, 0) - const bool nativeDialogs = - qApp->testAttribute(Qt::AA_DontUseNativeDialogs); +#if defined(__APPLE__) && QT_VERSION >= QT_VERSION_CHECK(6, 5, 0) && QT_VERSION < QT_VERSION_CHECK(6, 6, 0) + const bool nativeDialogs = qApp->testAttribute(Qt::AA_DontUseNativeDialogs); App()->setAttribute(Qt::AA_DontUseNativeDialogs, true); dlg.exec(); App()->setAttribute(Qt::AA_DontUseNativeDialogs, nativeDialogs); @@ -336,12 +303,10 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, dlg.exec(); #endif - if (dlg.result() == QMessageBox::Cancel || - dlg.result() == QDialog::Rejected) + if (dlg.result() == QMessageBox::Cancel || dlg.result() == QDialog::Rejected) return nullptr; - if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret, - QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION, + if (!auth->GetToken(YOUTUBE_TOKEN_URL, clientid, secret, QT_TO_UTF8(redirect_uri), YOUTUBE_SCOPE_VERSION, QT_TO_UTF8(auth_code), true)) { return nullptr; } @@ -351,8 +316,7 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, ChannelDescription cd; if (auth->GetChannelDescription(cd)) - config_set_string(config, "YouTube", "ChannelName", - QT_TO_UTF8(cd.title)); + config_set_string(config, "YouTube", "ChannelName", QT_TO_UTF8(cd.title)); config_save_safe(config, "tmp", nullptr); return auth; @@ -373,10 +337,8 @@ YoutubeChatDock::YoutubeChatDock(const QString &title) : BrowserDock(title) chatLayout->addWidget(lineEdit, 1); chatLayout->addWidget(sendButton); - QWidget::connect(lineEdit, &LineEditAutoResize::returnPressed, this, - &YoutubeChatDock::SendChatMessage); - QWidget::connect(sendButton, &QPushButton::pressed, this, - &YoutubeChatDock::SendChatMessage); + QWidget::connect(lineEdit, &LineEditAutoResize::returnPressed, this, &YoutubeChatDock::SendChatMessage); + QWidget::connect(sendButton, &QPushButton::pressed, this, &YoutubeChatDock::SendChatMessage); } void YoutubeChatDock::SetWidget(QCefWidget *widget_) @@ -392,15 +354,13 @@ void YoutubeChatDock::SetWidget(QCefWidget *widget_) cefWidget.reset(widget_); - QWidget::connect(cefWidget.get(), &QCefWidget::urlChanged, this, - &YoutubeChatDock::YoutubeCookieCheck); + QWidget::connect(cefWidget.get(), &QCefWidget::urlChanged, this, &YoutubeChatDock::YoutubeCookieCheck); } void YoutubeChatDock::SetApiChatId(const std::string &id) { this->apiChatId = id; - QMetaObject::invokeMethod(this, "EnableChatInput", Qt::QueuedConnection, - Q_ARG(bool, !id.empty())); + QMetaObject::invokeMethod(this, "EnableChatInput", Qt::QueuedConnection, Q_ARG(bool, !id.empty())); } void YoutubeChatDock::YoutubeCookieCheck() @@ -409,25 +369,20 @@ void YoutubeChatDock::YoutubeCookieCheck() auto cb = [this_](bool currentlyLoggedIn) { bool previouslyLoggedIn = this_->isLoggedIn; this_->isLoggedIn = currentlyLoggedIn; - bool loginStateChanged = - (currentlyLoggedIn && !previouslyLoggedIn) || - (!currentlyLoggedIn && previouslyLoggedIn); + bool loginStateChanged = (currentlyLoggedIn && !previouslyLoggedIn) || + (!currentlyLoggedIn && previouslyLoggedIn); if (loginStateChanged) { - QMetaObject::invokeMethod( - this_, "EnableChatInput", Qt::QueuedConnection, - Q_ARG(bool, !currentlyLoggedIn)); + QMetaObject::invokeMethod(this_, "EnableChatInput", Qt::QueuedConnection, + Q_ARG(bool, !currentlyLoggedIn)); OBSBasic *main = OBSBasic::Get(); if (main->GetYouTubeAppDock() != nullptr) { - QMetaObject::invokeMethod( - main->GetYouTubeAppDock(), - "SettingsUpdated", Qt::QueuedConnection, - Q_ARG(bool, !currentlyLoggedIn)); + QMetaObject::invokeMethod(main->GetYouTubeAppDock(), "SettingsUpdated", + Qt::QueuedConnection, Q_ARG(bool, !currentlyLoggedIn)); } } }; if (panel_cookies) { - panel_cookies->CheckForCookie("https://www.youtube.com", "SID", - cb); + panel_cookies->CheckForCookie("https://www.youtube.com", "SID", cb); } } @@ -438,31 +393,26 @@ void YoutubeChatDock::SendChatMessage() return; OBSBasic *main = OBSBasic::Get(); - YoutubeApiWrappers *apiYouTube( - dynamic_cast(main->GetAuth())); + YoutubeApiWrappers *apiYouTube(dynamic_cast(main->GetAuth())); ExecuteFuncSafeBlock([&]() { lineEdit->setText(""); - lineEdit->setPlaceholderText( - QTStr("YouTube.Chat.Input.Sending")); + lineEdit->setPlaceholderText(QTStr("YouTube.Chat.Input.Sending")); if (apiYouTube->SendChatMessage(apiChatId, message)) { os_sleep_ms(3000); } else { QString error = apiYouTube->GetLastError(); apiYouTube->GetTranslatedError(error); - QMetaObject::invokeMethod( - this, "ShowErrorMessage", Qt::QueuedConnection, - Q_ARG(const QString &, error)); + QMetaObject::invokeMethod(this, "ShowErrorMessage", Qt::QueuedConnection, + Q_ARG(const QString &, error)); } - lineEdit->setPlaceholderText( - QTStr("YouTube.Chat.Input.Placeholder")); + lineEdit->setPlaceholderText(QTStr("YouTube.Chat.Input.Placeholder")); }); } void YoutubeChatDock::ShowErrorMessage(const QString &error) { - QMessageBox::warning(this, QTStr("YouTube.Chat.Error.Title"), - QTStr("YouTube.Chat.Error.Text").arg(error)); + QMessageBox::warning(this, QTStr("YouTube.Chat.Error.Title"), QTStr("YouTube.Chat.Error.Text").arg(error)); } void YoutubeChatDock::EnableChatInput(bool visible) diff --git a/UI/auth-youtube.hpp b/UI/auth-youtube.hpp index 61dcfafaf..4552875d6 100644 --- a/UI/auth-youtube.hpp +++ b/UI/auth-youtube.hpp @@ -34,10 +34,9 @@ private slots: }; #endif -inline const std::vector youtubeServices = { - {"YouTube - RTMP", Auth::Type::OAuth_LinkedAccount, true, true}, - {"YouTube - RTMPS", Auth::Type::OAuth_LinkedAccount, true, true}, - {"YouTube - HLS", Auth::Type::OAuth_LinkedAccount, true, true}}; +inline const std::vector youtubeServices = {{"YouTube - RTMP", Auth::Type::OAuth_LinkedAccount, true, true}, + {"YouTube - RTMPS", Auth::Type::OAuth_LinkedAccount, true, true}, + {"YouTube - HLS", Auth::Type::OAuth_LinkedAccount, true, true}}; class YoutubeAuth : public OAuthStreamKey { Q_OBJECT @@ -64,6 +63,5 @@ public: void ResetChat(); void ReloadChat(); - static std::shared_ptr Login(QWidget *parent, - const std::string &service); + static std::shared_ptr Login(QWidget *parent, const std::string &service); }; diff --git a/UI/basic-controls.cpp b/UI/basic-controls.cpp index 075ae344f..fe9483136 100644 --- a/UI/basic-controls.cpp +++ b/UI/basic-controls.cpp @@ -2,80 +2,61 @@ #include "window-basic-main.hpp" -OBSBasicControls::OBSBasicControls(OBSBasic *main) - : QFrame(nullptr), - ui(new Ui::OBSBasicControls) +OBSBasicControls::OBSBasicControls(OBSBasic *main) : QFrame(nullptr), ui(new Ui::OBSBasicControls) { /* Create UI elements */ ui->setupUi(this); streamButtonMenu.reset(new QMenu()); - startStreamAction = - streamButtonMenu->addAction(QTStr("Basic.Main.StartStreaming")); - stopStreamAction = - streamButtonMenu->addAction(QTStr("Basic.Main.StopStreaming")); - QAction *forceStopStreamAction = streamButtonMenu->addAction( - QTStr("Basic.Main.ForceStopStreaming")); + startStreamAction = streamButtonMenu->addAction(QTStr("Basic.Main.StartStreaming")); + stopStreamAction = streamButtonMenu->addAction(QTStr("Basic.Main.StopStreaming")); + QAction *forceStopStreamAction = streamButtonMenu->addAction(QTStr("Basic.Main.ForceStopStreaming")); /* Transfer buttons signals as OBSBasicControls signals */ connect( - ui->streamButton, &QPushButton::clicked, this, - [this]() { emit this->StreamButtonClicked(); }, + ui->streamButton, &QPushButton::clicked, this, [this]() { emit this->StreamButtonClicked(); }, Qt::DirectConnection); connect( - ui->broadcastButton, &QPushButton::clicked, this, - [this]() { emit this->BroadcastButtonClicked(); }, + ui->broadcastButton, &QPushButton::clicked, this, [this]() { emit this->BroadcastButtonClicked(); }, Qt::DirectConnection); connect( - ui->recordButton, &QPushButton::clicked, this, - [this]() { emit this->RecordButtonClicked(); }, + ui->recordButton, &QPushButton::clicked, this, [this]() { emit this->RecordButtonClicked(); }, Qt::DirectConnection); connect( - ui->pauseRecordButton, &QPushButton::clicked, this, - [this]() { emit this->PauseRecordButtonClicked(); }, + ui->pauseRecordButton, &QPushButton::clicked, this, [this]() { emit this->PauseRecordButtonClicked(); }, Qt::DirectConnection); connect( ui->replayBufferButton, &QPushButton::clicked, this, - [this]() { emit this->ReplayBufferButtonClicked(); }, - Qt::DirectConnection); + [this]() { emit this->ReplayBufferButtonClicked(); }, Qt::DirectConnection); connect( ui->saveReplayButton, &QPushButton::clicked, this, - [this]() { emit this->SaveReplayBufferButtonClicked(); }, - Qt::DirectConnection); + [this]() { emit this->SaveReplayBufferButtonClicked(); }, Qt::DirectConnection); connect( - ui->virtualCamButton, &QPushButton::clicked, this, - [this]() { emit this->VirtualCamButtonClicked(); }, + ui->virtualCamButton, &QPushButton::clicked, this, [this]() { emit this->VirtualCamButtonClicked(); }, Qt::DirectConnection); connect( ui->virtualCamConfigButton, &QPushButton::clicked, this, - [this]() { emit this->VirtualCamConfigButtonClicked(); }, + [this]() { emit this->VirtualCamConfigButtonClicked(); }, Qt::DirectConnection); + connect( + ui->modeSwitch, &QPushButton::clicked, this, [this]() { emit this->StudioModeButtonClicked(); }, Qt::DirectConnection); connect( - ui->modeSwitch, &QPushButton::clicked, this, - [this]() { emit this->StudioModeButtonClicked(); }, + ui->settingsButton, &QPushButton::clicked, this, [this]() { emit this->SettingsButtonClicked(); }, Qt::DirectConnection); connect( - ui->settingsButton, &QPushButton::clicked, this, - [this]() { emit this->SettingsButtonClicked(); }, - Qt::DirectConnection); - connect( - ui->exitButton, &QPushButton::clicked, this, - [this]() { emit this->ExitButtonClicked(); }, + ui->exitButton, &QPushButton::clicked, this, [this]() { emit this->ExitButtonClicked(); }, Qt::DirectConnection); /* Transfer menu actions signals as OBSBasicControls signals */ connect( startStreamAction.get(), &QAction::triggered, this, - [this]() { emit this->StartStreamMenuActionClicked(); }, - Qt::DirectConnection); + [this]() { emit this->StartStreamMenuActionClicked(); }, Qt::DirectConnection); connect( stopStreamAction.get(), &QAction::triggered, this, - [this]() { emit this->StopStreamMenuActionClicked(); }, - Qt::DirectConnection); + [this]() { emit this->StopStreamMenuActionClicked(); }, Qt::DirectConnection); connect( forceStopStreamAction, &QAction::triggered, this, - [this]() { emit this->ForceStopStreamMenuActionClicked(); }, - Qt::DirectConnection); + [this]() { emit this->ForceStopStreamMenuActionClicked(); }, Qt::DirectConnection); /* Set up default visibilty */ ui->broadcastButton->setVisible(false); @@ -86,57 +67,35 @@ OBSBasicControls::OBSBasicControls(OBSBasic *main) ui->virtualCamConfigButton->setVisible(false); /* Set up state update connections */ - connect(main, &OBSBasic::StreamingPreparing, this, - &OBSBasicControls::StreamingPreparing); - connect(main, &OBSBasic::StreamingStarting, this, - &OBSBasicControls::StreamingStarting); - connect(main, &OBSBasic::StreamingStarted, this, - &OBSBasicControls::StreamingStarted); - connect(main, &OBSBasic::StreamingStopping, this, - &OBSBasicControls::StreamingStopping); - connect(main, &OBSBasic::StreamingStopped, this, - &OBSBasicControls::StreamingStopped); + connect(main, &OBSBasic::StreamingPreparing, this, &OBSBasicControls::StreamingPreparing); + connect(main, &OBSBasic::StreamingStarting, this, &OBSBasicControls::StreamingStarting); + connect(main, &OBSBasic::StreamingStarted, this, &OBSBasicControls::StreamingStarted); + connect(main, &OBSBasic::StreamingStopping, this, &OBSBasicControls::StreamingStopping); + connect(main, &OBSBasic::StreamingStopped, this, &OBSBasicControls::StreamingStopped); - connect(main, &OBSBasic::BroadcastStreamReady, this, - &OBSBasicControls::BroadcastStreamReady); - connect(main, &OBSBasic::BroadcastStreamActive, this, - &OBSBasicControls::BroadcastStreamActive); - connect(main, &OBSBasic::BroadcastStreamStarted, this, - &OBSBasicControls::BroadcastStreamStarted); + connect(main, &OBSBasic::BroadcastStreamReady, this, &OBSBasicControls::BroadcastStreamReady); + connect(main, &OBSBasic::BroadcastStreamActive, this, &OBSBasicControls::BroadcastStreamActive); + connect(main, &OBSBasic::BroadcastStreamStarted, this, &OBSBasicControls::BroadcastStreamStarted); - connect(main, &OBSBasic::RecordingStarted, this, - &OBSBasicControls::RecordingStarted); - connect(main, &OBSBasic::RecordingPaused, this, - &OBSBasicControls::RecordingPaused); - connect(main, &OBSBasic::RecordingUnpaused, this, - &OBSBasicControls::RecordingUnpaused); - connect(main, &OBSBasic::RecordingStopping, this, - &OBSBasicControls::RecordingStopping); - connect(main, &OBSBasic::RecordingStopped, this, - &OBSBasicControls::RecordingStopped); + connect(main, &OBSBasic::RecordingStarted, this, &OBSBasicControls::RecordingStarted); + connect(main, &OBSBasic::RecordingPaused, this, &OBSBasicControls::RecordingPaused); + connect(main, &OBSBasic::RecordingUnpaused, this, &OBSBasicControls::RecordingUnpaused); + connect(main, &OBSBasic::RecordingStopping, this, &OBSBasicControls::RecordingStopping); + connect(main, &OBSBasic::RecordingStopped, this, &OBSBasicControls::RecordingStopped); - connect(main, &OBSBasic::ReplayBufStarted, this, - &OBSBasicControls::ReplayBufferStarted); - connect(main, &OBSBasic::ReplayBufStopping, this, - &OBSBasicControls::ReplayBufferStopping); - connect(main, &OBSBasic::ReplayBufStopped, this, - &OBSBasicControls::ReplayBufferStopped); + connect(main, &OBSBasic::ReplayBufStarted, this, &OBSBasicControls::ReplayBufferStarted); + connect(main, &OBSBasic::ReplayBufStopping, this, &OBSBasicControls::ReplayBufferStopping); + connect(main, &OBSBasic::ReplayBufStopped, this, &OBSBasicControls::ReplayBufferStopped); - connect(main, &OBSBasic::VirtualCamStarted, this, - &OBSBasicControls::VirtualCamStarted); - connect(main, &OBSBasic::VirtualCamStopped, this, - &OBSBasicControls::VirtualCamStopped); + connect(main, &OBSBasic::VirtualCamStarted, this, &OBSBasicControls::VirtualCamStarted); + connect(main, &OBSBasic::VirtualCamStopped, this, &OBSBasicControls::VirtualCamStopped); - connect(main, &OBSBasic::PreviewProgramModeChanged, this, - &OBSBasicControls::UpdateStudioModeState); + connect(main, &OBSBasic::PreviewProgramModeChanged, this, &OBSBasicControls::UpdateStudioModeState); /* Set up enablement connection */ - connect(main, &OBSBasic::BroadcastFlowEnabled, this, - &OBSBasicControls::EnableBroadcastFlow); - connect(main, &OBSBasic::ReplayBufEnabled, this, - &OBSBasicControls::EnableReplayBufferButtons); - connect(main, &OBSBasic::VirtualCamEnabled, this, - &OBSBasicControls::EnableVirtualCamButtons); + connect(main, &OBSBasic::BroadcastFlowEnabled, this, &OBSBasicControls::EnableBroadcastFlow); + connect(main, &OBSBasic::ReplayBufEnabled, this, &OBSBasicControls::EnableReplayBufferButtons); + connect(main, &OBSBasic::VirtualCamEnabled, this, &OBSBasicControls::EnableVirtualCamButtons); } void OBSBasicControls::StreamingPreparing() @@ -153,8 +112,7 @@ void OBSBasicControls::StreamingStarting(bool broadcastAutoStart) // well, we need to disable button while stream is not active ui->broadcastButton->setEnabled(false); - ui->broadcastButton->setText( - QTStr("Basic.Main.StartBroadcast")); + ui->broadcastButton->setText(QTStr("Basic.Main.StartBroadcast")); ui->broadcastButton->setProperty("broadcastState", "ready"); ui->broadcastButton->style()->unpolish(ui->broadcastButton); @@ -209,9 +167,7 @@ void OBSBasicControls::BroadcastStreamActive() void OBSBasicControls::BroadcastStreamStarted(bool autoStop) { - ui->broadcastButton->setText( - QTStr(autoStop ? "Basic.Main.AutoStopEnabled" - : "Basic.Main.StopBroadcast")); + ui->broadcastButton->setText(QTStr(autoStop ? "Basic.Main.AutoStopEnabled" : "Basic.Main.StopBroadcast")); if (autoStop) ui->broadcastButton->setEnabled(false); @@ -276,8 +232,7 @@ void OBSBasicControls::ReplayBufferStarted() void OBSBasicControls::ReplayBufferStopping() { - ui->replayBufferButton->setText( - QTStr("Basic.Main.StoppingReplayBuffer")); + ui->replayBufferButton->setText(QTStr("Basic.Main.StoppingReplayBuffer")); } void OBSBasicControls::ReplayBufferStopped() diff --git a/UI/context-bar-controls.cpp b/UI/context-bar-controls.cpp index 3bd08d1ac..c45d06976 100644 --- a/UI/context-bar-controls.cpp +++ b/UI/context-bar-controls.cpp @@ -56,16 +56,12 @@ void SourceToolbar::SetUndoProperties(obs_source_t *source, bool repeatable) if (!currentSceneSource) return; std::string scene_uuid = obs_source_get_uuid(currentSceneSource); - auto undo_redo = [scene_uuid = std::move(scene_uuid), - main](const std::string &data) { - OBSDataAutoRelease settings = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(settings, "undo_suuid")); + auto undo_redo = [scene_uuid = std::move(scene_uuid), main](const std::string &data) { + OBSDataAutoRelease settings = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(settings, "undo_suuid")); obs_source_reset_settings(source, settings); - OBSSourceAutoRelease scene_source = - obs_get_source_by_uuid(scene_uuid.c_str()); + OBSSourceAutoRelease scene_source = obs_get_source_by_uuid(scene_uuid.c_str()); main->SetCurrentScene(scene_source.Get(), true); main->UpdateContextBar(); @@ -74,17 +70,14 @@ void SourceToolbar::SetUndoProperties(obs_source_t *source, bool repeatable) OBSDataAutoRelease new_settings = obs_data_create(); OBSDataAutoRelease curr_settings = obs_source_get_settings(source); obs_data_apply(new_settings, curr_settings); - obs_data_set_string(new_settings, "undo_suuid", - obs_source_get_uuid(source)); + obs_data_set_string(new_settings, "undo_suuid", obs_source_get_uuid(source)); std::string undo_data(obs_data_get_json(oldData)); std::string redo_data(obs_data_get_json(new_settings)); if (undo_data.compare(redo_data) != 0) - main->undo_s.add_action( - QTStr("Undo.Properties") - .arg(obs_source_get_name(source)), - undo_redo, undo_redo, undo_data, redo_data, repeatable); + main->undo_s.add_action(QTStr("Undo.Properties").arg(obs_source_get_name(source)), undo_redo, undo_redo, + undo_data, redo_data, repeatable); oldData = nullptr; } @@ -122,8 +115,7 @@ ComboSelectToolbar::ComboSelectToolbar(QWidget *parent, OBSSource source) ComboSelectToolbar::~ComboSelectToolbar() {} -static int FillPropertyCombo(QComboBox *c, obs_property_t *p, - const std::string &cur_id, bool is_int = false) +static int FillPropertyCombo(QComboBox *c, obs_property_t *p, const std::string &cur_id, bool is_int = false) { size_t count = obs_property_list_item_count(p); int cur_idx = -1; @@ -148,8 +140,7 @@ static int FillPropertyCombo(QComboBox *c, obs_property_t *p, return cur_idx; } -void UpdateSourceComboToolbarProperties(QComboBox *combo, OBSSource source, - obs_properties_t *props, +void UpdateSourceComboToolbarProperties(QComboBox *combo, OBSSource source, obs_properties_t *props, const char *prop_name, bool is_int) { std::string cur_id; @@ -168,9 +159,7 @@ void UpdateSourceComboToolbarProperties(QComboBox *combo, OBSSource source, if (cur_idx == -1 || obs_property_list_item_disabled(p, cur_idx)) { if (cur_idx == -1) { - combo->insertItem( - 0, - QTStr("Basic.Settings.Audio.UnknownAudioDevice")); + combo->insertItem(0, QTStr("Basic.Settings.Audio.UnknownAudioDevice")); cur_idx = 0; } @@ -188,12 +177,10 @@ void ComboSelectToolbar::Init() return; } - UpdateSourceComboToolbarProperties(ui->device, source, props.get(), - prop_name, is_int); + UpdateSourceComboToolbarProperties(ui->device, source, props.get(), prop_name, is_int); } -void UpdateSourceComboToolbarValue(QComboBox *combo, OBSSource source, int idx, - const char *prop_name, bool is_int) +void UpdateSourceComboToolbarValue(QComboBox *combo, OBSSource source, int idx, const char *prop_name, bool is_int) { QString id = combo->itemData(idx).toString(); @@ -214,28 +201,22 @@ void ComboSelectToolbar::on_device_currentIndexChanged(int idx) } SaveOldProperties(source); - UpdateSourceComboToolbarValue(ui->device, source, idx, prop_name, - is_int); + UpdateSourceComboToolbarValue(ui->device, source, idx, prop_name, is_int); SetUndoProperties(source); } -AudioCaptureToolbar::AudioCaptureToolbar(QWidget *parent, OBSSource source) - : ComboSelectToolbar(parent, source) -{ -} +AudioCaptureToolbar::AudioCaptureToolbar(QWidget *parent, OBSSource source) : ComboSelectToolbar(parent, source) {} void AudioCaptureToolbar::Init() { delete ui->activateButton; ui->activateButton = nullptr; - obs_module_t *mod = - get_os_module("win-wasapi", "mac-capture", "linux-pulseaudio"); + obs_module_t *mod = get_os_module("win-wasapi", "mac-capture", "linux-pulseaudio"); if (!mod) return; - const char *device_str = - get_os_text(mod, "Device", "CoreAudio.Device", "Device"); + const char *device_str = get_os_text(mod, "Device", "CoreAudio.Device", "Device"); ui->deviceLabel->setText(device_str); prop_name = "device_id"; @@ -243,23 +224,18 @@ void AudioCaptureToolbar::Init() ComboSelectToolbar::Init(); } -WindowCaptureToolbar::WindowCaptureToolbar(QWidget *parent, OBSSource source) - : ComboSelectToolbar(parent, source) -{ -} +WindowCaptureToolbar::WindowCaptureToolbar(QWidget *parent, OBSSource source) : ComboSelectToolbar(parent, source) {} void WindowCaptureToolbar::Init() { delete ui->activateButton; ui->activateButton = nullptr; - obs_module_t *mod = - get_os_module("win-capture", "mac-capture", "linux-capture"); + obs_module_t *mod = get_os_module("win-capture", "mac-capture", "linux-capture"); if (!mod) return; - const char *device_str = get_os_text(mod, "WindowCapture.Window", - "WindowUtils.Window", "Window"); + const char *device_str = get_os_text(mod, "WindowCapture.Window", "WindowUtils.Window", "Window"); ui->deviceLabel->setText(device_str); #if !defined(_WIN32) && !defined(__APPLE__) //linux @@ -275,8 +251,7 @@ void WindowCaptureToolbar::Init() ComboSelectToolbar::Init(); } -ApplicationAudioCaptureToolbar::ApplicationAudioCaptureToolbar(QWidget *parent, - OBSSource source) +ApplicationAudioCaptureToolbar::ApplicationAudioCaptureToolbar(QWidget *parent, OBSSource source) : ComboSelectToolbar(parent, source) { } @@ -295,23 +270,18 @@ void ApplicationAudioCaptureToolbar::Init() ComboSelectToolbar::Init(); } -DisplayCaptureToolbar::DisplayCaptureToolbar(QWidget *parent, OBSSource source) - : ComboSelectToolbar(parent, source) -{ -} +DisplayCaptureToolbar::DisplayCaptureToolbar(QWidget *parent, OBSSource source) : ComboSelectToolbar(parent, source) {} void DisplayCaptureToolbar::Init() { delete ui->activateButton; ui->activateButton = nullptr; - obs_module_t *mod = - get_os_module("win-capture", "mac-capture", "linux-capture"); + obs_module_t *mod = get_os_module("win-capture", "mac-capture", "linux-capture"); if (!mod) return; - const char *device_str = - get_os_text(mod, "Monitor", "DisplayCapture.Display", "Screen"); + const char *device_str = get_os_text(mod, "Monitor", "DisplayCapture.Display", "Screen"); ui->deviceLabel->setText(device_str); #ifdef _WIN32 @@ -399,8 +369,7 @@ GameCaptureToolbar::GameCaptureToolbar(QWidget *parent, OBSSource source) return; ui->modeLabel->setText(obs_module_get_locale_text(mod, "Mode")); - ui->windowLabel->setText( - obs_module_get_locale_text(mod, "WindowCapture.Window")); + ui->windowLabel->setText(obs_module_get_locale_text(mod, "WindowCapture.Window")); OBSDataAutoRelease settings = obs_source_get_settings(source); std::string cur_mode = obs_data_get_string(settings, "capture_mode"); @@ -522,8 +491,7 @@ void ImageSourceToolbar::on_browse_clicked() static inline QColor color_from_int(long long val) { - return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, - (val >> 24) & 0xff); + return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff); } static inline long long color_to_int(QColor color) @@ -532,8 +500,7 @@ static inline long long color_to_int(QColor color) return ((val & 0xff) << shift); }; - return shift(color.red(), 0) | shift(color.green(), 8) | - shift(color.blue(), 16) | shift(color.alpha(), 24); + return shift(color.red(), 0) | shift(color.green(), 8) | shift(color.blue(), 16) | shift(color.alpha(), 24); } ColorSourceToolbar::ColorSourceToolbar(QWidget *parent, OBSSource source) @@ -557,12 +524,9 @@ void ColorSourceToolbar::UpdateColor() ui->color->setFrameStyle(QFrame::Sunken | QFrame::Panel); ui->color->setText(color.name(QColor::HexRgb)); ui->color->setPalette(palette); - ui->color->setStyleSheet( - QString("background-color :%1; color: %2;") - .arg(palette.color(QPalette::Window) - .name(QColor::HexRgb)) - .arg(palette.color(QPalette::WindowText) - .name(QColor::HexRgb))); + ui->color->setStyleSheet(QString("background-color :%1; color: %2;") + .arg(palette.color(QPalette::Window).name(QColor::HexRgb)) + .arg(palette.color(QPalette::WindowText).name(QColor::HexRgb))); ui->color->setAutoFillBackground(true); ui->color->setAlignment(Qt::AlignCenter); } @@ -616,25 +580,20 @@ TextSourceToolbar::TextSourceToolbar(QWidget *parent, OBSSource source) const char *id = obs_source_get_unversioned_id(source); bool ft2 = strcmp(id, "text_ft2_source") == 0; - bool read_from_file = obs_data_get_bool( - settings, ft2 ? "from_file" : "read_from_file"); + bool read_from_file = obs_data_get_bool(settings, ft2 ? "from_file" : "read_from_file"); OBSDataAutoRelease font_obj = obs_data_get_obj(settings, "font"); MakeQFont(font_obj, font); // Use "color1" if it's a freetype source and "color" elsewise unsigned int val = (unsigned int)obs_data_get_int( - settings, - (strncmp(obs_source_get_id(source), "text_ft2_source", 15) == 0) - ? "color1" - : "color"); + settings, (strncmp(obs_source_get_id(source), "text_ft2_source", 15) == 0) ? "color1" : "color"); color = color_from_int(val); const char *text = obs_data_get_string(settings, "text"); - bool single_line = !read_from_file && - (!text || (strchr(text, '\n') == nullptr)); + bool single_line = !read_from_file && (!text || (strchr(text, '\n') == nullptr)); ui->emptySpace->setVisible(!single_line); ui->text->setVisible(single_line); if (single_line) @@ -658,10 +617,8 @@ void TextSourceToolbar::on_selectFont_clicked() options = QFontDialog::DontUseNativeDialog; #endif - font = QFontDialog::getFont( - &success, font, this, - QTStr("Basic.PropertiesWindow.SelectFont.WindowTitle"), - options); + font = QFontDialog::getFont(&success, font, this, QTStr("Basic.PropertiesWindow.SelectFont.WindowTitle"), + options); if (!success) { return; } @@ -695,11 +652,9 @@ void TextSourceToolbar::on_selectColor_clicked() return; } - bool freetype = - strncmp(obs_source_get_id(source), "text_ft2_source", 15) == 0; + bool freetype = strncmp(obs_source_get_id(source), "text_ft2_source", 15) == 0; - obs_property_t *p = - obs_properties_get(props.get(), freetype ? "color1" : "color"); + obs_property_t *p = obs_properties_get(props.get(), freetype ? "color1" : "color"); const char *desc = obs_property_description(p); diff --git a/UI/context-bar-controls.hpp b/UI/context-bar-controls.hpp index 48c743afb..acf88a5fb 100644 --- a/UI/context-bar-controls.hpp +++ b/UI/context-bar-controls.hpp @@ -18,8 +18,7 @@ class SourceToolbar : public QWidget { protected: using properties_delete_t = decltype(&obs_properties_destroy); - using properties_t = - std::unique_ptr; + using properties_t = std::unique_ptr; properties_t props; OBSDataAutoRelease oldData; diff --git a/UI/display-helpers.hpp b/UI/display-helpers.hpp index 19f85c194..586cbfeb6 100644 --- a/UI/display-helpers.hpp +++ b/UI/display-helpers.hpp @@ -20,8 +20,7 @@ #include #include -static inline void GetScaleAndCenterPos(int baseCX, int baseCY, int windowCX, - int windowCY, int &x, int &y, +static inline void GetScaleAndCenterPos(int baseCX, int baseCY, int windowCX, int windowCY, int &x, int &y, float &scale) { double windowAspect, baseAspect; @@ -44,9 +43,8 @@ static inline void GetScaleAndCenterPos(int baseCX, int baseCY, int windowCX, y = windowCY / 2 - newCY / 2; } -static inline void GetCenterPosFromFixedScale(int baseCX, int baseCY, - int windowCX, int windowCY, - int &x, int &y, float scale) +static inline void GetCenterPosFromFixedScale(int baseCX, int baseCY, int windowCX, int windowCY, int &x, int &y, + float scale) { x = (float(windowCX) - float(baseCX) * scale) / 2.0f; y = (float(windowCY) - float(baseCY) * scale) / 2.0f; @@ -65,12 +63,9 @@ static inline QSize GetPixelSize(QWidget *widget) #define GRAPHICS_SAFE_PERCENT 0.05f // 5.0% #define FOURBYTHREE_SAFE_PERCENT 0.1625f // 16.25% -static inline void InitSafeAreas(gs_vertbuffer_t **actionSafeMargin, - gs_vertbuffer_t **graphicsSafeMargin, - gs_vertbuffer_t **fourByThreeSafeMargin, - gs_vertbuffer_t **leftLine, - gs_vertbuffer_t **topLine, - gs_vertbuffer_t **rightLine) +static inline void InitSafeAreas(gs_vertbuffer_t **actionSafeMargin, gs_vertbuffer_t **graphicsSafeMargin, + gs_vertbuffer_t **fourByThreeSafeMargin, gs_vertbuffer_t **leftLine, + gs_vertbuffer_t **topLine, gs_vertbuffer_t **rightLine) { obs_enter_graphics(); diff --git a/UI/ffmpeg-utils.cpp b/UI/ffmpeg-utils.cpp index a55e2e9a8..88e9b0eab 100644 --- a/UI/ffmpeg-utils.cpp +++ b/UI/ffmpeg-utils.cpp @@ -26,8 +26,7 @@ extern "C" { using namespace std; -vector GetFormatCodecs(const FFmpegFormat &format, - bool ignore_compatibility) +vector GetFormatCodecs(const FFmpegFormat &format, bool ignore_compatibility) { vector codecs; const AVCodec *codec; @@ -38,8 +37,7 @@ vector GetFormatCodecs(const FFmpegFormat &format, if (!av_codec_is_encoder(codec)) continue; // Skip if not supported and compatibility check not disabled - if (!ignore_compatibility && - !av_codec_get_tag(format.codec_tags, codec->id)) { + if (!ignore_compatibility && !av_codec_get_tag(format.codec_tags, codec->id)) { continue; } @@ -82,8 +80,7 @@ vector GetSupportedFormats() FFmpegCodec FFmpegFormat::GetDefaultEncoder(FFmpegCodecType codec_type) const { - const AVCodecID codec_id = codec_type == VIDEO ? video_codec - : audio_codec; + const AVCodecID codec_id = codec_type == VIDEO ? video_codec : audio_codec; if (codec_type == UNKNOWN || codec_id == AV_CODEC_ID_NONE) return {}; @@ -100,23 +97,19 @@ bool FFCodecAndFormatCompatible(const char *codec, const char *format) if (!codec || !format) return false; - const AVOutputFormat *output_format = - av_guess_format(format, nullptr, nullptr); + const AVOutputFormat *output_format = av_guess_format(format, nullptr, nullptr); if (!output_format) return false; - const AVCodecDescriptor *codec_desc = - avcodec_descriptor_get_by_name(codec); + const AVCodecDescriptor *codec_desc = avcodec_descriptor_get_by_name(codec); if (!codec_desc) return false; - return avformat_query_codec(output_format, codec_desc->id, - FF_COMPLIANCE_NORMAL) == 1; + return avformat_query_codec(output_format, codec_desc->id, FF_COMPLIANCE_NORMAL) == 1; } static const unordered_set builtin_codecs = { - "h264", "hevc", "av1", "prores", "aac", "opus", - "alac", "flac", "pcm_s16le", "pcm_s24le", "pcm_f32le", + "h264", "hevc", "av1", "prores", "aac", "opus", "alac", "flac", "pcm_s16le", "pcm_s24le", "pcm_f32le", }; bool IsBuiltinCodec(const char *codec) diff --git a/UI/ffmpeg-utils.hpp b/UI/ffmpeg-utils.hpp index c6e23ffce..4a0ef5eba 100644 --- a/UI/ffmpeg-utils.hpp +++ b/UI/ffmpeg-utils.hpp @@ -114,10 +114,7 @@ struct FFmpegCodec { { } - FFmpegCodec(const AVCodec *codec) - : name(codec->name), - long_name(codec->long_name), - id(codec->id) + FFmpegCodec(const AVCodec *codec) : name(codec->name), long_name(codec->long_name), id(codec->id) { switch (codec->type) { case AVMEDIA_TYPE_AUDIO: @@ -142,10 +139,8 @@ struct FFmpegCodec { Q_DECLARE_METATYPE(FFmpegCodec) std::vector GetSupportedFormats(); -std::vector GetFormatCodecs(const FFmpegFormat &format, - bool ignore_compatibility); +std::vector GetFormatCodecs(const FFmpegFormat &format, bool ignore_compatibility); bool FFCodecAndFormatCompatible(const char *codec, const char *format); bool IsBuiltinCodec(const char *codec); -bool ContainerSupportsCodec(const std::string &container, - const std::string &codec); +bool ContainerSupportsCodec(const std::string &container, const std::string &codec); diff --git a/UI/focus-list.cpp b/UI/focus-list.cpp index bfa48f349..d5148b3a1 100644 --- a/UI/focus-list.cpp +++ b/UI/focus-list.cpp @@ -15,8 +15,7 @@ void FocusList::dragMoveEvent(QDragMoveEvent *event) QPoint pos = event->position().toPoint(); int itemRow = row(itemAt(pos)); - if ((itemRow == currentRow() + 1) || - (currentRow() == count() - 1 && itemRow == -1)) + if ((itemRow == currentRow() + 1) || (currentRow() == count() - 1 && itemRow == -1)) event->ignore(); else QListWidget::dragMoveEvent(event); diff --git a/UI/frontend-plugins/aja-output-ui/AJAOutputUI.cpp b/UI/frontend-plugins/aja-output-ui/AJAOutputUI.cpp index fdb820be4..d457067d6 100644 --- a/UI/frontend-plugins/aja-output-ui/AJAOutputUI.cpp +++ b/UI/frontend-plugins/aja-output-ui/AJAOutputUI.cpp @@ -46,46 +46,36 @@ void AJAOutputUI::SetupPropertiesView() obs_data_apply(settings, data); } else { // apply default settings - obs_data_set_default_int( - settings, kUIPropOutput.id, - static_cast(IOSelection::Invalid)); - obs_data_set_default_int( - settings, kUIPropVideoFormatSelect.id, - static_cast(kDefaultAJAVideoFormat)); - obs_data_set_default_int( - settings, kUIPropPixelFormatSelect.id, - static_cast(kDefaultAJAPixelFormat)); - obs_data_set_default_int( - settings, kUIPropSDITransport.id, - static_cast(kDefaultAJASDITransport)); - obs_data_set_default_int( - settings, kUIPropSDITransport4K.id, - static_cast(kDefaultAJASDITransport4K)); + obs_data_set_default_int(settings, kUIPropOutput.id, static_cast(IOSelection::Invalid)); + obs_data_set_default_int(settings, kUIPropVideoFormatSelect.id, + static_cast(kDefaultAJAVideoFormat)); + obs_data_set_default_int(settings, kUIPropPixelFormatSelect.id, + static_cast(kDefaultAJAPixelFormat)); + obs_data_set_default_int(settings, kUIPropSDITransport.id, + static_cast(kDefaultAJASDITransport)); + obs_data_set_default_int(settings, kUIPropSDITransport4K.id, + static_cast(kDefaultAJASDITransport4K)); } // Assign an ID to the program output plugin instance for channel usage tracking obs_data_set_string(settings, kUIPropAJAOutputID.id, kProgramOutputID); - propertiesView = new OBSPropertiesView( - settings, "aja_output", - (PropertiesReloadCallback)obs_get_output_properties, 170); + propertiesView = + new OBSPropertiesView(settings, "aja_output", (PropertiesReloadCallback)obs_get_output_properties, 170); ui->propertiesLayout->addWidget(propertiesView); obs_data_release(settings); - connect(propertiesView, &OBSPropertiesView::Changed, this, - &AJAOutputUI::PropertiesChanged); + connect(propertiesView, &OBSPropertiesView::Changed, this, &AJAOutputUI::PropertiesChanged); } void AJAOutputUI::SaveSettings(const char *filename, obs_data_t *settings) { - BPtr modulePath = - obs_module_get_config_path(obs_current_module(), ""); + BPtr modulePath = obs_module_get_config_path(obs_current_module(), ""); os_mkdirs(modulePath); - BPtr path = - obs_module_get_config_path(obs_current_module(), filename); + BPtr path = obs_module_get_config_path(obs_current_module(), filename); if (settings) obs_data_save_json_safe(settings, path, "tmp", "bak"); @@ -103,35 +93,27 @@ void AJAOutputUI::SetupPreviewPropertiesView() obs_data_apply(settings, data); } else { // apply default settings - obs_data_set_default_int( - settings, kUIPropOutput.id, - static_cast(IOSelection::Invalid)); - obs_data_set_default_int( - settings, kUIPropVideoFormatSelect.id, - static_cast(kDefaultAJAVideoFormat)); - obs_data_set_default_int( - settings, kUIPropPixelFormatSelect.id, - static_cast(kDefaultAJAPixelFormat)); - obs_data_set_default_int( - settings, kUIPropSDITransport.id, - static_cast(kDefaultAJASDITransport)); - obs_data_set_default_int( - settings, kUIPropSDITransport4K.id, - static_cast(kDefaultAJASDITransport4K)); + obs_data_set_default_int(settings, kUIPropOutput.id, static_cast(IOSelection::Invalid)); + obs_data_set_default_int(settings, kUIPropVideoFormatSelect.id, + static_cast(kDefaultAJAVideoFormat)); + obs_data_set_default_int(settings, kUIPropPixelFormatSelect.id, + static_cast(kDefaultAJAPixelFormat)); + obs_data_set_default_int(settings, kUIPropSDITransport.id, + static_cast(kDefaultAJASDITransport)); + obs_data_set_default_int(settings, kUIPropSDITransport4K.id, + static_cast(kDefaultAJASDITransport4K)); } // Assign an ID to the program output plugin instance for channel usage tracking obs_data_set_string(settings, kUIPropAJAOutputID.id, kPreviewOutputID); - previewPropertiesView = new OBSPropertiesView( - settings, "aja_output", - (PropertiesReloadCallback)obs_get_output_properties, 170); + previewPropertiesView = + new OBSPropertiesView(settings, "aja_output", (PropertiesReloadCallback)obs_get_output_properties, 170); ui->previewPropertiesLayout->addWidget(previewPropertiesView); obs_data_release(settings); - connect(previewPropertiesView, &OBSPropertiesView::Changed, this, - &AJAOutputUI::PreviewPropertiesChanged); + connect(previewPropertiesView, &OBSPropertiesView::Changed, this, &AJAOutputUI::PreviewPropertiesChanged); } void AJAOutputUI::on_outputButton_clicked() @@ -160,15 +142,13 @@ void AJAOutputUI::OutputStateChanged(bool active) void AJAOutputUI::on_previewOutputButton_clicked() { - SaveSettings(kPreviewPropsFilename, - previewPropertiesView->GetSettings()); + SaveSettings(kPreviewPropsFilename, previewPropertiesView->GetSettings()); preview_output_toggle(); } void AJAOutputUI::PreviewPropertiesChanged() { - SaveSettings(kPreviewPropsFilename, - previewPropertiesView->GetSettings()); + SaveSettings(kPreviewPropsFilename, previewPropertiesView->GetSettings()); } void AJAOutputUI::PreviewOutputStateChanged(bool active) @@ -205,15 +185,13 @@ static obs_properties_t *create_misc_props_ui(void *vp) } obs_properties_t *props = obs_properties_create(); - obs_property_t *deviceList = obs_properties_add_list( - props, kUIPropDevice.id, obs_module_text(kUIPropDevice.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_t *multiViewEnable = obs_properties_add_bool( - props, kUIPropMultiViewEnable.id, - obs_module_text(kUIPropMultiViewEnable.text)); + obs_property_t *deviceList = obs_properties_add_list(props, kUIPropDevice.id, + obs_module_text(kUIPropDevice.text), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); + obs_property_t *multiViewEnable = + obs_properties_add_bool(props, kUIPropMultiViewEnable.id, obs_module_text(kUIPropMultiViewEnable.text)); obs_property_t *multiViewAudioSources = obs_properties_add_list( - props, kUIPropMultiViewAudioSource.id, - obs_module_text(kUIPropMultiViewAudioSource.text), + props, kUIPropMultiViewAudioSource.id, obs_module_text(kUIPropMultiViewAudioSource.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_clear(deviceList); @@ -222,12 +200,9 @@ static obs_properties_t *create_misc_props_ui(void *vp) NTV2DeviceID firstDeviceID = DEVICE_ID_NOTFOUND; populate_misc_device_list(deviceList, cardManager, firstDeviceID); populate_multi_view_audio_sources(multiViewAudioSources, firstDeviceID); - obs_property_set_modified_callback2(deviceList, on_misc_device_selected, - cardManager); - obs_property_set_modified_callback2(multiViewEnable, - on_multi_view_toggle, cardManager); - obs_property_set_modified_callback2(multiViewAudioSources, - on_multi_view_toggle, cardManager); + obs_property_set_modified_callback2(deviceList, on_misc_device_selected, cardManager); + obs_property_set_modified_callback2(multiViewEnable, on_multi_view_toggle, cardManager); + obs_property_set_modified_callback2(multiViewAudioSources, on_multi_view_toggle, cardManager); outputUI->ui->label_3->setVisible(haveMultiView); obs_property_set_visible(deviceList, haveMultiView); @@ -263,12 +238,10 @@ void AJAOutputUI::SetupMiscPropertiesView() obs_data_apply(settings, data); } - miscPropertiesView = new OBSPropertiesView( - settings, this, (PropertiesReloadCallback)create_misc_props_ui, - nullptr, nullptr, 170); + miscPropertiesView = new OBSPropertiesView(settings, this, (PropertiesReloadCallback)create_misc_props_ui, + nullptr, nullptr, 170); ui->miscPropertiesLayout->addWidget(miscPropertiesView); obs_data_release(settings); - connect(miscPropertiesView, &OBSPropertiesView::Changed, this, - &AJAOutputUI::MiscPropertiesChanged); + connect(miscPropertiesView, &OBSPropertiesView::Changed, this, &AJAOutputUI::MiscPropertiesChanged); } diff --git a/UI/frontend-plugins/aja-output-ui/aja-ui-main.cpp b/UI/frontend-plugins/aja-output-ui/aja-ui-main.cpp index 7d34f6e35..a1eb58e10 100644 --- a/UI/frontend-plugins/aja-output-ui/aja-ui-main.cpp +++ b/UI/frontend-plugins/aja-output-ui/aja-ui-main.cpp @@ -43,8 +43,7 @@ static struct preview_output context = {0}; OBSData load_settings(const char *filename) { - BPtr path = - obs_module_get_config_path(obs_current_module(), filename); + BPtr path = obs_module_get_config_path(obs_current_module(), filename); BPtr jsonData = os_quick_read_utf8_file(path); if (!!jsonData) { obs_data_t *data = obs_data_create_from_json(jsonData); @@ -70,8 +69,7 @@ void output_start() OBSData settings = load_settings(kProgramPropsFilename); if (settings != nullptr) { - output = obs_output_create("aja_output", kProgramOutputID, - settings, NULL); + output = obs_output_create("aja_output", kProgramOutputID, settings, NULL); bool started = obs_output_start(output); obs_data_release(settings); @@ -122,8 +120,7 @@ void preview_output_start() OBSData settings = load_settings(kPreviewPropsFilename); if (settings != nullptr) { - context.output = obs_output_create( - "aja_output", kPreviewOutputID, settings, NULL); + context.output = obs_output_create("aja_output", kPreviewOutputID, settings, NULL); obs_get_video_info(&context.ovi); @@ -132,12 +129,10 @@ void preview_output_start() obs_enter_graphics(); context.texrender = gs_texrender_create(GS_BGRA, GS_ZS_NONE); - context.stagesurface = - gs_stagesurface_create(width, height, GS_BGRA); + context.stagesurface = gs_stagesurface_create(width, height, GS_BGRA); obs_leave_graphics(); - const video_output_info *mainVOI = - video_output_get_info(obs_get_video()); + const video_output_info *mainVOI = video_output_get_info(obs_get_video()); video_output_info vi = {0}; vi.format = VIDEO_FORMAT_BGRA; @@ -152,19 +147,15 @@ void preview_output_start() video_output_open(&context.video_queue, &vi); - obs_frontend_add_event_callback(on_preview_scene_changed, - &context); + obs_frontend_add_event_callback(on_preview_scene_changed, &context); if (obs_frontend_preview_program_mode_active()) { - context.current_source = - obs_frontend_get_current_preview_scene(); + context.current_source = obs_frontend_get_current_preview_scene(); } else { - context.current_source = - obs_frontend_get_current_scene(); + context.current_source = obs_frontend_get_current_scene(); } obs_add_main_render_callback(render_preview_source, &context); - obs_output_set_media(context.output, context.video_queue, - obs_get_audio()); + obs_output_set_media(context.output, context.video_queue, obs_get_audio()); bool started = obs_output_start(context.output); obs_data_release(settings); @@ -185,18 +176,15 @@ void preview_output_toggle() preview_output_start(); } -void populate_misc_device_list(obs_property_t *list, - aja::CardManager *cardManager, - NTV2DeviceID &firstDeviceID) +void populate_misc_device_list(obs_property_t *list, aja::CardManager *cardManager, NTV2DeviceID &firstDeviceID) { for (const auto &iter : *cardManager) { if (!iter.second) continue; if (firstDeviceID == DEVICE_ID_NOTFOUND) firstDeviceID = iter.second->GetDeviceID(); - obs_property_list_add_string( - list, iter.second->GetDisplayName().c_str(), - iter.second->GetCardID().c_str()); + obs_property_list_add_string(list, iter.second->GetDisplayName().c_str(), + iter.second->GetCardID().c_str()); } } @@ -211,16 +199,13 @@ void populate_multi_view_audio_sources(obs_property_t *list, NTV2DeviceID id) }; for (const auto &inp : kMultiViewAudioInputs) { if (NTV2DeviceCanDoInputSource(id, inp)) { - std::string inputSourceStr = - NTV2InputSourceToString(inp, true); - obs_property_list_add_int(list, inputSourceStr.c_str(), - (long long)inp); + std::string inputSourceStr = NTV2InputSourceToString(inp, true); + obs_property_list_add_int(list, inputSourceStr.c_str(), (long long)inp); } } } -bool on_misc_device_selected(void *data, obs_properties_t *props, - obs_property_t *, obs_data_t *settings) +bool on_misc_device_selected(void *data, obs_properties_t *props, obs_property_t *, obs_data_t *settings) { const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); if (!cardID || !cardID[0]) @@ -234,10 +219,8 @@ bool on_misc_device_selected(void *data, obs_properties_t *props, NTV2DeviceID deviceID = cardEntry->GetDeviceID(); bool enableMultiViewUI = NTV2DeviceCanDoHDMIMultiView(deviceID); - obs_property_t *multiViewCheckbox = - obs_properties_get(props, kUIPropMultiViewEnable.id); - obs_property_t *multiViewAudioSource = - obs_properties_get(props, kUIPropMultiViewAudioSource.id); + obs_property_t *multiViewCheckbox = obs_properties_get(props, kUIPropMultiViewEnable.id); + obs_property_t *multiViewAudioSource = obs_properties_get(props, kUIPropMultiViewAudioSource.id); populate_multi_view_audio_sources(multiViewAudioSource, deviceID); obs_property_set_enabled(multiViewCheckbox, enableMultiViewUI); obs_property_set_enabled(multiViewAudioSource, enableMultiViewUI); @@ -249,8 +232,7 @@ static void toggle_multi_view(CNTV2Card *card, NTV2InputSource src, bool enable) std::ostringstream oss; for (int i = 0; i < 4; i++) { std::string datastream = std::to_string(i); - oss << "sdi[" << datastream << "][0]->hdmi[0][" << datastream - << "];"; + oss << "sdi[" << datastream << "][0]->hdmi[0][" << datastream << "];"; } NTV2DeviceID deviceId = card->GetDeviceID(); @@ -262,29 +244,19 @@ static void toggle_multi_view(CNTV2Card *card, NTV2InputSource src, bool enable) if (enable) { card->ApplySignalRoute(cnx, false); if (NTV2DeviceCanDoAudioMixer(deviceId)) { - card->SetAudioMixerInputAudioSystem( - NTV2_AudioMixerInputMain, - audioSys); - card->SetAudioMixerInputChannelSelect( - NTV2_AudioMixerInputMain, - NTV2_AudioChannel1_2); - card->SetAudioMixerInputChannelsMute( - NTV2_AudioMixerInputAux1, - NTV2AudioChannelsMuteAll); - card->SetAudioMixerInputChannelsMute( - NTV2_AudioMixerInputAux2, - NTV2AudioChannelsMuteAll); + card->SetAudioMixerInputAudioSystem(NTV2_AudioMixerInputMain, audioSys); + card->SetAudioMixerInputChannelSelect(NTV2_AudioMixerInputMain, + NTV2_AudioChannel1_2); + card->SetAudioMixerInputChannelsMute(NTV2_AudioMixerInputAux1, + NTV2AudioChannelsMuteAll); + card->SetAudioMixerInputChannelsMute(NTV2_AudioMixerInputAux2, + NTV2AudioChannelsMuteAll); } - card->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_ON, - audioSys); - card->SetAudioOutputMonitorSource( - NTV2_AudioChannel1_2, audioSys); - card->SetHDMIOutAudioChannels( - NTV2_HDMIAudio8Channels); - card->SetHDMIOutAudioSource2Channel( - NTV2_AudioChannel1_2, audioSys); - card->SetHDMIOutAudioSource8Channel( - NTV2_AudioChannel1_8, audioSys); + card->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_ON, audioSys); + card->SetAudioOutputMonitorSource(NTV2_AudioChannel1_2, audioSys); + card->SetHDMIOutAudioChannels(NTV2_HDMIAudio8Channels); + card->SetHDMIOutAudioSource2Channel(NTV2_AudioChannel1_2, audioSys); + card->SetHDMIOutAudioSource8Channel(NTV2_AudioChannel1_8, audioSys); } else { card->RemoveConnections(cnx); } @@ -292,14 +264,11 @@ static void toggle_multi_view(CNTV2Card *card, NTV2InputSource src, bool enable) } } -bool on_multi_view_toggle(void *data, obs_properties_t *, obs_property_t *, - obs_data_t *settings) +bool on_multi_view_toggle(void *data, obs_properties_t *, obs_property_t *, obs_data_t *settings) { - bool multiViewEnabled = - obs_data_get_bool(settings, kUIPropMultiViewEnable.id) && - !main_output_running && !preview_output_running; - const int audioInputSource = - obs_data_get_int(settings, kUIPropMultiViewAudioSource.id); + bool multiViewEnabled = obs_data_get_bool(settings, kUIPropMultiViewEnable.id) && !main_output_running && + !preview_output_running; + const int audioInputSource = obs_data_get_int(settings, kUIPropMultiViewAudioSource.id); const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); if (!cardID || !cardID[0]) return false; @@ -359,8 +328,7 @@ void render_preview_source(void *param, uint32_t, uint32_t) vec4_zero(&background); gs_clear(GS_CLEAR_COLOR, &background, 0.0f, 0); - gs_ortho(0.0f, (float)width, 0.0f, (float)height, -100.0f, - 100.0f); + gs_ortho(0.0f, (float)width, 0.0f, (float)height, -100.0f, 100.0f); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO); @@ -371,24 +339,15 @@ void render_preview_source(void *param, uint32_t, uint32_t) gs_texrender_end(ctx->texrender); struct video_frame output_frame; - if (video_output_lock_frame(ctx->video_queue, &output_frame, 1, - os_gettime_ns())) { - gs_stage_texture( - ctx->stagesurface, - gs_texrender_get_texture(ctx->texrender)); + if (video_output_lock_frame(ctx->video_queue, &output_frame, 1, os_gettime_ns())) { + gs_stage_texture(ctx->stagesurface, gs_texrender_get_texture(ctx->texrender)); - if (gs_stagesurface_map(ctx->stagesurface, - &ctx->video_data, - &ctx->video_linesize)) { + if (gs_stagesurface_map(ctx->stagesurface, &ctx->video_data, &ctx->video_linesize)) { uint32_t linesize = output_frame.linesize[0]; - for (uint32_t i = 0; i < ctx->ovi.base_height; - i++) { + for (uint32_t i = 0; i < ctx->ovi.base_height; i++) { uint32_t dst_offset = linesize * i; - uint32_t src_offset = - ctx->video_linesize * i; - memcpy(output_frame.data[0] + - dst_offset, - ctx->video_data + src_offset, + uint32_t src_offset = ctx->video_linesize * i; + memcpy(output_frame.data[0] + dst_offset, ctx->video_data + src_offset, linesize); } @@ -403,8 +362,7 @@ void render_preview_source(void *param, uint32_t, uint32_t) void addOutputUI(void) { - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - "AJA I/O Device Output"); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction("AJA I/O Device Output"); QMainWindow *window = (QMainWindow *)obs_frontend_get_main_window(); @@ -423,20 +381,16 @@ static void OBSEvent(enum obs_frontend_event event, void *) { if (event == OBS_FRONTEND_EVENT_FINISHED_LOADING) { OBSData settings = load_settings(kProgramPropsFilename); - if (settings && - obs_data_get_bool(settings, kUIPropAutoStartOutput.id)) + if (settings && obs_data_get_bool(settings, kUIPropAutoStartOutput.id)) output_start(); OBSData previewSettings = load_settings(kPreviewPropsFilename); - if (previewSettings && - obs_data_get_bool(previewSettings, - kUIPropAutoStartOutput.id)) + if (previewSettings && obs_data_get_bool(previewSettings, kUIPropAutoStartOutput.id)) preview_output_start(); OBSData miscSettings = load_settings(kMiscPropsFilename); if (miscSettings && ajaOutputUI) { - on_multi_view_toggle(ajaOutputUI->GetCardManager(), - nullptr, nullptr, miscSettings); + on_multi_view_toggle(ajaOutputUI->GetCardManager(), nullptr, nullptr, miscSettings); } } else if (event == OBS_FRONTEND_EVENT_EXIT) { if (main_output_running) @@ -459,16 +413,14 @@ bool obs_module_load(void) CNTV2DeviceScanner scanner; auto numDevices = scanner.GetNumDevices(); if (numDevices == 0) { - blog(LOG_WARNING, - "No AJA devices found, skipping loading AJA UI plugin"); + blog(LOG_WARNING, "No AJA devices found, skipping loading AJA UI plugin"); return false; } // Signal to wait for AJA plugin to finish loading so we can access the CardManager instance auto signal_handler = obs_get_signal_handler(); signal_handler_add(signal_handler, "void aja_loaded(ptr card_manager)"); - signal_handler_connect(signal_handler, "aja_loaded", aja_loaded, - nullptr); + signal_handler_connect(signal_handler, "aja_loaded", aja_loaded, nullptr); addOutputUI(); diff --git a/UI/frontend-plugins/aja-output-ui/aja-ui-main.h b/UI/frontend-plugins/aja-output-ui/aja-ui-main.h index 2cc78e57e..f9348fc05 100644 --- a/UI/frontend-plugins/aja-output-ui/aja-ui-main.h +++ b/UI/frontend-plugins/aja-output-ui/aja-ui-main.h @@ -14,11 +14,7 @@ static const char *kMiscPropsFilename = "ajaMiscProps.json"; OBSData load_settings(const char *filename); void output_toggle(); void preview_output_toggle(); -void populate_misc_device_list(obs_property_t *list, - aja::CardManager *cardManager, - NTV2DeviceID &firstDeviceID); +void populate_misc_device_list(obs_property_t *list, aja::CardManager *cardManager, NTV2DeviceID &firstDeviceID); void populate_multi_view_audio_sources(obs_property_t *list, NTV2DeviceID id); -bool on_misc_device_selected(void *data, obs_properties_t *props, - obs_property_t *list, obs_data_t *settings); -bool on_multi_view_toggle(void *data, obs_properties_t *props, - obs_property_t *list, obs_data_t *settings); +bool on_misc_device_selected(void *data, obs_properties_t *props, obs_property_t *list, obs_data_t *settings); +bool on_multi_view_toggle(void *data, obs_properties_t *props, obs_property_t *list, obs_data_t *settings); diff --git a/UI/frontend-plugins/decklink-captions/decklink-captions.cpp b/UI/frontend-plugins/decklink-captions/decklink-captions.cpp index afd274b21..f853c3518 100644 --- a/UI/frontend-plugins/decklink-captions/decklink-captions.cpp +++ b/UI/frontend-plugins/decklink-captions/decklink-captions.cpp @@ -22,9 +22,7 @@ obs_captions::obs_captions() {} static obs_captions *captions = nullptr; -DecklinkCaptionsUI::DecklinkCaptionsUI(QWidget *parent) - : QDialog(parent), - ui(new Ui_CaptionsDialog) +DecklinkCaptionsUI::DecklinkCaptionsUI(QWidget *parent) : QDialog(parent), ui(new Ui_CaptionsDialog) { ui->setupUi(this); @@ -50,11 +48,7 @@ DecklinkCaptionsUI::DecklinkCaptionsUI(QWidget *parent) ui->source->blockSignals(true); ui->source->addItem(QStringLiteral("")); ui->source->setCurrentIndex(0); - obs_enum_sources( - [](void *data, obs_source_t *source) { - return (*static_cast(data))(source); - }, - &cb); + obs_enum_sources([](void *data, obs_source_t *source) { return (*static_cast(data))(source); }, &cb); ui->source->blockSignals(false); } @@ -68,13 +62,11 @@ void DecklinkCaptionsUI::on_source_currentIndexChanged(int) captions->start(); } -static void caption_callback(void * /* param */, obs_source_t * /* source */, - const struct obs_source_cea_708 *captions) +static void caption_callback(void * /* param */, obs_source_t * /* source */, const struct obs_source_cea_708 *captions) { obs_output *output = obs_frontend_get_streaming_output(); if (output) { - if (obs_frontend_streaming_active() && - obs_output_active(output)) { + if (obs_frontend_streaming_active() && obs_output_active(output)) { obs_output_caption(output, captions); } obs_output_release(output); @@ -95,32 +87,27 @@ void obs_captions::stop() { OBSSource s = OBSGetStrongRef(source); if (s) - obs_source_remove_caption_callback(s, caption_callback, - nullptr); + obs_source_remove_caption_callback(s, caption_callback, nullptr); } -static void save_decklink_caption_data(obs_data_t *save_data, bool saving, - void *) +static void save_decklink_caption_data(obs_data_t *save_data, bool saving, void *) { if (saving) { obs_data_t *obj = obs_data_create(); - obs_data_set_string(obj, "source", - captions->source_name.c_str()); + obs_data_set_string(obj, "source", captions->source_name.c_str()); obs_data_set_obj(save_data, "decklink_captions", obj); obs_data_release(obj); } else { captions->stop(); - obs_data_t *obj = - obs_data_get_obj(save_data, "decklink_captions"); + obs_data_t *obj = obs_data_get_obj(save_data, "decklink_captions"); if (!obj) obj = obs_data_create(); captions->source_name = obs_data_get_string(obj, "source"); - captions->source = - GetWeakSourceByName(captions->source_name.c_str()); + captions->source = GetWeakSourceByName(captions->source_name.c_str()); obs_data_release(obj); captions->start(); @@ -129,8 +116,7 @@ static void save_decklink_caption_data(obs_data_t *save_data, bool saving, void addOutputUI(void) { - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - obs_module_text("Decklink Captions")); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("Decklink Captions")); captions = new obs_captions; diff --git a/UI/frontend-plugins/decklink-output-ui/DecklinkOutputUI.cpp b/UI/frontend-plugins/decklink-output-ui/DecklinkOutputUI.cpp index 9ab99953f..6738b9af0 100644 --- a/UI/frontend-plugins/decklink-output-ui/DecklinkOutputUI.cpp +++ b/UI/frontend-plugins/decklink-output-ui/DecklinkOutputUI.cpp @@ -4,9 +4,7 @@ #include #include "decklink-ui-main.h" -DecklinkOutputUI::DecklinkOutputUI(QWidget *parent) - : QDialog(parent), - ui(new Ui_Output) +DecklinkOutputUI::DecklinkOutputUI(QWidget *parent) : QDialog(parent), ui(new Ui_Output) { ui->setupUi(this); @@ -37,26 +35,22 @@ void DecklinkOutputUI::SetupPropertiesView() if (data) obs_data_apply(settings, data); - propertiesView = new OBSPropertiesView( - settings, "decklink_output", - (PropertiesReloadCallback)obs_get_output_properties, 170); + propertiesView = new OBSPropertiesView(settings, "decklink_output", + (PropertiesReloadCallback)obs_get_output_properties, 170); ui->propertiesLayout->addWidget(propertiesView); obs_data_release(settings); - connect(propertiesView, &OBSPropertiesView::Changed, this, - &DecklinkOutputUI::PropertiesChanged); + connect(propertiesView, &OBSPropertiesView::Changed, this, &DecklinkOutputUI::PropertiesChanged); } void DecklinkOutputUI::SaveSettings() { - BPtr modulePath = - obs_module_get_config_path(obs_current_module(), ""); + BPtr modulePath = obs_module_get_config_path(obs_current_module(), ""); os_mkdirs(modulePath); - BPtr path = obs_module_get_config_path( - obs_current_module(), "decklinkOutputProps.json"); + BPtr path = obs_module_get_config_path(obs_current_module(), "decklinkOutputProps.json"); obs_data_t *settings = propertiesView->GetSettings(); if (settings) @@ -74,26 +68,22 @@ void DecklinkOutputUI::SetupPreviewPropertiesView() if (data) obs_data_apply(settings, data); - previewPropertiesView = new OBSPropertiesView( - settings, "decklink_output", - (PropertiesReloadCallback)obs_get_output_properties, 170); + previewPropertiesView = new OBSPropertiesView(settings, "decklink_output", + (PropertiesReloadCallback)obs_get_output_properties, 170); ui->previewPropertiesLayout->addWidget(previewPropertiesView); obs_data_release(settings); - connect(previewPropertiesView, &OBSPropertiesView::Changed, this, - &DecklinkOutputUI::PreviewPropertiesChanged); + connect(previewPropertiesView, &OBSPropertiesView::Changed, this, &DecklinkOutputUI::PreviewPropertiesChanged); } void DecklinkOutputUI::SavePreviewSettings() { - BPtr modulePath = - obs_module_get_config_path(obs_current_module(), ""); + BPtr modulePath = obs_module_get_config_path(obs_current_module(), ""); os_mkdirs(modulePath); - BPtr path = obs_module_get_config_path( - obs_current_module(), "decklinkPreviewOutputProps.json"); + BPtr path = obs_module_get_config_path(obs_current_module(), "decklinkPreviewOutputProps.json"); obs_data_t *settings = previewPropertiesView->GetSettings(); if (settings) diff --git a/UI/frontend-plugins/decklink-output-ui/decklink-ui-main.cpp b/UI/frontend-plugins/decklink-output-ui/decklink-ui-main.cpp index c1923edae..9c6bd23d8 100644 --- a/UI/frontend-plugins/decklink-output-ui/decklink-ui-main.cpp +++ b/UI/frontend-plugins/decklink-output-ui/decklink-ui-main.cpp @@ -43,8 +43,7 @@ static struct decklink_ui_output context_preview = {0}; OBSData load_settings() { - BPtr path = obs_module_get_config_path( - obs_current_module(), "decklinkOutputProps.json"); + BPtr path = obs_module_get_config_path(obs_current_module(), "decklinkOutputProps.json"); BPtr jsonData = os_quick_read_utf8_file(path); if (!!jsonData) { obs_data_t *data = obs_data_create_from_json(jsonData); @@ -90,10 +89,8 @@ void output_start() OBSData settings = load_settings(); if (settings != nullptr) { - obs_output_t *const output = obs_output_create( - "decklink_output", "decklink_output", settings, NULL); - const struct video_scale_info *const conversion = - obs_output_get_video_conversion(output); + obs_output_t *const output = obs_output_create("decklink_output", "decklink_output", settings, NULL); + const struct video_scale_info *const conversion = obs_output_get_video_conversion(output); if (conversion != nullptr) { context.output = output; obs_add_tick_callback(decklink_ui_tick, &context); @@ -105,11 +102,9 @@ void output_start() obs_enter_graphics(); context.texrender_premultiplied = nullptr; - context.texrender = - gs_texrender_create(GS_BGRA, GS_ZS_NONE); + context.texrender = gs_texrender_create(GS_BGRA, GS_ZS_NONE); for (gs_stagesurf_t *&surf : context.stagesurfaces) - surf = gs_stagesurface_create(width, height, - GS_BGRA); + surf = gs_stagesurface_create(width, height, GS_BGRA); obs_leave_graphics(); for (bool &written : context.surf_written) @@ -131,12 +126,9 @@ void output_start() video_output_open(&context.video_queue, &vi); context.current_source = nullptr; - obs_add_main_rendered_callback(decklink_ui_render, - &context); + obs_add_main_rendered_callback(decklink_ui_render, &context); - obs_output_set_media(context.output, - context.video_queue, - obs_get_audio()); + obs_output_set_media(context.output, context.video_queue, obs_get_audio()); bool started = obs_output_start(context.output); main_output_running = started; @@ -162,8 +154,7 @@ void output_toggle() OBSData load_preview_settings() { - BPtr path = obs_module_get_config_path( - obs_current_module(), "decklinkPreviewOutputProps.json"); + BPtr path = obs_module_get_config_path(obs_current_module(), "decklinkPreviewOutputProps.json"); BPtr jsonData = os_quick_read_utf8_file(path); if (!!jsonData) { obs_data_t *data = obs_data_create_from_json(jsonData); @@ -191,8 +182,7 @@ static void decklink_ui_tick(void *param, float /* sec */) void preview_output_stop() { obs_remove_main_rendered_callback(decklink_ui_render, &context_preview); - obs_frontend_remove_event_callback(on_preview_scene_changed, - &context_preview); + obs_frontend_remove_event_callback(on_preview_scene_changed, &context_preview); obs_output_stop(context_preview.output); obs_output_release(context_preview.output); @@ -224,14 +214,11 @@ void preview_output_start() OBSData settings = load_preview_settings(); if (settings != nullptr) { - obs_output_t *const output = obs_output_create( - "decklink_output", "decklink_output", settings, NULL); - const struct video_scale_info *const conversion = - obs_output_get_video_conversion(output); + obs_output_t *const output = obs_output_create("decklink_output", "decklink_output", settings, NULL); + const struct video_scale_info *const conversion = obs_output_get_video_conversion(output); if (conversion != nullptr) { context_preview.output = output; - obs_add_tick_callback(decklink_ui_tick, - &context_preview); + obs_add_tick_callback(decklink_ui_tick, &context_preview); obs_get_video_info(&context_preview.ovi); @@ -239,14 +226,10 @@ void preview_output_start() const uint32_t height = conversion->height; obs_enter_graphics(); - context_preview.texrender_premultiplied = - gs_texrender_create(GS_BGRA, GS_ZS_NONE); - context_preview.texrender = - gs_texrender_create(GS_BGRA, GS_ZS_NONE); - for (gs_stagesurf_t *&surf : - context_preview.stagesurfaces) - surf = gs_stagesurface_create(width, height, - GS_BGRA); + context_preview.texrender_premultiplied = gs_texrender_create(GS_BGRA, GS_ZS_NONE); + context_preview.texrender = gs_texrender_create(GS_BGRA, GS_ZS_NONE); + for (gs_stagesurf_t *&surf : context_preview.stagesurfaces) + surf = gs_stagesurface_create(width, height, GS_BGRA); obs_leave_graphics(); for (bool &written : context_preview.surf_written) @@ -267,21 +250,15 @@ void preview_output_start() video_output_open(&context_preview.video_queue, &vi); - obs_frontend_add_event_callback( - on_preview_scene_changed, &context_preview); + obs_frontend_add_event_callback(on_preview_scene_changed, &context_preview); if (obs_frontend_preview_program_mode_active()) { - context_preview.current_source = - obs_frontend_get_current_preview_scene(); + context_preview.current_source = obs_frontend_get_current_preview_scene(); } else { - context_preview.current_source = - obs_frontend_get_current_scene(); + context_preview.current_source = obs_frontend_get_current_scene(); } - obs_add_main_rendered_callback(decklink_ui_render, - &context_preview); + obs_add_main_rendered_callback(decklink_ui_render, &context_preview); - obs_output_set_media(context_preview.output, - context_preview.video_queue, - obs_get_audio()); + obs_output_set_media(context_preview.output, context_preview.video_queue, obs_get_audio()); bool started = obs_output_start(context_preview.output); preview_output_running = started; @@ -356,8 +333,7 @@ static void decklink_ui_render(void *param) width = obs_source_get_base_width(ctx->current_source); height = obs_source_get_base_height(ctx->current_source); - gs_texrender_t *const texrender_premultiplied = - ctx->texrender_premultiplied; + gs_texrender_t *const texrender_premultiplied = ctx->texrender_premultiplied; if (!gs_texrender_begin(texrender_premultiplied, width, height)) return; @@ -365,8 +341,7 @@ static void decklink_ui_render(void *param) vec4_zero(&background); gs_clear(GS_CLEAR_COLOR, &background, 0.0f, 0); - gs_ortho(0.0f, (float)width, 0.0f, (float)height, -100.0f, - 100.0f); + gs_ortho(0.0f, (float)width, 0.0f, (float)height, -100.0f, 100.0f); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO); @@ -381,8 +356,7 @@ static void decklink_ui_render(void *param) return; } - const struct video_scale_info *const conversion = - obs_output_get_video_conversion(ctx->output); + const struct video_scale_info *const conversion = obs_output_get_video_conversion(ctx->output); const uint32_t scaled_width = conversion->width; const uint32_t scaled_height = conversion->height; @@ -390,23 +364,17 @@ static void decklink_ui_render(void *param) return; const bool previous = gs_framebuffer_srgb_enabled(); - const bool source_hdr = (ctx->ovi.colorspace == VIDEO_CS_2100_PQ) || - (ctx->ovi.colorspace == VIDEO_CS_2100_HLG); - const bool target_hdr = source_hdr && - (conversion->colorspace == VIDEO_CS_2100_PQ); + const bool source_hdr = (ctx->ovi.colorspace == VIDEO_CS_2100_PQ) || (ctx->ovi.colorspace == VIDEO_CS_2100_HLG); + const bool target_hdr = source_hdr && (conversion->colorspace == VIDEO_CS_2100_PQ); gs_enable_framebuffer_srgb(!target_hdr); gs_enable_blending(false); gs_effect_t *const effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); - gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), - tex); - const char *const tech_name = - target_hdr ? "DrawAlphaDivideR10L" - : (source_hdr ? "DrawAlphaDivideTonemap" - : "DrawAlphaDivide"); + gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), tex); + const char *const tech_name = target_hdr ? "DrawAlphaDivideR10L" + : (source_hdr ? "DrawAlphaDivideTonemap" : "DrawAlphaDivide"); while (gs_effect_loop(effect, tech_name)) { - gs_effect_set_float(gs_effect_get_param_by_name(effect, - "multiplier"), + gs_effect_set_float(gs_effect_get_param_by_name(effect, "multiplier"), obs_get_video_sdr_white_level() / 10000.f); gs_draw_sprite(tex, 0, 0, 0); } @@ -417,28 +385,20 @@ static void decklink_ui_render(void *param) gs_texrender_end(ctx->texrender); const size_t write_stage_index = ctx->stage_index; - gs_stage_texture(ctx->stagesurfaces[write_stage_index], - gs_texrender_get_texture(ctx->texrender)); + gs_stage_texture(ctx->stagesurfaces[write_stage_index], gs_texrender_get_texture(ctx->texrender)); ctx->surf_written[write_stage_index] = true; - const size_t read_stage_index = - (write_stage_index + 1) % STAGE_BUFFER_COUNT; + const size_t read_stage_index = (write_stage_index + 1) % STAGE_BUFFER_COUNT; if (ctx->surf_written[read_stage_index]) { struct video_frame output_frame; - if (video_output_lock_frame(ctx->video_queue, &output_frame, 1, - os_gettime_ns())) { - gs_stagesurf_t *const read_surf = - ctx->stagesurfaces[read_stage_index]; - if (gs_stagesurface_map(read_surf, &ctx->video_data, - &ctx->video_linesize)) { + if (video_output_lock_frame(ctx->video_queue, &output_frame, 1, os_gettime_ns())) { + gs_stagesurf_t *const read_surf = ctx->stagesurfaces[read_stage_index]; + if (gs_stagesurface_map(read_surf, &ctx->video_data, &ctx->video_linesize)) { uint32_t linesize = output_frame.linesize[0]; for (uint32_t i = 0; i < scaled_height; i++) { uint32_t dst_offset = linesize * i; - uint32_t src_offset = - ctx->video_linesize * i; - memcpy(output_frame.data[0] + - dst_offset, - ctx->video_data + src_offset, + uint32_t src_offset = ctx->video_linesize * i; + memcpy(output_frame.data[0] + dst_offset, ctx->video_data + src_offset, linesize); } @@ -455,8 +415,7 @@ static void decklink_ui_render(void *param) void addOutputUI(void) { - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - obs_module_text("Decklink Output")); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("Decklink Output")); QMainWindow *window = (QMainWindow *)obs_frontend_get_main_window(); @@ -481,8 +440,7 @@ static void OBSEvent(enum obs_frontend_event event, void *) OBSData previewSettings = load_preview_settings(); - if (previewSettings && - obs_data_get_bool(previewSettings, "auto_start")) + if (previewSettings && obs_data_get_bool(previewSettings, "auto_start")) preview_output_start(); } else if (event == OBS_FRONTEND_EVENT_EXIT) { shutting_down = true; diff --git a/UI/frontend-plugins/frontend-tools/auto-scene-switcher-nix.cpp b/UI/frontend-plugins/frontend-tools/auto-scene-switcher-nix.cpp index e5e5f96af..48519dea5 100644 --- a/UI/frontend-plugins/frontend-tools/auto-scene-switcher-nix.cpp +++ b/UI/frontend-plugins/frontend-tools/auto-scene-switcher-nix.cpp @@ -39,8 +39,7 @@ void CleanupSceneSwitcher() static bool ewmhIsSupported() { Display *display = disp(); - Atom netSupportingWmCheck = - XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", true); + Atom netSupportingWmCheck = XInternAtom(display, "_NET_SUPPORTING_WM_CHECK", true); Atom actualType; int format = 0; unsigned long num = 0, bytes = 0; @@ -53,10 +52,8 @@ static bool ewmhIsSupported() return false; } - int status = XGetWindowProperty(display, root_window, - netSupportingWmCheck, 0L, 1L, false, - XA_WINDOW, &actualType, &format, &num, - &bytes, &data); + int status = XGetWindowProperty(display, root_window, netSupportingWmCheck, 0L, 1L, false, XA_WINDOW, + &actualType, &format, &num, &bytes, &data); if (status == Success) { if (num > 0) { @@ -69,12 +66,9 @@ static bool ewmhIsSupported() } if (ewmh_window) { - status = XGetWindowProperty(display, ewmh_window, - netSupportingWmCheck, 0L, 1L, false, - XA_WINDOW, &actualType, &format, - &num, &bytes, &data); - if (status != Success || num == 0 || - ewmh_window != ((Window *)data)[0]) { + status = XGetWindowProperty(display, ewmh_window, netSupportingWmCheck, 0L, 1L, false, XA_WINDOW, + &actualType, &format, &num, &bytes, &data); + if (status != Success || num == 0 || ewmh_window != ((Window *)data)[0]) { ewmh_window = 0; } if (status == Success && data) { @@ -107,10 +101,8 @@ static std::vector getTopLevelWindows() continue; } - int status = XGetWindowProperty(disp(), rootWin, netClList, 0L, - ~0L, false, AnyPropertyType, - &actualType, &format, &num, - &bytes, (uint8_t **)&data); + int status = XGetWindowProperty(disp(), rootWin, netClList, 0L, ~0L, false, AnyPropertyType, + &actualType, &format, &num, &bytes, (uint8_t **)&data); if (status != Success) { continue; @@ -141,8 +133,7 @@ static std::string GetWindowTitle(size_t i) XFree(name); } else { XTextProperty xtp_new_name; - if (XGetWMName(disp(), w, &xtp_new_name) != 0 && - xtp_new_name.value != nullptr) { + if (XGetWMName(disp(), w, &xtp_new_name) != 0 && xtp_new_name.value != nullptr) { std::string str((const char *)xtp_new_name.value); windowTitle = str; XFree(xtp_new_name.value); @@ -180,8 +171,7 @@ void GetCurrentWindowTitle(string &title) return; } - XGetWindowProperty(disp(), rootWin, active, 0L, ~0L, false, - AnyPropertyType, &actualType, &format, &num, &bytes, + XGetWindowProperty(disp(), rootWin, active, 0L, ~0L, false, AnyPropertyType, &actualType, &format, &num, &bytes, (uint8_t **)&data); if (!data[0]) { @@ -194,8 +184,7 @@ void GetCurrentWindowTitle(string &title) title = str; } else { XTextProperty xtp_new_name; - if (XGetWMName(disp(), data[0], &xtp_new_name) != 0 && - xtp_new_name.value != nullptr) { + if (XGetWMName(disp(), data[0], &xtp_new_name) != 0 && xtp_new_name.value != nullptr) { std::string str((const char *)xtp_new_name.value); title = str; XFree(xtp_new_name.value); diff --git a/UI/frontend-plugins/frontend-tools/auto-scene-switcher.cpp b/UI/frontend-plugins/frontend-tools/auto-scene-switcher.cpp index 5f4818c4f..f008a6884 100644 --- a/UI/frontend-plugins/frontend-tools/auto-scene-switcher.cpp +++ b/UI/frontend-plugins/frontend-tools/auto-scene-switcher.cpp @@ -25,12 +25,7 @@ struct SceneSwitch { string window; regex re; - inline SceneSwitch(OBSWeakSource scene_, const char *window_) - : scene(scene_), - window(window_), - re(window_) - { - } + inline SceneSwitch(OBSWeakSource scene_, const char *window_) : scene(scene_), window(window_), re(window_) {} }; static inline bool WeakSourceValid(obs_weak_source_t *ws) @@ -73,15 +68,12 @@ struct SwitcherData { static SwitcherData *switcher = nullptr; -static inline QString MakeSwitchName(const QString &scene, - const QString &window) +static inline QString MakeSwitchName(const QString &scene, const QString &window) { return QStringLiteral("[") + scene + QStringLiteral("]: ") + window; } -SceneSwitcher::SceneSwitcher(QWidget *parent) - : QDialog(parent), - ui(new Ui_SceneSwitcher) +SceneSwitcher::SceneSwitcher(QWidget *parent) : QDialog(parent), ui(new Ui_SceneSwitcher) { ui->setupUi(this); @@ -105,8 +97,7 @@ SceneSwitcher::SceneSwitcher(QWidget *parent) else ui->noMatchDontSwitch->setChecked(true); - ui->noMatchSwitchScene->setCurrentText( - GetWeakSourceName(switcher->nonMatchingScene).c_str()); + ui->noMatchSwitchScene->setCurrentText(GetWeakSourceName(switcher->nonMatchingScene).c_str()); ui->checkInterval->setValue(switcher->interval); vector windows; @@ -117,8 +108,7 @@ SceneSwitcher::SceneSwitcher(QWidget *parent) for (auto &s : switcher->switches) { string sceneName = GetWeakSourceName(s.scene); - QString text = - MakeSwitchName(sceneName.c_str(), s.window.c_str()); + QString text = MakeSwitchName(sceneName.c_str(), s.window.c_str()); QListWidgetItem *item = new QListWidgetItem(text, ui->switches); item->setData(Qt::UserRole, s.window.c_str()); @@ -201,16 +191,13 @@ void SceneSwitcher::on_add_clicked() if (idx == -1) { try { lock_guard lock(switcher->m); - switcher->switches.emplace_back( - source, windowName.toUtf8().constData()); + switcher->switches.emplace_back(source, windowName.toUtf8().constData()); - QListWidgetItem *item = - new QListWidgetItem(text, ui->switches); + QListWidgetItem *item = new QListWidgetItem(text, ui->switches); item->setData(Qt::UserRole, v); } catch (const regex_error &) { - QMessageBox::warning( - this, obs_module_text("InvalidRegex.Title"), - obs_module_text("InvalidRegex.Text")); + QMessageBox::warning(this, obs_module_text("InvalidRegex.Title"), + obs_module_text("InvalidRegex.Text")); } } else { QListWidgetItem *item = ui->switches->item(idx); @@ -238,8 +225,7 @@ void SceneSwitcher::on_remove_clicked() if (!item) return; - string window = - item->data(Qt::UserRole).toString().toUtf8().constData(); + string window = item->data(Qt::UserRole).toString().toUtf8().constData(); { lock_guard lock(switcher->m); @@ -260,8 +246,7 @@ void SceneSwitcher::on_remove_clicked() void SceneSwitcher::UpdateNonMatchingScene(const QString &name) { - OBSSourceAutoRelease scene = - obs_get_source_by_name(name.toUtf8().constData()); + OBSSourceAutoRelease scene = obs_get_source_by_name(name.toUtf8().constData()); OBSWeakSourceAutoRelease ws = obs_source_get_weak_source(scene); switcher->nonMatchingScene = ws.Get(); @@ -339,25 +324,20 @@ static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *) for (SceneSwitch &s : switcher->switches) { OBSDataAutoRelease array_obj = obs_data_create(); - OBSSourceAutoRelease source = - obs_weak_source_get_source(s.scene); + OBSSourceAutoRelease source = obs_weak_source_get_source(s.scene); if (source) { const char *n = obs_source_get_name(source); obs_data_set_string(array_obj, "scene", n); - obs_data_set_string(array_obj, "window_title", - s.window.c_str()); + obs_data_set_string(array_obj, "window_title", s.window.c_str()); obs_data_array_push_back(array, array_obj); } } - string nonMatchingSceneName = - GetWeakSourceName(switcher->nonMatchingScene); + string nonMatchingSceneName = GetWeakSourceName(switcher->nonMatchingScene); obs_data_set_int(obj, "interval", switcher->interval); - obs_data_set_string(obj, "non_matching_scene", - nonMatchingSceneName.c_str()); - obs_data_set_bool(obj, "switch_if_not_matching", - switcher->switchIfNotMatching); + obs_data_set_string(obj, "non_matching_scene", nonMatchingSceneName.c_str()); + obs_data_set_bool(obj, "switch_if_not_matching", switcher->switchIfNotMatching); obs_data_set_bool(obj, "active", switcher->th.joinable()); obs_data_set_array(obj, "switches", array); @@ -365,10 +345,8 @@ static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *) } else { switcher->m.lock(); - OBSDataAutoRelease obj = - obs_data_get_obj(save_data, "auto-scene-switcher"); - OBSDataArrayAutoRelease array = - obs_data_get_array(obj, "switches"); + OBSDataAutoRelease obj = obs_data_get_obj(save_data, "auto-scene-switcher"); + OBSDataArrayAutoRelease array = obs_data_get_array(obj, "switches"); size_t count = obs_data_array_count(array); if (!obj) @@ -377,28 +355,21 @@ static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *) obs_data_set_default_int(obj, "interval", DEFAULT_INTERVAL); switcher->interval = obs_data_get_int(obj, "interval"); - switcher->switchIfNotMatching = - obs_data_get_bool(obj, "switch_if_not_matching"); - string nonMatchingScene = - obs_data_get_string(obj, "non_matching_scene"); + switcher->switchIfNotMatching = obs_data_get_bool(obj, "switch_if_not_matching"); + string nonMatchingScene = obs_data_get_string(obj, "non_matching_scene"); bool active = obs_data_get_bool(obj, "active"); - switcher->nonMatchingScene = - GetWeakSourceByName(nonMatchingScene.c_str()); + switcher->nonMatchingScene = GetWeakSourceByName(nonMatchingScene.c_str()); switcher->switches.clear(); for (size_t i = 0; i < count; i++) { - OBSDataAutoRelease array_obj = - obs_data_array_item(array, i); + OBSDataAutoRelease array_obj = obs_data_array_item(array, i); - const char *scene = - obs_data_get_string(array_obj, "scene"); - const char *window = - obs_data_get_string(array_obj, "window_title"); + const char *scene = obs_data_get_string(array_obj, "scene"); + const char *window = obs_data_get_string(array_obj, "window_title"); - switcher->switches.emplace_back( - GetWeakSourceByName(scene), window); + switcher->switches.emplace_back(GetWeakSourceByName(scene), window); } switcher->m.unlock(); @@ -412,8 +383,7 @@ static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *) void SwitcherData::Thread() { - chrono::duration duration = - chrono::milliseconds(interval); + chrono::duration duration = chrono::milliseconds(interval); string lastTitle; string title; @@ -447,8 +417,7 @@ void SwitcherData::Thread() if (!match) { for (SceneSwitch &s : switches) { try { - bool matches = regex_match( - title, s.re); + bool matches = regex_match(title, s.re); if (matches) { match = true; scene = s.scene; @@ -465,10 +434,8 @@ void SwitcherData::Thread() } if (match) { - OBSSourceAutoRelease source = - obs_weak_source_get_source(scene); - OBSSourceAutoRelease currentSource = - obs_frontend_get_current_scene(); + OBSSourceAutoRelease source = obs_weak_source_get_source(scene); + OBSSourceAutoRelease currentSource = obs_frontend_get_current_scene(); if (source && source != currentSource) obs_frontend_set_current_scene(source); @@ -518,16 +485,14 @@ extern "C" void InitSceneSwitcher() return; #endif - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - obs_module_text("SceneSwitcher")); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("SceneSwitcher")); switcher = new SwitcherData; auto cb = []() { obs_frontend_push_ui_translation(obs_module_get_string); - QMainWindow *window = - (QMainWindow *)obs_frontend_get_main_window(); + QMainWindow *window = (QMainWindow *)obs_frontend_get_main_window(); SceneSwitcher ss(window); ss.exec(); diff --git a/UI/frontend-plugins/frontend-tools/captions-handler.cpp b/UI/frontend-plugins/frontend-tools/captions-handler.cpp index a2e5df7a1..80aa26360 100644 --- a/UI/frontend-plugins/frontend-tools/captions-handler.cpp +++ b/UI/frontend-plugins/frontend-tools/captions-handler.cpp @@ -1,23 +1,18 @@ #include "captions-handler.hpp" -captions_handler::captions_handler(captions_cb callback, - enum audio_format format, - uint32_t sample_rate) - : cb(callback) +captions_handler::captions_handler(captions_cb callback, enum audio_format format, uint32_t sample_rate) : cb(callback) { if (!reset_resampler(format, sample_rate)) throw CAPTIONS_ERROR_GENERIC_FAIL; } -bool captions_handler::reset_resampler(enum audio_format format, - uint32_t sample_rate) +bool captions_handler::reset_resampler(enum audio_format format, uint32_t sample_rate) try { obs_audio_info ai; if (!obs_get_audio_info(&ai)) throw std::string("Failed to get OBS audio info"); - resample_info src = {ai.samples_per_sec, AUDIO_FORMAT_FLOAT_PLANAR, - ai.speakers}; + resample_info src = {ai.samples_per_sec, AUDIO_FORMAT_FLOAT_PLANAR, ai.speakers}; resample_info dst = {sample_rate, format, SPEAKERS_MONO}; if (!resampler.reset(dst, src)) @@ -37,8 +32,7 @@ void captions_handler::push_audio(const audio_data *audio) uint64_t ts_offset; bool success; - success = audio_resampler_resample(resampler, out, &frames, &ts_offset, - (const uint8_t *const *)audio->data, + success = audio_resampler_resample(resampler, out, &frames, &ts_offset, (const uint8_t *const *)audio->data, audio->frames); if (success) pcm_data(out[0], frames); diff --git a/UI/frontend-plugins/frontend-tools/captions-handler.hpp b/UI/frontend-plugins/frontend-tools/captions-handler.hpp index b728ef641..5d9c1b6b7 100644 --- a/UI/frontend-plugins/frontend-tools/captions-handler.hpp +++ b/UI/frontend-plugins/frontend-tools/captions-handler.hpp @@ -25,8 +25,7 @@ public: typedef std::function captions_cb; -#define CAPTIONS_ERROR_GENERIC_FAIL \ - std::string(obs_module_text("Captions.Error.GenericFail")) +#define CAPTIONS_ERROR_GENERIC_FAIL std::string(obs_module_text("Captions.Error.GenericFail")) /* ------------------------------------------------------------------------- */ @@ -44,8 +43,7 @@ protected: public: /* throw std::string for errors shown to users */ - captions_handler(captions_cb callback, enum audio_format format, - uint32_t sample_rate); + captions_handler(captions_cb callback, enum audio_format format, uint32_t sample_rate); virtual ~captions_handler() {} void push_audio(const audio_data *audio); diff --git a/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.cpp b/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.cpp index 508dfec83..36182bb25 100644 --- a/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.cpp +++ b/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.cpp @@ -8,9 +8,7 @@ using namespace std; #if 0 -#define debugfunc(format, ...) \ - blog(LOG_DEBUG, "[Captions] %s(" format ")", __FUNCTION__, \ - ##__VA_ARGS__) +#define debugfunc(format, ...) blog(LOG_DEBUG, "[Captions] %s(" format ")", __FUNCTION__, ##__VA_ARGS__) #else #define debugfunc(format, ...) #endif @@ -144,8 +142,7 @@ STDMETHODIMP CaptionStream::Write(const void *, ULONG bytes, ULONG *) // IStream methods -STDMETHODIMP CaptionStream::Seek(LARGE_INTEGER move, DWORD origin, - ULARGE_INTEGER *new_pos) +STDMETHODIMP CaptionStream::Seek(LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *new_pos) { debugfunc("%lld, %lx, new_pos", move, origin); @@ -165,8 +162,7 @@ STDMETHODIMP CaptionStream::SetSize(ULARGE_INTEGER new_size) return STG_E_INVALIDFUNCTION; } -STDMETHODIMP CaptionStream::CopyTo(IStream *stream, ULARGE_INTEGER bytes, - ULARGE_INTEGER *read_bytes, +STDMETHODIMP CaptionStream::CopyTo(IStream *stream, ULARGE_INTEGER bytes, ULARGE_INTEGER *read_bytes, ULARGE_INTEGER *written_bytes) { HRESULT hr; @@ -207,16 +203,14 @@ STDMETHODIMP CaptionStream::Revert(void) return S_OK; } -STDMETHODIMP CaptionStream::LockRegion(ULARGE_INTEGER offset, - ULARGE_INTEGER size, DWORD type) +STDMETHODIMP CaptionStream::LockRegion(ULARGE_INTEGER offset, ULARGE_INTEGER size, DWORD type) { debugfunc("%llu, %llu, %ld", offset, size, type); /* TODO? */ return STG_E_INVALIDFUNCTION; } -STDMETHODIMP CaptionStream::UnlockRegion(ULARGE_INTEGER offset, - ULARGE_INTEGER size, DWORD type) +STDMETHODIMP CaptionStream::UnlockRegion(ULARGE_INTEGER offset, ULARGE_INTEGER size, DWORD type) { debugfunc("%llu, %llu, %ld", offset, size, type); /* TODO? */ @@ -255,8 +249,7 @@ STDMETHODIMP CaptionStream::Clone(IStream **stream) // ISpStreamFormat methods -STDMETHODIMP CaptionStream::GetFormat(GUID *guid, - WAVEFORMATEX **co_mem_wfex_out) +STDMETHODIMP CaptionStream::GetFormat(GUID *guid, WAVEFORMATEX **co_mem_wfex_out) { debugfunc("guid, co_mem_wfex_out"); @@ -284,8 +277,7 @@ STDMETHODIMP CaptionStream::SetState(SPAUDIOSTATE state_, ULONGLONG) return S_OK; } -STDMETHODIMP CaptionStream::SetFormat(REFGUID guid_ref, - const WAVEFORMATEX *wfex) +STDMETHODIMP CaptionStream::SetFormat(REFGUID guid_ref, const WAVEFORMATEX *wfex) { debugfunc("guid, wfex"); if (!wfex) @@ -294,8 +286,7 @@ STDMETHODIMP CaptionStream::SetFormat(REFGUID guid_ref, if (guid_ref == SPDFID_WaveFormatEx) { lock_guard lock(m); memcpy(&format, wfex, sizeof(format)); - if (!handler->reset_resampler(AUDIO_FORMAT_16BIT, - wfex->nSamplesPerSec)) + if (!handler->reset_resampler(AUDIO_FORMAT_16BIT, wfex->nSamplesPerSec)) return E_FAIL; /* 50 msec */ @@ -342,8 +333,7 @@ STDMETHODIMP CaptionStream::GetBufferInfo(SPAUDIOBUFFERINFO *buf_info_) return S_OK; } -STDMETHODIMP CaptionStream::GetDefaultFormat(GUID *format, - WAVEFORMATEX **co_mem_wfex_out) +STDMETHODIMP CaptionStream::GetDefaultFormat(GUID *format, WAVEFORMATEX **co_mem_wfex_out) { debugfunc("format, co_mem_wfex_out"); diff --git a/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.hpp b/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.hpp index 75106d862..3e761cfd1 100644 --- a/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.hpp +++ b/UI/frontend-plugins/frontend-tools/captions-mssapi-stream.hpp @@ -55,38 +55,30 @@ public: // ISequentialStream methods STDMETHODIMP Read(void *data, ULONG bytes, ULONG *read_bytes) override; - STDMETHODIMP Write(const void *data, ULONG bytes, - ULONG *written_bytes) override; + STDMETHODIMP Write(const void *data, ULONG bytes, ULONG *written_bytes) override; // IStream methods - STDMETHODIMP Seek(LARGE_INTEGER move, DWORD origin, - ULARGE_INTEGER *new_pos) override; + STDMETHODIMP Seek(LARGE_INTEGER move, DWORD origin, ULARGE_INTEGER *new_pos) override; STDMETHODIMP SetSize(ULARGE_INTEGER new_size) override; - STDMETHODIMP CopyTo(IStream *stream, ULARGE_INTEGER bytes, - ULARGE_INTEGER *read_bytes, + STDMETHODIMP CopyTo(IStream *stream, ULARGE_INTEGER bytes, ULARGE_INTEGER *read_bytes, ULARGE_INTEGER *written_bytes) override; STDMETHODIMP Commit(DWORD commit_flags) override; STDMETHODIMP Revert(void) override; - STDMETHODIMP LockRegion(ULARGE_INTEGER offset, ULARGE_INTEGER size, - DWORD type) override; - STDMETHODIMP UnlockRegion(ULARGE_INTEGER offset, ULARGE_INTEGER size, - DWORD type) override; + STDMETHODIMP LockRegion(ULARGE_INTEGER offset, ULARGE_INTEGER size, DWORD type) override; + STDMETHODIMP UnlockRegion(ULARGE_INTEGER offset, ULARGE_INTEGER size, DWORD type) override; STDMETHODIMP Stat(STATSTG *stg, DWORD flags) override; STDMETHODIMP Clone(IStream **stream) override; // ISpStreamFormat methods - STDMETHODIMP GetFormat(GUID *guid, - WAVEFORMATEX **co_mem_wfex_out) override; + STDMETHODIMP GetFormat(GUID *guid, WAVEFORMATEX **co_mem_wfex_out) override; // ISpAudio methods STDMETHODIMP SetState(SPAUDIOSTATE state, ULONGLONG reserved) override; - STDMETHODIMP SetFormat(REFGUID guid_ref, - const WAVEFORMATEX *wfex) override; + STDMETHODIMP SetFormat(REFGUID guid_ref, const WAVEFORMATEX *wfex) override; STDMETHODIMP GetStatus(SPAUDIOSTATUS *status) override; STDMETHODIMP SetBufferInfo(const SPAUDIOBUFFERINFO *buf_info) override; STDMETHODIMP GetBufferInfo(SPAUDIOBUFFERINFO *buf_info) override; - STDMETHODIMP GetDefaultFormat(GUID *format, - WAVEFORMATEX **co_mem_wfex_out) override; + STDMETHODIMP GetDefaultFormat(GUID *format, WAVEFORMATEX **co_mem_wfex_out) override; STDMETHODIMP_(HANDLE) EventHandle(void) override; STDMETHODIMP GetVolumeLevel(ULONG *level) override; STDMETHODIMP SetVolumeLevel(ULONG level) override; diff --git a/UI/frontend-plugins/frontend-tools/captions-mssapi.cpp b/UI/frontend-plugins/frontend-tools/captions-mssapi.cpp index edb4b138e..f551fe008 100644 --- a/UI/frontend-plugins/frontend-tools/captions-mssapi.cpp +++ b/UI/frontend-plugins/frontend-tools/captions-mssapi.cpp @@ -1,7 +1,6 @@ #include "captions-mssapi.hpp" -#define do_log(type, format, ...) \ - blog(type, "[Captions] " format, ##__VA_ARGS__) +#define do_log(type, format, ...) blog(type, "[Captions] " format, ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__) @@ -29,8 +28,8 @@ try : captions_handler(callback, AUDIO_FORMAT_16BIT, 16000) { if (FAILED(hr)) throw HRError("SpFindBestToken failed", hr); - hr = CoCreateInstance(CLSID_SpInprocRecognizer, nullptr, CLSCTX_ALL, - __uuidof(ISpRecognizer), (void **)&recognizer); + hr = CoCreateInstance(CLSID_SpInprocRecognizer, nullptr, CLSCTX_ALL, __uuidof(ISpRecognizer), + (void **)&recognizer); if (FAILED(hr)) throw HRError("CoCreateInstance for recognizer failed", hr); @@ -46,8 +45,7 @@ try : captions_handler(callback, AUDIO_FORMAT_16BIT, 16000) { if (FAILED(hr)) throw HRError("CreateRecoContext failed", hr); - ULONGLONG interest = SPFEI(SPEI_RECOGNITION) | - SPFEI(SPEI_END_SR_STREAM); + ULONGLONG interest = SPFEI(SPEI_RECOGNITION) | SPFEI(SPEI_END_SR_STREAM); hr = context->SetInterest(interest, interest); if (FAILED(hr)) throw HRError("SetInterest failed", hr); @@ -130,8 +128,7 @@ try { ISpRecoResult *result = event.RecoResult(); CoTaskMemPtr text; - hr = result->GetText((ULONG)-1, (ULONG)-1, true, - &text, nullptr); + hr = result->GetText((ULONG)-1, (ULONG)-1, true, &text, nullptr); if (FAILED(hr)) continue; @@ -164,8 +161,7 @@ void mssapi_captions::pcm_data(const void *data, size_t frames) audio->PushAudio(data, frames); } -captions_handler_info mssapi_info = { - []() -> std::string { return "Microsoft Speech-to-Text"; }, - [](captions_cb cb, const std::string &lang) -> captions_handler * { - return new mssapi_captions(cb, lang); - }}; +captions_handler_info mssapi_info = {[]() -> std::string { return "Microsoft Speech-to-Text"; }, + [](captions_cb cb, const std::string &lang) -> captions_handler * { + return new mssapi_captions(cb, lang); + }}; diff --git a/UI/frontend-plugins/frontend-tools/captions.cpp b/UI/frontend-plugins/frontend-tools/captions.cpp index f8ae0d954..db15f9484 100644 --- a/UI/frontend-plugins/frontend-tools/captions.cpp +++ b/UI/frontend-plugins/frontend-tools/captions.cpp @@ -31,8 +31,7 @@ #include "captions-mssapi.hpp" -#define do_log(type, format, ...) \ - blog(type, "[Captions] " format, ##__VA_ARGS__) +#define do_log(type, format, ...) blog(type, "[Captions] " format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__) @@ -50,11 +49,7 @@ struct obs_captions { std::unordered_map handler_types; - inline void register_handler(const char *id, - captions_handler_info &info) - { - handler_types.emplace(id, info); - } + inline void register_handler(const char *id, captions_handler_info &info) { handler_types.emplace(id, info); } void start(); void stop(); @@ -73,11 +68,7 @@ struct locale_info { inline locale_info() {} inline locale_info(const locale_info &) = delete; - inline locale_info(locale_info &&li) - : name(std::move(li.name)), - id(li.id) - { - } + inline locale_info(locale_info &&li) : name(std::move(li.name)), id(li.id) {} }; static void get_valid_locale_names(vector &names); @@ -85,9 +76,7 @@ static bool valid_lang(LANGID id); /* ------------------------------------------------------------------------- */ -CaptionsDialog::CaptionsDialog(QWidget *parent) - : QDialog(parent), - ui(new Ui_CaptionsDialog) +CaptionsDialog::CaptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui_CaptionsDialog) { ui->setupUi(this); @@ -111,11 +100,7 @@ CaptionsDialog::CaptionsDialog(QWidget *parent) ui->source->blockSignals(true); ui->source->addItem(QStringLiteral("")); ui->source->setCurrentIndex(0); - obs_enum_sources( - [](void *data, obs_source_t *source) { - return (*static_cast(data))(source); - }, - &cb); + obs_enum_sources([](void *data, obs_source_t *source) { return (*static_cast(data))(source); }, &cb); ui->source->blockSignals(false); for (auto &ht : captions->handler_types) { @@ -217,8 +202,7 @@ void CaptionsDialog::on_provider_currentIndexChanged(int idx) if (started) captions->stop(); - captions->handler_id = - ui->provider->itemData(idx).toString().toUtf8().constData(); + captions->handler_id = ui->provider->itemData(idx).toString().toUtf8().constData(); if (started) captions->start(); @@ -234,8 +218,7 @@ static void caption_text(const std::string &text) } } -static void audio_capture(void *, obs_source_t *, - const struct audio_data *audio, bool) +static void audio_capture(void *, obs_source_t *, const struct audio_data *audio, bool) { captions->handler->push_audio(audio); } @@ -252,8 +235,7 @@ void obs_captions::start() } if (!LCIDToLocaleName(lang_id, wname, 256, 0)) { - warn("Failed to get locale name: %d", - (int)GetLastError()); + warn("Failed to get locale name: %d", (int)GetLastError()); return; } @@ -272,24 +254,18 @@ void obs_captions::start() } try { - captions_handler *h = - pair->second.create(caption_text, lang_name); + captions_handler *h = pair->second.create(caption_text, lang_name); handler.reset(h); OBSSource s = OBSGetStrongRef(source); - obs_source_add_audio_capture_callback(s, audio_capture, - nullptr); + obs_source_add_audio_capture_callback(s, audio_capture, nullptr); } catch (std::string text) { - QWidget *window = - (QWidget *)obs_frontend_get_main_window(); + QWidget *window = (QWidget *)obs_frontend_get_main_window(); warn("Failed to create handler: %s", text.c_str()); - QMessageBox::warning( - window, - obs_module_text("Captions.Error.GenericFail"), - text.c_str()); + QMessageBox::warning(window, obs_module_text("Captions.Error.GenericFail"), text.c_str()); } } } @@ -298,8 +274,7 @@ void obs_captions::stop() { OBSSource s = OBSGetStrongRef(source); if (s) - obs_source_remove_audio_capture_callback(s, audio_capture, - nullptr); + obs_source_remove_audio_capture_callback(s, audio_capture, nullptr); handler.reset(); } @@ -332,19 +307,16 @@ static void get_valid_locale_names(vector &locales) locale_info cur; char locale_name[256]; - static const LANGID default_locales[] = { - 0x0409, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, - 0x0407, 0x0408, 0x040a, 0x040b, 0x040c, 0x040d, 0x040e, - 0x040f, 0x0410, 0x0411, 0x0412, 0x0413, 0x0414, 0x0415, - 0x0416, 0x0417, 0x0418, 0x0419, 0x041a, 0}; + static const LANGID default_locales[] = {0x0409, 0x0401, 0x0402, 0x0403, 0x0404, 0x0405, 0x0406, 0x0407, 0x0408, + 0x040a, 0x040b, 0x040c, 0x040d, 0x040e, 0x040f, 0x0410, 0x0411, 0x0412, + 0x0413, 0x0414, 0x0415, 0x0416, 0x0417, 0x0418, 0x0419, 0x041a, 0}; /* ---------------------------------- */ LANGID def_id = GetUserDefaultUILanguage(); LANGID id = def_id; if (valid_lang(id) && get_locale_name(id, locale_name)) { - dstr_copy(cur.name, - obs_module_text("Captions.CurrentSystemLanguage")); + dstr_copy(cur.name, obs_module_text("Captions.CurrentSystemLanguage")); dstr_replace(cur.name, "%1", locale_name); cur.id = id; @@ -358,8 +330,7 @@ static void get_valid_locale_names(vector &locales) while (*locale) { id = *locale; - if (id != def_id && valid_lang(id) && - get_locale_name(id, locale_name)) { + if (id != def_id && valid_lang(id) && get_locale_name(id, locale_name)) { dstr_copy(cur.name, locale_name); cur.id = id; @@ -399,32 +370,27 @@ static void save_caption_data(obs_data_t *save_data, bool saving, void *) if (saving) { OBSDataAutoRelease obj = obs_data_create(); - obs_data_set_string(obj, "source", - captions->source_name.c_str()); + obs_data_set_string(obj, "source", captions->source_name.c_str()); obs_data_set_bool(obj, "enabled", !!captions->handler); obs_data_set_int(obj, "lang_id", captions->lang_id); - obs_data_set_string(obj, "provider", - captions->handler_id.c_str()); + obs_data_set_string(obj, "provider", captions->handler_id.c_str()); obs_data_set_obj(save_data, "captions", obj); } else { captions->stop(); - OBSDataAutoRelease obj = - obs_data_get_obj(save_data, "captions"); + OBSDataAutoRelease obj = obs_data_get_obj(save_data, "captions"); if (!obj) obj = obs_data_create(); - obs_data_set_default_int(obj, "lang_id", - GetUserDefaultUILanguage()); + obs_data_set_default_int(obj, "lang_id", GetUserDefaultUILanguage()); obs_data_set_default_string(obj, "provider", DEFAULT_HANDLER); bool enabled = obs_data_get_bool(obj, "enabled"); captions->source_name = obs_data_get_string(obj, "source"); captions->lang_id = (int)obs_data_get_int(obj, "lang_id"); captions->handler_id = obs_data_get_string(obj, "provider"); - captions->source = - GetWeakSourceByName(captions->source_name.c_str()); + captions->source = GetWeakSourceByName(captions->source_name.c_str()); if (enabled) captions->start(); @@ -433,8 +399,7 @@ static void save_caption_data(obs_data_t *save_data, bool saving, void *) extern "C" void InitCaptions() { - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - obs_module_text("Captions")); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("Captions")); captions = new obs_captions; diff --git a/UI/frontend-plugins/frontend-tools/output-timer.cpp b/UI/frontend-plugins/frontend-tools/output-timer.cpp index 5b871bf9b..388f449b4 100644 --- a/UI/frontend-plugins/frontend-tools/output-timer.cpp +++ b/UI/frontend-plugins/frontend-tools/output-timer.cpp @@ -12,20 +12,16 @@ using namespace std; OutputTimer *ot; -OutputTimer::OutputTimer(QWidget *parent) - : QDialog(parent), - ui(new Ui_OutputTimer) +OutputTimer::OutputTimer(QWidget *parent) : QDialog(parent), ui(new Ui_OutputTimer) { ui->setupUi(this); setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); - QObject::connect(ui->outputTimerStream, &QPushButton::clicked, this, - &OutputTimer::StreamingTimerButton); - QObject::connect(ui->outputTimerRecord, &QPushButton::clicked, this, - &OutputTimer::RecordingTimerButton); - QObject::connect(ui->buttonBox->button(QDialogButtonBox::Close), - &QPushButton::clicked, this, &OutputTimer::hide); + QObject::connect(ui->outputTimerStream, &QPushButton::clicked, this, &OutputTimer::StreamingTimerButton); + QObject::connect(ui->outputTimerRecord, &QPushButton::clicked, this, &OutputTimer::RecordingTimerButton); + QObject::connect(ui->buttonBox->button(QDialogButtonBox::Close), &QPushButton::clicked, this, + &OutputTimer::hide); streamingTimer = new QTimer(this); streamingTimerDisplay = new QTimer(this); @@ -33,14 +29,10 @@ OutputTimer::OutputTimer(QWidget *parent) recordingTimer = new QTimer(this); recordingTimerDisplay = new QTimer(this); - QObject::connect(streamingTimer, &QTimer::timeout, this, - &OutputTimer::EventStopStreaming); - QObject::connect(streamingTimerDisplay, &QTimer::timeout, this, - &OutputTimer::UpdateStreamTimerDisplay); - QObject::connect(recordingTimer, &QTimer::timeout, this, - &OutputTimer::EventStopRecording); - QObject::connect(recordingTimerDisplay, &QTimer::timeout, this, - &OutputTimer::UpdateRecordTimerDisplay); + QObject::connect(streamingTimer, &QTimer::timeout, this, &OutputTimer::EventStopStreaming); + QObject::connect(streamingTimerDisplay, &QTimer::timeout, this, &OutputTimer::UpdateStreamTimerDisplay); + QObject::connect(recordingTimer, &QTimer::timeout, this, &OutputTimer::EventStopRecording); + QObject::connect(recordingTimerDisplay, &QTimer::timeout, this, &OutputTimer::UpdateRecordTimerDisplay); } void OutputTimer::closeEvent(QCloseEvent *) @@ -178,8 +170,7 @@ void OutputTimer::UpdateStreamTimerDisplay() int minutes = (remainingTime % 3600) / 60; int hours = remainingTime / 3600; - QString text = - QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); + QString text = QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); ui->streamTime->setText(text); } @@ -187,8 +178,7 @@ void OutputTimer::UpdateRecordTimerDisplay() { int remainingTime = 0; - if (obs_frontend_recording_paused() && - ui->pauseRecordTimer->isChecked()) + if (obs_frontend_recording_paused() && ui->pauseRecordTimer->isChecked()) remainingTime = recordingTimeLeft / 1000; else remainingTime = recordingTimer->remainingTime() / 1000; @@ -197,8 +187,7 @@ void OutputTimer::UpdateRecordTimerDisplay() int minutes = (remainingTime % 3600) / 60; int hours = remainingTime / 3600; - QString text = - QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); + QString text = QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); ui->recordTime->setText(text); } @@ -250,57 +239,38 @@ static void SaveOutputTimer(obs_data_t *save_data, bool saving, void *) if (saving) { OBSDataAutoRelease obj = obs_data_create(); - obs_data_set_int(obj, "streamTimerHours", - ot->ui->streamingTimerHours->value()); - obs_data_set_int(obj, "streamTimerMinutes", - ot->ui->streamingTimerMinutes->value()); - obs_data_set_int(obj, "streamTimerSeconds", - ot->ui->streamingTimerSeconds->value()); + obs_data_set_int(obj, "streamTimerHours", ot->ui->streamingTimerHours->value()); + obs_data_set_int(obj, "streamTimerMinutes", ot->ui->streamingTimerMinutes->value()); + obs_data_set_int(obj, "streamTimerSeconds", ot->ui->streamingTimerSeconds->value()); - obs_data_set_int(obj, "recordTimerHours", - ot->ui->recordingTimerHours->value()); - obs_data_set_int(obj, "recordTimerMinutes", - ot->ui->recordingTimerMinutes->value()); - obs_data_set_int(obj, "recordTimerSeconds", - ot->ui->recordingTimerSeconds->value()); + obs_data_set_int(obj, "recordTimerHours", ot->ui->recordingTimerHours->value()); + obs_data_set_int(obj, "recordTimerMinutes", ot->ui->recordingTimerMinutes->value()); + obs_data_set_int(obj, "recordTimerSeconds", ot->ui->recordingTimerSeconds->value()); - obs_data_set_bool(obj, "autoStartStreamTimer", - ot->ui->autoStartStreamTimer->isChecked()); - obs_data_set_bool(obj, "autoStartRecordTimer", - ot->ui->autoStartRecordTimer->isChecked()); + obs_data_set_bool(obj, "autoStartStreamTimer", ot->ui->autoStartStreamTimer->isChecked()); + obs_data_set_bool(obj, "autoStartRecordTimer", ot->ui->autoStartRecordTimer->isChecked()); - obs_data_set_bool(obj, "pauseRecordTimer", - ot->ui->pauseRecordTimer->isChecked()); + obs_data_set_bool(obj, "pauseRecordTimer", ot->ui->pauseRecordTimer->isChecked()); obs_data_set_obj(save_data, "output-timer", obj); } else { - OBSDataAutoRelease obj = - obs_data_get_obj(save_data, "output-timer"); + OBSDataAutoRelease obj = obs_data_get_obj(save_data, "output-timer"); if (!obj) obj = obs_data_create(); - ot->ui->streamingTimerHours->setValue( - obs_data_get_int(obj, "streamTimerHours")); - ot->ui->streamingTimerMinutes->setValue( - obs_data_get_int(obj, "streamTimerMinutes")); - ot->ui->streamingTimerSeconds->setValue( - obs_data_get_int(obj, "streamTimerSeconds")); + ot->ui->streamingTimerHours->setValue(obs_data_get_int(obj, "streamTimerHours")); + ot->ui->streamingTimerMinutes->setValue(obs_data_get_int(obj, "streamTimerMinutes")); + ot->ui->streamingTimerSeconds->setValue(obs_data_get_int(obj, "streamTimerSeconds")); - ot->ui->recordingTimerHours->setValue( - obs_data_get_int(obj, "recordTimerHours")); - ot->ui->recordingTimerMinutes->setValue( - obs_data_get_int(obj, "recordTimerMinutes")); - ot->ui->recordingTimerSeconds->setValue( - obs_data_get_int(obj, "recordTimerSeconds")); + ot->ui->recordingTimerHours->setValue(obs_data_get_int(obj, "recordTimerHours")); + ot->ui->recordingTimerMinutes->setValue(obs_data_get_int(obj, "recordTimerMinutes")); + ot->ui->recordingTimerSeconds->setValue(obs_data_get_int(obj, "recordTimerSeconds")); - ot->ui->autoStartStreamTimer->setChecked( - obs_data_get_bool(obj, "autoStartStreamTimer")); - ot->ui->autoStartRecordTimer->setChecked( - obs_data_get_bool(obj, "autoStartRecordTimer")); + ot->ui->autoStartStreamTimer->setChecked(obs_data_get_bool(obj, "autoStartStreamTimer")); + ot->ui->autoStartRecordTimer->setChecked(obs_data_get_bool(obj, "autoStartRecordTimer")); - ot->ui->pauseRecordTimer->setChecked( - obs_data_get_bool(obj, "pauseRecordTimer")); + ot->ui->pauseRecordTimer->setChecked(obs_data_get_bool(obj, "pauseRecordTimer")); } } @@ -328,8 +298,7 @@ static void OBSEvent(enum obs_frontend_event event, void *) extern "C" void InitOutputTimer() { - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - obs_module_text("OutputTimer")); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("OutputTimer")); obs_frontend_push_ui_translation(obs_module_get_string); diff --git a/UI/frontend-plugins/frontend-tools/scripts.cpp b/UI/frontend-plugins/frontend-tools/scripts.cpp index 3e2c433f1..b3e7c9c98 100644 --- a/UI/frontend-plugins/frontend-tools/scripts.cpp +++ b/UI/frontend-plugins/frontend-tools/scripts.cpp @@ -93,8 +93,7 @@ ScriptLogWindow::ScriptLogWindow() : QDialog(nullptr) QHBoxLayout *buttonLayout = new QHBoxLayout(); QPushButton *clearButton = new QPushButton(tr("Clear")); - connect(clearButton, &QPushButton::clicked, this, - &ScriptLogWindow::ClearWindow); + connect(clearButton, &QPushButton::clicked, this, &ScriptLogWindow::ClearWindow); QPushButton *closeButton = new QPushButton(tr("Close")); connect(closeButton, &QPushButton::clicked, this, &QDialog::hide); @@ -114,8 +113,7 @@ ScriptLogWindow::ScriptLogWindow() : QDialog(nullptr) resize(600, 400); config_t *global_config = obs_frontend_get_user_config(); - const char *geom = - config_get_string(global_config, "ScriptLogWindow", "geometry"); + const char *geom = config_get_string(global_config, "ScriptLogWindow", "geometry"); if (geom != nullptr) { QByteArray ba = QByteArray::fromBase64(QByteArray(geom)); restoreGeometry(ba); @@ -123,15 +121,13 @@ ScriptLogWindow::ScriptLogWindow() : QDialog(nullptr) setWindowTitle(obs_module_text("ScriptLogWindow")); - connect(edit->verticalScrollBar(), &QAbstractSlider::sliderMoved, this, - &ScriptLogWindow::ScrollChanged); + connect(edit->verticalScrollBar(), &QAbstractSlider::sliderMoved, this, &ScriptLogWindow::ScrollChanged); } ScriptLogWindow::~ScriptLogWindow() { config_t *global_config = obs_frontend_get_user_config(); - config_set_string(global_config, "ScriptLogWindow", "geometry", - saveGeometry().toBase64().constData()); + config_set_string(global_config, "ScriptLogWindow", "geometry", saveGeometry().toBase64().constData()); } void ScriptLogWindow::ScrollChanged(int val) @@ -190,8 +186,7 @@ ScriptsTool::ScriptsTool() : QDialog(nullptr), ui(new Ui_ScriptsTool) #if PYTHON_UI config_t *config = obs_frontend_get_user_config(); - const char *path = - config_get_string(config, "Python", "Path" ARCH_NAME); + const char *path = config_get_string(config, "Python", "Path" ARCH_NAME); ui->pythonPath->setText(path); ui->pythonPathLabel->setText(obs_module_text(PYTHONPATH_LABEL_TEXT)); updatePythonVersionLabel(); @@ -203,8 +198,7 @@ ScriptsTool::ScriptsTool() : QDialog(nullptr), ui(new Ui_ScriptsTool) delete propertiesView; propertiesView = new QWidget(); - propertiesView->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding); + propertiesView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->propertiesLayout->addWidget(propertiesView); config_t *user_config = obs_frontend_get_user_config(); @@ -215,8 +209,7 @@ ScriptsTool::ScriptsTool() : QDialog(nullptr), ui(new Ui_ScriptsTool) ScriptsTool::~ScriptsTool() { config_t *user_config = obs_frontend_get_user_config(); - config_set_int(user_config, "scripts-tool", "prevScriptRow", - ui->scripts->currentRow()); + config_set_int(user_config, "scripts-tool", "prevScriptRow", ui->scripts->currentRow()); } void ScriptsTool::updatePythonVersionLabel() @@ -225,8 +218,7 @@ void ScriptsTool::updatePythonVersionLabel() if (obs_scripting_python_loaded()) { char version[8]; obs_scripting_python_version(version, sizeof(version)); - label = QString(obs_module_text("PythonSettings.PythonVersion")) - .arg(version); + label = QString(obs_module_text("PythonSettings.PythonVersion")).arg(version); } else { label = obs_module_text("PythonSettings.PythonNotLoaded"); } @@ -240,8 +232,7 @@ void ScriptsTool::RemoveScript(const char *path) const char *script_path = obs_script_get_path(script); if (strcmp(script_path, path) == 0) { - scriptData->scripts.erase(scriptData->scripts.begin() + - i); + scriptData->scripts.erase(scriptData->scripts.begin() + i); break; } } @@ -256,8 +247,7 @@ void ScriptsTool::ReloadScript(const char *path) OBSDataAutoRelease settings = obs_data_create(); - obs_properties_t *prop = - obs_script_get_properties(script); + obs_properties_t *prop = obs_script_get_properties(script); obs_properties_apply_settings(prop, settings); obs_properties_destroy(prop); @@ -285,8 +275,7 @@ void ScriptsTool::SetScriptDefaults(const char *path) for (OBSScript &script : scriptData->scripts) { const char *script_path = obs_script_get_path(script); if (strcmp(script_path, path) == 0) { - OBSDataAutoRelease settings = - obs_script_get_settings(script); + OBSDataAutoRelease settings = obs_script_get_settings(script); obs_data_clear(settings); obs_script_update(script, nullptr); @@ -335,15 +324,13 @@ void ScriptsTool::on_addScripts_clicked() lastBrowsedDir = baseScriptPath; } - QStringList files = OpenFiles(this, - QT_UTF8(obs_module_text("AddScripts")), - QT_UTF8(lastBrowsedDir.c_str()), filter); + QStringList files = + OpenFiles(this, QT_UTF8(obs_module_text("AddScripts")), QT_UTF8(lastBrowsedDir.c_str()), filter); if (!files.count()) return; for (const QString &file : files) { - lastBrowsedDir = - QFileInfo(file).absolutePath().toUtf8().constData(); + lastBrowsedDir = QFileInfo(file).absolutePath().toUtf8().constData(); QByteArray pathBytes = file.toUtf8(); const char *path = pathBytes.constData(); @@ -358,15 +345,13 @@ void ScriptsTool::on_addScripts_clicked() scriptData->scripts.emplace_back(script); - QListWidgetItem *item = - new QListWidgetItem(script_file); + QListWidgetItem *item = new QListWidgetItem(script_file); item->setData(Qt::UserRole, QString(file)); ui->scripts->addItem(item); OBSDataAutoRelease settings = obs_data_create(); - obs_properties_t *prop = - obs_script_get_properties(script); + obs_properties_t *prop = obs_script_get_properties(script); obs_properties_apply_settings(prop, settings); obs_properties_destroy(prop); @@ -380,10 +365,7 @@ void ScriptsTool::on_removeScripts_clicked() QList items = ui->scripts->selectedItems(); for (QListWidgetItem *item : items) - RemoveScript(item->data(Qt::UserRole) - .toString() - .toUtf8() - .constData()); + RemoveScript(item->data(Qt::UserRole).toString().toUtf8().constData()); RefreshLists(); } @@ -391,10 +373,7 @@ void ScriptsTool::on_reloadScripts_clicked() { QList items = ui->scripts->selectedItems(); for (QListWidgetItem *item : items) - ReloadScript(item->data(Qt::UserRole) - .toString() - .toUtf8() - .constData()); + ReloadScript(item->data(Qt::UserRole).toString().toUtf8().constData()); on_scripts_currentRowChanged(ui->scripts->currentRow()); } @@ -405,8 +384,7 @@ void ScriptsTool::OpenScriptParentDirectory() for (QListWidgetItem *item : items) { QDir dir(item->data(Qt::UserRole).toString()); dir.cdUp(); - QDesktopServices::openUrl( - QUrl::fromLocalFile(dir.absolutePath())); + QDesktopServices::openUrl(QUrl::fromLocalFile(dir.absolutePath())); } } @@ -423,13 +401,10 @@ void ScriptsTool::on_scripts_customContextMenuRequested(const QPoint &pos) if (item) { popup.addSeparator(); - popup.addAction(obs_module_text("Reload"), this, - &ScriptsTool::on_reloadScripts_clicked); - popup.addAction(obs_module_text("OpenFileLocation"), this, - &ScriptsTool::OpenScriptParentDirectory); + popup.addAction(obs_module_text("Reload"), this, &ScriptsTool::on_reloadScripts_clicked); + popup.addAction(obs_module_text("OpenFileLocation"), this, &ScriptsTool::OpenScriptParentDirectory); popup.addSeparator(); - popup.addAction(tr("Remove"), this, - &ScriptsTool::on_removeScripts_clicked); + popup.addAction(tr("Remove"), this, &ScriptsTool::on_removeScripts_clicked); } obs_frontend_pop_ui_translation(); @@ -441,8 +416,7 @@ void ScriptsTool::on_editScript_clicked() int row = ui->scripts->currentRow(); if (row == -1) return; - QUrl url = QUrl::fromLocalFile( - ui->scripts->item(row)->data(Qt::UserRole).toString()); + QUrl url = QUrl::fromLocalFile(ui->scripts->item(row)->data(Qt::UserRole).toString()); QDesktopServices::openUrl(url); } @@ -455,8 +429,7 @@ void ScriptsTool::on_scriptLog_clicked() void ScriptsTool::on_pythonPathBrowse_clicked() { QString curPath = ui->pythonPath->text(); - QString newPath = - SelectDirectory(this, ui->pythonPathLabel->text(), curPath); + QString newPath = SelectDirectory(this, ui->pythonPathLabel->text(), curPath); if (newPath.isEmpty()) return; @@ -474,14 +447,8 @@ void ScriptsTool::on_pythonPathBrowse_clicked() if (loaded && !newPath.isEmpty() && curPath.compare(newPath) != 0) { char version[8]; obs_scripting_python_version(version, sizeof(version)); - QString message = - QString(obs_module_text( - "PythonSettings.AlreadyLoaded.Message")) - .arg(version); - OBSMessageBox::information( - this, - obs_module_text("PythonSettings.AlreadyLoaded.Title"), - message); + QString message = QString(obs_module_text("PythonSettings.AlreadyLoaded.Message")).arg(version); + OBSMessageBox::information(this, obs_module_text("PythonSettings.AlreadyLoaded.Title"), message); return; } else if (loaded) { return; @@ -509,15 +476,13 @@ void ScriptsTool::on_scripts_currentRowChanged(int row) if (row == -1) { propertiesView = new QWidget(); - propertiesView->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding); + propertiesView->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); ui->propertiesLayout->addWidget(propertiesView); ui->description->setText(QString()); return; } - QByteArray array = - ui->scripts->item(row)->data(Qt::UserRole).toString().toUtf8(); + QByteArray array = ui->scripts->item(row)->data(Qt::UserRole).toString().toUtf8(); const char *path = array.constData(); obs_script_t *script = scriptData->FindScript(path); @@ -528,10 +493,9 @@ void ScriptsTool::on_scripts_currentRowChanged(int row) OBSDataAutoRelease settings = obs_script_get_settings(script); - OBSPropertiesView *view = new OBSPropertiesView( - settings.Get(), script, - (PropertiesReloadCallback)obs_script_get_properties, nullptr, - (PropertiesVisualUpdateCb)obs_script_update); + OBSPropertiesView *view = new OBSPropertiesView(settings.Get(), script, + (PropertiesReloadCallback)obs_script_get_properties, nullptr, + (PropertiesVisualUpdateCb)obs_script_update); view->SetDeferrable(false); propertiesView = view; @@ -546,33 +510,26 @@ void ScriptsTool::on_defaults_clicked() if (!item) return; - SetScriptDefaults( - item->data(Qt::UserRole).toString().toUtf8().constData()); + SetScriptDefaults(item->data(Qt::UserRole).toString().toUtf8().constData()); } void ScriptsTool::on_description_linkActivated(const QString &link) { QUrl url(link, QUrl::StrictMode); - if (url.isValid() && (url.scheme().compare("http") == 0 || - url.scheme().compare("https") == 0)) { + if (url.isValid() && (url.scheme().compare("http") == 0 || url.scheme().compare("https") == 0)) { QString msg(obs_module_text("ScriptDescriptionLink.Text")); msg += "\n\n"; - msg += QString(obs_module_text( - "ScriptDescriptionLink.Text.Url")) - .arg(link); + msg += QString(obs_module_text("ScriptDescriptionLink.Text.Url")).arg(link); - const char *open = - obs_module_text("ScriptDescriptionLink.OpenURL"); + const char *open = obs_module_text("ScriptDescriptionLink.OpenURL"); QMessageBox messageBox(this); messageBox.setWindowTitle(open); messageBox.setText(msg); obs_frontend_push_ui_translation(obs_module_get_string); - QPushButton *yesButton = - messageBox.addButton(open, QMessageBox::YesRole); - QPushButton *noButton = - messageBox.addButton(tr("Cancel"), QMessageBox::NoRole); + QPushButton *yesButton = messageBox.addButton(open, QMessageBox::YesRole); + QPushButton *noButton = messageBox.addButton(tr("Cancel"), QMessageBox::NoRole); obs_frontend_pop_ui_translation(); messageBox.setDefaultButton(yesButton); messageBox.setEscapeButton(noButton); @@ -615,8 +572,7 @@ static void obs_event(enum obs_frontend_event event, void *) static void load_script_data(obs_data_t *load_data, bool, void *) { - OBSDataArrayAutoRelease array = - obs_data_get_array(load_data, "scripts-tool"); + OBSDataArrayAutoRelease array = obs_data_get_array(load_data, "scripts-tool"); delete scriptData; scriptData = new ScriptData; @@ -657,20 +613,17 @@ static void save_script_data(obs_data_t *save_data, bool saving, void *) obs_data_set_array(save_data, "scripts-tool", array); } -static void script_log(void *, obs_script_t *script, int log_level, - const char *message) +static void script_log(void *, obs_script_t *script, int log_level, const char *message) { QString qmsg; if (script) { - qmsg = QStringLiteral("[%1] %2").arg( - obs_script_get_file(script), message); + qmsg = QStringLiteral("[%1] %2").arg(obs_script_get_file(script), message); } else { qmsg = QStringLiteral("[Unknown Script] %1").arg(message); } - QMetaObject::invokeMethod(scriptLogWindow, "AddLogMsg", - Q_ARG(int, log_level), Q_ARG(QString, qmsg)); + QMetaObject::invokeMethod(scriptLogWindow, "AddLogMsg", Q_ARG(int, log_level), Q_ARG(QString, qmsg)); } extern "C" void InitScripts() @@ -680,24 +633,20 @@ extern "C" void InitScripts() obs_scripting_load(); obs_scripting_set_log_callback(script_log, nullptr); - QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction( - obs_module_text("Scripts")); + QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("Scripts")); #if PYTHON_UI config_t *config = obs_frontend_get_user_config(); - const char *python_path = - config_get_string(config, "Python", "Path" ARCH_NAME); + const char *python_path = config_get_string(config, "Python", "Path" ARCH_NAME); #ifdef __APPLE__ if (python_path && *python_path) { std::string _python_path(python_path); - std::size_t pos = - _python_path.find("/Python.framework/Versions"); + std::size_t pos = _python_path.find("/Python.framework/Versions"); if (pos != std::string::npos) { std::string _temp = _python_path.substr(0, pos); - config_set_string(config, "Python", "Path" ARCH_NAME, - _temp.c_str()); + config_set_string(config, "Python", "Path" ARCH_NAME, _temp.c_str()); config_save(config); python_path = _temp.c_str(); } diff --git a/UI/goliveapi-censoredjson.cpp b/UI/goliveapi-censoredjson.cpp index fed481912..bd59e5d1e 100644 --- a/UI/goliveapi-censoredjson.cpp +++ b/UI/goliveapi-censoredjson.cpp @@ -23,8 +23,7 @@ void censorRecurse(obs_data_t *data) censorRecurse(child_data); obs_data_release(child_data); } else if (typ == OBS_DATA_ARRAY) { - obs_data_array_t *child_array = - obs_data_item_get_array(item); + obs_data_array_t *child_array = obs_data_item_get_array(item); censorRecurseArray(child_array); obs_data_array_release(child_array); } @@ -55,8 +54,7 @@ QString censoredJson(obs_data_t *data, bool pretty) censorRecurse(clone); // Turn our copy into JSON - QString s = pretty ? obs_data_get_json_pretty(clone) - : obs_data_get_json(clone); + QString s = pretty ? obs_data_get_json_pretty(clone) : obs_data_get_json(clone); // Eliminate our copy obs_data_release(clone); diff --git a/UI/goliveapi-network.cpp b/UI/goliveapi-network.cpp index fb7871082..dc557bbc1 100644 --- a/UI/goliveapi-network.cpp +++ b/UI/goliveapi-network.cpp @@ -17,8 +17,7 @@ using json = nlohmann::json; Qt::ConnectionType BlockingConnectionTypeFor(QObject *object); -void HandleGoLiveApiErrors(QWidget *parent, const json &raw_json, - const GoLiveApi::Config &config) +void HandleGoLiveApiErrors(QWidget *parent, const json &raw_json, const GoLiveApi::Config &config) { using GoLiveApi::StatusResult; @@ -36,17 +35,12 @@ void HandleGoLiveApiErrors(QWidget *parent, const json &raw_json, [=] { QMessageBox mb(parent); mb.setIcon(QMessageBox::Warning); - mb.setWindowTitle(QTStr( - "ConfigDownload.WarningMessageTitle")); + mb.setWindowTitle(QTStr("ConfigDownload.WarningMessageTitle")); mb.setTextFormat(Qt::RichText); - mb.setText( - message + - QTStr("FailedToStartStream.WarningRetry")); - mb.setStandardButtons( - QMessageBox::StandardButton::Yes | - QMessageBox::StandardButton::No); - return mb.exec() == - QMessageBox::StandardButton::No; + mb.setText(message + QTStr("FailedToStartStream.WarningRetry")); + mb.setStandardButtons(QMessageBox::StandardButton::Yes | + QMessageBox::StandardButton::No); + return mb.exec() == QMessageBox::StandardButton::No; }, BlockingConnectionTypeFor(parent), &ret); if (ret) @@ -54,66 +48,52 @@ void HandleGoLiveApiErrors(QWidget *parent, const json &raw_json, }; auto missing_html = [] { - return QTStr("FailedToStartStream.StatusMissingHTML") - .toStdString(); + return QTStr("FailedToStartStream.StatusMissingHTML").toStdString(); }; if (status.result == StatusResult::Unknown) { - return warn_continue( - QTStr("FailedToStartStream.WarningUnknownStatus") - .arg(raw_json["status"]["result"] - .dump() - .c_str())); + return warn_continue(QTStr("FailedToStartStream.WarningUnknownStatus") + .arg(raw_json["status"]["result"].dump().c_str())); } else if (status.result == StatusResult::Warning) { if (config.encoder_configurations.empty()) { - throw MultitrackVideoError::warning( - status.html_en_us.value_or(missing_html()) - .c_str()); + throw MultitrackVideoError::warning(status.html_en_us.value_or(missing_html()).c_str()); } - return warn_continue( - status.html_en_us.value_or(missing_html()).c_str()); + return warn_continue(status.html_en_us.value_or(missing_html()).c_str()); } else if (status.result == StatusResult::Error) { - throw MultitrackVideoError::critical( - status.html_en_us.value_or(missing_html()).c_str()); + throw MultitrackVideoError::critical(status.html_en_us.value_or(missing_html()).c_str()); } } -GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, - const GoLiveApi::PostData &post_data, +GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, const GoLiveApi::PostData &post_data, const QString &multitrack_video_name) { json post_data_json = post_data; - blog(LOG_INFO, "Go live POST data: %s", - censoredJson(post_data_json).toUtf8().constData()); + blog(LOG_INFO, "Go live POST data: %s", censoredJson(post_data_json).toUtf8().constData()); if (url.isEmpty()) - throw MultitrackVideoError::critical( - QTStr("FailedToStartStream.MissingConfigURL")); + throw MultitrackVideoError::critical(QTStr("FailedToStartStream.MissingConfigURL")); std::string encodeConfigText; std::string libraryError; std::vector headers; headers.push_back("Content-Type: application/json"); - bool encodeConfigDownloadedOk = GetRemoteFile( - url.toLocal8Bit(), encodeConfigText, - libraryError, // out params - nullptr, - nullptr, // out params (response code and content type) - "POST", post_data_json.dump().c_str(), headers, - nullptr, // signature - 5); // timeout in seconds + bool encodeConfigDownloadedOk = GetRemoteFile(url.toLocal8Bit(), encodeConfigText, + libraryError, // out params + nullptr, + nullptr, // out params (response code and content type) + "POST", post_data_json.dump().c_str(), headers, + nullptr, // signature + 5); // timeout in seconds if (!encodeConfigDownloadedOk) throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.ConfigRequestFailed") - .arg(url, libraryError.c_str())); + QTStr("FailedToStartStream.ConfigRequestFailed").arg(url, libraryError.c_str())); try { auto data = json::parse(encodeConfigText); - blog(LOG_INFO, "Go live response data: %s", - censoredJson(data, true).toUtf8().constData()); + blog(LOG_INFO, "Go live response data: %s", censoredJson(data, true).toUtf8().constData()); GoLiveApi::Config config = data; HandleGoLiveApiErrors(parent, data, config); return config; @@ -121,19 +101,16 @@ GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, } catch (const json::exception &e) { blog(LOG_INFO, "Failed to parse go live config: %s", e.what()); throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.FallbackToDefault") - .arg(multitrack_video_name)); + QTStr("FailedToStartStream.FallbackToDefault").arg(multitrack_video_name)); } } QString MultitrackVideoAutoConfigURL(obs_service_t *service) { - static const std::optional cli_url = - []() -> std::optional { + static const std::optional cli_url = []() -> std::optional { auto args = qApp->arguments(); for (int i = 0; i < args.length() - 1; i++) { - if (args[i] == "--config-url" && - args.length() > (i + 1)) { + if (args[i] == "--config-url" && args.length() > (i + 1)) { return args[i + 1]; } } @@ -145,8 +122,7 @@ QString MultitrackVideoAutoConfigURL(obs_service_t *service) url = *cli_url; } else { OBSDataAutoRelease settings = obs_service_get_settings(service); - url = obs_data_get_string(settings, - "multitrack_video_configuration_url"); + url = obs_data_get_string(settings, "multitrack_video_configuration_url"); } blog(LOG_INFO, "Go live URL: %s", url.toUtf8().constData()); diff --git a/UI/goliveapi-network.hpp b/UI/goliveapi-network.hpp index e543640d9..2a2daecf8 100644 --- a/UI/goliveapi-network.hpp +++ b/UI/goliveapi-network.hpp @@ -10,6 +10,5 @@ QString MultitrackVideoAutoConfigURL(obs_service_t *service); class QWidget; -GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, - const GoLiveApi::PostData &post_data, +GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, const GoLiveApi::PostData &post_data, const QString &multitrack_video_name); diff --git a/UI/goliveapi-postdata.cpp b/UI/goliveapi-postdata.cpp index e67d2dbde..9056764db 100644 --- a/UI/goliveapi-postdata.cpp +++ b/UI/goliveapi-postdata.cpp @@ -6,11 +6,8 @@ #include "models/multitrack-video.hpp" -GoLiveApi::PostData -constructGoLivePost(QString streamKey, - const std::optional &maximum_aggregate_bitrate, - const std::optional &maximum_video_tracks, - bool vod_track_enabled) +GoLiveApi::PostData constructGoLivePost(QString streamKey, const std::optional &maximum_aggregate_bitrate, + const std::optional &maximum_video_tracks, bool vod_track_enabled) { GoLiveApi::PostData post_data{}; post_data.service = "IVS"; @@ -25,8 +22,7 @@ constructGoLivePost(QString streamKey, client.version = obs_get_version_string(); auto add_codec = [&](const char *codec) { - auto it = std::find(std::begin(client.supported_codecs), - std::end(client.supported_codecs), codec); + auto it = std::find(std::begin(client.supported_codecs), std::end(client.supported_codecs), codec); if (it != std::end(client.supported_codecs)) return; @@ -67,8 +63,7 @@ constructGoLivePost(QString streamKey, } if (maximum_aggregate_bitrate.has_value()) - preferences.maximum_aggregate_bitrate = - maximum_aggregate_bitrate.value(); + preferences.maximum_aggregate_bitrate = maximum_aggregate_bitrate.value(); if (maximum_video_tracks.has_value()) preferences.maximum_video_tracks = maximum_video_tracks.value(); diff --git a/UI/goliveapi-postdata.hpp b/UI/goliveapi-postdata.hpp index fbb671d9b..23f010883 100644 --- a/UI/goliveapi-postdata.hpp +++ b/UI/goliveapi-postdata.hpp @@ -5,8 +5,5 @@ #include #include "models/multitrack-video.hpp" -GoLiveApi::PostData -constructGoLivePost(QString streamKey, - const std::optional &maximum_aggregate_bitrate, - const std::optional &maximum_video_tracks, - bool vod_track_enabled); +GoLiveApi::PostData constructGoLivePost(QString streamKey, const std::optional &maximum_aggregate_bitrate, + const std::optional &maximum_video_tracks, bool vod_track_enabled); diff --git a/UI/hotkey-edit.cpp b/UI/hotkey-edit.cpp index efc98bdd9..5dc5355e7 100644 --- a/UI/hotkey-edit.cpp +++ b/UI/hotkey-edit.cpp @@ -49,12 +49,10 @@ void OBSHotkeyEdit::keyPressEvent(QKeyEvent *event) #endif default: - new_key.key = - obs_key_from_virtual_key(event->nativeVirtualKey()); + new_key.key = obs_key_from_virtual_key(event->nativeVirtualKey()); } - new_key.modifiers = - TranslateQtKeyboardEventModifiers(event->modifiers()); + new_key.modifiers = TranslateQtKeyboardEventModifiers(event->modifiers()); HandleNewKey(new_key); } @@ -81,8 +79,7 @@ void OBSHotkeyEdit::keyReleaseEvent(QKeyEvent *event) // kVK_CapsLock == 57 new_key.key = obs_key_from_virtual_key(57); - new_key.modifiers = - TranslateQtKeyboardEventModifiers(event->modifiers()); + new_key.modifiers = TranslateQtKeyboardEventModifiers(event->modifiers()); HandleNewKey(new_key); } @@ -135,8 +132,7 @@ void OBSHotkeyEdit::mousePressEvent(QMouseEvent *event) #undef MAP_BUTTON } - new_key.modifiers = - TranslateQtKeyboardEventModifiers(event->modifiers()); + new_key.modifiers = TranslateQtKeyboardEventModifiers(event->modifiers()); HandleNewKey(new_key); } @@ -198,22 +194,19 @@ void OBSHotkeyEdit::UpdateDuplicationState() void OBSHotkeyEdit::InitSignalHandler() { - layoutChanged = { - obs_get_signal_handler(), "hotkey_layout_change", - [](void *this_, calldata_t *) { - auto edit = static_cast(this_); - QMetaObject::invokeMethod(edit, "ReloadKeyLayout"); - }, - this}; + layoutChanged = {obs_get_signal_handler(), "hotkey_layout_change", + [](void *this_, calldata_t *) { + auto edit = static_cast(this_); + QMetaObject::invokeMethod(edit, "ReloadKeyLayout"); + }, + this}; } void OBSHotkeyEdit::CreateDupeIcon() { - dupeIcon = addAction(settings->GetHotkeyConflictIcon(), - ActionPosition::TrailingPosition); + dupeIcon = addAction(settings->GetHotkeyConflictIcon(), ActionPosition::TrailingPosition); dupeIcon->setToolTip(QTStr("Basic.Settings.Hotkeys.DuplicateWarning")); - QObject::connect(dupeIcon, &QAction::triggered, - [=] { emit SearchKey(key); }); + QObject::connect(dupeIcon, &QAction::triggered, [=] { emit SearchKey(key); }); dupeIcon->setVisible(false); } @@ -222,8 +215,7 @@ void OBSHotkeyEdit::ReloadKeyLayout() RenderKey(); } -void OBSHotkeyWidget::SetKeyCombinations( - const std::vector &combos) +void OBSHotkeyWidget::SetKeyCombinations(const std::vector &combos) { if (combos.empty()) AddEdit({0, OBS_KEY_NONE}); @@ -234,9 +226,7 @@ void OBSHotkeyWidget::SetKeyCombinations( bool OBSHotkeyWidget::Changed() const { - return changed || - std::any_of(begin(edits), end(edits), - [](OBSHotkeyEdit *edit) { return edit->changed; }); + return changed || std::any_of(begin(edits), end(edits), [](OBSHotkeyEdit *edit) { return edit->changed; }); } void OBSHotkeyWidget::Apply() @@ -252,8 +242,7 @@ void OBSHotkeyWidget::Apply() revertButton->setEnabled(false); } -void OBSHotkeyWidget::GetCombinations( - std::vector &combinations) const +void OBSHotkeyWidget::GetCombinations(std::vector &combinations) const { combinations.clear(); for (auto &edit : edits) @@ -275,16 +264,14 @@ void OBSHotkeyWidget::Save(std::vector &combinations) auto AtomicUpdate = [&]() { ignoreChangedBindings = true; - obs_hotkey_load_bindings(id, combinations.data(), - combinations.size()); + obs_hotkey_load_bindings(id, combinations.data(), combinations.size()); ignoreChangedBindings = false; }; using AtomicUpdate_t = decltype(&AtomicUpdate); - obs_hotkey_update_atomic( - [](void *d) { (*static_cast(d))(); }, - static_cast(&AtomicUpdate)); + obs_hotkey_update_atomic([](void *d) { (*static_cast(d))(); }, + static_cast(&AtomicUpdate)); } void OBSHotkeyWidget::AddEdit(obs_key_combination combo, int idx) @@ -302,13 +289,10 @@ void OBSHotkeyWidget::AddEdit(obs_key_combination combo, int idx) clear->setToolTip(QTStr("Clear")); clear->setEnabled(!obs_key_combination_is_empty(combo)); - QObject::connect( - edit, &OBSHotkeyEdit::KeyChanged, - [=](obs_key_combination_t new_combo) { - clear->setEnabled( - !obs_key_combination_is_empty(new_combo)); - revert->setEnabled(edit->original != new_combo); - }); + QObject::connect(edit, &OBSHotkeyEdit::KeyChanged, [=](obs_key_combination_t new_combo) { + clear->setEnabled(!obs_key_combination_is_empty(new_combo)); + revert->setEnabled(edit->original != new_combo); + }); auto add = new QPushButton; add->setProperty("class", "icon-plus"); @@ -320,8 +304,7 @@ void OBSHotkeyWidget::AddEdit(obs_key_combination combo, int idx) remove->setEnabled(removeButtons.size() > 0); auto CurrentIndex = [&, remove] { - auto res = std::find(begin(removeButtons), end(removeButtons), - remove); + auto res = std::find(begin(removeButtons), end(removeButtons), remove); return std::distance(begin(removeButtons), res); }; @@ -329,8 +312,7 @@ void OBSHotkeyWidget::AddEdit(obs_key_combination combo, int idx) AddEdit({0, OBS_KEY_NONE}, CurrentIndex() + 1); }); - QObject::connect(remove, &QPushButton::clicked, - [&, CurrentIndex] { RemoveEdit(CurrentIndex()); }); + QObject::connect(remove, &QPushButton::clicked, [&, CurrentIndex] { RemoveEdit(CurrentIndex()); }); QHBoxLayout *subLayout = new QHBoxLayout; subLayout->setContentsMargins(0, 2, 0, 2); @@ -355,17 +337,11 @@ void OBSHotkeyWidget::AddEdit(obs_key_combination combo, int idx) layout()->insertLayout(idx, subLayout); - QObject::connect(revert, &QPushButton::clicked, edit, - &OBSHotkeyEdit::ResetKey); - QObject::connect(clear, &QPushButton::clicked, edit, - &OBSHotkeyEdit::ClearKey); + QObject::connect(revert, &QPushButton::clicked, edit, &OBSHotkeyEdit::ResetKey); + QObject::connect(clear, &QPushButton::clicked, edit, &OBSHotkeyEdit::ClearKey); - QObject::connect(edit, &OBSHotkeyEdit::KeyChanged, - [&](obs_key_combination) { emit KeyChanged(); }); - QObject::connect(edit, &OBSHotkeyEdit::SearchKey, - [=](obs_key_combination combo) { - emit SearchKey(combo); - }); + QObject::connect(edit, &OBSHotkeyEdit::KeyChanged, [&](obs_key_combination) { emit KeyChanged(); }); + QObject::connect(edit, &OBSHotkeyEdit::SearchKey, [=](obs_key_combination combo) { emit SearchKey(combo); }); } void OBSHotkeyWidget::RemoveEdit(size_t idx, bool signal) @@ -398,8 +374,7 @@ void OBSHotkeyWidget::BindingsChanged(void *data, calldata_t *param) auto widget = static_cast(data); auto key = static_cast(calldata_ptr(param, "key")); - QMetaObject::invokeMethod(widget, "HandleChangedBindings", - Q_ARG(obs_hotkey_id, obs_hotkey_get_id(key))); + QMetaObject::invokeMethod(widget, "HandleChangedBindings", Q_ARG(obs_hotkey_id, obs_hotkey_get_id(key))); } void OBSHotkeyWidget::HandleChangedBindings(obs_hotkey_id id_) diff --git a/UI/hotkey-edit.hpp b/UI/hotkey-edit.hpp index 6770f7d5e..ea7e9b4ae 100644 --- a/UI/hotkey-edit.hpp +++ b/UI/hotkey-edit.hpp @@ -27,14 +27,12 @@ #include -static inline bool operator!=(const obs_key_combination_t &c1, - const obs_key_combination_t &c2) +static inline bool operator!=(const obs_key_combination_t &c1, const obs_key_combination_t &c2) { return c1.modifiers != c2.modifiers || c1.key != c2.key; } -static inline bool operator==(const obs_key_combination_t &c1, - const obs_key_combination_t &c2) +static inline bool operator==(const obs_key_combination_t &c1, const obs_key_combination_t &c2) { return !(c1 != c2); } @@ -58,8 +56,7 @@ class OBSHotkeyEdit : public QLineEdit { Q_OBJECT; public: - OBSHotkeyEdit(QWidget *parent, obs_key_combination_t original, - OBSBasicSettings *settings) + OBSHotkeyEdit(QWidget *parent, obs_key_combination_t original, OBSBasicSettings *settings) : QLineEdit(parent), original(original), settings(settings) @@ -74,10 +71,7 @@ public: InitSignalHandler(); ResetKey(); } - OBSHotkeyEdit(QWidget *parent = nullptr) - : QLineEdit(parent), - original({}), - settings(nullptr) + OBSHotkeyEdit(QWidget *parent = nullptr) : QLineEdit(parent), original({}), settings(nullptr) { #ifdef __APPLE__ // disable the input cursor on OSX, focus should be clear @@ -129,14 +123,12 @@ class OBSHotkeyWidget : public QWidget { Q_OBJECT; public: - OBSHotkeyWidget(QWidget *parent, obs_hotkey_id id, std::string name, - OBSBasicSettings *settings, + OBSHotkeyWidget(QWidget *parent, obs_hotkey_id id, std::string name, OBSBasicSettings *settings, const std::vector &combos = {}) : QWidget(parent), id(id), name(name), - bindingsChanged(obs_get_signal_handler(), - "hotkey_bindings_changed", + bindingsChanged(obs_get_signal_handler(), "hotkey_bindings_changed", &OBSHotkeyWidget::BindingsChanged, this), settings(settings) { @@ -187,10 +179,7 @@ private: bool ignoreChangedBindings = false; OBSBasicSettings *settings; - QVBoxLayout *layout() const - { - return dynamic_cast(QWidget::layout()); - } + QVBoxLayout *layout() const { return dynamic_cast(QWidget::layout()); } private slots: void HandleChangedBindings(obs_hotkey_id id_); diff --git a/UI/importers/classic.cpp b/UI/importers/classic.cpp index 32291360c..17d625213 100644 --- a/UI/importers/classic.cpp +++ b/UI/importers/classic.cpp @@ -33,11 +33,9 @@ static bool source_name_exists(const Json::array &sources, const string &name) return false; } -#define translate_int(in_key, in, out_key, out, off) \ - out[out_key] = in[in_key].int_value() + off; +#define translate_int(in_key, in, out_key, out, off) out[out_key] = in[in_key].int_value() + off; #define translate_string(in_key, in, out_key, out) out[out_key] = in[in_key]; -#define translate_bool(in_key, in, out_key, out) \ - out[out_key] = in[in_key].int_value() == 1; +#define translate_bool(in_key, in, out_key, out) out[out_key] = in[in_key].int_value() == 1; static Json::object translate_scene_item(const Json &in, const Json &source) { @@ -122,22 +120,15 @@ static Json::object translate_source(const Json &in, const Json &sources) settings["outline_color"] = color; translate_string("text", in_settings, "text", settings); - translate_int("backgroundOpacity", in_settings, "bk_opacity", - settings, 0); + translate_int("backgroundOpacity", in_settings, "bk_opacity", settings, 0); translate_bool("vertical", in_settings, "vertical", settings); - translate_int("textOpacity", in_settings, "opacity", settings, - 0); + translate_int("textOpacity", in_settings, "opacity", settings, 0); translate_bool("useOutline", in_settings, "outline", settings); - translate_int("outlineOpacity", in_settings, "outline_opacity", - settings, 0); - translate_int("outlineSize", in_settings, "outline_size", - settings, 0); - translate_bool("useTextExtents", in_settings, "extents", - settings); - translate_int("extentWidth", in_settings, "extents_cx", - settings, 0); - translate_int("extentHeight", in_settings, "extents_cy", - settings, 0); + translate_int("outlineOpacity", in_settings, "outline_opacity", settings, 0); + translate_int("outlineSize", in_settings, "outline_size", settings, 0); + translate_bool("useTextExtents", in_settings, "extents", settings); + translate_int("extentWidth", in_settings, "extents_cx", settings, 0); + translate_int("extentHeight", in_settings, "extents_cy", settings, 0); translate_bool("mode", in_settings, "read_from_file", settings); translate_bool("wrap", in_settings, "extents_wrap", settings); @@ -145,9 +136,7 @@ static Json::object translate_source(const Json &in, const Json &sources) settings["file"] = StringReplace(str, "\\\\", "/"); int in_align = in_settings["align"].int_value(); - string align = in_align == 0 - ? "left" - : (in_align == 1 ? "center" : "right"); + string align = in_align == 0 ? "left" : (in_align == 1 ? "center" : "right"); settings["align"] = align; @@ -181,8 +170,7 @@ static Json::object translate_source(const Json &in, const Json &sources) out["id"] = "monitor_capture"; translate_int("monitor", in_settings, "monitor", settings, 0); - translate_bool("captureMouse", in_settings, "capture_cursor", - settings); + translate_bool("captureMouse", in_settings, "capture_cursor", settings); } else if (id == "BitmapImageSource") { out["id"] = "image_source"; @@ -214,10 +202,7 @@ static Json::object translate_source(const Json &in, const Json &sources) out["id"] = "browser_source"; string browser_dec = - QByteArray::fromBase64(in_settings["sourceSettings"] - .string_value() - .c_str()) - .toStdString(); + QByteArray::fromBase64(in_settings["sourceSettings"].string_value().c_str()).toStdString(); string err; @@ -258,8 +243,7 @@ static Json::object translate_source(const Json &in, const Json &sources) settings["window"] = ":" + winClass + ":" + exec; - translate_bool("captureMouse", in_settings, "capture_cursor", - settings); + translate_bool("captureMouse", in_settings, "capture_cursor", settings); } out["settings"] = settings; @@ -303,10 +287,8 @@ static void translate_sc(const Json &in, Json &out) for (size_t x = sources.size(); x > 0; x--) { Json source = sources[x - 1]; - Json::object out_source = - translate_source(source, out_sources); - Json::object out_item = - translate_scene_item(source, out_source); + Json::object out_source = translate_source(source, out_sources); + Json::object out_item = translate_scene_item(source, out_source); out_item["id"] = (int)x - 1; @@ -316,12 +298,10 @@ static void translate_sc(const Json &in, Json &out) out_sources.push_back(out_source); } - out_sources.push_back(Json::object{ - {"id", "scene"}, - {"name", in_scene["name"]}, - {"settings", - Json::object{{"items", items}, - {"id_counter", (int)items.size()}}}}); + out_sources.push_back( + Json::object{{"id", "scene"}, + {"name", in_scene["name"]}, + {"settings", Json::object{{"items", items}, {"id_counter", (int)items.size()}}}}); } res["current_scene"] = first_name; @@ -332,8 +312,7 @@ static void translate_sc(const Json &in, Json &out) out = res; } -static void create_string(const string &name, Json::object &out, - const string &data) +static void create_string(const string &name, Json::object &out, const string &data) { string str = StringReplace(data, "\\\\", "/"); out[name] = str; @@ -346,15 +325,13 @@ static void create_string_obj(const string &data, Json::array &arr) arr.push_back(obj); } -static void create_double(const string &name, Json::object &out, - const string &data) +static void create_double(const string &name, Json::object &out, const string &data) { double d = atof(data.c_str()); out[name] = d; } -static void create_int(const string &name, Json::object &out, - const string &data) +static void create_int(const string &name, Json::object &out, const string &data) { int i = atoi(data.c_str()); out[name] = i; @@ -376,8 +353,7 @@ static void create_data_item(Json::object &out, const string &line) string first = line.substr(end_pos + 3); - if ((first[0] >= 'A' && first[0] <= 'Z') || - (first[0] >= 'a' && first[0] <= 'z') || first[0] == '\\' || + if ((first[0] >= 'A' && first[0] <= 'Z') || (first[0] >= 'a' && first[0] <= 'z') || first[0] == '\\' || first[0] == '/') { if (out.find(c_name) != out.end()) { Json::array arr = out[c_name].array_items(); @@ -515,8 +491,7 @@ int ClassicImporter::ImportScenes(const string &path, string &name, Json &res) string line = ReadLine(file); while (!line.empty() && line[0] != '\0') { - string key = line != "global sources : {" ? "scenes" - : "globals"; + string key = line != "global sources : {" ? "scenes" : "globals"; Json::array arr = create_sources(data, line, file); data[key] = arr; diff --git a/UI/importers/importers.cpp b/UI/importers/importers.cpp index f25546b33..6fbba89cf 100644 --- a/UI/importers/importers.cpp +++ b/UI/importers/importers.cpp @@ -32,8 +32,7 @@ void ImportersInit() importers.push_back(make_unique()); } -int ImportSCFromProg(const string &path, string &name, const string &program, - Json &res) +int ImportSCFromProg(const string &path, string &name, const string &program, Json &res) { if (!os_file_exists(path.c_str())) { return IMPORTER_FILE_NOT_FOUND; diff --git a/UI/importers/importers.hpp b/UI/importers/importers.hpp index b129cba12..8160f793e 100644 --- a/UI/importers/importers.hpp +++ b/UI/importers/importers.hpp @@ -41,8 +41,7 @@ class Importer { public: virtual ~Importer() {} virtual std::string Prog() { return "Null"; }; - virtual int ImportScenes(const std::string &path, std::string &name, - json11::Json &res) = 0; + virtual int ImportScenes(const std::string &path, std::string &name, json11::Json &res) = 0; virtual bool Check(const std::string &path) = 0; virtual std::string Name(const std::string &path) = 0; virtual OBSImporterFiles FindFiles() @@ -55,8 +54,7 @@ public: class ClassicImporter : public Importer { public: std::string Prog() { return "OBSClassic"; }; - int ImportScenes(const std::string &path, std::string &name, - json11::Json &res); + int ImportScenes(const std::string &path, std::string &name, json11::Json &res); bool Check(const std::string &path); std::string Name(const std::string &path); OBSImporterFiles FindFiles(); @@ -65,8 +63,7 @@ public: class StudioImporter : public Importer { public: std::string Prog() { return "OBSStudio"; }; - int ImportScenes(const std::string &path, std::string &name, - json11::Json &res); + int ImportScenes(const std::string &path, std::string &name, json11::Json &res); bool Check(const std::string &path); std::string Name(const std::string &path); }; @@ -74,8 +71,7 @@ public: class SLImporter : public Importer { public: std::string Prog() { return "Streamlabs"; }; - int ImportScenes(const std::string &path, std::string &name, - json11::Json &res); + int ImportScenes(const std::string &path, std::string &name, json11::Json &res); bool Check(const std::string &path); std::string Name(const std::string &path); OBSImporterFiles FindFiles(); @@ -84,8 +80,7 @@ public: class XSplitImporter : public Importer { public: std::string Prog() { return "XSplitBroadcaster"; }; - int ImportScenes(const std::string &path, std::string &name, - json11::Json &res); + int ImportScenes(const std::string &path, std::string &name, json11::Json &res); bool Check(const std::string &path); std::string Name(const std::string &) { return "XSplit Import"; }; OBSImporterFiles FindFiles(); @@ -96,8 +91,7 @@ void ImportersInit(); std::string DetectProgram(const std::string &path); std::string GetSCName(const std::string &path, const std::string &prog); -int ImportSCFromProg(const std::string &path, std::string &name, - const std::string &program, json11::Json &res); +int ImportSCFromProg(const std::string &path, std::string &name, const std::string &program, json11::Json &res); int ImportSC(const std::string &path, std::string &name, json11::Json &res); OBSImporterFiles ImportersFindFiles(); @@ -135,9 +129,7 @@ static inline std::string GetFolderFromPath(const std::string &path) return path.substr(0, pos + 1); } -static inline std::string StringReplace(const std::string &in, - const std::string &search, - const std::string &rep) +static inline std::string StringReplace(const std::string &in, const std::string &search, const std::string &rep) { std::string res = in; size_t pos; diff --git a/UI/importers/sl.cpp b/UI/importers/sl.cpp index 21c0e8da2..ac8e473ef 100644 --- a/UI/importers/sl.cpp +++ b/UI/importers/sl.cpp @@ -90,10 +90,8 @@ static string translate_hotkey(const Json &hotkey, const string &source) return out + source; \ } - add_translation(name, "TOGGLE_SOURCE_VISIBILITY_SHOW", - "libobs.show_scene_item.", source); - add_translation(name, "TOGGLE_SOURCE_VISIBILITY_HIDE", - "libobs.hide_scene_item.", source); + add_translation(name, "TOGGLE_SOURCE_VISIBILITY_SHOW", "libobs.show_scene_item.", source); + add_translation(name, "TOGGLE_SOURCE_VISIBILITY_HIDE", "libobs.hide_scene_item.", source); string empty = ""; @@ -103,8 +101,7 @@ static string translate_hotkey(const Json &hotkey, const string &source) add_translation(name, "TOGGLE_UNMUTE", "libobs.unmute", empty); add_translation(name, "PUSH_TO_MUTE", "libobs.push-to-mute", empty); add_translation(name, "PUSH_TO_TALK", "libobs.push-to-talk", empty); - add_translation(name, "GAME_CAPTURE_HOTKEY_START", "hotkey_start", - empty); + add_translation(name, "GAME_CAPTURE_HOTKEY_START", "hotkey_start", empty); add_translation(name, "GAME_CAPTURE_HOTKEY_STOP", "hotkey_stop", empty); return ""; @@ -124,9 +121,7 @@ static bool source_name_exists(const Json::array &sources, const string &name) return false; } -static string get_source_name_from_id(const Json &root, - const Json::array &sources, - const string &id) +static string get_source_name_from_id(const Json &root, const Json::array &sources, const string &id) { for (size_t i = 0; i < sources.size(); i++) { Json item = sources[i]; @@ -158,8 +153,7 @@ static string get_source_name_from_id(const Json &root, return ""; } -static void get_hotkey_bindings(Json::object &out_hotkeys, - const Json &in_hotkeys, const string &name) +static void get_hotkey_bindings(Json::object &out_hotkeys, const Json &in_hotkeys, const string &name) { Json::array hot_arr = in_hotkeys.array_items(); for (size_t i = 0; i < hot_arr.size(); i++) { @@ -173,26 +167,24 @@ static void get_hotkey_bindings(Json::object &out_hotkeys, Json binding = bindings[x]; Json modifiers = binding["modifiers"]; - string key = - translate_key(binding["key"].string_value()); + string key = translate_key(binding["key"].string_value()); if (key == "IGNORE") continue; - out_hotkey.push_back( - Json::object{{"control", modifiers["ctrl"]}, - {"shift", modifiers["shift"]}, - {"command", modifiers["meta"]}, - {"alt", modifiers["alt"]}, - {"key", key}}); + out_hotkey.push_back(Json::object{{"control", modifiers["ctrl"]}, + {"shift", modifiers["shift"]}, + {"command", modifiers["meta"]}, + {"alt", modifiers["alt"]}, + {"key", key}}); } out_hotkeys[hotkey_name] = out_hotkey; } } -static void get_scene_items(const Json &root, const Json::array &out_sources, - Json::object &scene, const Json::array &in) +static void get_scene_items(const Json &root, const Json::array &out_sources, Json::object &scene, + const Json::array &in) { int length = 0; @@ -206,35 +198,29 @@ static void get_scene_items(const Json &root, const Json::array &out_sources, string id = item["sourceId"].string_value(); string name = get_source_name_from_id(root, out_sources, id); - Json::array hotkey_items = - item["hotkeys"]["items"].array_items(); + Json::array hotkey_items = item["hotkeys"]["items"].array_items(); get_hotkey_bindings(hotkeys, hotkey_items, name); - out_items.push_back(Json::object{ - {"name", name}, - {"id", length++}, - {"pos", - Json::object{{"x", item["x"]}, {"y", item["y"]}}}, - {"scale", Json::object{{"x", item["scaleX"]}, - {"y", item["scaleY"]}}}, - {"rot", item["rotation"]}, - {"visible", item["visible"]}, - {"crop_top", in_crop["top"]}, - {"crop_bottom", in_crop["bottom"]}, - {"crop_left", in_crop["left"]}, - {"crop_right", in_crop["right"]}}); + out_items.push_back(Json::object{{"name", name}, + {"id", length++}, + {"pos", Json::object{{"x", item["x"]}, {"y", item["y"]}}}, + {"scale", Json::object{{"x", item["scaleX"]}, {"y", item["scaleY"]}}}, + {"rot", item["rotation"]}, + {"visible", item["visible"]}, + {"crop_top", in_crop["top"]}, + {"crop_bottom", in_crop["bottom"]}, + {"crop_left", in_crop["left"]}, + {"crop_right", in_crop["right"]}}); } scene["hotkeys"] = hotkeys; - scene["settings"] = - Json::object{{"items", out_items}, {"id_counter", length}}; + scene["settings"] = Json::object{{"items", out_items}, {"id_counter", length}}; } static void translate_screen_capture(Json::object &out_settings, string &type) { - string subtype_info = - out_settings["capture_source_list"].string_value(); + string subtype_info = out_settings["capture_source_list"].string_value(); size_t pos = subtype_info.find(':'); string subtype = subtype_info.substr(0, pos); @@ -246,8 +232,7 @@ static void translate_screen_capture(Json::object &out_settings, string &type) } else if (subtype == "window") { type = "window_capture"; out_settings["cursor"] = out_settings["capture_cursor"]; - out_settings["window"] = - out_settings["capture_window_line"].string_value(); + out_settings["window"] = out_settings["capture_window_line"].string_value(); out_settings["capture_cursor"] = nullptr; } out_settings["auto_capture_rules_path"] = nullptr; @@ -272,16 +257,14 @@ static int attempt_import(const Json &root, const string &name, Json &res) Json source = source_arr[i]; Json in_hotkeys = source["hotkeys"]; - Json::array hotkey_items = - source["hotkeys"]["items"].array_items(); + Json::array hotkey_items = source["hotkeys"]["items"].array_items(); Json in_filters = source["filters"]; Json::array filter_items = in_filters["items"].array_items(); Json in_settings = source["settings"]; Json in_sync = source["syncOffset"]; - int sync = (int)(in_sync["sec"].number_value() * 1000000000 + - in_sync["nsec"].number_value()); + int sync = (int)(in_sync["sec"].number_value() * 1000000000 + in_sync["nsec"].number_value()); double vol = source["volume"].number_value(); bool muted = source["muted"].bool_value(); @@ -313,17 +296,16 @@ static int attempt_import(const Json &root, const string &name, Json &res) translate_screen_capture(out_settings, type); } - out_sources.push_back( - Json::object{{"filters", out_filters}, - {"hotkeys", out_hotkeys}, - {"id", type}, - {"sl_id", sl_id}, - {"settings", out_settings}, - {"sync", sync}, - {"volume", vol}, - {"muted", muted}, - {"name", out_name}, - {"monitoring_type", monitoring}}); + out_sources.push_back(Json::object{{"filters", out_filters}, + {"hotkeys", out_hotkeys}, + {"id", type}, + {"sl_id", sl_id}, + {"settings", out_settings}, + {"sync", sync}, + {"volume", vol}, + {"muted", muted}, + {"name", out_name}, + {"monitoring_type", monitoring}}); } string scene_name = ""; @@ -362,15 +344,10 @@ static int attempt_import(const Json &root, const string &name, Json &res) string sl_id = scene["id"].string_value(); - Json::object out = - Json::object{{"filters", out_filters}, - {"hotkeys", out_hotkeys}, - {"id", "scene"}, - {"sl_id", sl_id}, - {"settings", in_settings}, - {"volume", 1.0}, - {"name", out_name}, - {"private_settings", Json::object{}}}; + Json::object out = Json::object{{"filters", out_filters}, {"hotkeys", out_hotkeys}, + {"id", "scene"}, {"sl_id", sl_id}, + {"settings", in_settings}, {"volume", 1.0}, + {"name", out_name}, {"private_settings", Json::object{}}}; Json in_items = scene["sceneItems"]; Json::array items_arr = in_items["items"].array_items(); @@ -394,11 +371,10 @@ static int attempt_import(const Json &root, const string &name, Json &res) if (id == t_id) transition_name = name; - out_transitions.push_back( - Json::object{{"id", transition["type"]}, - {"settings", in_settings}, - {"name", name}, - {"duration", duration}}); + out_transitions.push_back(Json::object{{"id", transition["type"]}, + {"settings", in_settings}, + {"name", name}, + {"duration", duration}}); } res = Json::object{{"sources", out_sources}, @@ -420,15 +396,13 @@ string SLImporter::Name(const string &path) string manifest_path = folder + "manifest.json"; if (os_file_exists(manifest_path.c_str())) { - BPtr file_data = - os_quick_read_utf8_file(manifest_path.c_str()); + BPtr file_data = os_quick_read_utf8_file(manifest_path.c_str()); string err; Json data = Json::parse(file_data, err); if (err == "") { - Json::array collections = - data["collections"].array_items(); + Json::array collections = data["collections"].array_items(); bool name_set = false; @@ -513,8 +487,7 @@ OBSImporterFiles SLImporter::FindFiles() #if defined(_WIN32) || defined(__APPLE__) char dst[512]; - int found = - os_get_config_path(dst, 512, "slobs-client/SceneCollections/"); + int found = os_get_config_path(dst, 512, "slobs-client/SceneCollections/"); if (found == -1) return res; diff --git a/UI/importers/studio.cpp b/UI/importers/studio.cpp index 15ccf1992..6c06828ba 100644 --- a/UI/importers/studio.cpp +++ b/UI/importers/studio.cpp @@ -49,19 +49,13 @@ void TranslateOSStudio(Json &res) ClearTranslation("game_capture", "syphon-input"); - ClearTranslation("wasapi_input_capture", - "coreaudio_input_capture"); - ClearTranslation("wasapi_output_capture", - "coreaudio_output_capture"); - ClearTranslation("pulse_input_capture", - "coreaudio_input_capture"); - ClearTranslation("pulse_output_capture", - "coreaudio_output_capture"); + ClearTranslation("wasapi_input_capture", "coreaudio_input_capture"); + ClearTranslation("wasapi_output_capture", "coreaudio_output_capture"); + ClearTranslation("pulse_input_capture", "coreaudio_input_capture"); + ClearTranslation("pulse_output_capture", "coreaudio_output_capture"); - ClearTranslation("jack_output_capture", - "coreaudio_output_capture"); - ClearTranslation("alsa_input_capture", - "coreaudio_input_capture"); + ClearTranslation("jack_output_capture", "coreaudio_output_capture"); + ClearTranslation("alsa_input_capture", "coreaudio_input_capture"); ClearTranslation("dshow_input", "av_capture_input"); ClearTranslation("v4l2_input", "av_capture_input"); @@ -69,10 +63,8 @@ void TranslateOSStudio(Json &res) ClearTranslation("xcomposite_input", "window_capture"); if (id == "monitor_capture") { - if (settings["show_cursor"].is_null() && - !settings["capture_cursor"].is_null()) { - bool cursor = - settings["capture_cursor"].bool_value(); + if (settings["show_cursor"].is_null() && !settings["capture_cursor"].is_null()) { + bool cursor = settings["capture_cursor"].bool_value(); settings["show_cursor"] = cursor; } @@ -84,16 +76,12 @@ void TranslateOSStudio(Json &res) ClearTranslation("syphon-input", "game_capture"); - ClearTranslation("coreaudio_input_capture", - "wasapi_input_capture"); - ClearTranslation("coreaudio_output_capture", - "wasapi_output_capture"); + ClearTranslation("coreaudio_input_capture", "wasapi_input_capture"); + ClearTranslation("coreaudio_output_capture", "wasapi_output_capture"); ClearTranslation("pulse_input_capture", "wasapi_input_capture"); - ClearTranslation("pulse_output_capture", - "wasapi_output_capture"); + ClearTranslation("pulse_output_capture", "wasapi_output_capture"); - ClearTranslation("jack_output_capture", - "wasapi_output_capture"); + ClearTranslation("jack_output_capture", "wasapi_output_capture"); ClearTranslation("alsa_input_capture", "wasapi_input_capture"); ClearTranslation("av_capture_input", "dshow_input"); @@ -103,8 +91,7 @@ void TranslateOSStudio(Json &res) if (id == "monitor_capture" || id == "xshm_input") { if (!settings["show_cursor"].is_null()) { - bool cursor = - settings["show_cursor"].bool_value(); + bool cursor = settings["show_cursor"].bool_value(); settings["capture_cursor"] = cursor; } @@ -114,13 +101,10 @@ void TranslateOSStudio(Json &res) #else DirectTranslation("text_gdiplus", "text_ft2_source"); - ClearTranslation("coreaudio_input_capture", - "pulse_input_capture"); - ClearTranslation("coreaudio_output_capture", - "pulse_output_capture"); + ClearTranslation("coreaudio_input_capture", "pulse_input_capture"); + ClearTranslation("coreaudio_output_capture", "pulse_output_capture"); ClearTranslation("wasapi_input_capture", "pulse_input_capture"); - ClearTranslation("wasapi_output_capture", - "pulse_output_capture"); + ClearTranslation("wasapi_output_capture", "pulse_output_capture"); ClearTranslation("av_capture_input", "v4l2_input"); ClearTranslation("dshow_input", "v4l2_input"); @@ -130,10 +114,8 @@ void TranslateOSStudio(Json &res) if (id == "monitor_capture") { source["id"] = "xshm_input"; - if (settings["show_cursor"].is_null() && - !settings["capture_cursor"].is_null()) { - bool cursor = - settings["capture_cursor"].bool_value(); + if (settings["show_cursor"].is_null() && !settings["capture_cursor"].is_null()) { + bool cursor = settings["capture_cursor"].bool_value(); settings["show_cursor"] = cursor; } @@ -158,8 +140,7 @@ static string CheckPath(const string &path, const string &rootDir) char absPath[512]; *absPath = 0; - size_t len = os_get_abs_path((rootDir + path).c_str(), absPath, - sizeof(absPath)); + size_t len = os_get_abs_path((rootDir + path).c_str(), absPath, sizeof(absPath)); if (len == 0) return path; @@ -185,8 +166,7 @@ void TranslatePaths(Json &res, const string &rootDir) if (val.string_value().rfind("./", 0) != 0) continue; - out[it->first] = - CheckPath(val.string_value(), rootDir); + out[it->first] = CheckPath(val.string_value(), rootDir); } else if (val.is_array() || val.is_object()) { TranslatePaths(val, rootDir); out[it->first] = val; diff --git a/UI/importers/xsplit.cpp b/UI/importers/xsplit.cpp index 4e5f0bba6..516da73ed 100644 --- a/UI/importers/xsplit.cpp +++ b/UI/importers/xsplit.cpp @@ -74,17 +74,15 @@ static Json::object parse_text(QString &config) Json font = Json::object{{"face", data["fontStyle"]}, {"size", 200}}; - return Json::object{ - {"text", data["text"]}, - {"font", font}, - {"outline", out > 0}, - {"outline_size", out}, - {"outline_color", - hex_string_to_int(data["outlineColor"].string_value())}, - {"color", hex_string_to_int(data["color"].string_value())}, - {"align", data["textAlign"]}, - {"valign", valign}, - {"alpha", data["opacity"]}}; + return Json::object{{"text", data["text"]}, + {"font", font}, + {"outline", out > 0}, + {"outline_size", out}, + {"outline_color", hex_string_to_int(data["outlineColor"].string_value())}, + {"color", hex_string_to_int(data["color"].string_value())}, + {"align", data["textAlign"]}, + {"valign", valign}, + {"alpha", data["opacity"]}}; } static Json::array parse_playlist(QString &playlist) @@ -107,8 +105,7 @@ static Json::array parse_playlist(QString &playlist) return out; } -static void parse_media_types(QDomNamedNodeMap &attr, Json::object &source, - Json::object &settings) +static void parse_media_types(QDomNamedNodeMap &attr, Json::object &source, Json::object &settings) { QString playlist = attr.namedItem("FilePlaylist").nodeValue(); @@ -143,8 +140,7 @@ static void parse_media_types(QDomNamedNodeMap &attr, Json::object &source, } } else { source["id"] = "ffmpeg_source"; - settings["local_file"] = - url.replace("\\", "/").toStdString(); + settings["local_file"] = url.replace("\\", "/").toStdString(); settings["is_local_file"] = true; } } @@ -186,8 +182,7 @@ static Json::object parse_slideshow(QString &config) return Json::object{}; return Json::object{{"randomize", opt["random"]}, - {"slide_time", - opt["delay"].number_value() * 1000 + 700}, + {"slide_time", opt["delay"].number_value() * 1000 + 700}, {"files", files_out}}; } @@ -211,8 +206,7 @@ static Json get_source_with_id(const string &src_id, const Json::array &sources) return nullptr; } -static void parse_items(QDomNode &item, Json::array &items, - Json::array &sources) +static void parse_items(QDomNode &item, Json::array &items, Json::array &sources) { while (!item.isNull()) { QDomNamedNodeMap attr = item.attributes(); @@ -245,9 +239,7 @@ static void parse_items(QDomNode &item, Json::array &items, name = temp_name; settings = Json::object{}; - source = Json::object{{"name", name}, - {"src_id", srcid.toStdString()}, - {"volume", vol}}; + source = Json::object{{"name", name}, {"src_id", srcid.toStdString()}, {"volume", vol}}; /** type=1 means Media of some kind (Video Playlist, RTSP, RTMP, NDI or Media File). @@ -270,8 +262,7 @@ static void parse_items(QDomNode &item, Json::array &items, source["id"] = "wasapi_input_capture"; int dev = audio.indexOf("\\wave:") + 6; - QString res = - "{0.0.1.00000000}." + audio.mid(dev); + QString res = "{0.0.1.00000000}." + audio.mid(dev); res = res.toLower(); settings["device_id"] = res.toStdString(); @@ -291,24 +282,18 @@ static void parse_items(QDomNode &item, Json::array &items, QDomNode el = options.documentElement(); QDomNamedNodeMap o_attr = el.attributes(); - QString display = - o_attr.namedItem("desktop").nodeValue(); + QString display = o_attr.namedItem("desktop").nodeValue(); if (!display.isEmpty()) { source["id"] = "monitor_capture"; - int cursor = attr.namedItem("ScrCapShowMouse") - .nodeValue() - .toInt(); + int cursor = attr.namedItem("ScrCapShowMouse").nodeValue().toInt(); settings["capture_cursor"] = cursor == 1; } else { source["id"] = "window_capture"; - QString exec = - o_attr.namedItem("module").nodeValue(); - QString window = - o_attr.namedItem("window").nodeValue(); - QString _class = - o_attr.namedItem("class").nodeValue(); + QString exec = o_attr.namedItem("module").nodeValue(); + QString window = o_attr.namedItem("window").nodeValue(); + QString _class = o_attr.namedItem("class").nodeValue(); int pos = exec.lastIndexOf('\\'); @@ -316,8 +301,7 @@ static void parse_items(QDomNode &item, Json::array &items, _class = "class"; } - QString res = window + ":" + _class + ":" + - exec.mid(pos + 1); + QString res = window + ":" + _class + ":" + exec.mid(pos + 1); settings["window"] = res.toStdString(); settings["priority"] = 2; @@ -335,8 +319,7 @@ static void parse_items(QDomNode &item, Json::array &items, QDomNamedNodeMap o_attr = el.attributes(); QString name = o_attr.namedItem("wndname").nodeValue(); - QString exec = - o_attr.namedItem("imagename").nodeValue(); + QString exec = o_attr.namedItem("imagename").nodeValue(); QString res = name = "::" + exec; @@ -346,8 +329,7 @@ static void parse_items(QDomNode &item, Json::array &items, } else if (type == 8) { QString plugin = attr.namedItem("item").nodeValue(); - if (plugin.startsWith( - "html:plugin:imageslideshowplg*")) { + if (plugin.startsWith("html:plugin:imageslideshowplg*")) { source["id"] = "slideshow"; settings = parse_slideshow(plugin); } else if (plugin.startsWith("html:plugin:titleplg")) { @@ -356,13 +338,11 @@ static void parse_items(QDomNode &item, Json::array &items, } else if (plugin.startsWith("http")) { source["id"] = "browser_source"; int end = plugin.indexOf('*'); - settings["url"] = - plugin.left(end).toStdString(); + settings["url"] = plugin.left(end).toStdString(); } } else if (type == 11) { QString id = attr.namedItem("item").nodeValue(); - Json source = - get_source_with_id(id.toStdString(), sources); + Json source = get_source_with_id(id.toStdString(), sources); name = source["name"].string_value(); goto skip; @@ -378,26 +358,19 @@ static void parse_items(QDomNode &item, Json::array &items, int width = ovi.base_width; int height = ovi.base_height; - double pos_left = - attr.namedItem("pos_left").nodeValue().toDouble(); - double pos_right = - attr.namedItem("pos_right").nodeValue().toDouble(); - double pos_top = - attr.namedItem("pos_top").nodeValue().toDouble(); - double pos_bottom = - attr.namedItem("pos_bottom").nodeValue().toDouble(); + double pos_left = attr.namedItem("pos_left").nodeValue().toDouble(); + double pos_right = attr.namedItem("pos_right").nodeValue().toDouble(); + double pos_top = attr.namedItem("pos_top").nodeValue().toDouble(); + double pos_bottom = attr.namedItem("pos_bottom").nodeValue().toDouble(); bool visible = attr.namedItem("visible").nodeValue() == "1"; - Json out_item = Json::object{ - {"bounds_type", 2}, - {"pos", Json::object{{"x", pos_left * width}, - {"y", pos_top * height}}}, - {"bounds", - Json::object{{"x", (pos_right - pos_left) * width}, - {"y", (pos_bottom - pos_top) * height}}}, - {"name", name}, - {"visible", visible}}; + Json out_item = Json::object{{"bounds_type", 2}, + {"pos", Json::object{{"x", pos_left * width}, {"y", pos_top * height}}}, + {"bounds", Json::object{{"x", (pos_right - pos_left) * width}, + {"y", (pos_bottom - pos_top) * height}}}, + {"name", name}, + {"visible", visible}}; items.push_back(out_item); @@ -424,10 +397,9 @@ static Json::object parse_scenes(QDomElement &scenes) if (first.isEmpty()) first = name; - Json out = Json::object{ - {"id", "scene"}, - {"name", name.toStdString().c_str()}, - {"src_id", id.toStdString().c_str()}}; + Json out = Json::object{{"id", "scene"}, + {"name", name.toStdString().c_str()}, + {"src_id", id.toStdString().c_str()}}; sources.push_back(out); } @@ -442,8 +414,7 @@ static Json::object parse_scenes(QDomElement &scenes) parse_items(firstChild, items, sources); - Json settings = Json::object{{"items", items}, - {"id_counter", (int)items.size()}}; + Json settings = Json::object{{"items", items}, {"id_counter", (int)items.size()}}; source["settings"] = settings; sources[i] = source; @@ -456,8 +427,7 @@ static Json::object parse_scenes(QDomElement &scenes) {"current_program_scene", first.toStdString()}}; } -int XSplitImporter::ImportScenes(const string &path, string &name, - json11::Json &res) +int XSplitImporter::ImportScenes(const string &path, string &name, json11::Json &res) { if (name == "") name = "XSplit Import"; @@ -516,8 +486,7 @@ OBSImporterFiles XSplitImporter::FindFiles() OBSImporterFiles res; #ifdef _WIN32 char dst[512]; - int found = os_get_program_data_path( - dst, 512, "SplitMediaLabs\\XSplit\\Presentation2.0\\"); + int found = os_get_program_data_path(dst, 512, "SplitMediaLabs\\XSplit\\Presentation2.0\\"); if (found == -1) return res; diff --git a/UI/item-widget-helpers.hpp b/UI/item-widget-helpers.hpp index 20d1affd7..599b83125 100644 --- a/UI/item-widget-helpers.hpp +++ b/UI/item-widget-helpers.hpp @@ -29,8 +29,7 @@ QListWidgetItem *TakeListItem(QListWidget *widget, int row); void DeleteListItem(QListWidget *widget, QListWidgetItem *item); void ClearListItems(QListWidget *widget); -template -void InsertQObjectByName(std::vector &controls, QObjectPtr control) +template void InsertQObjectByName(std::vector &controls, QObjectPtr control) { QString name = control->objectName(); auto finder = [name](QObjectPtr elem) { diff --git a/UI/lineedit-autoresize.cpp b/UI/lineedit-autoresize.cpp index 166cc6309..39912fe8f 100644 --- a/UI/lineedit-autoresize.cpp +++ b/UI/lineedit-autoresize.cpp @@ -2,10 +2,8 @@ LineEditAutoResize::LineEditAutoResize() : m_maxLength(32767) { - connect(this, &LineEditAutoResize::textChanged, this, - &LineEditAutoResize::checkTextLength); - connect(document()->documentLayout(), - &QAbstractTextDocumentLayout::documentSizeChanged, this, + connect(this, &LineEditAutoResize::textChanged, this, &LineEditAutoResize::checkTextLength); + connect(document()->documentLayout(), &QAbstractTextDocumentLayout::documentSizeChanged, this, &LineEditAutoResize::resizeVertically); } @@ -63,8 +61,7 @@ void LineEditAutoResize::keyPressEvent(QKeyEvent *event) * allow all. Actions that will still exceed the limit (like * Paste) can be caught in a later step. */ default: - if (toPlainText().length() >= m_maxLength && - event->modifiers() == Qt::NoModifier && + if (toPlainText().length() >= m_maxLength && event->modifiers() == Qt::NoModifier && !textCursor().hasSelection()) event->ignore(); else @@ -86,8 +83,7 @@ QString LineEditAutoResize::text() void LineEditAutoResize::setText(const QString &text) { - QMetaObject::invokeMethod(this, "SetPlainText", Qt::QueuedConnection, - Q_ARG(const QString &, text)); + QMetaObject::invokeMethod(this, "SetPlainText", Qt::QueuedConnection, Q_ARG(const QString &, text)); } void LineEditAutoResize::SetPlainText(const QString &text) diff --git a/UI/log-viewer.cpp b/UI/log-viewer.cpp index fca16551b..9ef67a69c 100644 --- a/UI/log-viewer.cpp +++ b/UI/log-viewer.cpp @@ -12,23 +12,18 @@ #include "moc_log-viewer.cpp" -OBSLogViewer::OBSLogViewer(QWidget *parent) - : QDialog(parent), - ui(new Ui::OBSLogViewer) +OBSLogViewer::OBSLogViewer(QWidget *parent) : QDialog(parent), ui(new Ui::OBSLogViewer) { - setWindowFlags(windowFlags() & Qt::WindowMaximizeButtonHint & - ~Qt::WindowContextHelpButtonHint); + setWindowFlags(windowFlags() & Qt::WindowMaximizeButtonHint & ~Qt::WindowContextHelpButtonHint); setAttribute(Qt::WA_DeleteOnClose); ui->setupUi(this); - bool showLogViewerOnStartup = config_get_bool( - App()->GetUserConfig(), "LogViewer", "ShowLogStartup"); + bool showLogViewerOnStartup = config_get_bool(App()->GetUserConfig(), "LogViewer", "ShowLogStartup"); ui->showStartup->setChecked(showLogViewerOnStartup); - const char *geom = config_get_string(App()->GetUserConfig(), - "LogViewer", "geometry"); + const char *geom = config_get_string(App()->GetUserConfig(), "LogViewer", "geometry"); if (geom != nullptr) { QByteArray ba = QByteArray::fromBase64(QByteArray(geom)); @@ -40,14 +35,12 @@ OBSLogViewer::OBSLogViewer(QWidget *parent) OBSLogViewer::~OBSLogViewer() { - config_set_string(App()->GetUserConfig(), "LogViewer", "geometry", - saveGeometry().toBase64().constData()); + config_set_string(App()->GetUserConfig(), "LogViewer", "geometry", saveGeometry().toBase64().constData()); } void OBSLogViewer::on_showStartup_clicked(bool checked) { - config_set_bool(App()->GetUserConfig(), "LogViewer", "ShowLogStartup", - checked); + config_set_bool(App()->GetUserConfig(), "LogViewer", "ShowLogStartup", checked); } extern QPointer obsLogViewer; diff --git a/UI/media-controls.cpp b/UI/media-controls.cpp index 194cfb62d..df720cc3c 100644 --- a/UI/media-controls.cpp +++ b/UI/media-controls.cpp @@ -43,9 +43,7 @@ void MediaControls::OBSMediaPrevious(void *data, calldata_t *) QMetaObject::invokeMethod(media, "UpdateSlideCounter"); } -MediaControls::MediaControls(QWidget *parent) - : QWidget(parent), - ui(new Ui::MediaControls) +MediaControls::MediaControls(QWidget *parent) : QWidget(parent), ui(new Ui::MediaControls) { ui->setupUi(this); ui->playPauseButton->setProperty("class", "icon-media-play"); @@ -54,47 +52,36 @@ MediaControls::MediaControls(QWidget *parent) ui->stopButton->setProperty("class", "icon-media-stop"); setFocusPolicy(Qt::StrongFocus); - connect(&mediaTimer, &QTimer::timeout, this, - &MediaControls::SetSliderPosition); - connect(&seekTimer, &QTimer::timeout, this, - &MediaControls::SeekTimerCallback); - connect(ui->slider, &AbsoluteSlider::sliderPressed, this, - &MediaControls::AbsoluteSliderClicked); - connect(ui->slider, &AbsoluteSlider::absoluteSliderHovered, this, - &MediaControls::AbsoluteSliderHovered); - connect(ui->slider, &AbsoluteSlider::sliderReleased, this, - &MediaControls::AbsoluteSliderReleased); - connect(ui->slider, &AbsoluteSlider::sliderMoved, this, - &MediaControls::AbsoluteSliderMoved); + connect(&mediaTimer, &QTimer::timeout, this, &MediaControls::SetSliderPosition); + connect(&seekTimer, &QTimer::timeout, this, &MediaControls::SeekTimerCallback); + connect(ui->slider, &AbsoluteSlider::sliderPressed, this, &MediaControls::AbsoluteSliderClicked); + connect(ui->slider, &AbsoluteSlider::absoluteSliderHovered, this, &MediaControls::AbsoluteSliderHovered); + connect(ui->slider, &AbsoluteSlider::sliderReleased, this, &MediaControls::AbsoluteSliderReleased); + connect(ui->slider, &AbsoluteSlider::sliderMoved, this, &MediaControls::AbsoluteSliderMoved); - countDownTimer = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "MediaControlsCountdownTimer"); + countDownTimer = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MediaControlsCountdownTimer"); QAction *restartAction = new QAction(this); restartAction->setShortcutContext(Qt::WidgetWithChildrenShortcut); restartAction->setShortcut({Qt::Key_R}); - connect(restartAction, &QAction::triggered, this, - &MediaControls::RestartMedia); + connect(restartAction, &QAction::triggered, this, &MediaControls::RestartMedia); addAction(restartAction); QAction *sliderFoward = new QAction(this); sliderFoward->setShortcutContext(Qt::WidgetWithChildrenShortcut); - connect(sliderFoward, &QAction::triggered, this, - &MediaControls::MoveSliderFoward); + connect(sliderFoward, &QAction::triggered, this, &MediaControls::MoveSliderFoward); sliderFoward->setShortcut({Qt::Key_Right}); addAction(sliderFoward); QAction *sliderBack = new QAction(this); sliderBack->setShortcutContext(Qt::WidgetWithChildrenShortcut); - connect(sliderBack, &QAction::triggered, this, - &MediaControls::MoveSliderBackwards); + connect(sliderBack, &QAction::triggered, this, &MediaControls::MoveSliderBackwards); sliderBack->setShortcut({Qt::Key_Left}); addAction(sliderBack); QAction *playPause = new QAction(this); playPause->setShortcutContext(Qt::WidgetWithChildrenShortcut); - connect(playPause, &QAction::triggered, this, - &MediaControls::on_playPauseButton_clicked); + connect(playPause, &QAction::triggered, this, &MediaControls::on_playPauseButton_clicked); playPause->setShortcut({Qt::Key_Space}); addAction(playPause); } @@ -216,8 +203,7 @@ void MediaControls::SetPlayingState() ui->playPauseButton->setProperty("class", "icon-media-pause"); ui->playPauseButton->style()->unpolish(ui->playPauseButton); ui->playPauseButton->style()->polish(ui->playPauseButton); - ui->playPauseButton->setToolTip( - QTStr("ContextBar.MediaControls.PauseMedia")); + ui->playPauseButton->setToolTip(QTStr("ContextBar.MediaControls.PauseMedia")); prevPaused = false; @@ -230,8 +216,7 @@ void MediaControls::SetPausedState() ui->playPauseButton->setProperty("class", "icon-media-play"); ui->playPauseButton->style()->unpolish(ui->playPauseButton); ui->playPauseButton->style()->polish(ui->playPauseButton); - ui->playPauseButton->setToolTip( - QTStr("ContextBar.MediaControls.PlayMedia")); + ui->playPauseButton->setToolTip(QTStr("ContextBar.MediaControls.PlayMedia")); StopMediaTimer(); } @@ -241,8 +226,7 @@ void MediaControls::SetRestartState() ui->playPauseButton->setProperty("class", "icon-media-restart"); ui->playPauseButton->style()->unpolish(ui->playPauseButton); ui->playPauseButton->style()->polish(ui->playPauseButton); - ui->playPauseButton->setToolTip( - QTStr("ContextBar.MediaControls.RestartMedia")); + ui->playPauseButton->setToolTip(QTStr("ContextBar.MediaControls.RestartMedia")); ui->slider->setValue(0); @@ -354,8 +338,7 @@ void MediaControls::SetSliderPosition() float sliderPosition; if (duration) - sliderPosition = - (time / duration) * (float)ui->slider->maximum(); + sliderPosition = (time / duration) * (float)ui->slider->maximum(); else sliderPosition = 0.0f; @@ -465,8 +448,7 @@ void MediaControls::on_durationLabel_clicked() { countDownTimer = !countDownTimer; - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "MediaControlsCountdownTimer", countDownTimer); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "MediaControlsCountdownTimer", countDownTimer); if (MediaPaused()) SetSliderPosition(); @@ -544,10 +526,7 @@ void MediaControls::UpdateLabels(int val) ui->timerLabel->setText(FormatSeconds((int)(time / 1000.0f))); if (!countDownTimer) - ui->durationLabel->setText( - FormatSeconds((int)(duration / 1000.0f))); + ui->durationLabel->setText(FormatSeconds((int)(duration / 1000.0f))); else - ui->durationLabel->setText( - QString("-") + - FormatSeconds((int)((duration - time) / 1000.0f))); + ui->durationLabel->setText(QString("-") + FormatSeconds((int)((duration - time) / 1000.0f))); } diff --git a/UI/menu-button.hpp b/UI/menu-button.hpp index ab1c1497e..fceceb8ba 100644 --- a/UI/menu-button.hpp +++ b/UI/menu-button.hpp @@ -10,14 +10,7 @@ protected: void keyPressEvent(QKeyEvent *event) override; public: - explicit inline MenuButton(QWidget *parent = nullptr) - : QPushButton(parent) - { - } + explicit inline MenuButton(QWidget *parent = nullptr) : QPushButton(parent) {} - explicit inline MenuButton(const QString &text, - QWidget *parent = nullptr) - : QPushButton(text, parent) - { - } + explicit inline MenuButton(const QString &text, QWidget *parent = nullptr) : QPushButton(text, parent) {} }; diff --git a/UI/models/multitrack-video.hpp b/UI/models/multitrack-video.hpp index 535da6579..aad4434ce 100644 --- a/UI/models/multitrack-video.hpp +++ b/UI/models/multitrack-video.hpp @@ -47,18 +47,16 @@ template struct nlohmann::adl_serializer> { } }; -NLOHMANN_JSON_SERIALIZE_ENUM(obs_scale_type, - { - {OBS_SCALE_DISABLE, "OBS_SCALE_DISABLE"}, - {OBS_SCALE_POINT, "OBS_SCALE_POINT"}, - {OBS_SCALE_BICUBIC, "OBS_SCALE_BICUBIC"}, - {OBS_SCALE_BILINEAR, "OBS_SCALE_BILINEAR"}, - {OBS_SCALE_LANCZOS, "OBS_SCALE_LANCZOS"}, - {OBS_SCALE_AREA, "OBS_SCALE_AREA"}, - }) +NLOHMANN_JSON_SERIALIZE_ENUM(obs_scale_type, { + {OBS_SCALE_DISABLE, "OBS_SCALE_DISABLE"}, + {OBS_SCALE_POINT, "OBS_SCALE_POINT"}, + {OBS_SCALE_BICUBIC, "OBS_SCALE_BICUBIC"}, + {OBS_SCALE_BILINEAR, "OBS_SCALE_BILINEAR"}, + {OBS_SCALE_LANCZOS, "OBS_SCALE_LANCZOS"}, + {OBS_SCALE_AREA, "OBS_SCALE_AREA"}, + }) -NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(media_frames_per_second, numerator, - denominator) +NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE(media_frames_per_second, numerator, denominator) namespace GoLiveApi { using std::string; @@ -79,8 +77,7 @@ struct Cpu { optional speed; optional name; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(Cpu, physical_cores, logical_cores, - speed, name) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(Cpu, physical_cores, logical_cores, speed, name) }; struct Memory { @@ -98,9 +95,8 @@ struct Gpu { uint64_t shared_system_memory; optional driver_version; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(Gpu, model, vendor_id, device_id, - dedicated_video_memory, - shared_system_memory, driver_version) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(Gpu, model, vendor_id, device_id, dedicated_video_memory, shared_system_memory, + driver_version) }; struct GamingFeatures { @@ -111,10 +107,8 @@ struct GamingFeatures { optional game_mode_enabled; optional hags_enabled; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(GamingFeatures, game_bar_enabled, - game_dvr_allowed, game_dvr_enabled, - game_dvr_bg_recording, game_mode_enabled, - hags_enabled) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(GamingFeatures, game_bar_enabled, game_dvr_allowed, game_dvr_enabled, + game_dvr_bg_recording, game_mode_enabled, hags_enabled) }; struct System { @@ -127,8 +121,7 @@ struct System { bool arm; bool armEmulation; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(System, version, name, build, release, - revision, bits, arm, armEmulation) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(System, version, name, build, release, revision, bits, arm, armEmulation) }; struct Capabilities { @@ -138,8 +131,7 @@ struct Capabilities { System system; optional> gpu; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(Capabilities, cpu, memory, - gaming_features, system, gpu) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(Capabilities, cpu, memory, gaming_features, system, gpu) }; struct Preferences { @@ -153,10 +145,8 @@ struct Preferences { uint32_t canvas_height; optional composition_gpu_index; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(Preferences, maximum_aggregate_bitrate, - maximum_video_tracks, vod_track_audio, - width, height, framerate, canvas_width, - canvas_height, composition_gpu_index) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(Preferences, maximum_aggregate_bitrate, maximum_video_tracks, vod_track_audio, + width, height, framerate, canvas_width, canvas_height, composition_gpu_index) }; struct PostData { @@ -168,8 +158,7 @@ struct PostData { Capabilities capabilities; Preferences preferences; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(PostData, service, schema_version, - authentication, client, capabilities, + NLOHMANN_DEFINE_TYPE_INTRUSIVE(PostData, service, schema_version, authentication, client, capabilities, preferences) }; @@ -190,13 +179,12 @@ enum struct StatusResult { Error, }; -NLOHMANN_JSON_SERIALIZE_ENUM(StatusResult, - { - {StatusResult::Unknown, nullptr}, - {StatusResult::Success, "success"}, - {StatusResult::Warning, "warning"}, - {StatusResult::Error, "error"}, - }) +NLOHMANN_JSON_SERIALIZE_ENUM(StatusResult, { + {StatusResult::Unknown, nullptr}, + {StatusResult::Success, "success"}, + {StatusResult::Warning, "warning"}, + {StatusResult::Error, "error"}, + }) struct Status { StatusResult result = StatusResult::Unknown; @@ -209,9 +197,7 @@ struct IngestEndpoint { string url_template; optional authentication; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(IngestEndpoint, protocol, - url_template, - authentication) + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(IngestEndpoint, protocol, url_template, authentication) }; struct VideoEncoderConfiguration { @@ -222,10 +208,8 @@ struct VideoEncoderConfiguration { optional gpu_scale_type; json settings; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(VideoEncoderConfiguration, - type, width, height, - framerate, gpu_scale_type, - settings) + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(VideoEncoderConfiguration, type, width, height, framerate, + gpu_scale_type, settings) }; struct AudioEncoderConfiguration { @@ -234,16 +218,14 @@ struct AudioEncoderConfiguration { uint32_t channels; json settings; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(AudioEncoderConfiguration, codec, - track_id, channels, settings) + NLOHMANN_DEFINE_TYPE_INTRUSIVE(AudioEncoderConfiguration, codec, track_id, channels, settings) }; struct AudioConfigurations { std::vector live; optional> vod; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(AudioConfigurations, live, - vod) + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(AudioConfigurations, live, vod) }; struct Config { @@ -253,9 +235,7 @@ struct Config { std::vector encoder_configurations; AudioConfigurations audio_configurations; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Config, meta, status, - ingest_endpoints, - encoder_configurations, + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(Config, meta, status, ingest_endpoints, encoder_configurations, audio_configurations) }; } // namespace GoLiveApi diff --git a/UI/multitrack-video-error.cpp b/UI/multitrack-video-error.cpp index 1786131c6..8f4b478b4 100644 --- a/UI/multitrack-video-error.cpp +++ b/UI/multitrack-video-error.cpp @@ -19,21 +19,17 @@ MultitrackVideoError MultitrackVideoError::cancel() return {Type::Cancel, {}}; } -bool MultitrackVideoError::ShowDialog( - QWidget *parent, const QString &multitrack_video_name) const +bool MultitrackVideoError::ShowDialog(QWidget *parent, const QString &multitrack_video_name) const { QMessageBox mb(parent); mb.setTextFormat(Qt::RichText); mb.setWindowTitle(QTStr("Output.StartStreamFailed")); if (type == Type::Warning) { - mb.setText( - error + - QTStr("FailedToStartStream.WarningRetryNonMultitrackVideo") - .arg(multitrack_video_name)); + mb.setText(error + + QTStr("FailedToStartStream.WarningRetryNonMultitrackVideo").arg(multitrack_video_name)); mb.setIcon(QMessageBox::Warning); - QAbstractButton *yesButton = - mb.addButton(QTStr("Yes"), QMessageBox::YesRole); + QAbstractButton *yesButton = mb.addButton(QTStr("Yes"), QMessageBox::YesRole); mb.addButton(QTStr("No"), QMessageBox::NoRole); mb.exec(); @@ -41,8 +37,7 @@ bool MultitrackVideoError::ShowDialog( } else if (type == Type::Critical) { mb.setText(error); mb.setIcon(QMessageBox::Critical); - mb.setStandardButtons( - QMessageBox::StandardButton::Ok); // cannot continue + mb.setStandardButtons(QMessageBox::StandardButton::Ok); // cannot continue mb.exec(); } diff --git a/UI/multitrack-video-error.hpp b/UI/multitrack-video-error.hpp index cbffb4254..7ce79fe72 100644 --- a/UI/multitrack-video-error.hpp +++ b/UI/multitrack-video-error.hpp @@ -8,8 +8,7 @@ struct MultitrackVideoError { static MultitrackVideoError warning(QString error); static MultitrackVideoError cancel(); - bool ShowDialog(QWidget *parent, - const QString &multitrack_video_name) const; + bool ShowDialog(QWidget *parent, const QString &multitrack_video_name) const; enum struct Type { Critical, diff --git a/UI/multitrack-video-output.cpp b/UI/multitrack-video-output.cpp index a58de5e22..8dc6fc2e8 100644 --- a/UI/multitrack-video-output.cpp +++ b/UI/multitrack-video-output.cpp @@ -40,9 +40,7 @@ Qt::ConnectionType BlockingConnectionTypeFor(QObject *object) { - return object->thread() == QThread::currentThread() - ? Qt::DirectConnection - : Qt::BlockingQueuedConnection; + return object->thread() == QThread::currentThread() ? Qt::DirectConnection : Qt::BlockingQueuedConnection; } bool MultitrackVideoDeveloperModeEnabled() @@ -59,10 +57,8 @@ bool MultitrackVideoDeveloperModeEnabled() return developer_mode; } -static OBSServiceAutoRelease -create_service(const GoLiveApi::Config &go_live_config, - const std::optional &rtmp_url, - const QString &in_stream_key) +static OBSServiceAutoRelease create_service(const GoLiveApi::Config &go_live_config, + const std::optional &rtmp_url, const QString &in_stream_key) { const char *url = nullptr; QString stream_key = in_stream_key; @@ -74,12 +70,9 @@ create_service(const GoLiveApi::Config &go_live_config, continue; url = endpoint.url_template.c_str(); - if (endpoint.authentication && - !endpoint.authentication->empty()) { - blog(LOG_INFO, - "Using stream key supplied by autoconfig"); - stream_key = QString::fromStdString( - *endpoint.authentication); + if (endpoint.authentication && !endpoint.authentication->empty()) { + blog(LOG_INFO, "Using stream key supplied by autoconfig"); + stream_key = QString::fromStdString(*endpoint.authentication); } break; } @@ -87,8 +80,7 @@ create_service(const GoLiveApi::Config &go_live_config, if (rtmp_url.has_value()) { // Despite being set by user, it was set to a "" if (rtmp_url->empty()) { - throw MultitrackVideoError::warning(QTStr( - "FailedToStartStream.NoCustomRTMPURLInSettings")); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.NoCustomRTMPURLInSettings")); } url = rtmp_url->c_str(); @@ -96,8 +88,7 @@ create_service(const GoLiveApi::Config &go_live_config, } else { if (!url) { blog(LOG_ERROR, "No RTMP URL in go live config"); - throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.NoRTMPURLInConfig")); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.NoRTMPURLInConfig")); } blog(LOG_INFO, "Using URL template: '%s'", url); @@ -111,8 +102,7 @@ create_service(const GoLiveApi::Config &go_live_config, if (!dstr_is_empty(str)) { auto found = dstr_find(str, "/{stream_key}"); if (found) - dstr_remove(str, found - str->array, - str->len - (found - str->array)); + dstr_remove(str, found - str->array, str->len - (found - str->array)); } /* The stream key itself may contain query parameters, such as @@ -129,25 +119,20 @@ create_service(const GoLiveApi::Config &go_live_config, parsed_query.addQueryItem(key, value); if (!go_live_config.meta.config_id.empty()) { - parsed_query.addQueryItem( - "clientConfigId", - QString::fromStdString(go_live_config.meta.config_id)); + parsed_query.addQueryItem("clientConfigId", QString::fromStdString(go_live_config.meta.config_id)); } parsed_key.setQuery(parsed_query); OBSDataAutoRelease settings = obs_data_create(); obs_data_set_string(settings, "server", str->array); - obs_data_set_string(settings, "key", - parsed_key.toString().toUtf8().constData()); + obs_data_set_string(settings, "key", parsed_key.toString().toUtf8().constData()); - auto service = obs_service_create( - "rtmp_custom", "multitrack video service", settings, nullptr); + auto service = obs_service_create("rtmp_custom", "multitrack video service", settings, nullptr); if (!service) { blog(LOG_WARNING, "Failed to create multitrack video service"); - throw MultitrackVideoError::warning(QTStr( - "FailedToStartStream.FailedToCreateMultitrackVideoService")); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.FailedToCreateMultitrackVideoService")); } return service; @@ -155,14 +140,11 @@ create_service(const GoLiveApi::Config &go_live_config, static OBSOutputAutoRelease create_output() { - OBSOutputAutoRelease output = obs_output_create( - "rtmp_output", "rtmp multitrack video", nullptr, nullptr); + OBSOutputAutoRelease output = obs_output_create("rtmp_output", "rtmp multitrack video", nullptr, nullptr); if (!output) { - blog(LOG_ERROR, - "Failed to create multitrack video rtmp output"); - throw MultitrackVideoError::warning(QTStr( - "FailedToStartStream.FailedToCreateMultitrackVideoOutput")); + blog(LOG_ERROR, "Failed to create multitrack video rtmp output"); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.FailedToCreateMultitrackVideoOutput")); } return output; @@ -174,81 +156,65 @@ static OBSOutputAutoRelease create_recording_output(obs_data_t *settings) bool useMP4 = obs_data_get_bool(settings, "use_mp4"); if (useMP4) { - output = obs_output_create("mp4_output", "mp4 multitrack video", - settings, nullptr); + output = obs_output_create("mp4_output", "mp4 multitrack video", settings, nullptr); } else { - output = obs_output_create("flv_output", "flv multitrack video", - settings, nullptr); + output = obs_output_create("flv_output", "flv multitrack video", settings, nullptr); } if (!output) { - blog(LOG_ERROR, "Failed to create multitrack video %s output", - useMP4 ? "mp4" : "flv"); + blog(LOG_ERROR, "Failed to create multitrack video %s output", useMP4 ? "mp4" : "flv"); } return output; } -static void adjust_video_encoder_scaling( - const obs_video_info &ovi, obs_encoder_t *video_encoder, - const GoLiveApi::VideoEncoderConfiguration &encoder_config, - size_t encoder_index) +static void adjust_video_encoder_scaling(const obs_video_info &ovi, obs_encoder_t *video_encoder, + const GoLiveApi::VideoEncoderConfiguration &encoder_config, + size_t encoder_index) { auto requested_width = encoder_config.width; auto requested_height = encoder_config.height; - if (ovi.output_width == requested_width || - ovi.output_height == requested_height) + if (ovi.output_width == requested_width || ovi.output_height == requested_height) return; - if (ovi.base_width < requested_width || - ovi.base_height < requested_height) { + if (ovi.base_width < requested_width || ovi.base_height < requested_height) { blog(LOG_WARNING, - "Requested resolution exceeds canvas/available resolution for encoder %zu: %" PRIu32 - "x%" PRIu32 " > %" PRIu32 "x%" PRIu32, - encoder_index, requested_width, requested_height, - ovi.base_width, ovi.base_height); + "Requested resolution exceeds canvas/available resolution for encoder %zu: %" PRIu32 "x%" PRIu32 + " > %" PRIu32 "x%" PRIu32, + encoder_index, requested_width, requested_height, ovi.base_width, ovi.base_height); } - obs_encoder_set_scaled_size(video_encoder, requested_width, - requested_height); - obs_encoder_set_gpu_scale_type( - video_encoder, - encoder_config.gpu_scale_type.value_or(OBS_SCALE_BICUBIC)); - obs_encoder_set_preferred_video_format(video_encoder, - VIDEO_FORMAT_NV12); + obs_encoder_set_scaled_size(video_encoder, requested_width, requested_height); + obs_encoder_set_gpu_scale_type(video_encoder, encoder_config.gpu_scale_type.value_or(OBS_SCALE_BICUBIC)); + obs_encoder_set_preferred_video_format(video_encoder, VIDEO_FORMAT_NV12); } -static uint32_t closest_divisor(const obs_video_info &ovi, - const media_frames_per_second &target_fps) +static uint32_t closest_divisor(const obs_video_info &ovi, const media_frames_per_second &target_fps) { auto target = (uint64_t)target_fps.numerator * ovi.fps_den; auto source = (uint64_t)ovi.fps_num * target_fps.denominator; return std::max(1u, static_cast(source / target)); } -static void adjust_encoder_frame_rate_divisor( - const obs_video_info &ovi, obs_encoder_t *video_encoder, - const GoLiveApi::VideoEncoderConfiguration &encoder_config, - const size_t encoder_index) +static void adjust_encoder_frame_rate_divisor(const obs_video_info &ovi, obs_encoder_t *video_encoder, + const GoLiveApi::VideoEncoderConfiguration &encoder_config, + const size_t encoder_index) { if (!encoder_config.framerate) { - blog(LOG_WARNING, "`framerate` not specified for encoder %zu", - encoder_index); + blog(LOG_WARNING, "`framerate` not specified for encoder %zu", encoder_index); return; } media_frames_per_second requested_fps = *encoder_config.framerate; - if (ovi.fps_num == requested_fps.numerator && - ovi.fps_den == requested_fps.denominator) + if (ovi.fps_num == requested_fps.numerator && ovi.fps_den == requested_fps.denominator) return; auto divisor = closest_divisor(ovi, requested_fps); if (divisor <= 1) return; - blog(LOG_INFO, "Setting frame rate divisor to %u for encoder %zu", - divisor, encoder_index); + blog(LOG_INFO, "Setting frame rate divisor to %u for encoder %zu", divisor, encoder_index); obs_encoder_set_frame_rate_divisor(video_encoder, divisor); } @@ -264,66 +230,50 @@ static bool encoder_available(const char *type) return false; } -static OBSEncoderAutoRelease -create_video_encoder(DStr &name_buffer, size_t encoder_index, - const GoLiveApi::VideoEncoderConfiguration &encoder_config) +static OBSEncoderAutoRelease create_video_encoder(DStr &name_buffer, size_t encoder_index, + const GoLiveApi::VideoEncoderConfiguration &encoder_config) { auto encoder_type = encoder_config.type.c_str(); if (!encoder_available(encoder_type)) { - blog(LOG_ERROR, "Encoder type '%s' not available", - encoder_type); - throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.EncoderNotAvailable") - .arg(encoder_type)); + blog(LOG_ERROR, "Encoder type '%s' not available", encoder_type); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.EncoderNotAvailable").arg(encoder_type)); } - dstr_printf(name_buffer, "multitrack video video encoder %zu", - encoder_index); + dstr_printf(name_buffer, "multitrack video video encoder %zu", encoder_index); - OBSDataAutoRelease encoder_settings = obs_data_create_from_json( - encoder_config.settings.dump().c_str()); + OBSDataAutoRelease encoder_settings = obs_data_create_from_json(encoder_config.settings.dump().c_str()); obs_data_set_bool(encoder_settings, "disable_scenecut", true); - OBSEncoderAutoRelease video_encoder = obs_video_encoder_create( - encoder_type, name_buffer, encoder_settings, nullptr); + OBSEncoderAutoRelease video_encoder = + obs_video_encoder_create(encoder_type, name_buffer, encoder_settings, nullptr); if (!video_encoder) { - blog(LOG_ERROR, "Failed to create video encoder '%s'", - name_buffer->array); + blog(LOG_ERROR, "Failed to create video encoder '%s'", name_buffer->array); throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.FailedToCreateVideoEncoder") - .arg(name_buffer->array, encoder_type)); + QTStr("FailedToStartStream.FailedToCreateVideoEncoder").arg(name_buffer->array, encoder_type)); } obs_encoder_set_video(video_encoder, obs_get_video()); obs_video_info ovi; if (!obs_get_video_info(&ovi)) { - blog(LOG_WARNING, - "Failed to get obs_video_info while creating encoder %zu", - encoder_index); + blog(LOG_WARNING, "Failed to get obs_video_info while creating encoder %zu", encoder_index); throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.FailedToGetOBSVideoInfo") - .arg(name_buffer->array, encoder_type)); + QTStr("FailedToStartStream.FailedToGetOBSVideoInfo").arg(name_buffer->array, encoder_type)); } - adjust_video_encoder_scaling(ovi, video_encoder, encoder_config, - encoder_index); - adjust_encoder_frame_rate_divisor(ovi, video_encoder, encoder_config, - encoder_index); + adjust_video_encoder_scaling(ovi, video_encoder, encoder_config, encoder_index); + adjust_encoder_frame_rate_divisor(ovi, video_encoder, encoder_config, encoder_index); return video_encoder; } -static OBSEncoderAutoRelease create_audio_encoder(const char *name, - const char *audio_encoder_id, - obs_data_t *settings, +static OBSEncoderAutoRelease create_audio_encoder(const char *name, const char *audio_encoder_id, obs_data_t *settings, size_t mixer_idx) { - OBSEncoderAutoRelease audio_encoder = obs_audio_encoder_create( - audio_encoder_id, name, settings, mixer_idx, nullptr); + OBSEncoderAutoRelease audio_encoder = + obs_audio_encoder_create(audio_encoder_id, name, settings, mixer_idx, nullptr); if (!audio_encoder) { blog(LOG_ERROR, "Failed to create audio encoder"); - throw MultitrackVideoError::warning(QTStr( - "FailedToStartStream.FailedToCreateAudioEncoder")); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.FailedToCreateAudioEncoder")); } obs_encoder_set_audio(audio_encoder, obs_get_audio()); return audio_encoder; @@ -333,35 +283,26 @@ struct OBSOutputs { OBSOutputAutoRelease output, recording_output; }; -static OBSOutputs -SetupOBSOutput(QWidget *parent, const QString &multitrack_video_name, - obs_data_t *dump_stream_to_file_config, - const GoLiveApi::Config &go_live_config, - std::vector &audio_encoders, - std::shared_ptr &video_encoder_group, - const char *audio_encoder_id, size_t main_audio_mixer, - std::optional vod_track_mixer); -static void SetupSignalHandlers(bool recording, MultitrackVideoOutput *self, - obs_output_t *output, OBSSignal &start, +static OBSOutputs SetupOBSOutput(QWidget *parent, const QString &multitrack_video_name, + obs_data_t *dump_stream_to_file_config, const GoLiveApi::Config &go_live_config, + std::vector &audio_encoders, + std::shared_ptr &video_encoder_group, + const char *audio_encoder_id, size_t main_audio_mixer, + std::optional vod_track_mixer); +static void SetupSignalHandlers(bool recording, MultitrackVideoOutput *self, obs_output_t *output, OBSSignal &start, OBSSignal &stop, OBSSignal &deactivate); void MultitrackVideoOutput::PrepareStreaming( - QWidget *parent, const char *service_name, obs_service_t *service, - const std::optional &rtmp_url, const QString &stream_key, - const char *audio_encoder_id, - std::optional maximum_aggregate_bitrate, - std::optional maximum_video_tracks, - std::optional custom_config, - obs_data_t *dump_stream_to_file_config, size_t main_audio_mixer, - std::optional vod_track_mixer) + QWidget *parent, const char *service_name, obs_service_t *service, const std::optional &rtmp_url, + const QString &stream_key, const char *audio_encoder_id, std::optional maximum_aggregate_bitrate, + std::optional maximum_video_tracks, std::optional custom_config, + obs_data_t *dump_stream_to_file_config, size_t main_audio_mixer, std::optional vod_track_mixer) { { const std::lock_guard current_lock{current_mutex}; - const std::lock_guard current_stream_dump_lock{ - current_stream_dump_mutex}; + const std::lock_guard current_stream_dump_lock{current_stream_dump_mutex}; if (current || current_stream_dump) { - blog(LOG_WARNING, - "Tried to prepare multitrack video output while it's already active"); + blog(LOG_WARNING, "Tried to prepare multitrack video output while it's already active"); return; } } @@ -371,20 +312,16 @@ void MultitrackVideoOutput::PrepareStreaming( auto auto_config_url = MultitrackVideoAutoConfigURL(service); OBSDataAutoRelease service_settings = obs_service_get_settings(service); - auto multitrack_video_name = - QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); - if (obs_data_has_user_value(service_settings, - "multitrack_video_name")) { - multitrack_video_name = obs_data_get_string( - service_settings, "multitrack_video_name"); + auto multitrack_video_name = QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); + if (obs_data_has_user_value(service_settings, "multitrack_video_name")) { + multitrack_video_name = obs_data_get_string(service_settings, "multitrack_video_name"); } auto auto_config_url_data = auto_config_url.toUtf8(); DStr vod_track_info_storage; if (vod_track_mixer.has_value()) - dstr_printf(vod_track_info_storage, "Yes (mixer: %zu)", - vod_track_mixer.value()); + dstr_printf(vod_track_info_storage, "Yes (mixer: %zu)", vod_track_mixer.value()); blog(LOG_INFO, "Preparing enhanced broadcasting stream for:\n" @@ -396,33 +333,22 @@ void MultitrackVideoOutput::PrepareStreaming( " max video tracks: %s (%" PRIu32 ")\n" " custom rtmp url: %s ('%s')\n" " vod track: %s", - is_custom_config ? "Yes" : "No", - !auto_config_url.isEmpty() ? auto_config_url_data.constData() - : "(null)", - service_name, - maximum_aggregate_bitrate.has_value() ? "Set" : "Auto", - maximum_aggregate_bitrate.value_or(0), - maximum_video_tracks.has_value() ? "Set" : "Auto", - maximum_video_tracks.value_or(0), - rtmp_url.has_value() ? "Yes" : "No", + is_custom_config ? "Yes" : "No", !auto_config_url.isEmpty() ? auto_config_url_data.constData() : "(null)", + service_name, maximum_aggregate_bitrate.has_value() ? "Set" : "Auto", + maximum_aggregate_bitrate.value_or(0), maximum_video_tracks.has_value() ? "Set" : "Auto", + maximum_video_tracks.value_or(0), rtmp_url.has_value() ? "Yes" : "No", rtmp_url.has_value() ? rtmp_url->c_str() : "", - vod_track_info_storage->array ? vod_track_info_storage->array - : "No"); + vod_track_info_storage->array ? vod_track_info_storage->array : "No"); - const bool custom_config_only = - auto_config_url.isEmpty() && - MultitrackVideoDeveloperModeEnabled() && - custom_config.has_value() && - strcmp(obs_service_get_id(service), "rtmp_custom") == 0; + const bool custom_config_only = auto_config_url.isEmpty() && MultitrackVideoDeveloperModeEnabled() && + custom_config.has_value() && + strcmp(obs_service_get_id(service), "rtmp_custom") == 0; if (!custom_config_only) { - auto go_live_post = constructGoLivePost( - stream_key, maximum_aggregate_bitrate, - maximum_video_tracks, vod_track_mixer.has_value()); + auto go_live_post = constructGoLivePost(stream_key, maximum_aggregate_bitrate, maximum_video_tracks, + vod_track_mixer.has_value()); - go_live_config = DownloadGoLiveConfig(parent, auto_config_url, - go_live_post, - multitrack_video_name); + go_live_config = DownloadGoLiveConfig(parent, auto_config_url, go_live_post, multitrack_video_name); } if (custom_config.has_value()) { @@ -430,38 +356,30 @@ void MultitrackVideoOutput::PrepareStreaming( try { parsed_custom = nlohmann::json::parse(*custom_config); } catch (const nlohmann::json::exception &exception) { - blog(LOG_WARNING, "Failed to parse custom config: %s", - exception.what()); - throw MultitrackVideoError::critical(QTStr( - "FailedToStartStream.InvalidCustomConfig")); + blog(LOG_WARNING, "Failed to parse custom config: %s", exception.what()); + throw MultitrackVideoError::critical(QTStr("FailedToStartStream.InvalidCustomConfig")); } // copy unique ID from go live request if (go_live_config.has_value()) { - parsed_custom.meta.config_id = - go_live_config->meta.config_id; - blog(LOG_INFO, - "Using config_id from go live config with custom config: %s", + parsed_custom.meta.config_id = go_live_config->meta.config_id; + blog(LOG_INFO, "Using config_id from go live config with custom config: %s", parsed_custom.meta.config_id.c_str()); } nlohmann::json custom_data = parsed_custom; - blog(LOG_INFO, "Using custom go live config: %s", - custom_data.dump(4).c_str()); + blog(LOG_INFO, "Using custom go live config: %s", custom_data.dump(4).c_str()); custom.emplace(std::move(parsed_custom)); } if (go_live_config.has_value()) { - blog(LOG_INFO, "Enhanced broadcasting config_id: '%s'", - go_live_config->meta.config_id.c_str()); + blog(LOG_INFO, "Enhanced broadcasting config_id: '%s'", go_live_config->meta.config_id.c_str()); } if (!go_live_config && !custom) { - blog(LOG_ERROR, - "MultitrackVideoOutput: no config set, this should never happen"); - throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.NoConfig")); + blog(LOG_ERROR, "MultitrackVideoOutput: no config set, this should never happen"); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.NoConfig")); } const auto &output_config = custom ? *custom : *go_live_config; @@ -469,24 +387,19 @@ void MultitrackVideoOutput::PrepareStreaming( std::vector audio_encoders; std::shared_ptr video_encoder_group; - auto outputs = SetupOBSOutput(parent, multitrack_video_name, - dump_stream_to_file_config, output_config, - audio_encoders, video_encoder_group, - audio_encoder_id, main_audio_mixer, + auto outputs = SetupOBSOutput(parent, multitrack_video_name, dump_stream_to_file_config, output_config, + audio_encoders, video_encoder_group, audio_encoder_id, main_audio_mixer, vod_track_mixer); auto output = std::move(outputs.output); auto recording_output = std::move(outputs.recording_output); if (!output) throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.FallbackToDefault") - .arg(multitrack_video_name)); + QTStr("FailedToStartStream.FallbackToDefault").arg(multitrack_video_name)); - auto multitrack_video_service = - create_service(service_config, rtmp_url, stream_key); + auto multitrack_video_service = create_service(service_config, rtmp_url, stream_key); if (!multitrack_video_service) throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.FallbackToDefault") - .arg(multitrack_video_name)); + QTStr("FailedToStartStream.FallbackToDefault").arg(multitrack_video_name)); obs_output_set_service(output, multitrack_video_service); @@ -496,27 +409,23 @@ void MultitrackVideoOutput::PrepareStreaming( OBSSignal start_streaming; OBSSignal stop_streaming; OBSSignal deactivate_stream; - SetupSignalHandlers(false, this, output, start_streaming, - stop_streaming, deactivate_stream); + SetupSignalHandlers(false, this, output, start_streaming, stop_streaming, deactivate_stream); if (dump_stream_to_file_config && recording_output) { OBSSignal start_recording; OBSSignal stop_recording; OBSSignal deactivate_recording; - SetupSignalHandlers(true, this, recording_output, - start_recording, stop_recording, + SetupSignalHandlers(true, this, recording_output, start_recording, stop_recording, deactivate_recording); decltype(audio_encoders) recording_audio_encoders; recording_audio_encoders.reserve(audio_encoders.size()); for (auto &encoder : audio_encoders) { - recording_audio_encoders.emplace_back( - obs_encoder_get_ref(encoder)); + recording_audio_encoders.emplace_back(obs_encoder_get_ref(encoder)); } { - const std::lock_guard current_stream_dump_lock{ - current_stream_dump_mutex}; + const std::lock_guard current_stream_dump_lock{current_stream_dump_mutex}; current_stream_dump.emplace(OBSOutputObjects{ std::move(recording_output), video_encoder_group, @@ -544,20 +453,16 @@ void MultitrackVideoOutput::PrepareStreaming( signal_handler_t *MultitrackVideoOutput::StreamingSignalHandler() { const std::lock_guard current_lock{current_mutex}; - return current.has_value() - ? obs_output_get_signal_handler(current->output_) - : nullptr; + return current.has_value() ? obs_output_get_signal_handler(current->output_) : nullptr; } void MultitrackVideoOutput::StartedStreaming() { OBSOutputAutoRelease dump_output; { - const std::lock_guard current_stream_dump_lock{ - current_stream_dump_mutex}; + const std::lock_guard current_stream_dump_lock{current_stream_dump_mutex}; if (current_stream_dump && current_stream_dump->output_) { - dump_output = obs_output_get_ref( - current_stream_dump->output_); + dump_output = obs_output_get_ref(current_stream_dump->output_); } } @@ -565,8 +470,7 @@ void MultitrackVideoOutput::StartedStreaming() return; auto result = obs_output_start(dump_output); - blog(LOG_INFO, "MultitrackVideoOutput: starting recording%s", - result ? "" : " failed"); + blog(LOG_INFO, "MultitrackVideoOutput: starting recording%s", result ? "" : " failed"); } void MultitrackVideoOutput::StopStreaming() @@ -582,19 +486,17 @@ void MultitrackVideoOutput::StopStreaming() OBSOutputAutoRelease dump_output; { - const std::lock_guard current_stream_dump_lock{ - current_stream_dump_mutex}; + const std::lock_guard current_stream_dump_lock{current_stream_dump_mutex}; if (current_stream_dump && current_stream_dump->output_) - dump_output = obs_output_get_ref( - current_stream_dump->output_); + dump_output = obs_output_get_ref(current_stream_dump->output_); } if (dump_output) obs_output_stop(dump_output); } -bool MultitrackVideoOutput::HandleIncompatibleSettings( - QWidget *parent, config_t *config, obs_service_t *service, - bool &useDelay, bool &enableNewSocketLoop, bool &enableDynBitrate) +bool MultitrackVideoOutput::HandleIncompatibleSettings(QWidget *parent, config_t *config, obs_service_t *service, + bool &useDelay, bool &enableNewSocketLoop, + bool &enableDynBitrate) { QString incompatible_settings; QString where_to_disable; @@ -602,36 +504,29 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings( size_t num = 1; - auto check_setting = [&](bool setting, const char *name, - const char *section) { + auto check_setting = [&](bool setting, const char *name, const char *section) { if (!setting) return; - incompatible_settings += - QString(" %1. %2\n").arg(num).arg(QTStr(name)); + incompatible_settings += QString(" %1. %2\n").arg(num).arg(QTStr(name)); - where_to_disable += - QString(" %1. [%2 → %3 → %4]\n") - .arg(num) - .arg(QTStr("Settings")) - .arg(QTStr("Basic.Settings.Advanced")) - .arg(QTStr(section)); + where_to_disable += QString(" %1. [%2 → %3 → %4]\n") + .arg(num) + .arg(QTStr("Settings")) + .arg(QTStr("Basic.Settings.Advanced")) + .arg(QTStr(section)); incompatible_settings_list += QString("%1, ").arg(name); num += 1; }; - check_setting(useDelay, "Basic.Settings.Advanced.StreamDelay", - "Basic.Settings.Advanced.StreamDelay"); + check_setting(useDelay, "Basic.Settings.Advanced.StreamDelay", "Basic.Settings.Advanced.StreamDelay"); #ifdef _WIN32 - check_setting(enableNewSocketLoop, - "Basic.Settings.Advanced.Network.EnableNewSocketLoop", + check_setting(enableNewSocketLoop, "Basic.Settings.Advanced.Network.EnableNewSocketLoop", "Basic.Settings.Advanced.Network"); #endif - check_setting(enableDynBitrate, - "Basic.Settings.Output.DynamicBitrate.Beta", - "Basic.Settings.Advanced.Network"); + check_setting(enableDynBitrate, "Basic.Settings.Output.DynamicBitrate.Beta", "Basic.Settings.Advanced.Network"); if (incompatible_settings.isEmpty()) return true; @@ -642,17 +537,13 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings( mb.setIcon(QMessageBox::Critical); mb.setWindowTitle(QTStr("MultitrackVideo.IncompatibleSettings.Title")); mb.setText(QString(QTStr("MultitrackVideo.IncompatibleSettings.Text")) - .arg(obs_data_get_string(service_settings, - "multitrack_video_name")) + .arg(obs_data_get_string(service_settings, "multitrack_video_name")) .arg(incompatible_settings) .arg(where_to_disable)); - auto this_stream = mb.addButton( - QTStr("MultitrackVideo.IncompatibleSettings.DisableAndStartStreaming"), - QMessageBox::AcceptRole); - auto all_streams = mb.addButton( - QString(QTStr( - "MultitrackVideo.IncompatibleSettings.UpdateAndStartStreaming")), - QMessageBox::AcceptRole); + auto this_stream = mb.addButton(QTStr("MultitrackVideo.IncompatibleSettings.DisableAndStartStreaming"), + QMessageBox::AcceptRole); + auto all_streams = mb.addButton(QString(QTStr("MultitrackVideo.IncompatibleSettings.UpdateAndStartStreaming")), + QMessageBox::AcceptRole); mb.setStandardButtons(QMessageBox::StandardButton::Cancel); mb.exec(); @@ -669,8 +560,7 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings( "settings (%s); action taken: %s", incompatible_settings_list.toUtf8().constData(), action); - if (mb.clickedButton() == this_stream || - mb.clickedButton() == all_streams) { + if (mb.clickedButton() == this_stream || mb.clickedButton() == all_streams) { useDelay = false; enableNewSocketLoop = false; enableDynBitrate = false; @@ -678,11 +568,9 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings( if (mb.clickedButton() == all_streams) { config_set_bool(config, "Output", "DelayEnable", false); #ifdef _WIN32 - config_set_bool(config, "Output", "NewSocketLoopEnable", - false); + config_set_bool(config, "Output", "NewSocketLoopEnable", false); #endif - config_set_bool(config, "Output", "DynamicBitrate", - false); + config_set_bool(config, "Output", "DynamicBitrate", false); } return true; @@ -694,29 +582,23 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings( return false; } -static bool -create_video_encoders(const GoLiveApi::Config &go_live_config, - std::shared_ptr &video_encoder_group, - obs_output_t *output, obs_output_t *recording_output) +static bool create_video_encoders(const GoLiveApi::Config &go_live_config, + std::shared_ptr &video_encoder_group, obs_output_t *output, + obs_output_t *recording_output) { DStr video_encoder_name_buffer; if (go_live_config.encoder_configurations.empty()) { - blog(LOG_WARNING, - "MultitrackVideoOutput: Missing video encoder configurations"); - throw MultitrackVideoError::warning( - QTStr("FailedToStartStream.MissingEncoderConfigs")); + blog(LOG_WARNING, "MultitrackVideoOutput: Missing video encoder configurations"); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.MissingEncoderConfigs")); } - std::shared_ptr encoder_group( - obs_encoder_group_create(), obs_encoder_group_destroy); + std::shared_ptr encoder_group(obs_encoder_group_create(), obs_encoder_group_destroy); if (!encoder_group) return false; - for (size_t i = 0; i < go_live_config.encoder_configurations.size(); - i++) { - auto encoder = create_video_encoder( - video_encoder_name_buffer, i, - go_live_config.encoder_configurations[i]); + for (size_t i = 0; i < go_live_config.encoder_configurations.size(); i++) { + auto encoder = + create_video_encoder(video_encoder_name_buffer, i, go_live_config.encoder_configurations[i]); if (!encoder) return false; @@ -725,22 +607,18 @@ create_video_encoders(const GoLiveApi::Config &go_live_config, obs_output_set_video_encoder2(output, encoder, i); if (recording_output) - obs_output_set_video_encoder2(recording_output, encoder, - i); + obs_output_set_video_encoder2(recording_output, encoder, i); } video_encoder_group = encoder_group; return true; } -static void -create_audio_encoders(const GoLiveApi::Config &go_live_config, - std::vector &audio_encoders, - obs_output_t *output, obs_output_t *recording_output, - const char *audio_encoder_id, size_t main_audio_mixer, - std::optional vod_track_mixer, - std::vector &speaker_layouts, - speaker_layout ¤t_layout) +static void create_audio_encoders(const GoLiveApi::Config &go_live_config, + std::vector &audio_encoders, obs_output_t *output, + obs_output_t *recording_output, const char *audio_encoder_id, size_t main_audio_mixer, + std::optional vod_track_mixer, std::vector &speaker_layouts, + speaker_layout ¤t_layout) { speaker_layout speakers = SPEAKERS_UNKNOWN; obs_audio_info oai = {}; @@ -749,8 +627,7 @@ create_audio_encoders(const GoLiveApi::Config &go_live_config, current_layout = speakers; - auto sanitize_audio_channels = [&](obs_encoder_t *encoder, - uint32_t channels) { + auto sanitize_audio_channels = [&](obs_encoder_t *encoder, uint32_t channels) { speaker_layout target_speakers = SPEAKERS_UNKNOWN; for (size_t i = 0; i <= (size_t)SPEAKERS_7POINT1; i++) { if (get_audio_channels((speaker_layout)i) != channels) @@ -768,67 +645,49 @@ create_audio_encoders(const GoLiveApi::Config &go_live_config, return; } if (speakers != SPEAKERS_UNKNOWN && - (channels > get_audio_channels(speakers) || - speakers == target_speakers)) + (channels > get_audio_channels(speakers) || speakers == target_speakers)) return; - auto it = std::find(std::begin(speaker_layouts), - std::end(speaker_layouts), target_speakers); + auto it = std::find(std::begin(speaker_layouts), std::end(speaker_layouts), target_speakers); if (it == std::end(speaker_layouts)) speaker_layouts.push_back(target_speakers); }; - using encoder_configs_type = - decltype(go_live_config.audio_configurations.live); + using encoder_configs_type = decltype(go_live_config.audio_configurations.live); DStr encoder_name_buffer; size_t output_encoder_index = 0; - auto create_encoders = [&](const char *name_prefix, - const encoder_configs_type &configs, - size_t mixer_idx) { + auto create_encoders = [&](const char *name_prefix, const encoder_configs_type &configs, size_t mixer_idx) { if (configs.empty()) { - blog(LOG_WARNING, - "MultitrackVideoOutput: Missing audio encoder configurations (for '%s')", + blog(LOG_WARNING, "MultitrackVideoOutput: Missing audio encoder configurations (for '%s')", name_prefix); - throw MultitrackVideoError::warning(QTStr( - "FailedToStartStream.MissingEncoderConfigs")); + throw MultitrackVideoError::warning(QTStr("FailedToStartStream.MissingEncoderConfigs")); } for (size_t i = 0; i < configs.size(); i++) { - dstr_printf(encoder_name_buffer, "%s %zu", name_prefix, - i); - OBSDataAutoRelease settings = obs_data_create_from_json( - configs[i].settings.dump().c_str()); + dstr_printf(encoder_name_buffer, "%s %zu", name_prefix, i); + OBSDataAutoRelease settings = obs_data_create_from_json(configs[i].settings.dump().c_str()); OBSEncoderAutoRelease audio_encoder = - create_audio_encoder(encoder_name_buffer->array, - audio_encoder_id, settings, - mixer_idx); + create_audio_encoder(encoder_name_buffer->array, audio_encoder_id, settings, mixer_idx); - sanitize_audio_channels(audio_encoder, - configs[i].channels); + sanitize_audio_channels(audio_encoder, configs[i].channels); - obs_output_set_audio_encoder(output, audio_encoder, - output_encoder_index); + obs_output_set_audio_encoder(output, audio_encoder, output_encoder_index); if (recording_output) - obs_output_set_audio_encoder( - recording_output, audio_encoder, - output_encoder_index); + obs_output_set_audio_encoder(recording_output, audio_encoder, output_encoder_index); output_encoder_index += 1; audio_encoders.emplace_back(std::move(audio_encoder)); } }; - create_encoders("multitrack video live audio", - go_live_config.audio_configurations.live, - main_audio_mixer); + create_encoders("multitrack video live audio", go_live_config.audio_configurations.live, main_audio_mixer); if (!vod_track_mixer.has_value()) return; // we already check for empty inside of `create_encoders` encoder_configs_type empty = {}; - create_encoders("multitrack video vod audio", - go_live_config.audio_configurations.vod.value_or(empty), + create_encoders("multitrack video vod audio", go_live_config.audio_configurations.vod.value_or(empty), *vod_track_mixer); return; @@ -857,24 +716,19 @@ static const char *speaker_layout_to_string(speaker_layout layout) return "Stereo"; } -static void handle_speaker_layout_issues( - QWidget *parent, const QString &multitrack_video_name, - const std::vector &requested_layouts, - speaker_layout layout) +static void handle_speaker_layout_issues(QWidget *parent, const QString &multitrack_video_name, + const std::vector &requested_layouts, speaker_layout layout) { if (requested_layouts.empty()) return; QString message; if (requested_layouts.size() == 1) { - message = - QTStr("MultitrackVideo.IncompatibleSettings.AudioChannelsSingle") - .arg(QTStr(speaker_layout_to_string( - requested_layouts.front()))); + message = QTStr("MultitrackVideo.IncompatibleSettings.AudioChannelsSingle") + .arg(QTStr(speaker_layout_to_string(requested_layouts.front()))); } else { message = - QTStr("MultitrackVideo.IncompatibleSettings.AudioChannelsMultiple") - .arg(multitrack_video_name); + QTStr("MultitrackVideo.IncompatibleSettings.AudioChannelsMultiple").arg(multitrack_video_name); } QMetaObject::invokeMethod( @@ -882,63 +736,50 @@ static void handle_speaker_layout_issues( [&] { QMessageBox mb(parent); mb.setIcon(QMessageBox::Critical); - mb.setWindowTitle(QTStr( - "MultitrackVideo.IncompatibleSettings.Title")); - mb.setText( - QTStr("MultitrackVideo.IncompatibleSettings.AudioChannels") - .arg(multitrack_video_name) - .arg(QTStr(speaker_layout_to_string( - layout))) - .arg(message)); + mb.setWindowTitle(QTStr("MultitrackVideo.IncompatibleSettings.Title")); + mb.setText(QTStr("MultitrackVideo.IncompatibleSettings.AudioChannels") + .arg(multitrack_video_name) + .arg(QTStr(speaker_layout_to_string(layout))) + .arg(message)); - mb.setStandardButtons( - QMessageBox::StandardButton::Cancel); + mb.setStandardButtons(QMessageBox::StandardButton::Cancel); mb.exec(); }, BlockingConnectionTypeFor(parent)); - blog(LOG_INFO, - "MultitrackVideoOutput: Attempted to start stream with incompatible " - "audio channel setting. Action taken: cancel"); + blog(LOG_INFO, "MultitrackVideoOutput: Attempted to start stream with incompatible " + "audio channel setting. Action taken: cancel"); throw MultitrackVideoError::cancel(); } -static OBSOutputs -SetupOBSOutput(QWidget *parent, const QString &multitrack_video_name, - obs_data_t *dump_stream_to_file_config, - const GoLiveApi::Config &go_live_config, - std::vector &audio_encoders, - std::shared_ptr &video_encoder_group, - const char *audio_encoder_id, size_t main_audio_mixer, - std::optional vod_track_mixer) +static OBSOutputs SetupOBSOutput(QWidget *parent, const QString &multitrack_video_name, + obs_data_t *dump_stream_to_file_config, const GoLiveApi::Config &go_live_config, + std::vector &audio_encoders, + std::shared_ptr &video_encoder_group, + const char *audio_encoder_id, size_t main_audio_mixer, + std::optional vod_track_mixer) { auto output = create_output(); OBSOutputAutoRelease recording_output; if (dump_stream_to_file_config) - recording_output = - create_recording_output(dump_stream_to_file_config); + recording_output = create_recording_output(dump_stream_to_file_config); - if (!create_video_encoders(go_live_config, video_encoder_group, output, - recording_output)) + if (!create_video_encoders(go_live_config, video_encoder_group, output, recording_output)) return {nullptr, nullptr}; std::vector requested_speaker_layouts; speaker_layout current_layout = SPEAKERS_UNKNOWN; - create_audio_encoders(go_live_config, audio_encoders, output, - recording_output, audio_encoder_id, - main_audio_mixer, vod_track_mixer, - requested_speaker_layouts, current_layout); + create_audio_encoders(go_live_config, audio_encoders, output, recording_output, audio_encoder_id, + main_audio_mixer, vod_track_mixer, requested_speaker_layouts, current_layout); - handle_speaker_layout_issues(parent, multitrack_video_name, - requested_speaker_layouts, current_layout); + handle_speaker_layout_issues(parent, multitrack_video_name, requested_speaker_layouts, current_layout); return {std::move(output), std::move(recording_output)}; } -void SetupSignalHandlers(bool recording, MultitrackVideoOutput *self, - obs_output_t *output, OBSSignal &start, +void SetupSignalHandlers(bool recording, MultitrackVideoOutput *self, obs_output_t *output, OBSSignal &start, OBSSignal &stop, OBSSignal &deactivate) { auto handler = obs_output_get_signal_handler(output); @@ -946,18 +787,13 @@ void SetupSignalHandlers(bool recording, MultitrackVideoOutput *self, if (recording) start.Connect(handler, "start", RecordingStartHandler, self); - stop.Connect(handler, "stop", - !recording ? StreamStopHandler : RecordingStopHandler, - self); + stop.Connect(handler, "stop", !recording ? StreamStopHandler : RecordingStopHandler, self); - deactivate.Connect(handler, "deactivate", - !recording ? StreamDeactivateHandler - : RecordingDeactivateHandler, + deactivate.Connect(handler, "deactivate", !recording ? StreamDeactivateHandler : RecordingDeactivateHandler, self); } -std::optional -MultitrackVideoOutput::take_current() +std::optional MultitrackVideoOutput::take_current() { const std::lock_guard current_lock{current_mutex}; auto val = std::move(current); @@ -965,26 +801,22 @@ MultitrackVideoOutput::take_current() return val; } -std::optional -MultitrackVideoOutput::take_current_stream_dump() +std::optional MultitrackVideoOutput::take_current_stream_dump() { - const std::lock_guard current_stream_dump_lock{ - current_stream_dump_mutex}; + const std::lock_guard current_stream_dump_lock{current_stream_dump_mutex}; auto val = std::move(current_stream_dump); current_stream_dump.reset(); return val; } -void MultitrackVideoOutput::ReleaseOnMainThread( - std::optional objects) +void MultitrackVideoOutput::ReleaseOnMainThread(std::optional objects) { if (!objects.has_value()) return; QMetaObject::invokeMethod( - QApplication::instance()->thread(), - [objects = std::move(objects)] {}, Qt::QueuedConnection); + QApplication::instance()->thread(), [objects = std::move(objects)] {}, Qt::QueuedConnection); } void StreamStopHandler(void *arg, calldata_t *params) @@ -993,18 +825,14 @@ void StreamStopHandler(void *arg, calldata_t *params) OBSOutputAutoRelease stream_dump_output; { - const std::lock_guard current_stream_dump_lock{ - self->current_stream_dump_mutex}; - if (self->current_stream_dump && - self->current_stream_dump->output_) - stream_dump_output = obs_output_get_ref( - self->current_stream_dump->output_); + const std::lock_guard current_stream_dump_lock{self->current_stream_dump_mutex}; + if (self->current_stream_dump && self->current_stream_dump->output_) + stream_dump_output = obs_output_get_ref(self->current_stream_dump->output_); } if (stream_dump_output) obs_output_stop(stream_dump_output); - if (obs_output_active(static_cast( - calldata_ptr(params, "output")))) + if (obs_output_active(static_cast(calldata_ptr(params, "output")))) return; MultitrackVideoOutput::ReleaseOnMainThread(self->take_current()); @@ -1014,18 +842,15 @@ void StreamDeactivateHandler(void *arg, calldata_t *params) { auto self = static_cast(arg); - if (obs_output_reconnecting(static_cast( - calldata_ptr(params, "output")))) + if (obs_output_reconnecting(static_cast(calldata_ptr(params, "output")))) return; /* Unregister the BPM (Broadcast Performance Metrics) callback * and destroy the allocated metrics data. */ - obs_output_remove_packet_callback( - static_cast(calldata_ptr(params, "output")), - bpm_inject, NULL); - bpm_destroy( - static_cast(calldata_ptr(params, "output"))); + obs_output_remove_packet_callback(static_cast(calldata_ptr(params, "output")), bpm_inject, + NULL); + bpm_destroy(static_cast(calldata_ptr(params, "output"))); MultitrackVideoOutput::ReleaseOnMainThread(self->take_current()); } @@ -1040,17 +865,14 @@ void RecordingStopHandler(void *arg, calldata_t *params) auto self = static_cast(arg); blog(LOG_INFO, "MultitrackVideoOutput: recording stopped"); - if (obs_output_active(static_cast( - calldata_ptr(params, "output")))) + if (obs_output_active(static_cast(calldata_ptr(params, "output")))) return; - MultitrackVideoOutput::ReleaseOnMainThread( - self->take_current_stream_dump()); + MultitrackVideoOutput::ReleaseOnMainThread(self->take_current_stream_dump()); } void RecordingDeactivateHandler(void *arg, calldata_t * /*data*/) { auto self = static_cast(arg); - MultitrackVideoOutput::ReleaseOnMainThread( - self->take_current_stream_dump()); + MultitrackVideoOutput::ReleaseOnMainThread(self->take_current_stream_dump()); } diff --git a/UI/multitrack-video-output.hpp b/UI/multitrack-video-output.hpp index 71f590aca..299251a0d 100644 --- a/UI/multitrack-video-output.hpp +++ b/UI/multitrack-video-output.hpp @@ -25,24 +25,17 @@ bool MultitrackVideoDeveloperModeEnabled(); struct MultitrackVideoOutput { public: - void PrepareStreaming(QWidget *parent, const char *service_name, - obs_service_t *service, - const std::optional &rtmp_url, - const QString &stream_key, - const char *audio_encoder_id, - std::optional maximum_aggregate_bitrate, - std::optional maximum_video_tracks, - std::optional custom_config, - obs_data_t *dump_stream_to_file_config, - size_t main_audio_mixer, + void PrepareStreaming(QWidget *parent, const char *service_name, obs_service_t *service, + const std::optional &rtmp_url, const QString &stream_key, + const char *audio_encoder_id, std::optional maximum_aggregate_bitrate, + std::optional maximum_video_tracks, std::optional custom_config, + obs_data_t *dump_stream_to_file_config, size_t main_audio_mixer, std::optional vod_track_mixer); signal_handler_t *StreamingSignalHandler(); void StartedStreaming(); void StopStreaming(); - bool HandleIncompatibleSettings(QWidget *parent, config_t *config, - obs_service_t *service, bool &useDelay, - bool &enableNewSocketLoop, - bool &enableDynBitrate); + bool HandleIncompatibleSettings(QWidget *parent, config_t *config, obs_service_t *service, bool &useDelay, + bool &enableNewSocketLoop, bool &enableDynBitrate); OBSOutputAutoRelease StreamingOutput() { @@ -62,8 +55,7 @@ private: std::optional take_current(); std::optional take_current_stream_dump(); - static void - ReleaseOnMainThread(std::optional objects); + static void ReleaseOnMainThread(std::optional objects); std::mutex current_mutex; std::optional current; diff --git a/UI/multiview.cpp b/UI/multiview.cpp index 082a3e23a..9fc8883dc 100644 --- a/UI/multiview.cpp +++ b/UI/multiview.cpp @@ -6,8 +6,7 @@ Multiview::Multiview() { - InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin, - &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine); + InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin, &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine); } Multiview::~Multiview() @@ -59,14 +58,12 @@ static OBSSource CreateLabel(const char *name, size_t h) const char *text_source_id = "text_ft2_source"; #endif - OBSSourceAutoRelease txtSource = - obs_source_create_private(text_source_id, name, settings); + OBSSourceAutoRelease txtSource = obs_source_create_private(text_source_id, name, settings); return txtSource.Get(); } -void Multiview::Update(MultiviewLayout multiviewLayout, bool drawLabel, - bool drawSafeArea) +void Multiview::Update(MultiviewLayout multiviewLayout, bool drawLabel, bool drawSafeArea) { this->multiviewLayout = multiviewLayout; this->drawLabel = drawLabel; @@ -87,10 +84,8 @@ void Multiview::Update(MultiviewLayout multiviewLayout, bool drawLabel, struct obs_frontend_source_list scenes = {}; obs_frontend_get_scenes(&scenes); - multiviewLabels.emplace_back( - CreateLabel(Str("StudioMode.Preview"), h / 2)); - multiviewLabels.emplace_back( - CreateLabel(Str("StudioMode.Program"), h / 2)); + multiviewLabels.emplace_back(CreateLabel(Str("StudioMode.Preview"), h / 2)); + multiviewLabels.emplace_back(CreateLabel(Str("StudioMode.Program"), h / 2)); switch (multiviewLayout) { case MultiviewLayout::HORIZONTAL_TOP_18_SCENES: @@ -175,15 +170,13 @@ void Multiview::Update(MultiviewLayout multiviewLayout, bool drawLabel, multiviewScenes.emplace_back(OBSGetWeakRef(src)); obs_source_inc_showing(src); - multiviewLabels.emplace_back( - CreateLabel(obs_source_get_name(src), h / 3)); + multiviewLabels.emplace_back(CreateLabel(obs_source_get_name(src), h / 3)); } obs_frontend_source_list_free(&scenes); } -static inline uint32_t labelOffset(MultiviewLayout multiviewLayout, - obs_source_t *label, uint32_t cx) +static inline uint32_t labelOffset(MultiviewLayout multiviewLayout, obs_source_t *label, uint32_t cx) { uint32_t w = obs_source_get_width(label); @@ -232,8 +225,7 @@ void Multiview::Render(uint32_t cx, uint32_t cy) auto drawBox = [&](float cx, float cy, uint32_t colorVal) { gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID); - gs_eparam_t *color = - gs_effect_get_param_by_name(solid, "color"); + gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color"); gs_effect_set_color(color, colorVal); while (gs_effect_loop(solid, "Solid")) @@ -375,8 +367,7 @@ void Multiview::Render(uint32_t cx, uint32_t cy) } }; - auto paintAreaWithColor = [&](float tx, float ty, float cx, float cy, - uint32_t color) { + auto paintAreaWithColor = [&](float tx, float ty, float cx, float cy, uint32_t color) { gs_matrix_push(); gs_matrix_translate3f(tx, ty, 0.0f); drawBox(cx, cy, color); @@ -384,8 +375,7 @@ void Multiview::Render(uint32_t cx, uint32_t cy) }; // Define the whole usable region for the multiview - startRegion(x, y, targetCX * scale, targetCY * scale, 0.0f, fw, 0.0f, - fh); + startRegion(x, y, targetCX * scale, targetCY * scale, 0.0f, fw, 0.0f, fh); // Change the background color to highlight all sources drawBox(fw, fh, outerColor); @@ -399,10 +389,8 @@ void Multiview::Render(uint32_t cx, uint32_t cy) if (i >= numSrcs) { // Just paint the background and continue - paintAreaWithColor(sourceX, sourceY, scenesCX, scenesCY, - outerColor); - paintAreaWithColor(siX, siY, siCX, siCY, - backgroundColor); + paintAreaWithColor(sourceX, sourceY, scenesCX, scenesCY, outerColor); + paintAreaWithColor(siX, siY, siCX, siCY, backgroundColor); continue; } @@ -416,8 +404,7 @@ void Multiview::Render(uint32_t cx, uint32_t cy) colorVal = studioMode ? previewColor : programColor; // Paint the background - paintAreaWithColor(sourceX, sourceY, scenesCX, scenesCY, - colorVal); + paintAreaWithColor(sourceX, sourceY, scenesCX, scenesCY, colorVal); paintAreaWithColor(siX, siY, siCX, siCY, backgroundColor); /* ----------- */ @@ -444,15 +431,11 @@ void Multiview::Render(uint32_t cx, uint32_t cy) offset = labelOffset(multiviewLayout, label, scenesCX); gs_matrix_push(); - gs_matrix_translate3f( - sourceX + offset, - sourceY + scenesCY - - (obs_source_get_height(label) * ppiScaleY) - - (thickness * 3), - 0.0f); + gs_matrix_translate3f(sourceX + offset, + sourceY + scenesCY - (obs_source_get_height(label) * ppiScaleY) - (thickness * 3), + 0.0f); gs_matrix_scale3f(ppiScaleX, ppiScaleY, 1.0f); - drawBox(obs_source_get_width(label), - obs_source_get_height(label) + thicknessx2, labelColor); + drawBox(obs_source_get_width(label), obs_source_get_height(label) + thicknessx2, labelColor); gs_matrix_translate3f(0, thickness, 0.0f); obs_source_video_render(label); gs_matrix_pop(); @@ -504,15 +487,9 @@ void Multiview::Render(uint32_t cx, uint32_t cy) if (drawLabel) { gs_matrix_push(); gs_matrix_translate3f( - labelX, - labelY - - (obs_source_get_height(previewLabel) * - ppiScaleY) - - (thickness * 3), - 0.0f); + labelX, labelY - (obs_source_get_height(previewLabel) * ppiScaleY) - (thickness * 3), 0.0f); gs_matrix_scale3f(ppiScaleX, ppiScaleY, 1.0f); - drawBox(obs_source_get_width(previewLabel), - obs_source_get_height(previewLabel) + thicknessx2, + drawBox(obs_source_get_width(previewLabel), obs_source_get_height(previewLabel) + thicknessx2, labelColor); gs_matrix_translate3f(0, thickness, 0.0f); obs_source_video_render(previewLabel); @@ -543,15 +520,9 @@ void Multiview::Render(uint32_t cx, uint32_t cy) if (drawLabel) { gs_matrix_push(); gs_matrix_translate3f( - labelX, - labelY - - (obs_source_get_height(programLabel) * - ppiScaleY) - - (thickness * 3), - 0.0f); + labelX, labelY - (obs_source_get_height(programLabel) * ppiScaleY) - (thickness * 3), 0.0f); gs_matrix_scale3f(ppiScaleX, ppiScaleY, 1.0f); - drawBox(obs_source_get_width(programLabel), - obs_source_get_height(programLabel) + thicknessx2, + drawBox(obs_source_get_width(programLabel), obs_source_get_height(programLabel) + thicknessx2, labelColor); gs_matrix_translate3f(0, thickness, 0.0f); obs_source_video_render(programLabel); @@ -561,10 +532,8 @@ void Multiview::Render(uint32_t cx, uint32_t cy) // Region for future usage with additional info. if (multiviewLayout == MultiviewLayout::HORIZONTAL_TOP_24_SCENES) { // Just paint the background for now - paintAreaWithColor(thickness, thickness, siCX, - siCY * 2 + thicknessx2, backgroundColor); - paintAreaWithColor(thickness + 2.5 * (thicknessx2 + ppiCX), - thickness, siCX, siCY * 2 + thicknessx2, + paintAreaWithColor(thickness, thickness, siCX, siCY * 2 + thicknessx2, backgroundColor); + paintAreaWithColor(thickness + 2.5 * (thicknessx2 + ppiCX), thickness, siCX, siCY * 2 + thicknessx2, backgroundColor); } diff --git a/UI/multiview.hpp b/UI/multiview.hpp index 2fa1d2309..61abd690b 100644 --- a/UI/multiview.hpp +++ b/UI/multiview.hpp @@ -20,8 +20,7 @@ class Multiview { public: Multiview(); ~Multiview(); - void Update(MultiviewLayout multiviewLayout, bool drawLabel, - bool drawSafeArea); + void Update(MultiviewLayout multiviewLayout, bool drawLabel, bool drawSafeArea); void Render(uint32_t cx, uint32_t cy); OBSSource GetSourceByPosition(int x, int y); @@ -41,10 +40,9 @@ private: // Multiview position helpers float thickness = 6; - float offset, thicknessx2 = thickness * 2, pvwprgCX, pvwprgCY, sourceX, - sourceY, labelX, labelY, scenesCX, scenesCY, ppiCX, ppiCY, - siX, siY, siCX, siCY, ppiScaleX, ppiScaleY, siScaleX, - siScaleY, fw, fh, ratio; + float offset, thicknessx2 = thickness * 2, pvwprgCX, pvwprgCY, sourceX, sourceY, labelX, labelY, scenesCX, + scenesCY, ppiCX, ppiCY, siX, siY, siCX, siCY, ppiScaleX, ppiScaleY, siScaleX, siScaleY, fw, fh, + ratio; // argb colors static const uint32_t outerColor = 0xFF999999; @@ -54,8 +52,7 @@ private: static const uint32_t programColor = 0xFFD00000; }; -static inline void startRegion(int vX, int vY, int vCX, int vCY, float oL, - float oR, float oT, float oB) +static inline void startRegion(int vX, int vY, int vCX, int vCY, float oL, float oR, float oT, float oB) { gs_projection_push(); gs_viewport_push(); diff --git a/UI/noncheckable-button.hpp b/UI/noncheckable-button.hpp index 71d942ef3..d5ef59a37 100644 --- a/UI/noncheckable-button.hpp +++ b/UI/noncheckable-button.hpp @@ -11,13 +11,6 @@ class NonCheckableButton : public QPushButton { inline void nextCheckState() override {} public: - inline NonCheckableButton(QWidget *parent = nullptr) - : QPushButton(parent) - { - } - inline NonCheckableButton(const QString &text, - QWidget *parent = nullptr) - : QPushButton(text, parent) - { - } + inline NonCheckableButton(QWidget *parent = nullptr) : QPushButton(parent) {} + inline NonCheckableButton(const QString &text, QWidget *parent = nullptr) : QPushButton(text, parent) {} }; diff --git a/UI/obf.c b/UI/obf.c index 895be4b68..feba1886e 100644 --- a/UI/obf.c +++ b/UI/obf.c @@ -13,8 +13,7 @@ void deobfuscate_str(char *str, uint64_t val) int pos = i / 2; bool bottom = (i % 2) == 0; uint8_t *ch = (uint8_t *)str; - uint8_t xor = bottom ? LOWER_HALFBYTE(dec_val[pos]) - : UPPER_HALFBYTE(dec_val[pos]); + uint8_t xor = bottom ? LOWER_HALFBYTE(dec_val[pos]) : UPPER_HALFBYTE(dec_val[pos]); *ch ^= xor; diff --git a/UI/obs-app-theming.cpp b/UI/obs-app-theming.cpp index 037bf0160..9698ac455 100644 --- a/UI/obs-app-theming.cpp +++ b/UI/obs-app-theming.cpp @@ -81,13 +81,11 @@ static optional ParseThemeMeta(const QString &path) if (!cf_next_token(cfp)) return nullopt; - ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name", - nullptr); + ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name", nullptr); if (ret != PARSE_SUCCESS) break; - string name(cfp->cur_token->str.array, - cfp->cur_token->str.len); + string name(cfp->cur_token->str.array, cfp->cur_token->str.len); ret = cf_next_token_should_be(cfp, ":", ";", nullptr); if (ret != PARSE_SUCCESS) @@ -96,14 +94,12 @@ static optional ParseThemeMeta(const QString &path) if (!cf_next_token(cfp)) return nullopt; - ret = cf_token_is_type(cfp, CFTOKEN_STRING, "value", - ";"); + ret = cf_token_is_type(cfp, CFTOKEN_STRING, "value", ";"); if (ret != PARSE_SUCCESS) continue; - BPtr str = cf_literal_to_str(cfp->cur_token->str.array, - cfp->cur_token->str.len); + BPtr str = cf_literal_to_str(cfp->cur_token->str.array, cfp->cur_token->str.len); if (str) { if (name == "dark") @@ -127,8 +123,7 @@ static optional ParseThemeMeta(const QString &path) meta.isBaseTheme = filepath.extension() == ".obt"; meta.filename = filepath.stem(); - if (meta.id.isEmpty() || meta.name.isEmpty() || - (!meta.isBaseTheme && meta.extends.isEmpty())) { + if (meta.id.isEmpty() || meta.name.isEmpty() || (!meta.isBaseTheme && meta.extends.isEmpty())) { /* Theme is invalid */ return nullopt; } else { @@ -156,8 +151,7 @@ static bool ParseVarName(CFParser &cfp, QString &value) if (!cf_next_token(cfp)) return false; - value = QString::fromUtf8(cfp->cur_token->str.array, - cfp->cur_token->str.len); + value = QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len); ret = cf_next_token_should_be(cfp, ")", ";", nullptr); if (ret != PARSE_SUCCESS) @@ -212,8 +206,7 @@ static QColor ParseColor(CFParser &cfp) return res; } -static bool ParseCalc(CFParser &cfp, QStringList &calc, - vector &vars) +static bool ParseCalc(CFParser &cfp, QStringList &calc, vector &vars) { int ret = cf_next_token_should_be(cfp, "(", ";", nullptr); if (ret != PARSE_SUCCESS) @@ -231,9 +224,7 @@ static bool ParseCalc(CFParser &cfp, QStringList &calc, OBSThemeVariable var; QStringList subcalc; - var.name = QString("__unnamed_%1") - .arg(QRandomGenerator::global() - ->generate64()); + var.name = QString("__unnamed_%1").arg(QRandomGenerator::global()->generate64()); if (!ParseCalc(cfp, subcalc, vars)) return false; @@ -249,8 +240,7 @@ static bool ParseCalc(CFParser &cfp, QStringList &calc, calc << value; } else { - calc << QString::fromUtf8(cfp->cur_token->str.array, - cfp->cur_token->str.len); + calc << QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len); } if (!cf_next_token(cfp)) @@ -305,8 +295,7 @@ static vector ParseThemeVariables(const char *themeData) if (ret != PARSE_SUCCESS) break; - QString key = QString::fromUtf8(cfp->cur_token->str.array, - cfp->cur_token->str.len); + QString key = QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len); OBSThemeVariable var; var.name = key; @@ -318,8 +307,7 @@ static vector ParseThemeVariables(const char *themeData) const QString osPrefix = "os_lin_"; #endif - if (key.startsWith(osPrefix) && - key.length() > osPrefix.length()) { + if (key.startsWith(osPrefix) && key.length() > osPrefix.length()) { var.name = key.sliced(osPrefix.length()); } @@ -340,17 +328,14 @@ static vector ParseThemeVariables(const char *themeData) /* Look for a suffix and mark variable as size if it exists */ while (ch < end) { - if (!isdigit(*ch) && !isspace(*ch) && - *ch != '.') { - var.suffix = - QString::fromUtf8(ch, end - ch); + if (!isdigit(*ch) && !isspace(*ch) && *ch != '.') { + var.suffix = QString::fromUtf8(ch, end - ch); var.type = OBSThemeVariable::Size; break; } ch++; } - } else if (cf_token_is(cfp, "rgb") || cf_token_is(cfp, "#") || - cf_token_is(cfp, "bikeshed")) { + } else if (cf_token_is(cfp, "rgb") || cf_token_is(cfp, "#") || cf_token_is(cfp, "bikeshed")) { QColor color = ParseColor(cfp); if (!color.isValid()) continue; @@ -375,9 +360,7 @@ static vector ParseThemeVariables(const char *themeData) var.value = calc; } else { var.type = OBSThemeVariable::String; - BPtr strVal = - cf_literal_to_str(cfp->cur_token->str.array, - cfp->cur_token->str.len); + BPtr strVal = cf_literal_to_str(cfp->cur_token->str.array, cfp->cur_token->str.len); var.value = QString::fromUtf8(strVal.Get()); } @@ -385,12 +368,9 @@ static vector ParseThemeVariables(const char *themeData) return vars; if (cf_token_is(cfp, "!") && - cf_next_token_should_be(cfp, "editable", nullptr, - nullptr) == PARSE_SUCCESS) { - if (var.type == OBSThemeVariable::Calc || - var.type == OBSThemeVariable::Alias) { - blog(LOG_WARNING, - "Variable of calc/alias type cannot be editable: %s", + cf_next_token_should_be(cfp, "editable", nullptr, nullptr) == PARSE_SUCCESS) { + if (var.type == OBSThemeVariable::Calc || var.type == OBSThemeVariable::Alias) { + blog(LOG_WARNING, "Variable of calc/alias type cannot be editable: %s", QT_TO_UTF8(var.name)); } else { var.editable = true; @@ -399,8 +379,7 @@ static vector ParseThemeVariables(const char *themeData) vars.push_back(std::move(var)); - if (!cf_token_is(cfp, ";") && - !cf_go_to_token(cfp, ";", nullptr)) + if (!cf_token_is(cfp, ";") && !cf_go_to_token(cfp, ";", nullptr)) return vars; } @@ -419,8 +398,7 @@ void OBSApp::FindThemes() { string themeDir; GetDataFilePath("themes/", themeDir); - QDirIterator it(QString::fromStdString(themeDir), filters, - QDir::Files); + QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files); while (it.hasNext()) { auto theme = ParseThemeMeta(it.next()); if (theme && !themes.contains(theme->id)) @@ -429,12 +407,9 @@ void OBSApp::FindThemes() } { - const std::string themeDir = - App()->userConfigLocation.u8string() + - "/obs-studio/themes"; + const std::string themeDir = App()->userConfigLocation.u8string() + "/obs-studio/themes"; - QDirIterator it(QString::fromStdString(themeDir), filters, - QDir::Files); + QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files); while (it.hasNext()) { auto theme = ParseThemeMeta(it.next()); @@ -449,8 +424,7 @@ void OBSApp::FindThemes() for (OBSTheme &theme : themes) { if (theme.extends.isEmpty()) { if (!theme.isBaseTheme) { - blog(LOG_ERROR, - R"(Theme "%s" is not base, but does not specify parent!)", + blog(LOG_ERROR, R"(Theme "%s" is not base, but does not specify parent!)", QT_TO_UTF8(theme.id)); invalid.insert(theme.id); } @@ -462,46 +436,36 @@ void OBSApp::FindThemes() while (!parentId.isEmpty()) { OBSTheme *parent = GetTheme(parentId); if (!parent) { - blog(LOG_ERROR, - R"(Theme "%s" is missing ancestor "%s"!)", - QT_TO_UTF8(theme.id), + blog(LOG_ERROR, R"(Theme "%s" is missing ancestor "%s"!)", QT_TO_UTF8(theme.id), QT_TO_UTF8(parentId)); invalid.insert(theme.id); break; } if (theme.isBaseTheme && !parent->isBaseTheme) { - blog(LOG_ERROR, - R"(Ancestor "%s" of base theme "%s" is not a base theme!)", - QT_TO_UTF8(parent->id), - QT_TO_UTF8(theme.id)); + blog(LOG_ERROR, R"(Ancestor "%s" of base theme "%s" is not a base theme!)", + QT_TO_UTF8(parent->id), QT_TO_UTF8(theme.id)); invalid.insert(theme.id); break; } - if (parent->id == theme.id || - theme.dependencies.contains(parent->id)) { - blog(LOG_ERROR, - R"(Dependency chain of "%s" ("%s") contains recursion!)", - QT_TO_UTF8(theme.id), - QT_TO_UTF8(parent->id)); + if (parent->id == theme.id || theme.dependencies.contains(parent->id)) { + blog(LOG_ERROR, R"(Dependency chain of "%s" ("%s") contains recursion!)", + QT_TO_UTF8(theme.id), QT_TO_UTF8(parent->id)); invalid.insert(theme.id); break; } /* Mark this theme as a variant of first parent that is a base theme. */ - if (!theme.isBaseTheme && parent->isBaseTheme && - theme.parent.isEmpty()) + if (!theme.isBaseTheme && parent->isBaseTheme && theme.parent.isEmpty()) theme.parent = parent->id; theme.dependencies.push_front(parent->id); parentId = parent->extends; if (parentId.isEmpty() && !parent->isBaseTheme) { - blog(LOG_ERROR, - R"(Final ancestor of "%s" ("%s") is not a base theme!)", - QT_TO_UTF8(theme.id), - QT_TO_UTF8(parent->id)); + blog(LOG_ERROR, R"(Final ancestor of "%s" ("%s") is not a base theme!)", + QT_TO_UTF8(theme.id), QT_TO_UTF8(parent->id)); invalid.insert(theme.id); break; } @@ -513,8 +477,7 @@ void OBSApp::FindThemes() } } -static bool ResolveVariable(const QHash &vars, - OBSThemeVariable &var) +static bool ResolveVariable(const QHash &vars, OBSThemeVariable &var) { if (var.type != OBSThemeVariable::Alias) return true; @@ -524,9 +487,8 @@ static bool ResolveVariable(const QHash &vars, key = vars[key].value.toString(); if (!vars.contains(key)) { - blog(LOG_ERROR, - R"(Variable "%s" (aliased by "%s") does not exist!)", - QT_TO_UTF8(key), QT_TO_UTF8(var.name)); + blog(LOG_ERROR, R"(Variable "%s" (aliased by "%s") does not exist!)", QT_TO_UTF8(key), + QT_TO_UTF8(var.name)); return false; } } @@ -536,12 +498,11 @@ static bool ResolveVariable(const QHash &vars, return true; } -static QString EvalCalc(const QHash &vars, - const OBSThemeVariable &var, const int recursion = 0); +static QString EvalCalc(const QHash &vars, const OBSThemeVariable &var, + const int recursion = 0); -static OBSThemeVariable -ParseCalcVariable(const QHash &vars, - const QString &value, const int recursion = 0) +static OBSThemeVariable ParseCalcVariable(const QHash &vars, const QString &value, + const int recursion = 0) { OBSThemeVariable var; const QByteArray utf8 = value.toUtf8(); @@ -555,8 +516,7 @@ ParseCalcVariable(const QHash &vars, const char *dataEnd = data + utf8.size(); while (data < dataEnd) { if (*data && !isdigit(*data) && *data != '.') { - var.suffix = - QString::fromUtf8(data, dataEnd - data); + var.suffix = QString::fromUtf8(data, dataEnd - data); var.type = OBSThemeVariable::Size; break; } @@ -576,11 +536,8 @@ ParseCalcVariable(const QHash &vars, } /* Only number or size would be valid here */ - if (var.type != OBSThemeVariable::Number && - var.type != OBSThemeVariable::Size) { - blog(LOG_ERROR, - "calc() operand is not a size or number: %s", - QT_TO_UTF8(var.value.toString())); + if (var.type != OBSThemeVariable::Number && var.type != OBSThemeVariable::Size) { + blog(LOG_ERROR, "calc() operand is not a size or number: %s", QT_TO_UTF8(var.value.toString())); throw invalid_argument("Operand not of numeric type"); } } @@ -588,8 +545,7 @@ ParseCalcVariable(const QHash &vars, return var; } -static QString EvalCalc(const QHash &vars, - const OBSThemeVariable &var, const int recursion) +static QString EvalCalc(const QHash &vars, const OBSThemeVariable &var, const int recursion) { if (recursion >= 10) { /* Abort after 10 levels of recursion */ @@ -599,16 +555,14 @@ static QString EvalCalc(const QHash &vars, QStringList args = var.value.toStringList(); if (args.length() != 3) { - blog(LOG_ERROR, - "calc() had invalid number of arguments: %lld (%s)", - args.length(), QT_TO_UTF8(args.join(", "))); + blog(LOG_ERROR, "calc() had invalid number of arguments: %lld (%s)", args.length(), + QT_TO_UTF8(args.join(", "))); return "'Invalid expression'"; } QString &opt = args[1]; if (opt != '*' && opt != '+' && opt != '-' && opt != '/') { - blog(LOG_ERROR, "Unknown/invalid calc() operator: %s", - QT_TO_UTF8(opt)); + blog(LOG_ERROR, "Unknown/invalid calc() operator: %s", QT_TO_UTF8(opt)); return "'Invalid expression'"; } @@ -621,19 +575,15 @@ static QString EvalCalc(const QHash &vars, } /* Ensure that suffixes match (if any) */ - if (!val1.suffix.isEmpty() && !val2.suffix.isEmpty() && - val1.suffix != val2.suffix) { - blog(LOG_ERROR, - "calc() requires suffixes to match or only one to be present! %s != %s", + if (!val1.suffix.isEmpty() && !val2.suffix.isEmpty() && val1.suffix != val2.suffix) { + blog(LOG_ERROR, "calc() requires suffixes to match or only one to be present! %s != %s", QT_TO_UTF8(val1.suffix), QT_TO_UTF8(val2.suffix)); return "'Invalid expression'"; } double val = numeric_limits::quiet_NaN(); - double d1 = val1.userValue.isValid() ? val1.userValue.toDouble() - : val1.value.toDouble(); - double d2 = val2.userValue.isValid() ? val2.userValue.toDouble() - : val2.value.toDouble(); + double d1 = val1.userValue.isValid() ? val1.userValue.toDouble() : val1.value.toDouble(); + double d2 = val2.userValue.isValid() ? val2.userValue.toDouble() : val2.value.toDouble(); if (!isfinite(d1) || !isfinite(d2)) { blog(LOG_ERROR, @@ -687,8 +637,7 @@ static qsizetype FindEndOfOBSMetadata(const QString &content) return end; } -static QString PrepareQSS(const QHash &vars, - const QStringList &contents) +static QString PrepareQSS(const QHash &vars, const QStringList &contents) { QString stylesheet; QString needleTemplate("var(--%1)"); @@ -710,15 +659,13 @@ static QString PrepareQSS(const QHash &vars, QString needle = needleTemplate.arg(var_.name); QString replace; - QVariant value = var.userValue.isValid() ? var.userValue - : var.value; + QVariant value = var.userValue.isValid() ? var.userValue : var.value; if (var.type == OBSThemeVariable::Color) { replace = value.value().name(QColor::HexRgb); } else if (var.type == OBSThemeVariable::Calc) { replace = EvalCalc(vars, var); - } else if (var.type == OBSThemeVariable::Size || - var.type == OBSThemeVariable::Number) { + } else if (var.type == OBSThemeVariable::Size || var.type == OBSThemeVariable::Number) { double val = value.toDouble(); bool isInteger = ceill(val) == val; replace = QString::number(val, 'f', isInteger ? 0 : -1); @@ -747,8 +694,7 @@ template static void FillEnumMap(QHash &map) } } -static QPalette PreparePalette(const QHash &vars, - const QPalette &defaultPalette) +static QPalette PreparePalette(const QHash &vars, const QPalette &defaultPalette) { static QHash roleMap; static QHash groupMap; @@ -767,8 +713,7 @@ static QPalette PreparePalette(const QHash &vars, continue; OBSThemeVariable var(var_); - if (!ResolveVariable(vars, var) || - var.type != OBSThemeVariable::Color) + if (!ResolveVariable(vars, var) || var.type != OBSThemeVariable::Color) continue; /* Determine role and optionally group based on name. @@ -780,9 +725,7 @@ static QPalette PreparePalette(const QHash &vars, if (parts.length() >= 2) { QString key = parts[1].toLower(); if (!roleMap.contains(key)) { - blog(LOG_WARNING, - "Palette role \"%s\" is not valid!", - QT_TO_UTF8(parts[1])); + blog(LOG_WARNING, "Palette role \"%s\" is not valid!", QT_TO_UTF8(parts[1])); continue; } role = roleMap[key]; @@ -791,16 +734,13 @@ static QPalette PreparePalette(const QHash &vars, if (parts.length() == 3) { QString key = parts[2].toLower(); if (!groupMap.contains(key)) { - blog(LOG_WARNING, - "Palette group \"%s\" is not valid!", - QT_TO_UTF8(parts[2])); + blog(LOG_WARNING, "Palette group \"%s\" is not valid!", QT_TO_UTF8(parts[2])); continue; } group = groupMap[key]; } - QVariant value = var.userValue.isValid() ? var.userValue - : var.value; + QVariant value = var.userValue.isValid() ? var.userValue : var.value; QColor color = value.value().name(QColor::HexRgb); pal.setColor(group, role, color); @@ -860,8 +800,7 @@ bool OBSApp::SetTheme(const QString &name) return false; const QByteArray content = file.readAll(); - for (OBSThemeVariable &var : - ParseThemeVariables(content.constData())) { + for (OBSThemeVariable &var : ParseThemeVariables(content.constData())) { vars[var.name] = std::move(var); } @@ -881,8 +820,7 @@ bool OBSApp::SetTheme(const QString &name) filesystem::path debugOut; char configPath[512]; - if (GetAppConfigPath(configPath, sizeof(configPath), - filename.c_str())) { + if (GetAppConfigPath(configPath, sizeof(configPath), filename.c_str())) { debugOut = absolute(filesystem::u8path(configPath)); filesystem::create_directories(debugOut.parent_path()); } @@ -904,8 +842,7 @@ bool OBSApp::SetTheme(const QString &name) themeWatcher->addPaths(filenames); /* Give it 250 ms before re-enabling the watcher to prevent too * many reloads when edited with an auto-saving IDE. */ - QTimer::singleShot(250, this, - [&] { themeWatcher->blockSignals(false); }); + QTimer::singleShot(250, this, [&] { themeWatcher->blockSignals(false); }); } return true; @@ -914,8 +851,7 @@ bool OBSApp::SetTheme(const QString &name) void OBSApp::themeFileChanged(const QString &path) { themeWatcher->blockSignals(true); - blog(LOG_INFO, "Theme file \"%s\" changed, reloading...", - QT_TO_UTF8(path)); + blog(LOG_INFO, "Theme file \"%s\" changed, reloading...", QT_TO_UTF8(path)); SetTheme(currentTheme->id); } @@ -957,24 +893,20 @@ bool OBSApp::InitTheme() if (config_get_bool(userConfig, "Appearance", "AutoReload")) { /* Set up Qt file watcher to automatically reload themes */ themeWatcher = new QFileSystemWatcher(this); - connect(themeWatcher.get(), &QFileSystemWatcher::fileChanged, - this, &OBSApp::themeFileChanged); + connect(themeWatcher.get(), &QFileSystemWatcher::fileChanged, this, &OBSApp::themeFileChanged); } /* Migrate old theme config key */ if (config_has_user_value(userConfig, "General", "CurrentTheme3") && !config_has_user_value(userConfig, "Appearance", "Theme")) { - const char *old = config_get_string(userConfig, "General", - "CurrentTheme3"); + const char *old = config_get_string(userConfig, "General", "CurrentTheme3"); if (themeMigrations.count(old)) { - config_set_string(userConfig, "Appearance", "Theme", - themeMigrations[old].c_str()); + config_set_string(userConfig, "Appearance", "Theme", themeMigrations[old].c_str()); } } - QString themeName = - config_get_string(userConfig, "Appearance", "Theme"); + QString themeName = config_get_string(userConfig, "Appearance", "Theme"); if (themeName.isEmpty() || !GetTheme(themeName)) { if (!themeName.isEmpty()) { @@ -984,8 +916,7 @@ bool OBSApp::InitTheme() QT_TO_UTF8(themeName), DEFAULT_THEME); } #ifdef _WIN32 - themeName = HighContrastEnabled() ? "com.obsproject.System" - : DEFAULT_THEME; + themeName = HighContrastEnabled() ? "com.obsproject.System" : DEFAULT_THEME; #else themeName = DEFAULT_THEME; #endif diff --git a/UI/obs-app.cpp b/UI/obs-app.cpp index 7166cbf79..66c71cc04 100644 --- a/UI/obs-app.cpp +++ b/UI/obs-app.cpp @@ -132,8 +132,7 @@ QObject *CreateShortcutFilter() { return new OBSEventFilter([](QObject *obj, QEvent *event) { auto mouse_event = [](QMouseEvent &event) { - if (!App()->HotkeysEnabledInFocus() && - event.button() != Qt::LeftButton) + if (!App()->HotkeysEnabledInFocus() && event.button() != Qt::LeftButton) return true; obs_key_combination_t hotkey = {0, OBS_KEY_NONE}; @@ -182,8 +181,7 @@ QObject *CreateShortcutFilter() #undef MAP_BUTTON } - hotkey.modifiers = TranslateQtKeyboardEventModifiers( - event.modifiers()); + hotkey.modifiers = TranslateQtKeyboardEventModifiers(event.modifiers()); obs_hotkey_inject_event(hotkey, pressed); return true; @@ -193,8 +191,7 @@ QObject *CreateShortcutFilter() int key = event->key(); bool enabledInFocus = App()->HotkeysEnabledInFocus(); - if (key != Qt::Key_Enter && key != Qt::Key_Escape && - key != Qt::Key_Return && !enabledInFocus) + if (key != Qt::Key_Enter && key != Qt::Key_Escape && key != Qt::Key_Return && !enabledInFocus) return true; QDialog *dialog = qobject_cast(obj); @@ -226,15 +223,13 @@ QObject *CreateShortcutFilter() return true; /* Falls through. */ default: - hotkey.key = obs_key_from_virtual_key( - event->nativeVirtualKey()); + hotkey.key = obs_key_from_virtual_key(event->nativeVirtualKey()); } if (event->isAutoRepeat()) return true; - hotkey.modifiers = TranslateQtKeyboardEventModifiers( - event->modifiers()); + hotkey.modifiers = TranslateQtKeyboardEventModifiers(event->modifiers()); obs_hotkey_inject_event(hotkey, pressed); return true; @@ -269,13 +264,11 @@ string CurrentTimeString() tstruct = *localtime(&now); size_t written = strftime(buf, sizeof(buf), "%T", &tstruct); - if (ratio_less::value && - written && (sizeof(buf) - written) > 5) { + if (ratio_less::value && written && (sizeof(buf) - written) > 5) { auto tp_secs = time_point_cast(tp); auto millis = duration_cast(tp - tp_secs).count(); - snprintf(buf + written, sizeof(buf) - written, ".%03u", - static_cast(millis)); + snprintf(buf + written, sizeof(buf) - written, ".%03u", static_cast(millis)); } return buf; @@ -291,8 +284,7 @@ string CurrentDateTimeString() return buf; } -static void LogString(fstream &logFile, const char *timeString, char *str, - int log_level) +static void LogString(fstream &logFile, const char *timeString, char *str, int log_level) { static mutex logfile_mutex; string msg; @@ -304,9 +296,7 @@ static void LogString(fstream &logFile, const char *timeString, char *str, logfile_mutex.unlock(); if (!!obsLogViewer) - QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine", - Qt::QueuedConnection, - Q_ARG(int, log_level), + QMetaObject::invokeMethod(obsLogViewer.data(), "AddLine", Qt::QueuedConnection, Q_ARG(int, log_level), Q_ARG(QString, QString(msg.c_str()))); } @@ -347,8 +337,7 @@ static inline int sum_chars(const char *str) return val; } -static inline bool too_many_repeated_entries(fstream &logFile, const char *msg, - const char *output_str) +static inline bool too_many_repeated_entries(fstream &logFile, const char *msg, const char *output_str) { static mutex log_mutex; static const char *last_msg_ptr = nullptr; @@ -371,10 +360,8 @@ static inline bool too_many_repeated_entries(fstream &logFile, const char *msg, } if (rep_count > MAX_REPEATED_LINES) { - logFile << CurrentTimeString() - << ": Last log entry repeated for " - << to_string(rep_count - MAX_REPEATED_LINES) - << " more lines" << endl; + logFile << CurrentTimeString() << ": Last log entry repeated for " + << to_string(rep_count - MAX_REPEATED_LINES) << " more lines" << endl; } last_msg_ptr = msg; @@ -406,8 +393,7 @@ static void do_log(int log_level, const char *msg, va_list args, void *param) lock_guard lock(wide_mutex); wide_buf.reserve(wNum + 1); wide_buf.resize(wNum - 1); - MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0], - wNum); + MultiByteToWideChar(CP_UTF8, 0, str, -1, &wide_buf[0], wNum); wide_buf.push_back('\n'); OutputDebugStringW(wide_buf.c_str()); @@ -443,29 +429,24 @@ bool OBSApp::InitGlobalConfigDefaults() { config_set_default_uint(appConfig, "General", "MaxLogs", 10); config_set_default_int(appConfig, "General", "InfoIncrement", -1); - config_set_default_string(appConfig, "General", "ProcessPriority", - "Normal"); - config_set_default_bool(appConfig, "General", "EnableAutoUpdates", - true); + config_set_default_string(appConfig, "General", "ProcessPriority", "Normal"); + config_set_default_bool(appConfig, "General", "EnableAutoUpdates", true); #if _WIN32 - config_set_default_string(appConfig, "Video", "Renderer", - "Direct3D 11"); + config_set_default_string(appConfig, "Video", "Renderer", "Direct3D 11"); #else config_set_default_string(appConfig, "Video", "Renderer", "OpenGL"); #endif #ifdef _WIN32 - config_set_default_bool(appConfig, "Audio", "DisableAudioDucking", - true); + config_set_default_bool(appConfig, "Audio", "DisableAudioDucking", true); config_set_default_bool(appConfig, "General", "BrowserHWAccel", true); #endif #ifdef __APPLE__ config_set_default_bool(appConfig, "General", "BrowserHWAccel", true); config_set_default_bool(appConfig, "Video", "DisableOSXVSync", true); - config_set_default_bool(appConfig, "Video", "ResetOSXVSyncOnExit", - true); + config_set_default_bool(appConfig, "Video", "ResetOSXVSyncOnExit", true); #endif return true; @@ -481,10 +462,8 @@ bool OBSApp::InitGlobalLocationDefaults() return false; } - config_set_default_string(appConfig, "Locations", "Configuration", - path); - config_set_default_string(appConfig, "Locations", "SceneCollections", - path); + config_set_default_string(appConfig, "Locations", "Configuration", path); + config_set_default_string(appConfig, "Locations", "SceneCollections", path); config_set_default_string(appConfig, "Locations", "Profiles", path); return true; @@ -494,66 +473,39 @@ void OBSApp::InitUserConfigDefaults() { config_set_default_bool(userConfig, "General", "ConfirmOnExit", true); - config_set_default_string(userConfig, "General", "HotkeyFocusType", - "NeverDisableHotkeys"); + config_set_default_string(userConfig, "General", "HotkeyFocusType", "NeverDisableHotkeys"); - config_set_default_bool(userConfig, "BasicWindow", "PreviewEnabled", - true); - config_set_default_bool(userConfig, "BasicWindow", "PreviewProgramMode", - false); - config_set_default_bool(userConfig, "BasicWindow", - "SceneDuplicationMode", true); - config_set_default_bool(userConfig, "BasicWindow", "SwapScenesMode", - true); - config_set_default_bool(userConfig, "BasicWindow", "SnappingEnabled", - true); - config_set_default_bool(userConfig, "BasicWindow", "ScreenSnapping", - true); - config_set_default_bool(userConfig, "BasicWindow", "SourceSnapping", - true); - config_set_default_bool(userConfig, "BasicWindow", "CenterSnapping", - false); - config_set_default_double(userConfig, "BasicWindow", "SnapDistance", - 10.0); - config_set_default_bool(userConfig, "BasicWindow", - "SpacingHelpersEnabled", true); - config_set_default_bool(userConfig, "BasicWindow", - "RecordWhenStreaming", false); - config_set_default_bool(userConfig, "BasicWindow", - "KeepRecordingWhenStreamStops", false); - config_set_default_bool(userConfig, "BasicWindow", "SysTrayEnabled", - true); - config_set_default_bool(userConfig, "BasicWindow", "SysTrayWhenStarted", - false); - config_set_default_bool(userConfig, "BasicWindow", "SaveProjectors", - false); - config_set_default_bool(userConfig, "BasicWindow", "ShowTransitions", - true); - config_set_default_bool(userConfig, "BasicWindow", - "ShowListboxToolbars", true); - config_set_default_bool(userConfig, "BasicWindow", "ShowStatusBar", - true); - config_set_default_bool(userConfig, "BasicWindow", "ShowSourceIcons", - true); - config_set_default_bool(userConfig, "BasicWindow", - "ShowContextToolbars", true); - config_set_default_bool(userConfig, "BasicWindow", "StudioModeLabels", - true); + config_set_default_bool(userConfig, "BasicWindow", "PreviewEnabled", true); + config_set_default_bool(userConfig, "BasicWindow", "PreviewProgramMode", false); + config_set_default_bool(userConfig, "BasicWindow", "SceneDuplicationMode", true); + config_set_default_bool(userConfig, "BasicWindow", "SwapScenesMode", true); + config_set_default_bool(userConfig, "BasicWindow", "SnappingEnabled", true); + config_set_default_bool(userConfig, "BasicWindow", "ScreenSnapping", true); + config_set_default_bool(userConfig, "BasicWindow", "SourceSnapping", true); + config_set_default_bool(userConfig, "BasicWindow", "CenterSnapping", false); + config_set_default_double(userConfig, "BasicWindow", "SnapDistance", 10.0); + config_set_default_bool(userConfig, "BasicWindow", "SpacingHelpersEnabled", true); + config_set_default_bool(userConfig, "BasicWindow", "RecordWhenStreaming", false); + config_set_default_bool(userConfig, "BasicWindow", "KeepRecordingWhenStreamStops", false); + config_set_default_bool(userConfig, "BasicWindow", "SysTrayEnabled", true); + config_set_default_bool(userConfig, "BasicWindow", "SysTrayWhenStarted", false); + config_set_default_bool(userConfig, "BasicWindow", "SaveProjectors", false); + config_set_default_bool(userConfig, "BasicWindow", "ShowTransitions", true); + config_set_default_bool(userConfig, "BasicWindow", "ShowListboxToolbars", true); + config_set_default_bool(userConfig, "BasicWindow", "ShowStatusBar", true); + config_set_default_bool(userConfig, "BasicWindow", "ShowSourceIcons", true); + config_set_default_bool(userConfig, "BasicWindow", "ShowContextToolbars", true); + config_set_default_bool(userConfig, "BasicWindow", "StudioModeLabels", true); - config_set_default_bool(userConfig, "BasicWindow", "VerticalVolControl", - false); + config_set_default_bool(userConfig, "BasicWindow", "VerticalVolControl", false); - config_set_default_bool(userConfig, "BasicWindow", - "MultiviewMouseSwitch", true); + config_set_default_bool(userConfig, "BasicWindow", "MultiviewMouseSwitch", true); - config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawNames", - true); + config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawNames", true); - config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawAreas", - true); + config_set_default_bool(userConfig, "BasicWindow", "MultiviewDrawAreas", true); - config_set_default_bool(userConfig, "BasicWindow", - "MediaControlsCountdownTimer", true); + config_set_default_bool(userConfig, "BasicWindow", "MediaControlsCountdownTimer", true); } static bool do_mkdir(const char *path) @@ -580,8 +532,7 @@ static bool MakeUserDirs() if (!do_mkdir(path)) return false; - if (GetAppConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= - 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/profiler_data") <= 0) return false; if (!do_mkdir(path)) return false; @@ -600,8 +551,7 @@ static bool MakeUserDirs() return false; #endif - if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= - 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0) return false; if (!do_mkdir(path)) return false; @@ -615,18 +565,15 @@ constexpr std::string_view OBSScenesSubDirectory = "obs-studio/basic/scenes"; static bool MakeUserProfileDirs() { const std::filesystem::path userProfilePath = - App()->userProfilesLocation / - std::filesystem::u8path(OBSProfileSubDirectory); + App()->userProfilesLocation / std::filesystem::u8path(OBSProfileSubDirectory); const std::filesystem::path userScenesPath = - App()->userScenesLocation / - std::filesystem::u8path(OBSScenesSubDirectory); + App()->userScenesLocation / std::filesystem::u8path(OBSScenesSubDirectory); if (!std::filesystem::exists(userProfilePath)) { try { std::filesystem::create_directories(userProfilePath); } catch (const std::filesystem::filesystem_error &error) { - blog(LOG_ERROR, - "Failed to create user profile directory '%s'\n%s", + blog(LOG_ERROR, "Failed to create user profile directory '%s'\n%s", userProfilePath.u8string().c_str(), error.what()); return false; } @@ -636,8 +583,7 @@ static bool MakeUserProfileDirs() try { std::filesystem::create_directories(userScenesPath); } catch (const std::filesystem::filesystem_error &error) { - blog(LOG_ERROR, - "Failed to create user scene collection directory '%s'\n%s", + blog(LOG_ERROR, "Failed to create user scene collection directory '%s'\n%s", userScenesPath.u8string().c_str(), error.what()); return false; } @@ -652,34 +598,26 @@ bool OBSApp::UpdatePre22MultiviewLayout(const char *layout) return false; if (astrcmpi(layout, "horizontaltop") == 0) { - config_set_int( - userConfig, "BasicWindow", "MultiviewLayout", - static_cast( - MultiviewLayout::HORIZONTAL_TOP_8_SCENES)); + config_set_int(userConfig, "BasicWindow", "MultiviewLayout", + static_cast(MultiviewLayout::HORIZONTAL_TOP_8_SCENES)); return true; } if (astrcmpi(layout, "horizontalbottom") == 0) { - config_set_int( - userConfig, "BasicWindow", "MultiviewLayout", - static_cast( - MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES)); + config_set_int(userConfig, "BasicWindow", "MultiviewLayout", + static_cast(MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES)); return true; } if (astrcmpi(layout, "verticalleft") == 0) { - config_set_int( - userConfig, "BasicWindow", "MultiviewLayout", - static_cast( - MultiviewLayout::VERTICAL_LEFT_8_SCENES)); + config_set_int(userConfig, "BasicWindow", "MultiviewLayout", + static_cast(MultiviewLayout::VERTICAL_LEFT_8_SCENES)); return true; } if (astrcmpi(layout, "verticalright") == 0) { - config_set_int( - userConfig, "BasicWindow", "MultiviewLayout", - static_cast( - MultiviewLayout::VERTICAL_RIGHT_8_SCENES)); + config_set_int(userConfig, "BasicWindow", "MultiviewLayout", + static_cast(MultiviewLayout::VERTICAL_RIGHT_8_SCENES)); return true; } @@ -701,18 +639,15 @@ bool OBSApp::InitGlobalConfig() return false; } - uint32_t lastVersion = - config_get_int(appConfig, "General", "LastVersion"); + uint32_t lastVersion = config_get_int(appConfig, "General", "LastVersion"); if (lastVersion < MAKE_SEMANTIC_VERSION(31, 0, 0)) { - bool migratedUserSettings = - config_get_bool(appConfig, "General", "Pre31Migrated"); + bool migratedUserSettings = config_get_bool(appConfig, "General", "Pre31Migrated"); if (!migratedUserSettings) { bool migrated = MigrateGlobalSettings(); - config_set_bool(appConfig, "General", "Pre31Migrated", - migrated); + config_set_bool(appConfig, "General", "Pre31Migrated", migrated); config_save_safe(appConfig, "tmp", nullptr); } } @@ -721,22 +656,18 @@ bool OBSApp::InitGlobalConfig() InitGlobalLocationDefaults(); if (IsPortableMode()) { - userConfigLocation = std::filesystem::u8path( - config_get_default_string(appConfig, "Locations", - "Configuration")); - userScenesLocation = std::filesystem::u8path( - config_get_default_string(appConfig, "Locations", - "SceneCollections")); - userProfilesLocation = std::filesystem::u8path( - config_get_default_string(appConfig, "Locations", - "Profiles")); + userConfigLocation = + std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Configuration")); + userScenesLocation = + std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "SceneCollections")); + userProfilesLocation = + std::filesystem::u8path(config_get_default_string(appConfig, "Locations", "Profiles")); } else { - userConfigLocation = std::filesystem::u8path(config_get_string( - appConfig, "Locations", "Configuration")); - userScenesLocation = std::filesystem::u8path(config_get_string( - appConfig, "Locations", "SceneCollections")); - userProfilesLocation = std::filesystem::u8path( - config_get_string(appConfig, "Locations", "Profiles")); + userConfigLocation = + std::filesystem::u8path(config_get_string(appConfig, "Locations", "Configuration")); + userScenesLocation = + std::filesystem::u8path(config_get_string(appConfig, "Locations", "SceneCollections")); + userProfilesLocation = std::filesystem::u8path(config_get_string(appConfig, "Locations", "Profiles")); } bool userConfigResult = InitUserConfig(userConfigLocation, lastVersion); @@ -744,16 +675,13 @@ bool OBSApp::InitGlobalConfig() return userConfigResult; } -bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation, - uint32_t lastVersion) +bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation, uint32_t lastVersion) { bool hasChanges = false; - const std::string userConfigFile = - userConfigLocation.u8string() + "/obs-studio/user.ini"; + const std::string userConfigFile = userConfigLocation.u8string() + "/obs-studio/user.ini"; - int errorCode = - userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS); + int errorCode = userConfig.Open(userConfigFile.c_str(), CONFIG_OPEN_ALWAYS); if (errorCode != CONFIG_SUCCESS) { OBSErrorBox(nullptr, "Failed to open user.ini: %d", errorCode); @@ -763,36 +691,27 @@ bool OBSApp::InitUserConfig(std::filesystem::path &userConfigLocation, hasChanges = MigrateLegacySettings(lastVersion); if (!opt_starting_collection.empty()) { - const OBSBasic *basic = - reinterpret_cast(GetMainWindow()); + const OBSBasic *basic = reinterpret_cast(GetMainWindow()); const std::optional foundCollection = - basic->GetSceneCollectionByName( - opt_starting_collection); + basic->GetSceneCollectionByName(opt_starting_collection); if (foundCollection) { - config_set_string(userConfig, "Basic", - "SceneCollection", - foundCollection.value().name.c_str()); - config_set_string( - userConfig, "Basic", "SceneCollectionFile", - foundCollection.value().fileName.c_str()); + config_set_string(userConfig, "Basic", "SceneCollection", foundCollection.value().name.c_str()); + config_set_string(userConfig, "Basic", "SceneCollectionFile", + foundCollection.value().fileName.c_str()); hasChanges = true; } } if (!opt_starting_profile.empty()) { - const OBSBasic *basic = - reinterpret_cast(GetMainWindow()); + const OBSBasic *basic = reinterpret_cast(GetMainWindow()); - const std::optional foundProfile = - basic->GetProfileByName(opt_starting_profile); + const std::optional foundProfile = basic->GetProfileByName(opt_starting_profile); if (foundProfile) { - config_set_string(userConfig, "Basic", "Profile", - foundProfile.value().name.c_str()); - config_set_string( - userConfig, "Basic", "ProfileDir", - foundProfile.value().directoryName.c_str()); + config_set_string(userConfig, "Basic", "Profile", foundProfile.value().name.c_str()); + config_set_string(userConfig, "Basic", "ProfileDir", + foundProfile.value().directoryName.c_str()); hasChanges = true; } @@ -817,27 +736,20 @@ bool OBSApp::MigrateLegacySettings(const uint32_t lastVersion) const uint32_t v24 = MAKE_SEMANTIC_VERSION(24, 0, 0); const uint32_t v24_1 = MAKE_SEMANTIC_VERSION(24, 1, 0); - const map defaultsMap{{{v19, "Pre19Defaults"}, - {v21, "Pre21Defaults"}, - {v23, "Pre23Defaults"}, - {v24_1, "Pre24.1Defaults"}}}; + const map defaultsMap{ + {{v19, "Pre19Defaults"}, {v21, "Pre21Defaults"}, {v23, "Pre23Defaults"}, {v24_1, "Pre24.1Defaults"}}}; for (auto &[version, configKey] : defaultsMap) { - if (!config_has_user_value(userConfig, "General", - configKey.c_str())) { - bool useOldDefaults = lastVersion && - lastVersion < version; - config_set_bool(userConfig, "General", - configKey.c_str(), useOldDefaults); + if (!config_has_user_value(userConfig, "General", configKey.c_str())) { + bool useOldDefaults = lastVersion && lastVersion < version; + config_set_bool(userConfig, "General", configKey.c_str(), useOldDefaults); hasChanges = true; } } - if (config_has_user_value(userConfig, "BasicWindow", - "MultiviewLayout")) { - const char *layout = config_get_string( - userConfig, "BasicWindow", "MultiviewLayout"); + if (config_has_user_value(userConfig, "BasicWindow", "MultiviewLayout")) { + const char *layout = config_get_string(userConfig, "BasicWindow", "MultiviewLayout"); bool layoutUpdated = UpdatePre22MultiviewLayout(layout); @@ -845,13 +757,10 @@ bool OBSApp::MigrateLegacySettings(const uint32_t lastVersion) } if (lastVersion && lastVersion < v24) { - bool disableHotkeysInFocus = config_get_bool( - userConfig, "General", "DisableHotkeysInFocus"); + bool disableHotkeysInFocus = config_get_bool(userConfig, "General", "DisableHotkeysInFocus"); if (disableHotkeysInFocus) { - config_set_string(userConfig, "General", - "HotkeyFocusType", - "DisableHotkeysInFocus"); + config_set_string(userConfig, "General", "HotkeyFocusType", "DisableHotkeysInFocus"); } hasChanges = true; @@ -869,8 +778,7 @@ bool OBSApp::MigrateGlobalSettings() int len = GetAppConfigPath(path, sizeof(path), nullptr); if (len <= 0) { - OBSErrorBox(nullptr, - "Unable to get global configuration path."); + OBSErrorBox(nullptr, "Unable to get global configuration path."); return false; } @@ -878,20 +786,17 @@ bool OBSApp::MigrateGlobalSettings() legacyConfigFileString.reserve(strlen(path) + OBSGlobalIniPath.size()); legacyConfigFileString.append(path).append(OBSGlobalIniPath); - const std::filesystem::path legacyGlobalConfigFile = - std::filesystem::u8path(legacyConfigFileString); + const std::filesystem::path legacyGlobalConfigFile = std::filesystem::u8path(legacyConfigFileString); std::string configFileString; configFileString.reserve(strlen(path) + OBSUserIniPath.size()); configFileString.append(path).append(OBSUserIniPath); - const std::filesystem::path userConfigFile = - std::filesystem::u8path(configFileString); + const std::filesystem::path userConfigFile = std::filesystem::u8path(configFileString); if (std::filesystem::exists(userConfigFile)) { - OBSErrorBox( - nullptr, - "Unable to migrate global configuration - user configuration file already exists."); + OBSErrorBox(nullptr, + "Unable to migrate global configuration - user configuration file already exists."); return false; } @@ -905,8 +810,7 @@ bool OBSApp::InitLocale() ProfileScope("OBSApp::InitLocale"); const char *lang = config_get_string(userConfig, "General", "Language"); - bool userLocale = - config_has_user_value(userConfig, "General", "Language"); + bool userLocale = config_has_user_value(userConfig, "General", "Language"); if (!userLocale || !lang || lang[0] == '\0') lang = DEFAULT_LANG; @@ -914,8 +818,7 @@ bool OBSApp::InitLocale() // set basic default application locale if (!locale.empty()) - QLocale::setDefault(QLocale( - QString::fromStdString(locale).replace('-', '_'))); + QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_'))); string englishPath; if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) { @@ -925,8 +828,7 @@ bool OBSApp::InitLocale() textLookup = text_lookup_create(englishPath.c_str()); if (!textLookup) { - OBSErrorBox(NULL, "Failed to create locale from file '%s'", - englishPath.c_str()); + OBSErrorBox(NULL, "Failed to create locale from file '%s'", englishPath.c_str()); return false; } @@ -950,15 +852,12 @@ bool OBSApp::InitLocale() if (!text_lookup_add(textLookup, path.c_str())) continue; - blog(LOG_INFO, "Using preferred locale '%s'", - locale_.c_str()); + blog(LOG_INFO, "Using preferred locale '%s'", locale_.c_str()); locale = locale_; // set application default locale to the new choosen one if (!locale.empty()) - QLocale::setDefault(QLocale( - QString::fromStdString(locale).replace( - '-', '_'))); + QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_'))); return true; } @@ -972,19 +871,16 @@ bool OBSApp::InitLocale() string path; if (GetDataFilePath(file.str().c_str(), path)) { if (!text_lookup_add(textLookup, path.c_str())) - blog(LOG_ERROR, "Failed to add locale file '%s'", - path.c_str()); + blog(LOG_ERROR, "Failed to add locale file '%s'", path.c_str()); } else { - blog(LOG_ERROR, "Could not find locale file '%s'", - file.str().c_str()); + blog(LOG_ERROR, "Could not find locale file '%s'", file.str().c_str()); } return true; } #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) -void ParseBranchesJson(const std::string &jsonString, vector &out, - std::string &error) +void ParseBranchesJson(const std::string &jsonString, vector &out, std::string &error) { JsonBranches branches; @@ -1021,8 +917,7 @@ bool LoadBranchesFile(vector &out) string error; string branchesText; - BPtr branchesFilePath = - GetAppConfigPathPtr("obs-studio/updates/branches.json"); + BPtr branchesFilePath = GetAppConfigPathPtr("obs-studio/updates/branches.json"); QFile branchesFile(branchesFilePath.Get()); if (!branchesFile.open(QIODevice::ReadOnly)) { @@ -1041,8 +936,7 @@ bool LoadBranchesFile(vector &out) return !out.empty(); fail: - blog(LOG_WARNING, "Loading branches from file failed: %s", - error.c_str()); + blog(LOG_WARNING, "Loading branches from file failed: %s", error.c_str()); return false; } #endif @@ -1056,8 +950,7 @@ void OBSApp::SetBranchData(const string &data) ParseBranchesJson(data, result, error); if (!error.empty()) { - blog(LOG_WARNING, "Reading branches JSON response failed: %s", - error.c_str()); + blog(LOG_WARNING, "Reading branches JSON response failed: %s", error.c_str()); return; } @@ -1088,8 +981,7 @@ std::vector OBSApp::GetBranches() /* Copy additional branches to result (if any) */ if (!updateBranches.empty()) - out.insert(out.end(), updateBranches.begin(), - updateBranches.end()); + out.insert(out.end(), updateBranches.begin(), updateBranches.end()); return out; } @@ -1108,11 +1000,9 @@ OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store) /* Handle SIGINT properly */ socketpair(AF_UNIX, SOCK_STREAM, 0, sigintFd); snInt = new QSocketNotifier(sigintFd[1], QSocketNotifier::Read, this); - connect(snInt, &QSocketNotifier::activated, this, - &OBSApp::ProcessSigInt); + connect(snInt, &QSocketNotifier::activated, this, &OBSApp::ProcessSigInt); #else - connect(qApp, &QGuiApplication::commitDataRequest, this, - &OBSApp::commitData); + connect(qApp, &QGuiApplication::commitDataRequest, this, &OBSApp::commitData); #endif sleepInhibitor = os_inhibit_sleep_create("OBS Video/audio"); @@ -1127,8 +1017,7 @@ OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store) OBSApp::~OBSApp() { #ifdef _WIN32 - bool disableAudioDucking = - config_get_bool(appConfig, "Audio", "DisableAudioDucking"); + bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking"); if (disableAudioDucking) DisableAudioDucking(false); #else @@ -1138,10 +1027,8 @@ OBSApp::~OBSApp() #endif #ifdef __APPLE__ - bool vsyncDisabled = - config_get_bool(appConfig, "Video", "DisableOSXVSync"); - bool resetVSync = - config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit"); + bool vsyncDisabled = config_get_bool(appConfig, "Video", "DisableOSXVSync"); + bool resetVSync = config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit"); if (vsyncDisabled && resetVSync) EnableOSXVSync(true); #endif @@ -1168,8 +1055,7 @@ static void move_basic_to_profiles(void) } const std::filesystem::path profilesPath = - App()->userProfilesLocation / - std::filesystem::u8path("obs-studio/basic/profiles"); + App()->userProfilesLocation / std::filesystem::u8path("obs-studio/basic/profiles"); if (std::filesystem::exists(profilesPath)) { return; @@ -1178,14 +1064,12 @@ static void move_basic_to_profiles(void) try { std::filesystem::create_directories(profilesPath); } catch (const std::filesystem::filesystem_error &error) { - blog(LOG_ERROR, - "Failed to create profiles directory for migration from basic profile\n%s", + blog(LOG_ERROR, "Failed to create profiles directory for migration from basic profile\n%s", error.what()); return; } - const std::filesystem::path newProfilePath = - profilesPath / std::filesystem::u8path(Str("Untitled")); + const std::filesystem::path newProfilePath = profilesPath / std::filesystem::u8path(Str("Untitled")); for (auto &entry : std::filesystem::directory_iterator(basicPath)) { if (entry.is_directory()) { @@ -1198,31 +1082,22 @@ static void move_basic_to_profiles(void) if (!std::filesystem::exists(newProfilePath)) { try { - std::filesystem::create_directory( - newProfilePath); - } catch ( - const std::filesystem::filesystem_error &error) { - blog(LOG_ERROR, - "Failed to create profile directory for 'Untitled'\n%s", - error.what()); + std::filesystem::create_directory(newProfilePath); + } catch (const std::filesystem::filesystem_error &error) { + blog(LOG_ERROR, "Failed to create profile directory for 'Untitled'\n%s", error.what()); return; } } - const filesystem::path destinationFile = - newProfilePath / entry.path().filename(); + const filesystem::path destinationFile = newProfilePath / entry.path().filename(); - const auto copyOptions = - std::filesystem::copy_options::overwrite_existing; + const auto copyOptions = std::filesystem::copy_options::overwrite_existing; try { - std::filesystem::copy(entry.path(), destinationFile, - copyOptions); + std::filesystem::copy(entry.path(), destinationFile, copyOptions); } catch (const std::filesystem::filesystem_error &error) { - blog(LOG_ERROR, - "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s", - entry.path().filename().u8string().c_str(), - error.what()); + blog(LOG_ERROR, "Failed to copy basic profile file '%s' to new profile 'Untitled'\n%s", + entry.path().filename().u8string().c_str(), error.what()); return; } @@ -1244,8 +1119,7 @@ static void move_basic_to_scene_collections(void) } const std::filesystem::path sceneCollectionPath = - App()->userScenesLocation / - std::filesystem::u8path("obs-studio/basic/scenes"); + App()->userScenesLocation / std::filesystem::u8path("obs-studio/basic/scenes"); if (std::filesystem::exists(sceneCollectionPath)) { return; @@ -1260,18 +1134,14 @@ static void move_basic_to_scene_collections(void) return; } - const std::filesystem::path sourceFile = - basicPath / std::filesystem::u8path("scenes.json"); + const std::filesystem::path sourceFile = basicPath / std::filesystem::u8path("scenes.json"); const std::filesystem::path destinationFile = - (sceneCollectionPath / std::filesystem::u8path(Str("Untitled"))) - .replace_extension(".json"); + (sceneCollectionPath / std::filesystem::u8path(Str("Untitled"))).replace_extension(".json"); try { std::filesystem::rename(sourceFile, destinationFile); } catch (const std::filesystem::filesystem_error &error) { - blog(LOG_ERROR, - "Failed to rename basic scene collection file:\n%s", - error.what()); + blog(LOG_ERROR, "Failed to rename basic scene collection file:\n%s", error.what()); return; } } @@ -1289,34 +1159,24 @@ void OBSApp::AppInit() if (!InitTheme()) throw "Failed to load theme"; - config_set_default_string(userConfig, "Basic", "Profile", - Str("Untitled")); - config_set_default_string(userConfig, "Basic", "ProfileDir", - Str("Untitled")); - config_set_default_string(userConfig, "Basic", "SceneCollection", - Str("Untitled")); - config_set_default_string(userConfig, "Basic", "SceneCollectionFile", - Str("Untitled")); - config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile", - true); + config_set_default_string(userConfig, "Basic", "Profile", Str("Untitled")); + config_set_default_string(userConfig, "Basic", "ProfileDir", Str("Untitled")); + config_set_default_string(userConfig, "Basic", "SceneCollection", Str("Untitled")); + config_set_default_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled")); + config_set_default_bool(userConfig, "Basic", "ConfigOnNewProfile", true); if (!config_has_user_value(userConfig, "Basic", "Profile")) { - config_set_string(userConfig, "Basic", "Profile", - Str("Untitled")); - config_set_string(userConfig, "Basic", "ProfileDir", - Str("Untitled")); + config_set_string(userConfig, "Basic", "Profile", Str("Untitled")); + config_set_string(userConfig, "Basic", "ProfileDir", Str("Untitled")); } if (!config_has_user_value(userConfig, "Basic", "SceneCollection")) { - config_set_string(userConfig, "Basic", "SceneCollection", - Str("Untitled")); - config_set_string(userConfig, "Basic", "SceneCollectionFile", - Str("Untitled")); + config_set_string(userConfig, "Basic", "SceneCollection", Str("Untitled")); + config_set_string(userConfig, "Basic", "SceneCollectionFile", Str("Untitled")); } #ifdef _WIN32 - bool disableAudioDucking = - config_get_bool(appConfig, "Audio", "DisableAudioDucking"); + bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking"); if (disableAudioDucking) DisableAudioDucking(true); #endif @@ -1337,8 +1197,7 @@ void OBSApp::AppInit() const char *OBSApp::GetRenderModule() const { - const char *renderer = - config_get_string(appConfig, "Video", "Renderer"); + const char *renderer = config_get_string(appConfig, "Video", "Renderer"); return (astrcmpi(renderer, "Direct3D 11") == 0) ? DL_D3D11 : DL_OPENGL; } @@ -1347,8 +1206,7 @@ static bool StartupOBS(const char *locale, profiler_name_store_t *store) { char path[512]; - if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= - 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/plugin_config") <= 0) return false; return obs_startup(locale, path, store); @@ -1356,9 +1214,7 @@ static bool StartupOBS(const char *locale, profiler_name_store_t *store) inline void OBSApp::ResetHotkeyState(bool inFocus) { - obs_hotkey_enable_background_press( - (inFocus && enableHotkeysInFocus) || - (!inFocus && enableHotkeysOutOfFocus)); + obs_hotkey_enable_background_press((inFocus && enableHotkeysInFocus) || (!inFocus && enableHotkeysOutOfFocus)); } void OBSApp::UpdateHotkeyFocusSetting(bool resetState) @@ -1366,8 +1222,7 @@ void OBSApp::UpdateHotkeyFocusSetting(bool resetState) enableHotkeysInFocus = true; enableHotkeysOutOfFocus = true; - const char *hotkeyFocusType = - config_get_string(userConfig, "General", "HotkeyFocusType"); + const char *hotkeyFocusType = config_get_string(userConfig, "General", "HotkeyFocusType"); if (astrcmpi(hotkeyFocusType, "DisableHotkeysInFocus") == 0) { enableHotkeysInFocus = false; @@ -1399,9 +1254,7 @@ static void ui_task_handler(obs_task_t task, void *param, bool wait) /* to get clang-format to behave */ task(param); }; - QMetaObject::invokeMethod(App(), "Exec", - wait ? WaitConnection() : Qt::AutoConnection, - Q_ARG(VoidFunc, doTask)); + QMetaObject::invokeMethod(App(), "Exec", wait ? WaitConnection() : Qt::AutoConnection, Q_ARG(VoidFunc, doTask)); } bool OBSApp::OBSInit() @@ -1424,10 +1277,8 @@ bool OBSApp::OBSInit() } #endif - QPlatformNativeInterface *native = - QGuiApplication::platformNativeInterface(); - obs_set_nix_platform_display( - native->nativeResourceForIntegration("display")); + QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); + obs_set_nix_platform_display(native->nativeResourceForIntegration("display")); #endif #ifdef __APPLE__ @@ -1442,28 +1293,22 @@ bool OBSApp::OBSInit() obs_set_ui_task_handler(ui_task_handler); #if defined(_WIN32) || defined(__APPLE__) - bool browserHWAccel = - config_get_bool(userConfig, "General", "BrowserHWAccel"); + bool browserHWAccel = config_get_bool(userConfig, "General", "BrowserHWAccel"); OBSDataAutoRelease settings = obs_data_create(); obs_data_set_bool(settings, "BrowserHWAccel", browserHWAccel); obs_apply_private_data(settings); - blog(LOG_INFO, "Current Date/Time: %s", - CurrentDateTimeString().c_str()); + blog(LOG_INFO, "Current Date/Time: %s", CurrentDateTimeString().c_str()); - blog(LOG_INFO, "Browser Hardware Acceleration: %s", - browserHWAccel ? "true" : "false"); + blog(LOG_INFO, "Browser Hardware Acceleration: %s", browserHWAccel ? "true" : "false"); #endif #ifdef _WIN32 - bool hideFromCapture = config_get_bool(userConfig, "BasicWindow", - "HideOBSWindowsFromCapture"); - blog(LOG_INFO, "Hide OBS windows from screen capture: %s", - hideFromCapture ? "true" : "false"); + bool hideFromCapture = config_get_bool(userConfig, "BasicWindow", "HideOBSWindowsFromCapture"); + blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hideFromCapture ? "true" : "false"); #endif - blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(), - QT_VERSION_STR); + blog(LOG_INFO, "Qt Version: %s (runtime), %s (compiled)", qVersion(), QT_VERSION_STR); blog(LOG_INFO, "Portable mode: %s", portable_mode ? "true" : "false"); if (safe_mode) { @@ -1482,9 +1327,7 @@ bool OBSApp::OBSInit() mainWindow->OBSInit(); connect(this, &QGuiApplication::applicationStateChanged, - [this](Qt::ApplicationState state) { - ResetHotkeyState(state == Qt::ApplicationActive); - }); + [this](Qt::ApplicationState state) { ResetHotkeyState(state == Qt::ApplicationActive); }); ResetHotkeyState(applicationState() == Qt::ApplicationActive); return true; } @@ -1496,8 +1339,7 @@ string OBSApp::GetVersionString(bool platform) const #ifdef HAVE_OBSCONFIG_H ver << obs_get_version_string(); #else - ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "." - << LIBOBS_API_PATCH_VER; + ver << LIBOBS_API_MAJOR_VER << "." << LIBOBS_API_MINOR_VER << "." << LIBOBS_API_PATCH_VER; #endif @@ -1611,8 +1453,7 @@ bool OBSApp::notify(QObject *receiver, QEvent *e) windowType = window->flags() & Qt::WindowType::WindowType_Mask; - if (windowType == Qt::WindowType::Dialog || - windowType == Qt::WindowType::Window || + if (windowType == Qt::WindowType::Dialog || windowType == Qt::WindowType::Window || windowType == Qt::WindowType::Tool) { OBSBasic *main = reinterpret_cast(GetMainWindow()); if (main) @@ -1623,8 +1464,7 @@ skip: return QApplication::notify(receiver, e); } -QString OBSTranslator::translate(const char *, const char *sourceText, - const char *, int) const +QString OBSTranslator::translate(const char *, const char *sourceText, const char *, int) const { const char *out = nullptr; QString str(sourceText); @@ -1704,8 +1544,7 @@ static void delete_oldest_file(bool has_prefix, const char *location) uint64_t oldest_ts = (uint64_t)-1; struct os_dirent *entry; - unsigned int maxLogs = (unsigned int)config_get_uint( - App()->GetUserConfig(), "General", "MaxLogs"); + unsigned int maxLogs = (unsigned int)config_get_uint(App()->GetUserConfig(), "General", "MaxLogs"); os_dir_t *dir = os_opendir(logDir); if (dir) { @@ -1715,8 +1554,7 @@ static void delete_oldest_file(bool has_prefix, const char *location) if (entry->directory || *entry->d_name == '.') continue; - uint64_t ts = - convert_log_name(has_prefix, entry->d_name); + uint64_t ts = convert_log_name(has_prefix, entry->d_name); if (ts) { if (ts < oldest_ts) { @@ -1739,8 +1577,7 @@ static void delete_oldest_file(bool has_prefix, const char *location) } } -static void get_last_log(bool has_prefix, const char *subdir_to_use, - std::string &last) +static void get_last_log(bool has_prefix, const char *subdir_to_use, std::string &last) { BPtr logDir(GetAppConfigPathPtr(subdir_to_use)); struct os_dirent *entry; @@ -1752,8 +1589,7 @@ static void get_last_log(bool has_prefix, const char *subdir_to_use, if (entry->directory || *entry->d_name == '.') continue; - uint64_t ts = - convert_log_name(has_prefix, entry->d_name); + uint64_t ts = convert_log_name(has_prefix, entry->d_name); if (ts > highest_ts) { last = entry->d_name; @@ -1772,19 +1608,16 @@ string GenerateTimeDateFilename(const char *extension, bool noSpace) struct tm *cur_time; cur_time = localtime(&now); - snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s", - cur_time->tm_year + 1900, cur_time->tm_mon + 1, - cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour, - cur_time->tm_min, cur_time->tm_sec, extension); + snprintf(file, sizeof(file), "%d-%02d-%02d%c%02d-%02d-%02d.%s", cur_time->tm_year + 1900, cur_time->tm_mon + 1, + cur_time->tm_mday, noSpace ? '_' : ' ', cur_time->tm_hour, cur_time->tm_min, cur_time->tm_sec, + extension); return string(file); } -string GenerateSpecifiedFilename(const char *extension, bool noSpace, - const char *format) +string GenerateSpecifiedFilename(const char *extension, bool noSpace, const char *format) { - BPtr filename = - os_generate_formatted_filename(extension, !noSpace, format); + BPtr filename = os_generate_formatted_filename(extension, !noSpace, format); return string(filename); } @@ -1842,8 +1675,7 @@ static void remove_reserved_file_characters(string &s) replace(s.begin(), s.end(), '<', '_'); } -string GetFormatString(const char *format, const char *prefix, - const char *suffix) +string GetFormatString(const char *format, const char *prefix, const char *suffix) { string f; @@ -1897,8 +1729,7 @@ string GetFormatExt(const char *container) return ext; } -string GetOutputFilename(const char *path, const char *container, bool noSpace, - bool overwrite, const char *format) +string GetOutputFilename(const char *path, const char *container, bool noSpace, bool overwrite, const char *format) { OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); @@ -1906,12 +1737,9 @@ string GetOutputFilename(const char *path, const char *container, bool noSpace, if (!dir) { if (main->isVisible()) - OBSMessageBox::warning(main, - QTStr("Output.BadPath.Title"), - QTStr("Output.BadPath.Text")); + OBSMessageBox::warning(main, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text")); else - main->SysTrayNotify(QTStr("Output.BadPath.Text"), - QSystemTrayIcon::Warning); + main->SysTrayNotify(QTStr("Output.BadPath.Text"), QSystemTrayIcon::Warning); return ""; } @@ -1990,21 +1818,18 @@ static auto ProfilerNameStoreRelease = [](profiler_name_store_t *store) { profiler_name_store_free(store); }; -using ProfilerNameStore = std::unique_ptr; +using ProfilerNameStore = std::unique_ptr; ProfilerNameStore CreateNameStore() { - return ProfilerNameStore{profiler_name_store_create(), - ProfilerNameStoreRelease}; + return ProfilerNameStore{profiler_name_store_create(), ProfilerNameStoreRelease}; } static auto SnapshotRelease = [](profiler_snapshot_t *snap) { profile_snapshot_free(snap); }; -using ProfilerSnapshot = - std::unique_ptr; +using ProfilerSnapshot = std::unique_ptr; ProfilerSnapshot GetSnapshot() { @@ -2029,8 +1854,7 @@ static void SaveProfilerData(const ProfilerSnapshot &snap) BPtr path = GetAppConfigPathPtr(dst.str().c_str()); if (!profiler_snapshot_dump_csv_gz(snap.get(), path)) - blog(LOG_WARNING, "Could not save profiler data to '%s'", - static_cast(path)); + blog(LOG_WARNING, "Could not save profiler data to '%s'", static_cast(path)); } static auto ProfilerFree = [](void *) { @@ -2046,13 +1870,10 @@ static auto ProfilerFree = [](void *) { profiler_free(); }; -QAccessibleInterface *accessibleFactory(const QString &classname, - QObject *object) +QAccessibleInterface *accessibleFactory(const QString &classname, QObject *object) { - if (classname == QLatin1String("VolumeSlider") && object && - object->isWidgetType()) - return new VolumeAccessibleInterface( - static_cast(object)); + if (classname == QLatin1String("VolumeSlider") && object && object->isWidgetType()) + return new VolumeAccessibleInterface(static_cast(object)); return nullptr; } @@ -2064,8 +1885,7 @@ static int run_program(fstream &logFile, int argc, char *argv[]) auto profilerNameStore = CreateNameStore(); - std::unique_ptr prof_release( - static_cast(&ProfilerFree), ProfilerFree); + std::unique_ptr prof_release(static_cast(&ProfilerFree), ProfilerFree); profiler_start(); profile_register_root(run_program_init, 0); @@ -2073,8 +1893,7 @@ static int run_program(fstream &logFile, int argc, char *argv[]) ScopeProfiler prof{run_program_init}; #ifdef _WIN32 - QGuiApplication::setHighDpiScaleFactorRoundingPolicy( - Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); + QGuiApplication::setHighDpiScaleFactorRoundingPolicy(Qt::HighDpiScaleFactorRoundingPolicy::PassThrough); #endif QCoreApplication::addLibraryPath("."); @@ -2109,11 +1928,9 @@ static int run_program(fstream &logFile, int argc, char *argv[]) OBSApp program(argc, argv, profilerNameStore.get()); try { QAccessible::installFactory(accessibleFactory); - QFontDatabase::addApplicationFont( - ":/fonts/OpenSans-Regular.ttf"); + QFontDatabase::addApplicationFont(":/fonts/OpenSans-Regular.ttf"); QFontDatabase::addApplicationFont(":/fonts/OpenSans-Bold.ttf"); - QFontDatabase::addApplicationFont( - ":/fonts/OpenSans-Italic.ttf"); + QFontDatabase::addApplicationFont(":/fonts/OpenSans-Italic.ttf"); bool created_log = false; @@ -2139,13 +1956,10 @@ static int run_program(fstream &logFile, int argc, char *argv[]) } if (!multi) { - QMessageBox mb(QMessageBox::Question, - QTStr("AlreadyRunning.Title"), + QMessageBox mb(QMessageBox::Question, QTStr("AlreadyRunning.Title"), QTStr("AlreadyRunning.Text")); - mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), - QMessageBox::YesRole); - QPushButton *cancelButton = mb.addButton( - QTStr("Cancel"), QMessageBox::NoRole); + mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::YesRole); + QPushButton *cancelButton = mb.addButton(QTStr("Cancel"), QMessageBox::NoRole); mb.setDefaultButton(cancelButton); mb.exec(); @@ -2184,9 +1998,7 @@ static int run_program(fstream &logFile, int argc, char *argv[]) os_dir_t *crosDir = os_opendir("/opt/google/cros-containers"); if (crosDir) { QMessageBox::StandardButtons buttons(QMessageBox::Ok); - QMessageBox mb(QMessageBox::Critical, - QTStr("ChromeOS.Title"), - QTStr("ChromeOS.Text"), buttons, + QMessageBox mb(QMessageBox::Critical, QTStr("ChromeOS.Title"), QTStr("ChromeOS.Text"), buttons, nullptr); mb.exec(); @@ -2198,36 +2010,27 @@ static int run_program(fstream &logFile, int argc, char *argv[]) create_log_file(logFile); if (unclean_shutdown) { - blog(LOG_WARNING, - "[Safe Mode] Unclean shutdown detected!"); + blog(LOG_WARNING, "[Safe Mode] Unclean shutdown detected!"); } if (unclean_shutdown && !safe_mode) { - QMessageBox mb(QMessageBox::Warning, - QTStr("AutoSafeMode.Title"), - QTStr("AutoSafeMode.Text")); + QMessageBox mb(QMessageBox::Warning, QTStr("AutoSafeMode.Title"), QTStr("AutoSafeMode.Text")); QPushButton *launchSafeButton = - mb.addButton(QTStr("AutoSafeMode.LaunchSafe"), - QMessageBox::AcceptRole); + mb.addButton(QTStr("AutoSafeMode.LaunchSafe"), QMessageBox::AcceptRole); QPushButton *launchNormalButton = - mb.addButton(QTStr("AutoSafeMode.LaunchNormal"), - QMessageBox::RejectRole); + mb.addButton(QTStr("AutoSafeMode.LaunchNormal"), QMessageBox::RejectRole); mb.setDefaultButton(launchNormalButton); mb.exec(); safe_mode = mb.clickedButton() == launchSafeButton; if (safe_mode) { - blog(LOG_INFO, - "[Safe Mode] User has launched in Safe Mode."); + blog(LOG_INFO, "[Safe Mode] User has launched in Safe Mode."); } else { - blog(LOG_WARNING, - "[Safe Mode] User elected to launch normally."); + blog(LOG_WARNING, "[Safe Mode] User elected to launch normally."); } } - qInstallMessageHandler([](QtMsgType type, - const QMessageLogContext &, - const QString &message) { + qInstallMessageHandler([](QtMsgType type, const QMessageLogContext &, const QString &message) { switch (type) { #ifdef _DEBUG case QtDebugMsg: @@ -2252,22 +2055,15 @@ static int run_program(fstream &logFile, int argc, char *argv[]) }); #ifdef __APPLE__ - MacPermissionStatus audio_permission = - CheckPermission(kAudioDeviceAccess); - MacPermissionStatus video_permission = - CheckPermission(kVideoDeviceAccess); - MacPermissionStatus accessibility_permission = - CheckPermission(kAccessibility); - MacPermissionStatus screen_permission = - CheckPermission(kScreenCapture); + MacPermissionStatus audio_permission = CheckPermission(kAudioDeviceAccess); + MacPermissionStatus video_permission = CheckPermission(kVideoDeviceAccess); + MacPermissionStatus accessibility_permission = CheckPermission(kAccessibility); + MacPermissionStatus screen_permission = CheckPermission(kScreenCapture); int permissionsDialogLastShown = - config_get_int(App()->GetAppConfig(), "General", - "MacOSPermissionsDialogLastShown"); - if (permissionsDialogLastShown < - MACOS_PERMISSIONS_DIALOG_VERSION) { - OBSPermissions check(nullptr, screen_permission, - video_permission, audio_permission, + config_get_int(App()->GetAppConfig(), "General", "MacOSPermissionsDialogLastShown"); + if (permissionsDialogLastShown < MACOS_PERMISSIONS_DIALOG_VERSION) { + OBSPermissions check(nullptr, screen_permission, video_permission, audio_permission, accessibility_permission); check.exec(); } @@ -2275,13 +2071,10 @@ static int run_program(fstream &logFile, int argc, char *argv[]) #ifdef _WIN32 if (IsRunningOnWine()) { - QMessageBox mb(QMessageBox::Question, - QTStr("Wine.Title"), QTStr("Wine.Text")); + QMessageBox mb(QMessageBox::Question, QTStr("Wine.Title"), QTStr("Wine.Text")); mb.setTextFormat(Qt::RichText); - mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), - QMessageBox::AcceptRole); - QPushButton *closeButton = - mb.addButton(QMessageBox::Close); + mb.addButton(QTStr("AlreadyRunning.LaunchAnyway"), QMessageBox::AcceptRole); + QPushButton *closeButton = mb.addButton(QMessageBox::Close); mb.setDefaultButton(closeButton); mb.exec(); @@ -2296,8 +2089,7 @@ static int run_program(fstream &logFile, int argc, char *argv[]) for (int i = 2; i < argc; ++i) { stor << " " << argv[i]; } - blog(LOG_INFO, "Command Line Arguments: %s", - stor.str().c_str()); + blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str()); } if (!program.OBSInit()) @@ -2333,8 +2125,7 @@ static int run_program(fstream &logFile, int argc, char *argv[]) "Woops, OBS has crashed!\n\nWould you like to copy the crash log " \ "to the clipboard? The crash log will still be saved to:\n\n%s" -static void main_crash_handler(const char *format, va_list args, - void * /* param */) +static void main_crash_handler(const char *format, va_list args, void * /* param */) { char *text = new char[MAX_CRASH_REPORT_SIZE]; @@ -2355,11 +2146,9 @@ static void main_crash_handler(const char *format, va_list args, #ifdef _WIN32 BPtr wpath; os_utf8_to_wcs_ptr(path, 0, &wpath); - file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc | - ios_base::binary); + file.open(wpath, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary); #else - file.open(path, ios_base::in | ios_base::out | ios_base::trunc | - ios_base::binary); + file.open(path, ios_base::in | ios_base::out | ios_base::trunc | ios_base::binary); #endif file << text; file.close(); @@ -2370,21 +2159,17 @@ static void main_crash_handler(const char *format, va_list args, std::replace(pathString.begin(), pathString.end(), '/', '\\'); #endif - string absolutePath = - canonical(filesystem::path(pathString)).u8string(); + string absolutePath = canonical(filesystem::path(pathString)).u8string(); size_t size = snprintf(nullptr, 0, CRASH_MESSAGE, absolutePath.c_str()); unique_ptr message_buffer(new char[size + 1]); - snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE, - absolutePath.c_str()); + snprintf(message_buffer.get(), size + 1, CRASH_MESSAGE, absolutePath.c_str()); - string finalMessage = - string(message_buffer.get(), message_buffer.get() + size); + string finalMessage = string(message_buffer.get(), message_buffer.get() + size); - int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!", - MB_YESNO | MB_ICONERROR | MB_TASKMODAL); + int ret = MessageBoxA(NULL, finalMessage.c_str(), "OBS has crashed!", MB_YESNO | MB_ICONERROR | MB_TASKMODAL); if (ret == IDYES) { size_t len = strlen(text); @@ -2418,8 +2203,7 @@ static void load_debug_privilege(void) tp.Privileges[0].Luid = val; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, - NULL); + AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL); } if (!!LookupPrivilegeValue(NULL, SE_INC_BASE_PRIORITY_NAME, &val)) { @@ -2427,8 +2211,7 @@ static void load_debug_privilege(void) tp.Privileges[0].Luid = val; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, - NULL)) { + if (!AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL)) { blog(LOG_INFO, "Could not set privilege to " "increase GPU priority"); } @@ -2566,11 +2349,9 @@ bool WindowPositionValid(QRect rect) return false; } -static inline bool arg_is(const char *arg, const char *long_form, - const char *short_form) +static inline bool arg_is(const char *arg, const char *long_form, const char *short_form) { - return (long_form && strcmp(arg, long_form) == 0) || - (short_form && strcmp(arg, short_form) == 0); + return (long_form && strcmp(arg, long_form) == 0) || (short_form && strcmp(arg, short_form) == 0); } static void check_safe_mode_sentinel(void) @@ -2643,11 +2424,9 @@ void OBSApp::commitData(QSessionManager &manager) #ifdef _WIN32 static constexpr char vcRunErrorTitle[] = "Outdated Visual C++ Runtime"; -static constexpr char vcRunErrorMsg[] = - "OBS Studio requires a newer version of the Microsoft Visual C++ " - "Redistributables.\n\nYou will now be directed to the download page."; -static constexpr char vcRunInstallerUrl[] = - "https://obsproject.com/visual-studio-2022-runtimes"; +static constexpr char vcRunErrorMsg[] = "OBS Studio requires a newer version of the Microsoft Visual C++ " + "Redistributables.\n\nYou will now be directed to the download page."; +static constexpr char vcRunInstallerUrl[] = "https://obsproject.com/visual-studio-2022-runtimes"; static bool vc_runtime_outdated() { @@ -2658,12 +2437,10 @@ static bool vc_runtime_outdated() if (ver.minor >= 40) return false; - int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle, - MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL); + int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle, MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL); if (choice == IDOK) { /* Open the URL in the default browser. */ - ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL, - SW_SHOWNORMAL); + ShellExecuteA(NULL, "open", vcRunInstallerUrl, NULL, NULL, SW_SHOWNORMAL); } return true; @@ -2710,8 +2487,7 @@ int main(int argc, char *argv[]) const HMODULE hRtwq = LoadLibrary(L"RTWorkQ.dll"); if (hRtwq) { typedef HRESULT(STDAPICALLTYPE * PFN_RtwqStartup)(); - PFN_RtwqStartup func = - (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup"); + PFN_RtwqStartup func = (PFN_RtwqStartup)GetProcAddress(hRtwq, "RtwqStartup"); func(); } #endif @@ -2739,8 +2515,7 @@ int main(int argc, char *argv[]) } else if (arg_is(argv[i], "--only-bundled-plugins", nullptr)) { disable_3p_plugins = true; - } else if (arg_is(argv[i], "--disable-shutdown-check", - nullptr)) { + } else if (arg_is(argv[i], "--disable-shutdown-check", nullptr)) { /* This exists mostly to bypass the dialog during development. */ disable_shutdown_check = true; @@ -2786,8 +2561,7 @@ int main(int argc, char *argv[]) } else if (arg_is(argv[i], "--disable-updater", nullptr)) { opt_disable_updater = true; - } else if (arg_is(argv[i], "--disable-missing-files-check", - nullptr)) { + } else if (arg_is(argv[i], "--disable-missing-files-check", nullptr)) { opt_disable_missing_files_check = true; } else if (arg_is(argv[i], "--steam", nullptr)) { @@ -2820,42 +2594,34 @@ int main(int argc, char *argv[]) "--disable-missing-files-check: Disable the missing files dialog which can appear on startup.\n\n"; #ifdef _WIN32 - MessageBoxA(NULL, help.c_str(), "Help", - MB_OK | MB_ICONASTERISK); + MessageBoxA(NULL, help.c_str(), "Help", MB_OK | MB_ICONASTERISK); #else - std::cout << help - << "--version, -V: Get current version.\n"; + std::cout << help << "--version, -V: Get current version.\n"; #endif exit(0); } else if (arg_is(argv[i], "--version", "-V")) { - std::cout << "OBS Studio - " - << App()->GetVersionString(false) << "\n"; + std::cout << "OBS Studio - " << App()->GetVersionString(false) << "\n"; exit(0); } } #if ALLOW_PORTABLE_MODE if (!portable_mode) { - portable_mode = - os_file_exists(BASE_PATH "/portable_mode") || - os_file_exists(BASE_PATH "/obs_portable_mode") || - os_file_exists(BASE_PATH "/portable_mode.txt") || - os_file_exists(BASE_PATH "/obs_portable_mode.txt"); + portable_mode = os_file_exists(BASE_PATH "/portable_mode") || + os_file_exists(BASE_PATH "/obs_portable_mode") || + os_file_exists(BASE_PATH "/portable_mode.txt") || + os_file_exists(BASE_PATH "/obs_portable_mode.txt"); } if (!opt_disable_updater) { - opt_disable_updater = - os_file_exists(BASE_PATH "/disable_updater") || - os_file_exists(BASE_PATH "/disable_updater.txt"); + opt_disable_updater = os_file_exists(BASE_PATH "/disable_updater") || + os_file_exists(BASE_PATH "/disable_updater.txt"); } if (!opt_disable_missing_files_check) { - opt_disable_missing_files_check = - os_file_exists(BASE_PATH - "/disable_missing_files_check") || - os_file_exists(BASE_PATH - "/disable_missing_files_check.txt"); + opt_disable_missing_files_check = os_file_exists(BASE_PATH "/disable_missing_files_check") || + os_file_exists(BASE_PATH "/disable_missing_files_check.txt"); } #endif @@ -2869,8 +2635,7 @@ int main(int argc, char *argv[]) #ifdef _WIN32 if (hRtwq) { typedef HRESULT(STDAPICALLTYPE * PFN_RtwqShutdown)(); - PFN_RtwqShutdown func = - (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown"); + PFN_RtwqShutdown func = (PFN_RtwqShutdown)GetProcAddress(hRtwq, "RtwqShutdown"); func(); FreeLibrary(hRtwq); } diff --git a/UI/obs-app.hpp b/UI/obs-app.hpp index 308bdaeb9..203eacd39 100644 --- a/UI/obs-app.hpp +++ b/UI/obs-app.hpp @@ -45,15 +45,12 @@ std::string CurrentTimeString(); std::string CurrentDateTimeString(); -std::string GenerateTimeDateFilename(const char *extension, - bool noSpace = false); -std::string GenerateSpecifiedFilename(const char *extension, bool noSpace, - const char *format); -std::string GetFormatString(const char *format, const char *prefix, - const char *suffix); +std::string GenerateTimeDateFilename(const char *extension, bool noSpace = false); +std::string GenerateSpecifiedFilename(const char *extension, bool noSpace, const char *format); +std::string GetFormatString(const char *format, const char *prefix, const char *suffix); std::string GetFormatExt(const char *container); -std::string GetOutputFilename(const char *path, const char *container, - bool noSpace, bool overwrite, const char *format); +std::string GetOutputFilename(const char *path, const char *container, bool noSpace, bool overwrite, + const char *format); QObject *CreateShortcutFilter(); struct BaseLexer { @@ -71,8 +68,7 @@ class OBSTranslator : public QTranslator { public: virtual bool isEmpty() const override { return false; } - virtual QString translate(const char *context, const char *sourceText, - const char *disambiguation, + virtual QString translate(const char *context, const char *sourceText, const char *disambiguation, int n) const override; }; @@ -119,8 +115,7 @@ private: bool MigrateGlobalSettings(); bool MigrateLegacySettings(uint32_t lastVersion); - bool InitUserConfig(std::filesystem::path &userConfigLocation, - uint32_t lastVersion); + bool InitUserConfig(std::filesystem::path &userConfigLocation, uint32_t lastVersion); void InitUserConfigDefaults(); bool InitLocale(); @@ -158,10 +153,7 @@ public: void UpdateHotkeyFocusSetting(bool reset = true); void DisableHotkeys(); - inline bool HotkeysEnabledInFocus() const - { - return enableHotkeysInFocus; - } + inline bool HotkeysEnabledInFocus() const { return enableHotkeysInFocus; } inline QMainWindow *GetMainWindow() const { return mainWindow.data(); } @@ -177,27 +169,18 @@ public: QList GetThemes() const { return themes.values(); } OBSTheme *GetTheme(const QString &name); bool SetTheme(const QString &name); - bool IsThemeDark() const - { - return currentTheme ? currentTheme->isDark : false; - } + bool IsThemeDark() const { return currentTheme ? currentTheme->isDark : false; } void SetBranchData(const std::string &data); std::vector GetBranches(); inline lookup_t *GetTextLookup() const { return textLookup; } - inline const char *GetString(const char *lookupVal) const - { - return textLookup.GetString(lookupVal); - } + inline const char *GetString(const char *lookupVal) const { return textLookup.GetString(lookupVal); } bool TranslateString(const char *lookupVal, const char **out) const; - profiler_name_store_t *GetProfilerNameStore() const - { - return profilerNameStore; - } + profiler_name_store_t *GetProfilerNameStore() const { return profilerNameStore; } const char *GetLastLog() const; const char *GetCurrentLog() const; @@ -232,10 +215,7 @@ public: os_inhibit_sleep_set_active(sleepInhibitor, false); } - inline void PushUITranslation(obs_frontend_translate_ui_cb cb) - { - translatorHooks.emplace_front(cb); - } + inline void PushUITranslation(obs_frontend_translate_ui_cb cb) { translatorHooks.emplace_front(cb); } inline void PopUITranslation() { translatorHooks.pop_front(); } #ifndef _WIN32 diff --git a/UI/obs-frontend-api/obs-frontend-api.cpp b/UI/obs-frontend-api/obs-frontend-api.cpp index 0e74ee376..59caa1696 100644 --- a/UI/obs-frontend-api/obs-frontend-api.cpp +++ b/UI/obs-frontend-api/obs-frontend-api.cpp @@ -13,8 +13,7 @@ void obs_frontend_set_callbacks_internal(obs_frontend_callbacks *callbacks) static inline bool callbacks_valid_(const char *func_name) { if (!c) { - blog(LOG_ERROR, "Tried to call %s with no callbacks!", - func_name); + blog(LOG_ERROR, "Tried to call %s with no callbacks!", func_name); return false; } @@ -59,20 +58,17 @@ static char **convert_string_list(vector &strings) void *obs_frontend_get_main_window(void) { - return !!callbacks_valid() ? c->obs_frontend_get_main_window() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_main_window() : nullptr; } void *obs_frontend_get_main_window_handle(void) { - return !!callbacks_valid() ? c->obs_frontend_get_main_window_handle() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_main_window_handle() : nullptr; } void *obs_frontend_get_system_tray(void) { - return !!callbacks_valid() ? c->obs_frontend_get_system_tray() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_system_tray() : nullptr; } char **obs_frontend_get_scene_names(void) @@ -102,8 +98,7 @@ void obs_frontend_get_scenes(struct obs_frontend_source_list *sources) obs_source_t *obs_frontend_get_current_scene(void) { - return !!callbacks_valid() ? c->obs_frontend_get_current_scene() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_scene() : nullptr; } void obs_frontend_set_current_scene(obs_source_t *scene) @@ -120,8 +115,7 @@ void obs_frontend_get_transitions(struct obs_frontend_source_list *sources) obs_source_t *obs_frontend_get_current_transition(void) { - return !!callbacks_valid() ? c->obs_frontend_get_current_transition() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_transition() : nullptr; } void obs_frontend_set_current_transition(obs_source_t *transition) @@ -132,8 +126,7 @@ void obs_frontend_set_current_transition(obs_source_t *transition) int obs_frontend_get_transition_duration(void) { - return !!callbacks_valid() ? c->obs_frontend_get_transition_duration() - : 0; + return !!callbacks_valid() ? c->obs_frontend_get_transition_duration() : 0; } void obs_frontend_set_transition_duration(int duration) @@ -171,9 +164,7 @@ char **obs_frontend_get_scene_collections(void) char *obs_frontend_get_current_scene_collection(void) { - return !!callbacks_valid() - ? c->obs_frontend_get_current_scene_collection() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_scene_collection() : nullptr; } void obs_frontend_set_current_scene_collection(const char *collection) @@ -184,8 +175,7 @@ void obs_frontend_set_current_scene_collection(const char *collection) bool obs_frontend_add_scene_collection(const char *name) { - return callbacks_valid() ? c->obs_frontend_add_scene_collection(name) - : false; + return callbacks_valid() ? c->obs_frontend_add_scene_collection(name) : false; } char **obs_frontend_get_profiles(void) @@ -200,14 +190,12 @@ char **obs_frontend_get_profiles(void) char *obs_frontend_get_current_profile(void) { - return !!callbacks_valid() ? c->obs_frontend_get_current_profile() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_profile() : nullptr; } char *obs_frontend_get_current_profile_path(void) { - return !!callbacks_valid() ? c->obs_frontend_get_current_profile_path() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_profile_path() : nullptr; } void obs_frontend_set_current_profile(const char *profile) @@ -281,14 +269,12 @@ bool obs_frontend_recording_paused(void) bool obs_frontend_recording_split_file(void) { - return !!callbacks_valid() ? c->obs_frontend_recording_split_file() - : false; + return !!callbacks_valid() ? c->obs_frontend_recording_split_file() : false; } bool obs_frontend_recording_add_chapter(const char *name) { - return !!callbacks_valid() ? c->obs_frontend_recording_add_chapter(name) - : false; + return !!callbacks_valid() ? c->obs_frontend_recording_add_chapter(name) : false; } void obs_frontend_replay_buffer_start(void) @@ -311,24 +297,18 @@ void obs_frontend_replay_buffer_stop(void) bool obs_frontend_replay_buffer_active(void) { - return !!callbacks_valid() ? c->obs_frontend_replay_buffer_active() - : false; + return !!callbacks_valid() ? c->obs_frontend_replay_buffer_active() : false; } void *obs_frontend_add_tools_menu_qaction(const char *name) { - return !!callbacks_valid() - ? c->obs_frontend_add_tools_menu_qaction(name) - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_add_tools_menu_qaction(name) : nullptr; } -void obs_frontend_add_tools_menu_item(const char *name, - obs_frontend_cb callback, - void *private_data) +void obs_frontend_add_tools_menu_item(const char *name, obs_frontend_cb callback, void *private_data) { if (callbacks_valid()) - c->obs_frontend_add_tools_menu_item(name, callback, - private_data); + c->obs_frontend_add_tools_menu_item(name, callback, private_data); } void *obs_frontend_add_dock(void *dock) @@ -336,12 +316,9 @@ void *obs_frontend_add_dock(void *dock) return !!callbacks_valid() ? c->obs_frontend_add_dock(dock) : nullptr; } -bool obs_frontend_add_dock_by_id(const char *id, const char *title, - void *widget) +bool obs_frontend_add_dock_by_id(const char *id, const char *title, void *widget) { - return !!callbacks_valid() - ? c->obs_frontend_add_dock_by_id(id, title, widget) - : false; + return !!callbacks_valid() ? c->obs_frontend_add_dock_by_id(id, title, widget) : false; } void obs_frontend_remove_dock(const char *id) @@ -352,19 +329,16 @@ void obs_frontend_remove_dock(const char *id) bool obs_frontend_add_custom_qdock(const char *id, void *dock) { - return !!callbacks_valid() ? c->obs_frontend_add_custom_qdock(id, dock) - : false; + return !!callbacks_valid() ? c->obs_frontend_add_custom_qdock(id, dock) : false; } -void obs_frontend_add_event_callback(obs_frontend_event_cb callback, - void *private_data) +void obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data) { if (callbacks_valid()) c->obs_frontend_add_event_callback(callback, private_data); } -void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, - void *private_data) +void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, void *private_data) { if (callbacks_valid()) c->obs_frontend_remove_event_callback(callback, private_data); @@ -372,26 +346,22 @@ void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, obs_output_t *obs_frontend_get_streaming_output(void) { - return !!callbacks_valid() ? c->obs_frontend_get_streaming_output() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_streaming_output() : nullptr; } obs_output_t *obs_frontend_get_recording_output(void) { - return !!callbacks_valid() ? c->obs_frontend_get_recording_output() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_recording_output() : nullptr; } obs_output_t *obs_frontend_get_replay_buffer_output(void) { - return !!callbacks_valid() ? c->obs_frontend_get_replay_buffer_output() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_replay_buffer_output() : nullptr; } config_t *obs_frontend_get_profile_config(void) { - return !!callbacks_valid() ? c->obs_frontend_get_profile_config() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_profile_config() : nullptr; } config_t *obs_frontend_get_app_config(void) @@ -401,8 +371,7 @@ config_t *obs_frontend_get_app_config(void) config_t *obs_frontend_get_user_config(void) { - return !!callbacks_valid() ? c->obs_frontend_get_user_config() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_user_config() : nullptr; } config_t *obs_frontend_get_global_config(void) @@ -412,8 +381,7 @@ config_t *obs_frontend_get_global_config(void) return !!callbacks_valid() ? c->obs_frontend_get_app_config() : nullptr; } -void obs_frontend_open_projector(const char *type, int monitor, - const char *geometry, const char *name) +void obs_frontend_open_projector(const char *type, int monitor, const char *geometry, const char *name) { if (callbacks_valid()) c->obs_frontend_open_projector(type, monitor, geometry, name); @@ -437,29 +405,25 @@ void obs_frontend_defer_save_end(void) c->obs_frontend_defer_save_end(); } -void obs_frontend_add_save_callback(obs_frontend_save_cb callback, - void *private_data) +void obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data) { if (callbacks_valid()) c->obs_frontend_add_save_callback(callback, private_data); } -void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, - void *private_data) +void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, void *private_data) { if (callbacks_valid()) c->obs_frontend_remove_save_callback(callback, private_data); } -void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, - void *private_data) +void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, void *private_data) { if (callbacks_valid()) c->obs_frontend_add_preload_callback(callback, private_data); } -void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, - void *private_data) +void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, void *private_data) { if (callbacks_valid()) c->obs_frontend_remove_preload_callback(callback, private_data); @@ -479,8 +443,7 @@ void obs_frontend_pop_ui_translation(void) obs_service_t *obs_frontend_get_streaming_service(void) { - return !!callbacks_valid() ? c->obs_frontend_get_streaming_service() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_streaming_service() : nullptr; } void obs_frontend_set_streaming_service(obs_service_t *service) @@ -497,9 +460,7 @@ void obs_frontend_save_streaming_service(void) bool obs_frontend_preview_program_mode_active(void) { - return !!callbacks_valid() - ? c->obs_frontend_preview_program_mode_active() - : false; + return !!callbacks_valid() ? c->obs_frontend_preview_program_mode_active() : false; } void obs_frontend_set_preview_program_mode(bool enable) @@ -527,8 +488,7 @@ void obs_frontend_set_preview_enabled(bool enable) obs_source_t *obs_frontend_get_current_preview_scene(void) { - return !!callbacks_valid() ? c->obs_frontend_get_current_preview_scene() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_preview_scene() : nullptr; } void obs_frontend_set_current_preview_scene(obs_source_t *scene) @@ -551,8 +511,7 @@ void obs_frontend_take_source_screenshot(obs_source_t *source) obs_output_t *obs_frontend_get_virtualcam_output(void) { - return !!callbacks_valid() ? c->obs_frontend_get_virtualcam_output() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_virtualcam_output() : nullptr; } void obs_frontend_start_virtualcam(void) @@ -569,8 +528,7 @@ void obs_frontend_stop_virtualcam(void) bool obs_frontend_virtualcam_active(void) { - return !!callbacks_valid() ? c->obs_frontend_virtualcam_active() - : false; + return !!callbacks_valid() ? c->obs_frontend_virtualcam_active() : false; } void obs_frontend_reset_video(void) @@ -605,15 +563,12 @@ void obs_frontend_open_sceneitem_edit_transform(obs_sceneitem_t *item) char *obs_frontend_get_current_record_output_path(void) { - return !!callbacks_valid() - ? c->obs_frontend_get_current_record_output_path() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_current_record_output_path() : nullptr; } const char *obs_frontend_get_locale_string(const char *string) { - return !!callbacks_valid() ? c->obs_frontend_get_locale_string(string) - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_locale_string(string) : nullptr; } bool obs_frontend_is_theme_dark(void) @@ -623,29 +578,22 @@ bool obs_frontend_is_theme_dark(void) char *obs_frontend_get_last_recording(void) { - return !!callbacks_valid() ? c->obs_frontend_get_last_recording() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_last_recording() : nullptr; } char *obs_frontend_get_last_screenshot(void) { - return !!callbacks_valid() ? c->obs_frontend_get_last_screenshot() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_last_screenshot() : nullptr; } char *obs_frontend_get_last_replay(void) { - return !!callbacks_valid() ? c->obs_frontend_get_last_replay() - : nullptr; + return !!callbacks_valid() ? c->obs_frontend_get_last_replay() : nullptr; } -void obs_frontend_add_undo_redo_action(const char *name, - const undo_redo_cb undo, - const undo_redo_cb redo, - const char *undo_data, - const char *redo_data, bool repeatable) +void obs_frontend_add_undo_redo_action(const char *name, const undo_redo_cb undo, const undo_redo_cb redo, + const char *undo_data, const char *redo_data, bool repeatable) { if (callbacks_valid()) - c->obs_frontend_add_undo_redo_action( - name, undo, redo, undo_data, redo_data, repeatable); + c->obs_frontend_add_undo_redo_action(name, undo, redo, undo_data, redo_data, repeatable); } diff --git a/UI/obs-frontend-api/obs-frontend-api.h b/UI/obs-frontend-api/obs-frontend-api.h index 1282b2819..4b409e337 100644 --- a/UI/obs-frontend-api/obs-frontend-api.h +++ b/UI/obs-frontend-api/obs-frontend-api.h @@ -72,8 +72,7 @@ struct obs_frontend_source_list { DARRAY(obs_source_t *) sources; }; -static inline void -obs_frontend_source_list_free(struct obs_frontend_source_list *source_list) +static inline void obs_frontend_source_list_free(struct obs_frontend_source_list *source_list) { size_t num = source_list->sources.num; for (size_t i = 0; i < num; i++) @@ -107,8 +106,7 @@ EXPORT void obs_frontend_get_scenes(struct obs_frontend_source_list *sources); EXPORT obs_source_t *obs_frontend_get_current_scene(void); EXPORT void obs_frontend_set_current_scene(obs_source_t *scene); -EXPORT void -obs_frontend_get_transitions(struct obs_frontend_source_list *sources); +EXPORT void obs_frontend_get_transitions(struct obs_frontend_source_list *sources); EXPORT obs_source_t *obs_frontend_get_current_transition(void); EXPORT void obs_frontend_set_current_transition(obs_source_t *transition); EXPORT int obs_frontend_get_transition_duration(void); @@ -133,49 +131,36 @@ EXPORT void obs_frontend_delete_profile(const char *profile); typedef void (*obs_frontend_cb)(void *private_data); EXPORT void *obs_frontend_add_tools_menu_qaction(const char *name); -EXPORT void obs_frontend_add_tools_menu_item(const char *name, - obs_frontend_cb callback, - void *private_data); +EXPORT void obs_frontend_add_tools_menu_item(const char *name, obs_frontend_cb callback, void *private_data); /* takes QDockWidget and returns QAction */ OBS_DEPRECATED EXPORT void *obs_frontend_add_dock(void *dock); /* takes QWidget for widget */ -EXPORT bool obs_frontend_add_dock_by_id(const char *id, const char *title, - void *widget); +EXPORT bool obs_frontend_add_dock_by_id(const char *id, const char *title, void *widget); EXPORT void obs_frontend_remove_dock(const char *id); /* takes QDockWidget for dock */ EXPORT bool obs_frontend_add_custom_qdock(const char *id, void *dock); -typedef void (*obs_frontend_event_cb)(enum obs_frontend_event event, - void *private_data); +typedef void (*obs_frontend_event_cb)(enum obs_frontend_event event, void *private_data); -EXPORT void obs_frontend_add_event_callback(obs_frontend_event_cb callback, - void *private_data); -EXPORT void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, - void *private_data); +EXPORT void obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data); +EXPORT void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, void *private_data); -typedef void (*obs_frontend_save_cb)(obs_data_t *save_data, bool saving, - void *private_data); +typedef void (*obs_frontend_save_cb)(obs_data_t *save_data, bool saving, void *private_data); -EXPORT void obs_frontend_add_save_callback(obs_frontend_save_cb callback, - void *private_data); -EXPORT void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, - void *private_data); +EXPORT void obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data); +EXPORT void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, void *private_data); -EXPORT void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, - void *private_data); -EXPORT void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, - void *private_data); +EXPORT void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, void *private_data); +EXPORT void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, void *private_data); -typedef bool (*obs_frontend_translate_ui_cb)(const char *text, - const char **out); +typedef bool (*obs_frontend_translate_ui_cb)(const char *text, const char **out); -EXPORT void -obs_frontend_push_ui_translation(obs_frontend_translate_ui_cb translate); +EXPORT void obs_frontend_push_ui_translation(obs_frontend_translate_ui_cb translate); EXPORT void obs_frontend_pop_ui_translation(void); #endif //!SWIG @@ -197,8 +182,7 @@ EXPORT void obs_frontend_replay_buffer_save(void); EXPORT void obs_frontend_replay_buffer_stop(void); EXPORT bool obs_frontend_replay_buffer_active(void); -EXPORT void obs_frontend_open_projector(const char *type, int monitor, - const char *geometry, const char *name); +EXPORT void obs_frontend_open_projector(const char *type, int monitor, const char *geometry, const char *name); EXPORT void obs_frontend_save(void); EXPORT void obs_frontend_defer_save_begin(void); EXPORT void obs_frontend_defer_save_end(void); @@ -251,9 +235,8 @@ EXPORT char *obs_frontend_get_last_screenshot(void); EXPORT char *obs_frontend_get_last_replay(void); typedef void (*undo_redo_cb)(const char *data); -EXPORT void obs_frontend_add_undo_redo_action( - const char *name, const undo_redo_cb undo, const undo_redo_cb redo, - const char *undo_data, const char *redo_data, bool repeatable); +EXPORT void obs_frontend_add_undo_redo_action(const char *name, const undo_redo_cb undo, const undo_redo_cb redo, + const char *undo_data, const char *redo_data, bool repeatable); /* ------------------------------------------------------------------------- */ diff --git a/UI/obs-frontend-api/obs-frontend-internal.hpp b/UI/obs-frontend-api/obs-frontend-internal.hpp index d5f1cf46d..5beca9af6 100644 --- a/UI/obs-frontend-api/obs-frontend-internal.hpp +++ b/UI/obs-frontend-api/obs-frontend-internal.hpp @@ -11,31 +11,25 @@ struct obs_frontend_callbacks { virtual void *obs_frontend_get_main_window_handle(void) = 0; virtual void *obs_frontend_get_system_tray(void) = 0; - virtual void - obs_frontend_get_scenes(struct obs_frontend_source_list *sources) = 0; + virtual void obs_frontend_get_scenes(struct obs_frontend_source_list *sources) = 0; virtual obs_source_t *obs_frontend_get_current_scene(void) = 0; virtual void obs_frontend_set_current_scene(obs_source_t *scene) = 0; - virtual void obs_frontend_get_transitions( - struct obs_frontend_source_list *sources) = 0; + virtual void obs_frontend_get_transitions(struct obs_frontend_source_list *sources) = 0; virtual obs_source_t *obs_frontend_get_current_transition(void) = 0; - virtual void - obs_frontend_set_current_transition(obs_source_t *transition) = 0; + virtual void obs_frontend_set_current_transition(obs_source_t *transition) = 0; virtual int obs_frontend_get_transition_duration(void) = 0; virtual void obs_frontend_set_transition_duration(int duration) = 0; virtual void obs_frontend_release_tbar(void) = 0; virtual int obs_frontend_get_tbar_position(void) = 0; virtual void obs_frontend_set_tbar_position(int position) = 0; - virtual void obs_frontend_get_scene_collections( - std::vector &strings) = 0; + virtual void obs_frontend_get_scene_collections(std::vector &strings) = 0; virtual char *obs_frontend_get_current_scene_collection(void) = 0; - virtual void - obs_frontend_set_current_scene_collection(const char *collection) = 0; + virtual void obs_frontend_set_current_scene_collection(const char *collection) = 0; virtual bool obs_frontend_add_scene_collection(const char *name) = 0; - virtual void - obs_frontend_get_profiles(std::vector &strings) = 0; + virtual void obs_frontend_get_profiles(std::vector &strings) = 0; virtual char *obs_frontend_get_current_profile(void) = 0; virtual char *obs_frontend_get_current_profile_path(void) = 0; virtual void obs_frontend_set_current_profile(const char *profile) = 0; @@ -61,64 +55,44 @@ struct obs_frontend_callbacks { virtual bool obs_frontend_replay_buffer_active(void) = 0; virtual void *obs_frontend_add_tools_menu_qaction(const char *name) = 0; - virtual void obs_frontend_add_tools_menu_item(const char *name, - obs_frontend_cb callback, + virtual void obs_frontend_add_tools_menu_item(const char *name, obs_frontend_cb callback, void *private_data) = 0; virtual void *obs_frontend_add_dock(void *dock) = 0; - virtual bool obs_frontend_add_dock_by_id(const char *id, - const char *title, - void *widget) = 0; + virtual bool obs_frontend_add_dock_by_id(const char *id, const char *title, void *widget) = 0; virtual void obs_frontend_remove_dock(const char *id) = 0; - virtual bool obs_frontend_add_custom_qdock(const char *id, - void *dock) = 0; + virtual bool obs_frontend_add_custom_qdock(const char *id, void *dock) = 0; - virtual void - obs_frontend_add_event_callback(obs_frontend_event_cb callback, - void *private_data) = 0; - virtual void - obs_frontend_remove_event_callback(obs_frontend_event_cb callback, - void *private_data) = 0; + virtual void obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data) = 0; + virtual void obs_frontend_remove_event_callback(obs_frontend_event_cb callback, void *private_data) = 0; virtual obs_output_t *obs_frontend_get_streaming_output(void) = 0; virtual obs_output_t *obs_frontend_get_recording_output(void) = 0; virtual obs_output_t *obs_frontend_get_replay_buffer_output(void) = 0; virtual config_t *obs_frontend_get_profile_config(void) = 0; - OBS_DEPRECATED virtual config_t * - obs_frontend_get_global_config(void) = 0; + OBS_DEPRECATED virtual config_t *obs_frontend_get_global_config(void) = 0; virtual config_t *obs_frontend_get_app_config(void) = 0; virtual config_t *obs_frontend_get_user_config(void) = 0; - virtual void obs_frontend_open_projector(const char *type, int monitor, - const char *geometry, + virtual void obs_frontend_open_projector(const char *type, int monitor, const char *geometry, const char *name) = 0; virtual void obs_frontend_save(void) = 0; virtual void obs_frontend_defer_save_begin(void) = 0; virtual void obs_frontend_defer_save_end(void) = 0; - virtual void - obs_frontend_add_save_callback(obs_frontend_save_cb callback, - void *private_data) = 0; - virtual void - obs_frontend_remove_save_callback(obs_frontend_save_cb callback, - void *private_data) = 0; + virtual void obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data) = 0; + virtual void obs_frontend_remove_save_callback(obs_frontend_save_cb callback, void *private_data) = 0; - virtual void - obs_frontend_add_preload_callback(obs_frontend_save_cb callback, - void *private_data) = 0; - virtual void - obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, - void *private_data) = 0; + virtual void obs_frontend_add_preload_callback(obs_frontend_save_cb callback, void *private_data) = 0; + virtual void obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, void *private_data) = 0; - virtual void obs_frontend_push_ui_translation( - obs_frontend_translate_ui_cb translate) = 0; + virtual void obs_frontend_push_ui_translation(obs_frontend_translate_ui_cb translate) = 0; virtual void obs_frontend_pop_ui_translation(void) = 0; virtual obs_service_t *obs_frontend_get_streaming_service(void) = 0; - virtual void - obs_frontend_set_streaming_service(obs_service_t *service) = 0; + virtual void obs_frontend_set_streaming_service(obs_service_t *service) = 0; virtual void obs_frontend_save_streaming_service() = 0; virtual bool obs_frontend_preview_program_mode_active(void) = 0; @@ -129,8 +103,7 @@ struct obs_frontend_callbacks { virtual void obs_frontend_set_preview_enabled(bool enable) = 0; virtual obs_source_t *obs_frontend_get_current_preview_scene(void) = 0; - virtual void - obs_frontend_set_current_preview_scene(obs_source_t *scene) = 0; + virtual void obs_frontend_set_current_preview_scene(obs_source_t *scene) = 0; virtual void on_load(obs_data_t *settings) = 0; virtual void on_preload(obs_data_t *settings) = 0; @@ -138,8 +111,7 @@ struct obs_frontend_callbacks { virtual void on_event(enum obs_frontend_event event) = 0; virtual void obs_frontend_take_screenshot() = 0; - virtual void - obs_frontend_take_source_screenshot(obs_source_t *source) = 0; + virtual void obs_frontend_take_source_screenshot(obs_source_t *source) = 0; virtual obs_output_t *obs_frontend_get_virtualcam_output(void) = 0; virtual void obs_frontend_start_virtualcam(void) = 0; @@ -148,17 +120,13 @@ struct obs_frontend_callbacks { virtual void obs_frontend_reset_video(void) = 0; - virtual void - obs_frontend_open_source_properties(obs_source_t *source) = 0; + virtual void obs_frontend_open_source_properties(obs_source_t *source) = 0; virtual void obs_frontend_open_source_filters(obs_source_t *source) = 0; - virtual void - obs_frontend_open_source_interaction(obs_source_t *source) = 0; - virtual void - obs_frontend_open_sceneitem_edit_transform(obs_sceneitem_t *item) = 0; + virtual void obs_frontend_open_source_interaction(obs_source_t *source) = 0; + virtual void obs_frontend_open_sceneitem_edit_transform(obs_sceneitem_t *item) = 0; virtual char *obs_frontend_get_current_record_output_path(void) = 0; - virtual const char * - obs_frontend_get_locale_string(const char *string) = 0; + virtual const char *obs_frontend_get_locale_string(const char *string) = 0; virtual bool obs_frontend_is_theme_dark(void) = 0; @@ -166,13 +134,9 @@ struct obs_frontend_callbacks { virtual char *obs_frontend_get_last_screenshot(void) = 0; virtual char *obs_frontend_get_last_replay(void) = 0; - virtual void obs_frontend_add_undo_redo_action(const char *name, - const undo_redo_cb undo, - const undo_redo_cb redo, - const char *undo_data, - const char *redo_data, - bool repeatable) = 0; + virtual void obs_frontend_add_undo_redo_action(const char *name, const undo_redo_cb undo, + const undo_redo_cb redo, const char *undo_data, + const char *redo_data, bool repeatable) = 0; }; -EXPORT void -obs_frontend_set_callbacks_internal(obs_frontend_callbacks *callbacks); +EXPORT void obs_frontend_set_callbacks_internal(obs_frontend_callbacks *callbacks); diff --git a/UI/obs-proxy-style.cpp b/UI/obs-proxy-style.cpp index 49be6524e..4daf7f47a 100644 --- a/UI/obs-proxy-style.cpp +++ b/UI/obs-proxy-style.cpp @@ -12,20 +12,16 @@ static inline uint qt_intensity(uint r, uint g, uint b) * * https://code.woboq.org/qt5/qtbase/src/widgets/styles/qcommonstyle.cpp.html#6429 */ -QPixmap -OBSContextBarProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, - const QPixmap &pixmap, - const QStyleOption *option) const +QPixmap OBSContextBarProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap &pixmap, + const QStyleOption *option) const { if (iconMode == QIcon::Disabled) { - QImage im = - pixmap.toImage().convertToFormat(QImage::Format_ARGB32); + QImage im = pixmap.toImage().convertToFormat(QImage::Format_ARGB32); /* Create a colortable based on the background * (black -> bg -> white) */ - QColor bg = option->palette.color(QPalette::Disabled, - QPalette::Window); + QColor bg = option->palette.color(QPalette::Disabled, QPalette::Window); int red = bg.red(); int green = bg.green(); int blue = bg.blue(); @@ -49,8 +45,7 @@ OBSContextBarProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, int intensity = qt_intensity(red, green, blue); const int factor = 191; - if ((red - factor > green && red - factor > blue) || - (green - factor > red && green - factor > blue) || + if ((red - factor > green && red - factor > blue) || (green - factor > red && green - factor > blue) || (blue - factor > red && blue - factor > green)) qMin(255, intensity + 20); else if (intensity <= 128) @@ -63,10 +58,8 @@ OBSContextBarProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, /* Calculate color table index, taking * intensity adjustment and a magic offset into * account. */ - uint ci = uint(qGray(pixel) / 3 + - (130 - intensity / 3)); - *scanLine = qRgba(reds[ci], greens[ci], - blues[ci], qAlpha(pixel)); + uint ci = uint(qGray(pixel) / 3 + (130 - intensity / 3)); + *scanLine = qRgba(reds[ci], greens[ci], blues[ci], qAlpha(pixel)); ++scanLine; } } @@ -77,8 +70,7 @@ OBSContextBarProxyStyle::generatedIconPixmap(QIcon::Mode iconMode, return QProxyStyle::generatedIconPixmap(iconMode, pixmap, option); } -int OBSProxyStyle::styleHint(StyleHint hint, const QStyleOption *option, - const QWidget *widget, +int OBSProxyStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const { if (hint == SH_ComboBox_AllowWheelScrolling) diff --git a/UI/obs-proxy-style.hpp b/UI/obs-proxy-style.hpp index 325b2abd4..5160f35a7 100644 --- a/UI/obs-proxy-style.hpp +++ b/UI/obs-proxy-style.hpp @@ -8,8 +8,7 @@ public: OBSProxyStyle(const QString &key) : QProxyStyle(key) {} - int styleHint(StyleHint hint, const QStyleOption *option, - const QWidget *widget, + int styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const override; }; diff --git a/UI/platform-windows.cpp b/UI/platform-windows.cpp index 457d0402e..d5d76ccc4 100644 --- a/UI/platform-windows.cpp +++ b/UI/platform-windows.cpp @@ -39,8 +39,7 @@ using namespace std; -static inline bool check_path(const char *data, const char *path, - string &output) +static inline bool check_path(const char *data, const char *path, string &output) { ostringstream str; str << path << data; @@ -64,8 +63,7 @@ string GetDefaultVideoSavePath() wchar_t path_utf16[MAX_PATH]; char path_utf8[MAX_PATH] = {}; - SHGetFolderPathW(NULL, CSIDL_MYVIDEO, NULL, SHGFP_TYPE_CURRENT, - path_utf16); + SHGetFolderPathW(NULL, CSIDL_MYVIDEO, NULL, SHGFP_TYPE_CURRENT, path_utf16); os_wcs_to_utf8(path_utf16, wcslen(path_utf16), path_utf8, MAX_PATH); return string(path_utf8); @@ -76,13 +74,11 @@ static vector GetUserPreferredLocales() vector result; ULONG num, length = 0; - if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num, nullptr, - &length)) + if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num, nullptr, &length)) return result; vector buffer(length); - if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num, - &buffer.front(), &length)) + if (!GetUserPreferredUILanguages(MUI_LANGUAGE_NAME, &num, &buffer.front(), &length)) return result; result.reserve(num); @@ -192,13 +188,11 @@ void SetProcessPriority(const char *priority) if (strcmp(priority, "High") == 0) SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); else if (strcmp(priority, "AboveNormal") == 0) - SetPriorityClass(GetCurrentProcess(), - ABOVE_NORMAL_PRIORITY_CLASS); + SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); else if (strcmp(priority, "Normal") == 0) SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS); else if (strcmp(priority, "BelowNormal") == 0) - SetPriorityClass(GetCurrentProcess(), - BELOW_NORMAL_PRIORITY_CLASS); + SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); else if (strcmp(priority, "Idle") == 0) SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS); } @@ -220,8 +214,7 @@ bool SetDisplayAffinitySupported(void) older Windows builds behaves like WDA_MONITOR (black box) */ if (!checked) { - if (GetWindowsVersion() > 0x0A00 || - GetWindowsVersion() == 0x0A00 && GetWindowsBuild() >= 19041) + if (GetWindowsVersion() > 0x0A00 || GetWindowsVersion() == 0x0A00 && GetWindowsBuild() >= 19041) supported = true; else supported = false; @@ -240,10 +233,8 @@ bool DisableAudioDucking(bool disable) ComPtr sessionControl; ComPtr sessionControl2; - HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, - CLSCTX_INPROC_SERVER, - __uuidof(IMMDeviceEnumerator), - (void **)&devEmum); + HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, + __uuidof(IMMDeviceEnumerator), (void **)&devEmum); if (FAILED(result)) return false; @@ -251,14 +242,12 @@ bool DisableAudioDucking(bool disable) if (FAILED(result)) return false; - result = device->Activate(__uuidof(IAudioSessionManager2), - CLSCTX_INPROC_SERVER, nullptr, + result = device->Activate(__uuidof(IAudioSessionManager2), CLSCTX_INPROC_SERVER, nullptr, (void **)&sessionManager2); if (FAILED(result)) return false; - result = sessionManager2->GetAudioSessionControl(nullptr, 0, - &sessionControl); + result = sessionManager2->GetAudioSessionControl(nullptr, 0, &sessionControl); if (FAILED(result)) return false; @@ -341,8 +330,7 @@ struct MonitorData { bool found; }; -static BOOL CALLBACK GetMonitorCallback(HMONITOR monitor, HDC, LPRECT, - LPARAM param) +static BOOL CALLBACK GetMonitorCallback(HMONITOR monitor, HDC, LPRECT, LPARAM param) { MonitorData *data = (MonitorData *)param; @@ -385,9 +373,7 @@ void TaskbarOverlayInit() void TaskbarOverlaySetStatus(TaskbarOverlayStatus status) { ITaskbarList4 *taskbarIcon; - auto hr = CoCreateInstance(CLSID_TaskbarList, NULL, - CLSCTX_INPROC_SERVER, - IID_PPV_ARGS(&taskbarIcon)); + auto hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbarIcon)); if (FAILED(hr)) { taskbarIcon->Release(); @@ -404,12 +390,10 @@ void TaskbarOverlaySetStatus(TaskbarOverlayStatus status) QIcon qicon; switch (status) { case TaskbarOverlayStatusActive: - qicon = QIcon::fromTheme("obs-active", - QIcon(":/res/images/active.png")); + qicon = QIcon::fromTheme("obs-active", QIcon(":/res/images/active.png")); break; case TaskbarOverlayStatusPaused: - qicon = QIcon::fromTheme("obs-paused", - QIcon(":/res/images/paused.png")); + qicon = QIcon::fromTheme("obs-paused", QIcon(":/res/images/paused.png")); break; case TaskbarOverlayStatusInactive: taskbarIcon->SetOverlayIcon(hwnd, nullptr, nullptr); @@ -420,8 +404,7 @@ void TaskbarOverlaySetStatus(TaskbarOverlayStatus status) HICON hicon = nullptr; if (!qicon.isNull()) { Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &p); - hicon = qt_pixmapToWinHICON( - qicon.pixmap(GetSystemMetrics(SM_CXSMICON))); + hicon = qt_pixmapToWinHICON(qicon.pixmap(GetSystemMetrics(SM_CXSMICON))); if (!hicon) return; } diff --git a/UI/platform-x11.cpp b/UI/platform-x11.cpp index 7de1008e4..5520e019b 100644 --- a/UI/platform-x11.cpp +++ b/UI/platform-x11.cpp @@ -61,8 +61,7 @@ void CheckIfAlreadyRunning(bool &already_running) int uniq = socket(AF_LOCAL, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (uniq == -1) { - blog(LOG_ERROR, - "Failed to check for running instance, socket: %d", errno); + blog(LOG_ERROR, "Failed to check for running instance, socket: %d", errno); already_running = 0; return; } @@ -70,13 +69,10 @@ void CheckIfAlreadyRunning(bool &already_running) struct sockaddr_un bindInfo; memset(&bindInfo, 0, sizeof(sockaddr_un)); bindInfo.sun_family = AF_LOCAL; - auto bindInfoStrlen = snprintf(bindInfo.sun_path + 1, - sizeof(bindInfo.sun_path) - 1, - "%s %d %s", "/com/obsproject", getpid(), - App()->GetVersionString().c_str()); + auto bindInfoStrlen = snprintf(bindInfo.sun_path + 1, sizeof(bindInfo.sun_path) - 1, "%s %d %s", + "/com/obsproject", getpid(), App()->GetVersionString().c_str()); - int bindErr = bind(uniq, (struct sockaddr *)&bindInfo, - sizeof(sa_family_t) + 1 + bindInfoStrlen); + int bindErr = bind(uniq, (struct sockaddr *)&bindInfo, sizeof(sa_family_t) + 1 + bindInfoStrlen); already_running = bindErr == 0 ? 0 : 1; if (already_running) { @@ -139,8 +135,7 @@ const char *RunOnce::thr_name = "OBS runonce"; void CheckIfAlreadyRunning(bool &already_running) { - std::string tmpfile_name = - "/tmp/obs-studio.lock." + std::to_string(geteuid()); + std::string tmpfile_name = "/tmp/obs-studio.lock." + std::to_string(geteuid()); int fd = open(tmpfile_name.c_str(), O_RDWR | O_CREAT | O_EXLOCK, 0600); if (fd == -1) { already_running = true; @@ -151,11 +146,9 @@ void CheckIfAlreadyRunning(bool &already_running) procstat *ps = procstat_open_sysctl(); unsigned int count; - auto procs = procstat_getprocs(ps, KERN_PROC_UID | KERN_PROC_INC_THREAD, - geteuid(), &count); + auto procs = procstat_getprocs(ps, KERN_PROC_UID | KERN_PROC_INC_THREAD, geteuid(), &count); for (unsigned int i = 0; i < count; i++) { - if (!strncmp(procs[i].ki_tdname, RunOnce::thr_name, - sizeof(procs[i].ki_tdname))) { + if (!strncmp(procs[i].ki_tdname, RunOnce::thr_name, sizeof(procs[i].ki_tdname))) { already_running = true; break; } @@ -175,8 +168,7 @@ void CheckIfAlreadyRunning(bool &already_running) } #endif -static inline bool check_path(const char *data, const char *path, - string &output) +static inline bool check_path(const char *data, const char *path, string &output) { ostringstream str; str << path << data; @@ -197,8 +189,7 @@ bool GetDataFilePath(const char *data, string &output) return true; } - char *relative_data_path = - os_get_executable_path_ptr("../" OBS_DATA_PATH "/obs-studio/"); + char *relative_data_path = os_get_executable_path_ptr("../" OBS_DATA_PATH "/obs-studio/"); if (relative_data_path) { bool result = check_path(data, relative_data_path, output); @@ -276,18 +267,16 @@ void TaskbarOverlaySetStatus(TaskbarOverlayStatus) {} bool HighContrastEnabled() { QDBusReply reply; - QDBusMessage msgXdpSettingsVersion = QDBusMessage::createMethodCall( - "org.freedesktop.portal.Desktop", - "/org/freedesktop/portal/desktop", - "org.freedesktop.DBus.Properties", "Get"); + QDBusMessage msgXdpSettingsVersion = QDBusMessage::createMethodCall("org.freedesktop.portal.Desktop", + "/org/freedesktop/portal/desktop", + "org.freedesktop.DBus.Properties", "Get"); msgXdpSettingsVersion << "org.freedesktop.portal.Settings" << "version"; reply = QDBusConnection::sessionBus().call(msgXdpSettingsVersion); if (!reply.isValid()) { - blog(LOG_WARNING, - "Get on org.freedesktop.portal.Settings returned an invalid reply"); + blog(LOG_WARNING, "Get on org.freedesktop.portal.Settings returned an invalid reply"); return false; } @@ -295,17 +284,14 @@ bool HighContrastEnabled() * the ReadOne method. So assumes that if ReadOne is not available, contrast * isn't available either. */ if (uint32_t version = reply.value().toUInt() < 2) { - blog(LOG_WARNING, - "org.freedesktop.portal.Settings version %u does not support ReadOne", - version); + blog(LOG_WARNING, "org.freedesktop.portal.Settings version %u does not support ReadOne", version); return false; } /* NOTE: If contrast is not available if will return 0 (false). */ - QDBusMessage msgXdpSettingsContrast = QDBusMessage::createMethodCall( - "org.freedesktop.portal.Desktop", - "/org/freedesktop/portal/desktop", - "org.freedesktop.portal.Settings", "ReadOne"); + QDBusMessage msgXdpSettingsContrast = + QDBusMessage::createMethodCall("org.freedesktop.portal.Desktop", "/org/freedesktop/portal/desktop", + "org.freedesktop.portal.Settings", "ReadOne"); msgXdpSettingsContrast << "org.freedesktop.appearance" << "contrast"; @@ -313,8 +299,7 @@ bool HighContrastEnabled() reply = QDBusConnection::sessionBus().call(msgXdpSettingsContrast); if (!reply.isValid()) { - blog(LOG_WARNING, - "ReadOne on org.freedesktop.portal.Settings returned an invalid reply"); + blog(LOG_WARNING, "ReadOne on org.freedesktop.portal.Settings returned an invalid reply"); return false; } diff --git a/UI/platform.hpp b/UI/platform.hpp index ecea323c8..e05bc66eb 100644 --- a/UI/platform.hpp +++ b/UI/platform.hpp @@ -102,8 +102,7 @@ void InstallNSThreadLocks(); void disableColorSpaceConversion(QWidget *window); void SetMacOSDarkMode(bool dark); -MacPermissionStatus CheckPermissionWithPrompt(MacPermissionType type, - bool prompt_for_permission); +MacPermissionStatus CheckPermissionWithPrompt(MacPermissionType type, bool prompt_for_permission); #define CheckPermission(x) CheckPermissionWithPrompt(x, false) #define RequestPermission(x) CheckPermissionWithPrompt(x, true) void OpenMacOSPrivacyPreferences(const char *tab); diff --git a/UI/preview-controls.cpp b/UI/preview-controls.cpp index ba4d6d400..7564e1bdb 100644 --- a/UI/preview-controls.cpp +++ b/UI/preview-controls.cpp @@ -51,8 +51,7 @@ void OBSPreviewScalingComboBox::OutputResized(uint32_t width, uint32_t height) { SetOutputSize(width, height); - bool canvasMatchesOutput = output_width == canvas_width && - output_height == canvas_height; + bool canvasMatchesOutput = output_width == canvas_width && output_height == canvas_height; SetScaleOutputEnabled(!canvasMatchesOutput); UpdateOutputText(); @@ -94,8 +93,7 @@ void OBSPreviewScalingComboBox::UpdateAllText() void OBSPreviewScalingComboBox::UpdateCanvasText() { QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas"); - text = text.arg(QString::number(canvas_width), - QString::number(canvas_height)); + text = text.arg(QString::number(canvas_width), QString::number(canvas_height)); setItemText(1, text); } @@ -103,8 +101,7 @@ void OBSPreviewScalingComboBox::UpdateOutputText() { if (scaleOutputEnabled) { QString text = QTStr("Basic.MainMenu.Edit.Scale.Output"); - text = text.arg(QString::number(output_width), - QString::number(output_height)); + text = text.arg(QString::number(output_width), QString::number(output_height)); setItemText(2, text); } } @@ -127,8 +124,7 @@ void OBSPreviewScalingComboBox::UpdateSelection() } else { if (previewScale == 1.0f) { setCurrentIndex(1); - } else if (scaleOutputEnabled && - (previewScale == outputScale)) { + } else if (scaleOutputEnabled && (previewScale == outputScale)) { setCurrentIndex(2); } else { setCurrentIndex(-1); diff --git a/UI/preview-controls.hpp b/UI/preview-controls.hpp index 360d992cd..4078dbea9 100644 --- a/UI/preview-controls.hpp +++ b/UI/preview-controls.hpp @@ -38,9 +38,7 @@ class OBSPreviewScalingComboBox : public QComboBox { Q_OBJECT public: - OBSPreviewScalingComboBox(QWidget *parent = nullptr) : QComboBox(parent) - { - } + OBSPreviewScalingComboBox(QWidget *parent = nullptr) : QComboBox(parent) {} inline void SetCanvasSize(uint32_t width, uint32_t height) { diff --git a/UI/qt-display.cpp b/UI/qt-display.cpp index 5941e7b05..f7c37ae9a 100644 --- a/UI/qt-display.cpp +++ b/UI/qt-display.cpp @@ -35,8 +35,7 @@ protected: switch (event->type()) { case QEvent::PlatformSurface: - surfaceEvent = - static_cast(event); + surfaceEvent = static_cast(event); switch (surfaceEvent->surfaceEventType()) { case QPlatformSurfaceEvent::SurfaceAboutToBeDestroyed: @@ -60,14 +59,12 @@ static inline long long color_to_int(const QColor &color) return ((val & 0xff) << shift); }; - return shift(color.red(), 0) | shift(color.green(), 8) | - shift(color.blue(), 16) | shift(color.alpha(), 24); + return shift(color.red(), 0) | shift(color.green(), 8) | shift(color.blue(), 16) | shift(color.alpha(), 24); } static inline QColor rgba_to_color(uint32_t rgba) { - return QColor::fromRgb(rgba & 0xFF, (rgba >> 8) & 0xFF, - (rgba >> 16) & 0xFF, (rgba >> 24) & 0xFF); + return QColor::fromRgb(rgba & 0xFF, (rgba >> 8) & 0xFF, (rgba >> 16) & 0xFF, (rgba >> 24) & 0xFF); } static bool QTToGSWindow(QWindow *window, gs_window &gswindow) @@ -86,10 +83,8 @@ static bool QTToGSWindow(QWindow *window, gs_window &gswindow) break; #ifdef ENABLE_WAYLAND case OBS_NIX_PLATFORM_WAYLAND: { - QPlatformNativeInterface *native = - QGuiApplication::platformNativeInterface(); - gswindow.display = - native->nativeResourceForWindow("surface", window); + QPlatformNativeInterface *native = QGuiApplication::platformNativeInterface(); + gswindow.display = native->nativeResourceForWindow("surface", window); success = gswindow.display != nullptr; break; } @@ -102,8 +97,7 @@ static bool QTToGSWindow(QWindow *window, gs_window &gswindow) return success; } -OBSQTDisplay::OBSQTDisplay(QWidget *parent, Qt::WindowFlags flags) - : QWidget(parent, flags) +OBSQTDisplay::OBSQTDisplay(QWidget *parent, Qt::WindowFlags flags) : QWidget(parent, flags) { setAttribute(Qt::WA_PaintOnScreen); setAttribute(Qt::WA_StaticContents); @@ -124,8 +118,7 @@ OBSQTDisplay::OBSQTDisplay(QWidget *parent, Qt::WindowFlags flags) CreateDisplay(); } else { QSize size = GetPixelSize(this); - obs_display_resize(display, size.width(), - size.height()); + obs_display_resize(display, size.width(), size.height()); } }; diff --git a/UI/qt-display.hpp b/UI/qt-display.hpp index 7a90f10fb..e83505a22 100644 --- a/UI/qt-display.hpp +++ b/UI/qt-display.hpp @@ -7,9 +7,8 @@ class OBSQTDisplay : public QWidget { Q_OBJECT - Q_PROPERTY(QColor displayBackgroundColor MEMBER backgroundColor READ - GetDisplayBackgroundColor WRITE - SetDisplayBackgroundColor) + Q_PROPERTY(QColor displayBackgroundColor MEMBER backgroundColor READ GetDisplayBackgroundColor WRITE + SetDisplayBackgroundColor) OBSDisplay display; bool destroying = false; @@ -17,16 +16,14 @@ class OBSQTDisplay : public QWidget { virtual void paintEvent(QPaintEvent *event) override; virtual void moveEvent(QMoveEvent *event) override; virtual void resizeEvent(QResizeEvent *event) override; - virtual bool nativeEvent(const QByteArray &eventType, void *message, - qintptr *result) override; + virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override; signals: void DisplayCreated(OBSQTDisplay *window); void DisplayResized(); public: - OBSQTDisplay(QWidget *parent = nullptr, - Qt::WindowFlags flags = Qt::WindowFlags()); + OBSQTDisplay(QWidget *parent = nullptr, Qt::WindowFlags flags = Qt::WindowFlags()); ~OBSQTDisplay() { display = nullptr; } virtual QPaintEngine *paintEngine() const override; diff --git a/UI/remote-text.cpp b/UI/remote-text.cpp index d07ec0e51..4b81e32bb 100644 --- a/UI/remote-text.cpp +++ b/UI/remote-text.cpp @@ -58,8 +58,7 @@ void RemoteTextThread::run() header = curl_slist_append(header, versionString.c_str()); if (!contentTypeString.empty()) { - header = curl_slist_append(header, - contentTypeString.c_str()); + header = curl_slist_append(header, contentTypeString.c_str()); } for (std::string &h : extraHeaders) @@ -70,24 +69,20 @@ void RemoteTextThread::run() curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, header); curl_easy_setopt(curl.get(), CURLOPT_ERRORBUFFER, error); curl_easy_setopt(curl.get(), CURLOPT_FAILONERROR, 1L); - curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, - string_write); + curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, string_write); curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &str); curl_obs_set_revoke_setting(curl.get()); if (timeoutSec) - curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, - timeoutSec); + curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, timeoutSec); if (!postData.empty()) { - curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, - postData.c_str()); + curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postData.c_str()); } code = curl_easy_perform(curl.get()); if (code != CURLE_OK) { - blog(LOG_WARNING, - "RemoteTextThread: HTTP request failed. %s", + blog(LOG_WARNING, "RemoteTextThread: HTTP request failed. %s", strlen(error) ? error : curl_easy_strerror(code)); emit Result(QString(), QT_UTF8(error)); } else { @@ -98,8 +93,7 @@ void RemoteTextThread::run() } } -static size_t header_write(char *ptr, size_t size, size_t nmemb, - vector &list) +static size_t header_write(char *ptr, size_t size, size_t nmemb, vector &list) { string str; @@ -116,12 +110,9 @@ static size_t header_write(char *ptr, size_t size, size_t nmemb, return total; } -bool GetRemoteFile(const char *url, std::string &str, std::string &error, - long *responseCode, const char *contentType, - std::string request_type, const char *postData, - std::vector extraHeaders, - std::string *signature, int timeoutSec, bool fail_on_error, - int postDataSize) +bool GetRemoteFile(const char *url, std::string &str, std::string &error, long *responseCode, const char *contentType, + std::string request_type, const char *postData, std::vector extraHeaders, + std::string *signature, int timeoutSec, bool fail_on_error, int postDataSize) { vector header_in_list; char error_in[CURL_ERROR_SIZE]; @@ -145,8 +136,7 @@ bool GetRemoteFile(const char *url, std::string &str, std::string &error, header = curl_slist_append(header, versionString.c_str()); if (!contentTypeString.empty()) { - header = curl_slist_append(header, - contentTypeString.c_str()); + header = curl_slist_append(header, contentTypeString.c_str()); } for (std::string &h : extraHeaders) @@ -158,61 +148,47 @@ bool GetRemoteFile(const char *url, std::string &str, std::string &error, curl_easy_setopt(curl.get(), CURLOPT_ERRORBUFFER, error_in); if (fail_on_error) curl_easy_setopt(curl.get(), CURLOPT_FAILONERROR, 1L); - curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, - string_write); + curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, string_write); curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &str); curl_obs_set_revoke_setting(curl.get()); if (signature) { - curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, - header_write); - curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, - &header_in_list); + curl_easy_setopt(curl.get(), CURLOPT_HEADERFUNCTION, header_write); + curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &header_in_list); } if (timeoutSec) - curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, - timeoutSec); + curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, timeoutSec); if (!request_type.empty()) { if (request_type != "GET") - curl_easy_setopt(curl.get(), - CURLOPT_CUSTOMREQUEST, - request_type.c_str()); + curl_easy_setopt(curl.get(), CURLOPT_CUSTOMREQUEST, request_type.c_str()); // Special case of "POST" if (request_type == "POST") { curl_easy_setopt(curl.get(), CURLOPT_POST, 1); if (!postData) - curl_easy_setopt(curl.get(), - CURLOPT_POSTFIELDS, - "{}"); + curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, "{}"); } } if (postData) { if (postDataSize > 0) { - curl_easy_setopt(curl.get(), - CURLOPT_POSTFIELDSIZE, - (long)postDataSize); + curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDSIZE, (long)postDataSize); } - curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, - postData); + curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postData); } code = curl_easy_perform(curl.get()); if (responseCode) - curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, - responseCode); + curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, responseCode); if (code != CURLE_OK) { - error = strlen(error_in) ? error_in - : curl_easy_strerror(code); + error = strlen(error_in) ? error_in : curl_easy_strerror(code); } else if (signature) { for (string &h : header_in_list) { string name = h.substr(0, 13); // HTTP headers are technically case-insensitive - if (name == "X-Signature: " || - name == "x-signature: ") { + if (name == "X-Signature: " || name == "x-signature: ") { *signature = h.substr(13); break; } diff --git a/UI/remote-text.hpp b/UI/remote-text.hpp index 5b8454f84..f6f8efbc1 100644 --- a/UI/remote-text.hpp +++ b/UI/remote-text.hpp @@ -38,10 +38,8 @@ signals: void Result(const QString &text, const QString &error); public: - inline RemoteTextThread(std::string url_, - std::string contentType_ = std::string(), - std::string postData_ = std::string(), - int timeoutSec_ = 0) + inline RemoteTextThread(std::string url_, std::string contentType_ = std::string(), + std::string postData_ = std::string(), int timeoutSec_ = 0) : url(url_), contentType(contentType_), postData(postData_), @@ -49,10 +47,8 @@ public: { } - inline RemoteTextThread(std::string url_, - std::vector &&extraHeaders_, - std::string contentType_ = std::string(), - std::string postData_ = std::string(), + inline RemoteTextThread(std::string url_, std::vector &&extraHeaders_, + std::string contentType_ = std::string(), std::string postData_ = std::string(), int timeoutSec_ = 0) : url(url_), contentType(contentType_), @@ -63,10 +59,7 @@ public: } }; -bool GetRemoteFile( - const char *url, std::string &str, std::string &error, - long *responseCode = nullptr, const char *contentType = nullptr, - std::string request_type = "", const char *postData = nullptr, - std::vector extraHeaders = std::vector(), - std::string *signature = nullptr, int timeoutSec = 0, - bool fail_on_error = true, int postDataSize = 0); +bool GetRemoteFile(const char *url, std::string &str, std::string &error, long *responseCode = nullptr, + const char *contentType = nullptr, std::string request_type = "", const char *postData = nullptr, + std::vector extraHeaders = std::vector(), std::string *signature = nullptr, + int timeoutSec = 0, bool fail_on_error = true, int postDataSize = 0); diff --git a/UI/scene-tree.cpp b/UI/scene-tree.cpp index 6ace1c478..fc64b11f7 100644 --- a/UI/scene-tree.cpp +++ b/UI/scene-tree.cpp @@ -182,9 +182,7 @@ void SceneTree::RepositionGrid(QDragMoveEvent *event) QModelIndex index = indexFromItem(wItem); - int off = (i >= r ? 1 : 0) - - (i > orig && i > r ? 1 : 0) - - (i > orig && i == r ? 2 : 0); + int off = (i >= r ? 1 : 0) - (i > orig && i > r ? 1 : 0) - (i > orig && i == r ? 2 : 0); int xPos = (i + off) % (int)std::ceil(wid / maxWidth); int yPos = (i + off) / (int)std::ceil(wid / maxWidth); @@ -240,11 +238,9 @@ void SceneTree::rowsInserted(const QModelIndex &parent, int start, int end) #if QT_VERSION < QT_VERSION_CHECK(6, 4, 3) // Workaround for QTBUG-105870. Remove once that is solved upstream. -void SceneTree::selectionChanged(const QItemSelection &selected, - const QItemSelection &deselected) +void SceneTree::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { - if (selected.count() == 0 && deselected.count() > 0 && - !property("clearing").toBool()) + if (selected.count() == 0 && deselected.count() > 0 && !property("clearing").toBool()) setCurrentRow(deselected.indexes().front().row()); } #endif diff --git a/UI/scene-tree.hpp b/UI/scene-tree.hpp index 0950f12ea..5fc765a92 100644 --- a/UI/scene-tree.hpp +++ b/UI/scene-tree.hpp @@ -6,10 +6,8 @@ class SceneTree : public QListWidget { Q_OBJECT - Q_PROPERTY(int gridItemWidth READ GetGridItemWidth WRITE - SetGridItemWidth DESIGNABLE true) - Q_PROPERTY(int gridItemHeight READ GetGridItemHeight WRITE - SetGridItemHeight DESIGNABLE true) + Q_PROPERTY(int gridItemWidth READ GetGridItemWidth WRITE SetGridItemWidth DESIGNABLE true) + Q_PROPERTY(int gridItemHeight READ GetGridItemHeight WRITE SetGridItemHeight DESIGNABLE true) bool gridMode = false; int maxWidth = 150; @@ -36,12 +34,9 @@ protected: virtual void dropEvent(QDropEvent *event) override; virtual void dragMoveEvent(QDragMoveEvent *event) override; virtual void dragLeaveEvent(QDragLeaveEvent *event) override; - virtual void rowsInserted(const QModelIndex &parent, int start, - int end) override; + virtual void rowsInserted(const QModelIndex &parent, int start, int end) override; #if QT_VERSION < QT_VERSION_CHECK(6, 4, 3) - virtual void - selectionChanged(const QItemSelection &selected, - const QItemSelection &deselected) override; + virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override; #endif signals: diff --git a/UI/source-label.hpp b/UI/source-label.hpp index b8f0fbe3c..a73fa3c6d 100644 --- a/UI/source-label.hpp +++ b/UI/source-label.hpp @@ -28,15 +28,11 @@ public: OBSSignal removedSignal; OBSSignal destroyedSignal; - OBSSourceLabel(const obs_source_t *source, QWidget *parent = nullptr, - Qt::WindowFlags f = Qt::WindowFlags()) + OBSSourceLabel(const obs_source_t *source, QWidget *parent = nullptr, Qt::WindowFlags f = Qt::WindowFlags()) : QLabel(obs_source_get_name(source), parent, f), - renamedSignal(obs_source_get_signal_handler(source), "rename", - &OBSSourceLabel::SourceRenamed, this), - removedSignal(obs_source_get_signal_handler(source), "remove", - &OBSSourceLabel::SourceRemoved, this), - destroyedSignal(obs_source_get_signal_handler(source), - "destroy", &OBSSourceLabel::SourceDestroyed, + renamedSignal(obs_source_get_signal_handler(source), "rename", &OBSSourceLabel::SourceRenamed, this), + removedSignal(obs_source_get_signal_handler(source), "remove", &OBSSourceLabel::SourceRemoved, this), + destroyedSignal(obs_source_get_signal_handler(source), "destroy", &OBSSourceLabel::SourceDestroyed, this) { } diff --git a/UI/source-tree.cpp b/UI/source-tree.cpp index 2cc70c1f6..a0242e3cd 100644 --- a/UI/source-tree.cpp +++ b/UI/source-tree.cpp @@ -30,9 +30,7 @@ static inline OBSScene GetCurrentScene() /* ========================================================================= */ -SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) - : tree(tree_), - sceneitem(sceneitem_) +SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) : tree(tree_), sceneitem(sceneitem_) { setAttribute(Qt::WA_TranslucentBackground); setMouseTracking(true); @@ -40,8 +38,7 @@ SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) obs_source_t *source = obs_sceneitem_get_source(sceneitem); const char *name = obs_source_get_name(source); - OBSDataAutoRelease privData = - obs_sceneitem_get_private_settings(sceneitem); + OBSDataAutoRelease privData = obs_sceneitem_get_private_settings(sceneitem); int preset = obs_data_get_int(privData, "color-preset"); if (preset == 1) { @@ -84,15 +81,13 @@ SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) vis->setProperty("class", "checkbox-icon indicator-visibility"); vis->setChecked(sourceVisible); vis->setAccessibleName(QTStr("Basic.Main.Sources.Visibility")); - vis->setAccessibleDescription( - QTStr("Basic.Main.Sources.VisibilityDescription").arg(name)); + vis->setAccessibleDescription(QTStr("Basic.Main.Sources.VisibilityDescription").arg(name)); lock = new QCheckBox(); lock->setProperty("class", "checkbox-icon indicator-lock"); lock->setChecked(obs_sceneitem_locked(sceneitem)); lock->setAccessibleName(QTStr("Basic.Main.Sources.Lock")); - lock->setAccessibleDescription( - QTStr("Basic.Main.Sources.LockDescription").arg(name)); + lock->setAccessibleDescription(QTStr("Basic.Main.Sources.LockDescription").arg(name)); label = new OBSSourceLabel(source); label->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); @@ -135,26 +130,20 @@ SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) const char *uuid = obs_source_get_uuid(scenesource); obs_source_t *source = obs_sceneitem_get_source(sceneitem); - auto undo_redo = [](const std::string &uuid, int64_t id, - bool val) { - OBSSourceAutoRelease s = - obs_get_source_by_uuid(uuid.c_str()); + auto undo_redo = [](const std::string &uuid, int64_t id, bool val) { + OBSSourceAutoRelease s = obs_get_source_by_uuid(uuid.c_str()); obs_scene_t *sc = obs_group_or_scene_from_source(s); - obs_sceneitem_t *si = - obs_scene_find_sceneitem_by_id(sc, id); + obs_sceneitem_t *si = obs_scene_find_sceneitem_by_id(sc, id); if (si) obs_sceneitem_set_visible(si, val); }; - QString str = QTStr(val ? "Undo.ShowSceneItem" - : "Undo.HideSceneItem"); + QString str = QTStr(val ? "Undo.ShowSceneItem" : "Undo.HideSceneItem"); OBSBasic *main = OBSBasic::Get(); - main->undo_s.add_action( - str.arg(obs_source_get_name(source), name), - std::bind(undo_redo, std::placeholders::_1, id, !val), - std::bind(undo_redo, std::placeholders::_1, id, val), - uuid, uuid); + main->undo_s.add_action(str.arg(obs_source_get_name(source), name), + std::bind(undo_redo, std::placeholders::_1, id, !val), + std::bind(undo_redo, std::placeholders::_1, id, val), uuid, uuid); QSignalBlocker sourcesSignalBlocker(this); obs_sceneitem_set_visible(sceneitem, val); @@ -200,16 +189,12 @@ void SourceTreeItem::ReconnectSignals() /* --------------------------------------------------------- */ auto removeItem = [](void *data, calldata_t *cd) { - SourceTreeItem *this_ = - reinterpret_cast(data); - obs_sceneitem_t *curItem = - (obs_sceneitem_t *)calldata_ptr(cd, "item"); - obs_scene_t *curScene = - (obs_scene_t *)calldata_ptr(cd, "scene"); + SourceTreeItem *this_ = reinterpret_cast(data); + obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); + obs_scene_t *curScene = (obs_scene_t *)calldata_ptr(cd, "scene"); if (curItem == this_->sceneitem) { - QMetaObject::invokeMethod(this_->tree, "Remove", - Q_ARG(OBSSceneItem, curItem), + QMetaObject::invokeMethod(this_->tree, "Remove", Q_ARG(OBSSceneItem, curItem), Q_ARG(OBSScene, curScene)); curItem = nullptr; } @@ -218,52 +203,41 @@ void SourceTreeItem::ReconnectSignals() }; auto itemVisible = [](void *data, calldata_t *cd) { - SourceTreeItem *this_ = - reinterpret_cast(data); - obs_sceneitem_t *curItem = - (obs_sceneitem_t *)calldata_ptr(cd, "item"); + SourceTreeItem *this_ = reinterpret_cast(data); + obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); bool visible = calldata_bool(cd, "visible"); if (curItem == this_->sceneitem) - QMetaObject::invokeMethod(this_, "VisibilityChanged", - Q_ARG(bool, visible)); + QMetaObject::invokeMethod(this_, "VisibilityChanged", Q_ARG(bool, visible)); }; auto itemLocked = [](void *data, calldata_t *cd) { - SourceTreeItem *this_ = - reinterpret_cast(data); - obs_sceneitem_t *curItem = - (obs_sceneitem_t *)calldata_ptr(cd, "item"); + SourceTreeItem *this_ = reinterpret_cast(data); + obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); bool locked = calldata_bool(cd, "locked"); if (curItem == this_->sceneitem) - QMetaObject::invokeMethod(this_, "LockedChanged", - Q_ARG(bool, locked)); + QMetaObject::invokeMethod(this_, "LockedChanged", Q_ARG(bool, locked)); }; auto itemSelect = [](void *data, calldata_t *cd) { - SourceTreeItem *this_ = - reinterpret_cast(data); - obs_sceneitem_t *curItem = - (obs_sceneitem_t *)calldata_ptr(cd, "item"); + SourceTreeItem *this_ = reinterpret_cast(data); + obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); if (curItem == this_->sceneitem) QMetaObject::invokeMethod(this_, "Select"); }; auto itemDeselect = [](void *data, calldata_t *cd) { - SourceTreeItem *this_ = - reinterpret_cast(data); - obs_sceneitem_t *curItem = - (obs_sceneitem_t *)calldata_ptr(cd, "item"); + SourceTreeItem *this_ = reinterpret_cast(data); + obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); if (curItem == this_->sceneitem) QMetaObject::invokeMethod(this_, "Deselect"); }; auto reorderGroup = [](void *data, calldata_t *) { - SourceTreeItem *this_ = - reinterpret_cast(data); + SourceTreeItem *this_ = reinterpret_cast(data); QMetaObject::invokeMethod(this_->tree, "ReorderItems"); }; @@ -288,8 +262,7 @@ void SourceTreeItem::ReconnectSignals() /* --------------------------------------------------------- */ auto removeSource = [](void *data, calldata_t *) { - SourceTreeItem *this_ = - reinterpret_cast(data); + SourceTreeItem *this_ = reinterpret_cast(data); this_->DisconnectSignals(); this_->sceneitem = nullptr; QMetaObject::invokeMethod(this_->tree, "RefreshItems"); @@ -308,8 +281,7 @@ void SourceTreeItem::mouseDoubleClickEvent(QMouseEvent *event) expand->setChecked(!expand->isChecked()); } else { obs_source_t *source = obs_sceneitem_get_source(sceneitem); - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); if (obs_source_configurable(source)) { main->CreatePropertiesWindow(source); } @@ -366,8 +338,7 @@ void SourceTreeItem::ExitEditMode(bool save) OBSData redoSceneData = main->BackupScene(GetCurrentScene()); QString text = QTStr("Undo.GroupItems").arg(newName.c_str()); - main->CreateSceneUndoRedoAction(text, tree->undoSceneData, - redoSceneData); + main->CreateSceneUndoRedoAction(text, tree->undoSceneData, redoSceneData); tree->undoSceneData = nullptr; } @@ -400,8 +371,7 @@ void SourceTreeItem::ExitEditModeInternal(bool save) return; if (newName.empty()) { - OBSMessageBox::information(main, QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::information(main, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); return; } @@ -415,13 +385,11 @@ void SourceTreeItem::ExitEditModeInternal(bool save) /* ----------------------------------------- */ /* check for existing source */ - OBSSourceAutoRelease existingSource = - obs_get_source_by_name(newName.c_str()); + OBSSourceAutoRelease existingSource = obs_get_source_by_name(newName.c_str()); bool exists = !!existingSource; if (exists) { - OBSMessageBox::information(main, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::information(main, QTStr("NameExists.Title"), QTStr("NameExists.Text")); return; } @@ -430,33 +398,27 @@ void SourceTreeItem::ExitEditModeInternal(bool save) QSignalBlocker sourcesSignalBlocker(this); std::string prevName(obs_source_get_name(source)); - std::string scene_uuid = - obs_source_get_uuid(main->GetCurrentSceneSource()); + std::string scene_uuid = obs_source_get_uuid(main->GetCurrentSceneSource()); auto undo = [scene_uuid, prevName, main](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(data.c_str()); obs_source_set_name(source, prevName.c_str()); - OBSSourceAutoRelease scene_source = - obs_get_source_by_uuid(scene_uuid.c_str()); + OBSSourceAutoRelease scene_source = obs_get_source_by_uuid(scene_uuid.c_str()); main->SetCurrentScene(scene_source.Get(), true); }; std::string editedName = newName; auto redo = [scene_uuid, main, editedName](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(data.c_str()); obs_source_set_name(source, editedName.c_str()); - OBSSourceAutoRelease scene_source = - obs_get_source_by_uuid(scene_uuid.c_str()); + OBSSourceAutoRelease scene_source = obs_get_source_by_uuid(scene_uuid.c_str()); main->SetCurrentScene(scene_source.Get(), true); }; const char *uuid = obs_source_get_uuid(source); - main->undo_s.add_action(QTStr("Undo.Rename").arg(newName.c_str()), undo, - redo, uuid, uuid); + main->undo_s.add_action(QTStr("Undo.Rename").arg(newName.c_str()), undo, redo, uuid, uuid); obs_source_set_name(source, newName.c_str()); } @@ -467,15 +429,11 @@ bool SourceTreeItem::eventFilter(QObject *object, QEvent *event) return false; if (LineEditCanceled(event)) { - QMetaObject::invokeMethod(this, "ExitEditMode", - Qt::QueuedConnection, - Q_ARG(bool, false)); + QMetaObject::invokeMethod(this, "ExitEditMode", Qt::QueuedConnection, Q_ARG(bool, false)); return true; } if (LineEditChanged(event)) { - QMetaObject::invokeMethod(this, "ExitEditMode", - Qt::QueuedConnection, - Q_ARG(bool, true)); + QMetaObject::invokeMethod(this, "ExitEditMode", Qt::QueuedConnection, Q_ARG(bool, true)); return true; } @@ -559,14 +517,12 @@ void SourceTreeItem::Update(bool force) #endif boxLayout->insertWidget(0, expand); - OBSDataAutoRelease data = - obs_sceneitem_get_private_settings(sceneitem); + OBSDataAutoRelease data = obs_sceneitem_get_private_settings(sceneitem); expand->blockSignals(true); expand->setChecked(obs_data_get_bool(data, "collapsed")); expand->blockSignals(false); - connect(expand, &QPushButton::toggled, this, - &SourceTreeItem::ExpandClicked); + connect(expand, &QPushButton::toggled, this, &SourceTreeItem::ExpandClicked); } else { spacer = new QSpacerItem(3, 1); @@ -633,8 +589,7 @@ void SourceTreeModel::Clear() static bool enumItem(obs_scene_t *, obs_sceneitem_t *item, void *ptr) { - QVector &items = - *reinterpret_cast *>(ptr); + QVector &items = *reinterpret_cast *>(ptr); obs_source_t *src = obs_sceneitem_get_source(item); if (obs_source_removed(src)) { @@ -642,13 +597,11 @@ static bool enumItem(obs_scene_t *, obs_sceneitem_t *item, void *ptr) } if (obs_sceneitem_is_group(item)) { - OBSDataAutoRelease data = - obs_sceneitem_get_private_settings(item); + OBSDataAutoRelease data = obs_sceneitem_get_private_settings(item); bool collapse = obs_data_get_bool(data, "collapsed"); if (!collapse) { - obs_scene_t *scene = - obs_sceneitem_group_get_scene(item); + obs_scene_t *scene = obs_sceneitem_group_get_scene(item); obs_scene_enum_items(scene, enumItem, &items); } @@ -674,15 +627,13 @@ void SourceTreeModel::SceneChanged() bool select = obs_sceneitem_selected(items[i]); QModelIndex index = createIndex(i, 0); - st->selectionModel()->select( - index, select ? QItemSelectionModel::Select - : QItemSelectionModel::Deselect); + st->selectionModel()->select(index, + select ? QItemSelectionModel::Select : QItemSelectionModel::Deselect); } } /* moves a scene item index (blame linux distros for using older Qt builds) */ -static inline void MoveItem(QVector &items, int oldIdx, - int newIdx) +static inline void MoveItem(QVector &items, int oldIdx, int newIdx) { OBSSceneItem item = items[oldIdx]; items.remove(oldIdx); @@ -755,8 +706,7 @@ void SourceTreeModel::ReorderItems() } /* move items */ - beginMoveRows(QModelIndex(), idx1Old, idx1Old + count - 1, - QModelIndex(), idx1New + count); + beginMoveRows(QModelIndex(), idx1Old, idx1Old + count - 1, QModelIndex(), idx1New + count); for (i = 0; i < count; i++) { int to = idx1New + count; if (to > idx1Old) @@ -802,8 +752,7 @@ void SourceTreeModel::Remove(obs_sceneitem_t *item) for (int i = endIdx + 1; i < items.count(); i++) { obs_sceneitem_t *subitem = items[i]; - obs_scene_t *subscene = - obs_sceneitem_get_scene(subitem); + obs_scene_t *subscene = obs_sceneitem_get_scene(subitem); if (subscene == scene) endIdx = i; @@ -829,9 +778,7 @@ OBSSceneItem SourceTreeModel::Get(int idx) return items[idx]; } -SourceTreeModel::SourceTreeModel(SourceTree *st_) - : QAbstractListModel(st_), - st(st_) +SourceTreeModel::SourceTreeModel(SourceTree *st_) : QAbstractListModel(st_), st(st_) { obs_frontend_add_event_callback(OBSFrontendEvent, this); } @@ -860,8 +807,7 @@ Qt::ItemFlags SourceTreeModel::flags(const QModelIndex &index) const obs_sceneitem_t *item = items[index.row()]; bool is_group = obs_sceneitem_is_group(item); - return QAbstractListModel::flags(index) | Qt::ItemIsEditable | - Qt::ItemIsDragEnabled | + return QAbstractListModel::flags(index) | Qt::ItemIsEditable | Qt::ItemIsDragEnabled | (is_group ? Qt::ItemIsDropEnabled : Qt::NoItemFlags); } @@ -877,8 +823,7 @@ QString SourceTreeModel::GetNewGroupName() int i = 2; for (;;) { - OBSSourceAutoRelease group = - obs_get_source_by_name(QT_TO_UTF8(name)); + OBSSourceAutoRelease group = obs_get_source_by_name(QT_TO_UTF8(name)); if (!group) break; name = QTStr("Basic.Main.Group").arg(QString::number(i++)); @@ -890,8 +835,7 @@ QString SourceTreeModel::GetNewGroupName() void SourceTreeModel::AddGroup() { QString name = GetNewGroupName(); - obs_sceneitem_t *group = - obs_scene_add_group(GetCurrentScene(), QT_TO_UTF8(name)); + obs_sceneitem_t *group = obs_scene_add_group(GetCurrentScene(), QT_TO_UTF8(name)); if (!group) return; @@ -902,8 +846,7 @@ void SourceTreeModel::AddGroup() st->UpdateWidget(createIndex(0, 0, nullptr), group); UpdateGroupState(true); - QMetaObject::invokeMethod(st, "Edit", Qt::QueuedConnection, - Q_ARG(int, 0)); + QMetaObject::invokeMethod(st, "Edit", Qt::QueuedConnection, Q_ARG(int, 0)); } void SourceTreeModel::GroupSelectedItems(QModelIndexList &indices) @@ -924,8 +867,7 @@ void SourceTreeModel::GroupSelectedItems(QModelIndexList &indices) st->undoSceneData = main->BackupScene(scene); - obs_sceneitem_t *item = obs_scene_insert_group( - scene, QT_TO_UTF8(name), item_order.data(), item_order.size()); + obs_sceneitem_t *item = obs_scene_insert_group(scene, QT_TO_UTF8(name), item_order.data(), item_order.size()); if (!item) { st->undoSceneData = nullptr; return; @@ -947,8 +889,7 @@ void SourceTreeModel::GroupSelectedItems(QModelIndexList &indices) /* that's created automatically. */ int newIdx = indices[0].row(); - QMetaObject::invokeMethod(st, "NewGroupEdit", Qt::QueuedConnection, - Q_ARG(int, newIdx)); + QMetaObject::invokeMethod(st, "NewGroupEdit", Qt::QueuedConnection, Q_ARG(int, newIdx)); } void SourceTreeModel::UngroupSelectedGroups(QModelIndexList &indices) @@ -968,8 +909,7 @@ void SourceTreeModel::UngroupSelectedGroups(QModelIndexList &indices) SceneChanged(); OBSData redoData = main->BackupScene(scene); - main->CreateSceneUndoRedoAction(QTStr("Basic.Main.Ungroup"), undoData, - redoData); + main->CreateSceneUndoRedoAction(QTStr("Basic.Main.Ungroup"), undoData, redoData); } void SourceTreeModel::ExpandGroup(obs_sceneitem_t *item) @@ -1045,19 +985,17 @@ SourceTree::SourceTree(QWidget *parent_) : QListView(parent_) { SourceTreeModel *stm_ = new SourceTreeModel(this); setModel(stm_); - setStyleSheet(QString( - "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" - "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" - "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" - "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" - "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" - "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" - "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" - "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}")); + setStyleSheet(QString("*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" + "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" + "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" + "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" + "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" + "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" + "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" + "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}")); UpdateNoSourcesMessage(); - connect(App(), &OBSApp::StyleChanged, this, - &SourceTree::UpdateNoSourcesMessage); + connect(App(), &OBSApp::StyleChanged, this, &SourceTree::UpdateNoSourcesMessage); connect(App(), &OBSApp::StyleChanged, this, &SourceTree::UpdateIcons); setItemDelegate(new SourceTreeDelegate(this)); @@ -1126,9 +1064,7 @@ void SourceTree::SelectItem(obs_sceneitem_t *sceneitem, bool select) QModelIndex index = stm->createIndex(i, 0); if (index.isValid() && select != selectionModel()->isSelected(index)) - selectionModel()->select( - index, select ? QItemSelectionModel::Select - : QItemSelectionModel::Deselect); + selectionModel()->select(index, select ? QItemSelectionModel::Select : QItemSelectionModel::Deselect); } Q_DECLARE_METATYPE(OBSSceneItem); @@ -1175,9 +1111,7 @@ void SourceTree::dropEvent(QDropEvent *event) obs_sceneitem_t *dropItem = items[row]; /* item being dropped on */ bool itemIsGroup = obs_sceneitem_is_group(dropItem); - obs_sceneitem_t *dropGroup = - itemIsGroup ? dropItem - : obs_sceneitem_get_group(scene, dropItem); + obs_sceneitem_t *dropGroup = itemIsGroup ? dropItem : obs_sceneitem_get_group(scene, dropItem); /* not a group if moving above the group */ if (indicator == QAbstractItemView::AboveItem && itemIsGroup) @@ -1191,14 +1125,12 @@ void SourceTree::dropEvent(QDropEvent *event) bool dropOnCollapsed = false; if (dropGroup) { - obs_data_t *data = - obs_sceneitem_get_private_settings(dropGroup); + obs_data_t *data = obs_sceneitem_get_private_settings(dropGroup); dropOnCollapsed = obs_data_get_bool(data, "collapsed"); obs_data_release(data); } - if (indicator == QAbstractItemView::BelowItem || - indicator == QAbstractItemView::OnItem || + if (indicator == QAbstractItemView::BelowItem || indicator == QAbstractItemView::OnItem || indicator == QAbstractItemView::OnViewport) row++; @@ -1230,8 +1162,7 @@ void SourceTree::dropEvent(QDropEvent *event) itemBelow = stm->items[row]; if (hasGroups) { - if (!itemBelow || - obs_sceneitem_get_group(scene, itemBelow) != dropGroup) { + if (!itemBelow || obs_sceneitem_get_group(scene, itemBelow) != dropGroup) { dropGroup = nullptr; dropOnCollapsed = false; } @@ -1252,8 +1183,7 @@ void SourceTree::dropEvent(QDropEvent *event) for (int i = 0; i < indices.size(); i++) { obs_sceneitem_t *item = items[indices[i].row()]; if (obs_sceneitem_get_scene(item) != scene) - sources.push_back(obs_scene_get_source( - obs_sceneitem_get_scene(item))); + sources.push_back(obs_scene_get_source(obs_sceneitem_get_scene(item))); } if (dropGroup) sources.push_back(obs_sceneitem_get_source(dropGroup)); @@ -1282,13 +1212,10 @@ void SourceTree::dropEvent(QDropEvent *event) if (obs_sceneitem_is_group(item)) { for (int j = items.size() - 1; j >= 0; j--) { obs_sceneitem_t *subitem = items[j]; - obs_sceneitem_t *subitemGroup = - obs_sceneitem_get_group( - scene, subitem); + obs_sceneitem_t *subitemGroup = obs_sceneitem_get_group(scene, subitem); if (subitemGroup == item) { - QModelIndex idx = - stm->createIndex(j, 0); + QModelIndex idx = stm->createIndex(j, 0); indices.insert(i + 1, idx); } } @@ -1318,8 +1245,7 @@ void SourceTree::dropEvent(QDropEvent *event) itemTo--; if (itemTo != from) { - stm->beginMoveRows(QModelIndex(), from, from, - QModelIndex(), to); + stm->beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); MoveItem(items, from, itemTo); stm->endMoveRows(); } @@ -1348,22 +1274,18 @@ void SourceTree::dropEvent(QDropEvent *event) using insertCollapsed_t = decltype(insertCollapsed); - auto preInsertCollapsed = [](obs_scene_t *, obs_sceneitem_t *item, - void *param) { + auto preInsertCollapsed = [](obs_scene_t *, obs_sceneitem_t *item, void *param) { (*reinterpret_cast(param))(item); return true; }; auto insertLastGroup = [&]() { - OBSDataAutoRelease data = - obs_sceneitem_get_private_settings(lastGroup); + OBSDataAutoRelease data = obs_sceneitem_get_private_settings(lastGroup); bool collapsed = obs_data_get_bool(data, "collapsed"); if (collapsed) { insertCollapsedIdx = 0; - obs_sceneitem_group_enum_items(lastGroup, - preInsertCollapsed, - &insertCollapsed); + obs_sceneitem_group_enum_items(lastGroup, preInsertCollapsed, &insertCollapsed); } struct obs_sceneitem_order_info info; @@ -1407,8 +1329,7 @@ void SourceTree::dropEvent(QDropEvent *event) insertLastGroup(); } - obs_scene_reorder_items2(scene, orderList.data(), - orderList.size()); + obs_scene_reorder_items2(scene, orderList.data(), orderList.size()); }; using updateScene_t = decltype(updateScene); @@ -1454,8 +1375,7 @@ void SourceTree::dropEvent(QDropEvent *event) QListView::dropEvent(event); } -void SourceTree::selectionChanged(const QItemSelection &selected, - const QItemSelection &deselected) +void SourceTree::selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) { { QSignalBlocker sourcesSignalBlocker(this); @@ -1504,8 +1424,7 @@ void SourceTree::NewGroupEdit(int row) OBSData redoSceneData = main->BackupScene(GetCurrentScene()); QString text = QTStr("Undo.GroupItems").arg("Unknown"); - main->CreateSceneUndoRedoAction(text, undoSceneData, - redoSceneData); + main->CreateSceneUndoRedoAction(text, undoSceneData, redoSceneData); undoSceneData = nullptr; } @@ -1610,10 +1529,8 @@ void SourceTree::Remove(OBSSceneItem item, OBSScene scene) if (!main->SavingDisabled()) { obs_source_t *sceneSource = obs_scene_get_source(scene); obs_source_t *itemSource = obs_sceneitem_get_source(item); - blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'", - obs_source_get_name(itemSource), - obs_source_get_id(itemSource), - obs_source_get_name(sceneSource)); + blog(LOG_INFO, "User Removed source '%s' (%s) from scene '%s'", obs_source_get_name(itemSource), + obs_source_get_id(itemSource), obs_source_get_name(sceneSource)); } } @@ -1637,8 +1554,7 @@ void SourceTree::AddGroup() void SourceTree::UpdateNoSourcesMessage() { - QString file = !App()->IsThemeDark() ? ":res/images/no_sources.svg" - : "theme:Dark/no_sources.svg"; + QString file = !App()->IsThemeDark() ? ":res/images/no_sources.svg" : "theme:Dark/no_sources.svg"; iconNoSources.load(file); QTextOption opt(Qt::AlignHCenter); @@ -1668,8 +1584,7 @@ void SourceTree::paintEvent(QPaintEvent *event) QSizeF thisSize = size(); const qreal spacing = 16.0; - qreal totalHeight = - iconSize.height() + spacing + textSize.height(); + qreal totalHeight = iconSize.height() + spacing + textSize.height(); qreal x = thisSize.width() / 2.0 - iconSize.width() / 2.0; qreal y = thisSize.height() / 2.0 - totalHeight / 2.0; @@ -1684,13 +1599,9 @@ void SourceTree::paintEvent(QPaintEvent *event) } } -SourceTreeDelegate::SourceTreeDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} +SourceTreeDelegate::SourceTreeDelegate(QObject *parent) : QStyledItemDelegate(parent) {} -QSize SourceTreeDelegate::sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const +QSize SourceTreeDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const { SourceTree *tree = qobject_cast(parent()); QWidget *item = tree->indexWidget(index); diff --git a/UI/source-tree.hpp b/UI/source-tree.hpp index cdf2e205b..8f8922d52 100644 --- a/UI/source-tree.hpp +++ b/UI/source-tree.hpp @@ -120,8 +120,7 @@ public: explicit SourceTreeModel(SourceTree *st); virtual int rowCount(const QModelIndex &parent) const override; - virtual QVariant data(const QModelIndex &index, - int role) const override; + virtual QVariant data(const QModelIndex &index, int role) const override; virtual Qt::ItemFlags flags(const QModelIndex &index) const override; virtual Qt::DropActions supportedDropActions() const override; @@ -149,10 +148,7 @@ class SourceTree : public QListView { void UpdateWidget(const QModelIndex &idx, obs_sceneitem_t *item); void UpdateWidgets(bool force = false); - inline SourceTreeModel *GetStm() const - { - return reinterpret_cast(model()); - } + inline SourceTreeModel *GetStm() const { return reinterpret_cast(model()); } public: inline SourceTreeItem *GetItemWidget(int idx) @@ -194,9 +190,7 @@ protected: virtual void dropEvent(QDropEvent *event) override; virtual void paintEvent(QPaintEvent *event) override; - virtual void - selectionChanged(const QItemSelection &selected, - const QItemSelection &deselected) override; + virtual void selectionChanged(const QItemSelection &selected, const QItemSelection &deselected) override; }; class SourceTreeDelegate : public QStyledItemDelegate { @@ -204,6 +198,5 @@ class SourceTreeDelegate : public QStyledItemDelegate { public: SourceTreeDelegate(QObject *parent); - virtual QSize sizeHint(const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + virtual QSize sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const override; }; diff --git a/UI/system-info-windows.cpp b/UI/system-info-windows.cpp index 557ff75d5..084cdffe6 100644 --- a/UI/system-info-windows.cpp +++ b/UI/system-info-windows.cpp @@ -49,16 +49,14 @@ static std::optional> system_gpu_data() /* driver version */ LARGE_INTEGER umd; - hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), - &umd); + hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); if (SUCCEEDED(hr)) { const uint64_t version = umd.QuadPart; const uint16_t aa = (version >> 48) & 0xffff; const uint16_t bb = (version >> 32) & 0xffff; const uint16_t ccccc = (version >> 16) & 0xffff; const uint16_t ddddd = version & 0xffff; - snprintf(driver_version, sizeof(driver_version), - "%" PRIu16 ".%" PRIu16 ".%" PRIu16 ".%" PRIu16, + snprintf(driver_version, sizeof(driver_version), "%" PRIu16 ".%" PRIu16 ".%" PRIu16 ".%" PRIu16, aa, bb, ccccc, ddddd); data.driver_version = driver_version; } @@ -78,15 +76,12 @@ static void get_processor_info(char **name, DWORD *speed) memset(data, 0, sizeof(data)); - status = RegOpenKeyW( - HKEY_LOCAL_MACHINE, - L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key); + status = RegOpenKeyW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key); if (status != ERROR_SUCCESS) return; size = sizeof(data); - status = RegQueryValueExW(key, L"ProcessorNameString", NULL, NULL, - (LPBYTE)data, &size); + status = RegQueryValueExW(key, L"ProcessorNameString", NULL, NULL, (LPBYTE)data, &size); if (status == ERROR_SUCCESS) { os_wcs_to_utf8_ptr(data, 0, name); } else { @@ -94,25 +89,20 @@ static void get_processor_info(char **name, DWORD *speed) } size = sizeof(*speed); - status = RegQueryValueExW(key, L"~MHz", NULL, NULL, (LPBYTE)speed, - &size); + status = RegQueryValueExW(key, L"~MHz", NULL, NULL, (LPBYTE)speed, &size); if (status != ERROR_SUCCESS) *speed = 0; RegCloseKey(key); } -#define WIN10_GAME_BAR_REG_KEY \ - L"Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR" -#define WIN10_GAME_DVR_POLICY_REG_KEY \ - L"SOFTWARE\\Policies\\Microsoft\\Windows\\GameDVR" +#define WIN10_GAME_BAR_REG_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR" +#define WIN10_GAME_DVR_POLICY_REG_KEY L"SOFTWARE\\Policies\\Microsoft\\Windows\\GameDVR" #define WIN10_GAME_DVR_REG_KEY L"System\\GameConfigStore" #define WIN10_GAME_MODE_REG_KEY L"Software\\Microsoft\\GameBar" -#define WIN10_HAGS_REG_KEY \ - L"SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers" +#define WIN10_HAGS_REG_KEY L"SYSTEM\\CurrentControlSet\\Control\\GraphicsDrivers" -static std::optional -get_gaming_features_data(const win_version_info &ver) +static std::optional get_gaming_features_data(const win_version_info &ver) { uint32_t win_ver = (ver.major << 8) | ver.minor; if (win_ver < 0xA00) @@ -130,36 +120,29 @@ get_gaming_features_data(const win_version_info &ver) DWORD disabled_value; }; struct feature_mapping_s features[] = { - {&gaming_features.game_bar_enabled, HKEY_CURRENT_USER, - WIN10_GAME_BAR_REG_KEY, L"AppCaptureEnabled", 0, false, 0}, - {&gaming_features.game_dvr_allowed, HKEY_CURRENT_USER, - WIN10_GAME_DVR_POLICY_REG_KEY, L"AllowGameDVR", 0, false, 0}, - {&gaming_features.game_dvr_enabled, HKEY_CURRENT_USER, - WIN10_GAME_DVR_REG_KEY, L"GameDVR_Enabled", 0, false, 0}, - {&gaming_features.game_dvr_bg_recording, HKEY_CURRENT_USER, - WIN10_GAME_BAR_REG_KEY, L"HistoricalCaptureEnabled", 0, false, - 0}, - {&gaming_features.game_mode_enabled, HKEY_CURRENT_USER, - WIN10_GAME_MODE_REG_KEY, L"AutoGameModeEnabled", + {&gaming_features.game_bar_enabled, HKEY_CURRENT_USER, WIN10_GAME_BAR_REG_KEY, L"AppCaptureEnabled", 0, + false, 0}, + {&gaming_features.game_dvr_allowed, HKEY_CURRENT_USER, WIN10_GAME_DVR_POLICY_REG_KEY, L"AllowGameDVR", + 0, false, 0}, + {&gaming_features.game_dvr_enabled, HKEY_CURRENT_USER, WIN10_GAME_DVR_REG_KEY, L"GameDVR_Enabled", 0, + false, 0}, + {&gaming_features.game_dvr_bg_recording, HKEY_CURRENT_USER, WIN10_GAME_BAR_REG_KEY, + L"HistoricalCaptureEnabled", 0, false, 0}, + {&gaming_features.game_mode_enabled, HKEY_CURRENT_USER, WIN10_GAME_MODE_REG_KEY, L"AutoGameModeEnabled", L"AllowAutoGameMode", false, 0}, - {&gaming_features.hags_enabled, HKEY_LOCAL_MACHINE, - WIN10_HAGS_REG_KEY, L"HwSchMode", 0, true, 1}}; + {&gaming_features.hags_enabled, HKEY_LOCAL_MACHINE, WIN10_HAGS_REG_KEY, L"HwSchMode", 0, true, 1}}; for (int i = 0; i < sizeof(features) / sizeof(*features); ++i) { struct reg_dword info; - get_reg_dword(features[i].hkey, features[i].sub_key, - features[i].value_name, &info); + get_reg_dword(features[i].hkey, features[i].sub_key, features[i].value_name, &info); - if (info.status != ERROR_SUCCESS && - features[i].backup_value_name) { - get_reg_dword(features[i].hkey, features[i].sub_key, - features[i].backup_value_name, &info); + if (info.status != ERROR_SUCCESS && features[i].backup_value_name) { + get_reg_dword(features[i].hkey, features[i].sub_key, features[i].backup_value_name, &info); } if (info.status == ERROR_SUCCESS) { - *features[i].field = info.return_value != - features[i].disabled_value; + *features[i].field = info.return_value != features[i].disabled_value; } else if (features[i].non_existence_is_false) { *features[i].field = false; } @@ -168,11 +151,9 @@ get_gaming_features_data(const win_version_info &ver) return gaming_features; } -static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf, - DWORD size) +static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf, DWORD size) { - const LSTATUS status = - RegGetValueW(key, NULL, val, RRF_RT_REG_SZ, NULL, buf, &size); + const LSTATUS status = RegGetValueW(key, NULL, val, RRF_RT_REG_SZ, NULL, buf, &size); return status == ERROR_SUCCESS; } @@ -194,18 +175,15 @@ static inline void get_reg_ver(struct win_version_info *ver) size = sizeof(dw_val); - status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL, - (LPBYTE)&dw_val, &size); + status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size); if (status == ERROR_SUCCESS) ver->major = (int)dw_val; - status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL, - (LPBYTE)&dw_val, &size); + status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size); if (status == ERROR_SUCCESS) ver->minor = (int)dw_val; - status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val, - &size); + status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val, &size); if (status == ERROR_SUCCESS) ver->revis = (int)dw_val; @@ -213,8 +191,7 @@ static inline void get_reg_ver(struct win_version_info *ver) ver->build = wcstol(str, NULL, 10); } - const wchar_t *release_key = ver->build > 19041 ? L"DisplayVersion" - : L"ReleaseId"; + const wchar_t *release_key = ver->build > 19041 ? L"DisplayVersion" : L"ReleaseId"; if (get_reg_sz(key, release_key, str, sizeof(str))) { os_wcs_to_utf8(str, 0, win_release_id, MAX_SZ_LEN); } diff --git a/UI/ui-validation.cpp b/UI/ui-validation.cpp index 50f1d7d58..482951604 100644 --- a/UI/ui-validation.cpp +++ b/UI/ui-validation.cpp @@ -44,8 +44,7 @@ bool UIValidation::NoSourcesConfirmation(QWidget *parent) messageBox.setWindowTitle(QTStr("NoSources.Title")); messageBox.setText(msg); - QAbstractButton *yesButton = - messageBox.addButton(QTStr("Yes"), QMessageBox::YesRole); + QAbstractButton *yesButton = messageBox.addButton(QTStr("Yes"), QMessageBox::YesRole); messageBox.addButton(QTStr("No"), QMessageBox::NoRole); messageBox.setIcon(QMessageBox::Question); messageBox.exec(); @@ -56,8 +55,7 @@ bool UIValidation::NoSourcesConfirmation(QWidget *parent) return true; } -StreamSettingsAction -UIValidation::StreamSettingsConfirmation(QWidget *parent, OBSService service) +StreamSettingsAction UIValidation::StreamSettingsConfirmation(QWidget *parent, OBSService service) { if (obs_service_can_try_to_connect(service)) return StreamSettingsAction::ContinueStream; @@ -65,10 +63,8 @@ UIValidation::StreamSettingsConfirmation(QWidget *parent, OBSService service) char const *serviceType = obs_service_get_type(service); bool isCustomService = (strcmp(serviceType, "rtmp_custom") == 0); - char const *streamUrl = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); - char const *streamKey = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_STREAM_KEY); + char const *streamUrl = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); + char const *streamKey = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_STREAM_KEY); bool streamUrlMissing = !(streamUrl != NULL && streamUrl[0] != '\0'); bool streamKeyMissing = !(streamKey != NULL && streamKey[0] != '\0'); @@ -83,8 +79,7 @@ UIValidation::StreamSettingsConfirmation(QWidget *parent, OBSService service) } QMessageBox messageBox(parent); - messageBox.setWindowTitle( - QTStr("Basic.Settings.Stream.MissingSettingAlert")); + messageBox.setWindowTitle(QTStr("Basic.Settings.Stream.MissingSettingAlert")); messageBox.setText(msg); QPushButton *cancel; @@ -97,9 +92,7 @@ UIValidation::StreamSettingsConfirmation(QWidget *parent, OBSService service) #define ACCEPT_BUTTON QMessageBox::NoRole #define REJECT_BUTTON QMessageBox::NoRole #endif - settings = messageBox.addButton( - QTStr("Basic.Settings.Stream.StreamSettingsWarning"), - ACCEPT_BUTTON); + settings = messageBox.addButton(QTStr("Basic.Settings.Stream.StreamSettingsWarning"), ACCEPT_BUTTON); cancel = messageBox.addButton(QTStr("Cancel"), REJECT_BUTTON); messageBox.setDefaultButton(settings); diff --git a/UI/ui-validation.hpp b/UI/ui-validation.hpp index 5dbe14b63..505db851d 100644 --- a/UI/ui-validation.hpp +++ b/UI/ui-validation.hpp @@ -25,6 +25,5 @@ public: * basics is missing in stream, explain missing fields and offer to * open settings, cancel, or continue. Returns Continue if all * settings are valid. */ - static StreamSettingsAction - StreamSettingsConfirmation(QWidget *parent, OBSService service); + static StreamSettingsAction StreamSettingsConfirmation(QWidget *parent, OBSService service); }; diff --git a/UI/undo-stack-obs.cpp b/UI/undo-stack-obs.cpp index 293252a8b..163a1180d 100644 --- a/UI/undo-stack-obs.cpp +++ b/UI/undo-stack-obs.cpp @@ -6,8 +6,7 @@ undo_stack::undo_stack(ui_ptr ui) : ui(ui) { - QObject::connect(&repeat_reset_timer, &QTimer::timeout, this, - &undo_stack::reset_repeatable_state); + QObject::connect(&repeat_reset_timer, &QTimer::timeout, this, &undo_stack::reset_repeatable_state); repeat_reset_timer.setSingleShot(true); repeat_reset_timer.setInterval(3000); } @@ -30,10 +29,8 @@ void undo_stack::clear() ui->actionMainRedo->setDisabled(true); } -void undo_stack::add_action(const QString &name, const undo_redo_cb &undo, - const undo_redo_cb &redo, - const std::string &undo_data, - const std::string &redo_data, bool repeatable) +void undo_stack::add_action(const QString &name, const undo_redo_cb &undo, const undo_redo_cb &redo, + const std::string &undo_data, const std::string &redo_data, bool repeatable) { if (!is_enabled()) return; @@ -85,8 +82,7 @@ void undo_stack::undo() ui->actionMainUndo->setDisabled(true); ui->actionMainUndo->setText(QTStr("Undo.Undo")); } else { - ui->actionMainUndo->setText( - QTStr("Undo.Item.Undo").arg(undo_items.front().name)); + ui->actionMainUndo->setText(QTStr("Undo.Item.Undo").arg(undo_items.front().name)); } } @@ -109,8 +105,7 @@ void undo_stack::redo() ui->actionMainRedo->setDisabled(true); ui->actionMainRedo->setText(QTStr("Undo.Redo")); } else { - ui->actionMainRedo->setText( - QTStr("Undo.Item.Redo").arg(redo_items.front().name)); + ui->actionMainRedo->setText(QTStr("Undo.Item.Redo").arg(redo_items.front().name)); } } diff --git a/UI/undo-stack-obs.hpp b/UI/undo-stack-obs.hpp index 67067132e..050471279 100644 --- a/UI/undo-stack-obs.hpp +++ b/UI/undo-stack-obs.hpp @@ -53,9 +53,8 @@ public: void pop_disabled(); void clear(); - void add_action(const QString &name, const undo_redo_cb &undo, - const undo_redo_cb &redo, const std::string &undo_data, - const std::string &redo_data, bool repeatable = false); + void add_action(const QString &name, const undo_redo_cb &undo, const undo_redo_cb &redo, + const std::string &undo_data, const std::string &redo_data, bool repeatable = false); void undo(); void redo(); }; diff --git a/UI/update/crypto-helpers-mbedtls.cpp b/UI/update/crypto-helpers-mbedtls.cpp index 95088bdbd..f17c98764 100644 --- a/UI/update/crypto-helpers-mbedtls.cpp +++ b/UI/update/crypto-helpers-mbedtls.cpp @@ -3,9 +3,8 @@ #include "mbedtls/md.h" #include "mbedtls/pk.h" -bool VerifySignature(const uint8_t *pubKey, const size_t pubKeyLen, - const uint8_t *buf, const size_t len, const uint8_t *sig, - const size_t sigLen) +bool VerifySignature(const uint8_t *pubKey, const size_t pubKeyLen, const uint8_t *buf, const size_t len, + const uint8_t *sig, const size_t sigLen) { bool result = false; int ret = 1; @@ -15,18 +14,15 @@ bool VerifySignature(const uint8_t *pubKey, const size_t pubKeyLen, mbedtls_pk_init(&pk); // Parse PEM key - if ((ret = mbedtls_pk_parse_public_key(&pk, pubKey, pubKeyLen + 1)) != - 0) { + if ((ret = mbedtls_pk_parse_public_key(&pk, pubKey, pubKeyLen + 1)) != 0) { goto exit; } // Hash input buffer - if ((ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), buf, - len, hash)) != 0) { + if ((ret = mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), buf, len, hash)) != 0) { goto exit; } // Verify signautre - if ((ret = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA512, hash, 64, sig, - sigLen)) != 0) { + if ((ret = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA512, hash, 64, sig, sigLen)) != 0) { goto exit; } diff --git a/UI/update/crypto-helpers.hpp b/UI/update/crypto-helpers.hpp index ebf94f0d9..8fe9c594e 100644 --- a/UI/update/crypto-helpers.hpp +++ b/UI/update/crypto-helpers.hpp @@ -3,6 +3,5 @@ #include #include -bool VerifySignature(const uint8_t *pubKey, const size_t pubKeyLen, - const uint8_t *buf, const size_t len, const uint8_t *sig, - const size_t sigLen); +bool VerifySignature(const uint8_t *pubKey, const size_t pubKeyLen, const uint8_t *buf, const size_t len, + const uint8_t *sig, const size_t sigLen); diff --git a/UI/update/mac-update.cpp b/UI/update/mac-update.cpp index 6e8965c3c..33fca9430 100644 --- a/UI/update/mac-update.cpp +++ b/UI/update/mac-update.cpp @@ -10,16 +10,14 @@ /* ------------------------------------------------------------------------ */ -static const char *MAC_BRANCHES_URL = - "https://obsproject.com/update_studio/branches.json"; +static const char *MAC_BRANCHES_URL = "https://obsproject.com/update_studio/branches.json"; static const char *MAC_DEFAULT_BRANCH = "stable"; /* ------------------------------------------------------------------------ */ bool GetBranch(std::string &selectedBranch) { - const char *config_branch = config_get_string( - App()->GetAppConfig(), "General", "UpdateBranch"); + const char *config_branch = config_get_string(App()->GetAppConfig(), "General", "UpdateBranch"); if (!config_branch) return true; @@ -50,8 +48,8 @@ void MacUpdateThread::infoMsg(const QString &title, const QString &text) void MacUpdateThread::info(const QString &title, const QString &text) { - QMetaObject::invokeMethod(this, "infoMsg", Qt::BlockingQueuedConnection, - Q_ARG(QString, title), Q_ARG(QString, text)); + QMetaObject::invokeMethod(this, "infoMsg", Qt::BlockingQueuedConnection, Q_ARG(QString, title), + Q_ARG(QString, text)); } void MacUpdateThread::run() @@ -62,18 +60,15 @@ try { /* ----------------------------------- * * get branches from server */ - if (FetchAndVerifyFile("branches", "obs-studio/updates/branches.json", - MAC_BRANCHES_URL, &text)) + if (FetchAndVerifyFile("branches", "obs-studio/updates/branches.json", MAC_BRANCHES_URL, &text)) App()->SetBranchData(text); /* ----------------------------------- * * Validate branch selection */ if (!GetBranch(branch)) { - config_set_string(App()->GetAppConfig(), "General", - "UpdateBranch", MAC_DEFAULT_BRANCH); - info(QTStr("Updater.BranchNotFound.Title"), - QTStr("Updater.BranchNotFound.Text")); + config_set_string(App()->GetAppConfig(), "General", "UpdateBranch", MAC_DEFAULT_BRANCH); + info(QTStr("Updater.BranchNotFound.Title"), QTStr("Updater.BranchNotFound.Text")); } emit Result(QString::fromStdString(branch), manualUpdate); diff --git a/UI/update/models/branches.hpp b/UI/update/models/branches.hpp index eab488ab6..f2cb89c56 100644 --- a/UI/update/models/branches.hpp +++ b/UI/update/models/branches.hpp @@ -34,10 +34,8 @@ struct JsonBranch { bool windows = false; bool macos = false; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(JsonBranch, name, - display_name, description, - enabled, visible, windows, - macos) + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(JsonBranch, name, display_name, description, enabled, visible, + windows, macos) }; using JsonBranches = std::vector; diff --git a/UI/update/models/whatsnew.hpp b/UI/update/models/whatsnew.hpp index 399bfa784..df3a5fb96 100644 --- a/UI/update/models/whatsnew.hpp +++ b/UI/update/models/whatsnew.hpp @@ -28,8 +28,7 @@ template struct nlohmann::adl_serializer> { static std::optional from_json(const json &json) { - return json.is_null() ? std::nullopt - : std::optional{json.get()}; + return json.is_null() ? std::nullopt : std::optional{json.get()}; } static void to_json(json &json, std::optional t) @@ -46,8 +45,7 @@ struct WhatsNewPlatforms { bool macos = false; bool linux = false; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(WhatsNewPlatforms, windows, - macos, linux) + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(WhatsNewPlatforms, windows, macos, linux) }; struct WhatsNewItem { @@ -63,8 +61,7 @@ struct WhatsNewItem { /* Optional OS filter */ std::optional os = std::nullopt; - NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(WhatsNewItem, version, Beta, - RC, url, increment, os) + NLOHMANN_DEFINE_TYPE_INTRUSIVE_WITH_DEFAULT(WhatsNewItem, version, Beta, RC, url, increment, os) }; using WhatsNewList = std::vector; diff --git a/UI/update/shared-update.cpp b/UI/update/shared-update.cpp index cc70406b8..0aedd8d95 100644 --- a/UI/update/shared-update.cpp +++ b/UI/update/shared-update.cpp @@ -50,16 +50,13 @@ extern QCef *cef; static bool QuickWriteFile(const char *file, const std::string &data) try { - std::ofstream fileStream(std::filesystem::u8path(file), - std::ios::binary); + std::ofstream fileStream(std::filesystem::u8path(file), std::ios::binary); if (fileStream.fail()) - throw strprintf("Failed to open file '%s': %s", file, - strerror(errno)); + throw strprintf("Failed to open file '%s': %s", file, strerror(errno)); fileStream.write(data.data(), data.size()); if (fileStream.fail()) - throw strprintf("Failed to write file '%s': %s", file, - strerror(errno)); + throw strprintf("Failed to write file '%s': %s", file, strerror(errno)); return true; @@ -70,11 +67,9 @@ try { static bool QuickReadFile(const char *file, std::string &data) try { - std::ifstream fileStream(std::filesystem::u8path(file), - std::ios::binary); + std::ifstream fileStream(std::filesystem::u8path(file), std::ios::binary); if (!fileStream.is_open() || fileStream.fail()) - throw strprintf("Failed to open file '%s': %s", file, - strerror(errno)); + throw strprintf("Failed to open file '%s': %s", file, strerror(errno)); fileStream.seekg(0, fileStream.end); size_t size = fileStream.tellg(); @@ -84,8 +79,7 @@ try { fileStream.read(&data[0], size); if (fileStream.fail()) - throw strprintf("Failed to write file '%s': %s", file, - strerror(errno)); + throw strprintf("Failed to write file '%s': %s", file, strerror(errno)); return true; @@ -147,8 +141,7 @@ std::string GetProgramGUID() /* NOTE: this is an arbitrary random number that we use to count the * number of unique OBS installations and is not associated with any * kind of identifiable information */ - const char *pguid = config_get_string(App()->GetAppConfig(), "General", - "InstallGUID"); + const char *pguid = config_get_string(App()->GetAppConfig(), "General", "InstallGUID"); std::string guid; if (pguid) guid = pguid; @@ -157,8 +150,7 @@ std::string GetProgramGUID() GenerateGUID(guid); if (!guid.empty()) - config_set_string(App()->GetAppConfig(), "General", - "InstallGUID", guid.c_str()); + config_set_string(App()->GetAppConfig(), "General", "InstallGUID", guid.c_str()); } return guid; @@ -176,16 +168,13 @@ static void LoadPublicKey(std::string &pubkey) throw std::string("Could not read OBS public key file!"); } -static bool CheckDataSignature(const char *name, const std::string &data, - const std::string &hexSig) +static bool CheckDataSignature(const char *name, const std::string &data, const std::string &hexSig) try { static std::mutex pubkey_mutex; static std::string obsPubKey; - if (hexSig.empty() || hexSig.length() > 0xFFFF || - (hexSig.length() & 1) != 0) - throw strprintf("Missing or invalid signature for %s: %s", name, - hexSig.c_str()); + if (hexSig.empty() || hexSig.length() > 0xFFFF || (hexSig.length() & 1) != 0) + throw strprintf("Missing or invalid signature for %s: %s", name, hexSig.c_str()); std::scoped_lock lock(pubkey_mutex); if (obsPubKey.empty()) @@ -194,8 +183,7 @@ try { // Convert hex string to bytes auto signature = QByteArray::fromHex(hexSig.data()); - if (!VerifySignature((uint8_t *)obsPubKey.data(), obsPubKey.size(), - (uint8_t *)data.data(), data.size(), + if (!VerifySignature((uint8_t *)obsPubKey.data(), obsPubKey.size(), (uint8_t *)data.data(), data.size(), (uint8_t *)signature.data(), signature.size())) throw strprintf("Signature check failed for %s", name); @@ -208,8 +196,7 @@ try { /* ------------------------------------------------------------------------ */ -bool FetchAndVerifyFile(const char *name, const char *file, const char *url, - std::string *out, +bool FetchAndVerifyFile(const char *name, const char *file, const char *url, std::string *out, const std::vector &extraHeaders) { long responseCode; @@ -223,16 +210,14 @@ bool FetchAndVerifyFile(const char *name, const char *file, const char *url, BPtr filePath = GetAppConfigPathPtr(file); if (!extraHeaders.empty()) { - headers.insert(headers.end(), extraHeaders.begin(), - extraHeaders.end()); + headers.insert(headers.end(), extraHeaders.begin(), extraHeaders.end()); } /* ----------------------------------- * * avoid downloading file again */ if (CalculateFileHash(filePath, fileHash)) { - auto hash = QByteArray::fromRawData((const char *)fileHash, - BLAKE2_HASH_LENGTH); + auto hash = QByteArray::fromRawData((const char *)fileHash, BLAKE2_HASH_LENGTH); QString header = "If-None-Match: " + hash.toHex(); headers.push_back(header.toStdString()); @@ -251,15 +236,13 @@ bool FetchAndVerifyFile(const char *name, const char *file, const char *url, /* ----------------------------------- * * get file from server */ - success = GetRemoteFile(url, data, error, &responseCode, nullptr, "", - nullptr, headers, &signature); + success = GetRemoteFile(url, data, error, &responseCode, nullptr, "", nullptr, headers, &signature); if (!success || (responseCode != 200 && responseCode != 304)) { if (responseCode == 404) return false; - throw strprintf("Failed to fetch %s file: %s", name, - error.c_str()); + throw strprintf("Failed to fetch %s file: %s", name, error.c_str()); } /* ----------------------------------- * @@ -276,12 +259,10 @@ bool FetchAndVerifyFile(const char *name, const char *file, const char *url, if (responseCode == 200) { if (!QuickWriteFile(filePath, data)) - throw strprintf("Could not write file '%s'", - filePath.Get()); + throw strprintf("Could not write file '%s'", filePath.Get()); } else if (out) { /* Only read file if caller wants data */ if (!QuickReadFile(filePath, data)) - throw strprintf("Could not read file '%s'", - filePath.Get()); + throw strprintf("Could not read file '%s'", filePath.Get()); } if (out) @@ -296,8 +277,7 @@ void WhatsNewInfoThread::run() try { std::string text; - if (FetchAndVerifyFile("whatsnew", "obs-studio/updates/whatsnew.json", - WHATSNEW_URL, &text)) { + if (FetchAndVerifyFile("whatsnew", "obs-studio/updates/whatsnew.json", WHATSNEW_URL, &text)) { emit Result(QString::fromStdString(text)); } } catch (std::string &text) { diff --git a/UI/update/shared-update.hpp b/UI/update/shared-update.hpp index b1522947c..c33b8823d 100644 --- a/UI/update/shared-update.hpp +++ b/UI/update/shared-update.hpp @@ -6,10 +6,8 @@ #include #include -bool FetchAndVerifyFile(const char *name, const char *file, const char *url, - std::string *out, - const std::vector &extraHeaders = - std::vector()); +bool FetchAndVerifyFile(const char *name, const char *file, const char *url, std::string *out, + const std::vector &extraHeaders = std::vector()); class WhatsNewInfoThread : public QThread { Q_OBJECT diff --git a/UI/update/update-window.cpp b/UI/update/update-window.cpp index 5a868bcf1..777eb7878 100644 --- a/UI/update/update-window.cpp +++ b/UI/update/update-window.cpp @@ -2,8 +2,7 @@ #include "obs-app.hpp" OBSUpdate::OBSUpdate(QWidget *parent, bool manualUpdate, const QString &text) - : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | - Qt::WindowCloseButtonHint), + : QDialog(parent, Qt::WindowSystemMenuHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint), ui(new Ui_OBSUpdate) { ui->setupUi(this); diff --git a/UI/update/win-update.cpp b/UI/update/win-update.cpp index b0f197462..73ef8e696 100644 --- a/UI/update/win-update.cpp +++ b/UI/update/win-update.cpp @@ -50,32 +50,26 @@ using namespace updater; /* ------------------------------------------------------------------------ */ -static bool ParseUpdateManifest(const char *manifest_data, - bool *updatesAvailable, string ¬es, - string &updateVer, const string &branch) +static bool ParseUpdateManifest(const char *manifest_data, bool *updatesAvailable, string ¬es, string &updateVer, + const string &branch) try { - constexpr uint64_t currentVersion = (uint64_t)LIBOBS_API_VER << 16ULL | - OBS_RELEASE_CANDIDATE << 8ULL | + constexpr uint64_t currentVersion = (uint64_t)LIBOBS_API_VER << 16ULL | OBS_RELEASE_CANDIDATE << 8ULL | OBS_BETA; - constexpr bool isPreRelease = - currentVersion & 0xffff || - std::char_traits::length(OBS_COMMIT); + constexpr bool isPreRelease = currentVersion & 0xffff || std::char_traits::length(OBS_COMMIT); json manifestContents = json::parse(manifest_data); Manifest manifest = manifestContents.get(); if (manifest.version_major == 0 && manifest.commit.empty()) - throw strprintf("Invalid version number: %d.%d.%d", - manifest.version_major, manifest.version_minor, + throw strprintf("Invalid version number: %d.%d.%d", manifest.version_major, manifest.version_minor, manifest.version_patch); notes = manifest.notes; if (manifest.commit.empty()) { - uint64_t new_ver = - MAKE_SEMANTIC_VERSION((uint64_t)manifest.version_major, - (uint64_t)manifest.version_minor, - (uint64_t)manifest.version_patch); + uint64_t new_ver = MAKE_SEMANTIC_VERSION((uint64_t)manifest.version_major, + (uint64_t)manifest.version_minor, + (uint64_t)manifest.version_patch); new_ver <<= 16; /* RC builds are shifted so that rc1 and beta1 versions do not result * in the same new_ver. */ @@ -96,9 +90,7 @@ try { /* Test or nightly builds may not have a (valid) version number, * so compare commit hashes instead. */ updateVer = manifest.commit.substr(0, 8); - *updatesAvailable = !currentVersion || - !manifest.commit.compare( - 0, strlen(OBS_COMMIT), OBS_COMMIT); + *updatesAvailable = !currentVersion || !manifest.commit.compare(0, strlen(OBS_COMMIT), OBS_COMMIT); } return true; @@ -112,8 +104,7 @@ try { bool GetBranchAndUrl(string &selectedBranch, string &manifestUrl) { - const char *config_branch = config_get_string( - App()->GetAppConfig(), "General", "UpdateBranch"); + const char *config_branch = config_get_string(App()->GetAppConfig(), "General", "UpdateBranch"); if (!config_branch) return true; @@ -130,9 +121,7 @@ bool GetBranchAndUrl(string &selectedBranch, string &manifestUrl) selectedBranch = branch.name.toStdString(); if (branch.name != WIN_DEFAULT_BRANCH) { manifestUrl = WIN_MANIFEST_BASE_URL; - manifestUrl += "manifest_" + - branch.name.toStdString() + - ".json"; + manifestUrl += "manifest_" + branch.name.toStdString() + ".json"; } } break; @@ -150,12 +139,11 @@ void AutoUpdateThread::infoMsg(const QString &title, const QString &text) void AutoUpdateThread::info(const QString &title, const QString &text) { - QMetaObject::invokeMethod(this, "infoMsg", Qt::BlockingQueuedConnection, - Q_ARG(QString, title), Q_ARG(QString, text)); + QMetaObject::invokeMethod(this, "infoMsg", Qt::BlockingQueuedConnection, Q_ARG(QString, title), + Q_ARG(QString, text)); } -int AutoUpdateThread::queryUpdateSlot(bool localManualUpdate, - const QString &text) +int AutoUpdateThread::queryUpdateSlot(bool localManualUpdate, const QString &text) { OBSUpdate updateDlg(App()->GetMainWindow(), localManualUpdate, text); return updateDlg.exec(); @@ -165,20 +153,16 @@ int AutoUpdateThread::queryUpdate(bool localManualUpdate, const char *text_utf8) { int ret = OBSUpdate::No; QString text = text_utf8; - QMetaObject::invokeMethod(this, "queryUpdateSlot", - Qt::BlockingQueuedConnection, - Q_RETURN_ARG(int, ret), - Q_ARG(bool, localManualUpdate), - Q_ARG(QString, text)); + QMetaObject::invokeMethod(this, "queryUpdateSlot", Qt::BlockingQueuedConnection, Q_RETURN_ARG(int, ret), + Q_ARG(bool, localManualUpdate), Q_ARG(QString, text)); return ret; } bool AutoUpdateThread::queryRepairSlot() { - QMessageBox::StandardButton res = OBSMessageBox::question( - App()->GetMainWindow(), QTStr("Updater.RepairConfirm.Title"), - QTStr("Updater.RepairConfirm.Text"), - QMessageBox::Yes | QMessageBox::Cancel); + QMessageBox::StandardButton res = + OBSMessageBox::question(App()->GetMainWindow(), QTStr("Updater.RepairConfirm.Title"), + QTStr("Updater.RepairConfirm.Text"), QMessageBox::Yes | QMessageBox::Cancel); return res == QMessageBox::Yes; } @@ -186,9 +170,7 @@ bool AutoUpdateThread::queryRepairSlot() bool AutoUpdateThread::queryRepair() { bool ret = false; - QMetaObject::invokeMethod(this, "queryRepairSlot", - Qt::BlockingQueuedConnection, - Q_RETURN_ARG(bool, ret)); + QMetaObject::invokeMethod(this, "queryRepairSlot", Qt::BlockingQueuedConnection, Q_RETURN_ARG(bool, ret)); return ret; } @@ -201,28 +183,21 @@ try { bool updatesAvailable = false; struct FinishedTrigger { - inline ~FinishedTrigger() - { - QMetaObject::invokeMethod(App()->GetMainWindow(), - "updateCheckFinished"); - } + inline ~FinishedTrigger() { QMetaObject::invokeMethod(App()->GetMainWindow(), "updateCheckFinished"); } } finishedTrigger; /* ----------------------------------- * * get branches from server */ - if (FetchAndVerifyFile("branches", "obs-studio\\updates\\branches.json", - WIN_BRANCHES_URL, &text)) + if (FetchAndVerifyFile("branches", "obs-studio\\updates\\branches.json", WIN_BRANCHES_URL, &text)) App()->SetBranchData(text); /* ----------------------------------- * * check branch and get manifest url */ if (!GetBranchAndUrl(branch, manifestUrl)) { - config_set_string(App()->GetAppConfig(), "General", - "UpdateBranch", WIN_DEFAULT_BRANCH); - info(QTStr("Updater.BranchNotFound.Title"), - QTStr("Updater.BranchNotFound.Text")); + config_set_string(App()->GetAppConfig(), "General", "UpdateBranch", WIN_DEFAULT_BRANCH); + info(QTStr("Updater.BranchNotFound.Title"), QTStr("Updater.BranchNotFound.Text")); } /* allow server to know if this was a manual update check in case @@ -234,9 +209,8 @@ try { * get manifest from server */ text.clear(); - if (!FetchAndVerifyFile("manifest", - "obs-studio\\updates\\manifest.json", - manifestUrl.c_str(), &text, extraHeaders)) + if (!FetchAndVerifyFile("manifest", "obs-studio\\updates\\manifest.json", manifestUrl.c_str(), &text, + extraHeaders)) return; /* ----------------------------------- * @@ -245,35 +219,29 @@ try { string notes; string updateVer; - if (!ParseUpdateManifest(text.c_str(), &updatesAvailable, notes, - updateVer, branch)) + if (!ParseUpdateManifest(text.c_str(), &updatesAvailable, notes, updateVer, branch)) throw string("Failed to parse manifest"); if (!updatesAvailable && !repairMode) { if (manualUpdate) - info(QTStr("Updater.NoUpdatesAvailable.Title"), - QTStr("Updater.NoUpdatesAvailable.Text")); + info(QTStr("Updater.NoUpdatesAvailable.Title"), QTStr("Updater.NoUpdatesAvailable.Text")); return; } else if (updatesAvailable && repairMode) { - info(QTStr("Updater.RepairButUpdatesAvailable.Title"), - QTStr("Updater.RepairButUpdatesAvailable.Text")); + info(QTStr("Updater.RepairButUpdatesAvailable.Title"), QTStr("Updater.RepairButUpdatesAvailable.Text")); return; } /* ----------------------------------- * * skip this version if set to skip */ - const char *skipUpdateVer = config_get_string( - App()->GetAppConfig(), "General", "SkipUpdateVersion"); - if (!manualUpdate && !repairMode && skipUpdateVer && - updateVer == skipUpdateVer) + const char *skipUpdateVer = config_get_string(App()->GetAppConfig(), "General", "SkipUpdateVersion"); + if (!manualUpdate && !repairMode && skipUpdateVer && updateVer == skipUpdateVer) return; /* ----------------------------------- * * fetch updater module */ - if (!FetchAndVerifyFile("updater", "obs-studio\\updates\\updater.exe", - WIN_UPDATER_URL, nullptr)) + if (!FetchAndVerifyFile("updater", "obs-studio\\updates\\updater.exe", WIN_UPDATER_URL, nullptr)) return; /* ----------------------------------- * @@ -288,15 +256,12 @@ try { if (queryResult == OBSUpdate::No) { if (!manualUpdate) { long long t = (long long)time(nullptr); - config_set_int(App()->GetAppConfig(), "General", - "LastUpdateCheck", t); + config_set_int(App()->GetAppConfig(), "General", "LastUpdateCheck", t); } return; } else if (queryResult == OBSUpdate::Skip) { - config_set_string(App()->GetAppConfig(), "General", - "SkipUpdateVersion", - updateVer.c_str()); + config_set_string(App()->GetAppConfig(), "General", "SkipUpdateVersion", updateVer.c_str()); return; } } @@ -313,8 +278,7 @@ try { /* ----------------------------------- * * execute updater */ - BPtr updateFilePath = - GetAppConfigPathPtr("obs-studio\\updates\\updater.exe"); + BPtr updateFilePath = GetAppConfigPathPtr("obs-studio\\updates\\updater.exe"); BPtr wUpdateFilePath; size_t size = os_utf8_to_wcs_ptr(updateFilePath, 0, &wUpdateFilePath); @@ -341,8 +305,7 @@ try { /* Portable mode can be enabled via sentinel files, so copying the * command line doesn't guarantee the flag to be there. */ - if (App()->IsPortableMode() && - parameters.find("--portable") == string::npos) { + if (App()->IsPortableMode() && parameters.find("--portable") == string::npos) { if (!parameters.empty()) parameters += " "; parameters += "--portable"; @@ -360,15 +323,13 @@ try { if (!ShellExecuteEx(&execInfo)) { QString msg = QTStr("Updater.FailedToLaunch"); info(msg, msg); - throw strprintf("Can't launch updater '%s': %d", - updateFilePath.Get(), GetLastError()); + throw strprintf("Can't launch updater '%s': %d", updateFilePath.Get(), GetLastError()); } /* force OBS to perform another update check immediately after updating * in case of issues with the new version */ config_set_int(App()->GetAppConfig(), "General", "LastUpdateCheck", 0); - config_set_string(App()->GetAppConfig(), "General", "SkipUpdateVersion", - "0"); + config_set_string(App()->GetAppConfig(), "General", "SkipUpdateVersion", "0"); QMetaObject::invokeMethod(App()->GetMainWindow(), "close"); diff --git a/UI/visibility-item-widget.cpp b/UI/visibility-item-widget.cpp index dcf4c57b1..50ea425ad 100644 --- a/UI/visibility-item-widget.cpp +++ b/UI/visibility-item-widget.cpp @@ -13,8 +13,7 @@ VisibilityItemWidget::VisibilityItemWidget(obs_source_t *source_) : source(source_), - enabledSignal(obs_source_get_signal_handler(source), "enable", - OBSSourceEnabled, this) + enabledSignal(obs_source_get_signal_handler(source), "enable", OBSSourceEnabled, this) { bool enabled = obs_source_enabled(source); @@ -33,19 +32,15 @@ VisibilityItemWidget::VisibilityItemWidget(obs_source_t *source_) setLayout(itemLayout); - connect(vis, &QCheckBox::clicked, [this](bool visible) { - obs_source_set_enabled(source, visible); - }); + connect(vis, &QCheckBox::clicked, [this](bool visible) { obs_source_set_enabled(source, visible); }); } void VisibilityItemWidget::OBSSourceEnabled(void *param, calldata_t *data) { - VisibilityItemWidget *window = - reinterpret_cast(param); + VisibilityItemWidget *window = reinterpret_cast(param); bool enabled = calldata_bool(data, "enabled"); - QMetaObject::invokeMethod(window, "SourceEnabled", - Q_ARG(bool, enabled)); + QMetaObject::invokeMethod(window, "SourceEnabled", Q_ARG(bool, enabled)); } void VisibilityItemWidget::SourceEnabled(bool enabled) @@ -54,8 +49,7 @@ void VisibilityItemWidget::SourceEnabled(bool enabled) vis->setChecked(enabled); } -void VisibilityItemWidget::SetColor(const QColor &color, bool active_, - bool selected_) +void VisibilityItemWidget::SetColor(const QColor &color, bool active_, bool selected_) { /* Do not update unless the state has actually changed */ if (active_ == active && selected_ == selected) @@ -71,13 +65,9 @@ void VisibilityItemWidget::SetColor(const QColor &color, bool active_, selected = selected_; } -VisibilityItemDelegate::VisibilityItemDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} +VisibilityItemDelegate::VisibilityItemDelegate(QObject *parent) : QStyledItemDelegate(parent) {} -void VisibilityItemDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, +void VisibilityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyledItemDelegate::paint(painter, option, index); @@ -88,8 +78,7 @@ void VisibilityItemDelegate::paint(QPainter *painter, return; QListWidgetItem *item = list->item(index.row()); - VisibilityItemWidget *widget = - qobject_cast(list->itemWidget(item)); + VisibilityItemWidget *widget = qobject_cast(list->itemWidget(item)); if (!widget) return; @@ -98,8 +87,7 @@ void VisibilityItemDelegate::paint(QPainter *painter, QPalette palette = list->palette(); #if defined(_WIN32) || defined(__APPLE__) - QPalette::ColorGroup group = active ? QPalette::Active - : QPalette::Inactive; + QPalette::ColorGroup group = active ? QPalette::Active : QPalette::Inactive; #else QPalette::ColorGroup group = QPalette::Active; #endif @@ -129,8 +117,7 @@ bool VisibilityItemDelegate::eventFilter(QObject *object, QEvent *event) if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); - if (keyEvent->key() == Qt::Key_Tab || - keyEvent->key() == Qt::Key_Backtab) { + if (keyEvent->key() == Qt::Key_Tab || keyEvent->key() == Qt::Key_Backtab) { return false; } } @@ -138,8 +125,7 @@ bool VisibilityItemDelegate::eventFilter(QObject *object, QEvent *event) return QStyledItemDelegate::eventFilter(object, event); } -void SetupVisibilityItem(QListWidget *list, QListWidgetItem *item, - obs_source_t *source) +void SetupVisibilityItem(QListWidget *list, QListWidgetItem *item, obs_source_t *source) { VisibilityItemWidget *baseWidget = new VisibilityItemWidget(source); diff --git a/UI/visibility-item-widget.hpp b/UI/visibility-item-widget.hpp index 8fbcb45f3..ec6b35e37 100644 --- a/UI/visibility-item-widget.hpp +++ b/UI/visibility-item-widget.hpp @@ -41,12 +41,10 @@ class VisibilityItemDelegate : public QStyledItemDelegate { public: VisibilityItemDelegate(QObject *parent = nullptr); - void paint(QPainter *painter, const QStyleOptionViewItem &option, - const QModelIndex &index) const override; + void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; protected: bool eventFilter(QObject *object, QEvent *event) override; }; -void SetupVisibilityItem(QListWidget *list, QListWidgetItem *item, - obs_source_t *source); +void SetupVisibilityItem(QListWidget *list, QListWidgetItem *item, obs_source_t *source); diff --git a/UI/volume-control.cpp b/UI/volume-control.cpp index 66818e1ad..cd00c14d7 100644 --- a/UI/volume-control.cpp +++ b/UI/volume-control.cpp @@ -37,8 +37,7 @@ static inline Qt::CheckState GetCheckState(bool muted, bool unassigned) static inline bool IsSourceUnassigned(obs_source_t *source) { - uint32_t mixes = (obs_source_get_audio_mixers(source) & - ((1 << MAX_AUDIO_MIXES) - 1)); + uint32_t mixes = (obs_source_get_audio_mixers(source) & ((1 << MAX_AUDIO_MIXES) - 1)); obs_monitoring_type mt = obs_source_get_monitoring_type(source); return mixes == 0 && mt != OBS_MONITORING_TYPE_MONITOR_ONLY; @@ -48,10 +47,8 @@ static void ShowUnassignedWarning(const char *name) { auto msgBox = [=]() { QMessageBox msgbox(App()->GetMainWindow()); - msgbox.setWindowTitle( - QTStr("VolControl.UnassignedWarning.Title")); - msgbox.setText( - QTStr("VolControl.UnassignedWarning.Text").arg(name)); + msgbox.setWindowTitle(QTStr("VolControl.UnassignedWarning.Title")); + msgbox.setText(QTStr("VolControl.UnassignedWarning.Text").arg(name)); msgbox.setIcon(QMessageBox::Icon::Information); msgbox.addButton(QMessageBox::Ok); @@ -61,15 +58,12 @@ static void ShowUnassignedWarning(const char *name) msgbox.exec(); if (cb->isChecked()) { - config_set_bool(App()->GetUserConfig(), "General", - "WarnedAboutUnassignedSources", true); - config_save_safe(App()->GetUserConfig(), "tmp", - nullptr); + config_set_bool(App()->GetUserConfig(), "General", "WarnedAboutUnassignedSources", true); + config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } }; - QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, - Q_ARG(VoidFunc, msgBox)); + QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, Q_ARG(VoidFunc, msgBox)); } void VolControl::OBSVolumeChanged(void *data, float db) @@ -80,10 +74,8 @@ void VolControl::OBSVolumeChanged(void *data, float db) QMetaObject::invokeMethod(volControl, "VolumeChanged"); } -void VolControl::OBSVolumeLevel(void *data, - const float magnitude[MAX_AUDIO_CHANNELS], - const float peak[MAX_AUDIO_CHANNELS], - const float inputPeak[MAX_AUDIO_CHANNELS]) +void VolControl::OBSVolumeLevel(void *data, const float magnitude[MAX_AUDIO_CHANNELS], + const float peak[MAX_AUDIO_CHANNELS], const float inputPeak[MAX_AUDIO_CHANNELS]) { VolControl *volControl = static_cast(data); @@ -95,15 +87,13 @@ void VolControl::OBSVolumeMuted(void *data, calldata_t *calldata) VolControl *volControl = static_cast(data); bool muted = calldata_bool(calldata, "muted"); - QMetaObject::invokeMethod(volControl, "VolumeMuted", - Q_ARG(bool, muted)); + QMetaObject::invokeMethod(volControl, "VolumeMuted", Q_ARG(bool, muted)); } void VolControl::VolumeChanged() { slider->blockSignals(true); - slider->setValue( - (int)(obs_fader_get_deflection(obs_fader) * FADER_PRECISION)); + slider->setValue((int)(obs_fader_get_deflection(obs_fader) * FADER_PRECISION)); slider->blockSignals(false); updateText(); @@ -124,8 +114,7 @@ void VolControl::OBSMixersOrMonitoringChanged(void *data, calldata_t *) { VolControl *volControl = static_cast(data); - QMetaObject::invokeMethod(volControl, "MixersOrMonitoringChanged", - Qt::QueuedConnection); + QMetaObject::invokeMethod(volControl, "MixersOrMonitoringChanged", Qt::QueuedConnection); } void VolControl::MixersOrMonitoringChanged() @@ -151,28 +140,22 @@ void VolControl::SetMuted(bool) mute->setCheckState(Qt::PartiallyChecked); /* Show notice about the source no being assigned to any tracks */ bool has_shown_warning = - config_get_bool(App()->GetUserConfig(), "General", - "WarnedAboutUnassignedSources"); + config_get_bool(App()->GetUserConfig(), "General", "WarnedAboutUnassignedSources"); if (!has_shown_warning) ShowUnassignedWarning(obs_source_get_name(source)); } auto undo_redo = [](const std::string &uuid, bool val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_muted(source, val); }; - QString text = - QTStr(checked ? "Undo.Volume.Mute" : "Undo.Volume.Unmute"); + QString text = QTStr(checked ? "Undo.Volume.Mute" : "Undo.Volume.Unmute"); const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - text.arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, checked), uuid, - uuid); + OBSBasic::Get()->undo_s.add_action(text.arg(name), std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, checked), uuid, uuid); } void VolControl::SliderChanged(int vol) @@ -183,19 +166,16 @@ void VolControl::SliderChanged(int vol) updateText(); auto undo_redo = [](const std::string &uuid, float val) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_volume(source, val); }; float val = obs_source_get_volume(source); const char *name = obs_source_get_name(source); const char *uuid = obs_source_get_uuid(source); - OBSBasic::Get()->undo_s.add_action( - QTStr("Undo.Volume.Change").arg(name), - std::bind(undo_redo, std::placeholders::_1, prev), - std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, - true); + OBSBasic::Get()->undo_s.add_action(QTStr("Undo.Volume.Change").arg(name), + std::bind(undo_redo, std::placeholders::_1, prev), + std::bind(undo_redo, std::placeholders::_1, val), uuid, uuid, true); } void VolControl::updateText() @@ -211,8 +191,7 @@ void VolControl::updateText() volLabel->setText(text); bool muted = obs_source_muted(source); - const char *accTextLookup = muted ? "VolControl.SliderMuted" - : "VolControl.SliderUnmuted"; + const char *accTextLookup = muted ? "VolControl.SliderMuted" : "VolControl.SliderUnmuted"; QString sourceName = obs_source_get_name(source); QString accText = QTStr(accTextLookup).arg(sourceName); @@ -265,11 +244,9 @@ VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical) config->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed); - config->setAccessibleName( - QTStr("VolControl.Properties").arg(sourceName)); + config->setAccessibleName(QTStr("VolControl.Properties").arg(sourceName)); - connect(config, &QAbstractButton::clicked, this, - &VolControl::EmitConfigClicked); + connect(config, &QAbstractButton::clicked, this, &VolControl::EmitConfigClicked); } QVBoxLayout *mainLayout = new QVBoxLayout; @@ -319,9 +296,7 @@ VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical) volLayout->setContentsMargins(0, 0, 0, 0); volLayout->setSpacing(0); volLayout->addWidget(volLabel); - volLayout->addItem( - new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, - QSizePolicy::Minimum)); + volLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::MinimumExpanding, QSizePolicy::Minimum)); mainLayout->addItem(nameLayout); mainLayout->addItem(volLayout); @@ -344,8 +319,7 @@ VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical) QVBoxLayout *buttonLayout = new QVBoxLayout; volMeter = new VolumeMeter(nullptr, obs_volmeter, false); - volMeter->setSizePolicy(QSizePolicy::MinimumExpanding, - QSizePolicy::Preferred); + volMeter->setSizePolicy(QSizePolicy::MinimumExpanding, QSizePolicy::Preferred); slider = new VolumeSlider(obs_fader, Qt::Horizontal); slider->setLayoutDirection(Qt::LeftToRight); @@ -372,9 +346,7 @@ VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical) if (showConfig) { buttonLayout->addWidget(config); } - buttonLayout->addItem( - new QSpacerItem(0, 0, QSizePolicy::Minimum, - QSizePolicy::MinimumExpanding)); + buttonLayout->addItem(new QSpacerItem(0, 0, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding)); buttonLayout->addWidget(mute); controlLayout->addItem(buttonLayout); @@ -401,18 +373,13 @@ VolControl::VolControl(OBSSource source_, bool showConfig, bool vertical) obs_fader_add_callback(obs_fader, OBSVolumeChanged, this); obs_volmeter_add_callback(obs_volmeter, OBSVolumeLevel, this); - sigs.emplace_back(obs_source_get_signal_handler(source), "mute", - OBSVolumeMuted, this); - sigs.emplace_back(obs_source_get_signal_handler(source), "audio_mixers", - OBSMixersOrMonitoringChanged, this); - sigs.emplace_back(obs_source_get_signal_handler(source), - "audio_monitoring", OBSMixersOrMonitoringChanged, + sigs.emplace_back(obs_source_get_signal_handler(source), "mute", OBSVolumeMuted, this); + sigs.emplace_back(obs_source_get_signal_handler(source), "audio_mixers", OBSMixersOrMonitoringChanged, this); + sigs.emplace_back(obs_source_get_signal_handler(source), "audio_monitoring", OBSMixersOrMonitoringChanged, this); - QWidget::connect(slider, &VolumeSlider::valueChanged, this, - &VolControl::SliderChanged); - QWidget::connect(mute, &MuteCheckBox::clicked, this, - &VolControl::SetMuted); + QWidget::connect(slider, &VolumeSlider::valueChanged, this, &VolControl::SliderChanged); + QWidget::connect(mute, &MuteCheckBox::clicked, this, &VolControl::SetMuted); obs_fader_attach_source(obs_fader, source); obs_volmeter_attach_source(obs_volmeter, source); @@ -439,8 +406,7 @@ VolControl::~VolControl() static inline QColor color_from_int(long long val) { - QColor color(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, - (val >> 24) & 0xff); + QColor color(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff); color.setAlpha(255); return color; @@ -460,10 +426,9 @@ void VolumeMeter::setBackgroundNominalColor(QColor c) { p_backgroundNominalColor = std::move(c); - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - backgroundNominalColor = color_from_int(config_get_int( - App()->GetUserConfig(), "Accessibility", "MixerGreen")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + backgroundNominalColor = + color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerGreen")); } else { backgroundNominalColor = p_backgroundNominalColor; } @@ -488,11 +453,9 @@ void VolumeMeter::setBackgroundWarningColor(QColor c) { p_backgroundWarningColor = std::move(c); - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - backgroundWarningColor = color_from_int( - config_get_int(App()->GetUserConfig(), "Accessibility", - "MixerYellow")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + backgroundWarningColor = + color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerYellow")); } else { backgroundWarningColor = p_backgroundWarningColor; } @@ -517,10 +480,9 @@ void VolumeMeter::setBackgroundErrorColor(QColor c) { p_backgroundErrorColor = std::move(c); - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - backgroundErrorColor = color_from_int(config_get_int( - App()->GetUserConfig(), "Accessibility", "MixerRed")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + backgroundErrorColor = + color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerRed")); } else { backgroundErrorColor = p_backgroundErrorColor; } @@ -545,11 +507,9 @@ void VolumeMeter::setForegroundNominalColor(QColor c) { p_foregroundNominalColor = std::move(c); - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - foregroundNominalColor = color_from_int( - config_get_int(App()->GetUserConfig(), "Accessibility", - "MixerGreenActive")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + foregroundNominalColor = + color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerGreenActive")); } else { foregroundNominalColor = p_foregroundNominalColor; } @@ -574,11 +534,9 @@ void VolumeMeter::setForegroundWarningColor(QColor c) { p_foregroundWarningColor = std::move(c); - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - foregroundWarningColor = color_from_int( - config_get_int(App()->GetUserConfig(), "Accessibility", - "MixerYellowActive")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + foregroundWarningColor = + color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerYellowActive")); } else { foregroundWarningColor = p_foregroundWarningColor; } @@ -603,11 +561,9 @@ void VolumeMeter::setForegroundErrorColor(QColor c) { p_foregroundErrorColor = std::move(c); - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - foregroundErrorColor = color_from_int( - config_get_int(App()->GetUserConfig(), "Accessibility", - "MixerRedActive")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + foregroundErrorColor = + color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "MixerRedActive")); } else { foregroundErrorColor = p_foregroundErrorColor; } @@ -682,15 +638,11 @@ void VolumeMeter::setMeterFontScaling(qreal v) void VolControl::refreshColors() { - volMeter->setBackgroundNominalColor( - volMeter->getBackgroundNominalColor()); - volMeter->setBackgroundWarningColor( - volMeter->getBackgroundWarningColor()); + volMeter->setBackgroundNominalColor(volMeter->getBackgroundNominalColor()); + volMeter->setBackgroundWarningColor(volMeter->getBackgroundWarningColor()); volMeter->setBackgroundErrorColor(volMeter->getBackgroundErrorColor()); - volMeter->setForegroundNominalColor( - volMeter->getForegroundNominalColor()); - volMeter->setForegroundWarningColor( - volMeter->getForegroundWarningColor()); + volMeter->setForegroundNominalColor(volMeter->getForegroundNominalColor()); + volMeter->setForegroundWarningColor(volMeter->getForegroundWarningColor()); volMeter->setForegroundErrorColor(volMeter->getForegroundErrorColor()); } @@ -828,8 +780,7 @@ void VolumeMeter::wheelEvent(QWheelEvent *event) QApplication::sendEvent(focusProxy(), event); } -VolumeMeter::VolumeMeter(QWidget *parent, obs_volmeter_t *obs_volmeter, - bool vertical) +VolumeMeter::VolumeMeter(QWidget *parent, obs_volmeter_t *obs_volmeter, bool vertical) : QWidget(parent), obs_volmeter(obs_volmeter), vertical(vertical) @@ -866,8 +817,7 @@ VolumeMeter::VolumeMeter(QWidget *parent, obs_volmeter_t *obs_volmeter, peakHoldDuration = 20.0; // 20 seconds inputPeakHoldDuration = 1.0; // 1 second meterThickness = 3; // Bar thickness in pixels - meterFontScaling = - 0.7; // Font size for numbers is 70% of Widget's font size + meterFontScaling = 0.7; // Font size for numbers is 70% of Widget's font size channels = (int)audio_output_get_channels(obs_get_audio()); doLayout(); @@ -887,8 +837,7 @@ VolumeMeter::~VolumeMeter() updateTimerRef->RemoveVolControl(this); } -void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS], - const float peak[MAX_AUDIO_CHANNELS], +void VolumeMeter::setLevels(const float magnitude[MAX_AUDIO_CHANNELS], const float peak[MAX_AUDIO_CHANNELS], const float inputPeak[MAX_AUDIO_CHANNELS]) { uint64_t ts = os_gettime_ns(); @@ -931,8 +880,7 @@ bool VolumeMeter::needLayoutChange() if (!currentNrAudioChannels) { struct obs_audio_info oai; obs_get_audio_info(&oai); - currentNrAudioChannels = (oai.speakers == SPEAKERS_MONO) ? 1 - : 2; + currentNrAudioChannels = (oai.speakers == SPEAKERS_MONO) ? 1 : 2; } if (displayNrAudioChannels != currentNrAudioChannels) { @@ -966,17 +914,13 @@ inline void VolumeMeter::doLayout() // Add 4 pixels for ticks, space to hold our longest label in this font, // and a few pixels before the fader. QRect scaleBounds = metrics.boundingRect("-88"); - setMinimumSize(displayNrAudioChannels * (meterThickness + 1) - - 1 + 10 + scaleBounds.width() + 2, - 100); + setMinimumSize(displayNrAudioChannels * (meterThickness + 1) - 1 + 10 + scaleBounds.width() + 2, 100); } else { // Each meter channel is meterThickness pixels high, plus one pixel // between channels, but not after the last. // Add 4 pixels for ticks, and space high enough to hold our label in // this font, presuming that digits don't have descenders. - setMinimumSize(100, - displayNrAudioChannels * (meterThickness + 1) - - 1 + 4 + metrics.capHeight()); + setMinimumSize(100, displayNrAudioChannels * (meterThickness + 1) - 1 + 4 + metrics.capHeight()); } resetLevels(); @@ -993,12 +937,9 @@ inline bool VolumeMeter::detectIdle(uint64_t ts) } } -inline void -VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, - qreal timeSinceLastRedraw) +inline void VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, qreal timeSinceLastRedraw) { - if (currentPeak[channelNr] >= displayPeak[channelNr] || - isnan(displayPeak[channelNr])) { + if (currentPeak[channelNr] >= displayPeak[channelNr] || isnan(displayPeak[channelNr])) { // Attack of peak is immediate. displayPeak[channelNr] = currentPeak[channelNr]; } else { @@ -1007,12 +948,10 @@ VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, // 24 dB / 2.8 seconds for Slow Profile (Type II PPM) float decay = float(peakDecayRate * timeSinceLastRedraw); displayPeak[channelNr] = - std::clamp(displayPeak[channelNr] - decay, - std::min(currentPeak[channelNr], 0.f), 0.f); + std::clamp(displayPeak[channelNr] - decay, std::min(currentPeak[channelNr], 0.f), 0.f); } - if (currentPeak[channelNr] >= displayPeakHold[channelNr] || - !isfinite(displayPeakHold[channelNr])) { + if (currentPeak[channelNr] >= displayPeakHold[channelNr] || !isfinite(displayPeakHold[channelNr])) { // Attack of peak-hold is immediate, but keep track // when it was last updated. displayPeakHold[channelNr] = currentPeak[channelNr]; @@ -1020,10 +959,7 @@ VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, } else { // The peak and hold falls back to peak // after 20 seconds. - qreal timeSinceLastPeak = - (uint64_t)(ts - - displayPeakHoldLastUpdateTime[channelNr]) * - 0.000000001; + qreal timeSinceLastPeak = (uint64_t)(ts - displayPeakHoldLastUpdateTime[channelNr]) * 0.000000001; if (timeSinceLastPeak > peakHoldDuration) { displayPeakHold[channelNr] = currentPeak[channelNr]; displayPeakHoldLastUpdateTime[channelNr] = ts; @@ -1038,13 +974,9 @@ VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, displayInputPeakHoldLastUpdateTime[channelNr] = ts; } else { // The peak and hold falls back to peak after 1 second. - qreal timeSinceLastPeak = - (uint64_t)(ts - - displayInputPeakHoldLastUpdateTime[channelNr]) * - 0.000000001; + qreal timeSinceLastPeak = (uint64_t)(ts - displayInputPeakHoldLastUpdateTime[channelNr]) * 0.000000001; if (timeSinceLastPeak > inputPeakHoldDuration) { - displayInputPeakHold[channelNr] = - currentInputPeak[channelNr]; + displayInputPeakHold[channelNr] = currentInputPeak[channelNr]; displayInputPeakHoldLastUpdateTime[channelNr] = ts; } } @@ -1057,29 +989,22 @@ VolumeMeter::calculateBallisticsForChannel(int channelNr, uint64_t ts, // A VU meter will integrate to the new value to 99% in 300 ms. // The calculation here is very simplified and is more accurate // with higher frame-rate. - float attack = - float((currentMagnitude[channelNr] - - displayMagnitude[channelNr]) * - (timeSinceLastRedraw / magnitudeIntegrationTime) * - 0.99); + float attack = float((currentMagnitude[channelNr] - displayMagnitude[channelNr]) * + (timeSinceLastRedraw / magnitudeIntegrationTime) * 0.99); displayMagnitude[channelNr] = - std::clamp(displayMagnitude[channelNr] + attack, - (float)minimumLevel, 0.f); + std::clamp(displayMagnitude[channelNr] + attack, (float)minimumLevel, 0.f); } } -inline void VolumeMeter::calculateBallistics(uint64_t ts, - qreal timeSinceLastRedraw) +inline void VolumeMeter::calculateBallistics(uint64_t ts, qreal timeSinceLastRedraw) { QMutexLocker locker(&dataMutex); for (int channelNr = 0; channelNr < MAX_AUDIO_CHANNELS; channelNr++) - calculateBallisticsForChannel(channelNr, ts, - timeSinceLastRedraw); + calculateBallisticsForChannel(channelNr, ts, timeSinceLastRedraw); } -void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width, - int height, float peakHold) +void VolumeMeter::paintInputMeter(QPainter &painter, int x, int y, int width, int height, float peakHold) { QMutexLocker locker(&dataMutex); QColor color; @@ -1142,12 +1067,9 @@ void VolumeMeter::paintVTicks(QPainter &painter, int x, int y, int height) // Center the number on the tick, but don't overflow if (i == 0) { - painter.drawText(x + 10, position + metrics.capHeight(), - str); + painter.drawText(x + 10, position + metrics.capHeight(), str); } else { - painter.drawText(x + 8, - position + (metrics.capHeight() / 2), - str); + painter.drawText(x + 8, position + (metrics.capHeight() / 2), str); } painter.drawLine(x, position, x + 2, position); @@ -1170,8 +1092,7 @@ inline int VolumeMeter::convertToInt(float number) return int(number); } -void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width, - int height, float magnitude, float peak, +void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width, int height, float magnitude, float peak, float peakHold) { qreal scale = width / minimumLevel; @@ -1196,94 +1117,66 @@ void VolumeMeter::paintHMeter(QPainter &painter, int x, int y, int width, if (peakPosition < minimumPosition) { painter.fillRect(minimumPosition, y, nominalLength, height, - muted ? backgroundNominalColorDisabled - : backgroundNominalColor); + muted ? backgroundNominalColorDisabled : backgroundNominalColor); painter.fillRect(warningPosition, y, warningLength, height, - muted ? backgroundWarningColorDisabled - : backgroundWarningColor); + muted ? backgroundWarningColorDisabled : backgroundWarningColor); painter.fillRect(errorPosition, y, errorLength, height, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else if (peakPosition < warningPosition) { - painter.fillRect(minimumPosition, y, - peakPosition - minimumPosition, height, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); - painter.fillRect(peakPosition, y, - warningPosition - peakPosition, height, - muted ? backgroundNominalColorDisabled - : backgroundNominalColor); + painter.fillRect(minimumPosition, y, peakPosition - minimumPosition, height, + muted ? foregroundNominalColorDisabled : foregroundNominalColor); + painter.fillRect(peakPosition, y, warningPosition - peakPosition, height, + muted ? backgroundNominalColorDisabled : backgroundNominalColor); painter.fillRect(warningPosition, y, warningLength, height, - muted ? backgroundWarningColorDisabled - : backgroundWarningColor); + muted ? backgroundWarningColorDisabled : backgroundWarningColor); painter.fillRect(errorPosition, y, errorLength, height, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else if (peakPosition < errorPosition) { painter.fillRect(minimumPosition, y, nominalLength, height, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); - painter.fillRect(warningPosition, y, - peakPosition - warningPosition, height, - muted ? foregroundWarningColorDisabled - : foregroundWarningColor); - painter.fillRect(peakPosition, y, errorPosition - peakPosition, - height, - muted ? backgroundWarningColorDisabled - : backgroundWarningColor); + muted ? foregroundNominalColorDisabled : foregroundNominalColor); + painter.fillRect(warningPosition, y, peakPosition - warningPosition, height, + muted ? foregroundWarningColorDisabled : foregroundWarningColor); + painter.fillRect(peakPosition, y, errorPosition - peakPosition, height, + muted ? backgroundWarningColorDisabled : backgroundWarningColor); painter.fillRect(errorPosition, y, errorLength, height, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else if (peakPosition < maximumPosition) { painter.fillRect(minimumPosition, y, nominalLength, height, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); + muted ? foregroundNominalColorDisabled : foregroundNominalColor); painter.fillRect(warningPosition, y, warningLength, height, - muted ? foregroundWarningColorDisabled - : foregroundWarningColor); - painter.fillRect(errorPosition, y, peakPosition - errorPosition, - height, - muted ? foregroundErrorColorDisabled - : foregroundErrorColor); - painter.fillRect(peakPosition, y, - maximumPosition - peakPosition, height, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? foregroundWarningColorDisabled : foregroundWarningColor); + painter.fillRect(errorPosition, y, peakPosition - errorPosition, height, + muted ? foregroundErrorColorDisabled : foregroundErrorColor); + painter.fillRect(peakPosition, y, maximumPosition - peakPosition, height, + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else { if (!clipping) { - QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, - [&]() { clipping = false; }); + QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, [&]() { clipping = false; }); clipping = true; } int end = errorLength + warningLength + nominalLength; painter.fillRect(minimumPosition, y, end, height, - QBrush(muted ? foregroundErrorColorDisabled - : foregroundErrorColor)); + QBrush(muted ? foregroundErrorColorDisabled : foregroundErrorColor)); } if (peakHoldPosition - 3 < minimumPosition) ; // Peak-hold below minimum, no drawing. else if (peakHoldPosition < warningPosition) painter.fillRect(peakHoldPosition - 3, y, 3, height, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); + muted ? foregroundNominalColorDisabled : foregroundNominalColor); else if (peakHoldPosition < errorPosition) painter.fillRect(peakHoldPosition - 3, y, 3, height, - muted ? foregroundWarningColorDisabled - : foregroundWarningColor); + muted ? foregroundWarningColorDisabled : foregroundWarningColor); else painter.fillRect(peakHoldPosition - 3, y, 3, height, - muted ? foregroundErrorColorDisabled - : foregroundErrorColor); + muted ? foregroundErrorColorDisabled : foregroundErrorColor); if (magnitudePosition - 3 >= minimumPosition) - painter.fillRect(magnitudePosition - 3, y, 3, height, - magnitudeColor); + painter.fillRect(magnitudePosition - 3, y, 3, height, magnitudeColor); } -void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width, - int height, float magnitude, float peak, +void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width, int height, float magnitude, float peak, float peakHold) { qreal scale = height / minimumLevel; @@ -1308,90 +1201,63 @@ void VolumeMeter::paintVMeter(QPainter &painter, int x, int y, int width, if (peakPosition < minimumPosition) { painter.fillRect(x, minimumPosition, width, nominalLength, - muted ? backgroundNominalColorDisabled - : backgroundNominalColor); + muted ? backgroundNominalColorDisabled : backgroundNominalColor); painter.fillRect(x, warningPosition, width, warningLength, - muted ? backgroundWarningColorDisabled - : backgroundWarningColor); + muted ? backgroundWarningColorDisabled : backgroundWarningColor); painter.fillRect(x, errorPosition, width, errorLength, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else if (peakPosition < warningPosition) { - painter.fillRect(x, minimumPosition, width, - peakPosition - minimumPosition, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); - painter.fillRect(x, peakPosition, width, - warningPosition - peakPosition, - muted ? backgroundNominalColorDisabled - : backgroundNominalColor); + painter.fillRect(x, minimumPosition, width, peakPosition - minimumPosition, + muted ? foregroundNominalColorDisabled : foregroundNominalColor); + painter.fillRect(x, peakPosition, width, warningPosition - peakPosition, + muted ? backgroundNominalColorDisabled : backgroundNominalColor); painter.fillRect(x, warningPosition, width, warningLength, - muted ? backgroundWarningColorDisabled - : backgroundWarningColor); + muted ? backgroundWarningColorDisabled : backgroundWarningColor); painter.fillRect(x, errorPosition, width, errorLength, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else if (peakPosition < errorPosition) { painter.fillRect(x, minimumPosition, width, nominalLength, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); - painter.fillRect(x, warningPosition, width, - peakPosition - warningPosition, - muted ? foregroundWarningColorDisabled - : foregroundWarningColor); - painter.fillRect(x, peakPosition, width, - errorPosition - peakPosition, - muted ? backgroundWarningColorDisabled - : backgroundWarningColor); + muted ? foregroundNominalColorDisabled : foregroundNominalColor); + painter.fillRect(x, warningPosition, width, peakPosition - warningPosition, + muted ? foregroundWarningColorDisabled : foregroundWarningColor); + painter.fillRect(x, peakPosition, width, errorPosition - peakPosition, + muted ? backgroundWarningColorDisabled : backgroundWarningColor); painter.fillRect(x, errorPosition, width, errorLength, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else if (peakPosition < maximumPosition) { painter.fillRect(x, minimumPosition, width, nominalLength, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); + muted ? foregroundNominalColorDisabled : foregroundNominalColor); painter.fillRect(x, warningPosition, width, warningLength, - muted ? foregroundWarningColorDisabled - : foregroundWarningColor); - painter.fillRect(x, errorPosition, width, - peakPosition - errorPosition, - muted ? foregroundErrorColorDisabled - : foregroundErrorColor); - painter.fillRect(x, peakPosition, width, - maximumPosition - peakPosition, - muted ? backgroundErrorColorDisabled - : backgroundErrorColor); + muted ? foregroundWarningColorDisabled : foregroundWarningColor); + painter.fillRect(x, errorPosition, width, peakPosition - errorPosition, + muted ? foregroundErrorColorDisabled : foregroundErrorColor); + painter.fillRect(x, peakPosition, width, maximumPosition - peakPosition, + muted ? backgroundErrorColorDisabled : backgroundErrorColor); } else { if (!clipping) { - QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, - [&]() { clipping = false; }); + QTimer::singleShot(CLIP_FLASH_DURATION_MS, this, [&]() { clipping = false; }); clipping = true; } int end = errorLength + warningLength + nominalLength; painter.fillRect(x, minimumPosition, width, end, - QBrush(muted ? foregroundErrorColorDisabled - : foregroundErrorColor)); + QBrush(muted ? foregroundErrorColorDisabled : foregroundErrorColor)); } if (peakHoldPosition - 3 < minimumPosition) ; // Peak-hold below minimum, no drawing. else if (peakHoldPosition < warningPosition) painter.fillRect(x, peakHoldPosition - 3, width, 3, - muted ? foregroundNominalColorDisabled - : foregroundNominalColor); + muted ? foregroundNominalColorDisabled : foregroundNominalColor); else if (peakHoldPosition < errorPosition) painter.fillRect(x, peakHoldPosition - 3, width, 3, - muted ? foregroundWarningColorDisabled - : foregroundWarningColor); + muted ? foregroundWarningColorDisabled : foregroundWarningColor); else painter.fillRect(x, peakHoldPosition - 3, width, 3, - muted ? foregroundErrorColorDisabled - : foregroundErrorColor); + muted ? foregroundErrorColorDisabled : foregroundErrorColor); if (magnitudePosition - 3 >= minimumPosition) - painter.fillRect(x, magnitudePosition - 3, width, 3, - magnitudeColor); + painter.fillRect(x, magnitudePosition - 3, width, 3, magnitudeColor); } void VolumeMeter::paintEvent(QPaintEvent *event) @@ -1421,16 +1287,10 @@ void VolumeMeter::paintEvent(QPaintEvent *event) doLayout(); if (vertical) { - paintVTicks(painter, - displayNrAudioChannels * - (meterThickness + 1) - - 1, - 0, height - (INDICATOR_THICKNESS + 3)); + paintVTicks(painter, displayNrAudioChannels * (meterThickness + 1) - 1, 0, + height - (INDICATOR_THICKNESS + 3)); } else { - paintHTicks(painter, INDICATOR_THICKNESS + 3, - displayNrAudioChannels * - (meterThickness + 1) - - 1, + paintHTicks(painter, INDICATOR_THICKNESS + 3, displayNrAudioChannels * (meterThickness + 1) - 1, width - (INDICATOR_THICKNESS + 3)); } } @@ -1441,29 +1301,18 @@ void VolumeMeter::paintEvent(QPaintEvent *event) painter.scale(1, -1); } - for (int channelNr = 0; channelNr < displayNrAudioChannels; - channelNr++) { + for (int channelNr = 0; channelNr < displayNrAudioChannels; channelNr++) { - int channelNrFixed = - (displayNrAudioChannels == 1 && channels > 2) - ? 2 - : channelNr; + int channelNrFixed = (displayNrAudioChannels == 1 && channels > 2) ? 2 : channelNr; if (vertical) - paintVMeter(painter, channelNr * (meterThickness + 1), - INDICATOR_THICKNESS + 2, meterThickness, - height - (INDICATOR_THICKNESS + 2), - displayMagnitude[channelNrFixed], - displayPeak[channelNrFixed], - displayPeakHold[channelNrFixed]); + paintVMeter(painter, channelNr * (meterThickness + 1), INDICATOR_THICKNESS + 2, meterThickness, + height - (INDICATOR_THICKNESS + 2), displayMagnitude[channelNrFixed], + displayPeak[channelNrFixed], displayPeakHold[channelNrFixed]); else - paintHMeter(painter, INDICATOR_THICKNESS + 2, - channelNr * (meterThickness + 1), - width - (INDICATOR_THICKNESS + 2), - meterThickness, - displayMagnitude[channelNrFixed], - displayPeak[channelNrFixed], - displayPeakHold[channelNrFixed]); + paintHMeter(painter, INDICATOR_THICKNESS + 2, channelNr * (meterThickness + 1), + width - (INDICATOR_THICKNESS + 2), meterThickness, displayMagnitude[channelNrFixed], + displayPeak[channelNrFixed], displayPeakHold[channelNrFixed]); if (idle) continue; @@ -1472,15 +1321,11 @@ void VolumeMeter::paintEvent(QPaintEvent *event) // see that the audio stream has been stopped, without // having too much visual impact. if (vertical) - paintInputMeter(painter, - channelNr * (meterThickness + 1), 0, - meterThickness, INDICATOR_THICKNESS, - displayInputPeakHold[channelNrFixed]); + paintInputMeter(painter, channelNr * (meterThickness + 1), 0, meterThickness, + INDICATOR_THICKNESS, displayInputPeakHold[channelNrFixed]); else - paintInputMeter(painter, 0, - channelNr * (meterThickness + 1), - INDICATOR_THICKNESS, meterThickness, - displayInputPeakHold[channelNrFixed]); + paintInputMeter(painter, 0, channelNr * (meterThickness + 1), INDICATOR_THICKNESS, + meterThickness, displayInputPeakHold[channelNrFixed]); } lastRedrawTime = ts; @@ -1492,8 +1337,7 @@ QRect VolumeMeter::getBarRect() const if (vertical) rec.setWidth(displayNrAudioChannels * (meterThickness + 1) - 1); else - rec.setHeight(displayNrAudioChannels * (meterThickness + 1) - - 1); + rec.setHeight(displayNrAudioChannels * (meterThickness + 1) - 1); return rec; } @@ -1529,14 +1373,12 @@ void VolumeMeterTimer::timerEvent(QTimerEvent *) } } -VolumeSlider::VolumeSlider(obs_fader_t *fader, QWidget *parent) - : AbsoluteSlider(parent) +VolumeSlider::VolumeSlider(obs_fader_t *fader, QWidget *parent) : AbsoluteSlider(parent) { fad = fader; } -VolumeSlider::VolumeSlider(obs_fader_t *fader, Qt::Orientation orientation, - QWidget *parent) +VolumeSlider::VolumeSlider(obs_fader_t *fader, Qt::Orientation orientation, QWidget *parent) : AbsoluteSlider(orientation, parent) { fad = fader; @@ -1567,25 +1409,21 @@ void VolumeSlider::paintEvent(QPaintEvent *event) QStyleOptionSlider opt; initStyleOption(&opt); - QRect groove = style()->subControlRect(QStyle::CC_Slider, &opt, - QStyle::SC_SliderGroove, this); - QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, - QStyle::SC_SliderHandle, this); + QRect groove = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderGroove, this); + QRect handle = style()->subControlRect(QStyle::CC_Slider, &opt, QStyle::SC_SliderHandle, this); if (orientation() == Qt::Horizontal) { const int sliderWidth = groove.width() - handle.width(); float tickLength = groove.height() * 1.5; - tickLength = std::max((int)tickLength + groove.height(), - 8 + groove.height()); + tickLength = std::max((int)tickLength + groove.height(), 8 + groove.height()); float yPos = groove.center().y() - (tickLength / 2) + 1; for (int db = -10; db >= -90; db -= 10) { float tickValue = fader_db_to_def(db); - float xPos = groove.left() + (tickValue * sliderWidth) + - (handle.width() / 2); + float xPos = groove.left() + (tickValue * sliderWidth) + (handle.width() / 2); painter.fillRect(xPos, yPos, 1, tickLength, tickColor); } } @@ -1594,17 +1432,15 @@ void VolumeSlider::paintEvent(QPaintEvent *event) const int sliderHeight = groove.height() - handle.height(); float tickLength = groove.width() * 1.5; - tickLength = std::max((int)tickLength + groove.width(), - 8 + groove.width()); + tickLength = std::max((int)tickLength + groove.width(), 8 + groove.width()); float xPos = groove.center().x() - (tickLength / 2) + 1; for (int db = -10; db >= -96; db -= 10) { float tickValue = fader_db_to_def(db); - float yPos = groove.height() + groove.top() - - (tickValue * sliderHeight) - - (handle.height() / 2); + float yPos = + groove.height() + groove.top() - (tickValue * sliderHeight) - (handle.height() / 2); painter.fillRect(xPos, yPos, tickLength, 1, tickColor); } } @@ -1612,10 +1448,7 @@ void VolumeSlider::paintEvent(QPaintEvent *event) QSlider::paintEvent(event); } -VolumeAccessibleInterface::VolumeAccessibleInterface(QWidget *w) - : QAccessibleWidget(w) -{ -} +VolumeAccessibleInterface::VolumeAccessibleInterface(QWidget *w) : QAccessibleWidget(w) {} VolumeSlider *VolumeAccessibleInterface::slider() const { diff --git a/UI/volume-control.hpp b/UI/volume-control.hpp index 7b520e79a..51c77f247 100644 --- a/UI/volume-control.hpp +++ b/UI/volume-control.hpp @@ -16,83 +16,57 @@ class VolumeSlider; class VolumeMeter : public QWidget { Q_OBJECT - Q_PROPERTY(QColor backgroundNominalColor READ getBackgroundNominalColor - WRITE setBackgroundNominalColor DESIGNABLE true) - Q_PROPERTY(QColor backgroundWarningColor READ getBackgroundWarningColor - WRITE setBackgroundWarningColor DESIGNABLE true) - Q_PROPERTY(QColor backgroundErrorColor READ getBackgroundErrorColor - WRITE setBackgroundErrorColor DESIGNABLE true) - Q_PROPERTY(QColor foregroundNominalColor READ getForegroundNominalColor - WRITE setForegroundNominalColor DESIGNABLE true) - Q_PROPERTY(QColor foregroundWarningColor READ getForegroundWarningColor - WRITE setForegroundWarningColor DESIGNABLE true) - Q_PROPERTY(QColor foregroundErrorColor READ getForegroundErrorColor - WRITE setForegroundErrorColor DESIGNABLE true) - - Q_PROPERTY(QColor backgroundNominalColorDisabled READ - getBackgroundNominalColorDisabled WRITE - setBackgroundNominalColorDisabled - DESIGNABLE true) - Q_PROPERTY(QColor backgroundWarningColorDisabled READ - getBackgroundWarningColorDisabled WRITE - setBackgroundWarningColorDisabled - DESIGNABLE true) - Q_PROPERTY( - QColor backgroundErrorColorDisabled READ - getBackgroundErrorColorDisabled WRITE - setBackgroundErrorColorDisabled DESIGNABLE true) - Q_PROPERTY(QColor foregroundNominalColorDisabled READ - getForegroundNominalColorDisabled WRITE - setForegroundNominalColorDisabled - DESIGNABLE true) - Q_PROPERTY(QColor foregroundWarningColorDisabled READ - getForegroundWarningColorDisabled WRITE - setForegroundWarningColorDisabled - DESIGNABLE true) - Q_PROPERTY( - QColor foregroundErrorColorDisabled READ - getForegroundErrorColorDisabled WRITE - setForegroundErrorColorDisabled DESIGNABLE true) - - Q_PROPERTY(QColor clipColor READ getClipColor WRITE setClipColor + Q_PROPERTY(QColor backgroundNominalColor READ getBackgroundNominalColor WRITE setBackgroundNominalColor DESIGNABLE true) - Q_PROPERTY(QColor magnitudeColor READ getMagnitudeColor WRITE - setMagnitudeColor DESIGNABLE true) - Q_PROPERTY(QColor majorTickColor READ getMajorTickColor WRITE - setMajorTickColor DESIGNABLE true) - Q_PROPERTY(QColor minorTickColor READ getMinorTickColor WRITE - setMinorTickColor DESIGNABLE true) - Q_PROPERTY(int meterThickness READ getMeterThickness WRITE - setMeterThickness DESIGNABLE true) - Q_PROPERTY(qreal meterFontScaling READ getMeterFontScaling WRITE - setMeterFontScaling DESIGNABLE true) + Q_PROPERTY(QColor backgroundWarningColor READ getBackgroundWarningColor WRITE setBackgroundWarningColor + DESIGNABLE true) + Q_PROPERTY( + QColor backgroundErrorColor READ getBackgroundErrorColor WRITE setBackgroundErrorColor DESIGNABLE true) + Q_PROPERTY(QColor foregroundNominalColor READ getForegroundNominalColor WRITE setForegroundNominalColor + DESIGNABLE true) + Q_PROPERTY(QColor foregroundWarningColor READ getForegroundWarningColor WRITE setForegroundWarningColor + DESIGNABLE true) + Q_PROPERTY( + QColor foregroundErrorColor READ getForegroundErrorColor WRITE setForegroundErrorColor DESIGNABLE true) + + Q_PROPERTY(QColor backgroundNominalColorDisabled READ getBackgroundNominalColorDisabled WRITE + setBackgroundNominalColorDisabled DESIGNABLE true) + Q_PROPERTY(QColor backgroundWarningColorDisabled READ getBackgroundWarningColorDisabled WRITE + setBackgroundWarningColorDisabled DESIGNABLE true) + Q_PROPERTY(QColor backgroundErrorColorDisabled READ getBackgroundErrorColorDisabled WRITE + setBackgroundErrorColorDisabled DESIGNABLE true) + Q_PROPERTY(QColor foregroundNominalColorDisabled READ getForegroundNominalColorDisabled WRITE + setForegroundNominalColorDisabled DESIGNABLE true) + Q_PROPERTY(QColor foregroundWarningColorDisabled READ getForegroundWarningColorDisabled WRITE + setForegroundWarningColorDisabled DESIGNABLE true) + Q_PROPERTY(QColor foregroundErrorColorDisabled READ getForegroundErrorColorDisabled WRITE + setForegroundErrorColorDisabled DESIGNABLE true) + + Q_PROPERTY(QColor clipColor READ getClipColor WRITE setClipColor DESIGNABLE true) + Q_PROPERTY(QColor magnitudeColor READ getMagnitudeColor WRITE setMagnitudeColor DESIGNABLE true) + Q_PROPERTY(QColor majorTickColor READ getMajorTickColor WRITE setMajorTickColor DESIGNABLE true) + Q_PROPERTY(QColor minorTickColor READ getMinorTickColor WRITE setMinorTickColor DESIGNABLE true) + Q_PROPERTY(int meterThickness READ getMeterThickness WRITE setMeterThickness DESIGNABLE true) + Q_PROPERTY(qreal meterFontScaling READ getMeterFontScaling WRITE setMeterFontScaling DESIGNABLE true) // Levels are denoted in dBFS. - Q_PROPERTY(qreal minimumLevel READ getMinimumLevel WRITE setMinimumLevel - DESIGNABLE true) - Q_PROPERTY(qreal warningLevel READ getWarningLevel WRITE setWarningLevel - DESIGNABLE true) - Q_PROPERTY(qreal errorLevel READ getErrorLevel WRITE setErrorLevel - DESIGNABLE true) - Q_PROPERTY(qreal clipLevel READ getClipLevel WRITE setClipLevel - DESIGNABLE true) - Q_PROPERTY(qreal minimumInputLevel READ getMinimumInputLevel WRITE - setMinimumInputLevel DESIGNABLE true) + Q_PROPERTY(qreal minimumLevel READ getMinimumLevel WRITE setMinimumLevel DESIGNABLE true) + Q_PROPERTY(qreal warningLevel READ getWarningLevel WRITE setWarningLevel DESIGNABLE true) + Q_PROPERTY(qreal errorLevel READ getErrorLevel WRITE setErrorLevel DESIGNABLE true) + Q_PROPERTY(qreal clipLevel READ getClipLevel WRITE setClipLevel DESIGNABLE true) + Q_PROPERTY(qreal minimumInputLevel READ getMinimumInputLevel WRITE setMinimumInputLevel DESIGNABLE true) // Rates are denoted in dB/second. - Q_PROPERTY(qreal peakDecayRate READ getPeakDecayRate WRITE - setPeakDecayRate DESIGNABLE true) + Q_PROPERTY(qreal peakDecayRate READ getPeakDecayRate WRITE setPeakDecayRate DESIGNABLE true) // Time in seconds for the VU meter to integrate over. - Q_PROPERTY( - qreal magnitudeIntegrationTime READ getMagnitudeIntegrationTime - WRITE setMagnitudeIntegrationTime DESIGNABLE true) + Q_PROPERTY(qreal magnitudeIntegrationTime READ getMagnitudeIntegrationTime WRITE setMagnitudeIntegrationTime + DESIGNABLE true) // Duration is denoted in seconds. - Q_PROPERTY(qreal peakHoldDuration READ getPeakHoldDuration WRITE - setPeakHoldDuration DESIGNABLE true) - Q_PROPERTY(qreal inputPeakHoldDuration READ getInputPeakHoldDuration - WRITE setInputPeakHoldDuration DESIGNABLE true) + Q_PROPERTY(qreal peakHoldDuration READ getPeakHoldDuration WRITE setPeakHoldDuration DESIGNABLE true) + Q_PROPERTY(qreal inputPeakHoldDuration READ getInputPeakHoldDuration WRITE setInputPeakHoldDuration + DESIGNABLE true) friend class VolControl; @@ -104,19 +78,16 @@ private: inline void resetLevels(); inline void doLayout(); inline bool detectIdle(uint64_t ts); - inline void calculateBallistics(uint64_t ts, - qreal timeSinceLastRedraw = 0.0); - inline void calculateBallisticsForChannel(int channelNr, uint64_t ts, - qreal timeSinceLastRedraw); + inline void calculateBallistics(uint64_t ts, qreal timeSinceLastRedraw = 0.0); + inline void calculateBallisticsForChannel(int channelNr, uint64_t ts, qreal timeSinceLastRedraw); inline int convertToInt(float number); - void paintInputMeter(QPainter &painter, int x, int y, int width, - int height, float peakHold); - void paintHMeter(QPainter &painter, int x, int y, int width, int height, - float magnitude, float peak, float peakHold); + void paintInputMeter(QPainter &painter, int x, int y, int width, int height, float peakHold); + void paintHMeter(QPainter &painter, int x, int y, int width, int height, float magnitude, float peak, + float peakHold); void paintHTicks(QPainter &painter, int x, int y, int width); - void paintVMeter(QPainter &painter, int x, int y, int width, int height, - float magnitude, float peak, float peakHold); + void paintVMeter(QPainter &painter, int x, int y, int width, int height, float magnitude, float peak, + float peakHold); void paintVTicks(QPainter &painter, int x, int y, int height); QMutex dataMutex; @@ -182,13 +153,10 @@ private: bool muted = false; public: - explicit VolumeMeter(QWidget *parent = nullptr, - obs_volmeter_t *obs_volmeter = nullptr, - bool vertical = false); + explicit VolumeMeter(QWidget *parent = nullptr, obs_volmeter_t *obs_volmeter = nullptr, bool vertical = false); ~VolumeMeter(); - void setLevels(const float magnitude[MAX_AUDIO_CHANNELS], - const float peak[MAX_AUDIO_CHANNELS], + void setLevels(const float magnitude[MAX_AUDIO_CHANNELS], const float peak[MAX_AUDIO_CHANNELS], const float inputPeak[MAX_AUDIO_CHANNELS]); QRect getBarRect() const; bool needLayoutChange(); @@ -297,10 +265,8 @@ private: QMenu *contextMenu; static void OBSVolumeChanged(void *param, float db); - static void OBSVolumeLevel(void *data, - const float magnitude[MAX_AUDIO_CHANNELS], - const float peak[MAX_AUDIO_CHANNELS], - const float inputPeak[MAX_AUDIO_CHANNELS]); + static void OBSVolumeLevel(void *data, const float magnitude[MAX_AUDIO_CHANNELS], + const float peak[MAX_AUDIO_CHANNELS], const float inputPeak[MAX_AUDIO_CHANNELS]); static void OBSVolumeMuted(void *data, calldata_t *calldata); static void OBSMixersOrMonitoringChanged(void *data, calldata_t *); @@ -319,8 +285,7 @@ signals: void ConfigClicked(); public: - explicit VolControl(OBSSource source, bool showConfig = false, - bool vertical = false); + explicit VolControl(OBSSource source, bool showConfig = false, bool vertical = false); ~VolControl(); inline obs_source_t *GetSource() const { return source; } @@ -341,8 +306,7 @@ public: obs_fader_t *fad; VolumeSlider(obs_fader_t *fader, QWidget *parent = nullptr); - VolumeSlider(obs_fader_t *fader, Qt::Orientation orientation, - QWidget *parent = nullptr); + VolumeSlider(obs_fader_t *fader, Qt::Orientation orientation, QWidget *parent = nullptr); bool getDisplayTicks() const; void setDisplayTicks(bool display); diff --git a/UI/win-dll-blocklist.c b/UI/win-dll-blocklist.c index 994690e1b..dc7d7ea4e 100644 --- a/UI/win-dll-blocklist.c +++ b/UI/win-dll-blocklist.c @@ -37,14 +37,12 @@ typedef struct _SECTION_BASIC_INFORMATION { LARGE_INTEGER Size; } SECTION_BASIC_INFORMATION; -typedef NTSTATUS(STDMETHODCALLTYPE *fn_NtMapViewOfSection)( - HANDLE, HANDLE, PVOID, ULONG_PTR, SIZE_T, PLARGE_INTEGER, PSIZE_T, - SECTION_INHERIT, ULONG, ULONG); +typedef NTSTATUS(STDMETHODCALLTYPE *fn_NtMapViewOfSection)(HANDLE, HANDLE, PVOID, ULONG_PTR, SIZE_T, PLARGE_INTEGER, + PSIZE_T, SECTION_INHERIT, ULONG, ULONG); typedef NTSTATUS(STDMETHODCALLTYPE *fn_NtUnmapViewOfSection)(HANDLE, PVOID); -typedef NTSTATUS(STDMETHODCALLTYPE *fn_NtQuerySection)( - HANDLE, SECTION_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T); +typedef NTSTATUS(STDMETHODCALLTYPE *fn_NtQuerySection)(HANDLE, SECTION_INFORMATION_CLASS, PVOID, SIZE_T, PSIZE_T); static fn_NtMapViewOfSection ntMap; static fn_NtUnmapViewOfSection ntUnmap; @@ -181,8 +179,7 @@ static blocked_module_t blocked_modules[] = { // HolisticMotionCapture capture filter, not yet patched. Blocking // all previous versions in case an update is released. // Reference: https://github.com/obsproject/obs-studio/issues/8552 - {L"\\holisticmotioncapturefilter64bit.dll", 0, 1680044549, - TS_LESS_THAN}, + {L"\\holisticmotioncapturefilter64bit.dll", 0, 1680044549, TS_LESS_THAN}, // Elgato Stream Deck plugin < 2024-02-01 // Blocking all previous versions because they have undefined behavior @@ -216,16 +213,13 @@ static bool is_module_blocked(wchar_t *dll, uint32_t timestamp) if (b->method == TS_IGNORE) { b->blocked_count++; return true; - } else if (b->method == TS_EQUAL && - timestamp == b->timestamp) { + } else if (b->method == TS_EQUAL && timestamp == b->timestamp) { b->blocked_count++; return true; - } else if (b->method == TS_LESS_THAN && - timestamp < b->timestamp) { + } else if (b->method == TS_LESS_THAN && timestamp < b->timestamp) { b->blocked_count++; return true; - } else if (b->method == TS_GREATER_THAN && - timestamp > b->timestamp) { + } else if (b->method == TS_GREATER_THAN && timestamp > b->timestamp) { b->blocked_count++; return true; } else if (b->method == TS_ALLOW_ONLY_THIS) { @@ -252,12 +246,10 @@ static bool is_module_blocked(wchar_t *dll, uint32_t timestamp) return should_block; } -static NTSTATUS -NtMapViewOfSection_hook(HANDLE SectionHandle, HANDLE ProcessHandle, - PVOID *BaseAddress, ULONG_PTR ZeroBits, - SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, - PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, - ULONG AllocationType, ULONG Win32Protect) +static NTSTATUS NtMapViewOfSection_hook(HANDLE SectionHandle, HANDLE ProcessHandle, PVOID *BaseAddress, + ULONG_PTR ZeroBits, SIZE_T CommitSize, PLARGE_INTEGER SectionOffset, + PSIZE_T ViewSize, SECTION_INHERIT InheritDisposition, ULONG AllocationType, + ULONG Win32Protect) { SECTION_BASIC_INFORMATION section_information; wchar_t fileName[MAX_PATH]; @@ -265,18 +257,16 @@ NtMapViewOfSection_hook(HANDLE SectionHandle, HANDLE ProcessHandle, NTSTATUS ret; uint32_t timestamp = 0; - ret = ntMap(SectionHandle, ProcessHandle, BaseAddress, ZeroBits, - CommitSize, SectionOffset, ViewSize, InheritDisposition, - AllocationType, Win32Protect); + ret = ntMap(SectionHandle, ProcessHandle, BaseAddress, ZeroBits, CommitSize, SectionOffset, ViewSize, + InheritDisposition, AllocationType, Win32Protect); // Verify map and process if (ret < 0 || ProcessHandle != GetCurrentProcess()) return ret; // Fetch section information - if (ntQuery(SectionHandle, SectionBasicInformation, - §ion_information, sizeof(section_information), - &wrote) < 0) + if (ntQuery(SectionHandle, SectionBasicInformation, §ion_information, sizeof(section_information), &wrote) < + 0) return ret; // Verify fetch was successful @@ -307,8 +297,7 @@ NtMapViewOfSection_hook(HANDLE SectionHandle, HANDLE ProcessHandle, } // Get the actual filename if possible - if (K32GetMappedFileNameW(ProcessHandle, *BaseAddress, fileName, - _countof(fileName)) == 0) + if (K32GetMappedFileNameW(ProcessHandle, *BaseAddress, fileName, _countof(fileName)) == 0) return ret; if (is_module_blocked(fileName, timestamp)) { @@ -329,8 +318,7 @@ void install_dll_blocklist_hook(void) if (!ntMap) return; - ntUnmap = (fn_NtUnmapViewOfSection)GetProcAddress( - nt, "NtUnmapViewOfSection"); + ntUnmap = (fn_NtUnmapViewOfSection)GetProcAddress(nt, "NtUnmapViewOfSection"); if (!ntUnmap) return; @@ -357,9 +345,7 @@ void log_blocked_dlls(void) for (int i = 0; i < _countof(blocked_modules); i++) { blocked_module_t *b = &blocked_modules[i]; if (b->blocked_count) { - blog(LOG_WARNING, - "Blocked loading of '%S' %" PRIu64 " time%S.", - b->name, b->blocked_count, + blog(LOG_WARNING, "Blocked loading of '%S' %" PRIu64 " time%S.", b->name, b->blocked_count, b->blocked_count == 1 ? L"" : L"s"); } } diff --git a/UI/win-update/updater/hash.cpp b/UI/win-update/updater/hash.cpp index 5aaf4d70f..06ef367d0 100644 --- a/UI/win-update/updater/hash.cpp +++ b/UI/win-update/updater/hash.cpp @@ -52,15 +52,13 @@ bool CalculateFileHash(const wchar_t *path, B2Hash &hash) hashBuffer.resize(1048576); - WinHandle handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, - nullptr, OPEN_EXISTING, 0, nullptr); + WinHandle handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); if (handle == INVALID_HANDLE_VALUE) return false; for (;;) { DWORD read = 0; - if (!ReadFile(handle, hashBuffer.data(), - (DWORD)hashBuffer.size(), &read, nullptr)) + if (!ReadFile(handle, hashBuffer.data(), (DWORD)hashBuffer.size(), &read, nullptr)) return false; if (!read) diff --git a/UI/win-update/updater/http.cpp b/UI/win-update/updater/http.cpp index 63353b8cb..c6bc6e892 100644 --- a/UI/win-update/updater/http.cpp +++ b/UI/win-update/updater/http.cpp @@ -25,8 +25,7 @@ using namespace std; /* ------------------------------------------------------------------------ */ -static bool ReadHTTPData(string &responseBuf, const uint8_t *buffer, - DWORD outSize) +static bool ReadHTTPData(string &responseBuf, const uint8_t *buffer, DWORD outSize) { try { responseBuf.append((const char *)buffer, outSize); @@ -36,8 +35,7 @@ static bool ReadHTTPData(string &responseBuf, const uint8_t *buffer, return true; } -bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, - const wchar_t *extraHeaders, int *responseCode, +bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, const wchar_t *extraHeaders, int *responseCode, string &responseBuf) { HttpHandle hSession; @@ -75,23 +73,17 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, /* -------------------------------------- * * connect to server */ - hSession = WinHttpOpen(L"OBS Studio Updater/3.0", - WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, - WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, - 0); + hSession = WinHttpOpen(L"OBS Studio Updater/3.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, WINHTTP_NO_PROXY_NAME, + WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) { *responseCode = -1; return false; } - WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, - (LPVOID)&tlsProtocols, sizeof(tlsProtocols)); - WinHttpSetOption(hSession, WINHTTP_OPTION_DECOMPRESSION, - (LPVOID)&compressionFlags, sizeof(compressionFlags)); + WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, (LPVOID)&tlsProtocols, sizeof(tlsProtocols)); + WinHttpSetOption(hSession, WINHTTP_OPTION_DECOMPRESSION, (LPVOID)&compressionFlags, sizeof(compressionFlags)); - hConnect = WinHttpConnect(hSession, hostName, - secure ? INTERNET_DEFAULT_HTTPS_PORT - : INTERNET_DEFAULT_HTTP_PORT, + hConnect = WinHttpConnect(hSession, hostName, secure ? INTERNET_DEFAULT_HTTPS_PORT : INTERNET_DEFAULT_HTTP_PORT, 0); if (!hConnect) { *responseCode = -2; @@ -101,19 +93,15 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, /* -------------------------------------- * * request data */ - hRequest = WinHttpOpenRequest(hConnect, L"POST", path, nullptr, - WINHTTP_NO_REFERER, acceptTypes, - secure ? WINHTTP_FLAG_SECURE | - WINHTTP_FLAG_REFRESH - : WINHTTP_FLAG_REFRESH); + hRequest = WinHttpOpenRequest(hConnect, L"POST", path, nullptr, WINHTTP_NO_REFERER, acceptTypes, + secure ? WINHTTP_FLAG_SECURE | WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) { *responseCode = -3; return false; } - bool bResults = !!WinHttpSendRequest(hRequest, extraHeaders, - extraHeaders ? -1 : 0, - (void *)data, dataLen, dataLen, 0); + bool bResults = + !!WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, (void *)data, dataLen, dataLen, 0); /* -------------------------------------- * * end request */ @@ -132,8 +120,7 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); - if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, - WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, + if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) { *responseCode = -4; return false; @@ -175,8 +162,7 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, dwSize = std::min(dwSize, (DWORD)sizeof(buffer)); - if (!WinHttpReadData(hRequest, (void *)buffer, dwSize, - &outSize)) { + if (!WinHttpReadData(hRequest, (void *)buffer, dwSize, &outSize)) { *responseCode = -9; return false; } @@ -200,8 +186,7 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, /* ------------------------------------------------------------------------ */ -static bool ReadHTTPFile(HANDLE updateFile, const uint8_t *buffer, - DWORD outSize, int *responseCode) +static bool ReadHTTPFile(HANDLE updateFile, const uint8_t *buffer, DWORD outSize, int *responseCode) { DWORD written; if (!WriteFile(updateFile, buffer, outSize, &written, nullptr)) { @@ -218,8 +203,7 @@ static bool ReadHTTPFile(HANDLE updateFile, const uint8_t *buffer, return true; } -bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, - const wchar_t *outputPath, const wchar_t *extraHeaders, +bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, const wchar_t *outputPath, const wchar_t *extraHeaders, int *responseCode) { HttpHandle hRequest; @@ -251,19 +235,15 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, /* -------------------------------------- * * request data */ - hRequest = WinHttpOpenRequest(hConnect, L"GET", path, nullptr, - WINHTTP_NO_REFERER, acceptTypes, - secure ? WINHTTP_FLAG_SECURE | - WINHTTP_FLAG_REFRESH - : WINHTTP_FLAG_REFRESH); + hRequest = WinHttpOpenRequest(hConnect, L"GET", path, nullptr, WINHTTP_NO_REFERER, acceptTypes, + secure ? WINHTTP_FLAG_SECURE | WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) { *responseCode = -3; return false; } - bool bResults = !!WinHttpSendRequest(hRequest, extraHeaders, - extraHeaders ? -1 : 0, - WINHTTP_NO_REQUEST_DATA, 0, 0, 0); + bool bResults = + !!WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); /* -------------------------------------- * * end request */ @@ -282,8 +262,7 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); - if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, - WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, + if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) { *responseCode = -4; return false; @@ -304,8 +283,7 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, DWORD dwSize, outSize; int lastPosition = 0; - WinHandle updateFile = CreateFile(outputPath, GENERIC_WRITE, 0, nullptr, - CREATE_ALWAYS, 0, nullptr); + WinHandle updateFile = CreateFile(outputPath, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); if (!updateFile.Valid()) { *responseCode = -7; return false; @@ -321,25 +299,20 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, dwSize = std::min(dwSize, (DWORD)sizeof(buffer)); - if (!WinHttpReadData(hRequest, (void *)buffer, dwSize, - &outSize)) { + if (!WinHttpReadData(hRequest, (void *)buffer, dwSize, &outSize)) { *responseCode = -9; return false; } else { if (!outSize) break; - if (!ReadHTTPFile(updateFile, buffer, outSize, - responseCode)) + if (!ReadHTTPFile(updateFile, buffer, outSize, responseCode)) return false; - int position = (int)(((float)completedFileSize / - (float)totalFileSize) * - 100.0f); + int position = (int)(((float)completedFileSize / (float)totalFileSize) * 100.0f); if (position > lastPosition) { lastPosition = position; - SendDlgItemMessage(hwndMain, IDC_PROGRESS, - PBM_SETPOS, position, 0); + SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETPOS, position, 0); } } @@ -353,8 +326,7 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, return true; } -bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, - const wchar_t *extraHeaders, vector &out, +bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, const wchar_t *extraHeaders, vector &out, int *responseCode) { HttpHandle hRequest; @@ -386,19 +358,15 @@ bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, /* -------------------------------------- * * request data */ - hRequest = WinHttpOpenRequest(hConnect, L"GET", path, nullptr, - WINHTTP_NO_REFERER, acceptTypes, - secure ? WINHTTP_FLAG_SECURE | - WINHTTP_FLAG_REFRESH - : WINHTTP_FLAG_REFRESH); + hRequest = WinHttpOpenRequest(hConnect, L"GET", path, nullptr, WINHTTP_NO_REFERER, acceptTypes, + secure ? WINHTTP_FLAG_SECURE | WINHTTP_FLAG_REFRESH : WINHTTP_FLAG_REFRESH); if (!hRequest) { *responseCode = -3; return false; } - bool bResults = !!WinHttpSendRequest(hRequest, extraHeaders, - extraHeaders ? -1 : 0, - WINHTTP_NO_REQUEST_DATA, 0, 0, 0); + bool bResults = + !!WinHttpSendRequest(hRequest, extraHeaders, extraHeaders ? -1 : 0, WINHTTP_NO_REQUEST_DATA, 0, 0, 0); /* -------------------------------------- * * end request */ @@ -417,8 +385,7 @@ bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, DWORD statusCodeLen; statusCodeLen = sizeof(statusCode); - if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, - WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, + if (!WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_STATUS_CODE, WINHTTP_HEADER_NAME_BY_INDEX, &statusCode, &statusCodeLen, WINHTTP_NO_HEADER_INDEX)) { *responseCode = -4; return false; @@ -449,25 +416,20 @@ bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, dwSize = std::min(dwSize, (DWORD)sizeof(buffer)); - if (!WinHttpReadData(hRequest, (void *)buffer, dwSize, - &outSize)) { + if (!WinHttpReadData(hRequest, (void *)buffer, dwSize, &outSize)) { *responseCode = -9; return false; } else { if (!outSize) break; - out.insert(out.end(), (std::byte *)buffer, - (std::byte *)buffer + outSize); + out.insert(out.end(), (std::byte *)buffer, (std::byte *)buffer + outSize); completedFileSize += outSize; - int position = (int)(((float)completedFileSize / - (float)totalFileSize) * - 100.0f); + int position = (int)(((float)completedFileSize / (float)totalFileSize) * 100.0f); if (position > lastPosition) { lastPosition = position; - SendDlgItemMessage(hwndMain, IDC_PROGRESS, - PBM_SETPOS, position, 0); + SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETPOS, position, 0); } } diff --git a/UI/win-update/updater/init-hook-files.c b/UI/win-update/updater/init-hook-files.c index 61017f12a..a5df3c767 100644 --- a/UI/win-update/updater/init-hook-files.c +++ b/UI/win-update/updater/init-hook-files.c @@ -15,9 +15,8 @@ static bool add_aap_perms(const wchar_t *dir) bool success = false; PACL dacl; - if (GetNamedSecurityInfoW(dir, SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, - NULL, &sd) != ERROR_SUCCESS) { + if (GetNamedSecurityInfoW(dir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, NULL, &sd) != + ERROR_SUCCESS) { goto fail; } @@ -35,8 +34,7 @@ static bool add_aap_perms(const wchar_t *dir) goto fail; } - ea.grfAccessPermissions = GENERIC_READ | GENERIC_WRITE | - GENERIC_EXECUTE; + ea.grfAccessPermissions = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE; /* BUILTIN_USERS */ ConvertStringSidToSidW(L"S-1-5-32-545", &bu_sid); @@ -47,9 +45,8 @@ static bool add_aap_perms(const wchar_t *dir) goto fail; } - if (SetNamedSecurityInfoW((wchar_t *)dir, SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, NULL, NULL, - new_dacl2, NULL) != ERROR_SUCCESS) { + if (SetNamedSecurityInfoW((wchar_t *)dir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, new_dacl2, + NULL) != ERROR_SUCCESS) { goto fail; } @@ -88,19 +85,17 @@ static LSTATUS get_reg(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, bool b64) status = RegOpenKeyEx(hkey, sub_key, 0, KEY_READ | flags, &key); if (status == ERROR_SUCCESS) { - status = RegQueryValueExW(key, value_name, NULL, NULL, - (LPBYTE)&val, &size); + status = RegQueryValueExW(key, value_name, NULL, NULL, (LPBYTE)&val, &size); RegCloseKey(key); } return status; } -#define get_programdata_path(path, subpath) \ - do { \ - SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, \ - SHGFP_TYPE_CURRENT, path); \ - StringCbCatW(path, sizeof(path), L"\\"); \ - StringCbCatW(path, sizeof(path), subpath); \ +#define get_programdata_path(path, subpath) \ + do { \ + SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, path); \ + StringCbCatW(path, sizeof(path), L"\\"); \ + StringCbCatW(path, sizeof(path), subpath); \ } while (false) #define make_filename(str, name, ext) \ @@ -159,8 +154,7 @@ static void update_vulkan_registry(bool b64) s = get_reg(HKEY_CURRENT_USER, IMPLICIT_LAYERS, path, b64); if (s == ERROR_SUCCESS) { - s = RegOpenKeyEx(HKEY_CURRENT_USER, IMPLICIT_LAYERS, 0, - KEY_WRITE | flags, &key); + s = RegOpenKeyEx(HKEY_CURRENT_USER, IMPLICIT_LAYERS, 0, KEY_WRITE | flags, &key); if (s == ERROR_SUCCESS) { RegDeleteValueW(key, path); RegCloseKey(key); @@ -174,15 +168,13 @@ static void update_vulkan_registry(bool b64) /* ------------------- */ - s = RegCreateKeyExW(HKEY_LOCAL_MACHINE, IMPLICIT_LAYERS, 0, NULL, 0, - KEY_WRITE | flags, NULL, &key, &temp); + s = RegCreateKeyExW(HKEY_LOCAL_MACHINE, IMPLICIT_LAYERS, 0, NULL, 0, KEY_WRITE | flags, NULL, &key, &temp); if (s != ERROR_SUCCESS) { goto finish; } DWORD zero = 0; - s = RegSetValueExW(key, path, 0, REG_DWORD, (const BYTE *)&zero, - sizeof(zero)); + s = RegSetValueExW(key, path, 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero)); if (s != ERROR_SUCCESS) { goto finish; } diff --git a/UI/win-update/updater/manifest.hpp b/UI/win-update/updater/manifest.hpp index ce6f7d2ce..23e4b14f8 100644 --- a/UI/win-update/updater/manifest.hpp +++ b/UI/win-update/updater/manifest.hpp @@ -61,8 +61,7 @@ struct Manifest { /* Release notes in HTML format */ std::string notes; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(Manifest, packages, version_major, - version_minor, version_patch, beta, rc, + NLOHMANN_DEFINE_TYPE_INTRUSIVE(Manifest, packages, version_major, version_minor, version_patch, beta, rc, commit, vc2019_redist_x64, notes) }; diff --git a/UI/win-update/updater/patch.cpp b/UI/win-update/updater/patch.cpp index 853c07f2b..6d77484a9 100644 --- a/UI/win-update/updater/patch.cpp +++ b/UI/win-update/updater/patch.cpp @@ -54,8 +54,7 @@ constexpr const char *kDeltaMagic = "BOUF//ZSTD//DICT"; constexpr int kMagicSize = 16; constexpr int kHeaderSize = kMagicSize + 8; // magic + int64_t delta size -int ApplyPatch(ZSTD_DCtx *zstdCtx, const std::byte *patch_data, - const size_t patch_size, const wchar_t *targetFile) +int ApplyPatch(ZSTD_DCtx *zstdCtx, const std::byte *patch_data, const size_t patch_size, const wchar_t *targetFile) try { int64_t newsize; bool success; @@ -65,8 +64,7 @@ try { /* --------------------------------- * * open patch and file to patch */ - hTarget = CreateFile(targetFile, GENERIC_READ, 0, nullptr, - OPEN_EXISTING, 0, nullptr); + hTarget = CreateFile(targetFile, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr); if (!hTarget.Valid()) throw int(GetLastError()); @@ -115,10 +113,8 @@ try { /* --------------------------------- * * patch to new file data */ - size_t result = ZSTD_decompress_usingDict( - zstdCtx, newData.data(), newData.size(), - patch_data + kHeaderSize, patch_size - kHeaderSize, - oldData.data(), oldData.size()); + size_t result = ZSTD_decompress_usingDict(zstdCtx, newData.data(), newData.size(), patch_data + kHeaderSize, + patch_size - kHeaderSize, oldData.data(), oldData.size()); if (result != newsize || ZSTD_isError(result)) throw int(-9); @@ -127,15 +123,13 @@ try { * write new file */ hTarget = nullptr; - hTarget = CreateFile(targetFile, GENERIC_WRITE, 0, nullptr, - CREATE_ALWAYS, 0, nullptr); + hTarget = CreateFile(targetFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); if (!hTarget.Valid()) throw int(GetLastError()); DWORD written; - success = !!WriteFile(hTarget, newData.data(), (DWORD)newsize, &written, - nullptr); + success = !!WriteFile(hTarget, newData.data(), (DWORD)newsize, &written, nullptr); if (!success || written != newsize) throw int(GetLastError()); diff --git a/UI/win-update/updater/updater.cpp b/UI/win-update/updater/updater.cpp index e505dd60c..9dc8d4d82 100644 --- a/UI/win-update/updater/updater.cpp +++ b/UI/win-update/updater/updater.cpp @@ -37,12 +37,9 @@ using namespace updater; constexpr const string_view kCDNUrl = "https://cdn-fastly.obsproject.com/"; constexpr const wchar_t *kCDNHostname = L"cdn-fastly.obsproject.com"; -constexpr const wchar_t *kCDNUpdateBaseUrl = - L"https://cdn-fastly.obsproject.com/update_studio"; -constexpr const wchar_t *kPatchManifestURL = - L"https://obsproject.com/update_studio/getpatchmanifest"; -constexpr const wchar_t *kVSRedistURL = - L"https://aka.ms/vs/17/release/vc_redist.x64.exe"; +constexpr const wchar_t *kCDNUpdateBaseUrl = L"https://cdn-fastly.obsproject.com/update_studio"; +constexpr const wchar_t *kPatchManifestURL = L"https://obsproject.com/update_studio/getpatchmanifest"; +constexpr const wchar_t *kVSRedistURL = L"https://aka.ms/vs/17/release/vc_redist.x64.exe"; constexpr const wchar_t *kMSHostname = L"aka.ms"; /* ----------------------------------------------------------------------- */ @@ -93,8 +90,7 @@ static bool IsVSRedistOutdated() if (!GetFileVersionInfo(vc_dll, 0, size, buf.data())) return true; - bool success = VerQueryValue(buf.data(), L"\\", - reinterpret_cast(&info), &len); + bool success = VerQueryValue(buf.data(), L"\\", reinterpret_cast(&info), &len); if (!success || !info || !len) return true; @@ -120,13 +116,12 @@ try { WinHandle hSrc; WinHandle hDest; - hSrc = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, nullptr, - OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); + hSrc = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, + nullptr); if (!hSrc.Valid()) throw LastError(); - hDest = CreateFile(dest, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, - nullptr); + hDest = CreateFile(dest, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); if (!hDest.Valid()) throw LastError(); @@ -182,8 +177,7 @@ static bool IsSafeFilename(const wchar_t *path) return false; while (*p) { - if (!isalnum(*p) && *p != '.' && *p != '/' && *p != '_' && - *p != '-') + if (!isalnum(*p) && *p != '.' && *p != '/' && *p != '_' && *p != '-') return false; p++; } @@ -195,8 +189,7 @@ static string QuickReadFile(const wchar_t *path) { string data; - WinHandle handle = CreateFileW(path, GENERIC_READ, 0, nullptr, - OPEN_EXISTING, 0, nullptr); + WinHandle handle = CreateFileW(path, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr); if (!handle.Valid()) { return {}; } @@ -210,8 +203,7 @@ static string QuickReadFile(const wchar_t *path) data.resize((size_t)size.QuadPart); DWORD read; - if (!ReadFile(handle, data.data(), (DWORD)data.size(), &read, - nullptr)) { + if (!ReadFile(handle, data.data(), (DWORD)data.size(), &read, nullptr)) { return {}; } if (read != size.QuadPart) { @@ -223,9 +215,7 @@ static string QuickReadFile(const wchar_t *path) static bool QuickWriteFile(const wchar_t *file, const void *data, size_t size) try { - WinHandle handle = CreateFile(file, GENERIC_WRITE, 0, nullptr, - CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, - nullptr); + WinHandle handle = CreateFile(file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_FLAG_WRITE_THROUGH, nullptr); if (handle == INVALID_HANDLE_VALUE) throw GetLastError(); @@ -247,9 +237,7 @@ try { template<> struct std::hash { size_t operator()(const B2Hash &value) const noexcept { - return hash{}(string_view( - reinterpret_cast(value.data()), - value.size())); + return hash{}(string_view(reinterpret_cast(value.data()), value.size())); } }; @@ -305,8 +293,7 @@ struct update_t { if (state == STATE_INSTALL_FAILED || state == STATE_INSTALLED) { if (!previousFile.empty()) { DeleteFile(outputPath.c_str()); - MyCopyFile(previousFile.c_str(), - outputPath.c_str()); + MyCopyFile(previousFile.c_str(), outputPath.c_str()); DeleteFile(previousFile.c_str()); } else { DeleteFile(outputPath.c_str()); @@ -324,8 +311,7 @@ struct deletion_t { void UndoRename() const { if (!deleteMeFilename.empty()) - MoveFile(deleteMeFilename.c_str(), - originalFilename.c_str()); + MoveFile(deleteMeFilename.c_str(), originalFilename.c_str()); } }; @@ -358,8 +344,7 @@ static int Decompress(ZSTD_DCtx *ctx, std::vector &buf, size_t size) } // Overwrite buffer with decompressed data - size_t result = ZSTD_decompressDCtx(ctx, buf.data(), buf.size(), - comp.data(), comp.size()); + size_t result = ZSTD_decompressDCtx(ctx, buf.data(), buf.size(), comp.data(), comp.size()); if (result != size) return -9; @@ -371,34 +356,28 @@ static int Decompress(ZSTD_DCtx *ctx, std::vector &buf, size_t size) bool DownloadWorkerThread() { - const DWORD tlsProtocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | - WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; + const DWORD tlsProtocols = WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_2 | WINHTTP_FLAG_SECURE_PROTOCOL_TLS1_3; const DWORD enableHTTP2Flag = WINHTTP_PROTOCOL_FLAG_HTTP2; const DWORD compressionFlags = WINHTTP_DECOMPRESSION_FLAG_ALL; - HttpHandle hSession = WinHttpOpen(L"OBS Studio Updater/3.0", - WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, - WINHTTP_NO_PROXY_NAME, - WINHTTP_NO_PROXY_BYPASS, 0); + HttpHandle hSession = WinHttpOpen(L"OBS Studio Updater/3.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) { downloadThreadFailure = true; Status(L"Update failed: Couldn't open obsproject.com"); return false; } - WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, - (LPVOID)&tlsProtocols, sizeof(tlsProtocols)); + WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, (LPVOID)&tlsProtocols, sizeof(tlsProtocols)); - WinHttpSetOption(hSession, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, - (LPVOID)&enableHTTP2Flag, sizeof(enableHTTP2Flag)); + WinHttpSetOption(hSession, WINHTTP_OPTION_ENABLE_HTTP_PROTOCOL, (LPVOID)&enableHTTP2Flag, + sizeof(enableHTTP2Flag)); - WinHttpSetOption(hSession, WINHTTP_OPTION_DECOMPRESSION, - (LPVOID)&compressionFlags, sizeof(compressionFlags)); + WinHttpSetOption(hSession, WINHTTP_OPTION_DECOMPRESSION, (LPVOID)&compressionFlags, sizeof(compressionFlags)); - HttpHandle hConnect = WinHttpConnect(hSession, kCDNHostname, - INTERNET_DEFAULT_HTTPS_PORT, 0); + HttpHandle hConnect = WinHttpConnect(hSession, kCDNHostname, INTERNET_DEFAULT_HTTPS_PORT, 0); if (!hConnect) { downloadThreadFailure = true; Status(L"Update failed: Couldn't connect to %S", kCDNHostname); @@ -415,8 +394,7 @@ bool DownloadWorkerThread() for (update_t &update : updates) { int responseCode; - DWORD waitResult = - WaitForSingleObject(cancelRequested, 0); + DWORD waitResult = WaitForSingleObject(cancelRequested, 0); if (waitResult == WAIT_OBJECT_0) { return false; } @@ -438,8 +416,7 @@ bool DownloadWorkerThread() /* Reserve required memory */ buf.reserve(update.fileSize); - if (!HTTPGetBuffer(hConnect, update.sourceURL.c_str(), - L"Accept-Encoding: gzip", buf, + if (!HTTPGetBuffer(hConnect, update.sourceURL.c_str(), L"Accept-Encoding: gzip", buf, &responseCode)) { downloadThreadFailure = true; Status(L"Update failed: Could not download " @@ -458,8 +435,7 @@ bool DownloadWorkerThread() /* Validate hash of downloaded data. */ B2Hash dataHash; - blake2b(dataHash.data(), dataHash.size(), buf.data(), - buf.size(), nullptr, 0); + blake2b(dataHash.data(), dataHash.size(), buf.data(), buf.size(), nullptr, 0); if (dataHash != update.downloadHash) { downloadThreadFailure = true; @@ -471,8 +447,7 @@ bool DownloadWorkerThread() /* Decompress data in compressed buffer. */ if (update.compressed && !update.patchable) { - int res = - Decompress(zCtx, buf, update.fileSize); + int res = Decompress(zCtx, buf, update.fileSize); if (res) { downloadThreadFailure = true; Status(L"Update failed: Decompression " @@ -531,9 +506,7 @@ static inline DWORD WaitIfOBS(DWORD id, const wchar_t *expected) *path = 0; - WinHandle proc = OpenProcess(PROCESS_QUERY_INFORMATION | - PROCESS_VM_READ | SYNCHRONIZE, - false, id); + WinHandle proc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | SYNCHRONIZE, false, id); if (!proc.Valid()) return WAITIFOBS_WRONG_PROCESS; @@ -602,8 +575,7 @@ static inline bool UTF8ToWide(wchar_t *wide, int wideSize, const char *utf8) static inline bool WideToUTF8(char *utf8, int utf8Size, const wchar_t *wide) { - return !!WideCharToMultiByte(CP_UTF8, 0, wide, -1, utf8, utf8Size, - nullptr, nullptr); + return !!WideCharToMultiByte(CP_UTF8, 0, wide, -1, utf8, utf8Size, nullptr, nullptr); } #define UTF8ToWideBuf(wide, utf8) UTF8ToWide(wide, _countof(wide), utf8) @@ -692,8 +664,7 @@ static bool AddPackageUpdateFiles(const Package &package, const wchar_t *branch) if (!UTF8ToWideBuf(wPackageName, package.name.c_str())) return false; - if (package.name != "core" && - !NonCorePackageInstalled(package.name.c_str())) + if (package.name != "core" && !NonCorePackageInstalled(package.name.c_str())) return true; for (const File &file : package.files) { @@ -723,8 +694,7 @@ static bool AddPackageUpdateFiles(const Package &package, const wchar_t *branch) return false; } - StringCbPrintf(sourceURL, sizeof(sourceURL), L"%s/%s/%s/%s", - kCDNUpdateBaseUrl, branch, wPackageName, + StringCbPrintf(sourceURL, sizeof(sourceURL), L"%s/%s/%s/%s", kCDNUpdateBaseUrl, branch, wPackageName, updateFileName); /* Convert hashes */ @@ -786,11 +756,9 @@ static void AddPackageRemovedFiles(const Package &package) continue; /* Technically GetFileAttributes can fail for other reasons, * so double-check by also checking the last error */ - if (GetFileAttributesW(removedFileName) == - INVALID_FILE_ATTRIBUTES) { + if (GetFileAttributesW(removedFileName) == INVALID_FILE_ATTRIBUTES) { int err = GetLastError(); - if (err == ERROR_FILE_NOT_FOUND || - err == ERROR_PATH_NOT_FOUND) + if (err == ERROR_FILE_NOT_FOUND || err == ERROR_PATH_NOT_FOUND) continue; } @@ -819,8 +787,7 @@ static bool RenameRemovedFile(deletion_t &deletion) randomStr[8] = 0; - StringCbCopy(deleteMeName, sizeof(deleteMeName), - deletion.originalFilename.c_str()); + StringCbCopy(deleteMeName, sizeof(deleteMeName), deletion.originalFilename.c_str()); StringCbCat(deleteMeName, sizeof(deleteMeName), L"."); StringCbCat(deleteMeName, sizeof(deleteMeName), randomStr); @@ -891,8 +858,7 @@ static bool MoveInUseFileAway(const update_t &file) randomStr[8] = 0; - StringCbCopy(deleteMeName, sizeof(deleteMeName), - file.outputPath.c_str()); + StringCbCopy(deleteMeName, sizeof(deleteMeName), file.outputPath.c_str()); StringCbCat(deleteMeName, sizeof(deleteMeName), L"."); StringCbCat(deleteMeName, sizeof(deleteMeName), randomStr); @@ -901,8 +867,7 @@ static bool MoveInUseFileAway(const update_t &file) if (MoveFile(file.outputPath.c_str(), deleteMeName)) { if (MyCopyFile(deleteMeName, file.outputPath.c_str())) { - MoveFileEx(deleteMeName, NULL, - MOVEFILE_DELAY_UNTIL_REBOOT); + MoveFileEx(deleteMeName, NULL, MOVEFILE_DELAY_UNTIL_REBOOT); return true; } else { @@ -927,8 +892,7 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) if (attribs != INVALID_FILE_ATTRIBUTES) { wchar_t baseName[MAX_PATH]; - StringCbCopy(baseName, sizeof(baseName), - file.outputPath.c_str()); + StringCbCopy(baseName, sizeof(baseName), file.outputPath.c_str()); wchar_t *curFileName = wcsrchr(baseName, '/'); if (curFileName) { @@ -938,16 +902,12 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) curFileName = baseName; /* Backup the existing file in case a rollback is needed */ - StringCbCopy(oldFileRenamedPath, sizeof(oldFileRenamedPath), - file.outputPath.c_str()); - StringCbCat(oldFileRenamedPath, sizeof(oldFileRenamedPath), - L".old"); + StringCbCopy(oldFileRenamedPath, sizeof(oldFileRenamedPath), file.outputPath.c_str()); + StringCbCat(oldFileRenamedPath, sizeof(oldFileRenamedPath), L".old"); if (!MyCopyFile(file.outputPath.c_str(), oldFileRenamedPath)) { DWORD err = GetLastError(); - int is_sharing_violation = - (err == ERROR_SHARING_VIOLATION || - err == ERROR_USER_MAPPED_FILE); + int is_sharing_violation = (err == ERROR_SHARING_VIOLATION || err == ERROR_USER_MAPPED_FILE); if (is_sharing_violation) Status(L"Update failed: %s is still in use. " @@ -969,16 +929,13 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) retryAfterMovingFile: if (file.patchable) { - error_code = ApplyPatch(ctx, patch_data.data(), - file.fileSize, - file.outputPath.c_str()); + error_code = ApplyPatch(ctx, patch_data.data(), file.fileSize, file.outputPath.c_str()); installed_ok = (error_code == 0); if (installed_ok) { B2Hash patchedFileHash; - if (!CalculateFileHash(file.outputPath.c_str(), - patchedFileHash)) { + if (!CalculateFileHash(file.outputPath.c_str(), patchedFileHash)) { Status(L"Update failed: Couldn't " L"verify integrity of patched %s", curFileName); @@ -998,16 +955,13 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) } } } else { - installed_ok = QuickWriteFile(file.outputPath.c_str(), - patch_data.data(), - patch_data.size()); + installed_ok = QuickWriteFile(file.outputPath.c_str(), patch_data.data(), patch_data.size()); error_code = GetLastError(); } if (!installed_ok) { int is_sharing_violation = - (error_code == ERROR_SHARING_VIOLATION || - error_code == ERROR_USER_MAPPED_FILE); + (error_code == ERROR_SHARING_VIOLATION || error_code == ERROR_USER_MAPPED_FILE); if (is_sharing_violation) { if (!already_tried_to_move) { @@ -1037,8 +991,7 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) if (file.patchable) { /* Uh oh, we thought we could patch something but it's * no longer there! */ - Status(L"Update failed: Source file %s not found", - file.outputPath.c_str()); + Status(L"Update failed: Source file %s not found", file.outputPath.c_str()); return false; } @@ -1049,12 +1002,10 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) file.previousFile = L""; - bool success = !!QuickWriteFile(file.outputPath.c_str(), - patch_data.data(), - patch_data.size()); + bool success = !!QuickWriteFile(file.outputPath.c_str(), patch_data.data(), patch_data.size()); if (!success) { - Status(L"Update failed: Couldn't install %s (error %d)", - file.outputPath.c_str(), GetLastError()); + Status(L"Update failed: Couldn't install %s (error %d)", file.outputPath.c_str(), + GetLastError()); file.state = STATE_INSTALL_FAILED; return false; } @@ -1091,13 +1042,10 @@ static bool UpdateWorker() updateThreadFailed = true; return false; } else { - int position = (int)(((float)++installed / - (float)completedUpdates) * - 100.0f); + int position = (int)(((float)++installed / (float)completedUpdates) * 100.0f); if (position > lastPosition) { lastPosition = position; - SendDlgItemMessage(hwndMain, IDC_PROGRESS, - PBM_SETPOS, position, 0); + SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETPOS, position, 0); } } } @@ -1137,23 +1085,18 @@ static bool UpdateVSRedists() const DWORD compressionFlags = WINHTTP_DECOMPRESSION_FLAG_ALL; - HttpHandle hSession = WinHttpOpen(L"OBS Studio Updater/3.0", - WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, - WINHTTP_NO_PROXY_NAME, - WINHTTP_NO_PROXY_BYPASS, 0); + HttpHandle hSession = WinHttpOpen(L"OBS Studio Updater/3.0", WINHTTP_ACCESS_TYPE_AUTOMATIC_PROXY, + WINHTTP_NO_PROXY_NAME, WINHTTP_NO_PROXY_BYPASS, 0); if (!hSession) { Status(L"VC Redist Update failed: Couldn't create session"); return false; } - WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, - (LPVOID)&tlsProtocols, sizeof(tlsProtocols)); + WinHttpSetOption(hSession, WINHTTP_OPTION_SECURE_PROTOCOLS, (LPVOID)&tlsProtocols, sizeof(tlsProtocols)); - WinHttpSetOption(hSession, WINHTTP_OPTION_DECOMPRESSION, - (LPVOID)&compressionFlags, sizeof(compressionFlags)); + WinHttpSetOption(hSession, WINHTTP_OPTION_DECOMPRESSION, (LPVOID)&compressionFlags, sizeof(compressionFlags)); - HttpHandle hConnect = WinHttpConnect(hSession, kMSHostname, - INTERNET_DEFAULT_HTTPS_PORT, 0); + HttpHandle hConnect = WinHttpConnect(hSession, kMSHostname, INTERNET_DEFAULT_HTTPS_PORT, 0); if (!hConnect) { Status(L"Update failed: Couldn't connect to %S", kMSHostname); return false; @@ -1175,8 +1118,7 @@ static bool UpdateVSRedists() destPath += tempPath; destPath += L"\\VC_redist.x64.exe"; - if (!HTTPGetFile(hConnect, kVSRedistURL, destPath.c_str(), - L"Accept-Encoding: gzip", &responseCode)) { + if (!HTTPGetFile(hConnect, kVSRedistURL, destPath.c_str(), L"Accept-Encoding: gzip", &responseCode)) { DeleteFile(destPath.c_str()); Status(L"Update failed: Could not download " @@ -1215,15 +1157,13 @@ static bool UpdateVSRedists() * If verification succeeded, install redist */ wchar_t commandline[MAX_PATH + MAX_PATH]; - StringCbPrintf(commandline, sizeof(commandline), - L"%s /install /quiet /norestart", destPath.c_str()); + StringCbPrintf(commandline, sizeof(commandline), L"%s /install /quiet /norestart", destPath.c_str()); PROCESS_INFORMATION pi = {}; STARTUPINFO si = {}; si.cb = sizeof(si); - bool success = !!CreateProcessW(destPath.c_str(), commandline, nullptr, - nullptr, false, CREATE_NO_WINDOW, + bool success = !!CreateProcessW(destPath.c_str(), commandline, nullptr, nullptr, false, CREATE_NO_WINDOW, nullptr, nullptr, &si, &pi); if (success) { Status(L"Installing %s...", L"Visual C++ Redistributable"); @@ -1249,8 +1189,7 @@ static bool UpdateVSRedists() static void UpdateRegistryVersion(const Manifest &manifest) { - const char *regKey = - R"(Software\Microsoft\Windows\CurrentVersion\Uninstall\OBS Studio)"; + const char *regKey = R"(Software\Microsoft\Windows\CurrentVersion\Uninstall\OBS Studio)"; LSTATUS res; HKEY key; char version[32]; @@ -1258,38 +1197,30 @@ static void UpdateRegistryVersion(const Manifest &manifest) /* The manifest does not store a version string, so we gotta make one ourselves. */ if (manifest.beta || manifest.rc) { - formattedLen = sprintf_s( - version, sizeof(version), "%d.%d.%d-%s%d", - manifest.version_major, manifest.version_minor, - manifest.version_patch, manifest.beta ? "beta" : "rc", - manifest.beta ? manifest.beta : manifest.rc); + formattedLen = sprintf_s(version, sizeof(version), "%d.%d.%d-%s%d", manifest.version_major, + manifest.version_minor, manifest.version_patch, manifest.beta ? "beta" : "rc", + manifest.beta ? manifest.beta : manifest.rc); } else { - formattedLen = sprintf_s(version, sizeof(version), "%d.%d.%d", - manifest.version_major, - manifest.version_minor, - manifest.version_patch); + formattedLen = sprintf_s(version, sizeof(version), "%d.%d.%d", manifest.version_major, + manifest.version_minor, manifest.version_patch); } if (formattedLen <= 0) return; - res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, regKey, 0, - KEY_WRITE | KEY_WOW64_32KEY, &key); + res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, regKey, 0, KEY_WRITE | KEY_WOW64_32KEY, &key); if (res != ERROR_SUCCESS) return; - RegSetValueExA(key, "DisplayVersion", 0, REG_SZ, (const BYTE *)version, - formattedLen + 1); + RegSetValueExA(key, "DisplayVersion", 0, REG_SZ, (const BYTE *)version, formattedLen + 1); RegCloseKey(key); } static void ClearShaderCache() { wchar_t shader_path[MAX_PATH]; - SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, - shader_path); - StringCbCatW(shader_path, sizeof(shader_path), - L"\\obs-studio\\shader-cache"); + SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, shader_path); + StringCbCatW(shader_path, sizeof(shader_path), L"\\obs-studio\\shader-cache"); filesystem::remove_all(shader_path); } @@ -1300,8 +1231,7 @@ static bool Update(wchar_t *cmdLine) /* ------------------------------------- * * Check to make sure OBS isn't running */ - HANDLE hObsUpdateMutex = - OpenMutexW(SYNCHRONIZE, false, L"OBSStudioUpdateMutex"); + HANDLE hObsUpdateMutex = OpenMutexW(SYNCHRONIZE, false, L"OBSStudioUpdateMutex"); if (hObsUpdateMutex) { HANDLE hWait[2]; hWait[0] = hObsUpdateMutex; @@ -1325,10 +1255,8 @@ static bool Update(wchar_t *cmdLine) * Init crypt stuff */ CryptProvider hProvider; - if (!CryptAcquireContext(&hProvider, nullptr, MS_ENH_RSA_AES_PROV, - PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) { - SetDlgItemTextW(hwndMain, IDC_STATUS, - L"Update failed: CryptAcquireContext failure"); + if (!CryptAcquireContext(&hProvider, nullptr, MS_ENH_RSA_AES_PROV, PROV_RSA_AES, CRYPT_VERIFYCONTEXT)) { + SetDlgItemTextW(hwndMain, IDC_STATUS, L"Update failed: CryptAcquireContext failure"); return false; } @@ -1336,8 +1264,7 @@ static bool Update(wchar_t *cmdLine) /* ------------------------------------- */ - SetDlgItemTextW(hwndMain, IDC_STATUS, - L"Searching for available updates..."); + SetDlgItemTextW(hwndMain, IDC_STATUS, L"Searching for available updates..."); HWND hProgress = GetDlgItem(hwndMain, IDC_PROGRESS); LONG_PTR style = GetWindowLongPtr(hProgress, GWL_STYLE); @@ -1362,18 +1289,13 @@ static bool Update(wchar_t *cmdLine) // Legacy OBS bIsPortable = true; break; - } else if (wcsncmp(argv[i], L"--branch=", 9) == - 0) { + } else if (wcsncmp(argv[i], L"--branch=", 9) == 0) { branch = argv[i] + 9; - } else if (wcsncmp(argv[i], L"--appdata=", - 10) == 0) { + } else if (wcsncmp(argv[i], L"--appdata=", 10) == 0) { appdata = argv[i] + 10; - } else if (wcscmp(argv[i], L"--portable") == - 0) { + } else if (wcscmp(argv[i], L"--portable") == 0) { bIsPortable = true; - } else if (wcsncmp(argv[i], - L"--portable--branch=", - 19) == 0) { + } else if (wcsncmp(argv[i], L"--portable--branch=", 19) == 0) { /* Versions pre-29.1 beta 2 produce broken parameters :( */ bIsPortable = true; branch = argv[i] + 19; @@ -1390,14 +1312,11 @@ static bool Update(wchar_t *cmdLine) lpAppDataPath[0] = 0; if (bIsPortable) { - StringCbCopy(lpAppDataPath, sizeof(lpAppDataPath), - obs_base_directory); + StringCbCopy(lpAppDataPath, sizeof(lpAppDataPath), obs_base_directory); StringCbCat(lpAppDataPath, sizeof(lpAppDataPath), L"\\config"); } else { if (!appdata.empty()) { - HRESULT hr = StringCbCopy(lpAppDataPath, - sizeof(lpAppDataPath), - appdata.c_str()); + HRESULT hr = StringCbCopy(lpAppDataPath, sizeof(lpAppDataPath), appdata.c_str()); if (hr != S_OK) { Status(L"Update failed: Could not determine AppData " L"location"); @@ -1405,17 +1324,14 @@ static bool Update(wchar_t *cmdLine) } } else { CoTaskMemPtr pOut; - HRESULT hr = SHGetKnownFolderPath( - FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, - nullptr, &pOut); + HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, nullptr, &pOut); if (hr != S_OK) { Status(L"Update failed: Could not determine AppData " L"location"); return false; } - StringCbCopy(lpAppDataPath, sizeof(lpAppDataPath), - pOut); + StringCbCopy(lpAppDataPath, sizeof(lpAppDataPath), pOut); } } @@ -1430,16 +1346,13 @@ static bool Update(wchar_t *cmdLine) manifestPath[0] = 0; tempDirName[0] = 0; - StringCbPrintf(manifestPath, sizeof(manifestPath), - L"%s\\updates\\manifest.json", lpAppDataPath); + StringCbPrintf(manifestPath, sizeof(manifestPath), L"%s\\updates\\manifest.json", lpAppDataPath); if (!GetTempPathW(_countof(tempDirName), tempDirName)) { - Status(L"Update failed: Failed to get temp path: %ld", - GetLastError()); + Status(L"Update failed: Failed to get temp path: %ld", GetLastError()); return false; } if (!GetTempFileNameW(tempDirName, L"obs-studio", 0, tempPath)) { - Status(L"Update failed: Failed to create temp dir name: %ld", - GetLastError()); + Status(L"Update failed: Failed to create temp dir name: %ld", GetLastError()); return false; } @@ -1544,10 +1457,8 @@ static bool Update(wchar_t *cmdLine) compressedJson.resize(compressSize); - size_t result = - ZSTD_compress(compressedJson.data(), - compressedJson.size(), post_body.data(), - post_body.size(), ZSTD_CLEVEL_DEFAULT); + size_t result = ZSTD_compress(compressedJson.data(), compressedJson.size(), post_body.data(), + post_body.size(), ZSTD_CLEVEL_DEFAULT); if (ZSTD_isError(result)) return false; @@ -1559,11 +1470,9 @@ static bool Update(wchar_t *cmdLine) manifestUrl += L"?branch=" + branch; int responseCode; - bool success = !!HTTPPostData(manifestUrl.c_str(), - (BYTE *)compressedJson.data(), - (int)compressedJson.size(), - L"Accept-Encoding: gzip", - &responseCode, newManifest); + bool success = !!HTTPPostData(manifestUrl.c_str(), (BYTE *)compressedJson.data(), + (int)compressedJson.size(), L"Accept-Encoding: gzip", &responseCode, + newManifest); if (!success) return false; @@ -1586,8 +1495,7 @@ static bool Update(wchar_t *cmdLine) json patchManifest = json::parse(newManifest); patches = patchManifest.get(); } catch (json::exception &e) { - Status(L"Update failed: Couldn't parse patch manifest: %S", - e.what()); + Status(L"Update failed: Couldn't parse patch manifest: %S", e.what()); return false; } @@ -1649,9 +1557,8 @@ static bool Update(wchar_t *cmdLine) si.wShowWindow = SW_HIDE; PROCESS_INFORMATION pi; - bool success = !!CreateProcessW(nullptr, cmd, nullptr, nullptr, - false, CREATE_NEW_CONSOLE, - nullptr, nullptr, &si, &pi); + bool success = !!CreateProcessW(nullptr, cmd, nullptr, nullptr, false, CREATE_NEW_CONSOLE, nullptr, + nullptr, &si, &pi); if (success) { WaitForSingleObject(pi.hProcess, INFINITE); CloseHandle(pi.hThread); @@ -1666,13 +1573,11 @@ static bool Update(wchar_t *cmdLine) wchar_t tmp[MAX_PATH]; wchar_t tmp2[MAX_PATH]; - SHGetFolderPathW(nullptr, CSIDL_SYSTEM, nullptr, - SHGFP_TYPE_CURRENT, regsvr); + SHGetFolderPathW(nullptr, CSIDL_SYSTEM, nullptr, SHGFP_TYPE_CURRENT, regsvr); StringCbCat(regsvr, sizeof(regsvr), L"\\regsvr32.exe"); StringCbCopy(src, sizeof(src), obs_base_directory); - StringCbCat(src, sizeof(src), - L"\\data\\obs-plugins\\win-dshow\\"); + StringCbCat(src, sizeof(src), L"\\data\\obs-plugins\\win-dshow\\"); StringCbCopy(tmp, sizeof(tmp), L"\""); StringCbCat(tmp, sizeof(tmp), regsvr); @@ -1809,13 +1714,11 @@ static void LaunchOBS(LPWSTR lpCmdLine) ShellExecuteEx(&execInfo); } -static INT_PTR CALLBACK UpdateDialogProc(HWND hwnd, UINT message, WPARAM wParam, - LPARAM lParam) +static INT_PTR CALLBACK UpdateDialogProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { case WM_INITDIALOG: { - static HICON hMainIcon = - LoadIcon(hinstMain, MAKEINTRESOURCE(IDI_ICON1)); + static HICON hMainIcon = LoadIcon(hinstMain, MAKEINTRESOURCE(IDI_ICON1)); SendMessage(hwnd, WM_SETICON, ICON_BIG, (LPARAM)hMainIcon); SendMessage(hwnd, WM_SETICON, ICON_SMALL, (LPARAM)hMainIcon); return true; @@ -1824,8 +1727,7 @@ static INT_PTR CALLBACK UpdateDialogProc(HWND hwnd, UINT message, WPARAM wParam, case WM_COMMAND: if (LOWORD(wParam) == IDC_BUTTON) { if (HIWORD(wParam) == BN_CLICKED) { - DWORD result = - WaitForSingleObject(updateThread, 0); + DWORD result = WaitForSingleObject(updateThread, 0); if (result == WAIT_OBJECT_0) { if (updateFailed) PostQuitMessage(0); @@ -1858,8 +1760,7 @@ static int RestartAsAdmin(LPCWSTR lpCmdLine, LPCWSTR cwd) * AppData to the command line so we can load the correct manifest. */ wstring elevatedCmdLine(lpCmdLine); CoTaskMemPtr pOut; - HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, - KF_FLAG_DEFAULT, nullptr, &pOut); + HRESULT hr = SHGetKnownFolderPath(FOLDERID_RoamingAppData, KF_FLAG_DEFAULT, nullptr, &pOut); if (hr == S_OK) { elevatedCmdLine += L" \"--appdata="; elevatedCmdLine += pOut; @@ -1870,10 +1771,9 @@ static int RestartAsAdmin(LPCWSTR lpCmdLine, LPCWSTR cwd) shExInfo.cbSize = sizeof(shExInfo); shExInfo.fMask = SEE_MASK_NOCLOSEPROCESS; shExInfo.hwnd = nullptr; - shExInfo.lpVerb = L"runas"; /* Operation to perform */ - shExInfo.lpFile = myPath; /* Application to start */ - shExInfo.lpParameters = - elevatedCmdLine.c_str(); /* Additional parameters */ + shExInfo.lpVerb = L"runas"; /* Operation to perform */ + shExInfo.lpFile = myPath; /* Application to start */ + shExInfo.lpParameters = elevatedCmdLine.c_str(); /* Additional parameters */ shExInfo.lpDirectory = cwd; shExInfo.nShow = SW_NORMAL; shExInfo.hInstApp = nullptr; @@ -1904,9 +1804,8 @@ static bool HasElevation() BOOL elevated = false; BOOL success; - success = AllocateAndInitializeSid(&sia, 2, SECURITY_BUILTIN_DOMAIN_RID, - DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, - 0, 0, &sid); + success = AllocateAndInitializeSid(&sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &sid); if (success && sid) { CheckTokenMembership(nullptr, sid, &elevated); FreeSid(sid); @@ -1923,37 +1822,31 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) GetCurrentDirectoryW(_countof(cwd) - 1, cwd); if (!IsWindows10OrGreater()) { - MessageBox( - nullptr, - L"OBS Studio 28 and newer no longer support Windows 7," - L" Windows 8, or Windows 8.1. You can disable the" - L" following setting to opt out of future updates:" - L" Settings → General → General → Automatically check" - L" for updates on startup", - L"Unsupported Operating System", MB_ICONWARNING); + MessageBox(nullptr, + L"OBS Studio 28 and newer no longer support Windows 7," + L" Windows 8, or Windows 8.1. You can disable the" + L" following setting to opt out of future updates:" + L" Settings → General → General → Automatically check" + L" for updates on startup", + L"Unsupported Operating System", MB_ICONWARNING); return 0; } if (!HasElevation()) { - WinHandle hMutex = OpenMutex( - SYNCHRONIZE, false, L"OBSUpdaterRunningAsNonAdminUser"); + WinHandle hMutex = OpenMutex(SYNCHRONIZE, false, L"OBSUpdaterRunningAsNonAdminUser"); if (hMutex) { - MessageBox( - nullptr, - L"OBS Studio Updater must be run as an administrator.", - L"Updater Error", MB_ICONWARNING); + MessageBox(nullptr, L"OBS Studio Updater must be run as an administrator.", L"Updater Error", + MB_ICONWARNING); return 2; } - HANDLE hLowMutex = CreateMutexW( - nullptr, true, L"OBSUpdaterRunningAsNonAdminUser"); + HANDLE hLowMutex = CreateMutexW(nullptr, true, L"OBSUpdaterRunningAsNonAdminUser"); /* return code 1 = user wanted to launch OBS */ if (RestartAsAdmin(lpCmdLine, cwd) == 1) { StringCbCat(cwd, sizeof(cwd), L"\\..\\.."); - GetFullPathName(cwd, _countof(obs_base_directory), - obs_base_directory, nullptr); + GetFullPathName(cwd, _countof(obs_base_directory), obs_base_directory, nullptr); SetCurrentDirectory(obs_base_directory); LaunchOBS(lpCmdLine); @@ -1967,8 +1860,7 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) return 0; } else { StringCbCat(cwd, sizeof(cwd), L"\\..\\.."); - GetFullPathName(cwd, _countof(obs_base_directory), - obs_base_directory, nullptr); + GetFullPathName(cwd, _countof(obs_base_directory), obs_base_directory, nullptr); SetCurrentDirectory(obs_base_directory); hinstMain = hInstance; @@ -1978,9 +1870,7 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) InitCommonControlsEx(&icce); - hwndMain = CreateDialog(hInstance, - MAKEINTRESOURCE(IDD_UPDATEDIALOG), - nullptr, UpdateDialogProc); + hwndMain = CreateDialog(hInstance, MAKEINTRESOURCE(IDD_UPDATEDIALOG), nullptr, UpdateDialogProc); if (!hwndMain) { return -1; } @@ -1989,8 +1879,7 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) SetForegroundWindow(hwndMain); cancelRequested = CreateEvent(nullptr, true, false, nullptr); - updateThread = CreateThread(nullptr, 0, UpdateThread, lpCmdLine, - 0, nullptr); + updateThread = CreateThread(nullptr, 0, UpdateThread, lpCmdLine, 0, nullptr); MSG msg; while (GetMessage(&msg, nullptr, 0, 0)) { @@ -2002,8 +1891,7 @@ int WINAPI wWinMain(HINSTANCE hInstance, HINSTANCE, LPWSTR lpCmdLine, int) /* there is no non-elevated process waiting for us if UAC is * disabled */ - WinHandle hMutex = OpenMutex( - SYNCHRONIZE, false, L"OBSUpdaterRunningAsNonAdminUser"); + WinHandle hMutex = OpenMutex(SYNCHRONIZE, false, L"OBSUpdaterRunningAsNonAdminUser"); if (msg.wParam == 1 && !hMutex) { LaunchOBS(lpCmdLine); } diff --git a/UI/win-update/updater/updater.hpp b/UI/win-update/updater/updater.hpp index 0a779c83a..3e28f4ed4 100644 --- a/UI/win-update/updater/updater.hpp +++ b/UI/win-update/updater/updater.hpp @@ -78,14 +78,11 @@ using B2Hash = std::array; #include #include "resource.h" -bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, - const wchar_t *outputPath, const wchar_t *extraHeaders, +bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, const wchar_t *outputPath, const wchar_t *extraHeaders, int *responseCode); -bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, - const wchar_t *extraHeaders, std::vector &out, +bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, const wchar_t *extraHeaders, std::vector &out, int *responseCode); -bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, - const wchar_t *extraHeaders, int *responseCode, +bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, const wchar_t *extraHeaders, int *responseCode, std::string &response); void HashToString(const B2Hash &in, std::string &out); @@ -93,8 +90,7 @@ void StringToHash(const std::string &in, B2Hash &out); bool CalculateFileHash(const wchar_t *path, B2Hash &hash); -int ApplyPatch(ZSTD_DCtx *zstdCtx, const std::byte *patch_data, - size_t patch_size, const wchar_t *targetFile); +int ApplyPatch(ZSTD_DCtx *zstdCtx, const std::byte *patch_data, size_t patch_size, const wchar_t *targetFile); extern HWND hwndMain; extern HCRYPTPROV hProvider; diff --git a/UI/window-basic-about.cpp b/UI/window-basic-about.cpp index 4616475f9..3509e279b 100644 --- a/UI/window-basic-about.cpp +++ b/UI/window-basic-about.cpp @@ -26,8 +26,7 @@ OBSAbout::OBSAbout(QWidget *parent) : QDialog(parent), ui(new Ui::OBSAbout) #ifdef HAVE_OBSCONFIG_H ver += obs_get_version_string(); #else - ver += LIBOBS_API_MAJOR_VER + "." + LIBOBS_API_MINOR_VER + "." + - LIBOBS_API_PATCH_VER; + ver += LIBOBS_API_MAJOR_VER + "." + LIBOBS_API_MINOR_VER + "." + LIBOBS_API_PATCH_VER; #endif ui->version->setText(ver + bitness); @@ -37,9 +36,8 @@ OBSAbout::OBSAbout(QWidget *parent) : QDialog(parent), ui(new Ui::OBSAbout) if (steam) { delete ui->donate; } else { - ui->donate->setText( - "  " + - QTStr("About.Donate") + ""); + ui->donate->setText("  " + QTStr("About.Donate") + + ""); ui->donate->setTextInteractionFlags(Qt::TextBrowserInteraction); ui->donate->setOpenExternalLinks(true); } @@ -61,24 +59,18 @@ OBSAbout::OBSAbout(QWidget *parent) : QDialog(parent), ui(new Ui::OBSAbout) ui->license->setProperty("class", "bg-base"); ui->info->setProperty("class", ""); - connect(ui->about, &ClickableLabel::clicked, this, - &OBSAbout::ShowAbout); - connect(ui->authors, &ClickableLabel::clicked, this, - &OBSAbout::ShowAuthors); - connect(ui->license, &ClickableLabel::clicked, this, - &OBSAbout::ShowLicense); + connect(ui->about, &ClickableLabel::clicked, this, &OBSAbout::ShowAbout); + connect(ui->authors, &ClickableLabel::clicked, this, &OBSAbout::ShowAuthors); + connect(ui->license, &ClickableLabel::clicked, this, &OBSAbout::ShowLicense); QPointer about(this); OBSBasic *main = OBSBasic::Get(); if (main->patronJson.empty() && !main->patronJsonThread) { - RemoteTextThread *thread = new RemoteTextThread( - "https://obsproject.com/patreon/about-box.json", - "application/json"); - QObject::connect(thread, &RemoteTextThread::Result, main, - &OBSBasic::UpdatePatronJson); - QObject::connect(thread, &RemoteTextThread::Result, this, - &OBSAbout::ShowAbout); + RemoteTextThread *thread = + new RemoteTextThread("https://obsproject.com/patreon/about-box.json", "application/json"); + QObject::connect(thread, &RemoteTextThread::Result, main, &OBSBasic::UpdatePatronJson); + QObject::connect(thread, &RemoteTextThread::Result, this, &OBSAbout::ShowAbout); main->patronJsonThread.reset(thread); thread->start(); } else { @@ -134,9 +126,7 @@ void OBSAbout::ShowAbout() void OBSAbout::ShowAuthors() { std::string path; - QString error = - QTStr("About.Error") - .arg("https://github.com/obsproject/obs-studio/blob/master/AUTHORS"); + QString error = QTStr("About.Error").arg("https://github.com/obsproject/obs-studio/blob/master/AUTHORS"); #ifdef __APPLE__ if (!GetDataFilePath("AUTHORS", path)) { @@ -162,9 +152,7 @@ void OBSAbout::ShowAuthors() void OBSAbout::ShowLicense() { std::string path; - QString error = - QTStr("About.Error") - .arg("https://github.com/obsproject/obs-studio/blob/master/COPYING"); + QString error = QTStr("About.Error").arg("https://github.com/obsproject/obs-studio/blob/master/COPYING"); if (!GetDataFilePath("license/gplv2.txt", path)) { ui->textBrowser->setPlainText(error); diff --git a/UI/window-basic-adv-audio.cpp b/UI/window-basic-adv-audio.cpp index b93fe3b14..001b804d7 100644 --- a/UI/window-basic-adv-audio.cpp +++ b/UI/window-basic-adv-audio.cpp @@ -9,22 +9,17 @@ Q_DECLARE_METATYPE(OBSSource); -OBSBasicAdvAudio::OBSBasicAdvAudio(QWidget *parent) - : QDialog(parent), - ui(new Ui::OBSAdvAudio), - showInactive(false) +OBSBasicAdvAudio::OBSBasicAdvAudio(QWidget *parent) : QDialog(parent), ui(new Ui::OBSAdvAudio), showInactive(false) { ui->setupUi(this); signal_handler_t *sh = obs_get_signal_handler(); sigs.emplace_back(sh, "source_audio_activate", OBSSourceAdded, this); - sigs.emplace_back(sh, "source_audio_deactivate", OBSSourceRemoved, - this); + sigs.emplace_back(sh, "source_audio_deactivate", OBSSourceRemoved, this); sigs.emplace_back(sh, "source_activate", OBSSourceActivated, this); sigs.emplace_back(sh, "source_deactivate", OBSSourceRemoved, this); - VolumeType volType = (VolumeType)config_get_int( - App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType"); + VolumeType volType = (VolumeType)config_get_int(App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType"); if (volType == VolumeType::Percent) ui->usePercent->setChecked(true); @@ -54,8 +49,7 @@ bool OBSBasicAdvAudio::EnumSources(void *param, obs_source_t *source) uint32_t flags = obs_source_get_output_flags(source); if ((flags & OBS_SOURCE_AUDIO) != 0 && - (dialog->showInactive || - (obs_source_active(source) && obs_source_audio_active(source)))) + (dialog->showInactive || (obs_source_active(source) && obs_source_audio_active(source)))) dialog->AddAudioSource(source); return true; @@ -65,16 +59,15 @@ void OBSBasicAdvAudio::OBSSourceAdded(void *param, calldata_t *calldata) { OBSSource source((obs_source_t *)calldata_ptr(calldata, "source")); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceAdded", Q_ARG(OBSSource, source)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceAdded", Q_ARG(OBSSource, source)); } void OBSBasicAdvAudio::OBSSourceRemoved(void *param, calldata_t *calldata) { OBSSource source((obs_source_t *)calldata_ptr(calldata, "source")); - QMetaObject::invokeMethod(reinterpret_cast(param), - "SourceRemoved", Q_ARG(OBSSource, source)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceRemoved", + Q_ARG(OBSSource, source)); } void OBSBasicAdvAudio::OBSSourceActivated(void *param, calldata_t *calldata) @@ -82,9 +75,8 @@ void OBSBasicAdvAudio::OBSSourceActivated(void *param, calldata_t *calldata) OBSSource source((obs_source_t *)calldata_ptr(calldata, "source")); if (obs_source_audio_active(source)) - QMetaObject::invokeMethod( - reinterpret_cast(param), - "SourceAdded", Q_ARG(OBSSource, source)); + QMetaObject::invokeMethod(reinterpret_cast(param), "SourceAdded", + Q_ARG(OBSSource, source)); } inline void OBSBasicAdvAudio::AddAudioSource(obs_source_t *source) @@ -140,8 +132,7 @@ void OBSBasicAdvAudio::on_usePercent_toggled(bool checked) for (size_t i = 0; i < controls.size(); i++) controls[i]->SetVolumeWidget(type); - config_set_int(App()->GetUserConfig(), "BasicWindow", - "AdvAudioVolumeType", (int)type); + config_set_int(App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType", (int)type); } void OBSBasicAdvAudio::on_activeOnly_toggled(bool checked) @@ -167,19 +158,14 @@ void OBSBasicAdvAudio::SetShowInactive(bool show) SetIconsVisible(showVisible); } else { - sigs.emplace_back(sh, "source_audio_activate", OBSSourceAdded, - this); - sigs.emplace_back(sh, "source_audio_deactivate", - OBSSourceRemoved, this); - sigs.emplace_back(sh, "source_activate", OBSSourceActivated, - this); - sigs.emplace_back(sh, "source_deactivate", OBSSourceRemoved, - this); + sigs.emplace_back(sh, "source_audio_activate", OBSSourceAdded, this); + sigs.emplace_back(sh, "source_audio_deactivate", OBSSourceRemoved, this); + sigs.emplace_back(sh, "source_activate", OBSSourceActivated, this); + sigs.emplace_back(sh, "source_deactivate", OBSSourceRemoved, this); for (size_t i = 0; i < controls.size(); i++) { const auto source = controls[i]->GetSource(); - if (!(obs_source_active(source) && - obs_source_audio_active(source))) { + if (!(obs_source_active(source) && obs_source_audio_active(source))) { delete controls[i]; controls.erase(controls.begin() + i); i--; diff --git a/UI/window-basic-auto-config-test.cpp b/UI/window-basic-auto-config-test.cpp index b1962d455..b53f37aa2 100644 --- a/UI/window-basic-auto-config-test.cpp +++ b/UI/window-basic-auto-config-test.cpp @@ -29,16 +29,14 @@ class TestMode { static void render_rand(void *, uint32_t cx, uint32_t cy) { gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID); - gs_eparam_t *randomvals[3] = { - gs_effect_get_param_by_name(solid, "randomvals1"), - gs_effect_get_param_by_name(solid, "randomvals2"), - gs_effect_get_param_by_name(solid, "randomvals3")}; + gs_eparam_t *randomvals[3] = {gs_effect_get_param_by_name(solid, "randomvals1"), + gs_effect_get_param_by_name(solid, "randomvals2"), + gs_effect_get_param_by_name(solid, "randomvals3")}; struct vec4 r; for (int i = 0; i < 3; i++) { - vec4_set(&r, rand_float(true) * 100.0f, - rand_float(true) * 100.0f, + vec4_set(&r, rand_float(true) * 100.0f, rand_float(true) * 100.0f, rand_float(true) * 50000.0f + 10000.0f, 0.0f); gs_effect_set_vec4(randomvals[i], &r); } @@ -156,12 +154,10 @@ static inline void string_depad_key(string &key) const char *FindAudioEncoderFromCodec(const char *type); -static inline bool can_use_output(const char *prot, const char *output, - const char *prot_test1, +static inline bool can_use_output(const char *prot, const char *output, const char *prot_test1, const char *prot_test2 = nullptr) { - return (strcmp(prot, prot_test1) == 0 || - (prot_test2 && strcmp(prot, prot_test2) == 0)) && + return (strcmp(prot, prot_test1) == 0 || (prot_test2 && strcmp(prot, prot_test2) == 0)) && (obs_get_output_flags(output) & OBS_OUTPUT_SERVICE) != 0; } @@ -189,21 +185,16 @@ void AutoConfigTestPage::TestBandwidthThread() * test for 10 seconds */ - QMetaObject::invokeMethod(this, "UpdateMessage", - Q_ARG(QString, QStringLiteral(""))); + QMetaObject::invokeMethod(this, "UpdateMessage", Q_ARG(QString, QStringLiteral(""))); /* -----------------------------------*/ /* create obs objects */ - const char *serverType = wiz->customServer ? "rtmp_custom" - : "rtmp_common"; + const char *serverType = wiz->customServer ? "rtmp_custom" : "rtmp_common"; - OBSEncoderAutoRelease vencoder = obs_video_encoder_create( - "obs_x264", "test_x264", nullptr, nullptr); - OBSEncoderAutoRelease aencoder = obs_audio_encoder_create( - "ffmpeg_aac", "test_aac", nullptr, 0, nullptr); - OBSServiceAutoRelease service = obs_service_create( - serverType, "test_service", nullptr, nullptr); + OBSEncoderAutoRelease vencoder = obs_video_encoder_create("obs_x264", "test_x264", nullptr, nullptr); + OBSEncoderAutoRelease aencoder = obs_audio_encoder_create("ffmpeg_aac", "test_aac", nullptr, 0, nullptr); + OBSServiceAutoRelease service = obs_service_create(serverType, "test_service", nullptr, nullptr); /* -----------------------------------*/ /* configure settings */ @@ -221,18 +212,15 @@ void AutoConfigTestPage::TestBandwidthThread() OBSDataAutoRelease output_settings = obs_data_create(); std::string key = wiz->key; - if (wiz->service == AutoConfig::Service::Twitch || - wiz->service == AutoConfig::Service::AmazonIVS) { + if (wiz->service == AutoConfig::Service::Twitch || wiz->service == AutoConfig::Service::AmazonIVS) { string_depad_key(key); key += "?bandwidthtest"; - } else if (wiz->serviceName == "Restream.io" || - wiz->serviceName == "Restream.io - RTMP") { + } else if (wiz->serviceName == "Restream.io" || wiz->serviceName == "Restream.io - RTMP") { string_depad_key(key); key += "?test=true"; } - obs_data_set_string(service_settings, "service", - wiz->serviceName.c_str()); + obs_data_set_string(service_settings, "service", wiz->serviceName.c_str()); obs_data_set_string(service_settings, "key", key.c_str()); obs_data_set_int(vencoder_settings, "bitrate", wiz->startingBitrate); @@ -243,12 +231,10 @@ void AutoConfigTestPage::TestBandwidthThread() obs_data_set_int(aencoder_settings, "bitrate", 32); OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); - const char *bind_ip = - config_get_string(main->Config(), "Output", "BindIP"); + const char *bind_ip = config_get_string(main->Config(), "Output", "BindIP"); obs_data_set_string(output_settings, "bind_ip", bind_ip); - const char *ip_family = - config_get_string(main->Config(), "Output", "IPFamily"); + const char *ip_family = config_get_string(main->Config(), "Output", "IPFamily"); obs_data_set_string(output_settings, "ip_family", ip_family); /* -----------------------------------*/ @@ -262,15 +248,11 @@ void AutoConfigTestPage::TestBandwidthThread() /* just use the first server if it only has one alternate server, * or if using Restream or Nimo TV due to their "auto" servers */ - if (servers.size() < 3 || - wiz->serviceName.substr(0, 11) == "Restream.io" || - wiz->serviceName == "Nimo TV") { + if (servers.size() < 3 || wiz->serviceName.substr(0, 11) == "Restream.io" || wiz->serviceName == "Nimo TV") { servers.resize(1); - } else if ((wiz->service == AutoConfig::Service::Twitch && - wiz->twitchAuto) || - (wiz->service == AutoConfig::Service::AmazonIVS && - wiz->amazonIVSAuto)) { + } else if ((wiz->service == AutoConfig::Service::Twitch && wiz->twitchAuto) || + (wiz->service == AutoConfig::Service::AmazonIVS && wiz->amazonIVSAuto)) { /* if using Twitch and "Auto" is available, test 3 closest * server */ servers.erase(servers.begin() + 1); @@ -281,27 +263,22 @@ void AutoConfigTestPage::TestBandwidthThread() } if (!wiz->serviceConfigServers.empty()) { - if (wiz->service == AutoConfig::Service::Twitch && - wiz->twitchAuto) { + if (wiz->service == AutoConfig::Service::Twitch && wiz->twitchAuto) { // servers from Twitch service config replace the "auto" entry servers.erase(servers.begin()); } - for (auto it = std::rbegin(wiz->serviceConfigServers); - it != std::rend(wiz->serviceConfigServers); it++) { - auto same_server = std::find_if( - std::begin(servers), std::end(servers), - [&](const ServerInfo &si) { - return si.address == it->address; - }); + for (auto it = std::rbegin(wiz->serviceConfigServers); it != std::rend(wiz->serviceConfigServers); + it++) { + auto same_server = + std::find_if(std::begin(servers), std::end(servers), + [&](const ServerInfo &si) { return si.address == it->address; }); if (same_server != std::end(servers)) servers.erase(same_server); - servers.emplace(std::begin(servers), it->name.c_str(), - it->address.c_str()); + servers.emplace(std::begin(servers), it->name.c_str(), it->address.c_str()); } - if (wiz->service == AutoConfig::Service::Twitch && - wiz->twitchAuto) { + if (wiz->service == AutoConfig::Service::Twitch && wiz->twitchAuto) { // see above, only test 3 servers // rtmps urls are currently counted as separate servers servers.resize(3); @@ -312,59 +289,48 @@ void AutoConfigTestPage::TestBandwidthThread() /* apply service settings */ obs_service_update(service, service_settings); - obs_service_apply_encoder_settings(service, vencoder_settings, - aencoder_settings); + obs_service_apply_encoder_settings(service, vencoder_settings, aencoder_settings); if (wiz->multitrackVideo.testSuccessful) { - obs_data_set_int(vencoder_settings, "bitrate", - wiz->startingBitrate); + obs_data_set_int(vencoder_settings, "bitrate", wiz->startingBitrate); } /* -----------------------------------*/ /* create output */ /* Check if the service has a preferred output type */ - const char *output_type = - obs_service_get_preferred_output_type(service); - if (!output_type || - (obs_get_output_flags(output_type) & OBS_OUTPUT_SERVICE) == 0) { + const char *output_type = obs_service_get_preferred_output_type(service); + if (!output_type || (obs_get_output_flags(output_type) & OBS_OUTPUT_SERVICE) == 0) { /* Otherwise, prefer first-party output types */ const char *protocol = obs_service_get_protocol(service); if (can_use_output(protocol, "rtmp_output", "RTMP", "RTMPS")) { output_type = "rtmp_output"; - } else if (can_use_output(protocol, "ffmpeg_hls_muxer", - "HLS")) { + } else if (can_use_output(protocol, "ffmpeg_hls_muxer", "HLS")) { output_type = "ffmpeg_hls_muxer"; - } else if (can_use_output(protocol, "ffmpeg_mpegts_muxer", - "SRT", "RIST")) { + } else if (can_use_output(protocol, "ffmpeg_mpegts_muxer", "SRT", "RIST")) { output_type = "ffmpeg_mpegts_muxer"; } /* If third-party protocol, use the first enumerated type */ if (!output_type) - obs_enum_output_types_with_protocol( - protocol, &output_type, return_first_id); + obs_enum_output_types_with_protocol(protocol, &output_type, return_first_id); /* If none, fail */ if (!output_type) { - QMetaObject::invokeMethod( - this, "Failure", - Q_ARG(QString, QTStr(TEST_BW_NO_OUTPUT))); + QMetaObject::invokeMethod(this, "Failure", Q_ARG(QString, QTStr(TEST_BW_NO_OUTPUT))); return; } } - OBSOutputAutoRelease output = - obs_output_create(output_type, "test_stream", nullptr, nullptr); + OBSOutputAutoRelease output = obs_output_create(output_type, "test_stream", nullptr, nullptr); obs_output_update(output, output_settings); const char *audio_codec = obs_output_get_supported_audio_codecs(output); if (strcmp(audio_codec, "aac") != 0) { const char *id = FindAudioEncoderFromCodec(audio_codec); - aencoder = obs_audio_encoder_create(id, "test_audio", nullptr, - 0, nullptr); + aencoder = obs_audio_encoder_create(id, "test_audio", nullptr, 0, nullptr); } /* -----------------------------------*/ @@ -402,14 +368,12 @@ void AutoConfigTestPage::TestBandwidthThread() using on_stopped_t = decltype(on_stopped); auto pre_on_started = [](void *data, calldata_t *) { - on_started_t &on_started = - *reinterpret_cast(data); + on_started_t &on_started = *reinterpret_cast(data); on_started(); }; auto pre_on_stopped = [](void *data, calldata_t *) { - on_stopped_t &on_stopped = - *reinterpret_cast(data); + on_stopped_t &on_stopped = *reinterpret_cast(data); on_stopped(); }; @@ -430,13 +394,10 @@ void AutoConfigTestPage::TestBandwidthThread() int per = int((i + 1) * 100 / servers.size()); QMetaObject::invokeMethod(this, "Progress", Q_ARG(int, per)); - QMetaObject::invokeMethod( - this, "UpdateMessage", - Q_ARG(QString, QTStr(TEST_BW_CONNECTING) - .arg(server.name.c_str()))); + QMetaObject::invokeMethod(this, "UpdateMessage", + Q_ARG(QString, QTStr(TEST_BW_CONNECTING).arg(server.name.c_str()))); - obs_data_set_string(service_settings, "server", - server.address.c_str()); + obs_data_set_string(service_settings, "server", server.address.c_str()); obs_service_update(service, service_settings); if (!obs_output_start(output)) @@ -458,10 +419,8 @@ void AutoConfigTestPage::TestBandwidthThread() if (!connected) continue; - QMetaObject::invokeMethod( - this, "UpdateMessage", - Q_ARG(QString, - QTStr(TEST_BW_SERVER).arg(server.name.c_str()))); + QMetaObject::invokeMethod(this, "UpdateMessage", + Q_ARG(QString, QTStr(TEST_BW_SERVER).arg(server.name.c_str()))); /* ignore first 2.5 seconds due to possible buffering skewing * the result */ @@ -494,13 +453,9 @@ void AutoConfigTestPage::TestBandwidthThread() if (total_time == 0) total_time = 1; - int total_bytes = - (int)obs_output_get_total_bytes(output) - start_bytes; - uint64_t bitrate = util_mul_div64( - total_bytes, 8ULL * 1000000000ULL / 1000ULL, - total_time); - if (obs_output_get_frames_dropped(output) || - (int)bitrate < (wiz->startingBitrate * 75 / 100)) { + int total_bytes = (int)obs_output_get_total_bytes(output) - start_bytes; + uint64_t bitrate = util_mul_div64(total_bytes, 8ULL * 1000000000ULL / 1000ULL, total_time); + if (obs_output_get_frames_dropped(output) || (int)bitrate < (wiz->startingBitrate * 75 / 100)) { server.bitrate = (int)bitrate * 70 / 100; } else { server.bitrate = wiz->startingBitrate; @@ -511,9 +466,7 @@ void AutoConfigTestPage::TestBandwidthThread() } if (!success) { - QMetaObject::invokeMethod(this, "Failure", - Q_ARG(QString, - QTStr(TEST_BW_CONNECT_FAIL))); + QMetaObject::invokeMethod(this, "Failure", Q_ARG(QString, QTStr(TEST_BW_CONNECT_FAIL))); return; } @@ -525,8 +478,7 @@ void AutoConfigTestPage::TestBandwidthThread() for (auto &server : servers) { bool close = abs(server.bitrate - bestBitrate) < 400; - if ((!close && server.bitrate > bestBitrate) || - (close && server.ms < bestMS)) { + if ((!close && server.bitrate > bestBitrate) || (close && server.ms < bestMS)) { bestServer = server.address; bestServerName = server.name; bestBitrate = server.bitrate; @@ -557,8 +509,7 @@ static long double EstimateMinBitrate(int cx, int cy, int fps_num, int fps_den) return EstimateBitrateVal(cx, cy, fps_num, fps_den) / val; } -static long double EstimateUpperBitrate(int cx, int cy, int fps_num, - int fps_den) +static long double EstimateUpperBitrate(int cx, int cy, int fps_num, int fps_den) { long double val = EstimateBitrateVal(1280, 720, 30, 1) / 3000.0l; return EstimateBitrateVal(cx, cy, fps_num, fps_den) / val; @@ -590,8 +541,7 @@ static void CalcBaseRes(int &baseCX, int &baseCY) * for 16:9 resolutions this will always change the starting value to * 1920x1080 */ if ((baseCX * baseCY) > maxBaseArea) { - long double xyAspect = - (long double)baseCX / (long double)baseCY; + long double xyAspect = (long double)baseCX / (long double)baseCY; baseCY = (int)sqrt((long double)clipResArea / xyAspect); baseCX = (int)((long double)baseCY * xyAspect); } @@ -600,18 +550,14 @@ static void CalcBaseRes(int &baseCX, int &baseCY) bool AutoConfigTestPage::TestSoftwareEncoding() { TestMode testMode; - QMetaObject::invokeMethod(this, "UpdateMessage", - Q_ARG(QString, QStringLiteral(""))); + QMetaObject::invokeMethod(this, "UpdateMessage", Q_ARG(QString, QStringLiteral(""))); /* -----------------------------------*/ /* create obs objects */ - OBSEncoderAutoRelease vencoder = obs_video_encoder_create( - "obs_x264", "test_x264", nullptr, nullptr); - OBSEncoderAutoRelease aencoder = obs_audio_encoder_create( - "ffmpeg_aac", "test_aac", nullptr, 0, nullptr); - OBSOutputAutoRelease output = - obs_output_create("null_output", "null", nullptr, nullptr); + OBSEncoderAutoRelease vencoder = obs_video_encoder_create("obs_x264", "test_x264", nullptr, nullptr); + OBSEncoderAutoRelease aencoder = obs_audio_encoder_create("ffmpeg_aac", "test_aac", nullptr, 0, nullptr); + OBSOutputAutoRelease output = obs_output_create("null_output", "null", nullptr, nullptr); /* -----------------------------------*/ /* configure settings */ @@ -622,8 +568,7 @@ bool AutoConfigTestPage::TestSoftwareEncoding() if (wiz->type != AutoConfig::Type::Recording) { obs_data_set_int(vencoder_settings, "keyint_sec", 2); - obs_data_set_int(vencoder_settings, "bitrate", - wiz->idealBitrate); + obs_data_set_int(vencoder_settings, "bitrate", wiz->idealBitrate); obs_data_set_string(vencoder_settings, "rate_control", "CBR"); obs_data_set_string(vencoder_settings, "profile", "main"); obs_data_set_string(vencoder_settings, "preset", "veryfast"); @@ -657,8 +602,7 @@ bool AutoConfigTestPage::TestSoftwareEncoding() using on_stopped_t = decltype(on_stopped); auto pre_on_stopped = [](void *data, calldata_t *) { - on_stopped_t &on_stopped = - *reinterpret_cast(data); + on_stopped_t &on_stopped = *reinterpret_cast(data); on_stopped(); }; @@ -720,8 +664,7 @@ bool AutoConfigTestPage::TestSoftwareEncoding() long double fps = ((long double)fps_num / (long double)fps_den); - int cx = int(((long double)baseCX / (long double)baseCY) * - (long double)cy); + int cx = int(((long double)baseCX / (long double)baseCY) * (long double)cy); if (!force && wiz->type != AutoConfig::Type::Recording) { int est = EstimateMinBitrate(cx, cy, fps_num, fps_den); @@ -744,22 +687,17 @@ bool AutoConfigTestPage::TestSoftwareEncoding() QString cxStr = QString::number(cx); QString cyStr = QString::number(cy); - QString fpsStr = (fps_den > 1) ? QString::number(fps, 'f', 2) - : QString::number(fps, 'g', 2); + QString fpsStr = (fps_den > 1) ? QString::number(fps, 'f', 2) : QString::number(fps, 'g', 2); - QMetaObject::invokeMethod( - this, "UpdateMessage", - Q_ARG(QString, - QTStr(TEST_RES_VAL).arg(cxStr, cyStr, fpsStr))); + QMetaObject::invokeMethod(this, "UpdateMessage", + Q_ARG(QString, QTStr(TEST_RES_VAL).arg(cxStr, cyStr, fpsStr))); unique_lock ul(m); if (cancel) return false; if (!obs_output_start(output)) { - QMetaObject::invokeMethod(this, "Failure", - Q_ARG(QString, - QTStr(TEST_RES_FAIL))); + QMetaObject::invokeMethod(this, "Failure", Q_ARG(QString, QTStr(TEST_RES_FAIL))); return false; } @@ -768,8 +706,7 @@ bool AutoConfigTestPage::TestSoftwareEncoding() obs_output_stop(output); cv.wait(ul); - int skipped = - (int)video_output_get_skipped_frames(obs_get_video()); + int skipped = (int)video_output_get_skipped_frames(obs_get_video()); if (force || skipped <= 10) results.emplace_back(cx, cy, fps_num, fps_den); @@ -846,8 +783,7 @@ bool AutoConfigTestPage::TestSoftwareEncoding() wiz->idealFPSNum = result.fps_num; wiz->idealFPSDen = result.fps_den; - long double fUpperBitrate = EstimateUpperBitrate( - result.cx, result.cy, result.fps_num, result.fps_den); + long double fUpperBitrate = EstimateUpperBitrate(result.cx, result.cy, result.fps_num, result.fps_den); int upperBitrate = int(floor(fUpperBitrate / 50.0l) * 50.0l); @@ -897,8 +833,7 @@ void AutoConfigTestPage::FindIdealHardwareResolution() long double fps = ((long double)fps_num / (long double)fps_den); - int cx = int(((long double)baseCX / (long double)baseCY) * - (long double)cy); + int cx = int(((long double)baseCX / (long double)baseCY) * (long double)cy); long double rate = (long double)cx * (long double)cy * fps; if (!force && rate > maxDataRate) @@ -1015,8 +950,7 @@ void AutoConfigTestPage::TestRecordingEncoderThread() } } - if (wiz->type == AutoConfig::Type::Recording && - wiz->hardwareEncodingAvailable) + if (wiz->type == AutoConfig::Type::Recording && wiz->hardwareEncodingAvailable) FindIdealHardwareResolution(); wiz->recordingQuality = AutoConfig::Quality::High; @@ -1056,8 +990,7 @@ void AutoConfigTestPage::TestRecordingEncoderThread() #define QUALITY_SAME "Basic.Settings.Output.Simple.RecordingQuality.Stream" #define QUALITY_HIGH "Basic.Settings.Output.Simple.RecordingQuality.Small" -void set_closest_res(int &cx, int &cy, struct obs_service_resolution *res_list, - size_t count) +void set_closest_res(int &cx, int &cy, struct obs_service_resolution *res_list, size_t count) { int best_pixel_diff = 0x7FFFFFFF; int start_cx = cx; @@ -1108,99 +1041,71 @@ void AutoConfigTestPage::FinalizeResults() }; if (wiz->type == AutoConfig::Type::Streaming) { - const char *serverType = wiz->customServer ? "rtmp_custom" - : "rtmp_common"; + const char *serverType = wiz->customServer ? "rtmp_custom" : "rtmp_common"; - OBSServiceAutoRelease service = obs_service_create( - serverType, "temp_service", nullptr, nullptr); + OBSServiceAutoRelease service = obs_service_create(serverType, "temp_service", nullptr, nullptr); OBSDataAutoRelease service_settings = obs_data_create(); OBSDataAutoRelease vencoder_settings = obs_data_create(); - if (wiz->testMultitrackVideo && - wiz->multitrackVideo.testSuccessful && + if (wiz->testMultitrackVideo && wiz->multitrackVideo.testSuccessful && !wiz->multitrackVideo.bitrate.has_value()) wiz->multitrackVideo.bitrate = wiz->idealBitrate; - obs_data_set_int(vencoder_settings, "bitrate", - wiz->idealBitrate); + obs_data_set_int(vencoder_settings, "bitrate", wiz->idealBitrate); - obs_data_set_string(service_settings, "service", - wiz->serviceName.c_str()); + obs_data_set_string(service_settings, "service", wiz->serviceName.c_str()); obs_service_update(service, service_settings); - obs_service_apply_encoder_settings(service, vencoder_settings, - nullptr); + obs_service_apply_encoder_settings(service, vencoder_settings, nullptr); BPtr res_list; size_t res_count; int maxFPS; - obs_service_get_supported_resolutions(service, &res_list, - &res_count); + obs_service_get_supported_resolutions(service, &res_list, &res_count); obs_service_get_max_fps(service, &maxFPS); if (res_list) { - set_closest_res(wiz->idealResolutionCX, - wiz->idealResolutionCY, res_list, - res_count); + set_closest_res(wiz->idealResolutionCX, wiz->idealResolutionCY, res_list, res_count); } if (maxFPS) { - double idealFPS = (double)wiz->idealFPSNum / - (double)wiz->idealFPSDen; + double idealFPS = (double)wiz->idealFPSNum / (double)wiz->idealFPSDen; if (idealFPS > (double)maxFPS) { wiz->idealFPSNum = maxFPS; wiz->idealFPSDen = 1; } } - wiz->idealBitrate = - (int)obs_data_get_int(vencoder_settings, "bitrate"); + wiz->idealBitrate = (int)obs_data_get_int(vencoder_settings, "bitrate"); if (!wiz->customServer) - form->addRow( - newLabel("Basic.AutoConfig.StreamPage.Service"), - new QLabel(wiz->serviceName.c_str(), - ui->finishPage)); + form->addRow(newLabel("Basic.AutoConfig.StreamPage.Service"), + new QLabel(wiz->serviceName.c_str(), ui->finishPage)); form->addRow(newLabel("Basic.AutoConfig.StreamPage.Server"), - new QLabel(wiz->serverName.c_str(), - ui->finishPage)); - form->addRow( - newLabel("Basic.Settings.Stream.MultitrackVideoLabel"), - newLabel(wiz->multitrackVideo.testSuccessful ? "Yes" - : "No")); + new QLabel(wiz->serverName.c_str(), ui->finishPage)); + form->addRow(newLabel("Basic.Settings.Stream.MultitrackVideoLabel"), + newLabel(wiz->multitrackVideo.testSuccessful ? "Yes" : "No")); if (wiz->multitrackVideo.testSuccessful) { - form->addRow( - newLabel("Basic.Settings.Output.VideoBitrate"), - newLabel("Automatic")); - form->addRow(newLabel(TEST_RESULT_SE), + form->addRow(newLabel("Basic.Settings.Output.VideoBitrate"), newLabel("Automatic")); + form->addRow(newLabel(TEST_RESULT_SE), newLabel("Automatic")); + form->addRow(newLabel("Basic.AutoConfig.TestPage.Result.StreamingResolution"), newLabel("Automatic")); - form->addRow( - newLabel( - "Basic.AutoConfig.TestPage.Result.StreamingResolution"), - newLabel("Automatic")); } else { - form->addRow( - newLabel("Basic.Settings.Output.VideoBitrate"), - new QLabel(QString::number(wiz->idealBitrate), - ui->finishPage)); + form->addRow(newLabel("Basic.Settings.Output.VideoBitrate"), + new QLabel(QString::number(wiz->idealBitrate), ui->finishPage)); form->addRow(newLabel(TEST_RESULT_SE), - new QLabel(encName(wiz->streamingEncoder), - ui->finishPage)); + new QLabel(encName(wiz->streamingEncoder), ui->finishPage)); } } QString baseRes = - QString("%1x%2").arg(QString::number(wiz->baseResolutionCX), - QString::number(wiz->baseResolutionCY)); + QString("%1x%2").arg(QString::number(wiz->baseResolutionCX), QString::number(wiz->baseResolutionCY)); QString scaleRes = - QString("%1x%2").arg(QString::number(wiz->idealResolutionCX), - QString::number(wiz->idealResolutionCY)); + QString("%1x%2").arg(QString::number(wiz->idealResolutionCX), QString::number(wiz->idealResolutionCY)); if (wiz->recordingEncoder != AutoConfig::Encoder::Stream || wiz->recordingQuality != AutoConfig::Quality::Stream) - form->addRow(newLabel(TEST_RESULT_RE), - new QLabel(encName(wiz->recordingEncoder), - ui->finishPage)); + form->addRow(newLabel(TEST_RESULT_RE), new QLabel(encName(wiz->recordingEncoder), ui->finishPage)); QString recQuality; @@ -1213,29 +1118,21 @@ void AutoConfigTestPage::FinalizeResults() break; } - form->addRow(newLabel("Basic.Settings.Output.Simple.RecordingQuality"), - new QLabel(recQuality, ui->finishPage)); + form->addRow(newLabel("Basic.Settings.Output.Simple.RecordingQuality"), new QLabel(recQuality, ui->finishPage)); - long double fps = - (long double)wiz->idealFPSNum / (long double)wiz->idealFPSDen; + long double fps = (long double)wiz->idealFPSNum / (long double)wiz->idealFPSDen; - QString fpsStr = (wiz->idealFPSDen > 1) ? QString::number(fps, 'f', 2) - : QString::number(fps, 'g', 2); + QString fpsStr = (wiz->idealFPSDen > 1) ? QString::number(fps, 'f', 2) : QString::number(fps, 'g', 2); - form->addRow(newLabel("Basic.Settings.Video.BaseResolution"), - new QLabel(baseRes, ui->finishPage)); - form->addRow(newLabel("Basic.Settings.Video.ScaledResolution"), - new QLabel(scaleRes, ui->finishPage)); - form->addRow(newLabel("Basic.Settings.Video.FPS"), - new QLabel(fpsStr, ui->finishPage)); + form->addRow(newLabel("Basic.Settings.Video.BaseResolution"), new QLabel(baseRes, ui->finishPage)); + form->addRow(newLabel("Basic.Settings.Video.ScaledResolution"), new QLabel(scaleRes, ui->finishPage)); + form->addRow(newLabel("Basic.Settings.Video.FPS"), new QLabel(fpsStr, ui->finishPage)); // FIXME: form layout is super squished, probably need to set proper sizepolicy on all widgets? } -#define STARTING_SEPARATOR \ - "\n==== Auto-config wizard testing commencing ======\n" -#define STOPPING_SEPARATOR \ - "\n==== Auto-config wizard testing stopping ========\n" +#define STARTING_SEPARATOR "\n==== Auto-config wizard testing commencing ======\n" +#define STOPPING_SEPARATOR "\n==== Auto-config wizard testing stopping ========\n" void AutoConfigTestPage::NextStage() { @@ -1295,9 +1192,7 @@ void AutoConfigTestPage::Progress(int percentage) ui->progressBar->setValue(percentage); } -AutoConfigTestPage::AutoConfigTestPage(QWidget *parent) - : QWizardPage(parent), - ui(new Ui_AutoConfigTestPage) +AutoConfigTestPage::AutoConfigTestPage(QWidget *parent) : QWizardPage(parent), ui(new Ui_AutoConfigTestPage) { ui->setupUi(this); setTitle(QTStr("Basic.AutoConfig.TestPage")); diff --git a/UI/window-basic-auto-config.cpp b/UI/window-basic-auto-config.cpp index 1133cddd6..eaed589ae 100644 --- a/UI/window-basic-auto-config.cpp +++ b/UI/window-basic-auto-config.cpp @@ -43,20 +43,16 @@ constexpr std::string_view OBSServiceFileName = "service.json"; static OBSData OpenServiceSettings(std::string &type) { - const OBSBasic *basic = - reinterpret_cast(App()->GetMainWindow()); + const OBSBasic *basic = reinterpret_cast(App()->GetMainWindow()); const OBSProfile ¤tProfile = basic->GetCurrentProfile(); - const std::filesystem::path jsonFilePath = - currentProfile.path / - std::filesystem::u8path(OBSServiceFileName); + const std::filesystem::path jsonFilePath = currentProfile.path / std::filesystem::u8path(OBSServiceFileName); if (!std::filesystem::exists(jsonFilePath)) { return OBSData(); } - OBSDataAutoRelease data = obs_data_create_from_json_file_safe( - jsonFilePath.u8string().c_str(), "bak"); + OBSDataAutoRelease data = obs_data_create_from_json_file_safe(jsonFilePath.u8string().c_str(), "bak"); obs_data_set_default_string(data, "type", "rtmp_common"); type = obs_data_get_string(data, "type"); @@ -66,8 +62,7 @@ static OBSData OpenServiceSettings(std::string &type) return settings.Get(); } -static void GetServiceInfo(std::string &type, std::string &service, - std::string &server, std::string &key) +static void GetServiceInfo(std::string &type, std::string &service, std::string &server, std::string &key) { OBSData settings = OpenServiceSettings(type); @@ -78,9 +73,7 @@ static void GetServiceInfo(std::string &type, std::string &service, /* ------------------------------------------------------------------------- */ -AutoConfigStartPage::AutoConfigStartPage(QWidget *parent) - : QWizardPage(parent), - ui(new Ui_AutoConfigStartPage) +AutoConfigStartPage::AutoConfigStartPage(QWidget *parent) : QWizardPage(parent), ui(new Ui_AutoConfigStartPage) { ui->setupUi(this); setTitle(QTStr("Basic.AutoConfig.StartPage")); @@ -88,14 +81,12 @@ AutoConfigStartPage::AutoConfigStartPage(QWidget *parent) OBSBasic *main = OBSBasic::Get(); if (main->VCamEnabled()) { - QRadioButton *prioritizeVCam = new QRadioButton( - QTStr("Basic.AutoConfig.StartPage.PrioritizeVirtualCam"), - this); + QRadioButton *prioritizeVCam = + new QRadioButton(QTStr("Basic.AutoConfig.StartPage.PrioritizeVirtualCam"), this); QBoxLayout *box = reinterpret_cast(layout()); box->insertWidget(2, prioritizeVCam); - connect(prioritizeVCam, &QPushButton::clicked, this, - &AutoConfigStartPage::PrioritizeVCam); + connect(prioritizeVCam, &QPushButton::clicked, this, &AutoConfigStartPage::PrioritizeVCam); } } @@ -103,9 +94,7 @@ AutoConfigStartPage::~AutoConfigStartPage() {} int AutoConfigStartPage::nextId() const { - return wiz->type == AutoConfig::Type::VirtualCam - ? AutoConfig::TestPage - : AutoConfig::VideoPage; + return wiz->type == AutoConfig::Type::VirtualCam ? AutoConfig::TestPage : AutoConfig::VideoPage; } void AutoConfigStartPage::on_prioritizeStreaming_clicked() @@ -132,9 +121,7 @@ void AutoConfigStartPage::PrioritizeVCam() #define FPS_PREFER_HIGH_FPS RES_TEXT("FPS.PreferHighFPS") #define FPS_PREFER_HIGH_RES RES_TEXT("FPS.PreferHighRes") -AutoConfigVideoPage::AutoConfigVideoPage(QWidget *parent) - : QWizardPage(parent), - ui(new Ui_AutoConfigVideoPage) +AutoConfigVideoPage::AutoConfigVideoPage(QWidget *parent) : QWizardPage(parent), ui(new Ui_AutoConfigVideoPage) { ui->setupUi(this); @@ -144,18 +131,13 @@ AutoConfigVideoPage::AutoConfigVideoPage(QWidget *parent) obs_video_info ovi; obs_get_video_info(&ovi); - long double fpsVal = - (long double)ovi.fps_num / (long double)ovi.fps_den; + long double fpsVal = (long double)ovi.fps_num / (long double)ovi.fps_den; - QString fpsStr = (ovi.fps_den > 1) ? QString::number(fpsVal, 'f', 2) - : QString::number(fpsVal, 'g'); + QString fpsStr = (ovi.fps_den > 1) ? QString::number(fpsVal, 'f', 2) : QString::number(fpsVal, 'g'); - ui->fps->addItem(QTStr(FPS_PREFER_HIGH_FPS), - (int)AutoConfig::FPSType::PreferHighFPS); - ui->fps->addItem(QTStr(FPS_PREFER_HIGH_RES), - (int)AutoConfig::FPSType::PreferHighRes); - ui->fps->addItem(QTStr(FPS_USE_CURRENT).arg(fpsStr), - (int)AutoConfig::FPSType::UseCurrent); + ui->fps->addItem(QTStr(FPS_PREFER_HIGH_FPS), (int)AutoConfig::FPSType::PreferHighFPS); + ui->fps->addItem(QTStr(FPS_PREFER_HIGH_RES), (int)AutoConfig::FPSType::PreferHighRes); + ui->fps->addItem(QTStr(FPS_USE_CURRENT).arg(fpsStr), (int)AutoConfig::FPSType::UseCurrent); ui->fps->addItem(QStringLiteral("30"), (int)AutoConfig::FPSType::fps30); ui->fps->addItem(QStringLiteral("60"), (int)AutoConfig::FPSType::fps60); ui->fps->setCurrentIndex(0); @@ -168,8 +150,7 @@ AutoConfigVideoPage::AutoConfigVideoPage(QWidget *parent) // Auto config only supports testing down to 240p, don't allow current // resolution if it's lower than that. if (ovi.base_height >= 240) - ui->canvasRes->addItem(QTStr(RES_USE_CURRENT).arg(cxStr, cyStr), - (int)encRes); + ui->canvasRes->addItem(QTStr(RES_USE_CURRENT).arg(cxStr, cyStr), (int)encRes); QList screens = QGuiApplication::screens(); for (int i = 0; i < screens.size(); i++) { @@ -185,18 +166,16 @@ AutoConfigVideoPage::AutoConfigVideoPage(QWidget *parent) encRes = as_width << 16 | as_height; - QString str = QTStr(RES_USE_DISPLAY) - .arg(QString::number(i + 1), - QString::number(as_width), - QString::number(as_height)); + QString str = + QTStr(RES_USE_DISPLAY) + .arg(QString::number(i + 1), QString::number(as_width), QString::number(as_height)); ui->canvasRes->addItem(str, encRes); } auto addRes = [&](int cx, int cy) { encRes = (cx << 16) | cy; - QString str = QString("%1x%2").arg(QString::number(cx), - QString::number(cy)); + QString str = QString("%1x%2").arg(QString::number(cx), QString::number(cy)); ui->canvasRes->addItem(str, encRes); }; @@ -210,9 +189,7 @@ AutoConfigVideoPage::~AutoConfigVideoPage() {} int AutoConfigVideoPage::nextId() const { - return wiz->type == AutoConfig::Type::Recording - ? AutoConfig::TestPage - : AutoConfig::StreamPage; + return wiz->type == AutoConfig::Type::Recording ? AutoConfig::TestPage : AutoConfig::StreamPage; } bool AutoConfigVideoPage::validatePage() @@ -263,9 +240,7 @@ enum class ListOpt : int { Custom, }; -AutoConfigStreamPage::AutoConfigStreamPage(QWidget *parent) - : QWizardPage(parent), - ui(new Ui_AutoConfigStreamPage) +AutoConfigStreamPage::AutoConfigStreamPage(QWidget *parent) : QWizardPage(parent), ui(new Ui_AutoConfigStreamPage) { ui->setupUi(this); ui->bitrateLabel->setVisible(false); @@ -296,24 +271,16 @@ AutoConfigStreamPage::AutoConfigStreamPage(QWidget *parent) LoadServices(false); - connect(ui->service, &QComboBox::currentIndexChanged, this, - &AutoConfigStreamPage::ServiceChanged); - connect(ui->customServer, &QLineEdit::textChanged, this, - &AutoConfigStreamPage::ServiceChanged); - connect(ui->customServer, &QLineEdit::textChanged, this, - &AutoConfigStreamPage::UpdateKeyLink); - connect(ui->customServer, &QLineEdit::editingFinished, this, - &AutoConfigStreamPage::UpdateKeyLink); - connect(ui->doBandwidthTest, &QCheckBox::toggled, this, - &AutoConfigStreamPage::ServiceChanged); + connect(ui->service, &QComboBox::currentIndexChanged, this, &AutoConfigStreamPage::ServiceChanged); + connect(ui->customServer, &QLineEdit::textChanged, this, &AutoConfigStreamPage::ServiceChanged); + connect(ui->customServer, &QLineEdit::textChanged, this, &AutoConfigStreamPage::UpdateKeyLink); + connect(ui->customServer, &QLineEdit::editingFinished, this, &AutoConfigStreamPage::UpdateKeyLink); + connect(ui->doBandwidthTest, &QCheckBox::toggled, this, &AutoConfigStreamPage::ServiceChanged); - connect(ui->service, &QComboBox::currentIndexChanged, this, - &AutoConfigStreamPage::UpdateServerList); + connect(ui->service, &QComboBox::currentIndexChanged, this, &AutoConfigStreamPage::UpdateServerList); - connect(ui->service, &QComboBox::currentIndexChanged, this, - &AutoConfigStreamPage::UpdateKeyLink); - connect(ui->service, &QComboBox::currentIndexChanged, this, - &AutoConfigStreamPage::UpdateMoreInfoLink); + connect(ui->service, &QComboBox::currentIndexChanged, this, &AutoConfigStreamPage::UpdateKeyLink); + connect(ui->service, &QComboBox::currentIndexChanged, this, &AutoConfigStreamPage::UpdateMoreInfoLink); connect(ui->useStreamKeyAdv, &QPushButton::clicked, [&]() { ui->streamKeyWidget->setVisible(true); @@ -321,16 +288,11 @@ AutoConfigStreamPage::AutoConfigStreamPage(QWidget *parent) ui->useStreamKeyAdv->setVisible(false); }); - connect(ui->key, &QLineEdit::textChanged, this, - &AutoConfigStreamPage::UpdateCompleted); - connect(ui->regionUS, &QCheckBox::toggled, this, - &AutoConfigStreamPage::UpdateCompleted); - connect(ui->regionEU, &QCheckBox::toggled, this, - &AutoConfigStreamPage::UpdateCompleted); - connect(ui->regionAsia, &QCheckBox::toggled, this, - &AutoConfigStreamPage::UpdateCompleted); - connect(ui->regionOther, &QCheckBox::toggled, this, - &AutoConfigStreamPage::UpdateCompleted); + connect(ui->key, &QLineEdit::textChanged, this, &AutoConfigStreamPage::UpdateCompleted); + connect(ui->regionUS, &QCheckBox::toggled, this, &AutoConfigStreamPage::UpdateCompleted); + connect(ui->regionEU, &QCheckBox::toggled, this, &AutoConfigStreamPage::UpdateCompleted); + connect(ui->regionAsia, &QCheckBox::toggled, this, &AutoConfigStreamPage::UpdateCompleted); + connect(ui->regionOther, &QCheckBox::toggled, this, &AutoConfigStreamPage::UpdateCompleted); } AutoConfigStreamPage::~AutoConfigStreamPage() {} @@ -356,16 +318,13 @@ bool AutoConfigStreamPage::validatePage() wiz->customServer = IsCustomService(); - const char *serverType = wiz->customServer ? "rtmp_custom" - : "rtmp_common"; + const char *serverType = wiz->customServer ? "rtmp_custom" : "rtmp_common"; if (!wiz->customServer) { - obs_data_set_string(service_settings, "service", - QT_TO_UTF8(ui->service->currentText())); + obs_data_set_string(service_settings, "service", QT_TO_UTF8(ui->service->currentText())); } - OBSServiceAutoRelease service = obs_service_create( - serverType, "temp_service", service_settings, nullptr); + OBSServiceAutoRelease service = obs_service_create(serverType, "temp_service", service_settings, nullptr); int bitrate; if (!ui->doBandwidthTest->isChecked()) { @@ -429,50 +388,34 @@ bool AutoConfigStreamPage::validatePage() wiz->testMultitrackVideo = ui->useMultitrackVideo->isChecked(); if (wiz->testMultitrackVideo) { - auto postData = constructGoLivePost( - QString::fromStdString(wiz->key), std::nullopt, - std::nullopt, false); + auto postData = constructGoLivePost(QString::fromStdString(wiz->key), std::nullopt, + std::nullopt, false); - OBSDataAutoRelease service_settings = - obs_service_get_settings(service); - auto multitrack_video_name = QTStr( - "Basic.Settings.Stream.MultitrackVideoLabel"); - if (obs_data_has_user_value(service_settings, - "multitrack_video_name")) { - multitrack_video_name = obs_data_get_string( - service_settings, - "multitrack_video_name"); + OBSDataAutoRelease service_settings = obs_service_get_settings(service); + auto multitrack_video_name = QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); + if (obs_data_has_user_value(service_settings, "multitrack_video_name")) { + multitrack_video_name = obs_data_get_string(service_settings, "multitrack_video_name"); } try { - auto config = DownloadGoLiveConfig( - this, - MultitrackVideoAutoConfigURL(service), - postData, multitrack_video_name); + auto config = DownloadGoLiveConfig(this, MultitrackVideoAutoConfigURL(service), + postData, multitrack_video_name); - for (const auto &endpoint : - config.ingest_endpoints) { - if (qstrnicmp("RTMP", - endpoint.protocol.c_str(), - 4) != 0) + for (const auto &endpoint : config.ingest_endpoints) { + if (qstrnicmp("RTMP", endpoint.protocol.c_str(), 4) != 0) continue; - std::string address = - endpoint.url_template; - auto pos = - address.find("/{stream_key}"); + std::string address = endpoint.url_template; + auto pos = address.find("/{stream_key}"); if (pos != address.npos) address.erase(pos); - wiz->serviceConfigServers.push_back( - {address, address}); + wiz->serviceConfigServers.push_back({address, address}); } int multitrackVideoBitrate = 0; - for (auto &encoder_config : - config.encoder_configurations) { - auto it = encoder_config.settings.find( - "bitrate"); + for (auto &encoder_config : config.encoder_configurations) { + auto it = encoder_config.settings.find("bitrate"); if (it == encoder_config.settings.end()) continue; @@ -486,29 +429,20 @@ bool AutoConfigStreamPage::validatePage() // grab a streamkey from the go live config if we can for (auto &endpoint : config.ingest_endpoints) { - const char *p = - endpoint.protocol.c_str(); - const char *auth = - endpoint.authentication - ? endpoint.authentication - ->c_str() - : nullptr; - if (qstrnicmp("RTMP", p, 4) == 0 && - auth && *auth) { + const char *p = endpoint.protocol.c_str(); + const char *auth = endpoint.authentication ? endpoint.authentication->c_str() + : nullptr; + if (qstrnicmp("RTMP", p, 4) == 0 && auth && *auth) { wiz->key = auth; break; } } if (multitrackVideoBitrate > 0) { - wiz->startingBitrate = - multitrackVideoBitrate; - wiz->idealBitrate = - multitrackVideoBitrate; - wiz->multitrackVideo.targetBitrate = - multitrackVideoBitrate; - wiz->multitrackVideo.testSuccessful = - true; + wiz->startingBitrate = multitrackVideoBitrate; + wiz->idealBitrate = multitrackVideoBitrate; + wiz->multitrackVideo.targetBitrate = multitrackVideoBitrate; + wiz->multitrackVideo.testSuccessful = true; } } catch (const MultitrackVideoError & /*err*/) { // FIXME: do something sensible @@ -516,14 +450,11 @@ bool AutoConfigStreamPage::validatePage() } } - if (wiz->service != AutoConfig::Service::Twitch && - wiz->service != AutoConfig::Service::YouTube && - wiz->service != AutoConfig::Service::AmazonIVS && - wiz->bandwidthTest) { + if (wiz->service != AutoConfig::Service::Twitch && wiz->service != AutoConfig::Service::YouTube && + wiz->service != AutoConfig::Service::AmazonIVS && wiz->bandwidthTest) { QMessageBox::StandardButton button; #define WARNING_TEXT(x) QTStr("Basic.AutoConfig.StreamPage.StreamWarning." x) - button = OBSMessageBox::question(this, WARNING_TEXT("Title"), - WARNING_TEXT("Text")); + button = OBSMessageBox::question(this, WARNING_TEXT("Title"), WARNING_TEXT("Text")); #undef WARNING_TEXT if (button == QMessageBox::No) @@ -570,20 +501,16 @@ void AutoConfigStreamPage::OnOAuthStreamKeyConnected() ui->connectedAccountLabel->setVisible(true); ui->connectedAccountText->setVisible(true); - ui->connectedAccountText->setText( - QTStr("Auth.LoadingChannel.Title")); + ui->connectedAccountText->setText(QTStr("Auth.LoadingChannel.Title")); - YoutubeApiWrappers *ytAuth = - reinterpret_cast(a); + YoutubeApiWrappers *ytAuth = reinterpret_cast(a); ChannelDescription cd; if (ytAuth->GetChannelDescription(cd)) { ui->connectedAccountText->setText(cd.title); /* Create throwaway stream key for bandwidth test */ if (ui->doBandwidthTest->isChecked()) { - StreamDescription stream = { - "", "", - "OBS Studio Test Stream"}; + StreamDescription stream = {"", "", "OBS Studio Test Stream"}; if (ytAuth->InsertStream(stream)) { ui->key->setText(stream.name); } @@ -602,8 +529,7 @@ void AutoConfigStreamPage::OnAuthConnected() std::string service = QT_TO_UTF8(ui->service->currentText()); Auth::Type type = Auth::AuthType(service); - if (type == Auth::Type::OAuth_StreamKey || - type == Auth::Type::OAuth_LinkedAccount) { + if (type == Auth::Type::OAuth_StreamKey || type == Auth::Type::OAuth_LinkedAccount) { OnOAuthStreamKeyConnected(); } } @@ -622,17 +548,14 @@ void AutoConfigStreamPage::on_connectAccount_clicked() } } -#define DISCONNECT_COMFIRM_TITLE \ - "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Title" -#define DISCONNECT_COMFIRM_TEXT \ - "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Text" +#define DISCONNECT_COMFIRM_TITLE "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Title" +#define DISCONNECT_COMFIRM_TEXT "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Text" void AutoConfigStreamPage::on_disconnectAccount_clicked() { QMessageBox::StandardButton button; - button = OBSMessageBox::question(this, QTStr(DISCONNECT_COMFIRM_TITLE), - QTStr(DISCONNECT_COMFIRM_TEXT)); + button = OBSMessageBox::question(this, QTStr(DISCONNECT_COMFIRM_TITLE), QTStr(DISCONNECT_COMFIRM_TEXT)); if (button == QMessageBox::No) { return; @@ -671,17 +594,13 @@ void AutoConfigStreamPage::on_useStreamKey_clicked() void AutoConfigStreamPage::on_preferHardware_clicked() { auto *main = OBSBasic::Get(); - bool multitrackVideoEnabled = - config_has_user_value(main->Config(), "Stream1", - "EnableMultitrackVideo") - ? config_get_bool(main->Config(), "Stream1", - "EnableMultitrackVideo") - : true; + bool multitrackVideoEnabled = config_has_user_value(main->Config(), "Stream1", "EnableMultitrackVideo") + ? config_get_bool(main->Config(), "Stream1", "EnableMultitrackVideo") + : true; ui->useMultitrackVideo->setEnabled(ui->preferHardware->isChecked()); ui->multitrackVideoInfo->setEnabled(ui->preferHardware->isChecked()); - ui->useMultitrackVideo->setChecked(ui->preferHardware->isChecked() && - multitrackVideoEnabled); + ui->useMultitrackVideo->setChecked(ui->preferHardware->isChecked() && multitrackVideoEnabled); } static inline bool is_auth_service(const std::string &service) @@ -720,8 +639,7 @@ void AutoConfigStreamPage::reset_service_ui_fields(std::string &service) } else if (cef) { QString key = ui->key->text(); bool can_auth = is_auth_service(service); - int page = can_auth && key.isEmpty() ? (int)Section::Connect - : (int)Section::StreamKey; + int page = can_auth && key.isEmpty() ? (int)Section::Connect : (int)Section::StreamKey; ui->stackedWidget->setCurrentIndex(page); ui->streamKeyWidget->setVisible(true); @@ -740,8 +658,7 @@ void AutoConfigStreamPage::reset_service_ui_fields(std::string &service) void AutoConfigStreamPage::ServiceChanged() { - bool showMore = ui->service->currentData().toInt() == - (int)ListOpt::ShowAll; + bool showMore = ui->service->currentData().toInt() == (int)ListOpt::ShowAll; if (showMore) return; @@ -753,58 +670,47 @@ void AutoConfigStreamPage::ServiceChanged() bool ertmp_multitrack_video_available = service == "Twitch"; bool custom_disclaimer = false; - auto multitrack_video_name = - QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); + auto multitrack_video_name = QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); if (!custom) { OBSDataAutoRelease service_settings = obs_data_create(); - obs_data_set_string(service_settings, "service", - service.c_str()); + obs_data_set_string(service_settings, "service", service.c_str()); OBSServiceAutoRelease obs_service = - obs_service_create("rtmp_common", "temp service", - service_settings, nullptr); + obs_service_create("rtmp_common", "temp service", service_settings, nullptr); - if (obs_data_has_user_value(service_settings, - "multitrack_video_name")) { - multitrack_video_name = obs_data_get_string( - service_settings, "multitrack_video_name"); + if (obs_data_has_user_value(service_settings, "multitrack_video_name")) { + multitrack_video_name = obs_data_get_string(service_settings, "multitrack_video_name"); } - if (obs_data_has_user_value(service_settings, - "multitrack_video_disclaimer")) { - ui->multitrackVideoInfo->setText(obs_data_get_string( - service_settings, - "multitrack_video_disclaimer")); + if (obs_data_has_user_value(service_settings, "multitrack_video_disclaimer")) { + ui->multitrackVideoInfo->setText( + obs_data_get_string(service_settings, "multitrack_video_disclaimer")); custom_disclaimer = true; } } if (!custom_disclaimer) { ui->multitrackVideoInfo->setText( - QTStr("MultitrackVideo.Info") - .arg(multitrack_video_name, service.c_str())); + QTStr("MultitrackVideo.Info").arg(multitrack_video_name, service.c_str())); } ui->multitrackVideoInfo->setVisible(ertmp_multitrack_video_available); ui->useMultitrackVideo->setVisible(ertmp_multitrack_video_available); ui->useMultitrackVideo->setText( - QTStr("Basic.AutoConfig.StreamPage.UseMultitrackVideo") - .arg(multitrack_video_name)); + QTStr("Basic.AutoConfig.StreamPage.UseMultitrackVideo").arg(multitrack_video_name)); ui->multitrackVideoInfo->setEnabled(wiz->hardwareEncodingAvailable); ui->useMultitrackVideo->setEnabled(wiz->hardwareEncodingAvailable); reset_service_ui_fields(service); /* Test three closest servers if "Auto" is available for Twitch */ - if ((service == "Twitch" && wiz->twitchAuto) || - (service == "Amazon IVS" && wiz->amazonIVSAuto)) + if ((service == "Twitch" && wiz->twitchAuto) || (service == "Amazon IVS" && wiz->amazonIVSAuto)) regionBased = false; ui->streamkeyPageLayout->removeWidget(ui->serverLabel); ui->streamkeyPageLayout->removeWidget(ui->serverStackedWidget); if (custom) { - ui->streamkeyPageLayout->insertRow(1, ui->serverLabel, - ui->serverStackedWidget); + ui->streamkeyPageLayout->insertRow(1, ui->serverLabel, ui->serverStackedWidget); ui->region->setVisible(false); ui->serverStackedWidget->setCurrentIndex(1); @@ -812,8 +718,7 @@ void AutoConfigStreamPage::ServiceChanged() ui->serverLabel->setVisible(true); } else { if (!testBandwidth) - ui->streamkeyPageLayout->insertRow( - 2, ui->serverLabel, ui->serverStackedWidget); + ui->streamkeyPageLayout->insertRow(2, ui->serverLabel, ui->serverStackedWidget); ui->region->setVisible(regionBased && testBandwidth); ui->serverStackedWidget->setCurrentIndex(0); @@ -830,13 +735,10 @@ void AutoConfigStreamPage::ServiceChanged() if (main->auth) { auto system_auth_service = main->auth->service(); - bool service_check = service.find(system_auth_service) != - std::string::npos; + bool service_check = service.find(system_auth_service) != std::string::npos; #ifdef YOUTUBE_ENABLED - service_check = - service_check ? service_check - : IsYouTubeService(system_auth_service) && - IsYouTubeService(service); + service_check = service_check ? service_check + : IsYouTubeService(system_auth_service) && IsYouTubeService(service); #endif if (service_check) { auth.reset(); @@ -864,8 +766,7 @@ void AutoConfigStreamPage::UpdateMoreInfoLink() obs_data_set_string(settings, "service", QT_TO_UTF8(serviceName)); obs_property_modified(services, settings); - const char *more_info_link = - obs_data_get_string(settings, "more_info_link"); + const char *more_info_link = obs_data_get_string(settings, "more_info_link"); if (!more_info_link || (*more_info_link == '\0')) { ui->moreInfoButton->hide(); @@ -893,35 +794,27 @@ void AutoConfigStreamPage::UpdateKeyLink() streamKeyLink = obs_data_get_string(settings, "stream_key_link"); if (customServer.contains("fbcdn.net") && IsCustomService()) { - streamKeyLink = - "https://www.facebook.com/live/producer?ref=OBS"; + streamKeyLink = "https://www.facebook.com/live/producer?ref=OBS"; } if (serviceName == "Dacast") { - ui->streamKeyLabel->setText( - QTStr("Basic.AutoConfig.StreamPage.EncoderKey")); + ui->streamKeyLabel->setText(QTStr("Basic.AutoConfig.StreamPage.EncoderKey")); ui->streamKeyLabel->setToolTip(""); } else if (!IsCustomService()) { - ui->streamKeyLabel->setText( - QTStr("Basic.AutoConfig.StreamPage.StreamKey")); + ui->streamKeyLabel->setText(QTStr("Basic.AutoConfig.StreamPage.StreamKey")); ui->streamKeyLabel->setToolTip(""); } else { /* add tooltips for stream key */ - QString file = !App()->IsThemeDark() - ? ":/res/images/help.svg" - : ":/res/images/help_light.svg"; + QString file = !App()->IsThemeDark() ? ":/res/images/help.svg" : ":/res/images/help_light.svg"; QString lStr = "%1 "; - ui->streamKeyLabel->setText(lStr.arg( - QTStr("Basic.AutoConfig.StreamPage.StreamKey"), file)); - ui->streamKeyLabel->setToolTip( - QTStr("Basic.AutoConfig.StreamPage.StreamKey.ToolTip")); + ui->streamKeyLabel->setText(lStr.arg(QTStr("Basic.AutoConfig.StreamPage.StreamKey"), file)); + ui->streamKeyLabel->setToolTip(QTStr("Basic.AutoConfig.StreamPage.StreamKey.ToolTip")); } - if (QString(streamKeyLink).isNull() || - QString(streamKeyLink).isEmpty()) { + if (QString(streamKeyLink).isNull() || QString(streamKeyLink).isEmpty()) { ui->streamKeyButton->hide(); } else { ui->streamKeyButton->setTargetUrl(QUrl(streamKeyLink)); @@ -960,14 +853,11 @@ void AutoConfigStreamPage::LoadServices(bool showAll) ui->service->addItem(name); if (!showAll) { - ui->service->addItem( - QTStr("Basic.AutoConfig.StreamPage.Service.ShowAll"), - QVariant((int)ListOpt::ShowAll)); + ui->service->addItem(QTStr("Basic.AutoConfig.StreamPage.Service.ShowAll"), + QVariant((int)ListOpt::ShowAll)); } - ui->service->insertItem( - 0, QTStr("Basic.AutoConfig.StreamPage.Service.Custom"), - QVariant((int)ListOpt::Custom)); + ui->service->insertItem(0, QTStr("Basic.AutoConfig.StreamPage.Service.Custom"), QVariant((int)ListOpt::Custom)); if (!lastService.isEmpty()) { int idx = ui->service->findText(lastService); @@ -983,8 +873,7 @@ void AutoConfigStreamPage::LoadServices(bool showAll) void AutoConfigStreamPage::UpdateServerList() { QString serviceName = ui->service->currentText(); - bool showMore = ui->service->currentData().toInt() == - (int)ListOpt::ShowAll; + bool showMore = ui->service->currentData().toInt() == (int)ListOpt::ShowAll; if (showMore) { LoadServices(true); @@ -1026,11 +915,8 @@ void AutoConfigStreamPage::UpdateCompleted() if (custom) { ready = !ui->customServer->text().isEmpty(); } else { - ready = !wiz->testRegions || - ui->regionUS->isChecked() || - ui->regionEU->isChecked() || - ui->regionAsia->isChecked() || - ui->regionOther->isChecked(); + ready = !wiz->testRegions || ui->regionUS->isChecked() || ui->regionEU->isChecked() || + ui->regionAsia->isChecked() || ui->regionOther->isChecked(); } } emit completeChanged(); @@ -1152,8 +1038,7 @@ AutoConfig::AutoConfig(QWidget *parent) : QWizard(parent) serverList->setCurrentIndex(idx); } else { streamPage->ui->customServer->setText(server.c_str()); - int idx = streamPage->ui->service->findData( - QVariant((int)ListOpt::Custom)); + int idx = streamPage->ui->service->findData(QVariant((int)ListOpt::Custom)); streamPage->ui->service->setCurrentIndex(idx); } @@ -1162,17 +1047,12 @@ AutoConfig::AutoConfig(QWidget *parent) : QWizard(parent) TestHardwareEncoding(); - int bitrate = - config_get_int(main->Config(), "SimpleOutput", "VBitrate"); - bool multitrackVideoEnabled = - config_has_user_value(main->Config(), "Stream1", - "EnableMultitrackVideo") - ? config_get_bool(main->Config(), "Stream1", - "EnableMultitrackVideo") - : true; + int bitrate = config_get_int(main->Config(), "SimpleOutput", "VBitrate"); + bool multitrackVideoEnabled = config_has_user_value(main->Config(), "Stream1", "EnableMultitrackVideo") + ? config_get_bool(main->Config(), "Stream1", "EnableMultitrackVideo") + : true; streamPage->ui->bitrate->setValue(bitrate); - streamPage->ui->useMultitrackVideo->setChecked( - hardwareEncodingAvailable && multitrackVideoEnabled); + streamPage->ui->useMultitrackVideo->setChecked(hardwareEncodingAvailable && multitrackVideoEnabled); streamPage->ServiceChanged(); if (!hardwareEncodingAvailable) { @@ -1182,14 +1062,12 @@ AutoConfig::AutoConfig(QWidget *parent) : QWizard(parent) /* Newer generations of NVENC have a high enough quality to * bitrate ratio that if NVENC is available, it makes sense to * just always prefer hardware encoding by default */ - bool preferHardware = nvencAvailable || appleAvailable || - os_get_physical_cores() <= 4; + bool preferHardware = nvencAvailable || appleAvailable || os_get_physical_cores() <= 4; streamPage->ui->preferHardware->setChecked(preferHardware); } setOptions(QWizard::WizardOptions()); - setButtonText(QWizard::FinishButton, - QTStr("Basic.AutoConfig.ApplySettings")); + setButtonText(QWizard::FinishButton, QTStr("Basic.AutoConfig.ApplySettings")); setButtonText(QWizard::BackButton, QTStr("Back")); setButtonText(QWizard::NextButton, QTStr("Next")); setButtonText(QWizard::CancelButton, QTStr("Cancel")); @@ -1214,16 +1092,13 @@ void AutoConfig::TestHardwareEncoding() else if (strcmp(id, "h264_texture_amf") == 0) hardwareEncodingAvailable = vceAvailable = true; #ifdef __APPLE__ - else if (strcmp(id, - "com.apple.videotoolbox.videoencoder.ave.avc") == - 0 + else if (strcmp(id, "com.apple.videotoolbox.videoencoder.ave.avc") == 0 #ifndef __aarch64__ && os_get_emulation_status() == true #endif ) if (__builtin_available(macOS 13.0, *)) - hardwareEncodingAvailable = appleAvailable = - true; + hardwareEncodingAvailable = appleAvailable = true; #endif } } @@ -1234,8 +1109,7 @@ bool AutoConfig::CanTestServer(const char *server) return true; if (service == Service::Twitch) { - if (astrcmp_n(server, "US West:", 8) == 0 || - astrcmp_n(server, "US East:", 8) == 0 || + if (astrcmp_n(server, "US West:", 8) == 0 || astrcmp_n(server, "US East:", 8) == 0 || astrcmp_n(server, "US Central:", 11) == 0) { return regionUS; } else if (astrcmp_n(server, "EU:", 3) == 0) { @@ -1310,8 +1184,7 @@ void AutoConfig::SaveStreamSettings() obs_data_set_string(settings, "key", key.c_str()); #endif - OBSServiceAutoRelease newService = obs_service_create( - service_id, "default_service", settings, hotkeyData); + OBSServiceAutoRelease newService = obs_service_create(service_id, "default_service", settings, hotkeyData); if (!newService) return; @@ -1329,36 +1202,24 @@ void AutoConfig::SaveStreamSettings() /* ---------------------------------- */ /* save stream settings */ - config_set_int(main->Config(), "SimpleOutput", "VBitrate", - idealBitrate); - config_set_string(main->Config(), "SimpleOutput", "StreamEncoder", - GetEncoderId(streamingEncoder)); + config_set_int(main->Config(), "SimpleOutput", "VBitrate", idealBitrate); + config_set_string(main->Config(), "SimpleOutput", "StreamEncoder", GetEncoderId(streamingEncoder)); config_remove_value(main->Config(), "SimpleOutput", "UseAdvanced"); - config_set_bool(main->Config(), "Stream1", "EnableMultitrackVideo", - multitrackVideo.testSuccessful); + config_set_bool(main->Config(), "Stream1", "EnableMultitrackVideo", multitrackVideo.testSuccessful); if (multitrackVideo.targetBitrate.has_value()) - config_set_int(main->Config(), "Stream1", - "MultitrackVideoTargetBitrate", + config_set_int(main->Config(), "Stream1", "MultitrackVideoTargetBitrate", *multitrackVideo.targetBitrate); else - config_remove_value(main->Config(), "Stream1", - "MultitrackVideoTargetBitrate"); + config_remove_value(main->Config(), "Stream1", "MultitrackVideoTargetBitrate"); - if (multitrackVideo.bitrate.has_value() && - multitrackVideo.targetBitrate.has_value() && - (static_cast(*multitrackVideo.bitrate) / - *multitrackVideo.targetBitrate) >= 0.90) { - config_set_bool(main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrateAuto", - true); + if (multitrackVideo.bitrate.has_value() && multitrackVideo.targetBitrate.has_value() && + (static_cast(*multitrackVideo.bitrate) / *multitrackVideo.targetBitrate) >= 0.90) { + config_set_bool(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrateAuto", true); } else if (multitrackVideo.bitrate.has_value()) { - config_set_bool(main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrateAuto", - false); - config_set_int(main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrate", + config_set_bool(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrateAuto", false); + config_set_int(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrate", *multitrackVideo.bitrate); } } @@ -1368,15 +1229,12 @@ void AutoConfig::SaveSettings() OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); if (recordingEncoder != Encoder::Stream) - config_set_string(main->Config(), "SimpleOutput", "RecEncoder", - GetEncoderId(recordingEncoder)); + config_set_string(main->Config(), "SimpleOutput", "RecEncoder", GetEncoderId(recordingEncoder)); - const char *quality = recordingQuality == Quality::High ? "Small" - : "Stream"; + const char *quality = recordingQuality == Quality::High ? "Small" : "Stream"; config_set_string(main->Config(), "Output", "Mode", "Simple"); - config_set_string(main->Config(), "SimpleOutput", "RecQuality", - quality); + config_set_string(main->Config(), "SimpleOutput", "RecQuality", quality); config_set_int(main->Config(), "Video", "BaseCX", baseResolutionCX); config_set_int(main->Config(), "Video", "BaseCY", baseResolutionCY); config_set_int(main->Config(), "Video", "OutputCX", idealResolutionCX); @@ -1384,8 +1242,7 @@ void AutoConfig::SaveSettings() if (fpsType != FPSType::UseCurrent) { config_set_uint(main->Config(), "Video", "FPSType", 0); - config_set_string(main->Config(), "Video", "FPSCommon", - std::to_string(idealFPSNum).c_str()); + config_set_string(main->Config(), "Video", "FPSCommon", std::to_string(idealFPSNum).c_str()); } main->ResetVideo(); diff --git a/UI/window-basic-auto-config.hpp b/UI/window-basic-auto-config.hpp index d715c1563..7e31bdf89 100644 --- a/UI/window-basic-auto-config.hpp +++ b/UI/window-basic-auto-config.hpp @@ -266,11 +266,7 @@ class AutoConfigTestPage : public QWizardPage { inline ServerInfo() {} - inline ServerInfo(const char *name_, const char *address_) - : name(name_), - address(address_) - { - } + inline ServerInfo(const char *name_, const char *address_) : name(name_), address(address_) {} }; void GetServers(std::vector &servers); diff --git a/UI/window-basic-filters.cpp b/UI/window-basic-filters.cpp index 4d0bf5ea8..c92036c89 100644 --- a/UI/window-basic-filters.cpp +++ b/UI/window-basic-filters.cpp @@ -49,17 +49,13 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) : QDialog(parent), ui(new Ui::OBSBasicFilters), source(source_), - addSignal(obs_source_get_signal_handler(source), "filter_add", - OBSBasicFilters::OBSSourceFilterAdded, this), - removeSignal(obs_source_get_signal_handler(source), "filter_remove", - OBSBasicFilters::OBSSourceFilterRemoved, this), - reorderSignal(obs_source_get_signal_handler(source), - "reorder_filters", OBSBasicFilters::OBSSourceReordered, + addSignal(obs_source_get_signal_handler(source), "filter_add", OBSBasicFilters::OBSSourceFilterAdded, this), + removeSignal(obs_source_get_signal_handler(source), "filter_remove", OBSBasicFilters::OBSSourceFilterRemoved, + this), + reorderSignal(obs_source_get_signal_handler(source), "reorder_filters", OBSBasicFilters::OBSSourceReordered, this), - removeSourceSignal(obs_source_get_signal_handler(source), "remove", - OBSBasicFilters::SourceRemoved, this), - renameSourceSignal(obs_source_get_signal_handler(source), "rename", - OBSBasicFilters::SourceRenamed, this), + removeSourceSignal(obs_source_get_signal_handler(source), "remove", OBSBasicFilters::SourceRemoved, this), + renameSourceSignal(obs_source_get_signal_handler(source), "rename", OBSBasicFilters::SourceRenamed, this), noPreviewMargin(13) { main = reinterpret_cast(parent); @@ -68,17 +64,14 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) ui->setupUi(this); - ui->asyncFilters->setItemDelegate( - new VisibilityItemDelegate(ui->asyncFilters)); - ui->effectFilters->setItemDelegate( - new VisibilityItemDelegate(ui->effectFilters)); + ui->asyncFilters->setItemDelegate(new VisibilityItemDelegate(ui->asyncFilters)); + ui->effectFilters->setItemDelegate(new VisibilityItemDelegate(ui->effectFilters)); const char *name = obs_source_get_name(source); setWindowTitle(QTStr("Basic.Filters.Title").arg(QT_UTF8(name))); #ifndef QT_NO_SHORTCUT - ui->actionRemoveFilter->setShortcut( - QApplication::translate("OBSBasicFilters", "Del", nullptr)); + ui->actionRemoveFilter->setShortcut(QApplication::translate("OBSBasicFilters", "Del", nullptr)); #endif // QT_NO_SHORTCUT addAction(ui->actionRenameFilter); @@ -88,27 +81,21 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) installEventFilter(CreateShortcutFilter()); - connect(ui->asyncFilters->itemDelegate(), - &QAbstractItemDelegate::closeEditor, [this](QWidget *editor) { - FilterNameEdited(editor, ui->asyncFilters); - }); + connect(ui->asyncFilters->itemDelegate(), &QAbstractItemDelegate::closeEditor, + [this](QWidget *editor) { FilterNameEdited(editor, ui->asyncFilters); }); - connect(ui->effectFilters->itemDelegate(), - &QAbstractItemDelegate::closeEditor, [this](QWidget *editor) { - FilterNameEdited(editor, ui->effectFilters); - }); + connect(ui->effectFilters->itemDelegate(), &QAbstractItemDelegate::closeEditor, + [this](QWidget *editor) { FilterNameEdited(editor, ui->effectFilters); }); QPushButton *close = ui->buttonBox->button(QDialogButtonBox::Close); connect(close, &QPushButton::clicked, this, &OBSBasicFilters::close); close->setDefault(true); - connect(ui->buttonBox->button(QDialogButtonBox::RestoreDefaults), - &QPushButton::clicked, this, &OBSBasicFilters::ResetFilters); + connect(ui->buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, this, + &OBSBasicFilters::ResetFilters); - connect(ui->asyncFilters->model(), &QAbstractItemModel::rowsMoved, this, - &OBSBasicFilters::FiltersMoved); - connect(ui->effectFilters->model(), &QAbstractItemModel::rowsMoved, - this, &OBSBasicFilters::FiltersMoved); + connect(ui->asyncFilters->model(), &QAbstractItemModel::rowsMoved, this, &OBSBasicFilters::FiltersMoved); + connect(ui->effectFilters->model(), &QAbstractItemModel::rowsMoved, this, &OBSBasicFilters::FiltersMoved); uint32_t caps = obs_source_get_output_flags(source); bool audio = (caps & OBS_SOURCE_AUDIO) != 0; @@ -125,8 +112,7 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) UpdateSplitter(false); } - if (async && !audioOnly && ui->asyncFilters->count() == 0 && - ui->effectFilters->count() != 0) { + if (async && !audioOnly && ui->asyncFilters->count() == 0 && ui->effectFilters->count() != 0) { ui->effectFilters->setFocus(); } @@ -142,21 +128,17 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) obs_source_inc_showing(source); auto addDrawCallback = [this]() { - obs_display_add_draw_callback(ui->preview->GetDisplay(), - OBSBasicFilters::DrawPreview, - this); + obs_display_add_draw_callback(ui->preview->GetDisplay(), OBSBasicFilters::DrawPreview, this); }; enum obs_source_type type = obs_source_get_type(source); - bool drawable_type = type == OBS_SOURCE_TYPE_INPUT || - type == OBS_SOURCE_TYPE_SCENE; + bool drawable_type = type == OBS_SOURCE_TYPE_INPUT || type == OBS_SOURCE_TYPE_SCENE; if ((caps & OBS_SOURCE_VIDEO) != 0) { ui->rightLayout->setContentsMargins(0, 0, 0, 0); ui->preview->show(); if (drawable_type) - connect(ui->preview, &OBSQTDisplay::DisplayCreated, - addDrawCallback); + connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDrawCallback); } else { ui->rightLayout->setContentsMargins(0, noPreviewMargin, 0, 0); ui->preview->hide(); @@ -197,8 +179,7 @@ inline OBSSource OBSBasicFilters::GetFilter(int row, bool async) return v.value(); } -void FilterChangeUndoRedo(void *vp, obs_data_t *nd_old_settings, - obs_data_t *new_settings) +void FilterChangeUndoRedo(void *vp, obs_data_t *nd_old_settings, obs_data_t *new_settings) { obs_source_t *source = reinterpret_cast(vp); const char *source_uuid = obs_source_get_uuid(source); @@ -207,25 +188,19 @@ void FilterChangeUndoRedo(void *vp, obs_data_t *nd_old_settings, OBSDataAutoRelease redo_wrapper = obs_data_create(); obs_data_set_string(redo_wrapper, "uuid", source_uuid); - obs_data_set_string(redo_wrapper, "settings", - obs_data_get_json(new_settings)); + obs_data_set_string(redo_wrapper, "settings", obs_data_get_json(new_settings)); OBSDataAutoRelease undo_wrapper = obs_data_create(); obs_data_set_string(undo_wrapper, "uuid", source_uuid); - obs_data_set_string(undo_wrapper, "settings", - obs_data_get_json(nd_old_settings)); + obs_data_set_string(undo_wrapper, "settings", obs_data_get_json(nd_old_settings)); auto undo_redo = [](const std::string &data) { - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); const char *filter_uuid = obs_data_get_string(dat, "uuid"); - OBSSourceAutoRelease filter = - obs_get_source_by_uuid(filter_uuid); - OBSDataAutoRelease new_settings = obs_data_create_from_json( - obs_data_get_string(dat, "settings")); + OBSSourceAutoRelease filter = obs_get_source_by_uuid(filter_uuid); + OBSDataAutoRelease new_settings = obs_data_create_from_json(obs_data_get_string(dat, "settings")); - OBSDataAutoRelease current_settings = - obs_source_get_settings(filter); + OBSDataAutoRelease current_settings = obs_source_get_settings(filter); obs_data_clear(current_settings); obs_source_update(filter, new_settings); @@ -236,8 +211,7 @@ void FilterChangeUndoRedo(void *vp, obs_data_t *nd_old_settings, std::string undo_data = obs_data_get_json(undo_wrapper); std::string redo_data = obs_data_get_json(redo_wrapper); - main->undo_s.add_action(QTStr("Undo.Filters").arg(name), undo_redo, - undo_redo, undo_data, redo_data); + main->undo_s.add_action(QTStr("Undo.Filters").arg(name), undo_redo, undo_redo, undo_data, redo_data); obs_source_update(source, new_settings); } @@ -281,21 +255,17 @@ void OBSBasicFilters::UpdatePropertiesView(int row, bool async) OBSDataAutoRelease settings = obs_source_get_settings(filter); auto disabled_undo = [](void *vp, obs_data_t *settings) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); main->undo_s.disable(); obs_source_t *source = reinterpret_cast(vp); obs_source_update(source, settings); }; - view = new OBSPropertiesView( - settings.Get(), filter, - (PropertiesReloadCallback)obs_source_properties, - (PropertiesUpdateCallback)FilterChangeUndoRedo, - (PropertiesVisualUpdateCb)disabled_undo); + view = new OBSPropertiesView(settings.Get(), filter, (PropertiesReloadCallback)obs_source_properties, + (PropertiesUpdateCallback)FilterChangeUndoRedo, + (PropertiesVisualUpdateCb)disabled_undo); - updatePropertiesSignal.Connect(obs_source_get_signal_handler(filter), - "update_properties", + updatePropertiesSignal.Connect(obs_source_get_signal_handler(filter), "update_properties", OBSBasicFilters::UpdateProperties, this); view->setMinimumHeight(150); @@ -306,8 +276,7 @@ void OBSBasicFilters::UpdatePropertiesView(int row, bool async) void OBSBasicFilters::UpdateProperties(void *data, calldata_t *) { - QMetaObject::invokeMethod(static_cast(data)->view, - "ReloadProperties"); + QMetaObject::invokeMethod(static_cast(data)->view, "ReloadProperties"); } void OBSBasicFilters::AddFilter(OBSSource filter, bool focus) @@ -353,8 +322,7 @@ void OBSBasicFilters::RemoveFilter(OBSSource filter) const char *filterId = obs_source_get_id(filter); - blog(LOG_INFO, "User removed filter '%s' (%s) from source '%s'", - filterName, filterId, sourceName); + blog(LOG_INFO, "User removed filter '%s' (%s) from source '%s'", filterName, filterId, sourceName); main->SaveProject(); } @@ -367,8 +335,7 @@ struct FilterOrderInfo { inline FilterOrderInfo(OBSBasicFilters *window_) : window(window_) {} }; -void OBSBasicFilters::ReorderFilter(QListWidget *list, obs_source_t *filter, - size_t idx) +void OBSBasicFilters::ReorderFilter(QListWidget *list, obs_source_t *filter, size_t idx) { int count = list->count(); @@ -384,8 +351,7 @@ void OBSBasicFilters::ReorderFilter(QListWidget *list, obs_source_t *filter, listItem = TakeListItem(list, i); if (listItem) { list->insertItem((int)idx, listItem); - SetupVisibilityItem(list, listItem, - filterItem); + SetupVisibilityItem(list, listItem, filterItem); if (sel) list->setCurrentRow((int)idx); @@ -404,8 +370,7 @@ void OBSBasicFilters::ReorderFilters() obs_source_enum_filters( source, [](obs_source_t *, obs_source_t *filter, void *p) { - FilterOrderInfo *info = - reinterpret_cast(p); + FilterOrderInfo *info = reinterpret_cast(p); uint32_t flags; bool async; @@ -413,13 +378,9 @@ void OBSBasicFilters::ReorderFilters() async = (flags & OBS_SOURCE_ASYNC) != 0; if (async) { - info->window->ReorderFilter( - info->window->ui->asyncFilters, filter, - info->asyncIdx++); + info->window->ReorderFilter(info->window->ui->asyncFilters, filter, info->asyncIdx++); } else { - info->window->ReorderFilter( - info->window->ui->effectFilters, filter, - info->effectIdx++); + info->window->ReorderFilter(info->window->ui->effectFilters, filter, info->effectIdx++); } }, &info); @@ -436,8 +397,7 @@ void OBSBasicFilters::UpdateFilters() obs_source_enum_filters( source, [](obs_source_t *, obs_source_t *filter, void *p) { - OBSBasicFilters *window = - reinterpret_cast(p); + OBSBasicFilters *window = reinterpret_cast(p); window->AddFilter(filter, false); }, @@ -454,8 +414,7 @@ void OBSBasicFilters::UpdateFilters() void OBSBasicFilters::UpdateSplitter() { - bool show_splitter_frame = - ui->asyncFilters->count() + ui->effectFilters->count() > 0; + bool show_splitter_frame = ui->asyncFilters->count() + ui->effectFilters->count() > 0; UpdateSplitter(show_splitter_frame); } @@ -474,8 +433,7 @@ void OBSBasicFilters::UpdateSplitter(bool show_splitter_frame) ui->propertiesFrame->setVisible(show_splitter_frame); } -static bool filter_compatible(bool async, uint32_t sourceFlags, - uint32_t filterFlags) +static bool filter_compatible(bool async, uint32_t sourceFlags, uint32_t filterFlags) { bool filterVideo = (filterFlags & OBS_SOURCE_VIDEO) != 0; bool filterAsync = (filterFlags & OBS_SOURCE_ASYNC) != 0; @@ -484,13 +442,11 @@ static bool filter_compatible(bool async, uint32_t sourceFlags, bool audioOnly = (sourceFlags & OBS_SOURCE_VIDEO) == 0; bool asyncSource = (sourceFlags & OBS_SOURCE_ASYNC) != 0; - if (async && - ((audioOnly && filterVideo) || (!audio && !asyncSource) || - (filterAudio && !audio) || (!asyncSource && !filterAudio))) + if (async && ((audioOnly && filterVideo) || (!audio && !asyncSource) || (filterAudio && !audio) || + (!asyncSource && !filterAudio))) return false; - return (async && (filterAudio || filterAsync)) || - (!async && !filterAudio && !filterAsync); + return (async && (filterAudio || filterAsync)) || (!async && !filterAudio && !filterAsync); } QMenu *OBSBasicFilters::CreateAddFilterPopupMenu(bool async) @@ -504,16 +460,9 @@ QMenu *OBSBasicFilters::CreateAddFilterPopupMenu(bool async) string type; string name; - inline FilterInfo(const char *type_, const char *name_) - : type(type_), - name(name_) - { - } + inline FilterInfo(const char *type_, const char *name_) : type(type_), name(name_) {} - bool operator<(const FilterInfo &r) const - { - return name < r.name; - } + bool operator<(const FilterInfo &r) const { return name < r.name; } }; vector types; @@ -535,17 +484,14 @@ QMenu *OBSBasicFilters::CreateAddFilterPopupMenu(bool async) QMenu *popup = new QMenu(QTStr("Add"), this); for (FilterInfo &type : types) { - uint32_t filterFlags = - obs_get_source_output_flags(type.type.c_str()); + uint32_t filterFlags = obs_get_source_output_flags(type.type.c_str()); if (!filter_compatible(async, sourceFlags, filterFlags)) continue; - QAction *popupItem = - new QAction(QT_UTF8(type.name.c_str()), this); + QAction *popupItem = new QAction(QT_UTF8(type.name.c_str()), this); popupItem->setData(QT_UTF8(type.type.c_str())); - connect(popupItem, &QAction::triggered, - [this, type]() { AddNewFilter(type.type.c_str()); }); + connect(popupItem, &QAction::triggered, [this, type]() { AddNewFilter(type.type.c_str()); }); popup->addAction(popupItem); foundValues = true; @@ -568,42 +514,33 @@ void OBSBasicFilters::AddNewFilter(const char *id) QString placeholder = QString::fromStdString(name); QString text{placeholder}; int i = 2; - while ((existing_filter = obs_source_get_filter_by_name( - source, QT_TO_UTF8(text)))) { + while ((existing_filter = obs_source_get_filter_by_name(source, QT_TO_UTF8(text)))) { text = QString("%1 %2").arg(placeholder).arg(i++); } - bool success = NameDialog::AskForName( - this, QTStr("Basic.Filters.AddFilter.Title"), - QTStr("Basic.Filters.AddFilter.Text"), name, text); + bool success = NameDialog::AskForName(this, QTStr("Basic.Filters.AddFilter.Title"), + QTStr("Basic.Filters.AddFilter.Text"), name, text); if (!success) return; if (name.empty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); AddNewFilter(id); return; } - existing_filter = - obs_source_get_filter_by_name(source, name.c_str()); + existing_filter = obs_source_get_filter_by_name(source, name.c_str()); if (existing_filter) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); AddNewFilter(id); return; } - OBSSourceAutoRelease filter = - obs_source_create(id, name.c_str(), nullptr, nullptr); + OBSSourceAutoRelease filter = obs_source_create(id, name.c_str(), nullptr, nullptr); if (filter) { const char *sourceName = obs_source_get_name(source); - blog(LOG_INFO, - "User added filter '%s' (%s) to source '%s'", - name.c_str(), id, sourceName); + blog(LOG_INFO, "User added filter '%s' (%s) to source '%s'", name.c_str(), id, sourceName); obs_source_filter_add(source, filter); } else { @@ -613,8 +550,7 @@ void OBSBasicFilters::AddNewFilter(const char *id) std::string parent_uuid(obs_source_get_uuid(source)); std::string scene_uuid = obs_source_get_uuid( - reinterpret_cast(App()->GetMainWindow()) - ->GetCurrentSceneSource()); + reinterpret_cast(App()->GetMainWindow())->GetCurrentSceneSource()); /* In order to ensure that the UUID persists through undo/redo, * we save the source data rather than just recreating the * source from scratch. */ @@ -622,46 +558,34 @@ void OBSBasicFilters::AddNewFilter(const char *id) obs_data_set_string(rwrapper, "undo_uuid", parent_uuid.c_str()); OBSDataAutoRelease uwrapper = obs_data_create(); - obs_data_set_string(uwrapper, "fname", - obs_source_get_name(filter)); + obs_data_set_string(uwrapper, "fname", obs_source_get_name(filter)); obs_data_set_string(uwrapper, "suuid", parent_uuid.c_str()); auto undo = [scene_uuid](const std::string &data) { - OBSSourceAutoRelease ssource = - obs_get_source_by_uuid(scene_uuid.c_str()); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(ssource.Get(), true); + OBSSourceAutoRelease ssource = obs_get_source_by_uuid(scene_uuid.c_str()); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(ssource.Get(), true); - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(dat, "suuid")); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "suuid")); OBSSourceAutoRelease filter = - obs_source_get_filter_by_name( - source, - obs_data_get_string(dat, "fname")); + obs_source_get_filter_by_name(source, obs_data_get_string(dat, "fname")); obs_source_filter_remove(source, filter); }; auto redo = [scene_uuid](const std::string &data) { - OBSSourceAutoRelease ssource = - obs_get_source_by_uuid(scene_uuid.c_str()); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(ssource.Get(), true); + OBSSourceAutoRelease ssource = obs_get_source_by_uuid(scene_uuid.c_str()); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(ssource.Get(), true); - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(dat, "undo_uuid")); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "undo_uuid")); OBSSourceAutoRelease filter = obs_load_source(dat); obs_source_filter_add(source, filter); }; std::string undo_data(obs_data_get_json(uwrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - main->undo_s.add_action( - QTStr("Undo.Add").arg(obs_source_get_name(filter)), - undo, redo, undo_data, redo_data, false); + main->undo_s.add_action(QTStr("Undo.Add").arg(obs_source_get_name(filter)), undo, redo, undo_data, + redo_data, false); } } @@ -671,8 +595,7 @@ void OBSBasicFilters::closeEvent(QCloseEvent *event) if (!event->isAccepted()) return; - obs_display_remove_draw_callback(ui->preview->GetDisplay(), - OBSBasicFilters::DrawPreview, this); + obs_display_remove_draw_callback(ui->preview->GetDisplay(), OBSBasicFilters::DrawPreview, this); main->SaveProject(); } @@ -683,14 +606,12 @@ bool OBSBasicFilters::nativeEvent(const QByteArray &, void *message, qintptr *) const MSG &msg = *static_cast(message); switch (msg.message) { case WM_MOVE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnMove(); } break; case WM_DISPLAYCHANGE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnDisplayChange(); } } @@ -708,8 +629,7 @@ void OBSBasicFilters::OBSSourceFilterAdded(void *param, calldata_t *data) OBSBasicFilters *window = reinterpret_cast(param); obs_source_t *filter = (obs_source_t *)calldata_ptr(data, "filter"); - QMetaObject::invokeMethod(window, "AddFilter", - Q_ARG(OBSSource, OBSSource(filter))); + QMetaObject::invokeMethod(window, "AddFilter", Q_ARG(OBSSource, OBSSource(filter))); } void OBSBasicFilters::OBSSourceFilterRemoved(void *param, calldata_t *data) @@ -717,20 +637,17 @@ void OBSBasicFilters::OBSSourceFilterRemoved(void *param, calldata_t *data) OBSBasicFilters *window = reinterpret_cast(param); obs_source_t *filter = (obs_source_t *)calldata_ptr(data, "filter"); - QMetaObject::invokeMethod(window, "RemoveFilter", - Q_ARG(OBSSource, OBSSource(filter))); + QMetaObject::invokeMethod(window, "RemoveFilter", Q_ARG(OBSSource, OBSSource(filter))); } void OBSBasicFilters::OBSSourceReordered(void *param, calldata_t *) { - QMetaObject::invokeMethod(reinterpret_cast(param), - "ReorderFilters"); + QMetaObject::invokeMethod(reinterpret_cast(param), "ReorderFilters"); } void OBSBasicFilters::SourceRemoved(void *param, calldata_t *) { - QMetaObject::invokeMethod(static_cast(param), - "close"); + QMetaObject::invokeMethod(static_cast(param), "close"); } void OBSBasicFilters::SourceRenamed(void *param, calldata_t *data) @@ -738,8 +655,7 @@ void OBSBasicFilters::SourceRenamed(void *param, calldata_t *data) const char *name = calldata_string(data, "new_name"); QString title = QTStr("Basic.Filters.Title").arg(QT_UTF8(name)); - QMetaObject::invokeMethod(static_cast(param), - "setWindowTitle", Q_ARG(QString, title)); + QMetaObject::invokeMethod(static_cast(param), "setWindowTitle", Q_ARG(QString, title)); } void OBSBasicFilters::DrawPreview(void *data, uint32_t cx, uint32_t cy) @@ -784,8 +700,7 @@ static bool QueryRemove(QWidget *parent, obs_source_t *source) QMessageBox remove_source(parent); remove_source.setText(text); - QAbstractButton *Yes = - remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole); + QAbstractButton *Yes = remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole); remove_source.addButton(QTStr("No"), QMessageBox::NoRole); remove_source.setIcon(QMessageBox::Question); remove_source.setWindowTitle(QTStr("ConfirmRemove.Title")); @@ -822,8 +737,7 @@ void OBSBasicFilters::on_moveAsyncFilterDown_clicked() { OBSSource filter = GetFilter(ui->asyncFilters->currentRow(), true); if (filter) - obs_source_filter_set_order(source, filter, - OBS_ORDER_MOVE_DOWN); + obs_source_filter_set_order(source, filter, OBS_ORDER_MOVE_DOWN); } void OBSBasicFilters::on_asyncFilters_GotFocus() @@ -866,8 +780,7 @@ void OBSBasicFilters::on_moveEffectFilterDown_clicked() { OBSSource filter = GetFilter(ui->effectFilters->currentRow(), false); if (filter) - obs_source_filter_set_order(source, filter, - OBS_ORDER_MOVE_DOWN); + obs_source_filter_set_order(source, filter, OBS_ORDER_MOVE_DOWN); } void OBSBasicFilters::on_effectFilters_GotFocus() @@ -927,8 +840,7 @@ void OBSBasicFilters::CustomContextMenu(const QPoint &pos, bool async) if (item) { popup.addSeparator(); popup.addAction(QTStr("Duplicate"), this, [&]() { - DuplicateItem(async ? ui->asyncFilters->currentItem() - : ui->effectFilters->currentItem()); + DuplicateItem(async ? ui->asyncFilters->currentItem() : ui->effectFilters->currentItem()); }); popup.addSeparator(); popup.addAction(ui->actionRenameFilter); @@ -936,8 +848,7 @@ void OBSBasicFilters::CustomContextMenu(const QPoint &pos, bool async) popup.addSeparator(); QAction *copyAction = new QAction(QTStr("Copy")); - connect(copyAction, &QAction::triggered, this, - &OBSBasicFilters::CopyFilter); + connect(copyAction, &QAction::triggered, this, &OBSBasicFilters::CopyFilter); copyAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_C)); ui->effectWidget->addAction(copyAction); ui->asyncWidget->addAction(copyAction); @@ -946,8 +857,7 @@ void OBSBasicFilters::CustomContextMenu(const QPoint &pos, bool async) QAction *pasteAction = new QAction(QTStr("Paste")); pasteAction->setEnabled(main->copyFilter); - connect(pasteAction, &QAction::triggered, this, - &OBSBasicFilters::PasteFilter); + connect(pasteAction, &QAction::triggered, this, &OBSBasicFilters::PasteFilter); pasteAction->setShortcut(QKeySequence(Qt::CTRL | Qt::Key_V)); ui->effectWidget->addAction(pasteAction); ui->asyncWidget->addAction(pasteAction); @@ -983,34 +893,29 @@ void OBSBasicFilters::DuplicateItem(QListWidgetItem *item) QString placeholder = QString::fromStdString(name); QString text{placeholder}; int i = 2; - while ((existing_filter = obs_source_get_filter_by_name( - source, QT_TO_UTF8(text)))) { + while ((existing_filter = obs_source_get_filter_by_name(source, QT_TO_UTF8(text)))) { text = QString("%1 %2").arg(placeholder).arg(i++); } - bool success = NameDialog::AskForName( - this, QTStr("Basic.Filters.AddFilter.Title"), - QTStr("Basic.Filters.AddFilter.Text"), name, text); + bool success = NameDialog::AskForName(this, QTStr("Basic.Filters.AddFilter.Title"), + QTStr("Basic.Filters.AddFilter.Text"), name, text); if (!success) return; if (name.empty()) { - OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); DuplicateItem(item); return; } existing_filter = obs_source_get_filter_by_name(source, name.c_str()); if (existing_filter) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); DuplicateItem(item); return; } bool enabled = obs_source_enabled(filter); - OBSSourceAutoRelease new_filter = - obs_source_duplicate(filter, name.c_str(), false); + OBSSourceAutoRelease new_filter = obs_source_duplicate(filter, name.c_str(), false); if (new_filter) { const char *sourceName = obs_source_get_name(source); const char *id = obs_source_get_id(new_filter); @@ -1023,14 +928,12 @@ void OBSBasicFilters::DuplicateItem(QListWidgetItem *item) } } -void OBSBasicFilters::on_asyncFilters_customContextMenuRequested( - const QPoint &pos) +void OBSBasicFilters::on_asyncFilters_customContextMenuRequested(const QPoint &pos) { CustomContextMenu(pos, true); } -void OBSBasicFilters::on_effectFilters_customContextMenuRequested( - const QPoint &pos) +void OBSBasicFilters::on_effectFilters_customContextMenuRequested(const QPoint &pos) { CustomContextMenu(pos, false); } @@ -1057,61 +960,44 @@ void OBSBasicFilters::FilterNameEdited(QWidget *editor, QListWidget *list) OBSSourceAutoRelease foundFilter = nullptr; if (!sameName) - foundFilter = - obs_source_get_filter_by_name(source, name.c_str()); + foundFilter = obs_source_get_filter_by_name(source, name.c_str()); if (foundFilter || name.empty() || sameName) { listItem->setText(QT_UTF8(prevName)); if (foundFilter) { - OBSMessageBox::information(window(), - QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::information(window(), QTStr("NameExists.Title"), QTStr("NameExists.Text")); } else if (name.empty()) { - OBSMessageBox::information(window(), - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::information(window(), QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); } } else { const char *sourceName = obs_source_get_name(source); - blog(LOG_INFO, - "User renamed filter '%s' on source '%s' to '%s'", - prevName, sourceName, name.c_str()); + blog(LOG_INFO, "User renamed filter '%s' on source '%s' to '%s'", prevName, sourceName, name.c_str()); listItem->setText(QT_UTF8(name.c_str())); obs_source_set_name(filter, name.c_str()); std::string scene_uuid = obs_source_get_uuid( - reinterpret_cast(App()->GetMainWindow()) - ->GetCurrentSceneSource()); - auto undo = [scene_uuid, prev = std::string(prevName), - name](const std::string &uuid) { - OBSSourceAutoRelease ssource = - obs_get_source_by_uuid(scene_uuid.c_str()); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(ssource.Get(), true); + reinterpret_cast(App()->GetMainWindow())->GetCurrentSceneSource()); + auto undo = [scene_uuid, prev = std::string(prevName), name](const std::string &uuid) { + OBSSourceAutoRelease ssource = obs_get_source_by_uuid(scene_uuid.c_str()); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(ssource.Get(), true); - OBSSourceAutoRelease filter = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease filter = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_name(filter, prev.c_str()); }; - auto redo = [scene_uuid, prev = std::string(prevName), - name](const std::string &uuid) { - OBSSourceAutoRelease ssource = - obs_get_source_by_uuid(scene_uuid.c_str()); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(ssource.Get(), true); + auto redo = [scene_uuid, prev = std::string(prevName), name](const std::string &uuid) { + OBSSourceAutoRelease ssource = obs_get_source_by_uuid(scene_uuid.c_str()); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(ssource.Get(), true); - OBSSourceAutoRelease filter = - obs_get_source_by_uuid(uuid.c_str()); + OBSSourceAutoRelease filter = obs_get_source_by_uuid(uuid.c_str()); obs_source_set_name(filter, name.c_str()); }; std::string filter_uuid(obs_source_get_uuid(filter)); - main->undo_s.add_action(QTStr("Undo.Rename").arg(name.c_str()), - undo, redo, filter_uuid, filter_uuid); + main->undo_s.add_action(QTStr("Undo.Rename").arg(name.c_str()), undo, redo, filter_uuid, filter_uuid); } listItem->setText(QString()); @@ -1123,8 +1009,7 @@ static bool ConfirmReset(QWidget *parent) { QMessageBox::StandardButton button; - button = OBSMessageBox::question(parent, QTStr("ConfirmReset.Title"), - QTStr("ConfirmReset.Text"), + button = OBSMessageBox::question(parent, QTStr("ConfirmReset.Title"), QTStr("ConfirmReset.Text"), QMessageBox::Yes | QMessageBox::No); return button == QMessageBox::Yes; @@ -1180,11 +1065,9 @@ void OBSBasicFilters::PasteFilter() const char *filterName = obs_source_get_name(filter); const char *sourceName = obs_source_get_name(source); - QString text = - QTStr("Undo.Filters.Paste.Single").arg(filterName, sourceName); + QString text = QTStr("Undo.Filters.Paste.Single").arg(filterName, sourceName); - main->CreateFilterPasteUndoRedoAction(text, source, undo_array, - redo_array); + main->CreateFilterPasteUndoRedoAction(text, source, undo_array, redo_array); } void OBSBasicFilters::delete_filter(OBSSource filter) @@ -1193,19 +1076,14 @@ void OBSBasicFilters::delete_filter(OBSSource filter) std::string parent_uuid(obs_source_get_uuid(source)); obs_data_set_string(wrapper, "undo_uuid", parent_uuid.c_str()); - std::string scene_uuid = obs_source_get_uuid( - reinterpret_cast(App()->GetMainWindow()) - ->GetCurrentSceneSource()); + std::string scene_uuid = + obs_source_get_uuid(reinterpret_cast(App()->GetMainWindow())->GetCurrentSceneSource()); auto undo = [scene_uuid](const std::string &data) { - OBSSourceAutoRelease ssource = - obs_get_source_by_uuid(scene_uuid.c_str()); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(ssource.Get(), true); + OBSSourceAutoRelease ssource = obs_get_source_by_uuid(scene_uuid.c_str()); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(ssource.Get(), true); - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(dat, "undo_uuid")); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "undo_uuid")); OBSSourceAutoRelease filter = obs_load_source(dat); obs_source_filter_add(source, filter); }; @@ -1214,30 +1092,23 @@ void OBSBasicFilters::delete_filter(OBSSource filter) obs_data_set_string(rwrapper, "fname", obs_source_get_name(filter)); obs_data_set_string(rwrapper, "suuid", parent_uuid.c_str()); auto redo = [scene_uuid](const std::string &data) { - OBSSourceAutoRelease ssource = - obs_get_source_by_uuid(scene_uuid.c_str()); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(ssource.Get(), true); + OBSSourceAutoRelease ssource = obs_get_source_by_uuid(scene_uuid.c_str()); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(ssource.Get(), true); - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(dat, "suuid")); - OBSSourceAutoRelease filter = obs_source_get_filter_by_name( - source, obs_data_get_string(dat, "fname")); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "suuid")); + OBSSourceAutoRelease filter = obs_source_get_filter_by_name(source, obs_data_get_string(dat, "fname")); obs_source_filter_remove(source, filter); }; std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - main->undo_s.add_action( - QTStr("Undo.Delete").arg(obs_source_get_name(filter)), undo, - redo, undo_data, redo_data, false); + main->undo_s.add_action(QTStr("Undo.Delete").arg(obs_source_get_name(filter)), undo, redo, undo_data, redo_data, + false); obs_source_filter_remove(source, filter); } -void OBSBasicFilters::FiltersMoved(const QModelIndex &, int srcIdxStart, int, - const QModelIndex &, int) +void OBSBasicFilters::FiltersMoved(const QModelIndex &, int srcIdxStart, int, const QModelIndex &, int) { QListWidget *list = isAsync ? ui->asyncFilters : ui->effectFilters; int neighborIdx = 0; diff --git a/UI/window-basic-filters.hpp b/UI/window-basic-filters.hpp index 9d9d9999b..c1e2e6c98 100644 --- a/UI/window-basic-filters.hpp +++ b/UI/window-basic-filters.hpp @@ -113,8 +113,7 @@ private slots: void CopyFilter(); void PasteFilter(); - void FiltersMoved(const QModelIndex &srcParent, int srcIdxStart, - int srcIdxEnd, const QModelIndex &dstParent, + void FiltersMoved(const QModelIndex &srcParent, int srcIdxStart, int srcIdxEnd, const QModelIndex &dstParent, int dstIdx); public: @@ -131,6 +130,5 @@ public: protected: virtual void closeEvent(QCloseEvent *event) override; - virtual bool nativeEvent(const QByteArray &eventType, void *message, - qintptr *result) override; + virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override; }; diff --git a/UI/window-basic-interaction.cpp b/UI/window-basic-interaction.cpp index b51b0f1f3..449da655f 100644 --- a/UI/window-basic-interaction.cpp +++ b/UI/window-basic-interaction.cpp @@ -38,16 +38,12 @@ OBSBasicInteraction::OBSBasicInteraction(QWidget *parent, OBSSource source_) main(qobject_cast(parent)), ui(new Ui::OBSBasicInteraction), source(source_), - removedSignal(obs_source_get_signal_handler(source), "remove", - OBSBasicInteraction::SourceRemoved, this), - renamedSignal(obs_source_get_signal_handler(source), "rename", - OBSBasicInteraction::SourceRenamed, this), + removedSignal(obs_source_get_signal_handler(source), "remove", OBSBasicInteraction::SourceRemoved, this), + renamedSignal(obs_source_get_signal_handler(source), "rename", OBSBasicInteraction::SourceRenamed, this), eventFilter(BuildEventFilter()) { - int cx = (int)config_get_int(App()->GetUserConfig(), - "InteractionWindow", "cx"); - int cy = (int)config_get_int(App()->GetUserConfig(), - "InteractionWindow", "cy"); + int cx = (int)config_get_int(App()->GetUserConfig(), "InteractionWindow", "cx"); + int cy = (int)config_get_int(App()->GetUserConfig(), "InteractionWindow", "cy"); Qt::WindowFlags flags = windowFlags(); Qt::WindowFlags helpFlag = Qt::WindowContextHelpButtonHint; @@ -66,9 +62,7 @@ OBSBasicInteraction::OBSBasicInteraction(QWidget *parent, OBSSource source_) setWindowTitle(QTStr("Basic.InteractionWindow").arg(QT_UTF8(name))); auto addDrawCallback = [this]() { - obs_display_add_draw_callback(ui->preview->GetDisplay(), - OBSBasicInteraction::DrawPreview, - this); + obs_display_add_draw_callback(ui->preview->GetDisplay(), OBSBasicInteraction::DrawPreview, this); }; connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDrawCallback); @@ -88,25 +82,20 @@ OBSEventFilter *OBSBasicInteraction::BuildEventFilter() case QEvent::MouseButtonPress: case QEvent::MouseButtonRelease: case QEvent::MouseButtonDblClick: - return this->HandleMouseClickEvent( - static_cast(event)); + return this->HandleMouseClickEvent(static_cast(event)); case QEvent::MouseMove: case QEvent::Enter: case QEvent::Leave: - return this->HandleMouseMoveEvent( - static_cast(event)); + return this->HandleMouseMoveEvent(static_cast(event)); case QEvent::Wheel: - return this->HandleMouseWheelEvent( - static_cast(event)); + return this->HandleMouseWheelEvent(static_cast(event)); case QEvent::FocusIn: case QEvent::FocusOut: - return this->HandleFocusEvent( - static_cast(event)); + return this->HandleFocusEvent(static_cast(event)); case QEvent::KeyPress: case QEvent::KeyRelease: - return this->HandleKeyEvent( - static_cast(event)); + return this->HandleKeyEvent(static_cast(event)); default: return false; } @@ -115,8 +104,7 @@ OBSEventFilter *OBSBasicInteraction::BuildEventFilter() void OBSBasicInteraction::SourceRemoved(void *data, calldata_t *) { - QMetaObject::invokeMethod(static_cast(data), - "close"); + QMetaObject::invokeMethod(static_cast(data), "close"); } void OBSBasicInteraction::SourceRenamed(void *data, calldata_t *params) @@ -124,8 +112,7 @@ void OBSBasicInteraction::SourceRenamed(void *data, calldata_t *params) const char *name = calldata_string(params, "new_name"); QString title = QTStr("Basic.InteractionWindow").arg(QT_UTF8(name)); - QMetaObject::invokeMethod(static_cast(data), - "setWindowTitle", Q_ARG(QString, title)); + QMetaObject::invokeMethod(static_cast(data), "setWindowTitle", Q_ARG(QString, title)); } void OBSBasicInteraction::DrawPreview(void *data, uint32_t cx, uint32_t cy) @@ -166,31 +153,24 @@ void OBSBasicInteraction::closeEvent(QCloseEvent *event) if (!event->isAccepted()) return; - config_set_int(App()->GetAppConfig(), "InteractionWindow", "cx", - width()); - config_set_int(App()->GetAppConfig(), "InteractionWindow", "cy", - height()); + config_set_int(App()->GetAppConfig(), "InteractionWindow", "cx", width()); + config_set_int(App()->GetAppConfig(), "InteractionWindow", "cy", height()); - obs_display_remove_draw_callback(ui->preview->GetDisplay(), - OBSBasicInteraction::DrawPreview, - this); + obs_display_remove_draw_callback(ui->preview->GetDisplay(), OBSBasicInteraction::DrawPreview, this); } -bool OBSBasicInteraction::nativeEvent(const QByteArray &, void *message, - qintptr *) +bool OBSBasicInteraction::nativeEvent(const QByteArray &, void *message, qintptr *) { #ifdef _WIN32 const MSG &msg = *static_cast(message); switch (msg.message) { case WM_MOVE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnMove(); } break; case WM_DISPLAYCHANGE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnDisplayChange(); } } @@ -201,8 +181,7 @@ bool OBSBasicInteraction::nativeEvent(const QByteArray &, void *message, return false; } -static int TranslateQtKeyboardEventModifiers(QInputEvent *event, - bool mouseEvent) +static int TranslateQtKeyboardEventModifiers(QInputEvent *event, bool mouseEvent) { int obsModifiers = INTERACT_NONE; @@ -244,8 +223,7 @@ static int TranslateQtMouseEventModifiers(QMouseEvent *event) return modifiers; } -bool OBSBasicInteraction::GetSourceRelativeXY(int mouseX, int mouseY, int &relX, - int &relY) +bool OBSBasicInteraction::GetSourceRelativeXY(int mouseX, int mouseY, int &relX, int &relY) { float pixelRatio = devicePixelRatioF(); int mouseXscaled = (int)roundf(mouseX * pixelRatio); @@ -259,8 +237,7 @@ bool OBSBasicInteraction::GetSourceRelativeXY(int mouseX, int mouseY, int &relX, int x, y; float scale; - GetScaleAndCenterPos(sourceCX, sourceCY, size.width(), size.height(), x, - y, scale); + GetScaleAndCenterPos(sourceCX, sourceCY, size.width(), size.height(), x, y, scale); if (x > 0) { relX = int(float(mouseXscaled - x) / scale); @@ -312,12 +289,10 @@ bool OBSBasicInteraction::HandleMouseClickEvent(QMouseEvent *event) // clickCount = 2; QPoint pos = event->pos(); - bool insideSource = GetSourceRelativeXY(pos.x(), pos.y(), mouseEvent.x, - mouseEvent.y); + bool insideSource = GetSourceRelativeXY(pos.x(), pos.y(), mouseEvent.x, mouseEvent.y); if (mouseUp || insideSource) - obs_source_send_mouse_click(source, &mouseEvent, button, - mouseUp, clickCount); + obs_source_send_mouse_click(source, &mouseEvent, button, mouseUp, clickCount); return true; } @@ -331,8 +306,7 @@ bool OBSBasicInteraction::HandleMouseMoveEvent(QMouseEvent *event) if (!mouseLeave) { mouseEvent.modifiers = TranslateQtMouseEventModifiers(event); QPoint pos = event->pos(); - mouseLeave = !GetSourceRelativeXY(pos.x(), pos.y(), - mouseEvent.x, mouseEvent.y); + mouseLeave = !GetSourceRelativeXY(pos.x(), pos.y(), mouseEvent.x, mouseEvent.y); } obs_source_send_mouse_move(source, &mouseEvent, mouseLeave); @@ -367,8 +341,7 @@ bool OBSBasicInteraction::HandleMouseWheelEvent(QWheelEvent *event) const int y = position.y(); if (GetSourceRelativeXY(x, y, mouseEvent.x, mouseEvent.y)) { - obs_source_send_mouse_wheel(source, &mouseEvent, xDelta, - yDelta); + obs_source_send_mouse_wheel(source, &mouseEvent, xDelta, yDelta); } return true; diff --git a/UI/window-basic-interaction.hpp b/UI/window-basic-interaction.hpp index df6a2b7d2..6bfaaab4a 100644 --- a/UI/window-basic-interaction.hpp +++ b/UI/window-basic-interaction.hpp @@ -64,8 +64,7 @@ public: protected: virtual void closeEvent(QCloseEvent *event) override; - virtual bool nativeEvent(const QByteArray &eventType, void *message, - qintptr *result) override; + virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override; }; typedef std::function EventFilterFunc; @@ -76,10 +75,7 @@ public: OBSEventFilter(EventFilterFunc filter_) : filter(filter_) {} protected: - bool eventFilter(QObject *obj, QEvent *event) - { - return filter(obj, event); - } + bool eventFilter(QObject *obj, QEvent *event) { return filter(obj, event); } public: EventFilterFunc filter; diff --git a/UI/window-basic-main-browser.cpp b/UI/window-basic-main-browser.cpp index 24be69fe7..e822bb134 100644 --- a/UI/window-basic-main-browser.cpp +++ b/UI/window-basic-main-browser.cpp @@ -52,8 +52,7 @@ void CheckExistingCookieId() if (config_has_user_value(main->Config(), "Panels", "CookieId")) return; - config_set_string(main->Config(), "Panels", "CookieId", - GenId().c_str()); + config_set_string(main->Config(), "Panels", "CookieId", GenId().c_str()); } #ifdef BROWSER_AVAILABLE @@ -67,8 +66,7 @@ static void InitPanelCookieManager() CheckExistingCookieId(); OBSBasic *main = OBSBasic::Get(); - const char *cookie_id = - config_get_string(main->Config(), "Panels", "CookieId"); + const char *cookie_id = config_get_string(main->Config(), "Panels", "CookieId"); std::string sub_path; sub_path += "obs_profile_cookies/"; @@ -103,8 +101,7 @@ void DuplicateCurrentCookieProfile(ConfigFile &config) #ifdef BROWSER_AVAILABLE if (cef) { OBSBasic *main = OBSBasic::Get(); - std::string cookie_id = - config_get_string(main->Config(), "Panels", "CookieId"); + std::string cookie_id = config_get_string(main->Config(), "Panels", "CookieId"); std::string src_path; src_path += "obs_profile_cookies/"; @@ -136,10 +133,8 @@ void DuplicateCurrentCookieProfile(ConfigFile &config) } } - config_set_string(config, "Panels", "CookieId", - cookie_id.c_str()); - config_set_string(main->Config(), "Panels", "CookieId", - new_id.c_str()); + config_set_string(config, "Panels", "CookieId", cookie_id.c_str()); + config_set_string(main->Config(), "Panels", "CookieId", new_id.c_str()); } #else UNUSED_PARAMETER(config); @@ -156,8 +151,7 @@ void OBSBasic::InitBrowserPanelSafeBlock() return; } - ExecThreadedWithoutBlocking([] { cef->wait_for_browser_init(); }, - QTStr("BrowserPanelInit.Title"), + ExecThreadedWithoutBlocking([] { cef->wait_for_browser_init(); }, QTStr("BrowserPanelInit.Title"), QTStr("BrowserPanelInit.Text")); InitPanelCookieManager(); #endif diff --git a/UI/window-basic-main-dropfiles.cpp b/UI/window-basic-main-dropfiles.cpp index 880ae3014..0e4713816 100644 --- a/UI/window-basic-main-dropfiles.cpp +++ b/UI/window-basic-main-dropfiles.cpp @@ -26,21 +26,15 @@ static const char *imageExtensions[] = {"bmp", "gif", "jpeg", "jpg", static const char *htmlExtensions[] = {"htm", "html", nullptr}; static const char *mediaExtensions[] = { - "3ga", "669", "a52", "aac", "ac3", "adt", "adts", "aif", - "aifc", "aiff", "amb", "amr", "aob", "ape", "au", "awb", - "caf", "dts", "flac", "it", "kar", "m4a", "m4b", "m4p", - "m5p", "mid", "mka", "mlp", "mod", "mpa", "mp1", "mp2", - "mp3", "mpc", "mpga", "mus", "oga", "ogg", "oma", "opus", - "qcp", "ra", "rmi", "s3m", "sid", "spx", "tak", "thd", - "tta", "voc", "vqf", "w64", "wav", "wma", "wv", "xa", - "xm", "3g2", "3gp", "3gp2", "3gpp", "amv", "asf", "avi", - "bik", "crf", "divx", "drc", "dv", "evo", "f4v", "flv", - "gvi", "gxf", "iso", "m1v", "m2v", "m2t", "m2ts", "m4v", - "mkv", "mov", "mp2", "mp2v", "mp4", "mp4v", "mpe", "mpeg", - "mpeg1", "mpeg2", "mpeg4", "mpg", "mpv2", "mts", "mtv", "mxf", - "mxg", "nsv", "nuv", "ogg", "ogm", "ogv", "ogx", "ps", - "rec", "rm", "rmvb", "rpl", "thp", "tod", "ts", "tts", - "txd", "vob", "vro", "webm", "wm", "wmv", "wtv", nullptr}; + "3ga", "669", "a52", "aac", "ac3", "adt", "adts", "aif", "aifc", "aiff", "amb", "amr", "aob", "ape", + "au", "awb", "caf", "dts", "flac", "it", "kar", "m4a", "m4b", "m4p", "m5p", "mid", "mka", "mlp", + "mod", "mpa", "mp1", "mp2", "mp3", "mpc", "mpga", "mus", "oga", "ogg", "oma", "opus", "qcp", "ra", + "rmi", "s3m", "sid", "spx", "tak", "thd", "tta", "voc", "vqf", "w64", "wav", "wma", "wv", "xa", + "xm", "3g2", "3gp", "3gp2", "3gpp", "amv", "asf", "avi", "bik", "crf", "divx", "drc", "dv", "evo", + "f4v", "flv", "gvi", "gxf", "iso", "m1v", "m2v", "m2t", "m2ts", "m4v", "mkv", "mov", "mp2", "mp2v", + "mp4", "mp4v", "mpe", "mpeg", "mpeg1", "mpeg2", "mpeg4", "mpg", "mpv2", "mts", "mtv", "mxf", "mxg", "nsv", + "nuv", "ogg", "ogm", "ogv", "ogx", "ps", "rec", "rm", "rmvb", "rpl", "thp", "tod", "ts", "tts", + "txd", "vob", "vro", "webm", "wm", "wmv", "wtv", nullptr}; static string GenerateSourceName(const char *base) { @@ -56,8 +50,7 @@ static string GenerateSourceName(const char *base) name += ")"; } - OBSSourceAutoRelease source = - obs_get_source_by_name(name.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(name.c_str()); if (!source) return name; @@ -73,8 +66,7 @@ static QString ReadWindowsURLFile(const QString &file) } #endif -void OBSBasic::AddDropURL(const char *url, QString &name, obs_data_t *settings, - const obs_video_info &ovi) +void OBSBasic::AddDropURL(const char *url, QString &name, obs_data_t *settings, const obs_video_info &ovi) { QUrl path = QString::fromUtf8(url); QUrlQuery query = QUrlQuery(path.query(QUrl::FullyEncoded)); @@ -93,20 +85,16 @@ void OBSBasic::AddDropURL(const char *url, QString &name, obs_data_t *settings, // decoding kicks in again. This is to allow JavaScript's // default searchParams.append function to simply append css // to the query parameters, which is the intended usecase for this. - QString fullyEncoded = - query.queryItemValue("layer-css", QUrl::FullyEncoded); + QString fullyEncoded = query.queryItemValue("layer-css", QUrl::FullyEncoded); fullyEncoded = fullyEncoded.replace("+", "%20"); - QString decoded = QUrl::fromPercentEncoding( - QByteArray::fromStdString(QT_TO_UTF8(fullyEncoded))); + QString decoded = QUrl::fromPercentEncoding(QByteArray::fromStdString(QT_TO_UTF8(fullyEncoded))); obs_data_set_string(settings, "css", QT_TO_UTF8(decoded)); } obs_data_set_int(settings, "width", cx); obs_data_set_int(settings, "height", cy); - name = query.hasQueryItem("layer-name") - ? query.queryItemValue("layer-name", QUrl::FullyDecoded) - : path.host(); + name = query.hasQueryItem("layer-name") ? query.queryItemValue("layer-name", QUrl::FullyDecoded) : path.host(); query.removeQueryItem("layer-width"); query.removeQueryItem("layer-height"); @@ -181,39 +169,30 @@ void OBSBasic::AddDropSource(const char *data, DropType image) if (name.isEmpty()) name = obs_source_get_display_name(type); std::string sourceName = GenerateSourceName(QT_TO_UTF8(name)); - OBSSourceAutoRelease source = - obs_source_create(type, sourceName.c_str(), settings, nullptr); + OBSSourceAutoRelease source = obs_source_create(type, sourceName.c_str(), settings, nullptr); if (source) { OBSDataAutoRelease wrapper = obs_save_source(source); OBSScene scene = main->GetCurrentScene(); - std::string sceneUUID = - obs_source_get_uuid(obs_scene_get_source(scene)); + std::string sceneUUID = obs_source_get_uuid(obs_scene_get_source(scene)); std::string sourceUUID = obs_source_get_uuid(source); auto undo = [sceneUUID, sourceUUID](const std::string &) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(sourceUUID.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(sourceUUID.c_str()); obs_source_remove(source); - OBSSourceAutoRelease scene = - obs_get_source_by_uuid(sceneUUID.c_str()); + OBSSourceAutoRelease scene = obs_get_source_by_uuid(sceneUUID.c_str()); OBSBasic::Get()->SetCurrentScene(scene.Get(), true); }; - auto redo = [sceneUUID, sourceName, - type](const std::string &data) { - OBSSourceAutoRelease scene = - obs_get_source_by_uuid(sceneUUID.c_str()); + auto redo = [sceneUUID, sourceName, type](const std::string &data) { + OBSSourceAutoRelease scene = obs_get_source_by_uuid(sceneUUID.c_str()); OBSBasic::Get()->SetCurrentScene(scene.Get(), true); - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); OBSSourceAutoRelease source = obs_load_source(dat); - obs_scene_add(obs_scene_from_source(scene), - source.Get()); + obs_scene_add(obs_scene_from_source(scene), source.Get()); }; - undo_s.add_action(QTStr("Undo.Add").arg(sourceName.c_str()), - undo, redo, "", + undo_s.add_action(QTStr("Undo.Add").arg(sourceName.c_str()), undo, redo, "", std::string(obs_data_get_json(wrapper))); obs_scene_add(scene, source); } @@ -255,10 +234,8 @@ void OBSBasic::ConfirmDropUrl(const QString &url) messageBox.setWindowTitle(QTStr("AddUrl.Title")); messageBox.setText(msg); - QPushButton *yesButton = messageBox.addButton( - QTStr("Yes"), QMessageBox::YesRole); - QPushButton *noButton = - messageBox.addButton(QTStr("No"), QMessageBox::NoRole); + QPushButton *yesButton = messageBox.addButton(QTStr("Yes"), QMessageBox::YesRole); + QPushButton *noButton = messageBox.addButton(QTStr("No"), QMessageBox::NoRole); messageBox.setDefaultButton(yesButton); messageBox.setEscapeButton(noButton); messageBox.setIcon(QMessageBox::Question); @@ -287,8 +264,7 @@ void OBSBasic::dropEvent(QDropEvent *event) } #ifdef _WIN32 - if (fileInfo.suffix().compare( - "url", Qt::CaseInsensitive) == 0) { + if (fileInfo.suffix().compare("url", Qt::CaseInsensitive) == 0) { QString urlTarget = ReadWindowsURLFile(file); if (!urlTarget.isEmpty()) { ConfirmDropUrl(urlTarget); diff --git a/UI/window-basic-main-outputs.cpp b/UI/window-basic-main-outputs.cpp index 9177f1084..291f6cf76 100644 --- a/UI/window-basic-main-outputs.cpp +++ b/UI/window-basic-main-outputs.cpp @@ -34,8 +34,7 @@ static void OBSStreamStarting(void *data, calldata_t *params) return; output->delayActive = true; - QMetaObject::invokeMethod(output->main, "StreamDelayStarting", - Q_ARG(int, sec)); + QMetaObject::invokeMethod(output->main, "StreamDelayStarting", Q_ARG(int, sec)); } static void OBSStreamStopping(void *data, calldata_t *params) @@ -47,8 +46,7 @@ static void OBSStreamStopping(void *data, calldata_t *params) if (sec == 0) QMetaObject::invokeMethod(output->main, "StreamStopping"); else - QMetaObject::invokeMethod(output->main, "StreamDelayStopping", - Q_ARG(int, sec)); + QMetaObject::invokeMethod(output->main, "StreamDelayStopping", Q_ARG(int, sec)); } static void OBSStartStreaming(void *data, calldata_t * /* params */) @@ -71,9 +69,7 @@ static void OBSStopStreaming(void *data, calldata_t *params) output->delayActive = false; output->multitrackVideoActive = false; os_atomic_set_bool(&streaming_active, false); - QMetaObject::invokeMethod(output->main, "StreamingStop", - Q_ARG(int, code), - Q_ARG(QString, arg_last_error)); + QMetaObject::invokeMethod(output->main, "StreamingStop", Q_ARG(int, code), Q_ARG(QString, arg_last_error)); } static void OBSStartRecording(void *data, calldata_t * /* params */) @@ -96,9 +92,7 @@ static void OBSStopRecording(void *data, calldata_t *params) output->recordingActive = false; os_atomic_set_bool(&recording_active, false); os_atomic_set_bool(&recording_paused, false); - QMetaObject::invokeMethod(output->main, "RecordingStop", - Q_ARG(int, code), - Q_ARG(QString, arg_last_error)); + QMetaObject::invokeMethod(output->main, "RecordingStop", Q_ARG(int, code), Q_ARG(QString, arg_last_error)); } static void OBSRecordStopping(void *data, calldata_t * /* params */) @@ -112,11 +106,9 @@ static void OBSRecordFileChanged(void *data, calldata_t *params) BasicOutputHandler *output = static_cast(data); const char *next_file = calldata_string(params, "next_file"); - QString arg_last_file = - QString::fromUtf8(output->lastRecordingPath.c_str()); + QString arg_last_file = QString::fromUtf8(output->lastRecordingPath.c_str()); - QMetaObject::invokeMethod(output->main, "RecordingFileChanged", - Q_ARG(QString, arg_last_file)); + QMetaObject::invokeMethod(output->main, "RecordingFileChanged", Q_ARG(QString, arg_last_file)); output->lastRecordingPath = next_file; } @@ -137,8 +129,7 @@ static void OBSStopReplayBuffer(void *data, calldata_t *params) output->replayBufferActive = false; os_atomic_set_bool(&replaybuf_active, false); - QMetaObject::invokeMethod(output->main, "ReplayBufferStop", - Q_ARG(int, code)); + QMetaObject::invokeMethod(output->main, "ReplayBufferStop", Q_ARG(int, code)); } static void OBSReplayBufferStopping(void *data, calldata_t * /* params */) @@ -150,8 +141,7 @@ static void OBSReplayBufferStopping(void *data, calldata_t * /* params */) static void OBSReplayBufferSaved(void *data, calldata_t * /* params */) { BasicOutputHandler *output = static_cast(data); - QMetaObject::invokeMethod(output->main, "ReplayBufferSaved", - Qt::QueuedConnection); + QMetaObject::invokeMethod(output->main, "ReplayBufferSaved", Qt::QueuedConnection); } static void OBSStartVirtualCam(void *data, calldata_t * /* params */) @@ -170,8 +160,7 @@ static void OBSStopVirtualCam(void *data, calldata_t *params) output->virtualCamActive = false; os_atomic_set_bool(&virtualcam_active, false); - QMetaObject::invokeMethod(output->main, "OnVirtualCamStop", - Q_ARG(int, code)); + QMetaObject::invokeMethod(output->main, "OnVirtualCamStop", Q_ARG(int, code)); } static void OBSDeactivateVirtualCam(void *data, calldata_t * /* params */) @@ -183,10 +172,7 @@ static void OBSDeactivateVirtualCam(void *data, calldata_t * /* params */) /* ------------------------------------------------------------------------ */ struct StartMultitrackVideoStreamingGuard { - StartMultitrackVideoStreamingGuard() - { - future = guard.get_future().share(); - }; + StartMultitrackVideoStreamingGuard() { future = guard.get_future().share(); }; ~StartMultitrackVideoStreamingGuard() { guard.set_value(); } std::shared_future GetFuture() const { return future; } @@ -204,8 +190,7 @@ private: /* ------------------------------------------------------------------------ */ -static bool CreateSimpleAACEncoder(OBSEncoder &res, int bitrate, - const char *name, size_t idx) +static bool CreateSimpleAACEncoder(OBSEncoder &res, int bitrate, const char *name, size_t idx) { const char *id_ = GetSimpleAACEncoderForBitrate(bitrate); if (!id_) { @@ -223,8 +208,7 @@ static bool CreateSimpleAACEncoder(OBSEncoder &res, int bitrate, return false; } -static bool CreateSimpleOpusEncoder(OBSEncoder &res, int bitrate, - const char *name, size_t idx) +static bool CreateSimpleOpusEncoder(OBSEncoder &res, int bitrate, const char *name, size_t idx) { const char *id_ = GetSimpleOpusEncoderForBitrate(bitrate); if (!id_) { @@ -242,12 +226,10 @@ static bool CreateSimpleOpusEncoder(OBSEncoder &res, int bitrate, return false; } -static inline bool can_use_output(const char *prot, const char *output, - const char *prot_test1, +static inline bool can_use_output(const char *prot, const char *output, const char *prot_test1, const char *prot_test2 = nullptr) { - return (strcmp(prot, prot_test1) == 0 || - (prot_test2 && strcmp(prot, prot_test2) == 0)) && + return (strcmp(prot, prot_test1) == 0 || (prot_test2 && strcmp(prot, prot_test2) == 0)) && (obs_get_output_flags(output) & OBS_OUTPUT_SERVICE) != 0; } @@ -265,14 +247,12 @@ static const char *GetStreamOutputType(const obs_service_t *service) const char *output = nullptr; if (!protocol) { - blog(LOG_WARNING, "The service '%s' has no protocol set", - obs_service_get_id(service)); + blog(LOG_WARNING, "The service '%s' has no protocol set", obs_service_get_id(service)); return nullptr; } if (!obs_is_output_protocol_registered(protocol)) { - blog(LOG_WARNING, "The protocol '%s' is not registered", - protocol); + blog(LOG_WARNING, "The protocol '%s' is not registered", protocol); return nullptr; } @@ -282,9 +262,7 @@ static const char *GetStreamOutputType(const obs_service_t *service) if ((obs_get_output_flags(output) & OBS_OUTPUT_SERVICE) != 0) return output; - blog(LOG_WARNING, - "The output '%s' is not registered, fallback to another one", - output); + blog(LOG_WARNING, "The output '%s' is not registered, fallback to another one", output); } /* Otherwise, prefer first-party output types */ @@ -292,8 +270,7 @@ static const char *GetStreamOutputType(const obs_service_t *service) return "rtmp_output"; } else if (can_use_output(protocol, "ffmpeg_hls_muxer", "HLS")) { return "ffmpeg_hls_muxer"; - } else if (can_use_output(protocol, "ffmpeg_mpegts_muxer", "SRT", - "RIST")) { + } else if (can_use_output(protocol, "ffmpeg_mpegts_muxer", "SRT", "RIST")) { return "ffmpeg_mpegts_muxer"; } @@ -302,9 +279,7 @@ static const char *GetStreamOutputType(const obs_service_t *service) if (output) return output; - blog(LOG_WARNING, - "No output compatible with the service '%s' is registered", - obs_service_get_id(service)); + blog(LOG_WARNING, "No output compatible with the service '%s' is registered", obs_service_get_id(service)); return nullptr; } @@ -314,26 +289,19 @@ static const char *GetStreamOutputType(const obs_service_t *service) inline BasicOutputHandler::BasicOutputHandler(OBSBasic *main_) : main(main_) { if (main->vcamEnabled) { - virtualCam = obs_output_create( - VIRTUAL_CAM_ID, "virtualcam_output", nullptr, nullptr); + virtualCam = obs_output_create(VIRTUAL_CAM_ID, "virtualcam_output", nullptr, nullptr); - signal_handler_t *signal = - obs_output_get_signal_handler(virtualCam); - startVirtualCam.Connect(signal, "start", OBSStartVirtualCam, - this); + signal_handler_t *signal = obs_output_get_signal_handler(virtualCam); + startVirtualCam.Connect(signal, "start", OBSStartVirtualCam, this); stopVirtualCam.Connect(signal, "stop", OBSStopVirtualCam, this); - deactivateVirtualCam.Connect(signal, "deactivate", - OBSDeactivateVirtualCam, this); + deactivateVirtualCam.Connect(signal, "deactivate", OBSDeactivateVirtualCam, this); } - auto multitrack_enabled = config_get_bool(main->Config(), "Stream1", - "EnableMultitrackVideo"); - if (!config_has_user_value(main->Config(), "Stream1", - "EnableMultitrackVideo")) { + auto multitrack_enabled = config_get_bool(main->Config(), "Stream1", "EnableMultitrackVideo"); + if (!config_has_user_value(main->Config(), "Stream1", "EnableMultitrackVideo")) { auto service = main_->GetService(); OBSDataAutoRelease settings = obs_service_get_settings(service); - multitrack_enabled = obs_data_has_user_value( - settings, "multitrack_video_configuration_url"); + multitrack_enabled = obs_data_has_user_value(settings, "multitrack_video_configuration_url"); } if (multitrack_enabled) multitrackVideo = make_unique(); @@ -346,8 +314,7 @@ bool BasicOutputHandler::StartVirtualCam() if (!main->vcamEnabled) return false; - bool typeIsProgram = main->vcamConfig.type == - VCamOutputType::ProgramView; + bool typeIsProgram = main->vcamConfig.type == VCamOutputType::ProgramView; if (!virtualCamView && !typeIsProgram) virtualCamView = obs_view_create(); @@ -355,8 +322,7 @@ bool BasicOutputHandler::StartVirtualCam() UpdateVirtualCamOutputSource(); if (!virtualCamVideo) { - virtualCamVideo = typeIsProgram ? obs_get_video() - : obs_view_add(virtualCamView); + virtualCamVideo = typeIsProgram ? obs_get_video() : obs_view_add(virtualCamView); if (!virtualCamVideo) return false; @@ -377,9 +343,7 @@ bool BasicOutputHandler::StartVirtualCam() errorReason = QTStr("Output.StartFailedGeneric"); } - QMessageBox::critical(main, - QTStr("Output.StartVirtualCamFailed"), - errorReason); + QMessageBox::critical(main, QTStr("Output.StartVirtualCamFailed"), errorReason); DestroyVirtualCamView(); } @@ -428,17 +392,13 @@ void BasicOutputHandler::UpdateVirtualCamOutputSource() source = obs_get_source_by_name(main->vcamConfig.scene.c_str()); break; case VCamOutputType::SourceOutput: - OBSSourceAutoRelease s = - obs_get_source_by_name(main->vcamConfig.source.c_str()); + OBSSourceAutoRelease s = obs_get_source_by_name(main->vcamConfig.source.c_str()); if (!vCamSourceScene) - vCamSourceScene = - obs_scene_create_private("vcam_source"); - source = obs_source_get_ref( - obs_scene_get_source(vCamSourceScene)); + vCamSourceScene = obs_scene_create_private("vcam_source"); + source = obs_source_get_ref(obs_scene_get_source(vCamSourceScene)); - if (vCamSourceSceneItem && - (obs_sceneitem_get_source(vCamSourceSceneItem) != s)) { + if (vCamSourceSceneItem && (obs_sceneitem_get_source(vCamSourceSceneItem) != s)) { obs_sceneitem_remove(vCamSourceSceneItem); vCamSourceSceneItem = nullptr; } @@ -446,10 +406,8 @@ void BasicOutputHandler::UpdateVirtualCamOutputSource() if (!vCamSourceSceneItem) { vCamSourceSceneItem = obs_scene_add(vCamSourceScene, s); - obs_sceneitem_set_bounds_type(vCamSourceSceneItem, - OBS_BOUNDS_SCALE_INNER); - obs_sceneitem_set_bounds_alignment(vCamSourceSceneItem, - OBS_ALIGN_CENTER); + obs_sceneitem_set_bounds_type(vCamSourceSceneItem, OBS_BOUNDS_SCALE_INNER); + obs_sceneitem_set_bounds_alignment(vCamSourceSceneItem, OBS_ALIGN_CENTER); const struct vec2 size = { (float)obs_source_get_width(source), @@ -541,9 +499,8 @@ struct SimpleOutput : BasicOutputHandler { bool IsVodTrackEnabled(obs_service_t *service); void SetupVodTrack(obs_service_t *service); - virtual std::shared_future - SetupStreaming(obs_service_t *service, - SetupStreamingContinuation_t continuation) override; + virtual std::shared_future SetupStreaming(obs_service_t *service, + SetupStreamingContinuation_t continuation) override; virtual bool StartStreaming(obs_service_t *service) override; virtual bool StartRecording() override; virtual bool StartReplayBuffer() override; @@ -557,8 +514,7 @@ struct SimpleOutput : BasicOutputHandler { void SimpleOutput::LoadRecordingPreset_Lossless() { - fileOutput = obs_output_create("ffmpeg_output", "simple_ffmpeg_output", - nullptr, nullptr); + fileOutput = obs_output_create("ffmpeg_output", "simple_ffmpeg_output", nullptr, nullptr); if (!fileOutput) throw "Failed to create recording FFmpeg output " "(simple output)"; @@ -573,8 +529,7 @@ void SimpleOutput::LoadRecordingPreset_Lossless() void SimpleOutput::LoadRecordingPreset_Lossy(const char *encoderId) { - videoRecording = obs_video_encoder_create( - encoderId, "simple_video_recording", nullptr, nullptr); + videoRecording = obs_video_encoder_create(encoderId, "simple_video_recording", nullptr, nullptr); if (!videoRecording) throw "Failed to create video recording encoder (simple output)"; obs_encoder_release(videoRecording); @@ -582,8 +537,7 @@ void SimpleOutput::LoadRecordingPreset_Lossy(const char *encoderId) void SimpleOutput::LoadStreamingPreset_Lossy(const char *encoderId) { - videoStreaming = obs_video_encoder_create( - encoderId, "simple_video_stream", nullptr, nullptr); + videoStreaming = obs_video_encoder_create(encoderId, "simple_video_stream", nullptr, nullptr); if (!videoStreaming) throw "Failed to create video streaming encoder (simple output)"; obs_encoder_release(videoStreaming); @@ -609,14 +563,10 @@ const char *get_simple_output_encoder(const char *encoder) } else if (strcmp(encoder, SIMPLE_ENCODER_AMD_AV1) == 0) { return "av1_texture_amf"; } else if (strcmp(encoder, SIMPLE_ENCODER_NVENC) == 0) { - return EncoderAvailable("obs_nvenc_h264_tex") - ? "obs_nvenc_h264_tex" - : "ffmpeg_nvenc"; + return EncoderAvailable("obs_nvenc_h264_tex") ? "obs_nvenc_h264_tex" : "ffmpeg_nvenc"; #ifdef ENABLE_HEVC } else if (strcmp(encoder, SIMPLE_ENCODER_NVENC_HEVC) == 0) { - return EncoderAvailable("obs_nvenc_hevc_tex") - ? "obs_nvenc_hevc_tex" - : "ffmpeg_hevc_nvenc"; + return EncoderAvailable("obs_nvenc_hevc_tex") ? "obs_nvenc_hevc_tex" : "ffmpeg_hevc_nvenc"; #endif } else if (strcmp(encoder, SIMPLE_ENCODER_NVENC_AV1) == 0) { return "obs_nvenc_av1_tex"; @@ -633,12 +583,9 @@ const char *get_simple_output_encoder(const char *encoder) void SimpleOutput::LoadRecordingPreset() { - const char *quality = - config_get_string(main->Config(), "SimpleOutput", "RecQuality"); - const char *encoder = - config_get_string(main->Config(), "SimpleOutput", "RecEncoder"); - const char *audio_encoder = config_get_string( - main->Config(), "SimpleOutput", "RecAudioEncoder"); + const char *quality = config_get_string(main->Config(), "SimpleOutput", "RecQuality"); + const char *encoder = config_get_string(main->Config(), "SimpleOutput", "RecEncoder"); + const char *audio_encoder = config_get_string(main->Config(), "SimpleOutput", "RecAudioEncoder"); videoEncoder = encoder; videoQuality = quality; @@ -667,12 +614,9 @@ void SimpleOutput::LoadRecordingPreset() bool success = false; if (strcmp(audio_encoder, "opus") == 0) - success = CreateSimpleOpusEncoder( - audioRecording, 192, "simple_opus_recording", - 0); + success = CreateSimpleOpusEncoder(audioRecording, 192, "simple_opus_recording", 0); else - success = CreateSimpleAACEncoder( - audioRecording, 192, "simple_aac_recording", 0); + success = CreateSimpleAACEncoder(audioRecording, 192, "simple_aac_recording", 0); if (!success) throw "Failed to create audio recording encoder " @@ -680,17 +624,11 @@ void SimpleOutput::LoadRecordingPreset() for (int i = 0; i < MAX_AUDIO_MIXES; i++) { char name[23]; if (strcmp(audio_encoder, "opus") == 0) { - snprintf(name, sizeof name, - "simple_opus_recording%d", i); - success = CreateSimpleOpusEncoder( - audioTrack[i], GetAudioBitrate(), name, - i); + snprintf(name, sizeof name, "simple_opus_recording%d", i); + success = CreateSimpleOpusEncoder(audioTrack[i], GetAudioBitrate(), name, i); } else { - snprintf(name, sizeof name, - "simple_aac_recording%d", i); - success = CreateSimpleAACEncoder( - audioTrack[i], GetAudioBitrate(), name, - i); + snprintf(name, sizeof name, "simple_aac_recording%d", i); + success = CreateSimpleAACEncoder(audioTrack[i], GetAudioBitrate(), name, i); } if (!success) throw "Failed to create multi-track audio recording encoder " @@ -703,33 +641,25 @@ void SimpleOutput::LoadRecordingPreset() SimpleOutput::SimpleOutput(OBSBasic *main_) : BasicOutputHandler(main_) { - const char *encoder = config_get_string(main->Config(), "SimpleOutput", - "StreamEncoder"); - const char *audio_encoder = config_get_string( - main->Config(), "SimpleOutput", "StreamAudioEncoder"); + const char *encoder = config_get_string(main->Config(), "SimpleOutput", "StreamEncoder"); + const char *audio_encoder = config_get_string(main->Config(), "SimpleOutput", "StreamAudioEncoder"); LoadStreamingPreset_Lossy(get_simple_output_encoder(encoder)); bool success = false; if (strcmp(audio_encoder, "opus") == 0) - success = CreateSimpleOpusEncoder( - audioStreaming, GetAudioBitrate(), "simple_opus", 0); + success = CreateSimpleOpusEncoder(audioStreaming, GetAudioBitrate(), "simple_opus", 0); else - success = CreateSimpleAACEncoder( - audioStreaming, GetAudioBitrate(), "simple_aac", 0); + success = CreateSimpleAACEncoder(audioStreaming, GetAudioBitrate(), "simple_aac", 0); if (!success) throw "Failed to create audio streaming encoder (simple output)"; if (strcmp(audio_encoder, "opus") == 0) - success = CreateSimpleOpusEncoder(audioArchive, - GetAudioBitrate(), - SIMPLE_ARCHIVE_NAME, 1); + success = CreateSimpleOpusEncoder(audioArchive, GetAudioBitrate(), SIMPLE_ARCHIVE_NAME, 1); else - success = CreateSimpleAACEncoder(audioArchive, - GetAudioBitrate(), - SIMPLE_ARCHIVE_NAME, 1); + success = CreateSimpleAACEncoder(audioArchive, GetAudioBitrate(), SIMPLE_ARCHIVE_NAME, 1); if (!success) throw "Failed to create audio archive encoder (simple output)"; @@ -737,65 +667,48 @@ SimpleOutput::SimpleOutput(OBSBasic *main_) : BasicOutputHandler(main_) LoadRecordingPreset(); if (!ffmpegOutput) { - bool useReplayBuffer = config_get_bool(main->Config(), - "SimpleOutput", "RecRB"); - const char *recFormat = config_get_string( - main->Config(), "SimpleOutput", "RecFormat2"); + bool useReplayBuffer = config_get_bool(main->Config(), "SimpleOutput", "RecRB"); + const char *recFormat = config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); if (useReplayBuffer) { OBSDataAutoRelease hotkey; - const char *str = config_get_string( - main->Config(), "Hotkeys", "ReplayBuffer"); + const char *str = config_get_string(main->Config(), "Hotkeys", "ReplayBuffer"); if (str) hotkey = obs_data_create_from_json(str); else hotkey = nullptr; - replayBuffer = obs_output_create("replay_buffer", - Str("ReplayBuffer"), - nullptr, hotkey); + replayBuffer = obs_output_create("replay_buffer", Str("ReplayBuffer"), nullptr, hotkey); if (!replayBuffer) throw "Failed to create replay buffer output " "(simple output)"; - signal_handler_t *signal = - obs_output_get_signal_handler(replayBuffer); + signal_handler_t *signal = obs_output_get_signal_handler(replayBuffer); - startReplayBuffer.Connect(signal, "start", - OBSStartReplayBuffer, this); - stopReplayBuffer.Connect(signal, "stop", - OBSStopReplayBuffer, this); - replayBufferStopping.Connect(signal, "stopping", - OBSReplayBufferStopping, - this); - replayBufferSaved.Connect(signal, "saved", - OBSReplayBufferSaved, this); + startReplayBuffer.Connect(signal, "start", OBSStartReplayBuffer, this); + stopReplayBuffer.Connect(signal, "stop", OBSStopReplayBuffer, this); + replayBufferStopping.Connect(signal, "stopping", OBSReplayBufferStopping, this); + replayBufferSaved.Connect(signal, "saved", OBSReplayBufferSaved, this); } bool use_native = strcmp(recFormat, "hybrid_mp4") == 0; - fileOutput = obs_output_create( - use_native ? "mp4_output" : "ffmpeg_muxer", - "simple_file_output", nullptr, nullptr); + fileOutput = obs_output_create(use_native ? "mp4_output" : "ffmpeg_muxer", "simple_file_output", + nullptr, nullptr); if (!fileOutput) throw "Failed to create recording output " "(simple output)"; } - startRecording.Connect(obs_output_get_signal_handler(fileOutput), - "start", OBSStartRecording, this); - stopRecording.Connect(obs_output_get_signal_handler(fileOutput), "stop", - OBSStopRecording, this); - recordStopping.Connect(obs_output_get_signal_handler(fileOutput), - "stopping", OBSRecordStopping, this); + startRecording.Connect(obs_output_get_signal_handler(fileOutput), "start", OBSStartRecording, this); + stopRecording.Connect(obs_output_get_signal_handler(fileOutput), "stop", OBSStopRecording, this); + recordStopping.Connect(obs_output_get_signal_handler(fileOutput), "stopping", OBSRecordStopping, this); } int SimpleOutput::GetAudioBitrate() const { - const char *audio_encoder = config_get_string( - main->Config(), "SimpleOutput", "StreamAudioEncoder"); - int bitrate = (int)config_get_uint(main->Config(), "SimpleOutput", - "ABitrate"); + const char *audio_encoder = config_get_string(main->Config(), "SimpleOutput", "StreamAudioEncoder"); + int bitrate = (int)config_get_uint(main->Config(), "SimpleOutput", "ABitrate"); if (strcmp(audio_encoder, "opus") == 0) return FindClosestAvailableSimpleOpusBitrate(bitrate); @@ -808,17 +721,12 @@ void SimpleOutput::Update() OBSDataAutoRelease videoSettings = obs_data_create(); OBSDataAutoRelease audioSettings = obs_data_create(); - int videoBitrate = - config_get_uint(main->Config(), "SimpleOutput", "VBitrate"); + int videoBitrate = config_get_uint(main->Config(), "SimpleOutput", "VBitrate"); int audioBitrate = GetAudioBitrate(); - bool advanced = - config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced"); - bool enforceBitrate = !config_get_bool(main->Config(), "Stream1", - "IgnoreRecommended"); - const char *custom = config_get_string(main->Config(), "SimpleOutput", - "x264Settings"); - const char *encoder = config_get_string(main->Config(), "SimpleOutput", - "StreamEncoder"); + bool advanced = config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced"); + bool enforceBitrate = !config_get_bool(main->Config(), "Stream1", "IgnoreRecommended"); + const char *custom = config_get_string(main->Config(), "SimpleOutput", "x264Settings"); + const char *encoder = config_get_string(main->Config(), "SimpleOutput", "StreamEncoder"); const char *encoder_id = obs_encoder_get_id(videoStreaming); const char *presetType; const char *preset; @@ -858,8 +766,7 @@ void SimpleOutput::Update() preset = config_get_string(main->Config(), "SimpleOutput", presetType); /* Only use preset2 for legacy/FFmpeg NVENC Encoder. */ - if (strncmp(encoder_id, "ffmpeg_", 7) == 0 && - strcmp(presetType, "NVENCPreset2") == 0) { + if (strncmp(encoder_id, "ffmpeg_", 7) == 0 && strcmp(presetType, "NVENCPreset2") == 0) { obs_data_set_string(videoSettings, "preset2", preset); } else { obs_data_set_string(videoSettings, "preset", preset); @@ -874,8 +781,7 @@ void SimpleOutput::Update() obs_data_set_string(audioSettings, "rate_control", "CBR"); obs_data_set_int(audioSettings, "bitrate", audioBitrate); - obs_service_apply_encoder_settings(main->GetService(), videoSettings, - audioSettings); + obs_service_apply_encoder_settings(main->GetService(), videoSettings, audioSettings); if (!enforceBitrate) { blog(LOG_INFO, "User is ignoring service bitrate limits."); @@ -893,8 +799,7 @@ void SimpleOutput::Update() case VIDEO_FORMAT_P010: break; default: - obs_encoder_set_preferred_video_format(videoStreaming, - VIDEO_FORMAT_NV12); + obs_encoder_set_preferred_video_format(videoStreaming, VIDEO_FORMAT_NV12); } obs_encoder_update(videoStreaming, videoSettings); @@ -908,12 +813,9 @@ void SimpleOutput::UpdateRecordingAudioSettings() obs_data_set_int(settings, "bitrate", 192); obs_data_set_string(settings, "rate_control", "CBR"); - int tracks = - config_get_int(main->Config(), "SimpleOutput", "RecTracks"); - const char *recFormat = - config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); - const char *quality = - config_get_string(main->Config(), "SimpleOutput", "RecQuality"); + int tracks = config_get_int(main->Config(), "SimpleOutput", "RecTracks"); + const char *recFormat = config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); + const char *quality = config_get_string(main->Config(), "SimpleOutput", "RecQuality"); bool flv = strcmp(recFormat, "flv") == 0; if (flv || strcmp(quality, "Stream") == 0) { @@ -940,8 +842,7 @@ int SimpleOutput::CalcCRF(int crf) crf -= 2; double crossDist = sqrt(fCX * fCX + fCY * fCY); - double crfResReduction = - fmin(CROSS_DIST_CUTOFF, crossDist) / CROSS_DIST_CUTOFF; + double crfResReduction = fmin(CROSS_DIST_CUTOFF, crossDist) / CROSS_DIST_CUTOFF; crfResReduction = (1.0 - crfResReduction) * 10.0; return crf - int(crfResReduction); @@ -954,8 +855,7 @@ void SimpleOutput::UpdateRecordingSettings_x264_crf(int crf) obs_data_set_bool(settings, "use_bufsize", true); obs_data_set_string(settings, "rate_control", "CRF"); obs_data_set_string(settings, "profile", "high"); - obs_data_set_string(settings, "preset", - lowCPUx264 ? "ultrafast" : "veryfast"); + obs_data_set_string(settings, "preset", lowCPUx264 ? "ultrafast" : "veryfast"); obs_encoder_update(videoRecording, settings); } @@ -1101,27 +1001,21 @@ inline void SimpleOutput::SetupOutputs() obs_encoder_set_video(videoStreaming, obs_get_video()); obs_encoder_set_audio(audioStreaming, obs_get_audio()); obs_encoder_set_audio(audioArchive, obs_get_audio()); - int tracks = - config_get_int(main->Config(), "SimpleOutput", "RecTracks"); - const char *recFormat = - config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); + int tracks = config_get_int(main->Config(), "SimpleOutput", "RecTracks"); + const char *recFormat = config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); bool flv = strcmp(recFormat, "flv") == 0; if (usingRecordingPreset) { if (ffmpegOutput) { - obs_output_set_media(fileOutput, obs_get_video(), - obs_get_audio()); + obs_output_set_media(fileOutput, obs_get_video(), obs_get_audio()); } else { obs_encoder_set_video(videoRecording, obs_get_video()); if (flv) { - obs_encoder_set_audio(audioRecording, - obs_get_audio()); + obs_encoder_set_audio(audioRecording, obs_get_audio()); } else { for (int i = 0; i < MAX_AUDIO_MIXES; i++) { if ((tracks & (1 << i)) != 0) { - obs_encoder_set_audio( - audioTrack[i], - obs_get_audio()); + obs_encoder_set_audio(audioTrack[i], obs_get_audio()); } } } @@ -1146,9 +1040,7 @@ const char *FindAudioEncoderFromCodec(const char *type) return nullptr; } -std::shared_future -SimpleOutput::SetupStreaming(obs_service_t *service, - SetupStreamingContinuation_t continuation) +std::shared_future SimpleOutput::SetupStreaming(obs_service_t *service, SetupStreamingContinuation_t continuation) { if (!Active()) SetupOutputs(); @@ -1166,11 +1058,9 @@ SimpleOutput::SetupStreaming(obs_service_t *service, } auto audio_bitrate = GetAudioBitrate(); - auto vod_track_mixer = IsVodTrackEnabled(service) ? std::optional{1} - : std::nullopt; + auto vod_track_mixer = IsVodTrackEnabled(service) ? std::optional{1} : std::nullopt; - auto handle_multitrack_video_result = [&](std::optional - multitrackVideoResult) { + auto handle_multitrack_video_result = [&](std::optional multitrackVideoResult) { if (multitrackVideoResult.has_value()) return multitrackVideoResult.value(); @@ -1181,8 +1071,7 @@ SimpleOutput::SetupStreaming(obs_service_t *service, startStreaming.Disconnect(); stopStreaming.Disconnect(); - streamOutput = obs_output_create(type, "simple_stream", - nullptr, nullptr); + streamOutput = obs_output_create(type, "simple_stream", nullptr, nullptr); if (!streamOutput) { blog(LOG_WARNING, "Creation of stream output type '%s' " @@ -1191,19 +1080,15 @@ SimpleOutput::SetupStreaming(obs_service_t *service, return false; } - streamDelayStarting.Connect( - obs_output_get_signal_handler(streamOutput), - "starting", OBSStreamStarting, this); - streamStopping.Connect( - obs_output_get_signal_handler(streamOutput), - "stopping", OBSStreamStopping, this); + streamDelayStarting.Connect(obs_output_get_signal_handler(streamOutput), "starting", + OBSStreamStarting, this); + streamStopping.Connect(obs_output_get_signal_handler(streamOutput), "stopping", + OBSStreamStopping, this); - startStreaming.Connect( - obs_output_get_signal_handler(streamOutput), - "start", OBSStartStreaming, this); - stopStreaming.Connect( - obs_output_get_signal_handler(streamOutput), - "stop", OBSStopStreaming, this); + startStreaming.Connect(obs_output_get_signal_handler(streamOutput), "start", OBSStartStreaming, + this); + stopStreaming.Connect(obs_output_get_signal_handler(streamOutput), "stop", OBSStopStreaming, + this); outputType = type; } @@ -1214,17 +1099,15 @@ SimpleOutput::SetupStreaming(obs_service_t *service, return true; }; - return SetupMultitrackVideo( - service, GetSimpleAACEncoderForBitrate(audio_bitrate), 0, - vod_track_mixer, [&, continuation](std::optional res) { - continuation(handle_multitrack_video_result(res)); - }); + return SetupMultitrackVideo(service, GetSimpleAACEncoderForBitrate(audio_bitrate), 0, vod_track_mixer, + [&, continuation](std::optional res) { + continuation(handle_multitrack_video_result(res)); + }); } static inline bool ServiceSupportsVodTrack(const char *service); -static void clear_archive_encoder(obs_output_t *output, - const char *expected_name) +static void clear_archive_encoder(obs_output_t *output, const char *expected_name) { obs_encoder_t *last = obs_output_get_audio_encoder(output, 1); bool clear = false; @@ -1242,13 +1125,9 @@ static void clear_archive_encoder(obs_output_t *output, bool SimpleOutput::IsVodTrackEnabled(obs_service_t *service) { - bool advanced = - config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced"); - bool enable = config_get_bool(main->Config(), "SimpleOutput", - "VodTrackEnabled"); - bool enableForCustomServer = - config_get_bool(App()->GetUserConfig(), "General", - "EnableCustomServerVodTrack"); + bool advanced = config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced"); + bool enable = config_get_bool(main->Config(), "SimpleOutput", "VodTrackEnabled"); + bool enableForCustomServer = config_get_bool(App()->GetUserConfig(), "General", "EnableCustomServerVodTrack"); OBSDataAutoRelease settings = obs_service_get_settings(service); const char *name = obs_data_get_string(settings, "service"); @@ -1271,34 +1150,24 @@ void SimpleOutput::SetupVodTrack(obs_service_t *service) bool SimpleOutput::StartStreaming(obs_service_t *service) { bool reconnect = config_get_bool(main->Config(), "Output", "Reconnect"); - int retryDelay = - config_get_uint(main->Config(), "Output", "RetryDelay"); - int maxRetries = - config_get_uint(main->Config(), "Output", "MaxRetries"); - bool useDelay = - config_get_bool(main->Config(), "Output", "DelayEnable"); + int retryDelay = config_get_uint(main->Config(), "Output", "RetryDelay"); + int maxRetries = config_get_uint(main->Config(), "Output", "MaxRetries"); + bool useDelay = config_get_bool(main->Config(), "Output", "DelayEnable"); int delaySec = config_get_int(main->Config(), "Output", "DelaySec"); - bool preserveDelay = - config_get_bool(main->Config(), "Output", "DelayPreserve"); - const char *bindIP = - config_get_string(main->Config(), "Output", "BindIP"); - const char *ipFamily = - config_get_string(main->Config(), "Output", "IPFamily"); + bool preserveDelay = config_get_bool(main->Config(), "Output", "DelayPreserve"); + const char *bindIP = config_get_string(main->Config(), "Output", "BindIP"); + const char *ipFamily = config_get_string(main->Config(), "Output", "IPFamily"); #ifdef _WIN32 - bool enableNewSocketLoop = config_get_bool(main->Config(), "Output", - "NewSocketLoopEnable"); - bool enableLowLatencyMode = - config_get_bool(main->Config(), "Output", "LowLatencyEnable"); + bool enableNewSocketLoop = config_get_bool(main->Config(), "Output", "NewSocketLoopEnable"); + bool enableLowLatencyMode = config_get_bool(main->Config(), "Output", "LowLatencyEnable"); #else bool enableNewSocketLoop = false; #endif - bool enableDynBitrate = - config_get_bool(main->Config(), "Output", "DynamicBitrate"); + bool enableDynBitrate = config_get_bool(main->Config(), "Output", "DynamicBitrate"); if (multitrackVideo && multitrackVideoActive && - !multitrackVideo->HandleIncompatibleSettings( - main, main->Config(), service, useDelay, - enableNewSocketLoop, enableDynBitrate)) { + !multitrackVideo->HandleIncompatibleSettings(main, main->Config(), service, useDelay, enableNewSocketLoop, + enableDynBitrate)) { multitrackVideoActive = false; return false; } @@ -1307,23 +1176,19 @@ bool SimpleOutput::StartStreaming(obs_service_t *service) obs_data_set_string(settings, "bind_ip", bindIP); obs_data_set_string(settings, "ip_family", ipFamily); #ifdef _WIN32 - obs_data_set_bool(settings, "new_socket_loop_enabled", - enableNewSocketLoop); - obs_data_set_bool(settings, "low_latency_mode_enabled", - enableLowLatencyMode); + obs_data_set_bool(settings, "new_socket_loop_enabled", enableNewSocketLoop); + obs_data_set_bool(settings, "low_latency_mode_enabled", enableLowLatencyMode); #endif obs_data_set_bool(settings, "dyn_bitrate", enableDynBitrate); - auto streamOutput = - StreamingOutput(); // shadowing is sort of bad, but also convenient + auto streamOutput = StreamingOutput(); // shadowing is sort of bad, but also convenient obs_output_update(streamOutput, settings); if (!reconnect) maxRetries = 0; - obs_output_set_delay(streamOutput, useDelay ? delaySec : 0, - preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0); + obs_output_set_delay(streamOutput, useDelay ? delaySec : 0, preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0); obs_output_set_reconnect_settings(streamOutput, maxRetries, retryDelay); @@ -1347,22 +1212,19 @@ bool SimpleOutput::StartStreaming(obs_service_t *service) lastError = string(); const char *type = obs_output_get_id(streamOutput); - blog(LOG_WARNING, "Stream output type '%s' failed to start!%s%s", type, - hasLastError ? " Last Error: " : "", hasLastError ? error : ""); + blog(LOG_WARNING, "Stream output type '%s' failed to start!%s%s", type, hasLastError ? " Last Error: " : "", + hasLastError ? error : ""); return false; } void SimpleOutput::UpdateRecording() { - const char *recFormat = - config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); + const char *recFormat = config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); bool flv = strcmp(recFormat, "flv") == 0; - int tracks = - config_get_int(main->Config(), "SimpleOutput", "RecTracks"); + int tracks = config_get_int(main->Config(), "SimpleOutput", "RecTracks"); int idx = 0; int idx2 = 0; - const char *quality = - config_get_string(main->Config(), "SimpleOutput", "RecQuality"); + const char *quality = config_get_string(main->Config(), "SimpleOutput", "RecQuality"); if (replayBufferActive || recordingActive) return; @@ -1380,14 +1242,11 @@ void SimpleOutput::UpdateRecording() if (!ffmpegOutput) { obs_output_set_video_encoder(fileOutput, videoRecording); if (flv || strcmp(quality, "Stream") == 0) { - obs_output_set_audio_encoder(fileOutput, audioRecording, - 0); + obs_output_set_audio_encoder(fileOutput, audioRecording, 0); } else { for (int i = 0; i < MAX_AUDIO_MIXES; i++) { if ((tracks & (1 << i)) != 0) { - obs_output_set_audio_encoder( - fileOutput, audioTrack[i], - idx++); + obs_output_set_audio_encoder(fileOutput, audioTrack[i], idx++); } } } @@ -1395,14 +1254,11 @@ void SimpleOutput::UpdateRecording() if (replayBuffer) { obs_output_set_video_encoder(replayBuffer, videoRecording); if (flv || strcmp(quality, "Stream") == 0) { - obs_output_set_audio_encoder(replayBuffer, - audioRecording, 0); + obs_output_set_audio_encoder(replayBuffer, audioRecording, 0); } else { for (int i = 0; i < MAX_AUDIO_MIXES; i++) { if ((tracks & (1 << i)) != 0) { - obs_output_set_audio_encoder( - replayBuffer, audioTrack[i], - idx2++); + obs_output_set_audio_encoder(replayBuffer, audioTrack[i], idx2++); } } } @@ -1413,28 +1269,17 @@ void SimpleOutput::UpdateRecording() bool SimpleOutput::ConfigureRecording(bool updateReplayBuffer) { - const char *path = - config_get_string(main->Config(), "SimpleOutput", "FilePath"); - const char *format = - config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); - const char *mux = config_get_string(main->Config(), "SimpleOutput", - "MuxerCustom"); - bool noSpace = config_get_bool(main->Config(), "SimpleOutput", - "FileNameWithoutSpace"); - const char *filenameFormat = config_get_string(main->Config(), "Output", - "FilenameFormatting"); - bool overwriteIfExists = - config_get_bool(main->Config(), "Output", "OverwriteIfExists"); - const char *rbPrefix = config_get_string(main->Config(), "SimpleOutput", - "RecRBPrefix"); - const char *rbSuffix = config_get_string(main->Config(), "SimpleOutput", - "RecRBSuffix"); - int rbTime = - config_get_int(main->Config(), "SimpleOutput", "RecRBTime"); - int rbSize = - config_get_int(main->Config(), "SimpleOutput", "RecRBSize"); - int tracks = - config_get_int(main->Config(), "SimpleOutput", "RecTracks"); + const char *path = config_get_string(main->Config(), "SimpleOutput", "FilePath"); + const char *format = config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); + const char *mux = config_get_string(main->Config(), "SimpleOutput", "MuxerCustom"); + bool noSpace = config_get_bool(main->Config(), "SimpleOutput", "FileNameWithoutSpace"); + const char *filenameFormat = config_get_string(main->Config(), "Output", "FilenameFormatting"); + bool overwriteIfExists = config_get_bool(main->Config(), "Output", "OverwriteIfExists"); + const char *rbPrefix = config_get_string(main->Config(), "SimpleOutput", "RecRBPrefix"); + const char *rbSuffix = config_get_string(main->Config(), "SimpleOutput", "RecRBSuffix"); + int rbTime = config_get_int(main->Config(), "SimpleOutput", "RecRBTime"); + int rbSize = config_get_int(main->Config(), "SimpleOutput", "RecRBSize"); + int tracks = config_get_int(main->Config(), "SimpleOutput", "RecTracks"); bool is_fragmented = strncmp(format, "fragmented", 10) == 0; bool is_lossless = videoQuality == "Lossless"; @@ -1450,35 +1295,28 @@ bool SimpleOutput::ConfigureRecording(bool updateReplayBuffer) obs_data_set_string(settings, "extension", ext.c_str()); obs_data_set_bool(settings, "allow_spaces", !noSpace); obs_data_set_int(settings, "max_time_sec", rbTime); - obs_data_set_int(settings, "max_size_mb", - usingRecordingPreset ? rbSize : 0); + obs_data_set_int(settings, "max_size_mb", usingRecordingPreset ? rbSize : 0); } else { f = GetFormatString(filenameFormat, nullptr, nullptr); - string strPath = GetRecordingFilename( - path, ffmpegOutput ? "avi" : format, noSpace, - overwriteIfExists, f.c_str(), ffmpegOutput); - obs_data_set_string(settings, ffmpegOutput ? "url" : "path", - strPath.c_str()); + string strPath = GetRecordingFilename(path, ffmpegOutput ? "avi" : format, noSpace, overwriteIfExists, + f.c_str(), ffmpegOutput); + obs_data_set_string(settings, ffmpegOutput ? "url" : "path", strPath.c_str()); if (ffmpegOutput) obs_output_set_mixers(fileOutput, tracks); } // Use fragmented MOV/MP4 if user has not already specified custom movflags - if (is_fragmented && !is_lossless && - (!mux || strstr(mux, "movflags") == NULL)) { - string mux_frag = - "movflags=frag_keyframe+empty_moov+delay_moov"; + if (is_fragmented && !is_lossless && (!mux || strstr(mux, "movflags") == NULL)) { + string mux_frag = "movflags=frag_keyframe+empty_moov+delay_moov"; if (mux) { mux_frag += " "; mux_frag += mux; } - obs_data_set_string(settings, "muxer_settings", - mux_frag.c_str()); + obs_data_set_string(settings, "muxer_settings", mux_frag.c_str()); } else { if (is_fragmented && !is_lossless) - blog(LOG_WARNING, - "User enabled fragmented recording, " - "but custom muxer settings contained movflags."); + blog(LOG_WARNING, "User enabled fragmented recording, " + "but custom muxer settings contained movflags."); obs_data_set_string(settings, "muxer_settings", mux); } @@ -1502,9 +1340,7 @@ bool SimpleOutput::StartRecording() error_reason = QT_UTF8(error); else error_reason = QTStr("Output.StartFailedGeneric"); - QMessageBox::critical(main, - QTStr("Output.StartRecordingFailed"), - error_reason); + QMessageBox::critical(main, QTStr("Output.StartRecordingFailed"), error_reason); return false; } @@ -1517,8 +1353,7 @@ bool SimpleOutput::StartReplayBuffer() if (!ConfigureRecording(true)) return false; if (!obs_output_start(replayBuffer)) { - QMessageBox::critical(main, QTStr("Output.StartReplayFailed"), - QTStr("Output.StartFailedGeneric")); + QMessageBox::critical(main, QTStr("Output.StartReplayFailed"), QTStr("Output.StartFailedGeneric")); return false; } @@ -1599,9 +1434,8 @@ struct AdvancedOutput : BasicOutputHandler { void SetupOutputs() override; int GetAudioBitrate(size_t i, const char *id) const; - virtual std::shared_future - SetupStreaming(obs_service_t *service, - SetupStreamingContinuation_t continuation) override; + virtual std::shared_future SetupStreaming(obs_service_t *service, + SetupStreamingContinuation_t continuation) override; virtual bool StartStreaming(obs_service_t *service) override; virtual bool StartRecording() override; virtual bool StartReplayBuffer() override; @@ -1616,19 +1450,16 @@ struct AdvancedOutput : BasicOutputHandler { static OBSData GetDataFromJsonFile(const char *jsonFile) { - const OBSBasic *basic = - reinterpret_cast(App()->GetMainWindow()); + const OBSBasic *basic = reinterpret_cast(App()->GetMainWindow()); const OBSProfile ¤tProfile = basic->GetCurrentProfile(); - const std::filesystem::path jsonFilePath = - currentProfile.path / std::filesystem::u8path(jsonFile); + const std::filesystem::path jsonFilePath = currentProfile.path / std::filesystem::u8path(jsonFile); OBSDataAutoRelease data = nullptr; if (!jsonFilePath.empty()) { - BPtr jsonData = os_quick_read_utf8_file( - jsonFilePath.u8string().c_str()); + BPtr jsonData = os_quick_read_utf8_file(jsonFilePath.u8string().c_str()); if (!!jsonData) { data = obs_data_create_from_json(jsonData); @@ -1642,8 +1473,7 @@ static OBSData GetDataFromJsonFile(const char *jsonFile) return data.Get(); } -static void ApplyEncoderDefaults(OBSData &settings, - const obs_encoder_t *encoder) +static void ApplyEncoderDefaults(OBSData &settings, const obs_encoder_t *encoder) { OBSData dataRet = obs_encoder_get_defaults(encoder); obs_data_release(dataRet); @@ -1668,27 +1498,19 @@ static void translate_macvth264_encoder(const char *&encoder) AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) { - const char *recType = - config_get_string(main->Config(), "AdvOut", "RecType"); - const char *streamEncoder = - config_get_string(main->Config(), "AdvOut", "Encoder"); - const char *streamAudioEncoder = - config_get_string(main->Config(), "AdvOut", "AudioEncoder"); - const char *recordEncoder = - config_get_string(main->Config(), "AdvOut", "RecEncoder"); - const char *recAudioEncoder = - config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); - const char *recFormat = - config_get_string(main->Config(), "AdvOut", "RecFormat2"); + const char *recType = config_get_string(main->Config(), "AdvOut", "RecType"); + const char *streamEncoder = config_get_string(main->Config(), "AdvOut", "Encoder"); + const char *streamAudioEncoder = config_get_string(main->Config(), "AdvOut", "AudioEncoder"); + const char *recordEncoder = config_get_string(main->Config(), "AdvOut", "RecEncoder"); + const char *recAudioEncoder = config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); + const char *recFormat = config_get_string(main->Config(), "AdvOut", "RecFormat2"); #ifdef __APPLE__ translate_macvth264_encoder(streamEncoder); translate_macvth264_encoder(recordEncoder); #endif ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0; - ffmpegRecording = - ffmpegOutput && - config_get_bool(main->Config(), "AdvOut", "FFOutputToFile"); + ffmpegRecording = ffmpegOutput && config_get_bool(main->Config(), "AdvOut", "FFOutputToFile"); useStreamEncoder = astrcmpi(recordEncoder, "none") == 0; useStreamAudioEncoder = astrcmpi(recAudioEncoder, "none") == 0; @@ -1696,57 +1518,44 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) OBSData recordEncSettings = GetDataFromJsonFile("recordEncoder.json"); if (ffmpegOutput) { - fileOutput = obs_output_create( - "ffmpeg_output", "adv_ffmpeg_output", nullptr, nullptr); + fileOutput = obs_output_create("ffmpeg_output", "adv_ffmpeg_output", nullptr, nullptr); if (!fileOutput) throw "Failed to create recording FFmpeg output " "(advanced output)"; } else { - bool useReplayBuffer = - config_get_bool(main->Config(), "AdvOut", "RecRB"); + bool useReplayBuffer = config_get_bool(main->Config(), "AdvOut", "RecRB"); if (useReplayBuffer) { OBSDataAutoRelease hotkey; - const char *str = config_get_string( - main->Config(), "Hotkeys", "ReplayBuffer"); + const char *str = config_get_string(main->Config(), "Hotkeys", "ReplayBuffer"); if (str) hotkey = obs_data_create_from_json(str); else hotkey = nullptr; - replayBuffer = obs_output_create("replay_buffer", - Str("ReplayBuffer"), - nullptr, hotkey); + replayBuffer = obs_output_create("replay_buffer", Str("ReplayBuffer"), nullptr, hotkey); if (!replayBuffer) throw "Failed to create replay buffer output " "(simple output)"; - signal_handler_t *signal = - obs_output_get_signal_handler(replayBuffer); + signal_handler_t *signal = obs_output_get_signal_handler(replayBuffer); - startReplayBuffer.Connect(signal, "start", - OBSStartReplayBuffer, this); - stopReplayBuffer.Connect(signal, "stop", - OBSStopReplayBuffer, this); - replayBufferStopping.Connect(signal, "stopping", - OBSReplayBufferStopping, - this); - replayBufferSaved.Connect(signal, "saved", - OBSReplayBufferSaved, this); + startReplayBuffer.Connect(signal, "start", OBSStartReplayBuffer, this); + stopReplayBuffer.Connect(signal, "stop", OBSStopReplayBuffer, this); + replayBufferStopping.Connect(signal, "stopping", OBSReplayBufferStopping, this); + replayBufferSaved.Connect(signal, "saved", OBSReplayBufferSaved, this); } bool native_muxer = strcmp(recFormat, "hybrid_mp4") == 0; - fileOutput = obs_output_create( - native_muxer ? "mp4_output" : "ffmpeg_muxer", - "adv_file_output", nullptr, nullptr); + fileOutput = obs_output_create(native_muxer ? "mp4_output" : "ffmpeg_muxer", "adv_file_output", nullptr, + nullptr); if (!fileOutput) throw "Failed to create recording output " "(advanced output)"; if (!useStreamEncoder) { - videoRecording = obs_video_encoder_create( - recordEncoder, "advanced_video_recording", - recordEncSettings, nullptr); + videoRecording = obs_video_encoder_create(recordEncoder, "advanced_video_recording", + recordEncSettings, nullptr); if (!videoRecording) throw "Failed to create recording video " "encoder (advanced output)"; @@ -1754,31 +1563,25 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) } } - videoStreaming = obs_video_encoder_create(streamEncoder, - "advanced_video_stream", - streamEncSettings, nullptr); + videoStreaming = obs_video_encoder_create(streamEncoder, "advanced_video_stream", streamEncSettings, nullptr); if (!videoStreaming) throw "Failed to create streaming video encoder " "(advanced output)"; obs_encoder_release(videoStreaming); - const char *rate_control = obs_data_get_string( - useStreamEncoder ? streamEncSettings : recordEncSettings, - "rate_control"); + const char *rate_control = + obs_data_get_string(useStreamEncoder ? streamEncSettings : recordEncSettings, "rate_control"); if (!rate_control) rate_control = ""; - usesBitrate = astrcmpi(rate_control, "CBR") == 0 || - astrcmpi(rate_control, "VBR") == 0 || + usesBitrate = astrcmpi(rate_control, "CBR") == 0 || astrcmpi(rate_control, "VBR") == 0 || astrcmpi(rate_control, "ABR") == 0; for (int i = 0; i < MAX_AUDIO_MIXES; i++) { char name[19]; snprintf(name, sizeof(name), "adv_record_audio_%d", i); - recordTrack[i] = obs_audio_encoder_create( - useStreamAudioEncoder ? streamAudioEncoder - : recAudioEncoder, - name, nullptr, i, nullptr); + recordTrack[i] = obs_audio_encoder_create(useStreamAudioEncoder ? streamAudioEncoder : recAudioEncoder, + name, nullptr, i, nullptr); if (!recordTrack[i]) { throw "Failed to create audio encoder " @@ -1788,8 +1591,7 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) obs_encoder_release(recordTrack[i]); snprintf(name, sizeof(name), "adv_stream_audio_%d", i); - streamTrack[i] = obs_audio_encoder_create( - streamAudioEncoder, name, nullptr, i, nullptr); + streamTrack[i] = obs_audio_encoder_create(streamAudioEncoder, name, nullptr, i, nullptr); if (!streamTrack[i]) { throw "Failed to create streaming audio encoders " @@ -1800,47 +1602,35 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) } std::string id; - int streamTrackIndex = - config_get_int(main->Config(), "AdvOut", "TrackIndex") - 1; - streamAudioEnc = obs_audio_encoder_create(streamAudioEncoder, - "adv_stream_audio", nullptr, - streamTrackIndex, nullptr); + int streamTrackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex") - 1; + streamAudioEnc = + obs_audio_encoder_create(streamAudioEncoder, "adv_stream_audio", nullptr, streamTrackIndex, nullptr); if (!streamAudioEnc) throw "Failed to create streaming audio encoder " "(advanced output)"; obs_encoder_release(streamAudioEnc); id = ""; - int vodTrack = - config_get_int(main->Config(), "AdvOut", "VodTrackIndex") - 1; - streamArchiveEnc = obs_audio_encoder_create(streamAudioEncoder, - ADV_ARCHIVE_NAME, nullptr, - vodTrack, nullptr); + int vodTrack = config_get_int(main->Config(), "AdvOut", "VodTrackIndex") - 1; + streamArchiveEnc = obs_audio_encoder_create(streamAudioEncoder, ADV_ARCHIVE_NAME, nullptr, vodTrack, nullptr); if (!streamArchiveEnc) throw "Failed to create archive audio encoder " "(advanced output)"; obs_encoder_release(streamArchiveEnc); - startRecording.Connect(obs_output_get_signal_handler(fileOutput), - "start", OBSStartRecording, this); - stopRecording.Connect(obs_output_get_signal_handler(fileOutput), "stop", - OBSStopRecording, this); - recordStopping.Connect(obs_output_get_signal_handler(fileOutput), - "stopping", OBSRecordStopping, this); - recordFileChanged.Connect(obs_output_get_signal_handler(fileOutput), - "file_changed", OBSRecordFileChanged, this); + startRecording.Connect(obs_output_get_signal_handler(fileOutput), "start", OBSStartRecording, this); + stopRecording.Connect(obs_output_get_signal_handler(fileOutput), "stop", OBSStopRecording, this); + recordStopping.Connect(obs_output_get_signal_handler(fileOutput), "stopping", OBSRecordStopping, this); + recordFileChanged.Connect(obs_output_get_signal_handler(fileOutput), "file_changed", OBSRecordFileChanged, + this); } void AdvancedOutput::UpdateStreamSettings() { - bool applyServiceSettings = config_get_bool(main->Config(), "AdvOut", - "ApplyServiceSettings"); - bool enforceBitrate = !config_get_bool(main->Config(), "Stream1", - "IgnoreRecommended"); - bool dynBitrate = - config_get_bool(main->Config(), "Output", "DynamicBitrate"); - const char *streamEncoder = - config_get_string(main->Config(), "AdvOut", "Encoder"); + bool applyServiceSettings = config_get_bool(main->Config(), "AdvOut", "ApplyServiceSettings"); + bool enforceBitrate = !config_get_bool(main->Config(), "Stream1", "IgnoreRecommended"); + bool dynBitrate = config_get_bool(main->Config(), "Output", "DynamicBitrate"); + const char *streamEncoder = config_get_string(main->Config(), "AdvOut", "Encoder"); OBSData settings = GetDataFromJsonFile("streamEncoder.json"); ApplyEncoderDefaults(settings, videoStreaming); @@ -1848,16 +1638,13 @@ void AdvancedOutput::UpdateStreamSettings() if (applyServiceSettings) { int bitrate = (int)obs_data_get_int(settings, "bitrate"); int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); - obs_service_apply_encoder_settings(main->GetService(), settings, - nullptr); + obs_service_apply_encoder_settings(main->GetService(), settings, nullptr); if (!enforceBitrate) { - blog(LOG_INFO, - "User is ignoring service bitrate limits."); + blog(LOG_INFO, "User is ignoring service bitrate limits."); obs_data_set_int(settings, "bitrate", bitrate); } - int enforced_keyint_sec = - (int)obs_data_get_int(settings, "keyint_sec"); + int enforced_keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); if (keyint_sec != 0 && keyint_sec < enforced_keyint_sec) obs_data_set_int(settings, "keyint_sec", keyint_sec); } else { @@ -1877,8 +1664,7 @@ void AdvancedOutput::UpdateStreamSettings() case VIDEO_FORMAT_P010: break; default: - obs_encoder_set_preferred_video_format(videoStreaming, - VIDEO_FORMAT_NV12); + obs_encoder_set_preferred_video_format(videoStreaming, VIDEO_FORMAT_NV12); } obs_encoder_update(videoStreaming, settings); @@ -1923,12 +1709,9 @@ inline bool AdvancedOutput::allowsMultiTrack() inline void AdvancedOutput::SetupStreaming() { - const char *rescaleRes = - config_get_string(main->Config(), "AdvOut", "RescaleRes"); - int rescaleFilter = - config_get_int(main->Config(), "AdvOut", "RescaleFilter"); - int multiTrackAudioMixes = config_get_int(main->Config(), "AdvOut", - "StreamMultiTrackAudioMixes"); + const char *rescaleRes = config_get_string(main->Config(), "AdvOut", "RescaleRes"); + int rescaleFilter = config_get_int(main->Config(), "AdvOut", "RescaleFilter"); + int multiTrackAudioMixes = config_get_int(main->Config(), "AdvOut", "StreamMultiTrackAudioMixes"); unsigned int cx = 0; unsigned int cy = 0; int idx = 0; @@ -1946,40 +1729,32 @@ inline void AdvancedOutput::SetupStreaming() } else { for (int i = 0; i < MAX_AUDIO_MIXES; i++) { if ((multiTrackAudioMixes & (1 << i)) != 0) { - obs_output_set_audio_encoder( - streamOutput, streamTrack[i], idx); + obs_output_set_audio_encoder(streamOutput, streamTrack[i], idx); idx++; } } } obs_encoder_set_scaled_size(videoStreaming, cx, cy); - obs_encoder_set_gpu_scale_type(videoStreaming, - (obs_scale_type)rescaleFilter); + obs_encoder_set_gpu_scale_type(videoStreaming, (obs_scale_type)rescaleFilter); const char *id = obs_service_get_id(main->GetService()); if (strcmp(id, "rtmp_custom") == 0) { OBSDataAutoRelease settings = obs_data_create(); - obs_service_apply_encoder_settings(main->GetService(), settings, - nullptr); + obs_service_apply_encoder_settings(main->GetService(), settings, nullptr); obs_encoder_update(videoStreaming, settings); } } inline void AdvancedOutput::SetupRecording() { - const char *path = - config_get_string(main->Config(), "AdvOut", "RecFilePath"); - const char *mux = - config_get_string(main->Config(), "AdvOut", "RecMuxerCustom"); - const char *rescaleRes = - config_get_string(main->Config(), "AdvOut", "RecRescaleRes"); - int rescaleFilter = - config_get_int(main->Config(), "AdvOut", "RecRescaleFilter"); + const char *path = config_get_string(main->Config(), "AdvOut", "RecFilePath"); + const char *mux = config_get_string(main->Config(), "AdvOut", "RecMuxerCustom"); + const char *rescaleRes = config_get_string(main->Config(), "AdvOut", "RecRescaleRes"); + int rescaleFilter = config_get_int(main->Config(), "AdvOut", "RecRescaleFilter"); int tracks; - const char *recFormat = - config_get_string(main->Config(), "AdvOut", "RecFormat2"); + const char *recFormat = config_get_string(main->Config(), "AdvOut", "RecFormat2"); bool is_fragmented = strncmp(recFormat, "fragmented", 10) == 0; bool flv = strcmp(recFormat, "flv") == 0; @@ -2004,11 +1779,9 @@ inline void AdvancedOutput::SetupRecording() if (useStreamEncoder) { obs_output_set_video_encoder(fileOutput, videoStreaming); if (replayBuffer) - obs_output_set_video_encoder(replayBuffer, - videoStreaming); + obs_output_set_video_encoder(replayBuffer, videoStreaming); } else { - if (rescaleFilter != OBS_SCALE_DISABLE && rescaleRes && - *rescaleRes) { + if (rescaleFilter != OBS_SCALE_DISABLE && rescaleRes && *rescaleRes) { if (sscanf(rescaleRes, "%ux%u", &cx, &cy) != 2) { cx = 0; cy = 0; @@ -2016,50 +1789,40 @@ inline void AdvancedOutput::SetupRecording() } obs_encoder_set_scaled_size(videoRecording, cx, cy); - obs_encoder_set_gpu_scale_type(videoRecording, - (obs_scale_type)rescaleFilter); + obs_encoder_set_gpu_scale_type(videoRecording, (obs_scale_type)rescaleFilter); obs_output_set_video_encoder(fileOutput, videoRecording); if (replayBuffer) - obs_output_set_video_encoder(replayBuffer, - videoRecording); + obs_output_set_video_encoder(replayBuffer, videoRecording); } if (!flv) { for (int i = 0; i < MAX_AUDIO_MIXES; i++) { if ((tracks & (1 << i)) != 0) { - obs_output_set_audio_encoder( - fileOutput, recordTrack[i], idx); + obs_output_set_audio_encoder(fileOutput, recordTrack[i], idx); if (replayBuffer) - obs_output_set_audio_encoder( - replayBuffer, recordTrack[i], - idx); + obs_output_set_audio_encoder(replayBuffer, recordTrack[i], idx); idx++; } } } else if (flv && tracks != 0) { - obs_output_set_audio_encoder(fileOutput, - recordTrack[tracks - 1], idx); + obs_output_set_audio_encoder(fileOutput, recordTrack[tracks - 1], idx); if (replayBuffer) - obs_output_set_audio_encoder( - replayBuffer, recordTrack[tracks - 1], idx); + obs_output_set_audio_encoder(replayBuffer, recordTrack[tracks - 1], idx); } // Use fragmented MOV/MP4 if user has not already specified custom movflags if (is_fragmented && (!mux || strstr(mux, "movflags") == NULL)) { - string mux_frag = - "movflags=frag_keyframe+empty_moov+delay_moov"; + string mux_frag = "movflags=frag_keyframe+empty_moov+delay_moov"; if (mux) { mux_frag += " "; mux_frag += mux; } - obs_data_set_string(settings, "muxer_settings", - mux_frag.c_str()); + obs_data_set_string(settings, "muxer_settings", mux_frag.c_str()); } else { if (is_fragmented) - blog(LOG_WARNING, - "User enabled fragmented recording, " - "but custom muxer settings contained movflags."); + blog(LOG_WARNING, "User enabled fragmented recording, " + "but custom muxer settings contained movflags."); obs_data_set_string(settings, "muxer_settings", mux); } @@ -2075,28 +1838,18 @@ inline void AdvancedOutput::SetupFFmpeg() int vBitrate = config_get_int(main->Config(), "AdvOut", "FFVBitrate"); int gopSize = config_get_int(main->Config(), "AdvOut", "FFVGOPSize"); bool rescale = config_get_bool(main->Config(), "AdvOut", "FFRescale"); - const char *rescaleRes = - config_get_string(main->Config(), "AdvOut", "FFRescaleRes"); - const char *formatName = - config_get_string(main->Config(), "AdvOut", "FFFormat"); - const char *mimeType = - config_get_string(main->Config(), "AdvOut", "FFFormatMimeType"); - const char *muxCustom = - config_get_string(main->Config(), "AdvOut", "FFMCustom"); - const char *vEncoder = - config_get_string(main->Config(), "AdvOut", "FFVEncoder"); - int vEncoderId = - config_get_int(main->Config(), "AdvOut", "FFVEncoderId"); - const char *vEncCustom = - config_get_string(main->Config(), "AdvOut", "FFVCustom"); + const char *rescaleRes = config_get_string(main->Config(), "AdvOut", "FFRescaleRes"); + const char *formatName = config_get_string(main->Config(), "AdvOut", "FFFormat"); + const char *mimeType = config_get_string(main->Config(), "AdvOut", "FFFormatMimeType"); + const char *muxCustom = config_get_string(main->Config(), "AdvOut", "FFMCustom"); + const char *vEncoder = config_get_string(main->Config(), "AdvOut", "FFVEncoder"); + int vEncoderId = config_get_int(main->Config(), "AdvOut", "FFVEncoderId"); + const char *vEncCustom = config_get_string(main->Config(), "AdvOut", "FFVCustom"); int aBitrate = config_get_int(main->Config(), "AdvOut", "FFABitrate"); int aMixes = config_get_int(main->Config(), "AdvOut", "FFAudioMixes"); - const char *aEncoder = - config_get_string(main->Config(), "AdvOut", "FFAEncoder"); - int aEncoderId = - config_get_int(main->Config(), "AdvOut", "FFAEncoderId"); - const char *aEncCustom = - config_get_string(main->Config(), "AdvOut", "FFACustom"); + const char *aEncoder = config_get_string(main->Config(), "AdvOut", "FFAEncoder"); + int aEncoderId = config_get_int(main->Config(), "AdvOut", "FFAEncoderId"); + const char *aEncCustom = config_get_string(main->Config(), "AdvOut", "FFACustom"); OBSDataArrayAutoRelease audio_names = obs_data_array_create(); @@ -2105,8 +1858,7 @@ inline void AdvancedOutput::SetupFFmpeg() cfg_name += to_string((int)i + 1); cfg_name += "Name"; - const char *audioName = config_get_string( - main->Config(), "AdvOut", cfg_name.c_str()); + const char *audioName = config_get_string(main->Config(), "AdvOut", cfg_name.c_str()); OBSDataAutoRelease item = obs_data_create(); obs_data_set_string(item, "name", audioName); @@ -2146,26 +1898,19 @@ inline void AdvancedOutput::SetupFFmpeg() obs_output_update(fileOutput, settings); } -static inline void SetEncoderName(obs_encoder_t *encoder, const char *name, - const char *defaultName) +static inline void SetEncoderName(obs_encoder_t *encoder, const char *name, const char *defaultName) { obs_encoder_set_name(encoder, (name && *name) ? name : defaultName); } inline void AdvancedOutput::UpdateAudioSettings() { - bool applyServiceSettings = config_get_bool(main->Config(), "AdvOut", - "ApplyServiceSettings"); - bool enforceBitrate = !config_get_bool(main->Config(), "Stream1", - "IgnoreRecommended"); - int streamTrackIndex = - config_get_int(main->Config(), "AdvOut", "TrackIndex"); - int vodTrackIndex = - config_get_int(main->Config(), "AdvOut", "VodTrackIndex"); - const char *audioEncoder = - config_get_string(main->Config(), "AdvOut", "AudioEncoder"); - const char *recAudioEncoder = - config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); + bool applyServiceSettings = config_get_bool(main->Config(), "AdvOut", "ApplyServiceSettings"); + bool enforceBitrate = !config_get_bool(main->Config(), "Stream1", "IgnoreRecommended"); + int streamTrackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex"); + int vodTrackIndex = config_get_int(main->Config(), "AdvOut", "VodTrackIndex"); + const char *audioEncoder = config_get_string(main->Config(), "AdvOut", "AudioEncoder"); + const char *recAudioEncoder = config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); bool is_multitrack_output = allowsMultiTrack(); @@ -2175,8 +1920,7 @@ inline void AdvancedOutput::UpdateAudioSettings() string cfg_name = "Track"; cfg_name += to_string((int)i + 1); cfg_name += "Name"; - const char *name = config_get_string(main->Config(), "AdvOut", - cfg_name.c_str()); + const char *name = config_get_string(main->Config(), "AdvOut", cfg_name.c_str()); string def_name = "Track"; def_name += to_string((int)i + 1); @@ -2187,36 +1931,27 @@ inline void AdvancedOutput::UpdateAudioSettings() for (size_t i = 0; i < MAX_AUDIO_MIXES; i++) { int track = (int)(i + 1); settings[i] = obs_data_create(); - obs_data_set_int(settings[i], "bitrate", - GetAudioBitrate(i, recAudioEncoder)); + obs_data_set_int(settings[i], "bitrate", GetAudioBitrate(i, recAudioEncoder)); obs_encoder_update(recordTrack[i], settings[i]); - obs_data_set_int(settings[i], "bitrate", - GetAudioBitrate(i, audioEncoder)); + obs_data_set_int(settings[i], "bitrate", GetAudioBitrate(i, audioEncoder)); if (!is_multitrack_output) { - if (track == streamTrackIndex || - track == vodTrackIndex) { + if (track == streamTrackIndex || track == vodTrackIndex) { if (applyServiceSettings) { - int bitrate = (int)obs_data_get_int( - settings[i], "bitrate"); - obs_service_apply_encoder_settings( - main->GetService(), nullptr, - settings[i]); + int bitrate = (int)obs_data_get_int(settings[i], "bitrate"); + obs_service_apply_encoder_settings(main->GetService(), nullptr, settings[i]); if (!enforceBitrate) - obs_data_set_int(settings[i], - "bitrate", - bitrate); + obs_data_set_int(settings[i], "bitrate", bitrate); } } if (track == streamTrackIndex) obs_encoder_update(streamAudioEnc, settings[i]); if (track == vodTrackIndex) - obs_encoder_update(streamArchiveEnc, - settings[i]); + obs_encoder_update(streamArchiveEnc, settings[i]); } else { obs_encoder_update(streamTrack[i], settings[i]); } @@ -2246,30 +1981,22 @@ void AdvancedOutput::SetupOutputs() int AdvancedOutput::GetAudioBitrate(size_t i, const char *id) const { static const char *names[] = { - "Track1Bitrate", "Track2Bitrate", "Track3Bitrate", - "Track4Bitrate", "Track5Bitrate", "Track6Bitrate", + "Track1Bitrate", "Track2Bitrate", "Track3Bitrate", "Track4Bitrate", "Track5Bitrate", "Track6Bitrate", }; int bitrate = (int)config_get_uint(main->Config(), "AdvOut", names[i]); return FindClosestAvailableAudioBitrate(id, bitrate); } -inline std::optional -AdvancedOutput::VodTrackMixerIdx(obs_service_t *service) +inline std::optional AdvancedOutput::VodTrackMixerIdx(obs_service_t *service) { - int streamTrackIndex = - config_get_int(main->Config(), "AdvOut", "TrackIndex"); - bool vodTrackEnabled = - config_get_bool(main->Config(), "AdvOut", "VodTrackEnabled"); - int vodTrackIndex = - config_get_int(main->Config(), "AdvOut", "VodTrackIndex"); - bool enableForCustomServer = - config_get_bool(App()->GetUserConfig(), "General", - "EnableCustomServerVodTrack"); + int streamTrackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex"); + bool vodTrackEnabled = config_get_bool(main->Config(), "AdvOut", "VodTrackEnabled"); + int vodTrackIndex = config_get_int(main->Config(), "AdvOut", "VodTrackIndex"); + bool enableForCustomServer = config_get_bool(App()->GetUserConfig(), "General", "EnableCustomServerVodTrack"); const char *id = obs_service_get_id(service); if (strcmp(id, "rtmp_custom") == 0) { - vodTrackEnabled = enableForCustomServer ? vodTrackEnabled - : false; + vodTrackEnabled = enableForCustomServer ? vodTrackEnabled : false; } else { OBSDataAutoRelease settings = obs_service_get_settings(service); const char *service = obs_data_get_string(settings, "service"); @@ -2290,18 +2017,15 @@ inline void AdvancedOutput::SetupVodTrack(obs_service_t *service) clear_archive_encoder(streamOutput, ADV_ARCHIVE_NAME); } -std::shared_future -AdvancedOutput::SetupStreaming(obs_service_t *service, - SetupStreamingContinuation_t continuation) +std::shared_future AdvancedOutput::SetupStreaming(obs_service_t *service, + SetupStreamingContinuation_t continuation) { - int multiTrackAudioMixes = config_get_int(main->Config(), "AdvOut", - "StreamMultiTrackAudioMixes"); + int multiTrackAudioMixes = config_get_int(main->Config(), "AdvOut", "StreamMultiTrackAudioMixes"); int idx = 0; bool is_multitrack_output = allowsMultiTrack(); - if (!useStreamEncoder || - (!ffmpegOutput && !obs_output_active(fileOutput))) { + if (!useStreamEncoder || (!ffmpegOutput && !obs_output_active(fileOutput))) { UpdateStreamSettings(); } @@ -2322,13 +2046,10 @@ AdvancedOutput::SetupStreaming(obs_service_t *service, return StartMultitrackVideoStreamingGuard::MakeReadyFuture(); } - const char *audio_encoder_id = - config_get_string(main->Config(), "AdvOut", "AudioEncoder"); - int streamTrackIndex = - config_get_int(main->Config(), "AdvOut", "TrackIndex") - 1; + const char *audio_encoder_id = config_get_string(main->Config(), "AdvOut", "AudioEncoder"); + int streamTrackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex") - 1; - auto handle_multitrack_video_result = [&](std::optional - multitrackVideoResult) { + auto handle_multitrack_video_result = [&](std::optional multitrackVideoResult) { if (multitrackVideoResult.has_value()) return multitrackVideoResult.value(); @@ -2339,8 +2060,7 @@ AdvancedOutput::SetupStreaming(obs_service_t *service, startStreaming.Disconnect(); stopStreaming.Disconnect(); - streamOutput = obs_output_create(type, "adv_stream", - nullptr, nullptr); + streamOutput = obs_output_create(type, "adv_stream", nullptr, nullptr); if (!streamOutput) { blog(LOG_WARNING, "Creation of stream output type '%s' " @@ -2349,19 +2069,15 @@ AdvancedOutput::SetupStreaming(obs_service_t *service, return false; } - streamDelayStarting.Connect( - obs_output_get_signal_handler(streamOutput), - "starting", OBSStreamStarting, this); - streamStopping.Connect( - obs_output_get_signal_handler(streamOutput), - "stopping", OBSStreamStopping, this); + streamDelayStarting.Connect(obs_output_get_signal_handler(streamOutput), "starting", + OBSStreamStarting, this); + streamStopping.Connect(obs_output_get_signal_handler(streamOutput), "stopping", + OBSStreamStopping, this); - startStreaming.Connect( - obs_output_get_signal_handler(streamOutput), - "start", OBSStartStreaming, this); - stopStreaming.Connect( - obs_output_get_signal_handler(streamOutput), - "stop", OBSStopStreaming, this); + startStreaming.Connect(obs_output_get_signal_handler(streamOutput), "start", OBSStartStreaming, + this); + stopStreaming.Connect(obs_output_get_signal_handler(streamOutput), "stop", OBSStopStreaming, + this); outputType = type; } @@ -2370,14 +2086,11 @@ AdvancedOutput::SetupStreaming(obs_service_t *service, obs_output_set_audio_encoder(streamOutput, streamAudioEnc, 0); if (!is_multitrack_output) { - obs_output_set_audio_encoder(streamOutput, - streamAudioEnc, 0); + obs_output_set_audio_encoder(streamOutput, streamAudioEnc, 0); } else { for (int i = 0; i < MAX_AUDIO_MIXES; i++) { if ((multiTrackAudioMixes & (1 << i)) != 0) { - obs_output_set_audio_encoder( - streamOutput, streamTrack[i], - idx); + obs_output_set_audio_encoder(streamOutput, streamTrack[i], idx); idx++; } } @@ -2386,13 +2099,10 @@ AdvancedOutput::SetupStreaming(obs_service_t *service, return true; }; - return SetupMultitrackVideo( - service, audio_encoder_id, - static_cast(streamTrackIndex), - VodTrackMixerIdx(service), - [&, continuation](std::optional res) { - continuation(handle_multitrack_video_result(res)); - }); + return SetupMultitrackVideo(service, audio_encoder_id, static_cast(streamTrackIndex), + VodTrackMixerIdx(service), [&, continuation](std::optional res) { + continuation(handle_multitrack_video_result(res)); + }); } bool AdvancedOutput::StartStreaming(obs_service_t *service) @@ -2402,30 +2112,22 @@ bool AdvancedOutput::StartStreaming(obs_service_t *service) bool reconnect = config_get_bool(main->Config(), "Output", "Reconnect"); int retryDelay = config_get_int(main->Config(), "Output", "RetryDelay"); int maxRetries = config_get_int(main->Config(), "Output", "MaxRetries"); - bool useDelay = - config_get_bool(main->Config(), "Output", "DelayEnable"); + bool useDelay = config_get_bool(main->Config(), "Output", "DelayEnable"); int delaySec = config_get_int(main->Config(), "Output", "DelaySec"); - bool preserveDelay = - config_get_bool(main->Config(), "Output", "DelayPreserve"); - const char *bindIP = - config_get_string(main->Config(), "Output", "BindIP"); - const char *ipFamily = - config_get_string(main->Config(), "Output", "IPFamily"); + bool preserveDelay = config_get_bool(main->Config(), "Output", "DelayPreserve"); + const char *bindIP = config_get_string(main->Config(), "Output", "BindIP"); + const char *ipFamily = config_get_string(main->Config(), "Output", "IPFamily"); #ifdef _WIN32 - bool enableNewSocketLoop = config_get_bool(main->Config(), "Output", - "NewSocketLoopEnable"); - bool enableLowLatencyMode = - config_get_bool(main->Config(), "Output", "LowLatencyEnable"); + bool enableNewSocketLoop = config_get_bool(main->Config(), "Output", "NewSocketLoopEnable"); + bool enableLowLatencyMode = config_get_bool(main->Config(), "Output", "LowLatencyEnable"); #else bool enableNewSocketLoop = false; #endif - bool enableDynBitrate = - config_get_bool(main->Config(), "Output", "DynamicBitrate"); + bool enableDynBitrate = config_get_bool(main->Config(), "Output", "DynamicBitrate"); if (multitrackVideo && multitrackVideoActive && - !multitrackVideo->HandleIncompatibleSettings( - main, main->Config(), service, useDelay, - enableNewSocketLoop, enableDynBitrate)) { + !multitrackVideo->HandleIncompatibleSettings(main, main->Config(), service, useDelay, enableNewSocketLoop, + enableDynBitrate)) { multitrackVideoActive = false; return false; } @@ -2434,8 +2136,7 @@ bool AdvancedOutput::StartStreaming(obs_service_t *service) obs_service_t *service_obj = main->GetService(); const char *protocol = obs_service_get_protocol(service_obj); if (protocol) { - if (astrcmpi_n(protocol, RTMP_PROTOCOL, - strlen(RTMP_PROTOCOL)) == 0) + if (astrcmpi_n(protocol, RTMP_PROTOCOL, strlen(RTMP_PROTOCOL)) == 0) is_rtmp = true; } @@ -2443,23 +2144,19 @@ bool AdvancedOutput::StartStreaming(obs_service_t *service) obs_data_set_string(settings, "bind_ip", bindIP); obs_data_set_string(settings, "ip_family", ipFamily); #ifdef _WIN32 - obs_data_set_bool(settings, "new_socket_loop_enabled", - enableNewSocketLoop); - obs_data_set_bool(settings, "low_latency_mode_enabled", - enableLowLatencyMode); + obs_data_set_bool(settings, "new_socket_loop_enabled", enableNewSocketLoop); + obs_data_set_bool(settings, "low_latency_mode_enabled", enableLowLatencyMode); #endif obs_data_set_bool(settings, "dyn_bitrate", enableDynBitrate); - auto streamOutput = - StreamingOutput(); // shadowing is sort of bad, but also convenient + auto streamOutput = StreamingOutput(); // shadowing is sort of bad, but also convenient obs_output_update(streamOutput, settings); if (!reconnect) maxRetries = 0; - obs_output_set_delay(streamOutput, useDelay ? delaySec : 0, - preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0); + obs_output_set_delay(streamOutput, useDelay ? delaySec : 0, preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0); obs_output_set_reconnect_settings(streamOutput, maxRetries, retryDelay); if (is_rtmp) { @@ -2482,8 +2179,8 @@ bool AdvancedOutput::StartStreaming(obs_service_t *service) lastError = string(); const char *type = obs_output_get_id(streamOutput); - blog(LOG_WARNING, "Stream output type '%s' failed to start!%s%s", type, - hasLastError ? " Last Error: " : "", hasLastError ? error : ""); + blog(LOG_WARNING, "Stream output type '%s' failed to start!%s%s", type, hasLastError ? " Last Error: " : "", + hasLastError ? error : ""); return false; } @@ -2513,59 +2210,37 @@ bool AdvancedOutput::StartRecording() SetupOutputs(); if (!ffmpegOutput || ffmpegRecording) { - path = config_get_string(main->Config(), "AdvOut", - ffmpegRecording ? "FFFilePath" - : "RecFilePath"); - recFormat = config_get_string(main->Config(), "AdvOut", - ffmpegRecording ? "FFExtension" - : "RecFormat2"); - filenameFormat = config_get_string(main->Config(), "Output", - "FilenameFormatting"); - overwriteIfExists = config_get_bool(main->Config(), "Output", - "OverwriteIfExists"); + path = config_get_string(main->Config(), "AdvOut", ffmpegRecording ? "FFFilePath" : "RecFilePath"); + recFormat = config_get_string(main->Config(), "AdvOut", ffmpegRecording ? "FFExtension" : "RecFormat2"); + filenameFormat = config_get_string(main->Config(), "Output", "FilenameFormatting"); + overwriteIfExists = config_get_bool(main->Config(), "Output", "OverwriteIfExists"); noSpace = config_get_bool(main->Config(), "AdvOut", - ffmpegRecording - ? "FFFileNameWithoutSpace" - : "RecFileNameWithoutSpace"); - splitFile = config_get_bool(main->Config(), "AdvOut", - "RecSplitFile"); + ffmpegRecording ? "FFFileNameWithoutSpace" : "RecFileNameWithoutSpace"); + splitFile = config_get_bool(main->Config(), "AdvOut", "RecSplitFile"); - string strPath = GetRecordingFilename(path, recFormat, noSpace, - overwriteIfExists, - filenameFormat, + string strPath = GetRecordingFilename(path, recFormat, noSpace, overwriteIfExists, filenameFormat, ffmpegRecording); OBSDataAutoRelease settings = obs_data_create(); - obs_data_set_string(settings, ffmpegRecording ? "url" : "path", - strPath.c_str()); + obs_data_set_string(settings, ffmpegRecording ? "url" : "path", strPath.c_str()); if (splitFile) { - splitFileType = config_get_string( - main->Config(), "AdvOut", "RecSplitFileType"); - splitFileTime = - (astrcmpi(splitFileType, "Time") == 0) - ? config_get_int(main->Config(), - "AdvOut", - "RecSplitFileTime") - : 0; - splitFileSize = - (astrcmpi(splitFileType, "Size") == 0) - ? config_get_int(main->Config(), - "AdvOut", - "RecSplitFileSize") - : 0; + splitFileType = config_get_string(main->Config(), "AdvOut", "RecSplitFileType"); + splitFileTime = (astrcmpi(splitFileType, "Time") == 0) + ? config_get_int(main->Config(), "AdvOut", "RecSplitFileTime") + : 0; + splitFileSize = (astrcmpi(splitFileType, "Size") == 0) + ? config_get_int(main->Config(), "AdvOut", "RecSplitFileSize") + : 0; string ext = GetFormatExt(recFormat); obs_data_set_string(settings, "directory", path); obs_data_set_string(settings, "format", filenameFormat); obs_data_set_string(settings, "extension", ext.c_str()); obs_data_set_bool(settings, "allow_spaces", !noSpace); - obs_data_set_bool(settings, "allow_overwrite", - overwriteIfExists); + obs_data_set_bool(settings, "allow_overwrite", overwriteIfExists); obs_data_set_bool(settings, "split_file", true); - obs_data_set_int(settings, "max_time_sec", - splitFileTime * 60); - obs_data_set_int(settings, "max_size_mb", - splitFileSize); + obs_data_set_int(settings, "max_time_sec", splitFileTime * 60); + obs_data_set_int(settings, "max_size_mb", splitFileSize); } obs_output_update(fileOutput, settings); @@ -2578,9 +2253,7 @@ bool AdvancedOutput::StartRecording() error_reason = QT_UTF8(error); else error_reason = QTStr("Output.StartFailedGeneric"); - QMessageBox::critical(main, - QTStr("Output.StartRecordingFailed"), - error_reason); + QMessageBox::critical(main, QTStr("Output.StartRecordingFailed"), error_reason); return false; } @@ -2612,24 +2285,14 @@ bool AdvancedOutput::StartReplayBuffer() SetupOutputs(); if (!ffmpegOutput || ffmpegRecording) { - path = config_get_string(main->Config(), "AdvOut", - ffmpegRecording ? "FFFilePath" - : "RecFilePath"); - recFormat = config_get_string(main->Config(), "AdvOut", - ffmpegRecording ? "FFExtension" - : "RecFormat2"); - filenameFormat = config_get_string(main->Config(), "Output", - "FilenameFormatting"); - overwriteIfExists = config_get_bool(main->Config(), "Output", - "OverwriteIfExists"); + path = config_get_string(main->Config(), "AdvOut", ffmpegRecording ? "FFFilePath" : "RecFilePath"); + recFormat = config_get_string(main->Config(), "AdvOut", ffmpegRecording ? "FFExtension" : "RecFormat2"); + filenameFormat = config_get_string(main->Config(), "Output", "FilenameFormatting"); + overwriteIfExists = config_get_bool(main->Config(), "Output", "OverwriteIfExists"); noSpace = config_get_bool(main->Config(), "AdvOut", - ffmpegRecording - ? "FFFileNameWithoutSpace" - : "RecFileNameWithoutSpace"); - rbPrefix = config_get_string(main->Config(), "SimpleOutput", - "RecRBPrefix"); - rbSuffix = config_get_string(main->Config(), "SimpleOutput", - "RecRBSuffix"); + ffmpegRecording ? "FFFileNameWithoutSpace" : "RecFileNameWithoutSpace"); + rbPrefix = config_get_string(main->Config(), "SimpleOutput", "RecRBPrefix"); + rbSuffix = config_get_string(main->Config(), "SimpleOutput", "RecRBSuffix"); rbTime = config_get_int(main->Config(), "AdvOut", "RecRBTime"); rbSize = config_get_int(main->Config(), "AdvOut", "RecRBSize"); @@ -2643,8 +2306,7 @@ bool AdvancedOutput::StartReplayBuffer() obs_data_set_string(settings, "extension", ext.c_str()); obs_data_set_bool(settings, "allow_spaces", !noSpace); obs_data_set_int(settings, "max_time_sec", rbTime); - obs_data_set_int(settings, "max_size_mb", - usesBitrate ? 0 : rbSize); + obs_data_set_int(settings, "max_size_mb", usesBitrate ? 0 : rbSize); obs_output_update(replayBuffer, settings); } @@ -2656,8 +2318,7 @@ bool AdvancedOutput::StartReplayBuffer() error_reason = QT_UTF8(error); else error_reason = QTStr("Output.StartFailedGeneric"); - QMessageBox::critical(main, QTStr("Output.StartReplayFailed"), - error_reason); + QMessageBox::critical(main, QTStr("Output.StartReplayFailed"), error_reason); return false; } @@ -2715,28 +2376,25 @@ void BasicOutputHandler::SetupAutoRemux(const char *&container) container = "mkv"; } -std::string BasicOutputHandler::GetRecordingFilename( - const char *path, const char *container, bool noSpace, bool overwrite, - const char *format, bool ffmpeg) +std::string BasicOutputHandler::GetRecordingFilename(const char *path, const char *container, bool noSpace, + bool overwrite, const char *format, bool ffmpeg) { if (!ffmpeg) SetupAutoRemux(container); - string dst = - GetOutputFilename(path, container, noSpace, overwrite, format); + string dst = GetOutputFilename(path, container, noSpace, overwrite, format); lastRecordingPath = dst; return dst; } extern std::string DeserializeConfigText(const char *text); -std::shared_future BasicOutputHandler::SetupMultitrackVideo( - obs_service_t *service, std::string audio_encoder_id, - size_t main_audio_mixer, std::optional vod_track_mixer, - std::function)> continuation) +std::shared_future BasicOutputHandler::SetupMultitrackVideo(obs_service_t *service, std::string audio_encoder_id, + size_t main_audio_mixer, + std::optional vod_track_mixer, + std::function)> continuation) { - auto start_streaming_guard = - std::make_shared(); + auto start_streaming_guard = std::make_shared(); if (!multitrackVideo) { continuation(std::nullopt); return start_streaming_guard->GetFuture(); @@ -2749,15 +2407,12 @@ std::shared_future BasicOutputHandler::SetupMultitrackVideo( startStreaming.Disconnect(); stopStreaming.Disconnect(); - bool is_custom = - strncmp("rtmp_custom", obs_service_get_type(service), 11) == 0; + bool is_custom = strncmp("rtmp_custom", obs_service_get_type(service), 11) == 0; std::optional custom_config = std::nullopt; - if (config_get_bool(main->Config(), "Stream1", - "MultitrackVideoConfigOverrideEnabled")) + if (config_get_bool(main->Config(), "Stream1", "MultitrackVideoConfigOverrideEnabled")) custom_config = DeserializeConfigText( - config_get_string(main->Config(), "Stream1", - "MultitrackVideoConfigOverride")); + config_get_string(main->Config(), "Stream1", "MultitrackVideoConfigOverride")); OBSDataAutoRelease settings = obs_service_get_settings(service); QString key = obs_data_get_string(settings, "key"); @@ -2775,47 +2430,32 @@ std::shared_future BasicOutputHandler::SetupMultitrackVideo( custom_rtmp_url = server; } - auto service_custom_server = - obs_data_get_bool(settings, "using_custom_server"); + auto service_custom_server = obs_data_get_bool(settings, "using_custom_server"); if (custom_rtmp_url.has_value()) { - blog(LOG_INFO, "Using %sserver '%s'", - service_custom_server ? "custom " : "", - custom_rtmp_url->c_str()); + blog(LOG_INFO, "Using %sserver '%s'", service_custom_server ? "custom " : "", custom_rtmp_url->c_str()); } auto maximum_aggregate_bitrate = - config_get_bool(main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrateAuto") + config_get_bool(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrateAuto") ? std::nullopt - : std::make_optional(config_get_int( - main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrate")); + : std::make_optional( + config_get_int(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrate")); - auto maximum_video_tracks = - config_get_bool(main->Config(), "Stream1", - "MultitrackVideoMaximumVideoTracksAuto") - ? std::nullopt - : std::make_optional(config_get_int( - main->Config(), "Stream1", - "MultitrackVideoMaximumVideoTracks")); + auto maximum_video_tracks = config_get_bool(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracksAuto") + ? std::nullopt + : std::make_optional(config_get_int( + main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracks")); auto stream_dump_config = GenerateMultitrackVideoStreamDumpConfig(); - auto continue_on_main_thread = [&, start_streaming_guard, - service = OBSService{service}, - continuation = std::move(continuation)]( - std::optional - error) { + auto continue_on_main_thread = [&, start_streaming_guard, service = OBSService{service}, + continuation = + std::move(continuation)](std::optional error) { if (error) { - OBSDataAutoRelease service_settings = - obs_service_get_settings(service); - auto multitrack_video_name = QTStr( - "Basic.Settings.Stream.MultitrackVideoLabel"); - if (obs_data_has_user_value(service_settings, - "multitrack_video_name")) { - multitrack_video_name = obs_data_get_string( - service_settings, - "multitrack_video_name"); + OBSDataAutoRelease service_settings = obs_service_get_settings(service); + auto multitrack_video_name = QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); + if (obs_data_has_user_value(service_settings, "multitrack_video_name")) { + multitrack_video_name = obs_data_get_string(service_settings, "multitrack_video_name"); } multitrackVideoActive = false; @@ -2828,80 +2468,59 @@ std::shared_future BasicOutputHandler::SetupMultitrackVideo( auto signal_handler = multitrackVideo->StreamingSignalHandler(); - streamDelayStarting.Connect(signal_handler, "starting", - OBSStreamStarting, this); - streamStopping.Connect(signal_handler, "stopping", - OBSStreamStopping, this); + streamDelayStarting.Connect(signal_handler, "starting", OBSStreamStarting, this); + streamStopping.Connect(signal_handler, "stopping", OBSStreamStopping, this); - startStreaming.Connect(signal_handler, "start", - OBSStartStreaming, this); - stopStreaming.Connect(signal_handler, "stop", OBSStopStreaming, - this); + startStreaming.Connect(signal_handler, "start", OBSStartStreaming, this); + stopStreaming.Connect(signal_handler, "stop", OBSStopStreaming, this); return continuation(true); }; - QThreadPool::globalInstance()->start( - [=, multitrackVideo = multitrackVideo.get(), - service_name = std::string{service_name}, - service = OBSService{service}, - stream_dump_config = OBSData{stream_dump_config}, - start_streaming_guard = start_streaming_guard]() mutable { - std::optional error; - try { - multitrackVideo->PrepareStreaming( - main, service_name.c_str(), service, - custom_rtmp_url, key, - audio_encoder_id.c_str(), - maximum_aggregate_bitrate, - maximum_video_tracks, custom_config, - stream_dump_config, main_audio_mixer, - vod_track_mixer); - } catch (const MultitrackVideoError &error_) { - error.emplace(error_); - } + QThreadPool::globalInstance()->start([=, multitrackVideo = multitrackVideo.get(), + service_name = std::string{service_name}, service = OBSService{service}, + stream_dump_config = OBSData{stream_dump_config}, + start_streaming_guard = start_streaming_guard]() mutable { + std::optional error; + try { + multitrackVideo->PrepareStreaming(main, service_name.c_str(), service, custom_rtmp_url, key, + audio_encoder_id.c_str(), maximum_aggregate_bitrate, + maximum_video_tracks, custom_config, stream_dump_config, + main_audio_mixer, vod_track_mixer); + } catch (const MultitrackVideoError &error_) { + error.emplace(error_); + } - QMetaObject::invokeMethod(main, [=] { - continue_on_main_thread(error); - }); - }); + QMetaObject::invokeMethod(main, [=] { continue_on_main_thread(error); }); + }); return start_streaming_guard->GetFuture(); } OBSDataAutoRelease BasicOutputHandler::GenerateMultitrackVideoStreamDumpConfig() { - auto stream_dump_enabled = config_get_bool( - main->Config(), "Stream1", "MultitrackVideoStreamDumpEnabled"); + auto stream_dump_enabled = config_get_bool(main->Config(), "Stream1", "MultitrackVideoStreamDumpEnabled"); if (!stream_dump_enabled) return nullptr; - const char *path = - config_get_string(main->Config(), "SimpleOutput", "FilePath"); - bool noSpace = config_get_bool(main->Config(), "SimpleOutput", - "FileNameWithoutSpace"); - const char *filenameFormat = config_get_string(main->Config(), "Output", - "FilenameFormatting"); - bool overwriteIfExists = - config_get_bool(main->Config(), "Output", "OverwriteIfExists"); - bool useMP4 = config_get_bool(main->Config(), "Stream1", - "MultitrackVideoStreamDumpAsMP4"); + const char *path = config_get_string(main->Config(), "SimpleOutput", "FilePath"); + bool noSpace = config_get_bool(main->Config(), "SimpleOutput", "FileNameWithoutSpace"); + const char *filenameFormat = config_get_string(main->Config(), "Output", "FilenameFormatting"); + bool overwriteIfExists = config_get_bool(main->Config(), "Output", "OverwriteIfExists"); + bool useMP4 = config_get_bool(main->Config(), "Stream1", "MultitrackVideoStreamDumpAsMP4"); string f; OBSDataAutoRelease settings = obs_data_create(); f = GetFormatString(filenameFormat, nullptr, nullptr); - string strPath = GetRecordingFilename(path, useMP4 ? "mp4" : "flv", - noSpace, overwriteIfExists, - f.c_str(), + string strPath = GetRecordingFilename(path, useMP4 ? "mp4" : "flv", noSpace, overwriteIfExists, f.c_str(), // never remux stream dump false); obs_data_set_string(settings, "path", strPath.c_str()); if (useMP4) { obs_data_set_bool(settings, "use_mp4", true); - obs_data_set_string(settings, "muxer_settings", - "write_encoder_info=1"); + obs_data_set_string(settings, "muxer_settings", "write_encoder_info=1"); } return settings; diff --git a/UI/window-basic-main-outputs.hpp b/UI/window-basic-main-outputs.hpp index 870f720a2..f7178f19d 100644 --- a/UI/window-basic-main-outputs.hpp +++ b/UI/window-basic-main-outputs.hpp @@ -29,8 +29,7 @@ struct BasicOutputHandler { { return (multitrackVideo && multitrackVideoActive) ? multitrackVideo->StreamingOutput() - : OBSOutputAutoRelease{ - obs_output_get_ref(streamOutput)}; + : OBSOutputAutoRelease{obs_output_get_ref(streamOutput)}; } obs_view_t *virtualCamView = nullptr; @@ -63,9 +62,8 @@ struct BasicOutputHandler { virtual ~BasicOutputHandler(){}; - virtual std::shared_future - SetupStreaming(obs_service_t *service, - SetupStreamingContinuation_t continuation) = 0; + virtual std::shared_future SetupStreaming(obs_service_t *service, + SetupStreamingContinuation_t continuation) = 0; virtual bool StartStreaming(obs_service_t *service) = 0; virtual bool StartRecording() = 0; virtual bool StartReplayBuffer() { return false; } @@ -88,22 +86,18 @@ struct BasicOutputHandler { inline bool Active() const { - return streamingActive || recordingActive || delayActive || - replayBufferActive || virtualCamActive || + return streamingActive || recordingActive || delayActive || replayBufferActive || virtualCamActive || multitrackVideoActive; } protected: void SetupAutoRemux(const char *&container); - std::string GetRecordingFilename(const char *path, - const char *container, bool noSpace, - bool overwrite, const char *format, - bool ffmpeg); + std::string GetRecordingFilename(const char *path, const char *container, bool noSpace, bool overwrite, + const char *format, bool ffmpeg); - std::shared_future SetupMultitrackVideo( - obs_service_t *service, std::string audio_encoder_id, - size_t main_audio_mixer, std::optional vod_track_mixer, - std::function)> continuation); + std::shared_future SetupMultitrackVideo(obs_service_t *service, std::string audio_encoder_id, + size_t main_audio_mixer, std::optional vod_track_mixer, + std::function)> continuation); OBSDataAutoRelease GenerateMultitrackVideoStreamDumpConfig(); }; diff --git a/UI/window-basic-main-profiles.cpp b/UI/window-basic-main-profiles.cpp index 3a54e5422..559170e5e 100644 --- a/UI/window-basic-main-profiles.cpp +++ b/UI/window-basic-main-profiles.cpp @@ -49,13 +49,11 @@ void OBSBasic::SetupNewProfile(const std::string &profileName, bool useWizard) { const OBSProfile &newProfile = CreateProfile(profileName); - config_set_bool(App()->GetUserConfig(), "Basic", "ConfigOnNewProfile", - useWizard); + config_set_bool(App()->GetUserConfig(), "Basic", "ConfigOnNewProfile", useWizard); ActivateProfile(newProfile, true); - blog(LOG_INFO, "Created profile '%s' (clean, %s)", - newProfile.name.c_str(), newProfile.directoryName.c_str()); + blog(LOG_INFO, "Created profile '%s' (clean, %s)", newProfile.name.c_str(), newProfile.directoryName.c_str()); blog(LOG_INFO, "------------------------------------------------"); if (useWizard) { @@ -71,24 +69,20 @@ void OBSBasic::SetupDuplicateProfile(const std::string &profileName) const OBSProfile &newProfile = CreateProfile(profileName); const OBSProfile ¤tProfile = GetCurrentProfile(); - const auto copyOptions = - std::filesystem::copy_options::recursive | - std::filesystem::copy_options::overwrite_existing; + const auto copyOptions = std::filesystem::copy_options::recursive | + std::filesystem::copy_options::overwrite_existing; try { - std::filesystem::copy(currentProfile.path, newProfile.path, - copyOptions); + std::filesystem::copy(currentProfile.path, newProfile.path, copyOptions); } catch (const std::filesystem::filesystem_error &error) { blog(LOG_DEBUG, "%s", error.what()); - throw std::logic_error( - "Failed to copy files for cloned profile: " + - newProfile.name); + throw std::logic_error("Failed to copy files for cloned profile: " + newProfile.name); } ActivateProfile(newProfile); - blog(LOG_INFO, "Created profile '%s' (duplicate, %s)", - newProfile.name.c_str(), newProfile.directoryName.c_str()); + blog(LOG_INFO, "Created profile '%s' (duplicate, %s)", newProfile.name.c_str(), + newProfile.directoryName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } @@ -97,17 +91,14 @@ void OBSBasic::SetupRenameProfile(const std::string &profileName) const OBSProfile &newProfile = CreateProfile(profileName); const OBSProfile currentProfile = GetCurrentProfile(); - const auto copyOptions = - std::filesystem::copy_options::recursive | - std::filesystem::copy_options::overwrite_existing; + const auto copyOptions = std::filesystem::copy_options::recursive | + std::filesystem::copy_options::overwrite_existing; try { - std::filesystem::copy(currentProfile.path, newProfile.path, - copyOptions); + std::filesystem::copy(currentProfile.path, newProfile.path, copyOptions); } catch (const std::filesystem::filesystem_error &error) { blog(LOG_DEBUG, "%s", error.what()); - throw std::logic_error("Failed to copy files for profile: " + - currentProfile.name); + throw std::logic_error("Failed to copy files for profile: " + currentProfile.name); } profiles.erase(currentProfile.name); @@ -115,8 +106,7 @@ void OBSBasic::SetupRenameProfile(const std::string &profileName) ActivateProfile(newProfile); RemoveProfile(currentProfile); - blog(LOG_INFO, "Renamed profile '%s' to '%s' (%s)", - currentProfile.name.c_str(), newProfile.name.c_str(), + blog(LOG_INFO, "Renamed profile '%s' to '%s' (%s)", currentProfile.name.c_str(), newProfile.name.c_str(), newProfile.directoryName.c_str()); blog(LOG_INFO, "------------------------------------------------"); @@ -128,50 +118,37 @@ void OBSBasic::SetupRenameProfile(const std::string &profileName) const OBSProfile &OBSBasic::CreateProfile(const std::string &profileName) { if (const auto &foundProfile = GetProfileByName(profileName)) { - throw std::invalid_argument("Profile already exists: " + - profileName); + throw std::invalid_argument("Profile already exists: " + profileName); } std::string directoryName; if (!GetFileSafeName(profileName.c_str(), directoryName)) { - throw std::invalid_argument( - "Failed to create safe directory for new profile: " + - profileName); + throw std::invalid_argument("Failed to create safe directory for new profile: " + profileName); } std::string profileDirectory; - profileDirectory.reserve(App()->userProfilesLocation.u8string().size() + - OBSProfilePath.size() + directoryName.size()); - profileDirectory.append(App()->userProfilesLocation.u8string()) - .append(OBSProfilePath) - .append(directoryName); + profileDirectory.reserve(App()->userProfilesLocation.u8string().size() + OBSProfilePath.size() + + directoryName.size()); + profileDirectory.append(App()->userProfilesLocation.u8string()).append(OBSProfilePath).append(directoryName); if (!GetClosestUnusedFileName(profileDirectory, nullptr)) { - throw std::invalid_argument( - "Failed to get closest directory name for new profile: " + - profileName); + throw std::invalid_argument("Failed to get closest directory name for new profile: " + profileName); } - const std::filesystem::path profileDirectoryPath = - std::filesystem::u8path(profileDirectory); + const std::filesystem::path profileDirectoryPath = std::filesystem::u8path(profileDirectory); try { std::filesystem::create_directory(profileDirectoryPath); } catch (const std::filesystem::filesystem_error error) { - throw std::logic_error( - "Failed to create directory for new profile: " + - profileDirectory); + throw std::logic_error("Failed to create directory for new profile: " + profileDirectory); } const std::filesystem::path profileFile = - profileDirectoryPath / - std::filesystem::u8path(OBSProfileSettingsFile); + profileDirectoryPath / std::filesystem::u8path(OBSProfileSettingsFile); - auto [iterator, success] = profiles.try_emplace( - profileName, - OBSProfile{profileName, - profileDirectoryPath.filename().u8string(), - profileDirectoryPath, profileFile}); + auto [iterator, success] = + profiles.try_emplace(profileName, OBSProfile{profileName, profileDirectoryPath.filename().u8string(), + profileDirectoryPath, profileFile}); OnEvent(OBS_FRONTEND_EVENT_PROFILE_LIST_CHANGED); @@ -184,13 +161,11 @@ void OBSBasic::RemoveProfile(OBSProfile profile) std::filesystem::remove_all(profile.path); } catch (const std::filesystem::filesystem_error &error) { blog(LOG_DEBUG, "%s", error.what()); - throw std::logic_error("Failed to remove profile directory: " + - profile.directoryName); + throw std::logic_error("Failed to remove profile directory: " + profile.directoryName); } blog(LOG_INFO, "------------------------------------------------"); - blog(LOG_INFO, "Removed profile '%s' (%s)", profile.name.c_str(), - profile.directoryName.c_str()); + blog(LOG_INFO, "Removed profile '%s' (%s)", profile.name.c_str(), profile.directoryName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } @@ -226,8 +201,7 @@ bool OBSBasic::CreateDuplicateProfile(const QString &name) void OBSBasic::DeleteProfile(const QString &name) { - const std::string_view currentProfileName{ - config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; + const std::string_view currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; if (currentProfileName == name.toStdString()) { on_actionRemoveProfile_triggered(); @@ -259,8 +233,7 @@ void OBSBasic::ChangeProfile() return; } - const std::string_view currentProfileName{ - config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; + const std::string_view currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; const std::string selectedProfileName{action->text().toStdString()}; if (currentProfileName == selectedProfileName) { @@ -268,14 +241,12 @@ void OBSBasic::ChangeProfile() return; } - const std::optional foundProfile = - GetProfileByName(selectedProfileName); + const std::optional foundProfile = GetProfileByName(selectedProfileName); if (!foundProfile) { const std::string errorMessage{"Selected profile not found: "}; - throw std::invalid_argument(errorMessage + - currentProfileName.data()); + throw std::invalid_argument(errorMessage + currentProfileName.data()); } const OBSProfile &selectedProfile = foundProfile.value(); @@ -284,16 +255,14 @@ void OBSBasic::ChangeProfile() ActivateProfile(selectedProfile, true); - blog(LOG_INFO, "Switched to profile '%s' (%s)", - selectedProfile.name.c_str(), + blog(LOG_INFO, "Switched to profile '%s' (%s)", selectedProfile.name.c_str(), selectedProfile.directoryName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } void OBSBasic::RefreshProfiles(bool refreshCache) { - std::string_view currentProfileName{ - config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; + std::string_view currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; QList menuActions = ui->profileMenu->actions(); @@ -311,13 +280,9 @@ void OBSBasic::RefreshProfiles(bool refreshCache) size_t numAddedProfiles = 0; for (auto &[profileName, profile] : profiles) { - QAction *action = - new QAction(QString().fromStdString(profileName), this); - action->setProperty( - "file_name", - QString().fromStdString(profile.directoryName)); - connect(action, &QAction::triggered, this, - &OBSBasic::ChangeProfile); + QAction *action = new QAction(QString().fromStdString(profileName), this); + action->setProperty("file_name", QString().fromStdString(profile.directoryName)); + connect(action, &QAction::triggered, this, &OBSBasic::ChangeProfile); action->setCheckable(true); action->setChecked(profileName == currentProfileName); @@ -337,37 +302,30 @@ void OBSBasic::RefreshProfileCache() std::map foundProfiles{}; const std::filesystem::path profilesPath = - App()->userProfilesLocation / - std::filesystem::u8path(OBSProfilePath.substr(1)); + App()->userProfilesLocation / std::filesystem::u8path(OBSProfilePath.substr(1)); if (!std::filesystem::exists(profilesPath)) { blog(LOG_WARNING, "Failed to get profiles config path"); return; } - for (const auto &entry : - std::filesystem::directory_iterator(profilesPath)) { + for (const auto &entry : std::filesystem::directory_iterator(profilesPath)) { if (!entry.is_directory()) { continue; } std::string profileCandidate; - profileCandidate.reserve(entry.path().u8string().size() + - OBSProfileSettingsFile.size() + 1); - profileCandidate.append(entry.path().u8string()) - .append("/") - .append(OBSProfileSettingsFile); + profileCandidate.reserve(entry.path().u8string().size() + OBSProfileSettingsFile.size() + 1); + profileCandidate.append(entry.path().u8string()).append("/").append(OBSProfileSettingsFile); ConfigFile config; - if (config.Open(profileCandidate.c_str(), - CONFIG_OPEN_EXISTING) != CONFIG_SUCCESS) { + if (config.Open(profileCandidate.c_str(), CONFIG_OPEN_EXISTING) != CONFIG_SUCCESS) { continue; } std::string candidateName; - const char *configName = - config_get_string(config, "General", "Name"); + const char *configName = config_get_string(config, "General", "Name"); if (configName) { candidateName = configName; @@ -375,11 +333,8 @@ void OBSBasic::RefreshProfileCache() candidateName = entry.path().filename().u8string(); } - foundProfiles.try_emplace( - candidateName, - OBSProfile{candidateName, - entry.path().filename().u8string(), - entry.path(), profileCandidate}); + foundProfiles.try_emplace(candidateName, OBSProfile{candidateName, entry.path().filename().u8string(), + entry.path(), profileCandidate}); } profiles.swap(foundProfiles); @@ -387,12 +342,10 @@ void OBSBasic::RefreshProfileCache() const OBSProfile &OBSBasic::GetCurrentProfile() const { - std::string currentProfileName{ - config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; + std::string currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; if (currentProfileName.empty()) { - throw std::invalid_argument( - "No valid profile name in configuration Basic->Profile"); + throw std::invalid_argument("No valid profile name in configuration Basic->Profile"); } const auto &foundProfile = profiles.find(currentProfileName); @@ -400,14 +353,11 @@ const OBSProfile &OBSBasic::GetCurrentProfile() const if (foundProfile != profiles.end()) { return foundProfile->second; } else { - throw std::invalid_argument( - "Profile not found in profile list: " + - currentProfileName); + throw std::invalid_argument("Profile not found in profile list: " + currentProfileName); } } -std::optional -OBSBasic::GetProfileByName(const std::string &profileName) const +std::optional OBSBasic::GetProfileByName(const std::string &profileName) const { auto foundProfile = profiles.find(profileName); @@ -418,8 +368,7 @@ OBSBasic::GetProfileByName(const std::string &profileName) const } } -std::optional -OBSBasic::GetProfileByDirectoryName(const std::string &directoryName) const +std::optional OBSBasic::GetProfileByDirectoryName(const std::string &directoryName) const { for (auto &[iterator, profile] : profiles) { if (profile.directoryName == directoryName) { @@ -434,24 +383,18 @@ OBSBasic::GetProfileByDirectoryName(const std::string &directoryName) const void OBSBasic::on_actionNewProfile_triggered() { - bool useProfileWizard = config_get_bool(App()->GetUserConfig(), "Basic", - "ConfigOnNewProfile"); + bool useProfileWizard = config_get_bool(App()->GetUserConfig(), "Basic", "ConfigOnNewProfile"); - const OBSPromptCallback profilePromptCallback = - [this](const OBSPromptResult &result) { - if (GetProfileByName(result.promptValue)) { - return false; - } + const OBSPromptCallback profilePromptCallback = [this](const OBSPromptResult &result) { + if (GetProfileByName(result.promptValue)) { + return false; + } - return true; - }; + return true; + }; - const OBSPromptRequest request{Str("AddProfile.Title"), - Str("AddProfile.Text"), - "", - true, - Str("AddProfile.WizardCheckbox"), - useProfileWizard}; + const OBSPromptRequest request{Str("AddProfile.Title"), Str("AddProfile.Text"), "", true, + Str("AddProfile.WizardCheckbox"), useProfileWizard}; OBSPromptResult result = PromptForName(request, profilePromptCallback); @@ -470,17 +413,15 @@ void OBSBasic::on_actionNewProfile_triggered() void OBSBasic::on_actionDupProfile_triggered() { - const OBSPromptCallback profilePromptCallback = - [this](const OBSPromptResult &result) { - if (GetProfileByName(result.promptValue)) { - return false; - } + const OBSPromptCallback profilePromptCallback = [this](const OBSPromptResult &result) { + if (GetProfileByName(result.promptValue)) { + return false; + } - return true; - }; + return true; + }; - const OBSPromptRequest request{Str("AddProfile.Title"), - Str("AddProfile.Text")}; + const OBSPromptRequest request{Str("AddProfile.Title"), Str("AddProfile.Text")}; OBSPromptResult result = PromptForName(request, profilePromptCallback); @@ -499,21 +440,17 @@ void OBSBasic::on_actionDupProfile_triggered() void OBSBasic::on_actionRenameProfile_triggered() { - const std::string currentProfileName = - config_get_string(App()->GetUserConfig(), "Basic", "Profile"); + const std::string currentProfileName = config_get_string(App()->GetUserConfig(), "Basic", "Profile"); - const OBSPromptCallback profilePromptCallback = - [this](const OBSPromptResult &result) { - if (GetProfileByName(result.promptValue)) { - return false; - } + const OBSPromptCallback profilePromptCallback = [this](const OBSPromptResult &result) { + if (GetProfileByName(result.promptValue)) { + return false; + } - return true; - }; + return true; + }; - const OBSPromptRequest request{Str("RenameProfile.Title"), - Str("RenameProfile.Text"), - currentProfileName}; + const OBSPromptRequest request{Str("RenameProfile.Title"), Str("RenameProfile.Text"), currentProfileName}; OBSPromptResult result = PromptForName(request, profilePromptCallback); @@ -543,14 +480,10 @@ void OBSBasic::on_actionRemoveProfile_triggered(bool skipConfirmation) if (!skipConfirmation) { const QString confirmationText = - QTStr("ConfirmRemove.Text") - .arg(QString::fromStdString( - currentProfile.name)); + QTStr("ConfirmRemove.Text").arg(QString::fromStdString(currentProfile.name)); const QMessageBox::StandardButton button = - OBSMessageBox::question( - this, QTStr("ConfirmRemove.Title"), - confirmationText); + OBSMessageBox::question(this, QTStr("ConfirmRemove.Title"), confirmationText); if (button == QMessageBox::No) { return; @@ -576,8 +509,7 @@ void OBSBasic::on_actionRemoveProfile_triggered(bool skipConfirmation) NewYouTubeAppDock(); #endif - blog(LOG_INFO, "Switched to profile '%s' (%s)", newProfile.name.c_str(), - newProfile.directoryName.c_str()); + blog(LOG_INFO, "Switched to profile '%s' (%s)", newProfile.name.c_str(), newProfile.directoryName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } @@ -585,40 +517,32 @@ void OBSBasic::on_actionImportProfile_triggered() { const QString home = QDir::homePath(); - const QString sourceDirectory = SelectDirectory( - this, QTStr("Basic.MainMenu.Profile.Import"), home); + const QString sourceDirectory = SelectDirectory(this, QTStr("Basic.MainMenu.Profile.Import"), home); if (!sourceDirectory.isEmpty() && !sourceDirectory.isNull()) { - const std::filesystem::path sourcePath = - std::filesystem::u8path(sourceDirectory.toStdString()); - const std::string directoryName = - sourcePath.filename().string(); + const std::filesystem::path sourcePath = std::filesystem::u8path(sourceDirectory.toStdString()); + const std::string directoryName = sourcePath.filename().string(); if (auto profile = GetProfileByDirectoryName(directoryName)) { - OBSMessageBox::warning( - this, QTStr("Basic.MainMenu.Profile.Import"), - QTStr("Basic.MainMenu.Profile.Exists")); + OBSMessageBox::warning(this, QTStr("Basic.MainMenu.Profile.Import"), + QTStr("Basic.MainMenu.Profile.Exists")); return; } std::string destinationPathString; - destinationPathString.reserve( - App()->userProfilesLocation.u8string().size() + - OBSProfilePath.size() + directoryName.size()); - destinationPathString - .append(App()->userProfilesLocation.u8string()) + destinationPathString.reserve(App()->userProfilesLocation.u8string().size() + OBSProfilePath.size() + + directoryName.size()); + destinationPathString.append(App()->userProfilesLocation.u8string()) .append(OBSProfilePath) .append(directoryName); - const std::filesystem::path destinationPath = - std::filesystem::u8path(destinationPathString); + const std::filesystem::path destinationPath = std::filesystem::u8path(destinationPathString); try { std::filesystem::create_directory(destinationPath); } catch (const std::filesystem::filesystem_error &error) { - blog(LOG_WARNING, - "Failed to create profile directory '%s':\n%s", - directoryName.c_str(), error.what()); + blog(LOG_WARNING, "Failed to create profile directory '%s':\n%s", directoryName.c_str(), + error.what()); return; } @@ -630,32 +554,25 @@ void OBSBasic::on_actionImportProfile_triggered() }}; for (auto &[file, isMandatory] : profileFiles) { - const std::filesystem::path sourceFile = - sourcePath / std::filesystem::u8path(file); + const std::filesystem::path sourceFile = sourcePath / std::filesystem::u8path(file); if (!std::filesystem::exists(sourceFile)) { if (isMandatory) { blog(LOG_ERROR, "Failed to import profile from directory '%s' - necessary file '%s' not found", - directoryName.c_str(), - file.c_str()); + directoryName.c_str(), file.c_str()); return; } continue; } - const std::filesystem::path destinationFile = - destinationPath / std::filesystem::u8path(file); + const std::filesystem::path destinationFile = destinationPath / std::filesystem::u8path(file); try { - std::filesystem::copy(sourceFile, - destinationFile); - } catch ( - const std::filesystem::filesystem_error &error) { - blog(LOG_WARNING, - "Failed to copy import file '%s' for profile '%s':\n%s", - file.c_str(), directoryName.c_str(), - error.what()); + std::filesystem::copy(sourceFile, destinationFile); + } catch (const std::filesystem::filesystem_error &error) { + blog(LOG_WARNING, "Failed to copy import file '%s' for profile '%s':\n%s", file.c_str(), + directoryName.c_str(), error.what()); return; } } @@ -670,49 +587,37 @@ void OBSBasic::on_actionExportProfile_triggered() const QString home = QDir::homePath(); - const QString destinationDirectory = SelectDirectory( - this, QTStr("Basic.MainMenu.Profile.Export"), home); + const QString destinationDirectory = SelectDirectory(this, QTStr("Basic.MainMenu.Profile.Export"), home); - const std::array profileFiles{"basic.ini", - "service.json", - "streamEncoder.json", + const std::array profileFiles{"basic.ini", "service.json", "streamEncoder.json", "recordEncoder.json"}; if (!destinationDirectory.isEmpty() && !destinationDirectory.isNull()) { const std::filesystem::path sourcePath = currentProfile.path; const std::filesystem::path destinationPath = - std::filesystem::u8path( - destinationDirectory.toStdString()) / + std::filesystem::u8path(destinationDirectory.toStdString()) / std::filesystem::u8path(currentProfile.directoryName); if (!std::filesystem::exists(destinationPath)) { std::filesystem::create_directory(destinationPath); } - std::filesystem::copy_options copyOptions = - std::filesystem::copy_options::overwrite_existing; + std::filesystem::copy_options copyOptions = std::filesystem::copy_options::overwrite_existing; for (auto &file : profileFiles) { - const std::filesystem::path sourceFile = - sourcePath / std::filesystem::u8path(file); + const std::filesystem::path sourceFile = sourcePath / std::filesystem::u8path(file); if (!std::filesystem::exists(sourceFile)) { continue; } - const std::filesystem::path destinationFile = - destinationPath / std::filesystem::u8path(file); + const std::filesystem::path destinationFile = destinationPath / std::filesystem::u8path(file); try { - std::filesystem::copy(sourceFile, - destinationFile, - copyOptions); - } catch ( - const std::filesystem::filesystem_error &error) { - blog(LOG_WARNING, - "Failed to copy export file '%s' for profile '%s'\n%s", - file.c_str(), currentProfile.name.c_str(), - error.what()); + std::filesystem::copy(sourceFile, destinationFile, copyOptions); + } catch (const std::filesystem::filesystem_error &error) { + blog(LOG_WARNING, "Failed to copy export file '%s' for profile '%s'\n%s", file.c_str(), + currentProfile.name.c_str(), error.what()); return; } } @@ -724,11 +629,9 @@ void OBSBasic::on_actionExportProfile_triggered() void OBSBasic::ActivateProfile(const OBSProfile &profile, bool reset) { ConfigFile config; - if (config.Open(profile.profileFile.u8string().c_str(), - CONFIG_OPEN_ALWAYS) != CONFIG_SUCCESS) { - throw std::logic_error( - "failed to open configuration file of new profile: " + - profile.profileFile.string()); + if (config.Open(profile.profileFile.u8string().c_str(), CONFIG_OPEN_ALWAYS) != CONFIG_SUCCESS) { + throw std::logic_error("failed to open configuration file of new profile: " + + profile.profileFile.string()); } config_set_string(config, "General", "Name", profile.name.c_str()); @@ -755,10 +658,8 @@ void OBSBasic::ActivateProfile(const OBSProfile &profile, bool reset) activeConfiguration.Swap(config); - config_set_string(App()->GetUserConfig(), "Basic", "Profile", - profile.name.c_str()); - config_set_string(App()->GetUserConfig(), "Basic", "ProfileDir", - profile.directoryName.c_str()); + config_set_string(App()->GetUserConfig(), "Basic", "Profile", profile.name.c_str()); + config_set_string(App()->GetUserConfig(), "Basic", "ProfileDir", profile.directoryName.c_str()); config_save_safe(App()->GetUserConfig(), "tmp", nullptr); @@ -782,16 +683,11 @@ void OBSBasic::ActivateProfile(const OBSProfile &profile, bool reset) if (!restartRequirements.empty()) { std::string requirements = std::accumulate( - std::next(restartRequirements.begin()), - restartRequirements.end(), restartRequirements[0], - [](std::string a, std::string b) { - return std::move(a) + "\n" + b; - }); + std::next(restartRequirements.begin()), restartRequirements.end(), restartRequirements[0], + [](std::string a, std::string b) { return std::move(a) + "\n" + b; }); QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("Restart"), - QTStr("LoadProfileNeedsRestart") - .arg(requirements.c_str())); + this, QTStr("Restart"), QTStr("LoadProfileNeedsRestart").arg(requirements.c_str())); if (button == QMessageBox::Yes) { restart = true; @@ -811,44 +707,34 @@ void OBSBasic::ResetProfileData() /* load audio monitoring */ if (obs_audio_monitoring_available()) { - const char *device_name = config_get_string( - activeConfiguration, "Audio", "MonitoringDeviceName"); - const char *device_id = config_get_string( - activeConfiguration, "Audio", "MonitoringDeviceId"); + const char *device_name = config_get_string(activeConfiguration, "Audio", "MonitoringDeviceName"); + const char *device_id = config_get_string(activeConfiguration, "Audio", "MonitoringDeviceId"); obs_set_audio_monitoring_device(device_name, device_id); - blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s", - device_name, device_id); + blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s", device_name, device_id); } } -std::vector -OBSBasic::GetRestartRequirements(const ConfigFile &config) const +std::vector OBSBasic::GetRestartRequirements(const ConfigFile &config) const { std::vector result; - const char *oldSpeakers = - config_get_string(activeConfiguration, "Audio", "ChannelSetup"); - const char *newSpeakers = - config_get_string(config, "Audio", "ChannelSetup"); + const char *oldSpeakers = config_get_string(activeConfiguration, "Audio", "ChannelSetup"); + const char *newSpeakers = config_get_string(config, "Audio", "ChannelSetup"); - uint64_t oldSampleRate = - config_get_uint(activeConfiguration, "Audio", "SampleRate"); + uint64_t oldSampleRate = config_get_uint(activeConfiguration, "Audio", "SampleRate"); uint64_t newSampleRate = config_get_uint(config, "Audio", "SampleRate"); if (oldSpeakers != NULL && newSpeakers != NULL) { - if (std::string_view{oldSpeakers} != - std::string_view{newSpeakers}) { - result.emplace_back( - Str("Basic.Settings.Audio.Channels")); + if (std::string_view{oldSpeakers} != std::string_view{newSpeakers}) { + result.emplace_back(Str("Basic.Settings.Audio.Channels")); } } if (oldSampleRate != 0 && newSampleRate != 0) { if (oldSampleRate != newSampleRate) { - result.emplace_back( - Str("Basic.Settings.Audio.SampleRate")); + result.emplace_back(Str("Basic.Settings.Audio.SampleRate")); } } @@ -857,10 +743,8 @@ OBSBasic::GetRestartRequirements(const ConfigFile &config) const void OBSBasic::CheckForSimpleModeX264Fallback() { - const char *curStreamEncoder = config_get_string( - activeConfiguration, "SimpleOutput", "StreamEncoder"); - const char *curRecEncoder = config_get_string( - activeConfiguration, "SimpleOutput", "RecEncoder"); + const char *curStreamEncoder = config_get_string(activeConfiguration, "SimpleOutput", "StreamEncoder"); + const char *curRecEncoder = config_get_string(activeConfiguration, "SimpleOutput", "RecEncoder"); bool qsv_supported = false; bool qsv_av1_supported = false; bool amd_supported = false; @@ -893,14 +777,10 @@ void OBSBasic::CheckForSimpleModeX264Fallback() #endif else if (strcmp(id, "av1_texture_amf") == 0) amd_av1_supported = true; - else if (strcmp(id, - "com.apple.videotoolbox.videoencoder.ave.avc") == - 0) + else if (strcmp(id, "com.apple.videotoolbox.videoencoder.ave.avc") == 0) apple_supported = true; #ifdef ENABLE_HEVC - else if (strcmp(id, - "com.apple.videotoolbox.videoencoder.ave.hevc") == - 0) + else if (strcmp(id, "com.apple.videotoolbox.videoencoder.ave.hevc") == 0) apple_hevc_supported = true; #endif } @@ -976,11 +856,9 @@ void OBSBasic::CheckForSimpleModeX264Fallback() }; if (!CheckEncoder(curStreamEncoder)) - config_set_string(activeConfiguration, "SimpleOutput", - "StreamEncoder", curStreamEncoder); + config_set_string(activeConfiguration, "SimpleOutput", "StreamEncoder", curStreamEncoder); if (!CheckEncoder(curRecEncoder)) - config_set_string(activeConfiguration, "SimpleOutput", - "RecEncoder", curRecEncoder); + config_set_string(activeConfiguration, "SimpleOutput", "RecEncoder", curRecEncoder); if (changed) { activeConfiguration.SaveSafe("tmp"); } diff --git a/UI/window-basic-main-scene-collections.cpp b/UI/window-basic-main-scene-collections.cpp index 4de7c29d4..895500d2f 100644 --- a/UI/window-basic-main-scene-collections.cpp +++ b/UI/window-basic-main-scene-collections.cpp @@ -38,48 +38,38 @@ constexpr std::string_view OBSSceneCollectionPath = "/obs-studio/basic/scenes/"; void OBSBasic::SetupNewSceneCollection(const std::string &collectionName) { - const OBSSceneCollection &newCollection = - CreateSceneCollection(collectionName); + const OBSSceneCollection &newCollection = CreateSceneCollection(collectionName); OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_CHANGING); ActivateSceneCollection(newCollection); - blog(LOG_INFO, "Created scene collection '%s' (clean, %s)", - newCollection.name.c_str(), newCollection.fileName.c_str()); + blog(LOG_INFO, "Created scene collection '%s' (clean, %s)", newCollection.name.c_str(), + newCollection.fileName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } void OBSBasic::SetupDuplicateSceneCollection(const std::string &collectionName) { - const OBSSceneCollection &newCollection = - CreateSceneCollection(collectionName); - const OBSSceneCollection ¤tCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection &newCollection = CreateSceneCollection(collectionName); + const OBSSceneCollection ¤tCollection = GetCurrentSceneCollection(); SaveProjectNow(); - const auto copyOptions = - std::filesystem::copy_options::overwrite_existing; + const auto copyOptions = std::filesystem::copy_options::overwrite_existing; try { - std::filesystem::copy(currentCollection.collectionFile, - newCollection.collectionFile, - copyOptions); + std::filesystem::copy(currentCollection.collectionFile, newCollection.collectionFile, copyOptions); } catch (const std::filesystem::filesystem_error &error) { blog(LOG_DEBUG, "%s", error.what()); - throw std::logic_error( - "Failed to copy file for cloned scene collection: " + - newCollection.name); + throw std::logic_error("Failed to copy file for cloned scene collection: " + newCollection.name); } - OBSDataAutoRelease collection = obs_data_create_from_json_file( - newCollection.collectionFile.u8string().c_str()); + OBSDataAutoRelease collection = obs_data_create_from_json_file(newCollection.collectionFile.u8string().c_str()); obs_data_set_string(collection, "name", newCollection.name.c_str()); - OBSDataArrayAutoRelease sources = - obs_data_get_array(collection, "sources"); + OBSDataArrayAutoRelease sources = obs_data_get_array(collection, "sources"); if (sources) { obs_data_erase(collection, "sources"); @@ -98,57 +88,44 @@ void OBSBasic::SetupDuplicateSceneCollection(const std::string &collectionName) obs_data_set_array(collection, "sources", sources); } - obs_data_save_json_safe(collection, - newCollection.collectionFile.u8string().c_str(), - "tmp", nullptr); + obs_data_save_json_safe(collection, newCollection.collectionFile.u8string().c_str(), "tmp", nullptr); ActivateSceneCollection(newCollection); - blog(LOG_INFO, "Created scene collection '%s' (duplicate, %s)", - newCollection.name.c_str(), newCollection.fileName.c_str()); + blog(LOG_INFO, "Created scene collection '%s' (duplicate, %s)", newCollection.name.c_str(), + newCollection.fileName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } void OBSBasic::SetupRenameSceneCollection(const std::string &collectionName) { - const OBSSceneCollection &newCollection = - CreateSceneCollection(collectionName); - const OBSSceneCollection currentCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection &newCollection = CreateSceneCollection(collectionName); + const OBSSceneCollection currentCollection = GetCurrentSceneCollection(); SaveProjectNow(); - const auto copyOptions = - std::filesystem::copy_options::overwrite_existing; + const auto copyOptions = std::filesystem::copy_options::overwrite_existing; try { - std::filesystem::copy(currentCollection.collectionFile, - newCollection.collectionFile, - copyOptions); + std::filesystem::copy(currentCollection.collectionFile, newCollection.collectionFile, copyOptions); } catch (const std::filesystem::filesystem_error &error) { blog(LOG_DEBUG, "%s", error.what()); - throw std::logic_error( - "Failed to copy file for scene collection: " + - currentCollection.name); + throw std::logic_error("Failed to copy file for scene collection: " + currentCollection.name); } collections.erase(currentCollection.name); - OBSDataAutoRelease collection = obs_data_create_from_json_file( - newCollection.collectionFile.u8string().c_str()); + OBSDataAutoRelease collection = obs_data_create_from_json_file(newCollection.collectionFile.u8string().c_str()); obs_data_set_string(collection, "name", newCollection.name.c_str()); - obs_data_save_json_safe(collection, - newCollection.collectionFile.u8string().c_str(), - "tmp", nullptr); + obs_data_save_json_safe(collection, newCollection.collectionFile.u8string().c_str(), "tmp", nullptr); ActivateSceneCollection(newCollection); RemoveSceneCollection(currentCollection); - blog(LOG_INFO, "Renamed scene collection '%s' to '%s' (%s)", - currentCollection.name.c_str(), newCollection.name.c_str(), - newCollection.fileName.c_str()); + blog(LOG_INFO, "Renamed scene collection '%s' to '%s' (%s)", currentCollection.name.c_str(), + newCollection.name.c_str(), newCollection.fileName.c_str()); blog(LOG_INFO, "------------------------------------------------"); OnEvent(OBS_FRONTEND_EVENT_SCENE_COLLECTION_RENAMED); @@ -156,43 +133,32 @@ void OBSBasic::SetupRenameSceneCollection(const std::string &collectionName) // MARK: - Scene Collection File Management Functions -const OBSSceneCollection & -OBSBasic::CreateSceneCollection(const std::string &collectionName) +const OBSSceneCollection &OBSBasic::CreateSceneCollection(const std::string &collectionName) { - if (const auto &foundCollection = - GetSceneCollectionByName(collectionName)) { - throw std::invalid_argument( - "Scene collection already exists: " + collectionName); + if (const auto &foundCollection = GetSceneCollectionByName(collectionName)) { + throw std::invalid_argument("Scene collection already exists: " + collectionName); } std::string fileName; if (!GetFileSafeName(collectionName.c_str(), fileName)) { - throw std::invalid_argument( - "Failed to create safe directory for new scene collection: " + - collectionName); + throw std::invalid_argument("Failed to create safe directory for new scene collection: " + + collectionName); } std::string collectionFile; - collectionFile.reserve(App()->userScenesLocation.u8string().size() + - OBSSceneCollectionPath.size() + fileName.size()); - collectionFile.append(App()->userScenesLocation.u8string()) - .append(OBSSceneCollectionPath) - .append(fileName); + collectionFile.reserve(App()->userScenesLocation.u8string().size() + OBSSceneCollectionPath.size() + + fileName.size()); + collectionFile.append(App()->userScenesLocation.u8string()).append(OBSSceneCollectionPath).append(fileName); if (!GetClosestUnusedFileName(collectionFile, "json")) { - throw std::invalid_argument( - "Failed to get closest file name for new scene collection: " + - fileName); + throw std::invalid_argument("Failed to get closest file name for new scene collection: " + fileName); } - const std::filesystem::path collectionFilePath = - std::filesystem::u8path(collectionFile); + const std::filesystem::path collectionFilePath = std::filesystem::u8path(collectionFile); auto [iterator, success] = collections.try_emplace( collectionName, - OBSSceneCollection{collectionName, - collectionFilePath.filename().u8string(), - collectionFilePath}); + OBSSceneCollection{collectionName, collectionFilePath.filename().u8string(), collectionFilePath}); return iterator->second; } @@ -207,13 +173,10 @@ void OBSBasic::RemoveSceneCollection(OBSSceneCollection collection) std::filesystem::remove(collectionBackupFile); } catch (const std::filesystem::filesystem_error &error) { blog(LOG_DEBUG, "%s", error.what()); - throw std::logic_error( - "Failed to remove scene collection file: " + - collection.fileName); + throw std::logic_error("Failed to remove scene collection file: " + collection.fileName); } - blog(LOG_INFO, "Removed scene collection '%s' (%s)", - collection.name.c_str(), collection.fileName.c_str()); + blog(LOG_INFO, "Removed scene collection '%s' (%s)", collection.name.c_str(), collection.fileName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } @@ -249,8 +212,8 @@ bool OBSBasic::CreateDuplicateSceneCollection(const QString &name) void OBSBasic::DeleteSceneCollection(const QString &name) { - const std::string_view currentCollectionName{config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection")}; + const std::string_view currentCollectionName{ + config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")}; if (currentCollectionName == name.toStdString()) { on_actionRemoveSceneCollection_triggered(); @@ -276,8 +239,8 @@ void OBSBasic::ChangeSceneCollection() return; } - const std::string_view currentCollectionName{config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection")}; + const std::string_view currentCollectionName{ + config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")}; const std::string selectedCollectionName{action->text().toStdString()}; if (currentCollectionName == selectedCollectionName) { @@ -285,15 +248,12 @@ void OBSBasic::ChangeSceneCollection() return; } - const std::optional foundCollection = - GetSceneCollectionByName(selectedCollectionName); + const std::optional foundCollection = GetSceneCollectionByName(selectedCollectionName); if (!foundCollection) { - const std::string errorMessage{ - "Selected scene collection not found: "}; + const std::string errorMessage{"Selected scene collection not found: "}; - throw std::invalid_argument(errorMessage + - currentCollectionName.data()); + throw std::invalid_argument(errorMessage + currentCollectionName.data()); } const OBSSceneCollection &selectedCollection = foundCollection.value(); @@ -302,16 +262,14 @@ void OBSBasic::ChangeSceneCollection() ActivateSceneCollection(selectedCollection); - blog(LOG_INFO, "Switched to scene collection '%s' (%s)", - selectedCollection.name.c_str(), + blog(LOG_INFO, "Switched to scene collection '%s' (%s)", selectedCollection.name.c_str(), selectedCollection.fileName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } void OBSBasic::RefreshSceneCollections(bool refreshCache) { - std::string_view currentCollectionName{config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection")}; + std::string_view currentCollectionName{config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")}; QList menuActions = ui->sceneCollectionMenu->actions(); @@ -328,12 +286,9 @@ void OBSBasic::RefreshSceneCollections(bool refreshCache) size_t numAddedCollections = 0; for (auto &[collectionName, collection] : collections) { - QAction *action = new QAction( - QString().fromStdString(collectionName), this); - action->setProperty("file_name", QString().fromStdString( - collection.fileName)); - connect(action, &QAction::triggered, this, - &OBSBasic::ChangeSceneCollection); + QAction *action = new QAction(QString().fromStdString(collectionName), this); + action->setProperty("file_name", QString().fromStdString(collection.fileName)); + connect(action, &QAction::triggered, this, &OBSBasic::ChangeSceneCollection); action->setCheckable(true); action->setChecked(collectionName == currentCollectionName); @@ -358,17 +313,14 @@ void OBSBasic::RefreshSceneCollectionCache() OBSSceneCollectionCache foundCollections{}; const std::filesystem::path collectionsPath = - App()->userScenesLocation / - std::filesystem::u8path(OBSSceneCollectionPath.substr(1)); + App()->userScenesLocation / std::filesystem::u8path(OBSSceneCollectionPath.substr(1)); if (!std::filesystem::exists(collectionsPath)) { - blog(LOG_WARNING, - "Failed to get scene collections config path"); + blog(LOG_WARNING, "Failed to get scene collections config path"); return; } - for (const auto &entry : - std::filesystem::directory_iterator(collectionsPath)) { + for (const auto &entry : std::filesystem::directory_iterator(collectionsPath)) { if (entry.is_directory()) { continue; } @@ -378,12 +330,10 @@ void OBSBasic::RefreshSceneCollectionCache() } OBSDataAutoRelease collectionData = - obs_data_create_from_json_file_safe( - entry.path().u8string().c_str(), "bak"); + obs_data_create_from_json_file_safe(entry.path().u8string().c_str(), "bak"); std::string candidateName; - const char *collectionName = - obs_data_get_string(collectionData, "name"); + const char *collectionName = obs_data_get_string(collectionData, "name"); if (!collectionName) { candidateName = entry.path().filename().u8string(); @@ -391,11 +341,9 @@ void OBSBasic::RefreshSceneCollectionCache() candidateName = collectionName; } - foundCollections.try_emplace( - candidateName, - OBSSceneCollection{candidateName, - entry.path().filename().u8string(), - entry.path()}); + foundCollections.try_emplace(candidateName, + OBSSceneCollection{candidateName, entry.path().filename().u8string(), + entry.path()}); } collections.swap(foundCollections); @@ -403,12 +351,10 @@ void OBSBasic::RefreshSceneCollectionCache() const OBSSceneCollection &OBSBasic::GetCurrentSceneCollection() const { - std::string currentCollectionName{config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection")}; + std::string currentCollectionName{config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")}; if (currentCollectionName.empty()) { - throw std::invalid_argument( - "No valid scene collection name in configuration Basic->SceneCollection"); + throw std::invalid_argument("No valid scene collection name in configuration Basic->SceneCollection"); } const auto &foundCollection = collections.find(currentCollectionName); @@ -416,14 +362,11 @@ const OBSSceneCollection &OBSBasic::GetCurrentSceneCollection() const if (foundCollection != collections.end()) { return foundCollection->second; } else { - throw std::invalid_argument( - "Scene collection not found in collection list: " + - currentCollectionName); + throw std::invalid_argument("Scene collection not found in collection list: " + currentCollectionName); } } -std::optional -OBSBasic::GetSceneCollectionByName(const std::string &collectionName) const +std::optional OBSBasic::GetSceneCollectionByName(const std::string &collectionName) const { auto foundCollection = collections.find(collectionName); @@ -434,8 +377,7 @@ OBSBasic::GetSceneCollectionByName(const std::string &collectionName) const } } -std::optional -OBSBasic::GetSceneCollectionByFileName(const std::string &fileName) const +std::optional OBSBasic::GetSceneCollectionByFileName(const std::string &fileName) const { for (auto &[iterator, collection] : collections) { if (collection.fileName == fileName) { @@ -450,21 +392,18 @@ OBSBasic::GetSceneCollectionByFileName(const std::string &fileName) const void OBSBasic::on_actionNewSceneCollection_triggered() { - const OBSPromptCallback sceneCollectionCallback = - [this](const OBSPromptResult &result) { - if (GetSceneCollectionByName(result.promptValue)) { - return false; - } + const OBSPromptCallback sceneCollectionCallback = [this](const OBSPromptResult &result) { + if (GetSceneCollectionByName(result.promptValue)) { + return false; + } - return true; - }; + return true; + }; - const OBSPromptRequest request{ - Str("Basic.Main.AddSceneCollection.Title"), - Str("Basic.Main.AddSceneCollection.Text")}; + const OBSPromptRequest request{Str("Basic.Main.AddSceneCollection.Title"), + Str("Basic.Main.AddSceneCollection.Text")}; - OBSPromptResult result = - PromptForName(request, sceneCollectionCallback); + OBSPromptResult result = PromptForName(request, sceneCollectionCallback); if (!result.success) { return; @@ -481,21 +420,18 @@ void OBSBasic::on_actionNewSceneCollection_triggered() void OBSBasic::on_actionDupSceneCollection_triggered() { - const OBSPromptCallback sceneCollectionCallback = - [this](const OBSPromptResult &result) { - if (GetSceneCollectionByName(result.promptValue)) { - return false; - } + const OBSPromptCallback sceneCollectionCallback = [this](const OBSPromptResult &result) { + if (GetSceneCollectionByName(result.promptValue)) { + return false; + } - return true; - }; + return true; + }; - const OBSPromptRequest request{ - Str("Basic.Main.AddSceneCollection.Title"), - Str("Basic.Main.AddSceneCollection.Text")}; + const OBSPromptRequest request{Str("Basic.Main.AddSceneCollection.Title"), + Str("Basic.Main.AddSceneCollection.Text")}; - OBSPromptResult result = - PromptForName(request, sceneCollectionCallback); + OBSPromptResult result = PromptForName(request, sceneCollectionCallback); if (!result.success) { return; @@ -512,25 +448,20 @@ void OBSBasic::on_actionDupSceneCollection_triggered() void OBSBasic::on_actionRenameSceneCollection_triggered() { - const OBSSceneCollection ¤tCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection ¤tCollection = GetCurrentSceneCollection(); - const OBSPromptCallback sceneCollectionCallback = - [this](const OBSPromptResult &result) { - if (GetSceneCollectionByName(result.promptValue)) { - return false; - } + const OBSPromptCallback sceneCollectionCallback = [this](const OBSPromptResult &result) { + if (GetSceneCollectionByName(result.promptValue)) { + return false; + } - return true; - }; + return true; + }; - const OBSPromptRequest request{ - Str("Basic.Main.RenameSceneCollection.Title"), - Str("Basic.Main.AddSceneCollection.Text"), - currentCollection.name}; + const OBSPromptRequest request{Str("Basic.Main.RenameSceneCollection.Title"), + Str("Basic.Main.AddSceneCollection.Text"), currentCollection.name}; - OBSPromptResult result = - PromptForName(request, sceneCollectionCallback); + OBSPromptResult result = PromptForName(request, sceneCollectionCallback); if (!result.success) { return; @@ -558,13 +489,9 @@ void OBSBasic::on_actionRemoveSceneCollection_triggered(bool skipConfirmation) if (!skipConfirmation) { const QString confirmationText = - QTStr("ConfirmRemove.Text") - .arg(QString::fromStdString( - currentCollection.name)); + QTStr("ConfirmRemove.Text").arg(QString::fromStdString(currentCollection.name)); const QMessageBox::StandardButton button = - OBSMessageBox::question( - this, QTStr("ConfirmRemove.Title"), - confirmationText); + OBSMessageBox::question(this, QTStr("ConfirmRemove.Title"), confirmationText); if (button == QMessageBox::No) { return; @@ -585,8 +512,8 @@ void OBSBasic::on_actionRemoveSceneCollection_triggered(bool skipConfirmation) ActivateSceneCollection(newCollection); RemoveSceneCollection(currentCollection); - blog(LOG_INFO, "Switched to scene collection '%s' (%s)", - newCollection.name.c_str(), newCollection.fileName.c_str()); + blog(LOG_INFO, "Switched to scene collection '%s' (%s)", newCollection.name.c_str(), + newCollection.fileName.c_str()); blog(LOG_INFO, "------------------------------------------------"); } @@ -602,31 +529,24 @@ void OBSBasic::on_actionExportSceneCollection_triggered() { SaveProjectNow(); - const OBSSceneCollection ¤tCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection ¤tCollection = GetCurrentSceneCollection(); const QString home = QDir::homePath(); - const QString destinationFileName = - SaveFile(this, QTStr("Basic.MainMenu.SceneCollection.Export"), - home + "/" + currentCollection.fileName.c_str(), - "JSON Files (*.json)"); + const QString destinationFileName = SaveFile(this, QTStr("Basic.MainMenu.SceneCollection.Export"), + home + "/" + currentCollection.fileName.c_str(), + "JSON Files (*.json)"); if (!destinationFileName.isEmpty() && !destinationFileName.isNull()) { - const std::filesystem::path sourceFile = - currentCollection.collectionFile; + const std::filesystem::path sourceFile = currentCollection.collectionFile; const std::filesystem::path destinationFile = - std::filesystem::u8path( - destinationFileName.toStdString()); + std::filesystem::u8path(destinationFileName.toStdString()); - OBSDataAutoRelease collection = obs_data_create_from_json_file( - sourceFile.u8string().c_str()); + OBSDataAutoRelease collection = obs_data_create_from_json_file(sourceFile.u8string().c_str()); - OBSDataArrayAutoRelease sources = - obs_data_get_array(collection, "sources"); + OBSDataArrayAutoRelease sources = obs_data_get_array(collection, "sources"); if (!sources) { - blog(LOG_WARNING, - "No sources in exported scene collection"); + blog(LOG_WARNING, "No sources in exported scene collection"); return; } @@ -638,19 +558,14 @@ void OBSBasic::on_actionExportSceneCollection_triggered() obs_data_array_enum( sources, [](obs_data_t *data, void *vector) -> void { - OBSDataVector &sourceItems{ - *static_cast(vector)}; + OBSDataVector &sourceItems{*static_cast(vector)}; sourceItems.push_back(data); }, &sourceItems); - std::sort(sourceItems.begin(), sourceItems.end(), - [](const OBSData &a, const OBSData &b) { - return astrcmpi(obs_data_get_string(a, - "name"), - obs_data_get_string( - b, "name")) < 0; - }); + std::sort(sourceItems.begin(), sourceItems.end(), [](const OBSData &a, const OBSData &b) { + return astrcmpi(obs_data_get_string(a, "name"), obs_data_get_string(b, "name")) < 0; + }); OBSDataArrayAutoRelease newSources = obs_data_array_create(); for (auto &item : sourceItems) { @@ -658,19 +573,15 @@ void OBSBasic::on_actionExportSceneCollection_triggered() } obs_data_set_array(collection, "sources", newSources); - obs_data_save_json_pretty_safe( - collection, destinationFile.u8string().c_str(), "tmp", - "bak"); + obs_data_save_json_pretty_safe(collection, destinationFile.u8string().c_str(), "tmp", "bak"); } } void OBSBasic::on_actionRemigrateSceneCollection_triggered() { if (Active()) { - OBSMessageBox::warning( - this, - QTStr("Basic.Main.RemigrateSceneCollection.Title"), - QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.Active")); + OBSMessageBox::warning(this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), + QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.Active")); return; } @@ -678,8 +589,7 @@ void OBSBasic::on_actionRemigrateSceneCollection_triggered() if (!usingAbsoluteCoordinates && !migrationBaseResolution) { OBSMessageBox::warning( - this, - QTStr("Basic.Main.RemigrateSceneCollection.Title"), + this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.UnknownBaseResolution")); return; } @@ -687,28 +597,21 @@ void OBSBasic::on_actionRemigrateSceneCollection_triggered() obs_video_info ovi; obs_get_video_info(&ovi); - if (!usingAbsoluteCoordinates && - migrationBaseResolution->first == ovi.base_width && + if (!usingAbsoluteCoordinates && migrationBaseResolution->first == ovi.base_width && migrationBaseResolution->second == ovi.base_height) { OBSMessageBox::warning( - this, - QTStr("Basic.Main.RemigrateSceneCollection.Title"), + this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.BaseResolutionMatches")); return; } - const OBSSceneCollection ¤tCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection ¤tCollection = GetCurrentSceneCollection(); QString name = QString::fromStdString(currentCollection.name); - QString message = QTStr("Basic.Main.RemigrateSceneCollection.Text") - .arg(name) - .arg(ovi.base_width) - .arg(ovi.base_height); + QString message = + QTStr("Basic.Main.RemigrateSceneCollection.Text").arg(name).arg(ovi.base_width).arg(ovi.base_height); - auto answer = OBSMessageBox::question( - this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), - message); + auto answer = OBSMessageBox::question(this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), message); if (answer == QMessageBox::No) return; @@ -722,8 +625,7 @@ void OBSBasic::on_actionRemigrateSceneCollection_triggered() if (obs_reset_video(&ovi) != OBS_VIDEO_SUCCESS) { OBSMessageBox::critical( - this, - QTStr("Basic.Main.RemigrateSceneCollection.Title"), + this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), QTStr("Basic.Main.RemigrateSceneCollection.CannotMigrate.FailedVideoReset")); return; } @@ -745,20 +647,16 @@ void OBSBasic::on_actionRemigrateSceneCollection_triggered() void OBSBasic::ActivateSceneCollection(const OBSSceneCollection &collection) { - const std::string currentCollectionName{config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection")}; + const std::string currentCollectionName{config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection")}; - if (auto foundCollection = - GetSceneCollectionByName(currentCollectionName)) { + if (auto foundCollection = GetSceneCollectionByName(currentCollectionName)) { if (collection.name != foundCollection.value().name) { SaveProjectNow(); } } - config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", - collection.name.c_str()); - config_set_string(App()->GetUserConfig(), "Basic", - "SceneCollectionFile", collection.fileName.c_str()); + config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", collection.name.c_str()); + config_set_string(App()->GetUserConfig(), "Basic", "SceneCollectionFile", collection.fileName.c_str()); Load(collection.collectionFile.u8string().c_str()); diff --git a/UI/window-basic-main-screenshot.cpp b/UI/window-basic-main-screenshot.cpp index 54700d0ff..a0b3622d1 100644 --- a/UI/window-basic-main-screenshot.cpp +++ b/UI/window-basic-main-screenshot.cpp @@ -31,8 +31,7 @@ static void ScreenshotTick(void *param, float); /* ========================================================================= */ -ScreenshotObj::ScreenshotObj(obs_source_t *source) - : weakSource(OBSGetWeakRef(source)) +ScreenshotObj::ScreenshotObj(obs_source_t *source) : weakSource(OBSGetWeakRef(source)) { obs_add_tick_callback(ScreenshotTick, this); } @@ -52,8 +51,7 @@ ScreenshotObj::~ScreenshotObj() if (cx && cy) { OBSBasic *main = OBSBasic::Get(); main->ShowStatusBarMessage( - QTStr("Basic.StatusBar.ScreenshotSavedTo") - .arg(QT_UTF8(path.c_str()))); + QTStr("Basic.StatusBar.ScreenshotSavedTo").arg(QT_UTF8(path.c_str()))); main->lastScreenshot = path; @@ -84,8 +82,7 @@ void ScreenshotObj::Screenshot() } #ifdef _WIN32 - enum gs_color_space space = - obs_source_get_color_space(source, 0, nullptr); + enum gs_color_space space = obs_source_get_color_space(source, 0, nullptr); if (space == GS_CS_709_EXTENDED) { /* Convert for JXR */ space = GS_CS_709_SCRGB; @@ -138,19 +135,15 @@ void ScreenshotObj::Copy() half_bytes.reserve(cx * cy * 8); for (uint32_t y = 0; y < cy; y++) { - const uint8_t *const line = - videoData + (y * videoLinesize); - half_bytes.insert(half_bytes.end(), line, - line + linesize); + const uint8_t *const line = videoData + (y * videoLinesize); + half_bytes.insert(half_bytes.end(), line, line + linesize); } } else { image = QImage(cx, cy, QImage::Format::Format_RGBX8888); int linesize = image.bytesPerLine(); for (int y = 0; y < (int)cy; y++) - memcpy(image.scanLine(y), - videoData + (y * videoLinesize), - linesize); + memcpy(image.scanLine(y), videoData + (y * videoLinesize), linesize); } gs_stagesurface_unmap(stagesurf); @@ -164,33 +157,24 @@ void ScreenshotObj::Save() const char *mode = config_get_string(config, "Output", "Mode"); const char *type = config_get_string(config, "AdvOut", "RecType"); - const char *adv_path = - strcmp(type, "Standard") - ? config_get_string(config, "AdvOut", "FFFilePath") - : config_get_string(config, "AdvOut", "RecFilePath"); - const char *rec_path = - strcmp(mode, "Advanced") - ? config_get_string(config, "SimpleOutput", "FilePath") - : adv_path; + const char *adv_path = strcmp(type, "Standard") ? config_get_string(config, "AdvOut", "FFFilePath") + : config_get_string(config, "AdvOut", "RecFilePath"); + const char *rec_path = strcmp(mode, "Advanced") ? config_get_string(config, "SimpleOutput", "FilePath") + : adv_path; - bool noSpace = - config_get_bool(config, "SimpleOutput", "FileNameWithoutSpace"); - const char *filenameFormat = - config_get_string(config, "Output", "FilenameFormatting"); - bool overwriteIfExists = - config_get_bool(config, "Output", "OverwriteIfExists"); + bool noSpace = config_get_bool(config, "SimpleOutput", "FileNameWithoutSpace"); + const char *filenameFormat = config_get_string(config, "Output", "FilenameFormatting"); + bool overwriteIfExists = config_get_bool(config, "Output", "OverwriteIfExists"); const char *ext = half_bytes.empty() ? "png" : "jxr"; - path = GetOutputFilename( - rec_path, ext, noSpace, overwriteIfExists, - GetFormatString(filenameFormat, "Screenshot", nullptr).c_str()); + path = GetOutputFilename(rec_path, ext, noSpace, overwriteIfExists, + GetFormatString(filenameFormat, "Screenshot", nullptr).c_str()); th = std::thread([this] { MuxAndFinish(); }); } #ifdef _WIN32 -static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx, - uint32_t cy, IWICBitmapFrameEncode *frameEncode, +static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy, IWICBitmapFrameEncode *frameEncode, IPropertyBag2 *options) { wchar_t lossless[] = L"Lossless"; @@ -220,8 +204,7 @@ static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx, if (FAILED(hr)) return hr; - if (memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf, - sizeof(WICPixelFormatGUID)) != 0) + if (memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf, sizeof(WICPixelFormatGUID)) != 0) return E_FAIL; hr = frameEncode->WritePixels(cy, cx * 8, cx * cy * 8, pixels); @@ -238,8 +221,7 @@ static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx, static HRESULT SaveJxr(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy) { Microsoft::WRL::ComPtr factory; - HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, - CLSCTX_INPROC_SERVER, + HRESULT hr = CoCreateInstance(CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(factory.GetAddressOf())); if (FAILED(hr)) return hr; @@ -254,8 +236,7 @@ static HRESULT SaveJxr(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy) return hr; Microsoft::WRL::ComPtr encoder = NULL; - hr = factory->CreateEncoder(GUID_ContainerFormatWmp, NULL, - encoder.GetAddressOf()); + hr = factory->CreateEncoder(GUID_ContainerFormatWmp, NULL, encoder.GetAddressOf()); if (FAILED(hr)) return hr; @@ -265,13 +246,11 @@ static HRESULT SaveJxr(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t cy) Microsoft::WRL::ComPtr frameEncode; Microsoft::WRL::ComPtr options; - hr = encoder->CreateNewFrame(frameEncode.GetAddressOf(), - options.GetAddressOf()); + hr = encoder->CreateNewFrame(frameEncode.GetAddressOf(), options.GetAddressOf()); if (FAILED(hr)) return hr; - hr = SaveJxrImage(path, pixels, cx, cy, frameEncode.Get(), - options.Get()); + hr = SaveJxrImage(path, pixels, cx, cy, frameEncode.Get(), options.Get()); if (FAILED(hr)) return hr; diff --git a/UI/window-basic-main-transitions.cpp b/UI/window-basic-main-transitions.cpp index a814ba603..a17137b2b 100644 --- a/UI/window-basic-main-transitions.cpp +++ b/UI/window-basic-main-transitions.cpp @@ -63,8 +63,7 @@ void OBSBasic::InitDefaultTransitions() if (!obs_is_source_configurable(id)) { const char *name = obs_source_get_display_name(id); - OBSSourceAutoRelease tr = - obs_source_create_private(id, name, NULL); + OBSSourceAutoRelease tr = obs_source_create_private(id, name, NULL); InitTransition(tr); transitions.emplace_back(tr); @@ -76,8 +75,7 @@ void OBSBasic::InitDefaultTransitions() } for (OBSSource &tr : transitions) { - ui->transitions->addItem(QT_UTF8(obs_source_get_name(tr)), - QVariant::fromValue(OBSSource(tr))); + ui->transitions->addItem(QT_UTF8(obs_source_get_name(tr)), QVariant::fromValue(OBSSource(tr))); } } @@ -87,25 +85,17 @@ void OBSBasic::AddQuickTransitionHotkey(QuickTransition *qt) QString hotkeyName; dstr_printf(hotkeyId, "OBSBasic.QuickTransition.%d", qt->id); - hotkeyName = QTStr("QuickTransitions.HotkeyName") - .arg(MakeQuickTransitionText(qt)); + hotkeyName = QTStr("QuickTransitions.HotkeyName").arg(MakeQuickTransitionText(qt)); - auto quickTransition = [](void *data, obs_hotkey_id, obs_hotkey_t *, - bool pressed) { + auto quickTransition = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { int id = (int)(uintptr_t)data; - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); if (pressed) - QMetaObject::invokeMethod(main, - "TriggerQuickTransition", - Qt::QueuedConnection, - Q_ARG(int, id)); + QMetaObject::invokeMethod(main, "TriggerQuickTransition", Qt::QueuedConnection, Q_ARG(int, id)); }; - qt->hotkey = obs_hotkey_register_frontend(hotkeyId->array, - QT_TO_UTF8(hotkeyName), - quickTransition, + qt->hotkey = obs_hotkey_register_frontend(hotkeyId->array, QT_TO_UTF8(hotkeyName), quickTransition, (void *)(uintptr_t)qt->id); } @@ -113,8 +103,7 @@ void QuickTransition::SourceRenamed(void *param, calldata_t *) { QuickTransition *qt = reinterpret_cast(param); - QString hotkeyName = QTStr("QuickTransitions.HotkeyName") - .arg(MakeQuickTransitionText(qt)); + QString hotkeyName = QTStr("QuickTransitions.HotkeyName").arg(MakeQuickTransitionText(qt)); obs_hotkey_set_description(qt->hotkey, QT_TO_UTF8(hotkeyName)); } @@ -132,8 +121,7 @@ void OBSBasic::TriggerQuickTransition(int id) overridingTransition = true; } - TransitionToScene(source, false, true, qt->duration, - qt->fadeToBlack); + TransitionToScene(source, false, true, qt->duration, qt->fadeToBlack); } } @@ -146,21 +134,17 @@ void OBSBasic::InitTransition(obs_source_t *transition) { auto onTransitionStop = [](void *data, calldata_t *) { OBSBasic *window = (OBSBasic *)data; - QMetaObject::invokeMethod(window, "TransitionStopped", - Qt::QueuedConnection); + QMetaObject::invokeMethod(window, "TransitionStopped", Qt::QueuedConnection); }; auto onTransitionFullStop = [](void *data, calldata_t *) { OBSBasic *window = (OBSBasic *)data; - QMetaObject::invokeMethod(window, "TransitionFullyStopped", - Qt::QueuedConnection); + QMetaObject::invokeMethod(window, "TransitionFullyStopped", Qt::QueuedConnection); }; signal_handler_t *handler = obs_source_get_signal_handler(transition); - signal_handler_connect(handler, "transition_video_stop", - onTransitionStop, this); - signal_handler_connect(handler, "transition_stop", onTransitionFullStop, - this); + signal_handler_connect(handler, "transition_video_stop", onTransitionStop, this); + signal_handler_connect(handler, "transition_stop", onTransitionFullStop, this); } static inline OBSSource GetTransitionComboItem(QComboBox *combo, int idx) @@ -172,12 +156,9 @@ void OBSBasic::CreateDefaultQuickTransitions() { /* non-configurable transitions are always available, so add them * to the "default quick transitions" list */ - quickTransitions.emplace_back(cutTransition, 300, - quickTransitionIdCounter++); - quickTransitions.emplace_back(fadeTransition, 300, - quickTransitionIdCounter++); - quickTransitions.emplace_back(fadeTransition, 300, - quickTransitionIdCounter++, true); + quickTransitions.emplace_back(cutTransition, 300, quickTransitionIdCounter++); + quickTransitions.emplace_back(fadeTransition, 300, quickTransitionIdCounter++); + quickTransitions.emplace_back(fadeTransition, 300, quickTransitionIdCounter++, true); } void OBSBasic::LoadQuickTransitions(obs_data_array_t *array) @@ -188,8 +169,7 @@ void OBSBasic::LoadQuickTransitions(obs_data_array_t *array) for (size_t i = 0; i < count; i++) { OBSDataAutoRelease data = obs_data_array_item(array, i); - OBSDataArrayAutoRelease hotkeys = - obs_data_get_array(data, "hotkeys"); + OBSDataArrayAutoRelease hotkeys = obs_data_get_array(data, "hotkeys"); const char *name = obs_data_get_string(data, "name"); int duration = obs_data_get_int(data, "duration"); int id = obs_data_get_int(data, "id"); @@ -198,17 +178,14 @@ void OBSBasic::LoadQuickTransitions(obs_data_array_t *array) if (id) { obs_source_t *source = FindTransition(name); if (source) { - quickTransitions.emplace_back(source, duration, - id, toBlack); + quickTransitions.emplace_back(source, duration, id, toBlack); if (quickTransitionIdCounter <= id) quickTransitionIdCounter = id + 1; int idx = (int)quickTransitions.size() - 1; - AddQuickTransitionHotkey( - &quickTransitions[idx]); - obs_hotkey_load(quickTransitions[idx].hotkey, - hotkeys); + AddQuickTransitionHotkey(&quickTransitions[idx]); + obs_hotkey_load(quickTransitions[idx].hotkey, hotkeys); } } } @@ -222,8 +199,7 @@ obs_data_array_t *OBSBasic::SaveQuickTransitions() OBSDataAutoRelease data = obs_data_create(); OBSDataArrayAutoRelease hotkeys = obs_hotkey_save(qt.hotkey); - obs_data_set_string(data, "name", - obs_source_get_name(qt.source)); + obs_data_set_string(data, "name", obs_source_get_name(qt.source)); obs_data_set_int(data, "duration", qt.duration); obs_data_set_array(data, "hotkeys", hotkeys); obs_data_set_int(data, "id", qt.id); @@ -292,9 +268,8 @@ void OBSBasic::TransitionFullyStopped() } } -void OBSBasic::TransitionToScene(OBSSource source, bool force, - bool quickTransition, int quickDuration, - bool black, bool manual) +void OBSBasic::TransitionToScene(OBSSource source, bool force, bool quickTransition, int quickDuration, bool black, + bool manual) { obs_scene_t *scene = obs_scene_from_source(source); bool usingPreviewProgram = IsPreviewProgramMode(); @@ -312,17 +287,15 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, if (!sceneDuplicationMode && lastScene == source) return; - if (swapScenesMode && lastScene && - lastScene != GetCurrentSceneSource()) + if (swapScenesMode && lastScene && lastScene != GetCurrentSceneSource()) swapScene = lastProgramScene; } } if (usingPreviewProgram && sceneDuplicationMode) { - scene = obs_scene_duplicate( - scene, obs_source_get_name(obs_scene_get_source(scene)), - editPropertiesMode ? OBS_SCENE_DUP_PRIVATE_COPY - : OBS_SCENE_DUP_PRIVATE_REFS); + scene = obs_scene_duplicate(scene, obs_source_get_name(obs_scene_get_source(scene)), + editPropertiesMode ? OBS_SCENE_DUP_PRIVATE_COPY + : OBS_SCENE_DUP_PRIVATE_REFS); source = obs_scene_get_source(scene); } @@ -343,27 +316,20 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, if (usingPreviewProgram) { if (!black && !manual) { const char *sceneName = obs_source_get_name(source); - blog(LOG_INFO, "User switched Program to scene '%s'", - sceneName); + blog(LOG_INFO, "User switched Program to scene '%s'", sceneName); } else if (black && !prevFTBSource) { - OBSSourceAutoRelease target = - obs_transition_get_active_source(transition); + OBSSourceAutoRelease target = obs_transition_get_active_source(transition); const char *sceneName = obs_source_get_name(target); - blog(LOG_INFO, "User faded from scene '%s' to black", - sceneName); + blog(LOG_INFO, "User faded from scene '%s' to black", sceneName); } else if (black && prevFTBSource) { - const char *sceneName = - obs_source_get_name(prevFTBSource); - blog(LOG_INFO, "User faded from black to scene '%s'", - sceneName); + const char *sceneName = obs_source_get_name(prevFTBSource); + blog(LOG_INFO, "User faded from black to scene '%s'", sceneName); } else if (manual) { const char *sceneName = obs_source_get_name(source); - blog(LOG_INFO, - "User started manual transition to scene '%s'", - sceneName); + blog(LOG_INFO, "User started manual transition to scene '%s'", sceneName); } } @@ -396,14 +362,11 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, if (quickTransition) duration = quickDuration; - enum obs_transition_mode mode = - manual ? OBS_TRANSITION_MODE_MANUAL - : OBS_TRANSITION_MODE_AUTO; + enum obs_transition_mode mode = manual ? OBS_TRANSITION_MODE_MANUAL : OBS_TRANSITION_MODE_AUTO; EnableTransitionWidgets(false); - bool success = obs_transition_start(transition, mode, duration, - source); + bool success = obs_transition_start(transition, mode, duration, source); if (!success) TransitionFullyStopped(); @@ -442,8 +405,7 @@ void OBSBasic::SetTransition(OBSSource transition) ui->transitionDurationLabel->setVisible(!fixed); ui->transitionDuration->setVisible(!fixed); - bool configurable = transition ? obs_source_configurable(transition) - : false; + bool configurable = transition ? obs_source_configurable(transition) : false; ui->transitionRemove->setEnabled(configurable); ui->transitionProps->setEnabled(configurable); @@ -473,24 +435,19 @@ void OBSBasic::AddTransition(const char *id) placeHolderText = format.arg(++i); } - bool accepted = NameDialog::AskForName(this, - QTStr("TransitionNameDlg.Title"), - QTStr("TransitionNameDlg.Text"), + bool accepted = NameDialog::AskForName(this, QTStr("TransitionNameDlg.Title"), QTStr("TransitionNameDlg.Text"), name, placeHolderText); if (accepted) { if (name.empty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); AddTransition(id); return; } source = FindTransition(name.c_str()); if (source) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); AddTransition(id); return; @@ -498,9 +455,7 @@ void OBSBasic::AddTransition(const char *id) source = obs_source_create_private(id, name.c_str(), NULL); InitTransition(source); - ui->transitions->addItem( - QT_UTF8(name.c_str()), - QVariant::fromValue(OBSSource(source))); + ui->transitions->addItem(QT_UTF8(name.c_str()), QVariant::fromValue(OBSSource(source))); ui->transitions->setCurrentIndex(ui->transitions->count() - 1); CreatePropertiesWindow(source); obs_source_release(source); @@ -524,8 +479,7 @@ void OBSBasic::on_transitionAdd_clicked() const char *name = obs_source_get_display_name(id); QAction *action = new QAction(name, this); - connect(action, &QAction::triggered, - [this, id]() { AddTransition(id); }); + connect(action, &QAction::triggered, [this, id]() { AddTransition(id); }); menu.addAction(action); foundConfigurableTransitions = true; @@ -553,8 +507,7 @@ void OBSBasic::on_transitionRemove_clicked() if (qt.button) qt.button->deleteLater(); RemoveQuickTransitionHotkey(&qt); - quickTransitions.erase(quickTransitions.begin() + i - - 1); + quickTransitions.erase(quickTransitions.begin() + i - 1); } } @@ -572,24 +525,20 @@ void OBSBasic::RenameTransition(OBSSource transition) QString placeHolderText = QT_UTF8(obs_source_get_name(transition)); obs_source_t *source = nullptr; - bool accepted = NameDialog::AskForName(this, - QTStr("TransitionNameDlg.Title"), - QTStr("TransitionNameDlg.Text"), + bool accepted = NameDialog::AskForName(this, QTStr("TransitionNameDlg.Title"), QTStr("TransitionNameDlg.Text"), name, placeHolderText); if (!accepted) return; if (name.empty()) { - OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); RenameTransition(transition); return; } source = FindTransition(name.c_str()); if (source) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); RenameTransition(transition); return; @@ -621,8 +570,7 @@ void OBSBasic::on_transitionProps_clicked() QMenu menu(this); QAction *action = new QAction(QTStr("Rename"), &menu); - connect(action, &QAction::triggered, - [this, source]() { RenameTransition(source); }); + connect(action, &QAction::triggered, [this, source]() { RenameTransition(source); }); menu.addAction(action); action = new QAction(QTStr("Properties"), &menu); @@ -697,11 +645,8 @@ void OBSBasic::SetCurrentScene(OBSSource scene, bool force) ui->scenes->setCurrentItem(item); ui->scenes->blockSignals(false); - if (vcamEnabled && - vcamConfig.type == - VCamOutputType::PreviewOutput) - outputHandler - ->UpdateVirtualCamOutputSource(); + if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput) + outputHandler->UpdateVirtualCamOutputSource(); OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED); break; @@ -714,8 +659,7 @@ void OBSBasic::SetCurrentScene(OBSSource scene, bool force) if (scene) { bool userSwitched = (!force && !disableSaving); - blog(LOG_INFO, "%s to scene '%s'", - userSwitched ? "User switched" : "Switched", + blog(LOG_INFO, "%s to scene '%s'", userSwitched ? "User switched" : "Switched", obs_source_get_name(scene)); } } @@ -725,8 +669,7 @@ void OBSBasic::CreateProgramDisplay() program = new OBSQTDisplay(); program->setContextMenuPolicy(Qt::CustomContextMenu); - connect(program.data(), &QWidget::customContextMenuRequested, this, - &OBSBasic::ProgramViewContextMenuRequested); + connect(program.data(), &QWidget::customContextMenuRequested, this, &OBSBasic::ProgramViewContextMenuRequested); auto displayResize = [this]() { struct obs_video_info ovi; @@ -738,8 +681,7 @@ void OBSBasic::CreateProgramDisplay() connect(program.data(), &OBSQTDisplay::DisplayResized, displayResize); auto addDisplay = [this](OBSQTDisplay *window) { - obs_display_add_draw_callback(window->GetDisplay(), - OBSBasic::RenderProgram, this); + obs_display_add_draw_callback(window->GetDisplay(), OBSBasic::RenderProgram, this); struct obs_video_info ovi; if (obs_get_video_info(&ovi)) @@ -774,8 +716,7 @@ void OBSBasic::CreateProgramOptions() mainButtonLayout->setSpacing(2); transitionButton = new QPushButton(QTStr("Transition")); - transitionButton->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Preferred); + transitionButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); QHBoxLayout *quickTransitions = new QHBoxLayout(); quickTransitions->setSpacing(2); @@ -784,8 +725,7 @@ void OBSBasic::CreateProgramOptions() addQuickTransition->setProperty("class", "icon-plus"); QLabel *quickTransitionsLabel = new QLabel(QTStr("QuickTransitions")); - quickTransitionsLabel->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Preferred); + quickTransitionsLabel->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred); quickTransitions->addWidget(quickTransitionsLabel); quickTransitions->addWidget(addQuickTransition); @@ -841,20 +781,17 @@ void OBSBasic::CreateProgramOptions() auto showToolTip = [&]() { QAction *act = menu.activeAction(); - QToolTip::showText(QCursor::pos(), act->toolTip(), - &menu, menu.actionGeometry(act)); + QToolTip::showText(QCursor::pos(), act->toolTip(), &menu, menu.actionGeometry(act)); }; - action = menu.addAction( - QTStr("QuickTransitions.DuplicateScene")); + action = menu.addAction(QTStr("QuickTransitions.DuplicateScene")); action->setToolTip(QTStr("QuickTransitions.DuplicateSceneTT")); action->setCheckable(true); action->setChecked(sceneDuplicationMode); connect(action, &QAction::triggered, toggleSceneDuplication); connect(action, &QAction::hovered, showToolTip); - action = menu.addAction( - QTStr("QuickTransitions.EditProperties")); + action = menu.addAction(QTStr("QuickTransitions.EditProperties")); action->setToolTip(QTStr("QuickTransitions.EditPropertiesTT")); action->setCheckable(true); action->setChecked(editPropertiesMode); @@ -872,8 +809,7 @@ void OBSBasic::CreateProgramOptions() menu.exec(QCursor::pos()); }; - connect(transitionButton.data(), &QAbstractButton::clicked, this, - &OBSBasic::TransitionClicked); + connect(transitionButton.data(), &QAbstractButton::clicked, this, &OBSBasic::TransitionClicked); connect(addQuickTransition, &QAbstractButton::clicked, onAdd); connect(configTransitions, &QAbstractButton::clicked, onConfig); } @@ -892,11 +828,9 @@ void OBSBasic::TBarReleased() tBarActive = false; EnableTransitionWidgets(true); - OBSSourceAutoRelease target = - obs_transition_get_active_source(transition); + OBSSourceAutoRelease target = obs_transition_get_active_source(transition); const char *sceneName = obs_source_get_name(target); - blog(LOG_INFO, "Manual transition to scene '%s' finished", - sceneName); + blog(LOG_INFO, "Manual transition to scene '%s' finished", sceneName); } else if (val <= T_BAR_CLAMP) { obs_transition_set_manual_time(transition, 0.0f); TransitionFullyStopped(); @@ -937,9 +871,7 @@ void OBSBasic::TBarChanged(int value) tBarTr = GetCurrentTransition(); if (!ValidTBarTransition(tBarTr)) - tBarTr = FindTransition( - obs_source_get_display_name( - "fade_transition")); + tBarTr = FindTransition(obs_source_get_display_name("fade_transition")); OverrideTransition(tBarTr); overridingTransition = true; @@ -952,8 +884,7 @@ void OBSBasic::TBarChanged(int value) tBarActive = true; } - obs_transition_set_manual_time(transition, - (float)value / T_BAR_PRECISION_F); + obs_transition_set_manual_time(transition, (float)value / T_BAR_PRECISION_F); OnEvent(OBS_FRONTEND_EVENT_TBAR_VALUE_CHANGED); } @@ -996,8 +927,7 @@ QMenu *OBSBasic::CreatePerSceneTransitionMenu() auto setTransition = [this](QAction *action) { int idx = action->property("transition_index").toInt(); OBSSource scene = GetCurrentSceneSource(); - OBSDataAutoRelease data = - obs_source_get_private_settings(scene); + OBSDataAutoRelease data = obs_source_get_private_settings(scene); if (idx == -1) { obs_data_set_string(data, "transition", ""); @@ -1014,14 +944,12 @@ QMenu *OBSBasic::CreatePerSceneTransitionMenu() auto setDuration = [this](int duration) { OBSSource scene = GetCurrentSceneSource(); - OBSDataAutoRelease data = - obs_source_get_private_settings(scene); + OBSDataAutoRelease data = obs_source_get_private_settings(scene); obs_data_set_int(data, "transition_duration", duration); }; - connect(duration, (void(QSpinBox::*)(int)) & QSpinBox::valueChanged, - setDuration); + connect(duration, (void(QSpinBox::*)(int)) & QSpinBox::valueChanged, setDuration); for (int i = -1; i < ui->transitions->count(); i++) { const char *name = ""; @@ -1044,8 +972,7 @@ QMenu *OBSBasic::CreatePerSceneTransitionMenu() action->setCheckable(true); action->setChecked(match); - connect(action, &QAction::triggered, - std::bind(setTransition, action)); + connect(action, &QAction::triggered, std::bind(setTransition, action)); } QWidgetAction *durationAction = new QWidgetAction(menu); @@ -1074,63 +1001,49 @@ void OBSBasic::HideTransitionProperties() CreatePropertiesWindow(source); } -void OBSBasic::PasteShowHideTransition(obs_sceneitem_t *item, bool show, - obs_source_t *tr, int duration) +void OBSBasic::PasteShowHideTransition(obs_sceneitem_t *item, bool show, obs_source_t *tr, int duration) { int64_t sceneItemId = obs_sceneitem_get_id(item); - std::string sceneUUID = obs_source_get_uuid( - obs_scene_get_source(obs_sceneitem_get_scene(item))); + std::string sceneUUID = obs_source_get_uuid(obs_scene_get_source(obs_sceneitem_get_scene(item))); - auto undo_redo = [sceneUUID, sceneItemId, - show](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(sceneUUID.c_str()); + auto undo_redo = [sceneUUID, sceneItemId, show](const std::string &data) { + OBSSourceAutoRelease source = obs_get_source_by_uuid(sceneUUID.c_str()); obs_scene_t *scene = obs_scene_from_source(source); - obs_sceneitem_t *i = - obs_scene_find_sceneitem_by_id(scene, sceneItemId); + obs_sceneitem_t *i = obs_scene_find_sceneitem_by_id(scene, sceneItemId); if (i) { - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); obs_sceneitem_transition_load(i, dat, show); } }; - OBSDataAutoRelease oldTransitionData = - obs_sceneitem_transition_save(item, show); + OBSDataAutoRelease oldTransitionData = obs_sceneitem_transition_save(item, show); - OBSSourceAutoRelease dup = - obs_source_duplicate(tr, obs_source_get_name(tr), true); + OBSSourceAutoRelease dup = obs_source_duplicate(tr, obs_source_get_name(tr), true); obs_sceneitem_set_transition(item, show, dup); obs_sceneitem_set_transition_duration(item, show, duration); - OBSDataAutoRelease transitionData = - obs_sceneitem_transition_save(item, show); + OBSDataAutoRelease transitionData = obs_sceneitem_transition_save(item, show); std::string undo_data(obs_data_get_json(oldTransitionData)); std::string redo_data(obs_data_get_json(transitionData)); if (undo_data.compare(redo_data) == 0) return; - QString text = show ? QTStr("Undo.ShowTransition") - : QTStr("Undo.HideTransition"); + QString text = show ? QTStr("Undo.ShowTransition") : QTStr("Undo.HideTransition"); const char *name = obs_source_get_name(obs_sceneitem_get_source(item)); - undo_s.add_action(text.arg(name), undo_redo, undo_redo, undo_data, - redo_data); + undo_s.add_action(text.arg(name), undo_redo, undo_redo, undo_data, redo_data); } QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) { OBSSceneItem si = GetCurrentSceneItem(); - QMenu *menu = - new QMenu(QTStr(visible ? "ShowTransition" : "HideTransition")); + QMenu *menu = new QMenu(QTStr(visible ? "ShowTransition" : "HideTransition")); QAction *action; OBSSource curTransition = obs_sceneitem_get_transition(si, visible); - const char *curId = curTransition ? obs_source_get_id(curTransition) - : nullptr; - int curDuration = - (int)obs_sceneitem_get_transition_duration(si, visible); + const char *curId = curTransition ? obs_source_get_id(curTransition) : nullptr; + int curDuration = (int)obs_sceneitem_get_transition_duration(si, visible); if (curDuration <= 0) curDuration = obs_frontend_get_transition_duration(); @@ -1143,96 +1056,67 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) duration->setValue(curDuration); auto setTransition = [this](QAction *action, bool visible) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); QString id = action->property("transition_id").toString(); OBSSceneItem sceneItem = main->GetCurrentSceneItem(); int64_t sceneItemId = obs_sceneitem_get_id(sceneItem); - std::string sceneUUID = - obs_source_get_uuid(obs_scene_get_source( - obs_sceneitem_get_scene(sceneItem))); + std::string sceneUUID = obs_source_get_uuid(obs_scene_get_source(obs_sceneitem_get_scene(sceneItem))); - auto undo_redo = [sceneUUID, sceneItemId, - visible](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(sceneUUID.c_str()); + auto undo_redo = [sceneUUID, sceneItemId, visible](const std::string &data) { + OBSSourceAutoRelease source = obs_get_source_by_uuid(sceneUUID.c_str()); obs_scene_t *scene = obs_scene_from_source(source); - obs_sceneitem_t *i = obs_scene_find_sceneitem_by_id( - scene, sceneItemId); + obs_sceneitem_t *i = obs_scene_find_sceneitem_by_id(scene, sceneItemId); if (i) { - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); obs_sceneitem_transition_load(i, dat, visible); } }; - OBSDataAutoRelease oldTransitionData = - obs_sceneitem_transition_save(sceneItem, visible); + OBSDataAutoRelease oldTransitionData = obs_sceneitem_transition_save(sceneItem, visible); if (id.isNull() || id.isEmpty()) { - obs_sceneitem_set_transition(sceneItem, visible, - nullptr); - obs_sceneitem_set_transition_duration(sceneItem, - visible, 0); + obs_sceneitem_set_transition(sceneItem, visible, nullptr); + obs_sceneitem_set_transition_duration(sceneItem, visible, 0); } else { - OBSSource tr = obs_sceneitem_get_transition(sceneItem, - visible); + OBSSource tr = obs_sceneitem_get_transition(sceneItem, visible); - if (!tr || strcmp(QT_TO_UTF8(id), - obs_source_get_id(tr)) != 0) { - QString name = QT_UTF8(obs_source_get_name( - obs_sceneitem_get_source(sceneItem))); + if (!tr || strcmp(QT_TO_UTF8(id), obs_source_get_id(tr)) != 0) { + QString name = QT_UTF8(obs_source_get_name(obs_sceneitem_get_source(sceneItem))); name += " "; - name += QTStr(visible ? "ShowTransition" - : "HideTransition"); - tr = obs_source_create_private(QT_TO_UTF8(id), - QT_TO_UTF8(name), - nullptr); - obs_sceneitem_set_transition(sceneItem, visible, - tr); + name += QTStr(visible ? "ShowTransition" : "HideTransition"); + tr = obs_source_create_private(QT_TO_UTF8(id), QT_TO_UTF8(name), nullptr); + obs_sceneitem_set_transition(sceneItem, visible, tr); obs_source_release(tr); - int duration = (int) - obs_sceneitem_get_transition_duration( - sceneItem, visible); + int duration = (int)obs_sceneitem_get_transition_duration(sceneItem, visible); if (duration <= 0) { - duration = - obs_frontend_get_transition_duration(); - obs_sceneitem_set_transition_duration( - sceneItem, visible, duration); + duration = obs_frontend_get_transition_duration(); + obs_sceneitem_set_transition_duration(sceneItem, visible, duration); } } if (obs_source_configurable(tr)) CreatePropertiesWindow(tr); } - OBSDataAutoRelease newTransitionData = - obs_sceneitem_transition_save(sceneItem, visible); + OBSDataAutoRelease newTransitionData = obs_sceneitem_transition_save(sceneItem, visible); std::string undo_data(obs_data_get_json(oldTransitionData)); std::string redo_data(obs_data_get_json(newTransitionData)); if (undo_data.compare(redo_data) != 0) - main->undo_s.add_action( - QTStr(visible ? "Undo.ShowTransition" - : "Undo.HideTransition") - .arg(obs_source_get_name( - obs_sceneitem_get_source( - sceneItem))), - undo_redo, undo_redo, undo_data, redo_data); + main->undo_s.add_action(QTStr(visible ? "Undo.ShowTransition" : "Undo.HideTransition") + .arg(obs_source_get_name(obs_sceneitem_get_source(sceneItem))), + undo_redo, undo_redo, undo_data, redo_data); }; auto setDuration = [visible](int duration) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); OBSSceneItem item = main->GetCurrentSceneItem(); obs_sceneitem_set_transition_duration(item, visible, duration); }; - connect(duration, (void(QSpinBox::*)(int)) & QSpinBox::valueChanged, - setDuration); + connect(duration, (void(QSpinBox::*)(int)) & QSpinBox::valueChanged, setDuration); action = menu->addAction(QT_UTF8(Str("None"))); action->setProperty("transition_id", QT_UTF8("")); action->setCheckable(true); action->setChecked(!curId); - connect(action, &QAction::triggered, - std::bind(setTransition, action, visible)); + connect(action, &QAction::triggered, std::bind(setTransition, action, visible)); size_t idx = 0; const char *id; while (obs_enum_transition_types(idx++, &id)) { @@ -1242,8 +1126,7 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) action->setProperty("transition_id", QT_UTF8(id)); action->setCheckable(true); action->setChecked(match); - connect(action, &QAction::triggered, - std::bind(setTransition, action, visible)); + connect(action, &QAction::triggered, std::bind(setTransition, action, visible)); } QWidgetAction *durationAction = new QWidgetAction(menu); @@ -1254,37 +1137,31 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) if (curId && obs_is_source_configurable(curId)) { menu->addSeparator(); menu->addAction(QTStr("Properties"), this, - visible ? &OBSBasic::ShowTransitionProperties - : &OBSBasic::HideTransitionProperties); + visible ? &OBSBasic::ShowTransitionProperties : &OBSBasic::HideTransitionProperties); } auto copyTransition = [this](QAction *, bool visible) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); OBSSceneItem item = main->GetCurrentSceneItem(); obs_source_t *tr = obs_sceneitem_get_transition(item, visible); - int trDur = - obs_sceneitem_get_transition_duration(item, visible); + int trDur = obs_sceneitem_get_transition_duration(item, visible); main->copySourceTransition = obs_source_get_weak_source(tr); main->copySourceTransitionDuration = trDur; }; menu->addSeparator(); action = menu->addAction(QT_UTF8(Str("Copy"))); action->setEnabled(curId != nullptr); - connect(action, &QAction::triggered, - std::bind(copyTransition, action, visible)); + connect(action, &QAction::triggered, std::bind(copyTransition, action, visible)); auto pasteTransition = [this](QAction *, bool show) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); OBSSource tr = OBSGetStrongRef(main->copySourceTransition); int trDuration = main->copySourceTransitionDuration; if (!tr) return; for (auto &selectedSource : GetAllSelectedSourceItems()) { - OBSSceneItem item = - main->ui->sources->Get(selectedSource.row()); + OBSSceneItem item = main->ui->sources->Get(selectedSource.row()); if (!item) continue; @@ -1294,8 +1171,7 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) action = menu->addAction(QT_UTF8(Str("Paste"))); action->setEnabled(!!OBSGetStrongRef(copySourceTransition)); - connect(action, &QAction::triggered, - std::bind(pasteTransition, action, visible)); + connect(action, &QAction::triggered, std::bind(pasteTransition, action, visible)); return menu; } @@ -1308,8 +1184,7 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) if (qt) { action = menu->addAction(QTStr("Remove")); action->setProperty("id", qt->id); - connect(action, &QAction::triggered, this, - &OBSBasic::QuickTransitionRemoveClicked); + connect(action, &QAction::triggered, this, &OBSBasic::QuickTransitionRemoveClicked); menu->addSeparator(); } @@ -1324,8 +1199,7 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) duration->setValue(qt ? qt->duration : 300); if (qt) { - connect(duration, - (void(QSpinBox::*)(int)) & QSpinBox::valueChanged, this, + connect(duration, (void(QSpinBox::*)(int)) & QSpinBox::valueChanged, this, &OBSBasic::QuickTransitionChangeDuration); } @@ -1336,13 +1210,10 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) if (qt) { action->setProperty("id", qt->id); - connect(action, &QAction::triggered, this, - &OBSBasic::QuickTransitionChange); + connect(action, &QAction::triggered, this, &OBSBasic::QuickTransitionChange); } else { - action->setProperty("duration", - QVariant::fromValue(duration)); - connect(action, &QAction::triggered, this, - &OBSBasic::AddQuickTransition); + action->setProperty("duration", QVariant::fromValue(duration)); + connect(action, &QAction::triggered, this, &OBSBasic::AddQuickTransition); } for (int i = 0; i < ui->transitions->count(); i++) { @@ -1356,14 +1227,10 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) if (qt) { action->setProperty("id", qt->id); - connect(action, &QAction::triggered, this, - &OBSBasic::QuickTransitionChange); + connect(action, &QAction::triggered, this, &OBSBasic::QuickTransitionChange); } else { - action->setProperty( - "duration", - QVariant::fromValue(duration)); - connect(action, &QAction::triggered, this, - &OBSBasic::AddQuickTransition); + action->setProperty("duration", QVariant::fromValue(duration)); + connect(action, &QAction::triggered, this, &OBSBasic::AddQuickTransition); } } @@ -1396,11 +1263,9 @@ void OBSBasic::AddQuickTransitionId(int id) /* --------------------------------- */ button->setMenu(buttonMenu); - connect(button, &QAbstractButton::clicked, this, - &OBSBasic::QuickTransitionClicked); + connect(button, &QAbstractButton::clicked, this, &OBSBasic::QuickTransitionClicked); - QVBoxLayout *programLayout = - reinterpret_cast(programOptions->layout()); + QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); int idx = 3; for (;; idx++) { @@ -1421,17 +1286,14 @@ void OBSBasic::AddQuickTransition() int trIdx = sender()->property("transition_index").toInt(); QSpinBox *duration = sender()->property("duration").value(); bool fadeToBlack = sender()->property("fadeToBlack").value(); - OBSSource transition = - fadeToBlack ? OBSSource(fadeTransition) - : GetTransitionComboItem(ui->transitions, trIdx); + OBSSource transition = fadeToBlack ? OBSSource(fadeTransition) : GetTransitionComboItem(ui->transitions, trIdx); if (!transition) return; int id = quickTransitionIdCounter++; - quickTransitions.emplace_back(transition, duration->value(), id, - fadeToBlack); + quickTransitions.emplace_back(transition, duration->value(), id, fadeToBlack); AddQuickTransitionId(id); int idx = (int)quickTransitions.size() - 1; @@ -1447,8 +1309,7 @@ void OBSBasic::ClearQuickTransitions() if (!programOptions) return; - QVBoxLayout *programLayout = - reinterpret_cast(programOptions->layout()); + QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); for (int idx = 0;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); @@ -1481,10 +1342,7 @@ void OBSBasic::QuickTransitionChange() QuickTransition *qt = GetQuickTransition(id); if (qt) { - OBSSource tr = fadeToBlack - ? OBSSource(fadeTransition) - : GetTransitionComboItem(ui->transitions, - trIdx); + OBSSource tr = fadeToBlack ? OBSSource(fadeTransition) : GetTransitionComboItem(ui->transitions, trIdx); if (tr) { qt->source = tr; qt->fadeToBlack = fadeToBlack; @@ -1525,8 +1383,7 @@ void OBSBasic::ClearQuickTransitionWidgets() if (!IsPreviewProgramMode()) return; - QVBoxLayout *programLayout = - reinterpret_cast(programOptions->layout()); + QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); for (int idx = 0;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); @@ -1561,24 +1418,21 @@ void OBSBasic::EnableTransitionWidgets(bool enable) if (!enable) { ui->transitionProps->setEnabled(false); } else { - bool configurable = - obs_source_configurable(GetCurrentTransition()); + bool configurable = obs_source_configurable(GetCurrentTransition()); ui->transitionProps->setEnabled(configurable); } if (!IsPreviewProgramMode()) return; - QVBoxLayout *programLayout = - reinterpret_cast(programOptions->layout()); + QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); for (int idx = 0;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); if (!item) break; - QPushButton *button = - qobject_cast(item->widget()); + QPushButton *button = qobject_cast(item->widget()); if (!button) continue; @@ -1608,13 +1462,9 @@ void OBSBasic::SetPreviewProgramMode(bool enabled) OBSSceneAutoRelease dup; if (sceneDuplicationMode) { - dup = obs_scene_duplicate( - curScene, - obs_source_get_name( - obs_scene_get_source(curScene)), - editPropertiesMode - ? OBS_SCENE_DUP_PRIVATE_COPY - : OBS_SCENE_DUP_PRIVATE_REFS); + dup = obs_scene_duplicate(curScene, obs_source_get_name(obs_scene_get_source(curScene)), + editPropertiesMode ? OBS_SCENE_DUP_PRIVATE_COPY + : OBS_SCENE_DUP_PRIVATE_REFS); } else { dup = std::move(OBSScene(curScene)); } @@ -1632,10 +1482,8 @@ void OBSBasic::SetPreviewProgramMode(bool enabled) RefreshQuickTransitions(); - programLabel = - new QLabel(QTStr("StudioMode.ProgramSceneLabel"), this); - programLabel->setSizePolicy(QSizePolicy::Ignored, - QSizePolicy::Preferred); + programLabel = new QLabel(QTStr("StudioMode.ProgramSceneLabel"), this); + programLabel->setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred); programLabel->setProperty("class", "label-preview-title"); programWidget = new QWidget(); @@ -1651,8 +1499,7 @@ void OBSBasic::SetPreviewProgramMode(bool enabled) ui->previewLayout->addWidget(programOptions); ui->previewLayout->addWidget(programWidget); - ui->previewLayout->setAlignment(programOptions, - Qt::AlignCenter); + ui->previewLayout->setAlignment(programOptions, Qt::AlignCenter); OnEvent(OBS_FRONTEND_EVENT_STUDIO_MODE_ENABLED); @@ -1720,10 +1567,8 @@ void OBSBasic::RenderProgram(void *data, uint32_t, uint32_t) /* --------------------------------------- */ - gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height), - -100.0f, 100.0f); - gs_set_viewport(window->programX, window->programY, window->programCX, - window->programCY); + gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height), -100.0f, 100.0f); + gs_set_viewport(window->programX, window->programY, window->programCX, window->programCY); obs_render_main_texture_src_color_only(); gs_load_vertexbuffer(nullptr); @@ -1742,10 +1587,8 @@ void OBSBasic::ResizeProgram(uint32_t cx, uint32_t cy) /* resize program panel to fix to the top section of the window */ targetSize = GetPixelSize(program); - GetScaleAndCenterPos(int(cx), int(cy), - targetSize.width() - PREVIEW_EDGE_SIZE * 2, - targetSize.height() - PREVIEW_EDGE_SIZE * 2, - programX, programY, programScale); + GetScaleAndCenterPos(int(cx), int(cy), targetSize.width() - PREVIEW_EDGE_SIZE * 2, + targetSize.height() - PREVIEW_EDGE_SIZE * 2, programX, programY, programScale); programX += float(PREVIEW_EDGE_SIZE); programY += float(PREVIEW_EDGE_SIZE); @@ -1763,8 +1606,7 @@ obs_data_array_t *OBSBasic::SaveTransitions() OBSDataAutoRelease sourceData = obs_data_create(); OBSDataAutoRelease settings = obs_source_get_settings(tr); - obs_data_set_string(sourceData, "name", - obs_source_get_name(tr)); + obs_data_set_string(sourceData, "name", obs_source_get_name(tr)); obs_data_set_string(sourceData, "id", obs_obj_get_id(tr)); obs_data_set_obj(sourceData, "settings", settings); @@ -1778,8 +1620,7 @@ obs_data_array_t *OBSBasic::SaveTransitions() return transitions; } -void OBSBasic::LoadTransitions(obs_data_array_t *transitions, - obs_load_source_cb cb, void *private_data) +void OBSBasic::LoadTransitions(obs_data_array_t *transitions, obs_load_source_cb cb, void *private_data) { size_t count = obs_data_array_count(transitions); @@ -1788,19 +1629,14 @@ void OBSBasic::LoadTransitions(obs_data_array_t *transitions, OBSDataAutoRelease item = obs_data_array_item(transitions, i); const char *name = obs_data_get_string(item, "name"); const char *id = obs_data_get_string(item, "id"); - OBSDataAutoRelease settings = - obs_data_get_obj(item, "settings"); + OBSDataAutoRelease settings = obs_data_get_obj(item, "settings"); - OBSSourceAutoRelease source = - obs_source_create_private(id, name, settings); + OBSSourceAutoRelease source = obs_source_create_private(id, name, settings); if (!obs_obj_invalid(source)) { InitTransition(source); - ui->transitions->addItem( - QT_UTF8(name), - QVariant::fromValue(OBSSource(source))); - ui->transitions->setCurrentIndex( - ui->transitions->count() - 1); + ui->transitions->addItem(QT_UTF8(name), QVariant::fromValue(OBSSource(source))); + ui->transitions->setCurrentIndex(ui->transitions->count() - 1); if (cb) cb(private_data, source); } else if (safe_mode || disable_3p_plugins) { @@ -1839,11 +1675,8 @@ int OBSBasic::GetOverrideTransitionDuration(OBSSource source) void OBSBasic::UpdatePreviewProgramIndicators() { - bool labels = previewProgramMode - ? config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "StudioModeLabels") - : false; + bool labels = previewProgramMode ? config_get_bool(App()->GetUserConfig(), "BasicWindow", "StudioModeLabels") + : false; ui->previewLabel->setVisible(labels); @@ -1853,13 +1686,10 @@ void OBSBasic::UpdatePreviewProgramIndicators() if (!labels) return; - QString preview = QTStr("StudioMode.PreviewSceneName") - .arg(QT_UTF8(obs_source_get_name( - GetCurrentSceneSource()))); + QString preview = + QTStr("StudioMode.PreviewSceneName").arg(QT_UTF8(obs_source_get_name(GetCurrentSceneSource()))); - QString program = - QTStr("StudioMode.ProgramSceneName") - .arg(QT_UTF8(obs_source_get_name(GetProgramSource()))); + QString program = QTStr("StudioMode.ProgramSceneName").arg(QT_UTF8(obs_source_get_name(GetProgramSource()))); if (ui->previewLabel->text() != preview) ui->previewLabel->setText(preview); diff --git a/UI/window-basic-main.cpp b/UI/window-basic-main.cpp index e7db3d765..0616a5fa9 100644 --- a/UI/window-basic-main.cpp +++ b/UI/window-basic-main.cpp @@ -158,8 +158,7 @@ template static T GetOBSRef(QListWidgetItem *item) template static void SetOBSRef(QListWidgetItem *item, T &&val) { - item->setData(static_cast(QtDataRole::OBSRef), - QVariant::fromValue(val)); + item->setData(static_cast(QtDataRole::OBSRef), QVariant::fromValue(val)); } constexpr std::string_view OBSProfilePath = "/obs-studio/basic/profiles/"; @@ -181,8 +180,7 @@ static void AddExtraModulePaths() string data_path_with_module_suffix; data_path_with_module_suffix += plugins_data_path; data_path_with_module_suffix += "/%module%"; - obs_add_module_path(plugins_path.c_str(), - data_path_with_module_suffix.c_str()); + obs_add_module_path(plugins_path.c_str(), data_path_with_module_suffix.c_str()); } if (portable_mode) @@ -190,14 +188,11 @@ static void AddExtraModulePaths() char base_module_dir[512]; #if defined(_WIN32) - int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir), - "obs-studio/plugins/%module%"); + int ret = GetProgramDataPath(base_module_dir, sizeof(base_module_dir), "obs-studio/plugins/%module%"); #elif defined(__APPLE__) - int ret = GetAppConfigPath(base_module_dir, sizeof(base_module_dir), - "obs-studio/plugins/%module%.plugin"); + int ret = GetAppConfigPath(base_module_dir, sizeof(base_module_dir), "obs-studio/plugins/%module%.plugin"); #else - int ret = GetAppConfigPath(base_module_dir, sizeof(base_module_dir), - "obs-studio/plugins/%module%"); + int ret = GetAppConfigPath(base_module_dir, sizeof(base_module_dir), "obs-studio/plugins/%module%"); #endif if (ret <= 0) @@ -206,34 +201,26 @@ static void AddExtraModulePaths() string path = base_module_dir; #if defined(__APPLE__) /* User Application Support Search Path */ - obs_add_module_path((path + "/Contents/MacOS").c_str(), - (path + "/Contents/Resources").c_str()); + obs_add_module_path((path + "/Contents/MacOS").c_str(), (path + "/Contents/Resources").c_str()); #ifndef __aarch64__ /* Legacy System Library Search Path */ char system_legacy_module_dir[PATH_MAX]; - GetProgramDataPath(system_legacy_module_dir, - sizeof(system_legacy_module_dir), - "obs-studio/plugins/%module%"); + GetProgramDataPath(system_legacy_module_dir, sizeof(system_legacy_module_dir), "obs-studio/plugins/%module%"); std::string path_system_legacy = system_legacy_module_dir; - obs_add_module_path((path_system_legacy + "/bin").c_str(), - (path_system_legacy + "/data").c_str()); + obs_add_module_path((path_system_legacy + "/bin").c_str(), (path_system_legacy + "/data").c_str()); /* Legacy User Application Support Search Path */ char user_legacy_module_dir[PATH_MAX]; - GetAppConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir), - "obs-studio/plugins/%module%"); + GetAppConfigPath(user_legacy_module_dir, sizeof(user_legacy_module_dir), "obs-studio/plugins/%module%"); std::string path_user_legacy = user_legacy_module_dir; - obs_add_module_path((path_user_legacy + "/bin").c_str(), - (path_user_legacy + "/data").c_str()); + obs_add_module_path((path_user_legacy + "/bin").c_str(), (path_user_legacy + "/data").c_str()); #endif #else #if ARCH_BITS == 64 - obs_add_module_path((path + "/bin/64bit").c_str(), - (path + "/data").c_str()); + obs_add_module_path((path + "/bin/64bit").c_str(), (path + "/data").c_str()); #else - obs_add_module_path((path + "/bin/32bit").c_str(), - (path + "/data").c_str()); + obs_add_module_path((path + "/bin/32bit").c_str(), (path + "/data").c_str()); #endif #endif } @@ -277,8 +264,7 @@ void assignDockToggle(QDockWidget *dock, QAction *action) dock->blockSignals(false); }; - dock->connect(dock->toggleViewAction(), &QAction::toggled, - handleWindowToggle); + dock->connect(dock->toggleViewAction(), &QAction::toggled, handleWindowToggle); dock->connect(action, &QAction::toggled, handleMenuToggle); } @@ -310,10 +296,7 @@ extern void RegisterRestreamAuth(); extern void RegisterYoutubeAuth(); #endif -OBSBasic::OBSBasic(QWidget *parent) - : OBSMainWindow(parent), - undo_s(ui), - ui(new Ui::OBSBasic) +OBSBasic::OBSBasic(QWidget *parent) : OBSMainWindow(parent), undo_s(ui), ui(new Ui::OBSBasic) { setAttribute(Qt::WA_NativeWindow); @@ -340,16 +323,13 @@ OBSBasic::OBSBasic(QWidget *parent) /* Set up streaming connections */ connect( - this, &OBSBasic::StreamingStarting, this, - [this] { this->streamingStarting = true; }, + this, &OBSBasic::StreamingStarting, this, [this] { this->streamingStarting = true; }, Qt::DirectConnection); connect( - this, &OBSBasic::StreamingStarted, this, - [this] { this->streamingStarting = false; }, + this, &OBSBasic::StreamingStarted, this, [this] { this->streamingStarting = false; }, Qt::DirectConnection); connect( - this, &OBSBasic::StreamingStopped, this, - [this] { this->streamingStarting = false; }, + this, &OBSBasic::StreamingStopped, this, [this] { this->streamingStarting = false; }, Qt::DirectConnection); /* Set up recording connections */ @@ -361,12 +341,10 @@ OBSBasic::OBSBasic(QWidget *parent) }, Qt::DirectConnection); connect( - this, &OBSBasic::RecordingPaused, this, - [this]() { this->recordingPaused = true; }, + this, &OBSBasic::RecordingPaused, this, [this]() { this->recordingPaused = true; }, Qt::DirectConnection); connect( - this, &OBSBasic::RecordingUnpaused, this, - [this]() { this->recordingPaused = false; }, + this, &OBSBasic::RecordingUnpaused, this, [this]() { this->recordingPaused = false; }, Qt::DirectConnection); connect( this, &OBSBasic::RecordingStopped, this, @@ -385,49 +363,34 @@ OBSBasic::OBSBasic(QWidget *parent) controlsDock->setWidget(controls); addDockWidget(Qt::BottomDockWidgetArea, controlsDock); - connect(controls, &OBSBasicControls::StreamButtonClicked, this, - &OBSBasic::StreamActionTriggered); + connect(controls, &OBSBasicControls::StreamButtonClicked, this, &OBSBasic::StreamActionTriggered); - connect(controls, &OBSBasicControls::StartStreamMenuActionClicked, this, - &OBSBasic::StartStreaming); - connect(controls, &OBSBasicControls::StopStreamMenuActionClicked, this, - &OBSBasic::StopStreaming); - connect(controls, &OBSBasicControls::ForceStopStreamMenuActionClicked, - this, &OBSBasic::ForceStopStreaming); + connect(controls, &OBSBasicControls::StartStreamMenuActionClicked, this, &OBSBasic::StartStreaming); + connect(controls, &OBSBasicControls::StopStreamMenuActionClicked, this, &OBSBasic::StopStreaming); + connect(controls, &OBSBasicControls::ForceStopStreamMenuActionClicked, this, &OBSBasic::ForceStopStreaming); - connect(controls, &OBSBasicControls::BroadcastButtonClicked, this, - &OBSBasic::BroadcastButtonClicked); + connect(controls, &OBSBasicControls::BroadcastButtonClicked, this, &OBSBasic::BroadcastButtonClicked); - connect(controls, &OBSBasicControls::RecordButtonClicked, this, - &OBSBasic::RecordActionTriggered); - connect(controls, &OBSBasicControls::PauseRecordButtonClicked, this, - &OBSBasic::RecordPauseToggled); + connect(controls, &OBSBasicControls::RecordButtonClicked, this, &OBSBasic::RecordActionTriggered); + connect(controls, &OBSBasicControls::PauseRecordButtonClicked, this, &OBSBasic::RecordPauseToggled); - connect(controls, &OBSBasicControls::ReplayBufferButtonClicked, this, - &OBSBasic::ReplayBufferActionTriggered); - connect(controls, &OBSBasicControls::SaveReplayBufferButtonClicked, - this, &OBSBasic::ReplayBufferSave); + connect(controls, &OBSBasicControls::ReplayBufferButtonClicked, this, &OBSBasic::ReplayBufferActionTriggered); + connect(controls, &OBSBasicControls::SaveReplayBufferButtonClicked, this, &OBSBasic::ReplayBufferSave); - connect(controls, &OBSBasicControls::VirtualCamButtonClicked, this, - &OBSBasic::VirtualCamActionTriggered); - connect(controls, &OBSBasicControls::VirtualCamConfigButtonClicked, - this, &OBSBasic::OpenVirtualCamConfig); + connect(controls, &OBSBasicControls::VirtualCamButtonClicked, this, &OBSBasic::VirtualCamActionTriggered); + connect(controls, &OBSBasicControls::VirtualCamConfigButtonClicked, this, &OBSBasic::OpenVirtualCamConfig); - connect(controls, &OBSBasicControls::StudioModeButtonClicked, this, - &OBSBasic::TogglePreviewProgramMode); + connect(controls, &OBSBasicControls::StudioModeButtonClicked, this, &OBSBasic::TogglePreviewProgramMode); - connect(controls, &OBSBasicControls::SettingsButtonClicked, this, - &OBSBasic::on_action_Settings_triggered); + connect(controls, &OBSBasicControls::SettingsButtonClicked, this, &OBSBasic::on_action_Settings_triggered); - connect(controls, &OBSBasicControls::ExitButtonClicked, this, - &QMainWindow::close); + connect(controls, &OBSBasicControls::ExitButtonClicked, this, &QMainWindow::close); startingDockLayout = saveState(); statsDock = new OBSDock(); statsDock->setObjectName(QStringLiteral("statsDock")); - statsDock->setFeatures(QDockWidget::DockWidgetClosable | - QDockWidget::DockWidgetMovable | + statsDock->setFeatures(QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); statsDock->setWindowTitle(QTStr("Basic.Stats")); addDockWidget(Qt::BottomDockWidgetArea, statsDock); @@ -448,8 +411,7 @@ OBSBasic::OBSBasic(QWidget *parent) ui->scenes->setAttribute(Qt::WA_MacShowFocusRect, false); ui->sources->setAttribute(Qt::WA_MacShowFocusRect, false); - bool sceneGrid = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "gridMode"); + bool sceneGrid = config_get_bool(App()->GetUserConfig(), "BasicWindow", "gridMode"); ui->scenes->SetGridMode(sceneGrid); if (sceneGrid) @@ -476,27 +438,21 @@ OBSBasic::OBSBasic(QWidget *parent) /* TODO: Move these into window-basic-preview */ /* Preview Scaling label */ - connect(ui->preview, &OBSBasicPreview::scalingChanged, - ui->previewScalePercent, + connect(ui->preview, &OBSBasicPreview::scalingChanged, ui->previewScalePercent, &OBSPreviewScalingLabel::PreviewScaleChanged); /* Preview Scaling dropdown */ - connect(ui->preview, &OBSBasicPreview::scalingChanged, - ui->previewScalingMode, + connect(ui->preview, &OBSBasicPreview::scalingChanged, ui->previewScalingMode, &OBSPreviewScalingComboBox::PreviewScaleChanged); - connect(ui->preview, &OBSBasicPreview::fixedScalingChanged, - ui->previewScalingMode, + connect(ui->preview, &OBSBasicPreview::fixedScalingChanged, ui->previewScalingMode, &OBSPreviewScalingComboBox::PreviewFixedScalingChanged); - connect(ui->previewScalingMode, - &OBSPreviewScalingComboBox::currentIndexChanged, this, + connect(ui->previewScalingMode, &OBSPreviewScalingComboBox::currentIndexChanged, this, &OBSBasic::PreviewScalingModeChanged); - connect(this, &OBSBasic::CanvasResized, ui->previewScalingMode, - &OBSPreviewScalingComboBox::CanvasResized); - connect(this, &OBSBasic::OutputResized, ui->previewScalingMode, - &OBSPreviewScalingComboBox::OutputResized); + connect(this, &OBSBasic::CanvasResized, ui->previewScalingMode, &OBSPreviewScalingComboBox::CanvasResized); + connect(this, &OBSBasic::OutputResized, ui->previewScalingMode, &OBSPreviewScalingComboBox::OutputResized); delete shortcutFilter; shortcutFilter = CreateShortcutFilter(); @@ -509,29 +465,24 @@ OBSBasic::OBSBasic(QWidget *parent) UpdateTitleBar(); - connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor, - this, &OBSBasic::SceneNameEdited); + connect(ui->scenes->itemDelegate(), &QAbstractItemDelegate::closeEditor, this, &OBSBasic::SceneNameEdited); cpuUsageInfo = os_cpu_usage_info_start(); cpuUsageTimer = new QTimer(this); - connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar, - &OBSBasicStatusBar::UpdateCPUUsage); + connect(cpuUsageTimer.data(), &QTimer::timeout, ui->statusbar, &OBSBasicStatusBar::UpdateCPUUsage); cpuUsageTimer->start(3000); diskFullTimer = new QTimer(this); - connect(diskFullTimer, &QTimer::timeout, this, - &OBSBasic::CheckDiskSpaceRemaining); + connect(diskFullTimer, &QTimer::timeout, this, &OBSBasic::CheckDiskSpaceRemaining); renameScene = new QAction(QTStr("Rename"), ui->scenesDock); renameScene->setShortcutContext(Qt::WidgetWithChildrenShortcut); - connect(renameScene, &QAction::triggered, this, - &OBSBasic::EditSceneName); + connect(renameScene, &QAction::triggered, this, &OBSBasic::EditSceneName); ui->scenesDock->addAction(renameScene); renameSource = new QAction(QTStr("Rename"), ui->sourcesDock); renameSource->setShortcutContext(Qt::WidgetWithChildrenShortcut); - connect(renameSource, &QAction::triggered, this, - &OBSBasic::EditSceneItemName); + connect(renameSource, &QAction::triggered, this, &OBSBasic::EditSceneItemName); ui->sourcesDock->addAction(renameSource); #ifdef __APPLE__ @@ -543,8 +494,7 @@ OBSBasic::OBSBasic(QWidget *parent) ui->actionCheckForUpdates->setMenuRole(QAction::AboutQtRole); ui->action_Settings->setMenuRole(QAction::PreferencesRole); - ui->actionShowMacPermissions->setMenuRole( - QAction::ApplicationSpecificRole); + ui->actionShowMacPermissions->setMenuRole(QAction::ApplicationSpecificRole); ui->actionE_xit->setMenuRole(QAction::QuitRole); #else renameScene->setShortcut({Qt::Key_F2}); @@ -555,16 +505,12 @@ OBSBasic::OBSBasic(QWidget *parent) ui->actionE_xit->setShortcut(Qt::CTRL | Qt::Key_Q); #endif - auto addNudge = [this](const QKeySequence &seq, MoveDir direction, - int distance) { + auto addNudge = [this](const QKeySequence &seq, MoveDir direction, int distance) { QAction *nudge = new QAction(ui->preview); nudge->setShortcut(seq); nudge->setShortcutContext(Qt::WidgetShortcut); ui->preview->addAction(nudge); - connect(nudge, &QAction::triggered, - [this, distance, direction]() { - Nudge(distance, direction); - }); + connect(nudge, &QAction::triggered, [this, distance, direction]() { Nudge(distance, direction); }); }; addNudge(Qt::Key_Up, MoveDir::Up, 1); @@ -594,8 +540,7 @@ OBSBasic::OBSBasic(QWidget *parent) // Register shortcuts for Undo/Redo ui->actionMainUndo->setShortcut(Qt::CTRL | Qt::Key_Z); QList shrt; - shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z) - << QKeySequence(Qt::CTRL | Qt::Key_Y); + shrt << QKeySequence((Qt::CTRL | Qt::SHIFT) | Qt::Key_Z) << QKeySequence(Qt::CTRL | Qt::Key_Y); ui->actionMainRedo->setShortcuts(shrt); ui->actionMainUndo->setShortcutContext(Qt::ApplicationShortcut); @@ -604,26 +549,20 @@ OBSBasic::OBSBasic(QWidget *parent) QPoint curPos; //restore parent window geometry - const char *geometry = config_get_string(App()->GetUserConfig(), - "BasicWindow", "geometry"); + const char *geometry = config_get_string(App()->GetUserConfig(), "BasicWindow", "geometry"); if (geometry != NULL) { - QByteArray byteArray = - QByteArray::fromBase64(QByteArray(geometry)); + QByteArray byteArray = QByteArray::fromBase64(QByteArray(geometry)); restoreGeometry(byteArray); QRect windowGeometry = normalGeometry(); if (!WindowPositionValid(windowGeometry)) { - QRect rect = - QGuiApplication::primaryScreen()->geometry(); - setGeometry(QStyle::alignedRect(Qt::LeftToRight, - Qt::AlignCenter, size(), - rect)); + QRect rect = QGuiApplication::primaryScreen()->geometry(); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), rect)); } curPos = pos(); } else { - QRect desktopRect = - QGuiApplication::primaryScreen()->geometry(); + QRect desktopRect = QGuiApplication::primaryScreen()->geometry(); QSize adjSize = desktopRect.size() / 2 - size() / 2; curPos = QPoint(adjSize.width(), adjSize.height()); } @@ -640,14 +579,11 @@ OBSBasic::OBSBasic(QWidget *parent) #endif ui->previewDisabledWidget->setContextMenuPolicy(Qt::CustomContextMenu); - connect(ui->enablePreviewButton, &QPushButton::clicked, this, - &OBSBasic::TogglePreview); + connect(ui->enablePreviewButton, &QPushButton::clicked, this, &OBSBasic::TogglePreview); - connect(ui->scenes, &SceneTree::scenesReordered, - []() { OBSProjector::UpdateMultiviewProjectors(); }); + connect(ui->scenes, &SceneTree::scenesReordered, []() { OBSProjector::UpdateMultiviewProjectors(); }); - connect(App(), &OBSApp::StyleChanged, this, - [this]() { OnEvent(OBS_FRONTEND_EVENT_THEME_CHANGED); }); + connect(App(), &OBSApp::StyleChanged, this, [this]() { OnEvent(OBS_FRONTEND_EVENT_THEME_CHANGED); }); QActionGroup *actionGroup = new QActionGroup(this); actionGroup->addAction(ui->actionSceneListMode); @@ -658,8 +594,7 @@ OBSBasic::OBSBasic(QWidget *parent) UpdatePreviewOverflowSettings(); } -static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent, - vector &audioSources) +static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent, vector &audioSources) { OBSSourceAutoRelease source = obs_get_output_source(channel); if (!source) @@ -672,12 +607,9 @@ static void SaveAudioDevice(const char *name, int channel, obs_data_t *parent, obs_data_set_obj(parent, name, data); } -static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, - obs_data_array_t *quickTransitionData, - int transitionDuration, - obs_data_array_t *transitions, - OBSScene &scene, OBSSource &curProgramScene, - obs_data_array_t *savedProjectorList) +static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, obs_data_array_t *quickTransitionData, + int transitionDuration, obs_data_array_t *transitions, OBSScene &scene, + OBSSource &curProgramScene, obs_data_array_t *savedProjectorList) { obs_data_t *saveData = obs_data_create(); @@ -698,8 +630,7 @@ static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, if (obs_source_is_group(source)) return false; - return find(begin(audioSources), end(audioSources), source) == - end(audioSources); + return find(begin(audioSources), end(audioSources), source) == end(audioSources); }; using FilterAudioSources_t = decltype(FilterAudioSources); @@ -715,10 +646,7 @@ static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, /* saving separately ensures they won't be loaded in older versions */ obs_data_array_t *groupsArray = obs_save_sources_filtered( - [](void *, obs_source_t *source) { - return obs_source_is_group(source); - }, - nullptr); + [](void *, obs_source_t *source) { return obs_source_is_group(source); }, nullptr); /* -------------------------------- */ @@ -727,8 +655,7 @@ static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, const char *sceneName = obs_source_get_name(currentScene); const char *programName = obs_source_get_name(curProgramScene); - const char *sceneCollection = config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection"); + const char *sceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection"); obs_data_set_string(saveData, "current_scene", sceneName); obs_data_set_string(saveData, "current_program_scene", programName); @@ -742,8 +669,7 @@ static obs_data_t *GenerateSaveData(obs_data_array_t *sceneOrder, obs_data_array_release(sourcesArray); obs_data_array_release(groupsArray); - obs_data_set_string(saveData, "current_transition", - obs_source_get_name(transition)); + obs_data_set_string(saveData, "current_transition", obs_source_get_name(transition)); obs_data_set_int(saveData, "transition_duration", transitionDuration); return saveData; @@ -788,8 +714,7 @@ void OBSBasic::copyActionsDynamicProperties() void OBSBasic::UpdateVolumeControlsDecayRate() { - double meterDecayRate = config_get_double(activeConfiguration, "Audio", - "MeterDecayRate"); + double meterDecayRate = config_get_double(activeConfiguration, "Audio", "MeterDecayRate"); for (size_t i = 0; i < volumes.size(); i++) { volumes[i]->SetMeterDecayRate(meterDecayRate); @@ -798,8 +723,7 @@ void OBSBasic::UpdateVolumeControlsDecayRate() void OBSBasic::UpdateVolumeControlsPeakMeterType() { - uint32_t peakMeterTypeIdx = - config_get_uint(activeConfiguration, "Audio", "PeakMeterType"); + uint32_t peakMeterTypeIdx = config_get_uint(activeConfiguration, "Audio", "PeakMeterType"); enum obs_peak_meter_type peakMeterType; switch (peakMeterTypeIdx) { @@ -840,8 +764,7 @@ obs_data_array_t *OBSBasic::SaveSceneListOrder() for (int i = 0; i < ui->scenes->count(); i++) { OBSDataAutoRelease data = obs_data_create(); - obs_data_set_string(data, "name", - QT_TO_UTF8(ui->scenes->item(i)->text())); + obs_data_set_string(data, "name", QT_TO_UTF8(ui->scenes->item(i)->text())); obs_data_array_push_back(sceneOrder, data); } @@ -873,16 +796,12 @@ obs_data_array_t *OBSBasic::SaveProjectors() obs_data_set_int(data, "monitor", projector->GetMonitor()); obs_data_set_int(data, "type", static_cast(type)); - obs_data_set_string( - data, "geometry", - projector->saveGeometry().toBase64().constData()); + obs_data_set_string(data, "geometry", projector->saveGeometry().toBase64().constData()); if (projector->IsAlwaysOnTopOverridden()) - obs_data_set_bool(data, "alwaysOnTop", - projector->IsAlwaysOnTop()); + obs_data_set_bool(data, "alwaysOnTop", projector->IsAlwaysOnTop()); - obs_data_set_bool(data, "alwaysOnTopOverridden", - projector->IsAlwaysOnTopOverridden()); + obs_data_set_bool(data, "alwaysOnTopOverridden", projector->IsAlwaysOnTopOverridden()); obs_data_array_push_back(savedProjectors, data); }; @@ -904,19 +823,14 @@ void OBSBasic::Save(const char *file) OBSDataArrayAutoRelease transitions = SaveTransitions(); OBSDataArrayAutoRelease quickTrData = SaveQuickTransitions(); OBSDataArrayAutoRelease savedProjectorList = SaveProjectors(); - OBSDataAutoRelease saveData = GenerateSaveData( - sceneOrder, quickTrData, ui->transitionDuration->value(), - transitions, scene, curProgramScene, savedProjectorList); + OBSDataAutoRelease saveData = GenerateSaveData(sceneOrder, quickTrData, ui->transitionDuration->value(), + transitions, scene, curProgramScene, savedProjectorList); obs_data_set_bool(saveData, "preview_locked", ui->preview->Locked()); - obs_data_set_bool(saveData, "scaling_enabled", - ui->preview->IsFixedScaling()); - obs_data_set_int(saveData, "scaling_level", - ui->preview->GetScalingLevel()); - obs_data_set_double(saveData, "scaling_off_x", - ui->preview->GetScrollX()); - obs_data_set_double(saveData, "scaling_off_y", - ui->preview->GetScrollY()); + obs_data_set_bool(saveData, "scaling_enabled", ui->preview->IsFixedScaling()); + obs_data_set_int(saveData, "scaling_level", ui->preview->GetScalingLevel()); + obs_data_set_double(saveData, "scaling_off_x", ui->preview->GetScrollX()); + obs_data_set_double(saveData, "scaling_off_y", ui->preview->GetScrollY()); if (vcamEnabled) { OBSDataAutoRelease obj = obs_data_create(); @@ -928,12 +842,10 @@ void OBSBasic::Save(const char *file) case VCamOutputType::PreviewOutput: break; case VCamOutputType::SceneOutput: - obs_data_set_string(obj, "scene", - vcamConfig.scene.c_str()); + obs_data_set_string(obj, "scene", vcamConfig.scene.c_str()); break; case VCamOutputType::SourceOutput: - obs_data_set_string(obj, "source", - vcamConfig.source.c_str()); + obs_data_set_string(obj, "source", vcamConfig.source.c_str()); break; } @@ -998,13 +910,10 @@ static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent) const char *source_name = obs_source_get_name(source); blog(LOG_INFO, "[Loaded global audio device]: '%s'", source_name); obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)1); - obs_monitoring_type monitoring_type = - obs_source_get_monitoring_type(source); + obs_monitoring_type monitoring_type = obs_source_get_monitoring_type(source); if (monitoring_type != OBS_MONITORING_TYPE_NONE) { - const char *type = - (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) - ? "monitor only" - : "monitor and output"; + const char *type = (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) ? "monitor only" + : "monitor and output"; blog(LOG_INFO, " - monitoring: %s", type); } @@ -1042,11 +951,9 @@ void OBSBasic::CreateFirstRunSources() #endif if (hasDesktopAudio) - ResetAudioDevice(App()->OutputAudioSource(), "default", - Str("Basic.DesktopDevice1"), 1); + ResetAudioDevice(App()->OutputAudioSource(), "default", Str("Basic.DesktopDevice1"), 1); if (hasInputAudio) - ResetAudioDevice(App()->InputAudioSource(), "default", - Str("Basic.AuxDevice1"), 3); + ResetAudioDevice(App()->InputAudioSource(), "default", Str("Basic.AuxDevice1"), 3); } void OBSBasic::DisableRelativeCoordinates(bool enable) @@ -1057,9 +964,8 @@ void OBSBasic::DisableRelativeCoordinates(bool enable) obs_data_set_bool(priv, "AbsoluteCoordinates", enable); usingAbsoluteCoordinates = enable; - ui->actionRemigrateSceneCollection->setText( - enable ? QTStr("Basic.MainMenu.SceneCollection.Migrate") - : QTStr("Basic.MainMenu.SceneCollection.Remigrate")); + ui->actionRemigrateSceneCollection->setText(enable ? QTStr("Basic.MainMenu.SceneCollection.Migrate") + : QTStr("Basic.MainMenu.SceneCollection.Remigrate")); ui->actionRemigrateSceneCollection->setEnabled(enable); } @@ -1125,14 +1031,11 @@ void OBSBasic::LoadSavedProjectors(obs_data_array_t *array) SavedProjectorInfo *info = new SavedProjectorInfo(); info->monitor = obs_data_get_int(data, "monitor"); - info->type = static_cast( - obs_data_get_int(data, "type")); - info->geometry = - std::string(obs_data_get_string(data, "geometry")); + info->type = static_cast(obs_data_get_int(data, "type")); + info->geometry = std::string(obs_data_get_string(data, "geometry")); info->name = std::string(obs_data_get_string(data, "name")); info->alwaysOnTop = obs_data_get_bool(data, "alwaysOnTop"); - info->alwaysOnTopOverridden = - obs_data_get_bool(data, "alwaysOnTopOverridden"); + info->alwaysOnTopOverridden = obs_data_get_bool(data, "alwaysOnTopOverridden"); savedProjectorsArray.emplace_back(info); } @@ -1164,33 +1067,28 @@ static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val) blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id); - obs_monitoring_type monitoring_type = - obs_source_get_monitoring_type(source); + obs_monitoring_type monitoring_type = obs_source_get_monitoring_type(source); if (monitoring_type != OBS_MONITORING_TYPE_NONE) { - const char *type = - (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) - ? "monitor only" - : "monitor and output"; + const char *type = (monitoring_type == OBS_MONITORING_TYPE_MONITOR_ONLY) ? "monitor only" + : "monitor and output"; blog(LOG_INFO, " %s- monitoring: %s", indent.c_str(), type); } int child_indent = 1 + indent_count; - obs_source_enum_filters(source, LogFilter, - (void *)(intptr_t)child_indent); + obs_source_enum_filters(source, LogFilter, (void *)(intptr_t)child_indent); obs_source_t *show_tn = obs_sceneitem_get_transition(item, true); obs_source_t *hide_tn = obs_sceneitem_get_transition(item, false); if (show_tn) - blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(), - obs_source_get_name(show_tn), obs_source_get_id(show_tn)); + blog(LOG_INFO, " %s- show: '%s' (%s)", indent.c_str(), obs_source_get_name(show_tn), + obs_source_get_id(show_tn)); if (hide_tn) - blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(), - obs_source_get_name(hide_tn), obs_source_get_id(hide_tn)); + blog(LOG_INFO, " %s- hide: '%s' (%s)", indent.c_str(), obs_source_get_name(hide_tn), + obs_source_get_id(hide_tn)); if (obs_sceneitem_is_group(item)) - obs_sceneitem_group_enum_items(item, LogSceneItem, - (void *)(intptr_t)child_indent); + obs_sceneitem_group_enum_items(item, LogSceneItem, (void *)(intptr_t)child_indent); return true; } @@ -1240,16 +1138,13 @@ void OBSBasic::Load(const char *file, bool remigrate) error_code ec; filesystem::rename(path, newPath, ec); if (ec) { - blog(LOG_ERROR, - "Failed renaming corrupt file with %d", - ec.value()); + blog(LOG_ERROR, "Failed renaming corrupt file with %d", ec.value()); } } blog(LOG_INFO, "No scene file found, creating default scene"); - bool hasFirstRun = config_get_bool(App()->GetUserConfig(), - "General", "FirstRun"); + bool hasFirstRun = config_get_bool(App()->GetUserConfig(), "General", "FirstRun"); CreateDefaultScene(!hasFirstRun); SaveProject(); @@ -1295,8 +1190,7 @@ void OBSBasic::LoadData(obs_data_t *data, const char *file, bool remigrate) /* Exit OBS if clearing scene data failed for some reason. */ if (clearingFailed) { - OBSMessageBox::critical(this, QTStr("SourceLeak.Title"), - QTStr("SourceLeak.Text")); + OBSMessageBox::critical(this, QTStr("SourceLeak.Title"), QTStr("SourceLeak.Text")); close(); return; } @@ -1318,17 +1212,13 @@ void OBSBasic::LoadData(obs_data_t *data, const char *file, bool remigrate) * not have their collection specific data lost. */ collectionModuleData = obs_data_get_obj(data, "modules"); - OBSDataArrayAutoRelease sceneOrder = - obs_data_get_array(data, "scene_order"); + OBSDataArrayAutoRelease sceneOrder = obs_data_get_array(data, "scene_order"); OBSDataArrayAutoRelease sources = obs_data_get_array(data, "sources"); OBSDataArrayAutoRelease groups = obs_data_get_array(data, "groups"); - OBSDataArrayAutoRelease transitions = - obs_data_get_array(data, "transitions"); + OBSDataArrayAutoRelease transitions = obs_data_get_array(data, "transitions"); const char *sceneName = obs_data_get_string(data, "current_scene"); - const char *programSceneName = - obs_data_get_string(data, "current_program_scene"); - const char *transitionName = - obs_data_get_string(data, "current_transition"); + const char *programSceneName = obs_data_get_string(data, "current_program_scene"); + const char *transitionName = obs_data_get_string(data, "current_transition"); if (!opt_starting_scene.empty()) { programSceneName = opt_starting_scene.c_str(); @@ -1343,8 +1233,7 @@ void OBSBasic::LoadData(obs_data_t *data, const char *file, bool remigrate) if (!transitionName) transitionName = obs_source_get_name(fadeTransition); - const char *curSceneCollection = config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection"); + const char *curSceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection"); obs_data_set_default_string(data, "name", curSceneCollection); @@ -1382,8 +1271,7 @@ void OBSBasic::LoadData(obs_data_t *data, const char *file, bool remigrate) int64_t version = obs_data_get_int(data, "version"); OBSDataAutoRelease res = obs_data_get_obj(data, "resolution"); if (res) { - lastOutputResolution = {obs_data_get_int(res, "x"), - obs_data_get_int(res, "y")}; + lastOutputResolution = {obs_data_get_int(res, "x"), obs_data_get_int(res, "y")}; } /* Only migrate legacy collection if resolution is saved. */ @@ -1409,9 +1297,7 @@ void OBSBasic::LoadData(obs_data_t *data, const char *file, bool remigrate) auto path = filesystem::u8path(file); auto backupPath = path.concat(".v1"); if (!filesystem::exists(backupPath)) { - if (!obs_data_save_json_pretty_safe( - data, backupPath.u8string().c_str(), - "tmp", NULL)) { + if (!obs_data_save_json_pretty_safe(data, backupPath.u8string().c_str(), "tmp", NULL)) { blog(LOG_WARNING, "Failed to create a backup of existing scene collection data!"); } @@ -1419,11 +1305,8 @@ void OBSBasic::LoadData(obs_data_t *data, const char *file, bool remigrate) } } else if (version < 2) { disableRelativeCoords = true; - } else if (OBSDataAutoRelease migration_res = - obs_data_get_obj(data, "migration_resolution")) { - migrationBaseResolution = {obs_data_get_int(migration_res, "x"), - obs_data_get_int(migration_res, - "y")}; + } else if (OBSDataAutoRelease migration_res = obs_data_get_obj(data, "migration_resolution")) { + migrationBaseResolution = {obs_data_get_int(migration_res, "x"), obs_data_get_int(migration_res, "y")}; } DisableRelativeCoordinates(disableRelativeCoords); @@ -1453,16 +1336,14 @@ retryScene: * fall back to original settings */ if (!opt_starting_scene.empty() && (!curScene || !curProgramScene)) { sceneName = obs_data_get_string(data, "current_scene"); - programSceneName = - obs_data_get_string(data, "current_program_scene"); + programSceneName = obs_data_get_string(data, "current_program_scene"); opt_starting_scene.clear(); goto retryScene; } if (!curScene) { auto find_scene_cb = [](void *source_ptr, obs_source_t *scene) { - *static_cast(source_ptr) = - obs_source_get_ref(scene); + *static_cast(source_ptr) = obs_source_get_ref(scene); return false; }; obs_enum_scenes(find_scene_cb, &curScene); @@ -1477,12 +1358,10 @@ retryScene: /* ------------------- */ - bool projectorSave = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "SaveProjectors"); + bool projectorSave = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SaveProjectors"); if (projectorSave) { - OBSDataArrayAutoRelease savedProjectors = - obs_data_get_array(data, "saved_projectors"); + OBSDataArrayAutoRelease savedProjectors = obs_data_get_array(data, "saved_projectors"); if (savedProjectors) { LoadSavedProjectors(savedProjectors); @@ -1496,13 +1375,10 @@ retryScene: std::string file_base = strrchr(file, '/') + 1; file_base.erase(file_base.size() - 5, 5); - config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", - name); - config_set_string(App()->GetUserConfig(), "Basic", - "SceneCollectionFile", file_base.c_str()); + config_set_string(App()->GetUserConfig(), "Basic", "SceneCollection", name); + config_set_string(App()->GetUserConfig(), "Basic", "SceneCollectionFile", file_base.c_str()); - OBSDataArrayAutoRelease quickTransitionData = - obs_data_get_array(data, "quick_transitions"); + OBSDataArrayAutoRelease quickTransitionData = obs_data_get_array(data, "quick_transitions"); LoadQuickTransitions(quickTransitionData); RefreshQuickTransitions(); @@ -1527,19 +1403,14 @@ retryScene: emit ui->preview->DisplayResized(); if (vcamEnabled) { - OBSDataAutoRelease obj = - obs_data_get_obj(data, "virtual-camera"); + OBSDataAutoRelease obj = obs_data_get_obj(data, "virtual-camera"); - vcamConfig.type = - (VCamOutputType)obs_data_get_int(obj, "type2"); + vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type2"); if (vcamConfig.type == VCamOutputType::Invalid) - vcamConfig.type = - (VCamOutputType)obs_data_get_int(obj, "type"); + vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type"); if (vcamConfig.type == VCamOutputType::Invalid) { - VCamInternalType internal = - (VCamInternalType)obs_data_get_int(obj, - "internal"); + VCamInternalType internal = (VCamInternalType)obs_data_get_int(obj, "internal"); switch (internal) { case VCamInternalType::Default: @@ -1556,10 +1427,8 @@ retryScene: if (obs_data_has_user_value(data, "resolution")) { OBSDataAutoRelease res = obs_data_get_obj(data, "resolution"); - if (obs_data_has_user_value(res, "x") && - obs_data_has_user_value(res, "y")) { - lastOutputResolution = {obs_data_get_int(res, "x"), - obs_data_get_int(res, "y")}; + if (obs_data_has_user_value(res, "x") && obs_data_has_user_value(res, "y")) { + lastOutputResolution = {obs_data_get_int(res, "x"), obs_data_get_int(res, "y")}; } } @@ -1575,28 +1444,23 @@ retryScene: if (opt_start_streaming && !safe_mode) { blog(LOG_INFO, "Starting stream due to command line parameter"); - QMetaObject::invokeMethod(this, "StartStreaming", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "StartStreaming", Qt::QueuedConnection); opt_start_streaming = false; } if (opt_start_recording && !safe_mode) { - blog(LOG_INFO, - "Starting recording due to command line parameter"); - QMetaObject::invokeMethod(this, "StartRecording", - Qt::QueuedConnection); + blog(LOG_INFO, "Starting recording due to command line parameter"); + QMetaObject::invokeMethod(this, "StartRecording", Qt::QueuedConnection); opt_start_recording = false; } if (opt_start_replaybuffer && !safe_mode) { - QMetaObject::invokeMethod(this, "StartReplayBuffer", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "StartReplayBuffer", Qt::QueuedConnection); opt_start_replaybuffer = false; } if (opt_start_virtualcam && !safe_mode) { - QMetaObject::invokeMethod(this, "StartVirtualCam", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "StartVirtualCam", Qt::QueuedConnection); opt_start_virtualcam = false; } @@ -1623,9 +1487,7 @@ void OBSBasic::SaveService() const OBSProfile ¤tProfile = GetCurrentProfile(); - const std::filesystem::path jsonFilePath = - currentProfile.path / - std::filesystem::u8path(OBSServiceFileName); + const std::filesystem::path jsonFilePath = currentProfile.path / std::filesystem::u8path(OBSServiceFileName); OBSDataAutoRelease data = obs_data_create(); OBSDataAutoRelease settings = obs_service_get_settings(service); @@ -1633,8 +1495,7 @@ void OBSBasic::SaveService() obs_data_set_string(data, "type", obs_service_get_type(service)); obs_data_set_obj(data, "settings", settings); - if (!obs_data_save_json_safe(data, jsonFilePath.u8string().c_str(), - "tmp", "bak")) { + if (!obs_data_save_json_safe(data, jsonFilePath.u8string().c_str(), "tmp", "bak")) { blog(LOG_WARNING, "Failed to save service"); } } @@ -1647,11 +1508,9 @@ bool OBSBasic::LoadService() const OBSProfile ¤tProfile = GetCurrentProfile(); const std::filesystem::path jsonFilePath = - currentProfile.path / - std::filesystem::u8path(OBSServiceFileName); + currentProfile.path / std::filesystem::u8path(OBSServiceFileName); - data = obs_data_create_from_json_file_safe( - jsonFilePath.u8string().c_str(), "bak"); + data = obs_data_create_from_json_file_safe(jsonFilePath.u8string().c_str(), "bak"); if (!data) { return false; @@ -1668,8 +1527,7 @@ bool OBSBasic::LoadService() OBSDataAutoRelease settings = obs_data_get_obj(data, "settings"); OBSDataAutoRelease hotkey_data = obs_data_get_obj(data, "hotkeys"); - service = obs_service_create(type, "default_service", settings, - hotkey_data); + service = obs_service_create(type, "default_service", settings, hotkey_data); obs_service_release(service); if (!service) @@ -1677,20 +1535,15 @@ bool OBSBasic::LoadService() /* Enforce Opus on WHIP if needed */ if (strcmp(obs_service_get_protocol(service), "WHIP") == 0) { - const char *option = config_get_string(activeConfiguration, - "SimpleOutput", - "StreamAudioEncoder"); + const char *option = config_get_string(activeConfiguration, "SimpleOutput", "StreamAudioEncoder"); if (strcmp(option, "opus") != 0) - config_set_string(activeConfiguration, "SimpleOutput", - "StreamAudioEncoder", "opus"); + config_set_string(activeConfiguration, "SimpleOutput", "StreamAudioEncoder", "opus"); - option = config_get_string(activeConfiguration, "AdvOut", - "AudioEncoder"); + option = config_get_string(activeConfiguration, "AdvOut", "AudioEncoder"); const char *encoder_codec = obs_get_encoder_codec(option); if (!encoder_codec || strcmp(encoder_codec, "opus") != 0) - config_set_string(activeConfiguration, "AdvOut", - "AudioEncoder", "ffmpeg_opus"); + config_set_string(activeConfiguration, "AdvOut", "AudioEncoder", "ffmpeg_opus"); } return true; @@ -1703,8 +1556,7 @@ bool OBSBasic::InitService() if (LoadService()) return true; - service = obs_service_create("rtmp_common", "default_service", nullptr, - nullptr); + service = obs_service_create("rtmp_common", "default_service", nullptr, nullptr); if (!service) return false; obs_service_release(service); @@ -1712,9 +1564,7 @@ bool OBSBasic::InitService() return true; } -static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, - (1.0 / 0.6), 1.75, 2.0, 2.25, - 2.5, 2.75, 3.0, 0.0}; +static const double scaled_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, (1.0 / 0.6), 1.75, 2.0, 2.25, 2.5, 2.75, 3.0, 0.0}; extern void CheckExistingCookieId(); @@ -1744,8 +1594,7 @@ bool OBSBasic::InitBasicConfigDefaults() cx *= devicePixelRatioF(); cy *= devicePixelRatioF(); - bool oldResolutionDefaults = config_get_bool( - App()->GetUserConfig(), "General", "Pre19Defaults"); + bool oldResolutionDefaults = config_get_bool(App()->GetUserConfig(), "General", "Pre19Defaults"); /* use 1920x1080 for new default base res if main monitor is above * 1920x1080, but don't apply for people from older builds -- only to @@ -1759,74 +1608,53 @@ bool OBSBasic::InitBasicConfigDefaults() /* ----------------------------------------------------- */ /* move over old FFmpeg track settings */ - if (config_has_user_value(activeConfiguration, "AdvOut", - "FFAudioTrack") && - !config_has_user_value(activeConfiguration, "AdvOut", - "Pre22.1Settings")) { + if (config_has_user_value(activeConfiguration, "AdvOut", "FFAudioTrack") && + !config_has_user_value(activeConfiguration, "AdvOut", "Pre22.1Settings")) { - int track = (int)config_get_int(activeConfiguration, "AdvOut", - "FFAudioTrack"); - config_set_int(activeConfiguration, "AdvOut", "FFAudioMixes", - 1LL << (track - 1)); - config_set_bool(activeConfiguration, "AdvOut", - "Pre22.1Settings", true); + int track = (int)config_get_int(activeConfiguration, "AdvOut", "FFAudioTrack"); + config_set_int(activeConfiguration, "AdvOut", "FFAudioMixes", 1LL << (track - 1)); + config_set_bool(activeConfiguration, "AdvOut", "Pre22.1Settings", true); changed = true; } /* ----------------------------------------------------- */ /* move over mixer values in advanced if older config */ - if (config_has_user_value(activeConfiguration, "AdvOut", - "RecTrackIndex") && - !config_has_user_value(activeConfiguration, "AdvOut", - "RecTracks")) { + if (config_has_user_value(activeConfiguration, "AdvOut", "RecTrackIndex") && + !config_has_user_value(activeConfiguration, "AdvOut", "RecTracks")) { - uint64_t track = config_get_uint(activeConfiguration, "AdvOut", - "RecTrackIndex"); + uint64_t track = config_get_uint(activeConfiguration, "AdvOut", "RecTrackIndex"); track = 1ULL << (track - 1); - config_set_uint(activeConfiguration, "AdvOut", "RecTracks", - track); - config_remove_value(activeConfiguration, "AdvOut", - "RecTrackIndex"); + config_set_uint(activeConfiguration, "AdvOut", "RecTracks", track); + config_remove_value(activeConfiguration, "AdvOut", "RecTrackIndex"); changed = true; } /* ----------------------------------------------------- */ /* set twitch chat extensions to "both" if prev version */ /* is under 24.1 */ - if (config_get_bool(App()->GetUserConfig(), "General", - "Pre24.1Defaults") && - !config_has_user_value(activeConfiguration, "Twitch", - "AddonChoice")) { + if (config_get_bool(App()->GetUserConfig(), "General", "Pre24.1Defaults") && + !config_has_user_value(activeConfiguration, "Twitch", "AddonChoice")) { config_set_int(activeConfiguration, "Twitch", "AddonChoice", 3); changed = true; } /* ----------------------------------------------------- */ /* move bitrate enforcement setting to new value */ - if (config_has_user_value(activeConfiguration, "SimpleOutput", - "EnforceBitrate") && - !config_has_user_value(activeConfiguration, "Stream1", - "IgnoreRecommended") && - !config_has_user_value(activeConfiguration, "Stream1", - "MovedOldEnforce")) { - bool enforce = config_get_bool( - activeConfiguration, "SimpleOutput", "EnforceBitrate"); - config_set_bool(activeConfiguration, "Stream1", - "IgnoreRecommended", !enforce); - config_set_bool(activeConfiguration, "Stream1", - "MovedOldEnforce", true); + if (config_has_user_value(activeConfiguration, "SimpleOutput", "EnforceBitrate") && + !config_has_user_value(activeConfiguration, "Stream1", "IgnoreRecommended") && + !config_has_user_value(activeConfiguration, "Stream1", "MovedOldEnforce")) { + bool enforce = config_get_bool(activeConfiguration, "SimpleOutput", "EnforceBitrate"); + config_set_bool(activeConfiguration, "Stream1", "IgnoreRecommended", !enforce); + config_set_bool(activeConfiguration, "Stream1", "MovedOldEnforce", true); changed = true; } /* ----------------------------------------------------- */ /* enforce minimum retry delay of 1 second prior to 27.1 */ - if (config_has_user_value(activeConfiguration, "Output", - "RetryDelay")) { - int retryDelay = config_get_uint(activeConfiguration, "Output", - "RetryDelay"); + if (config_has_user_value(activeConfiguration, "Output", "RetryDelay")) { + int retryDelay = config_get_uint(activeConfiguration, "Output", "RetryDelay"); if (retryDelay < 1) { - config_set_uint(activeConfiguration, "Output", - "RetryDelay", 1); + config_set_uint(activeConfiguration, "Output", "RetryDelay", 1); changed = true; } } @@ -1835,16 +1663,13 @@ bool OBSBasic::InitBasicConfigDefaults() /* Migrate old container selection (if any) to new key. */ auto MigrateFormat = [&](const char *section) { - bool has_old_key = config_has_user_value(activeConfiguration, - section, "RecFormat"); - bool has_new_key = config_has_user_value(activeConfiguration, - section, "RecFormat2"); + bool has_old_key = config_has_user_value(activeConfiguration, section, "RecFormat"); + bool has_new_key = config_has_user_value(activeConfiguration, section, "RecFormat2"); if (!has_new_key && !has_old_key) return; - string old_format = config_get_string( - activeConfiguration, section, - has_new_key ? "RecFormat2" : "RecFormat"); + string old_format = + config_get_string(activeConfiguration, section, has_new_key ? "RecFormat2" : "RecFormat"); string new_format = old_format; if (old_format == "ts") new_format = "mpegts"; @@ -1856,8 +1681,7 @@ bool OBSBasic::InitBasicConfigDefaults() new_format = "fragmented_mov"; if (new_format != old_format || !has_new_key) { - config_set_string(activeConfiguration, section, - "RecFormat2", new_format.c_str()); + config_set_string(activeConfiguration, section, "RecFormat2", new_format.c_str()); changed = true; } }; @@ -1869,17 +1693,13 @@ bool OBSBasic::InitBasicConfigDefaults() /* Migrate output scale setting to GPU scaling options. */ if (config_get_bool(activeConfiguration, "AdvOut", "Rescale") && - !config_has_user_value(activeConfiguration, "AdvOut", - "RescaleFilter")) { - config_set_int(activeConfiguration, "AdvOut", "RescaleFilter", - OBS_SCALE_BILINEAR); + !config_has_user_value(activeConfiguration, "AdvOut", "RescaleFilter")) { + config_set_int(activeConfiguration, "AdvOut", "RescaleFilter", OBS_SCALE_BILINEAR); } if (config_get_bool(activeConfiguration, "AdvOut", "RecRescale") && - !config_has_user_value(activeConfiguration, "AdvOut", - "RecRescaleFilter")) { - config_set_int(activeConfiguration, "AdvOut", - "RecRescaleFilter", OBS_SCALE_BILINEAR); + !config_has_user_value(activeConfiguration, "AdvOut", "RecRescaleFilter")) { + config_set_int(activeConfiguration, "AdvOut", "RecRescaleFilter", OBS_SCALE_BILINEAR); } /* ----------------------------------------------------- */ @@ -1890,113 +1710,63 @@ bool OBSBasic::InitBasicConfigDefaults() /* ----------------------------------------------------- */ - config_set_default_string(activeConfiguration, "Output", "Mode", - "Simple"); + config_set_default_string(activeConfiguration, "Output", "Mode", "Simple"); - config_set_default_bool(activeConfiguration, "Stream1", - "IgnoreRecommended", false); - config_set_default_bool(activeConfiguration, "Stream1", - "EnableMultitrackVideo", false); - config_set_default_bool(activeConfiguration, "Stream1", - "MultitrackVideoMaximumAggregateBitrateAuto", - true); - config_set_default_bool(activeConfiguration, "Stream1", - "MultitrackVideoMaximumVideoTracksAuto", true); + config_set_default_bool(activeConfiguration, "Stream1", "IgnoreRecommended", false); + config_set_default_bool(activeConfiguration, "Stream1", "EnableMultitrackVideo", false); + config_set_default_bool(activeConfiguration, "Stream1", "MultitrackVideoMaximumAggregateBitrateAuto", true); + config_set_default_bool(activeConfiguration, "Stream1", "MultitrackVideoMaximumVideoTracksAuto", true); - config_set_default_string(activeConfiguration, "SimpleOutput", - "FilePath", - GetDefaultVideoSavePath().c_str()); - config_set_default_string(activeConfiguration, "SimpleOutput", - "RecFormat2", DEFAULT_CONTAINER); - config_set_default_uint(activeConfiguration, "SimpleOutput", "VBitrate", - 2500); - config_set_default_uint(activeConfiguration, "SimpleOutput", "ABitrate", - 160); - config_set_default_bool(activeConfiguration, "SimpleOutput", - "UseAdvanced", false); - config_set_default_string(activeConfiguration, "SimpleOutput", "Preset", - "veryfast"); - config_set_default_string(activeConfiguration, "SimpleOutput", - "NVENCPreset2", "p5"); - config_set_default_string(activeConfiguration, "SimpleOutput", - "RecQuality", "Stream"); - config_set_default_bool(activeConfiguration, "SimpleOutput", "RecRB", - false); - config_set_default_int(activeConfiguration, "SimpleOutput", "RecRBTime", - 20); - config_set_default_int(activeConfiguration, "SimpleOutput", "RecRBSize", - 512); - config_set_default_string(activeConfiguration, "SimpleOutput", - "RecRBPrefix", "Replay"); - config_set_default_string(activeConfiguration, "SimpleOutput", - "StreamAudioEncoder", "aac"); - config_set_default_string(activeConfiguration, "SimpleOutput", - "RecAudioEncoder", "aac"); - config_set_default_uint(activeConfiguration, "SimpleOutput", - "RecTracks", (1 << 0)); + config_set_default_string(activeConfiguration, "SimpleOutput", "FilePath", GetDefaultVideoSavePath().c_str()); + config_set_default_string(activeConfiguration, "SimpleOutput", "RecFormat2", DEFAULT_CONTAINER); + config_set_default_uint(activeConfiguration, "SimpleOutput", "VBitrate", 2500); + config_set_default_uint(activeConfiguration, "SimpleOutput", "ABitrate", 160); + config_set_default_bool(activeConfiguration, "SimpleOutput", "UseAdvanced", false); + config_set_default_string(activeConfiguration, "SimpleOutput", "Preset", "veryfast"); + config_set_default_string(activeConfiguration, "SimpleOutput", "NVENCPreset2", "p5"); + config_set_default_string(activeConfiguration, "SimpleOutput", "RecQuality", "Stream"); + config_set_default_bool(activeConfiguration, "SimpleOutput", "RecRB", false); + config_set_default_int(activeConfiguration, "SimpleOutput", "RecRBTime", 20); + config_set_default_int(activeConfiguration, "SimpleOutput", "RecRBSize", 512); + config_set_default_string(activeConfiguration, "SimpleOutput", "RecRBPrefix", "Replay"); + config_set_default_string(activeConfiguration, "SimpleOutput", "StreamAudioEncoder", "aac"); + config_set_default_string(activeConfiguration, "SimpleOutput", "RecAudioEncoder", "aac"); + config_set_default_uint(activeConfiguration, "SimpleOutput", "RecTracks", (1 << 0)); - config_set_default_bool(activeConfiguration, "AdvOut", - "ApplyServiceSettings", true); - config_set_default_bool(activeConfiguration, "AdvOut", "UseRescale", - false); + config_set_default_bool(activeConfiguration, "AdvOut", "ApplyServiceSettings", true); + config_set_default_bool(activeConfiguration, "AdvOut", "UseRescale", false); config_set_default_uint(activeConfiguration, "AdvOut", "TrackIndex", 1); - config_set_default_uint(activeConfiguration, "AdvOut", "VodTrackIndex", - 2); - config_set_default_string(activeConfiguration, "AdvOut", "Encoder", - "obs_x264"); + config_set_default_uint(activeConfiguration, "AdvOut", "VodTrackIndex", 2); + config_set_default_string(activeConfiguration, "AdvOut", "Encoder", "obs_x264"); - config_set_default_string(activeConfiguration, "AdvOut", "RecType", - "Standard"); + config_set_default_string(activeConfiguration, "AdvOut", "RecType", "Standard"); - config_set_default_string(activeConfiguration, "AdvOut", "RecFilePath", - GetDefaultVideoSavePath().c_str()); - config_set_default_string(activeConfiguration, "AdvOut", "RecFormat2", - DEFAULT_CONTAINER); - config_set_default_bool(activeConfiguration, "AdvOut", "RecUseRescale", - false); - config_set_default_uint(activeConfiguration, "AdvOut", "RecTracks", - (1 << 0)); - config_set_default_string(activeConfiguration, "AdvOut", "RecEncoder", - "none"); + config_set_default_string(activeConfiguration, "AdvOut", "RecFilePath", GetDefaultVideoSavePath().c_str()); + config_set_default_string(activeConfiguration, "AdvOut", "RecFormat2", DEFAULT_CONTAINER); + config_set_default_bool(activeConfiguration, "AdvOut", "RecUseRescale", false); + config_set_default_uint(activeConfiguration, "AdvOut", "RecTracks", (1 << 0)); + config_set_default_string(activeConfiguration, "AdvOut", "RecEncoder", "none"); config_set_default_uint(activeConfiguration, "AdvOut", "FLVTrack", 1); - config_set_default_uint(activeConfiguration, "AdvOut", - "StreamMultiTrackAudioMixes", 1); - config_set_default_bool(activeConfiguration, "AdvOut", "FFOutputToFile", - true); - config_set_default_string(activeConfiguration, "AdvOut", "FFFilePath", - GetDefaultVideoSavePath().c_str()); - config_set_default_string(activeConfiguration, "AdvOut", "FFExtension", - "mp4"); - config_set_default_uint(activeConfiguration, "AdvOut", "FFVBitrate", - 2500); - config_set_default_uint(activeConfiguration, "AdvOut", "FFVGOPSize", - 250); - config_set_default_bool(activeConfiguration, "AdvOut", "FFUseRescale", - false); - config_set_default_bool(activeConfiguration, "AdvOut", "FFIgnoreCompat", - false); - config_set_default_uint(activeConfiguration, "AdvOut", "FFABitrate", - 160); - config_set_default_uint(activeConfiguration, "AdvOut", "FFAudioMixes", - 1); + config_set_default_uint(activeConfiguration, "AdvOut", "StreamMultiTrackAudioMixes", 1); + config_set_default_bool(activeConfiguration, "AdvOut", "FFOutputToFile", true); + config_set_default_string(activeConfiguration, "AdvOut", "FFFilePath", GetDefaultVideoSavePath().c_str()); + config_set_default_string(activeConfiguration, "AdvOut", "FFExtension", "mp4"); + config_set_default_uint(activeConfiguration, "AdvOut", "FFVBitrate", 2500); + config_set_default_uint(activeConfiguration, "AdvOut", "FFVGOPSize", 250); + config_set_default_bool(activeConfiguration, "AdvOut", "FFUseRescale", false); + config_set_default_bool(activeConfiguration, "AdvOut", "FFIgnoreCompat", false); + config_set_default_uint(activeConfiguration, "AdvOut", "FFABitrate", 160); + config_set_default_uint(activeConfiguration, "AdvOut", "FFAudioMixes", 1); - config_set_default_uint(activeConfiguration, "AdvOut", "Track1Bitrate", - 160); - config_set_default_uint(activeConfiguration, "AdvOut", "Track2Bitrate", - 160); - config_set_default_uint(activeConfiguration, "AdvOut", "Track3Bitrate", - 160); - config_set_default_uint(activeConfiguration, "AdvOut", "Track4Bitrate", - 160); - config_set_default_uint(activeConfiguration, "AdvOut", "Track5Bitrate", - 160); - config_set_default_uint(activeConfiguration, "AdvOut", "Track6Bitrate", - 160); + config_set_default_uint(activeConfiguration, "AdvOut", "Track1Bitrate", 160); + config_set_default_uint(activeConfiguration, "AdvOut", "Track2Bitrate", 160); + config_set_default_uint(activeConfiguration, "AdvOut", "Track3Bitrate", 160); + config_set_default_uint(activeConfiguration, "AdvOut", "Track4Bitrate", 160); + config_set_default_uint(activeConfiguration, "AdvOut", "Track5Bitrate", 160); + config_set_default_uint(activeConfiguration, "AdvOut", "Track6Bitrate", 160); - config_set_default_uint(activeConfiguration, "AdvOut", - "RecSplitFileTime", 15); - config_set_default_uint(activeConfiguration, "AdvOut", - "RecSplitFileSize", 2048); + config_set_default_uint(activeConfiguration, "AdvOut", "RecSplitFileTime", 15); + config_set_default_uint(activeConfiguration, "AdvOut", "RecSplitFileSize", 2048); config_set_default_bool(activeConfiguration, "AdvOut", "RecRB", false); config_set_default_uint(activeConfiguration, "AdvOut", "RecRBTime", 20); @@ -2013,30 +1783,20 @@ bool OBSBasic::InitBasicConfigDefaults() config_save_safe(activeConfiguration, "tmp", nullptr); } - config_set_default_string(activeConfiguration, "Output", - "FilenameFormatting", - "%CCYY-%MM-%DD %hh-%mm-%ss"); + config_set_default_string(activeConfiguration, "Output", "FilenameFormatting", "%CCYY-%MM-%DD %hh-%mm-%ss"); - config_set_default_bool(activeConfiguration, "Output", "DelayEnable", - false); + config_set_default_bool(activeConfiguration, "Output", "DelayEnable", false); config_set_default_uint(activeConfiguration, "Output", "DelaySec", 20); - config_set_default_bool(activeConfiguration, "Output", "DelayPreserve", - true); + config_set_default_bool(activeConfiguration, "Output", "DelayPreserve", true); - config_set_default_bool(activeConfiguration, "Output", "Reconnect", - true); + config_set_default_bool(activeConfiguration, "Output", "Reconnect", true); config_set_default_uint(activeConfiguration, "Output", "RetryDelay", 2); - config_set_default_uint(activeConfiguration, "Output", "MaxRetries", - 25); + config_set_default_uint(activeConfiguration, "Output", "MaxRetries", 25); - config_set_default_string(activeConfiguration, "Output", "BindIP", - "default"); - config_set_default_string(activeConfiguration, "Output", "IPFamily", - "IPv4+IPv6"); - config_set_default_bool(activeConfiguration, "Output", - "NewSocketLoopEnable", false); - config_set_default_bool(activeConfiguration, "Output", - "LowLatencyEnable", false); + config_set_default_string(activeConfiguration, "Output", "BindIP", "default"); + config_set_default_string(activeConfiguration, "Output", "IPFamily", "IPv4+IPv6"); + config_set_default_bool(activeConfiguration, "Output", "NewSocketLoopEnable", false); + config_set_default_bool(activeConfiguration, "Output", "LowLatencyEnable", false); int i = 0; uint32_t scale_cx = cx; @@ -2050,55 +1810,38 @@ bool OBSBasic::InitBasicConfigDefaults() scale_cy = uint32_t(double(cy) / scale); } - config_set_default_uint(activeConfiguration, "Video", "OutputCX", - scale_cx); - config_set_default_uint(activeConfiguration, "Video", "OutputCY", - scale_cy); + config_set_default_uint(activeConfiguration, "Video", "OutputCX", scale_cx); + config_set_default_uint(activeConfiguration, "Video", "OutputCY", scale_cy); /* don't allow OutputCX/OutputCY to be susceptible to defaults * changing */ if (!config_has_user_value(activeConfiguration, "Video", "OutputCX") || !config_has_user_value(activeConfiguration, "Video", "OutputCY")) { - config_set_uint(activeConfiguration, "Video", "OutputCX", - scale_cx); - config_set_uint(activeConfiguration, "Video", "OutputCY", - scale_cy); + config_set_uint(activeConfiguration, "Video", "OutputCX", scale_cx); + config_set_uint(activeConfiguration, "Video", "OutputCY", scale_cy); config_save_safe(activeConfiguration, "tmp", nullptr); } config_set_default_uint(activeConfiguration, "Video", "FPSType", 0); - config_set_default_string(activeConfiguration, "Video", "FPSCommon", - "30"); + config_set_default_string(activeConfiguration, "Video", "FPSCommon", "30"); config_set_default_uint(activeConfiguration, "Video", "FPSInt", 30); config_set_default_uint(activeConfiguration, "Video", "FPSNum", 30); config_set_default_uint(activeConfiguration, "Video", "FPSDen", 1); - config_set_default_string(activeConfiguration, "Video", "ScaleType", - "bicubic"); - config_set_default_string(activeConfiguration, "Video", "ColorFormat", - "NV12"); - config_set_default_string(activeConfiguration, "Video", "ColorSpace", - "709"); - config_set_default_string(activeConfiguration, "Video", "ColorRange", - "Partial"); - config_set_default_uint(activeConfiguration, "Video", "SdrWhiteLevel", - 300); - config_set_default_uint(activeConfiguration, "Video", - "HdrNominalPeakLevel", 1000); + config_set_default_string(activeConfiguration, "Video", "ScaleType", "bicubic"); + config_set_default_string(activeConfiguration, "Video", "ColorFormat", "NV12"); + config_set_default_string(activeConfiguration, "Video", "ColorSpace", "709"); + config_set_default_string(activeConfiguration, "Video", "ColorRange", "Partial"); + config_set_default_uint(activeConfiguration, "Video", "SdrWhiteLevel", 300); + config_set_default_uint(activeConfiguration, "Video", "HdrNominalPeakLevel", 1000); - config_set_default_string(activeConfiguration, "Audio", - "MonitoringDeviceId", "default"); - config_set_default_string( - activeConfiguration, "Audio", "MonitoringDeviceName", - Str("Basic.Settings.Advanced.Audio.MonitoringDevice" - ".Default")); - config_set_default_uint(activeConfiguration, "Audio", "SampleRate", - 48000); - config_set_default_string(activeConfiguration, "Audio", "ChannelSetup", - "Stereo"); - config_set_default_double(activeConfiguration, "Audio", - "MeterDecayRate", VOLUME_METER_DECAY_FAST); - config_set_default_uint(activeConfiguration, "Audio", "PeakMeterType", - 0); + config_set_default_string(activeConfiguration, "Audio", "MonitoringDeviceId", "default"); + config_set_default_string(activeConfiguration, "Audio", "MonitoringDeviceName", + Str("Basic.Settings.Advanced.Audio.MonitoringDevice" + ".Default")); + config_set_default_uint(activeConfiguration, "Audio", "SampleRate", 48000); + config_set_default_string(activeConfiguration, "Audio", "ChannelSetup", "Stereo"); + config_set_default_double(activeConfiguration, "Audio", "MeterDecayRate", VOLUME_METER_DECAY_FAST); + config_set_default_uint(activeConfiguration, "Audio", "PeakMeterType", 0); CheckExistingCookieId(); @@ -2109,16 +1852,13 @@ extern bool EncoderAvailable(const char *encoder); void OBSBasic::InitBasicConfigDefaults2() { - bool oldEncDefaults = config_get_bool(App()->GetUserConfig(), "General", - "Pre23Defaults"); + bool oldEncDefaults = config_get_bool(App()->GetUserConfig(), "General", "Pre23Defaults"); bool useNV = EncoderAvailable("ffmpeg_nvenc") && !oldEncDefaults; - config_set_default_string( - activeConfiguration, "SimpleOutput", "StreamEncoder", - useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264); - config_set_default_string( - activeConfiguration, "SimpleOutput", "RecEncoder", - useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264); + config_set_default_string(activeConfiguration, "SimpleOutput", "StreamEncoder", + useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264); + config_set_default_string(activeConfiguration, "SimpleOutput", "RecEncoder", + useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264); const char *aac_default = "ffmpeg_aac"; if (EncoderAvailable("CoreAudio_AAC")) @@ -2126,10 +1866,8 @@ void OBSBasic::InitBasicConfigDefaults2() else if (EncoderAvailable("libfdk_aac")) aac_default = "libfdk_aac"; - config_set_default_string(activeConfiguration, "AdvOut", "AudioEncoder", - aac_default); - config_set_default_string(activeConfiguration, "AdvOut", - "RecAudioEncoder", aac_default); + config_set_default_string(activeConfiguration, "AdvOut", "AudioEncoder", aac_default); + config_set_default_string(activeConfiguration, "AdvOut", "RecAudioEncoder", aac_default); } bool OBSBasic::InitBasicConfig() @@ -2138,21 +1876,18 @@ bool OBSBasic::InitBasicConfig() RefreshProfiles(true); - std::string currentProfileName{ - config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; + std::string currentProfileName{config_get_string(App()->GetUserConfig(), "Basic", "Profile")}; auto foundProfile = GetProfileByName(currentProfileName); if (!foundProfile) { - const OBSProfile &newProfile = - CreateProfile(currentProfileName); + const OBSProfile &newProfile = CreateProfile(currentProfileName); ActivateProfile(newProfile); } else { // TODO: Remove duplicate code from OBS initialization and just use ActivateProfile here instead - int code = activeConfiguration.Open( - foundProfile.value().profileFile.u8string().c_str(), - CONFIG_OPEN_ALWAYS); + int code = activeConfiguration.Open(foundProfile.value().profileFile.u8string().c_str(), + CONFIG_OPEN_ALWAYS); if (code != CONFIG_SUCCESS) { OBSErrorBox(NULL, "Failed to open basic.ini: %d", code); return false; @@ -2167,36 +1902,26 @@ void OBSBasic::InitOBSCallbacks() ProfileScope("OBSBasic::InitOBSCallbacks"); signalHandlers.reserve(signalHandlers.size() + 9); - signalHandlers.emplace_back(obs_get_signal_handler(), "source_create", - OBSBasic::SourceCreated, this); - signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove", - OBSBasic::SourceRemoved, this); - signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate", - OBSBasic::SourceActivated, this); - signalHandlers.emplace_back(obs_get_signal_handler(), - "source_deactivate", - OBSBasic::SourceDeactivated, this); - signalHandlers.emplace_back(obs_get_signal_handler(), - "source_audio_activate", - OBSBasic::SourceAudioActivated, this); - signalHandlers.emplace_back(obs_get_signal_handler(), - "source_audio_deactivate", + signalHandlers.emplace_back(obs_get_signal_handler(), "source_create", OBSBasic::SourceCreated, this); + signalHandlers.emplace_back(obs_get_signal_handler(), "source_remove", OBSBasic::SourceRemoved, this); + signalHandlers.emplace_back(obs_get_signal_handler(), "source_activate", OBSBasic::SourceActivated, this); + signalHandlers.emplace_back(obs_get_signal_handler(), "source_deactivate", OBSBasic::SourceDeactivated, this); + signalHandlers.emplace_back(obs_get_signal_handler(), "source_audio_activate", OBSBasic::SourceAudioActivated, + this); + signalHandlers.emplace_back(obs_get_signal_handler(), "source_audio_deactivate", OBSBasic::SourceAudioDeactivated, this); - signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename", - OBSBasic::SourceRenamed, this); + signalHandlers.emplace_back(obs_get_signal_handler(), "source_rename", OBSBasic::SourceRenamed, this); signalHandlers.emplace_back( obs_get_signal_handler(), "source_filter_add", [](void *data, calldata_t *) { - QMetaObject::invokeMethod(static_cast(data), - "UpdateEditMenu", + QMetaObject::invokeMethod(static_cast(data), "UpdateEditMenu", Qt::QueuedConnection); }, this); signalHandlers.emplace_back( obs_get_signal_handler(), "source_filter_remove", [](void *data, calldata_t *) { - QMetaObject::invokeMethod(static_cast(data), - "UpdateEditMenu", + QMetaObject::invokeMethod(static_cast(data), "UpdateEditMenu", Qt::QueuedConnection); }, this); @@ -2242,8 +1967,7 @@ void OBSBasic::InitPrimitives() } circle = gs_render_save(); - InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin, - &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine); + InitSafeAreas(&actionSafeMargin, &graphicsSafeMargin, &fourByThreeSafeMargin, &leftLine, &topLine, &rightLine); obs_leave_graphics(); } @@ -2259,23 +1983,19 @@ void OBSBasic::ResetOutputs() { ProfileScope("OBSBasic::ResetOutputs"); - const char *mode = - config_get_string(activeConfiguration, "Output", "Mode"); + const char *mode = config_get_string(activeConfiguration, "Output", "Mode"); bool advOut = astrcmpi(mode, "Advanced") == 0; if ((!outputHandler || !outputHandler->Active()) && (!setupStreamingGuard.valid() || - setupStreamingGuard.wait_for(std::chrono::seconds{0}) == - std::future_status::ready)) { + setupStreamingGuard.wait_for(std::chrono::seconds{0}) == std::future_status::ready)) { outputHandler.reset(); - outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this) - : CreateSimpleOutputHandler(this)); + outputHandler.reset(advOut ? CreateAdvancedOutputHandler(this) : CreateSimpleOutputHandler(this)); emit ReplayBufEnabled(outputHandler->replayBuffer); if (sysTrayReplayBuffer) - sysTrayReplayBuffer->setEnabled( - !!outputHandler->replayBuffer); + sysTrayReplayBuffer->setEnabled(!!outputHandler->replayBuffer); UpdateIsRecordingPausable(); } else { @@ -2283,10 +2003,8 @@ void OBSBasic::ResetOutputs() } } -#define STARTUP_SEPARATOR \ - "==== Startup complete ===============================================" -#define SHUTDOWN_SEPARATOR \ - "==== Shutting down ==================================================" +#define STARTUP_SEPARATOR "==== Startup complete ===============================================" +#define SHUTDOWN_SEPARATOR "==== Shutting down ==================================================" #define UNSUPPORTED_ERROR \ "Failed to initialize video:\n\nRequired graphics API functionality " \ @@ -2298,8 +2016,7 @@ void OBSBasic::ResetOutputs() static inline void LogEncoders() { - constexpr uint32_t hide_flags = OBS_ENCODER_CAP_DEPRECATED | - OBS_ENCODER_CAP_INTERNAL; + constexpr uint32_t hide_flags = OBS_ENCODER_CAP_DEPRECATED | OBS_ENCODER_CAP_INTERNAL; auto list_encoders = [](obs_encoder_type type) { size_t idx = 0; @@ -2311,8 +2028,7 @@ static inline void LogEncoders() continue; } - blog(LOG_INFO, "\t- %s (%s)", encoder_type, - obs_encoder_get_display_name(encoder_type)); + blog(LOG_INFO, "\t- %s (%s)", encoder_type, obs_encoder_get_display_name(encoder_type)); } }; @@ -2351,15 +2067,12 @@ void OBSBasic::OBSInit() /* load audio monitoring */ if (obs_audio_monitoring_available()) { - const char *device_name = config_get_string( - activeConfiguration, "Audio", "MonitoringDeviceName"); - const char *device_id = config_get_string( - activeConfiguration, "Audio", "MonitoringDeviceId"); + const char *device_name = config_get_string(activeConfiguration, "Audio", "MonitoringDeviceName"); + const char *device_id = config_get_string(activeConfiguration, "Audio", "MonitoringDeviceId"); obs_set_audio_monitoring_device(device_name, device_id); - blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s", - device_name, device_id); + blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s", device_name, device_id); } InitOBSCallbacks(); @@ -2401,8 +2114,7 @@ void OBSBasic::OBSInit() cef_js_avail = cef && obs_browser_qcef_version() >= 3; #endif - vcamEnabled = - (obs_get_output_flags(VIRTUAL_CAM_ID) & OBS_OUTPUT_VIDEO) != 0; + vcamEnabled = (obs_get_output_flags(VIRTUAL_CAM_ID) & OBS_OUTPUT_VIDEO) != 0; if (vcamEnabled) { emit VirtualCamEnabled(); } @@ -2423,42 +2135,33 @@ void OBSBasic::OBSInit() InitPrimitives(); - sceneDuplicationMode = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SceneDuplicationMode"); - swapScenesMode = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "SwapScenesMode"); - editPropertiesMode = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "EditPropertiesMode"); + sceneDuplicationMode = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SceneDuplicationMode"); + swapScenesMode = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SwapScenesMode"); + editPropertiesMode = config_get_bool(App()->GetUserConfig(), "BasicWindow", "EditPropertiesMode"); if (!opt_studio_mode) { - SetPreviewProgramMode(config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "PreviewProgramMode")); + SetPreviewProgramMode(config_get_bool(App()->GetUserConfig(), "BasicWindow", "PreviewProgramMode")); } else { SetPreviewProgramMode(true); opt_studio_mode = false; } -#define SET_VISIBILITY(name, control) \ - do { \ - if (config_has_user_value(App()->GetUserConfig(), \ - "BasicWindow", name)) { \ - bool visible = config_get_bool(App()->GetUserConfig(), \ - "BasicWindow", name); \ - ui->control->setChecked(visible); \ - } \ +#define SET_VISIBILITY(name, control) \ + do { \ + if (config_has_user_value(App()->GetUserConfig(), "BasicWindow", name)) { \ + bool visible = config_get_bool(App()->GetUserConfig(), "BasicWindow", name); \ + ui->control->setChecked(visible); \ + } \ } while (false) SET_VISIBILITY("ShowListboxToolbars", toggleListboxToolbars); SET_VISIBILITY("ShowStatusBar", toggleStatusBar); #undef SET_VISIBILITY - bool sourceIconsVisible = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "ShowSourceIcons"); + bool sourceIconsVisible = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ShowSourceIcons"); ui->toggleSourceIcons->setChecked(sourceIconsVisible); - bool contextVisible = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "ShowContextToolbars"); + bool contextVisible = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ShowContextToolbars"); ui->toggleContextBar->setChecked(contextVisible); ui->contextContainer->setVisible(contextVisible); if (contextVisible) @@ -2470,13 +2173,11 @@ void OBSBasic::OBSInit() disableSaving--; try { - const OBSSceneCollection ¤tCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection ¤tCollection = GetCurrentSceneCollection(); ActivateSceneCollection(currentCollection); } catch (const std::invalid_argument &) { const std::string collectionName = - config_get_string(App()->GetUserConfig(), - "Basic", "SceneCollection"); + config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection"); SetupNewSceneCollection(collectionName); } @@ -2486,23 +2187,18 @@ void OBSBasic::OBSInit() loaded = true; - previewEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "PreviewEnabled"); + previewEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "PreviewEnabled"); if (!previewEnabled && !IsPreviewProgramMode()) - QMetaObject::invokeMethod(this, "EnablePreviewDisplay", - Qt::QueuedConnection, + QMetaObject::invokeMethod(this, "EnablePreviewDisplay", Qt::QueuedConnection, Q_ARG(bool, previewEnabled)); else if (!previewEnabled && IsPreviewProgramMode()) - QMetaObject::invokeMethod(this, "EnablePreviewDisplay", - Qt::QueuedConnection, - Q_ARG(bool, true)); + QMetaObject::invokeMethod(this, "EnablePreviewDisplay", Qt::QueuedConnection, Q_ARG(bool, true)); disableSaving--; auto addDisplay = [this](OBSQTDisplay *window) { - obs_display_add_draw_callback(window->GetDisplay(), - OBSBasic::RenderMain, this); + obs_display_add_draw_callback(window->GetDisplay(), OBSBasic::RenderMain, this); struct obs_video_info ovi; if (obs_get_video_info(&ovi)) @@ -2513,12 +2209,9 @@ void OBSBasic::OBSInit() /* Show the main window, unless the tray icon isn't available * or neither the setting nor flag for starting minimized is set. */ - bool sysTrayEnabled = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "SysTrayEnabled"); - bool sysTrayWhenStarted = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); - bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() && - sysTrayEnabled && + bool sysTrayEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled"); + bool sysTrayWhenStarted = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); + bool hideWindowOnStart = QSystemTrayIcon::isSystemTrayAvailable() && sysTrayEnabled && (opt_minimize_tray || sysTrayWhenStarted); #ifdef _WIN32 @@ -2528,8 +2221,7 @@ void OBSBasic::OBSInit() show(); #endif - bool alwaysOnTop = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "AlwaysOnTop"); + bool alwaysOnTop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "AlwaysOnTop"); #ifdef ENABLE_WAYLAND bool isWayland = obs_get_nix_platform() == OBS_NIX_PLATFORM_WAYLAND; @@ -2542,8 +2234,7 @@ void OBSBasic::OBSInit() ui->actionAlwaysOnTop->setChecked(true); } else if (isWayland) { if (opt_always_on_top) - blog(LOG_INFO, - "Always On Top not available on Wayland, ignoring."); + blog(LOG_INFO, "Always On Top not available on Wayland, ignoring."); ui->actionAlwaysOnTop->setEnabled(false); ui->actionAlwaysOnTop->setVisible(false); } @@ -2568,12 +2259,9 @@ void OBSBasic::OBSInit() QAction *action = new QAction(QTStr("Basic.MainMenu.Docks." "CustomBrowserDocks"), this); - ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(), - action); - connect(action, &QAction::triggered, this, - &OBSBasic::ManageExtraBrowserDocks); - ui->menuDocks->insertSeparator( - ui->scenesDock->toggleViewAction()); + ui->menuDocks->insertAction(ui->scenesDock->toggleViewAction(), action); + connect(action, &QAction::triggered, this, &OBSBasic::ManageExtraBrowserDocks); + ui->menuDocks->insertSeparator(ui->scenesDock->toggleViewAction()); LoadExtraBrowserDocks(); } @@ -2585,42 +2273,33 @@ void OBSBasic::OBSInit() NewYouTubeAppDock(); #endif - const char *dockStateStr = config_get_string( - App()->GetUserConfig(), "BasicWindow", "DockState"); + const char *dockStateStr = config_get_string(App()->GetUserConfig(), "BasicWindow", "DockState"); if (!dockStateStr) { on_resetDocks_triggered(true); } else { - QByteArray dockState = - QByteArray::fromBase64(QByteArray(dockStateStr)); + QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); if (!restoreState(dockState)) on_resetDocks_triggered(true); } - bool pre23Defaults = config_get_bool(App()->GetUserConfig(), "General", - "Pre23Defaults"); + bool pre23Defaults = config_get_bool(App()->GetUserConfig(), "General", "Pre23Defaults"); if (pre23Defaults) { - bool resetDockLock23 = config_get_bool( - App()->GetUserConfig(), "General", "ResetDockLock23"); + bool resetDockLock23 = config_get_bool(App()->GetUserConfig(), "General", "ResetDockLock23"); if (!resetDockLock23) { - config_set_bool(App()->GetUserConfig(), "General", - "ResetDockLock23", true); - config_remove_value(App()->GetUserConfig(), - "BasicWindow", "DocksLocked"); - config_save_safe(App()->GetUserConfig(), "tmp", - nullptr); + config_set_bool(App()->GetUserConfig(), "General", "ResetDockLock23", true); + config_remove_value(App()->GetUserConfig(), "BasicWindow", "DocksLocked"); + config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } } - bool docksLocked = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "DocksLocked"); + bool docksLocked = config_get_bool(App()->GetUserConfig(), "BasicWindow", "DocksLocked"); on_lockDocks_toggled(docksLocked); ui->lockDocks->blockSignals(true); ui->lockDocks->setChecked(docksLocked); ui->lockDocks->blockSignals(false); - bool sideDocks = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "SideDocks"); + bool sideDocks = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SideDocks"); on_sideDocks_toggled(sideDocks); ui->sideDocks->blockSignals(true); ui->sideDocks->setChecked(sideDocks); @@ -2634,40 +2313,30 @@ void OBSBasic::OBSInit() disableColorSpaceConversion(this); #endif - bool has_last_version = config_has_user_value(App()->GetUserConfig(), - "General", "LastVersion"); - bool first_run = - config_get_bool(App()->GetUserConfig(), "General", "FirstRun"); + bool has_last_version = config_has_user_value(App()->GetUserConfig(), "General", "LastVersion"); + bool first_run = config_get_bool(App()->GetUserConfig(), "General", "FirstRun"); if (!first_run) { - config_set_bool(App()->GetUserConfig(), "General", "FirstRun", - true); + config_set_bool(App()->GetUserConfig(), "General", "FirstRun", true); config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } if (!first_run && !has_last_version && !Active()) - QMetaObject::invokeMethod(this, "on_autoConfigure_triggered", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "on_autoConfigure_triggered", Qt::QueuedConnection); -#if (defined(_WIN32) || defined(__APPLE__)) && \ - (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0) +#if (defined(_WIN32) || defined(__APPLE__)) && (OBS_RELEASE_CANDIDATE > 0 || OBS_BETA > 0) /* Automatically set branch to "beta" the first time a pre-release build is run. */ - if (!config_get_bool(App()->GetUserConfig(), "General", - "AutoBetaOptIn")) { - config_set_string(App()->GetUserConfig(), "General", - "UpdateBranch", "beta"); - config_set_bool(App()->GetUserConfig(), "General", - "AutoBetaOptIn", true); + if (!config_get_bool(App()->GetUserConfig(), "General", "AutoBetaOptIn")) { + config_set_string(App()->GetUserConfig(), "General", "UpdateBranch", "beta"); + config_set_bool(App()->GetUserConfig(), "General", "AutoBetaOptIn", true); config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } #endif TimedCheckForUpdates(); - ToggleMixerLayout(config_get_bool(App()->GetUserConfig(), "BasicWindow", - "VerticalVolControl")); + ToggleMixerLayout(config_get_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); - if (config_get_bool(activeConfiguration, "General", - "OpenStatsOnStartup")) + if (config_get_bool(activeConfiguration, "General", "OpenStatsOnStartup")) on_stats_triggered(); OBSBasicStats::InitializeValues(); @@ -2677,10 +2346,8 @@ void OBSBasic::OBSInit() ui->viewMenu->addSeparator(); - AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this, - &OBSBasic::OpenMultiviewProjector); - connect(ui->viewMenu->menuAction(), &QAction::hovered, this, - &OBSBasic::UpdateMultiviewProjectorMenu); + AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this, &OBSBasic::OpenMultiviewProjector); + connect(ui->viewMenu->menuAction(), &QAction::hovered, this, &OBSBasic::UpdateMultiviewProjectorMenu); ui->sources->UpdateIcons(); @@ -2724,8 +2391,7 @@ void OBSBasic::OBSInit() #endif if (safe_mode) { - ui->actionRestartSafe->setText( - QTStr("Basic.MainMenu.Help.RestartNormal")); + ui->actionRestartSafe->setText(QTStr("Basic.MainMenu.Help.RestartNormal")); } UpdatePreviewProgramIndicators(); @@ -2747,10 +2413,8 @@ void OBSBasic::OBSInit() plugin++; } - QString failed_msg = - QTStr("PluginsFailedToLoad.Text").arg(failed_plugins); - OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"), - failed_msg); + QString failed_msg = QTStr("PluginsFailedToLoad.Text").arg(failed_plugins); + OBSMessageBox::warning(this, QTStr("PluginsFailedToLoad.Title"), failed_msg); } } @@ -2762,8 +2426,7 @@ void OBSBasic::OnFirstLoad() /* Attempt to load init screen if available */ if (cef) { WhatsNewInfoThread *wnit = new WhatsNewInfoThread(); - connect(wnit, &WhatsNewInfoThread::Result, this, - &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection); + connect(wnit, &WhatsNewInfoThread::Result, this, &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection); introCheckThread.reset(wnit); introCheckThread->start(); @@ -2772,8 +2435,7 @@ void OBSBasic::OnFirstLoad() Auth::Load(); - bool showLogViewerOnStartup = config_get_bool( - App()->GetUserConfig(), "LogViewer", "ShowLogStartup"); + bool showLogViewerOnStartup = config_get_bool(App()->GetUserConfig(), "LogViewer", "ShowLogStartup"); if (showLogViewerOnStartup) on_actionViewCurrentLog_triggered(); @@ -2818,8 +2480,7 @@ void OBSBasic::ReceivedIntroJson(const QString &text) int minor = 0; sscanf(item.version.c_str(), "%d.%d", &major, &minor); - if (major == LIBOBS_API_MAJOR_VER && - minor == LIBOBS_API_MINOR_VER && + if (major == LIBOBS_API_MAJOR_VER && minor == LIBOBS_API_MINOR_VER && item.RC == OBS_RELEASE_CANDIDATE && item.Beta == OBS_BETA) { info_url = item.url; info_increment = item.increment; @@ -2838,39 +2499,30 @@ void OBSBasic::ReceivedIntroJson(const QString &text) #else constexpr const char *lastInfoVersion = "InfoLastVersion"; #endif - constexpr uint64_t currentVersion = (uint64_t)LIBOBS_API_VER << 16ULL | - OBS_RELEASE_CANDIDATE << 8ULL | + constexpr uint64_t currentVersion = (uint64_t)LIBOBS_API_VER << 16ULL | OBS_RELEASE_CANDIDATE << 8ULL | OBS_BETA; - uint64_t lastVersion = config_get_uint(App()->GetAppConfig(), "General", - lastInfoVersion); + uint64_t lastVersion = config_get_uint(App()->GetAppConfig(), "General", lastInfoVersion); int current_version_increment = -1; - if ((lastVersion & ~0xFFFF0000ULL) < - (currentVersion & ~0xFFFF0000ULL)) { - config_set_int(App()->GetAppConfig(), "General", - "InfoIncrement", -1); - config_set_uint(App()->GetAppConfig(), "General", - lastInfoVersion, currentVersion); + if ((lastVersion & ~0xFFFF0000ULL) < (currentVersion & ~0xFFFF0000ULL)) { + config_set_int(App()->GetAppConfig(), "General", "InfoIncrement", -1); + config_set_uint(App()->GetAppConfig(), "General", lastInfoVersion, currentVersion); } else { - current_version_increment = config_get_int( - App()->GetAppConfig(), "General", "InfoIncrement"); + current_version_increment = config_get_int(App()->GetAppConfig(), "General", "InfoIncrement"); } if (info_increment <= current_version_increment) { return; } - config_set_int(App()->GetAppConfig(), "General", "InfoIncrement", - info_increment); + config_set_int(App()->GetAppConfig(), "General", "InfoIncrement", info_increment); config_save_safe(App()->GetAppConfig(), "tmp", nullptr); cef->init_browser(); - WhatsNewBrowserInitThread *wnbit = - new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str())); + WhatsNewBrowserInitThread *wnbit = new WhatsNewBrowserInitThread(QT_UTF8(info_url.c_str())); - connect(wnbit, &WhatsNewBrowserInitThread::Result, this, - &OBSBasic::ShowWhatsNew, Qt::QueuedConnection); + connect(wnbit, &WhatsNewBrowserInitThread::Result, this, &OBSBasic::ShowWhatsNew, Qt::QueuedConnection); whatsNewInitThread.reset(wnbit); whatsNewInitThread->start(); @@ -2902,8 +2554,7 @@ void OBSBasic::ShowWhatsNew(const QString &url) return; } - connect(cefWidget, &QCefWidget::titleChanged, dlg, - &QDialog::setWindowTitle); + connect(cefWidget, &QCefWidget::titleChanged, dlg, &QDialog::setWindowTitle); QPushButton *close = new QPushButton(QTStr("Close")); connect(close, &QAbstractButton::clicked, dlg, &QDialog::accept); @@ -2926,8 +2577,7 @@ void OBSBasic::ShowWhatsNew(const QString &url) void OBSBasic::UpdateMultiviewProjectorMenu() { ui->multiviewProjectorMenu->clear(); - AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this, - &OBSBasic::OpenMultiviewProjector); + AddProjectorMenuMonitors(ui->multiviewProjectorMenu, this, &OBSBasic::OpenMultiviewProjector); } void OBSBasic::InitHotkeys() @@ -2976,12 +2626,10 @@ void OBSBasic::InitHotkeys() t.escape = Str("Hotkeys.Escape"); obs_hotkeys_set_translations(&t); - obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"), - Str("Push-to-mute"), + obs_hotkeys_set_audio_hotkeys_translations(Str("Mute"), Str("Unmute"), Str("Push-to-mute"), Str("Push-to-talk")); - obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"), - Str("SceneItemHide")); + obs_hotkeys_set_sceneitem_hotkeys_translations(Str("SceneItemShow"), Str("SceneItemHide")); obs_hotkey_enable_callback_rerouting(true); obs_hotkey_set_callback_routing_func(OBSBasic::HotkeyTriggered, this); @@ -2995,9 +2643,7 @@ void OBSBasic::ProcessHotkey(obs_hotkey_id id, bool pressed) void OBSBasic::HotkeyTriggered(void *data, obs_hotkey_id id, bool pressed) { OBSBasic &basic = *static_cast(data); - QMetaObject::invokeMethod(&basic, "ProcessHotkey", - Q_ARG(obs_hotkey_id, id), - Q_ARG(bool, pressed)); + QMetaObject::invokeMethod(&basic, "ProcessHotkey", Q_ARG(obs_hotkey_id, id), Q_ARG(bool, pressed)); } void OBSBasic::CreateHotkeys() @@ -3005,8 +2651,7 @@ void OBSBasic::CreateHotkeys() ProfileScope("OBSBasic::CreateHotkeys"); auto LoadHotkeyData = [&](const char *name) -> OBSData { - const char *info = - config_get_string(activeConfiguration, "Hotkeys", name); + const char *info = config_get_string(activeConfiguration, "Hotkeys", name); if (!info) return {}; @@ -3018,32 +2663,24 @@ void OBSBasic::CreateHotkeys() }; auto LoadHotkey = [&](obs_hotkey_id id, const char *name) { - OBSDataArrayAutoRelease array = - obs_data_get_array(LoadHotkeyData(name), "bindings"); + OBSDataArrayAutoRelease array = obs_data_get_array(LoadHotkeyData(name), "bindings"); obs_hotkey_load(id, array); }; - auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0, - const char *name1, + auto LoadHotkeyPair = [&](obs_hotkey_pair_id id, const char *name0, const char *name1, const char *oldName = NULL) { if (oldName) { - const auto info = config_get_string(activeConfiguration, - "Hotkeys", oldName); + const auto info = config_get_string(activeConfiguration, "Hotkeys", oldName); if (info) { - config_set_string(activeConfiguration, - "Hotkeys", name0, info); - config_set_string(activeConfiguration, - "Hotkeys", name1, info); - config_remove_value(activeConfiguration, - "Hotkeys", oldName); + config_set_string(activeConfiguration, "Hotkeys", name0, info); + config_set_string(activeConfiguration, "Hotkeys", name1, info); + config_remove_value(activeConfiguration, "Hotkeys", oldName); activeConfiguration.Save(); } } - OBSDataArrayAutoRelease array0 = - obs_data_get_array(LoadHotkeyData(name0), "bindings"); - OBSDataArrayAutoRelease array1 = - obs_data_get_array(LoadHotkeyData(name1), "bindings"); + OBSDataArrayAutoRelease array0 = obs_data_get_array(LoadHotkeyData(name0), "bindings"); + OBSDataArrayAutoRelease array1 = obs_data_get_array(LoadHotkeyData(name1), "bindings"); obs_hotkey_pair_load(id, array0, array1); }; @@ -3060,17 +2697,14 @@ void OBSBasic::CreateHotkeys() } streamingHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"), - "OBSBasic.StopStreaming", Str("Basic.Main.StopStreaming"), - MAKE_CALLBACK(!basic.outputHandler->StreamingActive() && - !basic.streamingStarting, - basic.StartStreaming, "Starting stream"), - MAKE_CALLBACK(basic.outputHandler->StreamingActive() && - !basic.streamingStarting, - basic.StopStreaming, "Stopping stream"), + "OBSBasic.StartStreaming", Str("Basic.Main.StartStreaming"), "OBSBasic.StopStreaming", + Str("Basic.Main.StopStreaming"), + MAKE_CALLBACK(!basic.outputHandler->StreamingActive() && !basic.streamingStarting, basic.StartStreaming, + "Starting stream"), + MAKE_CALLBACK(basic.outputHandler->StreamingActive() && !basic.streamingStarting, basic.StopStreaming, + "Stopping stream"), this, this); - LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming", - "OBSBasic.StopStreaming"); + LoadHotkeyPair(streamingHotkeys, "OBSBasic.StartStreaming", "OBSBasic.StopStreaming"); auto cb = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { OBSBasic &basic = *static_cast(data); @@ -3079,36 +2713,29 @@ void OBSBasic::CreateHotkeys() } }; - forceStreamingStopHotkey = obs_hotkey_register_frontend( - "OBSBasic.ForceStopStreaming", - Str("Basic.Main.ForceStopStreaming"), cb, this); + forceStreamingStopHotkey = obs_hotkey_register_frontend("OBSBasic.ForceStopStreaming", + Str("Basic.Main.ForceStopStreaming"), cb, this); LoadHotkey(forceStreamingStopHotkey, "OBSBasic.ForceStopStreaming"); recordingHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"), - "OBSBasic.StopRecording", Str("Basic.Main.StopRecording"), - MAKE_CALLBACK(!basic.outputHandler->RecordingActive() && - !basic.recordingStarted, - basic.StartRecording, "Starting recording"), - MAKE_CALLBACK(basic.outputHandler->RecordingActive() && - basic.recordingStarted, - basic.StopRecording, "Stopping recording"), + "OBSBasic.StartRecording", Str("Basic.Main.StartRecording"), "OBSBasic.StopRecording", + Str("Basic.Main.StopRecording"), + MAKE_CALLBACK(!basic.outputHandler->RecordingActive() && !basic.recordingStarted, basic.StartRecording, + "Starting recording"), + MAKE_CALLBACK(basic.outputHandler->RecordingActive() && basic.recordingStarted, basic.StopRecording, + "Stopping recording"), this, this); - LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording", - "OBSBasic.StopRecording"); + LoadHotkeyPair(recordingHotkeys, "OBSBasic.StartRecording", "OBSBasic.StopRecording"); - pauseHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"), - "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"), - MAKE_CALLBACK(basic.isRecordingPausable && - !basic.recordingPaused, - basic.PauseRecording, "Pausing recording"), - MAKE_CALLBACK(basic.isRecordingPausable && - basic.recordingPaused, - basic.UnpauseRecording, "Unpausing recording"), - this, this); - LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording", - "OBSBasic.UnpauseRecording"); + pauseHotkeys = + obs_hotkey_pair_register_frontend("OBSBasic.PauseRecording", Str("Basic.Main.PauseRecording"), + "OBSBasic.UnpauseRecording", Str("Basic.Main.UnpauseRecording"), + MAKE_CALLBACK(basic.isRecordingPausable && !basic.recordingPaused, + basic.PauseRecording, "Pausing recording"), + MAKE_CALLBACK(basic.isRecordingPausable && basic.recordingPaused, + basic.UnpauseRecording, "Unpausing recording"), + this, this); + LoadHotkeyPair(pauseHotkeys, "OBSBasic.PauseRecording", "OBSBasic.UnpauseRecording"); splitFileHotkey = obs_hotkey_register_frontend( "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"), @@ -3128,125 +2755,88 @@ void OBSBasic::CreateHotkeys() this); LoadHotkey(addChapterHotkey, "OBSBasic.AddChapterMarker"); - replayBufHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.StartReplayBuffer", - Str("Basic.Main.StartReplayBuffer"), - "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"), - MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(), - basic.StartReplayBuffer, - "Starting replay buffer"), - MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(), - basic.StopReplayBuffer, "Stopping replay buffer"), - this, this); - LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer", - "OBSBasic.StopReplayBuffer"); + replayBufHotkeys = + obs_hotkey_pair_register_frontend("OBSBasic.StartReplayBuffer", Str("Basic.Main.StartReplayBuffer"), + "OBSBasic.StopReplayBuffer", Str("Basic.Main.StopReplayBuffer"), + MAKE_CALLBACK(!basic.outputHandler->ReplayBufferActive(), + basic.StartReplayBuffer, "Starting replay buffer"), + MAKE_CALLBACK(basic.outputHandler->ReplayBufferActive(), + basic.StopReplayBuffer, "Stopping replay buffer"), + this, this); + LoadHotkeyPair(replayBufHotkeys, "OBSBasic.StartReplayBuffer", "OBSBasic.StopReplayBuffer"); if (vcamEnabled) { vcamHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.StartVirtualCam", - Str("Basic.Main.StartVirtualCam"), - "OBSBasic.StopVirtualCam", + "OBSBasic.StartVirtualCam", Str("Basic.Main.StartVirtualCam"), "OBSBasic.StopVirtualCam", Str("Basic.Main.StopVirtualCam"), - MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(), - basic.StartVirtualCam, + MAKE_CALLBACK(!basic.outputHandler->VirtualCamActive(), basic.StartVirtualCam, "Starting virtual camera"), - MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(), - basic.StopVirtualCam, + MAKE_CALLBACK(basic.outputHandler->VirtualCamActive(), basic.StopVirtualCam, "Stopping virtual camera"), this, this); - LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam", - "OBSBasic.StopVirtualCam"); + LoadHotkeyPair(vcamHotkeys, "OBSBasic.StartVirtualCam", "OBSBasic.StopVirtualCam"); } togglePreviewHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.EnablePreview", - Str("Basic.Main.PreviewConextMenu.Enable"), - "OBSBasic.DisablePreview", Str("Basic.Main.Preview.Disable"), - MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview, - "Enabling preview"), - MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview, - "Disabling preview"), - this, this); - LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview", - "OBSBasic.DisablePreview"); + "OBSBasic.EnablePreview", Str("Basic.Main.PreviewConextMenu.Enable"), "OBSBasic.DisablePreview", + Str("Basic.Main.Preview.Disable"), + MAKE_CALLBACK(!basic.previewEnabled, basic.EnablePreview, "Enabling preview"), + MAKE_CALLBACK(basic.previewEnabled, basic.DisablePreview, "Disabling preview"), this, this); + LoadHotkeyPair(togglePreviewHotkeys, "OBSBasic.EnablePreview", "OBSBasic.DisablePreview"); togglePreviewProgramHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.EnablePreviewProgram", - Str("Basic.EnablePreviewProgramMode"), - "OBSBasic.DisablePreviewProgram", - Str("Basic.DisablePreviewProgramMode"), - MAKE_CALLBACK(!basic.IsPreviewProgramMode(), - basic.EnablePreviewProgram, - "Enabling preview program"), - MAKE_CALLBACK(basic.IsPreviewProgramMode(), - basic.DisablePreviewProgram, - "Disabling preview program"), + "OBSBasic.EnablePreviewProgram", Str("Basic.EnablePreviewProgramMode"), + "OBSBasic.DisablePreviewProgram", Str("Basic.DisablePreviewProgramMode"), + MAKE_CALLBACK(!basic.IsPreviewProgramMode(), basic.EnablePreviewProgram, "Enabling preview program"), + MAKE_CALLBACK(basic.IsPreviewProgramMode(), basic.DisablePreviewProgram, "Disabling preview program"), this, this); - LoadHotkeyPair(togglePreviewProgramHotkeys, - "OBSBasic.EnablePreviewProgram", - "OBSBasic.DisablePreviewProgram", + LoadHotkeyPair(togglePreviewProgramHotkeys, "OBSBasic.EnablePreviewProgram", "OBSBasic.DisablePreviewProgram", "OBSBasic.TogglePreviewProgram"); contextBarHotkeys = obs_hotkey_pair_register_frontend( - "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"), - "OBSBasic.HideContextBar", Str("Basic.Main.HideContextBar"), - MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(), - basic.ShowContextBar, "Showing Context Bar"), - MAKE_CALLBACK(basic.ui->contextContainer->isVisible(), - basic.HideContextBar, "Hiding Context Bar"), + "OBSBasic.ShowContextBar", Str("Basic.Main.ShowContextBar"), "OBSBasic.HideContextBar", + Str("Basic.Main.HideContextBar"), + MAKE_CALLBACK(!basic.ui->contextContainer->isVisible(), basic.ShowContextBar, "Showing Context Bar"), + MAKE_CALLBACK(basic.ui->contextContainer->isVisible(), basic.HideContextBar, "Hiding Context Bar"), this, this); - LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar", - "OBSBasic.HideContextBar"); + LoadHotkeyPair(contextBarHotkeys, "OBSBasic.ShowContextBar", "OBSBasic.HideContextBar"); #undef MAKE_CALLBACK - auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *, - bool pressed) { + auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { if (pressed) - QMetaObject::invokeMethod(static_cast(data), - "TransitionClicked", + QMetaObject::invokeMethod(static_cast(data), "TransitionClicked", Qt::QueuedConnection); }; - transitionHotkey = obs_hotkey_register_frontend( - "OBSBasic.Transition", Str("Transition"), transition, this); + transitionHotkey = obs_hotkey_register_frontend("OBSBasic.Transition", Str("Transition"), transition, this); LoadHotkey(transitionHotkey, "OBSBasic.Transition"); - auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *, - bool pressed) { + auto resetStats = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { if (pressed) - QMetaObject::invokeMethod(static_cast(data), - "ResetStatsHotkey", + QMetaObject::invokeMethod(static_cast(data), "ResetStatsHotkey", Qt::QueuedConnection); }; - statsHotkey = obs_hotkey_register_frontend( - "OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"), - resetStats, this); + statsHotkey = + obs_hotkey_register_frontend("OBSBasic.ResetStats", Str("Basic.Stats.ResetStats"), resetStats, this); LoadHotkey(statsHotkey, "OBSBasic.ResetStats"); - auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *, - bool pressed) { + auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { if (pressed) - QMetaObject::invokeMethod(static_cast(data), - "Screenshot", - Qt::QueuedConnection); + QMetaObject::invokeMethod(static_cast(data), "Screenshot", Qt::QueuedConnection); }; - screenshotHotkey = obs_hotkey_register_frontend( - "OBSBasic.Screenshot", Str("Screenshot"), screenshot, this); + screenshotHotkey = obs_hotkey_register_frontend("OBSBasic.Screenshot", Str("Screenshot"), screenshot, this); LoadHotkey(screenshotHotkey, "OBSBasic.Screenshot"); - auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *, - bool pressed) { + auto screenshotSource = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { if (pressed) - QMetaObject::invokeMethod(static_cast(data), - "ScreenshotSelectedSource", + QMetaObject::invokeMethod(static_cast(data), "ScreenshotSelectedSource", Qt::QueuedConnection); }; - sourceScreenshotHotkey = obs_hotkey_register_frontend( - "OBSBasic.SelectedSourceScreenshot", - Str("Screenshot.SourceHotkey"), screenshotSource, this); + sourceScreenshotHotkey = obs_hotkey_register_frontend("OBSBasic.SelectedSourceScreenshot", + Str("Screenshot.SourceHotkey"), screenshotSource, this); LoadHotkey(sourceScreenshotHotkey, "OBSBasic.SelectedSourceScreenshot"); } @@ -3323,8 +2913,7 @@ OBSBasic::~OBSBasic() delete about; delete remux; - obs_display_remove_draw_callback(ui->preview->GetDisplay(), - OBSBasic::RenderMain, this); + obs_display_remove_draw_callback(ui->preview->GetDisplay(), OBSBasic::RenderMain, this); obs_enter_graphics(); gs_vertexbuffer_destroy(box); @@ -3350,26 +2939,17 @@ OBSBasic::~OBSBasic() * expect or want it to. */ QApplication::sendPostedEvents(nullptr); - config_set_int(App()->GetAppConfig(), "General", "LastVersion", - LIBOBS_API_VER); + config_set_int(App()->GetAppConfig(), "General", "LastVersion", LIBOBS_API_VER); config_save_safe(App()->GetAppConfig(), "tmp", nullptr); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "PreviewEnabled", - previewEnabled); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "AlwaysOnTop", - ui->actionAlwaysOnTop->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SceneDuplicationMode", sceneDuplicationMode); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "SwapScenesMode", - swapScenesMode); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "EditPropertiesMode", editPropertiesMode); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "PreviewProgramMode", IsPreviewProgramMode()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "DocksLocked", - ui->lockDocks->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "SideDocks", - ui->sideDocks->isChecked()); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "PreviewEnabled", previewEnabled); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "AlwaysOnTop", ui->actionAlwaysOnTop->isChecked()); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SceneDuplicationMode", sceneDuplicationMode); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SwapScenesMode", swapScenesMode); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "EditPropertiesMode", editPropertiesMode); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "PreviewProgramMode", IsPreviewProgramMode()); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "DocksLocked", ui->lockDocks->isChecked()); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SideDocks", ui->sideDocks->isChecked()); config_save_safe(App()->GetUserConfig(), "tmp", nullptr); #ifdef BROWSER_AVAILABLE @@ -3394,8 +2974,7 @@ void OBSBasic::SaveProject() return; projectChanged = true; - QMetaObject::invokeMethod(this, "SaveProjectDeferred", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "SaveProjectDeferred", Qt::QueuedConnection); } void OBSBasic::SaveProjectDeferred() @@ -3409,8 +2988,7 @@ void OBSBasic::SaveProjectDeferred() projectChanged = false; try { - const OBSSceneCollection ¤tCollection = - GetCurrentSceneCollection(); + const OBSSceneCollection ¤tCollection = GetCurrentSceneCollection(); Save(currentCollection.collectionFile.u8string().c_str()); } catch (const std::invalid_argument &error) { @@ -3454,9 +3032,7 @@ void OBSBasic::UpdatePreviewScalingMenu() ui->actionScaleWindow->setChecked(false); ui->actionScaleCanvas->setChecked(scalingAmount == 1.0f); - ui->actionScaleOutput->setChecked(scalingAmount == - float(ovi.output_width) / - float(ovi.base_width)); + ui->actionScaleOutput->setChecked(scalingAmount == float(ovi.output_width) / float(ovi.base_width)); } void OBSBasic::CreateInteractionWindow(obs_source_t *source) @@ -3513,16 +3089,12 @@ void OBSBasic::AddScene(OBSSource source) ui->scenes->insertItem(ui->scenes->currentRow() + 1, item); obs_hotkey_register_source( - source, "OBSBasic.SelectScene", - Str("Basic.Hotkeys.SelectScene"), + source, "OBSBasic.SelectScene", Str("Basic.Hotkeys.SelectScene"), [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { - OBSBasic *main = reinterpret_cast( - App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); - auto potential_source = - static_cast(data); - OBSSourceAutoRelease source = - obs_source_get_ref(potential_source); + auto potential_source = static_cast(data); + OBSSourceAutoRelease source = obs_source_get_ref(potential_source); if (source && pressed) main->SetCurrentScene(source.Get()); }, @@ -3533,16 +3105,12 @@ void OBSBasic::AddScene(OBSSource source) SignalContainer container; container.ref = scene; container.handlers.assign({ - std::make_shared(handler, "item_add", - OBSBasic::SceneItemAdded, this), - std::make_shared(handler, "reorder", - OBSBasic::SceneReordered, this), - std::make_shared(handler, "refresh", - OBSBasic::SceneRefreshed, this), + std::make_shared(handler, "item_add", OBSBasic::SceneItemAdded, this), + std::make_shared(handler, "reorder", OBSBasic::SceneReordered, this), + std::make_shared(handler, "refresh", OBSBasic::SceneRefreshed, this), }); - item->setData(static_cast(QtDataRole::OBSSignals), - QVariant::fromValue(container)); + item->setData(static_cast(QtDataRole::OBSSignals), QVariant::fromValue(container)); /* if the scene already has items (a duplicated scene) add them */ auto addSceneItem = [this](obs_sceneitem_t *item) { @@ -3565,8 +3133,7 @@ void OBSBasic::AddScene(OBSSource source) if (!disableSaving) { obs_source_t *source = obs_scene_get_source(scene); - blog(LOG_INFO, "User added scene '%s'", - obs_source_get_name(source)); + blog(LOG_INFO, "User added scene '%s'", obs_source_get_name(source)); OBSProjector::UpdateMultiviewProjectors(); } @@ -3600,8 +3167,7 @@ void OBSBasic::RemoveScene(OBSSource source) SaveProject(); if (!disableSaving) { - blog(LOG_INFO, "User Removed scene '%s'", - obs_source_get_name(source)); + blog(LOG_INFO, "User Removed scene '%s'", obs_source_get_name(source)); OBSProjector::UpdateMultiviewProjectors(); } @@ -3609,11 +3175,9 @@ void OBSBasic::RemoveScene(OBSSource source) OnEvent(OBS_FRONTEND_EVENT_SCENE_LIST_CHANGED); } -static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { - obs_sceneitem_t *selectedItem = - reinterpret_cast(param); + obs_sceneitem_t *selectedItem = reinterpret_cast(param); if (obs_sceneitem_is_group(item)) obs_sceneitem_group_enum_items(item, select_one, param); @@ -3634,36 +3198,28 @@ void OBSBasic::AddSceneItem(OBSSceneItem item) if (!disableSaving) { obs_source_t *sceneSource = obs_scene_get_source(scene); obs_source_t *itemSource = obs_sceneitem_get_source(item); - blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'", - obs_source_get_name(itemSource), - obs_source_get_id(itemSource), - obs_source_get_name(sceneSource)); + blog(LOG_INFO, "User added source '%s' (%s) to scene '%s'", obs_source_get_name(itemSource), + obs_source_get_id(itemSource), obs_source_get_name(sceneSource)); - obs_scene_enum_items(scene, select_one, - (obs_sceneitem_t *)item); + obs_scene_enum_items(scene, select_one, (obs_sceneitem_t *)item); } } -static void RenameListValues(QListWidget *listWidget, const QString &newName, - const QString &prevName) +static void RenameListValues(QListWidget *listWidget, const QString &newName, const QString &prevName) { - QList items = - listWidget->findItems(prevName, Qt::MatchExactly); + QList items = listWidget->findItems(prevName, Qt::MatchExactly); for (int i = 0; i < items.count(); i++) items[i]->setText(newName); } -void OBSBasic::RenameSources(OBSSource source, QString newName, - QString prevName) +void OBSBasic::RenameSources(OBSSource source, QString newName, QString prevName) { RenameListValues(ui->scenes, newName, prevName); - if (vcamConfig.type == VCamOutputType::SourceOutput && - prevName == QString::fromStdString(vcamConfig.source)) + if (vcamConfig.type == VCamOutputType::SourceOutput && prevName == QString::fromStdString(vcamConfig.source)) vcamConfig.source = newName.toStdString(); - if (vcamConfig.type == VCamOutputType::SceneOutput && - prevName == QString::fromStdString(vcamConfig.scene)) + if (vcamConfig.type == VCamOutputType::SceneOutput && prevName == QString::fromStdString(vcamConfig.scene)) vcamConfig.scene = newName.toStdString(); SaveProject(); @@ -3718,8 +3274,7 @@ static bool is_network_media_source(obs_source_t *source, const char *id) void OBSBasic::UpdateContextBarDeferred(bool force) { - QMetaObject::invokeMethod(this, "UpdateContextBar", - Qt::QueuedConnection, Q_ARG(bool, force)); + QMetaObject::invokeMethod(this, "UpdateContextBar", Qt::QueuedConnection, Q_ARG(bool, force)); } void OBSBasic::SourceToolBarActionsSetEnabled() @@ -3763,14 +3318,10 @@ void OBSBasic::UpdateContextBar(bool force) bool updateNeeded = true; QLayoutItem *la = ui->emptySpace->layout()->itemAt(0); if (la) { - if (SourceToolbar *toolbar = - dynamic_cast( - la->widget())) { + if (SourceToolbar *toolbar = dynamic_cast(la->widget())) { if (toolbar->GetSource() == source) updateNeeded = false; - } else if (MediaControls *toolbar = - dynamic_cast( - la->widget())) { + } else if (MediaControls *toolbar = dynamic_cast(la->widget())) { if (toolbar->GetSource() == source) updateNeeded = false; } @@ -3779,92 +3330,66 @@ void OBSBasic::UpdateContextBar(bool force) const char *id = obs_source_get_unversioned_id(source); uint32_t flags = obs_source_get_output_flags(source); - ui->sourceInteractButton->setVisible(flags & - OBS_SOURCE_INTERACTION); + ui->sourceInteractButton->setVisible(flags & OBS_SOURCE_INTERACTION); - if (contextBarSize >= ContextBarSize_Reduced && - (updateNeeded || force)) { + if (contextBarSize >= ContextBarSize_Reduced && (updateNeeded || force)) { ClearContextBar(); if (flags & OBS_SOURCE_CONTROLLABLE_MEDIA) { if (!is_network_media_source(source, id)) { - MediaControls *mediaControls = - new MediaControls( - ui->emptySpace); + MediaControls *mediaControls = new MediaControls(ui->emptySpace); mediaControls->SetSource(source); - ui->emptySpace->layout()->addWidget( - mediaControls); + ui->emptySpace->layout()->addWidget(mediaControls); } } else if (strcmp(id, "browser_source") == 0) { - BrowserToolbar *c = new BrowserToolbar( - ui->emptySpace, source); + BrowserToolbar *c = new BrowserToolbar(ui->emptySpace, source); ui->emptySpace->layout()->addWidget(c); } else if (strcmp(id, "wasapi_input_capture") == 0 || strcmp(id, "wasapi_output_capture") == 0 || strcmp(id, "coreaudio_input_capture") == 0 || - strcmp(id, "coreaudio_output_capture") == - 0 || - strcmp(id, "pulse_input_capture") == 0 || - strcmp(id, "pulse_output_capture") == 0 || + strcmp(id, "coreaudio_output_capture") == 0 || + strcmp(id, "pulse_input_capture") == 0 || strcmp(id, "pulse_output_capture") == 0 || strcmp(id, "alsa_input_capture") == 0) { - AudioCaptureToolbar *c = - new AudioCaptureToolbar(ui->emptySpace, - source); + AudioCaptureToolbar *c = new AudioCaptureToolbar(ui->emptySpace, source); c->Init(); ui->emptySpace->layout()->addWidget(c); - } else if (strcmp(id, - "wasapi_process_output_capture") == - 0) { + } else if (strcmp(id, "wasapi_process_output_capture") == 0) { ApplicationAudioCaptureToolbar *c = - new ApplicationAudioCaptureToolbar( - ui->emptySpace, source); + new ApplicationAudioCaptureToolbar(ui->emptySpace, source); c->Init(); ui->emptySpace->layout()->addWidget(c); - } else if (strcmp(id, "window_capture") == 0 || - strcmp(id, "xcomposite_input") == 0) { - WindowCaptureToolbar *c = - new WindowCaptureToolbar(ui->emptySpace, - source); + } else if (strcmp(id, "window_capture") == 0 || strcmp(id, "xcomposite_input") == 0) { + WindowCaptureToolbar *c = new WindowCaptureToolbar(ui->emptySpace, source); c->Init(); ui->emptySpace->layout()->addWidget(c); - } else if (strcmp(id, "monitor_capture") == 0 || - strcmp(id, "display_capture") == 0 || + } else if (strcmp(id, "monitor_capture") == 0 || strcmp(id, "display_capture") == 0 || strcmp(id, "xshm_input") == 0) { - DisplayCaptureToolbar *c = - new DisplayCaptureToolbar( - ui->emptySpace, source); + DisplayCaptureToolbar *c = new DisplayCaptureToolbar(ui->emptySpace, source); c->Init(); ui->emptySpace->layout()->addWidget(c); } else if (strcmp(id, "dshow_input") == 0) { - DeviceCaptureToolbar *c = - new DeviceCaptureToolbar(ui->emptySpace, - source); + DeviceCaptureToolbar *c = new DeviceCaptureToolbar(ui->emptySpace, source); ui->emptySpace->layout()->addWidget(c); } else if (strcmp(id, "game_capture") == 0) { - GameCaptureToolbar *c = new GameCaptureToolbar( - ui->emptySpace, source); + GameCaptureToolbar *c = new GameCaptureToolbar(ui->emptySpace, source); ui->emptySpace->layout()->addWidget(c); } else if (strcmp(id, "image_source") == 0) { - ImageSourceToolbar *c = new ImageSourceToolbar( - ui->emptySpace, source); + ImageSourceToolbar *c = new ImageSourceToolbar(ui->emptySpace, source); ui->emptySpace->layout()->addWidget(c); } else if (strcmp(id, "color_source") == 0) { - ColorSourceToolbar *c = new ColorSourceToolbar( - ui->emptySpace, source); + ColorSourceToolbar *c = new ColorSourceToolbar(ui->emptySpace, source); ui->emptySpace->layout()->addWidget(c); - } else if (strcmp(id, "text_ft2_source") == 0 || - strcmp(id, "text_gdiplus") == 0) { - TextSourceToolbar *c = new TextSourceToolbar( - ui->emptySpace, source); + } else if (strcmp(id, "text_ft2_source") == 0 || strcmp(id, "text_gdiplus") == 0) { + TextSourceToolbar *c = new TextSourceToolbar(ui->emptySpace, source); ui->emptySpace->layout()->addWidget(c); } } else if (contextBarSize == ContextBarSize_Minimized) { @@ -3889,14 +3414,12 @@ void OBSBasic::UpdateContextBar(bool force) ui->contextSourceLabel->setText(name); ui->sourceFiltersButton->setEnabled(true); - ui->sourcePropertiesButton->setEnabled( - obs_source_configurable(source)); + ui->sourcePropertiesButton->setEnabled(obs_source_configurable(source)); } else { ClearContextBar(); ui->contextSourceIcon->hide(); ui->contextSourceIconSpacer->show(); - ui->contextSourceLabel->setText( - QTStr("ContextBar.NoSelectedSource")); + ui->contextSourceLabel->setText(QTStr("ContextBar.NoSelectedSource")); ui->sourceFiltersButton->setEnabled(false); ui->sourcePropertiesButton->setEnabled(false); @@ -3916,8 +3439,7 @@ void OBSBasic::UpdateContextBar(bool force) static inline bool SourceMixerHidden(obs_source_t *source) { - OBSDataAutoRelease priv_settings = - obs_source_get_private_settings(source); + OBSDataAutoRelease priv_settings = obs_source_get_private_settings(source); bool hidden = obs_data_get_bool(priv_settings, "mixer_hidden"); return hidden; @@ -3925,8 +3447,7 @@ static inline bool SourceMixerHidden(obs_source_t *source) static inline void SetSourceMixerHidden(obs_source_t *source, bool hidden) { - OBSDataAutoRelease priv_settings = - obs_source_get_private_settings(source); + OBSDataAutoRelease priv_settings = obs_source_get_private_settings(source); obs_data_set_bool(priv_settings, "mixer_hidden", hidden); } @@ -4008,26 +3529,20 @@ void OBSBasic::MixerRenameSource() for (;;) { string name; - bool accepted = NameDialog::AskForName( - this, QTStr("Basic.Main.MixerRename.Title"), - QTStr("Basic.Main.MixerRename.Text"), name, - QT_UTF8(prevName)); + bool accepted = NameDialog::AskForName(this, QTStr("Basic.Main.MixerRename.Title"), + QTStr("Basic.Main.MixerRename.Text"), name, QT_UTF8(prevName)); if (!accepted) return; if (name.empty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); continue; } - OBSSourceAutoRelease sourceTest = - obs_get_source_by_name(name.c_str()); + OBSSourceAutoRelease sourceTest = obs_get_source_by_name(name.c_str()); if (sourceTest) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); continue; } @@ -4038,8 +3553,7 @@ void OBSBasic::MixerRenameSource() static inline bool SourceVolumeLocked(obs_source_t *source) { - OBSDataAutoRelease priv_settings = - obs_source_get_private_settings(source); + OBSDataAutoRelease priv_settings = obs_source_get_private_settings(source); bool lock = obs_data_get_bool(priv_settings, "volume_locked"); return lock; @@ -4051,8 +3565,7 @@ void OBSBasic::LockVolumeControl(bool lock) VolControl *vol = action->property("volControl").value(); obs_source_t *source = vol->GetSource(); - OBSDataAutoRelease priv_settings = - obs_source_get_private_settings(source); + OBSDataAutoRelease priv_settings = obs_source_get_private_settings(source); obs_data_set_bool(priv_settings, "volume_locked", lock); vol->EnableSlider(!lock); @@ -4081,63 +3594,47 @@ void OBSBasic::VolControlContextMenu() QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this); toggleControlLayoutAction.setCheckable(true); - toggleControlLayoutAction.setChecked(config_get_bool( - App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); + toggleControlLayoutAction.setChecked( + config_get_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); /* ------------------- */ - connect(&hideAction, &QAction::triggered, this, - &OBSBasic::HideAudioControl, Qt::DirectConnection); - connect(&unhideAllAction, &QAction::triggered, this, - &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection); - connect(&lockAction, &QAction::toggled, this, - &OBSBasic::LockVolumeControl, Qt::DirectConnection); - connect(&mixerRenameAction, &QAction::triggered, this, - &OBSBasic::MixerRenameSource, Qt::DirectConnection); + connect(&hideAction, &QAction::triggered, this, &OBSBasic::HideAudioControl, Qt::DirectConnection); + connect(&unhideAllAction, &QAction::triggered, this, &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection); + connect(&lockAction, &QAction::toggled, this, &OBSBasic::LockVolumeControl, Qt::DirectConnection); + connect(&mixerRenameAction, &QAction::triggered, this, &OBSBasic::MixerRenameSource, Qt::DirectConnection); - connect(©FiltersAction, &QAction::triggered, this, - &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection); - connect(&pasteFiltersAction, &QAction::triggered, this, - &OBSBasic::AudioMixerPasteFilters, Qt::DirectConnection); + connect(©FiltersAction, &QAction::triggered, this, &OBSBasic::AudioMixerCopyFilters, Qt::DirectConnection); + connect(&pasteFiltersAction, &QAction::triggered, this, &OBSBasic::AudioMixerPasteFilters, + Qt::DirectConnection); - connect(&filtersAction, &QAction::triggered, this, - &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection); - connect(&propertiesAction, &QAction::triggered, this, - &OBSBasic::GetAudioSourceProperties, Qt::DirectConnection); - connect(&advPropAction, &QAction::triggered, this, - &OBSBasic::on_actionAdvAudioProperties_triggered, + connect(&filtersAction, &QAction::triggered, this, &OBSBasic::GetAudioSourceFilters, Qt::DirectConnection); + connect(&propertiesAction, &QAction::triggered, this, &OBSBasic::GetAudioSourceProperties, + Qt::DirectConnection); + connect(&advPropAction, &QAction::triggered, this, &OBSBasic::on_actionAdvAudioProperties_triggered, Qt::DirectConnection); /* ------------------- */ - connect(&toggleControlLayoutAction, &QAction::changed, this, - &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection); + connect(&toggleControlLayoutAction, &QAction::changed, this, &OBSBasic::ToggleVolControlLayout, + Qt::DirectConnection); /* ------------------- */ - hideAction.setProperty("volControl", - QVariant::fromValue(vol)); - lockAction.setProperty("volControl", - QVariant::fromValue(vol)); - mixerRenameAction.setProperty("volControl", - QVariant::fromValue(vol)); + hideAction.setProperty("volControl", QVariant::fromValue(vol)); + lockAction.setProperty("volControl", QVariant::fromValue(vol)); + mixerRenameAction.setProperty("volControl", QVariant::fromValue(vol)); - copyFiltersAction.setProperty("volControl", - QVariant::fromValue(vol)); - pasteFiltersAction.setProperty("volControl", - QVariant::fromValue(vol)); + copyFiltersAction.setProperty("volControl", QVariant::fromValue(vol)); + pasteFiltersAction.setProperty("volControl", QVariant::fromValue(vol)); - filtersAction.setProperty("volControl", - QVariant::fromValue(vol)); - propertiesAction.setProperty("volControl", - QVariant::fromValue(vol)); + filtersAction.setProperty("volControl", QVariant::fromValue(vol)); + propertiesAction.setProperty("volControl", QVariant::fromValue(vol)); /* ------------------- */ - copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) > - 0); - pasteFiltersAction.setEnabled( - !obs_weak_source_expired(copyFiltersSource)); + copyFiltersAction.setEnabled(obs_source_filter_count(vol->GetSource()) > 0); + pasteFiltersAction.setEnabled(!obs_weak_source_expired(copyFiltersSource)); QMenu popup; vol->SetContextMenu(&popup); @@ -4180,22 +3677,20 @@ void OBSBasic::StackedMixerAreaContextMenuRequested() QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this); toggleControlLayoutAction.setCheckable(true); - toggleControlLayoutAction.setChecked(config_get_bool( - App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); + toggleControlLayoutAction.setChecked( + config_get_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); /* ------------------- */ - connect(&unhideAllAction, &QAction::triggered, this, - &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection); + connect(&unhideAllAction, &QAction::triggered, this, &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection); - connect(&advPropAction, &QAction::triggered, this, - &OBSBasic::on_actionAdvAudioProperties_triggered, + connect(&advPropAction, &QAction::triggered, this, &OBSBasic::on_actionAdvAudioProperties_triggered, Qt::DirectConnection); /* ------------------- */ - connect(&toggleControlLayoutAction, &QAction::changed, this, - &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection); + connect(&toggleControlLayoutAction, &QAction::changed, this, &OBSBasic::ToggleVolControlLayout, + Qt::DirectConnection); /* ------------------- */ @@ -4221,10 +3716,8 @@ void OBSBasic::ToggleMixerLayout(bool vertical) void OBSBasic::ToggleVolControlLayout() { - bool vertical = !config_get_bool(App()->GetUserConfig(), "BasicWindow", - "VerticalVolControl"); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "VerticalVolControl", vertical); + bool vertical = !config_get_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl"); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl", vertical); ToggleMixerLayout(vertical); // We need to store it so we can delete current and then add @@ -4248,18 +3741,15 @@ void OBSBasic::ActivateAudioSource(OBSSource source) if (!obs_source_audio_active(source)) return; - bool vertical = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "VerticalVolControl"); + bool vertical = config_get_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl"); VolControl *vol = new VolControl(source, true, vertical); vol->EnableSlider(!SourceVolumeLocked(source)); - double meterDecayRate = config_get_double(activeConfiguration, "Audio", - "MeterDecayRate"); + double meterDecayRate = config_get_double(activeConfiguration, "Audio", "MeterDecayRate"); vol->SetMeterDecayRate(meterDecayRate); - uint32_t peakMeterTypeIdx = - config_get_uint(activeConfiguration, "Audio", "PeakMeterType"); + uint32_t peakMeterTypeIdx = config_get_uint(activeConfiguration, "Audio", "PeakMeterType"); enum obs_peak_meter_type peakMeterType; switch (peakMeterTypeIdx) { @@ -4278,10 +3768,8 @@ void OBSBasic::ActivateAudioSource(OBSSource source) vol->setContextMenuPolicy(Qt::CustomContextMenu); - connect(vol, &QWidget::customContextMenuRequested, this, - &OBSBasic::VolControlContextMenu); - connect(vol, &VolControl::ConfigClicked, this, - &OBSBasic::VolControlContextMenu); + connect(vol, &QWidget::customContextMenuRequested, this, &OBSBasic::VolControlContextMenu); + connect(vol, &VolControl::ConfigClicked, this, &OBSBasic::VolControlContextMenu); InsertQObjectByName(volumes, vol); @@ -4306,14 +3794,11 @@ void OBSBasic::DeactivateAudioSource(OBSSource source) bool OBSBasic::QueryRemoveSource(obs_source_t *source) { - if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE && - !obs_source_is_group(source)) { + if (obs_source_get_type(source) == OBS_SOURCE_TYPE_SCENE && !obs_source_is_group(source)) { int count = ui->scenes->count(); if (count == 1) { - OBSMessageBox::information(this, - QTStr("FinalScene.Title"), - QTStr("FinalScene.Text")); + OBSMessageBox::information(this, QTStr("FinalScene.Title"), QTStr("FinalScene.Text")); return false; } } @@ -4324,8 +3809,7 @@ bool OBSBasic::QueryRemoveSource(obs_source_t *source) QMessageBox remove_source(this); remove_source.setText(text); - QPushButton *Yes = - remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole); + QPushButton *Yes = remove_source.addButton(QTStr("Yes"), QMessageBox::YesRole); remove_source.setDefaultButton(Yes); remove_source.addButton(QTStr("No"), QMessageBox::NoRole); remove_source.setIcon(QMessageBox::Question); @@ -4341,22 +3825,18 @@ void OBSBasic::TimedCheckForUpdates() { if (App()->IsUpdaterDisabled()) return; - if (!config_get_bool(App()->GetUserConfig(), "General", - "EnableAutoUpdates")) + if (!config_get_bool(App()->GetUserConfig(), "General", "EnableAutoUpdates")) return; #if defined(ENABLE_SPARKLE_UPDATER) CheckForUpdates(false); #elif _WIN32 - long long lastUpdate = config_get_int(App()->GetAppConfig(), "General", - "LastUpdateCheck"); - uint32_t lastVersion = - config_get_int(App()->GetAppConfig(), "General", "LastVersion"); + long long lastUpdate = config_get_int(App()->GetAppConfig(), "General", "LastUpdateCheck"); + uint32_t lastVersion = config_get_int(App()->GetAppConfig(), "General", "LastVersion"); if (lastVersion < LIBOBS_API_VER) { lastUpdate = 0; - config_set_int(App()->GetAppConfig(), "General", - "LastUpdateCheck", 0); + config_set_int(App()->GetAppConfig(), "General", "LastUpdateCheck", 0); } long long t = (long long)time(nullptr); @@ -4384,8 +3864,7 @@ void OBSBasic::CheckForUpdates(bool manualUpdate) return; MacUpdateThread *mut = new MacUpdateThread(manualUpdate); - connect(mut, &MacUpdateThread::Result, this, - &OBSBasic::MacBranchesFetched, Qt::QueuedConnection); + connect(mut, &MacUpdateThread::Result, this, &OBSBasic::MacBranchesFetched, Qt::QueuedConnection); updateCheckThread.reset(mut); updateCheckThread->start(); #else @@ -4399,8 +3878,7 @@ void OBSBasic::MacBranchesFetched(const QString &branch, bool manualUpdate) static OBSSparkle *updater; if (!updater) { - updater = new OBSSparkle(QT_TO_UTF8(branch), - ui->actionCheckForUpdates); + updater = new OBSSparkle(QT_TO_UTF8(branch), ui->actionCheckForUpdates); return; } @@ -4438,62 +3916,49 @@ void OBSBasic::DuplicateSelectedScene() for (;;) { string name; - bool accepted = NameDialog::AskForName( - this, QTStr("Basic.Main.AddSceneDlg.Title"), - QTStr("Basic.Main.AddSceneDlg.Text"), name, - placeHolderText); + bool accepted = NameDialog::AskForName(this, QTStr("Basic.Main.AddSceneDlg.Title"), + QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText); if (!accepted) return; if (name.empty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); continue; } obs_source_t *source = obs_get_source_by_name(name.c_str()); if (source) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); obs_source_release(source); continue; } - OBSSceneAutoRelease scene = obs_scene_duplicate( - curScene, name.c_str(), OBS_SCENE_DUP_REFS); + OBSSceneAutoRelease scene = obs_scene_duplicate(curScene, name.c_str(), OBS_SCENE_DUP_REFS); source = obs_scene_get_source(scene); SetCurrentScene(source, true); auto undo = [](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_name(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(data.c_str()); obs_source_remove(source); }; auto redo = [this, name](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_name(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(data.c_str()); obs_scene_t *scene = obs_scene_from_source(source); - scene = obs_scene_duplicate(scene, name.c_str(), - OBS_SCENE_DUP_REFS); + scene = obs_scene_duplicate(scene, name.c_str(), OBS_SCENE_DUP_REFS); source = obs_scene_get_source(scene); SetCurrentScene(source.Get(), true); }; - undo_s.add_action( - QTStr("Undo.Scene.Duplicate") - .arg(obs_source_get_name(source)), - undo, redo, obs_source_get_name(source), - obs_source_get_name(obs_scene_get_source(curScene))); + undo_s.add_action(QTStr("Undo.Scene.Duplicate").arg(obs_source_get_name(source)), undo, redo, + obs_source_get_name(source), obs_source_get_name(obs_scene_get_source(curScene))); break; } } -static bool save_undo_source_enum(obs_scene_t * /* scene */, - obs_sceneitem_t *item, void *p) +static bool save_undo_source_enum(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *p) { obs_source_t *source = obs_sceneitem_get_source(item); if (obs_obj_is_private(source) && !obs_source_removed(source)) @@ -4511,8 +3976,7 @@ static bool save_undo_source_enum(obs_scene_t * /* scene */, } if (obs_source_is_group(source)) - obs_scene_enum_items(obs_group_from_source(source), - save_undo_source_enum, p); + obs_scene_enum_items(obs_group_from_source(source), save_undo_source_enum, p); OBSDataAutoRelease source_data = obs_save_source(source); obs_data_array_push_back(array, source_data); @@ -4542,11 +4006,9 @@ void OBSBasic::RemoveSelectedScene() /* ------------------------------ */ /* save all sources in scene */ - OBSDataArrayAutoRelease sources_in_deleted_scene = - obs_data_array_create(); + OBSDataArrayAutoRelease sources_in_deleted_scene = obs_data_array_create(); - obs_scene_enum_items(scene, save_undo_source_enum, - sources_in_deleted_scene); + obs_scene_enum_items(scene, save_undo_source_enum, sources_in_deleted_scene); OBSDataAutoRelease scene_data = obs_save_source(source); obs_data_array_push_back(sources_in_deleted_scene, scene_data); @@ -4554,32 +4016,25 @@ void OBSBasic::RemoveSelectedScene() /* ----------------------------------------------- */ /* save all scenes and groups the scene is used in */ - OBSDataArrayAutoRelease scene_used_in_other_scenes = - obs_data_array_create(); + OBSDataArrayAutoRelease scene_used_in_other_scenes = obs_data_array_create(); struct other_scenes_cb_data { obs_source_t *oldScene; obs_data_array_t *scene_used_in_other_scenes; } other_scenes_cb_data; other_scenes_cb_data.oldScene = source; - other_scenes_cb_data.scene_used_in_other_scenes = - scene_used_in_other_scenes; + other_scenes_cb_data.scene_used_in_other_scenes = scene_used_in_other_scenes; auto other_scenes_cb = [](void *data_ptr, obs_source_t *scene) { - struct other_scenes_cb_data *data = - (struct other_scenes_cb_data *)data_ptr; - if (strcmp(obs_source_get_name(scene), - obs_source_get_name(data->oldScene)) == 0) + struct other_scenes_cb_data *data = (struct other_scenes_cb_data *)data_ptr; + if (strcmp(obs_source_get_name(scene), obs_source_get_name(data->oldScene)) == 0) return true; - obs_sceneitem_t *item = obs_scene_find_source( - obs_group_or_scene_from_source(scene), - obs_source_get_name(data->oldScene)); + obs_sceneitem_t *item = obs_scene_find_source(obs_group_or_scene_from_source(scene), + obs_source_get_name(data->oldScene)); if (item) { OBSDataAutoRelease scene_data = - obs_save_source(obs_scene_get_source( - obs_sceneitem_get_scene(item))); - obs_data_array_push_back( - data->scene_used_in_other_scenes, scene_data); + obs_save_source(obs_scene_get_source(obs_sceneitem_get_scene(item))); + obs_data_array_push_back(data->scene_used_in_other_scenes, scene_data); } return true; }; @@ -4589,10 +4044,8 @@ void OBSBasic::RemoveSelectedScene() /* undo/redo */ auto undo = [this](const std::string &json) { - OBSDataAutoRelease base = - obs_data_create_from_json(json.c_str()); - OBSDataArrayAutoRelease sources_in_deleted_scene = - obs_data_get_array(base, "sources_in_deleted_scene"); + OBSDataAutoRelease base = obs_data_create_from_json(json.c_str()); + OBSDataArrayAutoRelease sources_in_deleted_scene = obs_data_get_array(base, "sources_in_deleted_scene"); OBSDataArrayAutoRelease scene_used_in_other_scenes = obs_data_get_array(base, "scene_used_in_other_scenes"); int savedIndex = (int)obs_data_get_int(base, "index"); @@ -4603,12 +4056,10 @@ void OBSBasic::RemoveSelectedScene() sources.reserve(count); for (size_t i = 0; i < count; i++) { - OBSDataAutoRelease data = obs_data_array_item( - sources_in_deleted_scene, i); + OBSDataAutoRelease data = obs_data_array_item(sources_in_deleted_scene, i); const char *name = obs_data_get_string(data, "name"); - OBSSourceAutoRelease source = - obs_get_source_by_name(name); + OBSSourceAutoRelease source = obs_get_source_by_name(name); if (!source) { source = obs_load_source(data); sources.push_back(source.Get()); @@ -4620,39 +4071,27 @@ void OBSBasic::RemoveSelectedScene() obs_source_load2(source); /* Add scene to scenes and groups it was nested in */ - for (size_t i = 0; - i < obs_data_array_count(scene_used_in_other_scenes); - i++) { - OBSDataAutoRelease data = obs_data_array_item( - scene_used_in_other_scenes, i); + for (size_t i = 0; i < obs_data_array_count(scene_used_in_other_scenes); i++) { + OBSDataAutoRelease data = obs_data_array_item(scene_used_in_other_scenes, i); const char *name = obs_data_get_string(data, "name"); - OBSSourceAutoRelease source = - obs_get_source_by_name(name); + OBSSourceAutoRelease source = obs_get_source_by_name(name); - OBSDataAutoRelease settings = - obs_data_get_obj(data, "settings"); - OBSDataArrayAutoRelease items = - obs_data_get_array(settings, "items"); + OBSDataAutoRelease settings = obs_data_get_obj(data, "settings"); + OBSDataArrayAutoRelease items = obs_data_get_array(settings, "items"); /* Clear scene, but keep a reference to all sources in the scene to make sure they don't get destroyed */ std::vector existing_sources; - auto cb = [](obs_scene_t *, obs_sceneitem_t *item, - void *data) { - std::vector *existing = - (std::vector *)data; - OBSSource source = - obs_sceneitem_get_source(item); + auto cb = [](obs_scene_t *, obs_sceneitem_t *item, void *data) { + std::vector *existing = (std::vector *)data; + OBSSource source = obs_sceneitem_get_source(item); obs_sceneitem_remove(item); existing->push_back(source); return true; }; - obs_scene_enum_items( - obs_group_or_scene_from_source(source), cb, - (void *)&existing_sources); + obs_scene_enum_items(obs_group_or_scene_from_source(source), cb, (void *)&existing_sources); /* Re-add sources to the scene */ - obs_sceneitems_add( - obs_group_or_scene_from_source(source), items); + obs_sceneitems_add(obs_group_or_scene_from_source(source), items); } obs_source_t *scene_source = sources.back(); @@ -4670,21 +4109,17 @@ void OBSBasic::RemoveSelectedScene() }; auto redo = [](const std::string &name) { - OBSSourceAutoRelease source = - obs_get_source_by_name(name.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(name.c_str()); RemoveSceneAndReleaseNested(source); }; OBSDataAutoRelease data = obs_data_create(); - obs_data_set_array(data, "sources_in_deleted_scene", - sources_in_deleted_scene); - obs_data_set_array(data, "scene_used_in_other_scenes", - scene_used_in_other_scenes); + obs_data_set_array(data, "sources_in_deleted_scene", sources_in_deleted_scene); + obs_data_set_array(data, "scene_used_in_other_scenes", scene_used_in_other_scenes); obs_data_set_int(data, "index", ui->scenes->currentRow()); const char *scene_name = obs_source_get_name(source); - undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo, - obs_data_get_json(data), scene_name); + undo_s.add_action(QTStr("Undo.Delete").arg(scene_name), undo, redo, obs_data_get_json(data), scene_name); /* --------------------------- */ /* remove */ @@ -4720,8 +4155,7 @@ void OBSBasic::SceneReordered(void *data, calldata_t *params) obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene"); - QMetaObject::invokeMethod(window, "ReorderSources", - Q_ARG(OBSScene, OBSScene(scene))); + QMetaObject::invokeMethod(window, "ReorderSources", Q_ARG(OBSScene, OBSScene(scene))); } void OBSBasic::SceneRefreshed(void *data, calldata_t *params) @@ -4730,8 +4164,7 @@ void OBSBasic::SceneRefreshed(void *data, calldata_t *params) obs_scene_t *scene = (obs_scene_t *)calldata_ptr(params, "scene"); - QMetaObject::invokeMethod(window, "RefreshSources", - Q_ARG(OBSScene, OBSScene(scene))); + QMetaObject::invokeMethod(window, "RefreshSources", Q_ARG(OBSScene, OBSScene(scene))); } void OBSBasic::SceneItemAdded(void *data, calldata_t *params) @@ -4740,8 +4173,7 @@ void OBSBasic::SceneItemAdded(void *data, calldata_t *params) obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(params, "item"); - QMetaObject::invokeMethod(window, "AddSceneItem", - Q_ARG(OBSSceneItem, OBSSceneItem(item))); + QMetaObject::invokeMethod(window, "AddSceneItem", Q_ARG(OBSSceneItem, OBSSceneItem(item))); } void OBSBasic::SourceCreated(void *data, calldata_t *params) @@ -4749,8 +4181,7 @@ void OBSBasic::SourceCreated(void *data, calldata_t *params) obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source"); if (obs_scene_from_source(source) != NULL) - QMetaObject::invokeMethod(static_cast(data), - "AddScene", WaitConnection(), + QMetaObject::invokeMethod(static_cast(data), "AddScene", WaitConnection(), Q_ARG(OBSSource, OBSSource(source))); } @@ -4759,8 +4190,7 @@ void OBSBasic::SourceRemoved(void *data, calldata_t *params) obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source"); if (obs_scene_from_source(source) != NULL) - QMetaObject::invokeMethod(static_cast(data), - "RemoveScene", + QMetaObject::invokeMethod(static_cast(data), "RemoveScene", Q_ARG(OBSSource, OBSSource(source))); } @@ -4770,8 +4200,7 @@ void OBSBasic::SourceActivated(void *data, calldata_t *params) uint32_t flags = obs_source_get_output_flags(source); if (flags & OBS_SOURCE_AUDIO) - QMetaObject::invokeMethod(static_cast(data), - "ActivateAudioSource", + QMetaObject::invokeMethod(static_cast(data), "ActivateAudioSource", Q_ARG(OBSSource, OBSSource(source))); } @@ -4781,8 +4210,7 @@ void OBSBasic::SourceDeactivated(void *data, calldata_t *params) uint32_t flags = obs_source_get_output_flags(source); if (flags & OBS_SOURCE_AUDIO) - QMetaObject::invokeMethod(static_cast(data), - "DeactivateAudioSource", + QMetaObject::invokeMethod(static_cast(data), "DeactivateAudioSource", Q_ARG(OBSSource, OBSSource(source))); } @@ -4791,16 +4219,14 @@ void OBSBasic::SourceAudioActivated(void *data, calldata_t *params) obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source"); if (obs_source_active(source)) - QMetaObject::invokeMethod(static_cast(data), - "ActivateAudioSource", + QMetaObject::invokeMethod(static_cast(data), "ActivateAudioSource", Q_ARG(OBSSource, OBSSource(source))); } void OBSBasic::SourceAudioDeactivated(void *data, calldata_t *params) { obs_source_t *source = (obs_source_t *)calldata_ptr(params, "source"); - QMetaObject::invokeMethod(static_cast(data), - "DeactivateAudioSource", + QMetaObject::invokeMethod(static_cast(data), "DeactivateAudioSource", Q_ARG(OBSSource, OBSSource(source))); } @@ -4810,10 +4236,8 @@ void OBSBasic::SourceRenamed(void *data, calldata_t *params) const char *newName = calldata_string(params, "new_name"); const char *prevName = calldata_string(params, "prev_name"); - QMetaObject::invokeMethod(static_cast(data), - "RenameSources", Q_ARG(OBSSource, source), - Q_ARG(QString, QT_UTF8(newName)), - Q_ARG(QString, QT_UTF8(prevName))); + QMetaObject::invokeMethod(static_cast(data), "RenameSources", Q_ARG(OBSSource, source), + Q_ARG(QString, QT_UTF8(newName)), Q_ARG(QString, QT_UTF8(prevName))); blog(LOG_INFO, "Source '%s' renamed to '%s'", prevName, newName); } @@ -4872,21 +4296,17 @@ void OBSBasic::RenderMain(void *data, uint32_t, uint32_t) float right = float(width) - window->previewX; float bottom = float(height) - window->previewY; - gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f, - 100.0f); + gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f, 100.0f); window->ui->preview->DrawOverflow(); /* --------------------------------------- */ - gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height), - -100.0f, 100.0f); - gs_set_viewport(window->previewX, window->previewY, window->previewCX, - window->previewCY); + gs_ortho(0.0f, float(ovi.base_width), 0.0f, float(ovi.base_height), -100.0f, 100.0f); + gs_set_viewport(window->previewX, window->previewY, window->previewCX, window->previewCY); if (window->IsPreviewProgramMode()) { - window->DrawBackdrop(float(ovi.base_width), - float(ovi.base_height)); + window->DrawBackdrop(float(ovi.base_width), float(ovi.base_height)); OBSScene scene = window->GetCurrentScene(); obs_source_t *source = obs_scene_get_source(scene); @@ -4899,8 +4319,7 @@ void OBSBasic::RenderMain(void *data, uint32_t, uint32_t) /* --------------------------------------- */ - gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f, - 100.0f); + gs_ortho(-window->previewX, right, -window->previewY, bottom, -100.0f, 100.0f); gs_reset_viewport(); uint32_t targetCX = window->previewCX; @@ -4909,8 +4328,7 @@ void OBSBasic::RenderMain(void *data, uint32_t, uint32_t) if (window->drawSafeAreas) { RenderSafeAreas(window->actionSafeMargin, targetCX, targetCY); RenderSafeAreas(window->graphicsSafeMargin, targetCX, targetCY); - RenderSafeAreas(window->fourByThreeSafeMargin, targetCX, - targetCY); + RenderSafeAreas(window->fourByThreeSafeMargin, targetCX, targetCY); RenderSafeAreas(window->leftLine, targetCX, targetCY); RenderSafeAreas(window->topLine, targetCX, targetCY); RenderSafeAreas(window->rightLine, targetCX, targetCY); @@ -4934,8 +4352,7 @@ void OBSBasic::RenderMain(void *data, uint32_t, uint32_t) obs_service_t *OBSBasic::GetService() { if (!service) { - service = - obs_service_create("rtmp_common", NULL, NULL, nullptr); + service = obs_service_create("rtmp_common", NULL, NULL, nullptr); obs_service_release(service); } return service; @@ -4973,8 +4390,7 @@ static inline int AttemptToResetVideo(struct obs_video_info *ovi) static inline enum obs_scale_type GetScaleType(ConfigFile &activeConfiguration) { - const char *scaleTypeStr = - config_get_string(activeConfiguration, "Video", "ScaleType"); + const char *scaleTypeStr = config_get_string(activeConfiguration, "Video", "ScaleType"); if (astrcmpi(scaleTypeStr, "bilinear") == 0) return OBS_SCALE_BILINEAR; @@ -5031,8 +4447,7 @@ static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name) void OBSBasic::ResetUI() { - bool studioPortraitLayout = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "StudioPortraitLayout"); + bool studioPortraitLayout = config_get_bool(App()->GetUserConfig(), "BasicWindow", "StudioPortraitLayout"); if (studioPortraitLayout) ui->previewLayout->setDirection(QBoxLayout::BottomToTop); @@ -5054,28 +4469,19 @@ int OBSBasic::ResetVideo() GetConfigFPS(ovi.fps_num, ovi.fps_den); - const char *colorFormat = - config_get_string(activeConfiguration, "Video", "ColorFormat"); - const char *colorSpace = - config_get_string(activeConfiguration, "Video", "ColorSpace"); - const char *colorRange = - config_get_string(activeConfiguration, "Video", "ColorRange"); + const char *colorFormat = config_get_string(activeConfiguration, "Video", "ColorFormat"); + const char *colorSpace = config_get_string(activeConfiguration, "Video", "ColorSpace"); + const char *colorRange = config_get_string(activeConfiguration, "Video", "ColorRange"); ovi.graphics_module = App()->GetRenderModule(); - ovi.base_width = (uint32_t)config_get_uint(activeConfiguration, "Video", - "BaseCX"); - ovi.base_height = (uint32_t)config_get_uint(activeConfiguration, - "Video", "BaseCY"); - ovi.output_width = (uint32_t)config_get_uint(activeConfiguration, - "Video", "OutputCX"); - ovi.output_height = (uint32_t)config_get_uint(activeConfiguration, - "Video", "OutputCY"); + ovi.base_width = (uint32_t)config_get_uint(activeConfiguration, "Video", "BaseCX"); + ovi.base_height = (uint32_t)config_get_uint(activeConfiguration, "Video", "BaseCY"); + ovi.output_width = (uint32_t)config_get_uint(activeConfiguration, "Video", "OutputCX"); + ovi.output_height = (uint32_t)config_get_uint(activeConfiguration, "Video", "OutputCY"); ovi.output_format = GetVideoFormatFromName(colorFormat); ovi.colorspace = GetVideoColorSpaceFromName(colorSpace); - ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL - : VIDEO_RANGE_PARTIAL; - ovi.adapter = - config_get_uint(App()->GetUserConfig(), "Video", "AdapterIdx"); + ovi.range = astrcmpi(colorRange, "Full") == 0 ? VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL; + ovi.adapter = config_get_uint(App()->GetUserConfig(), "Video", "AdapterIdx"); ovi.gpu_conversion = true; ovi.scale_type = GetScaleType(activeConfiguration); @@ -5089,10 +4495,8 @@ int OBSBasic::ResetVideo() if (ovi.output_width < 32 || ovi.output_height < 32) { ovi.output_width = ovi.base_width; ovi.output_height = ovi.base_height; - config_set_uint(activeConfiguration, "Video", "OutputCX", - ovi.base_width); - config_set_uint(activeConfiguration, "Video", "OutputCY", - ovi.base_height); + config_set_uint(activeConfiguration, "Video", "OutputCX", ovi.base_width); + config_set_uint(activeConfiguration, "Video", "OutputCY", ovi.base_height); } ret = AttemptToResetVideo(&ovi); @@ -5106,19 +4510,16 @@ int OBSBasic::ResetVideo() if (program) ResizeProgram(ovi.base_width, ovi.base_height); - const float sdr_white_level = (float)config_get_uint( - activeConfiguration, "Video", "SdrWhiteLevel"); - const float hdr_nominal_peak_level = (float)config_get_uint( - activeConfiguration, "Video", "HdrNominalPeakLevel"); + const float sdr_white_level = (float)config_get_uint(activeConfiguration, "Video", "SdrWhiteLevel"); + const float hdr_nominal_peak_level = + (float)config_get_uint(activeConfiguration, "Video", "HdrNominalPeakLevel"); obs_set_video_levels(sdr_white_level, hdr_nominal_peak_level); OBSBasicStats::InitializeValues(); OBSProjector::UpdateMultiviewProjectors(); - bool canMigrate = - usingAbsoluteCoordinates || - (migrationBaseResolution && - (migrationBaseResolution->first != ovi.base_width || - migrationBaseResolution->second != ovi.base_height)); + bool canMigrate = usingAbsoluteCoordinates || + (migrationBaseResolution && (migrationBaseResolution->first != ovi.base_width || + migrationBaseResolution->second != ovi.base_height)); ui->actionRemigrateSceneCollection->setEnabled(canMigrate); emit CanvasResized(ovi.base_width, ovi.base_height); @@ -5133,11 +4534,9 @@ bool OBSBasic::ResetAudio() ProfileScope("OBSBasic::ResetAudio"); struct obs_audio_info2 ai = {}; - ai.samples_per_sec = - config_get_uint(activeConfiguration, "Audio", "SampleRate"); + ai.samples_per_sec = config_get_uint(activeConfiguration, "Audio", "SampleRate"); - const char *channelSetupStr = - config_get_string(activeConfiguration, "Audio", "ChannelSetup"); + const char *channelSetupStr = config_get_string(activeConfiguration, "Audio", "ChannelSetup"); if (strcmp(channelSetupStr, "Mono") == 0) ai.speakers = SPEAKERS_MONO; @@ -5154,8 +4553,7 @@ bool OBSBasic::ResetAudio() else ai.speakers = SPEAKERS_STEREO; - bool lowLatencyAudioBuffering = config_get_bool( - App()->GetUserConfig(), "Audio", "LowLatencyAudioBuffering"); + bool lowLatencyAudioBuffering = config_get_bool(App()->GetUserConfig(), "Audio", "LowLatencyAudioBuffering"); if (lowLatencyAudioBuffering) { ai.max_buffering_ms = 20; ai.fixed_buffering = true; @@ -5166,8 +4564,7 @@ bool OBSBasic::ResetAudio() extern char *get_new_source_name(const char *name, const char *format); -void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId, - const char *deviceDesc, int channel) +void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId, const char *deviceDesc, int channel) { bool disable = deviceId && strcmp(deviceId, "disabled") == 0; OBSSourceAutoRelease source; @@ -5179,11 +4576,9 @@ void OBSBasic::ResetAudioDevice(const char *sourceId, const char *deviceId, obs_set_output_source(channel, nullptr); } else { settings = obs_source_get_settings(source); - const char *oldId = - obs_data_get_string(settings, "device_id"); + const char *oldId = obs_data_get_string(settings, "device_id"); if (strcmp(oldId, deviceId) != 0) { - obs_data_set_string(settings, "device_id", - deviceId); + obs_data_set_string(settings, "device_id", deviceId); obs_source_update(source, settings); } } @@ -5216,20 +4611,15 @@ void OBSBasic::ResizePreview(uint32_t cx, uint32_t cy) ui->preview->ClampScrollingOffsets(); - GetCenterPosFromFixedScale( - int(cx), int(cy), - targetSize.width() - PREVIEW_EDGE_SIZE * 2, - targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX, - previewY, previewScale); + GetCenterPosFromFixedScale(int(cx), int(cy), targetSize.width() - PREVIEW_EDGE_SIZE * 2, + targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX, previewY, + previewScale); previewX += ui->preview->GetScrollX(); previewY += ui->preview->GetScrollY(); } else { - GetScaleAndCenterPos(int(cx), int(cy), - targetSize.width() - PREVIEW_EDGE_SIZE * 2, - targetSize.height() - - PREVIEW_EDGE_SIZE * 2, - previewX, previewY, previewScale); + GetScaleAndCenterPos(int(cx), int(cy), targetSize.width() - PREVIEW_EDGE_SIZE * 2, + targetSize.height() - PREVIEW_EDGE_SIZE * 2, previewX, previewY, previewScale); } ui->preview->SetScalingAmount(previewScale); @@ -5367,14 +4757,11 @@ void OBSBasic::ClearSceneData() if (!clearingFailed) { /* This ugly mess exists to join a vector of strings * with a user-defined delimiter. */ - string orphan_names = std::accumulate( - orphan_sources.begin(), orphan_sources.end(), - string(""), [](string a, string b) { - return std::move(a) + "\n- " + b; - }); + string orphan_names = + std::accumulate(orphan_sources.begin(), orphan_sources.end(), string(""), + [](string a, string b) { return std::move(a) + "\n- " + b; }); - blog(LOG_ERROR, - "Not all sources were cleared when clearing scene data:\n%s\n", + blog(LOG_ERROR, "Not all sources were cleared when clearing scene data:\n%s\n", orphan_names.c_str()); } @@ -5385,8 +4772,7 @@ void OBSBasic::ClearSceneData() disableSaving--; blog(LOG_INFO, "All scene data cleared"); - blog(LOG_INFO, - "------------------------------------------------"); + blog(LOG_INFO, "------------------------------------------------"); } } @@ -5394,8 +4780,7 @@ void OBSBasic::closeEvent(QCloseEvent *event) { /* Wait for multitrack video stream to start/finish processing in the background */ if (setupStreamingGuard.valid() && - setupStreamingGuard.wait_for(std::chrono::seconds{0}) != - std::future_status::ready) { + setupStreamingGuard.wait_for(std::chrono::seconds{0}) != std::future_status::ready) { QTimer::singleShot(1000, this, &OBSBasic::close); event->ignore(); return; @@ -5420,20 +4805,16 @@ void OBSBasic::closeEvent(QCloseEvent *event) #endif if (isVisible()) - config_set_string(App()->GetUserConfig(), "BasicWindow", - "geometry", + config_set_string(App()->GetUserConfig(), "BasicWindow", "geometry", saveGeometry().toBase64().constData()); - bool confirmOnExit = config_get_bool(App()->GetUserConfig(), "General", - "ConfirmOnExit"); + bool confirmOnExit = config_get_bool(App()->GetUserConfig(), "General", "ConfirmOnExit"); - if (confirmOnExit && outputHandler && outputHandler->Active() && - !clearingFailed) { + if (confirmOnExit && outputHandler && outputHandler->Active() && !clearingFailed) { SetShowing(true); - QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("ConfirmExit.Title"), - QTStr("ConfirmExit.Text")); + QMessageBox::StandardButton button = + OBSMessageBox::question(this, QTStr("ConfirmExit.Title"), QTStr("ConfirmExit.Text")); if (button == QMessageBox::No) { event->ignore(); @@ -5492,8 +4873,7 @@ void OBSBasic::closeEvent(QCloseEvent *event) delete extraBrowsers; - config_set_string(App()->GetUserConfig(), "BasicWindow", "DockState", - saveState().toBase64().constData()); + config_set_string(App()->GetUserConfig(), "BasicWindow", "DockState", saveState().toBase64().constData()); #ifdef BROWSER_AVAILABLE if (cef) @@ -5525,14 +4905,12 @@ bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *) const MSG &msg = *static_cast(message); switch (msg.message) { case WM_MOVE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnMove(); } break; case WM_DISPLAYCHANGE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnDisplayChange(); } } @@ -5546,20 +4924,17 @@ bool OBSBasic::nativeEvent(const QByteArray &, void *message, qintptr *) void OBSBasic::changeEvent(QEvent *event) { if (event->type() == QEvent::WindowStateChange) { - QWindowStateChangeEvent *stateEvent = - (QWindowStateChangeEvent *)event; + QWindowStateChangeEvent *stateEvent = (QWindowStateChangeEvent *)event; if (isMinimized()) { - if (trayIcon && trayIcon->isVisible() && - sysTrayMinimizeToTray()) { + if (trayIcon && trayIcon->isVisible() && sysTrayMinimizeToTray()) { ToggleShowHide(); return; } if (previewEnabled) EnablePreviewDisplay(false); - } else if (stateEvent->oldState() & Qt::WindowMinimized && - isVisible()) { + } else if (stateEvent->oldState() & Qt::WindowMinimized && isVisible()) { if (previewEnabled) EnablePreviewDisplay(true); } @@ -5568,21 +4943,13 @@ void OBSBasic::changeEvent(QEvent *event) void OBSBasic::on_actionShow_Recordings_triggered() { - const char *mode = - config_get_string(activeConfiguration, "Output", "Mode"); - const char *type = - config_get_string(activeConfiguration, "AdvOut", "RecType"); - const char *adv_path = - strcmp(type, "Standard") - ? config_get_string(activeConfiguration, "AdvOut", - "FFFilePath") - : config_get_string(activeConfiguration, "AdvOut", - "RecFilePath"); - const char *path = strcmp(mode, "Advanced") - ? config_get_string(activeConfiguration, - "SimpleOutput", - "FilePath") - : adv_path; + const char *mode = config_get_string(activeConfiguration, "Output", "Mode"); + const char *type = config_get_string(activeConfiguration, "AdvOut", "RecType"); + const char *adv_path = strcmp(type, "Standard") + ? config_get_string(activeConfiguration, "AdvOut", "FFFilePath") + : config_get_string(activeConfiguration, "AdvOut", "RecFilePath"); + const char *path = strcmp(mode, "Advanced") ? config_get_string(activeConfiguration, "SimpleOutput", "FilePath") + : adv_path; QDesktopServices::openUrl(QUrl::fromLocalFile(path)); } @@ -5594,14 +4961,9 @@ void OBSBasic::on_actionRemux_triggered() return; } - const char *mode = - config_get_string(activeConfiguration, "Output", "Mode"); - const char *path = strcmp(mode, "Advanced") - ? config_get_string(activeConfiguration, - "SimpleOutput", - "FilePath") - : config_get_string(activeConfiguration, - "AdvOut", "RecFilePath"); + const char *mode = config_get_string(activeConfiguration, "Output", "Mode"); + const char *path = strcmp(mode, "Advanced") ? config_get_string(activeConfiguration, "SimpleOutput", "FilePath") + : config_get_string(activeConfiguration, "AdvOut", "RecFilePath"); OBSRemux *remuxDlg; remuxDlg = new OBSRemux(path, this); @@ -5617,8 +4979,7 @@ void OBSBasic::on_action_Settings_triggered() * because we could be inside of an Auth::LoadUI call. Keep trying * once per second until we've exit any known sub-loops. */ if (os_atomic_load_long(&insideEventLoop) != 0) { - QTimer::singleShot(1000, this, - &OBSBasic::on_action_Settings_triggered); + QTimer::singleShot(1000, this, &OBSBasic::on_action_Settings_triggered); return; } @@ -5636,8 +4997,8 @@ void OBSBasic::on_action_Settings_triggered() settings_already_executing = false; if (restart) { - QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("Restart"), QTStr("NeedsRestart")); + QMessageBox::StandardButton button = + OBSMessageBox::question(this, QTStr("Restart"), QTStr("NeedsRestart")); if (button == QMessageBox::Yes) close(); @@ -5649,10 +5010,8 @@ void OBSBasic::on_action_Settings_triggered() void OBSBasic::on_actionShowMacPermissions_triggered() { #ifdef __APPLE__ - OBSPermissions check(this, CheckPermission(kScreenCapture), - CheckPermission(kVideoDeviceAccess), - CheckPermission(kAudioDeviceAccess), - CheckPermission(kAccessibility)); + OBSPermissions check(this, CheckPermission(kScreenCapture), CheckPermission(kVideoDeviceAccess), + CheckPermission(kAudioDeviceAccess), CheckPermission(kAccessibility)); check.exec(); #endif } @@ -5675,9 +5034,8 @@ void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files) /* Only raise dialog if triggered manually */ if (!disableSaving) - OBSMessageBox::information( - this, QTStr("MissingFiles.NoMissing.Title"), - QTStr("MissingFiles.NoMissing.Text")); + OBSMessageBox::information(this, QTStr("MissingFiles.NoMissing.Title"), + QTStr("MissingFiles.NoMissing.Text")); } } @@ -5701,8 +5059,7 @@ void OBSBasic::on_actionAdvAudioProperties_triggered() return; } - bool iconsVisible = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "ShowSourceIcons"); + bool iconsVisible = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ShowSourceIcons"); advAudioWindow = new OBSBasicAdvAudio(this); advAudioWindow->show(); @@ -5718,15 +5075,14 @@ void OBSBasic::on_actionMixerToolbarAdvAudio_triggered() void OBSBasic::on_actionMixerToolbarMenu_triggered() { QAction unhideAllAction(QTStr("UnhideAll"), this); - connect(&unhideAllAction, &QAction::triggered, this, - &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection); + connect(&unhideAllAction, &QAction::triggered, this, &OBSBasic::UnhideAllAudioControls, Qt::DirectConnection); QAction toggleControlLayoutAction(QTStr("VerticalLayout"), this); toggleControlLayoutAction.setCheckable(true); - toggleControlLayoutAction.setChecked(config_get_bool( - App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); - connect(&toggleControlLayoutAction, &QAction::changed, this, - &OBSBasic::ToggleVolControlLayout, Qt::DirectConnection); + toggleControlLayoutAction.setChecked( + config_get_bool(App()->GetUserConfig(), "BasicWindow", "VerticalVolControl")); + connect(&toggleControlLayoutAction, &QAction::changed, this, &OBSBasic::ToggleVolControlLayout, + Qt::DirectConnection); QMenu popup; popup.addAction(&unhideAllAction); @@ -5735,8 +5091,7 @@ void OBSBasic::on_actionMixerToolbarMenu_triggered() popup.exec(QCursor::pos()); } -void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current, - QListWidgetItem *) +void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current, QListWidgetItem *) { OBSSource source; @@ -5790,19 +5145,12 @@ QList OBSBasic::GetProjectorMenuMonitorsFormatted() name = name.simplified(); if (name.length() == 0) { - name = QString("%1 %2") - .arg(QTStr("Display")) - .arg(QString::number(i + 1)); + name = QString("%1 %2").arg(QTStr("Display")).arg(QString::number(i + 1)); } - QString str = - QString("%1: %2x%3 @ %4,%5") - .arg(name, - QString::number(screenGeometry.width() * - ratio), - QString::number(screenGeometry.height() * - ratio), - QString::number(screenGeometry.x()), - QString::number(screenGeometry.y())); + QString str = QString("%1: %2x%3 @ %4,%5") + .arg(name, QString::number(screenGeometry.width() * ratio), + QString::number(screenGeometry.height() * ratio), + QString::number(screenGeometry.x()), QString::number(screenGeometry.y())); projectorsFormatted.push_back(str); } return projectorsFormatted; @@ -5815,24 +5163,18 @@ void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos) QMenu popup(this); QMenu order(QTStr("Basic.MainMenu.Edit.Order"), this); - popup.addAction(QTStr("Add"), this, - &OBSBasic::on_actionAddScene_triggered); + popup.addAction(QTStr("Add"), this, &OBSBasic::on_actionAddScene_triggered); if (item) { QAction *copyFilters = new QAction(QTStr("Copy.Filters"), this); copyFilters->setEnabled(false); - connect(copyFilters, &QAction::triggered, this, - &OBSBasic::SceneCopyFilters); - QAction *pasteFilters = - new QAction(QTStr("Paste.Filters"), this); - pasteFilters->setEnabled( - !obs_weak_source_expired(copyFiltersSource)); - connect(pasteFilters, &QAction::triggered, this, - &OBSBasic::ScenePasteFilters); + connect(copyFilters, &QAction::triggered, this, &OBSBasic::SceneCopyFilters); + QAction *pasteFilters = new QAction(QTStr("Paste.Filters"), this); + pasteFilters->setEnabled(!obs_weak_source_expired(copyFiltersSource)); + connect(pasteFilters, &QAction::triggered, this, &OBSBasic::ScenePasteFilters); popup.addSeparator(); - popup.addAction(QTStr("Duplicate"), this, - &OBSBasic::DuplicateSelectedScene); + popup.addAction(QTStr("Duplicate"), this, &OBSBasic::DuplicateSelectedScene); popup.addAction(copyFilters); popup.addAction(pasteFilters); popup.addSeparator(); @@ -5840,34 +5182,27 @@ void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos) popup.addAction(ui->actionRemoveScene); popup.addSeparator(); - order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this, - &OBSBasic::on_actionSceneUp_triggered); - order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"), - this, &OBSBasic::on_actionSceneDown_triggered); + order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveUp"), this, &OBSBasic::on_actionSceneUp_triggered); + order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveDown"), this, + &OBSBasic::on_actionSceneDown_triggered); order.addSeparator(); - order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"), - this, &OBSBasic::MoveSceneToTop); - order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"), - this, &OBSBasic::MoveSceneToBottom); + order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToTop"), this, &OBSBasic::MoveSceneToTop); + order.addAction(QTStr("Basic.MainMenu.Edit.Order.MoveToBottom"), this, &OBSBasic::MoveSceneToBottom); popup.addMenu(&order); popup.addSeparator(); delete sceneProjectorMenu; sceneProjectorMenu = new QMenu(QTStr("SceneProjector")); - AddProjectorMenuMonitors(sceneProjectorMenu, this, - &OBSBasic::OpenSceneProjector); + AddProjectorMenuMonitors(sceneProjectorMenu, this, &OBSBasic::OpenSceneProjector); popup.addMenu(sceneProjectorMenu); - QAction *sceneWindow = popup.addAction( - QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow); + QAction *sceneWindow = popup.addAction(QTStr("SceneWindow"), this, &OBSBasic::OpenSceneWindow); popup.addAction(sceneWindow); - popup.addAction(QTStr("Screenshot.Scene"), this, - &OBSBasic::ScreenshotScene); + popup.addAction(QTStr("Screenshot.Scene"), this, &OBSBasic::ScreenshotScene); popup.addSeparator(); - popup.addAction(QTStr("Filters"), this, - &OBSBasic::OpenSceneFilters); + popup.addAction(QTStr("Filters"), this, &OBSBasic::OpenSceneFilters); popup.addSeparator(); @@ -5877,12 +5212,10 @@ void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos) /* ---------------------- */ - QAction *multiviewAction = - popup.addAction(QTStr("ShowInMultiview")); + QAction *multiviewAction = popup.addAction(QTStr("ShowInMultiview")); OBSSource source = GetCurrentSceneSource(); - OBSDataAutoRelease data = - obs_source_get_private_settings(source); + OBSDataAutoRelease data = obs_source_get_private_settings(source); obs_data_set_default_bool(data, "show_in_multiview", true); bool show = obs_data_get_bool(data, "show_in_multiview"); @@ -5891,14 +5224,12 @@ void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos) multiviewAction->setChecked(show); auto showInMultiview = [](OBSData data) { - bool show = - obs_data_get_bool(data, "show_in_multiview"); + bool show = obs_data_get_bool(data, "show_in_multiview"); obs_data_set_bool(data, "show_in_multiview", !show); OBSProjector::UpdateMultiviewProjectors(); }; - connect(multiviewAction, &QAction::triggered, - std::bind(showInMultiview, data.Get())); + connect(multiviewAction, &QAction::triggered, std::bind(showInMultiview, data.Get())); copyFilters->setEnabled(obs_source_filter_count(source) > 0); } @@ -5907,11 +5238,8 @@ void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos) bool grid = ui->scenes->GetGridMode(); - QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode") - : QTStr("Basic.Main.GridMode"), - this); - connect(gridAction, &QAction::triggered, this, - &OBSBasic::GridActionClicked); + QAction *gridAction = new QAction(grid ? QTStr("Basic.Main.ListMode") : QTStr("Basic.Main.GridMode"), this); + connect(gridAction, &QAction::triggered, this, &OBSBasic::GridActionClicked); popup.addAction(gridAction); popup.exec(QCursor::pos()); @@ -5920,15 +5248,13 @@ void OBSBasic::on_scenes_customContextMenuRequested(const QPoint &pos) void OBSBasic::on_actionSceneListMode_triggered() { ui->scenes->SetGridMode(false); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", - false); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", false); } void OBSBasic::on_actionSceneGridMode_triggered() { ui->scenes->SetGridMode(true); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", - true); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", true); } void OBSBasic::GridActionClicked() @@ -5941,8 +5267,7 @@ void OBSBasic::GridActionClicked() else ui->actionSceneListMode->setChecked(true); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", - gridMode); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", gridMode); } void OBSBasic::on_actionAddScene_triggered() @@ -5957,24 +5282,19 @@ void OBSBasic::on_actionAddScene_triggered() placeHolderText = format.arg(++i); } - bool accepted = NameDialog::AskForName( - this, QTStr("Basic.Main.AddSceneDlg.Title"), - QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText); + bool accepted = NameDialog::AskForName(this, QTStr("Basic.Main.AddSceneDlg.Title"), + QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText); if (accepted) { if (name.empty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); on_actionAddScene_triggered(); return; } - OBSSourceAutoRelease source = - obs_get_source_by_name(name.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(name.c_str()); if (source) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); on_actionAddScene_triggered(); return; @@ -5989,13 +5309,11 @@ void OBSBasic::on_actionAddScene_triggered() }; auto redo_fn = [this](const std::string &data) { - OBSSceneAutoRelease scene = - obs_scene_create(data.c_str()); + OBSSceneAutoRelease scene = obs_scene_create(data.c_str()); obs_source_t *source = obs_scene_get_source(scene); SetCurrentScene(source, true); }; - undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())), - undo_fn, redo_fn, name, name); + undo_s.add_action(QTStr("Undo.Add").arg(QString(name.c_str())), undo_fn, redo_fn, name, name); OBSSceneAutoRelease scene = obs_scene_create(name.c_str()); obs_source_t *scene_source = obs_scene_get_source(scene); @@ -6046,8 +5364,7 @@ void OBSBasic::MoveSceneToTop() void OBSBasic::MoveSceneToBottom() { - ChangeSceneIndex(false, ui->scenes->count() - 1, - ui->scenes->count() - 1); + ChangeSceneIndex(false, ui->scenes->count() - 1, ui->scenes->count() - 1); } void OBSBasic::EditSceneItemName() @@ -6059,8 +5376,7 @@ void OBSBasic::EditSceneItemName() void OBSBasic::SetDeinterlacingMode() { QAction *action = reinterpret_cast(sender()); - obs_deinterlace_mode mode = - (obs_deinterlace_mode)action->property("mode").toInt(); + obs_deinterlace_mode mode = (obs_deinterlace_mode)action->property("mode").toInt(); OBSSceneItem sceneItem = GetCurrentSceneItem(); obs_source_t *source = obs_sceneitem_get_source(sceneItem); @@ -6070,8 +5386,7 @@ void OBSBasic::SetDeinterlacingMode() void OBSBasic::SetDeinterlacingOrder() { QAction *action = reinterpret_cast(sender()); - obs_deinterlace_field_order order = - (obs_deinterlace_field_order)action->property("order").toInt(); + obs_deinterlace_field_order order = (obs_deinterlace_field_order)action->property("order").toInt(); OBSSceneItem sceneItem = GetCurrentSceneItem(); obs_source_t *source = obs_sceneitem_get_source(sceneItem); @@ -6080,17 +5395,14 @@ void OBSBasic::SetDeinterlacingOrder() QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source) { - obs_deinterlace_mode deinterlaceMode = - obs_source_get_deinterlace_mode(source); - obs_deinterlace_field_order deinterlaceOrder = - obs_source_get_deinterlace_field_order(source); + obs_deinterlace_mode deinterlaceMode = obs_source_get_deinterlace_mode(source); + obs_deinterlace_field_order deinterlaceOrder = obs_source_get_deinterlace_field_order(source); QAction *action; -#define ADD_MODE(name, mode) \ - action = menu->addAction(QTStr("" name), this, \ - &OBSBasic::SetDeinterlacingMode); \ - action->setProperty("mode", (int)mode); \ - action->setCheckable(true); \ +#define ADD_MODE(name, mode) \ + action = menu->addAction(QTStr("" name), this, &OBSBasic::SetDeinterlacingMode); \ + action->setProperty("mode", (int)mode); \ + action->setCheckable(true); \ action->setChecked(deinterlaceMode == mode); ADD_MODE("Disable", OBS_DEINTERLACE_MODE_DISABLE); @@ -6106,11 +5418,10 @@ QMenu *OBSBasic::AddDeinterlacingMenu(QMenu *menu, obs_source_t *source) menu->addSeparator(); -#define ADD_ORDER(name, order) \ - action = menu->addAction(QTStr("Deinterlacing." name), this, \ - &OBSBasic::SetDeinterlacingOrder); \ - action->setProperty("order", (int)order); \ - action->setCheckable(true); \ +#define ADD_ORDER(name, order) \ + action = menu->addAction(QTStr("Deinterlacing." name), this, &OBSBasic::SetDeinterlacingOrder); \ + action->setProperty("order", (int)order); \ + action->setCheckable(true); \ action->setChecked(deinterlaceOrder == order); ADD_ORDER("TopFieldFirst", OBS_DEINTERLACE_FIELD_ORDER_TOP); @@ -6134,11 +5445,10 @@ QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item) obs_scale_type scaleFilter = obs_sceneitem_get_scale_filter(item); QAction *action; -#define ADD_MODE(name, mode) \ - action = menu->addAction(QTStr("" name), this, \ - &OBSBasic::SetScaleFilter); \ - action->setProperty("mode", (int)mode); \ - action->setCheckable(true); \ +#define ADD_MODE(name, mode) \ + action = menu->addAction(QTStr("" name), this, &OBSBasic::SetScaleFilter); \ + action->setProperty("mode", (int)mode); \ + action->setCheckable(true); \ action->setChecked(scaleFilter == mode); ADD_MODE("Disable", OBS_SCALE_DISABLE); @@ -6155,8 +5465,7 @@ QMenu *OBSBasic::AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item) void OBSBasic::SetBlendingMethod() { QAction *action = reinterpret_cast(sender()); - obs_blending_method method = - (obs_blending_method)action->property("method").toInt(); + obs_blending_method method = (obs_blending_method)action->property("method").toInt(); OBSSceneItem sceneItem = GetCurrentSceneItem(); obs_sceneitem_set_blending_method(sceneItem, method); @@ -6164,15 +5473,13 @@ void OBSBasic::SetBlendingMethod() QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item) { - obs_blending_method blendingMethod = - obs_sceneitem_get_blending_method(item); + obs_blending_method blendingMethod = obs_sceneitem_get_blending_method(item); QAction *action; -#define ADD_MODE(name, method) \ - action = menu->addAction(QTStr("" name), this, \ - &OBSBasic::SetBlendingMethod); \ - action->setProperty("method", (int)method); \ - action->setCheckable(true); \ +#define ADD_MODE(name, method) \ + action = menu->addAction(QTStr("" name), this, &OBSBasic::SetBlendingMethod); \ + action->setProperty("method", (int)method); \ + action->setCheckable(true); \ action->setChecked(blendingMethod == method); ADD_MODE("BlendingMethod.Default", OBS_BLEND_METHOD_DEFAULT); @@ -6185,8 +5492,7 @@ QMenu *OBSBasic::AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item) void OBSBasic::SetBlendingMode() { QAction *action = reinterpret_cast(sender()); - obs_blending_type mode = - (obs_blending_type)action->property("mode").toInt(); + obs_blending_type mode = (obs_blending_type)action->property("mode").toInt(); OBSSceneItem sceneItem = GetCurrentSceneItem(); obs_sceneitem_set_blending_mode(sceneItem, mode); @@ -6197,11 +5503,10 @@ QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item) obs_blending_type blendingMode = obs_sceneitem_get_blending_mode(item); QAction *action; -#define ADD_MODE(name, mode) \ - action = menu->addAction(QTStr("" name), this, \ - &OBSBasic::SetBlendingMode); \ - action->setProperty("mode", (int)mode); \ - action->setCheckable(true); \ +#define ADD_MODE(name, mode) \ + action = menu->addAction(QTStr("" name), this, &OBSBasic::SetBlendingMode); \ + action->setProperty("mode", (int)mode); \ + action->setCheckable(true); \ action->setChecked(blendingMode == mode); ADD_MODE("BlendingMode.Normal", OBS_BLEND_NORMAL); @@ -6216,22 +5521,19 @@ QMenu *OBSBasic::AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item) return menu; } -QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, - QWidgetAction *widgetAction, - ColorSelect *select, +QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction, ColorSelect *select, obs_sceneitem_t *item) { QAction *action; - menu->setStyleSheet(QString( - "*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" - "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" - "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" - "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" - "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" - "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" - "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" - "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}")); + menu->setStyleSheet(QString("*[bgColor=\"1\"]{background-color:rgba(255,68,68,33%);}" + "*[bgColor=\"2\"]{background-color:rgba(255,255,68,33%);}" + "*[bgColor=\"3\"]{background-color:rgba(68,255,68,33%);}" + "*[bgColor=\"4\"]{background-color:rgba(68,255,255,33%);}" + "*[bgColor=\"5\"]{background-color:rgba(68,68,255,33%);}" + "*[bgColor=\"6\"]{background-color:rgba(255,68,255,33%);}" + "*[bgColor=\"7\"]{background-color:rgba(68,68,68,33%);}" + "*[bgColor=\"8\"]{background-color:rgba(255,255,255,33%);}")); obs_data_t *privData = obs_sceneitem_get_private_settings(item); obs_data_release(privData); @@ -6244,8 +5546,7 @@ QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, action->setProperty("bgColor", 0); action->setChecked(preset == 0); - action = menu->addAction(QTStr("CustomColor"), this, - &OBSBasic::ColorChange); + action = menu->addAction(QTStr("CustomColor"), this, &OBSBasic::ColorChange); action->setCheckable(true); action->setProperty("bgColor", 1); action->setChecked(preset == 1); @@ -6257,14 +5558,12 @@ QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, for (int i = 1; i < 9; i++) { stringstream button; button << "preset" << i; - QPushButton *colorButton = - select->findChild(button.str().c_str()); + QPushButton *colorButton = select->findChild(button.str().c_str()); if (preset == i + 1) colorButton->setStyleSheet("border: 2px solid black"); colorButton->setProperty("bgColor", i); - select->connect(colorButton, &QPushButton::released, this, - &OBSBasic::ColorChange); + select->connect(colorButton, &QPushButton::released, this, &OBSBasic::ColorChange); } menu->addAction(widgetAction); @@ -6272,9 +5571,7 @@ QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, return menu; } -ColorSelect::ColorSelect(QWidget *parent) - : QWidget(parent), - ui(new Ui::ColorSelect) +ColorSelect::ColorSelect(QWidget *parent) : QWidget(parent), ui(new Ui::ColorSelect) { ui->setupUi(this); } @@ -6293,12 +5590,10 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) delete deinterlaceMenu; if (preview) { - QAction *action = popup.addAction( - QTStr("Basic.Main.PreviewConextMenu.Enable"), this, - &OBSBasic::TogglePreview); + QAction *action = + popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"), this, &OBSBasic::TogglePreview); action->setCheckable(true); - action->setChecked( - obs_display_enabled(ui->preview->GetDisplay())); + action->setChecked(obs_display_enabled(ui->preview->GetDisplay())); if (IsPreviewProgramMode()) action->setEnabled(false); @@ -6306,19 +5601,15 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) popup.addMenu(ui->scalingMenu); previewProjectorSource = new QMenu(QTStr("PreviewProjector")); - AddProjectorMenuMonitors(previewProjectorSource, this, - &OBSBasic::OpenPreviewProjector); + AddProjectorMenuMonitors(previewProjectorSource, this, &OBSBasic::OpenPreviewProjector); popup.addMenu(previewProjectorSource); - QAction *previewWindow = - popup.addAction(QTStr("PreviewWindow"), this, - &OBSBasic::OpenPreviewWindow); + QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this, &OBSBasic::OpenPreviewWindow); popup.addAction(previewWindow); - popup.addAction(QTStr("Screenshot.Preview"), this, - &OBSBasic::ScreenshotScene); + popup.addAction(QTStr("Screenshot.Preview"), this, &OBSBasic::ScreenshotScene); popup.addSeparator(); } @@ -6329,13 +5620,11 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) if (ui->sources->MultipleBaseSelected()) { popup.addSeparator(); - popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources, - &SourceTree::GroupSelectedItems); + popup.addAction(QTStr("Basic.Main.GroupItems"), ui->sources, &SourceTree::GroupSelectedItems); } else if (ui->sources->GroupsSelected()) { popup.addSeparator(); - popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources, - &SourceTree::UngroupSelectedGroups); + popup.addAction(QTStr("Basic.Main.Ungroup"), ui->sources, &SourceTree::UngroupSelectedGroups); } popup.addSeparator(); @@ -6356,16 +5645,14 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) OBSSceneItem sceneItem = ui->sources->Get(idx); obs_source_t *source = obs_sceneitem_get_source(sceneItem); uint32_t flags = obs_source_get_output_flags(source); - bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) == - OBS_SOURCE_ASYNC_VIDEO; + bool isAsyncVideo = (flags & OBS_SOURCE_ASYNC_VIDEO) == OBS_SOURCE_ASYNC_VIDEO; bool hasAudio = (flags & OBS_SOURCE_AUDIO) == OBS_SOURCE_AUDIO; bool hasVideo = (flags & OBS_SOURCE_VIDEO) == OBS_SOURCE_VIDEO; colorMenu = new QMenu(QTStr("ChangeBG")); colorWidgetAction = new QWidgetAction(colorMenu); colorSelect = new ColorSelect(colorMenu); - popup.addMenu(AddBackgroundColorMenu( - colorMenu, colorWidgetAction, colorSelect, sceneItem)); + popup.addMenu(AddBackgroundColorMenu(colorMenu, colorWidgetAction, colorSelect, sceneItem)); popup.addAction(renameSource); popup.addAction(ui->actionRemoveSource); popup.addSeparator(); @@ -6379,17 +5666,15 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) if (hasAudio) { QAction *actionHideMixer = - popup.addAction(QTStr("HideMixer"), this, - &OBSBasic::ToggleHideMixer); + popup.addAction(QTStr("HideMixer"), this, &OBSBasic::ToggleHideMixer); actionHideMixer->setCheckable(true); actionHideMixer->setChecked(SourceMixerHidden(source)); popup.addSeparator(); } if (hasVideo) { - QAction *resizeOutput = popup.addAction( - QTStr("ResizeOutputSizeOfSource"), this, - &OBSBasic::ResizeOutputSizeOfSource); + QAction *resizeOutput = popup.addAction(QTStr("ResizeOutputSizeOfSource"), this, + &OBSBasic::ResizeOutputSizeOfSource); int width = obs_source_get_width(source); int height = obs_source_get_height(source); @@ -6400,19 +5685,14 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) resizeOutput->setEnabled(false); scaleFilteringMenu = new QMenu(QTStr("ScaleFiltering")); - popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu, - sceneItem)); + popup.addMenu(AddScaleFilteringMenu(scaleFilteringMenu, sceneItem)); blendingModeMenu = new QMenu(QTStr("BlendingMode")); - popup.addMenu(AddBlendingModeMenu(blendingModeMenu, - sceneItem)); + popup.addMenu(AddBlendingModeMenu(blendingModeMenu, sceneItem)); blendingMethodMenu = new QMenu(QTStr("BlendingMethod")); - popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu, - sceneItem)); + popup.addMenu(AddBlendingMethodMenu(blendingMethodMenu, sceneItem)); if (isAsyncVideo) { - deinterlaceMenu = - new QMenu(QTStr("Deinterlacing")); - popup.addMenu(AddDeinterlacingMenu( - deinterlaceMenu, source)); + deinterlaceMenu = new QMenu(QTStr("Deinterlacing")); + popup.addMenu(AddDeinterlacingMenu(deinterlaceMenu, source)); } popup.addSeparator(); @@ -6422,28 +5702,21 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) popup.addSeparator(); sourceProjector = new QMenu(QTStr("SourceProjector")); - AddProjectorMenuMonitors( - sourceProjector, this, - &OBSBasic::OpenSourceProjector); + AddProjectorMenuMonitors(sourceProjector, this, &OBSBasic::OpenSourceProjector); popup.addMenu(sourceProjector); - popup.addAction(QTStr("SourceWindow"), this, - &OBSBasic::OpenSourceWindow); + popup.addAction(QTStr("SourceWindow"), this, &OBSBasic::OpenSourceWindow); - popup.addAction(QTStr("Screenshot.Source"), this, - &OBSBasic::ScreenshotSelectedSource); + popup.addAction(QTStr("Screenshot.Source"), this, &OBSBasic::ScreenshotSelectedSource); } popup.addSeparator(); if (flags & OBS_SOURCE_INTERACTION) - popup.addAction(QTStr("Interact"), this, - &OBSBasic::on_actionInteract_triggered); + popup.addAction(QTStr("Interact"), this, &OBSBasic::on_actionInteract_triggered); - popup.addAction(QTStr("Filters"), this, - [&]() { OpenFilters(); }); - QAction *action = popup.addAction( - QTStr("Properties"), this, - &OBSBasic::on_actionSourceProperties_triggered); + popup.addAction(QTStr("Filters"), this, [&]() { OpenFilters(); }); + QAction *action = + popup.addAction(QTStr("Properties"), this, &OBSBasic::on_actionSourceProperties_triggered); action->setEnabled(obs_source_configurable(source)); } @@ -6465,8 +5738,7 @@ void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem) if (IsPreviewProgramMode()) { bool doubleClickSwitch = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "TransitionOnDoubleClick"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "TransitionOnDoubleClick"); if (doubleClickSwitch) TransitionClicked(); @@ -6515,20 +5787,17 @@ QMenu *OBSBasic::CreateAddSourcePopupMenu() QList actions = menu->actions(); for (QAction *menuAction : actions) { - if (menuAction->text().compare( - name, Qt::CaseInsensitive) >= 0) + if (menuAction->text().compare(name, Qt::CaseInsensitive) >= 0) return menuAction; } return (QAction *)nullptr; }; - auto addSource = [this, getActionAfter](QMenu *popup, const char *type, - const char *name) { + auto addSource = [this, getActionAfter](QMenu *popup, const char *type, const char *name) { QString qname = QT_UTF8(name); QAction *popupItem = new QAction(qname, this); - connect(popupItem, &QAction::triggered, - [this, type]() { AddSource(type); }); + connect(popupItem, &QAction::triggered, [this, type]() { AddSource(type); }); QIcon icon; @@ -6564,8 +5833,7 @@ QMenu *OBSBasic::CreateAddSourcePopupMenu() popup->addSeparator(); QAction *addGroup = new QAction(QTStr("Group"), this); addGroup->setIcon(GetGroupIcon()); - connect(addGroup, &QAction::triggered, - [this]() { AddSource("group"); }); + connect(addGroup, &QAction::triggered, [this]() { AddSource("group"); }); popup->addAction(addGroup); if (!foundDeprecated) { @@ -6589,9 +5857,8 @@ void OBSBasic::AddSourcePopupMenu(const QPoint &pos) { if (!GetCurrentScene()) { // Tell the user he needs a scene first (help beginners). - OBSMessageBox::information( - this, QTStr("Basic.Main.AddSourceHelp.Title"), - QTStr("Basic.Main.AddSourceHelp.Text")); + OBSMessageBox::information(this, QTStr("Basic.Main.AddSourceHelp.Title"), + QTStr("Basic.Main.AddSourceHelp.Text")); return; } @@ -6607,8 +5874,7 @@ void OBSBasic::on_actionAddSource_triggered() static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param) { - vector &items = - *reinterpret_cast *>(param); + vector &items = *reinterpret_cast *>(param); if (obs_sceneitem_selected(item)) { items.emplace_back(item); @@ -6618,8 +5884,7 @@ static bool remove_items(obs_scene_t *, obs_sceneitem_t *item, void *param) return true; }; -OBSData OBSBasic::BackupScene(obs_scene_t *scene, - std::vector *sources) +OBSData OBSBasic::BackupScene(obs_scene_t *scene, std::vector *sources) { OBSDataArrayAutoRelease undo_array = obs_data_array_create(); @@ -6633,8 +5898,7 @@ OBSData OBSBasic::BackupScene(obs_scene_t *scene, } } - OBSDataAutoRelease scene_data = - obs_save_source(obs_scene_get_source(scene)); + OBSDataAutoRelease scene_data = obs_save_source(obs_scene_get_source(scene)); obs_data_array_push_back(undo_array, scene_data); OBSDataAutoRelease data = obs_data_create(); @@ -6651,14 +5915,11 @@ static bool add_source_enum(obs_scene_t *, obs_sceneitem_t *item, void *p) return true; } -void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, - OBSData undo_data, OBSData redo_data) +void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, OBSData undo_data, OBSData redo_data) { auto undo_redo = [this](const std::string &json) { - OBSDataAutoRelease base = - obs_data_create_from_json(json.c_str()); - OBSDataArrayAutoRelease array = - obs_data_get_array(base, "array"); + OBSDataAutoRelease base = obs_data_create_from_json(json.c_str()); + OBSDataArrayAutoRelease array = obs_data_get_array(base, "array"); std::vector sources; std::vector old_sources; @@ -6670,8 +5931,7 @@ void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, OBSDataAutoRelease data = obs_data_array_item(array, i); const char *name = obs_data_get_string(data, "name"); - OBSSourceAutoRelease source = - obs_get_source_by_name(name); + OBSSourceAutoRelease source = obs_get_source_by_name(name); if (!source) source = obs_load_source(data); @@ -6679,13 +5939,10 @@ void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, /* update scene/group settings to restore their * contents to their saved settings */ - obs_scene_t *scene = - obs_group_or_scene_from_source(source); + obs_scene_t *scene = obs_group_or_scene_from_source(source); if (scene) { - obs_scene_enum_items(scene, add_source_enum, - &old_sources); - OBSDataAutoRelease scene_settings = - obs_data_get_obj(data, "settings"); + obs_scene_enum_items(scene, add_source_enum, &old_sources); + OBSDataAutoRelease scene_settings = obs_data_get_obj(data, "settings"); obs_source_update(source, scene_settings); } } @@ -6700,8 +5957,7 @@ void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, const char *undo_json = obs_data_get_last_json(undo_data); const char *redo_json = obs_data_get_last_json(redo_data); - undo_s.add_action(action_name, undo_redo, undo_redo, undo_json, - redo_json); + undo_s.add_action(action_name, undo_redo, undo_redo, undo_json, redo_json); } void OBSBasic::on_actionRemoveSource_triggered() @@ -6721,13 +5977,11 @@ void OBSBasic::on_actionRemoveSource_triggered() bool confirmed = false; if (items.size() > 1) { - QString text = QTStr("ConfirmRemove.TextMultiple") - .arg(QString::number(items.size())); + QString text = QTStr("ConfirmRemove.TextMultiple").arg(QString::number(items.size())); QMessageBox remove_items(this); remove_items.setText(text); - QPushButton *Yes = remove_items.addButton(QTStr("Yes"), - QMessageBox::YesRole); + QPushButton *Yes = remove_items.addButton(QTStr("Yes"), QMessageBox::YesRole); remove_items.setDefaultButton(Yes); remove_items.addButton(QTStr("No"), QMessageBox::NoRole); remove_items.setIcon(QMessageBox::Question); @@ -6765,12 +6019,10 @@ void OBSBasic::on_actionRemoveSource_triggered() QString action_name; if (items.size() > 1) { - action_name = QTStr("Undo.Sources.Multi") - .arg(QString::number(items.size())); + action_name = QTStr("Undo.Sources.Multi").arg(QString::number(items.size())); } else { QString str = QTStr("Undo.Delete"); - action_name = str.arg(obs_source_get_name( - obs_sceneitem_get_source(items[0]))); + action_name = str.arg(obs_source_get_name(obs_sceneitem_get_source(items[0]))); } CreateSceneUndoRedoAction(action_name, undo_data, redo_data); @@ -6794,8 +6046,7 @@ void OBSBasic::on_actionSourceProperties_triggered() CreatePropertiesWindow(source); } -void OBSBasic::MoveSceneItem(enum obs_order_movement movement, - const QString &action_name) +void OBSBasic::MoveSceneItem(enum obs_order_movement movement, const QString &action_name) { OBSSceneItem item = GetCurrentSceneItem(); obs_source_t *source = obs_sceneitem_get_source(item); @@ -6806,20 +6057,17 @@ void OBSBasic::MoveSceneItem(enum obs_order_movement movement, OBSScene scene = GetCurrentScene(); std::vector sources; if (scene != obs_sceneitem_get_scene(item)) - sources.push_back( - obs_scene_get_source(obs_sceneitem_get_scene(item))); + sources.push_back(obs_scene_get_source(obs_sceneitem_get_scene(item))); OBSData undo_data = BackupScene(scene, &sources); obs_sceneitem_set_order(item, movement); const char *source_name = obs_source_get_name(source); - const char *scene_name = - obs_source_get_name(obs_scene_get_source(scene)); + const char *scene_name = obs_source_get_name(obs_scene_get_source(scene)); OBSData redo_data = BackupScene(scene, &sources); - CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name), - undo_data, redo_data); + CreateSceneUndoRedoAction(action_name.arg(source_name, scene_name), undo_data, redo_data); } void OBSBasic::on_actionSourceUp_triggered() @@ -6885,24 +6133,20 @@ void OBSBasic::UploadLog(const char *subdir, const char *file, const bool crash) #endif stringstream ss; - ss << "OBS " << App()->GetVersionString(false) - << " log file uploaded at " << CurrentDateTimeString() << "\n\n" + ss << "OBS " << App()->GetVersionString(false) << " log file uploaded at " << CurrentDateTimeString() << "\n\n" << fileString; if (logUploadThread) { logUploadThread->wait(); } - RemoteTextThread *thread = new RemoteTextThread( - "https://obsproject.com/logs/upload", "text/plain", ss.str()); + RemoteTextThread *thread = new RemoteTextThread("https://obsproject.com/logs/upload", "text/plain", ss.str()); logUploadThread.reset(thread); if (crash) { - connect(thread, &RemoteTextThread::Result, this, - &OBSBasic::crashUploadFinished); + connect(thread, &RemoteTextThread::Result, this, &OBSBasic::crashUploadFinished); } else { - connect(thread, &RemoteTextThread::Result, this, - &OBSBasic::logUploadFinished); + connect(thread, &RemoteTextThread::Result, this, &OBSBasic::logUploadFinished); } logUploadThread->start(); } @@ -6933,9 +6177,7 @@ void OBSBasic::on_actionViewCurrentLog_triggered() logView = new OBSLogViewer(); logView->show(); - logView->setWindowState( - (logView->windowState() & ~Qt::WindowMinimized) | - Qt::WindowActive); + logView->setWindowState((logView->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); logView->activateWindow(); logView->raise(); } @@ -6977,9 +6219,7 @@ void OBSBasic::on_actionRepair_triggered() void OBSBasic::on_actionRestartSafe_triggered() { QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("Restart"), - safe_mode ? QTStr("SafeMode.RestartNormal") - : QTStr("SafeMode.Restart")); + this, QTStr("Restart"), safe_mode ? QTStr("SafeMode.RestartNormal") : QTStr("SafeMode.Restart")); if (button == QMessageBox::Yes) { restart = safe_mode; @@ -6996,9 +6236,7 @@ void OBSBasic::logUploadFinished(const QString &text, const QString &error) #endif if (text.isEmpty()) { - OBSMessageBox::critical( - this, QTStr("LogReturnDialog.ErrorUploadingLog"), - error); + OBSMessageBox::critical(this, QTStr("LogReturnDialog.ErrorUploadingLog"), error); return; } openLogDialog(text, false); @@ -7012,9 +6250,7 @@ void OBSBasic::crashUploadFinished(const QString &text, const QString &error) #endif if (text.isEmpty()) { - OBSMessageBox::critical( - this, QTStr("LogReturnDialog.ErrorUploadingLog"), - error); + OBSMessageBox::critical(this, QTStr("LogReturnDialog.ErrorUploadingLog"), error); return; } openLogDialog(text, true); @@ -7023,8 +6259,7 @@ void OBSBasic::crashUploadFinished(const QString &text, const QString &error) void OBSBasic::openLogDialog(const QString &text, const bool crash) { - OBSDataAutoRelease returnData = - obs_data_create_from_json(QT_TO_UTF8(text)); + OBSDataAutoRelease returnData = obs_data_create_from_json(QT_TO_UTF8(text)); string resURL = obs_data_get_string(returnData, "url"); QString logURL = resURL.c_str(); @@ -7032,8 +6267,7 @@ void OBSBasic::openLogDialog(const QString &text, const bool crash) logDialog.exec(); } -static void RenameListItem(OBSBasic *parent, QListWidget *listWidget, - obs_source_t *source, const string &name) +static void RenameListItem(OBSBasic *parent, QListWidget *listWidget, obs_source_t *source, const string &name) { const char *prevName = obs_source_get_name(source); if (name == prevName) @@ -7046,32 +6280,23 @@ static void RenameListItem(OBSBasic *parent, QListWidget *listWidget, listItem->setText(QT_UTF8(prevName)); if (foundSource) { - OBSMessageBox::warning(parent, - QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(parent, QTStr("NameExists.Title"), QTStr("NameExists.Text")); } else if (name.empty()) { - OBSMessageBox::warning(parent, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(parent, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); } } else { - auto undo = [prev = std::string(prevName)]( - const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(data.c_str()); + auto undo = [prev = std::string(prevName)](const std::string &data) { + OBSSourceAutoRelease source = obs_get_source_by_uuid(data.c_str()); obs_source_set_name(source, prev.c_str()); }; auto redo = [name](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_uuid(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(data.c_str()); obs_source_set_name(source, name.c_str()); }; std::string source_uuid(obs_source_get_uuid(source)); - parent->undo_s.add_action( - QTStr("Undo.Rename").arg(name.c_str()), undo, redo, - source_uuid, source_uuid); + parent->undo_s.add_action(QTStr("Undo.Rename").arg(name.c_str()), undo, redo, source_uuid, source_uuid); listItem->setText(QT_UTF8(name.c_str())); obs_source_set_name(source, name.c_str()); @@ -7139,28 +6364,19 @@ void OBSBasic::OpenSceneFilters() CreateFiltersWindow(source); } -#define RECORDING_START \ - "==== Recording Start ===============================================" -#define RECORDING_STOP \ - "==== Recording Stop ================================================" -#define REPLAY_BUFFER_START \ - "==== Replay Buffer Start ===========================================" -#define REPLAY_BUFFER_STOP \ - "==== Replay Buffer Stop ============================================" -#define STREAMING_START \ - "==== Streaming Start ===============================================" -#define STREAMING_STOP \ - "==== Streaming Stop ================================================" -#define VIRTUAL_CAM_START \ - "==== Virtual Camera Start ==========================================" -#define VIRTUAL_CAM_STOP \ - "==== Virtual Camera Stop ===========================================" +#define RECORDING_START "==== Recording Start ===============================================" +#define RECORDING_STOP "==== Recording Stop ================================================" +#define REPLAY_BUFFER_START "==== Replay Buffer Start ===========================================" +#define REPLAY_BUFFER_STOP "==== Replay Buffer Stop ============================================" +#define STREAMING_START "==== Streaming Start ===============================================" +#define STREAMING_STOP "==== Streaming Stop ================================================" +#define VIRTUAL_CAM_START "==== Virtual Camera Start ==========================================" +#define VIRTUAL_CAM_STOP "==== Virtual Camera Stop ===========================================" void OBSBasic::DisplayStreamStartError() { - QString message = !outputHandler->lastError.empty() - ? QTStr(outputHandler->lastError.c_str()) - : QTStr("Output.StartFailedGeneric"); + QString message = !outputHandler->lastError.empty() ? QTStr(outputHandler->lastError.c_str()) + : QTStr("Output.StartFailedGeneric"); emit StreamingStopped(); @@ -7173,10 +6389,8 @@ void OBSBasic::DisplayStreamStartError() } #ifdef YOUTUBE_ENABLED -void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id, - const QString &stream_id, - const QString &key, bool autostart, - bool autostop, bool start_now) +void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id, const QString &stream_id, const QString &key, + bool autostart, bool autostop, bool start_now) { //blog(LOG_DEBUG, "Stream key: %s", QT_TO_UTF8(key)); obs_service_t *service_obj = GetService(); @@ -7204,12 +6418,10 @@ void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id, void OBSBasic::YoutubeStreamCheck(const std::string &key) { - YoutubeApiWrappers *apiYouTube( - dynamic_cast(GetAuth())); + YoutubeApiWrappers *apiYouTube(dynamic_cast(GetAuth())); if (!apiYouTube) { /* technically we should never get here -Lain */ - QMetaObject::invokeMethod(this, "ForceStopStreaming", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "ForceStopStreaming", Qt::QueuedConnection); youtubeStreamCheckThread->deleteLater(); blog(LOG_ERROR, "=========================================="); blog(LOG_ERROR, "%s: Uh, hey, we got here", __FUNCTION__); @@ -7223,17 +6435,13 @@ void OBSBasic::YoutubeStreamCheck(const std::string &key) while (StreamingActive()) { if (timeout == 14) { - QMetaObject::invokeMethod(this, "ForceStopStreaming", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "ForceStopStreaming", Qt::QueuedConnection); break; } if (!apiYouTube->FindStream(id, json)) { - QMetaObject::invokeMethod(this, - "DisplayStreamStartError", - Qt::QueuedConnection); - QMetaObject::invokeMethod(this, "StopStreaming", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "DisplayStreamStartError", Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "StopStreaming", Qt::QueuedConnection); break; } @@ -7255,10 +6463,8 @@ void OBSBasic::ShowYouTubeAutoStartWarning() { auto msgBox = []() { QMessageBox msgbox(App()->GetMainWindow()); - msgbox.setWindowTitle(QTStr( - "YouTube.Actions.AutoStartStreamingWarning.Title")); - msgbox.setText( - QTStr("YouTube.Actions.AutoStartStreamingWarning")); + msgbox.setWindowTitle(QTStr("YouTube.Actions.AutoStartStreamingWarning.Title")); + msgbox.setText(QTStr("YouTube.Actions.AutoStartStreamingWarning")); msgbox.setIcon(QMessageBox::Icon::Information); msgbox.addButton(QMessageBox::Ok); @@ -7268,18 +6474,14 @@ void OBSBasic::ShowYouTubeAutoStartWarning() msgbox.exec(); if (cb->isChecked()) { - config_set_bool(App()->GetUserConfig(), "General", - "WarnedAboutYouTubeAutoStart", true); - config_save_safe(App()->GetUserConfig(), "tmp", - nullptr); + config_set_bool(App()->GetUserConfig(), "General", "WarnedAboutYouTubeAutoStart", true); + config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } }; - bool warned = config_get_bool(App()->GetUserConfig(), "General", - "WarnedAboutYouTubeAutoStart"); + bool warned = config_get_bool(App()->GetUserConfig(), "General", "WarnedAboutYouTubeAutoStart"); if (!warned) { - QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, - Q_ARG(VoidFunc, msgBox)); + QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, Q_ARG(VoidFunc, msgBox)); } } #endif @@ -7295,20 +6497,16 @@ void OBSBasic::StartStreaming() if (!broadcastActive && !broadcastReady) { QMessageBox no_broadcast(this); no_broadcast.setText(QTStr("Output.NoBroadcast.Text")); - QPushButton *SetupBroadcast = no_broadcast.addButton( - QTStr("Basic.Main.SetupBroadcast"), - QMessageBox::YesRole); + QPushButton *SetupBroadcast = + no_broadcast.addButton(QTStr("Basic.Main.SetupBroadcast"), QMessageBox::YesRole); no_broadcast.setDefaultButton(SetupBroadcast); - no_broadcast.addButton(QTStr("Close"), - QMessageBox::NoRole); + no_broadcast.addButton(QTStr("Close"), QMessageBox::NoRole); no_broadcast.setIcon(QMessageBox::Information); - no_broadcast.setWindowTitle( - QTStr("Output.NoBroadcast.Title")); + no_broadcast.setWindowTitle(QTStr("Output.NoBroadcast.Title")); no_broadcast.exec(); if (no_broadcast.clickedButton() == SetupBroadcast) - QMetaObject::invokeMethod(this, - "SetupBroadcast"); + QMetaObject::invokeMethod(this, "SetupBroadcast"); return; } } @@ -7346,14 +6544,12 @@ void OBSBasic::StartStreaming() } bool recordWhenStreaming = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "RecordWhenStreaming"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); if (recordWhenStreaming) StartRecording(); bool replayBufferWhileStreaming = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ReplayBufferWhileStreaming"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); if (replayBufferWhileStreaming) StartReplayBuffer(); @@ -7363,38 +6559,29 @@ void OBSBasic::StartStreaming() #endif }; - setupStreamingGuard = - outputHandler->SetupStreaming(service, finish_stream_setup); + setupStreamingGuard = outputHandler->SetupStreaming(service, finish_stream_setup); } void OBSBasic::BroadcastButtonClicked() { - if (!broadcastReady || - (!broadcastActive && !outputHandler->StreamingActive())) { + if (!broadcastReady || (!broadcastActive && !outputHandler->StreamingActive())) { SetupBroadcast(); return; } if (!autoStartBroadcast) { #ifdef YOUTUBE_ENABLED - std::shared_ptr ytAuth = - dynamic_pointer_cast(auth); + std::shared_ptr ytAuth = dynamic_pointer_cast(auth); if (ytAuth.get()) { if (!ytAuth->StartLatestBroadcast()) { auto last_error = ytAuth->GetLastError(); if (last_error.isEmpty()) - last_error = QTStr( - "YouTube.Actions.Error.YouTubeApi"); + last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); if (!ytAuth->GetTranslatedError(last_error)) - last_error = - QTStr("YouTube.Actions.Error.BroadcastTransitionFailed") - .arg(last_error, - ytAuth->GetBroadcastId()); + last_error = QTStr("YouTube.Actions.Error.BroadcastTransitionFailed") + .arg(last_error, ytAuth->GetBroadcastId()); - OBSMessageBox::warning( - this, - QTStr("Output.BroadcastStartFailed"), - last_error, true); + OBSMessageBox::warning(this, QTStr("Output.BroadcastStartFailed"), last_error, true); return; } } @@ -7405,38 +6592,27 @@ void OBSBasic::BroadcastButtonClicked() emit BroadcastStreamStarted(autoStopBroadcast); } else if (!autoStopBroadcast) { #ifdef YOUTUBE_ENABLED - bool confirm = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "WarnBeforeStoppingStream"); + bool confirm = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingStream"); if (confirm && isVisible()) { QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("ConfirmStop.Title"), - QTStr("YouTube.Actions.AutoStopStreamingWarning"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + this, QTStr("ConfirmStop.Title"), QTStr("YouTube.Actions.AutoStopStreamingWarning"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (button == QMessageBox::No) return; } - std::shared_ptr ytAuth = - dynamic_pointer_cast(auth); + std::shared_ptr ytAuth = dynamic_pointer_cast(auth); if (ytAuth.get()) { if (!ytAuth->StopLatestBroadcast()) { auto last_error = ytAuth->GetLastError(); if (last_error.isEmpty()) - last_error = QTStr( - "YouTube.Actions.Error.YouTubeApi"); + last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); if (!ytAuth->GetTranslatedError(last_error)) - last_error = - QTStr("YouTube.Actions.Error.BroadcastTransitionFailed") - .arg(last_error, - ytAuth->GetBroadcastId()); + last_error = QTStr("YouTube.Actions.Error.BroadcastTransitionFailed") + .arg(last_error, ytAuth->GetBroadcastId()); - OBSMessageBox::warning( - this, - QTStr("Output.BroadcastStopFailed"), - last_error, true); + OBSMessageBox::warning(this, QTStr("Output.BroadcastStopFailed"), last_error, true); } } #endif @@ -7461,8 +6637,7 @@ void OBSBasic::SetupBroadcast() Auth *const auth = GetAuth(); if (IsYouTubeService(auth->service())) { OBSYoutubeActions dialog(this, auth, broadcastReady); - connect(&dialog, &OBSYoutubeActions::ok, this, - &OBSBasic::YouTubeActionDialogOk); + connect(&dialog, &OBSYoutubeActions::ok, this, &OBSBasic::YouTubeActionDialogOk); dialog.exec(); } #endif @@ -7471,16 +6646,14 @@ void OBSBasic::SetupBroadcast() #ifdef _WIN32 static inline void UpdateProcessPriority() { - const char *priority = config_get_string(App()->GetAppConfig(), - "General", "ProcessPriority"); + const char *priority = config_get_string(App()->GetAppConfig(), "General", "ProcessPriority"); if (priority && strcmp(priority, "Normal") != 0) SetProcessPriority(priority); } static inline void ClearProcessPriority() { - const char *priority = config_get_string(App()->GetAppConfig(), - "General", "ProcessPriority"); + const char *priority = config_get_string(App()->GetAppConfig(), "General", "ProcessPriority"); if (priority && strcmp(priority, "Normal") != 0) SetProcessPriority("Normal"); } @@ -7508,15 +6681,11 @@ inline void OBSBasic::OnActivate(bool force) TaskbarOverlaySetStatus(TaskbarOverlayStatusActive); if (trayIcon && trayIcon->isVisible()) { #ifdef __APPLE__ - QIcon trayMask = - QIcon(":/res/images/tray_active_macos.svg"); + QIcon trayMask = QIcon(":/res/images/tray_active_macos.svg"); trayMask.setIsMask(true); - trayIcon->setIcon( - QIcon::fromTheme("obs-tray", trayMask)); + trayIcon->setIcon(QIcon::fromTheme("obs-tray", trayMask)); #else - trayIcon->setIcon(QIcon::fromTheme( - "obs-tray-active", - QIcon(":/res/images/tray_active.png"))); + trayIcon->setIcon(QIcon::fromTheme("obs-tray-active", QIcon(":/res/images/tray_active.png"))); #endif } } @@ -7536,40 +6705,31 @@ inline void OBSBasic::OnDeactivate() TaskbarOverlaySetStatus(TaskbarOverlayStatusInactive); if (trayIcon && trayIcon->isVisible()) { #ifdef __APPLE__ - QIcon trayIconFile = - QIcon(":/res/images/obs_macos.svg"); + QIcon trayIconFile = QIcon(":/res/images/obs_macos.svg"); trayIconFile.setIsMask(true); #else QIcon trayIconFile = QIcon(":/res/images/obs.png"); #endif - trayIcon->setIcon( - QIcon::fromTheme("obs-tray", trayIconFile)); + trayIcon->setIcon(QIcon::fromTheme("obs-tray", trayIconFile)); } - } else if (outputHandler->Active() && trayIcon && - trayIcon->isVisible()) { + } else if (outputHandler->Active() && trayIcon && trayIcon->isVisible()) { if (os_atomic_load_bool(&recording_paused)) { #ifdef __APPLE__ - QIcon trayIconFile = - QIcon(":/res/images/obs_paused_macos.svg"); + QIcon trayIconFile = QIcon(":/res/images/obs_paused_macos.svg"); trayIconFile.setIsMask(true); #else - QIcon trayIconFile = - QIcon(":/res/images/obs_paused.png"); + QIcon trayIconFile = QIcon(":/res/images/obs_paused.png"); #endif - trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused", - trayIconFile)); + trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused", trayIconFile)); TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused); } else { #ifdef __APPLE__ - QIcon trayIconFile = - QIcon(":/res/images/tray_active_macos.svg"); + QIcon trayIconFile = QIcon(":/res/images/tray_active_macos.svg"); trayIconFile.setIsMask(true); #else - QIcon trayIconFile = - QIcon(":/res/images/tray_active.png"); + QIcon trayIconFile = QIcon(":/res/images/tray_active.png"); #endif - trayIcon->setIcon(QIcon::fromTheme("obs-tray-active", - trayIconFile)); + trayIcon->setIcon(QIcon::fromTheme("obs-tray-active", trayIconFile)); TaskbarOverlaySetStatus(TaskbarOverlayStatusActive); } } @@ -7600,20 +6760,16 @@ void OBSBasic::StopStreaming() OnDeactivate(); - bool recordWhenStreaming = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); + bool recordWhenStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); bool keepRecordingWhenStreamStops = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "KeepRecordingWhenStreamStops"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops"); if (recordWhenStreaming && !keepRecordingWhenStreamStops) StopRecording(); bool replayBufferWhileStreaming = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ReplayBufferWhileStreaming"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); bool keepReplayBufferStreamStops = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "KeepReplayBufferStreamStops"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops"); if (replayBufferWhileStreaming && !keepReplayBufferStreamStops) StopReplayBuffer(); } @@ -7643,20 +6799,16 @@ void OBSBasic::ForceStopStreaming() OnDeactivate(); - bool recordWhenStreaming = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); + bool recordWhenStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); bool keepRecordingWhenStreamStops = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "KeepRecordingWhenStreamStops"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops"); if (recordWhenStreaming && !keepRecordingWhenStreamStops) StopRecording(); bool replayBufferWhileStreaming = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ReplayBufferWhileStreaming"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); bool keepReplayBufferStreamStops = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "KeepReplayBufferStreamStops"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops"); if (replayBufferWhileStreaming && !keepReplayBufferStreamStops) StopReplayBuffer(); } @@ -7704,14 +6856,11 @@ void OBSBasic::StreamingStart() if (!autoStartBroadcast) { // get a current stream key obs_service_t *service_obj = GetService(); - OBSDataAutoRelease settings = - obs_service_get_settings(service_obj); + OBSDataAutoRelease settings = obs_service_get_settings(service_obj); std::string key = obs_data_get_string(settings, "stream_id"); if (!key.empty() && !youtubeStreamCheckThread) { - youtubeStreamCheckThread = CreateQThread( - [this, key] { YoutubeStreamCheck(key); }); - youtubeStreamCheckThread->setObjectName( - "YouTubeStreamCheckThread"); + youtubeStreamCheckThread = CreateQThread([this, key] { YoutubeStreamCheck(key); }); + youtubeStreamCheckThread->setObjectName("YouTubeStreamCheckThread"); youtubeStreamCheckThread->start(); } } @@ -7783,8 +6932,7 @@ void OBSBasic::StreamingStop(int code, QString last_error) } if (use_last_error && !last_error.isEmpty()) - dstr_printf(errorMessage, "%s\n\n%s", errorDescription, - QT_TO_UTF8(last_error)); + dstr_printf(errorMessage, "%s\n\n%s", errorDescription, QT_TO_UTF8(last_error)); else dstr_copy(errorMessage, errorDescription); @@ -7810,22 +6958,15 @@ void OBSBasic::StreamingStop(int code, QString last_error) blog(LOG_INFO, STREAMING_STOP); if (encode_error) { - QString msg = - last_error.isEmpty() - ? QTStr("Output.StreamEncodeError.Msg") - : QTStr("Output.StreamEncodeError.Msg.LastError") - .arg(last_error); - OBSMessageBox::information( - this, QTStr("Output.StreamEncodeError.Title"), msg); + QString msg = last_error.isEmpty() ? QTStr("Output.StreamEncodeError.Msg") + : QTStr("Output.StreamEncodeError.Msg.LastError").arg(last_error); + OBSMessageBox::information(this, QTStr("Output.StreamEncodeError.Title"), msg); } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) { - OBSMessageBox::information(this, - QTStr("Output.ConnectFail.Title"), - QT_UTF8(errorMessage)); + OBSMessageBox::information(this, QTStr("Output.ConnectFail.Title"), QT_UTF8(errorMessage)); } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) { - SysTrayNotify(QT_UTF8(errorDescription), - QSystemTrayIcon::Warning); + SysTrayNotify(QT_UTF8(errorDescription), QSystemTrayIcon::Warning); } // Reset broadcast button state/text @@ -7852,8 +6993,7 @@ void OBSBasic::AutoRemux(QString input, bool no_show) } if (!isSimpleMode) { - const char *recType = - config_get_string(config, "AdvOut", "RecType"); + const char *recType = config_get_string(config, "AdvOut", "RecType"); bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0; @@ -7877,11 +7017,9 @@ void OBSBasic::AutoRemux(QString input, bool no_show) QString output = input; output.resize(output.size() - suffix.size()); - const obs_encoder_t *videoEncoder = - obs_output_get_video_encoder(outputHandler->fileOutput); + const obs_encoder_t *videoEncoder = obs_output_get_video_encoder(outputHandler->fileOutput); const char *vCodecName = obs_encoder_get_codec(videoEncoder); - const char *format = config_get_string( - config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2"); + const char *format = config_get_string(config, isSimpleMode ? "SimpleOutput" : "AdvOut", "RecFormat2"); /* Retain original container for fMP4/fMOV */ if (strncmp(format, "fragmented", 10) == 0) { @@ -7973,22 +7111,16 @@ void OBSBasic::RecordingStop(int code, QString last_error) blog(LOG_INFO, RECORDING_STOP); if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) { - OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"), - QTStr("Output.RecordFail.Unsupported")); + OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"), QTStr("Output.RecordFail.Unsupported")); } else if (code == OBS_OUTPUT_ENCODE_ERROR && isVisible()) { - QString msg = - last_error.isEmpty() - ? QTStr("Output.RecordError.EncodeErrorMsg") - : QTStr("Output.RecordError.EncodeErrorMsg.LastError") - .arg(last_error); - OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"), - msg); + QString msg = last_error.isEmpty() + ? QTStr("Output.RecordError.EncodeErrorMsg") + : QTStr("Output.RecordError.EncodeErrorMsg.LastError").arg(last_error); + OBSMessageBox::warning(this, QTStr("Output.RecordError.Title"), msg); } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) { - OBSMessageBox::warning(this, - QTStr("Output.RecordNoSpace.Title"), - QTStr("Output.RecordNoSpace.Msg")); + OBSMessageBox::warning(this, QTStr("Output.RecordNoSpace.Title"), QTStr("Output.RecordNoSpace.Msg")); } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) { @@ -7999,25 +7131,20 @@ void OBSBasic::RecordingStop(int code, QString last_error) errorDescription = Str("Output.RecordError.Msg"); if (use_last_error && !last_error.isEmpty()) - dstr_printf(errorMessage, "%s

%s", - errorDescription, QT_TO_UTF8(last_error)); + dstr_printf(errorMessage, "%s

%s", errorDescription, QT_TO_UTF8(last_error)); else dstr_copy(errorMessage, errorDescription); - OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"), - QT_UTF8(errorMessage)); + OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"), QT_UTF8(errorMessage)); } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) { - SysTrayNotify(QTStr("Output.RecordFail.Unsupported"), - QSystemTrayIcon::Warning); + SysTrayNotify(QTStr("Output.RecordFail.Unsupported"), QSystemTrayIcon::Warning); } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) { - SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"), - QSystemTrayIcon::Warning); + SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"), QSystemTrayIcon::Warning); } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) { - SysTrayNotify(QTStr("Output.RecordError.Msg"), - QSystemTrayIcon::Warning); + SysTrayNotify(QTStr("Output.RecordError.Msg"), QSystemTrayIcon::Warning); } else if (code == OBS_OUTPUT_SUCCESS) { if (outputHandler) { std::string path = outputHandler->lastRecordingPath; @@ -8061,18 +7188,14 @@ void OBSBasic::ShowReplayBufferPauseWarning() msgbox.exec(); if (cb->isChecked()) { - config_set_bool(App()->GetUserConfig(), "General", - "WarnedAboutReplayBufferPausing", true); - config_save_safe(App()->GetUserConfig(), "tmp", - nullptr); + config_set_bool(App()->GetUserConfig(), "General", "WarnedAboutReplayBufferPausing", true); + config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } }; - bool warned = config_get_bool(App()->GetUserConfig(), "General", - "WarnedAboutReplayBufferPausing"); + bool warned = config_get_bool(App()->GetUserConfig(), "General", "WarnedAboutReplayBufferPausing"); if (!warned) { - QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, - Q_ARG(VoidFunc, msgBox)); + QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, Q_ARG(VoidFunc, msgBox)); } } @@ -8102,8 +7225,7 @@ void OBSBasic::StartReplayBuffer() SaveProject(); - if (outputHandler->StartReplayBuffer() && - os_atomic_load_bool(&recording_paused)) { + if (outputHandler->StartReplayBuffer() && os_atomic_load_bool(&recording_paused)) { ShowReplayBufferPauseWarning(); } } @@ -8116,8 +7238,7 @@ void OBSBasic::ReplayBufferStopping() emit ReplayBufStopping(); if (sysTrayReplayBuffer) - sysTrayReplayBuffer->setText( - QTStr("Basic.Main.StoppingReplayBuffer")); + sysTrayReplayBuffer->setText(QTStr("Basic.Main.StoppingReplayBuffer")); replayBufferStopping = true; OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING); @@ -8144,8 +7265,7 @@ void OBSBasic::ReplayBufferStart() emit ReplayBufStarted(); if (sysTrayReplayBuffer) - sysTrayReplayBuffer->setText( - QTStr("Basic.Main.StopReplayBuffer")); + sysTrayReplayBuffer->setText(QTStr("Basic.Main.StopReplayBuffer")); replayBufferStopping = false; OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED); @@ -8163,8 +7283,7 @@ void OBSBasic::ReplayBufferSave() return; calldata_t cd = {0}; - proc_handler_t *ph = - obs_output_get_proc_handler(outputHandler->replayBuffer); + proc_handler_t *ph = obs_output_get_proc_handler(outputHandler->replayBuffer); proc_handler_call(ph, "save", &cd); calldata_free(&cd); } @@ -8177,12 +7296,10 @@ void OBSBasic::ReplayBufferSaved() return; calldata_t cd = {0}; - proc_handler_t *ph = - obs_output_get_proc_handler(outputHandler->replayBuffer); + proc_handler_t *ph = obs_output_get_proc_handler(outputHandler->replayBuffer); proc_handler_call(ph, "get_last_replay", &cd); std::string path = calldata_string(&cd, "path"); - QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo") - .arg(QT_UTF8(path.c_str())); + QString msg = QTStr("Basic.StatusBar.ReplayBufferSavedTo").arg(QT_UTF8(path.c_str())); ShowStatusBarMessage(msg); lastReplay = path; calldata_free(&cd); @@ -8200,35 +7317,27 @@ void OBSBasic::ReplayBufferStop(int code) emit ReplayBufStopped(); if (sysTrayReplayBuffer) - sysTrayReplayBuffer->setText( - QTStr("Basic.Main.StartReplayBuffer")); + sysTrayReplayBuffer->setText(QTStr("Basic.Main.StartReplayBuffer")); blog(LOG_INFO, REPLAY_BUFFER_STOP); if (code == OBS_OUTPUT_UNSUPPORTED && isVisible()) { - OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"), - QTStr("Output.RecordFail.Unsupported")); + OBSMessageBox::critical(this, QTStr("Output.RecordFail.Title"), QTStr("Output.RecordFail.Unsupported")); } else if (code == OBS_OUTPUT_NO_SPACE && isVisible()) { - OBSMessageBox::warning(this, - QTStr("Output.RecordNoSpace.Title"), - QTStr("Output.RecordNoSpace.Msg")); + OBSMessageBox::warning(this, QTStr("Output.RecordNoSpace.Title"), QTStr("Output.RecordNoSpace.Msg")); } else if (code != OBS_OUTPUT_SUCCESS && isVisible()) { - OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"), - QTStr("Output.RecordError.Msg")); + OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"), QTStr("Output.RecordError.Msg")); } else if (code == OBS_OUTPUT_UNSUPPORTED && !isVisible()) { - SysTrayNotify(QTStr("Output.RecordFail.Unsupported"), - QSystemTrayIcon::Warning); + SysTrayNotify(QTStr("Output.RecordFail.Unsupported"), QSystemTrayIcon::Warning); } else if (code == OBS_OUTPUT_NO_SPACE && !isVisible()) { - SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"), - QSystemTrayIcon::Warning); + SysTrayNotify(QTStr("Output.RecordNoSpace.Msg"), QSystemTrayIcon::Warning); } else if (code != OBS_OUTPUT_SUCCESS && !isVisible()) { - SysTrayNotify(QTStr("Output.RecordError.Msg"), - QSystemTrayIcon::Warning); + SysTrayNotify(QTStr("Output.RecordError.Msg"), QSystemTrayIcon::Warning); } OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPED); @@ -8307,18 +7416,13 @@ void OBSBasic::OnVirtualCamStop(int) void OBSBasic::StreamActionTriggered() { if (outputHandler->StreamingActive()) { - bool confirm = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "WarnBeforeStoppingStream"); + bool confirm = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingStream"); #ifdef YOUTUBE_ENABLED - if (isVisible() && auth && IsYouTubeService(auth->service()) && - autoStopBroadcast) { + if (isVisible() && auth && IsYouTubeService(auth->service()) && autoStopBroadcast) { QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("ConfirmStop.Title"), - QTStr("YouTube.Actions.AutoStopStreamingWarning"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + this, QTStr("ConfirmStop.Title"), QTStr("YouTube.Actions.AutoStopStreamingWarning"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (button == QMessageBox::No) return; @@ -8328,11 +7432,8 @@ void OBSBasic::StreamActionTriggered() #endif if (confirm && isVisible()) { QMessageBox::StandardButton button = - OBSMessageBox::question( - this, QTStr("ConfirmStop.Title"), - QTStr("ConfirmStop.Text"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + OBSMessageBox::question(this, QTStr("ConfirmStop.Title"), QTStr("ConfirmStop.Text"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (button == QMessageBox::No) return; @@ -8345,11 +7446,8 @@ void OBSBasic::StreamActionTriggered() Auth *auth = GetAuth(); - auto action = - (auth && auth->external()) - ? StreamSettingsAction::ContinueStream - : UIValidation::StreamSettingsConfirmation( - this, service); + auto action = (auth && auth->external()) ? StreamSettingsAction::ContinueStream + : UIValidation::StreamSettingsConfirmation(this, service); switch (action) { case StreamSettingsAction::ContinueStream: break; @@ -8360,37 +7458,28 @@ void OBSBasic::StreamActionTriggered() return; } - bool confirm = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "WarnBeforeStartingStream"); + bool confirm = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStartingStream"); bool bwtest = false; if (this->auth) { - OBSDataAutoRelease settings = - obs_service_get_settings(service); + OBSDataAutoRelease settings = obs_service_get_settings(service); bwtest = obs_data_get_bool(settings, "bwtest"); // Disable confirmation if this is going to open broadcast setup - if (auth && auth->broadcastFlow() && !broadcastReady && - !broadcastActive) + if (auth && auth->broadcastFlow() && !broadcastReady && !broadcastActive) confirm = false; } if (bwtest && isVisible()) { - QMessageBox::StandardButton button = - OBSMessageBox::question( - this, QTStr("ConfirmBWTest.Title"), - QTStr("ConfirmBWTest.Text")); + QMessageBox::StandardButton button = OBSMessageBox::question(this, QTStr("ConfirmBWTest.Title"), + QTStr("ConfirmBWTest.Text")); if (button == QMessageBox::No) return; } else if (confirm && isVisible()) { QMessageBox::StandardButton button = - OBSMessageBox::question( - this, QTStr("ConfirmStart.Title"), - QTStr("ConfirmStart.Text"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + OBSMessageBox::question(this, QTStr("ConfirmStart.Title"), QTStr("ConfirmStart.Text"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (button == QMessageBox::No) return; @@ -8403,17 +7492,12 @@ void OBSBasic::StreamActionTriggered() void OBSBasic::RecordActionTriggered() { if (outputHandler->RecordingActive()) { - bool confirm = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "WarnBeforeStoppingRecord"); + bool confirm = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingRecord"); if (confirm && isVisible()) { - QMessageBox::StandardButton button = - OBSMessageBox::question( - this, QTStr("ConfirmStopRecord.Title"), - QTStr("ConfirmStopRecord.Text"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + QMessageBox::StandardButton button = OBSMessageBox::question( + this, QTStr("ConfirmStopRecord.Title"), QTStr("ConfirmStopRecord.Text"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (button == QMessageBox::No) return; @@ -8441,13 +7525,10 @@ void OBSBasic::VirtualCamActionTriggered() void OBSBasic::OpenVirtualCamConfig() { - OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(), - this); + OBSBasicVCamConfig dialog(vcamConfig, outputHandler->VirtualCamActive(), this); - connect(&dialog, &OBSBasicVCamConfig::Accepted, this, - &OBSBasic::UpdateVirtualCamConfig); - connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this, - &OBSBasic::RestartVirtualCam); + connect(&dialog, &OBSBasicVCamConfig::Accepted, this, &OBSBasic::UpdateVirtualCamConfig); + connect(&dialog, &OBSBasicVCamConfig::AcceptedAndRestart, this, &OBSBasic::RestartVirtualCam); dialog.exec(); } @@ -8466,12 +7547,10 @@ void log_vcam_changed(const VCamConfig &config, bool starting) blog(LOG_INFO, "%s Virtual Camera output to Preview", action); break; case VCamOutputType::SceneOutput: - blog(LOG_INFO, "%s Virtual Camera output to Scene : %s", action, - config.scene.c_str()); + blog(LOG_INFO, "%s Virtual Camera output to Scene : %s", action, config.scene.c_str()); break; case VCamOutputType::SourceOutput: - blog(LOG_INFO, "%s Virtual Camera output to Source : %s", - action, config.source.c_str()); + blog(LOG_INFO, "%s Virtual Camera output to Source : %s", action, config.source.c_str()); break; } } @@ -8532,8 +7611,7 @@ void OBSBasic::on_actionShowWhatsNew_triggered() config_set_int(App()->GetAppConfig(), "General", "InfoIncrement", -1); WhatsNewInfoThread *wnit = new WhatsNewInfoThread(); - connect(wnit, &WhatsNewInfoThread::Result, this, - &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection); + connect(wnit, &WhatsNewInfoThread::Result, this, &OBSBasic::ReceivedIntroJson, Qt::QueuedConnection); introCheckThread.reset(wnit); introCheckThread->start(); @@ -8543,17 +7621,14 @@ void OBSBasic::on_actionShowWhatsNew_triggered() void OBSBasic::on_actionReleaseNotes_triggered() { QString addr("https://github.com/obsproject/obs-studio/releases"); - QUrl url(QString("%1/%2").arg(addr, obs_get_version_string()), - QUrl::TolerantMode); + QUrl url(QString("%1/%2").arg(addr, obs_get_version_string()), QUrl::TolerantMode); QDesktopServices::openUrl(url); } void OBSBasic::on_actionShowSettingsFolder_triggered() { - const std::string userConfigPath = - App()->userConfigLocation.u8string() + "/obs-studio"; - const QString userConfigLocation = - QString::fromStdString(userConfigPath); + const std::string userConfigPath = App()->userConfigLocation.u8string() + "/obs-studio"; + const QString userConfigLocation = QString::fromStdString(userConfigPath); QDesktopServices::openUrl(QUrl::fromLocalFile(userConfigLocation)); } @@ -8561,21 +7636,17 @@ void OBSBasic::on_actionShowSettingsFolder_triggered() void OBSBasic::on_actionShowProfileFolder_triggered() { std::string userProfilePath; - userProfilePath.reserve(App()->userProfilesLocation.u8string().size() + - OBSProfilePath.size()); - userProfilePath.append(App()->userProfilesLocation.u8string()) - .append(OBSProfilePath); + userProfilePath.reserve(App()->userProfilesLocation.u8string().size() + OBSProfilePath.size()); + userProfilePath.append(App()->userProfilesLocation.u8string()).append(OBSProfilePath); - const QString userProfileLocation = - QString::fromStdString(userProfilePath); + const QString userProfileLocation = QString::fromStdString(userProfilePath); QDesktopServices::openUrl(QUrl::fromLocalFile(userProfileLocation)); } int OBSBasic::GetTopSelectedSourceItem() { - QModelIndexList selectedItems = - ui->sources->selectionModel()->selectedIndexes(); + QModelIndexList selectedItems = ui->sources->selectionModel()->selectedIndexes(); return selectedItems.count() ? selectedItems[0].row() : -1; } @@ -8595,14 +7666,11 @@ void OBSBasic::ProgramViewContextMenuRequested() QPointer studioProgramProjector; studioProgramProjector = new QMenu(QTStr("StudioProgramProjector")); - AddProjectorMenuMonitors(studioProgramProjector, this, - &OBSBasic::OpenStudioProgramProjector); + AddProjectorMenuMonitors(studioProgramProjector, this, &OBSBasic::OpenStudioProgramProjector); popup.addMenu(studioProgramProjector); - popup.addAction(QTStr("StudioProgramWindow"), this, - &OBSBasic::OpenStudioProgramWindow); - popup.addAction(QTStr("Screenshot.StudioProgram"), this, - &OBSBasic::ScreenshotProgram); + popup.addAction(QTStr("StudioProgramWindow"), this, &OBSBasic::OpenStudioProgramWindow); + popup.addAction(QTStr("Screenshot.StudioProgram"), this, &OBSBasic::ScreenshotProgram); popup.exec(QCursor::pos()); } @@ -8612,18 +7680,14 @@ void OBSBasic::on_previewDisabledWidget_customContextMenuRequested() QMenu popup(this); delete previewProjectorMain; - QAction *action = - popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"), - this, &OBSBasic::TogglePreview); + QAction *action = popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"), this, &OBSBasic::TogglePreview); action->setCheckable(true); action->setChecked(obs_display_enabled(ui->preview->GetDisplay())); previewProjectorMain = new QMenu(QTStr("PreviewProjector")); - AddProjectorMenuMonitors(previewProjectorMain, this, - &OBSBasic::OpenPreviewProjector); + AddProjectorMenuMonitors(previewProjectorMain, this, &OBSBasic::OpenPreviewProjector); - QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this, - &OBSBasic::OpenPreviewWindow); + QAction *previewWindow = popup.addAction(QTStr("PreviewWindow"), this, &OBSBasic::OpenPreviewWindow); popup.addMenu(previewProjectorMain); popup.addAction(previewWindow); @@ -8640,8 +7704,7 @@ void OBSBasic::on_actionAlwaysOnTop_triggered() CloseDialogs(); #endif - QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "ToggleAlwaysOnTop", Qt::QueuedConnection); } void OBSBasic::ToggleAlwaysOnTop() @@ -8656,8 +7719,7 @@ void OBSBasic::ToggleAlwaysOnTop() void OBSBasic::GetFPSCommon(uint32_t &num, uint32_t &den) const { - const char *val = - config_get_string(activeConfiguration, "Video", "FPSCommon"); + const char *val = config_get_string(activeConfiguration, "Video", "FPSCommon"); if (strcmp(val, "10") == 0) { num = 10; @@ -8712,8 +7774,7 @@ void OBSBasic::GetFPSNanoseconds(uint32_t &num, uint32_t &den) const void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const { - uint32_t type = - config_get_uint(activeConfiguration, "Video", "FPSType"); + uint32_t type = config_get_uint(activeConfiguration, "Video", "FPSType"); if (type == 1) //"Integer" GetFPSInteger(num, den); @@ -8782,8 +7843,7 @@ void OBSBasic::UpdateEditMenu() size_t filter_count = 0; if (totalCount == 1) { - OBSSceneItem sceneItem = - ui->sources->Get(GetTopSelectedSourceItem()); + OBSSceneItem sceneItem = ui->sources->Get(GetTopSelectedSourceItem()); OBSSource source = obs_sceneitem_get_source(sceneItem); filter_count = obs_source_filter_count(source); } @@ -8796,11 +7856,8 @@ void OBSBasic::UpdateEditMenu() clipboard.erase(clipboard.begin() + idx); continue; } - OBSSourceAutoRelease strong = - obs_weak_source_get_source(weak.Get()); - if (allowPastingDuplicate && - obs_source_get_output_flags(strong) & - OBS_SOURCE_DO_NOT_DUPLICATE) + OBSSourceAutoRelease strong = obs_weak_source_get_source(weak.Get()); + if (allowPastingDuplicate && obs_source_get_output_flags(strong) & OBS_SOURCE_DO_NOT_DUPLICATE) allowPastingDuplicate = false; } @@ -8825,11 +7882,9 @@ void OBSBasic::UpdateEditMenu() ui->actionCopySource->setEnabled(totalCount > 0); ui->actionEditTransform->setEnabled(canTransformSingle && !locked); ui->actionCopyTransform->setEnabled(canTransformSingle); - ui->actionPasteTransform->setEnabled( - canTransformMultiple && hasCopiedTransform && videoCount > 0); + ui->actionPasteTransform->setEnabled(canTransformMultiple && hasCopiedTransform && videoCount > 0); ui->actionCopyFilters->setEnabled(filter_count > 0); - ui->actionPasteFilters->setEnabled( - !obs_weak_source_expired(copyFiltersSource) && totalCount > 0); + ui->actionPasteFilters->setEnabled(!obs_weak_source_expired(copyFiltersSource) && totalCount > 0); ui->actionPasteRef->setEnabled(!!clipboard.size()); ui->actionPasteDup->setEnabled(allowPastingDuplicate); @@ -8864,8 +7919,7 @@ void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item) if (transformWindow) transformWindow->close(); transformWindow = new OBSBasicTransform(item, this); - connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow, - &OBSBasicTransform::OnSceneChanged); + connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow, &OBSBasicTransform::OnSceneChanged); transformWindow->show(); transformWindow->setAttribute(Qt::WA_DeleteOnClose, true); } @@ -8884,18 +7938,15 @@ void OBSBasic::on_actionCopyTransform_triggered() void undo_redo(const std::string &data) { OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = - obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid")); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(source.Get(), true); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid")); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(source.Get(), true); obs_scene_load_transform_states(data.c_str()); } void OBSBasic::on_actionPasteTransform_triggered() { - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *data) { if (!obs_sceneitem_selected(item)) return true; @@ -8914,15 +7965,12 @@ void OBSBasic::on_actionPasteTransform_triggered() obs_scene_enum_items(GetCurrentScene(), func, this); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action( - QTStr("Undo.Transform.Paste") - .arg(obs_source_get_name(GetCurrentSceneSource())), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action(QTStr("Undo.Transform.Paste").arg(obs_source_get_name(GetCurrentSceneSource())), undo_redo, + undo_redo, undo_data, redo_data); } static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *) @@ -8959,18 +8007,14 @@ void OBSBasic::on_actionResetTransform_triggered() { OBSScene scene = GetCurrentScene(); - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(scene, false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(scene, false); obs_scene_enum_items(scene, reset_tr, nullptr); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(scene, false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(scene, false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action( - QTStr("Undo.Transform.Reset") - .arg(obs_source_get_name(obs_scene_get_source(scene))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action(QTStr("Undo.Transform.Reset").arg(obs_source_get_name(obs_scene_get_source(scene))), + undo_redo, undo_redo, undo_data, redo_data); obs_scene_enum_items(GetCurrentScene(), reset_tr, nullptr); } @@ -9016,12 +8060,10 @@ static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl) obs_sceneitem_set_pos(item, &pos); } -static bool RotateSelectedSources(obs_scene_t * /* scene */, - obs_sceneitem_t *item, void *param) +static bool RotateSelectedSources(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { if (obs_sceneitem_is_group(item)) - obs_sceneitem_group_enum_items(item, RotateSelectedSources, - param); + obs_sceneitem_group_enum_items(item, RotateSelectedSources, param); if (!obs_sceneitem_selected(item)) return true; if (obs_sceneitem_locked(item)) @@ -9048,62 +8090,51 @@ static bool RotateSelectedSources(obs_scene_t * /* scene */, void OBSBasic::on_actionRotate90CW_triggered() { float f90CW = 90.0f; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CW); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.Rotate") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.Rotate").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::on_actionRotate90CCW_triggered() { float f90CCW = -90.0f; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f90CCW); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.Rotate") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.Rotate").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::on_actionRotate180_triggered() { float f180 = 180.0f; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); obs_scene_enum_items(GetCurrentScene(), RotateSelectedSources, &f180); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.Rotate") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.Rotate").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } -static bool MultiplySelectedItemScale(obs_scene_t * /* scene */, - obs_sceneitem_t *item, void *param) +static bool MultiplySelectedItemScale(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { vec2 &mul = *reinterpret_cast(param); if (obs_sceneitem_is_group(item)) - obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale, - param); + obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale, param); if (!obs_sceneitem_selected(item)) return true; if (obs_sceneitem_locked(item)) @@ -9127,49 +8158,38 @@ void OBSBasic::on_actionFlipHorizontal_triggered() { vec2 scale; vec2_set(&scale, -1.0f, 1.0f); - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); - obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale, - &scale); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); + obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale, &scale); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.HFlip") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.HFlip").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::on_actionFlipVertical_triggered() { vec2 scale; vec2_set(&scale, 1.0f, -1.0f); - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); - obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale, - &scale); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); + obs_scene_enum_items(GetCurrentScene(), MultiplySelectedItemScale, &scale); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.VFlip") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.VFlip").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } -static bool CenterAlignSelectedItems(obs_scene_t * /* scene */, - obs_sceneitem_t *item, void *param) +static bool CenterAlignSelectedItems(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { - obs_bounds_type boundsType = - *reinterpret_cast(param); + obs_bounds_type boundsType = *reinterpret_cast(param); if (obs_sceneitem_is_group(item)) - obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems, - param); + obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems, param); if (!obs_sceneitem_selected(item)) return true; if (obs_sceneitem_locked(item)) @@ -9184,8 +8204,7 @@ static bool CenterAlignSelectedItems(obs_scene_t * /* scene */, itemInfo.alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP; itemInfo.rot = 0.0f; - vec2_set(&itemInfo.bounds, float(ovi.base_width), - float(ovi.base_height)); + vec2_set(&itemInfo.bounds, float(ovi.base_width), float(ovi.base_height)); itemInfo.bounds_type = boundsType; itemInfo.bounds_alignment = OBS_ALIGN_CENTER; itemInfo.crop_to_bounds = obs_sceneitem_get_bounds_crop(item); @@ -9198,36 +8217,28 @@ static bool CenterAlignSelectedItems(obs_scene_t * /* scene */, void OBSBasic::on_actionFitToScreen_triggered() { obs_bounds_type boundsType = OBS_BOUNDS_SCALE_INNER; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); - obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems, - &boundsType); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); + obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems, &boundsType); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.FitToScreen") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.FitToScreen").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::on_actionStretchToScreen_triggered() { obs_bounds_type boundsType = OBS_BOUNDS_STRETCH; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); - obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems, - &boundsType); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); + obs_scene_enum_items(GetCurrentScene(), CenterAlignSelectedItems, &boundsType); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); undo_s.add_action(QTStr("Undo.Transform.StretchToScreen") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), + .arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), undo_redo, undo_redo, undo_data, redo_data); } @@ -9248,8 +8259,7 @@ void OBSBasic::CenterSelectedSceneItems(const CenterType ¢erType) obs_source_t *source = obs_sceneitem_get_source(item); float width = float(obs_source_get_width(source)) * oti.scale.x; - float height = - float(obs_source_get_height(source)) * oti.scale.y; + float height = float(obs_source_get_height(source)) * oti.scale.y; if (width == 0.0f || height == 0.0f) continue; @@ -9288,8 +8298,7 @@ void OBSBasic::CenterSelectedSceneItems(const CenterType ¢erType) obs_get_video_info(&ovi); vec3 screenCenter; - vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height), - 0.0f); + vec3_set(&screenCenter, float(ovi.base_width), float(ovi.base_height), 0.0f); vec3_mulf(&screenCenter, &screenCenter, 0.5f); @@ -9319,52 +8328,43 @@ void OBSBasic::CenterSelectedSceneItems(const CenterType ¢erType) void OBSBasic::on_actionCenterToScreen_triggered() { CenterType centerType = CenterType::Scene; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); CenterSelectedSceneItems(centerType); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.Center") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.Center").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::on_actionVerticalCenter_triggered() { CenterType centerType = CenterType::Vertical; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); CenterSelectedSceneItems(centerType); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.VCenter") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.VCenter").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::on_actionHorizontalCenter_triggered() { CenterType centerType = CenterType::Horizontal; - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); CenterSelectedSceneItems(centerType); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(GetCurrentScene(), false); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), false); std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action(QTStr("Undo.Transform.HCenter") - .arg(obs_source_get_name(obs_scene_get_source( - GetCurrentScene()))), - undo_redo, undo_redo, undo_data, redo_data); + undo_s.add_action( + QTStr("Undo.Transform.HCenter").arg(obs_source_get_name(obs_scene_get_source(GetCurrentScene()))), + undo_redo, undo_redo, undo_data, redo_data); } void OBSBasic::EnablePreviewDisplay(bool enable) @@ -9429,8 +8429,7 @@ static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param) struct vec2 new_offset; vec2_set(&new_offset, offset3.x, offset3.y); - obs_sceneitem_group_enum_items(item, nudge_callback, - &new_offset); + obs_sceneitem_group_enum_items(item, nudge_callback, &new_offset); } return true; @@ -9467,31 +8466,20 @@ void OBSBasic::Nudge(int dist, MoveDir dir) if (!recent_nudge) { recent_nudge = true; - OBSDataAutoRelease wrapper = obs_scene_save_transform_states( - GetCurrentScene(), true); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), true); std::string undo_data(obs_data_get_json(wrapper)); nudge_timer = new QTimer; - QObject::connect( - nudge_timer, &QTimer::timeout, - [this, &recent_nudge = recent_nudge, undo_data]() { - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states( - GetCurrentScene(), true); - std::string redo_data( - obs_data_get_json(rwrapper)); + QObject::connect(nudge_timer, &QTimer::timeout, [this, &recent_nudge = recent_nudge, undo_data]() { + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(GetCurrentScene(), true); + std::string redo_data(obs_data_get_json(rwrapper)); - undo_s.add_action( - QTStr("Undo.Transform") - .arg(obs_source_get_name( - GetCurrentSceneSource())), - undo_redo, undo_redo, undo_data, - redo_data); + undo_s.add_action(QTStr("Undo.Transform").arg(obs_source_get_name(GetCurrentSceneSource())), + undo_redo, undo_redo, undo_data, redo_data); - recent_nudge = false; - }); - connect(nudge_timer, &QTimer::timeout, nudge_timer, - &QTimer::deleteLater); + recent_nudge = false; + }); + connect(nudge_timer, &QTimer::timeout, nudge_timer, &QTimer::deleteLater); nudge_timer->setSingleShot(true); } @@ -9516,16 +8504,13 @@ void OBSBasic::DeleteProjector(OBSProjector *projector) } } -OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor, - ProjectorType type) +OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor, ProjectorType type) { /* seriously? 10 monitors? */ if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1) return nullptr; - bool closeProjectors = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "CloseExistingProjectors"); + bool closeProjectors = config_get_bool(App()->GetUserConfig(), "BasicWindow", "CloseExistingProjectors"); if (closeProjectors && monitor > -1) { for (size_t i = projectors.size(); i > 0; i--) { @@ -9535,8 +8520,7 @@ OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor, } } - OBSProjector *projector = - new OBSProjector(nullptr, source, monitor, type); + OBSProjector *projector = new OBSProjector(nullptr, source, monitor, type); projectors.emplace_back(projector); @@ -9562,8 +8546,7 @@ void OBSBasic::OpenSourceProjector() if (!item) return; - OpenProjector(obs_sceneitem_get_source(item), monitor, - ProjectorType::Source); + OpenProjector(obs_sceneitem_get_source(item), monitor, ProjectorType::Source); } void OBSBasic::OpenMultiviewProjector() @@ -9579,8 +8562,7 @@ void OBSBasic::OpenSceneProjector() if (!scene) return; - OpenProjector(obs_scene_get_source(scene), monitor, - ProjectorType::Scene); + OpenProjector(obs_scene_get_source(scene), monitor, ProjectorType::Scene); } void OBSBasic::OpenStudioProgramWindow() @@ -9601,8 +8583,7 @@ void OBSBasic::OpenSourceWindow() OBSSource source = obs_sceneitem_get_source(item); - OpenProjector(obs_sceneitem_get_source(item), -1, - ProjectorType::Source); + OpenProjector(obs_sceneitem_get_source(item), -1, ProjectorType::Source); } void OBSBasic::OpenSceneWindow() @@ -9630,38 +8611,31 @@ void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info) switch (info->type) { case ProjectorType::Source: case ProjectorType::Scene: { - OBSSourceAutoRelease source = - obs_get_source_by_name(info->name.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(info->name.c_str()); if (!source) return; - projector = OpenProjector(source, info->monitor, - info->type); + projector = OpenProjector(source, info->monitor, info->type); break; } default: { - projector = OpenProjector(nullptr, info->monitor, - info->type); + projector = OpenProjector(nullptr, info->monitor, info->type); break; } } if (projector && !info->geometry.empty() && info->monitor < 0) { - QByteArray byteArray = QByteArray::fromBase64( - QByteArray(info->geometry.c_str())); + QByteArray byteArray = QByteArray::fromBase64(QByteArray(info->geometry.c_str())); projector->restoreGeometry(byteArray); if (!WindowPositionValid(projector->normalGeometry())) { - QRect rect = QGuiApplication::primaryScreen() - ->geometry(); - projector->setGeometry(QStyle::alignedRect( - Qt::LeftToRight, Qt::AlignCenter, - size(), rect)); + QRect rect = QGuiApplication::primaryScreen()->geometry(); + projector->setGeometry( + QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), rect)); } if (info->alwaysOnTopOverridden) - projector->SetIsAlwaysOnTop(info->alwaysOnTop, - true); + projector->SetIsAlwaysOnTop(info->alwaysOnTop, true); } } } @@ -9678,10 +8652,8 @@ void OBSBasic::UpdateTitleBar() { stringstream name; - const char *profile = - config_get_string(App()->GetUserConfig(), "Basic", "Profile"); - const char *sceneCollection = config_get_string( - App()->GetUserConfig(), "Basic", "SceneCollection"); + const char *profile = config_get_string(App()->GetUserConfig(), "Basic", "Profile"); + const char *sceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection"); name << "OBS "; if (previewProgramMode) @@ -9702,8 +8674,7 @@ void OBSBasic::UpdateTitleBar() int OBSBasic::GetProfilePath(char *path, size_t size, const char *file) const { char profiles_path[512]; - const char *profile = config_get_string(App()->GetUserConfig(), "Basic", - "ProfileDir"); + const char *profile = config_get_string(App()->GetUserConfig(), "Basic", "ProfileDir"); int ret; if (!profile) @@ -9734,18 +8705,14 @@ void OBSBasic::on_resetDocks_triggered(bool force) } #ifdef BROWSER_AVAILABLE - if ((oldExtraDocks.size() || extraDocks.size() || - extraCustomDocks.size() || extraBrowserDocks.size()) && + if ((oldExtraDocks.size() || extraDocks.size() || extraCustomDocks.size() || extraBrowserDocks.size()) && !force) #else - if ((oldExtraDocks.size() || extraDocks.size() || - extraCustomDocks.size()) && - !force) + if ((oldExtraDocks.size() || extraDocks.size() || extraCustomDocks.size()) && !force) #endif { - QMessageBox::StandardButton button = OBSMessageBox::question( - this, QTStr("ResetUIWarning.Title"), - QTStr("ResetUIWarning.Text")); + QMessageBox::StandardButton button = + OBSMessageBox::question(this, QTStr("ResetUIWarning.Title"), QTStr("ResetUIWarning.Text")); if (button == QMessageBox::No) return; @@ -9756,21 +8723,18 @@ void OBSBasic::on_resetDocks_triggered(bool force) if (oldExtraDocks[i]) { oldExtraDocks[i]->setVisible(true); oldExtraDocks[i]->setFloating(true); - oldExtraDocks[i]->move( - frameGeometry().topLeft() + rect().center() - - oldExtraDocks[i]->rect().center()); + oldExtraDocks[i]->move(frameGeometry().topLeft() + rect().center() - + oldExtraDocks[i]->rect().center()); oldExtraDocks[i]->setVisible(false); } } -#define RESET_DOCKLIST(dockList) \ - for (int i = dockList.size() - 1; i >= 0; i--) { \ - dockList[i]->setVisible(true); \ - dockList[i]->setFloating(true); \ - dockList[i]->move(frameGeometry().topLeft() + \ - rect().center() - \ - dockList[i]->rect().center()); \ - dockList[i]->setVisible(false); \ +#define RESET_DOCKLIST(dockList) \ + for (int i = dockList.size() - 1; i >= 0; i--) { \ + dockList[i]->setVisible(true); \ + dockList[i]->setFloating(true); \ + dockList[i]->move(frameGeometry().topLeft() + rect().center() - dockList[i]->rect().center()); \ + dockList[i]->setVisible(false); \ } RESET_DOCKLIST(extraDocks) @@ -9793,9 +8757,7 @@ void OBSBasic::on_resetDocks_triggered(bool force) int mixerSize = cx - (cx22_5 * 2 + cx5 + cx21); - QList docks{ui->scenesDock, ui->sourcesDock, - ui->mixerDock, ui->transitionsDock, - controlsDock}; + QList docks{ui->scenesDock, ui->sourcesDock, ui->mixerDock, ui->transitionsDock, controlsDock}; QList sizes{cx22_5, cx22_5, mixerSize, cx5, cx21}; @@ -9817,8 +8779,7 @@ void OBSBasic::on_lockDocks_toggled(bool lock) { QDockWidget::DockWidgetFeatures features = lock ? QDockWidget::NoDockWidgetFeatures - : (QDockWidget::DockWidgetClosable | - QDockWidget::DockWidgetMovable | + : (QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); QDockWidget::DockWidgetFeatures mainFeatures = features; @@ -9878,8 +8839,7 @@ void OBSBasic::on_resetUI_triggered() ui->scenes->SetGridMode(false); ui->actionSceneListMode->setChecked(true); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", - false); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", false); } void OBSBasic::on_multiviewProjectorWindowed_triggered() @@ -9893,8 +8853,7 @@ void OBSBasic::on_toggleListboxToolbars_toggled(bool visible) ui->scenesToolbar->setVisible(visible); ui->mixerToolbar->setVisible(visible); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ShowListboxToolbars", visible); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowListboxToolbars", visible); } void OBSBasic::ShowContextBar() @@ -9911,8 +8870,7 @@ void OBSBasic::HideContextBar() void OBSBasic::on_toggleContextBar_toggled(bool visible) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ShowContextToolbars", visible); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowContextToolbars", visible); this->ui->contextContainer->setVisible(visible); UpdateContextBar(true); } @@ -9921,8 +8879,7 @@ void OBSBasic::on_toggleStatusBar_toggled(bool visible) { ui->statusbar->setVisible(visible); - config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowStatusBar", - visible); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowStatusBar", visible); } void OBSBasic::on_toggleSourceIcons_toggled(bool visible) @@ -9931,8 +8888,7 @@ void OBSBasic::on_toggleSourceIcons_toggled(bool visible) if (advAudioWindow != nullptr) advAudioWindow->SetIconsVisible(visible); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ShowSourceIcons", visible); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowSourceIcons", visible); } void OBSBasic::on_actionLockPreview_triggered() @@ -9948,17 +8904,14 @@ void OBSBasic::on_scalingMenu_aboutToShow() QAction *action = ui->actionScaleCanvas; QString text = QTStr("Basic.MainMenu.Edit.Scale.Canvas"); - text = text.arg(QString::number(ovi.base_width), - QString::number(ovi.base_height)); + text = text.arg(QString::number(ovi.base_width), QString::number(ovi.base_height)); action->setText(text); action = ui->actionScaleOutput; text = QTStr("Basic.MainMenu.Edit.Scale.Output"); - text = text.arg(QString::number(ovi.output_width), - QString::number(ovi.output_height)); + text = text.arg(QString::number(ovi.output_width), QString::number(ovi.output_height)); action->setText(text); - action->setVisible(!(ovi.output_width == ovi.base_width && - ovi.output_height == ovi.base_height)); + action->setVisible(!(ovi.output_width == ovi.base_width && ovi.output_height == ovi.base_height)); UpdatePreviewScalingMenu(); } @@ -9987,18 +8940,15 @@ void OBSBasic::on_actionScaleOutput_triggered() ui->preview->SetFixedScaling(true); float scalingAmount = float(ovi.output_width) / float(ovi.base_width); // log base ZOOM_SENSITIVITY of x = log(x) / log(ZOOM_SENSITIVITY) - int32_t approxScalingLevel = - int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY))); - ui->preview->SetScalingLevelAndAmount(approxScalingLevel, - scalingAmount); + int32_t approxScalingLevel = int32_t(round(log(scalingAmount) / log(ZOOM_SENSITIVITY))); + ui->preview->SetScalingLevelAndAmount(approxScalingLevel, scalingAmount); emit ui->preview->DisplayResized(); } void OBSBasic::SetShowing(bool showing) { if (!showing && isVisible()) { - config_set_string(App()->GetUserConfig(), "BasicWindow", - "geometry", + config_set_string(App()->GetUserConfig(), "BasicWindow", "geometry", saveGeometry().toBase64().constData()); /* hide all visible child dialogs */ @@ -10077,36 +9027,29 @@ void OBSBasic::SystemTrayInit() #else QIcon trayIconFile = QIcon(":/res/images/obs.png"); #endif - trayIcon.reset(new QSystemTrayIcon( - QIcon::fromTheme("obs-tray", trayIconFile), this)); + trayIcon.reset(new QSystemTrayIcon(QIcon::fromTheme("obs-tray", trayIconFile), this)); trayIcon->setToolTip("OBS Studio"); showHide = new QAction(QTStr("Basic.SystemTray.Show"), trayIcon.data()); - sysTrayStream = new QAction( - StreamingActive() ? QTStr("Basic.Main.StopStreaming") - : QTStr("Basic.Main.StartStreaming"), - trayIcon.data()); - sysTrayRecord = new QAction( - RecordingActive() ? QTStr("Basic.Main.StopRecording") - : QTStr("Basic.Main.StartRecording"), - trayIcon.data()); - sysTrayReplayBuffer = new QAction( - ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer") - : QTStr("Basic.Main.StartReplayBuffer"), - trayIcon.data()); - sysTrayVirtualCam = new QAction( - VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam") - : QTStr("Basic.Main.StartVirtualCam"), - trayIcon.data()); + sysTrayStream = + new QAction(StreamingActive() ? QTStr("Basic.Main.StopStreaming") : QTStr("Basic.Main.StartStreaming"), + trayIcon.data()); + sysTrayRecord = + new QAction(RecordingActive() ? QTStr("Basic.Main.StopRecording") : QTStr("Basic.Main.StartRecording"), + trayIcon.data()); + sysTrayReplayBuffer = new QAction(ReplayBufferActive() ? QTStr("Basic.Main.StopReplayBuffer") + : QTStr("Basic.Main.StartReplayBuffer"), + trayIcon.data()); + sysTrayVirtualCam = new QAction(VirtualCamActive() ? QTStr("Basic.Main.StopVirtualCam") + : QTStr("Basic.Main.StartVirtualCam"), + trayIcon.data()); exit = new QAction(QTStr("Exit"), trayIcon.data()); trayMenu = new QMenu; previewProjector = new QMenu(QTStr("PreviewProjector")); studioProgramProjector = new QMenu(QTStr("StudioProgramProjector")); - AddProjectorMenuMonitors(previewProjector, this, - &OBSBasic::OpenPreviewProjector); - AddProjectorMenuMonitors(studioProgramProjector, this, - &OBSBasic::OpenStudioProgramProjector); + AddProjectorMenuMonitors(previewProjector, this, &OBSBasic::OpenPreviewProjector); + AddProjectorMenuMonitors(studioProgramProjector, this, &OBSBasic::OpenStudioProgramProjector); trayMenu->addAction(showHide); trayMenu->addSeparator(); trayMenu->addMenu(previewProjector); @@ -10129,17 +9072,12 @@ void OBSBasic::SystemTrayInit() if (Active()) OnActivate(true); - connect(trayIcon.data(), &QSystemTrayIcon::activated, this, - &OBSBasic::IconActivated); + connect(trayIcon.data(), &QSystemTrayIcon::activated, this, &OBSBasic::IconActivated); connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide); - connect(sysTrayStream, &QAction::triggered, this, - &OBSBasic::StreamActionTriggered); - connect(sysTrayRecord, &QAction::triggered, this, - &OBSBasic::RecordActionTriggered); - connect(sysTrayReplayBuffer.data(), &QAction::triggered, this, - &OBSBasic::ReplayBufferActionTriggered); - connect(sysTrayVirtualCam.data(), &QAction::triggered, this, - &OBSBasic::VirtualCamActionTriggered); + connect(sysTrayStream, &QAction::triggered, this, &OBSBasic::StreamActionTriggered); + connect(sysTrayRecord, &QAction::triggered, this, &OBSBasic::RecordActionTriggered); + connect(sysTrayReplayBuffer.data(), &QAction::triggered, this, &OBSBasic::ReplayBufferActionTriggered); + connect(sysTrayVirtualCam.data(), &QAction::triggered, this, &OBSBasic::VirtualCamActionTriggered); connect(exit, &QAction::triggered, this, &OBSBasic::close); } @@ -10148,10 +9086,8 @@ void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason) // Refresh projector list previewProjector->clear(); studioProgramProjector->clear(); - AddProjectorMenuMonitors(previewProjector, this, - &OBSBasic::OpenPreviewProjector); - AddProjectorMenuMonitors(studioProgramProjector, this, - &OBSBasic::OpenStudioProgramProjector); + AddProjectorMenuMonitors(previewProjector, this, &OBSBasic::OpenPreviewProjector); + AddProjectorMenuMonitors(studioProgramProjector, this, &OBSBasic::OpenStudioProgramProjector); #ifdef __APPLE__ UNUSED_PARAMETER(reason); @@ -10163,13 +9099,10 @@ void OBSBasic::IconActivated(QSystemTrayIcon::ActivationReason reason) #endif } -void OBSBasic::SysTrayNotify(const QString &text, - QSystemTrayIcon::MessageIcon n) +void OBSBasic::SysTrayNotify(const QString &text, QSystemTrayIcon::MessageIcon n) { - if (trayIcon && trayIcon->isVisible() && - QSystemTrayIcon::supportsMessages()) { - QSystemTrayIcon::MessageIcon icon = - QSystemTrayIcon::MessageIcon(n); + if (trayIcon && trayIcon->isVisible() && QSystemTrayIcon::supportsMessages()) { + QSystemTrayIcon::MessageIcon icon = QSystemTrayIcon::MessageIcon(n); trayIcon->showMessage("OBS Studio", text, icon, 10000); } } @@ -10181,10 +9114,8 @@ void OBSBasic::SystemTray(bool firstStarted) if (!trayIcon && !firstStarted) return; - bool sysTrayWhenStarted = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); - bool sysTrayEnabled = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "SysTrayEnabled"); + bool sysTrayWhenStarted = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); + bool sysTrayEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled"); if (firstStarted) SystemTrayInit(); @@ -10210,8 +9141,7 @@ void OBSBasic::SystemTray(bool firstStarted) bool OBSBasic::sysTrayMinimizeToTray() { - return config_get_bool(App()->GetUserConfig(), "BasicWindow", - "SysTrayMinimizeToTray"); + return config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayMinimizeToTray"); } void OBSBasic::on_actionMainUndo_triggered() @@ -10281,8 +9211,7 @@ void OBSBasic::on_actionPasteRef_triggered() const char *scene_name = obs_source_get_name(scene_source); OBSData redo_data = BackupScene(scene_source); - CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data, - redo_data); + CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data, redo_data); } void OBSBasic::on_actionPasteDup_triggered() @@ -10303,8 +9232,7 @@ void OBSBasic::on_actionPasteDup_triggered() const char *scene_name = obs_source_get_name(scene_source); OBSData redo_data = BackupScene(scene_source); - CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data, - redo_data); + CreateSceneUndoRedoAction(action_name.arg(scene_name), undo_data, redo_data); } void OBSBasic::SourcePasteFilters(OBSSource source, OBSSource dstSource) @@ -10312,19 +9240,15 @@ void OBSBasic::SourcePasteFilters(OBSSource source, OBSSource dstSource) if (source == dstSource) return; - OBSDataArrayAutoRelease undo_array = - obs_source_backup_filters(dstSource); + OBSDataArrayAutoRelease undo_array = obs_source_backup_filters(dstSource); obs_source_copy_filters(dstSource, source); - OBSDataArrayAutoRelease redo_array = - obs_source_backup_filters(dstSource); + OBSDataArrayAutoRelease redo_array = obs_source_backup_filters(dstSource); const char *srcName = obs_source_get_name(source); const char *dstName = obs_source_get_name(dstSource); - QString text = - QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName); + QString text = QTStr("Undo.Filters.Paste.Multiple").arg(srcName, dstName); - CreateFilterPasteUndoRedoAction(text, dstSource, undo_array, - redo_array); + CreateFilterPasteUndoRedoAction(text, dstSource, undo_array, redo_array); } void OBSBasic::AudioMixerCopyFilters() @@ -10343,8 +9267,7 @@ void OBSBasic::AudioMixerPasteFilters() VolControl *vol = action->property("volControl").value(); obs_source_t *dstSource = vol->GetSource(); - OBSSourceAutoRelease source = - obs_weak_source_get_source(copyFiltersSource); + OBSSourceAutoRelease source = obs_weak_source_get_source(copyFiltersSource); SourcePasteFilters(source.Get(), dstSource); } @@ -10357,8 +9280,7 @@ void OBSBasic::SceneCopyFilters() void OBSBasic::ScenePasteFilters() { - OBSSourceAutoRelease source = - obs_weak_source_get_source(copyFiltersSource); + OBSSourceAutoRelease source = obs_weak_source_get_source(copyFiltersSource); OBSSource dstSource = GetCurrentSceneSource(); @@ -10379,18 +9301,13 @@ void OBSBasic::on_actionCopyFilters_triggered() ui->actionPasteFilters->setEnabled(true); } -void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text, - obs_source_t *source, - obs_data_array_t *undo_array, +void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text, obs_source_t *source, obs_data_array_t *undo_array, obs_data_array_t *redo_array) { auto undo_redo = [this](const std::string &json) { - OBSDataAutoRelease data = - obs_data_create_from_json(json.c_str()); - OBSDataArrayAutoRelease array = - obs_data_get_array(data, "array"); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(data, "uuid")); + OBSDataAutoRelease data = obs_data_create_from_json(json.c_str()); + OBSDataArrayAutoRelease array = obs_data_get_array(data, "array"); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(data, "uuid")); obs_source_restore_filters(source, array); @@ -10407,15 +9324,12 @@ void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text, obs_data_set_string(undo_data, "uuid", uuid); obs_data_set_string(redo_data, "uuid", uuid); - undo_s.add_action(text, undo_redo, undo_redo, - obs_data_get_json(undo_data), - obs_data_get_json(redo_data)); + undo_s.add_action(text, undo_redo, undo_redo, obs_data_get_json(undo_data), obs_data_get_json(redo_data)); } void OBSBasic::on_actionPasteFilters_triggered() { - OBSSourceAutoRelease source = - obs_weak_source_get_source(copyFiltersSource); + OBSSourceAutoRelease source = obs_weak_source_get_source(copyFiltersSource); OBSSceneItem sceneItem = GetCurrentSceneItem(); OBSSource dstSource = obs_sceneitem_get_source(sceneItem); @@ -10423,30 +9337,24 @@ void OBSBasic::on_actionPasteFilters_triggered() SourcePasteFilters(source.Get(), dstSource); } -static void ConfirmColor(SourceTree *sources, const QColor &color, - QModelIndexList selectedItems) +static void ConfirmColor(SourceTree *sources, const QColor &color, QModelIndexList selectedItems) { for (int x = 0; x < selectedItems.count(); x++) { - SourceTreeItem *treeItem = - sources->GetItemWidget(selectedItems[x].row()); - treeItem->setStyleSheet("background: " + - color.name(QColor::HexArgb)); + SourceTreeItem *treeItem = sources->GetItemWidget(selectedItems[x].row()); + treeItem->setStyleSheet("background: " + color.name(QColor::HexArgb)); treeItem->style()->unpolish(treeItem); treeItem->style()->polish(treeItem); OBSSceneItem sceneItem = sources->Get(selectedItems[x].row()); - OBSDataAutoRelease privData = - obs_sceneitem_get_private_settings(sceneItem); + OBSDataAutoRelease privData = obs_sceneitem_get_private_settings(sceneItem); obs_data_set_int(privData, "color-preset", 1); - obs_data_set_string(privData, "color", - QT_TO_UTF8(color.name(QColor::HexArgb))); + obs_data_set_string(privData, "color", QT_TO_UTF8(color.name(QColor::HexArgb))); } } void OBSBasic::ColorChange() { - QModelIndexList selectedItems = - ui->sources->selectionModel()->selectedIndexes(); + QModelIndexList selectedItems = ui->sources->selectionModel()->selectedIndexes(); QAction *action = qobject_cast(sender()); QPushButton *colorButton = qobject_cast(sender()); @@ -10457,17 +9365,14 @@ void OBSBasic::ColorChange() int preset = colorButton->property("bgColor").value(); for (int x = 0; x < selectedItems.count(); x++) { - SourceTreeItem *treeItem = ui->sources->GetItemWidget( - selectedItems[x].row()); + SourceTreeItem *treeItem = ui->sources->GetItemWidget(selectedItems[x].row()); treeItem->setStyleSheet(""); treeItem->setProperty("bgColor", preset); treeItem->style()->unpolish(treeItem); treeItem->style()->polish(treeItem); - OBSSceneItem sceneItem = - ui->sources->Get(selectedItems[x].row()); - OBSDataAutoRelease privData = - obs_sceneitem_get_private_settings(sceneItem); + OBSSceneItem sceneItem = ui->sources->Get(selectedItems[x].row()); + OBSDataAutoRelease privData = obs_sceneitem_get_private_settings(sceneItem); obs_data_set_int(privData, "color-preset", preset + 1); obs_data_set_string(privData, "color", ""); } @@ -10476,9 +9381,7 @@ void OBSBasic::ColorChange() stringstream button; button << "preset" << i; QPushButton *cButton = - colorButton->parentWidget() - ->findChild( - button.str().c_str()); + colorButton->parentWidget()->findChild(button.str().c_str()); cButton->setStyleSheet("border: 1px solid black"); } @@ -10488,28 +9391,21 @@ void OBSBasic::ColorChange() if (preset == 1) { OBSSceneItem curSceneItem = GetCurrentSceneItem(); - SourceTreeItem *curTreeItem = - GetItemWidgetFromSceneItem(curSceneItem); - OBSDataAutoRelease curPrivData = - obs_sceneitem_get_private_settings( - curSceneItem); + SourceTreeItem *curTreeItem = GetItemWidgetFromSceneItem(curSceneItem); + OBSDataAutoRelease curPrivData = obs_sceneitem_get_private_settings(curSceneItem); - int oldPreset = - obs_data_get_int(curPrivData, "color-preset"); + int oldPreset = obs_data_get_int(curPrivData, "color-preset"); const QString oldSheet = curTreeItem->styleSheet(); auto liveChangeColor = [=](const QColor &color) { if (color.isValid()) { - curTreeItem->setStyleSheet( - "background: " + - color.name(QColor::HexArgb)); + curTreeItem->setStyleSheet("background: " + color.name(QColor::HexArgb)); } }; auto changedColor = [=](const QColor &color) { if (color.isValid()) { - ConfirmColor(ui->sources, color, - selectedItems); + ConfirmColor(ui->sources, color, selectedItems); } }; @@ -10518,26 +9414,21 @@ void OBSBasic::ColorChange() curTreeItem->setStyleSheet(oldSheet); curTreeItem->setProperty("bgColor", 0); } else if (oldPreset == 0) { - curTreeItem->setStyleSheet( - "background: none"); + curTreeItem->setStyleSheet("background: none"); curTreeItem->setProperty("bgColor", 0); } else { curTreeItem->setStyleSheet(""); - curTreeItem->setProperty("bgColor", - oldPreset - 1); + curTreeItem->setProperty("bgColor", oldPreset - 1); } curTreeItem->style()->unpolish(curTreeItem); curTreeItem->style()->polish(curTreeItem); }; - QColorDialog::ColorDialogOptions options = - QColorDialog::ShowAlphaChannel; + QColorDialog::ColorDialogOptions options = QColorDialog::ShowAlphaChannel; - const char *oldColor = - obs_data_get_string(curPrivData, "color"); - const char *customColor = *oldColor != 0 ? oldColor - : "#55FF0000"; + const char *oldColor = obs_data_get_string(curPrivData, "color"); + const char *customColor = *oldColor != 0 ? oldColor : "#55FF0000"; #ifdef __linux__ // TODO: Revisit hang on Ubuntu with native dialog options |= QColorDialog::DontUseNativeDialog; @@ -10546,29 +9437,21 @@ void OBSBasic::ColorChange() QColorDialog *colorDialog = new QColorDialog(this); colorDialog->setOptions(options); colorDialog->setCurrentColor(QColor(customColor)); - connect(colorDialog, &QColorDialog::currentColorChanged, - liveChangeColor); - connect(colorDialog, &QColorDialog::colorSelected, - changedColor); + connect(colorDialog, &QColorDialog::currentColorChanged, liveChangeColor); + connect(colorDialog, &QColorDialog::colorSelected, changedColor); connect(colorDialog, &QColorDialog::rejected, rejected); colorDialog->open(); } else { for (int x = 0; x < selectedItems.count(); x++) { - SourceTreeItem *treeItem = - ui->sources->GetItemWidget( - selectedItems[x].row()); + SourceTreeItem *treeItem = ui->sources->GetItemWidget(selectedItems[x].row()); treeItem->setStyleSheet("background: none"); treeItem->setProperty("bgColor", preset); treeItem->style()->unpolish(treeItem); treeItem->style()->polish(treeItem); - OBSSceneItem sceneItem = ui->sources->Get( - selectedItems[x].row()); - OBSDataAutoRelease privData = - obs_sceneitem_get_private_settings( - sceneItem); - obs_data_set_int(privData, "color-preset", - preset); + OBSSceneItem sceneItem = ui->sources->Get(selectedItems[x].row()); + OBSDataAutoRelease privData = obs_sceneitem_get_private_settings(sceneItem); + obs_data_set_int(privData, "color-preset", preset); obs_data_set_string(privData, "color", ""); } } @@ -10633,8 +9516,7 @@ void OBSBasic::ResizeOutputSizeOfSource() QMessageBox resize_output(this); resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" + QTStr("ResizeOutputSizeOfSource.Continue")); - QAbstractButton *Yes = - resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole); + QAbstractButton *Yes = resize_output.addButton(QTStr("Yes"), QMessageBox::YesRole); resize_output.addButton(QTStr("No"), QMessageBox::NoRole); resize_output.setIcon(QMessageBox::Warning); resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource")); @@ -10662,15 +9544,13 @@ void OBSBasic::ResizeOutputSizeOfSource() QAction *OBSBasic::AddDockWidget(QDockWidget *dock) { // Prevent the object name from being changed - connect(dock, &QObject::objectNameChanged, this, - &OBSBasic::RepairOldExtraDockName); + connect(dock, &QObject::objectNameChanged, this, &OBSBasic::RepairOldExtraDockName); #ifdef BROWSER_AVAILABLE QAction *action = new QAction(dock->windowTitle(), ui->menuDocks); if (!extraBrowserMenuDocksSeparator.isNull()) - ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator, - action); + ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator, action); else ui->menuDocks->addAction(action); #else @@ -10684,8 +9564,7 @@ QAction *OBSBasic::AddDockWidget(QDockWidget *dock) bool lock = ui->lockDocks->isChecked(); QDockWidget::DockWidgetFeatures features = lock ? QDockWidget::NoDockWidgetFeatures - : (QDockWidget::DockWidgetClosable | - QDockWidget::DockWidgetMovable | + : (QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); dock->setFeatures(features); @@ -10712,14 +9591,12 @@ void OBSBasic::RepairOldExtraDockName() return; } - blog(LOG_WARNING, "The dock '%s' got its object name restored", - QT_TO_UTF8(oldExtraDockNames[idx])); + blog(LOG_WARNING, "The dock '%s' got its object name restored", QT_TO_UTF8(oldExtraDockNames[idx])); dock->setObjectName(oldExtraDockNames[idx]); } -void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, - bool extraBrowser) +void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, bool extraBrowser) { if (dock->objectName().isEmpty()) return; @@ -10727,8 +9604,7 @@ void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, bool lock = ui->lockDocks->isChecked(); QDockWidget::DockWidgetFeatures features = lock ? QDockWidget::NoDockWidgetFeatures - : (QDockWidget::DockWidgetClosable | - QDockWidget::DockWidgetMovable | + : (QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); setupDockAction(dock); @@ -10740,8 +9616,7 @@ void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator(); if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull()) - ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator, - dock->toggleViewAction()); + ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator, dock->toggleViewAction()); else ui->menuDocks->addAction(dock->toggleViewAction()); @@ -10791,14 +9666,12 @@ bool OBSBasic::IsDockObjectNameUsed(const QString &name) void OBSBasic::AddCustomDockWidget(QDockWidget *dock) { // Prevent the object name from being changed - connect(dock, &QObject::objectNameChanged, this, - &OBSBasic::RepairCustomExtraDockName); + connect(dock, &QObject::objectNameChanged, this, &OBSBasic::RepairCustomExtraDockName); bool lock = ui->lockDocks->isChecked(); QDockWidget::DockWidgetFeatures features = lock ? QDockWidget::NoDockWidgetFeatures - : (QDockWidget::DockWidgetClosable | - QDockWidget::DockWidgetMovable | + : (QDockWidget::DockWidgetClosable | QDockWidget::DockWidgetMovable | QDockWidget::DockWidgetFloatable); dock->setFeatures(features); @@ -10819,8 +9692,7 @@ void OBSBasic::RepairCustomExtraDockName() return; } - blog(LOG_WARNING, "The custom dock '%s' got its object name restored", - QT_TO_UTF8(extraCustomDockNames[idx])); + blog(LOG_WARNING, "The custom dock '%s' got its object name restored", QT_TO_UTF8(extraCustomDockNames[idx])); dock->setObjectName(extraCustomDockNames[idx]); } @@ -10858,13 +9730,9 @@ bool OBSBasic::VirtualCamActive() return outputHandler->VirtualCamActive(); } -SceneRenameDelegate::SceneRenameDelegate(QObject *parent) - : QStyledItemDelegate(parent) -{ -} +SceneRenameDelegate::SceneRenameDelegate(QObject *parent) : QStyledItemDelegate(parent) {} -void SceneRenameDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const +void SceneRenameDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QStyledItemDelegate::setEditorData(editor, index); QLineEdit *lineEdit = qobject_cast(editor); @@ -10902,8 +9770,7 @@ void OBSBasic::UpdatePatronJson(const QString &text, const QString &error) void OBSBasic::PauseRecording() { - if (!isRecordingPausable || !outputHandler || - !outputHandler->fileOutput || + if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput || os_atomic_load_bool(&recording_paused)) return; @@ -10919,15 +9786,12 @@ void OBSBasic::PauseRecording() TaskbarOverlaySetStatus(TaskbarOverlayStatusPaused); if (trayIcon && trayIcon->isVisible()) { #ifdef __APPLE__ - QIcon trayIconFile = - QIcon(":/res/images/obs_paused_macos.svg"); + QIcon trayIconFile = QIcon(":/res/images/obs_paused_macos.svg"); trayIconFile.setIsMask(true); #else - QIcon trayIconFile = - QIcon(":/res/images/obs_paused.png"); + QIcon trayIconFile = QIcon(":/res/images/obs_paused.png"); #endif - trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused", - trayIconFile)); + trayIcon->setIcon(QIcon::fromTheme("obs-tray-paused", trayIconFile)); } OnEvent(OBS_FRONTEND_EVENT_RECORDING_PAUSED); @@ -10939,8 +9803,7 @@ void OBSBasic::PauseRecording() void OBSBasic::UnpauseRecording() { - if (!isRecordingPausable || !outputHandler || - !outputHandler->fileOutput || + if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput || !os_atomic_load_bool(&recording_paused)) return; @@ -10956,15 +9819,12 @@ void OBSBasic::UnpauseRecording() TaskbarOverlaySetStatus(TaskbarOverlayStatusActive); if (trayIcon && trayIcon->isVisible()) { #ifdef __APPLE__ - QIcon trayIconFile = - QIcon(":/res/images/tray_active_macos.svg"); + QIcon trayIconFile = QIcon(":/res/images/tray_active_macos.svg"); trayIconFile.setIsMask(true); #else - QIcon trayIconFile = - QIcon(":/res/images/tray_active.png"); + QIcon trayIconFile = QIcon(":/res/images/tray_active.png"); #endif - trayIcon->setIcon(QIcon::fromTheme("obs-tray-active", - trayIconFile)); + trayIcon->setIcon(QIcon::fromTheme("obs-tray-active", trayIconFile)); } OnEvent(OBS_FRONTEND_EVENT_RECORDING_UNPAUSED); @@ -10973,8 +9833,7 @@ void OBSBasic::UnpauseRecording() void OBSBasic::RecordPauseToggled() { - if (!isRecordingPausable || !outputHandler || - !outputHandler->fileOutput) + if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput) return; obs_output_t *output = outputHandler->fileOutput; @@ -10988,26 +9847,21 @@ void OBSBasic::RecordPauseToggled() void OBSBasic::UpdateIsRecordingPausable() { - const char *mode = - config_get_string(activeConfiguration, "Output", "Mode"); + const char *mode = config_get_string(activeConfiguration, "Output", "Mode"); bool adv = astrcmpi(mode, "Advanced") == 0; bool shared = true; if (adv) { - const char *recType = config_get_string(activeConfiguration, - "AdvOut", "RecType"); + const char *recType = config_get_string(activeConfiguration, "AdvOut", "RecType"); if (astrcmpi(recType, "FFmpeg") == 0) { - shared = config_get_bool(activeConfiguration, "AdvOut", - "FFOutputToFile"); + shared = config_get_bool(activeConfiguration, "AdvOut", "FFOutputToFile"); } else { - const char *recordEncoder = config_get_string( - activeConfiguration, "AdvOut", "RecEncoder"); + const char *recordEncoder = config_get_string(activeConfiguration, "AdvOut", "RecEncoder"); shared = astrcmpi(recordEncoder, "none") == 0; } } else { - const char *quality = config_get_string( - activeConfiguration, "SimpleOutput", "RecQuality"); + const char *quality = config_get_string(activeConfiguration, "SimpleOutput", "RecQuality"); shared = strcmp(quality, "Stream") == 0; } @@ -11024,15 +9878,12 @@ const char *OBSBasic::GetCurrentOutputPath() const char *mode = config_get_string(Config(), "Output", "Mode"); if (strcmp(mode, "Advanced") == 0) { - const char *advanced_mode = - config_get_string(Config(), "AdvOut", "RecType"); + const char *advanced_mode = config_get_string(Config(), "AdvOut", "RecType"); if (strcmp(advanced_mode, "FFmpeg") == 0) { - path = config_get_string(Config(), "AdvOut", - "FFFilePath"); + path = config_get_string(Config(), "AdvOut", "FFFilePath"); } else { - path = config_get_string(Config(), "AdvOut", - "RecFilePath"); + path = config_get_string(Config(), "AdvOut", "RecFilePath"); } } else { path = config_get_string(Config(), "SimpleOutput", "FilePath"); @@ -11045,19 +9896,16 @@ void OBSBasic::OutputPathInvalidMessage() { blog(LOG_ERROR, "Recording stopped because of bad output path"); - OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"), - QTStr("Output.BadPath.Text")); + OBSMessageBox::critical(this, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text")); } bool OBSBasic::IsFFmpegOutputToURL() const { const char *mode = config_get_string(Config(), "Output", "Mode"); if (strcmp(mode, "Advanced") == 0) { - const char *advanced_mode = - config_get_string(Config(), "AdvOut", "RecType"); + const char *advanced_mode = config_get_string(Config(), "AdvOut", "RecType"); if (strcmp(advanced_mode, "FFmpeg") == 0) { - bool is_local = config_get_bool(Config(), "AdvOut", - "FFOutputToFile"); + bool is_local = config_get_bool(Config(), "AdvOut", "FFOutputToFile"); if (!is_local) return true; } @@ -11079,8 +9927,7 @@ void OBSBasic::DiskSpaceMessage() { blog(LOG_ERROR, "Recording stopped because of low disk space"); - OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"), - QTStr("Output.RecordNoSpace.Msg")); + OBSMessageBox::critical(this, QTStr("Output.RecordNoSpace.Title"), QTStr("Output.RecordNoSpace.Msg")); } bool OBSBasic::LowDiskSpace() @@ -11129,8 +9976,7 @@ void OBSBasic::on_OBSBasic_customContextMenuRequested(const QPoint &pos) } QPoint globalPos = mapToGlobal(pos); - if (className && strstr(className, "Dock") != nullptr && - !objName.isEmpty()) { + if (className && strstr(className, "Dock") != nullptr && !objName.isEmpty()) { if (objName.compare("scenesDock") == 0) { ui->scenes->customContextMenuRequested(globalPos); } else if (objName.compare("sourcesDock") == 0) { @@ -11194,18 +10040,14 @@ void OBSBasic::ShowStatusBarMessage(const QString &message) void OBSBasic::UpdatePreviewSafeAreas() { - drawSafeAreas = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ShowSafeAreas"); + drawSafeAreas = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ShowSafeAreas"); } void OBSBasic::UpdatePreviewOverflowSettings() { - bool hidden = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "OverflowHidden"); - bool select = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "OverflowSelectionHidden"); - bool always = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "OverflowAlwaysVisible"); + bool hidden = config_get_bool(App()->GetUserConfig(), "BasicWindow", "OverflowHidden"); + bool select = config_get_bool(App()->GetUserConfig(), "BasicWindow", "OverflowSelectionHidden"); + bool always = config_get_bool(App()->GetUserConfig(), "BasicWindow", "OverflowAlwaysVisible"); ui->preview->SetOverflowHidden(hidden); ui->preview->SetOverflowSelectionHidden(select); @@ -11217,9 +10059,7 @@ void OBSBasic::SetDisplayAffinity(QWindow *window) if (!SetDisplayAffinitySupported()) return; - bool hideFromCapture = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "HideOBSWindowsFromCapture"); + bool hideFromCapture = config_get_bool(App()->GetUserConfig(), "BasicWindow", "HideOBSWindowsFromCapture"); // Don't hide projectors, those are designed to be visible / captured if (window->property("isOBSProjectorWindow") == true) @@ -11245,16 +10085,13 @@ void OBSBasic::SetDisplayAffinity(QWindow *window) static inline QColor color_from_int(long long val) { - return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, - (val >> 24) & 0xff); + return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff); } QColor OBSBasic::GetSelectionColor() const { - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - return color_from_int(config_get_int( - App()->GetUserConfig(), "Accessibility", "SelectRed")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + return color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "SelectRed")); } else { return QColor::fromRgb(255, 0, 0); } @@ -11262,11 +10099,8 @@ QColor OBSBasic::GetSelectionColor() const QColor OBSBasic::GetCropColor() const { - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - return color_from_int(config_get_int(App()->GetUserConfig(), - "Accessibility", - "SelectGreen")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + return color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "SelectGreen")); } else { return QColor::fromRgb(0, 255, 0); } @@ -11274,10 +10108,8 @@ QColor OBSBasic::GetCropColor() const QColor OBSBasic::GetHoverColor() const { - if (config_get_bool(App()->GetUserConfig(), "Accessibility", - "OverrideColors")) { - return color_from_int(config_get_int( - App()->GetUserConfig(), "Accessibility", "SelectBlue")); + if (config_get_bool(App()->GetUserConfig(), "Accessibility", "OverrideColors")) { + return color_from_int(config_get_int(App()->GetUserConfig(), "Accessibility", "SelectBlue")); } else { return QColor::fromRgb(0, 127, 255); } @@ -11285,8 +10117,7 @@ QColor OBSBasic::GetHoverColor() const void OBSBasic::UpdatePreviewSpacingHelpers() { - drawSpacingHelpers = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SpacingHelpersEnabled"); + drawSpacingHelpers = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SpacingHelpersEnabled"); } float OBSBasic::GetDevicePixelRatio() @@ -11335,8 +10166,7 @@ void OBSBasic::PreviewScalingModeChanged(int value) // MARK: - Generic UI Helper Functions -OBSPromptResult OBSBasic::PromptForName(const OBSPromptRequest &request, - const OBSPromptCallback &callback) +OBSPromptResult OBSBasic::PromptForName(const OBSPromptRequest &request, const OBSPromptCallback &callback) { OBSPromptResult result; @@ -11347,21 +10177,14 @@ OBSPromptResult OBSBasic::PromptForName(const OBSPromptRequest &request, result.optionValue = request.optionValue; result.success = NameDialog::AskForNameWithOption( - this, request.title.c_str(), - request.prompt.c_str(), result.promptValue, - request.optionPrompt.c_str(), - result.optionValue, - (request.promptValue.empty() - ? nullptr - : request.promptValue.c_str())); + this, request.title.c_str(), request.prompt.c_str(), result.promptValue, + request.optionPrompt.c_str(), result.optionValue, + (request.promptValue.empty() ? nullptr : request.promptValue.c_str())); } else { result.success = NameDialog::AskForName( - this, request.title.c_str(), - request.prompt.c_str(), result.promptValue, - (request.promptValue.empty() - ? nullptr - : request.promptValue.c_str())); + this, request.title.c_str(), request.prompt.c_str(), result.promptValue, + (request.promptValue.empty() ? nullptr : request.promptValue.c_str())); } if (!result.success) { @@ -11369,15 +10192,12 @@ OBSPromptResult OBSBasic::PromptForName(const OBSPromptRequest &request, } if (result.promptValue.empty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); continue; } if (!callback(result)) { - OBSMessageBox::warning(this, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::warning(this, QTStr("NameExists.Title"), QTStr("NameExists.Text")); continue; } diff --git a/UI/window-basic-main.hpp b/UI/window-basic-main.hpp index 2131e16de..d04edfeff 100644 --- a/UI/window-basic-main.hpp +++ b/UI/window-basic-main.hpp @@ -117,15 +117,13 @@ struct QuickTransition { bool fadeToBlack = false; inline QuickTransition() {} - inline QuickTransition(OBSSource source_, int duration_, int id_, - bool fadeToBlack_ = false) + inline QuickTransition(OBSSource source_, int duration_, int id_, bool fadeToBlack_ = false) : source(source_), duration(duration_), id(id_), fadeToBlack(fadeToBlack_), - renamedSignal(std::make_shared( - obs_source_get_signal_handler(source), "rename", - SourceRenamed, this)) + renamedSignal(std::make_shared(obs_source_get_signal_handler(source), "rename", + SourceRenamed, this)) { } @@ -178,38 +176,23 @@ private: class OBSBasic : public OBSMainWindow { Q_OBJECT - Q_PROPERTY(QIcon imageIcon READ GetImageIcon WRITE SetImageIcon + Q_PROPERTY(QIcon imageIcon READ GetImageIcon WRITE SetImageIcon DESIGNABLE true) + Q_PROPERTY(QIcon colorIcon READ GetColorIcon WRITE SetColorIcon DESIGNABLE true) + Q_PROPERTY(QIcon slideshowIcon READ GetSlideshowIcon WRITE SetSlideshowIcon DESIGNABLE true) + Q_PROPERTY(QIcon audioInputIcon READ GetAudioInputIcon WRITE SetAudioInputIcon DESIGNABLE true) + Q_PROPERTY(QIcon audioOutputIcon READ GetAudioOutputIcon WRITE SetAudioOutputIcon DESIGNABLE true) + Q_PROPERTY(QIcon desktopCapIcon READ GetDesktopCapIcon WRITE SetDesktopCapIcon DESIGNABLE true) + Q_PROPERTY(QIcon windowCapIcon READ GetWindowCapIcon WRITE SetWindowCapIcon DESIGNABLE true) + Q_PROPERTY(QIcon gameCapIcon READ GetGameCapIcon WRITE SetGameCapIcon DESIGNABLE true) + Q_PROPERTY(QIcon cameraIcon READ GetCameraIcon WRITE SetCameraIcon DESIGNABLE true) + Q_PROPERTY(QIcon textIcon READ GetTextIcon WRITE SetTextIcon DESIGNABLE true) + Q_PROPERTY(QIcon mediaIcon READ GetMediaIcon WRITE SetMediaIcon DESIGNABLE true) + Q_PROPERTY(QIcon browserIcon READ GetBrowserIcon WRITE SetBrowserIcon DESIGNABLE true) + Q_PROPERTY(QIcon groupIcon READ GetGroupIcon WRITE SetGroupIcon DESIGNABLE true) + Q_PROPERTY(QIcon sceneIcon READ GetSceneIcon WRITE SetSceneIcon DESIGNABLE true) + Q_PROPERTY(QIcon defaultIcon READ GetDefaultIcon WRITE SetDefaultIcon DESIGNABLE true) + Q_PROPERTY(QIcon audioProcessOutputIcon READ GetAudioProcessOutputIcon WRITE SetAudioProcessOutputIcon DESIGNABLE true) - Q_PROPERTY(QIcon colorIcon READ GetColorIcon WRITE SetColorIcon - DESIGNABLE true) - Q_PROPERTY(QIcon slideshowIcon READ GetSlideshowIcon WRITE - SetSlideshowIcon DESIGNABLE true) - Q_PROPERTY(QIcon audioInputIcon READ GetAudioInputIcon WRITE - SetAudioInputIcon DESIGNABLE true) - Q_PROPERTY(QIcon audioOutputIcon READ GetAudioOutputIcon WRITE - SetAudioOutputIcon DESIGNABLE true) - Q_PROPERTY(QIcon desktopCapIcon READ GetDesktopCapIcon WRITE - SetDesktopCapIcon DESIGNABLE true) - Q_PROPERTY(QIcon windowCapIcon READ GetWindowCapIcon WRITE - SetWindowCapIcon DESIGNABLE true) - Q_PROPERTY(QIcon gameCapIcon READ GetGameCapIcon WRITE SetGameCapIcon - DESIGNABLE true) - Q_PROPERTY(QIcon cameraIcon READ GetCameraIcon WRITE SetCameraIcon - DESIGNABLE true) - Q_PROPERTY(QIcon textIcon READ GetTextIcon WRITE SetTextIcon - DESIGNABLE true) - Q_PROPERTY(QIcon mediaIcon READ GetMediaIcon WRITE SetMediaIcon - DESIGNABLE true) - Q_PROPERTY(QIcon browserIcon READ GetBrowserIcon WRITE SetBrowserIcon - DESIGNABLE true) - Q_PROPERTY(QIcon groupIcon READ GetGroupIcon WRITE SetGroupIcon - DESIGNABLE true) - Q_PROPERTY(QIcon sceneIcon READ GetSceneIcon WRITE SetSceneIcon - DESIGNABLE true) - Q_PROPERTY(QIcon defaultIcon READ GetDefaultIcon WRITE SetDefaultIcon - DESIGNABLE true) - Q_PROPERTY(QIcon audioProcessOutputIcon READ GetAudioProcessOutputIcon - WRITE SetAudioProcessOutputIcon DESIGNABLE true) friend class OBSAbout; friend class OBSBasicPreview; @@ -243,11 +226,7 @@ class OBSBasic : public OBSMainWindow { DropType_Url, }; - enum ContextBarSize { - ContextBarSize_Minimized, - ContextBarSize_Reduced, - ContextBarSize_Normal - }; + enum ContextBarSize { ContextBarSize_Minimized, ContextBarSize_Reduced, ContextBarSize_Normal }; enum class CenterType { Scene, @@ -414,8 +393,7 @@ private: void UploadLog(const char *subdir, const char *file, const bool crash); void Save(const char *file); - void LoadData(obs_data_t *data, const char *file, - bool remigrate = false); + void LoadData(obs_data_t *data, const char *file, bool remigrate = false); void Load(const char *file, bool remigrate = false); void InitHotkeys(); @@ -455,8 +433,7 @@ private: void ChangeSceneIndex(bool relative, int idx, int invalidIdx); void TempFileOutput(const char *path, int vBitrate, int aBitrate); - void TempStreamOutput(const char *url, const char *key, int vBitrate, - int aBitrate); + void TempStreamOutput(const char *url, const char *key, int vBitrate, int aBitrate); void CloseDialogs(); void ClearSceneData(); @@ -464,8 +441,7 @@ private: void Nudge(int dist, MoveDir dir); - OBSProjector *OpenProjector(obs_source_t *source, int monitor, - ProjectorType type); + OBSProjector *OpenProjector(obs_source_t *source, int monitor, ProjectorType type); void GetAudioSourceFilters(); void GetAudioSourceProperties(); @@ -480,19 +456,16 @@ private: QModelIndexList GetAllSelectedSourceItems(); - obs_hotkey_pair_id streamingHotkeys, recordingHotkeys, pauseHotkeys, - replayBufHotkeys, vcamHotkeys, togglePreviewHotkeys, - contextBarHotkeys; - obs_hotkey_id forceStreamingStopHotkey, splitFileHotkey, - addChapterHotkey; + obs_hotkey_pair_id streamingHotkeys, recordingHotkeys, pauseHotkeys, replayBufHotkeys, vcamHotkeys, + togglePreviewHotkeys, contextBarHotkeys; + obs_hotkey_id forceStreamingStopHotkey, splitFileHotkey, addChapterHotkey; void InitDefaultTransitions(); void InitTransition(obs_source_t *transition); obs_source_t *FindTransition(const char *name); OBSSource GetCurrentTransition(); obs_data_array_t *SaveTransitions(); - void LoadTransitions(obs_data_array_t *transitions, - obs_load_source_cb cb, void *private_data); + void LoadTransitions(obs_data_array_t *transitions, obs_load_source_cb cb, void *private_data); obs_source_t *fadeTransition; obs_source_t *cutTransition; @@ -511,8 +484,7 @@ private: void EnableTransitionWidgets(bool enable); void CreateDefaultQuickTransitions(); - void PasteShowHideTransition(obs_sceneitem_t *item, bool show, - obs_source_t *tr, int duration); + void PasteShowHideTransition(obs_sceneitem_t *item, bool show, obs_source_t *tr, int duration); QMenu *CreatePerSceneTransitionMenu(); QMenu *CreateVisibilityTransitionMenu(bool visible); @@ -559,8 +531,7 @@ private: inline void OnDeactivate(); void AddDropSource(const char *file, DropType image); - void AddDropURL(const char *url, QString &name, obs_data_t *settings, - const obs_video_info &ovi); + void AddDropURL(const char *url, QString &name, obs_data_t *settings, const obs_video_info &ovi); void ConfirmDropUrl(const QString &url); void dragEnterEvent(QDragEnterEvent *event) override; void dragLeaveEvent(QDragLeaveEvent *event) override; @@ -605,8 +576,7 @@ private: void LoadExtraBrowserDocks(); void SaveExtraBrowserDocks(); void ManageExtraBrowserDocks(); - void AddExtraBrowserDock(const QString &title, const QString &url, - const QString &uuid, bool firstCreate); + void AddExtraBrowserDock(const QString &title, const QString &url, const QString &uuid, bool firstCreate); #endif QIcon imageIcon; @@ -653,8 +623,7 @@ private: QPointer screenshotData; - void MoveSceneItem(enum obs_order_movement movement, - const QString &action_name); + void MoveSceneItem(enum obs_order_movement movement, const QString &action_name); bool autoStartBroadcast = true; bool autoStopBroadcast = true; @@ -664,10 +633,8 @@ private: #ifdef YOUTUBE_ENABLED void YoutubeStreamCheck(const std::string &key); void ShowYouTubeAutoStartWarning(); - void YouTubeActionDialogOk(const QString &broadcast_id, - const QString &stream_id, const QString &key, - bool autostart, bool autostop, - bool start_now); + void YouTubeActionDialogOk(const QString &broadcast_id, const QString &stream_id, const QString &key, + bool autostart, bool autostop, bool start_now); #endif void BroadcastButtonClicked(); void SetBroadcastFlowEnabled(bool enabled); @@ -754,10 +721,8 @@ public slots: void SetTransition(OBSSource transition); void OverrideTransition(OBSSource transition); void TransitionToScene(OBSScene scene, bool force = false); - void TransitionToScene(OBSSource scene, bool force = false, - bool quickTransition = false, - int quickDuration = 0, bool black = false, - bool manual = false); + void TransitionToScene(OBSSource scene, bool force = false, bool quickTransition = false, int quickDuration = 0, + bool black = false, bool manual = false); void SetCurrentScene(OBSSource scene, bool force = false); void UpdatePatronJson(const QString &text, const QString &error); @@ -938,10 +903,7 @@ public: int GetTransitionDuration(); int GetTbarPosition(); - inline bool IsPreviewProgramMode() const - { - return os_atomic_load_bool(&previewProgramMode); - } + inline bool IsPreviewProgramMode() const { return os_atomic_load_bool(&previewProgramMode); } inline bool VCamEnabled() const { return vcamEnabled; } @@ -955,8 +917,7 @@ public: void RefreshVolumeColors(); - void ResetAudioDevice(const char *sourceId, const char *deviceId, - const char *deviceDesc, int channel); + void ResetAudioDevice(const char *sourceId, const char *deviceId, const char *deviceDesc, int channel); void NewProject(); void LoadProject(); @@ -971,10 +932,7 @@ public: inline bool SavingDisabled() const { return disableSaving; } - inline double GetCPUUsage() const - { - return os_cpu_usage_info_query(cpuUsageInfo); - } + inline double GetCPUUsage() const { return os_cpu_usage_info_query(cpuUsageInfo); } void SaveService(); bool LoadService(); @@ -995,8 +953,7 @@ public: QMenu *AddScaleFilteringMenu(QMenu *menu, obs_sceneitem_t *item); QMenu *AddBlendingMethodMenu(QMenu *menu, obs_sceneitem_t *item); QMenu *AddBlendingModeMenu(QMenu *menu, obs_sceneitem_t *item); - QMenu *AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction, - ColorSelect *select, + QMenu *AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction, ColorSelect *select, obs_sceneitem_t *item); void CreateSourcePopupMenu(int idx, bool preview); @@ -1013,8 +970,7 @@ public: void CreateEditTransformWindow(obs_sceneitem_t *item); QAction *AddDockWidget(QDockWidget *dock); - void AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, - bool extraBrowser = false); + void AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, bool extraBrowser = false); void RemoveDockWidget(const QString &name); bool IsDockObjectNameUsed(const QString &name); void AddCustomDockWidget(QDockWidget *dock); @@ -1027,8 +983,7 @@ public: static QList GetProjectorMenuMonitorsFormatted(); template - static void AddProjectorMenuMonitors(QMenu *parent, Receiver *target, - void (Receiver::*slot)(Args...)) + static void AddProjectorMenuMonitors(QMenu *parent, Receiver *target, void (Receiver::*slot)(Args...)) { auto projectors = GetProjectorMenuMonitorsFormatted(); for (int i = 0; i < projectors.size(); i++) { @@ -1046,23 +1001,16 @@ public: void ShowStatusBarMessage(const QString &message); - static OBSData - BackupScene(obs_scene_t *scene, - std::vector *sources = nullptr); - void CreateSceneUndoRedoAction(const QString &action_name, - OBSData undo_data, OBSData redo_data); + static OBSData BackupScene(obs_scene_t *scene, std::vector *sources = nullptr); + void CreateSceneUndoRedoAction(const QString &action_name, OBSData undo_data, OBSData redo_data); - static inline OBSData - BackupScene(obs_source_t *scene_source, - std::vector *sources = nullptr) + static inline OBSData BackupScene(obs_source_t *scene_source, std::vector *sources = nullptr) { obs_scene_t *scene = obs_scene_from_source(scene_source); return BackupScene(scene, sources); } - void CreateFilterPasteUndoRedoAction(const QString &text, - obs_source_t *source, - obs_data_array_t *undo_array, + void CreateFilterPasteUndoRedoAction(const QString &text, obs_source_t *source, obs_data_array_t *undo_array, obs_data_array_t *redo_array); void SetDisplayAffinity(QWindow *window); @@ -1072,8 +1020,7 @@ public: protected: virtual void closeEvent(QCloseEvent *event) override; - virtual bool nativeEvent(const QByteArray &eventType, void *message, - qintptr *result) override; + virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override; virtual void changeEvent(QEvent *event) override; private slots: @@ -1116,8 +1063,7 @@ private slots: void on_OBSBasic_customContextMenuRequested(const QPoint &pos); - void on_scenes_currentItemChanged(QListWidgetItem *current, - QListWidgetItem *prev); + void on_scenes_currentItemChanged(QListWidgetItem *current, QListWidgetItem *prev); void on_scenes_customContextMenuRequested(const QPoint &pos); void GridActionClicked(); void on_actionSceneListMode_triggered(); @@ -1326,8 +1272,7 @@ public: virtual config_t *Config() const override; - virtual int GetProfilePath(char *path, size_t size, - const char *file) const override; + virtual int GetProfilePath(char *path, size_t size, const char *file) const override; static void InitBrowserPanelSafeBlock(); #ifdef YOUTUBE_ENABLED @@ -1336,15 +1281,13 @@ public: YouTubeAppDock *GetYouTubeAppDock(); #endif // MARK: - Generic UI Helper Functions - OBSPromptResult PromptForName(const OBSPromptRequest &request, - const OBSPromptCallback &callback); + OBSPromptResult PromptForName(const OBSPromptRequest &request, const OBSPromptCallback &callback); // MARK: - OBS Profile Management private: OBSProfileCache profiles{}; - void SetupNewProfile(const std::string &profileName, - bool useWizard = false); + void SetupNewProfile(const std::string &profileName, bool useWizard = false); void SetupDuplicateProfile(const std::string &profileName); void SetupRenameProfile(const std::string &profileName); @@ -1358,23 +1301,17 @@ private: void RefreshProfiles(bool refreshCache = false); void ActivateProfile(const OBSProfile &profile, bool reset = false); - std::vector - GetRestartRequirements(const ConfigFile &config) const; + std::vector GetRestartRequirements(const ConfigFile &config) const; void ResetProfileData(); void CheckForSimpleModeX264Fallback(); public: - inline const OBSProfileCache &GetProfileCache() const noexcept - { - return profiles; - }; + inline const OBSProfileCache &GetProfileCache() const noexcept { return profiles; }; const OBSProfile &GetCurrentProfile() const; - std::optional - GetProfileByName(const std::string &profileName) const; - std::optional - GetProfileByDirectoryName(const std::string &directoryName) const; + std::optional GetProfileByName(const std::string &profileName) const; + std::optional GetProfileByDirectoryName(const std::string &directoryName) const; private slots: void on_actionNewProfile_triggered(); @@ -1397,8 +1334,7 @@ private: void SetupDuplicateSceneCollection(const std::string &collectionName); void SetupRenameSceneCollection(const std::string &collectionName); - const OBSSceneCollection & - CreateSceneCollection(const std::string &collectionName); + const OBSSceneCollection &CreateSceneCollection(const std::string &collectionName); void RemoveSceneCollection(OBSSceneCollection collection); bool CreateDuplicateSceneCollection(const QString &name); @@ -1411,25 +1347,18 @@ private: void ActivateSceneCollection(const OBSSceneCollection &collection); public: - inline const OBSSceneCollectionCache & - GetSceneCollectionCache() const noexcept - { - return collections; - }; + inline const OBSSceneCollectionCache &GetSceneCollectionCache() const noexcept { return collections; }; const OBSSceneCollection &GetCurrentSceneCollection() const; - std::optional - GetSceneCollectionByName(const std::string &collectionName) const; - std::optional - GetSceneCollectionByFileName(const std::string &fileName) const; + std::optional GetSceneCollectionByName(const std::string &collectionName) const; + std::optional GetSceneCollectionByFileName(const std::string &fileName) const; private slots: void on_actionNewSceneCollection_triggered(); void on_actionDupSceneCollection_triggered(); void on_actionRenameSceneCollection_triggered(); - void - on_actionRemoveSceneCollection_triggered(bool skipConfirmation = false); + void on_actionRemoveSceneCollection_triggered(bool skipConfirmation = false); void on_actionImportSceneCollection_triggered(); void on_actionExportSceneCollection_triggered(); void on_actionRemigrateSceneCollection_triggered(); @@ -1445,8 +1374,7 @@ class SceneRenameDelegate : public QStyledItemDelegate { public: SceneRenameDelegate(QObject *parent); - virtual void setEditorData(QWidget *editor, - const QModelIndex &index) const override; + virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override; protected: virtual bool eventFilter(QObject *editor, QEvent *event) override; diff --git a/UI/window-basic-preview.cpp b/UI/window-basic-preview.cpp index 6806150c0..361e318c2 100644 --- a/UI/window-basic-preview.cpp +++ b/UI/window-basic-preview.cpp @@ -18,8 +18,7 @@ /* TODO: make C++ math classes and clean up code here later */ -OBSBasicPreview::OBSBasicPreview(QWidget *parent, Qt::WindowFlags flags) - : OBSQTDisplay(parent, flags) +OBSBasicPreview::OBSBasicPreview(QWidget *parent, Qt::WindowFlags flags) : OBSQTDisplay(parent, flags) { ResetScrollingOffset(); setMouseTracking(true); @@ -42,10 +41,8 @@ OBSBasicPreview::~OBSBasicPreview() void OBSBasicPreview::Init() { OBSBasic *main = OBSBasic::Get(); - connect(main, &OBSBasic::PreviewXScrollBarMoved, this, - &OBSBasicPreview::XScrollBarMoved); - connect(main, &OBSBasic::PreviewYScrollBarMoved, this, - &OBSBasicPreview::YScrollBarMoved); + connect(main, &OBSBasic::PreviewXScrollBarMoved, this, &OBSBasicPreview::XScrollBarMoved); + connect(main, &OBSBasic::PreviewYScrollBarMoved, this, &OBSBasicPreview::YScrollBarMoved); } vec2 OBSBasicPreview::GetMouseEventPos(QMouseEvent *event) @@ -86,11 +83,7 @@ struct SceneFindData { SceneFindData &operator=(const SceneFindData &) = delete; SceneFindData &operator=(SceneFindData &&) = delete; - inline SceneFindData(const vec2 &pos_, bool selectBelow_) - : pos(pos_), - selectBelow(selectBelow_) - { - } + inline SceneFindData(const vec2 &pos_, bool selectBelow_) : pos(pos_), selectBelow(selectBelow_) {} }; struct SceneFindBoxData { @@ -103,11 +96,7 @@ struct SceneFindBoxData { SceneFindBoxData &operator=(const SceneFindData &) = delete; SceneFindBoxData &operator=(SceneFindData &&) = delete; - inline SceneFindBoxData(const vec2 &startPos_, const vec2 &pos_) - : startPos(startPos_), - pos(pos_) - { - } + inline SceneFindBoxData(const vec2 &startPos_, const vec2 &pos_) : startPos(startPos_), pos(pos_) {} }; static bool SceneItemHasVideo(obs_sceneitem_t *item) @@ -123,8 +112,7 @@ static bool CloseFloat(float a, float b, float epsilon = 0.01) return abs(a - b) <= epsilon; } -static bool FindItemAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool FindItemAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { SceneFindData *data = reinterpret_cast(param); matrix4 transform; @@ -146,9 +134,8 @@ static bool FindItemAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, vec3_transform(&transformedPos, &pos3, &invTransform); vec3_transform(&pos3_, &transformedPos, &transform); - if (CloseFloat(pos3.x, pos3_.x) && CloseFloat(pos3.y, pos3_.y) && - transformedPos.x >= 0.0f && transformedPos.x <= 1.0f && - transformedPos.y >= 0.0f && transformedPos.y <= 1.0f) { + if (CloseFloat(pos3.x, pos3_.x) && CloseFloat(pos3.y, pos3_.y) && transformedPos.x >= 0.0f && + transformedPos.x <= 1.0f && transformedPos.y >= 0.0f && transformedPos.y <= 1.0f) { if (data->selectBelow && obs_sceneitem_selected(item)) { if (data->item) return false; @@ -192,20 +179,15 @@ vec3 OBSBasicPreview::GetSnapOffset(const vec3 &tl, const vec3 &br) vec3_zero(&clampOffset); - const bool snap = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "SnappingEnabled"); + const bool snap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled"); if (snap == false) return clampOffset; - const bool screenSnap = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "ScreenSnapping"); - const bool centerSnap = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "CenterSnapping"); + const bool screenSnap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ScreenSnapping"); + const bool centerSnap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "CenterSnapping"); - const float clampDist = config_get_double(App()->GetUserConfig(), - "BasicWindow", - "SnapDistance") / - main->previewScale; + const float clampDist = + config_get_double(App()->GetUserConfig(), "BasicWindow", "SnapDistance") / main->previewScale; const float centerX = br.x - (br.x - tl.x) / 2.0f; const float centerY = br.y - (br.y - tl.y) / 2.0f; @@ -213,8 +195,7 @@ vec3 OBSBasicPreview::GetSnapOffset(const vec3 &tl, const vec3 &br) if (screenSnap && fabsf(tl.x) < clampDist) clampOffset.x = -tl.x; // Right screen edge. - if (screenSnap && fabsf(clampOffset.x) < EPSILON && - fabsf(screenSize.x - br.x) < clampDist) + if (screenSnap && fabsf(clampOffset.x) < EPSILON && fabsf(screenSize.x - br.x) < clampDist) clampOffset.x = screenSize.x - br.x; // Horizontal center. if (centerSnap && fabsf(screenSize.x - (br.x - tl.x)) > clampDist && @@ -225,8 +206,7 @@ vec3 OBSBasicPreview::GetSnapOffset(const vec3 &tl, const vec3 &br) if (screenSnap && fabsf(tl.y) < clampDist) clampOffset.y = -tl.y; // Bottom screen edge. - if (screenSnap && fabsf(clampOffset.y) < EPSILON && - fabsf(screenSize.y - br.y) < clampDist) + if (screenSnap && fabsf(clampOffset.y) < EPSILON && fabsf(screenSize.y - br.y) < clampDist) clampOffset.y = screenSize.y - br.y; // Vertical center. if (centerSnap && fabsf(screenSize.y - (br.y - tl.y)) > clampDist && @@ -249,8 +229,7 @@ OBSSceneItem OBSBasicPreview::GetItemAtPos(const vec2 &pos, bool selectBelow) return data.item; } -static bool CheckItemSelected(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool CheckItemSelected(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { SceneFindData *data = reinterpret_cast(param); matrix4 transform; @@ -275,16 +254,15 @@ static bool CheckItemSelected(obs_scene_t * /* scene */, obs_sceneitem_t *item, if (data->group) { matrix4 parent_transform; - obs_sceneitem_get_draw_transform(data->group, - &parent_transform); + obs_sceneitem_get_draw_transform(data->group, &parent_transform); matrix4_mul(&transform, &transform, &parent_transform); } matrix4_inv(&transform, &transform); vec3_transform(&transformedPos, &pos3, &transform); - if (transformedPos.x >= 0.0f && transformedPos.x <= 1.0f && - transformedPos.y >= 0.0f && transformedPos.y <= 1.0f) { + if (transformedPos.x >= 0.0f && transformedPos.x <= 1.0f && transformedPos.y >= 0.0f && + transformedPos.y <= 1.0f) { if (obs_sceneitem_selected(item)) { data->item = item; return false; @@ -325,15 +303,12 @@ struct HandleFindData { HandleFindData &operator=(const HandleFindData &) = delete; HandleFindData &operator=(HandleFindData &&) = delete; - inline HandleFindData(const vec2 &pos_, float scale) - : pos(pos_), - radius(HANDLE_SEL_RADIUS / scale) + inline HandleFindData(const vec2 &pos_, float scale) : pos(pos_), radius(HANDLE_SEL_RADIUS / scale) { matrix4_identity(&parent_xform); } - inline HandleFindData(const HandleFindData &hfd, - obs_sceneitem_t *parent) + inline HandleFindData(const HandleFindData &hfd, obs_sceneitem_t *parent) : pos(hfd.pos), radius(hfd.radius), item(hfd.item), @@ -346,8 +321,7 @@ struct HandleFindData { } }; -static bool FindHandleAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool FindHandleAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { HandleFindData &data = *reinterpret_cast(param); @@ -356,8 +330,7 @@ static bool FindHandleAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, HandleFindData newData(data, item); newData.angleOffset = obs_sceneitem_get_rot(item); - obs_sceneitem_group_enum_items(item, FindHandleAtPos, - &newData); + obs_sceneitem_group_enum_items(item, FindHandleAtPos, &newData); data.item = newData.item; data.handle = newData.handle; @@ -404,17 +377,15 @@ static bool FindHandleAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, obs_sceneitem_get_scale(item, &scale); obs_bounds_type boundsType = obs_sceneitem_get_bounds_type(item); vec2 rotHandleOffset; - vec2_set(&rotHandleOffset, 0.0f, - HANDLE_RADIUS * data.radius * 1.5 - data.radius); + vec2_set(&rotHandleOffset, 0.0f, HANDLE_RADIUS * data.radius * 1.5 - data.radius); bool invertx = scale.x < 0.0f && boundsType == OBS_BOUNDS_NONE; - float angle = atan2(invertx ? transform.x.y * -1.0f : transform.x.y, - invertx ? transform.x.x * -1.0f : transform.x.x); + float angle = + atan2(invertx ? transform.x.y * -1.0f : transform.x.y, invertx ? transform.x.x * -1.0f : transform.x.x); RotatePos(&rotHandleOffset, angle); RotatePos(&rotHandleOffset, RAD(data.angleOffset)); bool inverty = scale.y < 0.0f && boundsType == OBS_BOUNDS_NONE; - vec3 handlePos = - GetTransformedPos(0.5f, inverty ? 1.0f : 0.0f, transform); + vec3 handlePos = GetTransformedPos(0.5f, inverty ? 1.0f : 0.0f, transform); vec3_transform(&handlePos, &handlePos, &data.parent_xform); handlePos.x -= rotHandleOffset.x; handlePos.y -= rotHandleOffset.y; @@ -427,18 +398,14 @@ static bool FindHandleAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, data.angle = obs_sceneitem_get_rot(item); data.handle = ItemHandle::Rot; - vec2_set(&data.rotatePoint, - transform.t.x + transform.x.x / 2 + - transform.y.x / 2, - transform.t.y + transform.x.y / 2 + - transform.y.y / 2); + vec2_set(&data.rotatePoint, transform.t.x + transform.x.x / 2 + transform.y.x / 2, + transform.t.y + transform.x.y / 2 + transform.y.y / 2); obs_sceneitem_get_pos(item, &data.offsetPoint); data.offsetPoint.x -= data.rotatePoint.x; data.offsetPoint.y -= data.rotatePoint.y; - RotatePos(&data.offsetPoint, - -RAD(obs_sceneitem_get_rot(item))); + RotatePos(&data.offsetPoint, -RAD(obs_sceneitem_get_rot(item))); } } @@ -459,12 +426,8 @@ static vec2 GetItemSize(obs_sceneitem_t *item) obs_sceneitem_get_scale(item, &scale); obs_sceneitem_get_crop(item, &crop); - size.x = float(obs_source_get_width(source) - crop.left - - crop.right) * - scale.x; - size.y = float(obs_source_get_height(source) - crop.top - - crop.bottom) * - scale.y; + size.x = float(obs_source_get_width(source) - crop.left - crop.right) * scale.x; + size.y = float(obs_source_get_height(source) - crop.top - crop.bottom) * scale.y; } return size; @@ -504,30 +467,23 @@ void OBSBasicPreview::GetStretchHandleData(const vec2 &pos, bool ignoreGroup) /* build the item space conversion matrices */ matrix4_identity(&itemToScreen); - matrix4_rotate_aa4f(&itemToScreen, &itemToScreen, 0.0f, 0.0f, - 1.0f, RAD(itemRot)); - matrix4_translate3f(&itemToScreen, &itemToScreen, itemUL.x, - itemUL.y, 0.0f); + matrix4_rotate_aa4f(&itemToScreen, &itemToScreen, 0.0f, 0.0f, 1.0f, RAD(itemRot)); + matrix4_translate3f(&itemToScreen, &itemToScreen, itemUL.x, itemUL.y, 0.0f); matrix4_identity(&screenToItem); - matrix4_translate3f(&screenToItem, &screenToItem, -itemUL.x, - -itemUL.y, 0.0f); - matrix4_rotate_aa4f(&screenToItem, &screenToItem, 0.0f, 0.0f, - 1.0f, RAD(-itemRot)); + matrix4_translate3f(&screenToItem, &screenToItem, -itemUL.x, -itemUL.y, 0.0f); + matrix4_rotate_aa4f(&screenToItem, &screenToItem, 0.0f, 0.0f, 1.0f, RAD(-itemRot)); obs_sceneitem_get_crop(stretchItem, &startCrop); obs_sceneitem_get_pos(stretchItem, &startItemPos); obs_source_t *source = obs_sceneitem_get_source(stretchItem); - cropSize.x = float(obs_source_get_width(source) - - startCrop.left - startCrop.right); - cropSize.y = float(obs_source_get_height(source) - - startCrop.top - startCrop.bottom); + cropSize.x = float(obs_source_get_width(source) - startCrop.left - startCrop.right); + cropSize.y = float(obs_source_get_height(source) - startCrop.top - startCrop.bottom); stretchGroup = obs_sceneitem_get_group(scene, stretchItem); if (stretchGroup && !ignoreGroup) { - obs_sceneitem_get_draw_transform(stretchGroup, - &invGroupTransform); + obs_sceneitem_get_draw_transform(stretchGroup, &invGroupTransform); matrix4_inv(&invGroupTransform, &invGroupTransform); obs_sceneitem_defer_group_resize_begin(stretchGroup); } else { @@ -590,8 +546,7 @@ void OBSBasicPreview::mousePressEvent(QMouseEvent *event) { QPointF pos = event->position(); - if (scrollMode && IsFixedScaling() && - event->button() == Qt::LeftButton) { + if (scrollMode && IsFixedScaling() && event->button() == Qt::LeftButton) { setCursor(Qt::ClosedHandCursor); scrollingFrom.x = pos.x(); scrollingFrom.y = pos.y(); @@ -619,8 +574,7 @@ void OBSBasicPreview::mousePressEvent(QMouseEvent *event) OBSQTDisplay::mousePressEvent(event); - if (event->button() != Qt::LeftButton && - event->button() != Qt::RightButton) + if (event->button() != Qt::LeftButton && event->button() != Qt::RightButton) return; if (event->button() == Qt::LeftButton) @@ -638,8 +592,7 @@ void OBSBasicPreview::mousePressEvent(QMouseEvent *event) vec2 s; SceneFindBoxData data(s, s); - obs_scene_enum_items(main->GetCurrentScene(), FindSelected, - &data); + obs_scene_enum_items(main->GetCurrentScene(), FindSelected, &data); std::lock_guard lock(selectMutex); selectedItems = data.sceneItems; @@ -656,8 +609,7 @@ void OBSBasicPreview::mousePressEvent(QMouseEvent *event) vec2_zero(&lastMoveOffset); mousePos = startPos; - wrapper = - obs_scene_save_transform_states(main->GetCurrentScene(), true); + wrapper = obs_scene_save_transform_states(main->GetCurrentScene(), true); changed = false; } @@ -703,20 +655,16 @@ void OBSBasicPreview::UpdateCursor(uint32_t &flags) if (octant % 2 == 1) { if (isCorner) { - flags &= (flags % 3 == 0) ? ~ITEM_TOP & ~ITEM_BOTTOM - : ~ITEM_LEFT & ~ITEM_RIGHT; + flags &= (flags % 3 == 0) ? ~ITEM_TOP & ~ITEM_BOTTOM : ~ITEM_LEFT & ~ITEM_RIGHT; } else { - flags = (flags % 4 == 0) - ? flags | flags >> ((flags / 2) - 1) - : flags | ((flags >> 2) | (flags << 2)); + flags = (flags % 4 == 0) ? flags | flags >> ((flags / 2) - 1) + : flags | ((flags >> 2) | (flags << 2)); } } - if ((flags & ITEM_LEFT && flags & ITEM_TOP) || - (flags & ITEM_RIGHT && flags & ITEM_BOTTOM)) + if ((flags & ITEM_LEFT && flags & ITEM_TOP) || (flags & ITEM_RIGHT && flags & ITEM_BOTTOM)) setCursor(Qt::SizeFDiagCursor); - else if ((flags & ITEM_LEFT && flags & ITEM_BOTTOM) || - (flags & ITEM_RIGHT && flags & ITEM_TOP)) + else if ((flags & ITEM_LEFT && flags & ITEM_BOTTOM) || (flags & ITEM_RIGHT && flags & ITEM_TOP)) setCursor(Qt::SizeBDiagCursor); else if (flags & ITEM_LEFT || flags & ITEM_RIGHT) setCursor(Qt::SizeHorCursor); @@ -724,11 +672,9 @@ void OBSBasicPreview::UpdateCursor(uint32_t &flags) setCursor(Qt::SizeVerCursor); } -static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { - obs_sceneitem_t *selectedItem = - reinterpret_cast(param); + obs_sceneitem_t *selectedItem = reinterpret_cast(param); if (obs_sceneitem_is_group(item)) obs_sceneitem_group_enum_items(item, select_one, param); @@ -784,8 +730,7 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) ProcessClick(pos); if (selectionBox) { - Qt::KeyboardModifiers modifiers = - QGuiApplication::keyboardModifiers(); + Qt::KeyboardModifiers modifiers = QGuiApplication::keyboardModifiers(); bool altDown = modifiers & Qt::AltModifier; bool shiftDown = modifiers & Qt::ShiftModifier; @@ -793,15 +738,12 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) std::lock_guard lock(selectMutex); if (altDown || ctrlDown || shiftDown) { - for (size_t i = 0; i < selectedItems.size(); - i++) { - obs_sceneitem_select(selectedItems[i], - true); + for (size_t i = 0; i < selectedItems.size(); i++) { + obs_sceneitem_select(selectedItems[i], true); } } - for (size_t i = 0; i < hoveredPreviewItems.size(); - i++) { + for (size_t i = 0; i < hoveredPreviewItems.size(); i++) { bool select = true; obs_sceneitem_t *item = hoveredPreviewItems[i]; @@ -811,8 +753,7 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) select = !obs_sceneitem_selected(item); } - obs_sceneitem_select(hoveredPreviewItems[i], - select); + obs_sceneitem_select(hoveredPreviewItems[i], select); } } @@ -836,16 +777,12 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) selectedItems.clear(); } OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); - OBSDataAutoRelease rwrapper = - obs_scene_save_transform_states(main->GetCurrentScene(), true); + OBSDataAutoRelease rwrapper = obs_scene_save_transform_states(main->GetCurrentScene(), true); auto undo_redo = [](const std::string &data) { - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(dat, "scene_uuid")); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(source.Get(), true); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid")); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(source.Get(), true); obs_scene_load_transform_states(data.c_str()); }; @@ -855,9 +792,7 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) std::string redo_data(obs_data_get_json(rwrapper)); if (changed && undo_data.compare(redo_data) != 0) main->undo_s.add_action( - QTStr("Undo.Transform") - .arg(obs_source_get_name( - main->GetCurrentSceneSource())), + QTStr("Undo.Transform").arg(obs_source_get_name(main->GetCurrentSceneSource())), undo_redo, undo_redo, undo_data, redo_data); } @@ -869,11 +804,9 @@ struct SelectedItemBounds { vec3 tl, br; }; -static bool AddItemBounds(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool AddItemBounds(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { - SelectedItemBounds *data = - reinterpret_cast(param); + SelectedItemBounds *data = reinterpret_cast(param); vec3 t[4]; auto add_bounds = [data, &t]() { @@ -928,8 +861,7 @@ struct OffsetData { vec3 tl, br, offset; }; -static bool GetSourceSnapOffset(obs_scene_t * /* scene */, - obs_sceneitem_t *item, void *param) +static bool GetSourceSnapOffset(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { OffsetData *data = reinterpret_cast(param); @@ -939,10 +871,8 @@ static bool GetSourceSnapOffset(obs_scene_t * /* scene */, matrix4 boxTransform; obs_sceneitem_get_box_transform(item, &boxTransform); - vec3 t[4] = {GetTransformedPos(0.0f, 0.0f, boxTransform), - GetTransformedPos(1.0f, 0.0f, boxTransform), - GetTransformedPos(0.0f, 1.0f, boxTransform), - GetTransformedPos(1.0f, 1.0f, boxTransform)}; + vec3 t[4] = {GetTransformedPos(0.0f, 0.0f, boxTransform), GetTransformedPos(1.0f, 0.0f, boxTransform), + GetTransformedPos(0.0f, 1.0f, boxTransform), GetTransformedPos(1.0f, 1.0f, boxTransform)}; bool first = true; vec3 tl, br; @@ -960,15 +890,12 @@ static bool GetSourceSnapOffset(obs_scene_t * /* scene */, } // Snap to other source edges -#define EDGE_SNAP(l, r, x, y) \ - do { \ - double dist = fabsf(l.x - data->r.x); \ - if (dist < data->clampDist && \ - fabsf(data->offset.x) < EPSILON && data->tl.y < br.y && \ - data->br.y > tl.y && \ - (fabsf(data->offset.x) > dist || \ - data->offset.x < EPSILON)) \ - data->offset.x = l.x - data->r.x; \ +#define EDGE_SNAP(l, r, x, y) \ + do { \ + double dist = fabsf(l.x - data->r.x); \ + if (dist < data->clampDist && fabsf(data->offset.x) < EPSILON && data->tl.y < br.y && \ + data->br.y > tl.y && (fabsf(data->offset.x) > dist || data->offset.x < EPSILON)) \ + data->offset.x = l.x - data->r.x; \ } while (false) EDGE_SNAP(tl, br, x, y); @@ -995,10 +922,8 @@ void OBSBasicPreview::SnapItemMovement(vec2 &offset) vec3 snapOffset = GetSnapOffset(data.tl, data.br); - const bool snap = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "SnappingEnabled"); - const bool sourcesSnap = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SourceSnapping"); + const bool snap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled"); + const bool sourcesSnap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SourceSnapping"); if (snap == false) return; if (sourcesSnap == false) { @@ -1007,10 +932,8 @@ void OBSBasicPreview::SnapItemMovement(vec2 &offset) return; } - const float clampDist = config_get_double(App()->GetUserConfig(), - "BasicWindow", - "SnapDistance") / - main->previewScale; + const float clampDist = + config_get_double(App()->GetUserConfig(), "BasicWindow", "SnapDistance") / main->previewScale; OffsetData offsetData; offsetData.clampDist = clampDist; @@ -1020,8 +943,7 @@ void OBSBasicPreview::SnapItemMovement(vec2 &offset) obs_scene_enum_items(scene, GetSourceSnapOffset, &offsetData); - if (fabsf(offsetData.offset.x) > EPSILON || - fabsf(offsetData.offset.y) > EPSILON) { + if (fabsf(offsetData.offset.x) > EPSILON || fabsf(offsetData.offset.y) > EPSILON) { offset.x += offsetData.offset.x; offset.y += offsetData.offset.y; } else { @@ -1030,8 +952,7 @@ void OBSBasicPreview::SnapItemMovement(vec2 &offset) } } -static bool move_items(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool move_items(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { if (obs_sceneitem_locked(item)) return true; @@ -1079,14 +1000,12 @@ void OBSBasicPreview::MoveItems(const vec2 &pos) obs_scene_enum_items(scene, move_items, &moveOffset); } -static bool CounterClockwise(float x1, float x2, float x3, float y1, float y2, - float y3) +static bool CounterClockwise(float x1, float x2, float x3, float y1, float y2, float y3) { return (y3 - y1) * (x2 - x1) > (y2 - y1) * (x3 - x1); } -static bool IntersectLine(float x1, float x2, float x3, float x4, float y1, - float y2, float y3, float y4) +static bool IntersectLine(float x1, float x2, float x3, float x4, float y1, float y2, float y3, float y4) { bool a = CounterClockwise(x1, x2, x3, y1, y2, y3); bool b = CounterClockwise(x1, x2, x4, y1, y2, y4); @@ -1096,8 +1015,7 @@ static bool IntersectLine(float x1, float x2, float x3, float x4, float y1, return (a != b) && (c != d); } -static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, - float y2) +static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, float y2) { float x3, x4, y3, y4; @@ -1106,19 +1024,15 @@ static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, x4 = x3 + transform.x.x; y4 = y3 + transform.x.y; - if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || - IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) + if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || + IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) return true; x4 = x3 + transform.y.x; y4 = y3 + transform.y.y; - if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || - IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) + if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || + IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) return true; x3 = transform.t.x + transform.x.x; @@ -1126,10 +1040,8 @@ static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, x4 = x3 + transform.y.x; y4 = y3 + transform.y.y; - if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || - IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) + if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || + IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) return true; x3 = transform.t.x + transform.y.x; @@ -1137,18 +1049,15 @@ static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, x4 = x3 + transform.x.x; y4 = y3 + transform.x.y; - if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || - IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || - IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) + if (IntersectLine(x1, x1, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y1, y1, y3, y4) || + IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) return true; return false; } #undef PI -bool OBSBasicPreview::FindSelected(obs_scene_t *, obs_sceneitem_t *item, - void *param) +bool OBSBasicPreview::FindSelected(obs_scene_t *, obs_sceneitem_t *item, void *param) { SceneFindBoxData *data = reinterpret_cast(param); @@ -1158,8 +1067,7 @@ bool OBSBasicPreview::FindSelected(obs_scene_t *, obs_sceneitem_t *item, return true; } -static bool FindItemsInBox(obs_scene_t * /* scene */, obs_sceneitem_t *item, - void *param) +static bool FindItemsInBox(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { SceneFindBoxData *data = reinterpret_cast(param); matrix4 transform; @@ -1192,43 +1100,35 @@ static bool FindItemsInBox(obs_scene_t * /* scene */, obs_sceneitem_t *item, vec3_transform(&transformedPos, &pos3, &invTransform); vec3_transform(&pos3_, &transformedPos, &transform); - if (CloseFloat(pos3.x, pos3_.x) && CloseFloat(pos3.y, pos3_.y) && - transformedPos.x >= 0.0f && transformedPos.x <= 1.0f && - transformedPos.y >= 0.0f && transformedPos.y <= 1.0f) { + if (CloseFloat(pos3.x, pos3_.x) && CloseFloat(pos3.y, pos3_.y) && transformedPos.x >= 0.0f && + transformedPos.x <= 1.0f && transformedPos.y >= 0.0f && transformedPos.y <= 1.0f) { data->sceneItems.push_back(item); return true; } - if (transform.t.x > x1 && transform.t.x < x2 && transform.t.y > y1 && - transform.t.y < y2) { + if (transform.t.x > x1 && transform.t.x < x2 && transform.t.y > y1 && transform.t.y < y2) { data->sceneItems.push_back(item); return true; } - if (transform.t.x + transform.x.x > x1 && - transform.t.x + transform.x.x < x2 && - transform.t.y + transform.x.y > y1 && - transform.t.y + transform.x.y < y2) { + if (transform.t.x + transform.x.x > x1 && transform.t.x + transform.x.x < x2 && + transform.t.y + transform.x.y > y1 && transform.t.y + transform.x.y < y2) { data->sceneItems.push_back(item); return true; } - if (transform.t.x + transform.y.x > x1 && - transform.t.x + transform.y.x < x2 && - transform.t.y + transform.y.y > y1 && - transform.t.y + transform.y.y < y2) { + if (transform.t.x + transform.y.x > x1 && transform.t.x + transform.y.x < x2 && + transform.t.y + transform.y.y > y1 && transform.t.y + transform.y.y < y2) { data->sceneItems.push_back(item); return true; } - if (transform.t.x + transform.x.x + transform.y.x > x1 && - transform.t.x + transform.x.x + transform.y.x < x2 && - transform.t.y + transform.x.y + transform.y.y > y1 && - transform.t.y + transform.x.y + transform.y.y < y2) { + if (transform.t.x + transform.x.x + transform.y.x > x1 && transform.t.x + transform.x.x + transform.y.x < x2 && + transform.t.y + transform.x.y + transform.y.y > y1 && transform.t.y + transform.x.y + transform.y.y < y2) { data->sceneItems.push_back(item); return true; @@ -1293,43 +1193,34 @@ vec3 OBSBasicPreview::CalculateStretchPos(const vec3 &tl, const vec3 &br) return pos; } -void OBSBasicPreview::ClampAspect(vec3 &tl, vec3 &br, vec2 &size, - const vec2 &baseSize) +void OBSBasicPreview::ClampAspect(vec3 &tl, vec3 &br, vec2 &size, const vec2 &baseSize) { float baseAspect = baseSize.x / baseSize.y; float aspect = size.x / size.y; uint32_t stretchFlags = (uint32_t)stretchHandle; - if (stretchHandle == ItemHandle::TopLeft || - stretchHandle == ItemHandle::TopRight || - stretchHandle == ItemHandle::BottomLeft || - stretchHandle == ItemHandle::BottomRight) { + if (stretchHandle == ItemHandle::TopLeft || stretchHandle == ItemHandle::TopRight || + stretchHandle == ItemHandle::BottomLeft || stretchHandle == ItemHandle::BottomRight) { if (aspect < baseAspect) { - if ((size.y >= 0.0f && size.x >= 0.0f) || - (size.y <= 0.0f && size.x <= 0.0f)) + if ((size.y >= 0.0f && size.x >= 0.0f) || (size.y <= 0.0f && size.x <= 0.0f)) size.x = size.y * baseAspect; else size.x = size.y * baseAspect * -1.0f; } else { - if ((size.y >= 0.0f && size.x >= 0.0f) || - (size.y <= 0.0f && size.x <= 0.0f)) + if ((size.y >= 0.0f && size.x >= 0.0f) || (size.y <= 0.0f && size.x <= 0.0f)) size.y = size.x / baseAspect; else size.y = size.x / baseAspect * -1.0f; } - } else if (stretchHandle == ItemHandle::TopCenter || - stretchHandle == ItemHandle::BottomCenter) { - if ((size.y >= 0.0f && size.x >= 0.0f) || - (size.y <= 0.0f && size.x <= 0.0f)) + } else if (stretchHandle == ItemHandle::TopCenter || stretchHandle == ItemHandle::BottomCenter) { + if ((size.y >= 0.0f && size.x >= 0.0f) || (size.y <= 0.0f && size.x <= 0.0f)) size.x = size.y * baseAspect; else size.x = size.y * baseAspect * -1.0f; - } else if (stretchHandle == ItemHandle::CenterLeft || - stretchHandle == ItemHandle::CenterRight) { - if ((size.y >= 0.0f && size.x >= 0.0f) || - (size.y <= 0.0f && size.x <= 0.0f)) + } else if (stretchHandle == ItemHandle::CenterLeft || stretchHandle == ItemHandle::CenterRight) { + if ((size.y >= 0.0f && size.x >= 0.0f) || (size.y <= 0.0f && size.x <= 0.0f)) size.y = size.x / baseAspect; else size.y = size.x / baseAspect * -1.0f; @@ -1412,33 +1303,21 @@ void OBSBasicPreview::CropItem(const vec2 &pos) vec2 scale, rawscale; obs_sceneitem_get_scale(stretchItem, &rawscale); - vec2_set(&scale, - boundsType == OBS_BOUNDS_NONE ? rawscale.x : fabsf(rawscale.x), - boundsType == OBS_BOUNDS_NONE ? rawscale.y - : fabsf(rawscale.y)); + vec2_set(&scale, boundsType == OBS_BOUNDS_NONE ? rawscale.x : fabsf(rawscale.x), + boundsType == OBS_BOUNDS_NONE ? rawscale.y : fabsf(rawscale.y)); vec2 max_tl; vec2 max_br; - vec2_set(&max_tl, float(-crop.left) * scale.x, - float(-crop.top) * scale.y); - vec2_set(&max_br, stretchItemSize.x + crop.right * scale.x, - stretchItemSize.y + crop.bottom * scale.y); + vec2_set(&max_tl, float(-crop.left) * scale.x, float(-crop.top) * scale.y); + vec2_set(&max_br, stretchItemSize.x + crop.right * scale.x, stretchItemSize.y + crop.bottom * scale.y); typedef std::function minmax_func_t; - minmax_func_t min_x = scale.x < 0.0f && boundsType == OBS_BOUNDS_NONE - ? maxfunc - : minfunc; - minmax_func_t min_y = scale.y < 0.0f && boundsType == OBS_BOUNDS_NONE - ? maxfunc - : minfunc; - minmax_func_t max_x = scale.x < 0.0f && boundsType == OBS_BOUNDS_NONE - ? minfunc - : maxfunc; - minmax_func_t max_y = scale.y < 0.0f && boundsType == OBS_BOUNDS_NONE - ? minfunc - : maxfunc; + minmax_func_t min_x = scale.x < 0.0f && boundsType == OBS_BOUNDS_NONE ? maxfunc : minfunc; + minmax_func_t min_y = scale.y < 0.0f && boundsType == OBS_BOUNDS_NONE ? maxfunc : minfunc; + minmax_func_t max_x = scale.x < 0.0f && boundsType == OBS_BOUNDS_NONE ? minfunc : maxfunc; + minmax_func_t max_y = scale.y < 0.0f && boundsType == OBS_BOUNDS_NONE ? minfunc : maxfunc; pos3.x = min_x(pos3.x, max_br.x); pos3.x = max_x(pos3.x, max_tl.x); @@ -1491,14 +1370,12 @@ void OBSBasicPreview::CropItem(const vec2 &pos) if (stretchFlags & ITEM_LEFT) crop.left += int(std::round(tl.x / scale.x)); else if (stretchFlags & ITEM_RIGHT) - crop.right += - int(std::round((stretchItemSize.x - br.x) / scale.x)); + crop.right += int(std::round((stretchItemSize.x - br.x) / scale.x)); if (stretchFlags & ITEM_TOP) crop.top += int(std::round(tl.y / scale.y)); else if (stretchFlags & ITEM_BOTTOM) - crop.bottom += - int(std::round((stretchItemSize.y - br.y) / scale.y)); + crop.bottom += int(std::round((stretchItemSize.y - br.y) / scale.y)); vec3_transform(&newPos, &newPos, &itemToScreen); newPos.x = std::round(newPos.x); @@ -1612,8 +1489,7 @@ void OBSBasicPreview::RotateItem(const vec2 &pos) vec2 pos2; vec2_copy(&pos2, &pos); - float angle = - atan2(pos2.y - rotatePoint.y, pos2.x - rotatePoint.x) + RAD(90); + float angle = atan2(pos2.y - rotatePoint.y, pos2.x - rotatePoint.x) + RAD(90); #define ROT_SNAP(rot, thresh) \ if (abs(angle - RAD(rot)) < RAD(thresh)) { \ @@ -1676,8 +1552,7 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) if (mouseDown) { vec2 pos = GetMouseEventPos(event); - if (!mouseMoved && !mouseOverItems && - stretchHandle == ItemHandle::None) { + if (!mouseMoved && !mouseOverItems && stretchHandle == ItemHandle::None) { ProcessClick(startPos); mouseOverItems = SelectedAtPos(startPos); } @@ -1692,13 +1567,11 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) selectionBox = false; OBSScene scene = main->GetCurrentScene(); - obs_sceneitem_t *group = - obs_sceneitem_get_group(scene, stretchItem); + obs_sceneitem_t *group = obs_sceneitem_get_group(scene, stretchItem); if (group) { vec3 group_pos; vec3_set(&group_pos, pos.x, pos.y, 0.0f); - vec3_transform(&group_pos, &group_pos, - &invGroupTransform); + vec3_transform(&group_pos, &group_pos, &invGroupTransform); pos.x = group_pos.x; pos.y = group_pos.y; } @@ -1735,8 +1608,7 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) if (!mouseMoved && hoveredPreviewItems.size() > 0) { mousePos = pos; - OBSBasic *main = reinterpret_cast( - App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); float scale = main->GetDevicePixelRatio(); float x = qtPos.x() - main->previewX / scale; float y = qtPos.y() - main->previewY / scale; @@ -1759,24 +1631,18 @@ void OBSBasicPreview::leaveEvent(QEvent *) hoveredPreviewItems.clear(); } -static void DrawLine(float x1, float y1, float x2, float y2, float thickness, - vec2 scale) +static void DrawLine(float x1, float y1, float x2, float y2, float thickness, vec2 scale) { float ySide = (y1 == y2) ? (y1 < 0.5f ? 1.0f : -1.0f) : 0.0f; float xSide = (x1 == x2) ? (x1 < 0.5f ? 1.0f : -1.0f) : 0.0f; gs_render_start(true); - gs_vertex2f(x1 - (xSide * (thickness / scale.x) / 2), - y1 + (ySide * (thickness / scale.y) / 2)); - gs_vertex2f(x1 + (xSide * (thickness / scale.x) / 2), - y1 - (ySide * (thickness / scale.y) / 2)); - gs_vertex2f(x2 + (xSide * (thickness / scale.x) / 2), - y2 + (ySide * (thickness / scale.y) / 2)); - gs_vertex2f(x2 - (xSide * (thickness / scale.x) / 2), - y2 - (ySide * (thickness / scale.y) / 2)); - gs_vertex2f(x1 - (xSide * (thickness / scale.x) / 2), - y1 + (ySide * (thickness / scale.y) / 2)); + gs_vertex2f(x1 - (xSide * (thickness / scale.x) / 2), y1 + (ySide * (thickness / scale.y) / 2)); + gs_vertex2f(x1 + (xSide * (thickness / scale.x) / 2), y1 - (ySide * (thickness / scale.y) / 2)); + gs_vertex2f(x2 + (xSide * (thickness / scale.x) / 2), y2 + (ySide * (thickness / scale.y) / 2)); + gs_vertex2f(x2 - (xSide * (thickness / scale.x) / 2), y2 - (ySide * (thickness / scale.y) / 2)); + gs_vertex2f(x1 - (xSide * (thickness / scale.x) / 2), y1 + (ySide * (thickness / scale.y) / 2)); gs_vertbuffer_t *line = gs_render_save(); @@ -1798,17 +1664,14 @@ static void DrawSquareAtPos(float x, float y, float pixelRatio) gs_matrix_identity(); gs_matrix_translate(&pos); - gs_matrix_translate3f(-HANDLE_RADIUS * pixelRatio, - -HANDLE_RADIUS * pixelRatio, 0.0f); - gs_matrix_scale3f(HANDLE_RADIUS * pixelRatio * 2, - HANDLE_RADIUS * pixelRatio * 2, 1.0f); + gs_matrix_translate3f(-HANDLE_RADIUS * pixelRatio, -HANDLE_RADIUS * pixelRatio, 0.0f); + gs_matrix_scale3f(HANDLE_RADIUS * pixelRatio * 2, HANDLE_RADIUS * pixelRatio * 2, 1.0f); gs_draw(GS_TRISTRIP, 0, 0); gs_matrix_pop(); } -static void DrawRotationHandle(gs_vertbuffer_t *circle, float rot, - float pixelRatio, bool invert) +static void DrawRotationHandle(gs_vertbuffer_t *circle, float rot, float pixelRatio, bool invert) { struct vec3 pos; vec3_set(&pos, 0.5f, invert ? 1.0f : 0.0f, 0.0f); @@ -1834,10 +1697,8 @@ static void DrawRotationHandle(gs_vertbuffer_t *circle, float rot, gs_matrix_translate(&pos); gs_matrix_rotaa4f(0.0f, 0.0f, 1.0f, RAD(rot)); - gs_matrix_translate3f(-HANDLE_RADIUS * 1.5 * pixelRatio, - -HANDLE_RADIUS * 1.5 * pixelRatio, 0.0f); - gs_matrix_scale3f(HANDLE_RADIUS * 3 * pixelRatio, - HANDLE_RADIUS * 3 * pixelRatio, 1.0f); + gs_matrix_translate3f(-HANDLE_RADIUS * 1.5 * pixelRatio, -HANDLE_RADIUS * 1.5 * pixelRatio, 0.0f); + gs_matrix_scale3f(HANDLE_RADIUS * 3 * pixelRatio, HANDLE_RADIUS * 3 * pixelRatio, 1.0f); gs_draw(GS_TRISTRIP, 0, 0); @@ -1850,14 +1711,12 @@ static void DrawRotationHandle(gs_vertbuffer_t *circle, float rot, gs_vertexbuffer_destroy(line); } -static void DrawStripedLine(float x1, float y1, float x2, float y2, - float thickness, vec2 scale) +static void DrawStripedLine(float x1, float y1, float x2, float y2, float thickness, vec2 scale) { float ySide = (y1 == y2) ? (y1 < 0.5f ? 1.0f : -1.0f) : 0.0f; float xSide = (x1 == x2) ? (x1 < 0.5f ? 1.0f : -1.0f) : 0.0f; - float dist = - sqrt(pow((x1 - x2) * scale.x, 2) + pow((y1 - y2) * scale.y, 2)); + float dist = sqrt(pow((x1 - x2) * scale.x, 2) + pow((y1 - y2) * scale.y, 2)); float offX = (x2 - x1) / dist; float offY = (y2 - y1) / dist; @@ -1883,11 +1742,9 @@ static void DrawStripedLine(float x1, float y1, float x2, float y2, } gs_vertex2f(xx1, yy1); - gs_vertex2f(xx1 + (xSide * (thickness / scale.x)), - yy1 + (ySide * (thickness / scale.y))); + gs_vertex2f(xx1 + (xSide * (thickness / scale.x)), yy1 + (ySide * (thickness / scale.y))); gs_vertex2f(dx, dy); - gs_vertex2f(dx + (xSide * (thickness / scale.x)), - dy + (ySide * (thickness / scale.y))); + gs_vertex2f(dx + (xSide * (thickness / scale.x)), dy + (ySide * (thickness / scale.y))); gs_vertbuffer_t *line = gs_render_save(); @@ -1924,12 +1781,10 @@ static void DrawRect(float thickness, vec2 scale) static inline bool crop_enabled(const obs_sceneitem_crop *crop) { - return crop->left > 0 || crop->top > 0 || crop->right > 0 || - crop->bottom > 0; + return crop->left > 0 || crop->top > 0 || crop->right > 0 || crop->bottom > 0; } -bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, - void *param) +bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, void *param) { if (obs_sceneitem_locked(item)) return true; @@ -1948,8 +1803,7 @@ bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, gs_matrix_push(); gs_matrix_mul(&mat); - obs_sceneitem_group_enum_items(item, DrawSelectedOverflow, - param); + obs_sceneitem_group_enum_items(item, DrawSelectedOverflow, param); gs_matrix_pop(); } @@ -1968,13 +1822,12 @@ bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, {{{1.f, 1.f, 0.f}}}, }; - bool visible = std::all_of( - std::begin(bounds), std::end(bounds), [&](const vec3 &b) { - vec3 pos; - vec3_transform(&pos, &b, &boxTransform); - vec3_transform(&pos, &pos, &invBoxTransform); - return CloseFloat(pos.x, b.x) && CloseFloat(pos.y, b.y); - }); + bool visible = std::all_of(std::begin(bounds), std::end(bounds), [&](const vec3 &b) { + vec3 pos; + vec3_transform(&pos, &b, &boxTransform); + vec3_transform(&pos, &pos, &invBoxTransform); + return CloseFloat(pos.x, b.x) && CloseFloat(pos.y, b.y); + }); if (!visible) return true; @@ -2011,8 +1864,7 @@ bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, return true; } -bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, - void *param) +bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, void *param) { if (obs_sceneitem_locked(item)) return true; @@ -2080,20 +1932,16 @@ bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, vec4 green; vec4 blue; - vec4_set(&red, selColor.redF(), selColor.greenF(), selColor.blueF(), - 1.0f); - vec4_set(&green, cropColor.redF(), cropColor.greenF(), - cropColor.blueF(), 1.0f); - vec4_set(&blue, hoverColor.redF(), hoverColor.greenF(), - hoverColor.blueF(), 1.0f); + vec4_set(&red, selColor.redF(), selColor.greenF(), selColor.blueF(), 1.0f); + vec4_set(&green, cropColor.redF(), cropColor.greenF(), cropColor.blueF(), 1.0f); + vec4_set(&blue, hoverColor.redF(), hoverColor.greenF(), hoverColor.blueF(), 1.0f); - bool visible = std::all_of( - std::begin(bounds), std::end(bounds), [&](const vec3 &b) { - vec3 pos; - vec3_transform(&pos, &b, &boxTransform); - vec3_transform(&pos, &pos, &invBoxTransform); - return CloseFloat(pos.x, b.x) && CloseFloat(pos.y, b.y); - }); + bool visible = std::all_of(std::begin(bounds), std::end(bounds), [&](const vec3 &b) { + vec3 pos; + vec3_transform(&pos, &b, &boxTransform); + vec3_transform(&pos, &pos, &invBoxTransform); + return CloseFloat(pos.x, b.x) && CloseFloat(pos.y, b.y); + }); if (!visible) return true; @@ -2122,19 +1970,16 @@ bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, gs_effect_set_vec4(colParam, &red); if (info.bounds_type == OBS_BOUNDS_NONE && crop_enabled(&crop)) { -#define DRAW_SIDE(side, x1, y1, x2, y2) \ - if (hovered && !selected) { \ - gs_effect_set_vec4(colParam, &blue); \ - DrawLine(x1, y1, x2, y2, HANDLE_RADIUS *pixelRatio / 2, \ - boxScale); \ - } else if (crop.side > 0) { \ - gs_effect_set_vec4(colParam, &green); \ - DrawStripedLine(x1, y1, x2, y2, HANDLE_RADIUS *pixelRatio / 2, \ - boxScale); \ - } else { \ - DrawLine(x1, y1, x2, y2, HANDLE_RADIUS *pixelRatio / 2, \ - boxScale); \ - } \ +#define DRAW_SIDE(side, x1, y1, x2, y2) \ + if (hovered && !selected) { \ + gs_effect_set_vec4(colParam, &blue); \ + DrawLine(x1, y1, x2, y2, HANDLE_RADIUS *pixelRatio / 2, boxScale); \ + } else if (crop.side > 0) { \ + gs_effect_set_vec4(colParam, &green); \ + DrawStripedLine(x1, y1, x2, y2, HANDLE_RADIUS *pixelRatio / 2, boxScale); \ + } else { \ + DrawLine(x1, y1, x2, y2, HANDLE_RADIUS *pixelRatio / 2, boxScale); \ + } \ gs_effect_set_vec4(colParam, &red); DRAW_SIDE(left, 0.0f, 0.0f, 0.0f, 1.0f); @@ -2169,21 +2014,17 @@ bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, float angle = 180; for (int i = 0, l = 40; i < l; i++) { - gs_vertex2f(sin(RAD(angle)) / 2 + 0.5f, - cos(RAD(angle)) / 2 + 0.5f); + gs_vertex2f(sin(RAD(angle)) / 2 + 0.5f, cos(RAD(angle)) / 2 + 0.5f); angle += 360 / l; - gs_vertex2f(sin(RAD(angle)) / 2 + 0.5f, - cos(RAD(angle)) / 2 + 0.5f); + gs_vertex2f(sin(RAD(angle)) / 2 + 0.5f, cos(RAD(angle)) / 2 + 0.5f); gs_vertex2f(0.5f, 1.0f); } prev->circleFill = gs_render_save(); } - bool invert = info.scale.y < 0.0f && - info.bounds_type == OBS_BOUNDS_NONE; - DrawRotationHandle(prev->circleFill, info.rot + prev->groupRot, - pixelRatio, invert); + bool invert = info.scale.y < 0.0f && info.bounds_type == OBS_BOUNDS_NONE; + DrawRotationHandle(prev->circleFill, info.rot + prev->groupRot, pixelRatio, invert); } gs_matrix_pop(); @@ -2193,8 +2034,7 @@ bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, return true; } -bool OBSBasicPreview::DrawSelectionBox(float x1, float y1, float x2, float y2, - gs_vertbuffer_t *rectFill) +bool OBSBasicPreview::DrawSelectionBox(float x1, float y1, float x2, float y2, gs_vertbuffer_t *rectFill) { OBSBasic *main = OBSBasic::Get(); @@ -2303,10 +2143,8 @@ void OBSBasicPreview::DrawSceneEditing() rectFill = gs_render_save(); } - DrawSelectionBox(startPos.x * main->previewScale, - startPos.y * main->previewScale, - mousePos.x * main->previewScale, - mousePos.y * main->previewScale, rectFill); + DrawSelectionBox(startPos.x * main->previewScale, startPos.y * main->previewScale, + mousePos.x * main->previewScale, mousePos.y * main->previewScale, rectFill); } gs_load_vertexbuffer(nullptr); @@ -2324,10 +2162,8 @@ void OBSBasicPreview::ResetScrollingOffset() void OBSBasicPreview::SetScalingLevel(int32_t newScalingLevelVal) { - newScalingLevelVal = std::clamp(newScalingLevelVal, -MAX_SCALING_LEVEL, - MAX_SCALING_LEVEL); - float newScalingAmountVal = - pow(ZOOM_SENSITIVITY, float(newScalingLevelVal)); + newScalingLevelVal = std::clamp(newScalingLevelVal, -MAX_SCALING_LEVEL, MAX_SCALING_LEVEL); + float newScalingAmountVal = pow(ZOOM_SENSITIVITY, float(newScalingLevelVal)); scalingLevel = newScalingLevelVal; SetScalingAmount(newScalingAmountVal); } @@ -2344,11 +2180,9 @@ void OBSBasicPreview::SetScalingAmount(float newScalingAmountVal) emit scalingChanged(scalingAmount); } -void OBSBasicPreview::SetScalingLevelAndAmount(int32_t newScalingLevelVal, - float newScalingAmountVal) +void OBSBasicPreview::SetScalingLevelAndAmount(int32_t newScalingLevelVal, float newScalingAmountVal) { - newScalingLevelVal = std::clamp(newScalingLevelVal, -MAX_SCALING_LEVEL, - MAX_SCALING_LEVEL); + newScalingLevelVal = std::clamp(newScalingLevelVal, -MAX_SCALING_LEVEL, MAX_SCALING_LEVEL); scalingLevel = newScalingLevelVal; SetScalingAmount(newScalingAmountVal); } @@ -2421,8 +2255,7 @@ static void DrawLabel(OBSSource source, vec3 &pos, vec3 &viewport) gs_matrix_pop(); } -static void DrawSpacingLine(vec3 &start, vec3 &end, vec3 &viewport, - float pixelRatio) +static void DrawSpacingLine(vec3 &start, vec3 &end, vec3 &viewport, float pixelRatio) { OBSBasic *main = OBSBasic::Get(); @@ -2436,8 +2269,7 @@ static void DrawSpacingLine(vec3 &start, vec3 &end, vec3 &viewport, QColor selColor = main->GetSelectionColor(); vec4 color; - vec4_set(&color, selColor.redF(), selColor.greenF(), selColor.blueF(), - 1.0f); + vec4_set(&color, selColor.redF(), selColor.greenF(), selColor.blueF(), 1.0f); gs_effect_set_vec4(gs_effect_get_param_by_name(solid, "color"), &color); @@ -2450,8 +2282,7 @@ static void DrawSpacingLine(vec3 &start, vec3 &end, vec3 &viewport, vec2 scale; vec2_set(&scale, viewport.x, viewport.y); - DrawLine(start.x, start.y, end.x, end.y, - pixelRatio * (HANDLE_RADIUS / 2), scale); + DrawLine(start.x, start.y, end.x, end.y, pixelRatio * (HANDLE_RADIUS / 2), scale); gs_matrix_pop(); @@ -2461,14 +2292,12 @@ static void DrawSpacingLine(vec3 &start, vec3 &end, vec3 &viewport, gs_technique_end(tech); } -static void RenderSpacingHelper(int sourceIndex, vec3 &start, vec3 &end, - vec3 &viewport, float pixelRatio) +static void RenderSpacingHelper(int sourceIndex, vec3 &start, vec3 &end, vec3 &viewport, float pixelRatio) { bool horizontal = (sourceIndex == 2 || sourceIndex == 3); // If outside of preview, don't render - if (!((horizontal && (end.x >= start.x)) || - (!horizontal && (end.y >= start.y)))) + if (!((horizontal && (end.x >= start.x)) || (!horizontal && (end.y >= start.y)))) return; float length = vec3_dist(&start, &end); @@ -2490,22 +2319,19 @@ static void RenderSpacingHelper(int sourceIndex, vec3 &start, vec3 &end, OBSBasicPreview *prev = OBSBasicPreview::Get(); obs_source_t *source = prev->spacerLabel[sourceIndex]; vec3 labelSize, labelPos; - vec3_set(&labelSize, obs_source_get_width(source), - obs_source_get_height(source), 1.0f); + vec3_set(&labelSize, obs_source_get_width(source), obs_source_get_height(source), 1.0f); vec3_div(&labelSize, &labelSize, &viewport); vec3 labelMargin; - vec3_set(&labelMargin, SPACER_LABEL_MARGIN * pixelRatio, - SPACER_LABEL_MARGIN * pixelRatio, 1.0f); + vec3_set(&labelMargin, SPACER_LABEL_MARGIN * pixelRatio, SPACER_LABEL_MARGIN * pixelRatio, 1.0f); vec3_div(&labelMargin, &labelMargin, &viewport); vec3_set(&labelPos, end.x, end.y, end.z); if (horizontal) { labelPos.x -= (end.x - start.x) / 2; labelPos.x -= labelSize.x / 2; - labelPos.y -= labelMargin.y + (labelSize.y / 2) + - (HANDLE_RADIUS / viewport.y); + labelPos.y -= labelMargin.y + (labelSize.y / 2) + (HANDLE_RADIUS / viewport.y); } else { labelPos.y -= (end.y - start.y) / 2; labelPos.y -= labelSize.y / 2; @@ -2581,12 +2407,9 @@ void OBSBasicPreview::DrawSpacingHelpers() // Correct the scene item box transform // Based on scale, rotation angle, position of parent's group - matrix4_scale3f(&boxTransform, &boxTransform, groupOti.scale.x, - groupOti.scale.y, 1.0f); - matrix4_rotate_aa4f(&boxTransform, &boxTransform, 0.0f, 0.0f, - 1.0f, RAD(groupOti.rot)); - matrix4_translate3f(&boxTransform, &boxTransform, - groupOti.pos.x, groupOti.pos.y, 0.0f); + matrix4_scale3f(&boxTransform, &boxTransform, groupOti.scale.x, groupOti.scale.y, 1.0f); + matrix4_rotate_aa4f(&boxTransform, &boxTransform, 0.0f, 0.0f, 1.0f, RAD(groupOti.rot)); + matrix4_translate3f(&boxTransform, &boxTransform, groupOti.pos.x, groupOti.pos.y, 0.0f); } // Switch top/bottom or right/left if scale is negative @@ -2622,8 +2445,7 @@ void OBSBasicPreview::DrawSpacingHelpers() vec3_copy(&left, &b); } } else if (rot <= -HELPER_ROT_BREAKPOINT) { - for (float i = -HELPER_ROT_BREAKPOINT; i >= -360.0f; - i -= 90.0f) { + for (float i = -HELPER_ROT_BREAKPOINT; i >= -360.0f; i -= 90.0f) { if (rot > i) break; @@ -2696,8 +2518,7 @@ void OBSBasicPreview::ClampScrollingOffsets() QSize targetSize = GetPixelSize(this); vec3 target, offset; - vec3_set(&target, (float)targetSize.width(), (float)targetSize.height(), - 1.0f); + vec3_set(&target, (float)targetSize.width(), (float)targetSize.height(), 1.0f); vec3_set(&offset, (float)ovi.base_width, (float)ovi.base_height, 1.0f); vec3_mulf(&offset, &offset, scalingAmount); @@ -2748,8 +2569,7 @@ void OBSBasicPreview::UpdateXScrollBar(float cx) main->ui->previewXScrollBar->setRange(int(-cx), int(cx)); QSize targetSize = GetPixelSize(this); - main->ui->previewXScrollBar->setPageStep(targetSize.width() / - std::min(scalingAmount, 1.0f)); + main->ui->previewXScrollBar->setPageStep(targetSize.width() / std::min(scalingAmount, 1.0f)); QSignalBlocker sig(main->ui->previewXScrollBar); main->ui->previewXScrollBar->setValue(int(-scrollingOffset.x)); @@ -2768,8 +2588,7 @@ void OBSBasicPreview::UpdateYScrollBar(float cy) main->ui->previewYScrollBar->setRange(int(-cy), int(cy)); QSize targetSize = GetPixelSize(this); - main->ui->previewYScrollBar->setPageStep(targetSize.height() / - std::min(scalingAmount, 1.0f)); + main->ui->previewYScrollBar->setPageStep(targetSize.height() / std::min(scalingAmount, 1.0f)); QSignalBlocker sig(main->ui->previewYScrollBar); main->ui->previewYScrollBar->setValue(int(-scrollingOffset.y)); diff --git a/UI/window-basic-preview.hpp b/UI/window-basic-preview.hpp index 719da894e..e880a8dac 100644 --- a/UI/window-basic-preview.hpp +++ b/UI/window-basic-preview.hpp @@ -90,14 +90,10 @@ private: std::mutex selectMutex; static vec2 GetMouseEventPos(QMouseEvent *event); - static bool FindSelected(obs_scene_t *scene, obs_sceneitem_t *item, - void *param); - static bool DrawSelectedOverflow(obs_scene_t *scene, - obs_sceneitem_t *item, void *param); - static bool DrawSelectedItem(obs_scene_t *scene, obs_sceneitem_t *item, - void *param); - static bool DrawSelectionBox(float x1, float y1, float x2, float y2, - gs_vertbuffer_t *box); + static bool FindSelected(obs_scene_t *scene, obs_sceneitem_t *item, void *param); + static bool DrawSelectedOverflow(obs_scene_t *scene, obs_sceneitem_t *item, void *param); + static bool DrawSelectedItem(obs_scene_t *scene, obs_sceneitem_t *item, void *param); + static bool DrawSelectionBox(float x1, float y1, float x2, float y2, gs_vertbuffer_t *box); static OBSSceneItem GetItemAtPos(const vec2 &pos, bool selectBelow); static bool SelectedAtPos(const vec2 &pos); @@ -132,8 +128,7 @@ private slots: void YScrollBarMoved(int value); public: - OBSBasicPreview(QWidget *parent, - Qt::WindowFlags flags = Qt::WindowFlags()); + OBSBasicPreview(QWidget *parent, Qt::WindowFlags flags = Qt::WindowFlags()); ~OBSBasicPreview(); void Init(); @@ -169,37 +164,21 @@ public: void SetScalingLevel(int32_t newScalingLevelVal); void SetScalingAmount(float newScalingAmountVal); - void SetScalingLevelAndAmount(int32_t newScalingLevelVal, - float newScalingAmountVal); + void SetScalingLevelAndAmount(int32_t newScalingLevelVal, float newScalingAmountVal); inline int32_t GetScalingLevel() const { return scalingLevel; } inline float GetScalingAmount() const { return scalingAmount; } void ResetScrollingOffset(); - inline void SetScrollingOffset(float x, float y) - { - vec2_set(&scrollingOffset, x, y); - } + inline void SetScrollingOffset(float x, float y) { vec2_set(&scrollingOffset, x, y); } inline float GetScrollX() const { return scrollingOffset.x; } inline float GetScrollY() const { return scrollingOffset.y; } inline void SetOverflowHidden(bool hidden) { overflowHidden = hidden; } - inline void SetOverflowSelectionHidden(bool hidden) - { - overflowSelectionHidden = hidden; - } - inline void SetOverflowAlwaysVisible(bool visible) - { - overflowAlwaysVisible = visible; - } + inline void SetOverflowSelectionHidden(bool hidden) { overflowSelectionHidden = hidden; } + inline void SetOverflowAlwaysVisible(bool visible) { overflowAlwaysVisible = visible; } - inline bool GetOverflowSelectionHidden() const - { - return overflowSelectionHidden; - } - inline bool GetOverflowAlwaysVisible() const - { - return overflowAlwaysVisible; - } + inline bool GetOverflowSelectionHidden() const { return overflowSelectionHidden; } + inline bool GetOverflowAlwaysVisible() const { return overflowAlwaysVisible; } /* use libobs allocator for alignment because the matrices itemToScreen * and screenToItem may contain SSE data, which will cause SSE diff --git a/UI/window-basic-properties.cpp b/UI/window-basic-properties.cpp index e9decdc85..342b02dd4 100644 --- a/UI/window-basic-properties.cpp +++ b/UI/window-basic-properties.cpp @@ -38,8 +38,7 @@ using namespace std; -static void CreateTransitionScene(OBSSource scene, const char *text, - uint32_t color); +static void CreateTransitionScene(OBSSource scene, const char *text, uint32_t color); OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) : QDialog(parent), @@ -47,16 +46,12 @@ OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) main(qobject_cast(parent)), acceptClicked(false), source(source_), - removedSignal(obs_source_get_signal_handler(source), "remove", - OBSBasicProperties::SourceRemoved, this), - renamedSignal(obs_source_get_signal_handler(source), "rename", - OBSBasicProperties::SourceRenamed, this), + removedSignal(obs_source_get_signal_handler(source), "remove", OBSBasicProperties::SourceRemoved, this), + renamedSignal(obs_source_get_signal_handler(source), "rename", OBSBasicProperties::SourceRenamed, this), oldSettings(obs_data_create()) { - int cx = (int)config_get_int(App()->GetAppConfig(), "PropertiesWindow", - "cx"); - int cy = (int)config_get_int(App()->GetAppConfig(), "PropertiesWindow", - "cy"); + int cx = (int)config_get_int(App()->GetAppConfig(), "PropertiesWindow", "cx"); + int cy = (int)config_get_int(App()->GetAppConfig(), "PropertiesWindow", "cy"); enum obs_source_type type = obs_source_get_type(source); @@ -74,18 +69,15 @@ OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) OBSDataAutoRelease nd_settings = obs_source_get_settings(source); obs_data_apply(oldSettings, nd_settings); - view = new OBSPropertiesView( - nd_settings.Get(), source, - (PropertiesReloadCallback)obs_source_properties, - (PropertiesUpdateCallback) nullptr, // No special handling required for undo/redo - (PropertiesVisualUpdateCb)obs_source_update); + view = new OBSPropertiesView(nd_settings.Get(), source, (PropertiesReloadCallback)obs_source_properties, + (PropertiesUpdateCallback) nullptr, // No special handling required for undo/redo + (PropertiesVisualUpdateCb)obs_source_update); view->setMinimumHeight(150); ui->propertiesLayout->addWidget(view); if (type == OBS_SOURCE_TYPE_TRANSITION) { - connect(view, &OBSPropertiesView::PropertiesRefreshed, this, - &OBSBasicProperties::AddPreviewButton); + connect(view, &OBSPropertiesView::PropertiesRefreshed, this, &OBSBasicProperties::AddPreviewButton); } view->show(); @@ -96,36 +88,27 @@ OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) obs_source_inc_showing(source); - updatePropertiesSignal.Connect(obs_source_get_signal_handler(source), - "update_properties", - OBSBasicProperties::UpdateProperties, - this); + updatePropertiesSignal.Connect(obs_source_get_signal_handler(source), "update_properties", + OBSBasicProperties::UpdateProperties, this); auto addDrawCallback = [this]() { - obs_display_add_draw_callback(ui->preview->GetDisplay(), - OBSBasicProperties::DrawPreview, - this); + obs_display_add_draw_callback(ui->preview->GetDisplay(), OBSBasicProperties::DrawPreview, this); }; auto addTransitionDrawCallback = [this]() { - obs_display_add_draw_callback( - ui->preview->GetDisplay(), - OBSBasicProperties::DrawTransitionPreview, this); + obs_display_add_draw_callback(ui->preview->GetDisplay(), OBSBasicProperties::DrawTransitionPreview, + this); }; uint32_t caps = obs_source_get_output_flags(source); - bool drawable_type = type == OBS_SOURCE_TYPE_INPUT || - type == OBS_SOURCE_TYPE_SCENE; + bool drawable_type = type == OBS_SOURCE_TYPE_INPUT || type == OBS_SOURCE_TYPE_SCENE; bool drawable_preview = (caps & OBS_SOURCE_VIDEO) != 0; if (drawable_preview && drawable_type) { ui->preview->show(); - connect(ui->preview, &OBSQTDisplay::DisplayCreated, - addDrawCallback); + connect(ui->preview, &OBSQTDisplay::DisplayCreated, addDrawCallback); } else if (type == OBS_SOURCE_TYPE_TRANSITION) { - sourceA = - obs_source_create_private("scene", "sourceA", nullptr); - sourceB = - obs_source_create_private("scene", "sourceB", nullptr); + sourceA = obs_source_create_private("scene", "sourceA", nullptr); + sourceB = obs_source_create_private("scene", "sourceB", nullptr); uint32_t colorA = 0xFFB26F52; uint32_t colorB = 0xFF6FB252; @@ -141,15 +124,13 @@ OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) OBSDataAutoRelease settings = obs_source_get_settings(source); - sourceClone = obs_source_create_private( - obs_source_get_id(source), "clone", settings); + sourceClone = obs_source_create_private(obs_source_get_id(source), "clone", settings); obs_source_inc_active(sourceClone); obs_transition_set(sourceClone, sourceA); auto updateCallback = [=]() { - OBSDataAutoRelease settings = - obs_source_get_settings(source); + OBSDataAutoRelease settings = obs_source_get_settings(source); obs_source_update(sourceClone, settings); obs_transition_clear(sourceClone); @@ -162,8 +143,7 @@ OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) connect(view, &OBSPropertiesView::Changed, updateCallback); ui->preview->show(); - connect(ui->preview, &OBSQTDisplay::DisplayCreated, - addTransitionDrawCallback); + connect(ui->preview, &OBSQTDisplay::DisplayCreated, addTransitionDrawCallback); } else { ui->preview->hide(); @@ -182,8 +162,7 @@ OBSBasicProperties::~OBSBasicProperties() void OBSBasicProperties::AddPreviewButton() { - QPushButton *playButton = - new QPushButton(QTStr("PreviewTransition"), this); + QPushButton *playButton = new QPushButton(QTStr("PreviewTransition"), this); VScrollArea *area = view; area->widget()->layout()->addWidget(playButton); @@ -202,8 +181,7 @@ void OBSBasicProperties::AddPreviewButton() } obs_transition_set(sourceClone, start); - obs_transition_start(sourceClone, OBS_TRANSITION_MODE_AUTO, - main->GetTransitionDuration(), end); + obs_transition_start(sourceClone, OBS_TRANSITION_MODE_AUTO, main->GetTransitionDuration(), end); direction = !direction; start = nullptr; @@ -243,29 +221,24 @@ static obs_source_t *CreateLabel(const char *name, size_t h) const char *text_source_id = "text_ft2_source"; #endif - obs_source_t *txtSource = - obs_source_create_private(text_source_id, name, settings); + obs_source_t *txtSource = obs_source_create_private(text_source_id, name, settings); return txtSource; } -static void CreateTransitionScene(OBSSource scene, const char *text, - uint32_t color) +static void CreateTransitionScene(OBSSource scene, const char *text, uint32_t color) { OBSDataAutoRelease settings = obs_data_create(); obs_data_set_int(settings, "width", obs_source_get_width(scene)); obs_data_set_int(settings, "height", obs_source_get_height(scene)); obs_data_set_int(settings, "color", color); - OBSSourceAutoRelease colorBG = obs_source_create_private( - "color_source", "background", settings); + OBSSourceAutoRelease colorBG = obs_source_create_private("color_source", "background", settings); obs_scene_add(obs_scene_from_source(scene), colorBG); - OBSSourceAutoRelease label = - CreateLabel(text, obs_source_get_height(scene)); - obs_sceneitem_t *item = - obs_scene_add(obs_scene_from_source(scene), label); + OBSSourceAutoRelease label = CreateLabel(text, obs_source_get_height(scene)); + obs_sceneitem_t *item = obs_scene_add(obs_scene_from_source(scene), label); vec2 size; vec2_set(&size, obs_source_get_width(scene), @@ -281,8 +254,7 @@ static void CreateTransitionScene(OBSSource scene, const char *text, void OBSBasicProperties::SourceRemoved(void *data, calldata_t *) { - QMetaObject::invokeMethod(static_cast(data), - "close"); + QMetaObject::invokeMethod(static_cast(data), "close"); } void OBSBasicProperties::SourceRenamed(void *data, calldata_t *params) @@ -290,22 +262,19 @@ void OBSBasicProperties::SourceRenamed(void *data, calldata_t *params) const char *name = calldata_string(params, "new_name"); QString title = QTStr("Basic.PropertiesWindow").arg(QT_UTF8(name)); - QMetaObject::invokeMethod(static_cast(data), - "setWindowTitle", Q_ARG(QString, title)); + QMetaObject::invokeMethod(static_cast(data), "setWindowTitle", Q_ARG(QString, title)); } void OBSBasicProperties::UpdateProperties(void *data, calldata_t *) { - QMetaObject::invokeMethod(static_cast(data)->view, - "ReloadProperties"); + QMetaObject::invokeMethod(static_cast(data)->view, "ReloadProperties"); } static bool ConfirmReset(QWidget *parent) { QMessageBox::StandardButton button; - button = OBSMessageBox::question(parent, QTStr("ConfirmReset.Title"), - QTStr("ConfirmReset.Text"), + button = OBSMessageBox::question(parent, QTStr("ConfirmReset.Title"), QTStr("ConfirmReset.Text"), QMessageBox::Yes | QMessageBox::No); return button == QMessageBox::Yes; @@ -317,42 +286,33 @@ void OBSBasicProperties::on_buttonBox_clicked(QAbstractButton *button) if (val == QDialogButtonBox::AcceptRole) { - std::string scene_uuid = - obs_source_get_uuid(main->GetCurrentSceneSource()); + std::string scene_uuid = obs_source_get_uuid(main->GetCurrentSceneSource()); auto undo_redo = [scene_uuid](const std::string &data) { - OBSDataAutoRelease settings = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(settings, "undo_uuid")); + OBSDataAutoRelease settings = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = + obs_get_source_by_uuid(obs_data_get_string(settings, "undo_uuid")); obs_source_reset_settings(source, settings); obs_source_update_properties(source); - OBSSourceAutoRelease scene_source = - obs_get_source_by_uuid(scene_uuid.c_str()); + OBSSourceAutoRelease scene_source = obs_get_source_by_uuid(scene_uuid.c_str()); - OBSBasic::Get()->SetCurrentScene(scene_source.Get(), - true); + OBSBasic::Get()->SetCurrentScene(scene_source.Get(), true); }; OBSDataAutoRelease new_settings = obs_data_create(); - OBSDataAutoRelease curr_settings = - obs_source_get_settings(source); + OBSDataAutoRelease curr_settings = obs_source_get_settings(source); obs_data_apply(new_settings, curr_settings); - obs_data_set_string(new_settings, "undo_uuid", - obs_source_get_uuid(source)); - obs_data_set_string(oldSettings, "undo_uuid", - obs_source_get_uuid(source)); + obs_data_set_string(new_settings, "undo_uuid", obs_source_get_uuid(source)); + obs_data_set_string(oldSettings, "undo_uuid", obs_source_get_uuid(source)); std::string undo_data(obs_data_get_json(oldSettings)); std::string redo_data(obs_data_get_json(new_settings)); if (undo_data.compare(redo_data) != 0) - main->undo_s.add_action( - QTStr("Undo.Properties") - .arg(obs_source_get_name(source)), - undo_redo, undo_redo, undo_data, redo_data); + main->undo_s.add_action(QTStr("Undo.Properties").arg(obs_source_get_name(source)), undo_redo, + undo_redo, undo_data, redo_data); acceptClicked = true; close(); @@ -417,8 +377,7 @@ void OBSBasicProperties::DrawPreview(void *data, uint32_t cx, uint32_t cy) gs_viewport_pop(); } -void OBSBasicProperties::DrawTransitionPreview(void *data, uint32_t cx, - uint32_t cy) +void OBSBasicProperties::DrawTransitionPreview(void *data, uint32_t cx, uint32_t cy) { OBSBasicProperties *window = static_cast(data); @@ -450,16 +409,11 @@ void OBSBasicProperties::DrawTransitionPreview(void *data, uint32_t cx, void OBSBasicProperties::Cleanup() { - config_set_int(App()->GetAppConfig(), "PropertiesWindow", "cx", - width()); - config_set_int(App()->GetAppConfig(), "PropertiesWindow", "cy", - height()); + config_set_int(App()->GetAppConfig(), "PropertiesWindow", "cx", width()); + config_set_int(App()->GetAppConfig(), "PropertiesWindow", "cy", height()); - obs_display_remove_draw_callback(ui->preview->GetDisplay(), - OBSBasicProperties::DrawPreview, this); - obs_display_remove_draw_callback( - ui->preview->GetDisplay(), - OBSBasicProperties::DrawTransitionPreview, this); + obs_display_remove_draw_callback(ui->preview->GetDisplay(), OBSBasicProperties::DrawPreview, this); + obs_display_remove_draw_callback(ui->preview->GetDisplay(), OBSBasicProperties::DrawTransitionPreview, this); } void OBSBasicProperties::reject() @@ -481,21 +435,18 @@ void OBSBasicProperties::closeEvent(QCloseEvent *event) Cleanup(); } -bool OBSBasicProperties::nativeEvent(const QByteArray &, void *message, - qintptr *) +bool OBSBasicProperties::nativeEvent(const QByteArray &, void *message, qintptr *) { #ifdef _WIN32 const MSG &msg = *static_cast(message); switch (msg.message) { case WM_MOVE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnMove(); } break; case WM_DISPLAYCHANGE: - for (OBSQTDisplay *const display : - findChildren()) { + for (OBSQTDisplay *const display : findChildren()) { display->OnDisplayChange(); } } @@ -524,10 +475,9 @@ bool OBSBasicProperties::ConfirmQuit() { QMessageBox::StandardButton button; - button = OBSMessageBox::question( - this, QTStr("Basic.PropertiesWindow.ConfirmTitle"), - QTStr("Basic.PropertiesWindow.Confirm"), - QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); + button = OBSMessageBox::question(this, QTStr("Basic.PropertiesWindow.ConfirmTitle"), + QTStr("Basic.PropertiesWindow.Confirm"), + QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel); switch (button) { case QMessageBox::Save: diff --git a/UI/window-basic-properties.hpp b/UI/window-basic-properties.hpp index 887e48e4b..3f9557c2c 100644 --- a/UI/window-basic-properties.hpp +++ b/UI/window-basic-properties.hpp @@ -74,7 +74,6 @@ public: protected: virtual void closeEvent(QCloseEvent *event) override; - virtual bool nativeEvent(const QByteArray &eventType, void *message, - qintptr *result) override; + virtual bool nativeEvent(const QByteArray &eventType, void *message, qintptr *result) override; virtual void reject() override; }; diff --git a/UI/window-basic-settings-a11y.cpp b/UI/window-basic-settings-a11y.cpp index 2cce25ba6..d50cbfded 100644 --- a/UI/window-basic-settings-a11y.cpp +++ b/UI/window-basic-settings-a11y.cpp @@ -13,8 +13,7 @@ enum ColorPreset { static inline QColor color_from_int(long long val) { - return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, - (val >> 24) & 0xff); + return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff); } static inline long long color_to_int(QColor color) @@ -23,8 +22,7 @@ static inline long long color_to_int(QColor color) return ((val & 0xff) << shift); }; - return shift(color.red(), 0) | shift(color.green(), 8) | - shift(color.blue(), 16) | shift(color.alpha(), 24); + return shift(color.red(), 0) | shift(color.green(), 8) | shift(color.blue(), 16) | shift(color.alpha(), 24); } QColor OBSBasicSettings::GetColor(uint32_t colorVal, QString label) @@ -50,12 +48,10 @@ void OBSBasicSettings::LoadA11ySettings(bool presetChange) preset = config_get_int(config, "Accessibility", "ColorPreset"); bool block = ui->colorPreset->blockSignals(true); - ui->colorPreset->setCurrentIndex(std::min( - preset, (uint32_t)ui->colorPreset->count() - 1)); + ui->colorPreset->setCurrentIndex(std::min(preset, (uint32_t)ui->colorPreset->count() - 1)); ui->colorPreset->blockSignals(block); - bool checked = config_get_bool(config, "Accessibility", - "OverrideColors"); + bool checked = config_get_bool(config, "Accessibility", "OverrideColors"); ui->colorsGroupBox->setChecked(checked); } @@ -81,25 +77,17 @@ void OBSBasicSettings::LoadA11ySettings(bool presetChange) } else if (preset == COLOR_PRESET_CUSTOM) { SetDefaultColors(); - selectRed = - config_get_int(config, "Accessibility", "SelectRed"); - selectGreen = - config_get_int(config, "Accessibility", "SelectGreen"); - selectBlue = - config_get_int(config, "Accessibility", "SelectBlue"); + selectRed = config_get_int(config, "Accessibility", "SelectRed"); + selectGreen = config_get_int(config, "Accessibility", "SelectGreen"); + selectBlue = config_get_int(config, "Accessibility", "SelectBlue"); - mixerGreen = - config_get_int(config, "Accessibility", "MixerGreen"); - mixerYellow = - config_get_int(config, "Accessibility", "MixerYellow"); + mixerGreen = config_get_int(config, "Accessibility", "MixerGreen"); + mixerYellow = config_get_int(config, "Accessibility", "MixerYellow"); mixerRed = config_get_int(config, "Accessibility", "MixerRed"); - mixerGreenActive = config_get_int(config, "Accessibility", - "MixerGreenActive"); - mixerYellowActive = config_get_int(config, "Accessibility", - "MixerYellowActive"); - mixerRedActive = config_get_int(config, "Accessibility", - "MixerRedActive"); + mixerGreenActive = config_get_int(config, "Accessibility", "MixerGreenActive"); + mixerYellowActive = config_get_int(config, "Accessibility", "MixerYellowActive"); + mixerRedActive = config_get_int(config, "Accessibility", "MixerRedActive"); } UpdateA11yColors(); @@ -111,8 +99,7 @@ void OBSBasicSettings::SaveA11ySettings() { config_t *config = App()->GetUserConfig(); - config_set_bool(config, "Accessibility", "OverrideColors", - ui->colorsGroupBox->isChecked()); + config_set_bool(config, "Accessibility", "OverrideColors", ui->colorsGroupBox->isChecked()); config_set_int(config, "Accessibility", "ColorPreset", preset); config_set_int(config, "Accessibility", "SelectRed", selectRed); @@ -121,12 +108,9 @@ void OBSBasicSettings::SaveA11ySettings() config_set_int(config, "Accessibility", "MixerGreen", mixerGreen); config_set_int(config, "Accessibility", "MixerYellow", mixerYellow); config_set_int(config, "Accessibility", "MixerRed", mixerRed); - config_set_int(config, "Accessibility", "MixerGreenActive", - mixerGreenActive); - config_set_int(config, "Accessibility", "MixerYellowActive", - mixerYellowActive); - config_set_int(config, "Accessibility", "MixerRedActive", - mixerRedActive); + config_set_int(config, "Accessibility", "MixerGreenActive", mixerGreenActive); + config_set_int(config, "Accessibility", "MixerYellowActive", mixerYellowActive); + config_set_int(config, "Accessibility", "MixerRedActive", mixerRedActive); main->RefreshVolumeColors(); } @@ -140,10 +124,8 @@ static void SetStyle(QLabel *label, uint32_t colorVal) label->setText(color.name(QColor::HexRgb)); label->setPalette(palette); label->setStyleSheet(QString("background-color: %1; color: %2;") - .arg(palette.color(QPalette::Window) - .name(QColor::HexRgb)) - .arg(palette.color(QPalette::WindowText) - .name(QColor::HexRgb))); + .arg(palette.color(QPalette::Window).name(QColor::HexRgb)) + .arg(palette.color(QPalette::WindowText).name(QColor::HexRgb))); label->setAutoFillBackground(true); label->setAlignment(Qt::AlignCenter); } @@ -165,23 +147,16 @@ void OBSBasicSettings::SetDefaultColors() { config_t *config = App()->GetUserConfig(); config_set_default_int(config, "Accessibility", "SelectRed", selectRed); - config_set_default_int(config, "Accessibility", "SelectGreen", - selectGreen); - config_set_default_int(config, "Accessibility", "SelectBlue", - selectBlue); + config_set_default_int(config, "Accessibility", "SelectGreen", selectGreen); + config_set_default_int(config, "Accessibility", "SelectBlue", selectBlue); - config_set_default_int(config, "Accessibility", "MixerGreen", - mixerGreen); - config_set_default_int(config, "Accessibility", "MixerYellow", - mixerYellow); + config_set_default_int(config, "Accessibility", "MixerGreen", mixerGreen); + config_set_default_int(config, "Accessibility", "MixerYellow", mixerYellow); config_set_default_int(config, "Accessibility", "MixerRed", mixerRed); - config_set_default_int(config, "Accessibility", "MixerGreenActive", - mixerGreenActive); - config_set_default_int(config, "Accessibility", "MixerYellowActive", - mixerYellowActive); - config_set_default_int(config, "Accessibility", "MixerRedActive", - mixerRedActive); + config_set_default_int(config, "Accessibility", "MixerGreenActive", mixerGreenActive); + config_set_default_int(config, "Accessibility", "MixerYellowActive", mixerYellowActive); + config_set_default_int(config, "Accessibility", "MixerRedActive", mixerRedActive); } void OBSBasicSettings::ResetDefaultColors() @@ -199,16 +174,13 @@ void OBSBasicSettings::ResetDefaultColors() void OBSBasicSettings::on_colorPreset_currentIndexChanged(int idx) { - preset = idx == ui->colorPreset->count() - 1 ? COLOR_PRESET_CUSTOM - : idx; + preset = idx == ui->colorPreset->count() - 1 ? COLOR_PRESET_CUSTOM : idx; LoadA11ySettings(true); } void OBSBasicSettings::on_choose1_clicked() { - QColor color = GetColor( - selectRed, - QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectRed")); + QColor color = GetColor(selectRed, QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectRed")); if (!color.isValid()) return; @@ -227,9 +199,7 @@ void OBSBasicSettings::on_choose1_clicked() void OBSBasicSettings::on_choose2_clicked() { - QColor color = GetColor( - selectGreen, - QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectGreen")); + QColor color = GetColor(selectGreen, QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectGreen")); if (!color.isValid()) return; @@ -248,9 +218,7 @@ void OBSBasicSettings::on_choose2_clicked() void OBSBasicSettings::on_choose3_clicked() { - QColor color = GetColor( - selectBlue, - QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectBlue")); + QColor color = GetColor(selectBlue, QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectBlue")); if (!color.isValid()) return; @@ -269,9 +237,7 @@ void OBSBasicSettings::on_choose3_clicked() void OBSBasicSettings::on_choose4_clicked() { - QColor color = GetColor( - mixerGreen, - QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerGreen")); + QColor color = GetColor(mixerGreen, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerGreen")); if (!color.isValid()) return; @@ -290,9 +256,7 @@ void OBSBasicSettings::on_choose4_clicked() void OBSBasicSettings::on_choose5_clicked() { - QColor color = GetColor( - mixerYellow, - QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerYellow")); + QColor color = GetColor(mixerYellow, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerYellow")); if (!color.isValid()) return; @@ -311,9 +275,7 @@ void OBSBasicSettings::on_choose5_clicked() void OBSBasicSettings::on_choose6_clicked() { - QColor color = GetColor( - mixerRed, - QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerRed")); + QColor color = GetColor(mixerRed, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerRed")); if (!color.isValid()) return; @@ -332,9 +294,8 @@ void OBSBasicSettings::on_choose6_clicked() void OBSBasicSettings::on_choose7_clicked() { - QColor color = GetColor( - mixerGreenActive, - QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerGreenActive")); + QColor color = + GetColor(mixerGreenActive, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerGreenActive")); if (!color.isValid()) return; @@ -353,9 +314,8 @@ void OBSBasicSettings::on_choose7_clicked() void OBSBasicSettings::on_choose8_clicked() { - QColor color = GetColor( - mixerYellowActive, - QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerYellowActive")); + QColor color = + GetColor(mixerYellowActive, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerYellowActive")); if (!color.isValid()) return; @@ -374,9 +334,7 @@ void OBSBasicSettings::on_choose8_clicked() void OBSBasicSettings::on_choose9_clicked() { - QColor color = GetColor( - mixerRedActive, - QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerRedActive")); + QColor color = GetColor(mixerRedActive, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerRedActive")); if (!color.isValid()) return; diff --git a/UI/window-basic-settings-appearance.cpp b/UI/window-basic-settings-appearance.cpp index 20614c4b8..cdfbc92f5 100644 --- a/UI/window-basic-settings-appearance.cpp +++ b/UI/window-basic-settings-appearance.cpp @@ -20,13 +20,10 @@ using namespace std; void OBSBasicSettings::InitAppearancePage() { savedTheme = App()->GetTheme(); - const QString currentBaseTheme = - savedTheme->isBaseTheme ? savedTheme->id : savedTheme->parent; + const QString currentBaseTheme = savedTheme->isBaseTheme ? savedTheme->id : savedTheme->parent; for (const OBSTheme &theme : App()->GetThemes()) { - if (theme.isBaseTheme && - (HighContrastEnabled() || theme.isVisible || - theme.id == currentBaseTheme)) { + if (theme.isBaseTheme && (HighContrastEnabled() || theme.isVisible || theme.id == currentBaseTheme)) { ui->theme->addItem(theme.name, theme.id); } } @@ -35,8 +32,7 @@ void OBSBasicSettings::InitAppearancePage() if (idx != -1) ui->theme->setCurrentIndex(idx); - ui->themeVariant->setPlaceholderText( - QTStr("Basic.Settings.Appearance.General.NoVariant")); + ui->themeVariant->setPlaceholderText(QTStr("Basic.Settings.Appearance.General.NoVariant")); } void OBSBasicSettings::LoadThemeList(bool reload) @@ -44,9 +40,7 @@ void OBSBasicSettings::LoadThemeList(bool reload) ProfileScope("OBSBasicSettings::LoadThemeList"); const OBSTheme *currentTheme = App()->GetTheme(); - const QString currentBaseTheme = currentTheme->isBaseTheme - ? currentTheme->id - : currentTheme->parent; + const QString currentBaseTheme = currentTheme->isBaseTheme ? currentTheme->id : currentTheme->parent; /* Nothing to do if current and last base theme were the same */ const QString baseThemeId = ui->theme->currentData().toString(); @@ -57,11 +51,9 @@ void OBSBasicSettings::LoadThemeList(bool reload) ui->themeVariant->clear(); auto themes = App()->GetThemes(); - std::sort(themes.begin(), themes.end(), - [](const OBSTheme &a, const OBSTheme &b) -> bool { - return QString::compare(a.name, b.name, - Qt::CaseInsensitive) < 0; - }); + std::sort(themes.begin(), themes.end(), [](const OBSTheme &a, const OBSTheme &b) -> bool { + return QString::compare(a.name, b.name, Qt::CaseInsensitive) < 0; + }); QString defaultVariant; const OBSTheme *baseTheme = App()->GetTheme(baseThemeId); @@ -111,8 +103,7 @@ void OBSBasicSettings::SaveAppearanceSettings() OBSTheme *currentTheme = App()->GetTheme(); if (savedTheme != currentTheme) { - config_set_string(config, "Appearance", "Theme", - QT_TO_UTF8(currentTheme->id)); + config_set_string(config, "Appearance", "Theme", QT_TO_UTF8(currentTheme->id)); } } diff --git a/UI/window-basic-settings-stream.cpp b/UI/window-basic-settings-stream.cpp index d0741a0a7..885c49f8a 100644 --- a/UI/window-basic-settings-stream.cpp +++ b/UI/window-basic-settings-stream.cpp @@ -23,8 +23,7 @@ static const QUuid &CustomServerUUID() { - static const QUuid uuid = QUuid::fromString( - QT_UTF8("{241da255-70f2-4bbb-bef7-509695bf8e65}")); + static const QUuid uuid = QUuid::fromString(QT_UTF8("{241da255-70f2-4bbb-bef7-509695bf8e65}")); return uuid; } @@ -83,35 +82,26 @@ void OBSBasicSettings::InitStreamPage() LoadServices(false); - ui->twitchAddonDropdown->addItem( - QTStr("Basic.Settings.Stream.TTVAddon.None")); - ui->twitchAddonDropdown->addItem( - QTStr("Basic.Settings.Stream.TTVAddon.BTTV")); - ui->twitchAddonDropdown->addItem( - QTStr("Basic.Settings.Stream.TTVAddon.FFZ")); - ui->twitchAddonDropdown->addItem( - QTStr("Basic.Settings.Stream.TTVAddon.Both")); + ui->twitchAddonDropdown->addItem(QTStr("Basic.Settings.Stream.TTVAddon.None")); + ui->twitchAddonDropdown->addItem(QTStr("Basic.Settings.Stream.TTVAddon.BTTV")); + ui->twitchAddonDropdown->addItem(QTStr("Basic.Settings.Stream.TTVAddon.FFZ")); + ui->twitchAddonDropdown->addItem(QTStr("Basic.Settings.Stream.TTVAddon.Both")); - connect(ui->ignoreRecommended, &QCheckBox::clicked, this, - &OBSBasicSettings::DisplayEnforceWarning); - connect(ui->ignoreRecommended, &QCheckBox::toggled, this, - &OBSBasicSettings::UpdateResFPSLimits); + connect(ui->ignoreRecommended, &QCheckBox::clicked, this, &OBSBasicSettings::DisplayEnforceWarning); + connect(ui->ignoreRecommended, &QCheckBox::toggled, this, &OBSBasicSettings::UpdateResFPSLimits); - connect(ui->enableMultitrackVideo, &QCheckBox::toggled, this, + connect(ui->enableMultitrackVideo, &QCheckBox::toggled, this, &OBSBasicSettings::UpdateMultitrackVideo); + connect(ui->multitrackVideoMaximumAggregateBitrateAuto, &QCheckBox::toggled, this, &OBSBasicSettings::UpdateMultitrackVideo); - connect(ui->multitrackVideoMaximumAggregateBitrateAuto, - &QCheckBox::toggled, this, + connect(ui->multitrackVideoMaximumVideoTracksAuto, &QCheckBox::toggled, this, + &OBSBasicSettings::UpdateMultitrackVideo); + connect(ui->multitrackVideoConfigOverrideEnable, &QCheckBox::toggled, this, &OBSBasicSettings::UpdateMultitrackVideo); - connect(ui->multitrackVideoMaximumVideoTracksAuto, &QCheckBox::toggled, - this, &OBSBasicSettings::UpdateMultitrackVideo); - connect(ui->multitrackVideoConfigOverrideEnable, &QCheckBox::toggled, - this, &OBSBasicSettings::UpdateMultitrackVideo); } void OBSBasicSettings::LoadStream1Settings() { - bool ignoreRecommended = - config_get_bool(main->Config(), "Stream1", "IgnoreRecommended"); + bool ignoreRecommended = config_get_bool(main->Config(), "Stream1", "IgnoreRecommended"); obs_service_t *service_obj = main->GetService(); const char *type = obs_service_get_type(service_obj); @@ -126,11 +116,9 @@ void OBSBasicSettings::LoadStream1Settings() const char *service = obs_data_get_string(settings, "service"); const char *server = obs_data_get_string(settings, "server"); const char *key = obs_data_get_string(settings, "key"); - bool use_custom_server = - obs_data_get_bool(settings, "using_custom_server"); + bool use_custom_server = obs_data_get_bool(settings, "using_custom_server"); protocol = QT_UTF8(obs_service_get_protocol(service_obj)); - const char *bearer_token = - obs_data_get_string(settings, "bearer_token"); + const char *bearer_token = obs_data_get_string(settings, "bearer_token"); if (is_rtmp_custom || is_whip) ui->customServer->setText(server); @@ -141,10 +129,8 @@ void OBSBasicSettings::LoadStream1Settings() lastCustomServer = ui->customServer->text(); bool use_auth = obs_data_get_bool(settings, "use_auth"); - const char *username = - obs_data_get_string(settings, "username"); - const char *password = - obs_data_get_string(settings, "password"); + const char *username = obs_data_get_string(settings, "username"); + const char *password = obs_data_get_string(settings, "password"); ui->authUsername->setText(QT_UTF8(username)); ui->authPw->setText(QT_UTF8(password)); ui->useAuth->setChecked(use_auth); @@ -165,42 +151,30 @@ void OBSBasicSettings::LoadStream1Settings() ui->twitchAddonDropdown->setCurrentIndex(idx); } - ui->enableMultitrackVideo->setChecked(config_get_bool( - main->Config(), "Stream1", "EnableMultitrackVideo")); + ui->enableMultitrackVideo->setChecked(config_get_bool(main->Config(), "Stream1", "EnableMultitrackVideo")); ui->multitrackVideoMaximumAggregateBitrateAuto->setChecked( - config_get_bool(main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrateAuto")); - if (config_has_user_value(main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrate")) { + config_get_bool(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrateAuto")); + if (config_has_user_value(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrate")) { ui->multitrackVideoMaximumAggregateBitrate->setValue( - config_get_int( - main->Config(), "Stream1", - "MultitrackVideoMaximumAggregateBitrate")); + config_get_int(main->Config(), "Stream1", "MultitrackVideoMaximumAggregateBitrate")); } ui->multitrackVideoMaximumVideoTracksAuto->setChecked( - config_get_bool(main->Config(), "Stream1", - "MultitrackVideoMaximumVideoTracksAuto")); - if (config_has_user_value(main->Config(), "Stream1", - "MultitrackVideoMaximumVideoTracks")) + config_get_bool(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracksAuto")); + if (config_has_user_value(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracks")) ui->multitrackVideoMaximumVideoTracks->setValue( - config_get_int(main->Config(), "Stream1", - "MultitrackVideoMaximumVideoTracks")); + config_get_int(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracks")); - ui->multitrackVideoStreamDumpEnable->setChecked(config_get_bool( - main->Config(), "Stream1", "MultitrackVideoStreamDumpEnabled")); + ui->multitrackVideoStreamDumpEnable->setChecked( + config_get_bool(main->Config(), "Stream1", "MultitrackVideoStreamDumpEnabled")); ui->multitrackVideoConfigOverrideEnable->setChecked( - config_get_bool(main->Config(), "Stream1", - "MultitrackVideoConfigOverrideEnabled")); - if (config_has_user_value(main->Config(), "Stream1", - "MultitrackVideoConfigOverride")) + config_get_bool(main->Config(), "Stream1", "MultitrackVideoConfigOverrideEnabled")); + if (config_has_user_value(main->Config(), "Stream1", "MultitrackVideoConfigOverride")) ui->multitrackVideoConfigOverride->setPlainText( DeserializeConfigText( - config_get_string( - main->Config(), "Stream1", - "MultitrackVideoConfigOverride")) + config_get_string(main->Config(), "Stream1", "MultitrackVideoConfigOverride")) .c_str()); UpdateServerList(); @@ -244,8 +218,7 @@ void OBSBasicSettings::LoadStream1Settings() loading = false; - QMetaObject::invokeMethod(this, "UpdateResFPSLimits", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "UpdateResFPSLimits", Qt::QueuedConnection); } #define SRT_PROTOCOL "srt" @@ -261,11 +234,9 @@ void OBSBasicSettings::SwapMultiTrack(const char *protocol) { if (protocol) { if (AllowsMultiTrack(protocol)) { - ui->advStreamTrackWidget->setCurrentWidget( - ui->streamMultiTracks); + ui->advStreamTrackWidget->setCurrentWidget(ui->streamMultiTracks); } else { - ui->advStreamTrackWidget->setCurrentWidget( - ui->streamSingleTracks); + ui->advStreamTrackWidget->setCurrentWidget(ui->streamSingleTracks); } } } @@ -288,67 +259,47 @@ void OBSBasicSettings::SaveStream1Settings() OBSDataAutoRelease settings = obs_data_create(); if (!customServer && !whip) { - obs_data_set_string(settings, "service", - QT_TO_UTF8(ui->service->currentText())); + obs_data_set_string(settings, "service", QT_TO_UTF8(ui->service->currentText())); obs_data_set_string(settings, "protocol", QT_TO_UTF8(protocol)); if (ui->server->currentData() == CustomServerUUID()) { - obs_data_set_bool(settings, "using_custom_server", - true); + obs_data_set_bool(settings, "using_custom_server", true); - obs_data_set_string( - settings, "server", - QT_TO_UTF8(ui->serviceCustomServer->text())); + obs_data_set_string(settings, "server", QT_TO_UTF8(ui->serviceCustomServer->text())); } else { - obs_data_set_string( - settings, "server", - QT_TO_UTF8( - ui->server->currentData().toString())); + obs_data_set_string(settings, "server", QT_TO_UTF8(ui->server->currentData().toString())); } } else { - obs_data_set_string( - settings, "server", - QT_TO_UTF8(ui->customServer->text().trimmed())); - obs_data_set_bool(settings, "use_auth", - ui->useAuth->isChecked()); + obs_data_set_string(settings, "server", QT_TO_UTF8(ui->customServer->text().trimmed())); + obs_data_set_bool(settings, "use_auth", ui->useAuth->isChecked()); if (ui->useAuth->isChecked()) { - obs_data_set_string( - settings, "username", - QT_TO_UTF8(ui->authUsername->text())); - obs_data_set_string(settings, "password", - QT_TO_UTF8(ui->authPw->text())); + obs_data_set_string(settings, "username", QT_TO_UTF8(ui->authUsername->text())); + obs_data_set_string(settings, "password", QT_TO_UTF8(ui->authPw->text())); } } if (!!auth && strcmp(auth->service(), "Twitch") == 0) { - bool choiceExists = config_has_user_value( - main->Config(), "Twitch", "AddonChoice"); - int currentChoice = - config_get_int(main->Config(), "Twitch", "AddonChoice"); + bool choiceExists = config_has_user_value(main->Config(), "Twitch", "AddonChoice"); + int currentChoice = config_get_int(main->Config(), "Twitch", "AddonChoice"); int newChoice = ui->twitchAddonDropdown->currentIndex(); - config_set_int(main->Config(), "Twitch", "AddonChoice", - newChoice); + config_set_int(main->Config(), "Twitch", "AddonChoice", newChoice); if (choiceExists && currentChoice != newChoice) forceAuthReload = true; - obs_data_set_bool(settings, "bwtest", - ui->bandwidthTestEnable->isChecked()); + obs_data_set_bool(settings, "bwtest", ui->bandwidthTestEnable->isChecked()); } else { obs_data_set_bool(settings, "bwtest", false); } if (whip) { obs_data_set_string(settings, "service", "WHIP"); - obs_data_set_string(settings, "bearer_token", - QT_TO_UTF8(ui->key->text())); + obs_data_set_string(settings, "bearer_token", QT_TO_UTF8(ui->key->text())); } else { - obs_data_set_string(settings, "key", - QT_TO_UTF8(ui->key->text())); + obs_data_set_string(settings, "key", QT_TO_UTF8(ui->key->text())); } - OBSServiceAutoRelease newService = obs_service_create( - service_id, "default_service", settings, hotkeyData); + OBSServiceAutoRelease newService = obs_service_create(service_id, "default_service", settings, hotkeyData); if (!newService) return; @@ -365,44 +316,32 @@ void OBSBasicSettings::SaveStream1Settings() SaveCheckBox(ui->ignoreRecommended, "Stream1", "IgnoreRecommended"); - auto oldMultitrackVideoSetting = config_get_bool( - main->Config(), "Stream1", "EnableMultitrackVideo"); + auto oldMultitrackVideoSetting = config_get_bool(main->Config(), "Stream1", "EnableMultitrackVideo"); if (!IsCustomService()) { OBSDataAutoRelease settings = obs_data_create(); - obs_data_set_string(settings, "service", - QT_TO_UTF8(ui->service->currentText())); - OBSServiceAutoRelease temp_service = obs_service_create_private( - "rtmp_common", "auto config query service", settings); + obs_data_set_string(settings, "service", QT_TO_UTF8(ui->service->currentText())); + OBSServiceAutoRelease temp_service = + obs_service_create_private("rtmp_common", "auto config query service", settings); settings = obs_service_get_settings(temp_service); - auto available = obs_data_has_user_value( - settings, "multitrack_video_configuration_url"); + auto available = obs_data_has_user_value(settings, "multitrack_video_configuration_url"); if (available) { - SaveCheckBox(ui->enableMultitrackVideo, "Stream1", - "EnableMultitrackVideo"); + SaveCheckBox(ui->enableMultitrackVideo, "Stream1", "EnableMultitrackVideo"); } else { - config_remove_value(main->Config(), "Stream1", - "EnableMultitrackVideo"); + config_remove_value(main->Config(), "Stream1", "EnableMultitrackVideo"); } } else { - SaveCheckBox(ui->enableMultitrackVideo, "Stream1", - "EnableMultitrackVideo"); + SaveCheckBox(ui->enableMultitrackVideo, "Stream1", "EnableMultitrackVideo"); } SaveCheckBox(ui->multitrackVideoMaximumAggregateBitrateAuto, "Stream1", "MultitrackVideoMaximumAggregateBitrateAuto"); - SaveSpinBox(ui->multitrackVideoMaximumAggregateBitrate, "Stream1", - "MultitrackVideoMaximumAggregateBitrate"); - SaveCheckBox(ui->multitrackVideoMaximumVideoTracksAuto, "Stream1", - "MultitrackVideoMaximumVideoTracksAuto"); - SaveSpinBox(ui->multitrackVideoMaximumVideoTracks, "Stream1", - "MultitrackVideoMaximumVideoTracks"); - SaveCheckBox(ui->multitrackVideoStreamDumpEnable, "Stream1", - "MultitrackVideoStreamDumpEnabled"); - SaveCheckBox(ui->multitrackVideoConfigOverrideEnable, "Stream1", - "MultitrackVideoConfigOverrideEnabled"); - SaveText(ui->multitrackVideoConfigOverride, "Stream1", - "MultitrackVideoConfigOverride"); + SaveSpinBox(ui->multitrackVideoMaximumAggregateBitrate, "Stream1", "MultitrackVideoMaximumAggregateBitrate"); + SaveCheckBox(ui->multitrackVideoMaximumVideoTracksAuto, "Stream1", "MultitrackVideoMaximumVideoTracksAuto"); + SaveSpinBox(ui->multitrackVideoMaximumVideoTracks, "Stream1", "MultitrackVideoMaximumVideoTracks"); + SaveCheckBox(ui->multitrackVideoStreamDumpEnable, "Stream1", "MultitrackVideoStreamDumpEnabled"); + SaveCheckBox(ui->multitrackVideoConfigOverrideEnable, "Stream1", "MultitrackVideoConfigOverrideEnabled"); + SaveText(ui->multitrackVideoConfigOverride, "Stream1", "MultitrackVideoConfigOverride"); if (oldMultitrackVideoSetting != ui->enableMultitrackVideo->isChecked()) main->ResetOutputs(); @@ -426,8 +365,7 @@ void OBSBasicSettings::UpdateMoreInfoLink() obs_data_set_string(settings, "service", QT_TO_UTF8(serviceName)); obs_property_modified(services, settings); - const char *more_info_link = - obs_data_get_string(settings, "more_info_link"); + const char *more_info_link = obs_data_get_string(settings, "more_info_link"); if (!more_info_link || (*more_info_link == '\0')) { ui->moreInfoButton->hide(); @@ -455,49 +393,36 @@ void OBSBasicSettings::UpdateKeyLink() streamKeyLink = obs_data_get_string(settings, "stream_key_link"); if (customServer.contains("fbcdn.net") && IsCustomService()) { - streamKeyLink = - "https://www.facebook.com/live/producer?ref=OBS"; + streamKeyLink = "https://www.facebook.com/live/producer?ref=OBS"; } if (serviceName == "Dacast") { - ui->streamKeyLabel->setText( - QTStr("Basic.AutoConfig.StreamPage.EncoderKey")); + ui->streamKeyLabel->setText(QTStr("Basic.AutoConfig.StreamPage.EncoderKey")); ui->streamKeyLabel->setToolTip(""); } else if (IsWHIP()) { - ui->streamKeyLabel->setText( - QTStr("Basic.AutoConfig.StreamPage.BearerToken")); + ui->streamKeyLabel->setText(QTStr("Basic.AutoConfig.StreamPage.BearerToken")); ui->streamKeyLabel->setToolTip(""); } else if (!IsCustomService()) { - ui->streamKeyLabel->setText( - QTStr("Basic.AutoConfig.StreamPage.StreamKey")); + ui->streamKeyLabel->setText(QTStr("Basic.AutoConfig.StreamPage.StreamKey")); ui->streamKeyLabel->setToolTip(""); } else { /* add tooltips for stream key, user, password fields */ - QString file = !App()->IsThemeDark() - ? ":/res/images/help.svg" - : ":/res/images/help_light.svg"; + QString file = !App()->IsThemeDark() ? ":/res/images/help.svg" : ":/res/images/help_light.svg"; QString lStr = "%1 "; - ui->streamKeyLabel->setText(lStr.arg( - QTStr("Basic.AutoConfig.StreamPage.StreamKey"), file)); - ui->streamKeyLabel->setToolTip( - QTStr("Basic.AutoConfig.StreamPage.StreamKey.ToolTip")); + ui->streamKeyLabel->setText(lStr.arg(QTStr("Basic.AutoConfig.StreamPage.StreamKey"), file)); + ui->streamKeyLabel->setToolTip(QTStr("Basic.AutoConfig.StreamPage.StreamKey.ToolTip")); - ui->authUsernameLabel->setText(lStr.arg( - QTStr("Basic.Settings.Stream.Custom.Username"), file)); - ui->authUsernameLabel->setToolTip( - QTStr("Basic.Settings.Stream.Custom.Username.ToolTip")); + ui->authUsernameLabel->setText(lStr.arg(QTStr("Basic.Settings.Stream.Custom.Username"), file)); + ui->authUsernameLabel->setToolTip(QTStr("Basic.Settings.Stream.Custom.Username.ToolTip")); - ui->authPwLabel->setText(lStr.arg( - QTStr("Basic.Settings.Stream.Custom.Password"), file)); - ui->authPwLabel->setToolTip( - QTStr("Basic.Settings.Stream.Custom.Password.ToolTip")); + ui->authPwLabel->setText(lStr.arg(QTStr("Basic.Settings.Stream.Custom.Password"), file)); + ui->authPwLabel->setToolTip(QTStr("Basic.Settings.Stream.Custom.Password.ToolTip")); } - if (QString(streamKeyLink).isNull() || - QString(streamKeyLink).isEmpty()) { + if (QString(streamKeyLink).isNull() || QString(streamKeyLink).isEmpty()) { ui->getStreamKeyButton->hide(); } else { ui->getStreamKeyButton->setTargetUrl(QUrl(streamKeyLink)); @@ -536,19 +461,15 @@ void OBSBasicSettings::LoadServices(bool showAll) ui->service->addItem(name); if (obs_is_output_protocol_registered("WHIP")) { - ui->service->addItem(QTStr("WHIP"), - QVariant((int)ListOpt::WHIP)); + ui->service->addItem(QTStr("WHIP"), QVariant((int)ListOpt::WHIP)); } if (!showAll) { - ui->service->addItem( - QTStr("Basic.AutoConfig.StreamPage.Service.ShowAll"), - QVariant((int)ListOpt::ShowAll)); + ui->service->addItem(QTStr("Basic.AutoConfig.StreamPage.Service.ShowAll"), + QVariant((int)ListOpt::ShowAll)); } - ui->service->insertItem( - 0, QTStr("Basic.AutoConfig.StreamPage.Service.Custom"), - QVariant((int)ListOpt::Custom)); + ui->service->insertItem(0, QTStr("Basic.AutoConfig.StreamPage.Service.Custom"), QVariant((int)ListOpt::Custom)); if (!lastService.isEmpty()) { int idx = ui->service->findText(lastService); @@ -571,8 +492,7 @@ static inline bool is_external_oauth(const std::string &service) return Auth::External(service); } -static void reset_service_ui_fields(Ui::OBSBasicSettings *ui, - std::string &service, bool loading) +static void reset_service_ui_fields(Ui::OBSBasicSettings *ui, std::string &service, bool loading) { bool external_oauth = is_external_oauth(service); if (external_oauth) { @@ -584,9 +504,7 @@ static void reset_service_ui_fields(Ui::OBSBasicSettings *ui, } else if (cef) { QString key = ui->key->text(); bool can_auth = is_auth_service(service); - int page = can_auth && (!loading || key.isEmpty()) - ? (int)Section::Connect - : (int)Section::StreamKey; + int page = can_auth && (!loading || key.isEmpty()) ? (int)Section::Connect : (int)Section::StreamKey; ui->streamStackWidget->setCurrentIndex(page); ui->streamKeyWidget->setVisible(true); @@ -607,15 +525,13 @@ static void reset_service_ui_fields(Ui::OBSBasicSettings *ui, #ifdef YOUTUBE_ENABLED static void get_yt_ch_title(Ui::OBSBasicSettings *ui) { - const char *name = config_get_string(OBSBasic::Get()->Config(), - "YouTube", "ChannelName"); + const char *name = config_get_string(OBSBasic::Get()->Config(), "YouTube", "ChannelName"); if (name) { ui->connectedAccountText->setText(name); } else { // if we still not changed the service page if (IsYouTubeService(QT_TO_UTF8(ui->service->currentText()))) { - ui->connectedAccountText->setText( - QTStr("Auth.LoadingChannel.Error")); + ui->connectedAccountText->setText(QTStr("Auth.LoadingChannel.Error")); } } } @@ -656,8 +572,7 @@ void OBSBasicSettings::on_service_currentIndexChanged(int idx) } if (!IsCustomService()) { - ui->advStreamTrackWidget->setCurrentWidget( - ui->streamSingleTracks); + ui->advStreamTrackWidget->setCurrentWidget(ui->streamSingleTracks); } else { SwapMultiTrack(QT_TO_UTF8(protocol)); } @@ -691,8 +606,8 @@ void OBSBasicSettings::ServiceChanged(bool resetFields) if (resetFields || lastService != service.c_str()) { reset_service_ui_fields(ui.get(), service, loading); - ui->enableMultitrackVideo->setChecked(config_get_bool( - main->Config(), "Stream1", "EnableMultitrackVideo")); + ui->enableMultitrackVideo->setChecked( + config_get_bool(main->Config(), "Stream1", "EnableMultitrackVideo")); UpdateMultitrackVideo(); } @@ -703,8 +618,7 @@ void OBSBasicSettings::ServiceChanged(bool resetFields) ui->authPwWidget->setVisible(custom); if (custom || whip) { - ui->destinationLayout->insertRow(1, ui->serverLabel, - ui->serverStackedWidget); + ui->destinationLayout->insertRow(1, ui->serverLabel, ui->serverStackedWidget); ui->serverStackedWidget->setCurrentIndex(1); ui->serverStackedWidget->setVisible(true); @@ -721,12 +635,10 @@ void OBSBasicSettings::ServiceChanged(bool resetFields) } auto system_auth_service = main->auth->service(); - bool service_check = service.find(system_auth_service) != - std::string::npos; + bool service_check = service.find(system_auth_service) != std::string::npos; #ifdef YOUTUBE_ENABLED service_check = service_check ? service_check - : IsYouTubeService(system_auth_service) && - IsYouTubeService(service); + : IsYouTubeService(system_auth_service) && IsYouTubeService(service); #endif if (service_check) { auth = main->auth; @@ -742,8 +654,7 @@ QString OBSBasicSettings::FindProtocol() QString server = ui->customServer->text(); - if (obs_is_output_protocol_registered("RTMPS") && - server.startsWith("rtmps://")) + if (obs_is_output_protocol_registered("RTMPS") && server.startsWith("rtmps://")) return QString("RTMPS"); if (server.startsWith("srt://")) @@ -753,20 +664,17 @@ QString OBSBasicSettings::FindProtocol() return QString("RIST"); } else { - obs_properties_t *props = - obs_get_service_properties("rtmp_common"); + obs_properties_t *props = obs_get_service_properties("rtmp_common"); obs_property_t *services = obs_properties_get(props, "service"); OBSDataAutoRelease settings = obs_data_create(); - obs_data_set_string(settings, "service", - QT_TO_UTF8(ui->service->currentText())); + obs_data_set_string(settings, "service", QT_TO_UTF8(ui->service->currentText())); obs_property_modified(services, settings); obs_properties_destroy(props); - const char *protocol = - obs_data_get_string(settings, "protocol"); + const char *protocol = obs_data_get_string(settings, "protocol"); if (protocol && *protocol) return QT_UTF8(protocol); } @@ -800,9 +708,7 @@ void OBSBasicSettings::UpdateServerList() } if (serviceName == "Twitch" || serviceName == "Amazon IVS") { - ui->server->addItem( - QTStr("Basic.Settings.Stream.SpecifyCustomServer"), - CustomServerUUID()); + ui->server->addItem(QTStr("Basic.Settings.Stream.SpecifyCustomServer"), CustomServerUUID()); } obs_properties_destroy(props); @@ -845,26 +751,18 @@ OBSService OBSBasicSettings::SpawnTempService() OBSDataAutoRelease settings = obs_data_create(); if (!custom && !whip) { - obs_data_set_string(settings, "service", - QT_TO_UTF8(ui->service->currentText())); - obs_data_set_string( - settings, "server", - QT_TO_UTF8(ui->server->currentData().toString())); + obs_data_set_string(settings, "service", QT_TO_UTF8(ui->service->currentText())); + obs_data_set_string(settings, "server", QT_TO_UTF8(ui->server->currentData().toString())); } else { - obs_data_set_string( - settings, "server", - QT_TO_UTF8(ui->customServer->text().trimmed())); + obs_data_set_string(settings, "server", QT_TO_UTF8(ui->customServer->text().trimmed())); } if (whip) - obs_data_set_string(settings, "bearer_token", - QT_TO_UTF8(ui->key->text())); + obs_data_set_string(settings, "bearer_token", QT_TO_UTF8(ui->key->text())); else - obs_data_set_string(settings, "key", - QT_TO_UTF8(ui->key->text())); + obs_data_set_string(settings, "key", QT_TO_UTF8(ui->key->text())); - OBSServiceAutoRelease newService = obs_service_create( - service_id, "temp_service", settings, nullptr); + OBSServiceAutoRelease newService = obs_service_create(service_id, "temp_service", settings, nullptr); return newService.Get(); } @@ -901,8 +799,7 @@ void OBSBasicSettings::OnOAuthStreamKeyConnected() ui->connectedAccountLabel->setVisible(true); ui->connectedAccountText->setVisible(true); - ui->connectedAccountText->setText( - QTStr("Auth.LoadingChannel.Title")); + ui->connectedAccountText->setText(QTStr("Auth.LoadingChannel.Title")); get_yt_ch_title(ui.get()); } @@ -917,8 +814,7 @@ void OBSBasicSettings::OnAuthConnected() std::string service = QT_TO_UTF8(ui->service->currentText()); Auth::Type type = Auth::AuthType(service); - if (type == Auth::Type::OAuth_StreamKey || - type == Auth::Type::OAuth_LinkedAccount) { + if (type == Auth::Type::OAuth_StreamKey || type == Auth::Type::OAuth_LinkedAccount) { OnOAuthStreamKeyConnected(); } @@ -950,17 +846,14 @@ void OBSBasicSettings::on_connectAccount_clicked() } } -#define DISCONNECT_COMFIRM_TITLE \ - "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Title" -#define DISCONNECT_COMFIRM_TEXT \ - "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Text" +#define DISCONNECT_COMFIRM_TITLE "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Title" +#define DISCONNECT_COMFIRM_TEXT "Basic.AutoConfig.StreamPage.DisconnectAccount.Confirm.Text" void OBSBasicSettings::on_disconnectAccount_clicked() { QMessageBox::StandardButton button; - button = OBSMessageBox::question(this, QTStr(DISCONNECT_COMFIRM_TITLE), - QTStr(DISCONNECT_COMFIRM_TEXT)); + button = OBSMessageBox::question(this, QTStr(DISCONNECT_COMFIRM_TITLE), QTStr(DISCONNECT_COMFIRM_TEXT)); if (button == QMessageBox::No) { return; @@ -1032,9 +925,7 @@ void OBSBasicSettings::on_server_currentIndexChanged(int /*index*/) void OBSBasicSettings::UpdateVodTrackSetting() { - bool enableForCustomServer = - config_get_bool(App()->GetUserConfig(), "General", - "EnableCustomServerVodTrack"); + bool enableForCustomServer = config_get_bool(App()->GetUserConfig(), "General", "EnableCustomServerVodTrack"); bool enableVodTrack = ui->service->currentText() == "Twitch"; bool wasEnabled = !!vodTrackCheckbox; @@ -1055,31 +946,25 @@ void OBSBasicSettings::UpdateVodTrackSetting() /* simple output mode vod track widgets */ bool simpleAdv = ui->simpleOutAdvanced->isChecked(); - bool vodTrackEnabled = config_get_bool(main->Config(), "SimpleOutput", - "VodTrackEnabled"); + bool vodTrackEnabled = config_get_bool(main->Config(), "SimpleOutput", "VodTrackEnabled"); simpleVodTrack = new QCheckBox(this); - simpleVodTrack->setText( - QTStr("Basic.Settings.Output.Simple.TwitchVodTrack")); + simpleVodTrack->setText(QTStr("Basic.Settings.Output.Simple.TwitchVodTrack")); simpleVodTrack->setVisible(simpleAdv); simpleVodTrack->setChecked(vodTrackEnabled); int pos; - ui->simpleStreamingLayout->getWidgetPosition(ui->simpleOutAdvanced, - &pos, nullptr); + ui->simpleStreamingLayout->getWidgetPosition(ui->simpleOutAdvanced, &pos, nullptr); ui->simpleStreamingLayout->insertRow(pos + 1, nullptr, simpleVodTrack); - HookWidget(simpleVodTrack.data(), &QCheckBox::clicked, - &OBSBasicSettings::OutputsChanged); - connect(ui->simpleOutAdvanced, &QCheckBox::toggled, - simpleVodTrack.data(), &QCheckBox::setVisible); + HookWidget(simpleVodTrack.data(), &QCheckBox::clicked, &OBSBasicSettings::OutputsChanged); + connect(ui->simpleOutAdvanced, &QCheckBox::toggled, simpleVodTrack.data(), &QCheckBox::setVisible); /* -------------------------------------- */ /* advanced output mode vod track widgets */ vodTrackCheckbox = new QCheckBox(this); - vodTrackCheckbox->setText( - QTStr("Basic.Settings.Output.Adv.TwitchVodTrack")); + vodTrackCheckbox->setText(QTStr("Basic.Settings.Output.Adv.TwitchVodTrack")); vodTrackCheckbox->setLayoutDirection(Qt::RightToLeft); vodTrackContainer = new QWidget(this); @@ -1088,12 +973,10 @@ void OBSBasicSettings::UpdateVodTrackSetting() vodTrack[i] = new QRadioButton(QString::number(i + 1)); vodTrackLayout->addWidget(vodTrack[i]); - HookWidget(vodTrack[i].data(), &QRadioButton::clicked, - &OBSBasicSettings::OutputsChanged); + HookWidget(vodTrack[i].data(), &QRadioButton::clicked, &OBSBasicSettings::OutputsChanged); } - HookWidget(vodTrackCheckbox.data(), &QCheckBox::clicked, - &OBSBasicSettings::OutputsChanged); + HookWidget(vodTrackCheckbox.data(), &QCheckBox::clicked, &OBSBasicSettings::OutputsChanged); vodTrackLayout->addStretch(); vodTrackLayout->setContentsMargins(0, 0, 0, 0); @@ -1102,16 +985,13 @@ void OBSBasicSettings::UpdateVodTrackSetting() ui->advOutTopLayout->insertRow(2, vodTrackCheckbox, vodTrackContainer); - vodTrackEnabled = - config_get_bool(main->Config(), "AdvOut", "VodTrackEnabled"); + vodTrackEnabled = config_get_bool(main->Config(), "AdvOut", "VodTrackEnabled"); vodTrackCheckbox->setChecked(vodTrackEnabled); vodTrackContainer->setEnabled(vodTrackEnabled); - connect(vodTrackCheckbox, &QCheckBox::clicked, vodTrackContainer, - &QWidget::setEnabled); + connect(vodTrackCheckbox, &QCheckBox::clicked, vodTrackContainer, &QWidget::setEnabled); - int trackIndex = - config_get_int(main->Config(), "AdvOut", "VodTrackIndex"); + int trackIndex = config_get_int(main->Config(), "AdvOut", "VodTrackIndex"); for (int i = 0; i < MAX_AUDIO_MIXES; i++) { vodTrack[i]->setChecked((i + 1) == trackIndex); } @@ -1119,8 +999,7 @@ void OBSBasicSettings::UpdateVodTrackSetting() OBSService OBSBasicSettings::GetStream1Service() { - return stream1Changed ? SpawnTempService() - : OBSService(main->GetService()); + return stream1Changed ? SpawnTempService() : OBSService(main->GetService()); } void OBSBasicSettings::UpdateServiceRecommendations() @@ -1144,13 +1023,11 @@ void OBSBasicSettings::UpdateServiceRecommendations() #define ENFORCE_TEXT(x) QTStr("Basic.Settings.Stream.Recommended." x) if (vbitrate) - text += ENFORCE_TEXT("MaxVideoBitrate") - .arg(QString::number(vbitrate)); + text += ENFORCE_TEXT("MaxVideoBitrate").arg(QString::number(vbitrate)); if (abitrate) { if (!text.isEmpty()) text += "
"; - text += ENFORCE_TEXT("MaxAudioBitrate") - .arg(QString::number(abitrate)); + text += ENFORCE_TEXT("MaxAudioBitrate").arg(QString::number(abitrate)); } if (res_count) { if (!text.isEmpty()) @@ -1168,9 +1045,7 @@ void OBSBasicSettings::UpdateServiceRecommendations() } } - QString res_str = - QString("%1x%2").arg(QString::number(best_res.cx), - QString::number(best_res.cy)); + QString res_str = QString("%1x%2").arg(QString::number(best_res.cx), QString::number(best_res.cy)); text += ENFORCE_TEXT("MaxResolution").arg(res_str); } if (fps) { @@ -1209,16 +1084,13 @@ void OBSBasicSettings::DisplayEnforceWarning(bool checked) QMessageBox::StandardButton button; -#define ENFORCE_WARNING(x) \ - QTStr("Basic.Settings.Stream.IgnoreRecommended.Warn." x) +#define ENFORCE_WARNING(x) QTStr("Basic.Settings.Stream.IgnoreRecommended.Warn." x) - button = OBSMessageBox::question(this, ENFORCE_WARNING("Title"), - ENFORCE_WARNING("Text")); + button = OBSMessageBox::question(this, ENFORCE_WARNING("Title"), ENFORCE_WARNING("Text")); #undef ENFORCE_WARNING if (button == QMessageBox::No) { - QMetaObject::invokeMethod(ui->ignoreRecommended, "setChecked", - Qt::QueuedConnection, + QMetaObject::invokeMethod(ui->ignoreRecommended, "setChecked", Qt::QueuedConnection, Q_ARG(bool, false)); return; } @@ -1226,8 +1098,7 @@ void OBSBasicSettings::DisplayEnforceWarning(bool checked) SimpleRecordingEncoderChanged(); } -bool OBSBasicSettings::ResFPSValid(obs_service_resolution *res_list, - size_t res_count, int max_fps) +bool OBSBasicSettings::ResFPSValid(obs_service_resolution *res_list, size_t res_count, int max_fps) { if (!res_count && !max_fps) return true; @@ -1266,9 +1137,7 @@ bool OBSBasicSettings::ResFPSValid(obs_service_resolution *res_list, return true; } -extern void set_closest_res(int &cx, int &cy, - struct obs_service_resolution *res_list, - size_t count); +extern void set_closest_res(int &cx, int &cy, struct obs_service_resolution *res_list, size_t count); /* Checks for and updates the resolution and FPS limits of a service, if any. * @@ -1303,8 +1172,7 @@ bool OBSBasicSettings::UpdateResFPSLimits() if (!IsCustomService() && !ignoreRecommended) { OBSService service = GetStream1Service(); - obs_service_get_supported_resolutions(service, &res_list, - &res_count); + obs_service_get_supported_resolutions(service, &res_list, &res_count); obs_service_get_max_fps(service, &max_fps); } @@ -1329,19 +1197,16 @@ bool OBSBasicSettings::UpdateResFPSLimits() if (fpsType == 1) { //Integer fpsd = (double)ui->fpsInteger->value(); } else if (fpsType == 2) { //Fractional - fpsd = (double)ui->fpsNumerator->value() / - (double)ui->fpsDenominator->value(); + fpsd = (double)ui->fpsNumerator->value() / (double)ui->fpsDenominator->value(); } else { //Common - sscanf(QT_TO_UTF8(ui->fpsCommon->currentText()), "%lf", - &fpsd); + sscanf(QT_TO_UTF8(ui->fpsCommon->currentText()), "%lf", &fpsd); } double closest_diff = 1000000000000.0; for (int i = 0; i < ui->fpsCommon->count(); i++) { double com_fpsd; - sscanf(QT_TO_UTF8(ui->fpsCommon->itemText(i)), "%lf", - &com_fpsd); + sscanf(QT_TO_UTF8(ui->fpsCommon->itemText(i)), "%lf", &com_fpsd); if (com_fpsd > max_fpsd) { continue; @@ -1356,8 +1221,7 @@ bool OBSBasicSettings::UpdateResFPSLimits() } } - QString res_str = - QString("%1x%2").arg(QString::number(cx), QString::number(cy)); + QString res_str = QString("%1x%2").arg(QString::number(cx), QString::number(cy)); /* ------------------------------------ */ /* Display message box if res/FPS bad */ @@ -1377,8 +1241,7 @@ bool OBSBasicSettings::UpdateResFPSLimits() QMessageBox::StandardButton button; -#define WARNING_VAL(x) \ - QTStr("Basic.Settings.Output.Warn.EnforceResolutionFPS." x) +#define WARNING_VAL(x) QTStr("Basic.Settings.Output.Warn.EnforceResolutionFPS." x) QString str; if (res_count) @@ -1389,20 +1252,15 @@ bool OBSBasicSettings::UpdateResFPSLimits() str += WARNING_VAL("FPS").arg(fps_str); } - button = OBSMessageBox::question(this, WARNING_VAL("Title"), - WARNING_VAL("Msg").arg(str)); + button = OBSMessageBox::question(this, WARNING_VAL("Title"), WARNING_VAL("Msg").arg(str)); #undef WARNING_VAL if (button == QMessageBox::No) { if (idx != lastServiceIdx) - QMetaObject::invokeMethod( - ui->service, "setCurrentIndex", - Qt::QueuedConnection, - Q_ARG(int, lastServiceIdx)); + QMetaObject::invokeMethod(ui->service, "setCurrentIndex", Qt::QueuedConnection, + Q_ARG(int, lastServiceIdx)); else - QMetaObject::invokeMethod(ui->ignoreRecommended, - "setChecked", - Qt::QueuedConnection, + QMetaObject::invokeMethod(ui->ignoreRecommended, "setChecked", Qt::QueuedConnection, Q_ARG(bool, true)); return false; } @@ -1416,17 +1274,14 @@ bool OBSBasicSettings::UpdateResFPSLimits() if (res_count) { ui->outputResolution->clear(); ui->outputResolution->setEditable(false); - HookWidget(ui->outputResolution, - &QComboBox::currentIndexChanged, + HookWidget(ui->outputResolution, &QComboBox::currentIndexChanged, &OBSBasicSettings::VideoChangedResolution); int new_res_index = -1; for (size_t i = 0; i < res_count; i++) { obs_service_resolution val = res_list[i]; - QString str = - QString("%1x%2").arg(QString::number(val.cx), - QString::number(val.cy)); + QString str = QString("%1x%2").arg(QString::number(val.cx), QString::number(val.cy)); ui->outputResolution->addItem(str); if (val.cx == cx && val.cy == cy) @@ -1447,8 +1302,7 @@ bool OBSBasicSettings::UpdateResFPSLimits() if (!ui->outputResolution->isEditable()) { RecreateOutputResolutionWidget(); ui->outputResolution->blockSignals(true); - ResetDownscales((uint32_t)baseCX, (uint32_t)baseCY, - true); + ResetDownscales((uint32_t)baseCX, (uint32_t)baseCY, true); ui->outputResolution->setCurrentText(res); } } @@ -1457,8 +1311,7 @@ bool OBSBasicSettings::UpdateResFPSLimits() if (max_fps) { for (int i = 0; i < ui->fpsCommon->count(); i++) { double com_fpsd; - sscanf(QT_TO_UTF8(ui->fpsCommon->itemText(i)), "%lf", - &com_fpsd); + sscanf(QT_TO_UTF8(ui->fpsCommon->itemText(i)), "%lf", &com_fpsd); if (com_fpsd > max_fpsd) { SetComboItemEnabled(ui->fpsCommon, i, false); @@ -1506,8 +1359,7 @@ static bool service_supports_codec(const char **codecs, const char *codec) extern bool EncoderAvailable(const char *encoder); extern const char *get_simple_output_encoder(const char *name); -static inline bool service_supports_encoder(const char **codecs, - const char *encoder) +static inline bool service_supports_encoder(const char **codecs, const char *encoder) { if (!EncoderAvailable(encoder)) return false; @@ -1532,8 +1384,7 @@ bool OBSBasicSettings::ServiceAndVCodecCompatible() const char *codec; if (simple) { - QString encoder = - ui->simpleOutStrEncoder->currentData().toString(); + QString encoder = ui->simpleOutStrEncoder->currentData().toString(); const char *id = get_simple_output_encoder(QT_TO_UTF8(encoder)); codec = obs_get_encoder_codec(id); } else { @@ -1548,15 +1399,11 @@ bool OBSBasicSettings::ServiceAndVCodecCompatible() const char *output; char **output_codecs; - obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), - &output, return_first_id); + obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), &output, return_first_id); - output_codecs = strlist_split( - obs_get_output_supported_video_codecs(output), ';', - false); + output_codecs = strlist_split(obs_get_output_supported_video_codecs(output), ';', false); - ret = service_supports_codec((const char **)output_codecs, - codec); + ret = service_supports_codec((const char **)output_codecs, codec); strlist_free(output_codecs); } else { @@ -1587,14 +1434,10 @@ bool OBSBasicSettings::ServiceAndACodecCompatible() const char *output; char **output_codecs; - obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), - &output, return_first_id); - output_codecs = strlist_split( - obs_get_output_supported_audio_codecs(output), ';', - false); + obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), &output, return_first_id); + output_codecs = strlist_split(obs_get_output_supported_audio_codecs(output), ';', false); - ret = service_supports_codec((const char **)output_codecs, - QT_TO_UTF8(codec)); + ret = service_supports_codec((const char **)output_codecs, QT_TO_UTF8(codec)); strlist_free(output_codecs); } else { @@ -1607,8 +1450,8 @@ bool OBSBasicSettings::ServiceAndACodecCompatible() /* we really need a way to find fallbacks in a less hardcoded way. maybe. */ static QString get_adv_fallback(const QString &enc) { - if (enc == "obs_nvenc_hevc_tex" || enc == "obs_nvenc_av1_tex" || - enc == "jim_hevc_nvenc" || enc == "jim_av1_nvenc") + if (enc == "obs_nvenc_hevc_tex" || enc == "obs_nvenc_av1_tex" || enc == "jim_hevc_nvenc" || + enc == "jim_av1_nvenc") return "obs_nvenc_h264_tex"; if (enc == "h265_texture_amf" || enc == "av1_texture_amf") return "h264_texture_amf"; @@ -1657,8 +1500,7 @@ bool OBSBasicSettings::ServiceSupportsCodecCheck() bool acodec_compat = ServiceAndACodecCompatible(); if (vcodec_compat && acodec_compat) { - if (lastServiceIdx != ui->service->currentIndex() || - IsCustomService()) + if (lastServiceIdx != ui->service->currentIndex() || IsCustomService()) ResetEncoders(true); return true; } @@ -1674,8 +1516,7 @@ bool OBSBasicSettings::ServiceSupportsCodecCheck() /* get current codec */ if (simple) { - QString cur_enc = - ui->simpleOutStrEncoder->currentData().toString(); + QString cur_enc = ui->simpleOutStrEncoder->currentData().toString(); QString fb_enc = get_simple_fallback(cur_enc); int cur_idx = ui->simpleOutStrEncoder->findData(cur_enc); @@ -1687,55 +1528,39 @@ bool OBSBasicSettings::ServiceSupportsCodecCheck() cur_enc = ui->simpleOutStrAEncoder->currentData().toString(); fb_enc = (cur_enc == "opus") ? "aac" : "opus"; - cur_audio_name = ui->simpleOutStrAEncoder->itemText( - ui->simpleOutStrAEncoder->findData(cur_enc)); - fb_audio_name = - (cur_enc == "opus") - ? QTStr("Basic.Settings.Output.Simple.Codec.AAC") - : QTStr("Basic.Settings.Output.Simple.Codec.Opus"); + cur_audio_name = ui->simpleOutStrAEncoder->itemText(ui->simpleOutStrAEncoder->findData(cur_enc)); + fb_audio_name = (cur_enc == "opus") ? QTStr("Basic.Settings.Output.Simple.Codec.AAC") + : QTStr("Basic.Settings.Output.Simple.Codec.Opus"); } else { QString cur_enc = ui->advOutEncoder->currentData().toString(); QString fb_enc = get_adv_fallback(cur_enc); - cur_video_name = - obs_encoder_get_display_name(QT_TO_UTF8(cur_enc)); - fb_video_name = - obs_encoder_get_display_name(QT_TO_UTF8(fb_enc)); + cur_video_name = obs_encoder_get_display_name(QT_TO_UTF8(cur_enc)); + fb_video_name = obs_encoder_get_display_name(QT_TO_UTF8(fb_enc)); cur_enc = ui->advOutAEncoder->currentData().toString(); fb_enc = get_adv_audio_fallback(cur_enc); - cur_audio_name = - obs_encoder_get_display_name(QT_TO_UTF8(cur_enc)); - fb_audio_name = - obs_encoder_get_display_name(QT_TO_UTF8(fb_enc)); + cur_audio_name = obs_encoder_get_display_name(QT_TO_UTF8(cur_enc)); + fb_audio_name = obs_encoder_get_display_name(QT_TO_UTF8(fb_enc)); } -#define WARNING_VAL(x) \ - QTStr("Basic.Settings.Output.Warn.ServiceCodecCompatibility." x) +#define WARNING_VAL(x) QTStr("Basic.Settings.Output.Warn.ServiceCodecCompatibility." x) - QString msg = WARNING_VAL("Msg").arg( - service, vcodec_compat ? cur_audio_name : cur_video_name, - vcodec_compat ? fb_audio_name : fb_video_name); + QString msg = WARNING_VAL("Msg").arg(service, vcodec_compat ? cur_audio_name : cur_video_name, + vcodec_compat ? fb_audio_name : fb_video_name); if (!vcodec_compat && !acodec_compat) - msg = WARNING_VAL("Msg2").arg(service, cur_video_name, - cur_audio_name, fb_video_name, - fb_audio_name); + msg = WARNING_VAL("Msg2").arg(service, cur_video_name, cur_audio_name, fb_video_name, fb_audio_name); auto button = OBSMessageBox::question(this, WARNING_VAL("Title"), msg); #undef WARNING_VAL if (button == QMessageBox::No) { - if (lastServiceIdx == 0 && - lastServiceIdx == ui->service->currentIndex()) - QMetaObject::invokeMethod(ui->customServer, "setText", - Qt::QueuedConnection, - Q_ARG(QString, - lastCustomServer)); + if (lastServiceIdx == 0 && lastServiceIdx == ui->service->currentIndex()) + QMetaObject::invokeMethod(ui->customServer, "setText", Qt::QueuedConnection, + Q_ARG(QString, lastCustomServer)); else - QMetaObject::invokeMethod(ui->service, - "setCurrentIndex", - Qt::QueuedConnection, + QMetaObject::invokeMethod(ui->service, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(int, lastServiceIdx)); return false; } @@ -1744,17 +1569,14 @@ bool OBSBasicSettings::ServiceSupportsCodecCheck() return true; } -#define TEXT_USE_STREAM_ENC \ - QTStr("Basic.Settings.Output.Adv.Recording.UseStreamEncoder") +#define TEXT_USE_STREAM_ENC QTStr("Basic.Settings.Output.Adv.Recording.UseStreamEncoder") void OBSBasicSettings::ResetEncoders(bool streamOnly) { QString lastAdvVideoEnc = ui->advOutEncoder->currentData().toString(); - QString lastVideoEnc = - ui->simpleOutStrEncoder->currentData().toString(); + QString lastVideoEnc = ui->simpleOutStrEncoder->currentData().toString(); QString lastAdvAudioEnc = ui->advOutAEncoder->currentData().toString(); - QString lastAudioEnc = - ui->simpleOutStrAEncoder->currentData().toString(); + QString lastAudioEnc = ui->simpleOutStrAEncoder->currentData().toString(); OBSService service = SpawnTempService(); const char **vcodecs = obs_service_get_supported_video_codecs(service); const char **acodecs = obs_service_get_supported_audio_codecs(service); @@ -1766,22 +1588,16 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) if (!vcodecs || IsCustomService()) { const char *output; - obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), - &output, return_first_id); - output_vcodecs = strlist_split( - obs_get_output_supported_video_codecs(output), ';', - false); + obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), &output, return_first_id); + output_vcodecs = strlist_split(obs_get_output_supported_video_codecs(output), ';', false); vcodecs = (const char **)output_vcodecs.Get(); } if (!acodecs || IsCustomService()) { const char *output; - obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), - &output, return_first_id); - output_acodecs = strlist_split( - obs_get_output_supported_audio_codecs(output), ';', - false); + obs_enum_output_types_with_protocol(QT_TO_UTF8(protocol), &output, return_first_id); + output_acodecs = strlist_split(obs_get_output_supported_audio_codecs(output), ';', false); acodecs = (const char **)output_acodecs.Get(); } @@ -1837,11 +1653,9 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) if (!streamOnly) { ui->advOutRecEncoder->model()->sort(0); - ui->advOutRecEncoder->insertItem(0, TEXT_USE_STREAM_ENC, - "none"); + ui->advOutRecEncoder->insertItem(0, TEXT_USE_STREAM_ENC, "none"); ui->advOutRecAEncoder->model()->sort(0); - ui->advOutRecAEncoder->insertItem(0, TEXT_USE_STREAM_ENC, - "none"); + ui->advOutRecAEncoder->insertItem(0, TEXT_USE_STREAM_ENC, "none"); } /* ------------------------------------------------- */ @@ -1849,83 +1663,58 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) #define ENCODER_STR(str) QTStr("Basic.Settings.Output.Simple.Encoder." str) - ui->simpleOutStrEncoder->addItem(ENCODER_STR("Software"), - QString(SIMPLE_ENCODER_X264)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Software"), QString(SIMPLE_ENCODER_X264)); #ifdef _WIN32 if (service_supports_encoder(vcodecs, "obs_qsv11")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.QSV.H264"), - QString(SIMPLE_ENCODER_QSV)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.QSV.H264"), QString(SIMPLE_ENCODER_QSV)); if (service_supports_encoder(vcodecs, "obs_qsv11_av1")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.QSV.AV1"), - QString(SIMPLE_ENCODER_QSV_AV1)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.QSV.AV1"), QString(SIMPLE_ENCODER_QSV_AV1)); #endif if (service_supports_encoder(vcodecs, "ffmpeg_nvenc")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.NVENC.H264"), - QString(SIMPLE_ENCODER_NVENC)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.NVENC.H264"), QString(SIMPLE_ENCODER_NVENC)); if (service_supports_encoder(vcodecs, "obs_nvenc_av1_tex")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.NVENC.AV1"), - QString(SIMPLE_ENCODER_NVENC_AV1)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.NVENC.AV1"), QString(SIMPLE_ENCODER_NVENC_AV1)); #ifdef ENABLE_HEVC if (service_supports_encoder(vcodecs, "h265_texture_amf")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.AMD.HEVC"), - QString(SIMPLE_ENCODER_AMD_HEVC)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.AMD.HEVC"), QString(SIMPLE_ENCODER_AMD_HEVC)); if (service_supports_encoder(vcodecs, "ffmpeg_hevc_nvenc")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.NVENC.HEVC"), - QString(SIMPLE_ENCODER_NVENC_HEVC)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.NVENC.HEVC"), + QString(SIMPLE_ENCODER_NVENC_HEVC)); #endif if (service_supports_encoder(vcodecs, "h264_texture_amf")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.AMD.H264"), - QString(SIMPLE_ENCODER_AMD)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.AMD.H264"), QString(SIMPLE_ENCODER_AMD)); if (service_supports_encoder(vcodecs, "av1_texture_amf")) - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.AMD.AV1"), - QString(SIMPLE_ENCODER_AMD_AV1)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.AMD.AV1"), QString(SIMPLE_ENCODER_AMD_AV1)); /* Preprocessor guard required for the macOS version check */ #ifdef __APPLE__ - if (service_supports_encoder( - vcodecs, "com.apple.videotoolbox.videoencoder.ave.avc") + if (service_supports_encoder(vcodecs, "com.apple.videotoolbox.videoencoder.ave.avc") #ifndef __aarch64__ && os_get_emulation_status() == true #endif ) { if (__builtin_available(macOS 13.0, *)) { - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.Apple.H264"), - QString(SIMPLE_ENCODER_APPLE_H264)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.Apple.H264"), + QString(SIMPLE_ENCODER_APPLE_H264)); } } #ifdef ENABLE_HEVC - if (service_supports_encoder( - vcodecs, "com.apple.videotoolbox.videoencoder.ave.hevc") + if (service_supports_encoder(vcodecs, "com.apple.videotoolbox.videoencoder.ave.hevc") #ifndef __aarch64__ && os_get_emulation_status() == true #endif ) { if (__builtin_available(macOS 13.0, *)) { - ui->simpleOutStrEncoder->addItem( - ENCODER_STR("Hardware.Apple.HEVC"), - QString(SIMPLE_ENCODER_APPLE_HEVC)); + ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.Apple.HEVC"), + QString(SIMPLE_ENCODER_APPLE_HEVC)); } } #endif #endif - if (service_supports_encoder(acodecs, "CoreAudio_AAC") || - service_supports_encoder(acodecs, "libfdk_aac") || + if (service_supports_encoder(acodecs, "CoreAudio_AAC") || service_supports_encoder(acodecs, "libfdk_aac") || service_supports_encoder(acodecs, "ffmpeg_aac")) - ui->simpleOutStrAEncoder->addItem( - QTStr("Basic.Settings.Output.Simple.Codec.AAC.Default"), - "aac"); + ui->simpleOutStrAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.AAC.Default"), "aac"); if (service_supports_encoder(acodecs, "ffmpeg_opus")) - ui->simpleOutStrAEncoder->addItem( - QTStr("Basic.Settings.Output.Simple.Codec.Opus"), - "opus"); + ui->simpleOutStrAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.Opus"), "opus"); #undef ENCODER_STR /* ------------------------------------------------- */ @@ -1935,8 +1724,7 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) int idx = ui->advOutEncoder->findData(lastAdvVideoEnc); if (idx == -1) { lastAdvVideoEnc = get_adv_fallback(lastAdvVideoEnc); - ui->advOutEncoder->setProperty("changed", - QVariant(true)); + ui->advOutEncoder->setProperty("changed", QVariant(true)); OutputsChanged(); } @@ -1948,10 +1736,8 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) if (!lastAdvAudioEnc.isEmpty()) { int idx = ui->advOutAEncoder->findData(lastAdvAudioEnc); if (idx == -1) { - lastAdvAudioEnc = - get_adv_audio_fallback(lastAdvAudioEnc); - ui->advOutAEncoder->setProperty("changed", - QVariant(true)); + lastAdvAudioEnc = get_adv_audio_fallback(lastAdvAudioEnc); + ui->advOutAEncoder->setProperty("changed", QVariant(true)); OutputsChanged(); } @@ -1964,8 +1750,7 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) int idx = ui->simpleOutStrEncoder->findData(lastVideoEnc); if (idx == -1) { lastVideoEnc = get_simple_fallback(lastVideoEnc); - ui->simpleOutStrEncoder->setProperty("changed", - QVariant(true)); + ui->simpleOutStrEncoder->setProperty("changed", QVariant(true)); OutputsChanged(); } @@ -1977,10 +1762,8 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) if (!lastAudioEnc.isEmpty()) { int idx = ui->simpleOutStrAEncoder->findData(lastAudioEnc); if (idx == -1) { - lastAudioEnc = (lastAudioEnc == "opus") ? "aac" - : "opus"; - ui->simpleOutStrAEncoder->setProperty("changed", - QVariant(true)); + lastAudioEnc = (lastAudioEnc == "opus") ? "aac" : "opus"; + ui->simpleOutStrAEncoder->setProperty("changed", QVariant(true)); OutputsChanged(); } diff --git a/UI/window-basic-settings.cpp b/UI/window-basic-settings.cpp index 952709a4e..f4efc3e61 100644 --- a/UI/window-basic-settings.cpp +++ b/UI/window-basic-settings.cpp @@ -62,10 +62,7 @@ class SettingsEventFilter : public QObject { QScopedPointer shortcutFilter; public: - inline SettingsEventFilter() - : shortcutFilter((OBSEventFilter *)CreateShortcutFilter()) - { - } + inline SettingsEventFilter() : shortcutFilter((OBSEventFilter *)CreateShortcutFilter()) {} protected: bool eventFilter(QObject *obj, QEvent *event) override @@ -162,13 +159,11 @@ static inline bool SetComboByValue(QComboBox *combo, const char *name) return false; } -static inline bool SetInvalidValue(QComboBox *combo, const char *name, - const char *data = nullptr) +static inline bool SetInvalidValue(QComboBox *combo, const char *name, const char *data = nullptr) { combo->insertItem(0, name, data); - QStandardItemModel *model = - dynamic_cast(combo->model()); + QStandardItemModel *model = dynamic_cast(combo->model()); if (!model) return false; @@ -235,36 +230,30 @@ static int FindClosestAvailableAudioBitrate(QComboBox *box, int bitrate) static void PopulateSimpleBitrates(QComboBox *box, bool opus) { - auto &bitrateMap = opus ? GetSimpleOpusEncoderBitrateMap() - : GetSimpleAACEncoderBitrateMap(); + auto &bitrateMap = opus ? GetSimpleOpusEncoderBitrateMap() : GetSimpleAACEncoderBitrateMap(); if (bitrateMap.empty()) return; vector> pairs; for (auto &entry : bitrateMap) - pairs.emplace_back( - QString::number(entry.first), - obs_encoder_get_display_name(entry.second.c_str())); + pairs.emplace_back(QString::number(entry.first), obs_encoder_get_display_name(entry.second.c_str())); QString currentBitrate = box->currentText(); box->clear(); for (auto &pair : pairs) { box->addItem(pair.first); - box->setItemData(box->count() - 1, pair.second, - Qt::ToolTipRole); + box->setItemData(box->count() - 1, pair.second, Qt::ToolTipRole); } if (box->findData(currentBitrate) == -1) { - int bitrate = FindClosestAvailableAudioBitrate( - box, currentBitrate.toInt()); + int bitrate = FindClosestAvailableAudioBitrate(box, currentBitrate.toInt()); box->setCurrentText(QString::number(bitrate)); } else box->setCurrentText(currentBitrate); } -static void PopulateAdvancedBitrates(initializer_list boxes, - const char *stream_id, const char *rec_id) +static void PopulateAdvancedBitrates(initializer_list boxes, const char *stream_id, const char *rec_id) { auto &streamBitrates = GetAudioEncoderBitrates(stream_id); auto &recBitrates = GetAudioEncoderBitrates(rec_id); @@ -287,8 +276,7 @@ static void PopulateAdvancedBitrates(initializer_list boxes, } if (box->findData(currentBitrate) == -1) { - int bitrate = FindClosestAvailableAudioBitrate( - box, currentBitrate.toInt()); + int bitrate = FindClosestAvailableAudioBitrate(box, currentBitrate.toInt()); box->setCurrentText(QString::number(bitrate)); } else box->setCurrentText(currentBitrate); @@ -309,8 +297,7 @@ static std::tuple aspect_ratio(int cx, int cy) return std::make_tuple(newCX, newCY); } -static inline void HighlightGroupBoxLabel(QGroupBox *gb, QWidget *widget, - QString objectName) +static inline void HighlightGroupBoxLabel(QGroupBox *gb, QWidget *widget, QString objectName) { QFormLayout *layout = qobject_cast(gb->layout()); @@ -588,9 +575,7 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) HookWidget(ui->dynBitrate, CHECK_CHANGED, ADV_CHANGED); /* clang-format on */ -#define ADD_HOTKEY_FOCUS_TYPE(s) \ - ui->hotkeyFocusType->addItem( \ - QTStr("Basic.Settings.Advanced.Hotkeys." s), s) +#define ADD_HOTKEY_FOCUS_TYPE(s) ui->hotkeyFocusType->addItem(QTStr("Basic.Settings.Advanced.Hotkeys." s), s) ADD_HOTKEY_FOCUS_TYPE("NeverDisableHotkeys"); ADD_HOTKEY_FOCUS_TYPE("DisableHotkeysInFocus"); @@ -634,16 +619,11 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) const char *name; const char *val; } processPriorities[] = { - {"Basic.Settings.Advanced.General.ProcessPriority.High", - "High"}, - {"Basic.Settings.Advanced.General.ProcessPriority.AboveNormal", - "AboveNormal"}, - {"Basic.Settings.Advanced.General.ProcessPriority.Normal", - "Normal"}, - {"Basic.Settings.Advanced.General.ProcessPriority.BelowNormal", - "BelowNormal"}, - {"Basic.Settings.Advanced.General.ProcessPriority.Idle", - "Idle"}, + {"Basic.Settings.Advanced.General.ProcessPriority.High", "High"}, + {"Basic.Settings.Advanced.General.ProcessPriority.AboveNormal", "AboveNormal"}, + {"Basic.Settings.Advanced.General.ProcessPriority.Normal", "Normal"}, + {"Basic.Settings.Advanced.General.ProcessPriority.BelowNormal", "BelowNormal"}, + {"Basic.Settings.Advanced.General.ProcessPriority.Idle", "Idle"}, }; for (ProcessPriority pri : processPriorities) @@ -688,12 +668,9 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) ui->resetOSXVSync = nullptr; #endif - connect(ui->streamDelaySec, &QSpinBox::valueChanged, this, - &OBSBasicSettings::UpdateStreamDelayEstimate); - connect(ui->outputMode, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::UpdateStreamDelayEstimate); - connect(ui->simpleOutputVBitrate, &QSpinBox::valueChanged, this, - &OBSBasicSettings::UpdateStreamDelayEstimate); + connect(ui->streamDelaySec, &QSpinBox::valueChanged, this, &OBSBasicSettings::UpdateStreamDelayEstimate); + connect(ui->outputMode, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::UpdateStreamDelayEstimate); + connect(ui->simpleOutputVBitrate, &QSpinBox::valueChanged, this, &OBSBasicSettings::UpdateStreamDelayEstimate); connect(ui->simpleOutputABitrate, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::UpdateStreamDelayEstimate); connect(ui->advOutTrack1Bitrate, &QComboBox::currentIndexChanged, this, @@ -721,8 +698,7 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) auto ReloadAudioSources = [](void *data, calldata_t *param) { auto settings = static_cast(data); - auto source = static_cast( - calldata_ptr(param, "source")); + auto source = static_cast(calldata_ptr(param, "source")); if (!source) return; @@ -730,46 +706,33 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) if (!(obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO)) return; - QMetaObject::invokeMethod(settings, "ReloadAudioSources", - Qt::QueuedConnection); + QMetaObject::invokeMethod(settings, "ReloadAudioSources", Qt::QueuedConnection); }; - sourceCreated.Connect(obs_get_signal_handler(), "source_create", - ReloadAudioSources, this); - channelChanged.Connect(obs_get_signal_handler(), "channel_change", - ReloadAudioSources, this); + sourceCreated.Connect(obs_get_signal_handler(), "source_create", ReloadAudioSources, this); + channelChanged.Connect(obs_get_signal_handler(), "channel_change", ReloadAudioSources, this); - hotkeyConflictIcon = - QIcon::fromTheme("obs", QIcon(":/res/images/warning.svg")); + hotkeyConflictIcon = QIcon::fromTheme("obs", QIcon(":/res/images/warning.svg")); auto ReloadHotkeys = [](void *data, calldata_t *) { auto settings = static_cast(data); QMetaObject::invokeMethod(settings, "ReloadHotkeys"); }; - hotkeyRegistered.Connect(obs_get_signal_handler(), "hotkey_register", - ReloadHotkeys, this); + hotkeyRegistered.Connect(obs_get_signal_handler(), "hotkey_register", ReloadHotkeys, this); auto ReloadHotkeysIgnore = [](void *data, calldata_t *param) { auto settings = static_cast(data); - auto key = - static_cast(calldata_ptr(param, "key")); - QMetaObject::invokeMethod(settings, "ReloadHotkeys", - Q_ARG(obs_hotkey_id, - obs_hotkey_get_id(key))); + auto key = static_cast(calldata_ptr(param, "key")); + QMetaObject::invokeMethod(settings, "ReloadHotkeys", Q_ARG(obs_hotkey_id, obs_hotkey_get_id(key))); }; - hotkeyUnregistered.Connect(obs_get_signal_handler(), - "hotkey_unregister", ReloadHotkeysIgnore, - this); + hotkeyUnregistered.Connect(obs_get_signal_handler(), "hotkey_unregister", ReloadHotkeysIgnore, this); FillSimpleRecordingValues(); if (obs_audio_monitoring_available()) FillAudioMonitoringDevices(); - connect(ui->channelSetup, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::SurroundWarning); - connect(ui->channelSetup, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::SpeakerLayoutChanged); - connect(ui->lowLatencyBuffering, &QCheckBox::clicked, this, - &OBSBasicSettings::LowLatencyBufferingChanged); + connect(ui->channelSetup, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SurroundWarning); + connect(ui->channelSetup, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SpeakerLayoutChanged); + connect(ui->lowLatencyBuffering, &QCheckBox::clicked, this, &OBSBasicSettings::LowLatencyBufferingChanged); connect(ui->simpleOutRecQuality, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SimpleRecordingQualityChanged); connect(ui->simpleOutRecQuality, &QComboBox::currentIndexChanged, this, @@ -788,41 +751,27 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) &OBSBasicSettings::SimpleRecordingEncoderChanged); connect(ui->simpleOutputABitrate, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SimpleRecordingEncoderChanged); - connect(ui->simpleOutAdvanced, &QCheckBox::toggled, this, - &OBSBasicSettings::SimpleRecordingEncoderChanged); - connect(ui->ignoreRecommended, &QCheckBox::toggled, this, - &OBSBasicSettings::SimpleRecordingEncoderChanged); - connect(ui->simpleReplayBuf, &QGroupBox::toggled, this, - &OBSBasicSettings::SimpleReplayBufferChanged); - connect(ui->simpleOutputVBitrate, &QSpinBox::valueChanged, this, - &OBSBasicSettings::SimpleReplayBufferChanged); + connect(ui->simpleOutAdvanced, &QCheckBox::toggled, this, &OBSBasicSettings::SimpleRecordingEncoderChanged); + connect(ui->ignoreRecommended, &QCheckBox::toggled, this, &OBSBasicSettings::SimpleRecordingEncoderChanged); + connect(ui->simpleReplayBuf, &QGroupBox::toggled, this, &OBSBasicSettings::SimpleReplayBufferChanged); + connect(ui->simpleOutputVBitrate, &QSpinBox::valueChanged, this, &OBSBasicSettings::SimpleReplayBufferChanged); connect(ui->simpleOutputABitrate, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SimpleReplayBufferChanged); - connect(ui->simpleRBSecMax, &QSpinBox::valueChanged, this, - &OBSBasicSettings::SimpleReplayBufferChanged); + connect(ui->simpleRBSecMax, &QSpinBox::valueChanged, this, &OBSBasicSettings::SimpleReplayBufferChanged); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - connect(ui->advOutSplitFile, &QCheckBox::checkStateChanged, this, - &OBSBasicSettings::AdvOutSplitFileChanged); + connect(ui->advOutSplitFile, &QCheckBox::checkStateChanged, this, &OBSBasicSettings::AdvOutSplitFileChanged); #else - connect(ui->advOutSplitFile, &QCheckBox::stateChanged, this, - &OBSBasicSettings::AdvOutSplitFileChanged); + connect(ui->advOutSplitFile, &QCheckBox::stateChanged, this, &OBSBasicSettings::AdvOutSplitFileChanged); #endif connect(ui->advOutSplitFileType, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvOutSplitFileChanged); - connect(ui->advReplayBuf, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecTrack1, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecTrack2, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecTrack3, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecTrack4, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecTrack5, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecTrack6, &QCheckBox::toggled, this, - &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advReplayBuf, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecTrack1, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecTrack2, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecTrack3, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecTrack4, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecTrack5, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecTrack6, &QCheckBox::toggled, this, &OBSBasicSettings::AdvReplayBufferChanged); connect(ui->advOutTrack1Bitrate, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvReplayBufferChanged); connect(ui->advOutTrack2Bitrate, &QComboBox::currentIndexChanged, this, @@ -835,12 +784,9 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) &OBSBasicSettings::AdvReplayBufferChanged); connect(ui->advOutTrack6Bitrate, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecType, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advOutRecEncoder, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::AdvReplayBufferChanged); - connect(ui->advRBSecMax, &QSpinBox::valueChanged, this, - &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecType, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advOutRecEncoder, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvReplayBufferChanged); + connect(ui->advRBSecMax, &QSpinBox::valueChanged, this, &OBSBasicSettings::AdvReplayBufferChanged); // GPU scaling filters auto addScaleFilter = [&](const char *string, int value) -> void { @@ -848,24 +794,15 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) ui->advOutRecRescaleFilter->addItem(QTStr(string), value); }; - addScaleFilter("Basic.Settings.Output.Adv.Rescale.Disabled", - OBS_SCALE_DISABLE); - addScaleFilter("Basic.Settings.Video.DownscaleFilter.Bilinear", - OBS_SCALE_BILINEAR); - addScaleFilter("Basic.Settings.Video.DownscaleFilter.Area", - OBS_SCALE_AREA); - addScaleFilter("Basic.Settings.Video.DownscaleFilter.Bicubic", - OBS_SCALE_BICUBIC); - addScaleFilter("Basic.Settings.Video.DownscaleFilter.Lanczos", - OBS_SCALE_LANCZOS); + addScaleFilter("Basic.Settings.Output.Adv.Rescale.Disabled", OBS_SCALE_DISABLE); + addScaleFilter("Basic.Settings.Video.DownscaleFilter.Bilinear", OBS_SCALE_BILINEAR); + addScaleFilter("Basic.Settings.Video.DownscaleFilter.Area", OBS_SCALE_AREA); + addScaleFilter("Basic.Settings.Video.DownscaleFilter.Bicubic", OBS_SCALE_BICUBIC); + addScaleFilter("Basic.Settings.Video.DownscaleFilter.Lanczos", OBS_SCALE_LANCZOS); - auto connectScaleFilter = [&](QComboBox *filter, - QComboBox *res) -> void { + auto connectScaleFilter = [&](QComboBox *filter, QComboBox *res) -> void { connect(filter, &QComboBox::currentIndexChanged, this, - [this, res, filter](int) { - res->setEnabled(filter->currentData() != - OBS_SCALE_DISABLE); - }); + [this, res, filter](int) { res->setEnabled(filter->currentData() != OBS_SCALE_DISABLE); }); }; connectScaleFilter(ui->advOutRescaleFilter, ui->advOutRescale); @@ -902,91 +839,53 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) InitAppearancePage(); LoadSettings(false); - ui->advOutTrack1->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track1")); - ui->advOutTrack2->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track2")); - ui->advOutTrack3->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track3")); - ui->advOutTrack4->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track4")); - ui->advOutTrack5->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track5")); - ui->advOutTrack6->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track6")); + ui->advOutTrack1->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track1")); + ui->advOutTrack2->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track2")); + ui->advOutTrack3->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track3")); + ui->advOutTrack4->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track4")); + ui->advOutTrack5->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track5")); + ui->advOutTrack6->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track6")); - ui->advOutRecTrack1->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track1")); - ui->advOutRecTrack2->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track2")); - ui->advOutRecTrack3->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track3")); - ui->advOutRecTrack4->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track4")); - ui->advOutRecTrack5->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track5")); - ui->advOutRecTrack6->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track6")); + ui->advOutRecTrack1->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track1")); + ui->advOutRecTrack2->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track2")); + ui->advOutRecTrack3->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track3")); + ui->advOutRecTrack4->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track4")); + ui->advOutRecTrack5->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track5")); + ui->advOutRecTrack6->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track6")); - ui->advOutFFTrack1->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track1")); - ui->advOutFFTrack2->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track2")); - ui->advOutFFTrack3->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track3")); - ui->advOutFFTrack4->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track4")); - ui->advOutFFTrack5->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track5")); - ui->advOutFFTrack6->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Audio.Track6")); + ui->advOutFFTrack1->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track1")); + ui->advOutFFTrack2->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track2")); + ui->advOutFFTrack3->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track3")); + ui->advOutFFTrack4->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track4")); + ui->advOutFFTrack5->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track5")); + ui->advOutFFTrack6->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Audio.Track6")); - ui->snappingEnabled->setAccessibleName( - QTStr("Basic.Settings.General.Snapping")); - ui->systemTrayEnabled->setAccessibleName( - QTStr("Basic.Settings.General.SysTray")); - ui->label_31->setAccessibleName( - QTStr("Basic.Settings.Output.Adv.Recording.RecType")); - ui->streamDelayEnable->setAccessibleName( - QTStr("Basic.Settings.Advanced.StreamDelay")); - ui->reconnectEnable->setAccessibleName( - QTStr("Basic.Settings.Output.Reconnect")); + ui->snappingEnabled->setAccessibleName(QTStr("Basic.Settings.General.Snapping")); + ui->systemTrayEnabled->setAccessibleName(QTStr("Basic.Settings.General.SysTray")); + ui->label_31->setAccessibleName(QTStr("Basic.Settings.Output.Adv.Recording.RecType")); + ui->streamDelayEnable->setAccessibleName(QTStr("Basic.Settings.Advanced.StreamDelay")); + ui->reconnectEnable->setAccessibleName(QTStr("Basic.Settings.Output.Reconnect")); // Add warning checks to advanced output recording section controls - connect(ui->advOutRecTrack1, &QCheckBox::clicked, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecTrack2, &QCheckBox::clicked, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecTrack3, &QCheckBox::clicked, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecTrack4, &QCheckBox::clicked, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecTrack5, &QCheckBox::clicked, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecTrack6, &QCheckBox::clicked, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecFormat, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); - connect(ui->advOutRecEncoder, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecTrack1, &QCheckBox::clicked, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecTrack2, &QCheckBox::clicked, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecTrack3, &QCheckBox::clicked, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecTrack4, &QCheckBox::clicked, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecTrack5, &QCheckBox::clicked, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecTrack6, &QCheckBox::clicked, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecFormat, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvOutRecCheckWarnings); + connect(ui->advOutRecEncoder, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvOutRecCheckWarnings); // Check codec compatibility when format (container) changes - connect(ui->advOutRecFormat, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::AdvOutRecCheckCodecs); + connect(ui->advOutRecFormat, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvOutRecCheckCodecs); // Set placeholder used when selection was reset due to incompatibilities - ui->advOutAEncoder->setPlaceholderText( - QTStr("CodecCompat.CodecPlaceholder")); - ui->advOutRecEncoder->setPlaceholderText( - QTStr("CodecCompat.CodecPlaceholder")); - ui->advOutRecAEncoder->setPlaceholderText( - QTStr("CodecCompat.CodecPlaceholder")); - ui->simpleOutRecEncoder->setPlaceholderText( - QTStr("CodecCompat.CodecPlaceholder")); - ui->simpleOutRecAEncoder->setPlaceholderText( - QTStr("CodecCompat.CodecPlaceholder")); - ui->simpleOutRecFormat->setPlaceholderText( - QTStr("CodecCompat.ContainerPlaceholder")); + ui->advOutAEncoder->setPlaceholderText(QTStr("CodecCompat.CodecPlaceholder")); + ui->advOutRecEncoder->setPlaceholderText(QTStr("CodecCompat.CodecPlaceholder")); + ui->advOutRecAEncoder->setPlaceholderText(QTStr("CodecCompat.CodecPlaceholder")); + ui->simpleOutRecEncoder->setPlaceholderText(QTStr("CodecCompat.CodecPlaceholder")); + ui->simpleOutRecAEncoder->setPlaceholderText(QTStr("CodecCompat.CodecPlaceholder")); + ui->simpleOutRecFormat->setPlaceholderText(QTStr("CodecCompat.ContainerPlaceholder")); SimpleRecordingQualityChanged(); AdvOutSplitFileChanged(); @@ -1009,13 +908,11 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) ui->advOutRecRescale->lineEdit()->setValidator(validator); ui->advOutFFRescale->lineEdit()->setValidator(validator); - connect(ui->useStreamKeyAdv, &QCheckBox::clicked, this, - &OBSBasicSettings::UseStreamKeyAdvClicked); + connect(ui->useStreamKeyAdv, &QCheckBox::clicked, this, &OBSBasicSettings::UseStreamKeyAdvClicked); connect(ui->simpleOutStrAEncoder, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SimpleStreamAudioEncoderChanged); - connect(ui->advOutAEncoder, &QComboBox::currentIndexChanged, this, - &OBSBasicSettings::AdvAudioEncodersChanged); + connect(ui->advOutAEncoder, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvAudioEncodersChanged); connect(ui->advOutRecAEncoder, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::AdvAudioEncodersChanged); @@ -1037,27 +934,21 @@ OBSBasicSettings::~OBSBasicSettings() EnableThreadedMessageBoxes(false); } -void OBSBasicSettings::SaveCombo(QComboBox *widget, const char *section, - const char *value) +void OBSBasicSettings::SaveCombo(QComboBox *widget, const char *section, const char *value) { if (WidgetChanged(widget)) - config_set_string(main->Config(), section, value, - QT_TO_UTF8(widget->currentText())); + config_set_string(main->Config(), section, value, QT_TO_UTF8(widget->currentText())); } -void OBSBasicSettings::SaveComboData(QComboBox *widget, const char *section, - const char *value) +void OBSBasicSettings::SaveComboData(QComboBox *widget, const char *section, const char *value) { if (WidgetChanged(widget)) { QString str = GetComboData(widget); - config_set_string(main->Config(), section, value, - QT_TO_UTF8(str)); + config_set_string(main->Config(), section, value, QT_TO_UTF8(str)); } } -void OBSBasicSettings::SaveCheckBox(QAbstractButton *widget, - const char *section, const char *value, - bool invert) +void OBSBasicSettings::SaveCheckBox(QAbstractButton *widget, const char *section, const char *value, bool invert) { if (WidgetChanged(widget)) { bool checked = widget->isChecked(); @@ -1068,23 +959,19 @@ void OBSBasicSettings::SaveCheckBox(QAbstractButton *widget, } } -void OBSBasicSettings::SaveEdit(QLineEdit *widget, const char *section, - const char *value) +void OBSBasicSettings::SaveEdit(QLineEdit *widget, const char *section, const char *value) { if (WidgetChanged(widget)) - config_set_string(main->Config(), section, value, - QT_TO_UTF8(widget->text())); + config_set_string(main->Config(), section, value, QT_TO_UTF8(widget->text())); } -void OBSBasicSettings::SaveSpinBox(QSpinBox *widget, const char *section, - const char *value) +void OBSBasicSettings::SaveSpinBox(QSpinBox *widget, const char *section, const char *value) { if (WidgetChanged(widget)) config_set_int(main->Config(), section, value, widget->value()); } -void OBSBasicSettings::SaveText(QPlainTextEdit *widget, const char *section, - const char *value) +void OBSBasicSettings::SaveText(QPlainTextEdit *widget, const char *section, const char *value) { if (!WidgetChanged(widget)) return; @@ -1094,8 +981,7 @@ void OBSBasicSettings::SaveText(QPlainTextEdit *widget, const char *section, OBSDataAutoRelease safe_text = obs_data_create(); obs_data_set_string(safe_text, "text", utf8.constData()); - config_set_string(main->Config(), section, value, - obs_data_get_json(safe_text)); + config_set_string(main->Config(), section, value, obs_data_get_json(safe_text)); } std::string DeserializeConfigText(const char *value) @@ -1104,12 +990,10 @@ std::string DeserializeConfigText(const char *value) return obs_data_get_string(data, "text"); } -void OBSBasicSettings::SaveGroupBox(QGroupBox *widget, const char *section, - const char *value) +void OBSBasicSettings::SaveGroupBox(QGroupBox *widget, const char *section, const char *value) { if (WidgetChanged(widget)) - config_set_bool(main->Config(), section, value, - widget->isChecked()); + config_set_bool(main->Config(), section, value, widget->isChecked()); } #define CS_PARTIAL_STR QTStr("Basic.Settings.Advanced.Video.ColorRange.Partial") @@ -1157,8 +1041,7 @@ void OBSBasicSettings::LoadColorFormats() ui->colorFormat->addItem(CF_BGRA_STR, "RGB"); // Avoid config break } -#define AV_FORMAT_DEFAULT_STR \ - QTStr("Basic.Settings.Output.Adv.FFmpeg.FormatDefault") +#define AV_FORMAT_DEFAULT_STR QTStr("Basic.Settings.Output.Adv.FFmpeg.FormatDefault") #define AUDIO_STR QTStr("Basic.Settings.Output.Adv.FFmpeg.FormatAudio") #define VIDEO_STR QTStr("Basic.Settings.Output.Adv.FFmpeg.FormatVideo") @@ -1176,11 +1059,9 @@ void OBSBasicSettings::LoadFormats() if (audio || video) { QString itemText(format.name); if (audio ^ video) - itemText += QString(" (%1)").arg( - audio ? AUDIO_STR : VIDEO_STR); + itemText += QString(" (%1)").arg(audio ? AUDIO_STR : VIDEO_STR); - ui->advOutFFFormat->addItem( - itemText, QVariant::fromValue(format)); + ui->advOutFFFormat->addItem(itemText, QVariant::fromValue(format)); } } @@ -1223,11 +1104,9 @@ static void AddCodec(QComboBox *combo, const FFmpegCodec &codec) combo->addItem(itemText, QVariant::fromValue(codec)); } -#define AV_ENCODER_DEFAULT_STR \ - QTStr("Basic.Settings.Output.Adv.FFmpeg.AVEncoderDefault") +#define AV_ENCODER_DEFAULT_STR QTStr("Basic.Settings.Output.Adv.FFmpeg.AVEncoderDefault") -static void AddDefaultCodec(QComboBox *combo, const FFmpegFormat &format, - FFmpegCodecType codecType) +static void AddDefaultCodec(QComboBox *combo, const FFmpegFormat &format, FFmpegCodecType codecType) { FFmpegCodec codec = format.GetDefaultEncoder(codecType); @@ -1237,19 +1116,15 @@ static void AddDefaultCodec(QComboBox *combo, const FFmpegFormat &format, QString itemText; if (codec.long_name) { - itemText = QString("%1 - %2 (%3)") - .arg(codec.name, codec.long_name, - AV_ENCODER_DEFAULT_STR); + itemText = QString("%1 - %2 (%3)").arg(codec.name, codec.long_name, AV_ENCODER_DEFAULT_STR); } else { - itemText = QString("%1 (%2)").arg(codec.name, - AV_ENCODER_DEFAULT_STR); + itemText = QString("%1 (%2)").arg(codec.name, AV_ENCODER_DEFAULT_STR); } combo->addItem(itemText, QVariant::fromValue(codec)); } -#define AV_ENCODER_DISABLE_STR \ - QTStr("Basic.Settings.Output.Adv.FFmpeg.AVEncoderDisable") +#define AV_ENCODER_DISABLE_STR QTStr("Basic.Settings.Output.Adv.FFmpeg.AVEncoderDisable") void OBSBasicSettings::ReloadCodecs(const FFmpegFormat &format) { @@ -1259,8 +1134,7 @@ void OBSBasicSettings::ReloadCodecs(const FFmpegFormat &format) ui->advOutFFVEncoder->clear(); bool ignore_compatibility = ui->advOutFFIgnoreCompat->isChecked(); - vector supportedCodecs = - GetFormatCodecs(format, ignore_compatibility); + vector supportedCodecs = GetFormatCodecs(format, ignore_compatibility); for (auto &codec : supportedCodecs) { switch (codec.type) { @@ -1276,11 +1150,9 @@ void OBSBasicSettings::ReloadCodecs(const FFmpegFormat &format) } if (format.HasAudio()) - AddDefaultCodec(ui->advOutFFAEncoder, format, - FFmpegCodecType::AUDIO); + AddDefaultCodec(ui->advOutFFAEncoder, format, FFmpegCodecType::AUDIO); if (format.HasVideo()) - AddDefaultCodec(ui->advOutFFVEncoder, format, - FFmpegCodecType::VIDEO); + AddDefaultCodec(ui->advOutFFVEncoder, format, FFmpegCodecType::VIDEO); ui->advOutFFAEncoder->model()->sort(0); ui->advOutFFVEncoder->model()->sort(0); @@ -1303,8 +1175,7 @@ void OBSBasicSettings::LoadLanguageList() for (const auto &locale : GetLocaleNames()) { int idx = ui->language->count(); - ui->language->addItem(QT_UTF8(locale.second.c_str()), - QT_UTF8(locale.first.c_str())); + ui->language->addItem(QT_UTF8(locale.second.c_str()), QT_UTF8(locale.first.c_str())); if (locale.first == currentLang) ui->language->setCurrentIndex(idx); @@ -1314,13 +1185,10 @@ void OBSBasicSettings::LoadLanguageList() } #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) -void TranslateBranchInfo(const QString &name, QString &displayName, - QString &description) +void TranslateBranchInfo(const QString &name, QString &displayName, QString &description) { - QString translatedName = - QTStr("Basic.Settings.General.ChannelName." + name.toUtf8()); - QString translatedDesc = QTStr( - "Basic.Settings.General.ChannelDescription." + name.toUtf8()); + QString translatedName = QTStr("Basic.Settings.General.ChannelName." + name.toUtf8()); + QString translatedDesc = QTStr("Basic.Settings.General.ChannelDescription." + name.toUtf8()); if (!translatedName.startsWith("Basic.Settings.")) displayName = translatedName; @@ -1333,8 +1201,7 @@ void OBSBasicSettings::LoadBranchesList() { #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) bool configBranchRemoved = true; - QString configBranch = config_get_string(App()->GetAppConfig(), - "General", "UpdateBranch"); + QString configBranch = config_get_string(App()->GetAppConfig(), "General", "UpdateBranch"); for (const UpdateBranch &branch : App()->GetBranches()) { if (branch.name == configBranch) @@ -1350,23 +1217,18 @@ void OBSBasicSettings::LoadBranchesList() if (!branch.is_enabled) { itemDesc.prepend(" "); - itemDesc.prepend(QTStr( - "Basic.Settings.General.UpdateChannelDisabled")); + itemDesc.prepend(QTStr("Basic.Settings.General.UpdateChannelDisabled")); } else if (branch.name == "stable") { itemDesc.append(" "); - itemDesc.append(QTStr( - "Basic.Settings.General.UpdateChannelDefault")); + itemDesc.append(QTStr("Basic.Settings.General.UpdateChannelDefault")); } ui->updateChannelBox->addItem(itemDesc, branch.name); // Disable item if branch is disabled if (!branch.is_enabled) { - QStandardItemModel *model = - dynamic_cast( - ui->updateChannelBox->model()); - QStandardItem *item = - model->item(ui->updateChannelBox->count() - 1); + QStandardItemModel *model = dynamic_cast(ui->updateChannelBox->model()); + QStandardItem *item = model->item(ui->updateChannelBox->count() - 1); item->setFlags(Qt::NoItemFlags); } } @@ -1387,26 +1249,23 @@ void OBSBasicSettings::LoadGeneralSettings() LoadLanguageList(); #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) - bool enableAutoUpdates = config_get_bool( - App()->GetUserConfig(), "General", "EnableAutoUpdates"); + bool enableAutoUpdates = config_get_bool(App()->GetUserConfig(), "General", "EnableAutoUpdates"); ui->enableAutoUpdates->setChecked(enableAutoUpdates); LoadBranchesList(); #endif - bool openStatsOnStartup = config_get_bool(main->Config(), "General", - "OpenStatsOnStartup"); + bool openStatsOnStartup = config_get_bool(main->Config(), "General", "OpenStatsOnStartup"); ui->openStatsOnStartup->setChecked(openStatsOnStartup); #if defined(_WIN32) if (ui->hideOBSFromCapture) { bool hideWindowFromCapture = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "HideOBSWindowsFromCapture"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "HideOBSWindowsFromCapture"); ui->hideOBSFromCapture->setChecked(hideWindowFromCapture); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - connect(ui->hideOBSFromCapture, &QCheckBox::checkStateChanged, - this, &OBSBasicSettings::HideOBSWindowWarning); + connect(ui->hideOBSFromCapture, &QCheckBox::checkStateChanged, this, + &OBSBasicSettings::HideOBSWindowWarning); #else connect(ui->hideOBSFromCapture, &QCheckBox::stateChanged, this, &OBSBasicSettings::HideOBSWindowWarning); @@ -1414,174 +1273,125 @@ void OBSBasicSettings::LoadGeneralSettings() } #endif - bool recordWhenStreaming = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); + bool recordWhenStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); ui->recordWhenStreaming->setChecked(recordWhenStreaming); bool keepRecordStreamStops = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "KeepRecordingWhenStreamStops"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops"); ui->keepRecordStreamStops->setChecked(keepRecordStreamStops); bool replayWhileStreaming = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ReplayBufferWhileStreaming"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); ui->replayWhileStreaming->setChecked(replayWhileStreaming); bool keepReplayStreamStops = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "KeepReplayBufferStreamStops"); + config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops"); ui->keepReplayStreamStops->setChecked(keepReplayStreamStops); - bool systemTrayEnabled = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled"); + bool systemTrayEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled"); ui->systemTrayEnabled->setChecked(systemTrayEnabled); - bool systemTrayWhenStarted = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); + bool systemTrayWhenStarted = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); ui->systemTrayWhenStarted->setChecked(systemTrayWhenStarted); - bool systemTrayAlways = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SysTrayMinimizeToTray"); + bool systemTrayAlways = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayMinimizeToTray"); ui->systemTrayAlways->setChecked(systemTrayAlways); - bool saveProjectors = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "SaveProjectors"); + bool saveProjectors = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SaveProjectors"); ui->saveProjectors->setChecked(saveProjectors); - bool closeProjectors = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "CloseExistingProjectors"); + bool closeProjectors = config_get_bool(App()->GetUserConfig(), "BasicWindow", "CloseExistingProjectors"); ui->closeProjectors->setChecked(closeProjectors); - bool snappingEnabled = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SnappingEnabled"); + bool snappingEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled"); ui->snappingEnabled->setChecked(snappingEnabled); - bool screenSnapping = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "ScreenSnapping"); + bool screenSnapping = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ScreenSnapping"); ui->screenSnapping->setChecked(screenSnapping); - bool centerSnapping = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "CenterSnapping"); + bool centerSnapping = config_get_bool(App()->GetUserConfig(), "BasicWindow", "CenterSnapping"); ui->centerSnapping->setChecked(centerSnapping); - bool sourceSnapping = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "SourceSnapping"); + bool sourceSnapping = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SourceSnapping"); ui->sourceSnapping->setChecked(sourceSnapping); - double snapDistance = config_get_double(App()->GetUserConfig(), - "BasicWindow", "SnapDistance"); + double snapDistance = config_get_double(App()->GetUserConfig(), "BasicWindow", "SnapDistance"); ui->snapDistance->setValue(snapDistance); - bool warnBeforeStreamStart = - config_get_bool(App()->GetUserConfig(), "BasicWindow", - "WarnBeforeStartingStream"); + bool warnBeforeStreamStart = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStartingStream"); ui->warnBeforeStreamStart->setChecked(warnBeforeStreamStart); - bool spacingHelpersEnabled = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "SpacingHelpersEnabled"); + bool spacingHelpersEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SpacingHelpersEnabled"); ui->previewSpacingHelpers->setChecked(spacingHelpersEnabled); - bool warnBeforeStreamStop = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "WarnBeforeStoppingStream"); + bool warnBeforeStreamStop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingStream"); ui->warnBeforeStreamStop->setChecked(warnBeforeStreamStop); - bool warnBeforeRecordStop = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "WarnBeforeStoppingRecord"); + bool warnBeforeRecordStop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingRecord"); ui->warnBeforeRecordStop->setChecked(warnBeforeRecordStop); - bool hideProjectorCursor = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "HideProjectorCursor"); + bool hideProjectorCursor = config_get_bool(App()->GetUserConfig(), "BasicWindow", "HideProjectorCursor"); ui->hideProjectorCursor->setChecked(hideProjectorCursor); - bool projectorAlwaysOnTop = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "ProjectorAlwaysOnTop"); + bool projectorAlwaysOnTop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ProjectorAlwaysOnTop"); ui->projectorAlwaysOnTop->setChecked(projectorAlwaysOnTop); - bool overflowHide = config_get_bool(App()->GetUserConfig(), - "BasicWindow", "OverflowHidden"); + bool overflowHide = config_get_bool(App()->GetUserConfig(), "BasicWindow", "OverflowHidden"); ui->overflowHide->setChecked(overflowHide); - bool overflowAlwaysVisible = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "OverflowAlwaysVisible"); + bool overflowAlwaysVisible = config_get_bool(App()->GetUserConfig(), "BasicWindow", "OverflowAlwaysVisible"); ui->overflowAlwaysVisible->setChecked(overflowAlwaysVisible); - bool overflowSelectionHide = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "OverflowSelectionHidden"); + bool overflowSelectionHide = config_get_bool(App()->GetUserConfig(), "BasicWindow", "OverflowSelectionHidden"); ui->overflowSelectionHide->setChecked(overflowSelectionHide); - bool safeAreas = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ShowSafeAreas"); + bool safeAreas = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ShowSafeAreas"); ui->previewSafeAreas->setChecked(safeAreas); - bool automaticSearch = config_get_bool( - App()->GetUserConfig(), "General", "AutomaticCollectionSearch"); + bool automaticSearch = config_get_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch"); ui->automaticSearch->setChecked(automaticSearch); - bool doubleClickSwitch = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "TransitionOnDoubleClick"); + bool doubleClickSwitch = config_get_bool(App()->GetUserConfig(), "BasicWindow", "TransitionOnDoubleClick"); ui->doubleClickSwitch->setChecked(doubleClickSwitch); - bool studioPortraitLayout = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "StudioPortraitLayout"); + bool studioPortraitLayout = config_get_bool(App()->GetUserConfig(), "BasicWindow", "StudioPortraitLayout"); ui->studioPortraitLayout->setChecked(studioPortraitLayout); - bool prevProgLabels = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "StudioModeLabels"); + bool prevProgLabels = config_get_bool(App()->GetUserConfig(), "BasicWindow", "StudioModeLabels"); ui->prevProgLabelToggle->setChecked(prevProgLabels); - bool multiviewMouseSwitch = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "MultiviewMouseSwitch"); + bool multiviewMouseSwitch = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewMouseSwitch"); ui->multiviewMouseSwitch->setChecked(multiviewMouseSwitch); - bool multiviewDrawNames = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "MultiviewDrawNames"); + bool multiviewDrawNames = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewDrawNames"); ui->multiviewDrawNames->setChecked(multiviewDrawNames); - bool multiviewDrawAreas = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "MultiviewDrawAreas"); + bool multiviewDrawAreas = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewDrawAreas"); ui->multiviewDrawAreas->setChecked(multiviewDrawAreas); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.Top"), - static_cast(MultiviewLayout::HORIZONTAL_TOP_8_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.Bottom"), - static_cast(MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.Vertical.Left"), - static_cast(MultiviewLayout::VERTICAL_LEFT_8_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.Vertical.Right"), - static_cast(MultiviewLayout::VERTICAL_RIGHT_8_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.18Scene.Top"), - static_cast(MultiviewLayout::HORIZONTAL_TOP_18_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.Extended.Top"), - static_cast(MultiviewLayout::HORIZONTAL_TOP_24_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.4Scene"), - static_cast(MultiviewLayout::SCENES_ONLY_4_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.9Scene"), - static_cast(MultiviewLayout::SCENES_ONLY_9_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.16Scene"), - static_cast(MultiviewLayout::SCENES_ONLY_16_SCENES)); - ui->multiviewLayout->addItem( - QTStr("Basic.Settings.General.MultiviewLayout.25Scene"), - static_cast(MultiviewLayout::SCENES_ONLY_25_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.Top"), + static_cast(MultiviewLayout::HORIZONTAL_TOP_8_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.Bottom"), + static_cast(MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.Vertical.Left"), + static_cast(MultiviewLayout::VERTICAL_LEFT_8_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.Vertical.Right"), + static_cast(MultiviewLayout::VERTICAL_RIGHT_8_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.18Scene.Top"), + static_cast(MultiviewLayout::HORIZONTAL_TOP_18_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.Horizontal.Extended.Top"), + static_cast(MultiviewLayout::HORIZONTAL_TOP_24_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.4Scene"), + static_cast(MultiviewLayout::SCENES_ONLY_4_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.9Scene"), + static_cast(MultiviewLayout::SCENES_ONLY_9_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.16Scene"), + static_cast(MultiviewLayout::SCENES_ONLY_16_SCENES)); + ui->multiviewLayout->addItem(QTStr("Basic.Settings.General.MultiviewLayout.25Scene"), + static_cast(MultiviewLayout::SCENES_ONLY_25_SCENES)); - ui->multiviewLayout->setCurrentIndex( - ui->multiviewLayout->findData(QVariant::fromValue( - config_get_int(App()->GetUserConfig(), "BasicWindow", - "MultiviewLayout")))); + ui->multiviewLayout->setCurrentIndex(ui->multiviewLayout->findData( + QVariant::fromValue(config_get_int(App()->GetUserConfig(), "BasicWindow", "MultiviewLayout")))); prevLangIndex = ui->language->currentIndex(); @@ -1594,8 +1404,7 @@ void OBSBasicSettings::LoadGeneralSettings() void OBSBasicSettings::LoadRendererList() { #ifdef _WIN32 - const char *renderer = - config_get_string(App()->GetAppConfig(), "Video", "Renderer"); + const char *renderer = config_get_string(App()->GetAppConfig(), "Video", "Renderer"); ui->renderer->addItem(QT_UTF8("Direct3D 11")); if (opt_allow_opengl || strcmp(renderer, "OpenGL") == 0) @@ -1625,13 +1434,11 @@ static string ResString(uint32_t cx, uint32_t cy) } /* some nice default output resolution vals */ -static const double vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, (1.0 / 0.6), 1.75, - 2.0, 2.25, 2.5, 2.75, 3.0}; +static const double vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, (1.0 / 0.6), 1.75, 2.0, 2.25, 2.5, 2.75, 3.0}; static const size_t numVals = sizeof(vals) / sizeof(double); -void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, - bool ignoreAllSignals) +void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, bool ignoreAllSignals) { QString advRescale; QString advRecRescale; @@ -1666,8 +1473,7 @@ void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, out_cy = cy; oldOutputRes = ui->baseResolution->lineEdit()->text(); } else { - oldOutputRes = - QString::number(out_cx) + "x" + QString::number(out_cy); + oldOutputRes = QString::number(out_cx) + "x" + QString::number(out_cy); } for (size_t idx = 0; idx < numVals; idx++) { @@ -1712,16 +1518,14 @@ void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, ui->outputResolution->lineEdit()->setText(oldOutputRes); on_outputResolution_editTextChanged(oldOutputRes); } else { - ui->outputResolution->lineEdit()->setText( - bestScale.c_str()); + ui->outputResolution->lineEdit()->setText(bestScale.c_str()); on_outputResolution_editTextChanged(bestScale.c_str()); } ui->outputResolution->blockSignals(false); if (!closeAspect) { - ui->outputResolution->setProperty("changed", - QVariant(true)); + ui->outputResolution->setProperty("changed", QVariant(true)); videoChanged = true; } } @@ -1748,30 +1552,20 @@ void OBSBasicSettings::LoadDownscaleFilters() { QString downscaleFilter = ui->downscaleFilter->currentData().toString(); if (downscaleFilter.isEmpty()) - downscaleFilter = - config_get_string(main->Config(), "Video", "ScaleType"); + downscaleFilter = config_get_string(main->Config(), "Video", "ScaleType"); ui->downscaleFilter->clear(); - if (ui->baseResolution->currentText() == - ui->outputResolution->currentText()) { + if (ui->baseResolution->currentText() == ui->outputResolution->currentText()) { ui->downscaleFilter->setEnabled(false); - ui->downscaleFilter->addItem( - QTStr("Basic.Settings.Video.DownscaleFilter.Unavailable"), - downscaleFilter); + ui->downscaleFilter->addItem(QTStr("Basic.Settings.Video.DownscaleFilter.Unavailable"), + downscaleFilter); } else { ui->downscaleFilter->setEnabled(true); - ui->downscaleFilter->addItem( - QTStr("Basic.Settings.Video.DownscaleFilter.Bilinear"), - QT_UTF8("bilinear")); - ui->downscaleFilter->addItem( - QTStr("Basic.Settings.Video.DownscaleFilter.Area"), - QT_UTF8("area")); - ui->downscaleFilter->addItem( - QTStr("Basic.Settings.Video.DownscaleFilter.Bicubic"), - QT_UTF8("bicubic")); - ui->downscaleFilter->addItem( - QTStr("Basic.Settings.Video.DownscaleFilter.Lanczos"), - QT_UTF8("lanczos")); + ui->downscaleFilter->addItem(QTStr("Basic.Settings.Video.DownscaleFilter.Bilinear"), + QT_UTF8("bilinear")); + ui->downscaleFilter->addItem(QTStr("Basic.Settings.Video.DownscaleFilter.Area"), QT_UTF8("area")); + ui->downscaleFilter->addItem(QTStr("Basic.Settings.Video.DownscaleFilter.Bicubic"), QT_UTF8("bicubic")); + ui->downscaleFilter->addItem(QTStr("Basic.Settings.Video.DownscaleFilter.Lanczos"), QT_UTF8("lanczos")); if (downscaleFilter == "bilinear") ui->downscaleFilter->setCurrentIndex(0); @@ -1827,15 +1621,12 @@ void OBSBasicSettings::LoadResolutionLists() std::tuple aspect = aspect_ratio(cx, cy); ui->baseAspect->setText( - QTStr("AspectRatio") - .arg(QString::number(std::get<0>(aspect)), - QString::number(std::get<1>(aspect)))); + QTStr("AspectRatio").arg(QString::number(std::get<0>(aspect)), QString::number(std::get<1>(aspect)))); } static inline void LoadFPSCommon(OBSBasic *main, Ui::OBSBasicSettings *ui) { - const char *val = - config_get_string(main->Config(), "Video", "FPSCommon"); + const char *val = config_get_string(main->Config(), "Video", "FPSCommon"); int idx = ui->fpsCommon->findText(val); if (idx == -1) @@ -1878,8 +1669,7 @@ void OBSBasicSettings::LoadVideoSettings() if (obs_video_active()) { ui->videoPage->setEnabled(false); - ui->videoMsg->setText( - QTStr("Basic.Settings.Video.CurrentlyActive")); + ui->videoMsg->setText(QTStr("Basic.Settings.Video.CurrentlyActive")); } LoadResolutionLists(); @@ -1891,8 +1681,7 @@ void OBSBasicSettings::LoadVideoSettings() static inline bool IsSurround(const char *speakers) { - static const char *surroundLayouts[] = {"2.1", "4.0", "4.1", - "5.1", "7.1", nullptr}; + static const char *surroundLayouts[] = {"2.1", "4.0", "4.1", "5.1", "7.1", nullptr}; if (!speakers || !*speakers) return false; @@ -1909,50 +1698,28 @@ static inline bool IsSurround(const char *speakers) void OBSBasicSettings::LoadSimpleOutputSettings() { - const char *path = - config_get_string(main->Config(), "SimpleOutput", "FilePath"); - bool noSpace = config_get_bool(main->Config(), "SimpleOutput", - "FileNameWithoutSpace"); - const char *format = - config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); - int videoBitrate = - config_get_uint(main->Config(), "SimpleOutput", "VBitrate"); - const char *streamEnc = config_get_string( - main->Config(), "SimpleOutput", "StreamEncoder"); - const char *streamAudioEnc = config_get_string( - main->Config(), "SimpleOutput", "StreamAudioEncoder"); - int audioBitrate = - config_get_uint(main->Config(), "SimpleOutput", "ABitrate"); - bool advanced = - config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced"); - const char *preset = - config_get_string(main->Config(), "SimpleOutput", "Preset"); - const char *qsvPreset = - config_get_string(main->Config(), "SimpleOutput", "QSVPreset"); - const char *nvPreset = config_get_string(main->Config(), "SimpleOutput", - "NVENCPreset2"); - const char *amdPreset = - config_get_string(main->Config(), "SimpleOutput", "AMDPreset"); - const char *amdAV1Preset = config_get_string( - main->Config(), "SimpleOutput", "AMDAV1Preset"); - const char *custom = config_get_string(main->Config(), "SimpleOutput", - "x264Settings"); - const char *recQual = - config_get_string(main->Config(), "SimpleOutput", "RecQuality"); - const char *recEnc = - config_get_string(main->Config(), "SimpleOutput", "RecEncoder"); - const char *recAudioEnc = config_get_string( - main->Config(), "SimpleOutput", "RecAudioEncoder"); - const char *muxCustom = config_get_string( - main->Config(), "SimpleOutput", "MuxerCustom"); - bool replayBuf = - config_get_bool(main->Config(), "SimpleOutput", "RecRB"); - int rbTime = - config_get_int(main->Config(), "SimpleOutput", "RecRBTime"); - int rbSize = - config_get_int(main->Config(), "SimpleOutput", "RecRBSize"); - int tracks = - config_get_int(main->Config(), "SimpleOutput", "RecTracks"); + const char *path = config_get_string(main->Config(), "SimpleOutput", "FilePath"); + bool noSpace = config_get_bool(main->Config(), "SimpleOutput", "FileNameWithoutSpace"); + const char *format = config_get_string(main->Config(), "SimpleOutput", "RecFormat2"); + int videoBitrate = config_get_uint(main->Config(), "SimpleOutput", "VBitrate"); + const char *streamEnc = config_get_string(main->Config(), "SimpleOutput", "StreamEncoder"); + const char *streamAudioEnc = config_get_string(main->Config(), "SimpleOutput", "StreamAudioEncoder"); + int audioBitrate = config_get_uint(main->Config(), "SimpleOutput", "ABitrate"); + bool advanced = config_get_bool(main->Config(), "SimpleOutput", "UseAdvanced"); + const char *preset = config_get_string(main->Config(), "SimpleOutput", "Preset"); + const char *qsvPreset = config_get_string(main->Config(), "SimpleOutput", "QSVPreset"); + const char *nvPreset = config_get_string(main->Config(), "SimpleOutput", "NVENCPreset2"); + const char *amdPreset = config_get_string(main->Config(), "SimpleOutput", "AMDPreset"); + const char *amdAV1Preset = config_get_string(main->Config(), "SimpleOutput", "AMDAV1Preset"); + const char *custom = config_get_string(main->Config(), "SimpleOutput", "x264Settings"); + const char *recQual = config_get_string(main->Config(), "SimpleOutput", "RecQuality"); + const char *recEnc = config_get_string(main->Config(), "SimpleOutput", "RecEncoder"); + const char *recAudioEnc = config_get_string(main->Config(), "SimpleOutput", "RecAudioEncoder"); + const char *muxCustom = config_get_string(main->Config(), "SimpleOutput", "MuxerCustom"); + bool replayBuf = config_get_bool(main->Config(), "SimpleOutput", "RecRB"); + int rbTime = config_get_int(main->Config(), "SimpleOutput", "RecRBTime"); + int rbSize = config_get_int(main->Config(), "SimpleOutput", "RecRBSize"); + int tracks = config_get_int(main->Config(), "SimpleOutput", "RecTracks"); ui->simpleOutRecTrack1->setChecked(tracks & (1 << 0)); ui->simpleOutRecTrack2->setChecked(tracks & (1 << 1)); @@ -1968,9 +1735,8 @@ void OBSBasicSettings::LoadSimpleOutputSettings() curAMDAV1Preset = amdAV1Preset; bool isOpus = strcmp(streamAudioEnc, "opus") == 0; - audioBitrate = - isOpus ? FindClosestAvailableSimpleOpusBitrate(audioBitrate) - : FindClosestAvailableSimpleAACBitrate(audioBitrate); + audioBitrate = isOpus ? FindClosestAvailableSimpleOpusBitrate(audioBitrate) + : FindClosestAvailableSimpleAACBitrate(audioBitrate); ui->simpleOutputPath->setText(path); ui->simpleNoSpace->setChecked(noSpace); @@ -1981,15 +1747,13 @@ void OBSBasicSettings::LoadSimpleOutputSettings() PopulateSimpleBitrates(ui->simpleOutputABitrate, isOpus); - const char *speakers = - config_get_string(main->Config(), "Audio", "ChannelSetup"); + const char *speakers = config_get_string(main->Config(), "Audio", "ChannelSetup"); // restrict list of bitrates when multichannel is OFF if (!IsSurround(speakers)) RestrictResetBitrates({ui->simpleOutputABitrate}, 320); - SetComboByName(ui->simpleOutputABitrate, - std::to_string(audioBitrate).c_str()); + SetComboByName(ui->simpleOutputABitrate, std::to_string(audioBitrate).c_str()); ui->simpleOutAdvanced->setChecked(advanced); ui->simpleOutCustom->setText(custom); @@ -2027,34 +1791,20 @@ void OBSBasicSettings::LoadSimpleOutputSettings() static inline QString makeFormatToolTip() { static const char *format_list[][2] = { - {"CCYY", "FilenameFormatting.TT.CCYY"}, - {"YY", "FilenameFormatting.TT.YY"}, - {"MM", "FilenameFormatting.TT.MM"}, - {"DD", "FilenameFormatting.TT.DD"}, - {"hh", "FilenameFormatting.TT.hh"}, - {"mm", "FilenameFormatting.TT.mm"}, - {"ss", "FilenameFormatting.TT.ss"}, - {"%", "FilenameFormatting.TT.Percent"}, - {"a", "FilenameFormatting.TT.a"}, - {"A", "FilenameFormatting.TT.A"}, - {"b", "FilenameFormatting.TT.b"}, - {"B", "FilenameFormatting.TT.B"}, - {"d", "FilenameFormatting.TT.d"}, - {"H", "FilenameFormatting.TT.H"}, - {"I", "FilenameFormatting.TT.I"}, - {"m", "FilenameFormatting.TT.m"}, - {"M", "FilenameFormatting.TT.M"}, - {"p", "FilenameFormatting.TT.p"}, - {"s", "FilenameFormatting.TT.s"}, - {"S", "FilenameFormatting.TT.S"}, - {"y", "FilenameFormatting.TT.y"}, - {"Y", "FilenameFormatting.TT.Y"}, - {"z", "FilenameFormatting.TT.z"}, - {"Z", "FilenameFormatting.TT.Z"}, - {"FPS", "FilenameFormatting.TT.FPS"}, - {"CRES", "FilenameFormatting.TT.CRES"}, - {"ORES", "FilenameFormatting.TT.ORES"}, - {"VF", "FilenameFormatting.TT.VF"}, + {"CCYY", "FilenameFormatting.TT.CCYY"}, {"YY", "FilenameFormatting.TT.YY"}, + {"MM", "FilenameFormatting.TT.MM"}, {"DD", "FilenameFormatting.TT.DD"}, + {"hh", "FilenameFormatting.TT.hh"}, {"mm", "FilenameFormatting.TT.mm"}, + {"ss", "FilenameFormatting.TT.ss"}, {"%", "FilenameFormatting.TT.Percent"}, + {"a", "FilenameFormatting.TT.a"}, {"A", "FilenameFormatting.TT.A"}, + {"b", "FilenameFormatting.TT.b"}, {"B", "FilenameFormatting.TT.B"}, + {"d", "FilenameFormatting.TT.d"}, {"H", "FilenameFormatting.TT.H"}, + {"I", "FilenameFormatting.TT.I"}, {"m", "FilenameFormatting.TT.m"}, + {"M", "FilenameFormatting.TT.M"}, {"p", "FilenameFormatting.TT.p"}, + {"s", "FilenameFormatting.TT.s"}, {"S", "FilenameFormatting.TT.S"}, + {"y", "FilenameFormatting.TT.y"}, {"Y", "FilenameFormatting.TT.Y"}, + {"z", "FilenameFormatting.TT.z"}, {"Z", "FilenameFormatting.TT.Z"}, + {"FPS", "FilenameFormatting.TT.FPS"}, {"CRES", "FilenameFormatting.TT.CRES"}, + {"ORES", "FilenameFormatting.TT.ORES"}, {"VF", "FilenameFormatting.TT.VF"}, }; QString html = ""; @@ -2073,13 +1823,10 @@ static inline QString makeFormatToolTip() void OBSBasicSettings::LoadAdvOutputStreamingSettings() { - const char *rescaleRes = - config_get_string(main->Config(), "AdvOut", "RescaleRes"); - int rescaleFilter = - config_get_int(main->Config(), "AdvOut", "RescaleFilter"); + const char *rescaleRes = config_get_string(main->Config(), "AdvOut", "RescaleRes"); + int rescaleFilter = config_get_int(main->Config(), "AdvOut", "RescaleFilter"); int trackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex"); - int audioMixes = config_get_int(main->Config(), "AdvOut", - "StreamMultiTrackAudioMixes"); + int audioMixes = config_get_int(main->Config(), "AdvOut", "StreamMultiTrackAudioMixes"); ui->advOutRescale->setEnabled(rescaleFilter != OBS_SCALE_DISABLE); ui->advOutRescale->setCurrentText(rescaleRes); @@ -2087,8 +1834,7 @@ void OBSBasicSettings::LoadAdvOutputStreamingSettings() if (idx != -1) ui->advOutRescaleFilter->setCurrentIndex(idx); - QStringList specList = QTStr("FilenameFormatting.completer") - .split(QRegularExpression("\n")); + QStringList specList = QTStr("FilenameFormatting.completer").split(QRegularExpression("\n")); QCompleter *specCompleter = new QCompleter(specList); specCompleter->setCaseSensitivity(Qt::CaseSensitive); specCompleter->setFilterMode(Qt::MatchContains); @@ -2128,71 +1874,57 @@ void OBSBasicSettings::LoadAdvOutputStreamingSettings() SwapMultiTrack(protocol); } -OBSPropertiesView * -OBSBasicSettings::CreateEncoderPropertyView(const char *encoder, - const char *path, bool changed) +OBSPropertiesView *OBSBasicSettings::CreateEncoderPropertyView(const char *encoder, const char *path, bool changed) { OBSDataAutoRelease settings = obs_encoder_defaults(encoder); OBSPropertiesView *view; if (path) { - const OBSBasic *basic = - reinterpret_cast(App()->GetMainWindow()); + const OBSBasic *basic = reinterpret_cast(App()->GetMainWindow()); const OBSProfile ¤tProfile = basic->GetCurrentProfile(); - const std::filesystem::path jsonFilePath = - currentProfile.path / std::filesystem::u8path(path); + const std::filesystem::path jsonFilePath = currentProfile.path / std::filesystem::u8path(path); if (!jsonFilePath.empty()) { - obs_data_t *data = obs_data_create_from_json_file_safe( - jsonFilePath.u8string().c_str(), "bak"); + obs_data_t *data = obs_data_create_from_json_file_safe(jsonFilePath.u8string().c_str(), "bak"); obs_data_apply(settings, data); obs_data_release(data); } } - view = new OBSPropertiesView( - settings.Get(), encoder, - (PropertiesReloadCallback)obs_get_encoder_properties, 170); + view = new OBSPropertiesView(settings.Get(), encoder, (PropertiesReloadCallback)obs_get_encoder_properties, + 170); view->setFrameShape(QFrame::NoFrame); view->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); view->setProperty("changed", QVariant(changed)); view->setScrolling(false); - QObject::connect(view, &OBSPropertiesView::Changed, this, - &OBSBasicSettings::OutputsChanged); + QObject::connect(view, &OBSPropertiesView::Changed, this, &OBSBasicSettings::OutputsChanged); return view; } void OBSBasicSettings::LoadAdvOutputStreamingEncoderProperties() { - const char *type = - config_get_string(main->Config(), "AdvOut", "Encoder"); + const char *type = config_get_string(main->Config(), "AdvOut", "Encoder"); delete streamEncoderProps; - streamEncoderProps = - CreateEncoderPropertyView(type, "streamEncoder.json"); - streamEncoderProps->setSizePolicy(QSizePolicy::Preferred, - QSizePolicy::Minimum); + streamEncoderProps = CreateEncoderPropertyView(type, "streamEncoder.json"); + streamEncoderProps->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); ui->advOutEncoderLayout->addWidget(streamEncoderProps); - connect(streamEncoderProps, &OBSPropertiesView::Changed, this, - &OBSBasicSettings::UpdateStreamDelayEstimate); - connect(streamEncoderProps, &OBSPropertiesView::Changed, this, - &OBSBasicSettings::AdvReplayBufferChanged); + connect(streamEncoderProps, &OBSPropertiesView::Changed, this, &OBSBasicSettings::UpdateStreamDelayEstimate); + connect(streamEncoderProps, &OBSPropertiesView::Changed, this, &OBSBasicSettings::AdvReplayBufferChanged); curAdvStreamEncoder = type; if (!SetComboByValue(ui->advOutEncoder, type)) { uint32_t caps = obs_get_encoder_caps(type); if ((caps & ENCODER_HIDE_FLAGS) != 0) { - QString encName = - QT_UTF8(obs_encoder_get_display_name(type)); + QString encName = QT_UTF8(obs_encoder_get_display_name(type)); if (caps & OBS_ENCODER_CAP_DEPRECATED) encName += " (" + QTStr("Deprecated") + ")"; - ui->advOutEncoder->insertItem(0, encName, - QT_UTF8(type)); + ui->advOutEncoder->insertItem(0, encName, QT_UTF8(type)); SetComboByValue(ui->advOutEncoder, type); } } @@ -2202,30 +1934,19 @@ void OBSBasicSettings::LoadAdvOutputStreamingEncoderProperties() void OBSBasicSettings::LoadAdvOutputRecordingSettings() { - const char *type = - config_get_string(main->Config(), "AdvOut", "RecType"); - const char *format = - config_get_string(main->Config(), "AdvOut", "RecFormat2"); - const char *path = - config_get_string(main->Config(), "AdvOut", "RecFilePath"); - bool noSpace = config_get_bool(main->Config(), "AdvOut", - "RecFileNameWithoutSpace"); - const char *rescaleRes = - config_get_string(main->Config(), "AdvOut", "RecRescaleRes"); - int rescaleFilter = - config_get_int(main->Config(), "AdvOut", "RecRescaleFilter"); - const char *muxCustom = - config_get_string(main->Config(), "AdvOut", "RecMuxerCustom"); + const char *type = config_get_string(main->Config(), "AdvOut", "RecType"); + const char *format = config_get_string(main->Config(), "AdvOut", "RecFormat2"); + const char *path = config_get_string(main->Config(), "AdvOut", "RecFilePath"); + bool noSpace = config_get_bool(main->Config(), "AdvOut", "RecFileNameWithoutSpace"); + const char *rescaleRes = config_get_string(main->Config(), "AdvOut", "RecRescaleRes"); + int rescaleFilter = config_get_int(main->Config(), "AdvOut", "RecRescaleFilter"); + const char *muxCustom = config_get_string(main->Config(), "AdvOut", "RecMuxerCustom"); int tracks = config_get_int(main->Config(), "AdvOut", "RecTracks"); int flvTrack = config_get_int(main->Config(), "AdvOut", "FLVTrack"); - bool splitFile = - config_get_bool(main->Config(), "AdvOut", "RecSplitFile"); - const char *splitFileType = - config_get_string(main->Config(), "AdvOut", "RecSplitFileType"); - int splitFileTime = - config_get_int(main->Config(), "AdvOut", "RecSplitFileTime"); - int splitFileSize = - config_get_int(main->Config(), "AdvOut", "RecSplitFileSize"); + bool splitFile = config_get_bool(main->Config(), "AdvOut", "RecSplitFile"); + const char *splitFileType = config_get_string(main->Config(), "AdvOut", "RecSplitFileType"); + int splitFileTime = config_get_int(main->Config(), "AdvOut", "RecSplitFileTime"); + int splitFileSize = config_get_int(main->Config(), "AdvOut", "RecSplitFileSize"); int typeIndex = (astrcmpi(type, "FFmpeg") == 0) ? 1 : 0; ui->advOutRecType->setCurrentIndex(typeIndex); @@ -2285,19 +2006,15 @@ void OBSBasicSettings::LoadAdvOutputRecordingSettings() void OBSBasicSettings::LoadAdvOutputRecordingEncoderProperties() { - const char *type = - config_get_string(main->Config(), "AdvOut", "RecEncoder"); + const char *type = config_get_string(main->Config(), "AdvOut", "RecEncoder"); delete recordEncoderProps; recordEncoderProps = nullptr; if (astrcmpi(type, "none") != 0) { - recordEncoderProps = - CreateEncoderPropertyView(type, "recordEncoder.json"); - recordEncoderProps->setSizePolicy(QSizePolicy::Preferred, - QSizePolicy::Minimum); - ui->advOutRecEncoderProps->layout()->addWidget( - recordEncoderProps); + recordEncoderProps = CreateEncoderPropertyView(type, "recordEncoder.json"); + recordEncoderProps->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); + ui->advOutRecEncoderProps->layout()->addWidget(recordEncoderProps); connect(recordEncoderProps, &OBSPropertiesView::Changed, this, &OBSBasicSettings::AdvReplayBufferChanged); } @@ -2307,13 +2024,11 @@ void OBSBasicSettings::LoadAdvOutputRecordingEncoderProperties() if (!SetComboByValue(ui->advOutRecEncoder, type)) { uint32_t caps = obs_get_encoder_caps(type); if ((caps & ENCODER_HIDE_FLAGS) != 0) { - QString encName = - QT_UTF8(obs_encoder_get_display_name(type)); + QString encName = QT_UTF8(obs_encoder_get_display_name(type)); if (caps & OBS_ENCODER_CAP_DEPRECATED) encName += " (" + QTStr("Deprecated") + ")"; - ui->advOutRecEncoder->insertItem(1, encName, - QT_UTF8(type)); + ui->advOutRecEncoder->insertItem(1, encName, QT_UTF8(type)); SetComboByValue(ui->advOutRecEncoder, type); } else { ui->advOutRecEncoder->setCurrentIndex(-1); @@ -2321,8 +2036,7 @@ void OBSBasicSettings::LoadAdvOutputRecordingEncoderProperties() } } -static void SelectFormat(QComboBox *combo, const char *name, - const char *mimeType) +static void SelectFormat(QComboBox *combo, const char *name, const char *mimeType) { FFmpegFormat format{name, mimeType}; @@ -2348,43 +2062,26 @@ static void SelectEncoder(QComboBox *combo, const char *name, int id) void OBSBasicSettings::LoadAdvOutputFFmpegSettings() { - bool saveFile = - config_get_bool(main->Config(), "AdvOut", "FFOutputToFile"); - const char *path = - config_get_string(main->Config(), "AdvOut", "FFFilePath"); - bool noSpace = config_get_bool(main->Config(), "AdvOut", - "FFFileNameWithoutSpace"); + bool saveFile = config_get_bool(main->Config(), "AdvOut", "FFOutputToFile"); + const char *path = config_get_string(main->Config(), "AdvOut", "FFFilePath"); + bool noSpace = config_get_bool(main->Config(), "AdvOut", "FFFileNameWithoutSpace"); const char *url = config_get_string(main->Config(), "AdvOut", "FFURL"); - const char *format = - config_get_string(main->Config(), "AdvOut", "FFFormat"); - const char *mimeType = - config_get_string(main->Config(), "AdvOut", "FFFormatMimeType"); - const char *muxCustom = - config_get_string(main->Config(), "AdvOut", "FFMCustom"); - int videoBitrate = - config_get_int(main->Config(), "AdvOut", "FFVBitrate"); + const char *format = config_get_string(main->Config(), "AdvOut", "FFFormat"); + const char *mimeType = config_get_string(main->Config(), "AdvOut", "FFFormatMimeType"); + const char *muxCustom = config_get_string(main->Config(), "AdvOut", "FFMCustom"); + int videoBitrate = config_get_int(main->Config(), "AdvOut", "FFVBitrate"); int gopSize = config_get_int(main->Config(), "AdvOut", "FFVGOPSize"); bool rescale = config_get_bool(main->Config(), "AdvOut", "FFRescale"); - bool codecCompat = - config_get_bool(main->Config(), "AdvOut", "FFIgnoreCompat"); - const char *rescaleRes = - config_get_string(main->Config(), "AdvOut", "FFRescaleRes"); - const char *vEncoder = - config_get_string(main->Config(), "AdvOut", "FFVEncoder"); - int vEncoderId = - config_get_int(main->Config(), "AdvOut", "FFVEncoderId"); - const char *vEncCustom = - config_get_string(main->Config(), "AdvOut", "FFVCustom"); - int audioBitrate = - config_get_int(main->Config(), "AdvOut", "FFABitrate"); - int audioMixes = - config_get_int(main->Config(), "AdvOut", "FFAudioMixes"); - const char *aEncoder = - config_get_string(main->Config(), "AdvOut", "FFAEncoder"); - int aEncoderId = - config_get_int(main->Config(), "AdvOut", "FFAEncoderId"); - const char *aEncCustom = - config_get_string(main->Config(), "AdvOut", "FFACustom"); + bool codecCompat = config_get_bool(main->Config(), "AdvOut", "FFIgnoreCompat"); + const char *rescaleRes = config_get_string(main->Config(), "AdvOut", "FFRescaleRes"); + const char *vEncoder = config_get_string(main->Config(), "AdvOut", "FFVEncoder"); + int vEncoderId = config_get_int(main->Config(), "AdvOut", "FFVEncoderId"); + const char *vEncCustom = config_get_string(main->Config(), "AdvOut", "FFVCustom"); + int audioBitrate = config_get_int(main->Config(), "AdvOut", "FFABitrate"); + int audioMixes = config_get_int(main->Config(), "AdvOut", "FFAudioMixes"); + const char *aEncoder = config_get_string(main->Config(), "AdvOut", "FFAEncoder"); + int aEncoderId = config_get_int(main->Config(), "AdvOut", "FFAEncoderId"); + const char *aEncCustom = config_get_string(main->Config(), "AdvOut", "FFACustom"); ui->advOutFFType->setCurrentIndex(saveFile ? 0 : 1); ui->advOutFFRecPath->setText(QT_UTF8(path)); @@ -2414,82 +2111,49 @@ void OBSBasicSettings::LoadAdvOutputFFmpegSettings() void OBSBasicSettings::LoadAdvOutputAudioSettings() { - int track1Bitrate = - config_get_uint(main->Config(), "AdvOut", "Track1Bitrate"); - int track2Bitrate = - config_get_uint(main->Config(), "AdvOut", "Track2Bitrate"); - int track3Bitrate = - config_get_uint(main->Config(), "AdvOut", "Track3Bitrate"); - int track4Bitrate = - config_get_uint(main->Config(), "AdvOut", "Track4Bitrate"); - int track5Bitrate = - config_get_uint(main->Config(), "AdvOut", "Track5Bitrate"); - int track6Bitrate = - config_get_uint(main->Config(), "AdvOut", "Track6Bitrate"); - const char *name1 = - config_get_string(main->Config(), "AdvOut", "Track1Name"); - const char *name2 = - config_get_string(main->Config(), "AdvOut", "Track2Name"); - const char *name3 = - config_get_string(main->Config(), "AdvOut", "Track3Name"); - const char *name4 = - config_get_string(main->Config(), "AdvOut", "Track4Name"); - const char *name5 = - config_get_string(main->Config(), "AdvOut", "Track5Name"); - const char *name6 = - config_get_string(main->Config(), "AdvOut", "Track6Name"); + int track1Bitrate = config_get_uint(main->Config(), "AdvOut", "Track1Bitrate"); + int track2Bitrate = config_get_uint(main->Config(), "AdvOut", "Track2Bitrate"); + int track3Bitrate = config_get_uint(main->Config(), "AdvOut", "Track3Bitrate"); + int track4Bitrate = config_get_uint(main->Config(), "AdvOut", "Track4Bitrate"); + int track5Bitrate = config_get_uint(main->Config(), "AdvOut", "Track5Bitrate"); + int track6Bitrate = config_get_uint(main->Config(), "AdvOut", "Track6Bitrate"); + const char *name1 = config_get_string(main->Config(), "AdvOut", "Track1Name"); + const char *name2 = config_get_string(main->Config(), "AdvOut", "Track2Name"); + const char *name3 = config_get_string(main->Config(), "AdvOut", "Track3Name"); + const char *name4 = config_get_string(main->Config(), "AdvOut", "Track4Name"); + const char *name5 = config_get_string(main->Config(), "AdvOut", "Track5Name"); + const char *name6 = config_get_string(main->Config(), "AdvOut", "Track6Name"); - const char *encoder_id = - config_get_string(main->Config(), "AdvOut", "AudioEncoder"); - const char *rec_encoder_id = - config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); + const char *encoder_id = config_get_string(main->Config(), "AdvOut", "AudioEncoder"); + const char *rec_encoder_id = config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); - PopulateAdvancedBitrates( - {ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, - ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, - ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, - encoder_id, - strcmp(rec_encoder_id, "none") != 0 ? rec_encoder_id - : encoder_id); + PopulateAdvancedBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, + ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, + encoder_id, strcmp(rec_encoder_id, "none") != 0 ? rec_encoder_id : encoder_id); - track1Bitrate = FindClosestAvailableAudioBitrate( - ui->advOutTrack1Bitrate, track1Bitrate); - track2Bitrate = FindClosestAvailableAudioBitrate( - ui->advOutTrack2Bitrate, track2Bitrate); - track3Bitrate = FindClosestAvailableAudioBitrate( - ui->advOutTrack3Bitrate, track3Bitrate); - track4Bitrate = FindClosestAvailableAudioBitrate( - ui->advOutTrack4Bitrate, track4Bitrate); - track5Bitrate = FindClosestAvailableAudioBitrate( - ui->advOutTrack5Bitrate, track5Bitrate); - track6Bitrate = FindClosestAvailableAudioBitrate( - ui->advOutTrack6Bitrate, track6Bitrate); + track1Bitrate = FindClosestAvailableAudioBitrate(ui->advOutTrack1Bitrate, track1Bitrate); + track2Bitrate = FindClosestAvailableAudioBitrate(ui->advOutTrack2Bitrate, track2Bitrate); + track3Bitrate = FindClosestAvailableAudioBitrate(ui->advOutTrack3Bitrate, track3Bitrate); + track4Bitrate = FindClosestAvailableAudioBitrate(ui->advOutTrack4Bitrate, track4Bitrate); + track5Bitrate = FindClosestAvailableAudioBitrate(ui->advOutTrack5Bitrate, track5Bitrate); + track6Bitrate = FindClosestAvailableAudioBitrate(ui->advOutTrack6Bitrate, track6Bitrate); // restrict list of bitrates when multichannel is OFF - const char *speakers = - config_get_string(main->Config(), "Audio", "ChannelSetup"); + const char *speakers = config_get_string(main->Config(), "Audio", "ChannelSetup"); // restrict list of bitrates when multichannel is OFF if (!IsSurround(speakers)) { - RestrictResetBitrates( - {ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, - ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, - ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, - 320); + RestrictResetBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, + ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, + 320); } - SetComboByName(ui->advOutTrack1Bitrate, - std::to_string(track1Bitrate).c_str()); - SetComboByName(ui->advOutTrack2Bitrate, - std::to_string(track2Bitrate).c_str()); - SetComboByName(ui->advOutTrack3Bitrate, - std::to_string(track3Bitrate).c_str()); - SetComboByName(ui->advOutTrack4Bitrate, - std::to_string(track4Bitrate).c_str()); - SetComboByName(ui->advOutTrack5Bitrate, - std::to_string(track5Bitrate).c_str()); - SetComboByName(ui->advOutTrack6Bitrate, - std::to_string(track6Bitrate).c_str()); + SetComboByName(ui->advOutTrack1Bitrate, std::to_string(track1Bitrate).c_str()); + SetComboByName(ui->advOutTrack2Bitrate, std::to_string(track2Bitrate).c_str()); + SetComboByName(ui->advOutTrack3Bitrate, std::to_string(track3Bitrate).c_str()); + SetComboByName(ui->advOutTrack4Bitrate, std::to_string(track4Bitrate).c_str()); + SetComboByName(ui->advOutTrack5Bitrate, std::to_string(track5Bitrate).c_str()); + SetComboByName(ui->advOutTrack6Bitrate, std::to_string(track6Bitrate).c_str()); ui->advOutTrack1Name->setText(name1); ui->advOutTrack2Name->setText(name2); @@ -2514,8 +2178,7 @@ void OBSBasicSettings::LoadOutputSettings() LoadAdvOutputStreamingSettings(); LoadAdvOutputStreamingEncoderProperties(); - const char *type = - config_get_string(main->Config(), "AdvOut", "AudioEncoder"); + const char *type = config_get_string(main->Config(), "AdvOut", "AudioEncoder"); if (!SetComboByValue(ui->advOutAEncoder, type)) ui->advOutAEncoder->setCurrentIndex(-1); @@ -2546,9 +2209,7 @@ void OBSBasicSettings::LoadOutputSettings() loading = false; } -void OBSBasicSettings::SetAdvOutputFFmpegEnablement(FFmpegCodecType encoderType, - bool enabled, - bool enableEncoder) +void OBSBasicSettings::SetAdvOutputFFmpegEnablement(FFmpegCodecType encoderType, bool enabled, bool enableEncoder) { bool rescale = config_get_bool(main->Config(), "AdvOut", "FFRescale"); @@ -2576,14 +2237,12 @@ void OBSBasicSettings::SetAdvOutputFFmpegEnablement(FFmpegCodecType encoderType, } } -static inline void LoadListValue(QComboBox *widget, const char *text, - const char *val) +static inline void LoadListValue(QComboBox *widget, const char *text, const char *val) { widget->addItem(QT_UTF8(text), QT_UTF8(val)); } -void OBSBasicSettings::LoadListValues(QComboBox *widget, obs_property_t *prop, - int index) +void OBSBasicSettings::LoadListValues(QComboBox *widget, obs_property_t *prop, int index) { size_t count = obs_property_list_item_count(prop); @@ -2616,8 +2275,7 @@ void OBSBasicSettings::LoadListValues(QComboBox *widget, obs_property_t *prop, "UnknownAudioDevice"), var); widget->setCurrentIndex(0); - HighlightGroupBoxLabel(ui->audioDevicesGroupBox, widget, - "errorLabel"); + HighlightGroupBoxLabel(ui->audioDevicesGroupBox, widget, "errorLabel"); } } } @@ -2631,8 +2289,7 @@ void OBSBasicSettings::LoadAudioDevices() obs_properties_t *output_props = obs_get_source_properties(output_id); if (input_props) { - obs_property_t *inputs = - obs_properties_get(input_props, "device_id"); + obs_property_t *inputs = obs_properties_get(input_props, "device_id"); LoadListValues(ui->auxAudioDevice1, inputs, 3); LoadListValues(ui->auxAudioDevice2, inputs, 4); LoadListValues(ui->auxAudioDevice3, inputs, 5); @@ -2641,8 +2298,7 @@ void OBSBasicSettings::LoadAudioDevices() } if (output_props) { - obs_property_t *outputs = - obs_properties_get(output_props, "device_id"); + obs_property_t *outputs = obs_properties_get(output_props, "device_id"); LoadListValues(ui->desktopAudioDevice1, outputs, 1); LoadListValues(ui->desktopAudioDevice2, outputs, 2); obs_properties_destroy(output_props); @@ -2720,58 +2376,42 @@ void OBSBasicSettings::LoadAudioSources() audioSourceSignals.emplace_back( handler, "push_to_mute_changed", [](void *data, calldata_t *param) { - QMetaObject::invokeMethod( - static_cast(data), - "setCheckedSilently", - Q_ARG(bool, - calldata_bool(param, "enabled"))); + QMetaObject::invokeMethod(static_cast(data), "setCheckedSilently", + Q_ARG(bool, calldata_bool(param, "enabled"))); }, ptmCB); audioSourceSignals.emplace_back( handler, "push_to_mute_delay", [](void *data, calldata_t *param) { - QMetaObject::invokeMethod( - static_cast(data), - "setValueSilently", - Q_ARG(int, - calldata_int(param, "delay"))); + QMetaObject::invokeMethod(static_cast(data), "setValueSilently", + Q_ARG(int, calldata_int(param, "delay"))); }, ptmSB); audioSourceSignals.emplace_back( handler, "push_to_talk_changed", [](void *data, calldata_t *param) { - QMetaObject::invokeMethod( - static_cast(data), - "setCheckedSilently", - Q_ARG(bool, - calldata_bool(param, "enabled"))); + QMetaObject::invokeMethod(static_cast(data), "setCheckedSilently", + Q_ARG(bool, calldata_bool(param, "enabled"))); }, pttCB); audioSourceSignals.emplace_back( handler, "push_to_talk_delay", [](void *data, calldata_t *param) { - QMetaObject::invokeMethod( - static_cast(data), - "setValueSilently", - Q_ARG(int, - calldata_int(param, "delay"))); + QMetaObject::invokeMethod(static_cast(data), "setValueSilently", + Q_ARG(int, calldata_int(param, "delay"))); }, pttSB); - audioSources.emplace_back(OBSGetWeakRef(source), ptmCB, ptmSB, - pttCB, pttSB); + audioSources.emplace_back(OBSGetWeakRef(source), ptmCB, ptmSB, pttCB, pttSB); auto label = new OBSSourceLabel(source); TruncateLabel(label, label->text()); label->setMinimumSize(QSize(170, 0)); - label->setAlignment(Qt::AlignRight | Qt::AlignTrailing | - Qt::AlignVCenter); - connect(label, &OBSSourceLabel::Removed, [=]() { - QMetaObject::invokeMethod(this, "ReloadAudioSources"); - }); - connect(label, &OBSSourceLabel::Destroyed, [=]() { - QMetaObject::invokeMethod(this, "ReloadAudioSources"); - }); + label->setAlignment(Qt::AlignRight | Qt::AlignTrailing | Qt::AlignVCenter); + connect(label, &OBSSourceLabel::Removed, + [=]() { QMetaObject::invokeMethod(this, "ReloadAudioSources"); }); + connect(label, &OBSSourceLabel::Destroyed, + [=]() { QMetaObject::invokeMethod(this, "ReloadAudioSources"); }); layout->addRow(label, form); return true; @@ -2795,16 +2435,11 @@ void OBSBasicSettings::LoadAudioSources() void OBSBasicSettings::LoadAudioSettings() { - uint32_t sampleRate = - config_get_uint(main->Config(), "Audio", "SampleRate"); - const char *speakers = - config_get_string(main->Config(), "Audio", "ChannelSetup"); - double meterDecayRate = - config_get_double(main->Config(), "Audio", "MeterDecayRate"); - uint32_t peakMeterTypeIdx = - config_get_uint(main->Config(), "Audio", "PeakMeterType"); - bool enableLLAudioBuffering = config_get_bool( - App()->GetUserConfig(), "Audio", "LowLatencyAudioBuffering"); + uint32_t sampleRate = config_get_uint(main->Config(), "Audio", "SampleRate"); + const char *speakers = config_get_string(main->Config(), "Audio", "ChannelSetup"); + double meterDecayRate = config_get_double(main->Config(), "Audio", "MeterDecayRate"); + uint32_t peakMeterTypeIdx = config_get_uint(main->Config(), "Audio", "PeakMeterType"); + bool enableLLAudioBuffering = config_get_bool(App()->GetUserConfig(), "Audio", "LowLatencyAudioBuffering"); loading = true; @@ -2855,17 +2490,14 @@ void OBSBasicSettings::UpdateColorFormatSpaceWarning() switch (ui->colorSpace->currentIndex()) { case 3: /* Rec.2100 (PQ) */ case 4: /* Rec.2100 (HLG) */ - if ((format == "P010") || (format == "P216") || - (format == "P416")) { + if ((format == "P010") || (format == "P216") || (format == "P416")) { ui->advancedMsg2->clear(); ui->advancedMsg2->setVisible(false); } else if (format == "I010") { - ui->advancedMsg2->setText( - QTStr("Basic.Settings.Advanced.FormatWarning")); + ui->advancedMsg2->setText(QTStr("Basic.Settings.Advanced.FormatWarning")); ui->advancedMsg2->setVisible(true); } else { - ui->advancedMsg2->setText(QTStr( - "Basic.Settings.Advanced.FormatWarning2100")); + ui->advancedMsg2->setText(QTStr("Basic.Settings.Advanced.FormatWarning2100")); ui->advancedMsg2->setVisible(true); } break; @@ -2873,14 +2505,11 @@ void OBSBasicSettings::UpdateColorFormatSpaceWarning() if (format == "NV12") { ui->advancedMsg2->clear(); ui->advancedMsg2->setVisible(false); - } else if ((format == "I010") || (format == "P010") || - (format == "P216") || (format == "P416")) { - ui->advancedMsg2->setText(QTStr( - "Basic.Settings.Advanced.FormatWarningPreciseSdr")); + } else if ((format == "I010") || (format == "P010") || (format == "P216") || (format == "P416")) { + ui->advancedMsg2->setText(QTStr("Basic.Settings.Advanced.FormatWarningPreciseSdr")); ui->advancedMsg2->setVisible(true); } else { - ui->advancedMsg2->setText( - QTStr("Basic.Settings.Advanced.FormatWarning")); + ui->advancedMsg2->setText(QTStr("Basic.Settings.Advanced.FormatWarning")); ui->advancedMsg2->setVisible(true); } } @@ -2888,64 +2517,44 @@ void OBSBasicSettings::UpdateColorFormatSpaceWarning() void OBSBasicSettings::LoadAdvancedSettings() { - const char *videoColorFormat = - config_get_string(main->Config(), "Video", "ColorFormat"); - const char *videoColorSpace = - config_get_string(main->Config(), "Video", "ColorSpace"); - const char *videoColorRange = - config_get_string(main->Config(), "Video", "ColorRange"); - uint32_t sdrWhiteLevel = (uint32_t)config_get_uint( - main->Config(), "Video", "SdrWhiteLevel"); - uint32_t hdrNominalPeakLevel = (uint32_t)config_get_uint( - main->Config(), "Video", "HdrNominalPeakLevel"); + const char *videoColorFormat = config_get_string(main->Config(), "Video", "ColorFormat"); + const char *videoColorSpace = config_get_string(main->Config(), "Video", "ColorSpace"); + const char *videoColorRange = config_get_string(main->Config(), "Video", "ColorRange"); + uint32_t sdrWhiteLevel = (uint32_t)config_get_uint(main->Config(), "Video", "SdrWhiteLevel"); + uint32_t hdrNominalPeakLevel = (uint32_t)config_get_uint(main->Config(), "Video", "HdrNominalPeakLevel"); QString monDevName; QString monDevId; if (obs_audio_monitoring_available()) { - monDevName = config_get_string(main->Config(), "Audio", - "MonitoringDeviceName"); - monDevId = config_get_string(main->Config(), "Audio", - "MonitoringDeviceId"); + monDevName = config_get_string(main->Config(), "Audio", "MonitoringDeviceName"); + monDevId = config_get_string(main->Config(), "Audio", "MonitoringDeviceId"); } - bool enableDelay = - config_get_bool(main->Config(), "Output", "DelayEnable"); + bool enableDelay = config_get_bool(main->Config(), "Output", "DelayEnable"); int delaySec = config_get_int(main->Config(), "Output", "DelaySec"); - bool preserveDelay = - config_get_bool(main->Config(), "Output", "DelayPreserve"); + bool preserveDelay = config_get_bool(main->Config(), "Output", "DelayPreserve"); bool reconnect = config_get_bool(main->Config(), "Output", "Reconnect"); int retryDelay = config_get_int(main->Config(), "Output", "RetryDelay"); int maxRetries = config_get_int(main->Config(), "Output", "MaxRetries"); - const char *filename = config_get_string(main->Config(), "Output", - "FilenameFormatting"); - bool overwriteIfExists = - config_get_bool(main->Config(), "Output", "OverwriteIfExists"); - const char *bindIP = - config_get_string(main->Config(), "Output", "BindIP"); - const char *rbPrefix = config_get_string(main->Config(), "SimpleOutput", - "RecRBPrefix"); - const char *rbSuffix = config_get_string(main->Config(), "SimpleOutput", - "RecRBSuffix"); + const char *filename = config_get_string(main->Config(), "Output", "FilenameFormatting"); + bool overwriteIfExists = config_get_bool(main->Config(), "Output", "OverwriteIfExists"); + const char *bindIP = config_get_string(main->Config(), "Output", "BindIP"); + const char *rbPrefix = config_get_string(main->Config(), "SimpleOutput", "RecRBPrefix"); + const char *rbSuffix = config_get_string(main->Config(), "SimpleOutput", "RecRBSuffix"); bool replayBuf = config_get_bool(main->Config(), "AdvOut", "RecRB"); int rbTime = config_get_int(main->Config(), "AdvOut", "RecRBTime"); int rbSize = config_get_int(main->Config(), "AdvOut", "RecRBSize"); bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux"); - const char *hotkeyFocusType = config_get_string( - App()->GetUserConfig(), "General", "HotkeyFocusType"); - bool dynBitrate = - config_get_bool(main->Config(), "Output", "DynamicBitrate"); - const char *ipFamily = - config_get_string(main->Config(), "Output", "IPFamily"); - bool confirmOnExit = config_get_bool(App()->GetUserConfig(), "General", - "ConfirmOnExit"); + const char *hotkeyFocusType = config_get_string(App()->GetUserConfig(), "General", "HotkeyFocusType"); + bool dynBitrate = config_get_bool(main->Config(), "Output", "DynamicBitrate"); + const char *ipFamily = config_get_string(main->Config(), "Output", "IPFamily"); + bool confirmOnExit = config_get_bool(App()->GetUserConfig(), "General", "ConfirmOnExit"); loading = true; LoadRendererList(); - if (obs_audio_monitoring_available() && - !SetComboByValue(ui->monitoringDevice, monDevId.toUtf8())) - SetInvalidValue(ui->monitoringDevice, monDevName.toUtf8(), - monDevId.toUtf8()); + if (obs_audio_monitoring_available() && !SetComboByValue(ui->monitoringDevice, monDevId.toUtf8())) + SetInvalidValue(ui->monitoringDevice, monDevName.toUtf8(), monDevId.toUtf8()); ui->confirmOnExit->setChecked(confirmOnExit); @@ -2983,24 +2592,18 @@ void OBSBasicSettings::LoadAdvancedSettings() } #ifdef __APPLE__ - bool disableOSXVSync = config_get_bool(App()->GetAppConfig(), "Video", - "DisableOSXVSync"); - bool resetOSXVSync = config_get_bool(App()->GetAppConfig(), "Video", - "ResetOSXVSyncOnExit"); + bool disableOSXVSync = config_get_bool(App()->GetAppConfig(), "Video", "DisableOSXVSync"); + bool resetOSXVSync = config_get_bool(App()->GetAppConfig(), "Video", "ResetOSXVSyncOnExit"); ui->disableOSXVSync->setChecked(disableOSXVSync); ui->resetOSXVSync->setChecked(resetOSXVSync); ui->resetOSXVSync->setEnabled(disableOSXVSync); #elif _WIN32 - bool disableAudioDucking = config_get_bool( - App()->GetAppConfig(), "Audio", "DisableAudioDucking"); + bool disableAudioDucking = config_get_bool(App()->GetAppConfig(), "Audio", "DisableAudioDucking"); ui->disableAudioDucking->setChecked(disableAudioDucking); - const char *processPriority = config_get_string( - App()->GetAppConfig(), "General", "ProcessPriority"); - bool enableNewSocketLoop = config_get_bool(main->Config(), "Output", - "NewSocketLoopEnable"); - bool enableLowLatencyMode = - config_get_bool(main->Config(), "Output", "LowLatencyEnable"); + const char *processPriority = config_get_string(App()->GetAppConfig(), "General", "ProcessPriority"); + bool enableNewSocketLoop = config_get_bool(main->Config(), "Output", "NewSocketLoopEnable"); + bool enableLowLatencyMode = config_get_bool(main->Config(), "Output", "LowLatencyEnable"); int idx = ui->processPriority->findData(processPriority); if (idx == -1) @@ -3009,12 +2612,10 @@ void OBSBasicSettings::LoadAdvancedSettings() ui->enableNewSocketLoop->setChecked(enableNewSocketLoop); ui->enableLowLatencyMode->setChecked(enableLowLatencyMode); - ui->enableLowLatencyMode->setToolTip( - QTStr("Basic.Settings.Advanced.Network.TCPPacing.Tooltip")); + ui->enableLowLatencyMode->setToolTip(QTStr("Basic.Settings.Advanced.Network.TCPPacing.Tooltip")); #endif #if defined(_WIN32) || defined(__APPLE__) - bool browserHWAccel = config_get_bool(App()->GetUserConfig(), "General", - "BrowserHWAccel"); + bool browserHWAccel = config_get_bool(App()->GetUserConfig(), "General", "BrowserHWAccel"); ui->browserHWAccel->setChecked(browserHWAccel); prevBrowserAccel = ui->browserHWAccel->isChecked(); #endif @@ -3025,10 +2626,8 @@ void OBSBasicSettings::LoadAdvancedSettings() } template -static inline void -LayoutHotkey(OBSBasicSettings *settings, obs_hotkey_id id, obs_hotkey_t *key, - Func &&fun, - const map> &keys) +static inline void LayoutHotkey(OBSBasicSettings *settings, obs_hotkey_id id, obs_hotkey_t *key, Func &&fun, + const map> &keys) { auto *label = new OBSHotkeyLabel; QString text = QT_UTF8(obs_hotkey_get_description(key)); @@ -3040,11 +2639,9 @@ LayoutHotkey(OBSBasicSettings *settings, obs_hotkey_id id, obs_hotkey_t *key, auto combos = keys.find(id); if (combos == std::end(keys)) - hw = new OBSHotkeyWidget(settings, id, obs_hotkey_get_name(key), - settings); + hw = new OBSHotkeyWidget(settings, id, obs_hotkey_get_name(key), settings); else - hw = new OBSHotkeyWidget(settings, id, obs_hotkey_get_name(key), - settings, combos->second); + hw = new OBSHotkeyWidget(settings, id, obs_hotkey_get_name(key), settings, combos->second); hw->label = label; hw->setAccessibleName(text); @@ -3053,16 +2650,14 @@ LayoutHotkey(OBSBasicSettings *settings, obs_hotkey_id id, obs_hotkey_t *key, fun(key, label, hw); } -template -static QLabel *makeLabel(T &t, Func &&getName) +template static QLabel *makeLabel(T &t, Func &&getName) { QLabel *label = new QLabel(getName(t)); label->setStyleSheet("font-weight: bold;"); return label; } -template -static QLabel *makeLabel(const OBSSource &source, Func &&) +template static QLabel *makeLabel(const OBSSource &source, Func &&) { OBSSourceLabel *label = new OBSSourceLabel(source); label->setStyleSheet("font-weight: bold;"); @@ -3073,25 +2668,21 @@ static QLabel *makeLabel(const OBSSource &source, Func &&) } template -static inline void AddHotkeys( - QFormLayout &layout, Func &&getName, - std::vector, QPointer>> &hotkeys) +static inline void AddHotkeys(QFormLayout &layout, Func &&getName, + std::vector, QPointer>> &hotkeys) { if (hotkeys.empty()) return; - layout.setItem(layout.rowCount(), QFormLayout::SpanningRole, - new QSpacerItem(0, 10)); + layout.setItem(layout.rowCount(), QFormLayout::SpanningRole, new QSpacerItem(0, 10)); using tuple_type = std::tuple, QPointer>; - stable_sort(begin(hotkeys), end(hotkeys), - [&](const tuple_type &a, const tuple_type &b) { - const auto &o_a = get<0>(a); - const auto &o_b = get<0>(b); - return o_a != o_b && - string(getName(o_a)) < getName(o_b); - }); + stable_sort(begin(hotkeys), end(hotkeys), [&](const tuple_type &a, const tuple_type &b) { + const auto &o_a = get<0>(a); + const auto &o_b = get<0>(b); + return o_a != o_b && string(getName(o_a)) < getName(o_b); + }); string prevName; for (const auto &hotkey : hotkeys) { @@ -3099,9 +2690,7 @@ static inline void AddHotkeys( const char *name = getName(o); if (prevName != name) { prevName = name; - layout.setItem(layout.rowCount(), - QFormLayout::SpanningRole, - new QSpacerItem(0, 10)); + layout.setItem(layout.rowCount(), QFormLayout::SpanningRole, new QSpacerItem(0, 10)); layout.addRow(makeLabel(o, getName)); } @@ -3132,10 +2721,8 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) [](void *data, size_t, obs_hotkey_binding_t *binding) { auto &keys = *static_cast(data); - keys[obs_hotkey_binding_get_hotkey_id(binding)] - .emplace_back( - obs_hotkey_binding_get_key_combination( - binding)); + keys[obs_hotkey_binding_get_hotkey_id(binding)].emplace_back( + obs_hotkey_binding_get_key_combination(binding)); return true; }, @@ -3144,21 +2731,16 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) QFormLayout *hotkeysLayout = new QFormLayout(); hotkeysLayout->setVerticalSpacing(0); hotkeysLayout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); - hotkeysLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignTrailing | - Qt::AlignVCenter); + hotkeysLayout->setLabelAlignment(Qt::AlignRight | Qt::AlignTrailing | Qt::AlignVCenter); auto hotkeyChildWidget = new QWidget(); hotkeyChildWidget->setLayout(hotkeysLayout); ui->hotkeyFormLayout->addRow(hotkeyChildWidget); using namespace std; - using encoders_elem_t = - tuple, QPointer>; - using outputs_elem_t = - tuple, QPointer>; - using services_elem_t = - tuple, QPointer>; - using sources_elem_t = - tuple, QPointer>; + using encoders_elem_t = tuple, QPointer>; + using outputs_elem_t = tuple, QPointer>; + using services_elem_t = tuple, QPointer>; + using sources_elem_t = tuple, QPointer>; vector encoders; vector outputs; vector services; @@ -3170,10 +2752,8 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) using std::move; - auto HandleEncoder = [&](void *registerer, OBSHotkeyLabel *label, - OBSHotkeyWidget *hw) { - auto weak_encoder = - static_cast(registerer); + auto HandleEncoder = [&](void *registerer, OBSHotkeyLabel *label, OBSHotkeyWidget *hw) { + auto weak_encoder = static_cast(registerer); auto encoder = OBSGetStrongRef(weak_encoder); if (!encoder) @@ -3183,8 +2763,7 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) return false; }; - auto HandleOutput = [&](void *registerer, OBSHotkeyLabel *label, - OBSHotkeyWidget *hw) { + auto HandleOutput = [&](void *registerer, OBSHotkeyLabel *label, OBSHotkeyWidget *hw) { auto weak_output = static_cast(registerer); auto output = OBSGetStrongRef(weak_output); @@ -3195,10 +2774,8 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) return false; }; - auto HandleService = [&](void *registerer, OBSHotkeyLabel *label, - OBSHotkeyWidget *hw) { - auto weak_service = - static_cast(registerer); + auto HandleService = [&](void *registerer, OBSHotkeyLabel *label, OBSHotkeyWidget *hw) { + auto weak_service = static_cast(registerer); auto service = OBSGetStrongRef(weak_service); if (!service) @@ -3208,8 +2785,7 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) return false; }; - auto HandleSource = [&](void *registerer, OBSHotkeyLabel *label, - OBSHotkeyWidget *hw) { + auto HandleSource = [&](void *registerer, OBSHotkeyLabel *label, OBSHotkeyWidget *hw) { auto weak_source = static_cast(registerer); auto source = OBSGetStrongRef(weak_source); @@ -3224,15 +2800,13 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) return false; }; - auto RegisterHotkey = [&](obs_hotkey_t *key, OBSHotkeyLabel *label, - OBSHotkeyWidget *hw) { + auto RegisterHotkey = [&](obs_hotkey_t *key, OBSHotkeyLabel *label, OBSHotkeyWidget *hw) { auto registerer_type = obs_hotkey_get_registerer_type(key); void *registerer = obs_hotkey_get_registerer(key); obs_hotkey_id partner = obs_hotkey_get_pair_partner_id(key); if (partner != OBS_INVALID_HOTKEY_ID) { - pairLabels.emplace(obs_hotkey_get_id(key), - make_pair(partner, label)); + pairLabels.emplace(obs_hotkey_get_id(key), make_pair(partner, label)); pairIds.push_back(obs_hotkey_get_id(key)); } @@ -3264,29 +2838,25 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) break; } - hotkeys.emplace_back( - registerer_type == OBS_HOTKEY_REGISTERER_FRONTEND, hw); + hotkeys.emplace_back(registerer_type == OBS_HOTKEY_REGISTERER_FRONTEND, hw); connect(hw, &OBSHotkeyWidget::KeyChanged, this, [=]() { HotkeysChanged(); ScanDuplicateHotkeys(hotkeysLayout); }); - connect(hw, &OBSHotkeyWidget::SearchKey, - [=](obs_key_combination_t combo) { - ui->hotkeyFilterSearch->setText(""); - ui->hotkeyFilterInput->HandleNewKey(combo); - ui->hotkeyFilterInput->KeyChanged(combo); - }); + connect(hw, &OBSHotkeyWidget::SearchKey, [=](obs_key_combination_t combo) { + ui->hotkeyFilterSearch->setText(""); + ui->hotkeyFilterInput->HandleNewKey(combo); + ui->hotkeyFilterInput->KeyChanged(combo); + }); }; - auto data = - make_tuple(RegisterHotkey, std::move(keys), ignoreKey, this); + auto data = make_tuple(RegisterHotkey, std::move(keys), ignoreKey, this); using data_t = decltype(data); obs_enum_hotkeys( [](void *data, obs_hotkey_id id, obs_hotkey_t *key) { data_t &d = *static_cast(data); if (id != get<2>(d)) - LayoutHotkey(get<3>(d), id, key, get<0>(d), - get<1>(d)); + LayoutHotkey(get<3>(d), id, key, get<0>(d), get<1>(d)); return true; }, &data); @@ -3312,11 +2882,9 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) auto name1 = label1->text(); auto name2 = label2->text(); - auto Update = [&](OBSHotkeyLabel *label, const QString &name, - OBSHotkeyLabel *other, + auto Update = [&](OBSHotkeyLabel *label, const QString &name, OBSHotkeyLabel *other, const QString &otherName) { - QString string = - other->property("fullName").value(); + QString string = other->property("fullName").value(); if (string.isEmpty() || string.isNull()) string = otherName; @@ -3372,29 +2940,24 @@ void OBSBasicSettings::SaveGeneralSettings() string language = langData.toString().toStdString(); if (WidgetChanged(ui->language)) - config_set_string(App()->GetUserConfig(), "General", "Language", - language.c_str()); + config_set_string(App()->GetUserConfig(), "General", "Language", language.c_str()); #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) if (WidgetChanged(ui->enableAutoUpdates)) - config_set_bool(App()->GetUserConfig(), "General", - "EnableAutoUpdates", + config_set_bool(App()->GetUserConfig(), "General", "EnableAutoUpdates", ui->enableAutoUpdates->isChecked()); int branchIdx = ui->updateChannelBox->currentIndex(); - QString branchName = - ui->updateChannelBox->itemData(branchIdx).toString(); + QString branchName = ui->updateChannelBox->itemData(branchIdx).toString(); if (WidgetChanged(ui->updateChannelBox)) { - config_set_string(App()->GetAppConfig(), "General", - "UpdateBranch", QT_TO_UTF8(branchName)); + config_set_string(App()->GetAppConfig(), "General", "UpdateBranch", QT_TO_UTF8(branchName)); forceUpdateCheck = true; } #endif #ifdef _WIN32 if (ui->hideOBSFromCapture && WidgetChanged(ui->hideOBSFromCapture)) { bool hide_window = ui->hideOBSFromCapture->isChecked(); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "HideOBSWindowsFromCapture", hide_window); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "HideOBSWindowsFromCapture", hide_window); QWindowList windows = QGuiApplication::allWindows(); for (auto window : windows) { @@ -3403,155 +2966,122 @@ void OBSBasicSettings::SaveGeneralSettings() } } - blog(LOG_INFO, "Hide OBS windows from screen capture: %s", - hide_window ? "true" : "false"); + blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hide_window ? "true" : "false"); } #endif if (WidgetChanged(ui->openStatsOnStartup)) - config_set_bool(main->Config(), "General", "OpenStatsOnStartup", - ui->openStatsOnStartup->isChecked()); + config_set_bool(main->Config(), "General", "OpenStatsOnStartup", ui->openStatsOnStartup->isChecked()); if (WidgetChanged(ui->snappingEnabled)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SnappingEnabled", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled", ui->snappingEnabled->isChecked()); if (WidgetChanged(ui->screenSnapping)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ScreenSnapping", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ScreenSnapping", ui->screenSnapping->isChecked()); if (WidgetChanged(ui->centerSnapping)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "CenterSnapping", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "CenterSnapping", ui->centerSnapping->isChecked()); if (WidgetChanged(ui->sourceSnapping)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SourceSnapping", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SourceSnapping", ui->sourceSnapping->isChecked()); if (WidgetChanged(ui->snapDistance)) - config_set_double(App()->GetUserConfig(), "BasicWindow", - "SnapDistance", ui->snapDistance->value()); - if (WidgetChanged(ui->overflowAlwaysVisible) || - WidgetChanged(ui->overflowHide) || + config_set_double(App()->GetUserConfig(), "BasicWindow", "SnapDistance", ui->snapDistance->value()); + if (WidgetChanged(ui->overflowAlwaysVisible) || WidgetChanged(ui->overflowHide) || WidgetChanged(ui->overflowSelectionHide)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "OverflowAlwaysVisible", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "OverflowAlwaysVisible", ui->overflowAlwaysVisible->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "OverflowHidden", - ui->overflowHide->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "OverflowSelectionHidden", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "OverflowHidden", ui->overflowHide->isChecked()); + config_set_bool(App()->GetUserConfig(), "BasicWindow", "OverflowSelectionHidden", ui->overflowSelectionHide->isChecked()); main->UpdatePreviewOverflowSettings(); } if (WidgetChanged(ui->previewSafeAreas)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ShowSafeAreas", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowSafeAreas", ui->previewSafeAreas->isChecked()); main->UpdatePreviewSafeAreas(); } if (WidgetChanged(ui->previewSpacingHelpers)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SpacingHelpersEnabled", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SpacingHelpersEnabled", ui->previewSpacingHelpers->isChecked()); main->UpdatePreviewSpacingHelpers(); } if (WidgetChanged(ui->doubleClickSwitch)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "TransitionOnDoubleClick", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "TransitionOnDoubleClick", ui->doubleClickSwitch->isChecked()); if (WidgetChanged(ui->automaticSearch)) - config_set_bool(App()->GetUserConfig(), "General", - "AutomaticCollectionSearch", + config_set_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch", ui->automaticSearch->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "WarnBeforeStartingStream", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStartingStream", ui->warnBeforeStreamStart->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "WarnBeforeStoppingStream", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingStream", ui->warnBeforeStreamStop->isChecked()); - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "WarnBeforeStoppingRecord", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStoppingRecord", ui->warnBeforeRecordStop->isChecked()); if (WidgetChanged(ui->hideProjectorCursor)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "HideProjectorCursor", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "HideProjectorCursor", ui->hideProjectorCursor->isChecked()); main->UpdateProjectorHideCursor(); } if (WidgetChanged(ui->projectorAlwaysOnTop)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ProjectorAlwaysOnTop", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ProjectorAlwaysOnTop", ui->projectorAlwaysOnTop->isChecked()); #if defined(_WIN32) || defined(__APPLE__) - main->UpdateProjectorAlwaysOnTop( - ui->projectorAlwaysOnTop->isChecked()); + main->UpdateProjectorAlwaysOnTop(ui->projectorAlwaysOnTop->isChecked()); #else main->ResetProjectors(); #endif } if (WidgetChanged(ui->recordWhenStreaming)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "RecordWhenStreaming", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming", ui->recordWhenStreaming->isChecked()); if (WidgetChanged(ui->keepRecordStreamStops)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "KeepRecordingWhenStreamStops", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops", ui->keepRecordStreamStops->isChecked()); if (WidgetChanged(ui->replayWhileStreaming)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "ReplayBufferWhileStreaming", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming", ui->replayWhileStreaming->isChecked()); if (WidgetChanged(ui->keepReplayStreamStops)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "KeepReplayBufferStreamStops", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops", ui->keepReplayStreamStops->isChecked()); if (WidgetChanged(ui->systemTrayEnabled)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SysTrayEnabled", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled", ui->systemTrayEnabled->isChecked()); main->SystemTray(false); } if (WidgetChanged(ui->systemTrayWhenStarted)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SysTrayWhenStarted", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted", ui->systemTrayWhenStarted->isChecked()); if (WidgetChanged(ui->systemTrayAlways)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SysTrayMinimizeToTray", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayMinimizeToTray", ui->systemTrayAlways->isChecked()); if (WidgetChanged(ui->saveProjectors)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "SaveProjectors", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "SaveProjectors", ui->saveProjectors->isChecked()); if (WidgetChanged(ui->closeProjectors)) - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "CloseExistingProjectors", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "CloseExistingProjectors", ui->closeProjectors->isChecked()); if (WidgetChanged(ui->studioPortraitLayout)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "StudioPortraitLayout", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "StudioPortraitLayout", ui->studioPortraitLayout->isChecked()); main->ResetUI(); } if (WidgetChanged(ui->prevProgLabelToggle)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "StudioModeLabels", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "StudioModeLabels", ui->prevProgLabelToggle->isChecked()); main->ResetUI(); @@ -3559,29 +3089,25 @@ void OBSBasicSettings::SaveGeneralSettings() bool multiviewChanged = false; if (WidgetChanged(ui->multiviewMouseSwitch)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "MultiviewMouseSwitch", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewMouseSwitch", ui->multiviewMouseSwitch->isChecked()); multiviewChanged = true; } if (WidgetChanged(ui->multiviewDrawNames)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "MultiviewDrawNames", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewDrawNames", ui->multiviewDrawNames->isChecked()); multiviewChanged = true; } if (WidgetChanged(ui->multiviewDrawAreas)) { - config_set_bool(App()->GetUserConfig(), "BasicWindow", - "MultiviewDrawAreas", + config_set_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewDrawAreas", ui->multiviewDrawAreas->isChecked()); multiviewChanged = true; } if (WidgetChanged(ui->multiviewLayout)) { - config_set_int(App()->GetUserConfig(), "BasicWindow", - "MultiviewLayout", + config_set_int(App()->GetUserConfig(), "BasicWindow", "MultiviewLayout", ui->multiviewLayout->currentData().toInt()); multiviewChanged = true; } @@ -3599,14 +3125,12 @@ void OBSBasicSettings::SaveVideoSettings() /* ------------------- */ - if (WidgetChanged(ui->baseResolution) && - ConvertResText(QT_TO_UTF8(baseResolution), cx, cy)) { + if (WidgetChanged(ui->baseResolution) && ConvertResText(QT_TO_UTF8(baseResolution), cx, cy)) { config_set_uint(main->Config(), "Video", "BaseCX", cx); config_set_uint(main->Config(), "Video", "BaseCY", cy); } - if (WidgetChanged(ui->outputResolution) && - ConvertResText(QT_TO_UTF8(outputResolution), cx, cy)) { + if (WidgetChanged(ui->outputResolution) && ConvertResText(QT_TO_UTF8(outputResolution), cx, cy)) { config_set_uint(main->Config(), "Video", "OutputCX", cx); config_set_uint(main->Config(), "Video", "OutputCY", cy); } @@ -3623,18 +3147,14 @@ void OBSBasicSettings::SaveVideoSettings() void OBSBasicSettings::SaveAdvancedSettings() { - QString lastMonitoringDevice = config_get_string( - main->Config(), "Audio", "MonitoringDeviceId"); + QString lastMonitoringDevice = config_get_string(main->Config(), "Audio", "MonitoringDeviceId"); #ifdef _WIN32 if (WidgetChanged(ui->renderer)) - config_set_string(App()->GetAppConfig(), "Video", "Renderer", - QT_TO_UTF8(ui->renderer->currentText())); + config_set_string(App()->GetAppConfig(), "Video", "Renderer", QT_TO_UTF8(ui->renderer->currentText())); - std::string priority = - QT_TO_UTF8(ui->processPriority->currentData().toString()); - config_set_string(App()->GetAppConfig(), "General", "ProcessPriority", - priority.c_str()); + std::string priority = QT_TO_UTF8(ui->processPriority->currentData().toString()); + config_set_string(App()->GetAppConfig(), "General", "ProcessPriority", priority.c_str()); if (main->Active()) SetProcessPriority(priority.c_str()); @@ -3643,27 +3163,22 @@ void OBSBasicSettings::SaveAdvancedSettings() #endif #if defined(_WIN32) || defined(__APPLE__) bool browserHWAccel = ui->browserHWAccel->isChecked(); - config_set_bool(App()->GetUserConfig(), "General", "BrowserHWAccel", - browserHWAccel); + config_set_bool(App()->GetUserConfig(), "General", "BrowserHWAccel", browserHWAccel); #endif if (WidgetChanged(ui->hotkeyFocusType)) { QString str = GetComboData(ui->hotkeyFocusType); - config_set_string(App()->GetUserConfig(), "General", - "HotkeyFocusType", QT_TO_UTF8(str)); + config_set_string(App()->GetUserConfig(), "General", "HotkeyFocusType", QT_TO_UTF8(str)); } #ifdef __APPLE__ if (WidgetChanged(ui->disableOSXVSync)) { bool disable = ui->disableOSXVSync->isChecked(); - config_set_bool(App()->GetAppConfig(), "Video", - "DisableOSXVSync", disable); + config_set_bool(App()->GetAppConfig(), "Video", "DisableOSXVSync", disable); EnableOSXVSync(!disable); } if (WidgetChanged(ui->resetOSXVSync)) - config_set_bool(App()->GetAppConfig(), "Video", - "ResetOSXVSyncOnExit", - ui->resetOSXVSync->isChecked()); + config_set_bool(App()->GetAppConfig(), "Video", "ResetOSXVSyncOnExit", ui->resetOSXVSync->isChecked()); #endif SaveComboData(ui->colorFormat, "Video", "ColorFormat"); @@ -3672,25 +3187,20 @@ void OBSBasicSettings::SaveAdvancedSettings() SaveSpinBox(ui->sdrWhiteLevel, "Video", "SdrWhiteLevel"); SaveSpinBox(ui->hdrNominalPeakLevel, "Video", "HdrNominalPeakLevel"); if (obs_audio_monitoring_available()) { - SaveCombo(ui->monitoringDevice, "Audio", - "MonitoringDeviceName"); - SaveComboData(ui->monitoringDevice, "Audio", - "MonitoringDeviceId"); + SaveCombo(ui->monitoringDevice, "Audio", "MonitoringDeviceName"); + SaveComboData(ui->monitoringDevice, "Audio", "MonitoringDeviceId"); } #ifdef _WIN32 if (WidgetChanged(ui->disableAudioDucking)) { bool disable = ui->disableAudioDucking->isChecked(); - config_set_bool(App()->GetAppConfig(), "Audio", - "DisableAudioDucking", disable); + config_set_bool(App()->GetAppConfig(), "Audio", "DisableAudioDucking", disable); DisableAudioDucking(disable); } #endif if (WidgetChanged(ui->confirmOnExit)) - config_set_bool(App()->GetUserConfig(), "General", - "ConfirmOnExit", - ui->confirmOnExit->isChecked()); + config_set_bool(App()->GetUserConfig(), "General", "ConfirmOnExit", ui->confirmOnExit->isChecked()); SaveEdit(ui->filenameFormatting, "Output", "FilenameFormatting"); SaveEdit(ui->simpleRBPrefix, "SimpleOutput", "RecRBPrefix"); @@ -3708,18 +3218,14 @@ void OBSBasicSettings::SaveAdvancedSettings() SaveCheckBox(ui->dynBitrate, "Output", "DynamicBitrate"); if (obs_audio_monitoring_available()) { - QString newDevice = - ui->monitoringDevice->currentData().toString(); + QString newDevice = ui->monitoringDevice->currentData().toString(); if (lastMonitoringDevice != newDevice) { - obs_set_audio_monitoring_device( - QT_TO_UTF8(ui->monitoringDevice->currentText()), - QT_TO_UTF8(newDevice)); + obs_set_audio_monitoring_device(QT_TO_UTF8(ui->monitoringDevice->currentText()), + QT_TO_UTF8(newDevice)); - blog(LOG_INFO, - "Audio monitoring device:\n\tname: %s\n\tid: %s", - QT_TO_UTF8(ui->monitoringDevice->currentText()), - QT_TO_UTF8(newDevice)); + blog(LOG_INFO, "Audio monitoring device:\n\tname: %s\n\tid: %s", + QT_TO_UTF8(ui->monitoringDevice->currentText()), QT_TO_UTF8(newDevice)); } } } @@ -3755,28 +3261,22 @@ static void WriteJsonData(OBSPropertiesView *view, const char *path) if (!view || !WidgetChanged(view)) return; - const OBSBasic *basic = - reinterpret_cast(App()->GetMainWindow()); + const OBSBasic *basic = reinterpret_cast(App()->GetMainWindow()); const OBSProfile ¤tProfile = basic->GetCurrentProfile(); - const std::filesystem::path jsonFilePath = - currentProfile.path / std::filesystem::u8path(path); + const std::filesystem::path jsonFilePath = currentProfile.path / std::filesystem::u8path(path); if (!jsonFilePath.empty()) { obs_data_t *settings = view->GetSettings(); if (settings) { - obs_data_save_json_safe(settings, - jsonFilePath.u8string().c_str(), - "tmp", "bak"); + obs_data_save_json_safe(settings, jsonFilePath.u8string().c_str(), "tmp", "bak"); } } } -static void SaveTrackIndex(config_t *config, const char *section, - const char *name, QAbstractButton *check1, - QAbstractButton *check2, QAbstractButton *check3, - QAbstractButton *check4, QAbstractButton *check5, - QAbstractButton *check6) +static void SaveTrackIndex(config_t *config, const char *section, const char *name, QAbstractButton *check1, + QAbstractButton *check2, QAbstractButton *check3, QAbstractButton *check4, + QAbstractButton *check5, QAbstractButton *check6) { if (check1->isChecked()) config_set_int(config, section, name, 1); @@ -3797,10 +3297,8 @@ void OBSBasicSettings::SaveFormat(QComboBox *combo) QVariant v = combo->currentData(); if (!v.isNull()) { auto format = v.value(); - config_set_string(main->Config(), "AdvOut", "FFFormat", - format.name); - config_set_string(main->Config(), "AdvOut", "FFFormatMimeType", - format.mime_type); + config_set_string(main->Config(), "AdvOut", "FFFormat", format.name); + config_set_string(main->Config(), "AdvOut", "FFFormatMimeType", format.mime_type); const char *ext = format.extensions; string extStr = ext ? ext : ""; @@ -3809,28 +3307,23 @@ void OBSBasicSettings::SaveFormat(QComboBox *combo) if (comma) *comma = 0; - config_set_string(main->Config(), "AdvOut", "FFExtension", - extStr.c_str()); + config_set_string(main->Config(), "AdvOut", "FFExtension", extStr.c_str()); } else { - config_set_string(main->Config(), "AdvOut", "FFFormat", - nullptr); - config_set_string(main->Config(), "AdvOut", "FFFormatMimeType", - nullptr); + config_set_string(main->Config(), "AdvOut", "FFFormat", nullptr); + config_set_string(main->Config(), "AdvOut", "FFFormatMimeType", nullptr); config_remove_value(main->Config(), "AdvOut", "FFExtension"); } } -void OBSBasicSettings::SaveEncoder(QComboBox *combo, const char *section, - const char *value) +void OBSBasicSettings::SaveEncoder(QComboBox *combo, const char *section, const char *value) { QVariant v = combo->currentData(); FFmpegCodec cd{}; if (!v.isNull()) cd = v.value(); - config_set_int(main->Config(), section, - QT_TO_UTF8(QString("%1Id").arg(value)), cd.id); + config_set_int(main->Config(), section, QT_TO_UTF8(QString("%1Id").arg(value)), cd.id); if (cd.id != 0) config_set_string(main->Config(), section, value, cd.name); else @@ -3839,8 +3332,7 @@ void OBSBasicSettings::SaveEncoder(QComboBox *combo, const char *section, void OBSBasicSettings::SaveOutputSettings() { - config_set_string(main->Config(), "Output", "Mode", - OutputModeFromIdx(ui->outputMode->currentIndex())); + config_set_string(main->Config(), "Output", "Mode", OutputModeFromIdx(ui->outputMode->currentIndex())); QString encoder = ui->simpleOutStrEncoder->currentData().toString(); const char *presetType; @@ -3877,8 +3369,7 @@ void OBSBasicSettings::SaveOutputSettings() SaveSpinBox(ui->simpleOutputVBitrate, "SimpleOutput", "VBitrate"); SaveComboData(ui->simpleOutStrEncoder, "SimpleOutput", "StreamEncoder"); - SaveComboData(ui->simpleOutStrAEncoder, "SimpleOutput", - "StreamAudioEncoder"); + SaveComboData(ui->simpleOutStrAEncoder, "SimpleOutput", "StreamAudioEncoder"); SaveCombo(ui->simpleOutputABitrate, "SimpleOutput", "ABitrate"); SaveEdit(ui->simpleOutputPath, "SimpleOutput", "FilePath"); SaveCheckBox(ui->simpleNoSpace, "SimpleOutput", "FileNameWithoutSpace"); @@ -3888,14 +3379,12 @@ void OBSBasicSettings::SaveOutputSettings() SaveEdit(ui->simpleOutCustom, "SimpleOutput", "x264Settings"); SaveComboData(ui->simpleOutRecQuality, "SimpleOutput", "RecQuality"); SaveComboData(ui->simpleOutRecEncoder, "SimpleOutput", "RecEncoder"); - SaveComboData(ui->simpleOutRecAEncoder, "SimpleOutput", - "RecAudioEncoder"); + SaveComboData(ui->simpleOutRecAEncoder, "SimpleOutput", "RecAudioEncoder"); SaveEdit(ui->simpleOutMuxCustom, "SimpleOutput", "MuxerCustom"); SaveGroupBox(ui->simpleReplayBuf, "SimpleOutput", "RecRB"); SaveSpinBox(ui->simpleRBSecMax, "SimpleOutput", "RecRBTime"); SaveSpinBox(ui->simpleRBMegsMax, "SimpleOutput", "RecRBSize"); - config_set_int(main->Config(), "SimpleOutput", "RecTracks", - SimpleOutGetSelectedAudioTracks()); + config_set_int(main->Config(), "SimpleOutput", "RecTracks", SimpleOutGetSelectedAudioTracks()); curAdvStreamEncoder = GetComboData(ui->advOutEncoder); @@ -3903,13 +3392,10 @@ void OBSBasicSettings::SaveOutputSettings() SaveComboData(ui->advOutAEncoder, "AdvOut", "AudioEncoder"); SaveCombo(ui->advOutRescale, "AdvOut", "RescaleRes"); SaveComboData(ui->advOutRescaleFilter, "AdvOut", "RescaleFilter"); - SaveTrackIndex(main->Config(), "AdvOut", "TrackIndex", ui->advOutTrack1, - ui->advOutTrack2, ui->advOutTrack3, ui->advOutTrack4, - ui->advOutTrack5, ui->advOutTrack6); - config_set_int(main->Config(), "AdvOut", "StreamMultiTrackAudioMixes", - AdvOutGetStreamingSelectedAudioTracks()); - config_set_string(main->Config(), "AdvOut", "RecType", - RecTypeFromIdx(ui->advOutRecType->currentIndex())); + SaveTrackIndex(main->Config(), "AdvOut", "TrackIndex", ui->advOutTrack1, ui->advOutTrack2, ui->advOutTrack3, + ui->advOutTrack4, ui->advOutTrack5, ui->advOutTrack6); + config_set_int(main->Config(), "AdvOut", "StreamMultiTrackAudioMixes", AdvOutGetStreamingSelectedAudioTracks()); + config_set_string(main->Config(), "AdvOut", "RecType", RecTypeFromIdx(ui->advOutRecType->currentIndex())); curAdvRecordEncoder = GetComboData(ui->advOutRecEncoder); @@ -3922,14 +3408,12 @@ void OBSBasicSettings::SaveOutputSettings() SaveComboData(ui->advOutRecRescaleFilter, "AdvOut", "RecRescaleFilter"); SaveEdit(ui->advOutMuxCustom, "AdvOut", "RecMuxerCustom"); SaveCheckBox(ui->advOutSplitFile, "AdvOut", "RecSplitFile"); - config_set_string( - main->Config(), "AdvOut", "RecSplitFileType", - SplitFileTypeFromIdx(ui->advOutSplitFileType->currentIndex())); + config_set_string(main->Config(), "AdvOut", "RecSplitFileType", + SplitFileTypeFromIdx(ui->advOutSplitFileType->currentIndex())); SaveSpinBox(ui->advOutSplitFileTime, "AdvOut", "RecSplitFileTime"); SaveSpinBox(ui->advOutSplitFileSize, "AdvOut", "RecSplitFileSize"); - config_set_int(main->Config(), "AdvOut", "RecTracks", - AdvOutGetSelectedAudioTracks()); + config_set_int(main->Config(), "AdvOut", "RecTracks", AdvOutGetSelectedAudioTracks()); config_set_int(main->Config(), "AdvOut", "FLVTrack", CurrentFLVTrack()); @@ -3950,14 +3434,13 @@ void OBSBasicSettings::SaveOutputSettings() SaveSpinBox(ui->advOutFFABitrate, "AdvOut", "FFABitrate"); SaveEncoder(ui->advOutFFAEncoder, "AdvOut", "FFAEncoder"); SaveEdit(ui->advOutFFACfg, "AdvOut", "FFACustom"); - config_set_int( - main->Config(), "AdvOut", "FFAudioMixes", - (ui->advOutFFTrack1->isChecked() ? (1 << 0) : 0) | - (ui->advOutFFTrack2->isChecked() ? (1 << 1) : 0) | - (ui->advOutFFTrack3->isChecked() ? (1 << 2) : 0) | - (ui->advOutFFTrack4->isChecked() ? (1 << 3) : 0) | - (ui->advOutFFTrack5->isChecked() ? (1 << 4) : 0) | - (ui->advOutFFTrack6->isChecked() ? (1 << 5) : 0)); + config_set_int(main->Config(), "AdvOut", "FFAudioMixes", + (ui->advOutFFTrack1->isChecked() ? (1 << 0) : 0) | + (ui->advOutFFTrack2->isChecked() ? (1 << 1) : 0) | + (ui->advOutFFTrack3->isChecked() ? (1 << 2) : 0) | + (ui->advOutFFTrack4->isChecked() ? (1 << 3) : 0) | + (ui->advOutFFTrack5->isChecked() ? (1 << 4) : 0) | + (ui->advOutFFTrack6->isChecked() ? (1 << 5) : 0)); SaveCombo(ui->advOutTrack1Bitrate, "AdvOut", "Track1Bitrate"); SaveCombo(ui->advOutTrack2Bitrate, "AdvOut", "Track2Bitrate"); SaveCombo(ui->advOutTrack3Bitrate, "AdvOut", "Track3Bitrate"); @@ -3974,8 +3457,7 @@ void OBSBasicSettings::SaveOutputSettings() if (vodTrackCheckbox) { SaveCheckBox(simpleVodTrack, "SimpleOutput", "VodTrackEnabled"); SaveCheckBox(vodTrackCheckbox, "AdvOut", "VodTrackEnabled"); - SaveTrackIndex(main->Config(), "AdvOut", "VodTrackIndex", - vodTrack[0], vodTrack[1], vodTrack[2], + SaveTrackIndex(main->Config(), "AdvOut", "VodTrackIndex", vodTrack[0], vodTrack[1], vodTrack[2], vodTrack[3], vodTrack[4], vodTrack[5]); } @@ -4027,12 +3509,10 @@ void OBSBasicSettings::SaveAudioSettings() sampleRate = 48000; if (WidgetChanged(ui->sampleRate)) - config_set_uint(main->Config(), "Audio", "SampleRate", - sampleRate); + config_set_uint(main->Config(), "Audio", "SampleRate", sampleRate); if (WidgetChanged(ui->channelSetup)) - config_set_string(main->Config(), "Audio", "ChannelSetup", - channelSetup); + config_set_string(main->Config(), "Audio", "ChannelSetup", channelSetup); if (WidgetChanged(ui->meterDecayRate)) { double meterDecayRate; @@ -4050,26 +3530,21 @@ void OBSBasicSettings::SaveAudioSettings() meterDecayRate = VOLUME_METER_DECAY_FAST; break; } - config_set_double(main->Config(), "Audio", "MeterDecayRate", - meterDecayRate); + config_set_double(main->Config(), "Audio", "MeterDecayRate", meterDecayRate); main->UpdateVolumeControlsDecayRate(); } if (WidgetChanged(ui->peakMeterType)) { uint32_t peakMeterTypeIdx = ui->peakMeterType->currentIndex(); - config_set_uint(main->Config(), "Audio", "PeakMeterType", - peakMeterTypeIdx); + config_set_uint(main->Config(), "Audio", "PeakMeterType", peakMeterTypeIdx); main->UpdateVolumeControlsPeakMeterType(); } if (WidgetChanged(ui->lowLatencyBuffering)) { - bool enableLLAudioBuffering = - ui->lowLatencyBuffering->isChecked(); - config_set_bool(App()->GetUserConfig(), "Audio", - "LowLatencyAudioBuffering", - enableLLAudioBuffering); + bool enableLLAudioBuffering = ui->lowLatencyBuffering->isChecked(); + config_set_bool(App()->GetUserConfig(), "Audio", "LowLatencyAudioBuffering", enableLLAudioBuffering); } for (auto &audioSource : audioSources) { @@ -4089,18 +3564,13 @@ void OBSBasicSettings::SaveAudioSettings() obs_source_set_push_to_talk_delay(source, pttSB->value()); } - auto UpdateAudioDevice = [this](bool input, QComboBox *combo, - const char *name, int index) { - main->ResetAudioDevice(input ? App()->InputAudioSource() - : App()->OutputAudioSource(), - QT_TO_UTF8(GetComboData(combo)), - Str(name), index); + auto UpdateAudioDevice = [this](bool input, QComboBox *combo, const char *name, int index) { + main->ResetAudioDevice(input ? App()->InputAudioSource() : App()->OutputAudioSource(), + QT_TO_UTF8(GetComboData(combo)), Str(name), index); }; - UpdateAudioDevice(false, ui->desktopAudioDevice1, - "Basic.DesktopDevice1", 1); - UpdateAudioDevice(false, ui->desktopAudioDevice2, - "Basic.DesktopDevice2", 2); + UpdateAudioDevice(false, ui->desktopAudioDevice1, "Basic.DesktopDevice1", 1); + UpdateAudioDevice(false, ui->desktopAudioDevice2, "Basic.DesktopDevice2", 2); UpdateAudioDevice(true, ui->auxAudioDevice1, "Basic.AuxDevice1", 3); UpdateAudioDevice(true, ui->auxAudioDevice2, "Basic.AuxDevice2", 4); UpdateAudioDevice(true, ui->auxAudioDevice3, "Basic.AuxDevice3", 5); @@ -4137,10 +3607,8 @@ void OBSBasicSettings::SaveHotkeySettings() const char *id = obs_obj_get_id(main->outputHandler->replayBuffer); if (strcmp(id, "replay_buffer") == 0) { - OBSDataAutoRelease hotkeys = obs_hotkeys_save_output( - main->outputHandler->replayBuffer); - config_set_string(config, "Hotkeys", "ReplayBuffer", - obs_data_get_json(hotkeys)); + OBSDataAutoRelease hotkeys = obs_hotkeys_save_output(main->outputHandler->replayBuffer); + config_set_string(config, "Hotkeys", "ReplayBuffer", obs_data_get_json(hotkeys)); } } @@ -4206,11 +3674,9 @@ void OBSBasicSettings::SaveSettings() } bool langChanged = (ui->language->currentIndex() != prevLangIndex); - bool audioRestart = (ui->channelSetup->currentIndex() != channelIndex || - ui->sampleRate->currentIndex() != sampleRateIndex); - bool browserHWAccelChanged = - (ui->browserHWAccel && - ui->browserHWAccel->isChecked() != prevBrowserAccel); + bool audioRestart = + (ui->channelSetup->currentIndex() != channelIndex || ui->sampleRate->currentIndex() != sampleRateIndex); + bool browserHWAccelChanged = (ui->browserHWAccel && ui->browserHWAccel->isChecked() != prevBrowserAccel); if (langChanged || audioRestart || browserHWAccelChanged) restart = true; @@ -4222,10 +3688,8 @@ bool OBSBasicSettings::QueryChanges() { QMessageBox::StandardButton button; - button = OBSMessageBox::question( - this, QTStr("Basic.Settings.ConfirmTitle"), - QTStr("Basic.Settings.Confirm"), - QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); + button = OBSMessageBox::question(this, QTStr("Basic.Settings.ConfirmTitle"), QTStr("Basic.Settings.Confirm"), + QMessageBox::Yes | QMessageBox::No | QMessageBox::Cancel); if (button == QMessageBox::Cancel) { return false; @@ -4254,27 +3718,20 @@ bool OBSBasicSettings::QueryAllowedToClose() bool invalidFormat = false; bool invalidTracks = false; if (simple) { - if (ui->simpleOutRecEncoder->currentIndex() == -1 || - ui->simpleOutStrEncoder->currentIndex() == -1 || - ui->simpleOutRecAEncoder->currentIndex() == -1 || - ui->simpleOutStrAEncoder->currentIndex() == -1) + if (ui->simpleOutRecEncoder->currentIndex() == -1 || ui->simpleOutStrEncoder->currentIndex() == -1 || + ui->simpleOutRecAEncoder->currentIndex() == -1 || ui->simpleOutStrAEncoder->currentIndex() == -1) invalidEncoder = true; if (ui->simpleOutRecFormat->currentIndex() == -1) invalidFormat = true; - QString qual = - ui->simpleOutRecQuality->currentData().toString(); - QString format = - ui->simpleOutRecFormat->currentData().toString(); - if (SimpleOutGetSelectedAudioTracks() == 0 && - qual != "Stream" && format != "flv") + QString qual = ui->simpleOutRecQuality->currentData().toString(); + QString format = ui->simpleOutRecFormat->currentData().toString(); + if (SimpleOutGetSelectedAudioTracks() == 0 && qual != "Stream" && format != "flv") invalidTracks = true; } else { - if (ui->advOutRecEncoder->currentIndex() == -1 || - ui->advOutEncoder->currentIndex() == -1 || - ui->advOutRecAEncoder->currentIndex() == -1 || - ui->advOutAEncoder->currentIndex() == -1) + if (ui->advOutRecEncoder->currentIndex() == -1 || ui->advOutEncoder->currentIndex() == -1 || + ui->advOutRecAEncoder->currentIndex() == -1 || ui->advOutAEncoder->currentIndex() == -1) invalidEncoder = true; QString format = ui->advOutRecFormat->currentData().toString(); @@ -4285,20 +3742,16 @@ bool OBSBasicSettings::QueryAllowedToClose() } if (invalidEncoder) { - OBSMessageBox::warning( - this, QTStr("CodecCompat.CodecMissingOnExit.Title"), - QTStr("CodecCompat.CodecMissingOnExit.Text")); + OBSMessageBox::warning(this, QTStr("CodecCompat.CodecMissingOnExit.Title"), + QTStr("CodecCompat.CodecMissingOnExit.Text")); return false; } else if (invalidFormat) { - OBSMessageBox::warning( - this, QTStr("CodecCompat.ContainerMissingOnExit.Title"), - QTStr("CodecCompat.ContainerMissingOnExit.Text")); + OBSMessageBox::warning(this, QTStr("CodecCompat.ContainerMissingOnExit.Title"), + QTStr("CodecCompat.ContainerMissingOnExit.Text")); return false; } else if (invalidTracks) { - OBSMessageBox::warning( - this, - QTStr("OutputWarnings.NoTracksSelectedOnExit.Title"), - QTStr("OutputWarnings.NoTracksSelectedOnExit.Text")); + OBSMessageBox::warning(this, QTStr("OutputWarnings.NoTracksSelectedOnExit.Title"), + QTStr("OutputWarnings.NoTracksSelectedOnExit.Text")); return false; } @@ -4317,10 +3770,8 @@ void OBSBasicSettings::showEvent(QShowEvent *event) /* Reduce the height of the widget area if too tall compared to the screen * size (e.g., 720p) with potential window decoration (e.g., titlebar). */ - const int titleBarHeight = - QApplication::style()->pixelMetric(QStyle::PM_TitleBarHeight); - const int maxHeight = - round(screen()->availableGeometry().height() - titleBarHeight); + const int titleBarHeight = QApplication::style()->pixelMetric(QStyle::PM_TitleBarHeight); + const int maxHeight = round(screen()->availableGeometry().height() - titleBarHeight); if (size().height() >= maxHeight) resize(size().width(), maxHeight); } @@ -4364,8 +3815,7 @@ void OBSBasicSettings::UpdateYouTubeAppDockSettings() if (!main->GetYouTubeAppDock()) { main->NewYouTubeAppDock(); } - main->GetYouTubeAppDock()->SettingsUpdated( - !IsYouTubeService(service) || stream1Changed); + main->GetYouTubeAppDock()->SettingsUpdated(!IsYouTubeService(service) || stream1Changed); } else { if (main->GetYouTubeAppDock()) { main->GetYouTubeAppDock()->AccountDisconnected(); @@ -4380,8 +3830,7 @@ void OBSBasicSettings::on_buttonBox_clicked(QAbstractButton *button) { QDialogButtonBox::ButtonRole val = ui->buttonBox->buttonRole(button); - if (val == QDialogButtonBox::ApplyRole || - val == QDialogButtonBox::AcceptRole) { + if (val == QDialogButtonBox::ApplyRole || val == QDialogButtonBox::AcceptRole) { if (!QueryAllowedToClose()) return; @@ -4391,8 +3840,7 @@ void OBSBasicSettings::on_buttonBox_clicked(QAbstractButton *button) ClearChanged(); } - if (val == QDialogButtonBox::AcceptRole || - val == QDialogButtonBox::RejectRole) { + if (val == QDialogButtonBox::AcceptRole || val == QDialogButtonBox::RejectRole) { if (val == QDialogButtonBox::RejectRole) { if (savedTheme != App()->GetTheme()) App()->SetTheme(savedTheme->id); @@ -4404,9 +3852,8 @@ void OBSBasicSettings::on_buttonBox_clicked(QAbstractButton *button) void OBSBasicSettings::on_simpleOutputBrowse_clicked() { - QString dir = SelectDirectory( - this, QTStr("Basic.Settings.Output.SelectDirectory"), - ui->simpleOutputPath->text()); + QString dir = + SelectDirectory(this, QTStr("Basic.Settings.Output.SelectDirectory"), ui->simpleOutputPath->text()); if (dir.isEmpty()) return; @@ -4415,9 +3862,7 @@ void OBSBasicSettings::on_simpleOutputBrowse_clicked() void OBSBasicSettings::on_advOutRecPathBrowse_clicked() { - QString dir = SelectDirectory( - this, QTStr("Basic.Settings.Output.SelectDirectory"), - ui->advOutRecPath->text()); + QString dir = SelectDirectory(this, QTStr("Basic.Settings.Output.SelectDirectory"), ui->advOutRecPath->text()); if (dir.isEmpty()) return; @@ -4426,9 +3871,7 @@ void OBSBasicSettings::on_advOutRecPathBrowse_clicked() void OBSBasicSettings::on_advOutFFPathBrowse_clicked() { - QString dir = SelectDirectory( - this, QTStr("Basic.Settings.Output.SelectDirectory"), - ui->advOutRecPath->text()); + QString dir = SelectDirectory(this, QTStr("Basic.Settings.Output.SelectDirectory"), ui->advOutRecPath->text()); if (dir.isEmpty()) return; @@ -4442,11 +3885,9 @@ void OBSBasicSettings::on_advOutEncoder_currentIndexChanged() bool loadSettings = encoder == curAdvStreamEncoder; delete streamEncoderProps; - streamEncoderProps = CreateEncoderPropertyView( - QT_TO_UTF8(encoder), - loadSettings ? "streamEncoder.json" : nullptr, true); - streamEncoderProps->setSizePolicy(QSizePolicy::Preferred, - QSizePolicy::Minimum); + streamEncoderProps = CreateEncoderPropertyView(QT_TO_UTF8(encoder), + loadSettings ? "streamEncoder.json" : nullptr, true); + streamEncoderProps->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); ui->advOutEncoderLayout->addWidget(streamEncoderProps); } @@ -4472,13 +3913,10 @@ void OBSBasicSettings::on_advOutRecEncoder_currentIndexChanged(int idx) bool loadSettings = encoder == curAdvRecordEncoder; if (!loading) { - recordEncoderProps = CreateEncoderPropertyView( - QT_TO_UTF8(encoder), - loadSettings ? "recordEncoder.json" : nullptr, true); - recordEncoderProps->setSizePolicy(QSizePolicy::Preferred, - QSizePolicy::Minimum); - ui->advOutRecEncoderProps->layout()->addWidget( - recordEncoderProps); + recordEncoderProps = CreateEncoderPropertyView(QT_TO_UTF8(encoder), + loadSettings ? "recordEncoder.json" : nullptr, true); + recordEncoderProps->setSizePolicy(QSizePolicy::Preferred, QSizePolicy::Minimum); + ui->advOutRecEncoderProps->layout()->addWidget(recordEncoderProps); connect(recordEncoderProps, &OBSPropertiesView::Changed, this, &OBSBasicSettings::AdvReplayBufferChanged); } @@ -4491,12 +3929,10 @@ void OBSBasicSettings::on_advOutRecEncoder_currentIndexChanged(int idx) void OBSBasicSettings::on_advOutFFIgnoreCompat_stateChanged(int) { /* Little hack to reload codecs when checked */ - on_advOutFFFormat_currentIndexChanged( - ui->advOutFFFormat->currentIndex()); + on_advOutFFFormat_currentIndexChanged(ui->advOutFFFormat->currentIndex()); } -#define DEFAULT_CONTAINER_STR \ - QTStr("Basic.Settings.Output.Adv.FFmpeg.FormatDescDef") +#define DEFAULT_CONTAINER_STR QTStr("Basic.Settings.Output.Adv.FFmpeg.FormatDescDef") void OBSBasicSettings::on_advOutFFFormat_currentIndexChanged(int idx) { @@ -4504,22 +3940,16 @@ void OBSBasicSettings::on_advOutFFFormat_currentIndexChanged(int idx) if (!itemDataVariant.isNull()) { auto format = itemDataVariant.value(); - SetAdvOutputFFmpegEnablement(FFmpegCodecType::AUDIO, - format.HasAudio(), false); - SetAdvOutputFFmpegEnablement(FFmpegCodecType::VIDEO, - format.HasVideo(), false); + SetAdvOutputFFmpegEnablement(FFmpegCodecType::AUDIO, format.HasAudio(), false); + SetAdvOutputFFmpegEnablement(FFmpegCodecType::VIDEO, format.HasVideo(), false); ReloadCodecs(format); ui->advOutFFFormatDesc->setText(format.long_name); - FFmpegCodec defaultAudioCodecDesc = - format.GetDefaultEncoder(FFmpegCodecType::AUDIO); - FFmpegCodec defaultVideoCodecDesc = - format.GetDefaultEncoder(FFmpegCodecType::VIDEO); - SelectEncoder(ui->advOutFFAEncoder, defaultAudioCodecDesc.name, - defaultAudioCodecDesc.id); - SelectEncoder(ui->advOutFFVEncoder, defaultVideoCodecDesc.name, - defaultVideoCodecDesc.id); + FFmpegCodec defaultAudioCodecDesc = format.GetDefaultEncoder(FFmpegCodecType::AUDIO); + FFmpegCodec defaultVideoCodecDesc = format.GetDefaultEncoder(FFmpegCodecType::VIDEO); + SelectEncoder(ui->advOutFFAEncoder, defaultAudioCodecDesc.name, defaultAudioCodecDesc.id); + SelectEncoder(ui->advOutFFVEncoder, defaultVideoCodecDesc.name, defaultVideoCodecDesc.id); } else { ui->advOutFFAEncoder->blockSignals(true); ui->advOutFFVEncoder->blockSignals(true); @@ -4535,9 +3965,7 @@ void OBSBasicSettings::on_advOutFFAEncoder_currentIndexChanged(int idx) const QVariant itemDataVariant = ui->advOutFFAEncoder->itemData(idx); if (!itemDataVariant.isNull()) { auto desc = itemDataVariant.value(); - SetAdvOutputFFmpegEnablement( - FFmpegCodecType::AUDIO, - desc.id != 0 || desc.name != nullptr, true); + SetAdvOutputFFmpegEnablement(FFmpegCodecType::AUDIO, desc.id != 0 || desc.name != nullptr, true); } } @@ -4546,9 +3974,7 @@ void OBSBasicSettings::on_advOutFFVEncoder_currentIndexChanged(int idx) const QVariant itemDataVariant = ui->advOutFFVEncoder->itemData(idx); if (!itemDataVariant.isNull()) { auto desc = itemDataVariant.value(); - SetAdvOutputFFmpegEnablement( - FFmpegCodecType::VIDEO, - desc.id != 0 || desc.name != nullptr, true); + SetAdvOutputFFmpegEnablement(FFmpegCodecType::VIDEO, desc.id != 0 || desc.name != nullptr, true); } } @@ -4605,8 +4031,7 @@ void OBSBasicSettings::RecalcOutputResPixels(const char *resText) ui->scaledAspect->setText( QTStr("AspectRatio") - .arg(QString::number(std::get<0>(aspect)), - QString::number(std::get<1>(aspect)))); + .arg(QString::number(std::get<0>(aspect)), QString::number(std::get<1>(aspect)))); } } @@ -4667,8 +4092,7 @@ void OBSBasicSettings::on_baseResolution_editTextChanged(const QString &text) ui->baseAspect->setText( QTStr("AspectRatio") - .arg(QString::number(std::get<0>(aspect)), - QString::number(std::get<1>(aspect)))); + .arg(QString::number(std::get<0>(aspect)), QString::number(std::get<1>(aspect)))); ResetDownscales(cx, cy); } @@ -4719,14 +4143,11 @@ void OBSBasicSettings::AudioChangedRestart() if (!loading) { int currentChannelIndex = ui->channelSetup->currentIndex(); int currentSampleRateIndex = ui->sampleRate->currentIndex(); - bool currentLLAudioBufVal = - ui->lowLatencyBuffering->isChecked(); + bool currentLLAudioBufVal = ui->lowLatencyBuffering->isChecked(); - if (currentChannelIndex != channelIndex || - currentSampleRateIndex != sampleRateIndex || + if (currentChannelIndex != channelIndex || currentSampleRateIndex != sampleRateIndex || currentLLAudioBufVal != llBufferingEnabled) { - ui->audioMsg->setText( - QTStr("Basic.Settings.ProgramRestart")); + ui->audioMsg->setText(QTStr("Basic.Settings.ProgramRestart")); ui->audioMsg->setVisible(true); } else { ui->audioMsg->setText(""); @@ -4750,8 +4171,7 @@ void OBSBasicSettings::SpeakerLayoutChanged(int idx) QString speakerLayoutQstr = ui->channelSetup->itemText(idx); std::string speakerLayout = QT_TO_UTF8(speakerLayoutQstr); bool surround = IsSurround(speakerLayout.c_str()); - bool isOpus = ui->simpleOutStrAEncoder->currentData().toString() == - "opus"; + bool isOpus = ui->simpleOutStrAEncoder->currentData().toString() == "opus"; if (surround) { /* @@ -4759,31 +4179,22 @@ void OBSBasicSettings::SpeakerLayoutChanged(int idx) */ PopulateSimpleBitrates(ui->simpleOutputABitrate, isOpus); - string stream_encoder_id = ui->advOutAEncoder->currentData() - .toString() - .toStdString(); - string record_encoder_id = ui->advOutRecAEncoder->currentData() - .toString() - .toStdString(); - PopulateAdvancedBitrates( - {ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, - ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, - ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, - stream_encoder_id.c_str(), - record_encoder_id == "none" - ? stream_encoder_id.c_str() - : record_encoder_id.c_str()); + string stream_encoder_id = ui->advOutAEncoder->currentData().toString().toStdString(); + string record_encoder_id = ui->advOutRecAEncoder->currentData().toString().toStdString(); + PopulateAdvancedBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, + ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, + stream_encoder_id.c_str(), + record_encoder_id == "none" ? stream_encoder_id.c_str() + : record_encoder_id.c_str()); } else { /* * Reset audio bitrate for simple and adv mode, update list of * bitrates and save setting. */ - RestrictResetBitrates( - {ui->simpleOutputABitrate, ui->advOutTrack1Bitrate, - ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, - ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, - ui->advOutTrack6Bitrate}, - 320); + RestrictResetBitrates({ui->simpleOutputABitrate, ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, + ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, + ui->advOutTrack6Bitrate}, + 320); SaveCombo(ui->simpleOutputABitrate, "SimpleOutput", "ABitrate"); SaveCombo(ui->advOutTrack1Bitrate, "AdvOut", "Track1Bitrate"); @@ -4806,16 +4217,13 @@ void OBSBasicSettings::HideOBSWindowWarning(int state) if (loading || state == Qt::Unchecked) return; - if (config_get_bool(App()->GetUserConfig(), "General", - "WarnedAboutHideOBSFromCapture")) + if (config_get_bool(App()->GetUserConfig(), "General", "WarnedAboutHideOBSFromCapture")) return; - OBSMessageBox::information( - this, QTStr("Basic.Settings.General.HideOBSWindowsFromCapture"), - QTStr("Basic.Settings.General.HideOBSWindowsFromCapture.Message")); + OBSMessageBox::information(this, QTStr("Basic.Settings.General.HideOBSWindowsFromCapture"), + QTStr("Basic.Settings.General.HideOBSWindowsFromCapture.Message")); - config_set_bool(App()->GetUserConfig(), "General", - "WarnedAboutHideOBSFromCapture", true); + config_set_bool(App()->GetUserConfig(), "General", "WarnedAboutHideOBSFromCapture", true); config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } @@ -4828,20 +4236,16 @@ void RestrictResetBitrates(initializer_list boxes, int maxbitrate) { for (auto box : boxes) { int idx = box->currentIndex(); - int max_bitrate = - FindClosestAvailableAudioBitrate(box, maxbitrate); + int max_bitrate = FindClosestAvailableAudioBitrate(box, maxbitrate); int count = box->count(); - int max_idx = box->findText( - QT_UTF8(std::to_string(max_bitrate).c_str())); + int max_idx = box->findText(QT_UTF8(std::to_string(max_bitrate).c_str())); for (int i = (count - 1); i > max_idx; i--) box->removeItem(i); if (idx > max_idx) { - int default_bitrate = FindClosestAvailableAudioBitrate( - box, maxbitrate / 2); - int default_idx = box->findText(QT_UTF8( - std::to_string(default_bitrate).c_str())); + int default_bitrate = FindClosestAvailableAudioBitrate(box, maxbitrate / 2); + int default_idx = box->findText(QT_UTF8(std::to_string(default_bitrate).c_str())); box->setCurrentIndex(default_idx); box->setProperty("changed", QVariant(true)); @@ -4857,8 +4261,7 @@ void OBSBasicSettings::AdvancedChangedRestart() if (!loading) { advancedChanged = true; - ui->advancedMsg->setText( - QTStr("Basic.Settings.ProgramRestart")); + ui->advancedMsg->setText(QTStr("Basic.Settings.ProgramRestart")); ui->advancedMsg->setVisible(true); sender()->setProperty("changed", QVariant(true)); EnableApplyButton(true); @@ -4889,19 +4292,16 @@ void OBSBasicSettings::HotkeysChanged() if (loading) return; - hotkeysChanged = - any_of(begin(hotkeys), end(hotkeys), - [](const pair> &hotkey) { - const auto &hw = *hotkey.second; - return hw.Changed(); - }); + hotkeysChanged = any_of(begin(hotkeys), end(hotkeys), [](const pair> &hotkey) { + const auto &hw = *hotkey.second; + return hw.Changed(); + }); if (hotkeysChanged) EnableApplyButton(true); } -void OBSBasicSettings::SearchHotkeys(const QString &text, - obs_key_combination_t filterCombo) +void OBSBasicSettings::SearchHotkeys(const QString &text, obs_key_combination_t filterCombo) { if (ui->hotkeyFormLayout->rowCount() == 0) @@ -4916,8 +4316,7 @@ void OBSBasicSettings::SearchHotkeys(const QString &text, if (!hotkeys) return; - QFormLayout *hotkeysLayout = - qobject_cast(hotkeys->layout()); + QFormLayout *hotkeysLayout = qobject_cast(hotkeys->layout()); hotkeysLayout->setEnabled(false); QString needle = text.toLower(); @@ -4927,15 +4326,13 @@ void OBSBasicSettings::SearchHotkeys(const QString &text, if (!label) continue; - OBSHotkeyLabel *item = - qobject_cast(label->widget()); + OBSHotkeyLabel *item = qobject_cast(label->widget()); if (!item) continue; QString fullname = item->property("fullName").value(); - showHotkey = needle.isEmpty() || - fullname.toLower().contains(needle); + showHotkey = needle.isEmpty() || fullname.toLower().contains(needle); if (showHotkey && !obs_key_combination_is_empty(filterCombo)) { showHotkey = false; @@ -4969,8 +4366,7 @@ void OBSBasicSettings::on_hotkeyFilterSearch_textChanged(const QString text) SearchHotkeys(text, ui->hotkeyFilterInput->key); } -void OBSBasicSettings::on_hotkeyFilterInput_KeyChanged( - obs_key_combination_t combo) +void OBSBasicSettings::on_hotkeyFilterInput_KeyChanged(obs_key_combination_t combo) { SearchHotkeys(ui->hotkeyFilterSearch->text(), combo); } @@ -5003,8 +4399,7 @@ bool OBSBasicSettings::ScanDuplicateHotkeys(QFormLayout *layout) auto label = layout->itemAt(i, QFormLayout::LabelRole); if (!label) continue; - OBSHotkeyLabel *item = - qobject_cast(label->widget()); + OBSHotkeyLabel *item = qobject_cast(label->widget()); if (!item) continue; @@ -5073,8 +4468,7 @@ void OBSBasicSettings::AdvancedChanged() void OBSBasicSettings::AdvOutSplitFileChanged() { bool splitFile = ui->advOutSplitFile->isChecked(); - int splitFileType = splitFile ? ui->advOutSplitFileType->currentIndex() - : -1; + int splitFileType = splitFile ? ui->advOutSplitFileType->currentIndex() : -1; ui->advOutSplitFileType->setEnabled(splitFile); ui->advOutSplitFileTimeLabel->setVisible(splitFileType == 0); @@ -5083,61 +4477,49 @@ void OBSBasicSettings::AdvOutSplitFileChanged() ui->advOutSplitFileSize->setVisible(splitFileType == 1); } -static void DisableIncompatibleCodecs(QComboBox *cbox, const QString &format, - const QString &formatName, +static void DisableIncompatibleCodecs(QComboBox *cbox, const QString &format, const QString &formatName, const QString &streamEncoder) { - QString strEncLabel = - QTStr("Basic.Settings.Output.Adv.Recording.UseStreamEncoder"); + QString strEncLabel = QTStr("Basic.Settings.Output.Adv.Recording.UseStreamEncoder"); QString recEncoder = cbox->currentData().toString(); /* Check if selected encoders and output format are compatible, disable incompatible items. */ bool currentCompatible = true; for (int idx = 0; idx < cbox->count(); idx++) { QString encName = cbox->itemData(idx).toString(); - string encoderId = (encName == "none") - ? streamEncoder.toStdString() - : encName.toStdString(); - QString encDisplayName = (encName == "none") - ? strEncLabel - : obs_encoder_get_display_name( - encoderId.c_str()); + string encoderId = (encName == "none") ? streamEncoder.toStdString() : encName.toStdString(); + QString encDisplayName = (encName == "none") ? strEncLabel + : obs_encoder_get_display_name(encoderId.c_str()); /* Something has gone horribly wrong and there's no encoder */ if (encoderId.empty()) continue; - if (obs_get_encoder_caps(encoderId.c_str()) & - OBS_ENCODER_CAP_DEPRECATED) { + if (obs_get_encoder_caps(encoderId.c_str()) & OBS_ENCODER_CAP_DEPRECATED) { encDisplayName += " (" + QTStr("Deprecated") + ")"; } const char *codec = obs_get_encoder_codec(encoderId.c_str()); - bool is_compatible = - ContainerSupportsCodec(format.toStdString(), codec); + bool is_compatible = ContainerSupportsCodec(format.toStdString(), codec); /* Fall back to FFmpeg check if codec not one of the built-in ones. */ if (!is_compatible && !IsBuiltinCodec(codec)) { string ext = GetFormatExt(QT_TO_UTF8(format)); - is_compatible = - FFCodecAndFormatCompatible(codec, ext.c_str()); + is_compatible = FFCodecAndFormatCompatible(codec, ext.c_str()); } - QStandardItemModel *model = - dynamic_cast(cbox->model()); + QStandardItemModel *model = dynamic_cast(cbox->model()); QStandardItem *item = model->item(idx); if (is_compatible) { - item->setFlags(Qt::ItemIsSelectable | - Qt::ItemIsEnabled); + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); } else { if (recEncoder == encName) currentCompatible = false; item->setFlags(Qt::NoItemFlags); encDisplayName += " "; - encDisplayName += QTStr("CodecCompat.Incompatible") - .arg(formatName); + encDisplayName += QTStr("CodecCompat.Incompatible").arg(formatName); } item->setText(encDisplayName); @@ -5154,8 +4536,7 @@ void OBSBasicSettings::AdvOutRecCheckCodecs() QString recFormatName = ui->advOutRecFormat->currentText(); /* Set tooltip if available */ - QString tooltip = - QTStr("Basic.Settings.Output.Format.TT." + recFormat.toUtf8()); + QString tooltip = QTStr("Basic.Settings.Output.Format.TT." + recFormat.toUtf8()); if (!tooltip.startsWith("Basic.Settings.Output")) ui->advOutRecFormat->setToolTip(tooltip); @@ -5163,15 +4544,12 @@ void OBSBasicSettings::AdvOutRecCheckCodecs() ui->advOutRecFormat->setToolTip(nullptr); QString streamEncoder = ui->advOutEncoder->currentData().toString(); - QString streamAudioEncoder = - ui->advOutAEncoder->currentData().toString(); + QString streamAudioEncoder = ui->advOutAEncoder->currentData().toString(); int oldVEncoderIdx = ui->advOutRecEncoder->currentIndex(); int oldAEncoderIdx = ui->advOutRecAEncoder->currentIndex(); - DisableIncompatibleCodecs(ui->advOutRecEncoder, recFormat, - recFormatName, streamEncoder); - DisableIncompatibleCodecs(ui->advOutRecAEncoder, recFormat, - recFormatName, streamAudioEncoder); + DisableIncompatibleCodecs(ui->advOutRecEncoder, recFormat, recFormatName, streamEncoder); + DisableIncompatibleCodecs(ui->advOutRecAEncoder, recFormat, recFormatName, streamAudioEncoder); /* Only invoke AdvOutRecCheckWarnings() if it wouldn't already have * been triggered by one of the encoder selections being reset. */ @@ -5188,8 +4566,7 @@ static void ResetInvalidSelection(QComboBox *cbox) if (idx < 0) return; - QStandardItemModel *model = - dynamic_cast(cbox->model()); + QStandardItemModel *model = dynamic_cast(cbox->model()); QStandardItem *item = model->item(idx); if (item->isEnabled()) @@ -5210,10 +4587,8 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() QString errorMsg; QString warningMsg; - uint32_t tracks = - Checked(ui->advOutRecTrack1) + Checked(ui->advOutRecTrack2) + - Checked(ui->advOutRecTrack3) + Checked(ui->advOutRecTrack4) + - Checked(ui->advOutRecTrack5) + Checked(ui->advOutRecTrack6); + uint32_t tracks = Checked(ui->advOutRecTrack1) + Checked(ui->advOutRecTrack2) + Checked(ui->advOutRecTrack3) + + Checked(ui->advOutRecTrack4) + Checked(ui->advOutRecTrack5) + Checked(ui->advOutRecTrack6); bool useStreamEncoder = ui->advOutRecEncoder->currentIndex() == 0; if (useStreamEncoder) { @@ -5238,12 +4613,10 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() warningMsg += "\n\n"; warningMsg += QTStr("OutputWarnings.MP4Recording"); - ui->autoRemux->setText( - QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4") + - " " + QTStr("Basic.Settings.Advanced.AutoRemux.MP4")); + ui->autoRemux->setText(QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4") + " " + + QTStr("Basic.Settings.Advanced.AutoRemux.MP4")); } else { - ui->autoRemux->setText( - QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4")); + ui->autoRemux->setText(QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4")); } #if defined(__APPLE__) && QT_VERSION < QT_VERSION_CHECK(6, 5, 1) @@ -5253,8 +4626,7 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() #endif // Show warning if codec selection was reset to an invalid state - if (ui->advOutRecEncoder->currentIndex() == -1 || - ui->advOutRecAEncoder->currentIndex() == -1) { + if (ui->advOutRecEncoder->currentIndex() == -1 || ui->advOutRecAEncoder->currentIndex() == -1) { if (!warningMsg.isEmpty()) warningMsg += "\n\n"; @@ -5264,11 +4636,8 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() delete advOutRecWarning; if (!errorMsg.isEmpty() || !warningMsg.isEmpty()) { - advOutRecWarning = new QLabel( - errorMsg.isEmpty() ? warningMsg : errorMsg, this); - advOutRecWarning->setProperty("class", errorMsg.isEmpty() - ? "text-warning" - : "text-danger"); + advOutRecWarning = new QLabel(errorMsg.isEmpty() ? warningMsg : errorMsg, this); + advOutRecWarning->setProperty("class", errorMsg.isEmpty() ? "text-warning" : "text-danger"); advOutRecWarning->setWordWrap(true); ui->advOutRecInfoLayout->addWidget(advOutRecWarning); @@ -5357,10 +4726,8 @@ bool EncoderAvailable(const char *encoder) void OBSBasicSettings::FillSimpleRecordingValues() { -#define ADD_QUALITY(str) \ - ui->simpleOutRecQuality->addItem( \ - QTStr("Basic.Settings.Output.Simple.RecordingQuality." str), \ - QString(str)); +#define ADD_QUALITY(str) \ + ui->simpleOutRecQuality->addItem(QTStr("Basic.Settings.Output.Simple.RecordingQuality." str), QString(str)); #define ENCODER_STR(str) QTStr("Basic.Settings.Output.Simple.Encoder." str) ADD_QUALITY("Stream"); @@ -5368,72 +4735,48 @@ void OBSBasicSettings::FillSimpleRecordingValues() ADD_QUALITY("HQ"); ADD_QUALITY("Lossless"); - ui->simpleOutRecEncoder->addItem(ENCODER_STR("Software"), - QString(SIMPLE_ENCODER_X264)); - ui->simpleOutRecEncoder->addItem(ENCODER_STR("SoftwareLowCPU"), - QString(SIMPLE_ENCODER_X264_LOWCPU)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Software"), QString(SIMPLE_ENCODER_X264)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("SoftwareLowCPU"), QString(SIMPLE_ENCODER_X264_LOWCPU)); if (EncoderAvailable("obs_qsv11")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.QSV.H264"), - QString(SIMPLE_ENCODER_QSV)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.QSV.H264"), QString(SIMPLE_ENCODER_QSV)); if (EncoderAvailable("obs_qsv11_av1")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.QSV.AV1"), - QString(SIMPLE_ENCODER_QSV_AV1)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.QSV.AV1"), QString(SIMPLE_ENCODER_QSV_AV1)); if (EncoderAvailable("ffmpeg_nvenc")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.NVENC.H264"), - QString(SIMPLE_ENCODER_NVENC)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.NVENC.H264"), QString(SIMPLE_ENCODER_NVENC)); if (EncoderAvailable("obs_nvenc_av1_tex")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.NVENC.AV1"), - QString(SIMPLE_ENCODER_NVENC_AV1)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.NVENC.AV1"), QString(SIMPLE_ENCODER_NVENC_AV1)); #ifdef ENABLE_HEVC if (EncoderAvailable("h265_texture_amf")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.AMD.HEVC"), - QString(SIMPLE_ENCODER_AMD_HEVC)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.AMD.HEVC"), QString(SIMPLE_ENCODER_AMD_HEVC)); if (EncoderAvailable("ffmpeg_hevc_nvenc")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.NVENC.HEVC"), - QString(SIMPLE_ENCODER_NVENC_HEVC)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.NVENC.HEVC"), + QString(SIMPLE_ENCODER_NVENC_HEVC)); #endif if (EncoderAvailable("h264_texture_amf")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.AMD.H264"), - QString(SIMPLE_ENCODER_AMD)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.AMD.H264"), QString(SIMPLE_ENCODER_AMD)); if (EncoderAvailable("av1_texture_amf")) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.AMD.AV1"), - QString(SIMPLE_ENCODER_AMD_AV1)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.AMD.AV1"), QString(SIMPLE_ENCODER_AMD_AV1)); if (EncoderAvailable("com.apple.videotoolbox.videoencoder.ave.avc") #ifndef __aarch64__ && os_get_emulation_status() == true #endif ) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.Apple.H264"), - QString(SIMPLE_ENCODER_APPLE_H264)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.Apple.H264"), + QString(SIMPLE_ENCODER_APPLE_H264)); #ifdef ENABLE_HEVC if (EncoderAvailable("com.apple.videotoolbox.videoencoder.ave.hevc") #ifndef __aarch64__ && os_get_emulation_status() == true #endif ) - ui->simpleOutRecEncoder->addItem( - ENCODER_STR("Hardware.Apple.HEVC"), - QString(SIMPLE_ENCODER_APPLE_HEVC)); + ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.Apple.HEVC"), + QString(SIMPLE_ENCODER_APPLE_HEVC)); #endif - if (EncoderAvailable("CoreAudio_AAC") || - EncoderAvailable("libfdk_aac") || EncoderAvailable("ffmpeg_aac")) - ui->simpleOutRecAEncoder->addItem( - QTStr("Basic.Settings.Output.Simple.Codec.AAC.Default"), - "aac"); + if (EncoderAvailable("CoreAudio_AAC") || EncoderAvailable("libfdk_aac") || EncoderAvailable("ffmpeg_aac")) + ui->simpleOutRecAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.AAC.Default"), "aac"); if (EncoderAvailable("ffmpeg_opus")) - ui->simpleOutRecAEncoder->addItem( - QTStr("Basic.Settings.Output.Simple.Codec.Opus"), - "opus"); + ui->simpleOutRecAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.Opus"), "opus"); #undef ADD_QUALITY #undef ENCODER_STR @@ -5488,8 +4831,7 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() ui->simpleOutPreset->setVisible(true); ui->simpleOutPreset->clear(); - if (encoder == SIMPLE_ENCODER_QSV || - encoder == SIMPLE_ENCODER_QSV_AV1) { + if (encoder == SIMPLE_ENCODER_QSV || encoder == SIMPLE_ENCODER_QSV_AV1) { ui->simpleOutPreset->addItem("speed", "speed"); ui->simpleOutPreset->addItem("balanced", "balanced"); ui->simpleOutPreset->addItem("quality", "quality"); @@ -5497,17 +4839,14 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() defaultPreset = "balanced"; preset = curQSVPreset; - } else if (encoder == SIMPLE_ENCODER_NVENC || - encoder == SIMPLE_ENCODER_NVENC_HEVC || + } else if (encoder == SIMPLE_ENCODER_NVENC || encoder == SIMPLE_ENCODER_NVENC_HEVC || encoder == SIMPLE_ENCODER_NVENC_AV1) { - const char *name = - get_simple_output_encoder(QT_TO_UTF8(encoder)); + const char *name = get_simple_output_encoder(QT_TO_UTF8(encoder)); const bool isFFmpegEncoder = strncmp(name, "ffmpeg_", 7) == 0; obs_properties_t *props = obs_get_encoder_properties(name); - obs_property_t *p = obs_properties_get( - props, isFFmpegEncoder ? "preset2" : "preset"); + obs_property_t *p = obs_properties_get(props, isFFmpegEncoder ? "preset2" : "preset"); size_t num = obs_property_list_item_count(p); for (size_t i = 0; i < num; i++) { const char *name = obs_property_list_item_name(p, i); @@ -5521,8 +4860,7 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() defaultPreset = "default"; preset = curNVENCPreset; - } else if (encoder == SIMPLE_ENCODER_AMD || - encoder == SIMPLE_ENCODER_AMD_HEVC) { + } else if (encoder == SIMPLE_ENCODER_AMD || encoder == SIMPLE_ENCODER_AMD_HEVC) { ui->simpleOutPreset->addItem("Speed", "speed"); ui->simpleOutPreset->addItem("Balanced", "balanced"); ui->simpleOutPreset->addItem("Quality", "quality"); @@ -5549,13 +4887,10 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() preset = curAMDAV1Preset; } else { -#define PRESET_STR(val) \ - QString(Str("Basic.Settings.Output.EncoderPreset." val)).arg(val) - ui->simpleOutPreset->addItem(PRESET_STR("ultrafast"), - "ultrafast"); +#define PRESET_STR(val) QString(Str("Basic.Settings.Output.EncoderPreset." val)).arg(val) + ui->simpleOutPreset->addItem(PRESET_STR("ultrafast"), "ultrafast"); ui->simpleOutPreset->addItem("superfast", "superfast"); - ui->simpleOutPreset->addItem(PRESET_STR("veryfast"), - "veryfast"); + ui->simpleOutPreset->addItem(PRESET_STR("veryfast"), "veryfast"); ui->simpleOutPreset->addItem("faster", "faster"); ui->simpleOutPreset->addItem(PRESET_STR("fast"), "fast"); #undef PRESET_STR @@ -5565,11 +4900,8 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() * with their setups without them knowing. */ if (ui->simpleOutPreset->findData(curPreset) == -1) { ui->simpleOutPreset->addItem(curPreset, curPreset); - QStandardItemModel *model = - qobject_cast( - ui->simpleOutPreset->model()); - QStandardItem *item = - model->item(model->rowCount() - 1); + QStandardItemModel *model = qobject_cast(ui->simpleOutPreset->model()); + QStandardItem *item = model->item(model->rowCount() - 1); item->setEnabled(false); } @@ -5585,36 +4917,29 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() } #define ESTIMATE_STR "Basic.Settings.Output.ReplayBuffer.Estimate" -#define ESTIMATE_TOO_LARGE_STR \ - "Basic.Settings.Output.ReplayBuffer.EstimateTooLarge" -#define ESTIMATE_UNKNOWN_STR \ - "Basic.Settings.Output.ReplayBuffer.EstimateUnknown" +#define ESTIMATE_TOO_LARGE_STR "Basic.Settings.Output.ReplayBuffer.EstimateTooLarge" +#define ESTIMATE_UNKNOWN_STR "Basic.Settings.Output.ReplayBuffer.EstimateUnknown" void OBSBasicSettings::UpdateAutomaticReplayBufferCheckboxes() { bool state = false; switch (ui->outputMode->currentIndex()) { case 0: { - const bool lossless = - ui->simpleOutRecQuality->currentData().toString() == - "Lossless"; + const bool lossless = ui->simpleOutRecQuality->currentData().toString() == "Lossless"; state = ui->simpleReplayBuf->isChecked(); - ui->simpleReplayBuf->setEnabled( - !obs_frontend_replay_buffer_active() && !lossless); + ui->simpleReplayBuf->setEnabled(!obs_frontend_replay_buffer_active() && !lossless); break; } case 1: { state = ui->advReplayBuf->isChecked(); bool customFFmpeg = ui->advOutRecType->currentIndex() == 1; - ui->advReplayBuf->setEnabled( - !obs_frontend_replay_buffer_active() && !customFFmpeg); + ui->advReplayBuf->setEnabled(!obs_frontend_replay_buffer_active() && !customFFmpeg); ui->advReplayBufCustomFFmpeg->setVisible(customFFmpeg); break; } } ui->replayWhileStreaming->setEnabled(state); - ui->keepReplayStreamStops->setEnabled( - state && ui->replayWhileStreaming->isChecked()); + ui->keepReplayStreamStops->setEnabled(state && ui->replayWhileStreaming->isChecked()); } void OBSBasicSettings::SimpleReplayBufferChanged() @@ -5626,8 +4951,7 @@ void OBSBasicSettings::SimpleReplayBufferChanged() ui->simpleRBMegsMax->setVisible(!streamQuality); ui->simpleRBMegsMaxLabel->setVisible(!streamQuality); - if (ui->simpleOutRecFormat->currentText().compare("flv") == 0 || - streamQuality) { + if (ui->simpleOutRecFormat->currentText().compare("flv") == 0 || streamQuality) { abitrate = ui->simpleOutputABitrate->currentText().toInt(); } else { int delta = ui->simpleOutputABitrate->currentText().toInt(); @@ -5652,24 +4976,19 @@ void OBSBasicSettings::SimpleReplayBufferChanged() uint64_t memTotal = os_get_sys_total_size(); int64_t memMaxMB = memTotal ? memTotal * 3 / 4 / 1024 / 1024 : 8192; - int64_t memMB = int64_t(seconds) * int64_t(vbitrate + abitrate) * 1000 / - 8 / 1024 / 1024; + int64_t memMB = int64_t(seconds) * int64_t(vbitrate + abitrate) * 1000 / 8 / 1024 / 1024; if (memMB < 1) memMB = 1; ui->simpleRBEstimate->setObjectName(""); if (streamQuality) { if (memMB <= memMaxMB) { - ui->simpleRBEstimate->setText( - QTStr(ESTIMATE_STR) - .arg(QString::number(int(memMB)))); + ui->simpleRBEstimate->setText(QTStr(ESTIMATE_STR).arg(QString::number(int(memMB)))); } else { ui->simpleRBEstimate->setText( QTStr(ESTIMATE_TOO_LARGE_STR) - .arg(QString::number(int(memMB)), - QString::number(int(memMaxMB)))); - ui->simpleRBEstimate->setProperty("class", - "text-warning"); + .arg(QString::number(int(memMB)), QString::number(int(memMaxMB)))); + ui->simpleRBEstimate->setProperty("class", "text-warning"); } } else { ui->simpleRBEstimate->setText(QTStr(ESTIMATE_UNKNOWN_STR)); @@ -5681,8 +5000,7 @@ void OBSBasicSettings::SimpleReplayBufferChanged() UpdateAutomaticReplayBufferCheckboxes(); } -#define TEXT_USE_STREAM_ENC \ - QTStr("Basic.Settings.Output.Adv.Recording.UseStreamEncoder") +#define TEXT_USE_STREAM_ENC QTStr("Basic.Settings.Output.Adv.Recording.UseStreamEncoder") void OBSBasicSettings::AdvReplayBufferChanged() { @@ -5705,13 +5023,11 @@ void OBSBasicSettings::AdvReplayBufferChanged() const OBSProfile ¤tProfile = main->GetCurrentProfile(); const std::filesystem::path jsonFilePath = - currentProfile.path / - std::filesystem::u8path("recordEncoder.json"); + currentProfile.path / std::filesystem::u8path("recordEncoder.json"); if (!jsonFilePath.empty()) { OBSDataAutoRelease data = - obs_data_create_from_json_file_safe( - jsonFilePath.u8string().c_str(), "bak"); + obs_data_create_from_json_file_safe(jsonFilePath.u8string().c_str(), "bak"); obs_data_apply(settings, data); } } @@ -5722,8 +5038,7 @@ void OBSBasicSettings::AdvReplayBufferChanged() if (!rateControl) rateControl = ""; - bool lossless = strcmp(rateControl, "lossless") == 0 || - ui->advOutRecType->currentIndex() == 1; + bool lossless = strcmp(rateControl, "lossless") == 0 || ui->advOutRecType->currentIndex() == 1; bool replayBufferEnabled = ui->advReplayBuf->isChecked(); int abitrate = 0; @@ -5746,13 +5061,11 @@ void OBSBasicSettings::AdvReplayBufferChanged() uint64_t memTotal = os_get_sys_total_size(); int64_t memMaxMB = memTotal ? memTotal * 3 / 4 / 1024 / 1024 : 8192; - int64_t memMB = int64_t(seconds) * int64_t(vbitrate + abitrate) * 1000 / - 8 / 1024 / 1024; + int64_t memMB = int64_t(seconds) * int64_t(vbitrate + abitrate) * 1000 / 8 / 1024 / 1024; if (memMB < 1) memMB = 1; - bool varRateControl = (astrcmpi(rateControl, "CBR") == 0 || - astrcmpi(rateControl, "VBR") == 0 || + bool varRateControl = (astrcmpi(rateControl, "CBR") == 0 || astrcmpi(rateControl, "VBR") == 0 || astrcmpi(rateControl, "ABR") == 0); if (vbitrate == 0) varRateControl = false; @@ -5763,14 +5076,11 @@ void OBSBasicSettings::AdvReplayBufferChanged() ui->advRBMegsMaxLabel->setVisible(false); if (memMB <= memMaxMB) { - ui->advRBEstimate->setText( - QTStr(ESTIMATE_STR) - .arg(QString::number(int(memMB)))); + ui->advRBEstimate->setText(QTStr(ESTIMATE_STR).arg(QString::number(int(memMB)))); } else { ui->advRBEstimate->setText( QTStr(ESTIMATE_TOO_LARGE_STR) - .arg(QString::number(int(memMB)), - QString::number(int(memMaxMB)))); + .arg(QString::number(int(memMB)), QString::number(int(memMaxMB)))); ui->advRBEstimate->setProperty("class", "text-warning"); } } else { @@ -5787,11 +5097,9 @@ void OBSBasicSettings::AdvReplayBufferChanged() UpdateAutomaticReplayBufferCheckboxes(); } -#define SIMPLE_OUTPUT_WARNING(str) \ - QTStr("Basic.Settings.Output.Simple.Warn." str) +#define SIMPLE_OUTPUT_WARNING(str) QTStr("Basic.Settings.Output.Simple.Warn." str) -static void DisableIncompatibleSimpleCodecs(QComboBox *cbox, - const QString &format) +static void DisableIncompatibleSimpleCodecs(QComboBox *cbox, const QString &format) { /* Unlike in advanced mode the available simple mode encoders are * hardcoded, so this check is also a simpler, hardcoded one. */ @@ -5807,19 +5115,15 @@ static void DisableIncompatibleSimpleCodecs(QComboBox *cbox, if (encName == "opus" || encName == "aac") { codec = encName; } else { - const char *encoder_id = - get_simple_output_encoder(QT_TO_UTF8(encName)); + const char *encoder_id = get_simple_output_encoder(QT_TO_UTF8(encName)); codec = obs_get_encoder_codec(encoder_id); } - QStandardItemModel *model = - dynamic_cast(cbox->model()); + QStandardItemModel *model = dynamic_cast(cbox->model()); QStandardItem *item = model->item(idx); - if (ContainerSupportsCodec(format.toStdString(), - codec.toStdString())) { - item->setFlags(Qt::ItemIsSelectable | - Qt::ItemIsEnabled); + if (ContainerSupportsCodec(format.toStdString(), codec.toStdString())) { + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); } else { if (encoder == encName) currentCompatible = false; @@ -5832,15 +5136,12 @@ static void DisableIncompatibleSimpleCodecs(QComboBox *cbox, cbox->setCurrentIndex(-1); } -static void DisableIncompatibleSimpleContainer(QComboBox *cbox, - const QString ¤tFormat, - const QString &vEncoder, +static void DisableIncompatibleSimpleContainer(QComboBox *cbox, const QString ¤tFormat, const QString &vEncoder, const QString &aEncoder) { /* Similar to above, but works in reverse to disable incompatible formats * based on the encoder selection. */ - string vCodec = obs_get_encoder_codec( - get_simple_output_encoder(QT_TO_UTF8(vEncoder))); + string vCodec = obs_get_encoder_codec(get_simple_output_encoder(QT_TO_UTF8(vEncoder))); string aCodec = aEncoder.toStdString(); bool currentCompatible = true; @@ -5848,14 +5149,11 @@ static void DisableIncompatibleSimpleContainer(QComboBox *cbox, QString format = cbox->itemData(idx).toString(); string formatStr = format.toStdString(); - QStandardItemModel *model = - dynamic_cast(cbox->model()); + QStandardItemModel *model = dynamic_cast(cbox->model()); QStandardItem *item = model->item(idx); - if (ContainerSupportsCodec(formatStr, vCodec) && - ContainerSupportsCodec(formatStr, aCodec)) { - item->setFlags(Qt::ItemIsSelectable | - Qt::ItemIsEnabled); + if (ContainerSupportsCodec(formatStr, vCodec) && ContainerSupportsCodec(formatStr, aCodec)) { + item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); } else { if (format == currentFormat) currentCompatible = false; @@ -5881,32 +5179,27 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() OBSDataAutoRelease videoSettings = obs_data_create(); OBSDataAutoRelease audioSettings = obs_data_create(); int oldVBitrate = ui->simpleOutputVBitrate->value(); - int oldABitrate = - ui->simpleOutputABitrate->currentText().toInt(); + int oldABitrate = ui->simpleOutputABitrate->currentText().toInt(); obs_data_set_int(videoSettings, "bitrate", oldVBitrate); obs_data_set_int(audioSettings, "bitrate", oldABitrate); - obs_service_apply_encoder_settings(service, videoSettings, - audioSettings); + obs_service_apply_encoder_settings(service, videoSettings, audioSettings); int newVBitrate = obs_data_get_int(videoSettings, "bitrate"); int newABitrate = obs_data_get_int(audioSettings, "bitrate"); if (newVBitrate < oldVBitrate) - warning = SIMPLE_OUTPUT_WARNING("VideoBitrate") - .arg(newVBitrate); + warning = SIMPLE_OUTPUT_WARNING("VideoBitrate").arg(newVBitrate); if (newABitrate < oldABitrate) { if (!warning.isEmpty()) warning += "\n\n"; - warning += SIMPLE_OUTPUT_WARNING("AudioBitrate") - .arg(newABitrate); + warning += SIMPLE_OUTPUT_WARNING("AudioBitrate").arg(newABitrate); } } QString format = ui->simpleOutRecFormat->currentData().toString(); /* Set tooltip if available */ - QString tooltip = - QTStr("Basic.Settings.Output.Format.TT." + format.toUtf8()); + QString tooltip = QTStr("Basic.Settings.Output.Format.TT." + format.toUtf8()); if (!tooltip.startsWith("Basic.Settings.Output")) ui->simpleOutRecFormat->setToolTip(tooltip); @@ -5922,10 +5215,8 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() } else if (qual != "Stream") { QString enc = ui->simpleOutRecEncoder->currentData().toString(); - QString streamEnc = - ui->simpleOutStrEncoder->currentData().toString(); - bool x264RecEnc = (enc == SIMPLE_ENCODER_X264 || - enc == SIMPLE_ENCODER_X264_LOWCPU); + QString streamEnc = ui->simpleOutStrEncoder->currentData().toString(); + bool x264RecEnc = (enc == SIMPLE_ENCODER_X264 || enc == SIMPLE_ENCODER_X264_LOWCPU); if (streamEnc == SIMPLE_ENCODER_X264 && x264RecEnc) { if (!warning.isEmpty()) @@ -5936,36 +5227,29 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() /* Prevent function being called recursively if changes happen. */ ui->simpleOutRecEncoder->blockSignals(true); ui->simpleOutRecAEncoder->blockSignals(true); - DisableIncompatibleSimpleCodecs(ui->simpleOutRecEncoder, - format); - DisableIncompatibleSimpleCodecs(ui->simpleOutRecAEncoder, - format); + DisableIncompatibleSimpleCodecs(ui->simpleOutRecEncoder, format); + DisableIncompatibleSimpleCodecs(ui->simpleOutRecAEncoder, format); ui->simpleOutRecAEncoder->blockSignals(false); ui->simpleOutRecEncoder->blockSignals(false); - if (ui->simpleOutRecEncoder->currentIndex() == -1 || - ui->simpleOutRecAEncoder->currentIndex() == -1) { + if (ui->simpleOutRecEncoder->currentIndex() == -1 || ui->simpleOutRecAEncoder->currentIndex() == -1) { if (!warning.isEmpty()) warning += "\n\n"; warning += QTStr("OutputWarnings.CodecIncompatible"); } } else { /* When using stream encoders do the reverse; Disable containers that are incompatible. */ - QString streamEnc = - ui->simpleOutStrEncoder->currentData().toString(); - QString streamAEnc = - ui->simpleOutStrAEncoder->currentData().toString(); + QString streamEnc = ui->simpleOutStrEncoder->currentData().toString(); + QString streamAEnc = ui->simpleOutStrAEncoder->currentData().toString(); ui->simpleOutRecFormat->blockSignals(true); - DisableIncompatibleSimpleContainer( - ui->simpleOutRecFormat, format, streamEnc, streamAEnc); + DisableIncompatibleSimpleContainer(ui->simpleOutRecFormat, format, streamEnc, streamAEnc); ui->simpleOutRecFormat->blockSignals(false); if (ui->simpleOutRecFormat->currentIndex() == -1) { if (!warning.isEmpty()) warning += "\n\n"; - warning += - SIMPLE_OUTPUT_WARNING("IncompatibleContainer"); + warning += SIMPLE_OUTPUT_WARNING("IncompatibleContainer"); } if (!warning.isEmpty()) @@ -5977,12 +5261,10 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() if (!warning.isEmpty()) warning += "\n\n"; warning += QTStr("OutputWarnings.MP4Recording"); - ui->autoRemux->setText( - QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4") + - " " + QTStr("Basic.Settings.Advanced.AutoRemux.MP4")); + ui->autoRemux->setText(QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4") + " " + + QTStr("Basic.Settings.Advanced.AutoRemux.MP4")); } else { - ui->autoRemux->setText( - QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4")); + ui->autoRemux->setText(QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4")); } if (qual == "Stream") { @@ -5991,11 +5273,9 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() ui->simpleRecTrackWidget->setCurrentWidget(ui->simpleRecTracks); } else { if (format == "flv") { - ui->simpleRecTrackWidget->setCurrentWidget( - ui->simpleFlvTracks); + ui->simpleRecTrackWidget->setCurrentWidget(ui->simpleFlvTracks); } else { - ui->simpleRecTrackWidget->setCurrentWidget( - ui->simpleRecTracks); + ui->simpleRecTrackWidget->setCurrentWidget(ui->simpleRecTracks); } } @@ -6027,21 +5307,15 @@ void OBSBasicSettings::SurroundWarning(int idx) if (surround && !wasSurround) { QMessageBox::StandardButton button; - QString warningString = QTStr("Basic.Settings.ProgramRestart") + - QStringLiteral("\n\n") + - QTStr(MULTI_CHANNEL_WARNING) + - QStringLiteral("\n\n") + + QString warningString = QTStr("Basic.Settings.ProgramRestart") + QStringLiteral("\n\n") + + QTStr(MULTI_CHANNEL_WARNING) + QStringLiteral("\n\n") + QTStr(MULTI_CHANNEL_WARNING ".Confirm"); - button = OBSMessageBox::question( - this, QTStr(MULTI_CHANNEL_WARNING ".Title"), - warningString); + button = OBSMessageBox::question(this, QTStr(MULTI_CHANNEL_WARNING ".Title"), warningString); if (button == QMessageBox::No) { - QMetaObject::invokeMethod( - ui->channelSetup, "setCurrentIndex", - Qt::QueuedConnection, - Q_ARG(int, lastChannelSetupIdx)); + QMetaObject::invokeMethod(ui->channelSetup, "setCurrentIndex", Qt::QueuedConnection, + Q_ARG(int, lastChannelSetupIdx)); return; } } @@ -6060,16 +5334,14 @@ void OBSBasicSettings::UpdateAudioWarnings() QString text; if (surround) { - text = QTStr(MULTI_CHANNEL_WARNING ".Enabled") + - QStringLiteral("\n\n") + QTStr(MULTI_CHANNEL_WARNING); + text = QTStr(MULTI_CHANNEL_WARNING ".Enabled") + QStringLiteral("\n\n") + QTStr(MULTI_CHANNEL_WARNING); } if (lowBufferingActive) { if (!text.isEmpty()) text += QStringLiteral("\n\n"); - text += QTStr(LL_BUFFERING_WARNING ".Enabled") + - QStringLiteral("\n\n") + QTStr(LL_BUFFERING_WARNING); + text += QTStr(LL_BUFFERING_WARNING ".Enabled") + QStringLiteral("\n\n") + QTStr(LL_BUFFERING_WARNING); } ui->audioMsg_2->setText(text); @@ -6079,24 +5351,19 @@ void OBSBasicSettings::UpdateAudioWarnings() void OBSBasicSettings::LowLatencyBufferingChanged(bool checked) { if (checked) { - QString warningStr = QTStr(LL_BUFFERING_WARNING) + - QStringLiteral("\n\n") + - QTStr(LL_BUFFERING_WARNING ".Confirm"); + QString warningStr = + QTStr(LL_BUFFERING_WARNING) + QStringLiteral("\n\n") + QTStr(LL_BUFFERING_WARNING ".Confirm"); - auto button = OBSMessageBox::question( - this, QTStr(LL_BUFFERING_WARNING ".Title"), warningStr); + auto button = OBSMessageBox::question(this, QTStr(LL_BUFFERING_WARNING ".Title"), warningStr); if (button == QMessageBox::No) { - QMetaObject::invokeMethod(ui->lowLatencyBuffering, - "setChecked", - Qt::QueuedConnection, + QMetaObject::invokeMethod(ui->lowLatencyBuffering, "setChecked", Qt::QueuedConnection, Q_ARG(bool, false)); return; } } - QMetaObject::invokeMethod(this, "UpdateAudioWarnings", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "UpdateAudioWarnings", Qt::QueuedConnection); QMetaObject::invokeMethod(this, "AudioChangedRestart"); } @@ -6115,19 +5382,14 @@ void OBSBasicSettings::SimpleRecordingQualityLosslessWarning(int idx) if (qual == "Lossless") { QMessageBox::StandardButton button; - QString warningString = SIMPLE_OUTPUT_WARNING("Lossless") + - QString("\n\n") + - SIMPLE_OUTPUT_WARNING("Lossless.Msg"); + QString warningString = + SIMPLE_OUTPUT_WARNING("Lossless") + QString("\n\n") + SIMPLE_OUTPUT_WARNING("Lossless.Msg"); - button = OBSMessageBox::question( - this, SIMPLE_OUTPUT_WARNING("Lossless.Title"), - warningString); + button = OBSMessageBox::question(this, SIMPLE_OUTPUT_WARNING("Lossless.Title"), warningString); if (button == QMessageBox::No) { - QMetaObject::invokeMethod( - ui->simpleOutRecQuality, "setCurrentIndex", - Qt::QueuedConnection, - Q_ARG(int, lastSimpleRecQualityIdx)); + QMetaObject::invokeMethod(ui->simpleOutRecQuality, "setCurrentIndex", Qt::QueuedConnection, + Q_ARG(int, lastSimpleRecQualityIdx)); return; } } @@ -6266,12 +5528,10 @@ int OBSBasicSettings::SimpleOutGetSelectedAudioTracks() int OBSBasicSettings::AdvOutGetSelectedAudioTracks() { - int tracks = (ui->advOutRecTrack1->isChecked() ? (1 << 0) : 0) | - (ui->advOutRecTrack2->isChecked() ? (1 << 1) : 0) | - (ui->advOutRecTrack3->isChecked() ? (1 << 2) : 0) | - (ui->advOutRecTrack4->isChecked() ? (1 << 3) : 0) | - (ui->advOutRecTrack5->isChecked() ? (1 << 4) : 0) | - (ui->advOutRecTrack6->isChecked() ? (1 << 5) : 0); + int tracks = + (ui->advOutRecTrack1->isChecked() ? (1 << 0) : 0) | (ui->advOutRecTrack2->isChecked() ? (1 << 1) : 0) | + (ui->advOutRecTrack3->isChecked() ? (1 << 2) : 0) | (ui->advOutRecTrack4->isChecked() ? (1 << 3) : 0) | + (ui->advOutRecTrack5->isChecked() ? (1 << 4) : 0) | (ui->advOutRecTrack6->isChecked() ? (1 << 5) : 0); return tracks; } @@ -6296,8 +5556,7 @@ void OBSBasicSettings::RecreateOutputResolutionWidget() delete ui->outputResolution; ui->outputResolution = new QComboBox(ui->videoPage); - ui->outputResolution->setObjectName( - QString::fromUtf8("outputResolution")); + ui->outputResolution->setObjectName(QString::fromUtf8("outputResolution")); ui->outputResolution->setSizePolicy(sizePolicy); ui->outputResolution->setEditable(true); ui->outputResolution->setProperty("changed", changed); @@ -6313,8 +5572,7 @@ void OBSBasicSettings::RecreateOutputResolutionWidget() connect(ui->outputResolution, &QComboBox::editTextChanged, this, &OBSBasicSettings::on_outputResolution_editTextChanged); - ui->outputResolution->lineEdit()->setValidator( - ui->baseResolution->lineEdit()->validator()); + ui->outputResolution->lineEdit()->setValidator(ui->baseResolution->lineEdit()->validator()); } void OBSBasicSettings::UpdateAdvNetworkGroup() @@ -6349,13 +5607,11 @@ void OBSBasicSettings::UpdateMultitrackVideo() if (available && !IsCustomService()) { OBSDataAutoRelease settings = obs_data_create(); - obs_data_set_string(settings, "service", - QT_TO_UTF8(ui->service->currentText())); - OBSServiceAutoRelease temp_service = obs_service_create_private( - "rtmp_common", "auto config query service", settings); + obs_data_set_string(settings, "service", QT_TO_UTF8(ui->service->currentText())); + OBSServiceAutoRelease temp_service = + obs_service_create_private("rtmp_common", "auto config query service", settings); settings = obs_service_get_settings(temp_service); - available = obs_data_has_user_value( - settings, "multitrack_video_configuration_url"); + available = obs_data_has_user_value(settings, "multitrack_video_configuration_url"); if (!available && ui->enableMultitrackVideo->isChecked()) ui->enableMultitrackVideo->setChecked(false); } @@ -6371,46 +5627,35 @@ void OBSBasicSettings::UpdateMultitrackVideo() ui->enableMultitrackVideo->setEnabled(toggle_available); - ui->multitrackVideoMaximumAggregateBitrateLabel->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked()); - ui->multitrackVideoMaximumAggregateBitrateAuto->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked()); + ui->multitrackVideoMaximumAggregateBitrateLabel->setEnabled(toggle_available && + ui->enableMultitrackVideo->isChecked()); + ui->multitrackVideoMaximumAggregateBitrateAuto->setEnabled(toggle_available && + ui->enableMultitrackVideo->isChecked()); ui->multitrackVideoMaximumAggregateBitrate->setEnabled( toggle_available && ui->enableMultitrackVideo->isChecked() && !ui->multitrackVideoMaximumAggregateBitrateAuto->isChecked()); - ui->multitrackVideoMaximumVideoTracksLabel->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked()); - ui->multitrackVideoMaximumVideoTracksAuto->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked()); - ui->multitrackVideoMaximumVideoTracks->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked() && - !ui->multitrackVideoMaximumVideoTracksAuto->isChecked()); + ui->multitrackVideoMaximumVideoTracksLabel->setEnabled(toggle_available && + ui->enableMultitrackVideo->isChecked()); + ui->multitrackVideoMaximumVideoTracksAuto->setEnabled(toggle_available && + ui->enableMultitrackVideo->isChecked()); + ui->multitrackVideoMaximumVideoTracks->setEnabled(toggle_available && ui->enableMultitrackVideo->isChecked() && + !ui->multitrackVideoMaximumVideoTracksAuto->isChecked()); - ui->multitrackVideoStreamDumpEnable->setVisible( - available && MultitrackVideoDeveloperModeEnabled()); - ui->multitrackVideoConfigOverrideEnable->setVisible( - available && MultitrackVideoDeveloperModeEnabled()); - ui->multitrackVideoConfigOverrideLabel->setVisible( - available && MultitrackVideoDeveloperModeEnabled()); - ui->multitrackVideoConfigOverride->setVisible( - available && MultitrackVideoDeveloperModeEnabled()); + ui->multitrackVideoStreamDumpEnable->setVisible(available && MultitrackVideoDeveloperModeEnabled()); + ui->multitrackVideoConfigOverrideEnable->setVisible(available && MultitrackVideoDeveloperModeEnabled()); + ui->multitrackVideoConfigOverrideLabel->setVisible(available && MultitrackVideoDeveloperModeEnabled()); + ui->multitrackVideoConfigOverride->setVisible(available && MultitrackVideoDeveloperModeEnabled()); - ui->multitrackVideoStreamDumpEnable->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked()); - ui->multitrackVideoConfigOverrideEnable->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked()); - ui->multitrackVideoConfigOverrideLabel->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked() && - ui->multitrackVideoConfigOverrideEnable->isChecked()); - ui->multitrackVideoConfigOverride->setEnabled( - toggle_available && ui->enableMultitrackVideo->isChecked() && - ui->multitrackVideoConfigOverrideEnable->isChecked()); + ui->multitrackVideoStreamDumpEnable->setEnabled(toggle_available && ui->enableMultitrackVideo->isChecked()); + ui->multitrackVideoConfigOverrideEnable->setEnabled(toggle_available && ui->enableMultitrackVideo->isChecked()); + ui->multitrackVideoConfigOverrideLabel->setEnabled(toggle_available && ui->enableMultitrackVideo->isChecked() && + ui->multitrackVideoConfigOverrideEnable->isChecked()); + ui->multitrackVideoConfigOverride->setEnabled(toggle_available && ui->enableMultitrackVideo->isChecked() && + ui->multitrackVideoConfigOverrideEnable->isChecked()); auto update_simple_output_settings = [&](bool mtv_enabled) { - auto recording_uses_stream_encoder = - ui->simpleOutRecQuality->currentData().toString() == - "Stream"; + auto recording_uses_stream_encoder = ui->simpleOutRecQuality->currentData().toString() == "Stream"; mtv_enabled = mtv_enabled && !recording_uses_stream_encoder; ui->simpleOutputVBitrateLabel->setDisabled(mtv_enabled); @@ -6433,15 +5678,10 @@ void OBSBasicSettings::UpdateMultitrackVideo() }; auto update_advanced_output_settings = [&](bool mtv_enabled) { - auto recording_uses_stream_video_encoder = - ui->advOutRecEncoder->currentText() == - TEXT_USE_STREAM_ENC; - auto recording_uses_stream_audio_encoder = - ui->advOutRecAEncoder->currentData() == "none"; - auto disable_video = mtv_enabled && - !recording_uses_stream_video_encoder; - auto disable_audio = mtv_enabled && - !recording_uses_stream_audio_encoder; + auto recording_uses_stream_video_encoder = ui->advOutRecEncoder->currentText() == TEXT_USE_STREAM_ENC; + auto recording_uses_stream_audio_encoder = ui->advOutRecAEncoder->currentData() == "none"; + auto disable_video = mtv_enabled && !recording_uses_stream_video_encoder; + auto disable_audio = mtv_enabled && !recording_uses_stream_audio_encoder; ui->advOutAEncLabel->setDisabled(disable_audio); ui->advOutAEncoder->setDisabled(disable_audio); @@ -6458,59 +5698,45 @@ void OBSBasicSettings::UpdateMultitrackVideo() }; auto update_advanced_output_audio_tracks = [&](bool mtv_enabled) { - auto vod_track_enabled = vodTrackCheckbox && - vodTrackCheckbox->isChecked(); + auto vod_track_enabled = vodTrackCheckbox && vodTrackCheckbox->isChecked(); auto vod_track_idx_enabled = [&](size_t idx) { - return vod_track_enabled && vodTrack[idx - 1] && - vodTrack[idx - 1]->isChecked(); + return vod_track_enabled && vodTrack[idx - 1] && vodTrack[idx - 1]->isChecked(); }; auto track1_warning_visible = mtv_enabled && - (ui->advOutTrack1->isChecked() || - vod_track_idx_enabled(1)); - auto track1_disabled = track1_warning_visible && - !ui->advOutRecTrack1->isChecked(); + (ui->advOutTrack1->isChecked() || vod_track_idx_enabled(1)); + auto track1_disabled = track1_warning_visible && !ui->advOutRecTrack1->isChecked(); ui->advOutTrack1BitrateLabel->setDisabled(track1_disabled); ui->advOutTrack1Bitrate->setDisabled(track1_disabled); auto track2_warning_visible = mtv_enabled && - (ui->advOutTrack2->isChecked() || - vod_track_idx_enabled(2)); - auto track2_disabled = track2_warning_visible && - !ui->advOutRecTrack2->isChecked(); + (ui->advOutTrack2->isChecked() || vod_track_idx_enabled(2)); + auto track2_disabled = track2_warning_visible && !ui->advOutRecTrack2->isChecked(); ui->advOutTrack2BitrateLabel->setDisabled(track2_disabled); ui->advOutTrack2Bitrate->setDisabled(track2_disabled); auto track3_warning_visible = mtv_enabled && - (ui->advOutTrack3->isChecked() || - vod_track_idx_enabled(3)); - auto track3_disabled = track3_warning_visible && - !ui->advOutRecTrack3->isChecked(); + (ui->advOutTrack3->isChecked() || vod_track_idx_enabled(3)); + auto track3_disabled = track3_warning_visible && !ui->advOutRecTrack3->isChecked(); ui->advOutTrack3BitrateLabel->setDisabled(track3_disabled); ui->advOutTrack3Bitrate->setDisabled(track3_disabled); auto track4_warning_visible = mtv_enabled && - (ui->advOutTrack4->isChecked() || - vod_track_idx_enabled(4)); - auto track4_disabled = track4_warning_visible && - !ui->advOutRecTrack4->isChecked(); + (ui->advOutTrack4->isChecked() || vod_track_idx_enabled(4)); + auto track4_disabled = track4_warning_visible && !ui->advOutRecTrack4->isChecked(); ui->advOutTrack4BitrateLabel->setDisabled(track4_disabled); ui->advOutTrack4Bitrate->setDisabled(track4_disabled); auto track5_warning_visible = mtv_enabled && - (ui->advOutTrack5->isChecked() || - vod_track_idx_enabled(5)); - auto track5_disabled = track5_warning_visible && - !ui->advOutRecTrack5->isChecked(); + (ui->advOutTrack5->isChecked() || vod_track_idx_enabled(5)); + auto track5_disabled = track5_warning_visible && !ui->advOutRecTrack5->isChecked(); ui->advOutTrack5BitrateLabel->setDisabled(track5_disabled); ui->advOutTrack5Bitrate->setDisabled(track5_disabled); auto track6_warning_visible = mtv_enabled && - (ui->advOutTrack6->isChecked() || - vod_track_idx_enabled(6)); - auto track6_disabled = track6_warning_visible && - !ui->advOutRecTrack6->isChecked(); + (ui->advOutTrack6->isChecked() || vod_track_idx_enabled(6)); + auto track6_disabled = track6_warning_visible && !ui->advOutRecTrack6->isChecked(); ui->advOutTrack6BitrateLabel->setDisabled(track6_disabled); ui->advOutTrack6Bitrate->setDisabled(track6_disabled); }; @@ -6521,46 +5747,35 @@ void OBSBasicSettings::UpdateMultitrackVideo() auto service_name = ui->service->currentText(); auto custom_server = ui->customServer->text().trimmed(); - obs_properties_t *props = - obs_get_service_properties("rtmp_common"); - obs_property_t *service = - obs_properties_get(props, "service"); + obs_properties_t *props = obs_get_service_properties("rtmp_common"); + obs_property_t *service = obs_properties_get(props, "service"); settings = obs_data_create(); - obs_data_set_string(settings, "service", - QT_TO_UTF8(service_name)); + obs_data_set_string(settings, "service", QT_TO_UTF8(service_name)); obs_property_modified(service, settings); obs_properties_destroy(props); } - auto multitrack_video_name = - QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); + auto multitrack_video_name = QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); if (obs_data_has_user_value(settings, "multitrack_video_name")) - multitrack_video_name = obs_data_get_string( - settings, "multitrack_video_name"); + multitrack_video_name = obs_data_get_string(settings, "multitrack_video_name"); ui->enableMultitrackVideo->setText( - QTStr("Basic.Settings.Stream.EnableMultitrackVideo") - .arg(multitrack_video_name)); + QTStr("Basic.Settings.Stream.EnableMultitrackVideo").arg(multitrack_video_name)); - if (obs_data_has_user_value(settings, - "multitrack_video_disclaimer")) { + if (obs_data_has_user_value(settings, "multitrack_video_disclaimer")) { ui->multitrackVideoInfo->setVisible(true); - ui->multitrackVideoInfo->setText(obs_data_get_string( - settings, "multitrack_video_disclaimer")); + ui->multitrackVideoInfo->setText(obs_data_get_string(settings, "multitrack_video_disclaimer")); } else { ui->multitrackVideoInfo->setText( - QTStr("MultitrackVideo.Info") - .arg(multitrack_video_name, - ui->service->currentText())); + QTStr("MultitrackVideo.Info").arg(multitrack_video_name, ui->service->currentText())); } - auto disabled_text = - QTStr("Basic.Settings.MultitrackVideoDisabledSettings") - .arg(ui->service->currentText()) - .arg(multitrack_video_name); + auto disabled_text = QTStr("Basic.Settings.MultitrackVideoDisabledSettings") + .arg(ui->service->currentText()) + .arg(multitrack_video_name); ui->multitrackVideoNotice->setText(disabled_text); @@ -6581,9 +5796,7 @@ void OBSBasicSettings::UpdateMultitrackVideo() void OBSBasicSettings::SimpleStreamAudioEncoderChanged() { - PopulateSimpleBitrates( - ui->simpleOutputABitrate, - ui->simpleOutStrAEncoder->currentData().toString() == "opus"); + PopulateSimpleBitrates(ui->simpleOutputABitrate, ui->simpleOutStrAEncoder->currentData().toString() == "opus"); if (IsSurround(QT_TO_UTF8(ui->channelSetup->currentText()))) return; @@ -6599,18 +5812,14 @@ void OBSBasicSettings::AdvAudioEncodersChanged() if (recEncoder == "none") recEncoder = streamEncoder; - PopulateAdvancedBitrates( - {ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, - ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, - ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, - QT_TO_UTF8(streamEncoder), QT_TO_UTF8(recEncoder)); + PopulateAdvancedBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, + ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, + QT_TO_UTF8(streamEncoder), QT_TO_UTF8(recEncoder)); if (IsSurround(QT_TO_UTF8(ui->channelSetup->currentText()))) return; - RestrictResetBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, - ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, - ui->advOutTrack5Bitrate, - ui->advOutTrack6Bitrate}, + RestrictResetBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, + ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, 320); } diff --git a/UI/window-basic-settings.hpp b/UI/window-basic-settings.hpp index 846b80014..05d46fd41 100644 --- a/UI/window-basic-settings.hpp +++ b/UI/window-basic-settings.hpp @@ -74,37 +74,17 @@ std::string DeserializeConfigText(const char *value); class OBSBasicSettings : public QDialog { Q_OBJECT - Q_PROPERTY(QIcon generalIcon READ GetGeneralIcon WRITE SetGeneralIcon - DESIGNABLE true) - Q_PROPERTY(QIcon appearanceIcon READ GetAppearanceIcon WRITE - SetAppearanceIcon DESIGNABLE true) - Q_PROPERTY(QIcon streamIcon READ GetStreamIcon WRITE SetStreamIcon - DESIGNABLE true) - Q_PROPERTY(QIcon outputIcon READ GetOutputIcon WRITE SetOutputIcon - DESIGNABLE true) - Q_PROPERTY(QIcon audioIcon READ GetAudioIcon WRITE SetAudioIcon - DESIGNABLE true) - Q_PROPERTY(QIcon videoIcon READ GetVideoIcon WRITE SetVideoIcon - DESIGNABLE true) - Q_PROPERTY(QIcon hotkeysIcon READ GetHotkeysIcon WRITE SetHotkeysIcon - DESIGNABLE true) - Q_PROPERTY(QIcon accessibilityIcon READ GetAccessibilityIcon WRITE - SetAccessibilityIcon DESIGNABLE true) - Q_PROPERTY(QIcon advancedIcon READ GetAdvancedIcon WRITE SetAdvancedIcon - DESIGNABLE true) + Q_PROPERTY(QIcon generalIcon READ GetGeneralIcon WRITE SetGeneralIcon DESIGNABLE true) + Q_PROPERTY(QIcon appearanceIcon READ GetAppearanceIcon WRITE SetAppearanceIcon DESIGNABLE true) + Q_PROPERTY(QIcon streamIcon READ GetStreamIcon WRITE SetStreamIcon DESIGNABLE true) + Q_PROPERTY(QIcon outputIcon READ GetOutputIcon WRITE SetOutputIcon DESIGNABLE true) + Q_PROPERTY(QIcon audioIcon READ GetAudioIcon WRITE SetAudioIcon DESIGNABLE true) + Q_PROPERTY(QIcon videoIcon READ GetVideoIcon WRITE SetVideoIcon DESIGNABLE true) + Q_PROPERTY(QIcon hotkeysIcon READ GetHotkeysIcon WRITE SetHotkeysIcon DESIGNABLE true) + Q_PROPERTY(QIcon accessibilityIcon READ GetAccessibilityIcon WRITE SetAccessibilityIcon DESIGNABLE true) + Q_PROPERTY(QIcon advancedIcon READ GetAdvancedIcon WRITE SetAdvancedIcon DESIGNABLE true) - enum Pages { - GENERAL, - APPEARANCE, - STREAM, - OUTPUT, - AUDIO, - VIDEO, - HOTKEYS, - ACCESSIBILITY, - ADVANCED, - NUM_PAGES - }; + enum Pages { GENERAL, APPEARANCE, STREAM, OUTPUT, AUDIO, VIDEO, HOTKEYS, ACCESSIBILITY, ADVANCED, NUM_PAGES }; private: OBSBasic *main; @@ -136,8 +116,7 @@ private: int lastIgnoreRecommended = -1; int lastChannelSetupIdx = 0; - static constexpr uint32_t ENCODER_HIDE_FLAGS = - (OBS_ENCODER_CAP_DEPRECATED | OBS_ENCODER_CAP_INTERNAL); + static constexpr uint32_t ENCODER_HIDE_FLAGS = (OBS_ENCODER_CAP_DEPRECATED | OBS_ENCODER_CAP_INTERNAL); OBSTheme *savedTheme = nullptr; @@ -159,10 +138,8 @@ private: QString curAdvStreamEncoder; QString curAdvRecordEncoder; - using AudioSource_t = - std::tuple, - QPointer, QPointer, - QPointer>; + using AudioSource_t = std::tuple, QPointer, QPointer, + QPointer>; std::vector audioSources; std::vector audioSourceSignals; OBSSignal sourceCreated; @@ -183,40 +160,27 @@ private: QIcon hotkeyConflictIcon; - void SaveCombo(QComboBox *widget, const char *section, - const char *value); - void SaveComboData(QComboBox *widget, const char *section, - const char *value); - void SaveCheckBox(QAbstractButton *widget, const char *section, - const char *value, bool invert = false); - void SaveGroupBox(QGroupBox *widget, const char *section, - const char *value); - void SaveEdit(QLineEdit *widget, const char *section, - const char *value); - void SaveSpinBox(QSpinBox *widget, const char *section, - const char *value); - void SaveText(QPlainTextEdit *widget, const char *section, - const char *value); + void SaveCombo(QComboBox *widget, const char *section, const char *value); + void SaveComboData(QComboBox *widget, const char *section, const char *value); + void SaveCheckBox(QAbstractButton *widget, const char *section, const char *value, bool invert = false); + void SaveGroupBox(QGroupBox *widget, const char *section, const char *value); + void SaveEdit(QLineEdit *widget, const char *section, const char *value); + void SaveSpinBox(QSpinBox *widget, const char *section, const char *value); + void SaveText(QPlainTextEdit *widget, const char *section, const char *value); void SaveFormat(QComboBox *combo); - void SaveEncoder(QComboBox *combo, const char *section, - const char *value); + void SaveEncoder(QComboBox *combo, const char *section, const char *value); - bool ResFPSValid(obs_service_resolution *res_list, size_t res_count, - int max_fps); - void ClosestResFPS(obs_service_resolution *res_list, size_t res_count, - int max_fps, int &new_cx, int &new_cy, int &new_fps); + bool ResFPSValid(obs_service_resolution *res_list, size_t res_count, int max_fps); + void ClosestResFPS(obs_service_resolution *res_list, size_t res_count, int max_fps, int &new_cx, int &new_cy, + int &new_fps); inline bool Changed() const { - return generalChanged || appearanceChanged || outputsChanged || - stream1Changed || audioChanged || videoChanged || - advancedChanged || hotkeysChanged || a11yChanged; + return generalChanged || appearanceChanged || outputsChanged || stream1Changed || audioChanged || + videoChanged || advancedChanged || hotkeysChanged || a11yChanged; } - inline void EnableApplyButton(bool en) - { - ui->buttonBox->button(QDialogButtonBox::Apply)->setEnabled(en); - } + inline void EnableApplyButton(bool en) { ui->buttonBox->button(QDialogButtonBox::Apply)->setEnabled(en); } inline void ClearChanged() { @@ -232,10 +196,8 @@ private: EnableApplyButton(false); } - template - void HookWidget(Widget *widget, - void (WidgetParent::*signal)(SignalArgs...), + template + void HookWidget(Widget *widget, void (WidgetParent::*signal)(SignalArgs...), void (OBSBasicSettings::*slot)(SlotArgs...)) { QObject::connect(widget, signal, this, slot); @@ -259,16 +221,13 @@ private: void LoadOutputSettings(); void LoadAudioSettings(); void LoadVideoSettings(); - void - LoadHotkeySettings(obs_hotkey_id ignoreKey = OBS_INVALID_HOTKEY_ID); + void LoadHotkeySettings(obs_hotkey_id ignoreKey = OBS_INVALID_HOTKEY_ID); void LoadA11ySettings(bool presetChange = false); void LoadAppearanceSettings(bool reload = false); void LoadAdvancedSettings(); void LoadSettings(bool changedOnly); - OBSPropertiesView *CreateEncoderPropertyView(const char *encoder, - const char *path, - bool changed = false); + OBSPropertiesView *CreateEncoderPropertyView(const char *encoder, const char *path, bool changed = false); /* general */ void LoadLanguageList(); @@ -328,9 +287,7 @@ private: void LoadAdvOutputRecordingEncoderProperties(); void LoadAdvOutputFFmpegSettings(); void LoadAdvOutputAudioSettings(); - void SetAdvOutputFFmpegEnablement(FFmpegCodecType encoderType, - bool enabled, - bool enableEncode = false); + void SetAdvOutputFFmpegEnablement(FFmpegCodecType encoderType, bool enabled, bool enableEncode = false); /* audio */ void LoadListValues(QComboBox *widget, obs_property_t *prop, int index); @@ -339,8 +296,7 @@ private: /* video */ void LoadRendererList(); - void ResetDownscales(uint32_t cx, uint32_t cy, - bool ignoreAllSignals = false); + void ResetDownscales(uint32_t cx, uint32_t cy, bool ignoreAllSignals = false); void LoadDownscaleFilters(); void LoadResolutionLists(); void LoadFPSData(); @@ -372,8 +328,7 @@ private: void SaveAdvancedSettings(); void SaveSettings(); - void SearchHotkeys(const QString &text, - obs_key_combination_t filterCombo); + void SearchHotkeys(const QString &text, obs_key_combination_t filterCombo); void UpdateSimpleOutStreamDelayEstimate(); void UpdateAdvOutStreamDelayEstimate(); @@ -530,8 +485,5 @@ public: OBSBasicSettings(QWidget *parent); ~OBSBasicSettings(); - inline const QIcon &GetHotkeyConflictIcon() const - { - return hotkeyConflictIcon; - } + inline const QIcon &GetHotkeyConflictIcon() const { return hotkeyConflictIcon; } }; diff --git a/UI/window-basic-source-select.cpp b/UI/window-basic-source-select.cpp index 173913c5f..430a3f140 100644 --- a/UI/window-basic-source-select.cpp +++ b/UI/window-basic-source-select.cpp @@ -39,8 +39,7 @@ bool OBSBasicSourceSelect::EnumSources(void *data, obs_source_t *source) if (obs_source_is_hidden(source)) return true; - OBSBasicSourceSelect *window = - static_cast(data); + OBSBasicSourceSelect *window = static_cast(data); const char *name = obs_source_get_name(source); const char *id = obs_source_get_unversioned_id(source); @@ -52,14 +51,12 @@ bool OBSBasicSourceSelect::EnumSources(void *data, obs_source_t *source) bool OBSBasicSourceSelect::EnumGroups(void *data, obs_source_t *source) { - OBSBasicSourceSelect *window = - static_cast(data); + OBSBasicSourceSelect *window = static_cast(data); const char *name = obs_source_get_name(source); const char *id = obs_source_get_unversioned_id(source); if (strcmp(id, window->id) == 0) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); OBSScene scene = main->GetCurrentScene(); obs_sceneitem_t *existing = obs_scene_get_group(scene, name); @@ -72,22 +69,18 @@ bool OBSBasicSourceSelect::EnumGroups(void *data, obs_source_t *source) void OBSBasicSourceSelect::OBSSourceAdded(void *data, calldata_t *calldata) { - OBSBasicSourceSelect *window = - static_cast(data); + OBSBasicSourceSelect *window = static_cast(data); obs_source_t *source = (obs_source_t *)calldata_ptr(calldata, "source"); - QMetaObject::invokeMethod(window, "SourceAdded", - Q_ARG(OBSSource, source)); + QMetaObject::invokeMethod(window, "SourceAdded", Q_ARG(OBSSource, source)); } void OBSBasicSourceSelect::OBSSourceRemoved(void *data, calldata_t *calldata) { - OBSBasicSourceSelect *window = - static_cast(data); + OBSBasicSourceSelect *window = static_cast(data); obs_source_t *source = (obs_source_t *)calldata_ptr(calldata, "source"); - QMetaObject::invokeMethod(window, "SourceRemoved", - Q_ARG(OBSSource, source)); + QMetaObject::invokeMethod(window, "SourceRemoved", Q_ARG(OBSSource, source)); } void OBSBasicSourceSelect::SourceAdded(OBSSource source) @@ -109,8 +102,7 @@ void OBSBasicSourceSelect::SourceRemoved(OBSSource source) if (strcmp(sourceId, id) != 0) return; - QList items = - ui->sourceList->findItems(name, Qt::MatchFixedString); + QList items = ui->sourceList->findItems(name, Qt::MatchFixedString); if (!items.count()) return; @@ -130,8 +122,7 @@ static void AddSource(void *_data, obs_scene_t *scene) if (data->crop != nullptr) obs_sceneitem_set_crop(sceneitem, data->crop); if (data->blend_method != nullptr) - obs_sceneitem_set_blending_method(sceneitem, - *data->blend_method); + obs_sceneitem_set_blending_method(sceneitem, *data->blend_method); if (data->blend_mode != nullptr) obs_sceneitem_set_blending_mode(sceneitem, *data->blend_mode); @@ -148,8 +139,7 @@ char *get_new_source_name(const char *name, const char *format) dstr_copy(&new_name, name); for (;;) { - OBSSourceAutoRelease existing_source = - obs_get_source_by_name(new_name.array); + OBSSourceAutoRelease existing_source = obs_get_source_by_name(new_name.array); if (!existing_source) break; @@ -159,10 +149,8 @@ char *get_new_source_name(const char *name, const char *format) return new_name.array; } -static void AddExisting(OBSSource source, bool visible, bool duplicate, - obs_transform_info *transform, obs_sceneitem_crop *crop, - obs_blending_method *blend_method, - obs_blending_type *blend_mode) +static void AddExisting(OBSSource source, bool visible, bool duplicate, obs_transform_info *transform, + obs_sceneitem_crop *crop, obs_blending_method *blend_method, obs_blending_type *blend_mode) { OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); OBSScene scene = main->GetCurrentScene(); @@ -171,8 +159,7 @@ static void AddExisting(OBSSource source, bool visible, bool duplicate, if (duplicate) { OBSSource from = source; - char *new_name = get_new_source_name( - obs_source_get_name(source), "%s %d"); + char *new_name = get_new_source_name(obs_source_get_name(source), "%s %d"); source = obs_source_duplicate(from, new_name, false); obs_source_release(source); bfree(new_name); @@ -194,20 +181,16 @@ static void AddExisting(OBSSource source, bool visible, bool duplicate, obs_leave_graphics(); } -static void AddExisting(const char *name, bool visible, bool duplicate, - obs_transform_info *transform, obs_sceneitem_crop *crop, - obs_blending_method *blend_method, - obs_blending_type *blend_mode) +static void AddExisting(const char *name, bool visible, bool duplicate, obs_transform_info *transform, + obs_sceneitem_crop *crop, obs_blending_method *blend_method, obs_blending_type *blend_mode) { OBSSourceAutoRelease source = obs_get_source_by_name(name); if (source) { - AddExisting(source.Get(), visible, duplicate, transform, crop, - blend_method, blend_mode); + AddExisting(source.Get(), visible, duplicate, transform, crop, blend_method, blend_mode); } } -bool AddNew(QWidget *parent, const char *id, const char *name, - const bool visible, OBSSource &newSource, +bool AddNew(QWidget *parent, const char *id, const char *name, const bool visible, OBSSource &newSource, OBSSceneItem &newSceneItem) { OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); @@ -218,8 +201,7 @@ bool AddNew(QWidget *parent, const char *id, const char *name, OBSSourceAutoRelease source = obs_get_source_by_name(name); if (source && parent) { - OBSMessageBox::information(parent, QTStr("NameExists.Title"), - QTStr("NameExists.Text")); + OBSMessageBox::information(parent, QTStr("NameExists.Title"), QTStr("NameExists.Text")); } else { const char *v_id = obs_get_latest_input_type_id(id); @@ -240,9 +222,7 @@ bool AddNew(QWidget *parent, const char *id, const char *name, /* set monitoring if source monitors by default */ uint32_t flags = obs_source_get_output_flags(source); if ((flags & OBS_SOURCE_MONITOR_BY_DEFAULT) != 0) { - obs_source_set_monitoring_type( - source, - OBS_MONITORING_TYPE_MONITOR_ONLY); + obs_source_set_monitoring_type(source, OBS_MONITORING_TYPE_MONITOR_ONLY); } success = true; @@ -263,26 +243,20 @@ void OBSBasicSourceSelect::on_buttonBox_accepted() return; QString source_name = item->text(); - AddExisting(QT_TO_UTF8(source_name), visible, false, nullptr, - nullptr, nullptr, nullptr); + AddExisting(QT_TO_UTF8(source_name), visible, false, nullptr, nullptr, nullptr, nullptr); - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); - const char *scene_name = - obs_source_get_name(main->GetCurrentSceneSource()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); + const char *scene_name = obs_source_get_name(main->GetCurrentSceneSource()); auto undo = [scene_name, main](const std::string &) { - obs_source_t *scene_source = - obs_get_source_by_name(scene_name); + obs_source_t *scene_source = obs_get_source_by_name(scene_name); main->SetCurrentScene(scene_source, true); obs_source_release(scene_source); obs_scene_t *scene = obs_get_scene_by_name(scene_name); OBSSceneItem item; - auto cb = [](obs_scene_t *, obs_sceneitem_t *sceneitem, - void *data) { - OBSSceneItem &last = - *reinterpret_cast(data); + auto cb = [](obs_scene_t *, obs_sceneitem_t *sceneitem, void *data) { + OBSSceneItem &last = *reinterpret_cast(data); last = sceneitem; return true; }; @@ -292,71 +266,52 @@ void OBSBasicSourceSelect::on_buttonBox_accepted() obs_scene_release(scene); }; - auto redo = [scene_name, main, source_name, - visible](const std::string &) { - obs_source_t *scene_source = - obs_get_source_by_name(scene_name); + auto redo = [scene_name, main, source_name, visible](const std::string &) { + obs_source_t *scene_source = obs_get_source_by_name(scene_name); main->SetCurrentScene(scene_source, true); obs_source_release(scene_source); - AddExisting(QT_TO_UTF8(source_name), visible, false, - nullptr, nullptr, nullptr, nullptr); + AddExisting(QT_TO_UTF8(source_name), visible, false, nullptr, nullptr, nullptr, nullptr); }; - undo_s.add_action(QTStr("Undo.Add").arg(source_name), undo, - redo, "", ""); + undo_s.add_action(QTStr("Undo.Add").arg(source_name), undo, redo, "", ""); } else { if (ui->sourceName->text().isEmpty()) { - OBSMessageBox::warning(this, - QTStr("NoNameEntered.Title"), - QTStr("NoNameEntered.Text")); + OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); return; } OBSSceneItem item; - if (!AddNew(this, id, QT_TO_UTF8(ui->sourceName->text()), - visible, newSource, item)) + if (!AddNew(this, id, QT_TO_UTF8(ui->sourceName->text()), visible, newSource, item)) return; OBSBasic *main = OBSBasic::Get(); - std::string scene_name = - obs_source_get_name(main->GetCurrentSceneSource()); + std::string scene_name = obs_source_get_name(main->GetCurrentSceneSource()); auto undo = [scene_name, main](const std::string &data) { - OBSSourceAutoRelease source = - obs_get_source_by_name(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_name(data.c_str()); obs_source_remove(source); - OBSSourceAutoRelease scene_source = - obs_get_source_by_name(scene_name.c_str()); + OBSSourceAutoRelease scene_source = obs_get_source_by_name(scene_name.c_str()); main->SetCurrentScene(scene_source.Get(), true); }; OBSDataAutoRelease wrapper = obs_data_create(); obs_data_set_string(wrapper, "id", id); - obs_data_set_int(wrapper, "item_id", - obs_sceneitem_get_id(item)); - obs_data_set_string( - wrapper, "name", - ui->sourceName->text().toUtf8().constData()); + obs_data_set_int(wrapper, "item_id", obs_sceneitem_get_id(item)); + obs_data_set_string(wrapper, "name", ui->sourceName->text().toUtf8().constData()); obs_data_set_bool(wrapper, "visible", visible); auto redo = [scene_name, main](const std::string &data) { - OBSSourceAutoRelease scene_source = - obs_get_source_by_name(scene_name.c_str()); + OBSSourceAutoRelease scene_source = obs_get_source_by_name(scene_name.c_str()); main->SetCurrentScene(scene_source.Get(), true); - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); OBSSource source; OBSSceneItem item; - AddNew(NULL, obs_data_get_string(dat, "id"), - obs_data_get_string(dat, "name"), + AddNew(NULL, obs_data_get_string(dat, "id"), obs_data_get_string(dat, "name"), obs_data_get_bool(dat, "visible"), source, item); - obs_sceneitem_set_id(item, (int64_t)obs_data_get_int( - dat, "item_id")); + obs_sceneitem_set_id(item, (int64_t)obs_data_get_int(dat, "item_id")); }; - undo_s.add_action(QTStr("Undo.Add").arg(ui->sourceName->text()), - undo, redo, - std::string(obs_source_get_name(newSource)), - std::string(obs_data_get_json(wrapper))); + undo_s.add_action(QTStr("Undo.Add").arg(ui->sourceName->text()), undo, redo, + std::string(obs_source_get_name(newSource)), std::string(obs_data_get_json(wrapper))); } done(DialogCode::Accepted); @@ -384,8 +339,7 @@ template static inline T GetOBSRef(QListWidgetItem *item) return item->data(static_cast(QtDataRole::OBSRef)).value(); } -OBSBasicSourceSelect::OBSBasicSourceSelect(OBSBasic *parent, const char *id_, - undo_stack &undo_s) +OBSBasicSourceSelect::OBSBasicSourceSelect(OBSBasic *parent, const char *id_, undo_stack &undo_s) : QDialog(parent), ui(new Ui::OBSBasicSourceSelect), id(id_), @@ -413,28 +367,24 @@ OBSBasicSourceSelect::OBSBasicSourceSelect(OBSBasic *parent, const char *id_, installEventFilter(CreateShortcutFilter()); connect(ui->createNew, &QRadioButton::pressed, [&]() { - QPushButton *button = - ui->buttonBox->button(QDialogButtonBox::Ok); + QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok); if (!button->isEnabled()) button->setEnabled(true); }); connect(ui->selectExisting, &QRadioButton::pressed, [&]() { - QPushButton *button = - ui->buttonBox->button(QDialogButtonBox::Ok); + QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok); bool enabled = ui->sourceList->selectedItems().size() != 0; if (button->isEnabled() != enabled) button->setEnabled(enabled); }); connect(ui->sourceList, &QListWidget::itemSelectionChanged, [&]() { - QPushButton *button = - ui->buttonBox->button(QDialogButtonBox::Ok); + QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok); if (!button->isEnabled()) button->setEnabled(true); }); if (strcmp(id_, "scene") == 0) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); OBSSource curSceneSource = main->GetCurrentSceneSource(); ui->selectExisting->setChecked(true); @@ -468,6 +418,5 @@ void OBSBasicSourceSelect::SourcePaste(SourceCopyInfo &info, bool dup) if (!source) return; - AddExisting(source, info.visible, dup, &info.transform, &info.crop, - &info.blend_method, &info.blend_mode); + AddExisting(source, info.visible, dup, &info.transform, &info.crop, &info.blend_method, &info.blend_mode); } diff --git a/UI/window-basic-source-select.hpp b/UI/window-basic-source-select.hpp index e847c1357..3baadf7b3 100644 --- a/UI/window-basic-source-select.hpp +++ b/UI/window-basic-source-select.hpp @@ -48,8 +48,7 @@ private slots: void SourceRemoved(OBSSource source); public: - OBSBasicSourceSelect(OBSBasic *parent, const char *id, - undo_stack &undo_s); + OBSBasicSourceSelect(OBSBasic *parent, const char *id, undo_stack &undo_s); OBSSource newSource; diff --git a/UI/window-basic-stats.cpp b/UI/window-basic-stats.cpp index 3fed766b5..bb8ab0bd8 100644 --- a/UI/window-basic-stats.cpp +++ b/UI/window-basic-stats.cpp @@ -42,17 +42,13 @@ void OBSBasicStats::OBSFrontendEvent(enum obs_frontend_event event, void *ptr) static QString MakeTimeLeftText(int hours, int minutes) { - return QString::asprintf("%d %s, %d %s", hours, Str("Hours"), minutes, - Str("Minutes")); + return QString::asprintf("%d %s, %d %s", hours, Str("Hours"), minutes, Str("Minutes")); } -static QString MakeMissedFramesText(uint32_t total_lagged, - uint32_t total_rendered, long double num) +static QString MakeMissedFramesText(uint32_t total_lagged, uint32_t total_rendered, long double num) { return QString("%1 / %2 (%3%)") - .arg(QString::number(total_lagged), - QString::number(total_rendered), - QString::number(num, 'f', 1)); + .arg(QString::number(total_lagged), QString::number(total_rendered), QString::number(num, 'f', 1)); } OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) @@ -166,8 +162,7 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) /* --------------------------------------------- */ if (closable) - connect(closeButton, &QPushButton::clicked, - [this]() { close(); }); + connect(closeButton, &QPushButton::clicked, [this]() { close(); }); connect(resetButton, &QPushButton::clicked, [this]() { Reset(); }); delete shortcutFilter; @@ -178,8 +173,7 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) setWindowTitle(QTStr("Basic.Stats")); #ifdef __APPLE__ - setWindowIcon( - QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png"))); + setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png"))); #else setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png"))); #endif @@ -187,8 +181,7 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) setWindowModality(Qt::NonModal); setAttribute(Qt::WA_DeleteOnClose, true); - QObject::connect(&timer, &QTimer::timeout, this, - &OBSBasicStats::Update); + QObject::connect(&timer, &QTimer::timeout, this, &OBSBasicStats::Update); timer.setInterval(TIMER_INTERVAL); if (isVisible()) @@ -196,26 +189,20 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) Update(); - QObject::connect(&recTimeLeft, &QTimer::timeout, this, - &OBSBasicStats::RecordingTimeLeft); + QObject::connect(&recTimeLeft, &QTimer::timeout, this, &OBSBasicStats::RecordingTimeLeft); recTimeLeft.setInterval(REC_TIME_LEFT_INTERVAL); OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); - const char *geometry = - config_get_string(main->Config(), "Stats", "geometry"); + const char *geometry = config_get_string(main->Config(), "Stats", "geometry"); if (geometry != NULL) { - QByteArray byteArray = - QByteArray::fromBase64(QByteArray(geometry)); + QByteArray byteArray = QByteArray::fromBase64(QByteArray(geometry)); restoreGeometry(byteArray); QRect windowGeometry = normalGeometry(); if (!WindowPositionValid(windowGeometry)) { - QRect rect = - QGuiApplication::primaryScreen()->geometry(); - setGeometry(QStyle::alignedRect(Qt::LeftToRight, - Qt::AlignCenter, size(), - rect)); + QRect rect = QGuiApplication::primaryScreen()->geometry(); + setGeometry(QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), rect)); } } @@ -229,8 +216,7 @@ void OBSBasicStats::closeEvent(QCloseEvent *event) { OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); if (isVisible()) { - config_set_string(main->Config(), "Stats", "geometry", - saveGeometry().toBase64().constData()); + config_set_string(main->Config(), "Stats", "geometry", saveGeometry().toBase64().constData()); config_save_safe(main->Config(), "tmp", nullptr); } @@ -361,8 +347,7 @@ void OBSBasicStats::Update() str = QString::number(num, 'f', 1) + QStringLiteral(" ms"); renderTime->setText(str); - long double fpsFrameTime = - (long double)ovi.fps_den * 1000.0l / (long double)ovi.fps_num; + long double fpsFrameTime = (long double)ovi.fps_den * 1000.0l / (long double)ovi.fps_num; if (num > fpsFrameTime) setClasses(renderTime, "text-danger"); @@ -384,14 +369,11 @@ void OBSBasicStats::Update() total_encoded -= first_encoded; total_skipped -= first_skipped; - num = total_encoded - ? (long double)total_skipped / (long double)total_encoded - : 0.0l; + num = total_encoded ? (long double)total_skipped / (long double)total_encoded : 0.0l; num *= 100.0l; str = QString("%1 / %2 (%3%)") - .arg(QString::number(total_skipped), - QString::number(total_encoded), + .arg(QString::number(total_skipped), QString::number(total_encoded), QString::number(num, 'f', 1)); skippedFrames->setText(str); @@ -414,9 +396,7 @@ void OBSBasicStats::Update() total_rendered -= first_rendered; total_lagged -= first_lagged; - num = total_rendered - ? (long double)total_lagged / (long double)total_rendered - : 0.0l; + num = total_rendered ? (long double)total_lagged / (long double)total_rendered : 0.0l; num *= 100.0l; str = MakeMissedFramesText(total_lagged, total_rendered, num); @@ -464,9 +444,7 @@ void OBSBasicStats::RecordingTimeLeft() if (bitrates.empty()) return; - long double averageBitrate = - accumulate(bitrates.begin(), bitrates.end(), 0.0) / - (long double)bitrates.size(); + long double averageBitrate = accumulate(bitrates.begin(), bitrates.end(), 0.0) / (long double)bitrates.size(); if (averageBitrate == 0) return; @@ -513,8 +491,7 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) lastBytesSent = 0; uint64_t bitsBetween = (bytesSent - lastBytesSent) * 8; - long double timePassed = - (long double)(curTime - lastBytesSentTime) / 1000000000.0l; + long double timePassed = (long double)(curTime - lastBytesSentTime) / 1000000000.0l; kbps = (long double)bitsBetween / timePassed / 1000.0l; if (timePassed < 0.01l) @@ -528,9 +505,7 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) str = QTStr("Basic.Stats.Status.Recording"); } else { if (active) { - bool reconnecting = - output ? obs_output_reconnecting(output) - : false; + bool reconnecting = output ? obs_output_reconnecting(output) : false; if (reconnecting) { str = QTStr("Basic.Stats.Status.Reconnecting"); @@ -563,8 +538,7 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) if (!rec) { int total = output ? obs_output_get_total_frames(output) : 0; - int dropped = output ? obs_output_get_frames_dropped(output) - : 0; + int dropped = output ? obs_output_get_frames_dropped(output) : 0; if (total < first_total || dropped < first_dropped) { first_total = 0; @@ -574,13 +548,10 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) total -= first_total; dropped -= first_dropped; - num = total ? (long double)dropped / (long double)total * 100.0l - : 0.0l; + num = total ? (long double)dropped / (long double)total * 100.0l : 0.0l; str = QString("%1 / %2 (%3%)") - .arg(QString::number(dropped), - QString::number(total), - QString::number(num, 'f', 1)); + .arg(QString::number(dropped), QString::number(total), QString::number(num, 'f', 1)); droppedFrames->setText(str); if (num > 5.0l) diff --git a/UI/window-basic-status-bar.cpp b/UI/window-basic-status-bar.cpp index 04d1237d4..5bcae6f33 100644 --- a/UI/window-basic-status-bar.cpp +++ b/UI/window-basic-status-bar.cpp @@ -16,9 +16,7 @@ static constexpr float goodThreshold = 0.3333f; static constexpr float mediocreThreshold = 0.6667f; static constexpr float badThreshold = 1.0f; -StatusBarWidget::StatusBarWidget(QWidget *parent) - : QWidget(parent), - ui(new Ui::StatusBarWidget) +StatusBarWidget::StatusBarWidget(QWidget *parent) : QWidget(parent), ui(new Ui::StatusBarWidget) { ui->setupUi(this); } @@ -27,27 +25,19 @@ StatusBarWidget::~StatusBarWidget() {} OBSBasicStatusBar::OBSBasicStatusBar(QWidget *parent) : QStatusBar(parent), - excellentPixmap(QIcon(":/res/images/network-excellent.svg") - .pixmap(QSize(16, 16))), - goodPixmap( - QIcon(":/res/images/network-good.svg").pixmap(QSize(16, 16))), - mediocrePixmap(QIcon(":/res/images/network-mediocre.svg") - .pixmap(QSize(16, 16))), - badPixmap( - QIcon(":/res/images/network-bad.svg").pixmap(QSize(16, 16))), - recordingActivePixmap(QIcon(":/res/images/recording-active.svg") - .pixmap(QSize(16, 16))), - recordingPausePixmap(QIcon(":/res/images/recording-pause.svg") - .pixmap(QSize(16, 16))), - streamingActivePixmap(QIcon(":/res/images/streaming-active.svg") - .pixmap(QSize(16, 16))) + excellentPixmap(QIcon(":/res/images/network-excellent.svg").pixmap(QSize(16, 16))), + goodPixmap(QIcon(":/res/images/network-good.svg").pixmap(QSize(16, 16))), + mediocrePixmap(QIcon(":/res/images/network-mediocre.svg").pixmap(QSize(16, 16))), + badPixmap(QIcon(":/res/images/network-bad.svg").pixmap(QSize(16, 16))), + recordingActivePixmap(QIcon(":/res/images/recording-active.svg").pixmap(QSize(16, 16))), + recordingPausePixmap(QIcon(":/res/images/recording-pause.svg").pixmap(QSize(16, 16))), + streamingActivePixmap(QIcon(":/res/images/streaming-active.svg").pixmap(QSize(16, 16))) { congestionArray.reserve(congestionUpdateSeconds); statusWidget = new StatusBarWidget(this); statusWidget->ui->delayInfo->setText(""); - statusWidget->ui->droppedFrames->setText( - QTStr("DroppedFrames").arg("0", "0.0")); + statusWidget->ui->droppedFrames->setText(QTStr("DroppedFrames").arg("0", "0.0")); statusWidget->ui->statusIcon->setPixmap(inactivePixmap); statusWidget->ui->streamIcon->setPixmap(streamingInactivePixmap); statusWidget->ui->streamTime->setDisabled(true); @@ -61,13 +51,11 @@ OBSBasicStatusBar::OBSBasicStatusBar(QWidget *parent) setMinimumHeight(statusWidget->height()); UpdateIcons(); - connect(App(), &OBSApp::StyleChanged, this, - &OBSBasicStatusBar::UpdateIcons); + connect(App(), &OBSApp::StyleChanged, this, &OBSBasicStatusBar::UpdateIcons); messageTimer = new QTimer(this); messageTimer->setSingleShot(true); - connect(messageTimer, &QTimer::timeout, this, - &OBSBasicStatusBar::clearMessage); + connect(messageTimer, &QTimer::timeout, this, &OBSBasicStatusBar::clearMessage); clearMessage(); } @@ -76,8 +64,7 @@ void OBSBasicStatusBar::Activate() { if (!active) { refreshTimer = new QTimer(this); - connect(refreshTimer, &QTimer::timeout, this, - &OBSBasicStatusBar::UpdateStatusBar); + connect(refreshTimer, &QTimer::timeout, this, &OBSBasicStatusBar::UpdateStatusBar); int skipped = video_output_get_skipped_frames(obs_get_video()); int total = video_output_get_total_frames(obs_get_video()); @@ -119,8 +106,7 @@ void OBSBasicStatusBar::Deactivate() if (!streamOutput) { statusWidget->ui->streamTime->setText(QString("00:00:00")); statusWidget->ui->streamTime->setDisabled(true); - statusWidget->ui->streamIcon->setPixmap( - streamingInactivePixmap); + statusWidget->ui->streamIcon->setPixmap(streamingInactivePixmap); statusWidget->ui->statusIcon->setPixmap(inactivePixmap); statusWidget->ui->delayFrame->hide(); statusWidget->ui->issuesFrame->hide(); @@ -134,8 +120,7 @@ void OBSBasicStatusBar::Deactivate() if (!recordOutput) { statusWidget->ui->recordTime->setText(QString("00:00:00")); statusWidget->ui->recordTime->setDisabled(true); - statusWidget->ui->recordIcon->setPixmap( - recordingInactivePixmap); + statusWidget->ui->recordIcon->setPixmap(recordingInactivePixmap); totalRecordSeconds = 0; } @@ -143,8 +128,7 @@ void OBSBasicStatusBar::Deactivate() delete refreshTimer; statusWidget->ui->delayInfo->setText(""); - statusWidget->ui->droppedFrames->setText( - QTStr("DroppedFrames").arg("0", "0.0")); + statusWidget->ui->droppedFrames->setText(QTStr("DroppedFrames").arg("0", "0.0")); statusWidget->ui->kbps->setText("0 kbps"); delaySecTotal = 0; @@ -173,8 +157,7 @@ void OBSBasicStatusBar::UpdateDelayMsg() } else if (delaySecStarting && delaySecStopping) { msg = QTStr("Basic.StatusBar.DelayStartingStoppingIn"); - msg = msg.arg(QString::number(delaySecStopping), - QString::number(delaySecStarting)); + msg = msg.arg(QString::number(delaySecStopping), QString::number(delaySecStarting)); } else { msg = QTStr("Basic.StatusBar.Delay"); msg = msg.arg(QString::number(delaySecTotal)); @@ -209,8 +192,7 @@ void OBSBasicStatusBar::UpdateBandwidth() uint64_t bitsBetween = (bytesSent - lastBytesSent) * 8; - double timePassed = - double(bytesSentTime - lastBytesSentTime) / 1000000000.0; + double timePassed = double(bytesSentTime - lastBytesSentTime) / 1000000000.0; double kbitsPerSec = double(bitsBetween) / timePassed / 1000.0; @@ -218,8 +200,7 @@ void OBSBasicStatusBar::UpdateBandwidth() text += QString::number(kbitsPerSec, 'f', 0) + QString(" kbps"); statusWidget->ui->kbps->setText(text); - statusWidget->ui->kbps->setMinimumWidth( - statusWidget->ui->kbps->width()); + statusWidget->ui->kbps->setMinimumWidth(statusWidget->ui->kbps->width()); if (!statusWidget->ui->kbps->isVisible()) statusWidget->ui->kbps->show(); @@ -236,12 +217,10 @@ void OBSBasicStatusBar::UpdateCPUUsage() return; QString text; - text += QString("CPU: ") + - QString::number(main->GetCPUUsage(), 'f', 1) + QString("%"); + text += QString("CPU: ") + QString::number(main->GetCPUUsage(), 'f', 1) + QString("%"); statusWidget->ui->cpuUsage->setText(text); - statusWidget->ui->cpuUsage->setMinimumWidth( - statusWidget->ui->cpuUsage->width()); + statusWidget->ui->cpuUsage->setMinimumWidth(statusWidget->ui->cpuUsage->width()); UpdateCurrentFPS(); } @@ -252,12 +231,10 @@ void OBSBasicStatusBar::UpdateCurrentFPS() obs_get_video_info(&ovi); float targetFPS = (float)ovi.fps_num / (float)ovi.fps_den; - QString text = QString::asprintf("%.2f / %.2f FPS", - obs_get_active_fps(), targetFPS); + QString text = QString::asprintf("%.2f / %.2f FPS", obs_get_active_fps(), targetFPS); statusWidget->ui->fpsCurrent->setText(text); - statusWidget->ui->fpsCurrent->setMinimumWidth( - statusWidget->ui->fpsCurrent->width()); + statusWidget->ui->fpsCurrent->setMinimumWidth(statusWidget->ui->fpsCurrent->width()); } void OBSBasicStatusBar::UpdateStreamTime() @@ -269,16 +246,14 @@ void OBSBasicStatusBar::UpdateStreamTime() int minutes = totalMinutes % 60; int hours = totalMinutes / 60; - QString text = - QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); + QString text = QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); statusWidget->ui->streamTime->setText(text); if (streamOutput && !statusWidget->ui->streamTime->isEnabled()) statusWidget->ui->streamTime->setDisabled(false); if (reconnectTimeout > 0) { QString msg = QTStr("Basic.StatusBar.Reconnecting") - .arg(QString::number(retries), - QString::number(reconnectTimeout)); + .arg(QString::number(retries), QString::number(reconnectTimeout)); showMessage(msg); disconnected = true; statusWidget->ui->statusIcon->setPixmap(disconnectedPixmap); @@ -311,9 +286,8 @@ void OBSBasicStatusBar::UpdateRecordTime() if (recordOutput && !statusWidget->ui->recordTime->isEnabled()) statusWidget->ui->recordTime->setDisabled(false); } else { - statusWidget->ui->recordIcon->setPixmap( - streamPauseIconToggle ? recordingPauseInactivePixmap - : recordingPausePixmap); + statusWidget->ui->recordIcon->setPixmap(streamPauseIconToggle ? recordingPauseInactivePixmap + : recordingPausePixmap); streamPauseIconToggle = !streamPauseIconToggle; } @@ -328,8 +302,7 @@ void OBSBasicStatusBar::UpdateRecordTimeLabel() int minutes = totalMinutes % 60; int hours = totalMinutes / 60; - QString text = - QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); + QString text = QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); if (os_atomic_load_bool(&recording_paused)) { text += QStringLiteral(" (PAUSED)"); } @@ -354,8 +327,7 @@ void OBSBasicStatusBar::UpdateDroppedFrames() return; QString text = QTStr("DroppedFrames"); - text = text.arg(QString::number(totalDropped), - QString::number(percent, 'f', 1)); + text = text.arg(QString::number(totalDropped), QString::number(percent, 'f', 1)); statusWidget->ui->droppedFrames->setText(text); if (!statusWidget->ui->issuesFrame->isVisible()) @@ -380,8 +352,7 @@ void OBSBasicStatusBar::UpdateDroppedFrames() float congestionOverTime = avgCongestion; if (congestionArray.size() >= congestionUpdateSeconds) { - congestionOverTime = accumulate(congestionArray.begin(), - congestionArray.end(), 0.0f) / + congestionOverTime = accumulate(congestionArray.begin(), congestionArray.end(), 0.0f) / (float)congestionArray.size(); congestionArray.clear(); update = true; @@ -391,8 +362,7 @@ void OBSBasicStatusBar::UpdateDroppedFrames() if (update) { if (congestionOverTime <= excellentThreshold + EPSILON) - statusWidget->ui->statusIcon->setPixmap( - excellentPixmap); + statusWidget->ui->statusIcon->setPixmap(excellentPixmap); else if (congestionOverTime <= goodThreshold) statusWidget->ui->statusIcon->setPixmap(goodPixmap); else if (congestionOverTime <= mediocreThreshold) @@ -406,8 +376,7 @@ void OBSBasicStatusBar::UpdateDroppedFrames() void OBSBasicStatusBar::OBSOutputReconnect(void *data, calldata_t *params) { - OBSBasicStatusBar *statusBar = - reinterpret_cast(data); + OBSBasicStatusBar *statusBar = reinterpret_cast(data); int seconds = (int)calldata_int(params, "timeout_sec"); QMetaObject::invokeMethod(statusBar, "Reconnect", Q_ARG(int, seconds)); @@ -415,8 +384,7 @@ void OBSBasicStatusBar::OBSOutputReconnect(void *data, calldata_t *params) void OBSBasicStatusBar::OBSOutputReconnectSuccess(void *data, calldata_t *) { - OBSBasicStatusBar *statusBar = - reinterpret_cast(data); + OBSBasicStatusBar *statusBar = reinterpret_cast(data); QMetaObject::invokeMethod(statusBar, "ReconnectSuccess"); } @@ -426,9 +394,7 @@ void OBSBasicStatusBar::Reconnect(int seconds) OBSBasic *main = qobject_cast(parent()); if (!retries) - main->SysTrayNotify( - QTStr("Basic.SystemTray.Message.Reconnecting"), - QSystemTrayIcon::Warning); + main->SysTrayNotify(QTStr("Basic.SystemTray.Message.Reconnecting"), QSystemTrayIcon::Warning); reconnectTimeout = seconds; @@ -502,8 +468,7 @@ void OBSBasicStatusBar::UpdateStatusBar() if (diff > 10 && percentage >= 0.1f) { showMessage(QTStr("HighResourceUsage"), 4000); if (!main->isVisible() && overloadedNotify) { - main->SysTrayNotify(QTStr("HighResourceUsage"), - QSystemTrayIcon::Warning); + main->SysTrayNotify(QTStr("HighResourceUsage"), QSystemTrayIcon::Warning); overloadedNotify = false; } } @@ -535,10 +500,8 @@ void OBSBasicStatusBar::StreamStarted(obs_output_t *output) { streamOutput = OBSGetWeakRef(output); - streamSigs.emplace_back(obs_output_get_signal_handler(output), - "reconnect", OBSOutputReconnect, this); - streamSigs.emplace_back(obs_output_get_signal_handler(output), - "reconnect_success", OBSOutputReconnectSuccess, + streamSigs.emplace_back(obs_output_get_signal_handler(output), "reconnect", OBSOutputReconnect, this); + streamSigs.emplace_back(obs_output_get_signal_handler(output), "reconnect_success", OBSOutputReconnectSuccess, this); retries = 0; @@ -592,8 +555,7 @@ void OBSBasicStatusBar::RecordingUnpaused() static QPixmap GetPixmap(const QString &filename) { - QString path = obs_frontend_is_theme_dark() ? "theme:Dark/" - : ":/res/images/"; + QString path = obs_frontend_is_theme_dark() ? "theme:Dark/" : ":/res/images/"; return QIcon(path + filename).pixmap(QSize(16, 16)); } @@ -605,26 +567,22 @@ void OBSBasicStatusBar::UpdateIcons() streamingInactivePixmap = GetPixmap("streaming-inactive.svg"); recordingInactivePixmap = GetPixmap("recording-inactive.svg"); - recordingPauseInactivePixmap = - GetPixmap("recording-pause-inactive.svg"); + recordingPauseInactivePixmap = GetPixmap("recording-pause-inactive.svg"); bool streaming = obs_frontend_streaming_active(); if (!streaming) { - statusWidget->ui->streamIcon->setPixmap( - streamingInactivePixmap); + statusWidget->ui->streamIcon->setPixmap(streamingInactivePixmap); statusWidget->ui->statusIcon->setPixmap(inactivePixmap); } else { if (disconnected) - statusWidget->ui->statusIcon->setPixmap( - disconnectedPixmap); + statusWidget->ui->statusIcon->setPixmap(disconnectedPixmap); } bool recording = obs_frontend_recording_active(); if (!recording) - statusWidget->ui->recordIcon->setPixmap( - recordingInactivePixmap); + statusWidget->ui->recordIcon->setPixmap(recordingInactivePixmap); } void OBSBasicStatusBar::showMessage(const QString &message, int timeout) diff --git a/UI/window-basic-transform.cpp b/UI/window-basic-transform.cpp index 472f98d24..2e84f3519 100644 --- a/UI/window-basic-transform.cpp +++ b/UI/window-basic-transform.cpp @@ -43,45 +43,28 @@ OBSBasicTransform::OBSBasicTransform(OBSSceneItem item, OBSBasic *parent) ui->setupUi(this); - HookWidget(ui->positionX, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->positionY, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->rotation, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->sizeX, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->sizeY, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->align, COMBO_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->boundsType, COMBO_CHANGED, - &OBSBasicTransform::OnBoundsType); - HookWidget(ui->boundsAlign, COMBO_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->boundsWidth, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->boundsHeight, DSCROLL_CHANGED, - &OBSBasicTransform::OnControlChanged); - HookWidget(ui->cropLeft, ISCROLL_CHANGED, - &OBSBasicTransform::OnCropChanged); - HookWidget(ui->cropRight, ISCROLL_CHANGED, - &OBSBasicTransform::OnCropChanged); - HookWidget(ui->cropTop, ISCROLL_CHANGED, - &OBSBasicTransform::OnCropChanged); - HookWidget(ui->cropBottom, ISCROLL_CHANGED, - &OBSBasicTransform::OnCropChanged); + HookWidget(ui->positionX, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->positionY, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->rotation, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->sizeX, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->sizeY, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->align, COMBO_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->boundsType, COMBO_CHANGED, &OBSBasicTransform::OnBoundsType); + HookWidget(ui->boundsAlign, COMBO_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->boundsWidth, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->boundsHeight, DSCROLL_CHANGED, &OBSBasicTransform::OnControlChanged); + HookWidget(ui->cropLeft, ISCROLL_CHANGED, &OBSBasicTransform::OnCropChanged); + HookWidget(ui->cropRight, ISCROLL_CHANGED, &OBSBasicTransform::OnCropChanged); + HookWidget(ui->cropTop, ISCROLL_CHANGED, &OBSBasicTransform::OnCropChanged); + HookWidget(ui->cropBottom, ISCROLL_CHANGED, &OBSBasicTransform::OnCropChanged); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - HookWidget(ui->cropToBounds, &QCheckBox::checkStateChanged, - &OBSBasicTransform::OnControlChanged); + HookWidget(ui->cropToBounds, &QCheckBox::checkStateChanged, &OBSBasicTransform::OnControlChanged); #else - HookWidget(ui->cropToBounds, &QCheckBox::stateChanged, - &OBSBasicTransform::OnControlChanged); + HookWidget(ui->cropToBounds, &QCheckBox::stateChanged, &OBSBasicTransform::OnControlChanged); #endif ui->buttonBox->button(QDialogButtonBox::Close)->setDefault(true); - connect(ui->buttonBox->button(QDialogButtonBox::Reset), - &QPushButton::clicked, main, + connect(ui->buttonBox->button(QDialogButtonBox::Reset), &QPushButton::clicked, main, &OBSBasic::on_actionResetTransform_triggered); installEventFilter(CreateShortcutFilter()); @@ -93,35 +76,27 @@ OBSBasicTransform::OBSBasicTransform(OBSSceneItem item, OBSBasic *parent) std::string name = obs_source_get_name(obs_sceneitem_get_source(item)); setWindowTitle(QTStr("Basic.TransformWindow.Title").arg(name.c_str())); - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(main->GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(main->GetCurrentScene(), false); undo_data = std::string(obs_data_get_json(wrapper)); - channelChangedSignal.Connect(obs_get_signal_handler(), "channel_change", - OBSChannelChanged, this); + channelChangedSignal.Connect(obs_get_signal_handler(), "channel_change", OBSChannelChanged, this); } OBSBasicTransform::~OBSBasicTransform() { - OBSDataAutoRelease wrapper = - obs_scene_save_transform_states(main->GetCurrentScene(), false); + OBSDataAutoRelease wrapper = obs_scene_save_transform_states(main->GetCurrentScene(), false); auto undo_redo = [](const std::string &data) { - OBSDataAutoRelease dat = - obs_data_create_from_json(data.c_str()); - OBSSourceAutoRelease source = obs_get_source_by_uuid( - obs_data_get_string(dat, "scene_uuid")); - reinterpret_cast(App()->GetMainWindow()) - ->SetCurrentScene(source.Get(), true); + OBSDataAutoRelease dat = obs_data_create_from_json(data.c_str()); + OBSSourceAutoRelease source = obs_get_source_by_uuid(obs_data_get_string(dat, "scene_uuid")); + reinterpret_cast(App()->GetMainWindow())->SetCurrentScene(source.Get(), true); obs_scene_load_transform_states(data.c_str()); }; std::string redo_data(obs_data_get_json(wrapper)); if (undo_data.compare(redo_data) != 0) main->undo_s.add_action( - QTStr("Undo.Transform") - .arg(obs_source_get_name(obs_scene_get_source( - main->GetCurrentScene()))), + QTStr("Undo.Transform").arg(obs_source_get_name(obs_scene_get_source(main->GetCurrentScene()))), undo_redo, undo_redo, undo_data, redo_data); } @@ -131,26 +106,19 @@ void OBSBasicTransform::SetScene(OBSScene scene) if (scene) { OBSSource source = obs_scene_get_source(scene); - signal_handler_t *signal = - obs_source_get_signal_handler(source); + signal_handler_t *signal = obs_source_get_signal_handler(source); - sigs.emplace_back(signal, "item_transform", - OBSSceneItemTransform, this); - sigs.emplace_back(signal, "item_remove", OBSSceneItemRemoved, - this); - sigs.emplace_back(signal, "item_select", OBSSceneItemSelect, - this); - sigs.emplace_back(signal, "item_deselect", OBSSceneItemDeselect, - this); - sigs.emplace_back(signal, "item_locked", OBSSceneItemLocked, - this); + sigs.emplace_back(signal, "item_transform", OBSSceneItemTransform, this); + sigs.emplace_back(signal, "item_remove", OBSSceneItemRemoved, this); + sigs.emplace_back(signal, "item_select", OBSSceneItemSelect, this); + sigs.emplace_back(signal, "item_deselect", OBSSceneItemDeselect, this); + sigs.emplace_back(signal, "item_locked", OBSSceneItemLocked, this); } } void OBSBasicTransform::SetItem(OBSSceneItem newItem) { - QMetaObject::invokeMethod(this, "SetItemQt", - Q_ARG(OBSSceneItem, OBSSceneItem(newItem))); + QMetaObject::invokeMethod(this, "SetItemQt", Q_ARG(OBSSceneItem, OBSSceneItem(newItem))); } void OBSBasicTransform::SetEnabled(bool enable) @@ -171,8 +139,7 @@ void OBSBasicTransform::SetItemQt(OBSSceneItem newItem) void OBSBasicTransform::OBSChannelChanged(void *param, calldata_t *data) { - OBSBasicTransform *window = - reinterpret_cast(param); + OBSBasicTransform *window = reinterpret_cast(param); uint32_t channel = (uint32_t)calldata_int(data, "channel"); OBSSource source = (obs_source_t *)calldata_ptr(data, "source"); @@ -189,8 +156,7 @@ void OBSBasicTransform::OBSChannelChanged(void *param, calldata_t *data) void OBSBasicTransform::OBSSceneItemTransform(void *param, calldata_t *data) { - OBSBasicTransform *window = - reinterpret_cast(param); + OBSBasicTransform *window = reinterpret_cast(param); OBSSceneItem item = (obs_sceneitem_t *)calldata_ptr(data, "item"); if (item == window->item && !window->ignoreTransformSignal) @@ -199,8 +165,7 @@ void OBSBasicTransform::OBSSceneItemTransform(void *param, calldata_t *data) void OBSBasicTransform::OBSSceneItemRemoved(void *param, calldata_t *data) { - OBSBasicTransform *window = - reinterpret_cast(param); + OBSBasicTransform *window = reinterpret_cast(param); obs_scene_t *scene = (obs_scene_t *)calldata_ptr(data, "scene"); obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(data, "item"); @@ -210,8 +175,7 @@ void OBSBasicTransform::OBSSceneItemRemoved(void *param, calldata_t *data) void OBSBasicTransform::OBSSceneItemSelect(void *param, calldata_t *data) { - OBSBasicTransform *window = - reinterpret_cast(param); + OBSBasicTransform *window = reinterpret_cast(param); OBSSceneItem item = (obs_sceneitem_t *)calldata_ptr(data, "item"); if (item != window->item) @@ -220,22 +184,19 @@ void OBSBasicTransform::OBSSceneItemSelect(void *param, calldata_t *data) void OBSBasicTransform::OBSSceneItemDeselect(void *param, calldata_t *data) { - OBSBasicTransform *window = - reinterpret_cast(param); + OBSBasicTransform *window = reinterpret_cast(param); obs_scene_t *scene = (obs_scene_t *)calldata_ptr(data, "scene"); obs_sceneitem_t *item = (obs_sceneitem_t *)calldata_ptr(data, "item"); if (item == window->item) { - window->setWindowTitle( - QTStr("Basic.TransformWindow.NoSelectedSource")); + window->setWindowTitle(QTStr("Basic.TransformWindow.NoSelectedSource")); window->SetItem(FindASelectedItem(scene)); } } void OBSBasicTransform::OBSSceneItemLocked(void *param, calldata_t *data) { - OBSBasicTransform *window = - reinterpret_cast(param); + OBSBasicTransform *window = reinterpret_cast(param); bool locked = calldata_bool(data, "locked"); QMetaObject::invokeMethod(window, "SetEnabled", Q_ARG(bool, !locked)); @@ -396,8 +357,7 @@ template static T GetOBSRef(QListWidgetItem *item) return item->data(static_cast(QtDataRole::OBSRef)).value(); } -void OBSBasicTransform::OnSceneChanged(QListWidgetItem *current, - QListWidgetItem *) +void OBSBasicTransform::OnSceneChanged(QListWidgetItem *current, QListWidgetItem *) { if (!current) return; diff --git a/UI/window-basic-transform.hpp b/UI/window-basic-transform.hpp index 003d3b2fa..46905724f 100644 --- a/UI/window-basic-transform.hpp +++ b/UI/window-basic-transform.hpp @@ -24,10 +24,8 @@ private: bool ignoreTransformSignal = false; bool ignoreItemChange = false; - template - void HookWidget(Widget *widget, - void (WidgetParent::*signal)(SignalArgs...), + template + void HookWidget(Widget *widget, void (WidgetParent::*signal)(SignalArgs...), void (OBSBasicTransform::*slot)(SlotArgs...)) { QObject::connect(widget, signal, this, slot); diff --git a/UI/window-basic-vcam-config.cpp b/UI/window-basic-vcam-config.cpp index 86d7d4f58..7db63513f 100644 --- a/UI/window-basic-vcam-config.cpp +++ b/UI/window-basic-vcam-config.cpp @@ -7,8 +7,7 @@ #include -OBSBasicVCamConfig::OBSBasicVCamConfig(const VCamConfig &_config, - bool _vcamActive, QWidget *parent) +OBSBasicVCamConfig::OBSBasicVCamConfig(const VCamConfig &_config, bool _vcamActive, QWidget *parent) : config(_config), vcamActive(_vcamActive), activeType(_config.type), @@ -19,29 +18,21 @@ OBSBasicVCamConfig::OBSBasicVCamConfig(const VCamConfig &_config, ui->setupUi(this); - ui->outputType->addItem(QTStr("Basic.VCam.OutputType.Program"), - (int)VCamOutputType::ProgramView); - ui->outputType->addItem(QTStr("StudioMode.Preview"), - (int)VCamOutputType::PreviewOutput); - ui->outputType->addItem(QTStr("Basic.Scene"), - (int)VCamOutputType::SceneOutput); - ui->outputType->addItem(QTStr("Basic.Main.Source"), - (int)VCamOutputType::SourceOutput); + ui->outputType->addItem(QTStr("Basic.VCam.OutputType.Program"), (int)VCamOutputType::ProgramView); + ui->outputType->addItem(QTStr("StudioMode.Preview"), (int)VCamOutputType::PreviewOutput); + ui->outputType->addItem(QTStr("Basic.Scene"), (int)VCamOutputType::SceneOutput); + ui->outputType->addItem(QTStr("Basic.Main.Source"), (int)VCamOutputType::SourceOutput); - ui->outputType->setCurrentIndex( - ui->outputType->findData((int)config.type)); + ui->outputType->setCurrentIndex(ui->outputType->findData((int)config.type)); OutputTypeChanged(); - connect(ui->outputType, &QComboBox::currentIndexChanged, this, - &OBSBasicVCamConfig::OutputTypeChanged); + connect(ui->outputType, &QComboBox::currentIndexChanged, this, &OBSBasicVCamConfig::OutputTypeChanged); - connect(ui->buttonBox, &QDialogButtonBox::accepted, this, - &OBSBasicVCamConfig::UpdateConfig); + connect(ui->buttonBox, &QDialogButtonBox::accepted, this, &OBSBasicVCamConfig::UpdateConfig); } void OBSBasicVCamConfig::OutputTypeChanged() { - VCamOutputType type = - (VCamOutputType)ui->outputType->currentData().toInt(); + VCamOutputType type = (VCamOutputType)ui->outputType->currentData().toInt(); ui->outputSelection->setDisabled(false); auto list = ui->outputSelection; @@ -71,8 +62,7 @@ void OBSBasicVCamConfig::OutputTypeChanged() auto AddSource = [&](obs_source_t *source) { auto name = obs_source_get_name(source); - if (!(obs_source_get_output_flags(source) & - OBS_SOURCE_VIDEO)) + if (!(obs_source_get_output_flags(source) & OBS_SOURCE_VIDEO)) return; sources.push_back(name); @@ -81,8 +71,7 @@ void OBSBasicVCamConfig::OutputTypeChanged() obs_enum_sources( [](void *data, obs_source_t *source) { - auto &AddSource = - *static_cast(data); + auto &AddSource = *static_cast(data); if (!obs_source_removed(source)) AddSource(source); return true; @@ -104,18 +93,15 @@ void OBSBasicVCamConfig::OutputTypeChanged() if (!vcamActive) return; - requireRestart = (activeType == VCamOutputType::ProgramView && - type != VCamOutputType::ProgramView) || - (activeType != VCamOutputType::ProgramView && - type == VCamOutputType::ProgramView); + requireRestart = (activeType == VCamOutputType::ProgramView && type != VCamOutputType::ProgramView) || + (activeType != VCamOutputType::ProgramView && type == VCamOutputType::ProgramView); ui->warningLabel->setVisible(requireRestart); } void OBSBasicVCamConfig::UpdateConfig() { - VCamOutputType type = - (VCamOutputType)ui->outputType->currentData().toInt(); + VCamOutputType type = (VCamOutputType)ui->outputType->currentData().toInt(); switch (type) { case VCamOutputType::ProgramView: case VCamOutputType::PreviewOutput: @@ -124,8 +110,7 @@ void OBSBasicVCamConfig::UpdateConfig() config.scene = ui->outputSelection->currentText().toStdString(); break; case VCamOutputType::SourceOutput: - config.source = - ui->outputSelection->currentText().toStdString(); + config.source = ui->outputSelection->currentText().toStdString(); break; default: // unknown value, don't save type diff --git a/UI/window-basic-vcam-config.hpp b/UI/window-basic-vcam-config.hpp index 79cecb132..7ca154c15 100644 --- a/UI/window-basic-vcam-config.hpp +++ b/UI/window-basic-vcam-config.hpp @@ -20,8 +20,7 @@ class OBSBasicVCamConfig : public QDialog { bool requireRestart; public: - explicit OBSBasicVCamConfig(const VCamConfig &config, bool VCamActive, - QWidget *parent = 0); + explicit OBSBasicVCamConfig(const VCamConfig &config, bool VCamActive, QWidget *parent = 0); private slots: void OutputTypeChanged(); diff --git a/UI/window-dock-youtube-app.cpp b/UI/window-dock-youtube-app.cpp index a49b6cd97..5a2ec34de 100644 --- a/UI/window-dock-youtube-app.cpp +++ b/UI/window-dock-youtube-app.cpp @@ -11,19 +11,16 @@ using json = nlohmann::json; #ifdef YOUTUBE_WEBAPP_PLACEHOLDER -static constexpr const char *YOUTUBE_WEBAPP_PLACEHOLDER_URL = - YOUTUBE_WEBAPP_PLACEHOLDER; +static constexpr const char *YOUTUBE_WEBAPP_PLACEHOLDER_URL = YOUTUBE_WEBAPP_PLACEHOLDER; #else static constexpr const char *YOUTUBE_WEBAPP_PLACEHOLDER_URL = "https://studio.youtube.com/live/channel/UC/console?kc=OBS"; #endif #ifdef YOUTUBE_WEBAPP_ADDRESS -static constexpr const char *YOUTUBE_WEBAPP_ADDRESS_URL = - YOUTUBE_WEBAPP_ADDRESS; +static constexpr const char *YOUTUBE_WEBAPP_ADDRESS_URL = YOUTUBE_WEBAPP_ADDRESS; #else -static constexpr const char *YOUTUBE_WEBAPP_ADDRESS_URL = - "https://studio.youtube.com/live/channel/%1/console?kc=OBS"; +static constexpr const char *YOUTUBE_WEBAPP_ADDRESS_URL = "https://studio.youtube.com/live/channel/%1/console?kc=OBS"; #endif static constexpr const char *BROADCAST_CREATED = "BROADCAST_CREATED"; @@ -31,9 +28,7 @@ static constexpr const char *BROADCAST_SELECTED = "BROADCAST_SELECTED"; static constexpr const char *INGESTION_STARTED = "INGESTION_STARTED"; static constexpr const char *INGESTION_STOPPED = "INGESTION_STOPPED"; -YouTubeAppDock::YouTubeAppDock(const QString &title) - : BrowserDock(title), - dockBrowser(nullptr) +YouTubeAppDock::YouTubeAppDock(const QString &title) : BrowserDock(title), dockBrowser(nullptr) { cef->init_browser(); OBSBasic::InitBrowserPanelSafeBlock(); @@ -87,15 +82,11 @@ std::string YouTubeAppDock::InitYTUserUrl() YoutubeApiWrappers *apiYouTube = GetYTApi(); if (apiYouTube) { ChannelDescription channel_description; - if (apiYouTube->GetChannelDescription( - channel_description)) { - QString url = - QString(YOUTUBE_WEBAPP_ADDRESS_URL) - .arg(channel_description.id); + if (apiYouTube->GetChannelDescription(channel_description)) { + QString url = QString(YOUTUBE_WEBAPP_ADDRESS_URL).arg(channel_description.id); user_url = url.toStdString(); } else { - blog(LOG_ERROR, - "YT: InitYTUserUrl() Failed to get channel id"); + blog(LOG_ERROR, "YT: InitYTUserUrl() Failed to get channel id"); } } } else { @@ -140,8 +131,7 @@ void YouTubeAppDock::CreateBrowserWidget(const std::string &url) this->SetWidget(dockBrowser); - QWidget::connect(dockBrowser.get(), &QCefWidget::urlChanged, this, - &YouTubeAppDock::ReloadChatDock); + QWidget::connect(dockBrowser.get(), &QCefWidget::urlChanged, this, &YouTubeAppDock::ReloadChatDock); Update(); } @@ -175,21 +165,16 @@ void YouTubeAppDock::IngestionStarted() const char *service = obs_data_get_string(settings, "service"); if (IsYouTubeService(service)) { if (IsUserSignedIntoYT()) { - const char *broadcast_id = - obs_data_get_string(settings, "broadcast_id"); - this->IngestionStarted(broadcast_id, - YouTubeAppDock::YTSM_ACCOUNT); + const char *broadcast_id = obs_data_get_string(settings, "broadcast_id"); + this->IngestionStarted(broadcast_id, YouTubeAppDock::YTSM_ACCOUNT); } else { - const char *stream_key = - obs_data_get_string(settings, "key"); - this->IngestionStarted(stream_key, - YouTubeAppDock::YTSM_STREAM_KEY); + const char *stream_key = obs_data_get_string(settings, "key"); + this->IngestionStarted(stream_key, YouTubeAppDock::YTSM_STREAM_KEY); } } } -void YouTubeAppDock::IngestionStarted(const char *stream_id, - streaming_mode_t mode) +void YouTubeAppDock::IngestionStarted(const char *stream_id, streaming_mode_t mode) { DispatchYTEvent(INGESTION_STARTED, stream_id, mode); } @@ -203,21 +188,16 @@ void YouTubeAppDock::IngestionStopped() if (IsYouTubeService(service)) { if (IsUserSignedIntoYT()) { - const char *broadcast_id = - obs_data_get_string(settings, "broadcast_id"); - this->IngestionStopped(broadcast_id, - YouTubeAppDock::YTSM_ACCOUNT); + const char *broadcast_id = obs_data_get_string(settings, "broadcast_id"); + this->IngestionStopped(broadcast_id, YouTubeAppDock::YTSM_ACCOUNT); } else { - const char *stream_key = - obs_data_get_string(settings, "key"); - this->IngestionStopped(stream_key, - YouTubeAppDock::YTSM_STREAM_KEY); + const char *stream_key = obs_data_get_string(settings, "key"); + this->IngestionStopped(stream_key, YouTubeAppDock::YTSM_STREAM_KEY); } } } -void YouTubeAppDock::IngestionStopped(const char *stream_id, - streaming_mode_t mode) +void YouTubeAppDock::IngestionStopped(const char *stream_id, streaming_mode_t mode) { DispatchYTEvent(INGESTION_STOPPED, stream_id, mode); } @@ -234,8 +214,7 @@ void YouTubeAppDock::closeEvent(QCloseEvent *event) this->SetWidget(nullptr); } -void YouTubeAppDock::DispatchYTEvent(const char *event, const char *video_id, - streaming_mode_t mode) +void YouTubeAppDock::DispatchYTEvent(const char *event, const char *video_id, streaming_mode_t mode) { if (!dockBrowser) return; @@ -298,25 +277,18 @@ void YouTubeAppDock::Update() // if streaming already run, let's notify YT about past event if (OBSBasic::Get()->StreamingActive()) { obs_service_t *service_obj = OBSBasic::Get()->GetService(); - OBSDataAutoRelease settings = - obs_service_get_settings(service_obj); + OBSDataAutoRelease settings = obs_service_get_settings(service_obj); if (IsUserSignedIntoYT()) { channelId.clear(); // renew channelId UpdateChannelId(); - const char *broadcast_id = - obs_data_get_string(settings, "broadcast_id"); - SetInitEvent(YTSM_ACCOUNT, INGESTION_STARTED, - broadcast_id, - channelId.toStdString().c_str()); + const char *broadcast_id = obs_data_get_string(settings, "broadcast_id"); + SetInitEvent(YTSM_ACCOUNT, INGESTION_STARTED, broadcast_id, channelId.toStdString().c_str()); } else { - const char *stream_key = - obs_data_get_string(settings, "key"); - SetInitEvent(YTSM_STREAM_KEY, INGESTION_STARTED, - stream_key); + const char *stream_key = obs_data_get_string(settings, "key"); + SetInitEvent(YTSM_STREAM_KEY, INGESTION_STARTED, stream_key); } } else { - SetInitEvent(IsUserSignedIntoYT() ? YTSM_ACCOUNT - : YTSM_STREAM_KEY); + SetInitEvent(IsUserSignedIntoYT() ? YTSM_ACCOUNT : YTSM_STREAM_KEY); } dockBrowser->reloadPage(); @@ -328,8 +300,7 @@ void YouTubeAppDock::UpdateChannelId() YoutubeApiWrappers *apiYouTube = GetYTApi(); if (apiYouTube) { ChannelDescription channel_description; - if (apiYouTube->GetChannelDescription( - channel_description)) { + if (apiYouTube->GetChannelDescription(channel_description)) { channelId = channel_description.id; } else { blog(LOG_ERROR, "YT: AccountConnected() Failed " @@ -349,8 +320,7 @@ void YouTubeAppDock::ReloadChatDock() } } -void YouTubeAppDock::SetInitEvent(streaming_mode_t mode, const char *event, - const char *video_id, const char *channelId) +void YouTubeAppDock::SetInitEvent(streaming_mode_t mode, const char *event, const char *video_id, const char *channelId) { const std::string version = App()->GetVersionString(); @@ -397,8 +367,7 @@ void YouTubeAppDock::SetInitEvent(streaming_mode_t mode, const char *event, )""") .arg("OBS") .arg(version.c_str()) - .arg(mode == YTSM_ACCOUNT ? "'ACCOUNT'" - : "'STREAM_KEY'") + .arg(mode == YTSM_ACCOUNT ? "'ACCOUNT'" : "'STREAM_KEY'") .arg(api_event) .toStdString(); dockBrowser->setStartupScript(script); @@ -408,13 +377,11 @@ YoutubeApiWrappers *YouTubeAppDock::GetYTApi() { Auth *auth = OBSBasic::Get()->GetAuth(); if (auth) { - YoutubeApiWrappers *apiYouTube( - dynamic_cast(auth)); + YoutubeApiWrappers *apiYouTube(dynamic_cast(auth)); if (apiYouTube) { return apiYouTube; } else { - blog(LOG_ERROR, - "YT: GetYTApi() Failed to get YoutubeApiWrappers"); + blog(LOG_ERROR, "YT: GetYTApi() Failed to get YoutubeApiWrappers"); } } else { blog(LOG_ERROR, "YT: GetYTApi() Failed to get Auth"); @@ -427,21 +394,17 @@ void YouTubeAppDock::CleanupYouTubeUrls() if (!cef_js_avail) return; - static constexpr const char *YOUTUBE_VIDEO_URL = - "://studio.youtube.com/video/"; + static constexpr const char *YOUTUBE_VIDEO_URL = "://studio.youtube.com/video/"; // remove legacy YouTube Browser Docks (once) - bool youtube_cleanup_done = config_get_bool( - App()->GetUserConfig(), "General", "YtDockCleanupDone"); + bool youtube_cleanup_done = config_get_bool(App()->GetUserConfig(), "General", "YtDockCleanupDone"); if (youtube_cleanup_done) return; - config_set_bool(App()->GetUserConfig(), "General", "YtDockCleanupDone", - true); + config_set_bool(App()->GetUserConfig(), "General", "YtDockCleanupDone", true); - const char *jsonStr = config_get_string( - App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks"); + const char *jsonStr = config_get_string(App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks"); if (!jsonStr) return; @@ -456,8 +419,7 @@ void YouTubeAppDock::CleanupYouTubeUrls() auto url = item["url"].get(); if (url.find(YOUTUBE_VIDEO_URL) != std::string::npos) { - blog(LOG_DEBUG, "YT: found legacy url: %s", - url.c_str()); + blog(LOG_DEBUG, "YT: found legacy url: %s", url.c_str()); removedYTUrl += url; removedYTUrl += ";\n"; } else { @@ -467,13 +429,10 @@ void YouTubeAppDock::CleanupYouTubeUrls() if (!removedYTUrl.empty()) { const QString msg_title = QTStr("YouTube.DocksRemoval.Title"); - const QString msg_text = - QTStr("YouTube.DocksRemoval.Text") - .arg(QT_UTF8(removedYTUrl.c_str())); + const QString msg_text = QTStr("YouTube.DocksRemoval.Text").arg(QT_UTF8(removedYTUrl.c_str())); OBSMessageBox::warning(OBSBasic::Get(), msg_title, msg_text); std::string output = save_array.dump(); - config_set_string(App()->GetUserConfig(), "BasicWindow", - "ExtraBrowserDocks", output.c_str()); + config_set_string(App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks", output.c_str()); } } diff --git a/UI/window-dock-youtube-app.hpp b/UI/window-dock-youtube-app.hpp index 5f4632bcf..ff6074de7 100644 --- a/UI/window-dock-youtube-app.hpp +++ b/UI/window-dock-youtube-app.hpp @@ -41,12 +41,10 @@ private: void CreateBrowserWidget(const std::string &url); virtual void showEvent(QShowEvent *event) override; virtual void closeEvent(QCloseEvent *event) override; - void DispatchYTEvent(const char *event, const char *video_id, - streaming_mode_t mode); + void DispatchYTEvent(const char *event, const char *video_id, streaming_mode_t mode); void UpdateChannelId(); void ReloadChatDock(); - void SetInitEvent(streaming_mode_t mode, const char *event = nullptr, - const char *video_id = nullptr, + void SetInitEvent(streaming_mode_t mode, const char *event = nullptr, const char *video_id = nullptr, const char *channelId = nullptr); QString channelId; diff --git a/UI/window-dock.cpp b/UI/window-dock.cpp index 37a9b3dd9..8755dd097 100644 --- a/UI/window-dock.cpp +++ b/UI/window-dock.cpp @@ -20,18 +20,14 @@ void OBSDock::closeEvent(QCloseEvent *event) msgbox.exec(); if (cb->isChecked()) { - config_set_bool(App()->GetUserConfig(), "General", - "WarnedAboutClosingDocks", true); - config_save_safe(App()->GetUserConfig(), "tmp", - nullptr); + config_set_bool(App()->GetUserConfig(), "General", "WarnedAboutClosingDocks", true); + config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } }; - bool warned = config_get_bool(App()->GetUserConfig(), "General", - "WarnedAboutClosingDocks"); + bool warned = config_get_bool(App()->GetUserConfig(), "General", "WarnedAboutClosingDocks"); if (!OBSBasic::Get()->Closing() && !warned) { - QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, - Q_ARG(VoidFunc, msgBox)); + QMetaObject::invokeMethod(App(), "Exec", Qt::QueuedConnection, Q_ARG(VoidFunc, msgBox)); } QDockWidget::closeEvent(event); diff --git a/UI/window-dock.hpp b/UI/window-dock.hpp index e73620a2b..6d843a419 100644 --- a/UI/window-dock.hpp +++ b/UI/window-dock.hpp @@ -7,10 +7,7 @@ class OBSDock : public QDockWidget { public: inline OBSDock(QWidget *parent = nullptr) : QDockWidget(parent) {} - inline OBSDock(const QString &title, QWidget *parent = nullptr) - : QDockWidget(title, parent) - { - } + inline OBSDock(const QString &title, QWidget *parent = nullptr) : QDockWidget(title, parent) {} virtual void closeEvent(QCloseEvent *event); virtual void showEvent(QShowEvent *event); diff --git a/UI/window-extra-browsers.cpp b/UI/window-extra-browsers.cpp index 33171e644..8f4232e1d 100644 --- a/UI/window-extra-browsers.cpp +++ b/UI/window-extra-browsers.cpp @@ -56,8 +56,7 @@ QVariant ExtraBrowsersModel::data(const QModelIndex &index, int role) const int column = index.column(); int idx = index.row(); int count = items.size(); - bool validRole = role == Qt::DisplayRole || - role == Qt::AccessibleTextRole; + bool validRole = role == Qt::DisplayRole || role == Qt::AccessibleTextRole; if (!validRole) return QVariant(); @@ -81,12 +80,9 @@ QVariant ExtraBrowsersModel::data(const QModelIndex &index, int role) const return QVariant(); } -QVariant ExtraBrowsersModel::headerData(int section, - Qt::Orientation orientation, - int role) const +QVariant ExtraBrowsersModel::headerData(int section, Qt::Orientation orientation, int role) const { - bool validRole = role == Qt::DisplayRole || - role == Qt::AccessibleTextRole; + bool validRole = role == Qt::DisplayRole || role == Qt::AccessibleTextRole; if (validRole && orientation == Qt::Orientation::Horizontal) { switch (section) { @@ -119,11 +115,7 @@ public: class EditWidget : public QLineEdit { public: - inline EditWidget(QWidget *parent, QModelIndex index_) - : QLineEdit(parent), - index(index_) - { - } + inline EditWidget(QWidget *parent, QModelIndex index_) : QLineEdit(parent), index(index_) {} QPersistentModelIndex index; }; @@ -138,8 +130,7 @@ void ExtraBrowsersModel::AddDeleteButton(int idx) del->setProperty("class", "icon-trash"); del->setObjectName("extraPanelDelete"); del->setMinimumSize(QSize(20, 20)); - connect(del, &QPushButton::clicked, this, - &ExtraBrowsersModel::DeleteItem); + connect(del, &QPushButton::clicked, this, &ExtraBrowsersModel::DeleteItem); widget->setIndexWidget(index, del); widget->setRowHeight(idx, 20); @@ -173,8 +164,7 @@ void ExtraBrowsersModel::UpdateItem(Item &item) int idx = item.prevIdx; OBSBasic *main = OBSBasic::Get(); - BrowserDock *dock = reinterpret_cast( - main->extraBrowserDocks[idx].get()); + BrowserDock *dock = reinterpret_cast(main->extraBrowserDocks[idx].get()); dock->setWindowTitle(item.title); dock->setObjectName(item.title + OBJ_NAME_SUFFIX); @@ -230,8 +220,7 @@ void ExtraBrowsersModel::Apply() } else { QString uuid = QUuid::createUuid().toString(); uuid.replace(QRegularExpression("[{}-]"), ""); - main->AddExtraBrowserDock(item.title, item.url, uuid, - true); + main->AddExtraBrowserDock(item.title, item.url, uuid, true); } } @@ -296,20 +285,17 @@ void ExtraBrowsersModel::Init() /* ------------------------------------------------------------------------- */ -QWidget *ExtraBrowsersDelegate::createEditor(QWidget *parent, - const QStyleOptionViewItem &, +QWidget *ExtraBrowsersDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem &, const QModelIndex &index) const { QLineEdit *text = new EditWidget(parent, index); text->installEventFilter(const_cast(this)); - text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, - QSizePolicy::Policy::Expanding, + text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding, QSizePolicy::ControlType::LineEdit)); return text; } -void ExtraBrowsersDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const +void ExtraBrowsersDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit *text = reinterpret_cast(editor); text->blockSignals(true); @@ -384,8 +370,7 @@ bool ExtraBrowsersDelegate::UpdateText(QLineEdit *edit_) } if (col == (int)Column::Title) { - QString oldText = newItem ? model->newTitle - : model->items[row].title; + QString oldText = newItem ? model->newTitle : model->items[row].title; bool same = oldText.compare(text, Qt::CaseInsensitive) == 0; if (!same && !ValidName(text)) { @@ -424,9 +409,7 @@ bool ExtraBrowsersDelegate::UpdateText(QLineEdit *edit_) /* ------------------------------------------------------------------------- */ -OBSExtraBrowsers::OBSExtraBrowsers(QWidget *parent) - : QDialog(parent), - ui(new Ui::OBSExtraBrowsers) +OBSExtraBrowsers::OBSExtraBrowsers(QWidget *parent) : QDialog(parent), ui(new Ui::OBSExtraBrowsers) { ui->setupUi(this); @@ -436,16 +419,11 @@ OBSExtraBrowsers::OBSExtraBrowsers(QWidget *parent) model = new ExtraBrowsersModel(ui->table); ui->table->setModel(model); - ui->table->setItemDelegateForColumn((int)Column::Title, - new ExtraBrowsersDelegate(model)); - ui->table->setItemDelegateForColumn((int)Column::Url, - new ExtraBrowsersDelegate(model)); - ui->table->horizontalHeader()->setSectionResizeMode( - QHeaderView::ResizeMode::Stretch); - ui->table->horizontalHeader()->setSectionResizeMode( - (int)Column::Delete, QHeaderView::ResizeMode::Fixed); - ui->table->setEditTriggers( - QAbstractItemView::EditTrigger::CurrentChanged); + ui->table->setItemDelegateForColumn((int)Column::Title, new ExtraBrowsersDelegate(model)); + ui->table->setItemDelegateForColumn((int)Column::Url, new ExtraBrowsersDelegate(model)); + ui->table->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Stretch); + ui->table->horizontalHeader()->setSectionResizeMode((int)Column::Delete, QHeaderView::ResizeMode::Fixed); + ui->table->setEditTriggers(QAbstractItemView::EditTrigger::CurrentChanged); } OBSExtraBrowsers::~OBSExtraBrowsers() {} @@ -472,8 +450,7 @@ void OBSBasic::ClearExtraBrowserDocks() void OBSBasic::LoadExtraBrowserDocks() { - const char *jsonStr = config_get_string( - App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks"); + const char *jsonStr = config_get_string(App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks"); std::string err; Json json = Json::parse(jsonStr, err); @@ -489,8 +466,7 @@ void OBSBasic::LoadExtraBrowserDocks() std::string url = item["url"].string_value(); std::string uuid = item["uuid"].string_value(); - AddExtraBrowserDock(title.c_str(), url.c_str(), uuid.c_str(), - false); + AddExtraBrowserDock(title.c_str(), url.c_str(), uuid.c_str(), false); } } @@ -511,8 +487,7 @@ void OBSBasic::SaveExtraBrowserDocks() } std::string output = Json(array).dump(); - config_set_string(App()->GetUserConfig(), "BasicWindow", - "ExtraBrowserDocks", output.c_str()); + config_set_string(App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks", output.c_str()); } void OBSBasic::ManageExtraBrowserDocks() @@ -527,8 +502,7 @@ void OBSBasic::ManageExtraBrowserDocks() extraBrowsers->show(); } -void OBSBasic::AddExtraBrowserDock(const QString &title, const QString &url, - const QString &uuid, bool firstCreate) +void OBSBasic::AddExtraBrowserDock(const QString &title, const QString &url, const QString &uuid, bool firstCreate) { static int panel_version = -1; if (panel_version == -1) { @@ -545,23 +519,20 @@ void OBSBasic::AddExtraBrowserDock(const QString &title, const QString &url, dock->setWindowTitle(title); dock->setAllowedAreas(Qt::AllDockWidgetAreas); - QCefWidget *browser = - cef->create_widget(dock, QT_TO_UTF8(url), nullptr); + QCefWidget *browser = cef->create_widget(dock, QT_TO_UTF8(url), nullptr); if (browser && panel_version >= 1) browser->allowAllPopups(true); dock->SetWidget(browser); /* Add support for Twitch Dashboard panels */ - if (url.contains("twitch.tv/popout") && - url.contains("dashboard/live")) { + if (url.contains("twitch.tv/popout") && url.contains("dashboard/live")) { QRegularExpression re("twitch.tv\\/popout\\/([^/]+)\\/"); QRegularExpressionMatch match = re.match(url); QString username = match.captured(1); if (username.length() > 0) { std::string script; - script = - "Object.defineProperty(document, 'referrer', { get: () => '"; + script = "Object.defineProperty(document, 'referrer', { get: () => '"; script += "https://twitch.tv/"; script += QT_TO_UTF8(username); script += "/dashboard/live"; diff --git a/UI/window-extra-browsers.hpp b/UI/window-extra-browsers.hpp index ca967ea10..690d784dd 100644 --- a/UI/window-extra-browsers.hpp +++ b/UI/window-extra-browsers.hpp @@ -31,19 +31,16 @@ class ExtraBrowsersModel : public QAbstractTableModel { Q_OBJECT public: - inline ExtraBrowsersModel(QObject *parent = nullptr) - : QAbstractTableModel(parent) + inline ExtraBrowsersModel(QObject *parent = nullptr) : QAbstractTableModel(parent) { Reset(); QMetaObject::invokeMethod(this, "Init", Qt::QueuedConnection); } int rowCount(const QModelIndex &parent = QModelIndex()) const override; - int - columnCount(const QModelIndex &parent = QModelIndex()) const override; + int columnCount(const QModelIndex &parent = QModelIndex()) const override; QVariant data(const QModelIndex &index, int role) const override; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const override; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const override; Qt::ItemFlags flags(const QModelIndex &index) const override; struct Item { @@ -75,18 +72,12 @@ class ExtraBrowsersDelegate : public QStyledItemDelegate { Q_OBJECT public: - inline ExtraBrowsersDelegate(ExtraBrowsersModel *model_) - : QStyledItemDelegate(nullptr), - model(model_) - { - } + inline ExtraBrowsersDelegate(ExtraBrowsersModel *model_) : QStyledItemDelegate(nullptr), model(model_) {} - QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem &option, + QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem &option, const QModelIndex &index) const override; - void setEditorData(QWidget *editor, - const QModelIndex &index) const override; + void setEditorData(QWidget *editor, const QModelIndex &index) const override; bool eventFilter(QObject *object, QEvent *event) override; void RevertText(QLineEdit *edit); diff --git a/UI/window-importer.cpp b/UI/window-importer.cpp index e3e50d559..88d4ad2d9 100644 --- a/UI/window-importer.cpp +++ b/UI/window-importer.cpp @@ -41,45 +41,33 @@ enum ImporterColumn { Count }; -enum ImporterEntryRole { - EntryStateRole = Qt::UserRole, - NewPath, - AutoPath, - CheckEmpty -}; +enum ImporterEntryRole { EntryStateRole = Qt::UserRole, NewPath, AutoPath, CheckEmpty }; /********************************************************** Delegate - Presents cells in the grid. **********************************************************/ -ImporterEntryPathItemDelegate::ImporterEntryPathItemDelegate() - : QStyledItemDelegate() -{ -} +ImporterEntryPathItemDelegate::ImporterEntryPathItemDelegate() : QStyledItemDelegate() {} -QWidget *ImporterEntryPathItemDelegate::createEditor( - QWidget *parent, const QStyleOptionViewItem & /* option */, - const QModelIndex &index) const +QWidget *ImporterEntryPathItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */, + const QModelIndex &index) const { bool empty = index.model() ->index(index.row(), ImporterColumn::Path) .data(ImporterEntryRole::CheckEmpty) .value(); - QSizePolicy buttonSizePolicy(QSizePolicy::Policy::Minimum, - QSizePolicy::Policy::Expanding, + QSizePolicy buttonSizePolicy(QSizePolicy::Policy::Minimum, QSizePolicy::Policy::Expanding, QSizePolicy::ControlType::PushButton); QWidget *container = new QWidget(parent); auto browseCallback = [this, container]() { - const_cast(this)->handleBrowse( - container); + const_cast(this)->handleBrowse(container); }; auto clearCallback = [this, container]() { - const_cast(this)->handleClear( - container); + const_cast(this)->handleClear(container); }; QHBoxLayout *layout = new QHBoxLayout(); @@ -88,13 +76,11 @@ QWidget *ImporterEntryPathItemDelegate::createEditor( QLineEdit *text = new QLineEdit(); text->setObjectName(QStringLiteral("text")); - text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, - QSizePolicy::Policy::Expanding, + text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding, QSizePolicy::ControlType::LineEdit)); layout->addWidget(text); - QObject::connect(text, &QLineEdit::editingFinished, this, - &ImporterEntryPathItemDelegate::updateText); + QObject::connect(text, &QLineEdit::editingFinished, this, &ImporterEntryPathItemDelegate::updateText); QToolButton *browseButton = new QToolButton(); browseButton->setText("..."); @@ -111,8 +97,7 @@ QWidget *ImporterEntryPathItemDelegate::createEditor( clearButton->setSizePolicy(buttonSizePolicy); layout->addWidget(clearButton); - container->connect(clearButton, &QToolButton::clicked, - clearCallback); + container->connect(clearButton, &QToolButton::clicked, clearCallback); } container->setLayout(layout); @@ -120,16 +105,14 @@ QWidget *ImporterEntryPathItemDelegate::createEditor( return container; } -void ImporterEntryPathItemDelegate::setEditorData( - QWidget *editor, const QModelIndex &index) const +void ImporterEntryPathItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit *text = editor->findChild(); text->setText(index.data().toString()); editor->setProperty(PATH_LIST_PROP, QVariant()); } -void ImporterEntryPathItemDelegate::setModelData(QWidget *editor, - QAbstractItemModel *model, +void ImporterEntryPathItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { // We use the PATH_LIST_PROP property to pass a list of @@ -141,8 +124,7 @@ void ImporterEntryPathItemDelegate::setModelData(QWidget *editor, // as normal text data in the default role. QVariant pathListProp = editor->property(PATH_LIST_PROP); if (pathListProp.isValid()) { - QStringList list = - editor->property(PATH_LIST_PROP).toStringList(); + QStringList list = editor->property(PATH_LIST_PROP).toStringList(); model->setData(index, list, ImporterEntryRole::NewPath); } else { QLineEdit *lineEdit = editor->findChild(); @@ -150,15 +132,13 @@ void ImporterEntryPathItemDelegate::setModelData(QWidget *editor, } } -void ImporterEntryPathItemDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, +void ImporterEntryPathItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem localOption = option; initStyleOption(&localOption, index); - QApplication::style()->drawControl(QStyle::CE_ItemViewItem, - &localOption, painter); + QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &localOption, painter); } void ImporterEntryPathItemDelegate::handleBrowse(QWidget *container) @@ -170,9 +150,8 @@ void ImporterEntryPathItemDelegate::handleBrowse(QWidget *container) QString currentPath = text->text(); bool isSet = false; - QStringList paths = OpenFiles( - container, QTStr("Importer.SelectCollection"), currentPath, - QTStr("Importer.Collection") + QString(" ") + Pattern); + QStringList paths = OpenFiles(container, QTStr("Importer.SelectCollection"), currentPath, + QTStr("Importer.Collection") + QString(" ") + Pattern); if (!paths.empty()) { container->setProperty(PATH_LIST_PROP, paths); @@ -241,9 +220,7 @@ QVariant ImporterModel::data(const QModelIndex &index, int role) const switch (index.column()) { case ImporterColumn::Selected: if (options[index.row()].program != "") - result = options[index.row()].selected - ? Qt::Checked - : Qt::Unchecked; + result = options[index.row()].selected ? Qt::Checked : Qt::Unchecked; else result = Qt::Unchecked; } @@ -258,12 +235,10 @@ Qt::ItemFlags ImporterModel::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractTableModel::flags(index); - if (index.column() == ImporterColumn::Selected && - index.row() != options.length()) { + if (index.column() == ImporterColumn::Selected && index.row() != options.length()) { flags |= Qt::ItemIsUserCheckable; } else if (index.column() == ImporterColumn::Path || - (index.column() == ImporterColumn::Name && - index.row() != options.length())) { + (index.column() == ImporterColumn::Name && index.row() != options.length())) { flags |= Qt::ItemIsEditable; } @@ -288,8 +263,7 @@ void ImporterModel::checkInputPath(int row) if (program.empty()) { entry.selected = false; } else { - std::string name = - GetSCName(entry.path.toStdString(), program); + std::string name = GetSCName(entry.path.toStdString(), program); entry.name = name.c_str(); } } @@ -297,16 +271,14 @@ void ImporterModel::checkInputPath(int row) emit dataChanged(index(row, 0), index(row, ImporterColumn::Count)); } -bool ImporterModel::setData(const QModelIndex &index, const QVariant &value, - int role) +bool ImporterModel::setData(const QModelIndex &index, const QVariant &value, int role) { if (role == ImporterEntryRole::NewPath) { QStringList list = value.toStringList(); if (list.size() == 0) { if (index.row() < options.size()) { - beginRemoveRows(QModelIndex(), index.row(), - index.row()); + beginRemoveRows(QModelIndex(), index.row(), index.row()); options.removeAt(index.row()); endRemoveRows(); } @@ -348,8 +320,7 @@ bool ImporterModel::setData(const QModelIndex &index, const QVariant &value, entry.selected = role != ImporterEntryRole::AutoPath; entry.empty = false; - beginInsertRows(QModelIndex(), options.length() + 1, - options.length() + 1); + beginInsertRows(QModelIndex(), options.length() + 1, options.length() + 1); options.append(entry); endInsertRows(); @@ -374,13 +345,11 @@ bool ImporterModel::setData(const QModelIndex &index, const QVariant &value, return true; } -QVariant ImporterModel::headerData(int section, Qt::Orientation orientation, - int role) const +QVariant ImporterModel::headerData(int section, Qt::Orientation orientation, int role) const { QVariant result = QVariant(); - if (role == Qt::DisplayRole && - orientation == Qt::Orientation::Horizontal) { + if (role == Qt::DisplayRole && orientation == Qt::Orientation::Horizontal) { switch (section) { case ImporterColumn::Path: result = QTStr("Importer.Path"); @@ -400,10 +369,7 @@ QVariant ImporterModel::headerData(int section, Qt::Orientation orientation, Window **/ -OBSImporter::OBSImporter(QWidget *parent) - : QDialog(parent), - optionsModel(new ImporterModel), - ui(new Ui::OBSImporter) +OBSImporter::OBSImporter(QWidget *parent) : QDialog(parent), optionsModel(new ImporterModel), ui(new Ui::OBSImporter) { setAcceptDrops(true); @@ -412,53 +378,40 @@ OBSImporter::OBSImporter(QWidget *parent) ui->setupUi(this); ui->tableView->setModel(optionsModel); - ui->tableView->setItemDelegateForColumn( - ImporterColumn::Path, new ImporterEntryPathItemDelegate()); - ui->tableView->horizontalHeader()->setSectionResizeMode( - QHeaderView::ResizeMode::ResizeToContents); - ui->tableView->horizontalHeader()->setSectionResizeMode( - ImporterColumn::Path, QHeaderView::ResizeMode::Stretch); + ui->tableView->setItemDelegateForColumn(ImporterColumn::Path, new ImporterEntryPathItemDelegate()); + ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::ResizeToContents); + ui->tableView->horizontalHeader()->setSectionResizeMode(ImporterColumn::Path, QHeaderView::ResizeMode::Stretch); - connect(optionsModel, &ImporterModel::dataChanged, this, - &OBSImporter::dataChanged); + connect(optionsModel, &ImporterModel::dataChanged, this, &OBSImporter::dataChanged); - ui->tableView->setEditTriggers( - QAbstractItemView::EditTrigger::CurrentChanged); + ui->tableView->setEditTriggers(QAbstractItemView::EditTrigger::CurrentChanged); ui->buttonBox->button(QDialogButtonBox::Ok)->setText(QTStr("Import")); ui->buttonBox->button(QDialogButtonBox::Open)->setText(QTStr("Add")); - connect(ui->buttonBox->button(QDialogButtonBox::Ok), - &QPushButton::clicked, this, &OBSImporter::importCollections); - connect(ui->buttonBox->button(QDialogButtonBox::Open), - &QPushButton::clicked, this, &OBSImporter::browseImport); - connect(ui->buttonBox->button(QDialogButtonBox::Close), - &QPushButton::clicked, this, &OBSImporter::close); + connect(ui->buttonBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, + &OBSImporter::importCollections); + connect(ui->buttonBox->button(QDialogButtonBox::Open), &QPushButton::clicked, this, &OBSImporter::browseImport); + connect(ui->buttonBox->button(QDialogButtonBox::Close), &QPushButton::clicked, this, &OBSImporter::close); ImportersInit(); - bool autoSearchPrompt = config_get_bool(App()->GetUserConfig(), - "General", "AutoSearchPrompt"); + bool autoSearchPrompt = config_get_bool(App()->GetUserConfig(), "General", "AutoSearchPrompt"); if (!autoSearchPrompt) { QMessageBox::StandardButton button = OBSMessageBox::question( - parent, QTStr("Importer.AutomaticCollectionPrompt"), - QTStr("Importer.AutomaticCollectionText")); + parent, QTStr("Importer.AutomaticCollectionPrompt"), QTStr("Importer.AutomaticCollectionText")); if (button == QMessageBox::Yes) { - config_set_bool(App()->GetUserConfig(), "General", - "AutomaticCollectionSearch", true); + config_set_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch", true); } else { - config_set_bool(App()->GetUserConfig(), "General", - "AutomaticCollectionSearch", false); + config_set_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch", false); } - config_set_bool(App()->GetUserConfig(), "General", - "AutoSearchPrompt", true); + config_set_bool(App()->GetUserConfig(), "General", "AutoSearchPrompt", true); } - bool autoSearch = config_get_bool(App()->GetUserConfig(), "General", - "AutomaticCollectionSearch"); + bool autoSearch = config_get_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch"); OBSImporterFiles f; if (autoSearch) @@ -474,10 +427,8 @@ OBSImporter::OBSImporter(QWidget *parent) ui->tableView->resizeColumnsToContents(); - QModelIndex index = - optionsModel->createIndex(optionsModel->rowCount() - 1, 2); - QMetaObject::invokeMethod(ui->tableView, "setCurrentIndex", - Qt::QueuedConnection, + QModelIndex index = optionsModel->createIndex(optionsModel->rowCount() - 1, 2); + QMetaObject::invokeMethod(ui->tableView, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(const QModelIndex &, index)); } @@ -487,12 +438,9 @@ void OBSImporter::addImportOption(QString path, bool automatic) list.append(path); - QModelIndex insertIndex = optionsModel->index( - optionsModel->rowCount() - 1, ImporterColumn::Path); + QModelIndex insertIndex = optionsModel->index(optionsModel->rowCount() - 1, ImporterColumn::Path); - optionsModel->setData(insertIndex, list, - automatic ? ImporterEntryRole::AutoPath - : ImporterEntryRole::NewPath); + optionsModel->setData(insertIndex, list, automatic ? ImporterEntryRole::AutoPath : ImporterEntryRole::NewPath); } void OBSImporter::dropEvent(QDropEvent *ev) @@ -501,8 +449,7 @@ void OBSImporter::dropEvent(QDropEvent *ev) QFileInfo fileInfo(url.toLocalFile()); if (fileInfo.isDir()) { - QDirIterator dirIter(fileInfo.absoluteFilePath(), - QDir::Files); + QDirIterator dirIter(fileInfo.absoluteFilePath(), QDir::Files); while (dirIter.hasNext()) { addImportOption(dirIter.next(), false); @@ -523,9 +470,8 @@ void OBSImporter::browseImport() { QString Pattern = "(*.json *.bpres *.xml *.xconfig)"; - QStringList paths = OpenFiles( - this, QTStr("Importer.SelectCollection"), "", - QTStr("Importer.Collection") + QString(" ") + Pattern); + QStringList paths = OpenFiles(this, QTStr("Importer.SelectCollection"), "", + QTStr("Importer.Collection") + QString(" ") + Pattern); if (!paths.empty()) { for (int i = 0; i < paths.count(); i++) { @@ -561,27 +507,22 @@ void OBSImporter::importCollections() setEnabled(false); const std::filesystem::path sceneCollectionLocation = - App()->userScenesLocation / - std::filesystem::u8path(OBSSceneCollectionPath); + App()->userScenesLocation / std::filesystem::u8path(OBSSceneCollectionPath); for (int i = 0; i < optionsModel->rowCount() - 1; i++) { - int selected = optionsModel->index(i, ImporterColumn::Selected) - .data(Qt::CheckStateRole) - .value(); + int selected = optionsModel->index(i, ImporterColumn::Selected).data(Qt::CheckStateRole).value(); if (selected == Qt::Unchecked) continue; - std::string pathStr = - optionsModel->index(i, ImporterColumn::Path) - .data(Qt::DisplayRole) - .value() - .toStdString(); - std::string nameStr = - optionsModel->index(i, ImporterColumn::Name) - .data(Qt::DisplayRole) - .value() - .toStdString(); + std::string pathStr = optionsModel->index(i, ImporterColumn::Path) + .data(Qt::DisplayRole) + .value() + .toStdString(); + std::string nameStr = optionsModel->index(i, ImporterColumn::Name) + .data(Qt::DisplayRole) + .value() + .toStdString(); json11::Json res; ImportSC(pathStr, nameStr, res); @@ -599,33 +540,23 @@ void OBSImporter::importCollections() std::string fileName; if (!GetFileSafeName(name.c_str(), fileName)) { - blog(LOG_WARNING, - "Failed to create safe file name for '%s'", - fileName.c_str()); + blog(LOG_WARNING, "Failed to create safe file name for '%s'", fileName.c_str()); } std::string collectionFile; - collectionFile.reserve( - sceneCollectionLocation.u8string().size() + - fileName.size()); - collectionFile - .append(sceneCollectionLocation.u8string()) - .append(fileName); + collectionFile.reserve(sceneCollectionLocation.u8string().size() + fileName.size()); + collectionFile.append(sceneCollectionLocation.u8string()).append(fileName); if (!GetClosestUnusedFileName(collectionFile, "json")) { - blog(LOG_WARNING, - "Failed to get closest file name for %s", - fileName.c_str()); + blog(LOG_WARNING, "Failed to get closest file name for %s", fileName.c_str()); } std::string out_str = json11::Json(out).dump(); - bool success = os_quick_write_utf8_file( - collectionFile.c_str(), out_str.c_str(), - out_str.size(), false); + bool success = os_quick_write_utf8_file(collectionFile.c_str(), out_str.c_str(), out_str.size(), + false); - blog(LOG_INFO, "Import Scene Collection: %s (%s) - %s", - name.c_str(), fileName.c_str(), + blog(LOG_INFO, "Import Scene Collection: %s (%s) - %s", name.c_str(), fileName.c_str(), success ? "SUCCESS" : "FAILURE"); } } diff --git a/UI/window-importer.hpp b/UI/window-importer.hpp index 63309975e..8e77db645 100644 --- a/UI/window-importer.hpp +++ b/UI/window-importer.hpp @@ -58,8 +58,7 @@ public: int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); @@ -84,16 +83,12 @@ class ImporterEntryPathItemDelegate : public QStyledItemDelegate { public: ImporterEntryPathItemDelegate(); - virtual QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem & /* option */, + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */, const QModelIndex &index) const override; - virtual void setEditorData(QWidget *editor, - const QModelIndex &index) const override; - virtual void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; - virtual void paint(QPainter *painter, - const QStyleOptionViewItem &option, + virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override; + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: diff --git a/UI/window-log-reply.cpp b/UI/window-log-reply.cpp index 0f7130586..71c379dfe 100644 --- a/UI/window-log-reply.cpp +++ b/UI/window-log-reply.cpp @@ -31,8 +31,7 @@ OBSLogReply::OBSLogReply(QWidget *parent, const QString &url, const bool crash) ui->urlEdit->setText(url); if (crash) { ui->analyzeURL->hide(); - ui->description->setText( - Str("LogReturnDialog.Description.Crash")); + ui->description->setText(Str("LogReturnDialog.Description.Crash")); } installEventFilter(CreateShortcutFilter()); @@ -47,8 +46,7 @@ void OBSLogReply::on_copyURL_clicked() void OBSLogReply::on_analyzeURL_clicked() { QUrlQuery param; - param.addQueryItem("log_url", - QUrl::toPercentEncoding(ui->urlEdit->text())); + param.addQueryItem("log_url", QUrl::toPercentEncoding(ui->urlEdit->text())); QUrl url("https://obsproject.com/tools/analyzer", QUrl::TolerantMode); url.setQuery(param); QDesktopServices::openUrl(url); diff --git a/UI/window-main.hpp b/UI/window-main.hpp index 5b39da6b1..cfecfc375 100644 --- a/UI/window-main.hpp +++ b/UI/window-main.hpp @@ -13,6 +13,5 @@ public: virtual config_t *Config() const = 0; virtual void OBSInit() = 0; - virtual int GetProfilePath(char *path, size_t size, - const char *file) const = 0; + virtual int GetProfilePath(char *path, size_t size, const char *file) const = 0; }; diff --git a/UI/window-missing-files.cpp b/UI/window-missing-files.cpp index 0fbaf9497..57e641a74 100644 --- a/UI/window-missing-files.cpp +++ b/UI/window-missing-files.cpp @@ -41,32 +41,27 @@ enum MissingFilesRole { EntryStateRole = Qt::UserRole, NewPathsToProcessRole }; Delegate - Presents cells in the grid. **********************************************************/ -MissingFilesPathItemDelegate::MissingFilesPathItemDelegate( - bool isOutput, const QString &defaultPath) +MissingFilesPathItemDelegate::MissingFilesPathItemDelegate(bool isOutput, const QString &defaultPath) : QStyledItemDelegate(), isOutput(isOutput), defaultPath(defaultPath) { } -QWidget *MissingFilesPathItemDelegate::createEditor( - QWidget *parent, const QStyleOptionViewItem & /* option */, - const QModelIndex &) const +QWidget *MissingFilesPathItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */, + const QModelIndex &) const { - QSizePolicy buttonSizePolicy(QSizePolicy::Policy::Minimum, - QSizePolicy::Policy::Expanding, + QSizePolicy buttonSizePolicy(QSizePolicy::Policy::Minimum, QSizePolicy::Policy::Expanding, QSizePolicy::ControlType::PushButton); QWidget *container = new QWidget(parent); auto browseCallback = [this, container]() { - const_cast(this)->handleBrowse( - container); + const_cast(this)->handleBrowse(container); }; auto clearCallback = [this, container]() { - const_cast(this)->handleClear( - container); + const_cast(this)->handleClear(container); }; QHBoxLayout *layout = new QHBoxLayout(); @@ -75,8 +70,7 @@ QWidget *MissingFilesPathItemDelegate::createEditor( QLineEdit *text = new QLineEdit(); text->setObjectName(QStringLiteral("text")); - text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, - QSizePolicy::Policy::Expanding, + text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding, QSizePolicy::ControlType::LineEdit)); layout->addWidget(text); @@ -94,8 +88,7 @@ QWidget *MissingFilesPathItemDelegate::createEditor( clearButton->setSizePolicy(buttonSizePolicy); layout->addWidget(clearButton); - container->connect(clearButton, &QToolButton::clicked, - clearCallback); + container->connect(clearButton, &QToolButton::clicked, clearCallback); } container->setLayout(layout); @@ -104,8 +97,7 @@ QWidget *MissingFilesPathItemDelegate::createEditor( return container; } -void MissingFilesPathItemDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const +void MissingFilesPathItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit *text = editor->findChild(); text->setText(index.data().toString()); @@ -113,8 +105,7 @@ void MissingFilesPathItemDelegate::setEditorData(QWidget *editor, editor->setProperty(PATH_LIST_PROP, QVariant()); } -void MissingFilesPathItemDelegate::setModelData(QWidget *editor, - QAbstractItemModel *model, +void MissingFilesPathItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { // We use the PATH_LIST_PROP property to pass a list of @@ -126,28 +117,24 @@ void MissingFilesPathItemDelegate::setModelData(QWidget *editor, // as normal text data in the default role. QVariant pathListProp = editor->property(PATH_LIST_PROP); if (pathListProp.isValid()) { - QStringList list = - editor->property(PATH_LIST_PROP).toStringList(); + QStringList list = editor->property(PATH_LIST_PROP).toStringList(); if (isOutput) { model->setData(index, list); } else - model->setData(index, list, - MissingFilesRole::NewPathsToProcessRole); + model->setData(index, list, MissingFilesRole::NewPathsToProcessRole); } else { QLineEdit *lineEdit = editor->findChild(); model->setData(index, lineEdit->text(), 0); } } -void MissingFilesPathItemDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, +void MissingFilesPathItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { QStyleOptionViewItem localOption = option; initStyleOption(&localOption, index); - QApplication::style()->drawControl(QStyle::CE_ItemViewItem, - &localOption, painter); + QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &localOption, painter); } void MissingFilesPathItemDelegate::handleBrowse(QWidget *container) @@ -156,15 +143,13 @@ void MissingFilesPathItemDelegate::handleBrowse(QWidget *container) QLineEdit *text = container->findChild(); QString currentPath = text->text(); - if (currentPath.isEmpty() || - currentPath.compare(QTStr("MissingFiles.Clear")) == 0) + if (currentPath.isEmpty() || currentPath.compare(QTStr("MissingFiles.Clear")) == 0) currentPath = defaultPath; bool isSet = false; if (isOutput) { - QString newPath = QFileDialog::getOpenFileName( - container, QTStr("MissingFiles.SelectFile"), - currentPath, nullptr); + QString newPath = + QFileDialog::getOpenFileName(container, QTStr("MissingFiles.SelectFile"), currentPath, nullptr); #ifdef __APPLE__ // TODO: Revisit when QTBUG-42661 is fixed @@ -172,8 +157,7 @@ void MissingFilesPathItemDelegate::handleBrowse(QWidget *container) #endif if (!newPath.isEmpty()) { - container->setProperty(PATH_LIST_PROP, - QStringList() << newPath); + container->setProperty(PATH_LIST_PROP, QStringList() << newPath); isSet = true; } } @@ -186,8 +170,7 @@ void MissingFilesPathItemDelegate::handleClear(QWidget *container) { // An empty string list will indicate that the entry is being // blanked and should be deleted. - container->setProperty(PATH_LIST_PROP, - QStringList() << QTStr("MissingFiles.Clear")); + container->setProperty(PATH_LIST_PROP, QStringList() << QTStr("MissingFiles.Clear")); container->findChild()->clearFocus(); ((QWidget *)container->parent())->setFocus(); emit commitData(container); @@ -197,8 +180,7 @@ void MissingFilesPathItemDelegate::handleClear(QWidget *container) Model **/ -MissingFilesModel::MissingFilesModel(QObject *parent) - : QAbstractTableModel(parent) +MissingFilesModel::MissingFilesModel(QObject *parent) : QAbstractTableModel(parent) { QStyle *style = QApplication::style(); @@ -266,24 +248,19 @@ QVariant MissingFilesModel::data(const QModelIndex &index, int role) const } break; } - } else if (role == Qt::DecorationRole && - index.column() == MissingFilesColumn::Source) { - OBSBasic *main = - reinterpret_cast(App()->GetMainWindow()); - OBSSourceAutoRelease source = obs_get_source_by_name( - files[index.row()].source.toStdString().c_str()); + } else if (role == Qt::DecorationRole && index.column() == MissingFilesColumn::Source) { + OBSBasic *main = reinterpret_cast(App()->GetMainWindow()); + OBSSourceAutoRelease source = obs_get_source_by_name(files[index.row()].source.toStdString().c_str()); if (source) { result = main->GetSourceIcon(obs_source_get_id(source)); } - } else if (role == Qt::FontRole && - index.column() == MissingFilesColumn::State) { + } else if (role == Qt::FontRole && index.column() == MissingFilesColumn::State) { QFont font = QFont(); font.setBold(true); result = font; - } else if (role == Qt::ToolTipRole && - index.column() == MissingFilesColumn::State) { + } else if (role == Qt::ToolTipRole && index.column() == MissingFilesColumn::State) { switch (files[index.row()].state) { case MissingFilesState::Missing: result = QTStr("MissingFiles.Missing"); @@ -326,22 +303,18 @@ Qt::ItemFlags MissingFilesModel::flags(const QModelIndex &index) const if (index.column() == MissingFilesColumn::OriginalPath) { flags &= ~Qt::ItemIsEditable; - } else if (index.column() == MissingFilesColumn::NewPath && - index.row() != files.length()) { + } else if (index.column() == MissingFilesColumn::NewPath && index.row() != files.length()) { flags |= Qt::ItemIsEditable; } return flags; } -void MissingFilesModel::fileCheckLoop(QList files, - QString path, bool skipPrompt) +void MissingFilesModel::fileCheckLoop(QList files, QString path, bool skipPrompt) { loop = false; QUrl url = QUrl().fromLocalFile(path); - QString dir = - url.toDisplayString(QUrl::RemoveScheme | QUrl::RemoveFilename | - QUrl::PreferLocalFile); + QString dir = url.toDisplayString(QUrl::RemoveScheme | QUrl::RemoveFilename | QUrl::PreferLocalFile); bool prompted = skipPrompt; @@ -356,10 +329,8 @@ void MissingFilesModel::fileCheckLoop(QList files, if (os_file_exists(testFile.toStdString().c_str())) { if (!prompted) { QMessageBox::StandardButton button = - QMessageBox::question( - nullptr, - QTStr("MissingFiles.AutoSearch"), - QTStr("MissingFiles.AutoSearchText")); + QMessageBox::question(nullptr, QTStr("MissingFiles.AutoSearch"), + QTStr("MissingFiles.AutoSearchText")); if (button == QMessageBox::No) break; @@ -373,8 +344,7 @@ void MissingFilesModel::fileCheckLoop(QList files, loop = true; } -bool MissingFilesModel::setData(const QModelIndex &index, const QVariant &value, - int role) +bool MissingFilesModel::setData(const QModelIndex &index, const QVariant &value, int role) { bool success = false; @@ -399,25 +369,19 @@ bool MissingFilesModel::setData(const QModelIndex &index, const QVariant &value, if (index.column() == MissingFilesColumn::NewPath) { files[index.row()].newPath = value.toString(); QString fileName = QUrl(path).fileName(); - QString origFileName = - QUrl(files[index.row()].originalPath).fileName(); + QString origFileName = QUrl(files[index.row()].originalPath).fileName(); if (path.isEmpty()) { - files[index.row()].state = - MissingFilesState::Missing; - } else if (path.compare(QTStr("MissingFiles.Clear")) == - 0) { - files[index.row()].state = - MissingFilesState::Cleared; + files[index.row()].state = MissingFilesState::Missing; + } else if (path.compare(QTStr("MissingFiles.Clear")) == 0) { + files[index.row()].state = MissingFilesState::Cleared; } else if (fileName.compare(origFileName) == 0) { - files[index.row()].state = - MissingFilesState::Found; + files[index.row()].state = MissingFilesState::Found; if (loop) fileCheckLoop(files, path, false); } else { - files[index.row()].state = - MissingFilesState::Replaced; + files[index.row()].state = MissingFilesState::Replaced; if (loop) fileCheckLoop(files, path, false); @@ -431,13 +395,11 @@ bool MissingFilesModel::setData(const QModelIndex &index, const QVariant &value, return success; } -QVariant MissingFilesModel::headerData(int section, Qt::Orientation orientation, - int role) const +QVariant MissingFilesModel::headerData(int section, Qt::Orientation orientation, int role) const { QVariant result = QVariant(); - if (role == Qt::DisplayRole && - orientation == Qt::Orientation::Horizontal) { + if (role == Qt::DisplayRole && orientation == Qt::Orientation::Horizontal) { switch (section) { case MissingFilesColumn::State: result = QTStr("MissingFiles.State"); @@ -467,30 +429,22 @@ OBSMissingFiles::OBSMissingFiles(obs_missing_files_t *files, QWidget *parent) ui->setupUi(this); ui->tableView->setModel(filesModel); - ui->tableView->setItemDelegateForColumn( - MissingFilesColumn::OriginalPath, - new MissingFilesPathItemDelegate(false, "")); - ui->tableView->setItemDelegateForColumn( - MissingFilesColumn::NewPath, - new MissingFilesPathItemDelegate(true, "")); - ui->tableView->horizontalHeader()->setSectionResizeMode( - QHeaderView::ResizeMode::Stretch); - ui->tableView->horizontalHeader()->setSectionResizeMode( - MissingFilesColumn::Source, - QHeaderView::ResizeMode::ResizeToContents); + ui->tableView->setItemDelegateForColumn(MissingFilesColumn::OriginalPath, + new MissingFilesPathItemDelegate(false, "")); + ui->tableView->setItemDelegateForColumn(MissingFilesColumn::NewPath, + new MissingFilesPathItemDelegate(true, "")); + ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Stretch); + ui->tableView->horizontalHeader()->setSectionResizeMode(MissingFilesColumn::Source, + QHeaderView::ResizeMode::ResizeToContents); ui->tableView->horizontalHeader()->setMaximumSectionSize(width() / 3); - ui->tableView->horizontalHeader()->setSectionResizeMode( - MissingFilesColumn::State, - QHeaderView::ResizeMode::ResizeToContents); - ui->tableView->setEditTriggers( - QAbstractItemView::EditTrigger::CurrentChanged); + ui->tableView->horizontalHeader()->setSectionResizeMode(MissingFilesColumn::State, + QHeaderView::ResizeMode::ResizeToContents); + ui->tableView->setEditTriggers(QAbstractItemView::EditTrigger::CurrentChanged); - ui->warningIcon->setPixmap( - filesModel->warningIcon.pixmap(QSize(32, 32))); + ui->warningIcon->setPixmap(filesModel->warningIcon.pixmap(QSize(32, 32))); for (size_t i = 0; i < obs_missing_files_count(files); i++) { - obs_missing_file_t *f = - obs_missing_files_get_file(files, (int)i); + obs_missing_file_t *f = obs_missing_files_get_file(files, (int)i); const char *oldPath = obs_missing_file_get_path(f); const char *name = obs_missing_file_get_source_name(f); @@ -498,27 +452,19 @@ OBSMissingFiles::OBSMissingFiles(obs_missing_files_t *files, QWidget *parent) addMissingFile(oldPath, name); } - QString found = - QTStr("MissingFiles.NumFound") - .arg("0", - QString::number(obs_missing_files_count(files))); + QString found = QTStr("MissingFiles.NumFound").arg("0", QString::number(obs_missing_files_count(files))); ui->found->setText(found); fileStore = files; - connect(ui->doneButton, &QPushButton::clicked, this, - &OBSMissingFiles::saveFiles); - connect(ui->browseButton, &QPushButton::clicked, this, - &OBSMissingFiles::browseFolders); - connect(ui->cancelButton, &QPushButton::clicked, this, - &OBSMissingFiles::close); - connect(filesModel, &MissingFilesModel::dataChanged, this, - &OBSMissingFiles::dataChanged); + connect(ui->doneButton, &QPushButton::clicked, this, &OBSMissingFiles::saveFiles); + connect(ui->browseButton, &QPushButton::clicked, this, &OBSMissingFiles::browseFolders); + connect(ui->cancelButton, &QPushButton::clicked, this, &OBSMissingFiles::close); + connect(filesModel, &MissingFilesModel::dataChanged, this, &OBSMissingFiles::dataChanged); QModelIndex index = filesModel->createIndex(0, 1); - QMetaObject::invokeMethod(ui->tableView, "setCurrentIndex", - Qt::QueuedConnection, + QMetaObject::invokeMethod(ui->tableView, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(const QModelIndex &, index)); } @@ -527,19 +473,16 @@ OBSMissingFiles::~OBSMissingFiles() obs_missing_files_destroy(fileStore); } -void OBSMissingFiles::addMissingFile(const char *originalPath, - const char *sourceName) +void OBSMissingFiles::addMissingFile(const char *originalPath, const char *sourceName) { QStringList list; list.append(originalPath); list.append(sourceName); - QModelIndex insertIndex = filesModel->index(filesModel->rowCount() - 1, - MissingFilesColumn::Source); + QModelIndex insertIndex = filesModel->index(filesModel->rowCount() - 1, MissingFilesColumn::Source); - filesModel->setData(insertIndex, list, - MissingFilesRole::NewPathsToProcessRole); + filesModel->setData(insertIndex, list, MissingFilesRole::NewPathsToProcessRole); } void OBSMissingFiles::saveFiles() @@ -547,8 +490,7 @@ void OBSMissingFiles::saveFiles() for (int i = 0; i < filesModel->files.length(); i++) { MissingFilesState state = filesModel->files[i].state; if (state != MissingFilesState::Missing) { - obs_missing_file_t *f = - obs_missing_files_get_file(fileStore, i); + obs_missing_file_t *f = obs_missing_files_get_file(fileStore, i); QString path = filesModel->files[i].newPath; @@ -567,9 +509,8 @@ void OBSMissingFiles::saveFiles() void OBSMissingFiles::browseFolders() { - QString dir = QFileDialog::getExistingDirectory( - this, QTStr("MissingFiles.SelectDir"), "", - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + QString dir = QFileDialog::getExistingDirectory(this, QTStr("MissingFiles.SelectDir"), "", + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); if (dir != "") { dir += "/"; @@ -579,10 +520,9 @@ void OBSMissingFiles::browseFolders() void OBSMissingFiles::dataChanged() { - QString found = QTStr("MissingFiles.NumFound") - .arg(QString::number(filesModel->found()), - QString::number(obs_missing_files_count( - fileStore))); + QString found = + QTStr("MissingFiles.NumFound") + .arg(QString::number(filesModel->found()), QString::number(obs_missing_files_count(fileStore))); ui->found->setText(found); diff --git a/UI/window-missing-files.hpp b/UI/window-missing-files.hpp index 4e2144fee..2b24e0f8e 100644 --- a/UI/window-missing-files.hpp +++ b/UI/window-missing-files.hpp @@ -29,15 +29,13 @@ Q_DECLARE_METATYPE(MissingFilesState); class OBSMissingFiles : public QDialog { Q_OBJECT - Q_PROPERTY(QIcon warningIcon READ GetWarningIcon WRITE SetWarningIcon - DESIGNABLE true) + Q_PROPERTY(QIcon warningIcon READ GetWarningIcon WRITE SetWarningIcon DESIGNABLE true) QPointer filesModel; std::unique_ptr ui; public: - explicit OBSMissingFiles(obs_missing_files_t *files, - QWidget *parent = nullptr); + explicit OBSMissingFiles(obs_missing_files_t *files, QWidget *parent = nullptr); virtual ~OBSMissingFiles() override; void addMissingFile(const char *originalPath, const char *sourceName); @@ -67,8 +65,7 @@ public: int columnCount(const QModelIndex &parent = QModelIndex()) const; int found() const; QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); @@ -88,8 +85,7 @@ private: QList files; - void fileCheckLoop(QList files, QString path, - bool skipPrompt); + void fileCheckLoop(QList files, QString path, bool skipPrompt); }; class MissingFilesPathItemDelegate : public QStyledItemDelegate { @@ -98,16 +94,12 @@ class MissingFilesPathItemDelegate : public QStyledItemDelegate { public: MissingFilesPathItemDelegate(bool isOutput, const QString &defaultPath); - virtual QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem & /* option */, + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */, const QModelIndex &index) const override; - virtual void setEditorData(QWidget *editor, - const QModelIndex &index) const override; - virtual void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; - virtual void paint(QPainter *painter, - const QStyleOptionViewItem &option, + virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override; + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: diff --git a/UI/window-namedialog.cpp b/UI/window-namedialog.cpp index c2fd69e66..561bd15b9 100644 --- a/UI/window-namedialog.cpp +++ b/UI/window-namedialog.cpp @@ -42,8 +42,7 @@ NameDialog::NameDialog(QWidget *parent) : QDialog(parent) checkbox = new QCheckBox(this); layout->addWidget(checkbox); - QDialogButtonBox *buttonbox = new QDialogButtonBox( - QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + QDialogButtonBox *buttonbox = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); layout->addWidget(buttonbox); buttonbox->setCenterButtons(true); connect(buttonbox, &QDialogButtonBox::accepted, this, &QDialog::accept); @@ -63,8 +62,7 @@ static void CleanWhitespace(std::string &str) str.erase(str.begin()); } -bool NameDialog::AskForName(QWidget *parent, const QString &title, - const QString &text, std::string &userTextInput, +bool NameDialog::AskForName(QWidget *parent, const QString &title, const QString &text, std::string &userTextInput, const QString &placeHolder, int maxSize) { if (maxSize <= 0 || maxSize > 32767) @@ -87,11 +85,8 @@ bool NameDialog::AskForName(QWidget *parent, const QString &title, return true; } -bool NameDialog::AskForNameWithOption(QWidget *parent, const QString &title, - const QString &text, - std::string &userTextInput, - const QString &optionLabel, - bool &optionChecked, +bool NameDialog::AskForNameWithOption(QWidget *parent, const QString &title, const QString &text, + std::string &userTextInput, const QString &optionLabel, bool &optionChecked, const QString &placeHolder) { NameDialog dialog(parent); diff --git a/UI/window-namedialog.hpp b/UI/window-namedialog.hpp index 869822911..e0f7006ba 100644 --- a/UI/window-namedialog.hpp +++ b/UI/window-namedialog.hpp @@ -33,19 +33,15 @@ public: // Returns true if user clicks OK, false otherwise // userTextInput returns string that user typed into dialog - static bool AskForName(QWidget *parent, const QString &title, - const QString &text, std::string &userTextInput, - const QString &placeHolder = QString(""), - int maxSize = 170); + static bool AskForName(QWidget *parent, const QString &title, const QString &text, std::string &userTextInput, + const QString &placeHolder = QString(""), int maxSize = 170); // Returns true if user clicks OK, false otherwise // userTextInput returns string that user typed into dialog // userOptionReturn the checkbox was ticked user accepted - static bool - AskForNameWithOption(QWidget *parent, const QString &title, - const QString &text, std::string &userTextInput, - const QString &optionLabel, bool &optionChecked, - const QString &placeHolder = QString("")); + static bool AskForNameWithOption(QWidget *parent, const QString &title, const QString &text, + std::string &userTextInput, const QString &optionLabel, bool &optionChecked, + const QString &placeHolder = QString("")); private: QLabel *label; diff --git a/UI/window-permissions.cpp b/UI/window-permissions.cpp index 794cf2791..046a011f9 100644 --- a/UI/window-permissions.cpp +++ b/UI/window-permissions.cpp @@ -19,34 +19,26 @@ #include "moc_window-permissions.cpp" #include "obs-app.hpp" -OBSPermissions::OBSPermissions(QWidget *parent, MacPermissionStatus capture, - MacPermissionStatus video, - MacPermissionStatus audio, - MacPermissionStatus accessibility) +OBSPermissions::OBSPermissions(QWidget *parent, MacPermissionStatus capture, MacPermissionStatus video, + MacPermissionStatus audio, MacPermissionStatus accessibility) : QDialog(parent), ui(new Ui::OBSPermissions) { ui->setupUi(this); - SetStatus(ui->capturePermissionButton, capture, - QTStr("MacPermissions.Item.ScreenRecording")); - SetStatus(ui->videoPermissionButton, video, - QTStr("MacPermissions.Item.Camera")); - SetStatus(ui->audioPermissionButton, audio, - QTStr("MacPermissions.Item.Microphone")); - SetStatus(ui->accessibilityPermissionButton, accessibility, - QTStr("MacPermissions.Item.Accessibility")); + SetStatus(ui->capturePermissionButton, capture, QTStr("MacPermissions.Item.ScreenRecording")); + SetStatus(ui->videoPermissionButton, video, QTStr("MacPermissions.Item.Camera")); + SetStatus(ui->audioPermissionButton, audio, QTStr("MacPermissions.Item.Microphone")); + SetStatus(ui->accessibilityPermissionButton, accessibility, QTStr("MacPermissions.Item.Accessibility")); } -void OBSPermissions::SetStatus(QPushButton *btn, MacPermissionStatus status, - const QString &preference) +void OBSPermissions::SetStatus(QPushButton *btn, MacPermissionStatus status, const QString &preference) { if (status == kPermissionAuthorized) { btn->setText(QTStr("MacPermissions.AccessGranted")); } else if (status == kPermissionNotDetermined) { btn->setText(QTStr("MacPermissions.RequestAccess")); } else { - btn->setText( - QTStr("MacPermissions.OpenPreferences").arg(preference)); + btn->setText(QTStr("MacPermissions.OpenPreferences").arg(preference)); } btn->setEnabled(status != kPermissionAuthorized); btn->setProperty("status", status); @@ -60,14 +52,10 @@ void OBSPermissions::on_capturePermissionButton_clicked() void OBSPermissions::on_videoPermissionButton_clicked() { - MacPermissionStatus status = - (MacPermissionStatus)ui->videoPermissionButton - ->property("status") - .toInt(); + MacPermissionStatus status = (MacPermissionStatus)ui->videoPermissionButton->property("status").toInt(); if (status == kPermissionNotDetermined) { status = RequestPermission(kVideoDeviceAccess); - SetStatus(ui->videoPermissionButton, status, - QTStr("MacPermissions.Item.Camera")); + SetStatus(ui->videoPermissionButton, status, QTStr("MacPermissions.Item.Camera")); } else { OpenMacOSPrivacyPreferences("Camera"); } @@ -75,14 +63,10 @@ void OBSPermissions::on_videoPermissionButton_clicked() void OBSPermissions::on_audioPermissionButton_clicked() { - MacPermissionStatus status = - (MacPermissionStatus)ui->audioPermissionButton - ->property("status") - .toInt(); + MacPermissionStatus status = (MacPermissionStatus)ui->audioPermissionButton->property("status").toInt(); if (status == kPermissionNotDetermined) { status = RequestPermission(kAudioDeviceAccess); - SetStatus(ui->audioPermissionButton, status, - QTStr("MacPermissions.Item.Microphone")); + SetStatus(ui->audioPermissionButton, status, QTStr("MacPermissions.Item.Microphone")); } else { OpenMacOSPrivacyPreferences("Microphone"); } @@ -96,8 +80,7 @@ void OBSPermissions::on_accessibilityPermissionButton_clicked() void OBSPermissions::on_continueButton_clicked() { - config_set_int(App()->GetAppConfig(), "General", - "MacOSPermissionsDialogLastShown", + config_set_int(App()->GetAppConfig(), "General", "MacOSPermissionsDialogLastShown", MACOS_PERMISSIONS_DIALOG_VERSION); close(); } diff --git a/UI/window-permissions.hpp b/UI/window-permissions.hpp index f542f12ea..67a74cbb1 100644 --- a/UI/window-permissions.hpp +++ b/UI/window-permissions.hpp @@ -27,13 +27,11 @@ class OBSPermissions : public QDialog { private: std::unique_ptr ui; - void SetStatus(QPushButton *btn, MacPermissionStatus status, - const QString &preference); + void SetStatus(QPushButton *btn, MacPermissionStatus status, const QString &preference); public: - OBSPermissions(QWidget *parent, MacPermissionStatus capture, - MacPermissionStatus video, MacPermissionStatus audio, - MacPermissionStatus accessibility); + OBSPermissions(QWidget *parent, MacPermissionStatus capture, MacPermissionStatus video, + MacPermissionStatus audio, MacPermissionStatus accessibility); private slots: void on_capturePermissionButton_clicked(); diff --git a/UI/window-projector.cpp b/UI/window-projector.cpp index 94212a9d0..60f873bc9 100644 --- a/UI/window-projector.cpp +++ b/UI/window-projector.cpp @@ -15,21 +15,17 @@ static QList multiviewProjectors; static bool updatingMultiview = false, mouseSwitching, transitionOnDoubleClick; -OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, - ProjectorType type_) +OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, ProjectorType type_) : OBSQTDisplay(widget, Qt::Window), weakSource(OBSGetWeakRef(source_)) { OBSSource source = GetSource(); if (source) { - sigs.emplace_back(obs_source_get_signal_handler(source), - "rename", OBSSourceRenamed, this); - sigs.emplace_back(obs_source_get_signal_handler(source), - "destroy", OBSSourceDestroyed, this); + sigs.emplace_back(obs_source_get_signal_handler(source), "rename", OBSSourceRenamed, this); + sigs.emplace_back(obs_source_get_signal_handler(source), "destroy", OBSSourceDestroyed, this); } - isAlwaysOnTop = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "ProjectorAlwaysOnTop"); + isAlwaysOnTop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ProjectorAlwaysOnTop"); if (isAlwaysOnTop) setWindowFlags(Qt::WindowStaysOnTopHint); @@ -45,8 +41,7 @@ OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, type = type_; #ifdef __APPLE__ - setWindowIcon( - QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png"))); + setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs_256x256.png"))); #else setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png"))); #endif @@ -64,8 +59,7 @@ OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, QAction *action = new QAction(this); action->setShortcut(Qt::Key_Escape); addAction(action); - connect(action, &QAction::triggered, this, - &OBSProjector::EscapeTriggered); + connect(action, &QAction::triggered, this, &OBSProjector::EscapeTriggered); setAttribute(Qt::WA_DeleteOnClose, true); @@ -76,15 +70,12 @@ OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, auto addDrawCallback = [this]() { bool isMultiview = type == ProjectorType::Multiview; - obs_display_add_draw_callback( - GetDisplay(), - isMultiview ? OBSRenderMultiview : OBSRender, this); + obs_display_add_draw_callback(GetDisplay(), isMultiview ? OBSRenderMultiview : OBSRender, this); obs_display_set_background_color(GetDisplay(), 0x000000); }; connect(this, &OBSQTDisplay::DisplayCreated, addDrawCallback); - connect(App(), &QGuiApplication::screenRemoved, this, - &OBSProjector::ScreenRemoved); + connect(App(), &QGuiApplication::screenRemoved, this, &OBSProjector::ScreenRemoved); if (type == ProjectorType::Multiview) { multiview = new Multiview(); @@ -112,9 +103,7 @@ OBSProjector::~OBSProjector() sigs.clear(); bool isMultiview = type == ProjectorType::Multiview; - obs_display_remove_draw_callback( - GetDisplay(), isMultiview ? OBSRenderMultiview : OBSRender, - this); + obs_display_remove_draw_callback(GetDisplay(), isMultiview ? OBSRenderMultiview : OBSRender, this); OBSSource source = GetSource(); if (source) @@ -144,8 +133,7 @@ void OBSProjector::SetHideCursor() if (savedMonitor == -1) return; - bool hideCursor = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "HideProjectorCursor"); + bool hideCursor = config_get_bool(App()->GetUserConfig(), "BasicWindow", "HideProjectorCursor"); if (hideCursor && type != ProjectorType::Multiview) setCursor(Qt::BlankCursor); @@ -194,11 +182,9 @@ void OBSProjector::OBSRender(void *data, uint32_t cx, uint32_t cy) newCX = int(scale * float(targetCX)); newCY = int(scale * float(targetCY)); - startRegion(x, y, newCX, newCY, 0.0f, float(targetCX), 0.0f, - float(targetCY)); + startRegion(x, y, newCX, newCY, 0.0f, float(targetCX), 0.0f, float(targetCY)); - if (window->type == ProjectorType::Preview && - main->IsPreviewProgramMode()) { + if (window->type == ProjectorType::Preview && main->IsPreviewProgramMode()) { OBSSource curSource = main->GetCurrentSceneSource(); if (source != curSource) { @@ -207,8 +193,7 @@ void OBSProjector::OBSRender(void *data, uint32_t cx, uint32_t cy) source = curSource; window->weakSource = OBSGetWeakRef(source); } - } else if (window->type == ProjectorType::Preview && - !main->IsPreviewProgramMode()) { + } else if (window->type == ProjectorType::Preview && !main->IsPreviewProgramMode()) { window->weakSource = nullptr; } @@ -226,9 +211,7 @@ void OBSProjector::OBSSourceRenamed(void *data, calldata_t *params) QString oldName = calldata_string(params, "prev_name"); QString newName = calldata_string(params, "new_name"); - QMetaObject::invokeMethod(window, "RenameProjector", - Q_ARG(QString, oldName), - Q_ARG(QString, newName)); + QMetaObject::invokeMethod(window, "RenameProjector", Q_ARG(QString, oldName), Q_ARG(QString, newName)); } void OBSProjector::OBSSourceDestroyed(void *data, calldata_t *) @@ -257,8 +240,7 @@ void OBSProjector::mouseDoubleClickEvent(QMouseEvent *event) if (event->button() == Qt::LeftButton) { QPoint pos = event->pos(); - OBSSource src = - multiview->GetSourceByPosition(pos.x(), pos.y()); + OBSSource src = multiview->GetSourceByPosition(pos.x(), pos.y()); if (!src) return; @@ -273,34 +255,27 @@ void OBSProjector::mousePressEvent(QMouseEvent *event) if (event->button() == Qt::RightButton) { QMenu *projectorMenu = new QMenu(QTStr("Fullscreen")); - OBSBasic::AddProjectorMenuMonitors( - projectorMenu, this, - &OBSProjector::OpenFullScreenProjector); + OBSBasic::AddProjectorMenuMonitors(projectorMenu, this, &OBSProjector::OpenFullScreenProjector); QMenu popup(this); popup.addMenu(projectorMenu); if (GetMonitor() > -1) { - popup.addAction(QTStr("Windowed"), this, - &OBSProjector::OpenWindowedProjector); + popup.addAction(QTStr("Windowed"), this, &OBSProjector::OpenWindowedProjector); } else if (!this->isMaximized()) { - popup.addAction(QTStr("ResizeProjectorWindowToContent"), - this, &OBSProjector::ResizeToContent); + popup.addAction(QTStr("ResizeProjectorWindowToContent"), this, &OBSProjector::ResizeToContent); } - QAction *alwaysOnTopButton = new QAction( - QTStr("Basic.MainMenu.View.AlwaysOnTop"), this); + QAction *alwaysOnTopButton = new QAction(QTStr("Basic.MainMenu.View.AlwaysOnTop"), this); alwaysOnTopButton->setCheckable(true); alwaysOnTopButton->setChecked(isAlwaysOnTop); - connect(alwaysOnTopButton, &QAction::toggled, this, - &OBSProjector::AlwaysOnTopToggled); + connect(alwaysOnTopButton, &QAction::toggled, this, &OBSProjector::AlwaysOnTopToggled); popup.addAction(alwaysOnTopButton); - popup.addAction(QTStr("Close"), this, - &OBSProjector::EscapeTriggered); + popup.addAction(QTStr("Close"), this, &OBSProjector::EscapeTriggered); popup.exec(QCursor::pos()); } else if (event->button() == Qt::LeftButton) { // Only MultiView projectors handle left click @@ -311,8 +286,7 @@ void OBSProjector::mousePressEvent(QMouseEvent *event) return; QPoint pos = event->pos(); - OBSSource src = - multiview->GetSourceByPosition(pos.x(), pos.y()); + OBSSource src = multiview->GetSourceByPosition(pos.x(), pos.y()); if (!src) return; @@ -330,22 +304,16 @@ void OBSProjector::EscapeTriggered() void OBSProjector::UpdateMultiview() { - MultiviewLayout multiviewLayout = static_cast( - config_get_int(App()->GetUserConfig(), "BasicWindow", - "MultiviewLayout")); + MultiviewLayout multiviewLayout = + static_cast(config_get_int(App()->GetUserConfig(), "BasicWindow", "MultiviewLayout")); - bool drawLabel = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "MultiviewDrawNames"); + bool drawLabel = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewDrawNames"); - bool drawSafeArea = config_get_bool( - App()->GetUserConfig(), "BasicWindow", "MultiviewDrawAreas"); + bool drawSafeArea = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewDrawAreas"); - mouseSwitching = config_get_bool(App()->GetUserConfig(), "BasicWindow", - "MultiviewMouseSwitch"); + mouseSwitching = config_get_bool(App()->GetUserConfig(), "BasicWindow", "MultiviewMouseSwitch"); - transitionOnDoubleClick = config_get_bool(App()->GetUserConfig(), - "BasicWindow", - "TransitionOnDoubleClick"); + transitionOnDoubleClick = config_get_bool(App()->GetUserConfig(), "BasicWindow", "TransitionOnDoubleClick"); multiview->Update(multiviewLayout, drawLabel, drawSafeArea); } @@ -480,8 +448,7 @@ void OBSProjector::ResizeToContent() } QSize size = this->size(); - GetScaleAndCenterPos(targetCX, targetCY, size.width(), size.height(), x, - y, scale); + GetScaleAndCenterPos(targetCX, targetCY, size.width(), size.height(), x, y, scale); newX = size.width() - (x * 2); newY = size.height() - (y * 2); diff --git a/UI/window-projector.hpp b/UI/window-projector.hpp index 8be23d4d4..f95063261 100644 --- a/UI/window-projector.hpp +++ b/UI/window-projector.hpp @@ -57,8 +57,7 @@ private slots: void RenameProjector(QString oldName, QString newName); public: - OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, - ProjectorType type_); + OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, ProjectorType type_); ~OBSProjector(); OBSSource GetSource(); diff --git a/UI/window-remux.cpp b/UI/window-remux.cpp index 5872c1ad2..d72ebbd9c 100644 --- a/UI/window-remux.cpp +++ b/UI/window-remux.cpp @@ -54,25 +54,21 @@ enum RemuxEntryRole { EntryStateRole = Qt::UserRole, NewPathsToProcessRole }; Delegate - Presents cells in the grid. **********************************************************/ -RemuxEntryPathItemDelegate::RemuxEntryPathItemDelegate( - bool isOutput, const QString &defaultPath) +RemuxEntryPathItemDelegate::RemuxEntryPathItemDelegate(bool isOutput, const QString &defaultPath) : QStyledItemDelegate(), isOutput(isOutput), defaultPath(defaultPath) { } -QWidget *RemuxEntryPathItemDelegate::createEditor( - QWidget *parent, const QStyleOptionViewItem & /* option */, - const QModelIndex &index) const +QWidget *RemuxEntryPathItemDelegate::createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */, + const QModelIndex &index) const { - RemuxEntryState state = - index.model() - ->index(index.row(), RemuxEntryColumn::State) - .data(RemuxEntryRole::EntryStateRole) - .value(); - if (state == RemuxEntryState::Pending || - state == RemuxEntryState::InProgress) { + RemuxEntryState state = index.model() + ->index(index.row(), RemuxEntryColumn::State) + .data(RemuxEntryRole::EntryStateRole) + .value(); + if (state == RemuxEntryState::Pending || state == RemuxEntryState::InProgress) { // Never allow modification of rows that are // in progress. return Q_NULLPTR; @@ -85,21 +81,17 @@ QWidget *RemuxEntryPathItemDelegate::createEditor( // already complete. return Q_NULLPTR; } else { - QSizePolicy buttonSizePolicy( - QSizePolicy::Policy::Minimum, - QSizePolicy::Policy::Expanding, - QSizePolicy::ControlType::PushButton); + QSizePolicy buttonSizePolicy(QSizePolicy::Policy::Minimum, QSizePolicy::Policy::Expanding, + QSizePolicy::ControlType::PushButton); QWidget *container = new QWidget(parent); auto browseCallback = [this, container]() { - const_cast(this) - ->handleBrowse(container); + const_cast(this)->handleBrowse(container); }; auto clearCallback = [this, container]() { - const_cast(this) - ->handleClear(container); + const_cast(this)->handleClear(container); }; QHBoxLayout *layout = new QHBoxLayout(); @@ -108,22 +100,18 @@ QWidget *RemuxEntryPathItemDelegate::createEditor( QLineEdit *text = new QLineEdit(); text->setObjectName(QStringLiteral("text")); - text->setSizePolicy( - QSizePolicy(QSizePolicy::Policy::Expanding, - QSizePolicy::Policy::Expanding, - QSizePolicy::ControlType::LineEdit)); + text->setSizePolicy(QSizePolicy(QSizePolicy::Policy::Expanding, QSizePolicy::Policy::Expanding, + QSizePolicy::ControlType::LineEdit)); layout->addWidget(text); - QObject::connect(text, &QLineEdit::editingFinished, this, - &RemuxEntryPathItemDelegate::updateText); + QObject::connect(text, &QLineEdit::editingFinished, this, &RemuxEntryPathItemDelegate::updateText); QToolButton *browseButton = new QToolButton(); browseButton->setText("..."); browseButton->setSizePolicy(buttonSizePolicy); layout->addWidget(browseButton); - container->connect(browseButton, &QToolButton::clicked, - browseCallback); + container->connect(browseButton, &QToolButton::clicked, browseCallback); // The "clear" button is not shown in output cells // or the insertion point's input cell. @@ -133,8 +121,7 @@ QWidget *RemuxEntryPathItemDelegate::createEditor( clearButton->setSizePolicy(buttonSizePolicy); layout->addWidget(clearButton); - container->connect(clearButton, &QToolButton::clicked, - clearCallback); + container->connect(clearButton, &QToolButton::clicked, clearCallback); } container->setLayout(layout); @@ -143,16 +130,14 @@ QWidget *RemuxEntryPathItemDelegate::createEditor( } } -void RemuxEntryPathItemDelegate::setEditorData(QWidget *editor, - const QModelIndex &index) const +void RemuxEntryPathItemDelegate::setEditorData(QWidget *editor, const QModelIndex &index) const { QLineEdit *text = editor->findChild(); text->setText(index.data().toString()); editor->setProperty(PATH_LIST_PROP, QVariant()); } -void RemuxEntryPathItemDelegate::setModelData(QWidget *editor, - QAbstractItemModel *model, +void RemuxEntryPathItemDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { // We use the PATH_LIST_PROP property to pass a list of @@ -164,45 +149,39 @@ void RemuxEntryPathItemDelegate::setModelData(QWidget *editor, // as normal text data in the default role. QVariant pathListProp = editor->property(PATH_LIST_PROP); if (pathListProp.isValid()) { - QStringList list = - editor->property(PATH_LIST_PROP).toStringList(); + QStringList list = editor->property(PATH_LIST_PROP).toStringList(); if (isOutput) { if (list.size() > 0) model->setData(index, list); } else - model->setData(index, list, - RemuxEntryRole::NewPathsToProcessRole); + model->setData(index, list, RemuxEntryRole::NewPathsToProcessRole); } else { QLineEdit *lineEdit = editor->findChild(); model->setData(index, lineEdit->text()); } } -void RemuxEntryPathItemDelegate::paint(QPainter *painter, - const QStyleOptionViewItem &option, +void RemuxEntryPathItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const { - RemuxEntryState state = - index.model() - ->index(index.row(), RemuxEntryColumn::State) - .data(RemuxEntryRole::EntryStateRole) - .value(); + RemuxEntryState state = index.model() + ->index(index.row(), RemuxEntryColumn::State) + .data(RemuxEntryRole::EntryStateRole) + .value(); QStyleOptionViewItem localOption = option; initStyleOption(&localOption, index); if (isOutput) { if (state != Ready) { - QColor background = localOption.palette.color( - QPalette::ColorGroup::Disabled, - QPalette::ColorRole::Window); + QColor background = + localOption.palette.color(QPalette::ColorGroup::Disabled, QPalette::ColorRole::Window); localOption.backgroundBrush = QBrush(background); } } - QApplication::style()->drawControl(QStyle::CE_ItemViewItem, - &localOption, painter); + QApplication::style()->drawControl(QStyle::CE_ItemViewItem, &localOption, painter); } void RemuxEntryPathItemDelegate::handleBrowse(QWidget *container) @@ -217,20 +196,15 @@ void RemuxEntryPathItemDelegate::handleBrowse(QWidget *container) bool isSet = false; if (isOutput) { - QString newPath = SaveFile(container, - QTStr("Remux.SelectTarget"), - currentPath, ExtensionPattern); + QString newPath = SaveFile(container, QTStr("Remux.SelectTarget"), currentPath, ExtensionPattern); if (!newPath.isEmpty()) { - container->setProperty(PATH_LIST_PROP, - QStringList() << newPath); + container->setProperty(PATH_LIST_PROP, QStringList() << newPath); isSet = true; } } else { - QStringList paths = OpenFiles( - container, QTStr("Remux.SelectRecording"), currentPath, - QTStr("Remux.OBSRecording") + QString(" ") + - ExtensionPattern); + QStringList paths = OpenFiles(container, QTStr("Remux.SelectRecording"), currentPath, + QTStr("Remux.OBSRecording") + QString(" ") + ExtensionPattern); if (!paths.empty()) { container->setProperty(PATH_LIST_PROP, paths); @@ -291,8 +265,7 @@ QVariant RemuxQueueModel::data(const QModelIndex &index, int role) const result = queue[index.row()].targetPath; break; } - } else if (role == Qt::DecorationRole && - index.column() == RemuxEntryColumn::State) { + } else if (role == Qt::DecorationRole && index.column() == RemuxEntryColumn::State) { result = getIcon(queue[index.row()].state); } else if (role == RemuxEntryRole::EntryStateRole) { result = queue[index.row()].state; @@ -301,13 +274,11 @@ QVariant RemuxQueueModel::data(const QModelIndex &index, int role) const return result; } -QVariant RemuxQueueModel::headerData(int section, Qt::Orientation orientation, - int role) const +QVariant RemuxQueueModel::headerData(int section, Qt::Orientation orientation, int role) const { QVariant result = QVariant(); - if (role == Qt::DisplayRole && - orientation == Qt::Orientation::Horizontal) { + if (role == Qt::DisplayRole && orientation == Qt::Orientation::Horizontal) { switch (section) { case RemuxEntryColumn::State: result = QString(); @@ -330,16 +301,14 @@ Qt::ItemFlags RemuxQueueModel::flags(const QModelIndex &index) const if (index.column() == RemuxEntryColumn::InputPath) { flags |= Qt::ItemIsEditable; - } else if (index.column() == RemuxEntryColumn::OutputPath && - index.row() != queue.length()) { + } else if (index.column() == RemuxEntryColumn::OutputPath && index.row() != queue.length()) { flags |= Qt::ItemIsEditable; } return flags; } -bool RemuxQueueModel::setData(const QModelIndex &index, const QVariant &value, - int role) +bool RemuxQueueModel::setData(const QModelIndex &index, const QVariant &value, int role) { bool success = false; @@ -348,14 +317,12 @@ bool RemuxQueueModel::setData(const QModelIndex &index, const QVariant &value, if (pathList.size() == 0) { if (index.row() < queue.size()) { - beginRemoveRows(QModelIndex(), index.row(), - index.row()); + beginRemoveRows(QModelIndex(), index.row(), index.row()); queue.removeAt(index.row()); endRemoveRows(); } } else { - if (pathList.size() >= 1 && - index.row() < queue.length()) { + if (pathList.size() >= 1 && index.row() < queue.length()) { queue[index.row()].sourcePath = pathList[0]; checkInputPath(index.row()); @@ -394,8 +361,7 @@ bool RemuxQueueModel::setData(const QModelIndex &index, const QVariant &value, entry.sourcePath = path; entry.state = RemuxEntryState::Empty; - beginInsertRows(QModelIndex(), queue.length() + 1, - queue.length() + 1); + beginInsertRows(QModelIndex(), queue.length() + 1, queue.length() + 1); queue.append(entry); endInsertRows(); @@ -407,22 +373,19 @@ bool RemuxQueueModel::setData(const QModelIndex &index, const QVariant &value, if (path.isEmpty()) { if (index.column() == RemuxEntryColumn::InputPath) { - beginRemoveRows(QModelIndex(), index.row(), - index.row()); + beginRemoveRows(QModelIndex(), index.row(), index.row()); queue.removeAt(index.row()); endRemoveRows(); } } else { switch (index.column()) { case RemuxEntryColumn::InputPath: - queue[index.row()].sourcePath = - value.toString(); + queue[index.row()].sourcePath = value.toString(); checkInputPath(index.row()); success = true; break; case RemuxEntryColumn::OutputPath: - queue[index.row()].targetPath = - value.toString(); + queue[index.row()].targetPath = value.toString(); emit dataChanged(index, index); success = true; break; @@ -479,15 +442,13 @@ void RemuxQueueModel::checkInputPath(int row) QString newExt = ".mp4"; QString suffix = fileInfo.suffix(); - if (suffix.contains("mov", Qt::CaseInsensitive) || - suffix.contains("mp4", Qt::CaseInsensitive)) { + if (suffix.contains("mov", Qt::CaseInsensitive) || suffix.contains("mp4", Qt::CaseInsensitive)) { newExt = ".remuxed." + suffix; } if (entry.state == RemuxEntryState::Ready) - entry.targetPath = QDir::toNativeSeparators( - fileInfo.path() + QDir::separator() + - fileInfo.completeBaseName() + newExt); + entry.targetPath = QDir::toNativeSeparators(fileInfo.path() + QDir::separator() + + fileInfo.completeBaseName() + newExt); } if (entry.state == RemuxEntryState::Ready && isProcessing) @@ -572,8 +533,7 @@ void RemuxQueueModel::beginProcessing() isProcessing = true; - emit dataChanged(index(0, RemuxEntryColumn::State), - index(queue.length(), RemuxEntryColumn::State)); + emit dataChanged(index(0, RemuxEntryColumn::State), index(queue.length(), RemuxEntryColumn::State)); } void RemuxQueueModel::endProcessing() @@ -591,8 +551,7 @@ void RemuxQueueModel::endProcessing() endInsertRows(); } - emit dataChanged(index(0, RemuxEntryColumn::State), - index(queue.length(), RemuxEntryColumn::State)); + emit dataChanged(index(0, RemuxEntryColumn::State), index(queue.length(), RemuxEntryColumn::State)); } bool RemuxQueueModel::beginNextEntry(QString &inputPath, QString &outputPath) @@ -607,8 +566,7 @@ bool RemuxQueueModel::beginNextEntry(QString &inputPath, QString &outputPath) inputPath = entry.sourcePath; outputPath = entry.targetPath; - QModelIndex index = - this->index(row, RemuxEntryColumn::State); + QModelIndex index = this->index(row, RemuxEntryColumn::State); emit dataChanged(index, index); anyStarted = true; @@ -629,8 +587,7 @@ void RemuxQueueModel::finishEntry(bool success) else entry.state = RemuxEntryState::Error; - QModelIndex index = - this->index(row, RemuxEntryColumn::State); + QModelIndex index = this->index(row, RemuxEntryColumn::State); emit dataChanged(index, index); break; @@ -658,8 +615,7 @@ OBSRemux::OBSRemux(const char *path, QWidget *parent, bool autoRemux_) ui->progressBar->setVisible(false); ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - ui->buttonBox->button(QDialogButtonBox::RestoreDefaults) - ->setEnabled(false); + ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(false); if (autoRemux) { resize(280, 40); @@ -673,59 +629,43 @@ OBSRemux::OBSRemux(const char *path, QWidget *parent, bool autoRemux_) ui->progressBar->setValue(0); ui->tableView->setModel(queueModel); - ui->tableView->setItemDelegateForColumn( - RemuxEntryColumn::InputPath, - new RemuxEntryPathItemDelegate(false, recPath)); - ui->tableView->setItemDelegateForColumn( - RemuxEntryColumn::OutputPath, - new RemuxEntryPathItemDelegate(true, recPath)); - ui->tableView->horizontalHeader()->setSectionResizeMode( - QHeaderView::ResizeMode::Stretch); - ui->tableView->horizontalHeader()->setSectionResizeMode( - RemuxEntryColumn::State, QHeaderView::ResizeMode::Fixed); - ui->tableView->setEditTriggers( - QAbstractItemView::EditTrigger::CurrentChanged); + ui->tableView->setItemDelegateForColumn(RemuxEntryColumn::InputPath, + new RemuxEntryPathItemDelegate(false, recPath)); + ui->tableView->setItemDelegateForColumn(RemuxEntryColumn::OutputPath, + new RemuxEntryPathItemDelegate(true, recPath)); + ui->tableView->horizontalHeader()->setSectionResizeMode(QHeaderView::ResizeMode::Stretch); + ui->tableView->horizontalHeader()->setSectionResizeMode(RemuxEntryColumn::State, + QHeaderView::ResizeMode::Fixed); + ui->tableView->setEditTriggers(QAbstractItemView::EditTrigger::CurrentChanged); ui->tableView->setTextElideMode(Qt::ElideMiddle); ui->tableView->setWordWrap(false); installEventFilter(CreateShortcutFilter()); - ui->buttonBox->button(QDialogButtonBox::Ok) - ->setText(QTStr("Remux.Remux")); - ui->buttonBox->button(QDialogButtonBox::Reset) - ->setText(QTStr("Remux.ClearFinished")); - ui->buttonBox->button(QDialogButtonBox::RestoreDefaults) - ->setText(QTStr("Remux.ClearAll")); + ui->buttonBox->button(QDialogButtonBox::Ok)->setText(QTStr("Remux.Remux")); + ui->buttonBox->button(QDialogButtonBox::Reset)->setText(QTStr("Remux.ClearFinished")); + ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setText(QTStr("Remux.ClearAll")); ui->buttonBox->button(QDialogButtonBox::Reset)->setDisabled(true); - connect(ui->buttonBox->button(QDialogButtonBox::Ok), - &QPushButton::clicked, this, &OBSRemux::beginRemux); - connect(ui->buttonBox->button(QDialogButtonBox::Reset), - &QPushButton::clicked, this, &OBSRemux::clearFinished); - connect(ui->buttonBox->button(QDialogButtonBox::RestoreDefaults), - &QPushButton::clicked, this, &OBSRemux::clearAll); - connect(ui->buttonBox->button(QDialogButtonBox::Close), - &QPushButton::clicked, this, &OBSRemux::close); + connect(ui->buttonBox->button(QDialogButtonBox::Ok), &QPushButton::clicked, this, &OBSRemux::beginRemux); + connect(ui->buttonBox->button(QDialogButtonBox::Reset), &QPushButton::clicked, this, &OBSRemux::clearFinished); + connect(ui->buttonBox->button(QDialogButtonBox::RestoreDefaults), &QPushButton::clicked, this, + &OBSRemux::clearAll); + connect(ui->buttonBox->button(QDialogButtonBox::Close), &QPushButton::clicked, this, &OBSRemux::close); worker->moveToThread(&remuxer); remuxer.start(); - connect(worker.data(), &RemuxWorker::updateProgress, this, - &OBSRemux::updateProgress); - connect(&remuxer, &QThread::finished, worker.data(), - &QObject::deleteLater); - connect(worker.data(), &RemuxWorker::remuxFinished, this, - &OBSRemux::remuxFinished); + connect(worker.data(), &RemuxWorker::updateProgress, this, &OBSRemux::updateProgress); + connect(&remuxer, &QThread::finished, worker.data(), &QObject::deleteLater); + connect(worker.data(), &RemuxWorker::remuxFinished, this, &OBSRemux::remuxFinished); connect(this, &OBSRemux::remux, worker.data(), &RemuxWorker::remux); - connect(queueModel.data(), &RemuxQueueModel::rowsInserted, this, - &OBSRemux::rowCountChanged); - connect(queueModel.data(), &RemuxQueueModel::rowsRemoved, this, - &OBSRemux::rowCountChanged); + connect(queueModel.data(), &RemuxQueueModel::rowsInserted, this, &OBSRemux::rowCountChanged); + connect(queueModel.data(), &RemuxQueueModel::rowsRemoved, this, &OBSRemux::rowCountChanged); QModelIndex index = queueModel->createIndex(0, 1); - QMetaObject::invokeMethod(ui->tableView, "setCurrentIndex", - Qt::QueuedConnection, + QMetaObject::invokeMethod(ui->tableView, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(const QModelIndex &, index)); } @@ -741,10 +681,8 @@ bool OBSRemux::stopRemux() bool exit = false; - if (QMessageBox::critical(nullptr, QTStr("Remux.ExitUnfinishedTitle"), - QTStr("Remux.ExitUnfinished"), - QMessageBox::Yes | QMessageBox::No, - QMessageBox::No) == QMessageBox::Yes) { + if (QMessageBox::critical(nullptr, QTStr("Remux.ExitUnfinishedTitle"), QTStr("Remux.ExitUnfinished"), + QMessageBox::Yes | QMessageBox::No, QMessageBox::No) == QMessageBox::Yes) { exit = true; } @@ -773,16 +711,12 @@ void OBSRemux::rowCountChanged(const QModelIndex &, int, int) // at least one row for the empty insertion point. if (queueModel->rowCount() > 1) { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(true); - ui->buttonBox->button(QDialogButtonBox::RestoreDefaults) - ->setEnabled(true); - ui->buttonBox->button(QDialogButtonBox::Reset) - ->setEnabled(queueModel->canClearFinished()); + ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(true); + ui->buttonBox->button(QDialogButtonBox::Reset)->setEnabled(queueModel->canClearFinished()); } else { ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(false); - ui->buttonBox->button(QDialogButtonBox::RestoreDefaults) - ->setEnabled(false); - ui->buttonBox->button(QDialogButtonBox::Reset) - ->setEnabled(false); + ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(false); + ui->buttonBox->button(QDialogButtonBox::Reset)->setEnabled(false); } } @@ -802,8 +736,7 @@ void OBSRemux::dropEvent(QDropEvent *ev) << "*.ts" << "*.m3u8"; - QDirIterator dirIter(fileInfo.absoluteFilePath(), - directoryFilter, QDir::Files, + QDirIterator dirIter(fileInfo.absoluteFilePath(), directoryFilter, QDir::Files, QDirIterator::Subdirectories); while (dirIter.hasNext()) { @@ -815,16 +748,11 @@ void OBSRemux::dropEvent(QDropEvent *ev) } if (urlList.empty()) { - QMessageBox::information(nullptr, - QTStr("Remux.NoFilesAddedTitle"), - QTStr("Remux.NoFilesAdded"), + QMessageBox::information(nullptr, QTStr("Remux.NoFilesAddedTitle"), QTStr("Remux.NoFilesAdded"), QMessageBox::Ok); } else if (!autoRemux) { - QModelIndex insertIndex = - queueModel->index(queueModel->rowCount() - 1, - RemuxEntryColumn::InputPath); - queueModel->setData(insertIndex, urlList, - RemuxEntryRole::NewPathsToProcessRole); + QModelIndex insertIndex = queueModel->index(queueModel->rowCount() - 1, RemuxEntryColumn::InputPath); + queueModel->setData(insertIndex, urlList, RemuxEntryRole::NewPathsToProcessRole); } } @@ -851,9 +779,7 @@ void OBSRemux::beginRemux() for (QFileInfo fileInfo : overwriteFiles) message += fileInfo.canonicalFilePath() + "\n"; - if (OBSMessageBox::question(this, - QTStr("Remux.FileExistsTitle"), - message) != QMessageBox::Yes) + if (OBSMessageBox::question(this, QTStr("Remux.FileExistsTitle"), message) != QMessageBox::Yes) proceedWithRemux = false; } @@ -864,8 +790,7 @@ void OBSRemux::beginRemux() queueModel->beginProcessing(); ui->progressBar->setVisible(true); - ui->buttonBox->button(QDialogButtonBox::Ok) - ->setText(QTStr("Remux.Stop")); + ui->buttonBox->button(QDialogButtonBox::Ok)->setText(QTStr("Remux.Stop")); setAcceptDrops(false); remuxNextEntry(); @@ -892,20 +817,15 @@ void OBSRemux::remuxNextEntry() queueModel->endProcessing(); if (!autoRemux) { - OBSMessageBox::information( - this, QTStr("Remux.FinishedTitle"), - queueModel->checkForErrors() - ? QTStr("Remux.FinishedError") - : QTStr("Remux.Finished")); + OBSMessageBox::information(this, QTStr("Remux.FinishedTitle"), + queueModel->checkForErrors() ? QTStr("Remux.FinishedError") + : QTStr("Remux.Finished")); } ui->progressBar->setVisible(autoRemux); - ui->buttonBox->button(QDialogButtonBox::Ok) - ->setText(QTStr("Remux.Remux")); - ui->buttonBox->button(QDialogButtonBox::RestoreDefaults) - ->setEnabled(true); - ui->buttonBox->button(QDialogButtonBox::Reset) - ->setEnabled(queueModel->canClearFinished()); + ui->buttonBox->button(QDialogButtonBox::Ok)->setText(QTStr("Remux.Remux")); + ui->buttonBox->button(QDialogButtonBox::RestoreDefaults)->setEnabled(true); + ui->buttonBox->button(QDialogButtonBox::Reset)->setEnabled(queueModel->canClearFinished()); setAcceptDrops(true); } } @@ -941,9 +861,7 @@ void OBSRemux::remuxFinished(bool success) QTimer::singleShot(3000, this, &OBSRemux::close); OBSBasic *main = OBSBasic::Get(); - main->ShowStatusBarMessage( - QTStr("Basic.StatusBar.AutoRemuxedTo") - .arg(autoRemuxFile)); + main->ShowStatusBarMessage(QTStr("Basic.StatusBar.AutoRemuxedTo").arg(autoRemuxFile)); } remuxNextEntry(); @@ -991,8 +909,7 @@ void RemuxWorker::remux(const QString &source, const QString &target) bool success = false; media_remux_job_t mr_job = nullptr; - if (media_remux_job_create(&mr_job, QT_TO_UTF8(source), - QT_TO_UTF8(target))) { + if (media_remux_job_create(&mr_job, QT_TO_UTF8(source), QT_TO_UTF8(target))) { success = media_remux_job_process(mr_job, callback, this); diff --git a/UI/window-remux.hpp b/UI/window-remux.hpp index c9e7dcc41..20a13a780 100644 --- a/UI/window-remux.hpp +++ b/UI/window-remux.hpp @@ -31,15 +31,7 @@ class RemuxQueueModel; class RemuxWorker; -enum RemuxEntryState { - Empty, - Ready, - Pending, - InProgress, - Complete, - InvalidPath, - Error -}; +enum RemuxEntryState { Empty, Ready, Pending, InProgress, Complete, InvalidPath, Error }; Q_DECLARE_METATYPE(RemuxEntryState); class OBSRemux : public QDialog { @@ -60,8 +52,7 @@ class OBSRemux : public QDialog { QString autoRemuxFile; public: - explicit OBSRemux(const char *recPath, QWidget *parent = nullptr, - bool autoRemux = false); + explicit OBSRemux(const char *recPath, QWidget *parent = nullptr, bool autoRemux = false); virtual ~OBSRemux() override; using job_t = std::shared_ptr; @@ -95,17 +86,12 @@ class RemuxQueueModel : public QAbstractTableModel { friend class OBSRemux; public: - RemuxQueueModel(QObject *parent = 0) - : QAbstractTableModel(parent), - isProcessing(false) - { - } + RemuxQueueModel(QObject *parent = 0) : QAbstractTableModel(parent), isProcessing(false) {} int rowCount(const QModelIndex &parent = QModelIndex()) const; int columnCount(const QModelIndex &parent = QModelIndex()) const; QVariant data(const QModelIndex &index, int role) const; - QVariant headerData(int section, Qt::Orientation orientation, - int role = Qt::DisplayRole) const; + QVariant headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const; Qt::ItemFlags flags(const QModelIndex &index) const; bool setData(const QModelIndex &index, const QVariant &value, int role); @@ -166,16 +152,12 @@ class RemuxEntryPathItemDelegate : public QStyledItemDelegate { public: RemuxEntryPathItemDelegate(bool isOutput, const QString &defaultPath); - virtual QWidget *createEditor(QWidget *parent, - const QStyleOptionViewItem & /* option */, + virtual QWidget *createEditor(QWidget *parent, const QStyleOptionViewItem & /* option */, const QModelIndex &index) const override; - virtual void setEditorData(QWidget *editor, - const QModelIndex &index) const override; - virtual void setModelData(QWidget *editor, QAbstractItemModel *model, - const QModelIndex &index) const override; - virtual void paint(QPainter *painter, - const QStyleOptionViewItem &option, + virtual void setEditorData(QWidget *editor, const QModelIndex &index) const override; + virtual void setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const override; + virtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const override; private: diff --git a/UI/window-youtube-actions.cpp b/UI/window-youtube-actions.cpp index 39b4d5483..3c32509a2 100644 --- a/UI/window-youtube-actions.cpp +++ b/UI/window-youtube-actions.cpp @@ -16,8 +16,7 @@ const QString SchedulDateAndTimeFormat = "yyyy-MM-dd'T'hh:mm:ss'Z'"; const QString RepresentSchedulDateAndTimeFormat = "dddd, MMMM d, yyyy h:m"; const QString IndexOfGamingCategory = "20"; -OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, - bool broadcastReady) +OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, bool broadcastReady) : QDialog(parent), ui(new Ui::OBSYoutubeActions), apiYouTube(dynamic_cast(auth)), @@ -27,40 +26,26 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint); ui->setupUi(this); - ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Public"), - "public"); - ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Unlisted"), - "unlisted"); - ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Private"), - "private"); + ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Public"), "public"); + ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Unlisted"), "unlisted"); + ui->privacyBox->addItem(QTStr("YouTube.Actions.Privacy.Private"), "private"); - ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Normal"), - "normal"); + ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Normal"), "normal"); ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.Low"), "low"); - ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.UltraLow"), - "ultraLow"); + ui->latencyBox->addItem(QTStr("YouTube.Actions.Latency.UltraLow"), "ultraLow"); UpdateOkButtonStatus(); - connect(ui->title, &QLineEdit::textChanged, this, - [&](const QString &) { this->UpdateOkButtonStatus(); }); + connect(ui->title, &QLineEdit::textChanged, this, [&](const QString &) { this->UpdateOkButtonStatus(); }); connect(ui->privacyBox, &QComboBox::currentTextChanged, this, [&](const QString &) { this->UpdateOkButtonStatus(); }); - connect(ui->yesMakeForKids, &QRadioButton::toggled, this, - [&](bool) { this->UpdateOkButtonStatus(); }); - connect(ui->notMakeForKids, &QRadioButton::toggled, this, - [&](bool) { this->UpdateOkButtonStatus(); }); - connect(ui->tabWidget, &QTabWidget::currentChanged, this, - [&](int) { this->UpdateOkButtonStatus(); }); - connect(ui->pushButton, &QPushButton::clicked, this, - &OBSYoutubeActions::OpenYouTubeDashboard); + connect(ui->yesMakeForKids, &QRadioButton::toggled, this, [&](bool) { this->UpdateOkButtonStatus(); }); + connect(ui->notMakeForKids, &QRadioButton::toggled, this, [&](bool) { this->UpdateOkButtonStatus(); }); + connect(ui->tabWidget, &QTabWidget::currentChanged, this, [&](int) { this->UpdateOkButtonStatus(); }); + connect(ui->pushButton, &QPushButton::clicked, this, &OBSYoutubeActions::OpenYouTubeDashboard); connect(ui->helpAutoStartStop, &QLabel::linkActivated, this, - [](const QString &) { - QToolTip::showText( - QCursor::pos(), - QTStr("YouTube.Actions.AutoStartStop.TT")); - }); + [](const QString &) { QToolTip::showText(QCursor::pos(), QTStr("YouTube.Actions.AutoStartStop.TT")); }); connect(ui->help360Video, &QLabel::linkActivated, this, [](const QString &link) { QDesktopServices::openUrl(link); }); connect(ui->helpMadeForKids, &QLabel::linkActivated, this, @@ -103,53 +88,38 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, auto thumbSelectionHandler = [&]() { if (thumbnailFile.isEmpty()) { - QString filePath = OpenFile( - this, - QTStr("YouTube.Actions.Thumbnail.SelectFile"), - QStandardPaths::writableLocation( - QStandardPaths::PicturesLocation), - QString("Images (*.png *.jpg *.jpeg *.gif)")); + QString filePath = OpenFile(this, QTStr("YouTube.Actions.Thumbnail.SelectFile"), + QStandardPaths::writableLocation(QStandardPaths::PicturesLocation), + QString("Images (*.png *.jpg *.jpeg *.gif)")); if (!filePath.isEmpty()) { QFileInfo tFile(filePath); if (!tFile.exists()) { - return ShowErrorDialog( - this, - QTStr("YouTube.Actions.Error.FileMissing")); + return ShowErrorDialog(this, QTStr("YouTube.Actions.Error.FileMissing")); } else if (tFile.size() > 2 * 1024 * 1024) { - return ShowErrorDialog( - this, - QTStr("YouTube.Actions.Error.FileTooLarge")); + return ShowErrorDialog(this, QTStr("YouTube.Actions.Error.FileTooLarge")); } thumbnailFile = filePath; ui->selectedFileName->setText(thumbnailFile); - ui->selectFileButton->setText(QTStr( - "YouTube.Actions.Thumbnail.ClearFile")); + ui->selectFileButton->setText(QTStr("YouTube.Actions.Thumbnail.ClearFile")); QImageReader imgReader(filePath); imgReader.setAutoTransform(true); const QImage newImage = imgReader.read(); - ui->thumbnailPreview->setPixmap( - QPixmap::fromImage(newImage).scaled( - 160, 90, Qt::KeepAspectRatio, - Qt::SmoothTransformation)); + ui->thumbnailPreview->setPixmap(QPixmap::fromImage(newImage).scaled( + 160, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } } else { thumbnailFile.clear(); - ui->selectedFileName->setText(QTStr( - "YouTube.Actions.Thumbnail.NoFileSelected")); - ui->selectFileButton->setText( - QTStr("YouTube.Actions.Thumbnail.SelectFile")); - ui->thumbnailPreview->setPixmap( - GetPlaceholder().pixmap(QSize(16, 16))); + ui->selectedFileName->setText(QTStr("YouTube.Actions.Thumbnail.NoFileSelected")); + ui->selectFileButton->setText(QTStr("YouTube.Actions.Thumbnail.SelectFile")); + ui->thumbnailPreview->setPixmap(GetPlaceholder().pixmap(QSize(16, 16))); } }; - connect(ui->selectFileButton, &QPushButton::clicked, this, - thumbSelectionHandler); - connect(ui->thumbnailPreview, &ClickableLabel::clicked, this, - thumbSelectionHandler); + connect(ui->selectFileButton, &QPushButton::clicked, this, thumbSelectionHandler); + connect(ui->thumbnailPreview, &ClickableLabel::clicked, this, thumbSelectionHandler); if (!apiYouTube) { blog(LOG_DEBUG, "YouTube API auth NOT found."); @@ -157,18 +127,14 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, return; } - const char *name = config_get_string(OBSBasic::Get()->Config(), - "YouTube", "ChannelName"); + const char *name = config_get_string(OBSBasic::Get()->Config(), "YouTube", "ChannelName"); this->setWindowTitle(QTStr("YouTube.Actions.WindowTitle").arg(name)); QVector category_list; if (!apiYouTube->GetVideoCategoriesList(category_list)) { - ShowErrorDialog( - parent, - apiYouTube->GetLastError().isEmpty() - ? QTStr("YouTube.Actions.Error.General") - : QTStr("YouTube.Actions.Error.Text") - .arg(apiYouTube->GetLastError())); + ShowErrorDialog(parent, apiYouTube->GetLastError().isEmpty() + ? QTStr("YouTube.Actions.Error.General") + : QTStr("YouTube.Actions.Error.Text").arg(apiYouTube->GetLastError())); Cancel(); return; } @@ -179,32 +145,26 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, } } - connect(ui->okButton, &QPushButton::clicked, this, - &OBSYoutubeActions::InitBroadcast); - connect(ui->saveButton, &QPushButton::clicked, this, - &OBSYoutubeActions::ReadyBroadcast); + connect(ui->okButton, &QPushButton::clicked, this, &OBSYoutubeActions::InitBroadcast); + connect(ui->saveButton, &QPushButton::clicked, this, &OBSYoutubeActions::ReadyBroadcast); connect(ui->cancelButton, &QPushButton::clicked, this, [&]() { blog(LOG_DEBUG, "YouTube live broadcast creation cancelled."); // Close the dialog. Cancel(); }); - qDeleteAll(ui->scrollAreaWidgetContents->findChildren( - QString(), Qt::FindDirectChildrenOnly)); + qDeleteAll(ui->scrollAreaWidgetContents->findChildren(QString(), Qt::FindDirectChildrenOnly)); // Add label indicating loading state QLabel *loadingLabel = new QLabel(); loadingLabel->setTextFormat(Qt::RichText); loadingLabel->setAlignment(Qt::AlignHCenter); - loadingLabel->setText( - QString("%1") - .arg(QTStr("YouTube.Actions.EventsLoading"))); + loadingLabel->setText(QString("%1").arg(QTStr("YouTube.Actions.EventsLoading"))); ui->scrollAreaWidgetContents->layout()->addWidget(loadingLabel); // Delete "loading..." label on completion connect(workerThread, &WorkerThread::finished, this, [&] { - QLayoutItem *item = - ui->scrollAreaWidgetContents->layout()->takeAt(0); + QLayoutItem *item = ui->scrollAreaWidgetContents->layout()->takeAt(0); item->widget()->deleteLater(); }); @@ -214,70 +174,57 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); if (!apiYouTube->GetTranslatedError(last_error)) - last_error = QTStr("YouTube.Actions.Error.Text") - .arg(last_error); + last_error = QTStr("YouTube.Actions.Error.Text").arg(last_error); ShowErrorDialog(this, last_error); QDialog::reject(); }); connect(workerThread, &WorkerThread::new_item, this, - [&](const QString &title, const QString &dateTimeString, - const QString &broadcast, const QString &status, - bool astart, bool astop) { + [&](const QString &title, const QString &dateTimeString, const QString &broadcast, + const QString &status, bool astart, bool astop) { ClickableLabel *label = new ClickableLabel(); label->setTextFormat(Qt::RichText); if (status == "live" || status == "testing") { // Resumable stream - label->setText( - QString("%1
%2") - .arg(title, - QTStr("YouTube.Actions.Stream.Resume"))); + label->setText(QString("%1
%2") + .arg(title, QTStr("YouTube.Actions.Stream.Resume"))); } else if (dateTimeString.isEmpty()) { // The broadcast created by YouTube Studio has no start time. // Yes this does violate the restrictions set in YouTube's API // But why would YouTube care about consistency? - label->setText( - QString("%1
%2") - .arg(title, - QTStr("YouTube.Actions.Stream.YTStudio"))); + label->setText(QString("%1
%2") + .arg(title, QTStr("YouTube.Actions.Stream.YTStudio"))); } else { label->setText( QString("%1
%2") .arg(title, - QTStr("YouTube.Actions.Stream.ScheduledFor") - .arg(dateTimeString))); + QTStr("YouTube.Actions.Stream.ScheduledFor").arg(dateTimeString))); } label->setAlignment(Qt::AlignHCenter); label->setMargin(4); - connect(label, &ClickableLabel::clicked, this, - [&, label, broadcast, astart, astop]() { - for (QWidget *i : - ui->scrollAreaWidgetContents->findChildren< - QWidget *>( - QString(), - Qt::FindDirectChildrenOnly)) { + connect(label, &ClickableLabel::clicked, this, [&, label, broadcast, astart, astop]() { + for (QWidget *i : ui->scrollAreaWidgetContents->findChildren( + QString(), Qt::FindDirectChildrenOnly)) { - i->setProperty("class", ""); - i->style()->unpolish(i); - i->style()->polish(i); - } - label->setProperty("class", - "row-selected"); - label->style()->unpolish(label); - label->style()->polish(label); + i->setProperty("class", ""); + i->style()->unpolish(i); + i->style()->polish(i); + } + label->setProperty("class", "row-selected"); + label->style()->unpolish(label); + label->style()->polish(label); - this->selectedBroadcast = broadcast; - this->autostart = astart; - this->autostop = astop; - UpdateOkButtonStatus(); - }); - ui->scrollAreaWidgetContents->layout()->addWidget( - label); + this->selectedBroadcast = broadcast; + this->autostart = astart; + this->autostop = astop; + UpdateOkButtonStatus(); + }); + ui->scrollAreaWidgetContents->layout()->addWidget(label); if (selectedBroadcast == broadcast) label->clicked(); @@ -285,8 +232,7 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, workerThread->start(); OBSBasic *main = OBSBasic::Get(); - bool rememberSettings = config_get_bool(main->activeConfiguration, - "YouTube", "RememberSettings"); + bool rememberSettings = config_get_bool(main->activeConfiguration, "YouTube", "RememberSettings"); if (rememberSettings) LoadSettings(); @@ -307,8 +253,7 @@ void OBSYoutubeActions::showEvent(QShowEvent *event) { QDialog::showEvent(event); if (thumbnailFile.isEmpty()) - ui->thumbnailPreview->setPixmap( - GetPlaceholder().pixmap(QSize(16, 16))); + ui->thumbnailPreview->setPixmap(GetPlaceholder().pixmap(QSize(16, 16))); } OBSYoutubeActions::~OBSYoutubeActions() @@ -326,8 +271,7 @@ void WorkerThread::run() json11::Json broadcasts; for (QString broadcastStatus : {"active", "upcoming"}) { - if (!apiYouTube->GetBroadcastsList(broadcasts, "", - broadcastStatus)) { + if (!apiYouTube->GetBroadcastsList(broadcasts, "", broadcastStatus)) { emit failed(); return; } @@ -335,75 +279,50 @@ void WorkerThread::run() while (pending) { auto items = broadcasts["items"].array_items(); for (auto item : items) { - QString status = QString::fromStdString( - item["status"]["lifeCycleStatus"] - .string_value()); + QString status = + QString::fromStdString(item["status"]["lifeCycleStatus"].string_value()); if (status == "live" || status == "testing") { // Check that the attached liveStream is offline (reconnectable) QString stream_id = QString::fromStdString( - item["contentDetails"] - ["boundStreamId"] - .string_value()); + item["contentDetails"]["boundStreamId"].string_value()); json11::Json stream; - if (!apiYouTube->FindStream(stream_id, - stream)) + if (!apiYouTube->FindStream(stream_id, stream)) continue; - if (stream["status"]["streamStatus"] == - "active") + if (stream["status"]["streamStatus"] == "active") continue; } - QString title = QString::fromStdString( - item["snippet"]["title"].string_value()); + QString title = QString::fromStdString(item["snippet"]["title"].string_value()); QString scheduledStartTime = - QString::fromStdString( - item["snippet"] - ["scheduledStartTime"] - .string_value()); - QString broadcast = QString::fromStdString( - item["id"].string_value()); + QString::fromStdString(item["snippet"]["scheduledStartTime"].string_value()); + QString broadcast = QString::fromStdString(item["id"].string_value()); // Treat already started streams as autostart for UI purposes - bool astart = - status == "live" || - item["contentDetails"]["enableAutoStart"] - .bool_value(); - bool astop = - item["contentDetails"]["enableAutoStop"] - .bool_value(); + bool astart = status == "live" || + item["contentDetails"]["enableAutoStart"].bool_value(); + bool astop = item["contentDetails"]["enableAutoStop"].bool_value(); - QDateTime utcDTime = QDateTime::fromString( - scheduledStartTime, - SchedulDateAndTimeFormat); + QDateTime utcDTime = + QDateTime::fromString(scheduledStartTime, SchedulDateAndTimeFormat); // DateTime parser means that input datetime is a local, so we need to move it - QDateTime dateTime = utcDTime.addSecs( - utcDTime.offsetFromUtc()); + QDateTime dateTime = utcDTime.addSecs(utcDTime.offsetFromUtc()); QString dateTimeString = QLocale().toString( - dateTime, - QString("%1 %2").arg( - QLocale().dateFormat( - QLocale::LongFormat), - QLocale().timeFormat( - QLocale::ShortFormat))); + dateTime, QString("%1 %2").arg(QLocale().dateFormat(QLocale::LongFormat), + QLocale().timeFormat(QLocale::ShortFormat))); - emit new_item(title, dateTimeString, broadcast, - status, astart, astop); + emit new_item(title, dateTimeString, broadcast, status, astart, astop); } - auto nextPageToken = - broadcasts["nextPageToken"].string_value(); + auto nextPageToken = broadcasts["nextPageToken"].string_value(); if (nextPageToken.empty() || items.empty()) break; else { if (!pending) return; - if (!apiYouTube->GetBroadcastsList( - broadcasts, - QString::fromStdString( - nextPageToken), - broadcastStatus)) { + if (!apiYouTube->GetBroadcastsList(broadcasts, QString::fromStdString(nextPageToken), + broadcastStatus)) { emit failed(); return; } @@ -419,23 +338,17 @@ void OBSYoutubeActions::UpdateOkButtonStatus() bool enable = false; if (ui->tabWidget->currentIndex() == 0) { - enable = !ui->title->text().isEmpty() && - !ui->privacyBox->currentText().isEmpty() && - (ui->yesMakeForKids->isChecked() || - ui->notMakeForKids->isChecked()); + enable = !ui->title->text().isEmpty() && !ui->privacyBox->currentText().isEmpty() && + (ui->yesMakeForKids->isChecked() || ui->notMakeForKids->isChecked()); ui->okButton->setEnabled(enable); ui->saveButton->setEnabled(enable); if (ui->checkScheduledLater->checkState() == Qt::Checked) { - ui->okButton->setText( - QTStr("YouTube.Actions.Create_Schedule")); - ui->saveButton->setText( - QTStr("YouTube.Actions.Create_Schedule_Ready")); + ui->okButton->setText(QTStr("YouTube.Actions.Create_Schedule")); + ui->saveButton->setText(QTStr("YouTube.Actions.Create_Schedule_Ready")); } else { - ui->okButton->setText( - QTStr("YouTube.Actions.Create_GoLive")); - ui->saveButton->setText( - QTStr("YouTube.Actions.Create_Ready")); + ui->okButton->setText(QTStr("YouTube.Actions.Create_GoLive")); + ui->saveButton->setText(QTStr("YouTube.Actions.Create_Ready")); } ui->pushButton->setVisible(false); } else { @@ -448,11 +361,8 @@ void OBSYoutubeActions::UpdateOkButtonStatus() ui->pushButton->setVisible(true); } } -bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, - BroadcastDescription &broadcast, - StreamDescription &stream, - bool stream_later, - bool ready_broadcast) +bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, BroadcastDescription &broadcast, + StreamDescription &stream, bool stream_later, bool ready_broadcast) { YoutubeApiWrappers *apiYouTube = api; UiToBroadcast(broadcast); @@ -461,37 +371,30 @@ bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, // DateTime parser means that input datetime is a local, so we need to move it auto dateTime = ui->scheduledTime->dateTime(); auto utcDTime = dateTime.addSecs(-dateTime.offsetFromUtc()); - broadcast.schedul_date_time = - utcDTime.toString(SchedulDateAndTimeFormat); + broadcast.schedul_date_time = utcDTime.toString(SchedulDateAndTimeFormat); } else { // stream now is always autostart/autostop broadcast.auto_start = true; broadcast.auto_stop = true; - broadcast.schedul_date_time = - QDateTime::currentDateTimeUtc().toString( - SchedulDateAndTimeFormat); + broadcast.schedul_date_time = QDateTime::currentDateTimeUtc().toString(SchedulDateAndTimeFormat); } autostart = broadcast.auto_start; autostop = broadcast.auto_stop; - blog(LOG_DEBUG, "Scheduled date and time: %s", - broadcast.schedul_date_time.toStdString().c_str()); + blog(LOG_DEBUG, "Scheduled date and time: %s", broadcast.schedul_date_time.toStdString().c_str()); if (!apiYouTube->InsertBroadcast(broadcast)) { blog(LOG_DEBUG, "No broadcast created."); return false; } - if (!apiYouTube->SetVideoCategory(broadcast.id, broadcast.title, - broadcast.description, + if (!apiYouTube->SetVideoCategory(broadcast.id, broadcast.title, broadcast.description, broadcast.category.id)) { blog(LOG_DEBUG, "No category set."); return false; } if (!thumbnailFile.isEmpty()) { - blog(LOG_INFO, "Uploading thumbnail file \"%s\"...", - thumbnailFile.toStdString().c_str()); - if (!apiYouTube->SetVideoThumbnail(broadcast.id, - thumbnailFile)) { + blog(LOG_INFO, "Uploading thumbnail file \"%s\"...", thumbnailFile.toStdString().c_str()); + if (!apiYouTube->SetVideoThumbnail(broadcast.id, thumbnailFile)) { blog(LOG_DEBUG, "No thumbnail set."); return false; } @@ -510,8 +413,7 @@ bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, } if (broadcast.privacy != "private") { - const std::string apiLiveChatId = - json["snippet"]["liveChatId"].string_value(); + const std::string apiLiveChatId = json["snippet"]["liveChatId"].string_value(); apiYouTube->SetChatId(broadcast.id, apiLiveChatId); } else { apiYouTube->ResetChat(); @@ -520,15 +422,13 @@ bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, #ifdef YOUTUBE_ENABLED if (OBSBasic::Get()->GetYouTubeAppDock()) - OBSBasic::Get()->GetYouTubeAppDock()->BroadcastCreated( - broadcast.id.toStdString().c_str()); + OBSBasic::Get()->GetYouTubeAppDock()->BroadcastCreated(broadcast.id.toStdString().c_str()); #endif return true; } -bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, - StreamDescription &stream) +bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, StreamDescription &stream) { YoutubeApiWrappers *apiYouTube = api; @@ -538,24 +438,14 @@ bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, return false; } - std::string boundStreamId = - json["items"] - .array_items()[0]["contentDetails"]["boundStreamId"] - .string_value(); - std::string broadcastPrivacy = - json["items"] - .array_items()[0]["status"]["privacyStatus"] - .string_value(); - std::string apiLiveChatId = - json["items"] - .array_items()[0]["snippet"]["liveChatId"] - .string_value(); + std::string boundStreamId = json["items"].array_items()[0]["contentDetails"]["boundStreamId"].string_value(); + std::string broadcastPrivacy = json["items"].array_items()[0]["status"]["privacyStatus"].string_value(); + std::string apiLiveChatId = json["items"].array_items()[0]["snippet"]["liveChatId"].string_value(); stream.id = boundStreamId.c_str(); if (!stream.id.isEmpty() && apiYouTube->FindStream(stream.id, json)) { auto item = json["items"].array_items()[0]; - auto streamName = item["cdn"]["ingestionInfo"]["streamName"] - .string_value(); + auto streamName = item["cdn"]["ingestionInfo"]["streamName"].string_value(); auto title = item["snippet"]["title"].string_value(); stream.name = streamName.c_str(); @@ -567,8 +457,7 @@ bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, blog(LOG_DEBUG, "No stream created."); return false; } - if (!apiYouTube->BindStream(selectedBroadcast, stream.id, - json)) { + if (!apiYouTube->BindStream(selectedBroadcast, stream.id, json)) { blog(LOG_DEBUG, "No stream binded."); return false; } @@ -581,8 +470,7 @@ bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, #ifdef YOUTUBE_ENABLED if (OBSBasic::Get()->GetYouTubeAppDock()) - OBSBasic::Get()->GetYouTubeAppDock()->BroadcastSelected( - selectedBroadcast.toStdString().c_str()); + OBSBasic::Get()->GetYouTubeAppDock()->BroadcastSelected(selectedBroadcast.toStdString().c_str()); #endif return true; @@ -605,8 +493,7 @@ void OBSYoutubeActions::InitBroadcast() BroadcastDescription broadcast; StreamDescription stream; QMessageBox msgBox(this); - msgBox.setWindowFlags(msgBox.windowFlags() & - ~Qt::WindowCloseButtonHint); + msgBox.setWindowFlags(msgBox.windowFlags() & ~Qt::WindowCloseButtonHint); msgBox.setWindowTitle(QTStr("YouTube.Actions.Notify.Title")); msgBox.setText(QTStr("YouTube.Actions.Notify.CreatingBroadcast")); msgBox.setStandardButtons(QMessageBox::StandardButtons()); @@ -614,16 +501,14 @@ void OBSYoutubeActions::InitBroadcast() bool success = false; auto action = [&]() { if (ui->tabWidget->currentIndex() == 0) { - success = this->CreateEventAction( - apiYouTube, broadcast, stream, - ui->checkScheduledLater->isChecked()); + success = this->CreateEventAction(apiYouTube, broadcast, stream, + ui->checkScheduledLater->isChecked()); } else { success = this->ChooseAnEventAction(apiYouTube, stream); if (success) broadcast.id = this->selectedBroadcast; }; - QMetaObject::invokeMethod(&msgBox, "accept", - Qt::QueuedConnection); + QMetaObject::invokeMethod(&msgBox, "accept", Qt::QueuedConnection); }; QScopedPointer thread(CreateQThread(action)); thread->start(); @@ -635,29 +520,23 @@ void OBSYoutubeActions::InitBroadcast() // Stream later usecase. if (ui->checkScheduledLater->isChecked()) { QMessageBox msg(this); - msg.setWindowTitle(QTStr( - "YouTube.Actions.EventCreated.Title")); - msg.setText(QTStr( - "YouTube.Actions.EventCreated.Text")); + msg.setWindowTitle(QTStr("YouTube.Actions.EventCreated.Title")); + msg.setText(QTStr("YouTube.Actions.EventCreated.Text")); msg.setStandardButtons(QMessageBox::Ok); msg.exec(); // Close dialog without start streaming. Cancel(); } else { // Stream now usecase. - blog(LOG_DEBUG, "New valid stream: %s", - QT_TO_UTF8(stream.name)); - emit ok(QT_TO_UTF8(broadcast.id), - QT_TO_UTF8(stream.id), - QT_TO_UTF8(stream.name), true, true, - true); + blog(LOG_DEBUG, "New valid stream: %s", QT_TO_UTF8(stream.name)); + emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name), true, + true, true); Accept(); } } else { // Stream to precreated broadcast usecase. - emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), - QT_TO_UTF8(stream.name), autostart, autostop, - true); + emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name), autostart, + autostop, true); Accept(); } } else { @@ -666,9 +545,7 @@ void OBSYoutubeActions::InitBroadcast() if (last_error.isEmpty()) last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); if (!apiYouTube->GetTranslatedError(last_error)) - last_error = - QTStr("YouTube.Actions.Error.NoBroadcastCreated") - .arg(last_error); + last_error = QTStr("YouTube.Actions.Error.NoBroadcastCreated").arg(last_error); ShowErrorDialog(this, last_error); } @@ -679,8 +556,7 @@ void OBSYoutubeActions::ReadyBroadcast() BroadcastDescription broadcast; StreamDescription stream; QMessageBox msgBox(this); - msgBox.setWindowFlags(msgBox.windowFlags() & - ~Qt::WindowCloseButtonHint); + msgBox.setWindowFlags(msgBox.windowFlags() & ~Qt::WindowCloseButtonHint); msgBox.setWindowTitle(QTStr("YouTube.Actions.Notify.Title")); msgBox.setText(QTStr("YouTube.Actions.Notify.CreatingBroadcast")); msgBox.setStandardButtons(QMessageBox::StandardButtons()); @@ -688,16 +564,14 @@ void OBSYoutubeActions::ReadyBroadcast() bool success = false; auto action = [&]() { if (ui->tabWidget->currentIndex() == 0) { - success = this->CreateEventAction( - apiYouTube, broadcast, stream, - ui->checkScheduledLater->isChecked(), true); + success = this->CreateEventAction(apiYouTube, broadcast, stream, + ui->checkScheduledLater->isChecked(), true); } else { success = this->ChooseAnEventAction(apiYouTube, stream); if (success) broadcast.id = this->selectedBroadcast; }; - QMetaObject::invokeMethod(&msgBox, "accept", - Qt::QueuedConnection); + QMetaObject::invokeMethod(&msgBox, "accept", Qt::QueuedConnection); }; QScopedPointer thread(CreateQThread(action)); thread->start(); @@ -705,8 +579,8 @@ void OBSYoutubeActions::ReadyBroadcast() thread->wait(); if (success) { - emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), - QT_TO_UTF8(stream.name), autostart, autostop, false); + emit ok(QT_TO_UTF8(broadcast.id), QT_TO_UTF8(stream.id), QT_TO_UTF8(stream.name), autostart, autostop, + false); Accept(); } else { // Fail. @@ -714,9 +588,7 @@ void OBSYoutubeActions::ReadyBroadcast() if (last_error.isEmpty()) last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); if (!apiYouTube->GetTranslatedError(last_error)) - last_error = - QTStr("YouTube.Actions.Error.NoBroadcastCreated") - .arg(last_error); + last_error = QTStr("YouTube.Actions.Error.NoBroadcastCreated").arg(last_error); ShowErrorDialog(this, last_error); } @@ -736,8 +608,7 @@ void OBSYoutubeActions::UiToBroadcast(BroadcastDescription &broadcast) broadcast.auto_stop = ui->checkAutoStop->isChecked(); broadcast.dvr = ui->checkDVR->isChecked(); broadcast.schedul_for_later = ui->checkScheduledLater->isChecked(); - broadcast.projection = ui->check360Video->isChecked() ? "360" - : "rectangular"; + broadcast.projection = ui->check360Video->isChecked() ? "360" : "rectangular"; if (ui->checkRememberSettings->isChecked()) SaveSettings(broadcast); @@ -747,85 +618,62 @@ void OBSYoutubeActions::SaveSettings(BroadcastDescription &broadcast) { OBSBasic *main = OBSBasic::Get(); - config_set_string(main->activeConfiguration, "YouTube", "Title", - QT_TO_UTF8(broadcast.title)); - config_set_string(main->activeConfiguration, "YouTube", "Description", - QT_TO_UTF8(broadcast.description)); - config_set_string(main->activeConfiguration, "YouTube", "Privacy", - QT_TO_UTF8(broadcast.privacy)); - config_set_string(main->activeConfiguration, "YouTube", "CategoryID", - QT_TO_UTF8(broadcast.category.id)); - config_set_string(main->activeConfiguration, "YouTube", "Latency", - QT_TO_UTF8(broadcast.latency)); - config_set_bool(main->activeConfiguration, "YouTube", "MadeForKids", - broadcast.made_for_kids); - config_set_bool(main->activeConfiguration, "YouTube", "AutoStart", - broadcast.auto_start); - config_set_bool(main->activeConfiguration, "YouTube", "AutoStop", - broadcast.auto_start); - config_set_bool(main->activeConfiguration, "YouTube", "DVR", - broadcast.dvr); - config_set_bool(main->activeConfiguration, "YouTube", - "ScheduleForLater", broadcast.schedul_for_later); - config_set_string(main->activeConfiguration, "YouTube", "Projection", - QT_TO_UTF8(broadcast.projection)); - config_set_string(main->activeConfiguration, "YouTube", "ThumbnailFile", - QT_TO_UTF8(thumbnailFile)); - config_set_bool(main->activeConfiguration, "YouTube", - "RememberSettings", true); + config_set_string(main->activeConfiguration, "YouTube", "Title", QT_TO_UTF8(broadcast.title)); + config_set_string(main->activeConfiguration, "YouTube", "Description", QT_TO_UTF8(broadcast.description)); + config_set_string(main->activeConfiguration, "YouTube", "Privacy", QT_TO_UTF8(broadcast.privacy)); + config_set_string(main->activeConfiguration, "YouTube", "CategoryID", QT_TO_UTF8(broadcast.category.id)); + config_set_string(main->activeConfiguration, "YouTube", "Latency", QT_TO_UTF8(broadcast.latency)); + config_set_bool(main->activeConfiguration, "YouTube", "MadeForKids", broadcast.made_for_kids); + config_set_bool(main->activeConfiguration, "YouTube", "AutoStart", broadcast.auto_start); + config_set_bool(main->activeConfiguration, "YouTube", "AutoStop", broadcast.auto_start); + config_set_bool(main->activeConfiguration, "YouTube", "DVR", broadcast.dvr); + config_set_bool(main->activeConfiguration, "YouTube", "ScheduleForLater", broadcast.schedul_for_later); + config_set_string(main->activeConfiguration, "YouTube", "Projection", QT_TO_UTF8(broadcast.projection)); + config_set_string(main->activeConfiguration, "YouTube", "ThumbnailFile", QT_TO_UTF8(thumbnailFile)); + config_set_bool(main->activeConfiguration, "YouTube", "RememberSettings", true); } void OBSYoutubeActions::LoadSettings() { OBSBasic *main = OBSBasic::Get(); - const char *title = config_get_string(main->activeConfiguration, - "YouTube", "Title"); + const char *title = config_get_string(main->activeConfiguration, "YouTube", "Title"); ui->title->setText(QT_UTF8(title)); - const char *desc = config_get_string(main->activeConfiguration, - "YouTube", "Description"); + const char *desc = config_get_string(main->activeConfiguration, "YouTube", "Description"); ui->description->setPlainText(QT_UTF8(desc)); - const char *priv = config_get_string(main->activeConfiguration, - "YouTube", "Privacy"); + const char *priv = config_get_string(main->activeConfiguration, "YouTube", "Privacy"); int index = ui->privacyBox->findData(priv); ui->privacyBox->setCurrentIndex(index); - const char *catID = config_get_string(main->activeConfiguration, - "YouTube", "CategoryID"); + const char *catID = config_get_string(main->activeConfiguration, "YouTube", "CategoryID"); index = ui->categoryBox->findData(catID); ui->categoryBox->setCurrentIndex(index); - const char *latency = config_get_string(main->activeConfiguration, - "YouTube", "Latency"); + const char *latency = config_get_string(main->activeConfiguration, "YouTube", "Latency"); index = ui->latencyBox->findData(latency); ui->latencyBox->setCurrentIndex(index); bool dvr = config_get_bool(main->activeConfiguration, "YouTube", "DVR"); ui->checkDVR->setChecked(dvr); - bool forKids = config_get_bool(main->activeConfiguration, "YouTube", - "MadeForKids"); + bool forKids = config_get_bool(main->activeConfiguration, "YouTube", "MadeForKids"); if (forKids) ui->yesMakeForKids->setChecked(true); else ui->notMakeForKids->setChecked(true); - bool schedLater = config_get_bool(main->activeConfiguration, "YouTube", - "ScheduleForLater"); + bool schedLater = config_get_bool(main->activeConfiguration, "YouTube", "ScheduleForLater"); ui->checkScheduledLater->setChecked(schedLater); - bool autoStart = config_get_bool(main->activeConfiguration, "YouTube", - "AutoStart"); + bool autoStart = config_get_bool(main->activeConfiguration, "YouTube", "AutoStart"); ui->checkAutoStart->setChecked(autoStart); - bool autoStop = config_get_bool(main->activeConfiguration, "YouTube", - "AutoStop"); + bool autoStop = config_get_bool(main->activeConfiguration, "YouTube", "AutoStop"); ui->checkAutoStop->setChecked(autoStop); - const char *projection = config_get_string(main->activeConfiguration, - "YouTube", "Projection"); + const char *projection = config_get_string(main->activeConfiguration, "YouTube", "Projection"); if (projection && *projection) { if (strcmp(projection, "360") == 0) ui->check360Video->setChecked(true); @@ -833,24 +681,20 @@ void OBSYoutubeActions::LoadSettings() ui->check360Video->setChecked(false); } - const char *thumbFile = config_get_string(main->activeConfiguration, - "YouTube", "ThumbnailFile"); + const char *thumbFile = config_get_string(main->activeConfiguration, "YouTube", "ThumbnailFile"); if (thumbFile && *thumbFile) { QFileInfo tFile(thumbFile); // Re-check validity before setting path again if (tFile.exists() && tFile.size() <= 2 * 1024 * 1024) { thumbnailFile = tFile.absoluteFilePath(); ui->selectedFileName->setText(thumbnailFile); - ui->selectFileButton->setText( - QTStr("YouTube.Actions.Thumbnail.ClearFile")); + ui->selectFileButton->setText(QTStr("YouTube.Actions.Thumbnail.ClearFile")); QImageReader imgReader(thumbnailFile); imgReader.setAutoTransform(true); const QImage newImage = imgReader.read(); - ui->thumbnailPreview->setPixmap( - QPixmap::fromImage(newImage).scaled( - 160, 90, Qt::KeepAspectRatio, - Qt::SmoothTransformation)); + ui->thumbnailPreview->setPixmap(QPixmap::fromImage(newImage).scaled( + 160, 90, Qt::KeepAspectRatio, Qt::SmoothTransformation)); } } } @@ -860,12 +704,9 @@ void OBSYoutubeActions::OpenYouTubeDashboard() ChannelDescription channel; if (!apiYouTube->GetChannelDescription(channel)) { blog(LOG_DEBUG, "Could not get channel description."); - ShowErrorDialog( - this, - apiYouTube->GetLastError().isEmpty() - ? QTStr("YouTube.Actions.Error.General") - : QTStr("YouTube.Actions.Error.Text") - .arg(apiYouTube->GetLastError())); + ShowErrorDialog(this, apiYouTube->GetLastError().isEmpty() + ? QTStr("YouTube.Actions.Error.General") + : QTStr("YouTube.Actions.Error.Text").arg(apiYouTube->GetLastError())); return; } diff --git a/UI/window-youtube-actions.hpp b/UI/window-youtube-actions.hpp index d74001465..7543792a8 100644 --- a/UI/window-youtube-actions.hpp +++ b/UI/window-youtube-actions.hpp @@ -22,40 +22,33 @@ public slots: void run() override; signals: void ready(); - void new_item(const QString &title, const QString &dateTimeString, - const QString &broadcast, const QString &status, - bool astart, bool astop); + void new_item(const QString &title, const QString &dateTimeString, const QString &broadcast, + const QString &status, bool astart, bool astop); void failed(); }; class OBSYoutubeActions : public QDialog { Q_OBJECT - Q_PROPERTY(QIcon thumbPlaceholder READ GetPlaceholder WRITE - SetPlaceholder DESIGNABLE true) + Q_PROPERTY(QIcon thumbPlaceholder READ GetPlaceholder WRITE SetPlaceholder DESIGNABLE true) std::unique_ptr ui; signals: - void ok(const QString &broadcast_id, const QString &stream_id, - const QString &key, bool autostart, bool autostop, - bool start_now); + void ok(const QString &broadcast_id, const QString &stream_id, const QString &key, bool autostart, + bool autostop, bool start_now); protected: void showEvent(QShowEvent *event) override; void UpdateOkButtonStatus(); - bool CreateEventAction(YoutubeApiWrappers *api, - BroadcastDescription &broadcast, - StreamDescription &stream, bool stream_later, - bool ready_broadcast = false); - bool ChooseAnEventAction(YoutubeApiWrappers *api, - StreamDescription &stream); + bool CreateEventAction(YoutubeApiWrappers *api, BroadcastDescription &broadcast, StreamDescription &stream, + bool stream_later, bool ready_broadcast = false); + bool ChooseAnEventAction(YoutubeApiWrappers *api, StreamDescription &stream); void ShowErrorDialog(QWidget *parent, QString text); public: - explicit OBSYoutubeActions(QWidget *parent, Auth *auth, - bool broadcastReady); + explicit OBSYoutubeActions(QWidget *parent, Auth *auth, bool broadcastReady); virtual ~OBSYoutubeActions() override; bool Valid() { return valid; }; diff --git a/UI/youtube-api-wrappers.cpp b/UI/youtube-api-wrappers.cpp index 346dabf32..1f8a184f2 100644 --- a/UI/youtube-api-wrappers.cpp +++ b/UI/youtube-api-wrappers.cpp @@ -22,8 +22,7 @@ using namespace json11; #define YOUTUBE_LIVE_STREAM_URL YOUTUBE_LIVE_API_URL "/liveStreams" #define YOUTUBE_LIVE_BROADCAST_URL YOUTUBE_LIVE_API_URL "/liveBroadcasts" -#define YOUTUBE_LIVE_BROADCAST_TRANSITION_URL \ - YOUTUBE_LIVE_BROADCAST_URL "/transition" +#define YOUTUBE_LIVE_BROADCAST_TRANSITION_URL YOUTUBE_LIVE_BROADCAST_URL "/transition" #define YOUTUBE_LIVE_BROADCAST_BIND_URL YOUTUBE_LIVE_BROADCAST_URL "/bind" #define YOUTUBE_LIVE_CHANNEL_URL YOUTUBE_LIVE_API_URL "/channels" @@ -31,27 +30,22 @@ using namespace json11; #define YOUTUBE_LIVE_VIDEOCATEGORIES_URL YOUTUBE_LIVE_API_URL "/videoCategories" #define YOUTUBE_LIVE_VIDEOS_URL YOUTUBE_LIVE_API_URL "/videos" #define YOUTUBE_LIVE_CHAT_MESSAGES_URL YOUTUBE_LIVE_API_URL "/liveChat/messages" -#define YOUTUBE_LIVE_THUMBNAIL_URL \ - "https://www.googleapis.com/upload/youtube/v3/thumbnails/set" +#define YOUTUBE_LIVE_THUMBNAIL_URL "https://www.googleapis.com/upload/youtube/v3/thumbnails/set" -#define DEFAULT_BROADCASTS_PER_QUERY \ - "50" // acceptable values are 0 to 50, inclusive +#define DEFAULT_BROADCASTS_PER_QUERY "50" // acceptable values are 0 to 50, inclusive /* ------------------------------------------------------------------------- */ bool IsYouTubeService(const std::string &service) { auto it = find_if(youtubeServices.begin(), youtubeServices.end(), - [&service](const Auth::Def &yt) { - return service == yt.service; - }); + [&service](const Auth::Def &yt) { return service == yt.service; }); return it != youtubeServices.end(); } bool IsUserSignedIntoYT() { Auth *auth = OBSBasic::Get()->GetAuth(); if (auth) { - YoutubeApiWrappers *apiYouTube( - dynamic_cast(auth)); + YoutubeApiWrappers *apiYouTube(dynamic_cast(auth)); if (apiYouTube) { return true; } @@ -61,8 +55,7 @@ bool IsUserSignedIntoYT() bool YoutubeApiWrappers::GetTranslatedError(QString &error_message) { - QString translated = - QTStr("YouTube.Errors." + lastErrorReason.toUtf8()); + QString translated = QTStr("YouTube.Errors." + lastErrorReason.toUtf8()); // No translation found if (translated.startsWith("YouTube.Errors.")) return false; @@ -72,11 +65,8 @@ bool YoutubeApiWrappers::GetTranslatedError(QString &error_message) YoutubeApiWrappers::YoutubeApiWrappers(const Def &d) : YoutubeAuth(d) {} -bool YoutubeApiWrappers::TryInsertCommand(const char *url, - const char *content_type, - std::string request_type, - const char *data, Json &json_out, - long *error_code, int data_size) +bool YoutubeApiWrappers::TryInsertCommand(const char *url, const char *content_type, std::string request_type, + const char *data, Json &json_out, long *error_code, int data_size) { long httpStatusCode = 0; @@ -91,24 +81,20 @@ bool YoutubeApiWrappers::TryInsertCommand(const char *url, std::string error; // Increase timeout by the time it takes to transfer `data_size` at 1 Mbps int timeout = 60 + data_size / 125000; - bool success = GetRemoteFile(url, output, error, &httpStatusCode, - content_type, request_type, data, - {"Authorization: Bearer " + token}, - nullptr, timeout, false, data_size); + bool success = GetRemoteFile(url, output, error, &httpStatusCode, content_type, request_type, data, + {"Authorization: Bearer " + token}, nullptr, timeout, false, data_size); if (error_code) *error_code = httpStatusCode; if (!success || output.empty()) { if (!error.empty()) - blog(LOG_WARNING, "YouTube API request failed: %s", - error.c_str()); + blog(LOG_WARNING, "YouTube API request failed: %s", error.c_str()); return false; } json_out = Json::parse(output, error); #ifdef _DEBUG - blog(LOG_DEBUG, "YouTube API command answer: %s", - json_out.dump().c_str()); + blog(LOG_DEBUG, "YouTube API command answer: %s", json_out.dump().c_str()); #endif if (!error.empty()) { return false; @@ -127,60 +113,44 @@ bool YoutubeApiWrappers::UpdateAccessToken() deobfuscate_str(&clientid[0], YOUTUBE_CLIENTID_HASH); deobfuscate_str(&secret[0], YOUTUBE_SECRET_HASH); - std::string r_token = - QUrl::toPercentEncoding(refresh_token.c_str()).toStdString(); + std::string r_token = QUrl::toPercentEncoding(refresh_token.c_str()).toStdString(); const QString url = YOUTUBE_LIVE_TOKEN_URL; const QString data_template = "client_id=%1" "&client_secret=%2" "&refresh_token=%3" "&grant_type=refresh_token"; - const QString data = data_template.arg(QString(clientid.c_str()), - QString(secret.c_str()), - QString(r_token.c_str())); + const QString data = + data_template.arg(QString(clientid.c_str()), QString(secret.c_str()), QString(r_token.c_str())); Json json_out; - bool success = TryInsertCommand(QT_TO_UTF8(url), - "application/x-www-form-urlencoded", "", - QT_TO_UTF8(data), json_out); + bool success = + TryInsertCommand(QT_TO_UTF8(url), "application/x-www-form-urlencoded", "", QT_TO_UTF8(data), json_out); - if (!success || json_out.object_items().find("error") != - json_out.object_items().end()) + if (!success || json_out.object_items().find("error") != json_out.object_items().end()) return false; token = json_out["access_token"].string_value(); return token.empty() ? false : true; } -bool YoutubeApiWrappers::InsertCommand(const char *url, - const char *content_type, - std::string request_type, - const char *data, Json &json_out, - int data_size) +bool YoutubeApiWrappers::InsertCommand(const char *url, const char *content_type, std::string request_type, + const char *data, Json &json_out, int data_size) { long error_code; - bool success = TryInsertCommand(url, content_type, request_type, data, - json_out, &error_code, data_size); + bool success = TryInsertCommand(url, content_type, request_type, data, json_out, &error_code, data_size); if (error_code == 401) { // Attempt to update access token and try again if (!UpdateAccessToken()) return false; - success = TryInsertCommand(url, content_type, request_type, - data, json_out, &error_code, - data_size); + success = TryInsertCommand(url, content_type, request_type, data, json_out, &error_code, data_size); } - if (json_out.object_items().find("error") != - json_out.object_items().end()) { - blog(LOG_ERROR, - "YouTube API error:\n\tHTTP status: %ld\n\tURL: %s\n\tJSON: %s", - error_code, url, json_out.dump().c_str()); + if (json_out.object_items().find("error") != json_out.object_items().end()) { + blog(LOG_ERROR, "YouTube API error:\n\tHTTP status: %ld\n\tURL: %s\n\tJSON: %s", error_code, url, + json_out.dump().c_str()); lastError = json_out["error"]["code"].int_value(); - lastErrorReason = - QString(json_out["error"]["errors"][0]["reason"] - .string_value() - .c_str()); - lastErrorMessage = QString( - json_out["error"]["message"].string_value().c_str()); + lastErrorReason = QString(json_out["error"]["errors"][0]["reason"].string_value().c_str()); + lastErrorMessage = QString(json_out["error"]["message"].string_value().c_str()); // The existence of an error implies non-success even if the HTTP status code disagrees. success = false; @@ -188,14 +158,12 @@ bool YoutubeApiWrappers::InsertCommand(const char *url, return success; } -bool YoutubeApiWrappers::GetChannelDescription( - ChannelDescription &channel_description) +bool YoutubeApiWrappers::GetChannelDescription(ChannelDescription &channel_description) { lastErrorMessage.clear(); lastErrorReason.clear(); - const QByteArray url = YOUTUBE_LIVE_CHANNEL_URL - "?part=snippet,contentDetails,statistics" - "&mine=true"; + const QByteArray url = YOUTUBE_LIVE_CHANNEL_URL "?part=snippet,contentDetails,statistics" + "&mine=true"; Json json_out; if (!InsertCommand(url, "application/json", "", nullptr, json_out)) { return false; @@ -206,10 +174,8 @@ bool YoutubeApiWrappers::GetChannelDescription( return false; } - channel_description.id = - QString(json_out["items"][0]["id"].string_value().c_str()); - channel_description.title = QString( - json_out["items"][0]["snippet"]["title"].string_value().c_str()); + channel_description.id = QString(json_out["items"][0]["id"].string_value().c_str()); + channel_description.title = QString(json_out["items"][0]["snippet"]["title"].string_value().c_str()); return channel_description.id.isEmpty() ? false : true; } @@ -217,15 +183,13 @@ bool YoutubeApiWrappers::InsertBroadcast(BroadcastDescription &broadcast) { lastErrorMessage.clear(); lastErrorReason.clear(); - const QByteArray url = YOUTUBE_LIVE_BROADCAST_URL - "?part=snippet,status,contentDetails"; + const QByteArray url = YOUTUBE_LIVE_BROADCAST_URL "?part=snippet,status,contentDetails"; const Json data = Json::object{ {"snippet", Json::object{ {"title", QT_TO_UTF8(broadcast.title)}, {"description", QT_TO_UTF8(broadcast.description)}, - {"scheduledStartTime", - QT_TO_UTF8(broadcast.schedul_date_time)}, + {"scheduledStartTime", QT_TO_UTF8(broadcast.schedul_date_time)}, }}, {"status", Json::object{ @@ -248,8 +212,7 @@ bool YoutubeApiWrappers::InsertBroadcast(BroadcastDescription &broadcast) }}, }; Json json_out; - if (!InsertCommand(url, "application/json", "", data.dump().c_str(), - json_out)) { + if (!InsertCommand(url, "application/json", "", data.dump().c_str(), json_out)) { return false; } broadcast.id = QString(json_out["id"].string_value().c_str()); @@ -260,8 +223,7 @@ bool YoutubeApiWrappers::InsertStream(StreamDescription &stream) { lastErrorMessage.clear(); lastErrorReason.clear(); - const QByteArray url = YOUTUBE_LIVE_STREAM_URL - "?part=snippet,cdn,status,contentDetails"; + const QByteArray url = YOUTUBE_LIVE_STREAM_URL "?part=snippet,cdn,status,contentDetails"; const Json data = Json::object{ {"snippet", Json::object{ @@ -276,42 +238,33 @@ bool YoutubeApiWrappers::InsertStream(StreamDescription &stream) {"contentDetails", Json::object{{"isReusable", false}}}, }; Json json_out; - if (!InsertCommand(url, "application/json", "", data.dump().c_str(), - json_out)) { + if (!InsertCommand(url, "application/json", "", data.dump().c_str(), json_out)) { return false; } stream.id = QString(json_out["id"].string_value().c_str()); - stream.name = QString(json_out["cdn"]["ingestionInfo"]["streamName"] - .string_value() - .c_str()); + stream.name = QString(json_out["cdn"]["ingestionInfo"]["streamName"].string_value().c_str()); return stream.id.isEmpty() ? false : true; } -bool YoutubeApiWrappers::BindStream(const QString broadcast_id, - const QString stream_id, - json11::Json &json_out) +bool YoutubeApiWrappers::BindStream(const QString broadcast_id, const QString stream_id, json11::Json &json_out) { lastErrorMessage.clear(); lastErrorReason.clear(); - const QString url_template = YOUTUBE_LIVE_BROADCAST_BIND_URL - "?id=%1" - "&streamId=%2" - "&part=id,snippet,contentDetails,status"; + const QString url_template = YOUTUBE_LIVE_BROADCAST_BIND_URL "?id=%1" + "&streamId=%2" + "&part=id,snippet,contentDetails,status"; const QString url = url_template.arg(broadcast_id, stream_id); const Json data = Json::object{}; this->broadcast_id = broadcast_id; - return InsertCommand(QT_TO_UTF8(url), "application/json", "", - data.dump().c_str(), json_out); + return InsertCommand(QT_TO_UTF8(url), "application/json", "", data.dump().c_str(), json_out); } -bool YoutubeApiWrappers::GetBroadcastsList(Json &json_out, const QString &page, - const QString &status) +bool YoutubeApiWrappers::GetBroadcastsList(Json &json_out, const QString &page, const QString &status) { lastErrorMessage.clear(); lastErrorReason.clear(); - QByteArray url = YOUTUBE_LIVE_BROADCAST_URL - "?part=snippet,contentDetails,status" - "&broadcastType=all&maxResults=" DEFAULT_BROADCASTS_PER_QUERY; + QByteArray url = YOUTUBE_LIVE_BROADCAST_URL "?part=snippet,contentDetails,status" + "&broadcastType=all&maxResults=" DEFAULT_BROADCASTS_PER_QUERY; if (status.isEmpty()) url += "&mine=true"; @@ -323,15 +276,13 @@ bool YoutubeApiWrappers::GetBroadcastsList(Json &json_out, const QString &page, return InsertCommand(url, "application/json", "", nullptr, json_out); } -bool YoutubeApiWrappers::GetVideoCategoriesList( - QVector &category_list_out) +bool YoutubeApiWrappers::GetVideoCategoriesList(QVector &category_list_out) { lastErrorMessage.clear(); lastErrorReason.clear(); - const QString url_template = YOUTUBE_LIVE_VIDEOCATEGORIES_URL - "?part=snippet" - "®ionCode=%1" - "&hl=%2"; + const QString url_template = YOUTUBE_LIVE_VIDEOCATEGORIES_URL "?part=snippet" + "®ionCode=%1" + "&hl=%2"; /* * All OBS locale regions aside from "US" are missing category id 29 * ("Nonprofits & Activism"), but it is still available to channels @@ -344,15 +295,12 @@ bool YoutubeApiWrappers::GetVideoCategoriesList( QString url = url_template.arg("US", QLocale().name()); Json json_out; - if (!InsertCommand(QT_TO_UTF8(url), "application/json", "", nullptr, - json_out)) { - if (lastErrorReason != "unsupportedLanguageCode" && - lastErrorReason != "invalidLanguage") + if (!InsertCommand(QT_TO_UTF8(url), "application/json", "", nullptr, json_out)) { + if (lastErrorReason != "unsupportedLanguageCode" && lastErrorReason != "invalidLanguage") return false; // Try again with en-US if YouTube error indicates an unsupported locale url = url_template.arg("US", "en_US"); - if (!InsertCommand(QT_TO_UTF8(url), "application/json", "", - nullptr, json_out)) + if (!InsertCommand(QT_TO_UTF8(url), "application/json", "", nullptr, json_out)) return false; } category_list_out = {}; @@ -360,17 +308,14 @@ bool YoutubeApiWrappers::GetVideoCategoriesList( // Assignable only. if (j["snippet"]["assignable"].bool_value()) { category_list_out.push_back( - {j["id"].string_value().c_str(), - j["snippet"]["title"].string_value().c_str()}); + {j["id"].string_value().c_str(), j["snippet"]["title"].string_value().c_str()}); } } return category_list_out.isEmpty() ? false : true; } -bool YoutubeApiWrappers::SetVideoCategory(const QString &video_id, - const QString &video_title, - const QString &video_description, - const QString &categorie_id) +bool YoutubeApiWrappers::SetVideoCategory(const QString &video_id, const QString &video_title, + const QString &video_description, const QString &categorie_id) { lastErrorMessage.clear(); lastErrorReason.clear(); @@ -385,12 +330,10 @@ bool YoutubeApiWrappers::SetVideoCategory(const QString &video_id, }}, }; Json json_out; - return InsertCommand(url, "application/json", "PUT", - data.dump().c_str(), json_out); + return InsertCommand(url, "application/json", "PUT", data.dump().c_str(), json_out); } -bool YoutubeApiWrappers::SetVideoThumbnail(const QString &video_id, - const QString &thumbnail_file) +bool YoutubeApiWrappers::SetVideoThumbnail(const QString &video_id, const QString &thumbnail_file) { lastErrorMessage.clear(); lastErrorReason.clear(); @@ -403,19 +346,16 @@ bool YoutubeApiWrappers::SetVideoThumbnail(const QString &video_id, QFile thumbFile(thumbnail_file); if (!thumbFile.open(QFile::ReadOnly)) { - lastErrorMessage = - QTStr("YouTube.Actions.Error.FileOpeningFailed"); + lastErrorMessage = QTStr("YouTube.Actions.Error.FileOpeningFailed"); return false; } const QByteArray fileContents = thumbFile.readAll(); - const QString mime = - QMimeDatabase().mimeTypeForData(fileContents).name(); + const QString mime = QMimeDatabase().mimeTypeForData(fileContents).name(); const QString url = YOUTUBE_LIVE_THUMBNAIL_URL "?videoId=" + video_id; Json json_out; - return InsertCommand(QT_TO_UTF8(url), QT_TO_UTF8(mime), "POST", - fileContents.constData(), json_out, + return InsertCommand(QT_TO_UTF8(url), QT_TO_UTF8(mime), "POST", fileContents.constData(), json_out, fileContents.size()); } @@ -428,36 +368,29 @@ bool YoutubeApiWrappers::StartBroadcast(const QString &broadcast_id) if (!FindBroadcast(broadcast_id, json_out)) return false; - auto lifeCycleStatus = - json_out["items"][0]["status"]["lifeCycleStatus"].string_value(); + auto lifeCycleStatus = json_out["items"][0]["status"]["lifeCycleStatus"].string_value(); if (lifeCycleStatus == "live" || lifeCycleStatus == "liveStarting") // Broadcast is already (going to be) live return true; else if (lifeCycleStatus == "testStarting") { // User will need to wait a few seconds before attempting to start broadcast - lastErrorMessage = - QTStr("YouTube.Actions.Error.BroadcastTestStarting"); + lastErrorMessage = QTStr("YouTube.Actions.Error.BroadcastTestStarting"); lastErrorReason.clear(); return false; } // Only reset if broadcast has monitoring enabled and is not already in "testing" mode auto monitorStreamEnabled = - json_out["items"][0]["contentDetails"]["monitorStream"] - ["enableMonitorStream"] - .bool_value(); - if (lifeCycleStatus != "testing" && monitorStreamEnabled && - !ResetBroadcast(broadcast_id, json_out)) + json_out["items"][0]["contentDetails"]["monitorStream"]["enableMonitorStream"].bool_value(); + if (lifeCycleStatus != "testing" && monitorStreamEnabled && !ResetBroadcast(broadcast_id, json_out)) return false; - const QString url_template = YOUTUBE_LIVE_BROADCAST_TRANSITION_URL - "?id=%1" - "&broadcastStatus=%2" - "&part=status"; + const QString url_template = YOUTUBE_LIVE_BROADCAST_TRANSITION_URL "?id=%1" + "&broadcastStatus=%2" + "&part=status"; const QString live = url_template.arg(broadcast_id, "live"); - bool success = InsertCommand(QT_TO_UTF8(live), "application/json", - "POST", "{}", json_out); + bool success = InsertCommand(QT_TO_UTF8(live), "application/json", "POST", "{}", json_out); // Return a success if the command failed, but was redundant (broadcast already live) return success || lastErrorReason == "redundantTransition"; } @@ -472,14 +405,12 @@ bool YoutubeApiWrappers::StopBroadcast(const QString &broadcast_id) lastErrorMessage.clear(); lastErrorReason.clear(); - const QString url_template = YOUTUBE_LIVE_BROADCAST_TRANSITION_URL - "?id=%1" - "&broadcastStatus=complete" - "&part=status"; + const QString url_template = YOUTUBE_LIVE_BROADCAST_TRANSITION_URL "?id=%1" + "&broadcastStatus=complete" + "&part=status"; const QString url = url_template.arg(broadcast_id); Json json_out; - bool success = InsertCommand(QT_TO_UTF8(url), "application/json", - "POST", "{}", json_out); + bool success = InsertCommand(QT_TO_UTF8(url), "application/json", "POST", "{}", json_out); // Return a success if the command failed, but was redundant (broadcast already stopped) return success || lastErrorReason == "redundantTransition"; } @@ -499,8 +430,7 @@ QString YoutubeApiWrappers::GetBroadcastId() return this->broadcast_id; } -bool YoutubeApiWrappers::ResetBroadcast(const QString &broadcast_id, - json11::Json &json_out) +bool YoutubeApiWrappers::ResetBroadcast(const QString &broadcast_id, json11::Json &json_out) { lastErrorMessage.clear(); lastErrorReason.clear(); @@ -523,8 +453,7 @@ bool YoutubeApiWrappers::ResetBroadcast(const QString &broadcast_id, Json::object{ {"privacyStatus", status["privacyStatus"]}, {"madeForKids", status["madeForKids"]}, - {"selfDeclaredMadeForKids", - status["selfDeclaredMadeForKids"]}, + {"selfDeclaredMadeForKids", status["selfDeclaredMadeForKids"]}, }}, {"contentDetails", Json::object{ @@ -532,37 +461,30 @@ bool YoutubeApiWrappers::ResetBroadcast(const QString &broadcast_id, "monitorStream", Json::object{ {"enableMonitorStream", false}, - {"broadcastStreamDelayMs", - monitorStream["broadcastStreamDelayMs"]}, + {"broadcastStreamDelayMs", monitorStream["broadcastStreamDelayMs"]}, }, }, {"enableAutoStart", contentDetails["enableAutoStart"]}, {"enableAutoStop", contentDetails["enableAutoStop"]}, - {"enableClosedCaptions", - contentDetails["enableClosedCaptions"]}, + {"enableClosedCaptions", contentDetails["enableClosedCaptions"]}, {"enableDvr", contentDetails["enableDvr"]}, - {"enableContentEncryption", - contentDetails["enableContentEncryption"]}, + {"enableContentEncryption", contentDetails["enableContentEncryption"]}, {"enableEmbed", contentDetails["enableEmbed"]}, {"recordFromStart", contentDetails["recordFromStart"]}, {"startWithSlate", contentDetails["startWithSlate"]}, }}, }; - const QString put = YOUTUBE_LIVE_BROADCAST_URL - "?part=id,snippet,contentDetails,status"; - return InsertCommand(QT_TO_UTF8(put), "application/json", "PUT", - data.dump().c_str(), json_out); + const QString put = YOUTUBE_LIVE_BROADCAST_URL "?part=id,snippet,contentDetails,status"; + return InsertCommand(QT_TO_UTF8(put), "application/json", "PUT", data.dump().c_str(), json_out); } -bool YoutubeApiWrappers::FindBroadcast(const QString &id, - json11::Json &json_out) +bool YoutubeApiWrappers::FindBroadcast(const QString &id, json11::Json &json_out) { lastErrorMessage.clear(); lastErrorReason.clear(); - QByteArray url = YOUTUBE_LIVE_BROADCAST_URL - "?part=id,snippet,contentDetails,status" - "&broadcastType=all&maxResults=1"; + QByteArray url = YOUTUBE_LIVE_BROADCAST_URL "?part=id,snippet,contentDetails,status" + "&broadcastType=all&maxResults=1"; url += "&id=" + id.toUtf8(); if (!InsertCommand(url, "application/json", "", nullptr, json_out)) @@ -570,8 +492,7 @@ bool YoutubeApiWrappers::FindBroadcast(const QString &id, auto items = json_out["items"].array_items(); if (items.size() != 1) { - lastErrorMessage = - QTStr("YouTube.Actions.Error.BroadcastNotFound"); + lastErrorMessage = QTStr("YouTube.Actions.Error.BroadcastNotFound"); return false; } @@ -598,21 +519,17 @@ bool YoutubeApiWrappers::FindStream(const QString &id, json11::Json &json_out) return true; } -bool YoutubeApiWrappers::SendChatMessage(const std::string &chat_id, - const QString &message) +bool YoutubeApiWrappers::SendChatMessage(const std::string &chat_id, const QString &message) { QByteArray url = YOUTUBE_LIVE_CHAT_MESSAGES_URL "?part=snippet"; json11::Json json_in = Json::object{ - {"snippet", - Json::object{ - {"liveChatId", chat_id}, - {"type", "textMessageEvent"}, - {"textMessageDetails", - Json::object{{"messageText", QT_TO_UTF8(message)}}}, - }}}; + {"snippet", Json::object{ + {"liveChatId", chat_id}, + {"type", "textMessageEvent"}, + {"textMessageDetails", Json::object{{"messageText", QT_TO_UTF8(message)}}}, + }}}; json11::Json json_out; - return InsertCommand(url, "application/json", "POST", - json_in.dump().c_str(), json_out); + return InsertCommand(url, "application/json", "POST", json_in.dump().c_str(), json_out); } diff --git a/UI/youtube-api-wrappers.hpp b/UI/youtube-api-wrappers.hpp index 5e6b7f534..66c8ae46b 100644 --- a/UI/youtube-api-wrappers.hpp +++ b/UI/youtube-api-wrappers.hpp @@ -43,13 +43,10 @@ bool IsUserSignedIntoYT(); class YoutubeApiWrappers : public YoutubeAuth { Q_OBJECT - bool TryInsertCommand(const char *url, const char *content_type, - std::string request_type, const char *data, - json11::Json &ret, long *error_code = nullptr, - int data_size = 0); + bool TryInsertCommand(const char *url, const char *content_type, std::string request_type, const char *data, + json11::Json &ret, long *error_code = nullptr, int data_size = 0); bool UpdateAccessToken(); - bool InsertCommand(const char *url, const char *content_type, - std::string request_type, const char *data, + bool InsertCommand(const char *url, const char *content_type, std::string request_type, const char *data, json11::Json &ret, int data_size = 0); public: @@ -58,26 +55,18 @@ public: bool GetChannelDescription(ChannelDescription &channel_description); bool InsertBroadcast(BroadcastDescription &broadcast); bool InsertStream(StreamDescription &stream); - bool BindStream(const QString broadcast_id, const QString stream_id, - json11::Json &json_out); - bool GetBroadcastsList(json11::Json &json_out, const QString &page, - const QString &status); - bool - GetVideoCategoriesList(QVector &category_list_out); - bool SetVideoCategory(const QString &video_id, - const QString &video_title, - const QString &video_description, + bool BindStream(const QString broadcast_id, const QString stream_id, json11::Json &json_out); + bool GetBroadcastsList(json11::Json &json_out, const QString &page, const QString &status); + bool GetVideoCategoriesList(QVector &category_list_out); + bool SetVideoCategory(const QString &video_id, const QString &video_title, const QString &video_description, const QString &categorie_id); - bool SetVideoThumbnail(const QString &video_id, - const QString &thumbnail_file); + bool SetVideoThumbnail(const QString &video_id, const QString &thumbnail_file); bool StartBroadcast(const QString &broadcast_id); bool StopBroadcast(const QString &broadcast_id); - bool ResetBroadcast(const QString &broadcast_id, - json11::Json &json_out); + bool ResetBroadcast(const QString &broadcast_id, json11::Json &json_out); bool StartLatestBroadcast(); bool StopLatestBroadcast(); - bool SendChatMessage(const std::string &chat_id, - const QString &message); + bool SendChatMessage(const std::string &chat_id, const QString &message); void SetBroadcastId(QString &broadcast_id); QString GetBroadcastId(); diff --git a/libobs-d3d11/d3d11-duplicator.cpp b/libobs-d3d11/d3d11-duplicator.cpp index dff6e1af9..a1980711a 100644 --- a/libobs-d3d11/d3d11-duplicator.cpp +++ b/libobs-d3d11/d3d11-duplicator.cpp @@ -18,8 +18,7 @@ #include "d3d11-subsystem.hpp" #include -static inline bool get_monitor(gs_device_t *device, int monitor_idx, - IDXGIOutput **dxgiOutput) +static inline bool get_monitor(gs_device_t *device, int monitor_idx, IDXGIOutput **dxgiOutput) { HRESULT hr; @@ -52,16 +51,13 @@ void gs_duplicator::Start() DXGI_FORMAT_R16G16B16A16_FLOAT, DXGI_FORMAT_B8G8R8A8_UNORM, }; - hr = output5->DuplicateOutput1(device->device, 0, - _countof(supportedFormats), - supportedFormats, + hr = output5->DuplicateOutput1(device->device, 0, _countof(supportedFormats), supportedFormats, duplicator.Assign()); if (FAILED(hr)) throw HRError("Failed to DuplicateOutput1", hr); DXGI_OUTPUT_DESC desc; if (SUCCEEDED(output->GetDesc(&desc))) { - gs_monitor_color_info info = - device->GetMonitorColorInfo(desc.Monitor); + gs_monitor_color_info info = device->GetMonitorColorInfo(desc.Monitor); hdr = info.hdr; sdr_white_nits = (float)info.sdr_white_nits; } @@ -70,8 +66,7 @@ void gs_duplicator::Start() if (FAILED(hr)) throw HRError("Failed to query IDXGIOutput1", hr); - hr = output1->DuplicateOutput(device->device, - duplicator.Assign()); + hr = output1->DuplicateOutput(device->device, duplicator.Assign()); if (FAILED(hr)) throw HRError("Failed to DuplicateOutput", hr); } @@ -94,9 +89,7 @@ gs_duplicator::~gs_duplicator() extern "C" { -EXPORT bool device_get_duplicator_monitor_info(gs_device_t *device, - int monitor_idx, - struct gs_monitor_info *info) +EXPORT bool device_get_duplicator_monitor_info(gs_device_t *device, int monitor_idx, struct gs_monitor_info *info) { DXGI_OUTPUT_DESC desc; HRESULT hr; @@ -146,8 +139,7 @@ EXPORT bool device_get_duplicator_monitor_info(gs_device_t *device, return true; } -EXPORT int device_duplicator_get_monitor_index(gs_device_t *device, - void *monitor) +EXPORT int device_duplicator_get_monitor_index(gs_device_t *device, void *monitor) { const HMONITOR handle = (HMONITOR)monitor; @@ -156,8 +148,7 @@ EXPORT int device_duplicator_get_monitor_index(gs_device_t *device, UINT output = 0; while (index == -1) { IDXGIOutput *pOutput; - const HRESULT hr = - device->adapter->EnumOutputs(output, &pOutput); + const HRESULT hr = device->adapter->EnumOutputs(output, &pOutput); if (hr == DXGI_ERROR_NOT_FOUND) break; @@ -196,8 +187,7 @@ void reset_duplicators(void) } } -EXPORT gs_duplicator_t *device_duplicator_create(gs_device_t *device, - int monitor_idx) +EXPORT gs_duplicator_t *device_duplicator_create(gs_device_t *device, int monitor_idx) { gs_duplicator *duplicator = nullptr; @@ -217,8 +207,7 @@ EXPORT gs_duplicator_t *device_duplicator_create(gs_device_t *device, return nullptr; } catch (const HRError &error) { - blog(LOG_DEBUG, "device_duplicator_create: %s (%08lX)", - error.str, error.hr); + blog(LOG_DEBUG, "device_duplicator_create: %s (%08lX)", error.str, error.hr); return nullptr; } @@ -240,18 +229,14 @@ static inline void copy_texture(gs_duplicator_t *d, ID3D11Texture2D *tex) const gs_color_format format = ConvertDXGITextureFormat(desc.Format); const gs_color_format general_format = gs_generalize_format(format); - if (!d->texture || (d->texture->width != desc.Width) || - (d->texture->height != desc.Height) || + if (!d->texture || (d->texture->width != desc.Width) || (d->texture->height != desc.Height) || (d->texture->format != general_format)) { delete d->texture; - d->texture = (gs_texture_2d *)gs_texture_create( - desc.Width, desc.Height, general_format, 1, nullptr, 0); - d->color_space = d->hdr ? GS_CS_709_SCRGB - : ((desc.Format == - DXGI_FORMAT_R16G16B16A16_FLOAT) - ? GS_CS_SRGB_16F - : GS_CS_SRGB); + d->texture = (gs_texture_2d *)gs_texture_create(desc.Width, desc.Height, general_format, 1, nullptr, 0); + d->color_space = + d->hdr ? GS_CS_709_SCRGB + : ((desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT) ? GS_CS_SRGB_16F : GS_CS_SRGB); } if (d->texture) @@ -287,8 +272,7 @@ EXPORT bool gs_duplicator_update_frame(gs_duplicator_t *d) return true; } - hr = res->QueryInterface(__uuidof(ID3D11Texture2D), - (void **)tex.Assign()); + hr = res->QueryInterface(__uuidof(ID3D11Texture2D), (void **)tex.Assign()); if (FAILED(hr)) { blog(LOG_ERROR, "gs_duplicator_update_frame: Failed to query " @@ -309,8 +293,7 @@ EXPORT gs_texture_t *gs_duplicator_get_texture(gs_duplicator_t *duplicator) return duplicator->texture; } -EXPORT enum gs_color_space -gs_duplicator_get_color_space(gs_duplicator_t *duplicator) +EXPORT enum gs_color_space gs_duplicator_get_color_space(gs_duplicator_t *duplicator) { return duplicator->color_space; } diff --git a/libobs-d3d11/d3d11-indexbuffer.cpp b/libobs-d3d11/d3d11-indexbuffer.cpp index bf301d863..da0ca10e2 100644 --- a/libobs-d3d11/d3d11-indexbuffer.cpp +++ b/libobs-d3d11/d3d11-indexbuffer.cpp @@ -35,8 +35,8 @@ void gs_index_buffer::InitBuffer() throw HRError("Failed to create buffer", hr); } -gs_index_buffer::gs_index_buffer(gs_device_t *device, enum gs_index_type type, - void *indices, size_t num, uint32_t flags) +gs_index_buffer::gs_index_buffer(gs_device_t *device, enum gs_index_type type, void *indices, size_t num, + uint32_t flags) : gs_obj(device, gs_type::gs_index_buffer), dynamic((flags & GS_DYNAMIC) != 0), type(type), diff --git a/libobs-d3d11/d3d11-rebuild.cpp b/libobs-d3d11/d3d11-rebuild.cpp index 109f44031..6912ac1c7 100644 --- a/libobs-d3d11/d3d11-rebuild.cpp +++ b/libobs-d3d11/d3d11-rebuild.cpp @@ -34,12 +34,9 @@ void gs_index_buffer::Rebuild(ID3D11Device *dev) void gs_texture_2d::RebuildSharedTextureFallback() { static const gs_color_format format = GS_BGRA; - static const DXGI_FORMAT dxgi_format_resource = - ConvertGSTextureFormatResource(format); - static const DXGI_FORMAT dxgi_format_view = - ConvertGSTextureFormatView(format); - static const DXGI_FORMAT dxgi_format_view_linear = - ConvertGSTextureFormatViewLinear(format); + static const DXGI_FORMAT dxgi_format_resource = ConvertGSTextureFormatResource(format); + static const DXGI_FORMAT dxgi_format_view = ConvertGSTextureFormatView(format); + static const DXGI_FORMAT dxgi_format_view_linear = ConvertGSTextureFormatViewLinear(format); td = {}; td.Width = 2; @@ -72,19 +69,16 @@ void gs_texture_2d::Rebuild(ID3D11Device *dev) { HRESULT hr; if (isShared) { - hr = dev->OpenSharedResource((HANDLE)(uintptr_t)sharedHandle, - __uuidof(ID3D11Texture2D), + hr = dev->OpenSharedResource((HANDLE)(uintptr_t)sharedHandle, __uuidof(ID3D11Texture2D), (void **)&texture); if (FAILED(hr)) { - blog(LOG_WARNING, - "Failed to rebuild shared texture: 0x%08lX", hr); + blog(LOG_WARNING, "Failed to rebuild shared texture: 0x%08lX", hr); RebuildSharedTextureFallback(); } } if (!isShared) { - hr = dev->CreateTexture2D( - &td, data.size() ? srd.data() : nullptr, &texture); + hr = dev->CreateTexture2D(&td, data.size() ? srd.data() : nullptr, &texture); if (FAILED(hr)) throw HRError("Failed to create 2D texture", hr); } @@ -96,8 +90,7 @@ void gs_texture_2d::Rebuild(ID3D11Device *dev) if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { - hr = dev->CreateShaderResourceView(texture, &viewDescLinear, - &shaderResLinear); + hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); if (FAILED(hr)) throw HRError("Failed to create linear SRV", hr); } @@ -106,8 +99,7 @@ void gs_texture_2d::Rebuild(ID3D11Device *dev) InitRenderTargets(); if (isGDICompatible) { - hr = texture->QueryInterface(__uuidof(IDXGISurface1), - (void **)&gdiSurface); + hr = texture->QueryInterface(__uuidof(IDXGISurface1), (void **)&gdiSurface); if (FAILED(hr)) throw HRError("Failed to create GDI surface", hr); } @@ -138,8 +130,7 @@ void gs_texture_2d::RebuildPaired_Y(ID3D11Device *dev) if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { - hr = dev->CreateShaderResourceView(texture, &viewDescLinear, - &shaderResLinear); + hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); if (FAILED(hr)) throw HRError("Failed to create linear Y SRV", hr); } @@ -173,8 +164,7 @@ void gs_texture_2d::RebuildPaired_UV(ID3D11Device *dev) if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { - hr = dev->CreateShaderResourceView(texture, &viewDescLinear, - &shaderResLinear); + hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); if (FAILED(hr)) throw HRError("Failed to create linear UV SRV", hr); } @@ -212,15 +202,13 @@ void gs_sampler_state::Rebuild(ID3D11Device *dev) void gs_vertex_shader::Rebuild(ID3D11Device *dev) { HRESULT hr; - hr = dev->CreateVertexShader(data.data(), data.size(), nullptr, - &shader); + hr = dev->CreateVertexShader(data.data(), data.size(), nullptr, &shader); if (FAILED(hr)) throw HRError("Failed to create vertex shader", hr); const UINT layoutSize = (UINT)layoutData.size(); if (layoutSize > 0) { - hr = dev->CreateInputLayout(layoutData.data(), layoutSize, - data.data(), data.size(), &layout); + hr = dev->CreateInputLayout(layoutData.data(), layoutSize, data.data(), data.size(), &layout); if (FAILED(hr)) throw HRError("Failed to create input layout", hr); } @@ -293,12 +281,9 @@ void gs_timer_range::Rebuild(ID3D11Device *dev) void gs_texture_3d::RebuildSharedTextureFallback() { static const gs_color_format format = GS_BGRA; - static const DXGI_FORMAT dxgi_format_resource = - ConvertGSTextureFormatResource(format); - static const DXGI_FORMAT dxgi_format_view = - ConvertGSTextureFormatView(format); - static const DXGI_FORMAT dxgi_format_view_linear = - ConvertGSTextureFormatViewLinear(format); + static const DXGI_FORMAT dxgi_format_resource = ConvertGSTextureFormatResource(format); + static const DXGI_FORMAT dxgi_format_view = ConvertGSTextureFormatView(format); + static const DXGI_FORMAT dxgi_format_view_linear = ConvertGSTextureFormatViewLinear(format); td = {}; td.Width = 2; @@ -332,19 +317,16 @@ void gs_texture_3d::Rebuild(ID3D11Device *dev) { HRESULT hr; if (isShared) { - hr = dev->OpenSharedResource((HANDLE)(uintptr_t)sharedHandle, - __uuidof(ID3D11Texture3D), + hr = dev->OpenSharedResource((HANDLE)(uintptr_t)sharedHandle, __uuidof(ID3D11Texture3D), (void **)&texture); if (FAILED(hr)) { - blog(LOG_WARNING, - "Failed to rebuild shared texture: 0x%08lX", hr); + blog(LOG_WARNING, "Failed to rebuild shared texture: 0x%08lX", hr); RebuildSharedTextureFallback(); } } if (!isShared) { - hr = dev->CreateTexture3D( - &td, data.size() ? srd.data() : nullptr, &texture); + hr = dev->CreateTexture3D(&td, data.size() ? srd.data() : nullptr, &texture); if (FAILED(hr)) throw HRError("Failed to create 3D texture", hr); } @@ -356,8 +338,7 @@ void gs_texture_3d::Rebuild(ID3D11Device *dev) if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { - hr = dev->CreateShaderResourceView(texture, &viewDescLinear, - &shaderResLinear); + hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); if (FAILED(hr)) throw HRError("Failed to create linear 3D SRV", hr); } @@ -480,11 +461,9 @@ try { InitAdapter(adpIdx); uint32_t createFlags = D3D11_CREATE_DEVICE_BGRA_SUPPORT; - hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, - createFlags, featureLevels, - sizeof(featureLevels) / - sizeof(D3D_FEATURE_LEVEL), - D3D11_SDK_VERSION, &device, nullptr, &context); + hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, createFlags, featureLevels, + sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), D3D11_SDK_VERSION, &device, nullptr, + &context); if (FAILED(hr)) throw HRError("Failed to create device", hr); diff --git a/libobs-d3d11/d3d11-samplerstate.cpp b/libobs-d3d11/d3d11-samplerstate.cpp index e854776bb..e061c74d4 100644 --- a/libobs-d3d11/d3d11-samplerstate.cpp +++ b/libobs-d3d11/d3d11-samplerstate.cpp @@ -20,8 +20,7 @@ #include "d3d11-subsystem.hpp" -static inline D3D11_TEXTURE_ADDRESS_MODE -ConvertGSAddressMode(gs_address_mode mode) +static inline D3D11_TEXTURE_ADDRESS_MODE ConvertGSAddressMode(gs_address_mode mode) { switch (mode) { case GS_ADDRESS_WRAP: @@ -65,8 +64,7 @@ static inline D3D11_FILTER ConvertGSFilter(gs_sample_filter filter) return D3D11_FILTER_MIN_MAG_MIP_POINT; } -gs_sampler_state::gs_sampler_state(gs_device_t *device, - const gs_sampler_info *info) +gs_sampler_state::gs_sampler_state(gs_device_t *device, const gs_sampler_info *info) : gs_obj(device, gs_type::gs_sampler_state), info(*info) { diff --git a/libobs-d3d11/d3d11-shader.cpp b/libobs-d3d11/d3d11-shader.cpp index 11e0f12aa..d77c72946 100644 --- a/libobs-d3d11/d3d11-shader.cpp +++ b/libobs-d3d11/d3d11-shader.cpp @@ -28,8 +28,7 @@ #include #include -void gs_vertex_shader::GetBuffersExpected( - const vector &inputs) +void gs_vertex_shader::GetBuffersExpected(const vector &inputs) { for (size_t i = 0; i < inputs.size(); i++) { const D3D11_INPUT_ELEMENT_DESC &input = inputs[i]; @@ -44,8 +43,7 @@ void gs_vertex_shader::GetBuffersExpected( } } -gs_vertex_shader::gs_vertex_shader(gs_device_t *device, const char *file, - const char *shaderString) +gs_vertex_shader::gs_vertex_shader(gs_device_t *device, const char *file, const char *shaderString) : gs_shader(device, gs_type::gs_vertex_shader, GS_SHADER_VERTEX), hasNormals(false), hasColors(false), @@ -69,16 +67,13 @@ gs_vertex_shader::gs_vertex_shader(gs_device_t *device, const char *file, data.resize(shaderBlob->GetBufferSize()); memcpy(&data[0], shaderBlob->GetBufferPointer(), data.size()); - hr = device->device->CreateVertexShader(data.data(), data.size(), NULL, - shader.Assign()); + hr = device->device->CreateVertexShader(data.data(), data.size(), NULL, shader.Assign()); if (FAILED(hr)) throw HRError("Failed to create vertex shader", hr); const UINT layoutSize = (UINT)layoutData.size(); if (layoutSize > 0) { - hr = device->device->CreateInputLayout(layoutData.data(), - (UINT)layoutSize, - data.data(), data.size(), + hr = device->device->CreateInputLayout(layoutData.data(), (UINT)layoutSize, data.data(), data.size(), layout.Assign()); if (FAILED(hr)) throw HRError("Failed to create input layout", hr); @@ -88,8 +83,7 @@ gs_vertex_shader::gs_vertex_shader(gs_device_t *device, const char *file, world = gs_shader_get_param_by_name(this, "World"); } -gs_pixel_shader::gs_pixel_shader(gs_device_t *device, const char *file, - const char *shaderString) +gs_pixel_shader::gs_pixel_shader(gs_device_t *device, const char *file, const char *shaderString) : gs_shader(device, gs_type::gs_pixel_shader, GS_SHADER_PIXEL) { ShaderProcessor processor(device); @@ -108,8 +102,7 @@ gs_pixel_shader::gs_pixel_shader(gs_device_t *device, const char *file, data.resize(shaderBlob->GetBufferSize()); memcpy(&data[0], shaderBlob->GetBufferPointer(), data.size()); - hr = device->device->CreatePixelShader(data.data(), data.size(), NULL, - shader.Assign()); + hr = device->device->CreatePixelShader(data.data(), data.size(), NULL, shader.Assign()); if (FAILED(hr)) throw HRError("Failed to create pixel shader", hr); } @@ -196,8 +189,7 @@ void gs_shader::BuildConstantBuffer() bd.BindFlags = D3D11_BIND_CONSTANT_BUFFER; bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; - hr = device->device->CreateBuffer(&bd, NULL, - constants.Assign()); + hr = device->device->CreateBuffer(&bd, NULL, constants.Assign()); if (FAILED(hr)) throw HRError("Failed to create constant buffer", hr); } @@ -218,8 +210,7 @@ static uint64_t fnv1a_hash(const char *str, size_t len) return hash; } -void gs_shader::Compile(const char *shaderString, const char *file, - const char *target, ID3D10Blob **shader) +void gs_shader::Compile(const char *shaderString, const char *file, const char *target, ID3D10Blob **shader) { ComPtr errorsBlob; HRESULT hr; @@ -234,8 +225,7 @@ void gs_shader::Compile(const char *shaderString, const char *file, uint64_t hash = fnv1a_hash(shaderString, shaderStrLen); snprintf(hashstr, sizeof(hashstr), "%02llx", hash); - BPtr program_data = - os_get_program_data_path_ptr("obs-studio/shader-cache"); + BPtr program_data = os_get_program_data_path_ptr("obs-studio/shader-cache"); auto cachePath = filesystem::u8path(program_data.Get()) / hashstr; // Increment if on-disk format changes cachePath += ".v2"; @@ -259,10 +249,8 @@ void gs_shader::Compile(const char *shaderString, const char *file, len -= sizeof(checksum); D3DCreateBlob(len, shader); - cacheFile.read((char *)(*shader)->GetBufferPointer(), - len); - uint64_t calculated_checksum = fnv1a_hash( - (char *)(*shader)->GetBufferPointer(), len); + cacheFile.read((char *)(*shader)->GetBufferPointer(), len); + uint64_t calculated_checksum = fnv1a_hash((char *)(*shader)->GetBufferPointer(), len); cacheFile.read((char *)&checksum, sizeof(checksum)); if (calculated_checksum != checksum) @@ -271,19 +259,15 @@ void gs_shader::Compile(const char *shaderString, const char *file, is_cached = true; } catch (const exception &e) { // Something went wrong reading the cache file, delete it - blog(LOG_WARNING, - "Loading shader cache file failed with \"%s\": %s", - e.what(), file); + blog(LOG_WARNING, "Loading shader cache file failed with \"%s\": %s", e.what(), file); cacheFile.close(); filesystem::remove(cachePath); } } if (!is_cached) { - hr = D3DCompile(shaderString, shaderStrLen, file, NULL, NULL, - "main", target, - D3D10_SHADER_OPTIMIZATION_LEVEL3, 0, shader, - errorsBlob.Assign()); + hr = D3DCompile(shaderString, shaderStrLen, file, NULL, NULL, "main", target, + D3D10_SHADER_OPTIMIZATION_LEVEL3, 0, shader, errorsBlob.Assign()); if (FAILED(hr)) { if (errorsBlob != NULL && errorsBlob->GetBufferSize()) throw ShaderError(errorsBlob, hr); @@ -294,19 +278,13 @@ void gs_shader::Compile(const char *shaderString, const char *file, cacheFile.open(cachePath, ios::out | ios::binary); if (cacheFile.is_open()) { try { - uint64_t calculated_checksum = fnv1a_hash( - (char *)(*shader)->GetBufferPointer(), - (*shader)->GetBufferSize()); + uint64_t calculated_checksum = + fnv1a_hash((char *)(*shader)->GetBufferPointer(), (*shader)->GetBufferSize()); - cacheFile.write( - (char *)(*shader)->GetBufferPointer(), - (*shader)->GetBufferSize()); - cacheFile.write((char *)&calculated_checksum, - sizeof(calculated_checksum)); + cacheFile.write((char *)(*shader)->GetBufferPointer(), (*shader)->GetBufferSize()); + cacheFile.write((char *)&calculated_checksum, sizeof(calculated_checksum)); } catch (const exception &e) { - blog(LOG_WARNING, - "Writing shader cache file failed with \"%s\": %s", - e.what(), file); + blog(LOG_WARNING, "Writing shader cache file failed with \"%s\": %s", e.what(), file); cacheFile.close(); filesystem::remove(cachePath); } @@ -316,19 +294,16 @@ void gs_shader::Compile(const char *shaderString, const char *file, #ifdef DISASSEMBLE_SHADERS ComPtr asmBlob; - hr = D3DDisassemble((*shader)->GetBufferPointer(), - (*shader)->GetBufferSize(), 0, nullptr, &asmBlob); + hr = D3DDisassemble((*shader)->GetBufferPointer(), (*shader)->GetBufferSize(), 0, nullptr, &asmBlob); if (SUCCEEDED(hr) && !!asmBlob && asmBlob->GetBufferSize()) { blog(LOG_INFO, "============================================="); - blog(LOG_INFO, "Disassembly output for shader '%s':\n%s", file, - asmBlob->GetBufferPointer()); + blog(LOG_INFO, "Disassembly output for shader '%s':\n%s", file, asmBlob->GetBufferPointer()); } #endif } -inline void gs_shader::UpdateParam(vector &constData, - gs_shader_param ¶m, bool &upload) +inline void gs_shader::UpdateParam(vector &constData, gs_shader_param ¶m, bool &upload) { if (param.type != GS_SHADER_PARAM_TEXTURE) { if (!param.curValue.size()) @@ -339,12 +314,10 @@ inline void gs_shader::UpdateParam(vector &constData, if (param.pos > constData.size()) { uint8_t zero = 0; - constData.insert(constData.end(), - param.pos - constData.size(), zero); + constData.insert(constData.end(), param.pos - constData.size(), zero); } - constData.insert(constData.end(), param.curValue.begin(), - param.curValue.end()); + constData.insert(constData.end(), param.curValue.begin(), param.curValue.end()); if (param.changed) { upload = true; @@ -355,16 +328,13 @@ inline void gs_shader::UpdateParam(vector &constData, struct gs_shader_texture shader_tex; memcpy(&shader_tex, param.curValue.data(), sizeof(shader_tex)); if (shader_tex.srgb) - device_load_texture_srgb(device, shader_tex.tex, - param.textureID); + device_load_texture_srgb(device, shader_tex.tex, param.textureID); else - device_load_texture(device, shader_tex.tex, - param.textureID); + device_load_texture(device, shader_tex.tex, param.textureID); if (param.nextSampler) { ID3D11SamplerState *state = param.nextSampler->state; - device->context->PSSetSamplers(param.textureID, 1, - &state); + device->context->PSSetSamplers(param.textureID, 1, &state); param.nextSampler = nullptr; } } @@ -387,8 +357,7 @@ void gs_shader::UploadParams() D3D11_MAPPED_SUBRESOURCE map; HRESULT hr; - hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD, - 0, &map); + hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD, 0, &map); if (FAILED(hr)) throw HRError("Could not lock constant buffer", hr); @@ -441,8 +410,7 @@ gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader) return static_cast(shader)->world; } -void gs_shader_get_param_info(const gs_sparam_t *param, - struct gs_shader_param_info *info) +void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_info *info) { if (!param) return; @@ -451,8 +419,7 @@ void gs_shader_get_param_info(const gs_sparam_t *param, info->type = param->type; } -static inline void shader_setval_inline(gs_shader_param *param, - const void *data, size_t size) +static inline void shader_setval_inline(gs_shader_param *param, const void *data, size_t size) { assert(param); if (!param) @@ -524,8 +491,7 @@ void gs_shader_set_val(gs_sparam_t *param, const void *val, size_t size) void gs_shader_set_default(gs_sparam_t *param) { if (param->defaultValue.size()) - shader_setval_inline(param, param->defaultValue.data(), - param->defaultValue.size()); + shader_setval_inline(param, param->defaultValue.data(), param->defaultValue.size()); } void gs_shader_set_next_sampler(gs_sparam_t *param, gs_samplerstate_t *sampler) diff --git a/libobs-d3d11/d3d11-shaderprocessor.cpp b/libobs-d3d11/d3d11-shaderprocessor.cpp index f4c2756cf..1ec93444f 100644 --- a/libobs-d3d11/d3d11-shaderprocessor.cpp +++ b/libobs-d3d11/d3d11-shaderprocessor.cpp @@ -21,10 +21,8 @@ #include using namespace std; -static const char *semanticInputNames[] = {"POSITION", "NORMAL", "COLOR", - "TANGENT", "TEXCOORD", "VERTEXID"}; -static const char *semanticOutputNames[] = { - "SV_Position", "NORMAL", "COLOR", "TANGENT", "TEXCOORD", "VERTEXID"}; +static const char *semanticInputNames[] = {"POSITION", "NORMAL", "COLOR", "TANGENT", "TEXCOORD", "VERTEXID"}; +static const char *semanticOutputNames[] = {"SV_Position", "NORMAL", "COLOR", "TANGENT", "TEXCOORD", "VERTEXID"}; static const char *ConvertSemanticName(const char *name) { @@ -51,8 +49,7 @@ static void GetSemanticInfo(shader_var *var, const char *&name, uint32_t &index) name = ConvertSemanticName(nameStr.c_str()); } -static void AddInputLayoutVar(shader_var *var, - vector &layout) +static void AddInputLayoutVar(shader_var *var, vector &layout) { D3D11_INPUT_ELEMENT_DESC ied; const char *semanticName; @@ -68,8 +65,7 @@ static void AddInputLayoutVar(shader_var *var, if (strcmp(var->mapping, "COLOR") == 0) { ied.Format = DXGI_FORMAT_R8G8B8A8_UNORM; - } else if (strcmp(var->mapping, "POSITION") == 0 || - strcmp(var->mapping, "NORMAL") == 0 || + } else if (strcmp(var->mapping, "POSITION") == 0 || strcmp(var->mapping, "NORMAL") == 0 || strcmp(var->mapping, "TANGENT") == 0) { ied.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; @@ -92,13 +88,12 @@ static void AddInputLayoutVar(shader_var *var, layout.push_back(ied); } -static inline bool SetSlot(vector &layout, - const char *name, uint32_t index, uint32_t &slotIdx) +static inline bool SetSlot(vector &layout, const char *name, uint32_t index, + uint32_t &slotIdx) { for (size_t i = 0; i < layout.size(); i++) { D3D11_INPUT_ELEMENT_DESC &input = layout[i]; - if (input.SemanticIndex == index && - strcmpi(input.SemanticName, name) == 0) { + if (input.SemanticIndex == index && strcmpi(input.SemanticName, name) == 0) { layout[i].InputSlot = slotIdx++; return true; } @@ -107,8 +102,7 @@ static inline bool SetSlot(vector &layout, return false; } -static void BuildInputLayoutFromVars(shader_parser *parser, darray *vars, - vector &layout) +static void BuildInputLayoutFromVars(shader_parser *parser, darray *vars, vector &layout) { shader_var *array = (shader_var *)vars->array; @@ -119,11 +113,9 @@ static void BuildInputLayoutFromVars(shader_parser *parser, darray *vars, if (strcmp(var->mapping, "VERTEXID") != 0) AddInputLayoutVar(var, layout); } else { - shader_struct *st = - shader_parser_getstruct(parser, var->type); + shader_struct *st = shader_parser_getstruct(parser, var->type); if (st) - BuildInputLayoutFromVars(parser, &st->vars.da, - layout); + BuildInputLayoutFromVars(parser, &st->vars.da, layout); } } @@ -168,11 +160,9 @@ gs_shader_param::gs_shader_param(shader_var &var, uint32_t &texCounter) textureID = 0; } -static inline void AddParam(shader_var &var, vector ¶ms, - uint32_t &texCounter) +static inline void AddParam(shader_var &var, vector ¶ms, uint32_t &texCounter) { - if (var.var_type != SHADER_VAR_UNIFORM || - strcmp(var.type, "sampler") == 0) + if (var.var_type != SHADER_VAR_UNIFORM || strcmp(var.type, "sampler") == 0) return; params.push_back(gs_shader_param(var, texCounter)); @@ -186,8 +176,7 @@ void ShaderProcessor::BuildParams(vector ¶ms) AddParam(parser.params.array[i], params, texCounter); } -static inline void AddSampler(gs_device_t *device, shader_sampler &sampler, - vector> &samplers) +static inline void AddSampler(gs_device_t *device, shader_sampler &sampler, vector> &samplers) { gs_sampler_info si; shader_sampler_convert(&sampler, &si); diff --git a/libobs-d3d11/d3d11-stagesurf.cpp b/libobs-d3d11/d3d11-stagesurf.cpp index 64640b94a..1711af6ec 100644 --- a/libobs-d3d11/d3d11-stagesurf.cpp +++ b/libobs-d3d11/d3d11-stagesurf.cpp @@ -17,8 +17,7 @@ #include "d3d11-subsystem.hpp" -gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, - uint32_t height, gs_color_format colorFormat) +gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t height, gs_color_format colorFormat) : gs_obj(device, gs_type::gs_stage_surface), width(width), height(height), @@ -42,8 +41,7 @@ gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, throw HRError("Failed to create staging surface", hr); } -gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, - uint32_t height, bool p010) +gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t height, bool p010) : gs_obj(device, gs_type::gs_stage_surface), width(width), height(height), diff --git a/libobs-d3d11/d3d11-subsystem.cpp b/libobs-d3d11/d3d11-subsystem.cpp index fbb6cb461..29151b738 100644 --- a/libobs-d3d11/d3d11-subsystem.cpp +++ b/libobs-d3d11/d3d11-subsystem.cpp @@ -30,10 +30,7 @@ #include struct UnsupportedHWError : HRError { - inline UnsupportedHWError(const char *str, HRESULT hr) - : HRError(str, hr) - { - } + inline UnsupportedHWError(const char *str, HRESULT hr) : HRError(str, hr) {} }; #ifdef _MSC_VER @@ -44,16 +41,12 @@ struct UnsupportedHWError : HRError { static inline void LogD3D11ErrorDetails(HRError error, gs_device_t *device) { if (error.hr == DXGI_ERROR_DEVICE_REMOVED) { - HRESULT DeviceRemovedReason = - device->device->GetDeviceRemovedReason(); - blog(LOG_ERROR, " Device Removed Reason: %08lX", - DeviceRemovedReason); + HRESULT DeviceRemovedReason = device->device->GetDeviceRemovedReason(); + blog(LOG_ERROR, " Device Removed Reason: %08lX", DeviceRemovedReason); } } -gs_obj::gs_obj(gs_device_t *device_, gs_type type) - : device(device_), - obj_type(type) +gs_obj::gs_obj(gs_device_t *device_, gs_type type) : device(device_), obj_type(type) { prev_next = &device->first_obj; next = device->first_obj; @@ -70,16 +63,13 @@ gs_obj::~gs_obj() next->prev_next = prev_next; } -static enum gs_color_space get_next_space(gs_device_t *device, HWND hwnd, - DXGI_SWAP_EFFECT effect) +static enum gs_color_space get_next_space(gs_device_t *device, HWND hwnd, DXGI_SWAP_EFFECT effect) { enum gs_color_space next_space = GS_CS_SRGB; if (effect == DXGI_SWAP_EFFECT_FLIP_DISCARD) { - const HMONITOR hMonitor = - MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); + const HMONITOR hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); if (hMonitor) { - const gs_monitor_color_info info = - device->GetMonitorColorInfo(hMonitor); + const gs_monitor_color_info info = device->GetMonitorColorInfo(hMonitor); if (info.hdr) next_space = GS_CS_709_SCRGB; else if (info.bits_per_color > 8) @@ -90,8 +80,7 @@ static enum gs_color_space get_next_space(gs_device_t *device, HWND hwnd, return next_space; } -static enum gs_color_format -get_swap_format_from_space(gs_color_space space, gs_color_format sdr_format) +static enum gs_color_format get_swap_format_from_space(gs_color_space space, gs_color_format sdr_format) { gs_color_format format = sdr_format; switch (space) { @@ -103,14 +92,12 @@ get_swap_format_from_space(gs_color_space space, gs_color_format sdr_format) return format; } -static inline enum gs_color_space -make_swap_desc(gs_device *device, DXGI_SWAP_CHAIN_DESC &desc, - const gs_init_data *data, DXGI_SWAP_EFFECT effect, UINT flags) +static inline enum gs_color_space make_swap_desc(gs_device *device, DXGI_SWAP_CHAIN_DESC &desc, + const gs_init_data *data, DXGI_SWAP_EFFECT effect, UINT flags) { const HWND hwnd = (HWND)data->window.hwnd; const enum gs_color_space space = get_next_space(device, hwnd, effect); - const gs_color_format format = - get_swap_format_from_space(space, data->format); + const gs_color_format format = get_swap_format_from_space(space, data->format); memset(&desc, 0, sizeof(desc)); desc.BufferDesc.Width = data->cx; @@ -134,8 +121,7 @@ void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy) target.width = cx; target.height = cy; - hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D), - (void **)target.texture.Assign()); + hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D), (void **)target.texture.Assign()); if (FAILED(hr)) throw HRError("Failed to get swap buffer texture", hr); @@ -143,17 +129,15 @@ void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy) rtv.Format = target.dxgiFormatView; rtv.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtv.Texture2D.MipSlice = 0; - hr = device->device->CreateRenderTargetView( - target.texture, &rtv, target.renderTarget[0].Assign()); + hr = device->device->CreateRenderTargetView(target.texture, &rtv, target.renderTarget[0].Assign()); if (FAILED(hr)) throw HRError("Failed to create swap RTV", hr); if (target.dxgiFormatView == target.dxgiFormatViewLinear) { target.renderTargetLinear[0] = target.renderTarget[0]; } else { rtv.Format = target.dxgiFormatViewLinear; - hr = device->device->CreateRenderTargetView( - target.texture, &rtv, - target.renderTargetLinear[0].Assign()); + hr = device->device->CreateRenderTargetView(target.texture, &rtv, + target.renderTargetLinear[0].Assign()); if (FAILED(hr)) throw HRError("Failed to create linear swap RTV", hr); } @@ -195,16 +179,14 @@ void gs_swap_chain::Resize(uint32_t cx, uint32_t cy, gs_color_format format) } const DXGI_FORMAT dxgi_format = ConvertGSTextureFormatView(format); - hr = swap->ResizeBuffers(swapDesc.BufferCount, cx, cy, dxgi_format, - swapDesc.Flags); + hr = swap->ResizeBuffers(swapDesc.BufferCount, cx, cy, dxgi_format, swapDesc.Flags); if (FAILED(hr)) throw HRError("Failed to resize swap buffers", hr); ComQIPtr swap3 = swap; if (swap3) { - const DXGI_COLOR_SPACE_TYPE dxgi_space = - (format == GS_RGBA16F) - ? DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 - : DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + const DXGI_COLOR_SPACE_TYPE dxgi_space = (format == GS_RGBA16F) + ? DXGI_COLOR_SPACE_RGB_FULL_G10_NONE_P709 + : DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; hr = swap3->SetColorSpace1(dxgi_space); if (FAILED(hr)) throw HRError("Failed to set color space", hr); @@ -219,9 +201,8 @@ void gs_swap_chain::Resize(uint32_t cx, uint32_t cy, gs_color_format format) void gs_swap_chain::Init() { - const gs_color_format format = get_swap_format_from_space( - get_next_space(device, hwnd, swapDesc.SwapEffect), - initData.format); + const gs_color_format format = + get_swap_format_from_space(get_next_space(device, hwnd, swapDesc.SwapEffect), initData.format); target.device = device; target.isRenderTarget = true; @@ -255,8 +236,7 @@ gs_swap_chain::gs_swap_chain(gs_device *device, const gs_init_data *data) } space = make_swap_desc(device, swapDesc, &initData, effect, flags); - HRESULT hr = device->factory->CreateSwapChain(device->device, &swapDesc, - swap.Assign()); + HRESULT hr = device->factory->CreateSwapChain(device->device, &swapDesc, swap.Assign()); if (FAILED(hr)) throw HRError("Failed to create swap chain", hr); @@ -267,8 +247,7 @@ gs_swap_chain::gs_swap_chain(gs_device *device, const gs_init_data *data) ComPtr swap2 = ComQIPtr(swap); hWaitable = swap2->GetFrameLatencyWaitableObject(); if (hWaitable == NULL) { - throw HRError("Failed to GetFrameLatencyWaitableObject", - hr); + throw HRError("Failed to GetFrameLatencyWaitableObject", hr); } } @@ -345,11 +324,9 @@ try { vec3_set(&points[2], 1.0f, -1.0f, 0.0f); vec3_set(&points[3], 1.0f, 1.0f, 0.0f); - gs_texture_2d nv12_y(this, NV12_CX, NV12_CY, GS_R8, 1, nullptr, - GS_RENDER_TARGET | GS_SHARED_KM_TEX, GS_TEXTURE_2D, - false, true); - gs_texture_2d nv12_uv(this, nv12_y.texture, - GS_RENDER_TARGET | GS_SHARED_KM_TEX); + gs_texture_2d nv12_y(this, NV12_CX, NV12_CY, GS_R8, 1, nullptr, GS_RENDER_TARGET | GS_SHARED_KM_TEX, + GS_TEXTURE_2D, false, true); + gs_texture_2d nv12_uv(this, nv12_y.texture, GS_RENDER_TARGET | GS_SHARED_KM_TEX); gs_vertex_shader nv12_vs(this, "", NV12_VS); gs_pixel_shader nv12_y_ps(this, "", NV12_Y_PS); gs_pixel_shader nv12_uv_ps(this, "", NV12_UV_PS); @@ -414,8 +391,7 @@ try { return bad_driver; } catch (const HRError &error) { - blog(LOG_WARNING, "HasBadNV12Output failed: %s (%08lX)", error.str, - error.hr); + blog(LOG_WARNING, "HasBadNV12Output failed: %s (%08lX)", error.str, error.hr); return false; } catch (const char *error) { blog(LOG_WARNING, "HasBadNV12Output failed: %s", error); @@ -432,8 +408,7 @@ static bool increase_maximum_frame_latency(ID3D11Device *device) const HRESULT hr = dxgiDevice->SetMaximumFrameLatency(16); if (FAILED(hr)) { - blog(LOG_DEBUG, "%s: SetMaximumFrameLatency failed", - __FUNCTION__); + blog(LOG_DEBUG, "%s: SetMaximumFrameLatency failed", __FUNCTION__); return false; } @@ -452,18 +427,15 @@ static bool set_priority(ID3D11Device *device, bool hags_enabled) NTSTATUS status = D3DKMTSetProcessSchedulingPriorityClass( GetCurrentProcess(), - hags_enabled ? D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH - : D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME); + hags_enabled ? D3DKMT_SCHEDULINGPRIORITYCLASS_HIGH : D3DKMT_SCHEDULINGPRIORITYCLASS_REALTIME); if (status != 0) { - blog(LOG_DEBUG, "%s: Failed to set process priority class: %d", - __FUNCTION__, (int)status); + blog(LOG_DEBUG, "%s: Failed to set process priority class: %d", __FUNCTION__, (int)status); return false; } HRESULT hr = dxgiDevice->SetGPUThreadPriority(GPU_PRIORITY_VAL); if (FAILED(hr)) { - blog(LOG_DEBUG, "%s: SetGPUThreadPriority failed", - __FUNCTION__); + blog(LOG_DEBUG, "%s: SetGPUThreadPriority failed", __FUNCTION__); return false; } @@ -473,13 +445,7 @@ static bool set_priority(ID3D11Device *device, bool hags_enabled) #endif struct HagsStatus { - enum DriverSupport { - ALWAYS_OFF, - ALWAYS_ON, - EXPERIMENTAL, - STABLE, - UNKNOWN - }; + enum DriverSupport { ALWAYS_OFF, ALWAYS_ON, EXPERIMENTAL, STABLE, UNKNOWN }; bool enabled; bool enabled_by_default; @@ -489,8 +455,7 @@ struct HagsStatus { { enabled = caps->HwSchEnabled; enabled_by_default = caps->HwSchEnabledByDefault; - support = caps->HwSchSupported ? DriverSupport::STABLE - : DriverSupport::ALWAYS_OFF; + support = caps->HwSchSupported ? DriverSupport::STABLE : DriverSupport::ALWAYS_OFF; } void SetDriverSupport(const UINT DXGKVal) @@ -589,8 +554,7 @@ static optional GetAdapterHagsStatus(const DXGI_ADAPTER_DESC *desc) D3DKMT_CLOSEADAPTER d3dkmt_close = {d3dkmt_openluid.hAdapter}; res = D3DKMTCloseAdapter(&d3dkmt_close); if (FAILED(res)) { - blog(LOG_DEBUG, "Failed closing D3DKMT adapter %x: %x", - d3dkmt_openluid.hAdapter, res); + blog(LOG_DEBUG, "Failed closing D3DKMT adapter %x: %x", d3dkmt_openluid.hAdapter, res); } return ret; @@ -598,12 +562,10 @@ static optional GetAdapterHagsStatus(const DXGI_ADAPTER_DESC *desc) static bool CheckFormat(ID3D11Device *device, DXGI_FORMAT format) { - constexpr UINT required = D3D11_FORMAT_SUPPORT_TEXTURE2D | - D3D11_FORMAT_SUPPORT_RENDER_TARGET; + constexpr UINT required = D3D11_FORMAT_SUPPORT_TEXTURE2D | D3D11_FORMAT_SUPPORT_RENDER_TARGET; UINT support = 0; - return SUCCEEDED(device->CheckFormatSupport(format, &support)) && - ((support & required) == required); + return SUCCEEDED(device->CheckFormatSupport(format, &support)) && ((support & required) == required); } static bool FastClearSupported(UINT vendorId, uint64_t version) @@ -637,29 +599,23 @@ void gs_device::InitDevice(uint32_t adapterIdx) //createFlags |= D3D11_CREATE_DEVICE_DEBUG; #endif - adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description - : L""; + adapterName = (adapter->GetDesc(&desc) == S_OK) ? desc.Description : L""; BPtr adapterNameUTF8; os_wcs_to_utf8_ptr(adapterName.c_str(), 0, &adapterNameUTF8); - blog(LOG_INFO, "Loading up D3D11 on adapter %s (%" PRIu32 ")", - adapterNameUTF8.Get(), adapterIdx); + blog(LOG_INFO, "Loading up D3D11 on adapter %s (%" PRIu32 ")", adapterNameUTF8.Get(), adapterIdx); hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); if (SUCCEEDED(hr)) driverVersion = umd.QuadPart; - hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, - createFlags, featureLevels, - sizeof(featureLevels) / - sizeof(D3D_FEATURE_LEVEL), - D3D11_SDK_VERSION, device.Assign(), &levelUsed, - context.Assign()); + hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, createFlags, featureLevels, + sizeof(featureLevels) / sizeof(D3D_FEATURE_LEVEL), D3D11_SDK_VERSION, device.Assign(), + &levelUsed, context.Assign()); if (FAILED(hr)) throw UnsupportedHWError("Failed to create device", hr); - blog(LOG_INFO, "D3D11 loaded successfully, feature level used: %x", - (unsigned int)levelUsed); + blog(LOG_INFO, "D3D11 loaded successfully, feature level used: %x", (unsigned int)levelUsed); /* prevent stalls sometimes seen in Present calls */ if (!increase_maximum_frame_latency(device)) { @@ -672,8 +628,7 @@ void gs_device::InitDevice(uint32_t adapterIdx) hags_enabled = hags_status->enabled; if (hags_enabled) { - blog(LOG_WARNING, - "Hardware-Accelerated GPU Scheduling enabled on adapter!"); + blog(LOG_WARNING, "Hardware-Accelerated GPU Scheduling enabled on adapter!"); } /* adjust gpu thread priority on non-intel GPUs */ @@ -702,21 +657,18 @@ void gs_device::InitDevice(uint32_t adapterIdx) /* needs to support extended resource sharing */ D3D11_FEATURE_DATA_D3D11_OPTIONS opts = {}; - hr = d3d11_1->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &opts, - sizeof(opts)); + hr = d3d11_1->CheckFeatureSupport(D3D11_FEATURE_D3D11_OPTIONS, &opts, sizeof(opts)); if (FAILED(hr) || !opts.ExtendedResourceSharing) { return; } - nv12Supported = CheckFormat(device, DXGI_FORMAT_NV12) && - !HasBadNV12Output(); + nv12Supported = CheckFormat(device, DXGI_FORMAT_NV12) && !HasBadNV12Output(); p010Supported = nv12Supported && CheckFormat(device, DXGI_FORMAT_P010); fastClearSupported = FastClearSupported(desc.VendorId, driverVersion); } -static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc, - const StencilSide &side) +static inline void ConvertStencilSide(D3D11_DEPTH_STENCILOP_DESC &desc, const StencilSide &side) { desc.StencilFunc = ConvertGSDepthTest(side.test); desc.StencilFailOp = ConvertGSStencilOp(side.fail); @@ -732,14 +684,10 @@ ID3D11DepthStencilState *gs_device::AddZStencilState() dsd.DepthEnable = zstencilState.depthEnabled; dsd.DepthFunc = ConvertGSDepthTest(zstencilState.depthFunc); - dsd.DepthWriteMask = zstencilState.depthWriteEnabled - ? D3D11_DEPTH_WRITE_MASK_ALL - : D3D11_DEPTH_WRITE_MASK_ZERO; + dsd.DepthWriteMask = zstencilState.depthWriteEnabled ? D3D11_DEPTH_WRITE_MASK_ALL : D3D11_DEPTH_WRITE_MASK_ZERO; dsd.StencilEnable = zstencilState.stencilEnabled; dsd.StencilReadMask = D3D11_DEFAULT_STENCIL_READ_MASK; - dsd.StencilWriteMask = zstencilState.stencilWriteEnabled - ? D3D11_DEFAULT_STENCIL_WRITE_MASK - : 0; + dsd.StencilWriteMask = zstencilState.stencilWriteEnabled ? D3D11_DEFAULT_STENCIL_WRITE_MASK : 0; ConvertStencilSide(dsd.FrontFace, zstencilState.stencilFront); ConvertStencilSide(dsd.BackFace, zstencilState.stencilBack); @@ -788,29 +736,17 @@ ID3D11BlendState *gs_device::AddBlendState() memset(&bd, 0, sizeof(bd)); for (int i = 0; i < 8; i++) { bd.RenderTarget[i].BlendEnable = blendState.blendEnabled; - bd.RenderTarget[i].BlendOp = - ConvertGSBlendOpType(blendState.op); - bd.RenderTarget[i].BlendOpAlpha = - ConvertGSBlendOpType(blendState.op); - bd.RenderTarget[i].SrcBlend = - ConvertGSBlendType(blendState.srcFactorC); - bd.RenderTarget[i].DestBlend = - ConvertGSBlendType(blendState.destFactorC); - bd.RenderTarget[i].SrcBlendAlpha = - ConvertGSBlendType(blendState.srcFactorA); - bd.RenderTarget[i].DestBlendAlpha = - ConvertGSBlendType(blendState.destFactorA); + bd.RenderTarget[i].BlendOp = ConvertGSBlendOpType(blendState.op); + bd.RenderTarget[i].BlendOpAlpha = ConvertGSBlendOpType(blendState.op); + bd.RenderTarget[i].SrcBlend = ConvertGSBlendType(blendState.srcFactorC); + bd.RenderTarget[i].DestBlend = ConvertGSBlendType(blendState.destFactorC); + bd.RenderTarget[i].SrcBlendAlpha = ConvertGSBlendType(blendState.srcFactorA); + bd.RenderTarget[i].DestBlendAlpha = ConvertGSBlendType(blendState.destFactorA); bd.RenderTarget[i].RenderTargetWriteMask = - (blendState.redEnabled ? D3D11_COLOR_WRITE_ENABLE_RED - : 0) | - (blendState.greenEnabled - ? D3D11_COLOR_WRITE_ENABLE_GREEN - : 0) | - (blendState.blueEnabled ? D3D11_COLOR_WRITE_ENABLE_BLUE - : 0) | - (blendState.alphaEnabled - ? D3D11_COLOR_WRITE_ENABLE_ALPHA - : 0); + (blendState.redEnabled ? D3D11_COLOR_WRITE_ENABLE_RED : 0) | + (blendState.greenEnabled ? D3D11_COLOR_WRITE_ENABLE_GREEN : 0) | + (blendState.blueEnabled ? D3D11_COLOR_WRITE_ENABLE_BLUE : 0) | + (blendState.alphaEnabled ? D3D11_COLOR_WRITE_ENABLE_ALPHA : 0); } SavedBlendState savedState(blendState, bd); @@ -917,8 +853,7 @@ void gs_device::UpdateViewProjMatrix() matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix); if (curVertexShader->viewProj) - gs_shader_set_matrix4(curVertexShader->viewProj, - &curViewProjMatrix); + gs_shader_set_matrix4(curVertexShader->viewProj, &curViewProjMatrix); } void gs_device::FlushOutputViews() @@ -927,13 +862,10 @@ void gs_device::FlushOutputViews() ID3D11RenderTargetView *rtv = nullptr; if (curRenderTarget) { const int i = curRenderSide; - rtv = curFramebufferSrgb - ? curRenderTarget->renderTargetLinear[i] - .Get() - : curRenderTarget->renderTarget[i].Get(); + rtv = curFramebufferSrgb ? curRenderTarget->renderTargetLinear[i].Get() + : curRenderTarget->renderTarget[i].Get(); if (!rtv) { - blog(LOG_ERROR, - "device_draw (D3D11): texture is not a render target"); + blog(LOG_ERROR, "device_draw (D3D11): texture is not a render target"); return; } } @@ -945,8 +877,7 @@ void gs_device::FlushOutputViews() } } -gs_device::gs_device(uint32_t adapterIdx) - : curToplogy(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED) +gs_device::gs_device(uint32_t adapterIdx) : curToplogy(D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED) { matrix4_identity(&curProjMatrix); matrix4_identity(&curViewMatrix); @@ -985,8 +916,7 @@ const char *device_preprocessor_name(void) return "_D3D11"; } -static inline void -EnumD3DAdapters(bool (*callback)(void *, const char *, uint32_t), void *param) +static inline void EnumD3DAdapters(bool (*callback)(void *, const char *, uint32_t), void *param) { ComPtr factory; ComPtr adapter; @@ -1016,9 +946,7 @@ EnumD3DAdapters(bool (*callback)(void *, const char *, uint32_t), void *param) } } -bool device_enum_adapters(gs_device_t *device, - bool (*callback)(void *param, const char *name, - uint32_t id), +bool device_enum_adapters(gs_device_t *device, bool (*callback)(void *param, const char *name, uint32_t id), void *param) { UNUSED_PARAMETER(device); @@ -1028,24 +956,20 @@ bool device_enum_adapters(gs_device_t *device, return true; } catch (const HRError &error) { - blog(LOG_WARNING, "Failed enumerating devices: %s (%08lX)", - error.str, error.hr); + blog(LOG_WARNING, "Failed enumerating devices: %s (%08lX)", error.str, error.hr); return false; } } -static bool GetMonitorTarget(const MONITORINFOEX &info, - DISPLAYCONFIG_TARGET_DEVICE_NAME &target) +static bool GetMonitorTarget(const MONITORINFOEX &info, DISPLAYCONFIG_TARGET_DEVICE_NAME &target) { bool found = false; UINT32 numPath, numMode; - if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath, - &numMode) == ERROR_SUCCESS) { + if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath, &numMode) == ERROR_SUCCESS) { std::vector paths(numPath); std::vector modes(numMode); - if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath, - paths.data(), &numMode, modes.data(), + if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath, paths.data(), &numMode, modes.data(), nullptr) == ERROR_SUCCESS) { paths.resize(numPath); for (size_t i = 0; i < numPath; ++i) { @@ -1053,25 +977,17 @@ static bool GetMonitorTarget(const MONITORINFOEX &info, DISPLAYCONFIG_SOURCE_DEVICE_NAME source; - source.header.type = - DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; + source.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; source.header.size = sizeof(source); - source.header.adapterId = - path.sourceInfo.adapterId; + source.header.adapterId = path.sourceInfo.adapterId; source.header.id = path.sourceInfo.id; - if (DisplayConfigGetDeviceInfo( - &source.header) == ERROR_SUCCESS && - wcscmp(info.szDevice, - source.viewGdiDeviceName) == 0) { - target.header.type = - DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME; + if (DisplayConfigGetDeviceInfo(&source.header) == ERROR_SUCCESS && + wcscmp(info.szDevice, source.viewGdiDeviceName) == 0) { + target.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME; target.header.size = sizeof(target); - target.header.adapterId = - path.sourceInfo.adapterId; + target.header.adapterId = path.sourceInfo.adapterId; target.header.id = path.targetInfo.id; - found = DisplayConfigGetDeviceInfo( - &target.header) == - ERROR_SUCCESS; + found = DisplayConfigGetDeviceInfo(&target.header) == ERROR_SUCCESS; break; } } @@ -1090,8 +1006,7 @@ static bool GetOutputDesc1(IDXGIOutput *const output, DXGI_OUTPUT_DESC1 *desc1) hr = output6->GetDesc1(desc1); success = SUCCEEDED(hr); if (!success) { - blog(LOG_WARNING, - "IDXGIOutput6::GetDesc1 failed: 0x%08lX", hr); + blog(LOG_WARNING, "IDXGIOutput6::GetDesc1 failed: 0x%08lX", hr); } } @@ -1099,8 +1014,7 @@ static bool GetOutputDesc1(IDXGIOutput *const output, DXGI_OUTPUT_DESC1 *desc1) } // Returns true if this is an integrated display panel e.g. the screen attached to tablets or laptops. -static bool IsInternalVideoOutput( - const DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY VideoOutputTechnologyType) +static bool IsInternalVideoOutput(const DISPLAYCONFIG_VIDEO_OUTPUT_TECHNOLOGY VideoOutputTechnologyType) { switch (VideoOutputTechnologyType) { case DISPLAYCONFIG_OUTPUT_TECHNOLOGY_INTERNAL: @@ -1115,8 +1029,7 @@ static bool IsInternalVideoOutput( // Note: Since an hmon can represent multiple monitors while in clone, this function as written will return // the value for the internal monitor if one exists, and otherwise the highest clone-path priority. -static HRESULT GetPathInfo(_In_ PCWSTR pszDeviceName, - _Out_ DISPLAYCONFIG_PATH_INFO *pPathInfo) +static HRESULT GetPathInfo(_In_ PCWSTR pszDeviceName, _Out_ DISPLAYCONFIG_PATH_INFO *pPathInfo) { HRESULT hr = S_OK; UINT32 NumPathArrayElements = 0; @@ -1132,60 +1045,46 @@ static HRESULT GetPathInfo(_In_ PCWSTR pszDeviceName, delete[] ModeInfoArray; ModeInfoArray = nullptr; - hr = HRESULT_FROM_WIN32(GetDisplayConfigBufferSizes( - QDC_ONLY_ACTIVE_PATHS, &NumPathArrayElements, - &NumModeInfoArrayElements)); + hr = HRESULT_FROM_WIN32(GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &NumPathArrayElements, + &NumModeInfoArrayElements)); if (FAILED(hr)) { break; } - PathInfoArray = new (std::nothrow) - DISPLAYCONFIG_PATH_INFO[NumPathArrayElements]; + PathInfoArray = new (std::nothrow) DISPLAYCONFIG_PATH_INFO[NumPathArrayElements]; if (PathInfoArray == nullptr) { hr = E_OUTOFMEMORY; break; } - ModeInfoArray = new (std::nothrow) - DISPLAYCONFIG_MODE_INFO[NumModeInfoArrayElements]; + ModeInfoArray = new (std::nothrow) DISPLAYCONFIG_MODE_INFO[NumModeInfoArrayElements]; if (ModeInfoArray == nullptr) { hr = E_OUTOFMEMORY; break; } - hr = HRESULT_FROM_WIN32(QueryDisplayConfig( - QDC_ONLY_ACTIVE_PATHS, &NumPathArrayElements, - PathInfoArray, &NumModeInfoArrayElements, ModeInfoArray, - nullptr)); + hr = HRESULT_FROM_WIN32(QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &NumPathArrayElements, PathInfoArray, + &NumModeInfoArrayElements, ModeInfoArray, nullptr)); } while (hr == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER)); INT DesiredPathIdx = -1; if (SUCCEEDED(hr)) { // Loop through all sources until the one which matches the 'monitor' is found. - for (UINT PathIdx = 0; PathIdx < NumPathArrayElements; - ++PathIdx) { + for (UINT PathIdx = 0; PathIdx < NumPathArrayElements; ++PathIdx) { DISPLAYCONFIG_SOURCE_DEVICE_NAME SourceName = {}; - SourceName.header.type = - DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; + SourceName.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; SourceName.header.size = sizeof(SourceName); - SourceName.header.adapterId = - PathInfoArray[PathIdx].sourceInfo.adapterId; - SourceName.header.id = - PathInfoArray[PathIdx].sourceInfo.id; + SourceName.header.adapterId = PathInfoArray[PathIdx].sourceInfo.adapterId; + SourceName.header.id = PathInfoArray[PathIdx].sourceInfo.id; - hr = HRESULT_FROM_WIN32( - DisplayConfigGetDeviceInfo(&SourceName.header)); + hr = HRESULT_FROM_WIN32(DisplayConfigGetDeviceInfo(&SourceName.header)); if (SUCCEEDED(hr)) { - if (wcscmp(pszDeviceName, - SourceName.viewGdiDeviceName) == 0) { + if (wcscmp(pszDeviceName, SourceName.viewGdiDeviceName) == 0) { // Found the source which matches this hmonitor. The paths are given in path-priority order // so the first found is the most desired, unless we later find an internal. if (DesiredPathIdx == -1 || - IsInternalVideoOutput( - PathInfoArray[PathIdx] - .targetInfo - .outputTechnology)) { + IsInternalVideoOutput(PathInfoArray[PathIdx].targetInfo.outputTechnology)) { DesiredPathIdx = PathIdx; } } @@ -1209,8 +1108,7 @@ static HRESULT GetPathInfo(_In_ PCWSTR pszDeviceName, } // Overloaded function accepts an HMONITOR and converts to DeviceName -static HRESULT GetPathInfo(HMONITOR hMonitor, - _Out_ DISPLAYCONFIG_PATH_INFO *pPathInfo) +static HRESULT GetPathInfo(HMONITOR hMonitor, _Out_ DISPLAYCONFIG_PATH_INFO *pPathInfo) { HRESULT hr = S_OK; @@ -1236,8 +1134,7 @@ static ULONG GetSdrMaxNits(HMONITOR monitor) DISPLAYCONFIG_PATH_INFO info; if (SUCCEEDED(GetPathInfo(monitor, &info))) { - const DISPLAYCONFIG_PATH_TARGET_INFO &targetInfo = - info.targetInfo; + const DISPLAYCONFIG_PATH_TARGET_INFO &targetInfo = info.targetInfo; DISPLAYCONFIG_SDR_WHITE_LEVEL level; DISPLAYCONFIG_DEVICE_INFO_HEADER &header = level.header; @@ -1261,8 +1158,7 @@ gs_monitor_color_info gs_device::GetMonitorColorInfo(HMONITOR hMonitor) monitor_to_hdr.clear(); } - for (const std::pair &pair : - monitor_to_hdr) { + for (const std::pair &pair : monitor_to_hdr) { if (pair.first == hMonitor) return pair.second; } @@ -1270,25 +1166,15 @@ gs_monitor_color_info gs_device::GetMonitorColorInfo(HMONITOR hMonitor) ComPtr adapter; ComPtr output; ComPtr output6; - for (UINT adapterIndex = 0; - SUCCEEDED(factory1->EnumAdapters(adapterIndex, &adapter)); - ++adapterIndex) { - for (UINT outputIndex = 0; - SUCCEEDED(adapter->EnumOutputs(outputIndex, &output)); - ++outputIndex) { + for (UINT adapterIndex = 0; SUCCEEDED(factory1->EnumAdapters(adapterIndex, &adapter)); ++adapterIndex) { + for (UINT outputIndex = 0; SUCCEEDED(adapter->EnumOutputs(outputIndex, &output)); ++outputIndex) { DXGI_OUTPUT_DESC1 desc1; - if (SUCCEEDED(output->QueryInterface(&output6)) && - SUCCEEDED(output6->GetDesc1(&desc1)) && + if (SUCCEEDED(output->QueryInterface(&output6)) && SUCCEEDED(output6->GetDesc1(&desc1)) && (desc1.Monitor == hMonitor)) { - const bool hdr = - desc1.ColorSpace == - DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; + const bool hdr = desc1.ColorSpace == DXGI_COLOR_SPACE_RGB_FULL_G2084_NONE_P2020; const UINT bits = desc1.BitsPerColor; const ULONG nits = GetSdrMaxNits(desc1.Monitor); - return monitor_to_hdr - .emplace_back(hMonitor, - gs_monitor_color_info( - hdr, bits, nits)) + return monitor_to_hdr.emplace_back(hMonitor, gs_monitor_color_info(hdr, bits, nits)) .second; } } @@ -1297,8 +1183,7 @@ gs_monitor_color_info gs_device::GetMonitorColorInfo(HMONITOR hMonitor) return gs_monitor_color_info(false, 8, 80); } -static void PopulateMonitorIds(HMONITOR handle, char *id, char *alt_id, - size_t capacity) +static void PopulateMonitorIds(HMONITOR handle, char *id, char *alt_id, size_t capacity) { MONITORINFOEXA mi; mi.cbSize = sizeof(mi); @@ -1306,15 +1191,13 @@ static void PopulateMonitorIds(HMONITOR handle, char *id, char *alt_id, strcpy_s(alt_id, capacity, mi.szDevice); DISPLAY_DEVICEA device; device.cb = sizeof(device); - if (EnumDisplayDevicesA(mi.szDevice, 0, &device, - EDD_GET_DEVICE_INTERFACE_NAME)) { + if (EnumDisplayDevicesA(mi.szDevice, 0, &device, EDD_GET_DEVICE_INTERFACE_NAME)) { strcpy_s(id, capacity, device.DeviceID); } } } -static constexpr double DoubleTriangleArea(double ax, double ay, double bx, - double by, double cx, double cy) +static constexpr double DoubleTriangleArea(double ax, double ay, double bx, double by, double cx, double cy) { return ax * (by - cy) + bx * (cy - ay) + cx * (ay - by); } @@ -1347,8 +1230,7 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) DEVMODE mode; mode.dmSize = sizeof(mode); mode.dmDriverExtra = 0; - if (EnumDisplaySettings(info.szDevice, - ENUM_CURRENT_SETTINGS, &mode)) { + if (EnumDisplaySettings(info.szDevice, ENUM_CURRENT_SETTINGS, &mode)) { refresh = mode.dmDisplayFrequency; } } @@ -1358,8 +1240,7 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) } UINT bits_per_color = 8; - DXGI_COLOR_SPACE_TYPE type = - DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; + DXGI_COLOR_SPACE_TYPE type = DXGI_COLOR_SPACE_RGB_FULL_G22_NONE_P709; FLOAT primaries[4][2]{}; double gamut_size = 0.; FLOAT min_luminance = 0.f; @@ -1377,10 +1258,9 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) primaries[2][1] = desc1.BluePrimary[1]; primaries[3][0] = desc1.WhitePoint[0]; primaries[3][1] = desc1.WhitePoint[1]; - gamut_size = DoubleTriangleArea( - desc1.RedPrimary[0], desc1.RedPrimary[1], - desc1.GreenPrimary[0], desc1.GreenPrimary[1], - desc1.BluePrimary[0], desc1.BluePrimary[1]); + gamut_size = DoubleTriangleArea(desc1.RedPrimary[0], desc1.RedPrimary[1], desc1.GreenPrimary[0], + desc1.GreenPrimary[1], desc1.BluePrimary[0], + desc1.BluePrimary[1]); min_luminance = desc1.MinLuminance; max_luminance = desc1.MaxLuminance; max_full_frame_luminance = desc1.MaxFullFrameLuminance; @@ -1395,16 +1275,13 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) space = "RGB_FULL_G2084_NONE_P2020"; break; default: - blog(LOG_WARNING, - "Unexpected DXGI_COLOR_SPACE_TYPE: %u", - (unsigned)type); + blog(LOG_WARNING, "Unexpected DXGI_COLOR_SPACE_TYPE: %u", (unsigned)type); } // These are always identical, but you still have to supply both, thanks Microsoft! UINT dpiX, dpiY; unsigned scaling = 100; - if (GetDpiForMonitor(desc.Monitor, MDT_EFFECTIVE_DPI, &dpiX, - &dpiY) == S_OK) { + if (GetDpiForMonitor(desc.Monitor, MDT_EFFECTIVE_DPI, &dpiX, &dpiY) == S_OK) { scaling = (unsigned)(dpiX * 100.0f / 96.0f); } else { dpiX = 0; @@ -1414,8 +1291,7 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) const ULONG sdr_white_nits = GetSdrMaxNits(desc.Monitor); char *friendly_name; - os_wcs_to_utf8_ptr(target.monitorFriendlyDeviceName, 0, - &friendly_name); + os_wcs_to_utf8_ptr(target.monitorFriendlyDeviceName, 0, &friendly_name); blog(LOG_INFO, "\t output %u:\n" @@ -1433,20 +1309,13 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) "\t dpi=%u (%u%%)\n" "\t id=%s\n" "\t alt_id=%s", - i, friendly_name, rect.left, rect.top, - rect.right - rect.left, rect.bottom - rect.top, - desc.AttachedToDesktop ? "true" : "false", refresh, - bits_per_color, space, primaries[0][0], primaries[0][1], - primaries[1][0], primaries[1][1], primaries[2][0], - primaries[2][1], primaries[3][0], primaries[3][1], - gamut_size / - DoubleTriangleArea(.64, .33, .3, .6, .15, .06), - gamut_size / - DoubleTriangleArea(.68, .32, .265, .69, .15, .060), - gamut_size / DoubleTriangleArea(.708, .292, .17, .797, - .131, .046), - sdr_white_nits, min_luminance, max_luminance, - max_full_frame_luminance, dpiX, scaling, id, alt_id); + i, friendly_name, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, + desc.AttachedToDesktop ? "true" : "false", refresh, bits_per_color, space, primaries[0][0], + primaries[0][1], primaries[1][0], primaries[1][1], primaries[2][0], primaries[2][1], + primaries[3][0], primaries[3][1], gamut_size / DoubleTriangleArea(.64, .33, .3, .6, .15, .06), + gamut_size / DoubleTriangleArea(.68, .32, .265, .69, .15, .060), + gamut_size / DoubleTriangleArea(.708, .292, .17, .797, .131, .046), sdr_white_nits, min_luminance, + max_luminance, max_full_frame_luminance, dpiX, scaling, id, alt_id); bfree(friendly_name); } } @@ -1483,38 +1352,31 @@ static inline void LogD3DAdapters() os_wcs_to_utf8(desc.Description, 0, name, sizeof(name)); blog(LOG_INFO, "\tAdapter %u: %s", i, name); - blog(LOG_INFO, "\t Dedicated VRAM: %" PRIu64 " (%.01f GiB)", - desc.DedicatedVideoMemory, + blog(LOG_INFO, "\t Dedicated VRAM: %" PRIu64 " (%.01f GiB)", desc.DedicatedVideoMemory, to_GiB(desc.DedicatedVideoMemory)); - blog(LOG_INFO, "\t Shared VRAM: %" PRIu64 " (%.01f GiB)", - desc.SharedSystemMemory, to_GiB(desc.SharedSystemMemory)); - blog(LOG_INFO, "\t PCI ID: %x:%.4x", desc.VendorId, - desc.DeviceId); + blog(LOG_INFO, "\t Shared VRAM: %" PRIu64 " (%.01f GiB)", desc.SharedSystemMemory, + to_GiB(desc.SharedSystemMemory)); + blog(LOG_INFO, "\t PCI ID: %x:%.4x", desc.VendorId, desc.DeviceId); if (auto hags_support = GetAdapterHagsStatus(&desc)) { - blog(LOG_INFO, "\t HAGS Status: %s", - hags_support->ToString().c_str()); + blog(LOG_INFO, "\t HAGS Status: %s", hags_support->ToString().c_str()); } else { blog(LOG_WARNING, "\t HAGS Status: Unknown"); } /* driver version */ LARGE_INTEGER umd; - hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), - &umd); + hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); if (SUCCEEDED(hr)) { const uint64_t version = umd.QuadPart; const uint16_t aa = (version >> 48) & 0xffff; const uint16_t bb = (version >> 32) & 0xffff; const uint16_t ccccc = (version >> 16) & 0xffff; const uint16_t ddddd = version & 0xffff; - blog(LOG_INFO, - "\t Driver Version: %" PRIu16 ".%" PRIu16 - ".%" PRIu16 ".%" PRIu16, - aa, bb, ccccc, ddddd); + blog(LOG_INFO, "\t Driver Version: %" PRIu16 ".%" PRIu16 ".%" PRIu16 ".%" PRIu16, aa, bb, + ccccc, ddddd); } else { - blog(LOG_INFO, "\t Driver Version: Unknown (0x%X)", - (unsigned)hr); + blog(LOG_INFO, "\t Driver Version: Unknown (0x%X)", (unsigned)hr); } LogAdapterMonitors(adapter); @@ -1523,8 +1385,7 @@ static inline void LogD3DAdapters() static void CreateShaderCacheDirectory() { - BPtr cachePath = - os_get_program_data_path_ptr("obs-studio/shader-cache"); + BPtr cachePath = os_get_program_data_path_ptr("obs-studio/shader-cache"); if (os_mkdirs(cachePath) == MKDIR_ERROR) { blog(LOG_WARNING, "Failed to create shader cache directory, " @@ -1546,13 +1407,11 @@ int device_create(gs_device_t **p_device, uint32_t adapter) device = new gs_device(adapter); } catch (const UnsupportedHWError &error) { - blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str, - error.hr); + blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str, error.hr); errorcode = GS_ERROR_NOT_SUPPORTED; } catch (const HRError &error) { - blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str, - error.hr); + blog(LOG_ERROR, "device_create (D3D11): %s (%08lX)", error.str, error.hr); errorcode = GS_ERROR_FAIL; } @@ -1582,36 +1441,31 @@ void *device_get_device_obj(gs_device_t *device) return (void *)device->device.Get(); } -gs_swapchain_t *device_swapchain_create(gs_device_t *device, - const struct gs_init_data *data) +gs_swapchain_t *device_swapchain_create(gs_device_t *device, const struct gs_init_data *data) { gs_swap_chain *swap = NULL; try { swap = new gs_swap_chain(device, data); } catch (const HRError &error) { - blog(LOG_ERROR, "device_swapchain_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_swapchain_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } return swap; } -static void device_resize_internal(gs_device_t *device, uint32_t cx, - uint32_t cy, gs_color_space space) +static void device_resize_internal(gs_device_t *device, uint32_t cx, uint32_t cy, gs_color_space space) { try { - const gs_color_format format = get_swap_format_from_space( - space, device->curSwapChain->initData.format); + const gs_color_format format = get_swap_format_from_space(space, device->curSwapChain->initData.format); device->context->OMSetRenderTargets(0, NULL, NULL); device->curSwapChain->Resize(cx, cy, format); device->curSwapChain->space = space; device->curFramebufferInvalidate = true; } catch (const HRError &error) { - blog(LOG_ERROR, "device_resize_internal (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_resize_internal (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } } @@ -1624,8 +1478,7 @@ void device_resize(gs_device_t *device, uint32_t cx, uint32_t cy) } const enum gs_color_space next_space = - get_next_space(device, device->curSwapChain->hwnd, - device->curSwapChain->swapDesc.SwapEffect); + get_next_space(device, device->curSwapChain->hwnd, device->curSwapChain->swapDesc.SwapEffect); device_resize_internal(device, cx, cy, next_space); } @@ -1637,14 +1490,12 @@ enum gs_color_space device_get_color_space(gs_device_t *device) void device_update_color_space(gs_device_t *device) { if (device->curSwapChain) { - const enum gs_color_space next_space = get_next_space( - device, device->curSwapChain->hwnd, - device->curSwapChain->swapDesc.SwapEffect); + const enum gs_color_space next_space = + get_next_space(device, device->curSwapChain->hwnd, device->curSwapChain->swapDesc.SwapEffect); if (device->curSwapChain->space != next_space) device_resize_internal(device, 0, 0, next_space); } else { - blog(LOG_WARNING, - "device_update_color_space (D3D11): No active swap"); + blog(LOG_WARNING, "device_update_color_space (D3D11): No active swap"); } } @@ -1680,20 +1531,16 @@ uint32_t device_get_height(const gs_device_t *device) } } -gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, - uint32_t height, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, +gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t levels, const uint8_t **data, uint32_t flags) { gs_texture *texture = NULL; try { - texture = new gs_texture_2d(device, width, height, color_format, - levels, data, flags, GS_TEXTURE_2D, + texture = new gs_texture_2d(device, width, height, color_format, levels, data, flags, GS_TEXTURE_2D, false); } catch (const HRError &error) { - blog(LOG_ERROR, "device_texture_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_texture_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { blog(LOG_ERROR, "device_texture_create (D3D11): %s", error); @@ -1702,16 +1549,13 @@ gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, return texture; } -gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, - uint32_t flags) +gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size, enum gs_color_format color_format, + uint32_t levels, const uint8_t **data, uint32_t flags) { gs_texture *texture = NULL; try { - texture = new gs_texture_2d(device, size, size, color_format, - levels, data, flags, - GS_TEXTURE_CUBE, false); + texture = new gs_texture_2d(device, size, size, color_format, levels, data, flags, GS_TEXTURE_CUBE, + false); } catch (const HRError &error) { blog(LOG_ERROR, "device_cubetexture_create (D3D11): %s " @@ -1725,20 +1569,15 @@ gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size, return texture; } -gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, - uint32_t height, uint32_t depth, - enum gs_color_format color_format, - uint32_t levels, - const uint8_t *const *data, +gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, uint32_t height, uint32_t depth, + enum gs_color_format color_format, uint32_t levels, const uint8_t *const *data, uint32_t flags) { gs_texture *texture = NULL; try { - texture = new gs_texture_3d(device, width, height, depth, - color_format, levels, data, flags); + texture = new gs_texture_3d(device, width, height, depth, color_format, levels, data, flags); } catch (const HRError &error) { - blog(LOG_ERROR, "device_voltexture_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_voltexture_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { blog(LOG_ERROR, "device_voltexture_create (D3D11): %s", error); @@ -1747,31 +1586,26 @@ gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, return texture; } -gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width, - uint32_t height, +gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width, uint32_t height, enum gs_zstencil_format format) { gs_zstencil_buffer *zstencil = NULL; try { - zstencil = - new gs_zstencil_buffer(device, width, height, format); + zstencil = new gs_zstencil_buffer(device, width, height, format); } catch (const HRError &error) { - blog(LOG_ERROR, "device_zstencil_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_zstencil_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } return zstencil; } -gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width, - uint32_t height, +gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width, uint32_t height, enum gs_color_format color_format) { gs_stage_surface *surf = NULL; try { - surf = new gs_stage_surface(device, width, height, - color_format); + surf = new gs_stage_surface(device, width, height, color_format); } catch (const HRError &error) { blog(LOG_ERROR, "device_stagesurface_create (D3D11): %s " @@ -1783,9 +1617,7 @@ gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width, return surf; } -gs_samplerstate_t * -device_samplerstate_create(gs_device_t *device, - const struct gs_sampler_info *info) +gs_samplerstate_t *device_samplerstate_create(gs_device_t *device, const struct gs_sampler_info *info) { gs_sampler_state *ss = NULL; try { @@ -1801,9 +1633,8 @@ device_samplerstate_create(gs_device_t *device, return ss; } -gs_shader_t *device_vertexshader_create(gs_device_t *device, - const char *shader_string, - const char *file, char **error_string) +gs_shader_t *device_vertexshader_create(gs_device_t *device, const char *shader_string, const char *file, + char **error_string) { gs_vertex_shader *shader = NULL; try { @@ -1817,8 +1648,7 @@ gs_shader_t *device_vertexshader_create(gs_device_t *device, LogD3D11ErrorDetails(error, device); } catch (const ShaderError &error) { - const char *buf = - (const char *)error.errors->GetBufferPointer(); + const char *buf = (const char *)error.errors->GetBufferPointer(); if (error_string) *error_string = bstrdup(buf); blog(LOG_ERROR, @@ -1827,16 +1657,14 @@ gs_shader_t *device_vertexshader_create(gs_device_t *device, file, buf); } catch (const char *error) { - blog(LOG_ERROR, "device_vertexshader_create (D3D11): %s", - error); + blog(LOG_ERROR, "device_vertexshader_create (D3D11): %s", error); } return shader; } -gs_shader_t *device_pixelshader_create(gs_device_t *device, - const char *shader_string, - const char *file, char **error_string) +gs_shader_t *device_pixelshader_create(gs_device_t *device, const char *shader_string, const char *file, + char **error_string) { gs_pixel_shader *shader = NULL; try { @@ -1850,8 +1678,7 @@ gs_shader_t *device_pixelshader_create(gs_device_t *device, LogD3D11ErrorDetails(error, device); } catch (const ShaderError &error) { - const char *buf = - (const char *)error.errors->GetBufferPointer(); + const char *buf = (const char *)error.errors->GetBufferPointer(); if (error_string) *error_string = bstrdup(buf); blog(LOG_ERROR, @@ -1866,9 +1693,7 @@ gs_shader_t *device_pixelshader_create(gs_device_t *device, return shader; } -gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, - struct gs_vb_data *data, - uint32_t flags) +gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, struct gs_vb_data *data, uint32_t flags) { gs_vertex_buffer *buffer = NULL; try { @@ -1880,24 +1705,20 @@ gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { - blog(LOG_ERROR, "device_vertexbuffer_create (D3D11): %s", - error); + blog(LOG_ERROR, "device_vertexbuffer_create (D3D11): %s", error); } return buffer; } -gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, - enum gs_index_type type, - void *indices, size_t num, +gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, enum gs_index_type type, void *indices, size_t num, uint32_t flags) { gs_index_buffer *buffer = NULL; try { buffer = new gs_index_buffer(device, type, indices, num, flags); } catch (const HRError &error) { - blog(LOG_ERROR, "device_indexbuffer_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_indexbuffer_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } @@ -1910,8 +1731,7 @@ gs_timer_t *device_timer_create(gs_device_t *device) try { timer = new gs_timer(device); } catch (const HRError &error) { - blog(LOG_ERROR, "device_timer_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_timer_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } @@ -1924,8 +1744,7 @@ gs_timer_range_t *device_timer_range_create(gs_device_t *device) try { range = new gs_timer_range(device); } catch (const HRError &error) { - blog(LOG_ERROR, "device_timer_range_create (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_timer_range_create (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } @@ -1939,8 +1758,7 @@ enum gs_texture_type device_get_texture_type(const gs_texture_t *texture) void gs_device::LoadVertexBufferData() { - if (curVertexBuffer == lastVertexBuffer && - curVertexShader == lastVertexShader) + if (curVertexBuffer == lastVertexBuffer && curVertexShader == lastVertexShader) return; ID3D11Buffer *buffers[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; @@ -1953,12 +1771,9 @@ void gs_device::LoadVertexBufferData() assert(curVertexShader->NumBuffersExpected() <= _countof(offsets)); if (curVertexBuffer && curVertexShader) { - numBuffers = curVertexBuffer->MakeBufferList(curVertexShader, - buffers, strides); + numBuffers = curVertexBuffer->MakeBufferList(curVertexShader, buffers, strides); } else { - numBuffers = curVertexShader - ? curVertexShader->NumBuffersExpected() - : 0; + numBuffers = curVertexShader ? curVertexShader->NumBuffersExpected() : 0; std::fill_n(buffers, numBuffers, nullptr); std::fill_n(strides, numBuffers, 0); } @@ -2007,8 +1822,7 @@ void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer) device->context->IASetIndexBuffer(buffer, format, 0); } -static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex, - int unit, +static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex, int unit, ID3D11ShaderResourceView *view) { if (device->curTextures[unit] == tex) @@ -2038,8 +1852,7 @@ void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, int unit) return device_load_texture_internal(device, tex, unit, view); } -void device_load_samplerstate(gs_device_t *device, - gs_samplerstate_t *samplerstate, int unit) +void device_load_samplerstate(gs_device_t *device, gs_samplerstate_t *samplerstate, int unit) { ID3D11SamplerState *state = NULL; @@ -2125,8 +1938,7 @@ void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader) device->context->PSSetSamplers(0, GS_MAX_TEXTURES, states); for (int i = 0; i < GS_MAX_TEXTURES; i++) - if (device->curSamplers[i] && - device->curSamplers[i]->state != states[i]) + if (device->curSamplers[i] && device->curSamplers[i]->state != states[i]) device->curSamplers[i] = nullptr; } @@ -2164,9 +1976,7 @@ gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device) return device->curZStencilBuffer; } -static void device_set_render_target_internal(gs_device_t *device, - gs_texture_t *tex, - gs_zstencil_t *zstencil, +static void device_set_render_target_internal(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil, enum gs_color_space space) { if (device->curSwapChain) { @@ -2176,20 +1986,17 @@ static void device_set_render_target_internal(gs_device_t *device, zstencil = &device->curSwapChain->zs; } - if (device->curRenderTarget == tex && - device->curZStencilBuffer == zstencil) { + if (device->curRenderTarget == tex && device->curZStencilBuffer == zstencil) { device->curColorSpace = space; } if (tex && tex->type != GS_TEXTURE_2D) { - blog(LOG_ERROR, - "device_set_render_target_internal (D3D11): texture is not a 2D texture"); + blog(LOG_ERROR, "device_set_render_target_internal (D3D11): texture is not a 2D texture"); return; } gs_texture_2d *const tex2d = static_cast(tex); - if (device->curRenderTarget != tex2d || device->curRenderSide != 0 || - device->curZStencilBuffer != zstencil) { + if (device->curRenderTarget != tex2d || device->curRenderSide != 0 || device->curZStencilBuffer != zstencil) { device->curRenderTarget = tex2d; device->curZStencilBuffer = zstencil; device->curRenderSide = 0; @@ -2198,22 +2005,18 @@ static void device_set_render_target_internal(gs_device_t *device, } } -void device_set_render_target(gs_device_t *device, gs_texture_t *tex, - gs_zstencil_t *zstencil) +void device_set_render_target(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil) { device_set_render_target_internal(device, tex, zstencil, GS_CS_SRGB); } -void device_set_render_target_with_color_space(gs_device_t *device, - gs_texture_t *tex, - gs_zstencil_t *zstencil, +void device_set_render_target_with_color_space(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil, enum gs_color_space space) { device_set_render_target_internal(device, tex, zstencil, space); } -void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex, - int side, gs_zstencil_t *zstencil) +void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex, int side, gs_zstencil_t *zstencil) { if (device->curSwapChain) { if (!tex) { @@ -2225,8 +2028,7 @@ void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex, zstencil = &device->curSwapChain->zs; } - if (device->curRenderTarget == tex && device->curRenderSide == side && - device->curZStencilBuffer == zstencil) + if (device->curRenderTarget == tex && device->curRenderSide == side && device->curZStencilBuffer == zstencil) return; if (tex->type != GS_TEXTURE_CUBE) { @@ -2259,17 +2061,15 @@ bool device_framebuffer_srgb_enabled(gs_device_t *device) return device->curFramebufferSrgb; } -void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x, uint32_t dst_y, - gs_texture_t *src, uint32_t src_x, uint32_t src_y, - uint32_t src_w, uint32_t src_h) +void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x, uint32_t dst_y, gs_texture_t *src, uint32_t src_x, + uint32_t src_y, uint32_t src_w, uint32_t src_h) { if (src->type != GS_TEXTURE_2D) throw "Source texture must be a 2D texture"; gs_texture_2d *tex2d = static_cast(src); - if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 && - src_w == 0 && src_h == 0) { + if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 && src_w == 0 && src_h == 0) { context->CopyResource(dst, tex2d->texture); } else { D3D11_BOX sbox; @@ -2289,8 +2089,7 @@ void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x, uint32_t dst_y, sbox.front = 0; sbox.back = 1; - context->CopySubresourceRegion(dst, 0, dst_x, dst_y, 0, - tex2d->texture, 0, &sbox); + context->CopySubresourceRegion(dst, 0, dst_x, dst_y, 0, tex2d->texture, 0, &sbox); } } @@ -2308,10 +2107,8 @@ static DXGI_FORMAT get_copy_compare_format(gs_color_format format) } } -void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, - uint32_t dst_x, uint32_t dst_y, - gs_texture_t *src, uint32_t src_x, - uint32_t src_y, uint32_t src_w, uint32_t src_h) +void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, + gs_texture_t *src, uint32_t src_x, uint32_t src_y, uint32_t src_w, uint32_t src_h) { try { gs_texture_2d *src2d = static_cast(src); @@ -2324,17 +2121,14 @@ void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, if (src->type != GS_TEXTURE_2D || dst->type != GS_TEXTURE_2D) throw "Source and destination textures must be a 2D " "textures"; - if (get_copy_compare_format(dst->format) != - get_copy_compare_format(src->format)) + if (get_copy_compare_format(dst->format) != get_copy_compare_format(src->format)) throw "Source and destination formats do not match"; /* apparently casting to the same type that the variable * already exists as is supposed to prevent some warning * when used with the conditional operator? */ - uint32_t copyWidth = (uint32_t)src_w ? (uint32_t)src_w - : (src2d->width - src_x); - uint32_t copyHeight = (uint32_t)src_h ? (uint32_t)src_h - : (src2d->height - src_y); + uint32_t copyWidth = (uint32_t)src_w ? (uint32_t)src_w : (src2d->width - src_x); + uint32_t copyHeight = (uint32_t)src_h ? (uint32_t)src_h : (src2d->height - src_y); uint32_t dstWidth = dst2d->width - dst_x; uint32_t dstHeight = dst2d->height - dst_y; @@ -2343,28 +2137,24 @@ void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, throw "Destination texture region is not big " "enough to hold the source region"; - if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 && - src_w == 0 && src_h == 0) { + if (dst_x == 0 && dst_y == 0 && src_x == 0 && src_y == 0 && src_w == 0 && src_h == 0) { copyWidth = 0; copyHeight = 0; } - device->CopyTex(dst2d->texture, dst_x, dst_y, src, src_x, src_y, - copyWidth, copyHeight); + device->CopyTex(dst2d->texture, dst_x, dst_y, src, src_x, src_y, copyWidth, copyHeight); } catch (const char *error) { blog(LOG_ERROR, "device_copy_texture (D3D11): %s", error); } } -void device_copy_texture(gs_device_t *device, gs_texture_t *dst, - gs_texture_t *src) +void device_copy_texture(gs_device_t *device, gs_texture_t *dst, gs_texture_t *src) { device_copy_texture_region(device, dst, 0, 0, src, 0, 0, 0, 0); } -void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, - gs_texture_t *src) +void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, gs_texture_t *src) { try { gs_texture_2d *src2d = static_cast(src); @@ -2403,8 +2193,7 @@ void device_begin_scene(gs_device_t *device) clear_textures(device); } -void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, - uint32_t start_vert, uint32_t num_verts) +void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, uint32_t start_vert, uint32_t num_verts) { try { if (!device->curVertexShader) @@ -2438,8 +2227,7 @@ void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, return; } catch (const HRError &error) { - blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str, - error.hr); + blog(LOG_ERROR, "device_draw (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); return; } @@ -2471,10 +2259,7 @@ void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain) { gs_texture_t *target = device->curRenderTarget; gs_zstencil_t *zs = device->curZStencilBuffer; - bool is_cube = - device->curRenderTarget - ? (device->curRenderTarget->type == GS_TEXTURE_CUBE) - : false; + bool is_cube = device->curRenderTarget ? (device->curRenderTarget->type == GS_TEXTURE_CUBE) : false; if (device->curSwapChain) { if (target == &device->curSwapChain->target) @@ -2486,26 +2271,21 @@ void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain) device->curSwapChain = swapchain; if (is_cube) { - device_set_cube_render_target(device, target, - device->curRenderSide, zs); + device_set_cube_render_target(device, target, device->curRenderSide, zs); } else { - const enum gs_color_space space = swapchain ? swapchain->space - : GS_CS_SRGB; + const enum gs_color_space space = swapchain ? swapchain->space : GS_CS_SRGB; device_set_render_target_internal(device, target, zs, space); } } -void device_clear(gs_device_t *device, uint32_t clear_flags, - const struct vec4 *color, float depth, uint8_t stencil) +void device_clear(gs_device_t *device, uint32_t clear_flags, const struct vec4 *color, float depth, uint8_t stencil) { if (clear_flags & GS_CLEAR_COLOR) { gs_texture_2d *const tex = device->curRenderTarget; if (tex) { const int side = device->curRenderSide; - ID3D11RenderTargetView *const rtv = - device->curFramebufferSrgb - ? tex->renderTargetLinear[side] - : tex->renderTarget[side]; + ID3D11RenderTargetView *const rtv = device->curFramebufferSrgb ? tex->renderTargetLinear[side] + : tex->renderTarget[side]; device->context->ClearRenderTargetView(rtv, color->ptr); } } @@ -2518,9 +2298,7 @@ void device_clear(gs_device_t *device, uint32_t clear_flags, flags |= D3D11_CLEAR_STENCIL; if (flags && device->curZStencilBuffer->view) - device->context->ClearDepthStencilView( - device->curZStencilBuffer->view, flags, depth, - stencil); + device->context->ClearDepthStencilView(device->curZStencilBuffer->view, flags, depth, stencil); } } @@ -2530,11 +2308,9 @@ bool device_is_present_ready(gs_device_t *device) bool ready = curSwapChain != nullptr; if (ready) { const HANDLE hWaitable = curSwapChain->hWaitable; - ready = (hWaitable == NULL) || - WaitForSingleObject(hWaitable, 0) == WAIT_OBJECT_0; + ready = (hWaitable == NULL) || WaitForSingleObject(hWaitable, 0) == WAIT_OBJECT_0; } else { - blog(LOG_WARNING, - "device_is_present_ready (D3D11): No active swap"); + blog(LOG_WARNING, "device_is_present_ready (D3D11): No active swap"); } return ready; @@ -2549,8 +2325,7 @@ void device_present(gs_device_t *device) const UINT interval = curSwapChain->hWaitable ? 1 : 0; const HRESULT hr = curSwapChain->swap->Present(interval, 0); - if (hr == DXGI_ERROR_DEVICE_REMOVED || - hr == DXGI_ERROR_DEVICE_RESET) { + if (hr == DXGI_ERROR_DEVICE_REMOVED || hr == DXGI_ERROR_DEVICE_RESET) { device->RebuildDevice(); } } else { @@ -2613,13 +2388,10 @@ void device_enable_stencil_write(gs_device_t *device, bool enable) device->zstencilStateChanged = true; } -void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, - bool alpha) +void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, bool alpha) { - if (device->blendState.redEnabled == red && - device->blendState.greenEnabled == green && - device->blendState.blueEnabled == blue && - device->blendState.alphaEnabled == alpha) + if (device->blendState.redEnabled == red && device->blendState.greenEnabled == green && + device->blendState.blueEnabled == blue && device->blendState.alphaEnabled == alpha) return; device->blendState.redEnabled = red; @@ -2629,13 +2401,10 @@ void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, device->blendStateChanged = true; } -void device_blend_function(gs_device_t *device, enum gs_blend_type src, - enum gs_blend_type dest) +void device_blend_function(gs_device_t *device, enum gs_blend_type src, enum gs_blend_type dest) { - if (device->blendState.srcFactorC == src && - device->blendState.destFactorC == dest && - device->blendState.srcFactorA == src && - device->blendState.destFactorA == dest) + if (device->blendState.srcFactorC == src && device->blendState.destFactorC == dest && + device->blendState.srcFactorA == src && device->blendState.destFactorA == dest) return; device->blendState.srcFactorC = src; @@ -2645,16 +2414,11 @@ void device_blend_function(gs_device_t *device, enum gs_blend_type src, device->blendStateChanged = true; } -void device_blend_function_separate(gs_device_t *device, - enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, - enum gs_blend_type dest_a) +void device_blend_function_separate(gs_device_t *device, enum gs_blend_type src_c, enum gs_blend_type dest_c, + enum gs_blend_type src_a, enum gs_blend_type dest_a) { - if (device->blendState.srcFactorC == src_c && - device->blendState.destFactorC == dest_c && - device->blendState.srcFactorA == src_a && - device->blendState.destFactorA == dest_a) + if (device->blendState.srcFactorC == src_c && device->blendState.destFactorC == dest_c && + device->blendState.srcFactorA == src_a && device->blendState.destFactorA == dest_a) return; device->blendState.srcFactorC = src_c; @@ -2682,9 +2446,7 @@ void device_depth_function(gs_device_t *device, enum gs_depth_test test) device->zstencilStateChanged = true; } -static inline void update_stencilside_test(gs_device_t *device, - StencilSide &side, - gs_depth_test test) +static inline void update_stencilside_test(gs_device_t *device, StencilSide &side, gs_depth_test test) { if (side.test == test) return; @@ -2693,23 +2455,18 @@ static inline void update_stencilside_test(gs_device_t *device, device->zstencilStateChanged = true; } -void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, - enum gs_depth_test test) +void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, enum gs_depth_test test) { int sideVal = (int)side; if (sideVal & GS_STENCIL_FRONT) - update_stencilside_test( - device, device->zstencilState.stencilFront, test); + update_stencilside_test(device, device->zstencilState.stencilFront, test); if (sideVal & GS_STENCIL_BACK) - update_stencilside_test( - device, device->zstencilState.stencilBack, test); + update_stencilside_test(device, device->zstencilState.stencilBack, test); } -static inline void update_stencilside_op(gs_device_t *device, StencilSide &side, - enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, - enum gs_stencil_op_type zpass) +static inline void update_stencilside_op(gs_device_t *device, StencilSide &side, enum gs_stencil_op_type fail, + enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass) { if (side.fail == fail && side.zfail == zfail && side.zpass == zpass) return; @@ -2720,24 +2477,18 @@ static inline void update_stencilside_op(gs_device_t *device, StencilSide &side, device->zstencilStateChanged = true; } -void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, - enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, - enum gs_stencil_op_type zpass) +void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, enum gs_stencil_op_type fail, + enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass) { int sideVal = (int)side; if (sideVal & GS_STENCIL_FRONT) - update_stencilside_op(device, - device->zstencilState.stencilFront, fail, - zfail, zpass); + update_stencilside_op(device, device->zstencilState.stencilFront, fail, zfail, zpass); if (sideVal & GS_STENCIL_BACK) - update_stencilside_op(device, device->zstencilState.stencilBack, - fail, zfail, zpass); + update_stencilside_op(device, device->zstencilState.stencilBack, fail, zfail, zpass); } -void device_set_viewport(gs_device_t *device, int x, int y, int width, - int height) +void device_set_viewport(gs_device_t *device, int x, int y, int width, int height) { D3D11_VIEWPORT vp; memset(&vp, 0, sizeof(vp)); @@ -2776,8 +2527,7 @@ void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect) device->rasterStateChanged = true; } -void device_ortho(gs_device_t *device, float left, float right, float top, - float bottom, float zNear, float zFar) +void device_ortho(gs_device_t *device, float left, float right, float top, float bottom, float zNear, float zFar) { matrix4 *dst = &device->curProjMatrix; @@ -2802,8 +2552,7 @@ void device_ortho(gs_device_t *device, float left, float right, float top, dst->t.w = 1.0f; } -void device_frustum(gs_device_t *device, float left, float right, float top, - float bottom, float zNear, float zFar) +void device_frustum(gs_device_t *device, float left, float right, float top, float bottom, float zNear, float zFar) { matrix4 *dst = &device->curProjMatrix; @@ -2893,8 +2642,7 @@ bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize) gs_texture_2d *tex2d = static_cast(tex); D3D11_MAPPED_SUBRESOURCE map; - hr = tex2d->device->context->Map(tex2d->texture, 0, - D3D11_MAP_WRITE_DISCARD, 0, &map); + hr = tex2d->device->context->Map(tex2d->texture, 0, D3D11_MAP_WRITE_DISCARD, 0, &map); if (FAILED(hr)) return false; @@ -2935,8 +2683,7 @@ uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex) return tex->width; } -enum gs_color_format -gs_cubetexture_get_color_format(const gs_texture_t *cubetex) +enum gs_color_format gs_cubetexture_get_color_format(const gs_texture_t *cubetex) { if (cubetex->type != GS_TEXTURE_CUBE) return GS_UNKNOWN; @@ -2993,18 +2740,15 @@ uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf) return stagesurf->height; } -enum gs_color_format -gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) +enum gs_color_format gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) { return stagesurf->format; } -bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, - uint32_t *linesize) +bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, uint32_t *linesize) { D3D11_MAPPED_SUBRESOURCE map; - if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0, - D3D11_MAP_READ, 0, &map))) + if (FAILED(stagesurf->device->context->Map(stagesurf->texture, 0, D3D11_MAP_READ, 0, &map))) return false; *data = (uint8_t *)map.pData; @@ -3029,8 +2773,7 @@ void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate) if (samplerstate->device) for (int i = 0; i < GS_MAX_TEXTURES; i++) - if (samplerstate->device->curSamplers[i] == - samplerstate) + if (samplerstate->device->curSamplers[i] == samplerstate) samplerstate->device->curSamplers[i] = nullptr; delete samplerstate; @@ -3043,12 +2786,9 @@ void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer) delete vertbuffer; } -static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer, - const gs_vb_data *data) +static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer, const gs_vb_data *data) { - size_t num_tex = data->num_tex < vertbuffer->uvBuffers.size() - ? data->num_tex - : vertbuffer->uvBuffers.size(); + size_t num_tex = data->num_tex < vertbuffer->uvBuffers.size() ? data->num_tex : vertbuffer->uvBuffers.size(); if (!vertbuffer->dynamic) { blog(LOG_ERROR, "gs_vertexbuffer_flush: vertex buffer is " @@ -3057,25 +2797,20 @@ static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer, } if (data->points) - vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points, - sizeof(vec3)); + vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points, sizeof(vec3)); if (vertbuffer->normalBuffer && data->normals) - vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals, - sizeof(vec3)); + vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals, sizeof(vec3)); if (vertbuffer->tangentBuffer && data->tangents) - vertbuffer->FlushBuffer(vertbuffer->tangentBuffer, - data->tangents, sizeof(vec3)); + vertbuffer->FlushBuffer(vertbuffer->tangentBuffer, data->tangents, sizeof(vec3)); if (vertbuffer->colorBuffer && data->colors) - vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors, - sizeof(uint32_t)); + vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors, sizeof(uint32_t)); for (size_t i = 0; i < num_tex; i++) { gs_tvertarray &tv = data->tvarray[i]; - vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], tv.array, - tv.width * sizeof(float)); + vertbuffer->FlushBuffer(vertbuffer->uvBuffers[i], tv.array, tv.width * sizeof(float)); } } @@ -3084,8 +2819,7 @@ void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer) gs_vertexbuffer_flush_internal(vertbuffer, vertbuffer->vbd.data); } -void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer, - const gs_vb_data *data) +void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer, const gs_vb_data *data) { gs_vertexbuffer_flush_internal(vertbuffer, data); } @@ -3100,8 +2834,7 @@ void gs_indexbuffer_destroy(gs_indexbuffer_t *indexbuffer) delete indexbuffer; } -static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer, - const void *data) +static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer, const void *data) { HRESULT hr; @@ -3109,8 +2842,7 @@ static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer, return; D3D11_MAPPED_SUBRESOURCE map; - hr = indexbuffer->device->context->Map( - indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map); + hr = indexbuffer->device->context->Map(indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map); if (FAILED(hr)) return; @@ -3124,8 +2856,7 @@ void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer) gs_indexbuffer_flush_internal(indexbuffer, indexbuffer->indices.data); } -void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer, - const void *data) +void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer, const void *data) { gs_indexbuffer_flush_internal(indexbuffer, data); } @@ -3165,12 +2896,10 @@ bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks) uint64_t begin, end; HRESULT hr_begin, hr_end; do { - hr_begin = timer->device->context->GetData( - timer->query_begin, &begin, sizeof(begin), 0); + hr_begin = timer->device->context->GetData(timer->query_begin, &begin, sizeof(begin), 0); } while (hr_begin == S_FALSE); do { - hr_end = timer->device->context->GetData(timer->query_end, &end, - sizeof(end), 0); + hr_end = timer->device->context->GetData(timer->query_end, &end, sizeof(end), 0); } while (hr_end == S_FALSE); const bool succeeded = SUCCEEDED(hr_begin) && SUCCEEDED(hr_end); @@ -3195,16 +2924,13 @@ void gs_timer_range_end(gs_timer_range_t *range) range->device->context->End(range->query_disjoint); } -bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, - uint64_t *frequency) +bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, uint64_t *frequency) { D3D11_QUERY_DATA_TIMESTAMP_DISJOINT timestamp_disjoint; HRESULT hr; do { - hr = range->device->context->GetData(range->query_disjoint, - ×tamp_disjoint, - sizeof(timestamp_disjoint), - 0); + hr = range->device->context->GetData(range->query_disjoint, ×tamp_disjoint, + sizeof(timestamp_disjoint), 0); } while (hr == S_FALSE); const bool succeeded = SUCCEEDED(hr); @@ -3221,8 +2947,7 @@ gs_timer::gs_timer(gs_device_t *device) : gs_obj(device, gs_type::gs_timer) Rebuild(device->device); } -gs_timer_range::gs_timer_range(gs_device_t *device) - : gs_obj(device, gs_type::gs_timer_range) +gs_timer_range::gs_timer_range(gs_device_t *device) : gs_obj(device, gs_type::gs_timer_range) { Rebuild(device->device); } @@ -3253,14 +2978,10 @@ extern "C" EXPORT bool device_is_monitor_hdr(gs_device_t *device, void *monitor) return device->GetMonitorColorInfo(hMonitor).hdr; } -extern "C" EXPORT void device_debug_marker_begin(gs_device_t *, - const char *markername, - const float color[4]) +extern "C" EXPORT void device_debug_marker_begin(gs_device_t *, const char *markername, const float color[4]) { - D3DCOLOR bgra = D3DCOLOR_ARGB((DWORD)(255.0f * color[3]), - (DWORD)(255.0f * color[0]), - (DWORD)(255.0f * color[1]), - (DWORD)(255.0f * color[2])); + D3DCOLOR bgra = D3DCOLOR_ARGB((DWORD)(255.0f * color[3]), (DWORD)(255.0f * color[0]), + (DWORD)(255.0f * color[1]), (DWORD)(255.0f * color[2])); wchar_t wide[64]; os_utf8_to_wcs(markername, 0, wide, _countof(wide)); @@ -3273,18 +2994,14 @@ extern "C" EXPORT void device_debug_marker_end(gs_device_t *) D3DPERF_EndEvent(); } -extern "C" EXPORT gs_texture_t * -device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height) +extern "C" EXPORT gs_texture_t *device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height) { gs_texture *texture = nullptr; try { - texture = new gs_texture_2d(device, width, height, - GS_BGRA_UNORM, 1, nullptr, - GS_RENDER_TARGET, GS_TEXTURE_2D, - true); + texture = new gs_texture_2d(device, width, height, GS_BGRA_UNORM, 1, nullptr, GS_RENDER_TARGET, + GS_TEXTURE_2D, true); } catch (const HRError &error) { - blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { blog(LOG_ERROR, "device_texture_create_gdi (D3D11): %s", error); @@ -3296,8 +3013,7 @@ device_texture_create_gdi(gs_device_t *device, uint32_t width, uint32_t height) static inline bool TextureGDICompatible(gs_texture_2d *tex2d, const char *func) { if (!tex2d->isGDICompatible) { - blog(LOG_ERROR, "%s (D3D11): Texture is not GDI compatible", - func); + blog(LOG_ERROR, "%s (D3D11): Texture is not GDI compatible", func); return false; } @@ -3334,15 +3050,13 @@ extern "C" EXPORT void gs_texture_release_dc(gs_texture_t *tex) tex2d->gdiSurface->ReleaseDC(nullptr); } -extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device, - uint32_t handle) +extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device, uint32_t handle) { gs_texture *texture = nullptr; try { texture = new gs_texture_2d(device, handle); } catch (const HRError &error) { - blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { blog(LOG_ERROR, "gs_texture_open_shared (D3D11): %s", error); @@ -3351,15 +3065,13 @@ extern "C" EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device, return texture; } -extern "C" EXPORT gs_texture_t * -device_texture_open_nt_shared(gs_device_t *device, uint32_t handle) +extern "C" EXPORT gs_texture_t *device_texture_open_nt_shared(gs_device_t *device, uint32_t handle) { gs_texture *texture = nullptr; try { texture = new gs_texture_2d(device, handle, true); } catch (const HRError &error) { - blog(LOG_ERROR, "gs_texture_open_nt_shared (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "gs_texture_open_nt_shared (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { blog(LOG_ERROR, "gs_texture_open_nt_shared (D3D11): %s", error); @@ -3377,15 +3089,13 @@ extern "C" EXPORT uint32_t device_texture_get_shared_handle(gs_texture_t *tex) return tex2d->isShared ? tex2d->sharedHandle : GS_INVALID_HANDLE; } -extern "C" EXPORT gs_texture_t *device_texture_wrap_obj(gs_device_t *device, - void *obj) +extern "C" EXPORT gs_texture_t *device_texture_wrap_obj(gs_device_t *device, void *obj) { gs_texture *texture = nullptr; try { texture = new gs_texture_2d(device, (ID3D11Texture2D *)obj); } catch (const HRError &error) { - blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); } catch (const char *error) { blog(LOG_ERROR, "gs_texture_wrap_obj (D3D11): %s", error); @@ -3418,8 +3128,7 @@ int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms) return -1; } -extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex, - uint64_t key) +extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex, uint64_t key) { gs_texture_2d *tex2d = reinterpret_cast(tex); if (tex->type != GS_TEXTURE_2D) @@ -3441,10 +3150,8 @@ extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex, return -1; } -extern "C" EXPORT bool -device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y, - gs_texture_t **p_tex_uv, uint32_t width, - uint32_t height, uint32_t flags) +extern "C" EXPORT bool device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y, gs_texture_t **p_tex_uv, + uint32_t width, uint32_t height, uint32_t flags) { if (!device->nv12Supported) return false; @@ -3456,14 +3163,11 @@ device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y, gs_texture_2d *tex_uv; try { - tex_y = new gs_texture_2d(device, width, height, GS_R8, 1, - nullptr, flags, GS_TEXTURE_2D, false, - true); + tex_y = new gs_texture_2d(device, width, height, GS_R8, 1, nullptr, flags, GS_TEXTURE_2D, false, true); tex_uv = new gs_texture_2d(device, tex_y->texture, flags); } catch (const HRError &error) { - blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "gs_texture_create_nv12 (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); return false; @@ -3480,10 +3184,8 @@ device_texture_create_nv12(gs_device_t *device, gs_texture_t **p_tex_y, return true; } -extern "C" EXPORT bool -device_texture_create_p010(gs_device_t *device, gs_texture_t **p_tex_y, - gs_texture_t **p_tex_uv, uint32_t width, - uint32_t height, uint32_t flags) +extern "C" EXPORT bool device_texture_create_p010(gs_device_t *device, gs_texture_t **p_tex_y, gs_texture_t **p_tex_uv, + uint32_t width, uint32_t height, uint32_t flags) { if (!device->p010Supported) return false; @@ -3495,14 +3197,11 @@ device_texture_create_p010(gs_device_t *device, gs_texture_t **p_tex_y, gs_texture_2d *tex_uv; try { - tex_y = new gs_texture_2d(device, width, height, GS_R16, 1, - nullptr, flags, GS_TEXTURE_2D, false, - true); + tex_y = new gs_texture_2d(device, width, height, GS_R16, 1, nullptr, flags, GS_TEXTURE_2D, false, true); tex_uv = new gs_texture_2d(device, tex_y->texture, flags); } catch (const HRError &error) { - blog(LOG_ERROR, "gs_texture_create_p010 (D3D11): %s (%08lX)", - error.str, error.hr); + blog(LOG_ERROR, "gs_texture_create_p010 (D3D11): %s (%08lX)", error.str, error.hr); LogD3D11ErrorDetails(error, device); return false; @@ -3519,9 +3218,7 @@ device_texture_create_p010(gs_device_t *device, gs_texture_t **p_tex_y, return true; } -extern "C" EXPORT gs_stagesurf_t * -device_stagesurface_create_nv12(gs_device_t *device, uint32_t width, - uint32_t height) +extern "C" EXPORT gs_stagesurf_t *device_stagesurface_create_nv12(gs_device_t *device, uint32_t width, uint32_t height) { gs_stage_surface *surf = NULL; try { @@ -3537,9 +3234,7 @@ device_stagesurface_create_nv12(gs_device_t *device, uint32_t width, return surf; } -extern "C" EXPORT gs_stagesurf_t * -device_stagesurface_create_p010(gs_device_t *device, uint32_t width, - uint32_t height) +extern "C" EXPORT gs_stagesurf_t *device_stagesurface_create_p010(gs_device_t *device, uint32_t width, uint32_t height) { gs_stage_surface *surf = NULL; try { @@ -3555,18 +3250,14 @@ device_stagesurface_create_p010(gs_device_t *device, uint32_t width, return surf; } -extern "C" EXPORT void -device_register_loss_callbacks(gs_device_t *device, - const gs_device_loss *callbacks) +extern "C" EXPORT void device_register_loss_callbacks(gs_device_t *device, const gs_device_loss *callbacks) { device->loss_callbacks.emplace_back(*callbacks); } -extern "C" EXPORT void device_unregister_loss_callbacks(gs_device_t *device, - void *data) +extern "C" EXPORT void device_unregister_loss_callbacks(gs_device_t *device, void *data) { - for (auto iter = device->loss_callbacks.begin(); - iter != device->loss_callbacks.end(); ++iter) { + for (auto iter = device->loss_callbacks.begin(); iter != device->loss_callbacks.end(); ++iter) { if (iter->data == data) { device->loss_callbacks.erase(iter); break; @@ -3582,13 +3273,11 @@ uint32_t gs_get_adapter_count(void) HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); if (SUCCEEDED(hr)) { ComPtr adapter; - for (UINT i = 0; - factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) { + for (UINT i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) { DXGI_ADAPTER_DESC desc; if (SUCCEEDED(adapter->GetDesc(&desc))) { /* ignore Microsoft's 'basic' renderer' */ - if (desc.VendorId != 0x1414 && - desc.DeviceId != 0x8c) { + if (desc.VendorId != 0x1414 && desc.DeviceId != 0x8c) { ++count; } } diff --git a/libobs-d3d11/d3d11-subsystem.hpp b/libobs-d3d11/d3d11-subsystem.hpp index 89d04969f..9278d49ed 100644 --- a/libobs-d3d11/d3d11-subsystem.hpp +++ b/libobs-d3d11/d3d11-subsystem.hpp @@ -37,8 +37,7 @@ // #define DISASSEMBLE_SHADERS -typedef HRESULT(WINAPI *pD3DCreateBlob)(_In_ SIZE_T Size, - _Out_ ID3DBlob **ppBlob); +typedef HRESULT(WINAPI *pD3DCreateBlob)(_In_ SIZE_T Size, _Out_ ID3DBlob **ppBlob); struct shader_var; struct shader_sampler; @@ -128,8 +127,7 @@ static inline DXGI_FORMAT ConvertGSTextureFormatView(gs_color_format format) } } -static inline DXGI_FORMAT -ConvertGSTextureFormatViewLinear(gs_color_format format) +static inline DXGI_FORMAT ConvertGSTextureFormatViewLinear(gs_color_format format) { switch (format) { case GS_RGBA: @@ -387,11 +385,9 @@ struct gs_vertex_buffer : gs_obj { void FlushBuffer(ID3D11Buffer *buffer, void *array, size_t elementSize); - UINT MakeBufferList(gs_vertex_shader *shader, ID3D11Buffer **buffers, - uint32_t *strides); + UINT MakeBufferList(gs_vertex_shader *shader, ID3D11Buffer **buffers, uint32_t *strides); - void InitBuffer(const size_t elementSize, const size_t numVerts, - void *array, ID3D11Buffer **buffer); + void InitBuffer(const size_t elementSize, const size_t numVerts, void *array, ID3D11Buffer **buffer); void BuildBuffers(); @@ -406,8 +402,7 @@ struct gs_vertex_buffer : gs_obj { void Rebuild(); - gs_vertex_buffer(gs_device_t *device, struct gs_vb_data *data, - uint32_t flags); + gs_vertex_buffer(gs_device_t *device, struct gs_vb_data *data, uint32_t flags); }; /* exception-safe RAII wrapper for index buffer data (NOTE: not copy-safe) */ @@ -435,8 +430,7 @@ struct gs_index_buffer : gs_obj { inline void Release() { indexBuffer.Release(); } - gs_index_buffer(gs_device_t *device, enum gs_index_type type, - void *indices, size_t num, uint32_t flags); + gs_index_buffer(gs_device_t *device, enum gs_index_type type, void *indices, size_t num, uint32_t flags); }; struct gs_timer : gs_obj { @@ -476,23 +470,20 @@ struct gs_texture : gs_obj { void Rebuild(ID3D11Device *dev); - inline gs_texture(gs_texture_type type, uint32_t levels, - gs_color_format format) + inline gs_texture(gs_texture_type type, uint32_t levels, gs_color_format format) : type(type), levels(levels), format(format) { } - inline gs_texture(gs_device *device, gs_type obj_type, - gs_texture_type type) + inline gs_texture(gs_device *device, gs_type obj_type, gs_texture_type type) : gs_obj(device, obj_type), type(type) { } - inline gs_texture(gs_device *device, gs_type obj_type, - gs_texture_type type, uint32_t levels, + inline gs_texture(gs_device *device, gs_type obj_type, gs_texture_type type, uint32_t levels, gs_color_format format) : gs_obj(device, obj_type), type(type), @@ -555,16 +546,12 @@ struct gs_texture_2d : gs_texture { inline gs_texture_2d() : gs_texture(GS_TEXTURE_2D, 0, GS_UNKNOWN) {} - gs_texture_2d(gs_device_t *device, uint32_t width, uint32_t height, - gs_color_format colorFormat, uint32_t levels, - const uint8_t *const *data, uint32_t flags, - gs_texture_type type, bool gdiCompatible, - bool twoPlane = false); + gs_texture_2d(gs_device_t *device, uint32_t width, uint32_t height, gs_color_format colorFormat, + uint32_t levels, const uint8_t *const *data, uint32_t flags, gs_texture_type type, + bool gdiCompatible, bool twoPlane = false); - gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12, - uint32_t flags); - gs_texture_2d(gs_device_t *device, uint32_t handle, - bool ntHandle = false); + gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12, uint32_t flags); + gs_texture_2d(gs_device_t *device, uint32_t handle, bool ntHandle = false); gs_texture_2d(gs_device_t *device, ID3D11Texture2D *obj); }; @@ -607,10 +594,8 @@ struct gs_texture_3d : gs_texture { inline gs_texture_3d() : gs_texture(GS_TEXTURE_3D, 0, GS_UNKNOWN) {} - gs_texture_3d(gs_device_t *device, uint32_t width, uint32_t height, - uint32_t depth, gs_color_format colorFormat, - uint32_t levels, const uint8_t *const *data, - uint32_t flags); + gs_texture_3d(gs_device_t *device, uint32_t width, uint32_t height, uint32_t depth, gs_color_format colorFormat, + uint32_t levels, const uint8_t *const *data, uint32_t flags); gs_texture_3d(gs_device_t *device, uint32_t handle); }; @@ -636,15 +621,9 @@ struct gs_zstencil_buffer : gs_obj { view.Release(); } - inline gs_zstencil_buffer() - : width(0), - height(0), - dxgiFormat(DXGI_FORMAT_UNKNOWN) - { - } + inline gs_zstencil_buffer() : width(0), height(0), dxgiFormat(DXGI_FORMAT_UNKNOWN) {} - gs_zstencil_buffer(gs_device_t *device, uint32_t width, uint32_t height, - gs_zstencil_format format); + gs_zstencil_buffer(gs_device_t *device, uint32_t width, uint32_t height, gs_zstencil_format format); }; struct gs_stage_surface : gs_obj { @@ -659,10 +638,8 @@ struct gs_stage_surface : gs_obj { inline void Release() { texture.Release(); } - gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t height, - gs_color_format colorFormat); - gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t height, - bool p010); + gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t height, gs_color_format colorFormat); + gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t height, bool p010); }; struct gs_sampler_state : gs_obj { @@ -699,11 +676,7 @@ struct ShaderError { ComPtr errors; HRESULT hr; - inline ShaderError(const ComPtr &errors, HRESULT hr) - : errors(errors), - hr(hr) - { - } + inline ShaderError(const ComPtr &errors, HRESULT hr) : errors(errors), hr(hr) {} }; struct gs_shader : gs_obj { @@ -715,16 +688,13 @@ struct gs_shader : gs_obj { D3D11_BUFFER_DESC bd = {}; vector data; - inline void UpdateParam(vector &constData, - gs_shader_param ¶m, bool &upload); + inline void UpdateParam(vector &constData, gs_shader_param ¶m, bool &upload); void UploadParams(); void BuildConstantBuffer(); - void Compile(const char *shaderStr, const char *file, - const char *target, ID3D10Blob **shader); + void Compile(const char *shaderStr, const char *file, const char *target, ID3D10Blob **shader); - inline gs_shader(gs_device_t *device, gs_type obj_type, - gs_shader_type type) + inline gs_shader(gs_device_t *device, gs_type obj_type, gs_shader_type type) : gs_obj(device, obj_type), type(type), constantSize(0) @@ -738,8 +708,7 @@ struct ShaderSampler { string name; gs_sampler_state sampler; - inline ShaderSampler(const char *name, gs_device_t *device, - gs_sampler_info *info) + inline ShaderSampler(const char *name, gs_device_t *device, gs_sampler_info *info) : name(name), sampler(device, info) { @@ -783,8 +752,7 @@ struct gs_vertex_shader : gs_shader { void GetBuffersExpected(const vector &inputs); - gs_vertex_shader(gs_device_t *device, const char *file, - const char *shaderString); + gs_vertex_shader(gs_device_t *device, const char *file, const char *shaderString); }; struct gs_duplicator : gs_obj { @@ -826,8 +794,7 @@ struct gs_pixel_shader : gs_shader { states[i] = NULL; } - gs_pixel_shader(gs_device_t *device, const char *file, - const char *shaderString); + gs_pixel_shader(gs_device_t *device, const char *file, const char *shaderString); }; struct gs_swap_chain : gs_obj { @@ -890,10 +857,7 @@ struct BlendState { { } - inline BlendState(const BlendState &state) - { - memcpy(this, &state, sizeof(BlendState)); - } + inline BlendState(const BlendState &state) { memcpy(this, &state, sizeof(BlendState)); } }; struct SavedBlendState : BlendState { @@ -904,11 +868,7 @@ struct SavedBlendState : BlendState { inline void Release() { state.Release(); } - inline SavedBlendState(const BlendState &val, D3D11_BLEND_DESC &desc) - : BlendState(val), - bd(desc) - { - } + inline SavedBlendState(const BlendState &val, D3D11_BLEND_DESC &desc) : BlendState(val), bd(desc) {} }; struct StencilSide { @@ -917,13 +877,7 @@ struct StencilSide { gs_stencil_op_type zfail; gs_stencil_op_type zpass; - inline StencilSide() - : test(GS_ALWAYS), - fail(GS_KEEP), - zfail(GS_KEEP), - zpass(GS_KEEP) - { - } + inline StencilSide() : test(GS_ALWAYS), fail(GS_KEEP), zfail(GS_KEEP), zpass(GS_KEEP) {} }; struct ZStencilState { @@ -945,10 +899,7 @@ struct ZStencilState { { } - inline ZStencilState(const ZStencilState &state) - { - memcpy(this, &state, sizeof(ZStencilState)); - } + inline ZStencilState(const ZStencilState &state) { memcpy(this, &state, sizeof(ZStencilState)); } }; struct SavedZStencilState : ZStencilState { @@ -959,8 +910,7 @@ struct SavedZStencilState : ZStencilState { inline void Release() { state.Release(); } - inline SavedZStencilState(const ZStencilState &val, - D3D11_DEPTH_STENCIL_DESC desc) + inline SavedZStencilState(const ZStencilState &val, D3D11_DEPTH_STENCIL_DESC desc) : ZStencilState(val), dsd(desc) { @@ -973,10 +923,7 @@ struct RasterState { inline RasterState() : cullMode(GS_BACK), scissorEnabled(false) {} - inline RasterState(const RasterState &state) - { - memcpy(this, &state, sizeof(RasterState)); - } + inline RasterState(const RasterState &state) { memcpy(this, &state, sizeof(RasterState)); } }; struct SavedRasterState : RasterState { @@ -987,12 +934,7 @@ struct SavedRasterState : RasterState { inline void Release() { state.Release(); } - inline SavedRasterState(const RasterState &val, - D3D11_RASTERIZER_DESC &desc) - : RasterState(val), - rd(desc) - { - } + inline SavedRasterState(const RasterState &val, D3D11_RASTERIZER_DESC &desc) : RasterState(val), rd(desc) {} }; struct mat4float { @@ -1004,8 +946,7 @@ struct gs_monitor_color_info { UINT bits_per_color; ULONG sdr_white_nits; - gs_monitor_color_info(bool hdr, int bits_per_color, - ULONG sdr_white_nits) + gs_monitor_color_info(bool hdr, int bits_per_color, ULONG sdr_white_nits) : hdr(hdr), bits_per_color(bits_per_color), sdr_white_nits(sdr_white_nits) @@ -1080,9 +1021,8 @@ struct gs_device { void LoadVertexBufferData(); - void CopyTex(ID3D11Texture2D *dst, uint32_t dst_x, uint32_t dst_y, - gs_texture_t *src, uint32_t src_x, uint32_t src_y, - uint32_t src_w, uint32_t src_h); + void CopyTex(ID3D11Texture2D *dst, uint32_t dst_x, uint32_t dst_y, gs_texture_t *src, uint32_t src_x, + uint32_t src_y, uint32_t src_w, uint32_t src_h); void UpdateViewProjMatrix(); @@ -1098,5 +1038,4 @@ struct gs_device { ~gs_device(); }; -extern "C" EXPORT int device_texture_acquire_sync(gs_texture_t *tex, - uint64_t key, uint32_t ms); +extern "C" EXPORT int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms); diff --git a/libobs-d3d11/d3d11-texture2d.cpp b/libobs-d3d11/d3d11-texture2d.cpp index 9785ef6f5..cbb54762b 100644 --- a/libobs-d3d11/d3d11-texture2d.cpp +++ b/libobs-d3d11/d3d11-texture2d.cpp @@ -103,9 +103,7 @@ void gs_texture_2d::InitTexture(const uint8_t *const *data) td.Height = height; td.MipLevels = genMipmaps ? 0 : levels; td.ArraySize = type == GS_TEXTURE_CUBE ? 6 : 1; - td.Format = twoPlane ? ((format == GS_R16) ? DXGI_FORMAT_P010 - : DXGI_FORMAT_NV12) - : dxgiFormatResource; + td.Format = twoPlane ? ((format == GS_R16) ? DXGI_FORMAT_P010 : DXGI_FORMAT_NV12) : dxgiFormatResource; td.BindFlags = D3D11_BIND_SHADER_RESOURCE; td.SampleDesc.Count = 1; td.CPUAccessFlags = isDynamic ? D3D11_CPU_ACCESS_WRITE : 0; @@ -130,14 +128,12 @@ void gs_texture_2d::InitTexture(const uint8_t *const *data) InitSRD(srd); } - hr = device->device->CreateTexture2D(&td, data ? srd.data() : NULL, - texture.Assign()); + hr = device->device->CreateTexture2D(&td, data ? srd.data() : NULL, texture.Assign()); if (FAILED(hr)) throw HRError("Failed to create 2D texture", hr); if (isGDICompatible) { - hr = texture->QueryInterface(__uuidof(IDXGISurface1), - (void **)gdiSurface.Assign()); + hr = texture->QueryInterface(__uuidof(IDXGISurface1), (void **)gdiSurface.Assign()); if (FAILED(hr)) throw HRError("Failed to create GDI surface", hr); } @@ -147,8 +143,7 @@ void gs_texture_2d::InitTexture(const uint8_t *const *data) texture->SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM); - hr = texture->QueryInterface(__uuidof(IDXGIResource), - (void **)&dxgi_res); + hr = texture->QueryInterface(__uuidof(IDXGIResource), (void **)&dxgi_res); if (FAILED(hr)) { blog(LOG_WARNING, "InitTexture: Failed to query " @@ -159,9 +154,7 @@ void gs_texture_2d::InitTexture(const uint8_t *const *data) if (flags & GS_SHARED_KM_TEX) { ComPtr km; - hr = texture->QueryInterface( - __uuidof(IDXGIKeyedMutex), - (void **)&km); + hr = texture->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **)&km); if (FAILED(hr)) { throw HRError("Failed to query " "IDXGIKeyedMutex", @@ -184,16 +177,13 @@ void gs_texture_2d::InitResourceView() if (type == GS_TEXTURE_CUBE) { viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURECUBE; - viewDesc.TextureCube.MipLevels = genMipmaps || !levels ? -1 - : levels; + viewDesc.TextureCube.MipLevels = genMipmaps || !levels ? -1 : levels; } else { viewDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D; - viewDesc.Texture2D.MipLevels = genMipmaps || !levels ? -1 - : levels; + viewDesc.Texture2D.MipLevels = genMipmaps || !levels ? -1 : levels; } - hr = device->device->CreateShaderResourceView(texture, &viewDesc, - shaderRes.Assign()); + hr = device->device->CreateShaderResourceView(texture, &viewDesc, shaderRes.Assign()); if (FAILED(hr)) throw HRError("Failed to create SRV", hr); @@ -203,8 +193,7 @@ void gs_texture_2d::InitResourceView() if (dxgiFormatView == dxgiFormatViewLinear) { shaderResLinear = shaderRes; } else { - hr = device->device->CreateShaderResourceView( - texture, &viewDescLinear, shaderResLinear.Assign()); + hr = device->device->CreateShaderResourceView(texture, &viewDescLinear, shaderResLinear.Assign()); if (FAILED(hr)) throw HRError("Failed to create linear SRV", hr); } @@ -219,19 +208,16 @@ void gs_texture_2d::InitRenderTargets() rtv.ViewDimension = D3D11_RTV_DIMENSION_TEXTURE2D; rtv.Texture2D.MipSlice = 0; - hr = device->device->CreateRenderTargetView( - texture, &rtv, renderTarget[0].Assign()); + hr = device->device->CreateRenderTargetView(texture, &rtv, renderTarget[0].Assign()); if (FAILED(hr)) throw HRError("Failed to create RTV", hr); if (dxgiFormatView == dxgiFormatViewLinear) { renderTargetLinear[0] = renderTarget[0]; } else { rtv.Format = dxgiFormatViewLinear; - hr = device->device->CreateRenderTargetView( - texture, &rtv, renderTargetLinear[0].Assign()); + hr = device->device->CreateRenderTargetView(texture, &rtv, renderTargetLinear[0].Assign()); if (FAILED(hr)) - throw HRError("Failed to create linear RTV", - hr); + throw HRError("Failed to create linear RTV", hr); } } else { D3D11_RENDER_TARGET_VIEW_DESC rtv; @@ -242,21 +228,17 @@ void gs_texture_2d::InitRenderTargets() for (UINT i = 0; i < 6; i++) { rtv.Texture2DArray.FirstArraySlice = i; - hr = device->device->CreateRenderTargetView( - texture, &rtv, renderTarget[i].Assign()); + hr = device->device->CreateRenderTargetView(texture, &rtv, renderTarget[i].Assign()); if (FAILED(hr)) throw HRError("Failed to create cube RTV", hr); if (dxgiFormatView == dxgiFormatViewLinear) { renderTargetLinear[i] = renderTarget[i]; } else { rtv.Format = dxgiFormatViewLinear; - hr = device->device->CreateRenderTargetView( - texture, &rtv, - renderTargetLinear[i].Assign()); + hr = device->device->CreateRenderTargetView(texture, &rtv, + renderTargetLinear[i].Assign()); if (FAILED(hr)) - throw HRError( - "Failed to create linear cube RTV", - hr); + throw HRError("Failed to create linear cube RTV", hr); } } } @@ -264,10 +246,8 @@ void gs_texture_2d::InitRenderTargets() #define SHARED_FLAGS (GS_SHARED_TEX | GS_SHARED_KM_TEX) -gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t width, - uint32_t height, gs_color_format colorFormat, - uint32_t levels, const uint8_t *const *data, - uint32_t flags_, gs_texture_type type, +gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t width, uint32_t height, gs_color_format colorFormat, + uint32_t levels, const uint8_t *const *data, uint32_t flags_, gs_texture_type type, bool gdiCompatible, bool twoPlane_) : gs_texture(device, gs_type::gs_texture_2d, type, levels, colorFormat), width(width), @@ -291,8 +271,7 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t width, InitRenderTargets(); } -gs_texture_2d::gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12tex, - uint32_t flags_) +gs_texture_2d::gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12tex, uint32_t flags_) : gs_texture(device, gs_type::gs_texture_2d, GS_TEXTURE_2D), isRenderTarget((flags_ & GS_RENDER_TARGET) != 0), isDynamic((flags_ & GS_DYNAMIC) != 0), @@ -304,8 +283,7 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12tex, texture->GetDesc(&td); const bool p010 = td.Format == DXGI_FORMAT_P010; - const DXGI_FORMAT dxgi_format = p010 ? DXGI_FORMAT_R16G16_UNORM - : DXGI_FORMAT_R8G8_UNORM; + const DXGI_FORMAT dxgi_format = p010 ? DXGI_FORMAT_R16G16_UNORM : DXGI_FORMAT_R8G8_UNORM; this->type = GS_TEXTURE_2D; this->format = p010 ? GS_RG16 : GS_R8G8; @@ -324,8 +302,7 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12tex, InitRenderTargets(); } -gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t handle, - bool ntHandle) +gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t handle, bool ntHandle) : gs_texture(device, gs_type::gs_texture_2d, GS_TEXTURE_2D), isShared(true), sharedHandle(handle) @@ -333,13 +310,11 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t handle, HRESULT hr; if (ntHandle) { ComQIPtr dev = device->device; - hr = dev->OpenSharedResource1((HANDLE)(uintptr_t)handle, - __uuidof(ID3D11Texture2D), + hr = dev->OpenSharedResource1((HANDLE)(uintptr_t)handle, __uuidof(ID3D11Texture2D), (void **)texture.Assign()); } else { - hr = device->device->OpenSharedResource( - (HANDLE)(uintptr_t)handle, __uuidof(ID3D11Texture2D), - (void **)texture.Assign()); + hr = device->device->OpenSharedResource((HANDLE)(uintptr_t)handle, __uuidof(ID3D11Texture2D), + (void **)texture.Assign()); } if (FAILED(hr)) diff --git a/libobs-d3d11/d3d11-texture3d.cpp b/libobs-d3d11/d3d11-texture3d.cpp index 31eea0065..f40abbd69 100644 --- a/libobs-d3d11/d3d11-texture3d.cpp +++ b/libobs-d3d11/d3d11-texture3d.cpp @@ -113,8 +113,7 @@ void gs_texture_3d::InitTexture(const uint8_t *const *data) InitSRD(srd); } - hr = device->device->CreateTexture3D(&td, data ? srd.data() : NULL, - texture.Assign()); + hr = device->device->CreateTexture3D(&td, data ? srd.data() : NULL, texture.Assign()); if (FAILED(hr)) throw HRError("Failed to create 3D texture", hr); @@ -123,8 +122,7 @@ void gs_texture_3d::InitTexture(const uint8_t *const *data) texture->SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM); - hr = texture->QueryInterface(__uuidof(IDXGIResource), - (void **)&dxgi_res); + hr = texture->QueryInterface(__uuidof(IDXGIResource), (void **)&dxgi_res); if (FAILED(hr)) { blog(LOG_WARNING, "InitTexture: Failed to query " @@ -135,9 +133,7 @@ void gs_texture_3d::InitTexture(const uint8_t *const *data) if (flags & GS_SHARED_KM_TEX) { ComPtr km; - hr = texture->QueryInterface( - __uuidof(IDXGIKeyedMutex), - (void **)&km); + hr = texture->QueryInterface(__uuidof(IDXGIKeyedMutex), (void **)&km); if (FAILED(hr)) { throw HRError("Failed to query " "IDXGIKeyedMutex", @@ -162,8 +158,7 @@ void gs_texture_3d::InitResourceView() viewDesc.Texture3D.MostDetailedMip = 0; viewDesc.Texture3D.MipLevels = genMipmaps || !levels ? -1 : levels; - hr = device->device->CreateShaderResourceView(texture, &viewDesc, - shaderRes.Assign()); + hr = device->device->CreateShaderResourceView(texture, &viewDesc, shaderRes.Assign()); if (FAILED(hr)) throw HRError("Failed to create 3D SRV", hr); @@ -173,8 +168,7 @@ void gs_texture_3d::InitResourceView() if (dxgiFormatView == dxgiFormatViewLinear) { shaderResLinear = shaderRes; } else { - hr = device->device->CreateShaderResourceView( - texture, &viewDescLinear, shaderResLinear.Assign()); + hr = device->device->CreateShaderResourceView(texture, &viewDescLinear, shaderResLinear.Assign()); if (FAILED(hr)) throw HRError("Failed to create linear 3D SRV", hr); } @@ -182,12 +176,9 @@ void gs_texture_3d::InitResourceView() #define SHARED_FLAGS (GS_SHARED_TEX | GS_SHARED_KM_TEX) -gs_texture_3d::gs_texture_3d(gs_device_t *device, uint32_t width, - uint32_t height, uint32_t depth, - gs_color_format colorFormat, uint32_t levels, - const uint8_t *const *data, uint32_t flags_) - : gs_texture(device, gs_type::gs_texture_3d, GS_TEXTURE_3D, levels, - colorFormat), +gs_texture_3d::gs_texture_3d(gs_device_t *device, uint32_t width, uint32_t height, uint32_t depth, + gs_color_format colorFormat, uint32_t levels, const uint8_t *const *data, uint32_t flags_) + : gs_texture(device, gs_type::gs_texture_3d, GS_TEXTURE_3D, levels, colorFormat), width(width), height(height), depth(depth), @@ -210,8 +201,7 @@ gs_texture_3d::gs_texture_3d(gs_device_t *device, uint32_t handle) sharedHandle(handle) { HRESULT hr; - hr = device->device->OpenSharedResource((HANDLE)(uintptr_t)handle, - IID_PPV_ARGS(texture.Assign())); + hr = device->device->OpenSharedResource((HANDLE)(uintptr_t)handle, IID_PPV_ARGS(texture.Assign())); if (FAILED(hr)) throw HRError("Failed to open shared 3D texture", hr); diff --git a/libobs-d3d11/d3d11-vertexbuffer.cpp b/libobs-d3d11/d3d11-vertexbuffer.cpp index e7879ce7e..ba334a5a5 100644 --- a/libobs-d3d11/d3d11-vertexbuffer.cpp +++ b/libobs-d3d11/d3d11-vertexbuffer.cpp @@ -19,8 +19,7 @@ #include #include "d3d11-subsystem.hpp" -static inline void PushBuffer(UINT *refNumBuffers, ID3D11Buffer **buffers, - uint32_t *strides, ID3D11Buffer *buffer, +static inline void PushBuffer(UINT *refNumBuffers, ID3D11Buffer **buffers, uint32_t *strides, ID3D11Buffer *buffer, size_t elementSize, const char *name) { const UINT numBuffers = *refNumBuffers; @@ -29,41 +28,33 @@ static inline void PushBuffer(UINT *refNumBuffers, ID3D11Buffer **buffers, strides[numBuffers] = (uint32_t)elementSize; *refNumBuffers = numBuffers + 1; } else { - blog(LOG_ERROR, "This vertex shader requires a %s buffer", - name); + blog(LOG_ERROR, "This vertex shader requires a %s buffer", name); } } -void gs_vertex_buffer::FlushBuffer(ID3D11Buffer *buffer, void *array, - size_t elementSize) +void gs_vertex_buffer::FlushBuffer(ID3D11Buffer *buffer, void *array, size_t elementSize) { D3D11_MAPPED_SUBRESOURCE msr; HRESULT hr; - if (FAILED(hr = device->context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, - 0, &msr))) + if (FAILED(hr = device->context->Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &msr))) throw HRError("Failed to map buffer", hr); memcpy(msr.pData, array, elementSize * vbd.data->num); device->context->Unmap(buffer, 0); } -UINT gs_vertex_buffer::MakeBufferList(gs_vertex_shader *shader, - ID3D11Buffer **buffers, uint32_t *strides) +UINT gs_vertex_buffer::MakeBufferList(gs_vertex_shader *shader, ID3D11Buffer **buffers, uint32_t *strides) { UINT numBuffers = 0; - PushBuffer(&numBuffers, buffers, strides, vertexBuffer, sizeof(vec3), - "point"); + PushBuffer(&numBuffers, buffers, strides, vertexBuffer, sizeof(vec3), "point"); if (shader->hasNormals) - PushBuffer(&numBuffers, buffers, strides, normalBuffer, - sizeof(vec3), "normal"); + PushBuffer(&numBuffers, buffers, strides, normalBuffer, sizeof(vec3), "normal"); if (shader->hasColors) - PushBuffer(&numBuffers, buffers, strides, colorBuffer, - sizeof(uint32_t), "color"); + PushBuffer(&numBuffers, buffers, strides, colorBuffer, sizeof(uint32_t), "color"); if (shader->hasTangents) - PushBuffer(&numBuffers, buffers, strides, tangentBuffer, - sizeof(vec3), "tangent"); + PushBuffer(&numBuffers, buffers, strides, tangentBuffer, sizeof(vec3), "tangent"); if (shader->nTexUnits <= uvBuffers.size()) { for (size_t i = 0; i < shader->nTexUnits; i++) { buffers[numBuffers] = uvBuffers[i]; @@ -80,9 +71,7 @@ UINT gs_vertex_buffer::MakeBufferList(gs_vertex_shader *shader, return numBuffers; } -void gs_vertex_buffer::InitBuffer(const size_t elementSize, - const size_t numVerts, void *array, - ID3D11Buffer **buffer) +void gs_vertex_buffer::InitBuffer(const size_t elementSize, const size_t numVerts, void *array, ID3D11Buffer **buffer) { D3D11_BUFFER_DESC bd; D3D11_SUBRESOURCE_DATA srd; @@ -104,20 +93,16 @@ void gs_vertex_buffer::InitBuffer(const size_t elementSize, void gs_vertex_buffer::BuildBuffers() { - InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->points, - &vertexBuffer); + InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->points, &vertexBuffer); if (vbd.data->normals) - InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->normals, - &normalBuffer); + InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->normals, &normalBuffer); if (vbd.data->tangents) - InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->tangents, - &tangentBuffer); + InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->tangents, &tangentBuffer); if (vbd.data->colors) - InitBuffer(sizeof(uint32_t), vbd.data->num, vbd.data->colors, - &colorBuffer); + InitBuffer(sizeof(uint32_t), vbd.data->num, vbd.data->colors, &colorBuffer); for (size_t i = 0; i < vbd.data->num_tex; i++) { struct gs_tvertarray *tverts = vbd.data->tvarray + i; @@ -128,16 +113,14 @@ void gs_vertex_buffer::BuildBuffers() throw "No texture vertices specified"; ComPtr buffer; - InitBuffer(tverts->width * sizeof(float), vbd.data->num, - tverts->array, &buffer); + InitBuffer(tverts->width * sizeof(float), vbd.data->num, tverts->array, &buffer); uvBuffers.push_back(buffer); uvSizes.push_back(tverts->width * sizeof(float)); } } -gs_vertex_buffer::gs_vertex_buffer(gs_device_t *device, struct gs_vb_data *data, - uint32_t flags) +gs_vertex_buffer::gs_vertex_buffer(gs_device_t *device, struct gs_vb_data *data, uint32_t flags) : gs_obj(device, gs_type::gs_vertex_buffer), dynamic((flags & GS_DYNAMIC) != 0), vbd(data), diff --git a/libobs-d3d11/d3d11-zstencilbuffer.cpp b/libobs-d3d11/d3d11-zstencilbuffer.cpp index 7f74e9a42..97cf83668 100644 --- a/libobs-d3d11/d3d11-zstencilbuffer.cpp +++ b/libobs-d3d11/d3d11-zstencilbuffer.cpp @@ -39,15 +39,12 @@ void gs_zstencil_buffer::InitBuffer() dsvd.Format = dxgiFormat; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; - hr = device->device->CreateDepthStencilView(texture, &dsvd, - view.Assign()); + hr = device->device->CreateDepthStencilView(texture, &dsvd, view.Assign()); if (FAILED(hr)) throw HRError("Failed to create depth stencil view", hr); } -gs_zstencil_buffer::gs_zstencil_buffer(gs_device_t *device, uint32_t width, - uint32_t height, - gs_zstencil_format format) +gs_zstencil_buffer::gs_zstencil_buffer(gs_device_t *device, uint32_t width, uint32_t height, gs_zstencil_format format) : gs_obj(device, gs_type::gs_zstencil_buffer), width(width), height(height), diff --git a/libobs-opengl/gl-egl-common.c b/libobs-opengl/gl-egl-common.c index 77618dc58..8854e9d0c 100644 --- a/libobs-opengl/gl-egl-common.c +++ b/libobs-opengl/gl-egl-common.c @@ -46,8 +46,7 @@ typedef unsigned long drm_handle_t; #endif -typedef void(APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)( - GLenum target, GLeglImageOES image); +typedef void(APIENTRYP PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)(GLenum target, GLeglImageOES image); static PFNGLEGLIMAGETARGETTEXTURE2DOESPROC glEGLImageTargetTexture2DOES; static bool find_gl_extension(const char *extension) @@ -76,8 +75,7 @@ static bool init_egl_image_target_texture_2d_ext(void) } glEGLImageTargetTexture2DOES = - (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress( - "glEGLImageTargetTexture2DOES"); + (PFNGLEGLIMAGETARGETTEXTURE2DOESPROC)eglGetProcAddress("glEGLImageTargetTexture2DOES"); } if (!glEGLImageTargetTexture2DOES) @@ -86,12 +84,9 @@ static bool init_egl_image_target_texture_2d_ext(void) return true; } -static EGLImageKHR -create_dmabuf_egl_image(EGLDisplay egl_display, unsigned int width, - unsigned int height, uint32_t drm_format, - uint32_t n_planes, const int *fds, - const uint32_t *strides, const uint32_t *offsets, - const uint64_t *modifiers) +static EGLImageKHR create_dmabuf_egl_image(EGLDisplay egl_display, unsigned int width, unsigned int height, + uint32_t drm_format, uint32_t n_planes, const int *fds, + const uint32_t *strides, const uint32_t *offsets, const uint64_t *modifiers) { EGLAttrib attribs[47]; int atti = 0; @@ -173,20 +168,17 @@ create_dmabuf_egl_image(EGLDisplay egl_display, unsigned int width, attribs[atti++] = EGL_NONE; - return eglCreateImage(egl_display, EGL_NO_CONTEXT, - EGL_LINUX_DMA_BUF_EXT, 0, attribs); + return eglCreateImage(egl_display, EGL_NO_CONTEXT, EGL_LINUX_DMA_BUF_EXT, 0, attribs); } -struct gs_texture *gl_egl_create_texture_from_eglimage( - EGLDisplay egl_display, uint32_t width, uint32_t height, - enum gs_color_format color_format, EGLint target, EGLImage image) +struct gs_texture *gl_egl_create_texture_from_eglimage(EGLDisplay egl_display, uint32_t width, uint32_t height, + enum gs_color_format color_format, EGLint target, EGLImage image) { UNUSED_PARAMETER(egl_display); UNUSED_PARAMETER(target); struct gs_texture *texture = NULL; - texture = gs_texture_create(width, height, color_format, 1, NULL, - GS_GL_DUMMYTEX | GS_RENDER_TARGET); + texture = gs_texture_create(width, height, color_format, 1, NULL, GS_GL_DUMMYTEX | GS_RENDER_TARGET); const GLuint gltex = *(GLuint *)gs_texture_get_obj(texture); gl_bind_texture(GL_TEXTURE_2D, gltex); @@ -204,17 +196,12 @@ struct gs_texture *gl_egl_create_texture_from_eglimage( return texture; } -bool gl_egl_enum_adapters(EGLDisplay display, - bool (*callback)(void *param, const char *name, - uint32_t id), - void *param) +bool gl_egl_enum_adapters(EGLDisplay display, bool (*callback)(void *param, const char *name, uint32_t id), void *param) { EGLDeviceEXT display_dev; - if (eglQueryDisplayAttribEXT(display, EGL_DEVICE_EXT, - (EGLAttrib *)&display_dev) && + if (eglQueryDisplayAttribEXT(display, EGL_DEVICE_EXT, (EGLAttrib *)&display_dev) && eglGetError() == EGL_SUCCESS) { - const char *display_node = eglQueryDeviceStringEXT( - display_dev, EGL_DRM_RENDER_NODE_FILE_EXT); + const char *display_node = eglQueryDeviceStringEXT(display_dev, EGL_DRM_RENDER_NODE_FILE_EXT); if (eglGetError() != EGL_SUCCESS || display_node == NULL) { display_node = "/Software"; } @@ -231,8 +218,7 @@ bool gl_egl_enum_adapters(EGLDisplay display, } for (int i = 0; i < num_devices; i++) { - const char *node = eglQueryDeviceStringEXT( - devices[i], EGL_DRM_RENDER_NODE_FILE_EXT); + const char *node = eglQueryDeviceStringEXT(devices[i], EGL_DRM_RENDER_NODE_FILE_EXT); if (node == NULL || eglGetError() != EGL_SUCCESS) { // Do not enumerate additional software renderers. continue; @@ -251,12 +237,10 @@ uint32_t gs_get_adapter_count() return 1 + num_devices; // Display + devices. } -struct gs_texture * -gl_egl_create_dmabuf_image(EGLDisplay egl_display, unsigned int width, - unsigned int height, uint32_t drm_format, - enum gs_color_format color_format, uint32_t n_planes, - const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers) +struct gs_texture *gl_egl_create_dmabuf_image(EGLDisplay egl_display, unsigned int width, unsigned int height, + uint32_t drm_format, enum gs_color_format color_format, uint32_t n_planes, + const int *fds, const uint32_t *strides, const uint32_t *offsets, + const uint64_t *modifiers) { struct gs_texture *texture = NULL; EGLImage egl_image; @@ -264,29 +248,24 @@ gl_egl_create_dmabuf_image(EGLDisplay egl_display, unsigned int width, if (!init_egl_image_target_texture_2d_ext()) return NULL; - egl_image = create_dmabuf_egl_image(egl_display, width, height, - drm_format, n_planes, fds, strides, - offsets, modifiers); + egl_image = create_dmabuf_egl_image(egl_display, width, height, drm_format, n_planes, fds, strides, offsets, + modifiers); if (egl_image == EGL_NO_IMAGE) { - blog(LOG_ERROR, "Cannot create EGLImage: %s", - gl_egl_error_to_string(eglGetError())); + blog(LOG_ERROR, "Cannot create EGLImage: %s", gl_egl_error_to_string(eglGetError())); return NULL; } - texture = gl_egl_create_texture_from_eglimage(egl_display, width, - height, color_format, - GL_TEXTURE_2D, egl_image); + texture = + gl_egl_create_texture_from_eglimage(egl_display, width, height, color_format, GL_TEXTURE_2D, egl_image); if (texture) eglDestroyImage(egl_display, egl_image); return texture; } -struct gs_texture * -gl_egl_create_texture_from_pixmap(EGLDisplay egl_display, uint32_t width, - uint32_t height, - enum gs_color_format color_format, - EGLint target, EGLClientBuffer pixmap) +struct gs_texture *gl_egl_create_texture_from_pixmap(EGLDisplay egl_display, uint32_t width, uint32_t height, + enum gs_color_format color_format, EGLint target, + EGLClientBuffer pixmap) { if (!init_egl_image_target_texture_2d_ext()) return NULL; @@ -297,17 +276,14 @@ gl_egl_create_texture_from_pixmap(EGLDisplay egl_display, uint32_t width, EGL_NONE, }; - EGLImage image = eglCreateImage(egl_display, EGL_NO_CONTEXT, - EGL_NATIVE_PIXMAP_KHR, pixmap, - pixmap_attrs); + EGLImage image = eglCreateImage(egl_display, EGL_NO_CONTEXT, EGL_NATIVE_PIXMAP_KHR, pixmap, pixmap_attrs); if (image == EGL_NO_IMAGE) { - blog(LOG_DEBUG, "Cannot create EGLImage: %s", - gl_egl_error_to_string(eglGetError())); + blog(LOG_DEBUG, "Cannot create EGLImage: %s", gl_egl_error_to_string(eglGetError())); return NULL; } - struct gs_texture *texture = gl_egl_create_texture_from_eglimage( - egl_display, width, height, color_format, target, image); + struct gs_texture *texture = + gl_egl_create_texture_from_eglimage(egl_display, width, height, color_format, target, image); eglDestroyImage(egl_display, image); return texture; @@ -318,16 +294,13 @@ static inline bool is_implicit_dmabuf_modifiers_supported(void) return EGL_EXT_image_dma_buf_import > 0; } -static inline bool query_dmabuf_formats(EGLDisplay egl_display, - EGLint **formats, EGLint *num_formats) +static inline bool query_dmabuf_formats(EGLDisplay egl_display, EGLint **formats, EGLint *num_formats) { EGLint max_formats = 0; EGLint *format_list = NULL; - if (!glad_eglQueryDmaBufFormatsEXT(egl_display, 0, NULL, - &max_formats)) { - blog(LOG_ERROR, "Cannot query the number of formats: %s", - gl_egl_error_to_string(eglGetError())); + if (!glad_eglQueryDmaBufFormatsEXT(egl_display, 0, NULL, &max_formats)) { + blog(LOG_ERROR, "Cannot query the number of formats: %s", gl_egl_error_to_string(eglGetError())); return false; } @@ -337,10 +310,8 @@ static inline bool query_dmabuf_formats(EGLDisplay egl_display, return false; } - if (!glad_eglQueryDmaBufFormatsEXT(egl_display, max_formats, - format_list, &max_formats)) { - blog(LOG_ERROR, "Cannot query a list of formats: %s", - gl_egl_error_to_string(eglGetError())); + if (!glad_eglQueryDmaBufFormatsEXT(egl_display, max_formats, format_list, &max_formats)) { + blog(LOG_ERROR, "Cannot query a list of formats: %s", gl_egl_error_to_string(eglGetError())); bfree(format_list); return false; } @@ -350,9 +321,8 @@ static inline bool query_dmabuf_formats(EGLDisplay egl_display, return true; } -bool gl_egl_query_dmabuf_capabilities(EGLDisplay egl_display, - enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **formats, size_t *n_formats) +bool gl_egl_query_dmabuf_capabilities(EGLDisplay egl_display, enum gs_dmabuf_flags *dmabuf_flags, uint32_t **formats, + size_t *n_formats) { bool ret = false; @@ -366,41 +336,33 @@ bool gl_egl_query_dmabuf_capabilities(EGLDisplay egl_display, return ret; } - if (!query_dmabuf_formats(egl_display, (EGLint **)formats, - (EGLint *)n_formats)) { + if (!query_dmabuf_formats(egl_display, (EGLint **)formats, (EGLint *)n_formats)) { *n_formats = 0; *formats = NULL; } return ret; } -static inline bool query_dmabuf_modifiers(EGLDisplay egl_display, - EGLint drm_format, - EGLuint64KHR **modifiers, +static inline bool query_dmabuf_modifiers(EGLDisplay egl_display, EGLint drm_format, EGLuint64KHR **modifiers, EGLuint64KHR *n_modifiers) { EGLint max_modifiers; - if (!glad_eglQueryDmaBufModifiersEXT(egl_display, drm_format, 0, NULL, - NULL, &max_modifiers)) { - blog(LOG_ERROR, "Cannot query the number of modifiers: %s", - gl_egl_error_to_string(eglGetError())); + if (!glad_eglQueryDmaBufModifiersEXT(egl_display, drm_format, 0, NULL, NULL, &max_modifiers)) { + blog(LOG_ERROR, "Cannot query the number of modifiers: %s", gl_egl_error_to_string(eglGetError())); return false; } - EGLuint64KHR *modifier_list = - bzalloc(max_modifiers * sizeof(EGLuint64KHR)); + EGLuint64KHR *modifier_list = bzalloc(max_modifiers * sizeof(EGLuint64KHR)); EGLBoolean *external_only = NULL; if (!modifier_list) { blog(LOG_ERROR, "Unable to allocate memory"); return false; } - if (!glad_eglQueryDmaBufModifiersEXT(egl_display, drm_format, - max_modifiers, modifier_list, - external_only, &max_modifiers)) { - blog(LOG_ERROR, "Cannot query a list of modifiers: %s", - gl_egl_error_to_string(eglGetError())); + if (!glad_eglQueryDmaBufModifiersEXT(egl_display, drm_format, max_modifiers, modifier_list, external_only, + &max_modifiers)) { + blog(LOG_ERROR, "Cannot query a list of modifiers: %s", gl_egl_error_to_string(eglGetError())); bfree(modifier_list); return false; } @@ -410,17 +372,14 @@ static inline bool query_dmabuf_modifiers(EGLDisplay egl_display, return true; } -bool gl_egl_query_dmabuf_modifiers_for_format(EGLDisplay egl_display, - uint32_t drm_format, - uint64_t **modifiers, +bool gl_egl_query_dmabuf_modifiers_for_format(EGLDisplay egl_display, uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers) { if (!glad_eglQueryDmaBufModifiersEXT) { blog(LOG_ERROR, "Unable to load eglQueryDmaBufModifiersEXT"); return false; } - if (!query_dmabuf_modifiers(egl_display, drm_format, modifiers, - n_modifiers)) { + if (!query_dmabuf_modifiers(egl_display, drm_format, modifiers, n_modifiers)) { *n_modifiers = 0; *modifiers = NULL; return false; diff --git a/libobs-opengl/gl-egl-common.h b/libobs-opengl/gl-egl-common.h index 8cc9648f0..657e6c3a7 100644 --- a/libobs-opengl/gl-egl-common.h +++ b/libobs-opengl/gl-egl-common.h @@ -6,30 +6,21 @@ const char *gl_egl_error_to_string(EGLint error_number); -struct gs_texture * -gl_egl_create_dmabuf_image(EGLDisplay egl_display, unsigned int width, - unsigned int height, uint32_t drm_format, - enum gs_color_format color_format, uint32_t n_planes, - const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers); +struct gs_texture *gl_egl_create_dmabuf_image(EGLDisplay egl_display, unsigned int width, unsigned int height, + uint32_t drm_format, enum gs_color_format color_format, uint32_t n_planes, + const int *fds, const uint32_t *strides, const uint32_t *offsets, + const uint64_t *modifiers); -bool gl_egl_query_dmabuf_capabilities(EGLDisplay egl_display, - enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_format, size_t *n_formats); +bool gl_egl_query_dmabuf_capabilities(EGLDisplay egl_display, enum gs_dmabuf_flags *dmabuf_flags, uint32_t **drm_format, + size_t *n_formats); -bool gl_egl_query_dmabuf_modifiers_for_format(EGLDisplay egl_display, - uint32_t drm_format, - uint64_t **modifiers, +bool gl_egl_query_dmabuf_modifiers_for_format(EGLDisplay egl_display, uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers); -struct gs_texture * -gl_egl_create_texture_from_pixmap(EGLDisplay egl_display, uint32_t width, - uint32_t height, - enum gs_color_format color_format, - EGLint target, EGLClientBuffer pixmap); +struct gs_texture *gl_egl_create_texture_from_pixmap(EGLDisplay egl_display, uint32_t width, uint32_t height, + enum gs_color_format color_format, EGLint target, + EGLClientBuffer pixmap); -bool gl_egl_enum_adapters(EGLDisplay display, - bool (*callback)(void *param, const char *name, - uint32_t id), +bool gl_egl_enum_adapters(EGLDisplay display, bool (*callback)(void *param, const char *name, uint32_t id), void *param); uint32_t gs_get_adapter_count(); diff --git a/libobs-opengl/gl-helpers.c b/libobs-opengl/gl-helpers.c index 0e69c1e4c..86ea4bd19 100644 --- a/libobs-opengl/gl-helpers.c +++ b/libobs-opengl/gl-helpers.c @@ -17,10 +17,8 @@ #include "gl-subsystem.h" -bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels, - GLenum format, GLint internal_format, bool compressed, - uint32_t width, uint32_t height, uint32_t size, - const uint8_t ***p_data) +bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels, GLenum format, GLint internal_format, + bool compressed, uint32_t width, uint32_t height, uint32_t size, const uint8_t ***p_data) { bool success = true; const uint8_t **data = p_data ? *p_data : NULL; @@ -28,15 +26,12 @@ bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels, for (i = 0; i < num_levels; i++) { if (compressed) { - glCompressedTexImage2D(target, i, internal_format, - width, height, 0, size, - data ? *data : NULL); + glCompressedTexImage2D(target, i, internal_format, width, height, 0, size, data ? *data : NULL); if (!gl_success("glCompressedTexImage2D")) success = false; } else { - glTexImage2D(target, i, internal_format, width, height, - 0, format, type, data ? *data : NULL); + glTexImage2D(target, i, internal_format, width, height, 0, format, type, data ? *data : NULL); if (!gl_success("glTexImage2D")) success = false; } @@ -56,9 +51,8 @@ bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels, return success; } -static bool gl_copy_fbo(struct gs_texture *dst, uint32_t dst_x, uint32_t dst_y, - struct gs_texture *src, uint32_t src_x, uint32_t src_y, - uint32_t width, uint32_t height) +static bool gl_copy_fbo(struct gs_texture *dst, uint32_t dst_x, uint32_t dst_y, struct gs_texture *src, uint32_t src_x, + uint32_t src_y, uint32_t width, uint32_t height) { struct fbo_info *fbo = get_fbo(src, width, height); GLint last_fbo; @@ -74,8 +68,7 @@ static bool gl_copy_fbo(struct gs_texture *dst, uint32_t dst_x, uint32_t dst_y, if (!gl_bind_texture(dst->gl_target, dst->texture)) goto fail; - glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0, - src->gl_target, src->texture, 0); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0, src->gl_target, src->texture, 0); if (!gl_success("glFrameBufferTexture2D")) goto fail; @@ -83,8 +76,7 @@ static bool gl_copy_fbo(struct gs_texture *dst, uint32_t dst_x, uint32_t dst_y, if (!gl_success("glReadBuffer")) goto fail; - glCopyTexSubImage2D(dst->gl_target, 0, dst_x, dst_y, src_x, src_y, - width, height); + glCopyTexSubImage2D(dst->gl_target, 0, dst_x, dst_y, src_x, src_y, width, height); if (!gl_success("glCopyTexSubImage2D")) goto fail; @@ -99,28 +91,23 @@ fail: return success; } -bool gl_copy_texture(struct gs_device *device, struct gs_texture *dst, - uint32_t dst_x, uint32_t dst_y, struct gs_texture *src, - uint32_t src_x, uint32_t src_y, uint32_t width, - uint32_t height) +bool gl_copy_texture(struct gs_device *device, struct gs_texture *dst, uint32_t dst_x, uint32_t dst_y, + struct gs_texture *src, uint32_t src_x, uint32_t src_y, uint32_t width, uint32_t height) { bool success = false; if (device->copy_type == COPY_TYPE_ARB) { - glCopyImageSubData(src->texture, src->gl_target, 0, src_x, - src_y, 0, dst->texture, dst->gl_target, 0, + glCopyImageSubData(src->texture, src->gl_target, 0, src_x, src_y, 0, dst->texture, dst->gl_target, 0, dst_x, dst_y, 0, width, height, 1); success = gl_success("glCopyImageSubData"); } else if (device->copy_type == COPY_TYPE_NV) { - glCopyImageSubDataNV(src->texture, src->gl_target, 0, src_x, - src_y, 0, dst->texture, dst->gl_target, 0, + glCopyImageSubDataNV(src->texture, src->gl_target, 0, src_x, src_y, 0, dst->texture, dst->gl_target, 0, dst_x, dst_y, 0, width, height, 1); success = gl_success("glCopyImageSubDataNV"); } else if (device->copy_type == COPY_TYPE_FBO_BLIT) { - success = gl_copy_fbo(dst, dst_x, dst_y, src, src_x, src_y, - width, height); + success = gl_copy_fbo(dst, dst_x, dst_y, src, src_x, src_y, width, height); if (!success) blog(LOG_ERROR, "gl_copy_texture failed"); } @@ -128,8 +115,7 @@ bool gl_copy_texture(struct gs_device *device, struct gs_texture *dst, return success; } -bool gl_create_buffer(GLenum target, GLuint *buffer, GLsizeiptr size, - const GLvoid *data, GLenum usage) +bool gl_create_buffer(GLenum target, GLuint *buffer, GLsizeiptr size, const GLvoid *data, GLenum usage) { bool success; if (!gl_gen_buffers(1, buffer)) @@ -154,8 +140,7 @@ bool update_buffer(GLenum target, GLuint buffer, const void *data, size_t size) /* glMapBufferRange with these flags will actually give far better * performance than a plain glMapBuffer call */ - ptr = glMapBufferRange(target, 0, size, - GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); + ptr = glMapBufferRange(target, 0, size, GL_MAP_WRITE_BIT | GL_MAP_INVALIDATE_BUFFER_BIT); success = gl_success("glMapBufferRange"); if (success && ptr) { memcpy(ptr, data, size); diff --git a/libobs-opengl/gl-helpers.h b/libobs-opengl/gl-helpers.h index 98b8c5061..be9636886 100644 --- a/libobs-opengl/gl-helpers.h +++ b/libobs-opengl/gl-helpers.h @@ -71,15 +71,13 @@ static inline bool gl_success(const char *funcname) if (errorcode != GL_NO_ERROR) { int attempts = 8; do { - blog(LOG_ERROR, - "%s failed, glGetError returned %s(0x%X)", - funcname, gl_error_to_str(errorcode), errorcode); + blog(LOG_ERROR, "%s failed, glGetError returned %s(0x%X)", funcname, gl_error_to_str(errorcode), + errorcode); errorcode = glGetError(); --attempts; if (attempts == 0) { - blog(LOG_ERROR, - "Too many GL errors, moving on"); + blog(LOG_ERROR, "Too many GL errors, moving on"); break; } } while (errorcode != GL_NO_ERROR); @@ -215,18 +213,12 @@ static inline bool gl_get_integer_v(GLenum pname, GLint *params) return gl_success("glGetIntegerv"); } -extern bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels, - GLenum format, GLint internal_format, bool compressed, - uint32_t width, uint32_t height, uint32_t size, - const uint8_t ***p_data); +extern bool gl_init_face(GLenum target, GLenum type, uint32_t num_levels, GLenum format, GLint internal_format, + bool compressed, uint32_t width, uint32_t height, uint32_t size, const uint8_t ***p_data); -extern bool gl_copy_texture(struct gs_device *device, struct gs_texture *dst, - uint32_t dst_x, uint32_t dst_y, - struct gs_texture *src, uint32_t src_x, - uint32_t src_y, uint32_t width, uint32_t height); +extern bool gl_copy_texture(struct gs_device *device, struct gs_texture *dst, uint32_t dst_x, uint32_t dst_y, + struct gs_texture *src, uint32_t src_x, uint32_t src_y, uint32_t width, uint32_t height); -extern bool gl_create_buffer(GLenum target, GLuint *buffer, GLsizeiptr size, - const GLvoid *data, GLenum usage); +extern bool gl_create_buffer(GLenum target, GLuint *buffer, GLsizeiptr size, const GLvoid *data, GLenum usage); -extern bool update_buffer(GLenum target, GLuint buffer, const void *data, - size_t size); +extern bool update_buffer(GLenum target, GLuint buffer, const void *data, size_t size); diff --git a/libobs-opengl/gl-indexbuffer.c b/libobs-opengl/gl-indexbuffer.c index f3248ebbf..5a9e8c83d 100644 --- a/libobs-opengl/gl-indexbuffer.c +++ b/libobs-opengl/gl-indexbuffer.c @@ -22,8 +22,7 @@ static inline bool init_ib(struct gs_index_buffer *ib) GLenum usage = ib->dynamic ? GL_DYNAMIC_DRAW : GL_STATIC_DRAW; bool success; - success = gl_create_buffer(GL_ELEMENT_ARRAY_BUFFER, &ib->buffer, - ib->size, ib->data, usage); + success = gl_create_buffer(GL_ELEMENT_ARRAY_BUFFER, &ib->buffer, ib->size, ib->data, usage); if (!ib->dynamic) { bfree(ib->data); @@ -33,9 +32,7 @@ static inline bool init_ib(struct gs_index_buffer *ib) return success; } -gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, - enum gs_index_type type, - void *indices, size_t num, +gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, enum gs_index_type type, void *indices, size_t num, uint32_t flags) { struct gs_index_buffer *ib = bzalloc(sizeof(struct gs_index_buffer)); @@ -48,8 +45,7 @@ gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, ib->width = width; ib->size = width * num; ib->type = type; - ib->gl_type = type == GS_UNSIGNED_LONG ? GL_UNSIGNED_INT - : GL_UNSIGNED_SHORT; + ib->gl_type = type == GS_UNSIGNED_LONG ? GL_UNSIGNED_INT : GL_UNSIGNED_SHORT; if (!init_ib(ib)) { blog(LOG_ERROR, "device_indexbuffer_create (GL) failed"); @@ -71,8 +67,7 @@ void gs_indexbuffer_destroy(gs_indexbuffer_t *ib) } } -static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *ib, - const void *data) +static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *ib, const void *data) { if (!ib->dynamic) { blog(LOG_ERROR, "Index buffer is not dynamic"); diff --git a/libobs-opengl/gl-nix.c b/libobs-opengl/gl-nix.c index 12bb43dc8..d93638b70 100644 --- a/libobs-opengl/gl-nix.c +++ b/libobs-opengl/gl-nix.c @@ -43,8 +43,7 @@ static void init_winsys(void) assert(gl_vtable != NULL); } -extern struct gl_windowinfo * -gl_windowinfo_create(const struct gs_init_data *info) +extern struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info) { return gl_vtable->windowinfo_create(info); } @@ -54,8 +53,7 @@ extern void gl_windowinfo_destroy(struct gl_windowinfo *info) gl_vtable->windowinfo_destroy(info); } -extern struct gl_platform *gl_platform_create(gs_device_t *device, - uint32_t adapter) +extern struct gl_platform *gl_platform_create(gs_device_t *device, uint32_t adapter) { init_winsys(); @@ -95,9 +93,7 @@ extern void device_leave_context(gs_device_t *device) gl_vtable->device_leave_context(device); } -extern bool device_enum_adapters(gs_device_t *device, - bool (*callback)(void *param, const char *name, - uint32_t id), +extern bool device_enum_adapters(gs_device_t *device, bool (*callback)(void *param, const char *name, uint32_t id), void *param) { return gl_vtable->device_enum_adapters(device, callback, param); @@ -108,8 +104,7 @@ extern void *device_get_device_obj(gs_device_t *device) return gl_vtable->device_get_device_obj(device); } -extern void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, - uint32_t *height) +extern void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, uint32_t *height) { gl_vtable->getclientsize(swap, width, height); } @@ -148,39 +143,30 @@ extern bool device_is_monitor_hdr(gs_device_t *device, void *monitor) return false; } -extern struct gs_texture *device_texture_create_from_dmabuf( - gs_device_t *device, unsigned int width, unsigned int height, - uint32_t drm_format, enum gs_color_format color_format, - uint32_t n_planes, const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers) +extern struct gs_texture *device_texture_create_from_dmabuf(gs_device_t *device, unsigned int width, + unsigned int height, uint32_t drm_format, + enum gs_color_format color_format, uint32_t n_planes, + const int *fds, const uint32_t *strides, + const uint32_t *offsets, const uint64_t *modifiers) { - return gl_vtable->device_texture_create_from_dmabuf( - device, width, height, drm_format, color_format, n_planes, fds, - strides, offsets, modifiers); + return gl_vtable->device_texture_create_from_dmabuf(device, width, height, drm_format, color_format, n_planes, + fds, strides, offsets, modifiers); } -extern bool device_query_dmabuf_capabilities(gs_device_t *device, - enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, - size_t *n_formats) +extern bool device_query_dmabuf_capabilities(gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, + uint32_t **drm_formats, size_t *n_formats) { - return gl_vtable->device_query_dmabuf_capabilities( - device, dmabuf_flags, drm_formats, n_formats); + return gl_vtable->device_query_dmabuf_capabilities(device, dmabuf_flags, drm_formats, n_formats); } -extern bool device_query_dmabuf_modifiers_for_format(gs_device_t *device, - uint32_t drm_format, - uint64_t **modifiers, +extern bool device_query_dmabuf_modifiers_for_format(gs_device_t *device, uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers) { - return gl_vtable->device_query_dmabuf_modifiers_for_format( - device, drm_format, modifiers, n_modifiers); + return gl_vtable->device_query_dmabuf_modifiers_for_format(device, drm_format, modifiers, n_modifiers); } -struct gs_texture *device_texture_create_from_pixmap( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t target, void *pixmap) +struct gs_texture *device_texture_create_from_pixmap(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t target, void *pixmap) { - return gl_vtable->device_texture_create_from_pixmap( - device, width, height, color_format, target, pixmap); + return gl_vtable->device_texture_create_from_pixmap(device, width, height, color_format, target, pixmap); } diff --git a/libobs-opengl/gl-nix.h b/libobs-opengl/gl-nix.h index f0c4d2007..5b7e77bf5 100644 --- a/libobs-opengl/gl-nix.h +++ b/libobs-opengl/gl-nix.h @@ -23,12 +23,10 @@ #include "gl-subsystem.h" struct gl_winsys_vtable { - struct gl_windowinfo *(*windowinfo_create)( - const struct gs_init_data *info); + struct gl_windowinfo *(*windowinfo_create)(const struct gs_init_data *info); void (*windowinfo_destroy)(struct gl_windowinfo *info); - struct gl_platform *(*platform_create)(gs_device_t *device, - uint32_t adapter); + struct gl_platform *(*platform_create)(gs_device_t *device, uint32_t adapter); void (*platform_destroy)(struct gl_platform *plat); @@ -42,40 +40,31 @@ struct gl_winsys_vtable { void *(*device_get_device_obj)(gs_device_t *device); - void (*getclientsize)(const struct gs_swap_chain *swap, uint32_t *width, - uint32_t *height); + void (*getclientsize)(const struct gs_swap_chain *swap, uint32_t *width, uint32_t *height); void (*clear_context)(gs_device_t *device); void (*update)(gs_device_t *device); - void (*device_load_swapchain)(gs_device_t *device, - gs_swapchain_t *swap); + void (*device_load_swapchain)(gs_device_t *device, gs_swapchain_t *swap); void (*device_present)(gs_device_t *device); - struct gs_texture *(*device_texture_create_from_dmabuf)( - gs_device_t *device, unsigned int width, unsigned int height, - uint32_t drm_format, enum gs_color_format color_format, - uint32_t n_planes, const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers); + struct gs_texture *(*device_texture_create_from_dmabuf)(gs_device_t *device, unsigned int width, + unsigned int height, uint32_t drm_format, + enum gs_color_format color_format, uint32_t n_planes, + const int *fds, const uint32_t *strides, + const uint32_t *offsets, const uint64_t *modifiers); - bool (*device_query_dmabuf_capabilities)( - gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, size_t *n_formats); + bool (*device_query_dmabuf_capabilities)(gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, + uint32_t **drm_formats, size_t *n_formats); - bool (*device_query_dmabuf_modifiers_for_format)(gs_device_t *device, - uint32_t drm_format, - uint64_t **modifiers, + bool (*device_query_dmabuf_modifiers_for_format)(gs_device_t *device, uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers); - struct gs_texture *(*device_texture_create_from_pixmap)( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t target, - void *pixmap); - bool (*device_enum_adapters)(gs_device_t *device, - bool (*callback)(void *param, - const char *name, - uint32_t id), + struct gs_texture *(*device_texture_create_from_pixmap)(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t target, + void *pixmap); + bool (*device_enum_adapters)(gs_device_t *device, bool (*callback)(void *param, const char *name, uint32_t id), void *param); }; diff --git a/libobs-opengl/gl-shader.c b/libobs-opengl/gl-shader.c index 5da8a1eda..f3ece6701 100644 --- a/libobs-opengl/gl-shader.c +++ b/libobs-opengl/gl-shader.c @@ -37,8 +37,7 @@ static inline void shader_attrib_free(struct shader_attrib *attrib) bfree(attrib->name); } -static void gl_get_shader_info(GLuint shader, const char *file, - char **error_string) +static void gl_get_shader_info(GLuint shader, const char *file, char **error_string) { char *errors; GLint info_len = 0; @@ -60,8 +59,7 @@ static void gl_get_shader_info(GLuint shader, const char *file, bfree(errors); } -static bool gl_add_param(struct gs_shader *shader, struct shader_var *var, - GLint *texture_id) +static bool gl_add_param(struct gs_shader *shader, struct shader_var *var, GLint *texture_id) { struct gs_shader_param param = {0}; @@ -84,15 +82,13 @@ static bool gl_add_param(struct gs_shader *shader, struct shader_var *var, return true; } -static inline bool gl_add_params(struct gs_shader *shader, - struct gl_shader_parser *glsp) +static inline bool gl_add_params(struct gs_shader *shader, struct gl_shader_parser *glsp) { size_t i; GLint tex_id = 0; for (i = 0; i < glsp->parser.params.num; i++) - if (!gl_add_param(shader, glsp->parser.params.array + i, - &tex_id)) + if (!gl_add_param(shader, glsp->parser.params.array + i, &tex_id)) return false; shader->viewproj = gs_shader_get_param_by_name(shader, "ViewProj"); @@ -101,8 +97,7 @@ static inline bool gl_add_params(struct gs_shader *shader, return true; } -static inline void gl_add_sampler(struct gs_shader *shader, - struct shader_sampler *sampler) +static inline void gl_add_sampler(struct gs_shader *shader, struct shader_sampler *sampler) { gs_samplerstate_t *new_sampler; struct gs_sampler_info info; @@ -113,19 +108,16 @@ static inline void gl_add_sampler(struct gs_shader *shader, da_push_back(shader->samplers, &new_sampler); } -static inline void gl_add_samplers(struct gs_shader *shader, - struct gl_shader_parser *glsp) +static inline void gl_add_samplers(struct gs_shader *shader, struct gl_shader_parser *glsp) { size_t i; for (i = 0; i < glsp->parser.samplers.num; i++) { - struct shader_sampler *sampler = - glsp->parser.samplers.array + i; + struct shader_sampler *sampler = glsp->parser.samplers.array + i; gl_add_sampler(shader, sampler); } } -static void get_attrib_type(const char *mapping, enum attrib_type *type, - size_t *index) +static void get_attrib_type(const char *mapping, enum attrib_type *type, size_t *index) { if (strcmp(mapping, "POSITION") == 0) { *type = ATTRIB_POSITION; @@ -151,8 +143,7 @@ static void get_attrib_type(const char *mapping, enum attrib_type *type, *index = 0; } -static inline bool gl_process_attrib(struct gs_shader *program, - struct gl_parser_attrib *pa) +static inline bool gl_process_attrib(struct gs_shader *program, struct gl_parser_attrib *pa) { struct shader_attrib attrib = {0}; @@ -171,8 +162,7 @@ static inline bool gl_process_attrib(struct gs_shader *program, return true; } -static inline bool gl_process_attribs(struct gs_shader *shader, - struct gl_shader_parser *glsp) +static inline bool gl_process_attribs(struct gs_shader *shader, struct gl_shader_parser *glsp) { size_t i; for (i = 0; i < glsp->attribs.num; i++) { @@ -184,8 +174,7 @@ static inline bool gl_process_attribs(struct gs_shader *shader, return true; } -static bool gl_shader_init(struct gs_shader *shader, - struct gl_shader_parser *glsp, const char *file, +static bool gl_shader_init(struct gs_shader *shader, struct gl_shader_parser *glsp, const char *file, char **error_string) { GLenum type = convert_shader_type(shader->type); @@ -196,8 +185,7 @@ static bool gl_shader_init(struct gs_shader *shader, if (!gl_success("glCreateShader") || !shader->obj) return false; - glShaderSource(shader->obj, 1, (const GLchar **)&glsp->gl_string.array, - 0); + glShaderSource(shader->obj, 1, (const GLchar **)&glsp->gl_string.array, 0); if (!gl_success("glShaderSource")) return false; @@ -225,10 +213,8 @@ static bool gl_shader_init(struct gs_shader *shader, if (infoLog) { GLsizei returnedLength = 0; - glGetShaderInfoLog(shader->obj, infoLength, - &returnedLength, infoLog); - blog(LOG_ERROR, "Error compiling shader:\n%s\n", - infoLog); + glGetShaderInfoLog(shader->obj, infoLength, &returnedLength, infoLog); + blog(LOG_ERROR, "Error compiling shader:\n%s\n", infoLog); free(infoLog); } @@ -249,10 +235,8 @@ static bool gl_shader_init(struct gs_shader *shader, return success; } -static struct gs_shader *shader_create(gs_device_t *device, - enum gs_shader_type type, - const char *shader_str, const char *file, - char **error_string) +static struct gs_shader *shader_create(gs_device_t *device, enum gs_shader_type type, const char *shader_str, + const char *file, char **error_string) { struct gs_shader *shader = bzalloc(sizeof(struct gs_shader)); struct gl_shader_parser glsp; @@ -276,23 +260,19 @@ static struct gs_shader *shader_create(gs_device_t *device, return shader; } -gs_shader_t *device_vertexshader_create(gs_device_t *device, const char *shader, - const char *file, char **error_string) +gs_shader_t *device_vertexshader_create(gs_device_t *device, const char *shader, const char *file, char **error_string) { struct gs_shader *ptr; - ptr = shader_create(device, GS_SHADER_VERTEX, shader, file, - error_string); + ptr = shader_create(device, GS_SHADER_VERTEX, shader, file, error_string); if (!ptr) blog(LOG_ERROR, "device_vertexshader_create (GL) failed"); return ptr; } -gs_shader_t *device_pixelshader_create(gs_device_t *device, const char *shader, - const char *file, char **error_string) +gs_shader_t *device_pixelshader_create(gs_device_t *device, const char *shader, const char *file, char **error_string) { struct gs_shader *ptr; - ptr = shader_create(device, GS_SHADER_PIXEL, shader, file, - error_string); + ptr = shader_create(device, GS_SHADER_PIXEL, shader, file, error_string); if (!ptr) blog(LOG_ERROR, "device_pixelshader_create (GL) failed"); return ptr; @@ -306,12 +286,10 @@ static void remove_program_references(struct gs_shader *shader) struct gs_program *next = program->next; bool destroy = false; - if (shader->type == GS_SHADER_VERTEX && - program->vertex_shader == shader) + if (shader->type == GS_SHADER_VERTEX && program->vertex_shader == shader) destroy = true; - else if (shader->type == GS_SHADER_PIXEL && - program->pixel_shader == shader) + else if (shader->type == GS_SHADER_PIXEL && program->pixel_shader == shader) destroy = true; if (destroy) @@ -384,8 +362,7 @@ gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader) return shader->world; } -void gs_shader_get_param_info(const gs_sparam_t *param, - struct gs_shader_param_info *info) +void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_info *info) { info->type = param->type; info->name = param->name; @@ -440,28 +417,24 @@ void gs_shader_set_texture(gs_sparam_t *param, gs_texture_t *val) param->texture = val; } -static inline bool validate_param(struct program_param *pp, - size_t expected_size) +static inline bool validate_param(struct program_param *pp, size_t expected_size) { if (pp->param->cur_value.num != expected_size) { blog(LOG_ERROR, "Parameter '%s' set to invalid size %u, " "expected %u", - pp->param->name, (unsigned int)pp->param->cur_value.num, - (unsigned int)expected_size); + pp->param->name, (unsigned int)pp->param->cur_value.num, (unsigned int)expected_size); return false; } return true; } -static void program_set_param_data(struct gs_program *program, - struct program_param *pp) +static void program_set_param_data(struct gs_program *program, struct program_param *pp) { void *array = pp->param->cur_value.array; - if (pp->param->type == GS_SHADER_PARAM_BOOL || - pp->param->type == GS_SHADER_PARAM_INT) { + if (pp->param->type == GS_SHADER_PARAM_BOOL || pp->param->type == GS_SHADER_PARAM_INT) { if (validate_param(pp, sizeof(int))) { glUniform1iv(pp->obj, 1, (int *)array); gl_success("glUniform1iv"); @@ -517,19 +490,15 @@ static void program_set_param_data(struct gs_program *program, } else if (pp->param->type == GS_SHADER_PARAM_TEXTURE) { if (pp->param->next_sampler) { - program->device->cur_samplers[pp->param->sampler_id] = - pp->param->next_sampler; + program->device->cur_samplers[pp->param->sampler_id] = pp->param->next_sampler; pp->param->next_sampler = NULL; } glUniform1i(pp->obj, pp->param->texture_id); if (pp->param->srgb) - device_load_texture_srgb(program->device, - pp->param->texture, - pp->param->texture_id); + device_load_texture_srgb(program->device, pp->param->texture, pp->param->texture_id); else - device_load_texture(program->device, pp->param->texture, - pp->param->texture_id); + device_load_texture(program->device, pp->param->texture, pp->param->texture_id); } } @@ -560,8 +529,7 @@ static void print_link_errors(GLuint program) free(errors); } -static bool assign_program_attrib(struct gs_program *program, - struct shader_attrib *attrib) +static bool assign_program_attrib(struct gs_program *program, struct shader_attrib *attrib) { GLint attrib_obj = glGetAttribLocation(program->obj, attrib->name); if (!gl_success("glGetAttribLocation")) @@ -592,8 +560,7 @@ static inline bool assign_program_attribs(struct gs_program *program) return true; } -static bool assign_program_param(struct gs_program *program, - struct gs_shader_param *param) +static bool assign_program_param(struct gs_program *program, struct gs_shader_param *param) { struct program_param info; @@ -610,8 +577,7 @@ static bool assign_program_param(struct gs_program *program, return true; } -static inline bool assign_program_shader_params(struct gs_program *program, - struct gs_shader *shader) +static inline bool assign_program_shader_params(struct gs_program *program, struct gs_shader *shader) { for (size_t i = 0; i < shader->params.num; i++) { struct gs_shader_param *param = shader->params.array + i; diff --git a/libobs-opengl/gl-shaderparser.c b/libobs-opengl/gl-shaderparser.c index 49f48859b..9e8d13b38 100644 --- a/libobs-opengl/gl-shaderparser.c +++ b/libobs-opengl/gl-shaderparser.c @@ -18,12 +18,9 @@ #include "gl-subsystem.h" #include "gl-shaderparser.h" -static void gl_write_function_contents(struct gl_shader_parser *glsp, - struct cf_token **p_token, - const char *end); +static void gl_write_function_contents(struct gl_shader_parser *glsp, struct cf_token **p_token, const char *end); -static inline struct shader_var *sp_getparam(struct gl_shader_parser *glsp, - struct cf_token *token) +static inline struct shader_var *sp_getparam(struct gl_shader_parser *glsp, struct cf_token *token) { size_t i; for (i = 0; i < glsp->parser.params.num; i++) { @@ -35,13 +32,11 @@ static inline struct shader_var *sp_getparam(struct gl_shader_parser *glsp, return NULL; } -static inline size_t sp_getsampler(struct gl_shader_parser *glsp, - struct cf_token *token) +static inline size_t sp_getsampler(struct gl_shader_parser *glsp, struct cf_token *token) { size_t i; for (i = 0; i < glsp->parser.samplers.num; i++) { - struct shader_sampler *sampler = - glsp->parser.samplers.array + i; + struct shader_sampler *sampler = glsp->parser.samplers.array + i; if (strref_cmp(&token->str, sampler->name) == 0) return i; } @@ -49,15 +44,13 @@ static inline size_t sp_getsampler(struct gl_shader_parser *glsp, return -1; } -static inline int cmp_type(const char *name, const size_t name_len, - const char *type, const size_t type_len) +static inline int cmp_type(const char *name, const size_t name_len, const char *type, const size_t type_len) { size_t min_len = (name_len < type_len) ? type_len : name_len; return astrcmp_n(name, type, min_len); } -static bool gl_write_type_n(struct gl_shader_parser *glsp, const char *type, - size_t len) +static bool gl_write_type_n(struct gl_shader_parser *glsp, const char *type, size_t len) { if (cmp_type(type, len, "float2", 6) == 0) dstr_cat(&glsp->gl_string, "vec2"); @@ -97,15 +90,13 @@ static bool gl_write_type_n(struct gl_shader_parser *glsp, const char *type, return true; } -static inline void gl_write_type(struct gl_shader_parser *glsp, - const char *type) +static inline void gl_write_type(struct gl_shader_parser *glsp, const char *type) { if (!gl_write_type_n(glsp, type, strlen(type))) dstr_cat(&glsp->gl_string, type); } -static inline bool gl_write_type_token(struct gl_shader_parser *glsp, - struct cf_token *token) +static inline bool gl_write_type_token(struct gl_shader_parser *glsp, struct cf_token *token) { return gl_write_type_n(glsp, token->str.array, token->str.len); } @@ -138,13 +129,10 @@ static inline void gl_write_params(struct gl_shader_parser *glsp) dstr_cat(&glsp->gl_string, "\n"); } -static void gl_write_storage_var(struct gl_shader_parser *glsp, - struct shader_var *var, bool input, - const char *prefix); +static void gl_write_storage_var(struct gl_shader_parser *glsp, struct shader_var *var, bool input, const char *prefix); /* unwraps a structure that's used for input/output */ -static void gl_unwrap_storage_struct(struct gl_shader_parser *glsp, - struct shader_struct *st, const char *name, +static void gl_unwrap_storage_struct(struct gl_shader_parser *glsp, struct shader_struct *st, const char *name, bool input, const char *prefix) { struct dstr prefix_str; @@ -164,12 +152,9 @@ static void gl_unwrap_storage_struct(struct gl_shader_parser *glsp, dstr_free(&prefix_str); } -static void gl_write_storage_var(struct gl_shader_parser *glsp, - struct shader_var *var, bool input, - const char *prefix) +static void gl_write_storage_var(struct gl_shader_parser *glsp, struct shader_var *var, bool input, const char *prefix) { - struct shader_struct *st = - shader_parser_getstruct(&glsp->parser, var->type); + struct shader_struct *st = shader_parser_getstruct(&glsp->parser, var->type); if (st) { gl_unwrap_storage_struct(glsp, st, var->name, input, prefix); @@ -203,18 +188,15 @@ static void gl_write_storage_var(struct gl_shader_parser *glsp, } } -static inline void gl_write_inputs(struct gl_shader_parser *glsp, - struct shader_func *main) +static inline void gl_write_inputs(struct gl_shader_parser *glsp, struct shader_func *main) { size_t i; for (i = 0; i < main->params.num; i++) - gl_write_storage_var(glsp, main->params.array + i, true, - "inputval_"); + gl_write_storage_var(glsp, main->params.array + i, true, "inputval_"); dstr_cat(&glsp->gl_string, "\n"); } -static void gl_write_outputs(struct gl_shader_parser *glsp, - struct shader_func *main) +static void gl_write_outputs(struct gl_shader_parser *glsp, struct shader_func *main) { struct shader_var var = {0}; var.type = main->return_type; @@ -226,8 +208,7 @@ static void gl_write_outputs(struct gl_shader_parser *glsp, dstr_cat(&glsp->gl_string, "\n"); } -static void gl_write_struct(struct gl_shader_parser *glsp, - struct shader_struct *st) +static void gl_write_struct(struct gl_shader_parser *glsp, struct shader_struct *st) { size_t i; dstr_cat(&glsp->gl_string, "struct "); @@ -287,8 +268,7 @@ static inline void gl_write_structs(struct gl_shader_parser *glsp) * All else can be left as-is */ -static bool gl_write_mad(struct gl_shader_parser *glsp, - struct cf_token **p_token) +static bool gl_write_mad(struct gl_shader_parser *glsp, struct cf_token **p_token) { struct cf_parser *cfp = &glsp->parser.cfp; cfp->cur_token = *p_token; @@ -312,8 +292,7 @@ static bool gl_write_mad(struct gl_shader_parser *glsp, return true; } -static bool gl_write_mul(struct gl_shader_parser *glsp, - struct cf_token **p_token) +static bool gl_write_mul(struct gl_shader_parser *glsp, struct cf_token **p_token) { struct cf_parser *cfp = &glsp->parser.cfp; cfp->cur_token = *p_token; @@ -334,8 +313,7 @@ static bool gl_write_mul(struct gl_shader_parser *glsp, return true; } -static bool gl_write_sincos(struct gl_shader_parser *glsp, - struct cf_token **p_token) +static bool gl_write_sincos(struct gl_shader_parser *glsp, struct cf_token **p_token) { struct cf_parser *cfp = &glsp->parser.cfp; struct dstr var = {0}; @@ -379,8 +357,7 @@ fail: return success; } -static bool gl_write_saturate(struct gl_shader_parser *glsp, - struct cf_token **p_token) +static bool gl_write_saturate(struct gl_shader_parser *glsp, struct cf_token **p_token) { struct cf_parser *cfp = &glsp->parser.cfp; cfp->cur_token = *p_token; @@ -398,9 +375,8 @@ static bool gl_write_saturate(struct gl_shader_parser *glsp, return true; } -static inline bool gl_write_texture_call(struct gl_shader_parser *glsp, - struct shader_var *var, - const char *call, bool sampler) +static inline bool gl_write_texture_call(struct gl_shader_parser *glsp, struct shader_var *var, const char *call, + bool sampler) { struct cf_parser *cfp = &glsp->parser.cfp; @@ -431,9 +407,7 @@ static inline bool gl_write_texture_call(struct gl_shader_parser *glsp, } /* processes texture.Sample(sampler, texcoord) */ -static bool gl_write_texture_code(struct gl_shader_parser *glsp, - struct cf_token **p_token, - struct shader_var *var) +static bool gl_write_texture_code(struct gl_shader_parser *glsp, struct cf_token **p_token, struct shader_var *var) { struct cf_parser *cfp = &glsp->parser.cfp; bool written = false; @@ -457,9 +431,7 @@ static bool gl_write_texture_code(struct gl_shader_parser *glsp, } else if (cf_token_is(cfp, "SampleLevel")) { written = gl_write_texture_call(glsp, var, "textureLod", true); } else if (cf_token_is(cfp, "Load")) { - const char *const func = (strcmp(var->type, "texture3d") == 0) - ? "obs_load_3d" - : "obs_load_2d"; + const char *const func = (strcmp(var->type, "texture3d") == 0) ? "obs_load_3d" : "obs_load_2d"; written = gl_write_texture_call(glsp, var, func, false); } @@ -476,8 +448,7 @@ static bool gl_write_texture_code(struct gl_shader_parser *glsp, return true; } -static bool gl_write_intrinsic(struct gl_shader_parser *glsp, - struct cf_token **p_token) +static bool gl_write_intrinsic(struct gl_shader_parser *glsp, struct cf_token **p_token) { struct cf_token *token = *p_token; bool written = true; @@ -518,14 +489,11 @@ static bool gl_write_intrinsic(struct gl_shader_parser *glsp, return written; } -static void gl_write_function_contents(struct gl_shader_parser *glsp, - struct cf_token **p_token, - const char *end) +static void gl_write_function_contents(struct gl_shader_parser *glsp, struct cf_token **p_token, const char *end) { struct cf_token *token = *p_token; - if (token->type != CFTOKEN_NAME || (!gl_write_type_token(glsp, token) && - !gl_write_intrinsic(glsp, &token))) + if (token->type != CFTOKEN_NAME || (!gl_write_type_token(glsp, token) && !gl_write_intrinsic(glsp, &token))) dstr_cat_strref(&glsp->gl_string, &token->str); while (token->type != CFTOKEN_NONE) { @@ -535,8 +503,7 @@ static void gl_write_function_contents(struct gl_shader_parser *glsp, break; if (token->type == CFTOKEN_NAME) { - if (!gl_write_type_token(glsp, token) && - !gl_write_intrinsic(glsp, &token)) + if (!gl_write_type_token(glsp, token) && !gl_write_intrinsic(glsp, &token)) dstr_cat_strref(&glsp->gl_string, &token->str); } else if (token->type == CFTOKEN_OTHER) { @@ -555,8 +522,7 @@ static void gl_write_function_contents(struct gl_shader_parser *glsp, *p_token = token; } -static void gl_write_function(struct gl_shader_parser *glsp, - struct shader_func *func) +static void gl_write_function(struct gl_shader_parser *glsp, struct shader_func *func) { size_t i; struct cf_token *token; @@ -595,13 +561,11 @@ static inline void gl_write_functions(struct gl_shader_parser *glsp) } } -static inline void gl_write_main_interface_assign(struct gl_shader_parser *glsp, - struct shader_var *var, +static inline void gl_write_main_interface_assign(struct gl_shader_parser *glsp, struct shader_var *var, const char *src) { /* vertex shaders: write gl_Position */ - if (glsp->type == GS_SHADER_VERTEX && - strcmp(var->mapping, "POSITION") == 0) { + if (glsp->type == GS_SHADER_VERTEX && strcmp(var->mapping, "POSITION") == 0) { dstr_cat(&glsp->gl_string, "\tgl_Position = "); dstr_cat(&glsp->gl_string, src); dstr_cat(&glsp->gl_string, var->name); @@ -609,10 +573,8 @@ static inline void gl_write_main_interface_assign(struct gl_shader_parser *glsp, } } -static void gl_write_main_storage_assign(struct gl_shader_parser *glsp, - struct shader_var *var, - const char *dst, const char *src, - bool input) +static void gl_write_main_storage_assign(struct gl_shader_parser *glsp, struct shader_var *var, const char *dst, + const char *src, bool input) { struct shader_struct *st; struct dstr dst_copy = {0}; @@ -640,22 +602,18 @@ static void gl_write_main_storage_assign(struct gl_shader_parser *glsp, for (i = 0; i < st->vars.num; i++) { struct shader_var *st_var = st->vars.array + i; - gl_write_main_storage_assign(glsp, st_var, - dst_copy.array, - src_copy.array, input); + gl_write_main_storage_assign(glsp, st_var, dst_copy.array, src_copy.array, input); } dstr_free(&src_copy); } else { - if (input || (glsp->type != GS_SHADER_VERTEX) || - (strcmp(var->mapping, "POSITION"))) { + if (input || (glsp->type != GS_SHADER_VERTEX) || (strcmp(var->mapping, "POSITION"))) { if (!dstr_is_empty(&dst_copy)) dstr_cat_dstr(&glsp->gl_string, &dst_copy); dstr_cat(&glsp->gl_string, " = "); if (input && (strcmp(var->mapping, "VERTEXID") == 0)) dstr_cat(&glsp->gl_string, "uint(gl_VertexID)"); - else if (input && (glsp->type == GS_SHADER_PIXEL) && - (strcmp(var->mapping, "POSITION") == 0)) + else if (input && (glsp->type == GS_SHADER_PIXEL) && (strcmp(var->mapping, "POSITION") == 0)) dstr_cat(&glsp->gl_string, "gl_FragCoord"); else { if (src) @@ -672,15 +630,12 @@ static void gl_write_main_storage_assign(struct gl_shader_parser *glsp, dstr_free(&dst_copy); } -static inline void gl_write_main_storage_inputs(struct gl_shader_parser *glsp, - struct shader_func *main) +static inline void gl_write_main_storage_inputs(struct gl_shader_parser *glsp, struct shader_func *main) { - gl_write_main_storage_assign(glsp, main->params.array, NULL, - "inputval_", true); + gl_write_main_storage_assign(glsp, main->params.array, NULL, "inputval_", true); } -static inline void gl_write_main_storage_outputs(struct gl_shader_parser *glsp, - struct shader_func *main) +static inline void gl_write_main_storage_outputs(struct gl_shader_parser *glsp, struct shader_func *main) { /* we only do this *if* we're writing a struct, because otherwise * the call to 'main' already does the assignment for us */ @@ -693,8 +648,7 @@ static inline void gl_write_main_storage_outputs(struct gl_shader_parser *glsp, } } -static inline void gl_write_main_vars(struct gl_shader_parser *glsp, - struct shader_func *main_func) +static inline void gl_write_main_vars(struct gl_shader_parser *glsp, struct shader_func *main_func) { size_t i; for (i = 0; i < main_func->params.num; i++) { @@ -712,8 +666,7 @@ static inline void gl_write_main_vars(struct gl_shader_parser *glsp, } } -static inline void gl_write_main_func_call(struct gl_shader_parser *glsp, - struct shader_func *main_func) +static inline void gl_write_main_func_call(struct gl_shader_parser *glsp, struct shader_func *main_func) { size_t i; dstr_cat(&glsp->gl_string, "\n\toutputval = _main_wrap("); @@ -727,8 +680,7 @@ static inline void gl_write_main_func_call(struct gl_shader_parser *glsp, dstr_cat(&glsp->gl_string, ");\n"); } -static void gl_write_main(struct gl_shader_parser *glsp, - struct shader_func *main) +static void gl_write_main(struct gl_shader_parser *glsp, struct shader_func *main) { dstr_cat(&glsp->gl_string, "void main(void)\n{\n"); @@ -760,8 +712,7 @@ static void gl_rename_attributes(struct gl_shader_parser *glsp) } dstr_printf(&new_name, "%s%u", prefix, (unsigned int)val); - dstr_replace(&glsp->gl_string, attrib->name.array, - new_name.array); + dstr_replace(&glsp->gl_string, attrib->name.array, new_name.array); dstr_move(&attrib->name, &new_name); } } @@ -778,23 +729,19 @@ static bool gl_shader_buildstring(struct gl_shader_parser *glsp) dstr_copy(&glsp->gl_string, "#version 330\n\n"); dstr_cat(&glsp->gl_string, "const bool obs_glsl_compile = true;\n\n"); - dstr_cat(&glsp->gl_string, - "vec4 obs_load_2d(sampler2D s, ivec3 p_lod)\n"); + dstr_cat(&glsp->gl_string, "vec4 obs_load_2d(sampler2D s, ivec3 p_lod)\n"); dstr_cat(&glsp->gl_string, "{\n"); dstr_cat(&glsp->gl_string, "\tint lod = p_lod.z;\n"); dstr_cat(&glsp->gl_string, "\tvec2 size = textureSize(s, lod);\n"); - dstr_cat(&glsp->gl_string, - "\tvec2 p = (vec2(p_lod.xy) + 0.5) / size;\n"); + dstr_cat(&glsp->gl_string, "\tvec2 p = (vec2(p_lod.xy) + 0.5) / size;\n"); dstr_cat(&glsp->gl_string, "\tvec4 color = textureLod(s, p, lod);\n"); dstr_cat(&glsp->gl_string, "\treturn color;\n"); dstr_cat(&glsp->gl_string, "}\n\n"); - dstr_cat(&glsp->gl_string, - "vec4 obs_load_3d(sampler3D s, ivec4 p_lod)\n"); + dstr_cat(&glsp->gl_string, "vec4 obs_load_3d(sampler3D s, ivec4 p_lod)\n"); dstr_cat(&glsp->gl_string, "{\n"); dstr_cat(&glsp->gl_string, "\tint lod = p_lod.w;\n"); dstr_cat(&glsp->gl_string, "\tvec3 size = textureSize(s, lod);\n"); - dstr_cat(&glsp->gl_string, - "\tvec3 p = (vec3(p_lod.xyz) + 0.5) / size;\n"); + dstr_cat(&glsp->gl_string, "\tvec3 p = (vec3(p_lod.xyz) + 0.5) / size;\n"); dstr_cat(&glsp->gl_string, "\tvec4 color = textureLod(s, p, lod);\n"); dstr_cat(&glsp->gl_string, "\treturn color;\n"); dstr_cat(&glsp->gl_string, "}\n\n"); @@ -810,8 +757,7 @@ static bool gl_shader_buildstring(struct gl_shader_parser *glsp) return true; } -bool gl_shader_parse(struct gl_shader_parser *glsp, const char *shader_str, - const char *file) +bool gl_shader_parse(struct gl_shader_parser *glsp, const char *shader_str, const char *file) { bool success = shader_parse(&glsp->parser, shader_str, file); char *str = shader_parser_geterrors(&glsp->parser); diff --git a/libobs-opengl/gl-shaderparser.h b/libobs-opengl/gl-shaderparser.h index d481c1c80..9cf1a36ba 100644 --- a/libobs-opengl/gl-shaderparser.h +++ b/libobs-opengl/gl-shaderparser.h @@ -54,8 +54,7 @@ struct gl_shader_parser { DARRAY(struct gl_parser_attrib) attribs; }; -static inline void gl_shader_parser_init(struct gl_shader_parser *glsp, - enum gs_shader_type type) +static inline void gl_shader_parser_init(struct gl_shader_parser *glsp, enum gs_shader_type type) { glsp->type = type; @@ -86,5 +85,4 @@ static inline void gl_shader_parser_free(struct gl_shader_parser *glsp) shader_parser_free(&glsp->parser); } -extern bool gl_shader_parse(struct gl_shader_parser *glsp, - const char *shader_str, const char *file); +extern bool gl_shader_parse(struct gl_shader_parser *glsp, const char *shader_str, const char *file); diff --git a/libobs-opengl/gl-stagesurf.c b/libobs-opengl/gl-stagesurf.c index ba2e9da7f..4028a1ebf 100644 --- a/libobs-opengl/gl-stagesurf.c +++ b/libobs-opengl/gl-stagesurf.c @@ -42,8 +42,7 @@ static bool create_pixel_pack_buffer(struct gs_stage_surface *surf) return success; } -gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width, - uint32_t height, +gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width, uint32_t height, enum gs_color_format color_format) { struct gs_stage_surface *surf; @@ -111,8 +110,7 @@ static bool can_stage(struct gs_stage_surface *dst, struct gs_texture_2d *src) /* Apparently for mac, PBOs won't do an asynchronous transfer unless you use * FBOs along with glReadPixels, which is really dumb. */ -void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, - gs_texture_t *src) +void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, gs_texture_t *src) { struct gs_texture_2d *tex2d = (struct gs_texture_2d *)src; struct fbo_info *fbo; @@ -132,13 +130,11 @@ void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, if (!gl_bind_framebuffer(GL_READ_FRAMEBUFFER, fbo->fbo)) goto failed_unbind_buffer; - glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0, - src->gl_target, src->texture, 0); + glFramebufferTexture2D(GL_READ_FRAMEBUFFER, GL_COLOR_ATTACHMENT0 + 0, src->gl_target, src->texture, 0); if (!gl_success("glFrameBufferTexture2D")) goto failed_unbind_all; - glReadPixels(0, 0, dst->width, dst->height, dst->gl_format, - dst->gl_type, 0); + glReadPixels(0, 0, dst->width, dst->height, dst->gl_format, dst->gl_type, 0); if (!gl_success("glReadPixels")) goto failed_unbind_all; @@ -159,8 +155,7 @@ failed: #else -void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, - gs_texture_t *src) +void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, gs_texture_t *src) { struct gs_texture_2d *tex2d = (struct gs_texture_2d *)src; if (!can_stage(dst, tex2d)) @@ -199,14 +194,12 @@ uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf) return stagesurf->height; } -enum gs_color_format -gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) +enum gs_color_format gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) { return stagesurf->format; } -bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, - uint32_t *linesize) +bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, uint32_t *linesize) { if (!gl_bind_buffer(GL_PIXEL_PACK_BUFFER, stagesurf->pack_buffer)) goto fail; diff --git a/libobs-opengl/gl-subsystem.c b/libobs-opengl/gl-subsystem.c index 53dc8f2b4..f7b6ea097 100644 --- a/libobs-opengl/gl-subsystem.c +++ b/libobs-opengl/gl-subsystem.c @@ -31,8 +31,7 @@ #ifdef _DEBUG -static void APIENTRY gl_debug_proc(GLenum source, GLenum type, GLuint id, - GLenum severity, GLsizei length, +static void APIENTRY gl_debug_proc(GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar *message, const GLvoid *data) { UNUSED_PARAMETER(id); @@ -43,8 +42,7 @@ static void APIENTRY gl_debug_proc(GLenum source, GLenum type, GLuint id, /* frames can get a bit too much spam with irrelevant/insignificant opengl * debug messages */ #ifndef SHOW_ALL_GL_MESSAGES - if (type > GL_DEBUG_TYPE_PORTABILITY && - severity != GL_DEBUG_SEVERITY_HIGH) { + if (type > GL_DEBUG_TYPE_PORTABILITY && severity != GL_DEBUG_SEVERITY_HIGH) { return; } #endif @@ -112,8 +110,7 @@ static void APIENTRY gl_debug_proc(GLenum source, GLenum type, GLuint id, severity_str = "Unknown"; } - blog(LOG_DEBUG, "[%s][%s]{%s}: %.*s", source_str, type_str, - severity_str, length, message); + blog(LOG_DEBUG, "[%s][%s]{%s}: %.*s", source_str, type_str, severity_str, length, message); } static void gl_enable_debug() @@ -135,8 +132,7 @@ static void gl_enable_debug() {} static bool gl_init_extensions(struct gs_device *device) { if (!GLAD_GL_VERSION_3_3) { - blog(LOG_ERROR, - "obs-studio requires OpenGL version 3.3 or higher."); + blog(LOG_ERROR, "obs-studio requires OpenGL version 3.3 or higher."); return false; } @@ -172,12 +168,10 @@ static void clear_textures(struct gs_device *device) } } -void convert_sampler_info(struct gs_sampler_state *sampler, - const struct gs_sampler_info *info) +void convert_sampler_info(struct gs_sampler_state *sampler, const struct gs_sampler_info *info) { GLint max_anisotropy_max; - convert_filter(info->filter, &sampler->min_filter, - &sampler->mag_filter); + convert_filter(info->filter, &sampler->min_filter, &sampler->mag_filter); sampler->address_u = convert_address_mode(info->address_u); sampler->address_v = convert_address_mode(info->address_v); sampler->address_w = convert_address_mode(info->address_w); @@ -185,13 +179,11 @@ void convert_sampler_info(struct gs_sampler_state *sampler, max_anisotropy_max = 1; if (GLAD_GL_EXT_texture_filter_anisotropic) { - glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, - &max_anisotropy_max); + glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT, &max_anisotropy_max); gl_success("glGetIntegerv(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT)"); } - if (1 <= sampler->max_anisotropy && - sampler->max_anisotropy <= max_anisotropy_max) + if (1 <= sampler->max_anisotropy && sampler->max_anisotropy <= max_anisotropy_max) return; if (sampler->max_anisotropy < 1) @@ -237,8 +229,7 @@ int device_create(gs_device_t **p_device, uint32_t adapter) const char *glVendor = (const char *)glGetString(GL_VENDOR); const char *glRenderer = (const char *)glGetString(GL_RENDERER); - blog(LOG_INFO, "Loading up OpenGL on adapter %s %s", glVendor, - glRenderer); + blog(LOG_INFO, "Loading up OpenGL on adapter %s %s", glVendor, glRenderer); if (!gl_init_extensions(device)) { errorcode = GS_ERROR_NOT_SUPPORTED; @@ -246,8 +237,7 @@ int device_create(gs_device_t **p_device, uint32_t adapter) } const char *glVersion = (const char *)glGetString(GL_VERSION); - const char *glShadingLanguage = - (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); + const char *glShadingLanguage = (const char *)glGetString(GL_SHADING_LANGUAGE_VERSION); blog(LOG_INFO, "OpenGL loaded successfully, version %s, shading " @@ -264,8 +254,7 @@ int device_create(gs_device_t **p_device, uint32_t adapter) raw_load_info.address_w = GS_ADDRESS_BORDER; raw_load_info.max_anisotropy = 1; raw_load_info.border_color = 0; - device->raw_load_sampler = - device_samplerstate_create(device, &raw_load_info); + device->raw_load_sampler = device_samplerstate_create(device, &raw_load_info); gl_clear_context(device); device->cur_swap = NULL; @@ -304,8 +293,7 @@ void device_destroy(gs_device_t *device) } } -gs_swapchain_t *device_swapchain_create(gs_device_t *device, - const struct gs_init_data *info) +gs_swapchain_t *device_swapchain_create(gs_device_t *device, const struct gs_init_data *info) { struct gs_swap_chain *swap = bzalloc(sizeof(struct gs_swap_chain)); @@ -383,9 +371,7 @@ uint32_t device_get_height(const gs_device_t *device) } } -gs_samplerstate_t * -device_samplerstate_create(gs_device_t *device, - const struct gs_sampler_info *info) +gs_samplerstate_t *device_samplerstate_create(gs_device_t *device, const struct gs_sampler_info *info) { struct gs_sampler_state *sampler; @@ -477,8 +463,7 @@ static bool load_texture_sampler(gs_texture_t *tex, gs_samplerstate_t *ss) if (!gl_tex_param_i(tex->gl_target, GL_TEXTURE_MIN_FILTER, min_filter)) success = false; - if (!gl_tex_param_i(tex->gl_target, GL_TEXTURE_MAG_FILTER, - ss->mag_filter)) + if (!gl_tex_param_i(tex->gl_target, GL_TEXTURE_MAG_FILTER, ss->mag_filter)) success = false; if (!gl_tex_param_i(tex->gl_target, GL_TEXTURE_WRAP_S, ss->address_u)) success = false; @@ -486,17 +471,13 @@ static bool load_texture_sampler(gs_texture_t *tex, gs_samplerstate_t *ss) success = false; if (!gl_tex_param_i(tex->gl_target, GL_TEXTURE_WRAP_R, ss->address_w)) success = false; - if (ss->address_u == GL_CLAMP_TO_BORDER || - ss->address_v == GL_CLAMP_TO_BORDER || + if (ss->address_u == GL_CLAMP_TO_BORDER || ss->address_v == GL_CLAMP_TO_BORDER || ss->address_w == GL_CLAMP_TO_BORDER) { - if (!gl_tex_param_fv(tex->gl_target, GL_TEXTURE_BORDER_COLOR, - ss->border_color.ptr)) + if (!gl_tex_param_fv(tex->gl_target, GL_TEXTURE_BORDER_COLOR, ss->border_color.ptr)) success = false; } if (GLAD_GL_EXT_texture_filter_anisotropic) { - if (!gl_tex_param_i(tex->gl_target, - GL_TEXTURE_MAX_ANISOTROPY_EXT, - ss->max_anisotropy)) + if (!gl_tex_param_i(tex->gl_target, GL_TEXTURE_MAX_ANISOTROPY_EXT, ss->max_anisotropy)) success = false; } @@ -505,8 +486,7 @@ static bool load_texture_sampler(gs_texture_t *tex, gs_samplerstate_t *ss) return success; } -static inline struct gs_shader_param *get_texture_param(gs_device_t *device, - int unit) +static inline struct gs_shader_param *get_texture_param(gs_device_t *device, int unit) { struct gs_shader *shader = device->cur_pixel_shader; size_t i; @@ -522,8 +502,7 @@ static inline struct gs_shader_param *get_texture_param(gs_device_t *device, return NULL; } -static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex, - int unit, GLint decode) +static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex, int unit, GLint decode) { struct gs_shader_param *param; struct gs_sampler_state *sampler; @@ -584,8 +563,7 @@ void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, int unit) device_load_texture_internal(device, tex, unit, GL_DECODE_EXT); } -static bool load_sampler_on_textures(gs_device_t *device, gs_samplerstate_t *ss, - int sampler_unit) +static bool load_sampler_on_textures(gs_device_t *device, gs_samplerstate_t *ss, int sampler_unit) { struct gs_shader *shader = device->cur_pixel_shader; size_t i; @@ -593,8 +571,7 @@ static bool load_sampler_on_textures(gs_device_t *device, gs_samplerstate_t *ss, for (i = 0; i < shader->params.num; i++) { struct gs_shader_param *param = shader->params.array + i; - if (param->type == GS_SHADER_PARAM_TEXTURE && - param->sampler_id == (uint32_t)sampler_unit && + if (param->type == GS_SHADER_PARAM_TEXTURE && param->sampler_id == (uint32_t)sampler_unit && param->texture) { if (!gl_active_texture(GL_TEXTURE0 + param->texture_id)) return false; @@ -606,8 +583,7 @@ static bool load_sampler_on_textures(gs_device_t *device, gs_samplerstate_t *ss, return true; } -void device_load_samplerstate(gs_device_t *device, gs_samplerstate_t *ss, - int unit) +void device_load_samplerstate(gs_device_t *device, gs_samplerstate_t *ss, int unit) { /* need a pixel shader to properly bind samplers */ if (!device->cur_pixel_shader) @@ -641,8 +617,7 @@ void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader) device->cur_vertex_shader = vertshader; } -static void load_default_pixelshader_samplers(struct gs_device *device, - struct gs_shader *ps) +static void load_default_pixelshader_samplers(struct gs_device *device, struct gs_shader *ps) { size_t i; if (!ps) @@ -707,8 +682,7 @@ gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device) return device->cur_zstencil_buffer; } -static bool get_tex_dimensions(gs_texture_t *tex, uint32_t *width, - uint32_t *height) +static bool get_tex_dimensions(gs_texture_t *tex, uint32_t *width, uint32_t *height) { if (tex->type == GS_TEXTURE_2D) { struct gs_texture_2d *tex2d = (struct gs_texture_2d *)tex; @@ -733,8 +707,7 @@ static bool get_tex_dimensions(gs_texture_t *tex, uint32_t *width, */ struct fbo_info *get_fbo(gs_texture_t *tex, uint32_t width, uint32_t height) { - if (tex->fbo && tex->fbo->width == width && - tex->fbo->height == height && tex->fbo->format == tex->format) + if (tex->fbo && tex->fbo->width == width && tex->fbo->height == height && tex->fbo->format == tex->format) return tex->fbo; GLuint fbo; @@ -780,8 +753,7 @@ static bool set_current_fbo(gs_device_t *device, struct fbo_info *fbo) return true; } -static bool attach_rendertarget(struct fbo_info *fbo, gs_texture_t *tex, - int side) +static bool attach_rendertarget(struct fbo_info *fbo, gs_texture_t *tex, int side) { if (fbo->cur_render_target == tex) return true; @@ -789,14 +761,10 @@ static bool attach_rendertarget(struct fbo_info *fbo, gs_texture_t *tex, fbo->cur_render_target = tex; if (tex->type == GS_TEXTURE_2D) { - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, - tex->texture, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex->texture, 0); } else if (tex->type == GS_TEXTURE_CUBE) { - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, - GL_COLOR_ATTACHMENT0, - GL_TEXTURE_CUBE_MAP_POSITIVE_X + side, + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_CUBE_MAP_POSITIVE_X + side, tex->texture, 0); } else { @@ -821,22 +789,18 @@ static bool attach_zstencil(struct fbo_info *fbo, gs_zstencil_t *zs) zs_attachment = zs->attachment; } - glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, zs_attachment, - GL_RENDERBUFFER, zsbuffer); + glFramebufferRenderbuffer(GL_DRAW_FRAMEBUFFER, zs_attachment, GL_RENDERBUFFER, zsbuffer); if (!gl_success("glFramebufferRenderbuffer")) return false; return true; } -static bool set_target(gs_device_t *device, gs_texture_t *tex, int side, - gs_zstencil_t *zs, enum gs_color_space space) +static bool set_target(gs_device_t *device, gs_texture_t *tex, int side, gs_zstencil_t *zs, enum gs_color_space space) { device->cur_color_space = space; - if (device->cur_render_target == tex && - device->cur_zstencil_buffer == zs && - device->cur_render_side == side) + if (device->cur_render_target == tex && device->cur_zstencil_buffer == zs && device->cur_render_side == side) return true; device->cur_render_target = tex; @@ -860,8 +824,7 @@ static bool set_target(gs_device_t *device, gs_texture_t *tex, int side, return true; } -void device_set_render_target(gs_device_t *device, gs_texture_t *tex, - gs_zstencil_t *zstencil) +void device_set_render_target(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil) { if (tex) { if (tex->type != GS_TEXTURE_2D) { @@ -884,9 +847,7 @@ fail: blog(LOG_ERROR, "device_set_render_target (GL) failed"); } -void device_set_render_target_with_color_space(gs_device_t *device, - gs_texture_t *tex, - gs_zstencil_t *zstencil, +void device_set_render_target_with_color_space(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil, enum gs_color_space space) { if (tex) { @@ -907,12 +868,10 @@ void device_set_render_target_with_color_space(gs_device_t *device, return; fail: - blog(LOG_ERROR, - "device_set_render_target_with_color_space (GL) failed"); + blog(LOG_ERROR, "device_set_render_target_with_color_space (GL) failed"); } -void device_set_cube_render_target(gs_device_t *device, gs_texture_t *cubetex, - int side, gs_zstencil_t *zstencil) +void device_set_cube_render_target(gs_device_t *device, gs_texture_t *cubetex, int side, gs_zstencil_t *zstencil) { if (cubetex) { if (cubetex->type != GS_TEXTURE_CUBE) { @@ -954,10 +913,8 @@ bool device_framebuffer_srgb_enabled(gs_device_t *device) return enabled == GL_TRUE; } -void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, - uint32_t dst_x, uint32_t dst_y, - gs_texture_t *src, uint32_t src_x, - uint32_t src_y, uint32_t src_w, uint32_t src_h) +void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, + gs_texture_t *src, uint32_t src_x, uint32_t src_y, uint32_t src_w, uint32_t src_h) { struct gs_texture_2d *src2d = (struct gs_texture_2d *)src; struct gs_texture_2d *dst2d = (struct gs_texture_2d *)dst; @@ -978,16 +935,13 @@ void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, goto fail; } - if (gs_generalize_format(dst->format) != - gs_generalize_format(src->format)) { + if (gs_generalize_format(dst->format) != gs_generalize_format(src->format)) { blog(LOG_ERROR, "Source and destination formats do not match"); goto fail; } - uint32_t nw = (uint32_t)src_w ? (uint32_t)src_w - : (src2d->width - src_x); - uint32_t nh = (uint32_t)src_h ? (uint32_t)src_h - : (src2d->height - src_y); + uint32_t nw = (uint32_t)src_w ? (uint32_t)src_w : (src2d->width - src_x); + uint32_t nh = (uint32_t)src_h ? (uint32_t)src_h : (src2d->height - src_y); if (dst2d->width - dst_x < nw || dst2d->height - dst_y < nh) { blog(LOG_ERROR, "Destination texture region is not big " @@ -995,8 +949,7 @@ void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, goto fail; } - if (!gl_copy_texture(device, dst, dst_x, dst_y, src, src_x, src_y, nw, - nh)) + if (!gl_copy_texture(device, dst, dst_x, dst_y, src, src_x, src_y, nw, nh)) goto fail; return; @@ -1005,8 +958,7 @@ fail: blog(LOG_ERROR, "device_copy_texture (GL) failed"); } -void device_copy_texture(gs_device_t *device, gs_texture_t *dst, - gs_texture_t *src) +void device_copy_texture(gs_device_t *device, gs_texture_t *dst, gs_texture_t *src) { device_copy_texture_region(device, dst, 0, 0, src, 0, 0, 0, 0); } @@ -1100,8 +1052,7 @@ static inline struct gs_program *get_shader_program(struct gs_device *device) return program; } -void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, - uint32_t start_vert, uint32_t num_verts) +void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, uint32_t start_vert, uint32_t num_verts) { struct gs_vertex_buffer *vb = device->cur_vertex_buffer; struct gs_index_buffer *ib = device->cur_index_buffer; @@ -1144,8 +1095,7 @@ void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, if (ib) { if (num_verts == 0) num_verts = (uint32_t)device->cur_index_buffer->num; - glDrawElements(topology, num_verts, ib->gl_type, - (const GLvoid *)(start_vert * ib->width)); + glDrawElements(topology, num_verts, ib->gl_type, (const GLvoid *)(start_vert * ib->width)); if (!gl_success("glDrawElements")) goto fail; @@ -1169,8 +1119,7 @@ void device_end_scene(gs_device_t *device) UNUSED_PARAMETER(device); } -void device_clear(gs_device_t *device, uint32_t clear_flags, - const struct vec4 *color, float depth, uint8_t stencil) +void device_clear(gs_device_t *device, uint32_t clear_flags, const struct vec4 *color, float depth, uint8_t stencil) { GLbitfield gl_flags = 0; @@ -1271,16 +1220,14 @@ void device_enable_stencil_write(gs_device_t *device, bool enable) UNUSED_PARAMETER(device); } -void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, - bool alpha) +void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, bool alpha) { glColorMask(red, green, blue, alpha); UNUSED_PARAMETER(device); } -void device_blend_function(gs_device_t *device, enum gs_blend_type src, - enum gs_blend_type dest) +void device_blend_function(gs_device_t *device, enum gs_blend_type src, enum gs_blend_type dest) { GLenum gl_src = convert_gs_blend_type(src); GLenum gl_dst = convert_gs_blend_type(dest); @@ -1292,11 +1239,8 @@ void device_blend_function(gs_device_t *device, enum gs_blend_type src, UNUSED_PARAMETER(device); } -void device_blend_function_separate(gs_device_t *device, - enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, - enum gs_blend_type dest_a) +void device_blend_function_separate(gs_device_t *device, enum gs_blend_type src_c, enum gs_blend_type dest_c, + enum gs_blend_type src_a, enum gs_blend_type dest_a) { GLenum gl_src_c = convert_gs_blend_type(src_c); GLenum gl_dst_c = convert_gs_blend_type(dest_c); @@ -1332,8 +1276,7 @@ void device_depth_function(gs_device_t *device, enum gs_depth_test test) UNUSED_PARAMETER(device); } -void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, - enum gs_depth_test test) +void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, enum gs_depth_test test) { GLenum gl_side = convert_gs_stencil_side(side); GLenum gl_test = convert_gs_depth_test(test); @@ -1345,10 +1288,8 @@ void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, UNUSED_PARAMETER(device); } -void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, - enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, - enum gs_stencil_op_type zpass) +void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, enum gs_stencil_op_type fail, + enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass) { GLenum gl_side = convert_gs_stencil_side(side); GLenum gl_fail = convert_gs_stencil_op(fail); @@ -1373,8 +1314,7 @@ static inline uint32_t get_target_height(const struct gs_device *device) return gs_cubetexture_get_size(device->cur_render_target); } -void device_set_viewport(gs_device_t *device, int x, int y, int width, - int height) +void device_set_viewport(gs_device_t *device, int x, int y, int width, int height) { uint32_t base_height = 0; @@ -1421,8 +1361,7 @@ void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect) blog(LOG_ERROR, "device_set_scissor_rect (GL) failed"); } -void device_ortho(gs_device_t *device, float left, float right, float top, - float bottom, float near, float far) +void device_ortho(gs_device_t *device, float left, float right, float top, float bottom, float near, float far) { struct matrix4 *dst = &device->cur_proj; @@ -1447,8 +1386,7 @@ void device_ortho(gs_device_t *device, float left, float right, float top, dst->t.w = 1.0f; } -void device_frustum(gs_device_t *device, float left, float right, float top, - float bottom, float near, float far) +void device_frustum(gs_device_t *device, float left, float right, float top, float bottom, float near, float far) { struct matrix4 *dst = &device->cur_proj; @@ -1490,8 +1428,7 @@ void device_projection_pop(gs_device_t *device) da_pop_back(device->proj_stack); } -void device_debug_marker_begin(gs_device_t *device, const char *markername, - const float color[4]) +void device_debug_marker_begin(gs_device_t *device, const char *markername, const float color[4]) { UNUSED_PARAMETER(device); UNUSED_PARAMETER(color); @@ -1575,8 +1512,7 @@ void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate) if (samplerstate->device) for (int i = 0; i < GS_MAX_TEXTURES; i++) - if (samplerstate->device->cur_samplers[i] == - samplerstate) + if (samplerstate->device->cur_samplers[i] == samplerstate) samplerstate->device->cur_samplers[i] = NULL; samplerstate_release(samplerstate); @@ -1608,8 +1544,7 @@ void gs_timer_end(gs_timer_t *timer) bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks) { GLint available = 0; - glGetQueryObjectiv(timer->queries[1], GL_QUERY_RESULT_AVAILABLE, - &available); + glGetQueryObjectiv(timer->queries[1], GL_QUERY_RESULT_AVAILABLE, &available); GLuint64 begin, end; glGetQueryObjectui64v(timer->queries[0], GL_QUERY_RESULT, &begin); @@ -1636,8 +1571,7 @@ void gs_timer_range_end(gs_timer_range_t *range) UNUSED_PARAMETER(range); } -bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, - uint64_t *frequency) +bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, uint64_t *frequency) { UNUSED_PARAMETER(range); diff --git a/libobs-opengl/gl-subsystem.h b/libobs-opengl/gl-subsystem.h index 33bcc2a35..b98d41b60 100644 --- a/libobs-opengl/gl-subsystem.h +++ b/libobs-opengl/gl-subsystem.h @@ -330,8 +330,7 @@ static inline GLenum convert_shader_type(enum gs_shader_type type) return GL_VERTEX_SHADER; } -static inline void convert_filter(enum gs_sample_filter filter, - GLint *min_filter, GLint *mag_filter) +static inline void convert_filter(enum gs_sample_filter filter, GLint *min_filter, GLint *mag_filter) { switch (filter) { case GS_FILTER_POINT: @@ -412,8 +411,7 @@ static inline GLenum convert_gs_topology(enum gs_draw_mode mode) return GL_POINTS; } -extern void convert_sampler_info(struct gs_sampler_state *sampler, - const struct gs_sampler_info *info); +extern void convert_sampler_info(struct gs_sampler_state *sampler, const struct gs_sampler_info *info); struct gs_sampler_state { gs_device_t *device; @@ -461,14 +459,7 @@ struct gs_shader_param { bool changed; }; -enum attrib_type { - ATTRIB_POSITION, - ATTRIB_NORMAL, - ATTRIB_TANGENT, - ATTRIB_COLOR, - ATTRIB_TEXCOORD, - ATTRIB_TARGET -}; +enum attrib_type { ATTRIB_POSITION, ATTRIB_NORMAL, ATTRIB_TANGENT, ATTRIB_COLOR, ATTRIB_TEXCOORD, ATTRIB_TARGET }; struct shader_attrib { char *name; @@ -526,9 +517,7 @@ struct gs_vertex_buffer { struct gs_vb_data *data; }; -extern bool load_vb_buffers(struct gs_program *program, - struct gs_vertex_buffer *vb, - struct gs_index_buffer *ib); +extern bool load_vb_buffers(struct gs_program *program, struct gs_vertex_buffer *vb, struct gs_index_buffer *ib); struct gs_index_buffer { GLuint buffer; @@ -669,22 +658,18 @@ struct gs_device { struct fbo_info *cur_fbo; }; -extern struct fbo_info *get_fbo(gs_texture_t *tex, uint32_t width, - uint32_t height); +extern struct fbo_info *get_fbo(gs_texture_t *tex, uint32_t width, uint32_t height); extern void gl_update(gs_device_t *device); extern void gl_clear_context(gs_device_t *device); -extern struct gl_platform *gl_platform_create(gs_device_t *device, - uint32_t adapter); +extern struct gl_platform *gl_platform_create(gs_device_t *device, uint32_t adapter); extern void gl_platform_destroy(struct gl_platform *platform); extern bool gl_platform_init_swapchain(struct gs_swap_chain *swap); extern void gl_platform_cleanup_swapchain(struct gs_swap_chain *swap); -extern struct gl_windowinfo * -gl_windowinfo_create(const struct gs_init_data *info); +extern struct gl_windowinfo *gl_windowinfo_create(const struct gs_init_data *info); extern void gl_windowinfo_destroy(struct gl_windowinfo *wi); -extern void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, - uint32_t *height); +extern void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, uint32_t *height); diff --git a/libobs-opengl/gl-texture2d.c b/libobs-opengl/gl-texture2d.c index fe98353ed..1c6251e41 100644 --- a/libobs-opengl/gl-texture2d.c +++ b/libobs-opengl/gl-texture2d.c @@ -31,13 +31,10 @@ static bool upload_texture_2d(struct gs_texture_2d *tex, const uint8_t **data) if (!gl_bind_texture(GL_TEXTURE_2D, tex->base.texture)) return false; - success = gl_init_face(GL_TEXTURE_2D, tex->base.gl_type, num_levels, - tex->base.gl_format, - tex->base.gl_internal_format, compressed, - tex->width, tex->height, tex_size, &data); + success = gl_init_face(GL_TEXTURE_2D, tex->base.gl_type, num_levels, tex->base.gl_format, + tex->base.gl_internal_format, compressed, tex->width, tex->height, tex_size, &data); - if (!gl_tex_param_i(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, - num_levels - 1)) + if (!gl_tex_param_i(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, num_levels - 1)) success = false; if (!gl_bind_texture(GL_TEXTURE_2D, 0)) success = false; @@ -76,10 +73,8 @@ static bool create_pixel_unpack_buffer(struct gs_texture_2d *tex) return success; } -gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, - uint32_t height, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, +gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t levels, const uint8_t **data, uint32_t flags) { struct gs_texture_2d *tex = bzalloc(sizeof(struct gs_texture_2d)); @@ -110,8 +105,7 @@ gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, if (!gl_bind_texture(GL_TEXTURE_2D, tex->base.texture)) goto fail; - bool did_init = - gl_tex_param_i(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); + bool did_init = gl_tex_param_i(GL_TEXTURE_2D, GL_TEXTURE_MAX_LEVEL, 0); bool did_unbind = gl_bind_texture(GL_TEXTURE_2D, 0); if (!did_init || !did_unbind) @@ -144,13 +138,11 @@ void gs_texture_destroy(gs_texture_t *tex) if (!tex->is_dummy && tex->is_dynamic) { if (tex->type == GS_TEXTURE_2D) { - struct gs_texture_2d *tex2d = - (struct gs_texture_2d *)tex; + struct gs_texture_2d *tex2d = (struct gs_texture_2d *)tex; if (tex2d->unpack_buffer) gl_delete_buffers(1, &tex2d->unpack_buffer); } else if (tex->type == GS_TEXTURE_3D) { - struct gs_texture_3d *tex3d = - (struct gs_texture_3d *)tex; + struct gs_texture_3d *tex3d = (struct gs_texture_3d *)tex; if (tex3d->unpack_buffer) gl_delete_buffers(1, &tex3d->unpack_buffer); } @@ -234,8 +226,8 @@ void gs_texture_unmap(gs_texture_t *tex) if (!gl_bind_texture(GL_TEXTURE_2D, tex2d->base.texture)) goto failed; - glTexImage2D(GL_TEXTURE_2D, 0, tex->gl_internal_format, tex2d->width, - tex2d->height, 0, tex->gl_format, tex->gl_type, 0); + glTexImage2D(GL_TEXTURE_2D, 0, tex->gl_internal_format, tex2d->width, tex2d->height, 0, tex->gl_format, + tex->gl_type, 0); if (!gl_success("glTexImage2D")) goto failed; diff --git a/libobs-opengl/gl-texture3d.c b/libobs-opengl/gl-texture3d.c index 69bab3938..03f6592d3 100644 --- a/libobs-opengl/gl-texture3d.c +++ b/libobs-opengl/gl-texture3d.c @@ -17,10 +17,8 @@ #include "gl-subsystem.h" -static bool gl_init_volume(GLenum type, uint32_t num_levels, GLenum format, - GLint internal_format, bool compressed, - uint32_t width, uint32_t height, uint32_t depth, - const uint8_t *const **p_data) +static bool gl_init_volume(GLenum type, uint32_t num_levels, GLenum format, GLint internal_format, bool compressed, + uint32_t width, uint32_t height, uint32_t depth, const uint8_t *const **p_data) { bool success = true; const uint8_t *const *data = p_data ? *p_data : NULL; @@ -30,16 +28,13 @@ static bool gl_init_volume(GLenum type, uint32_t num_levels, GLenum format, for (i = 0; i < num_levels; i++) { if (compressed) { uint32_t mip_size = width * height * depth * bpp / 8; - glCompressedTexImage3D(GL_TEXTURE_3D, i, - internal_format, width, height, - depth, 0, mip_size, + glCompressedTexImage3D(GL_TEXTURE_3D, i, internal_format, width, height, depth, 0, mip_size, data ? *data : NULL); if (!gl_success("glCompressedTexImage3D")) success = false; } else { - glTexImage3D(GL_TEXTURE_3D, i, internal_format, width, - height, depth, 0, format, type, + glTexImage3D(GL_TEXTURE_3D, i, internal_format, width, height, depth, 0, format, type, data ? *data : NULL); if (!gl_success("glTexImage3D")) success = false; @@ -61,27 +56,22 @@ static bool gl_init_volume(GLenum type, uint32_t num_levels, GLenum format, return success; } -static bool upload_texture_3d(struct gs_texture_3d *tex, - const uint8_t *const *data) +static bool upload_texture_3d(struct gs_texture_3d *tex, const uint8_t *const *data) { uint32_t num_levels = tex->base.levels; bool compressed = gs_is_compressed_format(tex->base.format); bool success; if (!num_levels) - num_levels = gs_get_total_levels(tex->width, tex->height, - tex->depth); + num_levels = gs_get_total_levels(tex->width, tex->height, tex->depth); if (!gl_bind_texture(GL_TEXTURE_3D, tex->base.texture)) return false; - success = gl_init_volume(tex->base.gl_type, num_levels, - tex->base.gl_format, - tex->base.gl_internal_format, compressed, - tex->width, tex->height, tex->depth, &data); + success = gl_init_volume(tex->base.gl_type, num_levels, tex->base.gl_format, tex->base.gl_internal_format, + compressed, tex->width, tex->height, tex->depth, &data); - if (!gl_tex_param_i(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, - num_levels - 1)) + if (!gl_tex_param_i(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, num_levels - 1)) success = false; if (!gl_bind_texture(GL_TEXTURE_3D, 0)) success = false; @@ -122,11 +112,8 @@ static bool create_pixel_unpack_buffer(struct gs_texture_3d *tex) return success; } -gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, - uint32_t height, uint32_t depth, - enum gs_color_format color_format, - uint32_t levels, - const uint8_t *const *data, +gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, uint32_t height, uint32_t depth, + enum gs_color_format color_format, uint32_t levels, const uint8_t *const *data, uint32_t flags) { struct gs_texture_3d *tex = bzalloc(sizeof(struct gs_texture_3d)); @@ -159,13 +146,9 @@ gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, goto fail; bool compressed = gs_is_compressed_format(tex->base.format); - bool did_init = gl_init_volume(tex->base.gl_type, 1, - tex->base.gl_format, - tex->base.gl_internal_format, - compressed, tex->width, - tex->height, tex->depth, NULL); - did_init = - gl_tex_param_i(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 0); + bool did_init = gl_init_volume(tex->base.gl_type, 1, tex->base.gl_format, tex->base.gl_internal_format, + compressed, tex->width, tex->height, tex->depth, NULL); + did_init = gl_tex_param_i(GL_TEXTURE_3D, GL_TEXTURE_MAX_LEVEL, 0); bool did_unbind = gl_bind_texture(GL_TEXTURE_3D, 0); if (!did_init || !did_unbind) diff --git a/libobs-opengl/gl-texturecube.c b/libobs-opengl/gl-texturecube.c index efc7e343b..e5f69b66f 100644 --- a/libobs-opengl/gl-texturecube.c +++ b/libobs-opengl/gl-texturecube.c @@ -17,8 +17,7 @@ #include "gl-subsystem.h" -static inline bool upload_texture_cube(struct gs_texture_cube *tex, - const uint8_t **data) +static inline bool upload_texture_cube(struct gs_texture_cube *tex, const uint8_t **data) { uint32_t row_size = tex->size * gs_get_format_bpp(tex->base.format); uint32_t tex_size = tex->size * row_size / 8; @@ -37,10 +36,8 @@ static inline bool upload_texture_cube(struct gs_texture_cube *tex, if (!gl_bind_texture(target, tex->base.texture)) success = false; - if (!gl_init_face(target, gl_type, num_levels, - tex->base.gl_format, - tex->base.gl_internal_format, compressed, - tex->size, tex->size, tex_size, &data)) + if (!gl_init_face(target, gl_type, num_levels, tex->base.gl_format, tex->base.gl_internal_format, + compressed, tex->size, tex->size, tex_size, &data)) success = false; if (!gl_bind_texture(target, 0)) @@ -57,10 +54,8 @@ static inline bool upload_texture_cube(struct gs_texture_cube *tex, return success; } -gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, - uint32_t flags) +gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size, enum gs_color_format color_format, + uint32_t levels, const uint8_t **data, uint32_t flags) { struct gs_texture_cube *tex = bzalloc(sizeof(struct gs_texture_cube)); tex->base.device = device; @@ -111,8 +106,7 @@ static inline bool is_texture_cube(const gs_texture_t *tex, const char *func) uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex) { - const struct gs_texture_cube *cube = - (const struct gs_texture_cube *)cubetex; + const struct gs_texture_cube *cube = (const struct gs_texture_cube *)cubetex; if (!is_texture_cube(cubetex, "gs_cubetexture_get_size")) return 0; @@ -120,8 +114,7 @@ uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex) return cube->size; } -enum gs_color_format -gs_cubetexture_get_color_format(const gs_texture_t *cubetex) +enum gs_color_format gs_cubetexture_get_color_format(const gs_texture_t *cubetex) { return cubetex->format; } diff --git a/libobs-opengl/gl-vertexbuffer.c b/libobs-opengl/gl-vertexbuffer.c index 9bb674f5e..c7315882c 100644 --- a/libobs-opengl/gl-vertexbuffer.c +++ b/libobs-opengl/gl-vertexbuffer.c @@ -23,28 +23,24 @@ static bool create_buffers(struct gs_vertex_buffer *vb) GLenum usage = vb->dynamic ? GL_STREAM_DRAW : GL_STATIC_DRAW; size_t i; - if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->vertex_buffer, - vb->data->num * sizeof(struct vec3), + if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->vertex_buffer, vb->data->num * sizeof(struct vec3), vb->data->points, usage)) return false; if (vb->data->normals) { - if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->normal_buffer, - vb->data->num * sizeof(struct vec3), + if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->normal_buffer, vb->data->num * sizeof(struct vec3), vb->data->normals, usage)) return false; } if (vb->data->tangents) { - if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->tangent_buffer, - vb->data->num * sizeof(struct vec3), + if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->tangent_buffer, vb->data->num * sizeof(struct vec3), vb->data->tangents, usage)) return false; } if (vb->data->colors) { - if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->color_buffer, - vb->data->num * sizeof(uint32_t), + if (!gl_create_buffer(GL_ARRAY_BUFFER, &vb->color_buffer, vb->data->num * sizeof(uint32_t), vb->data->colors, usage)) return false; } @@ -57,8 +53,7 @@ static bool create_buffers(struct gs_vertex_buffer *vb) struct gs_tvertarray *tv = vb->data->tvarray + i; size_t size = vb->data->num * sizeof(float) * tv->width; - if (!gl_create_buffer(GL_ARRAY_BUFFER, &tex_buffer, size, - tv->array, usage)) + if (!gl_create_buffer(GL_ARRAY_BUFFER, &tex_buffer, size, tv->array, usage)) return false; da_push_back(vb->uv_buffers, &tex_buffer); @@ -76,9 +71,7 @@ static bool create_buffers(struct gs_vertex_buffer *vb) return true; } -gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, - struct gs_vb_data *data, - uint32_t flags) +gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, struct gs_vb_data *data, uint32_t flags) { struct gs_vertex_buffer *vb = bzalloc(sizeof(struct gs_vertex_buffer)); vb->device = device; @@ -107,8 +100,7 @@ void gs_vertexbuffer_destroy(gs_vertbuffer_t *vb) if (vb->color_buffer) gl_delete_buffers(1, &vb->color_buffer); if (vb->uv_buffers.num) - gl_delete_buffers((GLsizei)vb->uv_buffers.num, - vb->uv_buffers.array); + gl_delete_buffers((GLsizei)vb->uv_buffers.num, vb->uv_buffers.array); if (vb->vao) gl_delete_vertex_arrays(1, &vb->vao); @@ -121,12 +113,10 @@ void gs_vertexbuffer_destroy(gs_vertbuffer_t *vb) } } -static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vb, - const struct gs_vb_data *data) +static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vb, const struct gs_vb_data *data) { size_t i; - size_t num_tex = data->num_tex < vb->data->num_tex ? data->num_tex - : vb->data->num_tex; + size_t num_tex = data->num_tex < vb->data->num_tex ? data->num_tex : vb->data->num_tex; if (!vb->dynamic) { blog(LOG_ERROR, "vertex buffer is not dynamic"); @@ -134,29 +124,23 @@ static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vb, } if (data->points) { - if (!update_buffer(GL_ARRAY_BUFFER, vb->vertex_buffer, - data->points, - data->num * sizeof(struct vec3))) + if (!update_buffer(GL_ARRAY_BUFFER, vb->vertex_buffer, data->points, data->num * sizeof(struct vec3))) goto failed; } if (vb->normal_buffer && data->normals) { - if (!update_buffer(GL_ARRAY_BUFFER, vb->normal_buffer, - data->normals, - data->num * sizeof(struct vec3))) + if (!update_buffer(GL_ARRAY_BUFFER, vb->normal_buffer, data->normals, data->num * sizeof(struct vec3))) goto failed; } if (vb->tangent_buffer && data->tangents) { - if (!update_buffer(GL_ARRAY_BUFFER, vb->tangent_buffer, - data->tangents, + if (!update_buffer(GL_ARRAY_BUFFER, vb->tangent_buffer, data->tangents, data->num * sizeof(struct vec3))) goto failed; } if (vb->color_buffer && data->colors) { - if (!update_buffer(GL_ARRAY_BUFFER, vb->color_buffer, - data->colors, data->num * sizeof(uint32_t))) + if (!update_buffer(GL_ARRAY_BUFFER, vb->color_buffer, data->colors, data->num * sizeof(uint32_t))) goto failed; } @@ -180,8 +164,7 @@ void gs_vertexbuffer_flush(gs_vertbuffer_t *vb) gs_vertexbuffer_flush_internal(vb, vb->data); } -void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vb, - const struct gs_vb_data *data) +void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vb, const struct gs_vb_data *data) { gs_vertexbuffer_flush_internal(vb, data); } @@ -191,9 +174,8 @@ struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vb) return vb->data; } -static inline GLuint get_vb_buffer(struct gs_vertex_buffer *vb, - enum attrib_type type, size_t index, - GLint *width, GLenum *gl_type) +static inline GLuint get_vb_buffer(struct gs_vertex_buffer *vb, enum attrib_type type, size_t index, GLint *width, + GLenum *gl_type) { *gl_type = GL_FLOAT; *width = 4; @@ -218,8 +200,7 @@ static inline GLuint get_vb_buffer(struct gs_vertex_buffer *vb, return 0; } -static bool load_vb_buffer(struct shader_attrib *attrib, - struct gs_vertex_buffer *vb, GLint id) +static bool load_vb_buffer(struct shader_attrib *attrib, struct gs_vertex_buffer *vb, GLint id) { GLenum type; GLint width; @@ -250,8 +231,7 @@ static bool load_vb_buffer(struct shader_attrib *attrib, return success; } -bool load_vb_buffers(struct gs_program *program, struct gs_vertex_buffer *vb, - struct gs_index_buffer *ib) +bool load_vb_buffers(struct gs_program *program, struct gs_vertex_buffer *vb, struct gs_index_buffer *ib) { struct gs_shader *shader = program->vertex_shader; size_t i; diff --git a/libobs-opengl/gl-wayland-egl.c b/libobs-opengl/gl-wayland-egl.c index 913ca3c3a..35f09057c 100644 --- a/libobs-opengl/gl-wayland-egl.c +++ b/libobs-opengl/gl-wayland-egl.c @@ -92,11 +92,9 @@ struct gl_platform { EGLContext context; }; -struct gl_windowinfo * -gl_wayland_egl_windowinfo_create(const struct gs_init_data *info) +struct gl_windowinfo *gl_wayland_egl_windowinfo_create(const struct gs_init_data *info) { - struct wl_egl_window *window = - wl_egl_window_create(info->window.display, info->cx, info->cy); + struct wl_egl_window *window = wl_egl_window_create(info->window.display, info->cx, info->cy); if (window == NULL) { blog(LOG_ERROR, "wl_egl_window_create failed"); return NULL; @@ -113,8 +111,7 @@ static void gl_wayland_egl_windowinfo_destroy(struct gl_windowinfo *info) bfree(info); } -static bool egl_make_current(EGLDisplay display, EGLSurface surface, - EGLContext context) +static bool egl_make_current(EGLDisplay display, EGLSurface surface, EGLContext context) { if (eglBindAPI(EGL_OPENGL_API) == EGL_FALSE) { blog(LOG_ERROR, "eglBindAPI failed"); @@ -140,27 +137,22 @@ static bool egl_context_create(struct gl_platform *plat, const EGLint *attribs) blog(LOG_ERROR, "eglBindAPI failed"); } - EGLBoolean result = eglChooseConfig(plat->display, - config_attribs_native, - &plat->config, 1, &num_config); + EGLBoolean result = eglChooseConfig(plat->display, config_attribs_native, &plat->config, 1, &num_config); if (result != EGL_TRUE || num_config == 0) { - result = eglChooseConfig(plat->display, config_attribs, - &plat->config, 1, &num_config); + result = eglChooseConfig(plat->display, config_attribs, &plat->config, 1, &num_config); if (result != EGL_TRUE || num_config == 0) { blog(LOG_ERROR, "eglChooseConfig failed"); goto error; } } - plat->context = eglCreateContext(plat->display, plat->config, - EGL_NO_CONTEXT, attribs); + plat->context = eglCreateContext(plat->display, plat->config, EGL_NO_CONTEXT, attribs); if (plat->context == EGL_NO_CONTEXT) { blog(LOG_ERROR, "eglCreateContext failed"); goto error; } - success = - egl_make_current(plat->display, EGL_NO_SURFACE, plat->context); + success = egl_make_current(plat->display, EGL_NO_SURFACE, plat->context); error: return success; @@ -176,13 +168,11 @@ static bool extension_supported(const char *extensions, const char *search) { const char *result = strstr(extensions, search); unsigned long len = strlen(search); - return result != NULL && - (result == extensions || *(result - 1) == ' ') && + return result != NULL && (result == extensions || *(result - 1) == ' ') && (result[len] == ' ' || result[len] == '\0'); } -static struct gl_platform *gl_wayland_egl_platform_create(gs_device_t *device, - uint32_t adapter) +static struct gl_platform *gl_wayland_egl_platform_create(gs_device_t *device, uint32_t adapter) { struct gl_platform *plat = bmalloc(sizeof(struct gl_platform)); @@ -191,8 +181,7 @@ static struct gl_platform *gl_wayland_egl_platform_create(gs_device_t *device, device->plat = plat; const EGLAttrib plat_attribs[] = {EGL_NONE}; - plat->display = eglGetPlatformDisplay(EGL_PLATFORM_WAYLAND_EXT, - plat->wl_display, plat_attribs); + plat->display = eglGetPlatformDisplay(EGL_PLATFORM_WAYLAND_EXT, plat->wl_display, plat_attribs); if (plat->display == EGL_NO_DISPLAY) { blog(LOG_ERROR, "eglGetDisplay failed"); goto fail_display_init; @@ -216,8 +205,7 @@ static struct gl_platform *gl_wayland_egl_platform_create(gs_device_t *device, if (extension_supported(extensions, "EGL_KHR_create_context")) { attribs = khr_ctx_attribs; } else { - blog(LOG_ERROR, - "EGL_KHR_create_context extension is required to use EGL 1.4."); + blog(LOG_ERROR, "EGL_KHR_create_context extension is required to use EGL 1.4."); goto fail_context_create; } } else if (major < 1 || (major == 1 && minor < 4)) { @@ -266,8 +254,7 @@ static void gl_wayland_egl_platform_destroy(struct gl_platform *plat) static bool gl_wayland_egl_platform_init_swapchain(struct gs_swap_chain *swap) { struct gl_platform *plat = swap->device->plat; - EGLSurface egl_surface = eglCreateWindowSurface( - plat->display, plat->config, swap->wi->window, NULL); + EGLSurface egl_surface = eglCreateWindowSurface(plat->display, plat->config, swap->wi->window, NULL); if (egl_surface == EGL_NO_SURFACE) { blog(LOG_ERROR, "eglCreateWindowSurface failed"); return false; @@ -276,8 +263,7 @@ static bool gl_wayland_egl_platform_init_swapchain(struct gs_swap_chain *swap) return true; } -static void -gl_wayland_egl_platform_cleanup_swapchain(struct gs_swap_chain *swap) +static void gl_wayland_egl_platform_cleanup_swapchain(struct gs_swap_chain *swap) { struct gl_platform *plat = swap->device->plat; eglDestroySurface(plat->display, swap->wi->egl_surface); @@ -303,11 +289,9 @@ static void *gl_wayland_egl_device_get_device_obj(gs_device_t *device) return device->plat->context; } -static void gl_wayland_egl_getclientsize(const struct gs_swap_chain *swap, - uint32_t *width, uint32_t *height) +static void gl_wayland_egl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, uint32_t *height) { - wl_egl_window_get_attached_size(swap->wi->window, (void *)width, - (void *)height); + wl_egl_window_get_attached_size(swap->wi->window, (void *)width, (void *)height); } static void gl_wayland_egl_clear_context(gs_device_t *device) @@ -318,13 +302,10 @@ static void gl_wayland_egl_clear_context(gs_device_t *device) static void gl_wayland_egl_update(gs_device_t *device) { - wl_egl_window_resize(device->cur_swap->wi->window, - device->cur_swap->info.cx, - device->cur_swap->info.cy, 0, 0); + wl_egl_window_resize(device->cur_swap->wi->window, device->cur_swap->info.cx, device->cur_swap->info.cy, 0, 0); } -static void gl_wayland_egl_device_load_swapchain(gs_device_t *device, - gs_swapchain_t *swap) +static void gl_wayland_egl_device_load_swapchain(gs_device_t *device, gs_swapchain_t *swap) { if (device->cur_swap == swap) return; @@ -335,8 +316,7 @@ static void gl_wayland_egl_device_load_swapchain(gs_device_t *device, if (swap == NULL) { egl_make_current(plat->display, EGL_NO_SURFACE, EGL_NO_CONTEXT); } else { - egl_make_current(plat->display, swap->wi->egl_surface, - plat->context); + egl_make_current(plat->display, swap->wi->egl_surface, plat->context); } } @@ -352,42 +332,38 @@ static void gl_wayland_egl_device_present(gs_device_t *device) } } -static struct gs_texture *gl_wayland_egl_device_texture_create_from_dmabuf( - gs_device_t *device, unsigned int width, unsigned int height, - uint32_t drm_format, enum gs_color_format color_format, - uint32_t n_planes, const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers) +static struct gs_texture * +gl_wayland_egl_device_texture_create_from_dmabuf(gs_device_t *device, unsigned int width, unsigned int height, + uint32_t drm_format, enum gs_color_format color_format, + uint32_t n_planes, const int *fds, const uint32_t *strides, + const uint32_t *offsets, const uint64_t *modifiers) { struct gl_platform *plat = device->plat; - return gl_egl_create_dmabuf_image(plat->display, width, height, - drm_format, color_format, n_planes, - fds, strides, offsets, modifiers); + return gl_egl_create_dmabuf_image(plat->display, width, height, drm_format, color_format, n_planes, fds, + strides, offsets, modifiers); } -static bool gl_wayland_egl_device_query_dmabuf_capabilities( - gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, size_t *n_formats) +static bool gl_wayland_egl_device_query_dmabuf_capabilities(gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, + uint32_t **drm_formats, size_t *n_formats) { struct gl_platform *plat = device->plat; - return gl_egl_query_dmabuf_capabilities(plat->display, dmabuf_flags, - drm_formats, n_formats); + return gl_egl_query_dmabuf_capabilities(plat->display, dmabuf_flags, drm_formats, n_formats); } -static bool gl_wayland_egl_device_query_dmabuf_modifiers_for_format( - gs_device_t *device, uint32_t drm_format, uint64_t **modifiers, - size_t *n_modifiers) +static bool gl_wayland_egl_device_query_dmabuf_modifiers_for_format(gs_device_t *device, uint32_t drm_format, + uint64_t **modifiers, size_t *n_modifiers) { struct gl_platform *plat = device->plat; - return gl_egl_query_dmabuf_modifiers_for_format( - plat->display, drm_format, modifiers, n_modifiers); + return gl_egl_query_dmabuf_modifiers_for_format(plat->display, drm_format, modifiers, n_modifiers); } -static struct gs_texture *gl_wayland_egl_device_texture_create_from_pixmap( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t target, void *pixmap) +static struct gs_texture *gl_wayland_egl_device_texture_create_from_pixmap(gs_device_t *device, uint32_t width, + uint32_t height, + enum gs_color_format color_format, + uint32_t target, void *pixmap) { UNUSED_PARAMETER(device); UNUSED_PARAMETER(width); @@ -400,10 +376,7 @@ static struct gs_texture *gl_wayland_egl_device_texture_create_from_pixmap( } static bool gl_wayland_egl_enum_adapters(gs_device_t *device, - bool (*callback)(void *param, - const char *name, - uint32_t id), - void *param) + bool (*callback)(void *param, const char *name, uint32_t id), void *param) { return gl_egl_enum_adapters(device->plat->display, callback, param); } @@ -423,14 +396,10 @@ static const struct gl_winsys_vtable egl_wayland_winsys_vtable = { .update = gl_wayland_egl_update, .device_load_swapchain = gl_wayland_egl_device_load_swapchain, .device_present = gl_wayland_egl_device_present, - .device_texture_create_from_dmabuf = - gl_wayland_egl_device_texture_create_from_dmabuf, - .device_query_dmabuf_capabilities = - gl_wayland_egl_device_query_dmabuf_capabilities, - .device_query_dmabuf_modifiers_for_format = - gl_wayland_egl_device_query_dmabuf_modifiers_for_format, - .device_texture_create_from_pixmap = - gl_wayland_egl_device_texture_create_from_pixmap, + .device_texture_create_from_dmabuf = gl_wayland_egl_device_texture_create_from_dmabuf, + .device_query_dmabuf_capabilities = gl_wayland_egl_device_query_dmabuf_capabilities, + .device_query_dmabuf_modifiers_for_format = gl_wayland_egl_device_query_dmabuf_modifiers_for_format, + .device_texture_create_from_pixmap = gl_wayland_egl_device_texture_create_from_pixmap, .device_enum_adapters = gl_wayland_egl_enum_adapters, }; diff --git a/libobs-opengl/gl-windows.c b/libobs-opengl/gl-windows.c index b9825e384..2f39645a3 100644 --- a/libobs-opengl/gl-windows.c +++ b/libobs-opengl/gl-windows.c @@ -81,8 +81,7 @@ static inline void init_dummy_pixel_format(PIXELFORMATDESCRIPTOR *pfd) pfd->cDepthBits = 24; pfd->cStencilBits = 8; pfd->iLayerType = PFD_MAIN_PLANE; - pfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | - PFD_DOUBLEBUFFER; + pfd->dwFlags = PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER; } static const char *dummy_window_class = "GLDummyWindow"; @@ -118,8 +117,7 @@ static bool gl_register_dummy_window_class(void) static inline HWND gl_create_dummy_window(void) { - HWND hwnd = CreateWindowExA(0, dummy_window_class, "Dummy GL Window", - WS_POPUP, 0, 0, 2, 2, NULL, NULL, + HWND hwnd = CreateWindowExA(0, dummy_window_class, "Dummy GL Window", WS_POPUP, 0, 0, 2, 2, NULL, NULL, GetModuleHandle(NULL), NULL); if (!hwnd) blog(LOG_ERROR, "Could not create dummy context window"); @@ -205,14 +203,12 @@ static bool gl_dummy_context_init(struct dummy_context *dummy) init_dummy_pixel_format(&pfd); format_index = ChoosePixelFormat(dummy->hdc, &pfd); if (!format_index) { - blog(LOG_ERROR, "Dummy ChoosePixelFormat failed, %lu", - GetLastError()); + blog(LOG_ERROR, "Dummy ChoosePixelFormat failed, %lu", GetLastError()); return false; } if (!SetPixelFormat(dummy->hdc, format_index, &pfd)) { - blog(LOG_ERROR, "Dummy SetPixelFormat failed, %lu", - GetLastError()); + blog(LOG_ERROR, "Dummy SetPixelFormat failed, %lu", GetLastError()); return false; } @@ -297,11 +293,9 @@ static int gl_choose_pixel_format(HDC hdc, const struct gs_init_data *info) add_attrib(&attribs, WGL_STENCIL_BITS_ARB, stencil_bits); add_attrib(&attribs, 0, 0); - success = wglChoosePixelFormatARB(hdc, attribs.array, NULL, 1, &format, - &num_formats); + success = wglChoosePixelFormatARB(hdc, attribs.array, NULL, 1, &format, &num_formats); if (!success || !num_formats) { - blog(LOG_ERROR, "wglChoosePixelFormatARB failed, %lu", - GetLastError()); + blog(LOG_ERROR, "wglChoosePixelFormatARB failed, %lu", GetLastError()); format = 0; } @@ -310,8 +304,7 @@ static int gl_choose_pixel_format(HDC hdc, const struct gs_init_data *info) return format; } -static inline bool gl_getpixelformat(HDC hdc, const struct gs_init_data *info, - int *format, PIXELFORMATDESCRIPTOR *pfd) +static inline bool gl_getpixelformat(HDC hdc, const struct gs_init_data *info, int *format, PIXELFORMATDESCRIPTOR *pfd) { if (!format) return false; @@ -319,16 +312,14 @@ static inline bool gl_getpixelformat(HDC hdc, const struct gs_init_data *info, *format = gl_choose_pixel_format(hdc, info); if (!DescribePixelFormat(hdc, *format, sizeof(*pfd), pfd)) { - blog(LOG_ERROR, "DescribePixelFormat failed, %lu", - GetLastError()); + blog(LOG_ERROR, "DescribePixelFormat failed, %lu", GetLastError()); return false; } return true; } -static inline bool gl_setpixelformat(HDC hdc, int format, - PIXELFORMATDESCRIPTOR *pfd) +static inline bool gl_setpixelformat(HDC hdc, int format, PIXELFORMATDESCRIPTOR *pfd) { if (!SetPixelFormat(hdc, format, pfd)) { blog(LOG_ERROR, "SetPixelFormat failed, %lu", GetLastError()); @@ -369,8 +360,7 @@ static bool register_dummy_class(void) return true; if (!RegisterClassA(&wc)) { - blog(LOG_ERROR, "Failed to register dummy GL window class, %lu", - GetLastError()); + blog(LOG_ERROR, "Failed to register dummy GL window class, %lu", GetLastError()); return false; } @@ -380,28 +370,24 @@ static bool register_dummy_class(void) static bool create_dummy_window(struct gl_platform *plat) { - plat->window.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, - "OpenGL Dummy Window", WS_POPUP, 0, - 0, 1, 1, NULL, NULL, + plat->window.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, "OpenGL Dummy Window", WS_POPUP, 0, 0, 1, 1, NULL, NULL, GetModuleHandleW(NULL), NULL); if (!plat->window.hwnd) { - blog(LOG_ERROR, "Failed to create dummy GL window, %lu", - GetLastError()); + blog(LOG_ERROR, "Failed to create dummy GL window, %lu", GetLastError()); return false; } plat->window.hdc = GetDC(plat->window.hwnd); if (!plat->window.hdc) { - blog(LOG_ERROR, "Failed to get dummy GL window DC (%lu)", - GetLastError()); + blog(LOG_ERROR, "Failed to get dummy GL window DC (%lu)", GetLastError()); return false; } return true; } -static bool init_default_swap(struct gl_platform *plat, gs_device_t *device, - int pixel_format, PIXELFORMATDESCRIPTOR *pfd) +static bool init_default_swap(struct gl_platform *plat, gs_device_t *device, int pixel_format, + PIXELFORMATDESCRIPTOR *pfd) { if (!gl_setpixelformat(plat->window.hdc, pixel_format, pfd)) return false; @@ -590,8 +576,7 @@ void device_present(gs_device_t *device) } } -extern void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, - uint32_t *height) +extern void gl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, uint32_t *height) { RECT rc; if (swap) { diff --git a/libobs-opengl/gl-x11-egl.c b/libobs-opengl/gl-x11-egl.c index 9b200d1b6..1c660b737 100644 --- a/libobs-opengl/gl-x11-egl.c +++ b/libobs-opengl/gl-x11-egl.c @@ -34,8 +34,8 @@ #include -typedef EGLDisplay(EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC)( - EGLenum platform, void *native_display, const EGLint *attrib_list); +typedef EGLDisplay(EGLAPIENTRYP PFNEGLGETPLATFORMDISPLAYEXTPROC)(EGLenum platform, void *native_display, + const EGLint *attrib_list); static const int ctx_attribs[] = { #ifdef _DEBUG @@ -87,8 +87,7 @@ struct gl_platform { /* The following utility function is copied verbatim from GLX code. */ -static xcb_get_geometry_reply_t *get_window_geometry(xcb_connection_t *xcb_conn, - xcb_drawable_t drawable) +static xcb_get_geometry_reply_t *get_window_geometry(xcb_connection_t *xcb_conn, xcb_drawable_t drawable) { xcb_get_geometry_cookie_t cookie; xcb_generic_error_t *error; @@ -148,16 +147,13 @@ static EGLDisplay get_egl_display(struct gl_platform *plat) egl_client_extensions = eglQueryString(EGL_NO_DISPLAY, EGL_EXTENSIONS); PFNEGLGETPLATFORMDISPLAYEXTPROC eglGetPlatformDisplayEXT = - (PFNEGLGETPLATFORMDISPLAYEXTPROC)(strstr(egl_client_extensions, - "EGL_EXT_platform_base") - ? eglGetProcAddress( - "eglGetPlatformDisplayEXT") + (PFNEGLGETPLATFORMDISPLAYEXTPROC)(strstr(egl_client_extensions, "EGL_EXT_platform_base") + ? eglGetProcAddress("eglGetPlatformDisplayEXT") : NULL); if (eglGetPlatformDisplayEXT) { const EGLint plat_attribs[] = {EGL_NONE}; - edisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_X11_EXT, - display, plat_attribs); + edisplay = eglGetPlatformDisplayEXT(EGL_PLATFORM_X11_EXT, display, plat_attribs); if (EGL_NO_DISPLAY == edisplay) blog(LOG_ERROR, "Failed to get EGL/X11 display"); } @@ -183,54 +179,42 @@ static bool gl_context_create(struct gl_platform *plat) edisplay = get_egl_display(plat); if (EGL_NO_DISPLAY == edisplay) { - blog(LOG_ERROR, - "Failed to get EGL display using eglGetDisplay"); + blog(LOG_ERROR, "Failed to get EGL display using eglGetDisplay"); return false; } if (!eglInitialize(edisplay, &egl_maj, &egl_min)) { - blog(LOG_ERROR, "Failed to initialize EGL: %s", - get_egl_error_string()); + blog(LOG_ERROR, "Failed to initialize EGL: %s", get_egl_error_string()); return false; } - if (!eglChooseConfig(edisplay, ctx_config_attribs, &config, 1, - &frame_buf_config_count)) { - blog(LOG_ERROR, "Unable to find suitable EGL config: %s", - get_egl_error_string()); + if (!eglChooseConfig(edisplay, ctx_config_attribs, &config, 1, &frame_buf_config_count)) { + blog(LOG_ERROR, "Unable to find suitable EGL config: %s", get_egl_error_string()); goto error; } - context = - eglCreateContext(edisplay, config, EGL_NO_CONTEXT, ctx_attribs); + context = eglCreateContext(edisplay, config, EGL_NO_CONTEXT, ctx_attribs); #ifdef _DEBUG if (EGL_NO_CONTEXT == context) { const EGLint error = eglGetError(); if (error == EGL_BAD_ATTRIBUTE) { /* Sometimes creation fails because debug gl is not supported */ - blog(LOG_ERROR, - "Unable to create EGL context with DEBUG attrib, trying without"); - context = eglCreateContext(edisplay, config, - EGL_NO_CONTEXT, - ctx_attribs + 2); + blog(LOG_ERROR, "Unable to create EGL context with DEBUG attrib, trying without"); + context = eglCreateContext(edisplay, config, EGL_NO_CONTEXT, ctx_attribs + 2); } else { - blog(LOG_ERROR, "Unable to create EGL context: %s", - get_egl_error_string2(error)); + blog(LOG_ERROR, "Unable to create EGL context: %s", get_egl_error_string2(error)); goto error; } } #endif if (EGL_NO_CONTEXT == context) { - blog(LOG_ERROR, "Unable to create EGL context: %s", - get_egl_error_string()); + blog(LOG_ERROR, "Unable to create EGL context: %s", get_egl_error_string()); goto error; } - plat->pbuffer = - eglCreatePbufferSurface(edisplay, config, ctx_pbuffer_attribs); + plat->pbuffer = eglCreatePbufferSurface(edisplay, config, ctx_pbuffer_attribs); if (EGL_NO_SURFACE == plat->pbuffer) { - blog(LOG_ERROR, "Failed to create OpenGL pbuffer: %s", - get_egl_error_string()); + blog(LOG_ERROR, "Failed to create OpenGL pbuffer: %s", get_egl_error_string()); goto error; } @@ -254,13 +238,11 @@ error: static void gl_context_destroy(struct gl_platform *plat) { - eglMakeCurrent(plat->edisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, - EGL_NO_CONTEXT); + eglMakeCurrent(plat->edisplay, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT); eglDestroyContext(plat->edisplay, plat->context); } -static struct gl_windowinfo * -gl_x11_egl_windowinfo_create(const struct gs_init_data *info) +static struct gl_windowinfo *gl_x11_egl_windowinfo_create(const struct gs_init_data *info) { UNUSED_PARAMETER(info); return bmalloc(sizeof(struct gl_windowinfo)); @@ -325,8 +307,7 @@ static int x_error_handler(Display *display, XErrorEvent *error) return 0; } -static struct gl_platform *gl_x11_egl_platform_create(gs_device_t *device, - uint32_t adapter) +static struct gl_platform *gl_x11_egl_platform_create(gs_device_t *device, uint32_t adapter) { /* There's some trickery here... we're mixing libX11, xcb, and EGL For an explanation see here: http://xcb.freedesktop.org/MixingCalls/ @@ -351,10 +332,8 @@ static struct gl_platform *gl_x11_egl_platform_create(gs_device_t *device, goto fail_context_create; } - if (!eglMakeCurrent(plat->edisplay, plat->pbuffer, plat->pbuffer, - plat->context)) { - blog(LOG_ERROR, "Failed to make context current: %s", - get_egl_error_string()); + if (!eglMakeCurrent(plat->edisplay, plat->pbuffer, plat->pbuffer, plat->context)) { + blog(LOG_ERROR, "Failed to make context current: %s", get_egl_error_string()); goto fail_make_current; } @@ -398,8 +377,7 @@ static bool gl_x11_egl_platform_init_swapchain(struct gs_swap_chain *swap) xcb_connection_t *xcb_conn = XGetXCBConnection(display); xcb_window_t wid = xcb_generate_id(xcb_conn); xcb_window_t parent = swap->info.window.id; - xcb_get_geometry_reply_t *geometry = - get_window_geometry(xcb_conn, parent); + xcb_get_geometry_reply_t *geometry = get_window_geometry(xcb_conn, parent); bool status = false; int visual; @@ -408,12 +386,8 @@ static bool gl_x11_egl_platform_init_swapchain(struct gs_swap_chain *swap) goto fail_geometry_request; { - if (!eglGetConfigAttrib(plat->edisplay, plat->config, - EGL_NATIVE_VISUAL_ID, - (EGLint *)&visual)) { - blog(LOG_ERROR, - "Cannot get visual id for EGL context: %s", - get_egl_error_string()); + if (!eglGetConfigAttrib(plat->edisplay, plat->config, EGL_NATIVE_VISUAL_ID, (EGLint *)&visual)) { + blog(LOG_ERROR, "Cannot get visual id for EGL context: %s", get_egl_error_string()); goto fail_visual_id; } } @@ -422,13 +396,11 @@ static bool gl_x11_egl_platform_init_swapchain(struct gs_swap_chain *swap) uint32_t mask = XCB_CW_BORDER_PIXEL | XCB_CW_COLORMAP; uint32_t mask_values[] = {0, colormap, 0}; - xcb_create_colormap(xcb_conn, XCB_COLORMAP_ALLOC_NONE, colormap, parent, - visual); + xcb_create_colormap(xcb_conn, XCB_COLORMAP_ALLOC_NONE, colormap, parent, visual); - xcb_void_cookie_t window_cookie = xcb_create_window_checked( - xcb_conn, 24 /* Hardcoded? */, wid, parent, 0, 0, - geometry->width, geometry->height, 0, 0, visual, mask, - mask_values); + xcb_void_cookie_t window_cookie = xcb_create_window_checked(xcb_conn, 24 /* Hardcoded? */, wid, parent, 0, 0, + geometry->width, geometry->height, 0, 0, visual, + mask, mask_values); xcb_generic_error_t *err = xcb_request_check(xcb_conn, window_cookie); if (err != NULL) { char text[512]; @@ -440,11 +412,9 @@ static bool gl_x11_egl_platform_init_swapchain(struct gs_swap_chain *swap) goto fail_window_surface; } - const EGLSurface surface = - eglCreateWindowSurface(plat->edisplay, plat->config, wid, 0); + const EGLSurface surface = eglCreateWindowSurface(plat->edisplay, plat->config, wid, 0); if (EGL_NO_SURFACE == surface) { - blog(LOG_ERROR, "Cannot get window EGL surface: %s", - get_egl_error_string()); + blog(LOG_ERROR, "Cannot get window EGL surface: %s", get_egl_error_string()); goto fail_window_surface; } @@ -474,23 +444,18 @@ static void gl_x11_egl_device_enter_context(gs_device_t *device) { const EGLContext context = device->plat->context; const EGLDisplay display = device->plat->edisplay; - const EGLSurface surface = (device->cur_swap) - ? device->cur_swap->wi->surface - : device->plat->pbuffer; + const EGLSurface surface = (device->cur_swap) ? device->cur_swap->wi->surface : device->plat->pbuffer; if (!eglMakeCurrent(display, surface, surface, context)) - blog(LOG_ERROR, "Failed to make context current: %s", - get_egl_error_string()); + blog(LOG_ERROR, "Failed to make context current: %s", get_egl_error_string()); } static void gl_x11_egl_device_leave_context(gs_device_t *device) { const EGLDisplay display = device->plat->edisplay; - if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, - EGL_NO_CONTEXT)) { - blog(LOG_ERROR, "Failed to reset current context: %s", - get_egl_error_string()); + if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { + blog(LOG_ERROR, "Failed to reset current context: %s", get_egl_error_string()); } } @@ -499,15 +464,12 @@ static void *gl_x11_egl_device_get_device_obj(gs_device_t *device) return device->plat->context; } -static void gl_x11_egl_getclientsize(const struct gs_swap_chain *swap, - uint32_t *width, uint32_t *height) +static void gl_x11_egl_getclientsize(const struct gs_swap_chain *swap, uint32_t *width, uint32_t *height) { - xcb_connection_t *xcb_conn = - XGetXCBConnection(swap->device->plat->xdisplay); + xcb_connection_t *xcb_conn = XGetXCBConnection(swap->device->plat->xdisplay); xcb_window_t window = swap->wi->window; - xcb_get_geometry_reply_t *geometry = - get_window_geometry(xcb_conn, window); + xcb_get_geometry_reply_t *geometry = get_window_geometry(xcb_conn, window); if (geometry) { *width = geometry->width; *height = geometry->height; @@ -521,11 +483,9 @@ static void gl_x11_egl_update(gs_device_t *device) Display *display = device->plat->xdisplay; xcb_window_t window = device->cur_swap->wi->window; - uint32_t values[] = {device->cur_swap->info.cx, - device->cur_swap->info.cy}; + uint32_t values[] = {device->cur_swap->info.cx, device->cur_swap->info.cy}; - xcb_configure_window(XGetXCBConnection(display), window, - XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT, + xcb_configure_window(XGetXCBConnection(display), window, XCB_CONFIG_WINDOW_WIDTH | XCB_CONFIG_WINDOW_HEIGHT, values); } @@ -533,14 +493,12 @@ static void gl_x11_egl_clear_context(gs_device_t *device) { Display *display = device->plat->edisplay; - if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, - EGL_NO_CONTEXT)) { + if (!eglMakeCurrent(display, EGL_NO_SURFACE, EGL_NO_SURFACE, EGL_NO_CONTEXT)) { blog(LOG_ERROR, "Failed to reset current context."); } } -static void gl_x11_egl_device_load_swapchain(gs_device_t *device, - gs_swapchain_t *swap) +static void gl_x11_egl_device_load_swapchain(gs_device_t *device, gs_swapchain_t *swap) { if (device->cur_swap == swap) return; @@ -563,60 +521,51 @@ static void gl_x11_egl_device_present(gs_device_t *device) if (eglSwapInterval(device->plat->edisplay, 0) == EGL_FALSE) { blog(LOG_ERROR, "eglSwapInterval failed"); } - if (!eglSwapBuffers(device->plat->edisplay, - device->cur_swap->wi->surface)) - blog(LOG_ERROR, "Cannot swap EGL buffers: %s", - get_egl_error_string()); + if (!eglSwapBuffers(device->plat->edisplay, device->cur_swap->wi->surface)) + blog(LOG_ERROR, "Cannot swap EGL buffers: %s", get_egl_error_string()); } -static struct gs_texture *gl_x11_egl_device_texture_create_from_dmabuf( - gs_device_t *device, unsigned int width, unsigned int height, - uint32_t drm_format, enum gs_color_format color_format, - uint32_t n_planes, const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers) +static struct gs_texture *gl_x11_egl_device_texture_create_from_dmabuf(gs_device_t *device, unsigned int width, + unsigned int height, uint32_t drm_format, + enum gs_color_format color_format, + uint32_t n_planes, const int *fds, + const uint32_t *strides, const uint32_t *offsets, + const uint64_t *modifiers) { struct gl_platform *plat = device->plat; - return gl_egl_create_dmabuf_image(plat->edisplay, width, height, - drm_format, color_format, n_planes, - fds, strides, offsets, modifiers); + return gl_egl_create_dmabuf_image(plat->edisplay, width, height, drm_format, color_format, n_planes, fds, + strides, offsets, modifiers); } -static struct gs_texture *gl_x11_egl_device_texture_create_from_pixmap( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t target, void *pixmap) +static struct gs_texture *gl_x11_egl_device_texture_create_from_pixmap(gs_device_t *device, uint32_t width, + uint32_t height, + enum gs_color_format color_format, + uint32_t target, void *pixmap) { struct gl_platform *plat = device->plat; - return gl_egl_create_texture_from_pixmap(plat->edisplay, width, height, - color_format, target, + return gl_egl_create_texture_from_pixmap(plat->edisplay, width, height, color_format, target, (EGLClientBuffer)pixmap); } -static bool gl_x11_egl_device_query_dmabuf_capabilities( - gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, size_t *n_formats) +static bool gl_x11_egl_device_query_dmabuf_capabilities(gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, + uint32_t **drm_formats, size_t *n_formats) { struct gl_platform *plat = device->plat; - return gl_egl_query_dmabuf_capabilities(plat->edisplay, dmabuf_flags, - drm_formats, n_formats); + return gl_egl_query_dmabuf_capabilities(plat->edisplay, dmabuf_flags, drm_formats, n_formats); } -static bool gl_x11_egl_device_query_dmabuf_modifiers_for_format( - gs_device_t *device, uint32_t drm_format, uint64_t **modifiers, - size_t *n_modifiers) +static bool gl_x11_egl_device_query_dmabuf_modifiers_for_format(gs_device_t *device, uint32_t drm_format, + uint64_t **modifiers, size_t *n_modifiers) { struct gl_platform *plat = device->plat; - return gl_egl_query_dmabuf_modifiers_for_format( - plat->edisplay, drm_format, modifiers, n_modifiers); + return gl_egl_query_dmabuf_modifiers_for_format(plat->edisplay, drm_format, modifiers, n_modifiers); } -static bool gl_x11_egl_enum_adapters(gs_device_t *device, - bool (*callback)(void *param, - const char *name, - uint32_t id), +static bool gl_x11_egl_enum_adapters(gs_device_t *device, bool (*callback)(void *param, const char *name, uint32_t id), void *param) { return gl_egl_enum_adapters(device->plat->edisplay, callback, param); @@ -637,14 +586,10 @@ static const struct gl_winsys_vtable egl_x11_winsys_vtable = { .update = gl_x11_egl_update, .device_load_swapchain = gl_x11_egl_device_load_swapchain, .device_present = gl_x11_egl_device_present, - .device_texture_create_from_dmabuf = - gl_x11_egl_device_texture_create_from_dmabuf, - .device_query_dmabuf_capabilities = - gl_x11_egl_device_query_dmabuf_capabilities, - .device_query_dmabuf_modifiers_for_format = - gl_x11_egl_device_query_dmabuf_modifiers_for_format, - .device_texture_create_from_pixmap = - gl_x11_egl_device_texture_create_from_pixmap, + .device_texture_create_from_dmabuf = gl_x11_egl_device_texture_create_from_dmabuf, + .device_query_dmabuf_capabilities = gl_x11_egl_device_query_dmabuf_capabilities, + .device_query_dmabuf_modifiers_for_format = gl_x11_egl_device_query_dmabuf_modifiers_for_format, + .device_texture_create_from_pixmap = gl_x11_egl_device_texture_create_from_pixmap, .device_enum_adapters = gl_x11_egl_enum_adapters, }; diff --git a/libobs-opengl/gl-zstencil.c b/libobs-opengl/gl-zstencil.c index 48bcfbab2..51f7ccfd5 100644 --- a/libobs-opengl/gl-zstencil.c +++ b/libobs-opengl/gl-zstencil.c @@ -17,8 +17,7 @@ #include "gl-subsystem.h" -static bool gl_init_zsbuffer(struct gs_zstencil_buffer *zs, uint32_t width, - uint32_t height) +static bool gl_init_zsbuffer(struct gs_zstencil_buffer *zs, uint32_t width, uint32_t height) { glGenRenderbuffers(1, &zs->buffer); if (!gl_success("glGenRenderbuffers")) @@ -53,8 +52,7 @@ static inline GLenum get_attachment(enum gs_zstencil_format format) return 0; } -gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width, - uint32_t height, +gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width, uint32_t height, enum gs_zstencil_format format) { struct gs_zstencil_buffer *zs; diff --git a/libobs-winrt/winrt-capture.cpp b/libobs-winrt/winrt-capture.cpp index a7bef794b..8cdcf5aa3 100644 --- a/libobs-winrt/winrt-capture.cpp +++ b/libobs-winrt/winrt-capture.cpp @@ -3,84 +3,65 @@ extern "C" EXPORT BOOL winrt_capture_supported() try { /* no contract for IGraphicsCaptureItemInterop, verify 10.0.18362.0 */ - return winrt::Windows::Foundation::Metadata::ApiInformation:: - IsApiContractPresent(L"Windows.Foundation.UniversalApiContract", - 8); + return winrt::Windows::Foundation::Metadata::ApiInformation::IsApiContractPresent( + L"Windows.Foundation.UniversalApiContract", 8); } catch (const winrt::hresult_error &err) { - blog(LOG_ERROR, "winrt_capture_supported (0x%08X): %s", - err.code().value, winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "winrt_capture_supported (0x%08X): %s", err.code().value, + winrt::to_string(err.message()).c_str()); return false; } catch (...) { - blog(LOG_ERROR, "winrt_capture_supported (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "winrt_capture_supported (0x%08X)", winrt::to_hresult().value); return false; } extern "C" EXPORT BOOL winrt_capture_cursor_toggle_supported() try { - return winrt::Windows::Foundation::Metadata::ApiInformation:: - IsPropertyPresent( - L"Windows.Graphics.Capture.GraphicsCaptureSession", - L"IsCursorCaptureEnabled"); + return winrt::Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent( + L"Windows.Graphics.Capture.GraphicsCaptureSession", L"IsCursorCaptureEnabled"); } catch (const winrt::hresult_error &err) { - blog(LOG_ERROR, "winrt_capture_cursor_toggle_supported (0x%08X): %s", - err.code().value, winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "winrt_capture_cursor_toggle_supported (0x%08X): %s", err.code().value, + winrt::to_string(err.message()).c_str()); return false; } catch (...) { - blog(LOG_ERROR, "winrt_capture_cursor_toggle_supported (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "winrt_capture_cursor_toggle_supported (0x%08X)", winrt::to_hresult().value); return false; } template -static winrt::com_ptr GetDXGIInterfaceFromObject( - winrt::Windows::Foundation::IInspectable const &object) +static winrt::com_ptr GetDXGIInterfaceFromObject(winrt::Windows::Foundation::IInspectable const &object) { - auto access = object.as(); + auto access = object.as(); winrt::com_ptr result; - winrt::check_hresult( - access->GetInterface(winrt::guid_of(), result.put_void())); + winrt::check_hresult(access->GetInterface(winrt::guid_of(), result.put_void())); return result; } -static bool get_client_box(HWND window, uint32_t width, uint32_t height, - D3D11_BOX *client_box) +static bool get_client_box(HWND window, uint32_t width, uint32_t height, D3D11_BOX *client_box) { RECT client_rect{}, window_rect{}; POINT upper_left{}; /* check iconic (minimized) twice, ABA is very unlikely */ - bool client_box_available = - !IsIconic(window) && GetClientRect(window, &client_rect) && - !IsIconic(window) && (client_rect.right > 0) && - (client_rect.bottom > 0) && - (DwmGetWindowAttribute(window, DWMWA_EXTENDED_FRAME_BOUNDS, - &window_rect, - sizeof(window_rect)) == S_OK) && - ClientToScreen(window, &upper_left); + bool client_box_available = !IsIconic(window) && GetClientRect(window, &client_rect) && !IsIconic(window) && + (client_rect.right > 0) && (client_rect.bottom > 0) && + (DwmGetWindowAttribute(window, DWMWA_EXTENDED_FRAME_BOUNDS, &window_rect, + sizeof(window_rect)) == S_OK) && + ClientToScreen(window, &upper_left); if (client_box_available) { - const uint32_t left = - (upper_left.x > window_rect.left) - ? (upper_left.x - window_rect.left) - : 0; + const uint32_t left = (upper_left.x > window_rect.left) ? (upper_left.x - window_rect.left) : 0; client_box->left = left; - const uint32_t top = (upper_left.y > window_rect.top) - ? (upper_left.y - window_rect.top) - : 0; + const uint32_t top = (upper_left.y > window_rect.top) ? (upper_left.y - window_rect.top) : 0; client_box->top = top; uint32_t texture_width = 1; if (width > left) { - texture_width = - min(width - left, (uint32_t)client_rect.right); + texture_width = min(width - left, (uint32_t)client_rect.right); } uint32_t texture_height = 1; if (height > top) { - texture_height = - min(height - top, (uint32_t)client_rect.bottom); + texture_height = min(height - top, (uint32_t)client_rect.bottom); } client_box->right = left + texture_width; @@ -89,15 +70,13 @@ static bool get_client_box(HWND window, uint32_t width, uint32_t height, client_box->front = 0; client_box->back = 1; - client_box_available = (client_box->right <= width) && - (client_box->bottom <= height); + client_box_available = (client_box->right <= width) && (client_box->bottom <= height); } return client_box_available; } -static DXGI_FORMAT get_pixel_format(HWND window, HMONITOR monitor, - BOOL force_sdr) +static DXGI_FORMAT get_pixel_format(HWND window, HMONITOR monitor, BOOL force_sdr) { static constexpr DXGI_FORMAT sdr_format = DXGI_FORMAT_B8G8R8A8_UNORM; @@ -107,9 +86,7 @@ static DXGI_FORMAT get_pixel_format(HWND window, HMONITOR monitor, if (window) monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST); - return (monitor && gs_is_monitor_hdr(monitor)) - ? DXGI_FORMAT_R16G16B16A16_FLOAT - : sdr_format; + return (monitor && gs_is_monitor_hdr(monitor)) ? DXGI_FORMAT_R16G16B16A16_FLOAT : sdr_format; } struct winrt_capture { @@ -125,18 +102,13 @@ struct winrt_capture { gs_texture_t *texture; bool texture_written; winrt::Windows::Graphics::Capture::GraphicsCaptureItem item{nullptr}; - winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device{ - nullptr}; + winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device{nullptr}; ComPtr context; - winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool frame_pool{ - nullptr}; - winrt::Windows::Graphics::Capture::GraphicsCaptureSession session{ - nullptr}; + winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool frame_pool{nullptr}; + winrt::Windows::Graphics::Capture::GraphicsCaptureSession session{nullptr}; winrt::Windows::Graphics::SizeInt32 last_size; - winrt::Windows::Graphics::Capture::GraphicsCaptureItem::Closed_revoker - closed; - winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool:: - FrameArrived_revoker frame_arrived; + winrt::Windows::Graphics::Capture::GraphicsCaptureItem::Closed_revoker closed; + winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::FrameArrived_revoker frame_arrived; uint32_t texture_width; uint32_t texture_height; @@ -145,25 +117,20 @@ struct winrt_capture { BOOL active; struct winrt_capture *next; - void on_closed( - winrt::Windows::Graphics::Capture::GraphicsCaptureItem const &, - winrt::Windows::Foundation::IInspectable const &) + void on_closed(winrt::Windows::Graphics::Capture::GraphicsCaptureItem const &, + winrt::Windows::Foundation::IInspectable const &) { active = FALSE; } - void on_frame_arrived(winrt::Windows::Graphics::Capture:: - Direct3D11CaptureFramePool const &sender, + void on_frame_arrived(winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool const &sender, winrt::Windows::Foundation::IInspectable const &) { - const winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame - frame = sender.TryGetNextFrame(); - const winrt::Windows::Graphics::SizeInt32 frame_content_size = - frame.ContentSize(); + const winrt::Windows::Graphics::Capture::Direct3D11CaptureFrame frame = sender.TryGetNextFrame(); + const winrt::Windows::Graphics::SizeInt32 frame_content_size = frame.ContentSize(); winrt::com_ptr frame_surface = - GetDXGIInterfaceFromObject( - frame.Surface()); + GetDXGIInterfaceFromObject(frame.Surface()); /* need GetDesc because ContentSize is not reliable */ D3D11_TEXTURE2D_DESC desc; @@ -171,28 +138,19 @@ struct winrt_capture { obs_enter_graphics(); - if (desc.Format == - get_pixel_format(window, monitor, force_sdr)) { - if (!client_area || - get_client_box(window, desc.Width, desc.Height, - &client_box)) { + if (desc.Format == get_pixel_format(window, monitor, force_sdr)) { + if (!client_area || get_client_box(window, desc.Width, desc.Height, &client_box)) { if (client_area) { - texture_width = client_box.right - - client_box.left; - texture_height = client_box.bottom - - client_box.top; + texture_width = client_box.right - client_box.left; + texture_height = client_box.bottom - client_box.top; } else { texture_width = desc.Width; texture_height = desc.Height; } if (texture) { - if (texture_width != - gs_texture_get_width( - texture) || - texture_height != - gs_texture_get_height( - texture)) { + if (texture_width != gs_texture_get_width(texture) || + texture_height != gs_texture_get_height(texture)) { gs_texture_destroy(texture); texture = nullptr; } @@ -200,28 +158,18 @@ struct winrt_capture { if (!texture) { const gs_color_format color_format = - desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT - ? GS_RGBA16F - : GS_BGRA; - texture = gs_texture_create( - texture_width, texture_height, - color_format, 1, NULL, 0); + desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT ? GS_RGBA16F : GS_BGRA; + texture = gs_texture_create(texture_width, texture_height, color_format, 1, + NULL, 0); } if (client_area) { - context->CopySubresourceRegion( - (ID3D11Texture2D *) - gs_texture_get_obj( - texture), - 0, 0, 0, 0, frame_surface.get(), - 0, &client_box); + context->CopySubresourceRegion((ID3D11Texture2D *)gs_texture_get_obj(texture), + 0, 0, 0, 0, frame_surface.get(), 0, &client_box); } else { /* if they gave an SRV, we could avoid this copy */ - context->CopyResource( - (ID3D11Texture2D *) - gs_texture_get_obj( - texture), - frame_surface.get()); + context->CopyResource((ID3D11Texture2D *)gs_texture_get_obj(texture), + frame_surface.get()); } texture_written = true; @@ -232,11 +180,8 @@ struct winrt_capture { format = desc.Format; frame_pool.Recreate( device, - static_cast< - winrt::Windows::Graphics::DirectX:: - DirectXPixelFormat>( - format), - 2, frame_content_size); + static_cast(format), 2, + frame_content_size); last_size = frame_content_size; } @@ -260,22 +205,19 @@ static void winrt_capture_device_loss_release(void *data) try { capture->frame_pool.Close(); } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, - "Direct3D11CaptureFramePool::Close (0x%08X): %s", - err.code().value, winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "Direct3D11CaptureFramePool::Close (0x%08X): %s", err.code().value, + winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "Direct3D11CaptureFramePool::Close (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "Direct3D11CaptureFramePool::Close (0x%08X)", winrt::to_hresult().value); } try { capture->session.Close(); } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, "GraphicsCaptureSession::Close (0x%08X): %s", - err.code().value, winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "GraphicsCaptureSession::Close (0x%08X): %s", err.code().value, + winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "GraphicsCaptureSession::Close (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "GraphicsCaptureSession::Close (0x%08X)", winrt::to_hresult().value); } capture->session = nullptr; @@ -287,63 +229,48 @@ static void winrt_capture_device_loss_release(void *data) static bool winrt_capture_border_toggle_supported() try { - return winrt::Windows::Foundation::Metadata::ApiInformation:: - IsPropertyPresent( - L"Windows.Graphics.Capture.GraphicsCaptureSession", - L"IsBorderRequired"); + return winrt::Windows::Foundation::Metadata::ApiInformation::IsPropertyPresent( + L"Windows.Graphics.Capture.GraphicsCaptureSession", L"IsBorderRequired"); } catch (const winrt::hresult_error &err) { - blog(LOG_ERROR, "winrt_capture_border_toggle_supported (0x%08X): %s", - err.code().value, winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "winrt_capture_border_toggle_supported (0x%08X): %s", err.code().value, + winrt::to_string(err.message()).c_str()); return false; } catch (...) { - blog(LOG_ERROR, "winrt_capture_border_toggle_supported (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "winrt_capture_border_toggle_supported (0x%08X)", winrt::to_hresult().value); return false; } static winrt::Windows::Graphics::Capture::GraphicsCaptureItem -winrt_capture_create_item(IGraphicsCaptureItemInterop *const interop_factory, - HWND window, HMONITOR monitor) +winrt_capture_create_item(IGraphicsCaptureItemInterop *const interop_factory, HWND window, HMONITOR monitor) { winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = {nullptr}; if (window) { try { const HRESULT hr = interop_factory->CreateForWindow( - window, - winrt::guid_of(), - reinterpret_cast( - winrt::put_abi(item))); + window, winrt::guid_of(), + reinterpret_cast(winrt::put_abi(item))); if (FAILED(hr)) blog(LOG_ERROR, "CreateForWindow (0x%08X)", hr); } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, "CreateForWindow (0x%08X): %s", - err.code().value, + blog(LOG_ERROR, "CreateForWindow (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "CreateForWindow (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "CreateForWindow (0x%08X)", winrt::to_hresult().value); } } else { assert(monitor); try { const HRESULT hr = interop_factory->CreateForMonitor( - monitor, - winrt::guid_of(), - reinterpret_cast( - winrt::put_abi(item))); + monitor, winrt::guid_of(), + reinterpret_cast(winrt::put_abi(item))); if (FAILED(hr)) - blog(LOG_ERROR, "CreateForMonitor (0x%08X)", - hr); + blog(LOG_ERROR, "CreateForMonitor (0x%08X)", hr); } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, "CreateForMonitor (0x%08X): %s", - err.code().value, + blog(LOG_ERROR, "CreateForMonitor (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "CreateForMonitor (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "CreateForMonitor (0x%08X)", winrt::to_hresult().value); } } @@ -354,13 +281,11 @@ static void winrt_capture_device_loss_rebuild(void *device_void, void *data) { winrt_capture *capture = static_cast(data); - auto activation_factory = winrt::get_activation_factory< - winrt::Windows::Graphics::Capture::GraphicsCaptureItem>(); - auto interop_factory = - activation_factory.as(); + auto activation_factory = + winrt::get_activation_factory(); + auto interop_factory = activation_factory.as(); winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = - winrt_capture_create_item(interop_factory.get(), - capture->window, capture->monitor); + winrt_capture_create_item(interop_factory.get(), capture->window, capture->monitor); if (!item) return; @@ -370,61 +295,47 @@ static void winrt_capture_device_loss_rebuild(void *device_void, void *data) blog(LOG_ERROR, "Failed to get DXGI device"); winrt::com_ptr inspectable; - if (FAILED(CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(), - inspectable.put()))) + if (FAILED(CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(), inspectable.put()))) blog(LOG_ERROR, "Failed to get WinRT device"); - const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice - device = inspectable.as(); - const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool - frame_pool = winrt::Windows::Graphics::Capture:: - Direct3D11CaptureFramePool::Create( - device, - static_cast( - capture->format), - 2, capture->last_size); - const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session = - frame_pool.CreateCaptureSession(item); + const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device = + inspectable.as(); + const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool frame_pool = + winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::Create( + device, static_cast(capture->format), 2, + capture->last_size); + const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session = frame_pool.CreateCaptureSession(item); if (winrt_capture_border_toggle_supported()) { - winrt::Windows::Graphics::Capture::GraphicsCaptureAccess:: - RequestAccessAsync( - winrt::Windows::Graphics::Capture:: - GraphicsCaptureAccessKind::Borderless) - .get(); + winrt::Windows::Graphics::Capture::GraphicsCaptureAccess::RequestAccessAsync( + winrt::Windows::Graphics::Capture::GraphicsCaptureAccessKind::Borderless) + .get(); session.IsBorderRequired(false); } if (winrt_capture_cursor_toggle_supported()) - session.IsCursorCaptureEnabled(capture->capture_cursor && - capture->cursor_visible); + session.IsCursorCaptureEnabled(capture->capture_cursor && capture->cursor_visible); capture->item = item; capture->device = device; d3d_device->GetImmediateContext(&capture->context); capture->frame_pool = frame_pool; capture->session = session; - capture->frame_arrived = frame_pool.FrameArrived( - winrt::auto_revoke, - {capture, &winrt_capture::on_frame_arrived}); + capture->frame_arrived = + frame_pool.FrameArrived(winrt::auto_revoke, {capture, &winrt_capture::on_frame_arrived}); try { session.StartCapture(); capture->active = TRUE; } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, "StartCapture (0x%08X): %s", err.code().value, - winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "StartCapture (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "StartCapture (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "StartCapture (0x%08X)", winrt::to_hresult().value); } } -static struct winrt_capture * -winrt_capture_init_internal(BOOL cursor, HWND window, BOOL client_area, - BOOL force_sdr, HMONITOR monitor) +static struct winrt_capture *winrt_capture_init_internal(BOOL cursor, HWND window, BOOL client_area, BOOL force_sdr, + HMONITOR monitor) try { ID3D11Device *const d3d_device = (ID3D11Device *)gs_get_device_obj(); ComPtr dxgi_device; @@ -436,50 +347,38 @@ try { } winrt::com_ptr inspectable; - hr = CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(), - inspectable.put()); + hr = CreateDirect3D11DeviceFromDXGIDevice(dxgi_device.Get(), inspectable.put()); if (FAILED(hr)) { blog(LOG_ERROR, "Failed to get WinRT device"); return nullptr; } - auto activation_factory = winrt::get_activation_factory< - winrt::Windows::Graphics::Capture::GraphicsCaptureItem>(); - auto interop_factory = - activation_factory.as(); + auto activation_factory = + winrt::get_activation_factory(); + auto interop_factory = activation_factory.as(); winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = - winrt_capture_create_item(interop_factory.get(), window, - monitor); + winrt_capture_create_item(interop_factory.get(), window, monitor); if (!item) return nullptr; - const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice - device = inspectable.as(); + const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device = + inspectable.as(); const winrt::Windows::Graphics::SizeInt32 size = item.Size(); const DXGI_FORMAT format = get_pixel_format(window, monitor, force_sdr); - const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool - frame_pool = winrt::Windows::Graphics::Capture:: - Direct3D11CaptureFramePool::Create( - device, - static_cast(format), - 2, size); - const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session = - frame_pool.CreateCaptureSession(item); + const winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool frame_pool = + winrt::Windows::Graphics::Capture::Direct3D11CaptureFramePool::Create( + device, static_cast(format), 2, size); + const winrt::Windows::Graphics::Capture::GraphicsCaptureSession session = frame_pool.CreateCaptureSession(item); if (winrt_capture_border_toggle_supported()) { - winrt::Windows::Graphics::Capture::GraphicsCaptureAccess:: - RequestAccessAsync( - winrt::Windows::Graphics::Capture:: - GraphicsCaptureAccessKind::Borderless) - .get(); + winrt::Windows::Graphics::Capture::GraphicsCaptureAccess::RequestAccessAsync( + winrt::Windows::Graphics::Capture::GraphicsCaptureAccessKind::Borderless) + .get(); session.IsBorderRequired(false); } /* disable cursor capture if possible since ours performs better */ - const BOOL cursor_toggle_supported = - winrt_capture_cursor_toggle_supported(); + const BOOL cursor_toggle_supported = winrt_capture_cursor_toggle_supported(); if (cursor_toggle_supported) session.IsCursorCaptureEnabled(cursor); @@ -497,11 +396,9 @@ try { capture->frame_pool = frame_pool; capture->session = session; capture->last_size = size; - capture->closed = item.Closed(winrt::auto_revoke, - {capture, &winrt_capture::on_closed}); - capture->frame_arrived = frame_pool.FrameArrived( - winrt::auto_revoke, - {capture, &winrt_capture::on_frame_arrived}); + capture->closed = item.Closed(winrt::auto_revoke, {capture, &winrt_capture::on_closed}); + capture->frame_arrived = + frame_pool.FrameArrived(winrt::auto_revoke, {capture, &winrt_capture::on_frame_arrived}); capture->next = capture_list; capture_list = capture; @@ -517,28 +414,22 @@ try { return capture; } catch (const winrt::hresult_error &err) { - blog(LOG_ERROR, "winrt_capture_init (0x%08X): %s", err.code().value, - winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "winrt_capture_init (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); return nullptr; } catch (...) { - blog(LOG_ERROR, "winrt_capture_init (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "winrt_capture_init (0x%08X)", winrt::to_hresult().value); return nullptr; } -extern "C" EXPORT struct winrt_capture * -winrt_capture_init_window(BOOL cursor, HWND window, BOOL client_area, - BOOL force_sdr) +extern "C" EXPORT struct winrt_capture *winrt_capture_init_window(BOOL cursor, HWND window, BOOL client_area, + BOOL force_sdr) { - return winrt_capture_init_internal(cursor, window, client_area, - force_sdr, NULL); + return winrt_capture_init_internal(cursor, window, client_area, force_sdr, NULL); } -extern "C" EXPORT struct winrt_capture * -winrt_capture_init_monitor(BOOL cursor, HMONITOR monitor, BOOL force_sdr) +extern "C" EXPORT struct winrt_capture *winrt_capture_init_monitor(BOOL cursor, HMONITOR monitor, BOOL force_sdr) { - return winrt_capture_init_internal(cursor, NULL, false, force_sdr, - monitor); + return winrt_capture_init_internal(cursor, NULL, false, force_sdr, monitor); } extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture) @@ -569,28 +460,20 @@ extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture) if (capture->frame_pool) capture->frame_pool.Close(); } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, - "Direct3D11CaptureFramePool::Close (0x%08X): %s", - err.code().value, + blog(LOG_ERROR, "Direct3D11CaptureFramePool::Close (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, - "Direct3D11CaptureFramePool::Close (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "Direct3D11CaptureFramePool::Close (0x%08X)", winrt::to_hresult().value); } try { if (capture->session) capture->session.Close(); } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, - "GraphicsCaptureSession::Close (0x%08X): %s", - err.code().value, + blog(LOG_ERROR, "GraphicsCaptureSession::Close (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, - "GraphicsCaptureSession::Close (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "GraphicsCaptureSession::Close (0x%08X)", winrt::to_hresult().value); } delete capture; @@ -602,40 +485,32 @@ extern "C" EXPORT BOOL winrt_capture_active(const struct winrt_capture *capture) return capture->active; } -extern "C" EXPORT BOOL winrt_capture_show_cursor(struct winrt_capture *capture, - BOOL visible) +extern "C" EXPORT BOOL winrt_capture_show_cursor(struct winrt_capture *capture, BOOL visible) { BOOL success = FALSE; try { if (capture->capture_cursor) { if (capture->cursor_visible != visible) { - capture->session.IsCursorCaptureEnabled( - visible); + capture->session.IsCursorCaptureEnabled(visible); capture->cursor_visible = visible; } } success = TRUE; } catch (winrt::hresult_error &err) { - blog(LOG_ERROR, - "GraphicsCaptureSession::IsCursorCaptureEnabled (0x%08X): %s", - err.code().value, winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "GraphicsCaptureSession::IsCursorCaptureEnabled (0x%08X): %s", err.code().value, + winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, - "GraphicsCaptureSession::IsCursorCaptureEnabled (0x%08X)", - winrt::to_hresult().value); + blog(LOG_ERROR, "GraphicsCaptureSession::IsCursorCaptureEnabled (0x%08X)", winrt::to_hresult().value); } return success; } -extern "C" EXPORT enum gs_color_space -winrt_capture_get_color_space(const struct winrt_capture *capture) +extern "C" EXPORT enum gs_color_space winrt_capture_get_color_space(const struct winrt_capture *capture) { - return (capture->format == DXGI_FORMAT_R16G16B16A16_FLOAT) - ? GS_CS_709_EXTENDED - : GS_CS_SRGB; + return (capture->format == DXGI_FORMAT_R16G16B16A16_FLOAT) ? GS_CS_709_EXTENDED : GS_CS_SRGB; } extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture) @@ -649,23 +524,19 @@ extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture) case GS_CS_SRGB: case GS_CS_SRGB_16F: tech_name = "DrawMultiplyTonemap"; - multiplier = - 80.f / obs_get_video_sdr_white_level(); + multiplier = 80.f / obs_get_video_sdr_white_level(); break; case GS_CS_709_EXTENDED: tech_name = "DrawMultiply"; - multiplier = - 80.f / obs_get_video_sdr_white_level(); + multiplier = 80.f / obs_get_video_sdr_white_level(); } } else if (current_space == GS_CS_709_SCRGB) { tech_name = "DrawMultiply"; multiplier = obs_get_video_sdr_white_level() / 80.f; } - gs_effect_t *const effect = - obs_get_base_effect(OBS_EFFECT_DEFAULT); - gs_technique_t *tech = - gs_effect_get_technique(effect, tech_name); + gs_effect_t *const effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); + gs_technique_t *tech = gs_effect_get_technique(effect, tech_name); const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(true); @@ -674,11 +545,8 @@ extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture) gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); gs_texture_t *const texture = capture->texture; - gs_effect_set_texture_srgb( - gs_effect_get_param_by_name(effect, "image"), texture); - gs_effect_set_float(gs_effect_get_param_by_name(effect, - "multiplier"), - multiplier); + gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), texture); + gs_effect_set_float(gs_effect_get_param_by_name(effect, "multiplier"), multiplier); const size_t passes = gs_technique_begin(tech); for (size_t i = 0; i < passes; i++) { @@ -696,14 +564,12 @@ extern "C" EXPORT void winrt_capture_render(struct winrt_capture *capture) } } -extern "C" EXPORT uint32_t -winrt_capture_width(const struct winrt_capture *capture) +extern "C" EXPORT uint32_t winrt_capture_width(const struct winrt_capture *capture) { return capture ? capture->texture_width : 0; } -extern "C" EXPORT uint32_t -winrt_capture_height(const struct winrt_capture *capture) +extern "C" EXPORT uint32_t winrt_capture_height(const struct winrt_capture *capture) { return capture ? capture->texture_height : 0; } diff --git a/libobs-winrt/winrt-capture.h b/libobs-winrt/winrt-capture.h index cd38c50ef..a334003b8 100644 --- a/libobs-winrt/winrt-capture.h +++ b/libobs-winrt/winrt-capture.h @@ -11,18 +11,13 @@ extern "C" { EXPORT BOOL winrt_capture_supported(); EXPORT BOOL winrt_capture_cursor_toggle_supported(); -EXPORT struct winrt_capture *winrt_capture_init_window(BOOL cursor, HWND window, - BOOL client_area, - BOOL force_sdr); -EXPORT struct winrt_capture * -winrt_capture_init_monitor(BOOL cursor, HMONITOR monitor, BOOL force_sdr); +EXPORT struct winrt_capture *winrt_capture_init_window(BOOL cursor, HWND window, BOOL client_area, BOOL force_sdr); +EXPORT struct winrt_capture *winrt_capture_init_monitor(BOOL cursor, HMONITOR monitor, BOOL force_sdr); EXPORT void winrt_capture_free(struct winrt_capture *capture); EXPORT BOOL winrt_capture_active(const struct winrt_capture *capture); -EXPORT BOOL winrt_capture_show_cursor(struct winrt_capture *capture, - BOOL visible); -EXPORT enum gs_color_space -winrt_capture_get_color_space(const struct winrt_capture *capture); +EXPORT BOOL winrt_capture_show_cursor(struct winrt_capture *capture, BOOL visible); +EXPORT enum gs_color_space winrt_capture_get_color_space(const struct winrt_capture *capture); EXPORT void winrt_capture_render(struct winrt_capture *capture); EXPORT uint32_t winrt_capture_width(const struct winrt_capture *capture); EXPORT uint32_t winrt_capture_height(const struct winrt_capture *capture); diff --git a/libobs-winrt/winrt-dispatch.cpp b/libobs-winrt/winrt-dispatch.cpp index c3bf24e76..3751f99e4 100644 --- a/libobs-winrt/winrt-dispatch.cpp +++ b/libobs-winrt/winrt-dispatch.cpp @@ -8,18 +8,14 @@ extern "C" EXPORT void winrt_uninitialize() winrt::uninit_apartment(); } -static winrt::Windows::System::DispatcherQueueController -CreateDispatcherQueueController() +static winrt::Windows::System::DispatcherQueueController CreateDispatcherQueueController() { - DispatcherQueueOptions options{sizeof(DispatcherQueueOptions), - DQTYPE_THREAD_CURRENT, DQTAT_COM_STA}; + DispatcherQueueOptions options{sizeof(DispatcherQueueOptions), DQTYPE_THREAD_CURRENT, DQTAT_COM_STA}; winrt::Windows::System::DispatcherQueueController controller{nullptr}; winrt::check_hresult(CreateDispatcherQueueController( options, - reinterpret_cast< - ABI::Windows::System::IDispatcherQueueController **>( - winrt::put_abi(controller)))); + reinterpret_cast(winrt::put_abi(controller)))); return controller; } @@ -31,36 +27,30 @@ extern "C" EXPORT struct winrt_disaptcher *winrt_dispatcher_init() { struct winrt_disaptcher *dispatcher = NULL; try { - if (winrt::Windows::Foundation::Metadata::ApiInformation:: - IsApiContractPresent( - L"Windows.Foundation.UniversalApiContract", - 5)) { - winrt::Windows::System::DispatcherQueueController - controller = CreateDispatcherQueueController(); + if (winrt::Windows::Foundation::Metadata::ApiInformation::IsApiContractPresent( + L"Windows.Foundation.UniversalApiContract", 5)) { + winrt::Windows::System::DispatcherQueueController controller = + CreateDispatcherQueueController(); dispatcher = new struct winrt_disaptcher; dispatcher->controller = std::move(controller); } } catch (const winrt::hresult_error &err) { - blog(LOG_ERROR, "winrt_dispatcher_init (0x%08X): %s", - (int32_t)err.code(), + blog(LOG_ERROR, "winrt_dispatcher_init (0x%08X): %s", (int32_t)err.code(), winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "winrt_dispatcher_init (0x%08X)", - (int32_t)winrt::to_hresult()); + blog(LOG_ERROR, "winrt_dispatcher_init (0x%08X)", (int32_t)winrt::to_hresult()); } return dispatcher; } -extern "C" EXPORT void -winrt_dispatcher_free(struct winrt_disaptcher *dispatcher) +extern "C" EXPORT void winrt_dispatcher_free(struct winrt_disaptcher *dispatcher) try { delete dispatcher; } catch (const winrt::hresult_error &err) { - blog(LOG_ERROR, "winrt_dispatcher_free (0x%08X): %s", - (int32_t)err.code(), winrt::to_string(err.message()).c_str()); + blog(LOG_ERROR, "winrt_dispatcher_free (0x%08X): %s", (int32_t)err.code(), + winrt::to_string(err.message()).c_str()); } catch (...) { - blog(LOG_ERROR, "winrt_dispatcher_free (0x%08X)", - (int32_t)winrt::to_hresult()); + blog(LOG_ERROR, "winrt_dispatcher_free (0x%08X)", (int32_t)winrt::to_hresult()); } diff --git a/libobs/audio-monitoring/osx/coreaudio-enum-devices.c b/libobs/audio-monitoring/osx/coreaudio-enum-devices.c index 68f9e76ff..7961ef640 100644 --- a/libobs/audio-monitoring/osx/coreaudio-enum-devices.c +++ b/libobs/audio-monitoring/osx/coreaudio-enum-devices.c @@ -7,8 +7,7 @@ #include "mac-helpers.h" -static bool obs_enum_audio_monitoring_device(obs_enum_audio_device_cb cb, - void *data, AudioDeviceID id, +static bool obs_enum_audio_monitoring_device(obs_enum_audio_device_cb cb, void *data, AudioDeviceID id, bool allow_inputs) { UInt32 size = 0; @@ -19,8 +18,7 @@ static bool obs_enum_audio_monitoring_device(obs_enum_audio_device_cb cb, OSStatus stat; bool cont = true; - AudioObjectPropertyAddress addr = {kAudioDevicePropertyStreams, - kAudioDevicePropertyScopeOutput, + AudioObjectPropertyAddress addr = {kAudioDevicePropertyStreams, kAudioDevicePropertyScopeOutput, kAudioObjectPropertyElementMain}; /* Check if the device is capable of audio output. */ @@ -64,11 +62,9 @@ fail: return cont; } -static void enum_audio_devices(obs_enum_audio_device_cb cb, void *data, - bool allow_inputs) +static void enum_audio_devices(obs_enum_audio_device_cb cb, void *data, bool allow_inputs) { - AudioObjectPropertyAddress addr = {kAudioHardwarePropertyDevices, - kAudioObjectPropertyScopeGlobal, + AudioObjectPropertyAddress addr = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; UInt32 size = 0; @@ -76,20 +72,17 @@ static void enum_audio_devices(obs_enum_audio_device_cb cb, void *data, OSStatus stat; AudioDeviceID *ids; - stat = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, - 0, NULL, &size); + stat = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, 0, NULL, &size); if (!success(stat, "get data size")) return; ids = malloc(size); count = size / sizeof(AudioDeviceID); - stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, - NULL, &size, ids); + stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, NULL, &size, ids); if (success(stat, "get data")) { for (UInt32 i = 0; i < count; i++) { - if (!obs_enum_audio_monitoring_device(cb, data, ids[i], - allow_inputs)) + if (!obs_enum_audio_monitoring_device(cb, data, ids[i], allow_inputs)) break; } } @@ -113,10 +106,8 @@ static bool alloc_default_id(void *data, const char *name, const char *id) static void get_default_id(char **p_id) { - AudioObjectPropertyAddress addr = { - kAudioHardwarePropertyDefaultSystemOutputDevice, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMain}; + AudioObjectPropertyAddress addr = {kAudioHardwarePropertyDefaultSystemOutputDevice, + kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; if (*p_id) return; @@ -125,11 +116,9 @@ static void get_default_id(char **p_id) AudioDeviceID id = 0; UInt32 size = sizeof(id); - stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, - NULL, &size, &id); + stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, NULL, &size, &id); if (success(stat, "AudioObjectGetPropertyData")) - obs_enum_audio_monitoring_device(alloc_default_id, p_id, id, - true); + obs_enum_audio_monitoring_device(alloc_default_id, p_id, id, true); if (!*p_id) *p_id = bzalloc(1); } diff --git a/libobs/audio-monitoring/osx/coreaudio-output.c b/libobs/audio-monitoring/osx/coreaudio-output.c index de4ad040e..c1488a096 100644 --- a/libobs/audio-monitoring/osx/coreaudio-output.c +++ b/libobs/audio-monitoring/osx/coreaudio-output.c @@ -40,15 +40,13 @@ static inline bool fill_buffer(struct audio_monitor *monitor) } deque_pop_front(&monitor->empty_buffers, &buf, sizeof(buf)); - deque_pop_front(&monitor->new_data, buf->mAudioData, - monitor->buffer_size); + deque_pop_front(&monitor->new_data, buf->mAudioData, monitor->buffer_size); buf->mAudioDataByteSize = (UInt32)monitor->buffer_size; stat = AudioQueueEnqueueBuffer(monitor->queue, buf, 0, NULL); if (!success(stat, "AudioQueueEnqueueBuffer")) { - blog(LOG_WARNING, "%s: %s", __FUNCTION__, - "Failed to enqueue buffer"); + blog(LOG_WARNING, "%s: %s", __FUNCTION__, "Failed to enqueue buffer"); AudioQueueStop(monitor->queue, false); } return true; @@ -63,8 +61,7 @@ static void on_audio_pause(void *data, calldata_t *calldata) pthread_mutex_unlock(&monitor->mutex); } -static void on_audio_playback(void *param, obs_source_t *source, - const struct audio_data *audio_data, bool muted) +static void on_audio_playback(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted) { struct audio_monitor *monitor = param; float vol = source->user_volume; @@ -83,10 +80,8 @@ static void on_audio_playback(void *param, obs_source_t *source, uint64_t ts_offset; bool success; - success = audio_resampler_resample( - monitor->resampler, resample_data, &resample_frames, &ts_offset, - (const uint8_t *const *)audio_data->data, - (uint32_t)audio_data->frames); + success = audio_resampler_resample(monitor->resampler, resample_data, &resample_frames, &ts_offset, + (const uint8_t *const *)audio_data->data, (uint32_t)audio_data->frames); if (!success) { return; } @@ -99,8 +94,7 @@ static void on_audio_playback(void *param, obs_source_t *source, /* apply volume */ if (!close_float(vol, 1.0f, EPSILON)) { register float *cur = (float *)resample_data[0]; - register float *end = - cur + resample_frames * monitor->channels; + register float *end = cur + resample_frames * monitor->channels; while (cur < end) *(cur++) *= vol; @@ -151,30 +145,25 @@ static void buffer_audio(void *data, AudioQueueRef aq, AudioQueueBufferRef buf) extern bool devices_match(const char *id1, const char *id2); -static bool audio_monitor_init(struct audio_monitor *monitor, - obs_source_t *source) +static bool audio_monitor_init(struct audio_monitor *monitor, obs_source_t *source) { - const struct audio_output_info *info = - audio_output_get_info(obs->audio.audio); + const struct audio_output_info *info = audio_output_get_info(obs->audio.audio); uint32_t channels = get_audio_channels(info->speakers); OSStatus stat; - AudioStreamBasicDescription desc = { - .mSampleRate = (Float64)info->samples_per_sec, - .mFormatID = kAudioFormatLinearPCM, - .mFormatFlags = kAudioFormatFlagIsFloat | - kAudioFormatFlagIsPacked, - .mBytesPerPacket = sizeof(float) * channels, - .mFramesPerPacket = 1, - .mBytesPerFrame = sizeof(float) * channels, - .mChannelsPerFrame = channels, - .mBitsPerChannel = sizeof(float) * 8}; + AudioStreamBasicDescription desc = {.mSampleRate = (Float64)info->samples_per_sec, + .mFormatID = kAudioFormatLinearPCM, + .mFormatFlags = kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, + .mBytesPerPacket = sizeof(float) * channels, + .mFramesPerPacket = 1, + .mBytesPerFrame = sizeof(float) * channels, + .mChannelsPerFrame = channels, + .mBitsPerChannel = sizeof(float) * 8}; monitor->source = source; monitor->channels = channels; - monitor->buffer_size = - channels * sizeof(float) * info->samples_per_sec / 100 * 3; + monitor->buffer_size = channels * sizeof(float) * info->samples_per_sec / 100 * 3; monitor->wait_size = monitor->buffer_size * 3; pthread_mutex_init_value(&monitor->mutex); @@ -196,20 +185,17 @@ static bool audio_monitor_init(struct audio_monitor *monitor, } } - stat = AudioQueueNewOutput(&desc, buffer_audio, monitor, NULL, NULL, 0, - &monitor->queue); + stat = AudioQueueNewOutput(&desc, buffer_audio, monitor, NULL, NULL, 0, &monitor->queue); if (!success(stat, "AudioStreamBasicDescription")) { return false; } if (strcmp(uid, "default") != 0) { - CFStringRef cf_uid = CFStringCreateWithBytes( - NULL, (const UInt8 *)uid, strlen(uid), - kCFStringEncodingUTF8, false); + CFStringRef cf_uid = + CFStringCreateWithBytes(NULL, (const UInt8 *)uid, strlen(uid), kCFStringEncodingUTF8, false); - stat = AudioQueueSetProperty(monitor->queue, - kAudioQueueProperty_CurrentDevice, - &cf_uid, sizeof(cf_uid)); + stat = AudioQueueSetProperty(monitor->queue, kAudioQueueProperty_CurrentDevice, &cf_uid, + sizeof(cf_uid)); CFRelease(cf_uid); if (!success(stat, "set current device")) { @@ -217,27 +203,22 @@ static bool audio_monitor_init(struct audio_monitor *monitor, } } - stat = AudioQueueSetParameter(monitor->queue, kAudioQueueParam_Volume, - 1.0); + stat = AudioQueueSetParameter(monitor->queue, kAudioQueueParam_Volume, 1.0); if (!success(stat, "set volume")) { return false; } for (size_t i = 0; i < 3; i++) { - stat = AudioQueueAllocateBuffer(monitor->queue, - (UInt32)monitor->buffer_size, - &monitor->buffers[i]); + stat = AudioQueueAllocateBuffer(monitor->queue, (UInt32)monitor->buffer_size, &monitor->buffers[i]); if (!success(stat, "allocation of buffer")) { return false; } - deque_push_back(&monitor->empty_buffers, &monitor->buffers[i], - sizeof(monitor->buffers[i])); + deque_push_back(&monitor->empty_buffers, &monitor->buffers[i], sizeof(monitor->buffers[i])); } if (pthread_mutex_init(&monitor->mutex, NULL) != 0) { - blog(LOG_WARNING, "%s: %s", __FUNCTION__, - "Failed to init mutex"); + blog(LOG_WARNING, "%s: %s", __FUNCTION__, "Failed to init mutex"); return false; } @@ -250,8 +231,7 @@ static bool audio_monitor_init(struct audio_monitor *monitor, monitor->resampler = audio_resampler_create(&to, &from); if (!monitor->resampler) { - blog(LOG_WARNING, "%s: %s", __FUNCTION__, - "Failed to create resampler"); + blog(LOG_WARNING, "%s: %s", __FUNCTION__, "Failed to create resampler"); return false; } @@ -267,18 +247,15 @@ static bool audio_monitor_init(struct audio_monitor *monitor, static void audio_monitor_free(struct audio_monitor *monitor) { if (monitor->source) { - obs_source_remove_audio_capture_callback( - monitor->source, on_audio_playback, monitor); - obs_source_remove_audio_pause_callback(monitor->source, - on_audio_pause, monitor); + obs_source_remove_audio_capture_callback(monitor->source, on_audio_playback, monitor); + obs_source_remove_audio_pause_callback(monitor->source, on_audio_pause, monitor); } if (monitor->active) { AudioQueueStop(monitor->queue, true); } for (size_t i = 0; i < 3; i++) { if (monitor->buffers[i]) { - AudioQueueFreeBuffer(monitor->queue, - monitor->buffers[i]); + AudioQueueFreeBuffer(monitor->queue, monitor->buffers[i]); } } if (monitor->queue) { @@ -296,10 +273,8 @@ static void audio_monitor_init_final(struct audio_monitor *monitor) if (monitor->ignore) return; - obs_source_add_audio_capture_callback(monitor->source, - on_audio_playback, monitor); - obs_source_add_audio_pause_callback(monitor->source, on_audio_pause, - monitor); + obs_source_add_audio_capture_callback(monitor->source, on_audio_playback, monitor); + obs_source_add_audio_pause_callback(monitor->source, on_audio_pause, monitor); } struct audio_monitor *audio_monitor_create(obs_source_t *source) diff --git a/libobs/audio-monitoring/pulse/pulseaudio-enum-devices.c b/libobs/audio-monitoring/pulse/pulseaudio-enum-devices.c index e54f3e30c..3bbd7966c 100644 --- a/libobs/audio-monitoring/pulse/pulseaudio-enum-devices.c +++ b/libobs/audio-monitoring/pulse/pulseaudio-enum-devices.c @@ -1,8 +1,7 @@ #include #include "pulseaudio-wrapper.h" -static void pulseaudio_output_info(pa_context *c, const pa_sink_info *i, - int eol, void *userdata) +static void pulseaudio_output_info(pa_context *c, const pa_sink_info *i, int eol, void *userdata) { UNUSED_PARAMETER(c); if (eol != 0) diff --git a/libobs/audio-monitoring/pulse/pulseaudio-output.c b/libobs/audio-monitoring/pulse/pulseaudio-output.c index 6dc46eb5c..02fa643c2 100644 --- a/libobs/audio-monitoring/pulse/pulseaudio-output.c +++ b/libobs/audio-monitoring/pulse/pulseaudio-output.c @@ -25,8 +25,7 @@ struct audio_monitor { pthread_mutex_t playback_mutex; }; -static enum speaker_layout -pulseaudio_channels_to_obs_speakers(uint_fast32_t channels) +static enum speaker_layout pulseaudio_channels_to_obs_speakers(uint_fast32_t channels) { switch (channels) { case 0: @@ -50,8 +49,7 @@ pulseaudio_channels_to_obs_speakers(uint_fast32_t channels) } } -static enum audio_format -pulseaudio_to_obs_audio_format(pa_sample_format_t format) +static enum audio_format pulseaudio_to_obs_audio_format(pa_sample_format_t format) { switch (format) { case PA_SAMPLE_U8: @@ -158,25 +156,21 @@ static void process_float(void *p, size_t frames, size_t channels, float vol) *(cur++) *= vol; } -void process_volume(const struct audio_monitor *monitor, float vol, - uint8_t *const *resample_data, uint32_t resample_frames) +void process_volume(const struct audio_monitor *monitor, float vol, uint8_t *const *resample_data, + uint32_t resample_frames) { switch (monitor->format) { case PA_SAMPLE_U8: - process_byte(resample_data[0], resample_frames, - monitor->channels, vol); + process_byte(resample_data[0], resample_frames, monitor->channels, vol); break; case PA_SAMPLE_S16LE: - process_s16(resample_data[0], resample_frames, - monitor->channels, vol); + process_s16(resample_data[0], resample_frames, monitor->channels, vol); break; case PA_SAMPLE_S32LE: - process_s32(resample_data[0], resample_frames, - monitor->channels, vol); + process_s32(resample_data[0], resample_frames, monitor->channels, vol); break; case PA_SAMPLE_FLOAT32LE: - process_float(resample_data[0], resample_frames, - monitor->channels, vol); + process_float(resample_data[0], resample_frames, monitor->channels, vol); break; default: // just ignore @@ -199,8 +193,7 @@ static void do_stream_write(void *param) data->attr.prebuf = (uint32_t)-1; data->attr.minreq = (uint32_t)-1; data->attr.tlength = data->new_data.size; - pa_stream_set_buffer_attr(data->stream, &data->attr, NULL, - NULL); + pa_stream_set_buffer_attr(data->stream, &data->attr, NULL, NULL); } // Buffer up enough data before we start playing. @@ -214,8 +207,7 @@ static void do_stream_write(void *param) while (data->new_data.size > 0) { size_t bytesToFill = data->new_data.size; - if (pa_stream_begin_write(data->stream, (void **)&buffer, - &bytesToFill)) + if (pa_stream_begin_write(data->stream, (void **)&buffer, &bytesToFill)) goto finish; // PA may request we submit more or less data than we have. @@ -227,8 +219,7 @@ static void do_stream_write(void *param) deque_pop_front(&data->new_data, buffer, bytesToFill); - pa_stream_write(data->stream, buffer, bytesToFill, NULL, 0LL, - PA_SEEK_RELATIVE); + pa_stream_write(data->stream, buffer, bytesToFill, NULL, 0LL, PA_SEEK_RELATIVE); } finish: @@ -236,8 +227,7 @@ finish: pulseaudio_unlock(); } -static void on_audio_playback(void *param, obs_source_t *source, - const struct audio_data *audio_data, bool muted) +static void on_audio_playback(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted) { struct audio_monitor *monitor = param; float vol = source->user_volume; @@ -254,10 +244,8 @@ static void on_audio_playback(void *param, obs_source_t *source, if (os_atomic_load_long(&source->activate_refs) == 0) goto unlock; - success = audio_resampler_resample( - monitor->resampler, resample_data, &resample_frames, &ts_offset, - (const uint8_t *const *)audio_data->data, - (uint32_t)audio_data->frames); + success = audio_resampler_resample(monitor->resampler, resample_data, &resample_frames, &ts_offset, + (const uint8_t *const *)audio_data->data, (uint32_t)audio_data->frames); if (!success) goto unlock; @@ -268,8 +256,7 @@ static void on_audio_playback(void *param, obs_source_t *source, memset(resample_data[0], 0, bytes); } else { if (!close_float(vol, 1.0f, EPSILON)) { - process_volume(monitor, vol, resample_data, - resample_frames); + process_volume(monitor, vol, resample_data, resample_frames); } } @@ -282,20 +269,17 @@ unlock: do_stream_write(param); } -static void pulseaudio_server_info(pa_context *c, const pa_server_info *i, - void *userdata) +static void pulseaudio_server_info(pa_context *c, const pa_server_info *i, void *userdata) { UNUSED_PARAMETER(c); UNUSED_PARAMETER(userdata); - blog(LOG_INFO, "Server name: '%s %s'", i->server_name, - i->server_version); + blog(LOG_INFO, "Server name: '%s %s'", i->server_name, i->server_version); pulseaudio_signal(0); } -static void pulseaudio_sink_info(pa_context *c, const pa_sink_info *i, int eol, - void *userdata) +static void pulseaudio_sink_info(pa_context *c, const pa_sink_info *i, int eol, void *userdata) { UNUSED_PARAMETER(c); PULSE_DATA(userdata); @@ -309,8 +293,7 @@ static void pulseaudio_sink_info(pa_context *c, const pa_sink_info *i, int eol, goto skip; blog(LOG_INFO, "Audio format: %s, %" PRIu32 " Hz, %" PRIu8 " channels", - pa_sample_format_to_string(i->sample_spec.format), - i->sample_spec.rate, i->sample_spec.channels); + pa_sample_format_to_string(i->sample_spec.format), i->sample_spec.rate, i->sample_spec.channels); pa_sample_format_t format = i->sample_spec.format; if (pulseaudio_to_obs_audio_format(format) == AUDIO_FORMAT_UNKNOWN) { @@ -319,8 +302,7 @@ static void pulseaudio_sink_info(pa_context *c, const pa_sink_info *i, int eol, blog(LOG_INFO, "Sample format %s not supported by OBS," "using %s instead for recording", - pa_sample_format_to_string(i->sample_spec.format), - pa_sample_format_to_string(format)); + pa_sample_format_to_string(i->sample_spec.format), pa_sample_format_to_string(format)); } uint8_t channels = i->sample_spec.channels; @@ -360,16 +342,13 @@ static void pulseaudio_stop_playback(struct audio_monitor *monitor) } blog(LOG_INFO, "Stopped Monitoring in '%s'", monitor->device); - blog(LOG_INFO, - "Got %" PRIuFAST32 " packets with %" PRIuFAST64 " frames", - monitor->packets, monitor->frames); + blog(LOG_INFO, "Got %" PRIuFAST32 " packets with %" PRIuFAST64 " frames", monitor->packets, monitor->frames); monitor->packets = 0; monitor->frames = 0; } -static bool audio_monitor_init(struct audio_monitor *monitor, - obs_source_t *source) +static bool audio_monitor_init(struct audio_monitor *monitor, obs_source_t *source) { pthread_mutex_init_value(&monitor->playback_mutex); @@ -387,8 +366,7 @@ static bool audio_monitor_init(struct audio_monitor *monitor, if (match) { monitor->ignore = true; - blog(LOG_INFO, "Prevented feedback-loop in '%s'", - s_dev_id); + blog(LOG_INFO, "Prevented feedback-loop in '%s'", s_dev_id); return true; } } @@ -403,20 +381,17 @@ static bool audio_monitor_init(struct audio_monitor *monitor, if (!monitor->device) return false; - if (pulseaudio_get_server_info(pulseaudio_server_info, - (void *)monitor) < 0) { + if (pulseaudio_get_server_info(pulseaudio_server_info, (void *)monitor) < 0) { blog(LOG_ERROR, "Unable to get server info !"); return false; } - if (pulseaudio_get_sink_info(pulseaudio_sink_info, monitor->device, - (void *)monitor) < 0) { + if (pulseaudio_get_sink_info(pulseaudio_sink_info, monitor->device, (void *)monitor) < 0) { blog(LOG_ERROR, "Unable to get sink info !"); return false; } if (monitor->format == PA_SAMPLE_INVALID) { - blog(LOG_ERROR, - "An error occurred while getting the source info!"); + blog(LOG_ERROR, "An error occurred while getting the source info!"); return false; } @@ -430,22 +405,18 @@ static bool audio_monitor_init(struct audio_monitor *monitor, return false; } - const struct audio_output_info *info = - audio_output_get_info(obs->audio.audio); + const struct audio_output_info *info = audio_output_get_info(obs->audio.audio); struct resample_info from = {.samples_per_sec = info->samples_per_sec, .speakers = info->speakers, .format = AUDIO_FORMAT_FLOAT_PLANAR}; - struct resample_info to = { - .samples_per_sec = (uint32_t)monitor->samples_per_sec, - .speakers = - pulseaudio_channels_to_obs_speakers(monitor->channels), - .format = pulseaudio_to_obs_audio_format(monitor->format)}; + struct resample_info to = {.samples_per_sec = (uint32_t)monitor->samples_per_sec, + .speakers = pulseaudio_channels_to_obs_speakers(monitor->channels), + .format = pulseaudio_to_obs_audio_format(monitor->format)}; monitor->resampler = audio_resampler_create(&to, &from); if (!monitor->resampler) { - blog(LOG_WARNING, "%s: %s", __FUNCTION__, - "Failed to create resampler"); + blog(LOG_WARNING, "%s: %s", __FUNCTION__, "Failed to create resampler"); return false; } @@ -454,8 +425,7 @@ static bool audio_monitor_init(struct audio_monitor *monitor, pa_channel_map channel_map = pulseaudio_channel_map(monitor->speakers); - monitor->stream = pulseaudio_stream_new( - obs_source_get_name(monitor->source), &spec, &channel_map); + monitor->stream = pulseaudio_stream_new(obs_source_get_name(monitor->source), &spec, &channel_map); if (!monitor->stream) { blog(LOG_ERROR, "Unable to create stream"); return false; @@ -467,12 +437,9 @@ static bool audio_monitor_init(struct audio_monitor *monitor, monitor->attr.prebuf = (uint32_t)-1; monitor->attr.tlength = pa_usec_to_bytes(25000, &spec); - pa_stream_flags_t flags = PA_STREAM_INTERPOLATE_TIMING | - PA_STREAM_AUTO_TIMING_UPDATE | - PA_STREAM_START_CORKED; + pa_stream_flags_t flags = PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_AUTO_TIMING_UPDATE | PA_STREAM_START_CORKED; - int_fast32_t ret = pulseaudio_connect_playback( - monitor->stream, monitor->device, &monitor->attr, flags); + int_fast32_t ret = pulseaudio_connect_playback(monitor->stream, monitor->device, &monitor->attr, flags); if (ret < 0) { pulseaudio_stop_playback(monitor); blog(LOG_ERROR, "Unable to connect to stream"); @@ -488,8 +455,7 @@ static void audio_monitor_init_final(struct audio_monitor *monitor) if (monitor->ignore) return; - obs_source_add_audio_capture_callback(monitor->source, - on_audio_playback, monitor); + obs_source_add_audio_capture_callback(monitor->source, on_audio_playback, monitor); } static inline void audio_monitor_free(struct audio_monitor *monitor) @@ -498,8 +464,7 @@ static inline void audio_monitor_free(struct audio_monitor *monitor) return; if (monitor->source) - obs_source_remove_audio_capture_callback( - monitor->source, on_audio_playback, monitor); + obs_source_remove_audio_capture_callback(monitor->source, on_audio_playback, monitor); audio_resampler_destroy(monitor->resampler); deque_free(&monitor->new_data); diff --git a/libobs/audio-monitoring/pulse/pulseaudio-wrapper.c b/libobs/audio-monitoring/pulse/pulseaudio-wrapper.c index 5293ea142..53ec702b6 100644 --- a/libobs/audio-monitoring/pulse/pulseaudio-wrapper.c +++ b/libobs/audio-monitoring/pulse/pulseaudio-wrapper.c @@ -31,12 +31,10 @@ static pthread_mutex_t pulseaudio_mutex = PTHREAD_MUTEX_INITIALIZER; static pa_threaded_mainloop *pulseaudio_mainloop = NULL; static pa_context *pulseaudio_context = NULL; -static void pulseaudio_default_devices(pa_context *c, const pa_server_info *i, - void *userdata) +static void pulseaudio_default_devices(pa_context *c, const pa_server_info *i, void *userdata) { UNUSED_PARAMETER(c); - struct pulseaudio_default_output *d = - (struct pulseaudio_default_output *)userdata; + struct pulseaudio_default_output *d = (struct pulseaudio_default_output *)userdata; d->default_sink_name = bstrdup(i->default_sink_name); pulseaudio_signal(0); } @@ -44,10 +42,8 @@ static void pulseaudio_default_devices(pa_context *c, const pa_server_info *i, void get_default_id(char **id) { pulseaudio_init(); - struct pulseaudio_default_output *pdo = - bzalloc(sizeof(struct pulseaudio_default_output)); - pulseaudio_get_server_info( - (pa_server_info_cb_t)pulseaudio_default_devices, (void *)pdo); + struct pulseaudio_default_output *pdo = bzalloc(sizeof(struct pulseaudio_default_output)); + pulseaudio_get_server_info((pa_server_info_cb_t)pulseaudio_default_devices, (void *)pdo); if (!pdo->default_sink_name || !*pdo->default_sink_name) { *id = bzalloc(1); @@ -139,15 +135,12 @@ static void pulseaudio_init_context() pulseaudio_lock(); pa_proplist *p = pulseaudio_properties(); - pulseaudio_context = pa_context_new_with_proplist( - pa_threaded_mainloop_get_api(pulseaudio_mainloop), - "OBS-Monitor", p); + pulseaudio_context = + pa_context_new_with_proplist(pa_threaded_mainloop_get_api(pulseaudio_mainloop), "OBS-Monitor", p); - pa_context_set_state_callback(pulseaudio_context, - pulseaudio_context_state_changed, NULL); + pa_context_set_state_callback(pulseaudio_context, pulseaudio_context_state_changed, NULL); - pa_context_connect(pulseaudio_context, NULL, PA_CONTEXT_NOAUTOSPAWN, - NULL); + pa_context_connect(pulseaudio_context, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL); pa_proplist_free(p); pulseaudio_unlock(); @@ -238,16 +231,14 @@ void pulseaudio_accept() pa_threaded_mainloop_accept(pulseaudio_mainloop); } -int_fast32_t pulseaudio_get_source_info_list(pa_source_info_cb_t cb, - void *userdata) +int_fast32_t pulseaudio_get_source_info_list(pa_source_info_cb_t cb, void *userdata) { if (pulseaudio_context_ready() < 0) return -1; pulseaudio_lock(); - pa_operation *op = pa_context_get_source_info_list(pulseaudio_context, - cb, userdata); + pa_operation *op = pa_context_get_source_info_list(pulseaudio_context, cb, userdata); if (!op) { pulseaudio_unlock(); return -1; @@ -261,16 +252,14 @@ int_fast32_t pulseaudio_get_source_info_list(pa_source_info_cb_t cb, return 0; } -int_fast32_t pulseaudio_get_source_info(pa_source_info_cb_t cb, - const char *name, void *userdata) +int_fast32_t pulseaudio_get_source_info(pa_source_info_cb_t cb, const char *name, void *userdata) { if (pulseaudio_context_ready() < 0) return -1; pulseaudio_lock(); - pa_operation *op = pa_context_get_source_info_by_name( - pulseaudio_context, name, cb, userdata); + pa_operation *op = pa_context_get_source_info_by_name(pulseaudio_context, name, cb, userdata); if (!op) { pulseaudio_unlock(); return -1; @@ -291,8 +280,7 @@ int_fast32_t pulseaudio_get_sink_info_list(pa_sink_info_cb_t cb, void *userdata) pulseaudio_lock(); - pa_operation *op = - pa_context_get_sink_info_list(pulseaudio_context, cb, userdata); + pa_operation *op = pa_context_get_sink_info_list(pulseaudio_context, cb, userdata); if (!op) { pulseaudio_unlock(); return -1; @@ -306,16 +294,14 @@ int_fast32_t pulseaudio_get_sink_info_list(pa_sink_info_cb_t cb, void *userdata) return 0; } -int_fast32_t pulseaudio_get_sink_info(pa_sink_info_cb_t cb, const char *name, - void *userdata) +int_fast32_t pulseaudio_get_sink_info(pa_sink_info_cb_t cb, const char *name, void *userdata) { if (pulseaudio_context_ready() < 0) return -1; pulseaudio_lock(); - pa_operation *op = pa_context_get_sink_info_by_name(pulseaudio_context, - name, cb, userdata); + pa_operation *op = pa_context_get_sink_info_by_name(pulseaudio_context, name, cb, userdata); if (!op) { pulseaudio_unlock(); return -1; @@ -336,8 +322,7 @@ int_fast32_t pulseaudio_get_server_info(pa_server_info_cb_t cb, void *userdata) pulseaudio_lock(); - pa_operation *op = - pa_context_get_server_info(pulseaudio_context, cb, userdata); + pa_operation *op = pa_context_get_server_info(pulseaudio_context, cb, userdata); if (!op) { pulseaudio_unlock(); return -1; @@ -350,8 +335,7 @@ int_fast32_t pulseaudio_get_server_info(pa_server_info_cb_t cb, void *userdata) return 0; } -pa_stream *pulseaudio_stream_new(const char *name, const pa_sample_spec *ss, - const pa_channel_map *map) +pa_stream *pulseaudio_stream_new(const char *name, const pa_sample_spec *ss, const pa_channel_map *map) { if (pulseaudio_context_ready() < 0) return NULL; @@ -359,16 +343,14 @@ pa_stream *pulseaudio_stream_new(const char *name, const pa_sample_spec *ss, pulseaudio_lock(); pa_proplist *p = pulseaudio_properties(); - pa_stream *s = pa_stream_new_with_proplist(pulseaudio_context, name, ss, - map, p); + pa_stream *s = pa_stream_new_with_proplist(pulseaudio_context, name, ss, map, p); pa_proplist_free(p); pulseaudio_unlock(); return s; } -int_fast32_t pulseaudio_connect_playback(pa_stream *s, const char *name, - const pa_buffer_attr *attr, +int_fast32_t pulseaudio_connect_playback(pa_stream *s, const char *name, const pa_buffer_attr *attr, pa_stream_flags_t flags) { if (pulseaudio_context_ready() < 0) @@ -379,16 +361,14 @@ int_fast32_t pulseaudio_connect_playback(pa_stream *s, const char *name, memcpy(device, name, dev_len); pulseaudio_lock(); - int_fast32_t ret = - pa_stream_connect_playback(s, device, attr, flags, NULL, NULL); + int_fast32_t ret = pa_stream_connect_playback(s, device, attr, flags, NULL, NULL); pulseaudio_unlock(); bfree(device); return ret; } -void pulseaudio_write_callback(pa_stream *p, pa_stream_request_cb_t cb, - void *userdata) +void pulseaudio_write_callback(pa_stream *p, pa_stream_request_cb_t cb, void *userdata) { if (pulseaudio_context_ready() < 0) return; @@ -398,8 +378,7 @@ void pulseaudio_write_callback(pa_stream *p, pa_stream_request_cb_t cb, pulseaudio_unlock(); } -void pulseaudio_set_underflow_callback(pa_stream *p, pa_stream_notify_cb_t cb, - void *userdata) +void pulseaudio_set_underflow_callback(pa_stream *p, pa_stream_notify_cb_t cb, void *userdata) { if (pulseaudio_context_ready() < 0) return; diff --git a/libobs/audio-monitoring/pulse/pulseaudio-wrapper.h b/libobs/audio-monitoring/pulse/pulseaudio-wrapper.h index d64a27654..e53e6fdc2 100644 --- a/libobs/audio-monitoring/pulse/pulseaudio-wrapper.h +++ b/libobs/audio-monitoring/pulse/pulseaudio-wrapper.h @@ -106,8 +106,7 @@ void pulseaudio_accept(); * * @warning call without active locks */ -int_fast32_t pulseaudio_get_source_info_list(pa_source_info_cb_t cb, - void *userdata); +int_fast32_t pulseaudio_get_source_info_list(pa_source_info_cb_t cb, void *userdata); /** * Request source information from a specific source @@ -125,8 +124,7 @@ int_fast32_t pulseaudio_get_source_info_list(pa_source_info_cb_t cb, * * @warning call without active locks */ -int_fast32_t pulseaudio_get_source_info(pa_source_info_cb_t cb, - const char *name, void *userdata); +int_fast32_t pulseaudio_get_source_info(pa_source_info_cb_t cb, const char *name, void *userdata); /** * Request sink information @@ -140,8 +138,7 @@ int_fast32_t pulseaudio_get_source_info(pa_source_info_cb_t cb, * * @warning call without active locks */ -int_fast32_t pulseaudio_get_sink_info_list(pa_sink_info_cb_t cb, - void *userdata); +int_fast32_t pulseaudio_get_sink_info_list(pa_sink_info_cb_t cb, void *userdata); /** * Request sink information from a specific sink @@ -159,8 +156,7 @@ int_fast32_t pulseaudio_get_sink_info_list(pa_sink_info_cb_t cb, * * @warning call without active locks */ -int_fast32_t pulseaudio_get_sink_info(pa_sink_info_cb_t cb, const char *name, - void *userdata); +int_fast32_t pulseaudio_get_sink_info(pa_sink_info_cb_t cb, const char *name, void *userdata); /** * Request server information @@ -183,8 +179,7 @@ int_fast32_t pulseaudio_get_server_info(pa_server_info_cb_t cb, void *userdata); * * @warning call without active locks */ -pa_stream *pulseaudio_stream_new(const char *name, const pa_sample_spec *ss, - const pa_channel_map *map); +pa_stream *pulseaudio_stream_new(const char *name, const pa_sample_spec *ss, const pa_channel_map *map); /** * Connect to a pulseaudio playback stream @@ -195,8 +190,7 @@ pa_stream *pulseaudio_stream_new(const char *name, const pa_sample_spec *ss, * @param flags pa_stream_flags_t * @return negative on error */ -int_fast32_t pulseaudio_connect_playback(pa_stream *s, const char *name, - const pa_buffer_attr *attr, +int_fast32_t pulseaudio_connect_playback(pa_stream *s, const char *name, const pa_buffer_attr *attr, pa_stream_flags_t flags); /** @@ -206,8 +200,7 @@ int_fast32_t pulseaudio_connect_playback(pa_stream *s, const char *name, * @param cb pa_stream_request_cb_t * @param userdata pointer to userdata the callback will be called with */ -void pulseaudio_write_callback(pa_stream *p, pa_stream_request_cb_t cb, - void *userdata); +void pulseaudio_write_callback(pa_stream *p, pa_stream_request_cb_t cb, void *userdata); /** * Sets a callback function for when an underflow happen @@ -216,5 +209,4 @@ void pulseaudio_write_callback(pa_stream *p, pa_stream_request_cb_t cb, * @param cb pa_stream_notify_cb_t * @param userdata pointer to userdata the callback will be called with */ -void pulseaudio_set_underflow_callback(pa_stream *p, pa_stream_notify_cb_t cb, - void *userdata); +void pulseaudio_set_underflow_callback(pa_stream *p, pa_stream_notify_cb_t cb, void *userdata); diff --git a/libobs/audio-monitoring/win32/wasapi-enum-devices.c b/libobs/audio-monitoring/win32/wasapi-enum-devices.c index a15071672..f5c47ecd9 100644 --- a/libobs/audio-monitoring/win32/wasapi-enum-devices.c +++ b/libobs/audio-monitoring/win32/wasapi-enum-devices.c @@ -24,8 +24,8 @@ k, \ }}, \ l}; -DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, - 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, 14); +DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, 0x20, 0x67, 0xd1, 0x46, 0xa8, 0x50, 0xe0, + 14); #else @@ -33,8 +33,7 @@ DEFINE_PROPERTYKEY(PKEY_Device_FriendlyName, 0xa45c254e, 0xdf1c, 0x4efd, 0x80, #endif -static bool get_device_info(obs_enum_audio_device_cb cb, void *data, - IMMDeviceCollection *collection, UINT idx) +static bool get_device_info(obs_enum_audio_device_cb cb, void *data, IMMDeviceCollection *collection, UINT idx) { IPropertyStore *store = NULL; IMMDevice *device = NULL; @@ -61,8 +60,7 @@ static bool get_device_info(obs_enum_audio_device_cb cb, void *data, } PropVariantInit(&name_var); - hr = store->lpVtbl->GetValue(store, &PKEY_Device_FriendlyName, - &name_var); + hr = store->lpVtbl->GetValue(store, &PKEY_Device_FriendlyName, &name_var); if (FAILED(hr)) { goto fail; } @@ -88,14 +86,12 @@ void obs_enum_audio_monitoring_devices(obs_enum_audio_device_cb cb, void *data) UINT count; HRESULT hr; - hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, - &IID_IMMDeviceEnumerator, &enumerator); + hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, &enumerator); if (FAILED(hr)) { goto fail; } - hr = enumerator->lpVtbl->EnumAudioEndpoints( - enumerator, eRender, DEVICE_STATE_ACTIVE, &collection); + hr = enumerator->lpVtbl->EnumAudioEndpoints(enumerator, eRender, DEVICE_STATE_ACTIVE, &collection); if (FAILED(hr)) { goto fail; } @@ -126,14 +122,12 @@ static void get_default_id(char **p_id) if (*p_id) return; - hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, - &IID_IMMDeviceEnumerator, &immde); + hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, &immde); if (FAILED(hr)) { goto fail; } - hr = immde->lpVtbl->GetDefaultAudioEndpoint(immde, eRender, eConsole, - &device); + hr = immde->lpVtbl->GetDefaultAudioEndpoint(immde, eRender, eConsole, &device); if (FAILED(hr)) { goto fail; } diff --git a/libobs/audio-monitoring/win32/wasapi-output.c b/libobs/audio-monitoring/win32/wasapi-output.c index 8ca3c2820..b9821ec36 100644 --- a/libobs/audio-monitoring/win32/wasapi-output.c +++ b/libobs/audio-monitoring/win32/wasapi-output.c @@ -8,25 +8,22 @@ #include "wasapi-output.h" #define ACTUALLY_DEFINE_GUID(name, l, w1, w2, b1, b2, b3, b4, b5, b6, b7, b8) \ - EXTERN_C const GUID DECLSPEC_SELECTANY \ - name = {l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}} + EXTERN_C const GUID DECLSPEC_SELECTANY name = {l, w1, w2, {b1, b2, b3, b4, b5, b6, b7, b8}} -#define do_log(level, format, ...) \ - blog(level, "[audio monitoring: '%s'] " format, \ - obs_source_get_name(monitor->source), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[audio monitoring: '%s'] " format, obs_source_get_name(monitor->source), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__) -ACTUALLY_DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, 0x8E, - 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, 0x2E); -ACTUALLY_DEFINE_GUID(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, 0xA7, - 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, 0xE6); -ACTUALLY_DEFINE_GUID(IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4C32, 0xB1, 0x78, - 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2); -ACTUALLY_DEFINE_GUID(IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7, - 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, 0xE2); +ACTUALLY_DEFINE_GUID(CLSID_MMDeviceEnumerator, 0xBCDE0395, 0xE52F, 0x467C, 0x8E, 0x3D, 0xC4, 0x57, 0x92, 0x91, 0x69, + 0x2E); +ACTUALLY_DEFINE_GUID(IID_IMMDeviceEnumerator, 0xA95664D2, 0x9614, 0x4F35, 0xA7, 0x46, 0xDE, 0x8D, 0xB6, 0x36, 0x17, + 0xE6); +ACTUALLY_DEFINE_GUID(IID_IAudioClient, 0x1CB9AD4C, 0xDBFA, 0x4C32, 0xB1, 0x78, 0xC2, 0xF5, 0x68, 0xA7, 0x03, 0xB2); +ACTUALLY_DEFINE_GUID(IID_IAudioRenderClient, 0xF294ACFC, 0x3146, 0x4483, 0xA7, 0xBF, 0xAD, 0xDC, 0xA7, 0xC2, 0x60, + 0xE2); struct audio_monitor { obs_source_t *source; @@ -52,8 +49,8 @@ struct audio_monitor { /* #define DEBUG_AUDIO */ -static bool process_audio_delay(struct audio_monitor *monitor, float **data, - uint32_t *frames, uint64_t ts, uint32_t pad) +static bool process_audio_delay(struct audio_monitor *monitor, float **data, uint32_t *frames, uint64_t ts, + uint32_t pad) { obs_source_t *s = monitor->source; uint64_t last_frame_ts = s->last_frame_ts; @@ -78,8 +75,7 @@ static bool process_audio_delay(struct audio_monitor *monitor, float **data, monitor->prev_video_ts = last_frame_ts; } else if (monitor->prev_video_ts == last_frame_ts) { - monitor->time_since_prev += util_mul_div64( - *frames, 1000000000ULL, monitor->sample_rate); + monitor->time_since_prev += util_mul_div64(*frames, 1000000000ULL, monitor->sample_rate); } else { monitor->time_since_prev = 0; } @@ -89,11 +85,9 @@ static bool process_audio_delay(struct audio_monitor *monitor, float **data, bool bad_diff; deque_peek_front(&monitor->delay_buffer, &cur_ts, sizeof(ts)); - front_ts = cur_ts - util_mul_div64(pad, 1000000000ULL, - monitor->sample_rate); + front_ts = cur_ts - util_mul_div64(pad, 1000000000ULL, monitor->sample_rate); diff = (int64_t)front_ts - (int64_t)last_frame_ts; - bad_diff = !last_frame_ts || llabs(diff) > 5000000000 || - monitor->time_since_prev > 100000000ULL; + bad_diff = !last_frame_ts || llabs(diff) > 5000000000 || monitor->time_since_prev > 100000000ULL; /* delay audio if rushing */ if (!bad_diff && diff > 75000000) { @@ -102,31 +96,26 @@ static bool process_audio_delay(struct audio_monitor *monitor, float **data, "audio rushing, cutting audio, " "diff: %lld, delay buffer size: %lu, " "v: %llu: a: %llu", - diff, (int)monitor->delay_buffer.size, - last_frame_ts, front_ts); + diff, (int)monitor->delay_buffer.size, last_frame_ts, front_ts); #endif return false; } deque_pop_front(&monitor->delay_buffer, NULL, sizeof(ts)); - deque_pop_front(&monitor->delay_buffer, frames, - sizeof(*frames)); + deque_pop_front(&monitor->delay_buffer, frames, sizeof(*frames)); size = *frames * blocksize; da_resize(monitor->buf, size); - deque_pop_front(&monitor->delay_buffer, monitor->buf.array, - size); + deque_pop_front(&monitor->delay_buffer, monitor->buf.array, size); /* cut audio if dragging */ - if (!bad_diff && diff < -75000000 && - monitor->delay_buffer.size > 0) { + if (!bad_diff && diff < -75000000 && monitor->delay_buffer.size > 0) { #ifdef DEBUG_AUDIO blog(LOG_INFO, "audio dragging, cutting audio, " "diff: %lld, delay buffer size: %lu, " "v: %llu: a: %llu", - diff, (int)monitor->delay_buffer.size, - last_frame_ts, front_ts); + diff, (int)monitor->delay_buffer.size, last_frame_ts, front_ts); #endif continue; } @@ -167,19 +156,16 @@ static bool audio_monitor_init_wasapi(struct audio_monitor *monitor) /* ------------------------------------------ * * Init device */ - hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, - &IID_IMMDeviceEnumerator, (void **)&immde); + hr = CoCreateInstance(&CLSID_MMDeviceEnumerator, NULL, CLSCTX_ALL, &IID_IMMDeviceEnumerator, (void **)&immde); if (FAILED(hr)) { - warn("%s: Failed to create IMMDeviceEnumerator: %08lX", - __FUNCTION__, hr); + warn("%s: Failed to create IMMDeviceEnumerator: %08lX", __FUNCTION__, hr); return false; } IMMDevice *device = NULL; const char *const id = obs->audio.monitoring_device_id; if (strcmp(id, "default") == 0) { - hr = immde->lpVtbl->GetDefaultAudioEndpoint(immde, eRender, - eConsole, &device); + hr = immde->lpVtbl->GetDefaultAudioEndpoint(immde, eRender, eConsole, &device); } else { wchar_t w_id[512]; os_utf8_to_wcs(id, 0, w_id, 512); @@ -195,8 +181,7 @@ static bool audio_monitor_init_wasapi(struct audio_monitor *monitor) /* ------------------------------------------ * * Init client */ - hr = device->lpVtbl->Activate(device, &IID_IAudioClient, CLSCTX_ALL, - NULL, (void **)&monitor->client); + hr = device->lpVtbl->Activate(device, &IID_IAudioClient, CLSCTX_ALL, NULL, (void **)&monitor->client); device->lpVtbl->Release(device); if (FAILED(hr)) { warn("%s: Failed to activate device: %08lX", __FUNCTION__, hr); @@ -209,9 +194,7 @@ static bool audio_monitor_init_wasapi(struct audio_monitor *monitor) goto fail; } - hr = monitor->client->lpVtbl->Initialize(monitor->client, - AUDCLNT_SHAREMODE_SHARED, 0, - 10000000, 0, wfex, NULL); + hr = monitor->client->lpVtbl->Initialize(monitor->client, AUDCLNT_SHAREMODE_SHARED, 0, 10000000, 0, wfex, NULL); if (FAILED(hr)) { warn("%s: Failed to initialize: %08lX", __FUNCTION__, hr); goto fail; @@ -220,8 +203,7 @@ static bool audio_monitor_init_wasapi(struct audio_monitor *monitor) /* ------------------------------------------ * * Init resampler */ - const struct audio_output_info *info = - audio_output_get_info(obs->audio.audio); + const struct audio_output_info *info = audio_output_get_info(obs->audio.audio); WAVEFORMATEXTENSIBLE *ext = (WAVEFORMATEXTENSIBLE *)wfex; struct resample_info from; struct resample_info to; @@ -231,8 +213,7 @@ static bool audio_monitor_init_wasapi(struct audio_monitor *monitor) from.format = AUDIO_FORMAT_FLOAT_PLANAR; to.samples_per_sec = (uint32_t)wfex->nSamplesPerSec; - to.speakers = - convert_speaker_layout(ext->dwChannelMask, wfex->nChannels); + to.speakers = convert_speaker_layout(ext->dwChannelMask, wfex->nChannels); to.format = AUDIO_FORMAT_FLOAT; monitor->sample_rate = (uint32_t)wfex->nSamplesPerSec; @@ -251,12 +232,9 @@ static bool audio_monitor_init_wasapi(struct audio_monitor *monitor) goto fail; } - hr = monitor->client->lpVtbl->GetService(monitor->client, - &IID_IAudioRenderClient, - (void **)&monitor->render); + hr = monitor->client->lpVtbl->GetService(monitor->client, &IID_IAudioRenderClient, (void **)&monitor->render); if (FAILED(hr)) { - warn("%s: Failed to get IAudioRenderClient: %08lX", - __FUNCTION__, hr); + warn("%s: Failed to get IAudioRenderClient: %08lX", __FUNCTION__, hr); goto fail; } @@ -298,8 +276,7 @@ static void audio_monitor_free_for_reconnect(struct audio_monitor *monitor) da_free(monitor->buf); } -static void on_audio_playback(void *param, obs_source_t *source, - const struct audio_data *audio_data, bool muted) +static void on_audio_playback(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted) { struct audio_monitor *monitor = param; uint8_t *resample_data[MAX_AV_PLANES]; @@ -320,29 +297,24 @@ static void on_audio_playback(void *param, obs_source_t *source, goto free_for_reconnect; } - success = audio_resampler_resample( - monitor->resampler, resample_data, &resample_frames, &ts_offset, - (const uint8_t *const *)audio_data->data, - (uint32_t)audio_data->frames); + success = audio_resampler_resample(monitor->resampler, resample_data, &resample_frames, &ts_offset, + (const uint8_t *const *)audio_data->data, (uint32_t)audio_data->frames); if (!success) { goto unlock; } UINT32 pad = 0; - HRESULT hr = monitor->client->lpVtbl->GetCurrentPadding(monitor->client, - &pad); + HRESULT hr = monitor->client->lpVtbl->GetCurrentPadding(monitor->client, &pad); if (FAILED(hr)) { goto free_for_reconnect; } - bool decouple_audio = source->async_unbuffered && - source->async_decoupled; + bool decouple_audio = source->async_unbuffered && source->async_decoupled; if (monitor->source_has_video && !decouple_audio) { uint64_t ts = audio_data->timestamp - ts_offset; - if (!process_audio_delay(monitor, (float **)(&resample_data[0]), - &resample_frames, ts, pad)) { + if (!process_audio_delay(monitor, (float **)(&resample_data[0]), &resample_frames, ts, pad)) { goto unlock; } } @@ -357,19 +329,15 @@ static void on_audio_playback(void *param, obs_source_t *source, /* apply volume */ if (!close_float(vol, 1.0f, EPSILON)) { register float *cur = (float *)resample_data[0]; - register float *end = - cur + resample_frames * monitor->channels; + register float *end = cur + resample_frames * monitor->channels; while (cur < end) *(cur++) *= vol; } - memcpy(output, resample_data[0], - resample_frames * monitor->channels * sizeof(float)); + memcpy(output, resample_data[0], resample_frames * monitor->channels * sizeof(float)); } - hr = render->lpVtbl->ReleaseBuffer(render, resample_frames, - muted ? AUDCLNT_BUFFERFLAGS_SILENT - : 0); + hr = render->lpVtbl->ReleaseBuffer(render, resample_frames, muted ? AUDCLNT_BUFFERFLAGS_SILENT : 0); if (FAILED(hr)) { goto free_for_reconnect; } @@ -388,8 +356,7 @@ static inline void audio_monitor_free(struct audio_monitor *monitor) return; if (monitor->source) { - obs_source_remove_audio_capture_callback( - monitor->source, on_audio_playback, monitor); + obs_source_remove_audio_capture_callback(monitor->source, on_audio_playback, monitor); } if (monitor->client) @@ -404,8 +371,7 @@ static inline void audio_monitor_free(struct audio_monitor *monitor) extern bool devices_match(const char *id1, const char *id2); -static bool audio_monitor_init(struct audio_monitor *monitor, - obs_source_t *source) +static bool audio_monitor_init(struct audio_monitor *monitor, obs_source_t *source) { monitor->source = source; @@ -437,10 +403,8 @@ static void audio_monitor_init_final(struct audio_monitor *monitor) if (monitor->ignore) return; - monitor->source_has_video = - (monitor->source->info.output_flags & OBS_SOURCE_VIDEO) != 0; - obs_source_add_audio_capture_callback(monitor->source, - on_audio_playback, monitor); + monitor->source_has_video = (monitor->source->info.output_flags & OBS_SOURCE_VIDEO) != 0; + obs_source_add_audio_capture_callback(monitor->source, on_audio_playback, monitor); } struct audio_monitor *audio_monitor_create(obs_source_t *source) diff --git a/libobs/audio-monitoring/win32/wasapi-output.h b/libobs/audio-monitoring/win32/wasapi-output.h index 3eb559a05..80815acbe 100644 --- a/libobs/audio-monitoring/win32/wasapi-output.h +++ b/libobs/audio-monitoring/win32/wasapi-output.h @@ -8,12 +8,10 @@ #define KSAUDIO_SPEAKER_2POINT1 (KSAUDIO_SPEAKER_STEREO | SPEAKER_LOW_FREQUENCY) #endif -#define KSAUDIO_SPEAKER_SURROUND_AVUTIL \ - (KSAUDIO_SPEAKER_STEREO | SPEAKER_FRONT_CENTER) +#define KSAUDIO_SPEAKER_SURROUND_AVUTIL (KSAUDIO_SPEAKER_STEREO | SPEAKER_FRONT_CENTER) #ifndef KSAUDIO_SPEAKER_4POINT1 -#define KSAUDIO_SPEAKER_4POINT1 \ - (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY) +#define KSAUDIO_SPEAKER_4POINT1 (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY) #endif #define safe_release(ptr) \ diff --git a/libobs/callback/calldata.c b/libobs/callback/calldata.c index 01bea89d9..ae900ce44 100644 --- a/libobs/callback/calldata.c +++ b/libobs/callback/calldata.c @@ -109,8 +109,7 @@ static inline void cd_copy_data(uint8_t **pos, const void *in, size_t size) } } -static inline void cd_set_first_param(calldata_t *data, const char *name, - const void *in, size_t size) +static inline void cd_set_first_param(calldata_t *data, const char *name, const void *in, size_t size) { uint8_t *pos; size_t capacity; @@ -131,8 +130,7 @@ static inline void cd_set_first_param(calldata_t *data, const char *name, memset(pos, 0, sizeof(size_t)); } -static inline bool cd_ensure_capacity(calldata_t *data, uint8_t **pos, - size_t new_size) +static inline bool cd_ensure_capacity(calldata_t *data, uint8_t **pos, size_t new_size) { size_t offset; size_t new_capacity; @@ -159,8 +157,7 @@ static inline bool cd_ensure_capacity(calldata_t *data, uint8_t **pos, /* ------------------------------------------------------------------------- */ -bool calldata_get_data(const calldata_t *data, const char *name, void *out, - size_t size) +bool calldata_get_data(const calldata_t *data, const char *name, void *out, size_t size) { uint8_t *pos; size_t data_size; @@ -179,8 +176,7 @@ bool calldata_get_data(const calldata_t *data, const char *name, void *out, return true; } -void calldata_set_data(calldata_t *data, const char *name, const void *in, - size_t size) +void calldata_set_data(calldata_t *data, const char *name, const void *in, size_t size) { uint8_t *pos = NULL; @@ -228,8 +224,7 @@ void calldata_set_data(calldata_t *data, const char *name, const void *in, } } -bool calldata_get_string(const calldata_t *data, const char *name, - const char **str) +bool calldata_get_string(const calldata_t *data, const char *name, const char **str) { uint8_t *pos; if (!data || !name || !*name) diff --git a/libobs/callback/calldata.h b/libobs/callback/calldata.h index 0f7945468..833fd1c63 100644 --- a/libobs/callback/calldata.h +++ b/libobs/callback/calldata.h @@ -59,8 +59,7 @@ static inline void calldata_init(struct calldata *data) static inline void calldata_clear(struct calldata *data); -static inline void calldata_init_fixed(struct calldata *data, uint8_t *stack, - size_t size) +static inline void calldata_init_fixed(struct calldata *data, uint8_t *stack, size_t size) { data->stack = stack; data->capacity = size; @@ -75,10 +74,8 @@ static inline void calldata_free(struct calldata *data) bfree(data->stack); } -EXPORT bool calldata_get_data(const calldata_t *data, const char *name, - void *out, size_t size); -EXPORT void calldata_set_data(calldata_t *data, const char *name, - const void *in, size_t new_size); +EXPORT bool calldata_get_data(const calldata_t *data, const char *name, void *out, size_t size); +EXPORT void calldata_set_data(calldata_t *data, const char *name, const void *in, size_t new_size); static inline void calldata_clear(struct calldata *data) { @@ -103,32 +100,27 @@ static inline void calldata_destroy(calldata_t *cd) /* NOTE: 'get' functions return true only if parameter exists, and is the * same type. They return false otherwise. */ -static inline bool calldata_get_int(const calldata_t *data, const char *name, - long long *val) +static inline bool calldata_get_int(const calldata_t *data, const char *name, long long *val) { return calldata_get_data(data, name, val, sizeof(*val)); } -static inline bool calldata_get_float(const calldata_t *data, const char *name, - double *val) +static inline bool calldata_get_float(const calldata_t *data, const char *name, double *val) { return calldata_get_data(data, name, val, sizeof(*val)); } -static inline bool calldata_get_bool(const calldata_t *data, const char *name, - bool *val) +static inline bool calldata_get_bool(const calldata_t *data, const char *name, bool *val) { return calldata_get_data(data, name, val, sizeof(*val)); } -static inline bool calldata_get_ptr(const calldata_t *data, const char *name, - void *p_ptr) +static inline bool calldata_get_ptr(const calldata_t *data, const char *name, void *p_ptr) { return calldata_get_data(data, name, p_ptr, sizeof(p_ptr)); } -EXPORT bool calldata_get_string(const calldata_t *data, const char *name, - const char **str); +EXPORT bool calldata_get_string(const calldata_t *data, const char *name, const char **str); /* ------------------------------------------------------------------------- */ /* call if you know your data is valid */ @@ -161,8 +153,7 @@ static inline void *calldata_ptr(const calldata_t *data, const char *name) return val; } -static inline const char *calldata_string(const calldata_t *data, - const char *name) +static inline const char *calldata_string(const calldata_t *data, const char *name) { const char *val = NULL; calldata_get_string(data, name, &val); @@ -171,32 +162,27 @@ static inline const char *calldata_string(const calldata_t *data, /* ------------------------------------------------------------------------- */ -static inline void calldata_set_int(calldata_t *data, const char *name, - long long val) +static inline void calldata_set_int(calldata_t *data, const char *name, long long val) { calldata_set_data(data, name, &val, sizeof(val)); } -static inline void calldata_set_float(calldata_t *data, const char *name, - double val) +static inline void calldata_set_float(calldata_t *data, const char *name, double val) { calldata_set_data(data, name, &val, sizeof(val)); } -static inline void calldata_set_bool(calldata_t *data, const char *name, - bool val) +static inline void calldata_set_bool(calldata_t *data, const char *name, bool val) { calldata_set_data(data, name, &val, sizeof(val)); } -static inline void calldata_set_ptr(calldata_t *data, const char *name, - void *ptr) +static inline void calldata_set_ptr(calldata_t *data, const char *name, void *ptr) { calldata_set_data(data, name, &ptr, sizeof(ptr)); } -static inline void calldata_set_string(calldata_t *data, const char *name, - const char *str) +static inline void calldata_set_string(calldata_t *data, const char *name, const char *str) { if (str) calldata_set_data(data, name, str, strlen(str) + 1); diff --git a/libobs/callback/decl.c b/libobs/callback/decl.c index eb989962d..24a0eb846 100644 --- a/libobs/callback/decl.c +++ b/libobs/callback/decl.c @@ -17,17 +17,14 @@ #include "../util/cf-parser.h" #include "decl.h" -static inline void err_specifier_exists(struct cf_parser *cfp, - const char *storage) +static inline void err_specifier_exists(struct cf_parser *cfp, const char *storage) { - cf_adderror(cfp, "'$1' specifier already exists", LEX_ERROR, storage, - NULL, NULL); + cf_adderror(cfp, "'$1' specifier already exists", LEX_ERROR, storage, NULL, NULL); } static inline void err_reserved_name(struct cf_parser *cfp, const char *name) { - cf_adderror(cfp, "'$1' is a reserved name", LEX_ERROR, name, NULL, - NULL); + cf_adderror(cfp, "'$1' is a reserved name", LEX_ERROR, name, NULL, NULL); } static inline void err_existing_name(struct cf_parser *cfp, const char *name) @@ -35,8 +32,7 @@ static inline void err_existing_name(struct cf_parser *cfp, const char *name) cf_adderror(cfp, "'$1' already exists", LEX_ERROR, name, NULL, NULL); } -static bool is_in_out_specifier(struct cf_parser *cfp, struct strref *name, - uint32_t *type) +static bool is_in_out_specifier(struct cf_parser *cfp, struct strref *name, uint32_t *type) { if (strref_cmp(name, "in") == 0) { if (*type & CALL_PARAM_IN) @@ -59,8 +55,7 @@ static bool is_in_out_specifier(struct cf_parser *cfp, struct strref *name, #define TYPE_OR_STORAGE "type or storage specifier" -static bool get_type(struct strref *ref, enum call_param_type *type, - bool is_return) +static bool get_type(struct strref *ref, enum call_param_type *type, bool is_return) { if (strref_cmp(ref, "int") == 0) *type = CALL_PARAM_TYPE_INT; @@ -82,9 +77,8 @@ static bool get_type(struct strref *ref, enum call_param_type *type, static bool is_reserved_name(const char *str) { - return (strcmp(str, "int") == 0) || (strcmp(str, "float") == 0) || - (strcmp(str, "bool") == 0) || (strcmp(str, "ptr") == 0) || - (strcmp(str, "string") == 0) || (strcmp(str, "void") == 0) || + return (strcmp(str, "int") == 0) || (strcmp(str, "float") == 0) || (strcmp(str, "bool") == 0) || + (strcmp(str, "ptr") == 0) || (strcmp(str, "string") == 0) || (strcmp(str, "void") == 0) || (strcmp(str, "return") == 0); } @@ -176,8 +170,7 @@ static void print_errors(struct cf_parser *cfp, const char *decl_string) char *errors = error_data_buildstring(&cfp->error_list); if (errors) { - blog(LOG_WARNING, "Errors/warnings for '%s':\n\n%s", - decl_string, errors); + blog(LOG_WARNING, "Errors/warnings for '%s':\n\n%s", decl_string, errors); bfree(errors); } diff --git a/libobs/callback/proc.c b/libobs/callback/proc.c index 4039fd544..eb870b838 100644 --- a/libobs/callback/proc.c +++ b/libobs/callback/proc.c @@ -79,8 +79,7 @@ void proc_handler_destroy(proc_handler_t *handler) bfree(handler); } -void proc_handler_add(proc_handler_t *handler, const char *decl_string, - proc_handler_proc_t proc, void *data) +void proc_handler_add(proc_handler_t *handler, const char *decl_string, proc_handler_proc_t proc, void *data) { if (!handler) return; @@ -89,8 +88,7 @@ void proc_handler_add(proc_handler_t *handler, const char *decl_string, memset(&pi, 0, sizeof(struct proc_info)); if (!parse_decl_string(&pi.func, decl_string)) { - blog(LOG_ERROR, "Function declaration invalid: %s", - decl_string); + blog(LOG_ERROR, "Function declaration invalid: %s", decl_string); return; } @@ -101,8 +99,7 @@ void proc_handler_add(proc_handler_t *handler, const char *decl_string, struct proc_info *existing = getproc(handler, pi.func.name); if (existing) { - blog(LOG_WARNING, "Procedure '%s' already exists", - pi.func.name); + blog(LOG_WARNING, "Procedure '%s' already exists", pi.func.name); proc_info_free(&pi); } else { da_push_back(handler->procs, &pi); @@ -111,8 +108,7 @@ void proc_handler_add(proc_handler_t *handler, const char *decl_string, pthread_mutex_unlock(&handler->mutex); } -bool proc_handler_call(proc_handler_t *handler, const char *name, - calldata_t *params) +bool proc_handler_call(proc_handler_t *handler, const char *name, calldata_t *params) { if (!handler) return false; diff --git a/libobs/callback/proc.h b/libobs/callback/proc.h index 0dd540b96..7379d17d8 100644 --- a/libobs/callback/proc.h +++ b/libobs/callback/proc.h @@ -39,15 +39,13 @@ typedef void (*proc_handler_proc_t)(void *, calldata_t *); EXPORT proc_handler_t *proc_handler_create(void); EXPORT void proc_handler_destroy(proc_handler_t *handler); -EXPORT void proc_handler_add(proc_handler_t *handler, const char *decl_string, - proc_handler_proc_t proc, void *data); +EXPORT void proc_handler_add(proc_handler_t *handler, const char *decl_string, proc_handler_proc_t proc, void *data); /** * Calls a function in a procedure handler. Returns false if the named * procedure is not found. */ -EXPORT bool proc_handler_call(proc_handler_t *handler, const char *name, - calldata_t *params); +EXPORT bool proc_handler_call(proc_handler_t *handler, const char *name, calldata_t *params); #ifdef __cplusplus } diff --git a/libobs/callback/signal.c b/libobs/callback/signal.c index 46215d789..27a0f233b 100644 --- a/libobs/callback/signal.c +++ b/libobs/callback/signal.c @@ -65,9 +65,7 @@ static inline void signal_info_destroy(struct signal_info *si) } } -static inline size_t signal_get_callback_idx(struct signal_info *si, - signal_callback_t callback, - void *data) +static inline size_t signal_get_callback_idx(struct signal_info *si, signal_callback_t callback, void *data) { for (size_t i = 0; i < si->callbacks.num; i++) { struct signal_callback *sc = si->callbacks.array + i; @@ -95,9 +93,7 @@ struct signal_handler { pthread_mutex_t global_callbacks_mutex; }; -static struct signal_info *getsignal(signal_handler_t *handler, - const char *name, - struct signal_info **p_last) +static struct signal_info *getsignal(signal_handler_t *handler, const char *name, struct signal_info **p_last) { struct signal_info *signal, *last = NULL; @@ -128,8 +124,7 @@ signal_handler_t *signal_handler_create(void) bfree(handler); return NULL; } - if (pthread_mutex_init_recursive(&handler->global_callbacks_mutex) != - 0) { + if (pthread_mutex_init_recursive(&handler->global_callbacks_mutex) != 0) { blog(LOG_ERROR, "Couldn't create signal handler global " "callbacks mutex!"); pthread_mutex_destroy(&handler->mutex); @@ -193,9 +188,7 @@ bool signal_handler_add(signal_handler_t *handler, const char *signal_decl) return success; } -static void signal_handler_connect_internal(signal_handler_t *handler, - const char *signal, - signal_callback_t callback, +static void signal_handler_connect_internal(signal_handler_t *handler, const char *signal, signal_callback_t callback, void *data, bool keep_ref) { struct signal_info *sig, *last; @@ -231,20 +224,17 @@ static void signal_handler_connect_internal(signal_handler_t *handler, pthread_mutex_unlock(&sig->mutex); } -void signal_handler_connect(signal_handler_t *handler, const char *signal, - signal_callback_t callback, void *data) +void signal_handler_connect(signal_handler_t *handler, const char *signal, signal_callback_t callback, void *data) { signal_handler_connect_internal(handler, signal, callback, data, false); } -void signal_handler_connect_ref(signal_handler_t *handler, const char *signal, - signal_callback_t callback, void *data) +void signal_handler_connect_ref(signal_handler_t *handler, const char *signal, signal_callback_t callback, void *data) { signal_handler_connect_internal(handler, signal, callback, data, true); } -static inline struct signal_info *getsignal_locked(signal_handler_t *handler, - const char *name) +static inline struct signal_info *getsignal_locked(signal_handler_t *handler, const char *name) { struct signal_info *sig; @@ -258,8 +248,7 @@ static inline struct signal_info *getsignal_locked(signal_handler_t *handler, return sig; } -void signal_handler_disconnect(signal_handler_t *handler, const char *signal, - signal_callback_t callback, void *data) +void signal_handler_disconnect(signal_handler_t *handler, const char *signal, signal_callback_t callback, void *data) { struct signal_info *sig = getsignal_locked(handler, signal); bool keep_ref = false; @@ -298,8 +287,7 @@ void signal_handler_remove_current(void) current_global_cb->remove = true; } -void signal_handler_signal(signal_handler_t *handler, const char *signal, - calldata_t *params) +void signal_handler_signal(signal_handler_t *handler, const char *signal, calldata_t *params) { struct signal_info *sig = getsignal_locked(handler, signal); long remove_refs = 0; @@ -336,8 +324,7 @@ void signal_handler_signal(signal_handler_t *handler, const char *signal, if (handler->global_callbacks.num) { for (size_t i = 0; i < handler->global_callbacks.num; i++) { - struct global_callback_info *cb = - handler->global_callbacks.array + i; + struct global_callback_info *cb = handler->global_callbacks.array + i; if (!cb->remove) { cb->signaling++; @@ -349,8 +336,7 @@ void signal_handler_signal(signal_handler_t *handler, const char *signal, } for (size_t i = handler->global_callbacks.num; i > 0; i--) { - struct global_callback_info *cb = - handler->global_callbacks.array + (i - 1); + struct global_callback_info *cb = handler->global_callbacks.array + (i - 1); if (cb->remove && !cb->signaling) da_erase(handler->global_callbacks, i - 1); @@ -360,15 +346,11 @@ void signal_handler_signal(signal_handler_t *handler, const char *signal, pthread_mutex_unlock(&handler->global_callbacks_mutex); if (remove_refs) { - os_atomic_set_long(&handler->refs, - os_atomic_load_long(&handler->refs) - - remove_refs); + os_atomic_set_long(&handler->refs, os_atomic_load_long(&handler->refs) - remove_refs); } } -void signal_handler_connect_global(signal_handler_t *handler, - global_signal_callback_t callback, - void *data) +void signal_handler_connect_global(signal_handler_t *handler, global_signal_callback_t callback, void *data) { struct global_callback_info cb_data = {callback, data, 0, false}; size_t idx; @@ -385,9 +367,7 @@ void signal_handler_connect_global(signal_handler_t *handler, pthread_mutex_unlock(&handler->global_callbacks_mutex); } -void signal_handler_disconnect_global(signal_handler_t *handler, - global_signal_callback_t callback, - void *data) +void signal_handler_disconnect_global(signal_handler_t *handler, global_signal_callback_t callback, void *data) { struct global_callback_info cb_data = {callback, data, 0, false}; size_t idx; @@ -399,8 +379,7 @@ void signal_handler_disconnect_global(signal_handler_t *handler, idx = da_find(handler->global_callbacks, &cb_data, 0); if (idx != DARRAY_INVALID) { - struct global_callback_info *cb = - handler->global_callbacks.array + idx; + struct global_callback_info *cb = handler->global_callbacks.array + idx; if (cb->signaling) cb->remove = true; diff --git a/libobs/callback/signal.h b/libobs/callback/signal.h index 7e546f9b5..8b37a2269 100644 --- a/libobs/callback/signal.h +++ b/libobs/callback/signal.h @@ -39,11 +39,9 @@ typedef void (*signal_callback_t)(void *, calldata_t *); EXPORT signal_handler_t *signal_handler_create(void); EXPORT void signal_handler_destroy(signal_handler_t *handler); -EXPORT bool signal_handler_add(signal_handler_t *handler, - const char *signal_decl); +EXPORT bool signal_handler_add(signal_handler_t *handler, const char *signal_decl); -static inline bool signal_handler_add_array(signal_handler_t *handler, - const char **signal_decls) +static inline bool signal_handler_add_array(signal_handler_t *handler, const char **signal_decls) { bool success = true; if (!signal_decls) @@ -56,27 +54,19 @@ static inline bool signal_handler_add_array(signal_handler_t *handler, return success; } -EXPORT void signal_handler_connect(signal_handler_t *handler, - const char *signal, - signal_callback_t callback, void *data); -EXPORT void signal_handler_connect_ref(signal_handler_t *handler, - const char *signal, - signal_callback_t callback, void *data); -EXPORT void signal_handler_disconnect(signal_handler_t *handler, - const char *signal, - signal_callback_t callback, void *data); +EXPORT void signal_handler_connect(signal_handler_t *handler, const char *signal, signal_callback_t callback, + void *data); +EXPORT void signal_handler_connect_ref(signal_handler_t *handler, const char *signal, signal_callback_t callback, + void *data); +EXPORT void signal_handler_disconnect(signal_handler_t *handler, const char *signal, signal_callback_t callback, + void *data); -EXPORT void signal_handler_connect_global(signal_handler_t *handler, - global_signal_callback_t callback, - void *data); -EXPORT void signal_handler_disconnect_global(signal_handler_t *handler, - global_signal_callback_t callback, - void *data); +EXPORT void signal_handler_connect_global(signal_handler_t *handler, global_signal_callback_t callback, void *data); +EXPORT void signal_handler_disconnect_global(signal_handler_t *handler, global_signal_callback_t callback, void *data); EXPORT void signal_handler_remove_current(void); -EXPORT void signal_handler_signal(signal_handler_t *handler, const char *signal, - calldata_t *params); +EXPORT void signal_handler_signal(signal_handler_t *handler, const char *signal, calldata_t *params); #ifdef __cplusplus } diff --git a/libobs/graphics/axisang.h b/libobs/graphics/axisang.h index ddbcd7d01..18937cf28 100644 --- a/libobs/graphics/axisang.h +++ b/libobs/graphics/axisang.h @@ -50,8 +50,7 @@ static inline void axisang_copy(struct axisang *dst, struct axisang *aa) dst->w = aa->w; } -static inline void axisang_set(struct axisang *dst, float x, float y, float z, - float w) +static inline void axisang_set(struct axisang *dst, float x, float y, float z, float w) { dst->x = x; dst->y = y; diff --git a/libobs/graphics/bounds.c b/libobs/graphics/bounds.c index cee018ed6..ceee0e3d1 100644 --- a/libobs/graphics/bounds.c +++ b/libobs/graphics/bounds.c @@ -21,29 +21,25 @@ #include "matrix4.h" #include "plane.h" -void bounds_move(struct bounds *dst, const struct bounds *b, - const struct vec3 *v) +void bounds_move(struct bounds *dst, const struct bounds *b, const struct vec3 *v) { vec3_add(&dst->min, &b->min, v); vec3_add(&dst->max, &b->max, v); } -void bounds_scale(struct bounds *dst, const struct bounds *b, - const struct vec3 *v) +void bounds_scale(struct bounds *dst, const struct bounds *b, const struct vec3 *v) { vec3_mul(&dst->min, &b->min, v); vec3_mul(&dst->max, &b->max, v); } -void bounds_merge(struct bounds *dst, const struct bounds *b1, - const struct bounds *b2) +void bounds_merge(struct bounds *dst, const struct bounds *b1, const struct bounds *b2) { vec3_min(&dst->min, &b1->min, &b2->min); vec3_max(&dst->max, &b1->max, &b2->max); } -void bounds_merge_point(struct bounds *dst, const struct bounds *b, - const struct vec3 *v) +void bounds_merge_point(struct bounds *dst, const struct bounds *b, const struct vec3 *v) { vec3_min(&dst->min, &b->min, v); vec3_max(&dst->max, &b->max, v); @@ -91,8 +87,7 @@ void bounds_get_center(struct vec3 *dst, const struct bounds *b) vec3_add(dst, dst, &b->min); } -void bounds_transform(struct bounds *dst, const struct bounds *b, - const struct matrix4 *m) +void bounds_transform(struct bounds *dst, const struct bounds *b, const struct matrix4 *m) { struct bounds temp; bool b_init = false; @@ -130,8 +125,7 @@ void bounds_transform(struct bounds *dst, const struct bounds *b, bounds_copy(dst, &temp); } -void bounds_transform3x4(struct bounds *dst, const struct bounds *b, - const struct matrix3 *m) +void bounds_transform3x4(struct bounds *dst, const struct bounds *b, const struct matrix3 *m) { struct bounds temp; bool b_init = false; @@ -169,8 +163,7 @@ void bounds_transform3x4(struct bounds *dst, const struct bounds *b, bounds_copy(dst, &temp); } -bool bounds_intersection_ray(const struct bounds *b, const struct vec3 *orig, - const struct vec3 *dir, float *t) +bool bounds_intersection_ray(const struct bounds *b, const struct vec3 *orig, const struct vec3 *dir, float *t) { float t_max = M_INFINITE; float t_min = -M_INFINITE; @@ -204,8 +197,7 @@ bool bounds_intersection_ray(const struct bounds *b, const struct vec3 *orig, return false; if (t_max < 0.0f) return false; - } else if ((-e - max_offset.ptr[i]) > 0.0f || - (-e + max_offset.ptr[i]) < 0.0f) { + } else if ((-e - max_offset.ptr[i]) > 0.0f || (-e + max_offset.ptr[i]) < 0.0f) { return false; } } @@ -214,8 +206,7 @@ bool bounds_intersection_ray(const struct bounds *b, const struct vec3 *orig, return true; } -bool bounds_intersection_line(const struct bounds *b, const struct vec3 *p1, - const struct vec3 *p2, float *t) +bool bounds_intersection_line(const struct bounds *b, const struct vec3 *p1, const struct vec3 *p2, float *t) { struct vec3 dir; float length; @@ -269,19 +260,14 @@ bool bounds_under_plane(const struct bounds *b, const struct plane *p) return (vec3_dot(&vmin, &p->dir) <= p->dist); } -bool bounds_intersects(const struct bounds *b, const struct bounds *test, - float epsilon) +bool bounds_intersects(const struct bounds *b, const struct bounds *test, float epsilon) { - return ((b->min.x - test->max.x) <= epsilon) && - ((test->min.x - b->max.x) <= epsilon) && - ((b->min.y - test->max.y) <= epsilon) && - ((test->min.y - b->max.y) <= epsilon) && - ((b->min.z - test->max.z) <= epsilon) && - ((test->min.z - b->max.z) <= epsilon); + return ((b->min.x - test->max.x) <= epsilon) && ((test->min.x - b->max.x) <= epsilon) && + ((b->min.y - test->max.y) <= epsilon) && ((test->min.y - b->max.y) <= epsilon) && + ((b->min.z - test->max.z) <= epsilon) && ((test->min.z - b->max.z) <= epsilon); } -bool bounds_intersects_obb(const struct bounds *b, const struct bounds *test, - const struct matrix4 *m, float epsilon) +bool bounds_intersects_obb(const struct bounds *b, const struct bounds *test, const struct matrix4 *m, float epsilon) { struct bounds b_tr, test_tr; struct matrix4 m_inv; @@ -291,12 +277,10 @@ bool bounds_intersects_obb(const struct bounds *b, const struct bounds *test, bounds_transform(&b_tr, b, m); bounds_transform(&test_tr, test, &m_inv); - return bounds_intersects(b, &test_tr, epsilon) && - bounds_intersects(&b_tr, test, epsilon); + return bounds_intersects(b, &test_tr, epsilon) && bounds_intersects(&b_tr, test, epsilon); } -bool bounds_intersects_obb3x4(const struct bounds *b, const struct bounds *test, - const struct matrix3 *m, float epsilon) +bool bounds_intersects_obb3x4(const struct bounds *b, const struct bounds *test, const struct matrix3 *m, float epsilon) { struct bounds b_tr, test_tr; struct matrix3 m_inv; @@ -306,12 +290,10 @@ bool bounds_intersects_obb3x4(const struct bounds *b, const struct bounds *test, bounds_transform3x4(&b_tr, b, m); bounds_transform3x4(&test_tr, test, &m_inv); - return bounds_intersects(b, &test_tr, epsilon) && - bounds_intersects(&b_tr, test, epsilon); + return bounds_intersects(b, &test_tr, epsilon) && bounds_intersects(&b_tr, test, epsilon); } -static inline float vec3or_offset_len(const struct bounds *b, - const struct vec3 *v) +static inline float vec3or_offset_len(const struct bounds *b, const struct vec3 *v) { struct vec3 temp1, temp2; vec3_sub(&temp1, &b->max, &b->min); diff --git a/libobs/graphics/bounds.h b/libobs/graphics/bounds.h index 8f2ab343f..4a1f5cf86 100644 --- a/libobs/graphics/bounds.h +++ b/libobs/graphics/bounds.h @@ -48,76 +48,54 @@ static inline void bounds_copy(struct bounds *dst, const struct bounds *b) vec3_copy(&dst->max, &b->max); } -EXPORT void bounds_move(struct bounds *dst, const struct bounds *b, - const struct vec3 *v); +EXPORT void bounds_move(struct bounds *dst, const struct bounds *b, const struct vec3 *v); -EXPORT void bounds_scale(struct bounds *dst, const struct bounds *b, - const struct vec3 *v); +EXPORT void bounds_scale(struct bounds *dst, const struct bounds *b, const struct vec3 *v); -EXPORT void bounds_merge(struct bounds *dst, const struct bounds *b1, - const struct bounds *b2); -EXPORT void bounds_merge_point(struct bounds *dst, const struct bounds *b, - const struct vec3 *v); +EXPORT void bounds_merge(struct bounds *dst, const struct bounds *b1, const struct bounds *b2); +EXPORT void bounds_merge_point(struct bounds *dst, const struct bounds *b, const struct vec3 *v); -EXPORT void bounds_get_point(struct vec3 *dst, const struct bounds *b, - unsigned int i); +EXPORT void bounds_get_point(struct vec3 *dst, const struct bounds *b, unsigned int i); EXPORT void bounds_get_center(struct vec3 *dst, const struct bounds *b); /** * Note: transforms as OBB, then converts back to AABB, which can result in * the actual size becoming larger than it originally was. */ -EXPORT void bounds_transform(struct bounds *dst, const struct bounds *b, - const struct matrix4 *m); -EXPORT void bounds_transform3x4(struct bounds *dst, const struct bounds *b, - const struct matrix3 *m); +EXPORT void bounds_transform(struct bounds *dst, const struct bounds *b, const struct matrix4 *m); +EXPORT void bounds_transform3x4(struct bounds *dst, const struct bounds *b, const struct matrix3 *m); -EXPORT bool bounds_intersection_ray(const struct bounds *b, - const struct vec3 *orig, - const struct vec3 *dir, float *t); -EXPORT bool bounds_intersection_line(const struct bounds *b, - const struct vec3 *p1, - const struct vec3 *p2, float *t); +EXPORT bool bounds_intersection_ray(const struct bounds *b, const struct vec3 *orig, const struct vec3 *dir, float *t); +EXPORT bool bounds_intersection_line(const struct bounds *b, const struct vec3 *p1, const struct vec3 *p2, float *t); EXPORT bool bounds_plane_test(const struct bounds *b, const struct plane *p); EXPORT bool bounds_under_plane(const struct bounds *b, const struct plane *p); -static inline bool bounds_inside(const struct bounds *b, - const struct bounds *test) +static inline bool bounds_inside(const struct bounds *b, const struct bounds *test) { - return test->min.x >= b->min.x && test->min.y >= b->min.y && - test->min.z >= b->min.z && test->max.x <= b->max.x && - test->max.y <= b->max.y && test->max.z <= b->max.z; + return test->min.x >= b->min.x && test->min.y >= b->min.y && test->min.z >= b->min.z && + test->max.x <= b->max.x && test->max.y <= b->max.y && test->max.z <= b->max.z; } -static inline bool bounds_vec3_inside(const struct bounds *b, - const struct vec3 *v) +static inline bool bounds_vec3_inside(const struct bounds *b, const struct vec3 *v) { - return v->x >= (b->min.x - EPSILON) && v->x <= (b->max.x + EPSILON) && - v->y >= (b->min.y - EPSILON) && v->y <= (b->max.y + EPSILON) && - v->z >= (b->min.z - EPSILON) && v->z <= (b->max.z + EPSILON); + return v->x >= (b->min.x - EPSILON) && v->x <= (b->max.x + EPSILON) && v->y >= (b->min.y - EPSILON) && + v->y <= (b->max.y + EPSILON) && v->z >= (b->min.z - EPSILON) && v->z <= (b->max.z + EPSILON); } -EXPORT bool bounds_intersects(const struct bounds *b, const struct bounds *test, - float epsilon); -EXPORT bool bounds_intersects_obb(const struct bounds *b, - const struct bounds *test, - const struct matrix4 *m, float epsilon); -EXPORT bool bounds_intersects_obb3x4(const struct bounds *b, - const struct bounds *test, - const struct matrix3 *m, float epsilon); +EXPORT bool bounds_intersects(const struct bounds *b, const struct bounds *test, float epsilon); +EXPORT bool bounds_intersects_obb(const struct bounds *b, const struct bounds *test, const struct matrix4 *m, + float epsilon); +EXPORT bool bounds_intersects_obb3x4(const struct bounds *b, const struct bounds *test, const struct matrix3 *m, + float epsilon); -static inline bool bounds_intersects_ray(const struct bounds *b, - const struct vec3 *orig, - const struct vec3 *dir) +static inline bool bounds_intersects_ray(const struct bounds *b, const struct vec3 *orig, const struct vec3 *dir) { float t; return bounds_intersection_ray(b, orig, dir, &t); } -static inline bool bounds_intersects_line(const struct bounds *b, - const struct vec3 *p1, - const struct vec3 *p2) +static inline bool bounds_intersects_line(const struct bounds *b, const struct vec3 *p1, const struct vec3 *p2) { float t; return bounds_intersection_line(b, p1, p2, &t); diff --git a/libobs/graphics/device-exports.h b/libobs/graphics/device-exports.h index 650aadaa7..e69565021 100644 --- a/libobs/graphics/device-exports.h +++ b/libobs/graphics/device-exports.h @@ -25,9 +25,7 @@ extern "C" { EXPORT const char *device_get_name(void); EXPORT int device_get_type(void); -EXPORT bool device_enum_adapters(gs_device_t *device, - bool (*callback)(void *param, const char *name, - uint32_t id), +EXPORT bool device_enum_adapters(gs_device_t *device, bool (*callback)(void *param, const char *name, uint32_t id), void *param); EXPORT const char *device_preprocessor_name(void); EXPORT int device_create(gs_device_t **device, uint32_t adapter); @@ -35,104 +33,66 @@ EXPORT void device_destroy(gs_device_t *device); EXPORT void device_enter_context(gs_device_t *device); EXPORT void device_leave_context(gs_device_t *device); EXPORT void *device_get_device_obj(gs_device_t *device); -EXPORT gs_swapchain_t *device_swapchain_create(gs_device_t *device, - const struct gs_init_data *data); +EXPORT gs_swapchain_t *device_swapchain_create(gs_device_t *device, const struct gs_init_data *data); EXPORT void device_resize(gs_device_t *device, uint32_t x, uint32_t y); EXPORT enum gs_color_space device_get_color_space(gs_device_t *device); EXPORT void device_update_color_space(gs_device_t *device); -EXPORT void device_get_size(const gs_device_t *device, uint32_t *x, - uint32_t *y); +EXPORT void device_get_size(const gs_device_t *device, uint32_t *x, uint32_t *y); EXPORT uint32_t device_get_width(const gs_device_t *device); EXPORT uint32_t device_get_height(const gs_device_t *device); -EXPORT gs_texture_t * -device_texture_create(gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t levels, - const uint8_t **data, uint32_t flags); -EXPORT gs_texture_t * -device_cubetexture_create(gs_device_t *device, uint32_t size, - enum gs_color_format color_format, uint32_t levels, - const uint8_t **data, uint32_t flags); -EXPORT gs_texture_t * -device_voltexture_create(gs_device_t *device, uint32_t width, uint32_t height, - uint32_t depth, enum gs_color_format color_format, - uint32_t levels, const uint8_t *const *data, - uint32_t flags); -EXPORT gs_zstencil_t *device_zstencil_create(gs_device_t *device, - uint32_t width, uint32_t height, +EXPORT gs_texture_t *device_texture_create(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t levels, const uint8_t **data, + uint32_t flags); +EXPORT gs_texture_t *device_cubetexture_create(gs_device_t *device, uint32_t size, enum gs_color_format color_format, + uint32_t levels, const uint8_t **data, uint32_t flags); +EXPORT gs_texture_t *device_voltexture_create(gs_device_t *device, uint32_t width, uint32_t height, uint32_t depth, + enum gs_color_format color_format, uint32_t levels, + const uint8_t *const *data, uint32_t flags); +EXPORT gs_zstencil_t *device_zstencil_create(gs_device_t *device, uint32_t width, uint32_t height, enum gs_zstencil_format format); -EXPORT gs_stagesurf_t * -device_stagesurface_create(gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format); -EXPORT gs_samplerstate_t * -device_samplerstate_create(gs_device_t *device, - const struct gs_sampler_info *info); -EXPORT gs_shader_t *device_vertexshader_create(gs_device_t *device, - const char *shader, - const char *file, +EXPORT gs_stagesurf_t *device_stagesurface_create(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format); +EXPORT gs_samplerstate_t *device_samplerstate_create(gs_device_t *device, const struct gs_sampler_info *info); +EXPORT gs_shader_t *device_vertexshader_create(gs_device_t *device, const char *shader, const char *file, char **error_string); -EXPORT gs_shader_t *device_pixelshader_create(gs_device_t *device, - const char *shader, - const char *file, +EXPORT gs_shader_t *device_pixelshader_create(gs_device_t *device, const char *shader, const char *file, char **error_string); -EXPORT gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, - struct gs_vb_data *data, - uint32_t flags); -EXPORT gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, - enum gs_index_type type, - void *indices, size_t num, - uint32_t flags); +EXPORT gs_vertbuffer_t *device_vertexbuffer_create(gs_device_t *device, struct gs_vb_data *data, uint32_t flags); +EXPORT gs_indexbuffer_t *device_indexbuffer_create(gs_device_t *device, enum gs_index_type type, void *indices, + size_t num, uint32_t flags); EXPORT gs_timer_t *device_timer_create(gs_device_t *device); EXPORT gs_timer_range_t *device_timer_range_create(gs_device_t *device); -EXPORT enum gs_texture_type -device_get_texture_type(const gs_texture_t *texture); -EXPORT void device_load_vertexbuffer(gs_device_t *device, - gs_vertbuffer_t *vertbuffer); -EXPORT void device_load_indexbuffer(gs_device_t *device, - gs_indexbuffer_t *indexbuffer); -EXPORT void device_load_texture(gs_device_t *device, gs_texture_t *tex, - int unit); -EXPORT void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, - int unit); -EXPORT void device_load_samplerstate(gs_device_t *device, - gs_samplerstate_t *samplerstate, int unit); -EXPORT void device_load_vertexshader(gs_device_t *device, - gs_shader_t *vertshader); -EXPORT void device_load_pixelshader(gs_device_t *device, - gs_shader_t *pixelshader); -EXPORT void device_load_default_samplerstate(gs_device_t *device, bool b_3d, - int unit); +EXPORT enum gs_texture_type device_get_texture_type(const gs_texture_t *texture); +EXPORT void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vertbuffer); +EXPORT void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer); +EXPORT void device_load_texture(gs_device_t *device, gs_texture_t *tex, int unit); +EXPORT void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, int unit); +EXPORT void device_load_samplerstate(gs_device_t *device, gs_samplerstate_t *samplerstate, int unit); +EXPORT void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader); +EXPORT void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader); +EXPORT void device_load_default_samplerstate(gs_device_t *device, bool b_3d, int unit); EXPORT gs_shader_t *device_get_vertex_shader(const gs_device_t *device); EXPORT gs_shader_t *device_get_pixel_shader(const gs_device_t *device); EXPORT gs_texture_t *device_get_render_target(const gs_device_t *device); EXPORT gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device); -EXPORT void device_set_render_target(gs_device_t *device, gs_texture_t *tex, - gs_zstencil_t *zstencil); -EXPORT void device_set_render_target_with_color_space( - gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil, - enum gs_color_space space); -EXPORT void device_set_cube_render_target(gs_device_t *device, - gs_texture_t *cubetex, int side, +EXPORT void device_set_render_target(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil); +EXPORT void device_set_render_target_with_color_space(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil, + enum gs_color_space space); +EXPORT void device_set_cube_render_target(gs_device_t *device, gs_texture_t *cubetex, int side, gs_zstencil_t *zstencil); EXPORT void device_enable_framebuffer_srgb(gs_device_t *device, bool enable); EXPORT bool device_framebuffer_srgb_enabled(gs_device_t *device); -EXPORT void device_copy_texture(gs_device_t *device, gs_texture_t *dst, - gs_texture_t *src); -EXPORT void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, - uint32_t dst_x, uint32_t dst_y, - gs_texture_t *src, uint32_t src_x, - uint32_t src_y, uint32_t src_w, +EXPORT void device_copy_texture(gs_device_t *device, gs_texture_t *dst, gs_texture_t *src); +EXPORT void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, + gs_texture_t *src, uint32_t src_x, uint32_t src_y, uint32_t src_w, uint32_t src_h); -EXPORT void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, - gs_texture_t *src); +EXPORT void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, gs_texture_t *src); EXPORT void device_begin_frame(gs_device_t *device); EXPORT void device_begin_scene(gs_device_t *device); -EXPORT void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, - uint32_t start_vert, uint32_t num_verts); +EXPORT void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, uint32_t start_vert, uint32_t num_verts); EXPORT void device_end_scene(gs_device_t *device); -EXPORT void device_load_swapchain(gs_device_t *device, - gs_swapchain_t *swapchain); -EXPORT void device_clear(gs_device_t *device, uint32_t clear_flags, - const struct vec4 *color, float depth, +EXPORT void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain); +EXPORT void device_clear(gs_device_t *device, uint32_t clear_flags, const struct vec4 *color, float depth, uint8_t stencil); EXPORT bool device_is_present_ready(gs_device_t *device); EXPORT void device_present(gs_device_t *device); @@ -143,40 +103,26 @@ EXPORT void device_enable_blending(gs_device_t *device, bool enable); EXPORT void device_enable_depth_test(gs_device_t *device, bool enable); EXPORT void device_enable_stencil_test(gs_device_t *device, bool enable); EXPORT void device_enable_stencil_write(gs_device_t *device, bool enable); -EXPORT void device_enable_color(gs_device_t *device, bool red, bool green, - bool blue, bool alpha); -EXPORT void device_blend_function(gs_device_t *device, enum gs_blend_type src, - enum gs_blend_type dest); -EXPORT void device_blend_function_separate(gs_device_t *device, - enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, - enum gs_blend_type dest_a); +EXPORT void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, bool alpha); +EXPORT void device_blend_function(gs_device_t *device, enum gs_blend_type src, enum gs_blend_type dest); +EXPORT void device_blend_function_separate(gs_device_t *device, enum gs_blend_type src_c, enum gs_blend_type dest_c, + enum gs_blend_type src_a, enum gs_blend_type dest_a); EXPORT void device_blend_op(gs_device_t *device, enum gs_blend_op_type op); EXPORT void device_depth_function(gs_device_t *device, enum gs_depth_test test); -EXPORT void device_stencil_function(gs_device_t *device, - enum gs_stencil_side side, - enum gs_depth_test test); -EXPORT void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, - enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, - enum gs_stencil_op_type zpass); -EXPORT void device_set_viewport(gs_device_t *device, int x, int y, int width, - int height); -EXPORT void device_get_viewport(const gs_device_t *device, - struct gs_rect *rect); -EXPORT void device_set_scissor_rect(gs_device_t *device, - const struct gs_rect *rect); -EXPORT void device_ortho(gs_device_t *device, float left, float right, - float top, float bottom, float znear, float zfar); -EXPORT void device_frustum(gs_device_t *device, float left, float right, - float top, float bottom, float znear, float zfar); +EXPORT void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, enum gs_depth_test test); +EXPORT void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, enum gs_stencil_op_type fail, + enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass); +EXPORT void device_set_viewport(gs_device_t *device, int x, int y, int width, int height); +EXPORT void device_get_viewport(const gs_device_t *device, struct gs_rect *rect); +EXPORT void device_set_scissor_rect(gs_device_t *device, const struct gs_rect *rect); +EXPORT void device_ortho(gs_device_t *device, float left, float right, float top, float bottom, float znear, + float zfar); +EXPORT void device_frustum(gs_device_t *device, float left, float right, float top, float bottom, float znear, + float zfar); EXPORT void device_projection_push(gs_device_t *device); EXPORT void device_projection_pop(gs_device_t *device); -EXPORT void device_debug_marker_begin(gs_device_t *device, - const char *markername, - const float color[4]); +EXPORT void device_debug_marker_begin(gs_device_t *device, const char *markername, const float color[4]); EXPORT void device_debug_marker_end(gs_device_t *device); EXPORT bool device_is_monitor_hdr(gs_device_t *device, void *monitor); EXPORT bool device_shared_texture_available(void); @@ -184,33 +130,26 @@ EXPORT bool device_nv12_available(gs_device_t *device); EXPORT bool device_p010_available(gs_device_t *device); #ifdef __APPLE__ -EXPORT gs_texture_t *device_texture_create_from_iosurface(gs_device_t *device, - void *iosurf); -EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device, - uint32_t handle); +EXPORT gs_texture_t *device_texture_create_from_iosurface(gs_device_t *device, void *iosurf); +EXPORT gs_texture_t *device_texture_open_shared(gs_device_t *device, uint32_t handle); #endif #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) -EXPORT gs_texture_t *device_texture_create_from_dmabuf( - gs_device_t *device, unsigned int width, unsigned int height, - uint32_t drm_format, enum gs_color_format color_format, - uint32_t n_planes, const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers); +EXPORT gs_texture_t *device_texture_create_from_dmabuf(gs_device_t *device, unsigned int width, unsigned int height, + uint32_t drm_format, enum gs_color_format color_format, + uint32_t n_planes, const int *fds, const uint32_t *strides, + const uint32_t *offsets, const uint64_t *modifiers); -EXPORT bool -device_query_dmabuf_capabilities(gs_device_t *device, - enum gs_dmabuf_flags *gs_dmabuf_flags, - uint32_t **drm_formats, size_t *n_formats); +EXPORT bool device_query_dmabuf_capabilities(gs_device_t *device, enum gs_dmabuf_flags *gs_dmabuf_flags, + uint32_t **drm_formats, size_t *n_formats); -EXPORT bool device_query_dmabuf_modifiers_for_format(gs_device_t *device, - uint32_t drm_format, - uint64_t **modifiers, +EXPORT bool device_query_dmabuf_modifiers_for_format(gs_device_t *device, uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers); -EXPORT gs_texture_t *device_texture_create_from_pixmap( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t target, void *pixmap); +EXPORT gs_texture_t *device_texture_create_from_pixmap(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t target, + void *pixmap); #endif #ifdef __cplusplus diff --git a/libobs/graphics/effect-parser.c b/libobs/graphics/effect-parser.c index d260f9c67..58d8cc751 100644 --- a/libobs/graphics/effect-parser.c +++ b/libobs/graphics/effect-parser.c @@ -23,8 +23,7 @@ typedef DARRAY(struct dstr) dstr_array_t; -static inline bool ep_parse_param_assign(struct effect_parser *ep, - struct ep_param *param); +static inline bool ep_parse_param_assign(struct effect_parser *ep, struct ep_param *param); static enum gs_shader_param_type get_effect_param_type(const char *type) { @@ -79,8 +78,7 @@ void ep_free(struct effect_parser *ep) da_free(ep->techniques); } -static inline struct ep_func *ep_getfunc(struct effect_parser *ep, - const char *name) +static inline struct ep_func *ep_getfunc(struct effect_parser *ep, const char *name) { size_t i; for (i = 0; i < ep->funcs.num; i++) { @@ -91,8 +89,7 @@ static inline struct ep_func *ep_getfunc(struct effect_parser *ep, return NULL; } -static inline struct ep_struct *ep_getstruct(struct effect_parser *ep, - const char *name) +static inline struct ep_struct *ep_getstruct(struct effect_parser *ep, const char *name) { size_t i; for (i = 0; i < ep->structs.num; i++) { @@ -103,8 +100,7 @@ static inline struct ep_struct *ep_getstruct(struct effect_parser *ep, return NULL; } -static inline struct ep_sampler *ep_getsampler(struct effect_parser *ep, - const char *name) +static inline struct ep_sampler *ep_getsampler(struct effect_parser *ep, const char *name) { size_t i; for (i = 0; i < ep->samplers.num; i++) { @@ -115,8 +111,7 @@ static inline struct ep_sampler *ep_getsampler(struct effect_parser *ep, return NULL; } -static inline struct ep_param *ep_getparam(struct effect_parser *ep, - const char *name) +static inline struct ep_param *ep_getparam(struct effect_parser *ep, const char *name) { size_t i; for (i = 0; i < ep->params.num; i++) { @@ -127,8 +122,7 @@ static inline struct ep_param *ep_getparam(struct effect_parser *ep, return NULL; } -static inline struct ep_param *ep_getannotation(struct ep_param *param, - const char *name) +static inline struct ep_param *ep_getannotation(struct ep_param *param, const char *name) { size_t i; for (i = 0; i < param->annotations.num; i++) { @@ -139,8 +133,7 @@ static inline struct ep_param *ep_getannotation(struct ep_param *param, return NULL; } -static inline struct ep_func *ep_getfunc_strref(struct effect_parser *ep, - const struct strref *ref) +static inline struct ep_func *ep_getfunc_strref(struct effect_parser *ep, const struct strref *ref) { size_t i; for (i = 0; i < ep->funcs.num; i++) { @@ -151,8 +144,7 @@ static inline struct ep_func *ep_getfunc_strref(struct effect_parser *ep, return NULL; } -static inline struct ep_struct *ep_getstruct_strref(struct effect_parser *ep, - const struct strref *ref) +static inline struct ep_struct *ep_getstruct_strref(struct effect_parser *ep, const struct strref *ref) { size_t i; for (i = 0; i < ep->structs.num; i++) { @@ -163,8 +155,7 @@ static inline struct ep_struct *ep_getstruct_strref(struct effect_parser *ep, return NULL; } -static inline struct ep_sampler *ep_getsampler_strref(struct effect_parser *ep, - const struct strref *ref) +static inline struct ep_sampler *ep_getsampler_strref(struct effect_parser *ep, const struct strref *ref) { size_t i; for (i = 0; i < ep->samplers.num; i++) { @@ -175,8 +166,7 @@ static inline struct ep_sampler *ep_getsampler_strref(struct effect_parser *ep, return NULL; } -static inline struct ep_param *ep_getparam_strref(struct effect_parser *ep, - const struct strref *ref) +static inline struct ep_param *ep_getparam_strref(struct effect_parser *ep, const struct strref *ref) { size_t i; for (i = 0; i < ep->params.num; i++) { @@ -187,8 +177,7 @@ static inline struct ep_param *ep_getparam_strref(struct effect_parser *ep, return NULL; } -static inline int ep_parse_struct_var(struct effect_parser *ep, - struct ep_var *var) +static inline int ep_parse_struct_var(struct effect_parser *ep, struct ep_var *var) { int code; @@ -241,8 +230,7 @@ static inline int ep_parse_struct_var(struct effect_parser *ep, if (cf_token_is(&ep->cfp, "}")) return PARSE_UNEXPECTED_BREAK; - code = cf_token_is_type(&ep->cfp, CFTOKEN_NAME, "mapping name", - ";"); + code = cf_token_is_type(&ep->cfp, CFTOKEN_NAME, "mapping name", ";"); if (code != PARSE_SUCCESS) return code; @@ -318,8 +306,7 @@ error: ep_struct_free(&eps); } -static inline int ep_parse_param_annotation_var(struct effect_parser *ep, - struct ep_param *var) +static inline int ep_parse_param_annotation_var(struct effect_parser *ep, struct ep_param *var) { int code; @@ -395,8 +382,7 @@ static inline int ep_parse_param_annotation_var(struct effect_parser *ep, return PARSE_SUCCESS; } -static int ep_parse_annotations(struct effect_parser *ep, - ep_param_array_t *annotations) +static int ep_parse_annotations(struct effect_parser *ep, ep_param_array_t *annotations) { if (!cf_token_is(&ep->cfp, "<")) { cf_adderror_expecting(&ep->cfp, "<"); @@ -408,8 +394,7 @@ static int ep_parse_annotations(struct effect_parser *ep, bool do_break = false; struct ep_param var; - ep_param_init(&var, bstrdup(""), bstrdup(""), false, false, - false); + ep_param_init(&var, bstrdup(""), bstrdup(""), false, false, false); switch (ep_parse_param_annotation_var(ep, &var)) { case PARSE_UNEXPECTED_CONTINUE: @@ -451,14 +436,12 @@ error: return false; } -static int ep_parse_param_annotations(struct effect_parser *ep, - struct ep_param *param) +static int ep_parse_param_annotations(struct effect_parser *ep, struct ep_param *param) { return ep_parse_annotations(ep, ¶m->annotations); } -static inline int ep_parse_pass_command_call(struct effect_parser *ep, - cf_token_array_t *call) +static inline int ep_parse_pass_command_call(struct effect_parser *ep, cf_token_array_t *call) { struct cf_token end_token; cf_token_clear(&end_token); @@ -486,12 +469,10 @@ static int ep_parse_pass_command(struct effect_parser *ep, struct ep_pass *pass) if (!cf_next_valid_token(&ep->cfp)) return PARSE_EOF; - if (cf_token_is(&ep->cfp, "vertex_shader") || - cf_token_is(&ep->cfp, "vertex_program")) { + if (cf_token_is(&ep->cfp, "vertex_shader") || cf_token_is(&ep->cfp, "vertex_program")) { call = &pass->vertex_program; - } else if (cf_token_is(&ep->cfp, "pixel_shader") || - cf_token_is(&ep->cfp, "pixel_program")) { + } else if (cf_token_is(&ep->cfp, "pixel_shader") || cf_token_is(&ep->cfp, "pixel_program")) { call = &pass->fragment_program; } else { @@ -507,8 +488,7 @@ static int ep_parse_pass_command(struct effect_parser *ep, struct ep_pass *pass) if (!cf_next_valid_token(&ep->cfp)) return PARSE_EOF; if (cf_token_is(&ep->cfp, "compile")) { - cf_adderror(&ep->cfp, "compile keyword not necessary", - LEX_WARNING, NULL, NULL, NULL); + cf_adderror(&ep->cfp, "compile keyword not necessary", LEX_WARNING, NULL, NULL, NULL); if (!cf_next_valid_token(&ep->cfp)) return PARSE_EOF; } @@ -527,8 +507,7 @@ static int ep_parse_pass(struct effect_parser *ep, struct ep_pass *pass) return PARSE_EOF; if (!cf_token_is(&ep->cfp, "{")) { - pass->name = bstrdup_n(ep->cfp.cur_token->str.array, - ep->cfp.cur_token->str.len); + pass->name = bstrdup_n(ep->cfp.cur_token->str.array, ep->cfp.cur_token->str.len); if (!cf_next_valid_token(&ep->cfp)) return PARSE_EOF; } @@ -606,8 +585,7 @@ error: ep_technique_free(&ept); } -static int ep_parse_sampler_state_item(struct effect_parser *ep, - struct ep_sampler *eps) +static int ep_parse_sampler_state_item(struct effect_parser *ep, struct ep_sampler *eps) { int ret; char *state = NULL; @@ -682,8 +660,7 @@ error: ep_sampler_free(&eps); } -static inline int ep_check_for_keyword(struct effect_parser *ep, - const char *keyword, bool *val) +static inline int ep_check_for_keyword(struct effect_parser *ep, const char *keyword, bool *val) { bool new_val = cf_token_is(&ep->cfp, keyword); if (new_val) { @@ -691,8 +668,7 @@ static inline int ep_check_for_keyword(struct effect_parser *ep, return PARSE_EOF; if (new_val && *val) - cf_adderror(&ep->cfp, "'$1' keyword already specified", - LEX_WARNING, keyword, NULL, NULL); + cf_adderror(&ep->cfp, "'$1' keyword already specified", LEX_WARNING, keyword, NULL, NULL); *val = new_val; return PARSE_CONTINUE; @@ -701,8 +677,7 @@ static inline int ep_check_for_keyword(struct effect_parser *ep, return PARSE_SUCCESS; } -static inline int ep_parse_func_param(struct effect_parser *ep, - struct ep_func *func, struct ep_var *var) +static inline int ep_parse_func_param(struct effect_parser *ep, struct ep_func *func, struct ep_var *var) { int code; bool var_type_keyword = false; @@ -752,8 +727,7 @@ static inline int ep_parse_func_param(struct effect_parser *ep, return PARSE_EOF; if (cf_token_is(&ep->cfp, ":")) { - code = cf_next_name(&ep->cfp, &var->mapping, - "mapping specifier", ")"); + code = cf_next_name(&ep->cfp, &var->mapping, "mapping specifier", ")"); if (code != PARSE_SUCCESS) return code; @@ -808,18 +782,15 @@ exit: return true; } -static inline bool ep_process_struct_dep(struct effect_parser *ep, - struct ep_func *func) +static inline bool ep_process_struct_dep(struct effect_parser *ep, struct ep_func *func) { - struct ep_struct *val = - ep_getstruct_strref(ep, &ep->cfp.cur_token->str); + struct ep_struct *val = ep_getstruct_strref(ep, &ep->cfp.cur_token->str); if (val) da_push_back(func->struct_deps, &val->name); return val != NULL; } -static inline bool ep_process_func_dep(struct effect_parser *ep, - struct ep_func *func) +static inline bool ep_process_func_dep(struct effect_parser *ep, struct ep_func *func) { struct ep_func *val = ep_getfunc_strref(ep, &ep->cfp.cur_token->str); if (val) @@ -827,18 +798,15 @@ static inline bool ep_process_func_dep(struct effect_parser *ep, return val != NULL; } -static inline bool ep_process_sampler_dep(struct effect_parser *ep, - struct ep_func *func) +static inline bool ep_process_sampler_dep(struct effect_parser *ep, struct ep_func *func) { - struct ep_sampler *val = - ep_getsampler_strref(ep, &ep->cfp.cur_token->str); + struct ep_sampler *val = ep_getsampler_strref(ep, &ep->cfp.cur_token->str); if (val) da_push_back(func->sampler_deps, &val->name); return val != NULL; } -static inline bool ep_process_param_dep(struct effect_parser *ep, - struct ep_func *func) +static inline bool ep_process_param_dep(struct effect_parser *ep, struct ep_func *func) { struct ep_param *val = ep_getparam_strref(ep, &ep->cfp.cur_token->str); if (val) @@ -846,8 +814,7 @@ static inline bool ep_process_param_dep(struct effect_parser *ep, return val != NULL; } -static inline bool ep_parse_func_contents(struct effect_parser *ep, - struct ep_func *func) +static inline bool ep_parse_func_contents(struct effect_parser *ep, struct ep_func *func) { int braces = 1; @@ -857,16 +824,13 @@ static inline bool ep_parse_func_contents(struct effect_parser *ep, if ((ep->cfp.cur_token++)->type == CFTOKEN_NONE) return false; - if (ep->cfp.cur_token->type == CFTOKEN_SPACETAB || - ep->cfp.cur_token->type == CFTOKEN_NEWLINE) { + if (ep->cfp.cur_token->type == CFTOKEN_SPACETAB || ep->cfp.cur_token->type == CFTOKEN_NEWLINE) { } else if (cf_token_is(&ep->cfp, "{")) { braces++; } else if (cf_token_is(&ep->cfp, "}")) { braces--; - } else if (ep_process_struct_dep(ep, func) || - ep_process_func_dep(ep, func) || - ep_process_sampler_dep(ep, func) || - ep_process_param_dep(ep, func)) { + } else if (ep_process_struct_dep(ep, func) || ep_process_func_dep(ep, func) || + ep_process_sampler_dep(ep, func) || ep_process_param_dep(ep, func)) { } dstr_cat_strref(&func->contents, &ep->cfp.cur_token->str); @@ -892,8 +856,7 @@ static void ep_parse_function(struct effect_parser *ep, char *type, char *name) /* if function is mapped to something, for example COLOR */ if (cf_token_is(&ep->cfp, ":")) { - code = cf_next_name(&ep->cfp, &func.mapping, - "mapping specifier", "{"); + code = cf_next_name(&ep->cfp, &func.mapping, "mapping specifier", "{"); if (code == PARSE_EOF) goto error; else if (code != PARSE_CONTINUE) { @@ -921,19 +884,16 @@ error: } /* parses "array[count]" */ -static bool ep_parse_param_array(struct effect_parser *ep, - struct ep_param *param) +static bool ep_parse_param_array(struct effect_parser *ep, struct ep_param *param) { if (!cf_next_valid_token(&ep->cfp)) return false; if (ep->cfp.cur_token->type != CFTOKEN_NUM || - !valid_int_str(ep->cfp.cur_token->str.array, - ep->cfp.cur_token->str.len)) + !valid_int_str(ep->cfp.cur_token->str.array, ep->cfp.cur_token->str.len)) return false; - param->array_count = - (int)strtol(ep->cfp.cur_token->str.array, NULL, 10); + param->array_count = (int)strtol(ep->cfp.cur_token->str.array, NULL, 10); if (cf_next_token_should_be(&ep->cfp, "]", ";", NULL) == PARSE_EOF) return false; @@ -944,8 +904,7 @@ static bool ep_parse_param_array(struct effect_parser *ep, return true; } -static inline int ep_parse_param_assign_texture(struct effect_parser *ep, - struct ep_param *param) +static inline int ep_parse_param_assign_texture(struct effect_parser *ep, struct ep_param *param) { int code; char *str; @@ -953,13 +912,11 @@ static inline int ep_parse_param_assign_texture(struct effect_parser *ep, if (!cf_next_valid_token(&ep->cfp)) return PARSE_EOF; - code = cf_token_is_type(&ep->cfp, CFTOKEN_STRING, "texture path string", - ";"); + code = cf_token_is_type(&ep->cfp, CFTOKEN_STRING, "texture path string", ";"); if (code != PARSE_SUCCESS) return code; - str = cf_literal_to_str(ep->cfp.cur_token->str.array, - ep->cfp.cur_token->str.len); + str = cf_literal_to_str(ep->cfp.cur_token->str.array, ep->cfp.cur_token->str.len); if (str) { da_copy_array(param->default_val, str, strlen(str) + 1); @@ -969,8 +926,7 @@ static inline int ep_parse_param_assign_texture(struct effect_parser *ep, return PARSE_SUCCESS; } -static inline int ep_parse_param_assign_string(struct effect_parser *ep, - struct ep_param *param) +static inline int ep_parse_param_assign_string(struct effect_parser *ep, struct ep_param *param) { int code; char *str = NULL; @@ -982,8 +938,7 @@ static inline int ep_parse_param_assign_string(struct effect_parser *ep, if (code != PARSE_SUCCESS) return code; - str = cf_literal_to_str(ep->cfp.cur_token->str.array, - ep->cfp.cur_token->str.len); + str = cf_literal_to_str(ep->cfp.cur_token->str.array, ep->cfp.cur_token->str.len); if (str) { da_copy_array(param->default_val, str, strlen(str) + 1); @@ -993,9 +948,7 @@ static inline int ep_parse_param_assign_string(struct effect_parser *ep, return PARSE_SUCCESS; } -static inline int ep_parse_param_assign_intfloat(struct effect_parser *ep, - struct ep_param *param, - bool is_float) +static inline int ep_parse_param_assign_intfloat(struct effect_parser *ep, struct ep_param *param, bool is_float) { int code; bool is_negative = false; @@ -1018,34 +971,29 @@ static inline int ep_parse_param_assign_intfloat(struct effect_parser *ep, float f = (float)os_strtod(ep->cfp.cur_token->str.array); if (is_negative) f = -f; - da_push_back_array(param->default_val, (uint8_t *)&f, - sizeof(float)); + da_push_back_array(param->default_val, (uint8_t *)&f, sizeof(float)); } else { long l = strtol(ep->cfp.cur_token->str.array, NULL, 10); if (is_negative) l = -l; - da_push_back_array(param->default_val, (uint8_t *)&l, - sizeof(long)); + da_push_back_array(param->default_val, (uint8_t *)&l, sizeof(long)); } return PARSE_SUCCESS; } -static inline int ep_parse_param_assign_bool(struct effect_parser *ep, - struct ep_param *param) +static inline int ep_parse_param_assign_bool(struct effect_parser *ep, struct ep_param *param) { if (!cf_next_valid_token(&ep->cfp)) return PARSE_EOF; if (cf_token_is(&ep->cfp, "true")) { long l = 1; - da_push_back_array(param->default_val, (uint8_t *)&l, - sizeof(long)); + da_push_back_array(param->default_val, (uint8_t *)&l, sizeof(long)); return PARSE_SUCCESS; } else if (cf_token_is(&ep->cfp, "false")) { long l = 0; - da_push_back_array(param->default_val, (uint8_t *)&l, - sizeof(long)); + da_push_back_array(param->default_val, (uint8_t *)&l, sizeof(long)); return PARSE_SUCCESS; } @@ -1058,9 +1006,7 @@ static inline int ep_parse_param_assign_bool(struct effect_parser *ep, * parses assignment for float1, float2, float3, float4, int1, int2, int3, int4, * and any combination for float3x3, float4x4, int3x3, int4x4, etc */ -static inline int ep_parse_param_assign_intfloat_array(struct effect_parser *ep, - struct ep_param *param, - bool is_float) +static inline int ep_parse_param_assign_intfloat_array(struct effect_parser *ep, struct ep_param *param, bool is_float) { const char *intfloat_type = param->type + (is_float ? 5 : 3); int intfloat_count = 0, code, i; @@ -1068,15 +1014,13 @@ static inline int ep_parse_param_assign_intfloat_array(struct effect_parser *ep, /* -------------------------------------------- */ if (intfloat_type[0] < '1' || intfloat_type[0] > '4') - cf_adderror(&ep->cfp, "Invalid row count", LEX_ERROR, NULL, - NULL, NULL); + cf_adderror(&ep->cfp, "Invalid row count", LEX_ERROR, NULL, NULL, NULL); intfloat_count = intfloat_type[0] - '0'; if (intfloat_type[1] == 'x') { if (intfloat_type[2] < '1' || intfloat_type[2] > '4') - cf_adderror(&ep->cfp, "Invalid column count", LEX_ERROR, - NULL, NULL, NULL); + cf_adderror(&ep->cfp, "Invalid column count", LEX_ERROR, NULL, NULL, NULL); intfloat_count *= intfloat_type[2] - '0'; } @@ -1102,8 +1046,7 @@ static inline int ep_parse_param_assign_intfloat_array(struct effect_parser *ep, return PARSE_SUCCESS; } -static int ep_parse_param_assignment_val(struct effect_parser *ep, - struct ep_param *param) +static int ep_parse_param_assignment_val(struct effect_parser *ep, struct ep_param *param) { if (param->is_texture) return ep_parse_param_assign_texture(ep, param); @@ -1120,14 +1063,12 @@ static int ep_parse_param_assignment_val(struct effect_parser *ep, else if (strcmp(param->type, "bool") == 0) return ep_parse_param_assign_bool(ep, param); - cf_adderror(&ep->cfp, "Invalid type '$1' used for assignment", - LEX_ERROR, param->type, NULL, NULL); + cf_adderror(&ep->cfp, "Invalid type '$1' used for assignment", LEX_ERROR, param->type, NULL, NULL); return PARSE_CONTINUE; } -static inline bool ep_parse_param_assign(struct effect_parser *ep, - struct ep_param *param) +static inline bool ep_parse_param_assign(struct effect_parser *ep, struct ep_param *param) { if (ep_parse_param_assignment_val(ep, param) != PARSE_SUCCESS) return false; @@ -1143,8 +1084,8 @@ static inline bool ep_parse_param_assign(struct effect_parser *ep, { } */ -static void ep_parse_param(struct effect_parser *ep, char *type, char *name, - bool is_property, bool is_const, bool is_uniform) +static void ep_parse_param(struct effect_parser *ep, char *type, char *name, bool is_property, bool is_const, + bool is_uniform) { struct ep_param param; ep_param_init(¶m, type, name, is_property, is_const, is_uniform); @@ -1153,8 +1094,7 @@ static void ep_parse_param(struct effect_parser *ep, char *type, char *name, goto complete; if (cf_token_is(&ep->cfp, "[") && !ep_parse_param_array(ep, ¶m)) goto error; - if (cf_token_is(&ep->cfp, "<") && - !ep_parse_param_annotations(ep, ¶m)) + if (cf_token_is(&ep->cfp, "<") && !ep_parse_param_annotations(ep, ¶m)) goto error; if (cf_token_is(&ep->cfp, "=") && !ep_parse_param_assign(ep, ¶m)) goto error; @@ -1172,8 +1112,7 @@ error: ep_param_free(¶m); } -static bool ep_get_var_specifiers(struct effect_parser *ep, bool *is_property, - bool *is_const, bool *is_uniform) +static bool ep_get_var_specifiers(struct effect_parser *ep, bool *is_property, bool *is_const, bool *is_uniform) { while (true) { int code; @@ -1201,8 +1140,7 @@ static bool ep_get_var_specifiers(struct effect_parser *ep, bool *is_property, return true; } -static inline void report_invalid_func_keyword(struct effect_parser *ep, - const char *name, bool val) +static inline void report_invalid_func_keyword(struct effect_parser *ep, const char *name, bool val) { if (val) cf_adderror(&ep->cfp, @@ -1234,8 +1172,7 @@ static void ep_parse_other(struct effect_parser *ep) ep_parse_function(ep, type, name); return; } else { - ep_parse_param(ep, type, name, is_property, is_const, - is_uniform); + ep_parse_param(ep, type, name, is_property, is_const, is_uniform); return; } @@ -1249,8 +1186,7 @@ static bool ep_compile(struct effect_parser *ep); extern const char *gs_preprocessor_name(void); #if defined(_DEBUG) && defined(_DEBUG_SHADERS) -static void debug_get_default_value(struct gs_effect_param *param, char *buffer, - unsigned long long buf_size) +static void debug_get_default_value(struct gs_effect_param *param, char *buffer, unsigned long long buf_size) { if (param->default_val.num == 0) { snprintf(buffer, buf_size, "(null)"); @@ -1259,78 +1195,55 @@ static void debug_get_default_value(struct gs_effect_param *param, char *buffer, switch (param->type) { case GS_SHADER_PARAM_STRING: - snprintf(buffer, buf_size, "'%.*s'", param->default_val.num, - param->default_val.array); + snprintf(buffer, buf_size, "'%.*s'", param->default_val.num, param->default_val.array); break; case GS_SHADER_PARAM_INT: - snprintf(buffer, buf_size, "%ld", - *(int *)(param->default_val.array + 0)); + snprintf(buffer, buf_size, "%ld", *(int *)(param->default_val.array + 0)); break; case GS_SHADER_PARAM_INT2: - snprintf(buffer, buf_size, "%ld,%ld", - *(int *)(param->default_val.array + 0), + snprintf(buffer, buf_size, "%ld,%ld", *(int *)(param->default_val.array + 0), *(int *)(param->default_val.array + 4)); break; case GS_SHADER_PARAM_INT3: - snprintf(buffer, buf_size, "%ld,%ld,%ld", - *(int *)(param->default_val.array + 0), - *(int *)(param->default_val.array + 4), - *(int *)(param->default_val.array + 8)); + snprintf(buffer, buf_size, "%ld,%ld,%ld", *(int *)(param->default_val.array + 0), + *(int *)(param->default_val.array + 4), *(int *)(param->default_val.array + 8)); break; case GS_SHADER_PARAM_INT4: - snprintf(buffer, buf_size, "%ld,%ld,%ld,%ld", - *(int *)(param->default_val.array + 0), - *(int *)(param->default_val.array + 4), - *(int *)(param->default_val.array + 8), + snprintf(buffer, buf_size, "%ld,%ld,%ld,%ld", *(int *)(param->default_val.array + 0), + *(int *)(param->default_val.array + 4), *(int *)(param->default_val.array + 8), *(int *)(param->default_val.array + 12)); break; case GS_SHADER_PARAM_FLOAT: - snprintf(buffer, buf_size, "%e", - *(float *)(param->default_val.array + 0)); + snprintf(buffer, buf_size, "%e", *(float *)(param->default_val.array + 0)); break; case GS_SHADER_PARAM_VEC2: - snprintf(buffer, buf_size, "%e,%e", - *(float *)(param->default_val.array + 0), + snprintf(buffer, buf_size, "%e,%e", *(float *)(param->default_val.array + 0), *(float *)(param->default_val.array + 4)); break; case GS_SHADER_PARAM_VEC3: - snprintf(buffer, buf_size, "%e,%e,%e", - *(float *)(param->default_val.array + 0), - *(float *)(param->default_val.array + 4), - *(float *)(param->default_val.array + 8)); + snprintf(buffer, buf_size, "%e,%e,%e", *(float *)(param->default_val.array + 0), + *(float *)(param->default_val.array + 4), *(float *)(param->default_val.array + 8)); break; case GS_SHADER_PARAM_VEC4: - snprintf(buffer, buf_size, "%e,%e,%e,%e", - *(float *)(param->default_val.array + 0), - *(float *)(param->default_val.array + 4), - *(float *)(param->default_val.array + 8), + snprintf(buffer, buf_size, "%e,%e,%e,%e", *(float *)(param->default_val.array + 0), + *(float *)(param->default_val.array + 4), *(float *)(param->default_val.array + 8), *(float *)(param->default_val.array + 12)); break; case GS_SHADER_PARAM_MATRIX4X4: snprintf(buffer, buf_size, "[[%e,%e,%e,%e],[%e,%e,%e,%e]," "[%e,%e,%e,%e],[%e,%e,%e,%e]]", - *(float *)(param->default_val.array + 0), - *(float *)(param->default_val.array + 4), - *(float *)(param->default_val.array + 8), - *(float *)(param->default_val.array + 12), - *(float *)(param->default_val.array + 16), - *(float *)(param->default_val.array + 20), - *(float *)(param->default_val.array + 24), - *(float *)(param->default_val.array + 28), - *(float *)(param->default_val.array + 32), - *(float *)(param->default_val.array + 36), - *(float *)(param->default_val.array + 40), - *(float *)(param->default_val.array + 44), - *(float *)(param->default_val.array + 48), - *(float *)(param->default_val.array + 52), - *(float *)(param->default_val.array + 56), - *(float *)(param->default_val.array + 60)); + *(float *)(param->default_val.array + 0), *(float *)(param->default_val.array + 4), + *(float *)(param->default_val.array + 8), *(float *)(param->default_val.array + 12), + *(float *)(param->default_val.array + 16), *(float *)(param->default_val.array + 20), + *(float *)(param->default_val.array + 24), *(float *)(param->default_val.array + 28), + *(float *)(param->default_val.array + 32), *(float *)(param->default_val.array + 36), + *(float *)(param->default_val.array + 40), *(float *)(param->default_val.array + 44), + *(float *)(param->default_val.array + 48), *(float *)(param->default_val.array + 52), + *(float *)(param->default_val.array + 56), *(float *)(param->default_val.array + 60)); break; case GS_SHADER_PARAM_BOOL: - snprintf(buffer, buf_size, "%s", - (*param->default_val.array) != 0 ? "true\0" - : "false\0"); + snprintf(buffer, buf_size, "%s", (*param->default_val.array) != 0 ? "true\0" : "false\0"); break; case GS_SHADER_PARAM_UNKNOWN: case GS_SHADER_PARAM_TEXTURE: @@ -1339,8 +1252,7 @@ static void debug_get_default_value(struct gs_effect_param *param, char *buffer, } } -static void debug_param(struct gs_effect_param *param, - struct ep_param *param_in, unsigned long long idx, +static void debug_param(struct gs_effect_param *param, struct ep_param *param_in, unsigned long long idx, const char *offset) { char _debug_type[4096]; @@ -1389,25 +1301,22 @@ static void debug_param(struct gs_effect_param *param, char _debug_buf[4096]; debug_get_default_value(param, _debug_buf, sizeof(_debug_buf)); if (param->annotations.num > 0) { - blog(LOG_DEBUG, - "%s[%4lld] %.*s '%s' with value %.*s and %lld annotations:", - offset, idx, sizeof(_debug_type), _debug_type, param->name, - sizeof(_debug_buf), _debug_buf, param->annotations.num); + blog(LOG_DEBUG, "%s[%4lld] %.*s '%s' with value %.*s and %lld annotations:", offset, idx, + sizeof(_debug_type), _debug_type, param->name, sizeof(_debug_buf), _debug_buf, + param->annotations.num); } else { - blog(LOG_DEBUG, "%s[%4lld] %.*s '%s' with value %.*s.", offset, - idx, sizeof(_debug_type), _debug_type, param->name, - sizeof(_debug_buf), _debug_buf); + blog(LOG_DEBUG, "%s[%4lld] %.*s '%s' with value %.*s.", offset, idx, sizeof(_debug_type), _debug_type, + param->name, sizeof(_debug_buf), _debug_buf); } } -static void debug_param_annotation(struct gs_effect_param *param, - struct ep_param *param_in, - unsigned long long idx, const char *offset) +static void debug_param_annotation(struct gs_effect_param *param, struct ep_param *param_in, unsigned long long idx, + const char *offset) { char _debug_buf[4096]; debug_get_default_value(param, _debug_buf, sizeof(_debug_buf)); - blog(LOG_DEBUG, "%s[%4lld] %s '%s' with value %.*s", offset, idx, - param_in->type, param->name, sizeof(_debug_buf), _debug_buf); + blog(LOG_DEBUG, "%s[%4lld] %s '%s' with value %.*s", offset, idx, param_in->type, param->name, + sizeof(_debug_buf), _debug_buf); } static void debug_print_string(const char *offset, const char *str) @@ -1438,14 +1347,12 @@ static void debug_print_string(const char *offset, const char *str) } if (begin[0] != '\0') { // Final line was not written. - blog(LOG_DEBUG, "\t\t\t\t[%4lld] %*s", line, strlen(begin), - begin); + blog(LOG_DEBUG, "\t\t\t\t[%4lld] %*s", line, strlen(begin), begin); } } #endif -bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, - const char *effect_string, const char *file) +bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, const char *effect_string, const char *file) { bool success; @@ -1467,8 +1374,7 @@ bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, return false; while (ep->cfp.cur_token && ep->cfp.cur_token->type != CFTOKEN_NONE) { - if (cf_token_is(&ep->cfp, ";") || - is_whitespace(*ep->cfp.cur_token->str.array)) { + if (cf_token_is(&ep->cfp, ";") || is_whitespace(*ep->cfp.cur_token->str.array)) { /* do nothing */ ep->cfp.cur_token++; @@ -1483,8 +1389,7 @@ bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, } else if (cf_token_is(&ep->cfp, "{")) { /* add error and pass braces */ - cf_adderror(&ep->cfp, "Unexpected code segment", - LEX_ERROR, NULL, NULL, NULL); + cf_adderror(&ep->cfp, "Unexpected code segment", LEX_ERROR, NULL, NULL, NULL); cf_pass_pair(&ep->cfp, '{', '}'); } else { @@ -1494,8 +1399,7 @@ bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, } #if defined(_DEBUG) && defined(_DEBUG_SHADERS) - blog(LOG_DEBUG, - "================================================================================"); + blog(LOG_DEBUG, "================================================================================"); blog(LOG_DEBUG, "Effect Parser reformatted shader '%s' to:", file); debug_print_string("\t", ep->cfp.lex.reformatted); #endif @@ -1505,8 +1409,7 @@ bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, success = ep_compile(ep); #if defined(_DEBUG) && defined(_DEBUG_SHADERS) - blog(LOG_DEBUG, - "================================================================================"); + blog(LOG_DEBUG, "================================================================================"); #endif return success; @@ -1514,8 +1417,7 @@ bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, /* ------------------------------------------------------------------------- */ -static inline void ep_write_param(struct dstr *shader, struct ep_param *param, - dstr_array_t *used_params) +static inline void ep_write_param(struct dstr *shader, struct ep_param *param, dstr_array_t *used_params) { if (param->written) return; @@ -1542,9 +1444,7 @@ static inline void ep_write_param(struct dstr *shader, struct ep_param *param, param->written = true; } -static inline void ep_write_func_param_deps(struct effect_parser *ep, - struct dstr *shader, - struct ep_func *func, +static inline void ep_write_func_param_deps(struct effect_parser *ep, struct dstr *shader, struct ep_func *func, dstr_array_t *used_params) { size_t i; @@ -1581,9 +1481,7 @@ static void ep_write_sampler(struct dstr *shader, struct ep_sampler *sampler) sampler->written = true; } -static inline void ep_write_func_sampler_deps(struct effect_parser *ep, - struct dstr *shader, - struct ep_func *func) +static inline void ep_write_func_sampler_deps(struct effect_parser *ep, struct dstr *shader, struct ep_func *func) { size_t i; for (i = 0; i < func->sampler_deps.num; i++) { @@ -1637,9 +1535,7 @@ static void ep_write_struct(struct dstr *shader, struct ep_struct *st) st->written = true; } -static inline void ep_write_func_struct_deps(struct effect_parser *ep, - struct dstr *shader, - struct ep_func *func) +static inline void ep_write_func_struct_deps(struct effect_parser *ep, struct dstr *shader, struct ep_func *func) { size_t i; for (i = 0; i < func->struct_deps.num; i++) { @@ -1654,12 +1550,10 @@ static inline void ep_write_func_struct_deps(struct effect_parser *ep, } } -static void ep_write_func(struct effect_parser *ep, struct dstr *shader, - struct ep_func *func, dstr_array_t *used_params); +static void ep_write_func(struct effect_parser *ep, struct dstr *shader, struct ep_func *func, + dstr_array_t *used_params); -static inline void ep_write_func_func_deps(struct effect_parser *ep, - struct dstr *shader, - struct ep_func *func, +static inline void ep_write_func_func_deps(struct effect_parser *ep, struct dstr *shader, struct ep_func *func, dstr_array_t *used_params) { size_t i; @@ -1674,8 +1568,8 @@ static inline void ep_write_func_func_deps(struct effect_parser *ep, } } -static void ep_write_func(struct effect_parser *ep, struct dstr *shader, - struct ep_func *func, dstr_array_t *used_params) +static void ep_write_func(struct effect_parser *ep, struct dstr *shader, struct ep_func *func, + dstr_array_t *used_params) { size_t i; @@ -1707,8 +1601,8 @@ static void ep_write_func(struct effect_parser *ep, struct dstr *shader, } /* writes mapped vars used by the call as parameters for main */ -static void ep_write_main_params(struct effect_parser *ep, struct dstr *shader, - struct dstr *param_str, struct ep_func *func) +static void ep_write_main_params(struct effect_parser *ep, struct dstr *shader, struct dstr *param_str, + struct ep_func *func) { size_t i; bool empty_params = dstr_is_empty(param_str); @@ -1744,8 +1638,7 @@ static void ep_write_main_params(struct effect_parser *ep, struct dstr *shader, dstr_cat(param_str, ", "); } -static void ep_write_main(struct effect_parser *ep, struct dstr *shader, - struct ep_func *func, struct dstr *call_str) +static void ep_write_main(struct effect_parser *ep, struct dstr *shader, struct ep_func *func, struct dstr *call_str) { struct dstr param_str; struct dstr adjusted_call; @@ -1786,8 +1679,7 @@ static inline void ep_reset_written(struct effect_parser *ep) ep->samplers.array[i].written = false; } -static void ep_makeshaderstring(struct effect_parser *ep, struct dstr *shader, - cf_token_array_t *shader_call, +static void ep_makeshaderstring(struct effect_parser *ep, struct dstr *shader, cf_token_array_t *shader_call, dstr_array_t *used_params) { struct cf_token *token = shader_call->array; @@ -1829,8 +1721,7 @@ static void ep_makeshaderstring(struct effect_parser *ep, struct dstr *shader, ep_reset_written(ep); } -static void ep_compile_annotations(ep_param_array_t *ep_annotations, - gs_effect_param_array_t *gsp_annotations, +static void ep_compile_annotations(ep_param_array_t *ep_annotations, gs_effect_param_array_t *gsp_annotations, struct effect_parser *ep) { da_resize(*gsp_annotations, ep_annotations->num); @@ -1853,13 +1744,10 @@ static void ep_compile_annotations(ep_param_array_t *ep_annotations, } } -static void -ep_compile_param_annotations(struct ep_param *ep_param_input, - struct gs_effect_param *gs_effect_input, - struct effect_parser *ep) +static void ep_compile_param_annotations(struct ep_param *ep_param_input, struct gs_effect_param *gs_effect_input, + struct effect_parser *ep) { - ep_compile_annotations(&(ep_param_input->annotations), - &(gs_effect_input->annotations), ep); + ep_compile_annotations(&(ep_param_input->annotations), &(gs_effect_input->annotations), ep); } static void ep_compile_param(struct effect_parser *ep, size_t idx) @@ -1890,10 +1778,8 @@ static void ep_compile_param(struct effect_parser *ep, size_t idx) ep_compile_param_annotations(param_in, param, ep); } -static bool ep_compile_pass_shaderparams(struct effect_parser *ep, - pass_shaderparam_array_t *pass_params, - dstr_array_t *used_params, - gs_shader_t *shader) +static bool ep_compile_pass_shaderparams(struct effect_parser *ep, pass_shaderparam_array_t *pass_params, + dstr_array_t *used_params, gs_shader_t *shader) { size_t i; da_resize(*pass_params, used_params->num); @@ -1902,10 +1788,8 @@ static bool ep_compile_pass_shaderparams(struct effect_parser *ep, struct dstr *param_name = used_params->array + i; struct pass_shaderparam *param = pass_params->array + i; - param->eparam = gs_effect_get_param_by_name(ep->effect, - param_name->array); - param->sparam = - gs_shader_get_param_by_name(shader, param_name->array); + param->eparam = gs_effect_get_param_by_name(ep->effect, param_name->array); + param->sparam = gs_shader_get_param_by_name(shader, param_name->array); #if defined(_DEBUG) && defined(_DEBUG_SHADERS) debug_param(param->eparam, 0, i, "\t\t\t\t"); @@ -1920,11 +1804,8 @@ static bool ep_compile_pass_shaderparams(struct effect_parser *ep, return true; } -static inline bool ep_compile_pass_shader(struct effect_parser *ep, - struct gs_effect_technique *tech, - struct gs_effect_pass *pass, - struct ep_pass *pass_in, - size_t pass_idx, +static inline bool ep_compile_pass_shader(struct effect_parser *ep, struct gs_effect_technique *tech, + struct gs_effect_pass *pass, struct ep_pass *pass_in, size_t pass_idx, enum gs_shader_type type) { struct dstr shader_str; @@ -1948,46 +1829,38 @@ static inline bool ep_compile_pass_shader(struct effect_parser *ep, dstr_cat(&location, " (Geometry ");*/ assert(pass_idx <= UINT_MAX); - dstr_catf(&location, "shader, technique %s, pass %u)", tech->name, - (unsigned)pass_idx); + dstr_catf(&location, "shader, technique %s, pass %u)", tech->name, (unsigned)pass_idx); if (type == GS_SHADER_VERTEX) { - ep_makeshaderstring(ep, &shader_str, &pass_in->vertex_program, - &used_params); + ep_makeshaderstring(ep, &shader_str, &pass_in->vertex_program, &used_params); - pass->vertshader = gs_vertexshader_create( - shader_str.array, location.array, &errors); + pass->vertshader = gs_vertexshader_create(shader_str.array, location.array, &errors); shader = pass->vertshader; pass_params = &pass->vertshader_params; } else if (type == GS_SHADER_PIXEL) { - ep_makeshaderstring(ep, &shader_str, &pass_in->fragment_program, - &used_params); + ep_makeshaderstring(ep, &shader_str, &pass_in->fragment_program, &used_params); - pass->pixelshader = gs_pixelshader_create( - shader_str.array, location.array, &errors); + pass->pixelshader = gs_pixelshader_create(shader_str.array, location.array, &errors); shader = pass->pixelshader; pass_params = &pass->pixelshader_params; } if (errors && strlen(errors)) { - cf_adderror(&ep->cfp, "Error creating shader: $1", LEX_ERROR, - errors, NULL, NULL); + cf_adderror(&ep->cfp, "Error creating shader: $1", LEX_ERROR, errors, NULL, NULL); } bfree(errors); #if defined(_DEBUG) && defined(_DEBUG_SHADERS) - blog(LOG_DEBUG, "\t\t\t%s Shader:", - type == GS_SHADER_VERTEX ? "Vertex" : "Fragment"); + blog(LOG_DEBUG, "\t\t\t%s Shader:", type == GS_SHADER_VERTEX ? "Vertex" : "Fragment"); blog(LOG_DEBUG, "\t\t\tCode:"); debug_print_string("\t\t\t\t\t", shader_str.array); blog(LOG_DEBUG, "\t\t\tParameters:"); #endif if (shader) - success = ep_compile_pass_shaderparams(ep, pass_params, - &used_params, shader); + success = ep_compile_pass_shaderparams(ep, pass_params, &used_params, shader); else success = false; @@ -1999,9 +1872,8 @@ static inline bool ep_compile_pass_shader(struct effect_parser *ep, return success; } -static bool ep_compile_pass(struct effect_parser *ep, - struct gs_effect_technique *tech, - struct ep_technique *tech_in, size_t idx) +static bool ep_compile_pass(struct effect_parser *ep, struct gs_effect_technique *tech, struct ep_technique *tech_in, + size_t idx) { struct gs_effect_pass *pass; struct ep_pass *pass_in; @@ -2017,17 +1889,13 @@ static bool ep_compile_pass(struct effect_parser *ep, blog(LOG_DEBUG, "\t\t[%4lld] Pass '%s':", idx, pass->name); #endif - if (!ep_compile_pass_shader(ep, tech, pass, pass_in, idx, - GS_SHADER_VERTEX)) { + if (!ep_compile_pass_shader(ep, tech, pass, pass_in, idx, GS_SHADER_VERTEX)) { success = false; - blog(LOG_ERROR, "Pass (%zu) <%s> missing vertex shader!", idx, - pass->name ? pass->name : ""); + blog(LOG_ERROR, "Pass (%zu) <%s> missing vertex shader!", idx, pass->name ? pass->name : ""); } - if (!ep_compile_pass_shader(ep, tech, pass, pass_in, idx, - GS_SHADER_PIXEL)) { + if (!ep_compile_pass_shader(ep, tech, pass, pass_in, idx, GS_SHADER_PIXEL)) { success = false; - blog(LOG_ERROR, "Pass (%zu) <%s> missing pixel shader!", idx, - pass->name ? pass->name : ""); + blog(LOG_ERROR, "Pass (%zu) <%s> missing pixel shader!", idx, pass->name ? pass->name : ""); } return success; } @@ -2049,8 +1917,7 @@ static inline bool ep_compile_technique(struct effect_parser *ep, size_t idx) da_resize(tech->passes, tech_in->passes.num); #if defined(_DEBUG) && defined(_DEBUG_SHADERS) - blog(LOG_DEBUG, "\t[%4lld] Technique '%s' has %lld passes:", idx, - tech->name, tech->passes.num); + blog(LOG_DEBUG, "\t[%4lld] Technique '%s' has %lld passes:", idx, tech->name, tech->passes.num); #endif for (i = 0; i < tech->passes.num; i++) { diff --git a/libobs/graphics/effect-parser.h b/libobs/graphics/effect-parser.h index e0f555c8f..529dea4b0 100644 --- a/libobs/graphics/effect-parser.h +++ b/libobs/graphics/effect-parser.h @@ -41,13 +41,7 @@ typedef DARRAY(struct ep_var) ep_var_array_t; /* ------------------------------------------------------------------------- */ /* effect parser var data */ -enum ep_var_type { - EP_VAR_NONE, - EP_VAR_IN = EP_VAR_NONE, - EP_VAR_INOUT, - EP_VAR_OUT, - EP_VAR_UNIFORM -}; +enum ep_var_type { EP_VAR_NONE, EP_VAR_IN = EP_VAR_NONE, EP_VAR_INOUT, EP_VAR_OUT, EP_VAR_UNIFORM }; struct ep_var { char *type, *name, *mapping; @@ -79,8 +73,7 @@ struct ep_param { ep_param_array_t annotations; }; -static inline void ep_param_init(struct ep_param *epp, char *type, char *name, - bool is_property, bool is_const, +static inline void ep_param_init(struct ep_param *epp, char *type, char *name, bool is_property, bool is_const, bool is_uniform) { epp->type = type; @@ -290,8 +283,7 @@ static inline void ep_init(struct effect_parser *ep) extern void ep_free(struct effect_parser *ep); -extern bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, - const char *effect_string, const char *file); +extern bool ep_parse(struct effect_parser *ep, gs_effect_t *effect, const char *effect_string, const char *file); #ifdef __cplusplus } diff --git a/libobs/graphics/effect.c b/libobs/graphics/effect.c index 88c73fe87..76a6183c7 100644 --- a/libobs/graphics/effect.c +++ b/libobs/graphics/effect.c @@ -35,8 +35,7 @@ void gs_effect_destroy(gs_effect_t *effect) } } -gs_technique_t *gs_effect_get_technique(const gs_effect_t *effect, - const char *name) +gs_technique_t *gs_effect_get_technique(const gs_effect_t *effect, const char *name) { if (!effect) return NULL; @@ -89,8 +88,7 @@ bool gs_effect_loop(gs_effect_t *effect, const char *name) gs_technique_end_pass(effect->cur_technique); } - if (!gs_technique_begin_pass(effect->cur_technique, - effect->loop_pass++)) { + if (!gs_technique_begin_pass(effect->cur_technique, effect->loop_pass++)) { gs_technique_end(effect->cur_technique); effect->looping = false; effect->loop_pass = 0; @@ -145,8 +143,7 @@ static inline void reset_params(pass_shaderparam_array_t *shaderparams) params[i].eparam->changed = false; } -static void upload_shader_params(pass_shaderparam_array_t *pass_params, - bool changed_only) +static void upload_shader_params(pass_shaderparam_array_t *pass_params, bool changed_only) { struct pass_shaderparam *params = pass_params->array; size_t i; @@ -157,8 +154,7 @@ static void upload_shader_params(pass_shaderparam_array_t *pass_params, gs_sparam_t *sparam = param->sparam; if (eparam->next_sampler) - gs_shader_set_next_sampler(sparam, - eparam->next_sampler); + gs_shader_set_next_sampler(sparam, eparam->next_sampler); if (changed_only && !eparam->changed) continue; @@ -170,13 +166,11 @@ static void upload_shader_params(pass_shaderparam_array_t *pass_params, continue; } - gs_shader_set_val(sparam, eparam->cur_val.array, - eparam->cur_val.num); + gs_shader_set_val(sparam, eparam->cur_val.array, eparam->cur_val.num); } } -static inline void upload_parameters(struct gs_effect *effect, - bool changed_only) +static inline void upload_parameters(struct gs_effect *effect, bool changed_only) { pass_shaderparam_array_t *vshader_params, *pshader_params; @@ -278,8 +272,7 @@ gs_eparam_t *gs_effect_get_param_by_idx(const gs_effect_t *effect, size_t param) return params + param; } -gs_eparam_t *gs_effect_get_param_by_name(const gs_effect_t *effect, - const char *name) +gs_eparam_t *gs_effect_get_param_by_name(const gs_effect_t *effect, const char *name) { if (!effect) return NULL; @@ -301,8 +294,7 @@ size_t gs_param_get_num_annotations(const gs_eparam_t *param) return param ? param->annotations.num : 0; } -gs_eparam_t *gs_param_get_annotation_by_idx(const gs_eparam_t *param, - size_t annotation) +gs_eparam_t *gs_param_get_annotation_by_idx(const gs_eparam_t *param, size_t annotation) { if (!param) return NULL; @@ -314,8 +306,7 @@ gs_eparam_t *gs_param_get_annotation_by_idx(const gs_eparam_t *param, return params + annotation; } -gs_eparam_t *gs_param_get_annotation_by_name(const gs_eparam_t *param, - const char *name) +gs_eparam_t *gs_param_get_annotation_by_name(const gs_eparam_t *param, const char *name) { if (!param) return NULL; @@ -329,8 +320,7 @@ gs_eparam_t *gs_param_get_annotation_by_name(const gs_eparam_t *param, return NULL; } -gs_epass_t *gs_technique_get_pass_by_idx(const gs_technique_t *technique, - size_t pass) +gs_epass_t *gs_technique_get_pass_by_idx(const gs_technique_t *technique, size_t pass) { if (!technique) return NULL; @@ -342,8 +332,7 @@ gs_epass_t *gs_technique_get_pass_by_idx(const gs_technique_t *technique, return passes + pass; } -gs_epass_t *gs_technique_get_pass_by_name(const gs_technique_t *technique, - const char *name) +gs_epass_t *gs_technique_get_pass_by_name(const gs_technique_t *technique, const char *name) { if (!technique) return NULL; @@ -367,8 +356,7 @@ gs_eparam_t *gs_effect_get_world_matrix(const gs_effect_t *effect) return effect ? effect->world : NULL; } -void gs_effect_get_param_info(const gs_eparam_t *param, - struct gs_effect_param_info *info) +void gs_effect_get_param_info(const gs_eparam_t *param, struct gs_effect_param_info *info) { if (!param) return; @@ -377,8 +365,7 @@ void gs_effect_get_param_info(const gs_eparam_t *param, info->type = param->type; } -static inline void effect_setval_inline(gs_eparam_t *param, const void *data, - size_t size) +static inline void effect_setval_inline(gs_eparam_t *param, const void *data, size_t size) { bool size_changed; @@ -406,8 +393,7 @@ static inline void effect_setval_inline(gs_eparam_t *param, const void *data, #ifndef min #define min(a, b) (((a) < (b)) ? (a) : (b)) #endif -static inline void effect_getval_inline(gs_eparam_t *param, void *data, - size_t size) +static inline void effect_getval_inline(gs_eparam_t *param, void *data, size_t size) { if (!param) { blog(LOG_ERROR, "effect_getval_inline: invalid param"); @@ -424,8 +410,7 @@ static inline void effect_getval_inline(gs_eparam_t *param, void *data, memcpy(data, param->cur_val.array, bytes); } -static inline void effect_getdefaultval_inline(gs_eparam_t *param, void *data, - size_t size) +static inline void effect_getdefaultval_inline(gs_eparam_t *param, void *data, size_t size) { if (!param) { blog(LOG_ERROR, "effect_getdefaultval_inline: invalid param"); @@ -556,8 +541,7 @@ size_t gs_effect_get_default_val_size(gs_eparam_t *param) void gs_effect_set_default(gs_eparam_t *param) { - effect_setval_inline(param, param->default_val.array, - param->default_val.num); + effect_setval_inline(param, param->default_val.array, param->default_val.num); } void gs_effect_set_next_sampler(gs_eparam_t *param, gs_samplerstate_t *sampler) diff --git a/libobs/graphics/effect.h b/libobs/graphics/effect.h index 138a9fd43..703b71599 100644 --- a/libobs/graphics/effect.h +++ b/libobs/graphics/effect.h @@ -40,13 +40,7 @@ typedef DARRAY(struct pass_shaderparam) pass_shaderparam_array_t; /* ------------------------------------------------------------------------- */ -enum effect_section { - EFFECT_PARAM, - EFFECT_TECHNIQUE, - EFFECT_SAMPLER, - EFFECT_PASS, - EFFECT_ANNOTATION -}; +enum effect_section { EFFECT_PARAM, EFFECT_TECHNIQUE, EFFECT_SAMPLER, EFFECT_PASS, EFFECT_ANNOTATION }; /* ------------------------------------------------------------------------- */ @@ -88,8 +82,7 @@ static inline void effect_param_free(struct gs_effect_param *param) da_free(param->annotations); } -EXPORT void effect_param_parse_property(gs_eparam_t *param, - const char *property); +EXPORT void effect_param_parse_property(gs_eparam_t *param, const char *property); /* ------------------------------------------------------------------------- */ diff --git a/libobs/graphics/graphics-ffmpeg.c b/libobs/graphics/graphics-ffmpeg.c index aef1ff318..00face958 100644 --- a/libobs/graphics/graphics-ffmpeg.c +++ b/libobs/graphics/graphics-ffmpeg.c @@ -28,22 +28,18 @@ struct ffmpeg_image { static bool ffmpeg_image_open_decoder_context(struct ffmpeg_image *info) { AVFormatContext *const fmt_ctx = info->fmt_ctx; - int ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, 1, NULL, - 0); + int ret = av_find_best_stream(fmt_ctx, AVMEDIA_TYPE_VIDEO, -1, 1, NULL, 0); if (ret < 0) { - blog(LOG_WARNING, "Couldn't find video stream in file '%s': %s", - info->file, av_err2str(ret)); + blog(LOG_WARNING, "Couldn't find video stream in file '%s': %s", info->file, av_err2str(ret)); return false; } AVStream *const stream = fmt_ctx->streams[ret]; AVCodecParameters *const codecpar = stream->codecpar; - const AVCodec *const decoder = avcodec_find_decoder( - codecpar->codec_id); // fix discarded-qualifiers + const AVCodec *const decoder = avcodec_find_decoder(codecpar->codec_id); // fix discarded-qualifiers if (!decoder) { - blog(LOG_WARNING, "Failed to find decoder for file '%s'", - info->file); + blog(LOG_WARNING, "Failed to find decoder for file '%s'", info->file); return false; } @@ -85,8 +81,7 @@ static bool ffmpeg_image_init(struct ffmpeg_image *info, const char *file) ret = avformat_open_input(&info->fmt_ctx, file, NULL, NULL); if (ret < 0) { - blog(LOG_WARNING, "Failed to open file '%s': %s", info->file, - av_err2str(ret)); + blog(LOG_WARNING, "Failed to open file '%s': %s", info->file, av_err2str(ret)); return false; } @@ -115,8 +110,7 @@ fail: #define obs_bswap16(v) __builtin_bswap16(v) #endif -static void *ffmpeg_image_copy_data_straight(struct ffmpeg_image *info, - AVFrame *frame) +static void *ffmpeg_image_copy_data_straight(struct ffmpeg_image *info, AVFrame *frame) { const size_t linesize = (size_t)info->cx * 4; const size_t totalsize = info->cy * linesize; @@ -124,8 +118,7 @@ static void *ffmpeg_image_copy_data_straight(struct ffmpeg_image *info, const size_t src_linesize = frame->linesize[0]; if (linesize != src_linesize) { - const size_t min_line = linesize < src_linesize ? linesize - : src_linesize; + const size_t min_line = linesize < src_linesize ? linesize : src_linesize; uint8_t *dst = data; const uint8_t *src = frame->data[0]; @@ -141,9 +134,7 @@ static void *ffmpeg_image_copy_data_straight(struct ffmpeg_image *info, return data; } -static inline size_t get_dst_position(const size_t w, const size_t h, - const size_t x, const size_t y, - int orient) +static inline size_t get_dst_position(const size_t w, const size_t h, const size_t x, const size_t y, int orient) { size_t res_x = 0; size_t res_y = 0; @@ -302,8 +293,7 @@ static inline size_t get_dst_position(const size_t w, const size_t h, #define TILE_SIZE 16 #define MIN(a, b) (((a) < (b)) ? (a) : (b)) -static void *ffmpeg_image_orient(struct ffmpeg_image *info, void *in_data, - int orient) +static void *ffmpeg_image_orient(struct ffmpeg_image *info, void *in_data, int orient) { const size_t sx = (size_t)info->cx; const size_t sy = (size_t)info->cy; @@ -332,12 +322,9 @@ static void *ffmpeg_image_orient(struct ffmpeg_image *info, void *in_data, for (size_t x = x0; x < lim_x; x++) { off_src = (x + y * sx) * 4; - off_dst = get_dst_position(info->cx, - info->cy, x, - y, orient); + off_dst = get_dst_position(info->cx, info->cy, x, y, orient); - memcpy(data + off_dst, src + off_src, - 4); + memcpy(data + off_dst, src + off_src, 4); } } } @@ -347,9 +334,7 @@ static void *ffmpeg_image_orient(struct ffmpeg_image *info, void *in_data, return data; } -static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, - AVFrame *frame, - enum gs_image_alpha_mode alpha_mode) +static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, AVFrame *frame, enum gs_image_alpha_mode alpha_mode) { struct SwsContext *sws_ctx = NULL; void *data = NULL; @@ -361,8 +346,7 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, int orient = 0; if (dict) { - entry = av_dict_get(dict, "Orientation", NULL, - AV_DICT_MATCH_CASE); + entry = av_dict_get(dict, "Orientation", NULL, AV_DICT_MATCH_CASE); if (entry && entry->value) { orient = atoi(entry->value); } @@ -370,8 +354,7 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, if (info->format == AV_PIX_FMT_BGR0) { data = ffmpeg_image_copy_data_straight(info, frame); - } else if (info->format == AV_PIX_FMT_RGBA || - info->format == AV_PIX_FMT_BGRA) { + } else if (info->format == AV_PIX_FMT_RGBA || info->format == AV_PIX_FMT_BGRA) { if (alpha_mode == GS_IMAGE_ALPHA_STRAIGHT) { data = ffmpeg_image_copy_data_straight(info, frame); } else { @@ -379,23 +362,19 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, const size_t totalsize = info->cy * linesize; data = bmalloc(totalsize); const size_t src_linesize = frame->linesize[0]; - const size_t min_line = linesize < src_linesize - ? linesize - : src_linesize; + const size_t min_line = linesize < src_linesize ? linesize : src_linesize; uint8_t *dst = data; const uint8_t *src = frame->data[0]; const size_t row_elements = min_line >> 2; if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) { for (int y = 0; y < info->cy; y++) { - gs_premultiply_xyza_srgb_loop_restrict( - dst, src, row_elements); + gs_premultiply_xyza_srgb_loop_restrict(dst, src, row_elements); dst += linesize; src += src_linesize; } } else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) { for (int y = 0; y < info->cy; y++) { - gs_premultiply_xyza_loop_restrict( - dst, src, row_elements); + gs_premultiply_xyza_loop_restrict(dst, src, row_elements); dst += linesize; src += src_linesize; } @@ -405,9 +384,7 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, const size_t dst_linesize = (size_t)info->cx * 4; data = bmalloc(info->cy * dst_linesize); const size_t src_linesize = frame->linesize[0]; - const size_t src_min_line = (dst_linesize * 2) < src_linesize - ? (dst_linesize * 2) - : src_linesize; + const size_t src_min_line = (dst_linesize * 2) < src_linesize ? (dst_linesize * 2) : src_linesize; const size_t row_elements = src_min_line >> 3; uint8_t *dst = data; const uint8_t *src = frame->data[0]; @@ -417,14 +394,10 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, for (int y = 0; y < info->cy; y++) { for (size_t x = 0; x < row_elements; ++x) { memcpy(value, src, sizeof(value)); - f[0] = (float)obs_bswap16(value[0]) / - 65535.0f; - f[1] = (float)obs_bswap16(value[1]) / - 65535.0f; - f[2] = (float)obs_bswap16(value[2]) / - 65535.0f; - f[3] = (float)obs_bswap16(value[3]) / - 65535.0f; + f[0] = (float)obs_bswap16(value[0]) / 65535.0f; + f[1] = (float)obs_bswap16(value[1]) / 65535.0f; + f[2] = (float)obs_bswap16(value[2]) / 65535.0f; + f[3] = (float)obs_bswap16(value[3]) / 65535.0f; gs_float4_to_u8x4(dst, f); dst += sizeof(*dst) * 4; src += sizeof(value); @@ -436,14 +409,10 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, for (int y = 0; y < info->cy; y++) { for (size_t x = 0; x < row_elements; ++x) { memcpy(value, src, sizeof(value)); - f[0] = (float)obs_bswap16(value[0]) / - 65535.0f; - f[1] = (float)obs_bswap16(value[1]) / - 65535.0f; - f[2] = (float)obs_bswap16(value[2]) / - 65535.0f; - f[3] = (float)obs_bswap16(value[3]) / - 65535.0f; + f[0] = (float)obs_bswap16(value[0]) / 65535.0f; + f[1] = (float)obs_bswap16(value[1]) / 65535.0f; + f[2] = (float)obs_bswap16(value[2]) / 65535.0f; + f[3] = (float)obs_bswap16(value[3]) / 65535.0f; gs_float3_srgb_nonlinear_to_linear(f); gs_premultiply_float4(f); gs_float3_srgb_linear_to_nonlinear(f); @@ -458,14 +427,10 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, for (int y = 0; y < info->cy; y++) { for (size_t x = 0; x < row_elements; ++x) { memcpy(value, src, sizeof(value)); - f[0] = (float)obs_bswap16(value[0]) / - 65535.0f; - f[1] = (float)obs_bswap16(value[1]) / - 65535.0f; - f[2] = (float)obs_bswap16(value[2]) / - 65535.0f; - f[3] = (float)obs_bswap16(value[3]) / - 65535.0f; + f[0] = (float)obs_bswap16(value[0]) / 65535.0f; + f[1] = (float)obs_bswap16(value[1]) / 65535.0f; + f[2] = (float)obs_bswap16(value[2]) / 65535.0f; + f[3] = (float)obs_bswap16(value[3]) / 65535.0f; gs_premultiply_float4(f); gs_float4_to_u8x4(dst, f); dst += sizeof(*dst) * 4; @@ -480,9 +445,8 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, } else { static const enum AVPixelFormat format = AV_PIX_FMT_BGRA; - sws_ctx = sws_getContext(info->cx, info->cy, info->format, - info->cx, info->cy, format, SWS_POINT, - NULL, NULL, NULL); + sws_ctx = sws_getContext(info->cx, info->cy, info->format, info->cx, info->cy, format, SWS_POINT, NULL, + NULL, NULL); if (!sws_ctx) { blog(LOG_WARNING, "Failed to create scale context " @@ -493,23 +457,19 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, uint8_t *pointers[4]; int linesizes[4]; - ret = av_image_alloc(pointers, linesizes, info->cx, info->cy, - format, 32); + ret = av_image_alloc(pointers, linesizes, info->cx, info->cy, format, 32); if (ret < 0) { - blog(LOG_WARNING, "av_image_alloc failed for '%s': %s", - info->file, av_err2str(ret)); + blog(LOG_WARNING, "av_image_alloc failed for '%s': %s", info->file, av_err2str(ret)); sws_freeContext(sws_ctx); goto fail; } - ret = sws_scale(sws_ctx, (const uint8_t *const *)frame->data, - frame->linesize, 0, info->cy, pointers, + ret = sws_scale(sws_ctx, (const uint8_t *const *)frame->data, frame->linesize, 0, info->cy, pointers, linesizes); sws_freeContext(sws_ctx); if (ret < 0) { - blog(LOG_WARNING, "sws_scale failed for '%s': %s", - info->file, av_err2str(ret)); + blog(LOG_WARNING, "sws_scale failed for '%s': %s", info->file, av_err2str(ret)); av_freep(pointers); goto fail; } @@ -527,11 +487,9 @@ static void *ffmpeg_image_reformat_frame(struct ffmpeg_image *info, av_freep(pointers); if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) { - gs_premultiply_xyza_srgb_loop(data, (size_t)info->cx * - info->cy); + gs_premultiply_xyza_srgb_loop(data, (size_t)info->cx * info->cy); } else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) { - gs_premultiply_xyza_loop(data, - (size_t)info->cx * info->cy); + gs_premultiply_xyza_loop(data, (size_t)info->cx * info->cy); } info->format = format; @@ -543,8 +501,7 @@ fail: return data; } -static void *ffmpeg_image_decode(struct ffmpeg_image *info, - enum gs_image_alpha_mode alpha_mode) +static void *ffmpeg_image_decode(struct ffmpeg_image *info, enum gs_image_alpha_mode alpha_mode) { AVPacket packet = {0}; void *data = NULL; @@ -553,15 +510,13 @@ static void *ffmpeg_image_decode(struct ffmpeg_image *info, int ret; if (!frame) { - blog(LOG_WARNING, "Failed to create frame data for '%s'", - info->file); + blog(LOG_WARNING, "Failed to create frame data for '%s'", info->file); return NULL; } ret = av_read_frame(info->fmt_ctx, &packet); if (ret < 0) { - blog(LOG_WARNING, "Failed to read image frame from '%s': %s", - info->file, av_err2str(ret)); + blog(LOG_WARNING, "Failed to read image frame from '%s': %s", info->file, av_err2str(ret)); goto fail; } @@ -576,8 +531,7 @@ static void *ffmpeg_image_decode(struct ffmpeg_image *info, ret = 0; if (ret < 0) { - blog(LOG_WARNING, "Failed to decode frame for '%s': %s", - info->file, av_err2str(ret)); + blog(LOG_WARNING, "Failed to decode frame for '%s': %s", info->file, av_err2str(ret)); goto fail; } } @@ -610,9 +564,7 @@ static inline enum gs_color_format convert_format(enum AVPixelFormat format) } } -uint8_t *gs_create_texture_file_data(const char *file, - enum gs_color_format *format, - uint32_t *cx_out, uint32_t *cy_out) +uint8_t *gs_create_texture_file_data(const char *file, enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out) { struct ffmpeg_image image; uint8_t *data = NULL; @@ -635,13 +587,10 @@ uint8_t *gs_create_texture_file_data(const char *file, static float pq_to_linear(float u) { const float common = powf(u, 1.f / 78.84375f); - return powf(fabsf(max(common - 0.8359375f, 0.f) / - (18.8515625f - 18.6875f * common)), - 1.f / 0.1593017578f); + return powf(fabsf(max(common - 0.8359375f, 0.f) / (18.8515625f - 18.6875f * common)), 1.f / 0.1593017578f); } -static void convert_pq_to_cccs(const BYTE *intermediate, - const UINT intermediate_size, BYTE *bytes) +static void convert_pq_to_cccs(const BYTE *intermediate, const UINT intermediate_size, BYTE *bytes) { const BYTE *src_cursor = intermediate; const BYTE *src_cursor_end = src_cursor + intermediate_size; @@ -657,14 +606,11 @@ static void convert_pq_to_cccs(const BYTE *intermediate, const float red2020 = pq_to_linear(red); const float green2020 = pq_to_linear(green); const float blue2020 = pq_to_linear(blue); - const float red709 = 1.6604910021084345f * red2020 - - 0.58764113878854951f * green2020 - + const float red709 = 1.6604910021084345f * red2020 - 0.58764113878854951f * green2020 - 0.072849863319884883f * blue2020; - const float green709 = -0.12455047452159074f * red2020 + - 1.1328998971259603f * green2020 - + const float green709 = -0.12455047452159074f * red2020 + 1.1328998971259603f * green2020 - 0.0083494226043694768f * blue2020; - const float blue709 = -0.018150763354905303f * red2020 - - 0.10057889800800739f * green2020 + + const float blue709 = -0.018150763354905303f * red2020 - 0.10057889800800739f * green2020 + 1.1187296613629127f * blue2020; rgba16[0] = half_from_float(red709 * 125.f); rgba16[1] = half_from_float(green709 * 125.f); @@ -675,23 +621,16 @@ static void convert_pq_to_cccs(const BYTE *intermediate, } } -static void *wic_image_init_internal(const char *file, - IWICBitmapFrameDecode *pFrame, - enum gs_color_format *format, - uint32_t *cx_out, uint32_t *cy_out, - enum gs_color_space *space) +static void *wic_image_init_internal(const char *file, IWICBitmapFrameDecode *pFrame, enum gs_color_format *format, + uint32_t *cx_out, uint32_t *cy_out, enum gs_color_space *space) { BYTE *bytes = NULL; WICPixelFormatGUID pixelFormat; HRESULT hr = pFrame->lpVtbl->GetPixelFormat(pFrame, &pixelFormat); if (SUCCEEDED(hr)) { - const bool scrgb = memcmp(&pixelFormat, - &GUID_WICPixelFormat64bppRGBAHalf, - sizeof(pixelFormat)) == 0; - const bool pq10 = memcmp(&pixelFormat, - &GUID_WICPixelFormat32bppBGR101010, - sizeof(pixelFormat)) == 0; + const bool scrgb = memcmp(&pixelFormat, &GUID_WICPixelFormat64bppRGBAHalf, sizeof(pixelFormat)) == 0; + const bool pq10 = memcmp(&pixelFormat, &GUID_WICPixelFormat32bppBGR101010, sizeof(pixelFormat)) == 0; if (scrgb || pq10) { UINT width, height; hr = pFrame->lpVtbl->GetSize(pFrame, &width, &height); @@ -702,25 +641,18 @@ static void *wic_image_init_internal(const char *file, if (bytes) { bool success = false; if (pq10) { - const UINT intermediate_pitch = - 4 * width; - const UINT intermediate_size = - intermediate_pitch * - height; - BYTE *intermediate = bmalloc( - intermediate_size); + const UINT intermediate_pitch = 4 * width; + const UINT intermediate_size = intermediate_pitch * height; + BYTE *intermediate = bmalloc(intermediate_size); if (intermediate) { - hr = pFrame->lpVtbl->CopyPixels( - pFrame, NULL, - intermediate_pitch, - intermediate_size, - intermediate); + hr = pFrame->lpVtbl->CopyPixels(pFrame, NULL, + intermediate_pitch, + intermediate_size, + intermediate); success = SUCCEEDED(hr); if (success) { - convert_pq_to_cccs( - intermediate, - intermediate_size, - bytes); + convert_pq_to_cccs(intermediate, intermediate_size, + bytes); } else { blog(LOG_WARNING, "WIC: Failed to CopyPixels intermediate for file: %s", @@ -730,17 +662,13 @@ static void *wic_image_init_internal(const char *file, bfree(intermediate); } else { blog(LOG_WARNING, - "WIC: Failed to allocate intermediate for file: %s", - file); + "WIC: Failed to allocate intermediate for file: %s", file); } } else { - hr = pFrame->lpVtbl->CopyPixels( - pFrame, NULL, pitch, - size, bytes); + hr = pFrame->lpVtbl->CopyPixels(pFrame, NULL, pitch, size, bytes); success = SUCCEEDED(hr); if (!success) { - blog(LOG_WARNING, - "WIC: Failed to CopyPixels for file: %s", + blog(LOG_WARNING, "WIC: Failed to CopyPixels for file: %s", file); } } @@ -755,35 +683,28 @@ static void *wic_image_init_internal(const char *file, bytes = NULL; } } else { - blog(LOG_WARNING, - "WIC: Failed to allocate for file: %s", - file); + blog(LOG_WARNING, "WIC: Failed to allocate for file: %s", file); } } else { - blog(LOG_WARNING, - "WIC: Failed to GetSize of frame for file: %s", - file); + blog(LOG_WARNING, "WIC: Failed to GetSize of frame for file: %s", file); } } else { blog(LOG_WARNING, "WIC: Only handle GUID_WICPixelFormat32bppBGR101010 and GUID_WICPixelFormat64bppRGBAHalf for now"); } } else { - blog(LOG_WARNING, "WIC: Failed to GetPixelFormat for file: %s", - file); + blog(LOG_WARNING, "WIC: Failed to GetPixelFormat for file: %s", file); } return bytes; } -static void *wic_image_init(const struct ffmpeg_image *info, const char *file, - enum gs_color_format *format, uint32_t *cx_out, - uint32_t *cy_out, enum gs_color_space *space) +static void *wic_image_init(const struct ffmpeg_image *info, const char *file, enum gs_color_format *format, + uint32_t *cx_out, uint32_t *cy_out, enum gs_color_space *space) { const size_t len = strlen(file); if (len <= 4 && astrcmpi(file + len - 4, ".jxr") != 0) { - blog(LOG_WARNING, - "WIC: Only handle JXR for WIC images for now"); + blog(LOG_WARNING, "WIC: Only handle JXR for WIC images for now"); return NULL; } @@ -793,42 +714,32 @@ static void *wic_image_init(const struct ffmpeg_image *info, const char *file, os_utf8_to_wcs_ptr(file, 0, &file_w); if (file_w) { IWICImagingFactory *pFactory = NULL; - HRESULT hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, - CLSCTX_INPROC_SERVER, - &IID_IWICImagingFactory, - &pFactory); + HRESULT hr = CoCreateInstance(&CLSID_WICImagingFactory, NULL, CLSCTX_INPROC_SERVER, + &IID_IWICImagingFactory, &pFactory); if (SUCCEEDED(hr)) { IWICBitmapDecoder *pDecoder = NULL; - hr = pFactory->lpVtbl->CreateDecoderFromFilename( - pFactory, file_w, NULL, GENERIC_READ, - WICDecodeMetadataCacheOnDemand, &pDecoder); + hr = pFactory->lpVtbl->CreateDecoderFromFilename(pFactory, file_w, NULL, GENERIC_READ, + WICDecodeMetadataCacheOnDemand, &pDecoder); if (SUCCEEDED(hr)) { IWICBitmapFrameDecode *pFrame = NULL; - hr = pDecoder->lpVtbl->GetFrame(pDecoder, 0, - &pFrame); + hr = pDecoder->lpVtbl->GetFrame(pDecoder, 0, &pFrame); if (SUCCEEDED(hr)) { - bytes = wic_image_init_internal( - file, pFrame, format, cx_out, - cy_out, space); + bytes = wic_image_init_internal(file, pFrame, format, cx_out, cy_out, space); pFrame->lpVtbl->Release(pFrame); } else { - blog(LOG_WARNING, - "WIC: Failed to create IWICBitmapFrameDecode from file: %s", + blog(LOG_WARNING, "WIC: Failed to create IWICBitmapFrameDecode from file: %s", file); } pDecoder->lpVtbl->Release(pDecoder); } else { - blog(LOG_WARNING, - "WIC: Failed to create IWICBitmapDecoder from file: %s", - file); + blog(LOG_WARNING, "WIC: Failed to create IWICBitmapDecoder from file: %s", file); } pFactory->lpVtbl->Release(pFactory); } else { - blog(LOG_WARNING, - "WIC: Failed to create IWICImagingFactory"); + blog(LOG_WARNING, "WIC: Failed to create IWICImagingFactory"); } bfree(file_w); @@ -840,20 +751,15 @@ static void *wic_image_init(const struct ffmpeg_image *info, const char *file, } #endif -uint8_t *gs_create_texture_file_data2(const char *file, - enum gs_image_alpha_mode alpha_mode, - enum gs_color_format *format, - uint32_t *cx_out, uint32_t *cy_out) +uint8_t *gs_create_texture_file_data2(const char *file, enum gs_image_alpha_mode alpha_mode, + enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out) { enum gs_color_space unused; - return gs_create_texture_file_data3(file, alpha_mode, format, cx_out, - cy_out, &unused); + return gs_create_texture_file_data3(file, alpha_mode, format, cx_out, cy_out, &unused); } -uint8_t *gs_create_texture_file_data3(const char *file, - enum gs_image_alpha_mode alpha_mode, - enum gs_color_format *format, - uint32_t *cx_out, uint32_t *cy_out, +uint8_t *gs_create_texture_file_data3(const char *file, enum gs_image_alpha_mode alpha_mode, + enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out, enum gs_color_space *space) { struct ffmpeg_image image; @@ -873,8 +779,7 @@ uint8_t *gs_create_texture_file_data3(const char *file, #ifdef _WIN32 if (data == NULL) { - data = wic_image_init(&image, file, format, cx_out, cy_out, - space); + data = wic_image_init(&image, file, format, cx_out, cy_out, space); } #endif diff --git a/libobs/graphics/graphics-imports.c b/libobs/graphics/graphics-imports.c index 8e7bcc4d6..bc15674e0 100644 --- a/libobs/graphics/graphics-imports.c +++ b/libobs/graphics/graphics-imports.c @@ -37,8 +37,7 @@ exports->func = os_dlsym(module, #func); \ } while (false) -bool load_graphics_imports(struct gs_exports *exports, void *module, - const char *module_name) +bool load_graphics_imports(struct gs_exports *exports, void *module, const char *module_name) { bool success = true; diff --git a/libobs/graphics/graphics-internal.h b/libobs/graphics/graphics-internal.h index 87cdbeae0..041c5605a 100644 --- a/libobs/graphics/graphics-internal.h +++ b/libobs/graphics/graphics-internal.h @@ -26,156 +26,99 @@ struct gs_exports { const char *(*device_get_name)(void); int (*device_get_type)(void); - bool (*device_enum_adapters)(gs_device_t *device, - bool (*callback)(void *, const char *, - uint32_t), - void *); + bool (*device_enum_adapters)(gs_device_t *device, bool (*callback)(void *, const char *, uint32_t), void *); const char *(*device_preprocessor_name)(void); int (*device_create)(gs_device_t **device, uint32_t adapter); void (*device_destroy)(gs_device_t *device); void (*device_enter_context)(gs_device_t *device); void (*device_leave_context)(gs_device_t *device); void *(*device_get_device_obj)(gs_device_t *device); - gs_swapchain_t *(*device_swapchain_create)( - gs_device_t *device, const struct gs_init_data *data); + gs_swapchain_t *(*device_swapchain_create)(gs_device_t *device, const struct gs_init_data *data); void (*device_resize)(gs_device_t *device, uint32_t x, uint32_t y); enum gs_color_space (*device_get_color_space)(gs_device_t *device); void (*device_update_color_space)(gs_device_t *device); - void (*device_get_size)(const gs_device_t *device, uint32_t *x, - uint32_t *y); + void (*device_get_size)(const gs_device_t *device, uint32_t *x, uint32_t *y); uint32_t (*device_get_width)(const gs_device_t *device); uint32_t (*device_get_height)(const gs_device_t *device); - gs_texture_t *(*device_texture_create)( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t levels, - const uint8_t **data, uint32_t flags); - gs_texture_t *(*device_cubetexture_create)( - gs_device_t *device, uint32_t size, - enum gs_color_format color_format, uint32_t levels, - const uint8_t **data, uint32_t flags); - gs_texture_t *(*device_voltexture_create)( - gs_device_t *device, uint32_t width, uint32_t height, - uint32_t depth, enum gs_color_format color_format, - uint32_t levels, const uint8_t *const *data, uint32_t flags); - gs_zstencil_t *(*device_zstencil_create)( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_zstencil_format format); - gs_stagesurf_t *(*device_stagesurface_create)( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format); - gs_samplerstate_t *(*device_samplerstate_create)( - gs_device_t *device, const struct gs_sampler_info *info); - gs_shader_t *(*device_vertexshader_create)(gs_device_t *device, - const char *shader, - const char *file, + gs_texture_t *(*device_texture_create)(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t levels, const uint8_t **data, + uint32_t flags); + gs_texture_t *(*device_cubetexture_create)(gs_device_t *device, uint32_t size, + enum gs_color_format color_format, uint32_t levels, + const uint8_t **data, uint32_t flags); + gs_texture_t *(*device_voltexture_create)(gs_device_t *device, uint32_t width, uint32_t height, uint32_t depth, + enum gs_color_format color_format, uint32_t levels, + const uint8_t *const *data, uint32_t flags); + gs_zstencil_t *(*device_zstencil_create)(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_zstencil_format format); + gs_stagesurf_t *(*device_stagesurface_create)(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format); + gs_samplerstate_t *(*device_samplerstate_create)(gs_device_t *device, const struct gs_sampler_info *info); + gs_shader_t *(*device_vertexshader_create)(gs_device_t *device, const char *shader, const char *file, char **error_string); - gs_shader_t *(*device_pixelshader_create)(gs_device_t *device, - const char *shader, - const char *file, + gs_shader_t *(*device_pixelshader_create)(gs_device_t *device, const char *shader, const char *file, char **error_string); - gs_vertbuffer_t *(*device_vertexbuffer_create)(gs_device_t *device, - struct gs_vb_data *data, - uint32_t flags); - gs_indexbuffer_t *(*device_indexbuffer_create)(gs_device_t *device, - enum gs_index_type type, - void *indices, - size_t num, - uint32_t flags); + gs_vertbuffer_t *(*device_vertexbuffer_create)(gs_device_t *device, struct gs_vb_data *data, uint32_t flags); + gs_indexbuffer_t *(*device_indexbuffer_create)(gs_device_t *device, enum gs_index_type type, void *indices, + size_t num, uint32_t flags); gs_timer_t *(*device_timer_create)(gs_device_t *device); gs_timer_range_t *(*device_timer_range_create)(gs_device_t *device); - enum gs_texture_type (*device_get_texture_type)( - const gs_texture_t *texture); - void (*device_load_vertexbuffer)(gs_device_t *device, - gs_vertbuffer_t *vertbuffer); - void (*device_load_indexbuffer)(gs_device_t *device, - gs_indexbuffer_t *indexbuffer); - void (*device_load_texture)(gs_device_t *device, gs_texture_t *tex, - int unit); - void (*device_load_samplerstate)(gs_device_t *device, - gs_samplerstate_t *samplerstate, - int unit); - void (*device_load_vertexshader)(gs_device_t *device, - gs_shader_t *vertshader); - void (*device_load_pixelshader)(gs_device_t *device, - gs_shader_t *pixelshader); - void (*device_load_default_samplerstate)(gs_device_t *device, bool b_3d, - int unit); + enum gs_texture_type (*device_get_texture_type)(const gs_texture_t *texture); + void (*device_load_vertexbuffer)(gs_device_t *device, gs_vertbuffer_t *vertbuffer); + void (*device_load_indexbuffer)(gs_device_t *device, gs_indexbuffer_t *indexbuffer); + void (*device_load_texture)(gs_device_t *device, gs_texture_t *tex, int unit); + void (*device_load_samplerstate)(gs_device_t *device, gs_samplerstate_t *samplerstate, int unit); + void (*device_load_vertexshader)(gs_device_t *device, gs_shader_t *vertshader); + void (*device_load_pixelshader)(gs_device_t *device, gs_shader_t *pixelshader); + void (*device_load_default_samplerstate)(gs_device_t *device, bool b_3d, int unit); gs_shader_t *(*device_get_vertex_shader)(const gs_device_t *device); gs_shader_t *(*device_get_pixel_shader)(const gs_device_t *device); gs_texture_t *(*device_get_render_target)(const gs_device_t *device); gs_zstencil_t *(*device_get_zstencil_target)(const gs_device_t *device); - void (*device_set_render_target)(gs_device_t *device, gs_texture_t *tex, - gs_zstencil_t *zstencil); - void (*device_set_render_target_with_color_space)( - gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil, - enum gs_color_space space); - void (*device_set_cube_render_target)(gs_device_t *device, - gs_texture_t *cubetex, int side, + void (*device_set_render_target)(gs_device_t *device, gs_texture_t *tex, gs_zstencil_t *zstencil); + void (*device_set_render_target_with_color_space)(gs_device_t *device, gs_texture_t *tex, + gs_zstencil_t *zstencil, enum gs_color_space space); + void (*device_set_cube_render_target)(gs_device_t *device, gs_texture_t *cubetex, int side, gs_zstencil_t *zstencil); - void (*device_enable_framebuffer_srgb)(gs_device_t *device, - bool enable); + void (*device_enable_framebuffer_srgb)(gs_device_t *device, bool enable); bool (*device_framebuffer_srgb_enabled)(gs_device_t *device); - void (*device_copy_texture)(gs_device_t *device, gs_texture_t *dst, - gs_texture_t *src); - void (*device_copy_texture_region)(gs_device_t *device, - gs_texture_t *dst, uint32_t dst_x, - uint32_t dst_y, gs_texture_t *src, - uint32_t src_x, uint32_t src_y, - uint32_t src_w, uint32_t src_h); - void (*device_stage_texture)(gs_device_t *device, gs_stagesurf_t *dst, - gs_texture_t *src); + void (*device_copy_texture)(gs_device_t *device, gs_texture_t *dst, gs_texture_t *src); + void (*device_copy_texture_region)(gs_device_t *device, gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, + gs_texture_t *src, uint32_t src_x, uint32_t src_y, uint32_t src_w, + uint32_t src_h); + void (*device_stage_texture)(gs_device_t *device, gs_stagesurf_t *dst, gs_texture_t *src); void (*device_begin_frame)(gs_device_t *device); void (*device_begin_scene)(gs_device_t *device); - void (*device_draw)(gs_device_t *device, enum gs_draw_mode draw_mode, - uint32_t start_vert, uint32_t num_verts); + void (*device_draw)(gs_device_t *device, enum gs_draw_mode draw_mode, uint32_t start_vert, uint32_t num_verts); void (*device_end_scene)(gs_device_t *device); - void (*device_load_swapchain)(gs_device_t *device, - gs_swapchain_t *swaphchain); - void (*device_clear)(gs_device_t *device, uint32_t clear_flags, - const struct vec4 *color, float depth, + void (*device_load_swapchain)(gs_device_t *device, gs_swapchain_t *swaphchain); + void (*device_clear)(gs_device_t *device, uint32_t clear_flags, const struct vec4 *color, float depth, uint8_t stencil); bool (*device_is_present_ready)(gs_device_t *device); void (*device_present)(gs_device_t *device); void (*device_flush)(gs_device_t *device); - void (*device_set_cull_mode)(gs_device_t *device, - enum gs_cull_mode mode); + void (*device_set_cull_mode)(gs_device_t *device, enum gs_cull_mode mode); enum gs_cull_mode (*device_get_cull_mode)(const gs_device_t *device); void (*device_enable_blending)(gs_device_t *device, bool enable); void (*device_enable_depth_test)(gs_device_t *device, bool enable); void (*device_enable_stencil_test)(gs_device_t *device, bool enable); void (*device_enable_stencil_write)(gs_device_t *device, bool enable); - void (*device_enable_color)(gs_device_t *device, bool red, bool green, - bool blue, bool alpha); - void (*device_blend_function)(gs_device_t *device, - enum gs_blend_type src, - enum gs_blend_type dest); - void (*device_blend_function_separate)(gs_device_t *device, - enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, - enum gs_blend_type dest_a); + void (*device_enable_color)(gs_device_t *device, bool red, bool green, bool blue, bool alpha); + void (*device_blend_function)(gs_device_t *device, enum gs_blend_type src, enum gs_blend_type dest); + void (*device_blend_function_separate)(gs_device_t *device, enum gs_blend_type src_c, enum gs_blend_type dest_c, + enum gs_blend_type src_a, enum gs_blend_type dest_a); void (*device_blend_op)(gs_device_t *device, enum gs_blend_op_type op); - void (*device_depth_function)(gs_device_t *device, - enum gs_depth_test test); - void (*device_stencil_function)(gs_device_t *device, - enum gs_stencil_side side, - enum gs_depth_test test); - void (*device_stencil_op)(gs_device_t *device, - enum gs_stencil_side side, - enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, - enum gs_stencil_op_type zpass); - void (*device_set_viewport)(gs_device_t *device, int x, int y, - int width, int height); - void (*device_get_viewport)(const gs_device_t *device, - struct gs_rect *rect); - void (*device_set_scissor_rect)(gs_device_t *device, - const struct gs_rect *rect); - void (*device_ortho)(gs_device_t *device, float left, float right, - float top, float bottom, float znear, float zfar); - void (*device_frustum)(gs_device_t *device, float left, float right, - float top, float bottom, float znear, + void (*device_depth_function)(gs_device_t *device, enum gs_depth_test test); + void (*device_stencil_function)(gs_device_t *device, enum gs_stencil_side side, enum gs_depth_test test); + void (*device_stencil_op)(gs_device_t *device, enum gs_stencil_side side, enum gs_stencil_op_type fail, + enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass); + void (*device_set_viewport)(gs_device_t *device, int x, int y, int width, int height); + void (*device_get_viewport)(const gs_device_t *device, struct gs_rect *rect); + void (*device_set_scissor_rect)(gs_device_t *device, const struct gs_rect *rect); + void (*device_ortho)(gs_device_t *device, float left, float right, float top, float bottom, float znear, + float zfar); + void (*device_frustum)(gs_device_t *device, float left, float right, float top, float bottom, float znear, float zfar); void (*device_projection_push)(gs_device_t *device); void (*device_projection_pop)(gs_device_t *device); @@ -185,33 +128,27 @@ struct gs_exports { void (*gs_texture_destroy)(gs_texture_t *tex); uint32_t (*gs_texture_get_width)(const gs_texture_t *tex); uint32_t (*gs_texture_get_height)(const gs_texture_t *tex); - enum gs_color_format (*gs_texture_get_color_format)( - const gs_texture_t *tex); - bool (*gs_texture_map)(gs_texture_t *tex, uint8_t **ptr, - uint32_t *linesize); + enum gs_color_format (*gs_texture_get_color_format)(const gs_texture_t *tex); + bool (*gs_texture_map)(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize); void (*gs_texture_unmap)(gs_texture_t *tex); bool (*gs_texture_is_rect)(const gs_texture_t *tex); void *(*gs_texture_get_obj)(const gs_texture_t *tex); void (*gs_cubetexture_destroy)(gs_texture_t *cubetex); uint32_t (*gs_cubetexture_get_size)(const gs_texture_t *cubetex); - enum gs_color_format (*gs_cubetexture_get_color_format)( - const gs_texture_t *cubetex); + enum gs_color_format (*gs_cubetexture_get_color_format)(const gs_texture_t *cubetex); void (*gs_voltexture_destroy)(gs_texture_t *voltex); uint32_t (*gs_voltexture_get_width)(const gs_texture_t *voltex); uint32_t (*gs_voltexture_get_height)(const gs_texture_t *voltex); uint32_t (*gs_voltexture_get_depth)(const gs_texture_t *voltex); - enum gs_color_format (*gs_voltexture_get_color_format)( - const gs_texture_t *voltex); + enum gs_color_format (*gs_voltexture_get_color_format)(const gs_texture_t *voltex); void (*gs_stagesurface_destroy)(gs_stagesurf_t *stagesurf); uint32_t (*gs_stagesurface_get_width)(const gs_stagesurf_t *stagesurf); uint32_t (*gs_stagesurface_get_height)(const gs_stagesurf_t *stagesurf); - enum gs_color_format (*gs_stagesurface_get_color_format)( - const gs_stagesurf_t *stagesurf); - bool (*gs_stagesurface_map)(gs_stagesurf_t *stagesurf, uint8_t **data, - uint32_t *linesize); + enum gs_color_format (*gs_stagesurface_get_color_format)(const gs_stagesurf_t *stagesurf); + bool (*gs_stagesurface_map)(gs_stagesurf_t *stagesurf, uint8_t **data, uint32_t *linesize); void (*gs_stagesurface_unmap)(gs_stagesurf_t *stagesurf); void (*gs_zstencil_destroy)(gs_zstencil_t *zstencil); @@ -220,20 +157,15 @@ struct gs_exports { void (*gs_vertexbuffer_destroy)(gs_vertbuffer_t *vertbuffer); void (*gs_vertexbuffer_flush)(gs_vertbuffer_t *vertbuffer); - void (*gs_vertexbuffer_flush_direct)(gs_vertbuffer_t *vertbuffer, - const struct gs_vb_data *data); - struct gs_vb_data *(*gs_vertexbuffer_get_data)( - const gs_vertbuffer_t *vertbuffer); + void (*gs_vertexbuffer_flush_direct)(gs_vertbuffer_t *vertbuffer, const struct gs_vb_data *data); + struct gs_vb_data *(*gs_vertexbuffer_get_data)(const gs_vertbuffer_t *vertbuffer); void (*gs_indexbuffer_destroy)(gs_indexbuffer_t *indexbuffer); void (*gs_indexbuffer_flush)(gs_indexbuffer_t *indexbuffer); - void (*gs_indexbuffer_flush_direct)(gs_indexbuffer_t *indexbuffer, - const void *data); + void (*gs_indexbuffer_flush_direct)(gs_indexbuffer_t *indexbuffer, const void *data); void *(*gs_indexbuffer_get_data)(const gs_indexbuffer_t *indexbuffer); - size_t (*gs_indexbuffer_get_num_indices)( - const gs_indexbuffer_t *indexbuffer); - enum gs_index_type (*gs_indexbuffer_get_type)( - const gs_indexbuffer_t *indexbuffer); + size_t (*gs_indexbuffer_get_num_indices)(const gs_indexbuffer_t *indexbuffer); + enum gs_index_type (*gs_indexbuffer_get_type)(const gs_indexbuffer_t *indexbuffer); void (*gs_timer_destroy)(gs_timer_t *timer); void (*gs_timer_begin)(gs_timer_t *timer); @@ -242,135 +174,96 @@ struct gs_exports { void (*gs_timer_range_destroy)(gs_timer_range_t *range); bool (*gs_timer_range_begin)(gs_timer_range_t *range); bool (*gs_timer_range_end)(gs_timer_range_t *range); - bool (*gs_timer_range_get_data)(gs_timer_range_t *range, bool *disjoint, - uint64_t *frequency); + bool (*gs_timer_range_get_data)(gs_timer_range_t *range, bool *disjoint, uint64_t *frequency); void (*gs_shader_destroy)(gs_shader_t *shader); int (*gs_shader_get_num_params)(const gs_shader_t *shader); - gs_sparam_t *(*gs_shader_get_param_by_idx)(gs_shader_t *shader, - uint32_t param); - gs_sparam_t *(*gs_shader_get_param_by_name)(gs_shader_t *shader, - const char *name); + gs_sparam_t *(*gs_shader_get_param_by_idx)(gs_shader_t *shader, uint32_t param); + gs_sparam_t *(*gs_shader_get_param_by_name)(gs_shader_t *shader, const char *name); gs_sparam_t *(*gs_shader_get_viewproj_matrix)(const gs_shader_t *shader); gs_sparam_t *(*gs_shader_get_world_matrix)(const gs_shader_t *shader); - void (*gs_shader_get_param_info)(const gs_sparam_t *param, - struct gs_shader_param_info *info); + void (*gs_shader_get_param_info)(const gs_sparam_t *param, struct gs_shader_param_info *info); void (*gs_shader_set_bool)(gs_sparam_t *param, bool val); void (*gs_shader_set_float)(gs_sparam_t *param, float val); void (*gs_shader_set_int)(gs_sparam_t *param, int val); - void (*gs_shader_set_matrix3)(gs_sparam_t *param, - const struct matrix3 *val); - void (*gs_shader_set_matrix4)(gs_sparam_t *param, - const struct matrix4 *val); + void (*gs_shader_set_matrix3)(gs_sparam_t *param, const struct matrix3 *val); + void (*gs_shader_set_matrix4)(gs_sparam_t *param, const struct matrix4 *val); void (*gs_shader_set_vec2)(gs_sparam_t *param, const struct vec2 *val); void (*gs_shader_set_vec3)(gs_sparam_t *param, const struct vec3 *val); void (*gs_shader_set_vec4)(gs_sparam_t *param, const struct vec4 *val); void (*gs_shader_set_texture)(gs_sparam_t *param, gs_texture_t *val); - void (*gs_shader_set_val)(gs_sparam_t *param, const void *val, - size_t size); + void (*gs_shader_set_val)(gs_sparam_t *param, const void *val, size_t size); void (*gs_shader_set_default)(gs_sparam_t *param); - void (*gs_shader_set_next_sampler)(gs_sparam_t *param, - gs_samplerstate_t *sampler); + void (*gs_shader_set_next_sampler)(gs_sparam_t *param, gs_samplerstate_t *sampler); bool (*device_nv12_available)(gs_device_t *device); bool (*device_p010_available)(gs_device_t *device); - bool (*device_texture_create_nv12)(gs_device_t *device, - gs_texture_t **tex_y, - gs_texture_t **tex_uv, - uint32_t width, uint32_t height, - uint32_t flags); - bool (*device_texture_create_p010)(gs_device_t *device, - gs_texture_t **tex_y, - gs_texture_t **tex_uv, - uint32_t width, uint32_t height, - uint32_t flags); + bool (*device_texture_create_nv12)(gs_device_t *device, gs_texture_t **tex_y, gs_texture_t **tex_uv, + uint32_t width, uint32_t height, uint32_t flags); + bool (*device_texture_create_p010)(gs_device_t *device, gs_texture_t **tex_y, gs_texture_t **tex_uv, + uint32_t width, uint32_t height, uint32_t flags); bool (*device_is_monitor_hdr)(gs_device_t *device, void *monitor); - void (*device_debug_marker_begin)(gs_device_t *device, - const char *markername, - const float color[4]); + void (*device_debug_marker_begin)(gs_device_t *device, const char *markername, const float color[4]); void (*device_debug_marker_end)(gs_device_t *device); uint32_t (*gs_get_adapter_count)(void); #ifdef __APPLE__ /* OSX/Cocoa specific functions */ - gs_texture_t *(*device_texture_create_from_iosurface)(gs_device_t *dev, - void *iosurf); - gs_texture_t *(*device_texture_open_shared)(gs_device_t *dev, - uint32_t handle); - bool (*gs_texture_rebind_iosurface)(gs_texture_t *texture, - void *iosurf); + gs_texture_t *(*device_texture_create_from_iosurface)(gs_device_t *dev, void *iosurf); + gs_texture_t *(*device_texture_open_shared)(gs_device_t *dev, uint32_t handle); + bool (*gs_texture_rebind_iosurface)(gs_texture_t *texture, void *iosurf); bool (*device_shared_texture_available)(void); #elif _WIN32 bool (*device_gdi_texture_available)(void); bool (*device_shared_texture_available)(void); - bool (*device_get_duplicator_monitor_info)( - gs_device_t *device, int monitor_idx, - struct gs_monitor_info *monitor_info); - int (*device_duplicator_get_monitor_index)(gs_device_t *device, - void *monitor); + bool (*device_get_duplicator_monitor_info)(gs_device_t *device, int monitor_idx, + struct gs_monitor_info *monitor_info); + int (*device_duplicator_get_monitor_index)(gs_device_t *device, void *monitor); - gs_duplicator_t *(*device_duplicator_create)(gs_device_t *device, - int monitor_idx); + gs_duplicator_t *(*device_duplicator_create)(gs_device_t *device, int monitor_idx); void (*gs_duplicator_destroy)(gs_duplicator_t *duplicator); bool (*gs_duplicator_update_frame)(gs_duplicator_t *duplicator); gs_texture_t *(*gs_duplicator_get_texture)(gs_duplicator_t *duplicator); - enum gs_color_space (*gs_duplicator_get_color_space)( - gs_duplicator_t *duplicator); + enum gs_color_space (*gs_duplicator_get_color_space)(gs_duplicator_t *duplicator); float (*gs_duplicator_get_sdr_white_level)(gs_duplicator_t *duplicator); bool (*device_can_adapter_fast_clear)(gs_device_t *device); - gs_texture_t *(*device_texture_create_gdi)(gs_device_t *device, - uint32_t width, - uint32_t height); + gs_texture_t *(*device_texture_create_gdi)(gs_device_t *device, uint32_t width, uint32_t height); void *(*gs_texture_get_dc)(gs_texture_t *gdi_tex); void (*gs_texture_release_dc)(gs_texture_t *gdi_tex); - gs_texture_t *(*device_texture_open_shared)(gs_device_t *device, - uint32_t handle); - gs_texture_t *(*device_texture_open_nt_shared)(gs_device_t *device, - uint32_t handle); + gs_texture_t *(*device_texture_open_shared)(gs_device_t *device, uint32_t handle); + gs_texture_t *(*device_texture_open_nt_shared)(gs_device_t *device, uint32_t handle); uint32_t (*device_texture_get_shared_handle)(gs_texture_t *tex); - gs_texture_t *(*device_texture_wrap_obj)(gs_device_t *device, - void *obj); - int (*device_texture_acquire_sync)(gs_texture_t *tex, uint64_t key, - uint32_t ms); + gs_texture_t *(*device_texture_wrap_obj)(gs_device_t *device, void *obj); + int (*device_texture_acquire_sync)(gs_texture_t *tex, uint64_t key, uint32_t ms); int (*device_texture_release_sync)(gs_texture_t *tex, uint64_t key); - gs_stagesurf_t *(*device_stagesurface_create_nv12)(gs_device_t *device, - uint32_t width, - uint32_t height); - gs_stagesurf_t *(*device_stagesurface_create_p010)(gs_device_t *device, - uint32_t width, - uint32_t height); - void (*device_register_loss_callbacks)( - gs_device_t *device, const struct gs_device_loss *callbacks); - void (*device_unregister_loss_callbacks)(gs_device_t *device, - void *data); + gs_stagesurf_t *(*device_stagesurface_create_nv12)(gs_device_t *device, uint32_t width, uint32_t height); + gs_stagesurf_t *(*device_stagesurface_create_p010)(gs_device_t *device, uint32_t width, uint32_t height); + void (*device_register_loss_callbacks)(gs_device_t *device, const struct gs_device_loss *callbacks); + void (*device_unregister_loss_callbacks)(gs_device_t *device, void *data); #elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) - struct gs_texture *(*device_texture_create_from_dmabuf)( - gs_device_t *device, unsigned int width, unsigned int height, - uint32_t drm_format, enum gs_color_format color_format, - uint32_t n_planes, const int *fds, const uint32_t *strides, - const uint32_t *offsets, const uint64_t *modifiers); - bool (*device_query_dmabuf_capabilities)( - gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, size_t *n_formats); - bool (*device_query_dmabuf_modifiers_for_format)(gs_device_t *device, - uint32_t drm_format, - uint64_t **modifiers, + struct gs_texture *(*device_texture_create_from_dmabuf)(gs_device_t *device, unsigned int width, + unsigned int height, uint32_t drm_format, + enum gs_color_format color_format, uint32_t n_planes, + const int *fds, const uint32_t *strides, + const uint32_t *offsets, const uint64_t *modifiers); + bool (*device_query_dmabuf_capabilities)(gs_device_t *device, enum gs_dmabuf_flags *dmabuf_flags, + uint32_t **drm_formats, size_t *n_formats); + bool (*device_query_dmabuf_modifiers_for_format)(gs_device_t *device, uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers); - struct gs_texture *(*device_texture_create_from_pixmap)( - gs_device_t *device, uint32_t width, uint32_t height, - enum gs_color_format color_format, uint32_t target, - void *pixmap); + struct gs_texture *(*device_texture_create_from_pixmap)(gs_device_t *device, uint32_t width, uint32_t height, + enum gs_color_format color_format, uint32_t target, + void *pixmap); #endif }; diff --git a/libobs/graphics/graphics-magick.c b/libobs/graphics/graphics-magick.c index 3754c6c8a..e3b64c762 100644 --- a/libobs/graphics/graphics-magick.c +++ b/libobs/graphics/graphics-magick.c @@ -20,9 +20,7 @@ void gs_free_image_deps() MagickCoreTerminus(); } -uint8_t *gs_create_texture_file_data(const char *file, - enum gs_color_format *format, - uint32_t *cx_out, uint32_t *cy_out) +uint8_t *gs_create_texture_file_data(const char *file, enum gs_color_format *format, uint32_t *cx_out, uint32_t *cy_out) { uint8_t *data = NULL; ImageInfo *info; @@ -42,8 +40,7 @@ uint8_t *gs_create_texture_file_data(const char *file, size_t cy = image->magick_rows; data = bmalloc(cx * cy * 4); - ExportImagePixels(image, 0, 0, cx, cy, "BGRA", CharPixel, data, - exception); + ExportImagePixels(image, 0, 0, cx, cy, "BGRA", CharPixel, data, exception); if (exception->severity != UndefinedException) { blog(LOG_WARNING, "magickcore warning/error getting " diff --git a/libobs/graphics/graphics.c b/libobs/graphics/graphics.c index c064413f8..50a3d5654 100644 --- a/libobs/graphics/graphics.c +++ b/libobs/graphics/graphics.c @@ -37,8 +37,7 @@ static THREAD_LOCAL graphics_t *thread_graphics = NULL; -static inline bool gs_obj_valid(const void *obj, const char *f, - const char *name) +static inline bool gs_obj_valid(const void *obj, const char *f, const char *name) { if (!obj) { blog(LOG_DEBUG, "%s: Null '%s' parameter", f, name); @@ -51,8 +50,7 @@ static inline bool gs_obj_valid(const void *obj, const char *f, static inline bool gs_valid(const char *f) { if (!thread_graphics) { - blog(LOG_DEBUG, "%s: called while not in a graphics context", - f); + blog(LOG_DEBUG, "%s: called while not in a graphics context", f); return false; } @@ -63,18 +61,14 @@ static inline bool gs_valid(const char *f) #define gs_valid_p(func, param1) (gs_valid(func) && ptr_valid(param1, func)) -#define gs_valid_p2(func, param1, param2) \ - (gs_valid(func) && ptr_valid(param1, func) && ptr_valid(param2, func)) +#define gs_valid_p2(func, param1, param2) (gs_valid(func) && ptr_valid(param1, func) && ptr_valid(param2, func)) -#define gs_valid_p3(func, param1, param2, param3) \ - (gs_valid(func) && ptr_valid(param1, func) && \ - ptr_valid(param2, func) && ptr_valid(param3, func)) +#define gs_valid_p3(func, param1, param2, param3) \ + (gs_valid(func) && ptr_valid(param1, func) && ptr_valid(param2, func) && ptr_valid(param3, func)) #define IMMEDIATE_COUNT 512 -void gs_enum_adapters(bool (*callback)(void *param, const char *name, - uint32_t id), - void *param) +void gs_enum_adapters(bool (*callback)(void *param, const char *name, uint32_t id), void *param) { graphics_t *graphics = thread_graphics; @@ -82,8 +76,7 @@ void gs_enum_adapters(bool (*callback)(void *param, const char *name, return; if (graphics->exports.device_enum_adapters) { - if (graphics->exports.device_enum_adapters(graphics->device, - callback, param)) { + if (graphics->exports.device_enum_adapters(graphics->device, callback, param)) { return; } } @@ -97,8 +90,7 @@ void gs_enum_adapters(bool (*callback)(void *param, const char *name, extern void gs_init_image_deps(void); extern void gs_free_image_deps(void); -bool load_graphics_imports(struct gs_exports *exports, void *module, - const char *module_name); +bool load_graphics_imports(struct gs_exports *exports, void *module, const char *module_name); static bool graphics_init_immediate_vb(struct graphics_subsystem *graphics) { @@ -115,8 +107,7 @@ static bool graphics_init_immediate_vb(struct graphics_subsystem *graphics) vbd->tvarray[0].array = bmalloc(sizeof(struct vec2) * IMMEDIATE_COUNT); graphics->immediate_vertbuffer = - graphics->exports.device_vertexbuffer_create(graphics->device, - vbd, GS_DYNAMIC); + graphics->exports.device_vertexbuffer_create(graphics->device, vbd, GS_DYNAMIC); if (!graphics->immediate_vertbuffer) return false; @@ -138,8 +129,7 @@ static bool graphics_init_sprite_vb(struct graphics_subsystem *graphics) memset(vbd->points, 0, sizeof(struct vec3) * 4); memset(vbd->tvarray[0].array, 0, sizeof(struct vec2) * 4); - graphics->sprite_buffer = graphics->exports.device_vertexbuffer_create( - graphics->device, vbd, GS_DYNAMIC); + graphics->sprite_buffer = graphics->exports.device_vertexbuffer_create(graphics->device, vbd, GS_DYNAMIC); if (!graphics->sprite_buffer) return false; @@ -164,9 +154,8 @@ static bool graphics_init(struct graphics_subsystem *graphics) if (pthread_mutex_init(&graphics->effect_mutex, NULL) != 0) return false; - graphics->exports.device_blend_function_separate( - graphics->device, GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA, - GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); + graphics->exports.device_blend_function_separate(graphics->device, GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA, + GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); graphics->cur_blend_state.enabled = true; graphics->cur_blend_state.src_c = GS_BLEND_SRCALPHA; graphics->cur_blend_state.dest_c = GS_BLEND_INVSRCALPHA; @@ -174,8 +163,7 @@ static bool graphics_init(struct graphics_subsystem *graphics) graphics->cur_blend_state.dest_a = GS_BLEND_INVSRCALPHA; graphics->cur_blend_state.op = GS_BLEND_OP_ADD; - graphics->exports.device_blend_op(graphics->device, - graphics->cur_blend_state.op); + graphics->exports.device_blend_op(graphics->device, graphics->cur_blend_state.op); graphics->exports.device_leave_context(graphics->device); @@ -197,8 +185,7 @@ int gs_create(graphics_t **pgraphics, const char *module, uint32_t adapter) goto error; } - if (!load_graphics_imports(&graphics->exports, graphics->module, - module)) + if (!load_graphics_imports(&graphics->exports, graphics->module, module)) goto error; errcode = graphics->exports.device_create(&graphics->device, adapter); @@ -240,10 +227,8 @@ void gs_destroy(graphics_t *graphics) effect = next; } - graphics->exports.gs_vertexbuffer_destroy( - graphics->sprite_buffer); - graphics->exports.gs_vertexbuffer_destroy( - graphics->immediate_vertbuffer); + graphics->exports.gs_vertexbuffer_destroy(graphics->sprite_buffer); + graphics->exports.gs_vertexbuffer_destroy(graphics->immediate_vertbuffer); graphics->exports.device_destroy(graphics->device); thread_graphics = NULL; @@ -287,8 +272,7 @@ void gs_leave_context(void) if (!os_atomic_dec_long(&thread_graphics->ref)) { graphics_t *graphics = thread_graphics; - graphics->exports.device_leave_context( - graphics->device); + graphics->exports.device_leave_context(graphics->device); pthread_mutex_unlock(&graphics->mutex); thread_graphics = NULL; } @@ -305,22 +289,17 @@ void *gs_get_device_obj(void) if (!gs_valid("gs_get_device_obj")) return NULL; - return thread_graphics->exports.device_get_device_obj( - thread_graphics->device); + return thread_graphics->exports.device_get_device_obj(thread_graphics->device); } const char *gs_get_device_name(void) { - return gs_valid("gs_get_device_name") - ? thread_graphics->exports.device_get_name() - : NULL; + return gs_valid("gs_get_device_name") ? thread_graphics->exports.device_get_name() : NULL; } int gs_get_device_type(void) { - return gs_valid("gs_get_device_type") - ? thread_graphics->exports.device_get_type() - : -1; + return gs_valid("gs_get_device_type") ? thread_graphics->exports.device_get_type() : -1; } static inline struct matrix4 *top_matrix(graphics_t *graphics) @@ -529,10 +508,8 @@ void gs_render_start(bool b_new) if (b_new) { graphics->vbd = gs_vbdata_create(); } else { - graphics->vbd = gs_vertexbuffer_get_data( - graphics->immediate_vertbuffer); - memset(graphics->vbd->colors, 0xFF, - sizeof(uint32_t) * IMMEDIATE_COUNT); + graphics->vbd = gs_vertexbuffer_get_data(graphics->immediate_vertbuffer); + memset(graphics->vbd->colors, 0xFF, sizeof(uint32_t) * IMMEDIATE_COUNT); graphics->verts.array = graphics->vbd->points; graphics->norms.array = graphics->vbd->normals; @@ -573,22 +550,19 @@ void gs_render_stop(enum gs_draw_mode mode) return; } - if (graphics->norms.num && - (graphics->norms.num != graphics->verts.num)) { + if (graphics->norms.num && (graphics->norms.num != graphics->verts.num)) { blog(LOG_ERROR, "gs_render_stop: normal count does " "not match vertex count"); num = min_size(num, graphics->norms.num); } - if (graphics->colors.num && - (graphics->colors.num != graphics->verts.num)) { + if (graphics->colors.num && (graphics->colors.num != graphics->verts.num)) { blog(LOG_ERROR, "gs_render_stop: color count does " "not match vertex count"); num = min_size(num, graphics->colors.num); } - if (graphics->texverts[0].num && - (graphics->texverts[0].num != graphics->verts.num)) { + if (graphics->texverts[0].num && (graphics->texverts[0].num != graphics->verts.num)) { blog(LOG_ERROR, "gs_render_stop: texture vertex count does " "not match vertex count"); num = min_size(num, graphics->texverts[0].num); @@ -641,13 +615,11 @@ gs_vertbuffer_t *gs_render_save(void) graphics->vbd->num_tex = num_tex; if (graphics->vbd->num_tex) { - graphics->vbd->tvarray = - bmalloc(sizeof(struct gs_tvertarray) * num_tex); + graphics->vbd->tvarray = bmalloc(sizeof(struct gs_tvertarray) * num_tex); for (i = 0; i < num_tex; i++) { graphics->vbd->tvarray[i].width = 2; - graphics->vbd->tvarray[i].array = - graphics->texverts[i].array; + graphics->vbd->tvarray[i].array = graphics->texverts[i].array; } } @@ -689,8 +661,7 @@ void gs_normal3f(float x, float y, float z) gs_normal3v(&v3); } -static inline bool validvertsize(graphics_t *graphics, size_t num, - const char *name) +static inline bool validvertsize(graphics_t *graphics, size_t num, const char *name) { if (graphics->using_immediate && num == IMMEDIATE_COUNT) { blog(LOG_ERROR, @@ -773,8 +744,7 @@ void gs_texcoord2v(const struct vec2 *v, int unit) if (!gs_valid("gs_texcoord2v")) return; - if (!validvertsize(graphics, graphics->texverts[unit].num, - "gs_texcoord")) + if (!validvertsize(graphics, graphics->texverts[unit].num, "gs_texcoord")) return; da_push_back(graphics->texverts[unit], v); @@ -831,8 +801,7 @@ gs_effect_t *gs_effect_create_from_file(const char *file, char **error_string) return effect; } -gs_effect_t *gs_effect_create(const char *effect_string, const char *filename, - char **error_string) +gs_effect_t *gs_effect_create(const char *effect_string, const char *filename, char **error_string) { if (!gs_valid_p("gs_effect_create", effect_string)) return NULL; @@ -848,8 +817,7 @@ gs_effect_t *gs_effect_create(const char *effect_string, const char *filename, success = ep_parse(&parser, effect, effect_string, filename); if (!success) { if (error_string) - *error_string = - error_data_buildstring(&parser.cfp.error_list); + *error_string = error_data_buildstring(&parser.cfp.error_list); gs_effect_destroy(effect); effect = NULL; } @@ -870,8 +838,7 @@ gs_effect_t *gs_effect_create(const char *effect_string, const char *filename, return effect; } -gs_shader_t *gs_vertexshader_create_from_file(const char *file, - char **error_string) +gs_shader_t *gs_vertexshader_create_from_file(const char *file, char **error_string) { if (!gs_valid_p("gs_vertexshader_create_from_file", file)) return NULL; @@ -891,8 +858,7 @@ gs_shader_t *gs_vertexshader_create_from_file(const char *file, return shader; } -gs_shader_t *gs_pixelshader_create_from_file(const char *file, - char **error_string) +gs_shader_t *gs_pixelshader_create_from_file(const char *file, char **error_string) { char *file_string; gs_shader_t *shader = NULL; @@ -921,16 +887,14 @@ gs_texture_t *gs_texture_create_from_file(const char *file) gs_texture_t *tex = NULL; if (data) { - tex = gs_texture_create(cx, cy, format, 1, - (const uint8_t **)&data, 0); + tex = gs_texture_create(cx, cy, format, 1, (const uint8_t **)&data, 0); bfree(data); } return tex; } -static inline void assign_sprite_rect(float *start, float *end, float size, - bool flip) +static inline void assign_sprite_rect(float *start, float *end, float size, bool flip) { if (!flip) { *start = 0.0f; @@ -952,8 +916,8 @@ static inline void assign_sprite_uv(float *start, float *end, bool flip) } } -static void build_sprite(struct gs_vb_data *data, float fcx, float fcy, - float start_u, float end_u, float start_v, float end_v) +static void build_sprite(struct gs_vb_data *data, float fcx, float fcy, float start_u, float end_u, float start_v, + float end_v) { struct vec2 *tvarray = data->tvarray[0].array; @@ -967,8 +931,7 @@ static void build_sprite(struct gs_vb_data *data, float fcx, float fcy, vec2_set(tvarray + 3, end_u, end_v); } -static inline void build_sprite_norm(struct gs_vb_data *data, float fcx, - float fcy, uint32_t flip) +static inline void build_sprite_norm(struct gs_vb_data *data, float fcx, float fcy, uint32_t flip) { float start_u, end_u; float start_v, end_v; @@ -978,10 +941,8 @@ static inline void build_sprite_norm(struct gs_vb_data *data, float fcx, build_sprite(data, fcx, fcy, start_u, end_u, start_v, end_v); } -static inline void build_subsprite_norm(struct gs_vb_data *data, float fsub_x, - float fsub_y, float fsub_cx, - float fsub_cy, float fcx, float fcy, - uint32_t flip) +static inline void build_subsprite_norm(struct gs_vb_data *data, float fsub_x, float fsub_y, float fsub_cx, + float fsub_cy, float fcx, float fcy, uint32_t flip) { float start_u, end_u; float start_v, end_v; @@ -1005,8 +966,7 @@ static inline void build_subsprite_norm(struct gs_vb_data *data, float fsub_x, build_sprite(data, fsub_cx, fsub_cy, start_u, end_u, start_v, end_v); } -static inline void build_sprite_rect(struct gs_vb_data *data, gs_texture_t *tex, - float fcx, float fcy, uint32_t flip) +static inline void build_sprite_rect(struct gs_vb_data *data, gs_texture_t *tex, float fcx, float fcy, uint32_t flip) { float start_u, end_u; float start_v, end_v; @@ -1018,8 +978,7 @@ static inline void build_sprite_rect(struct gs_vb_data *data, gs_texture_t *tex, build_sprite(data, fcx, fcy, start_u, end_u, start_v, end_v); } -void gs_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, - uint32_t height) +void gs_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, uint32_t height) { graphics_t *graphics = thread_graphics; float fcx, fcy; @@ -1054,8 +1013,8 @@ void gs_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, gs_draw(GS_TRISTRIP, 0, 0); } -void gs_draw_sprite_subregion(gs_texture_t *tex, uint32_t flip, uint32_t sub_x, - uint32_t sub_y, uint32_t sub_cx, uint32_t sub_cy) +void gs_draw_sprite_subregion(gs_texture_t *tex, uint32_t flip, uint32_t sub_x, uint32_t sub_y, uint32_t sub_cx, + uint32_t sub_cy) { graphics_t *graphics = thread_graphics; float fcx, fcy; @@ -1072,8 +1031,7 @@ void gs_draw_sprite_subregion(gs_texture_t *tex, uint32_t flip, uint32_t sub_x, fcy = (float)gs_texture_get_height(tex); data = gs_vertexbuffer_get_data(graphics->sprite_buffer); - build_subsprite_norm(data, (float)sub_x, (float)sub_y, (float)sub_cx, - (float)sub_cy, fcx, fcy, flip); + build_subsprite_norm(data, (float)sub_x, (float)sub_y, (float)sub_cx, (float)sub_cy, fcx, fcy, flip); gs_vertexbuffer_flush(graphics->sprite_buffer); gs_load_vertexbuffer(graphics->sprite_buffer); @@ -1082,9 +1040,8 @@ void gs_draw_sprite_subregion(gs_texture_t *tex, uint32_t flip, uint32_t sub_x, gs_draw(GS_TRISTRIP, 0, 0); } -void gs_draw_cube_backdrop(gs_texture_t *cubetex, const struct quat *rot, - float left, float right, float top, float bottom, - float znear) +void gs_draw_cube_backdrop(gs_texture_t *cubetex, const struct quat *rot, float left, float right, float top, + float bottom, float znear) { /* TODO */ UNUSED_PARAMETER(cubetex); @@ -1131,8 +1088,7 @@ void gs_viewport_push(void) if (!gs_valid("gs_viewport_push")) return; - struct gs_rect *rect = - da_push_back_new(thread_graphics->viewport_stack); + struct gs_rect *rect = da_push_back_new(thread_graphics->viewport_stack); gs_get_viewport(rect); } @@ -1150,8 +1106,7 @@ void gs_viewport_pop(void) da_pop_back(thread_graphics->viewport_stack); } -void gs_texture_set_image(gs_texture_t *tex, const uint8_t *data, - uint32_t linesize, bool flip) +void gs_texture_set_image(gs_texture_t *tex, const uint8_t *data, uint32_t linesize, bool flip) { uint8_t *ptr; uint32_t linesize_out; @@ -1192,8 +1147,7 @@ void gs_texture_set_image(gs_texture_t *tex, const uint8_t *data, gs_texture_unmap(tex); } -void gs_cubetexture_set_image(gs_texture_t *cubetex, uint32_t side, - const void *data, uint32_t linesize, bool invert) +void gs_cubetexture_set_image(gs_texture_t *cubetex, uint32_t side, const void *data, uint32_t linesize, bool invert) { /* TODO */ UNUSED_PARAMETER(cubetex); @@ -1217,8 +1171,7 @@ void gs_perspective(float angle, float aspect, float near, float far) xmin = ymin * aspect; xmax = ymax * aspect; - graphics->exports.device_frustum(graphics->device, xmin, xmax, ymin, - ymax, near, far); + graphics->exports.device_frustum(graphics->device, xmin, xmax, ymin, ymax, near, far); } void gs_blend_state_push(void) @@ -1244,8 +1197,7 @@ void gs_blend_state_pop(void) return; gs_enable_blending(state->enabled); - gs_blend_function_separate(state->src_c, state->dest_c, state->src_a, - state->dest_a); + gs_blend_function_separate(state->src_c, state->dest_c, state->src_a, state->dest_a); gs_blend_op(state->op); da_pop_back(graphics->blend_state_stack); @@ -1265,9 +1217,7 @@ void gs_reset_blend_state(void) graphics->cur_blend_state.dest_c != GS_BLEND_INVSRCALPHA || graphics->cur_blend_state.src_a != GS_BLEND_ONE || graphics->cur_blend_state.dest_a != GS_BLEND_INVSRCALPHA) { - gs_blend_function_separate(GS_BLEND_SRCALPHA, - GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, - GS_BLEND_INVSRCALPHA); + gs_blend_function_separate(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); gs_blend_op(GS_BLEND_OP_ADD); } } @@ -1295,8 +1245,7 @@ gs_swapchain_t *gs_swapchain_create(const struct gs_init_data *data) if (new_data.num_backbuffers == 0) new_data.num_backbuffers = 1; - return graphics->exports.device_swapchain_create(graphics->device, - &new_data); + return graphics->exports.device_swapchain_create(graphics->device, &new_data); } void gs_resize(uint32_t x, uint32_t y) @@ -1354,10 +1303,8 @@ static inline bool is_pow2(uint32_t size) return size >= 2 && (size & (size - 1)) == 0; } -gs_texture_t *gs_texture_create(uint32_t width, uint32_t height, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, - uint32_t flags) +gs_texture_t *gs_texture_create(uint32_t width, uint32_t height, enum gs_color_format color_format, uint32_t levels, + const uint8_t **data, uint32_t flags) { graphics_t *graphics = thread_graphics; bool pow2tex = is_pow2(width) && is_pow2(height); @@ -1383,61 +1330,51 @@ gs_texture_t *gs_texture_create(uint32_t width, uint32_t height, levels = 1; } - return graphics->exports.device_texture_create(graphics->device, width, - height, color_format, - levels, data, flags); + return graphics->exports.device_texture_create(graphics->device, width, height, color_format, levels, data, + flags); } #if defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) -gs_texture_t *gs_texture_create_from_dmabuf( - unsigned int width, unsigned int height, uint32_t drm_format, - enum gs_color_format color_format, uint32_t n_planes, const int *fds, - const uint32_t *strides, const uint32_t *offsets, - const uint64_t *modifiers) +gs_texture_t *gs_texture_create_from_dmabuf(unsigned int width, unsigned int height, uint32_t drm_format, + enum gs_color_format color_format, uint32_t n_planes, const int *fds, + const uint32_t *strides, const uint32_t *offsets, const uint64_t *modifiers) { graphics_t *graphics = thread_graphics; return graphics->exports.device_texture_create_from_dmabuf( - graphics->device, width, height, drm_format, color_format, - n_planes, fds, strides, offsets, modifiers); + graphics->device, width, height, drm_format, color_format, n_planes, fds, strides, offsets, modifiers); } -bool gs_query_dmabuf_capabilities(enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, size_t *n_formats) +bool gs_query_dmabuf_capabilities(enum gs_dmabuf_flags *dmabuf_flags, uint32_t **drm_formats, size_t *n_formats) { graphics_t *graphics = thread_graphics; - return graphics->exports.device_query_dmabuf_capabilities( - graphics->device, dmabuf_flags, drm_formats, n_formats); + return graphics->exports.device_query_dmabuf_capabilities(graphics->device, dmabuf_flags, drm_formats, + n_formats); } -bool gs_query_dmabuf_modifiers_for_format(uint32_t drm_format, - uint64_t **modifiers, - size_t *n_modifiers) +bool gs_query_dmabuf_modifiers_for_format(uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers) { graphics_t *graphics = thread_graphics; - return graphics->exports.device_query_dmabuf_modifiers_for_format( - graphics->device, drm_format, modifiers, n_modifiers); + return graphics->exports.device_query_dmabuf_modifiers_for_format(graphics->device, drm_format, modifiers, + n_modifiers); } -gs_texture_t *gs_texture_create_from_pixmap(uint32_t width, uint32_t height, - enum gs_color_format color_format, +gs_texture_t *gs_texture_create_from_pixmap(uint32_t width, uint32_t height, enum gs_color_format color_format, uint32_t target, void *pixmap) { graphics_t *graphics = thread_graphics; - return graphics->exports.device_texture_create_from_pixmap( - graphics->device, width, height, color_format, target, pixmap); + return graphics->exports.device_texture_create_from_pixmap(graphics->device, width, height, color_format, + target, pixmap); } #endif -gs_texture_t *gs_cubetexture_create(uint32_t size, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, - uint32_t flags) +gs_texture_t *gs_cubetexture_create(uint32_t size, enum gs_color_format color_format, uint32_t levels, + const uint8_t **data, uint32_t flags) { graphics_t *graphics = thread_graphics; bool pow2tex = is_pow2(size); @@ -1464,49 +1401,39 @@ gs_texture_t *gs_cubetexture_create(uint32_t size, data = NULL; } - return graphics->exports.device_cubetexture_create( - graphics->device, size, color_format, levels, data, flags); + return graphics->exports.device_cubetexture_create(graphics->device, size, color_format, levels, data, flags); } -gs_texture_t *gs_voltexture_create(uint32_t width, uint32_t height, - uint32_t depth, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, - uint32_t flags) +gs_texture_t *gs_voltexture_create(uint32_t width, uint32_t height, uint32_t depth, enum gs_color_format color_format, + uint32_t levels, const uint8_t **data, uint32_t flags) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_voltexture_create")) return NULL; - return graphics->exports.device_voltexture_create(graphics->device, - width, height, depth, - color_format, levels, + return graphics->exports.device_voltexture_create(graphics->device, width, height, depth, color_format, levels, data, flags); } -gs_zstencil_t *gs_zstencil_create(uint32_t width, uint32_t height, - enum gs_zstencil_format format) +gs_zstencil_t *gs_zstencil_create(uint32_t width, uint32_t height, enum gs_zstencil_format format) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_zstencil_create")) return NULL; - return graphics->exports.device_zstencil_create(graphics->device, width, - height, format); + return graphics->exports.device_zstencil_create(graphics->device, width, height, format); } -gs_stagesurf_t *gs_stagesurface_create(uint32_t width, uint32_t height, - enum gs_color_format color_format) +gs_stagesurf_t *gs_stagesurface_create(uint32_t width, uint32_t height, enum gs_color_format color_format) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_stagesurface_create")) return NULL; - return graphics->exports.device_stagesurface_create( - graphics->device, width, height, color_format); + return graphics->exports.device_stagesurface_create(graphics->device, width, height, color_format); } gs_samplerstate_t *gs_samplerstate_create(const struct gs_sampler_info *info) @@ -1516,32 +1443,27 @@ gs_samplerstate_t *gs_samplerstate_create(const struct gs_sampler_info *info) if (!gs_valid_p("gs_samplerstate_create", info)) return NULL; - return graphics->exports.device_samplerstate_create(graphics->device, - info); + return graphics->exports.device_samplerstate_create(graphics->device, info); } -gs_shader_t *gs_vertexshader_create(const char *shader, const char *file, - char **error_string) +gs_shader_t *gs_vertexshader_create(const char *shader, const char *file, char **error_string) { graphics_t *graphics = thread_graphics; if (!gs_valid_p("gs_vertexshader_create", shader)) return NULL; - return graphics->exports.device_vertexshader_create( - graphics->device, shader, file, error_string); + return graphics->exports.device_vertexshader_create(graphics->device, shader, file, error_string); } -gs_shader_t *gs_pixelshader_create(const char *shader, const char *file, - char **error_string) +gs_shader_t *gs_pixelshader_create(const char *shader, const char *file, char **error_string) { graphics_t *graphics = thread_graphics; if (!gs_valid_p("gs_pixelshader_create", shader)) return NULL; - return graphics->exports.device_pixelshader_create( - graphics->device, shader, file, error_string); + return graphics->exports.device_pixelshader_create(graphics->device, shader, file, error_string); } gs_vertbuffer_t *gs_vertexbuffer_create(struct gs_vb_data *data, uint32_t flags) @@ -1556,11 +1478,10 @@ gs_vertbuffer_t *gs_vertexbuffer_create(struct gs_vb_data *data, uint32_t flags) new_data->num = data->num; -#define DUP_VAL(val) \ - do { \ - if (data->val) \ - new_data->val = bmemdup( \ - data->val, sizeof(*data->val) * data->num); \ +#define DUP_VAL(val) \ + do { \ + if (data->val) \ + new_data->val = bmemdup(data->val, sizeof(*data->val) * data->num); \ } while (false) DUP_VAL(points); @@ -1571,30 +1492,25 @@ gs_vertbuffer_t *gs_vertexbuffer_create(struct gs_vb_data *data, uint32_t flags) if (data->tvarray && data->num_tex) { new_data->num_tex = data->num_tex; - new_data->tvarray = bzalloc( - sizeof(struct gs_tvertarray) * data->num_tex); + new_data->tvarray = bzalloc(sizeof(struct gs_tvertarray) * data->num_tex); for (size_t i = 0; i < data->num_tex; i++) { struct gs_tvertarray *tv = &data->tvarray[i]; - struct gs_tvertarray *new_tv = - &new_data->tvarray[i]; + struct gs_tvertarray *new_tv = &new_data->tvarray[i]; size_t size = tv->width * sizeof(float); new_tv->width = tv->width; - new_tv->array = - bmemdup(tv->array, size * data->num); + new_tv->array = bmemdup(tv->array, size * data->num); } } data = new_data; } - return graphics->exports.device_vertexbuffer_create(graphics->device, - data, flags); + return graphics->exports.device_vertexbuffer_create(graphics->device, data, flags); } -gs_indexbuffer_t *gs_indexbuffer_create(enum gs_index_type type, void *indices, - size_t num, uint32_t flags) +gs_indexbuffer_t *gs_indexbuffer_create(enum gs_index_type type, void *indices, size_t num, uint32_t flags) { graphics_t *graphics = thread_graphics; @@ -1606,8 +1522,7 @@ gs_indexbuffer_t *gs_indexbuffer_create(enum gs_index_type type, void *indices, indices = bmemdup(indices, size * num); } - return graphics->exports.device_indexbuffer_create( - graphics->device, type, indices, num, flags); + return graphics->exports.device_indexbuffer_create(graphics->device, type, indices, num, flags); } gs_timer_t *gs_timer_create() @@ -1647,8 +1562,7 @@ void gs_load_vertexbuffer(gs_vertbuffer_t *vertbuffer) if (!gs_valid("gs_load_vertexbuffer")) return; - graphics->exports.device_load_vertexbuffer(graphics->device, - vertbuffer); + graphics->exports.device_load_vertexbuffer(graphics->device, vertbuffer); } void gs_load_indexbuffer(gs_indexbuffer_t *indexbuffer) @@ -1658,8 +1572,7 @@ void gs_load_indexbuffer(gs_indexbuffer_t *indexbuffer) if (!gs_valid("gs_load_indexbuffer")) return; - graphics->exports.device_load_indexbuffer(graphics->device, - indexbuffer); + graphics->exports.device_load_indexbuffer(graphics->device, indexbuffer); } void gs_load_texture(gs_texture_t *tex, int unit) @@ -1679,8 +1592,7 @@ void gs_load_samplerstate(gs_samplerstate_t *samplerstate, int unit) if (!gs_valid("gs_load_samplerstate")) return; - graphics->exports.device_load_samplerstate(graphics->device, - samplerstate, unit); + graphics->exports.device_load_samplerstate(graphics->device, samplerstate, unit); } void gs_load_vertexshader(gs_shader_t *vertshader) @@ -1690,8 +1602,7 @@ void gs_load_vertexshader(gs_shader_t *vertshader) if (!gs_valid("gs_load_vertexshader")) return; - graphics->exports.device_load_vertexshader(graphics->device, - vertshader); + graphics->exports.device_load_vertexshader(graphics->device, vertshader); } void gs_load_pixelshader(gs_shader_t *pixelshader) @@ -1701,8 +1612,7 @@ void gs_load_pixelshader(gs_shader_t *pixelshader) if (!gs_valid("gs_load_pixelshader")) return; - graphics->exports.device_load_pixelshader(graphics->device, - pixelshader); + graphics->exports.device_load_pixelshader(graphics->device, pixelshader); } void gs_load_default_samplerstate(bool b_3d, int unit) @@ -1712,8 +1622,7 @@ void gs_load_default_samplerstate(bool b_3d, int unit) if (!gs_valid("gs_load_default_samplerstate")) return; - graphics->exports.device_load_default_samplerstate(graphics->device, - b_3d, unit); + graphics->exports.device_load_default_samplerstate(graphics->device, b_3d, unit); } gs_shader_t *gs_get_vertex_shader(void) @@ -1773,33 +1682,27 @@ void gs_set_render_target(gs_texture_t *tex, gs_zstencil_t *zstencil) if (!gs_valid("gs_set_render_target")) return; - graphics->exports.device_set_render_target(graphics->device, tex, - zstencil); + graphics->exports.device_set_render_target(graphics->device, tex, zstencil); } -void gs_set_render_target_with_color_space(gs_texture_t *tex, - gs_zstencil_t *zstencil, - enum gs_color_space space) +void gs_set_render_target_with_color_space(gs_texture_t *tex, gs_zstencil_t *zstencil, enum gs_color_space space) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_set_render_target_with_color_space")) return; - graphics->exports.device_set_render_target_with_color_space( - graphics->device, tex, zstencil, space); + graphics->exports.device_set_render_target_with_color_space(graphics->device, tex, zstencil, space); } -void gs_set_cube_render_target(gs_texture_t *cubetex, int side, - gs_zstencil_t *zstencil) +void gs_set_cube_render_target(gs_texture_t *cubetex, int side, gs_zstencil_t *zstencil) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_set_cube_render_target")) return; - graphics->exports.device_set_cube_render_target( - graphics->device, cubetex, side, zstencil); + graphics->exports.device_set_cube_render_target(graphics->device, cubetex, side, zstencil); } void gs_enable_framebuffer_srgb(bool enable) @@ -1809,8 +1712,7 @@ void gs_enable_framebuffer_srgb(bool enable) if (!gs_valid("gs_enable_framebuffer_srgb")) return; - graphics->exports.device_enable_framebuffer_srgb(graphics->device, - enable); + graphics->exports.device_enable_framebuffer_srgb(graphics->device, enable); } bool gs_framebuffer_srgb_enabled(void) @@ -1820,8 +1722,7 @@ bool gs_framebuffer_srgb_enabled(void) if (!gs_valid("gs_framebuffer_srgb_enabled")) return false; - return graphics->exports.device_framebuffer_srgb_enabled( - graphics->device); + return graphics->exports.device_framebuffer_srgb_enabled(graphics->device); } bool gs_get_linear_srgb(void) @@ -1856,18 +1757,16 @@ void gs_copy_texture(gs_texture_t *dst, gs_texture_t *src) graphics->exports.device_copy_texture(graphics->device, dst, src); } -void gs_copy_texture_region(gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, - gs_texture_t *src, uint32_t src_x, uint32_t src_y, - uint32_t src_w, uint32_t src_h) +void gs_copy_texture_region(gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, gs_texture_t *src, uint32_t src_x, + uint32_t src_y, uint32_t src_w, uint32_t src_h) { graphics_t *graphics = thread_graphics; if (!gs_valid_p("gs_copy_texture_region", dst)) return; - graphics->exports.device_copy_texture_region(graphics->device, dst, - dst_x, dst_y, src, src_x, - src_y, src_w, src_h); + graphics->exports.device_copy_texture_region(graphics->device, dst, dst_x, dst_y, src, src_x, src_y, src_w, + src_h); } void gs_stage_texture(gs_stagesurf_t *dst, gs_texture_t *src) @@ -1900,16 +1799,14 @@ void gs_begin_scene(void) graphics->exports.device_begin_scene(graphics->device); } -void gs_draw(enum gs_draw_mode draw_mode, uint32_t start_vert, - uint32_t num_verts) +void gs_draw(enum gs_draw_mode draw_mode, uint32_t start_vert, uint32_t num_verts) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_draw")) return; - graphics->exports.device_draw(graphics->device, draw_mode, start_vert, - num_verts); + graphics->exports.device_draw(graphics->device, draw_mode, start_vert, num_verts); } void gs_end_scene(void) @@ -1932,16 +1829,14 @@ void gs_load_swapchain(gs_swapchain_t *swapchain) graphics->exports.device_load_swapchain(graphics->device, swapchain); } -void gs_clear(uint32_t clear_flags, const struct vec4 *color, float depth, - uint8_t stencil) +void gs_clear(uint32_t clear_flags, const struct vec4 *color, float depth, uint8_t stencil) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_clear")) return; - graphics->exports.device_clear(graphics->device, clear_flags, color, - depth, stencil); + graphics->exports.device_clear(graphics->device, clear_flags, color, depth, stencil); } bool gs_is_present_ready(void) @@ -2042,8 +1937,7 @@ void gs_enable_color(bool red, bool green, bool blue, bool alpha) if (!gs_valid("gs_enable_color")) return; - graphics->exports.device_enable_color(graphics->device, red, green, - blue, alpha); + graphics->exports.device_enable_color(graphics->device, red, green, blue, alpha); } void gs_blend_function(enum gs_blend_type src, enum gs_blend_type dest) @@ -2060,9 +1954,7 @@ void gs_blend_function(enum gs_blend_type src, enum gs_blend_type dest) graphics->exports.device_blend_function(graphics->device, src, dest); } -void gs_blend_function_separate(enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, +void gs_blend_function_separate(enum gs_blend_type src_c, enum gs_blend_type dest_c, enum gs_blend_type src_a, enum gs_blend_type dest_a) { graphics_t *graphics = thread_graphics; @@ -2074,8 +1966,7 @@ void gs_blend_function_separate(enum gs_blend_type src_c, graphics->cur_blend_state.dest_c = dest_c; graphics->cur_blend_state.src_a = src_a; graphics->cur_blend_state.dest_a = dest_a; - graphics->exports.device_blend_function_separate( - graphics->device, src_c, dest_c, src_a, dest_a); + graphics->exports.device_blend_function_separate(graphics->device, src_c, dest_c, src_a, dest_a); } void gs_blend_op(enum gs_blend_op_type op) @@ -2086,8 +1977,7 @@ void gs_blend_op(enum gs_blend_op_type op) return; graphics->cur_blend_state.op = op; - graphics->exports.device_blend_op(graphics->device, - graphics->cur_blend_state.op); + graphics->exports.device_blend_op(graphics->device, graphics->cur_blend_state.op); } void gs_depth_function(enum gs_depth_test test) @@ -2110,16 +2000,15 @@ void gs_stencil_function(enum gs_stencil_side side, enum gs_depth_test test) graphics->exports.device_stencil_function(graphics->device, side, test); } -void gs_stencil_op(enum gs_stencil_side side, enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass) +void gs_stencil_op(enum gs_stencil_side side, enum gs_stencil_op_type fail, enum gs_stencil_op_type zfail, + enum gs_stencil_op_type zpass) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_stencil_op")) return; - graphics->exports.device_stencil_op(graphics->device, side, fail, zfail, - zpass); + graphics->exports.device_stencil_op(graphics->device, side, fail, zfail, zpass); } void gs_set_viewport(int x, int y, int width, int height) @@ -2129,8 +2018,7 @@ void gs_set_viewport(int x, int y, int width, int height) if (!gs_valid("gs_set_viewport")) return; - graphics->exports.device_set_viewport(graphics->device, x, y, width, - height); + graphics->exports.device_set_viewport(graphics->device, x, y, width, height); } void gs_get_viewport(struct gs_rect *rect) @@ -2153,28 +2041,24 @@ void gs_set_scissor_rect(const struct gs_rect *rect) graphics->exports.device_set_scissor_rect(graphics->device, rect); } -void gs_ortho(float left, float right, float top, float bottom, float znear, - float zfar) +void gs_ortho(float left, float right, float top, float bottom, float znear, float zfar) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_ortho")) return; - graphics->exports.device_ortho(graphics->device, left, right, top, - bottom, znear, zfar); + graphics->exports.device_ortho(graphics->device, left, right, top, bottom, znear, zfar); } -void gs_frustum(float left, float right, float top, float bottom, float znear, - float zfar) +void gs_frustum(float left, float right, float top, float bottom, float znear, float zfar) { graphics_t *graphics = thread_graphics; if (!gs_valid("gs_frustum")) return; - graphics->exports.device_frustum(graphics->device, left, right, top, - bottom, znear, zfar); + graphics->exports.device_frustum(graphics->device, left, right, top, bottom, znear, zfar); } void gs_projection_push(void) @@ -2271,8 +2155,7 @@ gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader) return graphics->exports.gs_shader_get_world_matrix(shader); } -void gs_shader_get_param_info(const gs_sparam_t *param, - struct gs_shader_param_info *info) +void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_info *info) { graphics_t *graphics = thread_graphics; @@ -2509,8 +2392,7 @@ uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex) return graphics->exports.gs_cubetexture_get_size(cubetex); } -enum gs_color_format -gs_cubetexture_get_color_format(const gs_texture_t *cubetex) +enum gs_color_format gs_cubetexture_get_color_format(const gs_texture_t *cubetex) { graphics_t *graphics = thread_graphics; @@ -2604,8 +2486,7 @@ uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf) return graphics->exports.gs_stagesurface_get_height(stagesurf); } -enum gs_color_format -gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) +enum gs_color_format gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) { graphics_t *graphics = thread_graphics; @@ -2615,8 +2496,7 @@ gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf) return graphics->exports.gs_stagesurface_get_color_format(stagesurf); } -bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, - uint32_t *linesize) +bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, uint32_t *linesize) { graphics_t *graphics = thread_graphics; @@ -2676,8 +2556,7 @@ void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer) thread_graphics->exports.gs_vertexbuffer_flush(vertbuffer); } -void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer, - const struct gs_vb_data *data) +void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer, const struct gs_vb_data *data) { if (!gs_valid_p2("gs_vertexbuffer_flush_direct", vertbuffer, data)) return; @@ -2713,8 +2592,7 @@ void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer) thread_graphics->exports.gs_indexbuffer_flush(indexbuffer); } -void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer, - const void *data) +void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer, const void *data) { if (!gs_valid_p2("gs_indexbuffer_flush_direct", indexbuffer, data)) return; @@ -2735,8 +2613,7 @@ size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer) if (!gs_valid_p("gs_indexbuffer_get_num_indices", indexbuffer)) return 0; - return thread_graphics->exports.gs_indexbuffer_get_num_indices( - indexbuffer); + return thread_graphics->exports.gs_indexbuffer_get_num_indices(indexbuffer); } enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer) @@ -2827,14 +2704,12 @@ void gs_timer_range_end(gs_timer_range_t *range) graphics->exports.gs_timer_range_end(range); } -bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, - uint64_t *frequency) +bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, uint64_t *frequency) { if (!gs_valid_p2("gs_timer_range_get_data", disjoint, frequency)) return false; - return thread_graphics->exports.gs_timer_range_get_data(range, disjoint, - frequency); + return thread_graphics->exports.gs_timer_range_get_data(range, disjoint, frequency); } bool gs_nv12_available(void) @@ -2845,8 +2720,7 @@ bool gs_nv12_available(void) if (!thread_graphics->exports.device_nv12_available) return false; - return thread_graphics->exports.device_nv12_available( - thread_graphics->device); + return thread_graphics->exports.device_nv12_available(thread_graphics->device); } bool gs_p010_available(void) @@ -2857,8 +2731,7 @@ bool gs_p010_available(void) if (!thread_graphics->exports.device_p010_available) return false; - return thread_graphics->exports.device_p010_available( - thread_graphics->device); + return thread_graphics->exports.device_p010_available(thread_graphics->device); } bool gs_is_monitor_hdr(void *monitor) @@ -2866,8 +2739,7 @@ bool gs_is_monitor_hdr(void *monitor) if (!gs_valid("gs_is_monitor_hdr")) return false; - return thread_graphics->exports.device_is_monitor_hdr( - thread_graphics->device, monitor); + return thread_graphics->exports.device_is_monitor_hdr(thread_graphics->device, monitor); } void gs_debug_marker_begin(const float color[4], const char *markername) @@ -2878,8 +2750,7 @@ void gs_debug_marker_begin(const float color[4], const char *markername) if (!markername) markername = "(null)"; - thread_graphics->exports.device_debug_marker_begin( - thread_graphics->device, markername, color); + thread_graphics->exports.device_debug_marker_begin(thread_graphics->device, markername, color); } void gs_debug_marker_begin_format(const float color[4], const char *format, ...) @@ -2893,8 +2764,7 @@ void gs_debug_marker_begin_format(const float color[4], const char *format, ...) va_start(args, format); vsnprintf(markername, sizeof(markername), format, args); va_end(args); - thread_graphics->exports.device_debug_marker_begin( - thread_graphics->device, markername, color); + thread_graphics->exports.device_debug_marker_begin(thread_graphics->device, markername, color); } else { gs_debug_marker_begin(color, NULL); } @@ -2905,12 +2775,11 @@ void gs_debug_marker_end(void) if (!gs_valid("gs_debug_marker_end")) return; - thread_graphics->exports.device_debug_marker_end( - thread_graphics->device); + thread_graphics->exports.device_debug_marker_end(thread_graphics->device); } -bool gs_texture_create_nv12(gs_texture_t **tex_y, gs_texture_t **tex_uv, - uint32_t width, uint32_t height, uint32_t flags) +bool gs_texture_create_nv12(gs_texture_t **tex_y, gs_texture_t **tex_uv, uint32_t width, uint32_t height, + uint32_t flags) { graphics_t *graphics = thread_graphics; bool success = false; @@ -2925,15 +2794,14 @@ bool gs_texture_create_nv12(gs_texture_t **tex_y, gs_texture_t **tex_uv, } if (graphics->exports.device_texture_create_nv12) { - success = graphics->exports.device_texture_create_nv12( - graphics->device, tex_y, tex_uv, width, height, flags); + success = graphics->exports.device_texture_create_nv12(graphics->device, tex_y, tex_uv, width, height, + flags); if (success) return true; } *tex_y = gs_texture_create(width, height, GS_R8, 1, NULL, flags); - *tex_uv = gs_texture_create(width / 2, height / 2, GS_R8G8, 1, NULL, - flags); + *tex_uv = gs_texture_create(width / 2, height / 2, GS_R8G8, 1, NULL, flags); if (!*tex_y || !*tex_uv) { if (*tex_y) @@ -2948,8 +2816,8 @@ bool gs_texture_create_nv12(gs_texture_t **tex_y, gs_texture_t **tex_uv, return true; } -bool gs_texture_create_p010(gs_texture_t **tex_y, gs_texture_t **tex_uv, - uint32_t width, uint32_t height, uint32_t flags) +bool gs_texture_create_p010(gs_texture_t **tex_y, gs_texture_t **tex_uv, uint32_t width, uint32_t height, + uint32_t flags) { graphics_t *graphics = thread_graphics; bool success = false; @@ -2964,15 +2832,14 @@ bool gs_texture_create_p010(gs_texture_t **tex_y, gs_texture_t **tex_uv, } if (graphics->exports.device_texture_create_p010) { - success = graphics->exports.device_texture_create_p010( - graphics->device, tex_y, tex_uv, width, height, flags); + success = graphics->exports.device_texture_create_p010(graphics->device, tex_y, tex_uv, width, height, + flags); if (success) return true; } *tex_y = gs_texture_create(width, height, GS_R16, 1, NULL, flags); - *tex_uv = gs_texture_create(width / 2, height / 2, GS_RG16, 1, NULL, - flags); + *tex_uv = gs_texture_create(width / 2, height / 2, GS_RG16, 1, NULL, flags); if (!*tex_y || !*tex_uv) { if (*tex_y) @@ -3009,8 +2876,7 @@ gs_texture_t *gs_texture_create_from_iosurface(void *iosurf) if (!graphics->exports.device_texture_create_from_iosurface) return NULL; - return graphics->exports.device_texture_create_from_iosurface( - graphics->device, iosurf); + return graphics->exports.device_texture_create_from_iosurface(graphics->device, iosurf); } bool gs_texture_rebind_iosurface(gs_texture_t *texture, void *iosurf) @@ -3040,8 +2906,7 @@ gs_texture_t *gs_texture_open_shared(uint32_t handle) return NULL; if (graphics->exports.device_texture_open_shared) - return graphics->exports.device_texture_open_shared( - graphics->device, handle); + return graphics->exports.device_texture_open_shared(graphics->device, handle); return NULL; } @@ -3063,16 +2928,15 @@ bool gs_shared_texture_available(void) return thread_graphics->exports.device_shared_texture_available(); } -bool gs_get_duplicator_monitor_info(int monitor_idx, - struct gs_monitor_info *monitor_info) +bool gs_get_duplicator_monitor_info(int monitor_idx, struct gs_monitor_info *monitor_info) { if (!gs_valid_p("gs_get_duplicator_monitor_info", monitor_info)) return false; if (!thread_graphics->exports.device_get_duplicator_monitor_info) return false; - return thread_graphics->exports.device_get_duplicator_monitor_info( - thread_graphics->device, monitor_idx, monitor_info); + return thread_graphics->exports.device_get_duplicator_monitor_info(thread_graphics->device, monitor_idx, + monitor_info); } int gs_duplicator_get_monitor_index(void *monitor) @@ -3082,8 +2946,7 @@ int gs_duplicator_get_monitor_index(void *monitor) if (!thread_graphics->exports.device_duplicator_get_monitor_index) return false; - return thread_graphics->exports.device_duplicator_get_monitor_index( - thread_graphics->device, monitor); + return thread_graphics->exports.device_duplicator_get_monitor_index(thread_graphics->device, monitor); } gs_duplicator_t *gs_duplicator_create(int monitor_idx) @@ -3093,8 +2956,7 @@ gs_duplicator_t *gs_duplicator_create(int monitor_idx) if (!thread_graphics->exports.device_duplicator_create) return NULL; - return thread_graphics->exports.device_duplicator_create( - thread_graphics->device, monitor_idx); + return thread_graphics->exports.device_duplicator_create(thread_graphics->device, monitor_idx); } void gs_duplicator_destroy(gs_duplicator_t *duplicator) @@ -3126,8 +2988,7 @@ bool gs_can_adapter_fast_clear(void) if (!thread_graphics->exports.device_can_adapter_fast_clear) return false; - return thread_graphics->exports.device_can_adapter_fast_clear( - thread_graphics->device); + return thread_graphics->exports.device_can_adapter_fast_clear(thread_graphics->device); } gs_texture_t *gs_duplicator_get_texture(gs_duplicator_t *duplicator) @@ -3147,8 +3008,7 @@ enum gs_color_space gs_duplicator_get_color_space(gs_duplicator_t *duplicator) if (!thread_graphics->exports.gs_duplicator_get_color_space) return GS_CS_SRGB; - return thread_graphics->exports.gs_duplicator_get_color_space( - duplicator); + return thread_graphics->exports.gs_duplicator_get_color_space(duplicator); } float gs_duplicator_get_sdr_white_level(gs_duplicator_t *duplicator) @@ -3158,8 +3018,7 @@ float gs_duplicator_get_sdr_white_level(gs_duplicator_t *duplicator) if (!thread_graphics->exports.gs_duplicator_get_sdr_white_level) return 80.f; - return thread_graphics->exports.gs_duplicator_get_sdr_white_level( - duplicator); + return thread_graphics->exports.gs_duplicator_get_sdr_white_level(duplicator); } /** creates a windows GDI-lockable texture */ @@ -3171,8 +3030,7 @@ gs_texture_t *gs_texture_create_gdi(uint32_t width, uint32_t height) return NULL; if (graphics->exports.device_texture_create_gdi) - return graphics->exports.device_texture_create_gdi( - graphics->device, width, height); + return graphics->exports.device_texture_create_gdi(graphics->device, width, height); return NULL; } @@ -3202,8 +3060,7 @@ gs_texture_t *gs_texture_open_shared(uint32_t handle) return NULL; if (graphics->exports.device_texture_open_shared) - return graphics->exports.device_texture_open_shared( - graphics->device, handle); + return graphics->exports.device_texture_open_shared(graphics->device, handle); return NULL; } @@ -3214,8 +3071,7 @@ gs_texture_t *gs_texture_open_nt_shared(uint32_t handle) return NULL; if (graphics->exports.device_texture_open_nt_shared) - return graphics->exports.device_texture_open_nt_shared( - graphics->device, handle); + return graphics->exports.device_texture_open_nt_shared(graphics->device, handle); return NULL; } @@ -3237,8 +3093,7 @@ gs_texture_t *gs_texture_wrap_obj(void *obj) return NULL; if (graphics->exports.device_texture_wrap_obj) - return graphics->exports.device_texture_wrap_obj( - graphics->device, obj); + return graphics->exports.device_texture_wrap_obj(graphics->device, obj); return NULL; } @@ -3249,8 +3104,7 @@ int gs_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms) return -1; if (graphics->exports.device_texture_acquire_sync) - return graphics->exports.device_texture_acquire_sync(tex, key, - ms); + return graphics->exports.device_texture_acquire_sync(tex, key, ms); return -1; } @@ -3279,8 +3133,7 @@ gs_stagesurf_t *gs_stagesurface_create_nv12(uint32_t width, uint32_t height) } if (graphics->exports.device_stagesurface_create_nv12) - return graphics->exports.device_stagesurface_create_nv12( - graphics->device, width, height); + return graphics->exports.device_stagesurface_create_nv12(graphics->device, width, height); return NULL; } @@ -3299,8 +3152,7 @@ gs_stagesurf_t *gs_stagesurface_create_p010(uint32_t width, uint32_t height) } if (graphics->exports.device_stagesurface_create_p010) - return graphics->exports.device_stagesurface_create_p010( - graphics->device, width, height); + return graphics->exports.device_stagesurface_create_p010(graphics->device, width, height); return NULL; } @@ -3313,8 +3165,7 @@ void gs_register_loss_callbacks(const struct gs_device_loss *callbacks) return; if (graphics->exports.device_register_loss_callbacks) - graphics->exports.device_register_loss_callbacks( - graphics->device, callbacks); + graphics->exports.device_register_loss_callbacks(graphics->device, callbacks); } void gs_unregister_loss_callbacks(void *data) @@ -3325,8 +3176,7 @@ void gs_unregister_loss_callbacks(void *data) return; if (graphics->exports.device_unregister_loss_callbacks) - graphics->exports.device_unregister_loss_callbacks( - graphics->device, data); + graphics->exports.device_unregister_loss_callbacks(graphics->device, data); } #endif diff --git a/libobs/graphics/graphics.h b/libobs/graphics/graphics.h index 2237e6662..61d4a5ae5 100644 --- a/libobs/graphics/graphics.h +++ b/libobs/graphics/graphics.h @@ -340,31 +340,25 @@ enum gs_shader_type { EXPORT void gs_shader_destroy(gs_shader_t *shader); EXPORT int gs_shader_get_num_params(const gs_shader_t *shader); -EXPORT gs_sparam_t *gs_shader_get_param_by_idx(gs_shader_t *shader, - uint32_t param); -EXPORT gs_sparam_t *gs_shader_get_param_by_name(gs_shader_t *shader, - const char *name); +EXPORT gs_sparam_t *gs_shader_get_param_by_idx(gs_shader_t *shader, uint32_t param); +EXPORT gs_sparam_t *gs_shader_get_param_by_name(gs_shader_t *shader, const char *name); EXPORT gs_sparam_t *gs_shader_get_viewproj_matrix(const gs_shader_t *shader); EXPORT gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader); -EXPORT void gs_shader_get_param_info(const gs_sparam_t *param, - struct gs_shader_param_info *info); +EXPORT void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_info *info); EXPORT void gs_shader_set_bool(gs_sparam_t *param, bool val); EXPORT void gs_shader_set_float(gs_sparam_t *param, float val); EXPORT void gs_shader_set_int(gs_sparam_t *param, int val); -EXPORT void gs_shader_set_matrix3(gs_sparam_t *param, - const struct matrix3 *val); -EXPORT void gs_shader_set_matrix4(gs_sparam_t *param, - const struct matrix4 *val); +EXPORT void gs_shader_set_matrix3(gs_sparam_t *param, const struct matrix3 *val); +EXPORT void gs_shader_set_matrix4(gs_sparam_t *param, const struct matrix4 *val); EXPORT void gs_shader_set_vec2(gs_sparam_t *param, const struct vec2 *val); EXPORT void gs_shader_set_vec3(gs_sparam_t *param, const struct vec3 *val); EXPORT void gs_shader_set_vec4(gs_sparam_t *param, const struct vec4 *val); EXPORT void gs_shader_set_texture(gs_sparam_t *param, gs_texture_t *val); EXPORT void gs_shader_set_val(gs_sparam_t *param, const void *val, size_t size); EXPORT void gs_shader_set_default(gs_sparam_t *param); -EXPORT void gs_shader_set_next_sampler(gs_sparam_t *param, - gs_samplerstate_t *sampler); +EXPORT void gs_shader_set_next_sampler(gs_sparam_t *param, gs_samplerstate_t *sampler); #endif /* --------------------------------------------------- @@ -393,34 +387,24 @@ struct gs_effect_param_info { EXPORT void gs_effect_destroy(gs_effect_t *effect); -EXPORT gs_technique_t *gs_effect_get_technique(const gs_effect_t *effect, - const char *name); +EXPORT gs_technique_t *gs_effect_get_technique(const gs_effect_t *effect, const char *name); -EXPORT gs_technique_t * -gs_effect_get_current_technique(const gs_effect_t *effect); +EXPORT gs_technique_t *gs_effect_get_current_technique(const gs_effect_t *effect); EXPORT size_t gs_technique_begin(gs_technique_t *technique); EXPORT void gs_technique_end(gs_technique_t *technique); EXPORT bool gs_technique_begin_pass(gs_technique_t *technique, size_t pass); -EXPORT bool gs_technique_begin_pass_by_name(gs_technique_t *technique, - const char *name); +EXPORT bool gs_technique_begin_pass_by_name(gs_technique_t *technique, const char *name); EXPORT void gs_technique_end_pass(gs_technique_t *technique); -EXPORT gs_epass_t *gs_technique_get_pass_by_idx(const gs_technique_t *technique, - size_t pass); -EXPORT gs_epass_t * -gs_technique_get_pass_by_name(const gs_technique_t *technique, - const char *name); +EXPORT gs_epass_t *gs_technique_get_pass_by_idx(const gs_technique_t *technique, size_t pass); +EXPORT gs_epass_t *gs_technique_get_pass_by_name(const gs_technique_t *technique, const char *name); EXPORT size_t gs_effect_get_num_params(const gs_effect_t *effect); -EXPORT gs_eparam_t *gs_effect_get_param_by_idx(const gs_effect_t *effect, - size_t param); -EXPORT gs_eparam_t *gs_effect_get_param_by_name(const gs_effect_t *effect, - const char *name); +EXPORT gs_eparam_t *gs_effect_get_param_by_idx(const gs_effect_t *effect, size_t param); +EXPORT gs_eparam_t *gs_effect_get_param_by_name(const gs_effect_t *effect, const char *name); EXPORT size_t gs_param_get_num_annotations(const gs_eparam_t *param); -EXPORT gs_eparam_t *gs_param_get_annotation_by_idx(const gs_eparam_t *param, - size_t annotation); -EXPORT gs_eparam_t *gs_param_get_annotation_by_name(const gs_eparam_t *param, - const char *name); +EXPORT gs_eparam_t *gs_param_get_annotation_by_idx(const gs_eparam_t *param, size_t annotation); +EXPORT gs_eparam_t *gs_param_get_annotation_by_name(const gs_eparam_t *param, const char *name); /** Helper function to simplify effect usage. Use with a while loop that * contains drawing functions. Automatically handles techniques, passes, and @@ -434,15 +418,13 @@ EXPORT gs_eparam_t *gs_effect_get_viewproj_matrix(const gs_effect_t *effect); EXPORT gs_eparam_t *gs_effect_get_world_matrix(const gs_effect_t *effect); #ifndef SWIG -EXPORT void gs_effect_get_param_info(const gs_eparam_t *param, - struct gs_effect_param_info *info); +EXPORT void gs_effect_get_param_info(const gs_eparam_t *param, struct gs_effect_param_info *info); #endif EXPORT void gs_effect_set_bool(gs_eparam_t *param, bool val); EXPORT void gs_effect_set_float(gs_eparam_t *param, float val); EXPORT void gs_effect_set_int(gs_eparam_t *param, int val); -EXPORT void gs_effect_set_matrix4(gs_eparam_t *param, - const struct matrix4 *val); +EXPORT void gs_effect_set_matrix4(gs_eparam_t *param, const struct matrix4 *val); EXPORT void gs_effect_set_vec2(gs_eparam_t *param, const struct vec2 *val); EXPORT void gs_effect_set_vec3(gs_eparam_t *param, const struct vec3 *val); EXPORT void gs_effect_set_vec4(gs_eparam_t *param, const struct vec4 *val); @@ -454,8 +436,7 @@ EXPORT size_t gs_effect_get_val_size(gs_eparam_t *param); EXPORT void *gs_effect_get_val(gs_eparam_t *param); EXPORT size_t gs_effect_get_default_val_size(gs_eparam_t *param); EXPORT void *gs_effect_get_default_val(gs_eparam_t *param); -EXPORT void gs_effect_set_next_sampler(gs_eparam_t *param, - gs_samplerstate_t *sampler); +EXPORT void gs_effect_set_next_sampler(gs_eparam_t *param, gs_samplerstate_t *sampler); EXPORT void gs_effect_set_color(gs_eparam_t *param, uint32_t argb); @@ -463,19 +444,15 @@ EXPORT void gs_effect_set_color(gs_eparam_t *param, uint32_t argb); * texture render helper functions * --------------------------------------------------- */ -EXPORT gs_texrender_t *gs_texrender_create(enum gs_color_format format, - enum gs_zstencil_format zsformat); +EXPORT gs_texrender_t *gs_texrender_create(enum gs_color_format format, enum gs_zstencil_format zsformat); EXPORT void gs_texrender_destroy(gs_texrender_t *texrender); -EXPORT bool gs_texrender_begin(gs_texrender_t *texrender, uint32_t cx, - uint32_t cy); -EXPORT bool gs_texrender_begin_with_color_space(gs_texrender_t *texrender, - uint32_t cx, uint32_t cy, +EXPORT bool gs_texrender_begin(gs_texrender_t *texrender, uint32_t cx, uint32_t cy); +EXPORT bool gs_texrender_begin_with_color_space(gs_texrender_t *texrender, uint32_t cx, uint32_t cy, enum gs_color_space space); EXPORT void gs_texrender_end(gs_texrender_t *texrender); EXPORT void gs_texrender_reset(gs_texrender_t *texrender); EXPORT gs_texture_t *gs_texrender_get_texture(const gs_texrender_t *texrender); -EXPORT enum gs_color_format -gs_texrender_get_format(const gs_texrender_t *texrender); +EXPORT enum gs_color_format gs_texrender_get_format(const gs_texrender_t *texrender); /* --------------------------------------------------- * graphics subsystem @@ -526,12 +503,9 @@ struct gs_init_data { EXPORT const char *gs_get_device_name(void); EXPORT int gs_get_device_type(void); EXPORT uint32_t gs_get_adapter_count(void); -EXPORT void gs_enum_adapters(bool (*callback)(void *param, const char *name, - uint32_t id), - void *param); +EXPORT void gs_enum_adapters(bool (*callback)(void *param, const char *name, uint32_t id), void *param); -EXPORT int gs_create(graphics_t **graphics, const char *module, - uint32_t adapter); +EXPORT int gs_create(graphics_t **graphics, const char *module, uint32_t adapter); EXPORT void gs_destroy(graphics_t *graphics); EXPORT void gs_enter_context(graphics_t *graphics); @@ -571,15 +545,11 @@ EXPORT void gs_texcoord2v(const struct vec2 *v, int unit); EXPORT input_t *gs_get_input(void); EXPORT gs_effect_t *gs_get_effect(void); -EXPORT gs_effect_t *gs_effect_create_from_file(const char *file, - char **error_string); -EXPORT gs_effect_t *gs_effect_create(const char *effect_string, - const char *filename, char **error_string); +EXPORT gs_effect_t *gs_effect_create_from_file(const char *file, char **error_string); +EXPORT gs_effect_t *gs_effect_create(const char *effect_string, const char *filename, char **error_string); -EXPORT gs_shader_t *gs_vertexshader_create_from_file(const char *file, - char **error_string); -EXPORT gs_shader_t *gs_pixelshader_create_from_file(const char *file, - char **error_string); +EXPORT gs_shader_t *gs_vertexshader_create_from_file(const char *file, char **error_string); +EXPORT gs_shader_t *gs_pixelshader_create_from_file(const char *file, char **error_string); enum gs_image_alpha_mode { GS_IMAGE_ALPHA_STRAIGHT, @@ -588,17 +558,12 @@ enum gs_image_alpha_mode { }; EXPORT gs_texture_t *gs_texture_create_from_file(const char *file); -EXPORT uint8_t *gs_create_texture_file_data(const char *file, - enum gs_color_format *format, - uint32_t *cx, uint32_t *cy); -EXPORT uint8_t *gs_create_texture_file_data2( - const char *file, enum gs_image_alpha_mode alpha_mode, - enum gs_color_format *format, uint32_t *cx, uint32_t *cy); -EXPORT uint8_t * -gs_create_texture_file_data3(const char *file, - enum gs_image_alpha_mode alpha_mode, - enum gs_color_format *format, uint32_t *cx, - uint32_t *cy, enum gs_color_space *space); +EXPORT uint8_t *gs_create_texture_file_data(const char *file, enum gs_color_format *format, uint32_t *cx, uint32_t *cy); +EXPORT uint8_t *gs_create_texture_file_data2(const char *file, enum gs_image_alpha_mode alpha_mode, + enum gs_color_format *format, uint32_t *cx, uint32_t *cy); +EXPORT uint8_t *gs_create_texture_file_data3(const char *file, enum gs_image_alpha_mode alpha_mode, + enum gs_color_format *format, uint32_t *cx, uint32_t *cy, + enum gs_color_space *space); #define GS_FLIP_U (1 << 0) #define GS_FLIP_V (1 << 1) @@ -610,15 +575,12 @@ gs_create_texture_file_data3(const char *file, * The flip value specifies whether the texture should be flipped on the U or V * axis with GS_FLIP_U and GS_FLIP_V. */ -EXPORT void gs_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, - uint32_t height); +EXPORT void gs_draw_sprite(gs_texture_t *tex, uint32_t flip, uint32_t width, uint32_t height); -EXPORT void gs_draw_sprite_subregion(gs_texture_t *tex, uint32_t flip, - uint32_t x, uint32_t y, uint32_t cx, +EXPORT void gs_draw_sprite_subregion(gs_texture_t *tex, uint32_t flip, uint32_t x, uint32_t y, uint32_t cx, uint32_t cy); -EXPORT void gs_draw_cube_backdrop(gs_texture_t *cubetex, const struct quat *rot, - float left, float right, float top, +EXPORT void gs_draw_cube_backdrop(gs_texture_t *cubetex, const struct quat *rot, float left, float right, float top, float bottom, float znear); /** sets the viewport to current swap chain size */ @@ -632,10 +594,8 @@ EXPORT void gs_set_3d_mode(double fovy, double znear, double zvar); EXPORT void gs_viewport_push(void); EXPORT void gs_viewport_pop(void); -EXPORT void gs_texture_set_image(gs_texture_t *tex, const uint8_t *data, - uint32_t linesize, bool invert); -EXPORT void gs_cubetexture_set_image(gs_texture_t *cubetex, uint32_t side, - const void *data, uint32_t linesize, +EXPORT void gs_texture_set_image(gs_texture_t *tex, const uint8_t *data, uint32_t linesize, bool invert); +EXPORT void gs_cubetexture_set_image(gs_texture_t *cubetex, uint32_t side, const void *data, uint32_t linesize, bool invert); EXPORT void gs_perspective(float fovy, float aspect, float znear, float zfar); @@ -655,39 +615,25 @@ EXPORT void gs_get_size(uint32_t *x, uint32_t *y); EXPORT uint32_t gs_get_width(void); EXPORT uint32_t gs_get_height(void); -EXPORT gs_texture_t *gs_texture_create(uint32_t width, uint32_t height, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, - uint32_t flags); -EXPORT gs_texture_t * -gs_cubetexture_create(uint32_t size, enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, uint32_t flags); -EXPORT gs_texture_t *gs_voltexture_create(uint32_t width, uint32_t height, - uint32_t depth, - enum gs_color_format color_format, - uint32_t levels, const uint8_t **data, +EXPORT gs_texture_t *gs_texture_create(uint32_t width, uint32_t height, enum gs_color_format color_format, + uint32_t levels, const uint8_t **data, uint32_t flags); +EXPORT gs_texture_t *gs_cubetexture_create(uint32_t size, enum gs_color_format color_format, uint32_t levels, + const uint8_t **data, uint32_t flags); +EXPORT gs_texture_t *gs_voltexture_create(uint32_t width, uint32_t height, uint32_t depth, + enum gs_color_format color_format, uint32_t levels, const uint8_t **data, uint32_t flags); -EXPORT gs_zstencil_t *gs_zstencil_create(uint32_t width, uint32_t height, - enum gs_zstencil_format format); +EXPORT gs_zstencil_t *gs_zstencil_create(uint32_t width, uint32_t height, enum gs_zstencil_format format); -EXPORT gs_stagesurf_t * -gs_stagesurface_create(uint32_t width, uint32_t height, - enum gs_color_format color_format); +EXPORT gs_stagesurf_t *gs_stagesurface_create(uint32_t width, uint32_t height, enum gs_color_format color_format); -EXPORT gs_samplerstate_t * -gs_samplerstate_create(const struct gs_sampler_info *info); +EXPORT gs_samplerstate_t *gs_samplerstate_create(const struct gs_sampler_info *info); -EXPORT gs_shader_t *gs_vertexshader_create(const char *shader, const char *file, - char **error_string); -EXPORT gs_shader_t *gs_pixelshader_create(const char *shader, const char *file, - char **error_string); +EXPORT gs_shader_t *gs_vertexshader_create(const char *shader, const char *file, char **error_string); +EXPORT gs_shader_t *gs_pixelshader_create(const char *shader, const char *file, char **error_string); -EXPORT gs_vertbuffer_t *gs_vertexbuffer_create(struct gs_vb_data *data, - uint32_t flags); -EXPORT gs_indexbuffer_t *gs_indexbuffer_create(enum gs_index_type type, - void *indices, size_t num, - uint32_t flags); +EXPORT gs_vertbuffer_t *gs_vertexbuffer_create(struct gs_vb_data *data, uint32_t flags); +EXPORT gs_indexbuffer_t *gs_indexbuffer_create(enum gs_index_type type, void *indices, size_t num, uint32_t flags); EXPORT gs_timer_t *gs_timer_create(); EXPORT gs_timer_range_t *gs_timer_range_create(); @@ -711,11 +657,9 @@ EXPORT gs_texture_t *gs_get_render_target(void); EXPORT gs_zstencil_t *gs_get_zstencil_target(void); EXPORT void gs_set_render_target(gs_texture_t *tex, gs_zstencil_t *zstencil); -EXPORT void gs_set_render_target_with_color_space(gs_texture_t *tex, - gs_zstencil_t *zstencil, +EXPORT void gs_set_render_target_with_color_space(gs_texture_t *tex, gs_zstencil_t *zstencil, enum gs_color_space space); -EXPORT void gs_set_cube_render_target(gs_texture_t *cubetex, int side, - gs_zstencil_t *zstencil); +EXPORT void gs_set_cube_render_target(gs_texture_t *cubetex, int side, gs_zstencil_t *zstencil); EXPORT void gs_enable_framebuffer_srgb(bool enable); EXPORT bool gs_framebuffer_srgb_enabled(void); @@ -724,16 +668,13 @@ EXPORT bool gs_get_linear_srgb(void); EXPORT bool gs_set_linear_srgb(bool linear_srgb); EXPORT void gs_copy_texture(gs_texture_t *dst, gs_texture_t *src); -EXPORT void gs_copy_texture_region(gs_texture_t *dst, uint32_t dst_x, - uint32_t dst_y, gs_texture_t *src, - uint32_t src_x, uint32_t src_y, - uint32_t src_w, uint32_t src_h); +EXPORT void gs_copy_texture_region(gs_texture_t *dst, uint32_t dst_x, uint32_t dst_y, gs_texture_t *src, uint32_t src_x, + uint32_t src_y, uint32_t src_w, uint32_t src_h); EXPORT void gs_stage_texture(gs_stagesurf_t *dst, gs_texture_t *src); EXPORT void gs_begin_frame(void); EXPORT void gs_begin_scene(void); -EXPORT void gs_draw(enum gs_draw_mode draw_mode, uint32_t start_vert, - uint32_t num_verts); +EXPORT void gs_draw(enum gs_draw_mode draw_mode, uint32_t start_vert, uint32_t num_verts); EXPORT void gs_end_scene(void); #define GS_CLEAR_COLOR (1 << 0) @@ -741,8 +682,7 @@ EXPORT void gs_end_scene(void); #define GS_CLEAR_STENCIL (1 << 2) EXPORT void gs_load_swapchain(gs_swapchain_t *swapchain); -EXPORT void gs_clear(uint32_t clear_flags, const struct vec4 *color, - float depth, uint8_t stencil); +EXPORT void gs_clear(uint32_t clear_flags, const struct vec4 *color, float depth, uint8_t stencil); EXPORT bool gs_is_present_ready(void); EXPORT void gs_present(void); EXPORT void gs_flush(void); @@ -757,29 +697,22 @@ EXPORT void gs_enable_stencil_write(bool enable); EXPORT void gs_enable_color(bool red, bool green, bool blue, bool alpha); EXPORT void gs_blend_function(enum gs_blend_type src, enum gs_blend_type dest); -EXPORT void gs_blend_function_separate(enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, +EXPORT void gs_blend_function_separate(enum gs_blend_type src_c, enum gs_blend_type dest_c, enum gs_blend_type src_a, enum gs_blend_type dest_a); EXPORT void gs_blend_op(enum gs_blend_op_type op); EXPORT void gs_depth_function(enum gs_depth_test test); -EXPORT void gs_stencil_function(enum gs_stencil_side side, - enum gs_depth_test test); -EXPORT void gs_stencil_op(enum gs_stencil_side side, - enum gs_stencil_op_type fail, - enum gs_stencil_op_type zfail, +EXPORT void gs_stencil_function(enum gs_stencil_side side, enum gs_depth_test test); +EXPORT void gs_stencil_op(enum gs_stencil_side side, enum gs_stencil_op_type fail, enum gs_stencil_op_type zfail, enum gs_stencil_op_type zpass); EXPORT void gs_set_viewport(int x, int y, int width, int height); EXPORT void gs_get_viewport(struct gs_rect *rect); EXPORT void gs_set_scissor_rect(const struct gs_rect *rect); -EXPORT void gs_ortho(float left, float right, float top, float bottom, - float znear, float zfar); -EXPORT void gs_frustum(float left, float right, float top, float bottom, - float znear, float zfar); +EXPORT void gs_ortho(float left, float right, float top, float bottom, float znear, float zfar); +EXPORT void gs_frustum(float left, float right, float top, float bottom, float znear, float zfar); EXPORT void gs_projection_push(void); EXPORT void gs_projection_pop(void); @@ -789,10 +722,8 @@ EXPORT void gs_swapchain_destroy(gs_swapchain_t *swapchain); EXPORT void gs_texture_destroy(gs_texture_t *tex); EXPORT uint32_t gs_texture_get_width(const gs_texture_t *tex); EXPORT uint32_t gs_texture_get_height(const gs_texture_t *tex); -EXPORT enum gs_color_format -gs_texture_get_color_format(const gs_texture_t *tex); -EXPORT bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, - uint32_t *linesize); +EXPORT enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex); +EXPORT bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize); EXPORT void gs_texture_unmap(gs_texture_t *tex); /** special-case function (GL only) - specifies whether the texture is a * GL_TEXTURE_RECTANGLE type, which doesn't use normalized texture @@ -806,23 +737,19 @@ EXPORT void *gs_texture_get_obj(gs_texture_t *tex); EXPORT void gs_cubetexture_destroy(gs_texture_t *cubetex); EXPORT uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex); -EXPORT enum gs_color_format -gs_cubetexture_get_color_format(const gs_texture_t *cubetex); +EXPORT enum gs_color_format gs_cubetexture_get_color_format(const gs_texture_t *cubetex); EXPORT void gs_voltexture_destroy(gs_texture_t *voltex); EXPORT uint32_t gs_voltexture_get_width(const gs_texture_t *voltex); EXPORT uint32_t gs_voltexture_get_height(const gs_texture_t *voltex); EXPORT uint32_t gs_voltexture_get_depth(const gs_texture_t *voltex); -EXPORT enum gs_color_format -gs_voltexture_get_color_format(const gs_texture_t *voltex); +EXPORT enum gs_color_format gs_voltexture_get_color_format(const gs_texture_t *voltex); EXPORT void gs_stagesurface_destroy(gs_stagesurf_t *stagesurf); EXPORT uint32_t gs_stagesurface_get_width(const gs_stagesurf_t *stagesurf); EXPORT uint32_t gs_stagesurface_get_height(const gs_stagesurf_t *stagesurf); -EXPORT enum gs_color_format -gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf); -EXPORT bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, - uint32_t *linesize); +EXPORT enum gs_color_format gs_stagesurface_get_color_format(const gs_stagesurf_t *stagesurf); +EXPORT bool gs_stagesurface_map(gs_stagesurf_t *stagesurf, uint8_t **data, uint32_t *linesize); EXPORT void gs_stagesurface_unmap(gs_stagesurf_t *stagesurf); EXPORT void gs_zstencil_destroy(gs_zstencil_t *zstencil); @@ -831,20 +758,15 @@ EXPORT void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate); EXPORT void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer); EXPORT void gs_vertexbuffer_flush(gs_vertbuffer_t *vertbuffer); -EXPORT void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer, - const struct gs_vb_data *data); -EXPORT struct gs_vb_data * -gs_vertexbuffer_get_data(const gs_vertbuffer_t *vertbuffer); +EXPORT void gs_vertexbuffer_flush_direct(gs_vertbuffer_t *vertbuffer, const struct gs_vb_data *data); +EXPORT struct gs_vb_data *gs_vertexbuffer_get_data(const gs_vertbuffer_t *vertbuffer); EXPORT void gs_indexbuffer_destroy(gs_indexbuffer_t *indexbuffer); EXPORT void gs_indexbuffer_flush(gs_indexbuffer_t *indexbuffer); -EXPORT void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer, - const void *data); +EXPORT void gs_indexbuffer_flush_direct(gs_indexbuffer_t *indexbuffer, const void *data); EXPORT void *gs_indexbuffer_get_data(const gs_indexbuffer_t *indexbuffer); -EXPORT size_t -gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer); -EXPORT enum gs_index_type -gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer); +EXPORT size_t gs_indexbuffer_get_num_indices(const gs_indexbuffer_t *indexbuffer); +EXPORT enum gs_index_type gs_indexbuffer_get_type(const gs_indexbuffer_t *indexbuffer); EXPORT void gs_timer_destroy(gs_timer_t *timer); EXPORT void gs_timer_begin(gs_timer_t *timer); @@ -853,16 +775,13 @@ EXPORT bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks); EXPORT void gs_timer_range_destroy(gs_timer_range_t *timer); EXPORT void gs_timer_range_begin(gs_timer_range_t *range); EXPORT void gs_timer_range_end(gs_timer_range_t *range); -EXPORT bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, - uint64_t *frequency); +EXPORT bool gs_timer_range_get_data(gs_timer_range_t *range, bool *disjoint, uint64_t *frequency); EXPORT bool gs_nv12_available(void); EXPORT bool gs_p010_available(void); -EXPORT bool gs_texture_create_nv12(gs_texture_t **tex_y, gs_texture_t **tex_uv, - uint32_t width, uint32_t height, +EXPORT bool gs_texture_create_nv12(gs_texture_t **tex_y, gs_texture_t **tex_uv, uint32_t width, uint32_t height, uint32_t flags); -EXPORT bool gs_texture_create_p010(gs_texture_t **tex_y, gs_texture_t **tex_uv, - uint32_t width, uint32_t height, +EXPORT bool gs_texture_create_p010(gs_texture_t **tex_y, gs_texture_t **tex_uv, uint32_t width, uint32_t height, uint32_t flags); EXPORT bool gs_is_monitor_hdr(void *monitor); @@ -877,10 +796,8 @@ static const float GS_DEBUG_COLOR_SOURCE[] = {0.0f, 0.5f, 5.0f, 1.0f}; static const float GS_DEBUG_COLOR_ITEM[] = {0.5f, 0.0f, 0.0f, 1.0f}; static const float GS_DEBUG_COLOR_ITEM_TEXTURE[] = {0.25f, 0.0f, 0.0f, 1.0f}; static const float GS_DEBUG_COLOR_CONVERT_FORMAT[] = {0.5f, 0.5f, 0.0f, 1.0f}; -#define GS_DEBUG_MARKER_BEGIN(color, markername) \ - gs_debug_marker_begin(color, markername) -#define GS_DEBUG_MARKER_BEGIN_FORMAT(color, format, ...) \ - gs_debug_marker_begin_format(color, format, __VA_ARGS__) +#define GS_DEBUG_MARKER_BEGIN(color, markername) gs_debug_marker_begin(color, markername) +#define GS_DEBUG_MARKER_BEGIN_FORMAT(color, format, ...) gs_debug_marker_begin_format(color, format, __VA_ARGS__) #define GS_DEBUG_MARKER_END() gs_debug_marker_end() #else #define GS_DEBUG_MARKER_BEGIN(color, markername) ((void)0) @@ -889,8 +806,7 @@ static const float GS_DEBUG_COLOR_CONVERT_FORMAT[] = {0.5f, 0.5f, 0.0f, 1.0f}; #endif EXPORT void gs_debug_marker_begin(const float color[4], const char *markername); -EXPORT void gs_debug_marker_begin_format(const float color[4], - const char *format, ...); +EXPORT void gs_debug_marker_begin_format(const float color[4], const char *format, ...); EXPORT void gs_debug_marker_end(void); #ifdef __APPLE__ @@ -914,9 +830,7 @@ typedef struct gs_duplicator gs_duplicator_t; * Gets information about the monitor at the specific index, returns false * when there is no monitor at the specified index */ -EXPORT bool -gs_get_duplicator_monitor_info(int monitor_idx, - struct gs_monitor_info *monitor_info); +EXPORT bool gs_get_duplicator_monitor_info(int monitor_idx, struct gs_monitor_info *monitor_info); EXPORT int gs_duplicator_get_monitor_index(void *monitor); @@ -926,8 +840,7 @@ EXPORT void gs_duplicator_destroy(gs_duplicator_t *duplicator); EXPORT bool gs_duplicator_update_frame(gs_duplicator_t *duplicator); EXPORT gs_texture_t *gs_duplicator_get_texture(gs_duplicator_t *duplicator); -EXPORT enum gs_color_space -gs_duplicator_get_color_space(gs_duplicator_t *duplicator); +EXPORT enum gs_color_space gs_duplicator_get_color_space(gs_duplicator_t *duplicator); EXPORT float gs_duplicator_get_sdr_white_level(gs_duplicator_t *duplicator); EXPORT bool gs_can_adapter_fast_clear(void); @@ -953,8 +866,7 @@ EXPORT gs_texture_t *gs_texture_wrap_obj(void *obj); * acquires a lock on a keyed mutex texture. * returns -1 on generic failure, ETIMEDOUT if timed out */ -EXPORT int gs_texture_acquire_sync(gs_texture_t *tex, uint64_t key, - uint32_t ms); +EXPORT int gs_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms); /** * releases a lock on a keyed mutex texture to another device. @@ -962,39 +874,30 @@ EXPORT int gs_texture_acquire_sync(gs_texture_t *tex, uint64_t key, */ EXPORT int gs_texture_release_sync(gs_texture_t *tex, uint64_t key); -EXPORT gs_stagesurf_t *gs_stagesurface_create_nv12(uint32_t width, - uint32_t height); -EXPORT gs_stagesurf_t *gs_stagesurface_create_p010(uint32_t width, - uint32_t height); +EXPORT gs_stagesurf_t *gs_stagesurface_create_nv12(uint32_t width, uint32_t height); +EXPORT gs_stagesurf_t *gs_stagesurface_create_p010(uint32_t width, uint32_t height); EXPORT void gs_register_loss_callbacks(const struct gs_device_loss *callbacks); EXPORT void gs_unregister_loss_callbacks(void *data); #elif defined(__linux__) || defined(__FreeBSD__) || defined(__DragonFly__) -EXPORT gs_texture_t *gs_texture_create_from_dmabuf( - unsigned int width, unsigned int height, uint32_t drm_format, - enum gs_color_format color_format, uint32_t n_planes, const int *fds, - const uint32_t *strides, const uint32_t *offsets, - const uint64_t *modifiers); +EXPORT gs_texture_t *gs_texture_create_from_dmabuf(unsigned int width, unsigned int height, uint32_t drm_format, + enum gs_color_format color_format, uint32_t n_planes, const int *fds, + const uint32_t *strides, const uint32_t *offsets, + const uint64_t *modifiers); enum gs_dmabuf_flags { GS_DMABUF_FLAG_NONE = 0, GS_DMABUF_FLAG_IMPLICIT_MODIFIERS_SUPPORTED = (1 << 0), }; -EXPORT bool gs_query_dmabuf_capabilities(enum gs_dmabuf_flags *dmabuf_flags, - uint32_t **drm_formats, - size_t *n_formats); +EXPORT bool gs_query_dmabuf_capabilities(enum gs_dmabuf_flags *dmabuf_flags, uint32_t **drm_formats, size_t *n_formats); -EXPORT bool gs_query_dmabuf_modifiers_for_format(uint32_t drm_format, - uint64_t **modifiers, - size_t *n_modifiers); +EXPORT bool gs_query_dmabuf_modifiers_for_format(uint32_t drm_format, uint64_t **modifiers, size_t *n_modifiers); -EXPORT gs_texture_t * -gs_texture_create_from_pixmap(uint32_t width, uint32_t height, - enum gs_color_format color_format, - uint32_t target, void *pixmap); +EXPORT gs_texture_t *gs_texture_create_from_pixmap(uint32_t width, uint32_t height, enum gs_color_format color_format, + uint32_t target, void *pixmap); #endif @@ -1055,8 +958,7 @@ static inline bool gs_is_srgb_format(enum gs_color_format format) } } -static inline enum gs_color_format -gs_generalize_format(enum gs_color_format format) +static inline enum gs_color_format gs_generalize_format(enum gs_color_format format) { switch (format) { case GS_RGBA_UNORM: @@ -1070,8 +972,7 @@ gs_generalize_format(enum gs_color_format format) } } -static inline enum gs_color_format -gs_get_format_from_space(enum gs_color_space space) +static inline enum gs_color_format gs_get_format_from_space(enum gs_color_space space) { switch (space) { case GS_CS_SRGB: @@ -1085,8 +986,7 @@ gs_get_format_from_space(enum gs_color_space space) return GS_RGBA; } -static inline uint32_t gs_get_total_levels(uint32_t width, uint32_t height, - uint32_t depth) +static inline uint32_t gs_get_total_levels(uint32_t width, uint32_t height, uint32_t depth) { uint32_t size = width > height ? width : height; size = size > depth ? size : depth; diff --git a/libobs/graphics/half.h b/libobs/graphics/half.h index f597ea0b1..76a8fe12f 100644 --- a/libobs/graphics/half.h +++ b/libobs/graphics/half.h @@ -62,8 +62,7 @@ static inline struct half half_from_float(float f) if (IValue > 0x477FE000U) { // The number is too large to be represented as a half. Saturate to infinity. - if (((IValue & 0x7F800000) == 0x7F800000) && - ((IValue & 0x7FFFFF) != 0)) { + if (((IValue & 0x7F800000) == 0x7F800000) && ((IValue & 0x7FFFFF) != 0)) { Result = 0x7FFF; // NAN } else { Result = 0x7C00U; // INF @@ -81,8 +80,7 @@ static inline struct half half_from_float(float f) IValue += 0xC8000000U; } - Result = ((IValue + 0x0FFFU + ((IValue >> 13U) & 1U)) >> 13U) & - 0x7FFFU; + Result = ((IValue + 0x0FFFU + ((IValue >> 13U) & 1U)) >> 13U) & 0x7FFFU; } struct half h; diff --git a/libobs/graphics/image-file.c b/libobs/graphics/image-file.c index 7bfb16f58..a07fb004f 100644 --- a/libobs/graphics/image-file.c +++ b/libobs/graphics/image-file.c @@ -21,8 +21,7 @@ #include "../util/dstr.h" #include "vec4.h" -#define blog(level, format, ...) \ - blog(level, "%s: " format, __FUNCTION__, __VA_ARGS__) +#define blog(level, format, ...) blog(level, "%s: " format, __FUNCTION__, __VA_ARGS__) static void *bi_def_bitmap_create(int width, int height) { @@ -58,12 +57,10 @@ static void bi_def_bitmap_modified(void *bitmap) static inline int get_full_decoded_gif_size(gs_image_file_t *image) { - return image->gif.width * image->gif.height * 4 * - image->gif.frame_count; + return image->gif.width * image->gif.height * 4 * image->gif.frame_count; } -static inline void *alloc_mem(gs_image_file_t *image, uint64_t *mem_usage, - size_t size) +static inline void *alloc_mem(gs_image_file_t *image, uint64_t *mem_usage, size_t size) { UNUSED_PARAMETER(image); @@ -72,8 +69,7 @@ static inline void *alloc_mem(gs_image_file_t *image, uint64_t *mem_usage, return bzalloc(size); } -static bool init_animated_gif(gs_image_file_t *image, const char *path, - uint64_t *mem_usage, +static bool init_animated_gif(gs_image_file_t *image, const char *path, uint64_t *mem_usage, enum gs_image_alpha_mode alpha_mode) { bool is_animated_gif = true; @@ -120,17 +116,14 @@ static bool init_animated_gif(gs_image_file_t *image, const char *path, } while (result != GIF_OK); if (image->gif.width > 4096 || image->gif.height > 4096) { - blog(LOG_WARNING, "Bad texture dimensions (%dx%d) in '%s'", - image->gif.width, image->gif.height, path); + blog(LOG_WARNING, "Bad texture dimensions (%dx%d) in '%s'", image->gif.width, image->gif.height, path); goto fail; } - max_size = (uint64_t)image->gif.width * (uint64_t)image->gif.height * - (uint64_t)image->gif.frame_count * 4LLU; + max_size = (uint64_t)image->gif.width * (uint64_t)image->gif.height * (uint64_t)image->gif.frame_count * 4LLU; if ((uint64_t)get_full_decoded_gif_size(image) != max_size) { - blog(LOG_WARNING, "Gif '%s' overflowed maximum pointer size", - path); + blog(LOG_WARNING, "Gif '%s' overflowed maximum pointer size", path); goto fail; } @@ -138,11 +131,8 @@ static bool init_animated_gif(gs_image_file_t *image, const char *path, if (image->is_animated_gif) { gif_decode_frame(&image->gif, 0); - image->animation_frame_cache = - alloc_mem(image, mem_usage, - image->gif.frame_count * sizeof(uint8_t *)); - image->animation_frame_data = alloc_mem( - image, mem_usage, get_full_decoded_gif_size(image)); + image->animation_frame_cache = alloc_mem(image, mem_usage, image->gif.frame_count * sizeof(uint8_t *)); + image->animation_frame_data = alloc_mem(image, mem_usage, get_full_decoded_gif_size(image)); for (unsigned int i = 0; i < image->gif.frame_count; i++) { if (gif_decode_frame(&image->gif, i) != GIF_OK) @@ -164,12 +154,9 @@ static bool init_animated_gif(gs_image_file_t *image, const char *path, } if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) { - gs_premultiply_xyza_srgb_loop(image->gif.frame_image, - (size_t)image->cx * - image->cy); + gs_premultiply_xyza_srgb_loop(image->gif.frame_image, (size_t)image->cx * image->cy); } else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) { - gs_premultiply_xyza_loop(image->gif.frame_image, - (size_t)image->cx * image->cy); + gs_premultiply_xyza_loop(image->gif.frame_image, (size_t)image->cx * image->cy); } } else { gif_finalise(&image->gif); @@ -191,10 +178,8 @@ not_animated: return is_animated_gif; } -static void gs_image_file_init_internal(gs_image_file_t *image, - const char *file, uint64_t *mem_usage, - enum gs_color_space *space, - enum gs_image_alpha_mode alpha_mode) +static void gs_image_file_init_internal(gs_image_file_t *image, const char *file, uint64_t *mem_usage, + enum gs_color_space *space, enum gs_image_alpha_mode alpha_mode) { size_t len; @@ -215,12 +200,10 @@ static void gs_image_file_init_internal(gs_image_file_t *image, } image->texture_data = - gs_create_texture_file_data3(file, alpha_mode, &image->format, - &image->cx, &image->cy, space); + gs_create_texture_file_data3(file, alpha_mode, &image->format, &image->cx, &image->cy, space); if (mem_usage) { - *mem_usage += image->cx * image->cy * - gs_get_format_bpp(image->format) / 8; + *mem_usage += image->cx * image->cy * gs_get_format_bpp(image->format) / 8; } image->loaded = !!image->texture_data; @@ -233,8 +216,7 @@ static void gs_image_file_init_internal(gs_image_file_t *image, void gs_image_file_init(gs_image_file_t *image, const char *file) { enum gs_color_space unused; - gs_image_file_init_internal(image, file, NULL, &unused, - GS_IMAGE_ALPHA_STRAIGHT); + gs_image_file_init_internal(image, file, NULL, &unused, GS_IMAGE_ALPHA_STRAIGHT); } void gs_image_file_free(gs_image_file_t *image) @@ -260,25 +242,19 @@ void gs_image_file_free(gs_image_file_t *image) void gs_image_file2_init(gs_image_file2_t *if2, const char *file) { enum gs_color_space unused; - gs_image_file_init_internal(&if2->image, file, &if2->mem_usage, &unused, - GS_IMAGE_ALPHA_STRAIGHT); + gs_image_file_init_internal(&if2->image, file, &if2->mem_usage, &unused, GS_IMAGE_ALPHA_STRAIGHT); } -void gs_image_file3_init(gs_image_file3_t *if3, const char *file, - enum gs_image_alpha_mode alpha_mode) +void gs_image_file3_init(gs_image_file3_t *if3, const char *file, enum gs_image_alpha_mode alpha_mode) { enum gs_color_space unused; - gs_image_file_init_internal(&if3->image2.image, file, - &if3->image2.mem_usage, &unused, - alpha_mode); + gs_image_file_init_internal(&if3->image2.image, file, &if3->image2.mem_usage, &unused, alpha_mode); if3->alpha_mode = alpha_mode; } -void gs_image_file4_init(gs_image_file4_t *if4, const char *file, - enum gs_image_alpha_mode alpha_mode) +void gs_image_file4_init(gs_image_file4_t *if4, const char *file, enum gs_image_alpha_mode alpha_mode) { - gs_image_file_init_internal(&if4->image3.image2.image, file, - &if4->image3.image2.mem_usage, &if4->space, + gs_image_file_init_internal(&if4->image3.image2.image, file, &if4->image3.image2.mem_usage, &if4->space, alpha_mode); if4->image3.alpha_mode = alpha_mode; } @@ -289,14 +265,12 @@ void gs_image_file_init_texture(gs_image_file_t *image) return; if (image->is_animated_gif) { - image->texture = gs_texture_create( - image->cx, image->cy, image->format, 1, - (const uint8_t **)&image->gif.frame_image, GS_DYNAMIC); + image->texture = gs_texture_create(image->cx, image->cy, image->format, 1, + (const uint8_t **)&image->gif.frame_image, GS_DYNAMIC); } else { - image->texture = gs_texture_create( - image->cx, image->cy, image->format, 1, - (const uint8_t **)&image->texture_data, 0); + image->texture = gs_texture_create(image->cx, image->cy, image->format, 1, + (const uint8_t **)&image->texture_data, 0); bfree(image->texture_data); image->texture_data = NULL; } @@ -310,8 +284,7 @@ static inline uint64_t get_time(gs_image_file_t *image, int i) return val; } -static inline int calculate_new_frame(gs_image_file_t *image, - uint64_t elapsed_time_ns, int loops) +static inline int calculate_new_frame(gs_image_file_t *image, uint64_t elapsed_time_ns, int loops) { int new_frame = image->cur_frame; @@ -335,16 +308,13 @@ static inline int calculate_new_frame(gs_image_file_t *image, return new_frame; } -static void decode_new_frame(gs_image_file_t *image, int new_frame, - enum gs_image_alpha_mode alpha_mode) +static void decode_new_frame(gs_image_file_t *image, int new_frame, enum gs_image_alpha_mode alpha_mode) { if (!image->animation_frame_cache[new_frame]) { int last_frame; /* if looped, decode frame 0 */ - last_frame = (new_frame < image->last_decoded_frame) - ? 0 - : image->last_decoded_frame + 1; + last_frame = (new_frame < image->last_decoded_frame) ? 0 : image->last_decoded_frame + 1; /* decode missed frames */ for (int i = last_frame; i < new_frame; i++) { @@ -354,22 +324,17 @@ static void decode_new_frame(gs_image_file_t *image, int new_frame, /* decode actual desired frame */ if (gif_decode_frame(&image->gif, new_frame) == GIF_OK) { - const size_t area = - (size_t)image->gif.width * image->gif.height; + const size_t area = (size_t)image->gif.width * image->gif.height; size_t pos = new_frame * area * 4; - image->animation_frame_cache[new_frame] = - image->animation_frame_data + pos; + image->animation_frame_cache[new_frame] = image->animation_frame_data + pos; if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY_SRGB) { - gs_premultiply_xyza_srgb_loop( - image->gif.frame_image, area); + gs_premultiply_xyza_srgb_loop(image->gif.frame_image, area); } else if (alpha_mode == GS_IMAGE_ALPHA_PREMULTIPLY) { - gs_premultiply_xyza_loop(image->gif.frame_image, - area); + gs_premultiply_xyza_loop(image->gif.frame_image, area); } - memcpy(image->animation_frame_cache[new_frame], - image->gif.frame_image, area * 4); + memcpy(image->animation_frame_cache[new_frame], image->gif.frame_image, area * 4); image->last_decoded_frame = new_frame; } @@ -378,8 +343,7 @@ static void decode_new_frame(gs_image_file_t *image, int new_frame, image->cur_frame = new_frame; } -static bool gs_image_file_tick_internal(gs_image_file_t *image, - uint64_t elapsed_time_ns, +static bool gs_image_file_tick_internal(gs_image_file_t *image, uint64_t elapsed_time_ns, enum gs_image_alpha_mode alpha_mode) { int loops; @@ -392,8 +356,7 @@ static bool gs_image_file_tick_internal(gs_image_file_t *image, loops = 0; if (!loops || image->cur_loop < loops) { - int new_frame = - calculate_new_frame(image, elapsed_time_ns, loops); + int new_frame = calculate_new_frame(image, elapsed_time_ns, loops); if (new_frame != image->cur_frame) { decode_new_frame(image, new_frame, alpha_mode); @@ -416,20 +379,15 @@ bool gs_image_file2_tick(gs_image_file2_t *if2, uint64_t elapsed_time_ns) bool gs_image_file3_tick(gs_image_file3_t *if3, uint64_t elapsed_time_ns) { - return gs_image_file_tick_internal(&if3->image2.image, elapsed_time_ns, - if3->alpha_mode); + return gs_image_file_tick_internal(&if3->image2.image, elapsed_time_ns, if3->alpha_mode); } bool gs_image_file4_tick(gs_image_file4_t *if4, uint64_t elapsed_time_ns) { - return gs_image_file_tick_internal(&if4->image3.image2.image, - elapsed_time_ns, - if4->image3.alpha_mode); + return gs_image_file_tick_internal(&if4->image3.image2.image, elapsed_time_ns, if4->image3.alpha_mode); } -static void -gs_image_file_update_texture_internal(gs_image_file_t *image, - enum gs_image_alpha_mode alpha_mode) +static void gs_image_file_update_texture_internal(gs_image_file_t *image, enum gs_image_alpha_mode alpha_mode) { if (!image->is_animated_gif || !image->loaded) return; @@ -437,9 +395,8 @@ gs_image_file_update_texture_internal(gs_image_file_t *image, if (!image->animation_frame_cache[image->cur_frame]) decode_new_frame(image, image->cur_frame, alpha_mode); - gs_texture_set_image(image->texture, - image->animation_frame_cache[image->cur_frame], - image->gif.width * 4, false); + gs_texture_set_image(image->texture, image->animation_frame_cache[image->cur_frame], image->gif.width * 4, + false); } void gs_image_file_update_texture(gs_image_file_t *image) @@ -454,12 +411,10 @@ void gs_image_file2_update_texture(gs_image_file2_t *if2) void gs_image_file3_update_texture(gs_image_file3_t *if3) { - gs_image_file_update_texture_internal(&if3->image2.image, - if3->alpha_mode); + gs_image_file_update_texture_internal(&if3->image2.image, if3->alpha_mode); } void gs_image_file4_update_texture(gs_image_file4_t *if4) { - gs_image_file_update_texture_internal(&if4->image3.image2.image, - if4->image3.alpha_mode); + gs_image_file_update_texture_internal(&if4->image3.image2.image, if4->image3.alpha_mode); } diff --git a/libobs/graphics/image-file.h b/libobs/graphics/image-file.h index 855a08ace..0353f0d13 100644 --- a/libobs/graphics/image-file.h +++ b/libobs/graphics/image-file.h @@ -70,28 +70,22 @@ EXPORT void gs_image_file_init(gs_image_file_t *image, const char *file); EXPORT void gs_image_file_free(gs_image_file_t *image); EXPORT void gs_image_file_init_texture(gs_image_file_t *image); -EXPORT bool gs_image_file_tick(gs_image_file_t *image, - uint64_t elapsed_time_ns); +EXPORT bool gs_image_file_tick(gs_image_file_t *image, uint64_t elapsed_time_ns); EXPORT void gs_image_file_update_texture(gs_image_file_t *image); EXPORT void gs_image_file2_init(gs_image_file2_t *if2, const char *file); -EXPORT bool gs_image_file2_tick(gs_image_file2_t *if2, - uint64_t elapsed_time_ns); +EXPORT bool gs_image_file2_tick(gs_image_file2_t *if2, uint64_t elapsed_time_ns); EXPORT void gs_image_file2_update_texture(gs_image_file2_t *if2); -EXPORT void gs_image_file3_init(gs_image_file3_t *if3, const char *file, - enum gs_image_alpha_mode alpha_mode); +EXPORT void gs_image_file3_init(gs_image_file3_t *if3, const char *file, enum gs_image_alpha_mode alpha_mode); -EXPORT bool gs_image_file3_tick(gs_image_file3_t *if3, - uint64_t elapsed_time_ns); +EXPORT bool gs_image_file3_tick(gs_image_file3_t *if3, uint64_t elapsed_time_ns); EXPORT void gs_image_file3_update_texture(gs_image_file3_t *if3); -EXPORT void gs_image_file4_init(gs_image_file4_t *if4, const char *file, - enum gs_image_alpha_mode alpha_mode); +EXPORT void gs_image_file4_init(gs_image_file4_t *if4, const char *file, enum gs_image_alpha_mode alpha_mode); -EXPORT bool gs_image_file4_tick(gs_image_file4_t *if4, - uint64_t elapsed_time_ns); +EXPORT bool gs_image_file4_tick(gs_image_file4_t *if4, uint64_t elapsed_time_ns); EXPORT void gs_image_file4_update_texture(gs_image_file4_t *if4); static inline void gs_image_file2_free(gs_image_file2_t *if2) diff --git a/libobs/graphics/math-extra.c b/libobs/graphics/math-extra.c index f9c41786e..36a1889e1 100644 --- a/libobs/graphics/math-extra.c +++ b/libobs/graphics/math-extra.c @@ -64,8 +64,7 @@ void polar_to_norm(struct vec3 *dst, const struct vec2 *polar) dst->z = cosf(polar->x); } -float calc_torquef(float val1, float val2, float torque, float min_adjust, - float t) +float calc_torquef(float val1, float val2, float torque, float min_adjust, float t) { float out = val1; float dist; @@ -94,8 +93,8 @@ float calc_torquef(float val1, float val2, float torque, float min_adjust, return out; } -void calc_torque(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2, - float torque, float min_adjust, float t) +void calc_torque(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2, float torque, float min_adjust, + float t) { struct vec3 line, dir; float orig_dist, torque_dist, adjust_dist; diff --git a/libobs/graphics/math-extra.h b/libobs/graphics/math-extra.h index 43c178df9..c363ed167 100644 --- a/libobs/graphics/math-extra.h +++ b/libobs/graphics/math-extra.h @@ -39,11 +39,9 @@ EXPORT void cart_to_polar(struct vec3 *dst, const struct vec3 *v); EXPORT void norm_to_polar(struct vec2 *dst, const struct vec3 *norm); EXPORT void polar_to_norm(struct vec3 *dst, const struct vec2 *polar); -EXPORT float calc_torquef(float val1, float val2, float torque, - float min_adjust, float t); +EXPORT float calc_torquef(float val1, float val2, float torque, float min_adjust, float t); -EXPORT void calc_torque(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2, float torque, float min_adjust, +EXPORT void calc_torque(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2, float torque, float min_adjust, float t); static inline float get_percentage(float start, float end, float mid) diff --git a/libobs/graphics/matrix3.c b/libobs/graphics/matrix3.c index 2fe5ea848..12fb078dd 100644 --- a/libobs/graphics/matrix3.c +++ b/libobs/graphics/matrix3.c @@ -61,8 +61,7 @@ void matrix3_from_matrix4(struct matrix3 *dst, const struct matrix4 *m) dst->t.w = 0.0f; } -void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, - const struct matrix3 *m2) +void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, const struct matrix3 *m2) { if (dst == m2) { struct matrix3 temp; @@ -79,24 +78,21 @@ void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, } } -void matrix3_rotate(struct matrix3 *dst, const struct matrix3 *m, - const struct quat *q) +void matrix3_rotate(struct matrix3 *dst, const struct matrix3 *m, const struct quat *q) { struct matrix3 temp; matrix3_from_quat(&temp, q); matrix3_mul(dst, m, &temp); } -void matrix3_rotate_aa(struct matrix3 *dst, const struct matrix3 *m, - const struct axisang *aa) +void matrix3_rotate_aa(struct matrix3 *dst, const struct matrix3 *m, const struct axisang *aa) { struct matrix3 temp; matrix3_from_axisang(&temp, aa); matrix3_mul(dst, m, &temp); } -void matrix3_scale(struct matrix3 *dst, const struct matrix3 *m, - const struct vec3 *v) +void matrix3_scale(struct matrix3 *dst, const struct matrix3 *m, const struct vec3 *v) { vec3_mul(&dst->x, &m->x, v); vec3_mul(&dst->y, &m->y, v); @@ -125,8 +121,7 @@ void matrix3_inv(struct matrix3 *dst, const struct matrix3 *m) dst->t.w = 0.0f; } -void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, - const struct plane *p) +void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, const struct plane *p) { vec3_mirrorv(&dst->x, &m->x, &p->dir); vec3_mirrorv(&dst->y, &m->y, &p->dir); @@ -134,8 +129,7 @@ void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, vec3_mirror(&dst->t, &m->t, p); } -void matrix3_mirrorv(struct matrix3 *dst, const struct matrix3 *m, - const struct vec3 *v) +void matrix3_mirrorv(struct matrix3 *dst, const struct matrix3 *m, const struct vec3 *v) { vec3_mirrorv(&dst->x, &m->x, v); vec3_mirrorv(&dst->y, &m->y, v); diff --git a/libobs/graphics/matrix3.h b/libobs/graphics/matrix3.h index eeb9c751e..9f4350cf5 100644 --- a/libobs/graphics/matrix3.h +++ b/libobs/graphics/matrix3.h @@ -56,49 +56,37 @@ EXPORT void matrix3_from_quat(struct matrix3 *dst, const struct quat *q); EXPORT void matrix3_from_axisang(struct matrix3 *dst, const struct axisang *aa); EXPORT void matrix3_from_matrix4(struct matrix3 *dst, const struct matrix4 *m); -EXPORT void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, - const struct matrix3 *m2); -static inline void matrix3_translate(struct matrix3 *dst, - const struct matrix3 *m, - const struct vec3 *v) +EXPORT void matrix3_mul(struct matrix3 *dst, const struct matrix3 *m1, const struct matrix3 *m2); +static inline void matrix3_translate(struct matrix3 *dst, const struct matrix3 *m, const struct vec3 *v) { vec3_sub(&dst->t, &m->t, v); } -EXPORT void matrix3_rotate(struct matrix3 *dst, const struct matrix3 *m, - const struct quat *q); -EXPORT void matrix3_rotate_aa(struct matrix3 *dst, const struct matrix3 *m, - const struct axisang *aa); -EXPORT void matrix3_scale(struct matrix3 *dst, const struct matrix3 *m, - const struct vec3 *v); +EXPORT void matrix3_rotate(struct matrix3 *dst, const struct matrix3 *m, const struct quat *q); +EXPORT void matrix3_rotate_aa(struct matrix3 *dst, const struct matrix3 *m, const struct axisang *aa); +EXPORT void matrix3_scale(struct matrix3 *dst, const struct matrix3 *m, const struct vec3 *v); EXPORT void matrix3_transpose(struct matrix3 *dst, const struct matrix3 *m); EXPORT void matrix3_inv(struct matrix3 *dst, const struct matrix3 *m); -EXPORT void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, - const struct plane *p); -EXPORT void matrix3_mirrorv(struct matrix3 *dst, const struct matrix3 *m, - const struct vec3 *v); +EXPORT void matrix3_mirror(struct matrix3 *dst, const struct matrix3 *m, const struct plane *p); +EXPORT void matrix3_mirrorv(struct matrix3 *dst, const struct matrix3 *m, const struct vec3 *v); -static inline void matrix3_translate3f(struct matrix3 *dst, - const struct matrix3 *m, float x, - float y, float z) +static inline void matrix3_translate3f(struct matrix3 *dst, const struct matrix3 *m, float x, float y, float z) { struct vec3 v; vec3_set(&v, x, y, z); matrix3_translate(dst, m, &v); } -static inline void matrix3_rotate_aa4f(struct matrix3 *dst, - const struct matrix3 *m, float x, - float y, float z, float rot) +static inline void matrix3_rotate_aa4f(struct matrix3 *dst, const struct matrix3 *m, float x, float y, float z, + float rot) { struct axisang aa; axisang_set(&aa, x, y, z, rot); matrix3_rotate_aa(dst, m, &aa); } -static inline void matrix3_scale3f(struct matrix3 *dst, const struct matrix3 *m, - float x, float y, float z) +static inline void matrix3_scale3f(struct matrix3 *dst, const struct matrix3 *m, float x, float y, float z) { struct vec3 v; vec3_set(&v, x, y, z); diff --git a/libobs/graphics/matrix4.c b/libobs/graphics/matrix4.c index 8cf4096a2..8168ecbce 100644 --- a/libobs/graphics/matrix4.c +++ b/libobs/graphics/matrix4.c @@ -57,8 +57,7 @@ void matrix4_from_axisang(struct matrix4 *dst, const struct axisang *aa) matrix4_from_quat(dst, &q); } -void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, - const struct matrix4 *m2) +void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, const struct matrix4 *m2) { const struct vec4 *m1v = (const struct vec4 *)m1; const float *m2f = (const float *)m2; @@ -68,8 +67,7 @@ void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, for (i = 0; i < 4; i++) { for (j = 0; j < 4; j++) { struct vec4 temp; - vec4_set(&temp, m2f[j], m2f[j + 4], m2f[j + 8], - m2f[j + 12]); + vec4_set(&temp, m2f[j], m2f[j + 4], m2f[j + 8], m2f[j + 12]); out[i].ptr[j] = vec4_dot(&m1v[i], &temp); } } @@ -77,8 +75,7 @@ void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, matrix4_copy(dst, (struct matrix4 *)out); } -static inline void get_3x3_submatrix(float *dst, const struct matrix4 *m, int i, - int j) +static inline void get_3x3_submatrix(float *dst, const struct matrix4 *m, int i, int j) { const float *mf = (const float *)m; int ti, tj, idst, jdst; @@ -106,8 +103,7 @@ static inline void get_3x3_submatrix(float *dst, const struct matrix4 *m, int i, static inline float get_3x3_determinant(const float *m) { - return (m[0] * ((m[4] * m[8]) - (m[7] * m[5]))) - - (m[1] * ((m[3] * m[8]) - (m[6] * m[5]))) + + return (m[0] * ((m[4] * m[8]) - (m[7] * m[5]))) - (m[1] * ((m[3] * m[8]) - (m[6] * m[5]))) + (m[2] * ((m[3] * m[7]) - (m[6] * m[4]))); } @@ -128,8 +124,7 @@ float matrix4_determinant(const struct matrix4 *m) return result; } -void matrix4_translate3v(struct matrix4 *dst, const struct matrix4 *m, - const struct vec3 *v) +void matrix4_translate3v(struct matrix4 *dst, const struct matrix4 *m, const struct vec3 *v) { struct matrix4 temp; vec4_set(&temp.x, 1.0f, 0.0f, 0.0f, 0.0f); @@ -140,8 +135,7 @@ void matrix4_translate3v(struct matrix4 *dst, const struct matrix4 *m, matrix4_mul(dst, m, &temp); } -void matrix4_translate4v(struct matrix4 *dst, const struct matrix4 *m, - const struct vec4 *v) +void matrix4_translate4v(struct matrix4 *dst, const struct matrix4 *m, const struct vec4 *v) { struct matrix4 temp; vec4_set(&temp.x, 1.0f, 0.0f, 0.0f, 0.0f); @@ -152,24 +146,21 @@ void matrix4_translate4v(struct matrix4 *dst, const struct matrix4 *m, matrix4_mul(dst, m, &temp); } -void matrix4_rotate(struct matrix4 *dst, const struct matrix4 *m, - const struct quat *q) +void matrix4_rotate(struct matrix4 *dst, const struct matrix4 *m, const struct quat *q) { struct matrix4 temp; matrix4_from_quat(&temp, q); matrix4_mul(dst, m, &temp); } -void matrix4_rotate_aa(struct matrix4 *dst, const struct matrix4 *m, - const struct axisang *aa) +void matrix4_rotate_aa(struct matrix4 *dst, const struct matrix4 *m, const struct axisang *aa) { struct matrix4 temp; matrix4_from_axisang(&temp, aa); matrix4_mul(dst, m, &temp); } -void matrix4_scale(struct matrix4 *dst, const struct matrix4 *m, - const struct vec3 *v) +void matrix4_scale(struct matrix4 *dst, const struct matrix4 *m, const struct vec3 *v) { struct matrix4 temp; vec4_set(&temp.x, v->x, 0.0f, 0.0f, 0.0f); @@ -179,8 +170,7 @@ void matrix4_scale(struct matrix4 *dst, const struct matrix4 *m, matrix4_mul(dst, m, &temp); } -void matrix4_translate3v_i(struct matrix4 *dst, const struct vec3 *v, - const struct matrix4 *m) +void matrix4_translate3v_i(struct matrix4 *dst, const struct vec3 *v, const struct matrix4 *m) { struct matrix4 temp; vec4_set(&temp.x, 1.0f, 0.0f, 0.0f, 0.0f); @@ -191,8 +181,7 @@ void matrix4_translate3v_i(struct matrix4 *dst, const struct vec3 *v, matrix4_mul(dst, &temp, m); } -void matrix4_translate4v_i(struct matrix4 *dst, const struct vec4 *v, - const struct matrix4 *m) +void matrix4_translate4v_i(struct matrix4 *dst, const struct vec4 *v, const struct matrix4 *m) { struct matrix4 temp; vec4_set(&temp.x, 1.0f, 0.0f, 0.0f, 0.0f); @@ -203,24 +192,21 @@ void matrix4_translate4v_i(struct matrix4 *dst, const struct vec4 *v, matrix4_mul(dst, &temp, m); } -void matrix4_rotate_i(struct matrix4 *dst, const struct quat *q, - const struct matrix4 *m) +void matrix4_rotate_i(struct matrix4 *dst, const struct quat *q, const struct matrix4 *m) { struct matrix4 temp; matrix4_from_quat(&temp, q); matrix4_mul(dst, &temp, m); } -void matrix4_rotate_aa_i(struct matrix4 *dst, const struct axisang *aa, - const struct matrix4 *m) +void matrix4_rotate_aa_i(struct matrix4 *dst, const struct axisang *aa, const struct matrix4 *m) { struct matrix4 temp; matrix4_from_axisang(&temp, aa); matrix4_mul(dst, &temp, m); } -void matrix4_scale_i(struct matrix4 *dst, const struct vec3 *v, - const struct matrix4 *m) +void matrix4_scale_i(struct matrix4 *dst, const struct vec3 *v, const struct matrix4 *m) { struct matrix4 temp; vec4_set(&temp.x, v->x, 0.0f, 0.0f, 0.0f); @@ -252,8 +238,7 @@ bool matrix4_inv(struct matrix4 *dst, const struct matrix4 *m) for (j = 0; j < 4; j++) { sign = 1 - ((i + j) % 2) * 2; get_3x3_submatrix(m3x3, m, i, j); - dstv[j].ptr[i] = - get_3x3_determinant(m3x3) * (float)sign / det; + dstv[j].ptr[i] = get_3x3_determinant(m3x3) * (float)sign / det; } } diff --git a/libobs/graphics/matrix4.h b/libobs/graphics/matrix4.h index fad8884d2..e28663527 100644 --- a/libobs/graphics/matrix4.h +++ b/libobs/graphics/matrix4.h @@ -57,55 +57,40 @@ EXPORT void matrix4_from_matrix3(struct matrix4 *dst, const struct matrix3 *m); EXPORT void matrix4_from_quat(struct matrix4 *dst, const struct quat *q); EXPORT void matrix4_from_axisang(struct matrix4 *dst, const struct axisang *aa); -EXPORT void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, - const struct matrix4 *m2); +EXPORT void matrix4_mul(struct matrix4 *dst, const struct matrix4 *m1, const struct matrix4 *m2); EXPORT float matrix4_determinant(const struct matrix4 *m); -EXPORT void matrix4_translate3v(struct matrix4 *dst, const struct matrix4 *m, - const struct vec3 *v); -EXPORT void matrix4_translate4v(struct matrix4 *dst, const struct matrix4 *m, - const struct vec4 *v); -EXPORT void matrix4_rotate(struct matrix4 *dst, const struct matrix4 *m, - const struct quat *q); -EXPORT void matrix4_rotate_aa(struct matrix4 *dst, const struct matrix4 *m, - const struct axisang *aa); -EXPORT void matrix4_scale(struct matrix4 *dst, const struct matrix4 *m, - const struct vec3 *v); +EXPORT void matrix4_translate3v(struct matrix4 *dst, const struct matrix4 *m, const struct vec3 *v); +EXPORT void matrix4_translate4v(struct matrix4 *dst, const struct matrix4 *m, const struct vec4 *v); +EXPORT void matrix4_rotate(struct matrix4 *dst, const struct matrix4 *m, const struct quat *q); +EXPORT void matrix4_rotate_aa(struct matrix4 *dst, const struct matrix4 *m, const struct axisang *aa); +EXPORT void matrix4_scale(struct matrix4 *dst, const struct matrix4 *m, const struct vec3 *v); EXPORT bool matrix4_inv(struct matrix4 *dst, const struct matrix4 *m); EXPORT void matrix4_transpose(struct matrix4 *dst, const struct matrix4 *m); -EXPORT void matrix4_translate3v_i(struct matrix4 *dst, const struct vec3 *v, - const struct matrix4 *m); -EXPORT void matrix4_translate4v_i(struct matrix4 *dst, const struct vec4 *v, - const struct matrix4 *m); -EXPORT void matrix4_rotate_i(struct matrix4 *dst, const struct quat *q, - const struct matrix4 *m); -EXPORT void matrix4_rotate_aa_i(struct matrix4 *dst, const struct axisang *aa, - const struct matrix4 *m); -EXPORT void matrix4_scale_i(struct matrix4 *dst, const struct vec3 *v, - const struct matrix4 *m); +EXPORT void matrix4_translate3v_i(struct matrix4 *dst, const struct vec3 *v, const struct matrix4 *m); +EXPORT void matrix4_translate4v_i(struct matrix4 *dst, const struct vec4 *v, const struct matrix4 *m); +EXPORT void matrix4_rotate_i(struct matrix4 *dst, const struct quat *q, const struct matrix4 *m); +EXPORT void matrix4_rotate_aa_i(struct matrix4 *dst, const struct axisang *aa, const struct matrix4 *m); +EXPORT void matrix4_scale_i(struct matrix4 *dst, const struct vec3 *v, const struct matrix4 *m); -static inline void matrix4_translate3f(struct matrix4 *dst, - const struct matrix4 *m, float x, - float y, float z) +static inline void matrix4_translate3f(struct matrix4 *dst, const struct matrix4 *m, float x, float y, float z) { struct vec3 v; vec3_set(&v, x, y, z); matrix4_translate3v(dst, m, &v); } -static inline void matrix4_rotate_aa4f(struct matrix4 *dst, - const struct matrix4 *m, float x, - float y, float z, float rot) +static inline void matrix4_rotate_aa4f(struct matrix4 *dst, const struct matrix4 *m, float x, float y, float z, + float rot) { struct axisang aa; axisang_set(&aa, x, y, z, rot); matrix4_rotate_aa(dst, m, &aa); } -static inline void matrix4_scale3f(struct matrix4 *dst, const struct matrix4 *m, - float x, float y, float z) +static inline void matrix4_scale3f(struct matrix4 *dst, const struct matrix4 *m, float x, float y, float z) { struct vec3 v; vec3_set(&v, x, y, z); diff --git a/libobs/graphics/plane.c b/libobs/graphics/plane.c index 926063a7d..08e3ecc31 100644 --- a/libobs/graphics/plane.c +++ b/libobs/graphics/plane.c @@ -19,8 +19,7 @@ #include "matrix3.h" #include "plane.h" -void plane_from_tri(struct plane *dst, const struct vec3 *v1, - const struct vec3 *v2, const struct vec3 *v3) +void plane_from_tri(struct plane *dst, const struct vec3 *v1, const struct vec3 *v2, const struct vec3 *v3) { struct vec3 temp; @@ -31,8 +30,7 @@ void plane_from_tri(struct plane *dst, const struct vec3 *v1, dst->dist = vec3_dot(v1, &dst->dir); } -void plane_transform(struct plane *dst, const struct plane *p, - const struct matrix4 *m) +void plane_transform(struct plane *dst, const struct plane *p, const struct matrix4 *m) { struct vec3 temp; @@ -45,8 +43,7 @@ void plane_transform(struct plane *dst, const struct plane *p, dst->dist = p->dist - vec3_dot(&dst->dir, &temp); } -void plane_transform3x4(struct plane *dst, const struct plane *p, - const struct matrix3 *m) +void plane_transform3x4(struct plane *dst, const struct plane *p, const struct matrix3 *m) { struct vec3 temp; @@ -57,8 +54,7 @@ void plane_transform3x4(struct plane *dst, const struct plane *p, dst->dist = p->dist - vec3_dot(&dst->dir, &temp); } -bool plane_intersection_ray(const struct plane *p, const struct vec3 *orig, - const struct vec3 *dir, float *t) +bool plane_intersection_ray(const struct plane *p, const struct vec3 *orig, const struct vec3 *dir, float *t) { float c = vec3_dot(&p->dir, dir); @@ -71,8 +67,7 @@ bool plane_intersection_ray(const struct plane *p, const struct vec3 *orig, } } -bool plane_intersection_line(const struct plane *p, const struct vec3 *v1, - const struct vec3 *v2, float *t) +bool plane_intersection_line(const struct plane *p, const struct vec3 *v1, const struct vec3 *v2, float *t) { float p1_dist, p2_dist, p1_abs_dist, dist2; bool p1_over, p2_over; @@ -106,8 +101,7 @@ bool plane_intersection_line(const struct plane *p, const struct vec3 *v1, return true; } -bool plane_tri_inside(const struct plane *p, const struct vec3 *v1, - const struct vec3 *v2, const struct vec3 *v3, +bool plane_tri_inside(const struct plane *p, const struct vec3 *v1, const struct vec3 *v2, const struct vec3 *v3, float precision) { /* bit 1: part or all is behind the plane */ @@ -135,8 +129,7 @@ bool plane_tri_inside(const struct plane *p, const struct vec3 *v1, return sides; } -bool plane_line_inside(const struct plane *p, const struct vec3 *v1, - const struct vec3 *v2, float precision) +bool plane_line_inside(const struct plane *p, const struct vec3 *v1, const struct vec3 *v2, float precision) { /* bit 1: part or all is behind the plane */ /* bit 2: part or all is in front of the plane */ diff --git a/libobs/graphics/plane.h b/libobs/graphics/plane.h index 74d05e90f..3ca564663 100644 --- a/libobs/graphics/plane.h +++ b/libobs/graphics/plane.h @@ -38,51 +38,37 @@ static inline void plane_copy(struct plane *dst, const struct plane *p) dst->dist = p->dist; } -static inline void plane_set(struct plane *dst, const struct vec3 *dir, - float dist) +static inline void plane_set(struct plane *dst, const struct vec3 *dir, float dist) { vec3_copy(&dst->dir, dir); dst->dist = dist; } -static inline void plane_setf(struct plane *dst, float a, float b, float c, - float d) +static inline void plane_setf(struct plane *dst, float a, float b, float c, float d) { vec3_set(&dst->dir, a, b, c); dst->dist = d; } -EXPORT void plane_from_tri(struct plane *dst, const struct vec3 *v1, - const struct vec3 *v2, const struct vec3 *v3); +EXPORT void plane_from_tri(struct plane *dst, const struct vec3 *v1, const struct vec3 *v2, const struct vec3 *v3); -EXPORT void plane_transform(struct plane *dst, const struct plane *p, - const struct matrix4 *m); -EXPORT void plane_transform3x4(struct plane *dst, const struct plane *p, - const struct matrix3 *m); +EXPORT void plane_transform(struct plane *dst, const struct plane *p, const struct matrix4 *m); +EXPORT void plane_transform3x4(struct plane *dst, const struct plane *p, const struct matrix3 *m); -EXPORT bool plane_intersection_ray(const struct plane *p, - const struct vec3 *orig, - const struct vec3 *dir, float *t); -EXPORT bool plane_intersection_line(const struct plane *p, - const struct vec3 *v1, - const struct vec3 *v2, float *t); +EXPORT bool plane_intersection_ray(const struct plane *p, const struct vec3 *orig, const struct vec3 *dir, float *t); +EXPORT bool plane_intersection_line(const struct plane *p, const struct vec3 *v1, const struct vec3 *v2, float *t); -EXPORT bool plane_tri_inside(const struct plane *p, const struct vec3 *v1, - const struct vec3 *v2, const struct vec3 *v3, +EXPORT bool plane_tri_inside(const struct plane *p, const struct vec3 *v1, const struct vec3 *v2, const struct vec3 *v3, float precision); -EXPORT bool plane_line_inside(const struct plane *p, const struct vec3 *v1, - const struct vec3 *v2, float precision); +EXPORT bool plane_line_inside(const struct plane *p, const struct vec3 *v1, const struct vec3 *v2, float precision); -static inline bool plane_close(const struct plane *p1, const struct plane *p2, - float precision) +static inline bool plane_close(const struct plane *p1, const struct plane *p2, float precision) { - return vec3_close(&p1->dir, &p2->dir, precision) && - close_float(p1->dist, p2->dist, precision); + return vec3_close(&p1->dir, &p2->dir, precision) && close_float(p1->dist, p2->dist, precision); } -static inline bool plane_coplanar(const struct plane *p1, - const struct plane *p2, float precision) +static inline bool plane_coplanar(const struct plane *p1, const struct plane *p2, float precision) { float cos_angle = vec3_dot(&p1->dir, &p2->dir); diff --git a/libobs/graphics/quat.c b/libobs/graphics/quat.c index 47ee1266d..f5ffc9f27 100644 --- a/libobs/graphics/quat.c +++ b/libobs/graphics/quat.c @@ -92,9 +92,7 @@ void quat_from_matrix4(struct quat *dst, const struct matrix4 *m) /* ---------------------------------- */ - four_d = sqrtf( - (val->ptr[i][i] - val->ptr[j][j] - val->ptr[k][k]) + - 1.0f); + four_d = sqrtf((val->ptr[i][i] - val->ptr[j][j] - val->ptr[k][k]) + 1.0f); dst->ptr[i] = four_d * 0.5f; @@ -126,13 +124,11 @@ void quat_set_look_dir(struct quat *dst, const struct vec3 *dir) quat_identity(&xz_rot); quat_identity(&yz_rot); - xz_valid = close_float(new_dir.x, 0.0f, EPSILON) || - close_float(new_dir.z, 0.0f, EPSILON); + xz_valid = close_float(new_dir.x, 0.0f, EPSILON) || close_float(new_dir.z, 0.0f, EPSILON); yz_valid = close_float(new_dir.y, 0.0f, EPSILON); if (xz_valid) { - axisang_set(&aa, 0.0f, 1.0f, 0.0f, - atan2f(new_dir.x, new_dir.z)); + axisang_set(&aa, 0.0f, 1.0f, 0.0f, atan2f(new_dir.x, new_dir.z)); quat_from_axisang(&xz_rot, &aa); } @@ -175,8 +171,7 @@ void quat_exp(struct quat *dst, const struct quat *q) dst->w = cosf(length); } -void quat_interpolate(struct quat *dst, const struct quat *q1, - const struct quat *q2, float t) +void quat_interpolate(struct quat *dst, const struct quat *q1, const struct quat *q2, float t) { float dot = quat_dot(q1, q2); float anglef = acosf(dot); @@ -199,8 +194,7 @@ void quat_interpolate(struct quat *dst, const struct quat *q1, } } -void quat_get_tangent(struct quat *dst, const struct quat *prev, - const struct quat *q, const struct quat *next) +void quat_get_tangent(struct quat *dst, const struct quat *prev, const struct quat *q, const struct quat *next) { struct quat temp; @@ -210,8 +204,7 @@ void quat_get_tangent(struct quat *dst, const struct quat *prev, quat_mulf(dst, &temp, 0.5f); } -void quat_interpolate_cubic(struct quat *dst, const struct quat *q1, - const struct quat *q2, const struct quat *m1, +void quat_interpolate_cubic(struct quat *dst, const struct quat *q1, const struct quat *q2, const struct quat *m1, const struct quat *m2, float t) { struct quat temp1, temp2; diff --git a/libobs/graphics/quat.h b/libobs/graphics/quat.h index 3cf237987..2dabfd9e4 100644 --- a/libobs/graphics/quat.h +++ b/libobs/graphics/quat.h @@ -55,8 +55,7 @@ static inline void quat_identity(struct quat *q) q->w = 1.0f; } -static inline void quat_set(struct quat *dst, float x, float y, float z, - float w) +static inline void quat_set(struct quat *dst, float x, float y, float z, float w) { dst->m = _mm_set_ps(x, y, z, w); } @@ -66,20 +65,17 @@ static inline void quat_copy(struct quat *dst, const struct quat *q) dst->m = q->m; } -static inline void quat_add(struct quat *dst, const struct quat *q1, - const struct quat *q2) +static inline void quat_add(struct quat *dst, const struct quat *q1, const struct quat *q2) { dst->m = _mm_add_ps(q1->m, q2->m); } -static inline void quat_sub(struct quat *dst, const struct quat *q1, - const struct quat *q2) +static inline void quat_sub(struct quat *dst, const struct quat *q1, const struct quat *q2) { dst->m = _mm_sub_ps(q1->m, q2->m); } -EXPORT void quat_mul(struct quat *dst, const struct quat *q1, - const struct quat *q2); +EXPORT void quat_mul(struct quat *dst, const struct quat *q1, const struct quat *q2); static inline void quat_addf(struct quat *dst, const struct quat *q, float f) { @@ -144,18 +140,14 @@ static inline float quat_dist(const struct quat *q1, const struct quat *q2) static inline void quat_norm(struct quat *dst, const struct quat *q) { float dot_val = quat_dot(q, q); - dst->m = (dot_val > 0.0f) - ? _mm_mul_ps(q->m, _mm_set1_ps(1.0f / sqrtf(dot_val))) - : _mm_setzero_ps(); + dst->m = (dot_val > 0.0f) ? _mm_mul_ps(q->m, _mm_set1_ps(1.0f / sqrtf(dot_val))) : _mm_setzero_ps(); } -static inline bool quat_close(const struct quat *q1, const struct quat *q2, - float epsilon) +static inline bool quat_close(const struct quat *q1, const struct quat *q2, float epsilon) { struct quat test; quat_sub(&test, q1, q2); - return test.x < epsilon && test.y < epsilon && test.z < epsilon && - test.w < epsilon; + return test.x < epsilon && test.y < epsilon && test.z < epsilon && test.w < epsilon; } EXPORT void quat_from_axisang(struct quat *dst, const struct axisang *aa); @@ -168,13 +160,10 @@ EXPORT void quat_set_look_dir(struct quat *dst, const struct vec3 *dir); EXPORT void quat_log(struct quat *dst, const struct quat *q); EXPORT void quat_exp(struct quat *dst, const struct quat *q); -EXPORT void quat_interpolate(struct quat *dst, const struct quat *q1, - const struct quat *q2, float t); -EXPORT void quat_get_tangent(struct quat *dst, const struct quat *prev, - const struct quat *q, const struct quat *next); -EXPORT void quat_interpolate_cubic(struct quat *dst, const struct quat *q1, - const struct quat *q2, const struct quat *m1, - const struct quat *m2, float t); +EXPORT void quat_interpolate(struct quat *dst, const struct quat *q1, const struct quat *q2, float t); +EXPORT void quat_get_tangent(struct quat *dst, const struct quat *prev, const struct quat *q, const struct quat *next); +EXPORT void quat_interpolate_cubic(struct quat *dst, const struct quat *q1, const struct quat *q2, + const struct quat *m1, const struct quat *m2, float t); #ifdef __cplusplus } diff --git a/libobs/graphics/shader-parser.c b/libobs/graphics/shader-parser.c index 23d7add64..75a06a27d 100644 --- a/libobs/graphics/shader-parser.c +++ b/libobs/graphics/shader-parser.c @@ -53,12 +53,10 @@ enum gs_sample_filter get_sample_filter(const char *filter) if (astrcmpi(filter, "Anisotropy") == 0) return GS_FILTER_ANISOTROPIC; - else if (astrcmpi(filter, "Point") == 0 || - strcmp(filter, "MIN_MAG_MIP_POINT") == 0) + else if (astrcmpi(filter, "Point") == 0 || strcmp(filter, "MIN_MAG_MIP_POINT") == 0) return GS_FILTER_POINT; - else if (astrcmpi(filter, "Linear") == 0 || - strcmp(filter, "MIN_MAG_MIP_LINEAR") == 0) + else if (astrcmpi(filter, "Linear") == 0 || strcmp(filter, "MIN_MAG_MIP_LINEAR") == 0) return GS_FILTER_LINEAR; else if (strcmp(filter, "MIN_MAG_POINT_MIP_LINEAR") == 0) @@ -98,8 +96,7 @@ extern enum gs_address_mode get_address_mode(const char *mode) return GS_ADDRESS_CLAMP; } -void shader_sampler_convert(struct shader_sampler *ss, - struct gs_sampler_info *info) +void shader_sampler_convert(struct shader_sampler *ss, struct gs_sampler_info *info) { size_t i; memset(info, 0, sizeof(struct gs_sampler_info)); @@ -127,8 +124,7 @@ void shader_sampler_convert(struct shader_sampler *ss, /* ------------------------------------------------------------------------- */ -static int sp_parse_sampler_state_item(struct shader_parser *sp, - struct shader_sampler *ss) +static int sp_parse_sampler_state_item(struct shader_parser *sp, struct shader_sampler *ss) { int ret; char *state = NULL, *value = NULL; @@ -194,8 +190,7 @@ error: shader_sampler_free(&ss); } -static inline int sp_parse_struct_var(struct shader_parser *sp, - struct shader_var *var) +static inline int sp_parse_struct_var(struct shader_parser *sp, struct shader_var *var) { int code; @@ -248,8 +243,7 @@ static inline int sp_parse_struct_var(struct shader_parser *sp, if (cf_token_is(&sp->cfp, "}")) return PARSE_UNEXPECTED_BREAK; - code = cf_token_is_type(&sp->cfp, CFTOKEN_NAME, "mapping name", - ";"); + code = cf_token_is_type(&sp->cfp, CFTOKEN_NAME, "mapping name", ";"); if (code != PARSE_SUCCESS) return code; @@ -325,8 +319,7 @@ error: shader_struct_free(&ss); } -static inline int sp_check_for_keyword(struct shader_parser *sp, - const char *keyword, bool *val) +static inline int sp_check_for_keyword(struct shader_parser *sp, const char *keyword, bool *val) { bool new_val = cf_token_is(&sp->cfp, keyword); if (new_val) { @@ -334,8 +327,7 @@ static inline int sp_check_for_keyword(struct shader_parser *sp, return PARSE_EOF; if (new_val && *val) - cf_adderror(&sp->cfp, "'$1' keyword already specified", - LEX_WARNING, keyword, NULL, NULL); + cf_adderror(&sp->cfp, "'$1' keyword already specified", LEX_WARNING, keyword, NULL, NULL); *val = new_val; return PARSE_CONTINUE; @@ -344,8 +336,7 @@ static inline int sp_check_for_keyword(struct shader_parser *sp, return PARSE_SUCCESS; } -static inline int sp_parse_func_param(struct shader_parser *sp, - struct shader_var *var) +static inline int sp_parse_func_param(struct shader_parser *sp, struct shader_var *var) { int code; bool var_type_keyword = false; @@ -395,8 +386,7 @@ static inline int sp_parse_func_param(struct shader_parser *sp, return PARSE_EOF; if (cf_token_is(&sp->cfp, ":")) { - code = cf_next_name(&sp->cfp, &var->mapping, - "mapping specifier", ")"); + code = cf_next_name(&sp->cfp, &var->mapping, "mapping specifier", ")"); if (code != PARSE_SUCCESS) return code; @@ -407,8 +397,7 @@ static inline int sp_parse_func_param(struct shader_parser *sp, return PARSE_SUCCESS; } -static bool sp_parse_func_params(struct shader_parser *sp, - struct shader_func *func) +static bool sp_parse_func_params(struct shader_parser *sp, struct shader_func *func) { struct cf_token peek; int code; @@ -461,8 +450,7 @@ static void sp_parse_function(struct shader_parser *sp, char *type, char *name) /* if function is mapped to something, for example COLOR */ if (cf_token_is(&sp->cfp, ":")) { char *mapping = NULL; - int errorcode = - cf_next_name(&sp->cfp, &mapping, "mapping", "{"); + int errorcode = cf_next_name(&sp->cfp, &mapping, "mapping", "{"); if (errorcode != PARSE_SUCCESS) goto error; @@ -493,19 +481,16 @@ error: } /* parses "array[count]" */ -static bool sp_parse_param_array(struct shader_parser *sp, - struct shader_var *param) +static bool sp_parse_param_array(struct shader_parser *sp, struct shader_var *param) { if (!cf_next_valid_token(&sp->cfp)) return false; if (sp->cfp.cur_token->type != CFTOKEN_NUM || - !valid_int_str(sp->cfp.cur_token->str.array, - sp->cfp.cur_token->str.len)) + !valid_int_str(sp->cfp.cur_token->str.array, sp->cfp.cur_token->str.len)) return false; - param->array_count = - (int)strtol(sp->cfp.cur_token->str.array, NULL, 10); + param->array_count = (int)strtol(sp->cfp.cur_token->str.array, NULL, 10); if (cf_next_token_should_be(&sp->cfp, "]", ";", NULL) == PARSE_EOF) return false; @@ -516,9 +501,7 @@ static bool sp_parse_param_array(struct shader_parser *sp, return true; } -static inline int sp_parse_param_assign_intfloat(struct shader_parser *sp, - struct shader_var *param, - bool is_float) +static inline int sp_parse_param_assign_intfloat(struct shader_parser *sp, struct shader_var *param, bool is_float) { int code; bool is_negative = false; @@ -541,14 +524,12 @@ static inline int sp_parse_param_assign_intfloat(struct shader_parser *sp, float f = (float)os_strtod(sp->cfp.cur_token->str.array); if (is_negative) f = -f; - da_push_back_array(param->default_val, (uint8_t *)&f, - sizeof(float)); + da_push_back_array(param->default_val, (uint8_t *)&f, sizeof(float)); } else { long l = strtol(sp->cfp.cur_token->str.array, NULL, 10); if (is_negative) l = -l; - da_push_back_array(param->default_val, (uint8_t *)&l, - sizeof(long)); + da_push_back_array(param->default_val, (uint8_t *)&l, sizeof(long)); } return PARSE_SUCCESS; @@ -558,8 +539,7 @@ static inline int sp_parse_param_assign_intfloat(struct shader_parser *sp, * parses assignment for float1, float2, float3, float4, and any combination * for float3x3, float4x4, etc */ -static inline int sp_parse_param_assign_float_array(struct shader_parser *sp, - struct shader_var *param) +static inline int sp_parse_param_assign_float_array(struct shader_parser *sp, struct shader_var *param) { const char *float_type = param->type + 5; int float_count = 0, code, i; @@ -567,15 +547,13 @@ static inline int sp_parse_param_assign_float_array(struct shader_parser *sp, /* -------------------------------------------- */ if (float_type[0] < '1' || float_type[0] > '4') - cf_adderror(&sp->cfp, "Invalid row count", LEX_ERROR, NULL, - NULL, NULL); + cf_adderror(&sp->cfp, "Invalid row count", LEX_ERROR, NULL, NULL, NULL); float_count = float_type[0] - '0'; if (float_type[1] == 'x') { if (float_type[2] < '1' || float_type[2] > '4') - cf_adderror(&sp->cfp, "Invalid column count", LEX_ERROR, - NULL, NULL, NULL); + cf_adderror(&sp->cfp, "Invalid column count", LEX_ERROR, NULL, NULL, NULL); float_count *= float_type[2] - '0'; } @@ -601,8 +579,7 @@ static inline int sp_parse_param_assign_float_array(struct shader_parser *sp, return PARSE_SUCCESS; } -static int sp_parse_param_assignment_val(struct shader_parser *sp, - struct shader_var *param) +static int sp_parse_param_assignment_val(struct shader_parser *sp, struct shader_var *param) { if (strcmp(param->type, "int") == 0) return sp_parse_param_assign_intfloat(sp, param, false); @@ -611,14 +588,12 @@ static int sp_parse_param_assignment_val(struct shader_parser *sp, else if (astrcmp_n(param->type, "float", 5) == 0) return sp_parse_param_assign_float_array(sp, param); - cf_adderror(&sp->cfp, "Invalid type '$1' used for assignment", - LEX_ERROR, param->type, NULL, NULL); + cf_adderror(&sp->cfp, "Invalid type '$1' used for assignment", LEX_ERROR, param->type, NULL, NULL); return PARSE_CONTINUE; } -static inline bool sp_parse_param_assign(struct shader_parser *sp, - struct shader_var *param) +static inline bool sp_parse_param_assign(struct shader_parser *sp, struct shader_var *param) { if (sp_parse_param_assignment_val(sp, param) != PARSE_SUCCESS) return false; @@ -629,8 +604,7 @@ static inline bool sp_parse_param_assign(struct shader_parser *sp, return true; } -static void sp_parse_param(struct shader_parser *sp, char *type, char *name, - bool is_const, bool is_uniform) +static void sp_parse_param(struct shader_parser *sp, char *type, char *name, bool is_const, bool is_uniform) { struct shader_var param; shader_var_init_param(¶m, type, name, is_uniform, is_const); @@ -652,8 +626,7 @@ error: shader_var_free(¶m); } -static bool sp_get_var_specifiers(struct shader_parser *sp, bool *is_const, - bool *is_uniform) +static bool sp_get_var_specifiers(struct shader_parser *sp, bool *is_const, bool *is_uniform) { while (true) { int code = sp_check_for_keyword(sp, "const", is_const); @@ -674,8 +647,7 @@ static bool sp_get_var_specifiers(struct shader_parser *sp, bool *is_const, return true; } -static inline void report_invalid_func_keyword(struct shader_parser *sp, - const char *name, bool val) +static inline void report_invalid_func_keyword(struct shader_parser *sp, const char *name, bool val) { if (val) cf_adderror(&sp->cfp, @@ -716,15 +688,13 @@ error: bfree(name); } -bool shader_parse(struct shader_parser *sp, const char *shader, - const char *file) +bool shader_parse(struct shader_parser *sp, const char *shader, const char *file) { if (!cf_parser_parse(&sp->cfp, shader, file)) return false; while (sp->cfp.cur_token && sp->cfp.cur_token->type != CFTOKEN_NONE) { - if (cf_token_is(&sp->cfp, ";") || - is_whitespace(*sp->cfp.cur_token->str.array)) { + if (cf_token_is(&sp->cfp, ";") || is_whitespace(*sp->cfp.cur_token->str.array)) { sp->cfp.cur_token++; } else if (cf_token_is(&sp->cfp, "struct")) { @@ -734,8 +704,7 @@ bool shader_parse(struct shader_parser *sp, const char *shader, sp_parse_sampler_state(sp); } else if (cf_token_is(&sp->cfp, "{")) { - cf_adderror(&sp->cfp, "Unexpected code segment", - LEX_ERROR, NULL, NULL, NULL); + cf_adderror(&sp->cfp, "Unexpected code segment", LEX_ERROR, NULL, NULL, NULL); cf_pass_pair(&sp->cfp, '{', '}'); } else { diff --git a/libobs/graphics/shader-parser.h b/libobs/graphics/shader-parser.h index 1069628b2..7a19f6557 100644 --- a/libobs/graphics/shader-parser.h +++ b/libobs/graphics/shader-parser.h @@ -61,9 +61,7 @@ static inline void shader_var_init(struct shader_var *sv) memset(sv, 0, sizeof(struct shader_var)); } -static inline void shader_var_init_param(struct shader_var *sv, char *type, - char *name, bool is_uniform, - bool is_const) +static inline void shader_var_init_param(struct shader_var *sv, char *type, char *name, bool is_uniform, bool is_const) { if (is_uniform) sv->var_type = SHADER_VAR_UNIFORM; @@ -114,8 +112,7 @@ static inline void shader_sampler_free(struct shader_sampler *ss) da_free(ss->values); } -EXPORT void shader_sampler_convert(struct shader_sampler *ss, - struct gs_sampler_info *info); +EXPORT void shader_sampler_convert(struct shader_sampler *ss, struct gs_sampler_info *info); /* ------------------------------------------------------------------------- */ @@ -151,8 +148,7 @@ struct shader_func { struct cf_token *start, *end; }; -static inline void shader_func_init(struct shader_func *sf, char *return_type, - char *name) +static inline void shader_func_init(struct shader_func *sf, char *return_type, char *name) { da_init(sf->params); @@ -217,16 +213,14 @@ static inline void shader_parser_free(struct shader_parser *sp) da_free(sp->funcs); } -EXPORT bool shader_parse(struct shader_parser *sp, const char *shader, - const char *file); +EXPORT bool shader_parse(struct shader_parser *sp, const char *shader, const char *file); static inline char *shader_parser_geterrors(struct shader_parser *sp) { return error_data_buildstring(&sp->cfp.error_list); } -static inline struct shader_var * -shader_parser_getparam(struct shader_parser *sp, const char *param_name) +static inline struct shader_var *shader_parser_getparam(struct shader_parser *sp, const char *param_name) { size_t i; for (i = 0; i < sp->params.num; i++) { @@ -238,8 +232,7 @@ shader_parser_getparam(struct shader_parser *sp, const char *param_name) return NULL; } -static inline struct shader_struct * -shader_parser_getstruct(struct shader_parser *sp, const char *struct_name) +static inline struct shader_struct *shader_parser_getstruct(struct shader_parser *sp, const char *struct_name) { size_t i; for (i = 0; i < sp->structs.num; i++) { @@ -251,8 +244,7 @@ shader_parser_getstruct(struct shader_parser *sp, const char *struct_name) return NULL; } -static inline struct shader_sampler * -shader_parser_getsampler(struct shader_parser *sp, const char *sampler_name) +static inline struct shader_sampler *shader_parser_getsampler(struct shader_parser *sp, const char *sampler_name) { size_t i; for (i = 0; i < sp->samplers.num; i++) { @@ -264,8 +256,7 @@ shader_parser_getsampler(struct shader_parser *sp, const char *sampler_name) return NULL; } -static inline struct shader_func * -shader_parser_getfunc(struct shader_parser *sp, const char *func_name) +static inline struct shader_func *shader_parser_getfunc(struct shader_parser *sp, const char *func_name) { size_t i; for (i = 0; i < sp->funcs.num; i++) { diff --git a/libobs/graphics/srgb.h b/libobs/graphics/srgb.h index a4050a58a..06651594d 100644 --- a/libobs/graphics/srgb.h +++ b/libobs/graphics/srgb.h @@ -26,14 +26,12 @@ extern "C" { static inline float gs_srgb_nonlinear_to_linear(float u) { - return (u <= 0.04045f) ? (u / 12.92f) - : powf((u + 0.055f) / 1.055f, 2.4f); + return (u <= 0.04045f) ? (u / 12.92f) : powf((u + 0.055f) / 1.055f, 2.4f); } static inline float gs_srgb_linear_to_nonlinear(float u) { - return (u <= 0.0031308f) ? (12.92f * u) - : ((1.055f * powf(u, 1.0f / 2.4f)) - 0.055f); + return (u <= 0.0031308f) ? (12.92f * u) : ((1.055f * powf(u, 1.0f / 2.4f)) - 0.055f); } static inline float gs_u8_to_float(uint8_t u) @@ -114,8 +112,7 @@ static inline void gs_premultiply_xyza_srgb(uint8_t *data) memcpy(data, &u, sizeof(u)); } -static inline void gs_premultiply_xyza_restrict(uint8_t *__restrict dst, - const uint8_t *__restrict src) +static inline void gs_premultiply_xyza_restrict(uint8_t *__restrict dst, const uint8_t *__restrict src) { uint8_t u[4]; float f[4]; @@ -126,9 +123,7 @@ static inline void gs_premultiply_xyza_restrict(uint8_t *__restrict dst, memcpy(dst, &u, sizeof(u)); } -static inline void -gs_premultiply_xyza_srgb_restrict(uint8_t *__restrict dst, - const uint8_t *__restrict src) +static inline void gs_premultiply_xyza_srgb_restrict(uint8_t *__restrict dst, const uint8_t *__restrict src) { uint8_t u[4]; float f[4]; @@ -149,8 +144,7 @@ static inline void gs_premultiply_xyza_loop(uint8_t *data, size_t texel_count) } } -static inline void gs_premultiply_xyza_srgb_loop(uint8_t *data, - size_t texel_count) +static inline void gs_premultiply_xyza_srgb_loop(uint8_t *data, size_t texel_count) { for (size_t i = 0; i < texel_count; ++i) { gs_premultiply_xyza_srgb(data); @@ -158,10 +152,8 @@ static inline void gs_premultiply_xyza_srgb_loop(uint8_t *data, } } -static inline void -gs_premultiply_xyza_loop_restrict(uint8_t *__restrict dst, - const uint8_t *__restrict src, - size_t texel_count) +static inline void gs_premultiply_xyza_loop_restrict(uint8_t *__restrict dst, const uint8_t *__restrict src, + size_t texel_count) { for (size_t i = 0; i < texel_count; ++i) { gs_premultiply_xyza_restrict(dst, src); @@ -170,10 +162,8 @@ gs_premultiply_xyza_loop_restrict(uint8_t *__restrict dst, } } -static inline void -gs_premultiply_xyza_srgb_loop_restrict(uint8_t *__restrict dst, - const uint8_t *__restrict src, - size_t texel_count) +static inline void gs_premultiply_xyza_srgb_loop_restrict(uint8_t *__restrict dst, const uint8_t *__restrict src, + size_t texel_count) { for (size_t i = 0; i < texel_count; ++i) { gs_premultiply_xyza_srgb_restrict(dst, src); diff --git a/libobs/graphics/texture-render.c b/libobs/graphics/texture-render.c index cd7eac5d1..d467e12c1 100644 --- a/libobs/graphics/texture-render.c +++ b/libobs/graphics/texture-render.c @@ -36,8 +36,7 @@ struct gs_texture_render { bool rendered; }; -gs_texrender_t *gs_texrender_create(enum gs_color_format format, - enum gs_zstencil_format zsformat) +gs_texrender_t *gs_texrender_create(enum gs_color_format format, enum gs_zstencil_format zsformat) { struct gs_texture_render *texrender; texrender = bzalloc(sizeof(struct gs_texture_render)); @@ -56,8 +55,7 @@ void gs_texrender_destroy(gs_texrender_t *texrender) } } -static bool texrender_resetbuffer(gs_texrender_t *texrender, uint32_t cx, - uint32_t cy) +static bool texrender_resetbuffer(gs_texrender_t *texrender, uint32_t cx, uint32_t cy) { if (!texrender) return false; @@ -70,8 +68,7 @@ static bool texrender_resetbuffer(gs_texrender_t *texrender, uint32_t cx, texrender->cx = cx; texrender->cy = cy; - texrender->target = gs_texture_create(cx, cy, texrender->format, 1, - NULL, GS_RENDER_TARGET); + texrender->target = gs_texture_create(cx, cy, texrender->format, 1, NULL, GS_RENDER_TARGET); if (!texrender->target) return false; @@ -90,12 +87,10 @@ static bool texrender_resetbuffer(gs_texrender_t *texrender, uint32_t cx, bool gs_texrender_begin(gs_texrender_t *texrender, uint32_t cx, uint32_t cy) { - return gs_texrender_begin_with_color_space(texrender, cx, cy, - GS_CS_SRGB); + return gs_texrender_begin_with_color_space(texrender, cx, cy, GS_CS_SRGB); } -bool gs_texrender_begin_with_color_space(gs_texrender_t *texrender, uint32_t cx, - uint32_t cy, enum gs_color_space space) +bool gs_texrender_begin_with_color_space(gs_texrender_t *texrender, uint32_t cx, uint32_t cy, enum gs_color_space space) { if (!texrender || texrender->rendered) return false; @@ -118,8 +113,7 @@ bool gs_texrender_begin_with_color_space(gs_texrender_t *texrender, uint32_t cx, texrender->prev_target = gs_get_render_target(); texrender->prev_zs = gs_get_zstencil_target(); texrender->prev_space = gs_get_color_space(); - gs_set_render_target_with_color_space(texrender->target, texrender->zs, - space); + gs_set_render_target_with_color_space(texrender->target, texrender->zs, space); gs_set_viewport(0, 0, texrender->cx, texrender->cy); @@ -131,9 +125,7 @@ void gs_texrender_end(gs_texrender_t *texrender) if (!texrender) return; - gs_set_render_target_with_color_space(texrender->prev_target, - texrender->prev_zs, - texrender->prev_space); + gs_set_render_target_with_color_space(texrender->prev_target, texrender->prev_zs, texrender->prev_space); gs_matrix_pop(); gs_projection_pop(); diff --git a/libobs/graphics/vec2.c b/libobs/graphics/vec2.c index 06dc466cf..14b1863da 100644 --- a/libobs/graphics/vec2.c +++ b/libobs/graphics/vec2.c @@ -37,8 +37,7 @@ void vec2_ceil(struct vec2 *dst, const struct vec2 *v) int vec2_close(const struct vec2 *v1, const struct vec2 *v2, float epsilon) { - return close_float(v1->x, v2->x, epsilon) && - close_float(v1->y, v2->y, epsilon); + return close_float(v1->x, v2->x, epsilon) && close_float(v1->y, v2->y, epsilon); } void vec2_norm(struct vec2 *dst, const struct vec2 *v) diff --git a/libobs/graphics/vec2.h b/libobs/graphics/vec2.h index a845c31f1..44f5e84d9 100644 --- a/libobs/graphics/vec2.h +++ b/libobs/graphics/vec2.h @@ -51,26 +51,22 @@ static inline void vec2_copy(struct vec2 *dst, const struct vec2 *v) dst->y = v->y; } -static inline void vec2_add(struct vec2 *dst, const struct vec2 *v1, - const struct vec2 *v2) +static inline void vec2_add(struct vec2 *dst, const struct vec2 *v1, const struct vec2 *v2) { vec2_set(dst, v1->x + v2->x, v1->y + v2->y); } -static inline void vec2_sub(struct vec2 *dst, const struct vec2 *v1, - const struct vec2 *v2) +static inline void vec2_sub(struct vec2 *dst, const struct vec2 *v1, const struct vec2 *v2) { vec2_set(dst, v1->x - v2->x, v1->y - v2->y); } -static inline void vec2_mul(struct vec2 *dst, const struct vec2 *v1, - const struct vec2 *v2) +static inline void vec2_mul(struct vec2 *dst, const struct vec2 *v1, const struct vec2 *v2) { vec2_set(dst, v1->x * v2->x, v1->y * v2->y); } -static inline void vec2_div(struct vec2 *dst, const struct vec2 *v1, - const struct vec2 *v2) +static inline void vec2_div(struct vec2 *dst, const struct vec2 *v1, const struct vec2 *v2) { vec2_set(dst, v1->x / v2->x, v1->y / v2->y); } @@ -123,8 +119,7 @@ static inline void vec2_minf(struct vec2 *dst, const struct vec2 *v, float val) dst->y = (v->y < val) ? v->y : val; } -static inline void vec2_min(struct vec2 *dst, const struct vec2 *v, - const struct vec2 *min_v) +static inline void vec2_min(struct vec2 *dst, const struct vec2 *v, const struct vec2 *min_v) { dst->x = (v->x < min_v->x) ? v->x : min_v->x; dst->y = (v->y < min_v->y) ? v->y : min_v->y; @@ -136,8 +131,7 @@ static inline void vec2_maxf(struct vec2 *dst, const struct vec2 *v, float val) dst->y = (v->y > val) ? v->y : val; } -static inline void vec2_max(struct vec2 *dst, const struct vec2 *v, - const struct vec2 *max_v) +static inline void vec2_max(struct vec2 *dst, const struct vec2 *v, const struct vec2 *max_v) { dst->x = (v->x > max_v->x) ? v->x : max_v->x; dst->y = (v->y > max_v->y) ? v->y : max_v->y; @@ -146,8 +140,7 @@ static inline void vec2_max(struct vec2 *dst, const struct vec2 *v, EXPORT void vec2_abs(struct vec2 *dst, const struct vec2 *v); EXPORT void vec2_floor(struct vec2 *dst, const struct vec2 *v); EXPORT void vec2_ceil(struct vec2 *dst, const struct vec2 *v); -EXPORT int vec2_close(const struct vec2 *v1, const struct vec2 *v2, - float epsilon); +EXPORT int vec2_close(const struct vec2 *v1, const struct vec2 *v2, float epsilon); EXPORT void vec2_norm(struct vec2 *dst, const struct vec2 *v); #ifdef __cplusplus diff --git a/libobs/graphics/vec3.c b/libobs/graphics/vec3.c index 6df99ce2e..ebd775e3b 100644 --- a/libobs/graphics/vec3.c +++ b/libobs/graphics/vec3.c @@ -34,8 +34,7 @@ float vec3_plane_dist(const struct vec3 *v, const struct plane *p) return vec3_dot(v, &p->dir) - p->dist; } -void vec3_rotate(struct vec3 *dst, const struct vec3 *v, - const struct matrix3 *m) +void vec3_rotate(struct vec3 *dst, const struct vec3 *v, const struct matrix3 *m) { struct vec3 temp; vec3_copy(&temp, v); @@ -46,8 +45,7 @@ void vec3_rotate(struct vec3 *dst, const struct vec3 *v, dst->w = 0.0f; } -void vec3_transform(struct vec3 *dst, const struct vec3 *v, - const struct matrix4 *m) +void vec3_transform(struct vec3 *dst, const struct vec3 *v, const struct matrix4 *m) { struct vec4 v4; vec4_from_vec3(&v4, v); @@ -55,8 +53,7 @@ void vec3_transform(struct vec3 *dst, const struct vec3 *v, vec3_from_vec4(dst, &v4); } -void vec3_transform3x4(struct vec3 *dst, const struct vec3 *v, - const struct matrix3 *m) +void vec3_transform3x4(struct vec3 *dst, const struct vec3 *v, const struct matrix3 *m) { struct vec3 temp; vec3_sub(&temp, v, &m->t); @@ -74,8 +71,7 @@ void vec3_mirror(struct vec3 *dst, const struct vec3 *v, const struct plane *p) vec3_sub(dst, v, &temp); } -void vec3_mirrorv(struct vec3 *dst, const struct vec3 *v, - const struct vec3 *vec) +void vec3_mirrorv(struct vec3 *dst, const struct vec3 *v, const struct vec3 *vec) { struct vec3 temp; vec3_mulf(&temp, vec, vec3_dot(v, vec) * 2.0f); diff --git a/libobs/graphics/vec3.h b/libobs/graphics/vec3.h index 9879612cb..cf119f999 100644 --- a/libobs/graphics/vec3.h +++ b/libobs/graphics/vec3.h @@ -58,28 +58,24 @@ static inline void vec3_copy(struct vec3 *dst, const struct vec3 *v) EXPORT void vec3_from_vec4(struct vec3 *dst, const struct vec4 *v); -static inline void vec3_add(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_add(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { dst->m = _mm_add_ps(v1->m, v2->m); dst->w = 0.0f; } -static inline void vec3_sub(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_sub(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { dst->m = _mm_sub_ps(v1->m, v2->m); dst->w = 0.0f; } -static inline void vec3_mul(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_mul(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { dst->m = _mm_mul_ps(v1->m, v2->m); } -static inline void vec3_div(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_div(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { dst->m = _mm_div_ps(v1->m, v2->m); dst->w = 0.0f; @@ -117,8 +113,7 @@ static inline float vec3_dot(const struct vec3 *v1, const struct vec3 *v2) return add.x; } -static inline void vec3_cross(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_cross(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { __m128 s1v1 = _mm_shuffle_ps(v1->m, v1->m, _MM_SHUFFLE(3, 0, 2, 1)); __m128 s1v2 = _mm_shuffle_ps(v2->m, v2->m, _MM_SHUFFLE(3, 1, 0, 2)); @@ -154,21 +149,17 @@ static inline float vec3_dist(const struct vec3 *v1, const struct vec3 *v2) static inline void vec3_norm(struct vec3 *dst, const struct vec3 *v) { float dot_val = vec3_dot(v, v); - dst->m = (dot_val > 0.0f) - ? _mm_mul_ps(v->m, _mm_set1_ps(1.0f / sqrtf(dot_val))) - : _mm_setzero_ps(); + dst->m = (dot_val > 0.0f) ? _mm_mul_ps(v->m, _mm_set1_ps(1.0f / sqrtf(dot_val))) : _mm_setzero_ps(); } -static inline bool vec3_close(const struct vec3 *v1, const struct vec3 *v2, - float epsilon) +static inline bool vec3_close(const struct vec3 *v1, const struct vec3 *v2, float epsilon) { struct vec3 test; vec3_sub(&test, v1, v2); return test.x < epsilon && test.y < epsilon && test.z < epsilon; } -static inline void vec3_min(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_min(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { dst->m = _mm_min_ps(v1->m, v2->m); dst->w = 0.0f; @@ -180,8 +171,7 @@ static inline void vec3_minf(struct vec3 *dst, const struct vec3 *v, float f) dst->w = 0.0f; } -static inline void vec3_max(struct vec3 *dst, const struct vec3 *v1, - const struct vec3 *v2) +static inline void vec3_max(struct vec3 *dst, const struct vec3 *v1, const struct vec3 *v2) { dst->m = _mm_max_ps(v1->m, v2->m); dst->w = 0.0f; @@ -219,18 +209,13 @@ static inline void vec3_ceil(struct vec3 *dst, const struct vec3 *v) EXPORT float vec3_plane_dist(const struct vec3 *v, const struct plane *p); -EXPORT void vec3_transform(struct vec3 *dst, const struct vec3 *v, - const struct matrix4 *m); +EXPORT void vec3_transform(struct vec3 *dst, const struct vec3 *v, const struct matrix4 *m); -EXPORT void vec3_rotate(struct vec3 *dst, const struct vec3 *v, - const struct matrix3 *m); -EXPORT void vec3_transform3x4(struct vec3 *dst, const struct vec3 *v, - const struct matrix3 *m); +EXPORT void vec3_rotate(struct vec3 *dst, const struct vec3 *v, const struct matrix3 *m); +EXPORT void vec3_transform3x4(struct vec3 *dst, const struct vec3 *v, const struct matrix3 *m); -EXPORT void vec3_mirror(struct vec3 *dst, const struct vec3 *v, - const struct plane *p); -EXPORT void vec3_mirrorv(struct vec3 *dst, const struct vec3 *v, - const struct vec3 *vec); +EXPORT void vec3_mirror(struct vec3 *dst, const struct vec3 *v, const struct plane *p); +EXPORT void vec3_mirrorv(struct vec3 *dst, const struct vec3 *v, const struct vec3 *vec); EXPORT void vec3_rand(struct vec3 *dst, int positive_only); diff --git a/libobs/graphics/vec4.c b/libobs/graphics/vec4.c index 3ce998a28..56044a5ca 100644 --- a/libobs/graphics/vec4.c +++ b/libobs/graphics/vec4.c @@ -25,8 +25,7 @@ void vec4_from_vec3(struct vec4 *dst, const struct vec3 *v) dst->w = 1.0f; } -void vec4_transform(struct vec4 *dst, const struct vec4 *v, - const struct matrix4 *m) +void vec4_transform(struct vec4 *dst, const struct vec4 *v, const struct matrix4 *m) { struct vec4 temp; struct matrix4 transpose; diff --git a/libobs/graphics/vec4.h b/libobs/graphics/vec4.h index 9e84b2e32..0794db051 100644 --- a/libobs/graphics/vec4.h +++ b/libobs/graphics/vec4.h @@ -44,8 +44,7 @@ static inline void vec4_zero(struct vec4 *v) v->m = _mm_setzero_ps(); } -static inline void vec4_set(struct vec4 *dst, float x, float y, float z, - float w) +static inline void vec4_set(struct vec4 *dst, float x, float y, float z, float w) { dst->m = _mm_set_ps(w, z, y, x); } @@ -57,26 +56,22 @@ static inline void vec4_copy(struct vec4 *dst, const struct vec4 *v) EXPORT void vec4_from_vec3(struct vec4 *dst, const struct vec3 *v); -static inline void vec4_add(struct vec4 *dst, const struct vec4 *v1, - const struct vec4 *v2) +static inline void vec4_add(struct vec4 *dst, const struct vec4 *v1, const struct vec4 *v2) { dst->m = _mm_add_ps(v1->m, v2->m); } -static inline void vec4_sub(struct vec4 *dst, const struct vec4 *v1, - const struct vec4 *v2) +static inline void vec4_sub(struct vec4 *dst, const struct vec4 *v1, const struct vec4 *v2) { dst->m = _mm_sub_ps(v1->m, v2->m); } -static inline void vec4_mul(struct vec4 *dst, const struct vec4 *v1, - const struct vec4 *v2) +static inline void vec4_mul(struct vec4 *dst, const struct vec4 *v1, const struct vec4 *v2) { dst->m = _mm_mul_ps(v1->m, v2->m); } -static inline void vec4_div(struct vec4 *dst, const struct vec4 *v1, - const struct vec4 *v2) +static inline void vec4_div(struct vec4 *dst, const struct vec4 *v1, const struct vec4 *v2) { dst->m = _mm_div_ps(v1->m, v2->m); } @@ -137,22 +132,17 @@ static inline float vec4_dist(const struct vec4 *v1, const struct vec4 *v2) static inline void vec4_norm(struct vec4 *dst, const struct vec4 *v) { float dot_val = vec4_dot(v, v); - dst->m = (dot_val > 0.0f) - ? _mm_mul_ps(v->m, _mm_set1_ps(1.0f / sqrtf(dot_val))) - : _mm_setzero_ps(); + dst->m = (dot_val > 0.0f) ? _mm_mul_ps(v->m, _mm_set1_ps(1.0f / sqrtf(dot_val))) : _mm_setzero_ps(); } -static inline int vec4_close(const struct vec4 *v1, const struct vec4 *v2, - float epsilon) +static inline int vec4_close(const struct vec4 *v1, const struct vec4 *v2, float epsilon) { struct vec4 test; vec4_sub(&test, v1, v2); - return test.x < epsilon && test.y < epsilon && test.z < epsilon && - test.w < epsilon; + return test.x < epsilon && test.y < epsilon && test.z < epsilon && test.w < epsilon; } -static inline void vec4_min(struct vec4 *dst, const struct vec4 *v1, - const struct vec4 *v2) +static inline void vec4_min(struct vec4 *dst, const struct vec4 *v1, const struct vec4 *v2) { dst->m = _mm_min_ps(v1->m, v2->m); } @@ -162,8 +152,7 @@ static inline void vec4_minf(struct vec4 *dst, const struct vec4 *v, float f) dst->m = _mm_min_ps(v->m, _mm_set1_ps(f)); } -static inline void vec4_max(struct vec4 *dst, const struct vec4 *v1, - const struct vec4 *v2) +static inline void vec4_max(struct vec4 *dst, const struct vec4 *v1, const struct vec4 *v2) { dst->m = _mm_max_ps(v1->m, v2->m); } @@ -245,8 +234,7 @@ static inline void vec4_from_rgba_srgb(struct vec4 *dst, uint32_t rgba) gs_float3_srgb_nonlinear_to_linear(dst->ptr); } -EXPORT void vec4_transform(struct vec4 *dst, const struct vec4 *v, - const struct matrix4 *m); +EXPORT void vec4_transform(struct vec4 *dst, const struct vec4 *v, const struct matrix4 *m); #ifdef __cplusplus } diff --git a/libobs/media-io/audio-io.c b/libobs/media-io/audio-io.c index d2be5dc96..26d1604b3 100644 --- a/libobs/media-io/audio-io.c +++ b/libobs/media-io/audio-io.c @@ -81,8 +81,7 @@ struct audio_output { /* ------------------------------------------------------------------------- */ -static bool resample_audio_output(struct audio_input *input, - struct audio_data *data) +static bool resample_audio_output(struct audio_input *input, struct audio_data *data) { bool success = true; @@ -93,9 +92,8 @@ static bool resample_audio_output(struct audio_input *input, memset(output, 0, sizeof(output)); - success = audio_resampler_resample( - input->resampler, output, &frames, &offset, - (const uint8_t *const *)data->data, data->frames); + success = audio_resampler_resample(input->resampler, output, &frames, &offset, + (const uint8_t *const *)data->data, data->frames); for (size_t i = 0; i < MAX_AV_PLANES; i++) data->data[i] = output[i]; @@ -106,8 +104,7 @@ static bool resample_audio_output(struct audio_input *input, return success; } -static inline void do_audio_output(struct audio_output *audio, size_t mix_idx, - uint64_t timestamp, uint32_t frames) +static inline void do_audio_output(struct audio_output *audio, size_t mix_idx, uint64_t timestamp, uint32_t frames) { struct audio_mix *mix = &audio->mixes[mix_idx]; struct audio_data data; @@ -117,9 +114,8 @@ static inline void do_audio_output(struct audio_output *audio, size_t mix_idx, for (size_t i = mix->inputs.num; i > 0; i--) { struct audio_input *input = mix->inputs.array + (i - 1); - float(*buf)[AUDIO_OUTPUT_FRAMES] = - input->conversion.allow_clipping ? mix->buffer_unclamped - : mix->buffer; + float(*buf)[AUDIO_OUTPUT_FRAMES] = input->conversion.allow_clipping ? mix->buffer_unclamped + : mix->buffer; for (size_t i = 0; i < audio->planes; i++) data.data[i] = (uint8_t *)buf[i]; @@ -161,8 +157,7 @@ static inline void clamp_audio_output(struct audio_output *audio, size_t bytes) } } -static void input_and_output(struct audio_output *audio, uint64_t audio_time, - uint64_t prev_time) +static void input_and_output(struct audio_output *audio, uint64_t audio_time, uint64_t prev_time) { size_t bytes = AUDIO_OUTPUT_FRAMES * audio->block_size; struct audio_output_data data[MAX_AUDIO_MIXES]; @@ -173,8 +168,7 @@ static void input_and_output(struct audio_output *audio, uint64_t audio_time, memset(data, 0, sizeof(data)); #ifdef DEBUG_AUDIO - blog(LOG_DEBUG, "audio_time: %llu, prev_time: %llu, bytes: %lu", - audio_time, prev_time, bytes); + blog(LOG_DEBUG, "audio_time: %llu, prev_time: %llu, bytes: %lu", audio_time, prev_time, bytes); #endif /* get mixers */ @@ -196,8 +190,7 @@ static void input_and_output(struct audio_output *audio, uint64_t audio_time, } /* get new audio data */ - success = audio->input_cb(audio->input_param, prev_time, audio_time, - &new_ts, active_mixes, data); + success = audio->input_cb(audio->input_param, prev_time, audio_time, &new_ts, active_mixes, data); if (!success) return; @@ -225,13 +218,11 @@ static void *audio_thread(void *param) os_set_thread_name("audio-io: audio thread"); const char *audio_thread_name = - profile_store_name(obs_get_profiler_name_store(), - "audio_thread(%s)", audio->info.name); + profile_store_name(obs_get_profiler_name_store(), "audio_thread(%s)", audio->info.name); while (os_event_try(audio->stop_event) == EAGAIN) { samples += AUDIO_OUTPUT_FRAMES; - uint64_t audio_time = - start_time + audio_frames_to_ns(rate, samples); + uint64_t audio_time = start_time + audio_frames_to_ns(rate, samples); os_sleepto_ns_fast(audio_time); @@ -255,8 +246,7 @@ static void *audio_thread(void *param) /* ------------------------------------------------------------------------- */ -static size_t audio_get_input_idx(const audio_t *audio, size_t mix_idx, - audio_output_callback_t callback, void *param) +static size_t audio_get_input_idx(const audio_t *audio, size_t mix_idx, audio_output_callback_t callback, void *param) { const struct audio_mix *mix = &audio->mixes[mix_idx]; @@ -270,21 +260,18 @@ static size_t audio_get_input_idx(const audio_t *audio, size_t mix_idx, return DARRAY_INVALID; } -static inline bool audio_input_init(struct audio_input *input, - struct audio_output *audio) +static inline bool audio_input_init(struct audio_input *input, struct audio_output *audio) { if (input->conversion.format != audio->info.format || input->conversion.samples_per_sec != audio->info.samples_per_sec || input->conversion.speakers != audio->info.speakers) { - struct resample_info from = { - .format = audio->info.format, - .samples_per_sec = audio->info.samples_per_sec, - .speakers = audio->info.speakers}; + struct resample_info from = {.format = audio->info.format, + .samples_per_sec = audio->info.samples_per_sec, + .speakers = audio->info.speakers}; - struct resample_info to = { - .format = input->conversion.format, - .samples_per_sec = input->conversion.samples_per_sec, - .speakers = input->conversion.speakers}; + struct resample_info to = {.format = input->conversion.format, + .samples_per_sec = input->conversion.samples_per_sec, + .speakers = input->conversion.speakers}; input->resampler = audio_resampler_create(&to, &from); if (!input->resampler) { @@ -299,8 +286,7 @@ static inline bool audio_input_init(struct audio_input *input, return true; } -bool audio_output_connect(audio_t *audio, size_t mi, - const struct audio_convert_info *conversion, +bool audio_output_connect(audio_t *audio, size_t mi, const struct audio_convert_info *conversion, audio_output_callback_t callback, void *param) { bool success = false; @@ -322,8 +308,7 @@ bool audio_output_connect(audio_t *audio, size_t mi, } else { input.conversion.format = audio->info.format; input.conversion.speakers = audio->info.speakers; - input.conversion.samples_per_sec = - audio->info.samples_per_sec; + input.conversion.samples_per_sec = audio->info.samples_per_sec; } if (input.conversion.format == AUDIO_FORMAT_UNKNOWN) @@ -331,8 +316,7 @@ bool audio_output_connect(audio_t *audio, size_t mi, if (input.conversion.speakers == SPEAKERS_UNKNOWN) input.conversion.speakers = audio->info.speakers; if (input.conversion.samples_per_sec == 0) - input.conversion.samples_per_sec = - audio->info.samples_per_sec; + input.conversion.samples_per_sec = audio->info.samples_per_sec; success = audio_input_init(&input, audio); if (success) @@ -344,8 +328,7 @@ bool audio_output_connect(audio_t *audio, size_t mi, return success; } -void audio_output_disconnect(audio_t *audio, size_t mix_idx, - audio_output_callback_t callback, void *param) +void audio_output_disconnect(audio_t *audio, size_t mix_idx, audio_output_callback_t callback, void *param) { if (!audio || mix_idx >= MAX_AUDIO_MIXES) return; @@ -364,8 +347,7 @@ void audio_output_disconnect(audio_t *audio, size_t mix_idx, static inline bool valid_audio_params(const struct audio_output_info *info) { - return info->format && info->name && info->samples_per_sec > 0 && - info->speakers > 0; + return info->format && info->name && info->samples_per_sec > 0 && info->speakers > 0; } int audio_output_open(audio_t **audio, struct audio_output_info *info) @@ -385,8 +367,7 @@ int audio_output_open(audio_t **audio, struct audio_output_info *info) out->planes = planar ? out->channels : 1; out->input_cb = info->input_callback; out->input_param = info->input_param; - out->block_size = (planar ? 1 : out->channels) * - get_audio_bytes_per_channel(info->format); + out->block_size = (planar ? 1 : out->channels) * get_audio_bytes_per_channel(info->format); if (pthread_mutex_init_recursive(&out->input_mutex) != 0) goto fail0; diff --git a/libobs/media-io/audio-io.h b/libobs/media-io/audio-io.h index aeb761b9c..6f2d92745 100644 --- a/libobs/media-io/audio-io.h +++ b/libobs/media-io/audio-io.h @@ -30,9 +30,7 @@ extern "C" { #define MAX_DEVICE_INPUT_CHANNELS 64 #define AUDIO_OUTPUT_FRAMES 1024 -#define TOTAL_AUDIO_SIZE \ - (MAX_AUDIO_MIXES * MAX_AUDIO_CHANNELS * AUDIO_OUTPUT_FRAMES * \ - sizeof(float)) +#define TOTAL_AUDIO_SIZE (MAX_AUDIO_MIXES * MAX_AUDIO_CHANNELS * AUDIO_OUTPUT_FRAMES * sizeof(float)) /* * Base audio output component. Use this to create an audio output track @@ -86,10 +84,8 @@ struct audio_output_data { float *data[MAX_AUDIO_CHANNELS]; }; -typedef bool (*audio_input_callback_t)(void *param, uint64_t start_ts, - uint64_t end_ts, uint64_t *new_ts, - uint32_t active_mixers, - struct audio_output_data *mixes); +typedef bool (*audio_input_callback_t)(void *param, uint64_t start_ts, uint64_t end_ts, uint64_t *new_ts, + uint32_t active_mixers, struct audio_output_data *mixes); struct audio_output_info { const char *name; @@ -179,28 +175,21 @@ static inline bool is_audio_planar(enum audio_format format) return false; } -static inline size_t get_audio_planes(enum audio_format format, - enum speaker_layout speakers) +static inline size_t get_audio_planes(enum audio_format format, enum speaker_layout speakers) { return (is_audio_planar(format) ? get_audio_channels(speakers) : 1); } -static inline size_t get_audio_size(enum audio_format format, - enum speaker_layout speakers, - uint32_t frames) +static inline size_t get_audio_size(enum audio_format format, enum speaker_layout speakers, uint32_t frames) { bool planar = is_audio_planar(format); - return (planar ? 1 : get_audio_channels(speakers)) * - get_audio_bytes_per_channel(format) * frames; + return (planar ? 1 : get_audio_channels(speakers)) * get_audio_bytes_per_channel(format) * frames; } -static inline size_t get_total_audio_size(enum audio_format format, - enum speaker_layout speakers, - uint32_t frames) +static inline size_t get_total_audio_size(enum audio_format format, enum speaker_layout speakers, uint32_t frames) { - return get_audio_channels(speakers) * - get_audio_bytes_per_channel(format) * frames; + return get_audio_channels(speakers) * get_audio_bytes_per_channel(format) * frames; } static inline uint64_t audio_frames_to_ns(size_t sample_rate, uint64_t frames) @@ -220,15 +209,11 @@ static inline uint64_t ns_to_audio_frames(size_t sample_rate, uint64_t frames) EXPORT int audio_output_open(audio_t **audio, struct audio_output_info *info); EXPORT void audio_output_close(audio_t *audio); -typedef void (*audio_output_callback_t)(void *param, size_t mix_idx, - struct audio_data *data); +typedef void (*audio_output_callback_t)(void *param, size_t mix_idx, struct audio_data *data); -EXPORT bool audio_output_connect(audio_t *video, size_t mix_idx, - const struct audio_convert_info *conversion, +EXPORT bool audio_output_connect(audio_t *video, size_t mix_idx, const struct audio_convert_info *conversion, audio_output_callback_t callback, void *param); -EXPORT void audio_output_disconnect(audio_t *video, size_t mix_idx, - audio_output_callback_t callback, - void *param); +EXPORT void audio_output_disconnect(audio_t *video, size_t mix_idx, audio_output_callback_t callback, void *param); EXPORT bool audio_output_active(const audio_t *audio); @@ -236,8 +221,7 @@ EXPORT size_t audio_output_get_block_size(const audio_t *audio); EXPORT size_t audio_output_get_planes(const audio_t *audio); EXPORT size_t audio_output_get_channels(const audio_t *audio); EXPORT uint32_t audio_output_get_sample_rate(const audio_t *audio); -EXPORT const struct audio_output_info * -audio_output_get_info(const audio_t *audio); +EXPORT const struct audio_output_info *audio_output_get_info(const audio_t *audio); #ifdef __cplusplus } diff --git a/libobs/media-io/audio-resampler-ffmpeg.c b/libobs/media-io/audio-resampler-ffmpeg.c index 0b41a694b..eb5be4f74 100644 --- a/libobs/media-io/audio-resampler-ffmpeg.c +++ b/libobs/media-io/audio-resampler-ffmpeg.c @@ -97,8 +97,7 @@ static inline uint64_t convert_speaker_layout(enum speaker_layout layout) } #endif -audio_resampler_t *audio_resampler_create(const struct resample_info *dst, - const struct resample_info *src) +audio_resampler_t *audio_resampler_create(const struct resample_info *dst, const struct resample_info *src) { struct audio_resampler *rs = bzalloc(sizeof(struct audio_resampler)); int errcode; @@ -115,27 +114,20 @@ audio_resampler_t *audio_resampler_create(const struct resample_info *dst, #if (LIBSWRESAMPLE_VERSION_INT < AV_VERSION_INT(4, 5, 100)) rs->input_layout = convert_speaker_layout(src->speakers); rs->output_layout = convert_speaker_layout(dst->speakers); - rs->context = swr_alloc_set_opts(NULL, rs->output_layout, - rs->output_format, - dst->samples_per_sec, rs->input_layout, - rs->input_format, src->samples_per_sec, - 0, NULL); + rs->context = swr_alloc_set_opts(NULL, rs->output_layout, rs->output_format, dst->samples_per_sec, + rs->input_layout, rs->input_format, src->samples_per_sec, 0, NULL); #else int nb_ch = get_audio_channels(src->speakers); av_channel_layout_default(&rs->input_ch_layout, nb_ch); av_channel_layout_default(&rs->output_ch_layout, rs->output_ch); if (src->speakers == SPEAKERS_4POINT1) - rs->input_ch_layout = - (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; + rs->input_ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; if (dst->speakers == SPEAKERS_4POINT1) - rs->output_ch_layout = - (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; + rs->output_ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; - swr_alloc_set_opts2(&rs->context, &rs->output_ch_layout, - rs->output_format, dst->samples_per_sec, - &rs->input_ch_layout, rs->input_format, - src->samples_per_sec, 0, NULL); + swr_alloc_set_opts2(&rs->context, &rs->output_ch_layout, rs->output_format, dst->samples_per_sec, + &rs->input_ch_layout, rs->input_format, src->samples_per_sec, 0, NULL); #endif if (!rs->context) { @@ -148,8 +140,7 @@ audio_resampler_t *audio_resampler_create(const struct resample_info *dst, if (rs->input_layout == AV_CH_LAYOUT_MONO && rs->output_ch > 1) { #else AVChannelLayout test_ch = AV_CHANNEL_LAYOUT_MONO; - if (av_channel_layout_compare(&rs->input_ch_layout, &test_ch) == 0 && - rs->output_ch > 1) { + if (av_channel_layout_compare(&rs->input_ch_layout, &test_ch) == 0 && rs->output_ch > 1) { #endif const double matrix[MAX_AUDIO_CHANNELS][MAX_AUDIO_CHANNELS] = { {1}, @@ -161,16 +152,13 @@ audio_resampler_t *audio_resampler_create(const struct resample_info *dst, {1, 1, 1, 0, 1, 1, 1}, {1, 1, 1, 0, 1, 1, 1, 1}, }; - if (swr_set_matrix(rs->context, matrix[rs->output_ch - 1], 1) < - 0) - blog(LOG_DEBUG, - "swr_set_matrix failed for mono upmix\n"); + if (swr_set_matrix(rs->context, matrix[rs->output_ch - 1], 1) < 0) + blog(LOG_DEBUG, "swr_set_matrix failed for mono upmix\n"); } errcode = swr_init(rs->context); if (errcode != 0) { - blog(LOG_ERROR, "avresample_open failed: error code %d", - errcode); + blog(LOG_ERROR, "avresample_open failed: error code %d", errcode); audio_resampler_destroy(rs); return NULL; } @@ -190,8 +178,7 @@ void audio_resampler_destroy(audio_resampler_t *rs) } } -bool audio_resampler_resample(audio_resampler_t *rs, uint8_t *output[], - uint32_t *out_frames, uint64_t *ts_offset, +bool audio_resampler_resample(audio_resampler_t *rs, uint8_t *output[], uint32_t *out_frames, uint64_t *ts_offset, const uint8_t *const input[], uint32_t in_frames) { if (!rs) @@ -201,10 +188,8 @@ bool audio_resampler_resample(audio_resampler_t *rs, uint8_t *output[], int ret; int64_t delay = swr_get_delay(context, rs->input_freq); - int estimated = (int)av_rescale_rnd(delay + (int64_t)in_frames, - (int64_t)rs->output_freq, - (int64_t)rs->input_freq, - AV_ROUND_UP); + int estimated = (int)av_rescale_rnd(delay + (int64_t)in_frames, (int64_t)rs->output_freq, + (int64_t)rs->input_freq, AV_ROUND_UP); *ts_offset = (uint64_t)swr_get_delay(context, 1000000000); @@ -213,14 +198,12 @@ bool audio_resampler_resample(audio_resampler_t *rs, uint8_t *output[], if (rs->output_buffer[0]) av_freep(&rs->output_buffer[0]); - av_samples_alloc(rs->output_buffer, NULL, rs->output_ch, - estimated, rs->output_format, 0); + av_samples_alloc(rs->output_buffer, NULL, rs->output_ch, estimated, rs->output_format, 0); rs->output_size = estimated; } - ret = swr_convert(context, rs->output_buffer, rs->output_size, - (const uint8_t **)input, in_frames); + ret = swr_convert(context, rs->output_buffer, rs->output_size, (const uint8_t **)input, in_frames); if (ret < 0) { blog(LOG_ERROR, "swr_convert failed: %d", ret); diff --git a/libobs/media-io/audio-resampler.h b/libobs/media-io/audio-resampler.h index 376f98ad1..ca1e7b08d 100644 --- a/libobs/media-io/audio-resampler.h +++ b/libobs/media-io/audio-resampler.h @@ -33,16 +33,11 @@ struct resample_info { enum speaker_layout speakers; }; -EXPORT audio_resampler_t * -audio_resampler_create(const struct resample_info *dst, - const struct resample_info *src); +EXPORT audio_resampler_t *audio_resampler_create(const struct resample_info *dst, const struct resample_info *src); EXPORT void audio_resampler_destroy(audio_resampler_t *resampler); -EXPORT bool audio_resampler_resample(audio_resampler_t *resampler, - uint8_t *output[], uint32_t *out_frames, - uint64_t *ts_offset, - const uint8_t *const input[], - uint32_t in_frames); +EXPORT bool audio_resampler_resample(audio_resampler_t *resampler, uint8_t *output[], uint32_t *out_frames, + uint64_t *ts_offset, const uint8_t *const input[], uint32_t in_frames); #ifdef __cplusplus } diff --git a/libobs/media-io/format-conversion.c b/libobs/media-io/format-conversion.c index 8f5091cee..0de113302 100644 --- a/libobs/media-io/format-conversion.c +++ b/libobs/media-io/format-conversion.c @@ -25,64 +25,51 @@ #define get_m128_32_0(val) (*((uint32_t *)&val)) #define get_m128_32_1(val) (*(((uint32_t *)&val) + 1)) -#define pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, mask, sh) \ - do { \ - __m128i pack_val = _mm_packs_epi32( \ - _mm_srli_si128(_mm_and_si128(line1, mask), sh), \ - _mm_srli_si128(_mm_and_si128(line2, mask), sh)); \ - pack_val = _mm_packus_epi16(pack_val, pack_val); \ - \ - *(uint32_t *)(lum_plane + lum_pos0) = get_m128_32_0(pack_val); \ - *(uint32_t *)(lum_plane + lum_pos1) = get_m128_32_1(pack_val); \ +#define pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, mask, sh) \ + do { \ + __m128i pack_val = _mm_packs_epi32(_mm_srli_si128(_mm_and_si128(line1, mask), sh), \ + _mm_srli_si128(_mm_and_si128(line2, mask), sh)); \ + pack_val = _mm_packus_epi16(pack_val, pack_val); \ + \ + *(uint32_t *)(lum_plane + lum_pos0) = get_m128_32_0(pack_val); \ + *(uint32_t *)(lum_plane + lum_pos1) = get_m128_32_1(pack_val); \ } while (false) -#define pack_val(lum_plane, lum_pos0, lum_pos1, line1, line2, mask) \ - do { \ - __m128i pack_val = \ - _mm_packs_epi32(_mm_and_si128(line1, mask), \ - _mm_and_si128(line2, mask)); \ - pack_val = _mm_packus_epi16(pack_val, pack_val); \ - \ - *(uint32_t *)(lum_plane + lum_pos0) = get_m128_32_0(pack_val); \ - *(uint32_t *)(lum_plane + lum_pos1) = get_m128_32_1(pack_val); \ +#define pack_val(lum_plane, lum_pos0, lum_pos1, line1, line2, mask) \ + do { \ + __m128i pack_val = _mm_packs_epi32(_mm_and_si128(line1, mask), _mm_and_si128(line2, mask)); \ + pack_val = _mm_packus_epi16(pack_val, pack_val); \ + \ + *(uint32_t *)(lum_plane + lum_pos0) = get_m128_32_0(pack_val); \ + *(uint32_t *)(lum_plane + lum_pos1) = get_m128_32_1(pack_val); \ } while (false) -#define pack_ch_1plane(uv_plane, chroma_pos, line1, line2, uv_mask) \ - do { \ - __m128i add_val = \ - _mm_add_epi64(_mm_and_si128(line1, uv_mask), \ - _mm_and_si128(line2, uv_mask)); \ - __m128i avg_val = _mm_add_epi64( \ - add_val, \ - _mm_shuffle_epi32(add_val, _MM_SHUFFLE(2, 3, 0, 1))); \ - avg_val = _mm_srai_epi16(avg_val, 2); \ - avg_val = _mm_shuffle_epi32(avg_val, _MM_SHUFFLE(3, 1, 2, 0)); \ - avg_val = _mm_packus_epi16(avg_val, avg_val); \ - \ - *(uint32_t *)(uv_plane + chroma_pos) = get_m128_32_0(avg_val); \ +#define pack_ch_1plane(uv_plane, chroma_pos, line1, line2, uv_mask) \ + do { \ + __m128i add_val = _mm_add_epi64(_mm_and_si128(line1, uv_mask), _mm_and_si128(line2, uv_mask)); \ + __m128i avg_val = _mm_add_epi64(add_val, _mm_shuffle_epi32(add_val, _MM_SHUFFLE(2, 3, 0, 1))); \ + avg_val = _mm_srai_epi16(avg_val, 2); \ + avg_val = _mm_shuffle_epi32(avg_val, _MM_SHUFFLE(3, 1, 2, 0)); \ + avg_val = _mm_packus_epi16(avg_val, avg_val); \ + \ + *(uint32_t *)(uv_plane + chroma_pos) = get_m128_32_0(avg_val); \ } while (false) -#define pack_ch_2plane(u_plane, v_plane, chroma_pos, line1, line2, uv_mask) \ - do { \ - uint32_t packed_vals; \ - \ - __m128i add_val = \ - _mm_add_epi64(_mm_and_si128(line1, uv_mask), \ - _mm_and_si128(line2, uv_mask)); \ - __m128i avg_val = _mm_add_epi64( \ - add_val, \ - _mm_shuffle_epi32(add_val, _MM_SHUFFLE(2, 3, 0, 1))); \ - avg_val = _mm_srai_epi16(avg_val, 2); \ - avg_val = _mm_shuffle_epi32(avg_val, _MM_SHUFFLE(3, 1, 2, 0)); \ - avg_val = \ - _mm_shufflelo_epi16(avg_val, _MM_SHUFFLE(3, 1, 2, 0)); \ - avg_val = _mm_packus_epi16(avg_val, avg_val); \ - \ - packed_vals = get_m128_32_0(avg_val); \ - \ - *(uint16_t *)(u_plane + chroma_pos) = (uint16_t)(packed_vals); \ - *(uint16_t *)(v_plane + chroma_pos) = \ - (uint16_t)(packed_vals >> 16); \ +#define pack_ch_2plane(u_plane, v_plane, chroma_pos, line1, line2, uv_mask) \ + do { \ + uint32_t packed_vals; \ + \ + __m128i add_val = _mm_add_epi64(_mm_and_si128(line1, uv_mask), _mm_and_si128(line2, uv_mask)); \ + __m128i avg_val = _mm_add_epi64(add_val, _mm_shuffle_epi32(add_val, _MM_SHUFFLE(2, 3, 0, 1))); \ + avg_val = _mm_srai_epi16(avg_val, 2); \ + avg_val = _mm_shuffle_epi32(avg_val, _MM_SHUFFLE(3, 1, 2, 0)); \ + avg_val = _mm_shufflelo_epi16(avg_val, _MM_SHUFFLE(3, 1, 2, 0)); \ + avg_val = _mm_packus_epi16(avg_val, avg_val); \ + \ + packed_vals = get_m128_32_0(avg_val); \ + \ + *(uint16_t *)(u_plane + chroma_pos) = (uint16_t)(packed_vals); \ + *(uint16_t *)(v_plane + chroma_pos) = (uint16_t)(packed_vals >> 16); \ } while (false) static FORCE_INLINE uint32_t min_uint32(uint32_t a, uint32_t b) @@ -90,9 +77,8 @@ static FORCE_INLINE uint32_t min_uint32(uint32_t a, uint32_t b) return a < b ? a : b; } -void compress_uyvx_to_i420(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, uint8_t *output[], - const uint32_t out_linesize[]) +void compress_uyvx_to_i420(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output[], const uint32_t out_linesize[]) { uint8_t *lum_plane = output[0]; uint8_t *u_plane = output[1]; @@ -115,21 +101,16 @@ void compress_uyvx_to_i420(const uint8_t *input, uint32_t in_linesize, uint32_t lum_pos1 = lum_pos0 + out_linesize[0]; __m128i line1 = _mm_load_si128((const __m128i *)img); - __m128i line2 = _mm_load_si128( - (const __m128i *)(img + in_linesize)); + __m128i line2 = _mm_load_si128((const __m128i *)(img + in_linesize)); - pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, - lum_mask, 1); - pack_ch_2plane(u_plane, v_plane, - chroma_y_pos + (x >> 1), line1, line2, - uv_mask); + pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, lum_mask, 1); + pack_ch_2plane(u_plane, v_plane, chroma_y_pos + (x >> 1), line1, line2, uv_mask); } } } -void compress_uyvx_to_nv12(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, uint8_t *output[], - const uint32_t out_linesize[]) +void compress_uyvx_to_nv12(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output[], const uint32_t out_linesize[]) { uint8_t *lum_plane = output[0]; uint8_t *chroma_plane = output[1]; @@ -151,20 +132,16 @@ void compress_uyvx_to_nv12(const uint8_t *input, uint32_t in_linesize, uint32_t lum_pos1 = lum_pos0 + out_linesize[0]; __m128i line1 = _mm_load_si128((const __m128i *)img); - __m128i line2 = _mm_load_si128( - (const __m128i *)(img + in_linesize)); + __m128i line2 = _mm_load_si128((const __m128i *)(img + in_linesize)); - pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, - lum_mask, 1); - pack_ch_1plane(chroma_plane, chroma_y_pos + x, line1, - line2, uv_mask); + pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, lum_mask, 1); + pack_ch_1plane(chroma_plane, chroma_y_pos + x, line1, line2, uv_mask); } } } -void convert_uyvx_to_i444(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, uint8_t *output[], - const uint32_t out_linesize[]) +void convert_uyvx_to_i444(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output[], const uint32_t out_linesize[]) { uint8_t *lum_plane = output[0]; uint8_t *u_plane = output[1]; @@ -187,22 +164,17 @@ void convert_uyvx_to_i444(const uint8_t *input, uint32_t in_linesize, uint32_t lum_pos1 = lum_pos0 + out_linesize[0]; __m128i line1 = _mm_load_si128((const __m128i *)img); - __m128i line2 = _mm_load_si128( - (const __m128i *)(img + in_linesize)); + __m128i line2 = _mm_load_si128((const __m128i *)(img + in_linesize)); - pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, - lum_mask, 1); - pack_val(u_plane, lum_pos0, lum_pos1, line1, line2, - u_mask); - pack_shift(v_plane, lum_pos0, lum_pos1, line1, line2, - v_mask, 2); + pack_shift(lum_plane, lum_pos0, lum_pos1, line1, line2, lum_mask, 1); + pack_val(u_plane, lum_pos0, lum_pos1, line1, line2, u_mask); + pack_shift(v_plane, lum_pos0, lum_pos1, line1, line2, v_mask, 2); } } } -void decompress_420(const uint8_t *const input[], const uint32_t in_linesize[], - uint32_t start_y, uint32_t end_y, uint8_t *output, - uint32_t out_linesize) +void decompress_420(const uint8_t *const input[], const uint32_t in_linesize[], uint32_t start_y, uint32_t end_y, + uint8_t *output, uint32_t out_linesize) { uint32_t start_y_d2 = start_y / 2; uint32_t width_d2 = in_linesize[0] / 2; @@ -234,9 +206,8 @@ void decompress_420(const uint8_t *const input[], const uint32_t in_linesize[], } } -void decompress_nv12(const uint8_t *const input[], const uint32_t in_linesize[], - uint32_t start_y, uint32_t end_y, uint8_t *output, - uint32_t out_linesize) +void decompress_nv12(const uint8_t *const input[], const uint32_t in_linesize[], uint32_t start_y, uint32_t end_y, + uint8_t *output, uint32_t out_linesize) { uint32_t start_y_d2 = start_y / 2; uint32_t width_d2 = min_uint32(in_linesize[0], out_linesize) / 2; @@ -267,8 +238,7 @@ void decompress_nv12(const uint8_t *const input[], const uint32_t in_linesize[], } } -void decompress_422(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, uint8_t *output, +void decompress_422(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, uint8_t *output, uint32_t out_linesize, bool leading_lum) { uint32_t width_d2 = min_uint32(in_linesize, out_linesize) / 2; diff --git a/libobs/media-io/format-conversion.h b/libobs/media-io/format-conversion.h index fe3ba7dfb..3dd5fb439 100644 --- a/libobs/media-io/format-conversion.h +++ b/libobs/media-io/format-conversion.h @@ -27,34 +27,23 @@ extern "C" { * Functions for converting to and from packed 444 YUV */ -EXPORT void compress_uyvx_to_i420(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, - uint8_t *output[], - const uint32_t out_linesize[]); +EXPORT void compress_uyvx_to_i420(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output[], const uint32_t out_linesize[]); -EXPORT void compress_uyvx_to_nv12(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, - uint8_t *output[], - const uint32_t out_linesize[]); +EXPORT void compress_uyvx_to_nv12(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output[], const uint32_t out_linesize[]); -EXPORT void convert_uyvx_to_i444(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, - uint8_t *output[], - const uint32_t out_linesize[]); +EXPORT void convert_uyvx_to_i444(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output[], const uint32_t out_linesize[]); -EXPORT void decompress_nv12(const uint8_t *const input[], - const uint32_t in_linesize[], uint32_t start_y, - uint32_t end_y, uint8_t *output, - uint32_t out_linesize); +EXPORT void decompress_nv12(const uint8_t *const input[], const uint32_t in_linesize[], uint32_t start_y, + uint32_t end_y, uint8_t *output, uint32_t out_linesize); -EXPORT void decompress_420(const uint8_t *const input[], - const uint32_t in_linesize[], uint32_t start_y, - uint32_t end_y, uint8_t *output, - uint32_t out_linesize); +EXPORT void decompress_420(const uint8_t *const input[], const uint32_t in_linesize[], uint32_t start_y, uint32_t end_y, + uint8_t *output, uint32_t out_linesize); -EXPORT void decompress_422(const uint8_t *input, uint32_t in_linesize, - uint32_t start_y, uint32_t end_y, uint8_t *output, - uint32_t out_linesize, bool leading_lum); +EXPORT void decompress_422(const uint8_t *input, uint32_t in_linesize, uint32_t start_y, uint32_t end_y, + uint8_t *output, uint32_t out_linesize, bool leading_lum); #ifdef __cplusplus } diff --git a/libobs/media-io/frame-rate.h b/libobs/media-io/frame-rate.h index 6c6a3dba3..4f362c2f6 100644 --- a/libobs/media-io/frame-rate.h +++ b/libobs/media-io/frame-rate.h @@ -9,20 +9,17 @@ struct media_frames_per_second { uint32_t denominator; }; -static inline double -media_frames_per_second_to_frame_interval(struct media_frames_per_second fps) +static inline double media_frames_per_second_to_frame_interval(struct media_frames_per_second fps) { return (double)fps.denominator / fps.numerator; } -static inline double -media_frames_per_second_to_fps(struct media_frames_per_second fps) +static inline double media_frames_per_second_to_fps(struct media_frames_per_second fps) { return (double)fps.numerator / fps.denominator; } -static inline bool -media_frames_per_second_is_valid(struct media_frames_per_second fps) +static inline bool media_frames_per_second_is_valid(struct media_frames_per_second fps) { return fps.numerator && fps.denominator; } diff --git a/libobs/media-io/media-remux.c b/libobs/media-io/media-remux.c index 06bd88c0d..bced9a127 100644 --- a/libobs/media-io/media-remux.c +++ b/libobs/media-io/media-remux.c @@ -47,8 +47,7 @@ static inline bool init_input(media_remux_job_t job, const char *in_filename) { int ret = avformat_open_input(&job->ifmt_ctx, in_filename, NULL, NULL); if (ret < 0) { - blog(LOG_ERROR, "media_remux: Could not open input file '%s'", - in_filename); + blog(LOG_ERROR, "media_remux: Could not open input file '%s'", in_filename); return false; } @@ -69,8 +68,7 @@ static inline bool init_output(media_remux_job_t job, const char *out_filename) { int ret; - avformat_alloc_output_context2(&job->ofmt_ctx, NULL, NULL, - out_filename); + avformat_alloc_output_context2(&job->ofmt_ctx, NULL, NULL, out_filename); if (!job->ofmt_ctx) { blog(LOG_ERROR, "media_remux: Could not create output context"); return false; @@ -85,26 +83,21 @@ static inline bool init_output(media_remux_job_t job, const char *out_filename) return false; } - ret = avcodec_parameters_copy(out_stream->codecpar, - in_stream->codecpar); + ret = avcodec_parameters_copy(out_stream->codecpar, in_stream->codecpar); if (ret < 0) { - blog(LOG_ERROR, - "media_remux: Failed to copy parameters"); + blog(LOG_ERROR, "media_remux: Failed to copy parameters"); return false; } av_dict_copy(&out_stream->metadata, in_stream->metadata, 0); - if (in_stream->codecpar->codec_id == AV_CODEC_ID_HEVC && - job->ofmt_ctx->oformat->codec_tag && - av_codec_get_id(job->ofmt_ctx->oformat->codec_tag, - MKTAG('h', 'v', 'c', '1')) == + if (in_stream->codecpar->codec_id == AV_CODEC_ID_HEVC && job->ofmt_ctx->oformat->codec_tag && + av_codec_get_id(job->ofmt_ctx->oformat->codec_tag, MKTAG('h', 'v', 'c', '1')) == out_stream->codecpar->codec_id) { // Tag HEVC files with industry standard HVC1 tag for wider device compatibility // when HVC1 tag is supported by out stream codec - out_stream->codecpar->codec_tag = - MKTAG('h', 'v', 'c', '1'); + out_stream->codecpar->codec_tag = MKTAG('h', 'v', 'c', '1'); } else { // Otherwise tag 0 to let FFmpeg automatically select the appropriate tag out_stream->codecpar->codec_tag = 0; @@ -112,16 +105,13 @@ static inline bool init_output(media_remux_job_t job, const char *out_filename) if (in_stream->codecpar->codec_type == AVMEDIA_TYPE_AUDIO) { - av_channel_layout_default( - &out_stream->codecpar->ch_layout, - in_stream->codecpar->ch_layout.nb_channels); + av_channel_layout_default(&out_stream->codecpar->ch_layout, + in_stream->codecpar->ch_layout.nb_channels); /* The avutil default channel layout for 5 channels is * 5.0, which OBS does not support. Manually set 5 * channels to 4.1. */ if (in_stream->codecpar->ch_layout.nb_channels == 5) - out_stream->codecpar->ch_layout = - (AVChannelLayout) - AV_CHANNEL_LAYOUT_4POINT1; + out_stream->codecpar->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; } } @@ -130,8 +120,7 @@ static inline bool init_output(media_remux_job_t job, const char *out_filename) #endif if (!(job->ofmt_ctx->oformat->flags & AVFMT_NOFILE)) { - ret = avio_open(&job->ofmt_ctx->pb, out_filename, - AVIO_FLAG_WRITE); + ret = avio_open(&job->ofmt_ctx->pb, out_filename, AVIO_FLAG_WRITE); if (ret < 0) { blog(LOG_ERROR, "media_remux: Failed to open output" @@ -144,8 +133,7 @@ static inline bool init_output(media_remux_job_t job, const char *out_filename) return true; } -bool media_remux_job_create(media_remux_job_t *job, const char *in_filename, - const char *out_filename) +bool media_remux_job_create(media_remux_job_t *job, const char *in_filename, const char *out_filename) { if (!job) return false; @@ -176,23 +164,17 @@ fail: return false; } -static inline void process_packet(AVPacket *pkt, AVStream *in_stream, - AVStream *out_stream) +static inline void process_packet(AVPacket *pkt, AVStream *in_stream, AVStream *out_stream) { - pkt->pts = av_rescale_q_rnd(pkt->pts, in_stream->time_base, - out_stream->time_base, + pkt->pts = av_rescale_q_rnd(pkt->pts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); - pkt->dts = av_rescale_q_rnd(pkt->dts, in_stream->time_base, - out_stream->time_base, + pkt->dts = av_rescale_q_rnd(pkt->dts, in_stream->time_base, out_stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); - pkt->duration = (int)av_rescale_q(pkt->duration, in_stream->time_base, - out_stream->time_base); + pkt->duration = (int)av_rescale_q(pkt->duration, in_stream->time_base, out_stream->time_base); pkt->pos = -1; } -static inline int process_packets(media_remux_job_t job, - media_remux_progress_callback callback, - void *data) +static inline int process_packets(media_remux_job_t job, media_remux_progress_callback callback, void *data) { AVPacket pkt; @@ -222,8 +204,7 @@ static inline int process_packets(media_remux_job_t job, av_packet_unref(&pkt); if (ret < 0) { - blog(LOG_ERROR, "media_remux: Error muxing packet: %s", - av_err2str(ret)); + blog(LOG_ERROR, "media_remux: Error muxing packet: %s", av_err2str(ret)); /* Treat "Invalid data found when processing input" and * "Invalid argument" as non-fatal */ @@ -237,8 +218,7 @@ static inline int process_packets(media_remux_job_t job, return ret; } -bool media_remux_job_process(media_remux_job_t job, - media_remux_progress_callback callback, void *data) +bool media_remux_job_process(media_remux_job_t job, media_remux_progress_callback callback, void *data) { int ret; bool success = false; @@ -248,8 +228,7 @@ bool media_remux_job_process(media_remux_job_t job, ret = avformat_write_header(job->ofmt_ctx, NULL); if (ret < 0) { - blog(LOG_ERROR, "media_remux: Error opening output file: %s", - av_err2str(ret)); + blog(LOG_ERROR, "media_remux: Error opening output file: %s", av_err2str(ret)); return success; } @@ -261,8 +240,7 @@ bool media_remux_job_process(media_remux_job_t job, ret = av_write_trailer(job->ofmt_ctx); if (ret < 0) { - blog(LOG_ERROR, "media_remux: av_write_trailer: %s", - av_err2str(ret)); + blog(LOG_ERROR, "media_remux: av_write_trailer: %s", av_err2str(ret)); success = false; } diff --git a/libobs/media-io/media-remux.h b/libobs/media-io/media-remux.h index c04ff37e7..e197a9ed2 100644 --- a/libobs/media-io/media-remux.h +++ b/libobs/media-io/media-remux.h @@ -28,12 +28,8 @@ typedef bool(media_remux_progress_callback)(void *data, float percent); extern "C" { #endif -EXPORT bool media_remux_job_create(media_remux_job_t *job, - const char *in_filename, - const char *out_filename); -EXPORT bool media_remux_job_process(media_remux_job_t job, - media_remux_progress_callback callback, - void *data); +EXPORT bool media_remux_job_create(media_remux_job_t *job, const char *in_filename, const char *out_filename); +EXPORT bool media_remux_job_process(media_remux_job_t job, media_remux_progress_callback callback, void *data); EXPORT void media_remux_job_destroy(media_remux_job_t job); #ifdef __cplusplus diff --git a/libobs/media-io/video-fourcc.c b/libobs/media-io/video-fourcc.c index abe0d837a..f929442c9 100644 --- a/libobs/media-io/video-fourcc.c +++ b/libobs/media-io/video-fourcc.c @@ -18,8 +18,7 @@ #include "../util/c99defs.h" #include "video-io.h" -#define MAKE_FOURCC(a, b, c, d) \ - ((uint32_t)(((d) << 24) | ((c) << 16) | ((b) << 8) | (a))) +#define MAKE_FOURCC(a, b, c, d) ((uint32_t)(((d) << 24) | ((c) << 16) | ((b) << 8) | (a))) enum video_format video_format_from_fourcc(uint32_t fourcc) { diff --git a/libobs/media-io/video-frame.c b/libobs/media-io/video-frame.c index 37aeea99f..0e1ed49bd 100644 --- a/libobs/media-io/video-frame.c +++ b/libobs/media-io/video-frame.c @@ -18,8 +18,7 @@ #include "video-frame.h" #define HALF(size) ((size + 1) / 2) -#define ALIGN(size, alignment) \ - *size = (*size + alignment - 1) & (~(alignment - 1)); +#define ALIGN(size, alignment) *size = (*size + alignment - 1) & (~(alignment - 1)); static inline void align_size(size_t *size, size_t alignment) { @@ -32,8 +31,7 @@ static inline void align_uint32(uint32_t *size, size_t alignment) } /* assumes already-zeroed array */ -void video_frame_get_linesizes(uint32_t linesize[MAX_AV_PLANES], - enum video_format format, uint32_t width) +void video_frame_get_linesizes(uint32_t linesize[MAX_AV_PLANES], enum video_format format, uint32_t width) { switch (format) { default: @@ -122,8 +120,7 @@ void video_frame_get_linesizes(uint32_t linesize[MAX_AV_PLANES], } } -void video_frame_get_plane_heights(uint32_t heights[MAX_AV_PLANES], - enum video_format format, uint32_t height) +void video_frame_get_plane_heights(uint32_t heights[MAX_AV_PLANES], enum video_format format, uint32_t height) { switch (format) { default: @@ -190,8 +187,7 @@ void video_frame_get_plane_heights(uint32_t heights[MAX_AV_PLANES], } } -void video_frame_init(struct video_frame *frame, enum video_format format, - uint32_t width, uint32_t height) +void video_frame_init(struct video_frame *frame, enum video_format format, uint32_t width, uint32_t height) { size_t size = 0; uint32_t linesizes[MAX_AV_PLANES]; @@ -236,8 +232,7 @@ void video_frame_init(struct video_frame *frame, enum video_format format, } } -void video_frame_copy(struct video_frame *dst, const struct video_frame *src, - enum video_format format, uint32_t cy) +void video_frame_copy(struct video_frame *dst, const struct video_frame *src, enum video_format format, uint32_t cy) { uint32_t heights[MAX_AV_PLANES]; @@ -252,20 +247,15 @@ void video_frame_copy(struct video_frame *dst, const struct video_frame *src, continue; if (src->linesize[i] == dst->linesize[i]) { - memcpy(dst->data[i], src->data[i], - src->linesize[i] * heights[i]); + memcpy(dst->data[i], src->data[i], src->linesize[i] * heights[i]); } else { /* linesizes which do not match must be copied line-by-line */ size_t src_linesize = src->linesize[i]; size_t dst_linesize = dst->linesize[i]; /* determine how much we can write (frames with different line sizes require more )*/ - size_t linesize = src_linesize < dst_linesize - ? src_linesize - : dst_linesize; + size_t linesize = src_linesize < dst_linesize ? src_linesize : dst_linesize; for (uint32_t y = 0; y < heights[i]; y++) { - uint8_t *src_pos = - src->data[i] + (src_linesize * y); - uint8_t *dst_pos = - dst->data[i] + (dst_linesize * y); + uint8_t *src_pos = src->data[i] + (src_linesize * y); + uint8_t *dst_pos = dst->data[i] + (dst_linesize * y); memcpy(dst_pos, src_pos, linesize); } } diff --git a/libobs/media-io/video-frame.h b/libobs/media-io/video-frame.h index e3f64ddab..b4d2e4786 100644 --- a/libobs/media-io/video-frame.h +++ b/libobs/media-io/video-frame.h @@ -29,9 +29,7 @@ struct video_frame { uint32_t linesize[MAX_AV_PLANES]; }; -EXPORT void video_frame_init(struct video_frame *frame, - enum video_format format, uint32_t width, - uint32_t height); +EXPORT void video_frame_init(struct video_frame *frame, enum video_format format, uint32_t width, uint32_t height); static inline void video_frame_free(struct video_frame *frame) { @@ -41,8 +39,7 @@ static inline void video_frame_free(struct video_frame *frame) } } -static inline struct video_frame * -video_frame_create(enum video_format format, uint32_t width, uint32_t height) +static inline struct video_frame *video_frame_create(enum video_format format, uint32_t width, uint32_t height) { struct video_frame *frame; @@ -59,9 +56,8 @@ static inline void video_frame_destroy(struct video_frame *frame) } } -EXPORT void video_frame_copy(struct video_frame *dst, - const struct video_frame *src, - enum video_format format, uint32_t height); +EXPORT void video_frame_copy(struct video_frame *dst, const struct video_frame *src, enum video_format format, + uint32_t height); #ifdef __cplusplus } diff --git a/libobs/media-io/video-io.c b/libobs/media-io/video-io.c index 540f484d0..6801451f2 100644 --- a/libobs/media-io/video-io.c +++ b/libobs/media-io/video-io.c @@ -95,8 +95,7 @@ struct video_output { /* ------------------------------------------------------------------------- */ -static inline bool scale_video_output(struct video_input *input, - struct video_data *data) +static inline bool scale_video_output(struct video_input *input, struct video_data *data) { bool success = true; @@ -108,10 +107,8 @@ static inline bool scale_video_output(struct video_input *input, frame = &input->frame[input->cur_frame]; - success = video_scaler_scale(input->scaler, frame->data, - frame->linesize, - (const uint8_t *const *)data->data, - data->linesize); + success = video_scaler_scale(input->scaler, frame->data, frame->linesize, + (const uint8_t *const *)data->data, data->linesize); if (success) { for (size_t i = 0; i < MAX_AV_PLANES; i++) { @@ -152,8 +149,7 @@ static inline bool video_output_cur_frame(struct video_output *video) // to allow multiple encoders started at the same time to start on // the same frame uint32_t skip = input->frame_rate_divisor_counter++; - if (input->frame_rate_divisor_counter == - input->frame_rate_divisor) + if (input->frame_rate_divisor_counter == input->frame_rate_divisor) input->frame_rate_divisor_counter = 0; if (skip) @@ -198,8 +194,7 @@ static void *video_thread(void *param) os_set_thread_name("video-io: video thread"); const char *video_thread_name = - profile_store_name(obs_get_profiler_name_store(), - "video_thread(%s)", video->info.name); + profile_store_name(obs_get_profiler_name_store(), "video_thread(%s)", video->info.name); while (os_sem_wait(video->update_semaphore) == 0) { if (video->stop) @@ -223,8 +218,7 @@ static void *video_thread(void *param) static inline bool valid_video_params(const struct video_output_info *info) { - return info->height != 0 && info->width != 0 && info->fps_den != 0 && - info->fps_num != 0; + return info->height != 0 && info->width != 0 && info->fps_den != 0 && info->fps_num != 0; } static inline void init_cache(struct video_output *video) @@ -236,8 +230,7 @@ static inline void init_cache(struct video_output *video) struct video_frame *frame; frame = (struct video_frame *)&video->cache[i]; - video_frame_init(frame, video->info.format, video->info.width, - video->info.height); + video_frame_init(frame, video->info.format, video->info.width, video->info.height); } video->available_frames = video->info.cache_size; @@ -255,8 +248,7 @@ int video_output_open(video_t **video, struct video_output_info *info) goto fail0; memcpy(&out->info, info, sizeof(struct video_output_info)); - out->frame_time = - util_mul_div64(1000000000ULL, info->fps_den, info->fps_num); + out->frame_time = util_mul_div64(1000000000ULL, info->fps_den, info->fps_num); if (pthread_mutex_init_recursive(&out->data_mutex) != 0) goto fail0; @@ -307,9 +299,7 @@ void video_output_close(video_t *video) bfree(video); } -static size_t video_get_input_idx(const video_t *video, - void (*callback)(void *param, - struct video_data *frame), +static size_t video_get_input_idx(const video_t *video, void (*callback)(void *param, struct video_data *frame), void *param) { for (size_t i = 0; i < video->inputs.num; i++) { @@ -344,29 +334,22 @@ static enum video_colorspace collapse_space(enum video_colorspace cs) static bool match_space(enum video_colorspace a, enum video_colorspace b) { - return (a == VIDEO_CS_DEFAULT) || (b == VIDEO_CS_DEFAULT) || - (collapse_space(a) == collapse_space(b)); + return (a == VIDEO_CS_DEFAULT) || (b == VIDEO_CS_DEFAULT) || (collapse_space(a) == collapse_space(b)); } -static inline bool video_input_init(struct video_input *input, - struct video_output *video) +static inline bool video_input_init(struct video_input *input, struct video_output *video) { - if (input->conversion.width != video->info.width || - input->conversion.height != video->info.height || + if (input->conversion.width != video->info.width || input->conversion.height != video->info.height || input->conversion.format != video->info.format || !match_range(input->conversion.range, video->info.range) || - !match_space(input->conversion.colorspace, - video->info.colorspace)) { + !match_space(input->conversion.colorspace, video->info.colorspace)) { struct video_scale_info from = {.format = video->info.format, .width = video->info.width, .height = video->info.height, .range = video->info.range, - .colorspace = - video->info.colorspace}; + .colorspace = video->info.colorspace}; - int ret = video_scaler_create(&input->scaler, - &input->conversion, &from, - VIDEO_SCALE_FAST_BILINEAR); + int ret = video_scaler_create(&input->scaler, &input->conversion, &from, VIDEO_SCALE_FAST_BILINEAR); if (ret != VIDEO_SCALER_SUCCESS) { if (ret == VIDEO_SCALER_BAD_CONVERSION) blog(LOG_ERROR, "video_input_init: Bad " @@ -379,9 +362,7 @@ static inline bool video_input_init(struct video_input *input, } for (size_t i = 0; i < MAX_CONVERT_BUFFERS; i++) - video_frame_init(&input->frame[i], - input->conversion.format, - input->conversion.width, + video_frame_init(&input->frame[i], input->conversion.format, input->conversion.width, input->conversion.height); } @@ -408,17 +389,14 @@ static video_t *get_root(video_t *video) return video; } -bool video_output_connect( - video_t *video, const struct video_scale_info *conversion, - void (*callback)(void *param, struct video_data *frame), void *param) +bool video_output_connect(video_t *video, const struct video_scale_info *conversion, + void (*callback)(void *param, struct video_data *frame), void *param) { return video_output_connect2(video, conversion, 1, callback, param); } -bool video_output_connect2( - video_t *video, const struct video_scale_info *conversion, - uint32_t frame_rate_divisor, - void (*callback)(void *param, struct video_data *frame), void *param) +bool video_output_connect2(video_t *video, const struct video_scale_info *conversion, uint32_t frame_rate_divisor, + void (*callback)(void *param, struct video_data *frame), void *param) { bool success = false; @@ -473,9 +451,7 @@ bool video_output_connect2( static void log_skipped(video_t *video) { long skipped = os_atomic_load_long(&video->skipped_frames); - double percentage_skipped = - (double)skipped / - (double)os_atomic_load_long(&video->total_frames) * 100.0; + double percentage_skipped = (double)skipped / (double)os_atomic_load_long(&video->total_frames) * 100.0; if (skipped) blog(LOG_INFO, @@ -483,14 +459,10 @@ static void log_skipped(video_t *video) "skipped frames due " "to encoding lag: " "%ld/%ld (%0.1f%%)", - video->skipped_frames, video->total_frames, - percentage_skipped); + video->skipped_frames, video->total_frames, percentage_skipped); } -void video_output_disconnect(video_t *video, - void (*callback)(void *param, - struct video_data *frame), - void *param) +void video_output_disconnect(video_t *video, void (*callback)(void *param, struct video_data *frame), void *param) { if (!video || !callback) return; @@ -527,8 +499,7 @@ const struct video_output_info *video_output_get_info(const video_t *video) return video ? &video->info : NULL; } -bool video_output_lock_frame(video_t *video, struct video_frame *frame, - int count, uint64_t timestamp) +bool video_output_lock_frame(video_t *video, struct video_frame *frame, int count, uint64_t timestamp) { struct cached_frame_info *cfi; bool locked; @@ -637,14 +608,12 @@ double video_output_get_frame_rate(const video_t *video) uint32_t video_output_get_skipped_frames(const video_t *video) { - return (uint32_t)os_atomic_load_long( - &get_const_root(video)->skipped_frames); + return (uint32_t)os_atomic_load_long(&get_const_root(video)->skipped_frames); } uint32_t video_output_get_total_frames(const video_t *video) { - return (uint32_t)os_atomic_load_long( - &get_const_root(video)->total_frames); + return (uint32_t)os_atomic_load_long(&get_const_root(video)->total_frames); } /* Note: These four functions below are a very slight bit of a hack. If the @@ -657,8 +626,7 @@ void video_output_inc_texture_encoders(video_t *video) { video = get_root(video); - if (os_atomic_inc_long(&video->gpu_refs) == 1 && - !os_atomic_load_bool(&video->raw_active)) { + if (os_atomic_inc_long(&video->gpu_refs) == 1 && !os_atomic_load_bool(&video->raw_active)) { reset_frames(video); } } @@ -667,8 +635,7 @@ void video_output_dec_texture_encoders(video_t *video) { video = get_root(video); - if (os_atomic_dec_long(&video->gpu_refs) == 0 && - !os_atomic_load_bool(&video->raw_active)) { + if (os_atomic_dec_long(&video->gpu_refs) == 0 && !os_atomic_load_bool(&video->raw_active)) { log_skipped(video); } } @@ -683,8 +650,7 @@ void video_output_inc_texture_skipped_frames(video_t *video) os_atomic_inc_long(&get_root(video)->skipped_frames); } -video_t *video_output_create_with_frame_rate_divisor(video_t *video, - uint32_t divisor) +video_t *video_output_create_with_frame_rate_divisor(video_t *video, uint32_t divisor) { // `divisor == 1` would result in the same frame rate, // resulting in an unnecessary additional video output diff --git a/libobs/media-io/video-io.h b/libobs/media-io/video-io.h index 41cad67a5..84f8a1a82 100644 --- a/libobs/media-io/video-io.h +++ b/libobs/media-io/video-io.h @@ -252,19 +252,16 @@ static inline const char *get_video_colorspace_name(enum video_colorspace cs) return "Unknown"; } -static inline enum video_range_type -resolve_video_range(enum video_format format, enum video_range_type range) +static inline enum video_range_type resolve_video_range(enum video_format format, enum video_range_type range) { if (range == VIDEO_RANGE_DEFAULT) { - range = format_is_yuv(format) ? VIDEO_RANGE_PARTIAL - : VIDEO_RANGE_FULL; + range = format_is_yuv(format) ? VIDEO_RANGE_PARTIAL : VIDEO_RANGE_FULL; } return range; } -static inline const char *get_video_range_name(enum video_format format, - enum video_range_type range) +static inline const char *get_video_range_name(enum video_format format, enum video_range_type range) { range = resolve_video_range(format, range); return range == VIDEO_RANGE_FULL ? "Full" : "Partial"; @@ -288,14 +285,11 @@ struct video_scale_info { EXPORT enum video_format video_format_from_fourcc(uint32_t fourcc); -EXPORT bool video_format_get_parameters(enum video_colorspace color_space, - enum video_range_type range, - float matrix[16], float min_range[3], - float max_range[3]); -EXPORT bool video_format_get_parameters_for_format( - enum video_colorspace color_space, enum video_range_type range, - enum video_format format, float matrix[16], float min_range[3], - float max_range[3]); +EXPORT bool video_format_get_parameters(enum video_colorspace color_space, enum video_range_type range, + float matrix[16], float min_range[3], float max_range[3]); +EXPORT bool video_format_get_parameters_for_format(enum video_colorspace color_space, enum video_range_type range, + enum video_format format, float matrix[16], float min_range[3], + float max_range[3]); #define VIDEO_OUTPUT_SUCCESS 0 #define VIDEO_OUTPUT_INVALIDPARAM -1 @@ -304,26 +298,18 @@ EXPORT bool video_format_get_parameters_for_format( EXPORT int video_output_open(video_t **video, struct video_output_info *info); EXPORT void video_output_close(video_t *video); -EXPORT bool -video_output_connect(video_t *video, const struct video_scale_info *conversion, - void (*callback)(void *param, struct video_data *frame), - void *param); -EXPORT bool -video_output_connect2(video_t *video, const struct video_scale_info *conversion, - uint32_t frame_rate_divisor, - void (*callback)(void *param, struct video_data *frame), - void *param); -EXPORT void video_output_disconnect(video_t *video, - void (*callback)(void *param, - struct video_data *frame), +EXPORT bool video_output_connect(video_t *video, const struct video_scale_info *conversion, + void (*callback)(void *param, struct video_data *frame), void *param); +EXPORT bool video_output_connect2(video_t *video, const struct video_scale_info *conversion, + uint32_t frame_rate_divisor, void (*callback)(void *param, struct video_data *frame), + void *param); +EXPORT void video_output_disconnect(video_t *video, void (*callback)(void *param, struct video_data *frame), void *param); EXPORT bool video_output_active(const video_t *video); -EXPORT const struct video_output_info * -video_output_get_info(const video_t *video); -EXPORT bool video_output_lock_frame(video_t *video, struct video_frame *frame, - int count, uint64_t timestamp); +EXPORT const struct video_output_info *video_output_get_info(const video_t *video); +EXPORT bool video_output_lock_frame(video_t *video, struct video_frame *frame, int count, uint64_t timestamp); EXPORT void video_output_unlock_frame(video_t *video); EXPORT uint64_t video_output_get_frame_time(const video_t *video); EXPORT void video_output_stop(video_t *video); @@ -342,8 +328,7 @@ extern void video_output_dec_texture_encoders(video_t *video); extern void video_output_inc_texture_frames(video_t *video); extern void video_output_inc_texture_skipped_frames(video_t *video); -extern video_t *video_output_create_with_frame_rate_divisor(video_t *video, - uint32_t divisor); +extern video_t *video_output_create_with_frame_rate_divisor(video_t *video, uint32_t divisor); extern void video_output_free_frame_rate_divisor(video_t *video); #ifdef __cplusplus diff --git a/libobs/media-io/video-matrices.c b/libobs/media-io/video-matrices.c index 78712d431..6617e094d 100644 --- a/libobs/media-io/video-matrices.c +++ b/libobs/media-io/video-matrices.c @@ -65,16 +65,13 @@ static void log_matrix(float const matrix[16]) "\n% f, % f, % f, % f" "\n% f, % f, % f, % f" "\n% f, % f, % f, % f", - matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], - matrix[6], matrix[7], matrix[8], matrix[9], matrix[10], matrix[11], - matrix[12], matrix[13], matrix[14], matrix[15]); + matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8], + matrix[9], matrix[10], matrix[11], matrix[12], matrix[13], matrix[14], matrix[15]); } #endif -static void initialize_matrix(float const Kb, float const Kr, - float bit_range_max, float const range_min[3], - float const range_max[3], - float const black_levels[3], float matrix[16]) +static void initialize_matrix(float const Kb, float const Kr, float bit_range_max, float const range_min[3], + float const range_max[3], float const black_levels[3], float matrix[16]) { struct matrix3 color_matrix; @@ -89,13 +86,11 @@ static void initialize_matrix(float const Kb, float const Kr, float const Kg = (1.f - Kb - Kr); vec3_set(&color_matrix.x, yscale, 0.f, vscale * (1.f - Kr)); - vec3_set(&color_matrix.y, yscale, uscale * (Kb - 1.f) * Kb / Kg, - vscale * (Kr - 1.f) * Kr / Kg); + vec3_set(&color_matrix.y, yscale, uscale * (Kb - 1.f) * Kb / Kg, vscale * (Kr - 1.f) * Kr / Kg); vec3_set(&color_matrix.z, yscale, uscale * (1.f - Kb), 0.f); struct vec3 offsets, multiplied; - vec3_set(&offsets, -black_levels[0] / bit_range_max, - -black_levels[1] / bit_range_max, + vec3_set(&offsets, -black_levels[0] / bit_range_max, -black_levels[1] / bit_range_max, -black_levels[2] / bit_range_max); vec3_rotate(&multiplied, &offsets, &color_matrix); @@ -154,20 +149,14 @@ static void initialize_matrices() bpp_info[bpp_index].float_range_max[2] = max_chroma / range_max; for (size_t i = 0; i < NUM_FORMATS; i++) { - float full_range_max3[] = {range_max, range_max, - range_max}; - initialize_matrix(format_info[i].Kb, format_info[i].Kr, - range_max, full_range_min3, - full_range_max3, - bpp_info[bpp_index].black_levels[1], + float full_range_max3[] = {range_max, range_max, range_max}; + initialize_matrix(format_info[i].Kb, format_info[i].Kr, range_max, full_range_min3, + full_range_max3, bpp_info[bpp_index].black_levels[1], format_info[i].matrix[bpp_index][1]); - initialize_matrix(format_info[i].Kb, format_info[i].Kr, - range_max, - bpp_info[bpp_index].range_min, - bpp_info[bpp_index].range_max, - bpp_info[bpp_index].black_levels[0], - format_info[i].matrix[bpp_index][0]); + initialize_matrix(format_info[i].Kb, format_info[i].Kr, range_max, + bpp_info[bpp_index].range_min, bpp_info[bpp_index].range_max, + bpp_info[bpp_index].black_levels[0], format_info[i].matrix[bpp_index][0]); } min_value *= 2.f; @@ -182,9 +171,8 @@ static bool matrices_initialized = false; static const float full_min[3] = {0.0f, 0.0f, 0.0f}; static const float full_max[3] = {1.0f, 1.0f, 1.0f}; -static bool video_format_get_parameters_for_bpc( - enum video_colorspace color_space, enum video_range_type range, - float matrix[16], float range_min[3], float range_max[3], uint32_t bpc) +static bool video_format_get_parameters_for_bpc(enum video_colorspace color_space, enum video_range_type range, + float matrix[16], float range_min[3], float range_max[3], uint32_t bpc) { if (!matrices_initialized) { initialize_matrices(); @@ -209,26 +197,18 @@ static bool video_format_get_parameters_for_bpc( success = format_info[i].color_space == color_space; if (success) { const bool full_range = range == VIDEO_RANGE_FULL; - memcpy(matrix, - format_info[i].matrix[bpc_index][full_range], - sizeof(float) * 16); + memcpy(matrix, format_info[i].matrix[bpc_index][full_range], sizeof(float) * 16); if (range_min) { - const float *src_range_min = - full_range ? full_min - : bpp_info[bpc_index] - .float_range_min; - memcpy(range_min, src_range_min, - sizeof(float) * 3); + const float *src_range_min = full_range ? full_min + : bpp_info[bpc_index].float_range_min; + memcpy(range_min, src_range_min, sizeof(float) * 3); } if (range_max) { - const float *src_range_max = - full_range ? full_max - : bpp_info[bpc_index] - .float_range_max; - memcpy(range_max, src_range_max, - sizeof(float) * 3); + const float *src_range_max = full_range ? full_max + : bpp_info[bpc_index].float_range_max; + memcpy(range_max, src_range_max, sizeof(float) * 3); } break; @@ -238,24 +218,16 @@ static bool video_format_get_parameters_for_bpc( return success; } -bool video_format_get_parameters(enum video_colorspace color_space, - enum video_range_type range, float matrix[16], +bool video_format_get_parameters(enum video_colorspace color_space, enum video_range_type range, float matrix[16], float range_min[3], float range_max[3]) { - uint32_t bpc = (color_space == VIDEO_CS_2100_PQ || - color_space == VIDEO_CS_2100_HLG) - ? 10 - : 8; + uint32_t bpc = (color_space == VIDEO_CS_2100_PQ || color_space == VIDEO_CS_2100_HLG) ? 10 : 8; - return video_format_get_parameters_for_bpc(color_space, range, matrix, - range_min, range_max, bpc); + return video_format_get_parameters_for_bpc(color_space, range, matrix, range_min, range_max, bpc); } -bool video_format_get_parameters_for_format(enum video_colorspace color_space, - enum video_range_type range, - enum video_format format, - float matrix[16], - float range_min[3], +bool video_format_get_parameters_for_format(enum video_colorspace color_space, enum video_range_type range, + enum video_format format, float matrix[16], float range_min[3], float range_max[3]) { uint32_t bpc; @@ -280,6 +252,5 @@ bool video_format_get_parameters_for_format(enum video_colorspace color_space, break; } - return video_format_get_parameters_for_bpc(color_space, range, matrix, - range_min, range_max, bpc); + return video_format_get_parameters_for_bpc(color_space, range, matrix, range_min, range_max, bpc); } diff --git a/libobs/media-io/video-scaler-ffmpeg.c b/libobs/media-io/video-scaler-ffmpeg.c index f88f17db4..90cfdc571 100644 --- a/libobs/media-io/video-scaler-ffmpeg.c +++ b/libobs/media-io/video-scaler-ffmpeg.c @@ -30,8 +30,7 @@ struct video_scaler { int dst_linesizes[4]; }; -static inline enum AVPixelFormat -get_ffmpeg_video_format(enum video_format format) +static inline enum AVPixelFormat get_ffmpeg_video_format(enum video_format format) { switch (format) { case VIDEO_FORMAT_I420: @@ -141,10 +140,8 @@ static inline int get_ffmpeg_range_type(enum video_range_type type) #define FIXED_1_0 (1 << 16) -int video_scaler_create(video_scaler_t **scaler_out, - const struct video_scale_info *dst, - const struct video_scale_info *src, - enum video_scale_type type) +int video_scaler_create(video_scaler_t **scaler_out, const struct video_scale_info *dst, + const struct video_scale_info *src, enum video_scale_type type) { enum AVPixelFormat format_src = get_ffmpeg_video_format(src->format); enum AVPixelFormat format_dst = get_ffmpeg_video_format(dst->format); @@ -173,17 +170,14 @@ int video_scaler_create(video_scaler_t **scaler_out, scaler->dst_heights[0] = dst->height; for (size_t i = 1; i < 4; ++i) { if (has_plane[i]) { - const int s = (i == 1 || i == 2) ? desc->log2_chroma_h - : 0; + const int s = (i == 1 || i == 2) ? desc->log2_chroma_h : 0; scaler->dst_heights[i] = dst->height >> s; } } - ret = av_image_alloc(scaler->dst_pointers, scaler->dst_linesizes, - dst->width, dst->height, format_dst, 32); + ret = av_image_alloc(scaler->dst_pointers, scaler->dst_linesizes, dst->width, dst->height, format_dst, 32); if (ret < 0) { - blog(LOG_WARNING, - "video_scaler_create: av_image_alloc failed: %d", ret); + blog(LOG_WARNING, "video_scaler_create: av_image_alloc failed: %d", ret); goto fail; } @@ -208,8 +202,7 @@ int video_scaler_create(video_scaler_t **scaler_out, goto fail; } - ret = sws_setColorspaceDetails(scaler->swscale, coeff_src, range_src, - coeff_dst, range_dst, 0, FIXED_1_0, + ret = sws_setColorspaceDetails(scaler->swscale, coeff_src, range_src, coeff_dst, range_dst, 0, FIXED_1_0, FIXED_1_0); if (ret < 0) { blog(LOG_DEBUG, "video_scaler_create: " @@ -236,20 +229,16 @@ void video_scaler_destroy(video_scaler_t *scaler) } } -bool video_scaler_scale(video_scaler_t *scaler, uint8_t *output[], - const uint32_t out_linesize[], - const uint8_t *const input[], - const uint32_t in_linesize[]) +bool video_scaler_scale(video_scaler_t *scaler, uint8_t *output[], const uint32_t out_linesize[], + const uint8_t *const input[], const uint32_t in_linesize[]) { if (!scaler) return false; - int ret = sws_scale(scaler->swscale, input, (const int *)in_linesize, 0, - scaler->src_height, scaler->dst_pointers, - scaler->dst_linesizes); + int ret = sws_scale(scaler->swscale, input, (const int *)in_linesize, 0, scaler->src_height, + scaler->dst_pointers, scaler->dst_linesizes); if (ret <= 0) { - blog(LOG_ERROR, "video_scaler_scale: sws_scale failed: %d", - ret); + blog(LOG_ERROR, "video_scaler_scale: sws_scale failed: %d", ret); return false; } diff --git a/libobs/media-io/video-scaler.h b/libobs/media-io/video-scaler.h index 9c4fa515b..7539e6ffc 100644 --- a/libobs/media-io/video-scaler.h +++ b/libobs/media-io/video-scaler.h @@ -31,16 +31,12 @@ typedef struct video_scaler video_scaler_t; #define VIDEO_SCALER_BAD_CONVERSION -1 #define VIDEO_SCALER_FAILED -2 -EXPORT int video_scaler_create(video_scaler_t **scaler, - const struct video_scale_info *dst, - const struct video_scale_info *src, - enum video_scale_type type); +EXPORT int video_scaler_create(video_scaler_t **scaler, const struct video_scale_info *dst, + const struct video_scale_info *src, enum video_scale_type type); EXPORT void video_scaler_destroy(video_scaler_t *scaler); -EXPORT bool video_scaler_scale(video_scaler_t *scaler, uint8_t *output[], - const uint32_t out_linesize[], - const uint8_t *const input[], - const uint32_t in_linesize[]); +EXPORT bool video_scaler_scale(video_scaler_t *scaler, uint8_t *output[], const uint32_t out_linesize[], + const uint8_t *const input[], const uint32_t in_linesize[]); #ifdef __cplusplus } diff --git a/libobs/obs-audio-controls.c b/libobs/obs-audio-controls.c index 7a9ff6182..9fb2ca090 100644 --- a/libobs/obs-audio-controls.c +++ b/libobs/obs-audio-controls.c @@ -170,9 +170,7 @@ static float log_def_to_db(const float def) else if (def <= 0.0f) return -INFINITY; - return -(LOG_RANGE_DB + LOG_OFFSET_DB) * - powf((LOG_RANGE_DB + LOG_OFFSET_DB) / LOG_OFFSET_DB, - -def) + + return -(LOG_RANGE_DB + LOG_OFFSET_DB) * powf((LOG_RANGE_DB + LOG_OFFSET_DB) / LOG_OFFSET_DB, -def) + LOG_OFFSET_DB; } @@ -183,8 +181,7 @@ static float log_db_to_def(const float db) else if (db <= -96.0f) return 0.0f; - return (-log10f(-db + LOG_OFFSET_DB) - LOG_RANGE_VAL) / - (LOG_OFFSET_VAL - LOG_RANGE_VAL); + return (-log10f(-db + LOG_OFFSET_DB) - LOG_RANGE_VAL) / (LOG_OFFSET_VAL - LOG_RANGE_VAL); } static void signal_volume_changed(struct obs_fader *fader, const float db) @@ -197,10 +194,8 @@ static void signal_volume_changed(struct obs_fader *fader, const float db) pthread_mutex_unlock(&fader->callback_mutex); } -static void signal_levels_updated(struct obs_volmeter *volmeter, - const float magnitude[MAX_AUDIO_CHANNELS], - const float peak[MAX_AUDIO_CHANNELS], - const float input_peak[MAX_AUDIO_CHANNELS]) +static void signal_levels_updated(struct obs_volmeter *volmeter, const float magnitude[MAX_AUDIO_CHANNELS], + const float peak[MAX_AUDIO_CHANNELS], const float input_peak[MAX_AUDIO_CHANNELS]) { pthread_mutex_lock(&volmeter->callback_mutex); for (size_t i = volmeter->callbacks.num; i > 0; i--) { @@ -271,12 +266,11 @@ static int get_nr_channels_from_audio_data(const struct audio_data *data) /* msb(h, g, f, e) lsb(d, c, b, a) --> msb(h, h, g, f) lsb(e, d, c, b) */ -#define SHIFT_RIGHT_2PS(msb, lsb) \ - { \ - __m128 tmp = \ - _mm_shuffle_ps(lsb, msb, _MM_SHUFFLE(0, 0, 3, 3)); \ - lsb = _mm_shuffle_ps(lsb, tmp, _MM_SHUFFLE(2, 1, 2, 1)); \ - msb = _mm_shuffle_ps(msb, msb, _MM_SHUFFLE(3, 3, 2, 1)); \ +#define SHIFT_RIGHT_2PS(msb, lsb) \ + { \ + __m128 tmp = _mm_shuffle_ps(lsb, msb, _MM_SHUFFLE(0, 0, 3, 3)); \ + lsb = _mm_shuffle_ps(lsb, tmp, _MM_SHUFFLE(2, 1, 2, 1)); \ + msb = _mm_shuffle_ps(msb, msb, _MM_SHUFFLE(3, 3, 2, 1)); \ } /* x(d, c, b, a) --> (|d|, |c|, |b|, |a|) @@ -323,20 +317,15 @@ static int get_nr_channels_from_audio_data(const struct audio_data *data) * @param nr_samples Number of sets of 4 samples. * @returns 5 times oversampled true-peak from the set of samples. */ -static float get_true_peak(__m128 previous_samples, const float *samples, - size_t nr_samples) +static float get_true_peak(__m128 previous_samples, const float *samples, size_t nr_samples) { /* These are normalized-sinc parameters for interpolating over sample * points which are located at x-coords: -1.5, -0.5, +0.5, +1.5. * And oversample points at x-coords: -0.3, -0.1, 0.1, 0.3. */ - const __m128 m3 = - _mm_set_ps(-0.155915f, 0.935489f, 0.233872f, -0.103943f); - const __m128 m1 = - _mm_set_ps(-0.216236f, 0.756827f, 0.504551f, -0.189207f); - const __m128 p1 = - _mm_set_ps(-0.189207f, 0.504551f, 0.756827f, -0.216236f); - const __m128 p3 = - _mm_set_ps(-0.103943f, 0.233872f, 0.935489f, -0.155915f); + const __m128 m3 = _mm_set_ps(-0.155915f, 0.935489f, 0.233872f, -0.103943f); + const __m128 m1 = _mm_set_ps(-0.216236f, 0.756827f, 0.504551f, -0.189207f); + const __m128 p1 = _mm_set_ps(-0.189207f, 0.504551f, 0.756827f, -0.216236f); + const __m128 p3 = _mm_set_ps(-0.103943f, 0.233872f, 0.935489f, -0.155915f); __m128 work = previous_samples; __m128 peak = previous_samples; @@ -374,8 +363,7 @@ static float get_true_peak(__m128 previous_samples, const float *samples, /* points contain the first four samples to calculate the sinc interpolation * over. They will have come from a previous iteration. */ -static float get_sample_peak(__m128 previous_samples, const float *samples, - size_t nr_samples) +static float get_sample_peak(__m128 previous_samples, const float *samples, size_t nr_samples) { __m128 peak = previous_samples; for (size_t i = 0; (i + 3) < nr_samples; i += 4) { @@ -388,8 +376,7 @@ static float get_sample_peak(__m128 previous_samples, const float *samples, return r; } -static void volmeter_process_peak_last_samples(obs_volmeter_t *volmeter, - int channel_nr, float *samples, +static void volmeter_process_peak_last_samples(obs_volmeter_t *volmeter, int channel_nr, float *samples, size_t nr_samples) { /* Take the last 4 samples that need to be used for the next peak @@ -400,25 +387,19 @@ static void volmeter_process_peak_last_samples(obs_volmeter_t *volmeter, case 0: break; case 1: - volmeter->prev_samples[channel_nr][0] = - volmeter->prev_samples[channel_nr][1]; - volmeter->prev_samples[channel_nr][1] = - volmeter->prev_samples[channel_nr][2]; - volmeter->prev_samples[channel_nr][2] = - volmeter->prev_samples[channel_nr][3]; + volmeter->prev_samples[channel_nr][0] = volmeter->prev_samples[channel_nr][1]; + volmeter->prev_samples[channel_nr][1] = volmeter->prev_samples[channel_nr][2]; + volmeter->prev_samples[channel_nr][2] = volmeter->prev_samples[channel_nr][3]; volmeter->prev_samples[channel_nr][3] = samples[nr_samples - 1]; break; case 2: - volmeter->prev_samples[channel_nr][0] = - volmeter->prev_samples[channel_nr][2]; - volmeter->prev_samples[channel_nr][1] = - volmeter->prev_samples[channel_nr][3]; + volmeter->prev_samples[channel_nr][0] = volmeter->prev_samples[channel_nr][2]; + volmeter->prev_samples[channel_nr][1] = volmeter->prev_samples[channel_nr][3]; volmeter->prev_samples[channel_nr][2] = samples[nr_samples - 2]; volmeter->prev_samples[channel_nr][3] = samples[nr_samples - 1]; break; case 3: - volmeter->prev_samples[channel_nr][0] = - volmeter->prev_samples[channel_nr][3]; + volmeter->prev_samples[channel_nr][0] = volmeter->prev_samples[channel_nr][3]; volmeter->prev_samples[channel_nr][1] = samples[nr_samples - 3]; volmeter->prev_samples[channel_nr][2] = samples[nr_samples - 2]; volmeter->prev_samples[channel_nr][3] = samples[nr_samples - 1]; @@ -431,9 +412,7 @@ static void volmeter_process_peak_last_samples(obs_volmeter_t *volmeter, } } -static void volmeter_process_peak(obs_volmeter_t *volmeter, - const struct audio_data *data, - int nr_channels) +static void volmeter_process_peak(obs_volmeter_t *volmeter, const struct audio_data *data, int nr_channels) { int nr_samples = data->frames; int channel_nr = 0; @@ -453,25 +432,21 @@ static void volmeter_process_peak(obs_volmeter_t *volmeter, /* volmeter->prev_samples may not be aligned to 16 bytes; * use unaligned load. */ - __m128 previous_samples = - _mm_loadu_ps(volmeter->prev_samples[channel_nr]); + __m128 previous_samples = _mm_loadu_ps(volmeter->prev_samples[channel_nr]); float peak; switch (volmeter->peak_meter_type) { case TRUE_PEAK_METER: - peak = get_true_peak(previous_samples, samples, - nr_samples); + peak = get_true_peak(previous_samples, samples, nr_samples); break; case SAMPLE_PEAK_METER: default: - peak = get_sample_peak(previous_samples, samples, - nr_samples); + peak = get_sample_peak(previous_samples, samples, nr_samples); break; } - volmeter_process_peak_last_samples(volmeter, channel_nr, - samples, nr_samples); + volmeter_process_peak_last_samples(volmeter, channel_nr, samples, nr_samples); volmeter->peak[channel_nr] = peak; @@ -484,9 +459,7 @@ static void volmeter_process_peak(obs_volmeter_t *volmeter, } } -static void volmeter_process_magnitude(obs_volmeter_t *volmeter, - const struct audio_data *data, - int nr_channels) +static void volmeter_process_magnitude(obs_volmeter_t *volmeter, const struct audio_data *data, int nr_channels) { size_t nr_samples = data->frames; @@ -508,8 +481,7 @@ static void volmeter_process_magnitude(obs_volmeter_t *volmeter, } } -static void volmeter_process_audio_data(obs_volmeter_t *volmeter, - const struct audio_data *data) +static void volmeter_process_audio_data(obs_volmeter_t *volmeter, const struct audio_data *data) { int nr_channels = get_nr_channels_from_audio_data(data); @@ -517,9 +489,7 @@ static void volmeter_process_audio_data(obs_volmeter_t *volmeter, volmeter_process_magnitude(volmeter, data, nr_channels); } -static void volmeter_source_data_received(void *vptr, obs_source_t *source, - const struct audio_data *data, - bool muted) +static void volmeter_source_data_received(void *vptr, obs_source_t *source, const struct audio_data *data, bool muted) { struct obs_volmeter *volmeter = (struct obs_volmeter *)vptr; float mul; @@ -533,12 +503,9 @@ static void volmeter_source_data_received(void *vptr, obs_source_t *source, // Adjust magnitude/peak based on the volume level set by the user. // And convert to dB. - mul = muted && !obs_source_muted(source) ? 0.0f - : db_to_mul(volmeter->cur_db); - for (int channel_nr = 0; channel_nr < MAX_AUDIO_CHANNELS; - channel_nr++) { - magnitude[channel_nr] = - mul_to_db(volmeter->magnitude[channel_nr] * mul); + mul = muted && !obs_source_muted(source) ? 0.0f : db_to_mul(volmeter->cur_db); + for (int channel_nr = 0; channel_nr < MAX_AUDIO_CHANNELS; channel_nr++) { + magnitude[channel_nr] = mul_to_db(volmeter->magnitude[channel_nr] * mul); peak[channel_nr] = mul_to_db(volmeter->peak[channel_nr] * mul); /* The input-peak is NOT adjusted with volume, so that the user @@ -702,8 +669,7 @@ bool obs_fader_attach_source(obs_fader_t *fader, obs_source_t *source) obs_fader_detach_source(fader); sh = obs_source_get_signal_handler(source); - signal_handler_connect(sh, "volume", fader_source_volume_changed, - fader); + signal_handler_connect(sh, "volume", fader_source_volume_changed, fader); signal_handler_connect(sh, "destroy", fader_source_destroyed, fader); vol = obs_source_get_volume(source); @@ -734,13 +700,11 @@ void obs_fader_detach_source(obs_fader_t *fader) return; sh = obs_source_get_signal_handler(source); - signal_handler_disconnect(sh, "volume", fader_source_volume_changed, - fader); + signal_handler_disconnect(sh, "volume", fader_source_volume_changed, fader); signal_handler_disconnect(sh, "destroy", fader_source_destroyed, fader); } -void obs_fader_add_callback(obs_fader_t *fader, obs_fader_changed_t callback, - void *param) +void obs_fader_add_callback(obs_fader_t *fader, obs_fader_changed_t callback, void *param) { struct fader_cb cb = {callback, param}; @@ -752,8 +716,7 @@ void obs_fader_add_callback(obs_fader_t *fader, obs_fader_changed_t callback, pthread_mutex_unlock(&fader->callback_mutex); } -void obs_fader_remove_callback(obs_fader_t *fader, obs_fader_changed_t callback, - void *param) +void obs_fader_remove_callback(obs_fader_t *fader, obs_fader_changed_t callback, void *param) { struct fader_cb cb = {callback, param}; @@ -810,12 +773,9 @@ bool obs_volmeter_attach_source(obs_volmeter_t *volmeter, obs_source_t *source) obs_volmeter_detach_source(volmeter); sh = obs_source_get_signal_handler(source); - signal_handler_connect(sh, "volume", volmeter_source_volume_changed, - volmeter); - signal_handler_connect(sh, "destroy", volmeter_source_destroyed, - volmeter); - obs_source_add_audio_capture_callback( - source, volmeter_source_data_received, volmeter); + signal_handler_connect(sh, "volume", volmeter_source_volume_changed, volmeter); + signal_handler_connect(sh, "destroy", volmeter_source_destroyed, volmeter); + obs_source_add_audio_capture_callback(source, volmeter_source_data_received, volmeter); vol = obs_source_get_volume(source); pthread_mutex_lock(&volmeter->mutex); @@ -845,16 +805,12 @@ void obs_volmeter_detach_source(obs_volmeter_t *volmeter) return; sh = obs_source_get_signal_handler(source); - signal_handler_disconnect(sh, "volume", volmeter_source_volume_changed, - volmeter); - signal_handler_disconnect(sh, "destroy", volmeter_source_destroyed, - volmeter); - obs_source_remove_audio_capture_callback( - source, volmeter_source_data_received, volmeter); + signal_handler_disconnect(sh, "volume", volmeter_source_volume_changed, volmeter); + signal_handler_disconnect(sh, "destroy", volmeter_source_destroyed, volmeter); + obs_source_remove_audio_capture_callback(source, volmeter_source_data_received, volmeter); } -void obs_volmeter_set_peak_meter_type(obs_volmeter_t *volmeter, - enum obs_peak_meter_type peak_meter_type) +void obs_volmeter_set_peak_meter_type(obs_volmeter_t *volmeter, enum obs_peak_meter_type peak_meter_type) { pthread_mutex_lock(&volmeter->mutex); volmeter->peak_meter_type = peak_meter_type; @@ -867,8 +823,7 @@ int obs_volmeter_get_nr_channels(obs_volmeter_t *volmeter) int obs_nr_audio_channels; if (volmeter->source) { - source_nr_audio_channels = get_audio_channels( - volmeter->source->sample_info.speakers); + source_nr_audio_channels = get_audio_channels(volmeter->source->sample_info.speakers); } else { source_nr_audio_channels = 0; } @@ -883,8 +838,7 @@ int obs_volmeter_get_nr_channels(obs_volmeter_t *volmeter) return CLAMP(source_nr_audio_channels, 0, obs_nr_audio_channels); } -void obs_volmeter_add_callback(obs_volmeter_t *volmeter, - obs_volmeter_updated_t callback, void *param) +void obs_volmeter_add_callback(obs_volmeter_t *volmeter, obs_volmeter_updated_t callback, void *param) { struct meter_cb cb = {callback, param}; @@ -896,8 +850,7 @@ void obs_volmeter_add_callback(obs_volmeter_t *volmeter, pthread_mutex_unlock(&volmeter->callback_mutex); } -void obs_volmeter_remove_callback(obs_volmeter_t *volmeter, - obs_volmeter_updated_t callback, void *param) +void obs_volmeter_remove_callback(obs_volmeter_t *volmeter, obs_volmeter_updated_t callback, void *param) { struct meter_cb cb = {callback, param}; diff --git a/libobs/obs-audio-controls.h b/libobs/obs-audio-controls.h index c9c6d7695..64abcc23b 100644 --- a/libobs/obs-audio-controls.h +++ b/libobs/obs-audio-controls.h @@ -177,11 +177,8 @@ EXPORT void obs_fader_detach_source(obs_fader_t *fader); typedef void (*obs_fader_changed_t)(void *param, float db); -EXPORT void obs_fader_add_callback(obs_fader_t *fader, - obs_fader_changed_t callback, void *param); -EXPORT void obs_fader_remove_callback(obs_fader_t *fader, - obs_fader_changed_t callback, - void *param); +EXPORT void obs_fader_add_callback(obs_fader_t *fader, obs_fader_changed_t callback, void *param); +EXPORT void obs_fader_remove_callback(obs_fader_t *fader, obs_fader_changed_t callback, void *param); /** * @brief Create a volume meter @@ -213,8 +210,7 @@ EXPORT void obs_volmeter_destroy(obs_volmeter_t *volmeter); * volume updates on the source and after preparing the data emit its own * signal. */ -EXPORT bool obs_volmeter_attach_source(obs_volmeter_t *volmeter, - obs_source_t *source); +EXPORT bool obs_volmeter_attach_source(obs_volmeter_t *volmeter, obs_source_t *source); /** * @brief Detach the volume meter from the currently attached source @@ -227,9 +223,7 @@ EXPORT void obs_volmeter_detach_source(obs_volmeter_t *volmeter); * @param volmeter pointer to the volume meter object * @param peak_meter_type set if true-peak needs to be measured. */ -EXPORT void -obs_volmeter_set_peak_meter_type(obs_volmeter_t *volmeter, - enum obs_peak_meter_type peak_meter_type); +EXPORT void obs_volmeter_set_peak_meter_type(obs_volmeter_t *volmeter, enum obs_peak_meter_type peak_meter_type); /** * @brief Get the number of channels which are configured for this source. @@ -237,17 +231,12 @@ obs_volmeter_set_peak_meter_type(obs_volmeter_t *volmeter, */ EXPORT int obs_volmeter_get_nr_channels(obs_volmeter_t *volmeter); -typedef void (*obs_volmeter_updated_t)( - void *param, const float magnitude[MAX_AUDIO_CHANNELS], - const float peak[MAX_AUDIO_CHANNELS], - const float input_peak[MAX_AUDIO_CHANNELS]); +typedef void (*obs_volmeter_updated_t)(void *param, const float magnitude[MAX_AUDIO_CHANNELS], + const float peak[MAX_AUDIO_CHANNELS], + const float input_peak[MAX_AUDIO_CHANNELS]); -EXPORT void obs_volmeter_add_callback(obs_volmeter_t *volmeter, - obs_volmeter_updated_t callback, - void *param); -EXPORT void obs_volmeter_remove_callback(obs_volmeter_t *volmeter, - obs_volmeter_updated_t callback, - void *param); +EXPORT void obs_volmeter_add_callback(obs_volmeter_t *volmeter, obs_volmeter_updated_t callback, void *param); +EXPORT void obs_volmeter_remove_callback(obs_volmeter_t *volmeter, obs_volmeter_updated_t callback, void *param); EXPORT float obs_mul_to_db(float mul); EXPORT float obs_db_to_mul(float db); diff --git a/libobs/obs-audio.c b/libobs/obs-audio.c index e1cf012c1..29d805666 100644 --- a/libobs/obs-audio.c +++ b/libobs/obs-audio.c @@ -45,9 +45,8 @@ static inline size_t convert_time_to_frames(size_t sample_rate, uint64_t t) return (size_t)util_mul_div64(t, sample_rate, 1000000000ULL); } -static inline void mix_audio(struct audio_output_data *mixes, - obs_source_t *source, size_t channels, - size_t sample_rate, struct ts_info *ts) +static inline void mix_audio(struct audio_output_data *mixes, obs_source_t *source, size_t channels, size_t sample_rate, + struct ts_info *ts) { size_t total_floats = AUDIO_OUTPUT_FRAMES; size_t start_point = 0; @@ -56,8 +55,7 @@ static inline void mix_audio(struct audio_output_data *mixes, return; if (source->audio_ts != ts->start) { - start_point = convert_time_to_frames( - sample_rate, source->audio_ts - ts->start); + start_point = convert_time_to_frames(sample_rate, source->audio_ts - ts->start); if (start_point == AUDIO_OUTPUT_FRAMES) return; @@ -67,8 +65,7 @@ static inline void mix_audio(struct audio_output_data *mixes, for (size_t mix_idx = 0; mix_idx < MAX_AUDIO_MIXES; mix_idx++) { for (size_t ch = 0; ch < channels; ch++) { register float *mix = mixes[mix_idx].data[ch]; - register float *aud = - source->audio_output_buf[mix_idx][ch]; + register float *aud = source->audio_output_buf[mix_idx][ch]; register float *end; mix += start_point; @@ -80,47 +77,37 @@ static inline void mix_audio(struct audio_output_data *mixes, } } -static bool ignore_audio(obs_source_t *source, size_t channels, - size_t sample_rate, uint64_t start_ts) +static bool ignore_audio(obs_source_t *source, size_t channels, size_t sample_rate, uint64_t start_ts) { size_t num_floats = source->audio_input_buf[0].size / sizeof(float); const char *name = obs_source_get_name(source); if (!source->audio_ts && num_floats) { #if DEBUG_LAGGED_AUDIO == 1 - blog(LOG_DEBUG, "[src: %s] no timestamp, but audio available?", - name); + blog(LOG_DEBUG, "[src: %s] no timestamp, but audio available?", name); #endif for (size_t ch = 0; ch < channels; ch++) - deque_pop_front(&source->audio_input_buf[ch], NULL, - source->audio_input_buf[0].size); + deque_pop_front(&source->audio_input_buf[ch], NULL, source->audio_input_buf[0].size); source->last_audio_input_buf_size = 0; return false; } if (num_floats) { /* round up the number of samples to drop */ - size_t drop = - (size_t)util_mul_div64(start_ts - source->audio_ts - 1, - sample_rate, 1000000000ULL) + - 1; + size_t drop = (size_t)util_mul_div64(start_ts - source->audio_ts - 1, sample_rate, 1000000000ULL) + 1; if (drop > num_floats) drop = num_floats; #if DEBUG_LAGGED_AUDIO == 1 - blog(LOG_DEBUG, - "[src: %s] ignored %" PRIu64 "/%" PRIu64 " samples", name, - (uint64_t)drop, (uint64_t)num_floats); + blog(LOG_DEBUG, "[src: %s] ignored %" PRIu64 "/%" PRIu64 " samples", name, (uint64_t)drop, + (uint64_t)num_floats); #endif for (size_t ch = 0; ch < channels; ch++) - deque_pop_front(&source->audio_input_buf[ch], NULL, - drop * sizeof(float)); + deque_pop_front(&source->audio_input_buf[ch], NULL, drop * sizeof(float)); source->last_audio_input_buf_size = 0; - source->audio_ts += - util_mul_div64(drop, 1000000000ULL, sample_rate); - blog(LOG_DEBUG, "[src: %s] ts lag after ignoring: %" PRIu64, - name, start_ts - source->audio_ts); + source->audio_ts += util_mul_div64(drop, 1000000000ULL, sample_rate); + blog(LOG_DEBUG, "[src: %s] ts lag after ignoring: %" PRIu64, name, start_ts - source->audio_ts); /* rounding error, adjust */ if (source->audio_ts == (start_ts - 1)) @@ -131,8 +118,7 @@ static bool ignore_audio(obs_source_t *source, size_t channels, return true; } else { #if DEBUG_LAGGED_AUDIO == 1 - blog(LOG_DEBUG, "[src: %s] no samples to ignore! ts = %" PRIu64, - name, source->audio_ts); + blog(LOG_DEBUG, "[src: %s] no samples to ignore! ts = %" PRIu64, name, source->audio_ts); #endif } @@ -168,15 +154,13 @@ static bool discard_if_stopped(obs_source_t *source, size_t channels) if (!source->pending_stop) { source->pending_stop = true; #if DEBUG_AUDIO == 1 - blog(LOG_DEBUG, "doing pending stop trick: '%s'", - source->context.name); + blog(LOG_DEBUG, "doing pending stop trick: '%s'", source->context.name); #endif return false; } for (size_t ch = 0; ch < channels; ch++) - deque_pop_front(&source->audio_input_buf[ch], NULL, - source->audio_input_buf[ch].size); + deque_pop_front(&source->audio_input_buf[ch], NULL, source->audio_input_buf[ch].size); source->pending_stop = false; source->audio_ts = 0; @@ -194,8 +178,7 @@ static bool discard_if_stopped(obs_source_t *source, size_t channels) #define MAX_AUDIO_SIZE (AUDIO_OUTPUT_FRAMES * sizeof(float)) -static inline void discard_audio(struct obs_core_audio *audio, - obs_source_t *source, size_t channels, +static inline void discard_audio(struct obs_core_audio *audio, obs_source_t *source, size_t channels, size_t sample_rate, struct ts_info *ts) { size_t total_floats = AUDIO_OUTPUT_FRAMES; @@ -224,8 +207,7 @@ static inline void discard_audio(struct obs_core_audio *audio, } if (source->audio_ts < (ts->start - 1)) { - if (source->audio_pending && - source->audio_input_buf[0].size < MAX_AUDIO_SIZE && + if (source->audio_pending && source->audio_input_buf[0].size < MAX_AUDIO_SIZE && discard_if_stopped(source, channels)) return; @@ -240,18 +222,14 @@ static inline void discard_audio(struct obs_core_audio *audio, /* ignore_audio should have already run and marked this source * pending, unless we *just* added buffering */ - assert(audio->total_buffering_ticks < - audio->max_buffering_ticks || - source->audio_pending || !source->audio_ts || - audio->buffering_wait_ticks); + assert(audio->total_buffering_ticks < audio->max_buffering_ticks || source->audio_pending || + !source->audio_ts || audio->buffering_wait_ticks); #endif return; } - if (source->audio_ts != ts->start && - source->audio_ts != (ts->start - 1)) { - size_t start_point = convert_time_to_frames( - sample_rate, source->audio_ts - ts->start); + if (source->audio_ts != ts->start && source->audio_ts != (ts->start - 1)) { + size_t start_point = convert_time_to_frames(sample_rate, source->audio_ts - ts->start); if (start_point == AUDIO_OUTPUT_FRAMES) { #if DEBUG_AUDIO == 1 if (is_audio_source) @@ -297,8 +275,7 @@ static inline bool audio_buffering_maxed(struct obs_core_audio *audio) return audio->total_buffering_ticks == audio->max_buffering_ticks; } -static void set_fixed_audio_buffering(struct obs_core_audio *audio, - size_t sample_rate, struct ts_info *ts) +static void set_fixed_audio_buffering(struct obs_core_audio *audio, size_t sample_rate, struct ts_info *ts) { struct ts_info new_ts; size_t total_ms; @@ -313,8 +290,7 @@ static void set_fixed_audio_buffering(struct obs_core_audio *audio, ticks = audio->max_buffering_ticks - audio->total_buffering_ticks; audio->total_buffering_ticks += ticks; - total_ms = audio->total_buffering_ticks * AUDIO_OUTPUT_FRAMES * 1000 / - sample_rate; + total_ms = audio->total_buffering_ticks * AUDIO_OUTPUT_FRAMES * 1000 / sample_rate; blog(LOG_INFO, "Enabling fixed audio buffering, total " @@ -322,34 +298,26 @@ static void set_fixed_audio_buffering(struct obs_core_audio *audio, (int)total_ms); new_ts.start = - audio->buffered_ts - - audio_frames_to_ns(sample_rate, audio->buffering_wait_ticks * - AUDIO_OUTPUT_FRAMES); + audio->buffered_ts - audio_frames_to_ns(sample_rate, audio->buffering_wait_ticks * AUDIO_OUTPUT_FRAMES); while (ticks--) { const uint64_t cur_ticks = ++audio->buffering_wait_ticks; new_ts.end = new_ts.start; - new_ts.start = - audio->buffered_ts - - audio_frames_to_ns(sample_rate, - cur_ticks * AUDIO_OUTPUT_FRAMES); + new_ts.start = audio->buffered_ts - audio_frames_to_ns(sample_rate, cur_ticks * AUDIO_OUTPUT_FRAMES); #if DEBUG_AUDIO == 1 - blog(LOG_DEBUG, "add buffered ts: %" PRIu64 "-%" PRIu64, - new_ts.start, new_ts.end); + blog(LOG_DEBUG, "add buffered ts: %" PRIu64 "-%" PRIu64, new_ts.start, new_ts.end); #endif - deque_push_front(&audio->buffered_timestamps, &new_ts, - sizeof(new_ts)); + deque_push_front(&audio->buffered_timestamps, &new_ts, sizeof(new_ts)); } *ts = new_ts; } -static void add_audio_buffering(struct obs_core_audio *audio, - size_t sample_rate, struct ts_info *ts, - uint64_t min_ts, const char *buffering_name) +static void add_audio_buffering(struct obs_core_audio *audio, size_t sample_rate, struct ts_info *ts, uint64_t min_ts, + const char *buffering_name) { struct ts_info new_ts; uint64_t offset; @@ -371,15 +339,13 @@ static void add_audio_buffering(struct obs_core_audio *audio, audio->total_buffering_ticks += ticks; if (audio->total_buffering_ticks >= audio->max_buffering_ticks) { - ticks -= audio->total_buffering_ticks - - audio->max_buffering_ticks; + ticks -= audio->total_buffering_ticks - audio->max_buffering_ticks; audio->total_buffering_ticks = audio->max_buffering_ticks; blog(LOG_WARNING, "Max audio buffering reached!"); } ms = ticks * AUDIO_OUTPUT_FRAMES * 1000 / sample_rate; - total_ms = audio->total_buffering_ticks * AUDIO_OUTPUT_FRAMES * 1000 / - sample_rate; + total_ms = audio->total_buffering_ticks * AUDIO_OUTPUT_FRAMES * 1000 / sample_rate; blog(LOG_INFO, "adding %d milliseconds of audio buffering, total " @@ -391,50 +357,39 @@ static void add_audio_buffering(struct obs_core_audio *audio, "min_ts (%" PRIu64 ") < start timestamp " "(%" PRIu64 ")", min_ts, ts->start); - blog(LOG_DEBUG, "old buffered ts: %" PRIu64 "-%" PRIu64, ts->start, - ts->end); + blog(LOG_DEBUG, "old buffered ts: %" PRIu64 "-%" PRIu64, ts->start, ts->end); #endif new_ts.start = - audio->buffered_ts - - audio_frames_to_ns(sample_rate, audio->buffering_wait_ticks * - AUDIO_OUTPUT_FRAMES); + audio->buffered_ts - audio_frames_to_ns(sample_rate, audio->buffering_wait_ticks * AUDIO_OUTPUT_FRAMES); while (ticks--) { const uint64_t cur_ticks = ++audio->buffering_wait_ticks; new_ts.end = new_ts.start; - new_ts.start = - audio->buffered_ts - - audio_frames_to_ns(sample_rate, - cur_ticks * AUDIO_OUTPUT_FRAMES); + new_ts.start = audio->buffered_ts - audio_frames_to_ns(sample_rate, cur_ticks * AUDIO_OUTPUT_FRAMES); #if DEBUG_AUDIO == 1 - blog(LOG_DEBUG, "add buffered ts: %" PRIu64 "-%" PRIu64, - new_ts.start, new_ts.end); + blog(LOG_DEBUG, "add buffered ts: %" PRIu64 "-%" PRIu64, new_ts.start, new_ts.end); #endif - deque_push_front(&audio->buffered_timestamps, &new_ts, - sizeof(new_ts)); + deque_push_front(&audio->buffered_timestamps, &new_ts, sizeof(new_ts)); } *ts = new_ts; } -static bool audio_buffer_insufficient(struct obs_source *source, - size_t sample_rate, uint64_t min_ts) +static bool audio_buffer_insufficient(struct obs_source *source, size_t sample_rate, uint64_t min_ts) { size_t total_floats = AUDIO_OUTPUT_FRAMES; size_t size; - if (source->info.audio_render || source->audio_pending || - !source->audio_ts) { + if (source->info.audio_render || source->audio_pending || !source->audio_ts) { return false; } if (source->audio_ts != min_ts && source->audio_ts != (min_ts - 1)) { - size_t start_point = convert_time_to_frames( - sample_rate, source->audio_ts - min_ts); + size_t start_point = convert_time_to_frames(sample_rate, source->audio_ts - min_ts); if (start_point >= AUDIO_OUTPUT_FRAMES) return false; @@ -451,14 +406,12 @@ static bool audio_buffer_insufficient(struct obs_source *source, return false; } -static inline const char *find_min_ts(struct obs_core_data *data, - uint64_t *min_ts) +static inline const char *find_min_ts(struct obs_core_data *data, uint64_t *min_ts) { obs_source_t *buffering_source = NULL; struct obs_source *source = data->first_audio_source; while (source) { - if (!source->audio_pending && source->audio_ts && - source->audio_ts < *min_ts) { + if (!source->audio_pending && source->audio_ts && source->audio_ts < *min_ts) { *min_ts = source->audio_ts; buffering_source = source; } @@ -468,23 +421,20 @@ static inline const char *find_min_ts(struct obs_core_data *data, return buffering_source ? obs_source_get_name(buffering_source) : NULL; } -static inline bool mark_invalid_sources(struct obs_core_data *data, - size_t sample_rate, uint64_t min_ts) +static inline bool mark_invalid_sources(struct obs_core_data *data, size_t sample_rate, uint64_t min_ts) { bool recalculate = false; struct obs_source *source = data->first_audio_source; while (source) { - recalculate |= - audio_buffer_insufficient(source, sample_rate, min_ts); + recalculate |= audio_buffer_insufficient(source, sample_rate, min_ts); source = (struct obs_source *)source->next_audio_source; } return recalculate; } -static inline const char *calc_min_ts(struct obs_core_data *data, - size_t sample_rate, uint64_t *min_ts) +static inline const char *calc_min_ts(struct obs_core_data *data, size_t sample_rate, uint64_t *min_ts) { const char *buffering_name = find_min_ts(data, min_ts); if (mark_invalid_sources(data, sample_rate, *min_ts)) @@ -515,8 +465,7 @@ static inline void execute_audio_tasks(void) } } -bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, - uint64_t *out_ts, uint32_t mixers, +bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, uint64_t *out_ts, uint32_t mixers, struct audio_output_data *mixes) { struct obs_core_data *data = &obs->data; @@ -560,8 +509,7 @@ bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, if (!obs_source_active(source)) continue; - obs_source_enum_active_tree(source, push_audio_tree, - audio); + obs_source_enum_active_tree(source, push_audio_tree, audio); push_audio_tree(NULL, source, audio); if (obs->video.mixes.array[j] == obs->video.main_mix) @@ -585,13 +533,11 @@ bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, /* render audio data */ for (size_t i = 0; i < audio->render_order.num; i++) { obs_source_t *source = audio->render_order.array[i]; - obs_source_audio_render(source, mixers, channels, sample_rate, - audio_size); + obs_source_audio_render(source, mixers, channels, sample_rate, audio_size); /* if a source has gone backward in time and we can no * longer buffer, drop some or all of its audio */ - if (audio_buffering_maxed(audio) && source->audio_ts != 0 && - source->audio_ts < ts.start) { + if (audio_buffering_maxed(audio) && source->audio_ts != 0 && source->audio_ts < ts.start) { if (source->info.audio_render) { blog(LOG_DEBUG, "render audio source %s timestamp has " @@ -606,17 +552,12 @@ bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, #endif } else { pthread_mutex_lock(&source->audio_buf_mutex); - bool rerender = ignore_audio(source, channels, - sample_rate, - ts.start); + bool rerender = ignore_audio(source, channels, sample_rate, ts.start); pthread_mutex_unlock(&source->audio_buf_mutex); /* if we (potentially) recovered, re-render */ if (rerender) - obs_source_audio_render(source, mixers, - channels, - sample_rate, - audio_size); + obs_source_audio_render(source, mixers, channels, sample_rate, audio_size); } } } @@ -634,8 +575,7 @@ bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, set_fixed_audio_buffering(audio, sample_rate, &ts); } } else if (min_ts < ts.start) { - add_audio_buffering(audio, sample_rate, &ts, min_ts, - buffering_name); + add_audio_buffering(audio, sample_rate, &ts, min_ts, buffering_name); } /* ------------------------------------------------ */ @@ -650,8 +590,7 @@ bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, pthread_mutex_lock(&source->audio_buf_mutex); if (source->audio_output_buf[0][0] && source->audio_ts) - mix_audio(mixes, source, channels, sample_rate, - &ts); + mix_audio(mixes, source, channels, sample_rate, &ts); pthread_mutex_unlock(&source->audio_buf_mutex); } diff --git a/libobs/obs-av1.c b/libobs/obs-av1.c index 9b4e55c83..7640fe6c8 100644 --- a/libobs/obs-av1.c +++ b/libobs/obs-av1.c @@ -26,14 +26,12 @@ static inline uint64_t leb128(const uint8_t *buf, size_t size, size_t *len) return value; } -static inline unsigned int get_bits(uint8_t val, unsigned int n, - unsigned int count) +static inline unsigned int get_bits(uint8_t val, unsigned int n, unsigned int count) { return (val >> (8 - n - count)) & ((1 << (count - 1)) * 2 - 1); } -static void parse_obu_header(const uint8_t *buf, size_t size, size_t *obu_start, - size_t *obu_size, int *obu_type) +static void parse_obu_header(const uint8_t *buf, size_t size, size_t *obu_start, size_t *obu_size, int *obu_type) { int extension_flag, has_size_field; size_t size_len = 0; @@ -55,8 +53,7 @@ static void parse_obu_header(const uint8_t *buf, size_t size, size_t *obu_start, (*obu_start)++; if (has_size_field) - *obu_size = (size_t)leb128(buf + *obu_start, size - *obu_start, - &size_len); + *obu_size = (size_t)leb128(buf + *obu_start, size - *obu_start, &size_len); else *obu_size = size - 1; @@ -64,8 +61,7 @@ static void parse_obu_header(const uint8_t *buf, size_t size, size_t *obu_start, } // Pass a static 10 byte buffer in. The max size for a leb128. -static inline void encode_uleb128(uint64_t val, uint8_t *out_buf, - size_t *len_out) +static inline void encode_uleb128(uint64_t val, uint8_t *out_buf, size_t *len_out) { size_t num_bytes = 0; uint8_t b = val & 0x7f; @@ -84,16 +80,14 @@ static inline void encode_uleb128(uint64_t val, uint8_t *out_buf, /* metadata_obu_itu_t35() is a public symbol. Maintain the function * and make it call the more general metadata_obu() function. */ -void metadata_obu_itu_t35(const uint8_t *itut_t35_buffer, size_t itut_bufsize, - uint8_t **out_buffer, size_t *outbuf_size) +void metadata_obu_itu_t35(const uint8_t *itut_t35_buffer, size_t itut_bufsize, uint8_t **out_buffer, + size_t *outbuf_size) { - metadata_obu(itut_t35_buffer, itut_bufsize, out_buffer, outbuf_size, - METADATA_TYPE_ITUT_T35); + metadata_obu(itut_t35_buffer, itut_bufsize, out_buffer, outbuf_size, METADATA_TYPE_ITUT_T35); } // Create an OBU to carry AV1 metadata types, including captions and user private data -void metadata_obu(const uint8_t *source_buffer, size_t source_bufsize, - uint8_t **out_buffer, size_t *outbuf_size, +void metadata_obu(const uint8_t *source_buffer, size_t source_bufsize, uint8_t **out_buffer, size_t *outbuf_size, uint8_t metadata_type) { /* From the AV1 spec: 5.3.2 OBU Header Syntax @@ -167,16 +161,13 @@ bool obs_av1_keyframe(const uint8_t *data, size_t size) while (start < end) { size_t obu_start, obu_size; int obu_type; - parse_obu_header(start, end - start, &obu_start, &obu_size, - &obu_type); + parse_obu_header(start, end - start, &obu_start, &obu_size, &obu_type); if (obu_size) { - if (obu_type == OBS_OBU_FRAME || - obu_type == OBS_OBU_FRAME_HEADER) { + if (obu_type == OBS_OBU_FRAME || obu_type == OBS_OBU_FRAME_HEADER) { uint8_t val = *(start + obu_start); - if (!get_bits(val, 0, 1)) // show_existing_frame - return get_bits(val, 1, 2) == - 0; // frame_type + if (!get_bits(val, 0, 1)) // show_existing_frame + return get_bits(val, 1, 2) == 0; // frame_type return false; } } @@ -187,8 +178,7 @@ bool obs_av1_keyframe(const uint8_t *data, size_t size) return false; } -void obs_extract_av1_headers(const uint8_t *packet, size_t size, - uint8_t **new_packet_data, size_t *new_packet_size, +void obs_extract_av1_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, size_t *new_packet_size, uint8_t **header_data, size_t *header_size) { DARRAY(uint8_t) new_packet; @@ -201,11 +191,9 @@ void obs_extract_av1_headers(const uint8_t *packet, size_t size, while (start < end) { size_t obu_start, obu_size; int obu_type; - parse_obu_header(start, end - start, &obu_start, &obu_size, - &obu_type); + parse_obu_header(start, end - start, &obu_start, &obu_size, &obu_type); - if (obu_type == OBS_OBU_METADATA || - obu_type == OBS_OBU_SEQUENCE_HEADER) { + if (obu_type == OBS_OBU_METADATA || obu_type == OBS_OBU_SEQUENCE_HEADER) { da_push_back_array(header, start, obu_start + obu_size); } da_push_back_array(new_packet, start, obu_start + obu_size); diff --git a/libobs/obs-av1.h b/libobs/obs-av1.h index f325b4798..953c1d1db 100644 --- a/libobs/obs-av1.h +++ b/libobs/obs-av1.h @@ -34,16 +34,12 @@ enum av1_obu_metadata_type { /* Helpers for parsing AV1 OB units. */ EXPORT bool obs_av1_keyframe(const uint8_t *data, size_t size); -EXPORT void obs_extract_av1_headers(const uint8_t *packet, size_t size, - uint8_t **new_packet_data, - size_t *new_packet_size, - uint8_t **header_data, size_t *header_size); +EXPORT void obs_extract_av1_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, + size_t *new_packet_size, uint8_t **header_data, size_t *header_size); -EXPORT void metadata_obu_itu_t35(const uint8_t *itut_t35_buffer, - size_t itut_bufsize, uint8_t **out_buffer, +EXPORT void metadata_obu_itu_t35(const uint8_t *itut_t35_buffer, size_t itut_bufsize, uint8_t **out_buffer, size_t *outbuf_size); -EXPORT void metadata_obu(const uint8_t *source_buffer, size_t source_bufsize, - uint8_t **out_buffer, size_t *outbuf_size, +EXPORT void metadata_obu(const uint8_t *source_buffer, size_t source_bufsize, uint8_t **out_buffer, size_t *outbuf_size, uint8_t metadata_type); #ifdef __cplusplus diff --git a/libobs/obs-avc.c b/libobs/obs-avc.c index db3a311f4..77d43a92d 100644 --- a/libobs/obs-avc.c +++ b/libobs/obs-avc.c @@ -52,8 +52,7 @@ const uint8_t *obs_avc_find_startcode(const uint8_t *p, const uint8_t *end) return obs_nal_find_startcode(p, end); } -static int compute_avc_keyframe_priority(const uint8_t *nal_start, - bool *is_keyframe, int priority) +static int compute_avc_keyframe_priority(const uint8_t *nal_start, bool *is_keyframe, int priority) { const int type = nal_start[0] & 0x1F; if (type == OBS_NAL_SLICE_IDR) @@ -66,8 +65,7 @@ static int compute_avc_keyframe_priority(const uint8_t *nal_start, return priority; } -static void serialize_avc_data(struct serializer *s, const uint8_t *data, - size_t size, bool *is_keyframe, int *priority) +static void serialize_avc_data(struct serializer *s, const uint8_t *data, size_t size, bool *is_keyframe, int *priority) { const uint8_t *const end = data + size; const uint8_t *nal_start = obs_nal_find_startcode(data, end); @@ -78,11 +76,9 @@ static void serialize_avc_data(struct serializer *s, const uint8_t *data, if (nal_start == end) break; - *priority = compute_avc_keyframe_priority( - nal_start, is_keyframe, *priority); + *priority = compute_avc_keyframe_priority(nal_start, is_keyframe, *priority); - const uint8_t *const nal_end = - obs_nal_find_startcode(nal_start, end); + const uint8_t *const nal_end = obs_nal_find_startcode(nal_start, end); const size_t nal_size = nal_end - nal_start; s_wb32(s, (uint32_t)nal_size); s_write(s, nal_start, nal_size); @@ -90,8 +86,7 @@ static void serialize_avc_data(struct serializer *s, const uint8_t *data, } } -void obs_parse_avc_packet(struct encoder_packet *avc_packet, - const struct encoder_packet *src) +void obs_parse_avc_packet(struct encoder_packet *avc_packet, const struct encoder_packet *src) { struct array_output_data output; struct serializer s; @@ -101,8 +96,7 @@ void obs_parse_avc_packet(struct encoder_packet *avc_packet, *avc_packet = *src; serialize(&s, &ref, sizeof(ref)); - serialize_avc_data(&s, src->data, src->size, &avc_packet->keyframe, - &avc_packet->priority); + serialize_avc_data(&s, src->data, src->size, &avc_packet->keyframe, &avc_packet->priority); avc_packet->data = output.bytes.array + sizeof(ref); avc_packet->size = output.bytes.num - sizeof(ref); @@ -124,8 +118,7 @@ int obs_parse_avc_packet_priority(const struct encoder_packet *packet) break; bool unused; - priority = compute_avc_keyframe_priority(nal_start, &unused, - priority); + priority = compute_avc_keyframe_priority(nal_start, &unused, priority); nal_start = obs_nal_find_startcode(nal_start, end); } @@ -141,8 +134,8 @@ static inline bool has_start_code(const uint8_t *data) return data[2] == 1 || (data[2] == 0 && data[3] == 1); } -static void get_sps_pps(const uint8_t *data, size_t size, const uint8_t **sps, - size_t *sps_size, const uint8_t **pps, size_t *pps_size) +static void get_sps_pps(const uint8_t *data, size_t size, const uint8_t **sps, size_t *sps_size, const uint8_t **pps, + size_t *pps_size) { const uint8_t *nal_start, *nal_end; const uint8_t *end = data + size; @@ -180,9 +173,7 @@ static inline uint8_t get_ue_golomb(struct bitstream_reader *gb) return bitstream_reader_read_bits(gb, i) + (1 << i) - 1; } -static void get_sps_high_params(const uint8_t *sps, size_t size, - uint8_t *chroma_format_idc, - uint8_t *bit_depth_luma, +static void get_sps_high_params(const uint8_t *sps, size_t size, uint8_t *chroma_format_idc, uint8_t *bit_depth_luma, uint8_t *bit_depth_chroma) { struct bitstream_reader gb; @@ -261,11 +252,9 @@ size_t obs_parse_avc_header(uint8_t **header, const uint8_t *data, size_t size) /* Additional data required for high, high10, high422, high444 profiles. * See ISO/IEC 14496-15 Section 5.3.3.1.2. */ - if (profile_idc == 100 || profile_idc == 110 || profile_idc == 122 || - profile_idc == 244) { + if (profile_idc == 100 || profile_idc == 110 || profile_idc == 122 || profile_idc == 244) { uint8_t chroma_format_idc, bit_depth_luma, bit_depth_chroma; - get_sps_high_params(sps + 1, sps_size - 1, &chroma_format_idc, - &bit_depth_luma, &bit_depth_chroma); + get_sps_high_params(sps + 1, sps_size - 1, &chroma_format_idc, &bit_depth_luma, &bit_depth_chroma); // reserved + chroma_format s_w8(&s, 0xfc | chroma_format_idc); @@ -281,10 +270,8 @@ size_t obs_parse_avc_header(uint8_t **header, const uint8_t *data, size_t size) return output.bytes.num; } -void obs_extract_avc_headers(const uint8_t *packet, size_t size, - uint8_t **new_packet_data, size_t *new_packet_size, - uint8_t **header_data, size_t *header_size, - uint8_t **sei_data, size_t *sei_size) +void obs_extract_avc_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, size_t *new_packet_size, + uint8_t **header_data, size_t *header_size, uint8_t **sei_data, size_t *sei_size) { DARRAY(uint8_t) new_packet; DARRAY(uint8_t) header; @@ -314,15 +301,12 @@ void obs_extract_avc_headers(const uint8_t *packet, size_t size, nal_end = end; if (type == OBS_NAL_SPS || type == OBS_NAL_PPS) { - da_push_back_array(header, nal_codestart, - nal_end - nal_codestart); + da_push_back_array(header, nal_codestart, nal_end - nal_codestart); } else if (type == OBS_NAL_SEI) { - da_push_back_array(sei, nal_codestart, - nal_end - nal_codestart); + da_push_back_array(sei, nal_codestart, nal_end - nal_codestart); } else { - da_push_back_array(new_packet, nal_codestart, - nal_end - nal_codestart); + da_push_back_array(new_packet, nal_codestart, nal_end - nal_codestart); } nal_start = nal_end; diff --git a/libobs/obs-avc.h b/libobs/obs-avc.h index 133f28685..1e64216e7 100644 --- a/libobs/obs-avc.h +++ b/libobs/obs-avc.h @@ -42,17 +42,12 @@ enum { /* Helpers for parsing AVC NAL units. */ EXPORT bool obs_avc_keyframe(const uint8_t *data, size_t size); -EXPORT const uint8_t *obs_avc_find_startcode(const uint8_t *p, - const uint8_t *end); -EXPORT void obs_parse_avc_packet(struct encoder_packet *avc_packet, - const struct encoder_packet *src); +EXPORT const uint8_t *obs_avc_find_startcode(const uint8_t *p, const uint8_t *end); +EXPORT void obs_parse_avc_packet(struct encoder_packet *avc_packet, const struct encoder_packet *src); EXPORT int obs_parse_avc_packet_priority(const struct encoder_packet *packet); -EXPORT size_t obs_parse_avc_header(uint8_t **header, const uint8_t *data, - size_t size); -EXPORT void obs_extract_avc_headers(const uint8_t *packet, size_t size, - uint8_t **new_packet_data, - size_t *new_packet_size, - uint8_t **header_data, size_t *header_size, +EXPORT size_t obs_parse_avc_header(uint8_t **header, const uint8_t *data, size_t size); +EXPORT void obs_extract_avc_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, + size_t *new_packet_size, uint8_t **header_data, size_t *header_size, uint8_t **sei_data, size_t *sei_size); #ifdef __cplusplus diff --git a/libobs/obs-config.h b/libobs/obs-config.h index 544c643e9..2700c218f 100644 --- a/libobs/obs-config.h +++ b/libobs/obs-config.h @@ -43,12 +43,9 @@ */ #define LIBOBS_API_PATCH_VER 3 -#define MAKE_SEMANTIC_VERSION(major, minor, patch) \ - ((major << 24) | (minor << 16) | patch) +#define MAKE_SEMANTIC_VERSION(major, minor, patch) ((major << 24) | (minor << 16) | patch) -#define LIBOBS_API_VER \ - MAKE_SEMANTIC_VERSION(LIBOBS_API_MAJOR_VER, LIBOBS_API_MINOR_VER, \ - LIBOBS_API_PATCH_VER) +#define LIBOBS_API_VER MAKE_SEMANTIC_VERSION(LIBOBS_API_MAJOR_VER, LIBOBS_API_MINOR_VER, LIBOBS_API_PATCH_VER) #ifdef HAVE_OBSCONFIG_H #include "obsconfig.h" diff --git a/libobs/obs-data.c b/libobs/obs-data.c index be2d07293..c9721c266 100644 --- a/libobs/obs-data.c +++ b/libobs/obs-data.c @@ -124,8 +124,8 @@ static inline void *get_item_autoselect_data(struct obs_data_item *item) static inline size_t obs_data_item_total_size(struct obs_data_item *item) { - return sizeof(struct obs_data_item) + item->name_len + item->data_len + - item->default_len + item->autoselect_size; + return sizeof(struct obs_data_item) + item->name_len + item->data_len + item->default_len + + item->autoselect_size; } static inline obs_data_t *get_item_obj(struct obs_data_item *item) @@ -167,8 +167,7 @@ static inline obs_data_array_t *get_item_array(struct obs_data_item *item) return array ? *array : NULL; } -static inline obs_data_array_t * -get_item_default_array(struct obs_data_item *item) +static inline obs_data_array_t *get_item_default_array(struct obs_data_item *item) { if (!item || !item->default_size) return NULL; @@ -176,8 +175,7 @@ get_item_default_array(struct obs_data_item *item) return *(obs_data_array_t **)get_default_data_ptr(item); } -static inline obs_data_array_t * -get_item_autoselect_array(struct obs_data_item *item) +static inline obs_data_array_t *get_item_autoselect_array(struct obs_data_item *item) { if (!item || !item->autoselect_size) return NULL; @@ -263,11 +261,8 @@ static inline void item_autoselect_data_addref(struct obs_data_item *item) } } -static struct obs_data_item *obs_data_item_create(const char *name, - const void *data, size_t size, - enum obs_data_type type, - bool default_data, - bool autoselect_data) +static struct obs_data_item *obs_data_item_create(const char *name, const void *data, size_t size, + enum obs_data_type type, bool default_data, bool autoselect_data) { struct obs_data_item *item; size_t name_size, total_size; @@ -315,8 +310,7 @@ static inline void obs_data_item_detach(struct obs_data_item *item) } } -static inline void obs_data_item_reattach(struct obs_data *parent, - struct obs_data_item *item) +static inline void obs_data_item_reattach(struct obs_data *parent, struct obs_data_item *item) { if (parent) { HASH_ADD_STR(parent->items, name, item); @@ -324,8 +318,7 @@ static inline void obs_data_item_reattach(struct obs_data *parent, } } -static struct obs_data_item * -obs_data_item_ensure_capacity(struct obs_data_item *item) +static struct obs_data_item *obs_data_item_ensure_capacity(struct obs_data_item *item) { size_t new_size = obs_data_item_total_size(item); struct obs_data_item *new_item; @@ -357,8 +350,7 @@ static inline void obs_data_item_destroy(struct obs_data_item *item) bfree(item); } -static inline void move_data(obs_data_item_t *old_item, void *old_data, - obs_data_item_t *item, void *data, size_t len) +static inline void move_data(obs_data_item_t *old_item, void *old_data, obs_data_item_t *item, void *data, size_t len) { ptrdiff_t old_offset = (uint8_t *)old_data - (uint8_t *)old_item; ptrdiff_t new_offset = (uint8_t *)data - (uint8_t *)item; @@ -366,32 +358,26 @@ static inline void move_data(obs_data_item_t *old_item, void *old_data, if (!old_data) return; - memmove((uint8_t *)item + new_offset, (uint8_t *)item + old_offset, - len); + memmove((uint8_t *)item + new_offset, (uint8_t *)item + old_offset, len); } -static inline void obs_data_item_setdata(struct obs_data_item **p_item, - const void *data, size_t size, +static inline void obs_data_item_setdata(struct obs_data_item **p_item, const void *data, size_t size, enum obs_data_type type) { if (!p_item || !*p_item) return; struct obs_data_item *item = *p_item; - ptrdiff_t old_default_data_pos = - (uint8_t *)get_default_data_ptr(item) - (uint8_t *)item; + ptrdiff_t old_default_data_pos = (uint8_t *)get_default_data_ptr(item) - (uint8_t *)item; item_data_release(item); item->data_size = size; item->type = type; - item->data_len = (item->default_size || item->autoselect_size) - ? get_align_size(size) - : size; + item->data_len = (item->default_size || item->autoselect_size) ? get_align_size(size) : size; item = obs_data_item_ensure_capacity(item); if (item->default_size || item->autoselect_size) - memmove(get_default_data_ptr(item), - (uint8_t *)item + old_default_data_pos, + memmove(get_default_data_ptr(item), (uint8_t *)item + old_default_data_pos, item->default_len + item->autoselect_size); if (size) { @@ -402,8 +388,7 @@ static inline void obs_data_item_setdata(struct obs_data_item **p_item, *p_item = item; } -static inline void obs_data_item_set_default_data(struct obs_data_item **p_item, - const void *data, size_t size, +static inline void obs_data_item_set_default_data(struct obs_data_item **p_item, const void *data, size_t size, enum obs_data_type type) { if (!p_item || !*p_item) @@ -420,8 +405,7 @@ static inline void obs_data_item_set_default_data(struct obs_data_item **p_item, item = obs_data_item_ensure_capacity(item); if (item->autoselect_size) - move_data(*p_item, old_autoselect_data, item, - get_autoselect_data_ptr(item), item->autoselect_size); + move_data(*p_item, old_autoselect_data, item, get_autoselect_data_ptr(item), item->autoselect_size); if (size) { memcpy(get_item_default_data(item), data, size); @@ -431,10 +415,8 @@ static inline void obs_data_item_set_default_data(struct obs_data_item **p_item, *p_item = item; } -static inline void -obs_data_item_set_autoselect_data(struct obs_data_item **p_item, - const void *data, size_t size, - enum obs_data_type type) +static inline void obs_data_item_set_autoselect_data(struct obs_data_item **p_item, const void *data, size_t size, + enum obs_data_type type) { if (!p_item || !*p_item) return; @@ -445,8 +427,7 @@ obs_data_item_set_autoselect_data(struct obs_data_item **p_item, item->autoselect_size = size; item->type = type; item->data_len = item->data_size ? get_align_size(item->data_size) : 0; - item->default_len = - item->default_size ? get_align_size(item->default_size) : 0; + item->default_len = item->default_size ? get_align_size(item->default_size) : 0; item = obs_data_item_ensure_capacity(item); if (size) { @@ -459,8 +440,7 @@ obs_data_item_set_autoselect_data(struct obs_data_item **p_item, /* ------------------------------------------------------------------------- */ -static void obs_data_add_json_item(obs_data_t *data, const char *key, - json_t *json); +static void obs_data_add_json_item(obs_data_t *data, const char *key, json_t *json); static inline void obs_data_add_json_object_data(obs_data_t *data, json_t *jobj) { @@ -472,8 +452,7 @@ static inline void obs_data_add_json_object_data(obs_data_t *data, json_t *jobj) } } -static inline void obs_data_add_json_object(obs_data_t *data, const char *key, - json_t *jobj) +static inline void obs_data_add_json_object(obs_data_t *data, const char *key, json_t *jobj) { obs_data_t *sub_obj = obs_data_create(); @@ -482,8 +461,7 @@ static inline void obs_data_add_json_object(obs_data_t *data, const char *key, obs_data_release(sub_obj); } -static void obs_data_add_json_array(obs_data_t *data, const char *key, - json_t *jarray) +static void obs_data_add_json_array(obs_data_t *data, const char *key, json_t *jarray) { obs_data_array_t *array = obs_data_array_create(); size_t idx; @@ -505,8 +483,7 @@ static void obs_data_add_json_array(obs_data_t *data, const char *key, obs_data_array_release(array); } -static void obs_data_add_json_item(obs_data_t *data, const char *key, - json_t *json) +static void obs_data_add_json_item(obs_data_t *data, const char *key, json_t *json) { if (json_is_object(json)) obs_data_add_json_object(data, key, json); @@ -526,15 +503,13 @@ static void obs_data_add_json_item(obs_data_t *data, const char *key, /* ------------------------------------------------------------------------- */ -static inline void set_json_string(json_t *json, const char *name, - obs_data_item_t *item) +static inline void set_json_string(json_t *json, const char *name, obs_data_item_t *item) { const char *val = obs_data_item_get_string(item); json_object_set_new(json, name, json_string(val)); } -static inline void set_json_number(json_t *json, const char *name, - obs_data_item_t *item) +static inline void set_json_number(json_t *json, const char *name, obs_data_item_t *item) { enum obs_data_number_type type = obs_data_item_numtype(item); @@ -547,8 +522,7 @@ static inline void set_json_number(json_t *json, const char *name, } } -static inline void set_json_bool(json_t *json, const char *name, - obs_data_item_t *item) +static inline void set_json_bool(json_t *json, const char *name, obs_data_item_t *item) { bool val = obs_data_item_get_bool(item); json_object_set_new(json, name, val ? json_true() : json_false()); @@ -556,16 +530,14 @@ static inline void set_json_bool(json_t *json, const char *name, static json_t *obs_data_to_json(obs_data_t *data, bool with_defaults); -static inline void set_json_obj(json_t *json, const char *name, - obs_data_item_t *item, bool with_defaults) +static inline void set_json_obj(json_t *json, const char *name, obs_data_item_t *item, bool with_defaults) { obs_data_t *obj = obs_data_item_get_obj(item); json_object_set_new(json, name, obs_data_to_json(obj, with_defaults)); obs_data_release(obj); } -static inline void set_json_array(json_t *json, const char *name, - obs_data_item_t *item, bool with_defaults) +static inline void set_json_array(json_t *json, const char *name, obs_data_item_t *item, bool with_defaults) { json_t *jarray = json_array(); obs_data_array_t *array = obs_data_item_get_array(item); @@ -656,8 +628,7 @@ obs_data_t *obs_data_create_from_json_file(const char *json_file) return data; } -obs_data_t *obs_data_create_from_json_file_safe(const char *json_file, - const char *backup_ext) +obs_data_t *obs_data_create_from_json_file_safe(const char *json_file, const char *backup_ext) { obs_data_t *file_data = obs_data_create_from_json_file(json_file); if (!file_data && backup_ext && *backup_ext) { @@ -669,10 +640,9 @@ obs_data_t *obs_data_create_from_json_file_safe(const char *json_file, dstr_cat(&backup_file, backup_ext); if (os_file_exists(backup_file.array)) { - blog(LOG_WARNING, - "obs-data.c: " - "[obs_data_create_from_json_file_safe] " - "attempting backup file"); + blog(LOG_WARNING, "obs-data.c: " + "[obs_data_create_from_json_file_safe] " + "attempting backup file"); /* delete current file if corrupt to prevent it from * being backed up again */ @@ -716,8 +686,7 @@ void obs_data_release(obs_data_t *data) obs_data_destroy(data); } -static const char *obs_data_get_json_internal(obs_data_t *data, bool pretty, - bool with_defaults) +static const char *obs_data_get_json_internal(obs_data_t *data, bool pretty, bool with_defaults) { if (!data) return NULL; @@ -770,35 +739,29 @@ bool obs_data_save_json(obs_data_t *data, const char *file) const char *json = obs_data_get_json(data); if (json && *json) { - return os_quick_write_utf8_file(file, json, strlen(json), - false); + return os_quick_write_utf8_file(file, json, strlen(json), false); } return false; } -bool obs_data_save_json_safe(obs_data_t *data, const char *file, - const char *temp_ext, const char *backup_ext) +bool obs_data_save_json_safe(obs_data_t *data, const char *file, const char *temp_ext, const char *backup_ext) { const char *json = obs_data_get_json(data); if (json && *json) { - return os_quick_write_utf8_file_safe( - file, json, strlen(json), false, temp_ext, backup_ext); + return os_quick_write_utf8_file_safe(file, json, strlen(json), false, temp_ext, backup_ext); } return false; } -bool obs_data_save_json_pretty_safe(obs_data_t *data, const char *file, - const char *temp_ext, - const char *backup_ext) +bool obs_data_save_json_pretty_safe(obs_data_t *data, const char *file, const char *temp_ext, const char *backup_ext) { const char *json = obs_data_get_json_pretty(data); if (json && *json) { - return os_quick_write_utf8_file_safe( - file, json, strlen(json), false, temp_ext, backup_ext); + return os_quick_write_utf8_file_safe(file, json, strlen(json), false, temp_ext, backup_ext); } return false; @@ -830,8 +793,7 @@ obs_data_t *obs_data_get_defaults(obs_data_t *data) break; case OBS_DATA_STRING: { - const char *str = - obs_data_get_default_string(data, name); + const char *str = obs_data_get_default_string(data, name); obs_data_set_string(defaults, name, str); break; } @@ -839,15 +801,13 @@ obs_data_t *obs_data_get_defaults(obs_data_t *data) case OBS_DATA_NUMBER: { switch (obs_data_item_numtype(item)) { case OBS_DATA_NUM_DOUBLE: { - double val = - obs_data_get_default_double(data, name); + double val = obs_data_get_default_double(data, name); obs_data_set_double(defaults, name, val); break; } case OBS_DATA_NUM_INT: { - long long val = - obs_data_get_default_int(data, name); + long long val = obs_data_get_default_int(data, name); obs_data_set_int(defaults, name, val); break; } @@ -876,12 +836,10 @@ obs_data_t *obs_data_get_defaults(obs_data_t *data) } case OBS_DATA_ARRAY: { - obs_data_array_t *arr = - obs_data_get_default_array(data, name); + obs_data_array_t *arr = obs_data_get_default_array(data, name); obs_data_array_t *defs = obs_data_array_create(); - obs_data_array_enum(arr, get_defaults_array_cb, - (void *)defs); + obs_data_array_enum(arr, get_defaults_array_cb, (void *)defs); obs_data_set_array(defaults, name, defs); obs_data_array_release(defs); @@ -904,16 +862,13 @@ static struct obs_data_item *get_item(struct obs_data *data, const char *name) return item; } -static void set_item_data(struct obs_data *data, struct obs_data_item **item, - const char *name, const void *ptr, size_t size, - enum obs_data_type type, bool default_data, - bool autoselect_data) +static void set_item_data(struct obs_data *data, struct obs_data_item **item, const char *name, const void *ptr, + size_t size, enum obs_data_type type, bool default_data, bool autoselect_data) { obs_data_item_t *new_item = NULL; if ((!item || !*item) && data) { - new_item = obs_data_item_create(name, ptr, size, type, - default_data, autoselect_data); + new_item = obs_data_item_create(name, ptr, size, type, default_data, autoselect_data); new_item->parent = data; HASH_ADD_STR(data->items, name, new_item); @@ -926,9 +881,8 @@ static void set_item_data(struct obs_data *data, struct obs_data_item **item, } } -static inline void set_item(struct obs_data *data, obs_data_item_t **item, - const char *name, const void *ptr, size_t size, - enum obs_data_type type) +static inline void set_item(struct obs_data *data, obs_data_item_t **item, const char *name, const void *ptr, + size_t size, enum obs_data_type type) { obs_data_item_t *actual_item = NULL; @@ -943,9 +897,8 @@ static inline void set_item(struct obs_data *data, obs_data_item_t **item, set_item_data(data, item, name, ptr, size, type, false, false); } -static inline void set_item_def(struct obs_data *data, obs_data_item_t **item, - const char *name, const void *ptr, size_t size, - enum obs_data_type type) +static inline void set_item_def(struct obs_data *data, obs_data_item_t **item, const char *name, const void *ptr, + size_t size, enum obs_data_type type) { obs_data_item_t *actual_item = NULL; @@ -963,9 +916,8 @@ static inline void set_item_def(struct obs_data *data, obs_data_item_t **item, set_item_data(data, item, name, ptr, size, type, true, false); } -static inline void set_item_auto(struct obs_data *data, obs_data_item_t **item, - const char *name, const void *ptr, size_t size, - enum obs_data_type type) +static inline void set_item_auto(struct obs_data *data, obs_data_item_t **item, const char *name, const void *ptr, + size_t size, enum obs_data_type type) { obs_data_item_t *actual_item = NULL; @@ -980,8 +932,7 @@ static inline void set_item_auto(struct obs_data *data, obs_data_item_t **item, set_item_data(data, item, name, ptr, size, type, false, true); } -static void copy_obj(struct obs_data *data, const char *name, - struct obs_data *obj, +static void copy_obj(struct obs_data *data, const char *name, struct obs_data *obj, void (*callback)(obs_data_t *, const char *, obs_data_t *)) { if (obj) { @@ -992,10 +943,8 @@ static void copy_obj(struct obs_data *data, const char *name, } } -static void copy_array(struct obs_data *data, const char *name, - struct obs_data_array *array, - void (*callback)(obs_data_t *, const char *, - obs_data_array_t *)) +static void copy_array(struct obs_data *data, const char *name, struct obs_data_array *array, + void (*callback)(obs_data_t *, const char *, obs_data_array_t *)) { if (array) { obs_data_array_t *new_array = obs_data_array_create(); @@ -1035,8 +984,7 @@ static inline void copy_item(struct obs_data *data, struct obs_data_item *item) } else { if (item->data_size) - set_item(data, NULL, name, ptr, item->data_size, - item->type); + set_item(data, NULL, name, ptr, item->data_size, item->type); } } @@ -1101,11 +1049,9 @@ void obs_data_clear(obs_data_t *target) } } -typedef void (*set_item_t)(obs_data_t *, obs_data_item_t **, const char *, - const void *, size_t, enum obs_data_type); +typedef void (*set_item_t)(obs_data_t *, obs_data_item_t **, const char *, const void *, size_t, enum obs_data_type); -static inline void obs_set_string(obs_data_t *data, obs_data_item_t **item, - const char *name, const char *val, +static inline void obs_set_string(obs_data_t *data, obs_data_item_t **item, const char *name, const char *val, set_item_t set_item_) { if (!val) @@ -1113,53 +1059,43 @@ static inline void obs_set_string(obs_data_t *data, obs_data_item_t **item, set_item_(data, item, name, val, strlen(val) + 1, OBS_DATA_STRING); } -static inline void obs_set_int(obs_data_t *data, obs_data_item_t **item, - const char *name, long long val, +static inline void obs_set_int(obs_data_t *data, obs_data_item_t **item, const char *name, long long val, set_item_t set_item_) { struct obs_data_number num; num.type = OBS_DATA_NUM_INT; num.int_val = val; - set_item_(data, item, name, &num, sizeof(struct obs_data_number), - OBS_DATA_NUMBER); + set_item_(data, item, name, &num, sizeof(struct obs_data_number), OBS_DATA_NUMBER); } -static inline void obs_set_double(obs_data_t *data, obs_data_item_t **item, - const char *name, double val, +static inline void obs_set_double(obs_data_t *data, obs_data_item_t **item, const char *name, double val, set_item_t set_item_) { struct obs_data_number num; num.type = OBS_DATA_NUM_DOUBLE; num.double_val = val; - set_item_(data, item, name, &num, sizeof(struct obs_data_number), - OBS_DATA_NUMBER); + set_item_(data, item, name, &num, sizeof(struct obs_data_number), OBS_DATA_NUMBER); } -static inline void obs_set_bool(obs_data_t *data, obs_data_item_t **item, - const char *name, bool val, +static inline void obs_set_bool(obs_data_t *data, obs_data_item_t **item, const char *name, bool val, set_item_t set_item_) { set_item_(data, item, name, &val, sizeof(bool), OBS_DATA_BOOLEAN); } -static inline void obs_set_obj(obs_data_t *data, obs_data_item_t **item, - const char *name, obs_data_t *obj, +static inline void obs_set_obj(obs_data_t *data, obs_data_item_t **item, const char *name, obs_data_t *obj, set_item_t set_item_) { - set_item_(data, item, name, &obj, sizeof(obs_data_t *), - OBS_DATA_OBJECT); + set_item_(data, item, name, &obj, sizeof(obs_data_t *), OBS_DATA_OBJECT); } -static inline void obs_set_array(obs_data_t *data, obs_data_item_t **item, - const char *name, obs_data_array_t *array, +static inline void obs_set_array(obs_data_t *data, obs_data_item_t **item, const char *name, obs_data_array_t *array, set_item_t set_item_) { - set_item_(data, item, name, &array, sizeof(obs_data_t *), - OBS_DATA_ARRAY); + set_item_(data, item, name, &array, sizeof(obs_data_t *), OBS_DATA_ARRAY); } -static inline void obs_take_obj(obs_data_t *data, obs_data_item_t **item, - const char *name, obs_data_t *obj, +static inline void obs_take_obj(obs_data_t *data, obs_data_item_t **item, const char *name, obs_data_t *obj, set_item_t set_item_) { obs_set_obj(data, item, name, obj, set_item_); @@ -1191,14 +1127,12 @@ void obs_data_set_obj(obs_data_t *data, const char *name, obs_data_t *obj) obs_set_obj(data, NULL, name, obj, set_item); } -void obs_data_set_array(obs_data_t *data, const char *name, - obs_data_array_t *array) +void obs_data_set_array(obs_data_t *data, const char *name, obs_data_array_t *array) { obs_set_array(data, NULL, name, array, set_item); } -void obs_data_set_default_string(obs_data_t *data, const char *name, - const char *val) +void obs_data_set_default_string(obs_data_t *data, const char *name, const char *val) { obs_set_string(data, NULL, name, val, set_item_def); } @@ -1218,32 +1152,27 @@ void obs_data_set_default_bool(obs_data_t *data, const char *name, bool val) obs_set_bool(data, NULL, name, val, set_item_def); } -void obs_data_set_default_obj(obs_data_t *data, const char *name, - obs_data_t *obj) +void obs_data_set_default_obj(obs_data_t *data, const char *name, obs_data_t *obj) { obs_set_obj(data, NULL, name, obj, set_item_def); } -void obs_data_set_default_array(obs_data_t *data, const char *name, - obs_data_array_t *arr) +void obs_data_set_default_array(obs_data_t *data, const char *name, obs_data_array_t *arr) { obs_set_array(data, NULL, name, arr, set_item_def); } -void obs_data_set_autoselect_string(obs_data_t *data, const char *name, - const char *val) +void obs_data_set_autoselect_string(obs_data_t *data, const char *name, const char *val) { obs_set_string(data, NULL, name, val, set_item_auto); } -void obs_data_set_autoselect_int(obs_data_t *data, const char *name, - long long val) +void obs_data_set_autoselect_int(obs_data_t *data, const char *name, long long val) { obs_set_int(data, NULL, name, val, set_item_auto); } -void obs_data_set_autoselect_double(obs_data_t *data, const char *name, - double val) +void obs_data_set_autoselect_double(obs_data_t *data, const char *name, double val) { obs_set_double(data, NULL, name, val, set_item_auto); } @@ -1253,14 +1182,12 @@ void obs_data_set_autoselect_bool(obs_data_t *data, const char *name, bool val) obs_set_bool(data, NULL, name, val, set_item_auto); } -void obs_data_set_autoselect_obj(obs_data_t *data, const char *name, - obs_data_t *obj) +void obs_data_set_autoselect_obj(obs_data_t *data, const char *name, obs_data_t *obj) { obs_set_obj(data, NULL, name, obj, set_item_auto); } -void obs_data_set_autoselect_array(obs_data_t *data, const char *name, - obs_data_array_t *arr) +void obs_data_set_autoselect_array(obs_data_t *data, const char *name, obs_data_array_t *arr) { obs_set_array(data, NULL, name, arr, set_item_auto); } @@ -1350,8 +1277,7 @@ obs_data_t *obs_data_get_autoselect_obj(obs_data_t *data, const char *name) return obs_data_item_get_autoselect_obj(get_item(data, name)); } -obs_data_array_t *obs_data_get_autoselect_array(obs_data_t *data, - const char *name) +obs_data_array_t *obs_data_get_autoselect_array(obs_data_t *data, const char *name) { return obs_data_item_get_autoselect_array(get_item(data, name)); } @@ -1426,8 +1352,7 @@ void obs_data_array_insert(obs_data_array_t *array, size_t idx, obs_data_t *obj) da_insert(array->objects, idx, &obj); } -void obs_data_array_push_back_array(obs_data_array_t *array, - obs_data_array_t *array2) +void obs_data_array_push_back_array(obs_data_array_t *array, obs_data_array_t *array2) { if (!array || !array2) return; @@ -1447,8 +1372,7 @@ void obs_data_array_erase(obs_data_array_t *array, size_t idx) } } -void obs_data_array_enum(obs_data_array_t *array, - void (*cb)(obs_data_t *data, void *param), void *param) +void obs_data_array_enum(obs_data_array_t *array, void (*cb)(obs_data_t *data, void *param), void *param) { if (array && cb) { for (size_t i = 0; i < array->objects.num; i++) { @@ -1520,8 +1444,7 @@ void obs_data_item_unset_user_value(obs_data_item_t *item) item->data_len = 0; if (item->default_size || item->autoselect_size) - move_data(item, old_non_user_data, item, - get_default_data_ptr(item), + move_data(item, old_non_user_data, item, get_default_data_ptr(item), item->default_len + item->autoselect_size); } @@ -1537,8 +1460,7 @@ void obs_data_item_unset_default_value(obs_data_item_t *item) item->default_len = 0; if (item->autoselect_size) - move_data(item, old_autoselect_data, item, - get_autoselect_data_ptr(item), item->autoselect_size); + move_data(item, old_autoselect_data, item, get_autoselect_data_ptr(item), item->autoselect_size); } void obs_data_item_unset_autoselect_value(obs_data_item_t *item) @@ -1692,14 +1614,12 @@ void obs_data_item_set_default_obj(obs_data_item_t **item, obs_data_t *val) obs_set_obj(NULL, item, NULL, val, set_item_def); } -void obs_data_item_set_default_array(obs_data_item_t **item, - obs_data_array_t *val) +void obs_data_item_set_default_array(obs_data_item_t **item, obs_data_array_t *val) { obs_set_array(NULL, item, NULL, val, set_item_def); } -void obs_data_item_set_autoselect_string(obs_data_item_t **item, - const char *val) +void obs_data_item_set_autoselect_string(obs_data_item_t **item, const char *val) { obs_set_string(NULL, item, NULL, val, set_item_auto); } @@ -1724,87 +1644,69 @@ void obs_data_item_set_autoselect_obj(obs_data_item_t **item, obs_data_t *val) obs_set_obj(NULL, item, NULL, val, set_item_auto); } -void obs_data_item_set_autoselect_array(obs_data_item_t **item, - obs_data_array_t *val) +void obs_data_item_set_autoselect_array(obs_data_item_t **item, obs_data_array_t *val) { obs_set_array(NULL, item, NULL, val, set_item_auto); } -static inline bool item_valid(struct obs_data_item *item, - enum obs_data_type type) +static inline bool item_valid(struct obs_data_item *item, enum obs_data_type type) { return item && item->type == type; } typedef void *(*get_data_t)(obs_data_item_t *); -static inline const char *data_item_get_string(obs_data_item_t *item, - get_data_t get_data) +static inline const char *data_item_get_string(obs_data_item_t *item, get_data_t get_data) { const char *str; - return item_valid(item, OBS_DATA_STRING) && (str = get_data(item)) ? str - : ""; + return item_valid(item, OBS_DATA_STRING) && (str = get_data(item)) ? str : ""; } -static inline long long item_int(struct obs_data_item *item, - get_data_t get_data) +static inline long long item_int(struct obs_data_item *item, get_data_t get_data) { struct obs_data_number *num; if (item && (num = get_data(item))) { - return (num->type == OBS_DATA_NUM_INT) - ? num->int_val - : (long long)num->double_val; + return (num->type == OBS_DATA_NUM_INT) ? num->int_val : (long long)num->double_val; } return 0; } -static inline long long data_item_get_int(obs_data_item_t *item, - get_data_t get_data) +static inline long long data_item_get_int(obs_data_item_t *item, get_data_t get_data) { - return item_int(item_valid(item, OBS_DATA_NUMBER) ? item : NULL, - get_data); + return item_int(item_valid(item, OBS_DATA_NUMBER) ? item : NULL, get_data); } -static inline double item_double(struct obs_data_item *item, - get_data_t get_data) +static inline double item_double(struct obs_data_item *item, get_data_t get_data) { struct obs_data_number *num; if (item && (num = get_data(item))) { - return (num->type == OBS_DATA_NUM_INT) ? (double)num->int_val - : num->double_val; + return (num->type == OBS_DATA_NUM_INT) ? (double)num->int_val : num->double_val; } return 0.0; } -static inline double data_item_get_double(obs_data_item_t *item, - get_data_t get_data) +static inline double data_item_get_double(obs_data_item_t *item, get_data_t get_data) { - return item_double(item_valid(item, OBS_DATA_NUMBER) ? item : NULL, - get_data); + return item_double(item_valid(item, OBS_DATA_NUMBER) ? item : NULL, get_data); } -static inline bool data_item_get_bool(obs_data_item_t *item, - get_data_t get_data) +static inline bool data_item_get_bool(obs_data_item_t *item, get_data_t get_data) { bool *data; - return item_valid(item, OBS_DATA_BOOLEAN) && (data = get_data(item)) - ? *data - : false; + return item_valid(item, OBS_DATA_BOOLEAN) && (data = get_data(item)) ? *data : false; } typedef obs_data_t *(*get_obj_t)(obs_data_item_t *); -static inline obs_data_t *data_item_get_obj(obs_data_item_t *item, - get_obj_t get_obj) +static inline obs_data_t *data_item_get_obj(obs_data_item_t *item, get_obj_t get_obj) { - obs_data_t *obj = item_valid(item, OBS_DATA_OBJECT) ? get_obj(item) - : NULL; + obs_data_t *obj = item_valid(item, OBS_DATA_OBJECT) ? get_obj(item) : NULL; if (obj) os_atomic_inc_long(&obj->ref); @@ -1813,11 +1715,9 @@ static inline obs_data_t *data_item_get_obj(obs_data_item_t *item, typedef obs_data_array_t *(*get_array_t)(obs_data_item_t *); -static inline obs_data_array_t *data_item_get_array(obs_data_item_t *item, - get_array_t get_array) +static inline obs_data_array_t *data_item_get_array(obs_data_item_t *item, get_array_t get_array) { - obs_data_array_t *array = - item_valid(item, OBS_DATA_ARRAY) ? get_array(item) : NULL; + obs_data_array_t *array = item_valid(item, OBS_DATA_ARRAY) ? get_array(item) : NULL; if (array) os_atomic_inc_long(&array->ref); @@ -1919,8 +1819,7 @@ obs_data_array_t *obs_data_item_get_autoselect_array(obs_data_item_t *item) typedef void (*set_obj_t)(obs_data_t *, const char *, obs_data_t *); -static inline void set_vec2(obs_data_t *data, const char *name, - const struct vec2 *val, set_obj_t set_obj) +static inline void set_vec2(obs_data_t *data, const char *name, const struct vec2 *val, set_obj_t set_obj) { obs_data_t *obj = obs_data_create(); obs_data_set_double(obj, "x", val->x); @@ -1929,8 +1828,7 @@ static inline void set_vec2(obs_data_t *data, const char *name, obs_data_release(obj); } -static inline void set_vec3(obs_data_t *data, const char *name, - const struct vec3 *val, set_obj_t set_obj) +static inline void set_vec3(obs_data_t *data, const char *name, const struct vec3 *val, set_obj_t set_obj) { obs_data_t *obj = obs_data_create(); obs_data_set_double(obj, "x", val->x); @@ -1940,8 +1838,7 @@ static inline void set_vec3(obs_data_t *data, const char *name, obs_data_release(obj); } -static inline void set_vec4(obs_data_t *data, const char *name, - const struct vec4 *val, set_obj_t set_obj) +static inline void set_vec4(obs_data_t *data, const char *name, const struct vec4 *val, set_obj_t set_obj) { obs_data_t *obj = obs_data_create(); obs_data_set_double(obj, "x", val->x); @@ -1952,8 +1849,7 @@ static inline void set_vec4(obs_data_t *data, const char *name, obs_data_release(obj); } -static inline void set_quat(obs_data_t *data, const char *name, - const struct quat *val, set_obj_t set_obj) +static inline void set_quat(obs_data_t *data, const char *name, const struct quat *val, set_obj_t set_obj) { obs_data_t *obj = obs_data_create(); obs_data_set_double(obj, "x", val->x); @@ -1964,74 +1860,62 @@ static inline void set_quat(obs_data_t *data, const char *name, obs_data_release(obj); } -void obs_data_set_vec2(obs_data_t *data, const char *name, - const struct vec2 *val) +void obs_data_set_vec2(obs_data_t *data, const char *name, const struct vec2 *val) { set_vec2(data, name, val, obs_data_set_obj); } -void obs_data_set_vec3(obs_data_t *data, const char *name, - const struct vec3 *val) +void obs_data_set_vec3(obs_data_t *data, const char *name, const struct vec3 *val) { set_vec3(data, name, val, obs_data_set_obj); } -void obs_data_set_vec4(obs_data_t *data, const char *name, - const struct vec4 *val) +void obs_data_set_vec4(obs_data_t *data, const char *name, const struct vec4 *val) { set_vec4(data, name, val, obs_data_set_obj); } -void obs_data_set_quat(obs_data_t *data, const char *name, - const struct quat *val) +void obs_data_set_quat(obs_data_t *data, const char *name, const struct quat *val) { set_quat(data, name, val, obs_data_set_obj); } -void obs_data_set_default_vec2(obs_data_t *data, const char *name, - const struct vec2 *val) +void obs_data_set_default_vec2(obs_data_t *data, const char *name, const struct vec2 *val) { set_vec2(data, name, val, obs_data_set_default_obj); } -void obs_data_set_default_vec3(obs_data_t *data, const char *name, - const struct vec3 *val) +void obs_data_set_default_vec3(obs_data_t *data, const char *name, const struct vec3 *val) { set_vec3(data, name, val, obs_data_set_default_obj); } -void obs_data_set_default_vec4(obs_data_t *data, const char *name, - const struct vec4 *val) +void obs_data_set_default_vec4(obs_data_t *data, const char *name, const struct vec4 *val) { set_vec4(data, name, val, obs_data_set_default_obj); } -void obs_data_set_default_quat(obs_data_t *data, const char *name, - const struct quat *val) +void obs_data_set_default_quat(obs_data_t *data, const char *name, const struct quat *val) { set_quat(data, name, val, obs_data_set_default_obj); } -void obs_data_set_autoselect_vec2(obs_data_t *data, const char *name, - const struct vec2 *val) +void obs_data_set_autoselect_vec2(obs_data_t *data, const char *name, const struct vec2 *val) { set_vec2(data, name, val, obs_data_set_autoselect_obj); } -void obs_data_set_autoselect_vec3(obs_data_t *data, const char *name, - const struct vec3 *val) +void obs_data_set_autoselect_vec3(obs_data_t *data, const char *name, const struct vec3 *val) { set_vec3(data, name, val, obs_data_set_autoselect_obj); } -void obs_data_set_autoselect_vec4(obs_data_t *data, const char *name, - const struct vec4 *val) +void obs_data_set_autoselect_vec4(obs_data_t *data, const char *name, const struct vec4 *val) { set_vec4(data, name, val, obs_data_set_autoselect_obj); } -void obs_data_set_autoselect_quat(obs_data_t *data, const char *name, - const struct quat *val) +void obs_data_set_autoselect_quat(obs_data_t *data, const char *name, const struct quat *val) { set_quat(data, name, val, obs_data_set_autoselect_obj); } @@ -2101,50 +1985,42 @@ void obs_data_get_quat(obs_data_t *data, const char *name, struct quat *val) get_quat(obs_data_get_obj(data, name), val); } -void obs_data_get_default_vec2(obs_data_t *data, const char *name, - struct vec2 *val) +void obs_data_get_default_vec2(obs_data_t *data, const char *name, struct vec2 *val) { get_vec2(obs_data_get_default_obj(data, name), val); } -void obs_data_get_default_vec3(obs_data_t *data, const char *name, - struct vec3 *val) +void obs_data_get_default_vec3(obs_data_t *data, const char *name, struct vec3 *val) { get_vec3(obs_data_get_default_obj(data, name), val); } -void obs_data_get_default_vec4(obs_data_t *data, const char *name, - struct vec4 *val) +void obs_data_get_default_vec4(obs_data_t *data, const char *name, struct vec4 *val) { get_vec4(obs_data_get_default_obj(data, name), val); } -void obs_data_get_default_quat(obs_data_t *data, const char *name, - struct quat *val) +void obs_data_get_default_quat(obs_data_t *data, const char *name, struct quat *val) { get_quat(obs_data_get_default_obj(data, name), val); } -void obs_data_get_autoselect_vec2(obs_data_t *data, const char *name, - struct vec2 *val) +void obs_data_get_autoselect_vec2(obs_data_t *data, const char *name, struct vec2 *val) { get_vec2(obs_data_get_autoselect_obj(data, name), val); } -void obs_data_get_autoselect_vec3(obs_data_t *data, const char *name, - struct vec3 *val) +void obs_data_get_autoselect_vec3(obs_data_t *data, const char *name, struct vec3 *val) { get_vec3(obs_data_get_autoselect_obj(data, name), val); } -void obs_data_get_autoselect_vec4(obs_data_t *data, const char *name, - struct vec4 *val) +void obs_data_get_autoselect_vec4(obs_data_t *data, const char *name, struct vec4 *val) { get_vec4(obs_data_get_autoselect_obj(data, name), val); } -void obs_data_get_autoselect_quat(obs_data_t *data, const char *name, - struct quat *val) +void obs_data_get_autoselect_quat(obs_data_t *data, const char *name, struct quat *val) { get_quat(obs_data_get_autoselect_obj(data, name), val); } @@ -2152,8 +2028,7 @@ void obs_data_get_autoselect_quat(obs_data_t *data, const char *name, /* ------------------------------------------------------------------------- */ /* Helper functions for media_frames_per_seconds */ -static inline obs_data_t * -make_frames_per_second(struct media_frames_per_second fps, const char *option) +static inline obs_data_t *make_frames_per_second(struct media_frames_per_second fps, const char *option) { obs_data_t *obj = obs_data_create(); @@ -2168,28 +2043,22 @@ make_frames_per_second(struct media_frames_per_second fps, const char *option) return obj; } -void obs_data_set_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second fps, +void obs_data_set_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second fps, const char *option) { - obs_take_obj(data, NULL, name, make_frames_per_second(fps, option), - set_item); + obs_take_obj(data, NULL, name, make_frames_per_second(fps, option), set_item); } -void obs_data_set_default_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second fps, +void obs_data_set_default_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second fps, const char *option) { - obs_take_obj(data, NULL, name, make_frames_per_second(fps, option), - set_item_def); + obs_take_obj(data, NULL, name, make_frames_per_second(fps, option), set_item_def); } -void obs_data_set_autoselect_frames_per_second( - obs_data_t *data, const char *name, struct media_frames_per_second fps, - const char *option) +void obs_data_set_autoselect_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second fps, + const char *option) { - obs_take_obj(data, NULL, name, make_frames_per_second(fps, option), - set_item_auto); + obs_take_obj(data, NULL, name, make_frames_per_second(fps, option), set_item_auto); } static inline bool get_option(obs_data_t *data, const char **option) @@ -2211,9 +2080,7 @@ static inline bool get_option(obs_data_t *data, const char **option) #define CLAMP(x, min, max) ((x) < min ? min : ((x) > max ? max : (x))) -static inline bool get_frames_per_second(obs_data_t *data, - struct media_frames_per_second *fps, - const char **option) +static inline bool get_frames_per_second(obs_data_t *data, struct media_frames_per_second *fps, const char **option) { if (!data) return false; @@ -2250,72 +2117,55 @@ free: return false; } -bool obs_data_get_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second *fps, +bool obs_data_get_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second *fps, const char **option) { return get_frames_per_second(obs_data_get_obj(data, name), fps, option); } -bool obs_data_get_default_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second *fps, +bool obs_data_get_default_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second *fps, const char **option) { - return get_frames_per_second(obs_data_get_default_obj(data, name), fps, - option); + return get_frames_per_second(obs_data_get_default_obj(data, name), fps, option); } -bool obs_data_get_autoselect_frames_per_second( - obs_data_t *data, const char *name, struct media_frames_per_second *fps, - const char **option) +bool obs_data_get_autoselect_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second *fps, + const char **option) { - return get_frames_per_second(obs_data_get_autoselect_obj(data, name), - fps, option); + return get_frames_per_second(obs_data_get_autoselect_obj(data, name), fps, option); } -void obs_data_item_set_frames_per_second(obs_data_item_t **item, - struct media_frames_per_second fps, - const char *option) +void obs_data_item_set_frames_per_second(obs_data_item_t **item, struct media_frames_per_second fps, const char *option) { - obs_take_obj(NULL, item, NULL, make_frames_per_second(fps, option), - set_item); + obs_take_obj(NULL, item, NULL, make_frames_per_second(fps, option), set_item); } -void obs_data_item_set_default_frames_per_second( - obs_data_item_t **item, struct media_frames_per_second fps, - const char *option) +void obs_data_item_set_default_frames_per_second(obs_data_item_t **item, struct media_frames_per_second fps, + const char *option) { - obs_take_obj(NULL, item, NULL, make_frames_per_second(fps, option), - set_item_def); + obs_take_obj(NULL, item, NULL, make_frames_per_second(fps, option), set_item_def); } -void obs_data_item_set_autoselect_frames_per_second( - obs_data_item_t **item, struct media_frames_per_second fps, - const char *option) +void obs_data_item_set_autoselect_frames_per_second(obs_data_item_t **item, struct media_frames_per_second fps, + const char *option) { - obs_take_obj(NULL, item, NULL, make_frames_per_second(fps, option), - set_item_auto); + obs_take_obj(NULL, item, NULL, make_frames_per_second(fps, option), set_item_auto); } -bool obs_data_item_get_frames_per_second(obs_data_item_t *item, - struct media_frames_per_second *fps, +bool obs_data_item_get_frames_per_second(obs_data_item_t *item, struct media_frames_per_second *fps, const char **option) { return get_frames_per_second(obs_data_item_get_obj(item), fps, option); } -bool obs_data_item_get_default_frames_per_second( - obs_data_item_t *item, struct media_frames_per_second *fps, - const char **option) +bool obs_data_item_get_default_frames_per_second(obs_data_item_t *item, struct media_frames_per_second *fps, + const char **option) { - return get_frames_per_second(obs_data_item_get_default_obj(item), fps, - option); + return get_frames_per_second(obs_data_item_get_default_obj(item), fps, option); } -bool obs_data_item_get_autoselect_frames_per_second( - obs_data_item_t *item, struct media_frames_per_second *fps, - const char **option) +bool obs_data_item_get_autoselect_frames_per_second(obs_data_item_t *item, struct media_frames_per_second *fps, + const char **option) { - return get_frames_per_second(obs_data_item_get_autoselect_obj(item), - fps, option); + return get_frames_per_second(obs_data_item_get_autoselect_obj(item), fps, option); } diff --git a/libobs/obs-data.h b/libobs/obs-data.h index 540cde67d..e53167c73 100644 --- a/libobs/obs-data.h +++ b/libobs/obs-data.h @@ -52,11 +52,7 @@ enum obs_data_type { OBS_DATA_ARRAY }; -enum obs_data_number_type { - OBS_DATA_NUM_INVALID, - OBS_DATA_NUM_INT, - OBS_DATA_NUM_DOUBLE -}; +enum obs_data_number_type { OBS_DATA_NUM_INVALID, OBS_DATA_NUM_INT, OBS_DATA_NUM_DOUBLE }; /* ------------------------------------------------------------------------- */ /* Main usage functions */ @@ -64,8 +60,7 @@ enum obs_data_number_type { EXPORT obs_data_t *obs_data_create(); EXPORT obs_data_t *obs_data_create_from_json(const char *json_string); EXPORT obs_data_t *obs_data_create_from_json_file(const char *json_file); -EXPORT obs_data_t *obs_data_create_from_json_file_safe(const char *json_file, - const char *backup_ext); +EXPORT obs_data_t *obs_data_create_from_json_file_safe(const char *json_file, const char *backup_ext); EXPORT void obs_data_addref(obs_data_t *data); EXPORT void obs_data_release(obs_data_t *data); @@ -75,11 +70,8 @@ EXPORT const char *obs_data_get_json_pretty(obs_data_t *data); EXPORT const char *obs_data_get_json_pretty_with_defaults(obs_data_t *data); EXPORT const char *obs_data_get_last_json(obs_data_t *data); EXPORT bool obs_data_save_json(obs_data_t *data, const char *file); -EXPORT bool obs_data_save_json_safe(obs_data_t *data, const char *file, - const char *temp_ext, - const char *backup_ext); -EXPORT bool obs_data_save_json_pretty_safe(obs_data_t *data, const char *file, - const char *temp_ext, +EXPORT bool obs_data_save_json_safe(obs_data_t *data, const char *file, const char *temp_ext, const char *backup_ext); +EXPORT bool obs_data_save_json_pretty_safe(obs_data_t *data, const char *file, const char *temp_ext, const char *backup_ext); EXPORT void obs_data_apply(obs_data_t *target, obs_data_t *apply_data); @@ -88,15 +80,12 @@ EXPORT void obs_data_erase(obs_data_t *data, const char *name); EXPORT void obs_data_clear(obs_data_t *data); /* Set functions */ -EXPORT void obs_data_set_string(obs_data_t *data, const char *name, - const char *val); +EXPORT void obs_data_set_string(obs_data_t *data, const char *name, const char *val); EXPORT void obs_data_set_int(obs_data_t *data, const char *name, long long val); EXPORT void obs_data_set_double(obs_data_t *data, const char *name, double val); EXPORT void obs_data_set_bool(obs_data_t *data, const char *name, bool val); -EXPORT void obs_data_set_obj(obs_data_t *data, const char *name, - obs_data_t *obj); -EXPORT void obs_data_set_array(obs_data_t *data, const char *name, - obs_data_array_t *array); +EXPORT void obs_data_set_obj(obs_data_t *data, const char *name, obs_data_t *obj); +EXPORT void obs_data_set_array(obs_data_t *data, const char *name, obs_data_array_t *array); /* * Creates an obs_data_t * filled with all default values. @@ -106,36 +95,24 @@ EXPORT obs_data_t *obs_data_get_defaults(obs_data_t *data); /* * Default value functions. */ -EXPORT void obs_data_set_default_string(obs_data_t *data, const char *name, - const char *val); -EXPORT void obs_data_set_default_int(obs_data_t *data, const char *name, - long long val); -EXPORT void obs_data_set_default_double(obs_data_t *data, const char *name, - double val); -EXPORT void obs_data_set_default_bool(obs_data_t *data, const char *name, - bool val); -EXPORT void obs_data_set_default_obj(obs_data_t *data, const char *name, - obs_data_t *obj); -EXPORT void obs_data_set_default_array(obs_data_t *data, const char *name, - obs_data_array_t *arr); +EXPORT void obs_data_set_default_string(obs_data_t *data, const char *name, const char *val); +EXPORT void obs_data_set_default_int(obs_data_t *data, const char *name, long long val); +EXPORT void obs_data_set_default_double(obs_data_t *data, const char *name, double val); +EXPORT void obs_data_set_default_bool(obs_data_t *data, const char *name, bool val); +EXPORT void obs_data_set_default_obj(obs_data_t *data, const char *name, obs_data_t *obj); +EXPORT void obs_data_set_default_array(obs_data_t *data, const char *name, obs_data_array_t *arr); /* * Application overrides * Use these to communicate the actual values of settings in case the user * settings aren't appropriate */ -EXPORT void obs_data_set_autoselect_string(obs_data_t *data, const char *name, - const char *val); -EXPORT void obs_data_set_autoselect_int(obs_data_t *data, const char *name, - long long val); -EXPORT void obs_data_set_autoselect_double(obs_data_t *data, const char *name, - double val); -EXPORT void obs_data_set_autoselect_bool(obs_data_t *data, const char *name, - bool val); -EXPORT void obs_data_set_autoselect_obj(obs_data_t *data, const char *name, - obs_data_t *obj); -EXPORT void obs_data_set_autoselect_array(obs_data_t *data, const char *name, - obs_data_array_t *arr); +EXPORT void obs_data_set_autoselect_string(obs_data_t *data, const char *name, const char *val); +EXPORT void obs_data_set_autoselect_int(obs_data_t *data, const char *name, long long val); +EXPORT void obs_data_set_autoselect_double(obs_data_t *data, const char *name, double val); +EXPORT void obs_data_set_autoselect_bool(obs_data_t *data, const char *name, bool val); +EXPORT void obs_data_set_autoselect_obj(obs_data_t *data, const char *name, obs_data_t *obj); +EXPORT void obs_data_set_autoselect_array(obs_data_t *data, const char *name, obs_data_array_t *arr); /* * Get functions @@ -147,26 +124,19 @@ EXPORT bool obs_data_get_bool(obs_data_t *data, const char *name); EXPORT obs_data_t *obs_data_get_obj(obs_data_t *data, const char *name); EXPORT obs_data_array_t *obs_data_get_array(obs_data_t *data, const char *name); -EXPORT const char *obs_data_get_default_string(obs_data_t *data, - const char *name); +EXPORT const char *obs_data_get_default_string(obs_data_t *data, const char *name); EXPORT long long obs_data_get_default_int(obs_data_t *data, const char *name); EXPORT double obs_data_get_default_double(obs_data_t *data, const char *name); EXPORT bool obs_data_get_default_bool(obs_data_t *data, const char *name); EXPORT obs_data_t *obs_data_get_default_obj(obs_data_t *data, const char *name); -EXPORT obs_data_array_t *obs_data_get_default_array(obs_data_t *data, - const char *name); +EXPORT obs_data_array_t *obs_data_get_default_array(obs_data_t *data, const char *name); -EXPORT const char *obs_data_get_autoselect_string(obs_data_t *data, - const char *name); -EXPORT long long obs_data_get_autoselect_int(obs_data_t *data, - const char *name); -EXPORT double obs_data_get_autoselect_double(obs_data_t *data, - const char *name); +EXPORT const char *obs_data_get_autoselect_string(obs_data_t *data, const char *name); +EXPORT long long obs_data_get_autoselect_int(obs_data_t *data, const char *name); +EXPORT double obs_data_get_autoselect_double(obs_data_t *data, const char *name); EXPORT bool obs_data_get_autoselect_bool(obs_data_t *data, const char *name); -EXPORT obs_data_t *obs_data_get_autoselect_obj(obs_data_t *data, - const char *name); -EXPORT obs_data_array_t *obs_data_get_autoselect_array(obs_data_t *data, - const char *name); +EXPORT obs_data_t *obs_data_get_autoselect_obj(obs_data_t *data, const char *name); +EXPORT obs_data_array_t *obs_data_get_autoselect_array(obs_data_t *data, const char *name); /* Array functions */ EXPORT obs_data_array_t *obs_data_array_create(); @@ -175,16 +145,11 @@ EXPORT void obs_data_array_release(obs_data_array_t *array); EXPORT size_t obs_data_array_count(obs_data_array_t *array); EXPORT obs_data_t *obs_data_array_item(obs_data_array_t *array, size_t idx); -EXPORT size_t obs_data_array_push_back(obs_data_array_t *array, - obs_data_t *obj); -EXPORT void obs_data_array_insert(obs_data_array_t *array, size_t idx, - obs_data_t *obj); -EXPORT void obs_data_array_push_back_array(obs_data_array_t *array, - obs_data_array_t *array2); +EXPORT size_t obs_data_array_push_back(obs_data_array_t *array, obs_data_t *obj); +EXPORT void obs_data_array_insert(obs_data_array_t *array, size_t idx, obs_data_t *obj); +EXPORT void obs_data_array_push_back_array(obs_data_array_t *array, obs_data_array_t *array2); EXPORT void obs_data_array_erase(obs_data_array_t *array, size_t idx); -EXPORT void obs_data_array_enum(obs_data_array_t *array, - void (*cb)(obs_data_t *data, void *param), - void *param); +EXPORT void obs_data_array_enum(obs_data_array_t *array, void (*cb)(obs_data_t *data, void *param), void *param); /* ------------------------------------------------------------------------- */ /* Item status inspection */ @@ -212,8 +177,7 @@ EXPORT void obs_data_item_unset_autoselect_value(obs_data_item_t *data); /* Item iteration */ EXPORT obs_data_item_t *obs_data_first(obs_data_t *data); -EXPORT obs_data_item_t *obs_data_item_byname(obs_data_t *data, - const char *name); +EXPORT obs_data_item_t *obs_data_item_byname(obs_data_t *data, const char *name); EXPORT bool obs_data_item_next(obs_data_item_t **item); EXPORT void obs_data_item_release(obs_data_item_t **item); EXPORT void obs_data_item_remove(obs_data_item_t **item); @@ -229,32 +193,21 @@ EXPORT void obs_data_item_set_int(obs_data_item_t **item, long long val); EXPORT void obs_data_item_set_double(obs_data_item_t **item, double val); EXPORT void obs_data_item_set_bool(obs_data_item_t **item, bool val); EXPORT void obs_data_item_set_obj(obs_data_item_t **item, obs_data_t *val); -EXPORT void obs_data_item_set_array(obs_data_item_t **item, - obs_data_array_t *val); +EXPORT void obs_data_item_set_array(obs_data_item_t **item, obs_data_array_t *val); -EXPORT void obs_data_item_set_default_string(obs_data_item_t **item, - const char *val); -EXPORT void obs_data_item_set_default_int(obs_data_item_t **item, - long long val); -EXPORT void obs_data_item_set_default_double(obs_data_item_t **item, - double val); +EXPORT void obs_data_item_set_default_string(obs_data_item_t **item, const char *val); +EXPORT void obs_data_item_set_default_int(obs_data_item_t **item, long long val); +EXPORT void obs_data_item_set_default_double(obs_data_item_t **item, double val); EXPORT void obs_data_item_set_default_bool(obs_data_item_t **item, bool val); -EXPORT void obs_data_item_set_default_obj(obs_data_item_t **item, - obs_data_t *val); -EXPORT void obs_data_item_set_default_array(obs_data_item_t **item, - obs_data_array_t *val); +EXPORT void obs_data_item_set_default_obj(obs_data_item_t **item, obs_data_t *val); +EXPORT void obs_data_item_set_default_array(obs_data_item_t **item, obs_data_array_t *val); -EXPORT void obs_data_item_set_autoselect_string(obs_data_item_t **item, - const char *val); -EXPORT void obs_data_item_set_autoselect_int(obs_data_item_t **item, - long long val); -EXPORT void obs_data_item_set_autoselect_double(obs_data_item_t **item, - double val); +EXPORT void obs_data_item_set_autoselect_string(obs_data_item_t **item, const char *val); +EXPORT void obs_data_item_set_autoselect_int(obs_data_item_t **item, long long val); +EXPORT void obs_data_item_set_autoselect_double(obs_data_item_t **item, double val); EXPORT void obs_data_item_set_autoselect_bool(obs_data_item_t **item, bool val); -EXPORT void obs_data_item_set_autoselect_obj(obs_data_item_t **item, - obs_data_t *val); -EXPORT void obs_data_item_set_autoselect_array(obs_data_item_t **item, - obs_data_array_t *val); +EXPORT void obs_data_item_set_autoselect_obj(obs_data_item_t **item, obs_data_t *val); +EXPORT void obs_data_item_set_autoselect_array(obs_data_item_t **item, obs_data_array_t *val); /* Item get functions */ EXPORT const char *obs_data_item_get_string(obs_data_item_t *item); @@ -276,114 +229,69 @@ EXPORT long long obs_data_item_get_autoselect_int(obs_data_item_t *item); EXPORT double obs_data_item_get_autoselect_double(obs_data_item_t *item); EXPORT bool obs_data_item_get_autoselect_bool(obs_data_item_t *item); EXPORT obs_data_t *obs_data_item_get_autoselect_obj(obs_data_item_t *item); -EXPORT obs_data_array_t * -obs_data_item_get_autoselect_array(obs_data_item_t *item); +EXPORT obs_data_array_t *obs_data_item_get_autoselect_array(obs_data_item_t *item); /* ------------------------------------------------------------------------- */ /* Helper functions for certain structures */ -EXPORT void obs_data_set_vec2(obs_data_t *data, const char *name, - const struct vec2 *val); -EXPORT void obs_data_set_vec3(obs_data_t *data, const char *name, - const struct vec3 *val); -EXPORT void obs_data_set_vec4(obs_data_t *data, const char *name, - const struct vec4 *val); -EXPORT void obs_data_set_quat(obs_data_t *data, const char *name, - const struct quat *val); +EXPORT void obs_data_set_vec2(obs_data_t *data, const char *name, const struct vec2 *val); +EXPORT void obs_data_set_vec3(obs_data_t *data, const char *name, const struct vec3 *val); +EXPORT void obs_data_set_vec4(obs_data_t *data, const char *name, const struct vec4 *val); +EXPORT void obs_data_set_quat(obs_data_t *data, const char *name, const struct quat *val); -EXPORT void obs_data_set_default_vec2(obs_data_t *data, const char *name, - const struct vec2 *val); -EXPORT void obs_data_set_default_vec3(obs_data_t *data, const char *name, - const struct vec3 *val); -EXPORT void obs_data_set_default_vec4(obs_data_t *data, const char *name, - const struct vec4 *val); -EXPORT void obs_data_set_default_quat(obs_data_t *data, const char *name, - const struct quat *val); +EXPORT void obs_data_set_default_vec2(obs_data_t *data, const char *name, const struct vec2 *val); +EXPORT void obs_data_set_default_vec3(obs_data_t *data, const char *name, const struct vec3 *val); +EXPORT void obs_data_set_default_vec4(obs_data_t *data, const char *name, const struct vec4 *val); +EXPORT void obs_data_set_default_quat(obs_data_t *data, const char *name, const struct quat *val); -EXPORT void obs_data_set_autoselect_vec2(obs_data_t *data, const char *name, - const struct vec2 *val); -EXPORT void obs_data_set_autoselect_vec3(obs_data_t *data, const char *name, - const struct vec3 *val); -EXPORT void obs_data_set_autoselect_vec4(obs_data_t *data, const char *name, - const struct vec4 *val); -EXPORT void obs_data_set_autoselect_quat(obs_data_t *data, const char *name, - const struct quat *val); +EXPORT void obs_data_set_autoselect_vec2(obs_data_t *data, const char *name, const struct vec2 *val); +EXPORT void obs_data_set_autoselect_vec3(obs_data_t *data, const char *name, const struct vec3 *val); +EXPORT void obs_data_set_autoselect_vec4(obs_data_t *data, const char *name, const struct vec4 *val); +EXPORT void obs_data_set_autoselect_quat(obs_data_t *data, const char *name, const struct quat *val); -EXPORT void obs_data_get_vec2(obs_data_t *data, const char *name, - struct vec2 *val); -EXPORT void obs_data_get_vec3(obs_data_t *data, const char *name, - struct vec3 *val); -EXPORT void obs_data_get_vec4(obs_data_t *data, const char *name, - struct vec4 *val); -EXPORT void obs_data_get_quat(obs_data_t *data, const char *name, - struct quat *val); +EXPORT void obs_data_get_vec2(obs_data_t *data, const char *name, struct vec2 *val); +EXPORT void obs_data_get_vec3(obs_data_t *data, const char *name, struct vec3 *val); +EXPORT void obs_data_get_vec4(obs_data_t *data, const char *name, struct vec4 *val); +EXPORT void obs_data_get_quat(obs_data_t *data, const char *name, struct quat *val); -EXPORT void obs_data_get_default_vec2(obs_data_t *data, const char *name, - struct vec2 *val); -EXPORT void obs_data_get_default_vec3(obs_data_t *data, const char *name, - struct vec3 *val); -EXPORT void obs_data_get_default_vec4(obs_data_t *data, const char *name, - struct vec4 *val); -EXPORT void obs_data_get_default_quat(obs_data_t *data, const char *name, - struct quat *val); +EXPORT void obs_data_get_default_vec2(obs_data_t *data, const char *name, struct vec2 *val); +EXPORT void obs_data_get_default_vec3(obs_data_t *data, const char *name, struct vec3 *val); +EXPORT void obs_data_get_default_vec4(obs_data_t *data, const char *name, struct vec4 *val); +EXPORT void obs_data_get_default_quat(obs_data_t *data, const char *name, struct quat *val); -EXPORT void obs_data_get_autoselect_vec2(obs_data_t *data, const char *name, - struct vec2 *val); -EXPORT void obs_data_get_autoselect_vec3(obs_data_t *data, const char *name, - struct vec3 *val); -EXPORT void obs_data_get_autoselect_vec4(obs_data_t *data, const char *name, - struct vec4 *val); -EXPORT void obs_data_get_autoselect_quat(obs_data_t *data, const char *name, - struct quat *val); +EXPORT void obs_data_get_autoselect_vec2(obs_data_t *data, const char *name, struct vec2 *val); +EXPORT void obs_data_get_autoselect_vec3(obs_data_t *data, const char *name, struct vec3 *val); +EXPORT void obs_data_get_autoselect_vec4(obs_data_t *data, const char *name, struct vec4 *val); +EXPORT void obs_data_get_autoselect_quat(obs_data_t *data, const char *name, struct quat *val); /* ------------------------------------------------------------------------- */ /* Helper functions for media_frames_per_second/OBS_PROPERTY_FRAME_RATE */ -EXPORT void obs_data_set_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second fps, +EXPORT void obs_data_set_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second fps, const char *option); -EXPORT void -obs_data_set_default_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second fps, - const char *option); -EXPORT void -obs_data_set_autoselect_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second fps, - const char *option); +EXPORT void obs_data_set_default_frames_per_second(obs_data_t *data, const char *name, + struct media_frames_per_second fps, const char *option); +EXPORT void obs_data_set_autoselect_frames_per_second(obs_data_t *data, const char *name, + struct media_frames_per_second fps, const char *option); -EXPORT bool obs_data_get_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second *fps, +EXPORT bool obs_data_get_frames_per_second(obs_data_t *data, const char *name, struct media_frames_per_second *fps, const char **option); -EXPORT bool -obs_data_get_default_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second *fps, - const char **option); -EXPORT bool -obs_data_get_autoselect_frames_per_second(obs_data_t *data, const char *name, - struct media_frames_per_second *fps, - const char **option); +EXPORT bool obs_data_get_default_frames_per_second(obs_data_t *data, const char *name, + struct media_frames_per_second *fps, const char **option); +EXPORT bool obs_data_get_autoselect_frames_per_second(obs_data_t *data, const char *name, + struct media_frames_per_second *fps, const char **option); -EXPORT void -obs_data_item_set_frames_per_second(obs_data_item_t **item, - struct media_frames_per_second fps, - const char *option); -EXPORT void -obs_data_item_set_default_frames_per_second(obs_data_item_t **item, - struct media_frames_per_second fps, - const char *option); -EXPORT void obs_data_item_set_autoselect_frames_per_second( - obs_data_item_t **item, struct media_frames_per_second fps, - const char *option); +EXPORT void obs_data_item_set_frames_per_second(obs_data_item_t **item, struct media_frames_per_second fps, + const char *option); +EXPORT void obs_data_item_set_default_frames_per_second(obs_data_item_t **item, struct media_frames_per_second fps, + const char *option); +EXPORT void obs_data_item_set_autoselect_frames_per_second(obs_data_item_t **item, struct media_frames_per_second fps, + const char *option); -EXPORT bool -obs_data_item_get_frames_per_second(obs_data_item_t *item, - struct media_frames_per_second *fps, - const char **option); -EXPORT bool -obs_data_item_get_default_frames_per_second(obs_data_item_t *item, - struct media_frames_per_second *fps, - const char **option); -EXPORT bool obs_data_item_get_autoselect_frames_per_second( - obs_data_item_t *item, struct media_frames_per_second *fps, - const char **option); +EXPORT bool obs_data_item_get_frames_per_second(obs_data_item_t *item, struct media_frames_per_second *fps, + const char **option); +EXPORT bool obs_data_item_get_default_frames_per_second(obs_data_item_t *item, struct media_frames_per_second *fps, + const char **option); +EXPORT bool obs_data_item_get_autoselect_frames_per_second(obs_data_item_t *item, struct media_frames_per_second *fps, + const char **option); /* ------------------------------------------------------------------------- */ /* OBS-specific functions */ diff --git a/libobs/obs-display.c b/libobs/obs-display.c index 291000fd8..287ac73a6 100644 --- a/libobs/obs-display.c +++ b/libobs/obs-display.c @@ -19,16 +19,14 @@ #include "obs.h" #include "obs-internal.h" -bool obs_display_init(struct obs_display *display, - const struct gs_init_data *graphics_data) +bool obs_display_init(struct obs_display *display, const struct gs_init_data *graphics_data) { pthread_mutex_init_value(&display->draw_callbacks_mutex); pthread_mutex_init_value(&display->draw_info_mutex); #if defined(_WIN32) /* Conservative test for NVIDIA flickering in multi-GPU setups */ - display->use_clear_workaround = gs_get_adapter_count() > 1 && - !gs_can_adapter_fast_clear(); + display->use_clear_workaround = gs_get_adapter_count() > 1 && !gs_can_adapter_fast_clear(); #elif defined(__APPLE__) /* Apple Silicon GL driver doesn't seem to track SRGB clears correctly */ display->use_clear_workaround = true; @@ -65,8 +63,7 @@ bool obs_display_init(struct obs_display *display, return true; } -obs_display_t *obs_display_create(const struct gs_init_data *graphics_data, - uint32_t background_color) +obs_display_t *obs_display_create(const struct gs_init_data *graphics_data, uint32_t background_color) { struct obs_display *display = bzalloc(sizeof(struct obs_display)); @@ -147,9 +144,7 @@ void obs_display_update_color_space(obs_display_t *display) pthread_mutex_unlock(&display->draw_info_mutex); } -void obs_display_add_draw_callback(obs_display_t *display, - void (*draw)(void *param, uint32_t cx, - uint32_t cy), +void obs_display_add_draw_callback(obs_display_t *display, void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param) { if (!display) @@ -162,9 +157,7 @@ void obs_display_add_draw_callback(obs_display_t *display, pthread_mutex_unlock(&display->draw_callbacks_mutex); } -void obs_display_remove_draw_callback(obs_display_t *display, - void (*draw)(void *param, uint32_t cx, - uint32_t cy), +void obs_display_remove_draw_callback(obs_display_t *display, void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param) { if (!display) @@ -177,9 +170,7 @@ void obs_display_remove_draw_callback(obs_display_t *display, pthread_mutex_unlock(&display->draw_callbacks_mutex); } -static inline bool render_display_begin(struct obs_display *display, - uint32_t cx, uint32_t cy, - bool update_color_space) +static inline bool render_display_begin(struct obs_display *display, uint32_t cx, uint32_t cy, bool update_color_space) { struct vec4 clear_color; @@ -200,8 +191,7 @@ static inline bool render_display_begin(struct obs_display *display, if (gs_get_color_space() == GS_CS_SRGB) vec4_from_rgba(&clear_color, display->background_color); else - vec4_from_rgba_srgb(&clear_color, - display->background_color); + vec4_from_rgba_srgb(&clear_color, display->background_color); clear_color.w = 1.0f; const bool use_clear_workaround = display->use_clear_workaround; @@ -219,11 +209,8 @@ static inline bool render_display_begin(struct obs_display *display, gs_set_viewport(0, 0, cx, cy); if (use_clear_workaround) { - gs_effect_t *const solid_effect = - obs->video.solid_effect; - gs_effect_set_vec4(gs_effect_get_param_by_name( - solid_effect, "color"), - &clear_color); + gs_effect_t *const solid_effect = obs->video.solid_effect; + gs_effect_set_vec4(gs_effect_get_param_by_name(solid_effect, "color"), &clear_color); while (gs_effect_loop(solid_effect, "Solid")) gs_draw_sprite(NULL, 0, cx, cy); } diff --git a/libobs/obs-encoder.c b/libobs/obs-encoder.c index 9c97f1445..2dafee0cb 100644 --- a/libobs/obs-encoder.c +++ b/libobs/obs-encoder.c @@ -20,8 +20,7 @@ #include "util/util_uint64.h" #define encoder_active(encoder) os_atomic_load_bool(&encoder->active) -#define set_encoder_active(encoder, val) \ - os_atomic_set_bool(&encoder->active, val) +#define set_encoder_active(encoder, val) os_atomic_set_bool(&encoder->active, val) #define get_weak(encoder) ((obs_weak_encoder_t *)encoder->context.control) @@ -45,8 +44,7 @@ const char *obs_encoder_get_display_name(const char *id) return ei ? ei->get_name(ei->type_data) : NULL; } -static bool init_encoder(struct obs_encoder *encoder, const char *name, - obs_data_t *settings, obs_data_t *hotkey_data) +static bool init_encoder(struct obs_encoder *encoder, const char *name, obs_data_t *settings, obs_data_t *hotkey_data) { pthread_mutex_init_value(&encoder->init_mutex); pthread_mutex_init_value(&encoder->callbacks_mutex); @@ -54,8 +52,7 @@ static bool init_encoder(struct obs_encoder *encoder, const char *name, pthread_mutex_init_value(&encoder->pause.mutex); pthread_mutex_init_value(&encoder->roi_mutex); - if (!obs_context_data_init(&encoder->context, OBS_OBJ_TYPE_ENCODER, - settings, name, NULL, hotkey_data, false)) + if (!obs_context_data_init(&encoder->context, OBS_OBJ_TYPE_ENCODER, settings, name, NULL, hotkey_data, false)) return false; if (pthread_mutex_init_recursive(&encoder->init_mutex) != 0) return false; @@ -72,16 +69,14 @@ static bool init_encoder(struct obs_encoder *encoder, const char *name, encoder->orig_info.get_defaults(encoder->context.settings); } if (encoder->orig_info.get_defaults2) { - encoder->orig_info.get_defaults2(encoder->context.settings, - encoder->orig_info.type_data); + encoder->orig_info.get_defaults2(encoder->context.settings, encoder->orig_info.type_data); } return true; } -static struct obs_encoder * -create_encoder(const char *id, enum obs_encoder_type type, const char *name, - obs_data_t *settings, size_t mixer_idx, obs_data_t *hotkey_data) +static struct obs_encoder *create_encoder(const char *id, enum obs_encoder_type type, const char *name, + obs_data_t *settings, size_t mixer_idx, obs_data_t *hotkey_data) { struct obs_encoder *encoder; struct obs_encoder_info *ei = find_encoder(id); @@ -112,10 +107,8 @@ create_encoder(const char *id, enum obs_encoder_type type, const char *name, return NULL; } - obs_context_init_control(&encoder->context, encoder, - (obs_destroy_cb)obs_encoder_destroy); - obs_context_data_insert(&encoder->context, &obs->data.encoders_mutex, - &obs->data.first_encoder); + obs_context_init_control(&encoder->context, encoder, (obs_destroy_cb)obs_encoder_destroy); + obs_context_data_insert(&encoder->context, &obs->data.encoders_mutex, &obs->data.first_encoder); if (type == OBS_ENCODER_VIDEO) { encoder->frame_rate_divisor = 1; @@ -124,39 +117,31 @@ create_encoder(const char *id, enum obs_encoder_type type, const char *name, blog(LOG_DEBUG, "encoder '%s' (%s) created", name, id); if (ei && ei->caps & OBS_ENCODER_CAP_DEPRECATED) { - blog(LOG_WARNING, - "Encoder ID '%s' is deprecated and may be removed in a future version.", - id); + blog(LOG_WARNING, "Encoder ID '%s' is deprecated and may be removed in a future version.", id); } return encoder; } -obs_encoder_t *obs_video_encoder_create(const char *id, const char *name, - obs_data_t *settings, - obs_data_t *hotkey_data) +obs_encoder_t *obs_video_encoder_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data) { if (!name || !id) return NULL; - return create_encoder(id, OBS_ENCODER_VIDEO, name, settings, 0, - hotkey_data); + return create_encoder(id, OBS_ENCODER_VIDEO, name, settings, 0, hotkey_data); } -obs_encoder_t *obs_audio_encoder_create(const char *id, const char *name, - obs_data_t *settings, size_t mixer_idx, +obs_encoder_t *obs_audio_encoder_create(const char *id, const char *name, obs_data_t *settings, size_t mixer_idx, obs_data_t *hotkey_data) { if (!name || !id) return NULL; - return create_encoder(id, OBS_ENCODER_AUDIO, name, settings, mixer_idx, - hotkey_data); + return create_encoder(id, OBS_ENCODER_AUDIO, name, settings, mixer_idx, hotkey_data); } static void receive_video(void *param, struct video_data *frame); static void receive_audio(void *param, size_t mix_idx, struct audio_data *data); -static inline void get_audio_info(const struct obs_encoder *encoder, - struct audio_convert_info *info) +static inline void get_audio_info(const struct obs_encoder *encoder, struct audio_convert_info *info) { const struct audio_output_info *aoi; aoi = audio_output_get_info(encoder->media); @@ -172,8 +157,7 @@ static inline void get_audio_info(const struct obs_encoder *encoder, encoder->info.get_audio_info(encoder->context.data, info); } -static inline void get_video_info(struct obs_encoder *encoder, - struct video_scale_info *info) +static inline void get_video_info(struct obs_encoder *encoder, struct video_scale_info *info) { const struct video_output_info *voi; voi = video_output_get_info(encoder->media); @@ -238,18 +222,14 @@ static void maybe_set_up_gpu_rescale(struct obs_encoder *encoder) pthread_mutex_lock(&obs->video.mixes_mutex); for (size_t i = 0; i < obs->video.mixes.num; i++) { struct obs_core_video_mix *current = obs->video.mixes.array[i]; - const struct video_output_info *voi = - video_output_get_info(current->video); + const struct video_output_info *voi = video_output_get_info(current->video); if (current_mix->view != current->view) continue; - if (voi->width != encoder->scaled_width || - voi->height != encoder->scaled_height) + if (voi->width != encoder->scaled_width || voi->height != encoder->scaled_height) continue; - if (voi->format != info->format || - voi->colorspace != info->colorspace || - voi->range != info->range) + if (voi->format != info->format || voi->colorspace != info->colorspace || voi->range != info->range) continue; current->encoder_refs += 1; @@ -288,18 +268,14 @@ static void maybe_set_up_gpu_rescale(struct obs_encoder *encoder) // double check that nobody else added a matching mix while we've created our mix for (size_t i = 0; i < obs->video.mixes.num; i++) { struct obs_core_video_mix *current = obs->video.mixes.array[i]; - const struct video_output_info *voi = - video_output_get_info(current->video); + const struct video_output_info *voi = video_output_get_info(current->video); if (current->view != current_mix->view) continue; - if (voi->width != encoder->scaled_width || - voi->height != encoder->scaled_height) + if (voi->width != encoder->scaled_width || voi->height != encoder->scaled_height) continue; - if (voi->format != info->format || - voi->colorspace != info->colorspace || - voi->range != info->range) + if (voi->format != info->format || voi->colorspace != info->colorspace || voi->range != info->range) continue; obs_encoder_set_video(encoder, current->video); @@ -323,8 +299,7 @@ static void add_connection(struct obs_encoder *encoder) struct audio_convert_info audio_info = {0}; get_audio_info(encoder, &audio_info); - audio_output_connect(encoder->media, encoder->mixer_idx, - &audio_info, receive_audio, encoder); + audio_output_connect(encoder->media, encoder->mixer_idx, &audio_info, receive_audio, encoder); } else { struct video_scale_info info = {0}; get_video_info(encoder, &info); @@ -332,17 +307,14 @@ static void add_connection(struct obs_encoder *encoder) if (gpu_encode_available(encoder)) { start_gpu_encode(encoder); } else { - start_raw_video(encoder->media, &info, - encoder->frame_rate_divisor, - receive_video, encoder); + start_raw_video(encoder->media, &info, encoder->frame_rate_divisor, receive_video, encoder); } } if (encoder->encoder_group) { pthread_mutex_lock(&encoder->encoder_group->mutex); encoder->encoder_group->num_encoders_started += 1; - bool ready = encoder->encoder_group->num_encoders_started >= - encoder->encoder_group->encoders.num; + bool ready = encoder->encoder_group->num_encoders_started >= encoder->encoder_group->encoders.num; pthread_mutex_unlock(&encoder->encoder_group->mutex); if (ready) add_ready_encoder_group(encoder); @@ -355,8 +327,7 @@ void obs_encoder_group_actually_destroy(obs_encoder_group_t *group); static void remove_connection(struct obs_encoder *encoder, bool shutdown) { if (encoder->info.type == OBS_ENCODER_AUDIO) { - audio_output_disconnect(encoder->media, encoder->mixer_idx, - receive_audio, encoder); + audio_output_disconnect(encoder->media, encoder->mixer_idx, receive_audio, encoder); } else { if (gpu_encode_available(encoder)) { stop_gpu_encode(encoder); @@ -406,8 +377,7 @@ void obs_encoder_destroy(obs_encoder_t *encoder) da_free(encoder->outputs); pthread_mutex_unlock(&encoder->outputs_mutex); - blog(LOG_DEBUG, "encoder '%s' destroyed", - encoder->context.name); + blog(LOG_DEBUG, "encoder '%s' destroyed", encoder->context.name); obs_encoder_set_group(encoder, NULL); @@ -429,17 +399,14 @@ void obs_encoder_destroy(obs_encoder_t *encoder) if (encoder->last_error_message) bfree(encoder->last_error_message); if (encoder->fps_override) - video_output_free_frame_rate_divisor( - encoder->fps_override); + video_output_free_frame_rate_divisor(encoder->fps_override); bfree(encoder); } } const char *obs_encoder_get_name(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_get_name") - ? encoder->context.name - : NULL; + return obs_encoder_valid(encoder, "obs_encoder_get_name") ? encoder->context.name : NULL; } void obs_encoder_set_name(obs_encoder_t *encoder, const char *name) @@ -504,15 +471,13 @@ obs_properties_t *obs_encoder_properties(const obs_encoder_t *encoder) if (encoder->orig_info.get_properties2) { obs_properties_t *props; - props = encoder->orig_info.get_properties2( - encoder->context.data, encoder->orig_info.type_data); + props = encoder->orig_info.get_properties2(encoder->context.data, encoder->orig_info.type_data); obs_properties_apply_settings(props, encoder->context.settings); return props; } else if (encoder->orig_info.get_properties) { obs_properties_t *props; - props = encoder->orig_info.get_properties( - encoder->context.data); + props = encoder->orig_info.get_properties(encoder->context.data); obs_properties_apply_settings(props, encoder->context.settings); return props; } @@ -542,20 +507,17 @@ void obs_encoder_update(obs_encoder_t *encoder, obs_data_t *settings) if (encoder_active(encoder)) { encoder->reconfigure_requested = true; } else { - encoder->info.update(encoder->context.data, - encoder->context.settings); + encoder->info.update(encoder->context.data, encoder->context.settings); } } -bool obs_encoder_get_extra_data(const obs_encoder_t *encoder, - uint8_t **extra_data, size_t *size) +bool obs_encoder_get_extra_data(const obs_encoder_t *encoder, uint8_t **extra_data, size_t *size) { if (!obs_encoder_valid(encoder, "obs_encoder_get_extra_data")) return false; if (encoder->info.get_extra_data && encoder->context.data) - return encoder->info.get_extra_data(encoder->context.data, - extra_data, size); + return encoder->info.get_extra_data(encoder->context.data, extra_data, size); return false; } @@ -574,8 +536,7 @@ static inline void reset_audio_buffers(struct obs_encoder *encoder) free_audio_buffers(encoder); for (size_t i = 0; i < encoder->planes; i++) - encoder->audio_output_buffer[i] = - bmalloc(encoder->framesize_bytes); + encoder->audio_output_buffer[i] = bmalloc(encoder->framesize_bytes); } static void intitialize_audio_encoder(struct obs_encoder *encoder) @@ -586,8 +547,7 @@ static void intitialize_audio_encoder(struct obs_encoder *encoder) encoder->samplerate = info.samples_per_sec; encoder->planes = get_audio_planes(info.format, info.speakers); encoder->blocksize = get_audio_size(info.format, info.speakers, 1); - encoder->framesize = - encoder->info.get_frame_size(encoder->context.data); + encoder->framesize = encoder->info.get_frame_size(encoder->context.data); encoder->framesize_bytes = encoder->blocksize * encoder->framesize; reset_audio_buffers(encoder); @@ -598,8 +558,7 @@ static THREAD_LOCAL bool can_reroute = false; static inline bool obs_encoder_initialize_internal(obs_encoder_t *encoder) { if (!encoder->media) { - blog(LOG_ERROR, - "obs_encoder_initialize_internal: encoder '%s' has no media set", + blog(LOG_ERROR, "obs_encoder_initialize_internal: encoder '%s' has no media set", encoder->context.name); return false; } @@ -616,8 +575,7 @@ static inline bool obs_encoder_initialize_internal(obs_encoder_t *encoder) if (encoder->orig_info.create) { can_reroute = true; encoder->info = encoder->orig_info; - encoder->context.data = encoder->orig_info.create( - encoder->context.settings, encoder); + encoder->context.data = encoder->orig_info.create(encoder->context.settings, encoder); can_reroute = false; } if (!encoder->context.data) @@ -630,8 +588,7 @@ static inline bool obs_encoder_initialize_internal(obs_encoder_t *encoder) return true; } -void *obs_encoder_create_rerouted(obs_encoder_t *encoder, - const char *reroute_id) +void *obs_encoder_create_rerouted(obs_encoder_t *encoder, const char *reroute_id) { if (!obs_ptr_valid(encoder, "obs_encoder_reroute")) return NULL; @@ -642,8 +599,7 @@ void *obs_encoder_create_rerouted(obs_encoder_t *encoder, const struct obs_encoder_info *ei = find_encoder(reroute_id); if (ei) { - if (ei->type != encoder->orig_info.type || - astrcmpi(ei->codec, encoder->orig_info.codec) != 0) { + if (ei->type != encoder->orig_info.type || astrcmpi(ei->codec, encoder->orig_info.codec) != 0) { return NULL; } encoder->info = *ei; @@ -705,8 +661,7 @@ void obs_encoder_shutdown(obs_encoder_t *encoder) maybe_clear_encoder_core_video_mix(encoder); for (size_t i = 0; i < encoder->paired_encoders.num; i++) { - obs_weak_encoder_release( - encoder->paired_encoders.array[i]); + obs_weak_encoder_release(encoder->paired_encoders.array[i]); } da_free(encoder->paired_encoders); } @@ -714,9 +669,7 @@ void obs_encoder_shutdown(obs_encoder_t *encoder) pthread_mutex_unlock(&encoder->init_mutex); } -static inline size_t get_callback_idx(const struct obs_encoder *encoder, - encoded_callback_t new_packet, - void *param) +static inline size_t get_callback_idx(const struct obs_encoder *encoder, encoded_callback_t new_packet, void *param) { for (size_t i = 0; i < encoder->callbacks.num; i++) { struct encoder_callback *cb = encoder->callbacks.array + i; @@ -738,9 +691,7 @@ void pause_reset(struct pause_data *pause) pthread_mutex_unlock(&pause->mutex); } -static inline void obs_encoder_start_internal(obs_encoder_t *encoder, - encoded_callback_t new_packet, - void *param) +static inline void obs_encoder_start_internal(obs_encoder_t *encoder, encoded_callback_t new_packet, void *param) { struct encoder_callback cb = {false, new_packet, param}; bool first = false; @@ -767,8 +718,7 @@ static inline void obs_encoder_start_internal(obs_encoder_t *encoder, } } -void obs_encoder_start(obs_encoder_t *encoder, encoded_callback_t new_packet, - void *param) +void obs_encoder_start(obs_encoder_t *encoder, encoded_callback_t new_packet, void *param) { if (!obs_encoder_valid(encoder, "obs_encoder_start")) return; @@ -780,8 +730,7 @@ void obs_encoder_start(obs_encoder_t *encoder, encoded_callback_t new_packet, pthread_mutex_unlock(&encoder->init_mutex); } -void obs_encoder_stop(obs_encoder_t *encoder, encoded_callback_t new_packet, - void *param) +void obs_encoder_stop(obs_encoder_t *encoder, encoded_callback_t new_packet, void *param) { bool last = false; size_t idx; @@ -817,8 +766,7 @@ void obs_encoder_stop(obs_encoder_t *encoder, encoded_callback_t new_packet, * also destroyed. */ if (group) { pthread_mutex_lock(&group->mutex); - if (group->destroy_on_stop && - group->num_encoders_started == 0) + if (group->destroy_on_stop && group->num_encoders_started == 0) obs_encoder_group_actually_destroy(group); else pthread_mutex_unlock(&group->mutex); @@ -833,9 +781,7 @@ void obs_encoder_stop(obs_encoder_t *encoder, encoded_callback_t new_packet, const char *obs_encoder_get_codec(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_get_codec") - ? encoder->info.codec - : NULL; + return obs_encoder_valid(encoder, "obs_encoder_get_codec") ? encoder->info.codec : NULL; } const char *obs_get_encoder_codec(const char *id) @@ -846,9 +792,7 @@ const char *obs_get_encoder_codec(const char *id) enum obs_encoder_type obs_encoder_get_type(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_get_type") - ? encoder->info.type - : OBS_ENCODER_AUDIO; + return obs_encoder_valid(encoder, "obs_encoder_get_type") ? encoder->info.type : OBS_ENCODER_AUDIO; } enum obs_encoder_type obs_get_encoder_type(const char *id) @@ -859,13 +803,10 @@ enum obs_encoder_type obs_get_encoder_type(const char *id) uint32_t obs_encoder_get_encoded_frames(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_output_get_encoded_frames") - ? encoder->encoded_frames - : 0; + return obs_encoder_valid(encoder, "obs_output_get_encoded_frames") ? encoder->encoded_frames : 0; } -void obs_encoder_set_scaled_size(obs_encoder_t *encoder, uint32_t width, - uint32_t height) +void obs_encoder_set_scaled_size(obs_encoder_t *encoder, uint32_t width, uint32_t height) { if (!obs_encoder_valid(encoder, "obs_encoder_set_scaled_size")) return; @@ -907,8 +848,7 @@ void obs_encoder_set_scaled_size(obs_encoder_t *encoder, uint32_t width, encoder->scaled_height = height; } -void obs_encoder_set_gpu_scale_type(obs_encoder_t *encoder, - enum obs_scale_type gpu_scale_type) +void obs_encoder_set_gpu_scale_type(obs_encoder_t *encoder, enum obs_scale_type gpu_scale_type) { if (!obs_encoder_valid(encoder, "obs_encoder_set_gpu_scale_type")) return; @@ -937,8 +877,7 @@ void obs_encoder_set_gpu_scale_type(obs_encoder_t *encoder, encoder->gpu_scale_type = gpu_scale_type; } -bool obs_encoder_set_frame_rate_divisor(obs_encoder_t *encoder, - uint32_t frame_rate_divisor) +bool obs_encoder_set_frame_rate_divisor(obs_encoder_t *encoder, uint32_t frame_rate_divisor) { if (!obs_encoder_valid(encoder, "obs_encoder_set_frame_rate_divisor")) return false; @@ -984,8 +923,7 @@ bool obs_encoder_set_frame_rate_divisor(obs_encoder_t *encoder, if (encoder->media) { encoder->fps_override = - video_output_create_with_frame_rate_divisor( - encoder->media, encoder->frame_rate_divisor); + video_output_create_with_frame_rate_divisor(encoder->media, encoder->frame_rate_divisor); } return true; @@ -1013,9 +951,7 @@ uint32_t obs_encoder_get_width(const obs_encoder_t *encoder) if (!encoder->media) return 0; - return encoder->scaled_width != 0 - ? encoder->scaled_width - : video_output_get_width(encoder->media); + return encoder->scaled_width != 0 ? encoder->scaled_width : video_output_get_width(encoder->media); } uint32_t obs_encoder_get_height(const obs_encoder_t *encoder) @@ -1032,9 +968,7 @@ uint32_t obs_encoder_get_height(const obs_encoder_t *encoder) if (!encoder->media) return 0; - return encoder->scaled_height != 0 - ? encoder->scaled_height - : video_output_get_height(encoder->media); + return encoder->scaled_height != 0 ? encoder->scaled_height : video_output_get_height(encoder->media); } bool obs_encoder_gpu_scaling_enabled(obs_encoder_t *encoder) @@ -1097,9 +1031,7 @@ uint32_t obs_encoder_get_sample_rate(const obs_encoder_t *encoder) if (!encoder->media) return 0; - return encoder->samplerate != 0 - ? encoder->samplerate - : audio_output_get_sample_rate(encoder->media); + return encoder->samplerate != 0 ? encoder->samplerate : audio_output_get_sample_rate(encoder->media); } size_t obs_encoder_get_frame_size(const obs_encoder_t *encoder) @@ -1180,8 +1112,7 @@ static void encoder_set_video(obs_encoder_t *encoder, video_t *video) if (encoder->frame_rate_divisor) { encoder->fps_override = - video_output_create_with_frame_rate_divisor( - video, encoder->frame_rate_divisor); + video_output_create_with_frame_rate_divisor(video, encoder->frame_rate_divisor); } } else { encoder->media = NULL; @@ -1267,24 +1198,18 @@ audio_t *obs_encoder_audio(const obs_encoder_t *encoder) bool obs_encoder_active(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_active") - ? encoder_active(encoder) - : false; + return obs_encoder_valid(encoder, "obs_encoder_active") ? encoder_active(encoder) : false; } -static inline bool get_sei(const struct obs_encoder *encoder, uint8_t **sei, - size_t *size) +static inline bool get_sei(const struct obs_encoder *encoder, uint8_t **sei, size_t *size) { if (encoder->info.get_sei_data) - return encoder->info.get_sei_data(encoder->context.data, sei, - size); + return encoder->info.get_sei_data(encoder->context.data, sei, size); return false; } -static void send_first_video_packet(struct obs_encoder *encoder, - struct encoder_callback *cb, - struct encoder_packet *packet, - struct encoder_packet_time *packet_time) +static void send_first_video_packet(struct obs_encoder *encoder, struct encoder_callback *cb, + struct encoder_packet *packet, struct encoder_packet_time *packet_time) { struct encoder_packet first_packet; DARRAY(uint8_t) data; @@ -1317,9 +1242,7 @@ static void send_first_video_packet(struct obs_encoder *encoder, } static const char *send_packet_name = "send_packet"; -static inline void send_packet(struct obs_encoder *encoder, - struct encoder_callback *cb, - struct encoder_packet *packet, +static inline void send_packet(struct obs_encoder *encoder, struct encoder_callback *cb, struct encoder_packet *packet, struct encoder_packet_time *packet_time) { profile_start(send_packet_name); @@ -1353,12 +1276,10 @@ void full_stop(struct obs_encoder *encoder) } } -void send_off_encoder_packet(obs_encoder_t *encoder, bool success, - bool received, struct encoder_packet *pkt) +void send_off_encoder_packet(obs_encoder_t *encoder, bool success, bool received, struct encoder_packet *pkt) { if (!success) { - blog(LOG_ERROR, "Error encoding with encoder '%s'", - encoder->context.name); + blog(LOG_ERROR, "Error encoding with encoder '%s'", encoder->context.name); full_stop(encoder); return; } @@ -1371,8 +1292,7 @@ void send_off_encoder_packet(obs_encoder_t *encoder, bool success, /* we use system time here to ensure sync with other encoders, * you do not want to use relative timestamps here */ - pkt->dts_usec = encoder->start_ts / 1000 + - packet_dts_usec(pkt) - encoder->offset_usec; + pkt->dts_usec = encoder->start_ts / 1000 + packet_dts_usec(pkt) - encoder->offset_usec; pkt->sys_dts_usec = pkt->dts_usec; pthread_mutex_lock(&encoder->pause.mutex); @@ -1387,23 +1307,18 @@ void send_off_encoder_packet(obs_encoder_t *encoder, bool success, struct encoder_packet_time *ept = NULL; bool found_ept = false; if (pkt->type == OBS_ENCODER_VIDEO) { - for (size_t i = encoder->encoder_packet_times.num; - i > 0; i--) { - ept = &encoder->encoder_packet_times - .array[i - 1]; + for (size_t i = encoder->encoder_packet_times.num; i > 0; i--) { + ept = &encoder->encoder_packet_times.array[i - 1]; if (ept->pts == pkt->pts) { ept_local = *ept; - da_erase(encoder->encoder_packet_times, - i - 1); + da_erase(encoder->encoder_packet_times, i - 1); found_ept = true; break; } } if (!found_ept) - blog(LOG_DEBUG, - "%s: Encoder packet timing for PTS %" PRId64 - " not found", - __FUNCTION__, pkt->pts); + blog(LOG_DEBUG, "%s: Encoder packet timing for PTS %" PRId64 " not found", __FUNCTION__, + pkt->pts); } pthread_mutex_lock(&encoder->callbacks_mutex); @@ -1411,8 +1326,7 @@ void send_off_encoder_packet(obs_encoder_t *encoder, bool success, for (size_t i = encoder->callbacks.num; i > 0; i--) { struct encoder_callback *cb; cb = encoder->callbacks.array + (i - 1); - send_packet(encoder, cb, pkt, - found_ept ? &ept_local : NULL); + send_packet(encoder, cb, pkt, found_ept ? &ept_local : NULL); } pthread_mutex_unlock(&encoder->callbacks_mutex); @@ -1424,14 +1338,12 @@ void send_off_encoder_packet(obs_encoder_t *encoder, bool success, } static const char *do_encode_name = "do_encode"; -bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, - const uint64_t *frame_cts) +bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, const uint64_t *frame_cts) { profile_start(do_encode_name); if (!encoder->profile_encoder_encode_name) encoder->profile_encoder_encode_name = - profile_store_name(obs_get_profiler_name_store(), - "encode(%s)", encoder->context.name); + profile_store_name(obs_get_profiler_name_store(), "encode(%s)", encoder->context.name); struct encoder_packet pkt = {0}; bool received = false; @@ -1440,8 +1352,7 @@ bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, if (encoder->reconfigure_requested) { encoder->reconfigure_requested = false; - encoder->info.update(encoder->context.data, - encoder->context.settings); + encoder->info.update(encoder->context.data, encoder->context.settings); } pkt.timebase_num = encoder->timebase_num * encoder->frame_rate_divisor; @@ -1454,8 +1365,7 @@ bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, fer_ts = os_gettime_ns(); profile_start(encoder->profile_encoder_encode_name); - success = encoder->info.encode(encoder->context.data, frame, &pkt, - &received); + success = encoder->info.encode(encoder->context.data, frame, &pkt, &received); profile_end(encoder->profile_encoder_encode_name); /* Generate and enqueue the frame timing metrics, namely @@ -1463,8 +1373,7 @@ bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, * (frame encode request complete) and current PTS. PTS is used to * associate the frame timing data with the encode packet. */ if (frame_cts) { - struct encoder_packet_time *ept = - da_push_back_new(encoder->encoder_packet_times); + struct encoder_packet_time *ept = da_push_back_new(encoder->encoder_packet_times); // Get the frame encode request complete timestamp if (success) { ept->ferc = os_gettime_ns(); @@ -1483,8 +1392,7 @@ bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, return success; } -static inline bool video_pause_check_internal(struct pause_data *pause, - uint64_t ts) +static inline bool video_pause_check_internal(struct pause_data *pause, uint64_t ts) { pause->last_video_ts = ts; if (!pause->ts_start) { @@ -1533,13 +1441,11 @@ static void receive_video(void *param, struct video_data *frame) if (!encoder->first_received && encoder->paired_encoders.num) { for (size_t i = 0; i < encoder->paired_encoders.num; i++) { - obs_encoder_t *paired = obs_weak_encoder_get_encoder( - encoder->paired_encoders.array[i]); + obs_encoder_t *paired = obs_weak_encoder_get_encoder(encoder->paired_encoders.array[i]); if (!paired) continue; - if (!paired->first_received || - paired->first_raw_ts > frame->timestamp) { + if (!paired->first_received || paired->first_raw_ts > frame->timestamp) { obs_encoder_release(paired); goto wait_for_audio; } @@ -1565,8 +1471,7 @@ static void receive_video(void *param, struct video_data *frame) enc_frame.pts = encoder->cur_pts; if (do_encode(encoder, &enc_frame, &frame->timestamp)) - encoder->cur_pts += - encoder->timebase_num * encoder->frame_rate_divisor; + encoder->cur_pts += encoder->timebase_num * encoder->frame_rate_divisor; wait_for_audio: profile_end(receive_video_name); @@ -1578,8 +1483,7 @@ static void clear_audio(struct obs_encoder *encoder) deque_free(&encoder->audio_input_buffer[i]); } -static inline void push_back_audio(struct obs_encoder *encoder, - struct audio_data *data, size_t size, +static inline void push_back_audio(struct obs_encoder *encoder, struct audio_data *data, size_t size, size_t offset_size) { if (offset_size >= size) @@ -1589,12 +1493,10 @@ static inline void push_back_audio(struct obs_encoder *encoder, /* push in to the circular buffer */ for (size_t i = 0; i < encoder->planes; i++) - deque_push_back(&encoder->audio_input_buffer[i], - data->data[i] + offset_size, size); + deque_push_back(&encoder->audio_input_buffer[i], data->data[i] + offset_size, size); } -static inline size_t calc_offset_size(struct obs_encoder *encoder, - uint64_t v_start_ts, uint64_t a_start_ts) +static inline size_t calc_offset_size(struct obs_encoder *encoder, uint64_t v_start_ts, uint64_t a_start_ts) { uint64_t offset = v_start_ts - a_start_ts; offset = util_mul_div64(offset, encoder->samplerate, 1000000000ULL); @@ -1609,13 +1511,11 @@ static void start_from_buffer(struct obs_encoder *encoder, uint64_t v_start_ts) for (size_t i = 0; i < MAX_AV_PLANES; i++) { audio.data[i] = encoder->audio_input_buffer[i].data; - memset(&encoder->audio_input_buffer[i], 0, - sizeof(struct deque)); + memset(&encoder->audio_input_buffer[i], 0, sizeof(struct deque)); } if (encoder->first_raw_ts < v_start_ts) - offset_size = calc_offset_size(encoder, v_start_ts, - encoder->first_raw_ts); + offset_size = calc_offset_size(encoder, v_start_ts, encoder->first_raw_ts); push_back_audio(encoder, &audio, size, offset_size); @@ -1635,8 +1535,7 @@ static bool buffer_audio(struct obs_encoder *encoder, struct audio_data *data) struct obs_encoder *paired_encoder = NULL; /* Audio encoders can only be paired to one video encoder */ if (encoder->paired_encoders.num) { - paired_encoder = obs_weak_encoder_get_encoder( - encoder->paired_encoders.array[0]); + paired_encoder = obs_weak_encoder_get_encoder(encoder->paired_encoders.array[0]); } if (!encoder->start_ts && paired_encoder) { @@ -1651,8 +1550,7 @@ static bool buffer_audio(struct obs_encoder *encoder, struct audio_data *data) /* audio starting point still not synced with video starting * point, so don't start audio */ - end_ts += util_mul_div64(data->frames, 1000000000ULL, - encoder->samplerate); + end_ts += util_mul_div64(data->frames, 1000000000ULL, encoder->samplerate); if (end_ts <= v_start_ts) { success = false; goto fail; @@ -1660,8 +1558,7 @@ static bool buffer_audio(struct obs_encoder *encoder, struct audio_data *data) /* ready to start audio, truncate if necessary */ if (data->timestamp < v_start_ts) - offset_size = calc_offset_size(encoder, v_start_ts, - data->timestamp); + offset_size = calc_offset_size(encoder, v_start_ts, data->timestamp); if (data->timestamp <= v_start_ts) clear_audio(encoder); @@ -1691,8 +1588,7 @@ static bool send_audio_data(struct obs_encoder *encoder) memset(&enc_frame, 0, sizeof(struct encoder_frame)); for (size_t i = 0; i < encoder->planes; i++) { - deque_pop_front(&encoder->audio_input_buffer[i], - encoder->audio_output_buffer[i], + deque_pop_front(&encoder->audio_input_buffer[i], encoder->audio_output_buffer[i], encoder->framesize_bytes); enc_frame.data[i] = encoder->audio_output_buffer[i]; @@ -1709,8 +1605,7 @@ static bool send_audio_data(struct obs_encoder *encoder) return true; } -static void pause_audio(struct pause_data *pause, struct audio_data *data, - size_t sample_rate) +static void pause_audio(struct pause_data *pause, struct audio_data *data, size_t sample_rate) { uint64_t cutoff_frames = pause->ts_start - data->timestamp; cutoff_frames = ns_to_audio_frames(sample_rate, cutoff_frames); @@ -1718,8 +1613,7 @@ static void pause_audio(struct pause_data *pause, struct audio_data *data, data->frames = (uint32_t)cutoff_frames; } -static void unpause_audio(struct pause_data *pause, struct audio_data *data, - size_t sample_rate) +static void unpause_audio(struct pause_data *pause, struct audio_data *data, size_t sample_rate) { uint64_t cutoff_frames = pause->ts_end - data->timestamp; cutoff_frames = ns_to_audio_frames(sample_rate, cutoff_frames); @@ -1736,9 +1630,7 @@ static void unpause_audio(struct pause_data *pause, struct audio_data *data, pause->ts_end = 0; } -static inline bool audio_pause_check_internal(struct pause_data *pause, - struct audio_data *data, - size_t sample_rate) +static inline bool audio_pause_check_internal(struct pause_data *pause, struct audio_data *data, size_t sample_rate) { uint64_t end_ts; @@ -1746,8 +1638,7 @@ static inline bool audio_pause_check_internal(struct pause_data *pause, return false; } - end_ts = - data->timestamp + audio_frames_to_ns(sample_rate, data->frames); + end_ts = data->timestamp + audio_frames_to_ns(sample_rate, data->frames); if (pause->ts_start >= data->timestamp) { if (pause->ts_start <= end_ts) { @@ -1756,8 +1647,7 @@ static inline bool audio_pause_check_internal(struct pause_data *pause, } } else { - if (pause->ts_end >= data->timestamp && - pause->ts_end <= end_ts) { + if (pause->ts_end >= data->timestamp && pause->ts_end <= end_ts) { unpause_audio(pause, data, sample_rate); return !data->frames; } @@ -1768,8 +1658,7 @@ static inline bool audio_pause_check_internal(struct pause_data *pause, return false; } -bool audio_pause_check(struct pause_data *pause, struct audio_data *data, - size_t sample_rate) +bool audio_pause_check(struct pause_data *pause, struct audio_data *data, size_t sample_rate) { bool ignore_audio; @@ -1801,8 +1690,7 @@ static void receive_audio(void *param, size_t mix_idx, struct audio_data *in) if (!buffer_audio(encoder, &audio)) goto end; - while (encoder->audio_input_buffer[0].size >= - encoder->framesize_bytes) { + while (encoder->audio_input_buffer[0].size >= encoder->framesize_bytes) { if (!send_audio_data(encoder)) { break; } @@ -1814,8 +1702,7 @@ end: profile_end(receive_audio_name); } -void obs_encoder_add_output(struct obs_encoder *encoder, - struct obs_output *output) +void obs_encoder_add_output(struct obs_encoder *encoder, struct obs_output *output) { if (!encoder || !output) return; @@ -1825,8 +1712,7 @@ void obs_encoder_add_output(struct obs_encoder *encoder, pthread_mutex_unlock(&encoder->outputs_mutex); } -void obs_encoder_remove_output(struct obs_encoder *encoder, - struct obs_output *output) +void obs_encoder_remove_output(struct obs_encoder *encoder, struct obs_output *output) { if (!encoder || !output) return; @@ -1836,8 +1722,7 @@ void obs_encoder_remove_output(struct obs_encoder *encoder, pthread_mutex_unlock(&encoder->outputs_mutex); } -void obs_encoder_packet_create_instance(struct encoder_packet *dst, - const struct encoder_packet *src) +void obs_encoder_packet_create_instance(struct encoder_packet *dst, const struct encoder_packet *src) { long *p_refs; @@ -1848,8 +1733,7 @@ void obs_encoder_packet_create_instance(struct encoder_packet *dst, memcpy(dst->data, src->data, src->size); } -void obs_encoder_packet_ref(struct encoder_packet *dst, - struct encoder_packet *src) +void obs_encoder_packet_ref(struct encoder_packet *dst, struct encoder_packet *src) { if (!src) return; @@ -1876,8 +1760,7 @@ void obs_encoder_packet_release(struct encoder_packet *pkt) memset(pkt, 0, sizeof(struct encoder_packet)); } -void obs_encoder_set_preferred_video_format(obs_encoder_t *encoder, - enum video_format format) +void obs_encoder_set_preferred_video_format(obs_encoder_t *encoder, enum video_format format) { if (!encoder || encoder->info.type != OBS_ENCODER_VIDEO) return; @@ -1885,8 +1768,7 @@ void obs_encoder_set_preferred_video_format(obs_encoder_t *encoder, encoder->preferred_format = format; } -enum video_format -obs_encoder_get_preferred_video_format(const obs_encoder_t *encoder) +enum video_format obs_encoder_get_preferred_video_format(const obs_encoder_t *encoder) { if (!encoder || encoder->info.type != OBS_ENCODER_VIDEO) return VIDEO_FORMAT_NONE; @@ -1955,24 +1837,19 @@ obs_encoder_t *obs_weak_encoder_get_encoder(obs_weak_encoder_t *weak) return NULL; } -bool obs_weak_encoder_references_encoder(obs_weak_encoder_t *weak, - obs_encoder_t *encoder) +bool obs_weak_encoder_references_encoder(obs_weak_encoder_t *weak, obs_encoder_t *encoder) { return weak && encoder && weak->encoder == encoder; } void *obs_encoder_get_type_data(obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_get_type_data") - ? encoder->orig_info.type_data - : NULL; + return obs_encoder_valid(encoder, "obs_encoder_get_type_data") ? encoder->orig_info.type_data : NULL; } const char *obs_encoder_get_id(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_get_id") - ? encoder->orig_info.id - : NULL; + return obs_encoder_valid(encoder, "obs_encoder_get_id") ? encoder->orig_info.id : NULL; } uint32_t obs_get_encoder_caps(const char *encoder_id) @@ -1983,16 +1860,12 @@ uint32_t obs_get_encoder_caps(const char *encoder_id) uint32_t obs_encoder_get_caps(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_get_caps") - ? encoder->orig_info.caps - : 0; + return obs_encoder_valid(encoder, "obs_encoder_get_caps") ? encoder->orig_info.caps : 0; } bool obs_encoder_paused(const obs_encoder_t *encoder) { - return obs_encoder_valid(encoder, "obs_encoder_paused") - ? os_atomic_load_bool(&encoder->paused) - : false; + return obs_encoder_valid(encoder, "obs_encoder_paused") ? os_atomic_load_bool(&encoder->paused) : false; } const char *obs_encoder_get_last_error(obs_encoder_t *encoder) @@ -2027,8 +1900,7 @@ bool obs_encoder_has_roi(const obs_encoder_t *encoder) return encoder->roi.num > 0; } -bool obs_encoder_add_roi(obs_encoder_t *encoder, - const struct obs_encoder_roi *roi) +bool obs_encoder_add_roi(obs_encoder_t *encoder, const struct obs_encoder_roi *roi) { if (!roi) return false; @@ -2059,9 +1931,7 @@ void obs_encoder_clear_roi(obs_encoder_t *encoder) pthread_mutex_unlock(&encoder->roi_mutex); } -void obs_encoder_enum_roi(obs_encoder_t *encoder, - void (*enum_proc)(void *, struct obs_encoder_roi *), - void *param) +void obs_encoder_enum_roi(obs_encoder_t *encoder, void (*enum_proc)(void *, struct obs_encoder_roi *), void *param) { float scale_x = 0; float scale_y = 0; @@ -2087,11 +1957,9 @@ void obs_encoder_enum_roi(obs_encoder_t *encoder, if (scale_x > 0 && scale_y > 0) { struct obs_encoder_roi scaled_roi = { .top = (uint32_t)((float)roi->top * scale_y), - .bottom = (uint32_t)((float)roi->bottom * - scale_y), + .bottom = (uint32_t)((float)roi->bottom * scale_y), .left = (uint32_t)((float)roi->left * scale_x), - .right = - (uint32_t)((float)roi->right * scale_x), + .right = (uint32_t)((float)roi->right * scale_x), .priority = roi->priority, }; @@ -2115,9 +1983,7 @@ bool obs_encoder_set_group(obs_encoder_t *encoder, obs_encoder_group_t *group) return false; if (obs_encoder_active(encoder)) { - blog(LOG_ERROR, - "obs_encoder_set_group: encoder '%s' is already active", - obs_encoder_get_name(encoder)); + blog(LOG_ERROR, "obs_encoder_set_group: encoder '%s' is already active", obs_encoder_get_name(encoder)); return false; } @@ -2126,8 +1992,7 @@ bool obs_encoder_set_group(obs_encoder_t *encoder, obs_encoder_group_t *group) pthread_mutex_lock(&old_group->mutex); if (old_group->num_encoders_started) { pthread_mutex_unlock(&old_group->mutex); - blog(LOG_ERROR, - "obs_encoder_set_group: encoder '%s' existing group has started encoders", + blog(LOG_ERROR, "obs_encoder_set_group: encoder '%s' existing group has started encoders", obs_encoder_get_name(encoder)); return false; } @@ -2143,8 +2008,7 @@ bool obs_encoder_set_group(obs_encoder_t *encoder, obs_encoder_group_t *group) if (group->num_encoders_started) { pthread_mutex_unlock(&group->mutex); - blog(LOG_ERROR, - "obs_encoder_set_group: specified group has started encoders"); + blog(LOG_ERROR, "obs_encoder_set_group: specified group has started encoders"); return false; } @@ -2163,8 +2027,7 @@ bool obs_encoder_set_group(obs_encoder_t *encoder, obs_encoder_group_t *group) obs_encoder_group_t *obs_encoder_group_create() { - struct obs_encoder_group *group = - bzalloc(sizeof(struct obs_encoder_group)); + struct obs_encoder_group *group = bzalloc(sizeof(struct obs_encoder_group)); pthread_mutex_init_value(&group->mutex); if (pthread_mutex_init(&group->mutex, NULL) != 0) { diff --git a/libobs/obs-encoder.h b/libobs/obs-encoder.h index 780e0fe0e..475c82380 100644 --- a/libobs/obs-encoder.h +++ b/libobs/obs-encoder.h @@ -244,8 +244,7 @@ struct obs_encoder_info { * false otherwise * @return true if successful, false otherwise. */ - bool (*encode)(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet); + bool (*encode)(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet); /** Audio encoder only: Returns the frame size for this encoder */ size_t (*get_frame_size)(void *data); @@ -340,20 +339,14 @@ struct obs_encoder_info { */ obs_properties_t *(*get_properties2)(void *data, void *type_data); - bool (*encode_texture)(void *data, uint32_t handle, int64_t pts, - uint64_t lock_key, uint64_t *next_key, - struct encoder_packet *packet, - bool *received_packet); + bool (*encode_texture)(void *data, uint32_t handle, int64_t pts, uint64_t lock_key, uint64_t *next_key, + struct encoder_packet *packet, bool *received_packet); - bool (*encode_texture2)(void *data, struct encoder_texture *texture, - int64_t pts, uint64_t lock_key, - uint64_t *next_key, - struct encoder_packet *packet, - bool *received_packet); + bool (*encode_texture2)(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key, + uint64_t *next_key, struct encoder_packet *packet, bool *received_packet); }; -EXPORT void obs_register_encoder_s(const struct obs_encoder_info *info, - size_t size); +EXPORT void obs_register_encoder_s(const struct obs_encoder_info *info, size_t size); /** * Register an encoder definition to the current obs context. This should be @@ -361,8 +354,7 @@ EXPORT void obs_register_encoder_s(const struct obs_encoder_info *info, * * @param info Pointer to the source definition structure. */ -#define obs_register_encoder(info) \ - obs_register_encoder_s(info, sizeof(struct obs_encoder_info)) +#define obs_register_encoder(info) obs_register_encoder_s(info, sizeof(struct obs_encoder_info)) #ifdef __cplusplus } diff --git a/libobs/obs-ffmpeg-compat.h b/libobs/obs-ffmpeg-compat.h index 225968044..7d8288a28 100644 --- a/libobs/obs-ffmpeg-compat.h +++ b/libobs/obs-ffmpeg-compat.h @@ -6,10 +6,8 @@ * a is the major version * b and c the minor and micro versions of libav * d and e the minor and micro versions of FFmpeg */ -#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \ - ((LIBAVCODEC_VERSION_MICRO < 100 && \ - LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \ - (LIBAVCODEC_VERSION_MICRO >= 100 && \ - LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e))) +#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \ + ((LIBAVCODEC_VERSION_MICRO < 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \ + (LIBAVCODEC_VERSION_MICRO >= 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e))) #define INPUT_BUFFER_PADDING_SIZE AV_INPUT_BUFFER_PADDING_SIZE diff --git a/libobs/obs-hevc.c b/libobs/obs-hevc.c index 2fd8d0ecb..48c476184 100644 --- a/libobs/obs-hevc.c +++ b/libobs/obs-hevc.c @@ -46,8 +46,7 @@ bool obs_hevc_keyframe(const uint8_t *data, size_t size) return false; } -static int compute_hevc_keyframe_priority(const uint8_t *nal_start, - bool *is_keyframe, int priority) +static int compute_hevc_keyframe_priority(const uint8_t *nal_start, bool *is_keyframe, int priority) { // HEVC contains NAL unit specifier at [6..1] bits of // the byte next to the startcode 0x000001 @@ -56,12 +55,10 @@ static int compute_hevc_keyframe_priority(const uint8_t *nal_start, // Mark IDR slices as key-frames and set them to highest // priority if needed. Assume other slices are non-key // frames and set their priority as high - if (type >= OBS_HEVC_NAL_BLA_W_LP && - type <= OBS_HEVC_NAL_RSV_IRAP_VCL23) { + if (type >= OBS_HEVC_NAL_BLA_W_LP && type <= OBS_HEVC_NAL_RSV_IRAP_VCL23) { *is_keyframe = 1; priority = OBS_NAL_PRIORITY_HIGHEST; - } else if (type >= OBS_HEVC_NAL_TRAIL_N && - type <= OBS_HEVC_NAL_RASL_R) { + } else if (type >= OBS_HEVC_NAL_TRAIL_N && type <= OBS_HEVC_NAL_RASL_R) { if (priority < OBS_NAL_PRIORITY_HIGH) priority = OBS_NAL_PRIORITY_HIGH; } @@ -69,8 +66,8 @@ static int compute_hevc_keyframe_priority(const uint8_t *nal_start, return priority; } -static void serialize_hevc_data(struct serializer *s, const uint8_t *data, - size_t size, bool *is_keyframe, int *priority) +static void serialize_hevc_data(struct serializer *s, const uint8_t *data, size_t size, bool *is_keyframe, + int *priority) { const uint8_t *const end = data + size; const uint8_t *nal_start = obs_nal_find_startcode(data, end); @@ -81,11 +78,9 @@ static void serialize_hevc_data(struct serializer *s, const uint8_t *data, if (nal_start == end) break; - *priority = compute_hevc_keyframe_priority( - nal_start, is_keyframe, *priority); + *priority = compute_hevc_keyframe_priority(nal_start, is_keyframe, *priority); - const uint8_t *const nal_end = - obs_nal_find_startcode(nal_start, end); + const uint8_t *const nal_end = obs_nal_find_startcode(nal_start, end); const size_t nal_size = nal_end - nal_start; s_wb32(s, (uint32_t)nal_size); s_write(s, nal_start, nal_size); @@ -93,8 +88,7 @@ static void serialize_hevc_data(struct serializer *s, const uint8_t *data, } } -void obs_parse_hevc_packet(struct encoder_packet *hevc_packet, - const struct encoder_packet *src) +void obs_parse_hevc_packet(struct encoder_packet *hevc_packet, const struct encoder_packet *src) { struct array_output_data output; struct serializer s; @@ -104,8 +98,7 @@ void obs_parse_hevc_packet(struct encoder_packet *hevc_packet, *hevc_packet = *src; serialize(&s, &ref, sizeof(ref)); - serialize_hevc_data(&s, src->data, src->size, &hevc_packet->keyframe, - &hevc_packet->priority); + serialize_hevc_data(&s, src->data, src->size, &hevc_packet->keyframe, &hevc_packet->priority); hevc_packet->data = output.bytes.array + sizeof(ref); hevc_packet->size = output.bytes.num - sizeof(ref); @@ -127,8 +120,7 @@ int obs_parse_hevc_packet_priority(const struct encoder_packet *packet) break; bool unused; - priority = compute_hevc_keyframe_priority(nal_start, &unused, - priority); + priority = compute_hevc_keyframe_priority(nal_start, &unused, priority); nal_start = obs_nal_find_startcode(nal_start, end); } @@ -136,11 +128,8 @@ int obs_parse_hevc_packet_priority(const struct encoder_packet *packet) return priority; } -void obs_extract_hevc_headers(const uint8_t *packet, size_t size, - uint8_t **new_packet_data, - size_t *new_packet_size, uint8_t **header_data, - size_t *header_size, uint8_t **sei_data, - size_t *sei_size) +void obs_extract_hevc_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, size_t *new_packet_size, + uint8_t **header_data, size_t *header_size, uint8_t **sei_data, size_t *sei_size) { DARRAY(uint8_t) new_packet; DARRAY(uint8_t) header; @@ -169,18 +158,13 @@ void obs_extract_hevc_headers(const uint8_t *packet, size_t size, if (!nal_end) nal_end = end; - if (type == OBS_HEVC_NAL_VPS || type == OBS_HEVC_NAL_SPS || - type == OBS_HEVC_NAL_PPS) { - da_push_back_array(header, nal_codestart, - nal_end - nal_codestart); - } else if (type == OBS_HEVC_NAL_SEI_PREFIX || - type == OBS_HEVC_NAL_SEI_SUFFIX) { - da_push_back_array(sei, nal_codestart, - nal_end - nal_codestart); + if (type == OBS_HEVC_NAL_VPS || type == OBS_HEVC_NAL_SPS || type == OBS_HEVC_NAL_PPS) { + da_push_back_array(header, nal_codestart, nal_end - nal_codestart); + } else if (type == OBS_HEVC_NAL_SEI_PREFIX || type == OBS_HEVC_NAL_SEI_SUFFIX) { + da_push_back_array(sei, nal_codestart, nal_end - nal_codestart); } else { - da_push_back_array(new_packet, nal_codestart, - nal_end - nal_codestart); + da_push_back_array(new_packet, nal_codestart, nal_end - nal_codestart); } nal_start = nal_end; diff --git a/libobs/obs-hevc.h b/libobs/obs-hevc.h index fd7404f22..a65147054 100644 --- a/libobs/obs-hevc.h +++ b/libobs/obs-hevc.h @@ -70,13 +70,10 @@ enum { }; EXPORT bool obs_hevc_keyframe(const uint8_t *data, size_t size); -EXPORT void obs_parse_hevc_packet(struct encoder_packet *hevc_packet, - const struct encoder_packet *src); +EXPORT void obs_parse_hevc_packet(struct encoder_packet *hevc_packet, const struct encoder_packet *src); EXPORT int obs_parse_hevc_packet_priority(const struct encoder_packet *packet); -EXPORT void obs_extract_hevc_headers(const uint8_t *packet, size_t size, - uint8_t **new_packet_data, - size_t *new_packet_size, - uint8_t **header_data, size_t *header_size, +EXPORT void obs_extract_hevc_headers(const uint8_t *packet, size_t size, uint8_t **new_packet_data, + size_t *new_packet_size, uint8_t **header_data, size_t *header_size, uint8_t **sei_data, size_t *sei_size); #ifdef __cplusplus diff --git a/libobs/obs-hotkey-name-map.c b/libobs/obs-hotkey-name-map.c index 6ef6b36ad..6d9db805c 100644 --- a/libobs/obs-hotkey-name-map.c +++ b/libobs/obs-hotkey-name-map.c @@ -33,8 +33,7 @@ struct obs_hotkey_name_map_item { UT_hash_handle hh; }; -static void obs_hotkey_name_map_insert(obs_hotkey_name_map_item_t **hmap, - const char *key, int v) +static void obs_hotkey_name_map_insert(obs_hotkey_name_map_item_t **hmap, const char *key, int v) { if (!hmap || !key) return; @@ -51,8 +50,7 @@ static void obs_hotkey_name_map_insert(obs_hotkey_name_map_item_t **hmap, HASH_ADD_STR(*hmap, key, t); } -static bool obs_hotkey_name_map_lookup(obs_hotkey_name_map_item_t *hmap, - const char *key, int *v) +static bool obs_hotkey_name_map_lookup(obs_hotkey_name_map_item_t *hmap, const char *key, int *v) { if (!hmap || !key) return false; diff --git a/libobs/obs-hotkey.c b/libobs/obs-hotkey.c index dc2af467b..0503b3033 100644 --- a/libobs/obs-hotkey.c +++ b/libobs/obs-hotkey.c @@ -26,10 +26,8 @@ #define HASH_FUNCTION(s, len, hashv) (hashv) = *s % UINT_MAX /* Custom definitions to make adding/looking up size_t integers easier */ -#define HASH_ADD_HKEY(head, idfield, add) \ - HASH_ADD(hh, head, idfield, sizeof(size_t), add) -#define HASH_FIND_HKEY(head, id, out) \ - HASH_FIND(hh, head, &(id), sizeof(size_t), out) +#define HASH_ADD_HKEY(head, idfield, add) HASH_ADD(hh, head, idfield, sizeof(size_t), add) +#define HASH_FIND_HKEY(head, id, out) HASH_FIND(hh, head, &(id), sizeof(size_t), out) static inline bool lock(void) { @@ -75,8 +73,7 @@ obs_hotkey_id obs_hotkey_get_pair_partner_id(const obs_hotkey_t *key) return key->pair_partner_id; } -obs_key_combination_t -obs_hotkey_binding_get_key_combination(obs_hotkey_binding_t *binding) +obs_key_combination_t obs_hotkey_binding_get_key_combination(obs_hotkey_binding_t *binding) { return binding->key; } @@ -113,8 +110,7 @@ void obs_hotkey_set_description(obs_hotkey_id id, const char *desc) hotkey->description = bstrdup(desc); } -void obs_hotkey_pair_set_names(obs_hotkey_pair_id id, const char *name0, - const char *name1) +void obs_hotkey_pair_set_names(obs_hotkey_pair_id id, const char *name0, const char *name1) { obs_hotkey_pair_t *pair; @@ -126,8 +122,7 @@ void obs_hotkey_pair_set_names(obs_hotkey_pair_id id, const char *name0, obs_hotkey_set_name(pair->id[1], name1); } -void obs_hotkey_pair_set_descriptions(obs_hotkey_pair_id id, const char *desc0, - const char *desc1) +void obs_hotkey_pair_set_descriptions(obs_hotkey_pair_id id, const char *desc0, const char *desc1) { obs_hotkey_pair_t *pair; @@ -152,17 +147,14 @@ static void hotkey_signal(const char *signal, obs_hotkey_t *hotkey) static inline void load_bindings(obs_hotkey_t *hotkey, obs_data_array_t *data); -static inline void context_add_hotkey(struct obs_context_data *context, - obs_hotkey_id id) +static inline void context_add_hotkey(struct obs_context_data *context, obs_hotkey_id id) { da_push_back(context->hotkeys, &id); } -static inline obs_hotkey_id -obs_hotkey_register_internal(obs_hotkey_registerer_t type, void *registerer, - struct obs_context_data *context, const char *name, - const char *description, obs_hotkey_func func, - void *data) +static inline obs_hotkey_id obs_hotkey_register_internal(obs_hotkey_registerer_t type, void *registerer, + struct obs_context_data *context, const char *name, + const char *description, obs_hotkey_func func, void *data) { if ((obs->hotkeys.next_id + 1) == OBS_INVALID_HOTKEY_ID) blog(LOG_WARNING, "obs-hotkey: Available hotkey ids exhausted"); @@ -182,8 +174,7 @@ obs_hotkey_register_internal(obs_hotkey_registerer_t type, void *registerer, HASH_ADD_HKEY(obs->hotkeys.hotkeys, id, hotkey); if (context) { - obs_data_array_t *data = - obs_data_get_array(context->hotkey_data, name); + obs_data_array_t *data = obs_data_get_array(context->hotkey_data, name); load_bindings(hotkey, data); obs_data_array_release(data); @@ -195,91 +186,76 @@ obs_hotkey_register_internal(obs_hotkey_registerer_t type, void *registerer, return result; } -obs_hotkey_id obs_hotkey_register_frontend(const char *name, - const char *description, - obs_hotkey_func func, void *data) +obs_hotkey_id obs_hotkey_register_frontend(const char *name, const char *description, obs_hotkey_func func, void *data) { if (!lock()) return OBS_INVALID_HOTKEY_ID; - obs_hotkey_id id = obs_hotkey_register_internal( - OBS_HOTKEY_REGISTERER_FRONTEND, NULL, NULL, name, description, - func, data); + obs_hotkey_id id = + obs_hotkey_register_internal(OBS_HOTKEY_REGISTERER_FRONTEND, NULL, NULL, name, description, func, data); unlock(); return id; } -obs_hotkey_id obs_hotkey_register_encoder(obs_encoder_t *encoder, - const char *name, - const char *description, +obs_hotkey_id obs_hotkey_register_encoder(obs_encoder_t *encoder, const char *name, const char *description, obs_hotkey_func func, void *data) { if (!encoder || !lock()) return OBS_INVALID_HOTKEY_ID; - obs_hotkey_id id = obs_hotkey_register_internal( - OBS_HOTKEY_REGISTERER_ENCODER, - obs_encoder_get_weak_encoder(encoder), &encoder->context, name, - description, func, data); + obs_hotkey_id id = obs_hotkey_register_internal(OBS_HOTKEY_REGISTERER_ENCODER, + obs_encoder_get_weak_encoder(encoder), &encoder->context, name, + description, func, data); unlock(); return id; } -obs_hotkey_id obs_hotkey_register_output(obs_output_t *output, const char *name, - const char *description, +obs_hotkey_id obs_hotkey_register_output(obs_output_t *output, const char *name, const char *description, obs_hotkey_func func, void *data) { if (!output || !lock()) return OBS_INVALID_HOTKEY_ID; - obs_hotkey_id id = obs_hotkey_register_internal( - OBS_HOTKEY_REGISTERER_OUTPUT, - obs_output_get_weak_output(output), &output->context, name, - description, func, data); + obs_hotkey_id id = obs_hotkey_register_internal(OBS_HOTKEY_REGISTERER_OUTPUT, + obs_output_get_weak_output(output), &output->context, name, + description, func, data); unlock(); return id; } -obs_hotkey_id obs_hotkey_register_service(obs_service_t *service, - const char *name, - const char *description, +obs_hotkey_id obs_hotkey_register_service(obs_service_t *service, const char *name, const char *description, obs_hotkey_func func, void *data) { if (!service || !lock()) return OBS_INVALID_HOTKEY_ID; - obs_hotkey_id id = obs_hotkey_register_internal( - OBS_HOTKEY_REGISTERER_SERVICE, - obs_service_get_weak_service(service), &service->context, name, - description, func, data); + obs_hotkey_id id = obs_hotkey_register_internal(OBS_HOTKEY_REGISTERER_SERVICE, + obs_service_get_weak_service(service), &service->context, name, + description, func, data); unlock(); return id; } -obs_hotkey_id obs_hotkey_register_source(obs_source_t *source, const char *name, - const char *description, +obs_hotkey_id obs_hotkey_register_source(obs_source_t *source, const char *name, const char *description, obs_hotkey_func func, void *data) { if (!source || source->context.private || !lock()) return OBS_INVALID_HOTKEY_ID; - obs_hotkey_id id = obs_hotkey_register_internal( - OBS_HOTKEY_REGISTERER_SOURCE, - obs_source_get_weak_source(source), &source->context, name, - description, func, data); + obs_hotkey_id id = obs_hotkey_register_internal(OBS_HOTKEY_REGISTERER_SOURCE, + obs_source_get_weak_source(source), &source->context, name, + description, func, data); unlock(); return id; } -static obs_hotkey_pair_t *create_hotkey_pair(struct obs_context_data *context, - obs_hotkey_active_func func0, - obs_hotkey_active_func func1, - void *data0, void *data1) +static obs_hotkey_pair_t *create_hotkey_pair(struct obs_context_data *context, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1) { if ((obs->hotkeys.next_pair_id + 1) == OBS_INVALID_HOTKEY_PAIR_ID) blog(LOG_WARNING, "obs-hotkey: Available hotkey pair ids " @@ -303,8 +279,7 @@ static obs_hotkey_pair_t *create_hotkey_pair(struct obs_context_data *context, return pair; } -static void obs_hotkey_pair_first_func(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void obs_hotkey_pair_first_func(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); @@ -318,8 +293,7 @@ static void obs_hotkey_pair_first_func(void *data, obs_hotkey_id id, pair->pressed0 = pressed; } -static void obs_hotkey_pair_second_func(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void obs_hotkey_pair_second_func(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); @@ -333,29 +307,23 @@ static void obs_hotkey_pair_second_func(void *data, obs_hotkey_id id, pair->pressed1 = pressed; } -static obs_hotkey_pair_id register_hotkey_pair_internal( - obs_hotkey_registerer_t type, void *registerer, - void *(*weak_ref)(void *), struct obs_context_data *context, - const char *name0, const char *description0, const char *name1, - const char *description1, obs_hotkey_active_func func0, - obs_hotkey_active_func func1, void *data0, void *data1) +static obs_hotkey_pair_id register_hotkey_pair_internal(obs_hotkey_registerer_t type, void *registerer, + void *(*weak_ref)(void *), struct obs_context_data *context, + const char *name0, const char *description0, const char *name1, + const char *description1, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1) { if (!lock()) return OBS_INVALID_HOTKEY_PAIR_ID; - obs_hotkey_pair_t *pair = - create_hotkey_pair(context, func0, func1, data0, data1); + obs_hotkey_pair_t *pair = create_hotkey_pair(context, func0, func1, data0, data1); - pair->id[0] = obs_hotkey_register_internal(type, weak_ref(registerer), - context, name0, description0, - obs_hotkey_pair_first_func, - pair); + pair->id[0] = obs_hotkey_register_internal(type, weak_ref(registerer), context, name0, description0, + obs_hotkey_pair_first_func, pair); - pair->id[1] = obs_hotkey_register_internal(type, weak_ref(registerer), - context, name1, description1, - obs_hotkey_pair_second_func, - pair); + pair->id[1] = obs_hotkey_register_internal(type, weak_ref(registerer), context, name1, description1, + obs_hotkey_pair_second_func, pair); obs_hotkey_t *hotkey_1, *hotkey_2; HASH_FIND_HKEY(obs->hotkeys.hotkeys, pair->id[0], hotkey_1); @@ -377,15 +345,12 @@ static inline void *obs_id_(void *id_) return id_; } -obs_hotkey_pair_id obs_hotkey_pair_register_frontend( - const char *name0, const char *description0, const char *name1, - const char *description1, obs_hotkey_active_func func0, - obs_hotkey_active_func func1, void *data0, void *data1) +obs_hotkey_pair_id obs_hotkey_pair_register_frontend(const char *name0, const char *description0, const char *name1, + const char *description1, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1) { - return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_FRONTEND, - NULL, obs_id_, NULL, name0, - description0, name1, description1, - func0, func1, data0, data1); + return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_FRONTEND, NULL, obs_id_, NULL, name0, description0, + name1, description1, func0, func1, data0, data1); } static inline void *weak_encoder_ref(void *ref) @@ -393,19 +358,16 @@ static inline void *weak_encoder_ref(void *ref) return obs_encoder_get_weak_encoder(ref); } -obs_hotkey_pair_id obs_hotkey_pair_register_encoder( - obs_encoder_t *encoder, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1) +obs_hotkey_pair_id obs_hotkey_pair_register_encoder(obs_encoder_t *encoder, const char *name0, const char *description0, + const char *name1, const char *description1, + obs_hotkey_active_func func0, obs_hotkey_active_func func1, + void *data0, void *data1) { if (!encoder) return OBS_INVALID_HOTKEY_PAIR_ID; - return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_ENCODER, - encoder, weak_encoder_ref, - &encoder->context, name0, - description0, name1, description1, - func0, func1, data0, data1); + return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_ENCODER, encoder, weak_encoder_ref, + &encoder->context, name0, description0, name1, description1, func0, func1, + data0, data1); } static inline void *weak_output_ref(void *ref) @@ -413,19 +375,15 @@ static inline void *weak_output_ref(void *ref) return obs_output_get_weak_output(ref); } -obs_hotkey_pair_id obs_hotkey_pair_register_output( - obs_output_t *output, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1) +obs_hotkey_pair_id obs_hotkey_pair_register_output(obs_output_t *output, const char *name0, const char *description0, + const char *name1, const char *description1, + obs_hotkey_active_func func0, obs_hotkey_active_func func1, + void *data0, void *data1) { if (!output) return OBS_INVALID_HOTKEY_PAIR_ID; - return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_OUTPUT, - output, weak_output_ref, - &output->context, name0, - description0, name1, description1, - func0, func1, data0, data1); + return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_OUTPUT, output, weak_output_ref, &output->context, + name0, description0, name1, description1, func0, func1, data0, data1); } static inline void *weak_service_ref(void *ref) @@ -433,19 +391,16 @@ static inline void *weak_service_ref(void *ref) return obs_service_get_weak_service(ref); } -obs_hotkey_pair_id obs_hotkey_pair_register_service( - obs_service_t *service, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1) +obs_hotkey_pair_id obs_hotkey_pair_register_service(obs_service_t *service, const char *name0, const char *description0, + const char *name1, const char *description1, + obs_hotkey_active_func func0, obs_hotkey_active_func func1, + void *data0, void *data1) { if (!service) return OBS_INVALID_HOTKEY_PAIR_ID; - return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_SERVICE, - service, weak_service_ref, - &service->context, name0, - description0, name1, description1, - func0, func1, data0, data1); + return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_SERVICE, service, weak_service_ref, + &service->context, name0, description0, name1, description1, func0, func1, + data0, data1); } static inline void *weak_source_ref(void *ref) @@ -453,26 +408,20 @@ static inline void *weak_source_ref(void *ref) return obs_source_get_weak_source(ref); } -obs_hotkey_pair_id obs_hotkey_pair_register_source( - obs_source_t *source, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1) +obs_hotkey_pair_id obs_hotkey_pair_register_source(obs_source_t *source, const char *name0, const char *description0, + const char *name1, const char *description1, + obs_hotkey_active_func func0, obs_hotkey_active_func func1, + void *data0, void *data1) { if (!source) return OBS_INVALID_HOTKEY_PAIR_ID; - return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_SOURCE, - source, weak_source_ref, - &source->context, name0, - description0, name1, description1, - func0, func1, data0, data1); + return register_hotkey_pair_internal(OBS_HOTKEY_REGISTERER_SOURCE, source, weak_source_ref, &source->context, + name0, description0, name1, description1, func0, func1, data0, data1); } -typedef bool (*obs_hotkey_binding_internal_enum_func)( - void *data, size_t idx, obs_hotkey_binding_t *binding); +typedef bool (*obs_hotkey_binding_internal_enum_func)(void *data, size_t idx, obs_hotkey_binding_t *binding); -static inline void enum_bindings(obs_hotkey_binding_internal_enum_func func, - void *data) +static inline void enum_bindings(obs_hotkey_binding_internal_enum_func func, void *data) { const size_t num = obs->hotkeys.bindings.num; obs_hotkey_binding_t *array = obs->hotkeys.bindings.array; @@ -484,8 +433,7 @@ static inline void enum_bindings(obs_hotkey_binding_internal_enum_func func, typedef bool (*obs_hotkey_internal_enum_func)(void *data, obs_hotkey_t *hotkey); -static inline void enum_context_hotkeys(struct obs_context_data *context, - obs_hotkey_internal_enum_func func, +static inline void enum_context_hotkeys(struct obs_context_data *context, obs_hotkey_internal_enum_func func, void *data) { const size_t num = context->hotkeys.num; @@ -501,15 +449,13 @@ static inline void enum_context_hotkeys(struct obs_context_data *context, } } -static inline void load_modifier(uint32_t *modifiers, obs_data_t *data, - const char *name, uint32_t flag) +static inline void load_modifier(uint32_t *modifiers, obs_data_t *data, const char *name, uint32_t flag) { if (obs_data_get_bool(data, name)) *modifiers |= flag; } -static inline void create_binding(obs_hotkey_t *hotkey, - obs_key_combination_t combo) +static inline void create_binding(obs_hotkey_t *hotkey, obs_key_combination_t combo) { obs_hotkey_binding_t *binding = da_push_back_new(obs->hotkeys.bindings); if (!binding) @@ -533,8 +479,7 @@ static inline void load_binding(obs_hotkey_t *hotkey, obs_data_t *data) load_modifier(modifiers, data, "command", INTERACT_COMMAND_KEY); combo.key = obs_key_from_name(obs_data_get_string(data, "key")); - if (!modifiers && - (combo.key == OBS_KEY_NONE || combo.key >= OBS_KEY_LAST_VALUE)) + if (!modifiers && (combo.key == OBS_KEY_NONE || combo.key >= OBS_KEY_LAST_VALUE)) return; create_binding(hotkey, combo); @@ -555,8 +500,7 @@ static inline void load_bindings(obs_hotkey_t *hotkey, obs_data_array_t *data) static inline bool remove_bindings(obs_hotkey_id id); -void obs_hotkey_load_bindings(obs_hotkey_id id, - obs_key_combination_t *combinations, size_t num) +void obs_hotkey_load_bindings(obs_hotkey_id id, obs_key_combination_t *combinations, size_t num) { if (!lock()) return; @@ -644,8 +588,7 @@ void obs_hotkeys_load_source(obs_source_t *source, obs_data_t *hotkeys) unlock(); } -void obs_hotkey_pair_load(obs_hotkey_pair_id id, obs_data_array_t *data0, - obs_data_array_t *data1) +void obs_hotkey_pair_load(obs_hotkey_pair_id id, obs_data_array_t *data0, obs_data_array_t *data1) { if ((!data0 && !data1) || !lock()) return; @@ -672,8 +615,7 @@ unlock: unlock(); } -static inline void save_modifier(uint32_t modifiers, obs_data_t *data, - const char *name, uint32_t flag) +static inline void save_modifier(uint32_t modifiers, obs_data_t *data, const char *name, uint32_t flag) { if ((modifiers & flag) == flag) obs_data_set_bool(data, name, true); @@ -684,8 +626,7 @@ struct save_bindings_helper_t { obs_hotkey_t *hotkey; }; -static inline bool save_bindings_helper(void *data, size_t idx, - obs_hotkey_binding_t *binding) +static inline bool save_bindings_helper(void *data, size_t idx, obs_hotkey_binding_t *binding) { UNUSED_PARAMETER(idx); struct save_bindings_helper_t *h = data; @@ -737,8 +678,7 @@ obs_data_array_t *obs_hotkey_save(obs_hotkey_id id) return result; } -void obs_hotkey_pair_save(obs_hotkey_pair_id id, obs_data_array_t **p_data0, - obs_data_array_t **p_data1) +void obs_hotkey_pair_save(obs_hotkey_pair_id id, obs_data_array_t **p_data0, obs_data_array_t **p_data1) { if ((!p_data0 && !p_data1) || !lock()) return; @@ -840,8 +780,7 @@ struct binding_find_data { bool found; }; -static inline bool binding_finder(void *data, size_t idx, - obs_hotkey_binding_t *binding) +static inline bool binding_finder(void *data, size_t idx, obs_hotkey_binding_t *binding) { struct binding_find_data *find = data; if (binding->hotkey_id != find->id) @@ -866,8 +805,7 @@ static inline bool remove_bindings(obs_hotkey_id id) bool removed = false; size_t idx; while (find_binding(id, &idx)) { - obs_hotkey_binding_t *binding = - &obs->hotkeys.bindings.array[idx]; + obs_hotkey_binding_t *binding = &obs->hotkeys.bindings.array[idx]; if (binding->pressed) release_pressed_binding(binding); @@ -1052,8 +990,7 @@ void obs_enum_hotkey_bindings(obs_hotkey_binding_enum_func func, void *data) unlock(); } -static inline bool modifiers_match(obs_hotkey_binding_t *binding, - uint32_t modifiers_, bool strict_modifiers) +static inline bool modifiers_match(obs_hotkey_binding_t *binding, uint32_t modifiers_, bool strict_modifiers) { uint32_t modifiers = binding->key.modifiers; if (!strict_modifiers) @@ -1064,8 +1001,7 @@ static inline bool modifiers_match(obs_hotkey_binding_t *binding, static inline bool is_pressed(obs_key_t key) { - return obs_hotkeys_platform_is_pressed(obs->hotkeys.platform_context, - key); + return obs_hotkeys_platform_is_pressed(obs->hotkeys.platform_context, key); } static inline void press_released_binding(obs_hotkey_binding_t *binding) @@ -1079,8 +1015,7 @@ static inline void press_released_binding(obs_hotkey_binding_t *binding) if (!obs->hotkeys.reroute_hotkeys) hotkey->func(hotkey->data, hotkey->id, hotkey, true); else if (obs->hotkeys.router_func) - obs->hotkeys.router_func(obs->hotkeys.router_func_data, - hotkey->id, true); + obs->hotkeys.router_func(obs->hotkeys.router_func_data, hotkey->id, true); } static inline void release_pressed_binding(obs_hotkey_binding_t *binding) @@ -1094,16 +1029,13 @@ static inline void release_pressed_binding(obs_hotkey_binding_t *binding) if (!obs->hotkeys.reroute_hotkeys) hotkey->func(hotkey->data, hotkey->id, hotkey, false); else if (obs->hotkeys.router_func) - obs->hotkeys.router_func(obs->hotkeys.router_func_data, - hotkey->id, false); + obs->hotkeys.router_func(obs->hotkeys.router_func_data, hotkey->id, false); } -static inline void handle_binding(obs_hotkey_binding_t *binding, - uint32_t modifiers, bool no_press, +static inline void handle_binding(obs_hotkey_binding_t *binding, uint32_t modifiers, bool no_press, bool strict_modifiers, bool *pressed) { - bool modifiers_match_ = - modifiers_match(binding, modifiers, strict_modifiers); + bool modifiers_match_ = modifiers_match(binding, modifiers, strict_modifiers); bool modifiers_only = binding->key.key == OBS_KEY_NONE; if (!strict_modifiers && !binding->key.modifiers) @@ -1118,8 +1050,7 @@ static inline void handle_binding(obs_hotkey_binding_t *binding, if ((!binding->modifiers_match && !modifiers_only) || !modifiers_match_) goto reset; - if ((pressed && !*pressed) || - (!pressed && !is_pressed(binding->key.key))) + if ((pressed && !*pressed) || (!pressed && !is_pressed(binding->key.key))) goto reset; if (binding->pressed || no_press) @@ -1142,16 +1073,13 @@ struct obs_hotkey_internal_inject { bool strict_modifiers; }; -static inline bool inject_hotkey(void *data, size_t idx, - obs_hotkey_binding_t *binding) +static inline bool inject_hotkey(void *data, size_t idx, obs_hotkey_binding_t *binding) { UNUSED_PARAMETER(idx); struct obs_hotkey_internal_inject *event = data; - if (modifiers_match(binding, event->hotkey.modifiers, - event->strict_modifiers)) { - bool pressed = binding->key.key == event->hotkey.key && - event->pressed; + if (modifiers_match(binding, event->hotkey.modifiers, event->strict_modifiers)) { + bool pressed = binding->key.key == event->hotkey.key && event->pressed; if (binding->key.key == OBS_KEY_NONE) pressed = true; @@ -1194,15 +1122,12 @@ struct obs_query_hotkeys_helper { bool strict_modifiers; }; -static inline bool query_hotkey(void *data, size_t idx, - obs_hotkey_binding_t *binding) +static inline bool query_hotkey(void *data, size_t idx, obs_hotkey_binding_t *binding) { UNUSED_PARAMETER(idx); - struct obs_query_hotkeys_helper *param = - (struct obs_query_hotkeys_helper *)data; - handle_binding(binding, param->modifiers, param->no_press, - param->strict_modifiers, NULL); + struct obs_query_hotkeys_helper *param = (struct obs_query_hotkeys_helper *)data; + handle_binding(binding, param->modifiers, param->no_press, param->strict_modifiers, NULL); return true; } @@ -1236,8 +1161,7 @@ void *obs_hotkey_thread(void *arg) os_set_thread_name("libobs: hotkey thread"); const char *hotkey_thread_name = - profile_store_name(obs_get_profiler_name_store(), - "obs_hotkey_thread(%g" NBSP "ms)", 25.); + profile_store_name(obs_get_profiler_name_store(), "obs_hotkey_thread(%g" NBSP "ms)", 25.); profile_register_root(hotkey_thread_name, (uint64_t)25000000); while (os_event_timedwait(obs->hotkeys.stop_event, 25) == ETIMEDOUT) { @@ -1274,8 +1198,7 @@ unlock: unlock(); } -void obs_hotkey_set_callback_routing_func(obs_hotkey_callback_router_func func, - void *data) +void obs_hotkey_set_callback_routing_func(obs_hotkey_callback_router_func func, void *data) { if (!lock()) return; @@ -1303,8 +1226,7 @@ static void obs_set_key_translation(obs_key_t key, const char *translation) obs->hotkeys.translations[key] = bstrdup(translation); } -void obs_hotkeys_set_translations_s( - struct obs_hotkeys_translations *translations, size_t size) +void obs_hotkeys_set_translations_s(struct obs_hotkeys_translations *translations, size_t size) { #define ADD_TRANSLATION(key_name, var_name) \ if (t.var_name) \ @@ -1438,8 +1360,7 @@ const char *obs_get_hotkey_translation(obs_key_t key, const char *def) return NULL; } - return obs->hotkeys.translations[key] ? obs->hotkeys.translations[key] - : def; + return obs->hotkeys.translations[key] ? obs->hotkeys.translations[key] : def; } void obs_hotkey_update_atomic(obs_hotkey_atomic_update_func func, void *data) @@ -1452,9 +1373,7 @@ void obs_hotkey_update_atomic(obs_hotkey_atomic_update_func func, void *data) unlock(); } -void obs_hotkeys_set_audio_hotkeys_translations(const char *mute, - const char *unmute, - const char *push_to_mute, +void obs_hotkeys_set_audio_hotkeys_translations(const char *mute, const char *unmute, const char *push_to_mute, const char *push_to_talk) { #define SET_T(n) \ @@ -1467,8 +1386,7 @@ void obs_hotkeys_set_audio_hotkeys_translations(const char *mute, #undef SET_T } -void obs_hotkeys_set_sceneitem_hotkeys_translations(const char *show, - const char *hide) +void obs_hotkeys_set_sceneitem_hotkeys_translations(const char *show, const char *hide) { #define SET_T(n) \ bfree(obs->hotkeys.sceneitem_##n); \ diff --git a/libobs/obs-hotkey.h b/libobs/obs-hotkey.h index 4244a69df..0fa6ccc45 100644 --- a/libobs/obs-hotkey.h +++ b/libobs/obs-hotkey.h @@ -65,27 +65,20 @@ typedef enum obs_hotkey_registerer_type obs_hotkey_registerer_t; EXPORT obs_hotkey_id obs_hotkey_get_id(const obs_hotkey_t *key); EXPORT const char *obs_hotkey_get_name(const obs_hotkey_t *key); EXPORT const char *obs_hotkey_get_description(const obs_hotkey_t *key); -EXPORT obs_hotkey_registerer_t -obs_hotkey_get_registerer_type(const obs_hotkey_t *key); +EXPORT obs_hotkey_registerer_t obs_hotkey_get_registerer_type(const obs_hotkey_t *key); EXPORT void *obs_hotkey_get_registerer(const obs_hotkey_t *key); EXPORT obs_hotkey_id obs_hotkey_get_pair_partner_id(const obs_hotkey_t *key); -EXPORT obs_key_combination_t -obs_hotkey_binding_get_key_combination(obs_hotkey_binding_t *binding); -EXPORT obs_hotkey_id -obs_hotkey_binding_get_hotkey_id(obs_hotkey_binding_t *binding); -EXPORT obs_hotkey_t * -obs_hotkey_binding_get_hotkey(obs_hotkey_binding_t *binding); +EXPORT obs_key_combination_t obs_hotkey_binding_get_key_combination(obs_hotkey_binding_t *binding); +EXPORT obs_hotkey_id obs_hotkey_binding_get_hotkey_id(obs_hotkey_binding_t *binding); +EXPORT obs_hotkey_t *obs_hotkey_binding_get_hotkey(obs_hotkey_binding_t *binding); /* setter functions */ EXPORT void obs_hotkey_set_name(obs_hotkey_id id, const char *name); EXPORT void obs_hotkey_set_description(obs_hotkey_id id, const char *desc); -EXPORT void obs_hotkey_pair_set_names(obs_hotkey_pair_id id, const char *name0, - const char *name1); -EXPORT void obs_hotkey_pair_set_descriptions(obs_hotkey_pair_id id, - const char *desc0, - const char *desc1); +EXPORT void obs_hotkey_pair_set_names(obs_hotkey_pair_id id, const char *name0, const char *name1); +EXPORT void obs_hotkey_pair_set_descriptions(obs_hotkey_pair_id id, const char *desc0, const char *desc1); #ifndef SWIG struct obs_hotkeys_translations { @@ -134,88 +127,62 @@ struct obs_hotkeys_translations { * translations for these keys, it will use the operating system's translation * over these translations. If no translations are specified, it will use * the default English translations for that specific operating system. */ -EXPORT void -obs_hotkeys_set_translations_s(struct obs_hotkeys_translations *translations, - size_t size); +EXPORT void obs_hotkeys_set_translations_s(struct obs_hotkeys_translations *translations, size_t size); #endif #define obs_hotkeys_set_translations(translations) \ - obs_hotkeys_set_translations_s( \ - translations, sizeof(struct obs_hotkeys_translations)) + obs_hotkeys_set_translations_s(translations, sizeof(struct obs_hotkeys_translations)) -EXPORT void -obs_hotkeys_set_audio_hotkeys_translations(const char *mute, const char *unmute, - const char *push_to_mute, - const char *push_to_talk); +EXPORT void obs_hotkeys_set_audio_hotkeys_translations(const char *mute, const char *unmute, const char *push_to_mute, + const char *push_to_talk); -EXPORT void obs_hotkeys_set_sceneitem_hotkeys_translations(const char *show, - const char *hide); +EXPORT void obs_hotkeys_set_sceneitem_hotkeys_translations(const char *show, const char *hide); /* registering hotkeys (giving hotkeys a name and a function) */ -typedef void (*obs_hotkey_func)(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed); +typedef void (*obs_hotkey_func)(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed); -EXPORT obs_hotkey_id obs_hotkey_register_frontend(const char *name, - const char *description, - obs_hotkey_func func, +EXPORT obs_hotkey_id obs_hotkey_register_frontend(const char *name, const char *description, obs_hotkey_func func, void *data); -EXPORT obs_hotkey_id obs_hotkey_register_encoder(obs_encoder_t *encoder, - const char *name, - const char *description, - obs_hotkey_func func, - void *data); +EXPORT obs_hotkey_id obs_hotkey_register_encoder(obs_encoder_t *encoder, const char *name, const char *description, + obs_hotkey_func func, void *data); -EXPORT obs_hotkey_id obs_hotkey_register_output(obs_output_t *output, - const char *name, - const char *description, - obs_hotkey_func func, - void *data); +EXPORT obs_hotkey_id obs_hotkey_register_output(obs_output_t *output, const char *name, const char *description, + obs_hotkey_func func, void *data); -EXPORT obs_hotkey_id obs_hotkey_register_service(obs_service_t *service, - const char *name, - const char *description, - obs_hotkey_func func, - void *data); +EXPORT obs_hotkey_id obs_hotkey_register_service(obs_service_t *service, const char *name, const char *description, + obs_hotkey_func func, void *data); -EXPORT obs_hotkey_id obs_hotkey_register_source(obs_source_t *source, - const char *name, - const char *description, - obs_hotkey_func func, - void *data); +EXPORT obs_hotkey_id obs_hotkey_register_source(obs_source_t *source, const char *name, const char *description, + obs_hotkey_func func, void *data); -typedef bool (*obs_hotkey_active_func)(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *hotkey, bool pressed); +typedef bool (*obs_hotkey_active_func)(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed); -EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_frontend( - const char *name0, const char *description0, const char *name1, - const char *description1, obs_hotkey_active_func func0, - obs_hotkey_active_func func1, void *data0, void *data1); +EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_frontend(const char *name0, const char *description0, + const char *name1, const char *description1, + obs_hotkey_active_func func0, obs_hotkey_active_func func1, + void *data0, void *data1); -EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_encoder( - obs_encoder_t *encoder, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1); +EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_encoder(obs_encoder_t *encoder, const char *name0, + const char *description0, const char *name1, + const char *description1, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1); -EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_output( - obs_output_t *output, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1); +EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_output(obs_output_t *output, const char *name0, + const char *description0, const char *name1, + const char *description1, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1); -EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_service( - obs_service_t *service, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1); +EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_service(obs_service_t *service, const char *name0, + const char *description0, const char *name1, + const char *description1, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1); -EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_source( - obs_source_t *source, const char *name0, const char *description0, - const char *name1, const char *description1, - obs_hotkey_active_func func0, obs_hotkey_active_func func1, void *data0, - void *data1); +EXPORT obs_hotkey_pair_id obs_hotkey_pair_register_source(obs_source_t *source, const char *name0, + const char *description0, const char *name1, + const char *description1, obs_hotkey_active_func func0, + obs_hotkey_active_func func1, void *data0, void *data1); EXPORT void obs_hotkey_unregister(obs_hotkey_id id); @@ -223,30 +190,23 @@ EXPORT void obs_hotkey_pair_unregister(obs_hotkey_pair_id id); /* loading hotkeys (associating a hotkey with a physical key and modifiers) */ -EXPORT void obs_hotkey_load_bindings(obs_hotkey_id id, - obs_key_combination_t *combinations, - size_t num); +EXPORT void obs_hotkey_load_bindings(obs_hotkey_id id, obs_key_combination_t *combinations, size_t num); EXPORT void obs_hotkey_load(obs_hotkey_id id, obs_data_array_t *data); -EXPORT void obs_hotkeys_load_encoder(obs_encoder_t *encoder, - obs_data_t *hotkeys); +EXPORT void obs_hotkeys_load_encoder(obs_encoder_t *encoder, obs_data_t *hotkeys); EXPORT void obs_hotkeys_load_output(obs_output_t *output, obs_data_t *hotkeys); -EXPORT void obs_hotkeys_load_service(obs_service_t *service, - obs_data_t *hotkeys); +EXPORT void obs_hotkeys_load_service(obs_service_t *service, obs_data_t *hotkeys); EXPORT void obs_hotkeys_load_source(obs_source_t *source, obs_data_t *hotkeys); -EXPORT void obs_hotkey_pair_load(obs_hotkey_pair_id id, obs_data_array_t *data0, - obs_data_array_t *data1); +EXPORT void obs_hotkey_pair_load(obs_hotkey_pair_id id, obs_data_array_t *data0, obs_data_array_t *data1); EXPORT obs_data_array_t *obs_hotkey_save(obs_hotkey_id id); -EXPORT void obs_hotkey_pair_save(obs_hotkey_pair_id id, - obs_data_array_t **p_data0, - obs_data_array_t **p_data1); +EXPORT void obs_hotkey_pair_save(obs_hotkey_pair_id id, obs_data_array_t **p_data0, obs_data_array_t **p_data1); EXPORT obs_data_t *obs_hotkeys_save_encoder(obs_encoder_t *encoder); @@ -258,18 +218,15 @@ EXPORT obs_data_t *obs_hotkeys_save_source(obs_source_t *source); /* enumerating hotkeys */ -typedef bool (*obs_hotkey_enum_func)(void *data, obs_hotkey_id id, - obs_hotkey_t *key); +typedef bool (*obs_hotkey_enum_func)(void *data, obs_hotkey_id id, obs_hotkey_t *key); EXPORT void obs_enum_hotkeys(obs_hotkey_enum_func func, void *data); /* enumerating bindings */ -typedef bool (*obs_hotkey_binding_enum_func)(void *data, size_t idx, - obs_hotkey_binding_t *binding); +typedef bool (*obs_hotkey_binding_enum_func)(void *data, size_t idx, obs_hotkey_binding_t *binding); -EXPORT void obs_enum_hotkey_bindings(obs_hotkey_binding_enum_func func, - void *data); +EXPORT void obs_enum_hotkey_bindings(obs_hotkey_binding_enum_func func, void *data); /* hotkey event control */ @@ -279,12 +236,9 @@ EXPORT void obs_hotkey_enable_background_press(bool enable); /* hotkey callback routing (trigger callbacks through e.g. a UI thread) */ -typedef void (*obs_hotkey_callback_router_func)(void *data, obs_hotkey_id id, - bool pressed); +typedef void (*obs_hotkey_callback_router_func)(void *data, obs_hotkey_id id, bool pressed); -EXPORT void -obs_hotkey_set_callback_routing_func(obs_hotkey_callback_router_func func, - void *data); +EXPORT void obs_hotkey_set_callback_routing_func(obs_hotkey_callback_router_func func, void *data); EXPORT void obs_hotkey_trigger_routed_callback(obs_hotkey_id id, bool pressed); @@ -295,13 +249,11 @@ EXPORT void obs_hotkey_enable_callback_rerouting(bool enable); /* misc */ typedef void (*obs_hotkey_atomic_update_func)(void *); -EXPORT void obs_hotkey_update_atomic(obs_hotkey_atomic_update_func func, - void *data); +EXPORT void obs_hotkey_update_atomic(obs_hotkey_atomic_update_func func, void *data); struct dstr; EXPORT void obs_key_to_str(obs_key_t key, struct dstr *str); -EXPORT void obs_key_combination_to_str(obs_key_combination_t key, - struct dstr *str); +EXPORT void obs_key_combination_to_str(obs_key_combination_t key, struct dstr *str); EXPORT obs_key_t obs_key_from_virtual_key(int code); EXPORT int obs_key_to_virtual_key(obs_key_t key); diff --git a/libobs/obs-internal.h b/libobs/obs-internal.h index 348e290f7..1fac9c50b 100644 --- a/libobs/obs-internal.h +++ b/libobs/obs-internal.h @@ -43,10 +43,8 @@ #include
/* Custom helpers for the UUID hash table */ -#define HASH_FIND_UUID(head, uuid, out) \ - HASH_FIND(hh_uuid, head, uuid, UUID_STR_LENGTH, out) -#define HASH_ADD_UUID(head, uuid_field, add) \ - HASH_ADD(hh_uuid, head, uuid_field[0], UUID_STR_LENGTH, add) +#define HASH_FIND_UUID(head, uuid, out) HASH_FIND(hh_uuid, head, uuid, UUID_STR_LENGTH, out) +#define HASH_ADD_UUID(head, uuid_field, add) HASH_ADD(hh_uuid, head, uuid_field[0], UUID_STR_LENGTH, add) #define NUM_TEXTURES 2 #define NUM_CHANNELS 3 @@ -75,16 +73,15 @@ struct rendered_callback { }; struct packet_callback { - void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param); + void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, struct encoder_packet_time *pkt_time, + void *param); void *param; }; /* ------------------------------------------------------------------------- */ /* validity checks */ -static inline bool obs_object_valid(const void *obj, const char *f, - const char *t) +static inline bool obs_object_valid(const void *obj, const char *f, const char *t) { if (!obj) { blog(LOG_DEBUG, "%s: Null '%s' parameter", f, t); @@ -115,8 +112,7 @@ struct obs_module { void (*unload)(void); void (*post_load)(void); void (*set_locale)(const char *locale); - bool (*get_string)(const char *lookup_string, - const char **translated_string); + bool (*get_string)(const char *lookup_string, const char **translated_string); void (*free_locale)(void); uint32_t (*ver)(void); void (*set_pointer)(obs_module_t *module); @@ -142,8 +138,7 @@ static inline void free_module_path(struct obs_module_path *omp) } } -static inline bool check_path(const char *data, const char *path, - struct dstr *output) +static inline bool check_path(const char *data, const char *path, struct dstr *output) { dstr_copy(output, path); dstr_cat(output, data); @@ -191,8 +186,7 @@ void *obs_hotkey_thread(void *param); struct obs_core_hotkeys; bool obs_hotkeys_platform_init(struct obs_core_hotkeys *hotkeys); void obs_hotkeys_platform_free(struct obs_core_hotkeys *hotkeys); -bool obs_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, - obs_key_t key); +bool obs_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, obs_key_t key); const char *obs_get_hotkey_translation(obs_key_t key, const char *def); @@ -243,8 +237,7 @@ struct obs_display { struct obs_display **prev_next; }; -extern bool obs_display_init(struct obs_display *display, - const struct gs_init_data *graphics_data); +extern bool obs_display_init(struct obs_display *display, const struct gs_init_data *graphics_data); extern void obs_display_free(struct obs_display *display); /* ------------------------------------------------------------------------- */ @@ -322,8 +315,7 @@ struct obs_core_video_mix { long encoder_refs; }; -extern struct obs_core_video_mix * -obs_create_video_mix(struct obs_video_info *ovi); +extern struct obs_core_video_mix *obs_create_video_mix(struct obs_video_info *ovi); extern void obs_free_video_mix(struct obs_core_video_mix *video); struct obs_core_video { @@ -523,27 +515,19 @@ extern void *obs_graphics_thread(void *param); extern bool obs_graphics_thread_loop(struct obs_graphics_context *context); #ifdef __APPLE__ extern void *obs_graphics_thread_autorelease(void *param); -extern bool -obs_graphics_thread_loop_autorelease(struct obs_graphics_context *context); +extern bool obs_graphics_thread_loop_autorelease(struct obs_graphics_context *context); #endif extern gs_effect_t *obs_load_effect(gs_effect_t **effect, const char *file); -extern bool audio_callback(void *param, uint64_t start_ts_in, - uint64_t end_ts_in, uint64_t *out_ts, - uint32_t mixers, struct audio_output_data *mixes); +extern bool audio_callback(void *param, uint64_t start_ts_in, uint64_t end_ts_in, uint64_t *out_ts, uint32_t mixers, + struct audio_output_data *mixes); extern struct obs_core_video_mix *get_mix_for_video(video_t *video); -extern void -start_raw_video(video_t *video, const struct video_scale_info *conversion, - uint32_t frame_rate_divisor, - void (*callback)(void *param, struct video_data *frame), - void *param); -extern void stop_raw_video(video_t *video, - void (*callback)(void *param, - struct video_data *frame), - void *param); +extern void start_raw_video(video_t *video, const struct video_scale_info *conversion, uint32_t frame_rate_divisor, + void (*callback)(void *param, struct video_data *frame), void *param); +extern void stop_raw_video(video_t *video, void (*callback)(void *param, struct video_data *frame), void *param); /* ------------------------------------------------------------------------- */ /* obs shared context data */ @@ -589,34 +573,23 @@ struct obs_context_data { bool private; }; -extern bool obs_context_data_init(struct obs_context_data *context, - enum obs_obj_type type, obs_data_t *settings, - const char *name, const char *uuid, - obs_data_t *hotkey_data, bool private); -extern void obs_context_init_control(struct obs_context_data *context, - void *object, obs_destroy_cb destroy); +extern bool obs_context_data_init(struct obs_context_data *context, enum obs_obj_type type, obs_data_t *settings, + const char *name, const char *uuid, obs_data_t *hotkey_data, bool private); +extern void obs_context_init_control(struct obs_context_data *context, void *object, obs_destroy_cb destroy); extern void obs_context_data_free(struct obs_context_data *context); -extern void obs_context_data_insert(struct obs_context_data *context, - pthread_mutex_t *mutex, void *first); -extern void obs_context_data_insert_name(struct obs_context_data *context, - pthread_mutex_t *mutex, void *first); -extern void obs_context_data_insert_uuid(struct obs_context_data *context, - pthread_mutex_t *mutex, - void *first_uuid); +extern void obs_context_data_insert(struct obs_context_data *context, pthread_mutex_t *mutex, void *first); +extern void obs_context_data_insert_name(struct obs_context_data *context, pthread_mutex_t *mutex, void *first); +extern void obs_context_data_insert_uuid(struct obs_context_data *context, pthread_mutex_t *mutex, void *first_uuid); extern void obs_context_data_remove(struct obs_context_data *context); -extern void obs_context_data_remove_name(struct obs_context_data *context, - void *phead); -extern void obs_context_data_remove_uuid(struct obs_context_data *context, - void *puuid_head); +extern void obs_context_data_remove_name(struct obs_context_data *context, void *phead); +extern void obs_context_data_remove_uuid(struct obs_context_data *context, void *puuid_head); extern void obs_context_wait(struct obs_context_data *context); -extern void obs_context_data_setname(struct obs_context_data *context, - const char *name); -extern void obs_context_data_setname_ht(struct obs_context_data *context, - const char *name, void *phead); +extern void obs_context_data_setname(struct obs_context_data *context, const char *name); +extern void obs_context_data_setname_ht(struct obs_context_data *context, const char *name, void *phead); /* ------------------------------------------------------------------------- */ /* ref-counting */ @@ -645,8 +618,7 @@ static inline bool obs_weak_ref_get_ref(struct obs_weak_ref *ref) { long owners = os_atomic_load_long(&ref->refs); while (owners > -1) { - if (os_atomic_compare_exchange_long(&ref->refs, &owners, - owners + 1)) { + if (os_atomic_compare_exchange_long(&ref->refs, &owners, owners + 1)) { return true; } } @@ -913,19 +885,14 @@ struct obs_source { }; extern struct obs_source_info *get_source_info(const char *id); -extern struct obs_source_info *get_source_info2(const char *unversioned_id, - uint32_t ver); -extern bool obs_source_init_context(struct obs_source *source, - obs_data_t *settings, const char *name, - const char *uuid, obs_data_t *hotkey_data, - bool private); +extern struct obs_source_info *get_source_info2(const char *unversioned_id, uint32_t ver); +extern bool obs_source_init_context(struct obs_source *source, obs_data_t *settings, const char *name, const char *uuid, + obs_data_t *hotkey_data, bool private); extern bool obs_transition_init(obs_source_t *transition); extern void obs_transition_free(obs_source_t *transition); extern void obs_transition_tick(obs_source_t *transition, float t); -extern void obs_transition_enum_sources(obs_source_t *transition, - obs_source_enum_proc_t enum_callback, - void *param); +extern void obs_transition_enum_sources(obs_source_t *transition, obs_source_enum_proc_t enum_callback, void *param); extern void obs_transition_save(obs_source_t *source, obs_data_t *data); extern void obs_transition_load(obs_source_t *source, obs_data_t *data); @@ -933,11 +900,9 @@ struct audio_monitor *audio_monitor_create(obs_source_t *source); void audio_monitor_reset(struct audio_monitor *monitor); extern void audio_monitor_destroy(struct audio_monitor *monitor); -extern obs_source_t * -obs_source_create_set_last_ver(const char *id, const char *name, - const char *uuid, obs_data_t *settings, - obs_data_t *hotkey_data, uint32_t last_obs_ver, - bool is_private); +extern obs_source_t *obs_source_create_set_last_ver(const char *id, const char *name, const char *uuid, + obs_data_t *settings, obs_data_t *hotkey_data, + uint32_t last_obs_ver, bool is_private); extern void obs_source_destroy(struct obs_source *source); extern void obs_source_addref(obs_source_t *source); @@ -946,9 +911,7 @@ enum view_type { AUX_VIEW, }; -static inline void obs_source_dosignal(struct obs_source *source, - const char *signal_obs, - const char *signal_source) +static inline void obs_source_dosignal(struct obs_source *source, const char *signal_obs, const char *signal_source) { struct calldata data; uint8_t stack[128]; @@ -958,8 +921,7 @@ static inline void obs_source_dosignal(struct obs_source *source, if (signal_obs && !source->context.private) signal_handler_signal(obs->signals, signal_obs, &data); if (signal_source) - signal_handler_signal(source->context.signals, signal_source, - &data); + signal_handler_signal(source->context.signals, signal_source, &data); } /* maximum timestamp variance in nanoseconds */ @@ -973,8 +935,7 @@ static inline bool frame_out_of_bounds(const obs_source_t *source, uint64_t ts) return ((ts - source->last_frame_ts) > MAX_TS_VAR); } -static inline enum gs_color_format -convert_video_format(enum video_format format, enum video_trc trc) +static inline enum gs_color_format convert_video_format(enum video_format format, enum video_trc trc) { switch (trc) { case VIDEO_TRC_PQ: @@ -1006,8 +967,7 @@ convert_video_format(enum video_format format, enum video_trc trc) } } -static inline enum gs_color_space convert_video_space(enum video_format format, - enum video_trc trc) +static inline enum gs_color_space convert_video_space(enum video_format format, enum video_trc trc) { enum gs_color_space space = GS_CS_SRGB; if (convert_video_format(format, trc) == GS_RGBA16F) { @@ -1025,38 +985,28 @@ static inline enum gs_color_space convert_video_space(enum video_format format, return space; } -extern void obs_source_set_texcoords_centered(obs_source_t *source, - bool centered); +extern void obs_source_set_texcoords_centered(obs_source_t *source, bool centered); extern void obs_source_activate(obs_source_t *source, enum view_type type); extern void obs_source_deactivate(obs_source_t *source, enum view_type type); extern void obs_source_video_tick(obs_source_t *source, float seconds); -extern float obs_source_get_target_volume(obs_source_t *source, - obs_source_t *target); +extern float obs_source_get_target_volume(obs_source_t *source, obs_source_t *target); extern uint64_t obs_source_get_last_async_ts(const obs_source_t *source); -extern void obs_source_audio_render(obs_source_t *source, uint32_t mixers, - size_t channels, size_t sample_rate, +extern void obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size); extern void add_alignment(struct vec2 *v, uint32_t align, int cx, int cy); -extern struct obs_source_frame *filter_async_video(obs_source_t *source, - struct obs_source_frame *in); -extern bool update_async_texture(struct obs_source *source, - const struct obs_source_frame *frame, - gs_texture_t *tex, gs_texrender_t *texrender); -extern bool update_async_textures(struct obs_source *source, - const struct obs_source_frame *frame, - gs_texture_t *tex[MAX_AV_PLANES], - gs_texrender_t *texrender); -extern bool set_async_texture_size(struct obs_source *source, - const struct obs_source_frame *frame); -extern void remove_async_frame(obs_source_t *source, - struct obs_source_frame *frame); +extern struct obs_source_frame *filter_async_video(obs_source_t *source, struct obs_source_frame *in); +extern bool update_async_texture(struct obs_source *source, const struct obs_source_frame *frame, gs_texture_t *tex, + gs_texrender_t *texrender); +extern bool update_async_textures(struct obs_source *source, const struct obs_source_frame *frame, + gs_texture_t *tex[MAX_AV_PLANES], gs_texrender_t *texrender); +extern bool set_async_texture_size(struct obs_source *source, const struct obs_source_frame *frame); +extern void remove_async_frame(obs_source_t *source, struct obs_source_frame *frame); extern void set_deinterlace_texture_size(obs_source_t *source); -extern void deinterlace_process_last_frame(obs_source_t *source, - uint64_t sys_time); +extern void deinterlace_process_last_frame(obs_source_t *source, uint64_t sys_time); extern void deinterlace_update_async_video(obs_source_t *source); extern void deinterlace_render(obs_source_t *s); @@ -1077,8 +1027,7 @@ struct delay_data { struct encoder_packet_time packet_time; }; -typedef void (*encoded_callback_t)(void *data, struct encoder_packet *packet, - struct encoder_packet_time *frame_time); +typedef void (*encoded_callback_t)(void *data, struct encoder_packet *packet, struct encoder_packet_time *frame_time); struct obs_weak_output { struct obs_weak_ref ref; @@ -1111,8 +1060,7 @@ struct pause_data { }; extern bool video_pause_check(struct pause_data *pause, uint64_t timestamp); -extern bool audio_pause_check(struct pause_data *pause, struct audio_data *data, - size_t sample_rate); +extern bool audio_pause_check(struct pause_data *pause, struct audio_data *data, size_t sample_rate); extern void pause_reset(struct pause_data *pause); enum keyframe_group_track_status { @@ -1125,8 +1073,7 @@ struct keyframe_group_data { uintptr_t group_id; int64_t pts; uint32_t required_tracks; - enum keyframe_group_track_status - seen_on_track[MAX_OUTPUT_VIDEO_ENCODERS]; + enum keyframe_group_track_status seen_on_track[MAX_OUTPUT_VIDEO_ENCODERS]; }; struct obs_output { @@ -1221,8 +1168,7 @@ struct obs_output { float audio_data[MAX_AUDIO_CHANNELS][AUDIO_OUTPUT_FRAMES]; }; -static inline void do_output_signal(struct obs_output *output, - const char *signal) +static inline void do_output_signal(struct obs_output *output, const char *signal) { struct calldata params = {0}; calldata_set_ptr(¶ms, "output", output); @@ -1230,23 +1176,18 @@ static inline void do_output_signal(struct obs_output *output, calldata_free(¶ms); } -extern void process_delay(void *data, struct encoder_packet *packet, - struct encoder_packet_time *packet_time); +extern void process_delay(void *data, struct encoder_packet *packet, struct encoder_packet_time *packet_time); extern void obs_output_cleanup_delay(obs_output_t *output); extern bool obs_output_delay_start(obs_output_t *output); extern void obs_output_delay_stop(obs_output_t *output); extern bool obs_output_actual_start(obs_output_t *output); -extern void obs_output_actual_stop(obs_output_t *output, bool force, - uint64_t ts); +extern void obs_output_actual_stop(obs_output_t *output, bool force, uint64_t ts); extern const struct obs_output_info *find_output(const char *id); -extern void obs_output_remove_encoder(struct obs_output *output, - struct obs_encoder *encoder); +extern void obs_output_remove_encoder(struct obs_output *output, struct obs_encoder *encoder); -extern void -obs_encoder_packet_create_instance(struct encoder_packet *dst, - const struct encoder_packet *src); +extern void obs_encoder_packet_create_instance(struct encoder_packet *dst, const struct encoder_packet *src); void obs_output_destroy(obs_output_t *output); /* ------------------------------------------------------------------------- */ @@ -1370,23 +1311,17 @@ extern struct obs_encoder_info *find_encoder(const char *id); extern bool obs_encoder_initialize(obs_encoder_t *encoder); extern void obs_encoder_shutdown(obs_encoder_t *encoder); -extern void obs_encoder_start(obs_encoder_t *encoder, - encoded_callback_t new_packet, void *param); -extern void obs_encoder_stop(obs_encoder_t *encoder, - encoded_callback_t new_packet, void *param); +extern void obs_encoder_start(obs_encoder_t *encoder, encoded_callback_t new_packet, void *param); +extern void obs_encoder_stop(obs_encoder_t *encoder, encoded_callback_t new_packet, void *param); -extern void obs_encoder_add_output(struct obs_encoder *encoder, - struct obs_output *output); -extern void obs_encoder_remove_output(struct obs_encoder *encoder, - struct obs_output *output); +extern void obs_encoder_add_output(struct obs_encoder *encoder, struct obs_output *output); +extern void obs_encoder_remove_output(struct obs_encoder *encoder, struct obs_output *output); extern bool start_gpu_encode(obs_encoder_t *encoder); extern void stop_gpu_encode(obs_encoder_t *encoder); -extern bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, - const uint64_t *frame_cts); -extern void send_off_encoder_packet(obs_encoder_t *encoder, bool success, - bool received, struct encoder_packet *pkt); +extern bool do_encode(struct obs_encoder *encoder, struct encoder_frame *frame, const uint64_t *frame_cts); +extern void send_off_encoder_packet(obs_encoder_t *encoder, bool success, bool received, struct encoder_packet *pkt); void obs_encoder_destroy(obs_encoder_t *encoder); @@ -1414,13 +1349,11 @@ extern const struct obs_service_info *find_service(const char *id); extern void obs_service_activate(struct obs_service *service); extern void obs_service_deactivate(struct obs_service *service, bool remove); -extern bool obs_service_initialize(struct obs_service *service, - struct obs_output *output); +extern bool obs_service_initialize(struct obs_service *service, struct obs_output *output); void obs_service_destroy(obs_service_t *service); -void obs_output_remove_encoder_internal(struct obs_output *output, - struct obs_encoder *encoder); +void obs_output_remove_encoder_internal(struct obs_output *output, struct obs_encoder *encoder); /** Internal Source Profiler functions **/ @@ -1442,15 +1375,12 @@ extern void source_profiler_async_frame_received(obs_source_t *source); /* Get timestamp for start of tick */ extern uint64_t source_profiler_source_tick_start(void); /* Submit start timestamp for source */ -extern void source_profiler_source_tick_end(obs_source_t *source, - uint64_t start); +extern void source_profiler_source_tick_end(obs_source_t *source, uint64_t start); /* Obtain GPU timer and start timestamp for render start of a source. */ extern uint64_t source_profiler_source_render_begin(gs_timer_t **timer); /* Submit start timestamp and GPU timer after rendering source */ -extern void source_profiler_source_render_end(obs_source_t *source, - uint64_t start, - gs_timer_t *timer); +extern void source_profiler_source_render_end(obs_source_t *source, uint64_t start, gs_timer_t *timer); /* Remove source from profiler hashmaps */ extern void source_profiler_remove_source(obs_source_t *source); diff --git a/libobs/obs-missing-files.c b/libobs/obs-missing-files.c index 494ef301d..8fa303ea7 100644 --- a/libobs/obs-missing-files.c +++ b/libobs/obs-missing-files.c @@ -36,8 +36,7 @@ struct obs_missing_files { obs_missing_files_t *obs_missing_files_create() { - struct obs_missing_files *files = - bzalloc(sizeof(struct obs_missing_files)); + struct obs_missing_files *files = bzalloc(sizeof(struct obs_missing_files)); return files; } @@ -52,8 +51,7 @@ void obs_missing_files_destroy(obs_missing_files_t *files) bfree(files); } -void obs_missing_files_add_file(obs_missing_files_t *files, - obs_missing_file_t *file) +void obs_missing_files_add_file(obs_missing_files_t *files, obs_missing_file_t *file) { da_insert(files->files, files->files.num, &file); } @@ -63,14 +61,12 @@ size_t obs_missing_files_count(obs_missing_files_t *files) return files->files.num; } -obs_missing_file_t *obs_missing_files_get_file(obs_missing_files_t *files, - int idx) +obs_missing_file_t *obs_missing_files_get_file(obs_missing_files_t *files, int idx) { return files->files.array[idx]; } -void obs_missing_files_append(obs_missing_files_t *dst, - obs_missing_files_t *src) +void obs_missing_files_append(obs_missing_files_t *dst, obs_missing_files_t *src) { for (size_t i = 0; i < src->files.num; i++) { obs_missing_file_t *file = src->files.array[i]; @@ -79,12 +75,10 @@ void obs_missing_files_append(obs_missing_files_t *dst, } } -obs_missing_file_t *obs_missing_file_create(const char *path, - obs_missing_file_cb callback, - int src_type, void *src, void *data) +obs_missing_file_t *obs_missing_file_create(const char *path, obs_missing_file_cb callback, int src_type, void *src, + void *data) { - struct obs_missing_file *file = - bzalloc(sizeof(struct obs_missing_file)); + struct obs_missing_file *file = bzalloc(sizeof(struct obs_missing_file)); file->file_path = bstrdup(path); file->callback = callback; @@ -126,14 +120,11 @@ void obs_missing_file_destroy(obs_missing_file_t *file) bfree(file); } -void obs_missing_file_issue_callback(obs_missing_file_t *file, - const char *new_path) +void obs_missing_file_issue_callback(obs_missing_file_t *file, const char *new_path) { switch (file->src_type) { case OBS_MISSING_FILE_SOURCE: - obs_source_replace_missing_file(file->callback, - (obs_source_t *)file->src, - new_path, file->data); + obs_source_replace_missing_file(file->callback, (obs_source_t *)file->src, new_path, file->data); break; case OBS_MISSING_FILE_SCRIPT: break; diff --git a/libobs/obs-missing-files.h b/libobs/obs-missing-files.h index 6e626ff35..a082525e3 100644 --- a/libobs/obs-missing-files.h +++ b/libobs/obs-missing-files.h @@ -23,8 +23,7 @@ extern "C" { #endif -typedef void (*obs_missing_file_cb)(void *src, const char *new_path, - void *data); +typedef void (*obs_missing_file_cb)(void *src, const char *new_path, void *data); struct obs_missing_file; struct obs_missing_files; @@ -34,22 +33,16 @@ typedef struct obs_missing_files obs_missing_files_t; enum obs_missing_file_src { OBS_MISSING_FILE_SOURCE, OBS_MISSING_FILE_SCRIPT }; EXPORT obs_missing_files_t *obs_missing_files_create(); -EXPORT obs_missing_file_t *obs_missing_file_create(const char *path, - obs_missing_file_cb callback, - int src_type, void *src, - void *data); +EXPORT obs_missing_file_t *obs_missing_file_create(const char *path, obs_missing_file_cb callback, int src_type, + void *src, void *data); -EXPORT void obs_missing_files_add_file(obs_missing_files_t *files, - obs_missing_file_t *file); +EXPORT void obs_missing_files_add_file(obs_missing_files_t *files, obs_missing_file_t *file); EXPORT size_t obs_missing_files_count(obs_missing_files_t *files); -EXPORT obs_missing_file_t * -obs_missing_files_get_file(obs_missing_files_t *files, int idx); +EXPORT obs_missing_file_t *obs_missing_files_get_file(obs_missing_files_t *files, int idx); EXPORT void obs_missing_files_destroy(obs_missing_files_t *files); -EXPORT void obs_missing_files_append(obs_missing_files_t *dst, - obs_missing_files_t *src); +EXPORT void obs_missing_files_append(obs_missing_files_t *dst, obs_missing_files_t *src); -EXPORT void obs_missing_file_issue_callback(obs_missing_file_t *file, - const char *new_path); +EXPORT void obs_missing_file_issue_callback(obs_missing_file_t *file, const char *new_path); EXPORT const char *obs_missing_file_get_path(obs_missing_file_t *file); EXPORT const char *obs_missing_file_get_source_name(obs_missing_file_t *file); EXPORT void obs_missing_file_release(obs_missing_file_t *file); diff --git a/libobs/obs-module.c b/libobs/obs-module.c index 02c12bf00..5fe3b8a8f 100644 --- a/libobs/obs-module.c +++ b/libobs/obs-module.c @@ -59,9 +59,7 @@ static int load_module_exports(struct obs_module *mod, const char *path) return MODULE_SUCCESS; } -bool obs_module_get_locale_string(const obs_module_t *mod, - const char *lookup_string, - const char **translated_string) +bool obs_module_get_locale_string(const obs_module_t *mod, const char *lookup_string, const char **translated_string) { if (mod->get_string) { return mod->get_string(lookup_string, translated_string); @@ -70,8 +68,7 @@ bool obs_module_get_locale_string(const obs_module_t *mod, return false; } -const char *obs_module_get_locale_text(const obs_module_t *mod, - const char *text) +const char *obs_module_get_locale_text(const obs_module_t *mod, const char *text) { const char *str = text; obs_module_get_locale_string(mod, text, &str); @@ -97,8 +94,7 @@ static inline char *get_module_name(const char *file) extern void reset_win32_symbol_paths(void); #endif -int obs_open_module(obs_module_t **module, const char *path, - const char *data_path) +int obs_open_module(obs_module_t **module, const char *path, const char *data_path) { struct obs_module mod = {0}; int errorcode; @@ -110,8 +106,7 @@ int obs_open_module(obs_module_t **module, const char *path, /* HACK: Do not load obsolete obs-browser build on macOS; the * obs-browser plugin used to live in the Application Support * directory. */ - if (astrstri(path, "Library/Application Support/obs-studio") != NULL && - astrstri(path, "obs-browser") != NULL) { + if (astrstri(path, "Library/Application Support/obs-studio") != NULL && astrstri(path, "obs-browser") != NULL) { blog(LOG_WARNING, "Ignoring old obs-browser.so version"); return MODULE_HARDCODED_SKIP; } @@ -158,14 +153,12 @@ bool obs_init_module(obs_module_t *module) return true; const char *profile_name = - profile_store_name(obs_get_profiler_name_store(), - "obs_init_module(%s)", module->file); + profile_store_name(obs_get_profiler_name_store(), "obs_init_module(%s)", module->file); profile_start(profile_name); module->loaded = module->load(); if (!module->loaded) - blog(LOG_WARNING, "Failed to initialize module '%s'", - module->file); + blog(LOG_WARNING, "Failed to initialize module '%s'", module->file); profile_end(profile_name); return module->loaded; @@ -283,8 +276,7 @@ void obs_add_safe_module(const char *name) da_push_back(obs->safe_modules, &item); } -extern void get_plugin_info(const char *path, bool *is_obs_plugin, - bool *can_load); +extern void get_plugin_info(const char *path, bool *is_obs_plugin, bool *can_load); struct fail_info { struct dstr fail_modules; @@ -315,14 +307,12 @@ static void load_all_callback(void *param, const struct obs_module_info2 *info) get_plugin_info(info->bin_path, &is_obs_plugin, &can_load_obs_plugin); if (!is_obs_plugin) { - blog(LOG_WARNING, "Skipping module '%s', not an OBS plugin", - info->bin_path); + blog(LOG_WARNING, "Skipping module '%s', not an OBS plugin", info->bin_path); return; } if (!is_safe_module(info->name)) { - blog(LOG_WARNING, "Skipping module '%s', not on safe list", - info->name); + blog(LOG_WARNING, "Skipping module '%s', not on safe list", info->name); return; } @@ -337,23 +327,16 @@ static void load_all_callback(void *param, const struct obs_module_info2 *info) int code = obs_open_module(&module, info->bin_path, info->data_path); switch (code) { case MODULE_MISSING_EXPORTS: - blog(LOG_DEBUG, - "Failed to load module file '%s', not an OBS plugin", - info->bin_path); + blog(LOG_DEBUG, "Failed to load module file '%s', not an OBS plugin", info->bin_path); return; case MODULE_FILE_NOT_FOUND: - blog(LOG_DEBUG, - "Failed to load module file '%s', file not found", - info->bin_path); + blog(LOG_DEBUG, "Failed to load module file '%s', file not found", info->bin_path); return; case MODULE_ERROR: - blog(LOG_DEBUG, "Failed to load module file '%s'", - info->bin_path); + blog(LOG_DEBUG, "Failed to load module file '%s'", info->bin_path); goto load_failure; case MODULE_INCOMPATIBLE_VER: - blog(LOG_DEBUG, - "Failed to load module file '%s', incompatible version", - info->bin_path); + blog(LOG_DEBUG, "Failed to load module file '%s', incompatible version", info->bin_path); goto load_failure; case MODULE_HARDCODED_SKIP: return; @@ -407,8 +390,7 @@ void obs_load_all_modules2(struct obs_module_failure_info *mfi) profile_end(obs_load_all_modules2_name); mfi->count = fail_info.fail_count; - mfi->failed_modules = - strlist_split(fail_info.fail_modules.array, ';', false); + mfi->failed_modules = strlist_split(fail_info.fail_modules.array, ';', false); dstr_free(&fail_info.fail_modules); } @@ -427,8 +409,7 @@ void obs_post_load_modules(void) mod->post_load(); } -static inline void make_data_dir(struct dstr *parsed_data_dir, - const char *data_dir, const char *name) +static inline void make_data_dir(struct dstr *parsed_data_dir, const char *data_dir, const char *name) { dstr_copy(parsed_data_dir, data_dir); dstr_replace(parsed_data_dir, "%module%", name); @@ -451,8 +432,7 @@ static char *make_data_directory(const char *module_name, const char *data_dir) return parsed_data_dir.array; } -static bool parse_binary_from_directory(struct dstr *parsed_bin_path, - const char *bin_path, const char *file) +static bool parse_binary_from_directory(struct dstr *parsed_bin_path, const char *bin_path, const char *file) { struct dstr directory = {0}; bool found = true; @@ -492,10 +472,8 @@ static bool parse_binary_from_directory(struct dstr *parsed_bin_path, return found; } -static void process_found_module(struct obs_module_path *omp, const char *path, - bool directory, - obs_find_module_callback2_t callback, - void *param) +static void process_found_module(struct obs_module_path *omp, const char *path, bool directory, + obs_find_module_callback2_t callback, void *param) { struct obs_module_info2 info; struct dstr name = {0}; @@ -518,8 +496,7 @@ static void process_found_module(struct obs_module_path *omp, const char *path, if (!directory) { dstr_copy(&parsed_bin_path, path); } else { - bin_found = parse_binary_from_directory(&parsed_bin_path, - omp->bin, name.array); + bin_found = parse_binary_from_directory(&parsed_bin_path, omp->bin, name.array); } parsed_data_dir = make_data_directory(name.array, omp->data); @@ -536,9 +513,7 @@ static void process_found_module(struct obs_module_path *omp, const char *path, dstr_free(&parsed_bin_path); } -static void find_modules_in_path(struct obs_module_path *omp, - obs_find_module_callback2_t callback, - void *param) +static void find_modules_in_path(struct obs_module_path *omp, obs_find_module_callback2_t callback, void *param) { struct dstr search_path = {0}; char *module_start; @@ -563,9 +538,7 @@ static void find_modules_in_path(struct obs_module_path *omp, if (os_glob(search_path.array, 0, &gi) == 0) { for (size_t i = 0; i < gi->gl_pathc; i++) { if (search_directories == gi->gl_pathv[i].directory) - process_found_module(omp, gi->gl_pathv[i].path, - search_directories, - callback, param); + process_found_module(omp, gi->gl_pathv[i].path, search_directories, callback, param); } os_globfree(gi); @@ -637,8 +610,7 @@ void free_module(struct obs_module *mod) bfree(mod); } -lookup_t *obs_module_load_locale(obs_module_t *module, - const char *default_locale, const char *locale) +lookup_t *obs_module_load_locale(obs_module_t *module, const char *default_locale, const char *locale) { struct dstr str = {0}; lookup_t *lookup = NULL; @@ -659,8 +631,7 @@ lookup_t *obs_module_load_locale(obs_module_t *module, bfree(file); if (!lookup) { - blog(LOG_WARNING, "Failed to load '%s' text for module: '%s'", - default_locale, module->file); + blog(LOG_WARNING, "Failed to load '%s' text for module: '%s'", default_locale, module->file); goto cleanup; } @@ -674,8 +645,7 @@ lookup_t *obs_module_load_locale(obs_module_t *module, file = obs_find_module_file(module, str.array); if (!text_lookup_add(lookup, file)) - blog(LOG_WARNING, "Failed to load '%s' text for module: '%s'", - locale, module->file); + blog(LOG_WARNING, "Failed to load '%s' text for module: '%s'", locale, module->file); bfree(file); cleanup: @@ -683,32 +653,28 @@ cleanup: return lookup; } -#define REGISTER_OBS_DEF(size_var, structure, dest, info) \ - do { \ - struct structure data = {0}; \ - if (!size_var) { \ - blog(LOG_ERROR, "Tried to register " #structure \ - " outside of obs_module_load"); \ - return; \ - } \ - \ - if (size_var > sizeof(data)) { \ - blog(LOG_ERROR, \ - "Tried to register " #structure \ - " with size %llu which is more " \ - "than libobs currently supports " \ - "(%llu)", \ - (long long unsigned)size_var, \ - (long long unsigned)sizeof(data)); \ - goto error; \ - } \ - \ - memcpy(&data, info, size_var); \ - da_push_back(dest, &data); \ +#define REGISTER_OBS_DEF(size_var, structure, dest, info) \ + do { \ + struct structure data = {0}; \ + if (!size_var) { \ + blog(LOG_ERROR, "Tried to register " #structure " outside of obs_module_load"); \ + return; \ + } \ + \ + if (size_var > sizeof(data)) { \ + blog(LOG_ERROR, \ + "Tried to register " #structure " with size %llu which is more " \ + "than libobs currently supports " \ + "(%llu)", \ + (long long unsigned)size_var, (long long unsigned)sizeof(data)); \ + goto error; \ + } \ + \ + memcpy(&data, info, size_var); \ + da_push_back(dest, &data); \ } while (false) -#define HAS_VAL(type, info, val) \ - ((offsetof(type, val) + sizeof(info->val) <= size) && info->val) +#define HAS_VAL(type, info, val) ((offsetof(type, val) + sizeof(info->val) <= size) && info->val) #define CHECK_REQUIRED_VAL(type, info, val, func) \ do { \ @@ -721,39 +687,33 @@ cleanup: } \ } while (false) -#define CHECK_REQUIRED_VAL_EITHER(type, info, val1, val2, func) \ - do { \ - if (!HAS_VAL(type, info, val1) && \ - !HAS_VAL(type, info, val2)) { \ - blog(LOG_ERROR, \ - "Neither '" #val1 "' nor '" #val2 "' " \ - "for '%s' found. " #func " failed.", \ - info->id); \ - goto error; \ - } \ +#define CHECK_REQUIRED_VAL_EITHER(type, info, val1, val2, func) \ + do { \ + if (!HAS_VAL(type, info, val1) && !HAS_VAL(type, info, val2)) { \ + blog(LOG_ERROR, \ + "Neither '" #val1 "' nor '" #val2 "' " \ + "for '%s' found. " #func " failed.", \ + info->id); \ + goto error; \ + } \ } while (false) -#define HANDLE_ERROR(size_var, structure, info) \ - do { \ - struct structure data = {0}; \ - if (!size_var) \ - return; \ - \ - memcpy(&data, info, \ - sizeof(data) < size_var ? sizeof(data) : size_var); \ - \ - if (data.type_data && data.free_type_data) \ - data.free_type_data(data.type_data); \ +#define HANDLE_ERROR(size_var, structure, info) \ + do { \ + struct structure data = {0}; \ + if (!size_var) \ + return; \ + \ + memcpy(&data, info, sizeof(data) < size_var ? sizeof(data) : size_var); \ + \ + if (data.type_data && data.free_type_data) \ + data.free_type_data(data.type_data); \ } while (false) -#define source_warn(format, ...) \ - blog(LOG_WARNING, "obs_register_source: " format, ##__VA_ARGS__) -#define output_warn(format, ...) \ - blog(LOG_WARNING, "obs_register_output: " format, ##__VA_ARGS__) -#define encoder_warn(format, ...) \ - blog(LOG_WARNING, "obs_register_encoder: " format, ##__VA_ARGS__) -#define service_warn(format, ...) \ - blog(LOG_WARNING, "obs_register_service: " format, ##__VA_ARGS__) +#define source_warn(format, ...) blog(LOG_WARNING, "obs_register_source: " format, ##__VA_ARGS__) +#define output_warn(format, ...) blog(LOG_WARNING, "obs_register_output: " format, ##__VA_ARGS__) +#define encoder_warn(format, ...) blog(LOG_WARNING, "obs_register_encoder: " format, ##__VA_ARGS__) +#define service_warn(format, ...) blog(LOG_WARNING, "obs_register_service: " format, ##__VA_ARGS__) void obs_register_source_s(const struct obs_source_info *info, size_t size) { @@ -767,8 +727,7 @@ void obs_register_source_s(const struct obs_source_info *info, size_t size) } else if (info->type == OBS_SOURCE_TYPE_TRANSITION) { array = &obs->transition_types; } else if (info->type != OBS_SOURCE_TYPE_SCENE) { - source_warn("Tried to register unknown source type: %u", - info->type); + source_warn("Tried to register unknown source type: %u", info->type); goto error; } @@ -783,8 +742,7 @@ void obs_register_source_s(const struct obs_source_info *info, size_t size) source_warn("Tried to register obs_source_info with size " "%llu which is more than libobs currently " "supports (%llu)", - (long long unsigned)size, - (long long unsigned)sizeof(data)); + (long long unsigned)size, (long long unsigned)sizeof(data)); goto error; } @@ -805,8 +763,7 @@ void obs_register_source_s(const struct obs_source_info *info, size_t size) source_warn("get_height ignored registering " "transition '%s'", data.id); - data.output_flags |= OBS_SOURCE_COMPOSITE | OBS_SOURCE_VIDEO | - OBS_SOURCE_CUSTOM_DRAW; + data.output_flags |= OBS_SOURCE_COMPOSITE | OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW; } if ((data.output_flags & OBS_SOURCE_COMPOSITE) != 0) { @@ -824,14 +781,11 @@ void obs_register_source_s(const struct obs_source_info *info, size_t size) } } -#define CHECK_REQUIRED_VAL_(info, val, func) \ - CHECK_REQUIRED_VAL(struct obs_source_info, info, val, func) +#define CHECK_REQUIRED_VAL_(info, val, func) CHECK_REQUIRED_VAL(struct obs_source_info, info, val, func) CHECK_REQUIRED_VAL_(info, get_name, obs_register_source); - if (info->type != OBS_SOURCE_TYPE_FILTER && - info->type != OBS_SOURCE_TYPE_TRANSITION && - (info->output_flags & OBS_SOURCE_VIDEO) != 0 && - (info->output_flags & OBS_SOURCE_ASYNC) == 0) { + if (info->type != OBS_SOURCE_TYPE_FILTER && info->type != OBS_SOURCE_TYPE_TRANSITION && + (info->output_flags & OBS_SOURCE_VIDEO) != 0 && (info->output_flags & OBS_SOURCE_ASYNC) == 0) { CHECK_REQUIRED_VAL_(info, get_width, obs_register_source); CHECK_REQUIRED_VAL_(info, get_height, obs_register_source); } @@ -845,8 +799,7 @@ void obs_register_source_s(const struct obs_source_info *info, size_t size) data.unversioned_id = data.id; if (data.version) { struct dstr versioned_id = {0}; - dstr_printf(&versioned_id, "%s_v%d", data.id, - (int)data.version); + dstr_printf(&versioned_id, "%s_v%d", data.id, (int)data.version); data.id = versioned_id.array; } else { data.id = bstrdup(data.id); @@ -870,8 +823,7 @@ void obs_register_output_s(const struct obs_output_info *info, size_t size) goto error; } -#define CHECK_REQUIRED_VAL_(info, val, func) \ - CHECK_REQUIRED_VAL(struct obs_output_info, info, val, func) +#define CHECK_REQUIRED_VAL_(info, val, func) CHECK_REQUIRED_VAL(struct obs_output_info, info, val, func) CHECK_REQUIRED_VAL_(info, get_name, obs_register_output); CHECK_REQUIRED_VAL_(info, create, obs_register_output); CHECK_REQUIRED_VAL_(info, destroy, obs_register_output); @@ -885,16 +837,13 @@ void obs_register_output_s(const struct obs_output_info *info, size_t size) CHECK_REQUIRED_VAL_(info, encoded_packet, obs_register_output); } else { if (info->flags & OBS_OUTPUT_VIDEO) - CHECK_REQUIRED_VAL_(info, raw_video, - obs_register_output); + CHECK_REQUIRED_VAL_(info, raw_video, obs_register_output); if (info->flags & OBS_OUTPUT_AUDIO) { if (info->flags & OBS_OUTPUT_MULTI_TRACK) { - CHECK_REQUIRED_VAL_(info, raw_audio2, - obs_register_output); + CHECK_REQUIRED_VAL_(info, raw_audio2, obs_register_output); } else { - CHECK_REQUIRED_VAL_(info, raw_audio, - obs_register_output); + CHECK_REQUIRED_VAL_(info, raw_audio, obs_register_output); } } } @@ -907,8 +856,7 @@ void obs_register_output_s(const struct obs_output_info *info, size_t size) for (char **protocol = protocols; *protocol; ++protocol) { bool skip = false; for (size_t i = 0; i < obs->data.protocols.num; i++) { - if (strcmp(*protocol, - obs->data.protocols.array[i]) == 0) + if (strcmp(*protocol, obs->data.protocols.array[i]) == 0) skip = true; } @@ -934,23 +882,18 @@ void obs_register_encoder_s(const struct obs_encoder_info *info, size_t size) goto error; } - if (((info->caps & OBS_ENCODER_CAP_PASS_TEXTURE) != 0 && - info->caps & OBS_ENCODER_CAP_SCALING) != 0) { - encoder_warn( - "Texture encoders cannot self-scale. Encoder id '%s' not registered.", - info->id); + if (((info->caps & OBS_ENCODER_CAP_PASS_TEXTURE) != 0 && info->caps & OBS_ENCODER_CAP_SCALING) != 0) { + encoder_warn("Texture encoders cannot self-scale. Encoder id '%s' not registered.", info->id); goto error; } -#define CHECK_REQUIRED_VAL_(info, val, func) \ - CHECK_REQUIRED_VAL(struct obs_encoder_info, info, val, func) +#define CHECK_REQUIRED_VAL_(info, val, func) CHECK_REQUIRED_VAL(struct obs_encoder_info, info, val, func) CHECK_REQUIRED_VAL_(info, get_name, obs_register_encoder); CHECK_REQUIRED_VAL_(info, create, obs_register_encoder); CHECK_REQUIRED_VAL_(info, destroy, obs_register_encoder); if ((info->caps & OBS_ENCODER_CAP_PASS_TEXTURE) != 0) - CHECK_REQUIRED_VAL_EITHER(struct obs_encoder_info, info, - encode_texture, encode_texture2, + CHECK_REQUIRED_VAL_EITHER(struct obs_encoder_info, info, encode_texture, encode_texture2, obs_register_encoder); else CHECK_REQUIRED_VAL_(info, encode, obs_register_encoder); @@ -975,8 +918,7 @@ void obs_register_service_s(const struct obs_service_info *info, size_t size) goto error; } -#define CHECK_REQUIRED_VAL_(info, val, func) \ - CHECK_REQUIRED_VAL(struct obs_service_info, info, val, func) +#define CHECK_REQUIRED_VAL_(info, val, func) CHECK_REQUIRED_VAL(struct obs_service_info, info, val, func) CHECK_REQUIRED_VAL_(info, get_name, obs_register_service); CHECK_REQUIRED_VAL_(info, create, obs_register_service); CHECK_REQUIRED_VAL_(info, destroy, obs_register_service); diff --git a/libobs/obs-module.h b/libobs/obs-module.h index 87941320e..da81fa243 100644 --- a/libobs/obs-module.h +++ b/libobs/obs-module.h @@ -113,29 +113,28 @@ MODULE_EXPORT void obs_module_set_locale(const char *locale); MODULE_EXPORT void obs_module_free_locale(void); /** Optional: Use this macro in a module to use default locale handling. */ -#define OBS_MODULE_USE_DEFAULT_LOCALE(module_name, default_locale) \ - lookup_t *obs_module_lookup = NULL; \ - const char *obs_module_text(const char *val) \ - { \ - const char *out = val; \ - text_lookup_getstr(obs_module_lookup, val, &out); \ - return out; \ - } \ - bool obs_module_get_string(const char *val, const char **out) \ - { \ - return text_lookup_getstr(obs_module_lookup, val, out); \ - } \ - void obs_module_set_locale(const char *locale) \ - { \ - if (obs_module_lookup) \ - text_lookup_destroy(obs_module_lookup); \ - obs_module_lookup = obs_module_load_locale( \ - obs_current_module(), default_locale, locale); \ - } \ - void obs_module_free_locale(void) \ - { \ - text_lookup_destroy(obs_module_lookup); \ - obs_module_lookup = NULL; \ +#define OBS_MODULE_USE_DEFAULT_LOCALE(module_name, default_locale) \ + lookup_t *obs_module_lookup = NULL; \ + const char *obs_module_text(const char *val) \ + { \ + const char *out = val; \ + text_lookup_getstr(obs_module_lookup, val, &out); \ + return out; \ + } \ + bool obs_module_get_string(const char *val, const char **out) \ + { \ + return text_lookup_getstr(obs_module_lookup, val, out); \ + } \ + void obs_module_set_locale(const char *locale) \ + { \ + if (obs_module_lookup) \ + text_lookup_destroy(obs_module_lookup); \ + obs_module_lookup = obs_module_load_locale(obs_current_module(), default_locale, locale); \ + } \ + void obs_module_free_locale(void) \ + { \ + text_lookup_destroy(obs_module_lookup); \ + obs_module_lookup = NULL; \ } /** Helper function for looking up locale if default locale handler was used */ @@ -143,8 +142,7 @@ MODULE_EXTERN const char *obs_module_text(const char *lookup_string); /** Helper function for looking up locale if default locale handler was used, * returns true if text found, otherwise false */ -MODULE_EXPORT bool obs_module_get_string(const char *lookup_string, - const char **translated_string); +MODULE_EXPORT bool obs_module_get_string(const char *lookup_string, const char **translated_string); /** Helper function that returns the current module */ MODULE_EXTERN obs_module_t *obs_current_module(void); @@ -162,8 +160,7 @@ MODULE_EXTERN obs_module_t *obs_current_module(void); * directory is not set. Equivalent to: * obs_module_get_config_path(obs_current_module(), file); */ -#define obs_module_config_path(file) \ - obs_module_get_config_path(obs_current_module(), file) +#define obs_module_config_path(file) obs_module_get_config_path(obs_current_module(), file) /** * Optional: Declares the author(s) of the module diff --git a/libobs/obs-nal.c b/libobs/obs-nal.c index 97dcacae4..0b5debb6b 100644 --- a/libobs/obs-nal.c +++ b/libobs/obs-nal.c @@ -20,8 +20,7 @@ /* NOTE: I noticed that FFmpeg does some unusual special handling of certain * scenarios that I was unaware of, so instead of just searching for {0, 0, 1} * we'll just use the code from FFmpeg - http://www.ffmpeg.org/ */ -static const uint8_t *ff_avc_find_startcode_internal(const uint8_t *p, - const uint8_t *end) +static const uint8_t *ff_avc_find_startcode_internal(const uint8_t *p, const uint8_t *end) { const uint8_t *a = p + 4 - ((intptr_t)p & 3); diff --git a/libobs/obs-nal.h b/libobs/obs-nal.h index 8ef4134b9..adb976826 100644 --- a/libobs/obs-nal.h +++ b/libobs/obs-nal.h @@ -30,8 +30,7 @@ enum { OBS_NAL_PRIORITY_HIGHEST = 3, }; -EXPORT const uint8_t *obs_nal_find_startcode(const uint8_t *p, - const uint8_t *end); +EXPORT const uint8_t *obs_nal_find_startcode(const uint8_t *p, const uint8_t *end); #ifdef __cplusplus } diff --git a/libobs/obs-nix-wayland.c b/libobs/obs-nix-wayland.c index b649f131e..3155db91a 100644 --- a/libobs/obs-nix-wayland.c +++ b/libobs/obs-nix-wayland.c @@ -45,8 +45,7 @@ struct obs_hotkeys_platform { static obs_key_t obs_nix_wayland_key_from_virtual_key(int sym); -static void load_keymap_data(struct xkb_keymap *keymap, xkb_keycode_t key, - void *data) +static void load_keymap_data(struct xkb_keymap *keymap, xkb_keycode_t key, void *data) { obs_hotkeys_platform_t *plat = (obs_hotkeys_platform_t *)data; if (key >= MAX_KEYCODES) @@ -54,13 +53,11 @@ static void load_keymap_data(struct xkb_keymap *keymap, xkb_keycode_t key, const xkb_keysym_t *syms; for (int level = 0; level < MAX_SHIFT_LEVELS; level++) { - int nsyms = xkb_keymap_key_get_syms_by_level( - keymap, key, plat->current_layout, level, &syms); + int nsyms = xkb_keymap_key_get_syms_by_level(keymap, key, plat->current_layout, level, &syms); if (nsyms < 1) continue; - obs_key_t obs_key = - obs_nix_wayland_key_from_virtual_key(syms[0]); + obs_key_t obs_key = obs_nix_wayland_key_from_virtual_key(syms[0]); // This avoids ambiguity where multiple scancodes produce the same symbols. // e.g. LSGT and Shift+AB08 produce `<` on default US layout. if (!plat->obs_to_key[obs_key]) @@ -71,14 +68,13 @@ static void load_keymap_data(struct xkb_keymap *keymap, xkb_keycode_t key, static void rebuild_keymap_data(obs_hotkeys_platform_t *plat) { - memset(plat->key_to_sym, 0, - sizeof(xkb_keysym_t) * MAX_SHIFT_LEVELS * MAX_KEYCODES); + memset(plat->key_to_sym, 0, sizeof(xkb_keysym_t) * MAX_SHIFT_LEVELS * MAX_KEYCODES); memset(plat->obs_to_key, 0, sizeof(xkb_keysym_t) * OBS_KEY_LAST_VALUE); xkb_keymap_key_for_each(plat->xkb_keymap, load_keymap_data, plat); } -static void platform_keyboard_keymap(void *data, struct wl_keyboard *keyboard, - uint32_t format, int32_t fd, uint32_t size) +static void platform_keyboard_keymap(void *data, struct wl_keyboard *keyboard, uint32_t format, int32_t fd, + uint32_t size) { UNUSED_PARAMETER(keyboard); UNUSED_PARAMETER(format); @@ -91,8 +87,7 @@ static void platform_keyboard_keymap(void *data, struct wl_keyboard *keyboard, } struct xkb_keymap *xkb_keymap = xkb_keymap_new_from_string( - plat->xkb_context, keymap_shm, XKB_KEYMAP_FORMAT_TEXT_V1, - XKB_KEYMAP_COMPILE_NO_FLAGS); + plat->xkb_context, keymap_shm, XKB_KEYMAP_FORMAT_TEXT_V1, XKB_KEYMAP_COMPILE_NO_FLAGS); munmap(keymap_shm, size); close(fd); @@ -105,18 +100,14 @@ static void platform_keyboard_keymap(void *data, struct wl_keyboard *keyboard, rebuild_keymap_data(plat); } -static void platform_keyboard_modifiers(void *data, - struct wl_keyboard *keyboard, - uint32_t serial, - uint32_t mods_depressed, - uint32_t mods_latched, - uint32_t mods_locked, uint32_t group) +static void platform_keyboard_modifiers(void *data, struct wl_keyboard *keyboard, uint32_t serial, + uint32_t mods_depressed, uint32_t mods_latched, uint32_t mods_locked, + uint32_t group) { UNUSED_PARAMETER(keyboard); UNUSED_PARAMETER(serial); obs_hotkeys_platform_t *plat = (obs_hotkeys_platform_t *)data; - xkb_state_update_mask(plat->xkb_state, mods_depressed, mods_latched, - mods_locked, 0, 0, group); + xkb_state_update_mask(plat->xkb_state, mods_depressed, mods_latched, mods_locked, 0, 0, group); if (plat->current_layout != group) { plat->current_layout = group; @@ -124,9 +115,8 @@ static void platform_keyboard_modifiers(void *data, } } -static void platform_keyboard_key(void *data, struct wl_keyboard *keyboard, - uint32_t serial, uint32_t time, uint32_t key, - uint32_t state) +static void platform_keyboard_key(void *data, struct wl_keyboard *keyboard, uint32_t serial, uint32_t time, + uint32_t key, uint32_t state) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(keyboard); @@ -139,9 +129,8 @@ static void platform_keyboard_key(void *data, struct wl_keyboard *keyboard, // callbacks. } -static void platform_keyboard_enter(void *data, struct wl_keyboard *keyboard, - uint32_t serial, struct wl_surface *surface, - struct wl_array *keys) +static void platform_keyboard_enter(void *data, struct wl_keyboard *keyboard, uint32_t serial, + struct wl_surface *surface, struct wl_array *keys) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(keyboard); @@ -151,8 +140,8 @@ static void platform_keyboard_enter(void *data, struct wl_keyboard *keyboard, // Nothing to do here. } -static void platform_keyboard_leave(void *data, struct wl_keyboard *keyboard, - uint32_t serial, struct wl_surface *surface) +static void platform_keyboard_leave(void *data, struct wl_keyboard *keyboard, uint32_t serial, + struct wl_surface *surface) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(keyboard); @@ -161,9 +150,7 @@ static void platform_keyboard_leave(void *data, struct wl_keyboard *keyboard, // Nothing to do. } -static void platform_keyboard_repeat_info(void *data, - struct wl_keyboard *keyboard, - int32_t rate, int32_t delay) +static void platform_keyboard_repeat_info(void *data, struct wl_keyboard *keyboard, int32_t rate, int32_t delay) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(keyboard); @@ -181,8 +168,7 @@ const struct wl_keyboard_listener keyboard_listener = { .repeat_info = platform_keyboard_repeat_info, }; -static void platform_seat_capabilities(void *data, struct wl_seat *seat, - uint32_t capabilities) +static void platform_seat_capabilities(void *data, struct wl_seat *seat, uint32_t capabilities) { UNUSED_PARAMETER(seat); obs_hotkeys_platform_t *plat = (obs_hotkeys_platform_t *)data; @@ -191,15 +177,13 @@ static void platform_seat_capabilities(void *data, struct wl_seat *seat, if (kb_present && plat->keyboard == NULL) { plat->keyboard = wl_seat_get_keyboard(plat->seat); - wl_keyboard_add_listener(plat->keyboard, &keyboard_listener, - plat); + wl_keyboard_add_listener(plat->keyboard, &keyboard_listener, plat); } else if (!kb_present && plat->keyboard != NULL) { wl_keyboard_release(plat->keyboard); plat->keyboard = NULL; } } -static void platform_seat_name(void *data, struct wl_seat *seat, - const char *name) +static void platform_seat_name(void *data, struct wl_seat *seat, const char *name) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(seat); @@ -212,27 +196,23 @@ const struct wl_seat_listener seat_listener = { .name = platform_seat_name, }; -static void platform_registry_handler(void *data, struct wl_registry *registry, - uint32_t id, const char *interface, +static void platform_registry_handler(void *data, struct wl_registry *registry, uint32_t id, const char *interface, uint32_t version) { obs_hotkeys_platform_t *plat = (obs_hotkeys_platform_t *)data; if (strcmp(interface, wl_seat_interface.name) == 0) { if (version < 4) { - blog(LOG_WARNING, - "[wayland] hotkeys disabled, compositor is too old"); + blog(LOG_WARNING, "[wayland] hotkeys disabled, compositor is too old"); return; } // Only negotiate up to version 7, the current wl_seat at time of writing. - plat->seat = wl_registry_bind(registry, id, &wl_seat_interface, - version <= 7 ? version : 7); + plat->seat = wl_registry_bind(registry, id, &wl_seat_interface, version <= 7 ? version : 7); wl_seat_add_listener(plat->seat, &seat_listener, plat); } } -static void platform_registry_remover(void *data, struct wl_registry *registry, - uint32_t id) +static void platform_registry_remover(void *data, struct wl_registry *registry, uint32_t id) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(registry); @@ -256,24 +236,20 @@ void obs_nix_wayland_log_info(void) blog(LOG_INFO, "Connected to Wayland server"); } -static bool -obs_nix_wayland_hotkeys_platform_init(struct obs_core_hotkeys *hotkeys) +static bool obs_nix_wayland_hotkeys_platform_init(struct obs_core_hotkeys *hotkeys) { struct wl_display *display = obs_get_nix_platform_display(); hotkeys->platform_context = bzalloc(sizeof(obs_hotkeys_platform_t)); hotkeys->platform_context->display = display; - hotkeys->platform_context->xkb_context = - xkb_context_new(XKB_CONTEXT_NO_FLAGS); + hotkeys->platform_context->xkb_context = xkb_context_new(XKB_CONTEXT_NO_FLAGS); struct wl_registry *registry = wl_display_get_registry(display); - wl_registry_add_listener(registry, ®istry_listener, - hotkeys->platform_context); + wl_registry_add_listener(registry, ®istry_listener, hotkeys->platform_context); wl_display_roundtrip(display); return true; } -static void -obs_nix_wayland_hotkeys_platform_free(struct obs_core_hotkeys *hotkeys) +static void obs_nix_wayland_hotkeys_platform_free(struct obs_core_hotkeys *hotkeys) { obs_hotkeys_platform_t *plat = hotkeys->platform_context; xkb_context_unref(plat->xkb_context); @@ -282,9 +258,7 @@ obs_nix_wayland_hotkeys_platform_free(struct obs_core_hotkeys *hotkeys) bfree(plat); } -static bool -obs_nix_wayland_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, - obs_key_t key) +static bool obs_nix_wayland_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, obs_key_t key) { UNUSED_PARAMETER(context); UNUSED_PARAMETER(key); @@ -300,8 +274,7 @@ static void obs_nix_wayland_key_to_str(obs_key_t key, struct dstr *dstr) if (obs->hotkeys.translations[key]) { dstr_copy(dstr, obs->hotkeys.translations[key]); } else { - dstr_printf(dstr, "Mouse %d", - (int)(key - OBS_KEY_MOUSE1 + 1)); + dstr_printf(dstr, "Mouse %d", (int)(key - OBS_KEY_MOUSE1 + 1)); } return; } @@ -310,14 +283,12 @@ static void obs_nix_wayland_key_to_str(obs_key_t key, struct dstr *dstr) if (obs->hotkeys.translations[key]) { dstr_copy(dstr, obs->hotkeys.translations[key]); } else { - dstr_printf(dstr, "Numpad %d", - (int)(key - OBS_KEY_NUM0)); + dstr_printf(dstr, "Numpad %d", (int)(key - OBS_KEY_NUM0)); } return; } -#define translate_key(key, def) \ - dstr_copy(dstr, obs_get_hotkey_translation(key, def)) +#define translate_key(key, def) dstr_copy(dstr, obs_get_hotkey_translation(key, def)) switch (key) { case OBS_KEY_INSERT: diff --git a/libobs/obs-nix-x11.c b/libobs/obs-nix-x11.c index 924892e82..0c76b65a2 100644 --- a/libobs/obs-nix-x11.c +++ b/libobs/obs-nix-x11.c @@ -48,15 +48,13 @@ void obs_nix_x11_log_info(void) blog(LOG_INFO, "Window System: X%d.%d, Vendor: %s, Version: %d" ".%d.%d", - protocol_version, protocol_revision, vendor_name, - vendor_release / 10000000, (vendor_release / 100000) % 100, - (vendor_release / 1000) % 100); + protocol_version, protocol_revision, vendor_name, vendor_release / 10000000, + (vendor_release / 100000) % 100, (vendor_release / 1000) % 100); } else { blog(LOG_INFO, "Window System: X%d.%d - vendor string: %s - " "vendor release: %d", - protocol_version, protocol_revision, vendor_name, - vendor_release); + protocol_version, protocol_revision, vendor_name, vendor_release); } } @@ -700,8 +698,7 @@ static inline void fill_base_keysyms(struct obs_core_hotkeys *hotkeys) hotkeys->platform_context->base_keysyms[i] = get_keysym(i); } -static obs_key_t key_from_base_keysym(obs_hotkeys_platform_t *context, - xcb_keysym_t code) +static obs_key_t key_from_base_keysym(obs_hotkeys_platform_t *context, xcb_keysym_t code) { for (size_t i = 0; i < OBS_KEY_LAST_VALUE; i++) { if (context->base_keysyms[i] == (xcb_keysym_t)code) { @@ -721,8 +718,7 @@ static obs_key_t key_from_base_keysym(obs_hotkeys_platform_t *context, return OBS_KEY_NONE; } -static inline void add_key(obs_hotkeys_platform_t *context, obs_key_t key, - int code) +static inline void add_key(obs_hotkeys_platform_t *context, obs_key_t key, int code) { xcb_keycode_t kc = (xcb_keycode_t)code; da_push_back(context->keycodes[key].list, &kc); @@ -731,8 +727,7 @@ static inline void add_key(obs_hotkeys_platform_t *context, obs_key_t key, blog(LOG_DEBUG, "found alternate keycode %d for %s " "which already has keycode %d", - code, obs_key_to_name(key), - (int)context->keycodes[key].list.array[0]); + code, obs_key_to_name(key), (int)context->keycodes[key].list.array[0]); } } @@ -751,8 +746,7 @@ static inline bool fill_keycodes(struct obs_core_hotkeys *hotkeys) context->min_keycode = setup->min_keycode; - cookie = xcb_get_keyboard_mapping(connection, mincode, - maxcode - mincode + 1); + cookie = xcb_get_keyboard_mapping(connection, mincode, maxcode - mincode + 1); reply = xcb_get_keyboard_mapping_reply(connection, cookie, &error); @@ -766,8 +760,7 @@ static inline bool fill_keycodes(struct obs_core_hotkeys *hotkeys) context->num_keysyms = (maxcode - mincode + 1) * syms_per_code; context->syms_per_code = syms_per_code; - context->keysyms = - bmemdup(keysyms, sizeof(xcb_keysym_t) * context->num_keysyms); + context->keysyms = bmemdup(keysyms, sizeof(xcb_keysym_t) * context->num_keysyms); for (code = mincode; code <= maxcode; code++) { const xcb_keysym_t *sym; @@ -803,8 +796,7 @@ error1: return error != NULL || reply == NULL; } -static xcb_screen_t *default_screen(obs_hotkeys_platform_t *context, - xcb_connection_t *connection) +static xcb_screen_t *default_screen(obs_hotkeys_platform_t *context, xcb_connection_t *connection) { int def_screen_idx = XDefaultScreen(context->display); xcb_screen_iterator_t iter; @@ -820,8 +812,7 @@ static xcb_screen_t *default_screen(obs_hotkeys_platform_t *context, return NULL; } -static inline xcb_window_t root_window(obs_hotkeys_platform_t *context, - xcb_connection_t *connection) +static inline xcb_window_t root_window(obs_hotkeys_platform_t *context, xcb_connection_t *connection) { xcb_screen_t *screen = default_screen(context, connection); if (screen) @@ -842,8 +833,7 @@ static inline void registerMouseEvents(struct obs_core_hotkeys *hotkeys) } mask; mask.head.deviceid = XCB_INPUT_DEVICE_ALL_MASTER; mask.head.mask_len = sizeof(mask.mask) / sizeof(uint32_t); - mask.mask = XCB_INPUT_XI_EVENT_MASK_RAW_BUTTON_PRESS | - XCB_INPUT_XI_EVENT_MASK_RAW_BUTTON_RELEASE; + mask.mask = XCB_INPUT_XI_EVENT_MASK_RAW_BUTTON_PRESS | XCB_INPUT_XI_EVENT_MASK_RAW_BUTTON_RELEASE; xcb_input_xi_select_events(connection, window, 1, &mask.head); xcb_flush(connection); @@ -884,8 +874,7 @@ static void obs_nix_x11_hotkeys_platform_free(struct obs_core_hotkeys *hotkeys) hotkeys->platform_context = NULL; } -static bool mouse_button_pressed(xcb_connection_t *connection, - obs_hotkeys_platform_t *context, obs_key_t key) +static bool mouse_button_pressed(xcb_connection_t *connection, obs_hotkeys_platform_t *context, obs_key_t key) { bool ret = false; @@ -901,8 +890,7 @@ static bool mouse_button_pressed(xcb_connection_t *connection, xcb_input_raw_button_press_event_t *mot; mot = (xcb_input_raw_button_press_event_t *)ev; if (mot->detail < XINPUT_MOUSE_LEN) { - context->pressed[mot->detail - 1] = - true; + context->pressed[mot->detail - 1] = true; context->update[mot->detail - 1] = true; } else { blog(LOG_WARNING, "Unsupported button"); @@ -1055,22 +1043,19 @@ static bool mouse_button_pressed(xcb_connection_t *connection, return ret; } -static inline bool keycode_pressed(xcb_query_keymap_reply_t *reply, - xcb_keycode_t code) +static inline bool keycode_pressed(xcb_query_keymap_reply_t *reply, xcb_keycode_t code) { return (reply->keys[code / 8] & (1 << (code % 8))) != 0; } -static bool key_pressed(xcb_connection_t *connection, - obs_hotkeys_platform_t *context, obs_key_t key) +static bool key_pressed(xcb_connection_t *connection, obs_hotkeys_platform_t *context, obs_key_t key) { struct keycode_list *codes = &context->keycodes[key]; xcb_generic_error_t *error = NULL; xcb_query_keymap_reply_t *reply; bool pressed = false; - reply = xcb_query_keymap_reply(connection, xcb_query_keymap(connection), - &error); + reply = xcb_query_keymap_reply(connection, xcb_query_keymap(connection), &error); if (error) { blog(LOG_WARNING, "xcb_query_keymap failed"); @@ -1092,9 +1077,7 @@ static bool key_pressed(xcb_connection_t *connection, return pressed; } -static bool -obs_nix_x11_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, - obs_key_t key) +static bool obs_nix_x11_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, obs_key_t key) { xcb_connection_t *conn = XGetXCBConnection(context->display); @@ -1137,8 +1120,7 @@ static void obs_nix_x11_key_to_str(obs_key_t key, struct dstr *dstr) if (obs->hotkeys.translations[key]) { dstr_copy(dstr, obs->hotkeys.translations[key]); } else { - dstr_printf(dstr, "Mouse %d", - (int)(key - OBS_KEY_MOUSE1 + 1)); + dstr_printf(dstr, "Mouse %d", (int)(key - OBS_KEY_MOUSE1 + 1)); } return; } @@ -1147,14 +1129,12 @@ static void obs_nix_x11_key_to_str(obs_key_t key, struct dstr *dstr) if (obs->hotkeys.translations[key]) { dstr_copy(dstr, obs->hotkeys.translations[key]); } else { - dstr_printf(dstr, "Numpad %d", - (int)(key - OBS_KEY_NUM0)); + dstr_printf(dstr, "Numpad %d", (int)(key - OBS_KEY_NUM0)); } return; } -#define translate_key(key, def) \ - dstr_copy(dstr, obs_get_hotkey_translation(key, def)) +#define translate_key(key, def) dstr_copy(dstr, obs_get_hotkey_translation(key, def)) switch (key) { case OBS_KEY_INSERT: @@ -1239,8 +1219,7 @@ static void obs_nix_x11_key_to_str(obs_key_t key, struct dstr *dstr) } } -static obs_key_t key_from_keycode(obs_hotkeys_platform_t *context, - xcb_keycode_t code) +static obs_key_t key_from_keycode(obs_hotkeys_platform_t *context, xcb_keycode_t code) { for (size_t i = 0; i < OBS_KEY_LAST_VALUE; i++) { struct keycode_list *codes = &context->keycodes[i]; diff --git a/libobs/obs-nix.c b/libobs/obs-nix.c index 77c36be5e..c93f756c1 100644 --- a/libobs/obs-nix.c +++ b/libobs/obs-nix.c @@ -61,25 +61,20 @@ static const char *module_data[] = { FLATPAK_PLUGIN_PATH "/share/obs/obs-plugins/%module%", }; -static const int module_patterns_size = - sizeof(module_bin) / sizeof(module_bin[0]); +static const int module_patterns_size = sizeof(module_bin) / sizeof(module_bin[0]); static const struct obs_nix_hotkeys_vtable *hotkeys_vtable = NULL; void add_default_module_paths(void) { - char *module_bin_path = - os_get_executable_path_ptr("../" OBS_PLUGIN_PATH); - char *module_data_path = os_get_executable_path_ptr( - "../" OBS_DATA_PATH "/obs-plugins/%module%"); + char *module_bin_path = os_get_executable_path_ptr("../" OBS_PLUGIN_PATH); + char *module_data_path = os_get_executable_path_ptr("../" OBS_DATA_PATH "/obs-plugins/%module%"); if (module_bin_path && module_data_path) { - char *abs_module_bin_path = - os_get_abs_path_ptr(module_bin_path); + char *abs_module_bin_path = os_get_abs_path_ptr(module_bin_path); if (abs_module_bin_path && - strcmp(abs_module_bin_path, OBS_INSTALL_PREFIX - "/" OBS_PLUGIN_DESTINATION) != 0) { + strcmp(abs_module_bin_path, OBS_INSTALL_PREFIX "/" OBS_PLUGIN_DESTINATION) != 0) { obs_add_module_path(module_bin_path, module_data_path); } bfree(abs_module_bin_path); @@ -105,8 +100,7 @@ char *find_libobs_data_file(const char *file) if (check_path(file, OBS_DATA_PATH "/libobs/", &output)) return output.array; - char *relative_data_path = - os_get_executable_path_ptr("../" OBS_DATA_PATH "/libobs/"); + char *relative_data_path = os_get_executable_path_ptr("../" OBS_DATA_PATH "/libobs/"); if (relative_data_path) { bool found = check_path(file, relative_data_path, &output); @@ -128,8 +122,7 @@ char *find_libobs_data_file(const char *file) static void log_processor_cores(void) { - blog(LOG_INFO, "Physical Cores: %d, Logical Cores: %d", - os_get_physical_cores(), os_get_logical_cores()); + blog(LOG_INFO, "Physical Cores: %d, Logical Cores: %d", os_get_physical_cores(), os_get_logical_cores()); } #if defined(__linux__) @@ -267,18 +260,15 @@ static void log_memory_info(void) len = sizeof(mem); if (sysctl(mib, 2, &mem, &len, NULL, 0) >= 0) - blog(LOG_INFO, "Physical Memory: %" PRIi64 "MB Total", - mem / 1024 / 1024); + blog(LOG_INFO, "Physical Memory: %" PRIi64 "MB Total", mem / 1024 / 1024); #else struct sysinfo info; if (sysinfo(&info) < 0) return; - blog(LOG_INFO, - "Physical Memory: %" PRIu64 "MB Total, %" PRIu64 "MB Free", + blog(LOG_INFO, "Physical Memory: %" PRIu64 "MB Total, %" PRIu64 "MB Free", (uint64_t)info.totalram * info.mem_unit / 1024 / 1024, - ((uint64_t)info.freeram + (uint64_t)info.bufferram) * - info.mem_unit / 1024 / 1024); + ((uint64_t)info.freeram + (uint64_t)info.bufferram) * info.mem_unit / 1024 / 1024); #endif } @@ -354,8 +344,7 @@ static void log_flatpak_info(void) { config_t *fp_info = NULL; - if (config_open(&fp_info, "/.flatpak-info", CONFIG_OPEN_EXISTING) != - CONFIG_SUCCESS) { + if (config_open(&fp_info, "/.flatpak-info", CONFIG_OPEN_EXISTING) != CONFIG_SUCCESS) { blog(LOG_ERROR, "Unable to open .flatpak-info file"); return; } @@ -363,16 +352,12 @@ static void log_flatpak_info(void) const char *branch = config_get_string(fp_info, "Instance", "branch"); const char *arch = config_get_string(fp_info, "Instance", "arch"); - const char *runtime = - config_get_string(fp_info, "Application", "runtime"); + const char *runtime = config_get_string(fp_info, "Application", "runtime"); - const char *app_exts = - config_get_string(fp_info, "Instance", "app-extensions"); - const char *runtime_exts = - config_get_string(fp_info, "Instance", "runtime-extensions"); + const char *app_exts = config_get_string(fp_info, "Instance", "app-extensions"); + const char *runtime_exts = config_get_string(fp_info, "Instance", "runtime-extensions"); - const char *fp_version = - config_get_string(fp_info, "Instance", "flatpak-version"); + const char *fp_version = config_get_string(fp_info, "Instance", "flatpak-version"); blog(LOG_INFO, "Flatpak Branch: %s", branch ? branch : "none"); blog(LOG_INFO, "Flatpak Arch: %s", arch ? arch : "unknown"); @@ -389,8 +374,7 @@ static void log_flatpak_info(void) log_flatpak_extensions(runtime_exts); } - blog(LOG_INFO, "Flatpak Framework Version: %s", - fp_version ? fp_version : "unknown"); + blog(LOG_INFO, "Flatpak Framework Version: %s", fp_version ? fp_version : "unknown"); config_close(fp_info); } @@ -402,11 +386,9 @@ static void log_desktop_session_info(void) char *session_type = getenv("XDG_SESSION_TYPE"); if (current_desktop && session_desktop) - blog(LOG_INFO, "Desktop Environment: %s (%s)", current_desktop, - session_desktop); + blog(LOG_INFO, "Desktop Environment: %s (%s)", current_desktop, session_desktop); else if (current_desktop || session_desktop) - blog(LOG_INFO, "Desktop Environment: %s", - current_desktop ? current_desktop : session_desktop); + blog(LOG_INFO, "Desktop Environment: %s", current_desktop ? current_desktop : session_desktop); if (session_type) blog(LOG_INFO, "Session Type: %s", session_type); @@ -457,8 +439,7 @@ void obs_hotkeys_platform_free(struct obs_core_hotkeys *hotkeys) hotkeys_vtable = NULL; } -bool obs_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, - obs_key_t key) +bool obs_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, obs_key_t key) { return hotkeys_vtable->is_pressed(context, key); } @@ -494,8 +475,7 @@ static inline void add_combo_key(obs_key_t key, struct dstr *str) dstr_free(&key_str); } -void obs_key_combination_to_str(obs_key_combination_t combination, - struct dstr *str) +void obs_key_combination_to_str(obs_key_combination_t combination, struct dstr *str) { if ((combination.modifiers & INTERACT_CONTROL_KEY) != 0) { add_combo_key(OBS_KEY_CONTROL, str); diff --git a/libobs/obs-output-delay.c b/libobs/obs-output-delay.c index dd8161647..de72bd715 100644 --- a/libobs/obs-output-delay.c +++ b/libobs/obs-output-delay.c @@ -33,21 +33,18 @@ static inline bool flag_encoded(const struct obs_output *output) return (output->info.flags & OBS_OUTPUT_ENCODED) != 0; } -static inline bool log_flag_encoded(const struct obs_output *output, - const char *func_name, bool inverse_log) +static inline bool log_flag_encoded(const struct obs_output *output, const char *func_name, bool inverse_log) { const char *prefix = inverse_log ? "n encoded" : " raw"; bool ret = flag_encoded(output); if ((!inverse_log && !ret) || (inverse_log && ret)) - blog(LOG_WARNING, "Output '%s': Tried to use %s on a%s output", - output->context.name, func_name, prefix); + blog(LOG_WARNING, "Output '%s': Tried to use %s on a%s output", output->context.name, func_name, + prefix); return ret; } -static inline void push_packet(struct obs_output *output, - struct encoder_packet *packet, - struct encoder_packet_time *packet_time, - uint64_t t) +static inline void push_packet(struct obs_output *output, struct encoder_packet *packet, + struct encoder_packet_time *packet_time, uint64_t t) { struct delay_data dd; @@ -63,18 +60,14 @@ static inline void push_packet(struct obs_output *output, pthread_mutex_unlock(&output->delay_mutex); } -static inline void process_delay_data(struct obs_output *output, - struct delay_data *dd) +static inline void process_delay_data(struct obs_output *output, struct delay_data *dd) { switch (dd->msg) { case DELAY_MSG_PACKET: if (!delay_active(output) || !delay_capturing(output)) obs_encoder_packet_release(&dd->packet); else - output->delay_callback(output, &dd->packet, - dd->packet_time_valid - ? &dd->packet_time - : NULL); + output->delay_callback(output, &dd->packet, dd->packet_time_valid ? &dd->packet_time : NULL); break; case DELAY_MSG_START: obs_output_actual_start(output); @@ -136,8 +129,7 @@ static inline bool pop_packet(struct obs_output *output, uint64_t t) return popped; } -void process_delay(void *data, struct encoder_packet *packet, - struct encoder_packet_time *packet_time) +void process_delay(void *data, struct encoder_packet *packet, struct encoder_packet_time *packet_time) { struct obs_output *output = data; uint64_t t = os_gettime_ns(); @@ -194,8 +186,7 @@ void obs_output_delay_stop(obs_output_t *output) do_output_signal(output, "stopping"); } -void obs_output_set_delay(obs_output_t *output, uint32_t delay_sec, - uint32_t flags) +void obs_output_set_delay(obs_output_t *output, uint32_t delay_sec, uint32_t flags) { if (!obs_output_valid(output, "obs_output_set_delay")) return; @@ -208,14 +199,11 @@ void obs_output_set_delay(obs_output_t *output, uint32_t delay_sec, uint32_t obs_output_get_delay(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_set_delay") - ? output->delay_sec - : 0; + return obs_output_valid(output, "obs_output_set_delay") ? output->delay_sec : 0; } uint32_t obs_output_get_active_delay(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_set_delay") - ? (uint32_t)(output->active_delay_ns / 1000000000ULL) - : 0; + return obs_output_valid(output, "obs_output_set_delay") ? (uint32_t)(output->active_delay_ns / 1000000000ULL) + : 0; } diff --git a/libobs/obs-output.c b/libobs/obs-output.c index f8b71df5f..9fd4c2250 100644 --- a/libobs/obs-output.c +++ b/libobs/obs-output.c @@ -67,14 +67,13 @@ static inline bool flag_encoded(const struct obs_output *output) return (output->info.flags & OBS_OUTPUT_ENCODED) != 0; } -static inline bool log_flag_encoded(const struct obs_output *output, - const char *func_name, bool inverse_log) +static inline bool log_flag_encoded(const struct obs_output *output, const char *func_name, bool inverse_log) { const char *prefix = inverse_log ? "n encoded" : " raw"; bool ret = flag_encoded(output); if ((!inverse_log && !ret) || (inverse_log && ret)) - blog(LOG_WARNING, "Output '%s': Tried to use %s on a%s output", - output->context.name, func_name, prefix); + blog(LOG_WARNING, "Output '%s': Tried to use %s on a%s output", output->context.name, func_name, + prefix); return ret; } @@ -83,14 +82,12 @@ static inline bool flag_video(const struct obs_output *output) return (output->info.flags & OBS_OUTPUT_VIDEO) != 0; } -static inline bool log_flag_video(const struct obs_output *output, - const char *func_name) +static inline bool log_flag_video(const struct obs_output *output, const char *func_name) { bool ret = flag_video(output); if (!ret) - blog(LOG_WARNING, - "Output '%s': Tried to use %s on a non-video output", - output->context.name, func_name); + blog(LOG_WARNING, "Output '%s': Tried to use %s on a non-video output", output->context.name, + func_name); return ret; } @@ -99,14 +96,12 @@ static inline bool flag_audio(const struct obs_output *output) return (output->info.flags & OBS_OUTPUT_AUDIO) != 0; } -static inline bool log_flag_audio(const struct obs_output *output, - const char *func_name) +static inline bool log_flag_audio(const struct obs_output *output, const char *func_name) { bool ret = flag_audio(output); if (!ret) - blog(LOG_WARNING, - "Output '%s': Tried to use %s on a non-audio output", - output->context.name, func_name); + blog(LOG_WARNING, "Output '%s': Tried to use %s on a non-audio output", output->context.name, + func_name); return ret; } @@ -115,14 +110,12 @@ static inline bool flag_service(const struct obs_output *output) return (output->info.flags & OBS_OUTPUT_SERVICE) != 0; } -static inline bool log_flag_service(const struct obs_output *output, - const char *func_name) +static inline bool log_flag_service(const struct obs_output *output, const char *func_name) { bool ret = flag_service(output); if (!ret) - blog(LOG_WARNING, - "Output '%s': Tried to use %s on a non-service output", - output->context.name, func_name); + blog(LOG_WARNING, "Output '%s': Tried to use %s on a non-service output", output->context.name, + func_name); return ret; } @@ -156,19 +149,17 @@ static const char *output_signals[] = { NULL, }; -static bool init_output_handlers(struct obs_output *output, const char *name, - obs_data_t *settings, obs_data_t *hotkey_data) +static bool init_output_handlers(struct obs_output *output, const char *name, obs_data_t *settings, + obs_data_t *hotkey_data) { - if (!obs_context_data_init(&output->context, OBS_OBJ_TYPE_OUTPUT, - settings, name, NULL, hotkey_data, false)) + if (!obs_context_data_init(&output->context, OBS_OBJ_TYPE_OUTPUT, settings, name, NULL, hotkey_data, false)) return false; signal_handler_add_array(output->context.signals, output_signals); return true; } -obs_output_t *obs_output_create(const char *id, const char *name, - obs_data_t *settings, obs_data_t *hotkey_data) +obs_output_t *obs_output_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data) { const struct obs_output_info *info = find_output(id); struct obs_output *output; @@ -210,25 +201,20 @@ obs_output_t *obs_output_create(const char *id, const char *name, if (output->info.get_defaults) output->info.get_defaults(output->context.settings); - ret = os_event_init(&output->reconnect_stop_event, - OS_EVENT_TYPE_MANUAL); + ret = os_event_init(&output->reconnect_stop_event, OS_EVENT_TYPE_MANUAL); if (ret < 0) goto fail; output->reconnect_retry_sec = 2; output->reconnect_retry_max = 20; - output->reconnect_retry_exp = - RECONNECT_RETRY_BASE_EXP + (rand_float(0) * 0.05f); + output->reconnect_retry_exp = RECONNECT_RETRY_BASE_EXP + (rand_float(0) * 0.05f); output->valid = true; - obs_context_init_control(&output->context, output, - (obs_destroy_cb)obs_output_destroy); - obs_context_data_insert(&output->context, &obs->data.outputs_mutex, - &obs->data.first_output); + obs_context_init_control(&output->context, output, (obs_destroy_cb)obs_output_destroy); + obs_context_data_insert(&output->context, &obs->data.outputs_mutex, &obs->data.first_output); if (info) - output->context.data = - info->create(output->context.settings, output); + output->context.data = info->create(output->context.settings, output); if (!output->context.data) blog(LOG_ERROR, "Failed to create output '%s'!", name); @@ -243,8 +229,7 @@ fail: static inline void free_packets(struct obs_output *output) { for (size_t i = 0; i < output->interleaved_packets.num; i++) - obs_encoder_packet_release(output->interleaved_packets.array + - i); + obs_encoder_packet_release(output->interleaved_packets.array + i); da_free(output->interleaved_packets); } @@ -292,20 +277,17 @@ void obs_output_destroy(obs_output_t *output) for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (output->video_encoders[i]) { - obs_encoder_remove_output( - output->video_encoders[i], output); + obs_encoder_remove_output(output->video_encoders[i], output); obs_encoder_release(output->video_encoders[i]); } if (output->caption_tracks[i]) { - destroy_caption_track( - &output->caption_tracks[i]); + destroy_caption_track(&output->caption_tracks[i]); } } for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { if (output->audio_encoders[i]) { - obs_encoder_remove_output( - output->audio_encoders[i], output); + obs_encoder_remove_output(output->audio_encoders[i], output); obs_encoder_release(output->audio_encoders[i]); } } @@ -337,9 +319,7 @@ void obs_output_destroy(obs_output_t *output) const char *obs_output_get_name(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_name") - ? output->context.name - : NULL; + return obs_output_valid(output, "obs_output_get_name") ? output->context.name : NULL; } bool obs_output_actual_start(obs_output_t *output) @@ -387,8 +367,7 @@ bool obs_output_start(obs_output_t *output) return false; if (flag_service(output) && - !(obs_service_can_try_to_connect(output->service) && - obs_service_initialize(output->service, output))) + !(obs_service_can_try_to_connect(output->service) && obs_service_initialize(output->service, output))) return false; if (output->delay_sec) { @@ -428,8 +407,7 @@ static void log_frame_info(struct obs_output *output) blog(LOG_INFO, "Output '%s': stopping", output->context.name); if (!dropped || !total) - blog(LOG_INFO, "Output '%s': Total frames output: %d", - output->context.name, total); + blog(LOG_INFO, "Output '%s': Total frames output: %d", output->context.name, total); else blog(LOG_INFO, "Output '%s': Total frames output: %d" @@ -437,12 +415,9 @@ static void log_frame_info(struct obs_output *output) output->context.name, total - dropped, total); if (!lagged || !drawn) - blog(LOG_INFO, "Output '%s': Total drawn frames: %" PRIu32, - output->context.name, drawn); + blog(LOG_INFO, "Output '%s': Total drawn frames: %" PRIu32, output->context.name, drawn); else - blog(LOG_INFO, - "Output '%s': Total drawn frames: %" PRIu32 " (%" PRIu32 - " attempted)", + blog(LOG_INFO, "Output '%s': Total drawn frames: %" PRIu32 " (%" PRIu32 " attempted)", output->context.name, drawn - lagged, drawn); if (drawn && lagged) @@ -553,15 +528,12 @@ void obs_output_force_stop(obs_output_t *output) bool obs_output_active(const obs_output_t *output) { - return (output != NULL) ? (active(output) || reconnecting(output)) - : false; + return (output != NULL) ? (active(output) || reconnecting(output)) : false; } uint32_t obs_output_get_flags(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_flags") - ? output->info.flags - : 0; + return obs_output_valid(output, "obs_output_get_flags") ? output->info.flags : 0; } uint32_t obs_get_output_flags(const char *id) @@ -622,8 +594,7 @@ void obs_output_update(obs_output_t *output, obs_data_t *settings) obs_data_apply(output->context.settings, settings); if (output->info.update) - output->info.update(output->context.data, - output->context.settings); + output->info.update(output->context.data, output->context.settings); } obs_data_t *obs_output_get_settings(const obs_output_t *output) @@ -637,9 +608,7 @@ obs_data_t *obs_output_get_settings(const obs_output_t *output) bool obs_output_can_pause(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_can_pause") - ? !!(output->info.flags & OBS_OUTPUT_CAN_PAUSE) - : false; + return obs_output_valid(output, "obs_output_can_pause") ? !!(output->info.flags & OBS_OUTPUT_CAN_PAUSE) : false; } static inline void end_pause(struct pause_data *pause, uint64_t ts) @@ -656,8 +625,7 @@ static inline uint64_t get_closest_v_ts(struct pause_data *pause) uint64_t i2 = interval * 2; uint64_t ts = os_gettime_ns(); - return pause->last_video_ts + - ((ts - pause->last_video_ts + i2) / interval) * interval; + return pause->last_video_ts + ((ts - pause->last_video_ts + i2) / interval) * interval; } static inline bool pause_can_start(struct pause_data *pause) @@ -670,8 +638,7 @@ static inline bool pause_can_stop(struct pause_data *pause) return !!pause->ts_start && !pause->ts_end; } -static bool get_first_audio_encoder_index(const struct obs_output *output, - size_t *index) +static bool get_first_audio_encoder_index(const struct obs_output *output, size_t *index) { if (!index) return false; @@ -686,8 +653,7 @@ static bool get_first_audio_encoder_index(const struct obs_output *output, return false; } -static bool get_first_video_encoder_index(const struct obs_output *output, - size_t *index) +static bool get_first_video_encoder_index(const struct obs_output *output, size_t *index) { if (!index) return false; @@ -836,23 +802,19 @@ bool obs_output_pause(obs_output_t *output, bool pause) if (os_atomic_load_bool(&output->paused) == pause) return true; - success = flag_encoded(output) ? obs_encoded_output_pause(output, pause) - : obs_raw_output_pause(output, pause); + success = flag_encoded(output) ? obs_encoded_output_pause(output, pause) : obs_raw_output_pause(output, pause); if (success) { os_atomic_set_bool(&output->paused, pause); do_output_signal(output, pause ? "pause" : "unpause"); - blog(LOG_INFO, "output %s %spaused", output->context.name, - pause ? "" : "un"); + blog(LOG_INFO, "output %s %spaused", output->context.name, pause ? "" : "un"); } return success; } bool obs_output_paused(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_paused") - ? os_atomic_load_bool(&output->paused) - : false; + return obs_output_valid(output, "obs_output_paused") ? os_atomic_load_bool(&output->paused) : false; } uint64_t obs_output_get_pause_offset(obs_output_t *output) @@ -871,16 +833,12 @@ uint64_t obs_output_get_pause_offset(obs_output_t *output) signal_handler_t *obs_output_get_signal_handler(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_signal_handler") - ? output->context.signals - : NULL; + return obs_output_valid(output, "obs_output_get_signal_handler") ? output->context.signals : NULL; } proc_handler_t *obs_output_get_proc_handler(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_proc_handler") - ? output->context.procs - : NULL; + return obs_output_valid(output, "obs_output_get_proc_handler") ? output->context.procs : NULL; } void obs_output_set_media(obs_output_t *output, video_t *video, audio_t *audio) @@ -969,13 +927,10 @@ void obs_output_set_mixers(obs_output_t *output, size_t mixers) size_t obs_output_get_mixers(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_mixers") - ? output->mixer_mask - : 0; + return obs_output_valid(output, "obs_output_get_mixers") ? output->mixer_mask : 0; } -void obs_output_remove_encoder_internal(struct obs_output *output, - struct obs_encoder *encoder) +void obs_output_remove_encoder_internal(struct obs_output *output, struct obs_encoder *encoder) { if (!obs_output_valid(output, "obs_output_remove_encoder_internal")) return; @@ -999,8 +954,7 @@ void obs_output_remove_encoder_internal(struct obs_output *output, } } -void obs_output_remove_encoder(struct obs_output *output, - struct obs_encoder *encoder) +void obs_output_remove_encoder(struct obs_output *output, struct obs_encoder *encoder) { if (!obs_output_valid(output, "obs_output_remove_encoder")) return; @@ -1012,8 +966,7 @@ void obs_output_remove_encoder(struct obs_output *output, static struct caption_track_data *create_caption_track() { - struct caption_track_data *rval = - bzalloc(sizeof(struct caption_track_data)); + struct caption_track_data *rval = bzalloc(sizeof(struct caption_track_data)); pthread_mutex_init_value(&rval->caption_mutex); if (pthread_mutex_init(&rval->caption_mutex, NULL) != 0) { @@ -1023,13 +976,11 @@ static struct caption_track_data *create_caption_track() return rval; } -void obs_output_set_video_encoder2(obs_output_t *output, obs_encoder_t *encoder, - size_t idx) +void obs_output_set_video_encoder2(obs_output_t *output, obs_encoder_t *encoder, size_t idx) { if (!obs_output_valid(output, "obs_output_set_video_encoder2")) return; - if (!log_flag_encoded(output, __FUNCTION__, false) || - !log_flag_video(output, __FUNCTION__)) + if (!log_flag_encoded(output, __FUNCTION__, false) || !log_flag_video(output, __FUNCTION__)) return; if (encoder && encoder->info.type != OBS_ENCODER_VIDEO) { blog(LOG_WARNING, "obs_output_set_video_encoder: " @@ -1074,8 +1025,7 @@ void obs_output_set_video_encoder2(obs_output_t *output, obs_encoder_t *encoder, if (idx == 0) { /* set the preferred resolution on the encoder */ if (output->scaled_width && output->scaled_height) - obs_encoder_set_scaled_size(output->video_encoders[idx], - output->scaled_width, + obs_encoder_set_scaled_size(output->video_encoders[idx], output->scaled_width, output->scaled_height); } } @@ -1088,13 +1038,11 @@ void obs_output_set_video_encoder(obs_output_t *output, obs_encoder_t *encoder) obs_output_set_video_encoder2(output, encoder, 0); } -void obs_output_set_audio_encoder(obs_output_t *output, obs_encoder_t *encoder, - size_t idx) +void obs_output_set_audio_encoder(obs_output_t *output, obs_encoder_t *encoder, size_t idx) { if (!obs_output_valid(output, "obs_output_set_audio_encoder")) return; - if (!log_flag_encoded(output, __FUNCTION__, false) || - !log_flag_audio(output, __FUNCTION__)) + if (!log_flag_encoded(output, __FUNCTION__, false) || !log_flag_audio(output, __FUNCTION__)) return; if (encoder && encoder->info.type != OBS_ENCODER_AUDIO) { blog(LOG_WARNING, "obs_output_set_audio_encoder: " @@ -1129,8 +1077,7 @@ void obs_output_set_audio_encoder(obs_output_t *output, obs_encoder_t *encoder, obs_encoder_add_output(output->audio_encoders[idx], output); } -obs_encoder_t *obs_output_get_video_encoder2(const obs_output_t *output, - size_t idx) +obs_encoder_t *obs_output_get_video_encoder2(const obs_output_t *output, size_t idx) { if (!obs_output_valid(output, "obs_output_get_video_encoder2")) return NULL; @@ -1153,8 +1100,7 @@ obs_encoder_t *obs_output_get_video_encoder(const obs_output_t *output) return NULL; } -obs_encoder_t *obs_output_get_audio_encoder(const obs_output_t *output, - size_t idx) +obs_encoder_t *obs_output_get_audio_encoder(const obs_output_t *output, size_t idx) { if (!obs_output_valid(output, "obs_output_get_audio_encoder")) return NULL; @@ -1169,8 +1115,7 @@ void obs_output_set_service(obs_output_t *output, obs_service_t *service) { if (!obs_output_valid(output, "obs_output_set_service")) return; - if (!log_flag_service(output, __FUNCTION__) || active(output) || - !service || service->active) + if (!log_flag_service(output, __FUNCTION__) || active(output) || !service || service->active) return; if (service->output) @@ -1182,13 +1127,10 @@ void obs_output_set_service(obs_output_t *output, obs_service_t *service) obs_service_t *obs_output_get_service(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_service") - ? output->service - : NULL; + return obs_output_valid(output, "obs_output_get_service") ? output->service : NULL; } -void obs_output_set_reconnect_settings(obs_output_t *output, int retry_count, - int retry_sec) +void obs_output_set_reconnect_settings(obs_output_t *output, int retry_count, int retry_sec) { if (!obs_output_valid(output, "obs_output_set_reconnect_settings")) return; @@ -1222,13 +1164,10 @@ int obs_output_get_frames_dropped(const obs_output_t *output) int obs_output_get_total_frames(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_total_frames") - ? output->total_frames - : 0; + return obs_output_valid(output, "obs_output_get_total_frames") ? output->total_frames : 0; } -void obs_output_set_preferred_size2(obs_output_t *output, uint32_t width, - uint32_t height, size_t idx) +void obs_output_set_preferred_size2(obs_output_t *output, uint32_t width, uint32_t height, size_t idx) { if (!obs_output_valid(output, "obs_output_set_preferred_size2")) return; @@ -1253,13 +1192,11 @@ void obs_output_set_preferred_size2(obs_output_t *output, uint32_t width, if (flag_encoded(output)) { if (output->video_encoders[idx]) - obs_encoder_set_scaled_size(output->video_encoders[idx], - width, height); + obs_encoder_set_scaled_size(output->video_encoders[idx], width, height); } } -void obs_output_set_preferred_size(obs_output_t *output, uint32_t width, - uint32_t height) +void obs_output_set_preferred_size(obs_output_t *output, uint32_t width, uint32_t height) { if (!obs_output_valid(output, "obs_output_set_preferred_size")) return; @@ -1280,14 +1217,11 @@ uint32_t obs_output_get_width2(const obs_output_t *output, size_t idx) if (flag_encoded(output)) { if (output->video_encoders[idx]) - return obs_encoder_get_width( - output->video_encoders[idx]); + return obs_encoder_get_width(output->video_encoders[idx]); else return 0; } else - return output->scaled_width != 0 - ? output->scaled_width - : video_output_get_width(output->video); + return output->scaled_width != 0 ? output->scaled_width : video_output_get_width(output->video); } uint32_t obs_output_get_width(const obs_output_t *output) @@ -1311,14 +1245,11 @@ uint32_t obs_output_get_height2(const obs_output_t *output, size_t idx) if (flag_encoded(output)) { if (output->video_encoders[idx]) - return obs_encoder_get_height( - output->video_encoders[idx]); + return obs_encoder_get_height(output->video_encoders[idx]); else return 0; } else - return output->scaled_height != 0 - ? output->scaled_height - : video_output_get_height(output->video); + return output->scaled_height != 0 ? output->scaled_height : video_output_get_height(output->video); } uint32_t obs_output_get_height(const obs_output_t *output) @@ -1331,30 +1262,26 @@ uint32_t obs_output_get_height(const obs_output_t *output) return obs_output_get_height2(output, 0); } -void obs_output_set_video_conversion(obs_output_t *output, - const struct video_scale_info *conversion) +void obs_output_set_video_conversion(obs_output_t *output, const struct video_scale_info *conversion) { if (!obs_output_valid(output, "obs_output_set_video_conversion")) return; if (!obs_ptr_valid(conversion, "obs_output_set_video_conversion")) return; - if (log_flag_encoded(output, __FUNCTION__, true) || - !log_flag_video(output, __FUNCTION__)) + if (log_flag_encoded(output, __FUNCTION__, true) || !log_flag_video(output, __FUNCTION__)) return; output->video_conversion = *conversion; output->video_conversion_set = true; } -void obs_output_set_audio_conversion( - obs_output_t *output, const struct audio_convert_info *conversion) +void obs_output_set_audio_conversion(obs_output_t *output, const struct audio_convert_info *conversion) { if (!obs_output_valid(output, "obs_output_set_audio_conversion")) return; if (!obs_ptr_valid(conversion, "obs_output_set_audio_conversion")) return; - if (log_flag_encoded(output, __FUNCTION__, true) || - !log_flag_audio(output, __FUNCTION__)) + if (log_flag_encoded(output, __FUNCTION__, true) || !log_flag_audio(output, __FUNCTION__)) return; output->audio_conversion = *conversion; @@ -1409,31 +1336,25 @@ static inline bool has_scaling(const struct obs_output *output) uint32_t video_height = video_output_get_height(output->video); return output->scaled_width && output->scaled_height && - (video_width != output->scaled_width || - video_height != output->scaled_height); + (video_width != output->scaled_width || video_height != output->scaled_height); } -const struct video_scale_info * -obs_output_get_video_conversion(struct obs_output *output) +const struct video_scale_info *obs_output_get_video_conversion(struct obs_output *output) { - if (log_flag_encoded(output, __FUNCTION__, true) || - !log_flag_video(output, __FUNCTION__)) + if (log_flag_encoded(output, __FUNCTION__, true) || !log_flag_video(output, __FUNCTION__)) return NULL; if (output->video_conversion_set) { if (!output->video_conversion.width) - output->video_conversion.width = - obs_output_get_width(output); + output->video_conversion.width = obs_output_get_width(output); if (!output->video_conversion.height) - output->video_conversion.height = - obs_output_get_height(output); + output->video_conversion.height = obs_output_get_height(output); return &output->video_conversion; } else if (has_scaling(output)) { - const struct video_output_info *info = - video_output_get_info(output->video); + const struct video_output_info *info = video_output_get_info(output->video); output->video_conversion.format = info->format; output->video_conversion.colorspace = VIDEO_CS_DEFAULT; @@ -1446,14 +1367,12 @@ obs_output_get_video_conversion(struct obs_output *output) return NULL; } -static inline struct audio_convert_info * -get_audio_conversion(struct obs_output *output) +static inline struct audio_convert_info *get_audio_conversion(struct obs_output *output) { return output->audio_conversion_set ? &output->audio_conversion : NULL; } -static size_t get_encoder_index(const struct obs_output *output, - struct encoder_packet *pkt) +static size_t get_encoder_index(const struct obs_output *output, struct encoder_packet *pkt) { if (pkt->type == OBS_ENCODER_VIDEO) { for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { @@ -1475,8 +1394,7 @@ static size_t get_encoder_index(const struct obs_output *output, return 0; } -static inline void check_received(struct obs_output *output, - struct encoder_packet *out) +static inline void check_received(struct obs_output *output, struct encoder_packet *out) { if (out->type == OBS_ENCODER_VIDEO) { if (!output->received_video[out->track_idx]) @@ -1487,10 +1405,8 @@ static inline void check_received(struct obs_output *output, } } -static inline void -apply_interleaved_packet_offset(struct obs_output *output, - struct encoder_packet *out, - struct encoder_packet_time *packet_time) +static inline void apply_interleaved_packet_offset(struct obs_output *output, struct encoder_packet *out, + struct encoder_packet_time *packet_time) { int64_t offset; @@ -1498,9 +1414,8 @@ apply_interleaved_packet_offset(struct obs_output *output, * may not currently be at 0 when we get data. so, we store the * current dts as offset and subtract that value from the dts/pts * of the output packet. */ - offset = (out->type == OBS_ENCODER_VIDEO) - ? output->video_offsets[out->track_idx] - : output->audio_offsets[out->track_idx]; + offset = (out->type == OBS_ENCODER_VIDEO) ? output->video_offsets[out->track_idx] + : output->audio_offsets[out->track_idx]; out->dts -= offset; out->pts -= offset; @@ -1516,24 +1431,18 @@ apply_interleaved_packet_offset(struct obs_output *output, out->dts_usec = packet_dts_usec(out); } -static inline bool has_higher_opposing_ts(struct obs_output *output, - struct encoder_packet *packet) +static inline bool has_higher_opposing_ts(struct obs_output *output, struct encoder_packet *packet) { bool has_higher = true; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - if (!output->video_encoders[i] || - (packet->type == OBS_ENCODER_VIDEO && - i == packet->track_idx)) + if (!output->video_encoders[i] || (packet->type == OBS_ENCODER_VIDEO && i == packet->track_idx)) continue; - has_higher = has_higher && - output->highest_video_ts[i] > packet->dts_usec; + has_higher = has_higher && output->highest_video_ts[i] > packet->dts_usec; } - return packet->type == OBS_ENCODER_AUDIO - ? has_higher - : (has_higher && - output->highest_audio_ts > packet->dts_usec); + return packet->type == OBS_ENCODER_AUDIO ? has_higher + : (has_higher && output->highest_audio_ts > packet->dts_usec); } static size_t extract_buffer_from_sei(sei_t *sei, uint8_t **data_out) @@ -1583,12 +1492,9 @@ static bool add_caption(struct obs_output *output, struct encoder_packet *out) if (out->priority > 1) return false; - struct caption_track_data *ctrack = - output->caption_tracks[out->track_idx]; + struct caption_track_data *ctrack = output->caption_tracks[out->track_idx]; if (!ctrack) { - blog(LOG_DEBUG, - "Caption track for index: %lu has not been initialized", - out->track_idx); + blog(LOG_DEBUG, "Caption track for index: %lu has not been initialized", out->track_idx); return false; } @@ -1605,10 +1511,9 @@ static bool add_caption(struct obs_output *output, struct encoder_packet *out) } else { /* We shouldn't ever see this unless we start getting * packets without annex-b start codes. */ - blog(LOG_DEBUG, - "Annex-B start code not found. We may not " - "generate a valid HEVC NAL unit header " - "for our caption"); + blog(LOG_DEBUG, "Annex-B start code not found. We may not " + "generate a valid HEVC NAL unit header " + "for our caption"); return false; } /* We will use the same 2 byte NAL unit header for the CC SEI, @@ -1630,8 +1535,7 @@ static bool add_caption(struct obs_output *output, struct encoder_packet *out) void *caption_buf = bzalloc(3 * sizeof(uint8_t)); while (ctrack->caption_data.size > 0) { - deque_pop_front(&ctrack->caption_data, caption_buf, - 3 * sizeof(uint8_t)); + deque_pop_front(&ctrack->caption_data, caption_buf, 3 * sizeof(uint8_t)); if ((((uint8_t *)caption_buf)[0] & 0x3) != 0) { // only send cea 608 @@ -1655,18 +1559,13 @@ static bool add_caption(struct obs_output *output, struct encoder_packet *out) continue; } - cea708_add_cc_data(&cea708, 1, - ((uint8_t *)caption_buf)[0] & 0x3, - captionData); + cea708_add_cc_data(&cea708, 1, ((uint8_t *)caption_buf)[0] & 0x3, captionData); } bfree(caption_buf); - sei_message_t *msg = - sei_message_new(sei_type_user_data_registered_itu_t_t35, - 0, CEA608_MAX_SIZE); - msg->size = cea708_render(&cea708, sei_message_data(msg), - sei_message_size(msg)); + sei_message_t *msg = sei_message_new(sei_type_user_data_registered_itu_t_t35, 0, CEA608_MAX_SIZE); + msg->size = cea708_render(&cea708, sei_message_data(msg), sei_message_size(msg)); sei_message_append(&sei, msg); } else if (ctrack->caption_head) { caption_frame_t cf; @@ -1714,8 +1613,7 @@ static bool add_caption(struct obs_output *output, struct encoder_packet *out) /* The first bit is always 0, so we just need to * save the last bit off the original header and * add the SEI NAL type. */ - uint8_t first_byte = (prefix_sei_nal_type << 1) | - (0x01 & hevc_nal_header[0]); + uint8_t first_byte = (prefix_sei_nal_type << 1) | (0x01 & hevc_nal_header[0]); hevc_nal_header[0] = first_byte; /* The HEVC NAL unit header is 2 byte instead of * one, otherwise everything else is the @@ -1727,11 +1625,9 @@ static bool add_caption(struct obs_output *output, struct encoder_packet *out) uint8_t *obu_buffer = NULL; size_t obu_buffer_size = 0; size = extract_buffer_from_sei(&sei, &data); - metadata_obu(data, size, &obu_buffer, &obu_buffer_size, - METADATA_TYPE_ITUT_T35); + metadata_obu(data, size, &obu_buffer, &obu_buffer_size, METADATA_TYPE_ITUT_T35); if (obu_buffer) { - da_push_back_array(out_data, obu_buffer, - obu_buffer_size); + da_push_back_array(out_data, obu_buffer, obu_buffer_size); bfree(obu_buffer); } } @@ -1765,33 +1661,25 @@ static inline void send_interleaved(struct obs_output *output) if (out.type == OBS_ENCODER_VIDEO) { output->total_frames++; - pthread_mutex_lock( - &output->caption_tracks[out.track_idx]->caption_mutex); + pthread_mutex_lock(&output->caption_tracks[out.track_idx]->caption_mutex); - double frame_timestamp = - (out.pts * out.timebase_num) / (double)out.timebase_den; + double frame_timestamp = (out.pts * out.timebase_num) / (double)out.timebase_den; - struct caption_track_data *ctrack = - output->caption_tracks[out.track_idx]; + struct caption_track_data *ctrack = output->caption_tracks[out.track_idx]; - if (ctrack->caption_head && - ctrack->caption_timestamp <= frame_timestamp) { - blog(LOG_DEBUG, "Sending caption: %f \"%s\"", - frame_timestamp, &ctrack->caption_head->text[0]); + if (ctrack->caption_head && ctrack->caption_timestamp <= frame_timestamp) { + blog(LOG_DEBUG, "Sending caption: %f \"%s\"", frame_timestamp, &ctrack->caption_head->text[0]); - double display_duration = - ctrack->caption_head->display_duration; + double display_duration = ctrack->caption_head->display_duration; if (add_caption(output, &out)) { - ctrack->caption_timestamp = - frame_timestamp + display_duration; + ctrack->caption_timestamp = frame_timestamp + display_duration; } } if (ctrack->caption_data.size > 0) { if (ctrack->last_caption_timestamp < frame_timestamp) { - ctrack->last_caption_timestamp = - frame_timestamp; + ctrack->last_caption_timestamp = frame_timestamp; add_caption(output, &out); } } @@ -1802,32 +1690,25 @@ static inline void send_interleaved(struct obs_output *output) * Packet timing currently applies to video only. */ struct encoder_packet_time *ept = NULL; - size_t num_ept = - output->encoder_packet_times[out.track_idx].num; + size_t num_ept = output->encoder_packet_times[out.track_idx].num; if (num_ept) { for (size_t i = 0; i < num_ept; i++) { - ept = &output->encoder_packet_times[out.track_idx] - .array[i]; + ept = &output->encoder_packet_times[out.track_idx].array[i]; if (ept->pts == out.pts) { ept_local = *ept; - da_erase(output->encoder_packet_times - [out.track_idx], - i); + da_erase(output->encoder_packet_times[out.track_idx], i); found_ept = true; break; } } if (found_ept == false) { - blog(LOG_DEBUG, - "%s: Track %lu encoder packet timing for PTS%" PRId64 - " not found.", + blog(LOG_DEBUG, "%s: Track %lu encoder packet timing for PTS%" PRId64 " not found.", __FUNCTION__, out.track_idx, out.pts); } } else { // encoder_packet_times should not be empty; log if so. - blog(LOG_DEBUG, - "%s: Track %lu encoder packet timing array empty.", - __FUNCTION__, out.track_idx); + blog(LOG_DEBUG, "%s: Track %lu encoder packet timing array empty.", __FUNCTION__, + out.track_idx); } } @@ -1837,12 +1718,10 @@ static inline void send_interleaved(struct obs_output *output) */ pthread_mutex_lock(&output->pkt_callbacks_mutex); for (size_t i = 0; i < output->pkt_callbacks.num; ++i) { - struct packet_callback *const callback = - &output->pkt_callbacks.array[i]; + struct packet_callback *const callback = &output->pkt_callbacks.array[i]; // Packet interleave request timestamp ept_local.pir = os_gettime_ns(); - callback->packet_cb(output, &out, found_ept ? &ept_local : NULL, - callback->param); + callback->packet_cb(output, &out, found_ept ? &ept_local : NULL, callback->param); } pthread_mutex_unlock(&output->pkt_callbacks_mutex); @@ -1850,39 +1729,31 @@ static inline void send_interleaved(struct obs_output *output) obs_encoder_packet_release(&out); } -static inline void set_higher_ts(struct obs_output *output, - struct encoder_packet *packet) +static inline void set_higher_ts(struct obs_output *output, struct encoder_packet *packet) { if (packet->type == OBS_ENCODER_VIDEO) { - if (output->highest_video_ts[packet->track_idx] < - packet->dts_usec) - output->highest_video_ts[packet->track_idx] = - packet->dts_usec; + if (output->highest_video_ts[packet->track_idx] < packet->dts_usec) + output->highest_video_ts[packet->track_idx] = packet->dts_usec; } else { if (output->highest_audio_ts < packet->dts_usec) output->highest_audio_ts = packet->dts_usec; } } -static inline struct encoder_packet * -find_first_packet_type(struct obs_output *output, enum obs_encoder_type type, - size_t audio_idx); -static int find_first_packet_type_idx(struct obs_output *output, - enum obs_encoder_type type, - size_t audio_idx); +static inline struct encoder_packet *find_first_packet_type(struct obs_output *output, enum obs_encoder_type type, + size_t audio_idx); +static int find_first_packet_type_idx(struct obs_output *output, enum obs_encoder_type type, size_t audio_idx); /* gets the point where audio and video are closest together */ static size_t get_interleaved_start_idx(struct obs_output *output) { int64_t closest_diff = 0x7FFFFFFFFFFFFFFFLL; - struct encoder_packet *first_video = - find_first_packet_type(output, OBS_ENCODER_VIDEO, 0); + struct encoder_packet *first_video = find_first_packet_type(output, OBS_ENCODER_VIDEO, 0); size_t video_idx = DARRAY_INVALID; size_t idx = 0; for (size_t i = 0; i < output->interleaved_packets.num; i++) { - struct encoder_packet *packet = - &output->interleaved_packets.array[i]; + struct encoder_packet *packet = &output->interleaved_packets.array[i]; int64_t diff; if (packet->type != OBS_ENCODER_AUDIO) { @@ -1903,8 +1774,7 @@ static size_t get_interleaved_start_idx(struct obs_output *output) static int64_t get_encoder_duration(struct obs_encoder *encoder) { - return (encoder->timebase_num * 1000000LL / encoder->timebase_den) * - encoder->framesize; + return (encoder->timebase_num * 1000000LL / encoder->timebase_den) * encoder->framesize; } static int prune_premature_packets(struct obs_output *output) @@ -1934,8 +1804,7 @@ static int prune_premature_packets(struct obs_output *output) continue; audio_encoders++; - audio_idx = find_first_packet_type_idx(output, - OBS_ENCODER_AUDIO, i); + audio_idx = find_first_packet_type_idx(output, OBS_ENCODER_AUDIO, i); if (audio_idx == -1) { output->received_audio = false; return -1; @@ -1949,8 +1818,7 @@ static int prune_premature_packets(struct obs_output *output) if (diff > max_diff) max_diff = diff; - audio_duration_usec = - get_encoder_duration(output->audio_encoders[i]); + audio_duration_usec = get_encoder_duration(output->audio_encoders[i]); if (audio_duration_usec > max_audio_duration_usec) max_audio_duration_usec = audio_duration_usec; } @@ -1971,11 +1839,9 @@ static int prune_premature_packets(struct obs_output *output) static void discard_to_idx(struct obs_output *output, size_t idx) { for (size_t i = 0; i < idx; i++) { - struct encoder_packet *packet = - &output->interleaved_packets.array[i]; + struct encoder_packet *packet = &output->interleaved_packets.array[i]; if (packet->type == OBS_ENCODER_VIDEO) { - da_pop_front( - output->encoder_packet_times[packet->track_idx]); + da_pop_front(output->encoder_packet_times[packet->track_idx]); } obs_encoder_packet_release(packet); } @@ -1993,11 +1859,9 @@ static bool prune_interleaved_packets(struct obs_output *output) #if DEBUG_STARTING_PACKETS == 1 blog(LOG_DEBUG, "--------- Pruning! %d ---------", prune_start); for (size_t i = 0; i < output->interleaved_packets.num; i++) { - struct encoder_packet *packet = - &output->interleaved_packets.array[i]; + struct encoder_packet *packet = &output->interleaved_packets.array[i]; blog(LOG_DEBUG, "packet: %s %d, ts: %lld, pruned = %s", - packet->type == OBS_ENCODER_AUDIO ? "audio" : "video", - (int)packet->track_idx, packet->dts_usec, + packet->type == OBS_ENCODER_AUDIO ? "audio" : "video", (int)packet->track_idx, packet->dts_usec, (int)i < prune_start ? "true" : "false"); } #endif @@ -2016,12 +1880,10 @@ static bool prune_interleaved_packets(struct obs_output *output) return true; } -static int find_first_packet_type_idx(struct obs_output *output, - enum obs_encoder_type type, size_t idx) +static int find_first_packet_type_idx(struct obs_output *output, enum obs_encoder_type type, size_t idx) { for (size_t i = 0; i < output->interleaved_packets.num; i++) { - struct encoder_packet *packet = - &output->interleaved_packets.array[i]; + struct encoder_packet *packet = &output->interleaved_packets.array[i]; if (packet->type == type && packet->track_idx == idx) return (int)i; @@ -2030,12 +1892,10 @@ static int find_first_packet_type_idx(struct obs_output *output, return -1; } -static int find_last_packet_type_idx(struct obs_output *output, - enum obs_encoder_type type, size_t idx) +static int find_last_packet_type_idx(struct obs_output *output, enum obs_encoder_type type, size_t idx) { for (size_t i = output->interleaved_packets.num; i > 0; i--) { - struct encoder_packet *packet = - &output->interleaved_packets.array[i - 1]; + struct encoder_packet *packet = &output->interleaved_packets.array[i - 1]; if (packet->type == type && packet->track_idx == idx) return (int)(i - 1); @@ -2044,31 +1904,27 @@ static int find_last_packet_type_idx(struct obs_output *output, return -1; } -static inline struct encoder_packet * -find_first_packet_type(struct obs_output *output, enum obs_encoder_type type, - size_t audio_idx) +static inline struct encoder_packet *find_first_packet_type(struct obs_output *output, enum obs_encoder_type type, + size_t audio_idx) { int idx = find_first_packet_type_idx(output, type, audio_idx); return (idx != -1) ? &output->interleaved_packets.array[idx] : NULL; } -static inline struct encoder_packet * -find_last_packet_type(struct obs_output *output, enum obs_encoder_type type, - size_t audio_idx) +static inline struct encoder_packet *find_last_packet_type(struct obs_output *output, enum obs_encoder_type type, + size_t audio_idx) { int idx = find_last_packet_type_idx(output, type, audio_idx); return (idx != -1) ? &output->interleaved_packets.array[idx] : NULL; } -static bool get_audio_and_video_packets(struct obs_output *output, - struct encoder_packet **video, +static bool get_audio_and_video_packets(struct obs_output *output, struct encoder_packet **video, struct encoder_packet **audio) { bool found_video = false; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (output->video_encoders[i]) { - video[i] = find_first_packet_type(output, - OBS_ENCODER_VIDEO, i); + video[i] = find_first_packet_type(output, OBS_ENCODER_VIDEO, i); if (!video[i]) { output->received_video[i] = false; return false; @@ -2080,8 +1936,7 @@ static bool get_audio_and_video_packets(struct obs_output *output, for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { if (output->audio_encoders[i]) { - audio[i] = find_first_packet_type(output, - OBS_ENCODER_AUDIO, i); + audio[i] = find_first_packet_type(output, OBS_ENCODER_AUDIO, i); if (!audio[i]) { output->received_audio = false; return false; @@ -2111,16 +1966,14 @@ static bool initialize_interleaved_packets(struct obs_output *output) for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { if (output->audio_encoders[i]) { - last_audio[i] = find_last_packet_type( - output, OBS_ENCODER_AUDIO, i); + last_audio[i] = find_last_packet_type(output, OBS_ENCODER_AUDIO, i); } } /* ensure that there is audio past the first video packet */ for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { if (output->audio_encoders[i]) { - if (last_audio[i]->dts_usec < - video[first_video_idx]->dts_usec) { + if (last_audio[i]->dts_usec < video[first_video_idx]->dts_usec) { output->received_audio = false; return false; } @@ -2162,16 +2015,14 @@ static bool initialize_interleaved_packets(struct obs_output *output) /* apply new offsets to all existing packet DTS/PTS values */ for (size_t i = 0; i < output->interleaved_packets.num; i++) { - struct encoder_packet *packet = - &output->interleaved_packets.array[i]; + struct encoder_packet *packet = &output->interleaved_packets.array[i]; apply_interleaved_packet_offset(output, packet, NULL); } return true; } -static inline void insert_interleaved_packet(struct obs_output *output, - struct encoder_packet *out) +static inline void insert_interleaved_packet(struct obs_output *output, struct encoder_packet *out) { size_t idx; for (idx = 0; idx < output->interleaved_packets.num; idx++) { @@ -2181,14 +2032,11 @@ static inline void insert_interleaved_packet(struct obs_output *output, // sort video packets with same DTS by track index, // to prevent the pruning logic from removing additional // video tracks - if (out->dts_usec == cur_packet->dts_usec && - out->type == OBS_ENCODER_VIDEO && - cur_packet->type == OBS_ENCODER_VIDEO && - out->track_idx > cur_packet->track_idx) + if (out->dts_usec == cur_packet->dts_usec && out->type == OBS_ENCODER_VIDEO && + cur_packet->type == OBS_ENCODER_VIDEO && out->track_idx > cur_packet->track_idx) continue; - if (out->dts_usec == cur_packet->dts_usec && - out->type == OBS_ENCODER_VIDEO) { + if (out->dts_usec == cur_packet->dts_usec && out->type == OBS_ENCODER_VIDEO) { break; } else if (out->dts_usec < cur_packet->dts_usec) { break; @@ -2203,8 +2051,7 @@ static void resort_interleaved_packets(struct obs_output *output) DARRAY(struct encoder_packet) old_array; old_array.da = output->interleaved_packets.da; - memset(&output->interleaved_packets, 0, - sizeof(output->interleaved_packets)); + memset(&output->interleaved_packets, 0, sizeof(output->interleaved_packets)); for (size_t i = 0; i < old_array.num; i++) { set_higher_ts(output, &old_array.array[i]); @@ -2215,14 +2062,12 @@ static void resort_interleaved_packets(struct obs_output *output) da_free(old_array); } -static void discard_unused_audio_packets(struct obs_output *output, - int64_t dts_usec) +static void discard_unused_audio_packets(struct obs_output *output, int64_t dts_usec) { size_t idx = 0; for (; idx < output->interleaved_packets.num; idx++) { - struct encoder_packet *p = - &output->interleaved_packets.array[idx]; + struct encoder_packet *p = &output->interleaved_packets.array[idx]; if (p->dts_usec >= dts_usec) break; @@ -2234,8 +2079,7 @@ static void discard_unused_audio_packets(struct obs_output *output, static bool purge_encoder_group_keyframe_data(obs_output_t *output, size_t idx) { - struct keyframe_group_data *data = - &output->keyframe_group_tracking.array[idx]; + struct keyframe_group_data *data = &output->keyframe_group_tracking.array[idx]; uint32_t modified_count = 0; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (data->seen_on_track[i] != KEYFRAME_TRACK_STATUS_NOT_SEEN) @@ -2251,61 +2095,50 @@ static bool purge_encoder_group_keyframe_data(obs_output_t *output, size_t idx) /* Check whether keyframes are emitted from all grouped encoders, and log * if keyframes haven't been emitted from all grouped encoders. */ -static void -check_encoder_group_keyframe_alignment(obs_output_t *output, - struct encoder_packet *packet) +static void check_encoder_group_keyframe_alignment(obs_output_t *output, struct encoder_packet *packet) { size_t idx = 0; struct keyframe_group_data insert_data = {0}; - if (!packet->keyframe || packet->type != OBS_ENCODER_VIDEO || - !packet->encoder->encoder_group) + if (!packet->keyframe || packet->type != OBS_ENCODER_VIDEO || !packet->encoder->encoder_group) return; for (; idx < output->keyframe_group_tracking.num;) { - struct keyframe_group_data *data = - &output->keyframe_group_tracking.array[idx]; + struct keyframe_group_data *data = &output->keyframe_group_tracking.array[idx]; if (data->pts > packet->pts) break; - if (data->group_id != - (uintptr_t)packet->encoder->encoder_group) { + if (data->group_id != (uintptr_t)packet->encoder->encoder_group) { idx += 1; continue; } if (data->pts < packet->pts) { - if (data->seen_on_track[packet->track_idx] == - KEYFRAME_TRACK_STATUS_NOT_SEEN) { + if (data->seen_on_track[packet->track_idx] == KEYFRAME_TRACK_STATUS_NOT_SEEN) { blog(LOG_WARNING, "obs-output '%s': Missing keyframe with pts %" PRIi64 " for encoder '%s' (track: %zu)", - obs_output_get_name(output), data->pts, - obs_encoder_get_name(packet->encoder), + obs_output_get_name(output), data->pts, obs_encoder_get_name(packet->encoder), packet->track_idx); } - data->seen_on_track[packet->track_idx] = - KEYFRAME_TRACK_STATUS_SKIPPED; + data->seen_on_track[packet->track_idx] = KEYFRAME_TRACK_STATUS_SKIPPED; if (!purge_encoder_group_keyframe_data(output, idx)) idx += 1; continue; } - data->seen_on_track[packet->track_idx] = - KEYFRAME_TRACK_STATUS_SEEN; + data->seen_on_track[packet->track_idx] = KEYFRAME_TRACK_STATUS_SEEN; purge_encoder_group_keyframe_data(output, idx); return; } insert_data.group_id = (uintptr_t)packet->encoder->encoder_group; insert_data.pts = packet->pts; - insert_data.seen_on_track[packet->track_idx] = - KEYFRAME_TRACK_STATUS_SEEN; + insert_data.seen_on_track[packet->track_idx] = KEYFRAME_TRACK_STATUS_SEEN; pthread_mutex_lock(&packet->encoder->encoder_group->mutex); - insert_data.required_tracks = - packet->encoder->encoder_group->num_encoders_started; + insert_data.required_tracks = packet->encoder->encoder_group->num_encoders_started; pthread_mutex_unlock(&packet->encoder->encoder_group->mutex); da_insert(output->keyframe_group_tracking, idx, &insert_data); @@ -2314,16 +2147,13 @@ check_encoder_group_keyframe_alignment(obs_output_t *output, static void apply_ept_offsets(struct obs_output *output) { for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - for (size_t j = 0; j < output->encoder_packet_times[i].num; - j++) { - output->encoder_packet_times[i].array[j].pts -= - output->video_offsets[i]; + for (size_t j = 0; j < output->encoder_packet_times[i].num; j++) { + output->encoder_packet_times[i].array[j].pts -= output->video_offsets[i]; } } } -static void interleave_packets(void *data, struct encoder_packet *packet, - struct encoder_packet_time *packet_time) +static void interleave_packets(void *data, struct encoder_packet *packet, struct encoder_packet_time *packet_time) { struct obs_output *output = data; struct encoder_packet out; @@ -2339,8 +2169,7 @@ static void interleave_packets(void *data, struct encoder_packet *packet, pthread_mutex_lock(&output->interleaved_mutex); /* if first video frame is not a keyframe, discard until received */ - if (packet->type == OBS_ENCODER_VIDEO && - !output->received_video[packet->track_idx] && !packet->keyframe) { + if (packet->type == OBS_ENCODER_VIDEO && !output->received_video[packet->track_idx] && !packet->keyframe) { discard_unused_audio_packets(output, packet->dts_usec); pthread_mutex_unlock(&output->interleaved_mutex); @@ -2352,8 +2181,7 @@ static void interleave_packets(void *data, struct encoder_packet *packet, received_video = true; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (output->video_encoders[i]) - received_video = received_video && - output->received_video[i]; + received_video = received_video && output->received_video[i]; } check_encoder_group_keyframe_alignment(output, packet); @@ -2366,14 +2194,12 @@ static void interleave_packets(void *data, struct encoder_packet *packet, obs_encoder_packet_create_instance(&out, packet); if (packet_time) { - output_packet_time = da_push_back_new( - output->encoder_packet_times[packet->track_idx]); + output_packet_time = da_push_back_new(output->encoder_packet_times[packet->track_idx]); *output_packet_time = *packet_time; } if (was_started) - apply_interleaved_packet_offset(output, &out, - output_packet_time); + apply_interleaved_packet_offset(output, &out, output_packet_time); else check_received(output, packet); @@ -2382,8 +2208,7 @@ static void interleave_packets(void *data, struct encoder_packet *packet, received_video = true; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (output->video_encoders[i]) - received_video = received_video && - output->received_video[i]; + received_video = received_video && output->received_video[i]; } /* when both video and audio have been received, we're ready @@ -2438,8 +2263,7 @@ static void default_raw_video_callback(void *param, struct video_data *frame) output->total_frames++; } -static bool prepare_audio(struct obs_output *output, - const struct audio_data *old, struct audio_data *new) +static bool prepare_audio(struct obs_output *output, const struct audio_data *old, struct audio_data *new) { if ((output->info.flags & OBS_OUTPUT_VIDEO) == 0) { *new = *old; @@ -2460,8 +2284,7 @@ static bool prepare_audio(struct obs_output *output, *new = *old; if (old->timestamp < output->video_start_ts) { - uint64_t duration = util_mul_div64(old->frames, 1000000000ULL, - output->sample_rate); + uint64_t duration = util_mul_div64(old->frames, 1000000000ULL, output->sample_rate); uint64_t end_ts = (old->timestamp + duration); uint64_t cutoff; @@ -2471,8 +2294,7 @@ static bool prepare_audio(struct obs_output *output, cutoff = output->video_start_ts - old->timestamp; new->timestamp += cutoff; - cutoff = util_mul_div64(cutoff, output->sample_rate, - 1000000000ULL); + cutoff = util_mul_div64(cutoff, output->sample_rate, 1000000000ULL); for (size_t i = 0; i < output->planes; i++) new->data[i] += output->audio_size *(uint32_t)cutoff; @@ -2482,8 +2304,7 @@ static bool prepare_audio(struct obs_output *output, return true; } -static void default_raw_audio_callback(void *param, size_t mix_idx, - struct audio_data *in) +static void default_raw_audio_callback(void *param, size_t mix_idx, struct audio_data *in) { struct obs_output *output = param; struct audio_data out; @@ -2505,23 +2326,19 @@ static void default_raw_audio_callback(void *param, size_t mix_idx, frame_size_bytes = AUDIO_OUTPUT_FRAMES * output->audio_size; for (size_t i = 0; i < output->planes; i++) - deque_push_back(&output->audio_buffer[mix_idx][i], out.data[i], - out.frames * output->audio_size); + deque_push_back(&output->audio_buffer[mix_idx][i], out.data[i], out.frames * output->audio_size); /* -------------- */ while (output->audio_buffer[mix_idx][0].size > frame_size_bytes) { for (size_t i = 0; i < output->planes; i++) { - deque_pop_front(&output->audio_buffer[mix_idx][i], - output->audio_data[i], - frame_size_bytes); + deque_pop_front(&output->audio_buffer[mix_idx][i], output->audio_data[i], frame_size_bytes); out.data[i] = (uint8_t *)output->audio_data[i]; } out.frames = AUDIO_OUTPUT_FRAMES; - out.timestamp = output->audio_start_ts + - audio_frames_to_ns(output->sample_rate, - output->total_audio_frames); + out.timestamp = + output->audio_start_ts + audio_frames_to_ns(output->sample_rate, output->total_audio_frames); pthread_mutex_lock(&output->pause.mutex); out.timestamp += output->pause.ts_offset; @@ -2530,31 +2347,26 @@ static void default_raw_audio_callback(void *param, size_t mix_idx, output->total_audio_frames += AUDIO_OUTPUT_FRAMES; if (output->info.raw_audio2) - output->info.raw_audio2(output->context.data, mix_idx, - &out); + output->info.raw_audio2(output->context.data, mix_idx, &out); else output->info.raw_audio(output->context.data, &out); } } -static inline void start_audio_encoders(struct obs_output *output, - encoded_callback_t encoded_callback) +static inline void start_audio_encoders(struct obs_output *output, encoded_callback_t encoded_callback) { for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { if (output->audio_encoders[i]) { - obs_encoder_start(output->audio_encoders[i], - encoded_callback, output); + obs_encoder_start(output->audio_encoders[i], encoded_callback, output); } } } -static inline void start_video_encoders(struct obs_output *output, - encoded_callback_t encoded_callback) +static inline void start_video_encoders(struct obs_output *output, encoded_callback_t encoded_callback) { for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (output->video_encoders[i]) { - obs_encoder_start(output->video_encoders[i], - encoded_callback, output); + obs_encoder_start(output->video_encoders[i], encoded_callback, output); } } } @@ -2564,15 +2376,12 @@ static inline void start_raw_audio(obs_output_t *output) if (output->info.raw_audio2) { for (int idx = 0; idx < MAX_AUDIO_MIXES; idx++) { if ((output->mixer_mask & ((size_t)1 << idx)) != 0) { - audio_output_connect( - output->audio, idx, - get_audio_conversion(output), - default_raw_audio_callback, output); + audio_output_connect(output->audio, idx, get_audio_conversion(output), + default_raw_audio_callback, output); } } } else { - audio_output_connect(output->audio, get_first_mixer(output), - get_audio_conversion(output), + audio_output_connect(output->audio, get_first_mixer(output), get_audio_conversion(output), default_raw_audio_callback, output); } } @@ -2613,13 +2422,10 @@ static void hook_data_capture(struct obs_output *output) reset_packet_data(output); pthread_mutex_unlock(&output->interleaved_mutex); - encoded_callback = (has_video && has_audio) - ? interleave_packets - : default_encoded_callback; + encoded_callback = (has_video && has_audio) ? interleave_packets : default_encoded_callback; if (output->delay_sec) { - output->active_delay_ns = - (uint64_t)output->delay_sec * 1000000000ULL; + output->active_delay_ns = (uint64_t)output->delay_sec * 1000000000ULL; output->delay_cur_flags = output->delay_flags; output->delay_callback = encoded_callback; encoded_callback = process_delay; @@ -2628,8 +2434,7 @@ static void hook_data_capture(struct obs_output *output) blog(LOG_INFO, "Output '%s': %" PRIu32 " second delay " "active, preserve on disconnect is %s", - output->context.name, output->delay_sec, - preserve_active(output) ? "on" : "off"); + output->context.name, output->delay_sec, preserve_active(output) ? "on" : "off"); } if (has_audio) @@ -2638,9 +2443,8 @@ static void hook_data_capture(struct obs_output *output) start_video_encoders(output, encoded_callback); } else { if (has_video) - start_raw_video(output->video, - obs_output_get_video_conversion(output), - 1, default_raw_video_callback, output); + start_raw_video(output->video, obs_output_get_video_conversion(output), 1, + default_raw_video_callback, output); if (has_audio) start_raw_audio(output); } @@ -2657,8 +2461,7 @@ static inline void signal_reconnect(struct obs_output *output) uint8_t stack[128]; calldata_init_fixed(¶ms, stack, sizeof(stack)); - calldata_set_int(¶ms, "timeout_sec", - output->reconnect_retry_cur_msec / 1000); + calldata_set_int(¶ms, "timeout_sec", output->reconnect_retry_cur_msec / 1000); calldata_set_ptr(¶ms, "output", output); signal_handler_signal(output->context.signals, "reconnect", ¶ms); } @@ -2673,8 +2476,7 @@ static inline void signal_stop(struct obs_output *output) struct calldata params; calldata_init(¶ms); - calldata_set_string(¶ms, "last_error", - obs_output_get_last_error(output)); + calldata_set_string(¶ms, "last_error", obs_output_get_last_error(output)); calldata_set_int(¶ms, "code", output->stop_code); calldata_set_ptr(¶ms, "output", output); @@ -2683,8 +2485,7 @@ static inline void signal_stop(struct obs_output *output) calldata_free(¶ms); } -bool obs_output_can_begin_data_capture(const obs_output_t *output, - uint32_t flags) +bool obs_output_can_begin_data_capture(const obs_output_t *output, uint32_t flags) { UNUSED_PARAMETER(flags); @@ -2708,8 +2509,7 @@ static inline bool initialize_audio_encoders(obs_output_t *output) obs_encoder_t *audio = output->audio_encoders[i]; if (audio && !obs_encoder_initialize(audio)) { - obs_output_set_last_error( - output, obs_encoder_get_last_error(audio)); + obs_output_set_last_error(output, obs_encoder_get_last_error(audio)); return false; } } @@ -2723,8 +2523,7 @@ static inline bool initialize_video_encoders(obs_output_t *output) obs_encoder_t *video = output->video_encoders[i]; if (video && !obs_encoder_initialize(video)) { - obs_output_set_last_error( - output, obs_encoder_get_last_error(video)); + obs_output_set_last_error(output, obs_encoder_get_last_error(video)); return false; } } @@ -2752,10 +2551,8 @@ static inline void pair_encoders(obs_output_t *output) pthread_mutex_lock(&audio->init_mutex); if (!audio->active && !audio->paired_encoders.num) { - obs_weak_encoder_t *weak_audio = - obs_encoder_get_weak_encoder(audio); - obs_weak_encoder_t *weak_video = - obs_encoder_get_weak_encoder(video); + obs_weak_encoder_t *weak_audio = obs_encoder_get_weak_encoder(audio); + obs_weak_encoder_t *weak_video = obs_encoder_get_weak_encoder(video); da_push_back(video->paired_encoders, &weak_audio); da_push_back(audio->paired_encoders, &weak_video); } @@ -2808,8 +2605,7 @@ static void reset_raw_output(obs_output_t *output) clear_raw_audio_buffers(output); if (output->audio) { - const struct audio_output_info *aoi = - audio_output_get_info(output->audio); + const struct audio_output_info *aoi = audio_output_get_info(output->audio); struct audio_convert_info conv = output->audio_conversion; struct audio_convert_info info = { aoi->samples_per_sec, @@ -2829,8 +2625,7 @@ static void reset_raw_output(obs_output_t *output) output->sample_rate = info.samples_per_sec; output->planes = get_audio_planes(info.format, info.speakers); output->total_audio_frames = 0; - output->audio_size = - get_audio_size(info.format, info.speakers, 1); + output->audio_size = get_audio_size(info.format, info.speakers, 1); } output->audio_start_ts = 0; @@ -2885,8 +2680,7 @@ bool obs_output_begin_data_capture(obs_output_t *output, uint32_t flags) return true; } -static inline void stop_audio_encoders(obs_output_t *output, - encoded_callback_t encoded_callback) +static inline void stop_audio_encoders(obs_output_t *output, encoded_callback_t encoded_callback) { for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { obs_encoder_t *audio = output->audio_encoders[i]; @@ -2895,8 +2689,7 @@ static inline void stop_audio_encoders(obs_output_t *output, } } -static inline void stop_video_encoders(obs_output_t *output, - encoded_callback_t encoded_callback) +static inline void stop_video_encoders(obs_output_t *output, encoded_callback_t encoded_callback) { for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { obs_encoder_t *video = output->video_encoders[i]; @@ -2910,14 +2703,11 @@ static inline void stop_raw_audio(obs_output_t *output) if (output->info.raw_audio2) { for (int idx = 0; idx < MAX_AUDIO_MIXES; idx++) { if ((output->mixer_mask & ((size_t)1 << idx)) != 0) { - audio_output_disconnect( - output->audio, idx, - default_raw_audio_callback, output); + audio_output_disconnect(output->audio, idx, default_raw_audio_callback, output); } } } else { - audio_output_disconnect(output->audio, get_first_mixer(output), - default_raw_audio_callback, output); + audio_output_disconnect(output->audio, get_first_mixer(output), default_raw_audio_callback, output); } } @@ -2932,9 +2722,7 @@ static void *end_data_capture_thread(void *data) if (output->active_delay_ns) encoded_callback = process_delay; else - encoded_callback = (has_video && has_audio) - ? interleave_packets - : default_encoded_callback; + encoded_callback = (has_video && has_audio) ? interleave_packets : default_encoded_callback; if (has_video) stop_video_encoders(output, encoded_callback); @@ -2942,8 +2730,7 @@ static void *end_data_capture_thread(void *data) stop_audio_encoders(output, encoded_callback); } else { if (has_video) - stop_raw_video(output->video, - default_raw_video_callback, output); + stop_raw_video(output->video, default_raw_video_callback, output); if (has_audio) stop_raw_audio(output); } @@ -2962,8 +2749,7 @@ static void *end_data_capture_thread(void *data) return NULL; } -static void obs_output_end_data_capture_internal(obs_output_t *output, - bool signal) +static void obs_output_end_data_capture_internal(obs_output_t *output, bool signal) { int ret; @@ -2999,8 +2785,7 @@ static void obs_output_end_data_capture_internal(obs_output_t *output, pthread_join(output->end_data_capture_thread, NULL); os_atomic_set_bool(&output->end_data_capture_thread_active, true); - ret = pthread_create(&output->end_data_capture_thread, NULL, - end_data_capture_thread, output); + ret = pthread_create(&output->end_data_capture_thread, NULL, end_data_capture_thread, output); if (ret != 0) { blog(LOG_WARNING, "Failed to create end_data_capture_thread " @@ -3026,8 +2811,7 @@ static void *reconnect_thread(void *param) output->reconnect_thread_active = true; - if (os_event_timedwait(output->reconnect_stop_event, - output->reconnect_retry_cur_msec) == ETIMEDOUT) + if (os_event_timedwait(output->reconnect_stop_event, output->reconnect_retry_cur_msec) == ETIMEDOUT) obs_output_actual_start(output); if (os_event_try(output->reconnect_stop_event) == EAGAIN) @@ -3043,15 +2827,13 @@ static void output_reconnect(struct obs_output *output) { int ret; - if (reconnecting(output) && - os_event_try(output->reconnect_stop_event) != EAGAIN) { + if (reconnecting(output) && os_event_try(output->reconnect_stop_event) != EAGAIN) { os_atomic_set_bool(&output->reconnecting, false); return; } if (!reconnecting(output)) { - output->reconnect_retry_cur_msec = - output->reconnect_retry_sec * 1000; + output->reconnect_retry_cur_msec = output->reconnect_retry_sec * 1000; output->reconnect_retries = 0; } @@ -3071,26 +2853,21 @@ static void output_reconnect(struct obs_output *output) if (output->reconnect_retries) { output->reconnect_retry_cur_msec = - (uint32_t)(output->reconnect_retry_cur_msec * - output->reconnect_retry_exp); - if (output->reconnect_retry_cur_msec > - RECONNECT_RETRY_MAX_MSEC) { - output->reconnect_retry_cur_msec = - RECONNECT_RETRY_MAX_MSEC; + (uint32_t)(output->reconnect_retry_cur_msec * output->reconnect_retry_exp); + if (output->reconnect_retry_cur_msec > RECONNECT_RETRY_MAX_MSEC) { + output->reconnect_retry_cur_msec = RECONNECT_RETRY_MAX_MSEC; } } output->reconnect_retries++; output->stop_code = OBS_OUTPUT_DISCONNECTED; - ret = pthread_create(&output->reconnect_thread, NULL, &reconnect_thread, - output); + ret = pthread_create(&output->reconnect_thread, NULL, &reconnect_thread, output); if (ret < 0) { blog(LOG_WARNING, "Failed to create reconnect thread"); os_atomic_set_bool(&output->reconnecting, false); } else { - blog(LOG_INFO, "Output '%s': Reconnecting in %.02f seconds..", - output->context.name, + blog(LOG_INFO, "Output '%s': Reconnecting in %.02f seconds..", output->context.name, (float)(output->reconnect_retry_cur_msec / 1000.0)); signal_reconnect(output); @@ -3101,9 +2878,8 @@ static inline bool can_reconnect(const obs_output_t *output, int code) { bool reconnect_active = output->reconnect_retry_max != 0; - return code != OBS_OUTPUT_INVALID_STREAM && - ((reconnecting(output) && code != OBS_OUTPUT_SUCCESS) || - (reconnect_active && code == OBS_OUTPUT_DISCONNECTED)); + return code != OBS_OUTPUT_INVALID_STREAM && ((reconnecting(output) && code != OBS_OUTPUT_SUCCESS) || + (reconnect_active && code == OBS_OUTPUT_DISCONNECTED)); } void obs_output_signal_stop(obs_output_t *output, int code) @@ -3186,27 +2962,22 @@ obs_output_t *obs_weak_output_get_output(obs_weak_output_t *weak) return NULL; } -bool obs_weak_output_references_output(obs_weak_output_t *weak, - obs_output_t *output) +bool obs_weak_output_references_output(obs_weak_output_t *weak, obs_output_t *output) { return weak && output && weak->output == output; } void *obs_output_get_type_data(obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_type_data") - ? output->info.type_data - : NULL; + return obs_output_valid(output, "obs_output_get_type_data") ? output->info.type_data : NULL; } const char *obs_output_get_id(const obs_output_t *output) { - return obs_output_valid(output, "obs_output_get_id") ? output->info.id - : NULL; + return obs_output_valid(output, "obs_output_get_id") ? output->info.id : NULL; } -void obs_output_caption(obs_output_t *output, - const struct obs_source_cea_708 *captions) +void obs_output_caption(obs_output_t *output, const struct obs_source_cea_708 *captions) { for (int i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { struct caption_track_data *ctrack = output->caption_tracks[i]; @@ -3215,22 +2986,17 @@ void obs_output_caption(obs_output_t *output, } pthread_mutex_lock(&ctrack->caption_mutex); for (size_t i = 0; i < captions->packets; i++) { - deque_push_back(&ctrack->caption_data, - captions->data + (i * 3), - 3 * sizeof(uint8_t)); + deque_push_back(&ctrack->caption_data, captions->data + (i * 3), 3 * sizeof(uint8_t)); } pthread_mutex_unlock(&ctrack->caption_mutex); } } -static struct caption_text *caption_text_new(const char *text, size_t bytes, - struct caption_text *tail, - struct caption_text **head, - double display_duration) +static struct caption_text *caption_text_new(const char *text, size_t bytes, struct caption_text *tail, + struct caption_text **head, double display_duration) { struct caption_text *next = bzalloc(sizeof(struct caption_text)); - snprintf(&next->text[0], CAPTION_LINE_BYTES + 1, "%.*s", (int)bytes, - text); + snprintf(&next->text[0], CAPTION_LINE_BYTES + 1, "%.*s", (int)bytes, text); next->display_duration = display_duration; if (!*head) { @@ -3249,8 +3015,7 @@ void obs_output_output_caption_text1(obs_output_t *output, const char *text) obs_output_output_caption_text2(output, text, 2.0f); } -void obs_output_output_caption_text2(obs_output_t *output, const char *text, - double display_duration) +void obs_output_output_caption_text2(obs_output_t *output, const char *text, double display_duration) { if (!obs_output_valid(output, "obs_output_output_caption_text2")) return; @@ -3268,10 +3033,8 @@ void obs_output_output_caption_text2(obs_output_t *output, const char *text, } pthread_mutex_lock(&ctrack->caption_mutex); - ctrack->caption_tail = caption_text_new(text, size, - ctrack->caption_tail, - &ctrack->caption_head, - display_duration); + ctrack->caption_tail = + caption_text_new(text, size, ctrack->caption_tail, &ctrack->caption_head, display_duration); pthread_mutex_unlock(&ctrack->caption_mutex); } @@ -3353,16 +3116,12 @@ bool obs_output_reconnecting(const obs_output_t *output) const char *obs_output_get_supported_video_codecs(const obs_output_t *output) { - return obs_output_valid(output, __FUNCTION__) - ? output->info.encoded_video_codecs - : NULL; + return obs_output_valid(output, __FUNCTION__) ? output->info.encoded_video_codecs : NULL; } const char *obs_output_get_supported_audio_codecs(const obs_output_t *output) { - return obs_output_valid(output, __FUNCTION__) - ? output->info.encoded_audio_codecs - : NULL; + return obs_output_valid(output, __FUNCTION__) ? output->info.encoded_audio_codecs : NULL; } const char *obs_output_get_protocols(const obs_output_t *output) @@ -3373,9 +3132,7 @@ const char *obs_output_get_protocols(const obs_output_t *output) return flag_service(output) ? output->info.protocols : NULL; } -void obs_enum_output_types_with_protocol(const char *protocol, void *data, - bool (*enum_cb)(void *data, - const char *id)) +void obs_enum_output_types_with_protocol(const char *protocol, void *data, bool (*enum_cb)(void *data, const char *id)) { if (!obs_is_output_protocol_registered(protocol)) return; @@ -3388,12 +3145,9 @@ void obs_enum_output_types_with_protocol(const char *protocol, void *data, const char *substr = obs->output_types.array[i].protocols; while (substr && substr[0] != '\0') { const char *next = strchr(substr, ';'); - size_t len = next ? (size_t)(next - substr) - : strlen(substr); - if (protocol_len == len && - strncmp(substr, protocol, len) == 0) { - if (!enum_cb(data, - obs->output_types.array[i].id)) + size_t len = next ? (size_t)(next - substr) : strlen(substr); + if (protocol_len == len && strncmp(substr, protocol, len) == 0) { + if (!enum_cb(data, obs->output_types.array[i].id)) return; } substr = next ? next + 1 : NULL; @@ -3413,11 +3167,10 @@ const char *obs_get_output_supported_audio_codecs(const char *id) return info ? info->encoded_audio_codecs : NULL; } -void obs_output_add_packet_callback( - obs_output_t *output, - void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param), - void *param) +void obs_output_add_packet_callback(obs_output_t *output, + void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, + struct encoder_packet_time *pkt_time, void *param), + void *param) { struct packet_callback data = {packet_cb, param}; @@ -3426,11 +3179,10 @@ void obs_output_add_packet_callback( pthread_mutex_unlock(&output->pkt_callbacks_mutex); } -void obs_output_remove_packet_callback( - obs_output_t *output, - void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param), - void *param) +void obs_output_remove_packet_callback(obs_output_t *output, + void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, + struct encoder_packet_time *pkt_time, void *param), + void *param) { struct packet_callback data = {packet_cb, param}; diff --git a/libobs/obs-output.h b/libobs/obs-output.h index 1c3a26fc1..de0997dd2 100644 --- a/libobs/obs-output.h +++ b/libobs/obs-output.h @@ -31,8 +31,7 @@ extern "C" { #define OBS_OUTPUT_CAN_PAUSE (1 << 5) #define OBS_OUTPUT_MULTI_TRACK_AUDIO OBS_OUTPUT_MULTI_TRACK #define OBS_OUTPUT_MULTI_TRACK_VIDEO (1 << 6) -#define OBS_OUTPUT_MULTI_TRACK_AV \ - (OBS_OUTPUT_MULTI_TRACK_AUDIO | OBS_OUTPUT_MULTI_TRACK_VIDEO) +#define OBS_OUTPUT_MULTI_TRACK_AV (OBS_OUTPUT_MULTI_TRACK_AUDIO | OBS_OUTPUT_MULTI_TRACK_VIDEO) #define MAX_OUTPUT_AUDIO_ENCODERS 6 #define MAX_OUTPUT_VIDEO_ENCODERS 6 @@ -88,11 +87,9 @@ struct obs_output_info { const char *protocols; }; -EXPORT void obs_register_output_s(const struct obs_output_info *info, - size_t size); +EXPORT void obs_register_output_s(const struct obs_output_info *info, size_t size); -#define obs_register_output(info) \ - obs_register_output_s(info, sizeof(struct obs_output_info)) +#define obs_register_output(info) obs_register_output_s(info, sizeof(struct obs_output_info)) #ifdef __cplusplus } diff --git a/libobs/obs-properties.c b/libobs/obs-properties.c index a489a4a9e..166c9de67 100644 --- a/libobs/obs-properties.c +++ b/libobs/obs-properties.c @@ -112,8 +112,7 @@ static inline void editable_list_data_free(struct editable_list_data *data) bfree(data->filter); } -static inline void list_item_free(struct list_data *data, - struct list_item *item) +static inline void list_item_free(struct list_data *data, struct list_item *item) { bfree(item->name); if (data->format == OBS_COMBO_FORMAT_STRING) @@ -212,8 +211,7 @@ obs_properties_t *obs_properties_create(void) return props; } -void obs_properties_set_param(obs_properties_t *props, void *param, - void (*destroy)(void *param)) +void obs_properties_set_param(obs_properties_t *props, void *param, void (*destroy)(void *param)) { if (!props) return; @@ -241,8 +239,7 @@ void *obs_properties_get_param(obs_properties_t *props) return props ? props->param : NULL; } -obs_properties_t *obs_properties_create_param(void *param, - void (*destroy)(void *param)) +obs_properties_t *obs_properties_create_param(void *param, void (*destroy)(void *param)) { struct obs_properties *props = obs_properties_create(); obs_properties_set_param(props, param, destroy); @@ -355,23 +352,19 @@ void obs_properties_remove_by_name(obs_properties_t *props, const char *name) if (cur->type != OBS_PROPERTY_GROUP) continue; - obs_properties_remove_by_name(obs_property_group_content(cur), - name); + obs_properties_remove_by_name(obs_property_group_content(cur), name); } } typedef DARRAY(struct obs_property *) obs_property_da_t; -void obs_properties_apply_settings_internal( - obs_properties_t *props, obs_property_da_t *properties_with_callback) +void obs_properties_apply_settings_internal(obs_properties_t *props, obs_property_da_t *properties_with_callback) { struct obs_property *p = props->properties; while (p) { if (p->type == OBS_PROPERTY_GROUP) { - obs_properties_apply_settings_internal( - obs_property_group_content(p), - properties_with_callback); + obs_properties_apply_settings_internal(obs_property_group_content(p), properties_with_callback); } if (p->modified || p->modified2) da_push_back((*properties_with_callback), &p); @@ -380,8 +373,7 @@ void obs_properties_apply_settings_internal( } } -void obs_properties_apply_settings(obs_properties_t *props, - obs_data_t *settings) +void obs_properties_apply_settings(obs_properties_t *props, obs_data_t *settings) { if (!props) return; @@ -389,12 +381,10 @@ void obs_properties_apply_settings(obs_properties_t *props, obs_property_da_t properties_with_callback; da_init(properties_with_callback); - obs_properties_apply_settings_internal(props, - &properties_with_callback); + obs_properties_apply_settings_internal(props, &properties_with_callback); while (properties_with_callback.num > 0) { - struct obs_property *p = *(struct obs_property **)da_end( - properties_with_callback); + struct obs_property *p = *(struct obs_property **)da_end(properties_with_callback); if (p->modified) p->modified(props, p, settings); else if (p->modified2) @@ -443,8 +433,7 @@ static inline size_t get_property_size(enum obs_property_type type) return 0; } -static inline struct obs_property *new_prop(struct obs_properties *props, - const char *name, const char *desc, +static inline struct obs_property *new_prop(struct obs_properties *props, const char *name, const char *desc, enum obs_property_type type) { size_t data_size = get_property_size(type); @@ -507,8 +496,7 @@ static inline void *get_property_data(struct obs_property *prop) return (uint8_t *)prop + sizeof(struct obs_property); } -static inline void *get_type_data(struct obs_property *prop, - enum obs_property_type type) +static inline void *get_type_data(struct obs_property *prop, enum obs_property_type type) { if (!prop || prop->type != type) return NULL; @@ -516,16 +504,14 @@ static inline void *get_type_data(struct obs_property *prop, return get_property_data(prop); } -obs_property_t *obs_properties_add_bool(obs_properties_t *props, - const char *name, const char *desc) +obs_property_t *obs_properties_add_bool(obs_properties_t *props, const char *name, const char *desc) { if (!props || has_prop(props, name)) return NULL; return new_prop(props, name, desc, OBS_PROPERTY_BOOL); } -static obs_property_t *add_int(obs_properties_t *props, const char *name, - const char *desc, int min, int max, int step, +static obs_property_t *add_int(obs_properties_t *props, const char *name, const char *desc, int min, int max, int step, enum obs_number_type type) { if (!props || has_prop(props, name)) @@ -540,15 +526,13 @@ static obs_property_t *add_int(obs_properties_t *props, const char *name, return p; } -static obs_property_t *add_flt(obs_properties_t *props, const char *name, - const char *desc, double min, double max, +static obs_property_t *add_flt(obs_properties_t *props, const char *name, const char *desc, double min, double max, double step, enum obs_number_type type) { if (!props || has_prop(props, name)) return NULL; - struct obs_property *p = - new_prop(props, name, desc, OBS_PROPERTY_FLOAT); + struct obs_property *p = new_prop(props, name, desc, OBS_PROPERTY_FLOAT); struct float_data *data = get_property_data(p); data->min = min; data->max = max; @@ -557,38 +541,31 @@ static obs_property_t *add_flt(obs_properties_t *props, const char *name, return p; } -obs_property_t *obs_properties_add_int(obs_properties_t *props, - const char *name, const char *desc, - int min, int max, int step) +obs_property_t *obs_properties_add_int(obs_properties_t *props, const char *name, const char *desc, int min, int max, + int step) { return add_int(props, name, desc, min, max, step, OBS_NUMBER_SCROLLER); } -obs_property_t *obs_properties_add_float(obs_properties_t *props, - const char *name, const char *desc, - double min, double max, double step) +obs_property_t *obs_properties_add_float(obs_properties_t *props, const char *name, const char *desc, double min, + double max, double step) { return add_flt(props, name, desc, min, max, step, OBS_NUMBER_SCROLLER); } -obs_property_t *obs_properties_add_int_slider(obs_properties_t *props, - const char *name, - const char *desc, int min, +obs_property_t *obs_properties_add_int_slider(obs_properties_t *props, const char *name, const char *desc, int min, int max, int step) { return add_int(props, name, desc, min, max, step, OBS_NUMBER_SLIDER); } -obs_property_t *obs_properties_add_float_slider(obs_properties_t *props, - const char *name, - const char *desc, double min, +obs_property_t *obs_properties_add_float_slider(obs_properties_t *props, const char *name, const char *desc, double min, double max, double step) { return add_flt(props, name, desc, min, max, step, OBS_NUMBER_SLIDER); } -obs_property_t *obs_properties_add_text(obs_properties_t *props, - const char *name, const char *desc, +obs_property_t *obs_properties_add_text(obs_properties_t *props, const char *name, const char *desc, enum obs_text_type type) { if (!props || has_prop(props, name)) @@ -602,11 +579,8 @@ obs_property_t *obs_properties_add_text(obs_properties_t *props, return p; } -obs_property_t *obs_properties_add_path(obs_properties_t *props, - const char *name, const char *desc, - enum obs_path_type type, - const char *filter, - const char *default_path) +obs_property_t *obs_properties_add_path(obs_properties_t *props, const char *name, const char *desc, + enum obs_path_type type, const char *filter, const char *default_path) { if (!props || has_prop(props, name)) return NULL; @@ -622,16 +596,13 @@ obs_property_t *obs_properties_add_path(obs_properties_t *props, return p; } -obs_property_t *obs_properties_add_list(obs_properties_t *props, - const char *name, const char *desc, - enum obs_combo_type type, - enum obs_combo_format format) +obs_property_t *obs_properties_add_list(obs_properties_t *props, const char *name, const char *desc, + enum obs_combo_type type, enum obs_combo_format format) { if (!props || has_prop(props, name)) return NULL; - if (type == OBS_COMBO_TYPE_EDITABLE && - format != OBS_COMBO_FORMAT_STRING) { + if (type == OBS_COMBO_TYPE_EDITABLE && format != OBS_COMBO_FORMAT_STRING) { blog(LOG_WARNING, "List '%s', error: Editable combo boxes " "must be of the 'string' type", @@ -647,71 +618,59 @@ obs_property_t *obs_properties_add_list(obs_properties_t *props, return p; } -obs_property_t *obs_properties_add_color(obs_properties_t *props, - const char *name, const char *desc) +obs_property_t *obs_properties_add_color(obs_properties_t *props, const char *name, const char *desc) { if (!props || has_prop(props, name)) return NULL; return new_prop(props, name, desc, OBS_PROPERTY_COLOR); } -obs_property_t *obs_properties_add_color_alpha(obs_properties_t *props, - const char *name, - const char *desc) +obs_property_t *obs_properties_add_color_alpha(obs_properties_t *props, const char *name, const char *desc) { if (!props || has_prop(props, name)) return NULL; return new_prop(props, name, desc, OBS_PROPERTY_COLOR_ALPHA); } -obs_property_t *obs_properties_add_button(obs_properties_t *props, - const char *name, const char *text, +obs_property_t *obs_properties_add_button(obs_properties_t *props, const char *name, const char *text, obs_property_clicked_t callback) { if (!props || has_prop(props, name)) return NULL; - struct obs_property *p = - new_prop(props, name, text, OBS_PROPERTY_BUTTON); + struct obs_property *p = new_prop(props, name, text, OBS_PROPERTY_BUTTON); struct button_data *data = get_property_data(p); data->callback = callback; return p; } -obs_property_t *obs_properties_add_button2(obs_properties_t *props, - const char *name, const char *text, - obs_property_clicked_t callback, - void *priv) +obs_property_t *obs_properties_add_button2(obs_properties_t *props, const char *name, const char *text, + obs_property_clicked_t callback, void *priv) { if (!props || has_prop(props, name)) return NULL; - struct obs_property *p = - new_prop(props, name, text, OBS_PROPERTY_BUTTON); + struct obs_property *p = new_prop(props, name, text, OBS_PROPERTY_BUTTON); struct button_data *data = get_property_data(p); data->callback = callback; p->priv = priv; return p; } -obs_property_t *obs_properties_add_font(obs_properties_t *props, - const char *name, const char *desc) +obs_property_t *obs_properties_add_font(obs_properties_t *props, const char *name, const char *desc) { if (!props || has_prop(props, name)) return NULL; return new_prop(props, name, desc, OBS_PROPERTY_FONT); } -obs_property_t * -obs_properties_add_editable_list(obs_properties_t *props, const char *name, - const char *desc, - enum obs_editable_list_type type, - const char *filter, const char *default_path) +obs_property_t *obs_properties_add_editable_list(obs_properties_t *props, const char *name, const char *desc, + enum obs_editable_list_type type, const char *filter, + const char *default_path) { if (!props || has_prop(props, name)) return NULL; - struct obs_property *p = - new_prop(props, name, desc, OBS_PROPERTY_EDITABLE_LIST); + struct obs_property *p = new_prop(props, name, desc, OBS_PROPERTY_EDITABLE_LIST); struct editable_list_data *data = get_property_data(p); data->type = type; @@ -720,15 +679,12 @@ obs_properties_add_editable_list(obs_properties_t *props, const char *name, return p; } -obs_property_t *obs_properties_add_frame_rate(obs_properties_t *props, - const char *name, - const char *desc) +obs_property_t *obs_properties_add_frame_rate(obs_properties_t *props, const char *name, const char *desc) { if (!props || has_prop(props, name)) return NULL; - struct obs_property *p = - new_prop(props, name, desc, OBS_PROPERTY_FRAME_RATE); + struct obs_property *p = new_prop(props, name, desc, OBS_PROPERTY_FRAME_RATE); struct frame_rate_data *data = get_property_data(p); da_init(data->extra_options); @@ -736,8 +692,7 @@ obs_property_t *obs_properties_add_frame_rate(obs_properties_t *props, return p; } -static bool check_property_group_recursion(obs_properties_t *parent, - obs_properties_t *group) +static bool check_property_group_recursion(obs_properties_t *parent, obs_properties_t *group) { /* Scan the group for the parent. */ obs_property_t *p, *tmp; @@ -762,8 +717,7 @@ static bool check_property_group_recursion(obs_properties_t *parent, return false; } -static bool check_property_group_duplicates(obs_properties_t *parent, - obs_properties_t *group) +static bool check_property_group_duplicates(obs_properties_t *parent, obs_properties_t *group) { obs_property_t *p, *tmp; @@ -775,10 +729,8 @@ static bool check_property_group_duplicates(obs_properties_t *parent, return false; } -obs_property_t *obs_properties_add_group(obs_properties_t *props, - const char *name, const char *desc, - enum obs_group_type type, - obs_properties_t *group) +obs_property_t *obs_properties_add_group(obs_properties_t *props, const char *name, const char *desc, + enum obs_group_type type, obs_properties_t *group) { if (!props || has_prop(props, name)) return NULL; @@ -820,8 +772,7 @@ static inline struct list_data *get_list_data(struct obs_property *p) return get_property_data(p); } -static inline struct list_data *get_list_fmt_data(struct obs_property *p, - enum obs_combo_format format) +static inline struct list_data *get_list_fmt_data(struct obs_property *p, enum obs_combo_format format) { struct list_data *data = get_list_data(p); return (data && data->format == format) ? data : NULL; @@ -838,16 +789,13 @@ bool obs_property_next(obs_property_t **p) return *p != NULL; } -void obs_property_set_modified_callback(obs_property_t *p, - obs_property_modified_t modified) +void obs_property_set_modified_callback(obs_property_t *p, obs_property_modified_t modified) { if (p) p->modified = modified; } -void obs_property_set_modified_callback2(obs_property_t *p, - obs_property_modified2_t modified2, - void *priv) +void obs_property_set_modified_callback2(obs_property_t *p, obs_property_modified2_t modified2, void *priv) { if (p) { p->modified2 = modified2; @@ -873,14 +821,12 @@ bool obs_property_button_clicked(obs_property_t *p, void *obj) { struct obs_context_data *context = obj; if (p) { - struct button_data *data = - get_type_data(p, OBS_PROPERTY_BUTTON); + struct button_data *data = get_type_data(p, OBS_PROPERTY_BUTTON); if (data && data->callback) { obs_properties_t *top = get_topmost_parent(p->parent); if (p->priv) return data->callback(top, p, p->priv); - return data->callback(top, p, - (context ? context->data : NULL)); + return data->callback(top, p, (context ? context->data : NULL)); } } @@ -903,8 +849,7 @@ void obs_property_set_description(obs_property_t *p, const char *description) { if (p) { bfree(p->desc); - p->desc = description && *description ? bstrdup(description) - : NULL; + p->desc = description && *description ? bstrdup(description) : NULL; } } @@ -912,8 +857,7 @@ void obs_property_set_long_description(obs_property_t *p, const char *long_desc) { if (p) { bfree(p->long_desc); - p->long_desc = long_desc && *long_desc ? bstrdup(long_desc) - : NULL; + p->long_desc = long_desc && *long_desc ? bstrdup(long_desc) : NULL; } } @@ -1072,8 +1016,7 @@ void obs_property_int_set_limits(obs_property_t *p, int min, int max, int step) data->step = step; } -void obs_property_float_set_limits(obs_property_t *p, double min, double max, - double step) +void obs_property_float_set_limits(obs_property_t *p, double min, double max, double step) { struct float_data *data = get_type_data(p, OBS_PROPERTY_FLOAT); if (!data) @@ -1113,8 +1056,7 @@ void obs_property_text_set_monospace(obs_property_t *p, bool monospace) data->monospace = monospace; } -void obs_property_text_set_info_type(obs_property_t *p, - enum obs_text_info_type type) +void obs_property_text_set_info_type(obs_property_t *p, enum obs_text_info_type type) { struct text_data *data = get_type_data(p, OBS_PROPERTY_TEXT); if (!data) @@ -1157,8 +1099,7 @@ void obs_property_list_clear(obs_property_t *p) list_data_free(data); } -static size_t add_item(struct list_data *data, const char *name, - const void *val) +static size_t add_item(struct list_data *data, const char *name, const void *val) { struct list_item item = {NULL}; item.name = bstrdup(name); @@ -1175,8 +1116,7 @@ static size_t add_item(struct list_data *data, const char *name, return da_push_back(data->items, &item); } -static void insert_item(struct list_data *data, size_t idx, const char *name, - const void *val) +static void insert_item(struct list_data *data, size_t idx, const char *name, const void *val) { struct list_item item = {NULL}; item.name = bstrdup(name); @@ -1193,8 +1133,7 @@ static void insert_item(struct list_data *data, size_t idx, const char *name, da_insert(data->items, idx, &item); } -size_t obs_property_list_add_string(obs_property_t *p, const char *name, - const char *val) +size_t obs_property_list_add_string(obs_property_t *p, const char *name, const char *val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_STRING) @@ -1202,8 +1141,7 @@ size_t obs_property_list_add_string(obs_property_t *p, const char *name, return 0; } -size_t obs_property_list_add_int(obs_property_t *p, const char *name, - long long val) +size_t obs_property_list_add_int(obs_property_t *p, const char *name, long long val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_INT) @@ -1211,8 +1149,7 @@ size_t obs_property_list_add_int(obs_property_t *p, const char *name, return 0; } -size_t obs_property_list_add_float(obs_property_t *p, const char *name, - double val) +size_t obs_property_list_add_float(obs_property_t *p, const char *name, double val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_FLOAT) @@ -1228,32 +1165,28 @@ size_t obs_property_list_add_bool(obs_property_t *p, const char *name, bool val) return 0; } -void obs_property_list_insert_string(obs_property_t *p, size_t idx, - const char *name, const char *val) +void obs_property_list_insert_string(obs_property_t *p, size_t idx, const char *name, const char *val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_STRING) insert_item(data, idx, name, val); } -void obs_property_list_insert_int(obs_property_t *p, size_t idx, - const char *name, long long val) +void obs_property_list_insert_int(obs_property_t *p, size_t idx, const char *name, long long val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_INT) insert_item(data, idx, name, &val); } -void obs_property_list_insert_float(obs_property_t *p, size_t idx, - const char *name, double val) +void obs_property_list_insert_float(obs_property_t *p, size_t idx, const char *name, double val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_FLOAT) insert_item(data, idx, name, &val); } -void obs_property_list_insert_bool(obs_property_t *p, size_t idx, - const char *name, bool val) +void obs_property_list_insert_bool(obs_property_t *p, size_t idx, const char *name, bool val) { struct list_data *data = get_list_data(p); if (data && data->format == OBS_COMBO_FORMAT_BOOL) @@ -1278,12 +1211,10 @@ size_t obs_property_list_item_count(obs_property_t *p) bool obs_property_list_item_disabled(obs_property_t *p, size_t idx) { struct list_data *data = get_list_data(p); - return (data && idx < data->items.num) ? data->items.array[idx].disabled - : false; + return (data && idx < data->items.num) ? data->items.array[idx].disabled : false; } -void obs_property_list_item_disable(obs_property_t *p, size_t idx, - bool disabled) +void obs_property_list_item_disable(obs_property_t *p, size_t idx, bool disabled) { struct list_data *data = get_list_data(p); if (!data || idx >= data->items.num) @@ -1294,15 +1225,13 @@ void obs_property_list_item_disable(obs_property_t *p, size_t idx, const char *obs_property_list_item_name(obs_property_t *p, size_t idx) { struct list_data *data = get_list_data(p); - return (data && idx < data->items.num) ? data->items.array[idx].name - : NULL; + return (data && idx < data->items.num) ? data->items.array[idx].name : NULL; } const char *obs_property_list_item_string(obs_property_t *p, size_t idx) { struct list_data *data = get_list_fmt_data(p, OBS_COMBO_FORMAT_STRING); - return (data && idx < data->items.num) ? data->items.array[idx].str - : NULL; + return (data && idx < data->items.num) ? data->items.array[idx].str : NULL; } long long obs_property_list_item_int(obs_property_t *p, size_t idx) @@ -1320,28 +1249,24 @@ double obs_property_list_item_float(obs_property_t *p, size_t idx) bool obs_property_list_item_bool(obs_property_t *p, size_t idx) { struct list_data *data = get_list_fmt_data(p, OBS_COMBO_FORMAT_BOOL); - return (data && idx < data->items.num) ? data->items.array[idx].d - : false; + return (data && idx < data->items.num) ? data->items.array[idx].d : false; } enum obs_editable_list_type obs_property_editable_list_type(obs_property_t *p) { - struct editable_list_data *data = - get_type_data(p, OBS_PROPERTY_EDITABLE_LIST); + struct editable_list_data *data = get_type_data(p, OBS_PROPERTY_EDITABLE_LIST); return data ? data->type : OBS_EDITABLE_LIST_TYPE_STRINGS; } const char *obs_property_editable_list_filter(obs_property_t *p) { - struct editable_list_data *data = - get_type_data(p, OBS_PROPERTY_EDITABLE_LIST); + struct editable_list_data *data = get_type_data(p, OBS_PROPERTY_EDITABLE_LIST); return data ? data->filter : NULL; } const char *obs_property_editable_list_default_path(obs_property_t *p) { - struct editable_list_data *data = - get_type_data(p, OBS_PROPERTY_EDITABLE_LIST); + struct editable_list_data *data = get_type_data(p, OBS_PROPERTY_EDITABLE_LIST); return data ? data->default_path : NULL; } @@ -1350,8 +1275,7 @@ const char *obs_property_editable_list_default_path(obs_property_t *p) void obs_property_frame_rate_clear(obs_property_t *p) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return; @@ -1361,8 +1285,7 @@ void obs_property_frame_rate_clear(obs_property_t *p) void obs_property_frame_rate_options_clear(obs_property_t *p) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return; @@ -1371,19 +1294,16 @@ void obs_property_frame_rate_options_clear(obs_property_t *p) void obs_property_frame_rate_fps_ranges_clear(obs_property_t *p) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return; frame_rate_data_ranges_free(data); } -size_t obs_property_frame_rate_option_add(obs_property_t *p, const char *name, - const char *description) +size_t obs_property_frame_rate_option_add(obs_property_t *p, const char *name, const char *description) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return DARRAY_INVALID; @@ -1395,12 +1315,10 @@ size_t obs_property_frame_rate_option_add(obs_property_t *p, const char *name, return data->extra_options.num - 1; } -size_t obs_property_frame_rate_fps_range_add(obs_property_t *p, - struct media_frames_per_second min, +size_t obs_property_frame_rate_fps_range_add(obs_property_t *p, struct media_frames_per_second min, struct media_frames_per_second max) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return DARRAY_INVALID; @@ -1412,12 +1330,9 @@ size_t obs_property_frame_rate_fps_range_add(obs_property_t *p, return data->ranges.num - 1; } -void obs_property_frame_rate_option_insert(obs_property_t *p, size_t idx, - const char *name, - const char *description) +void obs_property_frame_rate_option_insert(obs_property_t *p, size_t idx, const char *name, const char *description) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return; @@ -1427,12 +1342,10 @@ void obs_property_frame_rate_option_insert(obs_property_t *p, size_t idx, opt->description = bstrdup(description); } -void obs_property_frame_rate_fps_range_insert( - obs_property_t *p, size_t idx, struct media_frames_per_second min, - struct media_frames_per_second max) +void obs_property_frame_rate_fps_range_insert(obs_property_t *p, size_t idx, struct media_frames_per_second min, + struct media_frames_per_second max) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); if (!data) return; @@ -1444,54 +1357,37 @@ void obs_property_frame_rate_fps_range_insert( size_t obs_property_frame_rate_options_count(obs_property_t *p) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); return data ? data->extra_options.num : 0; } const char *obs_property_frame_rate_option_name(obs_property_t *p, size_t idx) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); - return data && data->extra_options.num > idx - ? data->extra_options.array[idx].name - : NULL; + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); + return data && data->extra_options.num > idx ? data->extra_options.array[idx].name : NULL; } -const char *obs_property_frame_rate_option_description(obs_property_t *p, - size_t idx) +const char *obs_property_frame_rate_option_description(obs_property_t *p, size_t idx) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); - return data && data->extra_options.num > idx - ? data->extra_options.array[idx].description - : NULL; + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); + return data && data->extra_options.num > idx ? data->extra_options.array[idx].description : NULL; } size_t obs_property_frame_rate_fps_ranges_count(obs_property_t *p) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); return data ? data->ranges.num : 0; } -struct media_frames_per_second -obs_property_frame_rate_fps_range_min(obs_property_t *p, size_t idx) +struct media_frames_per_second obs_property_frame_rate_fps_range_min(obs_property_t *p, size_t idx) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); - return data && data->ranges.num > idx - ? data->ranges.array[idx].min_time - : (struct media_frames_per_second){0}; + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); + return data && data->ranges.num > idx ? data->ranges.array[idx].min_time : (struct media_frames_per_second){0}; } -struct media_frames_per_second -obs_property_frame_rate_fps_range_max(obs_property_t *p, size_t idx) +struct media_frames_per_second obs_property_frame_rate_fps_range_max(obs_property_t *p, size_t idx) { - struct frame_rate_data *data = - get_type_data(p, OBS_PROPERTY_FRAME_RATE); - return data && data->ranges.num > idx - ? data->ranges.array[idx].max_time - : (struct media_frames_per_second){0}; + struct frame_rate_data *data = get_type_data(p, OBS_PROPERTY_FRAME_RATE); + return data && data->ranges.num > idx ? data->ranges.array[idx].max_time : (struct media_frames_per_second){0}; } enum obs_group_type obs_property_group_type(obs_property_t *p) diff --git a/libobs/obs-properties.h b/libobs/obs-properties.h index 16339aad8..e25805b6b 100644 --- a/libobs/obs-properties.h +++ b/libobs/obs-properties.h @@ -128,21 +128,18 @@ typedef struct obs_property obs_property_t; /* ------------------------------------------------------------------------- */ EXPORT obs_properties_t *obs_properties_create(void); -EXPORT obs_properties_t * -obs_properties_create_param(void *param, void (*destroy)(void *param)); +EXPORT obs_properties_t *obs_properties_create_param(void *param, void (*destroy)(void *param)); EXPORT void obs_properties_destroy(obs_properties_t *props); EXPORT void obs_properties_set_flags(obs_properties_t *props, uint32_t flags); EXPORT uint32_t obs_properties_get_flags(obs_properties_t *props); -EXPORT void obs_properties_set_param(obs_properties_t *props, void *param, - void (*destroy)(void *param)); +EXPORT void obs_properties_set_param(obs_properties_t *props, void *param, void (*destroy)(void *param)); EXPORT void *obs_properties_get_param(obs_properties_t *props); EXPORT obs_property_t *obs_properties_first(obs_properties_t *props); -EXPORT obs_property_t *obs_properties_get(obs_properties_t *props, - const char *property); +EXPORT obs_property_t *obs_properties_get(obs_properties_t *props, const char *property); EXPORT obs_properties_t *obs_properties_get_parent(obs_properties_t *props); @@ -156,15 +153,13 @@ EXPORT obs_properties_t *obs_properties_get_parent(obs_properties_t *props); * @param props Properties to remove from. * @param property Name of the property to remove. */ -EXPORT void obs_properties_remove_by_name(obs_properties_t *props, - const char *property); +EXPORT void obs_properties_remove_by_name(obs_properties_t *props, const char *property); /** * Applies settings to the properties by calling all the necessary * modification callbacks */ -EXPORT void obs_properties_apply_settings(obs_properties_t *props, - obs_data_t *settings); +EXPORT void obs_properties_apply_settings(obs_properties_t *props, obs_data_t *settings); /* ------------------------------------------------------------------------- */ @@ -173,39 +168,23 @@ EXPORT void obs_properties_apply_settings(obs_properties_t *props, * need to be refreshed due to changes to the property layout, return true, * otherwise return false. */ -typedef bool (*obs_property_clicked_t)(obs_properties_t *props, - obs_property_t *property, void *data); +typedef bool (*obs_property_clicked_t)(obs_properties_t *props, obs_property_t *property, void *data); -EXPORT obs_property_t *obs_properties_add_bool(obs_properties_t *props, - const char *name, - const char *description); +EXPORT obs_property_t *obs_properties_add_bool(obs_properties_t *props, const char *name, const char *description); -EXPORT obs_property_t *obs_properties_add_int(obs_properties_t *props, - const char *name, - const char *description, int min, - int max, int step); +EXPORT obs_property_t *obs_properties_add_int(obs_properties_t *props, const char *name, const char *description, + int min, int max, int step); -EXPORT obs_property_t *obs_properties_add_float(obs_properties_t *props, - const char *name, - const char *description, - double min, double max, - double step); +EXPORT obs_property_t *obs_properties_add_float(obs_properties_t *props, const char *name, const char *description, + double min, double max, double step); -EXPORT obs_property_t *obs_properties_add_int_slider(obs_properties_t *props, - const char *name, - const char *description, - int min, int max, - int step); +EXPORT obs_property_t *obs_properties_add_int_slider(obs_properties_t *props, const char *name, const char *description, + int min, int max, int step); -EXPORT obs_property_t *obs_properties_add_float_slider(obs_properties_t *props, - const char *name, - const char *description, - double min, double max, - double step); +EXPORT obs_property_t *obs_properties_add_float_slider(obs_properties_t *props, const char *name, + const char *description, double min, double max, double step); -EXPORT obs_property_t *obs_properties_add_text(obs_properties_t *props, - const char *name, - const char *description, +EXPORT obs_property_t *obs_properties_add_text(obs_properties_t *props, const char *name, const char *description, enum obs_text_type type); /** @@ -224,33 +203,22 @@ EXPORT obs_property_t *obs_properties_add_text(obs_properties_t *props, * double semicolons. If multiple file types in a * filter, separate with space. */ -EXPORT obs_property_t * -obs_properties_add_path(obs_properties_t *props, const char *name, - const char *description, enum obs_path_type type, - const char *filter, const char *default_path); +EXPORT obs_property_t *obs_properties_add_path(obs_properties_t *props, const char *name, const char *description, + enum obs_path_type type, const char *filter, const char *default_path); -EXPORT obs_property_t *obs_properties_add_list(obs_properties_t *props, - const char *name, - const char *description, - enum obs_combo_type type, - enum obs_combo_format format); +EXPORT obs_property_t *obs_properties_add_list(obs_properties_t *props, const char *name, const char *description, + enum obs_combo_type type, enum obs_combo_format format); -EXPORT obs_property_t *obs_properties_add_color(obs_properties_t *props, - const char *name, - const char *description); +EXPORT obs_property_t *obs_properties_add_color(obs_properties_t *props, const char *name, const char *description); -EXPORT obs_property_t *obs_properties_add_color_alpha(obs_properties_t *props, - const char *name, +EXPORT obs_property_t *obs_properties_add_color_alpha(obs_properties_t *props, const char *name, const char *description); -EXPORT obs_property_t * -obs_properties_add_button(obs_properties_t *props, const char *name, - const char *text, obs_property_clicked_t callback); +EXPORT obs_property_t *obs_properties_add_button(obs_properties_t *props, const char *name, const char *text, + obs_property_clicked_t callback); -EXPORT obs_property_t * -obs_properties_add_button2(obs_properties_t *props, const char *name, - const char *text, obs_property_clicked_t callback, - void *priv); +EXPORT obs_property_t *obs_properties_add_button2(obs_properties_t *props, const char *name, const char *text, + obs_property_clicked_t callback, void *priv); /** * Adds a font selection property. @@ -261,25 +229,17 @@ obs_properties_add_button2(obs_properties_t *props, const char *name, * size: size integer * flags: font flags integer (OBS_FONT_* defined above) */ -EXPORT obs_property_t *obs_properties_add_font(obs_properties_t *props, - const char *name, - const char *description); +EXPORT obs_property_t *obs_properties_add_font(obs_properties_t *props, const char *name, const char *description); -EXPORT obs_property_t * -obs_properties_add_editable_list(obs_properties_t *props, const char *name, - const char *description, - enum obs_editable_list_type type, - const char *filter, const char *default_path); +EXPORT obs_property_t *obs_properties_add_editable_list(obs_properties_t *props, const char *name, + const char *description, enum obs_editable_list_type type, + const char *filter, const char *default_path); -EXPORT obs_property_t *obs_properties_add_frame_rate(obs_properties_t *props, - const char *name, +EXPORT obs_property_t *obs_properties_add_frame_rate(obs_properties_t *props, const char *name, const char *description); -EXPORT obs_property_t *obs_properties_add_group(obs_properties_t *props, - const char *name, - const char *description, - enum obs_group_type type, - obs_properties_t *group); +EXPORT obs_property_t *obs_properties_add_group(obs_properties_t *props, const char *name, const char *description, + enum obs_group_type type, obs_properties_t *group); /* ------------------------------------------------------------------------- */ @@ -288,18 +248,12 @@ EXPORT obs_property_t *obs_properties_add_group(obs_properties_t *props, * need to be refreshed due to changes to the property layout, return true, * otherwise return false. */ -typedef bool (*obs_property_modified_t)(obs_properties_t *props, - obs_property_t *property, - obs_data_t *settings); -typedef bool (*obs_property_modified2_t)(void *priv, obs_properties_t *props, - obs_property_t *property, +typedef bool (*obs_property_modified_t)(obs_properties_t *props, obs_property_t *property, obs_data_t *settings); +typedef bool (*obs_property_modified2_t)(void *priv, obs_properties_t *props, obs_property_t *property, obs_data_t *settings); -EXPORT void -obs_property_set_modified_callback(obs_property_t *p, - obs_property_modified_t modified); -EXPORT void obs_property_set_modified_callback2( - obs_property_t *p, obs_property_modified2_t modified, void *priv); +EXPORT void obs_property_set_modified_callback(obs_property_t *p, obs_property_modified_t modified); +EXPORT void obs_property_set_modified_callback2(obs_property_t *p, obs_property_modified2_t modified, void *priv); EXPORT bool obs_property_modified(obs_property_t *p, obs_data_t *settings); EXPORT bool obs_property_button_clicked(obs_property_t *p, void *obj); @@ -307,10 +261,8 @@ EXPORT bool obs_property_button_clicked(obs_property_t *p, void *obj); EXPORT void obs_property_set_visible(obs_property_t *p, bool visible); EXPORT void obs_property_set_enabled(obs_property_t *p, bool enabled); -EXPORT void obs_property_set_description(obs_property_t *p, - const char *description); -EXPORT void obs_property_set_long_description(obs_property_t *p, - const char *long_description); +EXPORT void obs_property_set_description(obs_property_t *p, const char *description); +EXPORT void obs_property_set_long_description(obs_property_t *p, const char *long_description); EXPORT const char *obs_property_name(obs_property_t *p); EXPORT const char *obs_property_description(obs_property_t *p); @@ -341,45 +293,30 @@ EXPORT const char *obs_property_path_default_path(obs_property_t *p); EXPORT enum obs_combo_type obs_property_list_type(obs_property_t *p); EXPORT enum obs_combo_format obs_property_list_format(obs_property_t *p); -EXPORT void obs_property_int_set_limits(obs_property_t *p, int min, int max, - int step); -EXPORT void obs_property_float_set_limits(obs_property_t *p, double min, - double max, double step); +EXPORT void obs_property_int_set_limits(obs_property_t *p, int min, int max, int step); +EXPORT void obs_property_float_set_limits(obs_property_t *p, double min, double max, double step); EXPORT void obs_property_int_set_suffix(obs_property_t *p, const char *suffix); -EXPORT void obs_property_float_set_suffix(obs_property_t *p, - const char *suffix); +EXPORT void obs_property_float_set_suffix(obs_property_t *p, const char *suffix); EXPORT void obs_property_text_set_monospace(obs_property_t *p, bool monospace); -EXPORT void obs_property_text_set_info_type(obs_property_t *p, - enum obs_text_info_type type); -EXPORT void obs_property_text_set_info_word_wrap(obs_property_t *p, - bool word_wrap); +EXPORT void obs_property_text_set_info_type(obs_property_t *p, enum obs_text_info_type type); +EXPORT void obs_property_text_set_info_word_wrap(obs_property_t *p, bool word_wrap); -EXPORT void obs_property_button_set_type(obs_property_t *p, - enum obs_button_type type); +EXPORT void obs_property_button_set_type(obs_property_t *p, enum obs_button_type type); EXPORT void obs_property_button_set_url(obs_property_t *p, char *url); EXPORT void obs_property_list_clear(obs_property_t *p); -EXPORT size_t obs_property_list_add_string(obs_property_t *p, const char *name, - const char *val); -EXPORT size_t obs_property_list_add_int(obs_property_t *p, const char *name, - long long val); -EXPORT size_t obs_property_list_add_float(obs_property_t *p, const char *name, - double val); -EXPORT size_t obs_property_list_add_bool(obs_property_t *p, const char *name, - bool val); +EXPORT size_t obs_property_list_add_string(obs_property_t *p, const char *name, const char *val); +EXPORT size_t obs_property_list_add_int(obs_property_t *p, const char *name, long long val); +EXPORT size_t obs_property_list_add_float(obs_property_t *p, const char *name, double val); +EXPORT size_t obs_property_list_add_bool(obs_property_t *p, const char *name, bool val); -EXPORT void obs_property_list_insert_string(obs_property_t *p, size_t idx, - const char *name, const char *val); -EXPORT void obs_property_list_insert_int(obs_property_t *p, size_t idx, - const char *name, long long val); -EXPORT void obs_property_list_insert_float(obs_property_t *p, size_t idx, - const char *name, double val); -EXPORT void obs_property_list_insert_bool(obs_property_t *p, size_t idx, - const char *name, bool val); +EXPORT void obs_property_list_insert_string(obs_property_t *p, size_t idx, const char *name, const char *val); +EXPORT void obs_property_list_insert_int(obs_property_t *p, size_t idx, const char *name, long long val); +EXPORT void obs_property_list_insert_float(obs_property_t *p, size_t idx, const char *name, double val); +EXPORT void obs_property_list_insert_bool(obs_property_t *p, size_t idx, const char *name, bool val); -EXPORT void obs_property_list_item_disable(obs_property_t *p, size_t idx, - bool disabled); +EXPORT void obs_property_list_item_disable(obs_property_t *p, size_t idx, bool disabled); EXPORT bool obs_property_list_item_disabled(obs_property_t *p, size_t idx); EXPORT void obs_property_list_item_remove(obs_property_t *p, size_t idx); @@ -391,8 +328,7 @@ EXPORT long long obs_property_list_item_int(obs_property_t *p, size_t idx); EXPORT double obs_property_list_item_float(obs_property_t *p, size_t idx); EXPORT bool obs_property_list_item_bool(obs_property_t *p, size_t idx); -EXPORT enum obs_editable_list_type -obs_property_editable_list_type(obs_property_t *p); +EXPORT enum obs_editable_list_type obs_property_editable_list_type(obs_property_t *p); EXPORT const char *obs_property_editable_list_filter(obs_property_t *p); EXPORT const char *obs_property_editable_list_default_path(obs_property_t *p); @@ -400,32 +336,22 @@ EXPORT void obs_property_frame_rate_clear(obs_property_t *p); EXPORT void obs_property_frame_rate_options_clear(obs_property_t *p); EXPORT void obs_property_frame_rate_fps_ranges_clear(obs_property_t *p); -EXPORT size_t obs_property_frame_rate_option_add(obs_property_t *p, - const char *name, - const char *description); -EXPORT size_t obs_property_frame_rate_fps_range_add( - obs_property_t *p, struct media_frames_per_second min, - struct media_frames_per_second max); +EXPORT size_t obs_property_frame_rate_option_add(obs_property_t *p, const char *name, const char *description); +EXPORT size_t obs_property_frame_rate_fps_range_add(obs_property_t *p, struct media_frames_per_second min, + struct media_frames_per_second max); -EXPORT void obs_property_frame_rate_option_insert(obs_property_t *p, size_t idx, - const char *name, +EXPORT void obs_property_frame_rate_option_insert(obs_property_t *p, size_t idx, const char *name, const char *description); -EXPORT void -obs_property_frame_rate_fps_range_insert(obs_property_t *p, size_t idx, - struct media_frames_per_second min, - struct media_frames_per_second max); +EXPORT void obs_property_frame_rate_fps_range_insert(obs_property_t *p, size_t idx, struct media_frames_per_second min, + struct media_frames_per_second max); EXPORT size_t obs_property_frame_rate_options_count(obs_property_t *p); -EXPORT const char *obs_property_frame_rate_option_name(obs_property_t *p, - size_t idx); -EXPORT const char *obs_property_frame_rate_option_description(obs_property_t *p, - size_t idx); +EXPORT const char *obs_property_frame_rate_option_name(obs_property_t *p, size_t idx); +EXPORT const char *obs_property_frame_rate_option_description(obs_property_t *p, size_t idx); EXPORT size_t obs_property_frame_rate_fps_ranges_count(obs_property_t *p); -EXPORT struct media_frames_per_second -obs_property_frame_rate_fps_range_min(obs_property_t *p, size_t idx); -EXPORT struct media_frames_per_second -obs_property_frame_rate_fps_range_max(obs_property_t *p, size_t idx); +EXPORT struct media_frames_per_second obs_property_frame_rate_fps_range_min(obs_property_t *p, size_t idx); +EXPORT struct media_frames_per_second obs_property_frame_rate_fps_range_max(obs_property_t *p, size_t idx); EXPORT enum obs_group_type obs_property_group_type(obs_property_t *p); EXPORT obs_properties_t *obs_property_group_content(obs_property_t *p); diff --git a/libobs/obs-scene.c b/libobs/obs-scene.c index 9e5028ed9..5252b2776 100644 --- a/libobs/obs-scene.c +++ b/libobs/obs-scene.c @@ -26,14 +26,11 @@ const struct obs_source_info group_info; static void resize_group(obs_sceneitem_t *group, bool scene_resize); static void resize_scene(obs_scene_t *scene); -static void signal_parent(obs_scene_t *parent, const char *name, - calldata_t *params); -static void get_ungrouped_transform(obs_sceneitem_t *group, struct vec2 *pos, - struct vec2 *scale, float *rot); +static void signal_parent(obs_scene_t *parent, const char *name, calldata_t *params); +static void get_ungrouped_transform(obs_sceneitem_t *group, struct vec2 *pos, struct vec2 *scale, float *rot); static inline bool crop_enabled(const struct obs_sceneitem_crop *crop); static inline bool item_texture_enabled(const struct obs_scene_item *item); -static void init_hotkeys(obs_scene_t *scene, obs_sceneitem_t *item, - const char *name); +static void init_hotkeys(obs_scene_t *scene, obs_sceneitem_t *item, const char *name); typedef DARRAY(struct obs_scene_item *) obs_scene_item_ptr_array_t; @@ -128,8 +125,7 @@ static const struct { /* clang-format on */ }; -static inline void signal_item_remove(struct obs_scene *parent, - struct obs_scene_item *item) +static inline void signal_item_remove(struct obs_scene *parent, struct obs_scene_item *item) { struct calldata params; uint8_t stack[128]; @@ -164,8 +160,7 @@ static void *scene_create(obs_data_t *settings, struct obs_source *source) scene->cy = 0; } - signal_handler_add_array(obs_source_get_signal_handler(source), - obs_scene_signals); + signal_handler_add_array(obs_source_get_signal_handler(source), obs_scene_signals); if (pthread_mutex_init_recursive(&scene->audio_mutex) != 0) { blog(LOG_ERROR, "scene_create: Couldn't initialize audio " @@ -178,8 +173,7 @@ static void *scene_create(obs_data_t *settings, struct obs_source *source) goto fail; } - scene->absolute_coordinates = obs_data_get_bool(obs->data.private_data, - "AbsoluteCoordinates"); + scene->absolute_coordinates = obs_data_get_bool(obs->data.private_data, "AbsoluteCoordinates"); UNUSED_PARAMETER(settings); return scene; @@ -248,12 +242,10 @@ static void scene_destroy(void *data) static inline bool transition_active(obs_source_t *transition) { - return transition && (transition->transitioning_audio || - transition->transitioning_video); + return transition && (transition->transitioning_audio || transition->transitioning_video); } -static void scene_enum_sources(void *data, obs_source_enum_proc_t enum_callback, - void *param, bool active) +static void scene_enum_sources(void *data, obs_source_enum_proc_t enum_callback, void *param, bool active) { struct obs_scene *scene = data; struct obs_scene_item *item; @@ -267,24 +259,17 @@ static void scene_enum_sources(void *data, obs_source_enum_proc_t enum_callback, obs_sceneitem_addref(item); if (active) { - if (item->visible && - transition_active(item->show_transition)) - enum_callback(scene->source, - item->show_transition, param); - else if (!item->visible && - transition_active(item->hide_transition)) - enum_callback(scene->source, - item->hide_transition, param); + if (item->visible && transition_active(item->show_transition)) + enum_callback(scene->source, item->show_transition, param); + else if (!item->visible && transition_active(item->hide_transition)) + enum_callback(scene->source, item->hide_transition, param); if (os_atomic_load_long(&item->active_refs) > 0) - enum_callback(scene->source, item->source, - param); + enum_callback(scene->source, item->source, param); } else { if (item->show_transition) - enum_callback(scene->source, - item->show_transition, param); + enum_callback(scene->source, item->show_transition, param); if (item->hide_transition) - enum_callback(scene->source, - item->hide_transition, param); + enum_callback(scene->source, item->hide_transition, param); enum_callback(scene->source, item->source, param); } @@ -296,16 +281,12 @@ static void scene_enum_sources(void *data, obs_source_enum_proc_t enum_callback, full_unlock(scene); } -static void scene_enum_active_sources(void *data, - obs_source_enum_proc_t enum_callback, - void *param) +static void scene_enum_active_sources(void *data, obs_source_enum_proc_t enum_callback, void *param) { scene_enum_sources(data, enum_callback, param, true); } -static void scene_enum_all_sources(void *data, - obs_source_enum_proc_t enum_callback, - void *param) +static void scene_enum_all_sources(void *data, obs_source_enum_proc_t enum_callback, void *param) { scene_enum_sources(data, enum_callback, param, false); } @@ -323,9 +304,7 @@ static inline void detach_sceneitem(struct obs_scene_item *item) item->parent = NULL; } -static inline void attach_sceneitem(struct obs_scene *parent, - struct obs_scene_item *item, - struct obs_scene_item *prev) +static inline void attach_sceneitem(struct obs_scene *parent, struct obs_scene_item *item, struct obs_scene_item *prev) { item->prev = prev; item->parent = parent; @@ -359,8 +338,7 @@ void add_alignment(struct vec2 *v, uint32_t align, int cx, int cy) static uint32_t scene_getwidth(void *data); static uint32_t scene_getheight(void *data); -static inline void get_scene_dimensions(const obs_sceneitem_t *item, float *x, - float *y) +static inline void get_scene_dimensions(const obs_sceneitem_t *item, float *x, float *y) { obs_scene_t *parent = item->parent; if (!parent || parent->is_group) { @@ -379,8 +357,7 @@ static inline void nudge_abs_values(struct vec2 *dst, const struct vec2 *v) dst->y = floorf(v->y * 2.0f + 0.5f) / 2.0f; } -static inline void pos_from_absolute(struct vec2 *dst, const struct vec2 *v, - const obs_sceneitem_t *item) +static inline void pos_from_absolute(struct vec2 *dst, const struct vec2 *v, const obs_sceneitem_t *item) { float x, y; get_scene_dimensions(item, &x, &y); @@ -389,8 +366,7 @@ static inline void pos_from_absolute(struct vec2 *dst, const struct vec2 *v, dst->y = 2 * v->y / y - 1.0f; } -static inline void pos_to_absolute(struct vec2 *dst, const struct vec2 *v, - const obs_sceneitem_t *item) +static inline void pos_to_absolute(struct vec2 *dst, const struct vec2 *v, const obs_sceneitem_t *item) { float x, y; get_scene_dimensions(item, &x, &y); @@ -403,8 +379,7 @@ static inline void pos_to_absolute(struct vec2 *dst, const struct vec2 *v, nudge_abs_values(dst, dst); } -static inline void size_from_absolute(struct vec2 *dst, const struct vec2 *v, - const obs_sceneitem_t *item) +static inline void size_from_absolute(struct vec2 *dst, const struct vec2 *v, const obs_sceneitem_t *item) { float x, y; get_scene_dimensions(item, &x, &y); @@ -414,8 +389,7 @@ static inline void size_from_absolute(struct vec2 *dst, const struct vec2 *v, dst->y = 2 * v->y / y; } -static inline void size_to_absolute(struct vec2 *dst, const struct vec2 *v, - const obs_sceneitem_t *item) +static inline void size_to_absolute(struct vec2 *dst, const struct vec2 *v, const obs_sceneitem_t *item) { float x, y; get_scene_dimensions(item, &x, &y); @@ -427,8 +401,7 @@ static inline void size_to_absolute(struct vec2 *dst, const struct vec2 *v, } /* Return item's scale value scaled from original to current canvas size. */ -static inline void item_canvas_scale(struct vec2 *dst, - const obs_sceneitem_t *item) +static inline void item_canvas_scale(struct vec2 *dst, const obs_sceneitem_t *item) { /* Groups will themselves resize so their items do not need to be * rescaled manually. Nested scenes will use the updated canvas @@ -445,8 +418,7 @@ static inline void item_canvas_scale(struct vec2 *dst, } /* Return scale value scaled to original canvas size. */ -static inline void item_relative_scale(struct vec2 *dst, const struct vec2 *v, - const obs_sceneitem_t *item) +static inline void item_relative_scale(struct vec2 *dst, const struct vec2 *v, const obs_sceneitem_t *item) { if (item->is_group || item->is_scene) { vec2_copy(dst, v); @@ -462,14 +434,12 @@ static inline void item_relative_scale(struct vec2 *dst, const struct vec2 *v, static inline bool crop_to_bounds(const struct obs_scene_item *item) { return item->crop_to_bounds && - (item->bounds_type == OBS_BOUNDS_SCALE_OUTER || - item->bounds_type == OBS_BOUNDS_SCALE_TO_HEIGHT || + (item->bounds_type == OBS_BOUNDS_SCALE_OUTER || item->bounds_type == OBS_BOUNDS_SCALE_TO_HEIGHT || item->bounds_type == OBS_BOUNDS_SCALE_TO_WIDTH); } -static void calculate_bounds_data(struct obs_scene_item *item, - struct vec2 *origin, struct vec2 *scale, - uint32_t *cx, uint32_t *cy) +static void calculate_bounds_data(struct obs_scene_item *item, struct vec2 *origin, struct vec2 *scale, uint32_t *cx, + uint32_t *cy) { struct vec2 bounds; if (item->absolute_coordinates) @@ -488,8 +458,7 @@ static void calculate_bounds_data(struct obs_scene_item *item, if (width > bounds.x || height > bounds.y) bounds_type = OBS_BOUNDS_SCALE_INNER; - if (bounds_type == OBS_BOUNDS_SCALE_INNER || - bounds_type == OBS_BOUNDS_SCALE_OUTER) { + if (bounds_type == OBS_BOUNDS_SCALE_INNER || bounds_type == OBS_BOUNDS_SCALE_OUTER) { bool use_width = (bounds_aspect < item_aspect); float mul; @@ -520,8 +489,7 @@ static void calculate_bounds_data(struct obs_scene_item *item, *cx = (uint32_t)bounds.x; *cy = (uint32_t)bounds.y; - add_alignment(origin, item->bounds_align, (int)-width_diff, - (int)-height_diff); + add_alignment(origin, item->bounds_align, (int)-width_diff, (int)-height_diff); /* Set cropping if enabled and large enough size difference exists */ if (crop_to_bounds(item) && (width_diff < -0.1 || height_diff < -0.1)) { @@ -533,9 +501,8 @@ static void calculate_bounds_data(struct obs_scene_item *item, float crop_origin = crop_width ? origin->x : origin->y; /* Only get alignment for relevant axis */ - uint32_t crop_align_mask = - crop_width ? OBS_ALIGN_LEFT | OBS_ALIGN_RIGHT - : OBS_ALIGN_TOP | OBS_ALIGN_BOTTOM; + uint32_t crop_align_mask = crop_width ? OBS_ALIGN_LEFT | OBS_ALIGN_RIGHT + : OBS_ALIGN_TOP | OBS_ALIGN_BOTTOM; uint32_t crop_align = item->bounds_align & crop_align_mask; /* Cropping values need to scaled to input source */ @@ -585,19 +552,15 @@ static void calculate_bounds_data(struct obs_scene_item *item, origin->y += (height < 0.0f) ? height : 0.0f; } -static inline uint32_t calc_cx(const struct obs_scene_item *item, - uint32_t width) +static inline uint32_t calc_cx(const struct obs_scene_item *item, uint32_t width) { - uint32_t crop_cx = item->crop.left + item->crop.right + - item->bounds_crop.left + item->bounds_crop.right; + uint32_t crop_cx = item->crop.left + item->crop.right + item->bounds_crop.left + item->bounds_crop.right; return (crop_cx > width) ? 2 : (width - crop_cx); } -static inline uint32_t calc_cy(const struct obs_scene_item *item, - uint32_t height) +static inline uint32_t calc_cy(const struct obs_scene_item *item, uint32_t height) { - uint32_t crop_cy = item->crop.top + item->crop.bottom + - item->bounds_crop.top + item->bounds_crop.bottom; + uint32_t crop_cy = item->crop.top + item->crop.bottom + item->bounds_crop.top + item->bounds_crop.bottom; return (crop_cy > height) ? 2 : (height - crop_cy); } @@ -610,14 +573,12 @@ static inline void log_matrix(const struct matrix4 *mat, const char *name) "┃ %9.4f %9.4f %9.4f %9.4f ┃\n" "┃ %9.4f %9.4f %9.4f %9.4f ┃\n" "┗ %9.4f %9.4f %9.4f %9.4f ┛", - name, mat->x.x, mat->x.y, mat->x.z, mat->x.w, mat->y.x, mat->y.y, - mat->y.z, mat->y.w, mat->z.x, mat->z.y, mat->z.z, mat->z.w, - mat->t.x, mat->t.y, mat->t.z, mat->t.w); + name, mat->x.x, mat->x.y, mat->x.z, mat->x.w, mat->y.x, mat->y.y, mat->y.z, mat->y.w, mat->z.x, mat->z.y, + mat->z.z, mat->z.w, mat->t.x, mat->t.y, mat->t.z, mat->t.w); } #endif -static inline void update_nested_scene_crop(struct obs_scene_item *item, - uint32_t width, uint32_t height) +static inline void update_nested_scene_crop(struct obs_scene_item *item, uint32_t width, uint32_t height) { if (!item->last_height || !item->last_width) return; @@ -689,18 +650,13 @@ static void update_item_transform(struct obs_scene_item *item, bool update_tex) add_alignment(&origin, item->align, (int)cx, (int)cy); matrix4_identity(&item->draw_transform); - matrix4_scale3f(&item->draw_transform, &item->draw_transform, scale.x, - scale.y, 1.0f); - matrix4_translate3f(&item->draw_transform, &item->draw_transform, - -origin.x, -origin.y, 0.0f); - matrix4_rotate_aa4f(&item->draw_transform, &item->draw_transform, 0.0f, - 0.0f, 1.0f, RAD(item->rot)); - matrix4_translate3f(&item->draw_transform, &item->draw_transform, - position.x, position.y, 0.0f); + matrix4_scale3f(&item->draw_transform, &item->draw_transform, scale.x, scale.y, 1.0f); + matrix4_translate3f(&item->draw_transform, &item->draw_transform, -origin.x, -origin.y, 0.0f); + matrix4_rotate_aa4f(&item->draw_transform, &item->draw_transform, 0.0f, 0.0f, 1.0f, RAD(item->rot)); + matrix4_translate3f(&item->draw_transform, &item->draw_transform, position.x, position.y, 0.0f); #ifdef DEBUG_TRANSFORM - blog(LOG_DEBUG, "Transform updated for \"%s\":", - obs_source_get_name(item->source)); + blog(LOG_DEBUG, "Transform updated for \"%s\":", obs_source_get_name(item->source)); log_matrix(&item->draw_transform, "draw_transform"); #endif @@ -723,14 +679,10 @@ static void update_item_transform(struct obs_scene_item *item, bool update_tex) add_alignment(&base_origin, item->align, (int)scale.x, (int)scale.y); matrix4_identity(&item->box_transform); - matrix4_scale3f(&item->box_transform, &item->box_transform, scale.x, - scale.y, 1.0f); - matrix4_translate3f(&item->box_transform, &item->box_transform, - -base_origin.x, -base_origin.y, 0.0f); - matrix4_rotate_aa4f(&item->box_transform, &item->box_transform, 0.0f, - 0.0f, 1.0f, RAD(item->rot)); - matrix4_translate3f(&item->box_transform, &item->box_transform, - position.x, position.y, 0.0f); + matrix4_scale3f(&item->box_transform, &item->box_transform, scale.x, scale.y, 1.0f); + matrix4_translate3f(&item->box_transform, &item->box_transform, -base_origin.x, -base_origin.y, 0.0f); + matrix4_rotate_aa4f(&item->box_transform, &item->box_transform, 0.0f, 0.0f, 1.0f, RAD(item->rot)); + matrix4_translate3f(&item->box_transform, &item->box_transform, position.x, position.y, 0.0f); #ifdef DEBUG_TRANSFORM log_matrix(&item->draw_transform, "box_transform"); @@ -778,15 +730,12 @@ static inline bool item_is_scene(const struct obs_scene_item *item) static inline bool item_texture_enabled(const struct obs_scene_item *item) { - return crop_enabled(&item->crop) || crop_enabled(&item->bounds_crop) || - scale_filter_enabled(item) || - (item->blend_method == OBS_BLEND_METHOD_SRGB_OFF) || - !default_blending_enabled(item) || + return crop_enabled(&item->crop) || crop_enabled(&item->bounds_crop) || scale_filter_enabled(item) || + (item->blend_method == OBS_BLEND_METHOD_SRGB_OFF) || !default_blending_enabled(item) || (item_is_scene(item) && !item->is_group); } -static void render_item_texture(struct obs_scene_item *item, - enum gs_color_space current_space, +static void render_item_texture(struct obs_scene_item *item, enum gs_color_space current_space, enum gs_color_space source_space) { gs_texture_t *tex = gs_texrender_get_texture(item->item_render); @@ -794,8 +743,7 @@ static void render_item_texture(struct obs_scene_item *item, return; } - GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_ITEM_TEXTURE, - "render_item_texture"); + GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_ITEM_TEXTURE, "render_item_texture"); gs_effect_t *effect = obs->video.default_effect; enum obs_scale_type type = item->scale_filter; @@ -805,15 +753,12 @@ static void render_item_texture(struct obs_scene_item *item, bool upscale = false; if (type != OBS_SCALE_DISABLE) { if (type == OBS_SCALE_POINT) { - gs_eparam_t *image = - gs_effect_get_param_by_name(effect, "image"); - gs_effect_set_next_sampler(image, - obs->video.point_sampler); + gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image"); + gs_effect_set_next_sampler(image, obs->video.point_sampler); } else if (!close_float(item->output_scale.x, 1.0f, EPSILON) || !close_float(item->output_scale.y, 1.0f, EPSILON)) { - if (item->output_scale.x < 0.5f || - item->output_scale.y < 0.5f) { + if (item->output_scale.x < 0.5f || item->output_scale.y < 0.5f) { effect = obs->video.bilinear_lowres_effect; } else if (type == OBS_SCALE_BICUBIC) { effect = obs->video.bicubic_effect; @@ -821,25 +766,19 @@ static void render_item_texture(struct obs_scene_item *item, effect = obs->video.lanczos_effect; } else if (type == OBS_SCALE_AREA) { effect = obs->video.area_effect; - upscale = (item->output_scale.x >= 1.0f) && - (item->output_scale.y >= 1.0f); + upscale = (item->output_scale.x >= 1.0f) && (item->output_scale.y >= 1.0f); } - gs_eparam_t *const scale_param = - gs_effect_get_param_by_name(effect, - "base_dimension"); + gs_eparam_t *const scale_param = gs_effect_get_param_by_name(effect, "base_dimension"); if (scale_param) { struct vec2 base_res = {(float)cx, (float)cy}; gs_effect_set_vec2(scale_param, &base_res); } - gs_eparam_t *const scale_i_param = - gs_effect_get_param_by_name(effect, - "base_dimension_i"); + gs_eparam_t *const scale_i_param = gs_effect_get_param_by_name(effect, "base_dimension_i"); if (scale_i_param) { - struct vec2 base_res_i = {1.0f / (float)cx, - 1.0f / (float)cy}; + struct vec2 base_res_i = {1.0f / (float)cx, 1.0f / (float)cy}; gs_effect_set_vec2(scale_i_param, &base_res_i); } @@ -882,15 +821,13 @@ static void render_item_texture(struct obs_scene_item *item, tech_name = "DrawUpscaleMultiply"; break; case GS_CS_709_EXTENDED: - if (current_space == GS_CS_SRGB || - current_space == GS_CS_SRGB_16F) + if (current_space == GS_CS_SRGB || current_space == GS_CS_SRGB_16F) tech_name = "DrawUpscaleTonemap"; else if (current_space == GS_CS_709_SCRGB) tech_name = "DrawUpscaleMultiply"; break; case GS_CS_709_SCRGB: - if (current_space == GS_CS_SRGB || - current_space == GS_CS_SRGB_16F) + if (current_space == GS_CS_SRGB || current_space == GS_CS_SRGB_16F) tech_name = "DrawUpscaleMultiplyTonemap"; else if (current_space == GS_CS_709_EXTENDED) tech_name = "DrawUpscaleMultiply"; @@ -904,15 +841,13 @@ static void render_item_texture(struct obs_scene_item *item, tech_name = "DrawMultiply"; break; case GS_CS_709_EXTENDED: - if (current_space == GS_CS_SRGB || - current_space == GS_CS_SRGB_16F) + if (current_space == GS_CS_SRGB || current_space == GS_CS_SRGB_16F) tech_name = "DrawTonemap"; else if (current_space == GS_CS_709_SCRGB) tech_name = "DrawMultiply"; break; case GS_CS_709_SCRGB: - if (current_space == GS_CS_SRGB || - current_space == GS_CS_SRGB_16F) + if (current_space == GS_CS_SRGB || current_space == GS_CS_SRGB_16F) tech_name = "DrawMultiplyTonemap"; else if (current_space == GS_CS_709_EXTENDED) tech_name = "DrawMultiply"; @@ -920,18 +855,16 @@ static void render_item_texture(struct obs_scene_item *item, } } - gs_eparam_t *const multiplier_param = - gs_effect_get_param_by_name(effect, "multiplier"); + gs_eparam_t *const multiplier_param = gs_effect_get_param_by_name(effect, "multiplier"); if (multiplier_param) gs_effect_set_float(multiplier_param, multiplier); gs_blend_state_push(); - gs_blend_function_separate( - obs_blend_mode_params[item->blend_type].src_color, - obs_blend_mode_params[item->blend_type].dst_color, - obs_blend_mode_params[item->blend_type].src_alpha, - obs_blend_mode_params[item->blend_type].dst_alpha); + gs_blend_function_separate(obs_blend_mode_params[item->blend_type].src_color, + obs_blend_mode_params[item->blend_type].dst_color, + obs_blend_mode_params[item->blend_type].src_alpha, + obs_blend_mode_params[item->blend_type].dst_alpha); gs_blend_op(obs_blend_mode_params[item->blend_type].op); while (gs_effect_loop(effect, tech_name)) @@ -958,21 +891,16 @@ static bool are_texcoords_centered(struct matrix4 *m) static inline void render_item(struct obs_scene_item *item) { - GS_DEBUG_MARKER_BEGIN_FORMAT(GS_DEBUG_COLOR_ITEM, "Item: %s", - obs_source_get_name(item->source)); + GS_DEBUG_MARKER_BEGIN_FORMAT(GS_DEBUG_COLOR_ITEM, "Item: %s", obs_source_get_name(item->source)); const bool use_texrender = item_texture_enabled(item); obs_source_t *const source = item->source; const enum gs_color_space current_space = gs_get_color_space(); - const enum gs_color_space source_space = - obs_source_get_color_space(source, 1, ¤t_space); - const enum gs_color_format format = - gs_get_format_from_space(source_space); + const enum gs_color_space source_space = obs_source_get_color_space(source, 1, ¤t_space); + const enum gs_color_format format = gs_get_format_from_space(source_space); - if (item->item_render && - (!use_texrender || - (gs_texrender_get_format(item->item_render) != format))) { + if (item->item_render && (!use_texrender || (gs_texrender_get_format(item->item_render) != format))) { gs_texrender_destroy(item->item_render); item->item_render = NULL; } @@ -992,78 +920,57 @@ static inline void render_item(struct obs_scene_item *item) uint32_t cx = calc_cx(item, width); uint32_t cy = calc_cy(item, height); - if (cx && cy && - gs_texrender_begin_with_color_space(item->item_render, cx, - cy, source_space)) { + if (cx && cy && gs_texrender_begin_with_color_space(item->item_render, cx, cy, source_space)) { float cx_scale = (float)width / (float)cx; float cy_scale = (float)height / (float)cy; struct vec4 clear_color; vec4_zero(&clear_color); gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0); - gs_ortho(0.0f, (float)width, 0.0f, (float)height, - -100.0f, 100.0f); + gs_ortho(0.0f, (float)width, 0.0f, (float)height, -100.0f, 100.0f); gs_matrix_scale3f(cx_scale, cy_scale, 1.0f); - gs_matrix_translate3f(-(float)(item->crop.left + - item->bounds_crop.left), - -(float)(item->crop.top + - item->bounds_crop.top), - 0.0f); + gs_matrix_translate3f(-(float)(item->crop.left + item->bounds_crop.left), + -(float)(item->crop.top + item->bounds_crop.top), 0.0f); - if (item->user_visible && - transition_active(item->show_transition)) { - const int cx = - obs_source_get_width(item->source); - const int cy = - obs_source_get_height(item->source); - obs_transition_set_size(item->show_transition, - cx, cy); + if (item->user_visible && transition_active(item->show_transition)) { + const int cx = obs_source_get_width(item->source); + const int cy = obs_source_get_height(item->source); + obs_transition_set_size(item->show_transition, cx, cy); obs_source_video_render(item->show_transition); - } else if (!item->user_visible && - transition_active(item->hide_transition)) { - const int cx = - obs_source_get_width(item->source); - const int cy = - obs_source_get_height(item->source); - obs_transition_set_size(item->hide_transition, - cx, cy); + } else if (!item->user_visible && transition_active(item->hide_transition)) { + const int cx = obs_source_get_width(item->source); + const int cy = obs_source_get_height(item->source); + obs_transition_set_size(item->hide_transition, cx, cy); obs_source_video_render(item->hide_transition); } else { - obs_source_set_texcoords_centered(item->source, - true); + obs_source_set_texcoords_centered(item->source, true); obs_source_video_render(item->source); - obs_source_set_texcoords_centered(item->source, - false); + obs_source_set_texcoords_centered(item->source, false); } gs_texrender_end(item->item_render); } } - const bool linear_srgb = - !item->item_render || - (item->blend_method != OBS_BLEND_METHOD_SRGB_OFF); + const bool linear_srgb = !item->item_render || (item->blend_method != OBS_BLEND_METHOD_SRGB_OFF); const bool previous = gs_set_linear_srgb(linear_srgb); gs_matrix_push(); gs_matrix_mul(&item->draw_transform); if (item->item_render) { render_item_texture(item, current_space, source_space); - } else if (item->user_visible && - transition_active(item->show_transition)) { + } else if (item->user_visible && transition_active(item->show_transition)) { const int cx = obs_source_get_width(item->source); const int cy = obs_source_get_height(item->source); obs_transition_set_size(item->show_transition, cx, cy); obs_source_video_render(item->show_transition); - } else if (!item->user_visible && - transition_active(item->hide_transition)) { + } else if (!item->user_visible && transition_active(item->hide_transition)) { const int cx = obs_source_get_width(item->source); const int cy = obs_source_get_height(item->source); obs_transition_set_size(item->hide_transition, cx, cy); obs_source_video_render(item->hide_transition); } else { - const bool centered = - are_texcoords_centered(&item->draw_transform); + const bool centered = are_texcoords_centered(&item->draw_transform); obs_source_set_texcoords_centered(item->source, centered); obs_source_video_render(item->source); obs_source_set_texcoords_centered(item->source, false); @@ -1093,14 +1000,11 @@ static void scene_video_tick(void *data, float seconds) } /* assumes video lock */ -static void update_transforms_and_prune_sources( - obs_scene_t *scene, obs_scene_item_ptr_array_t *remove_items, - obs_sceneitem_t *group_sceneitem, bool scene_size_changed) +static void update_transforms_and_prune_sources(obs_scene_t *scene, obs_scene_item_ptr_array_t *remove_items, + obs_sceneitem_t *group_sceneitem, bool scene_size_changed) { struct obs_scene_item *item = scene->first_item; - bool rebuild_group = - group_sceneitem && - os_atomic_load_bool(&group_sceneitem->update_group_resize); + bool rebuild_group = group_sceneitem && os_atomic_load_bool(&group_sceneitem->update_group_resize); while (item) { if (obs_source_removed(item->source)) { @@ -1117,14 +1021,11 @@ static void update_transforms_and_prune_sources( obs_scene_t *group_scene = item->source->context.data; video_lock(group_scene); - update_transforms_and_prune_sources(group_scene, - remove_items, item, - scene_size_changed); + update_transforms_and_prune_sources(group_scene, remove_items, item, scene_size_changed); video_unlock(group_scene); } - if (os_atomic_load_bool(&item->update_transform) || - source_size_changed(item) || scene_size_changed) { + if (os_atomic_load_bool(&item->update_transform) || source_size_changed(item) || scene_size_changed) { update_item_transform(item, true); rebuild_group = true; @@ -1162,8 +1063,7 @@ static void scene_video_render(void *data, gs_effect_t *effect) if (!scene->is_group) { bool size_changed = scene_size_changed(scene); - update_transforms_and_prune_sources(scene, &remove_items, NULL, - size_changed); + update_transforms_and_prune_sources(scene, &remove_items, NULL, size_changed); } gs_blend_state_push(); @@ -1171,8 +1071,7 @@ static void scene_video_render(void *data, gs_effect_t *effect) item = scene->first_item; while (item) { - if (item->user_visible || - transition_active(item->hide_transition)) + if (item->user_visible || transition_active(item->hide_transition)) render_item(item); item = item->next; @@ -1197,8 +1096,7 @@ static void set_visibility(struct obs_scene_item *item, bool vis) if (os_atomic_load_long(&item->active_refs) > 0) { if (!vis) - obs_source_remove_active_child(item->parent->source, - item->source); + obs_source_remove_active_child(item->parent->source, item->source); } else if (vis) { obs_source_add_active_child(item->parent->source, item->source); } @@ -1210,9 +1108,7 @@ static void set_visibility(struct obs_scene_item *item, bool vis) pthread_mutex_unlock(&item->actions_mutex); } -static obs_sceneitem_t *obs_scene_add_internal(obs_scene_t *scene, - obs_source_t *source, - obs_sceneitem_t *insert_after, +static obs_sceneitem_t *obs_scene_add_internal(obs_scene_t *scene, obs_source_t *source, obs_sceneitem_t *insert_after, int64_t id); static void scene_load_item(struct obs_scene *scene, obs_data_t *item_data) @@ -1247,8 +1143,7 @@ static void scene_load_item(struct obs_scene *scene, obs_data_t *item_data) return; } - item = obs_scene_add_internal(scene, source, NULL, - obs_data_get_int(item_data, "id")); + item = obs_scene_add_internal(scene, source, NULL, obs_data_get_int(item_data, "id")); if (!item) { blog(LOG_WARNING, "[scene_load_item] Could not add source '%s' " @@ -1262,23 +1157,19 @@ static void scene_load_item(struct obs_scene *scene, obs_data_t *item_data) calldata_init_fixed(¶ms, stack, sizeof(stack)); calldata_set_ptr(¶ms, "scene", scene); calldata_set_ptr(¶ms, "item", item); - signal_handler_signal(scene->source->context.signals, "item_add", - ¶ms); + signal_handler_signal(scene->source->context.signals, "item_add", ¶ms); item->is_group = strcmp(source->info.id, group_info.id) == 0; - obs_data_set_default_int(item_data, "align", - OBS_ALIGN_TOP | OBS_ALIGN_LEFT); + obs_data_set_default_int(item_data, "align", OBS_ALIGN_TOP | OBS_ALIGN_LEFT); item->rot = (float)obs_data_get_double(item_data, "rot"); item->align = (uint32_t)obs_data_get_int(item_data, "align"); visible = obs_data_get_bool(item_data, "visible"); lock = obs_data_get_bool(item_data, "locked"); - if (!item->absolute_coordinates && - obs_data_has_user_value(item_data, "pos_rel") && - obs_data_has_user_value(item_data, "scale_rel") && - obs_data_has_user_value(item_data, "scale_ref")) { + if (!item->absolute_coordinates && obs_data_has_user_value(item_data, "pos_rel") && + obs_data_has_user_value(item_data, "scale_rel") && obs_data_has_user_value(item_data, "scale_ref")) { obs_data_get_vec2(item_data, "pos_rel", &item->pos); obs_data_get_vec2(item_data, "scale_rel", &item->scale); obs_data_get_vec2(item_data, "scale_ref", &item->scale_ref); @@ -1290,23 +1181,19 @@ static void scene_load_item(struct obs_scene *scene, obs_data_t *item_data) } obs_data_release(item->private_settings); - item->private_settings = - obs_data_get_obj(item_data, "private_settings"); + item->private_settings = obs_data_get_obj(item_data, "private_settings"); if (!item->private_settings) item->private_settings = obs_data_create(); set_visibility(item, visible); obs_sceneitem_set_locked(item, lock); - item->bounds_type = (enum obs_bounds_type)obs_data_get_int( - item_data, "bounds_type"); - item->bounds_align = - (uint32_t)obs_data_get_int(item_data, "bounds_align"); + item->bounds_type = (enum obs_bounds_type)obs_data_get_int(item_data, "bounds_type"); + item->bounds_align = (uint32_t)obs_data_get_int(item_data, "bounds_align"); item->crop_to_bounds = obs_data_get_bool(item_data, "bounds_crop"); obs_data_get_vec2(item_data, "bounds", &item->bounds); - if (!item->absolute_coordinates && - obs_data_has_user_value(item_data, "bounds_rel")) { + if (!item->absolute_coordinates && obs_data_has_user_value(item_data, "bounds_rel")) { obs_data_get_vec2(item_data, "bounds_rel", &item->bounds); } else { obs_data_get_vec2(item_data, "bounds", &item->bounds); @@ -1317,8 +1204,7 @@ static void scene_load_item(struct obs_scene *scene, obs_data_t *item_data) item->crop.left = (uint32_t)obs_data_get_int(item_data, "crop_left"); item->crop.top = (uint32_t)obs_data_get_int(item_data, "crop_top"); item->crop.right = (uint32_t)obs_data_get_int(item_data, "crop_right"); - item->crop.bottom = - (uint32_t)obs_data_get_int(item_data, "crop_bottom"); + item->crop.bottom = (uint32_t)obs_data_get_int(item_data, "crop_bottom"); scale_filter_str = obs_data_get_string(item_data, "scale_filter"); item->scale_filter = OBS_SCALE_DISABLE; @@ -1396,8 +1282,7 @@ static void scene_load(void *data, obs_data_t *settings) if (obs_data_has_user_value(settings, "id_counter")) scene->id_counter = obs_data_get_int(settings, "id_counter"); - scene->absolute_coordinates = obs_data_get_bool(obs->data.private_data, - "AbsoluteCoordinates"); + scene->absolute_coordinates = obs_data_get_bool(obs->data.private_data, "AbsoluteCoordinates"); if (!items) return; @@ -1415,9 +1300,7 @@ static void scene_load(void *data, obs_data_t *settings) static void scene_save(void *data, obs_data_t *settings); -static void scene_save_item(obs_data_array_t *array, - struct obs_scene_item *item, - struct obs_scene_item *backup_group) +static void scene_save_item(obs_data_array_t *array, struct obs_scene_item *item, struct obs_scene_item *backup_group) { obs_data_t *item_data = obs_data_create(); const char *name = obs_source_get_name(item->source); @@ -1591,9 +1474,7 @@ static uint32_t scene_getheight(void *data) return 0; } -static void apply_scene_item_audio_actions(struct obs_scene_item *item, - float *buf, uint64_t ts, - size_t sample_rate) +static void apply_scene_item_audio_actions(struct obs_scene_item *item, float *buf, uint64_t ts, size_t sample_rate) { bool cur_visible = item->visible; uint64_t frame_num = 0; @@ -1609,8 +1490,7 @@ static void apply_scene_item_audio_actions(struct obs_scene_item *item, if (timestamp < ts) timestamp = ts; - new_frame_num = util_mul_div64(timestamp - ts, sample_rate, - 1000000000ULL); + new_frame_num = util_mul_div64(timestamp - ts, sample_rate, 1000000000ULL); if (ts && new_frame_num >= AUDIO_OUTPUT_FRAMES) break; @@ -1638,14 +1518,12 @@ static void apply_scene_item_audio_actions(struct obs_scene_item *item, while (deref_count--) { if (os_atomic_dec_long(&item->active_refs) == 0) { - obs_source_remove_active_child(item->parent->source, - item->source); + obs_source_remove_active_child(item->parent->source, item->source); } } } -static bool apply_scene_item_volume(struct obs_scene_item *item, float *buf, - uint64_t ts, size_t sample_rate) +static bool apply_scene_item_volume(struct obs_scene_item *item, float *buf, uint64_t ts, size_t sample_rate) { bool actions_pending; struct item_action action; @@ -1659,12 +1537,10 @@ static bool apply_scene_item_volume(struct obs_scene_item *item, float *buf, pthread_mutex_unlock(&item->actions_mutex); if (actions_pending) { - uint64_t duration = util_mul_div64(AUDIO_OUTPUT_FRAMES, - 1000000000ULL, sample_rate); + uint64_t duration = util_mul_div64(AUDIO_OUTPUT_FRAMES, 1000000000ULL, sample_rate); if (!ts || action.timestamp < (ts + duration)) { - apply_scene_item_audio_actions(item, buf, ts, - sample_rate); + apply_scene_item_audio_actions(item, buf, ts, sample_rate); return true; } } @@ -1672,15 +1548,13 @@ static bool apply_scene_item_volume(struct obs_scene_item *item, float *buf, return false; } -static void process_all_audio_actions(struct obs_scene_item *item, - size_t sample_rate) +static void process_all_audio_actions(struct obs_scene_item *item, size_t sample_rate) { while (apply_scene_item_volume(item, NULL, 0, sample_rate)) ; } -static void mix_audio_with_buf(float *p_out, float *p_in, float *buf_in, - size_t pos, size_t count) +static void mix_audio_with_buf(float *p_out, float *p_in, float *buf_in, size_t pos, size_t count) { register float *out = p_out + pos; register float *buf = buf_in; @@ -1691,8 +1565,7 @@ static void mix_audio_with_buf(float *p_out, float *p_in, float *buf_in, *(out++) += *(in++) * *(buf++); } -static inline void mix_audio(float *p_out, float *p_in, size_t pos, - size_t count) +static inline void mix_audio(float *p_out, float *p_in, size_t pos, size_t count) { register float *out = p_out + pos; register float *in = p_in; @@ -1702,8 +1575,7 @@ static inline void mix_audio(float *p_out, float *p_in, size_t pos, *(out++) += *(in++); } -static inline struct scene_source_mix *get_source_mix(struct obs_scene *scene, - struct obs_source *source) +static inline struct scene_source_mix *get_source_mix(struct obs_scene *scene, struct obs_source *source) { for (size_t i = 0; i < scene->mix_sources.num; i++) { struct scene_source_mix *mix = &scene->mix_sources.array[i]; @@ -1714,10 +1586,9 @@ static inline struct scene_source_mix *get_source_mix(struct obs_scene *scene, return NULL; } -static bool scene_audio_render_internal( - struct obs_scene *scene, struct obs_scene *parent, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, uint32_t mixers, - size_t channels, size_t sample_rate, float *parent_buf) +static bool scene_audio_render_internal(struct obs_scene *scene, struct obs_scene *parent, uint64_t *ts_out, + struct obs_source_audio_mix *audio_output, uint32_t mixers, size_t channels, + size_t sample_rate, float *parent_buf) { uint64_t timestamp = 0; float buf[AUDIO_OUTPUT_FRAMES]; @@ -1732,17 +1603,13 @@ static bool scene_audio_render_internal( struct obs_source *source; if (item->visible && transition_active(item->show_transition)) source = item->show_transition; - else if (!item->visible && - transition_active(item->hide_transition)) + else if (!item->visible && transition_active(item->hide_transition)) source = item->hide_transition; else source = item->source; - if (!obs_source_audio_pending(source) && - (item->visible || - transition_active(item->hide_transition))) { - uint64_t source_ts = - obs_source_get_audio_timestamp(source); + if (!obs_source_audio_pending(source) && (item->visible || transition_active(item->hide_transition))) { + uint64_t source_ts = obs_source_get_audio_timestamp(source); if (source_ts && (!timestamp || source_ts < timestamp)) timestamp = source_ts; @@ -1774,14 +1641,12 @@ static bool scene_audio_render_internal( if (item->visible && transition_active(item->show_transition)) source = item->show_transition; - else if (!item->visible && - transition_active(item->hide_transition)) + else if (!item->visible && transition_active(item->hide_transition)) source = item->hide_transition; else source = item->source; - apply_buf = apply_scene_item_volume(item, buf, timestamp, - sample_rate); + apply_buf = apply_scene_item_volume(item, buf, timestamp, sample_rate); if (obs_source_audio_pending(source)) { item = item->next; @@ -1794,16 +1659,14 @@ static bool scene_audio_render_internal( continue; } - pos = (size_t)ns_to_audio_frames(sample_rate, - source_ts - timestamp); + pos = (size_t)ns_to_audio_frames(sample_rate, source_ts - timestamp); if (pos >= AUDIO_OUTPUT_FRAMES) { item = item->next; continue; } - if (!apply_buf && !item->visible && - !transition_active(item->hide_transition)) { + if (!apply_buf && !item->visible && !transition_active(item->hide_transition)) { item = item->next; continue; } @@ -1812,16 +1675,12 @@ static bool scene_audio_render_internal( /* Update buf so that parent mute state applies to all current * scene items as well */ - if (parent_buf && - (!apply_buf || - memcmp(buf, parent_buf, sizeof(float) * count) != 0)) { + if (parent_buf && (!apply_buf || memcmp(buf, parent_buf, sizeof(float) * count) != 0)) { for (size_t i = 0; i < count; i++) { if (!apply_buf) { buf[i] = parent_buf[i]; } else { - buf[i] = buf[i] < parent_buf[i] - ? buf[i] - : parent_buf[i]; + buf[i] = buf[i] < parent_buf[i] ? buf[i] : parent_buf[i]; } } @@ -1830,11 +1689,8 @@ static bool scene_audio_render_internal( /* If "source" is a group/scene and has no transition, * add their items to the current list */ - if (source == item->source && (obs_source_is_group(source) || - obs_source_is_scene(source))) { - scene_audio_render_internal(source->context.data, - mix_scene, NULL, NULL, 0, 0, - sample_rate, + if (source == item->source && (obs_source_is_group(source) || obs_source_is_scene(source))) { + scene_audio_render_internal(source->context.data, mix_scene, NULL, NULL, 0, 0, sample_rate, apply_buf ? buf : NULL); item = item->next; continue; @@ -1845,14 +1701,12 @@ static bool scene_audio_render_internal( if (!source_mix) { source_mix = da_push_back_new(mix_scene->mix_sources); source_mix->source = item->source; - source_mix->transition = source != item->source ? source - : NULL; + source_mix->transition = source != item->source ? source : NULL; source_mix->apply_buf = apply_buf; source_mix->pos = pos; source_mix->count = count; if (apply_buf) { - memcpy(source_mix->buf, buf, - sizeof(float) * source_mix->count); + memcpy(source_mix->buf, buf, sizeof(float) * source_mix->count); } } else { /* Only transition audio if there are no @@ -1861,13 +1715,11 @@ static bool scene_audio_render_internal( source_mix->transition = NULL; /* Only apply buf to mix if all scene items for this * source require it. */ - source_mix->apply_buf = source_mix->apply_buf && - apply_buf; + source_mix->apply_buf = source_mix->apply_buf && apply_buf; /* Update buf so that only highest value across all * items is used. */ if (source_mix->apply_buf && - memcmp(source_mix->buf, buf, - source_mix->count * sizeof(float)) != 0) { + memcmp(source_mix->buf, buf, source_mix->count * sizeof(float)) != 0) { for (size_t i = 0; i < source_mix->count; i++) { if (buf[i] > source_mix->buf[i]) source_mix->buf[i] = buf[i]; @@ -1884,11 +1736,8 @@ static bool scene_audio_render_internal( } for (size_t i = 0; i < scene->mix_sources.num; i++) { - struct scene_source_mix *source_mix = - &scene->mix_sources.array[i]; - obs_source_get_audio_mix(source_mix->transition - ? source_mix->transition - : source_mix->source, + struct scene_source_mix *source_mix = &scene->mix_sources.array[i]; + obs_source_get_audio_mix(source_mix->transition ? source_mix->transition : source_mix->source, &child_audio); for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { @@ -1900,13 +1749,10 @@ static bool scene_audio_render_internal( float *in = child_audio.output[mix].data[ch]; if (source_mix->apply_buf) - mix_audio_with_buf(out, in, - source_mix->buf, - source_mix->pos, + mix_audio_with_buf(out, in, source_mix->buf, source_mix->pos, source_mix->count); else - mix_audio(out, in, source_mix->pos, - source_mix->count); + mix_audio(out, in, source_mix->pos, source_mix->count); } } } @@ -1919,19 +1765,14 @@ static bool scene_audio_render_internal( return true; } -static bool scene_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool scene_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio_output, uint32_t mixers, + size_t channels, size_t sample_rate) { struct obs_scene *scene = data; - return scene_audio_render_internal(scene, NULL, ts_out, audio_output, - mixers, channels, sample_rate, NULL); + return scene_audio_render_internal(scene, NULL, ts_out, audio_output, mixers, channels, sample_rate, NULL); } -enum gs_color_space -scene_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +enum gs_color_space scene_video_get_color_space(void *data, size_t count, const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(count); @@ -1940,8 +1781,7 @@ scene_video_get_color_space(void *data, size_t count, enum gs_color_space space = GS_CS_SRGB; struct obs_video_info ovi; if (obs_get_video_info(&ovi)) { - if (ovi.colorspace == VIDEO_CS_2100_PQ || - ovi.colorspace == VIDEO_CS_2100_HLG) + if (ovi.colorspace == VIDEO_CS_2100_PQ || ovi.colorspace == VIDEO_CS_2100_HLG) space = GS_CS_709_EXTENDED; } @@ -1951,8 +1791,7 @@ scene_video_get_color_space(void *data, size_t count, const struct obs_source_info scene_info = { .id = "scene", .type = OBS_SOURCE_TYPE_SCENE, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_COMPOSITE | OBS_SOURCE_DO_NOT_DUPLICATE | + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_COMPOSITE | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, .get_name = scene_getname, .create = scene_create, @@ -1972,8 +1811,7 @@ const struct obs_source_info scene_info = { const struct obs_source_info group_info = { .id = "group", .type = OBS_SOURCE_TYPE_SCENE, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_COMPOSITE | OBS_SOURCE_SRGB, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_COMPOSITE | OBS_SOURCE_SRGB, .get_name = group_getname, .create = scene_create, .destroy = scene_destroy, @@ -2020,8 +1858,7 @@ static obs_source_t *get_child_at_idx(obs_scene_t *scene, size_t idx) return item ? item->source : NULL; } -static inline obs_source_t *dup_child(obs_scene_item_ptr_array_t *old_items, - size_t idx, obs_scene_t *new_scene, +static inline obs_source_t *dup_child(obs_scene_item_ptr_array_t *old_items, size_t idx, obs_scene_t *new_scene, bool private) { obs_source_t *source; @@ -2039,8 +1876,7 @@ static inline obs_source_t *dup_child(obs_scene_item_ptr_array_t *old_items, } } - return obs_source_duplicate( - source, private ? obs_source_get_name(source) : NULL, private); + return obs_source_duplicate(source, private ? obs_source_get_name(source) : NULL, private); } static inline obs_source_t *new_ref(obs_source_t *source) @@ -2048,10 +1884,8 @@ static inline obs_source_t *new_ref(obs_source_t *source) return obs_source_get_ref(source); } -static inline void duplicate_item_data(struct obs_scene_item *dst, - struct obs_scene_item *src, - bool defer_texture_update, - bool duplicate_hotkeys) +static inline void duplicate_item_data(struct obs_scene_item *dst, struct obs_scene_item *src, + bool defer_texture_update, bool duplicate_hotkeys) { struct obs_scene *dst_scene = dst->parent; @@ -2079,16 +1913,14 @@ static inline void duplicate_item_data(struct obs_scene_item *dst, dst->bounds_crop = src->bounds_crop; if (src->show_transition) { - obs_source_t *transition = obs_source_duplicate( - src->show_transition, - obs_source_get_name(src->show_transition), true); + obs_source_t *transition = + obs_source_duplicate(src->show_transition, obs_source_get_name(src->show_transition), true); obs_sceneitem_set_transition(dst, true, transition); obs_source_release(transition); } if (src->hide_transition) { - obs_source_t *transition = obs_source_duplicate( - src->hide_transition, - obs_source_get_name(src->hide_transition), true); + obs_source_t *transition = + obs_source_duplicate(src->hide_transition, obs_source_get_name(src->hide_transition), true); obs_sceneitem_set_transition(dst, false, transition); obs_source_release(transition); } @@ -2107,8 +1939,7 @@ static inline void duplicate_item_data(struct obs_scene_item *dst, /* Fix scene item ID */ dstr_printf(&show, "libobs.show_scene_item.%" PRIi64, dst->id); dstr_printf(&hide, "libobs.hide_scene_item.%" PRIi64, dst->id); - obs_hotkey_pair_set_names(dst->toggle_visibility, show.array, - hide.array); + obs_hotkey_pair_set_names(dst->toggle_visibility, show.array, hide.array); obs_data_array_release(data0); obs_data_array_release(data1); @@ -2126,8 +1957,7 @@ static inline void duplicate_item_data(struct obs_scene_item *dst, obs_data_apply(dst->private_settings, src->private_settings); } -obs_scene_t *obs_scene_duplicate(obs_scene_t *scene, const char *name, - enum obs_scene_duplicate_type type) +obs_scene_t *obs_scene_duplicate(obs_scene_t *scene, const char *name, enum obs_scene_duplicate_type type) { bool make_unique = ((int)type & (1 << 0)) != 0; bool make_private = ((int)type & (1 << 1)) != 0; @@ -2156,14 +1986,12 @@ obs_scene_t *obs_scene_duplicate(obs_scene_t *scene, const char *name, /* --------------------------------- */ - new_scene = make_private - ? create_private_id(scene->source->info.id, name) - : create_id(scene->source->info.id, name); + new_scene = make_private ? create_private_id(scene->source->info.id, name) + : create_id(scene->source->info.id, name); obs_source_copy_filters(new_scene->source, scene->source); - obs_data_apply(new_scene->source->private_settings, - scene->source->private_settings); + obs_data_apply(new_scene->source->private_settings, scene->source->private_settings); /* never duplicate sub-items for groups */ if (scene->is_group) @@ -2171,13 +1999,10 @@ obs_scene_t *obs_scene_duplicate(obs_scene_t *scene, const char *name, for (size_t i = 0; i < items.num; i++) { item = items.array[i]; - source = make_unique - ? dup_child(&items, i, new_scene, make_private) - : new_ref(item->source); + source = make_unique ? dup_child(&items, i, new_scene, make_private) : new_ref(item->source); if (source) { - struct obs_scene_item *new_item = - obs_scene_add(new_scene, source); + struct obs_scene_item *new_item = obs_scene_add(new_scene, source); if (!new_item) { obs_source_release(source); @@ -2264,8 +2089,7 @@ obs_sceneitem_t *obs_scene_find_source(obs_scene_t *scene, const char *name) return item; } -obs_sceneitem_t *obs_scene_find_source_recursive(obs_scene_t *scene, - const char *name) +obs_sceneitem_t *obs_scene_find_source_recursive(obs_scene_t *scene, const char *name) { struct obs_scene_item *item; @@ -2281,8 +2105,7 @@ obs_sceneitem_t *obs_scene_find_source_recursive(obs_scene_t *scene, if (item->is_group) { obs_scene_t *group = item->source->context.data; - obs_sceneitem_t *child = - obs_scene_find_source(group, name); + obs_sceneitem_t *child = obs_scene_find_source(group, name); if (child) { item = child; break; @@ -2302,8 +2125,7 @@ struct sceneitem_check { obs_sceneitem_t *item_out; }; -bool check_sceneitem_exists(obs_scene_t *scene, obs_sceneitem_t *item, - void *vp_check) +bool check_sceneitem_exists(obs_scene_t *scene, obs_sceneitem_t *item, void *vp_check) { UNUSED_PARAMETER(scene); struct sceneitem_check *check = (struct sceneitem_check *)vp_check; @@ -2316,8 +2138,7 @@ bool check_sceneitem_exists(obs_scene_t *scene, obs_sceneitem_t *item, return true; } -obs_sceneitem_t *obs_scene_sceneitem_from_source(obs_scene_t *scene, - obs_source_t *source) +obs_sceneitem_t *obs_scene_sceneitem_from_source(obs_scene_t *scene, obs_source_t *source) { struct sceneitem_check check = {source, NULL}; obs_scene_enum_items(scene, check_sceneitem_exists, (void *)&check); @@ -2346,10 +2167,7 @@ obs_sceneitem_t *obs_scene_find_sceneitem_by_id(obs_scene_t *scene, int64_t id) return item; } -void obs_scene_enum_items(obs_scene_t *scene, - bool (*callback)(obs_scene_t *, obs_sceneitem_t *, - void *), - void *param) +void obs_scene_enum_items(obs_scene_t *scene, bool (*callback)(obs_scene_t *, obs_sceneitem_t *, void *), void *param) { struct obs_scene_item *item; @@ -2381,16 +2199,14 @@ static obs_sceneitem_t *sceneitem_get_ref(obs_sceneitem_t *si) { long owners = os_atomic_load_long(&si->ref); while (owners > 0) { - if (os_atomic_compare_exchange_long(&si->ref, &owners, - owners + 1)) { + if (os_atomic_compare_exchange_long(&si->ref, &owners, owners + 1)) { return si; } } return NULL; } -static bool hotkey_show_sceneitem(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *hotkey, bool pressed) +static bool hotkey_show_sceneitem(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -2406,8 +2222,7 @@ static bool hotkey_show_sceneitem(void *data, obs_hotkey_pair_id id, return false; } -static bool hotkey_hide_sceneitem(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *hotkey, bool pressed) +static bool hotkey_hide_sceneitem(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -2423,8 +2238,7 @@ static bool hotkey_hide_sceneitem(void *data, obs_hotkey_pair_id id, return false; } -static void init_hotkeys(obs_scene_t *scene, obs_sceneitem_t *item, - const char *name) +static void init_hotkeys(obs_scene_t *scene, obs_sceneitem_t *item, const char *name) { struct obs_data_array *hotkey_array; obs_data_t *hotkey_data = scene->source->context.hotkey_data; @@ -2458,10 +2272,9 @@ static void init_hotkeys(obs_scene_t *scene, obs_sceneitem_t *item, obs_data_array_release(hotkey_array); } - item->toggle_visibility = obs_hotkey_pair_register_source( - scene->source, show.array, show_desc.array, hide.array, - hide_desc.array, hotkey_show_sceneitem, hotkey_hide_sceneitem, - item, item); + item->toggle_visibility = obs_hotkey_pair_register_source(scene->source, show.array, show_desc.array, + hide.array, hide_desc.array, hotkey_show_sceneitem, + hotkey_hide_sceneitem, item, item); dstr_free(&show); dstr_free(&hide); @@ -2470,8 +2283,7 @@ static void init_hotkeys(obs_scene_t *scene, obs_sceneitem_t *item, dstr_free(&hide_desc); } -static void sceneitem_rename_hotkey(const obs_sceneitem_t *scene_item, - const char *new_name) +static void sceneitem_rename_hotkey(const obs_sceneitem_t *scene_item, const char *new_name) { struct dstr show_desc = {0}; struct dstr hide_desc = {0}; @@ -2481,8 +2293,7 @@ static void sceneitem_rename_hotkey(const obs_sceneitem_t *scene_item, dstr_copy(&hide_desc, obs->hotkeys.sceneitem_hide); dstr_replace(&hide_desc, "%1", new_name); - obs_hotkey_pair_set_descriptions(scene_item->toggle_visibility, - show_desc.array, hide_desc.array); + obs_hotkey_pair_set_descriptions(scene_item->toggle_visibility, show_desc.array, hide_desc.array); dstr_free(&show_desc); dstr_free(&hide_desc); @@ -2498,21 +2309,17 @@ static void sceneitem_renamed(void *param, calldata_t *data) static inline bool source_has_audio(obs_source_t *source) { - return (source->info.output_flags & - (OBS_SOURCE_AUDIO | OBS_SOURCE_COMPOSITE)) != 0; + return (source->info.output_flags & (OBS_SOURCE_AUDIO | OBS_SOURCE_COMPOSITE)) != 0; } -static obs_sceneitem_t *obs_scene_add_internal(obs_scene_t *scene, - obs_source_t *source, - obs_sceneitem_t *insert_after, +static obs_sceneitem_t *obs_scene_add_internal(obs_scene_t *scene, obs_source_t *source, obs_sceneitem_t *insert_after, int64_t id) { struct obs_scene_item *last; struct obs_scene_item *item; pthread_mutex_t mutex; - struct item_action action = {.visible = true, - .timestamp = os_gettime_ns()}; + struct item_action action = {.visible = true, .timestamp = os_gettime_ns()}; if (!scene) return NULL; @@ -2556,8 +2363,7 @@ static obs_sceneitem_t *obs_scene_add_internal(obs_scene_t *scene, item->absolute_coordinates = scene->absolute_coordinates; os_atomic_set_long(&item->active_refs, 1); vec2_set(&item->scale, 1.0f, 1.0f); - vec2_set(&item->scale_ref, (float)scene_getwidth(scene), - (float)scene_getheight(scene)); + vec2_set(&item->scale_ref, (float)scene_getwidth(scene), (float)scene_getheight(scene)); matrix4_identity(&item->draw_transform); matrix4_identity(&item->box_transform); @@ -2599,8 +2405,7 @@ static obs_sceneitem_t *obs_scene_add_internal(obs_scene_t *scene, if (!scene->source->context.private) init_hotkeys(scene, item, obs_source_get_name(source)); - signal_handler_connect(obs_source_get_signal_handler(source), "rename", - sceneitem_renamed, item); + signal_handler_connect(obs_source_get_signal_handler(source), "rename", sceneitem_renamed, item); return item; @@ -2621,8 +2426,7 @@ obs_sceneitem_t *obs_scene_add(obs_scene_t *scene, obs_source_t *source) calldata_init_fixed(¶ms, stack, sizeof(stack)); calldata_set_ptr(¶ms, "scene", scene); calldata_set_ptr(¶ms, "item", item); - signal_handler_signal(scene->source->context.signals, "item_add", - ¶ms); + signal_handler_signal(scene->source->context.signals, "item_add", ¶ms); return item; } @@ -2637,9 +2441,8 @@ static void obs_sceneitem_destroy(obs_sceneitem_t *item) obs_data_release(item->private_settings); obs_hotkey_pair_unregister(item->toggle_visibility); pthread_mutex_destroy(&item->actions_mutex); - signal_handler_disconnect( - obs_source_get_signal_handler(item->source), "rename", - sceneitem_renamed, item); + signal_handler_disconnect(obs_source_get_signal_handler(item->source), "rename", sceneitem_renamed, + item); if (item->show_transition) obs_source_release(item->show_transition); if (item->hide_transition) @@ -2726,8 +2529,7 @@ obs_source_t *obs_sceneitem_get_source(const obs_sceneitem_t *item) return item ? item->source : NULL; } -static void signal_parent(obs_scene_t *parent, const char *command, - calldata_t *params) +static void signal_parent(obs_scene_t *parent, const char *command, calldata_t *params) { calldata_set_ptr(params, "scene", parent); signal_handler_signal(parent->source->context.signals, command, params); @@ -2739,8 +2541,7 @@ struct passthrough { bool all_items; }; -bool save_transform_states(obs_scene_t *scene, obs_sceneitem_t *item, - void *vp_pass) +bool save_transform_states(obs_scene_t *scene, obs_sceneitem_t *item, void *vp_pass) { struct passthrough *pass = (struct passthrough *)vp_pass; if (obs_sceneitem_selected(item) || pass->all_items) { @@ -2786,17 +2587,12 @@ bool save_transform_states(obs_scene_t *scene, obs_sceneitem_t *item, obs_data_t *temp = obs_data_create(); obs_data_array_t *nids = obs_data_array_create(); - obs_data_set_string(temp, "scene_name", - obs_source_get_name(item_source)); + obs_data_set_string(temp, "scene_name", obs_source_get_name(item_source)); obs_data_set_bool(temp, "is_group", true); - obs_data_set_string( - temp, "group_parent", - obs_source_get_name(obs_scene_get_source(scene))); + obs_data_set_string(temp, "group_parent", obs_source_get_name(obs_scene_get_source(scene))); - struct passthrough npass = {nids, pass->scenes_and_groups, - pass->all_items}; - obs_sceneitem_group_enum_items(item, save_transform_states, - (void *)&npass); + struct passthrough npass = {nids, pass->scenes_and_groups, pass->all_items}; + obs_sceneitem_group_enum_items(item, save_transform_states, (void *)&npass); obs_data_set_array(temp, "items", nids); @@ -2819,10 +2615,8 @@ obs_data_t *obs_scene_save_transform_states(obs_scene_t *scene, bool all_items) obs_data_t *temp = obs_data_create(); - obs_data_set_string(temp, "scene_name", - obs_source_get_name(obs_scene_get_source(scene))); - obs_data_set_string(temp, "scene_uuid", - obs_source_get_uuid(obs_scene_get_source(scene))); + obs_data_set_string(temp, "scene_name", obs_source_get_name(obs_scene_get_source(scene))); + obs_data_set_string(temp, "scene_uuid", obs_source_get_uuid(obs_scene_get_source(scene))); obs_data_set_bool(temp, "is_group", false); obs_scene_enum_items(scene, save_transform_states, (void *)&pass); @@ -2851,10 +2645,8 @@ void load_transform_states(obs_data_t *temp, void *vp_scene) obs_data_get_vec2(temp, "scale", &info.scale); info.rot = (float)obs_data_get_double(temp, "rot"); info.alignment = (uint32_t)obs_data_get_int(temp, "alignment"); - info.bounds_type = - (enum obs_bounds_type)obs_data_get_int(temp, "bounds_type"); - info.bounds_alignment = - (uint32_t)obs_data_get_int(temp, "bounds_alignment"); + info.bounds_type = (enum obs_bounds_type)obs_data_get_int(temp, "bounds_type"); + info.bounds_alignment = (uint32_t)obs_data_get_int(temp, "bounds_alignment"); obs_data_get_vec2(temp, "bounds", &info.bounds); info.crop_to_bounds = obs_data_get_bool(temp, "crop_to_bounds"); crop.top = (int)obs_data_get_int(temp, "top"); @@ -2873,16 +2665,13 @@ void load_transform_states(obs_data_t *temp, void *vp_scene) void iterate_scenes_and_groups_transform_states(obs_data_t *data, void *vp) { obs_data_array_t *items = obs_data_get_array(data, "items"); - obs_source_t *scene_source = - obs_get_source_by_name(obs_data_get_string(data, "scene_name")); + obs_source_t *scene_source = obs_get_source_by_name(obs_data_get_string(data, "scene_name")); obs_scene_t *scene = obs_scene_from_source(scene_source); if (obs_data_get_bool(data, "is_group")) { - obs_source_t *parent_source = obs_get_source_by_name( - obs_data_get_string(data, "group_parent")); + obs_source_t *parent_source = obs_get_source_by_name(obs_data_get_string(data, "group_parent")); obs_scene_t *parent = obs_scene_from_source(parent_source); - obs_sceneitem_t *group = obs_scene_get_group( - parent, obs_data_get_string(data, "scene_name")); + obs_sceneitem_t *group = obs_scene_get_group(parent, obs_data_get_string(data, "scene_name")); scene = obs_sceneitem_group_get_scene(group); obs_source_release(parent_source); @@ -2900,11 +2689,9 @@ void obs_scene_load_transform_states(const char *data) { obs_data_t *dat = obs_data_create_from_json(data); - obs_data_array_t *scenes_and_groups = - obs_data_get_array(dat, "scenes_and_groups"); + obs_data_array_t *scenes_and_groups = obs_data_get_array(dat, "scenes_and_groups"); - obs_data_array_enum(scenes_and_groups, - iterate_scenes_and_groups_transform_states, NULL); + obs_data_array_enum(scenes_and_groups, iterate_scenes_and_groups_transform_states, NULL); obs_data_release(dat); obs_data_array_release(scenes_and_groups); @@ -2952,8 +2739,7 @@ void obs_sceneitem_set_pos(obs_sceneitem_t *item, const struct vec2 *pos) } } -void obs_sceneitem_set_relative_pos(obs_sceneitem_t *item, - const struct vec2 *pos) +void obs_sceneitem_set_relative_pos(obs_sceneitem_t *item, const struct vec2 *pos) { if (item) { if (!item->absolute_coordinates) @@ -3017,8 +2803,7 @@ static inline void signal_refresh(obs_scene_t *scene) signal_parent(scene, command, ¶ms); } -void obs_sceneitem_set_order(obs_sceneitem_t *item, - enum obs_order_movement movement) +void obs_sceneitem_set_order(obs_sceneitem_t *item, enum obs_order_movement movement) { if (!item) return; @@ -3115,8 +2900,7 @@ void obs_sceneitem_set_order_position(obs_sceneitem_t *item, int position) obs_scene_release(scene); } -void obs_sceneitem_set_bounds_type(obs_sceneitem_t *item, - enum obs_bounds_type type) +void obs_sceneitem_set_bounds_type(obs_sceneitem_t *item, enum obs_bounds_type type) { if (item) { item->bounds_type = type; @@ -3124,8 +2908,7 @@ void obs_sceneitem_set_bounds_type(obs_sceneitem_t *item, } } -void obs_sceneitem_set_bounds_alignment(obs_sceneitem_t *item, - uint32_t alignment) +void obs_sceneitem_set_bounds_alignment(obs_sceneitem_t *item, uint32_t alignment) { if (item) { item->bounds_align = alignment; @@ -3153,8 +2936,7 @@ void obs_sceneitem_set_bounds(obs_sceneitem_t *item, const struct vec2 *bounds) } } -void obs_sceneitem_set_relative_bounds(obs_sceneitem_t *item, - const struct vec2 *bounds) +void obs_sceneitem_set_relative_bounds(obs_sceneitem_t *item, const struct vec2 *bounds) { if (item) { if (!item->absolute_coordinates) @@ -3177,8 +2959,7 @@ void obs_sceneitem_get_pos(const obs_sceneitem_t *item, struct vec2 *pos) vec2_copy(pos, &item->pos); } -void obs_sceneitem_get_relative_pos(const obs_sceneitem_t *item, - struct vec2 *pos) +void obs_sceneitem_get_relative_pos(const obs_sceneitem_t *item, struct vec2 *pos) { if (!item) return; @@ -3236,8 +3017,7 @@ void obs_sceneitem_get_bounds(const obs_sceneitem_t *item, struct vec2 *bounds) vec2_copy(bounds, &item->bounds); } -void obs_sceneitem_get_relative_bounds(const obs_sceneitem_t *item, - struct vec2 *bounds) +void obs_sceneitem_get_relative_bounds(const obs_sceneitem_t *item, struct vec2 *bounds) { if (!item) return; @@ -3248,8 +3028,7 @@ void obs_sceneitem_get_relative_bounds(const obs_sceneitem_t *item, size_from_absolute(bounds, &item->bounds, item); } -static inline void scene_item_get_info_internal(const obs_sceneitem_t *item, - struct obs_transform_info *info) +static inline void scene_item_get_info_internal(const obs_sceneitem_t *item, struct obs_transform_info *info) { if (!item->absolute_coordinates) { pos_to_absolute(&info->pos, &item->pos, item); @@ -3266,16 +3045,14 @@ static inline void scene_item_get_info_internal(const obs_sceneitem_t *item, info->bounds_alignment = item->bounds_align; } -void obs_sceneitem_get_info(const obs_sceneitem_t *item, - struct obs_transform_info *info) +void obs_sceneitem_get_info(const obs_sceneitem_t *item, struct obs_transform_info *info) { if (item && info) { scene_item_get_info_internal(item, info); } } -void obs_sceneitem_get_info2(const obs_sceneitem_t *item, - struct obs_transform_info *info) +void obs_sceneitem_get_info2(const obs_sceneitem_t *item, struct obs_transform_info *info) { if (item && info) { scene_item_get_info_internal(item, info); @@ -3283,8 +3060,7 @@ void obs_sceneitem_get_info2(const obs_sceneitem_t *item, } } -void obs_sceneitem_get_info3(const obs_sceneitem_t *item, - struct obs_transform_info *info) +void obs_sceneitem_get_info3(const obs_sceneitem_t *item, struct obs_transform_info *info) { if (item && info) { if (!item->absolute_coordinates) { @@ -3304,9 +3080,7 @@ void obs_sceneitem_get_info3(const obs_sceneitem_t *item, } } -static inline void -scene_item_set_info_internal(obs_sceneitem_t *item, - const struct obs_transform_info *info) +static inline void scene_item_set_info_internal(obs_sceneitem_t *item, const struct obs_transform_info *info) { if (!item->absolute_coordinates) { pos_from_absolute(&item->pos, &info->pos, item); @@ -3328,8 +3102,7 @@ scene_item_set_info_internal(obs_sceneitem_t *item, item->bounds_align = info->bounds_alignment; } -void obs_sceneitem_set_info(obs_sceneitem_t *item, - const struct obs_transform_info *info) +void obs_sceneitem_set_info(obs_sceneitem_t *item, const struct obs_transform_info *info) { if (item && info) { scene_item_set_info_internal(item, info); @@ -3337,8 +3110,7 @@ void obs_sceneitem_set_info(obs_sceneitem_t *item, } } -void obs_sceneitem_set_info2(obs_sceneitem_t *item, - const struct obs_transform_info *info) +void obs_sceneitem_set_info2(obs_sceneitem_t *item, const struct obs_transform_info *info) { if (item && info) { scene_item_set_info_internal(item, info); @@ -3347,23 +3119,19 @@ void obs_sceneitem_set_info2(obs_sceneitem_t *item, } } -void obs_sceneitem_set_info3(obs_sceneitem_t *item, - const struct obs_transform_info *info) +void obs_sceneitem_set_info3(obs_sceneitem_t *item, const struct obs_transform_info *info) { if (item && info) { if (!item->absolute_coordinates) { item->pos = info->pos; item->bounds = info->bounds; - if (isfinite(info->scale.x) && - isfinite(info->scale.y)) { - item_relative_scale(&item->scale, &info->scale, - item); + if (isfinite(info->scale.x) && isfinite(info->scale.y)) { + item_relative_scale(&item->scale, &info->scale, item); } } else { pos_to_absolute(&item->pos, &info->pos, item); size_to_absolute(&item->bounds, &info->bounds, item); - if (isfinite(info->scale.x) && - isfinite(info->scale.y)) { + if (isfinite(info->scale.x) && isfinite(info->scale.y)) { item_canvas_scale(&item->scale, item); } } @@ -3377,22 +3145,19 @@ void obs_sceneitem_set_info3(obs_sceneitem_t *item, } } -void obs_sceneitem_get_draw_transform(const obs_sceneitem_t *item, - struct matrix4 *transform) +void obs_sceneitem_get_draw_transform(const obs_sceneitem_t *item, struct matrix4 *transform) { if (item) matrix4_copy(transform, &item->draw_transform); } -void obs_sceneitem_get_box_transform(const obs_sceneitem_t *item, - struct matrix4 *transform) +void obs_sceneitem_get_box_transform(const obs_sceneitem_t *item, struct matrix4 *transform) { if (item) matrix4_copy(transform, &item->box_transform); } -void obs_sceneitem_get_box_scale(const obs_sceneitem_t *item, - struct vec2 *scale) +void obs_sceneitem_get_box_scale(const obs_sceneitem_t *item, struct vec2 *scale) { if (item) *scale = item->box_scale; @@ -3403,8 +3168,7 @@ bool obs_sceneitem_visible(const obs_sceneitem_t *item) return item ? item->user_visible : false; } -static bool group_item_transition(obs_scene_t *scene, obs_sceneitem_t *item, - void *param) +static bool group_item_transition(obs_scene_t *scene, obs_sceneitem_t *item, void *param) { if (!param || !item) return true; @@ -3419,8 +3183,7 @@ bool obs_sceneitem_set_visible(obs_sceneitem_t *item, bool visible) { struct calldata cd; uint8_t stack[256]; - struct item_action action = {.visible = visible, - .timestamp = os_gettime_ns()}; + struct item_action action = {.visible = visible, .timestamp = os_gettime_ns()}; if (!item) return false; @@ -3433,15 +3196,13 @@ bool obs_sceneitem_set_visible(obs_sceneitem_t *item, bool visible) obs_sceneitem_do_transition(item, visible); if (obs_sceneitem_is_group(item)) - obs_sceneitem_group_enum_items(item, group_item_transition, - &visible); + obs_sceneitem_group_enum_items(item, group_item_transition, &visible); item->user_visible = visible; if (visible) { if (os_atomic_inc_long(&item->active_refs) == 1) { - if (!obs_source_add_active_child(item->parent->source, - item->source)) { + if (!obs_source_add_active_child(item->parent->source, item->source)) { os_atomic_dec_long(&item->active_refs); return false; } @@ -3494,8 +3255,7 @@ bool obs_sceneitem_set_locked(obs_sceneitem_t *item, bool lock) return true; } -static bool sceneitems_match(obs_scene_t *scene, obs_sceneitem_t *const *items, - size_t size, bool *order_matches) +static bool sceneitems_match(obs_scene_t *scene, obs_sceneitem_t *const *items, size_t size, bool *order_matches) { obs_sceneitem_t *item = scene->first_item; @@ -3523,9 +3283,7 @@ static bool sceneitems_match(obs_scene_t *scene, obs_sceneitem_t *const *items, return count == size; } -bool obs_scene_reorder_items(obs_scene_t *scene, - obs_sceneitem_t *const *item_order, - size_t item_order_size) +bool obs_scene_reorder_items(obs_scene_t *scene, obs_sceneitem_t *const *item_order, size_t item_order_size) { if (!scene || !item_order_size) return false; @@ -3537,9 +3295,7 @@ bool obs_scene_reorder_items(obs_scene_t *scene, full_lock(scene); bool order_matches = true; - if (!sceneitems_match(scene, item_order, item_order_size, - &order_matches) || - order_matches) { + if (!sceneitems_match(scene, item_order, item_order_size, &order_matches) || order_matches) { full_unlock(scene); obs_scene_release(scene); return false; @@ -3565,8 +3321,7 @@ bool obs_scene_reorder_items(obs_scene_t *scene, return true; } -void obs_scene_atomic_update(obs_scene_t *scene, - obs_scene_atomic_update_func func, void *data) +void obs_scene_atomic_update(obs_scene_t *scene, obs_scene_atomic_update_func func, void *data) { if (!scene) return; @@ -3581,15 +3336,13 @@ void obs_scene_atomic_update(obs_scene_t *scene, obs_scene_release(scene); } -static inline bool crop_equal(const struct obs_sceneitem_crop *crop1, - const struct obs_sceneitem_crop *crop2) +static inline bool crop_equal(const struct obs_sceneitem_crop *crop1, const struct obs_sceneitem_crop *crop2) { - return crop1->left == crop2->left && crop1->right == crop2->right && - crop1->top == crop2->top && crop1->bottom == crop2->bottom; + return crop1->left == crop2->left && crop1->right == crop2->right && crop1->top == crop2->top && + crop1->bottom == crop2->bottom; } -void obs_sceneitem_set_crop(obs_sceneitem_t *item, - const struct obs_sceneitem_crop *crop) +void obs_sceneitem_set_crop(obs_sceneitem_t *item, const struct obs_sceneitem_crop *crop) { if (!obs_ptr_valid(item, "obs_sceneitem_set_crop")) return; @@ -3612,8 +3365,7 @@ void obs_sceneitem_set_crop(obs_sceneitem_t *item, os_atomic_set_bool(&item->update_transform, true); } -void obs_sceneitem_get_crop(const obs_sceneitem_t *item, - struct obs_sceneitem_crop *crop) +void obs_sceneitem_get_crop(const obs_sceneitem_t *item, struct obs_sceneitem_crop *crop) { if (!obs_ptr_valid(item, "obs_sceneitem_get_crop")) return; @@ -3623,8 +3375,7 @@ void obs_sceneitem_get_crop(const obs_sceneitem_t *item, memcpy(crop, &item->crop, sizeof(*crop)); } -void obs_sceneitem_set_scale_filter(obs_sceneitem_t *item, - enum obs_scale_type filter) +void obs_sceneitem_set_scale_filter(obs_sceneitem_t *item, enum obs_scale_type filter) { if (!obs_ptr_valid(item, "obs_sceneitem_set_scale_filter")) return; @@ -3636,13 +3387,10 @@ void obs_sceneitem_set_scale_filter(obs_sceneitem_t *item, enum obs_scale_type obs_sceneitem_get_scale_filter(obs_sceneitem_t *item) { - return obs_ptr_valid(item, "obs_sceneitem_get_scale_filter") - ? item->scale_filter - : OBS_SCALE_DISABLE; + return obs_ptr_valid(item, "obs_sceneitem_get_scale_filter") ? item->scale_filter : OBS_SCALE_DISABLE; } -void obs_sceneitem_set_blending_method(obs_sceneitem_t *item, - enum obs_blending_method method) +void obs_sceneitem_set_blending_method(obs_sceneitem_t *item, enum obs_blending_method method) { if (!obs_ptr_valid(item, "obs_sceneitem_set_blending_method")) return; @@ -3650,16 +3398,12 @@ void obs_sceneitem_set_blending_method(obs_sceneitem_t *item, item->blend_method = method; } -enum obs_blending_method -obs_sceneitem_get_blending_method(obs_sceneitem_t *item) +enum obs_blending_method obs_sceneitem_get_blending_method(obs_sceneitem_t *item) { - return obs_ptr_valid(item, "obs_sceneitem_get_blending_method") - ? item->blend_method - : OBS_BLEND_METHOD_DEFAULT; + return obs_ptr_valid(item, "obs_sceneitem_get_blending_method") ? item->blend_method : OBS_BLEND_METHOD_DEFAULT; } -void obs_sceneitem_set_blending_mode(obs_sceneitem_t *item, - enum obs_blending_type type) +void obs_sceneitem_set_blending_mode(obs_sceneitem_t *item, enum obs_blending_type type) { if (!obs_ptr_valid(item, "obs_sceneitem_set_blending_mode")) return; @@ -3671,9 +3415,7 @@ void obs_sceneitem_set_blending_mode(obs_sceneitem_t *item, enum obs_blending_type obs_sceneitem_get_blending_mode(obs_sceneitem_t *item) { - return obs_ptr_valid(item, "obs_sceneitem_get_blending_mode") - ? item->blend_type - : OBS_BLEND_NORMAL; + return obs_ptr_valid(item, "obs_sceneitem_get_blending_mode") ? item->blend_type : OBS_BLEND_NORMAL; } void obs_sceneitem_defer_update_begin(obs_sceneitem_t *item) @@ -3741,8 +3483,7 @@ static inline void transform_val(struct vec2 *v2, struct matrix4 *transform) v2->y = v.y; } -static void get_ungrouped_transform(obs_sceneitem_t *group, struct vec2 *pos, - struct vec2 *scale, float *rot) +static void get_ungrouped_transform(obs_sceneitem_t *group, struct vec2 *pos, struct vec2 *scale, float *rot) { struct matrix4 transform; struct matrix4 mat; @@ -3766,8 +3507,7 @@ static void get_ungrouped_transform(obs_sceneitem_t *group, struct vec2 *pos, *rot += group->rot; } -static void remove_group_transform(obs_sceneitem_t *group, - obs_sceneitem_t *item) +static void remove_group_transform(obs_sceneitem_t *group, obs_sceneitem_t *item) { obs_scene_t *parent = item->parent; if (!parent || !group) @@ -3797,17 +3537,14 @@ static void apply_group_transform(obs_sceneitem_t *item, obs_sceneitem_t *group) vec4_set(&mat.t, 0.0f, 0.0f, 0.0f, 1.0f); matrix4_mul(&mat, &mat, &transform); - item->scale.x = - vec4_len(&mat.x) * (item->scale.x > 0.0f ? 1.0f : -1.0f); - item->scale.y = - vec4_len(&mat.y) * (item->scale.y > 0.0f ? 1.0f : -1.0f); + item->scale.x = vec4_len(&mat.x) * (item->scale.x > 0.0f ? 1.0f : -1.0f); + item->scale.y = vec4_len(&mat.y) * (item->scale.y > 0.0f ? 1.0f : -1.0f); item->rot -= group->rot; update_item_transform(item, false); } -static bool resize_scene_base(obs_scene_t *scene, struct vec2 *minv, - struct vec2 *maxv, struct vec2 *scale) +static bool resize_scene_base(obs_scene_t *scene, struct vec2 *minv, struct vec2 *maxv, struct vec2 *scale) { vec2_set(minv, M_INFINITE, M_INFINITE); vec2_set(maxv, -M_INFINITE, -M_INFINITE); @@ -3921,14 +3658,12 @@ obs_sceneitem_t *obs_scene_add_group(obs_scene_t *scene, const char *name) return obs_scene_insert_group(scene, name, NULL, 0); } -obs_sceneitem_t *obs_scene_add_group2(obs_scene_t *scene, const char *name, - bool signal) +obs_sceneitem_t *obs_scene_add_group2(obs_scene_t *scene, const char *name, bool signal) { return obs_scene_insert_group2(scene, name, NULL, 0, signal); } -obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, const char *name, - obs_sceneitem_t **items, size_t count) +obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, const char *name, obs_sceneitem_t **items, size_t count) { if (!scene) return NULL; @@ -3943,8 +3678,7 @@ obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, const char *name, obs_scene_t *sub_scene = create_id("group", name); obs_sceneitem_t *last_item = items ? items[count - 1] : NULL; - obs_sceneitem_t *item = - obs_scene_add_internal(scene, sub_scene->source, last_item, 0); + obs_sceneitem_t *item = obs_scene_add_internal(scene, sub_scene->source, last_item, 0); if (!items || !count) { obs_scene_release(sub_scene); @@ -3985,8 +3719,7 @@ obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, const char *name, calldata_init_fixed(¶ms, stack, sizeof(stack)); calldata_set_ptr(¶ms, "scene", scene); calldata_set_ptr(¶ms, "item", item); - signal_handler_signal(scene->source->context.signals, "item_add", - ¶ms); + signal_handler_signal(scene->source->context.signals, "item_add", ¶ms); /* ------------------------- */ @@ -3994,12 +3727,10 @@ obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, const char *name, return item; } -obs_sceneitem_t *obs_scene_insert_group2(obs_scene_t *scene, const char *name, - obs_sceneitem_t **items, size_t count, +obs_sceneitem_t *obs_scene_insert_group2(obs_scene_t *scene, const char *name, obs_sceneitem_t **items, size_t count, bool signal) { - obs_sceneitem_t *item = - obs_scene_insert_group(scene, name, items, count); + obs_sceneitem_t *item = obs_scene_insert_group(scene, name, items, count); if (signal && item) signal_refresh(scene); return item; @@ -4067,8 +3798,7 @@ void obs_sceneitem_group_ungroup(obs_sceneitem_t *item) obs_sceneitem_t *dst; remove_group_transform(item, last); - dst = obs_scene_add_internal(scene, last->source, insert_after, - 0); + dst = obs_scene_add_internal(scene, last->source, insert_after, 0); duplicate_item_data(dst, last, true, true); apply_group_transform(last, item); @@ -4132,8 +3862,7 @@ void obs_sceneitem_group_add_item(obs_sceneitem_t *group, obs_sceneitem_t *item) signal_refresh(scene); } -void obs_sceneitem_group_remove_item(obs_sceneitem_t *group, - obs_sceneitem_t *item) +void obs_sceneitem_group_remove_item(obs_sceneitem_t *group, obs_sceneitem_t *item) { if (!item || !group || !group->is_group) return; @@ -4161,10 +3890,7 @@ void obs_sceneitem_group_remove_item(obs_sceneitem_t *group, signal_refresh(scene); } -static void -build_current_order_info(obs_scene_t *scene, - struct obs_sceneitem_order_info **items_out, - size_t *size_out) +static void build_current_order_info(obs_scene_t *scene, struct obs_sceneitem_order_info **items_out, size_t *size_out) { DARRAY(struct obs_sceneitem_order_info) items; da_init(items); @@ -4200,9 +3926,7 @@ build_current_order_info(obs_scene_t *scene, *size_out = items.num; } -static bool sceneitems_match2(obs_scene_t *scene, - struct obs_sceneitem_order_info *items, - size_t size) +static bool sceneitems_match2(obs_scene_t *scene, struct obs_sceneitem_order_info *items, size_t size) { struct obs_sceneitem_order_info *cur_items; size_t cur_size; @@ -4227,16 +3951,14 @@ static bool sceneitems_match2(obs_scene_t *scene, return true; } -static obs_sceneitem_t * -get_sceneitem_parent_group(obs_scene_t *scene, obs_sceneitem_t *group_subitem) +static obs_sceneitem_t *get_sceneitem_parent_group(obs_scene_t *scene, obs_sceneitem_t *group_subitem) { if (group_subitem->is_group) return NULL; obs_sceneitem_t *item = scene->first_item; while (item) { - if (item->is_group && - item->source->context.data == group_subitem->parent) + if (item->is_group && item->source->context.data == group_subitem->parent) return item; item = item->next; } @@ -4244,8 +3966,7 @@ get_sceneitem_parent_group(obs_scene_t *scene, obs_sceneitem_t *group_subitem) return NULL; } -static void obs_sceneitem_move_hotkeys(obs_scene_t *parent, - obs_sceneitem_t *item) +static void obs_sceneitem_move_hotkeys(obs_scene_t *parent, obs_sceneitem_t *item) { obs_data_array_t *data0 = NULL; obs_data_array_t *data1 = NULL; @@ -4260,9 +3981,7 @@ static void obs_sceneitem_move_hotkeys(obs_scene_t *parent, obs_data_array_release(data1); } -bool obs_scene_reorder_items2(obs_scene_t *scene, - struct obs_sceneitem_order_info *item_order, - size_t item_order_size) +bool obs_scene_reorder_items2(obs_scene_t *scene, struct obs_sceneitem_order_info *item_order, size_t item_order_size) { if (!scene || !item_order_size || !item_order) return false; @@ -4282,8 +4001,7 @@ bool obs_scene_reorder_items2(obs_scene_t *scene, for (size_t i = 0; i < item_order_size; i++) { struct obs_sceneitem_order_info *info = &item_order[i]; if (!info->item->is_group) { - obs_sceneitem_t *group = - get_sceneitem_parent_group(scene, info->item); + obs_sceneitem_t *group = get_sceneitem_parent_group(scene, info->item); remove_group_transform(group, info->item); } } @@ -4297,8 +4015,7 @@ bool obs_scene_reorder_items2(obs_scene_t *scene, if (info->item->is_group) { obs_sceneitem_t *sub_prev = NULL; - obs_scene_t *sub_scene = - info->item->source->context.data; + obs_scene_t *sub_scene = info->item->source->context.data; sub_scene->first_item = NULL; @@ -4306,8 +4023,7 @@ bool obs_scene_reorder_items2(obs_scene_t *scene, full_lock(sub_scene); for (i++; i < item_order_size; i++) { - struct obs_sceneitem_order_info *sub_info = - &item_order[i]; + struct obs_sceneitem_order_info *sub_info = &item_order[i]; obs_sceneitem_t *sub_item = sub_info->item; if (sub_info->group != info->item) { @@ -4328,8 +4044,7 @@ bool obs_scene_reorder_items2(obs_scene_t *scene, if (sub_prev) sub_prev->next = sub_item; - apply_group_transform(sub_info->item, - sub_info->group); + apply_group_transform(sub_info->item, sub_info->group); sub_prev = sub_item; } @@ -4360,15 +4075,13 @@ bool obs_scene_reorder_items2(obs_scene_t *scene, return true; } -obs_sceneitem_t *obs_sceneitem_get_group(obs_scene_t *scene, - obs_sceneitem_t *group_subitem) +obs_sceneitem_t *obs_sceneitem_get_group(obs_scene_t *scene, obs_sceneitem_t *group_subitem) { if (!scene || !group_subitem || group_subitem->is_group) return NULL; full_lock(scene); - obs_sceneitem_t *group = - get_sceneitem_parent_group(scene, group_subitem); + obs_sceneitem_t *group = get_sceneitem_parent_group(scene, group_subitem); full_unlock(scene); return group; @@ -4389,9 +4102,7 @@ bool obs_scene_is_group(const obs_scene_t *scene) return scene ? scene->is_group : false; } -void obs_sceneitem_group_enum_items(obs_sceneitem_t *group, - bool (*callback)(obs_scene_t *, - obs_sceneitem_t *, void *), +void obs_sceneitem_group_enum_items(obs_sceneitem_t *group, bool (*callback)(obs_scene_t *, obs_sceneitem_t *, void *), void *param) { if (!group || !group->is_group) @@ -4411,14 +4122,12 @@ void obs_sceneitem_force_update_transform(obs_sceneitem_t *item) update_item_transform(item, false); } -void obs_sceneitem_set_transition(obs_sceneitem_t *item, bool show, - obs_source_t *transition) +void obs_sceneitem_set_transition(obs_sceneitem_t *item, bool show, obs_source_t *transition) { if (!item) return; - obs_source_t **target = show ? &item->show_transition - : &item->hide_transition; + obs_source_t **target = show ? &item->show_transition : &item->hide_transition; if (*target) obs_source_release(*target); *target = obs_source_get_ref(transition); @@ -4432,8 +4141,7 @@ obs_source_t *obs_sceneitem_get_transition(obs_sceneitem_t *item, bool show) return show ? item->show_transition : item->hide_transition; } -void obs_sceneitem_set_transition_duration(obs_sceneitem_t *item, bool show, - uint32_t duration_ms) +void obs_sceneitem_set_transition_duration(obs_sceneitem_t *item, bool show, uint32_t duration_ms) { if (!item) return; @@ -4447,8 +4155,7 @@ uint32_t obs_sceneitem_get_transition_duration(obs_sceneitem_t *item, bool show) { if (!item) return 0; - return show ? item->show_transition_duration - : item->hide_transition_duration; + return show ? item->show_transition_duration : item->hide_transition_duration; } void obs_sceneitem_transition_stop(void *data, calldata_t *calldata) @@ -4459,9 +4166,7 @@ void obs_sceneitem_transition_stop(void *data, calldata_t *calldata) obs_source_remove_active_child(parent, transition); signal_handler_t *sh = obs_source_get_signal_handler(transition); if (sh) - signal_handler_disconnect(sh, "transition_stop", - obs_sceneitem_transition_stop, - parent); + signal_handler_disconnect(sh, "transition_stop", obs_sceneitem_transition_stop, parent); } void obs_sceneitem_do_transition(obs_sceneitem_t *item, bool visible) @@ -4479,8 +4184,7 @@ void obs_sceneitem_do_transition(obs_sceneitem_t *item, bool visible) if (!transition) return; - int duration = - (int)obs_sceneitem_get_transition_duration(item, visible); + int duration = (int)obs_sceneitem_get_transition_duration(item, visible); const int cx = obs_source_get_width(item->source); const int cy = obs_source_get_height(item->source); @@ -4497,22 +4201,18 @@ void obs_sceneitem_do_transition(obs_sceneitem_t *item, bool visible) signal_handler_t *sh = obs_source_get_signal_handler(transition); if (sh) - signal_handler_connect(sh, "transition_stop", - obs_sceneitem_transition_stop, parent); + signal_handler_connect(sh, "transition_stop", obs_sceneitem_transition_stop, parent); if (!visible) { obs_transition_set(transition, item->source); - obs_transition_start(transition, OBS_TRANSITION_MODE_AUTO, - duration, NULL); + obs_transition_start(transition, OBS_TRANSITION_MODE_AUTO, duration, NULL); } else { obs_transition_set(transition, NULL); - obs_transition_start(transition, OBS_TRANSITION_MODE_AUTO, - duration, item->source); + obs_transition_start(transition, OBS_TRANSITION_MODE_AUTO, duration, item->source); } } -void obs_sceneitem_transition_load(struct obs_scene_item *item, - obs_data_t *data, bool show) +void obs_sceneitem_transition_load(struct obs_scene_item *item, obs_data_t *data, bool show) { if (!item || !data) return; @@ -4527,30 +4227,22 @@ void obs_sceneitem_transition_load(struct obs_scene_item *item, } else { obs_sceneitem_set_transition(item, show, NULL); } - obs_sceneitem_set_transition_duration( - item, show, (uint32_t)obs_data_get_int(data, "duration")); + obs_sceneitem_set_transition_duration(item, show, (uint32_t)obs_data_get_int(data, "duration")); } -obs_data_t *obs_sceneitem_transition_save(struct obs_scene_item *item, - bool show) +obs_data_t *obs_sceneitem_transition_save(struct obs_scene_item *item, bool show) { obs_data_t *data = obs_data_create(); - struct obs_source *transition = show ? item->show_transition - : item->hide_transition; + struct obs_source *transition = show ? item->show_transition : item->hide_transition; if (transition) { - obs_data_set_string(data, "id", - obs_source_get_unversioned_id(transition)); - obs_data_set_string(data, "versioned_id", - obs_source_get_id(transition)); - obs_data_set_string(data, "name", - obs_source_get_name(transition)); + obs_data_set_string(data, "id", obs_source_get_unversioned_id(transition)); + obs_data_set_string(data, "versioned_id", obs_source_get_id(transition)); + obs_data_set_string(data, "name", obs_source_get_name(transition)); obs_data_t *s = obs_source_get_settings(transition); obs_data_set_obj(data, "transition", s); obs_data_release(s); } - obs_data_set_int(data, "duration", - show ? item->show_transition_duration - : item->hide_transition_duration); + obs_data_set_int(data, "duration", show ? item->show_transition_duration : item->hide_transition_duration); return data; } diff --git a/libobs/obs-service.c b/libobs/obs-service.c index 3852c9586..538db5d17 100644 --- a/libobs/obs-service.c +++ b/libobs/obs-service.c @@ -35,11 +35,8 @@ const char *obs_service_get_display_name(const char *id) return (info != NULL) ? info->get_name(info->type_data) : NULL; } -static obs_service_t *obs_service_create_internal(const char *id, - const char *name, - obs_data_t *settings, - obs_data_t *hotkey_data, - bool private) +static obs_service_t *obs_service_create_internal(const char *id, const char *name, obs_data_t *settings, + obs_data_t *hotkey_data, bool private) { const struct obs_service_info *info = find_service(id); struct obs_service *service; @@ -51,37 +48,30 @@ static obs_service_t *obs_service_create_internal(const char *id, service = bzalloc(sizeof(struct obs_service)); - if (!obs_context_data_init(&service->context, OBS_OBJ_TYPE_SERVICE, - settings, name, NULL, hotkey_data, + if (!obs_context_data_init(&service->context, OBS_OBJ_TYPE_SERVICE, settings, name, NULL, hotkey_data, private)) { bfree(service); return NULL; } service->info = *info; - service->context.data = - service->info.create(service->context.settings, service); + service->context.data = service->info.create(service->context.settings, service); if (!service->context.data) blog(LOG_ERROR, "Failed to create service '%s'!", name); - obs_context_init_control(&service->context, service, - (obs_destroy_cb)obs_service_destroy); - obs_context_data_insert(&service->context, &obs->data.services_mutex, - &obs->data.first_service); + obs_context_init_control(&service->context, service, (obs_destroy_cb)obs_service_destroy); + obs_context_data_insert(&service->context, &obs->data.services_mutex, &obs->data.first_service); blog(LOG_DEBUG, "service '%s' (%s) created", name, id); return service; } -obs_service_t *obs_service_create(const char *id, const char *name, - obs_data_t *settings, obs_data_t *hotkey_data) +obs_service_t *obs_service_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data) { - return obs_service_create_internal(id, name, settings, hotkey_data, - false); + return obs_service_create_internal(id, name, settings, hotkey_data, false); } -obs_service_t *obs_service_create_private(const char *id, const char *name, - obs_data_t *settings) +obs_service_t *obs_service_create_private(const char *id, const char *name, obs_data_t *settings) { return obs_service_create_internal(id, name, settings, NULL, true); } @@ -118,9 +108,7 @@ void obs_service_destroy(obs_service_t *service) const char *obs_service_get_name(const obs_service_t *service) { - return obs_service_valid(service, "obs_service_get_name") - ? service->context.name - : NULL; + return obs_service_valid(service, "obs_service_get_name") ? service->context.name : NULL; } static inline obs_data_t *get_defaults(const struct obs_service_info *info) @@ -169,9 +157,7 @@ obs_properties_t *obs_service_properties(const obs_service_t *service) const char *obs_service_get_type(const obs_service_t *service) { - return obs_service_valid(service, "obs_service_get_type") - ? service->info.id - : NULL; + return obs_service_valid(service, "obs_service_get_type") ? service->info.id : NULL; } void obs_service_update(obs_service_t *service, obs_data_t *settings) @@ -182,8 +168,7 @@ void obs_service_update(obs_service_t *service, obs_data_t *settings) obs_data_apply(service->context.settings, settings); if (service->info.update) - service->info.update(service->context.data, - service->context.settings); + service->info.update(service->context.data, service->context.settings); } obs_data_t *obs_service_get_settings(const obs_service_t *service) @@ -197,16 +182,12 @@ obs_data_t *obs_service_get_settings(const obs_service_t *service) signal_handler_t *obs_service_get_signal_handler(const obs_service_t *service) { - return obs_service_valid(service, "obs_service_get_signal_handler") - ? service->context.signals - : NULL; + return obs_service_valid(service, "obs_service_get_signal_handler") ? service->context.signals : NULL; } proc_handler_t *obs_service_get_proc_handler(const obs_service_t *service) { - return obs_service_valid(service, "obs_service_get_proc_handler") - ? service->context.procs - : NULL; + return obs_service_valid(service, "obs_service_get_proc_handler") ? service->context.procs : NULL; } void obs_service_activate(struct obs_service *service) @@ -224,8 +205,7 @@ void obs_service_activate(struct obs_service *service) return; if (service->info.activate) - service->info.activate(service->context.data, - service->context.settings); + service->info.activate(service->context.data, service->context.settings); service->active = true; } @@ -254,8 +234,7 @@ void obs_service_deactivate(struct obs_service *service, bool remove) service->output = NULL; } -bool obs_service_initialize(struct obs_service *service, - struct obs_output *output) +bool obs_service_initialize(struct obs_service *service, struct obs_output *output) { if (!obs_service_valid(service, "obs_service_initialize")) return false; @@ -267,8 +246,7 @@ bool obs_service_initialize(struct obs_service *service, return true; } -void obs_service_apply_encoder_settings(obs_service_t *service, - obs_data_t *video_encoder_settings, +void obs_service_apply_encoder_settings(obs_service_t *service, obs_data_t *video_encoder_settings, obs_data_t *audio_encoder_settings) { if (!obs_service_valid(service, "obs_service_apply_encoder_settings")) @@ -277,8 +255,7 @@ void obs_service_apply_encoder_settings(obs_service_t *service, return; if (video_encoder_settings || audio_encoder_settings) - service->info.apply_encoder_settings(service->context.data, - video_encoder_settings, + service->info.apply_encoder_settings(service->context.data, video_encoder_settings, audio_encoder_settings); } @@ -343,29 +320,23 @@ obs_service_t *obs_weak_service_get_service(obs_weak_service_t *weak) return NULL; } -bool obs_weak_service_references_service(obs_weak_service_t *weak, - obs_service_t *service) +bool obs_weak_service_references_service(obs_weak_service_t *weak, obs_service_t *service) { return weak && service && weak->service == service; } void *obs_service_get_type_data(obs_service_t *service) { - return obs_service_valid(service, "obs_service_get_type_data") - ? service->info.type_data - : NULL; + return obs_service_valid(service, "obs_service_get_type_data") ? service->info.type_data : NULL; } const char *obs_service_get_id(const obs_service_t *service) { - return obs_service_valid(service, "obs_service_get_id") - ? service->info.id - : NULL; + return obs_service_valid(service, "obs_service_get_id") ? service->info.id : NULL; } -void obs_service_get_supported_resolutions( - const obs_service_t *service, - struct obs_service_resolution **resolutions, size_t *count) +void obs_service_get_supported_resolutions(const obs_service_t *service, struct obs_service_resolution **resolutions, + size_t *count) { if (!obs_service_valid(service, "obs_service_supported_resolutions")) return; @@ -378,8 +349,7 @@ void obs_service_get_supported_resolutions( *count = 0; if (service->info.get_supported_resolutions) - service->info.get_supported_resolutions(service->context.data, - resolutions, count); + service->info.get_supported_resolutions(service->context.data, resolutions, count); } void obs_service_get_max_fps(const obs_service_t *service, int *fps) @@ -395,8 +365,7 @@ void obs_service_get_max_fps(const obs_service_t *service, int *fps) service->info.get_max_fps(service->context.data, fps); } -void obs_service_get_max_bitrate(const obs_service_t *service, - int *video_bitrate, int *audio_bitrate) +void obs_service_get_max_bitrate(const obs_service_t *service, int *video_bitrate, int *audio_bitrate) { if (video_bitrate) *video_bitrate = 0; @@ -407,25 +376,20 @@ void obs_service_get_max_bitrate(const obs_service_t *service, return; if (service->info.get_max_bitrate) - service->info.get_max_bitrate(service->context.data, - video_bitrate, audio_bitrate); + service->info.get_max_bitrate(service->context.data, video_bitrate, audio_bitrate); } -const char ** -obs_service_get_supported_video_codecs(const obs_service_t *service) +const char **obs_service_get_supported_video_codecs(const obs_service_t *service) { if (service->info.get_supported_video_codecs) - return service->info.get_supported_video_codecs( - service->context.data); + return service->info.get_supported_video_codecs(service->context.data); return NULL; } -const char ** -obs_service_get_supported_audio_codecs(const obs_service_t *service) +const char **obs_service_get_supported_audio_codecs(const obs_service_t *service) { if (service->info.get_supported_audio_codecs) - return service->info.get_supported_audio_codecs( - service->context.data); + return service->info.get_supported_audio_codecs(service->context.data); return NULL; } @@ -439,8 +403,7 @@ const char *obs_service_get_protocol(const obs_service_t *service) const char *obs_service_get_preferred_output_type(const obs_service_t *service) { - if (!obs_service_valid(service, - "obs_service_get_preferred_output_type")) + if (!obs_service_valid(service, "obs_service_get_preferred_output_type")) return NULL; if (service->info.get_output_type) @@ -448,8 +411,7 @@ const char *obs_service_get_preferred_output_type(const obs_service_t *service) return NULL; } -const char *obs_service_get_connect_info(const obs_service_t *service, - uint32_t type) +const char *obs_service_get_connect_info(const obs_service_t *service, uint32_t type) { if (!obs_service_valid(service, "obs_service_get_info")) return NULL; diff --git a/libobs/obs-service.h b/libobs/obs-service.h index 698b1c431..57aaa7e3e 100644 --- a/libobs/obs-service.h +++ b/libobs/obs-service.h @@ -37,8 +37,7 @@ struct obs_service_resolution { enum obs_service_connect_info { OBS_SERVICE_CONNECT_INFO_SERVER_URL = 0, OBS_SERVICE_CONNECT_INFO_STREAM_ID = 2, - OBS_SERVICE_CONNECT_INFO_STREAM_KEY = - 2, // Alias of OBS_SERVICE_CONNECT_INFO_STREAM_ID + OBS_SERVICE_CONNECT_INFO_STREAM_KEY = 2, // Alias of OBS_SERVICE_CONNECT_INFO_STREAM_ID OBS_SERVICE_CONNECT_INFO_USERNAME = 4, OBS_SERVICE_CONNECT_INFO_PASSWORD = 6, OBS_SERVICE_CONNECT_INFO_ENCRYPT_PASSPHRASE = 8, @@ -82,8 +81,7 @@ struct obs_service_info { bool (*deprecated_1)(); - void (*apply_encoder_settings)(void *data, - obs_data_t *video_encoder_settings, + void (*apply_encoder_settings)(void *data, obs_data_t *video_encoder_settings, obs_data_t *audio_encoder_settings); void *type_data; @@ -92,13 +90,10 @@ struct obs_service_info { /* TODO: Rename to 'get_preferred_output_type' once a API/ABI break happen */ const char *(*get_output_type)(void *data); - void (*get_supported_resolutions)( - void *data, struct obs_service_resolution **resolutions, - size_t *count); + void (*get_supported_resolutions)(void *data, struct obs_service_resolution **resolutions, size_t *count); void (*get_max_fps)(void *data, int *fps); - void (*get_max_bitrate)(void *data, int *video_bitrate, - int *audio_bitrate); + void (*get_max_bitrate)(void *data, int *video_bitrate, int *audio_bitrate); const char **(*get_supported_video_codecs)(void *data); @@ -111,11 +106,9 @@ struct obs_service_info { bool (*can_try_to_connect)(void *data); }; -EXPORT void obs_register_service_s(const struct obs_service_info *info, - size_t size); +EXPORT void obs_register_service_s(const struct obs_service_info *info, size_t size); -#define obs_register_service(info) \ - obs_register_service_s(info, sizeof(struct obs_service_info)) +#define obs_register_service(info) obs_register_service_s(info, sizeof(struct obs_service_info)) #ifdef __cplusplus } diff --git a/libobs/obs-source-deinterlace.c b/libobs/obs-source-deinterlace.c index 60ee5dec8..ca4134021 100644 --- a/libobs/obs-source-deinterlace.c +++ b/libobs/obs-source-deinterlace.c @@ -36,22 +36,15 @@ static bool ready_deinterlace_frames(obs_source_t *source, uint64_t sys_time) if (source->async_frames.num == 2) { bool prev_frame = true; - if (source->async_unbuffered && - source->deinterlace_offset) { - const uint64_t timestamp = - source->async_frames.array[0]->timestamp; - const uint64_t after_timestamp = - source->async_frames.array[1]->timestamp; - const uint64_t duration = - after_timestamp - timestamp; - const uint64_t frame_end = - timestamp + source->deinterlace_offset + - duration; + if (source->async_unbuffered && source->deinterlace_offset) { + const uint64_t timestamp = source->async_frames.array[0]->timestamp; + const uint64_t after_timestamp = source->async_frames.array[1]->timestamp; + const uint64_t duration = after_timestamp - timestamp; + const uint64_t frame_end = timestamp + source->deinterlace_offset + duration; if (sys_time < frame_end) { // Don't skip ahead prematurely. prev_frame = false; - source->deinterlace_frame_ts = - timestamp - duration; + source->deinterlace_frame_ts = timestamp - duration; } } source->async_frames.array[0]->prev_frame = prev_frame; @@ -112,8 +105,7 @@ static bool ready_deinterlace_frames(obs_source_t *source, uint64_t sys_time) /* more timestamp checking and compensating */ if ((next_frame->timestamp - frame_time) > MAX_TS_VAR) { - source->last_frame_ts = - next_frame->timestamp - frame_offset; + source->last_frame_ts = next_frame->timestamp - frame_offset; source->deinterlace_offset = 0; } @@ -145,17 +137,14 @@ static inline uint64_t uint64_diff(uint64_t ts1, uint64_t ts2) #define TWOX_TOLERANCE 1000000 #define TS_JUMP_THRESHOLD 70000000ULL -static inline void deinterlace_get_closest_frames(obs_source_t *s, - uint64_t sys_time) +static inline void deinterlace_get_closest_frames(obs_source_t *s, uint64_t sys_time) { uint64_t half_interval; if (s->async_unbuffered && s->deinterlace_offset) { // Want to keep frame if it has not elapsed. - const uint64_t frame_end = - s->deinterlace_frame_ts + s->deinterlace_offset + - ((uint64_t)s->deinterlace_half_duration * 2) - - TWOX_TOLERANCE; + const uint64_t frame_end = s->deinterlace_frame_ts + s->deinterlace_offset + + ((uint64_t)s->deinterlace_half_duration * 2) - TWOX_TOLERANCE; if (sys_time < frame_end) { // Process new frames if we think time jumped. const uint64_t diff = frame_end - sys_time; @@ -178,22 +167,17 @@ static inline void deinterlace_get_closest_frames(obs_source_t *s, da_erase(s->async_frames, 0); - if ((s->async_frames.num > 0) && - s->cur_async_frame->prev_frame) { + if ((s->async_frames.num > 0) && s->cur_async_frame->prev_frame) { s->prev_async_frame = s->cur_async_frame; s->cur_async_frame = s->async_frames.array[0]; da_erase(s->async_frames, 0); s->deinterlace_half_duration = - (uint32_t)((s->cur_async_frame->timestamp - - s->prev_async_frame->timestamp) / - 2); + (uint32_t)((s->cur_async_frame->timestamp - s->prev_async_frame->timestamp) / 2); } else { s->deinterlace_half_duration = - (uint32_t)((s->cur_async_frame->timestamp - - s->deinterlace_frame_ts) / - 2); + (uint32_t)((s->cur_async_frame->timestamp - s->deinterlace_frame_ts) / 2); } if (!s->last_frame_ts) @@ -206,8 +190,7 @@ static inline void deinterlace_get_closest_frames(obs_source_t *s, if (!s->deinterlace_offset) { s->deinterlace_offset = offset; } else { - uint64_t offset_diff = - uint64_diff(s->deinterlace_offset, offset); + uint64_t offset_diff = uint64_diff(s->deinterlace_offset, offset); if (offset_diff > half_interval) s->deinterlace_offset = offset; } @@ -230,23 +213,18 @@ void deinterlace_process_last_frame(obs_source_t *s, uint64_t sys_time) void set_deinterlace_texture_size(obs_source_t *source) { - const enum gs_color_format format = - convert_video_format(source->async_format, source->async_trc); + const enum gs_color_format format = convert_video_format(source->async_format, source->async_trc); if (source->async_gpu_conversion) { - source->async_prev_texrender = - gs_texrender_create(format, GS_ZS_NONE); + source->async_prev_texrender = gs_texrender_create(format, GS_ZS_NONE); for (int c = 0; c < source->async_channel_count; c++) - source->async_prev_textures[c] = gs_texture_create( - source->async_convert_width[c], - source->async_convert_height[c], - source->async_texture_formats[c], 1, NULL, - GS_DYNAMIC); + source->async_prev_textures[c] = + gs_texture_create(source->async_convert_width[c], source->async_convert_height[c], + source->async_texture_formats[c], 1, NULL, GS_DYNAMIC); } else { - source->async_prev_textures[0] = gs_texture_create( - source->async_width, source->async_height, format, 1, - NULL, GS_DYNAMIC); + source->async_prev_textures[0] = + gs_texture_create(source->async_width, source->async_height, format, 1, NULL, GS_DYNAMIC); } } @@ -269,9 +247,7 @@ void deinterlace_update_async_video(obs_source_t *source) os_atomic_inc_long(&frame->refs); if (set_async_texture_size(source, frame)) { - update_async_textures(source, frame, - source->async_prev_textures, - source->async_prev_texrender); + update_async_textures(source, frame, source->async_prev_textures, source->async_prev_texrender); } obs_source_release_frame(source, frame); @@ -279,8 +255,7 @@ void deinterlace_update_async_video(obs_source_t *source) } else if (updated) { /* swap cur/prev if no previous texture */ for (size_t c = 0; c < MAX_AV_PLANES; c++) { gs_texture_t *prev_tex = source->async_prev_textures[c]; - source->async_prev_textures[c] = - source->async_textures[c]; + source->async_prev_textures[c] = source->async_textures[c]; source->async_textures[c] = prev_tex; } @@ -298,30 +273,21 @@ static inline gs_effect_t *get_effect(enum obs_deinterlace_mode mode) case OBS_DEINTERLACE_MODE_DISABLE: return NULL; case OBS_DEINTERLACE_MODE_DISCARD: - return obs_load_effect(&obs->video.deinterlace_discard_effect, - "deinterlace_discard.effect"); + return obs_load_effect(&obs->video.deinterlace_discard_effect, "deinterlace_discard.effect"); case OBS_DEINTERLACE_MODE_RETRO: - return obs_load_effect( - &obs->video.deinterlace_discard_2x_effect, - "deinterlace_discard_2x.effect"); + return obs_load_effect(&obs->video.deinterlace_discard_2x_effect, "deinterlace_discard_2x.effect"); case OBS_DEINTERLACE_MODE_BLEND: - return obs_load_effect(&obs->video.deinterlace_blend_effect, - "deinterlace_blend.effect"); + return obs_load_effect(&obs->video.deinterlace_blend_effect, "deinterlace_blend.effect"); case OBS_DEINTERLACE_MODE_BLEND_2X: - return obs_load_effect(&obs->video.deinterlace_blend_2x_effect, - "deinterlace_blend_2x.effect"); + return obs_load_effect(&obs->video.deinterlace_blend_2x_effect, "deinterlace_blend_2x.effect"); case OBS_DEINTERLACE_MODE_LINEAR: - return obs_load_effect(&obs->video.deinterlace_linear_effect, - "deinterlace_linear.effect"); + return obs_load_effect(&obs->video.deinterlace_linear_effect, "deinterlace_linear.effect"); case OBS_DEINTERLACE_MODE_LINEAR_2X: - return obs_load_effect(&obs->video.deinterlace_linear_2x_effect, - "deinterlace_linear_2x.effect"); + return obs_load_effect(&obs->video.deinterlace_linear_2x_effect, "deinterlace_linear_2x.effect"); case OBS_DEINTERLACE_MODE_YADIF: - return obs_load_effect(&obs->video.deinterlace_yadif_effect, - "deinterlace_yadif.effect"); + return obs_load_effect(&obs->video.deinterlace_yadif_effect, "deinterlace_yadif.effect"); case OBS_DEINTERLACE_MODE_YADIF_2X: - return obs_load_effect(&obs->video.deinterlace_yadif_2x_effect, - "deinterlace_yadif_2x.effect"); + return obs_load_effect(&obs->video.deinterlace_yadif_2x_effect, "deinterlace_yadif_2x.effect"); } return NULL; @@ -351,34 +317,25 @@ void deinterlace_render(obs_source_t *s) gs_effect_t *effect = s->deinterlace_effect; gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image"); - gs_eparam_t *prev = - gs_effect_get_param_by_name(effect, "previous_image"); - gs_eparam_t *multiplier_param = - gs_effect_get_param_by_name(effect, "multiplier"); + gs_eparam_t *prev = gs_effect_get_param_by_name(effect, "previous_image"); + gs_eparam_t *multiplier_param = gs_effect_get_param_by_name(effect, "multiplier"); gs_eparam_t *field = gs_effect_get_param_by_name(effect, "field_order"); gs_eparam_t *frame2 = gs_effect_get_param_by_name(effect, "frame2"); - gs_eparam_t *dimensions = - gs_effect_get_param_by_name(effect, "dimensions"); + gs_eparam_t *dimensions = gs_effect_get_param_by_name(effect, "dimensions"); struct vec2 size = {(float)s->async_width, (float)s->async_height}; - gs_texture_t *cur_tex = - s->async_texrender - ? gs_texrender_get_texture(s->async_texrender) - : s->async_textures[0]; - gs_texture_t *prev_tex = - s->async_prev_texrender - ? gs_texrender_get_texture(s->async_prev_texrender) - : s->async_prev_textures[0]; + gs_texture_t *cur_tex = s->async_texrender ? gs_texrender_get_texture(s->async_texrender) + : s->async_textures[0]; + gs_texture_t *prev_tex = s->async_prev_texrender ? gs_texrender_get_texture(s->async_prev_texrender) + : s->async_prev_textures[0]; if (!cur_tex || !prev_tex || !s->async_width || !s->async_height) return; - const enum gs_color_space source_space = - convert_video_space(s->async_format, s->async_trc); + const enum gs_color_space source_space = convert_video_space(s->async_format, s->async_trc); - const bool linear_srgb = - (source_space != GS_CS_SRGB) || gs_get_linear_srgb() || - deinterlace_linear_required(s->deinterlace_mode); + const bool linear_srgb = (source_space != GS_CS_SRGB) || gs_get_linear_srgb() || + deinterlace_linear_required(s->deinterlace_mode); const enum gs_color_space current_space = gs_get_color_space(); const char *tech_name = "Draw"; @@ -437,24 +394,20 @@ void deinterlace_render(obs_source_t *s) gs_effect_set_vec2(dimensions, &size); const uint64_t frame2_ts = - s->deinterlace_frame_ts + s->deinterlace_offset + - s->deinterlace_half_duration - TWOX_TOLERANCE; + s->deinterlace_frame_ts + s->deinterlace_offset + s->deinterlace_half_duration - TWOX_TOLERANCE; gs_effect_set_bool(frame2, obs->video.video_time >= frame2_ts); while (gs_effect_loop(effect, tech_name)) - gs_draw_sprite(NULL, s->async_flip ? GS_FLIP_V : 0, - s->async_width, s->async_height); + gs_draw_sprite(NULL, s->async_flip ? GS_FLIP_V : 0, s->async_width, s->async_height); gs_enable_framebuffer_srgb(previous); } -static void enable_deinterlacing(obs_source_t *source, - enum obs_deinterlace_mode mode) +static void enable_deinterlacing(obs_source_t *source, enum obs_deinterlace_mode mode) { obs_enter_graphics(); - if (source->async_format != VIDEO_FORMAT_NONE && - source->async_width != 0 && source->async_height != 0) + if (source->async_format != VIDEO_FORMAT_NONE && source->async_width != 0 && source->async_height != 0) set_deinterlace_texture_size(source); source->deinterlace_mode = mode; @@ -485,8 +438,7 @@ static void disable_deinterlacing(obs_source_t *source) obs_leave_graphics(); } -void obs_source_set_deinterlace_mode(obs_source_t *source, - enum obs_deinterlace_mode mode) +void obs_source_set_deinterlace_mode(obs_source_t *source, enum obs_deinterlace_mode mode) { if (!obs_source_valid(source, "obs_source_set_deinterlace_mode")) return; @@ -505,31 +457,24 @@ void obs_source_set_deinterlace_mode(obs_source_t *source, } } -enum obs_deinterlace_mode -obs_source_get_deinterlace_mode(const obs_source_t *source) +enum obs_deinterlace_mode obs_source_get_deinterlace_mode(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_set_deinterlace_mode") - ? source->deinterlace_mode - : OBS_DEINTERLACE_MODE_DISABLE; + return obs_source_valid(source, "obs_source_set_deinterlace_mode") ? source->deinterlace_mode + : OBS_DEINTERLACE_MODE_DISABLE; } -void obs_source_set_deinterlace_field_order( - obs_source_t *source, enum obs_deinterlace_field_order field_order) +void obs_source_set_deinterlace_field_order(obs_source_t *source, enum obs_deinterlace_field_order field_order) { if (!obs_source_valid(source, "obs_source_set_deinterlace_field_order")) return; - source->deinterlace_top_first = field_order == - OBS_DEINTERLACE_FIELD_ORDER_TOP; + source->deinterlace_top_first = field_order == OBS_DEINTERLACE_FIELD_ORDER_TOP; } -enum obs_deinterlace_field_order -obs_source_get_deinterlace_field_order(const obs_source_t *source) +enum obs_deinterlace_field_order obs_source_get_deinterlace_field_order(const obs_source_t *source) { if (!obs_source_valid(source, "obs_source_set_deinterlace_field_order")) return OBS_DEINTERLACE_FIELD_ORDER_TOP; - return source->deinterlace_top_first - ? OBS_DEINTERLACE_FIELD_ORDER_TOP - : OBS_DEINTERLACE_FIELD_ORDER_BOTTOM; + return source->deinterlace_top_first ? OBS_DEINTERLACE_FIELD_ORDER_TOP : OBS_DEINTERLACE_FIELD_ORDER_BOTTOM; } diff --git a/libobs/obs-source-transition.c b/libobs/obs-source-transition.c index 234d2f1f1..dfd1009d2 100644 --- a/libobs/obs-source-transition.c +++ b/libobs/obs-source-transition.c @@ -19,20 +19,14 @@ #include "util/util_uint64.h" #include "graphics/math-extra.h" -#define lock_transition(transition) \ - pthread_mutex_lock(&transition->transition_mutex); -#define unlock_transition(transition) \ - pthread_mutex_unlock(&transition->transition_mutex); +#define lock_transition(transition) pthread_mutex_lock(&transition->transition_mutex); +#define unlock_transition(transition) pthread_mutex_unlock(&transition->transition_mutex); -#define trylock_textures(transition) \ - pthread_mutex_trylock(&transition->transition_tex_mutex) -#define lock_textures(transition) \ - pthread_mutex_lock(&transition->transition_tex_mutex) -#define unlock_textures(transition) \ - pthread_mutex_unlock(&transition->transition_tex_mutex) +#define trylock_textures(transition) pthread_mutex_trylock(&transition->transition_tex_mutex) +#define lock_textures(transition) pthread_mutex_lock(&transition->transition_tex_mutex) +#define unlock_textures(transition) pthread_mutex_unlock(&transition->transition_tex_mutex) -static inline bool transition_valid(const obs_source_t *transition, - const char *func) +static inline bool transition_valid(const obs_source_t *transition, const char *func) { if (!obs_ptr_valid(transition, func)) return false; @@ -52,14 +46,11 @@ bool obs_transition_init(obs_source_t *transition) return false; transition->transition_alignment = OBS_ALIGN_LEFT | OBS_ALIGN_TOP; - transition->transition_texrender[0] = - gs_texrender_create(GS_RGBA, GS_ZS_NONE); - transition->transition_texrender[1] = - gs_texrender_create(GS_RGBA, GS_ZS_NONE); + transition->transition_texrender[0] = gs_texrender_create(GS_RGBA, GS_ZS_NONE); + transition->transition_texrender[1] = gs_texrender_create(GS_RGBA, GS_ZS_NONE); transition->transition_source_active[0] = true; - return transition->transition_texrender[0] != NULL && - transition->transition_texrender[1] != NULL; + return transition->transition_texrender[0] != NULL && transition->transition_texrender[1] != NULL; } void obs_transition_free(obs_source_t *transition) @@ -153,8 +144,7 @@ static void recalculate_transition_matrix(obs_source_t *tr, size_t idx) if (scale_type == OBS_TRANSITION_SCALE_ASPECT) { bool use_width = tr_aspect < source_aspect; - scale.x = scale.y = use_width ? tr_cx / source_cx - : tr_cy / source_cy; + scale.x = scale.y = use_width ? tr_cx / source_cx : tr_cy / source_cy; } else if (scale_type == OBS_TRANSITION_SCALE_STRETCH) { scale.x = tr_cx / source_cx; @@ -165,8 +155,7 @@ static void recalculate_transition_matrix(obs_source_t *tr, size_t idx) source_cy *= scale.y; vec2_zero(&pos); - add_alignment(&pos, tr->transition_alignment, (int)(tr_cx - source_cx), - (int)(tr_cy - source_cy)); + add_alignment(&pos, tr->transition_alignment, (int)(tr_cx - source_cx), (int)(tr_cy - source_cy)); matrix4_identity(&mat); matrix4_scale3f(&mat, &mat, scale.x, scale.y, 1.0f); @@ -212,14 +201,12 @@ void obs_transition_tick(obs_source_t *transition, float t) if (transition->transition_mode == OBS_TRANSITION_MODE_MANUAL) { if (transition->transition_manual_torque == 0.0f) { - transition->transition_manual_val = - transition->transition_manual_target; + transition->transition_manual_val = transition->transition_manual_target; } else { - transition->transition_manual_val = calc_torquef( - transition->transition_manual_val, - transition->transition_manual_target, - transition->transition_manual_torque, - transition->transition_manual_clamp, t); + transition->transition_manual_val = calc_torquef(transition->transition_manual_val, + transition->transition_manual_target, + transition->transition_manual_torque, + transition->transition_manual_clamp, t); } } @@ -230,10 +217,8 @@ void obs_transition_tick(obs_source_t *transition, float t) } } -static void -set_source(obs_source_t *transition, enum obs_transition_target target, - obs_source_t *new_child, - bool (*callback)(obs_source_t *t, size_t idx, obs_source_t *c)) +static void set_source(obs_source_t *transition, enum obs_transition_target target, obs_source_t *new_child, + bool (*callback)(obs_source_t *t, size_t idx, obs_source_t *c)) { size_t idx = (size_t)target; obs_source_t *old_child; @@ -257,8 +242,7 @@ set_source(obs_source_t *transition, enum obs_transition_target target, if (already_active) { if (new_child) - add_success = obs_source_add_active_child(transition, - new_child); + add_success = obs_source_add_active_child(transition, new_child); if (old_child && add_success) obs_source_remove_active_child(transition, old_child); } @@ -271,8 +255,7 @@ set_source(obs_source_t *transition, enum obs_transition_target target, unlock_transition(transition); if (add_success) { - if (transition->transition_cx == 0 || - transition->transition_cy == 0) { + if (transition->transition_cx == 0 || transition->transition_cy == 0) { recalculate_transition_size(transition); recalculate_transition_matrices(transition); } @@ -283,8 +266,7 @@ set_source(obs_source_t *transition, enum obs_transition_target target, obs_source_release(old_child); } -obs_source_t *obs_transition_get_source(obs_source_t *transition, - enum obs_transition_target target) +obs_source_t *obs_transition_get_source(obs_source_t *transition, enum obs_transition_target target) { size_t idx = (size_t)target; obs_source_t *ret; @@ -318,8 +300,7 @@ obs_source_t *obs_transition_get_active_source(obs_source_t *transition) return ret; } -static bool activate_transition(obs_source_t *transition, size_t idx, - obs_source_t *child) +static bool activate_transition(obs_source_t *transition, size_t idx, obs_source_t *child) { if (!transition->transition_source_active[idx]) { if (!obs_source_add_active_child(transition, child)) @@ -335,12 +316,10 @@ static bool activate_transition(obs_source_t *transition, size_t idx, static inline bool transition_active(obs_source_t *transition) { - return transition->transitioning_audio || - transition->transitioning_video; + return transition->transitioning_audio || transition->transitioning_video; } -bool obs_transition_start(obs_source_t *transition, - enum obs_transition_mode mode, uint32_t duration_ms, +bool obs_transition_start(obs_source_t *transition, enum obs_transition_mode mode, uint32_t duration_ms, obs_source_t *dest) { bool active; @@ -360,8 +339,7 @@ bool obs_transition_start(obs_source_t *transition, if (same_as_source && !active) return false; - if (active && mode == OBS_TRANSITION_MODE_MANUAL && same_mode && - same_as_dest) + if (active && mode == OBS_TRANSITION_MODE_MANUAL && same_mode && same_as_dest) return true; lock_transition(transition); @@ -378,19 +356,16 @@ bool obs_transition_start(obs_source_t *transition, if (!active || (!same_as_dest && !same_as_source)) { transition->transition_start_time = os_gettime_ns(); - transition->transition_duration = - (uint64_t)duration_ms * 1000000ULL; + transition->transition_duration = (uint64_t)duration_ms * 1000000ULL; } - set_source(transition, OBS_TRANSITION_SOURCE_B, dest, - activate_transition); + set_source(transition, OBS_TRANSITION_SOURCE_B, dest, activate_transition); if (dest == NULL && same_as_dest && !same_as_source) { transition->transitioning_video = true; transition->transitioning_audio = true; } - obs_source_dosignal(transition, "source_transition_start", - "transition_start"); + obs_source_dosignal(transition, "source_transition_start", "transition_start"); recalculate_transition_size(transition); recalculate_transition_matrices(transition); @@ -398,8 +373,7 @@ bool obs_transition_start(obs_source_t *transition, return true; } -void obs_transition_set_manual_torque(obs_source_t *transition, float torque, - float clamp) +void obs_transition_set_manual_torque(obs_source_t *transition, float torque, float clamp) { lock_transition(transition); transition->transition_manual_torque = torque; @@ -478,15 +452,13 @@ float obs_transition_get_time(obs_source_t *transition) return get_video_time(transition); } -static inline gs_texture_t *get_texture(obs_source_t *transition, - enum obs_transition_target target) +static inline gs_texture_t *get_texture(obs_source_t *transition, enum obs_transition_target target) { size_t idx = (size_t)target; return gs_texrender_get_texture(transition->transition_texrender[idx]); } -void obs_transition_set_scale_type(obs_source_t *transition, - enum obs_transition_scale_type type) +void obs_transition_set_scale_type(obs_source_t *transition, enum obs_transition_scale_type type) { if (!transition_valid(transition, "obs_transition_set_scale_type")) return; @@ -494,12 +466,10 @@ void obs_transition_set_scale_type(obs_source_t *transition, transition->transition_scale_type = type; } -enum obs_transition_scale_type -obs_transition_get_scale_type(const obs_source_t *transition) +enum obs_transition_scale_type obs_transition_get_scale_type(const obs_source_t *transition) { - return transition_valid(transition, "obs_transition_get_scale_type") - ? transition->transition_scale_type - : OBS_TRANSITION_SCALE_MAX_ONLY; + return transition_valid(transition, "obs_transition_get_scale_type") ? transition->transition_scale_type + : OBS_TRANSITION_SCALE_MAX_ONLY; } void obs_transition_set_alignment(obs_source_t *transition, uint32_t alignment) @@ -512,9 +482,7 @@ void obs_transition_set_alignment(obs_source_t *transition, uint32_t alignment) uint32_t obs_transition_get_alignment(const obs_source_t *transition) { - return transition_valid(transition, "obs_transition_get_alignment") - ? transition->transition_alignment - : 0; + return transition_valid(transition, "obs_transition_get_alignment") ? transition->transition_alignment : 0; } void obs_transition_set_size(obs_source_t *transition, uint32_t cx, uint32_t cy) @@ -526,8 +494,7 @@ void obs_transition_set_size(obs_source_t *transition, uint32_t cx, uint32_t cy) transition->transition_cy = cy; } -void obs_transition_get_size(const obs_source_t *transition, uint32_t *cx, - uint32_t *cy) +void obs_transition_get_size(const obs_source_t *transition, uint32_t *cx, uint32_t *cy) { if (!transition_valid(transition, "obs_transition_set_size")) { *cx = 0; @@ -544,16 +511,12 @@ void obs_transition_save(obs_source_t *tr, obs_data_t *data) obs_source_t *child; lock_transition(tr); - child = transition_active(tr) ? tr->transition_sources[1] - : tr->transition_sources[0]; + child = transition_active(tr) ? tr->transition_sources[1] : tr->transition_sources[0]; - obs_data_set_string(data, "transition_source_a", - child ? child->context.name : ""); - obs_data_set_int(data, "transition_alignment", - tr->transition_alignment); + obs_data_set_string(data, "transition_source_a", child ? child->context.name : ""); + obs_data_set_int(data, "transition_alignment", tr->transition_alignment); obs_data_set_int(data, "transition_mode", (int64_t)tr->transition_mode); - obs_data_set_int(data, "transition_scale_type", - (int64_t)tr->transition_scale_type); + obs_data_set_int(data, "transition_scale_type", (int64_t)tr->transition_scale_type); obs_data_set_int(data, "transition_cx", tr->transition_cx); obs_data_set_int(data, "transition_cy", tr->transition_cy); unlock_transition(tr); @@ -609,8 +572,7 @@ struct transition_state { bool transitioning_audio; }; -static inline void copy_transition_state(obs_source_t *transition, - struct transition_state *state) +static inline void copy_transition_state(obs_source_t *transition, struct transition_state *state) { state->s[0] = obs_source_get_ref(transition->transition_sources[0]); state->s[1] = obs_source_get_ref(transition->transition_sources[1]); @@ -619,20 +581,17 @@ static inline void copy_transition_state(obs_source_t *transition, state->transitioning_audio = transition->transitioning_audio; } -void obs_transition_enum_sources(obs_source_t *transition, - obs_source_enum_proc_t cb, void *param) +void obs_transition_enum_sources(obs_source_t *transition, obs_source_enum_proc_t cb, void *param) { lock_transition(transition); for (size_t i = 0; i < 2; i++) { if (transition->transition_sources[i]) - cb(transition, transition->transition_sources[i], - param); + cb(transition, transition->transition_sources[i], param); } unlock_transition(transition); } -static inline void render_child(obs_source_t *transition, obs_source_t *child, - size_t idx, enum gs_color_space space) +static inline void render_child(obs_source_t *transition, obs_source_t *child, size_t idx, enum gs_color_space space) { uint32_t cx = get_cx(transition); uint32_t cy = get_cy(transition); @@ -641,15 +600,12 @@ static inline void render_child(obs_source_t *transition, obs_source_t *child, return; enum gs_color_format format = gs_get_format_from_space(space); - if (gs_texrender_get_format(transition->transition_texrender[idx]) != - format) { + if (gs_texrender_get_format(transition->transition_texrender[idx]) != format) { gs_texrender_destroy(transition->transition_texrender[idx]); - transition->transition_texrender[idx] = - gs_texrender_create(format, GS_ZS_NONE); + transition->transition_texrender[idx] = gs_texrender_create(format, GS_ZS_NONE); } - if (gs_texrender_begin_with_color_space( - transition->transition_texrender[idx], cx, cy, space)) { + if (gs_texrender_begin_with_color_space(transition->transition_texrender[idx], cx, cy, space)) { vec4_zero(&blank); gs_clear(GS_CLEAR_COLOR, &blank, 0.0f, 0); gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); @@ -681,8 +637,7 @@ static inline void handle_stop(obs_source_t *transition) { if (transition->info.transition_stop) transition->info.transition_stop(transition->context.data); - obs_source_dosignal(transition, "source_transition_stop", - "transition_stop"); + obs_source_dosignal(transition, "source_transition_stop", "transition_stop"); } void obs_transition_force_stop(obs_source_t *transition) @@ -690,17 +645,13 @@ void obs_transition_force_stop(obs_source_t *transition) handle_stop(transition); } -void obs_transition_video_render(obs_source_t *transition, - obs_transition_video_render_callback_t callback) +void obs_transition_video_render(obs_source_t *transition, obs_transition_video_render_callback_t callback) { - obs_transition_video_render2(transition, callback, - obs->video.transparent_texture); + obs_transition_video_render2(transition, callback, obs->video.transparent_texture); } -void obs_transition_video_render2( - obs_source_t *transition, - obs_transition_video_render_callback_t callback, - gs_texture_t *placeholder_texture) +void obs_transition_video_render2(obs_source_t *transition, obs_transition_video_render_callback_t callback, + gs_texture_t *placeholder_texture) { struct transition_state state; struct matrix4 matrices[2]; @@ -740,13 +691,10 @@ void obs_transition_video_render2( uint32_t cy; const enum gs_color_space current_space = gs_get_color_space(); - const enum gs_color_space source_space = - obs_source_get_color_space(transition, 1, - ¤t_space); + const enum gs_color_space source_space = obs_source_get_color_space(transition, 1, ¤t_space); for (size_t i = 0; i < 2; i++) { if (state.s[i]) { - render_child(transition, state.s[i], i, - source_space); + render_child(transition, state.s[i], i, source_space); tex[i] = get_texture(transition, i); if (!tex[i]) tex[i] = placeholder_texture; @@ -761,8 +709,7 @@ void obs_transition_video_render2( gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - callback(transition->context.data, tex[0], tex[1], t, - cx, cy); + callback(transition->context.data, tex[0], tex[1], t, cx, cy); gs_blend_state_pop(); } @@ -790,25 +737,21 @@ void obs_transition_video_render2( obs_source_release(state.s[1]); if (video_stopped) - obs_source_dosignal(transition, "source_transition_video_stop", - "transition_video_stop"); + obs_source_dosignal(transition, "source_transition_video_stop", "transition_video_stop"); if (stopped) handle_stop(transition); } -static enum gs_color_space mix_spaces(enum gs_color_space a, - enum gs_color_space b) +static enum gs_color_space mix_spaces(enum gs_color_space a, enum gs_color_space b) { - if ((a == GS_CS_709_EXTENDED) || (a == GS_CS_709_SCRGB) || - (b == GS_CS_709_EXTENDED) || (b == GS_CS_709_SCRGB)) + if ((a == GS_CS_709_EXTENDED) || (a == GS_CS_709_SCRGB) || (b == GS_CS_709_EXTENDED) || (b == GS_CS_709_SCRGB)) return GS_CS_709_EXTENDED; if ((a == GS_CS_SRGB_16F) || (b == GS_CS_SRGB_16F)) return GS_CS_SRGB_16F; return GS_CS_SRGB; } -enum gs_color_space -obs_transition_video_get_color_space(obs_source_t *transition) +enum gs_color_space obs_transition_video_get_color_space(obs_source_t *transition) { obs_source_t *source0 = transition->transition_sources[0]; obs_source_t *source1 = transition->transition_sources[1]; @@ -822,24 +765,19 @@ obs_transition_video_get_color_space(obs_source_t *transition) enum gs_color_space space = GS_CS_SRGB; if (source0) { - space = mix_spaces(space, obs_source_get_color_space( - source0, - OBS_COUNTOF(preferred_spaces), - preferred_spaces)); + space = mix_spaces(space, obs_source_get_color_space(source0, OBS_COUNTOF(preferred_spaces), + preferred_spaces)); } if (source1) { - space = mix_spaces(space, obs_source_get_color_space( - source1, - OBS_COUNTOF(preferred_spaces), - preferred_spaces)); + space = mix_spaces(space, obs_source_get_color_space(source1, OBS_COUNTOF(preferred_spaces), + preferred_spaces)); } return space; } -bool obs_transition_video_render_direct(obs_source_t *transition, - enum obs_transition_target target) +bool obs_transition_video_render_direct(obs_source_t *transition, enum obs_transition_target target) { struct transition_state state; struct matrix4 matrices[2]; @@ -887,27 +825,22 @@ bool obs_transition_video_render_direct(obs_source_t *transition, obs_source_release(state.s[1]); if (video_stopped) - obs_source_dosignal(transition, "source_transition_video_stop", - "transition_video_stop"); + obs_source_dosignal(transition, "source_transition_video_stop", "transition_video_stop"); if (stopped) handle_stop(transition); return transitioning; } -static inline float get_sample_time(obs_source_t *transition, - size_t sample_rate, size_t sample, - uint64_t ts) +static inline float get_sample_time(obs_source_t *transition, size_t sample_rate, size_t sample, uint64_t ts) { - uint64_t sample_ts_offset = - util_mul_div64(sample, 1000000000ULL, sample_rate); + uint64_t sample_ts_offset = util_mul_div64(sample, 1000000000ULL, sample_rate); uint64_t i_ts = ts + sample_ts_offset; return calc_time(transition, i_ts); } -static inline void mix_child(obs_source_t *transition, float *out, float *in, - size_t count, size_t sample_rate, uint64_t ts, - obs_transition_audio_mix_callback_t mix) +static inline void mix_child(obs_source_t *transition, float *out, float *in, size_t count, size_t sample_rate, + uint64_t ts, obs_transition_audio_mix_callback_t mix) { void *context_data = transition->context.data; @@ -917,9 +850,8 @@ static inline void mix_child(obs_source_t *transition, float *out, float *in, } } -static void process_audio(obs_source_t *transition, obs_source_t *child, - struct obs_source_audio_mix *audio, uint64_t min_ts, - uint32_t mixers, size_t channels, size_t sample_rate, +static void process_audio(obs_source_t *transition, obs_source_t *child, struct obs_source_audio_mix *audio, + uint64_t min_ts, uint32_t mixers, size_t channels, size_t sample_rate, obs_transition_audio_mix_callback_t mix) { bool valid = child && !child->audio_pending && child->audio_ts; @@ -948,9 +880,7 @@ static void process_audio(obs_source_t *transition, obs_source_t *child, float *out = output->data[ch]; float *in = input->data[ch]; - mix_child(transition, out + pos, in, - AUDIO_OUTPUT_FRAMES - pos, sample_rate, ts, - mix); + mix_child(transition, out + pos, in, AUDIO_OUTPUT_FRAMES - pos, sample_rate, ts, mix); } } } @@ -960,8 +890,7 @@ static inline uint64_t calc_min_ts(obs_source_t *sources[2]) uint64_t min_ts = 0; for (size_t i = 0; i < 2; i++) { - if (sources[i] && !sources[i]->audio_pending && - sources[i]->audio_ts) { + if (sources[i] && !sources[i]->audio_pending && sources[i]->audio_ts) { if (!min_ts || sources[i]->audio_ts < min_ts) min_ts = sources[i]->audio_ts; } @@ -981,12 +910,9 @@ static inline bool stop_audio(obs_source_t *transition) return false; } -bool obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, - struct obs_source_audio_mix *audio, - uint32_t mixers, size_t channels, - size_t sample_rate, - obs_transition_audio_mix_callback_t mix_a, - obs_transition_audio_mix_callback_t mix_b) +bool obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, struct obs_source_audio_mix *audio, + uint32_t mixers, size_t channels, size_t sample_rate, + obs_transition_audio_mix_callback_t mix_a, obs_transition_audio_mix_callback_t mix_b) { obs_source_t *sources[2]; struct transition_state state = {0}; @@ -1016,8 +942,7 @@ bool obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, if (min_ts) copy_transition_state(transition, &state); - } else if (!transition->transitioning_video && - transition->transitioning_audio) { + } else if (!transition->transitioning_video && transition->transitioning_audio) { stopped = stop_audio(transition); } @@ -1026,17 +951,13 @@ bool obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, if (min_ts) { if (state.transitioning_audio) { if (state.s[0]) - process_audio(transition, state.s[0], audio, - min_ts, mixers, channels, - sample_rate, mix_a); + process_audio(transition, state.s[0], audio, min_ts, mixers, channels, sample_rate, + mix_a); if (state.s[1]) - process_audio(transition, state.s[1], audio, - min_ts, mixers, channels, - sample_rate, mix_b); + process_audio(transition, state.s[1], audio, min_ts, mixers, channels, sample_rate, + mix_b); } else if (state.s[0]) { - memcpy(audio->output[0].data[0], - state.s[0]->audio_output_buf[0][0], - TOTAL_AUDIO_SIZE); + memcpy(audio->output[0].data[0], state.s[0]->audio_output_buf[0][0], TOTAL_AUDIO_SIZE); } obs_source_release(state.s[0]); @@ -1050,8 +971,7 @@ bool obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, return !!min_ts; } -void obs_transition_enable_fixed(obs_source_t *transition, bool enable, - uint32_t duration) +void obs_transition_enable_fixed(obs_source_t *transition, bool enable, uint32_t duration) { if (!transition_valid(transition, "obs_transition_enable_fixed")) return; @@ -1062,17 +982,13 @@ void obs_transition_enable_fixed(obs_source_t *transition, bool enable, bool obs_transition_fixed(obs_source_t *transition) { - return transition_valid(transition, "obs_transition_fixed") - ? transition->transition_use_fixed_duration - : false; + return transition_valid(transition, "obs_transition_fixed") ? transition->transition_use_fixed_duration : false; } -static inline obs_source_t * -copy_source_state(obs_source_t *tr_dest, obs_source_t *tr_source, size_t idx) +static inline obs_source_t *copy_source_state(obs_source_t *tr_dest, obs_source_t *tr_source, size_t idx) { obs_source_t *old_child = tr_dest->transition_sources[idx]; - obs_source_t *new_child = - obs_source_get_ref(tr_source->transition_sources[idx]); + obs_source_t *new_child = obs_source_get_ref(tr_source->transition_sources[idx]); bool active = tr_source->transition_source_active[idx]; if (old_child && tr_dest->transition_source_active[idx]) diff --git a/libobs/obs-source.c b/libobs/obs-source.c index 1c816c3bc..d7719a29f 100644 --- a/libobs/obs-source.c +++ b/libobs/obs-source.c @@ -61,13 +61,11 @@ struct obs_source_info *get_source_info(const char *id) return NULL; } -struct obs_source_info *get_source_info2(const char *unversioned_id, - uint32_t ver) +struct obs_source_info *get_source_info2(const char *unversioned_id, uint32_t ver) { for (size_t i = 0; i < obs->source_types.num; i++) { struct obs_source_info *info = &obs->source_types.array[i]; - if (strcmp(info->unversioned_id, unversioned_id) == 0 && - info->version == ver) + if (strcmp(info->unversioned_id, unversioned_id) == 0 && info->version == ver) return info; } @@ -117,16 +115,13 @@ static const char *source_signals[] = { NULL, }; -bool obs_source_init_context(struct obs_source *source, obs_data_t *settings, - const char *name, const char *uuid, +bool obs_source_init_context(struct obs_source *source, obs_data_t *settings, const char *name, const char *uuid, obs_data_t *hotkey_data, bool private) { - if (!obs_context_data_init(&source->context, OBS_OBJ_TYPE_SOURCE, - settings, name, uuid, hotkey_data, private)) + if (!obs_context_data_init(&source->context, OBS_OBJ_TYPE_SOURCE, settings, name, uuid, hotkey_data, private)) return false; - return signal_handler_add_array(source->context.signals, - source_signals); + return signal_handler_add_array(source->context.signals, source_signals); } const char *obs_source_get_display_name(const char *id) @@ -137,16 +132,14 @@ const char *obs_source_get_display_name(const char *id) static void allocate_audio_output_buffer(struct obs_source *source) { - size_t size = sizeof(float) * AUDIO_OUTPUT_FRAMES * MAX_AUDIO_CHANNELS * - MAX_AUDIO_MIXES; + size_t size = sizeof(float) * AUDIO_OUTPUT_FRAMES * MAX_AUDIO_CHANNELS * MAX_AUDIO_MIXES; float *ptr = bzalloc(size); for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { size_t mix_pos = mix * AUDIO_OUTPUT_FRAMES * MAX_AUDIO_CHANNELS; for (size_t i = 0; i < MAX_AUDIO_CHANNELS; i++) { - source->audio_output_buf[mix][i] = - ptr + mix_pos + AUDIO_OUTPUT_FRAMES * i; + source->audio_output_buf[mix][i] = ptr + mix_pos + AUDIO_OUTPUT_FRAMES * i; } } } @@ -216,8 +209,7 @@ static bool obs_source_init(struct obs_source *source) return false; } - obs_context_init_control(&source->context, source, - (obs_destroy_cb)obs_source_destroy); + obs_context_init_control(&source->context, source, (obs_destroy_cb)obs_source_destroy); source->deinterlace_top_first = true; source->audio_mixers = 0xFF; @@ -234,24 +226,19 @@ static void obs_source_init_finalize(struct obs_source *source) source->next_audio_source = obs->data.first_audio_source; source->prev_next_audio_source = &obs->data.first_audio_source; if (obs->data.first_audio_source) - obs->data.first_audio_source->prev_next_audio_source = - &source->next_audio_source; + obs->data.first_audio_source->prev_next_audio_source = &source->next_audio_source; obs->data.first_audio_source = source; pthread_mutex_unlock(&obs->data.audio_sources_mutex); } if (!source->context.private) { - obs_context_data_insert_name(&source->context, - &obs->data.sources_mutex, - &obs->data.public_sources); + obs_context_data_insert_name(&source->context, &obs->data.sources_mutex, &obs->data.public_sources); } - obs_context_data_insert_uuid(&source->context, &obs->data.sources_mutex, - &obs->data.sources); + obs_context_data_insert_uuid(&source->context, &obs->data.sources_mutex, &obs->data.sources); } -static bool obs_source_hotkey_mute(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *key, bool pressed) +static bool obs_source_hotkey_mute(void *data, obs_hotkey_pair_id id, obs_hotkey_t *key, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(key); @@ -265,8 +252,7 @@ static bool obs_source_hotkey_mute(void *data, obs_hotkey_pair_id id, return true; } -static bool obs_source_hotkey_unmute(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *key, bool pressed) +static bool obs_source_hotkey_unmute(void *data, obs_hotkey_pair_id id, obs_hotkey_t *key, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(key); @@ -280,12 +266,9 @@ static bool obs_source_hotkey_unmute(void *data, obs_hotkey_pair_id id, return true; } -static void obs_source_hotkey_push_to_mute(void *data, obs_hotkey_id id, - obs_hotkey_t *key, bool pressed) +static void obs_source_hotkey_push_to_mute(void *data, obs_hotkey_id id, obs_hotkey_t *key, bool pressed) { - struct audio_action action = {.timestamp = os_gettime_ns(), - .type = AUDIO_ACTION_PTM, - .set = pressed}; + struct audio_action action = {.timestamp = os_gettime_ns(), .type = AUDIO_ACTION_PTM, .set = pressed}; UNUSED_PARAMETER(id); UNUSED_PARAMETER(key); @@ -299,12 +282,9 @@ static void obs_source_hotkey_push_to_mute(void *data, obs_hotkey_id id, source->user_push_to_mute_pressed = pressed; } -static void obs_source_hotkey_push_to_talk(void *data, obs_hotkey_id id, - obs_hotkey_t *key, bool pressed) +static void obs_source_hotkey_push_to_talk(void *data, obs_hotkey_id id, obs_hotkey_t *key, bool pressed) { - struct audio_action action = {.timestamp = os_gettime_ns(), - .type = AUDIO_ACTION_PTT, - .set = pressed}; + struct audio_action action = {.timestamp = os_gettime_ns(), .type = AUDIO_ACTION_PTT, .set = pressed}; UNUSED_PARAMETER(id); UNUSED_PARAMETER(key); @@ -320,31 +300,27 @@ static void obs_source_hotkey_push_to_talk(void *data, obs_hotkey_id id, static void obs_source_init_audio_hotkeys(struct obs_source *source) { - if (!(source->info.output_flags & OBS_SOURCE_AUDIO) || - source->info.type != OBS_SOURCE_TYPE_INPUT) { + if (!(source->info.output_flags & OBS_SOURCE_AUDIO) || source->info.type != OBS_SOURCE_TYPE_INPUT) { source->mute_unmute_key = OBS_INVALID_HOTKEY_ID; source->push_to_talk_key = OBS_INVALID_HOTKEY_ID; return; } - source->mute_unmute_key = obs_hotkey_pair_register_source( - source, "libobs.mute", obs->hotkeys.mute, "libobs.unmute", - obs->hotkeys.unmute, obs_source_hotkey_mute, - obs_source_hotkey_unmute, source, source); + source->mute_unmute_key = obs_hotkey_pair_register_source(source, "libobs.mute", obs->hotkeys.mute, + "libobs.unmute", obs->hotkeys.unmute, + obs_source_hotkey_mute, obs_source_hotkey_unmute, + source, source); - source->push_to_mute_key = obs_hotkey_register_source( - source, "libobs.push-to-mute", obs->hotkeys.push_to_mute, - obs_source_hotkey_push_to_mute, source); + source->push_to_mute_key = obs_hotkey_register_source(source, "libobs.push-to-mute", obs->hotkeys.push_to_mute, + obs_source_hotkey_push_to_mute, source); - source->push_to_talk_key = obs_hotkey_register_source( - source, "libobs.push-to-talk", obs->hotkeys.push_to_talk, - obs_source_hotkey_push_to_talk, source); + source->push_to_talk_key = obs_hotkey_register_source(source, "libobs.push-to-talk", obs->hotkeys.push_to_talk, + obs_source_hotkey_push_to_talk, source); } -static obs_source_t * -obs_source_create_internal(const char *id, const char *name, const char *uuid, - obs_data_t *settings, obs_data_t *hotkey_data, - bool private, uint32_t last_obs_ver) +static obs_source_t *obs_source_create_internal(const char *id, const char *name, const char *uuid, + obs_data_t *settings, obs_data_t *hotkey_data, bool private, + uint32_t last_obs_ver) { struct obs_source *source = bzalloc(sizeof(struct obs_source)); @@ -371,8 +347,7 @@ obs_source_create_internal(const char *id, const char *name, const char *uuid, source->push_to_talk_key = OBS_INVALID_HOTKEY_ID; source->last_obs_ver = last_obs_ver; - if (!obs_source_init_context(source, settings, name, uuid, hotkey_data, - private)) + if (!obs_source_init_context(source, settings, name, uuid, hotkey_data, private)) goto fail; if (info) { @@ -380,8 +355,7 @@ obs_source_create_internal(const char *id, const char *name, const char *uuid, info->get_defaults(source->context.settings); } if (info->get_defaults2) { - info->get_defaults2(info->type_data, - source->context.settings); + info->get_defaults2(info->type_data, source->context.settings); } } @@ -394,13 +368,11 @@ obs_source_create_internal(const char *id, const char *name, const char *uuid, /* allow the source to be created even if creation fails so that the * user's data doesn't become lost */ if (info && info->create) - source->context.data = - info->create(source->context.settings, source); + source->context.data = info->create(source->context.settings, source); if ((!info || info->create) && !source->context.data) blog(LOG_ERROR, "Failed to create source '%s'!", name); - blog(LOG_DEBUG, "%ssource '%s' (%s) created", private ? "private " : "", - name, id); + blog(LOG_DEBUG, "%ssource '%s' (%s) created", private ? "private " : "", name, id); source->flags = source->default_flags; source->enabled = true; @@ -418,29 +390,20 @@ fail: return NULL; } -obs_source_t *obs_source_create(const char *id, const char *name, - obs_data_t *settings, obs_data_t *hotkey_data) +obs_source_t *obs_source_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data) { - return obs_source_create_internal(id, name, NULL, settings, hotkey_data, - false, LIBOBS_API_VER); + return obs_source_create_internal(id, name, NULL, settings, hotkey_data, false, LIBOBS_API_VER); } -obs_source_t *obs_source_create_private(const char *id, const char *name, - obs_data_t *settings) +obs_source_t *obs_source_create_private(const char *id, const char *name, obs_data_t *settings) { - return obs_source_create_internal(id, name, NULL, settings, NULL, true, - LIBOBS_API_VER); + return obs_source_create_internal(id, name, NULL, settings, NULL, true, LIBOBS_API_VER); } -obs_source_t *obs_source_create_set_last_ver(const char *id, const char *name, - const char *uuid, - obs_data_t *settings, - obs_data_t *hotkey_data, - uint32_t last_obs_ver, - bool is_private) +obs_source_t *obs_source_create_set_last_ver(const char *id, const char *name, const char *uuid, obs_data_t *settings, + obs_data_t *hotkey_data, uint32_t last_obs_ver, bool is_private) { - return obs_source_create_internal(id, name, uuid, settings, hotkey_data, - is_private, last_obs_ver); + return obs_source_create_internal(id, name, uuid, settings, hotkey_data, is_private, last_obs_ver); } static char *get_new_filter_name(obs_source_t *dst, const char *name) @@ -451,8 +414,7 @@ static char *get_new_filter_name(obs_source_t *dst, const char *name) dstr_copy(&new_name, name); for (;;) { - obs_source_t *existing_filter = - obs_source_get_filter_by_name(dst, new_name.array); + obs_source_t *existing_filter = obs_source_get_filter_by_name(dst, new_name.array); if (!existing_filter) break; @@ -464,8 +426,7 @@ static char *get_new_filter_name(obs_source_t *dst, const char *name) return new_name.array; } -static void duplicate_filters(obs_source_t *dst, obs_source_t *src, - bool private) +static void duplicate_filters(obs_source_t *dst, obs_source_t *src, bool private) { DARRAY(obs_source_t *) filters; @@ -482,12 +443,10 @@ static void duplicate_filters(obs_source_t *dst, obs_source_t *src, for (size_t i = filters.num; i > 0; i--) { obs_source_t *src_filter = filters.array[i - 1]; - char *new_name = - get_new_filter_name(dst, src_filter->context.name); + char *new_name = get_new_filter_name(dst, src_filter->context.name); bool enabled = obs_source_enabled(src_filter); - obs_source_t *dst_filter = - obs_source_duplicate(src_filter, new_name, private); + obs_source_t *dst_filter = obs_source_duplicate(src_filter, new_name, private); obs_source_set_enabled(dst_filter, enabled); bfree(new_name); @@ -535,8 +494,7 @@ void obs_source_copy_single_filter(obs_source_t *dst, obs_source_t *filter) duplicate_filter(dst, filter); } -obs_source_t *obs_source_duplicate(obs_source_t *source, const char *new_name, - bool create_private) +obs_source_t *obs_source_duplicate(obs_source_t *source, const char *new_name, bool create_private) { obs_source_t *new_source; obs_data_t *settings; @@ -555,9 +513,7 @@ obs_source_t *obs_source_duplicate(obs_source_t *source, const char *new_name, return NULL; obs_scene_t *new_scene = obs_scene_duplicate( - scene, new_name, - create_private ? OBS_SCENE_DUP_PRIVATE_COPY - : OBS_SCENE_DUP_COPY); + scene, new_name, create_private ? OBS_SCENE_DUP_PRIVATE_COPY : OBS_SCENE_DUP_COPY); obs_source_t *new_source = obs_scene_get_source(new_scene); return new_source; } @@ -569,11 +525,8 @@ obs_source_t *obs_source_duplicate(obs_source_t *source, const char *new_name, settings = obs_data_create(); obs_data_apply(settings, source->context.settings); - new_source = create_private - ? obs_source_create_private(source->info.id, - new_name, settings) - : obs_source_create(source->info.id, new_name, - settings, NULL); + new_source = create_private ? obs_source_create_private(source->info.id, new_name, settings) + : obs_source_create(source->info.id, new_name, settings, NULL); new_source->audio_mixers = source->audio_mixers; new_source->sync_offset = source->sync_offset; @@ -592,9 +545,7 @@ obs_source_t *obs_source_duplicate(obs_source_t *source, const char *new_name, return new_source; } -void obs_source_frame_init(struct obs_source_frame *frame, - enum video_format format, uint32_t width, - uint32_t height) +void obs_source_frame_init(struct obs_source_frame *frame, enum video_format format, uint32_t width, uint32_t height) { struct video_frame vid_frame; @@ -618,8 +569,7 @@ static inline void obs_source_frame_decref(struct obs_source_frame *frame) obs_source_frame_destroy(frame); } -static bool obs_source_filter_remove_refless(obs_source_t *source, - obs_source_t *filter); +static bool obs_source_filter_remove_refless(obs_source_t *source, obs_source_t *filter); static void obs_source_destroy_defer(struct obs_source *source); void obs_source_destroy(struct obs_source *source) @@ -652,8 +602,7 @@ void obs_source_destroy(struct obs_source *source) if (source->prev_next_audio_source) { *source->prev_next_audio_source = source->next_audio_source; if (source->next_audio_source) - source->next_audio_source->prev_next_audio_source = - source->prev_next_audio_source; + source->next_audio_source->prev_next_audio_source = source->prev_next_audio_source; } pthread_mutex_unlock(&obs->data.audio_sources_mutex); @@ -665,14 +614,12 @@ void obs_source_destroy(struct obs_source *source) obs_context_data_remove_uuid(&source->context, &obs->data.sources); if (!source->context.private) - obs_context_data_remove_name(&source->context, - &obs->data.public_sources); + obs_context_data_remove_name(&source->context, &obs->data.public_sources); source_profiler_remove_source(source); /* defer source destroy */ - os_task_queue_queue_task(obs->destruction_task_thread, - (os_task_t)obs_source_destroy_defer, source); + os_task_queue_queue_task(obs->destruction_task_thread, (os_task_t)obs_source_destroy_defer, source); } static void obs_source_destroy_defer(struct obs_source *source) @@ -690,8 +637,7 @@ static void obs_source_destroy_defer(struct obs_source *source) source->context.data = NULL; } - blog(LOG_DEBUG, "%ssource '%s' destroyed", - source->context.private ? "private " : "", source->context.name); + blog(LOG_DEBUG, "%ssource '%s' destroyed", source->context.private ? "private " : "", source->context.name); audio_monitor_destroy(source->monitor); @@ -833,8 +779,7 @@ bool obs_weak_source_expired(obs_weak_source_t *weak) return weak ? obs_weak_ref_expired(&weak->ref) : true; } -bool obs_weak_source_references_source(obs_weak_source_t *weak, - obs_source_t *source) +bool obs_weak_source_references_source(obs_weak_source_t *weak, obs_source_t *source) { return weak && source && weak->source == source; } @@ -856,8 +801,7 @@ void obs_source_remove(obs_source_t *source) bool obs_source_removed(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_removed") ? source->removed - : true; + return obs_source_valid(source, "obs_source_removed") ? source->removed : true; } static inline obs_data_t *get_defaults(const struct obs_source_info *info) @@ -913,9 +857,7 @@ obs_missing_files_t *obs_source_get_missing_files(const obs_source_t *source) return obs_missing_files_create(); } -void obs_source_replace_missing_file(obs_missing_file_cb cb, - obs_source_t *source, const char *new_path, - void *data) +void obs_source_replace_missing_file(obs_missing_file_cb cb, obs_source_t *source, const char *new_path, void *data) { if (!data_valid(source, "obs_source_replace_missing_file")) return; @@ -942,8 +884,7 @@ obs_properties_t *obs_source_properties(const obs_source_t *source) if (source->info.get_properties2) { obs_properties_t *props; - props = source->info.get_properties2(source->context.data, - source->info.type_data); + props = source->info.get_properties2(source->context.data, source->info.type_data); obs_properties_apply_settings(props, source->context.settings); return props; @@ -959,9 +900,7 @@ obs_properties_t *obs_source_properties(const obs_source_t *source) uint32_t obs_source_get_output_flags(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_output_flags") - ? source->info.output_flags - : 0; + return obs_source_valid(source, "obs_source_get_output_flags") ? source->info.output_flags : 0; } uint32_t obs_get_source_output_flags(const char *id) @@ -974,10 +913,8 @@ static void obs_source_deferred_update(obs_source_t *source) { if (source->context.data && source->info.update) { long count = os_atomic_load_long(&source->defer_update_count); - source->info.update(source->context.data, - source->context.settings); - os_atomic_compare_swap_long(&source->defer_update_count, count, - 0); + source->info.update(source->context.data, source->context.settings); + os_atomic_compare_swap_long(&source->defer_update_count, count, 0); obs_source_dosignal(source, "source_update", "update"); } } @@ -994,8 +931,7 @@ void obs_source_update(obs_source_t *source, obs_data_t *settings) if (source->info.output_flags & OBS_SOURCE_VIDEO) { os_atomic_inc_long(&source->defer_update_count); } else if (source->context.data && source->info.update) { - source->info.update(source->context.data, - source->context.settings); + source->info.update(source->context.data, source->context.settings); obs_source_dosignal(source, "source_update", "update"); } } @@ -1017,9 +953,7 @@ void obs_source_update_properties(obs_source_t *source) obs_source_dosignal(source, NULL, "update_properties"); } -void obs_source_send_mouse_click(obs_source_t *source, - const struct obs_mouse_event *event, - int32_t type, bool mouse_up, +void obs_source_send_mouse_click(obs_source_t *source, const struct obs_mouse_event *event, int32_t type, bool mouse_up, uint32_t click_count) { if (!obs_source_valid(source, "obs_source_send_mouse_click")) @@ -1027,38 +961,31 @@ void obs_source_send_mouse_click(obs_source_t *source, if (source->info.output_flags & OBS_SOURCE_INTERACTION) { if (source->info.mouse_click) { - source->info.mouse_click(source->context.data, event, - type, mouse_up, click_count); + source->info.mouse_click(source->context.data, event, type, mouse_up, click_count); } } } -void obs_source_send_mouse_move(obs_source_t *source, - const struct obs_mouse_event *event, - bool mouse_leave) +void obs_source_send_mouse_move(obs_source_t *source, const struct obs_mouse_event *event, bool mouse_leave) { if (!obs_source_valid(source, "obs_source_send_mouse_move")) return; if (source->info.output_flags & OBS_SOURCE_INTERACTION) { if (source->info.mouse_move) { - source->info.mouse_move(source->context.data, event, - mouse_leave); + source->info.mouse_move(source->context.data, event, mouse_leave); } } } -void obs_source_send_mouse_wheel(obs_source_t *source, - const struct obs_mouse_event *event, - int x_delta, int y_delta) +void obs_source_send_mouse_wheel(obs_source_t *source, const struct obs_mouse_event *event, int x_delta, int y_delta) { if (!obs_source_valid(source, "obs_source_send_mouse_wheel")) return; if (source->info.output_flags & OBS_SOURCE_INTERACTION) { if (source->info.mouse_wheel) { - source->info.mouse_wheel(source->context.data, event, - x_delta, y_delta); + source->info.mouse_wheel(source->context.data, event, x_delta, y_delta); } } } @@ -1075,16 +1002,14 @@ void obs_source_send_focus(obs_source_t *source, bool focus) } } -void obs_source_send_key_click(obs_source_t *source, - const struct obs_key_event *event, bool key_up) +void obs_source_send_key_click(obs_source_t *source, const struct obs_key_event *event, bool key_up) { if (!obs_source_valid(source, "obs_source_send_key_click")) return; if (source->info.output_flags & OBS_SOURCE_INTERACTION) { if (source->info.key_click) { - source->info.key_click(source->context.data, event, - key_up); + source->info.key_click(source->context.data, event, key_up); } } } @@ -1127,8 +1052,7 @@ static void hide_source(obs_source_t *source) obs_source_dosignal(source, "source_hide", "hide"); } -static void activate_tree(obs_source_t *parent, obs_source_t *child, - void *param) +static void activate_tree(obs_source_t *parent, obs_source_t *child, void *param) { os_atomic_inc_long(&child->activate_refs); @@ -1136,8 +1060,7 @@ static void activate_tree(obs_source_t *parent, obs_source_t *child, UNUSED_PARAMETER(param); } -static void deactivate_tree(obs_source_t *parent, obs_source_t *child, - void *param) +static void deactivate_tree(obs_source_t *parent, obs_source_t *child, void *param) { os_atomic_dec_long(&child->activate_refs); @@ -1188,17 +1111,14 @@ void obs_source_deactivate(obs_source_t *source, enum view_type type) if (type == MAIN_VIEW) { if (os_atomic_load_long(&source->activate_refs) > 0) { os_atomic_dec_long(&source->activate_refs); - obs_source_enum_active_tree(source, deactivate_tree, - NULL); + obs_source_enum_active_tree(source, deactivate_tree, NULL); } } } -static inline struct obs_source_frame *get_closest_frame(obs_source_t *source, - uint64_t sys_time); +static inline struct obs_source_frame *get_closest_frame(obs_source_t *source, uint64_t sys_time); -static void filter_frame(obs_source_t *source, - struct obs_source_frame **ref_frame) +static void filter_frame(obs_source_t *source, struct obs_source_frame **ref_frame) { struct obs_source_frame *frame = *ref_frame; if (frame) { @@ -1229,12 +1149,10 @@ void process_media_actions(obs_source_t *source) case MEDIA_ACTION_NONE: return; case MEDIA_ACTION_PLAY_PAUSE: - source->info.media_play_pause(source->context.data, - action.pause); + source->info.media_play_pause(source->context.data, action.pause); if (action.pause) - obs_source_dosignal(source, NULL, - "media_pause"); + obs_source_dosignal(source, NULL, "media_pause"); else obs_source_dosignal(source, NULL, "media_play"); break; @@ -1257,8 +1175,7 @@ void process_media_actions(obs_source_t *source) obs_source_dosignal(source, NULL, "media_previous"); break; case MEDIA_ACTION_SET_TIME: - source->info.media_set_time(source->context.data, - action.ms); + source->info.media_set_time(source->context.data, action.ms); break; } } @@ -1288,8 +1205,7 @@ static void async_tick(obs_source_t *source) filter_frame(source, &source->cur_async_frame); if (source->cur_async_frame) - source->async_update_texture = - set_async_texture_size(source, source->cur_async_frame); + source->async_update_texture = set_async_texture_size(source, source->cur_async_frame); pthread_mutex_unlock(&source->async_mutex); } @@ -1328,8 +1244,7 @@ void obs_source_video_tick(obs_source_t *source, float seconds) if (source->filters.num) { for (size_t i = source->filters.num; i > 0; i--) { - obs_source_t *filter = - source->filters.array[i - 1]; + obs_source_t *filter = source->filters.array[i - 1]; if (now_showing) { show_source(filter); } else { @@ -1352,8 +1267,7 @@ void obs_source_video_tick(obs_source_t *source, float seconds) if (source->filters.num) { for (size_t i = source->filters.num; i > 0; i--) { - obs_source_t *filter = - source->filters.array[i - 1]; + obs_source_t *filter = source->filters.array[i - 1]; if (now_active) { activate_source(filter); } else { @@ -1373,8 +1287,7 @@ void obs_source_video_tick(obs_source_t *source, float seconds) } /* unless the value is 3+ hours worth of frames, this won't overflow */ -static inline uint64_t conv_frames_to_time(const size_t sample_rate, - const size_t frames) +static inline uint64_t conv_frames_to_time(const size_t sample_rate, const size_t frames) { if (!sample_rate) return 0; @@ -1382,8 +1295,7 @@ static inline uint64_t conv_frames_to_time(const size_t sample_rate, return util_mul_div64(frames, 1000000000ULL, sample_rate); } -static inline size_t conv_time_to_frames(const size_t sample_rate, - const uint64_t duration) +static inline size_t conv_time_to_frames(const size_t sample_rate, const uint64_t duration) { return (size_t)util_mul_div64(duration, sample_rate, 1000000000ULL); } @@ -1395,8 +1307,7 @@ static inline size_t conv_time_to_frames(const size_t sample_rate, * possible */ #define TS_SMOOTHING_THRESHOLD 70000000ULL -static inline void reset_audio_timing(obs_source_t *source, uint64_t timestamp, - uint64_t os_time) +static inline void reset_audio_timing(obs_source_t *source, uint64_t timestamp, uint64_t os_time) { source->timing_set = true; source->timing_adjust = os_time - timestamp; @@ -1406,8 +1317,7 @@ static void reset_audio_data(obs_source_t *source, uint64_t os_time) { for (size_t i = 0; i < MAX_AUDIO_CHANNELS; i++) { if (source->audio_input_buf[i].size) - deque_pop_front(&source->audio_input_buf[i], NULL, - source->audio_input_buf[i].size); + deque_pop_front(&source->audio_input_buf[i], NULL, source->audio_input_buf[i].size); } source->last_audio_input_buf_size = 0; @@ -1415,8 +1325,7 @@ static void reset_audio_data(obs_source_t *source, uint64_t os_time) source->next_audio_sys_ts_min = os_time; } -static void handle_ts_jump(obs_source_t *source, uint64_t expected, uint64_t ts, - uint64_t diff, uint64_t os_time) +static void handle_ts_jump(obs_source_t *source, uint64_t expected, uint64_t ts, uint64_t diff, uint64_t os_time) { blog(LOG_DEBUG, "Timestamp for source '%s' jumped by '%" PRIu64 "', " @@ -1429,8 +1338,7 @@ static void handle_ts_jump(obs_source_t *source, uint64_t expected, uint64_t ts, pthread_mutex_unlock(&source->audio_buf_mutex); } -static void source_signal_audio_data(obs_source_t *source, - const struct audio_data *in, bool muted) +static void source_signal_audio_data(obs_source_t *source, const struct audio_data *in, bool muted) { pthread_mutex_lock(&source->audio_cb_mutex); @@ -1453,8 +1361,7 @@ static inline size_t get_buf_placement(audio_t *audio, uint64_t offset) return (size_t)util_mul_div64(offset, sample_rate, 1000000000ULL); } -static void source_output_audio_place(obs_source_t *source, - const struct audio_data *in) +static void source_output_audio_place(obs_source_t *source, const struct audio_data *in) { audio_t *audio = obs->audio.audio; size_t buf_placement; @@ -1464,16 +1371,12 @@ static void source_output_audio_place(obs_source_t *source, if (!source->audio_ts || in->timestamp < source->audio_ts) reset_audio_data(source, in->timestamp); - buf_placement = - get_buf_placement(audio, in->timestamp - source->audio_ts) * - sizeof(float); + buf_placement = get_buf_placement(audio, in->timestamp - source->audio_ts) * sizeof(float); #if DEBUG_AUDIO == 1 - blog(LOG_DEBUG, - "frames: %lu, size: %lu, placement: %lu, base_ts: %llu, ts: %llu", - (unsigned long)in->frames, - (unsigned long)source->audio_input_buf[0].size, - (unsigned long)buf_placement, source->audio_ts, in->timestamp); + blog(LOG_DEBUG, "frames: %lu, size: %lu, placement: %lu, base_ts: %llu, ts: %llu", (unsigned long)in->frames, + (unsigned long)source->audio_input_buf[0].size, (unsigned long)buf_placement, source->audio_ts, + in->timestamp); #endif /* do not allow the circular buffers to become too big */ @@ -1481,18 +1384,15 @@ static void source_output_audio_place(obs_source_t *source, return; for (size_t i = 0; i < channels; i++) { - deque_place(&source->audio_input_buf[i], buf_placement, - in->data[i], size); + deque_place(&source->audio_input_buf[i], buf_placement, in->data[i], size); deque_pop_back(&source->audio_input_buf[i], NULL, - source->audio_input_buf[i].size - - (buf_placement + size)); + source->audio_input_buf[i].size - (buf_placement + size)); } source->last_audio_input_buf_size = 0; } -static inline void source_output_audio_push_back(obs_source_t *source, - const struct audio_data *in) +static inline void source_output_audio_push_back(obs_source_t *source, const struct audio_data *in) { audio_t *audio = obs->audio.audio; size_t channels = audio_output_get_channels(audio); @@ -1513,25 +1413,19 @@ static inline void source_output_audio_push_back(obs_source_t *source, static inline bool source_muted(obs_source_t *source, uint64_t os_time) { if (source->push_to_mute_enabled && source->user_push_to_mute_pressed) - source->push_to_mute_stop_time = - os_time + source->push_to_mute_delay * 1000000; + source->push_to_mute_stop_time = os_time + source->push_to_mute_delay * 1000000; if (source->push_to_talk_enabled && source->user_push_to_talk_pressed) - source->push_to_talk_stop_time = - os_time + source->push_to_talk_delay * 1000000; + source->push_to_talk_stop_time = os_time + source->push_to_talk_delay * 1000000; - bool push_to_mute_active = source->user_push_to_mute_pressed || - os_time < source->push_to_mute_stop_time; - bool push_to_talk_active = source->user_push_to_talk_pressed || - os_time < source->push_to_talk_stop_time; + bool push_to_mute_active = source->user_push_to_mute_pressed || os_time < source->push_to_mute_stop_time; + bool push_to_talk_active = source->user_push_to_talk_pressed || os_time < source->push_to_talk_stop_time; - return !source->enabled || source->user_muted || - (source->push_to_mute_enabled && push_to_mute_active) || + return !source->enabled || source->user_muted || (source->push_to_mute_enabled && push_to_mute_active) || (source->push_to_talk_enabled && !push_to_talk_active); } -static void source_output_audio_data(obs_source_t *source, - const struct audio_data *data) +static void source_output_audio_data(obs_source_t *source, const struct audio_data *data) { size_t sample_rate = audio_output_get_sample_rate(obs->audio.audio); struct audio_data in = *data; @@ -1557,8 +1451,7 @@ static void source_output_audio_data(obs_source_t *source, /* smooth audio if within threshold */ if (diff > MAX_TS_VAR && !using_direct_ts) - handle_ts_jump(source, source->next_audio_ts_min, - in.timestamp, diff, os_time); + handle_ts_jump(source, source->next_audio_ts_min, in.timestamp, diff, os_time); else if (diff < TS_SMOOTHING_THRESHOLD) { if (source->async_unbuffered && source->async_decoupled) source->timing_adjust = os_time - in.timestamp; @@ -1567,13 +1460,11 @@ static void source_output_audio_data(obs_source_t *source, blog(LOG_DEBUG, "Audio timestamp for '%s' exceeded TS_SMOOTHING_THRESHOLD, diff=%" PRIu64 " ns, expected %" PRIu64 ", input %" PRIu64, - source->context.name, diff, - source->next_audio_ts_min, in.timestamp); + source->context.name, diff, source->next_audio_ts_min, in.timestamp); } } - source->next_audio_ts_min = - in.timestamp + conv_frames_to_time(sample_rate, in.frames); + source->next_audio_ts_min = in.timestamp + conv_frames_to_time(sample_rate, in.frames); in.timestamp += source->timing_adjust; @@ -1604,8 +1495,7 @@ static void source_output_audio_data(obs_source_t *source, in.timestamp += sync_offset; in.timestamp -= source->resample_offset; - source->next_audio_sys_ts_min = - source->next_audio_ts_min + source->timing_adjust; + source->next_audio_sys_ts_min = source->next_audio_ts_min + source->timing_adjust; if (source->last_sync_offset != sync_offset) { if (source->last_sync_offset) @@ -1649,8 +1539,7 @@ enum convert_type { CONVERT_R10L, }; -static inline enum convert_type get_convert_type(enum video_format format, - bool full_range, uint8_t trc) +static inline enum convert_type get_convert_type(enum video_format format, bool full_range, uint8_t trc) { switch (format) { case VIDEO_FORMAT_I420: @@ -1719,8 +1608,7 @@ static inline enum convert_type get_convert_type(enum video_format format, return CONVERT_NONE; } -static inline bool set_packed422_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_packed422_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1732,9 +1620,7 @@ static inline bool set_packed422_sizes(struct obs_source *source, return true; } -static inline bool -set_packed444_alpha_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_packed444_alpha_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_height[0] = frame->height; @@ -1743,8 +1629,7 @@ set_packed444_alpha_sizes(struct obs_source *source, return true; } -static inline bool set_planar444_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar444_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_width[1] = frame->width; @@ -1759,8 +1644,7 @@ static inline bool set_planar444_sizes(struct obs_source *source, return true; } -static inline bool set_planar444_16_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar444_16_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_width[1] = frame->width; @@ -1775,9 +1659,7 @@ static inline bool set_planar444_16_sizes(struct obs_source *source, return true; } -static inline bool -set_planar444_alpha_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar444_alpha_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_width[1] = frame->width; @@ -1795,9 +1677,7 @@ set_planar444_alpha_sizes(struct obs_source *source, return true; } -static inline bool -set_planar444_16_alpha_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar444_16_alpha_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_width[1] = frame->width; @@ -1815,8 +1695,7 @@ set_planar444_16_alpha_sizes(struct obs_source *source, return true; } -static inline bool set_planar420_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar420_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1835,9 +1714,7 @@ static inline bool set_planar420_sizes(struct obs_source *source, return true; } -static inline bool -set_planar420_alpha_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar420_alpha_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1859,8 +1736,7 @@ set_planar420_alpha_sizes(struct obs_source *source, return true; } -static inline bool set_planar422_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar422_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1877,8 +1753,7 @@ static inline bool set_planar422_sizes(struct obs_source *source, source->async_channel_count = 3; return true; } -static inline bool set_planar422_16_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar422_16_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1896,9 +1771,7 @@ static inline bool set_planar422_16_sizes(struct obs_source *source, return true; } -static inline bool -set_planar422_alpha_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_planar422_alpha_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1919,8 +1792,7 @@ set_planar422_alpha_sizes(struct obs_source *source, return true; } -static inline bool set_nv12_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_nv12_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1936,8 +1808,7 @@ static inline bool set_nv12_sizes(struct obs_source *source, return true; } -static inline bool set_y800_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_y800_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_height[0] = frame->height; @@ -1946,19 +1817,16 @@ static inline bool set_y800_sizes(struct obs_source *source, return true; } -static inline bool set_rgb_limited_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_rgb_limited_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_height[0] = frame->height; - source->async_texture_formats[0] = - convert_video_format(frame->format, frame->trc); + source->async_texture_formats[0] = convert_video_format(frame->format, frame->trc); source->async_channel_count = 1; return true; } -static inline bool set_bgr3_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_bgr3_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width * 3; source->async_convert_height[0] = frame->height; @@ -1967,8 +1835,7 @@ static inline bool set_bgr3_sizes(struct obs_source *source, return true; } -static inline bool set_i010_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_i010_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -1987,8 +1854,7 @@ static inline bool set_i010_sizes(struct obs_source *source, return true; } -static inline bool set_p010_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_p010_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -2004,8 +1870,7 @@ static inline bool set_p010_sizes(struct obs_source *source, return true; } -static inline bool set_v210_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_v210_sizes(struct obs_source *source, const struct obs_source_frame *frame) { const uint32_t width = frame->width; const uint32_t height = frame->height; @@ -2017,8 +1882,7 @@ static inline bool set_v210_sizes(struct obs_source *source, return true; } -static inline bool set_r10l_sizes(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool set_r10l_sizes(struct obs_source *source, const struct obs_source_frame *frame) { source->async_convert_width[0] = frame->width; source->async_convert_height[0] = frame->height; @@ -2027,11 +1891,9 @@ static inline bool set_r10l_sizes(struct obs_source *source, return true; } -static inline bool init_gpu_conversion(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool init_gpu_conversion(struct obs_source *source, const struct obs_source_frame *frame) { - switch (get_convert_type(frame->format, frame->full_range, - frame->trc)) { + switch (get_convert_type(frame->format, frame->full_range, frame->trc)) { case CONVERT_422_PACK: return set_packed422_sizes(source, frame); @@ -2097,16 +1959,12 @@ static inline bool init_gpu_conversion(struct obs_source *source, return false; } -bool set_async_texture_size(struct obs_source *source, - const struct obs_source_frame *frame) +bool set_async_texture_size(struct obs_source *source, const struct obs_source_frame *frame) { - enum convert_type cur = - get_convert_type(frame->format, frame->full_range, frame->trc); + enum convert_type cur = get_convert_type(frame->format, frame->full_range, frame->trc); - if (source->async_width == frame->width && - source->async_height == frame->height && - source->async_format == frame->format && - source->async_full_range == frame->full_range && + if (source->async_width == frame->width && source->async_height == frame->height && + source->async_format == frame->format && source->async_full_range == frame->full_range && source->async_trc == frame->trc) return true; @@ -2130,25 +1988,18 @@ bool set_async_texture_size(struct obs_source *source, source->async_texrender = NULL; source->async_prev_texrender = NULL; - const enum gs_color_format format = - convert_video_format(frame->format, frame->trc); - const bool async_gpu_conversion = (cur != CONVERT_NONE) && - init_gpu_conversion(source, frame); + const enum gs_color_format format = convert_video_format(frame->format, frame->trc); + const bool async_gpu_conversion = (cur != CONVERT_NONE) && init_gpu_conversion(source, frame); source->async_gpu_conversion = async_gpu_conversion; if (async_gpu_conversion) { - source->async_texrender = - gs_texrender_create(format, GS_ZS_NONE); + source->async_texrender = gs_texrender_create(format, GS_ZS_NONE); for (int c = 0; c < source->async_channel_count; ++c) - source->async_textures[c] = gs_texture_create( - source->async_convert_width[c], - source->async_convert_height[c], - source->async_texture_formats[c], 1, NULL, - GS_DYNAMIC); + source->async_textures[c] = + gs_texture_create(source->async_convert_width[c], source->async_convert_height[c], + source->async_texture_formats[c], 1, NULL, GS_DYNAMIC); } else { - source->async_textures[0] = - gs_texture_create(frame->width, frame->height, format, - 1, NULL, GS_DYNAMIC); + source->async_textures[0] = gs_texture_create(frame->width, frame->height, format, 1, NULL, GS_DYNAMIC); } if (deinterlacing_enabled(source)) @@ -2159,11 +2010,9 @@ bool set_async_texture_size(struct obs_source *source, return source->async_textures[0] != NULL; } -static void upload_raw_frame(gs_texture_t *tex[MAX_AV_PLANES], - const struct obs_source_frame *frame) +static void upload_raw_frame(gs_texture_t *tex[MAX_AV_PLANES], const struct obs_source_frame *frame) { - switch (get_convert_type(frame->format, frame->full_range, - frame->trc)) { + switch (get_convert_type(frame->format, frame->full_range, frame->trc)) { case CONVERT_422_PACK: case CONVERT_800: case CONVERT_RGB_LIMITED: @@ -2186,8 +2035,7 @@ static void upload_raw_frame(gs_texture_t *tex[MAX_AV_PLANES], case CONVERT_R10L: for (size_t c = 0; c < MAX_AV_PLANES; c++) { if (tex[c]) - gs_texture_set_image(tex[c], frame->data[c], - frame->linesize[c], false); + gs_texture_set_image(tex[c], frame->data[c], frame->linesize[c], false); } break; @@ -2197,8 +2045,7 @@ static void upload_raw_frame(gs_texture_t *tex[MAX_AV_PLANES], } } -static const char *select_conversion_technique(enum video_format format, - bool full_range, uint8_t trc) +static const char *select_conversion_technique(enum video_format format, bool full_range, uint8_t trc) { switch (format) { case VIDEO_FORMAT_UYVY: @@ -2320,14 +2167,11 @@ static const char *select_conversion_technique(enum video_format format, case VIDEO_FORMAT_R10L: { switch (trc) { case VIDEO_TRC_PQ: - return full_range ? "R10L_PQ_2020_709_Full_Reverse" - : "R10L_PQ_2020_709_Limited_Reverse"; + return full_range ? "R10L_PQ_2020_709_Full_Reverse" : "R10L_PQ_2020_709_Limited_Reverse"; case VIDEO_TRC_HLG: - return full_range ? "R10L_HLG_2020_709_Full_Reverse" - : "R10L_HLG_2020_709_Limited_Reverse"; + return full_range ? "R10L_HLG_2020_709_Full_Reverse" : "R10L_HLG_2020_709_Limited_Reverse"; default: - return full_range ? "R10L_SRGB_Full_Reverse" - : "R10L_SRGB_Limited_Reverse"; + return full_range ? "R10L_SRGB_Full_Reverse" : "R10L_SRGB_Limited_Reverse"; } } @@ -2351,9 +2195,8 @@ static const char *select_conversion_technique(enum video_format format, static bool need_linear_output(enum video_format format) { - return (format == VIDEO_FORMAT_I010) || (format == VIDEO_FORMAT_P010) || - (format == VIDEO_FORMAT_I210) || (format == VIDEO_FORMAT_I412) || - (format == VIDEO_FORMAT_YA2L); + return (format == VIDEO_FORMAT_I010) || (format == VIDEO_FORMAT_P010) || (format == VIDEO_FORMAT_I210) || + (format == VIDEO_FORMAT_I412) || (format == VIDEO_FORMAT_YA2L); } static inline void set_eparam(gs_effect_t *effect, const char *name, float val) @@ -2362,10 +2205,8 @@ static inline void set_eparam(gs_effect_t *effect, const char *name, float val) gs_effect_set_float(param, val); } -static bool update_async_texrender(struct obs_source *source, - const struct obs_source_frame *frame, - gs_texture_t *tex[MAX_AV_PLANES], - gs_texrender_t *texrender) +static bool update_async_texrender(struct obs_source *source, const struct obs_source_frame *frame, + gs_texture_t *tex[MAX_AV_PLANES], gs_texrender_t *texrender) { GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_CONVERT_FORMAT, "Convert Format"); @@ -2376,8 +2217,7 @@ static bool update_async_texrender(struct obs_source *source, uint32_t cx = source->async_width; uint32_t cy = source->async_height; - const char *tech_name = select_conversion_technique( - frame->format, frame->full_range, frame->trc); + const char *tech_name = select_conversion_technique(frame->format, frame->full_range, frame->trc); gs_effect_t *conv = obs->video.conversion_effect; gs_technique_t *tech = gs_effect_get_technique(conv, tech_name); const bool linear = need_linear_output(frame->format); @@ -2394,21 +2234,13 @@ static bool update_async_texrender(struct obs_source *source, gs_technique_begin_pass(tech, 0); if (tex[0]) - gs_effect_set_texture( - gs_effect_get_param_by_name(conv, "image"), - tex[0]); + gs_effect_set_texture(gs_effect_get_param_by_name(conv, "image"), tex[0]); if (tex[1]) - gs_effect_set_texture( - gs_effect_get_param_by_name(conv, "image1"), - tex[1]); + gs_effect_set_texture(gs_effect_get_param_by_name(conv, "image1"), tex[1]); if (tex[2]) - gs_effect_set_texture( - gs_effect_get_param_by_name(conv, "image2"), - tex[2]); + gs_effect_set_texture(gs_effect_get_param_by_name(conv, "image2"), tex[2]); if (tex[3]) - gs_effect_set_texture( - gs_effect_get_param_by_name(conv, "image3"), - tex[3]); + gs_effect_set_texture(gs_effect_get_param_by_name(conv, "image3"), tex[3]); set_eparam(conv, "width", (float)cx); set_eparam(conv, "height", (float)cy); set_eparam(conv, "width_d2", (float)cx * 0.5f); @@ -2421,40 +2253,28 @@ static bool update_async_texrender(struct obs_source *source, if (hlg_peak_level > 1000.f) hlg_peak_level = 1000.f; - const float maximum_nits = (frame->trc == VIDEO_TRC_HLG) - ? hlg_peak_level - : 10000.f; - set_eparam(conv, "maximum_over_sdr_white_nits", - maximum_nits / obs_get_video_sdr_white_level()); - const float hlg_exponent = - 0.2f + (0.42f * log10f(hlg_peak_level / 1000.f)); + const float maximum_nits = (frame->trc == VIDEO_TRC_HLG) ? hlg_peak_level : 10000.f; + set_eparam(conv, "maximum_over_sdr_white_nits", maximum_nits / obs_get_video_sdr_white_level()); + const float hlg_exponent = 0.2f + (0.42f * log10f(hlg_peak_level / 1000.f)); set_eparam(conv, "hlg_exponent", hlg_exponent); set_eparam(conv, "hdr_lw", (float)frame->max_luminance); - set_eparam(conv, "hdr_lmax", - obs_get_video_hdr_nominal_peak_level()); + set_eparam(conv, "hdr_lmax", obs_get_video_hdr_nominal_peak_level()); struct vec4 vec0, vec1, vec2; - vec4_set(&vec0, frame->color_matrix[0], frame->color_matrix[1], - frame->color_matrix[2], frame->color_matrix[3]); - vec4_set(&vec1, frame->color_matrix[4], frame->color_matrix[5], - frame->color_matrix[6], frame->color_matrix[7]); - vec4_set(&vec2, frame->color_matrix[8], frame->color_matrix[9], - frame->color_matrix[10], frame->color_matrix[11]); - gs_effect_set_vec4( - gs_effect_get_param_by_name(conv, "color_vec0"), &vec0); - gs_effect_set_vec4( - gs_effect_get_param_by_name(conv, "color_vec1"), &vec1); - gs_effect_set_vec4( - gs_effect_get_param_by_name(conv, "color_vec2"), &vec2); + vec4_set(&vec0, frame->color_matrix[0], frame->color_matrix[1], frame->color_matrix[2], + frame->color_matrix[3]); + vec4_set(&vec1, frame->color_matrix[4], frame->color_matrix[5], frame->color_matrix[6], + frame->color_matrix[7]); + vec4_set(&vec2, frame->color_matrix[8], frame->color_matrix[9], frame->color_matrix[10], + frame->color_matrix[11]); + gs_effect_set_vec4(gs_effect_get_param_by_name(conv, "color_vec0"), &vec0); + gs_effect_set_vec4(gs_effect_get_param_by_name(conv, "color_vec1"), &vec1); + gs_effect_set_vec4(gs_effect_get_param_by_name(conv, "color_vec2"), &vec2); if (!frame->full_range) { - gs_eparam_t *min_param = gs_effect_get_param_by_name( - conv, "color_range_min"); - gs_effect_set_val(min_param, frame->color_range_min, - sizeof(float) * 3); - gs_eparam_t *max_param = gs_effect_get_param_by_name( - conv, "color_range_max"); - gs_effect_set_val(max_param, frame->color_range_max, - sizeof(float) * 3); + gs_eparam_t *min_param = gs_effect_get_param_by_name(conv, "color_range_min"); + gs_effect_set_val(min_param, frame->color_range_min, sizeof(float) * 3); + gs_eparam_t *max_param = gs_effect_get_param_by_name(conv, "color_range_max"); + gs_effect_set_val(max_param, frame->color_range_max, sizeof(float) * 3); } gs_draw(GS_TRIS, 0, 3); @@ -2473,41 +2293,34 @@ static bool update_async_texrender(struct obs_source *source, return success; } -bool update_async_texture(struct obs_source *source, - const struct obs_source_frame *frame, - gs_texture_t *tex, gs_texrender_t *texrender) +bool update_async_texture(struct obs_source *source, const struct obs_source_frame *frame, gs_texture_t *tex, + gs_texrender_t *texrender) { - gs_texture_t *tex3[MAX_AV_PLANES] = {tex, NULL, NULL, NULL, - NULL, NULL, NULL, NULL}; + gs_texture_t *tex3[MAX_AV_PLANES] = {tex, NULL, NULL, NULL, NULL, NULL, NULL, NULL}; return update_async_textures(source, frame, tex3, texrender); } -bool update_async_textures(struct obs_source *source, - const struct obs_source_frame *frame, - gs_texture_t *tex[MAX_AV_PLANES], - gs_texrender_t *texrender) +bool update_async_textures(struct obs_source *source, const struct obs_source_frame *frame, + gs_texture_t *tex[MAX_AV_PLANES], gs_texrender_t *texrender) { enum convert_type type; source->async_flip = frame->flip; - source->async_linear_alpha = - (frame->flags & OBS_SOURCE_FRAME_LINEAR_ALPHA) != 0; + source->async_linear_alpha = (frame->flags & OBS_SOURCE_FRAME_LINEAR_ALPHA) != 0; if (source->async_gpu_conversion && texrender) return update_async_texrender(source, frame, tex, texrender); type = get_convert_type(frame->format, frame->full_range, frame->trc); if (type == CONVERT_NONE) { - gs_texture_set_image(tex[0], frame->data[0], frame->linesize[0], - false); + gs_texture_set_image(tex[0], frame->data[0], frame->linesize[0], false); return true; } return false; } -static inline void obs_source_draw_texture(struct obs_source *source, - gs_effect_t *effect) +static inline void obs_source_draw_texture(struct obs_source *source, gs_effect_t *effect) { gs_texture_t *tex = source->async_textures[0]; gs_eparam_t *param; @@ -2536,21 +2349,17 @@ static inline void obs_source_draw_texture(struct obs_source *source, gs_enable_framebuffer_srgb(previous); } -static void recreate_async_texture(obs_source_t *source, - enum gs_color_format format) +static void recreate_async_texture(obs_source_t *source, enum gs_color_format format) { uint32_t cx = gs_texture_get_width(source->async_textures[0]); uint32_t cy = gs_texture_get_height(source->async_textures[0]); gs_texture_destroy(source->async_textures[0]); - source->async_textures[0] = - gs_texture_create(cx, cy, format, 1, NULL, GS_DYNAMIC); + source->async_textures[0] = gs_texture_create(cx, cy, format, 1, NULL, GS_DYNAMIC); } -static inline void check_to_swap_bgrx_bgra(obs_source_t *source, - struct obs_source_frame *frame) +static inline void check_to_swap_bgrx_bgra(obs_source_t *source, struct obs_source_frame *frame) { - enum gs_color_format format = - gs_texture_get_color_format(source->async_textures[0]); + enum gs_color_format format = gs_texture_get_color_format(source->async_textures[0]); if (format == GS_BGRX && frame->format == VIDEO_FORMAT_BGRA) { recreate_async_texture(source, GS_BGRA); } else if (format == GS_BGRA && frame->format == VIDEO_FORMAT_BGRX) { @@ -2567,17 +2376,13 @@ static void obs_source_update_async_video(obs_source_t *source) if (frame) { check_to_swap_bgrx_bgra(source, frame); - if (!source->async_decoupled || - !source->async_unbuffered) { - source->timing_adjust = obs->video.video_time - - frame->timestamp; + if (!source->async_decoupled || !source->async_unbuffered) { + source->timing_adjust = obs->video.video_time - frame->timestamp; source->timing_set = true; } if (source->async_update_texture) { - update_async_textures(source, frame, - source->async_textures, - source->async_texrender); + update_async_textures(source, frame, source->async_textures, source->async_texrender); source->async_update_texture = false; } @@ -2613,14 +2418,11 @@ static inline void obs_source_render_async_video(obs_source_t *source) { if (source->async_textures[0] && source->async_active) { gs_timer_t *timer = NULL; - const uint64_t start = - source_profiler_source_render_begin(&timer); + const uint64_t start = source_profiler_source_render_begin(&timer); - const enum gs_color_space source_space = convert_video_space( - source->async_format, source->async_trc); + const enum gs_color_space source_space = convert_video_space(source->async_format, source->async_trc); - gs_effect_t *const effect = - obs_get_base_effect(OBS_EFFECT_DEFAULT); + gs_effect_t *const effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); const char *tech_name = "Draw"; float multiplier = 1.0; const enum gs_color_space current_space = gs_get_color_space(); @@ -2628,10 +2430,8 @@ static inline void obs_source_render_async_video(obs_source_t *source) bool nonlinear_alpha = false; switch (source_space) { case GS_CS_SRGB: - linear_srgb = linear_srgb || - (current_space != GS_CS_SRGB); - nonlinear_alpha = linear_srgb && - !source->async_linear_alpha; + linear_srgb = linear_srgb || (current_space != GS_CS_SRGB); + nonlinear_alpha = linear_srgb && !source->async_linear_alpha; switch (current_space) { case GS_CS_SRGB: case GS_CS_SRGB_16F: @@ -2640,19 +2440,14 @@ static inline void obs_source_render_async_video(obs_source_t *source) tech_name = "DrawNonlinearAlpha"; break; case GS_CS_709_SCRGB: - tech_name = - nonlinear_alpha - ? "DrawNonlinearAlphaMultiply" - : "DrawMultiply"; - multiplier = - obs_get_video_sdr_white_level() / 80.0f; + tech_name = nonlinear_alpha ? "DrawNonlinearAlphaMultiply" : "DrawMultiply"; + multiplier = obs_get_video_sdr_white_level() / 80.0f; } break; case GS_CS_SRGB_16F: if (current_space == GS_CS_709_SCRGB) { tech_name = "DrawMultiply"; - multiplier = - obs_get_video_sdr_white_level() / 80.0f; + multiplier = obs_get_video_sdr_white_level() / 80.0f; } break; case GS_CS_709_EXTENDED: @@ -2664,8 +2459,7 @@ static inline void obs_source_render_async_video(obs_source_t *source) break; case GS_CS_709_SCRGB: tech_name = "DrawMultiply"; - multiplier = - obs_get_video_sdr_white_level() / 80.0f; + multiplier = obs_get_video_sdr_white_level() / 80.0f; break; case GS_CS_709_EXTENDED: break; @@ -2676,14 +2470,12 @@ static inline void obs_source_render_async_video(obs_source_t *source) case GS_CS_SRGB: case GS_CS_SRGB_16F: tech_name = "DrawMultiplyTonemap"; - multiplier = - 80.0f / obs_get_video_sdr_white_level(); + multiplier = 80.0f / obs_get_video_sdr_white_level(); linear_srgb = true; break; case GS_CS_709_EXTENDED: tech_name = "DrawMultiply"; - multiplier = - 80.0f / obs_get_video_sdr_white_level(); + multiplier = 80.0f / obs_get_video_sdr_white_level(); break; case GS_CS_709_SCRGB: break; @@ -2692,11 +2484,8 @@ static inline void obs_source_render_async_video(obs_source_t *source) const bool previous = gs_set_linear_srgb(linear_srgb); - gs_technique_t *const tech = - gs_effect_get_technique(effect, tech_name); - gs_effect_set_float(gs_effect_get_param_by_name(effect, - "multiplier"), - multiplier); + gs_technique_t *const tech = gs_effect_get_technique(effect, tech_name); + gs_effect_set_float(gs_effect_get_param_by_name(effect, "multiplier"), multiplier); gs_technique_begin(tech); gs_technique_begin_pass(tech, 0); @@ -2747,14 +2536,12 @@ static inline void obs_source_render_filters(obs_source_t *source) static inline uint32_t get_async_width(const obs_source_t *source) { - return ((source->async_rotation % 180) == 0) ? source->async_width - : source->async_height; + return ((source->async_rotation % 180) == 0) ? source->async_width : source->async_height; } static inline uint32_t get_async_height(const obs_source_t *source) { - return ((source->async_rotation % 180) == 0) ? source->async_height - : source->async_width; + return ((source->async_rotation % 180) == 0) ? source->async_height : source->async_width; } static uint32_t get_base_width(const obs_source_t *source) @@ -2800,8 +2587,7 @@ static void source_render(obs_source_t *source, gs_effect_t *effect) void *const data = source->context.data; const enum gs_color_space current_space = gs_get_color_space(); - const enum gs_color_space source_space = - obs_source_get_color_space(source, 1, ¤t_space); + const enum gs_color_space source_space = obs_source_get_color_space(source, 1, ¤t_space); const char *convert_tech = NULL; float multiplier = 1.0; @@ -2855,32 +2641,26 @@ static void source_render(obs_source_t *source, gs_effect_t *effect) if (convert_tech) { if (source->color_space_texrender) { - if (gs_texrender_get_format( - source->color_space_texrender) != format) { - gs_texrender_destroy( - source->color_space_texrender); + if (gs_texrender_get_format(source->color_space_texrender) != format) { + gs_texrender_destroy(source->color_space_texrender); source->color_space_texrender = NULL; } } if (!source->color_space_texrender) { - source->color_space_texrender = - gs_texrender_create(format, GS_ZS_NONE); + source->color_space_texrender = gs_texrender_create(format, GS_ZS_NONE); } gs_texrender_reset(source->color_space_texrender); const int cx = get_base_width(source); const int cy = get_base_height(source); - if (gs_texrender_begin_with_color_space( - source->color_space_texrender, cx, cy, - source_space)) { + if (gs_texrender_begin_with_color_space(source->color_space_texrender, cx, cy, source_space)) { gs_enable_blending(false); struct vec4 clear_color; vec4_zero(&clear_color); gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0); - gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, - 100.0f); + gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); source->info.video_render(data, effect); @@ -2889,22 +2669,14 @@ static void source_render(obs_source_t *source, gs_effect_t *effect) gs_texrender_end(source->color_space_texrender); gs_effect_t *default_effect = obs->video.default_effect; - gs_technique_t *tech = gs_effect_get_technique( - default_effect, convert_tech); + gs_technique_t *tech = gs_effect_get_technique(default_effect, convert_tech); const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(true); - gs_texture_t *const tex = gs_texrender_get_texture( - source->color_space_texrender); - gs_effect_set_texture_srgb( - gs_effect_get_param_by_name(default_effect, - "image"), - tex); - gs_effect_set_float( - gs_effect_get_param_by_name(default_effect, - "multiplier"), - multiplier); + gs_texture_t *const tex = gs_texrender_get_texture(source->color_space_texrender); + gs_effect_set_texture_srgb(gs_effect_get_param_by_name(default_effect, "image"), tex); + gs_effect_set_float(gs_effect_get_param_by_name(default_effect, "multiplier"), multiplier); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); @@ -2949,8 +2721,7 @@ static inline void obs_source_main_render(obs_source_t *source) uint32_t flags = source->info.output_flags; bool custom_draw = (flags & OBS_SOURCE_CUSTOM_DRAW) != 0; bool srgb_aware = (flags & OBS_SOURCE_SRGB) != 0; - bool default_effect = !source->filter_parent && - source->filters.num == 0 && !custom_draw; + bool default_effect = !source->filter_parent && source->filters.num == 0 && !custom_draw; bool previous_srgb = false; if (!srgb_aware) { @@ -2990,15 +2761,13 @@ static const char *get_type_format(enum obs_source_type type) static inline void render_video(obs_source_t *source) { - if (source->info.type != OBS_SOURCE_TYPE_FILTER && - (source->info.output_flags & OBS_SOURCE_VIDEO) == 0) { + if (source->info.type != OBS_SOURCE_TYPE_FILTER && (source->info.output_flags & OBS_SOURCE_VIDEO) == 0) { if (source->filter_parent) obs_source_skip_video_filter(source); return; } - if (source->info.type == OBS_SOURCE_TYPE_INPUT && - (source->info.output_flags & OBS_SOURCE_ASYNC) != 0 && + if (source->info.type == OBS_SOURCE_TYPE_INPUT && (source->info.output_flags & OBS_SOURCE_ASYNC) != 0 && !source->rendering_filter) { if (deinterlacing_enabled(source)) deinterlace_update_async_video(source); @@ -3011,8 +2780,7 @@ static inline void render_video(obs_source_t *source) return; } - GS_DEBUG_MARKER_BEGIN_FORMAT(GS_DEBUG_COLOR_SOURCE, - get_type_format(source->info.type), + GS_DEBUG_MARKER_BEGIN_FORMAT(GS_DEBUG_COLOR_SOURCE, get_type_format(source->info.type), obs_source_get_name(source)); if (source->filters.num && !source->rendering_filter) @@ -3051,8 +2819,7 @@ static uint32_t get_recurse_width(obs_source_t *source) pthread_mutex_lock(&source->filter_mutex); - width = (source->filters.num) ? get_base_width(source->filters.array[0]) - : get_base_width(source); + width = (source->filters.num) ? get_base_width(source->filters.array[0]) : get_base_width(source); pthread_mutex_unlock(&source->filter_mutex); @@ -3065,9 +2832,7 @@ static uint32_t get_recurse_height(obs_source_t *source) pthread_mutex_lock(&source->filter_mutex); - height = (source->filters.num) - ? get_base_height(source->filters.array[0]) - : get_base_height(source); + height = (source->filters.num) ? get_base_height(source->filters.array[0]) : get_base_height(source); pthread_mutex_unlock(&source->filter_mutex); @@ -3079,9 +2844,7 @@ uint32_t obs_source_get_width(obs_source_t *source) if (!data_valid(source, "obs_source_get_width")) return 0; - return (source->info.type != OBS_SOURCE_TYPE_FILTER) - ? get_recurse_width(source) - : get_base_width(source); + return (source->info.type != OBS_SOURCE_TYPE_FILTER) ? get_recurse_width(source) : get_base_width(source); } uint32_t obs_source_get_height(obs_source_t *source) @@ -3089,34 +2852,27 @@ uint32_t obs_source_get_height(obs_source_t *source) if (!data_valid(source, "obs_source_get_height")) return 0; - return (source->info.type != OBS_SOURCE_TYPE_FILTER) - ? get_recurse_height(source) - : get_base_height(source); + return (source->info.type != OBS_SOURCE_TYPE_FILTER) ? get_recurse_height(source) : get_base_height(source); } -enum gs_color_space -obs_source_get_color_space(obs_source_t *source, size_t count, - const enum gs_color_space *preferred_spaces) +enum gs_color_space obs_source_get_color_space(obs_source_t *source, size_t count, + const enum gs_color_space *preferred_spaces) { if (!data_valid(source, "obs_source_get_color_space")) return GS_CS_SRGB; - if (source->info.type != OBS_SOURCE_TYPE_FILTER && - (source->info.output_flags & OBS_SOURCE_VIDEO) == 0) { + if (source->info.type != OBS_SOURCE_TYPE_FILTER && (source->info.output_flags & OBS_SOURCE_VIDEO) == 0) { if (source->filter_parent) - return obs_source_get_color_space( - source->filter_parent, count, preferred_spaces); + return obs_source_get_color_space(source->filter_parent, count, preferred_spaces); } if (!source->context.data || !source->enabled) { if (source->filter_target) - return obs_source_get_color_space( - source->filter_target, count, preferred_spaces); + return obs_source_get_color_space(source->filter_target, count, preferred_spaces); } if (source->info.output_flags & OBS_SOURCE_ASYNC) { - const enum gs_color_space video_space = convert_video_space( - source->async_format, source->async_trc); + const enum gs_color_space video_space = convert_video_space(source->async_format, source->async_trc); enum gs_color_space space = video_space; for (size_t i = 0; i < count; ++i) { @@ -3130,8 +2886,7 @@ obs_source_get_color_space(obs_source_t *source, size_t count, assert(source->context.data); return source->info.video_get_color_space - ? source->info.video_get_color_space( - source->context.data, count, preferred_spaces) + ? source->info.video_get_color_space(source->context.data, count, preferred_spaces) : GS_CS_SRGB; } @@ -3153,16 +2908,12 @@ uint32_t obs_source_get_base_height(obs_source_t *source) obs_source_t *obs_filter_get_parent(const obs_source_t *filter) { - return obs_ptr_valid(filter, "obs_filter_get_parent") - ? filter->filter_parent - : NULL; + return obs_ptr_valid(filter, "obs_filter_get_parent") ? filter->filter_parent : NULL; } obs_source_t *obs_filter_get_target(const obs_source_t *filter) { - return obs_ptr_valid(filter, "obs_filter_get_target") - ? filter->filter_target - : NULL; + return obs_ptr_valid(filter, "obs_filter_get_target") ? filter->filter_target : NULL; } #define OBS_SOURCE_AV (OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO) @@ -3172,8 +2923,7 @@ static bool filter_compatible(obs_source_t *source, obs_source_t *filter) uint32_t s_caps = source->info.output_flags & OBS_SOURCE_AV; uint32_t f_caps = filter->info.output_flags & OBS_SOURCE_AV; - if ((f_caps & OBS_SOURCE_AUDIO) != 0 && - (f_caps & OBS_SOURCE_VIDEO) == 0) + if ((f_caps & OBS_SOURCE_AUDIO) != 0 && (f_caps & OBS_SOURCE_VIDEO) == 0) f_caps &= ~OBS_SOURCE_ASYNC; return (s_caps & f_caps) == f_caps; @@ -3208,8 +2958,7 @@ void obs_source_filter_add(obs_source_t *source, obs_source_t *filter) return; filter->filter_parent = source; - filter->filter_target = !source->filters.num ? source - : source->filters.array[0]; + filter->filter_target = !source->filters.num ? source : source->filters.array[0]; da_insert(source->filters, 0, &filter); @@ -3222,16 +2971,14 @@ void obs_source_filter_add(obs_source_t *source, obs_source_t *filter) signal_handler_signal(obs->signals, "source_filter_add", &cd); signal_handler_signal(source->context.signals, "filter_add", &cd); - blog(LOG_DEBUG, "- filter '%s' (%s) added to source '%s'", - filter->context.name, filter->info.id, source->context.name); + blog(LOG_DEBUG, "- filter '%s' (%s) added to source '%s'", filter->context.name, filter->info.id, + source->context.name); if (filter->info.filter_add) - filter->info.filter_add(filter->context.data, - filter->filter_parent); + filter->info.filter_add(filter->context.data, filter->filter_parent); } -static bool obs_source_filter_remove_refless(obs_source_t *source, - obs_source_t *filter) +static bool obs_source_filter_remove_refless(obs_source_t *source, obs_source_t *filter) { struct calldata cd; uint8_t stack[128]; @@ -3261,12 +3008,11 @@ static bool obs_source_filter_remove_refless(obs_source_t *source, signal_handler_signal(obs->signals, "source_filter_remove", &cd); signal_handler_signal(source->context.signals, "filter_remove", &cd); - blog(LOG_DEBUG, "- filter '%s' (%s) removed from source '%s'", - filter->context.name, filter->info.id, source->context.name); + blog(LOG_DEBUG, "- filter '%s' (%s) removed from source '%s'", filter->context.name, filter->info.id, + source->context.name); if (filter->info.filter_remove) - filter->info.filter_remove(filter->context.data, - filter->filter_parent); + filter->info.filter_remove(filter->context.data, filter->filter_parent); filter->filter_parent = NULL; filter->filter_target = NULL; @@ -3284,8 +3030,7 @@ void obs_source_filter_remove(obs_source_t *source, obs_source_t *filter) obs_source_release(filter); } -static size_t find_next_filter(obs_source_t *source, obs_source_t *filter, - size_t cur_idx) +static size_t find_next_filter(obs_source_t *source, obs_source_t *filter, size_t cur_idx) { bool curAsync = (filter->info.output_flags & OBS_SOURCE_ASYNC) != 0; bool nextAsync; @@ -3303,8 +3048,7 @@ static size_t find_next_filter(obs_source_t *source, obs_source_t *filter, return find_next_filter(source, filter, cur_idx + 1); } -static size_t find_prev_filter(obs_source_t *source, obs_source_t *filter, - size_t cur_idx) +static size_t find_prev_filter(obs_source_t *source, obs_source_t *filter, size_t cur_idx) { bool curAsync = (filter->info.output_flags & OBS_SOURCE_ASYNC) != 0; bool prevAsync; @@ -3326,18 +3070,14 @@ static void reorder_filter_targets(obs_source_t *source) { /* reorder filter targets, not the nicest way of dealing with things */ for (size_t i = 0; i < source->filters.num; i++) { - obs_source_t *next_filter = - (i == source->filters.num - 1) - ? source - : source->filters.array[i + 1]; + obs_source_t *next_filter = (i == source->filters.num - 1) ? source : source->filters.array[i + 1]; source->filters.array[i]->filter_target = next_filter; } } /* moves filters above/below matching filter types */ -static bool move_filter_dir(obs_source_t *source, obs_source_t *filter, - enum obs_order_movement movement) +static bool move_filter_dir(obs_source_t *source, obs_source_t *filter, enum obs_order_movement movement) { size_t idx; @@ -3373,8 +3113,7 @@ static bool move_filter_dir(obs_source_t *source, obs_source_t *filter, return true; } -void obs_source_filter_set_order(obs_source_t *source, obs_source_t *filter, - enum obs_order_movement movement) +void obs_source_filter_set_order(obs_source_t *source, obs_source_t *filter, enum obs_order_movement movement) { bool success; @@ -3407,8 +3146,7 @@ int obs_source_filter_get_index(obs_source_t *source, obs_source_t *filter) return idx != DARRAY_INVALID ? (int)idx : -1; } -static bool set_filter_index(obs_source_t *source, obs_source_t *filter, - size_t index) +static bool set_filter_index(obs_source_t *source, obs_source_t *filter, size_t index) { size_t idx = da_find(source->filters, &filter, 0); if (idx == DARRAY_INVALID) @@ -3420,8 +3158,7 @@ static bool set_filter_index(obs_source_t *source, obs_source_t *filter, return true; } -void obs_source_filter_set_index(obs_source_t *source, obs_source_t *filter, - size_t index) +void obs_source_filter_set_index(obs_source_t *source, obs_source_t *filter, size_t index) { bool success; @@ -3447,8 +3184,7 @@ obs_data_t *obs_source_get_settings(const obs_source_t *source) return source->context.settings; } -struct obs_source_frame *filter_async_video(obs_source_t *source, - struct obs_source_frame *in) +struct obs_source_frame *filter_async_video(obs_source_t *source, struct obs_source_frame *in) { size_t i; @@ -3461,8 +3197,7 @@ struct obs_source_frame *filter_async_video(obs_source_t *source, continue; if (filter->context.data && filter->info.filter_video) { - in = filter->info.filter_video(filter->context.data, - in); + in = filter->info.filter_video(filter->context.data, in); if (!in) break; } @@ -3473,34 +3208,28 @@ struct obs_source_frame *filter_async_video(obs_source_t *source, return in; } -static inline void copy_frame_data_line(struct obs_source_frame *dst, - const struct obs_source_frame *src, +static inline void copy_frame_data_line(struct obs_source_frame *dst, const struct obs_source_frame *src, uint32_t plane, uint32_t y) { uint32_t pos_src = y * src->linesize[plane]; uint32_t pos_dst = y * dst->linesize[plane]; - uint32_t bytes = dst->linesize[plane] < src->linesize[plane] - ? dst->linesize[plane] - : src->linesize[plane]; + uint32_t bytes = dst->linesize[plane] < src->linesize[plane] ? dst->linesize[plane] : src->linesize[plane]; memcpy(dst->data[plane] + pos_dst, src->data[plane] + pos_src, bytes); } -static inline void copy_frame_data_plane(struct obs_source_frame *dst, - const struct obs_source_frame *src, +static inline void copy_frame_data_plane(struct obs_source_frame *dst, const struct obs_source_frame *src, uint32_t plane, uint32_t lines) { if (dst->linesize[plane] != src->linesize[plane]) { for (uint32_t y = 0; y < lines; y++) copy_frame_data_line(dst, src, plane, y); } else { - memcpy(dst->data[plane], src->data[plane], - (size_t)dst->linesize[plane] * (size_t)lines); + memcpy(dst->data[plane], src->data[plane], (size_t)dst->linesize[plane] * (size_t)lines); } } -static void copy_frame_data(struct obs_source_frame *dst, - const struct obs_source_frame *src) +static void copy_frame_data(struct obs_source_frame *dst, const struct obs_source_frame *src) { dst->flip = src->flip; dst->flags = src->flags; @@ -3585,23 +3314,18 @@ static void copy_frame_data(struct obs_source_frame *dst, } } -void obs_source_frame_copy(struct obs_source_frame *dst, - const struct obs_source_frame *src) +void obs_source_frame_copy(struct obs_source_frame *dst, const struct obs_source_frame *src) { copy_frame_data(dst, src); } -static inline bool async_texture_changed(struct obs_source *source, - const struct obs_source_frame *frame) +static inline bool async_texture_changed(struct obs_source *source, const struct obs_source_frame *frame) { enum convert_type prev, cur; - prev = get_convert_type(source->async_cache_format, - source->async_cache_full_range, - source->async_cache_trc); + prev = get_convert_type(source->async_cache_format, source->async_cache_full_range, source->async_cache_trc); cur = get_convert_type(frame->format, frame->full_range, frame->trc); - return source->async_cache_width != frame->width || - source->async_cache_height != frame->height || prev != cur; + return source->async_cache_width != frame->width || source->async_cache_height != frame->height || prev != cur; } static inline void free_async_cache(struct obs_source *source) @@ -3634,8 +3358,7 @@ static void clean_cache(obs_source_t *source) #define MAX_ASYNC_FRAMES 30 //if return value is not null then do (os_atomic_dec_long(&output->refs) == 0) && obs_source_frame_destroy(output) -static inline struct obs_source_frame * -cache_video(struct obs_source *source, const struct obs_source_frame *frame) +static inline struct obs_source_frame *cache_video(struct obs_source *source, const struct obs_source_frame *frame) { struct obs_source_frame *new_frame = NULL; @@ -3675,8 +3398,7 @@ cache_video(struct obs_source *source, const struct obs_source_frame *frame) if (!new_frame) { struct async_frame new_af; - new_frame = obs_source_frame_create(format, frame->width, - frame->height); + new_frame = obs_source_frame_create(format, frame->width, frame->height); new_af.frame = new_frame; new_af.used = true; new_af.unused_count = 0; @@ -3694,9 +3416,7 @@ cache_video(struct obs_source *source, const struct obs_source_frame *frame) return new_frame; } -static void -obs_source_output_video_internal(obs_source_t *source, - const struct obs_source_frame *frame) +static void obs_source_output_video_internal(obs_source_t *source, const struct obs_source_frame *frame) { if (!obs_source_valid(source, "obs_source_output_video")) return; @@ -3728,8 +3448,7 @@ obs_source_output_video_internal(obs_source_t *source, pthread_mutex_unlock(&source->async_mutex); } -void obs_source_output_video(obs_source_t *source, - const struct obs_source_frame *frame) +void obs_source_output_video(obs_source_t *source, const struct obs_source_frame *frame) { if (destroying(source)) return; @@ -3739,14 +3458,12 @@ void obs_source_output_video(obs_source_t *source, } struct obs_source_frame new_frame = *frame; - new_frame.full_range = - format_is_yuv(frame->format) ? new_frame.full_range : true; + new_frame.full_range = format_is_yuv(frame->format) ? new_frame.full_range : true; obs_source_output_video_internal(source, &new_frame); } -void obs_source_output_video2(obs_source_t *source, - const struct obs_source_frame2 *frame) +void obs_source_output_video2(obs_source_t *source, const struct obs_source_frame2 *frame) { if (destroying(source)) return; @@ -3756,8 +3473,7 @@ void obs_source_output_video2(obs_source_t *source, } struct obs_source_frame new_frame = {0}; - enum video_range_type range = - resolve_video_range(frame->format, frame->range); + enum video_range_type range = resolve_video_range(frame->format, frame->range); for (size_t i = 0; i < MAX_AV_PLANES; i++) { new_frame.data[i] = frame->data[i]; @@ -3774,12 +3490,9 @@ void obs_source_output_video2(obs_source_t *source, new_frame.flags = frame->flags; new_frame.trc = frame->trc; - memcpy(&new_frame.color_matrix, &frame->color_matrix, - sizeof(frame->color_matrix)); - memcpy(&new_frame.color_range_min, &frame->color_range_min, - sizeof(frame->color_range_min)); - memcpy(&new_frame.color_range_max, &frame->color_range_max, - sizeof(frame->color_range_max)); + memcpy(&new_frame.color_matrix, &frame->color_matrix, sizeof(frame->color_matrix)); + memcpy(&new_frame.color_range_min, &frame->color_range_min, sizeof(frame->color_range_min)); + memcpy(&new_frame.color_range_max, &frame->color_range_max, sizeof(frame->color_range_max)); obs_source_output_video_internal(source, &new_frame); } @@ -3790,8 +3503,7 @@ void obs_source_set_async_rotation(obs_source_t *source, long rotation) source->async_rotation = rotation; } -void obs_source_output_cea708(obs_source_t *source, - const struct obs_source_cea_708 *captions) +void obs_source_output_cea708(obs_source_t *source, const struct obs_source_cea_708 *captions) { if (destroying(source)) return; @@ -3802,16 +3514,14 @@ void obs_source_output_cea708(obs_source_t *source, pthread_mutex_lock(&source->caption_cb_mutex); for (size_t i = source->caption_cb_list.num; i > 0; i--) { - struct caption_cb_info info = - source->caption_cb_list.array[i - 1]; + struct caption_cb_info info = source->caption_cb_list.array[i - 1]; info.callback(info.param, source, captions); } pthread_mutex_unlock(&source->caption_cb_mutex); } -void obs_source_add_caption_callback(obs_source_t *source, - obs_source_caption_t callback, void *param) +void obs_source_add_caption_callback(obs_source_t *source, obs_source_caption_t callback, void *param) { struct caption_cb_info info = {callback, param}; @@ -3823,9 +3533,7 @@ void obs_source_add_caption_callback(obs_source_t *source, pthread_mutex_unlock(&source->caption_cb_mutex); } -void obs_source_remove_caption_callback(obs_source_t *source, - obs_source_caption_t callback, - void *param) +void obs_source_remove_caption_callback(obs_source_t *source, obs_source_caption_t callback, void *param) { struct caption_cb_info info = {callback, param}; @@ -3837,20 +3545,16 @@ void obs_source_remove_caption_callback(obs_source_t *source, pthread_mutex_unlock(&source->caption_cb_mutex); } -static inline bool preload_frame_changed(obs_source_t *source, - const struct obs_source_frame *in) +static inline bool preload_frame_changed(obs_source_t *source, const struct obs_source_frame *in) { if (!source->async_preload_frame) return true; - return in->width != source->async_preload_frame->width || - in->height != source->async_preload_frame->height || + return in->width != source->async_preload_frame->width || in->height != source->async_preload_frame->height || in->format != source->async_preload_frame->format; } -static void -obs_source_preload_video_internal(obs_source_t *source, - const struct obs_source_frame *frame) +static void obs_source_preload_video_internal(obs_source_t *source, const struct obs_source_frame *frame) { if (!obs_source_valid(source, "obs_source_preload_video")) return; @@ -3861,8 +3565,7 @@ obs_source_preload_video_internal(obs_source_t *source, if (preload_frame_changed(source, frame)) { obs_source_frame_destroy(source->async_preload_frame); - source->async_preload_frame = obs_source_frame_create( - frame->format, frame->width, frame->height); + source->async_preload_frame = obs_source_frame_create(frame->format, frame->width, frame->height); } copy_frame_data(source->async_preload_frame, frame); @@ -3870,8 +3573,7 @@ obs_source_preload_video_internal(obs_source_t *source, source->last_frame_ts = frame->timestamp; } -void obs_source_preload_video(obs_source_t *source, - const struct obs_source_frame *frame) +void obs_source_preload_video(obs_source_t *source, const struct obs_source_frame *frame) { if (destroying(source)) return; @@ -3881,14 +3583,12 @@ void obs_source_preload_video(obs_source_t *source, } struct obs_source_frame new_frame = *frame; - new_frame.full_range = - format_is_yuv(frame->format) ? new_frame.full_range : true; + new_frame.full_range = format_is_yuv(frame->format) ? new_frame.full_range : true; obs_source_preload_video_internal(source, &new_frame); } -void obs_source_preload_video2(obs_source_t *source, - const struct obs_source_frame2 *frame) +void obs_source_preload_video2(obs_source_t *source, const struct obs_source_frame2 *frame) { if (destroying(source)) return; @@ -3898,8 +3598,7 @@ void obs_source_preload_video2(obs_source_t *source, } struct obs_source_frame new_frame = {0}; - enum video_range_type range = - resolve_video_range(frame->format, frame->range); + enum video_range_type range = resolve_video_range(frame->format, frame->range); for (size_t i = 0; i < MAX_AV_PLANES; i++) { new_frame.data[i] = frame->data[i]; @@ -3916,12 +3615,9 @@ void obs_source_preload_video2(obs_source_t *source, new_frame.flags = frame->flags; new_frame.trc = frame->trc; - memcpy(&new_frame.color_matrix, &frame->color_matrix, - sizeof(frame->color_matrix)); - memcpy(&new_frame.color_range_min, &frame->color_range_min, - sizeof(frame->color_range_min)); - memcpy(&new_frame.color_range_max, &frame->color_range_max, - sizeof(frame->color_range_max)); + memcpy(&new_frame.color_matrix, &frame->color_matrix, sizeof(frame->color_matrix)); + memcpy(&new_frame.color_range_min, &frame->color_range_min, sizeof(frame->color_range_min)); + memcpy(&new_frame.color_range_max, &frame->color_range_max, sizeof(frame->color_range_max)); obs_source_preload_video_internal(source, &new_frame); } @@ -3940,24 +3636,19 @@ void obs_source_show_preloaded_video(obs_source_t *source) obs_enter_graphics(); set_async_texture_size(source, source->async_preload_frame); - update_async_textures(source, source->async_preload_frame, - source->async_textures, source->async_texrender); + update_async_textures(source, source->async_preload_frame, source->async_textures, source->async_texrender); source->async_active = true; obs_leave_graphics(); pthread_mutex_lock(&source->audio_buf_mutex); - sys_ts = (source->monitoring_type != OBS_MONITORING_TYPE_MONITOR_ONLY) - ? os_gettime_ns() - : 0; + sys_ts = (source->monitoring_type != OBS_MONITORING_TYPE_MONITOR_ONLY) ? os_gettime_ns() : 0; reset_audio_timing(source, source->last_frame_ts, sys_ts); reset_audio_data(source, sys_ts); pthread_mutex_unlock(&source->audio_buf_mutex); } -static void -obs_source_set_video_frame_internal(obs_source_t *source, - const struct obs_source_frame *frame) +static void obs_source_set_video_frame_internal(obs_source_t *source, const struct obs_source_frame *frame) { if (!obs_source_valid(source, "obs_source_set_video_frame")) return; @@ -3968,22 +3659,19 @@ obs_source_set_video_frame_internal(obs_source_t *source, if (preload_frame_changed(source, frame)) { obs_source_frame_destroy(source->async_preload_frame); - source->async_preload_frame = obs_source_frame_create( - frame->format, frame->width, frame->height); + source->async_preload_frame = obs_source_frame_create(frame->format, frame->width, frame->height); } copy_frame_data(source->async_preload_frame, frame); set_async_texture_size(source, source->async_preload_frame); - update_async_textures(source, source->async_preload_frame, - source->async_textures, source->async_texrender); + update_async_textures(source, source->async_preload_frame, source->async_textures, source->async_texrender); source->last_frame_ts = frame->timestamp; obs_leave_graphics(); } -void obs_source_set_video_frame(obs_source_t *source, - const struct obs_source_frame *frame) +void obs_source_set_video_frame(obs_source_t *source, const struct obs_source_frame *frame) { if (destroying(source)) return; @@ -3993,14 +3681,12 @@ void obs_source_set_video_frame(obs_source_t *source, } struct obs_source_frame new_frame = *frame; - new_frame.full_range = - format_is_yuv(frame->format) ? new_frame.full_range : true; + new_frame.full_range = format_is_yuv(frame->format) ? new_frame.full_range : true; obs_source_set_video_frame_internal(source, &new_frame); } -void obs_source_set_video_frame2(obs_source_t *source, - const struct obs_source_frame2 *frame) +void obs_source_set_video_frame2(obs_source_t *source, const struct obs_source_frame2 *frame) { if (destroying(source)) return; @@ -4010,8 +3696,7 @@ void obs_source_set_video_frame2(obs_source_t *source, } struct obs_source_frame new_frame = {0}; - enum video_range_type range = - resolve_video_range(frame->format, frame->range); + enum video_range_type range = resolve_video_range(frame->format, frame->range); for (size_t i = 0; i < MAX_AV_PLANES; i++) { new_frame.data[i] = frame->data[i]; @@ -4028,18 +3713,14 @@ void obs_source_set_video_frame2(obs_source_t *source, new_frame.flags = frame->flags; new_frame.trc = frame->trc; - memcpy(&new_frame.color_matrix, &frame->color_matrix, - sizeof(frame->color_matrix)); - memcpy(&new_frame.color_range_min, &frame->color_range_min, - sizeof(frame->color_range_min)); - memcpy(&new_frame.color_range_max, &frame->color_range_max, - sizeof(frame->color_range_max)); + memcpy(&new_frame.color_matrix, &frame->color_matrix, sizeof(frame->color_matrix)); + memcpy(&new_frame.color_range_min, &frame->color_range_min, sizeof(frame->color_range_min)); + memcpy(&new_frame.color_range_max, &frame->color_range_max, sizeof(frame->color_range_max)); obs_source_set_video_frame_internal(source, &new_frame); } -static inline struct obs_audio_data * -filter_async_audio(obs_source_t *source, struct obs_audio_data *in) +static inline struct obs_audio_data *filter_async_audio(obs_source_t *source, struct obs_audio_data *in) { size_t i; for (i = source->filters.num; i > 0; i--) { @@ -4049,8 +3730,7 @@ filter_async_audio(obs_source_t *source, struct obs_audio_data *in) continue; if (filter->context.data && filter->info.filter_audio) { - in = filter->info.filter_audio(filter->context.data, - in); + in = filter->info.filter_audio(filter->context.data, in); if (!in) return NULL; } @@ -4059,8 +3739,7 @@ filter_async_audio(obs_source_t *source, struct obs_audio_data *in) return in; } -static inline void reset_resampler(obs_source_t *source, - const struct obs_source_audio *audio) +static inline void reset_resampler(obs_source_t *source, const struct obs_source_audio *audio) { const struct audio_output_info *obs_info; struct resample_info output_info; @@ -4080,22 +3759,19 @@ static inline void reset_resampler(obs_source_t *source, source->resample_offset = 0; if (source->sample_info.samples_per_sec == obs_info->samples_per_sec && - source->sample_info.format == obs_info->format && - source->sample_info.speakers == obs_info->speakers) { + source->sample_info.format == obs_info->format && source->sample_info.speakers == obs_info->speakers) { source->audio_failed = false; return; } - source->resampler = - audio_resampler_create(&output_info, &source->sample_info); + source->resampler = audio_resampler_create(&output_info, &source->sample_info); source->audio_failed = source->resampler == NULL; if (source->resampler == NULL) blog(LOG_ERROR, "creation of resampler failed"); } -static void copy_audio_data(obs_source_t *source, const uint8_t *const data[], - uint32_t frames, uint64_t ts) +static void copy_audio_data(obs_source_t *source, const uint8_t *const data[], uint32_t frames, uint64_t ts) { size_t planes = audio_output_get_planes(obs->audio.audio); size_t blocksize = audio_output_get_block_size(obs->audio.audio); @@ -4140,18 +3816,16 @@ static void downmix_to_mono_planar(struct obs_source *source, uint32_t frames) } } -static void process_audio_balancing(struct obs_source *source, uint32_t frames, - float balance, enum obs_balance_type type) +static void process_audio_balancing(struct obs_source *source, uint32_t frames, float balance, + enum obs_balance_type type) { float **data = (float **)source->audio_data.data; switch (type) { case OBS_BALANCE_TYPE_SINE_LAW: for (uint32_t frame = 0; frame < frames; frame++) { - data[0][frame] = data[0][frame] * - sinf((1.0f - balance) * (M_PI / 2.0f)); - data[1][frame] = - data[1][frame] * sinf(balance * (M_PI / 2.0f)); + data[0][frame] = data[0][frame] * sinf((1.0f - balance) * (M_PI / 2.0f)); + data[1][frame] = data[1][frame] * sinf(balance * (M_PI / 2.0f)); } break; case OBS_BALANCE_TYPE_SQUARE_LAW: @@ -4172,15 +3846,13 @@ static void process_audio_balancing(struct obs_source *source, uint32_t frames, } /* resamples/remixes new audio to the designated main audio output format */ -static void process_audio(obs_source_t *source, - const struct obs_source_audio *audio) +static void process_audio(obs_source_t *source, const struct obs_source_audio *audio) { uint32_t frames = audio->frames; bool mono_output; if (source->sample_info.samples_per_sec != audio->samples_per_sec || - source->sample_info.format != audio->format || - source->sample_info.speakers != audio->speakers) + source->sample_info.format != audio->format || source->sample_info.speakers != audio->speakers) reset_resampler(source, audio); if (source->audio_failed) @@ -4191,31 +3863,26 @@ static void process_audio(obs_source_t *source, memset(output, 0, sizeof(output)); - audio_resampler_resample(source->resampler, output, &frames, - &source->resample_offset, audio->data, + audio_resampler_resample(source->resampler, output, &frames, &source->resample_offset, audio->data, audio->frames); - copy_audio_data(source, (const uint8_t *const *)output, frames, - audio->timestamp); + copy_audio_data(source, (const uint8_t *const *)output, frames, audio->timestamp); } else { - copy_audio_data(source, audio->data, audio->frames, - audio->timestamp); + copy_audio_data(source, audio->data, audio->frames, audio->timestamp); } mono_output = audio_output_get_channels(obs->audio.audio) == 1; if (!mono_output && source->sample_info.speakers == SPEAKERS_STEREO && (source->balance > 0.51f || source->balance < 0.49f)) { - process_audio_balancing(source, frames, source->balance, - OBS_BALANCE_TYPE_SINE_LAW); + process_audio_balancing(source, frames, source->balance, OBS_BALANCE_TYPE_SINE_LAW); } if (!mono_output && (source->flags & OBS_SOURCE_FLAG_FORCE_MONO) != 0) downmix_to_mono_planar(source, frames); } -void obs_source_output_audio(obs_source_t *source, - const struct obs_source_audio *audio_in) +void obs_source_output_audio(obs_source_t *source, const struct obs_source_audio *audio_in) { struct obs_audio_data *output; @@ -4297,8 +3964,7 @@ static bool ready_async_frame(obs_source_t *source, uint64_t sys_time) "source->last_frame_ts: %llu, frame_time: %llu, " "sys_offset: %llu, frame_offset: %llu, " "number of frames: %lu", - source->last_frame_ts, frame_time, sys_offset, - frame_time - source->last_frame_ts, + source->last_frame_ts, frame_time, sys_offset, frame_time - source->last_frame_ts, (unsigned long)source->async_frames.num); #endif @@ -4320,8 +3986,7 @@ static bool ready_async_frame(obs_source_t *source, uint64_t sys_time) * helps smooth out async rendering to frame boundaries. In * other words, tries to keep the framerate as smooth as * possible */ - if (frame && - (source->last_frame_ts - next_frame->timestamp) < 2000000) + if (frame && (source->last_frame_ts - next_frame->timestamp) < 2000000) break; if (frame) @@ -4348,8 +4013,7 @@ static bool ready_async_frame(obs_source_t *source, uint64_t sys_time) #if DEBUG_ASYNC_FRAMES blog(LOG_DEBUG, "timing jump"); #endif - source->last_frame_ts = - next_frame->timestamp - frame_offset; + source->last_frame_ts = next_frame->timestamp - frame_offset; } frame_time = next_frame->timestamp; @@ -4364,8 +4028,7 @@ static bool ready_async_frame(obs_source_t *source, uint64_t sys_time) return frame != NULL; } -static inline struct obs_source_frame *get_closest_frame(obs_source_t *source, - uint64_t sys_time) +static inline struct obs_source_frame *get_closest_frame(obs_source_t *source, uint64_t sys_time) { if (!source->async_frames.num) return NULL; @@ -4410,8 +4073,7 @@ struct obs_source_frame *obs_source_get_frame(obs_source_t *source) return frame; } -void obs_source_release_frame(obs_source_t *source, - struct obs_source_frame *frame) +void obs_source_release_frame(obs_source_t *source, struct obs_source_frame *frame) { if (!frame) return; @@ -4432,16 +4094,12 @@ void obs_source_release_frame(obs_source_t *source, const char *obs_source_get_name(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_name") - ? source->context.name - : NULL; + return obs_source_valid(source, "obs_source_get_name") ? source->context.name : NULL; } const char *obs_source_get_uuid(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_uuid") - ? source->context.uuid - : NULL; + return obs_source_valid(source, "obs_source_get_uuid") ? source->context.uuid : NULL; } void obs_source_set_name(obs_source_t *source, const char *name) @@ -4449,14 +4107,12 @@ void obs_source_set_name(obs_source_t *source, const char *name) if (!obs_source_valid(source, "obs_source_set_name")) return; - if (!name || !*name || !source->context.name || - strcmp(name, source->context.name) != 0) { + if (!name || !*name || !source->context.name || strcmp(name, source->context.name) != 0) { struct calldata data; char *prev_name = bstrdup(source->context.name); if (!source->context.private) { - obs_context_data_setname_ht(&source->context, name, - &obs->data.public_sources); + obs_context_data_setname_ht(&source->context, name, &obs->data.public_sources); } else { obs_context_data_setname(&source->context, name); } @@ -4466,8 +4122,7 @@ void obs_source_set_name(obs_source_t *source, const char *name) calldata_set_string(&data, "new_name", source->context.name); calldata_set_string(&data, "prev_name", prev_name); if (!source->context.private) - signal_handler_signal(obs->signals, "source_rename", - &data); + signal_handler_signal(obs->signals, "source_rename", &data); signal_handler_signal(source->context.signals, "rename", &data); calldata_free(&data); bfree(prev_name); @@ -4476,27 +4131,20 @@ void obs_source_set_name(obs_source_t *source, const char *name) enum obs_source_type obs_source_get_type(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_type") - ? source->info.type - : OBS_SOURCE_TYPE_INPUT; + return obs_source_valid(source, "obs_source_get_type") ? source->info.type : OBS_SOURCE_TYPE_INPUT; } const char *obs_source_get_id(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_id") ? source->info.id - : NULL; + return obs_source_valid(source, "obs_source_get_id") ? source->info.id : NULL; } const char *obs_source_get_unversioned_id(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_unversioned_id") - ? source->info.unversioned_id - : NULL; + return obs_source_valid(source, "obs_source_get_unversioned_id") ? source->info.unversioned_id : NULL; } -static inline void render_filter_bypass(obs_source_t *target, - gs_effect_t *effect, - const char *tech_name) +static inline void render_filter_bypass(obs_source_t *target, gs_effect_t *effect, const char *tech_name) { gs_technique_t *tech = gs_effect_get_technique(effect, tech_name); size_t passes, i; @@ -4510,8 +4158,7 @@ static inline void render_filter_bypass(obs_source_t *target, gs_technique_end(tech); } -static inline void render_filter_tex(gs_texture_t *tex, gs_effect_t *effect, - uint32_t width, uint32_t height, +static inline void render_filter_tex(gs_texture_t *tex, gs_effect_t *effect, uint32_t width, uint32_t height, const char *tech_name) { gs_technique_t *tech = gs_effect_get_technique(effect, tech_name); @@ -4539,38 +4186,29 @@ static inline void render_filter_tex(gs_texture_t *tex, gs_effect_t *effect, gs_enable_framebuffer_srgb(previous); } -static inline bool can_bypass(obs_source_t *target, obs_source_t *parent, - uint32_t filter_flags, uint32_t parent_flags, - enum obs_allow_direct_render allow_direct, - enum gs_color_space space) +static inline bool can_bypass(obs_source_t *target, obs_source_t *parent, uint32_t filter_flags, uint32_t parent_flags, + enum obs_allow_direct_render allow_direct, enum gs_color_space space) { - return (target == parent) && - (allow_direct == OBS_ALLOW_DIRECT_RENDERING) && - ((parent_flags & OBS_SOURCE_CUSTOM_DRAW) == 0) && - ((parent_flags & OBS_SOURCE_ASYNC) == 0) && - ((filter_flags & OBS_SOURCE_SRGB) == - (parent_flags & OBS_SOURCE_SRGB) && - space == gs_get_color_space()); + return (target == parent) && (allow_direct == OBS_ALLOW_DIRECT_RENDERING) && + ((parent_flags & OBS_SOURCE_CUSTOM_DRAW) == 0) && ((parent_flags & OBS_SOURCE_ASYNC) == 0) && + ((filter_flags & OBS_SOURCE_SRGB) == (parent_flags & OBS_SOURCE_SRGB) && space == gs_get_color_space()); } -bool obs_source_process_filter_begin(obs_source_t *filter, - enum gs_color_format format, +bool obs_source_process_filter_begin(obs_source_t *filter, enum gs_color_format format, enum obs_allow_direct_render allow_direct) { - return obs_source_process_filter_begin_with_color_space( - filter, format, GS_CS_SRGB, allow_direct); + return obs_source_process_filter_begin_with_color_space(filter, format, GS_CS_SRGB, allow_direct); } -bool obs_source_process_filter_begin_with_color_space( - obs_source_t *filter, enum gs_color_format format, - enum gs_color_space space, enum obs_allow_direct_render allow_direct) +bool obs_source_process_filter_begin_with_color_space(obs_source_t *filter, enum gs_color_format format, + enum gs_color_space space, + enum obs_allow_direct_render allow_direct) { obs_source_t *target, *parent; uint32_t filter_flags, parent_flags; int cx, cy; - if (!obs_ptr_valid(filter, - "obs_source_process_filter_begin_with_color_space")) + if (!obs_ptr_valid(filter, "obs_source_process_filter_begin_with_color_space")) return false; filter->filter_bypass_active = false; @@ -4579,13 +4217,11 @@ bool obs_source_process_filter_begin_with_color_space( parent = obs_filter_get_parent(filter); if (!target) { - blog(LOG_INFO, "filter '%s' being processed with no target!", - filter->context.name); + blog(LOG_INFO, "filter '%s' being processed with no target!", filter->context.name); return false; } if (!parent) { - blog(LOG_INFO, "filter '%s' being processed with no parent!", - filter->context.name); + blog(LOG_INFO, "filter '%s' being processed with no parent!", filter->context.name); return false; } @@ -4600,8 +4236,7 @@ bool obs_source_process_filter_begin_with_color_space( * filter in the chain for the parent, then render the parent directly * using the filter effect instead of rendering to texture to reduce * the total number of passes */ - if (can_bypass(target, parent, filter_flags, parent_flags, allow_direct, - space)) { + if (can_bypass(target, parent, filter_flags, parent_flags, allow_direct, space)) { filter->filter_bypass_active = true; return true; } @@ -4611,23 +4246,18 @@ bool obs_source_process_filter_begin_with_color_space( return false; } - if (filter->filter_texrender && - (gs_texrender_get_format(filter->filter_texrender) != format)) { + if (filter->filter_texrender && (gs_texrender_get_format(filter->filter_texrender) != format)) { gs_texrender_destroy(filter->filter_texrender); filter->filter_texrender = NULL; } if (!filter->filter_texrender) { - filter->filter_texrender = - gs_texrender_create(format, GS_ZS_NONE); + filter->filter_texrender = gs_texrender_create(format, GS_ZS_NONE); } - if (gs_texrender_begin_with_color_space(filter->filter_texrender, cx, - cy, space)) { + if (gs_texrender_begin_with_color_space(filter->filter_texrender, cx, cy, space)) { gs_blend_state_push(); - gs_blend_function_separate(GS_BLEND_SRCALPHA, - GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, - GS_BLEND_INVSRCALPHA); + gs_blend_function_separate(GS_BLEND_SRCALPHA, GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); bool custom_draw = (parent_flags & OBS_SOURCE_CUSTOM_DRAW) != 0; bool async = (parent_flags & OBS_SOURCE_ASYNC) != 0; @@ -4649,9 +4279,8 @@ bool obs_source_process_filter_begin_with_color_space( return true; } -void obs_source_process_filter_tech_end(obs_source_t *filter, - gs_effect_t *effect, uint32_t width, - uint32_t height, const char *tech_name) +void obs_source_process_filter_tech_end(obs_source_t *filter, gs_effect_t *effect, uint32_t width, uint32_t height, + const char *tech_name) { obs_source_t *target, *parent; gs_texture_t *texture; @@ -4671,8 +4300,7 @@ void obs_source_process_filter_tech_end(obs_source_t *filter, filter_flags = filter->info.output_flags; - const bool previous = - gs_set_linear_srgb((filter_flags & OBS_SOURCE_SRGB) != 0); + const bool previous = gs_set_linear_srgb((filter_flags & OBS_SOURCE_SRGB) != 0); const char *tech = tech_name ? tech_name : "Draw"; @@ -4688,14 +4316,12 @@ void obs_source_process_filter_tech_end(obs_source_t *filter, gs_set_linear_srgb(previous); } -void obs_source_process_filter_end(obs_source_t *filter, gs_effect_t *effect, - uint32_t width, uint32_t height) +void obs_source_process_filter_end(obs_source_t *filter, gs_effect_t *effect, uint32_t width, uint32_t height) { if (!obs_ptr_valid(filter, "obs_source_process_filter_end")) return; - obs_source_process_filter_tech_end(filter, effect, width, height, - "Draw"); + obs_source_process_filter_tech_end(filter, effect, width, height, "Draw"); } void obs_source_skip_video_filter(obs_source_t *filter) @@ -4730,24 +4356,18 @@ void obs_source_skip_video_filter(obs_source_t *filter) signal_handler_t *obs_source_get_signal_handler(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_signal_handler") - ? source->context.signals - : NULL; + return obs_source_valid(source, "obs_source_get_signal_handler") ? source->context.signals : NULL; } proc_handler_t *obs_source_get_proc_handler(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_proc_handler") - ? source->context.procs - : NULL; + return obs_source_valid(source, "obs_source_get_proc_handler") ? source->context.procs : NULL; } void obs_source_set_volume(obs_source_t *source, float volume) { if (obs_source_valid(source, "obs_source_set_volume")) { - struct audio_action action = {.timestamp = os_gettime_ns(), - .type = AUDIO_ACTION_VOL, - .vol = volume}; + struct audio_action action = {.timestamp = os_gettime_ns(), .type = AUDIO_ACTION_VOL, .vol = volume}; struct calldata data; uint8_t stack[128]; @@ -4758,8 +4378,7 @@ void obs_source_set_volume(obs_source_t *source, float volume) signal_handler_signal(source->context.signals, "volume", &data); if (!source->context.private) - signal_handler_signal(obs->signals, "source_volume", - &data); + signal_handler_signal(obs->signals, "source_volume", &data); volume = (float)calldata_float(&data, "volume"); @@ -4773,9 +4392,7 @@ void obs_source_set_volume(obs_source_t *source, float volume) float obs_source_get_volume(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_volume") - ? source->user_volume - : 0.0f; + return obs_source_valid(source, "obs_source_get_volume") ? source->user_volume : 0.0f; } void obs_source_set_sync_offset(obs_source_t *source, int64_t offset) @@ -4788,8 +4405,7 @@ void obs_source_set_sync_offset(obs_source_t *source, int64_t offset) calldata_set_ptr(&data, "source", source); calldata_set_int(&data, "offset", offset); - signal_handler_signal(source->context.signals, "audio_sync", - &data); + signal_handler_signal(source->context.signals, "audio_sync", &data); source->sync_offset = calldata_int(&data, "offset"); } @@ -4797,9 +4413,7 @@ void obs_source_set_sync_offset(obs_source_t *source, int64_t offset) int64_t obs_source_get_sync_offset(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_sync_offset") - ? source->sync_offset - : 0; + return obs_source_valid(source, "obs_source_get_sync_offset") ? source->sync_offset : 0; } struct source_enum_data { @@ -4807,29 +4421,23 @@ struct source_enum_data { void *param; }; -static void enum_source_active_tree_callback(obs_source_t *parent, - obs_source_t *child, void *param) +static void enum_source_active_tree_callback(obs_source_t *parent, obs_source_t *child, void *param) { struct source_enum_data *data = param; bool is_transition = child->info.type == OBS_SOURCE_TYPE_TRANSITION; if (is_transition) - obs_transition_enum_sources( - child, enum_source_active_tree_callback, param); + obs_transition_enum_sources(child, enum_source_active_tree_callback, param); if (child->info.enum_active_sources) { if (child->context.data) { - child->info.enum_active_sources( - child->context.data, - enum_source_active_tree_callback, data); + child->info.enum_active_sources(child->context.data, enum_source_active_tree_callback, data); } } data->enum_callback(parent, child, data->param); } -void obs_source_enum_active_sources(obs_source_t *source, - obs_source_enum_proc_t enum_callback, - void *param) +void obs_source_enum_active_sources(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param) { bool is_transition; if (!data_valid(source, "obs_source_enum_active_sources")) @@ -4846,15 +4454,12 @@ void obs_source_enum_active_sources(obs_source_t *source, if (is_transition) obs_transition_enum_sources(source, enum_callback, param); if (source->info.enum_active_sources) - source->info.enum_active_sources(source->context.data, - enum_callback, param); + source->info.enum_active_sources(source->context.data, enum_callback, param); obs_source_release(source); } -void obs_source_enum_active_tree(obs_source_t *source, - obs_source_enum_proc_t enum_callback, - void *param) +void obs_source_enum_active_tree(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param) { struct source_enum_data data = {enum_callback, param}; bool is_transition; @@ -4871,45 +4476,34 @@ void obs_source_enum_active_tree(obs_source_t *source, return; if (source->info.type == OBS_SOURCE_TYPE_TRANSITION) - obs_transition_enum_sources( - source, enum_source_active_tree_callback, &data); + obs_transition_enum_sources(source, enum_source_active_tree_callback, &data); if (source->info.enum_active_sources) - source->info.enum_active_sources( - source->context.data, enum_source_active_tree_callback, - &data); + source->info.enum_active_sources(source->context.data, enum_source_active_tree_callback, &data); obs_source_release(source); } -static void enum_source_full_tree_callback(obs_source_t *parent, - obs_source_t *child, void *param) +static void enum_source_full_tree_callback(obs_source_t *parent, obs_source_t *child, void *param) { struct source_enum_data *data = param; bool is_transition = child->info.type == OBS_SOURCE_TYPE_TRANSITION; if (is_transition) - obs_transition_enum_sources( - child, enum_source_full_tree_callback, param); + obs_transition_enum_sources(child, enum_source_full_tree_callback, param); if (child->info.enum_all_sources) { if (child->context.data) { - child->info.enum_all_sources( - child->context.data, - enum_source_full_tree_callback, data); + child->info.enum_all_sources(child->context.data, enum_source_full_tree_callback, data); } } else if (child->info.enum_active_sources) { if (child->context.data) { - child->info.enum_active_sources( - child->context.data, - enum_source_full_tree_callback, data); + child->info.enum_active_sources(child->context.data, enum_source_full_tree_callback, data); } } data->enum_callback(parent, child, data->param); } -void obs_source_enum_full_tree(obs_source_t *source, - obs_source_enum_proc_t enum_callback, - void *param) +void obs_source_enum_full_tree(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param) { struct source_enum_data data = {enum_callback, param}; bool is_transition; @@ -4926,18 +4520,13 @@ void obs_source_enum_full_tree(obs_source_t *source, return; if (source->info.type == OBS_SOURCE_TYPE_TRANSITION) - obs_transition_enum_sources( - source, enum_source_full_tree_callback, &data); + obs_transition_enum_sources(source, enum_source_full_tree_callback, &data); if (source->info.enum_all_sources) { - source->info.enum_all_sources(source->context.data, - enum_source_full_tree_callback, - &data); + source->info.enum_all_sources(source->context.data, enum_source_full_tree_callback, &data); } else if (source->info.enum_active_sources) { - source->info.enum_active_sources(source->context.data, - enum_source_full_tree_callback, - &data); + source->info.enum_active_sources(source->context.data, enum_source_full_tree_callback, &data); } obs_source_release(source); @@ -4948,8 +4537,7 @@ struct descendant_info { obs_source_t *target; }; -static void check_descendant(obs_source_t *parent, obs_source_t *child, - void *param) +static void check_descendant(obs_source_t *parent, obs_source_t *child, void *param) { struct descendant_info *info = param; if (child == info->target || parent == info->target) @@ -5005,8 +4593,7 @@ void obs_source_save(obs_source_t *source) obs_source_dosignal(source, "source_save", "save"); if (source->info.save) - source->info.save(source->context.data, - source->context.settings); + source->info.save(source->context.data, source->context.settings); } void obs_source_load(obs_source_t *source) @@ -5014,8 +4601,7 @@ void obs_source_load(obs_source_t *source) if (!data_valid(source, "obs_source_load")) return; if (source->info.load) - source->info.load(source->context.data, - source->context.settings); + source->info.load(source->context.data, source->context.settings); obs_source_dosignal(source, "source_load", "load"); } @@ -5035,16 +4621,12 @@ void obs_source_load2(obs_source_t *source) bool obs_source_active(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_active") - ? source->activate_refs != 0 - : false; + return obs_source_valid(source, "obs_source_active") ? source->activate_refs != 0 : false; } bool obs_source_showing(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_showing") - ? source->show_refs != 0 - : false; + return obs_source_valid(source, "obs_source_showing") ? source->show_refs != 0 : false; } static inline void signal_flags_updated(obs_source_t *source) @@ -5080,8 +4662,7 @@ void obs_source_set_default_flags(obs_source_t *source, uint32_t flags) uint32_t obs_source_get_flags(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_flags") ? source->flags - : 0; + return obs_source_valid(source, "obs_source_get_flags") ? source->flags : 0; } void obs_source_set_audio_mixers(obs_source_t *source, uint32_t mixers) @@ -5091,8 +4672,7 @@ void obs_source_set_audio_mixers(obs_source_t *source, uint32_t mixers) if (!obs_source_valid(source, "obs_source_set_audio_mixers")) return; - if (!source->owns_info_id && - (source->info.output_flags & OBS_SOURCE_AUDIO) == 0) + if (!source->owns_info_id && (source->info.output_flags & OBS_SOURCE_AUDIO) == 0) return; if (source->audio_mixers == mixers) @@ -5113,15 +4693,13 @@ uint32_t obs_source_get_audio_mixers(const obs_source_t *source) { if (!obs_source_valid(source, "obs_source_get_audio_mixers")) return 0; - if (!source->owns_info_id && - (source->info.output_flags & OBS_SOURCE_AUDIO) == 0) + if (!source->owns_info_id && (source->info.output_flags & OBS_SOURCE_AUDIO) == 0) return 0; return source->audio_mixers; } -void obs_source_draw_set_color_matrix(const struct matrix4 *color_matrix, - const struct vec3 *color_range_min, +void obs_source_draw_set_color_matrix(const struct matrix4 *color_matrix, const struct vec3 *color_range_min, const struct vec3 *color_range_max) { struct vec3 color_range_min_def; @@ -5158,8 +4736,7 @@ void obs_source_draw_set_color_matrix(const struct matrix4 *color_matrix, gs_effect_set_val(range_max, color_range_max, sizeof(float) * 3); } -void obs_source_draw(gs_texture_t *texture, int x, int y, uint32_t cx, - uint32_t cy, bool flip) +void obs_source_draw(gs_texture_t *texture, int x, int y, uint32_t cx, uint32_t cy, bool flip) { if (!obs_ptr_valid(texture, "obs_source_draw")) return; @@ -5219,8 +4796,7 @@ void obs_source_dec_active(obs_source_t *source) obs_source_deactivate(source, MAIN_VIEW); } -void obs_source_enum_filters(obs_source_t *source, - obs_source_enum_proc_t callback, void *param) +void obs_source_enum_filters(obs_source_t *source, obs_source_enum_proc_t callback, void *param) { if (!obs_source_valid(source, "obs_source_enum_filters")) return; @@ -5247,8 +4823,7 @@ bool obs_source_is_hidden(obs_source_t *source) return source->temp_removed; } -obs_source_t *obs_source_get_filter_by_name(obs_source_t *source, - const char *name) +obs_source_t *obs_source_get_filter_by_name(obs_source_t *source, const char *name) { obs_source_t *filter = NULL; @@ -5274,15 +4849,12 @@ obs_source_t *obs_source_get_filter_by_name(obs_source_t *source, size_t obs_source_filter_count(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_filter_count") - ? source->filters.num - : 0; + return obs_source_valid(source, "obs_source_filter_count") ? source->filters.num : 0; } bool obs_source_enabled(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_enabled") ? source->enabled - : false; + return obs_source_valid(source, "obs_source_enabled") ? source->enabled : false; } void obs_source_set_enabled(obs_source_t *source, bool enabled) @@ -5304,17 +4876,14 @@ void obs_source_set_enabled(obs_source_t *source, bool enabled) bool obs_source_muted(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_muted") ? source->user_muted - : false; + return obs_source_valid(source, "obs_source_muted") ? source->user_muted : false; } void obs_source_set_muted(obs_source_t *source, bool muted) { struct calldata data; uint8_t stack[128]; - struct audio_action action = {.timestamp = os_gettime_ns(), - .type = AUDIO_ACTION_MUTE, - .set = muted}; + struct audio_action action = {.timestamp = os_gettime_ns(), .type = AUDIO_ACTION_MUTE, .set = muted}; if (!obs_source_valid(source, "obs_source_set_muted")) return; @@ -5332,8 +4901,7 @@ void obs_source_set_muted(obs_source_t *source, bool muted) pthread_mutex_unlock(&source->audio_actions_mutex); } -static void source_signal_push_to_changed(obs_source_t *source, - const char *signal, bool enabled) +static void source_signal_push_to_changed(obs_source_t *source, const char *signal, bool enabled) { struct calldata data; uint8_t stack[128]; @@ -5345,8 +4913,7 @@ static void source_signal_push_to_changed(obs_source_t *source, signal_handler_signal(source->context.signals, signal, &data); } -static void source_signal_push_to_delay(obs_source_t *source, - const char *signal, uint64_t delay) +static void source_signal_push_to_delay(obs_source_t *source, const char *signal, uint64_t delay) { struct calldata data; uint8_t stack[128]; @@ -5379,15 +4946,13 @@ void obs_source_enable_push_to_mute(obs_source_t *source, bool enabled) pthread_mutex_lock(&source->audio_mutex); bool changed = source->push_to_mute_enabled != enabled; if (obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO && changed) - blog(LOG_INFO, "source '%s' %s push-to-mute", - obs_source_get_name(source), + blog(LOG_INFO, "source '%s' %s push-to-mute", obs_source_get_name(source), enabled ? "enabled" : "disabled"); source->push_to_mute_enabled = enabled; if (changed) - source_signal_push_to_changed(source, "push_to_mute_changed", - enabled); + source_signal_push_to_changed(source, "push_to_mute_changed", enabled); pthread_mutex_unlock(&source->audio_mutex); } @@ -5437,15 +5002,13 @@ void obs_source_enable_push_to_talk(obs_source_t *source, bool enabled) pthread_mutex_lock(&source->audio_mutex); bool changed = source->push_to_talk_enabled != enabled; if (obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO && changed) - blog(LOG_INFO, "source '%s' %s push-to-talk", - obs_source_get_name(source), + blog(LOG_INFO, "source '%s' %s push-to-talk", obs_source_get_name(source), enabled ? "enabled" : "disabled"); source->push_to_talk_enabled = enabled; if (changed) - source_signal_push_to_changed(source, "push_to_talk_changed", - enabled); + source_signal_push_to_changed(source, "push_to_talk_changed", enabled); pthread_mutex_unlock(&source->audio_mutex); } @@ -5476,28 +5039,21 @@ void obs_source_set_push_to_talk_delay(obs_source_t *source, uint64_t delay) void *obs_source_get_type_data(obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_type_data") - ? source->info.type_data - : NULL; + return obs_source_valid(source, "obs_source_get_type_data") ? source->info.type_data : NULL; } static float get_source_volume(obs_source_t *source, uint64_t os_time) { if (source->push_to_mute_enabled && source->push_to_mute_pressed) - source->push_to_mute_stop_time = - os_time + source->push_to_mute_delay * 1000000; + source->push_to_mute_stop_time = os_time + source->push_to_mute_delay * 1000000; if (source->push_to_talk_enabled && source->push_to_talk_pressed) - source->push_to_talk_stop_time = - os_time + source->push_to_talk_delay * 1000000; + source->push_to_talk_stop_time = os_time + source->push_to_talk_delay * 1000000; - bool push_to_mute_active = source->push_to_mute_pressed || - os_time < source->push_to_mute_stop_time; - bool push_to_talk_active = source->push_to_talk_pressed || - os_time < source->push_to_talk_stop_time; + bool push_to_mute_active = source->push_to_mute_pressed || os_time < source->push_to_mute_stop_time; + bool push_to_talk_active = source->push_to_talk_pressed || os_time < source->push_to_talk_stop_time; - bool muted = !source->enabled || source->muted || - (source->push_to_mute_enabled && push_to_mute_active) || + bool muted = !source->enabled || source->muted || (source->push_to_mute_enabled && push_to_mute_active) || (source->push_to_talk_enabled && !push_to_talk_active); if (muted || close_float(source->volume, 0.0f, 0.0001f)) @@ -5508,8 +5064,7 @@ static float get_source_volume(obs_source_t *source, uint64_t os_time) return source->volume; } -static inline void multiply_output_audio(obs_source_t *source, size_t mix, - size_t channels, float vol) +static inline void multiply_output_audio(obs_source_t *source, size_t mix, size_t channels, float vol) { register float *out = source->audio_output_buf[mix][0]; register float *end = out + AUDIO_OUTPUT_FRAMES * channels; @@ -5518,8 +5073,7 @@ static inline void multiply_output_audio(obs_source_t *source, size_t mix, *(out++) *= vol; } -static inline void multiply_vol_data(obs_source_t *source, size_t mix, - size_t channels, float *vol_data) +static inline void multiply_vol_data(obs_source_t *source, size_t mix, size_t channels, float *vol_data) { for (size_t ch = 0; ch < channels; ch++) { register float *out = source->audio_output_buf[mix][ch]; @@ -5531,8 +5085,7 @@ static inline void multiply_vol_data(obs_source_t *source, size_t mix, } } -static inline void apply_audio_action(obs_source_t *source, - const struct audio_action *action) +static inline void apply_audio_action(obs_source_t *source, const struct audio_action *action) { switch (action->type) { case AUDIO_ACTION_VOL: @@ -5550,8 +5103,7 @@ static inline void apply_audio_action(obs_source_t *source, } } -static void apply_audio_actions(obs_source_t *source, size_t channels, - size_t sample_rate) +static void apply_audio_actions(obs_source_t *source, size_t channels, size_t sample_rate) { float vol_data[AUDIO_OUTPUT_FRAMES]; float cur_vol = get_source_volume(source, source->audio_ts); @@ -5567,8 +5119,7 @@ static void apply_audio_actions(obs_source_t *source, size_t channels, if (timestamp < source->audio_ts) timestamp = source->audio_ts; - new_frame_num = conv_time_to_frames( - sample_rate, timestamp - source->audio_ts); + new_frame_num = conv_time_to_frames(sample_rate, timestamp - source->audio_ts); if (new_frame_num >= AUDIO_OUTPUT_FRAMES) break; @@ -5596,8 +5147,7 @@ static void apply_audio_actions(obs_source_t *source, size_t channels, } } -static void apply_audio_volume(obs_source_t *source, uint32_t mixers, - size_t channels, size_t sample_rate) +static void apply_audio_volume(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate) { struct audio_action action; bool actions_pending; @@ -5612,8 +5162,7 @@ static void apply_audio_volume(obs_source_t *source, uint32_t mixers, pthread_mutex_unlock(&source->audio_actions_mutex); if (actions_pending) { - uint64_t duration = - conv_frames_to_time(sample_rate, AUDIO_OUTPUT_FRAMES); + uint64_t duration = conv_frames_to_time(sample_rate, AUDIO_OUTPUT_FRAMES); if (action.timestamp < (source->audio_ts + duration)) { apply_audio_actions(source, channels, sample_rate); @@ -5627,21 +5176,18 @@ static void apply_audio_volume(obs_source_t *source, uint32_t mixers, if (vol == 0.0f || mixers == 0) { memset(source->audio_output_buf[0][0], 0, - AUDIO_OUTPUT_FRAMES * sizeof(float) * - MAX_AUDIO_CHANNELS * MAX_AUDIO_MIXES); + AUDIO_OUTPUT_FRAMES * sizeof(float) * MAX_AUDIO_CHANNELS * MAX_AUDIO_MIXES); return; } for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { uint32_t mix_and_val = (1 << mix); - if ((source->audio_mixers & mix_and_val) != 0 && - (mixers & mix_and_val) != 0) + if ((source->audio_mixers & mix_and_val) != 0 && (mixers & mix_and_val) != 0) multiply_output_audio(source, mix, channels, vol); } } -static void custom_audio_render(obs_source_t *source, uint32_t mixers, - size_t channels, size_t sample_rate) +static void custom_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate) { struct obs_source_audio_mix audio_data; bool success; @@ -5649,19 +5195,15 @@ static void custom_audio_render(obs_source_t *source, uint32_t mixers, for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { for (size_t ch = 0; ch < channels; ch++) { - audio_data.output[mix].data[ch] = - source->audio_output_buf[mix][ch]; + audio_data.output[mix].data[ch] = source->audio_output_buf[mix][ch]; } if ((source->audio_mixers & mixers & (1 << mix)) != 0) { - memset(source->audio_output_buf[mix][0], 0, - sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); + memset(source->audio_output_buf[mix][0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); } } - success = source->info.audio_render(source->context.data, &ts, - &audio_data, mixers, channels, - sample_rate); + success = source->info.audio_render(source->context.data, &ts, &audio_data, mixers, channels, sample_rate); source->audio_ts = success ? ts : 0; source->audio_pending = !success; @@ -5675,16 +5217,14 @@ static void custom_audio_render(obs_source_t *source, uint32_t mixers, continue; if ((source->audio_mixers & mix_bit) == 0) { - memset(source->audio_output_buf[mix][0], 0, - sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); + memset(source->audio_output_buf[mix][0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); } } apply_audio_volume(source, mixers, channels, sample_rate); } -static void audio_submix(obs_source_t *source, size_t channels, - size_t sample_rate) +static void audio_submix(obs_source_t *source, size_t channels, size_t sample_rate) { struct audio_output_data audio_data; struct obs_source_audio audio = {0}; @@ -5695,11 +5235,9 @@ static void audio_submix(obs_source_t *source, size_t channels, audio_data.data[ch] = source->audio_mix_buf[ch]; } - memset(source->audio_mix_buf[0], 0, - sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); + memset(source->audio_mix_buf[0], 0, sizeof(float) * AUDIO_OUTPUT_FRAMES * channels); - success = source->info.audio_mix(source->context.data, &ts, &audio_data, - channels, sample_rate); + success = source->info.audio_mix(source->context.data, &ts, &audio_data, channels, sample_rate); if (!success) return; @@ -5716,9 +5254,8 @@ static void audio_submix(obs_source_t *source, size_t channels, obs_source_output_audio(source, &audio); } -static inline void process_audio_source_tick(obs_source_t *source, - uint32_t mixers, size_t channels, - size_t sample_rate, size_t size) +static inline void process_audio_source_tick(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, + size_t size) { bool audio_submix = !!(source->info.output_flags & OBS_SOURCE_SUBMIX); @@ -5731,8 +5268,7 @@ static inline void process_audio_source_tick(obs_source_t *source, } for (size_t ch = 0; ch < channels; ch++) - deque_peek_front(&source->audio_input_buf[ch], - source->audio_output_buf[0][ch], size); + deque_peek_front(&source->audio_input_buf[ch], source->audio_output_buf[0][ch], size); pthread_mutex_unlock(&source->audio_buf_mutex); @@ -5747,16 +5283,13 @@ static inline void process_audio_source_tick(obs_source_t *source, mix_and_val = 1; } - if ((source->audio_mixers & mix_and_val) == 0 || - (mixers & mix_and_val) == 0) { - memset(source->audio_output_buf[mix][0], 0, - size * channels); + if ((source->audio_mixers & mix_and_val) == 0 || (mixers & mix_and_val) == 0) { + memset(source->audio_output_buf[mix][0], 0, size * channels); continue; } for (size_t ch = 0; ch < channels; ch++) - memcpy(source->audio_output_buf[mix][ch], - source->audio_output_buf[0][ch], size); + memcpy(source->audio_output_buf[mix][ch], source->audio_output_buf[0][ch], size); } if (audio_submix) { @@ -5771,8 +5304,7 @@ static inline void process_audio_source_tick(obs_source_t *source, source->audio_pending = false; } -void obs_source_audio_render(obs_source_t *source, uint32_t mixers, - size_t channels, size_t sample_rate, size_t size) +void obs_source_audio_render(obs_source_t *source, uint32_t mixers, size_t channels, size_t sample_rate, size_t size) { if (!source->audio_output_buf[0][0]) { source->audio_pending = true; @@ -5805,20 +5337,15 @@ bool obs_source_audio_pending(const obs_source_t *source) if (!obs_source_valid(source, "obs_source_audio_pending")) return true; - return (is_composite_source(source) || is_audio_source(source)) - ? source->audio_pending - : true; + return (is_composite_source(source) || is_audio_source(source)) ? source->audio_pending : true; } uint64_t obs_source_get_audio_timestamp(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_audio_timestamp") - ? source->audio_ts - : 0; + return obs_source_valid(source, "obs_source_get_audio_timestamp") ? source->audio_ts : 0; } -void obs_source_get_audio_mix(const obs_source_t *source, - struct obs_source_audio_mix *audio) +void obs_source_get_audio_mix(const obs_source_t *source, struct obs_source_audio_mix *audio) { if (!obs_source_valid(source, "obs_source_get_audio_mix")) return; @@ -5827,15 +5354,12 @@ void obs_source_get_audio_mix(const obs_source_t *source, for (size_t mix = 0; mix < MAX_AUDIO_MIXES; mix++) { for (size_t ch = 0; ch < MAX_AUDIO_CHANNELS; ch++) { - audio->output[mix].data[ch] = - source->audio_output_buf[mix][ch]; + audio->output[mix].data[ch] = source->audio_output_buf[mix][ch]; } } } -void obs_source_add_audio_pause_callback(obs_source_t *source, - signal_callback_t callback, - void *param) +void obs_source_add_audio_pause_callback(obs_source_t *source, signal_callback_t callback, void *param) { if (!obs_source_valid(source, "obs_source_add_audio_pause_callback")) return; @@ -5846,9 +5370,7 @@ void obs_source_add_audio_pause_callback(obs_source_t *source, signal_handler_connect(handler, "media_stopped", callback, param); } -void obs_source_remove_audio_pause_callback(obs_source_t *source, - signal_callback_t callback, - void *param) +void obs_source_remove_audio_pause_callback(obs_source_t *source, signal_callback_t callback, void *param) { if (!obs_source_valid(source, "obs_source_remove_audio_pause_callback")) return; @@ -5859,9 +5381,7 @@ void obs_source_remove_audio_pause_callback(obs_source_t *source, signal_handler_disconnect(handler, "media_stopped", callback, param); } -void obs_source_add_audio_capture_callback(obs_source_t *source, - obs_source_audio_capture_t callback, - void *param) +void obs_source_add_audio_capture_callback(obs_source_t *source, obs_source_audio_capture_t callback, void *param) { struct audio_cb_info info = {callback, param}; @@ -5873,13 +5393,11 @@ void obs_source_add_audio_capture_callback(obs_source_t *source, pthread_mutex_unlock(&source->audio_cb_mutex); } -void obs_source_remove_audio_capture_callback( - obs_source_t *source, obs_source_audio_capture_t callback, void *param) +void obs_source_remove_audio_capture_callback(obs_source_t *source, obs_source_audio_capture_t callback, void *param) { struct audio_cb_info info = {callback, param}; - if (!obs_source_valid(source, - "obs_source_remove_audio_capture_callback")) + if (!obs_source_valid(source, "obs_source_remove_audio_capture_callback")) return; pthread_mutex_lock(&source->audio_cb_mutex); @@ -5887,8 +5405,7 @@ void obs_source_remove_audio_capture_callback( pthread_mutex_unlock(&source->audio_cb_mutex); } -void obs_source_set_monitoring_type(obs_source_t *source, - enum obs_monitoring_type type) +void obs_source_set_monitoring_type(obs_source_t *source, enum obs_monitoring_type type) { struct calldata data; uint8_t stack[128]; @@ -5904,8 +5421,7 @@ void obs_source_set_monitoring_type(obs_source_t *source, calldata_set_ptr(&data, "source", source); calldata_set_int(&data, "type", type); - signal_handler_signal(source->context.signals, "audio_monitoring", - &data); + signal_handler_signal(source->context.signals, "audio_monitoring", &data); was_on = source->monitoring_type != OBS_MONITORING_TYPE_NONE; now_on = type != OBS_MONITORING_TYPE_NONE; @@ -5922,12 +5438,10 @@ void obs_source_set_monitoring_type(obs_source_t *source, source->monitoring_type = type; } -enum obs_monitoring_type -obs_source_get_monitoring_type(const obs_source_t *source) +enum obs_monitoring_type obs_source_get_monitoring_type(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_monitoring_type") - ? source->monitoring_type - : OBS_MONITORING_TYPE_NONE; + return obs_source_valid(source, "obs_source_get_monitoring_type") ? source->monitoring_type + : OBS_MONITORING_TYPE_NONE; } void obs_source_set_async_unbuffered(obs_source_t *source, bool unbuffered) @@ -5940,9 +5454,7 @@ void obs_source_set_async_unbuffered(obs_source_t *source, bool unbuffered) bool obs_source_async_unbuffered(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_async_unbuffered") - ? source->async_unbuffered - : false; + return obs_source_valid(source, "obs_source_async_unbuffered") ? source->async_unbuffered : false; } obs_data_t *obs_source_get_private_settings(obs_source_t *source) @@ -5970,9 +5482,7 @@ void obs_source_set_async_decoupled(obs_source_t *source, bool decouple) bool obs_source_async_decoupled(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_async_decoupled") - ? source->async_decoupled - : false; + return obs_source_valid(source, "obs_source_async_decoupled") ? source->async_decoupled : false; } /* hidden/undocumented export to allow source type redefinition for scripts */ @@ -6006,8 +5516,7 @@ void obs_source_set_balance_value(obs_source_t *source, float balance) calldata_set_ptr(&data, "source", source); calldata_set_float(&data, "balance", balance); - signal_handler_signal(source->context.signals, "audio_balance", - &data); + signal_handler_signal(source->context.signals, "audio_balance", &data); source->balance = (float)calldata_float(&data, "balance"); } @@ -6015,9 +5524,7 @@ void obs_source_set_balance_value(obs_source_t *source, float balance) float obs_source_get_balance_value(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_balance_value") - ? source->balance - : 0.5f; + return obs_source_valid(source, "obs_source_get_balance_value") ? source->balance : 0.5f; } void obs_source_set_audio_active(obs_source_t *source, bool active) @@ -6029,25 +5536,19 @@ void obs_source_set_audio_active(obs_source_t *source, bool active) return; if (active) - obs_source_dosignal(source, "source_audio_activate", - "audio_activate"); + obs_source_dosignal(source, "source_audio_activate", "audio_activate"); else - obs_source_dosignal(source, "source_audio_deactivate", - "audio_deactivate"); + obs_source_dosignal(source, "source_audio_deactivate", "audio_deactivate"); } bool obs_source_audio_active(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_audio_active") - ? os_atomic_load_bool(&source->audio_active) - : false; + return obs_source_valid(source, "obs_source_audio_active") ? os_atomic_load_bool(&source->audio_active) : false; } uint32_t obs_source_get_last_obs_version(const obs_source_t *source) { - return obs_source_valid(source, "obs_source_get_last_obs_version") - ? source->last_obs_ver - : 0; + return obs_source_valid(source, "obs_source_get_last_obs_version") ? source->last_obs_ver : 0; } enum obs_icon_type obs_source_get_icon_type(const char *id) diff --git a/libobs/obs-source.h b/libobs/obs-source.h index 051586159..4849d5394 100644 --- a/libobs/obs-source.h +++ b/libobs/obs-source.h @@ -205,8 +205,7 @@ enum obs_media_state { /** @} */ -typedef void (*obs_source_enum_proc_t)(obs_source_t *parent, - obs_source_t *child, void *param); +typedef void (*obs_source_enum_proc_t)(obs_source_t *parent, obs_source_t *child, void *param); struct obs_source_audio_mix { struct audio_output_data output[MAX_AUDIO_MIXES]; @@ -356,8 +355,7 @@ struct obs_source_info { * @return New video frame data. This can defer video data to * be drawn later if time is needed for processing */ - struct obs_source_frame *(*filter_video)( - void *data, struct obs_source_frame *frame); + struct obs_source_frame *(*filter_video)(void *data, struct obs_source_frame *frame); /** * Called to filter raw audio data. @@ -373,8 +371,7 @@ struct obs_source_info { * until the next call to the filter_audio callback or * until the filter is removed/destroyed. */ - struct obs_audio_data *(*filter_audio)(void *data, - struct obs_audio_data *audio); + struct obs_audio_data *(*filter_audio)(void *data, struct obs_audio_data *audio); /** * Called to enumerate all active sources being used within this @@ -385,9 +382,7 @@ struct obs_source_info { * @param enum_callback Enumeration callback * @param param User data to pass to callback */ - void (*enum_active_sources)(void *data, - obs_source_enum_proc_t enum_callback, - void *param); + void (*enum_active_sources)(void *data, obs_source_enum_proc_t enum_callback, void *param); /** * Called when saving a source. This is a separate function because @@ -420,8 +415,8 @@ struct obs_source_info { * @param mouse_up Mouse event type (true if mouse-up) * @param click_count Mouse click count (1 for single click, etc.) */ - void (*mouse_click)(void *data, const struct obs_mouse_event *event, - int32_t type, bool mouse_up, uint32_t click_count); + void (*mouse_click)(void *data, const struct obs_mouse_event *event, int32_t type, bool mouse_up, + uint32_t click_count); /** * Called when interacting with a source and a mouse-move occurs. * @@ -429,8 +424,7 @@ struct obs_source_info { * @param event Mouse event properties * @param mouse_leave Mouse leave state (true if mouse left source) */ - void (*mouse_move)(void *data, const struct obs_mouse_event *event, - bool mouse_leave); + void (*mouse_move)(void *data, const struct obs_mouse_event *event, bool mouse_leave); /** * Called when interacting with a source and a mouse-wheel occurs. @@ -440,8 +434,7 @@ struct obs_source_info { * @param x_delta Movement delta in the horizontal direction * @param y_delta Movement delta in the vertical direction */ - void (*mouse_wheel)(void *data, const struct obs_mouse_event *event, - int x_delta, int y_delta); + void (*mouse_wheel)(void *data, const struct obs_mouse_event *event, int x_delta, int y_delta); /** * Called when interacting with a source and gain focus/lost focus event * occurs. @@ -459,8 +452,7 @@ struct obs_source_info { * @param event Key event properties * @param focus Key event type (true if mouse-up) */ - void (*key_click)(void *data, const struct obs_key_event *event, - bool key_up); + void (*key_click)(void *data, const struct obs_key_event *event, bool key_up); /** * Called when the filter is removed from a source @@ -480,10 +472,8 @@ struct obs_source_info { */ void (*free_type_data)(void *type_data); - bool (*audio_render)(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, - uint32_t mixers, size_t channels, - size_t sample_rate); + bool (*audio_render)(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio_output, uint32_t mixers, + size_t channels, size_t sample_rate); /** * Called to enumerate all active and inactive sources being used @@ -496,9 +486,7 @@ struct obs_source_info { * @param enum_callback Enumeration callback * @param param User data to pass to callback */ - void (*enum_all_sources)(void *data, - obs_source_enum_proc_t enum_callback, - void *param); + void (*enum_all_sources)(void *data, obs_source_enum_proc_t enum_callback, void *param); void (*transition_start)(void *data); void (*transition_stop)(void *data); @@ -523,9 +511,8 @@ struct obs_source_info { */ obs_properties_t *(*get_properties2)(void *data, void *type_data); - bool (*audio_mix)(void *data, uint64_t *ts_out, - struct audio_output_data *audio_output, - size_t channels, size_t sample_rate); + bool (*audio_mix)(void *data, uint64_t *ts_out, struct audio_output_data *audio_output, size_t channels, + size_t sample_rate); /** Icon type for the source */ enum obs_icon_type icon_type; @@ -542,16 +529,15 @@ struct obs_source_info { enum obs_media_state (*media_get_state)(void *data); /* version-related stuff */ - uint32_t version; /* increment if needed to specify a new version */ + uint32_t version; /* increment if needed to specify a new version */ const char *unversioned_id; /* set internally, don't set manually */ /** Missing files **/ obs_missing_files_t *(*missing_files)(void *data); /** Get color space **/ - enum gs_color_space (*video_get_color_space)( - void *data, size_t count, - const enum gs_color_space *preferred_spaces); + enum gs_color_space (*video_get_color_space)(void *data, size_t count, + const enum gs_color_space *preferred_spaces); /** * Called when the filter is added to a source @@ -562,8 +548,7 @@ struct obs_source_info { void (*filter_add)(void *data, obs_source_t *source); }; -EXPORT void obs_register_source_s(const struct obs_source_info *info, - size_t size); +EXPORT void obs_register_source_s(const struct obs_source_info *info, size_t size); /** * Registers a source definition to the current obs context. This should be @@ -571,8 +556,7 @@ EXPORT void obs_register_source_s(const struct obs_source_info *info, * * @param info Pointer to the source definition structure */ -#define obs_register_source(info) \ - obs_register_source_s(info, sizeof(struct obs_source_info)) +#define obs_register_source(info) obs_register_source_s(info, sizeof(struct obs_source_info)) #ifdef __cplusplus } diff --git a/libobs/obs-video-gpu-encode.c b/libobs/obs-video-gpu-encode.c index 3762fc826..977562194 100644 --- a/libobs/obs-video-gpu-encode.c +++ b/libobs/obs-video-gpu-encode.c @@ -30,8 +30,7 @@ static void *gpu_encode_thread(void *data) os_set_thread_name("obs gpu encode thread"); const char *gpu_encode_thread_name = profile_store_name( - obs_get_profiler_name_store(), - "obs_gpu_encode_thread(%g" NBSP "ms)", interval / 1000000.); + obs_get_profiler_name_store(), "obs_gpu_encode_thread(%g" NBSP "ms)", interval / 1000000.); profile_register_root(gpu_encode_thread_name, interval); while (os_sem_wait(video->gpu_encode_semaphore) == 0) { @@ -66,8 +65,7 @@ static void *gpu_encode_thread(void *data) video_output_inc_texture_frames(video->video); for (size_t i = 0; i < video->gpu_encoders.num; i++) { - obs_encoder_t *encoder = obs_encoder_get_ref( - video->gpu_encoders.array[i]); + obs_encoder_t *encoder = obs_encoder_get_ref(video->gpu_encoders.array[i]); if (encoder) da_push_back(encoders, &encoder); } @@ -83,18 +81,15 @@ static void *gpu_encode_thread(void *data) uint32_t skip = 0; obs_encoder_t *encoder = encoders.array[i]; - obs_weak_encoder_t **paired = - encoder->paired_encoders.array; + obs_weak_encoder_t **paired = encoder->paired_encoders.array; size_t num_paired = encoder->paired_encoders.num; - pkt.timebase_num = encoder->timebase_num * - encoder->frame_rate_divisor; + pkt.timebase_num = encoder->timebase_num * encoder->frame_rate_divisor; pkt.timebase_den = encoder->timebase_den; pkt.encoder = encoder; if (encoder->encoder_group && !encoder->start_ts) { - struct obs_encoder_group *group = - encoder->encoder_group; + struct obs_encoder_group *group = encoder->encoder_group; bool ready = false; pthread_mutex_lock(&group->mutex); ready = group->start_timestamp == timestamp; @@ -106,17 +101,12 @@ static void *gpu_encode_thread(void *data) if (!encoder->first_received && num_paired) { bool wait_for_audio = false; - for (size_t idx = 0; - !wait_for_audio && idx < num_paired; - idx++) { - obs_encoder_t *enc = - obs_weak_encoder_get_encoder( - paired[idx]); + for (size_t idx = 0; !wait_for_audio && idx < num_paired; idx++) { + obs_encoder_t *enc = obs_weak_encoder_get_encoder(paired[idx]); if (!enc) continue; - if (!enc->first_received || - enc->first_raw_ts > timestamp) { + if (!enc->first_received || enc->first_raw_ts > timestamp) { wait_for_audio = true; } @@ -132,16 +122,14 @@ static void *gpu_encode_thread(void *data) if (encoder->reconfigure_requested) { encoder->reconfigure_requested = false; - encoder->info.update(encoder->context.data, - encoder->context.settings); + encoder->info.update(encoder->context.data, encoder->context.settings); } // an explicit counter is used instead of remainder calculation // to allow multiple encoders started at the same time to start on // the same frame skip = encoder->frame_rate_divisor_counter++; - if (encoder->frame_rate_divisor_counter == - encoder->frame_rate_divisor) + if (encoder->frame_rate_divisor_counter == encoder->frame_rate_divisor) encoder->frame_rate_divisor_counter = 0; if (skip) continue; @@ -167,15 +155,12 @@ static void *gpu_encode_thread(void *data) tex.tex[0] = tf.tex; tex.tex[1] = tf.tex_uv; tex.tex[2] = NULL; - success = encoder->info.encode_texture2( - encoder->context.data, &tex, - encoder->cur_pts, lock_key, &next_key, - &pkt, &received); + success = encoder->info.encode_texture2(encoder->context.data, &tex, encoder->cur_pts, + lock_key, &next_key, &pkt, &received); } else { - success = encoder->info.encode_texture( - encoder->context.data, tf.handle, - encoder->cur_pts, lock_key, &next_key, - &pkt, &received); + success = encoder->info.encode_texture(encoder->context.data, tf.handle, + encoder->cur_pts, lock_key, &next_key, &pkt, + &received); } profile_end(gpu_encode_frame_name); @@ -184,9 +169,7 @@ static void *gpu_encode_thread(void *data) * (frame encode request complete) and current PTS. PTS is used to * associate the frame timing data with the encode packet. */ if (tf.timestamp) { - struct encoder_packet_time *ept = - da_push_back_new( - encoder->encoder_packet_times); + struct encoder_packet_time *ept = da_push_back_new(encoder->encoder_packet_times); // Get the frame encode request complete timestamp if (success) { ept->ferc = os_gettime_ns(); @@ -200,13 +183,11 @@ static void *gpu_encode_thread(void *data) ept->fer = fer_ts; } - send_off_encoder_packet(encoder, success, received, - &pkt); + send_off_encoder_packet(encoder, success, received, &pkt); lock_key = next_key; - encoder->cur_pts += encoder->timebase_num * - encoder->frame_rate_divisor; + encoder->cur_pts += encoder->timebase_num * encoder->frame_rate_divisor; } /* -------------- */ @@ -217,13 +198,11 @@ static void *gpu_encode_thread(void *data) if (--tf.count) { tf.timestamp += interval; - deque_push_front(&video->gpu_encoder_queue, &tf, - sizeof(tf)); + deque_push_front(&video->gpu_encoder_queue, &tf, sizeof(tf)); video_output_inc_texture_skipped_frames(video->video); } else { - deque_push_back(&video->gpu_encoder_avail_queue, &tf, - sizeof(tf)); + deque_push_back(&video->gpu_encoder_avail_queue, &tf, sizeof(tf)); } pthread_mutex_unlock(&video->gpu_encoder_mutex); @@ -247,8 +226,7 @@ static void *gpu_encode_thread(void *data) bool init_gpu_encoding(struct obs_core_video_mix *video) { - const struct video_output_info *info = - video_output_get_info(video->video); + const struct video_output_info *info = video_output_get_info(video->video); video->gpu_encode_stop = false; @@ -258,13 +236,11 @@ bool init_gpu_encoding(struct obs_core_video_mix *video) gs_texture_t *tex_uv; if (info->format == VIDEO_FORMAT_P010) { - gs_texture_create_p010( - &tex, &tex_uv, info->width, info->height, - GS_RENDER_TARGET | GS_SHARED_KM_TEX); + gs_texture_create_p010(&tex, &tex_uv, info->width, info->height, + GS_RENDER_TARGET | GS_SHARED_KM_TEX); } else { - gs_texture_create_nv12( - &tex, &tex_uv, info->width, info->height, - GS_RENDER_TARGET | GS_SHARED_KM_TEX); + gs_texture_create_nv12(&tex, &tex_uv, info->width, info->height, + GS_RENDER_TARGET | GS_SHARED_KM_TEX); } if (!tex) { return false; @@ -276,21 +252,16 @@ bool init_gpu_encoding(struct obs_core_video_mix *video) uint32_t handle = (uint32_t)-1; #endif - struct obs_tex_frame frame = {.tex = tex, - .tex_uv = tex_uv, - .handle = handle}; + struct obs_tex_frame frame = {.tex = tex, .tex_uv = tex_uv, .handle = handle}; - deque_push_back(&video->gpu_encoder_avail_queue, &frame, - sizeof(frame)); + deque_push_back(&video->gpu_encoder_avail_queue, &frame, sizeof(frame)); } if (os_sem_init(&video->gpu_encode_semaphore, 0) != 0) return false; - if (os_event_init(&video->gpu_encode_inactive, OS_EVENT_TYPE_MANUAL) != - 0) + if (os_event_init(&video->gpu_encode_inactive, OS_EVENT_TYPE_MANUAL) != 0) return false; - if (pthread_create(&video->gpu_encode_thread, NULL, gpu_encode_thread, - video) != 0) + if (pthread_create(&video->gpu_encode_thread, NULL, gpu_encode_thread, video) != 0) return false; os_event_signal(video->gpu_encode_inactive); diff --git a/libobs/obs-video.c b/libobs/obs-video.c index 09b885452..246d8f771 100644 --- a/libobs/obs-video.c +++ b/libobs/obs-video.c @@ -131,20 +131,17 @@ static inline void unmap_last_surface(struct obs_core_video_mix *video) } } -static inline bool can_reuse_mix_texture(const struct obs_core_video_mix *mix, - size_t *idx) +static inline bool can_reuse_mix_texture(const struct obs_core_video_mix *mix, size_t *idx) { for (size_t i = 0, num = obs->video.mixes.num; i < num; i++) { - const struct obs_core_video_mix *other = - obs->video.mixes.array[i]; + const struct obs_core_video_mix *other = obs->video.mixes.array[i]; if (other == mix) break; if (other->view != mix->view) continue; if (other->render_space != mix->render_space) continue; - if (other->ovi.base_width != mix->ovi.base_width || - other->ovi.base_height != mix->ovi.base_height) + if (other->ovi.base_width != mix->ovi.base_width || other->ovi.base_height != mix->ovi.base_height) continue; if (!other->texture_rendered) continue; @@ -176,14 +173,12 @@ static inline void render_main_texture(struct obs_core_video_mix *video) uint32_t base_height = video->ovi.base_height; profile_start(render_main_texture_name); - GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_MAIN_TEXTURE, - render_main_texture_name); + GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_MAIN_TEXTURE, render_main_texture_name); struct vec4 clear_color; vec4_set(&clear_color, 0.0f, 0.0f, 0.0f, 0.0f); - gs_set_render_target_with_color_space(video->render_texture, NULL, - video->render_space); + gs_set_render_target_with_color_space(video->render_texture, NULL, video->render_space); gs_clear(GS_CLEAR_COLOR, &clear_color, 1.0f, 0); set_render_size(base_width, base_height); @@ -191,8 +186,7 @@ static inline void render_main_texture(struct obs_core_video_mix *video) pthread_mutex_lock(&obs->data.draw_callbacks_mutex); for (size_t i = obs->data.draw_callbacks.num; i > 0; i--) { - struct draw_callback *const callback = - obs->data.draw_callbacks.array + (i - 1); + struct draw_callback *const callback = obs->data.draw_callbacks.array + (i - 1); callback->draw(callback->param, base_width, base_height); } @@ -210,8 +204,7 @@ static inline void render_main_texture(struct obs_core_video_mix *video) pthread_mutex_lock(&obs->data.draw_callbacks_mutex); for (size_t i = 0; i < obs->data.rendered_callbacks.num; ++i) { - struct rendered_callback *const callback = - &obs->data.rendered_callbacks.array[i]; + struct rendered_callback *const callback = &obs->data.rendered_callbacks.array[i]; callback->rendered(callback->param); } @@ -221,18 +214,15 @@ static inline void render_main_texture(struct obs_core_video_mix *video) profile_end(render_main_texture_name); } -static inline gs_effect_t * -get_scale_effect_internal(struct obs_core_video_mix *mix) +static inline gs_effect_t *get_scale_effect_internal(struct obs_core_video_mix *mix) { struct obs_core_video *video = &obs->video; - const struct video_output_info *info = - video_output_get_info(mix->video); + const struct video_output_info *info = video_output_get_info(mix->video); /* if the dimension is under half the size of the original image, * bicubic/lanczos can't sample enough pixels to create an accurate * image, so use the bilinear low resolution effect instead */ - if (info->width < (mix->ovi.base_width / 2) && - info->height < (mix->ovi.base_height / 2)) { + if (info->width < (mix->ovi.base_width / 2) && info->height < (mix->ovi.base_height / 2)) { return video->bilinear_lowres_effect; } @@ -250,8 +240,7 @@ get_scale_effect_internal(struct obs_core_video_mix *mix) return video->bicubic_effect; } -static inline bool resolution_close(struct obs_core_video_mix *mix, - uint32_t width, uint32_t height) +static inline bool resolution_close(struct obs_core_video_mix *mix, uint32_t width, uint32_t height) { long width_cmp = (long)mix->ovi.base_width - (long)width; long height_cmp = (long)mix->ovi.base_height - (long)height; @@ -259,8 +248,7 @@ static inline bool resolution_close(struct obs_core_video_mix *mix, return labs(width_cmp) <= 16 && labs(height_cmp) <= 16; } -static inline gs_effect_t *get_scale_effect(struct obs_core_video_mix *mix, - uint32_t width, uint32_t height) +static inline gs_effect_t *get_scale_effect(struct obs_core_video_mix *mix, uint32_t width, uint32_t height) { struct obs_core_video *video = &obs->video; @@ -271,16 +259,13 @@ static inline gs_effect_t *get_scale_effect(struct obs_core_video_mix *mix, * or bilinear by default */ gs_effect_t *effect = get_scale_effect_internal(mix); if (!effect) - effect = !!video->bicubic_effect - ? video->bicubic_effect - : video->default_effect; + effect = !!video->bicubic_effect ? video->bicubic_effect : video->default_effect; return effect; } } static const char *render_output_texture_name = "render_output_texture"; -static inline gs_texture_t * -render_output_texture(struct obs_core_video_mix *mix) +static inline gs_texture_t *render_output_texture(struct obs_core_video_mix *mix) { struct obs_video_info *const ovi = &mix->ovi; gs_texture_t *texture = mix->render_texture; @@ -296,10 +281,8 @@ render_output_texture(struct obs_core_video_mix *mix) gs_technique_t *tech = gs_effect_get_technique(effect, "Draw"); gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image"); - gs_eparam_t *bres = - gs_effect_get_param_by_name(effect, "base_dimension"); - gs_eparam_t *bres_i = - gs_effect_get_param_by_name(effect, "base_dimension_i"); + gs_eparam_t *bres = gs_effect_get_param_by_name(effect, "base_dimension"); + gs_eparam_t *bres_i = gs_effect_get_param_by_name(effect, "base_dimension_i"); size_t passes, i; gs_set_render_target(target, NULL); @@ -307,15 +290,13 @@ render_output_texture(struct obs_core_video_mix *mix) if (bres) { struct vec2 base; - vec2_set(&base, (float)mix->ovi.base_width, - (float)mix->ovi.base_height); + vec2_set(&base, (float)mix->ovi.base_width, (float)mix->ovi.base_height); gs_effect_set_vec2(bres, &base); } if (bres_i) { struct vec2 base_i; - vec2_set(&base_i, 1.0f / (float)mix->ovi.base_width, - 1.0f / (float)mix->ovi.base_height); + vec2_set(&base_i, 1.0f / (float)mix->ovi.base_width, 1.0f / (float)mix->ovi.base_height); gs_effect_set_vec2(bres_i, &base_i); } @@ -338,8 +319,7 @@ render_output_texture(struct obs_core_video_mix *mix) return target; } -static void render_convert_plane(gs_effect_t *effect, gs_texture_t *target, - const char *tech_name) +static void render_convert_plane(gs_effect_t *effect, gs_texture_t *target, const char *tech_name) { gs_technique_t *tech = gs_effect_get_technique(effect, tech_name); @@ -359,47 +339,37 @@ static void render_convert_plane(gs_effect_t *effect, gs_texture_t *target, } static const char *render_convert_texture_name = "render_convert_texture"; -static void render_convert_texture(struct obs_core_video_mix *video, - gs_texture_t *const *const convert_textures, +static void render_convert_texture(struct obs_core_video_mix *video, gs_texture_t *const *const convert_textures, gs_texture_t *texture) { profile_start(render_convert_texture_name); gs_effect_t *effect = obs->video.conversion_effect; - gs_eparam_t *color_vec0 = - gs_effect_get_param_by_name(effect, "color_vec0"); - gs_eparam_t *color_vec1 = - gs_effect_get_param_by_name(effect, "color_vec1"); - gs_eparam_t *color_vec2 = - gs_effect_get_param_by_name(effect, "color_vec2"); + gs_eparam_t *color_vec0 = gs_effect_get_param_by_name(effect, "color_vec0"); + gs_eparam_t *color_vec1 = gs_effect_get_param_by_name(effect, "color_vec1"); + gs_eparam_t *color_vec2 = gs_effect_get_param_by_name(effect, "color_vec2"); gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image"); gs_eparam_t *width_i = gs_effect_get_param_by_name(effect, "width_i"); gs_eparam_t *height_i = gs_effect_get_param_by_name(effect, "height_i"); - gs_eparam_t *sdr_white_nits_over_maximum = gs_effect_get_param_by_name( - effect, "sdr_white_nits_over_maximum"); + gs_eparam_t *sdr_white_nits_over_maximum = gs_effect_get_param_by_name(effect, "sdr_white_nits_over_maximum"); gs_eparam_t *hdr_lw = gs_effect_get_param_by_name(effect, "hdr_lw"); struct vec4 vec0, vec1, vec2; - vec4_set(&vec0, video->color_matrix[4], video->color_matrix[5], - video->color_matrix[6], video->color_matrix[7]); - vec4_set(&vec1, video->color_matrix[0], video->color_matrix[1], - video->color_matrix[2], video->color_matrix[3]); - vec4_set(&vec2, video->color_matrix[8], video->color_matrix[9], - video->color_matrix[10], video->color_matrix[11]); + vec4_set(&vec0, video->color_matrix[4], video->color_matrix[5], video->color_matrix[6], video->color_matrix[7]); + vec4_set(&vec1, video->color_matrix[0], video->color_matrix[1], video->color_matrix[2], video->color_matrix[3]); + vec4_set(&vec2, video->color_matrix[8], video->color_matrix[9], video->color_matrix[10], + video->color_matrix[11]); gs_enable_blending(false); if (convert_textures[0]) { - const float hdr_nominal_peak_level = - obs->video.hdr_nominal_peak_level; - const float multiplier = - obs_get_video_sdr_white_level() / 10000.f; + const float hdr_nominal_peak_level = obs->video.hdr_nominal_peak_level; + const float multiplier = obs_get_video_sdr_white_level() / 10000.f; gs_effect_set_texture(image, texture); gs_effect_set_vec4(color_vec0, &vec0); gs_effect_set_float(sdr_white_nits_over_maximum, multiplier); gs_effect_set_float(hdr_lw, hdr_nominal_peak_level); - render_convert_plane(effect, convert_textures[0], - video->conversion_techs[0]); + render_convert_plane(effect, convert_textures[0], video->conversion_techs[0]); if (convert_textures[1]) { gs_effect_set_texture(image, texture); @@ -407,28 +377,19 @@ static void render_convert_texture(struct obs_core_video_mix *video, if (!convert_textures[2]) gs_effect_set_vec4(color_vec2, &vec2); gs_effect_set_float(width_i, video->conversion_width_i); - gs_effect_set_float(height_i, - video->conversion_height_i); - gs_effect_set_float(sdr_white_nits_over_maximum, - multiplier); + gs_effect_set_float(height_i, video->conversion_height_i); + gs_effect_set_float(sdr_white_nits_over_maximum, multiplier); gs_effect_set_float(hdr_lw, hdr_nominal_peak_level); - render_convert_plane(effect, convert_textures[1], - video->conversion_techs[1]); + render_convert_plane(effect, convert_textures[1], video->conversion_techs[1]); if (convert_textures[2]) { gs_effect_set_texture(image, texture); gs_effect_set_vec4(color_vec2, &vec2); - gs_effect_set_float(width_i, - video->conversion_width_i); - gs_effect_set_float(height_i, - video->conversion_height_i); - gs_effect_set_float(sdr_white_nits_over_maximum, - multiplier); - gs_effect_set_float(hdr_lw, - hdr_nominal_peak_level); - render_convert_plane( - effect, convert_textures[2], - video->conversion_techs[2]); + gs_effect_set_float(width_i, video->conversion_width_i); + gs_effect_set_float(height_i, video->conversion_height_i); + gs_effect_set_float(sdr_white_nits_over_maximum, multiplier); + gs_effect_set_float(hdr_lw, hdr_nominal_peak_level); + render_convert_plane(effect, convert_textures[2], video->conversion_techs[2]); } } } @@ -441,12 +402,9 @@ static void render_convert_texture(struct obs_core_video_mix *video, } static const char *stage_output_texture_name = "stage_output_texture"; -static inline void -stage_output_texture(struct obs_core_video_mix *video, int cur_texture, - gs_texture_t *const *const convert_textures, - gs_texture_t *output_texture, - gs_stagesurf_t *const *const copy_surfaces, - size_t channel_count) +static inline void stage_output_texture(struct obs_core_video_mix *video, int cur_texture, + gs_texture_t *const *const convert_textures, gs_texture_t *output_texture, + gs_stagesurf_t *const *const copy_surfaces, size_t channel_count) { profile_start(stage_output_texture_name); @@ -479,18 +437,14 @@ stage_output_texture(struct obs_core_video_mix *video, int cur_texture, profile_end(stage_output_texture_name); } -static inline bool queue_frame(struct obs_core_video_mix *video, - bool raw_active, - struct obs_vframe_info *vframe_info) +static inline bool queue_frame(struct obs_core_video_mix *video, bool raw_active, struct obs_vframe_info *vframe_info) { - bool duplicate = - !video->gpu_encoder_avail_queue.size || - (video->gpu_encoder_queue.size && vframe_info->count > 1); + bool duplicate = !video->gpu_encoder_avail_queue.size || + (video->gpu_encoder_queue.size && vframe_info->count > 1); if (duplicate) { struct obs_tex_frame *tf = - deque_data(&video->gpu_encoder_queue, - video->gpu_encoder_queue.size - sizeof(*tf)); + deque_data(&video->gpu_encoder_queue, video->gpu_encoder_queue.size - sizeof(*tf)); /* texture-based encoding is stopping */ if (!tf) { @@ -553,16 +507,14 @@ finish: extern void full_stop(struct obs_encoder *encoder); -static inline void encode_gpu(struct obs_core_video_mix *video, bool raw_active, - struct obs_vframe_info *vframe_info) +static inline void encode_gpu(struct obs_core_video_mix *video, bool raw_active, struct obs_vframe_info *vframe_info) { while (queue_frame(video, raw_active, vframe_info)) ; } static const char *output_gpu_encoders_name = "output_gpu_encoders"; -static void output_gpu_encoders(struct obs_core_video_mix *video, - bool raw_active) +static void output_gpu_encoders(struct obs_core_video_mix *video, bool raw_active) { profile_start(output_gpu_encoders_name); @@ -572,8 +524,7 @@ static void output_gpu_encoders(struct obs_core_video_mix *video, goto end; struct obs_vframe_info vframe_info; - deque_pop_front(&video->vframe_info_buffer_gpu, &vframe_info, - sizeof(vframe_info)); + deque_pop_front(&video->vframe_info_buffer_gpu, &vframe_info, sizeof(vframe_info)); pthread_mutex_lock(&video->gpu_encoder_mutex); encode_gpu(video, raw_active, &vframe_info); @@ -583,8 +534,7 @@ end: profile_end(output_gpu_encoders_name); } -static inline void render_video(struct obs_core_video_mix *video, - bool raw_active, const bool gpu_active, +static inline void render_video(struct obs_core_video_mix *video, bool raw_active, const bool gpu_active, int cur_texture) { gs_begin_scene(); @@ -596,8 +546,7 @@ static inline void render_video(struct obs_core_video_mix *video, if (raw_active || gpu_active) { gs_texture_t *const *convert_textures = video->convert_textures; - gs_stagesurf_t *const *copy_surfaces = - video->copy_surfaces[cur_texture]; + gs_stagesurf_t *const *copy_surfaces = video->copy_surfaces[cur_texture]; size_t channel_count = NUM_CHANNELS; gs_texture_t *output_texture = render_output_texture(video); @@ -611,8 +560,7 @@ static inline void render_video(struct obs_core_video_mix *video, } if (video->gpu_conversion) { - render_convert_texture(video, convert_textures, - output_texture); + render_convert_texture(video, convert_textures, output_texture); } if (gpu_active) { @@ -621,9 +569,8 @@ static inline void render_video(struct obs_core_video_mix *video, } if (raw_active) { - stage_output_texture(video, cur_texture, - convert_textures, output_texture, - copy_surfaces, channel_count); + stage_output_texture(video, cur_texture, convert_textures, output_texture, copy_surfaces, + channel_count); } } @@ -633,18 +580,15 @@ static inline void render_video(struct obs_core_video_mix *video, gs_end_scene(); } -static inline bool download_frame(struct obs_core_video_mix *video, - int prev_texture, struct video_data *frame) +static inline bool download_frame(struct obs_core_video_mix *video, int prev_texture, struct video_data *frame) { if (!video->textures_copied[prev_texture]) return false; for (int channel = 0; channel < NUM_CHANNELS; ++channel) { - gs_stagesurf_t *surface = - video->active_copy_surfaces[prev_texture][channel]; + gs_stagesurf_t *surface = video->active_copy_surfaces[prev_texture][channel]; if (surface) { - if (!gs_stagesurface_map(surface, &frame->data[channel], - &frame->linesize[channel])) + if (!gs_stagesurface_map(surface, &frame->data[channel], &frame->linesize[channel])) return false; video->mapped_surfaces[channel] = surface; @@ -653,10 +597,8 @@ static inline bool download_frame(struct obs_core_video_mix *video, return true; } -static const uint8_t *set_gpu_converted_plane(uint32_t width, uint32_t height, - uint32_t linesize_input, - uint32_t linesize_output, - const uint8_t *in, uint8_t *out) +static const uint8_t *set_gpu_converted_plane(uint32_t width, uint32_t height, uint32_t linesize_input, + uint32_t linesize_output, const uint8_t *in, uint8_t *out) { if ((width == linesize_input) && (width == linesize_output)) { size_t total = (size_t)width * (size_t)height; @@ -673,8 +615,7 @@ static const uint8_t *set_gpu_converted_plane(uint32_t width, uint32_t height, return in; } -static void set_gpu_converted_data(struct video_frame *output, - const struct video_data *input, +static void set_gpu_converted_data(struct video_frame *output, const struct video_data *input, const struct video_output_info *info) { switch (info->format) { @@ -682,19 +623,16 @@ static void set_gpu_converted_data(struct video_frame *output, const uint32_t width = info->width; const uint32_t height = info->height; - set_gpu_converted_plane(width, height, input->linesize[0], - output->linesize[0], input->data[0], + set_gpu_converted_plane(width, height, input->linesize[0], output->linesize[0], input->data[0], output->data[0]); const uint32_t width_d2 = width / 2; const uint32_t height_d2 = height / 2; - set_gpu_converted_plane(width_d2, height_d2, input->linesize[1], - output->linesize[1], input->data[1], + set_gpu_converted_plane(width_d2, height_d2, input->linesize[1], output->linesize[1], input->data[1], output->data[1]); - set_gpu_converted_plane(width_d2, height_d2, input->linesize[2], - output->linesize[2], input->data[2], + set_gpu_converted_plane(width_d2, height_d2, input->linesize[2], output->linesize[2], input->data[2], output->data[2]); break; @@ -704,24 +642,15 @@ static void set_gpu_converted_data(struct video_frame *output, const uint32_t height = info->height; const uint32_t height_d2 = height / 2; if (input->linesize[1]) { - set_gpu_converted_plane(width, height, - input->linesize[0], - output->linesize[0], - input->data[0], + set_gpu_converted_plane(width, height, input->linesize[0], output->linesize[0], input->data[0], output->data[0]); - set_gpu_converted_plane(width, height_d2, - input->linesize[1], - output->linesize[1], - input->data[1], - output->data[1]); + set_gpu_converted_plane(width, height_d2, input->linesize[1], output->linesize[1], + input->data[1], output->data[1]); } else { - const uint8_t *const in_uv = set_gpu_converted_plane( - width, height, input->linesize[0], - output->linesize[0], input->data[0], - output->data[0]); - set_gpu_converted_plane(width, height_d2, - input->linesize[0], - output->linesize[1], in_uv, + const uint8_t *const in_uv = set_gpu_converted_plane(width, height, input->linesize[0], + output->linesize[0], input->data[0], + output->data[0]); + set_gpu_converted_plane(width, height_d2, input->linesize[0], output->linesize[1], in_uv, output->data[1]); } @@ -731,16 +660,13 @@ static void set_gpu_converted_data(struct video_frame *output, const uint32_t width = info->width; const uint32_t height = info->height; - set_gpu_converted_plane(width, height, input->linesize[0], - output->linesize[0], input->data[0], + set_gpu_converted_plane(width, height, input->linesize[0], output->linesize[0], input->data[0], output->data[0]); - set_gpu_converted_plane(width, height, input->linesize[1], - output->linesize[1], input->data[1], + set_gpu_converted_plane(width, height, input->linesize[1], output->linesize[1], input->data[1], output->data[1]); - set_gpu_converted_plane(width, height, input->linesize[2], - output->linesize[2], input->data[2], + set_gpu_converted_plane(width, height, input->linesize[2], output->linesize[2], input->data[2], output->data[2]); break; @@ -749,18 +675,15 @@ static void set_gpu_converted_data(struct video_frame *output, const uint32_t width = info->width; const uint32_t height = info->height; - set_gpu_converted_plane(width * 2, height, input->linesize[0], - output->linesize[0], input->data[0], + set_gpu_converted_plane(width * 2, height, input->linesize[0], output->linesize[0], input->data[0], output->data[0]); const uint32_t height_d2 = height / 2; - set_gpu_converted_plane(width, height_d2, input->linesize[1], - output->linesize[1], input->data[1], + set_gpu_converted_plane(width, height_d2, input->linesize[1], output->linesize[1], input->data[1], output->data[1]); - set_gpu_converted_plane(width, height_d2, input->linesize[2], - output->linesize[2], input->data[2], + set_gpu_converted_plane(width, height_d2, input->linesize[2], output->linesize[2], input->data[2], output->data[2]); break; @@ -770,24 +693,15 @@ static void set_gpu_converted_data(struct video_frame *output, const uint32_t height = info->height; const uint32_t height_d2 = height / 2; if (input->linesize[1]) { - set_gpu_converted_plane(width_x2, height, - input->linesize[0], - output->linesize[0], - input->data[0], - output->data[0]); - set_gpu_converted_plane(width_x2, height_d2, - input->linesize[1], - output->linesize[1], - input->data[1], - output->data[1]); + set_gpu_converted_plane(width_x2, height, input->linesize[0], output->linesize[0], + input->data[0], output->data[0]); + set_gpu_converted_plane(width_x2, height_d2, input->linesize[1], output->linesize[1], + input->data[1], output->data[1]); } else { - const uint8_t *const in_uv = set_gpu_converted_plane( - width_x2, height, input->linesize[0], - output->linesize[0], input->data[0], - output->data[0]); - set_gpu_converted_plane(width_x2, height_d2, - input->linesize[0], - output->linesize[1], in_uv, + const uint8_t *const in_uv = set_gpu_converted_plane(width_x2, height, input->linesize[0], + output->linesize[0], input->data[0], + output->data[0]); + set_gpu_converted_plane(width_x2, height_d2, input->linesize[0], output->linesize[1], in_uv, output->data[1]); } @@ -797,12 +711,10 @@ static void set_gpu_converted_data(struct video_frame *output, const uint32_t width_x2 = info->width * 2; const uint32_t height = info->height; - set_gpu_converted_plane(width_x2, height, input->linesize[0], - output->linesize[0], input->data[0], + set_gpu_converted_plane(width_x2, height, input->linesize[0], output->linesize[0], input->data[0], output->data[0]); - set_gpu_converted_plane(width_x2, height, input->linesize[1], - output->linesize[1], input->data[1], + set_gpu_converted_plane(width_x2, height, input->linesize[1], output->linesize[1], input->data[1], output->data[1]); break; @@ -810,12 +722,10 @@ static void set_gpu_converted_data(struct video_frame *output, case VIDEO_FORMAT_P416: { const uint32_t height = info->height; - set_gpu_converted_plane(info->width * 2, height, - input->linesize[0], output->linesize[0], + set_gpu_converted_plane(info->width * 2, height, input->linesize[0], output->linesize[0], input->data[0], output->data[0]); - set_gpu_converted_plane(info->width * 4, height, - input->linesize[1], output->linesize[1], + set_gpu_converted_plane(info->width * 4, height, input->linesize[1], output->linesize[1], input->data[1], output->data[1]); break; @@ -845,8 +755,7 @@ static void set_gpu_converted_data(struct video_frame *output, } } -static inline void copy_rgbx_frame(struct video_frame *output, - const struct video_data *input, +static inline void copy_rgbx_frame(struct video_frame *output, const struct video_data *input, const struct video_output_info *info) { uint8_t *in_ptr = input->data[0]; @@ -854,8 +763,7 @@ static inline void copy_rgbx_frame(struct video_frame *output, /* if the line sizes match, do a single copy */ if (input->linesize[0] == output->linesize[0]) { - memcpy(out_ptr, in_ptr, - (size_t)input->linesize[0] * (size_t)info->height); + memcpy(out_ptr, in_ptr, (size_t)input->linesize[0] * (size_t)info->height); } else { const size_t copy_size = (size_t)info->width * 4; for (size_t y = 0; y < info->height; y++) { @@ -866,8 +774,7 @@ static inline void copy_rgbx_frame(struct video_frame *output, } } -static inline void output_video_data(struct obs_core_video_mix *video, - struct video_data *input_frame, int count) +static inline void output_video_data(struct obs_core_video_mix *video, struct video_data *input_frame, int count) { const struct video_output_info *info; struct video_frame output_frame; @@ -875,12 +782,10 @@ static inline void output_video_data(struct obs_core_video_mix *video, info = video_output_get_info(video->video); - locked = video_output_lock_frame(video->video, &output_frame, count, - input_frame->timestamp); + locked = video_output_lock_frame(video->video, &output_frame, count, input_frame->timestamp); if (locked) { if (video->gpu_conversion) { - set_gpu_converted_data(&output_frame, input_frame, - info); + set_gpu_converted_data(&output_frame, input_frame, info); } else { copy_rgbx_frame(&output_frame, input_frame, info); } @@ -897,8 +802,7 @@ void add_ready_encoder_group(obs_encoder_t *encoder) pthread_mutex_unlock(&obs->video.encoder_group_mutex); } -static inline void video_sleep(struct obs_core_video *video, uint64_t *p_time, - uint64_t interval_ns) +static inline void video_sleep(struct obs_core_video *video, uint64_t *p_time, uint64_t interval_ns) { struct obs_vframe_info vframe_info; uint64_t cur_time = *p_time; @@ -912,9 +816,7 @@ static inline void video_sleep(struct obs_core_video *video, uint64_t *p_time, const uint64_t udiff = os_gettime_ns() - cur_time; int64_t diff; memcpy(&diff, &udiff, sizeof(diff)); - const uint64_t clamped_diff = (diff > (int64_t)interval_ns) - ? (uint64_t)diff - : interval_ns; + const uint64_t clamped_diff = (diff > (int64_t)interval_ns) ? (uint64_t)diff : interval_ns; count = (int)(clamped_diff / interval_ns); *p_time = cur_time + interval_ns * count; } @@ -927,19 +829,15 @@ static inline void video_sleep(struct obs_core_video *video, uint64_t *p_time, pthread_mutex_lock(&video->encoder_group_mutex); for (size_t i = 0; i < video->ready_encoder_groups.num; i++) { - obs_encoder_t *encoder = obs_weak_encoder_get_encoder( - video->ready_encoder_groups.array[i]); + obs_encoder_t *encoder = obs_weak_encoder_get_encoder(video->ready_encoder_groups.array[i]); obs_weak_encoder_release(video->ready_encoder_groups.array[i]); if (!encoder) continue; if (encoder->encoder_group) { - struct obs_encoder_group *group = - encoder->encoder_group; + struct obs_encoder_group *group = encoder->encoder_group; pthread_mutex_lock(&group->mutex); - if (group->num_encoders_started >= - group->encoders.num && - !group->start_timestamp) + if (group->num_encoders_started >= group->encoders.num && !group->start_timestamp) group->start_timestamp = *p_time; pthread_mutex_unlock(&group->mutex); } @@ -955,11 +853,9 @@ static inline void video_sleep(struct obs_core_video *video, uint64_t *p_time, bool gpu_active = video->gpu_was_active; if (raw_active) - deque_push_back(&video->vframe_info_buffer, - &vframe_info, sizeof(vframe_info)); + deque_push_back(&video->vframe_info_buffer, &vframe_info, sizeof(vframe_info)); if (gpu_active) - deque_push_back(&video->vframe_info_buffer_gpu, - &vframe_info, sizeof(vframe_info)); + deque_push_back(&video->vframe_info_buffer_gpu, &vframe_info, sizeof(vframe_info)); } pthread_mutex_unlock(&obs->video.mixes_mutex); } @@ -975,8 +871,7 @@ static inline void output_frame(struct obs_core_video_mix *video) const bool gpu_active = video->gpu_was_active; int cur_texture = video->cur_texture; - int prev_texture = cur_texture == 0 ? NUM_TEXTURES - 1 - : cur_texture - 1; + int prev_texture = cur_texture == 0 ? NUM_TEXTURES - 1 : cur_texture - 1; struct video_data frame; bool frame_ready = 0; @@ -986,8 +881,7 @@ static inline void output_frame(struct obs_core_video_mix *video) gs_enter_context(obs->video.graphics); profile_start(output_frame_render_video_name); - GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_RENDER_VIDEO, - output_frame_render_video_name); + GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_RENDER_VIDEO, output_frame_render_video_name); render_video(video, raw_active, gpu_active, cur_texture); GS_DEBUG_MARKER_END(); profile_end(output_frame_render_video_name); @@ -1007,8 +901,7 @@ static inline void output_frame(struct obs_core_video_mix *video) if (raw_active && frame_ready) { struct obs_vframe_info vframe_info; - deque_pop_front(&video->vframe_info_buffer, &vframe_info, - sizeof(vframe_info)); + deque_pop_front(&video->vframe_info_buffer, &vframe_info, sizeof(vframe_info)); frame.timestamp = vframe_info.timestamp; profile_start(output_frame_output_video_data_name); @@ -1101,8 +994,7 @@ struct winrt_exports { } \ } while (false) -static bool load_winrt_imports(struct winrt_exports *exports, void *module, - const char *module_name) +static bool load_winrt_imports(struct winrt_exports *exports, void *module, const char *module_name) { bool success = true; @@ -1128,9 +1020,7 @@ static void init_winrt_state(struct winrt_state *winrt) static const char *const module_name = "libobs-winrt"; winrt->winrt_module = os_dlopen(module_name); - winrt->loaded = winrt->winrt_module && - load_winrt_imports(&winrt->exports, winrt->winrt_module, - module_name); + winrt->loaded = winrt->winrt_module && load_winrt_imports(&winrt->exports, winrt->winrt_module, module_name); winrt->dispatcher = NULL; if (winrt->loaded) { winrt->exports.winrt_initialize(); @@ -1148,8 +1038,7 @@ static void uninit_winrt_state(struct winrt_state *winrt) if (winrt->loaded) { winrt->exports.winrt_capture_thread_stop(); if (winrt->dispatcher) - winrt->exports.winrt_dispatcher_free( - winrt->dispatcher); + winrt->exports.winrt_dispatcher_free(winrt->dispatcher); winrt->exports.winrt_uninitialize(); } @@ -1169,8 +1058,7 @@ static inline void update_active_state(struct obs_core_video_mix *video) const bool was_active = video->was_active; bool raw_active = os_atomic_load_long(&video->raw_active) > 0; - const bool gpu_active = - os_atomic_load_long(&video->gpu_encoder_active) > 0; + const bool gpu_active = os_atomic_load_long(&video->gpu_encoder_active) > 0; const bool active = raw_active || gpu_active; if (!was_active && active) @@ -1221,8 +1109,7 @@ bool obs_graphics_thread_loop(struct obs_graphics_context *context) gs_leave_context(); profile_start(tick_sources_name); - context->last_time = - tick_sources(obs->video.video_time, context->last_time); + context->last_time = tick_sources(obs->video.video_time, context->last_time); profile_end(tick_sources_name); #ifdef _WIN32 @@ -1260,11 +1147,8 @@ bool obs_graphics_thread_loop(struct obs_graphics_context *context) if (context->fps_total_ns >= 1000000000ULL) { obs->video.video_fps = - (double)context->fps_total_frames / - ((double)context->fps_total_ns / 1000000000.0); - obs->video.video_avg_frame_time_ns = - context->frame_time_total_ns / - (uint64_t)context->fps_total_frames; + (double)context->fps_total_frames / ((double)context->fps_total_ns / 1000000000.0); + obs->video.video_avg_frame_time_ns = context->frame_time_total_ns / (uint64_t)context->fps_total_frames; context->frame_time_total_ns = 0; context->fps_total_ns = 0; @@ -1289,9 +1173,8 @@ void *obs_graphics_thread(void *param) os_set_thread_name("libobs: graphics thread"); - const char *video_thread_name = profile_store_name( - obs_get_profiler_name_store(), - "obs_graphics_thread(%g" NBSP "ms)", interval / 1000000.); + const char *video_thread_name = profile_store_name(obs_get_profiler_name_store(), + "obs_graphics_thread(%g" NBSP "ms)", interval / 1000000.); profile_register_root(video_thread_name, interval); srand((unsigned int)time(NULL)); diff --git a/libobs/obs-view.c b/libobs/obs-view.c index 4437ac8ab..fd97e2636 100644 --- a/libobs/obs-view.c +++ b/libobs/obs-view.c @@ -87,8 +87,7 @@ obs_source_t *obs_view_get_source(obs_view_t *view, uint32_t channel) return source; } -void obs_view_set_source(obs_view_t *view, uint32_t channel, - obs_source_t *source) +void obs_view_set_source(obs_view_t *view, uint32_t channel, obs_source_t *source) { struct obs_source *prev_source; @@ -219,10 +218,7 @@ bool obs_view_get_video_info(obs_view_t *view, struct obs_video_info *ovi) return false; } -void obs_view_enum_video_info(obs_view_t *view, - bool (*enum_proc)(void *, - struct obs_video_info *), - void *param) +void obs_view_enum_video_info(obs_view_t *view, bool (*enum_proc)(void *, struct obs_video_info *), void *param) { pthread_mutex_lock(&obs->video.mixes_mutex); diff --git a/libobs/obs-win-crash-handler.c b/libobs/obs-win-crash-handler.c index 57172c830..649b0ca96 100644 --- a/libobs/obs-win-crash-handler.c +++ b/libobs/obs-win-crash-handler.c @@ -27,44 +27,33 @@ #include "util/platform.h" #include "util/windows/win-version.h" -typedef BOOL(WINAPI *ENUMERATELOADEDMODULES64)( - HANDLE process, - PENUMLOADED_MODULES_CALLBACK64 enum_loaded_modules_callback, - PVOID user_context); +typedef BOOL(WINAPI *ENUMERATELOADEDMODULES64)(HANDLE process, + PENUMLOADED_MODULES_CALLBACK64 enum_loaded_modules_callback, + PVOID user_context); typedef DWORD(WINAPI *SYMSETOPTIONS)(DWORD sym_options); -typedef BOOL(WINAPI *SYMINITIALIZE)(HANDLE process, PCTSTR user_search_path, - BOOL invade_process); +typedef BOOL(WINAPI *SYMINITIALIZE)(HANDLE process, PCTSTR user_search_path, BOOL invade_process); typedef BOOL(WINAPI *SYMCLEANUP)(HANDLE process); -typedef BOOL(WINAPI *STACKWALK64)( - DWORD machine_type, HANDLE process, HANDLE thread, - LPSTACKFRAME64 stack_frame, PVOID context_record, - PREAD_PROCESS_MEMORY_ROUTINE64 read_memory_routine, - PFUNCTION_TABLE_ACCESS_ROUTINE64 function_table_access_routine, - PGET_MODULE_BASE_ROUTINE64 get_module_base_routine, - PTRANSLATE_ADDRESS_ROUTINE64 translate_address); +typedef BOOL(WINAPI *STACKWALK64)(DWORD machine_type, HANDLE process, HANDLE thread, LPSTACKFRAME64 stack_frame, + PVOID context_record, PREAD_PROCESS_MEMORY_ROUTINE64 read_memory_routine, + PFUNCTION_TABLE_ACCESS_ROUTINE64 function_table_access_routine, + PGET_MODULE_BASE_ROUTINE64 get_module_base_routine, + PTRANSLATE_ADDRESS_ROUTINE64 translate_address); typedef BOOL(WINAPI *SYMREFRESHMODULELIST)(HANDLE process); -typedef PVOID(WINAPI *SYMFUNCTIONTABLEACCESS64)(HANDLE process, - DWORD64 addr_base); +typedef PVOID(WINAPI *SYMFUNCTIONTABLEACCESS64)(HANDLE process, DWORD64 addr_base); typedef DWORD64(WINAPI *SYMGETMODULEBASE64)(HANDLE process, DWORD64 addr); -typedef BOOL(WINAPI *SYMFROMADDR)(HANDLE process, DWORD64 address, - PDWORD64 displacement, PSYMBOL_INFOW symbol); -typedef BOOL(WINAPI *SYMGETMODULEINFO64)(HANDLE process, DWORD64 addr, - PIMAGEHLP_MODULE64 module_info); +typedef BOOL(WINAPI *SYMFROMADDR)(HANDLE process, DWORD64 address, PDWORD64 displacement, PSYMBOL_INFOW symbol); +typedef BOOL(WINAPI *SYMGETMODULEINFO64)(HANDLE process, DWORD64 addr, PIMAGEHLP_MODULE64 module_info); -typedef DWORD64(WINAPI *SYMLOADMODULE64)(HANDLE process, HANDLE file, - PSTR image_name, PSTR module_name, - DWORD64 base_of_dll, - DWORD size_of_dll); +typedef DWORD64(WINAPI *SYMLOADMODULE64)(HANDLE process, HANDLE file, PSTR image_name, PSTR module_name, + DWORD64 base_of_dll, DWORD size_of_dll); -typedef BOOL(WINAPI *MINIDUMPWRITEDUMP)( - HANDLE process, DWORD process_id, HANDLE file, MINIDUMP_TYPE dump_type, - PMINIDUMP_EXCEPTION_INFORMATION exception_param, - PMINIDUMP_USER_STREAM_INFORMATION user_stream_param, - PMINIDUMP_CALLBACK_INFORMATION callback_param); +typedef BOOL(WINAPI *MINIDUMPWRITEDUMP)(HANDLE process, DWORD process_id, HANDLE file, MINIDUMP_TYPE dump_type, + PMINIDUMP_EXCEPTION_INFORMATION exception_param, + PMINIDUMP_USER_STREAM_INFORMATION user_stream_param, + PMINIDUMP_CALLBACK_INFORMATION callback_param); -typedef HINSTANCE(WINAPI *SHELLEXECUTEA)(HWND hwnd, LPCTSTR operation, - LPCTSTR file, LPCTSTR parameters, +typedef HINSTANCE(WINAPI *SHELLEXECUTEA)(HWND hwnd, LPCTSTR operation, LPCTSTR file, LPCTSTR parameters, LPCTSTR directory, INT show_flags); typedef HRESULT(WINAPI *GETTHREADDESCRIPTION)(HANDLE thread, PWSTR *desc); @@ -104,8 +93,7 @@ struct exception_handler_data { struct dstr module_list; }; -static inline void -exception_handler_data_free(struct exception_handler_data *data) +static inline void exception_handler_data_free(struct exception_handler_data *data) { LocalFree(data->sym_info); dstr_free(&data->str); @@ -136,15 +124,13 @@ static inline bool get_dbghelp_imports(struct exception_handler_data *data) GET_DBGHELP_IMPORT(sym_initialize, "SymInitialize"); GET_DBGHELP_IMPORT(sym_cleanup, "SymCleanup"); GET_DBGHELP_IMPORT(sym_set_options, "SymSetOptions"); - GET_DBGHELP_IMPORT(sym_function_table_access64, - "SymFunctionTableAccess64"); + GET_DBGHELP_IMPORT(sym_function_table_access64, "SymFunctionTableAccess64"); GET_DBGHELP_IMPORT(sym_get_module_base64, "SymGetModuleBase64"); GET_DBGHELP_IMPORT(sym_from_addr, "SymFromAddrW"); GET_DBGHELP_IMPORT(sym_get_module_info64, "SymGetModuleInfo64"); GET_DBGHELP_IMPORT(sym_refresh_module_list, "SymRefreshModuleList"); GET_DBGHELP_IMPORT(stack_walk64, "StackWalk64"); - GET_DBGHELP_IMPORT(enumerate_loaded_modules64, - "EnumerateLoadedModulesW64"); + GET_DBGHELP_IMPORT(enumerate_loaded_modules64, "EnumerateLoadedModulesW64"); GET_DBGHELP_IMPORT(minidump_write_dump, "MiniDumpWriteDump"); return true; @@ -175,8 +161,7 @@ extern bool sym_initialize_called; static inline void init_sym_info(struct exception_handler_data *data) { - data->sym_set_options(SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | - SYMOPT_LOAD_ANYTHING); + data->sym_set_options(SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_LOAD_ANYTHING); if (!sym_initialize_called) data->sym_initialize(data->process, NULL, true); @@ -208,8 +193,7 @@ static inline void init_cpu_info(struct exception_handler_data *data) wchar_t str[1024]; DWORD size = 1024; - status = RegQueryValueExW(key, L"ProcessorNameString", NULL, - NULL, (LPBYTE)str, &size); + status = RegQueryValueExW(key, L"ProcessorNameString", NULL, NULL, (LPBYTE)str, &size); if (status == ERROR_SUCCESS) dstr_from_wcs(&data->cpu_info, str); else @@ -219,8 +203,7 @@ static inline void init_cpu_info(struct exception_handler_data *data) } } -static BOOL CALLBACK enum_all_modules(PCTSTR module_name, DWORD64 module_base, - ULONG module_size, +static BOOL CALLBACK enum_all_modules(PCTSTR module_name, DWORD64 module_base, ULONG module_size, struct exception_handler_data *data) { char name_utf8[MAX_PATH]; @@ -234,20 +217,18 @@ static BOOL CALLBACK enum_all_modules(PCTSTR module_name, DWORD64 module_base, } #ifdef _WIN64 - dstr_catf(&data->module_list, "%016" PRIX64 "-%016" PRIX64 " %s\r\n", - module_base, module_base + module_size, name_utf8); + dstr_catf(&data->module_list, "%016" PRIX64 "-%016" PRIX64 " %s\r\n", module_base, module_base + module_size, + name_utf8); #else - dstr_catf(&data->module_list, "%08" PRIX64 "-%08" PRIX64 " %s\r\n", - module_base, module_base + module_size, name_utf8); + dstr_catf(&data->module_list, "%08" PRIX64 "-%08" PRIX64 " %s\r\n", module_base, module_base + module_size, + name_utf8); #endif return true; } static inline void init_module_info(struct exception_handler_data *data) { - data->enumerate_loaded_modules64( - data->process, (PENUMLOADED_MODULES_CALLBACK64)enum_all_modules, - data); + data->enumerate_loaded_modules64(data->process, (PENUMLOADED_MODULES_CALLBACK64)enum_all_modules, data); } extern const char *get_win_release_id(); @@ -276,11 +257,10 @@ static inline void write_header(struct exception_handler_data *data) "Windows version: %d.%d build %d (release: %s; revision: %d; " "%s-bit)\r\n" "CPU: %s\r\n\r\n", - data->exception->ExceptionRecord->ExceptionCode, date_time, - data->main_trace.instruction_ptr, data->module_name.array, - obs_bitness, data->win_version.major, data->win_version.minor, - data->win_version.build, release_id, data->win_version.revis, - is_64_bit_windows() ? "64" : "32", data->cpu_info.array); + data->exception->ExceptionRecord->ExceptionCode, date_time, data->main_trace.instruction_ptr, + data->module_name.array, obs_bitness, data->win_version.major, data->win_version.minor, + data->win_version.build, release_id, data->win_version.revis, is_64_bit_windows() ? "64" : "32", + data->cpu_info.array); } struct module_info { @@ -288,11 +268,9 @@ struct module_info { char name_utf8[MAX_PATH]; }; -static BOOL CALLBACK enum_module(PCTSTR module_name, DWORD64 module_base, - ULONG module_size, struct module_info *info) +static BOOL CALLBACK enum_module(PCTSTR module_name, DWORD64 module_base, ULONG module_size, struct module_info *info) { - if (info->addr >= module_base && - info->addr < module_base + module_size) { + if (info->addr >= module_base && info->addr < module_base + module_size) { os_wcs_to_utf8(module_name, 0, info->name_utf8, MAX_PATH); strlwr(info->name_utf8); @@ -302,27 +280,20 @@ static BOOL CALLBACK enum_module(PCTSTR module_name, DWORD64 module_base, return true; } -static inline void get_module_name(struct exception_handler_data *data, - struct module_info *info) +static inline void get_module_name(struct exception_handler_data *data, struct module_info *info) { - data->enumerate_loaded_modules64( - data->process, (PENUMLOADED_MODULES_CALLBACK64)enum_module, - info); + data->enumerate_loaded_modules64(data->process, (PENUMLOADED_MODULES_CALLBACK64)enum_module, info); } -static inline bool walk_stack(struct exception_handler_data *data, - HANDLE thread, struct stack_trace *trace) +static inline bool walk_stack(struct exception_handler_data *data, HANDLE thread, struct stack_trace *trace) { struct module_info module_info = {0}; DWORD64 func_offset; char sym_name[256]; char *p; - bool success = data->stack_walk64(trace->image_type, data->process, - thread, &trace->frame, - &trace->context, NULL, - data->sym_function_table_access64, - data->sym_get_module_base64, NULL); + bool success = data->stack_walk64(trace->image_type, data->process, thread, &trace->frame, &trace->context, + NULL, data->sym_function_table_access64, data->sym_get_module_base64, NULL); if (!success) return false; @@ -338,9 +309,8 @@ static inline bool walk_stack(struct exception_handler_data *data, } if (data->sym_info) { - success = !!data->sym_from_addr(data->process, - trace->frame.AddrPC.Offset, - &func_offset, data->sym_info); + success = + !!data->sym_from_addr(data->process, trace->frame.AddrPC.Offset, &func_offset, data->sym_info); if (success) os_wcs_to_utf8(data->sym_info->Name, 0, sym_name, 256); @@ -372,18 +342,13 @@ static inline bool walk_stack(struct exception_handler_data *data, #endif if (success && (data->sym_info->Flags & SYMFLAG_EXPORT) == 0) { - dstr_catf(&data->str, SUCCESS_FORMAT, - trace->frame.AddrStack.Offset, - trace->frame.AddrPC.Offset, trace->frame.Params[0], - trace->frame.Params[1], trace->frame.Params[2], + dstr_catf(&data->str, SUCCESS_FORMAT, trace->frame.AddrStack.Offset, trace->frame.AddrPC.Offset, + trace->frame.Params[0], trace->frame.Params[1], trace->frame.Params[2], trace->frame.Params[3], p, sym_name, func_offset); } else { - dstr_catf(&data->str, FAIL_FORMAT, - trace->frame.AddrStack.Offset, - trace->frame.AddrPC.Offset, trace->frame.Params[0], - trace->frame.Params[1], trace->frame.Params[2], - trace->frame.Params[3], p, - trace->frame.AddrPC.Offset); + dstr_catf(&data->str, FAIL_FORMAT, trace->frame.AddrStack.Offset, trace->frame.AddrPC.Offset, + trace->frame.Params[0], trace->frame.Params[1], trace->frame.Params[2], + trace->frame.Params[3], p, trace->frame.AddrPC.Offset); } return true; @@ -410,8 +375,7 @@ static inline char *get_thread_name(HANDLE thread) } HMODULE k32 = LoadLibraryW(L"kernel32.dll"); - get_thread_desc = (GETTHREADDESCRIPTION)GetProcAddress( - k32, "GetThreadDescription"); + get_thread_desc = (GETTHREADDESCRIPTION)GetProcAddress(k32, "GetThreadDescription"); if (!get_thread_desc) { failed = true; return NULL; @@ -433,8 +397,7 @@ static inline char *get_thread_name(HANDLE thread) return name.array; } -static inline void write_thread_trace(struct exception_handler_data *data, - THREADENTRY32 *entry, bool first_thread) +static inline void write_thread_trace(struct exception_handler_data *data, THREADENTRY32 *entry, bool first_thread) { bool crash_thread = entry->th32ThreadID == GetCurrentThreadId(); struct stack_trace trace = {0}; @@ -458,8 +421,7 @@ static inline void write_thread_trace(struct exception_handler_data *data, thread_name = get_thread_name(thread); - dstr_catf(&data->str, "\r\nThread %lX:%s%s\r\n" TRACE_TOP, - entry->th32ThreadID, thread_name ? thread_name : "", + dstr_catf(&data->str, "\r\nThread %lX:%s%s\r\n" TRACE_TOP, entry->th32ThreadID, thread_name ? thread_name : "", crash_thread ? " (Crashed)" : ""); bfree(thread_name); @@ -475,8 +437,7 @@ static inline void write_thread_trace(struct exception_handler_data *data, static inline void write_thread_traces(struct exception_handler_data *data) { THREADENTRY32 entry = {0}; - HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, - GetCurrentProcessId()); + HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPTHREAD, GetCurrentProcessId()); bool success; if (snapshot == INVALID_HANDLE_VALUE) @@ -512,8 +473,7 @@ static inline void write_module_list(struct exception_handler_data *data) /* ------------------------------------------------------------------------- */ -static inline void handle_exception(struct exception_handler_data *data, - PEXCEPTION_POINTERS exception) +static inline void handle_exception(struct exception_handler_data *data, PEXCEPTION_POINTERS exception) { if (!get_dbghelp_imports(data)) return; diff --git a/libobs/obs-windows.c b/libobs/obs-windows.c index 3f08795b6..90fb34305 100644 --- a/libobs/obs-windows.c +++ b/libobs/obs-windows.c @@ -38,8 +38,7 @@ static const char *module_bin[] = {"../../obs-plugins/64bit"}; static const char *module_data[] = {"../../data/obs-plugins/%module%"}; -static const int module_patterns_size = - sizeof(module_bin) / sizeof(module_bin[0]); +static const int module_patterns_size = sizeof(module_bin) / sizeof(module_bin[0]); void add_default_module_paths(void) { @@ -70,15 +69,12 @@ static void log_processor_info(void) memset(data, 0, sizeof(data)); - status = RegOpenKeyW( - HKEY_LOCAL_MACHINE, - L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key); + status = RegOpenKeyW(HKEY_LOCAL_MACHINE, L"HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0", &key); if (status != ERROR_SUCCESS) return; size = sizeof(data); - status = RegQueryValueExW(key, L"ProcessorNameString", NULL, NULL, - (LPBYTE)data, &size); + status = RegQueryValueExW(key, L"ProcessorNameString", NULL, NULL, (LPBYTE)data, &size); if (status == ERROR_SUCCESS) { os_wcs_to_utf8_ptr(data, 0, &str); blog(LOG_INFO, "CPU Name: %s", str); @@ -86,8 +82,7 @@ static void log_processor_info(void) } size = sizeof(speed); - status = RegQueryValueExW(key, L"~MHz", NULL, NULL, (LPBYTE)&speed, - &size); + status = RegQueryValueExW(key, L"~MHz", NULL, NULL, (LPBYTE)&speed, &size); if (status == ERROR_SUCCESS) blog(LOG_INFO, "CPU Speed: %ldMHz", speed); @@ -96,8 +91,7 @@ static void log_processor_info(void) static void log_processor_cores(void) { - blog(LOG_INFO, "Physical Cores: %d, Logical Cores: %d", - os_get_physical_cores(), os_get_logical_cores()); + blog(LOG_INFO, "Physical Cores: %d, Logical Cores: %d", os_get_physical_cores(), os_get_logical_cores()); } static void log_emulation_status(void) @@ -120,8 +114,7 @@ static void log_available_memory(void) const char *note = " (NOTE: 32bit programs cannot use more than 3gb)"; #endif - blog(LOG_INFO, "Physical Memory: %luMB Total, %luMB Free%s", - (DWORD)(ms.ullTotalPhys / 1048576), + blog(LOG_INFO, "Physical Memory: %luMB Total, %luMB Free%s", (DWORD)(ms.ullTotalPhys / 1048576), (DWORD)(ms.ullAvailPhys / 1048576), note); } @@ -132,13 +125,11 @@ static void log_lenovo_vantage(void) if (!manager) return; - SC_HANDLE service = - OpenService(manager, L"FBNetFilter", SERVICE_QUERY_STATUS); + SC_HANDLE service = OpenService(manager, L"FBNetFilter", SERVICE_QUERY_STATUS); if (service) { - blog(LOG_WARNING, - "Lenovo Vantage / Legion Edge is installed. The \"Network Boost\" " - "feature must be disabled when streaming with OBS."); + blog(LOG_WARNING, "Lenovo Vantage / Legion Edge is installed. The \"Network Boost\" " + "feature must be disabled when streaming with OBS."); CloseServiceHandle(service); } @@ -165,10 +156,8 @@ static void log_windows_version(void) bool arm64 = is_arm64_windows(); const char *arm64_windows = arm64 ? "ARM " : ""; - blog(LOG_INFO, - "Windows Version: %d.%d Build %d (release: %s; revision: %d; %s%s-bit)", - ver.major, ver.minor, ver.build, release_id, ver.revis, - arm64_windows, windows_bitness); + blog(LOG_INFO, "Windows Version: %d.%d Build %d (release: %s; revision: %d; %s%s-bit)", ver.major, ver.minor, + ver.build, release_id, ver.revis, arm64_windows, windows_bitness); } static void log_admin_status(void) @@ -177,9 +166,7 @@ static void log_admin_status(void) PSID admin_group; BOOL success; - success = AllocateAndInitializeSid(&auth, 2, - SECURITY_BUILTIN_DOMAIN_RID, - DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, + success = AllocateAndInitializeSid(&auth, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &admin_group); if (success) { if (!CheckTokenMembership(NULL, admin_group, &success)) @@ -187,14 +174,11 @@ static void log_admin_status(void) FreeSid(admin_group); } - blog(LOG_INFO, "Running as administrator: %s", - success ? "true" : "false"); + blog(LOG_INFO, "Running as administrator: %s", success ? "true" : "false"); } -#define WIN10_GAME_BAR_REG_KEY \ - L"Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR" -#define WIN10_GAME_DVR_POLICY_REG_KEY \ - L"SOFTWARE\\Policies\\Microsoft\\Windows\\GameDVR" +#define WIN10_GAME_BAR_REG_KEY L"Software\\Microsoft\\Windows\\CurrentVersion\\GameDVR" +#define WIN10_GAME_DVR_POLICY_REG_KEY L"SOFTWARE\\Policies\\Microsoft\\Windows\\GameDVR" #define WIN10_GAME_DVR_REG_KEY L"System\\GameConfigStore" #define WIN10_GAME_MODE_REG_KEY L"Software\\Microsoft\\GameBar" @@ -209,36 +193,27 @@ static void log_gaming_features(void) struct reg_dword game_dvr_bg_recording; struct reg_dword game_mode_enabled; - get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_BAR_REG_KEY, - L"AppCaptureEnabled", &game_bar_enabled); - get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_DVR_POLICY_REG_KEY, - L"AllowGameDVR", &game_dvr_allowed); - get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_DVR_REG_KEY, - L"GameDVR_Enabled", &game_dvr_enabled); - get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_BAR_REG_KEY, - L"HistoricalCaptureEnabled", &game_dvr_bg_recording); - get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_MODE_REG_KEY, - L"AutoGameModeEnabled", &game_mode_enabled); + get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_BAR_REG_KEY, L"AppCaptureEnabled", &game_bar_enabled); + get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_DVR_POLICY_REG_KEY, L"AllowGameDVR", &game_dvr_allowed); + get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_DVR_REG_KEY, L"GameDVR_Enabled", &game_dvr_enabled); + get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_BAR_REG_KEY, L"HistoricalCaptureEnabled", &game_dvr_bg_recording); + get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_MODE_REG_KEY, L"AutoGameModeEnabled", &game_mode_enabled); if (game_mode_enabled.status != ERROR_SUCCESS) { - get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_MODE_REG_KEY, - L"AllowAutoGameMode", &game_mode_enabled); + get_reg_dword(HKEY_CURRENT_USER, WIN10_GAME_MODE_REG_KEY, L"AllowAutoGameMode", &game_mode_enabled); } blog(LOG_INFO, "Windows 10/11 Gaming Features:"); if (game_bar_enabled.status == ERROR_SUCCESS) { - blog(LOG_INFO, "\tGame Bar: %s", - (bool)game_bar_enabled.return_value ? "On" : "Off"); + blog(LOG_INFO, "\tGame Bar: %s", (bool)game_bar_enabled.return_value ? "On" : "Off"); } if (game_dvr_allowed.status == ERROR_SUCCESS) { - blog(LOG_INFO, "\tGame DVR Allowed: %s", - (bool)game_dvr_allowed.return_value ? "Yes" : "No"); + blog(LOG_INFO, "\tGame DVR Allowed: %s", (bool)game_dvr_allowed.return_value ? "Yes" : "No"); } if (game_dvr_enabled.status == ERROR_SUCCESS) { - blog(LOG_INFO, "\tGame DVR: %s", - (bool)game_dvr_enabled.return_value ? "On" : "Off"); + blog(LOG_INFO, "\tGame DVR: %s", (bool)game_dvr_enabled.return_value ? "On" : "Off"); } if (game_dvr_bg_recording.status == ERROR_SUCCESS) { @@ -247,8 +222,7 @@ static void log_gaming_features(void) } if (game_mode_enabled.status == ERROR_SUCCESS) { - blog(LOG_INFO, "\tGame Mode: %s", - (bool)game_mode_enabled.return_value ? "On" : "Off"); + blog(LOG_INFO, "\tGame Mode: %s", (bool)game_mode_enabled.return_value ? "On" : "Off"); } else if (win_build >= 19042) { // On by default in newer Windows 10 builds (no registry key set) blog(LOG_INFO, "\tGame Mode: Probably On (no reg key set)"); @@ -322,8 +296,7 @@ static void log_security_products_by_type(IWSCProductList *prod_list, int type) char *product_name; os_wcs_to_utf8_ptr(name, 0, &product_name); - blog(LOG_INFO, "\t%s: %s (%s)", product_name, - get_str_for_state(prod_state), get_str_for_type(type)); + blog(LOG_INFO, "\t%s: %s (%s)", product_name, get_str_for_state(prod_state), get_str_for_type(type)); bfree(product_name); @@ -347,36 +320,25 @@ static void log_security_products(void) if (!h_wsc) return; - const CLSID *prod_list_clsid = - (const CLSID *)GetProcAddress(h_wsc, "CLSID_WSCProductList"); - const IID *prod_list_iid = - (const IID *)GetProcAddress(h_wsc, "IID_IWSCProductList"); + const CLSID *prod_list_clsid = (const CLSID *)GetProcAddress(h_wsc, "CLSID_WSCProductList"); + const IID *prod_list_iid = (const IID *)GetProcAddress(h_wsc, "IID_IWSCProductList"); if (prod_list_clsid && prod_list_iid) { blog(LOG_INFO, "Sec. Software Status:"); - hr = CoCreateInstance(prod_list_clsid, NULL, - CLSCTX_INPROC_SERVER, prod_list_iid, - &prod_list); + hr = CoCreateInstance(prod_list_clsid, NULL, CLSCTX_INPROC_SERVER, prod_list_iid, &prod_list); if (!FAILED(hr)) { - log_security_products_by_type( - prod_list, WSC_SECURITY_PROVIDER_ANTIVIRUS); + log_security_products_by_type(prod_list, WSC_SECURITY_PROVIDER_ANTIVIRUS); } - hr = CoCreateInstance(prod_list_clsid, NULL, - CLSCTX_INPROC_SERVER, prod_list_iid, - &prod_list); + hr = CoCreateInstance(prod_list_clsid, NULL, CLSCTX_INPROC_SERVER, prod_list_iid, &prod_list); if (!FAILED(hr)) { - log_security_products_by_type( - prod_list, WSC_SECURITY_PROVIDER_FIREWALL); + log_security_products_by_type(prod_list, WSC_SECURITY_PROVIDER_FIREWALL); } - hr = CoCreateInstance(prod_list_clsid, NULL, - CLSCTX_INPROC_SERVER, prod_list_iid, - &prod_list); + hr = CoCreateInstance(prod_list_clsid, NULL, CLSCTX_INPROC_SERVER, prod_list_iid, &prod_list); if (!FAILED(hr)) { - log_security_products_by_type( - prod_list, WSC_SECURITY_PROVIDER_ANTISPYWARE); + log_security_products_by_type(prod_list, WSC_SECURITY_PROVIDER_ANTISPYWARE); } } @@ -1029,8 +991,7 @@ static bool vk_down(DWORD vk) return down; } -bool obs_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, - obs_key_t key) +bool obs_hotkeys_platform_is_pressed(obs_hotkeys_platform_t *context, obs_key_t key) { if (key == OBS_KEY_META) { return vk_down(VK_LWIN) || vk_down(VK_RWIN); @@ -1056,8 +1017,7 @@ void obs_key_to_str(obs_key_t key, struct dstr *str) if (obs->hotkeys.translations[key]) { dstr_copy(str, obs->hotkeys.translations[key]); } else { - dstr_printf(str, "Mouse %d", - (int)(key - OBS_KEY_MOUSE1 + 1)); + dstr_printf(str, "Mouse %d", (int)(key - OBS_KEY_MOUSE1 + 1)); } return; } @@ -1088,8 +1048,8 @@ void obs_key_to_str(obs_key_t key, struct dstr *str) scan_code |= 0x01000000; } - if ((key < OBS_KEY_VK_CANCEL || key > OBS_KEY_VK_OEM_CLEAR) && - scan_code != 0 && GetKeyNameTextW(scan_code, name, 128) != 0) { + if ((key < OBS_KEY_VK_CANCEL || key > OBS_KEY_VK_OEM_CLEAR) && scan_code != 0 && + GetKeyNameTextW(scan_code, name, 128) != 0) { dstr_from_wcs(str, name); } else if (key != OBS_KEY_NONE) { dstr_copy(str, obs_key_to_name(key)); @@ -1133,8 +1093,7 @@ static inline void add_combo_key(obs_key_t key, struct dstr *str) dstr_free(&key_str); } -void obs_key_combination_to_str(obs_key_combination_t combination, - struct dstr *str) +void obs_key_combination_to_str(obs_key_combination_t combination, struct dstr *str) { if ((combination.modifiers & INTERACT_CONTROL_KEY) != 0) { add_combo_key(OBS_KEY_CONTROL, str); @@ -1178,10 +1137,8 @@ void reset_win32_symbol_paths(void) if (!mod) return; - sym_initialize_w = - (void *)GetProcAddress(mod, "SymInitializeW"); - sym_set_search_path_w = - (void *)GetProcAddress(mod, "SymSetSearchPathW"); + sym_initialize_w = (void *)GetProcAddress(mod, "SymInitializeW"); + sym_set_search_path_w = (void *)GetProcAddress(mod, "SymSetSearchPathW"); if (!sym_initialize_w || !sym_set_search_path_w) { FreeLibrary(mod); return; @@ -1250,12 +1207,10 @@ void reset_win32_symbol_paths(void) os_utf8_to_wcs_ptr(path_str.array, path_str.len, &path_str_w); if (path_str_w) { if (!sym_initialize_called) { - sym_initialize_w(GetCurrentProcess(), - path_str_w, false); + sym_initialize_w(GetCurrentProcess(), path_str_w, false); sym_initialize_called = true; } else { - sym_set_search_path_w(GetCurrentProcess(), - path_str_w); + sym_set_search_path_w(GetCurrentProcess(), path_str_w); } bfree(path_str_w); diff --git a/libobs/obs.c b/libobs/obs.c index 4f000ac7a..845c9d49b 100644 --- a/libobs/obs.c +++ b/libobs/obs.c @@ -30,8 +30,7 @@ static THREAD_LOCAL bool is_ui_thread = false; extern void add_default_module_paths(void); extern char *find_libobs_data_file(const char *file); -static inline void make_video_info(struct video_output_info *vi, - struct obs_video_info *ovi) +static inline void make_video_info(struct video_output_info *vi, struct obs_video_info *ovi) { vi->name = "video"; vi->format = ovi->output_format; @@ -46,8 +45,7 @@ static inline void make_video_info(struct video_output_info *vi, static inline void calc_gpu_conversion_sizes(struct obs_core_video_mix *video) { - const struct video_output_info *info = - video_output_get_info(video->video); + const struct video_output_info *info = video_output_get_info(video->video); video->conversion_needed = false; video->conversion_techs[0] = NULL; @@ -146,19 +144,15 @@ static inline void calc_gpu_conversion_sizes(struct obs_core_video_mix *video) static bool obs_init_gpu_conversion(struct obs_core_video_mix *video) { - const struct video_output_info *info = - video_output_get_info(video->video); + const struct video_output_info *info = video_output_get_info(video->video); calc_gpu_conversion_sizes(video); - video->using_nv12_tex = - info->format == VIDEO_FORMAT_NV12 ? gs_nv12_available() : false; - video->using_p010_tex = - info->format == VIDEO_FORMAT_P010 ? gs_p010_available() : false; + video->using_nv12_tex = info->format == VIDEO_FORMAT_NV12 ? gs_nv12_available() : false; + video->using_p010_tex = info->format == VIDEO_FORMAT_P010 ? gs_p010_available() : false; if (!video->conversion_needed) { - blog(LOG_INFO, "GPU conversion not available for format: %u", - (unsigned int)info->format); + blog(LOG_INFO, "GPU conversion not available for format: %u", (unsigned int)info->format); video->gpu_conversion = false; video->using_nv12_tex = false; video->using_p010_tex = false; @@ -183,19 +177,13 @@ static bool obs_init_gpu_conversion(struct obs_core_video_mix *video) video->convert_textures_encode[1] = NULL; video->convert_textures_encode[2] = NULL; if (video->using_nv12_tex) { - if (!gs_texture_create_nv12(&video->convert_textures_encode[0], - &video->convert_textures_encode[1], - info->width, info->height, - GS_RENDER_TARGET | - GS_SHARED_KM_TEX)) { + if (!gs_texture_create_nv12(&video->convert_textures_encode[0], &video->convert_textures_encode[1], + info->width, info->height, GS_RENDER_TARGET | GS_SHARED_KM_TEX)) { return false; } } else if (video->using_p010_tex) { - if (!gs_texture_create_p010(&video->convert_textures_encode[0], - &video->convert_textures_encode[1], - info->width, info->height, - GS_RENDER_TARGET | - GS_SHARED_KM_TEX)) { + if (!gs_texture_create_p010(&video->convert_textures_encode[0], &video->convert_textures_encode[1], + info->width, info->height, GS_RENDER_TARGET | GS_SHARED_KM_TEX)) { return false; } } @@ -205,83 +193,63 @@ static bool obs_init_gpu_conversion(struct obs_core_video_mix *video) switch (info->format) { case VIDEO_FORMAT_I420: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R8, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R8, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width / 2, info->height / 2, - GS_R8, 1, NULL, GS_RENDER_TARGET); + gs_texture_create(info->width / 2, info->height / 2, GS_R8, 1, NULL, GS_RENDER_TARGET); video->convert_textures[2] = - gs_texture_create(info->width / 2, info->height / 2, - GS_R8, 1, NULL, GS_RENDER_TARGET); - if (!video->convert_textures[0] || - !video->convert_textures[1] || !video->convert_textures[2]) + gs_texture_create(info->width / 2, info->height / 2, GS_R8, 1, NULL, GS_RENDER_TARGET); + if (!video->convert_textures[0] || !video->convert_textures[1] || !video->convert_textures[2]) success = false; break; case VIDEO_FORMAT_NV12: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R8, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R8, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width / 2, info->height / 2, - GS_R8G8, 1, NULL, GS_RENDER_TARGET); + gs_texture_create(info->width / 2, info->height / 2, GS_R8G8, 1, NULL, GS_RENDER_TARGET); if (!video->convert_textures[0] || !video->convert_textures[1]) success = false; break; case VIDEO_FORMAT_I444: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R8, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R8, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width, info->height, GS_R8, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R8, 1, NULL, GS_RENDER_TARGET); video->convert_textures[2] = - gs_texture_create(info->width, info->height, GS_R8, 1, - NULL, GS_RENDER_TARGET); - if (!video->convert_textures[0] || - !video->convert_textures[1] || !video->convert_textures[2]) + gs_texture_create(info->width, info->height, GS_R8, 1, NULL, GS_RENDER_TARGET); + if (!video->convert_textures[0] || !video->convert_textures[1] || !video->convert_textures[2]) success = false; break; case VIDEO_FORMAT_I010: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R16, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R16, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width / 2, info->height / 2, - GS_R16, 1, NULL, GS_RENDER_TARGET); + gs_texture_create(info->width / 2, info->height / 2, GS_R16, 1, NULL, GS_RENDER_TARGET); video->convert_textures[2] = - gs_texture_create(info->width / 2, info->height / 2, - GS_R16, 1, NULL, GS_RENDER_TARGET); - if (!video->convert_textures[0] || - !video->convert_textures[1] || !video->convert_textures[2]) + gs_texture_create(info->width / 2, info->height / 2, GS_R16, 1, NULL, GS_RENDER_TARGET); + if (!video->convert_textures[0] || !video->convert_textures[1] || !video->convert_textures[2]) success = false; break; case VIDEO_FORMAT_P010: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R16, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R16, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width / 2, info->height / 2, - GS_RG16, 1, NULL, GS_RENDER_TARGET); + gs_texture_create(info->width / 2, info->height / 2, GS_RG16, 1, NULL, GS_RENDER_TARGET); if (!video->convert_textures[0] || !video->convert_textures[1]) success = false; break; case VIDEO_FORMAT_P216: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R16, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R16, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width / 2, info->height, - GS_RG16, 1, NULL, GS_RENDER_TARGET); + gs_texture_create(info->width / 2, info->height, GS_RG16, 1, NULL, GS_RENDER_TARGET); if (!video->convert_textures[0] || !video->convert_textures[1]) success = false; break; case VIDEO_FORMAT_P416: video->convert_textures[0] = - gs_texture_create(info->width, info->height, GS_R16, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_R16, 1, NULL, GS_RENDER_TARGET); video->convert_textures[1] = - gs_texture_create(info->width, info->height, GS_RG16, 1, - NULL, GS_RENDER_TARGET); + gs_texture_create(info->width, info->height, GS_RG16, 1, NULL, GS_RENDER_TARGET); if (!video->convert_textures[0] || !video->convert_textures[1]) success = false; break; @@ -296,8 +264,7 @@ static bool obs_init_gpu_conversion(struct obs_core_video_mix *video) video->convert_textures[c] = NULL; } if (video->convert_textures_encode[c]) { - gs_texture_destroy( - video->convert_textures_encode[c]); + gs_texture_destroy(video->convert_textures_encode[c]); video->convert_textures_encode[c] = NULL; } } @@ -306,91 +273,72 @@ static bool obs_init_gpu_conversion(struct obs_core_video_mix *video) return success; } -static bool obs_init_gpu_copy_surfaces(struct obs_core_video_mix *video, - size_t i) +static bool obs_init_gpu_copy_surfaces(struct obs_core_video_mix *video, size_t i) { - const struct video_output_info *info = - video_output_get_info(video->video); + const struct video_output_info *info = video_output_get_info(video->video); switch (info->format) { case VIDEO_FORMAT_I420: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R8); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R8); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width / 2, info->height / 2, GS_R8); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width / 2, info->height / 2, GS_R8); if (!video->copy_surfaces[i][1]) return false; - video->copy_surfaces[i][2] = gs_stagesurface_create( - info->width / 2, info->height / 2, GS_R8); + video->copy_surfaces[i][2] = gs_stagesurface_create(info->width / 2, info->height / 2, GS_R8); if (!video->copy_surfaces[i][2]) return false; break; case VIDEO_FORMAT_NV12: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R8); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R8); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width / 2, info->height / 2, GS_R8G8); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width / 2, info->height / 2, GS_R8G8); if (!video->copy_surfaces[i][1]) return false; break; case VIDEO_FORMAT_I444: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R8); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R8); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width, info->height, GS_R8); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width, info->height, GS_R8); if (!video->copy_surfaces[i][1]) return false; - video->copy_surfaces[i][2] = gs_stagesurface_create( - info->width, info->height, GS_R8); + video->copy_surfaces[i][2] = gs_stagesurface_create(info->width, info->height, GS_R8); if (!video->copy_surfaces[i][2]) return false; break; case VIDEO_FORMAT_I010: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R16); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R16); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width / 2, info->height / 2, GS_R16); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width / 2, info->height / 2, GS_R16); if (!video->copy_surfaces[i][1]) return false; - video->copy_surfaces[i][2] = gs_stagesurface_create( - info->width / 2, info->height / 2, GS_R16); + video->copy_surfaces[i][2] = gs_stagesurface_create(info->width / 2, info->height / 2, GS_R16); if (!video->copy_surfaces[i][2]) return false; break; case VIDEO_FORMAT_P010: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R16); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R16); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width / 2, info->height / 2, GS_RG16); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width / 2, info->height / 2, GS_RG16); if (!video->copy_surfaces[i][1]) return false; break; case VIDEO_FORMAT_P216: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R16); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R16); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width / 2, info->height, GS_RG16); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width / 2, info->height, GS_RG16); if (!video->copy_surfaces[i][1]) return false; break; case VIDEO_FORMAT_P416: - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, GS_R16); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, GS_R16); if (!video->copy_surfaces[i][0]) return false; - video->copy_surfaces[i][1] = gs_stagesurface_create( - info->width, info->height, GS_RG16); + video->copy_surfaces[i][1] = gs_stagesurface_create(info->width, info->height, GS_RG16); if (!video->copy_surfaces[i][1]) return false; break; @@ -403,8 +351,7 @@ static bool obs_init_gpu_copy_surfaces(struct obs_core_video_mix *video, static bool obs_init_textures(struct obs_core_video_mix *video) { - const struct video_output_info *info = - video_output_get_info(video->video); + const struct video_output_info *info = video_output_get_info(video->video); bool success = true; @@ -426,17 +373,13 @@ static bool obs_init_textures(struct obs_core_video_mix *video) for (size_t i = 0; i < NUM_TEXTURES; i++) { #ifdef _WIN32 if (video->using_nv12_tex) { - video->copy_surfaces_encode[i] = - gs_stagesurface_create_nv12(info->width, - info->height); + video->copy_surfaces_encode[i] = gs_stagesurface_create_nv12(info->width, info->height); if (!video->copy_surfaces_encode[i]) { success = false; break; } } else if (video->using_p010_tex) { - video->copy_surfaces_encode[i] = - gs_stagesurface_create_p010(info->width, - info->height); + video->copy_surfaces_encode[i] = gs_stagesurface_create_p010(info->width, info->height); if (!video->copy_surfaces_encode[i]) { success = false; break; @@ -450,8 +393,7 @@ static bool obs_init_textures(struct obs_core_video_mix *video) break; } } else { - video->copy_surfaces[i][0] = gs_stagesurface_create( - info->width, info->height, format); + video->copy_surfaces[i][0] = gs_stagesurface_create(info->width, info->height, format); if (!video->copy_surfaces[i][0]) { success = false; break; @@ -481,13 +423,11 @@ static bool obs_init_textures(struct obs_core_video_mix *video) } video->render_texture = - gs_texture_create(video->ovi.base_width, video->ovi.base_height, - format, 1, NULL, GS_RENDER_TARGET); + gs_texture_create(video->ovi.base_width, video->ovi.base_height, format, 1, NULL, GS_RENDER_TARGET); if (!video->render_texture) success = false; - video->output_texture = gs_texture_create( - info->width, info->height, format, 1, NULL, GS_RENDER_TARGET); + video->output_texture = gs_texture_create(info->width, info->height, format, 1, NULL, GS_RENDER_TARGET); if (!video->output_texture) success = false; @@ -497,15 +437,13 @@ static bool obs_init_textures(struct obs_core_video_mix *video) for (size_t i = 0; i < NUM_TEXTURES; i++) { for (size_t c = 0; c < NUM_CHANNELS; c++) { if (video->copy_surfaces[i][c]) { - gs_stagesurface_destroy( - video->copy_surfaces[i][c]); + gs_stagesurface_destroy(video->copy_surfaces[i][c]); video->copy_surfaces[i][c] = NULL; } } #ifdef _WIN32 if (video->copy_surfaces_encode[i]) { - gs_stagesurface_destroy( - video->copy_surfaces_encode[i]); + gs_stagesurface_destroy(video->copy_surfaces_encode[i]); video->copy_surfaces_encode[i] = NULL; } #endif @@ -549,8 +487,7 @@ static int obs_init_graphics(struct obs_video_info *ovi) profile_start(obs_init_graphics_name); - errorcode = - gs_create(&video->graphics, ovi->graphics_module, ovi->adapter); + errorcode = gs_create(&video->graphics, ovi->graphics_module, ovi->adapter); if (errorcode != GS_SUCCESS) { profile_end(obs_init_graphics_name); @@ -573,8 +510,7 @@ static int obs_init_graphics(struct obs_video_info *ovi) if (gs_get_device_type() == GS_DEVICE_OPENGL) { filename = obs_find_data_file("default_rect.effect"); - video->default_rect_effect = - gs_effect_create_from_file(filename, NULL); + video->default_rect_effect = gs_effect_create_from_file(filename, NULL); bfree(filename); } @@ -607,20 +543,17 @@ static int obs_init_graphics(struct obs_video_info *ovi) bfree(filename); filename = obs_find_data_file("bilinear_lowres_scale.effect"); - video->bilinear_lowres_effect = - gs_effect_create_from_file(filename, NULL); + video->bilinear_lowres_effect = gs_effect_create_from_file(filename, NULL); bfree(filename); filename = obs_find_data_file("premultiplied_alpha.effect"); - video->premultiplied_alpha_effect = - gs_effect_create_from_file(filename, NULL); + video->premultiplied_alpha_effect = gs_effect_create_from_file(filename, NULL); bfree(filename); point_sampler.max_anisotropy = 1; video->point_sampler = gs_samplerstate_create(&point_sampler); - obs->video.transparent_texture = - gs_texture_create(2, 2, GS_RGBA, 1, &transparent_tex, 0); + obs->video.transparent_texture = gs_texture_create(2, 2, GS_RGBA, 1, &transparent_tex, 0); if (!video->default_effect) success = false; @@ -648,16 +581,14 @@ static int obs_init_graphics(struct obs_video_info *ovi) return success ? OBS_VIDEO_SUCCESS : OBS_VIDEO_FAIL; } -static inline void set_video_matrix(struct obs_core_video_mix *video, - struct video_output_info *info) +static inline void set_video_matrix(struct obs_core_video_mix *video, struct video_output_info *info) { struct matrix4 mat; struct vec4 r_row; if (format_is_yuv(info->format)) { - video_format_get_parameters_for_format( - info->colorspace, info->range, info->format, - (float *)&mat, NULL, NULL); + video_format_get_parameters_for_format(info->colorspace, info->range, info->format, (float *)&mat, NULL, + NULL); matrix4_inv(&mat, &mat); /* swap R and G */ @@ -671,8 +602,7 @@ static inline void set_video_matrix(struct obs_core_video_mix *video, memcpy(video->color_matrix, &mat, sizeof(float) * 16); } -static int obs_init_video_mix(struct obs_video_info *ovi, - struct obs_core_video_mix *video) +static int obs_init_video_mix(struct obs_video_info *ovi, struct obs_core_video_mix *video) { struct video_output_info vi; @@ -727,8 +657,7 @@ static int obs_init_video_mix(struct obs_video_info *ovi, struct obs_core_video_mix *obs_create_video_mix(struct obs_video_info *ovi) { - struct obs_core_video_mix *video = - bzalloc(sizeof(struct obs_core_video_mix)); + struct obs_core_video_mix *video = bzalloc(sizeof(struct obs_core_video_mix)); if (obs_init_video_mix(ovi, video) != OBS_VIDEO_SUCCESS) { bfree(video); video = NULL; @@ -739,10 +668,8 @@ struct obs_core_video_mix *obs_create_video_mix(struct obs_video_info *ovi) static int obs_init_video(struct obs_video_info *ovi) { struct obs_core_video *video = &obs->video; - video->video_frame_interval_ns = - util_mul_div64(1000000000ULL, ovi->fps_den, ovi->fps_num); - video->video_half_frame_interval_ns = - util_mul_div64(500000000ULL, ovi->fps_den, ovi->fps_num); + video->video_frame_interval_ns = util_mul_div64(1000000000ULL, ovi->fps_den, ovi->fps_num); + video->video_half_frame_interval_ns = util_mul_div64(500000000ULL, ovi->fps_den, ovi->fps_num); if (pthread_mutex_init(&video->task_mutex, NULL) < 0) return OBS_VIDEO_FAIL; @@ -759,11 +686,9 @@ static int obs_init_video(struct obs_video_info *ovi) pthread_attr_t attr; pthread_attr_init(&attr); pthread_attr_set_qos_class_np(&attr, QOS_CLASS_USER_INTERACTIVE, 0); - errorcode = pthread_create(&video->video_thread, &attr, - obs_graphics_thread_autorelease, obs); + errorcode = pthread_create(&video->video_thread, &attr, obs_graphics_thread_autorelease, obs); #else - errorcode = pthread_create(&video->video_thread, NULL, - obs_graphics_thread, obs); + errorcode = pthread_create(&video->video_thread, NULL, obs_graphics_thread, obs); #endif if (errorcode != 0) return OBS_VIDEO_FAIL; @@ -806,8 +731,7 @@ static void obs_free_render_textures(struct obs_core_video_mix *video) for (size_t i = 0; i < NUM_TEXTURES; i++) { for (size_t c = 0; c < NUM_CHANNELS; c++) { if (video->copy_surfaces[i][c]) { - gs_stagesurface_destroy( - video->copy_surfaces[i][c]); + gs_stagesurface_destroy(video->copy_surfaces[i][c]); video->copy_surfaces[i][c] = NULL; } @@ -853,8 +777,7 @@ void obs_free_video_mix(struct obs_core_video_mix *video) deque_free(&video->vframe_info_buffer_gpu); video->texture_rendered = false; - memset(video->textures_copied, 0, - sizeof(video->textures_copied)); + memset(video->textures_copied, 0, sizeof(video->textures_copied)); video->texture_converted = false; pthread_mutex_destroy(&video->gpu_encoder_mutex); @@ -887,8 +810,7 @@ static void obs_free_video(void) pthread_mutex_init_value(&obs->video.mixes_mutex); for (size_t i = 0; i < obs->video.ready_encoder_groups.num; i++) { - obs_weak_encoder_release( - obs->video.ready_encoder_groups.array[i]); + obs_weak_encoder_release(obs->video.ready_encoder_groups.array[i]); } da_free(obs->video.ready_encoder_groups); @@ -1039,30 +961,27 @@ void obs_main_view_free(struct obs_view *view) pthread_mutex_destroy(&view->channels_mutex); } -#define FREE_OBS_HASH_TABLE(handle, table, type) \ - do { \ - struct obs_context_data *ctx, *tmp; \ - int unfreed = 0; \ - HASH_ITER (handle, *(struct obs_context_data **)table, ctx, \ - tmp) { \ - obs_##type##_destroy((obs_##type##_t *)ctx); \ - unfreed++; \ - } \ - if (unfreed) \ - blog(LOG_INFO, "\t%d " #type "(s) were remaining", \ - unfreed); \ +#define FREE_OBS_HASH_TABLE(handle, table, type) \ + do { \ + struct obs_context_data *ctx, *tmp; \ + int unfreed = 0; \ + HASH_ITER (handle, *(struct obs_context_data **)table, ctx, tmp) { \ + obs_##type##_destroy((obs_##type##_t *)ctx); \ + unfreed++; \ + } \ + if (unfreed) \ + blog(LOG_INFO, "\t%d " #type "(s) were remaining", unfreed); \ } while (false) -#define FREE_OBS_LINKED_LIST(type) \ - do { \ - int unfreed = 0; \ - while (data->first_##type) { \ - obs_##type##_destroy(data->first_##type); \ - unfreed++; \ - } \ - if (unfreed) \ - blog(LOG_INFO, "\t%d " #type "(s) were remaining", \ - unfreed); \ +#define FREE_OBS_LINKED_LIST(type) \ + do { \ + int unfreed = 0; \ + while (data->first_##type) { \ + obs_##type##_destroy(data->first_##type); \ + unfreed++; \ + } \ + if (unfreed) \ + blog(LOG_INFO, "\t%d " #type "(s) were remaining", unfreed); \ } while (false) static void obs_free_data(void) @@ -1177,8 +1096,7 @@ static inline bool obs_init_hotkeys(void) if (os_event_init(&hotkeys->stop_event, OS_EVENT_TYPE_MANUAL) != 0) goto fail; - if (pthread_create(&hotkeys->hotkey_thread, NULL, obs_hotkey_thread, - NULL)) + if (pthread_create(&hotkeys->hotkey_thread, NULL, obs_hotkey_thread, NULL)) goto fail; hotkeys->strict_modifiers = true; @@ -1234,15 +1152,13 @@ static const char *submix_name(void *unused) const struct obs_source_info audio_line_info = { .id = "audio_line", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_CAP_DISABLED | - OBS_SOURCE_SUBMIX, + .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_CAP_DISABLED | OBS_SOURCE_SUBMIX, .get_name = submix_name, }; extern void log_system_info(void); -static bool obs_init(const char *locale, const char *module_config_path, - profiler_name_store_t *store) +static bool obs_init(const char *locale, const char *module_config_path, profiler_name_store_t *store) { obs = bzalloc(sizeof(struct obs_core)); @@ -1306,8 +1222,7 @@ char *obs_find_data_file(const char *file) return path.array; } - blog(LOG_ERROR, "Failed to find file '%s' in libobs data directory", - file); + blog(LOG_ERROR, "Failed to find file '%s' in libobs data directory", file); dstr_free(&path); return NULL; @@ -1335,8 +1250,7 @@ bool obs_remove_data_path(const char *path) } static const char *obs_startup_name = "obs_startup"; -bool obs_startup(const char *locale, const char *module_config_path, - profiler_name_store_t *store) +bool obs_startup(const char *locale, const char *module_config_path, profiler_name_store_t *store) { bool success; @@ -1518,8 +1432,7 @@ const char *obs_get_locale(void) static inline bool size_valid(uint32_t width, uint32_t height) { - return (width >= OBS_SIZE_MIN && height >= OBS_SIZE_MIN && - width <= OBS_SIZE_MAX && height <= OBS_SIZE_MAX); + return (width >= OBS_SIZE_MIN && height >= OBS_SIZE_MIN && width <= OBS_SIZE_MAX && height <= OBS_SIZE_MAX); } int obs_reset_video(struct obs_video_info *ovi) @@ -1531,8 +1444,7 @@ int obs_reset_video(struct obs_video_info *ovi) if (obs_video_active()) return OBS_VIDEO_CURRENTLY_ACTIVE; - if (!size_valid(ovi->output_width, ovi->output_height) || - !size_valid(ovi->base_width, ovi->base_height)) + if (!size_valid(ovi->output_width, ovi->output_height) || !size_valid(ovi->base_width, ovi->base_height)) return OBS_VIDEO_INVALID_PARAM; stop_video(); @@ -1574,8 +1486,7 @@ int obs_reset_video(struct obs_video_info *ovi) bool yuv = format_is_yuv(ovi->output_format); const char *yuv_format = get_video_colorspace_name(ovi->colorspace); - const char *yuv_range = - get_video_range_name(ovi->output_format, ovi->range); + const char *yuv_range = get_video_range_name(ovi->output_format, ovi->range); blog(LOG_INFO, "---------------------------------"); blog(LOG_INFO, @@ -1586,10 +1497,9 @@ int obs_reset_video(struct obs_video_info *ovi) "\tfps: %d/%d\n" "\tformat: %s\n" "\tYUV mode: %s%s%s", - ovi->base_width, ovi->base_height, ovi->output_width, - ovi->output_height, scale_type_name, ovi->fps_num, ovi->fps_den, - get_video_format_name(ovi->output_format), - yuv ? yuv_format : "None", yuv ? "/" : "", yuv ? yuv_range : ""); + ovi->base_width, ovi->base_height, ovi->output_width, ovi->output_height, scale_type_name, ovi->fps_num, + ovi->fps_den, get_video_format_name(ovi->output_format), yuv ? yuv_format : "None", yuv ? "/" : "", + yuv ? yuv_range : ""); source_profiler_reset_video(ovi); @@ -1614,8 +1524,7 @@ bool obs_reset_audio2(const struct obs_audio_info2 *oai) return true; if (oai->max_buffering_ms) { - uint32_t max_frames = oai->max_buffering_ms * - oai->samples_per_sec / SEC_TO_MSEC; + uint32_t max_frames = oai->max_buffering_ms * oai->samples_per_sec / SEC_TO_MSEC; max_frames += (AUDIO_OUTPUT_FRAMES - 1); audio->max_buffering_ticks = max_frames / AUDIO_OUTPUT_FRAMES; } else { @@ -1623,9 +1532,8 @@ bool obs_reset_audio2(const struct obs_audio_info2 *oai) } audio->fixed_buffer = oai->fixed_buffering; - int max_buffering_ms = audio->max_buffering_ticks * - AUDIO_OUTPUT_FRAMES * SEC_TO_MSEC / - (int)oai->samples_per_sec; + int max_buffering_ms = + audio->max_buffering_ticks * AUDIO_OUTPUT_FRAMES * SEC_TO_MSEC / (int)oai->samples_per_sec; ai.name = "Audio"; ai.samples_per_sec = oai->samples_per_sec; @@ -1717,8 +1625,7 @@ bool obs_enum_input_types(size_t idx, const char **id) return true; } -bool obs_enum_input_types2(size_t idx, const char **id, - const char **unversioned_id) +bool obs_enum_input_types2(size_t idx, const char **id, const char **unversioned_id) { if (idx >= obs->input_types.num) return false; @@ -1739,8 +1646,7 @@ const char *obs_get_latest_input_type_id(const char *unversioned_id) for (size_t i = 0; i < obs->source_types.num; i++) { struct obs_source_info *info = &obs->source_types.array[i]; - if (strcmp(info->unversioned_id, unversioned_id) == 0 && - (int)info->version > version) { + if (strcmp(info->unversioned_id, unversioned_id) == 0 && (int)info->version > version) { latest = info; version = info->version; } @@ -1867,12 +1773,10 @@ void obs_enum_sources(bool (*enum_proc)(void *, obs_source_t *), void *param) while (source) { obs_source_t *s = obs_source_get_ref(source); if (s) { - if (s->info.type == OBS_SOURCE_TYPE_INPUT && - !enum_proc(param, s)) { + if (s->info.type == OBS_SOURCE_TYPE_INPUT && !enum_proc(param, s)) { obs_source_release(s); break; - } else if (strcmp(s->info.id, group_info.id) == 0 && - !enum_proc(param, s)) { + } else if (strcmp(s->info.id, group_info.id) == 0 && !enum_proc(param, s)) { obs_source_release(s); break; } @@ -1895,8 +1799,7 @@ void obs_enum_scenes(bool (*enum_proc)(void *, obs_source_t *), void *param) while (source) { obs_source_t *s = obs_source_get_ref(source); if (s) { - if (source->info.type == OBS_SOURCE_TYPE_SCENE && - !enum_proc(param, s)) { + if (source->info.type == OBS_SOURCE_TYPE_SCENE && !enum_proc(param, s)) { obs_source_release(s); break; } @@ -1909,8 +1812,7 @@ void obs_enum_scenes(bool (*enum_proc)(void *, obs_source_t *), void *param) pthread_mutex_unlock(&obs->data.sources_mutex); } -static inline void obs_enum(void *pstart, pthread_mutex_t *mutex, void *proc, - void *param) +static inline void obs_enum(void *pstart, pthread_mutex_t *mutex, void *proc, void *param) { struct obs_context_data **start = pstart, *context; bool (*enum_proc)(void *, void *) = proc; @@ -1932,8 +1834,7 @@ static inline void obs_enum(void *pstart, pthread_mutex_t *mutex, void *proc, pthread_mutex_unlock(mutex); } -static inline void obs_enum_uuid(void *pstart, pthread_mutex_t *mutex, - void *proc, void *param) +static inline void obs_enum_uuid(void *pstart, pthread_mutex_t *mutex, void *proc, void *param) { struct obs_context_data **start = pstart, *context, *tmp; bool (*enum_proc)(void *, void *) = proc; @@ -1952,34 +1853,27 @@ static inline void obs_enum_uuid(void *pstart, pthread_mutex_t *mutex, pthread_mutex_unlock(mutex); } -void obs_enum_all_sources(bool (*enum_proc)(void *, obs_source_t *), - void *param) +void obs_enum_all_sources(bool (*enum_proc)(void *, obs_source_t *), void *param) { - obs_enum_uuid(&obs->data.sources, &obs->data.sources_mutex, enum_proc, - param); + obs_enum_uuid(&obs->data.sources, &obs->data.sources_mutex, enum_proc, param); } void obs_enum_outputs(bool (*enum_proc)(void *, obs_output_t *), void *param) { - obs_enum(&obs->data.first_output, &obs->data.outputs_mutex, enum_proc, - param); + obs_enum(&obs->data.first_output, &obs->data.outputs_mutex, enum_proc, param); } void obs_enum_encoders(bool (*enum_proc)(void *, obs_encoder_t *), void *param) { - obs_enum(&obs->data.first_encoder, &obs->data.encoders_mutex, enum_proc, - param); + obs_enum(&obs->data.first_encoder, &obs->data.encoders_mutex, enum_proc, param); } void obs_enum_services(bool (*enum_proc)(void *, obs_service_t *), void *param) { - obs_enum(&obs->data.first_service, &obs->data.services_mutex, enum_proc, - param); + obs_enum(&obs->data.first_service, &obs->data.services_mutex, enum_proc, param); } -static inline void *get_context_by_name(void *vfirst, const char *name, - pthread_mutex_t *mutex, - void *(*addref)(void *)) +static inline void *get_context_by_name(void *vfirst, const char *name, pthread_mutex_t *mutex, void *(*addref)(void *)) { struct obs_context_data **first = vfirst; struct obs_context_data *context; @@ -1992,8 +1886,7 @@ static inline void *get_context_by_name(void *vfirst, const char *name, } else { context = *first; while (context) { - if (!context->private && - strcmp(context->name, name) == 0) { + if (!context->private && strcmp(context->name, name) == 0) { break; } @@ -2008,9 +1901,7 @@ static inline void *get_context_by_name(void *vfirst, const char *name, return context; } -static void *get_context_by_uuid(void *ptable, const char *uuid, - pthread_mutex_t *mutex, - void *(*addref)(void *)) +static void *get_context_by_uuid(void *ptable, const char *uuid, pthread_mutex_t *mutex, void *(*addref)(void *)) { struct obs_context_data **ht = ptable; struct obs_context_data *context; @@ -2047,16 +1938,12 @@ static inline void *obs_service_addref_safe_(void *ref) obs_source_t *obs_get_source_by_name(const char *name) { - return get_context_by_name(&obs->data.public_sources, name, - &obs->data.sources_mutex, - obs_source_addref_safe_); + return get_context_by_name(&obs->data.public_sources, name, &obs->data.sources_mutex, obs_source_addref_safe_); } obs_source_t *obs_get_source_by_uuid(const char *uuid) { - return get_context_by_uuid(&obs->data.sources, uuid, - &obs->data.sources_mutex, - obs_source_addref_safe_); + return get_context_by_uuid(&obs->data.sources, uuid, &obs->data.sources_mutex, obs_source_addref_safe_); } obs_source_t *obs_get_transition_by_name(const char *name) @@ -2070,8 +1957,7 @@ obs_source_t *obs_get_transition_by_name(const char *name) * can't look them up by name in the public_sources hash table. */ source = *first; while (source) { - if (source->info.type == OBS_SOURCE_TYPE_TRANSITION && - strcmp(source->context.name, name) == 0) { + if (source->info.type == OBS_SOURCE_TYPE_TRANSITION && strcmp(source->context.name, name) == 0) { source = obs_source_addref_safe_(source); break; } @@ -2096,23 +1982,17 @@ obs_source_t *obs_get_transition_by_uuid(const char *uuid) obs_output_t *obs_get_output_by_name(const char *name) { - return get_context_by_name(&obs->data.first_output, name, - &obs->data.outputs_mutex, - obs_output_addref_safe_); + return get_context_by_name(&obs->data.first_output, name, &obs->data.outputs_mutex, obs_output_addref_safe_); } obs_encoder_t *obs_get_encoder_by_name(const char *name) { - return get_context_by_name(&obs->data.first_encoder, name, - &obs->data.encoders_mutex, - obs_encoder_addref_safe_); + return get_context_by_name(&obs->data.first_encoder, name, &obs->data.encoders_mutex, obs_encoder_addref_safe_); } obs_service_t *obs_get_service_by_name(const char *name) { - return get_context_by_name(&obs->data.first_service, name, - &obs->data.services_mutex, - obs_service_addref_safe_); + return get_context_by_name(&obs->data.first_service, name, &obs->data.services_mutex, obs_service_addref_safe_); } gs_effect_t *obs_get_base_effect(enum obs_base_effect effect) @@ -2153,10 +2033,8 @@ proc_handler_t *obs_get_proc_handler(void) return obs->procs; } -static void obs_render_main_texture_internal(enum gs_blend_type src_c, - enum gs_blend_type dest_c, - enum gs_blend_type src_a, - enum gs_blend_type dest_a) +static void obs_render_main_texture_internal(enum gs_blend_type src_c, enum gs_blend_type dest_c, + enum gs_blend_type src_a, enum gs_blend_type dest_a) { struct obs_core_video_mix *video; gs_texture_t *tex; @@ -2208,14 +2086,12 @@ static void obs_render_main_texture_internal(enum gs_blend_type src_c, void obs_render_main_texture(void) { - obs_render_main_texture_internal(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA, - GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); + obs_render_main_texture_internal(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); } void obs_render_main_texture_src_color_only(void) { - obs_render_main_texture_internal(GS_BLEND_ONE, GS_BLEND_ZERO, - GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); + obs_render_main_texture_internal(GS_BLEND_ONE, GS_BLEND_ZERO, GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); } gs_texture_t *obs_get_main_texture(void) @@ -2229,8 +2105,7 @@ gs_texture_t *obs_get_main_texture(void) return video->render_texture; } -static obs_source_t *obs_load_source_type(obs_data_t *source_data, - bool is_private) +static obs_source_t *obs_load_source_type(obs_data_t *source_data, bool is_private) { obs_data_array_t *filters = obs_data_get_array(source_data, "filters"); obs_source_t *source; @@ -2256,8 +2131,7 @@ static obs_source_t *obs_load_source_type(obs_data_t *source_data, if (!*v_id) v_id = id; - source = obs_source_create_set_last_ver(v_id, name, uuid, settings, - hotkeys, prev_ver, is_private); + source = obs_source_create_set_last_ver(v_id, name, uuid, settings, hotkeys, prev_ver, is_private); if (source->owns_info_id) { bfree((void *)source->info.unversioned_id); @@ -2288,36 +2162,28 @@ static obs_source_t *obs_load_source_type(obs_data_t *source_data, obs_source_set_flags(source, flags); obs_data_set_default_bool(source_data, "enabled", true); - obs_source_set_enabled(source, - obs_data_get_bool(source_data, "enabled")); + obs_source_set_enabled(source, obs_data_get_bool(source_data, "enabled")); obs_data_set_default_bool(source_data, "muted", false); obs_source_set_muted(source, obs_data_get_bool(source_data, "muted")); obs_data_set_default_bool(source_data, "push-to-mute", false); - obs_source_enable_push_to_mute( - source, obs_data_get_bool(source_data, "push-to-mute")); + obs_source_enable_push_to_mute(source, obs_data_get_bool(source_data, "push-to-mute")); obs_data_set_default_int(source_data, "push-to-mute-delay", 0); - obs_source_set_push_to_mute_delay( - source, obs_data_get_int(source_data, "push-to-mute-delay")); + obs_source_set_push_to_mute_delay(source, obs_data_get_int(source_data, "push-to-mute-delay")); obs_data_set_default_bool(source_data, "push-to-talk", false); - obs_source_enable_push_to_talk( - source, obs_data_get_bool(source_data, "push-to-talk")); + obs_source_enable_push_to_talk(source, obs_data_get_bool(source_data, "push-to-talk")); obs_data_set_default_int(source_data, "push-to-talk-delay", 0); - obs_source_set_push_to_talk_delay( - source, obs_data_get_int(source_data, "push-to-talk-delay")); + obs_source_set_push_to_talk_delay(source, obs_data_get_int(source_data, "push-to-talk-delay")); di_mode = (int)obs_data_get_int(source_data, "deinterlace_mode"); - obs_source_set_deinterlace_mode(source, - (enum obs_deinterlace_mode)di_mode); + obs_source_set_deinterlace_mode(source, (enum obs_deinterlace_mode)di_mode); - di_order = - (int)obs_data_get_int(source_data, "deinterlace_field_order"); - obs_source_set_deinterlace_field_order( - source, (enum obs_deinterlace_field_order)di_order); + di_order = (int)obs_data_get_int(source_data, "deinterlace_field_order"); + obs_source_set_deinterlace_field_order(source, (enum obs_deinterlace_field_order)di_order); monitoring_type = (int)obs_data_get_int(source_data, "monitoring_type"); if (prev_ver < MAKE_SEMANTIC_VERSION(23, 2, 2)) { @@ -2329,12 +2195,10 @@ static obs_source_t *obs_load_source_type(obs_data_t *source_data, obs_source_set_audio_mixers(source, 0x3F); } } - obs_source_set_monitoring_type( - source, (enum obs_monitoring_type)monitoring_type); + obs_source_set_monitoring_type(source, (enum obs_monitoring_type)monitoring_type); obs_data_release(source->private_settings); - source->private_settings = - obs_data_get_obj(source_data, "private_settings"); + source->private_settings = obs_data_get_obj(source_data, "private_settings"); if (!source->private_settings) source->private_settings = obs_data_create(); @@ -2342,11 +2206,9 @@ static obs_source_t *obs_load_source_type(obs_data_t *source_data, size_t count = obs_data_array_count(filters); for (size_t i = 0; i < count; i++) { - obs_data_t *filter_data = - obs_data_array_item(filters, i); + obs_data_t *filter_data = obs_data_array_item(filters, i); - obs_source_t *filter = - obs_load_source_type(filter_data, true); + obs_source_t *filter = obs_load_source_type(filter_data, true); if (filter) { obs_source_filter_add(source, filter); obs_source_release(filter); @@ -2373,8 +2235,7 @@ obs_source_t *obs_load_private_source(obs_data_t *source_data) return obs_load_source_type(source_data, true); } -void obs_load_sources(obs_data_array_t *array, obs_load_source_cb cb, - void *private_data) +void obs_load_sources(obs_data_array_t *array, obs_load_source_cb cb, void *private_data) { struct obs_core_data *data = &obs->data; DARRAY(obs_source_t *) sources; @@ -2478,8 +2339,7 @@ obs_data_t *obs_save_source(obs_source_t *source) obs_data_set_int(source_data, "deinterlace_field_order", di_order); obs_data_set_int(source_data, "monitoring_type", m_type); - obs_data_set_obj(source_data, "private_settings", - source->private_settings); + obs_data_set_obj(source_data, "private_settings", source->private_settings); if (source->info.type == OBS_SOURCE_TYPE_TRANSITION) obs_transition_save(source, source_data); @@ -2489,8 +2349,7 @@ obs_data_t *obs_save_source(obs_source_t *source) da_reserve(filters_copy, source->filters.num); for (size_t i = 0; i < source->filters.num; i++) { - obs_source_t *filter = - obs_source_get_ref(source->filters.array[i]); + obs_source_t *filter = obs_source_get_ref(source->filters.array[i]); if (filter) da_push_back(filters_copy, &filter); } @@ -2517,8 +2376,7 @@ obs_data_t *obs_save_source(obs_source_t *source) return source_data; } -obs_data_array_t *obs_save_sources_filtered(obs_save_source_filter_cb cb, - void *data_) +obs_data_array_t *obs_save_sources_filtered(obs_save_source_filter_cb cb, void *data_) { struct obs_core_data *data = &obs->data; obs_data_array_t *array; @@ -2531,8 +2389,7 @@ obs_data_array_t *obs_save_sources_filtered(obs_save_source_filter_cb cb, source = data->public_sources; while (source) { - if ((source->info.type != OBS_SOURCE_TYPE_FILTER) != 0 && - !source->removed && !source->temp_removed && + if ((source->info.type != OBS_SOURCE_TYPE_FILTER) != 0 && !source->removed && !source->temp_removed && cb(data_, source)) { obs_data_t *source_data = obs_save_source(source); @@ -2565,8 +2422,7 @@ void obs_reset_source_uuids() pthread_mutex_lock(&obs->data.sources_mutex); /* Move all sources to a new hash table */ - struct obs_context_data *ht = - (struct obs_context_data *)obs->data.sources; + struct obs_context_data *ht = (struct obs_context_data *)obs->data.sources; struct obs_context_data *new_ht = NULL; struct obs_context_data *ctx, *tmp; @@ -2594,8 +2450,7 @@ static inline char *dup_name(const char *name, bool private) if (!name || !*name) { struct dstr unnamed = {0}; - dstr_printf(&unnamed, "__unnamed%04lld", - obs->data.unnamed_index++); + dstr_printf(&unnamed, "__unnamed%04lld", obs->data.unnamed_index++); return unnamed.array; } else { @@ -2603,11 +2458,9 @@ static inline char *dup_name(const char *name, bool private) } } -static inline bool -obs_context_data_init_wrap(struct obs_context_data *context, - enum obs_obj_type type, obs_data_t *settings, - const char *name, const char *uuid, - obs_data_t *hotkey_data, bool private) +static inline bool obs_context_data_init_wrap(struct obs_context_data *context, enum obs_obj_type type, + obs_data_t *settings, const char *name, const char *uuid, + obs_data_t *hotkey_data, bool private) { assert(context); memset(context, 0, sizeof(*context)); @@ -2638,13 +2491,10 @@ obs_context_data_init_wrap(struct obs_context_data *context, return true; } -bool obs_context_data_init(struct obs_context_data *context, - enum obs_obj_type type, obs_data_t *settings, - const char *name, const char *uuid, - obs_data_t *hotkey_data, bool private) +bool obs_context_data_init(struct obs_context_data *context, enum obs_obj_type type, obs_data_t *settings, + const char *name, const char *uuid, obs_data_t *hotkey_data, bool private) { - if (obs_context_data_init_wrap(context, type, settings, name, uuid, - hotkey_data, private)) { + if (obs_context_data_init_wrap(context, type, settings, name, uuid, hotkey_data, private)) { return true; } else { obs_context_data_free(context); @@ -2670,16 +2520,14 @@ void obs_context_data_free(struct obs_context_data *context) memset(context, 0, sizeof(*context)); } -void obs_context_init_control(struct obs_context_data *context, void *object, - obs_destroy_cb destroy) +void obs_context_init_control(struct obs_context_data *context, void *object, obs_destroy_cb destroy) { context->control = bzalloc(sizeof(obs_weak_object_t)); context->control->object = object; context->destroy = destroy; } -void obs_context_data_insert(struct obs_context_data *context, - pthread_mutex_t *mutex, void *pfirst) +void obs_context_data_insert(struct obs_context_data *context, pthread_mutex_t *mutex, void *pfirst) { struct obs_context_data **first = pfirst; @@ -2718,8 +2566,7 @@ static inline char *obs_context_deduplicate_name(void *phash, const char *name) return new_name.array; } -void obs_context_data_insert_name(struct obs_context_data *context, - pthread_mutex_t *mutex, void *pfirst) +void obs_context_data_insert_name(struct obs_context_data *context, pthread_mutex_t *mutex, void *pfirst) { struct obs_context_data **first = pfirst; char *new_name; @@ -2750,8 +2597,7 @@ void obs_context_data_insert_name(struct obs_context_data *context, pthread_mutex_unlock(mutex); } -void obs_context_data_insert_uuid(struct obs_context_data *context, - pthread_mutex_t *mutex, void *pfirst_uuid) +void obs_context_data_insert_uuid(struct obs_context_data *context, pthread_mutex_t *mutex, void *pfirst_uuid) { struct obs_context_data **first_uuid = pfirst_uuid; struct obs_context_data *item = NULL; @@ -2770,9 +2616,7 @@ void obs_context_data_insert_uuid(struct obs_context_data *context, * or regenerating the UUID. */ HASH_FIND_UUID(*first_uuid, context->uuid, item); if (item) { - blog(LOG_WARNING, - "Attempted to insert context with duplicate UUID \"%s\"!", - context->uuid); + blog(LOG_WARNING, "Attempted to insert context with duplicate UUID \"%s\"!", context->uuid); /* It is practically impossible for the new UUID to be a * duplicate, so don't bother checking again. */ bfree((void *)context->uuid); @@ -2809,8 +2653,7 @@ void obs_context_data_remove_name(struct obs_context_data *context, void *phead) pthread_mutex_unlock(context->mutex); } -void obs_context_data_remove_uuid(struct obs_context_data *context, - void *puuid_head) +void obs_context_data_remove_uuid(struct obs_context_data *context, void *puuid_head) { struct obs_context_data **uuid_head = puuid_head; @@ -2830,8 +2673,7 @@ void obs_context_wait(struct obs_context_data *context) pthread_mutex_unlock(context->mutex); } -void obs_context_data_setname(struct obs_context_data *context, - const char *name) +void obs_context_data_setname(struct obs_context_data *context, const char *name) { pthread_mutex_lock(&context->rename_cache_mutex); @@ -2842,8 +2684,7 @@ void obs_context_data_setname(struct obs_context_data *context, pthread_mutex_unlock(&context->rename_cache_mutex); } -void obs_context_data_setname_ht(struct obs_context_data *context, - const char *name, void *phead) +void obs_context_data_setname_ht(struct obs_context_data *context, const char *name, void *phead) { struct obs_context_data **head = phead; char *new_name; @@ -3002,8 +2843,7 @@ void obs_get_audio_monitoring_device(const char **name, const char **id) *id = obs->audio.monitoring_device_id; } -void obs_add_tick_callback(void (*tick)(void *param, float seconds), - void *param) +void obs_add_tick_callback(void (*tick)(void *param, float seconds), void *param) { struct tick_callback data = {tick, param}; @@ -3012,8 +2852,7 @@ void obs_add_tick_callback(void (*tick)(void *param, float seconds), pthread_mutex_unlock(&obs->data.draw_callbacks_mutex); } -void obs_remove_tick_callback(void (*tick)(void *param, float seconds), - void *param) +void obs_remove_tick_callback(void (*tick)(void *param, float seconds), void *param) { struct tick_callback data = {tick, param}; @@ -3022,9 +2861,7 @@ void obs_remove_tick_callback(void (*tick)(void *param, float seconds), pthread_mutex_unlock(&obs->data.draw_callbacks_mutex); } -void obs_add_main_render_callback(void (*draw)(void *param, uint32_t cx, - uint32_t cy), - void *param) +void obs_add_main_render_callback(void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param) { struct draw_callback data = {draw, param}; @@ -3033,9 +2870,7 @@ void obs_add_main_render_callback(void (*draw)(void *param, uint32_t cx, pthread_mutex_unlock(&obs->data.draw_callbacks_mutex); } -void obs_remove_main_render_callback(void (*draw)(void *param, uint32_t cx, - uint32_t cy), - void *param) +void obs_remove_main_render_callback(void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param) { struct draw_callback data = {draw, param}; @@ -3053,8 +2888,7 @@ void obs_add_main_rendered_callback(void (*rendered)(void *param), void *param) pthread_mutex_unlock(&obs->data.draw_callbacks_mutex); } -void obs_remove_main_rendered_callback(void (*rendered)(void *param), - void *param) +void obs_remove_main_rendered_callback(void (*rendered)(void *param), void *param) { struct rendered_callback data = {rendered, param}; @@ -3091,21 +2925,16 @@ struct obs_core_video_mix *get_mix_for_video(video_t *v) return result; } -void start_raw_video(video_t *v, const struct video_scale_info *conversion, - uint32_t frame_rate_divisor, - void (*callback)(void *param, struct video_data *frame), - void *param) +void start_raw_video(video_t *v, const struct video_scale_info *conversion, uint32_t frame_rate_divisor, + void (*callback)(void *param, struct video_data *frame), void *param) { struct obs_core_video_mix *video = get_mix_for_video(v); if (video) os_atomic_inc_long(&video->raw_active); - video_output_connect2(v, conversion, frame_rate_divisor, callback, - param); + video_output_connect2(v, conversion, frame_rate_divisor, callback, param); } -void stop_raw_video(video_t *v, - void (*callback)(void *param, struct video_data *frame), - void *param) +void stop_raw_video(video_t *v, void (*callback)(void *param, struct video_data *frame), void *param) { struct obs_core_video_mix *video = get_mix_for_video(v); if (video) @@ -3114,42 +2943,32 @@ void stop_raw_video(video_t *v, } void obs_add_raw_video_callback(const struct video_scale_info *conversion, - void (*callback)(void *param, - struct video_data *frame), - void *param) + void (*callback)(void *param, struct video_data *frame), void *param) { obs_add_raw_video_callback2(conversion, 1, callback, param); } -void obs_add_raw_video_callback2( - const struct video_scale_info *conversion, uint32_t frame_rate_divisor, - void (*callback)(void *param, struct video_data *frame), void *param) +void obs_add_raw_video_callback2(const struct video_scale_info *conversion, uint32_t frame_rate_divisor, + void (*callback)(void *param, struct video_data *frame), void *param) { struct obs_core_video_mix *video = obs->video.main_mix; - start_raw_video(video->video, conversion, frame_rate_divisor, callback, - param); + start_raw_video(video->video, conversion, frame_rate_divisor, callback, param); } -void obs_remove_raw_video_callback(void (*callback)(void *param, - struct video_data *frame), - void *param) +void obs_remove_raw_video_callback(void (*callback)(void *param, struct video_data *frame), void *param) { struct obs_core_video_mix *video = obs->video.main_mix; stop_raw_video(video->video, callback, param); } -void obs_add_raw_audio_callback(size_t mix_idx, - const struct audio_convert_info *conversion, +void obs_add_raw_audio_callback(size_t mix_idx, const struct audio_convert_info *conversion, audio_output_callback_t callback, void *param) { struct obs_core_audio *audio = &obs->audio; - audio_output_connect(audio->audio, mix_idx, conversion, callback, - param); + audio_output_connect(audio->audio, mix_idx, conversion, callback, param); } -void obs_remove_raw_audio_callback(size_t mix_idx, - audio_output_callback_t callback, - void *param) +void obs_remove_raw_audio_callback(size_t mix_idx, audio_output_callback_t callback, void *param) { struct obs_core_audio *audio = &obs->audio; audio_output_disconnect(audio->audio, mix_idx, callback, param); @@ -3306,8 +3125,7 @@ bool obs_in_task_thread(enum obs_task_type type) return false; } -void obs_queue_task(enum obs_task_type type, obs_task_t task, void *param, - bool wait) +void obs_queue_task(enum obs_task_type type, obs_task_t task, void *param, bool wait) { if (type == OBS_TASK_UI) { if (obs->ui_task_handler) { @@ -3349,8 +3167,7 @@ void obs_queue_task(enum obs_task_type type, obs_task_t task, void *param, } else if (type == OBS_TASK_DESTROY) { os_task_t os_task = (os_task_t)task; - os_task_queue_queue_task(obs->destruction_task_thread, - os_task, param); + os_task_queue_queue_task(obs->destruction_task_thread, os_task, param); } } } @@ -3455,8 +3272,7 @@ bool obs_weak_object_expired(obs_weak_object_t *weak) return weak ? obs_weak_ref_expired(&weak->ref) : true; } -bool obs_weak_object_references_object(obs_weak_object_t *weak, - obs_object_t *object) +bool obs_weak_object_references_object(obs_weak_object_t *weak, obs_object_t *object) { return weak && object && weak->object == object; } diff --git a/libobs/obs.h b/libobs/obs.h index 23bd3defe..095bccc5e 100644 --- a/libobs/obs.h +++ b/libobs/obs.h @@ -343,8 +343,7 @@ EXPORT bool obs_remove_data_path(const char *path); * (or NULL if none) * @param store The profiler name store for OBS to use or NULL */ -EXPORT bool obs_startup(const char *locale, const char *module_config_path, - profiler_name_store_t *store); +EXPORT bool obs_startup(const char *locale, const char *module_config_path, profiler_name_store_t *store); /** Releases all data associated with OBS and terminates the OBS context */ EXPORT void obs_shutdown(void); @@ -436,8 +435,7 @@ EXPORT float obs_get_video_sdr_white_level(void); EXPORT float obs_get_video_hdr_nominal_peak_level(void); /** Sets the video levels */ -EXPORT void obs_set_video_levels(float sdr_white_level, - float hdr_nominal_peak_level); +EXPORT void obs_set_video_levels(float sdr_white_level, float hdr_nominal_peak_level); /** Gets the current audio settings, returns false if no audio */ EXPORT bool obs_get_audio_info(struct obs_audio_info *oai); @@ -463,8 +461,7 @@ EXPORT bool obs_get_audio_info(struct obs_audio_info *oai); * MODULE_MISSING_EXPORTS if required exports are missing * MODULE_INCOMPATIBLE_VER if incompatible version */ -EXPORT int obs_open_module(obs_module_t **module, const char *path, - const char *data_path); +EXPORT int obs_open_module(obs_module_t **module, const char *path, const char *data_path); /** * Initializes the module, which calls its obs_module_load export. If the @@ -480,12 +477,10 @@ EXPORT obs_module_t *obs_get_module(const char *name); EXPORT void *obs_get_module_lib(obs_module_t *module); /** Returns locale text from a specific module */ -EXPORT bool obs_module_get_locale_string(const obs_module_t *mod, - const char *lookup_string, +EXPORT bool obs_module_get_locale_string(const obs_module_t *mod, const char *lookup_string, const char **translated_string); -EXPORT const char *obs_module_get_locale_text(const obs_module_t *mod, - const char *text); +EXPORT const char *obs_module_get_locale_text(const obs_module_t *mod, const char *text); /** Logs loaded modules */ EXPORT void obs_log_loaded_modules(void); @@ -547,8 +542,7 @@ struct obs_module_info { const char *data_path; }; -typedef void (*obs_find_module_callback_t)(void *param, - const struct obs_module_info *info); +typedef void (*obs_find_module_callback_t)(void *param, const struct obs_module_info *info); /** Finds all modules within the search paths added by obs_add_module_path. */ EXPORT void obs_find_modules(obs_find_module_callback_t callback, void *param); @@ -559,12 +553,10 @@ struct obs_module_info2 { const char *name; }; -typedef void (*obs_find_module_callback2_t)( - void *param, const struct obs_module_info2 *info); +typedef void (*obs_find_module_callback2_t)(void *param, const struct obs_module_info2 *info); /** Finds all modules within the search paths added by obs_add_module_path. */ -EXPORT void obs_find_modules2(obs_find_module_callback2_t callback, - void *param); +EXPORT void obs_find_modules2(obs_find_module_callback2_t callback, void *param); #endif typedef void (*obs_enum_module_callback_t)(void *param, obs_module_t *module); @@ -573,9 +565,7 @@ typedef void (*obs_enum_module_callback_t)(void *param, obs_module_t *module); EXPORT void obs_enum_modules(obs_enum_module_callback_t callback, void *param); /** Helper function for using default module locale */ -EXPORT lookup_t *obs_module_load_locale(obs_module_t *module, - const char *default_locale, - const char *locale); +EXPORT lookup_t *obs_module_load_locale(obs_module_t *module, const char *default_locale, const char *locale); /** * Returns the location of a plugin module data file. @@ -613,8 +603,7 @@ EXPORT bool obs_enum_source_types(size_t idx, const char **id); * etc). */ EXPORT bool obs_enum_input_types(size_t idx, const char **id); -EXPORT bool obs_enum_input_types2(size_t idx, const char **id, - const char **unversioned_id); +EXPORT bool obs_enum_input_types2(size_t idx, const char **id, const char **unversioned_id); EXPORT const char *obs_get_latest_input_type_id(const char *unversioned_id); @@ -676,28 +665,22 @@ EXPORT obs_source_t *obs_get_output_source(uint32_t channel); * Use obs_source_get_ref or obs_source_get_weak_source if you want to retain * a reference after obs_enum_sources finishes */ -EXPORT void obs_enum_sources(bool (*enum_proc)(void *, obs_source_t *), - void *param); +EXPORT void obs_enum_sources(bool (*enum_proc)(void *, obs_source_t *), void *param); /** Enumerates scenes */ -EXPORT void obs_enum_scenes(bool (*enum_proc)(void *, obs_source_t *), - void *param); +EXPORT void obs_enum_scenes(bool (*enum_proc)(void *, obs_source_t *), void *param); /** Enumerates all sources (regardless of type) */ -EXPORT void obs_enum_all_sources(bool (*enum_proc)(void *, obs_source_t *), - void *param); +EXPORT void obs_enum_all_sources(bool (*enum_proc)(void *, obs_source_t *), void *param); /** Enumerates outputs */ -EXPORT void obs_enum_outputs(bool (*enum_proc)(void *, obs_output_t *), - void *param); +EXPORT void obs_enum_outputs(bool (*enum_proc)(void *, obs_output_t *), void *param); /** Enumerates encoders */ -EXPORT void obs_enum_encoders(bool (*enum_proc)(void *, obs_encoder_t *), - void *param); +EXPORT void obs_enum_encoders(bool (*enum_proc)(void *, obs_encoder_t *), void *param); /** Enumerates encoders */ -EXPORT void obs_enum_services(bool (*enum_proc)(void *, obs_service_t *), - void *param); +EXPORT void obs_enum_services(bool (*enum_proc)(void *, obs_service_t *), void *param); /** * Gets a source by its name. @@ -731,13 +714,13 @@ EXPORT obs_encoder_t *obs_get_encoder_by_name(const char *name); EXPORT obs_service_t *obs_get_service_by_name(const char *name); enum obs_base_effect { - OBS_EFFECT_DEFAULT, /**< RGB/YUV */ - OBS_EFFECT_DEFAULT_RECT, /**< RGB/YUV (using texture_rect) */ - OBS_EFFECT_OPAQUE, /**< RGB/YUV (alpha set to 1.0) */ - OBS_EFFECT_SOLID, /**< RGB/YUV (solid color only) */ - OBS_EFFECT_BICUBIC, /**< Bicubic downscale */ - OBS_EFFECT_LANCZOS, /**< Lanczos downscale */ - OBS_EFFECT_BILINEAR_LOWRES, /**< Bilinear low resolution downscale */ + OBS_EFFECT_DEFAULT, /**< RGB/YUV */ + OBS_EFFECT_DEFAULT_RECT, /**< RGB/YUV (using texture_rect) */ + OBS_EFFECT_OPAQUE, /**< RGB/YUV (alpha set to 1.0) */ + OBS_EFFECT_SOLID, /**< RGB/YUV (solid color only) */ + OBS_EFFECT_BICUBIC, /**< Bicubic downscale */ + OBS_EFFECT_LANCZOS, /**< Lanczos downscale */ + OBS_EFFECT_BILINEAR_LOWRES, /**< Bilinear low resolution downscale */ OBS_EFFECT_PREMULTIPLIED_ALPHA, /**< Premultiplied alpha */ OBS_EFFECT_REPEAT, /**< RGB/YUV (repeating) */ OBS_EFFECT_AREA, /**< Area rescale */ @@ -783,15 +766,13 @@ EXPORT void obs_source_load2(obs_source_t *source); typedef void (*obs_load_source_cb)(void *private_data, obs_source_t *source); /** Loads sources from a data array */ -EXPORT void obs_load_sources(obs_data_array_t *array, obs_load_source_cb cb, - void *private_data); +EXPORT void obs_load_sources(obs_data_array_t *array, obs_load_source_cb cb, void *private_data); /** Saves sources to a data array */ EXPORT obs_data_array_t *obs_save_sources(void); typedef bool (*obs_save_source_filter_cb)(void *data, obs_source_t *source); -EXPORT obs_data_array_t *obs_save_sources_filtered(obs_save_source_filter_cb cb, - void *data); +EXPORT obs_data_array_t *obs_save_sources_filtered(obs_save_source_filter_cb cb, void *data); /** Reset source UUIDs. NOTE: this function is only to be used by the UI and * will be removed in a future version! */ @@ -811,51 +792,35 @@ EXPORT bool obs_obj_invalid(void *obj); EXPORT void *obs_obj_get_data(void *obj); EXPORT bool obs_obj_is_private(void *obj); -typedef bool (*obs_enum_audio_device_cb)(void *data, const char *name, - const char *id); +typedef bool (*obs_enum_audio_device_cb)(void *data, const char *name, const char *id); EXPORT bool obs_audio_monitoring_available(void); EXPORT void obs_reset_audio_monitoring(void); -EXPORT void obs_enum_audio_monitoring_devices(obs_enum_audio_device_cb cb, - void *data); +EXPORT void obs_enum_audio_monitoring_devices(obs_enum_audio_device_cb cb, void *data); EXPORT bool obs_set_audio_monitoring_device(const char *name, const char *id); EXPORT void obs_get_audio_monitoring_device(const char **name, const char **id); -EXPORT void obs_add_tick_callback(void (*tick)(void *param, float seconds), - void *param); -EXPORT void obs_remove_tick_callback(void (*tick)(void *param, float seconds), - void *param); +EXPORT void obs_add_tick_callback(void (*tick)(void *param, float seconds), void *param); +EXPORT void obs_remove_tick_callback(void (*tick)(void *param, float seconds), void *param); -EXPORT void obs_add_main_render_callback(void (*draw)(void *param, uint32_t cx, - uint32_t cy), - void *param); -EXPORT void obs_remove_main_render_callback( - void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param); +EXPORT void obs_add_main_render_callback(void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param); +EXPORT void obs_remove_main_render_callback(void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param); -EXPORT void obs_add_main_rendered_callback(void (*rendered)(void *param), - void *param); -EXPORT void obs_remove_main_rendered_callback(void (*rendered)(void *param), - void *param); +EXPORT void obs_add_main_rendered_callback(void (*rendered)(void *param), void *param); +EXPORT void obs_remove_main_rendered_callback(void (*rendered)(void *param), void *param); -EXPORT void obs_add_raw_video_callback( - const struct video_scale_info *conversion, - void (*callback)(void *param, struct video_data *frame), void *param); -EXPORT void obs_add_raw_video_callback2( - const struct video_scale_info *conversion, uint32_t frame_rate_divisor, - void (*callback)(void *param, struct video_data *frame), void *param); -EXPORT void obs_remove_raw_video_callback( - void (*callback)(void *param, struct video_data *frame), void *param); +EXPORT void obs_add_raw_video_callback(const struct video_scale_info *conversion, + void (*callback)(void *param, struct video_data *frame), void *param); +EXPORT void obs_add_raw_video_callback2(const struct video_scale_info *conversion, uint32_t frame_rate_divisor, + void (*callback)(void *param, struct video_data *frame), void *param); +EXPORT void obs_remove_raw_video_callback(void (*callback)(void *param, struct video_data *frame), void *param); -EXPORT void -obs_add_raw_audio_callback(size_t mix_idx, - const struct audio_convert_info *conversion, - audio_output_callback_t callback, void *param); -EXPORT void obs_remove_raw_audio_callback(size_t mix_idx, - audio_output_callback_t callback, - void *param); +EXPORT void obs_add_raw_audio_callback(size_t mix_idx, const struct audio_convert_info *conversion, + audio_output_callback_t callback, void *param); +EXPORT void obs_remove_raw_audio_callback(size_t mix_idx, audio_output_callback_t callback, void *param); EXPORT uint64_t obs_get_video_frame_time(void); @@ -882,8 +847,7 @@ enum obs_task_type { OBS_TASK_DESTROY, }; -EXPORT void obs_queue_task(enum obs_task_type type, obs_task_t task, - void *param, bool wait); +EXPORT void obs_queue_task(enum obs_task_type type, obs_task_t task, void *param, bool wait); EXPORT bool obs_in_task_thread(enum obs_task_type type); EXPORT bool obs_wait_for_destroy_queue(void); @@ -899,8 +863,7 @@ EXPORT void obs_weak_object_release(obs_weak_object_t *weak); EXPORT obs_weak_object_t *obs_object_get_weak_object(obs_object_t *object); EXPORT obs_object_t *obs_weak_object_get_object(obs_weak_object_t *weak); EXPORT bool obs_weak_object_expired(obs_weak_object_t *weak); -EXPORT bool obs_weak_object_references_object(obs_weak_object_t *weak, - obs_object_t *object); +EXPORT bool obs_weak_object_references_object(obs_weak_object_t *weak, obs_object_t *object); /* ------------------------------------------------------------------------- */ /* View context */ @@ -917,8 +880,7 @@ EXPORT obs_view_t *obs_view_create(void); EXPORT void obs_view_destroy(obs_view_t *view); /** Sets the source to be used for this view context. */ -EXPORT void obs_view_set_source(obs_view_t *view, uint32_t channel, - obs_source_t *source); +EXPORT void obs_view_set_source(obs_view_t *view, uint32_t channel, obs_source_t *source); /** Gets the source currently in use for this view context */ EXPORT obs_source_t *obs_view_get_source(obs_view_t *view, uint32_t channel); @@ -936,14 +898,10 @@ EXPORT video_t *obs_view_add2(obs_view_t *view, struct obs_video_info *ovi); EXPORT void obs_view_remove(obs_view_t *view); /** Gets the video settings currently in use for this view context, returns false if no video */ -OBS_DEPRECATED EXPORT bool obs_view_get_video_info(obs_view_t *view, - struct obs_video_info *ovi); +OBS_DEPRECATED EXPORT bool obs_view_get_video_info(obs_view_t *view, struct obs_video_info *ovi); /** Enumerate the video info of all mixes using the specified view context */ -EXPORT void obs_view_enum_video_info(obs_view_t *view, - bool (*enum_proc)(void *, - struct obs_video_info *), - void *param); +EXPORT void obs_view_enum_video_info(obs_view_t *view, bool (*enum_proc)(void *, struct obs_video_info *), void *param); /* ------------------------------------------------------------------------- */ /* Display context */ @@ -955,16 +913,13 @@ EXPORT void obs_view_enum_video_info(obs_view_t *view, * @param graphics_data The swap chain initialization data. * @return The new display context, or NULL if failed. */ -EXPORT obs_display_t * -obs_display_create(const struct gs_init_data *graphics_data, - uint32_t backround_color); +EXPORT obs_display_t *obs_display_create(const struct gs_init_data *graphics_data, uint32_t backround_color); /** Destroys a display context */ EXPORT void obs_display_destroy(obs_display_t *display); /** Changes the size of this display */ -EXPORT void obs_display_resize(obs_display_t *display, uint32_t cx, - uint32_t cy); +EXPORT void obs_display_resize(obs_display_t *display, uint32_t cx, uint32_t cy); /** Updates the color space of this display */ EXPORT void obs_display_update_color_space(obs_display_t *display); @@ -977,24 +932,19 @@ EXPORT void obs_display_update_color_space(obs_display_t *display); * updates. * @param param The user data to be associated with this draw callback. */ -EXPORT void obs_display_add_draw_callback(obs_display_t *display, - void (*draw)(void *param, uint32_t cx, - uint32_t cy), +EXPORT void obs_display_add_draw_callback(obs_display_t *display, void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param); /** Removes a draw callback for this display context */ -EXPORT void obs_display_remove_draw_callback( - obs_display_t *display, - void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param); +EXPORT void obs_display_remove_draw_callback(obs_display_t *display, + void (*draw)(void *param, uint32_t cx, uint32_t cy), void *param); EXPORT void obs_display_set_enabled(obs_display_t *display, bool enable); EXPORT bool obs_display_enabled(obs_display_t *display); -EXPORT void obs_display_set_background_color(obs_display_t *display, - uint32_t color); +EXPORT void obs_display_set_background_color(obs_display_t *display, uint32_t color); -EXPORT void obs_display_size(obs_display_t *display, uint32_t *width, - uint32_t *height); +EXPORT void obs_display_size(obs_display_t *display, uint32_t *width, uint32_t *height); /* ------------------------------------------------------------------------- */ /* Sources */ @@ -1008,18 +958,13 @@ EXPORT const char *obs_source_get_display_name(const char *id); * The "source" context is used for anything related to presenting * or modifying video/audio. Use obs_source_release to release it. */ -EXPORT obs_source_t *obs_source_create(const char *id, const char *name, - obs_data_t *settings, - obs_data_t *hotkey_data); +EXPORT obs_source_t *obs_source_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data); -EXPORT obs_source_t *obs_source_create_private(const char *id, const char *name, - obs_data_t *settings); +EXPORT obs_source_t *obs_source_create_private(const char *id, const char *name, obs_data_t *settings); /* if source has OBS_SOURCE_DO_NOT_DUPLICATE output flag set, only returns a * reference */ -EXPORT obs_source_t *obs_source_duplicate(obs_source_t *source, - const char *desired_name, - bool create_private); +EXPORT obs_source_t *obs_source_duplicate(obs_source_t *source, const char *desired_name, bool create_private); /** * Adds/releases a reference to a source. When the last reference is * released, the source is destroyed. @@ -1034,8 +979,7 @@ EXPORT obs_weak_source_t *obs_source_get_weak_source(obs_source_t *source); EXPORT obs_source_t *obs_weak_source_get_source(obs_weak_source_t *weak); EXPORT bool obs_weak_source_expired(obs_weak_source_t *weak); -EXPORT bool obs_weak_source_references_source(obs_weak_source_t *weak, - obs_source_t *source); +EXPORT bool obs_weak_source_references_source(obs_weak_source_t *weak, obs_source_t *source); /** Notifies all references that the source should be released */ EXPORT void obs_source_remove(obs_source_t *source); @@ -1063,12 +1007,10 @@ EXPORT obs_data_t *obs_get_source_defaults(const char *id); /** Returns the property list, if any. Free with obs_properties_destroy */ EXPORT obs_properties_t *obs_get_source_properties(const char *id); -EXPORT obs_missing_files_t * -obs_source_get_missing_files(const obs_source_t *source); +EXPORT obs_missing_files_t *obs_source_get_missing_files(const obs_source_t *source); -EXPORT void obs_source_replace_missing_file(obs_missing_file_cb cb, - obs_source_t *source, - const char *new_path, void *data); +EXPORT void obs_source_replace_missing_file(obs_missing_file_cb cb, obs_source_t *source, const char *new_path, + void *data); /** Returns whether the source has custom properties or not */ EXPORT bool obs_is_source_configurable(const char *id); @@ -1083,8 +1025,7 @@ EXPORT obs_properties_t *obs_source_properties(const obs_source_t *source); /** Updates settings for this source */ EXPORT void obs_source_update(obs_source_t *source, obs_data_t *settings); -EXPORT void obs_source_reset_settings(obs_source_t *source, - obs_data_t *settings); +EXPORT void obs_source_reset_settings(obs_source_t *source, obs_data_t *settings); /** Renders a video source. */ EXPORT void obs_source_video_render(obs_source_t *source); @@ -1096,9 +1037,8 @@ EXPORT uint32_t obs_source_get_width(obs_source_t *source); EXPORT uint32_t obs_source_get_height(obs_source_t *source); /** Gets the color space of a source (if it has video) */ -EXPORT enum gs_color_space -obs_source_get_color_space(obs_source_t *source, size_t count, - const enum gs_color_space *preferred_spaces); +EXPORT enum gs_color_space obs_source_get_color_space(obs_source_t *source, size_t count, + const enum gs_color_space *preferred_spaces); /** Hints whether or not the source will blend texels */ EXPORT bool obs_source_get_texcoords_centered(obs_source_t *source); @@ -1124,21 +1064,16 @@ EXPORT void obs_source_default_render(obs_source_t *source); EXPORT void obs_source_filter_add(obs_source_t *source, obs_source_t *filter); /** Removes a filter from the source */ -EXPORT void obs_source_filter_remove(obs_source_t *source, - obs_source_t *filter); +EXPORT void obs_source_filter_remove(obs_source_t *source, obs_source_t *filter); /** Modifies the order of a specific filter */ -EXPORT void obs_source_filter_set_order(obs_source_t *source, - obs_source_t *filter, - enum obs_order_movement movement); +EXPORT void obs_source_filter_set_order(obs_source_t *source, obs_source_t *filter, enum obs_order_movement movement); /** Gets filter index */ -EXPORT int obs_source_filter_get_index(obs_source_t *source, - obs_source_t *filter); +EXPORT int obs_source_filter_get_index(obs_source_t *source, obs_source_t *filter); /** Sets filter index */ -EXPORT void obs_source_filter_set_index(obs_source_t *source, - obs_source_t *filter, size_t index); +EXPORT void obs_source_filter_set_index(obs_source_t *source, obs_source_t *filter, size_t index); /** Gets the settings string for a source */ EXPORT obs_data_t *obs_source_get_settings(const obs_source_t *source); @@ -1160,8 +1095,7 @@ EXPORT const char *obs_source_get_id(const obs_source_t *source); EXPORT const char *obs_source_get_unversioned_id(const obs_source_t *source); /** Returns the signal handler for a source */ -EXPORT signal_handler_t * -obs_source_get_signal_handler(const obs_source_t *source); +EXPORT signal_handler_t *obs_source_get_signal_handler(const obs_source_t *source); /** Returns the procedure handler for a source */ EXPORT proc_handler_t *obs_source_get_proc_handler(const obs_source_t *source); @@ -1188,18 +1122,12 @@ EXPORT void obs_source_set_sync_offset(obs_source_t *source, int64_t offset); EXPORT int64_t obs_source_get_sync_offset(const obs_source_t *source); /** Enumerates active child sources used by this source */ -EXPORT void obs_source_enum_active_sources(obs_source_t *source, - obs_source_enum_proc_t enum_callback, - void *param); +EXPORT void obs_source_enum_active_sources(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param); /** Enumerates the entire active child source tree used by this source */ -EXPORT void obs_source_enum_active_tree(obs_source_t *source, - obs_source_enum_proc_t enum_callback, - void *param); +EXPORT void obs_source_enum_active_tree(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param); -EXPORT void obs_source_enum_full_tree(obs_source_t *source, - obs_source_enum_proc_t enum_callback, - void *param); +EXPORT void obs_source_enum_full_tree(obs_source_t *source, obs_source_enum_proc_t enum_callback, void *param); /** Returns true if active, false if not */ EXPORT bool obs_source_active(const obs_source_t *source); @@ -1271,20 +1199,16 @@ EXPORT void obs_source_dec_showing(obs_source_t *source); EXPORT void obs_source_dec_active(obs_source_t *source); /** Enumerates filters assigned to the source */ -EXPORT void obs_source_enum_filters(obs_source_t *source, - obs_source_enum_proc_t callback, - void *param); +EXPORT void obs_source_enum_filters(obs_source_t *source, obs_source_enum_proc_t callback, void *param); /** Gets a filter of a source by its display name. */ -EXPORT obs_source_t *obs_source_get_filter_by_name(obs_source_t *source, - const char *name); +EXPORT obs_source_t *obs_source_get_filter_by_name(obs_source_t *source, const char *name); /** Gets the number of filters the source has. */ EXPORT size_t obs_source_filter_count(const obs_source_t *source); EXPORT void obs_source_copy_filters(obs_source_t *dst, obs_source_t *src); -EXPORT void obs_source_copy_single_filter(obs_source_t *dst, - obs_source_t *filter); +EXPORT void obs_source_copy_single_filter(obs_source_t *dst, obs_source_t *filter); EXPORT bool obs_source_enabled(const obs_source_t *source); EXPORT void obs_source_set_enabled(obs_source_t *source, bool enabled); @@ -1296,40 +1220,28 @@ EXPORT bool obs_source_push_to_mute_enabled(obs_source_t *source); EXPORT void obs_source_enable_push_to_mute(obs_source_t *source, bool enabled); EXPORT uint64_t obs_source_get_push_to_mute_delay(obs_source_t *source); -EXPORT void obs_source_set_push_to_mute_delay(obs_source_t *source, - uint64_t delay); +EXPORT void obs_source_set_push_to_mute_delay(obs_source_t *source, uint64_t delay); EXPORT bool obs_source_push_to_talk_enabled(obs_source_t *source); EXPORT void obs_source_enable_push_to_talk(obs_source_t *source, bool enabled); EXPORT uint64_t obs_source_get_push_to_talk_delay(obs_source_t *source); -EXPORT void obs_source_set_push_to_talk_delay(obs_source_t *source, - uint64_t delay); +EXPORT void obs_source_set_push_to_talk_delay(obs_source_t *source, uint64_t delay); -typedef void (*obs_source_audio_capture_t)(void *param, obs_source_t *source, - const struct audio_data *audio_data, +typedef void (*obs_source_audio_capture_t)(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted); -EXPORT void obs_source_add_audio_pause_callback(obs_source_t *source, - signal_callback_t callback, - void *param); -EXPORT void obs_source_remove_audio_pause_callback(obs_source_t *source, - signal_callback_t callback, - void *param); -EXPORT void obs_source_add_audio_capture_callback( - obs_source_t *source, obs_source_audio_capture_t callback, void *param); -EXPORT void obs_source_remove_audio_capture_callback( - obs_source_t *source, obs_source_audio_capture_t callback, void *param); +EXPORT void obs_source_add_audio_pause_callback(obs_source_t *source, signal_callback_t callback, void *param); +EXPORT void obs_source_remove_audio_pause_callback(obs_source_t *source, signal_callback_t callback, void *param); +EXPORT void obs_source_add_audio_capture_callback(obs_source_t *source, obs_source_audio_capture_t callback, + void *param); +EXPORT void obs_source_remove_audio_capture_callback(obs_source_t *source, obs_source_audio_capture_t callback, + void *param); -typedef void (*obs_source_caption_t)(void *param, obs_source_t *source, - const struct obs_source_cea_708 *captions); +typedef void (*obs_source_caption_t)(void *param, obs_source_t *source, const struct obs_source_cea_708 *captions); -EXPORT void obs_source_add_caption_callback(obs_source_t *source, - obs_source_caption_t callback, - void *param); -EXPORT void obs_source_remove_caption_callback(obs_source_t *source, - obs_source_caption_t callback, - void *param); +EXPORT void obs_source_add_caption_callback(obs_source_t *source, obs_source_caption_t callback, void *param); +EXPORT void obs_source_remove_caption_callback(obs_source_t *source, obs_source_caption_t callback, void *param); enum obs_deinterlace_mode { OBS_DEINTERLACE_MODE_DISABLE, @@ -1348,14 +1260,10 @@ enum obs_deinterlace_field_order { OBS_DEINTERLACE_FIELD_ORDER_BOTTOM, }; -EXPORT void obs_source_set_deinterlace_mode(obs_source_t *source, - enum obs_deinterlace_mode mode); -EXPORT enum obs_deinterlace_mode -obs_source_get_deinterlace_mode(const obs_source_t *source); -EXPORT void obs_source_set_deinterlace_field_order( - obs_source_t *source, enum obs_deinterlace_field_order field_order); -EXPORT enum obs_deinterlace_field_order -obs_source_get_deinterlace_field_order(const obs_source_t *source); +EXPORT void obs_source_set_deinterlace_mode(obs_source_t *source, enum obs_deinterlace_mode mode); +EXPORT enum obs_deinterlace_mode obs_source_get_deinterlace_mode(const obs_source_t *source); +EXPORT void obs_source_set_deinterlace_field_order(obs_source_t *source, enum obs_deinterlace_field_order field_order); +EXPORT enum obs_deinterlace_field_order obs_source_get_deinterlace_field_order(const obs_source_t *source); enum obs_monitoring_type { OBS_MONITORING_TYPE_NONE, @@ -1363,18 +1271,15 @@ enum obs_monitoring_type { OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT, }; -EXPORT void obs_source_set_monitoring_type(obs_source_t *source, - enum obs_monitoring_type type); -EXPORT enum obs_monitoring_type -obs_source_get_monitoring_type(const obs_source_t *source); +EXPORT void obs_source_set_monitoring_type(obs_source_t *source, enum obs_monitoring_type type); +EXPORT enum obs_monitoring_type obs_source_get_monitoring_type(const obs_source_t *source); /** Gets private front-end settings data. This data is saved/loaded * automatically. Returns an incremented reference. */ EXPORT obs_data_t *obs_source_get_private_settings(obs_source_t *item); EXPORT obs_data_array_t *obs_source_backup_filters(obs_source_t *source); -EXPORT void obs_source_restore_filters(obs_source_t *source, - obs_data_array_t *array); +EXPORT void obs_source_restore_filters(obs_source_t *source, obs_data_array_t *array); /* ------------------------------------------------------------------------- */ /* Functions used by sources */ @@ -1393,10 +1298,8 @@ EXPORT void *obs_source_get_type_data(obs_source_t *source); * 'color_range_max' effect variable. If NULL, * {1.0f, 1.0f, 1.0f} is used. */ -EXPORT void -obs_source_draw_set_color_matrix(const struct matrix4 *color_matrix, - const struct vec3 *color_range_min, - const struct vec3 *color_range_max); +EXPORT void obs_source_draw_set_color_matrix(const struct matrix4 *color_matrix, const struct vec3 *color_range_min, + const struct vec3 *color_range_max); /** * Helper function to draw sprites for a source (synchronous video). @@ -1409,8 +1312,7 @@ obs_source_draw_set_color_matrix(const struct matrix4 *color_matrix, * @param cy Height of the sprite. If 0, uses the texture height. * @param flip Specifies whether to flip the image vertically. */ -EXPORT void obs_source_draw(gs_texture_t *image, int x, int y, uint32_t cx, - uint32_t cy, bool flip); +EXPORT void obs_source_draw(gs_texture_t *image, int x, int y, uint32_t cx, uint32_t cy, bool flip); /** * Outputs asynchronous video data. Set to NULL to deactivate the texture @@ -1419,15 +1321,12 @@ EXPORT void obs_source_draw(gs_texture_t *image, int x, int y, uint32_t cx, * function! Use obs_source_output_video2 instead if partial range support is * desired for non-YUV video formats. */ -EXPORT void obs_source_output_video(obs_source_t *source, - const struct obs_source_frame *frame); -EXPORT void obs_source_output_video2(obs_source_t *source, - const struct obs_source_frame2 *frame); +EXPORT void obs_source_output_video(obs_source_t *source, const struct obs_source_frame *frame); +EXPORT void obs_source_output_video2(obs_source_t *source, const struct obs_source_frame2 *frame); EXPORT void obs_source_set_async_rotation(obs_source_t *source, long rotation); -EXPORT void obs_source_output_cea708(obs_source_t *source, - const struct obs_source_cea_708 *captions); +EXPORT void obs_source_output_cea708(obs_source_t *source, const struct obs_source_cea_708 *captions); /** * Preloads asynchronous video data to allow instantaneous playback @@ -1436,10 +1335,8 @@ EXPORT void obs_source_output_cea708(obs_source_t *source, * function! Use obs_source_preload_video2 instead if partial range support is * desired for non-YUV video formats. */ -EXPORT void obs_source_preload_video(obs_source_t *source, - const struct obs_source_frame *frame); -EXPORT void obs_source_preload_video2(obs_source_t *source, - const struct obs_source_frame2 *frame); +EXPORT void obs_source_preload_video(obs_source_t *source, const struct obs_source_frame *frame); +EXPORT void obs_source_preload_video2(obs_source_t *source, const struct obs_source_frame2 *frame); /** Shows any preloaded video data */ EXPORT void obs_source_show_preloaded_video(obs_source_t *source); @@ -1451,14 +1348,11 @@ EXPORT void obs_source_show_preloaded_video(obs_source_t *source); * function! Use obs_source_preload_video2 instead if partial range support is * desired for non-YUV video formats. */ -EXPORT void obs_source_set_video_frame(obs_source_t *source, - const struct obs_source_frame *frame); -EXPORT void obs_source_set_video_frame2(obs_source_t *source, - const struct obs_source_frame2 *frame); +EXPORT void obs_source_set_video_frame(obs_source_t *source, const struct obs_source_frame *frame); +EXPORT void obs_source_set_video_frame2(obs_source_t *source, const struct obs_source_frame2 *frame); /** Outputs audio data (always asynchronous) */ -EXPORT void obs_source_output_audio(obs_source_t *source, - const struct obs_source_audio *audio); +EXPORT void obs_source_output_audio(obs_source_t *source, const struct obs_source_audio *audio); /** Signal an update to any currently used properties via 'update_properties' */ EXPORT void obs_source_update_properties(obs_source_t *source); @@ -1467,8 +1361,7 @@ EXPORT void obs_source_update_properties(obs_source_t *source); EXPORT struct obs_source_frame *obs_source_get_frame(obs_source_t *source); /** Releases the current async video frame */ -EXPORT void obs_source_release_frame(obs_source_t *source, - struct obs_source_frame *frame); +EXPORT void obs_source_release_frame(obs_source_t *source, struct obs_source_frame *frame); /** * Default RGB filter handler for generic effect filters. Processes the @@ -1481,14 +1374,12 @@ EXPORT void obs_source_release_frame(obs_source_t *source, * Returns true if filtering should continue, false if the filter is bypassed * for whatever reason. */ -EXPORT bool -obs_source_process_filter_begin(obs_source_t *filter, - enum gs_color_format format, - enum obs_allow_direct_render allow_direct); +EXPORT bool obs_source_process_filter_begin(obs_source_t *filter, enum gs_color_format format, + enum obs_allow_direct_render allow_direct); -EXPORT bool obs_source_process_filter_begin_with_color_space( - obs_source_t *filter, enum gs_color_format format, - enum gs_color_space space, enum obs_allow_direct_render allow_direct); +EXPORT bool obs_source_process_filter_begin_with_color_space(obs_source_t *filter, enum gs_color_format format, + enum gs_color_space space, + enum obs_allow_direct_render allow_direct); /** * Draws the filter. @@ -1497,9 +1388,7 @@ EXPORT bool obs_source_process_filter_begin_with_color_space( * then set the effect parameters, and then call this function to finalize the * filter. */ -EXPORT void obs_source_process_filter_end(obs_source_t *filter, - gs_effect_t *effect, uint32_t width, - uint32_t height); +EXPORT void obs_source_process_filter_end(obs_source_t *filter, gs_effect_t *effect, uint32_t width, uint32_t height); /** * Draws the filter with a specific technique. @@ -1508,10 +1397,8 @@ EXPORT void obs_source_process_filter_end(obs_source_t *filter, * then set the effect parameters, and then call this function to finalize the * filter. */ -EXPORT void obs_source_process_filter_tech_end(obs_source_t *filter, - gs_effect_t *effect, - uint32_t width, uint32_t height, - const char *tech_name); +EXPORT void obs_source_process_filter_tech_end(obs_source_t *filter, gs_effect_t *effect, uint32_t width, + uint32_t height, const char *tech_name); /** Skips the filter if the filter is invalid and cannot be rendered */ EXPORT void obs_source_skip_video_filter(obs_source_t *filter); @@ -1523,40 +1410,31 @@ EXPORT void obs_source_skip_video_filter(obs_source_t *filter); * * @returns true if source can be added, false if it causes recursion */ -EXPORT bool obs_source_add_active_child(obs_source_t *parent, - obs_source_t *child); +EXPORT bool obs_source_add_active_child(obs_source_t *parent, obs_source_t *child); /** * Removes an active child source. Must be called by parent sources on child * sources when the child is removed or inactive. This ensures that the source * is properly deactivated if the parent is no longer active. */ -EXPORT void obs_source_remove_active_child(obs_source_t *parent, - obs_source_t *child); +EXPORT void obs_source_remove_active_child(obs_source_t *parent, obs_source_t *child); /** Sends a mouse down/up event to a source */ -EXPORT void obs_source_send_mouse_click(obs_source_t *source, - const struct obs_mouse_event *event, - int32_t type, bool mouse_up, - uint32_t click_count); +EXPORT void obs_source_send_mouse_click(obs_source_t *source, const struct obs_mouse_event *event, int32_t type, + bool mouse_up, uint32_t click_count); /** Sends a mouse move event to a source. */ -EXPORT void obs_source_send_mouse_move(obs_source_t *source, - const struct obs_mouse_event *event, - bool mouse_leave); +EXPORT void obs_source_send_mouse_move(obs_source_t *source, const struct obs_mouse_event *event, bool mouse_leave); /** Sends a mouse wheel event to a source */ -EXPORT void obs_source_send_mouse_wheel(obs_source_t *source, - const struct obs_mouse_event *event, - int x_delta, int y_delta); +EXPORT void obs_source_send_mouse_wheel(obs_source_t *source, const struct obs_mouse_event *event, int x_delta, + int y_delta); /** Sends a got-focus or lost-focus event to a source */ EXPORT void obs_source_send_focus(obs_source_t *source, bool focus); /** Sends a key up/down event to a source */ -EXPORT void obs_source_send_key_click(obs_source_t *source, - const struct obs_key_event *event, - bool key_up); +EXPORT void obs_source_send_key_click(obs_source_t *source, const struct obs_key_event *event, bool key_up); /** Sets the default source flags. */ EXPORT void obs_source_set_default_flags(obs_source_t *source, uint32_t flags); @@ -1569,11 +1447,9 @@ EXPORT uint32_t obs_source_get_base_height(obs_source_t *source); EXPORT bool obs_source_audio_pending(const obs_source_t *source); EXPORT uint64_t obs_source_get_audio_timestamp(const obs_source_t *source); -EXPORT void obs_source_get_audio_mix(const obs_source_t *source, - struct obs_source_audio_mix *audio); +EXPORT void obs_source_get_audio_mix(const obs_source_t *source, struct obs_source_audio_mix *audio); -EXPORT void obs_source_set_async_unbuffered(obs_source_t *source, - bool unbuffered); +EXPORT void obs_source_set_async_unbuffered(obs_source_t *source, bool unbuffered); EXPORT bool obs_source_async_unbuffered(const obs_source_t *source); /** Used to decouple audio from video so that audio doesn't attempt to sync up @@ -1607,9 +1483,7 @@ enum obs_transition_target { OBS_TRANSITION_SOURCE_B, }; -EXPORT obs_source_t * -obs_transition_get_source(obs_source_t *transition, - enum obs_transition_target target); +EXPORT obs_source_t *obs_transition_get_source(obs_source_t *transition, enum obs_transition_target target); EXPORT void obs_transition_clear(obs_source_t *transition); EXPORT obs_source_t *obs_transition_get_active_source(obs_source_t *transition); @@ -1619,15 +1493,13 @@ enum obs_transition_mode { OBS_TRANSITION_MODE_MANUAL, }; -EXPORT bool obs_transition_start(obs_source_t *transition, - enum obs_transition_mode mode, - uint32_t duration_ms, obs_source_t *dest); +EXPORT bool obs_transition_start(obs_source_t *transition, enum obs_transition_mode mode, uint32_t duration_ms, + obs_source_t *dest); EXPORT void obs_transition_set(obs_source_t *transition, obs_source_t *source); EXPORT void obs_transition_set_manual_time(obs_source_t *transition, float t); -EXPORT void obs_transition_set_manual_torque(obs_source_t *transition, - float torque, float clamp); +EXPORT void obs_transition_set_manual_torque(obs_source_t *transition, float torque, float clamp); enum obs_transition_scale_type { OBS_TRANSITION_SCALE_MAX_ONLY, @@ -1635,19 +1507,14 @@ enum obs_transition_scale_type { OBS_TRANSITION_SCALE_STRETCH, }; -EXPORT void obs_transition_set_scale_type(obs_source_t *transition, - enum obs_transition_scale_type type); -EXPORT enum obs_transition_scale_type -obs_transition_get_scale_type(const obs_source_t *transition); +EXPORT void obs_transition_set_scale_type(obs_source_t *transition, enum obs_transition_scale_type type); +EXPORT enum obs_transition_scale_type obs_transition_get_scale_type(const obs_source_t *transition); -EXPORT void obs_transition_set_alignment(obs_source_t *transition, - uint32_t alignment); +EXPORT void obs_transition_set_alignment(obs_source_t *transition, uint32_t alignment); EXPORT uint32_t obs_transition_get_alignment(const obs_source_t *transition); -EXPORT void obs_transition_set_size(obs_source_t *transition, uint32_t cx, - uint32_t cy); -EXPORT void obs_transition_get_size(const obs_source_t *transition, - uint32_t *cx, uint32_t *cy); +EXPORT void obs_transition_set_size(obs_source_t *transition, uint32_t cx, uint32_t cy); +EXPORT void obs_transition_get_size(const obs_source_t *transition, uint32_t *cx, uint32_t *cy); /* function used by transitions */ @@ -1655,52 +1522,37 @@ EXPORT void obs_transition_get_size(const obs_source_t *transition, * Enables fixed transitions (videos or specific types of transitions that * are of fixed duration and linearly interpolated */ -EXPORT void obs_transition_enable_fixed(obs_source_t *transition, bool enable, - uint32_t duration_ms); +EXPORT void obs_transition_enable_fixed(obs_source_t *transition, bool enable, uint32_t duration_ms); EXPORT bool obs_transition_fixed(obs_source_t *transition); -typedef void (*obs_transition_video_render_callback_t)(void *data, - gs_texture_t *a, - gs_texture_t *b, float t, - uint32_t cx, - uint32_t cy); +typedef void (*obs_transition_video_render_callback_t)(void *data, gs_texture_t *a, gs_texture_t *b, float t, + uint32_t cx, uint32_t cy); typedef float (*obs_transition_audio_mix_callback_t)(void *data, float t); EXPORT float obs_transition_get_time(obs_source_t *transition); EXPORT void obs_transition_force_stop(obs_source_t *transition); -EXPORT void -obs_transition_video_render(obs_source_t *transition, - obs_transition_video_render_callback_t callback); +EXPORT void obs_transition_video_render(obs_source_t *transition, obs_transition_video_render_callback_t callback); -EXPORT void -obs_transition_video_render2(obs_source_t *transition, - obs_transition_video_render_callback_t callback, - gs_texture_t *placeholder_texture); +EXPORT void obs_transition_video_render2(obs_source_t *transition, obs_transition_video_render_callback_t callback, + gs_texture_t *placeholder_texture); -EXPORT enum gs_color_space -obs_transition_video_get_color_space(obs_source_t *transition); +EXPORT enum gs_color_space obs_transition_video_get_color_space(obs_source_t *transition); /** Directly renders its sub-source instead of to texture. Returns false if no * longer transitioning */ -EXPORT bool -obs_transition_video_render_direct(obs_source_t *transition, - enum obs_transition_target target); +EXPORT bool obs_transition_video_render_direct(obs_source_t *transition, enum obs_transition_target target); -EXPORT bool -obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, - struct obs_source_audio_mix *audio, uint32_t mixers, - size_t channels, size_t sample_rate, - obs_transition_audio_mix_callback_t mix_a_callback, - obs_transition_audio_mix_callback_t mix_b_callback); +EXPORT bool obs_transition_audio_render(obs_source_t *transition, uint64_t *ts_out, struct obs_source_audio_mix *audio, + uint32_t mixers, size_t channels, size_t sample_rate, + obs_transition_audio_mix_callback_t mix_a_callback, + obs_transition_audio_mix_callback_t mix_b_callback); /* swaps transition sources and textures as an optimization and to reduce * memory usage when switching between transitions */ -EXPORT void obs_transition_swap_begin(obs_source_t *tr_dest, - obs_source_t *tr_source); -EXPORT void obs_transition_swap_end(obs_source_t *tr_dest, - obs_source_t *tr_source); +EXPORT void obs_transition_swap_begin(obs_source_t *tr_dest, obs_source_t *tr_source); +EXPORT void obs_transition_swap_end(obs_source_t *tr_dest, obs_source_t *tr_source); /* ------------------------------------------------------------------------- */ /* Scenes */ @@ -1725,8 +1577,7 @@ enum obs_scene_duplicate_type { /** * Duplicates a scene. */ -EXPORT obs_scene_t *obs_scene_duplicate(obs_scene_t *scene, const char *name, - enum obs_scene_duplicate_type type); +EXPORT obs_scene_t *obs_scene_duplicate(obs_scene_t *scene, const char *name, enum obs_scene_duplicate_type type); EXPORT void obs_scene_release(obs_scene_t *scene); @@ -1739,14 +1590,11 @@ EXPORT obs_source_t *obs_scene_get_source(const obs_scene_t *scene); EXPORT obs_scene_t *obs_scene_from_source(const obs_source_t *source); /** Determines whether a source is within a scene */ -EXPORT obs_sceneitem_t *obs_scene_find_source(obs_scene_t *scene, - const char *name); +EXPORT obs_sceneitem_t *obs_scene_find_source(obs_scene_t *scene, const char *name); -EXPORT obs_sceneitem_t *obs_scene_find_source_recursive(obs_scene_t *scene, - const char *name); +EXPORT obs_sceneitem_t *obs_scene_find_source_recursive(obs_scene_t *scene, const char *name); -EXPORT obs_sceneitem_t *obs_scene_find_sceneitem_by_id(obs_scene_t *scene, - int64_t id); +EXPORT obs_sceneitem_t *obs_scene_find_sceneitem_by_id(obs_scene_t *scene, int64_t id); /** Gets scene by name, increments the reference */ static inline obs_scene_t *obs_get_scene_by_name(const char *name) @@ -1761,24 +1609,18 @@ static inline obs_scene_t *obs_get_scene_by_name(const char *name) } /** Enumerates sources within a scene */ -EXPORT void obs_scene_enum_items(obs_scene_t *scene, - bool (*callback)(obs_scene_t *, - obs_sceneitem_t *, void *), +EXPORT void obs_scene_enum_items(obs_scene_t *scene, bool (*callback)(obs_scene_t *, obs_sceneitem_t *, void *), void *param); -EXPORT bool obs_scene_reorder_items(obs_scene_t *scene, - obs_sceneitem_t *const *item_order, - size_t item_order_size); +EXPORT bool obs_scene_reorder_items(obs_scene_t *scene, obs_sceneitem_t *const *item_order, size_t item_order_size); struct obs_sceneitem_order_info { obs_sceneitem_t *group; obs_sceneitem_t *item; }; -EXPORT bool -obs_scene_reorder_items2(obs_scene_t *scene, - struct obs_sceneitem_order_info *item_order, - size_t item_order_size); +EXPORT bool obs_scene_reorder_items2(obs_scene_t *scene, struct obs_sceneitem_order_info *item_order, + size_t item_order_size); EXPORT bool obs_source_is_scene(const obs_source_t *source); @@ -1786,9 +1628,7 @@ EXPORT bool obs_source_is_scene(const obs_source_t *source); EXPORT obs_sceneitem_t *obs_scene_add(obs_scene_t *scene, obs_source_t *source); typedef void (*obs_scene_atomic_update_func)(void *, obs_scene_t *scene); -EXPORT void obs_scene_atomic_update(obs_scene_t *scene, - obs_scene_atomic_update_func func, - void *data); +EXPORT void obs_scene_atomic_update(obs_scene_t *scene, obs_scene_atomic_update_func func, void *data); EXPORT void obs_sceneitem_addref(obs_sceneitem_t *item); EXPORT void obs_sceneitem_release(obs_sceneitem_t *item); @@ -1806,12 +1646,10 @@ EXPORT void obs_sceneitem_save(obs_sceneitem_t *item, obs_data_array_t *arr); EXPORT void obs_sceneitem_set_id(obs_sceneitem_t *sceneitem, int64_t id); /** Tries to find the sceneitem of the source in a given scene. Returns NULL if not found */ -OBS_DEPRECATED EXPORT obs_sceneitem_t * -obs_scene_sceneitem_from_source(obs_scene_t *scene, obs_source_t *source); +OBS_DEPRECATED EXPORT obs_sceneitem_t *obs_scene_sceneitem_from_source(obs_scene_t *scene, obs_source_t *source); /** Save all the transform states for a current scene's sceneitems */ -EXPORT obs_data_t *obs_scene_save_transform_states(obs_scene_t *scene, - bool all_items); +EXPORT obs_data_t *obs_scene_save_transform_states(obs_scene_t *scene, bool all_items); /** Load all the transform states of sceneitems in that scene */ EXPORT void obs_scene_load_transform_states(const char *state); @@ -1833,70 +1671,43 @@ EXPORT bool obs_sceneitem_locked(const obs_sceneitem_t *item); EXPORT bool obs_sceneitem_set_locked(obs_sceneitem_t *item, bool lock); /* Functions for getting/setting specific orientation of a scene item */ -EXPORT void obs_sceneitem_set_pos(obs_sceneitem_t *item, - const struct vec2 *pos); -EXPORT void obs_sceneitem_set_relative_pos(obs_sceneitem_t *item, - const struct vec2 *pos); +EXPORT void obs_sceneitem_set_pos(obs_sceneitem_t *item, const struct vec2 *pos); +EXPORT void obs_sceneitem_set_relative_pos(obs_sceneitem_t *item, const struct vec2 *pos); EXPORT void obs_sceneitem_set_rot(obs_sceneitem_t *item, float rot_deg); -EXPORT void obs_sceneitem_set_scale(obs_sceneitem_t *item, - const struct vec2 *scale); -EXPORT void obs_sceneitem_set_alignment(obs_sceneitem_t *item, - uint32_t alignment); -EXPORT void obs_sceneitem_set_order(obs_sceneitem_t *item, - enum obs_order_movement movement); -EXPORT void obs_sceneitem_set_order_position(obs_sceneitem_t *item, - int position); -EXPORT void obs_sceneitem_set_bounds_type(obs_sceneitem_t *item, - enum obs_bounds_type type); -EXPORT void obs_sceneitem_set_bounds_alignment(obs_sceneitem_t *item, - uint32_t alignment); +EXPORT void obs_sceneitem_set_scale(obs_sceneitem_t *item, const struct vec2 *scale); +EXPORT void obs_sceneitem_set_alignment(obs_sceneitem_t *item, uint32_t alignment); +EXPORT void obs_sceneitem_set_order(obs_sceneitem_t *item, enum obs_order_movement movement); +EXPORT void obs_sceneitem_set_order_position(obs_sceneitem_t *item, int position); +EXPORT void obs_sceneitem_set_bounds_type(obs_sceneitem_t *item, enum obs_bounds_type type); +EXPORT void obs_sceneitem_set_bounds_alignment(obs_sceneitem_t *item, uint32_t alignment); EXPORT void obs_sceneitem_set_bounds_crop(obs_sceneitem_t *item, bool crop); -EXPORT void obs_sceneitem_set_bounds(obs_sceneitem_t *item, - const struct vec2 *bounds); -EXPORT void obs_sceneitem_set_relative_bounds(obs_sceneitem_t *item, - const struct vec2 *bounds); +EXPORT void obs_sceneitem_set_bounds(obs_sceneitem_t *item, const struct vec2 *bounds); +EXPORT void obs_sceneitem_set_relative_bounds(obs_sceneitem_t *item, const struct vec2 *bounds); EXPORT int64_t obs_sceneitem_get_id(const obs_sceneitem_t *item); -EXPORT void obs_sceneitem_get_pos(const obs_sceneitem_t *item, - struct vec2 *pos); -EXPORT void obs_sceneitem_get_relative_pos(const obs_sceneitem_t *item, - struct vec2 *pos); +EXPORT void obs_sceneitem_get_pos(const obs_sceneitem_t *item, struct vec2 *pos); +EXPORT void obs_sceneitem_get_relative_pos(const obs_sceneitem_t *item, struct vec2 *pos); EXPORT float obs_sceneitem_get_rot(const obs_sceneitem_t *item); -EXPORT void obs_sceneitem_get_scale(const obs_sceneitem_t *item, - struct vec2 *scale); +EXPORT void obs_sceneitem_get_scale(const obs_sceneitem_t *item, struct vec2 *scale); EXPORT uint32_t obs_sceneitem_get_alignment(const obs_sceneitem_t *item); -EXPORT enum obs_bounds_type -obs_sceneitem_get_bounds_type(const obs_sceneitem_t *item); +EXPORT enum obs_bounds_type obs_sceneitem_get_bounds_type(const obs_sceneitem_t *item); EXPORT uint32_t obs_sceneitem_get_bounds_alignment(const obs_sceneitem_t *item); EXPORT bool obs_sceneitem_get_bounds_crop(const obs_sceneitem_t *item); -EXPORT void obs_sceneitem_get_bounds(const obs_sceneitem_t *item, - struct vec2 *bounds); -EXPORT void obs_sceneitem_get_relative_bounds(const obs_sceneitem_t *item, - struct vec2 *bounds); +EXPORT void obs_sceneitem_get_bounds(const obs_sceneitem_t *item, struct vec2 *bounds); +EXPORT void obs_sceneitem_get_relative_bounds(const obs_sceneitem_t *item, struct vec2 *bounds); -OBS_DEPRECATED EXPORT void -obs_sceneitem_get_info(const obs_sceneitem_t *item, - struct obs_transform_info *info); -OBS_DEPRECATED EXPORT void -obs_sceneitem_set_info(obs_sceneitem_t *item, - const struct obs_transform_info *info); -EXPORT void obs_sceneitem_get_info2(const obs_sceneitem_t *item, - struct obs_transform_info *info); -EXPORT void obs_sceneitem_set_info2(obs_sceneitem_t *item, - const struct obs_transform_info *info); -EXPORT void obs_sceneitem_get_info3(const obs_sceneitem_t *item, - struct obs_transform_info *info); -EXPORT void obs_sceneitem_set_info3(obs_sceneitem_t *item, - const struct obs_transform_info *info); +OBS_DEPRECATED EXPORT void obs_sceneitem_get_info(const obs_sceneitem_t *item, struct obs_transform_info *info); +OBS_DEPRECATED EXPORT void obs_sceneitem_set_info(obs_sceneitem_t *item, const struct obs_transform_info *info); +EXPORT void obs_sceneitem_get_info2(const obs_sceneitem_t *item, struct obs_transform_info *info); +EXPORT void obs_sceneitem_set_info2(obs_sceneitem_t *item, const struct obs_transform_info *info); +EXPORT void obs_sceneitem_get_info3(const obs_sceneitem_t *item, struct obs_transform_info *info); +EXPORT void obs_sceneitem_set_info3(obs_sceneitem_t *item, const struct obs_transform_info *info); -EXPORT void obs_sceneitem_get_draw_transform(const obs_sceneitem_t *item, - struct matrix4 *transform); -EXPORT void obs_sceneitem_get_box_transform(const obs_sceneitem_t *item, - struct matrix4 *transform); -EXPORT void obs_sceneitem_get_box_scale(const obs_sceneitem_t *item, - struct vec2 *scale); +EXPORT void obs_sceneitem_get_draw_transform(const obs_sceneitem_t *item, struct matrix4 *transform); +EXPORT void obs_sceneitem_get_box_transform(const obs_sceneitem_t *item, struct matrix4 *transform); +EXPORT void obs_sceneitem_get_box_scale(const obs_sceneitem_t *item, struct vec2 *scale); EXPORT bool obs_sceneitem_visible(const obs_sceneitem_t *item); EXPORT bool obs_sceneitem_set_visible(obs_sceneitem_t *item, bool visible); @@ -1908,25 +1719,17 @@ struct obs_sceneitem_crop { int bottom; }; -EXPORT void obs_sceneitem_set_crop(obs_sceneitem_t *item, - const struct obs_sceneitem_crop *crop); -EXPORT void obs_sceneitem_get_crop(const obs_sceneitem_t *item, - struct obs_sceneitem_crop *crop); +EXPORT void obs_sceneitem_set_crop(obs_sceneitem_t *item, const struct obs_sceneitem_crop *crop); +EXPORT void obs_sceneitem_get_crop(const obs_sceneitem_t *item, struct obs_sceneitem_crop *crop); -EXPORT void obs_sceneitem_set_scale_filter(obs_sceneitem_t *item, - enum obs_scale_type filter); -EXPORT enum obs_scale_type -obs_sceneitem_get_scale_filter(obs_sceneitem_t *item); +EXPORT void obs_sceneitem_set_scale_filter(obs_sceneitem_t *item, enum obs_scale_type filter); +EXPORT enum obs_scale_type obs_sceneitem_get_scale_filter(obs_sceneitem_t *item); -EXPORT void obs_sceneitem_set_blending_method(obs_sceneitem_t *item, - enum obs_blending_method method); -EXPORT enum obs_blending_method -obs_sceneitem_get_blending_method(obs_sceneitem_t *item); +EXPORT void obs_sceneitem_set_blending_method(obs_sceneitem_t *item, enum obs_blending_method method); +EXPORT enum obs_blending_method obs_sceneitem_get_blending_method(obs_sceneitem_t *item); -EXPORT void obs_sceneitem_set_blending_mode(obs_sceneitem_t *item, - enum obs_blending_type type); -EXPORT enum obs_blending_type -obs_sceneitem_get_blending_mode(obs_sceneitem_t *item); +EXPORT void obs_sceneitem_set_blending_mode(obs_sceneitem_t *item, enum obs_blending_type type); +EXPORT enum obs_blending_type obs_sceneitem_get_blending_mode(obs_sceneitem_t *item); EXPORT void obs_sceneitem_force_update_transform(obs_sceneitem_t *item); @@ -1937,22 +1740,15 @@ EXPORT void obs_sceneitem_defer_update_end(obs_sceneitem_t *item); * automatically. Returns an incremented reference. */ EXPORT obs_data_t *obs_sceneitem_get_private_settings(obs_sceneitem_t *item); -EXPORT obs_sceneitem_t *obs_scene_add_group(obs_scene_t *scene, - const char *name); -EXPORT obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, - const char *name, - obs_sceneitem_t **items, +EXPORT obs_sceneitem_t *obs_scene_add_group(obs_scene_t *scene, const char *name); +EXPORT obs_sceneitem_t *obs_scene_insert_group(obs_scene_t *scene, const char *name, obs_sceneitem_t **items, size_t count); -EXPORT obs_sceneitem_t *obs_scene_add_group2(obs_scene_t *scene, - const char *name, bool signal); -EXPORT obs_sceneitem_t *obs_scene_insert_group2(obs_scene_t *scene, - const char *name, - obs_sceneitem_t **items, +EXPORT obs_sceneitem_t *obs_scene_add_group2(obs_scene_t *scene, const char *name, bool signal); +EXPORT obs_sceneitem_t *obs_scene_insert_group2(obs_scene_t *scene, const char *name, obs_sceneitem_t **items, size_t count, bool signal); -EXPORT obs_sceneitem_t *obs_scene_get_group(obs_scene_t *scene, - const char *name); +EXPORT obs_sceneitem_t *obs_scene_get_group(obs_scene_t *scene, const char *name); EXPORT bool obs_sceneitem_is_group(obs_sceneitem_t *item); @@ -1961,28 +1757,21 @@ EXPORT obs_scene_t *obs_sceneitem_group_get_scene(const obs_sceneitem_t *group); EXPORT void obs_sceneitem_group_ungroup(obs_sceneitem_t *group); EXPORT void obs_sceneitem_group_ungroup2(obs_sceneitem_t *group, bool signal); -EXPORT void obs_sceneitem_group_add_item(obs_sceneitem_t *group, - obs_sceneitem_t *item); -EXPORT void obs_sceneitem_group_remove_item(obs_sceneitem_t *group, - obs_sceneitem_t *item); +EXPORT void obs_sceneitem_group_add_item(obs_sceneitem_t *group, obs_sceneitem_t *item); +EXPORT void obs_sceneitem_group_remove_item(obs_sceneitem_t *group, obs_sceneitem_t *item); -EXPORT obs_sceneitem_t *obs_sceneitem_get_group(obs_scene_t *scene, - obs_sceneitem_t *item); +EXPORT obs_sceneitem_t *obs_sceneitem_get_group(obs_scene_t *scene, obs_sceneitem_t *item); EXPORT bool obs_source_is_group(const obs_source_t *source); EXPORT bool obs_scene_is_group(const obs_scene_t *scene); EXPORT void obs_sceneitem_group_enum_items(obs_sceneitem_t *group, - bool (*callback)(obs_scene_t *, - obs_sceneitem_t *, - void *), - void *param); + bool (*callback)(obs_scene_t *, obs_sceneitem_t *, void *), void *param); /** Gets the group from its source, or NULL if not a group */ EXPORT obs_scene_t *obs_group_from_source(const obs_source_t *source); -static inline obs_scene_t * -obs_group_or_scene_from_source(const obs_source_t *source) +static inline obs_scene_t *obs_group_or_scene_from_source(const obs_source_t *source) { obs_scene_t *s = obs_scene_from_source(source); return s ? s : obs_group_from_source(source); @@ -1991,20 +1780,13 @@ obs_group_or_scene_from_source(const obs_source_t *source) EXPORT void obs_sceneitem_defer_group_resize_begin(obs_sceneitem_t *item); EXPORT void obs_sceneitem_defer_group_resize_end(obs_sceneitem_t *item); -EXPORT void obs_sceneitem_set_transition(obs_sceneitem_t *item, bool show, - obs_source_t *transition); -EXPORT obs_source_t *obs_sceneitem_get_transition(obs_sceneitem_t *item, - bool show); -EXPORT void obs_sceneitem_set_transition_duration(obs_sceneitem_t *item, - bool show, - uint32_t duration_ms); -EXPORT uint32_t obs_sceneitem_get_transition_duration(obs_sceneitem_t *item, - bool show); +EXPORT void obs_sceneitem_set_transition(obs_sceneitem_t *item, bool show, obs_source_t *transition); +EXPORT obs_source_t *obs_sceneitem_get_transition(obs_sceneitem_t *item, bool show); +EXPORT void obs_sceneitem_set_transition_duration(obs_sceneitem_t *item, bool show, uint32_t duration_ms); +EXPORT uint32_t obs_sceneitem_get_transition_duration(obs_sceneitem_t *item, bool show); EXPORT void obs_sceneitem_do_transition(obs_sceneitem_t *item, bool visible); -EXPORT void obs_sceneitem_transition_load(struct obs_scene_item *item, - obs_data_t *data, bool show); -EXPORT obs_data_t *obs_sceneitem_transition_save(struct obs_scene_item *item, - bool show); +EXPORT void obs_sceneitem_transition_load(struct obs_scene_item *item, obs_data_t *data, bool show); +EXPORT obs_data_t *obs_sceneitem_transition_save(struct obs_scene_item *item, bool show); EXPORT void obs_scene_prune_sources(obs_scene_t *scene); /* ------------------------------------------------------------------------- */ @@ -2018,9 +1800,7 @@ EXPORT const char *obs_output_get_display_name(const char *id); * Outputs allow outputting to file, outputting to network, outputting to * directshow, or other custom outputs. */ -EXPORT obs_output_t *obs_output_create(const char *id, const char *name, - obs_data_t *settings, - obs_data_t *hotkey_data); +EXPORT obs_output_t *obs_output_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data); /** * Adds/releases a reference to an output. When the last reference is @@ -2035,8 +1815,7 @@ EXPORT obs_output_t *obs_output_get_ref(obs_output_t *output); EXPORT obs_weak_output_t *obs_output_get_weak_output(obs_output_t *output); EXPORT obs_output_t *obs_weak_output_get_output(obs_weak_output_t *weak); -EXPORT bool obs_weak_output_references_output(obs_weak_output_t *weak, - obs_output_t *output); +EXPORT bool obs_weak_output_references_output(obs_weak_output_t *weak, obs_output_t *output); EXPORT const char *obs_output_get_name(const obs_output_t *output); @@ -2060,8 +1839,7 @@ EXPORT void obs_output_stop(obs_output_t *output); * affect the current delay, it will only affect the next time the output is * activated. */ -EXPORT void obs_output_set_delay(obs_output_t *output, uint32_t delay_sec, - uint32_t flags); +EXPORT void obs_output_set_delay(obs_output_t *output, uint32_t delay_sec, uint32_t flags); /** Gets the currently set delay value, in seconds. */ EXPORT uint32_t obs_output_get_delay(const obs_output_t *output); @@ -2109,8 +1887,7 @@ EXPORT bool obs_output_paused(const obs_output_t *output); EXPORT obs_data_t *obs_output_get_settings(const obs_output_t *output); /** Returns the signal handler for an output */ -EXPORT signal_handler_t * -obs_output_get_signal_handler(const obs_output_t *output); +EXPORT signal_handler_t *obs_output_get_signal_handler(const obs_output_t *output); /** Returns the procedure handler for an output */ EXPORT proc_handler_t *obs_output_get_proc_handler(const obs_output_t *output); @@ -2119,8 +1896,7 @@ EXPORT proc_handler_t *obs_output_get_proc_handler(const obs_output_t *output); * Sets the current audio/video media contexts associated with this output, * required for non-encoded outputs. Can be null. */ -EXPORT void obs_output_set_media(obs_output_t *output, video_t *video, - audio_t *audio); +EXPORT void obs_output_set_media(obs_output_t *output, video_t *video, audio_t *audio); /** Returns the video media context associated with this output */ EXPORT video_t *obs_output_video(const obs_output_t *output); @@ -2144,8 +1920,7 @@ EXPORT size_t obs_output_get_mixers(const obs_output_t *output); * Sets the current video encoder associated with this output, * required for encoded outputs */ -EXPORT void obs_output_set_video_encoder(obs_output_t *output, - obs_encoder_t *encoder); +EXPORT void obs_output_set_video_encoder(obs_output_t *output, obs_encoder_t *encoder); /** * Sets the current video encoder associated with this output, @@ -2155,8 +1930,7 @@ EXPORT void obs_output_set_video_encoder(obs_output_t *output, * Only used with outputs that have multiple video outputs (FFmpeg typically), * otherwise the parameter is ignored. */ -EXPORT void obs_output_set_video_encoder2(obs_output_t *output, - obs_encoder_t *encoder, size_t idx); +EXPORT void obs_output_set_video_encoder2(obs_output_t *output, obs_encoder_t *encoder, size_t idx); /** * Sets the current audio encoder associated with this output, @@ -2166,8 +1940,7 @@ EXPORT void obs_output_set_video_encoder2(obs_output_t *output, * Only used with outputs that have multiple audio outputs (RTMP typically), * otherwise the parameter is ignored. */ -EXPORT void obs_output_set_audio_encoder(obs_output_t *output, - obs_encoder_t *encoder, size_t idx); +EXPORT void obs_output_set_audio_encoder(obs_output_t *output, obs_encoder_t *encoder, size_t idx); /** Returns the current video encoder associated with this output */ EXPORT obs_encoder_t *obs_output_get_video_encoder(const obs_output_t *output); @@ -2179,8 +1952,7 @@ EXPORT obs_encoder_t *obs_output_get_video_encoder(const obs_output_t *output); * Only used with outputs that have multiple video outputs (FFmpeg typically), * otherwise specifying an idx > 0 returns a NULL. * */ -EXPORT obs_encoder_t *obs_output_get_video_encoder2(const obs_output_t *output, - size_t idx); +EXPORT obs_encoder_t *obs_output_get_video_encoder2(const obs_output_t *output, size_t idx); /** * Returns the current audio encoder associated with this output @@ -2189,12 +1961,10 @@ EXPORT obs_encoder_t *obs_output_get_video_encoder2(const obs_output_t *output, * outputs that have multiple audio outputs, otherwise the parameter is * ignored. */ -EXPORT obs_encoder_t *obs_output_get_audio_encoder(const obs_output_t *output, - size_t idx); +EXPORT obs_encoder_t *obs_output_get_audio_encoder(const obs_output_t *output, size_t idx); /** Sets the current service associated with this output. */ -EXPORT void obs_output_set_service(obs_output_t *output, - obs_service_t *service); +EXPORT void obs_output_set_service(obs_output_t *output, obs_service_t *service); /** Gets the current service associated with this output. */ EXPORT obs_service_t *obs_output_get_service(const obs_output_t *output); @@ -2202,8 +1972,7 @@ EXPORT obs_service_t *obs_output_get_service(const obs_output_t *output); /** * Sets the reconnect settings. Set retry_count to 0 to disable reconnecting. */ -EXPORT void obs_output_set_reconnect_settings(obs_output_t *output, - int retry_count, int retry_sec); +EXPORT void obs_output_set_reconnect_settings(obs_output_t *output, int retry_count, int retry_sec); EXPORT uint64_t obs_output_get_total_bytes(const obs_output_t *output); EXPORT int obs_output_get_frames_dropped(const obs_output_t *output); @@ -2217,8 +1986,7 @@ EXPORT int obs_output_get_total_frames(const obs_output_t *output); * the encoder before the stream is started. If the encoder is already active, * then this function will trigger a warning and do nothing. */ -EXPORT void obs_output_set_preferred_size(obs_output_t *output, uint32_t width, - uint32_t height); +EXPORT void obs_output_set_preferred_size(obs_output_t *output, uint32_t width, uint32_t height); /** * Sets the preferred scaled resolution for this output. Set width and height @@ -2232,8 +2000,7 @@ EXPORT void obs_output_set_preferred_size(obs_output_t *output, uint32_t width, * Only used with outputs that have multiple video outputs (FFmpeg typically), * otherwise the parameter is ignored. */ -EXPORT void obs_output_set_preferred_size2(obs_output_t *output, uint32_t width, - uint32_t height, size_t idx); +EXPORT void obs_output_set_preferred_size2(obs_output_t *output, uint32_t width, uint32_t height, size_t idx); /** For video outputs, returns the width of the encoded image */ EXPORT uint32_t obs_output_get_width(const obs_output_t *output); @@ -2261,14 +2028,10 @@ EXPORT uint32_t obs_output_get_height2(const obs_output_t *output, size_t idx); EXPORT const char *obs_output_get_id(const obs_output_t *output); -EXPORT void obs_output_caption(obs_output_t *output, - const struct obs_source_cea_708 *captions); +EXPORT void obs_output_caption(obs_output_t *output, const struct obs_source_cea_708 *captions); -EXPORT void obs_output_output_caption_text1(obs_output_t *output, - const char *text); -EXPORT void obs_output_output_caption_text2(obs_output_t *output, - const char *text, - double display_duration); +EXPORT void obs_output_output_caption_text1(obs_output_t *output, const char *text); +EXPORT void obs_output_output_caption_text2(obs_output_t *output, const char *text, double display_duration); EXPORT float obs_output_get_congestion(obs_output_t *output); EXPORT int obs_output_get_connect_time_ms(obs_output_t *output); @@ -2276,14 +2039,11 @@ EXPORT int obs_output_get_connect_time_ms(obs_output_t *output); EXPORT bool obs_output_reconnecting(const obs_output_t *output); /** Pass a string of the last output error, for UI use */ -EXPORT void obs_output_set_last_error(obs_output_t *output, - const char *message); +EXPORT void obs_output_set_last_error(obs_output_t *output, const char *message); EXPORT const char *obs_output_get_last_error(obs_output_t *output); -EXPORT const char * -obs_output_get_supported_video_codecs(const obs_output_t *output); -EXPORT const char * -obs_output_get_supported_audio_codecs(const obs_output_t *output); +EXPORT const char *obs_output_get_supported_video_codecs(const obs_output_t *output); +EXPORT const char *obs_output_get_supported_audio_codecs(const obs_output_t *output); EXPORT const char *obs_output_get_protocols(const obs_output_t *output); @@ -2291,9 +2051,8 @@ EXPORT bool obs_is_output_protocol_registered(const char *protocol); EXPORT bool obs_enum_output_protocols(size_t idx, char **protocol); -EXPORT void obs_enum_output_types_with_protocol( - const char *protocol, void *data, - bool (*enum_cb)(void *data, const char *id)); +EXPORT void obs_enum_output_types_with_protocol(const char *protocol, void *data, + bool (*enum_cb)(void *data, const char *id)); EXPORT const char *obs_get_output_supported_video_codecs(const char *id); @@ -2306,16 +2065,14 @@ EXPORT const char *obs_get_output_supported_audio_codecs(const char *id); * keep code to a minimum and understand it is running synchronously with the * calling thread. */ -EXPORT void obs_output_add_packet_callback( - obs_output_t *output, - void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param), - void *param); -EXPORT void obs_output_remove_packet_callback( - obs_output_t *output, - void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param), - void *param); +EXPORT void obs_output_add_packet_callback(obs_output_t *output, + void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, + struct encoder_packet_time *pkt_time, void *param), + void *param); +EXPORT void obs_output_remove_packet_callback(obs_output_t *output, + void (*packet_cb)(obs_output_t *output, struct encoder_packet *pkt, + struct encoder_packet_time *pkt_time, void *param), + void *param); /* ------------------------------------------------------------------------- */ /* Functions used by outputs */ @@ -2323,26 +2080,19 @@ EXPORT void obs_output_remove_packet_callback( EXPORT void *obs_output_get_type_data(obs_output_t *output); /** Gets the video conversion info. Used only for raw output */ -EXPORT const struct video_scale_info * -obs_output_get_video_conversion(obs_output_t *output); +EXPORT const struct video_scale_info *obs_output_get_video_conversion(obs_output_t *output); /** Optionally sets the video conversion info. Used only for raw output */ -EXPORT void -obs_output_set_video_conversion(obs_output_t *output, - const struct video_scale_info *conversion); +EXPORT void obs_output_set_video_conversion(obs_output_t *output, const struct video_scale_info *conversion); /** Optionally sets the audio conversion info. Used only for raw output */ -EXPORT void -obs_output_set_audio_conversion(obs_output_t *output, - const struct audio_convert_info *conversion); +EXPORT void obs_output_set_audio_conversion(obs_output_t *output, const struct audio_convert_info *conversion); /** Returns whether data capture can begin */ -EXPORT bool obs_output_can_begin_data_capture(const obs_output_t *output, - uint32_t flags); +EXPORT bool obs_output_can_begin_data_capture(const obs_output_t *output, uint32_t flags); /** Initializes encoders (if any) */ -EXPORT bool obs_output_initialize_encoders(obs_output_t *output, - uint32_t flags); +EXPORT bool obs_output_initialize_encoders(obs_output_t *output, uint32_t flags); /** * Begins data capture from media/encoders. @@ -2378,8 +2128,7 @@ EXPORT const char *obs_encoder_get_display_name(const char *id); * @param settings Settings * @return The video encoder context, or NULL if failed or not found. */ -EXPORT obs_encoder_t *obs_video_encoder_create(const char *id, const char *name, - obs_data_t *settings, +EXPORT obs_encoder_t *obs_video_encoder_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data); /** @@ -2391,9 +2140,7 @@ EXPORT obs_encoder_t *obs_video_encoder_create(const char *id, const char *name, * @param mixer_idx Index of the mixer to use for this audio encoder * @return The video encoder context, or NULL if failed or not found. */ -EXPORT obs_encoder_t *obs_audio_encoder_create(const char *id, const char *name, - obs_data_t *settings, - size_t mixer_idx, +EXPORT obs_encoder_t *obs_audio_encoder_create(const char *id, const char *name, obs_data_t *settings, size_t mixer_idx, obs_data_t *hotkey_data); /** @@ -2409,8 +2156,7 @@ EXPORT obs_encoder_t *obs_encoder_get_ref(obs_encoder_t *encoder); EXPORT obs_weak_encoder_t *obs_encoder_get_weak_encoder(obs_encoder_t *encoder); EXPORT obs_encoder_t *obs_weak_encoder_get_encoder(obs_weak_encoder_t *weak); -EXPORT bool obs_weak_encoder_references_encoder(obs_weak_encoder_t *weak, - obs_encoder_t *encoder); +EXPORT bool obs_weak_encoder_references_encoder(obs_weak_encoder_t *weak, obs_encoder_t *encoder); EXPORT void obs_encoder_set_name(obs_encoder_t *encoder, const char *name); EXPORT const char *obs_encoder_get_name(const obs_encoder_t *encoder); @@ -2432,8 +2178,7 @@ EXPORT enum obs_encoder_type obs_encoder_get_type(const obs_encoder_t *encoder); * to disable scaling. If the encoder is active, this function will trigger * a warning, and do nothing. */ -EXPORT void obs_encoder_set_scaled_size(obs_encoder_t *encoder, uint32_t width, - uint32_t height); +EXPORT void obs_encoder_set_scaled_size(obs_encoder_t *encoder, uint32_t width, uint32_t height); /** * Enable/disable GPU based scaling for a video encoder. @@ -2441,8 +2186,7 @@ EXPORT void obs_encoder_set_scaled_size(obs_encoder_t *encoder, uint32_t width, * any other value enables GPU based scaling. If the encoder * is active, this function will trigger a warning, and do nothing. */ -EXPORT void obs_encoder_set_gpu_scale_type(obs_encoder_t *encoder, - enum obs_scale_type gpu_scale_type); +EXPORT void obs_encoder_set_gpu_scale_type(obs_encoder_t *encoder, enum obs_scale_type gpu_scale_type); /** * Set frame rate divisor for a video encoder. This allows recording at @@ -2451,8 +2195,7 @@ EXPORT void obs_encoder_set_gpu_scale_type(obs_encoder_t *encoder, * * Can only be called on stopped encoders, changing this on the fly is not supported */ -EXPORT bool obs_encoder_set_frame_rate_divisor(obs_encoder_t *encoder, - uint32_t divisor); +EXPORT bool obs_encoder_set_frame_rate_divisor(obs_encoder_t *encoder, uint32_t divisor); /** * Adds region of interest (ROI) for an encoder. This allows prioritizing @@ -2461,16 +2204,13 @@ EXPORT bool obs_encoder_set_frame_rate_divisor(obs_encoder_t *encoder, * * Returns false if the encoder does not support ROI or region is invalid. */ -EXPORT bool obs_encoder_add_roi(obs_encoder_t *encoder, - const struct obs_encoder_roi *roi); +EXPORT bool obs_encoder_add_roi(obs_encoder_t *encoder, const struct obs_encoder_roi *roi); /** For video encoders, returns true if any ROIs were set */ EXPORT bool obs_encoder_has_roi(const obs_encoder_t *encoder); /** Clear all regions */ EXPORT void obs_encoder_clear_roi(obs_encoder_t *encoder); /** Enumerate regions with callback (reverse order of addition) */ -EXPORT void obs_encoder_enum_roi(obs_encoder_t *encoder, - void (*enum_proc)(void *, - struct obs_encoder_roi *), +EXPORT void obs_encoder_enum_roi(obs_encoder_t *encoder, void (*enum_proc)(void *, struct obs_encoder_roi *), void *param); /** Get ROI increment, encoders must rebuild their ROI map if it has changed */ EXPORT uint32_t obs_encoder_get_roi_increment(const obs_encoder_t *encoder); @@ -2513,10 +2253,8 @@ EXPORT size_t obs_encoder_get_mixer_index(const obs_encoder_t *encoder); * If the format is set to VIDEO_FORMAT_NONE, will revert to the default * functionality of converting only when absolutely necessary. */ -EXPORT void obs_encoder_set_preferred_video_format(obs_encoder_t *encoder, - enum video_format format); -EXPORT enum video_format -obs_encoder_get_preferred_video_format(const obs_encoder_t *encoder); +EXPORT void obs_encoder_set_preferred_video_format(obs_encoder_t *encoder, enum video_format format); +EXPORT enum video_format obs_encoder_get_preferred_video_format(const obs_encoder_t *encoder); /** Gets the default settings for an encoder type */ EXPORT obs_data_t *obs_encoder_defaults(const char *id); @@ -2538,8 +2276,7 @@ EXPORT obs_properties_t *obs_encoder_properties(const obs_encoder_t *encoder); EXPORT void obs_encoder_update(obs_encoder_t *encoder, obs_data_t *settings); /** Gets extra data (headers) associated with this context */ -EXPORT bool obs_encoder_get_extra_data(const obs_encoder_t *encoder, - uint8_t **extra_data, size_t *size); +EXPORT bool obs_encoder_get_extra_data(const obs_encoder_t *encoder, uint8_t **extra_data, size_t *size); /** Returns the current settings for this encoder */ EXPORT obs_data_t *obs_encoder_get_settings(const obs_encoder_t *encoder); @@ -2579,19 +2316,16 @@ EXPORT const char *obs_encoder_get_id(const obs_encoder_t *encoder); EXPORT uint32_t obs_get_encoder_caps(const char *encoder_id); EXPORT uint32_t obs_encoder_get_caps(const obs_encoder_t *encoder); -EXPORT void obs_encoder_packet_ref(struct encoder_packet *dst, - struct encoder_packet *src); +EXPORT void obs_encoder_packet_ref(struct encoder_packet *dst, struct encoder_packet *src); EXPORT void obs_encoder_packet_release(struct encoder_packet *packet); -EXPORT void *obs_encoder_create_rerouted(obs_encoder_t *encoder, - const char *reroute_id); +EXPORT void *obs_encoder_create_rerouted(obs_encoder_t *encoder, const char *reroute_id); /** Returns whether encoder is paused */ EXPORT bool obs_encoder_paused(const obs_encoder_t *output); EXPORT const char *obs_encoder_get_last_error(obs_encoder_t *encoder); -EXPORT void obs_encoder_set_last_error(obs_encoder_t *encoder, - const char *message); +EXPORT void obs_encoder_set_last_error(obs_encoder_t *encoder, const char *message); EXPORT uint64_t obs_encoder_get_pause_offset(const obs_encoder_t *encoder); @@ -2601,8 +2335,7 @@ EXPORT uint64_t obs_encoder_get_pause_offset(const obs_encoder_t *encoder); * encoders within the group. Calling destroy on an active group will not actually * destroy the group until it becomes completely inactive. */ -EXPORT bool obs_encoder_set_group(obs_encoder_t *encoder, - obs_encoder_group_t *group); +EXPORT bool obs_encoder_set_group(obs_encoder_t *encoder, obs_encoder_group_t *group); EXPORT obs_encoder_group_t *obs_encoder_group_create(); EXPORT void obs_encoder_group_destroy(obs_encoder_group_t *group); @@ -2611,13 +2344,10 @@ EXPORT void obs_encoder_group_destroy(obs_encoder_group_t *group); EXPORT const char *obs_service_get_display_name(const char *id); -EXPORT obs_service_t *obs_service_create(const char *id, const char *name, - obs_data_t *settings, +EXPORT obs_service_t *obs_service_create(const char *id, const char *name, obs_data_t *settings, obs_data_t *hotkey_data); -EXPORT obs_service_t *obs_service_create_private(const char *id, - const char *name, - obs_data_t *settings); +EXPORT obs_service_t *obs_service_create_private(const char *id, const char *name, obs_data_t *settings); /** * Adds/releases a reference to a service. When the last reference is @@ -2632,8 +2362,7 @@ EXPORT obs_service_t *obs_service_get_ref(obs_service_t *service); EXPORT obs_weak_service_t *obs_service_get_weak_service(obs_service_t *service); EXPORT obs_service_t *obs_weak_service_get_service(obs_weak_service_t *weak); -EXPORT bool obs_weak_service_references_service(obs_weak_service_t *weak, - obs_service_t *service); +EXPORT bool obs_weak_service_references_service(obs_weak_service_t *weak, obs_service_t *service); EXPORT const char *obs_service_get_name(const obs_service_t *service); @@ -2664,44 +2393,35 @@ EXPORT obs_data_t *obs_service_get_settings(const obs_service_t *service); * @param video_encoder_settings Video encoder settings. Optional. * @param audio_encoder_settings Audio encoder settings. Optional. */ -EXPORT void -obs_service_apply_encoder_settings(obs_service_t *service, - obs_data_t *video_encoder_settings, - obs_data_t *audio_encoder_settings); +EXPORT void obs_service_apply_encoder_settings(obs_service_t *service, obs_data_t *video_encoder_settings, + obs_data_t *audio_encoder_settings); EXPORT void *obs_service_get_type_data(obs_service_t *service); EXPORT const char *obs_service_get_id(const obs_service_t *service); -EXPORT void obs_service_get_supported_resolutions( - const obs_service_t *service, - struct obs_service_resolution **resolutions, size_t *count); +EXPORT void obs_service_get_supported_resolutions(const obs_service_t *service, + struct obs_service_resolution **resolutions, size_t *count); EXPORT void obs_service_get_max_fps(const obs_service_t *service, int *fps); -EXPORT void obs_service_get_max_bitrate(const obs_service_t *service, - int *video_bitrate, int *audio_bitrate); +EXPORT void obs_service_get_max_bitrate(const obs_service_t *service, int *video_bitrate, int *audio_bitrate); -EXPORT const char ** -obs_service_get_supported_video_codecs(const obs_service_t *service); +EXPORT const char **obs_service_get_supported_video_codecs(const obs_service_t *service); -EXPORT const char ** -obs_service_get_supported_audio_codecs(const obs_service_t *service); +EXPORT const char **obs_service_get_supported_audio_codecs(const obs_service_t *service); /** Returns the protocol for this service context */ EXPORT const char *obs_service_get_protocol(const obs_service_t *service); -EXPORT const char * -obs_service_get_preferred_output_type(const obs_service_t *service); +EXPORT const char *obs_service_get_preferred_output_type(const obs_service_t *service); -EXPORT const char *obs_service_get_connect_info(const obs_service_t *service, - uint32_t type); +EXPORT const char *obs_service_get_connect_info(const obs_service_t *service, uint32_t type); EXPORT bool obs_service_can_try_to_connect(const obs_service_t *service); /* ------------------------------------------------------------------------- */ /* Source frame allocation functions */ -EXPORT void obs_source_frame_init(struct obs_source_frame *frame, - enum video_format format, uint32_t width, +EXPORT void obs_source_frame_init(struct obs_source_frame *frame, enum video_format format, uint32_t width, uint32_t height); static inline void obs_source_frame_free(struct obs_source_frame *frame) @@ -2712,9 +2432,8 @@ static inline void obs_source_frame_free(struct obs_source_frame *frame) } } -static inline struct obs_source_frame * -obs_source_frame_create(enum video_format format, uint32_t width, - uint32_t height) +static inline struct obs_source_frame *obs_source_frame_create(enum video_format format, uint32_t width, + uint32_t height) { struct obs_source_frame *frame; @@ -2731,8 +2450,7 @@ static inline void obs_source_frame_destroy(struct obs_source_frame *frame) } } -EXPORT void obs_source_frame_copy(struct obs_source_frame *dst, - const struct obs_source_frame *src); +EXPORT void obs_source_frame_copy(struct obs_source_frame *dst, const struct obs_source_frame *src); /* ------------------------------------------------------------------------- */ /* Get source icon type */ diff --git a/libobs/obs.hpp b/libobs/obs.hpp index 9b046ca7f..c23a040a9 100644 --- a/libobs/obs.hpp +++ b/libobs/obs.hpp @@ -27,63 +27,38 @@ template class OBSRefAutoRelease; template class OBSRef; template class OBSSafeRef; -using OBSObject = - OBSSafeRef; -using OBSSource = - OBSSafeRef; -using OBSScene = - OBSSafeRef; -using OBSSceneItem = - OBSRef; +using OBSObject = OBSSafeRef; +using OBSSource = OBSSafeRef; +using OBSScene = OBSSafeRef; +using OBSSceneItem = OBSRef; using OBSData = OBSRef; -using OBSDataArray = OBSRef; -using OBSOutput = - OBSSafeRef; -using OBSEncoder = - OBSSafeRef; -using OBSService = - OBSSafeRef; +using OBSDataArray = OBSRef; +using OBSOutput = OBSSafeRef; +using OBSEncoder = OBSSafeRef; +using OBSService = OBSSafeRef; -using OBSWeakObject = OBSRef; -using OBSWeakSource = OBSRef; -using OBSWeakOutput = OBSRef; -using OBSWeakEncoder = OBSRef; -using OBSWeakService = OBSRef; +using OBSWeakObject = OBSRef; +using OBSWeakSource = OBSRef; +using OBSWeakOutput = OBSRef; +using OBSWeakEncoder = OBSRef; +using OBSWeakService = OBSRef; #define OBS_AUTORELEASE -using OBSObjectAutoRelease = - OBSRefAutoRelease; -using OBSSourceAutoRelease = - OBSRefAutoRelease; +using OBSObjectAutoRelease = OBSRefAutoRelease; +using OBSSourceAutoRelease = OBSRefAutoRelease; using OBSSceneAutoRelease = OBSRefAutoRelease; -using OBSSceneItemAutoRelease = - OBSRefAutoRelease; +using OBSSceneItemAutoRelease = OBSRefAutoRelease; using OBSDataAutoRelease = OBSRefAutoRelease; -using OBSDataArrayAutoRelease = - OBSRefAutoRelease; -using OBSOutputAutoRelease = - OBSRefAutoRelease; -using OBSEncoderAutoRelease = - OBSRefAutoRelease; -using OBSServiceAutoRelease = - OBSRefAutoRelease; +using OBSDataArrayAutoRelease = OBSRefAutoRelease; +using OBSOutputAutoRelease = OBSRefAutoRelease; +using OBSEncoderAutoRelease = OBSRefAutoRelease; +using OBSServiceAutoRelease = OBSRefAutoRelease; -using OBSWeakObjectAutoRelease = - OBSRefAutoRelease; -using OBSWeakSourceAutoRelease = - OBSRefAutoRelease; -using OBSWeakOutputAutoRelease = - OBSRefAutoRelease; -using OBSWeakEncoderAutoRelease = - OBSRefAutoRelease; -using OBSWeakServiceAutoRelease = - OBSRefAutoRelease; +using OBSWeakObjectAutoRelease = OBSRefAutoRelease; +using OBSWeakSourceAutoRelease = OBSRefAutoRelease; +using OBSWeakOutputAutoRelease = OBSRefAutoRelease; +using OBSWeakEncoderAutoRelease = OBSRefAutoRelease; +using OBSWeakServiceAutoRelease = OBSRefAutoRelease; template class OBSRefAutoRelease { protected: @@ -93,10 +68,7 @@ public: inline OBSRefAutoRelease() : val(nullptr) {} inline OBSRefAutoRelease(T val_) : val(val_) {} OBSRefAutoRelease(const OBSRefAutoRelease &ref) = delete; - inline OBSRefAutoRelease(OBSRefAutoRelease &&ref) : val(ref.val) - { - ref.val = nullptr; - } + inline OBSRefAutoRelease(OBSRefAutoRelease &&ref) : val(ref.val) { ref.val = nullptr; } inline ~OBSRefAutoRelease() { release(val); } @@ -125,8 +97,7 @@ public: } }; -template -class OBSRef : public OBSRefAutoRelease { +template class OBSRef : public OBSRefAutoRelease { inline OBSRef &Replace(T valIn) { @@ -137,26 +108,15 @@ class OBSRef : public OBSRefAutoRelease { } struct TakeOwnership {}; - inline OBSRef(T val_, TakeOwnership) - : OBSRefAutoRelease::OBSRefAutoRelease(val_) - { - } + inline OBSRef(T val_, TakeOwnership) : OBSRefAutoRelease::OBSRefAutoRelease(val_) {} public: - inline OBSRef() - : OBSRefAutoRelease::OBSRefAutoRelease(nullptr) - { - } - inline OBSRef(const OBSRef &ref) - : OBSRefAutoRelease::OBSRefAutoRelease(ref.val) - { - addref(this->val); - } - inline OBSRef(T val_) - : OBSRefAutoRelease::OBSRefAutoRelease(val_) + inline OBSRef() : OBSRefAutoRelease::OBSRefAutoRelease(nullptr) {} + inline OBSRef(const OBSRef &ref) : OBSRefAutoRelease::OBSRefAutoRelease(ref.val) { addref(this->val); } + inline OBSRef(T val_) : OBSRefAutoRelease::OBSRefAutoRelease(val_) { addref(this->val); } inline OBSRef &operator=(const OBSRef &ref) { return Replace(ref.val); } inline OBSRef &operator=(T valIn) { return Replace(valIn); } @@ -168,8 +128,7 @@ public: friend OBSWeakService OBSGetWeakRef(obs_service_t *service); }; -template -class OBSSafeRef : public OBSRefAutoRelease { +template class OBSSafeRef : public OBSRefAutoRelease { inline OBSSafeRef &Replace(T valIn) { @@ -180,31 +139,20 @@ class OBSSafeRef : public OBSRefAutoRelease { } struct TakeOwnership {}; - inline OBSSafeRef(T val_, TakeOwnership) - : OBSRefAutoRelease::OBSRefAutoRelease(val_) - { - } + inline OBSSafeRef(T val_, TakeOwnership) : OBSRefAutoRelease::OBSRefAutoRelease(val_) {} public: - inline OBSSafeRef() - : OBSRefAutoRelease::OBSRefAutoRelease(nullptr) - { - } - inline OBSSafeRef(const OBSSafeRef &ref) - : OBSRefAutoRelease::OBSRefAutoRelease(ref.val) + inline OBSSafeRef() : OBSRefAutoRelease::OBSRefAutoRelease(nullptr) {} + inline OBSSafeRef(const OBSSafeRef &ref) : OBSRefAutoRelease::OBSRefAutoRelease(ref.val) { this->val = getref(ref.val); } - inline OBSSafeRef(T val_) - : OBSRefAutoRelease::OBSRefAutoRelease(val_) + inline OBSSafeRef(T val_) : OBSRefAutoRelease::OBSRefAutoRelease(val_) { this->val = getref(this->val); } - inline OBSSafeRef &operator=(const OBSSafeRef &ref) - { - return Replace(ref.val); - } + inline OBSSafeRef &operator=(const OBSSafeRef &ref) { return Replace(ref.val); } inline OBSSafeRef &operator=(T valIn) { return Replace(valIn); } friend OBSObject OBSGetStrongRef(obs_weak_object_t *weak); @@ -221,8 +169,7 @@ inline OBSObject OBSGetStrongRef(obs_weak_object_t *weak) inline OBSWeakObject OBSGetWeakRef(obs_object_t *object) { - return {obs_object_get_weak_object(object), - OBSWeakObject::TakeOwnership()}; + return {obs_object_get_weak_object(object), OBSWeakObject::TakeOwnership()}; } inline OBSSource OBSGetStrongRef(obs_weak_source_t *weak) @@ -232,8 +179,7 @@ inline OBSSource OBSGetStrongRef(obs_weak_source_t *weak) inline OBSWeakSource OBSGetWeakRef(obs_source_t *source) { - return {obs_source_get_weak_source(source), - OBSWeakSource::TakeOwnership()}; + return {obs_source_get_weak_source(source), OBSWeakSource::TakeOwnership()}; } inline OBSOutput OBSGetStrongRef(obs_weak_output_t *weak) @@ -243,32 +189,27 @@ inline OBSOutput OBSGetStrongRef(obs_weak_output_t *weak) inline OBSWeakOutput OBSGetWeakRef(obs_output_t *output) { - return {obs_output_get_weak_output(output), - OBSWeakOutput::TakeOwnership()}; + return {obs_output_get_weak_output(output), OBSWeakOutput::TakeOwnership()}; } inline OBSEncoder OBSGetStrongRef(obs_weak_encoder_t *weak) { - return {obs_weak_encoder_get_encoder(weak), - OBSEncoder::TakeOwnership()}; + return {obs_weak_encoder_get_encoder(weak), OBSEncoder::TakeOwnership()}; } inline OBSWeakEncoder OBSGetWeakRef(obs_encoder_t *encoder) { - return {obs_encoder_get_weak_encoder(encoder), - OBSWeakEncoder::TakeOwnership()}; + return {obs_encoder_get_weak_encoder(encoder), OBSWeakEncoder::TakeOwnership()}; } inline OBSService OBSGetStrongRef(obs_weak_service_t *weak) { - return {obs_weak_service_get_service(weak), - OBSService::TakeOwnership()}; + return {obs_weak_service_get_service(weak), OBSService::TakeOwnership()}; } inline OBSWeakService OBSGetWeakRef(obs_service_t *service) { - return {obs_service_get_weak_service(service), - OBSWeakService::TakeOwnership()}; + return {obs_service_get_weak_service(service), OBSWeakService::TakeOwnership()}; } /* objects that are not meant to be instanced */ @@ -319,16 +260,9 @@ class OBSSignal { void *param; public: - inline OBSSignal() - : handler(nullptr), - signal(nullptr), - callback(nullptr), - param(nullptr) - { - } + inline OBSSignal() : handler(nullptr), signal(nullptr), callback(nullptr), param(nullptr) {} - inline OBSSignal(signal_handler_t *handler_, const char *signal_, - signal_callback_t callback_, void *param_) + inline OBSSignal(signal_handler_t *handler_, const char *signal_, signal_callback_t callback_, void *param_) : handler(handler_), signal(signal_), callback(callback_), @@ -348,8 +282,7 @@ public: inline ~OBSSignal() { Disconnect(); } - inline void Connect(signal_handler_t *handler_, const char *signal_, - signal_callback_t callback_, void *param_) + inline void Connect(signal_handler_t *handler_, const char *signal_, signal_callback_t callback_, void *param_) { Disconnect(); diff --git a/libobs/util/apple/cfstring-utils.h b/libobs/util/apple/cfstring-utils.h index e8477409b..8dc282f4f 100644 --- a/libobs/util/apple/cfstring-utils.h +++ b/libobs/util/apple/cfstring-utils.h @@ -9,8 +9,7 @@ extern "C" { EXPORT char *cfstr_copy_cstr(CFStringRef cfstr, CFStringEncoding cfstr_enc); -EXPORT bool cfstr_copy_dstr(CFStringRef cfstr, CFStringEncoding cfstr_enc, - struct dstr *str); +EXPORT bool cfstr_copy_dstr(CFStringRef cfstr, CFStringEncoding cfstr_enc, struct dstr *str); #ifdef __cplusplus } diff --git a/libobs/util/array-serializer.c b/libobs/util/array-serializer.c index cc8094057..c35b28b7f 100644 --- a/libobs/util/array-serializer.c +++ b/libobs/util/array-serializer.c @@ -25,8 +25,7 @@ static size_t array_output_write(void *param, const void *data, size_t size) size_t new_size = output->cur_pos + size; if (new_size > output->bytes.num) { - darray_ensure_capacity(sizeof(uint8_t), - &output->bytes.da, new_size); + darray_ensure_capacity(sizeof(uint8_t), &output->bytes.da, new_size); output->bytes.num = new_size; } @@ -46,8 +45,7 @@ static int64_t array_output_get_pos(void *param) return (int64_t)data->bytes.num; } -static int64_t array_output_seek(void *param, int64_t offset, - enum serialize_seek_type seek_type) +static int64_t array_output_seek(void *param, int64_t offset, enum serialize_seek_type seek_type) { struct array_output_data *output = param; @@ -73,8 +71,7 @@ static int64_t array_output_seek(void *param, int64_t offset, return (int64_t)new_pos; } -void array_output_serializer_init(struct serializer *s, - struct array_output_data *data) +void array_output_serializer_init(struct serializer *s, struct array_output_data *data) { memset(s, 0, sizeof(struct serializer)); memset(data, 0, sizeof(struct array_output_data)); diff --git a/libobs/util/array-serializer.h b/libobs/util/array-serializer.h index 1848debe1..8393a23ad 100644 --- a/libobs/util/array-serializer.h +++ b/libobs/util/array-serializer.h @@ -28,8 +28,7 @@ struct array_output_data { size_t cur_pos; }; -EXPORT void array_output_serializer_init(struct serializer *s, - struct array_output_data *data); +EXPORT void array_output_serializer_init(struct serializer *s, struct array_output_data *data); EXPORT void array_output_serializer_free(struct array_output_data *data); EXPORT void array_output_serializer_reset(struct array_output_data *data); diff --git a/libobs/util/base.c b/libobs/util/base.c index 1800727b1..4e91dcb1d 100644 --- a/libobs/util/base.c +++ b/libobs/util/base.c @@ -24,8 +24,7 @@ static int crashing = 0; static void *log_param = NULL; static void *crash_param = NULL; -static void def_log_handler(int log_level, const char *format, va_list args, - void *param) +static void def_log_handler(int log_level, const char *format, va_list args, void *param) { char out[8192]; vsnprintf(out, sizeof(out), format, args); @@ -54,8 +53,7 @@ static void def_log_handler(int log_level, const char *format, va_list args, UNUSED_PARAMETER(param); } -OBS_NORETURN static void def_crash_handler(const char *format, va_list args, - void *param) +OBS_NORETURN static void def_crash_handler(const char *format, va_list args, void *param) { vfprintf(stderr, format, args); exit(0); @@ -83,8 +81,7 @@ void base_set_log_handler(log_handler_t handler, void *param) log_handler = handler; } -void base_set_crash_handler(void (*handler)(const char *, va_list, void *), - void *param) +void base_set_crash_handler(void (*handler)(const char *, va_list, void *), void *param) { crash_param = param; crash_handler = handler; diff --git a/libobs/util/base.h b/libobs/util/base.h index 6b0df4c08..cdead5f69 100644 --- a/libobs/util/base.h +++ b/libobs/util/base.h @@ -72,9 +72,7 @@ typedef void (*log_handler_t)(int lvl, const char *msg, va_list args, void *p); EXPORT void base_get_log_handler(log_handler_t *handler, void **param); EXPORT void base_set_log_handler(log_handler_t handler, void *param); -EXPORT void base_set_crash_handler(void (*handler)(const char *, va_list, - void *), - void *param); +EXPORT void base_set_crash_handler(void (*handler)(const char *, va_list, void *), void *param); EXPORT void blogva(int log_level, const char *format, va_list args); diff --git a/libobs/util/bitstream.c b/libobs/util/bitstream.c index 801e59cd4..040b94c8c 100644 --- a/libobs/util/bitstream.c +++ b/libobs/util/bitstream.c @@ -3,8 +3,7 @@ #include #include -void bitstream_reader_init(struct bitstream_reader *r, uint8_t *data, - size_t len) +void bitstream_reader_init(struct bitstream_reader *r, uint8_t *data, size_t len) { memset(r, 0, sizeof(struct bitstream_reader)); r->buf = data; diff --git a/libobs/util/bitstream.h b/libobs/util/bitstream.h index 9612c900c..1252f0c0f 100644 --- a/libobs/util/bitstream.h +++ b/libobs/util/bitstream.h @@ -18,8 +18,7 @@ struct bitstream_reader { size_t len; }; -EXPORT void bitstream_reader_init(struct bitstream_reader *r, uint8_t *data, - size_t len); +EXPORT void bitstream_reader_init(struct bitstream_reader *r, uint8_t *data, size_t len); EXPORT uint8_t bitstream_reader_read_bits(struct bitstream_reader *r, int bits); EXPORT uint8_t bitstream_reader_r8(struct bitstream_reader *r); EXPORT uint16_t bitstream_reader_r16(struct bitstream_reader *r); diff --git a/libobs/util/bmem.c b/libobs/util/bmem.c index b1b1f1786..a17f42eff 100644 --- a/libobs/util/bmem.c +++ b/libobs/util/bmem.c @@ -101,10 +101,9 @@ static long num_allocs = 0; void *bmalloc(size_t size) { if (!size) { - blog(LOG_ERROR, - "bmalloc: Allocating 0 bytes is broken behavior, please " - "fix your code! This will crash in future versions of " - "OBS."); + blog(LOG_ERROR, "bmalloc: Allocating 0 bytes is broken behavior, please " + "fix your code! This will crash in future versions of " + "OBS."); size = 1; } @@ -112,8 +111,7 @@ void *bmalloc(size_t size) if (!ptr) { os_breakpoint(); - bcrash("Out of memory while trying to allocate %lu bytes", - (unsigned long)size); + bcrash("Out of memory while trying to allocate %lu bytes", (unsigned long)size); } os_atomic_inc_long(&num_allocs); @@ -126,10 +124,9 @@ void *brealloc(void *ptr, size_t size) os_atomic_inc_long(&num_allocs); if (!size) { - blog(LOG_ERROR, - "brealloc: Allocating 0 bytes is broken behavior, please " - "fix your code! This will crash in future versions of " - "OBS."); + blog(LOG_ERROR, "brealloc: Allocating 0 bytes is broken behavior, please " + "fix your code! This will crash in future versions of " + "OBS."); size = 1; } @@ -137,8 +134,7 @@ void *brealloc(void *ptr, size_t size) if (!ptr) { os_breakpoint(); - bcrash("Out of memory while trying to allocate %lu bytes", - (unsigned long)size); + bcrash("Out of memory while trying to allocate %lu bytes", (unsigned long)size); } return ptr; diff --git a/libobs/util/buffered-file-serializer.c b/libobs/util/buffered-file-serializer.c index 6b65652ee..88fa1f19d 100644 --- a/libobs/util/buffered-file-serializer.c +++ b/libobs/util/buffered-file-serializer.c @@ -90,8 +90,7 @@ static void *io_thread(void *opaque) for (;;) { pthread_mutex_lock(&out->io.data_mutex); - shutting_down = os_atomic_load_bool( - &out->io.shutdown_requested); + shutting_down = os_atomic_load_bool(&out->io.shutdown_requested); // Fetch as many writes as possible from the deque // and fill up our local chunk. This may involve @@ -106,12 +105,10 @@ static void *io_thread(void *opaque) // Get seek offset and data size struct io_header header; - deque_peek_front(&out->io.data, &header, - sizeof(header)); + deque_peek_front(&out->io.data, &header, sizeof(header)); // Do we need to seek? - if (header.seek_offset != - current_seek_position) { + if (header.seek_offset != current_seek_position) { // If there's already part of a chunk pending, // flush it at the current offset. Similarly, @@ -126,26 +123,21 @@ static void *io_thread(void *opaque) next_seek_position = header.seek_offset; // Update our virtual position - current_seek_position = - header.seek_offset; + current_seek_position = header.seek_offset; } // Make sure there's enough room for the data, if // not then force a flush - if (header.data_length + chunk_used > - chunk_size) { + if (header.data_length + chunk_used > chunk_size) { force_flush_chunk = true; break; } // Remove header that we already read - deque_pop_front(&out->io.data, NULL, - sizeof(header)); + deque_pop_front(&out->io.data, NULL, sizeof(header)); // Copy from the buffer to our local chunk - deque_pop_front(&out->io.data, - chunk + chunk_used, - header.data_length); + deque_pop_front(&out->io.data, chunk + chunk_used, header.data_length); // Update offsets chunk_used += header.data_length; @@ -158,11 +150,8 @@ static void *io_thread(void *opaque) // Try to avoid lots of small writes unless this was the final // data left in the buffer. The buffer might be entirely empty // if we were woken up to exit. - if (!force_flush_chunk && - (!chunk_used || - (chunk_used < 65536 && !shutting_down))) { - os_event_reset( - out->io.new_data_available_event); + if (!force_flush_chunk && (!chunk_used || (chunk_used < 65536 && !shutting_down))) { + os_event_reset(out->io.new_data_available_event); pthread_mutex_unlock(&out->io.data_mutex); break; } @@ -171,13 +160,11 @@ static void *io_thread(void *opaque) // Seek if we need to if (want_seek) { - os_fseeki64(out->io.output_file, - next_seek_position, SEEK_SET); + os_fseeki64(out->io.output_file, next_seek_position, SEEK_SET); // Update the next virtual position, making sure to take // into account the size of the chunk we're about to write. - current_seek_position = - next_seek_position + chunk_used; + current_seek_position = next_seek_position + chunk_used; want_seek = false; @@ -190,13 +177,10 @@ static void *io_thread(void *opaque) } // Write the current chunk to the output file - size_t bytes_written = fwrite(chunk, 1, chunk_used, - out->io.output_file); + size_t bytes_written = fwrite(chunk, 1, chunk_used, out->io.output_file); if (bytes_written != chunk_used) { - blog(LOG_ERROR, - "Error writing to '%s': %s (%zu != %zu)\n", - out->filename.array, strerror(errno), - bytes_written, chunk_used); + blog(LOG_ERROR, "Error writing to '%s': %s (%zu != %zu)\n", out->filename.array, + strerror(errno), bytes_written, chunk_used); os_atomic_set_bool(&out->io.output_error, true); goto error; @@ -222,8 +206,7 @@ error: /* ========================================================================== */ /* Serializer Implementation */ -static int64_t file_output_seek(void *opaque, int64_t offset, - enum serialize_seek_type seek_type) +static int64_t file_output_seek(void *opaque, int64_t offset, enum serialize_seek_type seek_type) { struct file_output_data *out = opaque; @@ -296,8 +279,7 @@ static size_t file_output_write(void *opaque, const void *buf, size_t buf_size) } // Calculate how many chunks we can fit into the buffer - size_t num_chunks = free_space / (next_chunk_size + - sizeof(struct io_header)); + size_t num_chunks = free_space / (next_chunk_size + sizeof(struct io_header)); while (remaining && num_chunks--) { struct io_header header = { @@ -307,8 +289,7 @@ static size_t file_output_write(void *opaque, const void *buf, size_t buf_size) // Copy the data into the buffer deque_push_back(&out->io.data, &header, sizeof(header)); - deque_push_back(&out->io.data, (const void *)ptr, - next_chunk_size); + deque_push_back(&out->io.data, (const void *)ptr, next_chunk_size); // Advance the next write position out->io.next_pos += next_chunk_size; @@ -338,14 +319,12 @@ static int64_t file_output_get_pos(void *opaque) return (int64_t)out->io.next_pos; } -bool buffered_file_serializer_init_defaults(struct serializer *s, - const char *path) +bool buffered_file_serializer_init_defaults(struct serializer *s, const char *path) { return buffered_file_serializer_init(s, path, 0, 0); } -bool buffered_file_serializer_init(struct serializer *s, const char *path, - size_t max_bufsize, size_t chunk_size) +bool buffered_file_serializer_init(struct serializer *s, const char *path, size_t max_bufsize, size_t chunk_size) { struct file_output_data *out; @@ -366,8 +345,7 @@ bool buffered_file_serializer_init(struct serializer *s, const char *path, pthread_mutex_init(&out->io.data_mutex, NULL); - os_event_init(&out->io.buffer_space_available_event, - OS_EVENT_TYPE_AUTO); + os_event_init(&out->io.buffer_space_available_event, OS_EVENT_TYPE_AUTO); os_event_init(&out->io.new_data_available_event, OS_EVENT_TYPE_AUTO); pthread_create(&out->io.io_thread, NULL, io_thread, out); @@ -403,8 +381,7 @@ void buffered_file_serializer_free(struct serializer *s) pthread_mutex_destroy(&out->io.data_mutex); - blog(LOG_DEBUG, "Final buffer capacity: %zu KiB", - out->io.data.capacity / 1024); + blog(LOG_DEBUG, "Final buffer capacity: %zu KiB", out->io.data.capacity / 1024); deque_free(&out->io.data); } diff --git a/libobs/util/buffered-file-serializer.h b/libobs/util/buffered-file-serializer.h index 8a7be1a53..10350b3b7 100644 --- a/libobs/util/buffered-file-serializer.h +++ b/libobs/util/buffered-file-serializer.h @@ -22,10 +22,8 @@ extern "C" { #endif -EXPORT bool buffered_file_serializer_init_defaults(struct serializer *s, - const char *path); -EXPORT bool buffered_file_serializer_init(struct serializer *s, - const char *path, size_t max_bufsize, +EXPORT bool buffered_file_serializer_init_defaults(struct serializer *s, const char *path); +EXPORT bool buffered_file_serializer_init(struct serializer *s, const char *path, size_t max_bufsize, size_t chunk_size); EXPORT void buffered_file_serializer_free(struct serializer *s); diff --git a/libobs/util/c99defs.h b/libobs/util/c99defs.h index 46012a4a4..5a30a742c 100644 --- a/libobs/util/c99defs.h +++ b/libobs/util/c99defs.h @@ -58,13 +58,11 @@ #elif defined(__clang__) #define PRAGMA_WARN_PUSH _Pragma("clang diagnostic push") #define PRAGMA_WARN_POP _Pragma("clang diagnostic pop") -#define PRAGMA_WARN_DEPRECATION \ - _Pragma("clang diagnostic warning \"-Wdeprecated-declarations\"") +#define PRAGMA_WARN_DEPRECATION _Pragma("clang diagnostic warning \"-Wdeprecated-declarations\"") #elif defined(__GNUC__) #define PRAGMA_WARN_PUSH _Pragma("GCC diagnostic push") #define PRAGMA_WARN_POP _Pragma("GCC diagnostic pop") -#define PRAGMA_WARN_DEPRECATION \ - _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"") +#define PRAGMA_WARN_DEPRECATION _Pragma("GCC diagnostic warning \"-Wdeprecated-declarations\"") #else #define PRAGMA_WARN_PUSH #define PRAGMA_WARN_POP diff --git a/libobs/util/cf-lexer.c b/libobs/util/cf-lexer.c index d52e00d9b..0212cda39 100644 --- a/libobs/util/cf-lexer.c +++ b/libobs/util/cf-lexer.c @@ -19,8 +19,7 @@ #include "platform.h" #include "cf-lexer.h" -static inline void cf_convert_from_escape_literal(char **p_dst, - const char **p_src) +static inline void cf_convert_from_escape_literal(char **p_dst, const char **p_src) { char *dst = *p_dst; const char *src = *p_src; @@ -118,33 +117,28 @@ char *cf_literal_to_str(const char *literal, size_t count) return str; } -static bool cf_is_token_break(struct base_token *start_token, - const struct base_token *token) +static bool cf_is_token_break(struct base_token *start_token, const struct base_token *token) { switch (start_token->type) { case BASETOKEN_ALPHA: - if (token->type == BASETOKEN_OTHER || - token->type == BASETOKEN_WHITESPACE) + if (token->type == BASETOKEN_OTHER || token->type == BASETOKEN_WHITESPACE) return true; break; case BASETOKEN_DIGIT: if (token->type == BASETOKEN_WHITESPACE || - (token->type == BASETOKEN_OTHER && - *token->text.array != '.')) + (token->type == BASETOKEN_OTHER && *token->text.array != '.')) return true; break; case BASETOKEN_WHITESPACE: /* lump all non-newline whitespace together when possible */ - if (is_space_or_tab(*start_token->text.array) && - is_space_or_tab(*token->text.array)) + if (is_space_or_tab(*start_token->text.array) && is_space_or_tab(*token->text.array)) break; return true; case BASETOKEN_OTHER: - if (*start_token->text.array == '.' && - token->type == BASETOKEN_DIGIT) { + if (*start_token->text.array == '.' && token->type == BASETOKEN_DIGIT) { start_token->type = BASETOKEN_DIGIT; break; } @@ -180,8 +174,7 @@ static inline bool cf_is_comment(const char *array) return false; } -static bool cf_lexer_process_comment(struct cf_lexer *lex, - struct cf_token *out_token) +static bool cf_lexer_process_comment(struct cf_lexer *lex, struct cf_token *out_token) { const char *offset; @@ -215,16 +208,14 @@ static bool cf_lexer_process_comment(struct cf_lexer *lex, } } - out_token->unmerged_str.len += - (size_t)(offset - out_token->unmerged_str.array); + out_token->unmerged_str.len += (size_t)(offset - out_token->unmerged_str.array); out_token->type = CFTOKEN_SPACETAB; lex->base_lexer.offset = offset; return true; } -static inline void cf_lexer_write_strref(struct cf_lexer *lex, - const struct strref *ref) +static inline void cf_lexer_write_strref(struct cf_lexer *lex, const struct strref *ref) { strncpy(lex->write_offset, ref->array, ref->len); lex->write_offset[ref->len] = 0; @@ -244,8 +235,7 @@ static bool cf_lexer_is_include(struct cf_lexer *lex) continue; if (!found_include_import) { - if (strref_cmp(&token->str, "include") != 0 && - strref_cmp(&token->str, "import") != 0) + if (strref_cmp(&token->str, "include") != 0 && strref_cmp(&token->str, "import") != 0) break; found_include_import = true; @@ -265,8 +255,7 @@ static bool cf_lexer_is_include(struct cf_lexer *lex) return found_preprocessor && found_include_import; } -static void cf_lexer_getstrtoken(struct cf_lexer *lex, - struct cf_token *out_token, char delimiter, +static void cf_lexer_getstrtoken(struct cf_lexer *lex, struct cf_token *out_token, char delimiter, bool allow_escaped_delimiters) { const char *offset = lex->base_lexer.offset; @@ -297,14 +286,12 @@ static void cf_lexer_getstrtoken(struct cf_lexer *lex, } *lex->write_offset = 0; - out_token->unmerged_str.len += - (size_t)(offset - out_token->unmerged_str.array); + out_token->unmerged_str.len += (size_t)(offset - out_token->unmerged_str.array); out_token->type = CFTOKEN_STRING; lex->base_lexer.offset = offset; } -static bool cf_lexer_process_string(struct cf_lexer *lex, - struct cf_token *out_token) +static bool cf_lexer_process_string(struct cf_lexer *lex, struct cf_token *out_token) { char ch = *out_token->unmerged_str.array; @@ -313,17 +300,14 @@ static bool cf_lexer_process_string(struct cf_lexer *lex, return true; } else if (ch == '"' || ch == '\'') { - cf_lexer_getstrtoken(lex, out_token, ch, - !cf_lexer_is_include(lex)); + cf_lexer_getstrtoken(lex, out_token, ch, !cf_lexer_is_include(lex)); return true; } return false; } -static inline enum cf_token_type -cf_get_token_type(const struct cf_token *token, - const struct base_token *start_token) +static inline enum cf_token_type cf_get_token_type(const struct cf_token *token, const struct base_token *start_token) { switch (start_token->type) { case BASETOKEN_ALPHA: @@ -362,8 +346,7 @@ static bool cf_lexer_nexttoken(struct cf_lexer *lex, struct cf_token *out_token) /* ignore escaped newlines to merge spliced lines */ if (cf_is_splice(token.text.array)) { - lex->base_lexer.offset += - newline_size(token.text.array + 1); + lex->base_lexer.offset += newline_size(token.text.array + 1); continue; } @@ -393,9 +376,7 @@ static bool cf_lexer_nexttoken(struct cf_lexer *lex, struct cf_token *out_token) } if (wrote_data) { - out_token->unmerged_str.len = - (size_t)(lex->base_lexer.offset - - out_token->unmerged_str.array); + out_token->unmerged_str.len = (size_t)(lex->base_lexer.offset - out_token->unmerged_str.array); out_token->type = cf_get_token_type(out_token, &start_token); } @@ -446,8 +427,7 @@ bool cf_lexer_lex(struct cf_lexer *lex, const char *str, const char *file) lex->write_offset = lex->reformatted; while (cf_lexer_nexttoken(lex, &token)) { - if (last_token && is_space_or_tab(*last_token->str.array) && - is_space_or_tab(*token.str.array)) { + if (last_token && is_space_or_tab(*last_token->str.array) && is_space_or_tab(*token.str.array)) { cf_token_add(last_token, &token); continue; } @@ -505,8 +485,7 @@ static inline void macro_params_free(struct macro_params *params) da_free(params->params); } -static inline struct macro_param * -get_macro_param(const struct macro_params *params, const struct strref *name) +static inline struct macro_param *get_macro_param(const struct macro_params *params, const struct strref *name) { size_t i; if (!params) @@ -523,16 +502,13 @@ get_macro_param(const struct macro_params *params, const struct strref *name) /* ------------------------------------------------------------------------- */ -static bool cf_preprocessor(struct cf_preprocessor *pp, bool if_block, - struct cf_token **p_cur_token); -static void cf_preprocess_tokens(struct cf_preprocessor *pp, bool if_block, - struct cf_token **p_cur_token); +static bool cf_preprocessor(struct cf_preprocessor *pp, bool if_block, struct cf_token **p_cur_token); +static void cf_preprocess_tokens(struct cf_preprocessor *pp, bool if_block, struct cf_token **p_cur_token); static inline bool go_to_newline(struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; - while (cur_token->type != CFTOKEN_NEWLINE && - cur_token->type != CFTOKEN_NONE) + while (cur_token->type != CFTOKEN_NEWLINE && cur_token->type != CFTOKEN_NONE) cur_token++; *p_cur_token = cur_token; @@ -548,68 +524,56 @@ static inline bool next_token(struct cf_token **p_cur_token, bool preprocessor) cur_token++; /* if preprocessor, stop at newline */ - while (cur_token->type == CFTOKEN_SPACETAB && - (preprocessor || cur_token->type == CFTOKEN_NEWLINE)) + while (cur_token->type == CFTOKEN_SPACETAB && (preprocessor || cur_token->type == CFTOKEN_NEWLINE)) cur_token++; *p_cur_token = cur_token; return cur_token->type != CFTOKEN_NONE; } -static inline void cf_gettokenoffset(struct cf_preprocessor *pp, - const struct cf_token *token, - uint32_t *row, uint32_t *col) +static inline void cf_gettokenoffset(struct cf_preprocessor *pp, const struct cf_token *token, uint32_t *row, + uint32_t *col) { - lexer_getstroffset(&pp->lex->base_lexer, token->unmerged_str.array, row, - col); + lexer_getstroffset(&pp->lex->base_lexer, token->unmerged_str.array, row, col); } -static void cf_addew(struct cf_preprocessor *pp, const struct cf_token *token, - const char *message, int error_level, const char *val1, - const char *val2, const char *val3) +static void cf_addew(struct cf_preprocessor *pp, const struct cf_token *token, const char *message, int error_level, + const char *val1, const char *val2, const char *val3) { uint32_t row, col; cf_gettokenoffset(pp, token, &row, &col); if (!val1 && !val2 && !val3) { - error_data_add(pp->ed, token->lex->file, row, col, message, - error_level); + error_data_add(pp->ed, token->lex->file, row, col, message, error_level); } else { struct dstr formatted; dstr_init(&formatted); dstr_safe_printf(&formatted, message, val1, val2, val3, NULL); - error_data_add(pp->ed, token->lex->file, row, col, - formatted.array, error_level); + error_data_add(pp->ed, token->lex->file, row, col, formatted.array, error_level); dstr_free(&formatted); } } -static inline void cf_adderror(struct cf_preprocessor *pp, - const struct cf_token *token, const char *error, - const char *val1, const char *val2, - const char *val3) +static inline void cf_adderror(struct cf_preprocessor *pp, const struct cf_token *token, const char *error, + const char *val1, const char *val2, const char *val3) { cf_addew(pp, token, error, LEX_ERROR, val1, val2, val3); } -static inline void cf_addwarning(struct cf_preprocessor *pp, - const struct cf_token *token, - const char *warning, const char *val1, - const char *val2, const char *val3) +static inline void cf_addwarning(struct cf_preprocessor *pp, const struct cf_token *token, const char *warning, + const char *val1, const char *val2, const char *val3) { cf_addew(pp, token, warning, LEX_WARNING, val1, val2, val3); } -static inline void cf_adderror_expecting(struct cf_preprocessor *pp, - const struct cf_token *token, +static inline void cf_adderror_expecting(struct cf_preprocessor *pp, const struct cf_token *token, const char *expecting) { cf_adderror(pp, token, "Expected $1", expecting, NULL, NULL); } -static inline void cf_adderror_expected_newline(struct cf_preprocessor *pp, - const struct cf_token *token) +static inline void cf_adderror_expected_newline(struct cf_preprocessor *pp, const struct cf_token *token) { cf_adderror(pp, token, "Unexpected token after preprocessor, expected " @@ -617,22 +581,17 @@ static inline void cf_adderror_expected_newline(struct cf_preprocessor *pp, NULL, NULL, NULL); } -static inline void -cf_adderror_unexpected_endif_eof(struct cf_preprocessor *pp, - const struct cf_token *token) +static inline void cf_adderror_unexpected_endif_eof(struct cf_preprocessor *pp, const struct cf_token *token) { - cf_adderror(pp, token, "Unexpected end of file before #endif", NULL, - NULL, NULL); + cf_adderror(pp, token, "Unexpected end of file before #endif", NULL, NULL, NULL); } -static inline void cf_adderror_unexpected_eof(struct cf_preprocessor *pp, - const struct cf_token *token) +static inline void cf_adderror_unexpected_eof(struct cf_preprocessor *pp, const struct cf_token *token) { cf_adderror(pp, token, "Unexpected end of file", NULL, NULL, NULL); } -static inline void insert_path(struct cf_preprocessor *pp, - struct dstr *str_file) +static inline void insert_path(struct cf_preprocessor *pp, struct dstr *str_file) { const char *file; const char *slash; @@ -649,8 +608,7 @@ static inline void insert_path(struct cf_preprocessor *pp, } } -static void cf_include_file(struct cf_preprocessor *pp, - const struct cf_token *file_token) +static void cf_include_file(struct cf_preprocessor *pp, const struct cf_token *file_token) { struct cf_lexer new_lex; struct dstr str_file; @@ -677,8 +635,7 @@ static void cf_include_file(struct cf_preprocessor *pp, file = os_fopen(str_file.array, "rb"); if (!file) { - cf_adderror(pp, file_token, "Could not open file '$1'", - file_token->str.array, NULL, NULL); + cf_adderror(pp, file_token, "Could not open file '$1'", file_token->str.array, NULL, NULL); goto exit; } @@ -699,18 +656,15 @@ exit: static inline bool is_sys_include(struct strref *ref) { - return ref->len >= 2 && ref->array[0] == '<' && - ref->array[ref->len - 1] == '>'; + return ref->len >= 2 && ref->array[0] == '<' && ref->array[ref->len - 1] == '>'; } static inline bool is_loc_include(struct strref *ref) { - return ref->len >= 2 && ref->array[0] == '"' && - ref->array[ref->len - 1] == '"'; + return ref->len >= 2 && ref->array[0] == '"' && ref->array[ref->len - 1] == '"'; } -static void cf_preprocess_include(struct cf_preprocessor *pp, - struct cf_token **p_cur_token) +static void cf_preprocess_include(struct cf_preprocessor *pp, struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; @@ -733,8 +687,7 @@ static void cf_preprocess_include(struct cf_preprocessor *pp, if (!pp->ignore_state) cf_include_file(pp, cur_token); } else { - cf_adderror(pp, cur_token, "Invalid or incomplete string", NULL, - NULL, NULL); + cf_adderror(pp, cur_token, "Invalid or incomplete string", NULL, NULL, NULL); go_to_newline(&cur_token); goto exit; } @@ -745,9 +698,7 @@ exit: *p_cur_token = cur_token; } -static bool cf_preprocess_macro_params(struct cf_preprocessor *pp, - struct cf_def *def, - struct cf_token **p_cur_token) +static bool cf_preprocess_macro_params(struct cf_preprocessor *pp, struct cf_def *def, struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; bool success = false; @@ -765,8 +716,7 @@ static bool cf_preprocess_macro_params(struct cf_preprocessor *pp, next_token(&cur_token, true); if (cur_token->type != CFTOKEN_OTHER || - (*cur_token->str.array != ',' && - *cur_token->str.array != ')')) { + (*cur_token->str.array != ',' && *cur_token->str.array != ')')) { cf_adderror_expecting(pp, cur_token, "',' or ')'"); go_to_newline(&cur_token); @@ -785,8 +735,7 @@ exit: #define INVALID_INDEX ((size_t)-1) -static inline size_t cf_preprocess_get_def_idx(struct cf_preprocessor *pp, - const struct strref *def_name) +static inline size_t cf_preprocess_get_def_idx(struct cf_preprocessor *pp, const struct strref *def_name) { struct cf_def *array = pp->defines.array; size_t i; @@ -801,8 +750,7 @@ static inline size_t cf_preprocess_get_def_idx(struct cf_preprocessor *pp, return INVALID_INDEX; } -static inline struct cf_def * -cf_preprocess_get_def(struct cf_preprocessor *pp, const struct strref *def_name) +static inline struct cf_def *cf_preprocess_get_def(struct cf_preprocessor *pp, const struct strref *def_name) { size_t idx = cf_preprocess_get_def_idx(pp, def_name); if (idx == INVALID_INDEX) @@ -813,9 +761,7 @@ cf_preprocess_get_def(struct cf_preprocessor *pp, const struct strref *def_name) static char space_filler[2] = " "; -static inline void append_space(struct cf_preprocessor *pp, - cf_token_array_t *tokens, - const struct cf_token *base) +static inline void append_space(struct cf_preprocessor *pp, cf_token_array_t *tokens, const struct cf_token *base) { struct cf_token token; @@ -839,8 +785,7 @@ static inline void append_end_token(cf_token_array_t *tokens) da_push_back(*tokens, &end); } -static void cf_preprocess_define(struct cf_preprocessor *pp, - struct cf_token **p_cur_token) +static void cf_preprocess_define(struct cf_preprocessor *pp, struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; struct cf_def def; @@ -871,8 +816,7 @@ static void cf_preprocess_define(struct cf_preprocessor *pp, goto error; } - while (cur_token->type != CFTOKEN_NEWLINE && - cur_token->type != CFTOKEN_NONE) + while (cur_token->type != CFTOKEN_NEWLINE && cur_token->type != CFTOKEN_NONE) cf_def_addtoken(&def, cur_token++); complete: @@ -888,8 +832,7 @@ exit: *p_cur_token = cur_token; } -static inline void cf_preprocess_remove_def_strref(struct cf_preprocessor *pp, - const struct strref *ref) +static inline void cf_preprocess_remove_def_strref(struct cf_preprocessor *pp, const struct strref *ref) { size_t def_idx = cf_preprocess_get_def_idx(pp, ref); if (def_idx != INVALID_INDEX) { @@ -899,8 +842,7 @@ static inline void cf_preprocess_remove_def_strref(struct cf_preprocessor *pp, } } -static void cf_preprocess_undef(struct cf_preprocessor *pp, - struct cf_token **p_cur_token) +static void cf_preprocess_undef(struct cf_preprocessor *pp, struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; @@ -924,9 +866,7 @@ exit: } /* Processes an #ifdef/#ifndef/#if/#else/#elif sub block recursively */ -static inline bool cf_preprocess_subblock(struct cf_preprocessor *pp, - bool ignore, - struct cf_token **p_cur_token) +static inline bool cf_preprocess_subblock(struct cf_preprocessor *pp, bool ignore, struct cf_token **p_cur_token) { bool eof; @@ -947,8 +887,7 @@ static inline bool cf_preprocess_subblock(struct cf_preprocessor *pp, return !eof; } -static void cf_preprocess_ifdef(struct cf_preprocessor *pp, bool ifnot, - struct cf_token **p_cur_token) +static void cf_preprocess_ifdef(struct cf_preprocessor *pp, bool ifnot, struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; struct cf_def *def; @@ -979,8 +918,7 @@ exit: *p_cur_token = cur_token; } -static bool cf_preprocessor(struct cf_preprocessor *pp, bool if_block, - struct cf_token **p_cur_token) +static bool cf_preprocessor(struct cf_preprocessor *pp, bool if_block, struct cf_token **p_cur_token) { struct cf_token *cur_token = *p_cur_token; @@ -1019,8 +957,7 @@ static bool cf_preprocessor(struct cf_preprocessor *pp, bool if_block, return false; - } else if (cur_token->type != CFTOKEN_NEWLINE && - cur_token->type != CFTOKEN_NONE) { + } else if (cur_token->type != CFTOKEN_NEWLINE && cur_token->type != CFTOKEN_NONE) { /* * TODO: language-specific preprocessor stuff should be sent to * handler of some sort @@ -1031,11 +968,8 @@ static bool cf_preprocessor(struct cf_preprocessor *pp, bool if_block, return true; } -static void cf_preprocess_addtoken(struct cf_preprocessor *pp, - cf_token_array_t *dst, - struct cf_token **p_cur_token, - const struct cf_token *base, - const struct macro_params *params); +static void cf_preprocess_addtoken(struct cf_preprocessor *pp, cf_token_array_t *dst, struct cf_token **p_cur_token, + const struct cf_token *base, const struct macro_params *params); /* * collects tokens for a macro parameter @@ -1044,10 +978,9 @@ static void cf_preprocess_addtoken(struct cf_preprocessor *pp, * within a macro parameter is preserved, example MACRO(func(1, 2), 3), do not * let it stop on the comma at "1," */ -static void cf_preprocess_save_macro_param( - struct cf_preprocessor *pp, struct cf_token **p_cur_token, - struct macro_param *param, const struct cf_token *base, - const struct macro_params *cur_params) +static void cf_preprocess_save_macro_param(struct cf_preprocessor *pp, struct cf_token **p_cur_token, + struct macro_param *param, const struct cf_token *base, + const struct macro_params *cur_params) { struct cf_token *cur_token = *p_cur_token; int brace_count = 0; @@ -1067,8 +1000,7 @@ static void cf_preprocess_save_macro_param( break; } - cf_preprocess_addtoken(pp, ¶m->tokens, &cur_token, base, - cur_params); + cf_preprocess_addtoken(pp, ¶m->tokens, &cur_token, base, cur_params); } if (cur_token->type == CFTOKEN_NONE) @@ -1086,8 +1018,7 @@ static inline bool param_is_whitespace(const struct macro_param *param) size_t i; for (i = 0; i < param->tokens.num; i++) - if (array[i].type != CFTOKEN_NONE && - array[i].type != CFTOKEN_SPACETAB && + if (array[i].type != CFTOKEN_NONE && array[i].type != CFTOKEN_SPACETAB && array[i].type != CFTOKEN_NEWLINE) return false; @@ -1095,10 +1026,9 @@ static inline bool param_is_whitespace(const struct macro_param *param) } /* collects parameter tokens of a used macro and stores them for the unwrap */ -static void cf_preprocess_save_macro_params( - struct cf_preprocessor *pp, struct cf_token **p_cur_token, - const struct cf_def *def, const struct cf_token *base, - const struct macro_params *cur_params, struct macro_params *dst) +static void cf_preprocess_save_macro_params(struct cf_preprocessor *pp, struct cf_token **p_cur_token, + const struct cf_def *def, const struct cf_token *base, + const struct macro_params *cur_params, struct macro_params *dst) { struct cf_token *cur_token = *p_cur_token; size_t count = 0; @@ -1115,11 +1045,9 @@ static void cf_preprocess_save_macro_params( cur_token++; count++; - cf_preprocess_save_macro_param(pp, &cur_token, ¶m, base, - cur_params); + cf_preprocess_save_macro_param(pp, &cur_token, ¶m, base, cur_params); if (cur_token->type != CFTOKEN_OTHER || - (*cur_token->str.array != ',' && - *cur_token->str.array != ')')) { + (*cur_token->str.array != ',' && *cur_token->str.array != ')')) { macro_param_free(¶m); cf_adderror_expecting(pp, cur_token, "',' or ')'"); @@ -1128,16 +1056,14 @@ static void cf_preprocess_save_macro_params( if (param_is_whitespace(¶m)) { /* if 0-param macro, ignore first entry */ - if (count == 1 && !def->params.num && - *cur_token->str.array == ')') { + if (count == 1 && !def->params.num && *cur_token->str.array == ')') { macro_param_free(¶m); break; } } if (count <= def->params.num) { - cf_token_copy(¶m.name, - cf_def_getparam(def, count - 1)); + cf_token_copy(¶m.name, cf_def_getparam(def, count - 1)); da_push_back(dst->params, ¶m); } else { macro_param_free(¶m); @@ -1145,18 +1071,14 @@ static void cf_preprocess_save_macro_params( } while (*cur_token->str.array != ')'); if (count != def->params.num) - cf_adderror(pp, cur_token, - "Mismatching number of macro parameters", NULL, - NULL, NULL); + cf_adderror(pp, cur_token, "Mismatching number of macro parameters", NULL, NULL, NULL); exit: *p_cur_token = cur_token; } -static inline void cf_preprocess_unwrap_param(struct cf_preprocessor *pp, - cf_token_array_t *dst, - struct cf_token **p_cur_token, - const struct cf_token *base, +static inline void cf_preprocess_unwrap_param(struct cf_preprocessor *pp, cf_token_array_t *dst, + struct cf_token **p_cur_token, const struct cf_token *base, const struct macro_param *param) { struct cf_token *cur_token = *p_cur_token; @@ -1169,10 +1091,9 @@ static inline void cf_preprocess_unwrap_param(struct cf_preprocessor *pp, *p_cur_token = cur_token; } -static inline void cf_preprocess_unwrap_define( - struct cf_preprocessor *pp, cf_token_array_t *dst, - struct cf_token **p_cur_token, const struct cf_token *base, - const struct cf_def *def, const struct macro_params *cur_params) +static inline void cf_preprocess_unwrap_define(struct cf_preprocessor *pp, cf_token_array_t *dst, + struct cf_token **p_cur_token, const struct cf_token *base, + const struct cf_def *def, const struct macro_params *cur_params) { struct cf_token *cur_token = *p_cur_token; struct macro_params new_params; @@ -1181,12 +1102,10 @@ static inline void cf_preprocess_unwrap_define( macro_params_init(&new_params); if (def->macro) - cf_preprocess_save_macro_params(pp, &cur_token, def, base, - cur_params, &new_params); + cf_preprocess_save_macro_params(pp, &cur_token, def, base, cur_params, &new_params); while (cur_def_token->type != CFTOKEN_NONE) - cf_preprocess_addtoken(pp, dst, &cur_def_token, base, - &new_params); + cf_preprocess_addtoken(pp, dst, &cur_def_token, base, &new_params); macro_params_free(&new_params); @@ -1194,11 +1113,8 @@ static inline void cf_preprocess_unwrap_define( *p_cur_token = cur_token; } -static void cf_preprocess_addtoken(struct cf_preprocessor *pp, - cf_token_array_t *dst, - struct cf_token **p_cur_token, - const struct cf_token *base, - const struct macro_params *params) +static void cf_preprocess_addtoken(struct cf_preprocessor *pp, cf_token_array_t *dst, struct cf_token **p_cur_token, + const struct cf_token *base, const struct macro_params *params) { struct cf_token *cur_token = *p_cur_token; @@ -1214,15 +1130,13 @@ static void cf_preprocess_addtoken(struct cf_preprocessor *pp, param = get_macro_param(params, &cur_token->str); if (param) { - cf_preprocess_unwrap_param(pp, dst, &cur_token, base, - param); + cf_preprocess_unwrap_param(pp, dst, &cur_token, base, param); goto exit; } def = cf_preprocess_get_def(pp, &cur_token->str); if (def) { - cf_preprocess_unwrap_define(pp, dst, &cur_token, base, - def, params); + cf_preprocess_unwrap_define(pp, dst, &cur_token, base, def, params); goto exit; } } @@ -1236,16 +1150,14 @@ exit: *p_cur_token = cur_token; } -static void cf_preprocess_tokens(struct cf_preprocessor *pp, bool if_block, - struct cf_token **p_cur_token) +static void cf_preprocess_tokens(struct cf_preprocessor *pp, bool if_block, struct cf_token **p_cur_token) { bool newline = true; bool preprocessor_line = if_block; struct cf_token *cur_token = *p_cur_token; while (cur_token->type != CFTOKEN_NONE) { - if (cur_token->type != CFTOKEN_SPACETAB && - cur_token->type != CFTOKEN_NEWLINE) { + if (cur_token->type != CFTOKEN_SPACETAB && cur_token->type != CFTOKEN_NEWLINE) { if (preprocessor_line) { cf_adderror_expected_newline(pp, cur_token); if (!go_to_newline(&cur_token)) @@ -1312,8 +1224,7 @@ void cf_preprocessor_free(struct cf_preprocessor *pp) pp->ignore_state = false; } -bool cf_preprocess(struct cf_preprocessor *pp, struct cf_lexer *lex, - struct error_data *ed) +bool cf_preprocess(struct cf_preprocessor *pp, struct cf_lexer *lex, struct error_data *ed) { struct cf_token *token = cf_lexer_get_tokens(lex); if (!token) @@ -1334,11 +1245,8 @@ void cf_preprocessor_add_def(struct cf_preprocessor *pp, struct cf_def *def) if (existing) { struct dstr name; dstr_init_copy_strref(&name, &def->name.str); - cf_addwarning(pp, &def->name, "Token $1 already defined", - name.array, NULL, NULL); - cf_addwarning(pp, &existing->name, - "Previous definition of $1 is here", name.array, - NULL, NULL); + cf_addwarning(pp, &def->name, "Token $1 already defined", name.array, NULL, NULL); + cf_addwarning(pp, &existing->name, "Previous definition of $1 is here", name.array, NULL, NULL); cf_def_free(existing); memcpy(existing, def, sizeof(struct cf_def)); @@ -1347,8 +1255,7 @@ void cf_preprocessor_add_def(struct cf_preprocessor *pp, struct cf_def *def) } } -void cf_preprocessor_remove_def(struct cf_preprocessor *pp, - const char *def_name) +void cf_preprocessor_remove_def(struct cf_preprocessor *pp, const char *def_name) { struct strref ref; ref.array = def_name; diff --git a/libobs/util/cf-lexer.h b/libobs/util/cf-lexer.h index 8d631da7d..be8f4748e 100644 --- a/libobs/util/cf-lexer.h +++ b/libobs/util/cf-lexer.h @@ -58,14 +58,12 @@ static inline void cf_token_clear(struct cf_token *t) memset(t, 0, sizeof(struct cf_token)); } -static inline void cf_token_copy(struct cf_token *dst, - const struct cf_token *src) +static inline void cf_token_copy(struct cf_token *dst, const struct cf_token *src) { memcpy(dst, src, sizeof(struct cf_token)); } -static inline void cf_token_add(struct cf_token *dst, - const struct cf_token *add) +static inline void cf_token_add(struct cf_token *dst, const struct cf_token *add) { strref_add(&dst->str, &add->str); strref_add(&dst->unmerged_str, &add->unmerged_str); @@ -100,8 +98,7 @@ static inline struct cf_token *cf_lexer_get_tokens(struct cf_lexer *lex) return lex->tokens.array; } -EXPORT bool cf_lexer_lex(struct cf_lexer *lex, const char *str, - const char *file); +EXPORT bool cf_lexer_lex(struct cf_lexer *lex, const char *str, const char *file); /* ------------------------------------------------------------------------- */ /* c-family preprocessor definition */ @@ -131,8 +128,7 @@ static inline void cf_def_addtoken(struct cf_def *cfd, struct cf_token *token) da_push_back(cfd->tokens, token); } -static inline struct cf_token *cf_def_getparam(const struct cf_def *cfd, - size_t idx) +static inline struct cf_token *cf_def_getparam(const struct cf_def *cfd, size_t idx) { return cfd->params.array + idx; } @@ -181,25 +177,19 @@ struct cf_preprocessor { EXPORT void cf_preprocessor_init(struct cf_preprocessor *pp); EXPORT void cf_preprocessor_free(struct cf_preprocessor *pp); -EXPORT bool cf_preprocess(struct cf_preprocessor *pp, struct cf_lexer *lex, - struct error_data *ed); +EXPORT bool cf_preprocess(struct cf_preprocessor *pp, struct cf_lexer *lex, struct error_data *ed); -static inline void -cf_preprocessor_add_sys_include_dir(struct cf_preprocessor *pp, - const char *include_dir) +static inline void cf_preprocessor_add_sys_include_dir(struct cf_preprocessor *pp, const char *include_dir) { char *str = bstrdup(include_dir); if (include_dir) da_push_back(pp->sys_include_dirs, &str); } -EXPORT void cf_preprocessor_add_def(struct cf_preprocessor *pp, - struct cf_def *def); -EXPORT void cf_preprocessor_remove_def(struct cf_preprocessor *pp, - const char *def_name); +EXPORT void cf_preprocessor_add_def(struct cf_preprocessor *pp, struct cf_def *def); +EXPORT void cf_preprocessor_remove_def(struct cf_preprocessor *pp, const char *def_name); -static inline struct cf_token * -cf_preprocessor_get_tokens(struct cf_preprocessor *pp) +static inline struct cf_token *cf_preprocessor_get_tokens(struct cf_preprocessor *pp) { return pp->tokens.array; } diff --git a/libobs/util/cf-parser.c b/libobs/util/cf-parser.c index 944b4a48e..ccfc3e4a0 100644 --- a/libobs/util/cf-parser.c +++ b/libobs/util/cf-parser.c @@ -16,23 +16,20 @@ #include "cf-parser.h" -void cf_adderror(struct cf_parser *p, const char *error, int level, - const char *val1, const char *val2, const char *val3) +void cf_adderror(struct cf_parser *p, const char *error, int level, const char *val1, const char *val2, + const char *val3) { uint32_t row, col; - lexer_getstroffset(&p->cur_token->lex->base_lexer, - p->cur_token->unmerged_str.array, &row, &col); + lexer_getstroffset(&p->cur_token->lex->base_lexer, p->cur_token->unmerged_str.array, &row, &col); if (!val1 && !val2 && !val3) { - error_data_add(&p->error_list, p->cur_token->lex->file, row, - col, error, level); + error_data_add(&p->error_list, p->cur_token->lex->file, row, col, error, level); } else { struct dstr formatted; dstr_init(&formatted); dstr_safe_printf(&formatted, error, val1, val2, val3, NULL); - error_data_add(&p->error_list, p->cur_token->lex->file, row, - col, formatted.array, level); + error_data_add(&p->error_list, p->cur_token->lex->file, row, col, formatted.array, level); dstr_free(&formatted); } @@ -40,8 +37,7 @@ void cf_adderror(struct cf_parser *p, const char *error, int level, bool cf_pass_pair(struct cf_parser *p, char in, char out) { - if (p->cur_token->type != CFTOKEN_OTHER || - *p->cur_token->str.array != in) + if (p->cur_token->type != CFTOKEN_OTHER || *p->cur_token->str.array != in) return p->cur_token->type != CFTOKEN_NONE; p->cur_token++; diff --git a/libobs/util/cf-parser.h b/libobs/util/cf-parser.h index 9f5d63600..30c399635 100644 --- a/libobs/util/cf-parser.h +++ b/libobs/util/cf-parser.h @@ -63,8 +63,7 @@ static inline void cf_parser_free(struct cf_parser *parser) parser->cur_token = NULL; } -static inline bool cf_parser_parse(struct cf_parser *parser, const char *str, - const char *file) +static inline bool cf_parser_parse(struct cf_parser *parser, const char *str, const char *file) { if (!cf_lexer_lex(&parser->lex, str, file)) return false; @@ -76,11 +75,10 @@ static inline bool cf_parser_parse(struct cf_parser *parser, const char *str, return true; } -EXPORT void cf_adderror(struct cf_parser *parser, const char *error, int level, - const char *val1, const char *val2, const char *val3); +EXPORT void cf_adderror(struct cf_parser *parser, const char *error, int level, const char *val1, const char *val2, + const char *val3); -static inline void cf_adderror_expecting(struct cf_parser *p, - const char *expected) +static inline void cf_adderror_expecting(struct cf_parser *p, const char *expected) { cf_adderror(p, "Expected '$1'", LEX_ERROR, expected, NULL, NULL); } @@ -97,13 +95,11 @@ static inline void cf_adderror_syntax_error(struct cf_parser *p) static inline bool cf_next_token(struct cf_parser *p) { - if (p->cur_token->type != CFTOKEN_SPACETAB && - p->cur_token->type != CFTOKEN_NEWLINE && + if (p->cur_token->type != CFTOKEN_SPACETAB && p->cur_token->type != CFTOKEN_NEWLINE && p->cur_token->type != CFTOKEN_NONE) p->cur_token++; - while (p->cur_token->type == CFTOKEN_SPACETAB || - p->cur_token->type == CFTOKEN_NEWLINE) + while (p->cur_token->type == CFTOKEN_SPACETAB || p->cur_token->type == CFTOKEN_NEWLINE) p->cur_token++; return p->cur_token->type != CFTOKEN_NONE; @@ -121,8 +117,7 @@ static inline bool cf_next_valid_token(struct cf_parser *p) EXPORT bool cf_pass_pair(struct cf_parser *p, char in, char out); -static inline bool cf_go_to_token(struct cf_parser *p, const char *str1, - const char *str2) +static inline bool cf_go_to_token(struct cf_parser *p, const char *str1, const char *str2) { while (cf_next_token(p)) { if (strref_cmp(&p->cur_token->str, str1) == 0) { @@ -138,8 +133,7 @@ static inline bool cf_go_to_token(struct cf_parser *p, const char *str1, return false; } -static inline bool cf_go_to_valid_token(struct cf_parser *p, const char *str1, - const char *str2) +static inline bool cf_go_to_valid_token(struct cf_parser *p, const char *str1, const char *str2) { if (!cf_go_to_token(p, str1, str2)) { cf_adderror_unexpected_eof(p); @@ -149,8 +143,7 @@ static inline bool cf_go_to_valid_token(struct cf_parser *p, const char *str1, return true; } -static inline bool cf_go_to_token_type(struct cf_parser *p, - enum cf_token_type type) +static inline bool cf_go_to_token_type(struct cf_parser *p, enum cf_token_type type) { while (p->cur_token->type != CFTOKEN_NONE && p->cur_token->type != type) p->cur_token++; @@ -158,8 +151,7 @@ static inline bool cf_go_to_token_type(struct cf_parser *p, return p->cur_token->type != CFTOKEN_NONE; } -static inline int cf_token_should_be(struct cf_parser *p, const char *str, - const char *goto1, const char *goto2) +static inline int cf_token_should_be(struct cf_parser *p, const char *str, const char *goto1, const char *goto2) { if (strref_cmp(&p->cur_token->str, str) == 0) return PARSE_SUCCESS; @@ -173,8 +165,7 @@ static inline int cf_token_should_be(struct cf_parser *p, const char *str, return PARSE_CONTINUE; } -static inline int cf_next_token_should_be(struct cf_parser *p, const char *str, - const char *goto1, const char *goto2) +static inline int cf_next_token_should_be(struct cf_parser *p, const char *str, const char *goto1, const char *goto2) { if (!cf_next_token(p)) { cf_adderror_unexpected_eof(p); @@ -203,8 +194,7 @@ static inline bool cf_peek_token(struct cf_parser *p, struct cf_token *peek) return success; } -static inline bool cf_peek_valid_token(struct cf_parser *p, - struct cf_token *peek) +static inline bool cf_peek_valid_token(struct cf_parser *p, struct cf_token *peek) { bool success = cf_peek_token(p, peek); if (!success) @@ -217,8 +207,7 @@ static inline bool cf_token_is(struct cf_parser *p, const char *val) return strref_cmp(&p->cur_token->str, val) == 0; } -static inline int cf_token_is_type(struct cf_parser *p, enum cf_token_type type, - const char *type_expected, +static inline int cf_token_is_type(struct cf_parser *p, enum cf_token_type type, const char *type_expected, const char *goto_token) { if (p->cur_token->type != type) { @@ -238,8 +227,7 @@ static inline void cf_copy_token(struct cf_parser *p, char **dst) *dst = bstrdup_n(p->cur_token->str.array, p->cur_token->str.len); } -static inline int cf_get_name(struct cf_parser *p, char **dst, const char *name, - const char *goto_token) +static inline int cf_get_name(struct cf_parser *p, char **dst, const char *name, const char *goto_token) { int errcode; @@ -251,8 +239,7 @@ static inline int cf_get_name(struct cf_parser *p, char **dst, const char *name, return PARSE_SUCCESS; } -static inline int cf_next_name(struct cf_parser *p, char **dst, - const char *name, const char *goto_token) +static inline int cf_next_name(struct cf_parser *p, char **dst, const char *name, const char *goto_token) { if (!cf_next_valid_token(p)) return PARSE_EOF; @@ -269,8 +256,7 @@ static inline int cf_next_token_copy(struct cf_parser *p, char **dst) return PARSE_SUCCESS; } -static inline int cf_get_name_ref(struct cf_parser *p, struct strref *dst, - const char *name, const char *goto_token) +static inline int cf_get_name_ref(struct cf_parser *p, struct strref *dst, const char *name, const char *goto_token) { int errcode; @@ -282,8 +268,7 @@ static inline int cf_get_name_ref(struct cf_parser *p, struct strref *dst, return PARSE_SUCCESS; } -static inline int cf_next_name_ref(struct cf_parser *p, struct strref *dst, - const char *name, const char *goto_token) +static inline int cf_next_name_ref(struct cf_parser *p, struct strref *dst, const char *name, const char *goto_token) { if (!cf_next_valid_token(p)) return PARSE_EOF; diff --git a/libobs/util/circlebuf.h b/libobs/util/circlebuf.h index 2a6eb275a..b93244247 100644 --- a/libobs/util/circlebuf.h +++ b/libobs/util/circlebuf.h @@ -49,8 +49,7 @@ OBS_DEPRECATED static inline void circlebuf_free(struct circlebuf *cb) memset(cb, 0, sizeof(struct circlebuf)); } -OBS_DEPRECATED static inline void circlebuf_reorder_data(struct circlebuf *cb, - size_t new_capacity) +OBS_DEPRECATED static inline void circlebuf_reorder_data(struct circlebuf *cb, size_t new_capacity) { size_t difference; uint8_t *data; @@ -64,8 +63,7 @@ OBS_DEPRECATED static inline void circlebuf_reorder_data(struct circlebuf *cb, cb->start_pos += difference; } -OBS_DEPRECATED static inline void -circlebuf_ensure_capacity(struct circlebuf *cb) +OBS_DEPRECATED static inline void circlebuf_ensure_capacity(struct circlebuf *cb) { size_t new_capacity; if (cb->size <= cb->capacity) @@ -80,8 +78,7 @@ circlebuf_ensure_capacity(struct circlebuf *cb) cb->capacity = new_capacity; } -OBS_DEPRECATED static inline void circlebuf_reserve(struct circlebuf *cb, - size_t capacity) +OBS_DEPRECATED static inline void circlebuf_reserve(struct circlebuf *cb, size_t capacity) { if (capacity <= cb->capacity) return; @@ -91,8 +88,7 @@ OBS_DEPRECATED static inline void circlebuf_reserve(struct circlebuf *cb, cb->capacity = capacity; } -OBS_DEPRECATED static inline void circlebuf_upsize(struct circlebuf *cb, - size_t size) +OBS_DEPRECATED static inline void circlebuf_upsize(struct circlebuf *cb, size_t size) { size_t add_size = size - cb->size; size_t new_end_pos = cb->end_pos + add_size; @@ -120,9 +116,7 @@ OBS_DEPRECATED static inline void circlebuf_upsize(struct circlebuf *cb, } /** Overwrites data at a specific point in the buffer (relative). */ -OBS_DEPRECATED static inline void circlebuf_place(struct circlebuf *cb, - size_t position, - const void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_place(struct circlebuf *cb, size_t position, const void *data, size_t size) { size_t end_point = position + size; size_t data_end_pos; @@ -146,8 +140,7 @@ OBS_DEPRECATED static inline void circlebuf_place(struct circlebuf *cb, } } -OBS_DEPRECATED static inline void -circlebuf_push_back(struct circlebuf *cb, const void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_push_back(struct circlebuf *cb, const void *data, size_t size) { size_t new_end_pos = cb->end_pos + size; @@ -159,8 +152,7 @@ circlebuf_push_back(struct circlebuf *cb, const void *data, size_t size) size_t loop_size = size - back_size; if (back_size) - memcpy((uint8_t *)cb->data + cb->end_pos, data, - back_size); + memcpy((uint8_t *)cb->data + cb->end_pos, data, back_size); memcpy(cb->data, (uint8_t *)data + back_size, loop_size); new_end_pos -= cb->capacity; @@ -171,8 +163,7 @@ circlebuf_push_back(struct circlebuf *cb, const void *data, size_t size) cb->end_pos = new_end_pos; } -OBS_DEPRECATED static inline void -circlebuf_push_front(struct circlebuf *cb, const void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_push_front(struct circlebuf *cb, const void *data, size_t size) { cb->size += size; circlebuf_ensure_capacity(cb); @@ -186,8 +177,7 @@ circlebuf_push_front(struct circlebuf *cb, const void *data, size_t size) size_t back_size = size - cb->start_pos; if (cb->start_pos) - memcpy(cb->data, (uint8_t *)data + back_size, - cb->start_pos); + memcpy(cb->data, (uint8_t *)data + back_size, cb->start_pos); cb->start_pos = cb->capacity - back_size; memcpy((uint8_t *)cb->data + cb->start_pos, data, back_size); @@ -197,8 +187,7 @@ circlebuf_push_front(struct circlebuf *cb, const void *data, size_t size) } } -OBS_DEPRECATED static inline void circlebuf_push_back_zero(struct circlebuf *cb, - size_t size) +OBS_DEPRECATED static inline void circlebuf_push_back_zero(struct circlebuf *cb, size_t size) { size_t new_end_pos = cb->end_pos + size; @@ -221,8 +210,7 @@ OBS_DEPRECATED static inline void circlebuf_push_back_zero(struct circlebuf *cb, cb->end_pos = new_end_pos; } -OBS_DEPRECATED static inline void -circlebuf_push_front_zero(struct circlebuf *cb, size_t size) +OBS_DEPRECATED static inline void circlebuf_push_front_zero(struct circlebuf *cb, size_t size) { cb->size += size; circlebuf_ensure_capacity(cb); @@ -246,8 +234,7 @@ circlebuf_push_front_zero(struct circlebuf *cb, size_t size) } } -OBS_DEPRECATED static inline void circlebuf_peek_front(struct circlebuf *cb, - void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_peek_front(struct circlebuf *cb, void *data, size_t size) { assert(size <= cb->size); @@ -255,18 +242,15 @@ OBS_DEPRECATED static inline void circlebuf_peek_front(struct circlebuf *cb, size_t start_size = cb->capacity - cb->start_pos; if (start_size < size) { - memcpy(data, (uint8_t *)cb->data + cb->start_pos, - start_size); - memcpy((uint8_t *)data + start_size, cb->data, - size - start_size); + memcpy(data, (uint8_t *)cb->data + cb->start_pos, start_size); + memcpy((uint8_t *)data + start_size, cb->data, size - start_size); } else { memcpy(data, (uint8_t *)cb->data + cb->start_pos, size); } } } -OBS_DEPRECATED static inline void circlebuf_peek_back(struct circlebuf *cb, - void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_peek_back(struct circlebuf *cb, void *data, size_t size) { assert(size <= cb->size); @@ -277,19 +261,15 @@ OBS_DEPRECATED static inline void circlebuf_peek_back(struct circlebuf *cb, size_t front_size = size - back_size; size_t new_end_pos = cb->capacity - front_size; - memcpy((uint8_t *)data + (size - back_size), cb->data, - back_size); - memcpy(data, (uint8_t *)cb->data + new_end_pos, - front_size); + memcpy((uint8_t *)data + (size - back_size), cb->data, back_size); + memcpy(data, (uint8_t *)cb->data + new_end_pos, front_size); } else { - memcpy(data, (uint8_t *)cb->data + cb->end_pos - size, - size); + memcpy(data, (uint8_t *)cb->data + cb->end_pos - size, size); } } } -OBS_DEPRECATED static inline void circlebuf_pop_front(struct circlebuf *cb, - void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_pop_front(struct circlebuf *cb, void *data, size_t size) { circlebuf_peek_front(cb, data, size); @@ -304,8 +284,7 @@ OBS_DEPRECATED static inline void circlebuf_pop_front(struct circlebuf *cb, cb->start_pos -= cb->capacity; } -OBS_DEPRECATED static inline void circlebuf_pop_back(struct circlebuf *cb, - void *data, size_t size) +OBS_DEPRECATED static inline void circlebuf_pop_back(struct circlebuf *cb, void *data, size_t size) { circlebuf_peek_back(cb, data, size); @@ -321,8 +300,7 @@ OBS_DEPRECATED static inline void circlebuf_pop_back(struct circlebuf *cb, cb->end_pos -= size; } -OBS_DEPRECATED static inline void *circlebuf_data(struct circlebuf *cb, - size_t idx) +OBS_DEPRECATED static inline void *circlebuf_data(struct circlebuf *cb, size_t idx) { uint8_t *ptr = (uint8_t *)cb->data; size_t offset = cb->start_pos + idx; diff --git a/libobs/util/config-file.c b/libobs/util/config-file.c index 2771162f4..ab03176f7 100644 --- a/libobs/util/config-file.c +++ b/libobs/util/config-file.c @@ -144,8 +144,7 @@ static void unescape(struct dstr *str) *write = '\0'; } -static void config_add_item(struct config_item **items, struct strref *name, - struct strref *value) +static void config_add_item(struct config_item **items, struct strref *name, struct strref *value) { struct config_item *item; struct dstr item_value; @@ -165,8 +164,7 @@ static void config_add_item(struct config_item **items, struct strref *name, HASH_ADD_STR(*items, name, item); } -static void config_parse_section(struct config_section *section, - struct lexer *lex) +static void config_parse_section(struct config_section *section, struct lexer *lex) { struct base_token token; @@ -181,9 +179,7 @@ static void config_parse_section(struct config_section *section, if (token.type == BASETOKEN_OTHER) { if (*token.text.array == '#') { do { - if (!lexer_getbasetoken( - lex, &token, - PARSE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, PARSE_WHITESPACE)) return; } while (!is_newline(*token.text.array)); @@ -204,8 +200,7 @@ static void config_parse_section(struct config_section *section, } } -static void parse_config_data(struct config_section **sections, - struct lexer *lex) +static void parse_config_data(struct config_section **sections, struct lexer *lex) { struct strref section_name; struct base_token token; @@ -222,8 +217,7 @@ static void parse_config_data(struct config_section **sections, if (*token.text.array != '[') { while (!is_newline(*token.text.array)) { - if (!lexer_getbasetoken(lex, &token, - PARSE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, PARSE_WHITESPACE)) return; } @@ -244,8 +238,7 @@ static void parse_config_data(struct config_section **sections, } } -static int config_parse_file(struct config_section **sections, const char *file, - bool always_open) +static int config_parse_file(struct config_section **sections, const char *file, bool always_open) { char *file_data; struct lexer lex; @@ -272,8 +265,7 @@ static int config_parse_file(struct config_section **sections, const char *file, return CONFIG_SUCCESS; } -int config_open(config_t **config, const char *file, - enum config_open_type open_type) +int config_open(config_t **config, const char *file, enum config_open_type open_type) { int errorcode; bool always_open = open_type == CONFIG_OPEN_ALWAYS; @@ -403,8 +395,7 @@ cleanup: return ret; } -int config_save_safe(config_t *config, const char *temp_ext, - const char *backup_ext) +int config_save_safe(config_t *config, const char *temp_ext, const char *backup_ext) { struct dstr temp_file = {0}; struct dstr backup_file = {0}; @@ -504,9 +495,8 @@ unlock: return name; } -static const struct config_item * -config_find_item(const struct config_section *sections, const char *section, - const char *name) +static const struct config_item *config_find_item(const struct config_section *sections, const char *section, + const char *name) { struct config_section *sec; struct config_item *res; @@ -520,8 +510,8 @@ config_find_item(const struct config_section *sections, const char *section, return res; } -static void config_set_item(config_t *config, struct config_section **sections, - const char *section, const char *name, char *value) +static void config_set_item(config_t *config, struct config_section **sections, const char *section, const char *name, + char *value) { struct config_section *sec; struct config_item *item; @@ -551,27 +541,22 @@ static void config_set_item(config_t *config, struct config_section **sections, pthread_mutex_unlock(&config->mutex); } -static void config_set_item_default(config_t *config, const char *section, - const char *name, char *value) +static void config_set_item_default(config_t *config, const char *section, const char *name, char *value) { config_set_item(config, &config->defaults, section, name, value); if (!config_has_user_value(config, section, name)) - config_set_item(config, &config->sections, section, name, - bstrdup(value)); + config_set_item(config, &config->sections, section, name, bstrdup(value)); } -void config_set_string(config_t *config, const char *section, const char *name, - const char *value) +void config_set_string(config_t *config, const char *section, const char *name, const char *value) { if (!value) value = ""; - config_set_item(config, &config->sections, section, name, - bstrdup(value)); + config_set_item(config, &config->sections, section, name, bstrdup(value)); } -void config_set_int(config_t *config, const char *section, const char *name, - int64_t value) +void config_set_int(config_t *config, const char *section, const char *name, int64_t value) { struct dstr str; dstr_init(&str); @@ -579,8 +564,7 @@ void config_set_int(config_t *config, const char *section, const char *name, config_set_item(config, &config->sections, section, name, str.array); } -void config_set_uint(config_t *config, const char *section, const char *name, - uint64_t value) +void config_set_uint(config_t *config, const char *section, const char *name, uint64_t value) { struct dstr str; dstr_init(&str); @@ -588,31 +572,27 @@ void config_set_uint(config_t *config, const char *section, const char *name, config_set_item(config, &config->sections, section, name, str.array); } -void config_set_bool(config_t *config, const char *section, const char *name, - bool value) +void config_set_bool(config_t *config, const char *section, const char *name, bool value) { char *str = bstrdup(value ? "true" : "false"); config_set_item(config, &config->sections, section, name, str); } -void config_set_double(config_t *config, const char *section, const char *name, - double value) +void config_set_double(config_t *config, const char *section, const char *name, double value) { char *str = bzalloc(64); os_dtostr(value, str, 64); config_set_item(config, &config->sections, section, name, str); } -void config_set_default_string(config_t *config, const char *section, - const char *name, const char *value) +void config_set_default_string(config_t *config, const char *section, const char *name, const char *value) { if (!value) value = ""; config_set_item_default(config, section, name, bstrdup(value)); } -void config_set_default_int(config_t *config, const char *section, - const char *name, int64_t value) +void config_set_default_int(config_t *config, const char *section, const char *name, int64_t value) { struct dstr str; dstr_init(&str); @@ -620,8 +600,7 @@ void config_set_default_int(config_t *config, const char *section, config_set_item_default(config, section, name, str.array); } -void config_set_default_uint(config_t *config, const char *section, - const char *name, uint64_t value) +void config_set_default_uint(config_t *config, const char *section, const char *name, uint64_t value) { struct dstr str; dstr_init(&str); @@ -629,15 +608,13 @@ void config_set_default_uint(config_t *config, const char *section, config_set_item_default(config, section, name, str.array); } -void config_set_default_bool(config_t *config, const char *section, - const char *name, bool value) +void config_set_default_bool(config_t *config, const char *section, const char *name, bool value) { char *str = bstrdup(value ? "true" : "false"); config_set_item_default(config, section, name, str); } -void config_set_default_double(config_t *config, const char *section, - const char *name, double value) +void config_set_default_double(config_t *config, const char *section, const char *name, double value) { struct dstr str; dstr_init(&str); @@ -645,8 +622,7 @@ void config_set_default_double(config_t *config, const char *section, config_set_item_default(config, section, name, str.array); } -const char *config_get_string(config_t *config, const char *section, - const char *name) +const char *config_get_string(config_t *config, const char *section, const char *name) { const struct config_item *item; const char *value = NULL; @@ -694,8 +670,7 @@ int64_t config_get_int(config_t *config, const char *section, const char *name) return 0; } -uint64_t config_get_uint(config_t *config, const char *section, - const char *name) +uint64_t config_get_uint(config_t *config, const char *section, const char *name) { const char *value = config_get_string(config, section, name); if (value) @@ -713,8 +688,7 @@ bool config_get_bool(config_t *config, const char *section, const char *name) return false; } -double config_get_double(config_t *config, const char *section, - const char *name) +double config_get_double(config_t *config, const char *section, const char *name) { const char *value = config_get_string(config, section, name); if (value) @@ -723,8 +697,7 @@ double config_get_double(config_t *config, const char *section, return 0.0; } -bool config_remove_value(config_t *config, const char *section, - const char *name) +bool config_remove_value(config_t *config, const char *section, const char *name) { struct config_section *sec; struct config_item *item; @@ -746,8 +719,7 @@ bool config_remove_value(config_t *config, const char *section, return success; } -const char *config_get_default_string(config_t *config, const char *section, - const char *name) +const char *config_get_default_string(config_t *config, const char *section, const char *name) { const struct config_item *item; const char *value = NULL; @@ -762,8 +734,7 @@ const char *config_get_default_string(config_t *config, const char *section, return value; } -int64_t config_get_default_int(config_t *config, const char *section, - const char *name) +int64_t config_get_default_int(config_t *config, const char *section, const char *name) { const char *value = config_get_default_string(config, section, name); if (value) @@ -772,8 +743,7 @@ int64_t config_get_default_int(config_t *config, const char *section, return 0; } -uint64_t config_get_default_uint(config_t *config, const char *section, - const char *name) +uint64_t config_get_default_uint(config_t *config, const char *section, const char *name) { const char *value = config_get_default_string(config, section, name); if (value) @@ -782,8 +752,7 @@ uint64_t config_get_default_uint(config_t *config, const char *section, return 0; } -bool config_get_default_bool(config_t *config, const char *section, - const char *name) +bool config_get_default_bool(config_t *config, const char *section, const char *name) { const char *value = config_get_default_string(config, section, name); if (value) @@ -792,8 +761,7 @@ bool config_get_default_bool(config_t *config, const char *section, return false; } -double config_get_default_double(config_t *config, const char *section, - const char *name) +double config_get_default_double(config_t *config, const char *section, const char *name) { const char *value = config_get_default_string(config, section, name); if (value) @@ -802,8 +770,7 @@ double config_get_default_double(config_t *config, const char *section, return 0.0; } -bool config_has_user_value(config_t *config, const char *section, - const char *name) +bool config_has_user_value(config_t *config, const char *section, const char *name) { bool success; pthread_mutex_lock(&config->mutex); @@ -812,8 +779,7 @@ bool config_has_user_value(config_t *config, const char *section, return success; } -bool config_has_default_value(config_t *config, const char *section, - const char *name) +bool config_has_default_value(config_t *config, const char *section, const char *name) { bool success; pthread_mutex_lock(&config->mutex); diff --git a/libobs/util/config-file.h b/libobs/util/config-file.h index b9505354f..1eaf9d490 100644 --- a/libobs/util/config-file.h +++ b/libobs/util/config-file.h @@ -42,41 +42,28 @@ enum config_open_type { }; EXPORT config_t *config_create(const char *file); -EXPORT int config_open(config_t **config, const char *file, - enum config_open_type open_type); +EXPORT int config_open(config_t **config, const char *file, enum config_open_type open_type); EXPORT int config_open_string(config_t **config, const char *str); EXPORT int config_save(config_t *config); -EXPORT int config_save_safe(config_t *config, const char *temp_ext, - const char *backup_ext); +EXPORT int config_save_safe(config_t *config, const char *temp_ext, const char *backup_ext); EXPORT void config_close(config_t *config); EXPORT size_t config_num_sections(config_t *config); EXPORT const char *config_get_section(config_t *config, size_t idx); -EXPORT void config_set_string(config_t *config, const char *section, - const char *name, const char *value); -EXPORT void config_set_int(config_t *config, const char *section, - const char *name, int64_t value); -EXPORT void config_set_uint(config_t *config, const char *section, - const char *name, uint64_t value); -EXPORT void config_set_bool(config_t *config, const char *section, - const char *name, bool value); -EXPORT void config_set_double(config_t *config, const char *section, - const char *name, double value); +EXPORT void config_set_string(config_t *config, const char *section, const char *name, const char *value); +EXPORT void config_set_int(config_t *config, const char *section, const char *name, int64_t value); +EXPORT void config_set_uint(config_t *config, const char *section, const char *name, uint64_t value); +EXPORT void config_set_bool(config_t *config, const char *section, const char *name, bool value); +EXPORT void config_set_double(config_t *config, const char *section, const char *name, double value); -EXPORT const char *config_get_string(config_t *config, const char *section, - const char *name); -EXPORT int64_t config_get_int(config_t *config, const char *section, - const char *name); -EXPORT uint64_t config_get_uint(config_t *config, const char *section, - const char *name); -EXPORT bool config_get_bool(config_t *config, const char *section, - const char *name); -EXPORT double config_get_double(config_t *config, const char *section, - const char *name); +EXPORT const char *config_get_string(config_t *config, const char *section, const char *name); +EXPORT int64_t config_get_int(config_t *config, const char *section, const char *name); +EXPORT uint64_t config_get_uint(config_t *config, const char *section, const char *name); +EXPORT bool config_get_bool(config_t *config, const char *section, const char *name); +EXPORT double config_get_double(config_t *config, const char *section, const char *name); -EXPORT bool config_remove_value(config_t *config, const char *section, - const char *name); +EXPORT bool config_remove_value(config_t *config, const char *section, const char *name); /* * DEFAULT VALUES @@ -94,35 +81,22 @@ EXPORT bool config_remove_value(config_t *config, const char *section, */ EXPORT int config_open_defaults(config_t *config, const char *file); -EXPORT void config_set_default_string(config_t *config, const char *section, - const char *name, const char *value); -EXPORT void config_set_default_int(config_t *config, const char *section, - const char *name, int64_t value); -EXPORT void config_set_default_uint(config_t *config, const char *section, - const char *name, uint64_t value); -EXPORT void config_set_default_bool(config_t *config, const char *section, - const char *name, bool value); -EXPORT void config_set_default_double(config_t *config, const char *section, - const char *name, double value); +EXPORT void config_set_default_string(config_t *config, const char *section, const char *name, const char *value); +EXPORT void config_set_default_int(config_t *config, const char *section, const char *name, int64_t value); +EXPORT void config_set_default_uint(config_t *config, const char *section, const char *name, uint64_t value); +EXPORT void config_set_default_bool(config_t *config, const char *section, const char *name, bool value); +EXPORT void config_set_default_double(config_t *config, const char *section, const char *name, double value); /* These functions allow you to get the current default values rather than get * the actual values. Probably almost never really needed */ -EXPORT const char *config_get_default_string(config_t *config, - const char *section, - const char *name); -EXPORT int64_t config_get_default_int(config_t *config, const char *section, - const char *name); -EXPORT uint64_t config_get_default_uint(config_t *config, const char *section, - const char *name); -EXPORT bool config_get_default_bool(config_t *config, const char *section, - const char *name); -EXPORT double config_get_default_double(config_t *config, const char *section, - const char *name); +EXPORT const char *config_get_default_string(config_t *config, const char *section, const char *name); +EXPORT int64_t config_get_default_int(config_t *config, const char *section, const char *name); +EXPORT uint64_t config_get_default_uint(config_t *config, const char *section, const char *name); +EXPORT bool config_get_default_bool(config_t *config, const char *section, const char *name); +EXPORT double config_get_default_double(config_t *config, const char *section, const char *name); -EXPORT bool config_has_user_value(config_t *config, const char *section, - const char *name); -EXPORT bool config_has_default_value(config_t *config, const char *section, - const char *name); +EXPORT bool config_has_user_value(config_t *config, const char *section, const char *name); +EXPORT bool config_has_default_value(config_t *config, const char *section, const char *name); #ifdef __cplusplus } diff --git a/libobs/util/crc32.c b/libobs/util/crc32.c index 4a5565f9b..c80b9eb94 100644 --- a/libobs/util/crc32.c +++ b/libobs/util/crc32.c @@ -20,48 +20,34 @@ /* CRC32 code derived from work by Gary S. Brown. */ static uint32_t crc32_tab[] = { - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, - 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, - 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, - 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, - 0x136c9856, 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, - 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, - 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, 0x45df5c75, 0xdcd60dcf, 0xabd13d59, - 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, - 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, 0x01db7106, - 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, - 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, - 0x91646c97, 0xe6635c01, 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, - 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, - 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, - 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, - 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, - 0xbe0b1010, 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, - 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, - 0xead54739, 0x9dd277af, 0x04db2615, 0x73dc1683, 0xe3630b12, 0x94643b84, - 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, - 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, 0x67dd4acc, - 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, - 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, - 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, - 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, - 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, - 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, - 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, - 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, - 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, - 0x616bffd3, 0x166ccf45, 0xa00ae278, 0xd70dd2ee, 0x4e048354, 0x3903b3c2, - 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, - 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, 0xcdd70693, - 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, + 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, + 0x79dcb8a4, 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, 0x90bf1d91, 0x1db71064, 0x6ab020f2, + 0xf3b97148, 0x84be41de, 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, 0x646ba8c0, 0xfd62f97a, + 0x8a65c9ec, 0x14015c4f, 0x63066cd9, 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, 0xa2677172, + 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, + 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, + 0xcfba9599, 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, 0x2f6f7c87, 0x58684c11, 0xc1611dab, + 0xb6662d3d, 0x76dc4190, 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, 0x9fbfe4a5, 0xe8b8d433, + 0x7807c9a2, 0x0f00f934, 0x9609a88e, 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, 0x6b6b51f4, + 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, + 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, + 0xd4bb30e2, 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, 0x346ed9fc, 0xad678846, 0xda60b8d0, + 0x44042d73, 0x33031de5, 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, 0xc90c2086, 0x5768b525, + 0x206f85b3, 0xb966d409, 0xce61e49f, 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, 0x2eb40d81, + 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, + 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, + 0xf00f9344, 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, 0x196c3671, 0x6e6b06e7, 0xfed41b76, + 0x89d32be0, 0x10da7a5a, 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, 0xd6d6a3e8, 0xa1d1937e, + 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, 0x36034af6, + 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, + 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, + 0xb5d0cf31, 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, 0x026d930a, 0x9c0906a9, 0xeb0e363f, + 0x72076785, 0x05005713, 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, 0xe5d5be0d, 0x7cdcefb7, + 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, 0x18b74777, + 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, + 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, + 0x40df0b66, 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, 0xbdbdf21c, 0xcabac28a, 0x53b39330, + 0x24b4a3a6, 0xbad03605, 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, 0x2d02ef8d}; uint32_t calc_crc32(uint32_t crc, const void *buf, size_t size) diff --git a/libobs/util/curl/curl-helper.h b/libobs/util/curl/curl-helper.h index 04abb4f0c..374daa147 100644 --- a/libobs/util/curl/curl-helper.h +++ b/libobs/util/curl/curl-helper.h @@ -26,8 +26,7 @@ #define CURL_OBS_REVOKE_SETTING CURLSSLOPT_NO_REVOKE #endif -#define curl_obs_set_revoke_setting(handle) \ - curl_easy_setopt(handle, CURLOPT_SSL_OPTIONS, CURL_OBS_REVOKE_SETTING) +#define curl_obs_set_revoke_setting(handle) curl_easy_setopt(handle, CURLOPT_SSL_OPTIONS, CURL_OBS_REVOKE_SETTING) #else diff --git a/libobs/util/darray.h b/libobs/util/darray.h index 6a729a74b..f21fb5f4f 100644 --- a/libobs/util/darray.h +++ b/libobs/util/darray.h @@ -59,20 +59,17 @@ static inline void darray_free(struct darray *dst) dst->capacity = 0; } -static inline size_t darray_alloc_size(const size_t element_size, - const struct darray *da) +static inline size_t darray_alloc_size(const size_t element_size, const struct darray *da) { return element_size * da->num; } -static inline void *darray_item(const size_t element_size, - const struct darray *da, size_t idx) +static inline void *darray_item(const size_t element_size, const struct darray *da, size_t idx) { return (void *)(((uint8_t *)da->array) + element_size * idx); } -static inline void *darray_end(const size_t element_size, - const struct darray *da) +static inline void *darray_end(const size_t element_size, const struct darray *da) { if (!da->num) return NULL; @@ -80,8 +77,7 @@ static inline void *darray_end(const size_t element_size, return darray_item(element_size, da, da->num - 1); } -static inline void darray_reserve(const size_t element_size, struct darray *dst, - const size_t capacity) +static inline void darray_reserve(const size_t element_size, struct darray *dst, const size_t capacity) { void *ptr; if (capacity == 0 || capacity <= dst->capacity) @@ -98,9 +94,7 @@ static inline void darray_reserve(const size_t element_size, struct darray *dst, dst->capacity = capacity; } -static inline void darray_ensure_capacity(const size_t element_size, - struct darray *dst, - const size_t new_size) +static inline void darray_ensure_capacity(const size_t element_size, struct darray *dst, const size_t new_size) { size_t new_cap; void *ptr; @@ -126,8 +120,7 @@ static inline void darray_clear(struct darray *dst) dst->num = 0; } -static inline void darray_resize(const size_t element_size, struct darray *dst, - const size_t size) +static inline void darray_resize(const size_t element_size, struct darray *dst, const size_t size) { int b_clear; size_t old_num; @@ -146,12 +139,10 @@ static inline void darray_resize(const size_t element_size, struct darray *dst, dst->num = size; if (b_clear) - memset(darray_item(element_size, dst, old_num), 0, - element_size * (dst->num - old_num)); + memset(darray_item(element_size, dst, old_num), 0, element_size * (dst->num - old_num)); } -static inline void darray_copy(const size_t element_size, struct darray *dst, - const struct darray *da) +static inline void darray_copy(const size_t element_size, struct darray *dst, const struct darray *da) { if (da->num == 0) { darray_free(dst); @@ -161,9 +152,7 @@ static inline void darray_copy(const size_t element_size, struct darray *dst, } } -static inline void darray_copy_array(const size_t element_size, - struct darray *dst, const void *array, - const size_t num) +static inline void darray_copy_array(const size_t element_size, struct darray *dst, const void *array, const size_t num) { darray_resize(element_size, dst, num); memcpy(dst->array, array, element_size * dst->num); @@ -178,9 +167,7 @@ static inline void darray_move(struct darray *dst, struct darray *src) src->num = 0; } -static inline size_t darray_find(const size_t element_size, - const struct darray *da, const void *item, - const size_t idx) +static inline size_t darray_find(const size_t element_size, const struct darray *da, const void *item, const size_t idx) { size_t i; @@ -195,8 +182,7 @@ static inline size_t darray_find(const size_t element_size, return DARRAY_INVALID; } -static inline size_t darray_push_back(const size_t element_size, - struct darray *dst, const void *item) +static inline size_t darray_push_back(const size_t element_size, struct darray *dst, const void *item) { darray_ensure_capacity(element_size, dst, ++dst->num); memcpy(darray_end(element_size, dst), item, element_size); @@ -204,8 +190,7 @@ static inline size_t darray_push_back(const size_t element_size, return dst->num - 1; } -static inline void *darray_push_back_new(const size_t element_size, - struct darray *dst) +static inline void *darray_push_back_new(const size_t element_size, struct darray *dst) { void *last; @@ -216,9 +201,8 @@ static inline void *darray_push_back_new(const size_t element_size, return last; } -static inline size_t darray_push_back_array(const size_t element_size, - struct darray *dst, - const void *array, const size_t num) +static inline size_t darray_push_back_array(const size_t element_size, struct darray *dst, const void *array, + const size_t num) { size_t old_num; if (!dst) @@ -228,21 +212,17 @@ static inline size_t darray_push_back_array(const size_t element_size, old_num = dst->num; darray_resize(element_size, dst, dst->num + num); - memcpy(darray_item(element_size, dst, old_num), array, - element_size * num); + memcpy(darray_item(element_size, dst, old_num), array, element_size * num); return old_num; } -static inline size_t darray_push_back_darray(const size_t element_size, - struct darray *dst, - const struct darray *da) +static inline size_t darray_push_back_darray(const size_t element_size, struct darray *dst, const struct darray *da) { return darray_push_back_array(element_size, dst, da->array, da->num); } -static inline void darray_insert(const size_t element_size, struct darray *dst, - const size_t idx, const void *item) +static inline void darray_insert(const size_t element_size, struct darray *dst, const size_t idx, const void *item) { void *new_item; size_t move_count; @@ -259,13 +239,11 @@ static inline void darray_insert(const size_t element_size, struct darray *dst, new_item = darray_item(element_size, dst, idx); - memmove(darray_item(element_size, dst, idx + 1), new_item, - move_count * element_size); + memmove(darray_item(element_size, dst, idx + 1), new_item, move_count * element_size); memcpy(new_item, item, element_size); } -static inline void *darray_insert_new(const size_t element_size, - struct darray *dst, const size_t idx) +static inline void *darray_insert_new(const size_t element_size, struct darray *dst, const size_t idx) { void *item; size_t move_count; @@ -278,15 +256,13 @@ static inline void *darray_insert_new(const size_t element_size, darray_ensure_capacity(element_size, dst, ++dst->num); item = darray_item(element_size, dst, idx); - memmove(darray_item(element_size, dst, idx + 1), item, - move_count * element_size); + memmove(darray_item(element_size, dst, idx + 1), item, move_count * element_size); memset(item, 0, element_size); return item; } -static inline void darray_insert_array(const size_t element_size, - struct darray *dst, const size_t idx, +static inline void darray_insert_array(const size_t element_size, struct darray *dst, const size_t idx, const void *array, const size_t num) { size_t old_num; @@ -298,42 +274,36 @@ static inline void darray_insert_array(const size_t element_size, old_num = dst->num; darray_resize(element_size, dst, dst->num + num); - memmove(darray_item(element_size, dst, idx + num), - darray_item(element_size, dst, idx), + memmove(darray_item(element_size, dst, idx + num), darray_item(element_size, dst, idx), element_size * (old_num - idx)); memcpy(darray_item(element_size, dst, idx), array, element_size * num); } -static inline void darray_insert_darray(const size_t element_size, - struct darray *dst, const size_t idx, +static inline void darray_insert_darray(const size_t element_size, struct darray *dst, const size_t idx, const struct darray *da) { darray_insert_array(element_size, dst, idx, da->array, da->num); } -static inline void darray_erase(const size_t element_size, struct darray *dst, - const size_t idx) +static inline void darray_erase(const size_t element_size, struct darray *dst, const size_t idx) { assert(idx < dst->num); if (idx >= dst->num || !--dst->num) return; - memmove(darray_item(element_size, dst, idx), - darray_item(element_size, dst, idx + 1), + memmove(darray_item(element_size, dst, idx), darray_item(element_size, dst, idx + 1), element_size * (dst->num - idx)); } -static inline void darray_erase_item(const size_t element_size, - struct darray *dst, const void *item) +static inline void darray_erase_item(const size_t element_size, struct darray *dst, const void *item) { size_t idx = darray_find(element_size, dst, item, 0); if (idx != DARRAY_INVALID) darray_erase(element_size, dst, idx); } -static inline void darray_erase_range(const size_t element_size, - struct darray *dst, const size_t start, +static inline void darray_erase_range(const size_t element_size, struct darray *dst, const size_t start, const size_t end) { size_t count, move_count; @@ -353,15 +323,13 @@ static inline void darray_erase_range(const size_t element_size, move_count = dst->num - end; if (move_count) - memmove(darray_item(element_size, dst, start), - darray_item(element_size, dst, end), + memmove(darray_item(element_size, dst, start), darray_item(element_size, dst, end), move_count * element_size); dst->num -= count; } -static inline void darray_pop_front(const size_t element_size, - struct darray *dst) +static inline void darray_pop_front(const size_t element_size, struct darray *dst) { assert(dst->num != 0); @@ -369,8 +337,7 @@ static inline void darray_pop_front(const size_t element_size, darray_erase(element_size, dst, 0); } -static inline void darray_pop_back(const size_t element_size, - struct darray *dst) +static inline void darray_pop_back(const size_t element_size, struct darray *dst) { assert(dst->num != 0); @@ -378,16 +345,14 @@ static inline void darray_pop_back(const size_t element_size, darray_erase(element_size, dst, dst->num - 1); } -static inline void darray_join(const size_t element_size, struct darray *dst, - struct darray *da) +static inline void darray_join(const size_t element_size, struct darray *dst, struct darray *da) { darray_push_back_darray(element_size, dst, da); darray_free(da); } -static inline void darray_split(const size_t element_size, struct darray *dst1, - struct darray *dst2, const struct darray *da, - const size_t idx) +static inline void darray_split(const size_t element_size, struct darray *dst1, struct darray *dst2, + const struct darray *da, const size_t idx) { struct darray temp; @@ -402,20 +367,15 @@ static inline void darray_split(const size_t element_size, struct darray *dst1, if (da->num) { if (idx) - darray_copy_array(element_size, dst1, temp.array, - temp.num); + darray_copy_array(element_size, dst1, temp.array, temp.num); if (idx < temp.num - 1) - darray_copy_array(element_size, dst2, - darray_item(element_size, &temp, idx), - temp.num - idx); + darray_copy_array(element_size, dst2, darray_item(element_size, &temp, idx), temp.num - idx); } darray_free(&temp); } -static inline void darray_move_item(const size_t element_size, - struct darray *dst, const size_t from, - const size_t to) +static inline void darray_move_item(const size_t element_size, struct darray *dst, const size_t from, const size_t to) { void *temp, *p_from, *p_to; @@ -434,18 +394,15 @@ static inline void darray_move_item(const size_t element_size, memcpy(temp, p_from, element_size); if (to < from) - memmove(darray_item(element_size, dst, to + 1), p_to, - element_size * (from - to)); + memmove(darray_item(element_size, dst, to + 1), p_to, element_size * (from - to)); else - memmove(p_from, darray_item(element_size, dst, from + 1), - element_size * (to - from)); + memmove(p_from, darray_item(element_size, dst, from + 1), element_size * (to - from)); memcpy(p_to, temp, element_size); free(temp); } -static inline void darray_swap(const size_t element_size, struct darray *dst, - const size_t a, const size_t b) +static inline void darray_swap(const size_t element_size, struct darray *dst, const size_t a, const size_t b) { void *temp, *a_ptr, *b_ptr; @@ -496,18 +453,15 @@ static inline void darray_swap(const size_t element_size, struct darray *dst, #define da_end(v) darray_end(sizeof(*(v).array), &(v).da) -#define da_reserve(v, capacity) \ - darray_reserve(sizeof(*(v).array), &(v).da, capacity) +#define da_reserve(v, capacity) darray_reserve(sizeof(*(v).array), &(v).da, capacity) #define da_resize(v, size) darray_resize(sizeof(*(v).array), &(v).da, size) #define da_clear(v) darray_clear(&(v).da) -#define da_copy(dst, src) \ - darray_copy(sizeof(*(dst).array), &(dst).da, &(src).da) +#define da_copy(dst, src) darray_copy(sizeof(*(dst).array), &(dst).da, &(src).da) -#define da_copy_array(dst, src_array, n) \ - darray_copy_array(sizeof(*(dst).array), &(dst).da, src_array, n) +#define da_copy_array(dst, src_array, n) darray_copy_array(sizeof(*(dst).array), &(dst).da, src_array, n) #define da_move(dst, src) darray_move(&(dst).da, &(src).da) @@ -542,8 +496,7 @@ static inline void darray_swap(const size_t element_size, struct darray *dst, darray_find(sizeof(*(v).array), &(v).da, item, idx); \ }) #else -#define da_find(v, item, idx) \ - darray_find(sizeof(*(v).array), &(v).da, item, idx) +#define da_find(v, item, idx) darray_find(sizeof(*(v).array), &(v).da, item, idx) #endif #ifdef ENABLE_DARRAY_TYPE_TEST @@ -553,8 +506,7 @@ static inline void darray_swap(const size_t element_size, struct darray *dst, darray_push_back(sizeof(*(v).array), &(v).da, item); \ }) #else -#define da_push_back(v, item) \ - darray_push_back(sizeof(*(v).array), &(v).da, item) +#define da_push_back(v, item) darray_push_back(sizeof(*(v).array), &(v).da, item) #endif #ifdef __GNUC__ @@ -573,27 +525,23 @@ static inline void darray_swap(const size_t element_size, struct darray *dst, #endif #ifdef ENABLE_DARRAY_TYPE_TEST -#define da_push_back_array(dst, src_array, n) \ - ({ \ - da_type_test(dst, src_array); \ - darray_push_back_array(sizeof(*(dst).array), &(dst).da, \ - src_array, n); \ +#define da_push_back_array(dst, src_array, n) \ + ({ \ + da_type_test(dst, src_array); \ + darray_push_back_array(sizeof(*(dst).array), &(dst).da, src_array, n); \ }) #else -#define da_push_back_array(dst, src_array, n) \ - darray_push_back_array(sizeof(*(dst).array), &(dst).da, src_array, n) +#define da_push_back_array(dst, src_array, n) darray_push_back_array(sizeof(*(dst).array), &(dst).da, src_array, n) #endif #ifdef ENABLE_DARRAY_TYPE_TEST -#define da_push_back_da(dst, src) \ - ({ \ - da_type_test(dst, (src).array); \ - darray_push_back_darray(sizeof(*(dst).array), &(dst).da, \ - &(src).da); \ +#define da_push_back_da(dst, src) \ + ({ \ + da_type_test(dst, (src).array); \ + darray_push_back_darray(sizeof(*(dst).array), &(dst).da, &(src).da); \ }) #else -#define da_push_back_da(dst, src) \ - darray_push_back_darray(sizeof(*(dst).array), &(dst).da, &(src).da) +#define da_push_back_da(dst, src) darray_push_back_darray(sizeof(*(dst).array), &(dst).da, &(src).da) #endif #ifdef ENABLE_DARRAY_TYPE_TEST @@ -603,35 +551,29 @@ static inline void darray_swap(const size_t element_size, struct darray *dst, darray_insert(sizeof(*(v).array), &(v).da, idx, item); \ }) #else -#define da_insert(v, idx, item) \ - darray_insert(sizeof(*(v).array), &(v).da, idx, item) +#define da_insert(v, idx, item) darray_insert(sizeof(*(v).array), &(v).da, idx, item) #endif -#define da_insert_new(v, idx) \ - darray_insert_new(sizeof(*(v).array), &(v).da, idx) +#define da_insert_new(v, idx) darray_insert_new(sizeof(*(v).array), &(v).da, idx) #ifdef ENABLE_DARRAY_TYPE_TEST -#define da_insert_array(dst, idx, src_array, n) \ - ({ \ - da_type_test(dst, src_array); \ - darray_insert_array(sizeof(*(dst).array), &(dst).da, idx, \ - src_array, n); \ +#define da_insert_array(dst, idx, src_array, n) \ + ({ \ + da_type_test(dst, src_array); \ + darray_insert_array(sizeof(*(dst).array), &(dst).da, idx, src_array, n); \ }) #else -#define da_insert_array(dst, idx, src_array, n) \ - darray_insert_array(sizeof(*(dst).array), &(dst).da, idx, src_array, n) +#define da_insert_array(dst, idx, src_array, n) darray_insert_array(sizeof(*(dst).array), &(dst).da, idx, src_array, n) #endif #ifdef ENABLE_DARRAY_TYPE_TEST -#define da_insert_da(dst, idx, src) \ - ({ \ - da_type_test(dst, (src).array); \ - darray_insert_darray(sizeof(*(dst).array), &(dst).da, idx, \ - &(src).da); \ +#define da_insert_da(dst, idx, src) \ + ({ \ + da_type_test(dst, (src).array); \ + darray_insert_darray(sizeof(*(dst).array), &(dst).da, idx, &(src).da); \ }) #else -#define da_insert_da(dst, idx, src) \ - darray_insert_darray(sizeof(*(dst).array), &(dst).da, idx, &(src).da) +#define da_insert_da(dst, idx, src) darray_insert_darray(sizeof(*(dst).array), &(dst).da, idx, &(src).da) #endif #define da_erase(dst, idx) darray_erase(sizeof(*(dst).array), &(dst).da, idx) @@ -643,28 +585,21 @@ static inline void darray_swap(const size_t element_size, struct darray *dst, darray_erase_item(sizeof(*(dst).array), &(dst).da, item); \ }) #else -#define da_erase_item(dst, item) \ - darray_erase_item(sizeof(*(dst).array), &(dst).da, item) +#define da_erase_item(dst, item) darray_erase_item(sizeof(*(dst).array), &(dst).da, item) #endif -#define da_erase_range(dst, from, to) \ - darray_erase_range(sizeof(*(dst).array), &(dst).da, from, to) +#define da_erase_range(dst, from, to) darray_erase_range(sizeof(*(dst).array), &(dst).da, from, to) #define da_pop_front(dst) darray_pop_front(sizeof(*(dst).array), &(dst).da); #define da_pop_back(dst) darray_pop_back(sizeof(*(dst).array), &(dst).da); -#define da_join(dst, src) \ - darray_join(sizeof(*(dst).array), &(dst).da, &(src).da) +#define da_join(dst, src) darray_join(sizeof(*(dst).array), &(dst).da, &(src).da) -#define da_split(dst1, dst2, src, idx) \ - darray_split(sizeof(*(src).array), &(dst1).da, &(dst2).da, &(src).da, \ - idx) +#define da_split(dst1, dst2, src, idx) darray_split(sizeof(*(src).array), &(dst1).da, &(dst2).da, &(src).da, idx) -#define da_move_item(v, from, to) \ - darray_move_item(sizeof(*(v).array), &(v).da, from, to) +#define da_move_item(v, from, to) darray_move_item(sizeof(*(v).array), &(v).da, from, to) -#define da_swap(v, idx1, idx2) \ - darray_swap(sizeof(*(v).array), &(v).da, idx1, idx2) +#define da_swap(v, idx1, idx2) darray_swap(sizeof(*(v).array), &(v).da, idx1, idx2) #ifdef __cplusplus } diff --git a/libobs/util/deque.h b/libobs/util/deque.h index 54a52a0ee..48cfddab9 100644 --- a/libobs/util/deque.h +++ b/libobs/util/deque.h @@ -116,8 +116,7 @@ static inline void deque_upsize(struct deque *dq, size_t size) } /** Overwrites data at a specific point in the buffer (relative). */ -static inline void deque_place(struct deque *dq, size_t position, - const void *data, size_t size) +static inline void deque_place(struct deque *dq, size_t position, const void *data, size_t size) { size_t end_point = position + size; size_t data_end_pos; @@ -141,8 +140,7 @@ static inline void deque_place(struct deque *dq, size_t position, } } -static inline void deque_push_back(struct deque *dq, const void *data, - size_t size) +static inline void deque_push_back(struct deque *dq, const void *data, size_t size) { size_t new_end_pos = dq->end_pos + size; @@ -154,8 +152,7 @@ static inline void deque_push_back(struct deque *dq, const void *data, size_t loop_size = size - back_size; if (back_size) - memcpy((uint8_t *)dq->data + dq->end_pos, data, - back_size); + memcpy((uint8_t *)dq->data + dq->end_pos, data, back_size); memcpy(dq->data, (uint8_t *)data + back_size, loop_size); new_end_pos -= dq->capacity; @@ -166,8 +163,7 @@ static inline void deque_push_back(struct deque *dq, const void *data, dq->end_pos = new_end_pos; } -static inline void deque_push_front(struct deque *dq, const void *data, - size_t size) +static inline void deque_push_front(struct deque *dq, const void *data, size_t size) { dq->size += size; deque_ensure_capacity(dq); @@ -181,8 +177,7 @@ static inline void deque_push_front(struct deque *dq, const void *data, size_t back_size = size - dq->start_pos; if (dq->start_pos) - memcpy(dq->data, (uint8_t *)data + back_size, - dq->start_pos); + memcpy(dq->data, (uint8_t *)data + back_size, dq->start_pos); dq->start_pos = dq->capacity - back_size; memcpy((uint8_t *)dq->data + dq->start_pos, data, back_size); @@ -247,10 +242,8 @@ static inline void deque_peek_front(struct deque *dq, void *data, size_t size) size_t start_size = dq->capacity - dq->start_pos; if (start_size < size) { - memcpy(data, (uint8_t *)dq->data + dq->start_pos, - start_size); - memcpy((uint8_t *)data + start_size, dq->data, - size - start_size); + memcpy(data, (uint8_t *)dq->data + dq->start_pos, start_size); + memcpy((uint8_t *)data + start_size, dq->data, size - start_size); } else { memcpy(data, (uint8_t *)dq->data + dq->start_pos, size); } @@ -268,13 +261,10 @@ static inline void deque_peek_back(struct deque *dq, void *data, size_t size) size_t front_size = size - back_size; size_t new_end_pos = dq->capacity - front_size; - memcpy((uint8_t *)data + (size - back_size), dq->data, - back_size); - memcpy(data, (uint8_t *)dq->data + new_end_pos, - front_size); + memcpy((uint8_t *)data + (size - back_size), dq->data, back_size); + memcpy(data, (uint8_t *)dq->data + new_end_pos, front_size); } else { - memcpy(data, (uint8_t *)dq->data + dq->end_pos - size, - size); + memcpy(data, (uint8_t *)dq->data + dq->end_pos - size, size); } } } diff --git a/libobs/util/dstr.c b/libobs/util/dstr.c index 1f4645362..4dc415cb3 100644 --- a/libobs/util/dstr.c +++ b/libobs/util/dstr.c @@ -473,8 +473,7 @@ void dstr_insert(struct dstr *dst, const size_t idx, const char *array) dst->len = new_len; } -void dstr_insert_dstr(struct dstr *dst, const size_t idx, - const struct dstr *str) +void dstr_insert_dstr(struct dstr *dst, const size_t idx, const struct dstr *str) { size_t new_len; if (!str->len) @@ -488,8 +487,7 @@ void dstr_insert_dstr(struct dstr *dst, const size_t idx, dstr_ensure_capacity(dst, (new_len + 1)); - memmove(dst->array + idx + str->len, dst->array + idx, - dst->len - idx + 1); + memmove(dst->array + idx + str->len, dst->array + idx, dst->len - idx + 1); memcpy(dst->array + idx, str->array, str->len); dst->len = new_len; @@ -586,8 +584,8 @@ void dstr_vcatf(struct dstr *dst, const char *format, va_list args) dst->len += len < 0 ? strlen(dst->array + dst->len) : (size_t)len; } -void dstr_safe_printf(struct dstr *dst, const char *format, const char *val1, - const char *val2, const char *val3, const char *val4) +void dstr_safe_printf(struct dstr *dst, const char *format, const char *val1, const char *val2, const char *val3, + const char *val4) { dstr_copy(dst, format); if (val1) @@ -692,8 +690,7 @@ void dstr_left(struct dstr *dst, const struct dstr *str, const size_t pos) memcpy(dst->array, str->array, pos); } -void dstr_mid(struct dstr *dst, const struct dstr *str, const size_t start, - const size_t count) +void dstr_mid(struct dstr *dst, const struct dstr *str, const size_t start, const size_t count) { struct dstr temp; dstr_init(&temp); diff --git a/libobs/util/dstr.h b/libobs/util/dstr.h index 0ff70754d..4292557b2 100644 --- a/libobs/util/dstr.h +++ b/libobs/util/dstr.h @@ -65,8 +65,7 @@ static inline void dstr_init(struct dstr *dst); static inline void dstr_init_move(struct dstr *dst, struct dstr *src); static inline void dstr_init_move_array(struct dstr *dst, char *str); static inline void dstr_init_copy(struct dstr *dst, const char *src); -static inline void dstr_init_copy_dstr(struct dstr *dst, - const struct dstr *src); +static inline void dstr_init_copy_dstr(struct dstr *dst, const struct dstr *src); EXPORT void dstr_init_copy_strref(struct dstr *dst, const struct strref *src); static inline void dstr_free(struct dstr *dst); @@ -80,8 +79,7 @@ static inline void dstr_copy_dstr(struct dstr *dst, const struct dstr *src); EXPORT void dstr_copy_strref(struct dstr *dst, const struct strref *src); EXPORT void dstr_ncopy(struct dstr *dst, const char *array, const size_t len); -EXPORT void dstr_ncopy_dstr(struct dstr *dst, const struct dstr *src, - const size_t len); +EXPORT void dstr_ncopy_dstr(struct dstr *dst, const struct dstr *src, const size_t len); static inline void dstr_resize(struct dstr *dst, const size_t num); static inline void dstr_reserve(struct dstr *dst, const size_t num); @@ -95,12 +93,10 @@ EXPORT void dstr_cat_strref(struct dstr *dst, const struct strref *str); static inline void dstr_cat_ch(struct dstr *dst, char ch); EXPORT void dstr_ncat(struct dstr *dst, const char *array, const size_t len); -EXPORT void dstr_ncat_dstr(struct dstr *dst, const struct dstr *str, - const size_t len); +EXPORT void dstr_ncat_dstr(struct dstr *dst, const struct dstr *str, const size_t len); EXPORT void dstr_insert(struct dstr *dst, const size_t idx, const char *array); -EXPORT void dstr_insert_dstr(struct dstr *dst, const size_t idx, - const struct dstr *str); +EXPORT void dstr_insert_dstr(struct dstr *dst, const size_t idx, const struct dstr *str); EXPORT void dstr_insert_ch(struct dstr *dst, const size_t idx, const char ch); EXPORT void dstr_remove(struct dstr *dst, const size_t idx, const size_t count); @@ -113,31 +109,24 @@ EXPORT void dstr_catf(struct dstr *dst, const char *format, ...); EXPORT void dstr_vprintf(struct dstr *dst, const char *format, va_list args); EXPORT void dstr_vcatf(struct dstr *dst, const char *format, va_list args); -EXPORT void dstr_safe_printf(struct dstr *dst, const char *format, - const char *val1, const char *val2, - const char *val3, const char *val4); +EXPORT void dstr_safe_printf(struct dstr *dst, const char *format, const char *val1, const char *val2, const char *val3, + const char *val4); static inline const char *dstr_find_i(const struct dstr *str, const char *find); static inline const char *dstr_find(const struct dstr *str, const char *find); -EXPORT void dstr_replace(struct dstr *str, const char *find, - const char *replace); +EXPORT void dstr_replace(struct dstr *str, const char *find, const char *replace); static inline int dstr_cmp(const struct dstr *str1, const char *str2); static inline int dstr_cmpi(const struct dstr *str1, const char *str2); -static inline int dstr_ncmp(const struct dstr *str1, const char *str2, - const size_t n); -static inline int dstr_ncmpi(const struct dstr *str1, const char *str2, - const size_t n); +static inline int dstr_ncmp(const struct dstr *str1, const char *str2, const size_t n); +static inline int dstr_ncmpi(const struct dstr *str1, const char *str2, const size_t n); EXPORT void dstr_depad(struct dstr *dst); -EXPORT void dstr_left(struct dstr *dst, const struct dstr *str, - const size_t pos); -EXPORT void dstr_mid(struct dstr *dst, const struct dstr *str, - const size_t start, const size_t count); -EXPORT void dstr_right(struct dstr *dst, const struct dstr *str, - const size_t pos); +EXPORT void dstr_left(struct dstr *dst, const struct dstr *str, const size_t pos); +EXPORT void dstr_mid(struct dstr *dst, const struct dstr *str, const size_t start, const size_t count); +EXPORT void dstr_right(struct dstr *dst, const struct dstr *str, const size_t pos); static inline char dstr_end(const struct dstr *str); @@ -306,14 +295,12 @@ static inline int dstr_cmpi(const struct dstr *str1, const char *str2) return astrcmpi(str1->array, str2); } -static inline int dstr_ncmp(const struct dstr *str1, const char *str2, - const size_t n) +static inline int dstr_ncmp(const struct dstr *str1, const char *str2, const size_t n) { return astrcmp_n(str1->array, str2, n); } -static inline int dstr_ncmpi(const struct dstr *str1, const char *str2, - const size_t n) +static inline int dstr_ncmpi(const struct dstr *str1, const char *str2, const size_t n) { return astrcmpi_n(str1->array, str2, n); } diff --git a/libobs/util/file-serializer.c b/libobs/util/file-serializer.c index f9ba2b004..df1df93b9 100644 --- a/libobs/util/file-serializer.c +++ b/libobs/util/file-serializer.c @@ -23,8 +23,7 @@ static size_t file_input_read(void *file, void *data, size_t size) return fread(data, 1, size, file); } -static int64_t file_input_seek(void *file, int64_t offset, - enum serialize_seek_type seek_type) +static int64_t file_input_seek(void *file, int64_t offset, enum serialize_seek_type seek_type) { int origin = SEEK_SET; @@ -84,8 +83,7 @@ static size_t file_output_write(void *sdata, const void *data, size_t size) return fwrite(data, 1, size, out->file); } -static int64_t file_output_seek(void *sdata, int64_t offset, - enum serialize_seek_type seek_type) +static int64_t file_output_seek(void *sdata, int64_t offset, enum serialize_seek_type seek_type) { struct file_output_data *out = sdata; int origin = SEEK_SET; @@ -133,8 +131,7 @@ bool file_output_serializer_init(struct serializer *s, const char *path) return true; } -bool file_output_serializer_init_safe(struct serializer *s, const char *path, - const char *temp_ext) +bool file_output_serializer_init_safe(struct serializer *s, const char *path, const char *temp_ext) { struct dstr temp_name = {0}; struct file_output_data *out; diff --git a/libobs/util/file-serializer.h b/libobs/util/file-serializer.h index 93a691495..e0d44ee12 100644 --- a/libobs/util/file-serializer.h +++ b/libobs/util/file-serializer.h @@ -26,9 +26,7 @@ EXPORT bool file_input_serializer_init(struct serializer *s, const char *path); EXPORT void file_input_serializer_free(struct serializer *s); EXPORT bool file_output_serializer_init(struct serializer *s, const char *path); -EXPORT bool file_output_serializer_init_safe(struct serializer *s, - const char *path, - const char *temp_ext); +EXPORT bool file_output_serializer_init_safe(struct serializer *s, const char *path, const char *temp_ext); EXPORT void file_output_serializer_free(struct serializer *s); #ifdef __cplusplus diff --git a/libobs/util/lexer.c b/libobs/util/lexer.c index 98fefa878..a69634c15 100644 --- a/libobs/util/lexer.c +++ b/libobs/util/lexer.c @@ -190,8 +190,8 @@ bool valid_float_str(const char *str, size_t n) /* ------------------------------------------------------------------------- */ -void error_data_add(struct error_data *data, const char *file, uint32_t row, - uint32_t column, const char *msg, int level) +void error_data_add(struct error_data *data, const char *file, uint32_t row, uint32_t column, const char *msg, + int level) { struct error_item item; @@ -216,8 +216,7 @@ char *error_data_buildstring(struct error_data *ed) dstr_init(&str); for (i = 0; i < ed->errors.num; i++) { struct error_item *item = items + i; - dstr_catf(&str, "%s (%u, %u): %s\n", item->file, item->row, - item->column, item->error); + dstr_catf(&str, "%s (%u, %u): %s\n", item->file, item->row, item->column, item->error); } return str.array; @@ -237,8 +236,7 @@ static inline enum base_token_type get_char_token_type(const char ch) return BASETOKEN_OTHER; } -bool lexer_getbasetoken(struct lexer *lex, struct base_token *token, - enum ignore_whitespace iws) +bool lexer_getbasetoken(struct lexer *lex, struct base_token *token, enum ignore_whitespace iws) { const char *offset = lex->offset; const char *token_start = NULL; @@ -253,17 +251,14 @@ bool lexer_getbasetoken(struct lexer *lex, struct base_token *token, enum base_token_type new_type = get_char_token_type(ch); if (type == BASETOKEN_NONE) { - if (new_type == BASETOKEN_WHITESPACE && - ignore_whitespace) + if (new_type == BASETOKEN_WHITESPACE && ignore_whitespace) continue; token_start = offset - 1; type = new_type; - if (type != BASETOKEN_DIGIT && - type != BASETOKEN_ALPHA) { - if (is_newline(ch) && - is_newline_pair(ch, *offset)) { + if (type != BASETOKEN_DIGIT && type != BASETOKEN_ALPHA) { + if (is_newline(ch) && is_newline_pair(ch, *offset)) { offset++; } break; @@ -285,8 +280,7 @@ bool lexer_getbasetoken(struct lexer *lex, struct base_token *token, return false; } -void lexer_getstroffset(const struct lexer *lex, const char *str, uint32_t *row, - uint32_t *col) +void lexer_getstroffset(const struct lexer *lex, const char *str, uint32_t *row, uint32_t *col) { uint32_t cur_col = 1, cur_row = 1; const char *text = lex->text; diff --git a/libobs/util/lexer.h b/libobs/util/lexer.h index ad65174f2..dd95560fb 100644 --- a/libobs/util/lexer.h +++ b/libobs/util/lexer.h @@ -65,10 +65,8 @@ static inline bool strref_is_empty(const struct strref *str) EXPORT int strref_cmp(const struct strref *str1, const char *str2); EXPORT int strref_cmpi(const struct strref *str1, const char *str2); -EXPORT int strref_cmp_strref(const struct strref *str1, - const struct strref *str2); -EXPORT int strref_cmpi_strref(const struct strref *str1, - const struct strref *str2); +EXPORT int strref_cmp_strref(const struct strref *str1, const struct strref *str2); +EXPORT int strref_cmpi_strref(const struct strref *str1, const struct strref *str2); /* ------------------------------------------------------------------------- */ @@ -144,8 +142,7 @@ static inline void base_token_clear(struct base_token *t) memset(t, 0, sizeof(struct base_token)); } -static inline void base_token_copy(struct base_token *dst, - struct base_token *src) +static inline void base_token_copy(struct base_token *dst, struct base_token *src) { memcpy(dst, src, sizeof(struct base_token)); } @@ -197,16 +194,14 @@ static inline void error_data_free(struct error_data *data) da_free(data->errors); } -static inline const struct error_item *error_data_item(struct error_data *ed, - size_t idx) +static inline const struct error_item *error_data_item(struct error_data *ed, size_t idx) { return ed->errors.array + idx; } EXPORT char *error_data_buildstring(struct error_data *ed); -EXPORT void error_data_add(struct error_data *ed, const char *file, - uint32_t row, uint32_t column, const char *msg, +EXPORT void error_data_add(struct error_data *ed, const char *file, uint32_t row, uint32_t column, const char *msg, int level); static inline size_t error_data_type_count(struct error_data *ed, int type) @@ -269,11 +264,9 @@ static inline void lexer_reset(struct lexer *lex) enum ignore_whitespace { PARSE_WHITESPACE, IGNORE_WHITESPACE }; -EXPORT bool lexer_getbasetoken(struct lexer *lex, struct base_token *t, - enum ignore_whitespace iws); +EXPORT bool lexer_getbasetoken(struct lexer *lex, struct base_token *t, enum ignore_whitespace iws); -EXPORT void lexer_getstroffset(const struct lexer *lex, const char *str, - uint32_t *row, uint32_t *col); +EXPORT void lexer_getstroffset(const struct lexer *lex, const char *str, uint32_t *row, uint32_t *col); #ifdef __cplusplus } diff --git a/libobs/util/pipe-posix.c b/libobs/util/pipe-posix.c index 6f06752d8..cf97d4562 100644 --- a/libobs/util/pipe-posix.c +++ b/libobs/util/pipe-posix.c @@ -31,8 +31,7 @@ struct os_process_pipe { FILE *err_file; }; -os_process_pipe_t *os_process_pipe_create_internal(const char *bin, char **argv, - const char *type) +os_process_pipe_t *os_process_pipe_create_internal(const char *bin, char **argv, const char *type) { struct os_process_pipe process_pipe = {0}; struct os_process_pipe *out; @@ -75,27 +74,21 @@ os_process_pipe_t *os_process_pipe_create_internal(const char *bin, char **argv, if (process_pipe.read_pipe) { posix_spawn_file_actions_addclose(&file_actions, mainfds[0]); if (mainfds[1] != STDOUT_FILENO) { - posix_spawn_file_actions_adddup2( - &file_actions, mainfds[1], STDOUT_FILENO); - posix_spawn_file_actions_addclose(&file_actions, - mainfds[0]); + posix_spawn_file_actions_adddup2(&file_actions, mainfds[1], STDOUT_FILENO); + posix_spawn_file_actions_addclose(&file_actions, mainfds[0]); } } else { if (mainfds[0] != STDIN_FILENO) { - posix_spawn_file_actions_adddup2( - &file_actions, mainfds[0], STDIN_FILENO); - posix_spawn_file_actions_addclose(&file_actions, - mainfds[1]); + posix_spawn_file_actions_adddup2(&file_actions, mainfds[0], STDIN_FILENO); + posix_spawn_file_actions_addclose(&file_actions, mainfds[1]); } } posix_spawn_file_actions_addclose(&file_actions, errfds[0]); - posix_spawn_file_actions_adddup2(&file_actions, errfds[1], - STDERR_FILENO); + posix_spawn_file_actions_adddup2(&file_actions, errfds[1], STDERR_FILENO); int pid; - int ret = posix_spawn(&pid, bin, &file_actions, NULL, - (char *const *)argv, NULL); + int ret = posix_spawn(&pid, bin, &file_actions, NULL, (char *const *)argv, NULL); posix_spawn_file_actions_destroy(&file_actions); @@ -126,8 +119,7 @@ os_process_pipe_t *os_process_pipe_create_internal(const char *bin, char **argv, return out; } -os_process_pipe_t *os_process_pipe_create(const char *cmd_line, - const char *type) +os_process_pipe_t *os_process_pipe_create(const char *cmd_line, const char *type) { if (!cmd_line) return NULL; @@ -136,8 +128,7 @@ os_process_pipe_t *os_process_pipe_create(const char *cmd_line, return os_process_pipe_create_internal("/bin/sh", argv, type); } -os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, - const char *type) +os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, const char *type) { char **argv = os_process_args_get_argv(args); return os_process_pipe_create_internal(argv[0], argv, type); @@ -180,8 +171,7 @@ size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, size_t len) return fread(data, 1, len, pp->file); } -size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, - size_t len) +size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, size_t len) { if (!pp) { return 0; @@ -190,8 +180,7 @@ size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, return fread(data, 1, len, pp->err_file); } -size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, - size_t len) +size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, size_t len) { if (!pp) { return 0; diff --git a/libobs/util/pipe-windows.c b/libobs/util/pipe-windows.c index 3bceab522..a73780a79 100644 --- a/libobs/util/pipe-windows.c +++ b/libobs/util/pipe-windows.c @@ -43,8 +43,7 @@ static bool create_pipe(HANDLE *input, HANDLE *output) return true; } -static inline bool create_process(const char *cmd_line, HANDLE stdin_handle, - HANDLE stdout_handle, HANDLE stderr_handle, +static inline bool create_process(const char *cmd_line, HANDLE stdin_handle, HANDLE stdout_handle, HANDLE stderr_handle, HANDLE *process) { PROCESS_INFORMATION pi = {0}; @@ -65,8 +64,7 @@ static inline bool create_process(const char *cmd_line, HANDLE stdin_handle, os_utf8_to_wcs_ptr(cmd_line, 0, &cmd_line_w); if (cmd_line_w) { - success = !!CreateProcessW(NULL, cmd_line_w, NULL, NULL, true, - flags, NULL, NULL, &si, &pi); + success = !!CreateProcessW(NULL, cmd_line_w, NULL, NULL, true, flags, NULL, NULL, &si, &pi); if (success) { *process = pi.hProcess; @@ -74,8 +72,7 @@ static inline bool create_process(const char *cmd_line, HANDLE stdin_handle, } else { // Not logging the full command line is intentional // as it may contain stream keys etc. - blog(LOG_ERROR, "CreateProcessW failed: %lu", - GetLastError()); + blog(LOG_ERROR, "CreateProcessW failed: %lu", GetLastError()); } bfree(cmd_line_w); @@ -84,8 +81,7 @@ static inline bool create_process(const char *cmd_line, HANDLE stdin_handle, return success; } -os_process_pipe_t *os_process_pipe_create(const char *cmd_line, - const char *type) +os_process_pipe_t *os_process_pipe_create(const char *cmd_line, const char *type) { os_process_pipe_t *pp = NULL; bool read_pipe; @@ -111,8 +107,7 @@ os_process_pipe_t *os_process_pipe_create(const char *cmd_line, read_pipe = *type == 'r'; - success = !!SetHandleInformation(read_pipe ? input : output, - HANDLE_FLAG_INHERIT, false); + success = !!SetHandleInformation(read_pipe ? input : output, HANDLE_FLAG_INHERIT, false); if (!success) { goto error; } @@ -122,9 +117,7 @@ os_process_pipe_t *os_process_pipe_create(const char *cmd_line, goto error; } - success = create_process(cmd_line, read_pipe ? NULL : input, - read_pipe ? output : NULL, err_output, - &process); + success = create_process(cmd_line, read_pipe ? NULL : input, read_pipe ? output : NULL, err_output, &process); if (!success) { goto error; } @@ -152,8 +145,7 @@ static inline void add_backslashes(struct dstr *str, size_t count) dstr_cat_ch(str, '\\'); } -os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, - const char *type) +os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, const char *type) { struct dstr cmd_line = {0}; @@ -165,9 +157,7 @@ os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, while (*argv) { size_t bs_count = 0; const char *arg = *argv; - bool needs_quotes = strlen(arg) == 0 || - strstr(arg, " ") != NULL || - strstr(arg, "\t") != NULL; + bool needs_quotes = strlen(arg) == 0 || strstr(arg, " ") != NULL || strstr(arg, "\t") != NULL; if (cmd_line.len) dstr_cat_ch(&cmd_line, ' '); @@ -250,8 +240,7 @@ size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, size_t len) return 0; } -size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, - size_t len) +size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, size_t len) { DWORD bytes_read; bool success; @@ -260,8 +249,7 @@ size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, return 0; } - success = - !!ReadFile(pp->handle_err, data, (DWORD)len, &bytes_read, NULL); + success = !!ReadFile(pp->handle_err, data, (DWORD)len, &bytes_read, NULL); if (success && bytes_read) { return bytes_read; } else @@ -270,8 +258,7 @@ size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, return 0; } -size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, - size_t len) +size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, size_t len) { DWORD bytes_written; bool success; @@ -283,8 +270,7 @@ size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, return 0; } - success = - !!WriteFile(pp->handle, data, (DWORD)len, &bytes_written, NULL); + success = !!WriteFile(pp->handle, data, (DWORD)len, &bytes_written, NULL); if (success && bytes_written) { return bytes_written; } diff --git a/libobs/util/pipe.c b/libobs/util/pipe.c index 592848776..fdfa1f1e1 100644 --- a/libobs/util/pipe.c +++ b/libobs/util/pipe.c @@ -40,8 +40,7 @@ void os_process_args_add_arg(struct os_process_args *args, const char *arg) da_insert(args->arguments, args->arguments.num - 1, &str); } -void os_process_args_add_argf(struct os_process_args *args, const char *format, - ...) +void os_process_args_add_argf(struct os_process_args *args, const char *format, ...) { va_list va_args; struct dstr tmp = {0}; diff --git a/libobs/util/pipe.h b/libobs/util/pipe.h index 2c39ad754..c803cf313 100644 --- a/libobs/util/pipe.h +++ b/libobs/util/pipe.h @@ -28,22 +28,16 @@ typedef struct os_process_pipe os_process_pipe_t; struct os_process_args; typedef struct os_process_args os_process_args_t; -EXPORT os_process_pipe_t *os_process_pipe_create(const char *cmd_line, - const char *type); -EXPORT os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, - const char *type); +EXPORT os_process_pipe_t *os_process_pipe_create(const char *cmd_line, const char *type); +EXPORT os_process_pipe_t *os_process_pipe_create2(const os_process_args_t *args, const char *type); EXPORT int os_process_pipe_destroy(os_process_pipe_t *pp); -EXPORT size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, - size_t len); -EXPORT size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, - size_t len); -EXPORT size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, - size_t len); +EXPORT size_t os_process_pipe_read(os_process_pipe_t *pp, uint8_t *data, size_t len); +EXPORT size_t os_process_pipe_read_err(os_process_pipe_t *pp, uint8_t *data, size_t len); +EXPORT size_t os_process_pipe_write(os_process_pipe_t *pp, const uint8_t *data, size_t len); EXPORT struct os_process_args *os_process_args_create(const char *executable); -EXPORT void os_process_args_add_arg(struct os_process_args *args, - const char *arg); +EXPORT void os_process_args_add_arg(struct os_process_args *args, const char *arg); #ifndef _MSC_VER __attribute__((__format__(__printf__, 2, 3))) #endif diff --git a/libobs/util/platform-nix-dbus.c b/libobs/util/platform-nix-dbus.c index e137c5b99..36fdcf9b5 100644 --- a/libobs/util/platform-nix-dbus.c +++ b/libobs/util/platform-nix-dbus.c @@ -66,8 +66,7 @@ static const struct service_info services[] = { }, }; -static const size_t num_services = - (sizeof(services) / sizeof(struct service_info)); +static const size_t num_services = (sizeof(services) / sizeof(struct service_info)); struct dbus_sleep_info { const struct service_info *service; @@ -91,8 +90,7 @@ struct dbus_sleep_info *dbus_sleep_info_create(void) info->c = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error); if (!info->c) { - blog(LOG_ERROR, "Could not create dbus connection: %s", - error->message); + blog(LOG_ERROR, "Could not create dbus connection: %s", error->message); bfree(info); return NULL; } @@ -104,15 +102,13 @@ struct dbus_sleep_info *dbus_sleep_info_create(void) if (!service->name) continue; - reply = g_dbus_connection_call_sync( - info->c, "org.freedesktop.DBus", - "/org/freedesktop/DBus", "org.freedesktop.DBus", - "GetNameOwner", g_variant_new("(s)", service->name), - NULL, G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL, NULL); + reply = g_dbus_connection_call_sync(info->c, "org.freedesktop.DBus", "/org/freedesktop/DBus", + "org.freedesktop.DBus", "GetNameOwner", + g_variant_new("(s)", service->name), NULL, + G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL, NULL); if (reply != NULL) { - blog(LOG_DEBUG, "Found dbus service: %s", - service->name); + blog(LOG_DEBUG, "Found dbus service: %s", service->name); info->service = service; info->type = (enum service_type)i; return info; @@ -123,8 +119,7 @@ struct dbus_sleep_info *dbus_sleep_info_create(void) return NULL; } -void dbus_inhibit_sleep(struct dbus_sleep_info *info, const char *reason, - bool active) +void dbus_inhibit_sleep(struct dbus_sleep_info *info, const char *reason, bool active) { g_autoptr(GVariant) reply = NULL; g_autoptr(GError) error = NULL; @@ -146,9 +141,7 @@ void dbus_inhibit_sleep(struct dbus_sleep_info *info, const char *reason, switch (info->type) { case MATE_SM: case GNOME_SM: - params = g_variant_new("(s@usu)", program, - g_variant_new_uint32(xid), - reason, flags); + params = g_variant_new("(s@usu)", program, g_variant_new_uint32(xid), reason, flags); break; default: params = g_variant_new("(ss)", program, reason); @@ -158,14 +151,11 @@ void dbus_inhibit_sleep(struct dbus_sleep_info *info, const char *reason, params = g_variant_new("(u)", info->cookie); } - reply = g_dbus_connection_call_sync( - info->c, info->service->name, info->service->path, - info->service->interface, method, params, NULL, - G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); + reply = g_dbus_connection_call_sync(info->c, info->service->name, info->service->path, info->service->interface, + method, params, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, &error); if (error != NULL) { - blog(LOG_ERROR, "Failed to call %s: %s", method, - error->message); + blog(LOG_ERROR, "Failed to call %s: %s", method, error->message); return; } diff --git a/libobs/util/platform-nix-portal.c b/libobs/util/platform-nix-portal.c index 2f0206fec..d26b4295d 100644 --- a/libobs/util/platform-nix-portal.c +++ b/libobs/util/platform-nix-portal.c @@ -31,8 +31,7 @@ struct portal_inhibit_info { bool active; }; -static void new_request(struct portal_inhibit_info *info, char **out_token, - char **out_path) +static void new_request(struct portal_inhibit_info *info, char **out_token, char **out_path) { struct dstr token; struct dstr path; @@ -45,8 +44,7 @@ static void new_request(struct portal_inhibit_info *info, char **out_token, *out_token = token.array; dstr_init(&path); - dstr_printf(&path, "/org/freedesktop/portal/desktop/request/%s/%s", - info->sender_name, token.array); + dstr_printf(&path, "/org/freedesktop/portal/desktop/request/%s/%s", info->sender_name, token.array); *out_path = path.array; } @@ -64,11 +62,8 @@ static inline void remove_inhibit_data(struct portal_inhibit_info *info) info->active = false; } -static void response_received(GDBusConnection *bus, const char *sender_name, - const char *object_path, - const char *interface_name, - const char *signal_name, GVariant *parameters, - gpointer data) +static void response_received(GDBusConnection *bus, const char *sender_name, const char *object_path, + const char *interface_name, const char *signal_name, GVariant *parameters, gpointer data) { UNUSED_PARAMETER(bus); UNUSED_PARAMETER(sender_name); @@ -92,8 +87,7 @@ static void response_received(GDBusConnection *bus, const char *sender_name, unsubscribe_from_request(info); } -static void inhibited_cb(GObject *source_object, GAsyncResult *result, - gpointer user_data) +static void inhibited_cb(GObject *source_object, GAsyncResult *result, gpointer user_data) { UNUSED_PARAMETER(source_object); @@ -105,8 +99,7 @@ static void inhibited_cb(GObject *source_object, GAsyncResult *result, if (error != NULL) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, "Failed to inhibit: %s", - error->message); + blog(LOG_ERROR, "Failed to inhibit: %s", error->message); unsubscribe_from_request(info); remove_inhibit_data(info); } @@ -124,31 +117,25 @@ static void do_inhibit(struct portal_inhibit_info *info, const char *reason) new_request(info, &token, &info->request_path); - info->signal_id = g_dbus_connection_signal_subscribe( - info->c, PORTAL_NAME, "org.freedesktop.portal.Request", - "Response", info->request_path, NULL, - G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, response_received, info, - NULL); + info->signal_id = g_dbus_connection_signal_subscribe(info->c, PORTAL_NAME, "org.freedesktop.portal.Request", + "Response", info->request_path, NULL, + G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, response_received, info, + NULL); g_variant_builder_init(&options, G_VARIANT_TYPE_VARDICT); - g_variant_builder_add(&options, "{sv}", "handle_token", - g_variant_new_string(token)); - g_variant_builder_add(&options, "{sv}", "reason", - g_variant_new_string(reason)); + g_variant_builder_add(&options, "{sv}", "handle_token", g_variant_new_string(token)); + g_variant_builder_add(&options, "{sv}", "reason", g_variant_new_string(reason)); bfree(token); info->cancellable = g_cancellable_new(); - g_dbus_connection_call(info->c, PORTAL_NAME, - "/org/freedesktop/portal/desktop", + g_dbus_connection_call(info->c, PORTAL_NAME, "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Inhibit", "Inhibit", - g_variant_new("(sua{sv})", "", flags, &options), - NULL, G_DBUS_CALL_FLAGS_NONE, -1, + g_variant_new("(sua{sv})", "", flags, &options), NULL, G_DBUS_CALL_FLAGS_NONE, -1, info->cancellable, inhibited_cb, info); } -static void uninhibited_cb(GObject *source_object, GAsyncResult *result, - gpointer user_data) +static void uninhibited_cb(GObject *source_object, GAsyncResult *result, gpointer user_data) { UNUSED_PARAMETER(source_object); @@ -171,12 +158,9 @@ static void do_uninhibit(struct portal_inhibit_info *info) g_cancellable_cancel(info->cancellable); g_clear_object(&info->cancellable); } else { - g_dbus_connection_call(info->c, PORTAL_NAME, info->request_path, - "org.freedesktop.portal.Request", - "Close", g_variant_new("()"), - G_VARIANT_TYPE_UNIT, - G_DBUS_CALL_FLAGS_NONE, -1, NULL, - uninhibited_cb, info); + g_dbus_connection_call(info->c, PORTAL_NAME, info->request_path, "org.freedesktop.portal.Request", + "Close", g_variant_new("()"), G_VARIANT_TYPE_UNIT, G_DBUS_CALL_FLAGS_NONE, -1, + NULL, uninhibited_cb, info); } remove_inhibit_data(info); @@ -204,22 +188,18 @@ struct portal_inhibit_info *portal_inhibit_info_create(void) info->c = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error); if (!info->c) { - blog(LOG_ERROR, "Could not create dbus connection: %s", - error->message); + blog(LOG_ERROR, "Could not create dbus connection: %s", error->message); bfree(info); return NULL; } - info->sender_name = - bstrdup(g_dbus_connection_get_unique_name(info->c) + 1); + info->sender_name = bstrdup(g_dbus_connection_get_unique_name(info->c) + 1); while ((aux = strstr(info->sender_name, ".")) != NULL) *aux = '_'; - reply = g_dbus_connection_call_sync( - info->c, "org.freedesktop.DBus", "/org/freedesktop/DBus", - "org.freedesktop.DBus", "GetNameOwner", - g_variant_new("(s)", PORTAL_NAME), NULL, - G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL, NULL); + reply = g_dbus_connection_call_sync(info->c, "org.freedesktop.DBus", "/org/freedesktop/DBus", + "org.freedesktop.DBus", "GetNameOwner", g_variant_new("(s)", PORTAL_NAME), + NULL, G_DBUS_CALL_FLAGS_NO_AUTO_START, -1, NULL, NULL); if (reply != NULL) { blog(LOG_DEBUG, "Found portal inhibitor"); @@ -230,8 +210,7 @@ struct portal_inhibit_info *portal_inhibit_info_create(void) return NULL; } -void portal_inhibit(struct portal_inhibit_info *info, const char *reason, - bool active) +void portal_inhibit(struct portal_inhibit_info *info, const char *reason, bool active) { if (active == info->active) return; diff --git a/libobs/util/platform-nix.c b/libobs/util/platform-nix.c index a76416451..4bbc99390 100644 --- a/libobs/util/platform-nix.c +++ b/libobs/util/platform-nix.c @@ -74,8 +74,7 @@ void *os_dlopen(const char *path) dstr_init_copy(&dylib_name, path); #ifdef __APPLE__ - if (!dstr_find(&dylib_name, ".framework") && - !dstr_find(&dylib_name, ".plugin") && + if (!dstr_find(&dylib_name, ".framework") && !dstr_find(&dylib_name, ".plugin") && !dstr_find(&dylib_name, ".dylib") && !dstr_find(&dylib_name, ".so")) #else if (!dstr_find(&dylib_name, ".so")) @@ -94,8 +93,7 @@ void *os_dlopen(const char *path) void *res = dlopen(dylib_name.array, RTLD_LAZY); #endif if (!res) - blog(LOG_ERROR, "os_dlopen(%s->%s): %s\n", path, - dylib_name.array, dlerror()); + blog(LOG_ERROR, "os_dlopen(%s->%s): %s\n", path, dylib_name.array, dlerror()); dstr_free(&dylib_name); return res; @@ -196,13 +194,12 @@ double os_cpu_usage_info_query(os_cpu_usage_info_t *info) return 0.0; cur_cpu_time = times(&time_sample); - if (cur_cpu_time <= info->last_cpu_time || - time_sample.tms_stime < info->last_sys_time || + if (cur_cpu_time <= info->last_cpu_time || time_sample.tms_stime < info->last_sys_time || time_sample.tms_utime < info->last_user_time) return 0.0; - percent = (double)(time_sample.tms_stime - info->last_sys_time + - (time_sample.tms_utime - info->last_user_time)); + percent = + (double)(time_sample.tms_stime - info->last_sys_time + (time_sample.tms_utime - info->last_user_time)); percent /= (double)(cur_cpu_time - info->last_cpu_time); percent /= (double)info->core_count; @@ -291,8 +288,7 @@ int os_get_config_path(char *dst, size_t size, const char *name) if (!name || !*name) { return snprintf(dst, size, "%s/.config", home_ptr); } else { - return snprintf(dst, size, "%s/.config/%s", home_ptr, - name); + return snprintf(dst, size, "%s/.config/%s", home_ptr, name); } } else { if (!name || !*name) @@ -356,8 +352,7 @@ int os_get_program_data_path(char *dst, size_t size, const char *name) char *os_get_program_data_path_ptr(const char *name) { - size_t len = - snprintf(NULL, 0, "/usr/local/share/%s", !!name ? name : ""); + size_t len = snprintf(NULL, 0, "/usr/local/share/%s", !!name ? name : ""); char *str = bmalloc(len + 1); snprintf(str, len + 1, "/usr/local/share/%s", !!name ? name : ""); str[len] = 0; @@ -427,10 +422,8 @@ char *os_get_executable_path_ptr(const char *name) int sysctlname[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, -1}; size_t pathlen = PATH_MAX; ssize_t count; - if (sysctl(sysctlname, nitems(sysctlname), exe, &pathlen, NULL, 0) == - -1) { - blog(LOG_ERROR, "sysctl(KERN_PROC_PATHNAME) failed, errno %d", - errno); + if (sysctl(sysctlname, nitems(sysctlname), exe, &pathlen, NULL, 0) == -1) { + blog(LOG_ERROR, "sysctl(KERN_PROC_PATHNAME) failed, errno %d", errno); return NULL; } count = pathlen; @@ -723,13 +716,11 @@ struct dbus_sleep_info; struct portal_inhibit_info; extern struct dbus_sleep_info *dbus_sleep_info_create(void); -extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep, - bool active); +extern void dbus_inhibit_sleep(struct dbus_sleep_info *dbus, const char *sleep, bool active); extern void dbus_sleep_info_destroy(struct dbus_sleep_info *dbus); extern struct portal_inhibit_info *portal_inhibit_info_create(void); -extern void portal_inhibit(struct portal_inhibit_info *portal, - const char *reason, bool active); +extern void portal_inhibit(struct portal_inhibit_info *portal, const char *reason, bool active); extern void portal_inhibit_info_destroy(struct portal_inhibit_info *portal); #endif @@ -774,8 +765,7 @@ os_inhibit_t *os_inhibit_sleep_create(const char *reason) posix_spawnattr_setsigmask(&info->attr, &set); sigaddset(&set, SIGPIPE); posix_spawnattr_setsigdefault(&info->attr, &set); - posix_spawnattr_setflags(&info->attr, POSIX_SPAWN_SETSIGDEF | - POSIX_SPAWN_SETSIGMASK); + posix_spawnattr_setflags(&info->attr, POSIX_SPAWN_SETSIGDEF | POSIX_SPAWN_SETSIGMASK); info->reason = bstrdup(reason); return info; @@ -788,8 +778,7 @@ static void reset_screensaver(os_inhibit_t *info) char *argv[3] = {(char *)"xdg-screensaver", (char *)"reset", NULL}; pid_t pid; - int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr, argv, - environ); + int err = posix_spawnp(&pid, "xdg-screensaver", NULL, &info->attr, argv, environ); if (err == 0) { int status; while (waitpid(pid, &status, 0) == -1) @@ -833,8 +822,7 @@ bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active) return true; if (active) { - ret = pthread_create(&info->screensaver_thread, NULL, - &screensaver_thread, info); + ret = pthread_create(&info->screensaver_thread, NULL, &screensaver_thread, info); if (ret < 0) { blog(LOG_ERROR, "Failed to create screensaver " "inhibitor thread"); @@ -929,8 +917,7 @@ static void os_get_cores_internal(void) continue; if (dstr_is_empty(&proc_phys_ids) || - (!dstr_is_empty(&proc_phys_ids) && - !dstr_find(&proc_phys_ids, proc_phys_id.array))) { + (!dstr_is_empty(&proc_phys_ids) && !dstr_find(&proc_phys_ids, proc_phys_id.array))) { dstr_cat_dstr(&proc_phys_ids, &proc_phys_id); dstr_cat(&proc_phys_ids, " "); core_count += atoi(start); @@ -1029,8 +1016,7 @@ uint64_t os_get_sys_free_size(void) { uint64_t mem_free = 0; size_t length = sizeof(mem_free); - if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL, - 0) < 0) + if (sysctlbyname("vm.stats.vm.v_free_count", &mem_free, &length, NULL, 0) < 0) return 0; return mem_free; } @@ -1039,8 +1025,7 @@ static inline bool os_get_proc_memory_usage_internal(struct kinfo_proc *kinfo) { int mib[] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()}; size_t length = sizeof(*kinfo); - if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), kinfo, &length, NULL, 0) < - 0) + if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), kinfo, &length, NULL, 0) < 0) return false; return true; } @@ -1051,8 +1036,7 @@ bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage) if (!os_get_proc_memory_usage_internal(&kinfo)) return false; - usage->resident_size = - (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE); + usage->resident_size = (uint64_t)kinfo.ki_rssize * sysconf(_SC_PAGESIZE); usage->virtual_size = (uint64_t)kinfo.ki_size; return true; } @@ -1096,9 +1080,8 @@ static inline bool os_get_proc_memory_usage_internal(statm_t *statm) if (!f) return false; - if (fscanf(f, "%lu %lu %lu %lu %lu %lu %lu", &statm->virtual_size, - &statm->resident_size, &statm->share_pages, &statm->text, - &statm->library, &statm->data, &statm->dirty_pages) != 7) { + if (fscanf(f, "%lu %lu %lu %lu %lu %lu %lu", &statm->virtual_size, &statm->resident_size, &statm->share_pages, + &statm->text, &statm->library, &statm->data, &statm->dirty_pages) != 7) { fclose(f); return false; } @@ -1113,8 +1096,7 @@ bool os_get_proc_memory_usage(os_proc_memory_usage_t *usage) if (!os_get_proc_memory_usage_internal(&statm)) return false; - usage->resident_size = - (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE); + usage->resident_size = (uint64_t)statm.resident_size * sysconf(_SC_PAGESIZE); usage->virtual_size = statm.virtual_size; return true; } diff --git a/libobs/util/platform-windows.c b/libobs/util/platform-windows.c index 5cbd2231a..8b562aa04 100644 --- a/libobs/util/platform-windows.c +++ b/libobs/util/platform-windows.c @@ -107,15 +107,11 @@ void *os_dlopen(const char *path) char *message = NULL; - FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_IGNORE_INSERTS | + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS | FORMAT_MESSAGE_ALLOCATE_BUFFER, - NULL, error, - MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - (LPSTR)&message, 0, NULL); + NULL, error, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPSTR)&message, 0, NULL); - blog(LOG_INFO, "LoadLibrary failed for '%s': %s (%lu)", path, - message, error); + blog(LOG_INFO, "LoadLibrary failed for '%s': %s (%lu)", path, message, error); if (message) LocalFree(message); @@ -142,9 +138,7 @@ static bool has_qt5_import(VOID *base, PIMAGE_NT_HEADERS nt_headers) { __try { PIMAGE_DATA_DIRECTORY data_dir; - data_dir = - &nt_headers->OptionalHeader - .DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; + data_dir = &nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_IMPORT]; if (data_dir->Size == 0) return false; @@ -156,8 +150,7 @@ static bool has_qt5_import(VOID *base, PIMAGE_NT_HEADERS nt_headers) /* find the section that contains the export directory */ int i; for (i = 0; i < nt_headers->FileHeader.NumberOfSections; i++) { - if (section->VirtualAddress <= - data_dir->VirtualAddress) { + if (section->VirtualAddress <= data_dir->VirtualAddress) { last_section = section; section++; continue; @@ -175,14 +168,11 @@ static bool has_qt5_import(VOID *base, PIMAGE_NT_HEADERS nt_headers) /* get a pointer to the import directory */ PIMAGE_IMPORT_DESCRIPTOR import; - import = (PIMAGE_IMPORT_DESCRIPTOR)((byte *)base + - data_dir->VirtualAddress - - section->VirtualAddress + + import = (PIMAGE_IMPORT_DESCRIPTOR)((byte *)base + data_dir->VirtualAddress - section->VirtualAddress + section->PointerToRawData); while (import->Name != 0) { - char *name = (char *)((byte *)base + import->Name - - section->VirtualAddress + + char *name = (char *)((byte *)base + import->Name - section->VirtualAddress + section->PointerToRawData); /* qt5? bingo, reject this library */ @@ -205,9 +195,7 @@ static bool has_obs_export(VOID *base, PIMAGE_NT_HEADERS nt_headers) { __try { PIMAGE_DATA_DIRECTORY data_dir; - data_dir = - &nt_headers->OptionalHeader - .DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; + data_dir = &nt_headers->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT]; if (data_dir->Size == 0) return false; @@ -219,8 +207,7 @@ static bool has_obs_export(VOID *base, PIMAGE_NT_HEADERS nt_headers) /* find the section that contains the export directory */ int i; for (i = 0; i < nt_headers->FileHeader.NumberOfSections; i++) { - if (section->VirtualAddress <= - data_dir->VirtualAddress) { + if (section->VirtualAddress <= data_dir->VirtualAddress) { last_section = section; section++; continue; @@ -238,9 +225,7 @@ static bool has_obs_export(VOID *base, PIMAGE_NT_HEADERS nt_headers) /* get a pointer to the export directory */ PIMAGE_EXPORT_DIRECTORY export; - export = (PIMAGE_EXPORT_DIRECTORY)((byte *)base + - data_dir->VirtualAddress - - section->VirtualAddress + + export = (PIMAGE_EXPORT_DIRECTORY)((byte *)base + data_dir->VirtualAddress - section->VirtualAddress + section->PointerToRawData); if (export->NumberOfNames == 0) @@ -248,8 +233,7 @@ static bool has_obs_export(VOID *base, PIMAGE_NT_HEADERS nt_headers) /* get a pointer to the export directory names */ DWORD *names_ptr; - names_ptr = (DWORD *)((byte *)base + export->AddressOfNames - - section->VirtualAddress + + names_ptr = (DWORD *)((byte *)base + export->AddressOfNames - section->VirtualAddress + section->PointerToRawData); /* iterate through each name and see if its an obs plugin */ @@ -257,9 +241,7 @@ static bool has_obs_export(VOID *base, PIMAGE_NT_HEADERS nt_headers) size_t j; for (j = 0; j < export->NumberOfNames; j++) { - name = (CHAR *)base + names_ptr[j] - - section->VirtualAddress + - section->PointerToRawData; + name = (CHAR *)base + names_ptr[j] - section->VirtualAddress + section->PointerToRawData; if (!strcmp(name, "obs_module_load")) { return true; @@ -300,16 +282,14 @@ void get_plugin_info(const char *path, bool *is_obs_plugin, bool *can_load) dstr_free(&dll_name); - hFile = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, - OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); + hFile = CreateFileW(wpath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0); bfree(wpath); if (hFile == INVALID_HANDLE_VALUE) goto cleanup; - hFileMapping = - CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); + hFileMapping = CreateFileMapping(hFile, NULL, PAGE_READONLY, 0, 0, NULL); if (hFileMapping == NULL) goto cleanup; @@ -325,8 +305,7 @@ void get_plugin_info(const char *path, bool *is_obs_plugin, bool *can_load) if (dos_header->e_magic != IMAGE_DOS_SIGNATURE) goto cleanup; - nt_headers = (PIMAGE_NT_HEADERS)((byte *)dos_header + - dos_header->e_lfanew); + nt_headers = (PIMAGE_NT_HEADERS)((byte *)dos_header + dos_header->e_lfanew); if (nt_headers->Signature != IMAGE_NT_SIGNATURE) goto cleanup; @@ -384,8 +363,7 @@ os_cpu_usage_info_t *os_cpu_usage_info_start(void) GetSystemInfo(&si); GetSystemTimeAsFileTime(&info->last_time.ft); - GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, - &info->last_sys_time.ft, &info->last_user_time.ft); + GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, &info->last_sys_time.ft, &info->last_user_time.ft); info->core_count = si.dwNumberOfProcessors; return info; @@ -401,11 +379,9 @@ double os_cpu_usage_info_query(os_cpu_usage_info_t *info) return 0.0; GetSystemTimeAsFileTime(&cur_time.ft); - GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, &cur_sys_time.ft, - &cur_user_time.ft); + GetProcessTimes(GetCurrentProcess(), &dummy, &dummy, &cur_sys_time.ft, &cur_user_time.ft); - percent = (double)(cur_sys_time.val - info->last_sys_time.val + - (cur_user_time.val - info->last_user_time.val)); + percent = (double)(cur_sys_time.val - info->last_sys_time.val + (cur_user_time.val - info->last_user_time.val)); percent /= (double)(cur_time.val - info->last_time.val); percent /= (double)info->core_count; @@ -425,17 +401,14 @@ void os_cpu_usage_info_destroy(os_cpu_usage_info_t *info) bool os_sleepto_ns(uint64_t time_target) { const uint64_t freq = get_clockfreq(); - const LONGLONG count_target = - util_mul_div64(time_target, freq, 1000000000); + const LONGLONG count_target = util_mul_div64(time_target, freq, 1000000000); LARGE_INTEGER count; QueryPerformanceCounter(&count); const bool stall = count.QuadPart < count_target; if (stall) { - const DWORD milliseconds = - (DWORD)(((count_target - count.QuadPart) * 1000.0) / - freq); + const DWORD milliseconds = (DWORD)(((count_target - count.QuadPart) * 1000.0) / freq); if (milliseconds > 1) Sleep(milliseconds - 1); @@ -482,13 +455,11 @@ uint64_t os_gettime_ns(void) { LARGE_INTEGER current_time; QueryPerformanceCounter(¤t_time); - return util_mul_div64(current_time.QuadPart, 1000000000, - get_clockfreq()); + return util_mul_div64(current_time.QuadPart, 1000000000, get_clockfreq()); } /* returns [folder]\[name] on windows */ -static int os_get_path_internal(char *dst, size_t size, const char *name, - int folder) +static int os_get_path_internal(char *dst, size_t size, const char *name, int folder) { wchar_t path_utf16[MAX_PATH]; @@ -669,8 +640,7 @@ struct os_dirent *os_readdir(os_dir_t *dir) return NULL; } - os_wcs_to_utf8(dir->wfd.cFileName, 0, dir->out.d_name, - sizeof(dir->out.d_name)); + os_wcs_to_utf8(dir->wfd.cFileName, 0, dir->out.d_name, sizeof(dir->out.d_name)); dir->out.directory = is_dir(&dir->wfd); @@ -693,9 +663,7 @@ int64_t os_get_free_space(const char *path) if (os_get_abs_path(path, abs_path, 512) > 0) { if (os_utf8_to_wcs(abs_path, 0, w_abs_path, 512) > 0) { - BOOL success = GetDiskFreeSpaceExW( - w_abs_path, (PULARGE_INTEGER)&remainingSpace, - NULL, NULL); + BOOL success = GetDiskFreeSpaceExW(w_abs_path, (PULARGE_INTEGER)&remainingSpace, NULL, NULL); if (success) return (int64_t)remainingSpace.QuadPart; } @@ -704,8 +672,7 @@ int64_t os_get_free_space(const char *path) return -1; } -static void make_globent(struct os_globent *ent, WIN32_FIND_DATA *wfd, - const char *pattern) +static void make_globent(struct os_globent *ent, WIN32_FIND_DATA *wfd, const char *pattern) { struct dstr name = {0}; struct dstr path = {0}; @@ -818,8 +785,7 @@ int os_mkdir(const char *path) bfree(path_utf16); if (!success) - return (GetLastError() == ERROR_ALREADY_EXISTS) ? MKDIR_EXISTS - : MKDIR_ERROR; + return (GetLastError() == ERROR_ALREADY_EXISTS) ? MKDIR_EXISTS : MKDIR_ERROR; return MKDIR_SUCCESS; } @@ -837,10 +803,7 @@ int os_rename(const char *old_path, const char *new_path) goto error; } - code = MoveFileExW(old_path_utf16, new_path_utf16, - MOVEFILE_REPLACE_EXISTING) - ? 0 - : -1; + code = MoveFileExW(old_path_utf16, new_path_utf16, MOVEFILE_REPLACE_EXISTING) ? 0 : -1; error: bfree(old_path_utf16); @@ -867,9 +830,7 @@ int os_safe_replace(const char *target, const char *from, const char *backup) if (ReplaceFileW(wtarget, wfrom, wbackup, 0, NULL, NULL)) { code = 0; } else if (GetLastError() == ERROR_FILE_NOT_FOUND) { - code = MoveFileExW(wfrom, wtarget, MOVEFILE_REPLACE_EXISTING) - ? 0 - : -1; + code = MoveFileExW(wfrom, wtarget, MOVEFILE_REPLACE_EXISTING) ? 0 : -1; } fail: @@ -980,12 +941,9 @@ int os_chdir(const char *path) return ret; } -typedef DWORD(WINAPI *get_file_version_info_size_w_t)(LPCWSTR module, - LPDWORD unused); -typedef BOOL(WINAPI *get_file_version_info_w_t)(LPCWSTR module, DWORD unused, - DWORD len, LPVOID data); -typedef BOOL(WINAPI *ver_query_value_w_t)(LPVOID data, LPCWSTR subblock, - LPVOID *buf, PUINT sizeout); +typedef DWORD(WINAPI *get_file_version_info_size_w_t)(LPCWSTR module, LPDWORD unused); +typedef BOOL(WINAPI *get_file_version_info_w_t)(LPCWSTR module, DWORD unused, DWORD len, LPVOID data); +typedef BOOL(WINAPI *ver_query_value_w_t)(LPVOID data, LPCWSTR subblock, LPVOID *buf, PUINT sizeout); static get_file_version_info_size_w_t get_file_version_info_size = NULL; static get_file_version_info_w_t get_file_version_info = NULL; @@ -1008,16 +966,11 @@ static bool initialize_version_functions(void) } } - get_file_version_info_size = - (get_file_version_info_size_w_t)GetProcAddress( - ver, "GetFileVersionInfoSizeW"); - get_file_version_info = (get_file_version_info_w_t)GetProcAddress( - ver, "GetFileVersionInfoW"); - ver_query_value = - (ver_query_value_w_t)GetProcAddress(ver, "VerQueryValueW"); + get_file_version_info_size = (get_file_version_info_size_w_t)GetProcAddress(ver, "GetFileVersionInfoSizeW"); + get_file_version_info = (get_file_version_info_w_t)GetProcAddress(ver, "GetFileVersionInfoW"); + ver_query_value = (ver_query_value_w_t)GetProcAddress(ver, "VerQueryValueW"); - if (!get_file_version_info_size || !get_file_version_info || - !ver_query_value) { + if (!get_file_version_info_size || !get_file_version_info || !ver_query_value) { blog(LOG_ERROR, "Failed to load windows version " "functions"); return false; @@ -1058,8 +1011,7 @@ bool get_dll_ver(const wchar_t *lib, struct win_version_info *ver_info) success = ver_query_value(data, L"\\", (LPVOID *)&info, &len); if (!success || !info || !len) { - blog(LOG_ERROR, "Failed to get %s version info value", - utf8_lib); + blog(LOG_ERROR, "Failed to get %s version info value", utf8_lib); bfree(data); return false; } @@ -1090,8 +1042,7 @@ bool is_arm64_windows(void) #else USHORT processMachine; USHORT nativeMachine; - bool result = IsWow64Process2(GetCurrentProcess(), &processMachine, - &nativeMachine); + bool result = IsWow64Process2(GetCurrentProcess(), &processMachine, &nativeMachine); return (result && (nativeMachine == IMAGE_FILE_MACHINE_ARM64)); #endif } @@ -1105,8 +1056,7 @@ bool os_get_emulation_status(void) #endif } -void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, - struct reg_dword *info) +void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, struct reg_dword *info) { struct reg_dword reg = {0}; HKEY key; @@ -1123,8 +1073,7 @@ void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, reg.size = sizeof(reg.return_value); - reg.status = RegQueryValueExW(key, value_name, NULL, NULL, - (LPBYTE)®.return_value, ®.size); + reg.status = RegQueryValueExW(key, value_name, NULL, NULL, (LPBYTE)®.return_value, ®.size); RegCloseKey(key); @@ -1140,8 +1089,7 @@ static inline void rtl_get_ver(struct win_version_info *ver) return; NTSTATUS(WINAPI * get_ver) - (RTL_OSVERSIONINFOEXW *) = - (void *)GetProcAddress(ntdll, "RtlGetVersion"); + (RTL_OSVERSIONINFOEXW *) = (void *)GetProcAddress(ntdll, "RtlGetVersion"); if (!get_ver) { return; } @@ -1159,11 +1107,9 @@ static inline void rtl_get_ver(struct win_version_info *ver) ver->revis = 0; } -static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf, - DWORD size) +static inline bool get_reg_sz(HKEY key, const wchar_t *val, wchar_t *buf, DWORD size) { - const LSTATUS status = - RegGetValueW(key, NULL, val, RRF_RT_REG_SZ, NULL, buf, &size); + const LSTATUS status = RegGetValueW(key, NULL, val, RRF_RT_REG_SZ, NULL, buf, &size); return status == ERROR_SUCCESS; } @@ -1180,18 +1126,15 @@ static inline void get_reg_ver(struct win_version_info *ver) size = sizeof(dw_val); - status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL, - (LPBYTE)&dw_val, &size); + status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size); if (status == ERROR_SUCCESS) ver->major = (int)dw_val; - status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL, - (LPBYTE)&dw_val, &size); + status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size); if (status == ERROR_SUCCESS) ver->minor = (int)dw_val; - status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val, - &size); + status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val, &size); if (status == ERROR_SUCCESS) ver->revis = (int)dw_val; @@ -1199,8 +1142,7 @@ static inline void get_reg_ver(struct win_version_info *ver) ver->build = wcstol(str, NULL, 10); } - const wchar_t *release_key = ver->build > 19041 ? L"DisplayVersion" - : L"ReleaseId"; + const wchar_t *release_key = ver->build > 19041 ? L"DisplayVersion" : L"ReleaseId"; if (get_reg_sz(key, release_key, str, sizeof(str))) { os_wcs_to_utf8(str, 0, win_release_id, MAX_SZ_LEN); } @@ -1208,8 +1150,7 @@ static inline void get_reg_ver(struct win_version_info *ver) RegCloseKey(key); } -static inline bool version_higher(struct win_version_info *cur, - struct win_version_info *new) +static inline bool version_higher(struct win_version_info *cur, struct win_version_info *new) { if (new->major > cur->major) { return true; @@ -1232,8 +1173,7 @@ static inline bool version_higher(struct win_version_info *cur, return false; } -static inline void use_higher_ver(struct win_version_info *cur, - struct win_version_info *new) +static inline void use_higher_ver(struct win_version_info *cur, struct win_version_info *new) { if (version_higher(cur, new)) *cur = *new; @@ -1294,8 +1234,7 @@ bool os_inhibit_sleep_set_active(os_inhibit_t *info, bool active) return false; if (active) { - SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | - ES_AWAYMODE_REQUIRED | + SetThreadExecutionState(ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_AWAYMODE_REQUIRED | ES_DISPLAY_REQUIRED); } else { SetThreadExecutionState(ES_CONTINUOUS); @@ -1358,13 +1297,11 @@ static void os_get_cores_internal(void) temp = info; for (DWORD i = 0; i < num; i++) { - if (temp->Relationship == - RelationProcessorCore) { + if (temp->Relationship == RelationProcessorCore) { ULONG_PTR mask = temp->ProcessorMask; physical_cores++; - logical_cores += - num_logical_cores(mask); + logical_cores += num_logical_cores(mask); } temp++; @@ -1426,8 +1363,7 @@ uint64_t os_get_sys_total_size(void) return total_memory; } -static inline bool -os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc) +static inline bool os_get_proc_memory_usage_internal(PROCESS_MEMORY_COUNTERS *pmc) { if (!GetProcessMemoryInfo(GetCurrentProcess(), pmc, sizeof(*pmc))) return false; @@ -1484,11 +1420,9 @@ char *os_generate_uuid(void) bcrash("Failed to get UUID, RPC_STATUS: %l", res); struct dstr uuid_str = {0}; - dstr_printf(&uuid_str, - "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", - uuid.Data1, uuid.Data2, uuid.Data3, uuid.Data4[0], - uuid.Data4[1], uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], - uuid.Data4[5], uuid.Data4[6], uuid.Data4[7]); + dstr_printf(&uuid_str, "%08x-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x", uuid.Data1, uuid.Data2, uuid.Data3, + uuid.Data4[0], uuid.Data4[1], uuid.Data4[2], uuid.Data4[3], uuid.Data4[4], uuid.Data4[5], + uuid.Data4[6], uuid.Data4[7]); return uuid_str.array; } diff --git a/libobs/util/platform.c b/libobs/util/platform.c index 1b9d894aa..548afc03f 100644 --- a/libobs/util/platform.c +++ b/libobs/util/platform.c @@ -258,8 +258,7 @@ bool os_quick_write_mbs_file(const char *path, const char *str, size_t len) return true; } -bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, - bool marker) +bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, bool marker) { FILE *f = os_fopen(path, "wb"); if (!f) @@ -284,9 +283,8 @@ bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, return true; } -bool os_quick_write_utf8_file_safe(const char *path, const char *str, - size_t len, bool marker, - const char *temp_ext, const char *backup_ext) +bool os_quick_write_utf8_file_safe(const char *path, const char *str, size_t len, bool marker, const char *temp_ext, + const char *backup_ext) { struct dstr backup_path = {0}; struct dstr temp_path = {0}; @@ -363,8 +361,7 @@ size_t os_mbs_to_wcs(const char *str, size_t len, wchar_t *dst, size_t dst_size) return out_len; } -size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t *dst, - size_t dst_size) +size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t *dst, size_t dst_size) { size_t in_len; size_t out_len; @@ -380,8 +377,7 @@ size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t *dst, return 0; if (out_len) - out_len = - utf8_to_wchar(str, in_len, dst, out_len + 1, 0); + out_len = utf8_to_wchar(str, in_len, dst, out_len + 1, 0); dst[out_len] = 0; } @@ -413,8 +409,7 @@ size_t os_wcs_to_mbs(const wchar_t *str, size_t len, char *dst, size_t dst_size) return out_len; } -size_t os_wcs_to_utf8(const wchar_t *str, size_t len, char *dst, - size_t dst_size) +size_t os_wcs_to_utf8(const wchar_t *str, size_t len, char *dst, size_t dst_size) { size_t in_len; size_t out_len; @@ -677,8 +672,7 @@ static inline bool valid_string(const char *str) return false; } -static void replace_text(struct dstr *str, size_t pos, size_t len, - const char *new_text) +static void replace_text(struct dstr *str, size_t pos, size_t len, const char *new_text) { struct dstr front = {0}; struct dstr back = {0}; @@ -701,8 +695,7 @@ static void erase_ch(struct dstr *str, size_t pos) *str = new_str; } -char *os_generate_formatted_filename(const char *extension, bool space, - const char *format) +char *os_generate_formatted_filename(const char *extension, bool space, const char *format) { time_t now = time(0); struct tm *cur_time; @@ -712,13 +705,12 @@ char *os_generate_formatted_filename(const char *extension, bool space, const size_t spec_count = 23; static const char *spec[][2] = { - {"%CCYY", "%Y"}, {"%YY", "%y"}, {"%MM", "%m"}, {"%DD", "%d"}, - {"%hh", "%H"}, {"%mm", "%M"}, {"%ss", "%S"}, {"%%", "%%"}, + {"%CCYY", "%Y"}, {"%YY", "%y"}, {"%MM", "%m"}, {"%DD", "%d"}, {"%hh", "%H"}, + {"%mm", "%M"}, {"%ss", "%S"}, {"%%", "%%"}, - {"%a", ""}, {"%A", ""}, {"%b", ""}, {"%B", ""}, - {"%d", ""}, {"%H", ""}, {"%I", ""}, {"%m", ""}, - {"%M", ""}, {"%p", ""}, {"%S", ""}, {"%y", ""}, - {"%Y", ""}, {"%z", ""}, {"%Z", ""}, + {"%a", ""}, {"%A", ""}, {"%b", ""}, {"%B", ""}, {"%d", ""}, + {"%H", ""}, {"%I", ""}, {"%m", ""}, {"%M", ""}, {"%p", ""}, + {"%S", ""}, {"%y", ""}, {"%Y", ""}, {"%z", ""}, {"%Z", ""}, }; char convert[128] = {0}; @@ -735,11 +727,9 @@ char *os_generate_formatted_filename(const char *extension, bool space, if (astrcmp_n(cmp, spec[i][0], len) == 0) { if (strlen(spec[i][1])) - strftime(convert, sizeof(convert), - spec[i][1], cur_time); + strftime(convert, sizeof(convert), spec[i][1], cur_time); else - strftime(convert, sizeof(convert), - spec[i][0], cur_time); + strftime(convert, sizeof(convert), spec[i][0], cur_time); dstr_copy(&c, convert); if (c.len && valid_string(c.array)) @@ -750,35 +740,27 @@ char *os_generate_formatted_filename(const char *extension, bool space, if (!convert[0]) { if (astrcmp_n(cmp, "%FPS", 4) == 0) { if (ovi.fps_den <= 1) { - snprintf(convert, sizeof(convert), "%u", - ovi.fps_num); + snprintf(convert, sizeof(convert), "%u", ovi.fps_num); } else { - const double obsFPS = - (double)ovi.fps_num / - (double)ovi.fps_den; - snprintf(convert, sizeof(convert), - "%.2f", obsFPS); + const double obsFPS = (double)ovi.fps_num / (double)ovi.fps_den; + snprintf(convert, sizeof(convert), "%.2f", obsFPS); } replace_text(&sf, pos, 4, convert); } else if (astrcmp_n(cmp, "%CRES", 5) == 0) { - snprintf(convert, sizeof(convert), "%ux%u", - ovi.base_width, ovi.base_height); + snprintf(convert, sizeof(convert), "%ux%u", ovi.base_width, ovi.base_height); replace_text(&sf, pos, 5, convert); } else if (astrcmp_n(cmp, "%ORES", 5) == 0) { - snprintf(convert, sizeof(convert), "%ux%u", - ovi.output_width, ovi.output_height); + snprintf(convert, sizeof(convert), "%ux%u", ovi.output_width, ovi.output_height); replace_text(&sf, pos, 5, convert); } else if (astrcmp_n(cmp, "%VF", 3) == 0) { - strcpy(convert, get_video_format_name( - ovi.output_format)); + strcpy(convert, get_video_format_name(ovi.output_format)); replace_text(&sf, pos, 3, convert); } else if (astrcmp_n(cmp, "%s", 2) == 0) { - snprintf(convert, sizeof(convert), "%" PRId64, - (int64_t)now); + snprintf(convert, sizeof(convert), "%" PRId64, (int64_t)now); replace_text(&sf, pos, 2, convert); } } @@ -817,13 +799,11 @@ static struct { static void init_timespec_offset(void) { - timespec_offset.ts_valid = - timespec_get(×pec_offset.ts, TIME_UTC) == TIME_UTC; + timespec_offset.ts_valid = timespec_get(×pec_offset.ts, TIME_UTC) == TIME_UTC; timespec_offset.timestamp = os_gettime_ns(); } -struct timespec *os_nstime_to_timespec(uint64_t timestamp, - struct timespec *storage) +struct timespec *os_nstime_to_timespec(uint64_t timestamp, struct timespec *storage) { static pthread_once_t once = PTHREAD_ONCE_INIT; pthread_once(&once, init_timespec_offset); diff --git a/libobs/util/platform.h b/libobs/util/platform.h index d66394f82..f652645bb 100644 --- a/libobs/util/platform.h +++ b/libobs/util/platform.h @@ -48,27 +48,19 @@ EXPORT size_t os_fread_utf8(FILE *file, char **pstr); /* functions purely for convenience */ EXPORT char *os_quick_read_utf8_file(const char *path); -EXPORT bool os_quick_write_utf8_file(const char *path, const char *str, - size_t len, bool marker); -EXPORT bool os_quick_write_utf8_file_safe(const char *path, const char *str, - size_t len, bool marker, - const char *temp_ext, - const char *backup_ext); +EXPORT bool os_quick_write_utf8_file(const char *path, const char *str, size_t len, bool marker); +EXPORT bool os_quick_write_utf8_file_safe(const char *path, const char *str, size_t len, bool marker, + const char *temp_ext, const char *backup_ext); EXPORT char *os_quick_read_mbs_file(const char *path); -EXPORT bool os_quick_write_mbs_file(const char *path, const char *str, - size_t len); +EXPORT bool os_quick_write_mbs_file(const char *path, const char *str, size_t len); EXPORT int64_t os_get_file_size(const char *path); EXPORT int64_t os_get_free_space(const char *path); -EXPORT size_t os_mbs_to_wcs(const char *str, size_t str_len, wchar_t *dst, - size_t dst_size); -EXPORT size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t *dst, - size_t dst_size); -EXPORT size_t os_wcs_to_mbs(const wchar_t *str, size_t len, char *dst, - size_t dst_size); -EXPORT size_t os_wcs_to_utf8(const wchar_t *str, size_t len, char *dst, - size_t dst_size); +EXPORT size_t os_mbs_to_wcs(const char *str, size_t str_len, wchar_t *dst, size_t dst_size); +EXPORT size_t os_utf8_to_wcs(const char *str, size_t len, wchar_t *dst, size_t dst_size); +EXPORT size_t os_wcs_to_mbs(const wchar_t *str, size_t len, char *dst, size_t dst_size); +EXPORT size_t os_wcs_to_utf8(const wchar_t *str, size_t len, char *dst, size_t dst_size); EXPORT size_t os_mbs_to_wcs_ptr(const char *str, size_t len, wchar_t **pstr); EXPORT size_t os_utf8_to_wcs_ptr(const char *str, size_t len, wchar_t **pstr); @@ -170,11 +162,9 @@ EXPORT int os_mkdir(const char *path); EXPORT int os_mkdirs(const char *path); EXPORT int os_rename(const char *old_path, const char *new_path); EXPORT int os_copyfile(const char *file_in, const char *file_out); -EXPORT int os_safe_replace(const char *target_path, const char *from_path, - const char *backup_path); +EXPORT int os_safe_replace(const char *target_path, const char *from_path, const char *backup_path); -EXPORT char *os_generate_formatted_filename(const char *extension, bool space, - const char *format); +EXPORT char *os_generate_formatted_filename(const char *extension, bool space, const char *format); struct os_inhibit_info; typedef struct os_inhibit_info os_inhibit_t; @@ -206,8 +196,7 @@ EXPORT uint64_t os_get_proc_virtual_size(void); EXPORT char *os_generate_uuid(void); EXPORT -struct timespec *os_nstime_to_timespec(uint64_t timestamp, - struct timespec *storage); +struct timespec *os_nstime_to_timespec(uint64_t timestamp, struct timespec *storage); /* clang-format off */ #ifdef __APPLE__ diff --git a/libobs/util/profiler.c b/libobs/util/profiler.c index ff5f48bea..d604a9882 100644 --- a/libobs/util/profiler.c +++ b/libobs/util/profiler.c @@ -93,16 +93,13 @@ static inline uint64_t diff_ns_to_usec(uint64_t prev, uint64_t next) static inline void update_max_probes(profile_times_table *map, size_t val) { - map->max_probe_count = - map->max_probe_count < val ? val : map->max_probe_count; + map->max_probe_count = map->max_probe_count < val ? val : map->max_probe_count; } static void migrate_old_entries(profile_times_table *map, bool limit_items); -static void grow_hashmap(profile_times_table *map, uint64_t usec, - uint64_t count); +static void grow_hashmap(profile_times_table *map, uint64_t usec, uint64_t count); -static void add_hashmap_entry(profile_times_table *map, uint64_t usec, - uint64_t count) +static void add_hashmap_entry(profile_times_table *map, uint64_t usec, uint64_t count) { size_t probes = 1; @@ -176,19 +173,16 @@ static void migrate_old_entries(profile_times_table *map, bool limit_items) if (!map->old_occupied) return; - profile_times_table_entry *entry = - &map->old_entries[map->old_start_index]; + profile_times_table_entry *entry = &map->old_entries[map->old_start_index]; if (!entry->probes) continue; - add_hashmap_entry(map, entry->entry.time_delta, - entry->entry.count); + add_hashmap_entry(map, entry->entry.time_delta, entry->entry.count); map->old_occupied -= 1; } } -static void grow_hashmap(profile_times_table *map, uint64_t usec, - uint64_t count) +static void grow_hashmap(profile_times_table *map, uint64_t usec, uint64_t count) { migrate_old_entries(map, false); @@ -228,8 +222,7 @@ static profile_entry *get_child(profile_entry *parent, const char *name) return init_entry(da_push_back_new(parent->children), name); } -static void merge_call(profile_entry *entry, profile_call *call, - profile_call *prev_call) +static void merge_call(profile_entry *entry, profile_call *call, profile_call *prev_call) { const size_t num = call->children.num; for (size_t i = 0; i < num; i++) { @@ -239,8 +232,7 @@ static void merge_call(profile_entry *entry, profile_call *call, if (entry->expected_time_between_calls != 0 && prev_call) { migrate_old_entries(&entry->times_between_calls, true); - uint64_t usec = diff_ns_to_usec(prev_call->start_time, - call->start_time); + uint64_t usec = diff_ns_to_usec(prev_call->start_time, call->start_time); add_hashmap_entry(&entry->times_between_calls, usec, 1); } @@ -323,14 +315,12 @@ static profile_root_entry *get_root_entry(const char *name) return r_entry; } -void profile_register_root(const char *name, - uint64_t expected_time_between_calls) +void profile_register_root(const char *name, uint64_t expected_time_between_calls) { if (!lock_root()) return; - get_root_entry(name)->entry->expected_time_between_calls = - (expected_time_between_calls + 500) / 1000; + get_root_entry(name)->entry->expected_time_between_calls = (expected_time_between_calls + 500) / 1000; pthread_mutex_unlock(&root_mutex); } @@ -441,14 +431,12 @@ void profile_end(const char *name) static int profiler_time_entry_compare(const void *first, const void *second) { - int64_t diff = ((profiler_time_entry *)second)->time_delta - - ((profiler_time_entry *)first)->time_delta; + int64_t diff = ((profiler_time_entry *)second)->time_delta - ((profiler_time_entry *)first)->time_delta; return diff < 0 ? -1 : (diff > 0 ? 1 : 0); } -static uint64_t copy_map_to_array(profile_times_table *map, - profiler_time_entries_t *entry_buffer, - uint64_t *min_, uint64_t *max_) +static uint64_t copy_map_to_array(profile_times_table *map, profiler_time_entries_t *entry_buffer, uint64_t *min_, + uint64_t *max_) { migrate_old_entries(map, false); @@ -480,10 +468,8 @@ static uint64_t copy_map_to_array(profile_times_table *map, return calls; } -typedef void (*profile_entry_print_func)(profiler_snapshot_entry_t *entry, - struct dstr *indent_buffer, - struct dstr *output_buffer, - unsigned indent, uint64_t active, +typedef void (*profile_entry_print_func)(profiler_snapshot_entry_t *entry, struct dstr *indent_buffer, + struct dstr *output_buffer, unsigned indent, uint64_t active, uint64_t parent_calls); /* UTF-8 characters */ @@ -491,8 +477,7 @@ typedef void (*profile_entry_print_func)(profiler_snapshot_entry_t *entry, #define VPIPE " \xe2\x94\x83" #define DOWN_RIGHT " \xe2\x94\x97" -static void make_indent_string(struct dstr *indent_buffer, unsigned indent, - uint64_t active) +static void make_indent_string(struct dstr *indent_buffer, unsigned indent, uint64_t active) { indent_buffer->len = 0; @@ -513,10 +498,8 @@ static void make_indent_string(struct dstr *indent_buffer, unsigned indent, } } -static void gather_stats(uint64_t expected_time_between_calls, - profiler_time_entries_t *entries, uint64_t calls, - uint64_t *percentile99, uint64_t *median, - double *percent_within_bounds) +static void gather_stats(uint64_t expected_time_between_calls, profiler_time_entries_t *entries, uint64_t calls, + uint64_t *percentile99, uint64_t *median, double *percent_within_bounds) { if (!entries->num) { *percentile99 = 0; @@ -561,10 +544,8 @@ static void gather_stats(uint64_t expected_time_between_calls, #define G_MS "g\xC2\xA0ms" -static void profile_print_entry(profiler_snapshot_entry_t *entry, - struct dstr *indent_buffer, - struct dstr *output_buffer, unsigned indent, - uint64_t active, uint64_t parent_calls) +static void profile_print_entry(profiler_snapshot_entry_t *entry, struct dstr *indent_buffer, + struct dstr *output_buffer, unsigned indent, uint64_t active, uint64_t parent_calls) { uint64_t calls = entry->overall_count; uint64_t min_ = entry->min_time; @@ -572,34 +553,30 @@ static void profile_print_entry(profiler_snapshot_entry_t *entry, uint64_t percentile99 = 0; uint64_t median = 0; double percent_within_bounds = 0.; - gather_stats(entry->expected_time_between_calls, &entry->times, calls, - &percentile99, &median, &percent_within_bounds); + gather_stats(entry->expected_time_between_calls, &entry->times, calls, &percentile99, &median, + &percent_within_bounds); make_indent_string(indent_buffer, indent, active); if (min_ == max_) { - dstr_printf(output_buffer, "%s%s: %" G_MS, indent_buffer->array, - entry->name, min_ / 1000.); + dstr_printf(output_buffer, "%s%s: %" G_MS, indent_buffer->array, entry->name, min_ / 1000.); } else { dstr_printf(output_buffer, "%s%s: min=%" G_MS ", median=%" G_MS ", " "max=%" G_MS ", 99th percentile=%" G_MS, - indent_buffer->array, entry->name, min_ / 1000., - median / 1000., max_ / 1000., percentile99 / 1000.); + indent_buffer->array, entry->name, min_ / 1000., median / 1000., max_ / 1000., + percentile99 / 1000.); if (entry->expected_time_between_calls) { - double expected_ms = - entry->expected_time_between_calls / 1000.; - dstr_catf(output_buffer, ", %g%% below %" G_MS, - percent_within_bounds, expected_ms); + double expected_ms = entry->expected_time_between_calls / 1000.; + dstr_catf(output_buffer, ", %g%% below %" G_MS, percent_within_bounds, expected_ms); } } if (parent_calls && calls != parent_calls) { double calls_per_parent = (double)calls / parent_calls; if (lround(calls_per_parent * 10) != 10) - dstr_catf(output_buffer, ", %g calls per parent call", - calls_per_parent); + dstr_catf(output_buffer, ", %g calls per parent call", calls_per_parent); } blog(LOG_INFO, "%s", output_buffer->array); @@ -608,16 +585,13 @@ static void profile_print_entry(profiler_snapshot_entry_t *entry, for (size_t i = 0; i < entry->children.num; i++) { if ((i + 1) == entry->children.num) active &= (1 << indent) - 1; - profile_print_entry(&entry->children.array[i], indent_buffer, - output_buffer, indent + 1, active, calls); + profile_print_entry(&entry->children.array[i], indent_buffer, output_buffer, indent + 1, active, calls); } } -static void gather_stats_between(profiler_time_entries_t *entries, - uint64_t calls, uint64_t lower_bound, - uint64_t upper_bound, uint64_t min_, - uint64_t max_, uint64_t *median, - double *percent, double *lower, double *higher) +static void gather_stats_between(profiler_time_entries_t *entries, uint64_t calls, uint64_t lower_bound, + uint64_t upper_bound, uint64_t min_, uint64_t max_, uint64_t *median, double *percent, + double *lower, double *higher) { *median = 0; *percent = 0.; @@ -680,10 +654,8 @@ static void gather_stats_between(profiler_time_entries_t *entries, } } -static void profile_print_entry_expected(profiler_snapshot_entry_t *entry, - struct dstr *indent_buffer, - struct dstr *output_buffer, - unsigned indent, uint64_t active, +static void profile_print_entry_expected(profiler_snapshot_entry_t *entry, struct dstr *indent_buffer, + struct dstr *output_buffer, unsigned indent, uint64_t active, uint64_t parent_calls) { UNUSED_PARAMETER(parent_calls); @@ -699,10 +671,8 @@ static void profile_print_entry_expected(profiler_snapshot_entry_t *entry, double percent = 0.; double lower = 0.; double higher = 0.; - gather_stats_between(&entry->times_between_calls, - entry->overall_between_calls_count, - (uint64_t)(expected_time * 0.98), - (uint64_t)(expected_time * 1.02 + 0.5), min_, max_, + gather_stats_between(&entry->times_between_calls, entry->overall_between_calls_count, + (uint64_t)(expected_time * 0.98), (uint64_t)(expected_time * 1.02 + 0.5), min_, max_, &median, &percent, &lower, &higher); make_indent_string(indent_buffer, indent, active); @@ -710,21 +680,19 @@ static void profile_print_entry_expected(profiler_snapshot_entry_t *entry, blog(LOG_INFO, "%s%s: min=%" G_MS ", median=%" G_MS ", max=%" G_MS ", %g%% " "within ±2%% of %" G_MS " (%g%% lower, %g%% higher)", - indent_buffer->array, entry->name, min_ / 1000., median / 1000., - max_ / 1000., percent, expected_time / 1000., lower, higher); + indent_buffer->array, entry->name, min_ / 1000., median / 1000., max_ / 1000., percent, + expected_time / 1000., lower, higher); active |= (uint64_t)1 << indent; for (size_t i = 0; i < entry->children.num; i++) { if ((i + 1) == entry->children.num) active &= (1 << indent) - 1; - profile_print_entry_expected(&entry->children.array[i], - indent_buffer, output_buffer, - indent + 1, active, 0); + profile_print_entry_expected(&entry->children.array[i], indent_buffer, output_buffer, indent + 1, + active, 0); } } -void profile_print_func(const char *intro, profile_entry_print_func print, - profiler_snapshot_t *snap) +void profile_print_func(const char *intro, profile_entry_print_func print, profiler_snapshot_t *snap) { struct dstr indent_buffer = {0}; struct dstr output_buffer = {0}; @@ -735,8 +703,7 @@ void profile_print_func(const char *intro, profile_entry_print_func print, blog(LOG_INFO, "%s", intro); for (size_t i = 0; i < snap->roots.num; i++) { - print(&snap->roots.array[i], &indent_buffer, &output_buffer, 0, - 0, 0); + print(&snap->roots.array[i], &indent_buffer, &output_buffer, 0, 0, 0); } blog(LOG_INFO, "================================================="); @@ -749,14 +716,12 @@ void profile_print_func(const char *intro, profile_entry_print_func print, void profiler_print(profiler_snapshot_t *snap) { - profile_print_func("== Profiler Results =============================", - profile_print_entry, snap); + profile_print_func("== Profiler Results =============================", profile_print_entry, snap); } void profiler_print_time_between_calls(profiler_snapshot_t *snap) { - profile_print_func("== Profiler Time Between Calls ==================", - profile_print_entry_expected, snap); + profile_print_func("== Profiler Time Between Calls ==================", profile_print_entry_expected, snap); } static void free_call_children(profile_call *call) @@ -866,8 +831,7 @@ void profiler_name_store_free(profiler_name_store_t *store) bfree(store); } -const char *profile_store_name(profiler_name_store_t *store, const char *format, - ...) +const char *profile_store_name(profiler_name_store_t *store, const char *format, ...) { va_list args; va_start(args, format); @@ -890,38 +854,30 @@ const char *profile_store_name(profiler_name_store_t *store, const char *format, /* ------------------------------------------------------------------------- */ /* Profiler data access */ -static void add_entry_to_snapshot(profile_entry *entry, - profiler_snapshot_entry_t *s_entry) +static void add_entry_to_snapshot(profile_entry *entry, profiler_snapshot_entry_t *s_entry) { s_entry->name = entry->name; s_entry->overall_count = - copy_map_to_array(&entry->times, &s_entry->times, - &s_entry->min_time, &s_entry->max_time); + copy_map_to_array(&entry->times, &s_entry->times, &s_entry->min_time, &s_entry->max_time); - if ((s_entry->expected_time_between_calls = - entry->expected_time_between_calls)) + if ((s_entry->expected_time_between_calls = entry->expected_time_between_calls)) s_entry->overall_between_calls_count = - copy_map_to_array(&entry->times_between_calls, - &s_entry->times_between_calls, - &s_entry->min_time_between_calls, - &s_entry->max_time_between_calls); + copy_map_to_array(&entry->times_between_calls, &s_entry->times_between_calls, + &s_entry->min_time_between_calls, &s_entry->max_time_between_calls); da_reserve(s_entry->children, entry->children.num); for (size_t i = 0; i < entry->children.num; i++) - add_entry_to_snapshot(&entry->children.array[i], - da_push_back_new(s_entry->children)); + add_entry_to_snapshot(&entry->children.array[i], da_push_back_new(s_entry->children)); } static void sort_snapshot_entry(profiler_snapshot_entry_t *entry) { - qsort(entry->times.array, entry->times.num, sizeof(profiler_time_entry), - profiler_time_entry_compare); + qsort(entry->times.array, entry->times.num, sizeof(profiler_time_entry), profiler_time_entry_compare); if (entry->expected_time_between_calls) - qsort(entry->times_between_calls.array, - entry->times_between_calls.num, - sizeof(profiler_time_entry), profiler_time_entry_compare); + qsort(entry->times_between_calls.array, entry->times_between_calls.num, sizeof(profiler_time_entry), + profiler_time_entry_compare); for (size_t i = 0; i < entry->children.num; i++) sort_snapshot_entry(&entry->children.array[i]); @@ -935,8 +891,7 @@ profiler_snapshot_t *profile_snapshot_create(void) da_reserve(snap->roots, root_entries.num); for (size_t i = 0; i < root_entries.num; i++) { pthread_mutex_lock(root_entries.array[i].mutex); - add_entry_to_snapshot(root_entries.array[i].entry, - da_push_back_new(snap->roots)); + add_entry_to_snapshot(root_entries.array[i].entry, da_push_back_new(snap->roots)); pthread_mutex_unlock(root_entries.array[i].mutex); } pthread_mutex_unlock(&root_mutex); @@ -970,10 +925,8 @@ void profile_snapshot_free(profiler_snapshot_t *snap) } typedef void (*dump_csv_func)(void *data, struct dstr *buffer); -static void entry_dump_csv(struct dstr *buffer, - const profiler_snapshot_entry_t *parent, - const profiler_snapshot_entry_t *entry, - dump_csv_func func, void *data) +static void entry_dump_csv(struct dstr *buffer, const profiler_snapshot_entry_t *parent, + const profiler_snapshot_entry_t *entry, dump_csv_func func, void *data) { const char *parent_name = parent ? parent->name : NULL; @@ -981,8 +934,7 @@ static void entry_dump_csv(struct dstr *buffer, dstr_printf(buffer, "%p,%p,%p,%p,%s,0," "%" PRIu64 ",%" PRIu64 "\n", - entry, parent, entry->name, parent_name, - entry->name, entry->times.array[i].time_delta, + entry, parent, entry->name, parent_name, entry->name, entry->times.array[i].time_delta, entry->times.array[i].count); func(data, buffer); } @@ -991,20 +943,16 @@ static void entry_dump_csv(struct dstr *buffer, dstr_printf(buffer, "%p,%p,%p,%p,%s," "%" PRIu64 ",%" PRIu64 ",%" PRIu64 "\n", - entry, parent, entry->name, parent_name, - entry->name, entry->expected_time_between_calls, - entry->times_between_calls.array[i].time_delta, - entry->times_between_calls.array[i].count); + entry, parent, entry->name, parent_name, entry->name, entry->expected_time_between_calls, + entry->times_between_calls.array[i].time_delta, entry->times_between_calls.array[i].count); func(data, buffer); } for (size_t i = 0; i < entry->children.num; i++) - entry_dump_csv(buffer, entry, &entry->children.array[i], func, - data); + entry_dump_csv(buffer, entry, &entry->children.array[i], func, data); } -static void profiler_snapshot_dump(const profiler_snapshot_t *snap, - dump_csv_func func, void *data) +static void profiler_snapshot_dump(const profiler_snapshot_t *snap, dump_csv_func func, void *data) { struct dstr buffer = {0}; @@ -1013,8 +961,7 @@ static void profiler_snapshot_dump(const profiler_snapshot_t *snap, func(data, &buffer); for (size_t i = 0; i < snap->roots.num; i++) - entry_dump_csv(&buffer, NULL, &snap->roots.array[i], func, - data); + entry_dump_csv(&buffer, NULL, &snap->roots.array[i], func, data); dstr_free(&buffer); } @@ -1024,8 +971,7 @@ static void dump_csv_fwrite(void *data, struct dstr *buffer) fwrite(buffer->array, 1, buffer->len, data); } -bool profiler_snapshot_dump_csv(const profiler_snapshot_t *snap, - const char *filename) +bool profiler_snapshot_dump_csv(const profiler_snapshot_t *snap, const char *filename) { FILE *f = os_fopen(filename, "wb+"); if (!f) @@ -1042,8 +988,7 @@ static void dump_csv_gzwrite(void *data, struct dstr *buffer) gzwrite(data, buffer->array, (unsigned)buffer->len); } -bool profiler_snapshot_dump_csv_gz(const profiler_snapshot_t *snap, - const char *filename) +bool profiler_snapshot_dump_csv_gz(const profiler_snapshot_t *snap, const char *filename) { gzFile gz; #ifdef _WIN32 @@ -1076,9 +1021,7 @@ size_t profiler_snapshot_num_roots(profiler_snapshot_t *snap) return snap ? snap->roots.num : 0; } -void profiler_snapshot_enumerate_roots(profiler_snapshot_t *snap, - profiler_entry_enum_func func, - void *context) +void profiler_snapshot_enumerate_roots(profiler_snapshot_t *snap, profiler_entry_enum_func func, void *context) { if (!snap) return; @@ -1088,8 +1031,7 @@ void profiler_snapshot_enumerate_roots(profiler_snapshot_t *snap, break; } -void profiler_snapshot_filter_roots(profiler_snapshot_t *snap, - profiler_name_filter_func func, void *data) +void profiler_snapshot_filter_roots(profiler_snapshot_t *snap, profiler_name_filter_func func, void *data) { for (size_t i = 0; i < snap->roots.num;) { bool remove = false; @@ -1113,8 +1055,7 @@ size_t profiler_snapshot_num_children(profiler_snapshot_entry_t *entry) return entry ? entry->children.num : 0; } -void profiler_snapshot_enumerate_children(profiler_snapshot_entry_t *entry, - profiler_entry_enum_func func, +void profiler_snapshot_enumerate_children(profiler_snapshot_entry_t *entry, profiler_entry_enum_func func, void *context) { if (!entry) @@ -1130,8 +1071,7 @@ const char *profiler_snapshot_entry_name(profiler_snapshot_entry_t *entry) return entry ? entry->name : NULL; } -profiler_time_entries_t * -profiler_snapshot_entry_times(profiler_snapshot_entry_t *entry) +profiler_time_entries_t *profiler_snapshot_entry_times(profiler_snapshot_entry_t *entry) { return entry ? &entry->times : NULL; } @@ -1151,32 +1091,27 @@ uint64_t profiler_snapshot_entry_max_time(profiler_snapshot_entry_t *entry) return entry ? entry->max_time : 0; } -profiler_time_entries_t * -profiler_snapshot_entry_times_between_calls(profiler_snapshot_entry_t *entry) +profiler_time_entries_t *profiler_snapshot_entry_times_between_calls(profiler_snapshot_entry_t *entry) { return entry ? &entry->times_between_calls : NULL; } -uint64_t profiler_snapshot_entry_expected_time_between_calls( - profiler_snapshot_entry_t *entry) +uint64_t profiler_snapshot_entry_expected_time_between_calls(profiler_snapshot_entry_t *entry) { return entry ? entry->expected_time_between_calls : 0; } -uint64_t -profiler_snapshot_entry_min_time_between_calls(profiler_snapshot_entry_t *entry) +uint64_t profiler_snapshot_entry_min_time_between_calls(profiler_snapshot_entry_t *entry) { return entry ? entry->min_time_between_calls : 0; } -uint64_t -profiler_snapshot_entry_max_time_between_calls(profiler_snapshot_entry_t *entry) +uint64_t profiler_snapshot_entry_max_time_between_calls(profiler_snapshot_entry_t *entry) { return entry ? entry->max_time_between_calls : 0; } -uint64_t profiler_snapshot_entry_overall_between_calls_count( - profiler_snapshot_entry_t *entry) +uint64_t profiler_snapshot_entry_overall_between_calls_count(profiler_snapshot_entry_t *entry) { return entry ? entry->overall_between_calls_count : 0; } diff --git a/libobs/util/profiler.h b/libobs/util/profiler.h index 91d958e0c..f944ee335 100644 --- a/libobs/util/profiler.h +++ b/libobs/util/profiler.h @@ -14,8 +14,7 @@ typedef struct profiler_time_entry profiler_time_entry_t; /* ------------------------------------------------------------------------- */ /* Profiling */ -EXPORT void profile_register_root(const char *name, - uint64_t expected_time_between_calls); +EXPORT void profile_register_root(const char *name, uint64_t expected_time_between_calls); EXPORT void profile_start(const char *name); EXPORT void profile_end(const char *name); @@ -48,8 +47,7 @@ EXPORT void profiler_name_store_free(profiler_name_store_t *store); #endif PRINTFATTR(2, 3) -EXPORT const char *profile_store_name(profiler_name_store_t *store, - const char *format, ...); +EXPORT const char *profile_store_name(profiler_name_store_t *store, const char *format, ...); #undef PRINTFATTR @@ -63,56 +61,36 @@ struct profiler_time_entry { typedef DARRAY(profiler_time_entry_t) profiler_time_entries_t; -typedef bool (*profiler_entry_enum_func)(void *context, - profiler_snapshot_entry_t *entry); +typedef bool (*profiler_entry_enum_func)(void *context, profiler_snapshot_entry_t *entry); EXPORT profiler_snapshot_t *profile_snapshot_create(void); EXPORT void profile_snapshot_free(profiler_snapshot_t *snap); -EXPORT bool profiler_snapshot_dump_csv(const profiler_snapshot_t *snap, - const char *filename); -EXPORT bool profiler_snapshot_dump_csv_gz(const profiler_snapshot_t *snap, - const char *filename); +EXPORT bool profiler_snapshot_dump_csv(const profiler_snapshot_t *snap, const char *filename); +EXPORT bool profiler_snapshot_dump_csv_gz(const profiler_snapshot_t *snap, const char *filename); EXPORT size_t profiler_snapshot_num_roots(profiler_snapshot_t *snap); -EXPORT void profiler_snapshot_enumerate_roots(profiler_snapshot_t *snap, - profiler_entry_enum_func func, - void *context); +EXPORT void profiler_snapshot_enumerate_roots(profiler_snapshot_t *snap, profiler_entry_enum_func func, void *context); -typedef bool (*profiler_name_filter_func)(void *data, const char *name, - bool *remove); -EXPORT void profiler_snapshot_filter_roots(profiler_snapshot_t *snap, - profiler_name_filter_func func, - void *data); +typedef bool (*profiler_name_filter_func)(void *data, const char *name, bool *remove); +EXPORT void profiler_snapshot_filter_roots(profiler_snapshot_t *snap, profiler_name_filter_func func, void *data); EXPORT size_t profiler_snapshot_num_children(profiler_snapshot_entry_t *entry); -EXPORT void -profiler_snapshot_enumerate_children(profiler_snapshot_entry_t *entry, - profiler_entry_enum_func func, - void *context); +EXPORT void profiler_snapshot_enumerate_children(profiler_snapshot_entry_t *entry, profiler_entry_enum_func func, + void *context); -EXPORT const char * -profiler_snapshot_entry_name(profiler_snapshot_entry_t *entry); +EXPORT const char *profiler_snapshot_entry_name(profiler_snapshot_entry_t *entry); -EXPORT profiler_time_entries_t * -profiler_snapshot_entry_times(profiler_snapshot_entry_t *entry); -EXPORT uint64_t -profiler_snapshot_entry_min_time(profiler_snapshot_entry_t *entry); -EXPORT uint64_t -profiler_snapshot_entry_max_time(profiler_snapshot_entry_t *entry); -EXPORT uint64_t -profiler_snapshot_entry_overall_count(profiler_snapshot_entry_t *entry); +EXPORT profiler_time_entries_t *profiler_snapshot_entry_times(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_min_time(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_max_time(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_overall_count(profiler_snapshot_entry_t *entry); -EXPORT profiler_time_entries_t * -profiler_snapshot_entry_times_between_calls(profiler_snapshot_entry_t *entry); -EXPORT uint64_t profiler_snapshot_entry_expected_time_between_calls( - profiler_snapshot_entry_t *entry); -EXPORT uint64_t profiler_snapshot_entry_min_time_between_calls( - profiler_snapshot_entry_t *entry); -EXPORT uint64_t profiler_snapshot_entry_max_time_between_calls( - profiler_snapshot_entry_t *entry); -EXPORT uint64_t profiler_snapshot_entry_overall_between_calls_count( - profiler_snapshot_entry_t *entry); +EXPORT profiler_time_entries_t *profiler_snapshot_entry_times_between_calls(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_expected_time_between_calls(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_min_time_between_calls(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_max_time_between_calls(profiler_snapshot_entry_t *entry); +EXPORT uint64_t profiler_snapshot_entry_overall_between_calls_count(profiler_snapshot_entry_t *entry); #ifdef __cplusplus } diff --git a/libobs/util/profiler.hpp b/libobs/util/profiler.hpp index dbfbdfac3..f9ba14944 100644 --- a/libobs/util/profiler.hpp +++ b/libobs/util/profiler.hpp @@ -11,12 +11,7 @@ struct ScopeProfiler { ~ScopeProfiler() { Stop(); } ScopeProfiler(const ScopeProfiler &) = delete; - ScopeProfiler(ScopeProfiler &&other) - : name(other.name), - enabled(other.enabled) - { - other.enabled = false; - } + ScopeProfiler(ScopeProfiler &&other) : name(other.name), enabled(other.enabled) { other.enabled = false; } ScopeProfiler &operator=(const ScopeProfiler &) = delete; ScopeProfiler &operator=(ScopeProfiler &&other) = delete; diff --git a/libobs/util/serializer.h b/libobs/util/serializer.h index 336806ba7..db1186183 100644 --- a/libobs/util/serializer.h +++ b/libobs/util/serializer.h @@ -27,11 +27,7 @@ extern "C" { #endif -enum serialize_seek_type { - SERIALIZE_SEEK_START, - SERIALIZE_SEEK_CURRENT, - SERIALIZE_SEEK_END -}; +enum serialize_seek_type { SERIALIZE_SEEK_START, SERIALIZE_SEEK_CURRENT, SERIALIZE_SEEK_END }; struct serializer { void *data; @@ -49,8 +45,7 @@ static inline size_t s_read(struct serializer *s, void *data, size_t size) return 0; } -static inline size_t s_write(struct serializer *s, const void *data, - size_t size) +static inline size_t s_write(struct serializer *s, const void *data, size_t size) { if (s && s->write && data && size) return s->write(s->data, (void *)data, size); @@ -69,8 +64,7 @@ static inline size_t serialize(struct serializer *s, void *data, size_t len) return 0; } -static inline int64_t serializer_seek(struct serializer *s, int64_t offset, - enum serialize_seek_type seek_type) +static inline int64_t serializer_seek(struct serializer *s, int64_t offset, enum serialize_seek_type seek_type) { if (s && s->seek) return s->seek(s->data, offset, seek_type); diff --git a/libobs/util/source-profiler.c b/libobs/util/source-profiler.c index 7a70354e2..18188b545 100644 --- a/libobs/util/source-profiler.c +++ b/libobs/util/source-profiler.c @@ -277,12 +277,10 @@ void source_profiler_frame_begin(void) static inline bool is_async_video_source(const struct obs_source *source) { - return (source->info.output_flags & OBS_SOURCE_ASYNC_VIDEO) == - OBS_SOURCE_ASYNC_VIDEO; + return (source->info.output_flags & OBS_SOURCE_ASYNC_VIDEO) == OBS_SOURCE_ASYNC_VIDEO; } -static const char *source_profiler_frame_collect_name = - "source_profiler_frame_collect"; +static const char *source_profiler_frame_collect_name = "source_profiler_frame_collect"; void source_profiler_frame_collect(void) { if (!enabled) @@ -299,13 +297,11 @@ void source_profiler_frame_collect(void) if (timer_ranges[timer_range_idx]) { gpu_ready = true; gs_enter_context(obs->video.graphics); - gs_timer_range_get_data(timer_ranges[timer_range_idx], - &gpu_disjoint, &freq); + gs_timer_range_get_data(timer_ranges[timer_range_idx], &gpu_disjoint, &freq); } if (gpu_disjoint) { - blog(LOG_WARNING, - "GPU Timers were disjoint, discarding samples."); + blog(LOG_WARNING, "GPU Timers were disjoint, discarding samples."); } } @@ -337,8 +333,7 @@ void source_profiler_frame_collect(void) for (size_t idx = 0; idx < smp->render_cpu.num; idx++) { sum += smp->render_cpu.array[idx]; } - ucirclebuf_push(&ent->render_cpu, - smp->render_cpu.array[0]); + ucirclebuf_push(&ent->render_cpu, smp->render_cpu.array[0]); ucirclebuf_push(&ent->render_cpu_sum, sum); da_clear(smp->render_cpu); } else { @@ -354,11 +349,9 @@ void source_profiler_frame_collect(void) for (size_t i = 0; i < smp->render_timers.num; i++) { gs_timer_t *timer = smp->render_timers.array[i]; - if (gpu_ready && !gpu_disjoint && - gs_timer_get_data(timer, &ticks)) { + if (gpu_ready && !gpu_disjoint && gs_timer_get_data(timer, &ticks)) { /* Convert ticks to ns */ - sum += util_mul_div64( - ticks, 1000000000ULL, freq); + sum += util_mul_div64(ticks, 1000000000ULL, freq); if (!first) first = sum; } @@ -463,8 +456,7 @@ uint64_t source_profiler_source_render_begin(gs_timer_t **timer) return os_gettime_ns(); } -void source_profiler_source_render_end(obs_source_t *source, uint64_t start, - gs_timer_t *timer) +void source_profiler_source_render_end(obs_source_t *source, uint64_t start, gs_timer_t *timer) { if (!enabled) return; @@ -479,8 +471,7 @@ void source_profiler_source_render_end(obs_source_t *source, uint64_t start, if (smp) { da_push_back(smp->frames[smp->frame_idx]->render_cpu, &delta); if (timer) { - da_push_back(smp->frames[smp->frame_idx]->render_timers, - &timer); + da_push_back(smp->frames[smp->frame_idx]->render_timers, &timer); } } else if (timer) { gs_timer_destroy(timer); @@ -514,8 +505,7 @@ void source_profiler_remove_source(obs_source_t *source) obs_queue_task(OBS_TASK_GRAPHICS, task_delete_source, source, false); } -static inline void calculate_tick(struct profiler_entry *ent, - struct profiler_result *result) +static inline void calculate_tick(struct profiler_entry *ent, struct profiler_result *result) { size_t idx = 0; uint64_t sum = 0; @@ -532,8 +522,7 @@ static inline void calculate_tick(struct profiler_entry *ent, result->tick_avg = sum / idx; } -static inline void calculate_render(struct profiler_entry *ent, - struct profiler_result *result) +static inline void calculate_render(struct profiler_entry *ent, struct profiler_result *result) { size_t idx; uint64_t sum = 0, sum_sum = 0; @@ -571,8 +560,7 @@ static inline void calculate_render(struct profiler_entry *ent, } } -static inline void calculate_fps(const struct ucirclebuf *frames, double *avg, - uint64_t *best, uint64_t *worst) +static inline void calculate_fps(const struct ucirclebuf *frames, double *avg, uint64_t *best, uint64_t *worst) { uint64_t deltas = 0, delta_sum = 0, best_delta = 0, worst_delta = 0; @@ -603,8 +591,7 @@ static inline void calculate_fps(const struct ucirclebuf *frames, double *avg, } } -bool source_profiler_fill_result(obs_source_t *source, - struct profiler_result *result) +bool source_profiler_fill_result(obs_source_t *source, struct profiler_result *result) { if (!enabled || !result) return false; @@ -620,13 +607,9 @@ bool source_profiler_fill_result(obs_source_t *source, calculate_render(ent, result); if (is_async_video_source(source)) { - calculate_fps(&ent->async_frame_ts, - &result->async_input, - &result->async_input_best, + calculate_fps(&ent->async_frame_ts, &result->async_input, &result->async_input_best, &result->async_input_worst); - calculate_fps(&ent->async_rendered_ts, - &result->async_rendered, - &result->async_rendered_best, + calculate_fps(&ent->async_rendered_ts, &result->async_rendered, &result->async_rendered_best, &result->async_rendered_worst); } } diff --git a/libobs/util/source-profiler.h b/libobs/util/source-profiler.h index 956e7be8d..b6ff4741c 100644 --- a/libobs/util/source-profiler.h +++ b/libobs/util/source-profiler.h @@ -59,8 +59,7 @@ EXPORT void source_profiler_gpu_enable(bool enable); /* Get latest profiling results for source (must be freed by user) */ EXPORT profiler_result_t *source_profiler_get_result(obs_source_t *source); /* Update existing profiler results object for source */ -EXPORT bool source_profiler_fill_result(obs_source_t *source, - profiler_result_t *result); +EXPORT bool source_profiler_fill_result(obs_source_t *source, profiler_result_t *result); #ifdef __cplusplus } diff --git a/libobs/util/sse-intrin.h b/libobs/util/sse-intrin.h index df2b075fe..76b36dd86 100644 --- a/libobs/util/sse-intrin.h +++ b/libobs/util/sse-intrin.h @@ -19,8 +19,7 @@ #include "c99defs.h" -#if (defined(_MSC_VER) || defined(__MINGW32__)) && \ - ((defined(_M_X64) && !defined(_M_ARM64EC)) || defined(_M_IX86)) +#if (defined(_MSC_VER) || defined(__MINGW32__)) && ((defined(_M_X64) && !defined(_M_ARM64EC)) || defined(_M_IX86)) #include #else #ifndef WIN32_LEAN_AND_MEAN diff --git a/libobs/util/task.c b/libobs/util/task.c index afa97e51f..fbfea3627 100644 --- a/libobs/util/task.c +++ b/libobs/util/task.c @@ -38,8 +38,7 @@ os_task_queue_t *os_task_queue_create(void) goto fail2; if (os_event_init(&tq->wait_event, OS_EVENT_TYPE_AUTO) != 0) goto fail3; - if (pthread_create(&tq->thread, NULL, tiny_tubular_task_thread, tq) != - 0) + if (pthread_create(&tq->thread, NULL, tiny_tubular_task_thread, tq) != 0) goto fail4; return tq; diff --git a/libobs/util/task.h b/libobs/util/task.h index bb677ca91..fc8a2ca05 100644 --- a/libobs/util/task.h +++ b/libobs/util/task.h @@ -12,8 +12,7 @@ typedef struct os_task_queue os_task_queue_t; typedef void (*os_task_t)(void *param); EXPORT os_task_queue_t *os_task_queue_create(void); -EXPORT bool os_task_queue_queue_task(os_task_queue_t *tt, os_task_t task, - void *param); +EXPORT bool os_task_queue_queue_task(os_task_queue_t *tt, os_task_t task, void *param); EXPORT void os_task_queue_destroy(os_task_queue_t *tt); EXPORT bool os_task_queue_wait(os_task_queue_t *tt); EXPORT bool os_task_queue_inside(os_task_queue_t *tt); diff --git a/libobs/util/text-lookup.c b/libobs/util/text-lookup.c index bf5c38bd4..5a53225c2 100644 --- a/libobs/util/text-lookup.c +++ b/libobs/util/text-lookup.c @@ -88,8 +88,7 @@ static bool lookup_gettoken(struct lexer *lex, struct strref *str) if (!str->array) { /* comments are designated with a #, and end at LF */ if (ch == '#') { - while (*lex->offset != '\n' && - *lex->offset != 0) + while (*lex->offset != '\n' && *lex->offset != 0) ++lex->offset; } else if (temp.type == BASETOKEN_WHITESPACE) { strref_copy(str, &temp.text); @@ -104,8 +103,7 @@ static bool lookup_gettoken(struct lexer *lex, struct strref *str) } } } else { - if (temp.type == BASETOKEN_WHITESPACE || - *temp.text.array == '=') { + if (temp.type == BASETOKEN_WHITESPACE || *temp.text.array == '=') { lex->offset -= temp.text.len; break; } @@ -156,8 +154,7 @@ static char *convert_string(const char *str, size_t len) return out.array; } -static void lookup_addfiledata(struct text_lookup *lookup, - const char *file_data) +static void lookup_addfiledata(struct text_lookup *lookup, const char *file_data) { struct lexer lex; struct strref name, value; @@ -200,8 +197,7 @@ static void lookup_addfiledata(struct text_lookup *lookup, lexer_free(&lex); } -static inline bool lookup_getstring(const char *lookup_val, const char **out, - struct text_lookup *lookup) +static inline bool lookup_getstring(const char *lookup_val, const char **out, struct text_lookup *lookup) { struct text_item *item; @@ -267,8 +263,7 @@ void text_lookup_destroy(lookup_t *lookup) } } -bool text_lookup_getstr(lookup_t *lookup, const char *lookup_val, - const char **out) +bool text_lookup_getstr(lookup_t *lookup, const char *lookup_val, const char **out) { if (lookup) return lookup_getstring(lookup_val, out, lookup); diff --git a/libobs/util/text-lookup.h b/libobs/util/text-lookup.h index 118b9fa86..4ac474d65 100644 --- a/libobs/util/text-lookup.h +++ b/libobs/util/text-lookup.h @@ -38,8 +38,7 @@ typedef struct text_lookup lookup_t; EXPORT lookup_t *text_lookup_create(const char *path); EXPORT bool text_lookup_add(lookup_t *lookup, const char *path); EXPORT void text_lookup_destroy(lookup_t *lookup); -EXPORT bool text_lookup_getstr(lookup_t *lookup, const char *lookup_val, - const char **out); +EXPORT bool text_lookup_getstr(lookup_t *lookup, const char *lookup_val, const char **out); #ifdef __cplusplus } diff --git a/libobs/util/threading-posix.h b/libobs/util/threading-posix.h index 7ac14e510..2cdddfe58 100644 --- a/libobs/util/threading-posix.h +++ b/libobs/util/threading-posix.h @@ -46,18 +46,14 @@ static inline long os_atomic_load_long(const volatile long *ptr) return __atomic_load_n(ptr, __ATOMIC_SEQ_CST); } -static inline bool os_atomic_compare_swap_long(volatile long *val, long old_val, - long new_val) +static inline bool os_atomic_compare_swap_long(volatile long *val, long old_val, long new_val) { - return __atomic_compare_exchange_n(val, &old_val, new_val, false, - __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return __atomic_compare_exchange_n(val, &old_val, new_val, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); } -static inline bool os_atomic_compare_exchange_long(volatile long *val, - long *old_val, long new_val) +static inline bool os_atomic_compare_exchange_long(volatile long *val, long *old_val, long new_val) { - return __atomic_compare_exchange_n(val, old_val, new_val, false, - __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); + return __atomic_compare_exchange_n(val, old_val, new_val, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); } static inline void os_atomic_store_bool(volatile bool *ptr, bool val) diff --git a/libobs/util/threading-windows.c b/libobs/util/threading-windows.c index 3d690bb69..3c62968e5 100644 --- a/libobs/util/threading-windows.c +++ b/libobs/util/threading-windows.c @@ -163,8 +163,7 @@ struct vs_threadname_info { }; #pragma pack(pop) -#define THREADNAME_INFO_SIZE \ - (sizeof(struct vs_threadname_info) / sizeof(ULONG_PTR)) +#define THREADNAME_INFO_SIZE (sizeof(struct vs_threadname_info) / sizeof(ULONG_PTR)) void os_set_thread_name(const char *name) { @@ -183,8 +182,7 @@ void os_set_thread_name(const char *name) #else __try { #endif - RaiseException(VC_EXCEPTION, 0, THREADNAME_INFO_SIZE, - (ULONG_PTR *)&info); + RaiseException(VC_EXCEPTION, 0, THREADNAME_INFO_SIZE, (ULONG_PTR *)&info); #ifdef NO_SEH_MINGW } __except1{ @@ -196,12 +194,10 @@ void os_set_thread_name(const char *name) const HMODULE hModule = LoadLibrary(L"KernelBase.dll"); if (hModule) { - typedef HRESULT(WINAPI * set_thread_description_t)(HANDLE, - PCWSTR); + typedef HRESULT(WINAPI * set_thread_description_t)(HANDLE, PCWSTR); const set_thread_description_t std = - (set_thread_description_t)GetProcAddress( - hModule, "SetThreadDescription"); + (set_thread_description_t)GetProcAddress(hModule, "SetThreadDescription"); if (std) { wchar_t *wname; os_utf8_to_wcs_ptr(name, 0, &wname); diff --git a/libobs/util/threading-windows.h b/libobs/util/threading-windows.h index 4dfb46a9f..38c4d1db2 100644 --- a/libobs/util/threading-windows.h +++ b/libobs/util/threading-windows.h @@ -19,8 +19,7 @@ #include #include -#if !defined(_M_IX86) && !defined(_M_X64) && !defined(_M_ARM) && \ - !defined(_M_ARM64) +#if !defined(_M_IX86) && !defined(_M_X64) && !defined(_M_ARM) && !defined(_M_ARM64) #error Processor not supported #endif @@ -76,18 +75,15 @@ static inline long os_atomic_load_long(const volatile long *ptr) return val; } -static inline bool os_atomic_compare_swap_long(volatile long *val, long old_val, - long new_val) +static inline bool os_atomic_compare_swap_long(volatile long *val, long old_val, long new_val) { return _InterlockedCompareExchange(val, new_val, old_val) == old_val; } -static inline bool os_atomic_compare_exchange_long(volatile long *val, - long *old_ptr, long new_val) +static inline bool os_atomic_compare_exchange_long(volatile long *val, long *old_ptr, long new_val) { const long old_val = *old_ptr; - const long previous = - _InterlockedCompareExchange(val, new_val, old_val); + const long previous = _InterlockedCompareExchange(val, new_val, old_val); *old_ptr = previous; return previous == old_val; } diff --git a/libobs/util/utf8.c b/libobs/util/utf8.c index a90618ac8..afcb903b2 100644 --- a/libobs/util/utf8.c +++ b/libobs/util/utf8.c @@ -28,8 +28,7 @@ static inline bool has_utf8_bom(const char *in_char) return (in && in[0] == 0xef && in[1] == 0xbb && in[2] == 0xbf); } -size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, - size_t outsize, int flags) +size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, size_t outsize, int flags) { int i_insize = (int)insize; int ret; @@ -51,8 +50,7 @@ size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, return (ret > 0) ? (size_t)ret : 0; } -size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, - size_t outsize, int flags) +size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, size_t outsize, int flags) { int i_insize = (int)insize; int ret; @@ -60,8 +58,7 @@ size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, if (i_insize == 0) i_insize = (int)wcslen(in); - ret = WideCharToMultiByte(CP_UTF8, 0, in, i_insize, out, (int)outsize, - NULL, NULL); + ret = WideCharToMultiByte(CP_UTF8, 0, in, i_insize, out, (int)outsize, NULL, NULL); UNUSED_PARAMETER(flags); return (ret > 0) ? (size_t)ret : 0; @@ -130,8 +127,7 @@ static int utf8_forbidden(unsigned char octet) * not prepare buffer in advance (\0 terminate) but after calling this * function. */ -size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, - size_t outsize, int flags) +size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, size_t outsize, int flags) { unsigned char *p, *lim; wchar_t *wlim, high; @@ -259,8 +255,7 @@ size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, * If UCS-4 string contains zero symbols, they will be translated * as regular symbols. */ -size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, - size_t outsize, int flags) +size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, size_t outsize, int flags) { wchar_t *w, *wlim, ch = 0; unsigned char *p, *lim, *oc; @@ -335,16 +330,14 @@ size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, case 4: p[3] = _NXT | (oc[0] & 0x3f); p[2] = _NXT | (oc[0] >> 6) | ((oc[1] & 0x0f) << 2); - p[1] = _NXT | ((oc[1] & 0xf0) >> 4) | - ((oc[2] & 0x03) << 4); + p[1] = _NXT | ((oc[1] & 0xf0) >> 4) | ((oc[2] & 0x03) << 4); p[0] = _SEQ4 | ((oc[2] & 0x1f) >> 2); break; case 5: p[4] = _NXT | (oc[0] & 0x3f); p[3] = _NXT | (oc[0] >> 6) | ((oc[1] & 0x0f) << 2); - p[2] = _NXT | ((oc[1] & 0xf0) >> 4) | - ((oc[2] & 0x03) << 4); + p[2] = _NXT | ((oc[1] & 0xf0) >> 4) | ((oc[2] & 0x03) << 4); p[1] = _NXT | (oc[2] >> 2); p[0] = _SEQ5 | (oc[3] & 0x03); break; diff --git a/libobs/util/utf8.h b/libobs/util/utf8.h index 74c969510..923886034 100644 --- a/libobs/util/utf8.h +++ b/libobs/util/utf8.h @@ -27,10 +27,8 @@ extern "C" { #define UTF8_IGNORE_ERROR 0x01 #define UTF8_SKIP_BOM 0x02 -size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, - size_t outsize, int flags); -size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, - size_t outsize, int flags); +size_t utf8_to_wchar(const char *in, size_t insize, wchar_t *out, size_t outsize, int flags); +size_t wchar_to_utf8(const wchar_t *in, size_t insize, char *out, size_t outsize, int flags); #ifdef __cplusplus } diff --git a/libobs/util/util.hpp b/libobs/util/util.hpp index a55ea3f9c..c59da282a 100644 --- a/libobs/util/util.hpp +++ b/libobs/util/util.hpp @@ -77,10 +77,7 @@ class ConfigFile { public: inline ConfigFile() : config(NULL) {} - inline ConfigFile(ConfigFile &&other) noexcept : config(other.config) - { - other.config = nullptr; - } + inline ConfigFile(ConfigFile &&other) noexcept : config(other.config) { other.config = nullptr; } inline ~ConfigFile() { config_close(config); } inline bool Create(const char *file) @@ -111,8 +108,7 @@ public: inline int Save() { return config_save(config); } - inline int SaveSafe(const char *temp_ext, - const char *backup_ext = nullptr) + inline int SaveSafe(const char *temp_ext, const char *backup_ext = nullptr) { return config_save_safe(config, temp_ext, backup_ext); } @@ -135,10 +131,7 @@ class TextLookup { public: inline TextLookup(lookup_t *lookup = nullptr) : lookup(lookup) {} - inline TextLookup(TextLookup &&other) noexcept : lookup(other.lookup) - { - other.lookup = nullptr; - } + inline TextLookup(TextLookup &&other) noexcept : lookup(other.lookup) { other.lookup = nullptr; } inline ~TextLookup() { text_lookup_destroy(lookup); } inline TextLookup &operator=(lookup_t *val) diff --git a/libobs/util/windows/ComPtr.hpp b/libobs/util/windows/ComPtr.hpp index 297f0c3ac..fc7a8402d 100644 --- a/libobs/util/windows/ComPtr.hpp +++ b/libobs/util/windows/ComPtr.hpp @@ -58,10 +58,7 @@ public: ptr->AddRef(); } inline ComPtr(ComPtr &&c) noexcept : ptr(c.ptr) { c.ptr = nullptr; } - template - inline ComPtr(ComPtr &&c) noexcept : ptr(c.Detach()) - { - } + template inline ComPtr(ComPtr &&c) noexcept : ptr(c.Detach()) {} inline ~ComPtr() { Kill(); } inline void Clear() diff --git a/libobs/util/windows/WinHandle.hpp b/libobs/util/windows/WinHandle.hpp index c21cfb6bc..f652bdfc5 100644 --- a/libobs/util/windows/WinHandle.hpp +++ b/libobs/util/windows/WinHandle.hpp @@ -44,10 +44,7 @@ public: inline HANDLE *operator&() { return &handle; } - inline bool Valid() const - { - return handle && handle != INVALID_HANDLE_VALUE; - } + inline bool Valid() const { return handle && handle != INVALID_HANDLE_VALUE; } }; class WinModule { diff --git a/libobs/util/windows/device-enum.c b/libobs/util/windows/device-enum.c index c087e2db7..b1d6701be 100644 --- a/libobs/util/windows/device-enum.c +++ b/libobs/util/windows/device-enum.c @@ -13,9 +13,7 @@ void enum_graphics_device_luids(device_luid_cb device_luid, void *param) if (FAILED(hr)) return; - for (UINT i = 0; - factory->lpVtbl->EnumAdapters1(factory, i, &adapter) == S_OK; - i++) { + for (UINT i = 0; factory->lpVtbl->EnumAdapters1(factory, i, &adapter) == S_OK; i++) { DXGI_ADAPTER_DESC desc; hr = adapter->lpVtbl->GetDesc(adapter, &desc); diff --git a/libobs/util/windows/obfuscate.c b/libobs/util/windows/obfuscate.c index 7d665752d..93768e26c 100644 --- a/libobs/util/windows/obfuscate.c +++ b/libobs/util/windows/obfuscate.c @@ -18,8 +18,7 @@ static void deobfuscate_str(char *str, uint64_t val) int pos = i / 2; bool bottom = (i % 2) == 0; uint8_t *ch = (uint8_t *)str; - uint8_t xor = bottom ? LOWER_HALFBYTE(dec_val[pos]) - : UPPER_HALFBYTE(dec_val[pos]); + uint8_t xor = bottom ? LOWER_HALFBYTE(dec_val[pos]) : UPPER_HALFBYTE(dec_val[pos]); *ch ^= xor; diff --git a/libobs/util/windows/win-registry.h b/libobs/util/windows/win-registry.h index d58eb83c5..89611b168 100644 --- a/libobs/util/windows/win-registry.h +++ b/libobs/util/windows/win-registry.h @@ -30,8 +30,7 @@ struct reg_dword { DWORD return_value; }; -EXPORT void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, - struct reg_dword *info); +EXPORT void get_reg_dword(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, struct reg_dword *info); #ifdef __cplusplus } diff --git a/libobs/util/windows/win-version.h b/libobs/util/windows/win-version.h index a0cae80a0..084981836 100644 --- a/libobs/util/windows/win-version.h +++ b/libobs/util/windows/win-version.h @@ -29,8 +29,7 @@ struct win_version_info { int revis; }; -static inline int win_version_compare(const struct win_version_info *dst, - const struct win_version_info *src) +static inline int win_version_compare(const struct win_version_info *dst, const struct win_version_info *src) { if (dst->major > src->major) return 1; diff --git a/libobs/util/windows/window-helpers.c b/libobs/util/windows/window-helpers.c index 919d6e275..94b2eae1f 100644 --- a/libobs/util/windows/window-helpers.c +++ b/libobs/util/windows/window-helpers.c @@ -20,8 +20,7 @@ static inline char *decode_str(const char *src) return str.array; } -void ms_build_window_strings(const char *str, char **class, char **title, - char **exe) +void ms_build_window_strings(const char *str, char **class, char **title, char **exe) { char **strlist; @@ -63,8 +62,7 @@ static void insert_preserved_val(obs_property_t *p, const char *val, size_t idx) bfree(executable); } -bool ms_check_window_property_setting(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings, const char *val, +bool ms_check_window_property_setting(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings, const char *val, size_t idx) { const char *cur_val; @@ -104,14 +102,13 @@ static HMODULE kernel32(void) return kernel32_handle; } -static inline HANDLE open_process(DWORD desired_access, bool inherit_handle, - DWORD process_id) +static inline HANDLE open_process(DWORD desired_access, bool inherit_handle, DWORD process_id) { typedef HANDLE(WINAPI * PFN_OpenProcess)(DWORD, BOOL, DWORD); static PFN_OpenProcess open_process_proc = NULL; if (!open_process_proc) - open_process_proc = (PFN_OpenProcess)ms_get_obfuscated_func( - kernel32(), "B}caZyah`~q", 0x2D5BEBAF6DDULL); + open_process_proc = + (PFN_OpenProcess)ms_get_obfuscated_func(kernel32(), "B}caZyah`~q", 0x2D5BEBAF6DDULL); return open_process_proc(desired_access, inherit_handle, process_id); } @@ -225,8 +222,7 @@ static bool is_microsoft_internal_window_exe(const char *exe) return true; } - for (const char **vals = internal_microsoft_exes_partial; *vals; - vals++) { + for (const char **vals = internal_microsoft_exes_partial; *vals; vals++) { if (astrcmpi_n(exe, *vals, strlen(*vals)) == 0) return true; } @@ -289,8 +285,7 @@ static void add_window(obs_property_t *p, HWND hwnd, add_window_cb callback) static inline bool IsWindowCloaked(HWND window) { DWORD cloaked; - HRESULT hr = DwmGetWindowAttribute(window, DWMWA_CLOAKED, &cloaked, - sizeof(cloaked)); + HRESULT hr = DwmGetWindowAttribute(window, DWMWA_CLOAKED, &cloaked, sizeof(cloaked)); return SUCCEEDED(hr) && cloaked; } @@ -299,9 +294,7 @@ static bool check_window_valid(HWND window, enum window_search_mode mode) DWORD styles, ex_styles; RECT rect; - if (!IsWindowVisible(window) || - (mode == EXCLUDE_MINIMIZED && - (IsIconic(window) || IsWindowCloaked(window)))) + if (!IsWindowVisible(window) || (mode == EXCLUDE_MINIMIZED && (IsIconic(window) || IsWindowCloaked(window)))) return false; GetClientRect(window, &rect); @@ -326,8 +319,7 @@ bool ms_is_uwp_window(HWND hwnd) if (!GetClassNameW(hwnd, name, sizeof(name) / sizeof(wchar_t))) return false; - return wcscmp(name, L"ApplicationFrameWindow") == 0 || - wcscmp(name, L"WinUIDesktopWin32WindowClass") == 0; + return wcscmp(name, L"ApplicationFrameWindow") == 0 || wcscmp(name, L"WinUIDesktopWin32WindowClass") == 0; } HWND ms_get_uwp_actual_window(HWND parent) @@ -351,8 +343,7 @@ HWND ms_get_uwp_actual_window(HWND parent) return NULL; } -static HWND next_window(HWND window, enum window_search_mode mode, HWND *parent, - bool use_findwindowex) +static HWND next_window(HWND window, enum window_search_mode mode, HWND *parent, bool use_findwindowex) { if (*parent) { window = *parent; @@ -361,8 +352,7 @@ static HWND next_window(HWND window, enum window_search_mode mode, HWND *parent, while (true) { if (use_findwindowex) - window = FindWindowEx(GetDesktopWindow(), window, NULL, - NULL); + window = FindWindowEx(GetDesktopWindow(), window, NULL, NULL); else window = GetNextWindow(window, GW_HWNDNEXT); @@ -381,8 +371,7 @@ static HWND next_window(HWND window, enum window_search_mode mode, HWND *parent, return window; } -static HWND first_window(enum window_search_mode mode, HWND *parent, - bool *use_findwindowex) +static HWND first_window(enum window_search_mode mode, HWND *parent, bool *use_findwindowex) { HWND window = FindWindowEx(GetDesktopWindow(), NULL, NULL, NULL); @@ -403,8 +392,7 @@ static HWND first_window(enum window_search_mode mode, HWND *parent, window = GetWindow(GetDesktopWindow(), GW_CHILD); if (!check_window_valid(window, mode)) - window = next_window(window, mode, parent, - *use_findwindowex); + window = next_window(window, mode, parent, *use_findwindowex); } } @@ -419,8 +407,7 @@ static HWND first_window(enum window_search_mode mode, HWND *parent, return window; } -void ms_fill_window_list(obs_property_t *p, enum window_search_mode mode, - add_window_cb callback) +void ms_fill_window_list(obs_property_t *p, enum window_search_mode mode, add_window_cb callback) { HWND parent; bool use_findwindowex = false; @@ -433,9 +420,8 @@ void ms_fill_window_list(obs_property_t *p, enum window_search_mode mode, } } -static int window_rating(HWND window, enum window_priority priority, - const char *class, const char *title, const char *exe, - bool uwp_window, bool generic_class) +static int window_rating(HWND window, enum window_priority priority, const char *class, const char *title, + const char *exe, bool uwp_window, bool generic_class) { struct dstr cur_class = {0}; struct dstr cur_title = {0}; @@ -504,8 +490,8 @@ static bool is_uwp_class(const char *window_class) strcmp(window_class, "WinUIDesktopWin32WindowClass") == 0; } -HWND ms_find_window(enum window_search_mode mode, enum window_priority priority, - const char *class, const char *title, const char *exe) +HWND ms_find_window(enum window_search_mode mode, enum window_priority priority, const char *class, const char *title, + const char *exe) { HWND parent; bool use_findwindowex = false; @@ -521,8 +507,7 @@ HWND ms_find_window(enum window_search_mode mode, enum window_priority priority, const bool generic_class = is_generic_class(class); while (window) { - int rating = window_rating(window, priority, class, title, exe, - uwp_window, generic_class); + int rating = window_rating(window, priority, class, title, exe, uwp_window, generic_class); if (rating < best_rating) { best_rating = rating; best_window = window; @@ -558,9 +543,8 @@ BOOL CALLBACK enum_windows_proc(HWND window, LPARAM lParam) if (IsWindowCloaked(window)) return TRUE; - const int rating = window_rating(window, data->priority, data->class, - data->title, data->exe, - data->uwp_window, data->generic_class); + const int rating = window_rating(window, data->priority, data->class, data->title, data->exe, data->uwp_window, + data->generic_class); if (rating < data->best_rating) { data->best_rating = rating; data->best_window = window; @@ -569,8 +553,7 @@ BOOL CALLBACK enum_windows_proc(HWND window, LPARAM lParam) return rating > 0; } -HWND ms_find_window_top_level(enum window_search_mode mode, - enum window_priority priority, const char *class, +HWND ms_find_window_top_level(enum window_search_mode mode, enum window_priority priority, const char *class, const char *title, const char *exe) { if (!class) diff --git a/libobs/util/windows/window-helpers.h b/libobs/util/windows/window-helpers.h index c42640676..0f060c45b 100644 --- a/libobs/util/windows/window-helpers.h +++ b/libobs/util/windows/window-helpers.h @@ -26,31 +26,21 @@ EXPORT void ms_get_window_class(struct dstr *window_class, HWND hwnd); EXPORT bool ms_is_uwp_window(HWND hwnd); EXPORT HWND ms_get_uwp_actual_window(HWND parent); -typedef bool (*add_window_cb)(const char *title, const char *window_class, - const char *exe); +typedef bool (*add_window_cb)(const char *title, const char *window_class, const char *exe); -EXPORT void ms_fill_window_list(obs_property_t *p, enum window_search_mode mode, - add_window_cb callback); +EXPORT void ms_fill_window_list(obs_property_t *p, enum window_search_mode mode, add_window_cb callback); -EXPORT void ms_build_window_strings(const char *str, char **window_class, - char **title, char **exe); +EXPORT void ms_build_window_strings(const char *str, char **window_class, char **title, char **exe); -EXPORT bool ms_check_window_property_setting(obs_properties_t *ppts, - obs_property_t *p, - obs_data_t *settings, +EXPORT bool ms_check_window_property_setting(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings, const char *val, size_t idx); -EXPORT void ms_build_window_strings(const char *str, char **window_class, - char **title, char **exe); +EXPORT void ms_build_window_strings(const char *str, char **window_class, char **title, char **exe); -EXPORT HWND ms_find_window(enum window_search_mode mode, - enum window_priority priority, - const char *window_class, const char *title, - const char *exe); -EXPORT HWND ms_find_window_top_level(enum window_search_mode mode, - enum window_priority priority, - const char *window_class, - const char *title, const char *exe); +EXPORT HWND ms_find_window(enum window_search_mode mode, enum window_priority priority, const char *window_class, + const char *title, const char *exe); +EXPORT HWND ms_find_window_top_level(enum window_search_mode mode, enum window_priority priority, + const char *window_class, const char *title, const char *exe); #ifdef __cplusplus } diff --git a/plugins/aja/aja-card-manager.cpp b/plugins/aja/aja-card-manager.cpp index a54777c9d..f260dc339 100644 --- a/plugins/aja/aja-card-manager.cpp +++ b/plugins/aja/aja-card-manager.cpp @@ -67,8 +67,7 @@ bool CardEntry::Initialize() mCard->SetEveryFrameServices(NTV2_OEM_TASKS); const int32_t obsPid = (int32_t)AJAProcess::GetPid(); - mCard->AcquireStreamForApplicationWithReference((ULWord)kStreamingAppID, - obsPid); + mCard->AcquireStreamForApplicationWithReference((ULWord)kStreamingAppID, obsPid); mCard->SetSuspendHostAudio(true); @@ -81,8 +80,7 @@ bool CardEntry::Initialize() mCard->SetReference(NTV2_REFERENCE_FREERUN); for (UWord i = 0; i < aja::CardNumAudioSystems(deviceID); i++) { - mCard->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_OFF, - static_cast(i)); + mCard->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_OFF, static_cast(i)); } auto numFramestores = aja::CardNumFramestores(deviceID); @@ -91,8 +89,7 @@ bool CardEntry::Initialize() mCard->SetInputFrame(static_cast(i), 0xff); // Disable 3G Level B converter by default if (NTV2DeviceCanDo3GLevelConversion(deviceID)) { - mCard->SetSDIInLevelBtoLevelAConversion( - static_cast(i), false); + mCard->SetSDIInLevelBtoLevelAConversion(static_cast(i), false); } } @@ -120,8 +117,7 @@ bool CardEntry::Initialize() mCard->AutoCirculateStop(channel, true); } - mCard->SetVideoFormat(NTV2_FORMAT_1080p_5994_A, false, false, - channel); + mCard->SetVideoFormat(NTV2_FORMAT_1080p_5994_A, false, false, channel); mCard->SetFrameBufferFormat(channel, NTV2_FBF_8BIT_YCBCR); mCard->DisableChannel(channel); @@ -146,8 +142,7 @@ std::string CardEntry::GetDisplayName() const { if (mCard) { std::ostringstream oss; - oss << mCard->GetIndexNumber() << " - " - << mCard->GetModelName(); + oss << mCard->GetIndexNumber() << " - " << mCard->GetModelName(); const std::string &serial = GetSerial(); if (!serial.empty()) oss << " (" << serial << ")"; @@ -189,25 +184,21 @@ bool CardEntry::ChannelReady(NTV2Channel chan, const std::string &owner) const return true; } -bool CardEntry::AcquireChannel(NTV2Channel chan, NTV2Mode mode, - const std::string &owner) +bool CardEntry::AcquireChannel(NTV2Channel chan, NTV2Mode mode, const std::string &owner) { bool acquired = false; if (ChannelReady(chan, owner)) { const std::lock_guard lock(mMutex); if (mChannelPwnz.find(owner) != mChannelPwnz.end()) { - if (mChannelPwnz[owner] & - (1 << static_cast(chan))) { + if (mChannelPwnz[owner] & (1 << static_cast(chan))) { acquired = true; } else { - mChannelPwnz[owner] |= - (1 << static_cast(chan)); + mChannelPwnz[owner] |= (1 << static_cast(chan)); acquired = true; } } else { - mChannelPwnz[owner] |= - (1 << static_cast(chan)); + mChannelPwnz[owner] |= (1 << static_cast(chan)); acquired = true; } @@ -226,29 +217,22 @@ bool CardEntry::AcquireChannel(NTV2Channel chan, NTV2Mode mode, return acquired; } -bool CardEntry::ReleaseChannel(NTV2Channel chan, NTV2Mode mode, - const std::string &owner) +bool CardEntry::ReleaseChannel(NTV2Channel chan, NTV2Mode mode, const std::string &owner) { const std::lock_guard lock(mMutex); for (const auto &pwn : mChannelPwnz) { if (pwn.first == owner) { - if (mChannelPwnz[owner] & - (1 << static_cast(chan))) { - mChannelPwnz[owner] ^= - (1 << static_cast(chan)); + if (mChannelPwnz[owner] & (1 << static_cast(chan))) { + mChannelPwnz[owner] ^= (1 << static_cast(chan)); // Release interrupt handles if (mCard) { if (mode == NTV2_MODE_CAPTURE) { - mCard->DisableInputInterrupt( - chan); - mCard->UnsubscribeInputVerticalEvent( - chan); + mCard->DisableInputInterrupt(chan); + mCard->UnsubscribeInputVerticalEvent(chan); } else if (mode == NTV2_MODE_DISPLAY) { - mCard->DisableOutputInterrupt( - chan); - mCard->UnsubscribeOutputVerticalEvent( - chan); + mCard->DisableOutputInterrupt(chan); + mCard->UnsubscribeOutputVerticalEvent(chan); } } @@ -260,8 +244,7 @@ bool CardEntry::ReleaseChannel(NTV2Channel chan, NTV2Mode mode, return false; } -bool CardEntry::InputSelectionReady(IOSelection io, NTV2DeviceID id, - const std::string &owner) const +bool CardEntry::InputSelectionReady(IOSelection io, NTV2DeviceID id, const std::string &owner) const { if (id == DEVICE_ID_KONA1 && io == IOSelection::SDI1) { return true; @@ -283,20 +266,17 @@ bool CardEntry::InputSelectionReady(IOSelection io, NTV2DeviceID id, return false; } -bool CardEntry::OutputSelectionReady(IOSelection io, NTV2DeviceID id, - const std::string &owner) const +bool CardEntry::OutputSelectionReady(IOSelection io, NTV2DeviceID id, const std::string &owner) const { /* Handle checking special case outputs before all other outputs. * 1. HDMI Monitor uses framestore 4 * 2. SDI Monitor on Io 4K/Io 4K Plus, etc. uses framestore 4. * 3. Everything else... */ - if (aja::CardCanDoHDMIMonitorOutput(id) && - io == IOSelection::HDMIMonitorOut) { + if (aja::CardCanDoHDMIMonitorOutput(id) && io == IOSelection::HDMIMonitorOut) { NTV2Channel hdmiMonChannel = NTV2_CHANNEL4; return ChannelReady(hdmiMonChannel, owner); - } else if (aja::CardCanDoSDIMonitorOutput(id) && - io == IOSelection::SDI5) { + } else if (aja::CardCanDoSDIMonitorOutput(id) && io == IOSelection::SDI5) { NTV2Channel sdiMonChannel = NTV2_CHANNEL4; return ChannelReady(sdiMonChannel, owner); } else if (id == DEVICE_ID_KONA1 && io == IOSelection::SDI1) { @@ -307,8 +287,7 @@ bool CardEntry::OutputSelectionReady(IOSelection io, NTV2DeviceID id, if (outputDests.size() > 0) { size_t channelsReady = 0; for (auto &&dst : outputDests) { - auto channel = - NTV2OutputDestinationToChannel(dst); + auto channel = NTV2OutputDestinationToChannel(dst); if (ChannelReady(channel, owner)) channelsReady++; } @@ -320,8 +299,7 @@ bool CardEntry::OutputSelectionReady(IOSelection io, NTV2DeviceID id, return false; } -bool CardEntry::AcquireInputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner) +bool CardEntry::AcquireInputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner) { UNUSED_PARAMETER(id); @@ -332,14 +310,11 @@ bool CardEntry::AcquireInputSelection(IOSelection io, NTV2DeviceID id, for (auto &&src : inputSources) { auto acqChan = NTV2InputSourceToChannel(src); if (AcquireChannel(acqChan, NTV2_MODE_CAPTURE, owner)) { - blog(LOG_DEBUG, "Source %s acquired channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Source %s acquired channel %s", owner.c_str(), NTV2ChannelToString(acqChan).c_str()); acquiredChannels.push_back(acqChan); } else { - blog(LOG_DEBUG, - "Source %s could not acquire channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Source %s could not acquire channel %s", owner.c_str(), NTV2ChannelToString(acqChan).c_str()); } } @@ -354,8 +329,7 @@ bool CardEntry::AcquireInputSelection(IOSelection io, NTV2DeviceID id, return acquiredChannels.size() == inputSources.size(); } -bool CardEntry::ReleaseInputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner) +bool CardEntry::ReleaseInputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner) { UNUSED_PARAMETER(id); @@ -365,16 +339,14 @@ bool CardEntry::ReleaseInputSelection(IOSelection io, NTV2DeviceID id, for (auto &&src : currentInputSources) { auto relChan = NTV2InputSourceToChannel(src); if (ReleaseChannel(relChan, NTV2_MODE_CAPTURE, owner)) { - blog(LOG_DEBUG, "Released Channel %s", - NTV2ChannelToString(relChan).c_str()); + blog(LOG_DEBUG, "Released Channel %s", NTV2ChannelToString(relChan).c_str()); releasedCount++; } } return releasedCount == currentInputSources.size(); } -bool CardEntry::AcquireOutputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner) +bool CardEntry::AcquireOutputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner) { std::vector acquiredChannels; NTV2OutputDestinations outputDests; @@ -382,33 +354,25 @@ bool CardEntry::AcquireOutputSelection(IOSelection io, NTV2DeviceID id, // Handle acquiring special case outputs -- // HDMI Monitor uses framestore 4 - if (aja::CardCanDoHDMIMonitorOutput(id) && - io == IOSelection::HDMIMonitorOut) { + if (aja::CardCanDoHDMIMonitorOutput(id) && io == IOSelection::HDMIMonitorOut) { NTV2Channel hdmiMonChannel = NTV2_CHANNEL4; if (AcquireChannel(hdmiMonChannel, NTV2_MODE_DISPLAY, owner)) { - blog(LOG_DEBUG, "Output %s acquired channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Output %s acquired channel %s", owner.c_str(), NTV2ChannelToString(hdmiMonChannel).c_str()); acquiredChannels.push_back(hdmiMonChannel); } else { - blog(LOG_DEBUG, - "Output %s could not acquire channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Output %s could not acquire channel %s", owner.c_str(), NTV2ChannelToString(hdmiMonChannel).c_str()); } - } else if (aja::CardCanDoSDIMonitorOutput(id) && - io == IOSelection::SDI5) { + } else if (aja::CardCanDoSDIMonitorOutput(id) && io == IOSelection::SDI5) { // SDI Monitor on io4K/io4K+/etc. uses framestore 4 NTV2Channel sdiMonChannel = NTV2_CHANNEL4; if (AcquireChannel(sdiMonChannel, NTV2_MODE_DISPLAY, owner)) { - blog(LOG_DEBUG, "Output %s acquired channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Output %s acquired channel %s", owner.c_str(), NTV2ChannelToString(sdiMonChannel).c_str()); acquiredChannels.push_back(sdiMonChannel); } else { - blog(LOG_DEBUG, - "Output %s could not acquire channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Output %s could not acquire channel %s", owner.c_str(), NTV2ChannelToString(sdiMonChannel).c_str()); } } else { @@ -417,13 +381,10 @@ bool CardEntry::AcquireOutputSelection(IOSelection io, NTV2DeviceID id, auto acqChan = NTV2OutputDestinationToChannel(dst); if (AcquireChannel(acqChan, NTV2_MODE_DISPLAY, owner)) { acquiredChannels.push_back(acqChan); - blog(LOG_DEBUG, "Output %s acquired channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Output %s acquired channel %s", owner.c_str(), NTV2ChannelToString(acqChan).c_str()); } else { - blog(LOG_DEBUG, - "Output %s could not acquire channel %s", - owner.c_str(), + blog(LOG_DEBUG, "Output %s could not acquire channel %s", owner.c_str(), NTV2ChannelToString(acqChan).c_str()); } } @@ -439,8 +400,7 @@ bool CardEntry::AcquireOutputSelection(IOSelection io, NTV2DeviceID id, return acquiredChannels.size() == outputDests.size(); } -bool CardEntry::ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner) +bool CardEntry::ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner) { NTV2OutputDestinations currentOutputDests; aja::IOSelectionToOutputDests(io, currentOutputDests); @@ -448,21 +408,17 @@ bool CardEntry::ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, // Handle releasing special case outputs -- // HDMI Monitor uses framestore 4 - if (aja::CardCanDoHDMIMonitorOutput(id) && - io == IOSelection::HDMIMonitorOut) { + if (aja::CardCanDoHDMIMonitorOutput(id) && io == IOSelection::HDMIMonitorOut) { NTV2Channel hdmiMonChannel = NTV2_CHANNEL4; if (ReleaseChannel(hdmiMonChannel, NTV2_MODE_DISPLAY, owner)) { - blog(LOG_DEBUG, "Released Channel %s", - NTV2ChannelToString(hdmiMonChannel).c_str()); + blog(LOG_DEBUG, "Released Channel %s", NTV2ChannelToString(hdmiMonChannel).c_str()); releasedCount++; } - } else if (aja::CardCanDoSDIMonitorOutput(id) && - io == IOSelection::SDI5) { + } else if (aja::CardCanDoSDIMonitorOutput(id) && io == IOSelection::SDI5) { // SDI Monitor on io4K/io4K+/etc. uses framestore 4 NTV2Channel sdiMonChannel = NTV2_CHANNEL4; if (ReleaseChannel(sdiMonChannel, NTV2_MODE_DISPLAY, owner)) { - blog(LOG_DEBUG, "Released Channel %s", - NTV2ChannelToString(sdiMonChannel).c_str()); + blog(LOG_DEBUG, "Released Channel %s", NTV2ChannelToString(sdiMonChannel).c_str()); releasedCount++; } } else { @@ -470,8 +426,7 @@ bool CardEntry::ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, for (auto &&dst : currentOutputDests) { auto relChan = NTV2OutputDestinationToChannel(dst); if (ReleaseChannel(relChan, NTV2_MODE_DISPLAY, owner)) { - blog(LOG_DEBUG, "Released Channel %s", - NTV2ChannelToString(relChan).c_str()); + blog(LOG_DEBUG, "Released Channel %s", NTV2ChannelToString(relChan).c_str()); releasedCount++; } } @@ -479,14 +434,12 @@ bool CardEntry::ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, return releasedCount == currentOutputDests.size(); } -bool CardEntry::UpdateChannelOwnerName(const std::string &oldName, - const std::string &newName) +bool CardEntry::UpdateChannelOwnerName(const std::string &oldName, const std::string &newName) { const std::lock_guard lock(mMutex); for (const auto &pwn : mChannelPwnz) { if (pwn.first == oldName) { - mChannelPwnz.insert(std::pair{ - newName, pwn.second}); + mChannelPwnz.insert(std::pair{newName, pwn.second}); mChannelPwnz.erase(oldName); @@ -504,10 +457,8 @@ bool CardEntry::isAutoCirculateRunning(NTV2Channel chan) AUTOCIRCULATE_STATUS acStatus; if (mCard->AutoCirculateGetStatus(chan, acStatus)) { - if (acStatus.acState != NTV2_AUTOCIRCULATE_RUNNING && - acStatus.acState != NTV2_AUTOCIRCULATE_STARTING && - acStatus.acState != NTV2_AUTOCIRCULATE_PAUSED && - acStatus.acState != NTV2_AUTOCIRCULATE_INIT) { + if (acStatus.acState != NTV2_AUTOCIRCULATE_RUNNING && acStatus.acState != NTV2_AUTOCIRCULATE_STARTING && + acStatus.acState != NTV2_AUTOCIRCULATE_PAUSED && acStatus.acState != NTV2_AUTOCIRCULATE_INIT) { return false; } } @@ -525,16 +476,12 @@ void CardManager::ClearCardEntries() card->SetEveryFrameServices(NTV2_STANDARD_TASKS); // Workaround for AJA internal bug #11378 // Set HDMI output back to Audio System 1 on card release - if (NTV2DeviceGetNumHDMIVideoOutputs( - card->GetDeviceID()) > 0) { - card->SetHDMIOutAudioSource8Channel( - NTV2_AudioChannel1_8, - NTV2_AUDIOSYSTEM_1); + if (NTV2DeviceGetNumHDMIVideoOutputs(card->GetDeviceID()) > 0) { + card->SetHDMIOutAudioSource8Channel(NTV2_AudioChannel1_8, NTV2_AUDIOSYSTEM_1); } int32_t pid = (int32_t)AJAProcess::GetPid(); - card->ReleaseStreamForApplicationWithReference( - (ULWord)kStreamingAppID, pid); + card->ReleaseStreamForApplicationWithReference((ULWord)kStreamingAppID, pid); } } @@ -551,25 +498,18 @@ void CardManager::EnumerateCards() // New Card Entry if (mCardEntries.find(cardID) == mCardEntries.end()) { - CardEntryPtr cardEntry = std::make_shared( - iter.deviceIndex, cardID); + CardEntryPtr cardEntry = std::make_shared(iter.deviceIndex, cardID); if (cardEntry && cardEntry->Initialize()) mCardEntries.emplace(cardID, cardEntry); } else { // Card fell off of the bus and came back with a new physical index? auto currEntry = mCardEntries[cardID]; if (currEntry) { - if (currEntry->GetCardIndex() != - iter.deviceIndex) { + if (currEntry->GetCardIndex() != iter.deviceIndex) { mCardEntries.erase(cardID); - CardEntryPtr cardEntry = - std::make_shared( - iter.deviceIndex, - cardID); - if (cardEntry && - cardEntry->Initialize()) - mCardEntries.emplace(cardID, - cardEntry); + CardEntryPtr cardEntry = std::make_shared(iter.deviceIndex, cardID); + if (cardEntry && cardEntry->Initialize()) + mCardEntries.emplace(cardID, cardEntry); } } } diff --git a/plugins/aja/aja-card-manager.hpp b/plugins/aja/aja-card-manager.hpp index 53d5bb6d6..04c87ffe0 100644 --- a/plugins/aja/aja-card-manager.hpp +++ b/plugins/aja/aja-card-manager.hpp @@ -37,26 +37,16 @@ public: virtual std::string GetDisplayName() const; virtual std::string GetSerial() const; virtual NTV2DeviceID GetDeviceID() const; - virtual bool ChannelReady(NTV2Channel chan, - const std::string &owner) const; - virtual bool AcquireChannel(NTV2Channel chan, NTV2Mode mode, - const std::string &owner); - virtual bool ReleaseChannel(NTV2Channel chan, NTV2Mode mode, - const std::string &owner); - virtual bool InputSelectionReady(IOSelection io, NTV2DeviceID id, - const std::string &owner) const; - virtual bool OutputSelectionReady(IOSelection io, NTV2DeviceID id, - const std::string &owner) const; - virtual bool AcquireInputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner); - virtual bool ReleaseInputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner); - virtual bool AcquireOutputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner); - virtual bool ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, - const std::string &owner); - virtual bool UpdateChannelOwnerName(const std::string &oldName, - const std::string &newName); + virtual bool ChannelReady(NTV2Channel chan, const std::string &owner) const; + virtual bool AcquireChannel(NTV2Channel chan, NTV2Mode mode, const std::string &owner); + virtual bool ReleaseChannel(NTV2Channel chan, NTV2Mode mode, const std::string &owner); + virtual bool InputSelectionReady(IOSelection io, NTV2DeviceID id, const std::string &owner) const; + virtual bool OutputSelectionReady(IOSelection io, NTV2DeviceID id, const std::string &owner) const; + virtual bool AcquireInputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner); + virtual bool ReleaseInputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner); + virtual bool AcquireOutputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner); + virtual bool ReleaseOutputSelection(IOSelection io, NTV2DeviceID id, const std::string &owner); + virtual bool UpdateChannelOwnerName(const std::string &oldName, const std::string &newName); private: virtual bool isAutoCirculateRunning(NTV2Channel); diff --git a/plugins/aja/aja-common.cpp b/plugins/aja/aja-common.cpp index e057802c5..7e11a9be7 100644 --- a/plugins/aja/aja-common.cpp +++ b/plugins/aja/aja-common.cpp @@ -9,16 +9,12 @@ #include #include -void filter_io_selection_input_list(const std::string &cardID, - const std::string &channelOwner, - obs_property_t *list) +void filter_io_selection_input_list(const std::string &cardID, const std::string &channelOwner, obs_property_t *list) { auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "filter_io_selection_input_list: Card Entry not found for %s", - cardID.c_str()); + blog(LOG_DEBUG, "filter_io_selection_input_list: Card Entry not found for %s", cardID.c_str()); return; } @@ -29,33 +25,26 @@ void filter_io_selection_input_list(const std::string &cardID, // Gray out the IOSelection list items that are in use by other plugin instances for (size_t idx = 0; idx < obs_property_list_item_count(list); idx++) { - auto io_select = static_cast( - obs_property_list_item_int(list, idx)); + auto io_select = static_cast(obs_property_list_item_int(list, idx)); if (io_select == IOSelection::Invalid) { obs_property_list_item_disable(list, idx, false); continue; } - bool enabled = cardEntry->InputSelectionReady( - io_select, deviceID, channelOwner); + bool enabled = cardEntry->InputSelectionReady(io_select, deviceID, channelOwner); obs_property_list_item_disable(list, idx, !enabled); - blog(LOG_DEBUG, "IOSelection %s = %s", - aja::IOSelectionToString(io_select).c_str(), + blog(LOG_DEBUG, "IOSelection %s = %s", aja::IOSelectionToString(io_select).c_str(), enabled ? "enabled" : "disabled"); } } -void filter_io_selection_output_list(const std::string &cardID, - const std::string &channelOwner, - obs_property_t *list) +void filter_io_selection_output_list(const std::string &cardID, const std::string &channelOwner, obs_property_t *list) { auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "filter_io_selection_output_list: Card Entry not found for %s", - cardID.c_str()); + blog(LOG_DEBUG, "filter_io_selection_output_list: Card Entry not found for %s", cardID.c_str()); return; } @@ -66,78 +55,57 @@ void filter_io_selection_output_list(const std::string &cardID, // Gray out the IOSelection list items that are in use by other plugin instances for (size_t idx = 0; idx < obs_property_list_item_count(list); idx++) { - auto io_select = static_cast( - obs_property_list_item_int(list, idx)); + auto io_select = static_cast(obs_property_list_item_int(list, idx)); if (io_select == IOSelection::Invalid) { obs_property_list_item_disable(list, idx, false); continue; } - bool enabled = cardEntry->OutputSelectionReady( - io_select, deviceID, channelOwner); + bool enabled = cardEntry->OutputSelectionReady(io_select, deviceID, channelOwner); obs_property_list_item_disable(list, idx, !enabled); - blog(LOG_DEBUG, "IOSelection %s = %s", - aja::IOSelectionToString(io_select).c_str(), + blog(LOG_DEBUG, "IOSelection %s = %s", aja::IOSelectionToString(io_select).c_str(), enabled ? "enabled" : "disabled"); } } -void populate_io_selection_input_list(const std::string &cardID, - const std::string &channelOwner, - NTV2DeviceID deviceID, +void populate_io_selection_input_list(const std::string &cardID, const std::string &channelOwner, NTV2DeviceID deviceID, obs_property_t *list) { obs_property_list_clear(list); - obs_property_list_add_int(list, - obs_module_text(kUIPropIOSelectNone.text), + obs_property_list_add_int(list, obs_module_text(kUIPropIOSelectNone.text), static_cast(IOSelection::Invalid)); - for (auto i = 0; i < static_cast(IOSelection::NumIOSelections); - i++) { + for (auto i = 0; i < static_cast(IOSelection::NumIOSelections); i++) { auto ioSelect = static_cast(i); if (ioSelect == IOSelection::AnalogIn) continue; if (aja::DeviceCanDoIOSelectionIn(deviceID, ioSelect)) { - obs_property_list_add_int( - list, - aja::IOSelectionToString(ioSelect).c_str(), - static_cast(ioSelect)); + obs_property_list_add_int(list, aja::IOSelectionToString(ioSelect).c_str(), + static_cast(ioSelect)); } } filter_io_selection_input_list(cardID, channelOwner, list); } -void populate_io_selection_output_list(const std::string &cardID, - const std::string &channelOwner, - NTV2DeviceID deviceID, - obs_property_t *list) +void populate_io_selection_output_list(const std::string &cardID, const std::string &channelOwner, + NTV2DeviceID deviceID, obs_property_t *list) { obs_property_list_clear(list); - obs_property_list_add_int(list, - obs_module_text(kUIPropIOSelectNone.text), + obs_property_list_add_int(list, obs_module_text(kUIPropIOSelectNone.text), static_cast(IOSelection::Invalid)); if (deviceID == DEVICE_ID_TTAP_PRO) { - obs_property_list_add_int( - list, "SDI & HDMI", - static_cast(IOSelection::HDMIMonitorOut)); + obs_property_list_add_int(list, "SDI & HDMI", static_cast(IOSelection::HDMIMonitorOut)); } else { - for (auto i = 0; - i < static_cast(IOSelection::NumIOSelections); - i++) { + for (auto i = 0; i < static_cast(IOSelection::NumIOSelections); i++) { auto ioSelect = static_cast(i); - if (ioSelect == IOSelection::Invalid || - ioSelect == IOSelection::AnalogOut) + if (ioSelect == IOSelection::Invalid || ioSelect == IOSelection::AnalogOut) continue; - if (aja::DeviceCanDoIOSelectionOut(deviceID, - ioSelect)) { - obs_property_list_add_int( - list, - aja::IOSelectionToString(ioSelect) - .c_str(), - static_cast(ioSelect)); + if (aja::DeviceCanDoIOSelectionOut(deviceID, ioSelect)) { + obs_property_list_add_int(list, aja::IOSelectionToString(ioSelect).c_str(), + static_cast(ioSelect)); } } } @@ -145,9 +113,8 @@ void populate_io_selection_output_list(const std::string &cardID, filter_io_selection_output_list(cardID, channelOwner, list); } -void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, - NTV2VideoFormat genlockFormat, bool want4KHFR, - bool matchFPS) +void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, NTV2VideoFormat genlockFormat, + bool want4KHFR, bool matchFPS) { VideoFormatList videoFormats = {}; VideoStandardList orderedStandards = {}; @@ -182,13 +149,11 @@ void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, struct obs_video_info ovi; if (matchFPS && obs_get_video_info(&ovi)) { - NTV2FrameRate frameRate = - GetNTV2FrameRateFromVideoFormat(vf); + NTV2FrameRate frameRate = GetNTV2FrameRateFromVideoFormat(vf); ULWord fpsNum = 0; ULWord fpsDen = 0; GetFramesPerSecond(frameRate, fpsNum, fpsDen); - uint32_t obsFrameTime = - 1000000 * ovi.fps_den / ovi.fps_num; + uint32_t obsFrameTime = 1000000 * ovi.fps_den / ovi.fps_num; uint32_t ajaFrameTime = 1000000 * fpsDen / fpsNum; if (obsFrameTime != ajaFrameTime) addFormat = false; @@ -201,66 +166,50 @@ void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, } } -void populate_pixel_format_list(NTV2DeviceID deviceID, - const std::vector &fmts, - obs_property_t *list) +void populate_pixel_format_list(NTV2DeviceID deviceID, const std::vector &fmts, obs_property_t *list) { for (auto &&pf : fmts) { if (NTV2DeviceCanDoFrameBufferFormat(deviceID, pf)) { - obs_property_list_add_int( - list, - NTV2FrameBufferFormatToString(pf, true).c_str(), - static_cast(pf)); + obs_property_list_add_int(list, NTV2FrameBufferFormatToString(pf, true).c_str(), + static_cast(pf)); } } } -void populate_sdi_transport_list(obs_property_t *list, NTV2DeviceID deviceID, - bool capture) +void populate_sdi_transport_list(obs_property_t *list, NTV2DeviceID deviceID, bool capture) { if (capture) { - obs_property_list_add_int(list, obs_module_text("Auto"), - kAutoDetect); + obs_property_list_add_int(list, obs_module_text("Auto"), kAutoDetect); } for (int i = 0; i < (int)SDITransport::Unknown; i++) { SDITransport sdi_trx = static_cast(i); - if (sdi_trx == SDITransport::SDI6G || - sdi_trx == SDITransport::SDI12G) { + if (sdi_trx == SDITransport::SDI6G || sdi_trx == SDITransport::SDI12G) { if (!NTV2DeviceCanDo12GSDI(deviceID)) continue; } // Disabling 12G in Output plugin until AJA 4K HFR bug is fixed if (!capture && sdi_trx == SDITransport::SDI12G) continue; - obs_property_list_add_int( - list, aja::SDITransportToString(sdi_trx).c_str(), - static_cast(sdi_trx)); + obs_property_list_add_int(list, aja::SDITransportToString(sdi_trx).c_str(), + static_cast(sdi_trx)); } } void populate_sdi_4k_transport_list(obs_property_t *list) { - obs_property_list_add_int( - list, - aja::SDITransport4KToString(SDITransport4K::Squares).c_str(), - static_cast(SDITransport4K::Squares)); - obs_property_list_add_int( - list, - aja::SDITransport4KToString(SDITransport4K::TwoSampleInterleave) - .c_str(), - static_cast(SDITransport4K::TwoSampleInterleave)); + obs_property_list_add_int(list, aja::SDITransport4KToString(SDITransport4K::Squares).c_str(), + static_cast(SDITransport4K::Squares)); + obs_property_list_add_int(list, aja::SDITransport4KToString(SDITransport4K::TwoSampleInterleave).c_str(), + static_cast(SDITransport4K::TwoSampleInterleave)); } -bool aja_video_format_changed(obs_properties_t *props, obs_property_t *list, - obs_data_t *settings) +bool aja_video_format_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { - auto vid_fmt = static_cast( - obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); + auto vid_fmt = static_cast(obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); size_t itemCount = obs_property_list_item_count(list); bool itemFound = false; for (size_t i = 0; i < itemCount; i++) { - auto itemFormat = static_cast( - obs_property_list_item_int(list, i)); + auto itemFormat = static_cast(obs_property_list_item_int(list, i)); if (itemFormat == vid_fmt) { itemFound = true; break; @@ -273,8 +222,7 @@ bool aja_video_format_changed(obs_properties_t *props, obs_property_t *list, return true; } - obs_property_t *sdi_4k_trx = - obs_properties_get(props, kUIPropSDITransport4K.id); + obs_property_t *sdi_4k_trx = obs_properties_get(props, kUIPropSDITransport4K.id); obs_property_set_visible(sdi_4k_trx, NTV2_IS_4K_VIDEO_FORMAT(vid_fmt)); return true; @@ -334,8 +282,7 @@ video_format AJAPixelFormatToOBSVideoFormat(NTV2PixelFormat pf) return obs_video_format; } -void GetSortedVideoFormats(NTV2DeviceID id, const VideoStandardList &standards, - VideoFormatList &videoFormats) +void GetSortedVideoFormats(NTV2DeviceID id, const VideoStandardList &standards, VideoFormatList &videoFormats) { if (standards.empty()) return; @@ -343,34 +290,27 @@ void GetSortedVideoFormats(NTV2DeviceID id, const VideoStandardList &standards, VideoFormatMap videoFormatMap; // Bin all the formats based on video standard - for (size_t i = (size_t)NTV2_FORMAT_UNKNOWN; - i < (size_t)NTV2_MAX_NUM_VIDEO_FORMATS; i++) { + for (size_t i = (size_t)NTV2_FORMAT_UNKNOWN; i < (size_t)NTV2_MAX_NUM_VIDEO_FORMATS; i++) { NTV2VideoFormat fmt = (NTV2VideoFormat)i; NTV2Standard standard = GetNTV2StandardFromVideoFormat(fmt); - if (id != DEVICE_ID_NOTFOUND && - NTV2DeviceCanDoVideoFormat(id, fmt)) { + if (id != DEVICE_ID_NOTFOUND && NTV2DeviceCanDoVideoFormat(id, fmt)) { if (videoFormatMap.count(standard)) { videoFormatMap.at(standard).push_back(fmt); } else { std::vector v; v.push_back(fmt); videoFormatMap.insert( - std::pair>( - standard, v)); + std::pair>(standard, v)); } } } - for (size_t v = (size_t)NTV2_STANDARD_1080; - v < (size_t)NTV2_NUM_STANDARDS; v++) { + for (size_t v = (size_t)NTV2_STANDARD_1080; v < (size_t)NTV2_NUM_STANDARDS; v++) { NTV2Standard standard = (NTV2Standard)v; if (videoFormatMap.count(standard)) { - std::sort(videoFormatMap.at(standard).begin(), - videoFormatMap.at(standard).end(), - [&](const NTV2VideoFormat &d1, - const NTV2VideoFormat &d2) { + std::sort(videoFormatMap.at(standard).begin(), videoFormatMap.at(standard).end(), + [&](const NTV2VideoFormat &d1, const NTV2VideoFormat &d2) { std::string d1Str, d2Str; d1Str = NTV2VideoFormatToString(d1); @@ -384,32 +324,26 @@ void GetSortedVideoFormats(NTV2DeviceID id, const VideoStandardList &standards, for (size_t v = 0; v < standards.size(); v++) { NTV2Standard standard = standards.at(v); if (videoFormatMap.count(standard)) { - for (size_t i = 0; - i < videoFormatMap.at(standard).size(); i++) { - NTV2VideoFormat vf = - videoFormatMap.at(standard).at(i); + for (size_t i = 0; i < videoFormatMap.at(standard).size(); i++) { + NTV2VideoFormat vf = videoFormatMap.at(standard).at(i); videoFormats.push_back(vf); } } } } -NTV2VideoFormat HandleSpecialCaseFormats(IOSelection io, NTV2VideoFormat vf, - NTV2DeviceID id) +NTV2VideoFormat HandleSpecialCaseFormats(IOSelection io, NTV2VideoFormat vf, NTV2DeviceID id) { // 1080p Level-B formats and ST372M - if (NTV2_VIDEO_FORMAT_IS_B(vf) && - !(IsSDITwoWireIOSelection(io) && NTV2_IS_HD_VIDEO_FORMAT(vf))) { + if (NTV2_VIDEO_FORMAT_IS_B(vf) && !(IsSDITwoWireIOSelection(io) && NTV2_IS_HD_VIDEO_FORMAT(vf))) { vf = aja::GetLevelAFormatForLevelBFormat(vf); } // UHD/4K Square Division auto-detect - if ((io == IOSelection::SDI1__4 || io == IOSelection::SDI5__8) && - NTV2_IS_HD_VIDEO_FORMAT(vf)) { + if ((io == IOSelection::SDI1__4 || io == IOSelection::SDI5__8) && NTV2_IS_HD_VIDEO_FORMAT(vf)) { vf = GetQuadSizedVideoFormat(vf, true); } // Kona5/io4K+ auto-detection of UHD/4K 6G/12G SDI formats. - if (aja::IsSDIOneWireIOSelection(io) && NTV2_IS_4K_VIDEO_FORMAT(vf) && - !NTV2_IS_SQUARE_DIVISION_FORMAT(vf) && + if (aja::IsSDIOneWireIOSelection(io) && NTV2_IS_4K_VIDEO_FORMAT(vf) && !NTV2_IS_SQUARE_DIVISION_FORMAT(vf) && !NTV2DeviceCanDo12gRouting(id)) { vf = GetQuadSizedVideoFormat(GetQuarterSizedVideoFormat(vf)); } @@ -452,27 +386,23 @@ bool CardCanDoSDIMonitorOutput(NTV2DeviceID id) // Cards with a dedicated HDMI Monitor Input, tied to "Framestore 4". bool CardCanDoHDMIMonitorInput(NTV2DeviceID id) { - return (id == DEVICE_ID_IO4K || id == DEVICE_ID_IO4KUFC || - id == DEVICE_ID_IO4KPLUS || id == DEVICE_ID_IOXT || + return (id == DEVICE_ID_IO4K || id == DEVICE_ID_IO4KUFC || id == DEVICE_ID_IO4KPLUS || id == DEVICE_ID_IOXT || id == DEVICE_ID_IOX3 || id == DEVICE_ID_KONALHI); } // Cards with a dedicated HDMI Monitor Output, tied to "Framestore 4". bool CardCanDoHDMIMonitorOutput(NTV2DeviceID id) { - return (id == DEVICE_ID_IO4K || id == DEVICE_ID_IO4KPLUS || - id == DEVICE_ID_IOXT || id == DEVICE_ID_IOX3 || - id == DEVICE_ID_KONA4 || id == DEVICE_ID_KONA5 || - id == DEVICE_ID_KONA5_8K || id == DEVICE_ID_KONA5_2X4K || - id == DEVICE_ID_KONA5_8KMK); + return (id == DEVICE_ID_IO4K || id == DEVICE_ID_IO4KPLUS || id == DEVICE_ID_IOXT || id == DEVICE_ID_IOX3 || + id == DEVICE_ID_KONA4 || id == DEVICE_ID_KONA5 || id == DEVICE_ID_KONA5_8K || + id == DEVICE_ID_KONA5_2X4K || id == DEVICE_ID_KONA5_8KMK); } // Cards capable of 1x SDI at 6G/12G. bool CardCanDo1xSDI12G(NTV2DeviceID id) { - return (id == DEVICE_ID_KONA5_8K || id == DEVICE_ID_KONA5_8KMK || - id == DEVICE_ID_KONA5 || id == DEVICE_ID_KONA5_2X4K || - id == DEVICE_ID_IO4KPLUS || id == DEVICE_ID_CORVID44_12G); + return (id == DEVICE_ID_KONA5_8K || id == DEVICE_ID_KONA5_8KMK || id == DEVICE_ID_KONA5 || + id == DEVICE_ID_KONA5_2X4K || id == DEVICE_ID_IO4KPLUS || id == DEVICE_ID_CORVID44_12G); } // Check for 3G level-B SDI on the wire. @@ -485,8 +415,7 @@ bool Is3GLevelB(CNTV2Card *card, NTV2Channel channel) auto deviceID = card->GetDeviceID(); UWord channelIndex = static_cast(channel); - if (NTV2DeviceCanDo3GIn(deviceID, channelIndex) || - NTV2DeviceCanDo12GIn(deviceID, channelIndex)) { + if (NTV2DeviceCanDo3GIn(deviceID, channelIndex) || NTV2DeviceCanDo12GIn(deviceID, channelIndex)) { if (!card->GetSDIInput3GbPresent(levelB, channel)) return false; } @@ -553,8 +482,7 @@ bool IsSingleSDIDevice(NTV2DeviceID id) bool IsIODevice(NTV2DeviceID id) { - return (id == DEVICE_ID_IOXT || id == DEVICE_ID_IOX3 || - id == DEVICE_ID_IO4K || id == DEVICE_ID_IO4KPLUS || + return (id == DEVICE_ID_IOXT || id == DEVICE_ID_IOX3 || id == DEVICE_ID_IO4K || id == DEVICE_ID_IO4KPLUS || id == DEVICE_ID_IOIP_2022 || id == DEVICE_ID_IOIP_2110); } @@ -778,8 +706,7 @@ void IOSelectionToInputSources(IOSelection io, NTV2InputSourceSet &inputSources) } } -void IOSelectionToOutputDests(IOSelection io, - NTV2OutputDestinations &outputDests) +void IOSelectionToOutputDests(IOSelection io, NTV2OutputDestinations &outputDests) { switch (io) { case IOSelection::SDI1: @@ -963,13 +890,10 @@ bool IsMonitorOutputSelection(NTV2DeviceID id, IOSelection io) bool IsIOSelectionSDI(IOSelection io) { - if (io == IOSelection::SDI1 || io == IOSelection::SDI2 || - io == IOSelection::SDI3 || io == IOSelection::SDI4 || - io == IOSelection::SDI5 || io == IOSelection::SDI6 || - io == IOSelection::SDI7 || io == IOSelection::SDI8 || - io == IOSelection::SDI1_2 || io == IOSelection::SDI3_4 || - io == IOSelection::SDI5_6 || io == IOSelection::SDI7_8 || - io == IOSelection::SDI1__4 || io == IOSelection::SDI5__8) { + if (io == IOSelection::SDI1 || io == IOSelection::SDI2 || io == IOSelection::SDI3 || io == IOSelection::SDI4 || + io == IOSelection::SDI5 || io == IOSelection::SDI6 || io == IOSelection::SDI7 || io == IOSelection::SDI8 || + io == IOSelection::SDI1_2 || io == IOSelection::SDI3_4 || io == IOSelection::SDI5_6 || + io == IOSelection::SDI7_8 || io == IOSelection::SDI1__4 || io == IOSelection::SDI5__8) { return true; } return false; @@ -977,10 +901,8 @@ bool IsIOSelectionSDI(IOSelection io) bool IsIOSelectionHDMI(IOSelection io) { - if (io == IOSelection::HDMI1 || io == IOSelection::HDMI2 || - io == IOSelection::HDMI3 || io == IOSelection::HDMI4 || - io == IOSelection::HDMIMonitorIn || - io == IOSelection::HDMIMonitorOut) { + if (io == IOSelection::HDMI1 || io == IOSelection::HDMI2 || io == IOSelection::HDMI3 || + io == IOSelection::HDMI4 || io == IOSelection::HDMIMonitorIn || io == IOSelection::HDMIMonitorOut) { return true; } return false; @@ -991,8 +913,7 @@ std::string MakeCardID(CNTV2Card &card) std::string cardID; if (card.GetSerialNumberString(cardID)) { // Try to construct CardID from device ID and serial number... - cardID = NTV2DeviceIDToString(card.GetDeviceID(), false) + "_" + - cardID; + cardID = NTV2DeviceIDToString(card.GetDeviceID(), false) + "_" + cardID; } else { // ...otherwise fall back to the CNTV2DeviceScanner method. cardID = CNTV2DeviceScanner::GetDeviceRefName(card); @@ -1019,31 +940,27 @@ RasterDefinition DetermineRasterDefinition(NTV2VideoFormat vf) inline bool IsStandard1080i(NTV2Standard standard) { - if (standard == NTV2_STANDARD_1080 || - standard == NTV2_STANDARD_2Kx1080i) { + if (standard == NTV2_STANDARD_1080 || standard == NTV2_STANDARD_2Kx1080i) { return true; } return false; } inline bool IsStandard1080p(NTV2Standard standard) { - if (standard == NTV2_STANDARD_1080p || standard == NTV2_STANDARD_2K || - standard == NTV2_STANDARD_2Kx1080p) { + if (standard == NTV2_STANDARD_1080p || standard == NTV2_STANDARD_2K || standard == NTV2_STANDARD_2Kx1080p) { return true; } return false; } -VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, - NTV2PixelFormat pf, SDITransport trx, +VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, NTV2PixelFormat pf, SDITransport trx, SDITransport4K t4k) { VPIDStandard vpid = VPIDStandard_Unknown; auto rd = aja::DetermineRasterDefinition(vf); auto standard = GetNTV2StandardFromVideoFormat(vf); bool is_rgb = NTV2_IS_FBF_RGB(pf); - bool is_hfr = - NTV2_IS_HIGH_NTV2FrameRate(GetNTV2FrameRateFromVideoFormat(vf)); + bool is_hfr = NTV2_IS_HIGH_NTV2FrameRate(GetNTV2FrameRateFromVideoFormat(vf)); if (rd == RasterDefinition::SD) { vpid = VPIDStandard_483_576; } else if (rd == RasterDefinition::HD) { @@ -1053,21 +970,17 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, if (standard == NTV2_STANDARD_720) { if (trx == SDITransport::SingleLink) { vpid = VPIDStandard_720; - } else if (trx == - SDITransport::SDI3Ga) { + } else if (trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_720_3Ga; - } else if (trx == - SDITransport::SDI3Gb) { + } else if (trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_720_3Gb; } } else if (IsStandard1080p(standard)) { if (trx == SDITransport::SingleLink) { vpid = VPIDStandard_1080; - } else if (trx == - SDITransport::SDI3Ga) { + } else if (trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_1080_3Ga; - } else if (trx == - SDITransport::SDI3Gb) { + } else if (trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_1080_3Gb; } } @@ -1076,11 +989,9 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, vpid = VPIDStandard_720; } else if (IsStandard1080i(standard)) { vpid = VPIDStandard_1080; - } else if (IsStandard1080p(standard) && - trx == SDITransport::SDI3Ga) { + } else if (IsStandard1080p(standard) && trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_1080_3Ga; - } else if (IsStandard1080p(standard) && - trx == SDITransport::SDI3Gb) { + } else if (IsStandard1080p(standard) && trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_1080_3Gb; } } @@ -1100,8 +1011,7 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, vpid = VPIDStandard_1080_Dual_3Gb; } } else { - if (IsStandard1080p(standard) && - trx == SDITransport::HDDualLink) { + if (IsStandard1080p(standard) && trx == SDITransport::HDDualLink) { vpid = VPIDStandard_1080_DualLink; } } @@ -1130,13 +1040,10 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, // YCbCr if (t4k == SDITransport4K::Squares) { vpid = VPIDStandard_1080; - } else if (t4k == - SDITransport4K::TwoSampleInterleave) { - if (is_hfr && - trx == SDITransport::SDI3Ga) { + } else if (t4k == SDITransport4K::TwoSampleInterleave) { + if (is_hfr && trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_2160_QuadLink_3Ga; - } else if (is_hfr && - trx == SDITransport::SDI3Gb) { + } else if (is_hfr && trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_2160_QuadDualLink_3Gb; } else { vpid = VPIDStandard_2160_DualLink; @@ -1148,8 +1055,7 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, if (t4k == SDITransport4K::Squares) { if (trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_1080_3Ga; - } else if (trx == - SDITransport::SDI3Gb) { + } else if (trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_1080_DualLink_3Gb; } } @@ -1158,18 +1064,15 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, if (t4k == SDITransport4K::Squares) { if (trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_1080_3Ga; - } else if (trx == - SDITransport::SDI3Gb) { + } else if (trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_1080_DualLink_3Gb; } else { vpid = VPIDStandard_1080; } - } else if (t4k == - SDITransport4K::TwoSampleInterleave) { + } else if (t4k == SDITransport4K::TwoSampleInterleave) { if (trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_2160_QuadLink_3Ga; - } else if (trx == - SDITransport::SDI3Gb) { + } else if (trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_2160_QuadDualLink_3Gb; } } diff --git a/plugins/aja/aja-common.hpp b/plugins/aja/aja-common.hpp index f8e0d7516..f1ebf93ad 100644 --- a/plugins/aja/aja-common.hpp +++ b/plugins/aja/aja-common.hpp @@ -21,38 +21,25 @@ static const int kAutoDetect = -1; static const NTV2VideoFormat kDefaultAJAVideoFormat = NTV2_FORMAT_720p_5994; static const NTV2PixelFormat kDefaultAJAPixelFormat = NTV2_FBF_8BIT_YCBCR; static const SDITransport kDefaultAJASDITransport = SDITransport::SingleLink; -static const SDITransport4K kDefaultAJASDITransport4K = - SDITransport4K::TwoSampleInterleave; +static const SDITransport4K kDefaultAJASDITransport4K = SDITransport4K::TwoSampleInterleave; // Common OBS property helpers used by both the capture and output plugins -extern void filter_io_selection_input_list(const std::string &cardID, - const std::string &channelOwner, +extern void filter_io_selection_input_list(const std::string &cardID, const std::string &channelOwner, obs_property_t *list); -extern void filter_io_selection_output_list(const std::string &cardID, - const std::string &channelOwner, +extern void filter_io_selection_output_list(const std::string &cardID, const std::string &channelOwner, obs_property_t *list); -extern void populate_io_selection_input_list(const std::string &cardID, - const std::string &channelOwner, - NTV2DeviceID deviceID, - obs_property_t *list); -extern void populate_io_selection_output_list(const std::string &cardID, - const std::string &channelOwner, - NTV2DeviceID deviceID, - obs_property_t *list); -extern void -populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, - NTV2VideoFormat genlockFormat = NTV2_FORMAT_UNKNOWN, - bool want4KHFR = false, bool matchFPS = false); -extern void populate_pixel_format_list(NTV2DeviceID deviceID, - const std::vector &fmts, +extern void populate_io_selection_input_list(const std::string &cardID, const std::string &channelOwner, + NTV2DeviceID deviceID, obs_property_t *list); +extern void populate_io_selection_output_list(const std::string &cardID, const std::string &channelOwner, + NTV2DeviceID deviceID, obs_property_t *list); +extern void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, + NTV2VideoFormat genlockFormat = NTV2_FORMAT_UNKNOWN, bool want4KHFR = false, + bool matchFPS = false); +extern void populate_pixel_format_list(NTV2DeviceID deviceID, const std::vector &fmts, obs_property_t *list); -extern void populate_sdi_transport_list(obs_property_t *list, - NTV2DeviceID deviceID, - bool capture = false); +extern void populate_sdi_transport_list(obs_property_t *list, NTV2DeviceID deviceID, bool capture = false); extern void populate_sdi_4k_transport_list(obs_property_t *list); -extern bool aja_video_format_changed(obs_properties_t *props, - obs_property_t *list, - obs_data_t *settings); +extern bool aja_video_format_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings); // Additional helpers for AJA channel and signal routing configuration not found in the NTV2 SDK namespace aja { @@ -64,11 +51,8 @@ template bool vec_contains(const std::vector &vec, const T &elem) extern video_format AJAPixelFormatToOBSVideoFormat(NTV2PixelFormat pf); -extern void GetSortedVideoFormats(NTV2DeviceID id, - const VideoStandardList &standards, - VideoFormatList &videoFormats); -extern NTV2VideoFormat -HandleSpecialCaseFormats(IOSelection io, NTV2VideoFormat vf, NTV2DeviceID id); +extern void GetSortedVideoFormats(NTV2DeviceID id, const VideoStandardList &standards, VideoFormatList &videoFormats); +extern NTV2VideoFormat HandleSpecialCaseFormats(IOSelection io, NTV2VideoFormat vf, NTV2DeviceID id); extern NTV2Channel WidgetIDToChannel(NTV2WidgetID id); @@ -90,10 +74,8 @@ extern std::string SDITransportToString(SDITransport mode); extern std::string SDITransport4KToString(SDITransport4K mode); extern std::string IOSelectionToString(IOSelection io); -extern void IOSelectionToInputSources(IOSelection io, - NTV2InputSourceSet &inputSources); -extern void IOSelectionToOutputDests(IOSelection io, - NTV2OutputDestinations &outputDests); +extern void IOSelectionToInputSources(IOSelection io, NTV2InputSourceSet &inputSources); +extern void IOSelectionToOutputDests(IOSelection io, NTV2OutputDestinations &outputDests); extern bool DeviceCanDoIOSelectionIn(NTV2DeviceID id, IOSelection io); extern bool DeviceCanDoIOSelectionOut(NTV2DeviceID id, IOSelection io); extern bool IsSDIOneWireIOSelection(IOSelection io); @@ -106,8 +88,7 @@ extern bool IsIOSelectionHDMI(IOSelection io); extern std::string MakeCardID(CNTV2Card &card); extern RasterDefinition DetermineRasterDefinition(NTV2VideoFormat vf); -extern VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, - NTV2PixelFormat pf, SDITransport trx, +extern VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, NTV2PixelFormat pf, SDITransport trx, SDITransport4K t4k); extern std::vector MultiViewCards(); diff --git a/plugins/aja/aja-enums.hpp b/plugins/aja/aja-enums.hpp index 5c705e64a..f406be00a 100644 --- a/plugins/aja/aja-enums.hpp +++ b/plugins/aja/aja-enums.hpp @@ -59,20 +59,8 @@ enum class SDITransport { enum class SDITransport4K { Squares = 0, TwoSampleInterleave = 1, Unknown = 2 }; -enum class RasterDefinition { - SD = 0, - HD = 1, - UHD_4K = 2, - UHD2_8K = 3, - Unknown -}; +enum class RasterDefinition { SD = 0, HD = 1, UHD_4K = 2, UHD2_8K = 3, Unknown }; -enum class HDMIWireFormat { - SD_HD_YCBCR = 0, - SD_HD_RGB = 1, - UHD_4K_YCBCR = 2, - UHD_4K_RGB = 3, - Unknown -}; +enum class HDMIWireFormat { SD_HD_YCBCR = 0, SD_HD_RGB = 1, UHD_4K_YCBCR = 2, UHD_4K_RGB = 3, Unknown }; using VPIDSpec = std::pair; diff --git a/plugins/aja/aja-output.cpp b/plugins/aja/aja-output.cpp index 94e0816f1..91d0ad62e 100644 --- a/plugins/aja/aja-output.cpp +++ b/plugins/aja/aja-output.cpp @@ -30,8 +30,7 @@ static constexpr int64_t kDefaultStatPeriod = 2000000000; static constexpr int64_t kAudioSyncAdjust = 500; static constexpr int64_t kVideoSyncAdjust = 1; -static void copy_audio_data(struct audio_data *src, struct audio_data *dst, - size_t size) +static void copy_audio_data(struct audio_data *src, struct audio_data *dst, size_t size) { if (src->data[0]) { dst->data[0] = (uint8_t *)bmemdup(src->data[0], size); @@ -47,8 +46,7 @@ static void free_audio_data(struct audio_data *frames) memset(frames, 0, sizeof(*frames)); } -static void copy_video_data(struct video_data *src, struct video_data *dst, - size_t size) +static void copy_video_data(struct video_data *src, struct video_data *dst, size_t size) { if (src->data[0]) { dst->data[0] = (uint8_t *)bmemdup(src->data[0], size); @@ -65,29 +63,23 @@ static void free_video_frame(struct video_data *frame) memset(frame, 0, sizeof(*frame)); } -static void update_sdi_transport_and_sdi_transport_4k(obs_properties_t *props, - NTV2DeviceID device_id, - IOSelection io, +static void update_sdi_transport_and_sdi_transport_4k(obs_properties_t *props, NTV2DeviceID device_id, IOSelection io, NTV2VideoFormat vf) { // Update SDI Transport and SDI 4K Transport selections - obs_property_t *sdi_trx_list = - obs_properties_get(props, kUIPropSDITransport.id); + obs_property_t *sdi_trx_list = obs_properties_get(props, kUIPropSDITransport.id); obs_property_list_clear(sdi_trx_list); populate_sdi_transport_list(sdi_trx_list, device_id); - obs_property_t *sdi_4k_trx_list = - obs_properties_get(props, kUIPropSDITransport4K.id); + obs_property_t *sdi_4k_trx_list = obs_properties_get(props, kUIPropSDITransport4K.id); obs_property_list_clear(sdi_4k_trx_list); populate_sdi_4k_transport_list(sdi_4k_trx_list); bool is_sdi = aja::IsIOSelectionSDI(io); obs_property_set_visible(sdi_trx_list, is_sdi); - obs_property_set_visible(sdi_4k_trx_list, - is_sdi && NTV2_IS_4K_VIDEO_FORMAT(vf)); + obs_property_set_visible(sdi_4k_trx_list, is_sdi && NTV2_IS_4K_VIDEO_FORMAT(vf)); } -AJAOutput::AJAOutput(CNTV2Card *card, const std::string &cardID, - const std::string &outputID, UWord deviceIndex, +AJAOutput::AJAOutput(CNTV2Card *card, const std::string &cardID, const std::string &outputID, UWord deviceIndex, const NTV2DeviceID deviceID) : mCardID{cardID}, mOutputID{outputID}, @@ -167,28 +159,23 @@ void AJAOutput::Initialize(const OutputProps &props) // Specify small ring of frame buffers on the card for DMA and playback. // Starts at frame index corresponding to the output Channel * numFrames. - calculate_card_frame_indices(kNumCardFrames, mCard->GetDeviceID(), - props.Channel(), props.videoFormat, + calculate_card_frame_indices(kNumCardFrames, mCard->GetDeviceID(), props.Channel(), props.videoFormat, props.pixelFormat); // Write black frames to the card to prevent playing garbage before the first DMA write. for (uint32_t i = mFirstCardFrame; i <= mLastCardFrame; i++) { - GenerateTestPattern(props.videoFormat, props.pixelFormat, - NTV2_TestPatt_Black, i); + GenerateTestPattern(props.videoFormat, props.pixelFormat, NTV2_TestPatt_Black, i); } mCard->WaitForOutputVerticalInterrupt(props.Channel()); - const auto &cardFrameRate = - GetNTV2FrameRateFromVideoFormat(props.videoFormat); + const auto &cardFrameRate = GetNTV2FrameRateFromVideoFormat(props.videoFormat); ULWord fpsNum = 0; ULWord fpsDen = 0; GetFramesPerSecond(cardFrameRate, fpsNum, fpsDen); mFrameRateNum = fpsNum; mFrameRateDen = fpsDen; - mOutputDelay = - (int64_t)kFrameDelay * 1000000 * mFrameRateDen / mFrameRateNum; - mVideoMax = (int64_t)kVideoSyncAdjust * 1000000 * mFrameRateDen / - mFrameRateNum; + mOutputDelay = (int64_t)kFrameDelay * 1000000 * mFrameRateDen / mFrameRateNum; + mVideoMax = (int64_t)kVideoSyncAdjust * 1000000 * mFrameRateDen / mFrameRateNum; mVideoMax -= 100; mAudioMax = (int64_t)kAudioSyncAdjust * 1000000 / props.audioSampleRate; SetOutputProps(props); @@ -238,8 +225,7 @@ void AJAOutput::ClearConnections() mCrosspoints.clear(); } -void AJAOutput::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, - NTV2TestPatternSelect pattern, +void AJAOutput::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2TestPatternSelect pattern, uint32_t frameNum) { NTV2VideoFormat vid_fmt = vf; @@ -256,21 +242,16 @@ void AJAOutput::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, mTestPattern.clear(); mTestPattern.resize(bufSize); NTV2TestPatternGen gen; - gen.DrawTestPattern(pattern, fd.GetRasterWidth(), - fd.GetRasterHeight(), pix_fmt, - mTestPattern); + gen.DrawTestPattern(pattern, fd.GetRasterWidth(), fd.GetRasterHeight(), pix_fmt, mTestPattern); } if (mTestPattern.size() == 0) { - blog(LOG_DEBUG, - "AJAOutput::GenerateTestPattern: Error generating test pattern!"); + blog(LOG_DEBUG, "AJAOutput::GenerateTestPattern: Error generating test pattern!"); return; } - if (mCard->DMAWriteFrame( - frameNum, - reinterpret_cast(&mTestPattern.data()[0]), - static_cast(mTestPattern.size()))) { + if (mCard->DMAWriteFrame(frameNum, reinterpret_cast(&mTestPattern.data()[0]), + static_cast(mTestPattern.size()))) { mCard->SetOutputFrame(mOutputProps.Channel(), frameNum); } } @@ -348,8 +329,7 @@ size_t AJAOutput::AudioQueueSize() } // lock audio queue before calling -void AJAOutput::DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, - uint32_t sampleRate, uint32_t sampleSize) +void AJAOutput::DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, uint32_t sampleRate, uint32_t sampleSize) { AudioFrames &af = mAudioQueue->front(); size_t sizeLeft = af.size - af.offset; @@ -373,8 +353,7 @@ void AJAOutput::DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, if (mAudioPlayCursor <= mAudioWriteCursor) { audioPlaySamples = audioPlayBytes / (channels * sampleSize); } else { - audioPlayBytes = mAudioWrapAddress - mAudioPlayCursor + - mAudioWriteCursor; + audioPlayBytes = mAudioWrapAddress - mAudioPlayCursor + mAudioWriteCursor; audioPlaySamples = audioPlayBytes / (channels * sampleSize); } mAudioDelay = 1000000 * (int64_t)audioPlaySamples / sampleRate; @@ -384,52 +363,37 @@ void AJAOutput::DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, if (mAudioAdjust != 0) { if (mAudioAdjust > 0) { // Throw away some samples to resync audio - uint32_t adjustSamples = - (uint32_t)mAudioAdjust * sampleRate / 1000000; - uint32_t adjustSize = - adjustSamples * sampleSize * channels; + uint32_t adjustSamples = (uint32_t)mAudioAdjust * sampleRate / 1000000; + uint32_t adjustSize = adjustSamples * sampleSize * channels; if (adjustSize <= sizeLeft) { af.offset += adjustSize; sizeLeft -= adjustSize; mAudioAdjust = 0; - blog(LOG_DEBUG, - "AJAOutput::DMAAudioFromQueue: Drop %d audio samples", - adjustSamples); + blog(LOG_DEBUG, "AJAOutput::DMAAudioFromQueue: Drop %d audio samples", adjustSamples); } else { - uint32_t samples = (uint32_t)sizeLeft / - (sampleSize * channels); + uint32_t samples = (uint32_t)sizeLeft / (sampleSize * channels); af.offset += sizeLeft; sizeLeft = 0; adjustSamples -= samples; - mAudioAdjust = (int64_t)adjustSamples * - 1000000 / sampleRate; - blog(LOG_DEBUG, - "AJAOutput::DMAAudioFromQueue: Drop %d audio samples", - samples); + mAudioAdjust = (int64_t)adjustSamples * 1000000 / sampleRate; + blog(LOG_DEBUG, "AJAOutput::DMAAudioFromQueue: Drop %d audio samples", samples); } } else { // Add some silence to resync audio - uint32_t adjustSamples = (uint32_t)(-mAudioAdjust) * - sampleRate / 1000000; - uint32_t adjustSize = - adjustSamples * sampleSize * channels; + uint32_t adjustSamples = (uint32_t)(-mAudioAdjust) * sampleRate / 1000000; + uint32_t adjustSize = adjustSamples * sampleSize * channels; uint8_t *silentBuffer = new uint8_t[adjustSize]; memset(silentBuffer, 0, adjustSize); - dma_audio_samples(audioSys, (uint32_t *)silentBuffer, - adjustSize); + dma_audio_samples(audioSys, (uint32_t *)silentBuffer, adjustSize); delete[] silentBuffer; mAudioAdjust = 0; - blog(LOG_DEBUG, - "AJAOutput::DMAAudioFromQueue: Add %d audio samples", - adjustSamples); + blog(LOG_DEBUG, "AJAOutput::DMAAudioFromQueue: Add %d audio samples", adjustSamples); } } // Write audio to the hardware ring if (af.frames.data[0] && sizeLeft > 0) { - dma_audio_samples(audioSys, - (uint32_t *)&af.frames.data[0][af.offset], - sizeLeft); + dma_audio_samples(audioSys, (uint32_t *)&af.frames.data[0][af.offset], sizeLeft); af.offset += sizeLeft; } @@ -453,8 +417,7 @@ void AJAOutput::DMAVideoFromQueue() mFirstVideoTS = vf.frame.timestamp; mLastVideoTS = vf.frame.timestamp; - mVideoDelay = (((int64_t)mWriteCardFrame + (int64_t)mNumCardFrames - - (int64_t)mPlayCardFrame) % + mVideoDelay = (((int64_t)mWriteCardFrame + (int64_t)mNumCardFrames - (int64_t)mPlayCardFrame) % (int64_t)mNumCardFrames) * 1000000 * mFrameRateDen / mFrameRateNum; @@ -482,12 +445,9 @@ void AJAOutput::DMAVideoFromQueue() mVideoWriteFrames++; - auto result = mCard->DMAWriteFrame( - mWriteCardFrame, reinterpret_cast(data), - (ULWord)vf.size); + auto result = mCard->DMAWriteFrame(mWriteCardFrame, reinterpret_cast(data), (ULWord)vf.size); if (!result) - blog(LOG_DEBUG, - "AJAOutput::DMAVideoFromQueue: Failed to write video frame!"); + blog(LOG_DEBUG, "AJAOutput::DMAVideoFromQueue: Failed to write video frame!"); } if (freeFrame) { @@ -499,30 +459,24 @@ void AJAOutput::DMAVideoFromQueue() // TODO(paulh): Keep track of framebuffer indices used on the card, between the capture // and output plugins, so that we can optimize frame index placement in memory and // reduce unused gaps in between channel frame indices. -void AJAOutput::calculate_card_frame_indices(uint32_t numFrames, - NTV2DeviceID id, - NTV2Channel channel, - NTV2VideoFormat vf, - NTV2PixelFormat pf) +void AJAOutput::calculate_card_frame_indices(uint32_t numFrames, NTV2DeviceID id, NTV2Channel channel, + NTV2VideoFormat vf, NTV2PixelFormat pf) { ULWord channelIndex = GetIndexForNTV2Channel(channel); - ULWord totalCardFrames = NTV2DeviceGetNumberFrameBuffers( - id, GetNTV2FrameGeometryFromVideoFormat(vf), pf); + ULWord totalCardFrames = NTV2DeviceGetNumberFrameBuffers(id, GetNTV2FrameGeometryFromVideoFormat(vf), pf); mFirstCardFrame = channelIndex * numFrames; uint32_t lastFrame = mFirstCardFrame + (numFrames - 1); - if (totalCardFrames - mFirstCardFrame > 0 && - totalCardFrames - lastFrame > 0) { + if (totalCardFrames - mFirstCardFrame > 0 && totalCardFrames - lastFrame > 0) { // Reserve N framebuffers in card DRAM. mNumCardFrames = numFrames; mWriteCardFrame = mFirstCardFrame; mLastCardFrame = lastFrame; mPlayCardFrame = mWriteCardFrame; mPlayCardNext = mPlayCardFrame + 1; - blog(LOG_INFO, "AJA Output using %d card frames (%d-%d).", - mNumCardFrames, mFirstCardFrame, mLastCardFrame); + blog(LOG_INFO, "AJA Output using %d card frames (%d-%d).", mNumCardFrames, mFirstCardFrame, + mLastCardFrame); } else { - blog(LOG_WARNING, - "AJA Output Card frames %d-%d out of bounds. %d total frames on card!", + blog(LOG_WARNING, "AJA Output Card frames %d-%d out of bounds. %d total frames on card!", mFirstCardFrame, mLastCardFrame, totalCardFrames); } } @@ -532,8 +486,8 @@ uint32_t AJAOutput::get_card_play_count() uint32_t frameCount = 0; NTV2Channel channel = mOutputProps.Channel(); INTERRUPT_ENUMS interrupt = NTV2ChannelToOutputInterrupt(channel); - bool isProgressiveTransport = NTV2_IS_PROGRESSIVE_STANDARD( - ::GetNTV2StandardFromVideoFormat(mOutputProps.videoFormat)); + bool isProgressiveTransport = + NTV2_IS_PROGRESSIVE_STANDARD(::GetNTV2StandardFromVideoFormat(mOutputProps.videoFormat)); if (isProgressiveTransport) { mCard->GetInterruptCount(interrupt, frameCount); @@ -558,24 +512,19 @@ uint32_t AJAOutput::get_card_play_count() // Perform DMA of audio samples to AJA card while taking into account wrapping around the // ends of the card's audio buffer (size set to 4MB in aja::Routing::ConfigureOutputAudio). -void AJAOutput::dma_audio_samples(NTV2AudioSystem audioSys, uint32_t *data, - size_t size) +void AJAOutput::dma_audio_samples(NTV2AudioSystem audioSys, uint32_t *data, size_t size) { bool result = false; if ((mAudioWriteCursor + size) > mAudioWrapAddress) { - const uint32_t remainingBuffer = - mAudioWrapAddress - mAudioWriteCursor; + const uint32_t remainingBuffer = mAudioWrapAddress - mAudioWriteCursor; - auto audioDataRemain = reinterpret_cast( - (uint8_t *)(data) + remainingBuffer); + auto audioDataRemain = reinterpret_cast((uint8_t *)(data) + remainingBuffer); // Incoming audio size will wrap around the end of the card audio buffer. // Transfer enough bytes to fill to the end of the buffer... if (remainingBuffer > 0) { - result = mCard->DMAWriteAudio(audioSys, data, - mAudioWriteCursor, - remainingBuffer); + result = mCard->DMAWriteAudio(audioSys, data, mAudioWriteCursor, remainingBuffer); if (result) { mAudioWriteBytes += remainingBuffer; } else { @@ -589,9 +538,7 @@ void AJAOutput::dma_audio_samples(NTV2AudioSystem audioSys, uint32_t *data, // ...transfer remaining bytes at the front of the card audio buffer. size_t frontRemaining = size - remainingBuffer; if (frontRemaining > 0) { - result = mCard->DMAWriteAudio(audioSys, audioDataRemain, - 0, - (ULWord)frontRemaining); + result = mCard->DMAWriteAudio(audioSys, audioDataRemain, 0, (ULWord)frontRemaining); if (result) { mAudioWriteBytes += frontRemaining; } else { @@ -606,9 +553,7 @@ void AJAOutput::dma_audio_samples(NTV2AudioSystem audioSys, uint32_t *data, } else { // No wrap, so just do a linear DMA from the buffer... if (size > 0) { - result = mCard->DMAWriteAudio(audioSys, data, - mAudioWriteCursor, - (ULWord)size); + result = mCard->DMAWriteAudio(audioSys, data, mAudioWriteCursor, (ULWord)size); if (result) { mAudioWriteBytes += size; } else { @@ -657,15 +602,13 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) AJAOutput *ajaOutput = static_cast(ctx); if (!ajaOutput) { - blog(LOG_ERROR, - "AJAOutput::OutputThread: AJA Output instance is null!"); + blog(LOG_ERROR, "AJAOutput::OutputThread: AJA Output instance is null!"); return; } CNTV2Card *card = ajaOutput->GetCard(); if (!card) { - blog(LOG_ERROR, - "AJAOutput::OutputThread: Card instance is null!"); + blog(LOG_ERROR, "AJAOutput::OutputThread: Card instance is null!"); return; } @@ -684,12 +627,10 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) // thread loop while (ajaOutput->ThreadRunning()) { // Wait for preroll - if (!ajaOutput->mAudioStarted && - (ajaOutput->mAudioDelay > ajaOutput->mOutputDelay)) { + if (!ajaOutput->mAudioStarted && (ajaOutput->mAudioDelay > ajaOutput->mOutputDelay)) { card->StartAudioOutput(audioSystem, false); ajaOutput->mAudioStarted = true; - blog(LOG_DEBUG, - "AJAOutput::OutputThread: Audio Preroll complete"); + blog(LOG_DEBUG, "AJAOutput::OutputThread: Audio Preroll complete"); } // Check if a vsync occurred @@ -698,22 +639,16 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) videoPlayLast = frameCount; ajaOutput->mPlayCardFrame = ajaOutput->mPlayCardNext; - if (ajaOutput->mPlayCardFrame != - ajaOutput->mWriteCardFrame) { - uint32_t playCardNext = - ajaOutput->mPlayCardFrame + 1; + if (ajaOutput->mPlayCardFrame != ajaOutput->mWriteCardFrame) { + uint32_t playCardNext = ajaOutput->mPlayCardFrame + 1; if (playCardNext > ajaOutput->mLastCardFrame) - playCardNext = - ajaOutput->mFirstCardFrame; + playCardNext = ajaOutput->mFirstCardFrame; - if (playCardNext != - ajaOutput->mWriteCardFrame) { + if (playCardNext != ajaOutput->mWriteCardFrame) { ajaOutput->mPlayCardNext = playCardNext; // Increment the play frame - ajaOutput->mCard->SetOutputFrame( - ajaOutput->mOutputProps - .Channel(), - ajaOutput->mPlayCardNext); + ajaOutput->mCard->SetOutputFrame(ajaOutput->mOutputProps.Channel(), + ajaOutput->mPlayCardNext); ajaOutput->mVideoPlayFrames++; } } @@ -721,20 +656,16 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) // Audio DMA { - const std::lock_guard lock( - ajaOutput->mAudioLock); + const std::lock_guard lock(ajaOutput->mAudioLock); while (ajaOutput->AudioQueueSize() > 0) { - ajaOutput->DMAAudioFromQueue( - audioSystem, props.audioNumChannels, - props.audioSampleRate, - props.audioSampleSize); + ajaOutput->DMAAudioFromQueue(audioSystem, props.audioNumChannels, props.audioSampleRate, + props.audioSampleSize); } } // Video DMA { - const std::lock_guard lock( - ajaOutput->mVideoLock); + const std::lock_guard lock(ajaOutput->mVideoLock); while (ajaOutput->VideoQueueSize() > 0) { ajaOutput->DMAVideoFromQueue(); } @@ -742,27 +673,20 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) // Get current time and audio play cursor int64_t curTime = (int64_t)os_gettime_ns(); - card->ReadAudioLastOut(ajaOutput->mAudioPlayCursor, - audioSystem); + card->ReadAudioLastOut(ajaOutput->mAudioPlayCursor, audioSystem); if ((curTime - ajaOutput->mLastStatTime) > kDefaultStatPeriod) { ajaOutput->mLastStatTime = curTime; if (ajaOutput->mAudioStarted) { // Calculate audio sync delay - ajaOutput->mAudioSync = ajaOutput->mAudioDelay - - ajaOutput->mOutputDelay; + ajaOutput->mAudioSync = ajaOutput->mAudioDelay - ajaOutput->mOutputDelay; - if (ajaOutput->mAudioSync > - ajaOutput->mAudioMax) { + if (ajaOutput->mAudioSync > ajaOutput->mAudioMax) { audioSyncSlowCount++; - audioSyncSlowSum += - ajaOutput->mAudioSync; - if (audioSyncSlowCount >= - audioSyncCountMax) { - ajaOutput->mAudioAdjust = - audioSyncSlowSum / - audioSyncCountMax; + audioSyncSlowSum += ajaOutput->mAudioSync; + if (audioSyncSlowCount >= audioSyncCountMax) { + ajaOutput->mAudioAdjust = audioSyncSlowSum / audioSyncCountMax; audioSyncSlowCount = 0; audioSyncSlowSum = 0; } @@ -770,16 +694,11 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) audioSyncSlowCount = 0; audioSyncSlowSum = 0; } - if (ajaOutput->mAudioSync < - -ajaOutput->mAudioMax) { + if (ajaOutput->mAudioSync < -ajaOutput->mAudioMax) { audioSyncFastCount++; - audioSyncFastSum += - ajaOutput->mAudioSync; - if (audioSyncFastCount >= - audioSyncCountMax) { - ajaOutput->mAudioAdjust = - audioSyncFastSum / - audioSyncCountMax; + audioSyncFastSum += ajaOutput->mAudioSync; + if (audioSyncFastCount >= audioSyncCountMax) { + ajaOutput->mAudioAdjust = audioSyncFastSum / audioSyncCountMax; audioSyncFastCount = 0; audioSyncFastSum = 0; } @@ -791,24 +710,19 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) // calculate video sync delay if (ajaOutput->mVideoDelay > 0) { - ajaOutput->mVideoSync = ajaOutput->mVideoDelay - - ajaOutput->mOutputDelay; + ajaOutput->mVideoSync = ajaOutput->mVideoDelay - ajaOutput->mOutputDelay; - if (ajaOutput->mVideoSync > - ajaOutput->mVideoMax) { + if (ajaOutput->mVideoSync > ajaOutput->mVideoMax) { videoSyncSlowCount++; - if (videoSyncSlowCount > - videoSyncCountMax) { + if (videoSyncSlowCount > videoSyncCountMax) { ajaOutput->mVideoAdjust = 1; } } else { videoSyncSlowCount = 0; } - if (ajaOutput->mVideoSync < - -ajaOutput->mVideoMax) { + if (ajaOutput->mVideoSync < -ajaOutput->mVideoMax) { videoSyncFastCount++; - if (videoSyncFastCount > - videoSyncCountMax) { + if (videoSyncFastCount > videoSyncCountMax) { ajaOutput->mVideoAdjust = -1; } } else { @@ -819,17 +733,13 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) #ifdef AJA_OUTPUT_STATS blog(LOG_INFO, "AJAOutput::OutputThread: od %li vd %li vs %li vm %li ad %li as %li am %li", - ajaOutput->mOutputDelay, ajaOutput->mVideoDelay, - ajaOutput->mVideoSync, ajaOutput->mVideoMax, - ajaOutput->mAudioDelay, ajaOutput->mAudioSync, - ajaOutput->mAudioMax); + ajaOutput->mOutputDelay, ajaOutput->mVideoDelay, ajaOutput->mVideoSync, + ajaOutput->mVideoMax, ajaOutput->mAudioDelay, ajaOutput->mAudioSync, ajaOutput->mAudioMax); #endif } #ifdef AJA_OUTPUT_FRAME_NUMBERS - blog(LOG_INFO, - "AJAOutput::OutputThread: dma: %d play: %d next: %d", - ajaOutput->mWriteCardFrame, ajaOutput->mPlayCardFrame, - ajaOutput->mPlayCardNext); + blog(LOG_INFO, "AJAOutput::OutputThread: dma: %d play: %d next: %d", ajaOutput->mWriteCardFrame, + ajaOutput->mPlayCardFrame, ajaOutput->mPlayCardNext); #endif os_sleep_ms(1); } @@ -840,13 +750,10 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) uint32_t audioSize = props.audioNumChannels / props.audioSampleSize; if (audioSize > 0) { blog(LOG_INFO, - "AJAOutput::OutputThread: Thread stopped\n[Video] qf: %" PRIu64 - " wf: %" PRIu64 " pf: %" PRIu64 "\n[Audio] qs: %" PRIu64 - " ws: %" PRIu64 " ps: %" PRIu64, - ajaOutput->mVideoQueueFrames, ajaOutput->mVideoWriteFrames, - ajaOutput->mVideoPlayFrames, - ajaOutput->mAudioQueueBytes / audioSize, - ajaOutput->mAudioWriteBytes / audioSize, + "AJAOutput::OutputThread: Thread stopped\n[Video] qf: %" PRIu64 " wf: %" PRIu64 " pf: %" PRIu64 + "\n[Audio] qs: %" PRIu64 " ws: %" PRIu64 " ps: %" PRIu64, + ajaOutput->mVideoQueueFrames, ajaOutput->mVideoWriteFrames, ajaOutput->mVideoPlayFrames, + ajaOutput->mAudioQueueBytes / audioSize, ajaOutput->mAudioWriteBytes / audioSize, ajaOutput->mAudioPlayBytes / audioSize); } } @@ -869,18 +776,15 @@ void populate_output_device_list(obs_property_t *list) //TODO(paulh): Add support for analog I/O // w/ NTV2DeviceGetNumAnalogVideoOutputs(cardEntry.deviceID) - if (NTV2DeviceGetNumVideoOutputs(deviceID) > 0 || - NTV2DeviceGetNumHDMIVideoOutputs(deviceID) > 0) { + if (NTV2DeviceGetNumVideoOutputs(deviceID) > 0 || NTV2DeviceGetNumHDMIVideoOutputs(deviceID) > 0) { - obs_property_list_add_string( - list, iter.second->GetDisplayName().c_str(), - iter.second->GetCardID().c_str()); + obs_property_list_add_string(list, iter.second->GetDisplayName().c_str(), + iter.second->GetCardID().c_str()); } } } -bool aja_output_device_changed(void *data, obs_properties_t *props, - obs_property_t *list, obs_data_t *settings) +bool aja_output_device_changed(void *data, obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { UNUSED_PARAMETER(data); @@ -892,35 +796,27 @@ bool aja_output_device_changed(void *data, obs_properties_t *props, if (!cardID || !cardID[0]) return false; - const char *outputID = - obs_data_get_string(settings, kUIPropAJAOutputID.id); + const char *outputID = obs_data_get_string(settings, kUIPropAJAOutputID.id); auto &cardManager = aja::CardManager::Instance(); cardManager.EnumerateCards(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_ERROR, - "aja_output_device_changed: Card Entry not found for %s", - cardID); + blog(LOG_ERROR, "aja_output_device_changed: Card Entry not found for %s", cardID); return false; } CNTV2Card *card = cardEntry->GetCard(); if (!card) { - blog(LOG_ERROR, - "aja_output_device_changed: Card instance is null!"); + blog(LOG_ERROR, "aja_output_device_changed: Card instance is null!"); return false; } - obs_property_t *io_select_list = - obs_properties_get(props, kUIPropOutput.id); - obs_property_t *vid_fmt_list = - obs_properties_get(props, kUIPropVideoFormatSelect.id); - obs_property_t *pix_fmt_list = - obs_properties_get(props, kUIPropPixelFormatSelect.id); + obs_property_t *io_select_list = obs_properties_get(props, kUIPropOutput.id); + obs_property_t *vid_fmt_list = obs_properties_get(props, kUIPropVideoFormatSelect.id); + obs_property_t *pix_fmt_list = obs_properties_get(props, kUIPropPixelFormatSelect.id); const NTV2DeviceID deviceID = cardEntry->GetDeviceID(); - populate_io_selection_output_list(cardID, outputID, deviceID, - io_select_list); + populate_io_selection_output_list(cardID, outputID, deviceID, io_select_list); // If Channel 1 is actively in use, filter the video format list to only // show video formats within the same framerate family. If Channel 1 is @@ -932,27 +828,21 @@ bool aja_output_device_changed(void *data, obs_properties_t *props, } obs_property_list_clear(vid_fmt_list); - populate_video_format_list(deviceID, vid_fmt_list, videoFormatChannel1, - false, MATCH_OBS_FRAMERATE); + populate_video_format_list(deviceID, vid_fmt_list, videoFormatChannel1, false, MATCH_OBS_FRAMERATE); obs_property_list_clear(pix_fmt_list); - populate_pixel_format_list(deviceID, - {kDefaultAJAPixelFormat, NTV2_FBF_24BIT_BGR}, - pix_fmt_list); + populate_pixel_format_list(deviceID, {kDefaultAJAPixelFormat, NTV2_FBF_24BIT_BGR}, pix_fmt_list); - IOSelection io_select = static_cast( - obs_data_get_int(settings, kUIPropOutput.id)); + IOSelection io_select = static_cast(obs_data_get_int(settings, kUIPropOutput.id)); update_sdi_transport_and_sdi_transport_4k( props, cardEntry->GetDeviceID(), io_select, - static_cast(obs_data_get_int( - settings, kUIPropVideoFormatSelect.id))); + static_cast(obs_data_get_int(settings, kUIPropVideoFormatSelect.id))); return true; } -bool aja_output_dest_changed(obs_properties_t *props, obs_property_t *list, - obs_data_t *settings) +bool aja_output_dest_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { blog(LOG_DEBUG, "AJA Output Dest Changed"); @@ -963,9 +853,7 @@ bool aja_output_dest_changed(obs_properties_t *props, obs_property_t *list, auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "aja_output_dest_changed: Card Entry not found for %s", - cardID); + blog(LOG_DEBUG, "aja_output_dest_changed: Card Entry not found for %s", cardID); return false; } @@ -986,18 +874,12 @@ bool aja_output_dest_changed(obs_properties_t *props, obs_property_t *list, } // Revert to "Select..." if desired IOSelection is already in use - auto io_select = static_cast( - obs_data_get_int(settings, kUIPropOutput.id)); + auto io_select = static_cast(obs_data_get_int(settings, kUIPropOutput.id)); for (size_t i = 0; i < obs_property_list_item_count(list); i++) { - auto io_item = static_cast( - obs_property_list_item_int(list, i)); - if (io_item == io_select && - obs_property_list_item_disabled(list, i)) { - obs_data_set_int( - settings, kUIPropOutput.id, - static_cast(IOSelection::Invalid)); - blog(LOG_WARNING, - "aja_output_dest_changed: IOSelection %s is already in use", + auto io_item = static_cast(obs_property_list_item_int(list, i)); + if (io_item == io_select && obs_property_list_item_disabled(list, i)) { + obs_data_set_int(settings, kUIPropOutput.id, static_cast(IOSelection::Invalid)); + blog(LOG_WARNING, "aja_output_dest_changed: IOSelection %s is already in use", aja::IOSelectionToString(io_select).c_str()); return false; } @@ -1005,8 +887,7 @@ bool aja_output_dest_changed(obs_properties_t *props, obs_property_t *list, update_sdi_transport_and_sdi_transport_4k( props, cardEntry->GetDeviceID(), io_select, - static_cast(obs_data_get_int( - settings, kUIPropVideoFormatSelect.id))); + static_cast(obs_data_get_int(settings, kUIPropVideoFormatSelect.id))); return true; } @@ -1043,76 +924,58 @@ static void *aja_output_create(obs_data_t *settings, obs_output_t *output) if (!cardID || !cardID[0]) return nullptr; - const char *outputID = - obs_data_get_string(settings, kUIPropAJAOutputID.id); + const char *outputID = obs_data_get_string(settings, kUIPropAJAOutputID.id); auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_ERROR, - "aja_output_create: Card Entry not found for %s", cardID); + blog(LOG_ERROR, "aja_output_create: Card Entry not found for %s", cardID); return nullptr; } CNTV2Card *card = cardEntry->GetCard(); if (!card) { - blog(LOG_ERROR, - "aja_output_create: Card instance is null for %s", cardID); + blog(LOG_ERROR, "aja_output_create: Card instance is null for %s", cardID); return nullptr; } NTV2DeviceID deviceID = card->GetDeviceID(); OutputProps outputProps(deviceID); - outputProps.ioSelect = static_cast( - obs_data_get_int(settings, kUIPropOutput.id)); - outputProps.videoFormat = static_cast( - obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); - outputProps.pixelFormat = static_cast( - obs_data_get_int(settings, kUIPropPixelFormatSelect.id)); - outputProps.sdiTransport = static_cast( - obs_data_get_int(settings, kUIPropSDITransport.id)); - outputProps.sdi4kTransport = static_cast( - obs_data_get_int(settings, kUIPropSDITransport4K.id)); + outputProps.ioSelect = static_cast(obs_data_get_int(settings, kUIPropOutput.id)); + outputProps.videoFormat = static_cast(obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); + outputProps.pixelFormat = static_cast(obs_data_get_int(settings, kUIPropPixelFormatSelect.id)); + outputProps.sdiTransport = static_cast(obs_data_get_int(settings, kUIPropSDITransport.id)); + outputProps.sdi4kTransport = static_cast(obs_data_get_int(settings, kUIPropSDITransport4K.id)); outputProps.audioNumChannels = kDefaultAudioChannels; outputProps.audioSampleSize = kDefaultAudioSampleSize; outputProps.audioSampleRate = kDefaultAudioSampleRate; if (outputProps.ioSelect == IOSelection::Invalid) { - blog(LOG_DEBUG, - "aja_output_create: Select a valid AJA Output IOSelection!"); + blog(LOG_DEBUG, "aja_output_create: Select a valid AJA Output IOSelection!"); return nullptr; } - if (outputProps.videoFormat == NTV2_FORMAT_UNKNOWN || - outputProps.pixelFormat == NTV2_FBF_INVALID) { - blog(LOG_ERROR, - "aja_output_create: Select a valid video and/or pixel format!"); + if (outputProps.videoFormat == NTV2_FORMAT_UNKNOWN || outputProps.pixelFormat == NTV2_FBF_INVALID) { + blog(LOG_ERROR, "aja_output_create: Select a valid video and/or pixel format!"); return nullptr; } - const std::string &ioSelectStr = - aja::IOSelectionToString(outputProps.ioSelect); + const std::string &ioSelectStr = aja::IOSelectionToString(outputProps.ioSelect); NTV2OutputDestinations outputDests; aja::IOSelectionToOutputDests(outputProps.ioSelect, outputDests); if (outputDests.empty()) { - blog(LOG_ERROR, - "No Output Destinations found for IOSelection %s!", - ioSelectStr.c_str()); + blog(LOG_ERROR, "No Output Destinations found for IOSelection %s!", ioSelectStr.c_str()); return nullptr; } outputProps.outputDest = *outputDests.begin(); - if (!cardEntry->AcquireOutputSelection(outputProps.ioSelect, deviceID, - outputID)) { - blog(LOG_ERROR, - "aja_output_create: Error acquiring IOSelection %s for card ID %s", - ioSelectStr.c_str(), cardID); + if (!cardEntry->AcquireOutputSelection(outputProps.ioSelect, deviceID, outputID)) { + blog(LOG_ERROR, "aja_output_create: Error acquiring IOSelection %s for card ID %s", ioSelectStr.c_str(), + cardID); return nullptr; } - auto ajaOutput = new AJAOutput(card, cardID, outputID, - (UWord)cardEntry->GetCardIndex(), - deviceID); + auto ajaOutput = new AJAOutput(card, cardID, outputID, (UWord)cardEntry->GetCardIndex(), deviceID); ajaOutput->Initialize(outputProps); ajaOutput->ClearVideoQueue(); ajaOutput->ClearAudioQueue(); @@ -1124,8 +987,7 @@ static void *aja_output_create(obs_data_t *settings, obs_output_t *output) wavFormat.channelCount = outputProps.AudioChannels(); wavFormat.sampleRate = outputProps.audioSampleRate; wavFormat.sampleSize = outputProps.AudioSize(); - ajaOutput->mWaveWriter = - new AJAWavWriter("obs_aja_output.wav", wavFormat); + ajaOutput->mWaveWriter = new AJAWavWriter("obs_aja_output.wav", wavFormat); ajaOutput->mWaveWriter->open(); #endif @@ -1156,9 +1018,7 @@ static bool aja_output_start(void *data) cardManager.EnumerateCards(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "aja_io_selection_changed: Card Entry not found for %s", - cardID.c_str()); + blog(LOG_DEBUG, "aja_io_selection_changed: Card Entry not found for %s", cardID.c_str()); return false; } @@ -1174,11 +1034,9 @@ static bool aja_output_start(void *data) auto videoFormat = outputProps.videoFormat; auto pixelFormat = outputProps.pixelFormat; - blog(LOG_INFO, - "Output Dest: %s | Audio System: %s | Video Format: %s | Pixel Format: %s", + blog(LOG_INFO, "Output Dest: %s | Audio System: %s | Video Format: %s | Pixel Format: %s", NTV2OutputDestinationToString(outputDest, true).c_str(), - NTV2AudioSystemToString(audioSystem, true).c_str(), - NTV2VideoFormatToString(videoFormat, false).c_str(), + NTV2AudioSystemToString(audioSystem, true).c_str(), NTV2VideoFormatToString(videoFormat, false).c_str(), NTV2FrameBufferFormatToString(pixelFormat, true).c_str()); const NTV2DeviceID deviceID = card->GetDeviceID(); @@ -1187,14 +1045,10 @@ static bool aja_output_start(void *data) auto numFramestores = aja::CardNumFramestores(deviceID); for (UWord i = 0; i < numFramestores; i++) { auto channel = GetNTV2ChannelForIndex(i); - if (cardEntry->ChannelReady(channel, - ajaOutput->mOutputID)) { - card->SetVideoFormat(videoFormat, false, false, - channel); - card->SetRegisterWriteMode( - NTV2_REGWRITE_SYNCTOFRAME, channel); - card->SetFrameBufferFormat(channel, - pixelFormat); + if (cardEntry->ChannelReady(channel, ajaOutput->mOutputID)) { + card->SetVideoFormat(videoFormat, false, false, channel); + card->SetRegisterWriteMode(NTV2_REGWRITE_SYNCTOFRAME, channel); + card->SetFrameBufferFormat(channel, pixelFormat); } } } @@ -1202,10 +1056,8 @@ static bool aja_output_start(void *data) // Configures crosspoint routing on AJA card ajaOutput->ClearConnections(); NTV2XptConnections xpt_cnx; - if (!aja::Routing::ConfigureOutputRoute(outputProps, NTV2_MODE_DISPLAY, - card, xpt_cnx)) { - blog(LOG_ERROR, - "aja_output_start: Error configuring output route!"); + if (!aja::Routing::ConfigureOutputRoute(outputProps, NTV2_MODE_DISPLAY, card, xpt_cnx)) { + blog(LOG_ERROR, "aja_output_start: Error configuring output route!"); return false; } ajaOutput->CacheConnections(xpt_cnx); @@ -1232,8 +1084,7 @@ static bool aja_output_start(void *data) obs_output_set_audio_conversion(ajaOutput->GetOBSOutput(), &conversion); if (!obs_output_begin_data_capture(ajaOutput->GetOBSOutput(), 0)) { - blog(LOG_ERROR, - "aja_output_start: Begin OBS data capture failed!"); + blog(LOG_ERROR, "aja_output_start: Begin OBS data capture failed!"); return false; } @@ -1258,8 +1109,7 @@ static void aja_output_stop(void *data, uint64_t ts) cardManager.EnumerateCards(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_ERROR, "aja_output_stop: Card Entry not found for %s", - cardID.c_str()); + blog(LOG_ERROR, "aja_output_stop: Card Entry not found for %s", cardID.c_str()); return; } CNTV2Card *card = ajaOutput->GetCard(); @@ -1269,18 +1119,12 @@ static void aja_output_stop(void *data, uint64_t ts) } auto outputProps = ajaOutput->GetOutputProps(); - if (!cardEntry->ReleaseOutputSelection(outputProps.ioSelect, - card->GetDeviceID(), - ajaOutput->mOutputID)) { - blog(LOG_WARNING, - "aja_output_stop: Error releasing IOSelection %s from card ID %s", - aja::IOSelectionToString(outputProps.ioSelect).c_str(), - cardID.c_str()); + if (!cardEntry->ReleaseOutputSelection(outputProps.ioSelect, card->GetDeviceID(), ajaOutput->mOutputID)) { + blog(LOG_WARNING, "aja_output_stop: Error releasing IOSelection %s from card ID %s", + aja::IOSelectionToString(outputProps.ioSelect).c_str(), cardID.c_str()); } - ajaOutput->GenerateTestPattern(outputProps.videoFormat, - outputProps.pixelFormat, - NTV2_TestPatt_Black, + ajaOutput->GenerateTestPattern(outputProps.videoFormat, outputProps.pixelFormat, NTV2_TestPatt_Black, ajaOutput->mWriteCardFrame); obs_output_end_data_capture(ajaOutput->GetOBSOutput()); @@ -1317,37 +1161,28 @@ static void aja_output_raw_audio(void *data, struct audio_data *frames) static obs_properties_t *aja_output_get_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *device_list = obs_properties_add_list( - props, kUIPropDevice.id, obs_module_text(kUIPropDevice.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_t *output_list = obs_properties_add_list( - props, kUIPropOutput.id, obs_module_text(kUIPropOutput.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_t *vid_fmt_list = obs_properties_add_list( - props, kUIPropVideoFormatSelect.id, - obs_module_text(kUIPropVideoFormatSelect.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropPixelFormatSelect.id, - obs_module_text(kUIPropPixelFormatSelect.text), + obs_property_t *device_list = obs_properties_add_list(props, kUIPropDevice.id, + obs_module_text(kUIPropDevice.text), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); + obs_property_t *output_list = obs_properties_add_list(props, kUIPropOutput.id, + obs_module_text(kUIPropOutput.text), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); + obs_property_t *vid_fmt_list = obs_properties_add_list(props, kUIPropVideoFormatSelect.id, + obs_module_text(kUIPropVideoFormatSelect.text), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, kUIPropPixelFormatSelect.id, obs_module_text(kUIPropPixelFormatSelect.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropSDITransport.id, - obs_module_text(kUIPropSDITransport.text), + obs_properties_add_list(props, kUIPropSDITransport.id, obs_module_text(kUIPropSDITransport.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropSDITransport.id, - obs_module_text(kUIPropSDITransport.text), + obs_properties_add_list(props, kUIPropSDITransport.id, obs_module_text(kUIPropSDITransport.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropSDITransport4K.id, - obs_module_text(kUIPropSDITransport4K.text), + obs_properties_add_list(props, kUIPropSDITransport4K.id, obs_module_text(kUIPropSDITransport4K.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_bool(props, kUIPropAutoStartOutput.id, - obs_module_text(kUIPropAutoStartOutput.text)); + obs_properties_add_bool(props, kUIPropAutoStartOutput.id, obs_module_text(kUIPropAutoStartOutput.text)); - obs_property_set_modified_callback(vid_fmt_list, - aja_video_format_changed); - obs_property_set_modified_callback(output_list, - aja_output_dest_changed); - obs_property_set_modified_callback2(device_list, - aja_output_device_changed, data); + obs_property_set_modified_callback(vid_fmt_list, aja_video_format_changed); + obs_property_set_modified_callback(output_list, aja_output_dest_changed); + obs_property_set_modified_callback2(device_list, aja_output_device_changed, data); return props; } @@ -1358,20 +1193,11 @@ static const char *aja_output_get_name(void *) static void aja_output_defaults(obs_data_t *settings) { - obs_data_set_default_int(settings, kUIPropOutput.id, - static_cast(IOSelection::Invalid)); - obs_data_set_default_int( - settings, kUIPropVideoFormatSelect.id, - static_cast(kDefaultAJAVideoFormat)); - obs_data_set_default_int( - settings, kUIPropPixelFormatSelect.id, - static_cast(kDefaultAJAPixelFormat)); - obs_data_set_default_int( - settings, kUIPropSDITransport.id, - static_cast(kDefaultAJASDITransport)); - obs_data_set_default_int( - settings, kUIPropSDITransport4K.id, - static_cast(kDefaultAJASDITransport4K)); + obs_data_set_default_int(settings, kUIPropOutput.id, static_cast(IOSelection::Invalid)); + obs_data_set_default_int(settings, kUIPropVideoFormatSelect.id, static_cast(kDefaultAJAVideoFormat)); + obs_data_set_default_int(settings, kUIPropPixelFormatSelect.id, static_cast(kDefaultAJAPixelFormat)); + obs_data_set_default_int(settings, kUIPropSDITransport.id, static_cast(kDefaultAJASDITransport)); + obs_data_set_default_int(settings, kUIPropSDITransport4K.id, static_cast(kDefaultAJASDITransport4K)); } void register_aja_output_info() diff --git a/plugins/aja/aja-output.hpp b/plugins/aja/aja-output.hpp index 9f50b3bc9..532e6031f 100644 --- a/plugins/aja/aja-output.hpp +++ b/plugins/aja/aja-output.hpp @@ -38,12 +38,10 @@ public: enum { // min queue sizes computed in AJAOutput kVideoQueueMaxSize = 15, - kAudioQueueMaxSize = - 96, // ~(48000 / 1024 samples per audio_frame) * 2sec + kAudioQueueMaxSize = 96, // ~(48000 / 1024 samples per audio_frame) * 2sec }; - AJAOutput(CNTV2Card *card, const std::string &cardID, - const std::string &outputID, UWord deviceIndex, + AJAOutput(CNTV2Card *card, const std::string &cardID, const std::string &outputID, UWord deviceIndex, const NTV2DeviceID deviceID); ~AJAOutput(); @@ -61,8 +59,7 @@ public: void CacheConnections(const NTV2XptConnections &cnx); void ClearConnections(); - void GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, - NTV2TestPatternSelect pattern, + void GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2TestPatternSelect pattern, uint32_t frameNum); void QueueVideoFrame(struct video_data *frame, size_t size); @@ -72,8 +69,7 @@ public: size_t VideoQueueSize(); size_t AudioQueueSize(); - void DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, - uint32_t sampleRate, uint32_t sampleSize); + void DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, uint32_t sampleRate, uint32_t sampleSize); void DMAVideoFromQueue(); void CreateThread(bool enable = false); @@ -128,13 +124,10 @@ public: private: void reset_frame_counts(); - void calculate_card_frame_indices(uint32_t numFrames, NTV2DeviceID id, - NTV2Channel channel, - NTV2VideoFormat vf, + void calculate_card_frame_indices(uint32_t numFrames, NTV2DeviceID id, NTV2Channel channel, NTV2VideoFormat vf, NTV2PixelFormat pf); uint32_t get_card_play_count(); - void dma_audio_samples(NTV2AudioSystem audioSys, uint32_t *data, - size_t size); + void dma_audio_samples(NTV2AudioSystem audioSys, uint32_t *data, size_t size); CNTV2Card *mCard; diff --git a/plugins/aja/aja-presets.cpp b/plugins/aja/aja-presets.cpp index 4010eb122..d828b48c6 100644 --- a/plugins/aja/aja-presets.cpp +++ b/plugins/aja/aja-presets.cpp @@ -11,16 +11,14 @@ RoutingConfigurator::RoutingConfigurator() build_preset_table(); } -void RoutingConfigurator::AddPreset(const std::string &name, - const RoutingPreset &preset) +void RoutingConfigurator::AddPreset(const std::string &name, const RoutingPreset &preset) { if (m_presets.find(name) != m_presets.end()) return; m_presets.insert(RoutingPresetPair{name, preset}); } -bool RoutingConfigurator::PresetByName(const std::string &name, - RoutingPreset &preset) const +bool RoutingConfigurator::PresetByName(const std::string &name, RoutingPreset &preset) const { if (m_presets.find(name) != m_presets.end()) { preset = m_presets.at(name); @@ -1789,23 +1787,17 @@ RoutingPresetMap RoutingConfigurator::GetPresetTable() const return m_presets; } -bool RoutingConfigurator::FindFirstPreset(ConnectionKind kind, NTV2DeviceID id, - NTV2Mode mode, NTV2VideoFormat vf, - NTV2PixelFormat pf, - VPIDStandard standard, - HDMIWireFormat hwf, +bool RoutingConfigurator::FindFirstPreset(ConnectionKind kind, NTV2DeviceID id, NTV2Mode mode, NTV2VideoFormat vf, + NTV2PixelFormat pf, VPIDStandard standard, HDMIWireFormat hwf, RoutingPreset &preset) { - if (NTV2DeviceCanDoVideoFormat(id, vf) && - NTV2DeviceCanDoFrameBufferFormat(id, pf)) { + if (NTV2DeviceCanDoVideoFormat(id, vf) && NTV2DeviceCanDoFrameBufferFormat(id, pf)) { const auto &rd = DetermineRasterDefinition(vf); bool is_rgb = NTV2_IS_FBF_RGB(pf); std::vector query; for (const auto &p : m_presets) { - if (p.second.kind == kind && p.second.mode == mode && - p.second.raster_def == rd && - p.second.is_rgb == is_rgb && - p.second.vpid_standard == standard && + if (p.second.kind == kind && p.second.mode == mode && p.second.raster_def == rd && + p.second.is_rgb == is_rgb && p.second.vpid_standard == standard && p.second.hdmi_wire_format == hwf) { query.push_back(p); } diff --git a/plugins/aja/aja-presets.hpp b/plugins/aja/aja-presets.hpp index 1277abdd5..a39c33c9c 100644 --- a/plugins/aja/aja-presets.hpp +++ b/plugins/aja/aja-presets.hpp @@ -36,10 +36,8 @@ public: void AddPreset(const std::string &name, const RoutingPreset &preset); bool PresetByName(const std::string &name, RoutingPreset &preset) const; RoutingPresetMap GetPresetTable() const; - bool FindFirstPreset(ConnectionKind kind, NTV2DeviceID id, - NTV2Mode mode, NTV2VideoFormat vf, - NTV2PixelFormat pf, VPIDStandard standard, - HDMIWireFormat hwf, RoutingPreset &preset); + bool FindFirstPreset(ConnectionKind kind, NTV2DeviceID id, NTV2Mode mode, NTV2VideoFormat vf, + NTV2PixelFormat pf, VPIDStandard standard, HDMIWireFormat hwf, RoutingPreset &preset); private: void build_preset_table(); diff --git a/plugins/aja/aja-props.cpp b/plugins/aja/aja-props.cpp index abea0f575..c737d17fa 100644 --- a/plugins/aja/aja-props.cpp +++ b/plugins/aja/aja-props.cpp @@ -117,15 +117,11 @@ bool SourceProps::operator==(const SourceProps &props) { return (deviceID == props.deviceID && ioSelect == props.ioSelect && // inputSource == props.inputSource && - videoFormat == props.videoFormat && - pixelFormat == props.pixelFormat && + videoFormat == props.videoFormat && pixelFormat == props.pixelFormat && // vpid == props.vpid && - autoDetect == props.autoDetect && - sdiTransport == props.sdiTransport && - sdi4kTransport == props.sdi4kTransport && - audioNumChannels == props.audioNumChannels && - audioSampleSize == props.audioSampleSize && - audioSampleRate == props.audioSampleRate && + autoDetect == props.autoDetect && sdiTransport == props.sdiTransport && + sdi4kTransport == props.sdi4kTransport && audioNumChannels == props.audioNumChannels && + audioSampleSize == props.audioSampleSize && audioSampleRate == props.audioSampleRate && deactivateWhileNotShowing == props.deactivateWhileNotShowing && swapFrontCenterLFE == props.swapFrontCenterLFE); } @@ -158,8 +154,7 @@ NTV2Channel SourceProps::Channel() const NTV2Channel SourceProps::Framestore() const { - if (deviceID == DEVICE_ID_KONAHDMI && ioSelect == IOSelection::HDMI2 && - NTV2_IS_4K_VIDEO_FORMAT(videoFormat)) { + if (deviceID == DEVICE_ID_KONAHDMI && ioSelect == IOSelection::HDMI2 && NTV2_IS_4K_VIDEO_FORMAT(videoFormat)) { return NTV2_CHANNEL3; } return Channel(); @@ -295,12 +290,9 @@ bool OutputProps::operator==(const OutputProps &props) { return (deviceID == props.deviceID && ioSelect == props.ioSelect && // outputDest == props.outputDest && - videoFormat == props.videoFormat && - pixelFormat == props.pixelFormat && - sdiTransport == props.sdiTransport && - sdi4kTransport == props.sdi4kTransport && - audioNumChannels == props.audioNumChannels && - audioSampleSize == props.audioSampleSize && + videoFormat == props.videoFormat && pixelFormat == props.pixelFormat && + sdiTransport == props.sdiTransport && sdi4kTransport == props.sdi4kTransport && + audioNumChannels == props.audioNumChannels && audioSampleSize == props.audioSampleSize && audioSampleRate == props.audioSampleRate); } @@ -320,19 +312,16 @@ NTV2Channel OutputProps::Channel() const // KONA1 -- Has 2 framestores but only 1 bi-directional SDI widget if (deviceID == DEVICE_ID_KONA1) { return NTV2_CHANNEL2; - } else if ((deviceID == DEVICE_ID_IO4K || - deviceID == DEVICE_ID_IO4KPLUS) && + } else if ((deviceID == DEVICE_ID_IO4K || deviceID == DEVICE_ID_IO4KPLUS) && outputDest == NTV2_OUTPUTDESTINATION_SDI5) { // IO4K/IO4K+ SDI Monitor - Use framestore 4 but SDI5 return NTV2_CHANNEL4; } if (NTV2_OUTPUT_DEST_IS_HDMI(outputDest)) { - if (aja::CardCanDoHDMIMonitorOutput(deviceID) && - NTV2_IS_4K_VIDEO_FORMAT(videoFormat)) + if (aja::CardCanDoHDMIMonitorOutput(deviceID) && NTV2_IS_4K_VIDEO_FORMAT(videoFormat)) return NTV2_CHANNEL3; - return static_cast( - NTV2DeviceGetNumFrameStores(deviceID) - 1); + return static_cast(NTV2DeviceGetNumFrameStores(deviceID) - 1); } return NTV2OutputDestinationToChannel(outputDest); @@ -344,8 +333,7 @@ NTV2Channel OutputProps::Framestore() const return NTV2_CHANNEL1; } else if (deviceID == DEVICE_ID_KONA1) { return NTV2_CHANNEL2; - } else if (deviceID == DEVICE_ID_IO4K || - deviceID == DEVICE_ID_IO4KPLUS) { + } else if (deviceID == DEVICE_ID_IO4K || deviceID == DEVICE_ID_IO4KPLUS) { // SDI Monitor output uses framestore 4 if (ioSelect == IOSelection::SDI5) return NTV2_CHANNEL4; diff --git a/plugins/aja/aja-routing.cpp b/plugins/aja/aja-routing.cpp index 57c5edc31..235a477d0 100644 --- a/plugins/aja/aja-routing.cpp +++ b/plugins/aja/aja-routing.cpp @@ -17,19 +17,16 @@ namespace aja { * SDI1/Datastream1 (NTV2_XptSDIIn1) to the input crosspoint for Framestore1/Datastream1 (NTV2_XptFrameBuffer1Input). * These routing shorthand strings are found within the RoutingConfig structs in the "routing" sub-directory of the plugin. */ -bool Routing::ParseRouteString(const std::string &route, - NTV2XptConnections &cnx) +bool Routing::ParseRouteString(const std::string &route, NTV2XptConnections &cnx) { - blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Input string: %s", - route.c_str()); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Input string: %s", route.c_str()); std::string route_strip(route); aja::lower(route_strip); aja::replace(route_strip, " ", ""); if (route_strip.empty()) { - blog(LOG_DEBUG, - "Routing::ParseRouteString: input string is empty!"); + blog(LOG_DEBUG, "Routing::ParseRouteString: input string is empty!"); return false; } @@ -46,82 +43,60 @@ bool Routing::ParseRouteString(const std::string &route, int32_t parse_ok = 0; for (const auto &l : lines) { if (l.empty()) { - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: Empty line!"); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Empty line!"); continue; } - blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Line: %s", - l.c_str()); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Line: %s", l.c_str()); NTV2StringList tokens = aja::split(l, "->"); if (tokens.empty() || tokens.size() != 2) { - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: Invalid token count!"); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Invalid token count!"); continue; } const std::string &left = tokens[0]; // output crosspoint const std::string &right = tokens[1]; // input crosspoint if (left.empty() || left.length() > 64) { - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: Invalid Left token!"); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Invalid Left token!"); continue; } if (right.empty() || right.length() > 64) { - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: Invalid right token!"); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Invalid right token!"); continue; } - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: Left Token: %s -> Right Token: %s", - left.c_str(), right.c_str()); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Left Token: %s -> Right Token: %s", left.c_str(), + right.c_str()); // Parse Output Crosspoint from left token int32_t out_chan = 0; int32_t out_ds = 0; std::string out_name(64, ' '); - if (std::sscanf(left.c_str(), "%[A-Za-z_0-9][%d][%d]", - &out_name[0], &out_chan, &out_ds)) { - out_name = aja::rstrip(out_name).substr( - 0, out_name.find_first_of('\0')); + if (std::sscanf(left.c_str(), "%[A-Za-z_0-9][%d][%d]", &out_name[0], &out_chan, &out_ds)) { + out_name = aja::rstrip(out_name).substr(0, out_name.find_first_of('\0')); WidgetOutputSocket widget_out; - if (WidgetOutputSocket::Find(out_name, - (NTV2Channel)out_chan, - out_ds, widget_out)) { - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: Found NTV2OutputCrosspointID %s", - NTV2OutputCrosspointIDToString( - widget_out.id) - .c_str()); + if (WidgetOutputSocket::Find(out_name, (NTV2Channel)out_chan, out_ds, widget_out)) { + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Found NTV2OutputCrosspointID %s", + NTV2OutputCrosspointIDToString(widget_out.id).c_str()); // Parse Input Crosspoint from right token int32_t inp_chan = 0; int32_t inp_ds = 0; std::string inp_name(64, ' '); - if (std::sscanf(right.c_str(), - "%[A-Za-z_0-9][%d][%d]", - &inp_name[0], &inp_chan, + if (std::sscanf(right.c_str(), "%[A-Za-z_0-9][%d][%d]", &inp_name[0], &inp_chan, &inp_ds)) { - inp_name = aja::rstrip(inp_name).substr( - 0, - inp_name.find_first_of('\0')); + inp_name = aja::rstrip(inp_name).substr(0, inp_name.find_first_of('\0')); WidgetInputSocket widget_inp; - if (WidgetInputSocket::Find( - inp_name, - (NTV2Channel)inp_chan, - inp_ds, widget_inp)) { + if (WidgetInputSocket::Find(inp_name, (NTV2Channel)inp_chan, inp_ds, + widget_inp)) { blog(LOG_DEBUG, "aja::Routing::ParseRouteString: Found NTV2InputCrosspointID %s", - NTV2InputCrosspointIDToString( - widget_inp.id) - .c_str()); + NTV2InputCrosspointIDToString(widget_inp.id).c_str()); - cnx[widget_inp.id] = - widget_out.id; + cnx[widget_inp.id] = widget_out.id; parse_ok++; } else { blog(LOG_DEBUG, @@ -129,8 +104,7 @@ bool Routing::ParseRouteString(const std::string &route, } } } else { - blog(LOG_DEBUG, - "aja::Routing::ParseRouteString: NTV2OutputCrosspointID not found!"); + blog(LOG_DEBUG, "aja::Routing::ParseRouteString: NTV2OutputCrosspointID not found!"); } } } @@ -148,9 +122,8 @@ void Routing::StartSourceAudio(const SourceProps &props, CNTV2Card *card) auto audioSys = props.AudioSystem(); card->WriteAudioSource(0, channel); - card->SetAudioSystemInputSource( - audioSys, NTV2InputSourceToAudioSource(inputSrc), - NTV2InputSourceToEmbeddedAudioInput(inputSrc)); + card->SetAudioSystemInputSource(audioSys, NTV2InputSourceToAudioSource(inputSrc), + NTV2InputSourceToEmbeddedAudioInput(inputSrc)); card->SetNumberAudioChannels(kDefaultAudioChannels, audioSys); card->SetAudioRate(props.AudioRate(), audioSys); @@ -186,10 +159,8 @@ void Routing::StartSourceAudio(const SourceProps &props, CNTV2Card *card) card->WriteAudioSource(oldValue | magicAudioBits, channel); } - for (int a = 0; a < NTV2DeviceGetNumAudioSystems(card->GetDeviceID()); - a++) { - card->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_ON, - NTV2AudioSystem(a)); + for (int a = 0; a < NTV2DeviceGetNumAudioSystems(card->GetDeviceID()); a++) { + card->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_ON, NTV2AudioSystem(a)); } card->StartAudioInput(audioSys); @@ -205,8 +176,7 @@ void Routing::StopSourceAudio(const SourceProps &props, CNTV2Card *card) } } -bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, - CNTV2Card *card, NTV2XptConnections &cnx) +bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV2Card *card, NTV2XptConnections &cnx) { if (!card) return false; @@ -229,10 +199,8 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, vpidStandard = vpidList.at(0).Standard(); } if (vpidStandard == VPIDStandard_Unknown) { - vpidStandard = DetermineVPIDStandard( - props.ioSelect, props.videoFormat, - props.pixelFormat, props.sdiTransport, - props.sdi4kTransport); + vpidStandard = DetermineVPIDStandard(props.ioSelect, props.videoFormat, props.pixelFormat, + props.sdiTransport, props.sdi4kTransport); } } else if (NTV2_INPUT_SOURCE_IS_HDMI(init_src)) { kind = ConnectionKind::HDMI; @@ -250,13 +218,12 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, } } } else { - blog(LOG_WARNING, - "Unsupported connection kind. SDI and HDMI only!"); + blog(LOG_WARNING, "Unsupported connection kind. SDI and HDMI only!"); return false; } - if (!rc.FindFirstPreset(kind, props.deviceID, NTV2_MODE_CAPTURE, vf, - props.pixelFormat, vpidStandard, hwf, rp)) { + if (!rc.FindFirstPreset(kind, props.deviceID, NTV2_MODE_CAPTURE, vf, props.pixelFormat, vpidStandard, hwf, + rp)) { blog(LOG_WARNING, "No SDI capture routing preset found!"); return false; } @@ -267,18 +234,13 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, std::string route_string = rp.route_string; // Channel-substitution for widgets associated with framestore channel(s) - ULWord start_framestore_index = - GetIndexForNTV2Channel(props.Framestore()); + ULWord start_framestore_index = GetIndexForNTV2Channel(props.Framestore()); const std::vector fs_associated = {"fb", "tsi", "dli"}; for (ULWord c = 0; c < NTV2_MAX_NUM_CHANNELS; c++) { for (const auto &name : fs_associated) { - std::string placeholder = std::string( - name + "[{ch" + aja::to_string(c + 1) + "}]"); - aja::replace( - route_string, placeholder, - name + "[" + - aja::to_string(start_framestore_index) + - "]"); + std::string placeholder = std::string(name + "[{ch" + aja::to_string(c + 1) + "}]"); + aja::replace(route_string, placeholder, + name + "[" + aja::to_string(start_framestore_index) + "]"); } start_framestore_index++; } @@ -286,10 +248,8 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, // Replace other channel placeholders ULWord start_channel_index = GetIndexForNTV2Channel(init_channel); for (ULWord c = 0; c < NTV2_MAX_NUM_CHANNELS; c++) { - std::string channel_placeholder = - std::string("{ch" + aja::to_string(c + 1) + "}"); - aja::replace(route_string, channel_placeholder, - aja::to_string(start_channel_index++)); + std::string channel_placeholder = std::string("{ch" + aja::to_string(c + 1) + "}"); + aja::replace(route_string, channel_placeholder, aja::to_string(start_channel_index++)); } if (!ParseRouteString(route_string, cnx)) @@ -299,23 +259,18 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, // Apply SDI widget settings start_channel_index = GetIndexForNTV2Channel(init_channel); - for (uint32_t i = (uint32_t)start_channel_index; - i < (start_channel_index + rp.num_channels); i++) { + for (uint32_t i = (uint32_t)start_channel_index; i < (start_channel_index + rp.num_channels); i++) { NTV2Channel channel = GetNTV2ChannelForIndex(i); if (::NTV2DeviceHasBiDirectionalSDI(deviceID)) { - card->SetSDITransmitEnable(channel, - mode == NTV2_MODE_DISPLAY); + card->SetSDITransmitEnable(channel, mode == NTV2_MODE_DISPLAY); } card->SetSDIOut3GEnable(channel, rp.flags & kEnable3GOut); card->SetSDIOut3GbEnable(channel, rp.flags & kEnable3GbOut); card->SetSDIOut6GEnable(channel, rp.flags & kEnable6GOut); card->SetSDIOut12GEnable(channel, rp.flags & kEnable12GOut); - card->SetSDIInLevelBtoLevelAConversion((UWord)i, - rp.flags & kConvert3GIn); - card->SetSDIOutLevelAtoLevelBConversion( - (UWord)i, rp.flags & kConvert3GOut); - card->SetSDIOutRGBLevelAConversion( - (UWord)i, rp.flags & kConvert3GaRGBOut); + card->SetSDIInLevelBtoLevelAConversion((UWord)i, rp.flags & kConvert3GIn); + card->SetSDIOutLevelAtoLevelBConversion((UWord)i, rp.flags & kConvert3GOut); + card->SetSDIOutRGBLevelAConversion((UWord)i, rp.flags & kConvert3GaRGBOut); } // Apply HDMI settings @@ -328,8 +283,7 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, // Apply Framestore settings start_framestore_index = GetIndexForNTV2Channel(props.Framestore()); - for (uint32_t i = (uint32_t)start_framestore_index; - i < (start_framestore_index + rp.num_framestores); i++) { + for (uint32_t i = (uint32_t)start_framestore_index; i < (start_framestore_index + rp.num_framestores); i++) { NTV2Channel channel = GetNTV2ChannelForIndex(i); card->EnableChannel(channel); card->SetMode(channel, mode); @@ -338,15 +292,13 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, card->SetFrameBufferFormat(channel, props.pixelFormat); card->SetTsiFrameEnable(rp.flags & kEnable4KTSI, channel); card->Set4kSquaresEnable(rp.flags & kEnable4KSquares, channel); - card->SetQuadQuadSquaresEnable(rp.flags & kEnable8KSquares, - channel); + card->SetQuadQuadSquaresEnable(rp.flags & kEnable8KSquares, channel); } return true; } -bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, - CNTV2Card *card, NTV2XptConnections &cnx) +bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, CNTV2Card *card, NTV2XptConnections &cnx) { if (!card) return false; @@ -355,8 +307,7 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, NTV2OutputDestinations outputDests; aja::IOSelectionToOutputDests(props.ioSelect, outputDests); if (outputDests.empty()) { - blog(LOG_DEBUG, - "No Output Destinations specified to configure routing!"); + blog(LOG_DEBUG, "No Output Destinations specified to configure routing!"); return false; } auto init_dest = *outputDests.begin(); @@ -368,9 +319,8 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, HDMIWireFormat hwf = HDMIWireFormat::Unknown; if (NTV2_OUTPUT_DEST_IS_SDI(init_dest)) { kind = ConnectionKind::SDI; - vpidStandard = DetermineVPIDStandard( - props.ioSelect, props.videoFormat, props.pixelFormat, - props.sdiTransport, props.sdi4kTransport); + vpidStandard = DetermineVPIDStandard(props.ioSelect, props.videoFormat, props.pixelFormat, + props.sdiTransport, props.sdi4kTransport); } else if (NTV2_OUTPUT_DEST_IS_HDMI(init_dest)) { kind = ConnectionKind::HDMI; hwf = HDMIWireFormat::Unknown; @@ -388,13 +338,11 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, } } } else { - blog(LOG_WARNING, - "Unsupported connection kind. SDI and HDMI only!"); + blog(LOG_WARNING, "Unsupported connection kind. SDI and HDMI only!"); return false; } - if (!rc.FindFirstPreset(kind, props.deviceID, NTV2_MODE_DISPLAY, - props.videoFormat, props.pixelFormat, + if (!rc.FindFirstPreset(kind, props.deviceID, NTV2_MODE_DISPLAY, props.videoFormat, props.pixelFormat, vpidStandard, hwf, rp)) { blog(LOG_WARNING, "No HDMI output routing preset found!"); return false; @@ -406,8 +354,7 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, // Replace framestore channel placeholders auto init_channel = NTV2OutputDestinationToChannel(init_dest); - ULWord start_framestore_index = - GetIndexForNTV2Channel(props.Framestore()); + ULWord start_framestore_index = GetIndexForNTV2Channel(props.Framestore()); if (rp.verbatim) { // Presets marked "verbatim" must only be routed on the specified channels start_framestore_index = 0; @@ -418,13 +365,9 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, const std::vector fs_associated = {"fb", "tsi", "dlo"}; for (ULWord c = 0; c < NTV2_MAX_NUM_CHANNELS; c++) { for (const auto &name : fs_associated) { - std::string placeholder = std::string( - name + "[{ch" + aja::to_string(c + 1) + "}]"); - aja::replace( - route_string, placeholder, - name + "[" + - aja::to_string(start_framestore_index) + - "]"); + std::string placeholder = std::string(name + "[{ch" + aja::to_string(c + 1) + "}]"); + aja::replace(route_string, placeholder, + name + "[" + aja::to_string(start_framestore_index) + "]"); } start_framestore_index++; } @@ -432,10 +375,8 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, // Replace other channel placeholders ULWord start_channel_index = GetIndexForNTV2Channel(init_channel); for (ULWord c = 0; c < NTV2_MAX_NUM_CHANNELS; c++) { - std::string channel_placeholder = - std::string("{ch" + aja::to_string(c + 1) + "}"); - aja::replace(route_string, channel_placeholder, - aja::to_string(start_channel_index++)); + std::string channel_placeholder = std::string("{ch" + aja::to_string(c + 1) + "}"); + aja::replace(route_string, channel_placeholder, aja::to_string(start_channel_index++)); } if (!ParseRouteString(route_string, cnx)) @@ -444,30 +385,20 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, card->ApplySignalRoute(cnx, false); // Apply SDI widget settings - if (props.ioSelect != IOSelection::HDMIMonitorOut || - props.deviceID == DEVICE_ID_TTAP_PRO) { + if (props.ioSelect != IOSelection::HDMIMonitorOut || props.deviceID == DEVICE_ID_TTAP_PRO) { start_channel_index = GetIndexForNTV2Channel(init_channel); - for (uint32_t i = (uint32_t)start_channel_index; - i < (start_channel_index + rp.num_channels); i++) { + for (uint32_t i = (uint32_t)start_channel_index; i < (start_channel_index + rp.num_channels); i++) { NTV2Channel channel = GetNTV2ChannelForIndex(i); if (::NTV2DeviceHasBiDirectionalSDI(deviceID)) { - card->SetSDITransmitEnable( - channel, mode == NTV2_MODE_DISPLAY); + card->SetSDITransmitEnable(channel, mode == NTV2_MODE_DISPLAY); } - card->SetSDIOut3GEnable(channel, - rp.flags & kEnable3GOut); - card->SetSDIOut3GbEnable(channel, - rp.flags & kEnable3GbOut); - card->SetSDIOut6GEnable(channel, - rp.flags & kEnable6GOut); - card->SetSDIOut12GEnable(channel, - rp.flags & kEnable12GOut); - card->SetSDIInLevelBtoLevelAConversion( - (UWord)i, rp.flags & kConvert3GIn); - card->SetSDIOutLevelAtoLevelBConversion( - (UWord)i, rp.flags & kConvert3GOut); - card->SetSDIOutRGBLevelAConversion( - (UWord)i, rp.flags & kConvert3GaRGBOut); + card->SetSDIOut3GEnable(channel, rp.flags & kEnable3GOut); + card->SetSDIOut3GbEnable(channel, rp.flags & kEnable3GbOut); + card->SetSDIOut6GEnable(channel, rp.flags & kEnable6GOut); + card->SetSDIOut12GEnable(channel, rp.flags & kEnable12GOut); + card->SetSDIInLevelBtoLevelAConversion((UWord)i, rp.flags & kConvert3GIn); + card->SetSDIOutLevelAtoLevelBConversion((UWord)i, rp.flags & kConvert3GOut); + card->SetSDIOutRGBLevelAConversion((UWord)i, rp.flags & kConvert3GaRGBOut); } } @@ -476,8 +407,7 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, if (rp.verbatim) { start_framestore_index = 0; } - for (uint32_t i = (uint32_t)start_framestore_index; - i < (start_framestore_index + rp.num_framestores); i++) { + for (uint32_t i = (uint32_t)start_framestore_index; i < (start_framestore_index + rp.num_framestores); i++) { NTV2Channel channel = GetNTV2ChannelForIndex(i); card->EnableChannel(channel); card->SetMode(channel, mode); @@ -486,8 +416,7 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, card->SetFrameBufferFormat(channel, props.pixelFormat); card->SetTsiFrameEnable(rp.flags & kEnable4KTSI, channel); card->Set4kSquaresEnable(rp.flags & kEnable4KSquares, channel); - card->SetQuadQuadSquaresEnable(rp.flags & kEnable8KSquares, - channel); + card->SetQuadQuadSquaresEnable(rp.flags & kEnable8KSquares, channel); } return true; @@ -522,9 +451,8 @@ void Routing::ConfigureOutputAudio(const OutputProps &props, CNTV2Card *card) * * This fixes AJA internal bugs: 10730, 10986, 16274 */ - if (deviceID == DEVICE_ID_IOXT || deviceID == DEVICE_ID_IO4KUFC || - deviceID == DEVICE_ID_IO4KPLUS || deviceID == DEVICE_ID_KONA1 || - deviceID == DEVICE_ID_KONA3G || deviceID == DEVICE_ID_KONA4UFC || + if (deviceID == DEVICE_ID_IOXT || deviceID == DEVICE_ID_IO4KUFC || deviceID == DEVICE_ID_IO4KPLUS || + deviceID == DEVICE_ID_KONA1 || deviceID == DEVICE_ID_KONA3G || deviceID == DEVICE_ID_KONA4UFC || deviceID == DEVICE_ID_KONA5 || deviceID == DEVICE_ID_KONA5_2X4K) { // Make sure SDI out 1 (aka Channel 1) is set to the correct sub-system card->SetSDIOutputAudioSystem(NTV2_CHANNEL1, audioSys); @@ -541,35 +469,23 @@ void Routing::ConfigureOutputAudio(const OutputProps &props, CNTV2Card *card) card->SetHDMIOutAudioFormat(NTV2_AUDIO_FORMAT_LPCM); card->SetAudioOutputMonitorSource(NTV2_AudioChannel1_2, channel); - card->SetAESOutputSource(NTV2_AudioChannel1_4, audioSys, - NTV2_AudioChannel1_4); - card->SetAESOutputSource(NTV2_AudioChannel5_8, audioSys, - NTV2_AudioChannel5_8); - card->SetAESOutputSource(NTV2_AudioChannel9_12, audioSys, - NTV2_AudioChannel9_12); - card->SetAESOutputSource(NTV2_AudioChannel13_16, audioSys, - NTV2_AudioChannel13_16); + card->SetAESOutputSource(NTV2_AudioChannel1_4, audioSys, NTV2_AudioChannel1_4); + card->SetAESOutputSource(NTV2_AudioChannel5_8, audioSys, NTV2_AudioChannel5_8); + card->SetAESOutputSource(NTV2_AudioChannel9_12, audioSys, NTV2_AudioChannel9_12); + card->SetAESOutputSource(NTV2_AudioChannel13_16, audioSys, NTV2_AudioChannel13_16); // make sure that audio is setup for HDMI output on devices that support it if (NTV2DeviceGetNumHDMIVideoOutputs(deviceID) > 0) { if (NTV2DeviceCanDoAudioMixer(deviceID)) { - card->SetAudioMixerInputAudioSystem( - NTV2_AudioMixerInputMain, audioSys); - card->SetAudioMixerInputChannelSelect( - NTV2_AudioMixerInputMain, NTV2_AudioChannel1_2); - card->SetAudioMixerInputChannelsMute( - NTV2_AudioMixerInputAux1, - NTV2AudioChannelsMuteAll); - card->SetAudioMixerInputChannelsMute( - NTV2_AudioMixerInputAux2, - NTV2AudioChannelsMuteAll); + card->SetAudioMixerInputAudioSystem(NTV2_AudioMixerInputMain, audioSys); + card->SetAudioMixerInputChannelSelect(NTV2_AudioMixerInputMain, NTV2_AudioChannel1_2); + card->SetAudioMixerInputChannelsMute(NTV2_AudioMixerInputAux1, NTV2AudioChannelsMuteAll); + card->SetAudioMixerInputChannelsMute(NTV2_AudioMixerInputAux2, NTV2AudioChannelsMuteAll); } card->SetHDMIOutAudioChannels(NTV2_HDMIAudio8Channels); - card->SetHDMIOutAudioSource2Channel(NTV2_AudioChannel1_2, - audioSys); - card->SetHDMIOutAudioSource8Channel(NTV2_AudioChannel1_8, - audioSys); + card->SetHDMIOutAudioSource2Channel(NTV2_AudioChannel1_2, audioSys); + card->SetHDMIOutAudioSource8Channel(NTV2_AudioChannel1_8, audioSys); } card->SetAudioLoopBack(NTV2_AUDIO_LOOPBACK_OFF, audioSys); @@ -581,19 +497,16 @@ void Routing::LogRoutingPreset(const RoutingPreset &rp) { auto hexStr = [&](uint8_t val) -> std::string { std::stringstream ss; - ss << std::setfill('0') << std::setw(sizeof(uint8_t) * 2) - << std::hex << (val | 0); + ss << std::setfill('0') << std::setw(sizeof(uint8_t) * 2) << std::hex << (val | 0); return ss.str(); }; std::stringstream ss; ss << "\nPreset: " << rp.name; if (rp.kind == ConnectionKind::SDI) { - ss << "\nVPID Standard: 0x" - << hexStr(static_cast(rp.vpid_standard)); + ss << "\nVPID Standard: 0x" << hexStr(static_cast(rp.vpid_standard)); } - ss << "\nMode: " << NTV2ModeToString(rp.mode) - << "\nChannels: " << rp.num_channels + ss << "\nMode: " << NTV2ModeToString(rp.mode) << "\nChannels: " << rp.num_channels << "\nFramestores: " << rp.num_framestores; blog(LOG_INFO, "[ AJA Crosspoint Routing Preset ]%s", ss.str().c_str()); @@ -603,8 +516,7 @@ void Routing::LogRoutingPreset(const RoutingPreset &rp) for (auto id : rp.device_ids) { ss << " - " << NTV2DeviceIDToString(id) << "\n"; } - blog(LOG_INFO, "\nCompatible Device IDs: \n%s", - ss.str().c_str()); + blog(LOG_INFO, "\nCompatible Device IDs: \n%s", ss.str().c_str()); } } diff --git a/plugins/aja/aja-routing.hpp b/plugins/aja/aja-routing.hpp index 6f452a7aa..a5d155ac8 100644 --- a/plugins/aja/aja-routing.hpp +++ b/plugins/aja/aja-routing.hpp @@ -25,40 +25,35 @@ namespace aja { */ struct RoutingConfig { - NTV2Mode mode; // capture or playout? - uint32_t num_wires; // number of physical connections - uint32_t num_framestores; // number of framestores used - bool enable_3g_out; // enable register for 3G SDI Output? - bool enable_6g_out; // enable register for 6G SDI Output? - bool enable_12g_out; // enable register for 12G SDI Output? - bool convert_3g_in; // enable register for 3G level-B -> level-A SDI input conversion? - bool convert_3g_out; // enable register for 3G level-A -> level-B SDI output conversion? + NTV2Mode mode; // capture or playout? + uint32_t num_wires; // number of physical connections + uint32_t num_framestores; // number of framestores used + bool enable_3g_out; // enable register for 3G SDI Output? + bool enable_6g_out; // enable register for 6G SDI Output? + bool enable_12g_out; // enable register for 12G SDI Output? + bool convert_3g_in; // enable register for 3G level-B -> level-A SDI input conversion? + bool convert_3g_out; // enable register for 3G level-A -> level-B SDI output conversion? bool enable_rgb_3ga_convert; // enable register for RGB 3G level-B -> level-A SDI output conversion? - bool enable_3gb_out; // enable register for 3G level-B SDI output? - bool enable_4k_squares; // enable register for 4K square division? - bool enable_8k_squares; // enable register for 8K square division? - bool enable_tsi; // enable register for two-sample interleave (UHD/4K/8K) - std::string - route_string; // signal routing shorthand string to parse into crosspoint connections + bool enable_3gb_out; // enable register for 3G level-B SDI output? + bool enable_4k_squares; // enable register for 4K square division? + bool enable_8k_squares; // enable register for 8K square division? + bool enable_tsi; // enable register for two-sample interleave (UHD/4K/8K) + std::string route_string; // signal routing shorthand string to parse into crosspoint connections }; // Applies RoutingConfig settings to the card to configure a specific SDI/HDMI capture/output mode. class Routing { public: - static bool ParseRouteString(const std::string &route, - NTV2XptConnections &cnx); + static bool ParseRouteString(const std::string &route, NTV2XptConnections &cnx); static void StartSourceAudio(const SourceProps &props, CNTV2Card *card); static void StopSourceAudio(const SourceProps &props, CNTV2Card *card); - static bool ConfigureSourceRoute(const SourceProps &props, - NTV2Mode mode, CNTV2Card *card, + static bool ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV2Card *card, NTV2XptConnections &cnx); - static bool ConfigureOutputRoute(const OutputProps &props, - NTV2Mode mode, CNTV2Card *card, + static bool ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, CNTV2Card *card, NTV2XptConnections &cnx); - static void ConfigureOutputAudio(const OutputProps &props, - CNTV2Card *card); + static void ConfigureOutputAudio(const OutputProps &props, CNTV2Card *card); static void LogRoutingPreset(const RoutingPreset &rp); }; diff --git a/plugins/aja/aja-source.cpp b/plugins/aja/aja-source.cpp index 25a40c29c..2b83f00cd 100644 --- a/plugins/aja/aja-source.cpp +++ b/plugins/aja/aja-source.cpp @@ -20,8 +20,7 @@ static constexpr int kDefaultAudioCaptureChannels = 2; -static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format, - bool swap = false) +static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format, bool swap = false) { switch (format) { case SPEAKERS_STEREO: @@ -114,9 +113,8 @@ void populate_source_device_list(obs_property_t *list) if (aja::IsOutputOnlyDevice(iter.second->GetDeviceID())) continue; - obs_property_list_add_string( - list, iter.second->GetDisplayName().c_str(), - iter.second->GetCardID().c_str()); + obs_property_list_add_string(list, iter.second->GetDisplayName().c_str(), + iter.second->GetCardID().c_str()); } } } @@ -133,9 +131,7 @@ struct AudioOffsets { ULWord bytesRead = 0; }; -static void ResetAudioBufferOffsets(CNTV2Card *card, - NTV2AudioSystem audioSystem, - AudioOffsets &offsets) +static void ResetAudioBufferOffsets(CNTV2Card *card, NTV2AudioSystem audioSystem, AudioOffsets &offsets) { if (!card) return; @@ -151,8 +147,7 @@ static void ResetAudioBufferOffsets(CNTV2Card *card, offsets.lastAddress = offsets.readOffset; } -void AJASource::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, - NTV2TestPatternSelect ps) +void AJASource::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2TestPatternSelect ps) { NTV2VideoFormat vid_fmt = vf; NTV2PixelFormat pix_fmt = pf; @@ -167,18 +162,14 @@ void AJASource::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, mTestPattern.clear(); mTestPattern.resize(bufSize); NTV2TestPatternGen gen; - gen.DrawTestPattern(ps, fd.GetRasterWidth(), - fd.GetRasterHeight(), pix_fmt, - mTestPattern); + gen.DrawTestPattern(ps, fd.GetRasterWidth(), fd.GetRasterHeight(), pix_fmt, mTestPattern); } if (mTestPattern.size() == 0) { - blog(LOG_DEBUG, - "AJASource::GenerateTestPattern: Error generating test pattern!"); + blog(LOG_DEBUG, "AJASource::GenerateTestPattern: Error generating test pattern!"); return; } - const enum video_format obs_vid_fmt = - aja::AJAPixelFormatToOBSVideoFormat(pix_fmt); + const enum video_format obs_vid_fmt = aja::AJAPixelFormatToOBSVideoFormat(pix_fmt); struct obs_source_frame2 obsFrame; obsFrame.flip = false; @@ -191,11 +182,8 @@ void AJASource::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, video_colorspace colorspace = VIDEO_CS_709; if (NTV2_IS_SD_VIDEO_FORMAT(vid_fmt)) colorspace = VIDEO_CS_601; - video_format_get_parameters_for_format(colorspace, VIDEO_RANGE_PARTIAL, - obs_vid_fmt, - obsFrame.color_matrix, - obsFrame.color_range_min, - obsFrame.color_range_max); + video_format_get_parameters_for_format(colorspace, VIDEO_RANGE_PARTIAL, obs_vid_fmt, obsFrame.color_matrix, + obsFrame.color_range_min, obsFrame.color_range_max); obs_source_output_video2(mSource, &obsFrame); blog(LOG_DEBUG, "AJASource::GenerateTestPattern: Black"); } @@ -210,15 +198,11 @@ static inline uint64_t get_sample_time(size_t frames, uint_fast32_t rate) return os_gettime_ns() - samples_to_ns(frames, rate); } -static bool CheckTransferAudioDMA(CNTV2Card *card, - const NTV2AudioSystem audioSystem, - void *buffer, ULWord bufferSize, - ULWord dmaOffset, ULWord dmaSize, - const char *log_id) +static bool CheckTransferAudioDMA(CNTV2Card *card, const NTV2AudioSystem audioSystem, void *buffer, ULWord bufferSize, + ULWord dmaOffset, ULWord dmaSize, const char *log_id) { if (dmaSize > bufferSize) { - blog(LOG_DEBUG, - "AJASource::CaptureThread: Audio overrun %s! Buffer Size: %u, Bytes Captured: %u", + blog(LOG_DEBUG, "AJASource::CaptureThread: Audio overrun %s! Buffer Size: %u, Bytes Captured: %u", log_id, bufferSize, dmaSize); return false; } @@ -227,9 +211,7 @@ static bool CheckTransferAudioDMA(CNTV2Card *card, return true; } -static inline bool TransferAudio(CNTV2Card *card, - const NTV2AudioSystem audioSystem, - NTV2_POINTER &audioBuffer, +static inline bool TransferAudio(CNTV2Card *card, const NTV2AudioSystem audioSystem, NTV2_POINTER &audioBuffer, AudioOffsets &offsets) { card->ReadAudioLastIn(offsets.currentAddress, audioSystem); @@ -239,29 +221,20 @@ static inline bool TransferAudio(CNTV2Card *card, if (offsets.currentAddress < offsets.lastAddress) { offsets.bytesRead = offsets.wrapAddress - offsets.lastAddress; - if (!CheckTransferAudioDMA(card, audioSystem, audioBuffer, - audioBuffer.GetByteCount(), - offsets.lastAddress, - offsets.bytesRead, "(1)")) + if (!CheckTransferAudioDMA(card, audioSystem, audioBuffer, audioBuffer.GetByteCount(), + offsets.lastAddress, offsets.bytesRead, "(1)")) return false; - if (!CheckTransferAudioDMA( - card, audioSystem, - audioBuffer.GetHostAddress(offsets.bytesRead), - audioBuffer.GetByteCount() - offsets.bytesRead, - offsets.readOffset, - offsets.currentAddress - offsets.readOffset, "(2)")) + if (!CheckTransferAudioDMA(card, audioSystem, audioBuffer.GetHostAddress(offsets.bytesRead), + audioBuffer.GetByteCount() - offsets.bytesRead, offsets.readOffset, + offsets.currentAddress - offsets.readOffset, "(2)")) return false; - offsets.bytesRead += - offsets.currentAddress - offsets.readOffset; + offsets.bytesRead += offsets.currentAddress - offsets.readOffset; } else { - offsets.bytesRead = - offsets.currentAddress - offsets.lastAddress; - if (!CheckTransferAudioDMA(card, audioSystem, audioBuffer, - audioBuffer.GetByteCount(), - offsets.lastAddress, - offsets.bytesRead, "(3)")) + offsets.bytesRead = offsets.currentAddress - offsets.lastAddress; + if (!CheckTransferAudioDMA(card, audioSystem, audioBuffer, audioBuffer.GetByteCount(), + offsets.lastAddress, offsets.bytesRead, "(3)")) return false; } @@ -274,25 +247,21 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) auto ajaSource = (AJASource *)data; if (!ajaSource) { - blog(LOG_WARNING, - "AJASource::CaptureThread: Plugin instance is null!"); + blog(LOG_WARNING, "AJASource::CaptureThread: Plugin instance is null!"); return; } - blog(LOG_INFO, - "AJASource::CaptureThread: Starting capture thread for AJA source %s", + blog(LOG_INFO, "AJASource::CaptureThread: Starting capture thread for AJA source %s", ajaSource->GetName().c_str()); auto card = ajaSource->GetCard(); if (!card) { - blog(LOG_ERROR, - "AJASource::CaptureThread: Card instance is null!"); + blog(LOG_ERROR, "AJASource::CaptureThread: Card instance is null!"); return; } auto sourceProps = ajaSource->GetSourceProps(); - ajaSource->ResetVideoBuffer(sourceProps.videoFormat, - sourceProps.pixelFormat); + ajaSource->ResetVideoBuffer(sourceProps.videoFormat, sourceProps.pixelFormat); auto inputSource = sourceProps.InitialInputSource(); auto channel = sourceProps.Channel(); auto framestore = sourceProps.Framestore(); @@ -316,10 +285,9 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) obs_data_t *settings = obs_source_get_settings(ajaSource->mSource); - AudioRepacker *audioRepacker = new AudioRepacker( - ConvertRepackFormat(sourceProps.SpeakerLayout(), - sourceProps.swapFrontCenterLFE), - sourceProps.audioSampleSize * 8); + AudioRepacker *audioRepacker = + new AudioRepacker(ConvertRepackFormat(sourceProps.SpeakerLayout(), sourceProps.swapFrontCenterLFE), + sourceProps.audioSampleSize * 8); while (ajaSource->IsCapturing()) { if (card->GetModelName() == "(Not Found)") { @@ -336,88 +304,65 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) currentCardFrame ^= 1; // Card format detection -- restarts capture thread via aja_source_update callback - auto newVideoFormat = card->GetInputVideoFormat( - inputSource, aja::Is3GLevelB(card, channel)); + auto newVideoFormat = card->GetInputVideoFormat(inputSource, aja::Is3GLevelB(card, channel)); if (newVideoFormat == NTV2_FORMAT_UNKNOWN) { - blog(LOG_DEBUG, - "AJASource::CaptureThread: Video format unknown!"); - ajaSource->GenerateTestPattern(videoFormat, pixelFormat, - NTV2_TestPatt_Black); + blog(LOG_DEBUG, "AJASource::CaptureThread: Video format unknown!"); + ajaSource->GenerateTestPattern(videoFormat, pixelFormat, NTV2_TestPatt_Black); os_sleep_ms(250); continue; } - newVideoFormat = aja::HandleSpecialCaseFormats( - ioSelection, newVideoFormat, sourceProps.deviceID); + newVideoFormat = aja::HandleSpecialCaseFormats(ioSelection, newVideoFormat, sourceProps.deviceID); if (sourceProps.autoDetect && (videoFormat != newVideoFormat)) { blog(LOG_INFO, "AJASource::CaptureThread: New Video Format detected! Triggering 'aja_source_update' callback and returning..."); - blog(LOG_INFO, - "AJASource::CaptureThread: Current Video Format: %s, | Want Video Format: %s", + blog(LOG_INFO, "AJASource::CaptureThread: Current Video Format: %s, | Want Video Format: %s", NTV2VideoFormatToString(videoFormat, true).c_str(), - NTV2VideoFormatToString(newVideoFormat, true) - .c_str()); + NTV2VideoFormatToString(newVideoFormat, true).c_str()); os_sleep_ms(250); obs_source_update(ajaSource->mSource, settings); break; } - if (!TransferAudio(card, audioSystem, ajaSource->mAudioBuffer, - offsets)) { + if (!TransferAudio(card, audioSystem, ajaSource->mAudioBuffer, offsets)) { ResetAudioBufferOffsets(card, audioSystem, offsets); } else { offsets.lastAddress = offsets.currentAddress; - uint32_t sampleCount = offsets.bytesRead / - (kDefaultAudioChannels * - sourceProps.audioSampleSize); + uint32_t sampleCount = + offsets.bytesRead / (kDefaultAudioChannels * sourceProps.audioSampleSize); obs_source_audio audioPacket; - audioPacket.samples_per_sec = - sourceProps.audioSampleRate; + audioPacket.samples_per_sec = sourceProps.audioSampleRate; audioPacket.format = sourceProps.AudioFormat(); audioPacket.speakers = sourceProps.SpeakerLayout(); audioPacket.frames = sampleCount; - audioPacket.timestamp = - get_sample_time(audioPacket.frames, - sourceProps.audioSampleRate); - uint8_t *hostAudioBuffer = - (uint8_t *)ajaSource->mAudioBuffer - .GetHostPointer(); - if (sourceProps.audioNumChannels >= 2 && - sourceProps.audioNumChannels <= 6) { + audioPacket.timestamp = get_sample_time(audioPacket.frames, sourceProps.audioSampleRate); + uint8_t *hostAudioBuffer = (uint8_t *)ajaSource->mAudioBuffer.GetHostPointer(); + if (sourceProps.audioNumChannels >= 2 && sourceProps.audioNumChannels <= 6) { /* Repack 8ch audio to fit specified OBS speaker layout */ - audioRepacker->repack(hostAudioBuffer, - sampleCount); - audioPacket.data[0] = - (*audioRepacker)->packet_buffer; + audioRepacker->repack(hostAudioBuffer, sampleCount); + audioPacket.data[0] = (*audioRepacker)->packet_buffer; } else { /* Silence, or pass-through 8ch of audio */ if (sourceProps.audioNumChannels == 0) - memset(hostAudioBuffer, 0, - offsets.bytesRead); + memset(hostAudioBuffer, 0, offsets.bytesRead); audioPacket.data[0] = hostAudioBuffer; } - obs_source_output_audio(ajaSource->mSource, - &audioPacket); + obs_source_output_audio(ajaSource->mSource, &audioPacket); } if (ajaSource->mVideoBuffer.GetByteCount() == 0) { - blog(LOG_DEBUG, - "AJASource::CaptureThread: 0 bytes in video buffer! Something went wrong!"); + blog(LOG_DEBUG, "AJASource::CaptureThread: 0 bytes in video buffer! Something went wrong!"); continue; } - card->DMAReadFrame(currentCardFrame, ajaSource->mVideoBuffer, - ajaSource->mVideoBuffer.GetByteCount()); + card->DMAReadFrame(currentCardFrame, ajaSource->mVideoBuffer, ajaSource->mVideoBuffer.GetByteCount()); auto actualVideoFormat = videoFormat; if (aja::Is3GLevelB(card, channel)) - actualVideoFormat = aja::GetLevelAFormatForLevelBFormat( - videoFormat); + actualVideoFormat = aja::GetLevelAFormatForLevelBFormat(videoFormat); - const enum video_format obs_vid_fmt = - aja::AJAPixelFormatToOBSVideoFormat( - sourceProps.pixelFormat); + const enum video_format obs_vid_fmt = aja::AJAPixelFormatToOBSVideoFormat(sourceProps.pixelFormat); NTV2FormatDesc fd(actualVideoFormat, pixelFormat); struct obs_source_frame2 obsFrame; @@ -426,16 +371,14 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) obsFrame.width = fd.GetRasterWidth(); obsFrame.height = fd.GetRasterHeight(); obsFrame.format = obs_vid_fmt; - obsFrame.data[0] = reinterpret_cast( - (ULWord *)ajaSource->mVideoBuffer.GetHostPointer()); + obsFrame.data[0] = reinterpret_cast((ULWord *)ajaSource->mVideoBuffer.GetHostPointer()); obsFrame.linesize[0] = fd.GetBytesPerRow(); video_colorspace colorspace = VIDEO_CS_709; if (NTV2_IS_SD_VIDEO_FORMAT(actualVideoFormat)) colorspace = VIDEO_CS_601; - video_format_get_parameters_for_format( - colorspace, VIDEO_RANGE_PARTIAL, obs_vid_fmt, - obsFrame.color_matrix, obsFrame.color_range_min, - obsFrame.color_range_max); + video_format_get_parameters_for_format(colorspace, VIDEO_RANGE_PARTIAL, obs_vid_fmt, + obsFrame.color_matrix, obsFrame.color_range_min, + obsFrame.color_range_max); obs_source_output_video2(ajaSource->mSource, &obsFrame); @@ -447,9 +390,7 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) delete audioRepacker; audioRepacker = nullptr; } - ajaSource->GenerateTestPattern(sourceProps.videoFormat, - sourceProps.pixelFormat, - NTV2_TestPatt_Black); + ajaSource->GenerateTestPattern(sourceProps.videoFormat, sourceProps.pixelFormat, NTV2_TestPatt_Black); obs_data_release(settings); } @@ -556,15 +497,13 @@ bool AJASource::ReadChannelVPIDs(NTV2Channel channel, VPIDData &vpids) return read_ok; } -bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, - NTV2VideoFormat &vf, NTV2PixelFormat &pf, +bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, NTV2VideoFormat &vf, NTV2PixelFormat &pf, VPIDDataList &vpids) { NTV2InputSourceSet input_srcs; aja::IOSelectionToInputSources(io_select, input_srcs); if (input_srcs.empty()) { - blog(LOG_INFO, - "AJASource::ReadWireFormats: No NTV2InputSources found for IOSelection %s", + blog(LOG_INFO, "AJASource::ReadWireFormats: No NTV2InputSources found for IOSelection %s", aja::IOSelectionToString(io_select).c_str()); return false; } @@ -584,20 +523,16 @@ bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, } else if (NTV2_INPUT_SOURCE_IS_HDMI(src)) { mCard->WaitForInputVerticalInterrupt(channel); - ULWord hdmi_version = - NTV2DeviceGetHDMIVersion(device_id); + ULWord hdmi_version = NTV2DeviceGetHDMIVersion(device_id); // HDMIv1 handles its own RGB->YCbCr color space conversion if (hdmi_version == 1) { pf = kDefaultAJAPixelFormat; } else { NTV2LHIHDMIColorSpace hdmiInputColor; - mCard->GetHDMIInputColor(hdmiInputColor, - channel); - if (hdmiInputColor == - NTV2_LHIHDMIColorSpaceYCbCr) { + mCard->GetHDMIInputColor(hdmiInputColor, channel); + if (hdmiInputColor == NTV2_LHIHDMIColorSpaceYCbCr) { pf = kDefaultAJAPixelFormat; - } else if (hdmiInputColor == - NTV2_LHIHDMIColorSpaceRGB) { + } else if (hdmiInputColor == NTV2_LHIHDMIColorSpaceRGB) { pf = NTV2_FBF_24BIT_BGR; } } @@ -607,8 +542,7 @@ bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, NTV2Channel initial_channel = NTV2InputSourceToChannel(initial_src); mCard->WaitForInputVerticalInterrupt(initial_channel); - vf = mCard->GetInputVideoFormat( - initial_src, aja::Is3GLevelB(mCard, initial_channel)); + vf = mCard->GetInputVideoFormat(initial_src, aja::Is3GLevelB(mCard, initial_channel)); if (NTV2_INPUT_SOURCE_IS_SDI(initial_src)) { if (vpids.size() > 0) { @@ -618,24 +552,19 @@ bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, pf = NTV2_FBF_8BIT_YCBCR; else if (vpid.BitDepth() == VPIDBitDepth_10) pf = NTV2_FBF_10BIT_YCBCR; - blog(LOG_INFO, - "AJASource::ReadWireFormats - Detected pixel format %s", - NTV2FrameBufferFormatToString(pf, true) - .c_str()); + blog(LOG_INFO, "AJASource::ReadWireFormats - Detected pixel format %s", + NTV2FrameBufferFormatToString(pf, true).c_str()); } else if (vpid.Sampling() == VPIDSampling_GBR_444) { pf = NTV2_FBF_24BIT_BGR; - blog(LOG_INFO, - "AJASource::ReadWireFormats - Detected pixel format %s", - NTV2FrameBufferFormatToString(pf, true) - .c_str()); + blog(LOG_INFO, "AJASource::ReadWireFormats - Detected pixel format %s", + NTV2FrameBufferFormatToString(pf, true).c_str()); } } } vf = aja::HandleSpecialCaseFormats(io_select, vf, device_id); - blog(LOG_INFO, "AJASource::ReadWireFormats - Detected video format %s", - NTV2VideoFormatToString(vf).c_str()); + blog(LOG_INFO, "AJASource::ReadWireFormats - Detected video format %s", NTV2VideoFormatToString(vf).c_str()); return true; } @@ -650,10 +579,8 @@ void AJASource::ResetVideoBuffer(NTV2VideoFormat vf, NTV2PixelFormat pf) mVideoBuffer.Allocate(videoBufferSize, true); - blog(LOG_INFO, - "AJASource::ResetVideoBuffer: Video Format: %s | Pixel Format: %s | Buffer Size: %d", - NTV2VideoFormatToString(vf, false).c_str(), - NTV2FrameBufferFormatToString(pf, true).c_str(), + blog(LOG_INFO, "AJASource::ResetVideoBuffer: Video Format: %s | Pixel Format: %s | Buffer Size: %d", + NTV2VideoFormatToString(vf, false).c_str(), NTV2FrameBufferFormatToString(pf, true).c_str(), videoBufferSize); } } @@ -678,8 +605,7 @@ const char *aja_source_get_name(void *unused) return obs_module_text(kUIPropCaptureModule.text); } -bool aja_source_device_changed(void *data, obs_properties_t *props, - obs_property_t *list, obs_data_t *settings) +bool aja_source_device_changed(void *data, obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { UNUSED_PARAMETER(list); @@ -687,8 +613,7 @@ bool aja_source_device_changed(void *data, obs_properties_t *props, auto *ajaSource = (AJASource *)data; if (!ajaSource) { - blog(LOG_DEBUG, - "aja_source_device_changed: AJA Source instance is null!"); + blog(LOG_DEBUG, "aja_source_device_changed: AJA Source instance is null!"); return false; } @@ -699,16 +624,13 @@ bool aja_source_device_changed(void *data, obs_properties_t *props, auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "aja_source_device_changed: Card Entry not found for %s", - cardID); + blog(LOG_DEBUG, "aja_source_device_changed: Card Entry not found for %s", cardID); return false; } blog(LOG_DEBUG, "Found CardEntry for %s", cardID); CNTV2Card *card = cardEntry->GetCard(); if (!card) { - blog(LOG_DEBUG, - "aja_source_device_changed: Card instance is null!"); + blog(LOG_DEBUG, "aja_source_device_changed: Card instance is null!"); return false; } @@ -724,37 +646,24 @@ bool aja_source_device_changed(void *data, obs_properties_t *props, card->GetVideoFormat(videoFormatChannel1, NTV2_CHANNEL1); } - obs_property_t *devices_list = - obs_properties_get(props, kUIPropDevice.id); - obs_property_t *io_select_list = - obs_properties_get(props, kUIPropInput.id); - obs_property_t *vid_fmt_list = - obs_properties_get(props, kUIPropVideoFormatSelect.id); - obs_property_t *pix_fmt_list = - obs_properties_get(props, kUIPropPixelFormatSelect.id); - obs_property_t *sdi_trx_list = - obs_properties_get(props, kUIPropSDITransport.id); - obs_property_t *sdi_4k_list = - obs_properties_get(props, kUIPropSDITransport4K.id); - obs_property_t *channel_format_list = - obs_properties_get(props, kUIPropChannelFormat.id); + obs_property_t *devices_list = obs_properties_get(props, kUIPropDevice.id); + obs_property_t *io_select_list = obs_properties_get(props, kUIPropInput.id); + obs_property_t *vid_fmt_list = obs_properties_get(props, kUIPropVideoFormatSelect.id); + obs_property_t *pix_fmt_list = obs_properties_get(props, kUIPropPixelFormatSelect.id); + obs_property_t *sdi_trx_list = obs_properties_get(props, kUIPropSDITransport.id); + obs_property_t *sdi_4k_list = obs_properties_get(props, kUIPropSDITransport4K.id); + obs_property_t *channel_format_list = obs_properties_get(props, kUIPropChannelFormat.id); obs_property_list_clear(vid_fmt_list); - obs_property_list_add_int(vid_fmt_list, obs_module_text("Auto"), - kAutoDetect); - populate_video_format_list(deviceID, vid_fmt_list, videoFormatChannel1, - true); + obs_property_list_add_int(vid_fmt_list, obs_module_text("Auto"), kAutoDetect); + populate_video_format_list(deviceID, vid_fmt_list, videoFormatChannel1, true); obs_property_list_clear(pix_fmt_list); - obs_property_list_add_int(pix_fmt_list, obs_module_text("Auto"), - kAutoDetect); - populate_pixel_format_list(deviceID, - {kDefaultAJAPixelFormat, - NTV2_FBF_10BIT_YCBCR, NTV2_FBF_24BIT_BGR}, + obs_property_list_add_int(pix_fmt_list, obs_module_text("Auto"), kAutoDetect); + populate_pixel_format_list(deviceID, {kDefaultAJAPixelFormat, NTV2_FBF_10BIT_YCBCR, NTV2_FBF_24BIT_BGR}, pix_fmt_list); - IOSelection io_select = static_cast( - obs_data_get_int(settings, kUIPropInput.id)); + IOSelection io_select = static_cast(obs_data_get_int(settings, kUIPropInput.id)); obs_property_list_clear(sdi_trx_list); populate_sdi_transport_list(sdi_trx_list, deviceID, true); @@ -762,49 +671,36 @@ bool aja_source_device_changed(void *data, obs_properties_t *props, populate_sdi_4k_transport_list(sdi_4k_list); obs_property_list_clear(channel_format_list); - obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_NONE, - 0); - obs_property_list_add_int(channel_format_list, - TEXT_CHANNEL_FORMAT_2_0CH, 2); - obs_property_list_add_int(channel_format_list, - TEXT_CHANNEL_FORMAT_2_1CH, 3); - obs_property_list_add_int(channel_format_list, - TEXT_CHANNEL_FORMAT_4_0CH, 4); - obs_property_list_add_int(channel_format_list, - TEXT_CHANNEL_FORMAT_4_1CH, 5); - obs_property_list_add_int(channel_format_list, - TEXT_CHANNEL_FORMAT_5_1CH, 6); - obs_property_list_add_int(channel_format_list, - TEXT_CHANNEL_FORMAT_7_1CH, 8); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_NONE, 0); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_2_0CH, 2); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_2_1CH, 3); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_4_0CH, 4); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_4_1CH, 5); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_5_1CH, 6); + obs_property_list_add_int(channel_format_list, TEXT_CHANNEL_FORMAT_7_1CH, 8); - populate_io_selection_input_list(cardID, ajaSource->GetName(), deviceID, - io_select_list); + populate_io_selection_input_list(cardID, ajaSource->GetName(), deviceID, io_select_list); - auto curr_vf = static_cast( - obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); + auto curr_vf = static_cast(obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); bool have_cards = cardManager.NumCardEntries() > 0; obs_property_set_visible(devices_list, have_cards); obs_property_set_visible(io_select_list, have_cards); obs_property_set_visible(vid_fmt_list, have_cards); obs_property_set_visible(pix_fmt_list, have_cards); - obs_property_set_visible( - sdi_trx_list, have_cards && aja::IsIOSelectionSDI(io_select)); - obs_property_set_visible( - sdi_4k_list, have_cards && NTV2_IS_4K_VIDEO_FORMAT(curr_vf)); + obs_property_set_visible(sdi_trx_list, have_cards && aja::IsIOSelectionSDI(io_select)); + obs_property_set_visible(sdi_4k_list, have_cards && NTV2_IS_4K_VIDEO_FORMAT(curr_vf)); return true; } -bool aja_io_selection_changed(void *data, obs_properties_t *props, - obs_property_t *list, obs_data_t *settings) +bool aja_io_selection_changed(void *data, obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { UNUSED_PARAMETER(list); AJASource *ajaSource = (AJASource *)data; if (!ajaSource) { - blog(LOG_DEBUG, - "aja_io_selection_changed: AJA Source instance is null!"); + blog(LOG_DEBUG, "aja_io_selection_changed: AJA Source instance is null!"); return false; } @@ -815,25 +711,19 @@ bool aja_io_selection_changed(void *data, obs_properties_t *props, auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "aja_io_selection_changed: Card Entry not found for %s", - cardID); + blog(LOG_DEBUG, "aja_io_selection_changed: Card Entry not found for %s", cardID); return false; } - filter_io_selection_input_list(cardID, ajaSource->GetName(), - obs_properties_get(props, - kUIPropInput.id)); + filter_io_selection_input_list(cardID, ajaSource->GetName(), obs_properties_get(props, kUIPropInput.id)); obs_property_set_visible( obs_properties_get(props, kUIPropSDITransport.id), - aja::IsIOSelectionSDI(static_cast( - obs_data_get_int(settings, kUIPropInput.id)))); + aja::IsIOSelectionSDI(static_cast(obs_data_get_int(settings, kUIPropInput.id)))); return true; } -bool aja_sdi_mode_list_changed(obs_properties_t *props, obs_property_t *list, - obs_data_t *settings) +bool aja_sdi_mode_list_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { UNUSED_PARAMETER(props); UNUSED_PARAMETER(list); @@ -877,8 +767,7 @@ void aja_source_destroy(void *data) CNTV2Card *card = ajaSource->GetCard(); if (card) { deviceID = card->GetDeviceID(); - aja::Routing::StopSourceAudio(ajaSource->GetSourceProps(), - card); + aja::Routing::StopSourceAudio(ajaSource->GetSourceProps(), card); } ajaSource->mVideoBuffer.Deallocate(); @@ -890,17 +779,13 @@ void aja_source_destroy(void *data) const auto &cardID = ajaSource->CardID(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, - "aja_source_destroy: Card Entry not found for %s", - cardID.c_str()); + blog(LOG_DEBUG, "aja_source_destroy: Card Entry not found for %s", cardID.c_str()); return; } auto ioSelect = ajaSource->GetSourceProps().ioSelect; - if (!cardEntry->ReleaseInputSelection(ioSelect, deviceID, - ajaSource->GetName())) { - blog(LOG_WARNING, - "aja_source_destroy: Error releasing Input Selection!"); + if (!cardEntry->ReleaseInputSelection(ioSelect, deviceID, ajaSource->GetName())) { + blog(LOG_WARNING, "aja_source_destroy: Error releasing Input Selection!"); } delete ajaSource; @@ -911,18 +796,14 @@ static void aja_source_show(void *data) { auto ajaSource = (AJASource *)data; if (!ajaSource) { - blog(LOG_ERROR, - "aja_source_show: AJA Source instance is null!"); + blog(LOG_ERROR, "aja_source_show: AJA Source instance is null!"); return; } - bool deactivateWhileNotShowing = - ajaSource->GetSourceProps().deactivateWhileNotShowing; + bool deactivateWhileNotShowing = ajaSource->GetSourceProps().deactivateWhileNotShowing; bool showing = obs_source_showing(ajaSource->GetOBSSource()); - blog(LOG_DEBUG, - "aja_source_show: deactivateWhileNotShowing = %s, showing = %s", - deactivateWhileNotShowing ? "true" : "false", - showing ? "true" : "false"); + blog(LOG_DEBUG, "aja_source_show: deactivateWhileNotShowing = %s, showing = %s", + deactivateWhileNotShowing ? "true" : "false", showing ? "true" : "false"); if (deactivateWhileNotShowing && showing && !ajaSource->IsCapturing()) { ajaSource->Activate(true); blog(LOG_DEBUG, "aja_source_show: activated capture thread!"); @@ -935,13 +816,10 @@ static void aja_source_hide(void *data) if (!ajaSource) return; - bool deactivateWhileNotShowing = - ajaSource->GetSourceProps().deactivateWhileNotShowing; + bool deactivateWhileNotShowing = ajaSource->GetSourceProps().deactivateWhileNotShowing; bool showing = obs_source_showing(ajaSource->GetOBSSource()); - blog(LOG_DEBUG, - "aja_source_hide: deactivateWhileNotShowing = %s, showing = %s", - deactivateWhileNotShowing ? "true" : "false", - showing ? "true" : "false"); + blog(LOG_DEBUG, "aja_source_hide: deactivateWhileNotShowing = %s, showing = %s", + deactivateWhileNotShowing ? "true" : "false", showing ? "true" : "false"); if (deactivateWhileNotShowing && !showing && ajaSource->IsCapturing()) { ajaSource->Deactivate(); blog(LOG_DEBUG, "aja_source_hide: deactivated capture thread!"); @@ -964,33 +842,21 @@ static void aja_source_update(void *data, obs_data_t *settings) auto ajaSource = (AJASource *)data; if (!ajaSource) { - blog(LOG_WARNING, - "aja_source_update: Plugin instance is null!"); + blog(LOG_WARNING, "aja_source_update: Plugin instance is null!"); return; } - auto io_select = static_cast( - obs_data_get_int(settings, kUIPropInput.id)); - auto vf_select = static_cast( - obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); - auto pf_select = static_cast( - obs_data_get_int(settings, kUIPropPixelFormatSelect.id)); - auto sdi_trx_select = static_cast( - obs_data_get_int(settings, kUIPropSDITransport.id)); - auto sdi_t4k_select = static_cast( - obs_data_get_int(settings, kUIPropSDITransport4K.id)); - auto num_audio_channels = - obs_data_get_int(settings, kUIPropChannelFormat.id); - bool deactivateWhileNotShowing = - obs_data_get_bool(settings, kUIPropDeactivateWhenNotShowing.id); - bool swapFrontCenterLFE = - obs_data_get_bool(settings, kUIPropChannelSwap_FC_LFE.id); - const std::string &wantCardID = - obs_data_get_string(settings, kUIPropDevice.id); + auto io_select = static_cast(obs_data_get_int(settings, kUIPropInput.id)); + auto vf_select = static_cast(obs_data_get_int(settings, kUIPropVideoFormatSelect.id)); + auto pf_select = static_cast(obs_data_get_int(settings, kUIPropPixelFormatSelect.id)); + auto sdi_trx_select = static_cast(obs_data_get_int(settings, kUIPropSDITransport.id)); + auto sdi_t4k_select = static_cast(obs_data_get_int(settings, kUIPropSDITransport4K.id)); + auto num_audio_channels = obs_data_get_int(settings, kUIPropChannelFormat.id); + bool deactivateWhileNotShowing = obs_data_get_bool(settings, kUIPropDeactivateWhenNotShowing.id); + bool swapFrontCenterLFE = obs_data_get_bool(settings, kUIPropChannelSwap_FC_LFE.id); + const std::string &wantCardID = obs_data_get_string(settings, kUIPropDevice.id); - obs_source_set_async_unbuffered( - ajaSource->GetOBSSource(), - !obs_data_get_bool(settings, kUIPropBuffering.id)); + obs_source_set_async_unbuffered(ajaSource->GetOBSSource(), !obs_data_get_bool(settings, kUIPropBuffering.id)); const std::string ¤tCardID = ajaSource->CardID(); if (wantCardID != currentCardID) { @@ -1002,21 +868,16 @@ static void aja_source_update(void *data, obs_data_t *settings) cardManager.EnumerateCards(); auto cardEntry = cardManager.GetCardEntry(wantCardID); if (!cardEntry) { - blog(LOG_DEBUG, - "aja_source_update: Card Entry not found for %s", - wantCardID.c_str()); + blog(LOG_DEBUG, "aja_source_update: Card Entry not found for %s", wantCardID.c_str()); return; } CNTV2Card *card = cardEntry->GetCard(); if (!card || !card->IsOpen()) { - blog(LOG_ERROR, "aja_source_update: AJA device %s not open!", - wantCardID.c_str()); + blog(LOG_ERROR, "aja_source_update: AJA device %s not open!", wantCardID.c_str()); return; } if (card->GetModelName() == "(Not Found)") { - blog(LOG_ERROR, - "aja_source_update: AJA device %s disconnected?", - wantCardID.c_str()); + blog(LOG_ERROR, "aja_source_update: AJA device %s disconnected?", wantCardID.c_str()); return; } ajaSource->SetCard(cardEntry->GetCard()); @@ -1027,20 +888,14 @@ static void aja_source_update(void *data, obs_data_t *settings) if (wantCardID != currentCardID) { auto prevCardEntry = cardManager.GetCardEntry(currentCardID); if (prevCardEntry) { - const std::string &ioSelectStr = - aja::IOSelectionToString(curr_props.ioSelect); - if (!prevCardEntry->ReleaseInputSelection( - curr_props.ioSelect, curr_props.deviceID, - ajaSource->GetName())) { - blog(LOG_WARNING, - "aja_source_update: Error releasing IOSelection %s for card ID %s", - ioSelectStr.c_str(), - currentCardID.c_str()); + const std::string &ioSelectStr = aja::IOSelectionToString(curr_props.ioSelect); + if (!prevCardEntry->ReleaseInputSelection(curr_props.ioSelect, curr_props.deviceID, + ajaSource->GetName())) { + blog(LOG_WARNING, "aja_source_update: Error releasing IOSelection %s for card ID %s", + ioSelectStr.c_str(), currentCardID.c_str()); } else { - blog(LOG_INFO, - "aja_source_update: Released IOSelection %s for card ID %s", - ioSelectStr.c_str(), - currentCardID.c_str()); + blog(LOG_INFO, "aja_source_update: Released IOSelection %s for card ID %s", + ioSelectStr.c_str(), currentCardID.c_str()); ajaSource->SetCardID(wantCardID); io_select = IOSelection::Invalid; } @@ -1055,18 +910,12 @@ static void aja_source_update(void *data, obs_data_t *settings) SourceProps want_props; want_props.deviceID = card->GetDeviceID(); want_props.ioSelect = io_select; - want_props.videoFormat = - ((int32_t)vf_select == kAutoDetect) - ? NTV2_FORMAT_UNKNOWN - : static_cast(vf_select); - want_props.pixelFormat = - ((int32_t)pf_select == kAutoDetect) - ? NTV2_FBF_INVALID - : static_cast(pf_select); - want_props.sdiTransport = - ((int32_t)sdi_trx_select == kAutoDetect) - ? SDITransport::Unknown - : static_cast(sdi_trx_select); + want_props.videoFormat = ((int32_t)vf_select == kAutoDetect) ? NTV2_FORMAT_UNKNOWN + : static_cast(vf_select); + want_props.pixelFormat = ((int32_t)pf_select == kAutoDetect) ? NTV2_FBF_INVALID + : static_cast(pf_select); + want_props.sdiTransport = ((int32_t)sdi_trx_select == kAutoDetect) ? SDITransport::Unknown + : static_cast(sdi_trx_select); want_props.sdi4kTransport = sdi_t4k_select; want_props.audioNumChannels = (uint32_t)num_audio_channels; want_props.swapFrontCenterLFE = swapFrontCenterLFE; @@ -1075,35 +924,26 @@ static void aja_source_update(void *data, obs_data_t *settings) if (aja::IsIOSelectionSDI(io_select)) { want_props.autoDetect = (int)sdi_trx_select == kAutoDetect; } else { - want_props.autoDetect = ((int)vf_select == kAutoDetect || - (int)pf_select == kAutoDetect); + want_props.autoDetect = ((int)vf_select == kAutoDetect || (int)pf_select == kAutoDetect); } ajaSource->SetCardID(wantCardID); ajaSource->SetDeviceIndex((UWord)cardEntry->GetCardIndex()); // Release Channels if IOSelection changes if (want_props.ioSelect != curr_props.ioSelect) { - const std::string &ioSelectStr = - aja::IOSelectionToString(curr_props.ioSelect); - if (!cardEntry->ReleaseInputSelection(curr_props.ioSelect, - curr_props.deviceID, - ajaSource->GetName())) { - blog(LOG_WARNING, - "aja_source_update: Error releasing IOSelection %s for card ID %s", + const std::string &ioSelectStr = aja::IOSelectionToString(curr_props.ioSelect); + if (!cardEntry->ReleaseInputSelection(curr_props.ioSelect, curr_props.deviceID, ajaSource->GetName())) { + blog(LOG_WARNING, "aja_source_update: Error releasing IOSelection %s for card ID %s", ioSelectStr.c_str(), currentCardID.c_str()); } else { - blog(LOG_INFO, - "aja_source_update: Released IOSelection %s for card ID %s", - ioSelectStr.c_str(), currentCardID.c_str()); + blog(LOG_INFO, "aja_source_update: Released IOSelection %s for card ID %s", ioSelectStr.c_str(), + currentCardID.c_str()); } } // Acquire Channels for current IOSelection - if (!cardEntry->AcquireInputSelection(want_props.ioSelect, - want_props.deviceID, - ajaSource->GetName())) { - blog(LOG_ERROR, - "aja_source_update: Could not acquire IOSelection %s", + if (!cardEntry->AcquireInputSelection(want_props.ioSelect, want_props.deviceID, ajaSource->GetName())) { + blog(LOG_ERROR, "aja_source_update: Could not acquire IOSelection %s", aja::IOSelectionToString(want_props.ioSelect).c_str()); return; } @@ -1111,13 +951,9 @@ static void aja_source_update(void *data, obs_data_t *settings) // Read SDI video payload IDs (VPID) used for helping to determine the wire format NTV2VideoFormat new_vf = want_props.videoFormat; NTV2PixelFormat new_pf = want_props.pixelFormat; - if (!ajaSource->ReadWireFormats(want_props.deviceID, - want_props.ioSelect, new_vf, new_pf, - want_props.vpids)) { + if (!ajaSource->ReadWireFormats(want_props.deviceID, want_props.ioSelect, new_vf, new_pf, want_props.vpids)) { blog(LOG_ERROR, "aja_source_update: ReadWireFormats failed!"); - cardEntry->ReleaseInputSelection(want_props.ioSelect, - curr_props.deviceID, - ajaSource->GetName()); + cardEntry->ReleaseInputSelection(want_props.ioSelect, curr_props.deviceID, ajaSource->GetName()); return; } @@ -1127,16 +963,11 @@ static void aja_source_update(void *data, obs_data_t *settings) if ((int32_t)pf_select == kAutoDetect) want_props.pixelFormat = new_pf; - if (want_props.videoFormat == NTV2_FORMAT_UNKNOWN || - want_props.pixelFormat == NTV2_FBF_INVALID) { - blog(LOG_ERROR, - "aja_source_update: Unknown video/pixel format(s): %s / %s", + if (want_props.videoFormat == NTV2_FORMAT_UNKNOWN || want_props.pixelFormat == NTV2_FBF_INVALID) { + blog(LOG_ERROR, "aja_source_update: Unknown video/pixel format(s): %s / %s", NTV2VideoFormatToString(want_props.videoFormat).c_str(), - NTV2FrameBufferFormatToString(want_props.pixelFormat) - .c_str()); - cardEntry->ReleaseInputSelection(want_props.ioSelect, - curr_props.deviceID, - ajaSource->GetName()); + NTV2FrameBufferFormatToString(want_props.pixelFormat).c_str()); + cardEntry->ReleaseInputSelection(want_props.ioSelect, curr_props.deviceID, ajaSource->GetName()); return; } @@ -1144,8 +975,7 @@ static void aja_source_update(void *data, obs_data_t *settings) if (!initialized || want_props != ajaSource->GetSourceProps()) { ajaSource->ClearConnections(); NTV2XptConnections xpt_cnx; - aja::Routing::ConfigureSourceRoute( - want_props, NTV2_MODE_CAPTURE, card, xpt_cnx); + aja::Routing::ConfigureSourceRoute(want_props, NTV2_MODE_CAPTURE, card, xpt_cnx); ajaSource->CacheConnections(xpt_cnx); ajaSource->Deactivate(); initialized = true; @@ -1160,71 +990,49 @@ static void aja_source_update(void *data, obs_data_t *settings) static obs_properties_t *aja_source_get_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *device_list = obs_properties_add_list( - props, kUIPropDevice.id, obs_module_text(kUIPropDevice.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *device_list = obs_properties_add_list(props, kUIPropDevice.id, + obs_module_text(kUIPropDevice.text), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); populate_source_device_list(device_list); obs_property_t *io_select_list = obs_properties_add_list( - props, kUIPropInput.id, obs_module_text(kUIPropInput.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_t *vid_fmt_list = obs_properties_add_list( - props, kUIPropVideoFormatSelect.id, - obs_module_text(kUIPropVideoFormatSelect.text), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropPixelFormatSelect.id, - obs_module_text(kUIPropPixelFormatSelect.text), + props, kUIPropInput.id, obs_module_text(kUIPropInput.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *vid_fmt_list = obs_properties_add_list(props, kUIPropVideoFormatSelect.id, + obs_module_text(kUIPropVideoFormatSelect.text), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, kUIPropPixelFormatSelect.id, obs_module_text(kUIPropPixelFormatSelect.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropSDITransport.id, - obs_module_text(kUIPropSDITransport.text), + obs_properties_add_list(props, kUIPropSDITransport.id, obs_module_text(kUIPropSDITransport.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropSDITransport4K.id, - obs_module_text(kUIPropSDITransport4K.text), + obs_properties_add_list(props, kUIPropSDITransport4K.id, obs_module_text(kUIPropSDITransport4K.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, kUIPropChannelFormat.id, - obs_module_text(kUIPropChannelFormat.text), + obs_properties_add_list(props, kUIPropChannelFormat.id, obs_module_text(kUIPropChannelFormat.text), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_t *swap = obs_properties_add_bool( - props, kUIPropChannelSwap_FC_LFE.id, - obs_module_text(kUIPropChannelSwap_FC_LFE.text)); - obs_property_set_long_description(swap, - kUIPropChannelSwap_FC_LFE.tooltip); - obs_properties_add_bool( - props, kUIPropDeactivateWhenNotShowing.id, - obs_module_text(kUIPropDeactivateWhenNotShowing.text)); - obs_properties_add_bool(props, kUIPropBuffering.id, - obs_module_text(kUIPropBuffering.text)); - obs_properties_add_bool(props, kUIPropBuffering.id, - obs_module_text(kUIPropBuffering.text)); + obs_property_t *swap = obs_properties_add_bool(props, kUIPropChannelSwap_FC_LFE.id, + obs_module_text(kUIPropChannelSwap_FC_LFE.text)); + obs_property_set_long_description(swap, kUIPropChannelSwap_FC_LFE.tooltip); + obs_properties_add_bool(props, kUIPropDeactivateWhenNotShowing.id, + obs_module_text(kUIPropDeactivateWhenNotShowing.text)); + obs_properties_add_bool(props, kUIPropBuffering.id, obs_module_text(kUIPropBuffering.text)); + obs_properties_add_bool(props, kUIPropBuffering.id, obs_module_text(kUIPropBuffering.text)); - obs_property_set_modified_callback(vid_fmt_list, - aja_video_format_changed); - obs_property_set_modified_callback2(device_list, - aja_source_device_changed, data); - obs_property_set_modified_callback2(io_select_list, - aja_io_selection_changed, data); + obs_property_set_modified_callback(vid_fmt_list, aja_video_format_changed); + obs_property_set_modified_callback2(device_list, aja_source_device_changed, data); + obs_property_set_modified_callback2(io_select_list, aja_io_selection_changed, data); return props; } void aja_source_get_defaults(obs_data_t *settings) { - obs_data_set_default_int(settings, kUIPropInput.id, - static_cast(IOSelection::Invalid)); - obs_data_set_default_int(settings, kUIPropVideoFormatSelect.id, - static_cast(kAutoDetect)); - obs_data_set_default_int(settings, kUIPropPixelFormatSelect.id, - static_cast(kAutoDetect)); - obs_data_set_default_int(settings, kUIPropSDITransport.id, - static_cast(kAutoDetect)); - obs_data_set_default_int( - settings, kUIPropSDITransport4K.id, - static_cast(SDITransport4K::TwoSampleInterleave)); - obs_data_set_default_int(settings, kUIPropChannelFormat.id, - kDefaultAudioCaptureChannels); - obs_data_set_default_bool(settings, kUIPropChannelSwap_FC_LFE.id, - false); - obs_data_set_default_bool(settings, kUIPropDeactivateWhenNotShowing.id, - false); + obs_data_set_default_int(settings, kUIPropInput.id, static_cast(IOSelection::Invalid)); + obs_data_set_default_int(settings, kUIPropVideoFormatSelect.id, static_cast(kAutoDetect)); + obs_data_set_default_int(settings, kUIPropPixelFormatSelect.id, static_cast(kAutoDetect)); + obs_data_set_default_int(settings, kUIPropSDITransport.id, static_cast(kAutoDetect)); + obs_data_set_default_int(settings, kUIPropSDITransport4K.id, + static_cast(SDITransport4K::TwoSampleInterleave)); + obs_data_set_default_int(settings, kUIPropChannelFormat.id, kDefaultAudioCaptureChannels); + obs_data_set_default_bool(settings, kUIPropChannelSwap_FC_LFE.id, false); + obs_data_set_default_bool(settings, kUIPropDeactivateWhenNotShowing.id, false); } static void aja_source_get_defaults_v1(obs_data_t *settings) @@ -1237,8 +1045,7 @@ void aja_source_save(void *data, obs_data_t *settings) { AJASource *ajaSource = (AJASource *)data; if (!ajaSource) { - blog(LOG_ERROR, - "aja_source_save: AJA Source instance is null!"); + blog(LOG_ERROR, "aja_source_save: AJA Source instance is null!"); return; } @@ -1249,18 +1056,15 @@ void aja_source_save(void *data, obs_data_t *settings) auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); if (!cardEntry) { - blog(LOG_DEBUG, "aja_source_save: Card Entry not found for %s", - cardID); + blog(LOG_DEBUG, "aja_source_save: Card Entry not found for %s", cardID); return; } auto oldName = ajaSource->GetName(); auto newName = obs_source_get_name(ajaSource->GetOBSSource()); - if (oldName != newName && - cardEntry->UpdateChannelOwnerName(oldName, newName)) { + if (oldName != newName && cardEntry->UpdateChannelOwnerName(oldName, newName)) { ajaSource->SetName(newName); - blog(LOG_DEBUG, "aja_source_save: Renamed \"%s\" to \"%s\"", - oldName.c_str(), newName); + blog(LOG_DEBUG, "aja_source_save: Renamed \"%s\" to \"%s\"", oldName.c_str(), newName); } } @@ -1269,9 +1073,8 @@ void register_aja_source_info() struct obs_source_info aja_source_info = {}; aja_source_info.id = kUIPropCaptureModule.id; aja_source_info.type = OBS_SOURCE_TYPE_INPUT; - aja_source_info.output_flags = - OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_CAP_OBSOLETE; + aja_source_info.output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | + OBS_SOURCE_CAP_OBSOLETE; aja_source_info.get_name = aja_source_get_name; aja_source_info.create = aja_source_create; aja_source_info.destroy = aja_source_destroy; diff --git a/plugins/aja/aja-source.hpp b/plugins/aja/aja-source.hpp index cb56a963a..b86dfd95c 100644 --- a/plugins/aja/aja-source.hpp +++ b/plugins/aja/aja-source.hpp @@ -29,8 +29,7 @@ public: void SetName(const std::string &name); std::string GetName() const; - void GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, - NTV2TestPatternSelect ps); + void GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2TestPatternSelect ps); // Capture Thread stuff static void CaptureThread(AJAThread *thread, void *data); @@ -54,8 +53,7 @@ public: bool ReadChannelVPIDs(NTV2Channel channel, VPIDData &vpids); - bool ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, - NTV2VideoFormat &vf, NTV2PixelFormat &pf, + bool ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, NTV2VideoFormat &vf, NTV2PixelFormat &pf, VPIDDataList &vpids); void ResetVideoBuffer(NTV2VideoFormat vf, NTV2PixelFormat pf); diff --git a/plugins/aja/aja-ui-props.hpp b/plugins/aja/aja-ui-props.hpp index da082d664..b37c35a45 100644 --- a/plugins/aja/aja-ui-props.hpp +++ b/plugins/aja/aja-ui-props.hpp @@ -52,8 +52,7 @@ static const UIProperty kUIPropInput = { }; // Used for showing "Select..." item in Input/Output selection drop-downs -static const UIProperty kUIPropIOSelectNone = {"ui_prop_select_input", - "IOSelect", ""}; +static const UIProperty kUIPropIOSelectNone = {"ui_prop_select_input", "IOSelect", ""}; static const UIProperty kUIPropSDITransport = { "ui_prop_sdi_transport", diff --git a/plugins/aja/aja-widget-io.cpp b/plugins/aja/aja-widget-io.cpp index c7d01c0ac..b22e82429 100644 --- a/plugins/aja/aja-widget-io.cpp +++ b/plugins/aja/aja-widget-io.cpp @@ -342,12 +342,10 @@ static WidgetOutputSocket kWidgetOutputSockets[] = { }; // clang-format on -bool WidgetInputSocket::Find(const std::string &name, NTV2Channel channel, - int32_t datastream, WidgetInputSocket &inp) +bool WidgetInputSocket::Find(const std::string &name, NTV2Channel channel, int32_t datastream, WidgetInputSocket &inp) { for (const auto &in : kWidgetInputSockets) { - if (name == in.name && - channel == aja::WidgetIDToChannel(in.widget_id) && + if (name == in.name && channel == aja::WidgetIDToChannel(in.widget_id) && datastream == in.datastream_index) { inp = in; return true; @@ -357,8 +355,7 @@ bool WidgetInputSocket::Find(const std::string &name, NTV2Channel channel, return false; } -bool WidgetInputSocket::GetWidgetInputSocketByXpt(InputXpt id, - WidgetInputSocket &inp) +bool WidgetInputSocket::GetWidgetInputSocketByXpt(InputXpt id, WidgetInputSocket &inp) { for (const auto &in : kWidgetInputSockets) { if (in.id == id) { @@ -406,15 +403,13 @@ const char *WidgetInputSocket::InputXptName(InputXpt xpt) return name; } -bool WidgetOutputSocket::Find(const std::string &name, NTV2Channel channel, - int32_t datastream, WidgetOutputSocket &out) +bool WidgetOutputSocket::Find(const std::string &name, NTV2Channel channel, int32_t datastream, WidgetOutputSocket &out) { // std::cout << "DEBUG -- WidgetOutputSocket::Find: name = " << name // << ", chan = " << NTV2ChannelToString(channel) // << ", datastream = " << datastream << std::endl; for (const auto &wo : kWidgetOutputSockets) { - if (name == wo.name && - channel == aja::WidgetIDToChannel(wo.widget_id) && + if (name == wo.name && channel == aja::WidgetIDToChannel(wo.widget_id) && datastream == wo.datastream_index) { out = wo; return true; @@ -424,8 +419,7 @@ bool WidgetOutputSocket::Find(const std::string &name, NTV2Channel channel, return false; } -bool WidgetOutputSocket::GetWidgetOutputSocketByXpt(OutputXpt id, - WidgetOutputSocket &out) +bool WidgetOutputSocket::GetWidgetOutputSocketByXpt(OutputXpt id, WidgetOutputSocket &out) { for (const auto &wo : kWidgetOutputSockets) { if (wo.id == id) { diff --git a/plugins/aja/aja-widget-io.hpp b/plugins/aja/aja-widget-io.hpp index 2cbc73233..7c9e9cf73 100644 --- a/plugins/aja/aja-widget-io.hpp +++ b/plugins/aja/aja-widget-io.hpp @@ -14,10 +14,8 @@ struct WidgetInputSocket { const char *name; int32_t datastream_index; - static bool Find(const std::string &route, NTV2Channel channel, - int32_t datastream, WidgetInputSocket &inp); - static bool GetWidgetInputSocketByXpt(InputXpt id, - WidgetInputSocket &inp); + static bool Find(const std::string &route, NTV2Channel channel, int32_t datastream, WidgetInputSocket &inp); + static bool GetWidgetInputSocketByXpt(InputXpt id, WidgetInputSocket &inp); static int32_t InputXptDatastreamIndex(InputXpt xpt); static NTV2Channel InputXptChannel(InputXpt xpt); static const char *InputXptName(InputXpt xpt); @@ -30,10 +28,8 @@ struct WidgetOutputSocket { const char *name; int32_t datastream_index; - static bool Find(const std::string &route, NTV2Channel channel, - int32_t datastream, WidgetOutputSocket &out); - static bool GetWidgetOutputSocketByXpt(OutputXpt id, - WidgetOutputSocket &out); + static bool Find(const std::string &route, NTV2Channel channel, int32_t datastream, WidgetOutputSocket &out); + static bool GetWidgetOutputSocketByXpt(OutputXpt id, WidgetOutputSocket &out); static int32_t OutputXptDatastreamIndex(OutputXpt xpt); static NTV2Channel OutputXptChannel(OutputXpt xpt); static const char *OutputXptName(OutputXpt xpt); diff --git a/plugins/aja/audio-repack.c b/plugins/aja/audio-repack.c index d8c1d5974..9ce6cfae3 100644 --- a/plugins/aja/audio-repack.c +++ b/plugins/aja/audio-repack.c @@ -9,12 +9,10 @@ int check_buffer(struct audio_repack *repack, uint32_t frame_count) { - const uint32_t new_size = - frame_count * repack->base_dst_size + repack->pad_dst_size; + const uint32_t new_size = frame_count * repack->base_dst_size + repack->pad_dst_size; if (repack->packet_size < new_size) { - repack->packet_buffer = - brealloc(repack->packet_buffer, new_size); + repack->packet_buffer = brealloc(repack->packet_buffer, new_size); if (!repack->packet_buffer) return -1; repack->packet_size = new_size; @@ -34,8 +32,7 @@ int check_buffer(struct audio_repack *repack, uint32_t frame_count) * | | | * | FL | FR | LFE | */ -int repack_squash16(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash16(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; @@ -69,8 +66,7 @@ int repack_squash16(struct audio_repack *repack, const uint8_t *bsrc, * | | | * | FL | FR | LFE | FC | RL | RR | LC | RC | */ -int repack_squash_swap16(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash_swap16(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; @@ -80,8 +76,7 @@ int repack_squash_swap16(struct audio_repack *repack, const uint8_t *bsrc, uint16_t *dst = (uint16_t *)repack->packet_buffer; while (src != end) { __m128i target = _mm_load_si128(src++); - __m128i buf = - _mm_shufflelo_epi16(target, _MM_SHUFFLE(2, 3, 1, 0)); + __m128i buf = _mm_shufflelo_epi16(target, _MM_SHUFFLE(2, 3, 1, 0)); _mm_storeu_si128((__m128i *)dst, buf); dst += NUM_CHANNELS - squash; } @@ -92,16 +87,14 @@ int repack_squash_swap16(struct audio_repack *repack, const uint8_t *bsrc, * Squash array of 8ch to new channel count * 32-bit PCM, SIMD version */ -int repack_squash32(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash32(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; int squash = repack->squash_count; const __m128i *src = (__m128i *)bsrc; - const __m128i *end = - (__m128i *)(bsrc + (frame_count * repack->base_src_size)); + const __m128i *end = (__m128i *)(bsrc + (frame_count * repack->base_src_size)); uint32_t *dst = (uint32_t *)repack->packet_buffer; if (squash > 0) { @@ -123,19 +116,16 @@ int repack_squash32(struct audio_repack *repack, const uint8_t *bsrc, * Squash array of 8ch to new channel count and swap FC with LFE * 32-bit PCM, SIMD version */ -int repack_squash_swap32(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash_swap32(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; int squash = repack->squash_count; const __m128i *src = (__m128i *)bsrc; - const __m128i *end = - (__m128i *)(bsrc + (frame_count * repack->base_src_size)); + const __m128i *end = (__m128i *)(bsrc + (frame_count * repack->base_src_size)); uint32_t *dst = (uint32_t *)repack->packet_buffer; while (src != end) { - __m128i tgt_lo = _mm_shuffle_epi32(_mm_loadu_si128(src++), - _MM_SHUFFLE(2, 3, 1, 0)); + __m128i tgt_lo = _mm_shuffle_epi32(_mm_loadu_si128(src++), _MM_SHUFFLE(2, 3, 1, 0)); __m128i tgt_hi = _mm_loadu_si128(src++); _mm_storeu_si128((__m128i *)dst, tgt_lo); dst += 4; @@ -152,8 +142,7 @@ int repack_squash_swap32(struct audio_repack *repack, const uint8_t *bsrc, * Squash array of 8ch to new channel count * 16-bit or 32-bit PCM, C version */ -int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; @@ -164,8 +153,7 @@ int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, uint32_t new_channel_count = NUM_CHANNELS - squash; if (squash > 0) { while (src != end) { - memcpy(dst, src, - repack->bytes_per_sample * new_channel_count); + memcpy(dst, src, repack->bytes_per_sample * new_channel_count); dst += (new_channel_count * repack->bytes_per_sample); src += NUM_CHANNELS * repack->bytes_per_sample; } @@ -174,8 +162,8 @@ int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, return 0; } -void shuffle_8ch(uint8_t *dst, const uint8_t *src, size_t szb, int ch1, int ch2, - int ch3, int ch4, int ch5, int ch6, int ch7, int ch8) +void shuffle_8ch(uint8_t *dst, const uint8_t *src, size_t szb, int ch1, int ch2, int ch3, int ch4, int ch5, int ch6, + int ch7, int ch8) { /* shuffle 8 channels of audio */ for (size_t i = 0; i < szb; i++) { @@ -194,8 +182,7 @@ void shuffle_8ch(uint8_t *dst, const uint8_t *src, size_t szb, int ch1, int ch2, * Squash array of 8ch to new channel count and swap FC with LFE * 16-bit or 32-bit PCM, C version */ -int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; @@ -217,8 +204,7 @@ int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, } #endif -int audio_repack_init(struct audio_repack *repack, - audio_repack_mode_t repack_mode, uint8_t bits_per_sample) +int audio_repack_init(struct audio_repack *repack, audio_repack_mode_t repack_mode, uint8_t bits_per_sample) { memset(repack, 0, sizeof(*repack)); @@ -228,8 +214,7 @@ int audio_repack_init(struct audio_repack *repack, int bytes_per_sample = (bits_per_sample / 8); repack->bytes_per_sample = bytes_per_sample; repack->base_src_size = NUM_CHANNELS * bytes_per_sample; - repack->base_dst_size = - _audio_repack_ch[repack_mode] * bytes_per_sample; + repack->base_dst_size = _audio_repack_ch[repack_mode] * bytes_per_sample; uint32_t squash_count = NUM_CHANNELS - _audio_repack_ch[repack_mode]; repack->pad_dst_size = squash_count * bytes_per_sample; repack->squash_count = squash_count; @@ -237,21 +222,18 @@ int audio_repack_init(struct audio_repack *repack, #ifdef USE_SIMD if (bits_per_sample == 16) { repack->repack_func = &repack_squash16; - if (repack_mode == repack_mode_8to5ch_swap || - repack_mode == repack_mode_8to6ch_swap || + if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap || repack_mode == repack_mode_8ch_swap) repack->repack_func = &repack_squash_swap16; } else if (bits_per_sample == 32) { repack->repack_func = &repack_squash32; - if (repack_mode == repack_mode_8to5ch_swap || - repack_mode == repack_mode_8to6ch_swap || + if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap || repack_mode == repack_mode_8ch_swap) repack->repack_func = &repack_squash_swap32; } #else repack->repack_func = &repack_squash; - if (repack_mode == repack_mode_8to5ch_swap || - repack_mode == repack_mode_8to6ch_swap || + if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap || repack_mode == repack_mode_8ch_swap) repack->repack_func = &repack_squash_swap; #endif diff --git a/plugins/aja/audio-repack.h b/plugins/aja/audio-repack.h index 992e907f8..7fc51472a 100644 --- a/plugins/aja/audio-repack.h +++ b/plugins/aja/audio-repack.h @@ -11,8 +11,7 @@ extern "C" { struct audio_repack; -typedef int (*audio_repack_func_t)(struct audio_repack *, const uint8_t *, - uint32_t); +typedef int (*audio_repack_func_t)(struct audio_repack *, const uint8_t *, uint32_t); struct audio_repack { uint8_t *packet_buffer; @@ -41,9 +40,7 @@ enum _audio_repack_mode { typedef enum _audio_repack_mode audio_repack_mode_t; -extern int audio_repack_init(struct audio_repack *repack, - audio_repack_mode_t repack_mode, - uint8_t bits_per_sample); +extern int audio_repack_init(struct audio_repack *repack, audio_repack_mode_t repack_mode, uint8_t bits_per_sample); extern void audio_repack_free(struct audio_repack *repack); #ifdef __cplusplus diff --git a/plugins/aja/audio-repack.hpp b/plugins/aja/audio-repack.hpp index 946a40388..33d9ab919 100644 --- a/plugins/aja/audio-repack.hpp +++ b/plugins/aja/audio-repack.hpp @@ -6,8 +6,7 @@ class AudioRepacker { struct audio_repack arepack; public: - inline AudioRepacker(audio_repack_mode_t repack_mode, - int bits_per_sample) + inline AudioRepacker(audio_repack_mode_t repack_mode, int bits_per_sample) { audio_repack_init(&arepack, repack_mode, bits_per_sample); } diff --git a/plugins/aja/main.cpp b/plugins/aja/main.cpp index f6fa1a65a..fd13cff7e 100644 --- a/plugins/aja/main.cpp +++ b/plugins/aja/main.cpp @@ -18,8 +18,7 @@ bool obs_module_load(void) CNTV2DeviceScanner scanner; auto numDevices = scanner.GetNumDevices(); if (numDevices == 0) { - blog(LOG_WARNING, - "No AJA devices found, skipping loading AJA plugin"); + blog(LOG_WARNING, "No AJA devices found, skipping loading AJA plugin"); return false; } diff --git a/plugins/coreaudio-encoder/encoder.cpp b/plugins/coreaudio-encoder/encoder.cpp index ded746420..c306abdb0 100644 --- a/plugins/coreaudio-encoder/encoder.cpp +++ b/plugins/coreaudio-encoder/encoder.cpp @@ -13,14 +13,10 @@ #include #endif -#define CA_LOG(level, format, ...) \ - blog(level, "[CoreAudio encoder]: " format, ##__VA_ARGS__) -#define CA_LOG_ENCODER(format_name, encoder, level, format, ...) \ - blog(level, "[CoreAudio %s: '%s']: " format, format_name, \ - obs_encoder_get_name(encoder), ##__VA_ARGS__) -#define CA_BLOG(level, format, ...) \ - CA_LOG_ENCODER(ca->format_name, ca->encoder, level, format, \ - ##__VA_ARGS__) +#define CA_LOG(level, format, ...) blog(level, "[CoreAudio encoder]: " format, ##__VA_ARGS__) +#define CA_LOG_ENCODER(format_name, encoder, level, format, ...) \ + blog(level, "[CoreAudio %s: '%s']: " format, format_name, obs_encoder_get_name(encoder), ##__VA_ARGS__) +#define CA_BLOG(level, format, ...) CA_LOG_ENCODER(ca->format_name, ca->encoder, level, format, ##__VA_ARGS__) #define CA_CO_LOG(level, format, ...) \ do { \ if (ca) \ @@ -132,31 +128,21 @@ namespace std { #ifndef _WIN32 template<> struct default_delete::type> { - void operator()(remove_pointer::type *err) - { - CFRelease(err); - } + void operator()(remove_pointer::type *err) { CFRelease(err); } }; template<> struct default_delete::type> { - void operator()(remove_pointer::type *str) - { - CFRelease(str); - } + void operator()(remove_pointer::type *str) { CFRelease(str); } }; #endif template<> struct default_delete::type> { - void operator()(AudioConverterRef converter) - { - AudioConverterDispose(converter); - } + void operator()(AudioConverterRef converter) { AudioConverterDispose(converter); } }; } // namespace std -template -using cf_ptr = unique_ptr::type>; +template using cf_ptr = unique_ptr::type>; #ifndef _MSC_VER __attribute__((__format__(__printf__, 3, 4))) @@ -208,11 +194,9 @@ static const char *flush_log(DStr &log) return log->array; } -#define CA_CO_DLOG_(level, format) \ - CA_CO_LOG(level, format "%s%s", log->array ? ":\n" : "", flush_log(log)) -#define CA_CO_DLOG(level, format, ...) \ - CA_CO_LOG(level, format "%s%s", ##__VA_ARGS__, \ - log->array ? ":\n" : "", flush_log(log)) +#define CA_CO_DLOG_(level, format) CA_CO_LOG(level, format "%s%s", log->array ? ":\n" : "", flush_log(log)) +#define CA_CO_DLOG(level, format, ...) \ + CA_CO_LOG(level, format "%s%s", ##__VA_ARGS__, log->array ? ":\n" : "", flush_log(log)) static const char *aac_get_name(void *) { @@ -257,8 +241,7 @@ static DStr osstatus_to_dstr(OSStatus code) DStr result; #ifndef _WIN32 - cf_ptr err{CFErrorCreate( - kCFAllocatorDefault, kCFErrorDomainOSStatus, code, NULL)}; + cf_ptr err{CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, code, NULL)}; cf_ptr str{CFErrorCopyDescription(err.get())}; if (cfstr_copy_dstr(str.get(), kCFStringEncodingUTF8, result)) @@ -266,14 +249,12 @@ static DStr osstatus_to_dstr(OSStatus code) #endif const char *code_str = code_to_str(code); - dstr_printf(result, "%s%s%d%s", code_str ? code_str : "", - code_str ? " (" : "", static_cast(code), + dstr_printf(result, "%s%s%d%s", code_str ? code_str : "", code_str ? " (" : "", static_cast(code), code_str ? ")" : ""); return result; } -static void log_osstatus(int log_level, ca_encoder *ca, const char *context, - OSStatus code) +static void log_osstatus(int log_level, ca_encoder *ca, const char *context, OSStatus code) { DStr str = osstatus_to_dstr(code); if (ca) @@ -336,19 +317,14 @@ static void aac_destroy(void *data) } template -static bool query_converter_property_raw(DStr &log, ca_encoder *ca, - AudioFormatPropertyID property, - const char *get_property_info, - const char *get_property, - AudioConverterRef converter, - Func &&func) +static bool query_converter_property_raw(DStr &log, ca_encoder *ca, AudioFormatPropertyID property, + const char *get_property_info, const char *get_property, + AudioConverterRef converter, Func &&func) { UInt32 size = 0; - OSStatus code = AudioConverterGetPropertyInfo(converter, property, - &size, nullptr); + OSStatus code = AudioConverterGetPropertyInfo(converter, property, &size, nullptr); if (code) { - log_to_dstr(log, ca, "%s: %s\n", get_property_info, - osstatus_to_dstr(code)->array); + log_to_dstr(log, ca, "%s: %s\n", get_property_info, osstatus_to_dstr(code)->array); return false; } @@ -362,16 +338,13 @@ static bool query_converter_property_raw(DStr &log, ca_encoder *ca, try { buffer.resize(size); } catch (...) { - log_to_dstr(log, ca, "Failed to allocate %u bytes for %s\n", - static_cast(size), get_property); + log_to_dstr(log, ca, "Failed to allocate %u bytes for %s\n", static_cast(size), get_property); return false; } - code = AudioConverterGetProperty(converter, property, &size, - buffer.data()); + code = AudioConverterGetProperty(converter, property, &size, buffer.data()); if (code) { - log_to_dstr(log, ca, "%s: %s\n", get_property, - osstatus_to_dstr(code)->array); + log_to_dstr(log, ca, "%s: %s\n", get_property, osstatus_to_dstr(code)->array); return false; } @@ -380,30 +353,23 @@ static bool query_converter_property_raw(DStr &log, ca_encoder *ca, return true; } -#define EXPAND_CONVERTER_NAMES(x) \ - x, "AudioConverterGetPropertyInfo(" #x ")", \ - "AudioConverterGetProperty(" #x ")" +#define EXPAND_CONVERTER_NAMES(x) x, "AudioConverterGetPropertyInfo(" #x ")", "AudioConverterGetProperty(" #x ")" template -static bool enumerate_bitrates(DStr &log, ca_encoder *ca, - AudioConverterRef converter, Func &&func) +static bool enumerate_bitrates(DStr &log, ca_encoder *ca, AudioConverterRef converter, Func &&func) { auto helper = [&](UInt32 size, void *data) { auto range = static_cast(data); size_t num_ranges = size / sizeof(AudioValueRange); for (size_t i = 0; i < num_ranges; i++) - func(static_cast(range[i].mMinimum), - static_cast(range[i].mMaximum)); + func(static_cast(range[i].mMinimum), static_cast(range[i].mMaximum)); }; - return query_converter_property_raw( - log, ca, - EXPAND_CONVERTER_NAMES(kAudioConverterApplicableEncodeBitRates), - converter, helper); + return query_converter_property_raw(log, ca, EXPAND_CONVERTER_NAMES(kAudioConverterApplicableEncodeBitRates), + converter, helper); } -static bool bitrate_valid(DStr &log, ca_encoder *ca, - AudioConverterRef converter, UInt32 bitrate) +static bool bitrate_valid(DStr &log, ca_encoder *ca, AudioConverterRef converter, UInt32 bitrate) { bool valid = false; @@ -417,48 +383,37 @@ static bool bitrate_valid(DStr &log, ca_encoder *ca, return valid; } -static bool create_encoder(DStr &log, ca_encoder *ca, - AudioStreamBasicDescription *in, - AudioStreamBasicDescription *out, UInt32 format_id, - UInt32 bitrate, UInt32 samplerate, - UInt32 rate_control) +static bool create_encoder(DStr &log, ca_encoder *ca, AudioStreamBasicDescription *in, AudioStreamBasicDescription *out, + UInt32 format_id, UInt32 bitrate, UInt32 samplerate, UInt32 rate_control) { -#define STATUS_CHECK(c) \ - code = c; \ - if (code) { \ - log_to_dstr(log, ca, #c " returned %s", \ - osstatus_to_dstr(code)->array); \ - return false; \ +#define STATUS_CHECK(c) \ + code = c; \ + if (code) { \ + log_to_dstr(log, ca, #c " returned %s", osstatus_to_dstr(code)->array); \ + return false; \ } - Float64 srate = samplerate ? (Float64)samplerate - : (Float64)ca->samples_per_second; + Float64 srate = samplerate ? (Float64)samplerate : (Float64)ca->samples_per_second; - auto out_ = asbd_builder() - .sample_rate(srate) - .channels_per_frame((UInt32)ca->channels) - .format_id(format_id) - .asbd; + auto out_ = + asbd_builder().sample_rate(srate).channels_per_frame((UInt32)ca->channels).format_id(format_id).asbd; UInt32 size = sizeof(*out); OSStatus code; - STATUS_CHECK(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, - NULL, &size, &out_)); + STATUS_CHECK(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &size, &out_)); *out = out_; STATUS_CHECK(AudioConverterNew(in, out, &ca->converter)) - STATUS_CHECK(AudioConverterSetProperty( - ca->converter, kAudioCodecPropertyBitRateControlMode, - sizeof(rate_control), &rate_control)); + STATUS_CHECK(AudioConverterSetProperty(ca->converter, kAudioCodecPropertyBitRateControlMode, + sizeof(rate_control), &rate_control)); if (!bitrate_valid(log, ca, ca->converter, bitrate)) { log_to_dstr(log, ca, "Encoder does not support bitrate %u " "for format %s (0x%x)\n", - (uint32_t)bitrate, format_id_to_str(format_id), - (uint32_t)format_id); + (uint32_t)bitrate, format_id_to_str(format_id), (uint32_t)format_id); return false; } @@ -489,16 +444,14 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) UInt32 bitrate = (UInt32)obs_data_get_int(settings, "bitrate") * 1000; if (!bitrate) { - CA_LOG_ENCODER("AAC", encoder, LOG_ERROR, - "Invalid bitrate specified"); + CA_LOG_ENCODER("AAC", encoder, LOG_ERROR, "Invalid bitrate specified"); return NULL; } const enum audio_format format = AUDIO_FORMAT_FLOAT; if (is_audio_planar(format)) { - CA_LOG_ENCODER("AAC", encoder, LOG_ERROR, - "Got non-interleaved audio format %d", format); + CA_LOG_ENCODER("AAC", encoder, LOG_ERROR, "Got non-interleaved audio format %d", format); return NULL; } @@ -507,8 +460,7 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) try { ca.reset(new ca_encoder()); } catch (...) { - CA_LOG_ENCODER("AAC", encoder, LOG_ERROR, - "Could not allocate encoder"); + CA_LOG_ENCODER("AAC", encoder, LOG_ERROR, "Could not allocate encoder"); return nullptr; } @@ -532,8 +484,7 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) .bytes_per_packet((UInt32)(1 * bytes_per_frame)) .bits_per_channel((UInt32)bits_per_channel) .format_id(kAudioFormatLinearPCM) - .format_flags(kAudioFormatFlagsNativeEndian | - kAudioFormatFlagIsPacked | + .format_flags(kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsFloat | 0) .asbd; @@ -547,18 +498,16 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) ca->allowed_formats = &aac_lc_formats; } - auto samplerate = - static_cast(obs_data_get_int(settings, "samplerate")); + auto samplerate = static_cast(obs_data_get_int(settings, "samplerate")); DStr log; bool encoder_created = false; for (UInt32 format_id : *ca->allowed_formats) { - log_to_dstr(log, ca.get(), "Trying format %s (0x%x)\n", - format_id_to_str(format_id), (uint32_t)format_id); + log_to_dstr(log, ca.get(), "Trying format %s (0x%x)\n", format_id_to_str(format_id), + (uint32_t)format_id); - if (!create_encoder(log, ca.get(), &in, &out, format_id, - bitrate, samplerate, rate_control)) + if (!create_encoder(log, ca.get(), &in, &out, format_id, bitrate, samplerate, rate_control)) continue; encoder_created = true; @@ -578,28 +527,22 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) OSStatus code; UInt32 converter_quality = kAudioConverterQuality_Max; - STATUS_CHECK(AudioConverterSetProperty( - ca->converter, kAudioConverterCodecQuality, - sizeof(converter_quality), &converter_quality)); + STATUS_CHECK(AudioConverterSetProperty(ca->converter, kAudioConverterCodecQuality, sizeof(converter_quality), + &converter_quality)); - STATUS_CHECK(AudioConverterSetProperty(ca->converter, - kAudioConverterEncodeBitRate, - sizeof(bitrate), &bitrate)); + STATUS_CHECK(AudioConverterSetProperty(ca->converter, kAudioConverterEncodeBitRate, sizeof(bitrate), &bitrate)); UInt32 size = sizeof(in); - STATUS_CHECK(AudioConverterGetProperty( - ca->converter, kAudioConverterCurrentInputStreamDescription, - &size, &in)); + STATUS_CHECK( + AudioConverterGetProperty(ca->converter, kAudioConverterCurrentInputStreamDescription, &size, &in)); size = sizeof(out); - STATUS_CHECK(AudioConverterGetProperty( - ca->converter, kAudioConverterCurrentOutputStreamDescription, - &size, &out)); + STATUS_CHECK( + AudioConverterGetProperty(ca->converter, kAudioConverterCurrentOutputStreamDescription, &size, &out)); AudioConverterPrimeInfo primeInfo; size = sizeof(primeInfo); - STATUS_CHECK(AudioConverterGetProperty( - ca->converter, kAudioConverterPrimeInfo, &size, &primeInfo)); + STATUS_CHECK(AudioConverterGetProperty(ca->converter, kAudioConverterPrimeInfo, &size, &primeInfo)); /* * Fix channel map differences between CoreAudio AAC, FFmpeg, Wav @@ -608,9 +551,7 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) if (ca->channels == 3) { SInt32 channelMap3[3] = {2, 0, 1}; - AudioConverterSetProperty(ca->converter, - kAudioConverterChannelMap, - sizeof(channelMap3), channelMap3); + AudioConverterSetProperty(ca->converter, kAudioConverterChannelMap, sizeof(channelMap3), channelMap3); } else if (ca->channels == 4) { /* @@ -620,34 +561,22 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) */ AudioChannelLayout inAcl = {0}; inAcl.mChannelLayoutTag = (116L << 16) | 4; - AudioConverterSetProperty(ca->converter, - kAudioConverterInputChannelLayout, - sizeof(inAcl), &inAcl); - AudioConverterSetProperty(ca->converter, - kAudioConverterOutputChannelLayout, - sizeof(inAcl), &inAcl); + AudioConverterSetProperty(ca->converter, kAudioConverterInputChannelLayout, sizeof(inAcl), &inAcl); + AudioConverterSetProperty(ca->converter, kAudioConverterOutputChannelLayout, sizeof(inAcl), &inAcl); SInt32 channelMap4[4] = {2, 0, 1, 3}; - AudioConverterSetProperty(ca->converter, - kAudioConverterChannelMap, - sizeof(channelMap4), channelMap4); + AudioConverterSetProperty(ca->converter, kAudioConverterChannelMap, sizeof(channelMap4), channelMap4); } else if (ca->channels == 5) { SInt32 channelMap5[5] = {2, 0, 1, 3, 4}; - AudioConverterSetProperty(ca->converter, - kAudioConverterChannelMap, - sizeof(channelMap5), channelMap5); + AudioConverterSetProperty(ca->converter, kAudioConverterChannelMap, sizeof(channelMap5), channelMap5); } else if (ca->channels == 6) { SInt32 channelMap6[6] = {2, 0, 1, 4, 5, 3}; - AudioConverterSetProperty(ca->converter, - kAudioConverterChannelMap, - sizeof(channelMap6), channelMap6); + AudioConverterSetProperty(ca->converter, kAudioConverterChannelMap, sizeof(channelMap6), channelMap6); } else if (ca->channels == 8) { SInt32 channelMap8[8] = {2, 0, 1, 6, 7, 4, 5, 3}; - AudioConverterSetProperty(ca->converter, - kAudioConverterChannelMap, - sizeof(channelMap8), channelMap8); + AudioConverterSetProperty(ca->converter, kAudioConverterChannelMap, sizeof(channelMap8), channelMap8); } ca->in_frame_size = in.mBytesPerFrame; @@ -663,14 +592,10 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) UInt32 max_packet_size = 0; size = sizeof(max_packet_size); - code = AudioConverterGetProperty( - ca->converter, - kAudioConverterPropertyMaximumOutputPacketSize, &size, - &max_packet_size); + code = AudioConverterGetProperty(ca->converter, kAudioConverterPropertyMaximumOutputPacketSize, &size, + &max_packet_size); if (code) { - log_osstatus(LOG_WARNING, ca.get(), - "AudioConverterGetProperty(PacketSz)", - code); + log_osstatus(LOG_WARNING, ca.get(), "AudioConverterGetProperty(PacketSz)", code); ca->output_buffer_size = 32768; } else { ca->output_buffer_size = max_packet_size; @@ -684,10 +609,9 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) return nullptr; } - const char *format_name = - out.mFormatID == kAudioFormatMPEG4AAC_HE_V2 ? "HE-AAC v2" - : out.mFormatID == kAudioFormatMPEG4AAC_HE ? "HE-AAC" - : "AAC"; + const char *format_name = out.mFormatID == kAudioFormatMPEG4AAC_HE_V2 ? "HE-AAC v2" + : out.mFormatID == kAudioFormatMPEG4AAC_HE ? "HE-AAC" + : "AAC"; CA_BLOG(LOG_INFO, "settings:\n" "\tmode: %s\n" @@ -695,21 +619,17 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) "\tsample rate: %llu\n" "\tcbr: %s\n" "\toutput buffer: %lu", - format_name, (unsigned int)bitrate / 1000, - ca->samples_per_second, - rate_control == kAudioCodecBitRateControlMode_Constant ? "on" - : "off", + format_name, (unsigned int)bitrate / 1000, ca->samples_per_second, + rate_control == kAudioCodecBitRateControlMode_Constant ? "on" : "off", (unsigned long)ca->output_buffer_size); return ca.release(); #undef STATUS_CHECK } -static OSStatus -complex_input_data_proc(AudioConverterRef inAudioConverter, - UInt32 *ioNumberDataPackets, AudioBufferList *ioData, - AudioStreamPacketDescription **outDataPacketDescription, - void *inUserData) +static OSStatus complex_input_data_proc(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, + AudioBufferList *ioData, + AudioStreamPacketDescription **outDataPacketDescription, void *inUserData) { UNUSED_PARAMETER(inAudioConverter); UNUSED_PARAMETER(outDataPacketDescription); @@ -727,8 +647,7 @@ complex_input_data_proc(AudioConverterRef inAudioConverter, ca->encode_buffer.assign(start, stop); ca->input_buffer.erase(start, stop); - *ioNumberDataPackets = - (UInt32)(ca->in_bytes_required / ca->in_frame_size); + *ioNumberDataPackets = (UInt32)(ca->in_bytes_required / ca->in_frame_size); ioData->mNumberBuffers = 1; ioData->mBuffers[0].mData = ca->encode_buffer.data(); @@ -744,13 +663,11 @@ complex_input_data_proc(AudioConverterRef inAudioConverter, #pragma warning(push) #pragma warning(disable : 4706) #endif -static bool aac_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool aac_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { ca_encoder *ca = static_cast(data); - ca->input_buffer.insert(end(ca->input_buffer), frame->data[0], - frame->data[0] + frame->linesize[0]); + ca->input_buffer.insert(end(ca->input_buffer), frame->data[0], frame->data[0] + frame->linesize[0]); if (ca->input_buffer.size() < ca->in_bytes_required) return true; @@ -765,12 +682,10 @@ static bool aac_encode(void *data, struct encoder_frame *frame, AudioStreamPacketDescription out_desc = {0}; - OSStatus code = AudioConverterFillComplexBuffer( - ca->converter, complex_input_data_proc, ca, &packets, - &buffer_list, &out_desc); + OSStatus code = AudioConverterFillComplexBuffer(ca->converter, complex_input_data_proc, ca, &packets, + &buffer_list, &out_desc); if (code && code != 1) { - log_osstatus(LOG_ERROR, ca, "AudioConverterFillComplexBuffer", - code); + log_osstatus(LOG_ERROR, ca, "AudioConverterFillComplexBuffer", code); return false; } @@ -784,8 +699,7 @@ static bool aac_encode(void *data, struct encoder_frame *frame, packet->type = OBS_ENCODER_AUDIO; packet->keyframe = true; packet->size = out_desc.mDataByteSize; - packet->data = (uint8_t *)buffer_list.mBuffers[0].mData + - out_desc.mStartOffset; + packet->data = (uint8_t *)buffer_list.mBuffers[0].mData + out_desc.mStartOffset; ca->total_samples += ca->in_bytes_required / ca->in_frame_size; @@ -835,8 +749,7 @@ static int read_descr(uint8_t **buffer, int *tag) } // based off of mov_read_esds from mov.c in ffmpeg's libavformat -static void read_esds_desc_ext(uint8_t *desc_ext, vector &buffer, - bool version_flags) +static void read_esds_desc_ext(uint8_t *desc_ext, vector &buffer, bool version_flags) { uint8_t *esds = desc_ext; int tag, len; @@ -873,13 +786,9 @@ static void query_extra_data(ca_encoder *ca) UInt32 size = 0; OSStatus code; - code = AudioConverterGetPropertyInfo( - ca->converter, kAudioConverterCompressionMagicCookie, &size, - NULL); + code = AudioConverterGetPropertyInfo(ca->converter, kAudioConverterCompressionMagicCookie, &size, NULL); if (code) { - log_osstatus(LOG_ERROR, ca, - "AudioConverterGetPropertyInfo(magic_cookie)", - code); + log_osstatus(LOG_ERROR, ca, "AudioConverterGetPropertyInfo(magic_cookie)", code); return; } @@ -897,12 +806,10 @@ static void query_extra_data(ca_encoder *ca) return; } - code = AudioConverterGetProperty(ca->converter, - kAudioConverterCompressionMagicCookie, - &size, extra_data.data()); + code = AudioConverterGetProperty(ca->converter, kAudioConverterCompressionMagicCookie, &size, + extra_data.data()); if (code) { - log_osstatus(LOG_ERROR, ca, - "AudioConverterGetProperty(magic_cookie)", code); + log_osstatus(LOG_ERROR, ca, "AudioConverterGetProperty(magic_cookie)", code); return; } @@ -929,9 +836,7 @@ static bool aac_extra_data(void *data, uint8_t **extra_data, size_t *size) return true; } -static asbd_builder fill_common_asbd_fields(asbd_builder builder, - bool in = false, - UInt32 channels = 2) +static asbd_builder fill_common_asbd_fields(asbd_builder builder, bool in = false, UInt32 channels = 2) { UInt32 bytes_per_frame = sizeof(float) * channels; UInt32 bits_per_channel = bytes_per_frame / channels * 8; @@ -953,35 +858,29 @@ static AudioStreamBasicDescription get_default_in_asbd() return fill_common_asbd_fields(asbd_builder(), true) .sample_rate(44100) .format_id(kAudioFormatLinearPCM) - .format_flags(kAudioFormatFlagsNativeEndian | - kAudioFormatFlagIsPacked | - kAudioFormatFlagIsFloat | 0) + .format_flags(kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsFloat | 0) .asbd; } static asbd_builder get_default_out_asbd_builder(UInt32 channels) { - return fill_common_asbd_fields(asbd_builder(), false, channels) - .sample_rate(44100); + return fill_common_asbd_fields(asbd_builder(), false, channels).sample_rate(44100); } -static cf_ptr -get_converter(DStr &log, ca_encoder *ca, AudioStreamBasicDescription out, - AudioStreamBasicDescription in = get_default_in_asbd()) +static cf_ptr get_converter(DStr &log, ca_encoder *ca, AudioStreamBasicDescription out, + AudioStreamBasicDescription in = get_default_in_asbd()) { UInt32 size = sizeof(out); OSStatus code; -#define STATUS_CHECK(x) \ - code = x; \ - if (code) { \ - log_to_dstr(log, ca, "%s: %s\n", #x, \ - osstatus_to_dstr(code)->array); \ - return nullptr; \ +#define STATUS_CHECK(x) \ + code = x; \ + if (code) { \ + log_to_dstr(log, ca, "%s: %s\n", #x, osstatus_to_dstr(code)->array); \ + return nullptr; \ } - STATUS_CHECK(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, - NULL, &size, &out)); + STATUS_CHECK(AudioFormatGetProperty(kAudioFormatProperty_FormatInfo, 0, NULL, &size, &out)); AudioConverterRef converter; STATUS_CHECK(AudioConverterNew(&in, &out, &converter)); @@ -990,8 +889,7 @@ get_converter(DStr &log, ca_encoder *ca, AudioStreamBasicDescription out, #undef STATUS_CHECK } -static bool find_best_match(DStr &log, ca_encoder *ca, UInt32 bitrate, - UInt32 &best_match) +static bool find_best_match(DStr &log, ca_encoder *ca, UInt32 bitrate, UInt32 &best_match) { UInt32 actual_bitrate = bitrate * 1000; bool found_match = false; @@ -999,8 +897,7 @@ static bool find_best_match(DStr &log, ca_encoder *ca, UInt32 bitrate, auto handle_bitrate = [&](UInt32 candidate) { if (abs(static_cast(actual_bitrate - candidate)) < abs(static_cast(actual_bitrate - best_match))) { - log_to_dstr(log, ca, "Found new best match %u\n", - static_cast(candidate)); + log_to_dstr(log, ca, "Found new best match %u\n", static_cast(candidate)); found_match = true; best_match = candidate; @@ -1013,20 +910,16 @@ static bool find_best_match(DStr &log, ca_encoder *ca, UInt32 bitrate, if (min_ == max_) return; - log_to_dstr(log, ca, "Got actual bit rate range: %u<->%u\n", - static_cast(min_), + log_to_dstr(log, ca, "Got actual bit rate range: %u<->%u\n", static_cast(min_), static_cast(max_)); handle_bitrate(max_); }; for (UInt32 format_id : aac_formats) { - log_to_dstr(log, ca, "Trying %s (0x%x)\n", - format_id_to_str(format_id), format_id); + log_to_dstr(log, ca, "Trying %s (0x%x)\n", format_id_to_str(format_id), format_id); - auto out = get_default_out_asbd_builder(2) - .format_id(format_id) - .asbd; + auto out = get_default_out_asbd_builder(2).format_id(format_id).asbd; auto converter = get_converter(log, ca, out); @@ -1065,8 +958,7 @@ static UInt32 find_matching_bitrate(UInt32 bitrate) CA_CO_DLOG(LOG_INFO, "Default bitrate (%u) isn't " "supported, returning %u as closest match", - static_cast(bitrate), - static_cast(match)); + static_cast(bitrate), static_cast(match)); return; } @@ -1083,23 +975,18 @@ static UInt32 find_matching_bitrate(UInt32 bitrate) static void aac_defaults(obs_data_t *settings) { obs_data_set_default_int(settings, "samplerate", 0); //match input - obs_data_set_default_int(settings, "bitrate", - find_matching_bitrate(128)); + obs_data_set_default_int(settings, "bitrate", find_matching_bitrate(128)); obs_data_set_default_bool(settings, "allow he-aac", true); } template -static bool -query_property_raw(DStr &log, ca_encoder *ca, AudioFormatPropertyID property, - const char *get_property_info, const char *get_property, - AudioStreamBasicDescription &desc, Func &&func) +static bool query_property_raw(DStr &log, ca_encoder *ca, AudioFormatPropertyID property, const char *get_property_info, + const char *get_property, AudioStreamBasicDescription &desc, Func &&func) { UInt32 size = 0; - OSStatus code = AudioFormatGetPropertyInfo( - property, sizeof(AudioStreamBasicDescription), &desc, &size); + OSStatus code = AudioFormatGetPropertyInfo(property, sizeof(AudioStreamBasicDescription), &desc, &size); if (code) { - log_to_dstr(log, ca, "%s: %s\n", get_property_info, - osstatus_to_dstr(code)->array); + log_to_dstr(log, ca, "%s: %s\n", get_property_info, osstatus_to_dstr(code)->array); return false; } @@ -1113,17 +1000,13 @@ query_property_raw(DStr &log, ca_encoder *ca, AudioFormatPropertyID property, try { buffer.resize(size); } catch (...) { - log_to_dstr(log, ca, "Failed to allocate %u bytes for %s\n", - static_cast(size), get_property); + log_to_dstr(log, ca, "Failed to allocate %u bytes for %s\n", static_cast(size), get_property); return false; } - code = AudioFormatGetProperty(property, - sizeof(AudioStreamBasicDescription), - &desc, &size, buffer.data()); + code = AudioFormatGetProperty(property, sizeof(AudioStreamBasicDescription), &desc, &size, buffer.data()); if (code) { - log_to_dstr(log, ca, "%s: %s\n", get_property, - osstatus_to_dstr(code)->array); + log_to_dstr(log, ca, "%s: %s\n", get_property, osstatus_to_dstr(code)->array); return false; } @@ -1132,14 +1015,10 @@ query_property_raw(DStr &log, ca_encoder *ca, AudioFormatPropertyID property, return true; } -#define EXPAND_PROPERTY_NAMES(x) \ - x, "AudioFormatGetPropertyInfo(" #x ")", \ - "AudioFormatGetProperty(" #x ")" +#define EXPAND_PROPERTY_NAMES(x) x, "AudioFormatGetPropertyInfo(" #x ")", "AudioFormatGetProperty(" #x ")" template -static bool enumerate_samplerates(DStr &log, ca_encoder *ca, - AudioStreamBasicDescription &desc, - Func &&func) +static bool enumerate_samplerates(DStr &log, ca_encoder *ca, AudioStreamBasicDescription &desc, Func &&func) { auto helper = [&](UInt32 size, void *data) { auto range = static_cast(data); @@ -1148,11 +1027,8 @@ static bool enumerate_samplerates(DStr &log, ca_encoder *ca, func(range[i]); }; - return query_property_raw( - log, ca, - EXPAND_PROPERTY_NAMES( - kAudioFormatProperty_AvailableEncodeSampleRates), - desc, helper); + return query_property_raw(log, ca, EXPAND_PROPERTY_NAMES(kAudioFormatProperty_AvailableEncodeSampleRates), desc, + helper); } #if 0 @@ -1182,14 +1058,11 @@ static vector get_samplerates(DStr &log, ca_encoder *ca) vector samplerates; auto handle_samplerate = [&](UInt32 rate) { - if (find(begin(samplerates), end(samplerates), rate) == - end(samplerates)) { - log_to_dstr(log, ca, "Adding sample rate %u\n", - static_cast(rate)); + if (find(begin(samplerates), end(samplerates), rate) == end(samplerates)) { + log_to_dstr(log, ca, "Adding sample rate %u\n", static_cast(rate)); samplerates.push_back(rate); } else { - log_to_dstr(log, ca, "Sample rate %u already added\n", - static_cast(rate)); + log_to_dstr(log, ca, "Sample rate %u already added\n", static_cast(rate)); } }; @@ -1202,17 +1075,14 @@ static vector get_samplerates(DStr &log, ca_encoder *ca) if (min_ == max_) return; - log_to_dstr(log, ca, "Got actual sample rate range: %u<->%u\n", - static_cast(min_), + log_to_dstr(log, ca, "Got actual sample rate range: %u<->%u\n", static_cast(min_), static_cast(max_)); handle_samplerate(max_); }; for (UInt32 format : (ca ? *ca->allowed_formats : aac_formats)) { - log_to_dstr(log, ca, "Trying %s (0x%x)\n", - format_id_to_str(format), - static_cast(format)); + log_to_dstr(log, ca, "Trying %s (0x%x)\n", format_id_to_str(format), static_cast(format)); auto asbd = asbd_builder().format_id(format).asbd; @@ -1224,8 +1094,7 @@ static vector get_samplerates(DStr &log, ca_encoder *ca) static void add_samplerates(obs_property_t *prop, ca_encoder *ca) { - obs_property_list_add_int(prop, obs_module_text("UseInputSampleRate"), - 0); + obs_property_list_add_int(prop, obs_module_text("UseInputSampleRate"), 0); DStr log; @@ -1250,8 +1119,7 @@ static void add_samplerates(obs_property_t *prop, ca_encoder *ca) #define NBSP "\xC2\xA0" -static vector get_bitrates(DStr &log, ca_encoder *ca, - Float64 samplerate) +static vector get_bitrates(DStr &log, ca_encoder *ca, Float64 samplerate) { vector bitrates; struct obs_audio_info aoi; @@ -1261,14 +1129,11 @@ static vector get_bitrates(DStr &log, ca_encoder *ca, channels = get_audio_channels(aoi.speakers); auto handle_bitrate = [&](UInt32 bitrate) { - if (find(begin(bitrates), end(bitrates), bitrate) == - end(bitrates)) { - log_to_dstr(log, ca, "Adding bitrate %u\n", - static_cast(bitrate)); + if (find(begin(bitrates), end(bitrates), bitrate) == end(bitrates)) { + log_to_dstr(log, ca, "Adding bitrate %u\n", static_cast(bitrate)); bitrates.push_back(bitrate); } else { - log_to_dstr(log, ca, "Bitrate %u already added\n", - static_cast(bitrate)); + log_to_dstr(log, ca, "Bitrate %u already added\n", static_cast(bitrate)); } }; @@ -1278,22 +1143,17 @@ static vector get_bitrates(DStr &log, ca_encoder *ca, if (min_ == max_) return; - log_to_dstr(log, ca, "Got actual bitrate range: %u<->%u\n", - static_cast(min_), + log_to_dstr(log, ca, "Got actual bitrate range: %u<->%u\n", static_cast(min_), static_cast(max_)); handle_bitrate(max_); }; for (UInt32 format_id : (ca ? *ca->allowed_formats : aac_formats)) { - log_to_dstr(log, ca, "Trying %s (0x%x) at %g" NBSP "hz\n", - format_id_to_str(format_id), + log_to_dstr(log, ca, "Trying %s (0x%x) at %g" NBSP "hz\n", format_id_to_str(format_id), static_cast(format_id), samplerate); - auto out = get_default_out_asbd_builder(channels) - .format_id(format_id) - .sample_rate(samplerate) - .asbd; + auto out = get_default_out_asbd_builder(channels).format_id(format_id).sample_rate(samplerate).asbd; auto converter = get_converter(log, ca, out); @@ -1304,9 +1164,7 @@ static vector get_bitrates(DStr &log, ca_encoder *ca, return bitrates; } -static void add_bitrates(obs_property_t *prop, ca_encoder *ca, - Float64 samplerate = 44100., - UInt32 *selected = nullptr) +static void add_bitrates(obs_property_t *prop, ca_encoder *ca, Float64 samplerate = 44100., UInt32 *selected = nullptr) { obs_property_list_clear(prop); @@ -1324,8 +1182,7 @@ static void add_bitrates(obs_property_t *prop, ca_encoder *ca, bool selected_in_range = true; if (selected) { - selected_in_range = find(begin(bitrates), end(bitrates), - *selected * 1000) != end(bitrates); + selected_in_range = find(begin(bitrates), end(bitrates), *selected * 1000) != end(bitrates); if (!selected_in_range) bitrates.push_back(*selected * 1000); @@ -1336,8 +1193,7 @@ static void add_bitrates(obs_property_t *prop, ca_encoder *ca, DStr buffer; for (UInt32 bitrate : bitrates) { dstr_printf(buffer, "%u", (uint32_t)bitrate / 1000); - size_t idx = obs_property_list_add_int(prop, buffer->array, - bitrate / 1000); + size_t idx = obs_property_list_add_int(prop, buffer->array, bitrate / 1000); if (selected_in_range || bitrate / 1000 != *selected) continue; @@ -1346,18 +1202,15 @@ static void add_bitrates(obs_property_t *prop, ca_encoder *ca, } } -static bool samplerate_updated(obs_properties_t *props, obs_property_t *prop, - obs_data_t *settings) +static bool samplerate_updated(obs_properties_t *props, obs_property_t *prop, obs_data_t *settings) { - auto samplerate = - static_cast(obs_data_get_int(settings, "samplerate")); + auto samplerate = static_cast(obs_data_get_int(settings, "samplerate")); if (!samplerate) samplerate = 44100; prop = obs_properties_get(props, "bitrate"); if (prop) { - auto bitrate = static_cast( - obs_data_get_int(settings, "bitrate")); + auto bitrate = static_cast(obs_data_get_int(settings, "bitrate")); add_bitrates(prop, nullptr, samplerate, &bitrate); @@ -1372,18 +1225,15 @@ static obs_properties_t *aac_properties(void *data) obs_properties_t *props = obs_properties_create(); - obs_property_t *sample_rates = obs_properties_add_list( - props, "samplerate", obs_module_text("OutputSamplerate"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *sample_rates = obs_properties_add_list(props, "samplerate", obs_module_text("OutputSamplerate"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(sample_rates, samplerate_updated); - obs_property_t *bit_rates = obs_properties_add_list( - props, "bitrate", obs_module_text("Bitrate"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *bit_rates = obs_properties_add_list(props, "bitrate", obs_module_text("Bitrate"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_bool(props, "allow he-aac", - obs_module_text("AllowHEAAC")); + obs_properties_add_bool(props, "allow he-aac", obs_module_text("AllowHEAAC")); if (data) { ca_encoder *ca = static_cast(data); diff --git a/plugins/coreaudio-encoder/windows-imports.h b/plugins/coreaudio-encoder/windows-imports.h index 8a400062a..41533be23 100644 --- a/plugins/coreaudio-encoder/windows-imports.h +++ b/plugins/coreaudio-encoder/windows-imports.h @@ -85,11 +85,10 @@ struct AudioConverterPrimeInfo { }; typedef struct AudioConverterPrimeInfo AudioConverterPrimeInfo; -typedef OSStatus (*AudioConverterComplexInputDataProc)( - AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, - AudioBufferList *ioData, - AudioStreamPacketDescription **outDataPacketDescription, - void *inUserData); +typedef OSStatus (*AudioConverterComplexInputDataProc)(AudioConverterRef inAudioConverter, UInt32 *ioNumberDataPackets, + AudioBufferList *ioData, + AudioStreamPacketDescription **outDataPacketDescription, + void *inUserData); enum { kAudioCodecPropertyNameCFString = 'lnam', @@ -321,46 +320,38 @@ enum { kAudioConverterErr_OutputSampleRateOutOfRange = '!osr', }; -typedef OSStatus (*AudioConverterNew_t)( - const AudioStreamBasicDescription *inSourceFormat, - const AudioStreamBasicDescription *inDestinationFormat, - AudioConverterRef *outAudioConverter); +typedef OSStatus (*AudioConverterNew_t)(const AudioStreamBasicDescription *inSourceFormat, + const AudioStreamBasicDescription *inDestinationFormat, + AudioConverterRef *outAudioConverter); typedef OSStatus (*AudioConverterDispose_t)(AudioConverterRef inAudioConverter); typedef OSStatus (*AudioConverterReset_t)(AudioConverterRef inAudioConverter); -typedef OSStatus (*AudioConverterGetProperty_t)( - AudioConverterRef inAudioConverter, - AudioConverterPropertyID inPropertyID, UInt32 *ioPropertyDataSize, - void *outPropertyData); +typedef OSStatus (*AudioConverterGetProperty_t)(AudioConverterRef inAudioConverter, + AudioConverterPropertyID inPropertyID, UInt32 *ioPropertyDataSize, + void *outPropertyData); -typedef OSStatus (*AudioConverterGetPropertyInfo_t)( - AudioConverterRef inAudioConverter, - AudioConverterPropertyID inPropertyID, UInt32 *outSize, - Boolean *outWritable); +typedef OSStatus (*AudioConverterGetPropertyInfo_t)(AudioConverterRef inAudioConverter, + AudioConverterPropertyID inPropertyID, UInt32 *outSize, + Boolean *outWritable); -typedef OSStatus (*AudioConverterSetProperty_t)( - AudioConverterRef inAudioConverter, - AudioConverterPropertyID inPropertyID, UInt32 inPropertyDataSize, - const void *inPropertyData); +typedef OSStatus (*AudioConverterSetProperty_t)(AudioConverterRef inAudioConverter, + AudioConverterPropertyID inPropertyID, UInt32 inPropertyDataSize, + const void *inPropertyData); -typedef OSStatus (*AudioConverterFillComplexBuffer_t)( - AudioConverterRef inAudioConverter, - AudioConverterComplexInputDataProc inInputDataProc, - void *inInputDataProcUserData, UInt32 *ioOutputDataPacketSize, - AudioBufferList *outOutputData, - AudioStreamPacketDescription *outPacketDescription); +typedef OSStatus (*AudioConverterFillComplexBuffer_t)(AudioConverterRef inAudioConverter, + AudioConverterComplexInputDataProc inInputDataProc, + void *inInputDataProcUserData, UInt32 *ioOutputDataPacketSize, + AudioBufferList *outOutputData, + AudioStreamPacketDescription *outPacketDescription); -typedef OSStatus (*AudioFormatGetProperty_t)(AudioFormatPropertyID inPropertyID, - UInt32 inSpecifierSize, - const void *inSpecifier, - UInt32 *ioPropertyDataSize, +typedef OSStatus (*AudioFormatGetProperty_t)(AudioFormatPropertyID inPropertyID, UInt32 inSpecifierSize, + const void *inSpecifier, UInt32 *ioPropertyDataSize, void *outPropertyData); -typedef OSStatus (*AudioFormatGetPropertyInfo_t)( - AudioFormatPropertyID inPropertyID, UInt32 inSpecifierSize, - const void *inSpecifier, UInt32 *outPropertyDataSize); +typedef OSStatus (*AudioFormatGetPropertyInfo_t)(AudioFormatPropertyID inPropertyID, UInt32 inSpecifierSize, + const void *inSpecifier, UInt32 *outPropertyDataSize); static AudioConverterNew_t AudioConverterNew = NULL; static AudioConverterDispose_t AudioConverterDispose = NULL; @@ -419,8 +410,7 @@ static bool load_lib(void) }; path_list_t path_list[] = { - {FOLDERID_ProgramFilesCommon, - L"Apple\\Apple Application Support"}, + {FOLDERID_ProgramFilesCommon, L"Apple\\Apple Application Support"}, {FOLDERID_ProgramFiles, L"iTunes"}, }; @@ -457,17 +447,14 @@ static bool load_core_audio(void) if (!load_lib()) return false; -#define LOAD_SYM_FROM_LIB(sym, lib, dll) \ - if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ - DWORD err = GetLastError(); \ - CA_LOG(LOG_ERROR, \ - "Couldn't load " #sym " from " dll ": %lu (0x%lx)", \ - err, err); \ - goto unload_everything; \ +#define LOAD_SYM_FROM_LIB(sym, lib, dll) \ + if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ + DWORD err = GetLastError(); \ + CA_LOG(LOG_ERROR, "Couldn't load " #sym " from " dll ": %lu (0x%lx)", err, err); \ + goto unload_everything; \ } -#define LOAD_SYM(sym) \ - LOAD_SYM_FROM_LIB(sym, audio_toolbox, "CoreAudioToolbox.dll") +#define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, audio_toolbox, "CoreAudioToolbox.dll") LOAD_SYM(AudioConverterNew); LOAD_SYM(AudioConverterDispose); LOAD_SYM(AudioConverterReset); diff --git a/plugins/decklink/DecklinkBase.cpp b/plugins/decklink/DecklinkBase.cpp index d41d10682..eaec78856 100644 --- a/plugins/decklink/DecklinkBase.cpp +++ b/plugins/decklink/DecklinkBase.cpp @@ -1,9 +1,6 @@ #include "DecklinkBase.h" -DecklinkBase::DecklinkBase(DeckLinkDeviceDiscovery *discovery_) - : discovery(discovery_) -{ -} +DecklinkBase::DecklinkBase(DeckLinkDeviceDiscovery *discovery_) : discovery(discovery_) {} DeckLinkDevice *DecklinkBase::GetDevice() const { @@ -15,8 +12,7 @@ bool DecklinkBase::Activate(DeckLinkDevice *, long long) return false; } -bool DecklinkBase::Activate(DeckLinkDevice *, long long, BMDVideoConnection, - BMDAudioConnection) +bool DecklinkBase::Activate(DeckLinkDevice *, long long, BMDVideoConnection, BMDAudioConnection) { return false; } diff --git a/plugins/decklink/DecklinkBase.h b/plugins/decklink/DecklinkBase.h index f8544d703..750cc0c51 100644 --- a/plugins/decklink/DecklinkBase.h +++ b/plugins/decklink/DecklinkBase.h @@ -27,8 +27,7 @@ protected: public: virtual bool Activate(DeckLinkDevice *device, long long modeId); - virtual bool Activate(DeckLinkDevice *device, long long modeId, - BMDVideoConnection bmdVideoConnection, + virtual bool Activate(DeckLinkDevice *device, long long modeId, BMDVideoConnection bmdVideoConnection, BMDAudioConnection bmdAudioConnection); virtual void Deactivate() = 0; diff --git a/plugins/decklink/DecklinkInput.cpp b/plugins/decklink/DecklinkInput.cpp index 7a28419b2..a0e14cce4 100644 --- a/plugins/decklink/DecklinkInput.cpp +++ b/plugins/decklink/DecklinkInput.cpp @@ -2,8 +2,7 @@ #include -DeckLinkInput::DeckLinkInput(obs_source_t *source, - DeckLinkDeviceDiscovery *discovery_) +DeckLinkInput::DeckLinkInput(obs_source_t *source, DeckLinkDeviceDiscovery *discovery_) : DecklinkBase(discovery_), source(source) { @@ -16,8 +15,7 @@ DeckLinkInput::~DeckLinkInput(void) Deactivate(); } -void DeckLinkInput::DevicesChanged(void *param, DeckLinkDevice *device, - bool added) +void DeckLinkInput::DevicesChanged(void *param, DeckLinkDevice *device, bool added) { DeckLinkInput *decklink = reinterpret_cast(param); std::lock_guard lock(decklink->deviceMutex); @@ -33,18 +31,15 @@ void DeckLinkInput::DevicesChanged(void *param, DeckLinkDevice *device, settings = obs_source_get_settings(decklink->source); hash = obs_data_get_string(settings, "device_hash"); - videoConnection = (BMDVideoConnection)obs_data_get_int( - settings, "video_connection"); - audioConnection = (BMDAudioConnection)obs_data_get_int( - settings, "audio_connection"); + videoConnection = (BMDVideoConnection)obs_data_get_int(settings, "video_connection"); + audioConnection = (BMDAudioConnection)obs_data_get_int(settings, "audio_connection"); mode = obs_data_get_int(settings, "mode_id"); obs_data_release(settings); if (device->GetHash().compare(hash) == 0) { if (!decklink->activateRefs) return; - if (decklink->Activate(device, mode, videoConnection, - audioConnection)) + if (decklink->Activate(device, mode, videoConnection, audioConnection)) os_atomic_dec_long(&decklink->activateRefs); } @@ -56,8 +51,7 @@ void DeckLinkInput::DevicesChanged(void *param, DeckLinkDevice *device, } } -bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, - BMDVideoConnection bmdVideoConnection, +bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, BMDVideoConnection bmdVideoConnection, BMDAudioConnection bmdAudioConnection) { std::lock_guard lock(deviceMutex); @@ -68,14 +62,11 @@ bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, if (same) { if (!isActive) return false; - if (instance->GetActiveModeId() == modeId && - instance->GetVideoConnection() == bmdVideoConnection && + if (instance->GetActiveModeId() == modeId && instance->GetVideoConnection() == bmdVideoConnection && instance->GetAudioConnection() == bmdAudioConnection && - instance->GetActivePixelFormat() == pixelFormat && - instance->GetActiveColorSpace() == colorSpace && + instance->GetActivePixelFormat() == pixelFormat && instance->GetActiveColorSpace() == colorSpace && instance->GetActiveColorRange() == colorRange && - instance->GetActiveChannelFormat() == channelFormat && - instance->GetActiveSwapState() == swap) + instance->GetActiveChannelFormat() == channelFormat && instance->GetActiveSwapState() == swap) return false; } @@ -90,8 +81,7 @@ bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, return false; if (GetDevice() == nullptr) { - LOG(LOG_ERROR, - "Tried to activate an input with nullptr device."); + LOG(LOG_ERROR, "Tried to activate an input with nullptr device."); return false; } @@ -101,8 +91,7 @@ bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, return false; } - if (!instance->StartCapture(mode, allow10Bit, bmdVideoConnection, - bmdAudioConnection)) { + if (!instance->StartCapture(mode, allow10Bit, bmdVideoConnection, bmdAudioConnection)) { instance = nullptr; return false; } @@ -141,8 +130,7 @@ void DeckLinkInput::SaveSettings() obs_data_t *settings = obs_source_get_settings(source); obs_data_set_string(settings, "device_hash", device->GetHash().c_str()); - obs_data_set_string(settings, "device_name", - device->GetDisplayName().c_str()); + obs_data_set_string(settings, "device_name", device->GetDisplayName().c_str()); obs_data_set_int(settings, "mode_id", instance->GetActiveModeId()); obs_data_set_string(settings, "mode_name", mode->GetName().c_str()); diff --git a/plugins/decklink/DecklinkInput.hpp b/plugins/decklink/DecklinkInput.hpp index a030f7545..d7f58ee60 100644 --- a/plugins/decklink/DecklinkInput.hpp +++ b/plugins/decklink/DecklinkInput.hpp @@ -8,8 +8,7 @@ protected: obs_source_t *source; void SaveSettings(); - static void DevicesChanged(void *param, DeckLinkDevice *device, - bool added); + static void DevicesChanged(void *param, DeckLinkDevice *device, bool added); public: DeckLinkInput(obs_source_t *source, DeckLinkDeviceDiscovery *discovery); @@ -19,28 +18,15 @@ public: obs_source_t *GetSource(void) const; inline BMDPixelFormat GetPixelFormat() const { return pixelFormat; } - inline void SetPixelFormat(BMDPixelFormat format) - { - pixelFormat = format; - } + inline void SetPixelFormat(BMDPixelFormat format) { pixelFormat = format; } inline video_colorspace GetColorSpace() const { return colorSpace; } - inline void SetColorSpace(video_colorspace format) - { - colorSpace = format; - } + inline void SetColorSpace(video_colorspace format) { colorSpace = format; } inline video_range_type GetColorRange() const { return colorRange; } - inline void SetColorRange(video_range_type format) - { - colorRange = format; - } + inline void SetColorRange(video_range_type format) { colorRange = format; } inline speaker_layout GetChannelFormat() const { return channelFormat; } - inline void SetChannelFormat(speaker_layout format) - { - channelFormat = format; - } + inline void SetChannelFormat(speaker_layout format) { channelFormat = format; } - bool Activate(DeckLinkDevice *device, long long modeId, - BMDVideoConnection bmdVideoConnection, + bool Activate(DeckLinkDevice *device, long long modeId, BMDVideoConnection bmdVideoConnection, BMDAudioConnection bmdAudioConnection) override; void Deactivate() override; bool Capturing(); diff --git a/plugins/decklink/DecklinkOutput.cpp b/plugins/decklink/DecklinkOutput.cpp index c7e6523a0..e563aabb2 100644 --- a/plugins/decklink/DecklinkOutput.cpp +++ b/plugins/decklink/DecklinkOutput.cpp @@ -2,8 +2,7 @@ #include -DeckLinkOutput::DeckLinkOutput(obs_output_t *output, - DeckLinkDeviceDiscovery *discovery_) +DeckLinkOutput::DeckLinkOutput(obs_output_t *output, DeckLinkDeviceDiscovery *discovery_) : DecklinkBase(discovery_), output(output) { @@ -35,10 +34,8 @@ bool DeckLinkOutput::Activate(DeckLinkDevice *device, long long modeId) if (!isActive) return false; - if (instance->GetActiveModeId() == modeId && - instance->GetActivePixelFormat() == pixelFormat && - instance->GetActiveColorSpace() == colorSpace && - instance->GetActiveColorRange() == colorRange && + if (instance->GetActiveModeId() == modeId && instance->GetActivePixelFormat() == pixelFormat && + instance->GetActiveColorSpace() == colorSpace && instance->GetActiveColorRange() == colorRange && instance->GetActiveChannelFormat() == channelFormat) return false; } diff --git a/plugins/decklink/DecklinkOutput.hpp b/plugins/decklink/DecklinkOutput.hpp index f50f234f9..2627937c8 100644 --- a/plugins/decklink/DecklinkOutput.hpp +++ b/plugins/decklink/DecklinkOutput.hpp @@ -10,8 +10,7 @@ protected: int width; int height; - static void DevicesChanged(void *param, DeckLinkDevice *device, - bool added); + static void DevicesChanged(void *param, DeckLinkDevice *device, bool added); public: const char *deviceHash; @@ -23,8 +22,7 @@ public: int keyerMode; bool force_sdr; - DeckLinkOutput(obs_output_t *output, - DeckLinkDeviceDiscovery *discovery); + DeckLinkOutput(obs_output_t *output, DeckLinkDeviceDiscovery *discovery); virtual ~DeckLinkOutput(void); obs_output_t *GetOutput(void) const; bool Activate(DeckLinkDevice *device, long long modeId) override; diff --git a/plugins/decklink/OBSVideoFrame.cpp b/plugins/decklink/OBSVideoFrame.cpp index ce4affdd4..614b309c0 100644 --- a/plugins/decklink/OBSVideoFrame.cpp +++ b/plugins/decklink/OBSVideoFrame.cpp @@ -1,7 +1,6 @@ #include "OBSVideoFrame.h" -OBSVideoFrame::OBSVideoFrame(long width, long height, - BMDPixelFormat pixelFormat) +OBSVideoFrame::OBSVideoFrame(long width, long height, BMDPixelFormat pixelFormat) { int bpp = 2; this->width = width; @@ -22,8 +21,7 @@ HRESULT OBSVideoFrame::SetFlags(BMDFrameFlags newFlags) return S_OK; } -HRESULT OBSVideoFrame::SetTimecode(BMDTimecodeFormat format, - IDeckLinkTimecode *timecode) +HRESULT OBSVideoFrame::SetTimecode(BMDTimecodeFormat format, IDeckLinkTimecode *timecode) { UNUSED_PARAMETER(format); UNUSED_PARAMETER(timecode); @@ -31,10 +29,8 @@ HRESULT OBSVideoFrame::SetTimecode(BMDTimecodeFormat format, } HRESULT -OBSVideoFrame::SetTimecodeFromComponents(BMDTimecodeFormat format, - uint8_t hours, uint8_t minutes, - uint8_t seconds, uint8_t frames, - BMDTimecodeFlags flags) +OBSVideoFrame::SetTimecodeFromComponents(BMDTimecodeFormat format, uint8_t hours, uint8_t minutes, uint8_t seconds, + uint8_t frames, BMDTimecodeFlags flags) { UNUSED_PARAMETER(format); UNUSED_PARAMETER(hours); @@ -51,8 +47,7 @@ HRESULT OBSVideoFrame::SetAncillaryData(IDeckLinkVideoFrameAncillary *ancillary) return 0; } -HRESULT OBSVideoFrame::SetTimecodeUserBits(BMDTimecodeFormat format, - BMDTimecodeUserBits userBits) +HRESULT OBSVideoFrame::SetTimecodeUserBits(BMDTimecodeFormat format, BMDTimecodeUserBits userBits) { UNUSED_PARAMETER(format); UNUSED_PARAMETER(userBits); @@ -92,11 +87,7 @@ HRESULT OBSVideoFrame::GetBytes(void **buffer) #define CompareREFIID(iid1, iid2) (memcmp(&iid1, &iid2, sizeof(REFIID)) == 0) -HDRVideoFrame::HDRVideoFrame(IDeckLinkMutableVideoFrame *frame) - : m_videoFrame(frame), - m_refCount(1) -{ -} +HDRVideoFrame::HDRVideoFrame(IDeckLinkMutableVideoFrame *frame) : m_videoFrame(frame), m_refCount(1) {} HRESULT HDRVideoFrame::QueryInterface(REFIID iid, LPVOID *ppv) { @@ -109,8 +100,7 @@ HRESULT HDRVideoFrame::QueryInterface(REFIID iid, LPVOID *ppv) else if (CompareREFIID(iid, IID_IDeckLinkVideoFrame)) *ppv = static_cast(this); else if (CompareREFIID(iid, IID_IDeckLinkVideoFrameMetadataExtensions)) - *ppv = static_cast( - this); + *ppv = static_cast(this); else { *ppv = nullptr; return E_NOINTERFACE; @@ -135,8 +125,7 @@ ULONG HDRVideoFrame::Release(void) return newRefValue; } -HRESULT HDRVideoFrame::GetInt(BMDDeckLinkFrameMetadataID metadataID, - int64_t *value) +HRESULT HDRVideoFrame::GetInt(BMDDeckLinkFrameMetadataID metadataID, int64_t *value) { HRESULT result = S_OK; @@ -157,8 +146,7 @@ HRESULT HDRVideoFrame::GetInt(BMDDeckLinkFrameMetadataID metadataID, return result; } -HRESULT HDRVideoFrame::GetFloat(BMDDeckLinkFrameMetadataID metadataID, - double *value) +HRESULT HDRVideoFrame::GetFloat(BMDDeckLinkFrameMetadataID metadataID, double *value) { HRESULT result = S_OK; @@ -224,15 +212,13 @@ HRESULT HDRVideoFrame::GetFlag(BMDDeckLinkFrameMetadataID, decklink_bool_t *) return E_INVALIDARG; } -HRESULT HDRVideoFrame::GetString(BMDDeckLinkFrameMetadataID, - decklink_string_t *) +HRESULT HDRVideoFrame::GetString(BMDDeckLinkFrameMetadataID, decklink_string_t *) { // Not expecting GetString return E_INVALIDARG; } -HRESULT HDRVideoFrame::GetBytes(BMDDeckLinkFrameMetadataID, void *, - uint32_t *bufferSize) +HRESULT HDRVideoFrame::GetBytes(BMDDeckLinkFrameMetadataID, void *, uint32_t *bufferSize) { *bufferSize = 0; // Not expecting GetBytes diff --git a/plugins/decklink/OBSVideoFrame.h b/plugins/decklink/OBSVideoFrame.h index fe92cacb5..b6c09e6d9 100644 --- a/plugins/decklink/OBSVideoFrame.h +++ b/plugins/decklink/OBSVideoFrame.h @@ -21,21 +21,17 @@ public: HRESULT STDMETHODCALLTYPE SetFlags(BMDFrameFlags newFlags) override; - HRESULT STDMETHODCALLTYPE SetTimecode( - BMDTimecodeFormat format, IDeckLinkTimecode *timecode) override; + HRESULT STDMETHODCALLTYPE SetTimecode(BMDTimecodeFormat format, IDeckLinkTimecode *timecode) override; - HRESULT STDMETHODCALLTYPE SetTimecodeFromComponents( - BMDTimecodeFormat format, uint8_t hours, uint8_t minutes, - uint8_t seconds, uint8_t frames, - BMDTimecodeFlags flags) override; + HRESULT STDMETHODCALLTYPE SetTimecodeFromComponents(BMDTimecodeFormat format, uint8_t hours, uint8_t minutes, + uint8_t seconds, uint8_t frames, + BMDTimecodeFlags flags) override; HRESULT STDMETHODCALLTYPE SetAncillaryData(IDeckLinkVideoFrameAncillary *ancillary) override; - HRESULT STDMETHODCALLTYPE - SetTimecodeUserBits(BMDTimecodeFormat format, - BMDTimecodeUserBits userBits) override; + HRESULT STDMETHODCALLTYPE SetTimecodeUserBits(BMDTimecodeFormat format, BMDTimecodeUserBits userBits) override; long STDMETHODCALLTYPE GetWidth() override; @@ -50,9 +46,8 @@ public: HRESULT STDMETHODCALLTYPE GetBytes(void **buffer) override; //Dummy implementations of remaining virtual methods - virtual HRESULT STDMETHODCALLTYPE - GetTimecode(/* in */ BMDTimecodeFormat format, - /* out */ IDeckLinkTimecode **timecode) override + virtual HRESULT STDMETHODCALLTYPE GetTimecode(/* in */ BMDTimecodeFormat format, + /* out */ IDeckLinkTimecode **timecode) override { UNUSED_PARAMETER(format); UNUSED_PARAMETER(timecode); @@ -66,8 +61,7 @@ public: }; // IUnknown interface (dummy implementation) - virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, - LPVOID *ppv) override + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv) override { UNUSED_PARAMETER(iid); UNUSED_PARAMETER(ppv); @@ -77,67 +71,42 @@ public: virtual ULONG STDMETHODCALLTYPE Release() override { return 1; } }; -class HDRVideoFrame : public IDeckLinkVideoFrame, - public IDeckLinkVideoFrameMetadataExtensions { +class HDRVideoFrame : public IDeckLinkVideoFrame, public IDeckLinkVideoFrameMetadataExtensions { public: HDRVideoFrame(IDeckLinkMutableVideoFrame *frame); virtual ~HDRVideoFrame() {} // IUnknown interface - virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, - LPVOID *ppv); + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv); virtual ULONG STDMETHODCALLTYPE AddRef(void); virtual ULONG STDMETHODCALLTYPE Release(void); // IDeckLinkVideoFrame interface - virtual long STDMETHODCALLTYPE GetWidth(void) - { - return m_videoFrame->GetWidth(); - } - virtual long STDMETHODCALLTYPE GetHeight(void) - { - return m_videoFrame->GetHeight(); - } - virtual long STDMETHODCALLTYPE GetRowBytes(void) - { - return m_videoFrame->GetRowBytes(); - } - virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void) - { - return m_videoFrame->GetPixelFormat(); - } + virtual long STDMETHODCALLTYPE GetWidth(void) { return m_videoFrame->GetWidth(); } + virtual long STDMETHODCALLTYPE GetHeight(void) { return m_videoFrame->GetHeight(); } + virtual long STDMETHODCALLTYPE GetRowBytes(void) { return m_videoFrame->GetRowBytes(); } + virtual BMDPixelFormat STDMETHODCALLTYPE GetPixelFormat(void) { return m_videoFrame->GetPixelFormat(); } virtual BMDFrameFlags STDMETHODCALLTYPE GetFlags(void) { return m_videoFrame->GetFlags() | bmdFrameContainsHDRMetadata; } - virtual HRESULT STDMETHODCALLTYPE GetBytes(void **buffer) - { - return m_videoFrame->GetBytes(buffer); - } - virtual HRESULT STDMETHODCALLTYPE - GetTimecode(BMDTimecodeFormat format, IDeckLinkTimecode **timecode) + virtual HRESULT STDMETHODCALLTYPE GetBytes(void **buffer) { return m_videoFrame->GetBytes(buffer); } + virtual HRESULT STDMETHODCALLTYPE GetTimecode(BMDTimecodeFormat format, IDeckLinkTimecode **timecode) { return m_videoFrame->GetTimecode(format, timecode); } - virtual HRESULT STDMETHODCALLTYPE - GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary) + virtual HRESULT STDMETHODCALLTYPE GetAncillaryData(IDeckLinkVideoFrameAncillary **ancillary) { return m_videoFrame->GetAncillaryData(ancillary); } // IDeckLinkVideoFrameMetadataExtensions interface - virtual HRESULT STDMETHODCALLTYPE - GetInt(BMDDeckLinkFrameMetadataID metadataID, int64_t *value); - virtual HRESULT STDMETHODCALLTYPE - GetFloat(BMDDeckLinkFrameMetadataID metadataID, double *value); - virtual HRESULT STDMETHODCALLTYPE - GetFlag(BMDDeckLinkFrameMetadataID metadataID, decklink_bool_t *value); - virtual HRESULT STDMETHODCALLTYPE - GetString(BMDDeckLinkFrameMetadataID metadataID, - decklink_string_t *value); - virtual HRESULT STDMETHODCALLTYPE - GetBytes(BMDDeckLinkFrameMetadataID metadataID, void *buffer, - uint32_t *bufferSize); + virtual HRESULT STDMETHODCALLTYPE GetInt(BMDDeckLinkFrameMetadataID metadataID, int64_t *value); + virtual HRESULT STDMETHODCALLTYPE GetFloat(BMDDeckLinkFrameMetadataID metadataID, double *value); + virtual HRESULT STDMETHODCALLTYPE GetFlag(BMDDeckLinkFrameMetadataID metadataID, decklink_bool_t *value); + virtual HRESULT STDMETHODCALLTYPE GetString(BMDDeckLinkFrameMetadataID metadataID, decklink_string_t *value); + virtual HRESULT STDMETHODCALLTYPE GetBytes(BMDDeckLinkFrameMetadataID metadataID, void *buffer, + uint32_t *bufferSize); private: ComPtr m_videoFrame; diff --git a/plugins/decklink/audio-repack.c b/plugins/decklink/audio-repack.c index b5968dd27..673f207d2 100644 --- a/plugins/decklink/audio-repack.c +++ b/plugins/decklink/audio-repack.c @@ -4,12 +4,10 @@ int check_buffer(struct audio_repack *repack, uint32_t frame_count) { - const uint32_t new_size = - frame_count * repack->base_dst_size + repack->extra_dst_size; + const uint32_t new_size = frame_count * repack->base_dst_size + repack->extra_dst_size; if (repack->packet_size < new_size) { - repack->packet_buffer = - brealloc(repack->packet_buffer, new_size); + repack->packet_buffer = brealloc(repack->packet_buffer, new_size); if (!repack->packet_buffer) return -1; @@ -29,8 +27,7 @@ int check_buffer(struct audio_repack *repack, uint32_t frame_count) * | FL | FR | LFE | */ -int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; @@ -54,8 +51,7 @@ int repack_squash(struct audio_repack *repack, const uint8_t *bsrc, return 0; } -int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, - uint32_t frame_count) +int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, uint32_t frame_count) { if (check_buffer(repack, frame_count) < 0) return -1; @@ -65,16 +61,14 @@ int repack_squash_swap(struct audio_repack *repack, const uint8_t *bsrc, uint16_t *dst = (uint16_t *)repack->packet_buffer; while (src != esrc) { __m128i target = _mm_load_si128(src++); - __m128i buf = - _mm_shufflelo_epi16(target, _MM_SHUFFLE(2, 3, 1, 0)); + __m128i buf = _mm_shufflelo_epi16(target, _MM_SHUFFLE(2, 3, 1, 0)); _mm_storeu_si128((__m128i *)dst, buf); dst += 8 - squash; } return 0; } -int audio_repack_init(struct audio_repack *repack, - audio_repack_mode_t repack_mode, uint8_t sample_bit) +int audio_repack_init(struct audio_repack *repack, audio_repack_mode_t repack_mode, uint8_t sample_bit) { memset(repack, 0, sizeof(*repack)); @@ -85,8 +79,7 @@ int audio_repack_init(struct audio_repack *repack, repack->base_dst_size = _audio_repack_ch[repack_mode] * (16 / 8); repack->extra_dst_size = 8 - _audio_repack_ch[repack_mode]; repack->repack_func = &repack_squash; - if (repack_mode == repack_mode_8to5ch_swap || - repack_mode == repack_mode_8to6ch_swap || + if (repack_mode == repack_mode_8to5ch_swap || repack_mode == repack_mode_8to6ch_swap || repack_mode == repack_mode_8ch_swap) repack->repack_func = &repack_squash_swap; diff --git a/plugins/decklink/audio-repack.h b/plugins/decklink/audio-repack.h index abe383be3..5ff310e94 100644 --- a/plugins/decklink/audio-repack.h +++ b/plugins/decklink/audio-repack.h @@ -11,8 +11,7 @@ extern "C" { struct audio_repack; -typedef int (*audio_repack_func_t)(struct audio_repack *, const uint8_t *, - uint32_t); +typedef int (*audio_repack_func_t)(struct audio_repack *, const uint8_t *, uint32_t); struct audio_repack { uint8_t *packet_buffer; @@ -38,9 +37,7 @@ enum _audio_repack_mode { typedef enum _audio_repack_mode audio_repack_mode_t; -extern int audio_repack_init(struct audio_repack *repack, - audio_repack_mode_t repack_mode, - uint8_t sample_bit); +extern int audio_repack_init(struct audio_repack *repack, audio_repack_mode_t repack_mode, uint8_t sample_bit); extern void audio_repack_free(struct audio_repack *repack); #ifdef __cplusplus diff --git a/plugins/decklink/audio-repack.hpp b/plugins/decklink/audio-repack.hpp index 69e9365c6..c4e1de5a8 100644 --- a/plugins/decklink/audio-repack.hpp +++ b/plugins/decklink/audio-repack.hpp @@ -6,10 +6,7 @@ class AudioRepacker { struct audio_repack arepack; public: - inline AudioRepacker(audio_repack_mode_t repack_mode) - { - audio_repack_init(&arepack, repack_mode, 16); - } + inline AudioRepacker(audio_repack_mode_t repack_mode) { audio_repack_init(&arepack, repack_mode, 16); } inline ~AudioRepacker() { audio_repack_free(&arepack); } inline int repack(const uint8_t *src, uint32_t frame_size) diff --git a/plugins/decklink/decklink-device-discovery.cpp b/plugins/decklink/decklink-device-discovery.cpp index 28e5ee247..b25a3ee83 100644 --- a/plugins/decklink/decklink-device-discovery.cpp +++ b/plugins/decklink/decklink-device-discovery.cpp @@ -54,8 +54,7 @@ DeckLinkDevice *DeckLinkDeviceDiscovery::FindByHash(const char *hash) return ret; } -HRESULT STDMETHODCALLTYPE -DeckLinkDeviceDiscovery::DeckLinkDeviceArrived(IDeckLink *device) +HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::DeckLinkDeviceArrived(IDeckLink *device) { DeckLinkDevice *newDev = new DeckLinkDevice(device); if (!newDev->Init()) { @@ -73,8 +72,7 @@ DeckLinkDeviceDiscovery::DeckLinkDeviceArrived(IDeckLink *device) return S_OK; } -HRESULT STDMETHODCALLTYPE -DeckLinkDeviceDiscovery::DeckLinkDeviceRemoved(IDeckLink *device) +HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::DeckLinkDeviceRemoved(IDeckLink *device) { std::lock_guard lock(deviceMutex); @@ -97,8 +95,7 @@ ULONG STDMETHODCALLTYPE DeckLinkDeviceDiscovery::AddRef(void) return os_atomic_inc_long(&refCount); } -HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::QueryInterface(REFIID iid, - LPVOID *ppv) +HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::QueryInterface(REFIID iid, LPVOID *ppv) { HRESULT result = E_NOINTERFACE; @@ -109,8 +106,7 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::QueryInterface(REFIID iid, *ppv = this; AddRef(); result = S_OK; - } else if (memcmp(&iid, &IID_IDeckLinkDeviceNotificationCallback, - sizeof(REFIID)) == 0) { + } else if (memcmp(&iid, &IID_IDeckLinkDeviceNotificationCallback, sizeof(REFIID)) == 0) { *ppv = (IDeckLinkDeviceNotificationCallback *)this; AddRef(); result = S_OK; diff --git a/plugins/decklink/decklink-device-discovery.hpp b/plugins/decklink/decklink-device-discovery.hpp index 6f62f77aa..9822f82c6 100644 --- a/plugins/decklink/decklink-device-discovery.hpp +++ b/plugins/decklink/decklink-device-discovery.hpp @@ -8,8 +8,7 @@ class DeckLinkDevice; -typedef void (*DeviceChangeCallback)(void *param, DeckLinkDevice *device, - bool added); +typedef void (*DeviceChangeCallback)(void *param, DeckLinkDevice *device, bool added); struct DeviceChangeInfo { DeviceChangeCallback callback; @@ -58,8 +57,7 @@ public: for (size_t i = 0; i < callbacks.size(); i++) { DeviceChangeInfo &curCB = callbacks[i]; - if (curCB.callback == callback && - curCB.param == param) { + if (curCB.callback == callback && curCB.param == param) { callbacks.erase(callbacks.begin() + i); return; } @@ -70,10 +68,7 @@ public: inline void Lock() { deviceMutex.lock(); } inline void Unlock() { deviceMutex.unlock(); } - inline const std::vector &GetDevices() const - { - return devices; - } + inline const std::vector &GetDevices() const { return devices; } ULONG STDMETHODCALLTYPE AddRef(void); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv); diff --git a/plugins/decklink/decklink-device-instance.cpp b/plugins/decklink/decklink-device-instance.cpp index c903e0a5b..3c5de5d19 100644 --- a/plugins/decklink/decklink-device-instance.cpp +++ b/plugins/decklink/decklink-device-instance.cpp @@ -24,8 +24,7 @@ template RenderDelegate::RenderDelegate(T *pOwner) template RenderDelegate::~RenderDelegate() {} -template -HRESULT RenderDelegate::QueryInterface(REFIID, LPVOID *ppv) +template HRESULT RenderDelegate::QueryInterface(REFIID, LPVOID *ppv) { *ppv = NULL; return E_NOINTERFACE; @@ -48,9 +47,7 @@ template ULONG RenderDelegate::Release() } template -HRESULT -RenderDelegate::ScheduledFrameCompleted(IDeckLinkVideoFrame *completedFrame, - BMDOutputFrameCompletionResult) +HRESULT RenderDelegate::ScheduledFrameCompleted(IDeckLinkVideoFrame *completedFrame, BMDOutputFrameCompletionResult) { m_pOwner->ScheduleVideoFrame(completedFrame); return S_OK; @@ -92,8 +89,7 @@ static inline int ConvertChannelFormat(speaker_layout format) } } -static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format, - bool swap) +static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format, bool swap) { switch (format) { case SPEAKERS_2POINT1: @@ -112,8 +108,7 @@ static inline audio_repack_mode_t ConvertRepackFormat(speaker_layout format, } } -DeckLinkDeviceInstance::DeckLinkDeviceInstance(DecklinkBase *decklink_, - DeckLinkDevice *device_) +DeckLinkDeviceInstance::DeckLinkDeviceInstance(DecklinkBase *decklink_, DeckLinkDevice *device_) : currentFrame(), currentPacket(), currentCaptions(), @@ -132,8 +127,7 @@ DeckLinkDeviceInstance::~DeckLinkDeviceInstance() } } -void DeckLinkDeviceInstance::HandleAudioPacket( - IDeckLinkAudioInputPacket *audioPacket, const uint64_t timestamp) +void DeckLinkDeviceInstance::HandleAudioPacket(IDeckLinkAudioInputPacket *audioPacket, const uint64_t timestamp) { if (audioPacket == nullptr) return; @@ -144,25 +138,19 @@ void DeckLinkDeviceInstance::HandleAudioPacket( return; } - const uint32_t frameCount = - (uint32_t)audioPacket->GetSampleFrameCount(); + const uint32_t frameCount = (uint32_t)audioPacket->GetSampleFrameCount(); currentPacket.frames = frameCount; currentPacket.timestamp = timestamp; if (decklink && !static_cast(decklink)->buffering) { currentPacket.timestamp = os_gettime_ns(); - currentPacket.timestamp -= - util_mul_div64(frameCount, 1000000000ULL, - currentPacket.samples_per_sec); + currentPacket.timestamp -= util_mul_div64(frameCount, 1000000000ULL, currentPacket.samples_per_sec); } int maxdevicechannel = device->GetMaxChannel(); - if (channelFormat != SPEAKERS_UNKNOWN && - channelFormat != SPEAKERS_MONO && - channelFormat != SPEAKERS_STEREO && - (channelFormat != SPEAKERS_7POINT1 || - static_cast(decklink)->swap) && + if (channelFormat != SPEAKERS_UNKNOWN && channelFormat != SPEAKERS_MONO && channelFormat != SPEAKERS_STEREO && + (channelFormat != SPEAKERS_7POINT1 || static_cast(decklink)->swap) && maxdevicechannel >= 8) { if (audioRepacker->repack((uint8_t *)bytes, frameCount) < 0) { @@ -174,24 +162,19 @@ void DeckLinkDeviceInstance::HandleAudioPacket( currentPacket.data[0] = (uint8_t *)bytes; } - nextAudioTS = timestamp + - util_mul_div64(frameCount, 1000000000ULL, 48000ULL) + 1; + nextAudioTS = timestamp + util_mul_div64(frameCount, 1000000000ULL, 48000ULL) + 1; - obs_source_output_audio( - static_cast(decklink)->GetSource(), - ¤tPacket); + obs_source_output_audio(static_cast(decklink)->GetSource(), ¤tPacket); } -void DeckLinkDeviceInstance::HandleVideoFrame( - IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp) +void DeckLinkDeviceInstance::HandleVideoFrame(IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp) { if (videoFrame == nullptr) return; ComPtr packets; - if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets, - (void **)&packets) == S_OK) { + if (videoFrame->QueryInterface(IID_IDeckLinkVideoFrameAncillaryPackets, (void **)&packets) == S_OK) { ComPtr iterator; packets->GetPacketIterator(&iterator); @@ -239,13 +222,11 @@ void DeckLinkDeviceInstance::HandleVideoFrame( enum video_trc trc = VIDEO_TRC_DEFAULT; if (frame->GetFlags() & bmdFrameContainsHDRMetadata) { ComPtr metadata; - if (SUCCEEDED(videoFrame->QueryInterface( - IID_IDeckLinkVideoFrameMetadataExtensions, - (void **)&metadata))) { + if (SUCCEEDED(videoFrame->QueryInterface(IID_IDeckLinkVideoFrameMetadataExtensions, + (void **)&metadata))) { int64_t range; - if (SUCCEEDED(metadata->GetInt( - bmdDeckLinkFrameMetadataHDRElectroOpticalTransferFunc, - &range))) { + if (SUCCEEDED( + metadata->GetInt(bmdDeckLinkFrameMetadataHDRElectroOpticalTransferFunc, &range))) { switch (range) { case 2: trc = VIDEO_TRC_PQ; @@ -262,13 +243,10 @@ void DeckLinkDeviceInstance::HandleVideoFrame( } currentFrame.trc = trc; - obs_source_output_video2( - static_cast(decklink)->GetSource(), - ¤tFrame); + obs_source_output_video2(static_cast(decklink)->GetSource(), ¤tFrame); } -void DeckLinkDeviceInstance::HandleCaptionPacket( - IDeckLinkAncillaryPacket *packet, const uint64_t timestamp) +void DeckLinkDeviceInstance::HandleCaptionPacket(IDeckLinkAncillaryPacket *packet, const uint64_t timestamp) { const void *data; uint32_t size; @@ -343,17 +321,14 @@ void DeckLinkDeviceInstance::HandleCaptionPacket( auto cc_count = bitstream_reader_read_bits(&reader, 5); - auto *outData = - (uint8_t *)bzalloc(sizeof(uint8_t) * cc_count * 3); + auto *outData = (uint8_t *)bzalloc(sizeof(uint8_t) * cc_count * 3); memcpy(outData, anc + reader.pos, cc_count * 3); currentCaptions.data = outData; currentCaptions.timestamp = timestamp; currentCaptions.packets = cc_count; - obs_source_output_cea708( - static_cast(decklink)->GetSource(), - ¤tCaptions); + obs_source_output_cea708(static_cast(decklink)->GetSource(), ¤tCaptions); bfree(outData); } } @@ -402,9 +377,8 @@ void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_) colorRange = static_cast(decklink)->GetColorRange(); currentFrame.range = colorRange; - video_format_get_parameters_for_format( - activeColorSpace, colorRange, format, currentFrame.color_matrix, - currentFrame.color_range_min, currentFrame.color_range_max); + video_format_get_parameters_for_format(activeColorSpace, colorRange, format, currentFrame.color_matrix, + currentFrame.color_range_min, currentFrame.color_range_max); delete convertFrame; @@ -420,21 +394,17 @@ void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_) break; } - convertFrame = new OBSVideoFrame(mode_->GetWidth(), mode_->GetHeight(), - convertFormat); + convertFrame = new OBSVideoFrame(mode_->GetWidth(), mode_->GetHeight(), convertFormat); #ifdef LOG_SETUP_VIDEO_FORMAT - LOG(LOG_INFO, "Setup video format: %s, %s, %s", - pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB", + LOG(LOG_INFO, "Setup video format: %s, %s, %s", pixelFormat == bmdFormat8BitYUV ? "YUV" : "RGB", activeColorSpace == VIDEO_CS_601 ? "BT.601" : "BT.709", colorRange == VIDEO_RANGE_FULL ? "full" : "limited"); #endif } -bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, - bool allow10Bit_, - BMDVideoConnection bmdVideoConnection, - BMDAudioConnection bmdAudioConnection) +bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, bool allow10Bit_, + BMDVideoConnection bmdVideoConnection, BMDAudioConnection bmdAudioConnection) { if (mode != nullptr) return false; @@ -446,32 +416,23 @@ bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, if (!device->GetInput(&input)) return false; - HRESULT result = input->QueryInterface(IID_IDeckLinkConfiguration, - (void **)&deckLinkConfiguration); + HRESULT result = input->QueryInterface(IID_IDeckLinkConfiguration, (void **)&deckLinkConfiguration); if (result != S_OK) { - LOG(LOG_ERROR, - "Could not obtain the IDeckLinkConfiguration interface: %08x\n", - result); + LOG(LOG_ERROR, "Could not obtain the IDeckLinkConfiguration interface: %08x\n", result); } else { if (bmdVideoConnection > 0) { - result = deckLinkConfiguration->SetInt( - bmdDeckLinkConfigVideoInputConnection, - bmdVideoConnection); + result = deckLinkConfiguration->SetInt(bmdDeckLinkConfigVideoInputConnection, + bmdVideoConnection); if (result != S_OK) { - LOG(LOG_ERROR, - "Couldn't set input video port to %d\n\n", - bmdVideoConnection); + LOG(LOG_ERROR, "Couldn't set input video port to %d\n\n", bmdVideoConnection); } } if (bmdAudioConnection > 0) { - result = deckLinkConfiguration->SetInt( - bmdDeckLinkConfigAudioInputConnection, - bmdAudioConnection); + result = deckLinkConfiguration->SetInt(bmdDeckLinkConfigAudioInputConnection, + bmdAudioConnection); if (result != S_OK) { - LOG(LOG_ERROR, - "Couldn't set input audio port to %d\n\n", - bmdVideoConnection); + LOG(LOG_ERROR, "Couldn't set input audio port to %d\n\n", bmdVideoConnection); } } } @@ -492,15 +453,13 @@ bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, flags = bmdVideoInputEnableFormatDetection; } else { displayMode = mode_->GetDisplayMode(); - pixelFormat = - static_cast(decklink)->GetPixelFormat(); + pixelFormat = static_cast(decklink)->GetPixelFormat(); flags = bmdVideoInputFlagDefault; } allow10Bit = allow10Bit_; - const HRESULT videoResult = - input->EnableVideoInput(displayMode, pixelFormat, flags); + const HRESULT videoResult = input->EnableVideoInput(displayMode, pixelFormat, flags); if (videoResult != S_OK) { LOG(LOG_ERROR, "Failed to enable video input"); return false; @@ -508,8 +467,7 @@ bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, SetupVideoFormat(mode_); - channelFormat = - static_cast(decklink)->GetChannelFormat(); + channelFormat = static_cast(decklink)->GetChannelFormat(); currentPacket.speakers = channelFormat; swap = static_cast(decklink)->swap; @@ -517,21 +475,16 @@ bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, if (channelFormat != SPEAKERS_UNKNOWN) { const int channel = ConvertChannelFormat(channelFormat); - const HRESULT audioResult = input->EnableAudioInput( - bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, - channel); + const HRESULT audioResult = + input->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, channel); if (audioResult != S_OK) - LOG(LOG_WARNING, - "Failed to enable audio input; continuing..."); + LOG(LOG_WARNING, "Failed to enable audio input; continuing..."); - if (channelFormat != SPEAKERS_UNKNOWN && - channelFormat != SPEAKERS_MONO && - channelFormat != SPEAKERS_STEREO && - (channelFormat != SPEAKERS_7POINT1 || swap) && + if (channelFormat != SPEAKERS_UNKNOWN && channelFormat != SPEAKERS_MONO && + channelFormat != SPEAKERS_STEREO && (channelFormat != SPEAKERS_7POINT1 || swap) && maxdevicechannel >= 8) { - const audio_repack_mode_t repack_mode = - ConvertRepackFormat(channelFormat, swap); + const audio_repack_mode_t repack_mode = ConvertRepackFormat(channelFormat, swap); audioRepacker = new AudioRepacker(repack_mode); } } @@ -558,8 +511,7 @@ bool DeckLinkDeviceInstance::StopCapture(void) if (mode == nullptr || input == nullptr) return false; - LOG(LOG_INFO, "Stopping capture of '%s'...", - GetDevice()->GetDisplayName().c_str()); + LOG(LOG_INFO, "Stopping capture of '%s'...", GetDevice()->GetDisplayName().c_str()); input->StopStreams(); FinalizeStream(); @@ -584,16 +536,14 @@ bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_) if (!device->GetOutput(&output_)) return false; - const HRESULT videoResult = output_->EnableVideoOutput( - mode_->GetDisplayMode(), bmdVideoOutputFlagDefault); + const HRESULT videoResult = output_->EnableVideoOutput(mode_->GetDisplayMode(), bmdVideoOutputFlagDefault); if (videoResult != S_OK) { LOG(LOG_ERROR, "Failed to enable video output"); return false; } - const HRESULT audioResult = output_->EnableAudioOutput( - bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, 2, - bmdAudioOutputStreamTimestamped); + const HRESULT audioResult = output_->EnableAudioOutput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, + 2, bmdAudioOutputStreamTimestamped); if (audioResult != S_OK) { LOG(LOG_ERROR, "Failed to enable audio output"); return false; @@ -627,53 +577,39 @@ bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_) activeBlob = nullptr; struct obs_video_info ovi; - const enum video_colorspace colorspace = - obs_get_video_info(&ovi) ? ovi.colorspace : VIDEO_CS_DEFAULT; - const bool source_hdr = (colorspace == VIDEO_CS_2100_PQ) || - (colorspace == VIDEO_CS_2100_HLG); + const enum video_colorspace colorspace = obs_get_video_info(&ovi) ? ovi.colorspace : VIDEO_CS_DEFAULT; + const bool source_hdr = (colorspace == VIDEO_CS_2100_PQ) || (colorspace == VIDEO_CS_2100_HLG); const bool enable_hdr = source_hdr && - (obs_output_get_video_conversion(decklinkOutput->GetOutput()) - ->colorspace == VIDEO_CS_2100_PQ); - BMDPixelFormat pixelFormat = enable_hdr ? bmdFormat10BitRGBXLE - : bmdFormat8BitBGRA; - const int64_t minimumPrerollFrames = - std::max(device->GetMinimumPrerollFrames(), INT64_C(3)); + (obs_output_get_video_conversion(decklinkOutput->GetOutput())->colorspace == VIDEO_CS_2100_PQ); + BMDPixelFormat pixelFormat = enable_hdr ? bmdFormat10BitRGBXLE : bmdFormat8BitBGRA; + const int64_t minimumPrerollFrames = std::max(device->GetMinimumPrerollFrames(), INT64_C(3)); for (int64_t i = 0; i < minimumPrerollFrames; ++i) { ComPtr decklinkOutputFrame; - HRESULT result = output_->CreateVideoFrame( - decklinkOutput->GetWidth(), decklinkOutput->GetHeight(), - rowSize, pixelFormat, bmdFrameFlagDefault, - &decklinkOutputFrame); + HRESULT result = output_->CreateVideoFrame(decklinkOutput->GetWidth(), decklinkOutput->GetHeight(), + rowSize, pixelFormat, bmdFrameFlagDefault, + &decklinkOutputFrame); if (result != S_OK) { - blog(LOG_ERROR, "failed to create video frame 0x%X", - result); + blog(LOG_ERROR, "failed to create video frame 0x%X", result); return false; } IDeckLinkVideoFrame *theFrame = decklinkOutputFrame.Get(); ComPtr decklinkOutputHDRFrame; if (enable_hdr) { - *decklinkOutputHDRFrame.Assign() = - new HDRVideoFrame(decklinkOutputFrame); + *decklinkOutputHDRFrame.Assign() = new HDRVideoFrame(decklinkOutputFrame); theFrame = decklinkOutputHDRFrame.Get(); } - result = output_->ScheduleVideoFrame(theFrame, - i * frameDuration, - frameDuration, - frameTimescale); + result = output_->ScheduleVideoFrame(theFrame, i * frameDuration, frameDuration, frameTimescale); if (result != S_OK) { - blog(LOG_ERROR, - "failed to schedule video frame for preroll 0x%X", - result); + blog(LOG_ERROR, "failed to schedule video frame for preroll 0x%X", result); return false; } } totalFramesScheduled = minimumPrerollFrames; - *renderDelegate.Assign() = - new RenderDelegate(this); + *renderDelegate.Assign() = new RenderDelegate(this); output_->SetScheduledFrameCompletionCallback(renderDelegate); output_->StartScheduledPlayback(0, 100, 1.0); @@ -689,8 +625,7 @@ bool DeckLinkDeviceInstance::StopOutput() if (mode == nullptr || output == nullptr) return false; - LOG(LOG_INFO, "Stopping output of '%s'...", - GetDevice()->GetDisplayName().c_str()); + LOG(LOG_INFO, "Stopping output of '%s'...", GetDevice()->GetDisplayName().c_str()); output->SetScheduledFrameCompletionCallback(NULL); output->DisableVideoOutput(); @@ -711,8 +646,7 @@ void DeckLinkDeviceInstance::UpdateVideoFrame(video_data *frame) uint8_t *const blob = frameQueueDecklinkToObs.pop(); if (blob) { - memcpy(blob, frame->data[0], - frame->linesize[0] * decklinkOutput->GetHeight()); + memcpy(blob, frame->data[0], frame->linesize[0] * decklinkOutput->GetHeight()); frameQueueObsToDecklink.push(blob); } } @@ -736,9 +670,7 @@ void DeckLinkDeviceInstance::ScheduleVideoFrame(IDeckLinkVideoFrame *frame) else memset(bytes, 0, frameSize); - output->ScheduleVideoFrame(frame, - totalFramesScheduled * frameDuration, - frameDuration, frameTimescale); + output->ScheduleVideoFrame(frame, totalFramesScheduled * frameDuration, frameDuration, frameTimescale); ++totalFramesScheduled; } } @@ -746,15 +678,13 @@ void DeckLinkDeviceInstance::ScheduleVideoFrame(IDeckLinkVideoFrame *frame) void DeckLinkDeviceInstance::WriteAudio(audio_data *frames) { uint32_t sampleFramesWritten; - output->WriteAudioSamplesSync(frames->data[0], frames->frames, - &sampleFramesWritten); + output->WriteAudioSamplesSync(frames->data[0], frames->frames, &sampleFramesWritten); } #define TIME_BASE 1000000000 -HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived( - IDeckLinkVideoInputFrame *videoFrame, - IDeckLinkAudioInputPacket *audioPacket) +HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived(IDeckLinkVideoInputFrame *videoFrame, + IDeckLinkAudioInputPacket *audioPacket) { BMDTimeValue videoTS = 0; BMDTimeValue videoDur = 0; @@ -790,30 +720,25 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived( return S_OK; } -HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFormatChanged( - BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *newMode, - BMDDetectedVideoInputFormatFlags detectedSignalFlags) +HRESULT STDMETHODCALLTYPE +DeckLinkDeviceInstance::VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, IDeckLinkDisplayMode *newMode, + BMDDetectedVideoInputFormatFlags detectedSignalFlags) { bool formatChanged = false; if (events & bmdVideoInputColorspaceChanged) { constexpr BMDDetectedVideoInputFormatFlags highBitFlags = - (bmdDetectedVideoInput12BitDepth | - bmdDetectedVideoInput10BitDepth); + (bmdDetectedVideoInput12BitDepth | bmdDetectedVideoInput10BitDepth); if (detectedSignalFlags & bmdDetectedVideoInputRGB444) { - const BMDPixelFormat nextFormat = - ((detectedSignalFlags & highBitFlags) && - allow10Bit) - ? bmdFormat10BitRGBXLE - : bmdFormat8BitBGRA; + const BMDPixelFormat nextFormat = ((detectedSignalFlags & highBitFlags) && allow10Bit) + ? bmdFormat10BitRGBXLE + : bmdFormat8BitBGRA; formatChanged = pixelFormat != nextFormat; pixelFormat = nextFormat; } if (detectedSignalFlags & bmdDetectedVideoInputYCbCr422) { - const BMDPixelFormat nextFormat = - ((detectedSignalFlags & highBitFlags) && - allow10Bit) - ? bmdFormat10BitYUV - : bmdFormat8BitYUV; + const BMDPixelFormat nextFormat = ((detectedSignalFlags & highBitFlags) && allow10Bit) + ? bmdFormat10BitYUV + : bmdFormat8BitYUV; formatChanged = pixelFormat != nextFormat; pixelFormat = nextFormat; } @@ -824,9 +749,8 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFormatChanged( mode->SetMode(newMode); displayMode = mode->GetDisplayMode(); - const HRESULT videoResult = input->EnableVideoInput( - displayMode, pixelFormat, - bmdVideoInputEnableFormatDetection); + const HRESULT videoResult = + input->EnableVideoInput(displayMode, pixelFormat, bmdVideoInputEnableFormatDetection); if (videoResult != S_OK) { LOG(LOG_ERROR, "Failed to enable video input"); input->StopStreams(); @@ -847,8 +771,7 @@ ULONG STDMETHODCALLTYPE DeckLinkDeviceInstance::AddRef(void) return os_atomic_inc_long(&refCount); } -HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid, - LPVOID *ppv) +HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid, LPVOID *ppv) { HRESULT result = E_NOINTERFACE; @@ -859,8 +782,7 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::QueryInterface(REFIID iid, *ppv = this; AddRef(); result = S_OK; - } else if (memcmp(&iid, &IID_IDeckLinkNotificationCallback, - sizeof(REFIID)) == 0) { + } else if (memcmp(&iid, &IID_IDeckLinkNotificationCallback, sizeof(REFIID)) == 0) { *ppv = (IDeckLinkNotificationCallback *)this; AddRef(); result = S_OK; diff --git a/plugins/decklink/decklink-device-instance.hpp b/plugins/decklink/decklink-device-instance.hpp index 0eda6e17c..c4ac535db 100644 --- a/plugins/decklink/decklink-device-instance.hpp +++ b/plugins/decklink/decklink-device-instance.hpp @@ -1,7 +1,6 @@ #pragma once -#define LOG(level, message, ...) \ - blog(level, "%s: " message, "decklink", ##__VA_ARGS__) +#define LOG(level, message, ...) blog(level, "%s: " message, "decklink", ##__VA_ARGS__) #include #include @@ -13,8 +12,7 @@ class AudioRepacker; class DecklinkBase; -template -class RenderDelegate : public IDeckLinkVideoOutputCallback { +template class RenderDelegate : public IDeckLinkVideoOutputCallback { private: std::atomic m_refCount = 1; T *m_pOwner; @@ -25,15 +23,13 @@ public: RenderDelegate(T *pOwner); // IUnknown - virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, - LPVOID *ppv); + virtual HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv); virtual ULONG STDMETHODCALLTYPE AddRef(); virtual ULONG STDMETHODCALLTYPE Release(); // IDeckLinkVideoOutputCallback - virtual HRESULT STDMETHODCALLTYPE - ScheduledFrameCompleted(IDeckLinkVideoFrame *completedFrame, - BMDOutputFrameCompletionResult result); + virtual HRESULT STDMETHODCALLTYPE ScheduledFrameCompleted(IDeckLinkVideoFrame *completedFrame, + BMDOutputFrameCompletionResult result); virtual HRESULT STDMETHODCALLTYPE ScheduledPlaybackHasStopped(); }; @@ -94,8 +90,7 @@ public: void reset() { for (size_t i = 0; i < FrameQueueFrameCount; ++i) { - cache[i].node.next.store(&cache[i + 1].node, - std::memory_order_relaxed); + cache[i].node.next.store(&cache[i + 1].node, std::memory_order_relaxed); } Node &last = cache[FrameQueueFrameCount].node; @@ -124,8 +119,7 @@ public: { uint8_t *frame = nullptr; - Node *const n_front = - front->next.load(std::memory_order_consume); + Node *const n_front = front->next.load(std::memory_order_consume); if (n_front != nullptr) { frame = n_front->frame; front = n_front; @@ -175,64 +169,38 @@ protected: void FinalizeStream(); void SetupVideoFormat(DeckLinkDeviceMode *mode_); - void HandleAudioPacket(IDeckLinkAudioInputPacket *audioPacket, - const uint64_t timestamp); - void HandleVideoFrame(IDeckLinkVideoInputFrame *videoFrame, - const uint64_t timestamp); + void HandleAudioPacket(IDeckLinkAudioInputPacket *audioPacket, const uint64_t timestamp); + void HandleVideoFrame(IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp); public: DeckLinkDeviceInstance(DecklinkBase *decklink, DeckLinkDevice *device); virtual ~DeckLinkDeviceInstance(); inline DeckLinkDevice *GetDevice() const { return device; } - inline long long GetActiveModeId() const - { - return mode ? mode->GetId() : 0; - } + inline long long GetActiveModeId() const { return mode ? mode->GetId() : 0; } - inline BMDPixelFormat GetActivePixelFormat() const - { - return pixelFormat; - } - inline video_colorspace GetActiveColorSpace() const - { - return colorSpace; - } - inline video_range_type GetActiveColorRange() const - { - return colorRange; - } - inline speaker_layout GetActiveChannelFormat() const - { - return channelFormat; - } + inline BMDPixelFormat GetActivePixelFormat() const { return pixelFormat; } + inline video_colorspace GetActiveColorSpace() const { return colorSpace; } + inline video_range_type GetActiveColorRange() const { return colorRange; } + inline speaker_layout GetActiveChannelFormat() const { return channelFormat; } inline bool GetActiveSwapState() const { return swap; } - inline BMDVideoConnection GetVideoConnection() const - { - return videoConnection; - } - inline BMDAudioConnection GetAudioConnection() const - { - return audioConnection; - } + inline BMDVideoConnection GetVideoConnection() const { return videoConnection; } + inline BMDAudioConnection GetAudioConnection() const { return audioConnection; } inline DeckLinkDeviceMode *GetMode() const { return mode; } - bool StartCapture(DeckLinkDeviceMode *mode, bool allow10Bit, - BMDVideoConnection bmdVideoConnection, + bool StartCapture(DeckLinkDeviceMode *mode, bool allow10Bit, BMDVideoConnection bmdVideoConnection, BMDAudioConnection bmdAudioConnection); bool StopCapture(void); bool StartOutput(DeckLinkDeviceMode *mode_); bool StopOutput(void); - HRESULT STDMETHODCALLTYPE - VideoInputFrameArrived(IDeckLinkVideoInputFrame *videoFrame, - IDeckLinkAudioInputPacket *audioPacket); - HRESULT STDMETHODCALLTYPE VideoInputFormatChanged( - BMDVideoInputFormatChangedEvents events, - IDeckLinkDisplayMode *newMode, - BMDDetectedVideoInputFormatFlags detectedSignalFlags); + HRESULT STDMETHODCALLTYPE VideoInputFrameArrived(IDeckLinkVideoInputFrame *videoFrame, + IDeckLinkAudioInputPacket *audioPacket); + HRESULT STDMETHODCALLTYPE VideoInputFormatChanged(BMDVideoInputFormatChangedEvents events, + IDeckLinkDisplayMode *newMode, + BMDDetectedVideoInputFormatFlags detectedSignalFlags); ULONG STDMETHODCALLTYPE AddRef(void); HRESULT STDMETHODCALLTYPE QueryInterface(REFIID iid, LPVOID *ppv); @@ -241,6 +209,5 @@ public: void UpdateVideoFrame(video_data *frame); void ScheduleVideoFrame(IDeckLinkVideoFrame *frame); void WriteAudio(audio_data *frames); - void HandleCaptionPacket(IDeckLinkAncillaryPacket *packet, - const uint64_t timestamp); + void HandleCaptionPacket(IDeckLinkAncillaryPacket *packet, const uint64_t timestamp); }; diff --git a/plugins/decklink/decklink-device-mode.cpp b/plugins/decklink/decklink-device-mode.cpp index 5ceeca5cc..ed9a5a1d4 100644 --- a/plugins/decklink/decklink-device-mode.cpp +++ b/plugins/decklink/decklink-device-mode.cpp @@ -1,8 +1,6 @@ #include "decklink-device-mode.hpp" -DeckLinkDeviceMode::DeckLinkDeviceMode(IDeckLinkDisplayMode *mode, long long id) - : id(id), - mode(mode) +DeckLinkDeviceMode::DeckLinkDeviceMode(IDeckLinkDisplayMode *mode, long long id) : id(id), mode(mode) { if (mode == nullptr) return; @@ -12,12 +10,7 @@ DeckLinkDeviceMode::DeckLinkDeviceMode(IDeckLinkDisplayMode *mode, long long id) DeckLinkStringToStdString(decklinkStringName, name); } -DeckLinkDeviceMode::DeckLinkDeviceMode(const std::string &name, long long id) - : id(id), - mode(nullptr), - name(name) -{ -} +DeckLinkDeviceMode::DeckLinkDeviceMode(const std::string &name, long long id) : id(id), mode(nullptr), name(name) {} DeckLinkDeviceMode::~DeckLinkDeviceMode(void) {} @@ -45,8 +38,7 @@ int DeckLinkDeviceMode::GetHeight() return 0; } -bool DeckLinkDeviceMode::GetFrameRate(BMDTimeValue *frameDuration, - BMDTimeScale *timeScale) +bool DeckLinkDeviceMode::GetFrameRate(BMDTimeValue *frameDuration, BMDTimeScale *timeScale) { if (mode != nullptr) return SUCCEEDED(mode->GetFrameRate(frameDuration, timeScale)); diff --git a/plugins/decklink/decklink-device.cpp b/plugins/decklink/decklink-device.cpp index 489e47862..ec144b9ce 100644 --- a/plugins/decklink/decklink-device.cpp +++ b/plugins/decklink/decklink-device.cpp @@ -31,15 +31,11 @@ ULONG DeckLinkDevice::Release() bool DeckLinkDevice::Init() { ComPtr attributes; - const HRESULT result = device->QueryInterface( - IID_IDeckLinkProfileAttributes, (void **)&attributes); + const HRESULT result = device->QueryInterface(IID_IDeckLinkProfileAttributes, (void **)&attributes); if (result == S_OK) { decklink_bool_t detectable = false; - if (attributes->GetFlag(BMDDeckLinkSupportsInputFormatDetection, - &detectable) == S_OK && - !!detectable) { - DeckLinkDeviceMode *mode = - new DeckLinkDeviceMode("Auto", MODE_ID_AUTO); + if (attributes->GetFlag(BMDDeckLinkSupportsInputFormatDetection, &detectable) == S_OK && !!detectable) { + DeckLinkDeviceMode *mode = new DeckLinkDeviceMode("Auto", MODE_ID_AUTO); inputModes.push_back(mode); inputModeIdMap[MODE_ID_AUTO] = mode; } @@ -47,8 +43,7 @@ bool DeckLinkDevice::Init() // Find input modes ComPtr input; - if (device->QueryInterface(IID_IDeckLinkInput, (void **)&input) == - S_OK) { + if (device->QueryInterface(IID_IDeckLinkInput, (void **)&input) == S_OK) { ComPtr modeIterator; if (input->GetDisplayModeIterator(&modeIterator) == S_OK) { ComPtr displayMode; @@ -58,9 +53,7 @@ bool DeckLinkDevice::Init() if (displayMode == nullptr) continue; - DeckLinkDeviceMode *mode = - new DeckLinkDeviceMode(displayMode, - modeId); + DeckLinkDeviceMode *mode = new DeckLinkDeviceMode(displayMode, modeId); inputModes.push_back(mode); inputModeIdMap[modeId] = mode; ++modeId; @@ -69,21 +62,16 @@ bool DeckLinkDevice::Init() } // Get supported video connections - attributes->GetInt(BMDDeckLinkVideoInputConnections, - &supportedVideoInputConnections); - attributes->GetInt(BMDDeckLinkVideoOutputConnections, - &supportedVideoOutputConnections); + attributes->GetInt(BMDDeckLinkVideoInputConnections, &supportedVideoInputConnections); + attributes->GetInt(BMDDeckLinkVideoOutputConnections, &supportedVideoOutputConnections); // Get supported audio connections - attributes->GetInt(BMDDeckLinkAudioInputConnections, - &supportedAudioInputConnections); - attributes->GetInt(BMDDeckLinkAudioOutputConnections, - &supportedAudioOutputConnections); + attributes->GetInt(BMDDeckLinkAudioInputConnections, &supportedAudioInputConnections); + attributes->GetInt(BMDDeckLinkAudioOutputConnections, &supportedAudioOutputConnections); // find output modes ComPtr output; - if (device->QueryInterface(IID_IDeckLinkOutput, (void **)&output) == - S_OK) { + if (device->QueryInterface(IID_IDeckLinkOutput, (void **)&output) == S_OK) { ComPtr modeIterator; if (output->GetDisplayModeIterator(&modeIterator) == S_OK) { @@ -94,9 +82,7 @@ bool DeckLinkDevice::Init() if (displayMode == nullptr) continue; - DeckLinkDeviceMode *mode = - new DeckLinkDeviceMode(displayMode, - modeId); + DeckLinkDeviceMode *mode = new DeckLinkDeviceMode(displayMode, modeId); outputModes.push_back(mode); outputModeIdMap[modeId] = mode; ++modeId; @@ -105,20 +91,16 @@ bool DeckLinkDevice::Init() } // get keyer support - attributes->GetFlag(BMDDeckLinkSupportsExternalKeying, - &supportsExternalKeyer); - attributes->GetFlag(BMDDeckLinkSupportsInternalKeying, - &supportsInternalKeyer); + attributes->GetFlag(BMDDeckLinkSupportsExternalKeying, &supportsExternalKeyer); + attributes->GetFlag(BMDDeckLinkSupportsInternalKeying, &supportsInternalKeyer); - attributes->GetFlag(BMDDeckLinkSupportsHDRMetadata, - &supportsHDRMetadata); + attributes->GetFlag(BMDDeckLinkSupportsHDRMetadata, &supportsHDRMetadata); // Sub Device Counts attributes->GetInt(BMDDeckLinkSubDeviceIndex, &subDeviceIndex); attributes->GetInt(BMDDeckLinkNumberOfSubDevices, &numSubDevices); - if (FAILED(attributes->GetInt(BMDDeckLinkMinimumPrerollFrames, - &minimumPrerollFrames))) { + if (FAILED(attributes->GetInt(BMDDeckLinkMinimumPrerollFrames, &minimumPrerollFrames))) { minimumPrerollFrames = 3; } @@ -142,8 +124,7 @@ bool DeckLinkDevice::Init() /* Intensity Shuttle for Thunderbolt return 2; however, it supports 8 channels */ if (name == "Intensity Shuttle Thunderbolt") maxChannel = 8; - else if (attributes->GetInt(BMDDeckLinkMaximumAudioChannels, - &channels) == S_OK) + else if (attributes->GetInt(BMDDeckLinkMaximumAudioChannels, &channels) == S_OK) maxChannel = (int32_t)channels; else maxChannel = 2; @@ -172,8 +153,7 @@ bool DeckLinkDevice::GetInput(IDeckLinkInput **input) bool DeckLinkDevice::GetOutput(IDeckLinkOutput **output) { - if (device->QueryInterface(IID_IDeckLinkOutput, (void **)output) != - S_OK) + if (device->QueryInterface(IID_IDeckLinkOutput, (void **)output) != S_OK) return false; return true; @@ -181,10 +161,8 @@ bool DeckLinkDevice::GetOutput(IDeckLinkOutput **output) bool DeckLinkDevice::GetKeyer(IDeckLinkKeyer **deckLinkKeyer) { - if (device->QueryInterface(IID_IDeckLinkKeyer, - (void **)deckLinkKeyer) != S_OK) { - fprintf(stderr, - "Could not obtain the IDeckLinkKeyer interface\n"); + if (device->QueryInterface(IID_IDeckLinkKeyer, (void **)deckLinkKeyer) != S_OK) { + fprintf(stderr, "Could not obtain the IDeckLinkKeyer interface\n"); return false; } @@ -221,14 +199,12 @@ const std::string &DeckLinkDevice::GetHash(void) const return hash; } -const std::vector & -DeckLinkDevice::GetInputModes(void) const +const std::vector &DeckLinkDevice::GetInputModes(void) const { return inputModes; } -const std::vector & -DeckLinkDevice::GetOutputModes(void) const +const std::vector &DeckLinkDevice::GetOutputModes(void) const { return outputModes; } diff --git a/plugins/decklink/decklink-devices.cpp b/plugins/decklink/decklink-devices.cpp index c304c6940..4cf730e47 100644 --- a/plugins/decklink/decklink-devices.cpp +++ b/plugins/decklink/decklink-devices.cpp @@ -8,9 +8,7 @@ void fill_out_devices(obs_property_t *list) const std::vector &devices = deviceEnum->GetDevices(); for (DeckLinkDevice *device : devices) { - obs_property_list_add_string(list, - device->GetDisplayName().c_str(), - device->GetHash().c_str()); + obs_property_list_add_string(list, device->GetDisplayName().c_str(), device->GetHash().c_str()); } deviceEnum->Unlock(); diff --git a/plugins/decklink/decklink-output.cpp b/plugins/decklink/decklink-output.cpp index 66bdb9940..6d13e18b5 100644 --- a/plugins/decklink/decklink-output.cpp +++ b/plugins/decklink/decklink-output.cpp @@ -29,18 +29,15 @@ static void *decklink_output_create(obs_data_t *settings, obs_output_t *output) ComPtr device; device.Set(deviceEnum->FindByHash(decklinkOutput->deviceHash)); if (device) { - DeckLinkDeviceMode *mode = - device->FindOutputMode(decklinkOutput->modeID); + DeckLinkDeviceMode *mode = device->FindOutputMode(decklinkOutput->modeID); struct video_scale_info to = {}; to.format = VIDEO_FORMAT_BGRA; to.width = mode->GetWidth(); to.height = mode->GetHeight(); to.range = VIDEO_RANGE_FULL; - to.colorspace = (device->GetSupportsHDRMetadata() && - !decklinkOutput->force_sdr) - ? VIDEO_CS_2100_PQ - : VIDEO_CS_709; + to.colorspace = (device->GetSupportsHDRMetadata() && !decklinkOutput->force_sdr) ? VIDEO_CS_2100_PQ + : VIDEO_CS_709; obs_output_set_video_conversion(output, &to); } @@ -73,8 +70,7 @@ static bool decklink_output_start(void *data) decklink->audio_samplerate = aoi.samples_per_sec; decklink->audio_planes = 2; - decklink->audio_size = - get_audio_size(AUDIO_FORMAT_16BIT, aoi.speakers, 1); + decklink->audio_size = get_audio_size(AUDIO_FORMAT_16BIT, aoi.speakers, 1); decklink->start_timestamp = 0; @@ -89,8 +85,7 @@ static bool decklink_output_start(void *data) struct obs_video_info ovi; if (!obs_get_video_info(&ovi)) { - LOG(LOG_ERROR, - "Start failed: could not retrieve obs_video_info!"); + LOG(LOG_ERROR, "Start failed: could not retrieve obs_video_info!"); return false; } @@ -138,15 +133,12 @@ static void decklink_output_raw_video(void *data, struct video_data *frame) decklink->UpdateVideoFrame(frame); } -static bool prepare_audio(DeckLinkOutput *decklink, - const struct audio_data *frame, - struct audio_data *output) +static bool prepare_audio(DeckLinkOutput *decklink, const struct audio_data *frame, struct audio_data *output) { *output = *frame; if (frame->timestamp < decklink->start_timestamp) { - uint64_t duration = util_mul_div64(frame->frames, 1000000000ULL, - decklink->audio_samplerate); + uint64_t duration = util_mul_div64(frame->frames, 1000000000ULL, decklink->audio_samplerate); uint64_t end_ts = frame->timestamp + duration; uint64_t cutoff; @@ -156,12 +148,10 @@ static bool prepare_audio(DeckLinkOutput *decklink, cutoff = decklink->start_timestamp - frame->timestamp; output->timestamp += cutoff; - cutoff = util_mul_div64(cutoff, decklink->audio_samplerate, - 1000000000ULL); + cutoff = util_mul_div64(cutoff, decklink->audio_samplerate, 1000000000ULL); for (size_t i = 0; i < decklink->audio_planes; i++) - output->data[i] += - decklink->audio_size * (uint32_t)cutoff; + output->data[i] += decklink->audio_size * (uint32_t)cutoff; output->frames -= (uint32_t)cutoff; } @@ -183,9 +173,7 @@ static void decklink_output_raw_audio(void *data, struct audio_data *frames) decklink->WriteAudio(&in); } -static bool decklink_output_device_changed(obs_properties_t *props, - obs_property_t *list, - obs_data_t *settings) +static bool decklink_output_device_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { const char *hash = obs_data_get_string(settings, DEVICE_HASH); if (*hash) { @@ -197,8 +185,7 @@ static bool decklink_output_device_changed(obs_properties_t *props, bool itemFound = false; for (size_t i = 0; i < itemCount; i++) { - const char *curHash = - obs_property_list_item_string(list, i); + const char *curHash = obs_property_list_item_string(list, i); if (strcmp(hash, curHash) == 0) { itemFound = true; break; @@ -224,18 +211,14 @@ static bool decklink_output_device_changed(obs_properties_t *props, obs_property_list_item_disable(modeList, 0, true); obs_property_list_item_disable(keyerList, 0, true); } else { - const std::vector &modes = - device->GetOutputModes(); + const std::vector &modes = device->GetOutputModes(); struct obs_video_info ovi; if (obs_get_video_info(&ovi)) { for (DeckLinkDeviceMode *mode : modes) { - if (mode->IsEqualFrameRate( - ovi.fps_num, ovi.fps_den)) { - obs_property_list_add_int( - modeList, - mode->GetName().c_str(), - mode->GetId()); + if (mode->IsEqualFrameRate(ovi.fps_num, ovi.fps_den)) { + obs_property_list_add_int(modeList, mode->GetName().c_str(), + mode->GetId()); } } } @@ -243,13 +226,11 @@ static bool decklink_output_device_changed(obs_properties_t *props, obs_property_list_add_int(keyerList, "Disabled", 0); if (device->GetSupportsExternalKeyer()) { - obs_property_list_add_int(keyerList, "External", - 1); + obs_property_list_add_int(keyerList, "External", 1); } if (device->GetSupportsInternalKeyer()) { - obs_property_list_add_int(keyerList, "Internal", - 2); + obs_property_list_add_int(keyerList, "Internal", 2); } } } @@ -262,23 +243,18 @@ static obs_properties_t *decklink_output_properties(void *unused) UNUSED_PARAMETER(unused); obs_properties_t *props = obs_properties_create(); - obs_property_t *list = obs_properties_add_list(props, DEVICE_HASH, - TEXT_DEVICE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); - obs_property_set_modified_callback(list, - decklink_output_device_changed); + obs_property_t *list = + obs_properties_add_list(props, DEVICE_HASH, TEXT_DEVICE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_set_modified_callback(list, decklink_output_device_changed); fill_out_devices(list); - obs_properties_add_list(props, MODE_ID, TEXT_MODE, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, MODE_ID, TEXT_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_properties_add_bool(props, AUTO_START, TEXT_AUTO_START); obs_properties_add_bool(props, FORCE_SDR, TEXT_FORCE_SDR); - obs_properties_add_list(props, KEYER, TEXT_ENABLE_KEYER, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, KEYER, TEXT_ENABLE_KEYER, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); return props; } diff --git a/plugins/decklink/decklink-source.cpp b/plugins/decklink/decklink-source.cpp index 829d1b0ab..6dcf6a7b5 100644 --- a/plugins/decklink/decklink-source.cpp +++ b/plugins/decklink/decklink-source.cpp @@ -15,8 +15,7 @@ static void decklink_enable_buffering(DeckLinkInput *decklink, bool enabled) decklink->buffering = enabled; } -static void decklink_deactivate_when_not_showing(DeckLinkInput *decklink, - bool dwns) +static void decklink_deactivate_when_not_showing(DeckLinkInput *decklink, bool dwns) { decklink->dwns = dwns; } @@ -26,8 +25,7 @@ static void *decklink_create(obs_data_t *settings, obs_source_t *source) DeckLinkInput *decklink = new DeckLinkInput(source, deviceEnum); obs_source_set_async_decoupled(source, true); - decklink_enable_buffering(decklink, - obs_data_get_bool(settings, BUFFERING)); + decklink_enable_buffering(decklink, obs_data_get_bool(settings, BUFFERING)); obs_source_update(source, settings); return decklink; @@ -44,18 +42,11 @@ static void decklink_update(void *data, obs_data_t *settings) DeckLinkInput *decklink = (DeckLinkInput *)data; const char *hash = obs_data_get_string(settings, DEVICE_HASH); long long id = obs_data_get_int(settings, MODE_ID); - BMDVideoConnection videoConnection = - (BMDVideoConnection)obs_data_get_int(settings, - VIDEO_CONNECTION); - BMDAudioConnection audioConnection = - (BMDAudioConnection)obs_data_get_int(settings, - AUDIO_CONNECTION); - BMDPixelFormat pixelFormat = - (BMDPixelFormat)obs_data_get_int(settings, PIXEL_FORMAT); - video_colorspace colorSpace = - (video_colorspace)obs_data_get_int(settings, COLOR_SPACE); - video_range_type colorRange = - (video_range_type)obs_data_get_int(settings, COLOR_RANGE); + BMDVideoConnection videoConnection = (BMDVideoConnection)obs_data_get_int(settings, VIDEO_CONNECTION); + BMDAudioConnection audioConnection = (BMDAudioConnection)obs_data_get_int(settings, AUDIO_CONNECTION); + BMDPixelFormat pixelFormat = (BMDPixelFormat)obs_data_get_int(settings, PIXEL_FORMAT); + video_colorspace colorSpace = (video_colorspace)obs_data_get_int(settings, COLOR_SPACE); + video_range_type colorRange = (video_range_type)obs_data_get_int(settings, COLOR_RANGE); int chFmtInt = (int)obs_data_get_int(settings, CHANNEL_FORMAT); if (chFmtInt == 7) @@ -65,11 +56,9 @@ static void decklink_update(void *data, obs_data_t *settings) speaker_layout channelFormat = (speaker_layout)chFmtInt; - decklink_enable_buffering(decklink, - obs_data_get_bool(settings, BUFFERING)); + decklink_enable_buffering(decklink, obs_data_get_bool(settings, BUFFERING)); - decklink_deactivate_when_not_showing( - decklink, obs_data_get_bool(settings, DEACTIVATE_WNS)); + decklink_deactivate_when_not_showing(decklink, obs_data_get_bool(settings, DEACTIVATE_WNS)); ComPtr device; device.Set(deviceEnum->FindByHash(hash)); @@ -91,9 +80,7 @@ static void decklink_show(void *data) if (decklink->dwns && !decklink->Capturing()) { ComPtr device; device.Set(deviceEnum->FindByHash(decklink->hash.c_str())); - decklink->Activate(device, decklink->id, - decklink->videoConnection, - decklink->audioConnection); + decklink->Activate(device, decklink->id, decklink->videoConnection, decklink->audioConnection); } } static void decklink_hide(void *data) @@ -119,8 +106,7 @@ static const char *decklink_get_name(void *) return obs_module_text("BlackmagicDevice"); } -static bool decklink_device_changed(obs_properties_t *props, - obs_property_t *list, obs_data_t *settings) +static bool decklink_device_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { const char *name = obs_data_get_string(settings, DEVICE_NAME); const char *hash = obs_data_get_string(settings, DEVICE_HASH); @@ -143,10 +129,8 @@ static bool decklink_device_changed(obs_properties_t *props, obs_property_list_item_disable(list, 0, true); } - obs_property_t *videoConnectionList = - obs_properties_get(props, VIDEO_CONNECTION); - obs_property_t *audioConnectionList = - obs_properties_get(props, AUDIO_CONNECTION); + obs_property_t *videoConnectionList = obs_properties_get(props, VIDEO_CONNECTION); + obs_property_t *audioConnectionList = obs_properties_get(props, AUDIO_CONNECTION); obs_property_t *modeList = obs_properties_get(props, MODE_ID); obs_property_t *channelList = obs_properties_get(props, CHANNEL_FORMAT); @@ -156,10 +140,8 @@ static bool decklink_device_changed(obs_properties_t *props, obs_property_list_clear(modeList); obs_property_list_clear(channelList); - obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_NONE, - SPEAKERS_UNKNOWN); - obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_2_0CH, - SPEAKERS_STEREO); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_NONE, SPEAKERS_UNKNOWN); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_2_0CH, SPEAKERS_STEREO); ComPtr device; device.Set(deviceEnum->FindByHash(hash)); @@ -171,75 +153,47 @@ static bool decklink_device_changed(obs_properties_t *props, obs_property_list_item_disable(modeList, 0, true); } else { const BMDVideoConnection BMDVideoConnections[] = { - bmdVideoConnectionSDI, - bmdVideoConnectionHDMI, - bmdVideoConnectionOpticalSDI, - bmdVideoConnectionComponent, - bmdVideoConnectionComposite, - bmdVideoConnectionSVideo}; + bmdVideoConnectionSDI, bmdVideoConnectionHDMI, bmdVideoConnectionOpticalSDI, + bmdVideoConnectionComponent, bmdVideoConnectionComposite, bmdVideoConnectionSVideo}; for (BMDVideoConnection conn : BMDVideoConnections) { - if ((device->GetVideoInputConnections() & conn) == - conn) { - obs_property_list_add_int( - videoConnectionList, - bmd_video_connection_to_name(conn), - conn); + if ((device->GetVideoInputConnections() & conn) == conn) { + obs_property_list_add_int(videoConnectionList, bmd_video_connection_to_name(conn), + conn); } } const BMDAudioConnection BMDAudioConnections[] = { - bmdAudioConnectionEmbedded, - bmdAudioConnectionAESEBU, - bmdAudioConnectionAnalog, - bmdAudioConnectionAnalogXLR, - bmdAudioConnectionAnalogRCA, - bmdAudioConnectionMicrophone, + bmdAudioConnectionEmbedded, bmdAudioConnectionAESEBU, bmdAudioConnectionAnalog, + bmdAudioConnectionAnalogXLR, bmdAudioConnectionAnalogRCA, bmdAudioConnectionMicrophone, bmdAudioConnectionHeadphones}; for (BMDAudioConnection conn : BMDAudioConnections) { - if ((device->GetAudioInputConnections() & conn) == - conn) { - obs_property_list_add_int( - audioConnectionList, - bmd_audio_connection_to_name(conn), - conn); + if ((device->GetAudioInputConnections() & conn) == conn) { + obs_property_list_add_int(audioConnectionList, bmd_audio_connection_to_name(conn), + conn); } } - const std::vector &modes = - device->GetInputModes(); + const std::vector &modes = device->GetInputModes(); for (DeckLinkDeviceMode *mode : modes) { - obs_property_list_add_int(modeList, - mode->GetName().c_str(), - mode->GetId()); + obs_property_list_add_int(modeList, mode->GetName().c_str(), mode->GetId()); } if (device->GetMaxChannel() >= 8) { - obs_property_list_add_int(channelList, - TEXT_CHANNEL_FORMAT_2_1CH, - SPEAKERS_2POINT1); - obs_property_list_add_int(channelList, - TEXT_CHANNEL_FORMAT_4_0CH, - SPEAKERS_4POINT0); - obs_property_list_add_int(channelList, - TEXT_CHANNEL_FORMAT_4_1CH, - SPEAKERS_4POINT1); - obs_property_list_add_int(channelList, - TEXT_CHANNEL_FORMAT_5_1CH, - SPEAKERS_5POINT1); - obs_property_list_add_int(channelList, - TEXT_CHANNEL_FORMAT_7_1CH, - SPEAKERS_7POINT1); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_2_1CH, SPEAKERS_2POINT1); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_4_0CH, SPEAKERS_4POINT0); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_4_1CH, SPEAKERS_4POINT1); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_5_1CH, SPEAKERS_5POINT1); + obs_property_list_add_int(channelList, TEXT_CHANNEL_FORMAT_7_1CH, SPEAKERS_7POINT1); } } return true; } -static bool mode_id_changed(obs_properties_t *props, obs_property_t *list, - obs_data_t *settings) +static bool mode_id_changed(obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { long long id = obs_data_get_int(settings, MODE_ID); @@ -256,68 +210,47 @@ static obs_properties_t *decklink_get_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *list = obs_properties_add_list(props, DEVICE_HASH, - TEXT_DEVICE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *list = + obs_properties_add_list(props, DEVICE_HASH, TEXT_DEVICE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(list, decklink_device_changed); fill_out_devices(list); - obs_properties_add_list(props, VIDEO_CONNECTION, TEXT_VIDEO_CONNECTION, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, AUDIO_CONNECTION, TEXT_AUDIO_CONNECTION, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, VIDEO_CONNECTION, TEXT_VIDEO_CONNECTION, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, AUDIO_CONNECTION, TEXT_AUDIO_CONNECTION, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); - list = obs_properties_add_list(props, MODE_ID, TEXT_MODE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + list = obs_properties_add_list(props, MODE_ID, TEXT_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(list, mode_id_changed); - list = obs_properties_add_list(props, PIXEL_FORMAT, TEXT_PIXEL_FORMAT, - OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, PIXEL_FORMAT, TEXT_PIXEL_FORMAT, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(list, "8-bit YUV", bmdFormat8BitYUV); obs_property_list_add_int(list, "10-bit YUV", bmdFormat10BitYUV); obs_property_list_add_int(list, "8-bit BGRA", bmdFormat8BitBGRA); - list = obs_properties_add_list(props, COLOR_SPACE, TEXT_COLOR_SPACE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(list, TEXT_COLOR_SPACE_DEFAULT, - VIDEO_CS_DEFAULT); + list = obs_properties_add_list(props, COLOR_SPACE, TEXT_COLOR_SPACE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(list, TEXT_COLOR_SPACE_DEFAULT, VIDEO_CS_DEFAULT); obs_property_list_add_int(list, "Rec. 601", VIDEO_CS_601); obs_property_list_add_int(list, "Rec. 709", VIDEO_CS_709); obs_property_list_add_int(list, "Rec. 2020", VIDEO_CS_2100_PQ); - list = obs_properties_add_list(props, COLOR_RANGE, TEXT_COLOR_RANGE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(list, TEXT_COLOR_RANGE_DEFAULT, - VIDEO_RANGE_DEFAULT); - obs_property_list_add_int(list, TEXT_COLOR_RANGE_PARTIAL, - VIDEO_RANGE_PARTIAL); - obs_property_list_add_int(list, TEXT_COLOR_RANGE_FULL, - VIDEO_RANGE_FULL); + list = obs_properties_add_list(props, COLOR_RANGE, TEXT_COLOR_RANGE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(list, TEXT_COLOR_RANGE_DEFAULT, VIDEO_RANGE_DEFAULT); + obs_property_list_add_int(list, TEXT_COLOR_RANGE_PARTIAL, VIDEO_RANGE_PARTIAL); + obs_property_list_add_int(list, TEXT_COLOR_RANGE_FULL, VIDEO_RANGE_FULL); - list = obs_properties_add_list(props, CHANNEL_FORMAT, - TEXT_CHANNEL_FORMAT, OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, CHANNEL_FORMAT, TEXT_CHANNEL_FORMAT, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_NONE, - SPEAKERS_UNKNOWN); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_2_0CH, - SPEAKERS_STEREO); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_2_1CH, - SPEAKERS_2POINT1); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_4_0CH, - SPEAKERS_4POINT0); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_4_1CH, - SPEAKERS_4POINT1); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_5_1CH, - SPEAKERS_5POINT1); - obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_7_1CH, - SPEAKERS_7POINT1); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_NONE, SPEAKERS_UNKNOWN); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_2_0CH, SPEAKERS_STEREO); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_2_1CH, SPEAKERS_2POINT1); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_4_0CH, SPEAKERS_4POINT0); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_4_1CH, SPEAKERS_4POINT1); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_5_1CH, SPEAKERS_5POINT1); + obs_property_list_add_int(list, TEXT_CHANNEL_FORMAT_7_1CH, SPEAKERS_7POINT1); obs_property_t *swap = obs_properties_add_bool(props, SWAP, TEXT_SWAP); obs_property_set_long_description(swap, TEXT_SWAP_TOOLTIP); @@ -337,9 +270,8 @@ struct obs_source_info create_decklink_source_info() struct obs_source_info decklink_source_info = {}; decklink_source_info.id = "decklink-input"; decklink_source_info.type = OBS_SOURCE_TYPE_INPUT; - decklink_source_info.output_flags = - OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_CEA_708; + decklink_source_info.output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | + OBS_SOURCE_CEA_708; decklink_source_info.create = decklink_create; decklink_source_info.destroy = decklink_destroy; decklink_source_info.get_defaults = decklink_get_defaults; diff --git a/plugins/decklink/plugin-main.cpp b/plugins/decklink/plugin-main.cpp index 8b3238ec8..37cdfd854 100644 --- a/plugins/decklink/plugin-main.cpp +++ b/plugins/decklink/plugin-main.cpp @@ -27,21 +27,17 @@ bool log_sdk_version() return false; } - result = deckLinkIterator->QueryInterface( - IID_IDeckLinkAPIInformation, (void **)&deckLinkAPIInformation); + result = deckLinkIterator->QueryInterface(IID_IDeckLinkAPIInformation, (void **)&deckLinkAPIInformation); if (result == S_OK) { decklink_string_t deckLinkVersion; - deckLinkAPIInformation->GetString(BMDDeckLinkAPIVersion, - &deckLinkVersion); + deckLinkAPIInformation->GetString(BMDDeckLinkAPIVersion, &deckLinkVersion); - blog(LOG_INFO, "Decklink API Compiled version %s", - BLACKMAGIC_DECKLINK_API_VERSION_STRING); + blog(LOG_INFO, "Decklink API Compiled version %s", BLACKMAGIC_DECKLINK_API_VERSION_STRING); std::string versionString; DeckLinkStringToStdString(deckLinkVersion, versionString); - blog(LOG_INFO, "Decklink API Installed version %s", - versionString.c_str()); + blog(LOG_INFO, "Decklink API Installed version %s", versionString.c_str()); } return true; diff --git a/plugins/decklink/win/platform.cpp b/plugins/decklink/win/platform.cpp index 59e0721f0..e7269b612 100644 --- a/plugins/decklink/win/platform.cpp +++ b/plugins/decklink/win/platform.cpp @@ -5,28 +5,24 @@ IDeckLinkDiscovery *CreateDeckLinkDiscoveryInstance(void) { IDeckLinkDiscovery *instance; - const HRESULT result = - CoCreateInstance(CLSID_CDeckLinkDiscovery, nullptr, CLSCTX_ALL, - IID_IDeckLinkDiscovery, (void **)&instance); + const HRESULT result = CoCreateInstance(CLSID_CDeckLinkDiscovery, nullptr, CLSCTX_ALL, IID_IDeckLinkDiscovery, + (void **)&instance); return result == S_OK ? instance : nullptr; } IDeckLinkIterator *CreateDeckLinkIteratorInstance(void) { IDeckLinkIterator *iterator; - const HRESULT result = - CoCreateInstance(CLSID_CDeckLinkIterator, nullptr, CLSCTX_ALL, - IID_IDeckLinkIterator, (void **)&iterator); + const HRESULT result = CoCreateInstance(CLSID_CDeckLinkIterator, nullptr, CLSCTX_ALL, IID_IDeckLinkIterator, + (void **)&iterator); return result == S_OK ? iterator : nullptr; } IDeckLinkVideoConversion *CreateVideoConversionInstance(void) { IDeckLinkVideoConversion *conversion; - const HRESULT result = CoCreateInstance(CLSID_CDeckLinkVideoConversion, - nullptr, CLSCTX_ALL, - IID_IDeckLinkVideoConversion, - (void **)&conversion); + const HRESULT result = CoCreateInstance(CLSID_CDeckLinkVideoConversion, nullptr, CLSCTX_ALL, + IID_IDeckLinkVideoConversion, (void **)&conversion); return result == S_OK ? conversion : nullptr; } diff --git a/plugins/image-source/color-source.c b/plugins/image-source/color-source.c index b489abfb6..af3a19430 100644 --- a/plugins/image-source/color-source.c +++ b/plugins/image-source/color-source.c @@ -50,22 +50,16 @@ static obs_properties_t *color_source_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_color_alpha(props, "color", - obs_module_text("ColorSource.Color")); + obs_properties_add_color_alpha(props, "color", obs_module_text("ColorSource.Color")); - obs_properties_add_int(props, "width", - obs_module_text("ColorSource.Width"), 0, 4096, - 1); + obs_properties_add_int(props, "width", obs_module_text("ColorSource.Width"), 0, 4096, 1); - obs_properties_add_int(props, "height", - obs_module_text("ColorSource.Height"), 0, 4096, - 1); + obs_properties_add_int(props, "height", obs_module_text("ColorSource.Height"), 0, 4096, 1); return props; } -static void color_source_render_helper(struct color_source *context, - struct vec4 *colorVal) +static void color_source_render_helper(struct color_source *context, struct vec4 *colorVal) { gs_effect_t *solid = obs_get_base_effect(OBS_EFFECT_SOLID); gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color"); @@ -89,8 +83,7 @@ static void color_source_render(void *data, gs_effect_t *effect) struct color_source *context = data; /* need linear path for correct alpha blending */ - const bool linear_srgb = gs_get_linear_srgb() || - (context->color.w < 1.0f); + const bool linear_srgb = gs_get_linear_srgb() || (context->color.w < 1.0f); const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(linear_srgb); @@ -139,8 +132,7 @@ static void color_source_defaults_v3(obs_data_t *settings) struct obs_source_info color_source_info_v1 = { .id = "color_source", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_CAP_OBSOLETE, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_CAP_OBSOLETE, .create = color_source_create, .destroy = color_source_destroy, .update = color_source_update, @@ -157,8 +149,7 @@ struct obs_source_info color_source_info_v2 = { .id = "color_source", .version = 2, .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_CAP_OBSOLETE, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_CAP_OBSOLETE, .create = color_source_create, .destroy = color_source_destroy, .update = color_source_update, @@ -175,8 +166,7 @@ struct obs_source_info color_source_info_v3 = { .id = "color_source", .version = 3, .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_SRGB, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_SRGB, .create = color_source_create, .destroy = color_source_destroy, .update = color_source_update, diff --git a/plugins/image-source/image-source.c b/plugins/image-source/image-source.c index a6540065e..259d2fce0 100644 --- a/plugins/image-source/image-source.c +++ b/plugins/image-source/image-source.c @@ -5,9 +5,8 @@ #include #include -#define blog(log_level, format, ...) \ - blog(log_level, "[image_source: '%s'] " format, \ - obs_source_get_name(context->source), ##__VA_ARGS__) +#define blog(log_level, format, ...) \ + blog(log_level, "[image_source: '%s'] " format, obs_source_get_name(context->source), ##__VA_ARGS__) #define debug(format, ...) blog(LOG_DEBUG, format, ##__VA_ARGS__) #define info(format, ...) blog(LOG_INFO, format, ##__VA_ARGS__) @@ -53,9 +52,7 @@ void image_source_preload_image(void *data) context->file_timestamp = get_modified_timestamp(context->file); gs_image_file4_init(&context->if4, context->file, - context->linear_alpha - ? GS_IMAGE_ALPHA_PREMULTIPLY_SRGB - : GS_IMAGE_ALPHA_PREMULTIPLY); + context->linear_alpha ? GS_IMAGE_ALPHA_PREMULTIPLY_SRGB : GS_IMAGE_ALPHA_PREMULTIPLY); os_atomic_set_bool(&context->file_decoded, true); } @@ -271,8 +268,7 @@ static void image_source_tick(void *data, float seconds) return; } - if (context->last_time && - context->if4.image3.image2.image.is_animated_gif) { + if (context->last_time && context->if4.image3.image2.image.is_animated_gif) { uint64_t elapsed = frame_time - context->last_time; bool updated = gs_image_file4_tick(&context->if4, elapsed); @@ -310,12 +306,9 @@ static obs_properties_t *image_source_properties(void *data) obs_properties_t *props = obs_properties_create(); - obs_properties_add_path(props, "file", obs_module_text("File"), - OBS_PATH_FILE, image_filter, NULL); - obs_properties_add_bool(props, "unload", - obs_module_text("UnloadWhenNotShowing")); - obs_properties_add_bool(props, "linear_alpha", - obs_module_text("LinearAlpha")); + obs_properties_add_path(props, "file", obs_module_text("File"), OBS_PATH_FILE, image_filter, NULL); + obs_properties_add_bool(props, "unload", obs_module_text("UnloadWhenNotShowing")); + obs_properties_add_bool(props, "linear_alpha", obs_module_text("LinearAlpha")); return props; } @@ -346,9 +339,8 @@ static obs_missing_files_t *image_source_missingfiles(void *data) if (strcmp(s->file, "") != 0) { if (!os_file_exists(s->file)) { - obs_missing_file_t *file = obs_missing_file_create( - s->file, missing_file_callback, - OBS_MISSING_FILE_SOURCE, s->source, NULL); + obs_missing_file_t *file = obs_missing_file_create(s->file, missing_file_callback, + OBS_MISSING_FILE_SOURCE, s->source, NULL); obs_missing_files_add_file(files, file); } @@ -357,9 +349,8 @@ static obs_missing_files_t *image_source_missingfiles(void *data) return files; } -static enum gs_color_space -image_source_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space image_source_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); diff --git a/plugins/image-source/obs-slideshow-mk2.c b/plugins/image-source/obs-slideshow-mk2.c index 64bfdaee3..4932a7d63 100644 --- a/plugins/image-source/obs-slideshow-mk2.c +++ b/plugins/image-source/obs-slideshow-mk2.c @@ -8,9 +8,8 @@ #include -#define do_log(level, format, ...) \ - blog(level, "[slideshow: '%s'] " format, \ - obs_source_get_name(ss->source), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[slideshow: '%s'] " format, obs_source_get_name(ss->source), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -208,8 +207,7 @@ static size_t random_file(struct slideshow_data *ssd, size_t slide_idx) } /* gets a new file idx based upon a prior index */ -static inline size_t get_new_file(struct slideshow_data *ssd, size_t slide_idx, - bool next) +static inline size_t get_new_file(struct slideshow_data *ssd, size_t slide_idx, bool next) { if (ssd->randomize) { return random_file(ssd, slide_idx); @@ -249,12 +247,10 @@ static void do_transition(void *data, bool to_null) obs_transition_set(ss->transition, ssd->slides.cur.source); } else if (valid && !to_null) { - obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, - ssd->tr_speed, ssd->slides.cur.source); + obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, ssd->tr_speed, ssd->slides.cur.source); } else { - obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, - ssd->tr_speed, NULL); + obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, ssd->tr_speed, NULL); set_media_state(ss, OBS_MEDIA_STATE_ENDED); obs_source_media_ended(ss->source); } @@ -263,16 +259,14 @@ static void do_transition(void *data, bool to_null) calldata_set_int(&ssd->cd, "index", ssd->slides.cur.slide_idx); calldata_set_string(&ssd->cd, "path", ssd->slides.cur.path); - signal_handler_t *sh = - obs_source_get_signal_handler(ss->source); + signal_handler_t *sh = obs_source_get_signal_handler(ss->source); signal_handler_signal(sh, "slide_changed", &ssd->cd); } } /* get a source via its slide idx in one of slideshow_data's deques. * * only used in get_new_source(). */ -static inline struct source_data *deque_get_source(struct deque *buf, - size_t slide_idx) +static inline struct source_data *deque_get_source(struct deque *buf, size_t slide_idx) { struct source_data *cur; size_t count = buf->size / sizeof(*cur); @@ -300,8 +294,7 @@ static void decode_image(void *data) } /* creates source from a file path. only used in get_new_source(). */ -static inline obs_source_t *create_source_from_file(struct slideshow *ss, - const char *file, bool now) +static inline obs_source_t *create_source_from_file(struct slideshow *ss, const char *file, bool now) { obs_data_t *settings = obs_data_create(); obs_source_t *source; @@ -313,16 +306,14 @@ static inline obs_source_t *create_source_from_file(struct slideshow *ss, obs_data_release(settings); - os_task_queue_queue_task(ss->queue, decode_image, - obs_source_get_weak_source(source)); + os_task_queue_queue_task(ss->queue, decode_image, obs_source_get_weak_source(source)); return source; } /* searches the active slides for the same slide so we can reuse existing * * sources */ -static struct source_data *find_existing_source(struct active_slides *as, - size_t slide_idx) +static struct source_data *find_existing_source(struct active_slides *as, size_t slide_idx) { struct source_data *psd; @@ -340,9 +331,7 @@ static struct source_data *find_existing_source(struct active_slides *as, /* get a new source_data structure and reuse existing sources if possible. * * use the 'new' parameter if you want to create a brand new list of * * active sources while still reusing the old list as well. */ -static struct source_data get_new_source(struct slideshow *ss, - struct active_slides *new, - size_t slide_idx) +static struct source_data get_new_source(struct slideshow *ss, struct active_slides *new, size_t slide_idx) { struct slideshow_data *ssd = &ss->data; struct source_data *psd; @@ -460,20 +449,15 @@ static void ss_update(void *data, obs_data_t *settings) /* Migrate and old loop/random settings to playback mode. */ if (!obs_data_has_user_value(settings, S_PLAYBACK_MODE)) { - if (obs_data_has_user_value(settings, S_RANDOMIZE) && - obs_data_get_bool(settings, S_RANDOMIZE)) { - obs_data_set_string(settings, S_PLAYBACK_MODE, - S_PLAYBACK_RANDOM); + if (obs_data_has_user_value(settings, S_RANDOMIZE) && obs_data_get_bool(settings, S_RANDOMIZE)) { + obs_data_set_string(settings, S_PLAYBACK_MODE, S_PLAYBACK_RANDOM); } else if (obs_data_has_user_value(settings, S_LOOP)) { bool loop = obs_data_get_bool(settings, S_LOOP); - obs_data_set_string(settings, S_PLAYBACK_MODE, - loop ? S_PLAYBACK_LOOP - : S_PLAYBACK_ONCE); + obs_data_set_string(settings, S_PLAYBACK_MODE, loop ? S_PLAYBACK_LOOP : S_PLAYBACK_ONCE); } } - const char *playback_mode = - obs_data_get_string(settings, S_PLAYBACK_MODE); + const char *playback_mode = obs_data_get_string(settings, S_PLAYBACK_MODE); new_data.randomize = strcmp(playback_mode, S_PLAYBACK_RANDOM) == 0; new_data.loop = strcmp(playback_mode, S_PLAYBACK_LOOP) == 0; @@ -587,8 +571,7 @@ static void ss_update(void *data, obs_data_t *settings) ss->cy = cy; obs_transition_set_size(ss->transition, cx, cy); obs_transition_set_alignment(ss->transition, OBS_ALIGN_CENTER); - obs_transition_set_scale_type(ss->transition, - OBS_TRANSITION_SCALE_ASPECT); + obs_transition_set_scale_type(ss->transition, OBS_TRANSITION_SCALE_ASPECT); if (new_tr) obs_source_add_active_child(ss->source, new_tr); @@ -661,8 +644,7 @@ static void ss_next_slide(void *data) if (!ssd->files.num || obs_transition_get_time(ss->transition) < 1.0f) return; - struct source_data *last = deque_data( - &slides->next, (SLIDE_BUFFER_COUNT - 1) * sizeof(sd)); + struct source_data *last = deque_data(&slides->next, (SLIDE_BUFFER_COUNT - 1) * sizeof(sd)); size_t slide_idx = last->slide_idx; if (ss->data.randomize) @@ -710,8 +692,7 @@ static void ss_previous_slide(void *data) do_transition(ss, false); } -static void play_pause_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void play_pause_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -722,8 +703,7 @@ static void play_pause_hotkey(void *data, obs_hotkey_id id, obs_source_media_play_pause(ss->source, !ss->data.paused); } -static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -734,8 +714,7 @@ static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, obs_source_media_restart(ss->source); } -static void stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -746,8 +725,7 @@ static void stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, obs_source_media_stop(ss->source); } -static void next_slide_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void next_slide_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -761,8 +739,7 @@ static void next_slide_hotkey(void *data, obs_hotkey_id id, obs_source_media_next(ss->source); } -static void previous_slide_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void previous_slide_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -812,30 +789,23 @@ static void *ss_create(obs_data_t *settings, obs_source_t *source) ss->queue = os_task_queue_create(); ss->play_pause_hotkey = obs_hotkey_register_source( - source, "SlideShow.PlayPause", - obs_module_text("SlideShow.PlayPause"), play_pause_hotkey, ss); + source, "SlideShow.PlayPause", obs_module_text("SlideShow.PlayPause"), play_pause_hotkey, ss); - ss->restart_hotkey = obs_hotkey_register_source( - source, "SlideShow.Restart", - obs_module_text("SlideShow.Restart"), restart_hotkey, ss); + ss->restart_hotkey = obs_hotkey_register_source(source, "SlideShow.Restart", + obs_module_text("SlideShow.Restart"), restart_hotkey, ss); - ss->stop_hotkey = obs_hotkey_register_source( - source, "SlideShow.Stop", obs_module_text("SlideShow.Stop"), - stop_hotkey, ss); + ss->stop_hotkey = obs_hotkey_register_source(source, "SlideShow.Stop", obs_module_text("SlideShow.Stop"), + stop_hotkey, ss); - ss->next_hotkey = obs_hotkey_register_source( - source, "SlideShow.NextSlide", - obs_module_text("SlideShow.NextSlide"), next_slide_hotkey, ss); + ss->next_hotkey = obs_hotkey_register_source(source, "SlideShow.NextSlide", + obs_module_text("SlideShow.NextSlide"), next_slide_hotkey, ss); - ss->prev_hotkey = obs_hotkey_register_source( - source, "SlideShow.PreviousSlide", - obs_module_text("SlideShow.PreviousSlide"), - previous_slide_hotkey, ss); + ss->prev_hotkey = obs_hotkey_register_source(source, "SlideShow.PreviousSlide", + obs_module_text("SlideShow.PreviousSlide"), previous_slide_hotkey, + ss); - proc_handler_add(ph, "void current_index(out int current_index)", - current_slide_proc, ss); - proc_handler_add(ph, "void total_files(out int total_files)", - total_slides_proc, ss); + proc_handler_add(ph, "void current_index(out int current_index)", current_slide_proc, ss); + proc_handler_add(ph, "void total_files(out int total_files)", total_slides_proc, ss); signal_handler_t *sh = obs_source_get_signal_handler(ss->source); signal_handler_add(sh, "void slide_changed(int index, string path)"); @@ -883,8 +853,7 @@ static void ss_video_tick(void *data, float seconds) /* ----------------------------------------------------- */ /* fade to transparency when the file list becomes empty */ if (!ssd->files.num) { - obs_source_t *active_transition_source = - obs_transition_get_active_source(ss->transition); + obs_source_t *active_transition_source = obs_transition_get_active_source(ss->transition); if (active_transition_source) { obs_source_release(active_transition_source); @@ -899,8 +868,7 @@ static void ss_video_tick(void *data, float seconds) if (ssd->elapsed > ssd->slide_time) { ssd->elapsed -= ssd->slide_time; - if (!ssd->loop && - ssd->slides.cur.slide_idx == ssd->files.num - 1) { + if (!ssd->loop && ssd->slides.cur.slide_idx == ssd->files.num - 1) { if (ssd->hide) do_transition(ss, true); else @@ -914,8 +882,7 @@ static void ss_video_tick(void *data, float seconds) } static inline bool ss_audio_render_(obs_source_t *transition, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, - uint32_t mixers, size_t channels, + struct obs_source_audio_mix *audio_output, uint32_t mixers, size_t channels, size_t sample_rate) { struct obs_source_audio_mix child_audio; @@ -947,10 +914,8 @@ static inline bool ss_audio_render_(obs_source_t *transition, uint64_t *ts_out, return true; } -static bool ss_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool ss_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio_output, uint32_t mixers, + size_t channels, size_t sample_rate) { struct slideshow *ss = data; obs_source_t *transition = get_transition(ss); @@ -959,8 +924,7 @@ static bool ss_audio_render(void *data, uint64_t *ts_out, if (!transition) return false; - success = ss_audio_render_(transition, ts_out, audio_output, mixers, - channels, sample_rate); + success = ss_audio_render_(transition, ts_out, audio_output, mixers, channels, sample_rate); obs_source_release(transition); return success; @@ -992,8 +956,7 @@ static void ss_defaults(obs_data_t *settings) obs_data_set_default_int(settings, S_SLIDE_TIME, 2000); //8000); obs_data_set_default_int(settings, S_TR_SPEED, 700); obs_data_set_default_string(settings, S_CUSTOM_SIZE, "1920x1080"); - obs_data_set_default_string(settings, S_BEHAVIOR, - S_BEHAVIOR_ALWAYS_PLAY); + obs_data_set_default_string(settings, S_BEHAVIOR, S_BEHAVIOR_ALWAYS_PLAY); obs_data_set_default_string(settings, S_MODE, S_MODE_AUTO); obs_data_set_default_string(settings, S_PLAYBACK_MODE, S_PLAYBACK_LOOP); } @@ -1022,39 +985,28 @@ static obs_properties_t *ss_properties(void *data) /* ----------------- */ - p = obs_properties_add_list(ppts, S_BEHAVIOR, T_BEHAVIOR, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, T_BEHAVIOR_ALWAYS_PLAY, - S_BEHAVIOR_ALWAYS_PLAY); - obs_property_list_add_string(p, T_BEHAVIOR_STOP_RESTART, - S_BEHAVIOR_STOP_RESTART); - obs_property_list_add_string(p, T_BEHAVIOR_PAUSE_UNPAUSE, - S_BEHAVIOR_PAUSE_UNPAUSE); + p = obs_properties_add_list(ppts, S_BEHAVIOR, T_BEHAVIOR, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_list_add_string(p, T_BEHAVIOR_ALWAYS_PLAY, S_BEHAVIOR_ALWAYS_PLAY); + obs_property_list_add_string(p, T_BEHAVIOR_STOP_RESTART, S_BEHAVIOR_STOP_RESTART); + obs_property_list_add_string(p, T_BEHAVIOR_PAUSE_UNPAUSE, S_BEHAVIOR_PAUSE_UNPAUSE); - p = obs_properties_add_list(ppts, S_MODE, T_MODE, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, S_MODE, T_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_MODE_AUTO, S_MODE_AUTO); obs_property_list_add_string(p, T_MODE_MANUAL, S_MODE_MANUAL); - p = obs_properties_add_list(ppts, S_TRANSITION, T_TRANSITION, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, S_TRANSITION, T_TRANSITION, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_TR_CUT, TR_CUT); obs_property_list_add_string(p, T_TR_FADE, TR_FADE); obs_property_list_add_string(p, T_TR_SWIPE, TR_SWIPE); obs_property_list_add_string(p, T_TR_SLIDE, TR_SLIDE); - p = obs_properties_add_int(ppts, S_SLIDE_TIME, T_SLIDE_TIME, 50, - 3600000, 50); + p = obs_properties_add_int(ppts, S_SLIDE_TIME, T_SLIDE_TIME, 50, 3600000, 50); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_int(ppts, S_TR_SPEED, T_TR_SPEED, 0, 3600000, - 50); + p = obs_properties_add_int(ppts, S_TR_SPEED, T_TR_SPEED, 0, 3600000, 50); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_list(ppts, S_PLAYBACK_MODE, T_PLAYBACK_MODE, - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, S_PLAYBACK_MODE, T_PLAYBACK_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_PLAYBACK_ONCE, S_PLAYBACK_ONCE); obs_property_list_add_string(p, T_PLAYBACK_LOOP, S_PLAYBACK_LOOP); @@ -1062,8 +1014,7 @@ static obs_properties_t *ss_properties(void *data) obs_properties_add_bool(ppts, S_HIDE, T_HIDE); - p = obs_properties_add_list(ppts, S_CUSTOM_SIZE, T_CUSTOM_SIZE, - OBS_COMBO_TYPE_EDITABLE, + p = obs_properties_add_list(ppts, S_CUSTOM_SIZE, T_CUSTOM_SIZE, OBS_COMBO_TYPE_EDITABLE, OBS_COMBO_FORMAT_STRING); char str[32]; @@ -1083,9 +1034,7 @@ static obs_properties_t *ss_properties(void *data) } } - obs_properties_add_editable_list(ppts, S_FILES, T_FILES, - OBS_EDITABLE_LIST_TYPE_FILES, - file_filter, path.array); + obs_properties_add_editable_list(ppts, S_FILES, T_FILES, OBS_EDITABLE_LIST_TYPE_FILES, file_filter, path.array); dstr_free(&path); return ppts; @@ -1164,11 +1113,8 @@ static obs_missing_files_t *ss_missingfiles(void *data) if (*path != 0) { if (!os_file_exists(path)) { - obs_missing_file_t *file = - obs_missing_file_create( - path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, source, - (void *)path); + obs_missing_file_t *file = obs_missing_file_create( + path, missing_file_callback, OBS_MISSING_FILE_SOURCE, source, (void *)path); obs_missing_files_add_file(missing_files, file); } @@ -1183,17 +1129,15 @@ static obs_missing_files_t *ss_missingfiles(void *data) return missing_files; } -static enum gs_color_space -ss_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space ss_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { enum gs_color_space space = GS_CS_SRGB; struct slideshow *ss = data; obs_source_t *transition = get_transition(ss); if (transition) { - space = obs_source_get_color_space(transition, count, - preferred_spaces); + space = obs_source_get_color_space(transition, count, preferred_spaces); obs_source_release(transition); } @@ -1204,8 +1148,8 @@ struct obs_source_info slideshow_info_mk2 = { .id = "slideshow", .version = 2, .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_COMPOSITE | OBS_SOURCE_CONTROLLABLE_MEDIA, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_COMPOSITE | + OBS_SOURCE_CONTROLLABLE_MEDIA, .get_name = ss_getname, .create = ss_create, .destroy = ss_destroy, diff --git a/plugins/image-source/obs-slideshow.c b/plugins/image-source/obs-slideshow.c index 3604ce2f3..7d61cf0c3 100644 --- a/plugins/image-source/obs-slideshow.c +++ b/plugins/image-source/obs-slideshow.c @@ -4,9 +4,8 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[slideshow: '%s'] " format, \ - obs_source_get_name(ss->source), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[slideshow: '%s'] " format, obs_source_get_name(ss->source), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -201,8 +200,7 @@ static const char *ss_getname(void *unused) return obs_module_text("SlideShow"); } -static void add_file(struct slideshow *ss, image_file_array_t *new_files, - const char *path, uint32_t *cx, uint32_t *cy) +static void add_file(struct slideshow *ss, image_file_array_t *new_files, const char *path, uint32_t *cx, uint32_t *cy) { struct image_file_data data; obs_source_t *new_source; @@ -238,9 +236,8 @@ bool valid_extension(const char *ext) { if (!ext) return false; - return astrcmpi(ext, ".bmp") == 0 || astrcmpi(ext, ".tga") == 0 || - astrcmpi(ext, ".png") == 0 || astrcmpi(ext, ".jpeg") == 0 || - astrcmpi(ext, ".jpg") == 0 || + return astrcmpi(ext, ".bmp") == 0 || astrcmpi(ext, ".tga") == 0 || astrcmpi(ext, ".png") == 0 || + astrcmpi(ext, ".jpeg") == 0 || astrcmpi(ext, ".jpg") == 0 || #ifdef _WIN32 astrcmpi(ext, ".jxr") == 0 || #endif @@ -258,28 +255,23 @@ static void do_transition(void *data, bool to_null) bool valid = item_valid(ss); if (valid && ss->use_cut) { - obs_transition_set(ss->transition, - ss->files.array[ss->cur_item].source); + obs_transition_set(ss->transition, ss->files.array[ss->cur_item].source); } else if (valid && !to_null) { - obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, - ss->tr_speed, + obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, ss->tr_speed, ss->files.array[ss->cur_item].source); } else { - obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, - ss->tr_speed, NULL); + obs_transition_start(ss->transition, OBS_TRANSITION_MODE_AUTO, ss->tr_speed, NULL); set_media_state(ss, OBS_MEDIA_STATE_ENDED); obs_source_media_ended(ss->source); } if (valid && !to_null) { calldata_set_int(&ss->cd, "index", ss->cur_item); - calldata_set_string(&ss->cd, "path", - ss->files.array[ss->cur_item].path); + calldata_set_string(&ss->cd, "path", ss->files.array[ss->cur_item].path); - signal_handler_t *sh = - obs_source_get_signal_handler(ss->source); + signal_handler_t *sh = obs_source_get_signal_handler(ss->source); signal_handler_signal(sh, "slide_changed", &ss->cd); } } @@ -377,8 +369,7 @@ static void ss_update(void *data, obs_data_t *settings) dstr_copy(&dir_path, path); dstr_cat_ch(&dir_path, '/'); dstr_cat(&dir_path, ent->d_name); - add_file(ss, &new_files, dir_path.array, &cx, - &cy); + add_file(ss, &new_files, dir_path.array, &cx, &cy); if (ss->mem_usage >= MAX_MEM_USAGE) break; @@ -479,8 +470,7 @@ static void ss_update(void *data, obs_data_t *settings) ss->elapsed = 0.0f; obs_transition_set_size(ss->transition, cx, cy); obs_transition_set_alignment(ss->transition, OBS_ALIGN_CENTER); - obs_transition_set_scale_type(ss->transition, - OBS_TRANSITION_SCALE_ASPECT); + obs_transition_set_scale_type(ss->transition, OBS_TRANSITION_SCALE_ASPECT); if (ss->randomize && ss->files.num) ss->cur_item = random_file(ss); @@ -578,8 +568,7 @@ static void ss_previous_slide(void *data) do_transition(ss, false); } -static void play_pause_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void play_pause_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -590,8 +579,7 @@ static void play_pause_hotkey(void *data, obs_hotkey_id id, obs_source_media_play_pause(ss->source, !ss->paused); } -static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -602,8 +590,7 @@ static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, obs_source_media_restart(ss->source); } -static void stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -614,8 +601,7 @@ static void stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, obs_source_media_stop(ss->source); } -static void next_slide_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void next_slide_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -629,8 +615,7 @@ static void next_slide_hotkey(void *data, obs_hotkey_id id, obs_source_media_next(ss->source); } -static void previous_slide_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void previous_slide_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -679,30 +664,23 @@ static void *ss_create(obs_data_t *settings, obs_source_t *source) ss->stop = false; ss->play_pause_hotkey = obs_hotkey_register_source( - source, "SlideShow.PlayPause", - obs_module_text("SlideShow.PlayPause"), play_pause_hotkey, ss); + source, "SlideShow.PlayPause", obs_module_text("SlideShow.PlayPause"), play_pause_hotkey, ss); - ss->restart_hotkey = obs_hotkey_register_source( - source, "SlideShow.Restart", - obs_module_text("SlideShow.Restart"), restart_hotkey, ss); + ss->restart_hotkey = obs_hotkey_register_source(source, "SlideShow.Restart", + obs_module_text("SlideShow.Restart"), restart_hotkey, ss); - ss->stop_hotkey = obs_hotkey_register_source( - source, "SlideShow.Stop", obs_module_text("SlideShow.Stop"), - stop_hotkey, ss); + ss->stop_hotkey = obs_hotkey_register_source(source, "SlideShow.Stop", obs_module_text("SlideShow.Stop"), + stop_hotkey, ss); - ss->next_hotkey = obs_hotkey_register_source( - source, "SlideShow.NextSlide", - obs_module_text("SlideShow.NextSlide"), next_slide_hotkey, ss); + ss->next_hotkey = obs_hotkey_register_source(source, "SlideShow.NextSlide", + obs_module_text("SlideShow.NextSlide"), next_slide_hotkey, ss); - ss->prev_hotkey = obs_hotkey_register_source( - source, "SlideShow.PreviousSlide", - obs_module_text("SlideShow.PreviousSlide"), - previous_slide_hotkey, ss); + ss->prev_hotkey = obs_hotkey_register_source(source, "SlideShow.PreviousSlide", + obs_module_text("SlideShow.PreviousSlide"), previous_slide_hotkey, + ss); - proc_handler_add(ph, "void current_index(out int current_index)", - current_slide_proc, ss); - proc_handler_add(ph, "void total_files(out int total_files)", - total_slides_proc, ss); + proc_handler_add(ph, "void current_index(out int current_index)", current_slide_proc, ss); + proc_handler_add(ph, "void total_files(out int total_files)", total_slides_proc, ss); signal_handler_t *sh = obs_source_get_signal_handler(ss->source); signal_handler_add(sh, "void slide_changed(int index, string path)"); @@ -759,8 +737,7 @@ static void ss_video_tick(void *data, float seconds) /* ----------------------------------------------------- */ /* fade to transparency when the file list becomes empty */ if (!ss->files.num) { - obs_source_t *active_transition_source = - obs_transition_get_active_source(ss->transition); + obs_source_t *active_transition_source = obs_transition_get_active_source(ss->transition); if (active_transition_source) { obs_source_release(active_transition_source); @@ -792,8 +769,7 @@ finish: } static inline bool ss_audio_render_(obs_source_t *transition, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, - uint32_t mixers, size_t channels, + struct obs_source_audio_mix *audio_output, uint32_t mixers, size_t channels, size_t sample_rate) { struct obs_source_audio_mix child_audio; @@ -825,10 +801,8 @@ static inline bool ss_audio_render_(obs_source_t *transition, uint64_t *ts_out, return true; } -static bool ss_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio_output, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool ss_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio_output, uint32_t mixers, + size_t channels, size_t sample_rate) { struct slideshow *ss = data; obs_source_t *transition = get_transition(ss); @@ -837,8 +811,7 @@ static bool ss_audio_render(void *data, uint64_t *ts_out, if (!transition) return false; - success = ss_audio_render_(transition, ts_out, audio_output, mixers, - channels, sample_rate); + success = ss_audio_render_(transition, ts_out, audio_output, mixers, channels, sample_rate); obs_source_release(transition); return success; @@ -871,10 +844,8 @@ static void ss_defaults(obs_data_t *settings) obs_data_set_default_string(settings, S_TRANSITION, "fade"); obs_data_set_default_int(settings, S_SLIDE_TIME, 8000); obs_data_set_default_int(settings, S_TR_SPEED, 700); - obs_data_set_default_string(settings, S_CUSTOM_SIZE, - T_CUSTOM_SIZE_AUTO); - obs_data_set_default_string(settings, S_BEHAVIOR, - S_BEHAVIOR_ALWAYS_PLAY); + obs_data_set_default_string(settings, S_CUSTOM_SIZE, T_CUSTOM_SIZE_AUTO); + obs_data_set_default_string(settings, S_BEHAVIOR, S_BEHAVIOR_ALWAYS_PLAY); obs_data_set_default_string(settings, S_MODE, S_MODE_AUTO); obs_data_set_default_bool(settings, S_LOOP, true); } @@ -907,43 +878,32 @@ static obs_properties_t *ss_properties(void *data) /* ----------------- */ - p = obs_properties_add_list(ppts, S_BEHAVIOR, T_BEHAVIOR, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, T_BEHAVIOR_ALWAYS_PLAY, - S_BEHAVIOR_ALWAYS_PLAY); - obs_property_list_add_string(p, T_BEHAVIOR_STOP_RESTART, - S_BEHAVIOR_STOP_RESTART); - obs_property_list_add_string(p, T_BEHAVIOR_PAUSE_UNPAUSE, - S_BEHAVIOR_PAUSE_UNPAUSE); + p = obs_properties_add_list(ppts, S_BEHAVIOR, T_BEHAVIOR, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_list_add_string(p, T_BEHAVIOR_ALWAYS_PLAY, S_BEHAVIOR_ALWAYS_PLAY); + obs_property_list_add_string(p, T_BEHAVIOR_STOP_RESTART, S_BEHAVIOR_STOP_RESTART); + obs_property_list_add_string(p, T_BEHAVIOR_PAUSE_UNPAUSE, S_BEHAVIOR_PAUSE_UNPAUSE); - p = obs_properties_add_list(ppts, S_MODE, T_MODE, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, S_MODE, T_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_MODE_AUTO, S_MODE_AUTO); obs_property_list_add_string(p, T_MODE_MANUAL, S_MODE_MANUAL); - p = obs_properties_add_list(ppts, S_TRANSITION, T_TRANSITION, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, S_TRANSITION, T_TRANSITION, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_TR_CUT, TR_CUT); obs_property_list_add_string(p, T_TR_FADE, TR_FADE); obs_property_list_add_string(p, T_TR_SWIPE, TR_SWIPE); obs_property_list_add_string(p, T_TR_SLIDE, TR_SLIDE); - p = obs_properties_add_int(ppts, S_SLIDE_TIME, T_SLIDE_TIME, 50, - 3600000, 50); + p = obs_properties_add_int(ppts, S_SLIDE_TIME, T_SLIDE_TIME, 50, 3600000, 50); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_int(ppts, S_TR_SPEED, T_TR_SPEED, 0, 3600000, - 50); + p = obs_properties_add_int(ppts, S_TR_SPEED, T_TR_SPEED, 0, 3600000, 50); obs_property_int_set_suffix(p, " ms"); obs_properties_add_bool(ppts, S_LOOP, T_LOOP); obs_properties_add_bool(ppts, S_HIDE, T_HIDE); obs_properties_add_bool(ppts, S_RANDOMIZE, T_RANDOMIZE); - p = obs_properties_add_list(ppts, S_CUSTOM_SIZE, T_CUSTOM_SIZE, - OBS_COMBO_TYPE_EDITABLE, + p = obs_properties_add_list(ppts, S_CUSTOM_SIZE, T_CUSTOM_SIZE, OBS_COMBO_TYPE_EDITABLE, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_CUSTOM_SIZE_AUTO, T_CUSTOM_SIZE_AUTO); @@ -970,9 +930,7 @@ static obs_properties_t *ss_properties(void *data) pthread_mutex_unlock(&ss->mutex); } - obs_properties_add_editable_list(ppts, S_FILES, T_FILES, - OBS_EDITABLE_LIST_TYPE_FILES, - file_filter, path.array); + obs_properties_add_editable_list(ppts, S_FILES, T_FILES, OBS_EDITABLE_LIST_TYPE_FILES, file_filter, path.array); dstr_free(&path); return ppts; @@ -1051,11 +1009,8 @@ static obs_missing_files_t *ss_missingfiles(void *data) if (strcmp(path, "") != 0) { if (!os_file_exists(path)) { - obs_missing_file_t *file = - obs_missing_file_create( - path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, source, - (void *)path); + obs_missing_file_t *file = obs_missing_file_create( + path, missing_file_callback, OBS_MISSING_FILE_SOURCE, source, (void *)path); obs_missing_files_add_file(missing_files, file); } @@ -1070,17 +1025,15 @@ static obs_missing_files_t *ss_missingfiles(void *data) return missing_files; } -static enum gs_color_space -ss_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space ss_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { enum gs_color_space space = GS_CS_SRGB; struct slideshow *ss = data; obs_source_t *transition = get_transition(ss); if (transition) { - space = obs_source_get_color_space(transition, count, - preferred_spaces); + space = obs_source_get_color_space(transition, count, preferred_spaces); obs_source_release(transition); } @@ -1090,9 +1043,8 @@ ss_video_get_color_space(void *data, size_t count, struct obs_source_info slideshow_info = { .id = "slideshow", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_COMPOSITE | OBS_SOURCE_CONTROLLABLE_MEDIA | - OBS_SOURCE_CAP_OBSOLETE, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_COMPOSITE | + OBS_SOURCE_CONTROLLABLE_MEDIA | OBS_SOURCE_CAP_OBSOLETE, .get_name = ss_getname, .create = ss_create, .destroy = ss_destroy, diff --git a/plugins/linux-alsa/alsa-input.c b/plugins/linux-alsa/alsa-input.c index 5af8fade0..cb6d79dce 100644 --- a/plugins/linux-alsa/alsa-input.c +++ b/plugins/linux-alsa/alsa-input.c @@ -65,8 +65,7 @@ struct alsa_data { }; static const char *alsa_get_name(void *); -static bool alsa_devices_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings); +static bool alsa_devices_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings); static obs_properties_t *alsa_get_properties(void *); static void *alsa_create(obs_data_t *, obs_source_t *); static void alsa_destroy(void *); @@ -234,8 +233,7 @@ void alsa_get_defaults(obs_data_t *settings) obs_data_set_default_int(settings, "rate", 44100); } -static bool alsa_devices_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool alsa_devices_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); bool visible = false; @@ -268,19 +266,14 @@ obs_properties_t *alsa_get_properties(void *unused) props = obs_properties_create(); - devices = obs_properties_add_list(props, "device_id", - obs_module_text("Device"), - OBS_COMBO_TYPE_LIST, + devices = obs_properties_add_list(props, "device_id", obs_module_text("Device"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(devices, obs_module_text("Default"), - "default"); + obs_property_list_add_string(devices, obs_module_text("Default"), "default"); - obs_properties_add_text(props, "custom_pcm", obs_module_text("PCM"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "custom_pcm", obs_module_text("PCM"), OBS_TEXT_DEFAULT); - rate = obs_properties_add_list(props, "rate", obs_module_text("Rate"), - OBS_COMBO_TYPE_LIST, + rate = obs_properties_add_list(props, "rate", obs_module_text("Rate"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(devices, alsa_devices_changed); @@ -336,8 +329,7 @@ obs_properties_t *alsa_get_properties(void *unused) ++hint; } - obs_property_list_add_string(devices, obs_module_text("Custom"), - "__custom__"); + obs_property_list_add_string(devices, obs_module_text("Custom"), "__custom__"); snd_device_name_free_hint(hints); @@ -363,11 +355,9 @@ bool _alsa_open(struct alsa_data *data) pthread_attr_t attr; int err; - err = snd_pcm_open(&data->handle, data->device, SND_PCM_STREAM_CAPTURE, - 0); + err = snd_pcm_open(&data->handle, data->device, SND_PCM_STREAM_CAPTURE, 0); if (err < 0) { - blog(LOG_ERROR, "Failed to open '%s': %s", data->device, - snd_strerror(err)); + blog(LOG_ERROR, "Failed to open '%s': %s", data->device, snd_strerror(err)); return false; } @@ -383,8 +373,7 @@ bool _alsa_open(struct alsa_data *data) err = snd_pcm_start(data->handle); if (err < 0) { - blog(LOG_ERROR, "Failed to start '%s': %s", data->device, - snd_strerror(err)); + blog(LOG_ERROR, "Failed to start '%s': %s", data->device, snd_strerror(err)); goto cleanup; } @@ -396,9 +385,7 @@ bool _alsa_open(struct alsa_data *data) err = pthread_create(&data->listen_thread, &attr, _alsa_listen, data); if (err) { pthread_attr_destroy(&attr); - blog(LOG_ERROR, - "Failed to create capture thread for device '%s'.", - data->device); + blog(LOG_ERROR, "Failed to create capture thread for device '%s'.", data->device); goto cleanup; } @@ -440,29 +427,23 @@ bool _alsa_configure(struct alsa_data *data) err = snd_pcm_hw_params_any(data->handle, hwparams); if (err < 0) { - blog(LOG_ERROR, "snd_pcm_hw_params_any failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params_any failed: %s", snd_strerror(err)); return false; } - err = snd_pcm_hw_params_set_access(data->handle, hwparams, - SND_PCM_ACCESS_RW_INTERLEAVED); + err = snd_pcm_hw_params_set_access(data->handle, hwparams, SND_PCM_ACCESS_RW_INTERLEAVED); if (err < 0) { - blog(LOG_ERROR, "snd_pcm_hw_params_set_access failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params_set_access failed: %s", snd_strerror(err)); return false; } #define FORMAT_SIZE 4 - snd_pcm_format_t formats[FORMAT_SIZE] = {SND_PCM_FORMAT_S16_LE, - SND_PCM_FORMAT_S32_LE, - SND_PCM_FORMAT_FLOAT_LE, + snd_pcm_format_t formats[FORMAT_SIZE] = {SND_PCM_FORMAT_S16_LE, SND_PCM_FORMAT_S32_LE, SND_PCM_FORMAT_FLOAT_LE, SND_PCM_FORMAT_U8}; bool format_found = false; for (int i = 0; i < FORMAT_SIZE; ++i) { data->format = formats[i]; - err = snd_pcm_hw_params_test_format(data->handle, hwparams, - data->format); + err = snd_pcm_hw_params_test_format(data->handle, hwparams, data->format); if (err == 0) { format_found = true; break; @@ -475,16 +456,13 @@ bool _alsa_configure(struct alsa_data *data) } snd_pcm_hw_params_set_format(data->handle, hwparams, data->format); if (err < 0) { - blog(LOG_ERROR, "snd_pcm_hw_params_set_format failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params_set_format failed: %s", snd_strerror(err)); return false; } - err = snd_pcm_hw_params_set_rate_near(data->handle, hwparams, - &data->rate, 0); + err = snd_pcm_hw_params_set_rate_near(data->handle, hwparams, &data->rate, 0); if (err < 0) { - blog(LOG_ERROR, "snd_pcm_hw_params_set_rate_near failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params_set_rate_near failed: %s", snd_strerror(err)); return false; } blog(LOG_INFO, "PCM '%s' rate set to %d", data->device, data->rate); @@ -493,35 +471,26 @@ bool _alsa_configure(struct alsa_data *data) if (err < 0) data->channels = 2; - err = snd_pcm_hw_params_set_channels_near(data->handle, hwparams, - &data->channels); + err = snd_pcm_hw_params_set_channels_near(data->handle, hwparams, &data->channels); if (err < 0) { - blog(LOG_ERROR, - "snd_pcm_hw_params_set_channels_near failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params_set_channels_near failed: %s", snd_strerror(err)); return false; } - blog(LOG_INFO, "PCM '%s' channels set to %d", data->device, - data->channels); + blog(LOG_INFO, "PCM '%s' channels set to %d", data->device, data->channels); err = snd_pcm_hw_params(data->handle, hwparams); if (err < 0) { - blog(LOG_ERROR, "snd_pcm_hw_params failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params failed: %s", snd_strerror(err)); return false; } - err = snd_pcm_hw_params_get_period_size(hwparams, &data->period_size, - &dir); + err = snd_pcm_hw_params_get_period_size(hwparams, &data->period_size, &dir); if (err < 0) { - blog(LOG_ERROR, "snd_pcm_hw_params_get_period_size failed: %s", - snd_strerror(err)); + blog(LOG_ERROR, "snd_pcm_hw_params_get_period_size failed: %s", snd_strerror(err)); return false; } - data->sample_size = - (data->channels * snd_pcm_format_physical_width(data->format)) / - 8; + data->sample_size = (data->channels * snd_pcm_format_physical_width(data->format)) / 8; if (data->buffer) bfree(data->buffer); @@ -543,9 +512,7 @@ void _alsa_start_reopen(struct alsa_data *data) err = pthread_create(&data->reopen_thread, &attr, _alsa_reopen, data); if (err) { - blog(LOG_ERROR, - "Failed to create reopen thread for device '%s'.", - data->device); + blog(LOG_ERROR, "Failed to create reopen thread for device '%s'.", data->device); } pthread_attr_destroy(&attr); @@ -579,8 +546,7 @@ void *_alsa_listen(void *attr) os_atomic_set_bool(&data->listen, true); do { - snd_pcm_sframes_t frames = snd_pcm_readi( - data->handle, data->buffer, data->period_size); + snd_pcm_sframes_t frames = snd_pcm_readi(data->handle, data->buffer, data->period_size); if (!os_atomic_load_bool(&data->listen)) break; @@ -594,9 +560,7 @@ void *_alsa_listen(void *attr) } out.frames = frames; - out.timestamp = - os_gettime_ns() - - util_mul_div64(frames, NSEC_PER_SEC, data->rate); + out.timestamp = os_gettime_ns() - util_mul_div64(frames, NSEC_PER_SEC, data->rate); if (!data->first_ts) data->first_ts = out.timestamp + STARTUP_TIMEOUT_NS; diff --git a/plugins/linux-capture/xcomposite-input.c b/plugins/linux-capture/xcomposite-input.c index 272294532..a040bf62f 100644 --- a/plugins/linux-capture/xcomposite-input.c +++ b/plugins/linux-capture/xcomposite-input.c @@ -69,15 +69,12 @@ struct xcompcap { }; static void xcompcap_update(void *data, obs_data_t *settings); -static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, - char **p_wcls); +static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, char **p_wcls); xcb_atom_t get_atom(xcb_connection_t *conn, const char *name) { - xcb_intern_atom_cookie_t atom_c = - xcb_intern_atom(conn, 1, strlen(name), name); - xcb_intern_atom_reply_t *atom_r = - xcb_intern_atom_reply(conn, atom_c, NULL); + xcb_intern_atom_cookie_t atom_c = xcb_intern_atom(conn, 1, strlen(name), name); + xcb_intern_atom_reply_t *atom_r = xcb_intern_atom_reply(conn, atom_c, NULL); xcb_atom_t a = atom_r->atom; free(atom_r); return a; @@ -92,36 +89,30 @@ void xcomp_gather_atoms(xcb_connection_t *conn) ATOM_WM_NAME = get_atom(conn, "WM_NAME"); ATOM_WM_CLASS = get_atom(conn, "WM_CLASS"); ATOM__NET_WM_NAME = get_atom(conn, "_NET_WM_NAME"); - ATOM__NET_SUPPORTING_WM_CHECK = - get_atom(conn, "_NET_SUPPORTING_WM_CHECK"); + ATOM__NET_SUPPORTING_WM_CHECK = get_atom(conn, "_NET_SUPPORTING_WM_CHECK"); ATOM__NET_CLIENT_LIST = get_atom(conn, "_NET_CLIENT_LIST"); } bool xcomp_window_exists(xcb_connection_t *conn, xcb_window_t win) { xcb_generic_error_t *err = NULL; - xcb_get_window_attributes_cookie_t attr_cookie = - xcb_get_window_attributes(conn, win); - xcb_get_window_attributes_reply_t *attr = - xcb_get_window_attributes_reply(conn, attr_cookie, &err); + xcb_get_window_attributes_cookie_t attr_cookie = xcb_get_window_attributes(conn, win); + xcb_get_window_attributes_reply_t *attr = xcb_get_window_attributes_reply(conn, attr_cookie, &err); bool exists = err == NULL && attr->map_state == XCB_MAP_STATE_VIEWABLE; free(attr); return exists; } -xcb_get_property_reply_t *xcomp_property_sync(xcb_connection_t *conn, - xcb_window_t win, xcb_atom_t atom) +xcb_get_property_reply_t *xcomp_property_sync(xcb_connection_t *conn, xcb_window_t win, xcb_atom_t atom) { if (atom == XCB_ATOM_NONE) return NULL; xcb_generic_error_t *err = NULL; // Read properties up to 4096*4 bytes - xcb_get_property_cookie_t prop_cookie = - xcb_get_property(conn, 0, win, atom, 0, 0, 4096); - xcb_get_property_reply_t *prop = - xcb_get_property_reply(conn, prop_cookie, &err); + xcb_get_property_cookie_t prop_cookie = xcb_get_property(conn, 0, win, atom, 0, 0, 4096); + xcb_get_property_reply_t *prop = xcb_get_property_reply(conn, prop_cookie, &err); if (err != NULL || xcb_get_property_value_length(prop) == 0) { free(prop); return NULL; @@ -132,13 +123,11 @@ xcb_get_property_reply_t *xcomp_property_sync(xcb_connection_t *conn, // See ICCCM https://www.x.org/releases/X11R7.6/doc/xorg-docs/specs/ICCCM/icccm.html#text_properties // for more info on the galactic brained string types used in Xorg. -struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp, - xcb_window_t win) +struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp, xcb_window_t win) { struct dstr ret = {0}; - xcb_get_property_reply_t *name = - xcomp_property_sync(conn, win, ATOM__NET_WM_NAME); + xcb_get_property_reply_t *name = xcomp_property_sync(conn, win, ATOM__NET_WM_NAME); if (name) { // Guaranteed to be UTF8_STRING. const char *data = (const char *)xcb_get_property_value(name); @@ -165,8 +154,7 @@ struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp, } if (name->type == ATOM_TEXT) { // Default charset char *utf8; - if (!os_mbs_to_utf8_ptr( - data, xcb_get_property_value_length(name), &utf8)) { + if (!os_mbs_to_utf8_ptr(data, xcb_get_property_value_length(name), &utf8)) { free(name); goto fail; } @@ -174,8 +162,7 @@ struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp, dstr_init_move_array(&ret, utf8); return ret; } - if (name->type == - ATOM_COMPOUND_TEXT) { // LibX11 is the only decoder for these. + if (name->type == ATOM_COMPOUND_TEXT) { // LibX11 is the only decoder for these. XTextProperty xname = { (unsigned char *)data, name->type, 8, // 8 by definition. @@ -183,9 +170,7 @@ struct dstr xcomp_window_name(xcb_connection_t *conn, Display *disp, }; char **list; int len = 0; - if (XmbTextPropertyToTextList(disp, &xname, &list, &len) < - Success || - !list || len < 1) { + if (XmbTextPropertyToTextList(disp, &xname, &list, &len) < Success || !list || len < 1) { free(name); goto fail; } @@ -210,8 +195,7 @@ struct dstr xcomp_window_class(xcb_connection_t *conn, xcb_window_t win) { struct dstr ret = {0}; dstr_copy(&ret, "unknown"); - xcb_get_property_reply_t *cls = - xcomp_property_sync(conn, win, ATOM_WM_CLASS); + xcb_get_property_reply_t *cls = xcomp_property_sync(conn, win, ATOM_WM_CLASS); if (!cls) return ret; @@ -226,17 +210,14 @@ struct dstr xcomp_window_class(xcb_connection_t *conn, xcb_window_t win) // http://standards.freedesktop.org/wm-spec/wm-spec-latest.html#idm140200472693600 bool xcomp_check_ewmh(xcb_connection_t *conn, xcb_window_t root) { - xcb_get_property_reply_t *check = - xcomp_property_sync(conn, root, ATOM__NET_SUPPORTING_WM_CHECK); + xcb_get_property_reply_t *check = xcomp_property_sync(conn, root, ATOM__NET_SUPPORTING_WM_CHECK); if (!check) return false; - xcb_window_t ewmh_window = - ((xcb_window_t *)xcb_get_property_value(check))[0]; + xcb_window_t ewmh_window = ((xcb_window_t *)xcb_get_property_value(check))[0]; free(check); - xcb_get_property_reply_t *check2 = xcomp_property_sync( - conn, ewmh_window, ATOM__NET_SUPPORTING_WM_CHECK); + xcb_get_property_reply_t *check2 = xcomp_property_sync(conn, ewmh_window, ATOM__NET_SUPPORTING_WM_CHECK); if (!check2) return false; free(check2); @@ -252,26 +233,20 @@ struct darray xcomp_top_level_windows(xcb_connection_t *conn) if (ATOM__NET_CLIENT_LIST == XCB_ATOM_NONE) return res.da; - xcb_screen_iterator_t screen_iter = - xcb_setup_roots_iterator(xcb_get_setup(conn)); + xcb_screen_iterator_t screen_iter = xcb_setup_roots_iterator(xcb_get_setup(conn)); for (; screen_iter.rem > 0; xcb_screen_next(&screen_iter)) { xcb_generic_error_t *err = NULL; // Read properties up to 4096*4 bytes xcb_get_property_cookie_t cl_list_cookie = - xcb_get_property(conn, 0, screen_iter.data->root, - ATOM__NET_CLIENT_LIST, 0, 0, 4096); - xcb_get_property_reply_t *cl_list = - xcb_get_property_reply(conn, cl_list_cookie, &err); + xcb_get_property(conn, 0, screen_iter.data->root, ATOM__NET_CLIENT_LIST, 0, 0, 4096); + xcb_get_property_reply_t *cl_list = xcb_get_property_reply(conn, cl_list_cookie, &err); if (err != NULL) { goto done; } - uint32_t len = xcb_get_property_value_length(cl_list) / - sizeof(xcb_window_t); + uint32_t len = xcb_get_property_value_length(cl_list) / sizeof(xcb_window_t); for (uint32_t i = 0; i < len; i++) - da_push_back(res, - &(((xcb_window_t *)xcb_get_property_value( - cl_list))[i])); + da_push_back(res, &(((xcb_window_t *)xcb_get_property_value(cl_list))[i])); done: free(cl_list); @@ -280,14 +255,12 @@ struct darray xcomp_top_level_windows(xcb_connection_t *conn) return res.da; } -static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, - char **p_wcls) +static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, char **p_wcls) { size_t markSize = strlen(WIN_STRING_DIV); const char *firstMark = strstr(str, WIN_STRING_DIV); - const char *secondMark = - firstMark ? strstr(firstMark + markSize, WIN_STRING_DIV) : NULL; + const char *secondMark = firstMark ? strstr(firstMark + markSize, WIN_STRING_DIV) : NULL; const char *strEnd = str + strlen(str); const char *secondStr = firstMark + markSize; @@ -312,8 +285,7 @@ static xcb_window_t convert_encoded_window_id(const char *str, char **p_wname, return ret; } -xcb_window_t xcomp_find_window(xcb_connection_t *conn, Display *disp, - const char *str) +xcb_window_t xcomp_find_window(xcb_connection_t *conn, Display *disp, const char *str) { xcb_window_t ret = 0; char *wname = NULL; @@ -334,13 +306,11 @@ xcb_window_t xcomp_find_window(xcb_connection_t *conn, Display *disp, // then try to find a match by name & class for (size_t i = 0; i < tlw.num; i++) { - xcb_window_t cwin = *(xcb_window_t *)darray_item( - sizeof(xcb_window_t), &tlw.da, i); + xcb_window_t cwin = *(xcb_window_t *)darray_item(sizeof(xcb_window_t), &tlw.da, i); struct dstr cwname = xcomp_window_name(conn, disp, cwin); struct dstr cwcls = xcomp_window_class(conn, cwin); - bool found = strcmp(wname, cwname.array) == 0 && - strcmp(wcls, cwcls.array) == 0; + bool found = strcmp(wname, cwname.array) == 0 && strcmp(wcls, cwcls.array) == 0; dstr_free(&cwname); dstr_free(&cwcls); @@ -350,9 +320,7 @@ xcb_window_t xcomp_find_window(xcb_connection_t *conn, Display *disp, } } - blog(LOG_DEBUG, - "Did not find new window id for Name '%s' or Class '%s'", wname, - wcls); + blog(LOG_DEBUG, "Did not find new window id for Name '%s' or Class '%s'", wname, wcls); cleanup: bfree(wname); @@ -382,16 +350,14 @@ static int silence_x11_errors(Display *display, XErrorEvent *err) return 0; } -void xcomp_create_pixmap(xcb_connection_t *conn, struct xcompcap *s, - int log_level) +void xcomp_create_pixmap(xcb_connection_t *conn, struct xcompcap *s, int log_level) { if (!s->win) return; xcb_generic_error_t *err = NULL; xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(conn, s->win); - xcb_get_geometry_reply_t *geom = - xcb_get_geometry_reply(conn, geom_cookie, &err); + xcb_get_geometry_reply_t *geom = xcb_get_geometry_reply(conn, geom_cookie, &err); if (err != NULL) { return; } @@ -413,9 +379,7 @@ void xcomp_create_pixmap(xcb_connection_t *conn, struct xcompcap *s, return; s->pixmap = xcb_generate_id(conn); - xcb_void_cookie_t name_cookie = - xcb_composite_name_window_pixmap_checked(conn, s->win, - s->pixmap); + xcb_void_cookie_t name_cookie = xcb_composite_name_window_pixmap_checked(conn, s->win, s->pixmap); err = NULL; if ((err = xcb_request_check(conn, name_cookie)) != NULL) { blog(log_level, "xcb_composite_name_window_pixmap failed"); @@ -424,9 +388,7 @@ void xcomp_create_pixmap(xcb_connection_t *conn, struct xcompcap *s, } XErrorHandler prev = XSetErrorHandler(silence_x11_errors); - s->gltex = gs_texture_create_from_pixmap(s->width, s->height, - GS_BGRA_UNORM, GL_TEXTURE_2D, - (void *)s->pixmap); + s->gltex = gs_texture_create_from_pixmap(s->width, s->height, GS_BGRA_UNORM, GL_TEXTURE_2D, (void *)s->pixmap); XSetErrorHandler(prev); } @@ -443,12 +405,9 @@ void watcher_register(xcb_connection_t *conn, struct xcompcap *s) if (xcomp_window_exists(conn, s->win)) { // Subscribe to Events - uint32_t vals[1] = {StructureNotifyMask | ExposureMask | - VisibilityChangeMask}; - xcb_change_window_attributes(conn, s->win, XCB_CW_EVENT_MASK, - vals); - xcb_composite_redirect_window(conn, s->win, - XCB_COMPOSITE_REDIRECT_AUTOMATIC); + uint32_t vals[1] = {StructureNotifyMask | ExposureMask | VisibilityChangeMask}; + xcb_change_window_attributes(conn, s->win, XCB_CW_EVENT_MASK, vals); + xcb_composite_redirect_window(conn, s->win, XCB_COMPOSITE_REDIRECT_AUTOMATIC); da_push_back(watcher_registry, (&(struct reg_item){s, s->win})); } @@ -462,8 +421,8 @@ void watcher_unregister(xcb_connection_t *conn, struct xcompcap *s) size_t idx = DARRAY_INVALID; xcb_window_t win = 0; for (size_t i = 0; i < watcher_registry.num; i++) { - struct reg_item *item = (struct reg_item *)darray_item( - sizeof(struct reg_item), &watcher_registry.da, i); + struct reg_item *item = + (struct reg_item *)darray_item(sizeof(struct reg_item), &watcher_registry.da, i); if (item->src == s) { idx = i; @@ -479,8 +438,8 @@ void watcher_unregister(xcb_connection_t *conn, struct xcompcap *s) // Check if there are still sources listening for the same window. bool windowInUse = false; for (size_t i = 0; i < watcher_registry.num; i++) { - struct reg_item *item = (struct reg_item *)darray_item( - sizeof(struct reg_item), &watcher_registry.da, i); + struct reg_item *item = + (struct reg_item *)darray_item(sizeof(struct reg_item), &watcher_registry.da, i); if (item->win == win) { windowInUse = true; @@ -491,8 +450,7 @@ void watcher_unregister(xcb_connection_t *conn, struct xcompcap *s) if (!windowInUse && xcomp_window_exists(conn, s->win)) { // Last source released, stop listening for events. uint32_t vals[1] = {0}; - xcb_change_window_attributes(conn, win, XCB_CW_EVENT_MASK, - vals); + xcb_change_window_attributes(conn, win, XCB_CW_EVENT_MASK, vals); } done: @@ -527,9 +485,8 @@ void watcher_process(xcb_generic_event_t *ev) if (win != 0) { for (size_t i = 0; i < watcher_registry.num; i++) { - struct reg_item *item = (struct reg_item *)darray_item( - sizeof(struct reg_item), &watcher_registry.da, - i); + struct reg_item *item = + (struct reg_item *)darray_item(sizeof(struct reg_item), &watcher_registry.da, i); if (item->win == win) { item->src->window_changed = true; } @@ -589,8 +546,7 @@ static uint32_t xcompcap_get_height(void *data) static void *xcompcap_create(obs_data_t *settings, obs_source_t *source) { - struct xcompcap *s = - (struct xcompcap *)bzalloc(sizeof(struct xcompcap)); + struct xcompcap *s = (struct xcompcap *)bzalloc(sizeof(struct xcompcap)); pthread_mutex_init(&s->lock, NULL); s->show_cursor = true; s->source = source; @@ -602,14 +558,11 @@ static void *xcompcap_create(obs_data_t *settings, obs_source_t *source) signal_handler_t *sh = obs_source_get_signal_handler(source); signal_handler_add(sh, "void unhooked(ptr source)"); - signal_handler_add( - sh, "void hooked(ptr source, string name, string class)"); + signal_handler_add(sh, "void hooked(ptr source, string name, string class)"); proc_handler_t *ph = obs_source_get_proc_handler(source); - proc_handler_add( - ph, - "void get_hooked(out bool hooked, out string name, out string class)", - xcompcap_get_hooked, s); + proc_handler_add(ph, "void get_hooked(out bool hooked, out string name, out string class)", xcompcap_get_hooked, + s); xcompcap_update(s, settings); return s; @@ -663,8 +616,7 @@ static void xcompcap_video_tick(void *data, float seconds) // Reacquire window after interval or immediately if reconfigured. s->window_check_time += seconds; bool window_lost = !xcomp_window_exists(conn, s->win) || !s->gltex; - if ((window_lost && s->window_check_time > FIND_WINDOW_INTERVAL) || - s->window_changed) { + if ((window_lost && s->window_check_time > FIND_WINDOW_INTERVAL) || s->window_changed) { watcher_unregister(conn, s); s->window_changed = false; @@ -675,12 +627,10 @@ static void xcompcap_video_tick(void *data, float seconds) if (!s->window_hooked && xcomp_window_exists(conn, s->win)) { s->window_hooked = true; - signal_handler_t *sh = - obs_source_get_signal_handler(s->source); + signal_handler_t *sh = obs_source_get_signal_handler(s->source); calldata_t data = {0}; calldata_set_ptr(&data, "source", s->source); - struct dstr wname = - xcomp_window_name(conn, disp, s->win); + struct dstr wname = xcomp_window_name(conn, disp, s->win); struct dstr wcls = xcomp_window_class(conn, s->win); calldata_set_string(&data, "name", wname.array); calldata_set_string(&data, "class", wcls.array); @@ -696,8 +646,7 @@ static void xcompcap_video_tick(void *data, float seconds) // minimized or on offscreen workspaces or already captured on NVIDIA. xcomp_create_pixmap(conn, s, LOG_DEBUG); xcb_xcursor_offset_win(conn, s->cursor, s->win); - xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left, - s->cursor->y_org + s->crop_top); + xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left, s->cursor->y_org + s->crop_top); } if (!s->gltex) @@ -709,8 +658,7 @@ static void xcompcap_video_tick(void *data, float seconds) if (s->show_cursor) { xcb_xcursor_update(conn, s->cursor); - s->cursor_outside = s->cursor->x < 0 || s->cursor->y < 0 || - s->cursor->x > (int)xcompcap_get_width(s) || + s->cursor_outside = s->cursor->x < 0 || s->cursor->y < 0 || s->cursor->x > (int)xcompcap_get_width(s) || s->cursor->y > (int)xcompcap_get_height(s); } @@ -737,8 +685,7 @@ static void xcompcap_video_render(void *data, gs_effect_t *effect) gs_effect_set_texture(image, s->gltex); while (gs_effect_loop(effect, "Draw")) { - gs_draw_sprite_subregion(s->gltex, 0, s->crop_left, s->crop_top, - xcompcap_get_width(s), + gs_draw_sprite_subregion(s->gltex, 0, s->crop_left, s->crop_top, xcompcap_get_width(s), xcompcap_get_height(s)); } @@ -787,9 +734,7 @@ static obs_properties_t *xcompcap_props(void *data) obs_properties_t *props = obs_properties_create(); obs_property_t *prop; - prop = obs_properties_add_list(props, "capture_window", - obs_module_text("Window"), - OBS_COMBO_TYPE_LIST, + prop = obs_properties_add_list(props, "capture_window", obs_module_text("Window"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); DARRAY(struct WindowInfo) window_strings = {0}; @@ -808,26 +753,18 @@ static obs_properties_t *xcompcap_props(void *data) struct dstr desc = {0}; struct dstr name_lower = {0}; - dstr_copy(&name, - wname ? wname - : obs_module_text("UnknownWindow")); + dstr_copy(&name, wname ? wname : obs_module_text("UnknownWindow")); bfree(wname); dstr_copy(&desc, s->windowName); dstr_copy_dstr(&name_lower, &name); dstr_to_lower(&name_lower); - da_push_back( - window_strings, - (&(struct WindowInfo){name_lower, name, desc})); + da_push_back(window_strings, (&(struct WindowInfo){name_lower, name, desc})); } else { struct dstr select_window_str; - dstr_init_copy(&select_window_str, - obs_module_text("SelectAWindow")); - da_push_back(window_strings, - (&(struct WindowInfo){{0}, - select_window_str, - {0}})); + dstr_init_copy(&select_window_str, obs_module_text("SelectAWindow")); + da_push_back(window_strings, (&(struct WindowInfo){{0}, select_window_str, {0}})); } } @@ -835,26 +772,21 @@ static obs_properties_t *xcompcap_props(void *data) bool window_found = false; for (size_t w = 0; w < windows.num; w++) { - xcb_window_t win = *(xcb_window_t *)darray_item( - sizeof(xcb_window_t), &windows, w); + xcb_window_t win = *(xcb_window_t *)darray_item(sizeof(xcb_window_t), &windows, w); struct dstr name = xcomp_window_name(conn, disp, win); struct dstr cls = xcomp_window_class(conn, win); struct dstr desc = {0}; - dstr_printf(&desc, "%d" WIN_STRING_DIV "%s" WIN_STRING_DIV "%s", - win, name.array, cls.array); + dstr_printf(&desc, "%d" WIN_STRING_DIV "%s" WIN_STRING_DIV "%s", win, name.array, cls.array); dstr_free(&cls); struct dstr name_lower; dstr_init_copy_dstr(&name_lower, &name); dstr_to_lower(&name_lower); - if (!had_window_saved || - (s && !compare_ids(desc.array, s->windowName))) - da_push_back( - window_strings, - (&(struct WindowInfo){name_lower, name, desc})); + if (!had_window_saved || (s && !compare_ids(desc.array, s->windowName))) + da_push_back(window_strings, (&(struct WindowInfo){name_lower, name, desc})); else { window_found = true; dstr_free(&name); @@ -865,15 +797,13 @@ static obs_properties_t *xcompcap_props(void *data) darray_free(&windows); if (window_strings.num > 2) - qsort(window_strings.array + 1, window_strings.num - 1, - sizeof(struct WindowInfo), cmp_wi); + qsort(window_strings.array + 1, window_strings.num - 1, sizeof(struct WindowInfo), cmp_wi); for (size_t i = 0; i < window_strings.num; i++) { - struct WindowInfo *w = (struct WindowInfo *)darray_item( - sizeof(struct WindowInfo), &window_strings.da, i); + struct WindowInfo *w = + (struct WindowInfo *)darray_item(sizeof(struct WindowInfo), &window_strings.da, i); - obs_property_list_add_string(prop, w->name.array, - w->desc.array); + obs_property_list_add_string(prop, w->name.array, w->desc.array); dstr_free(&w->name_lower); dstr_free(&w->name); @@ -885,30 +815,23 @@ static obs_properties_t *xcompcap_props(void *data) obs_property_list_item_disable(prop, 0, true); } - prop = obs_properties_add_int(props, "cut_top", - obs_module_text("CropTop"), 0, 4096, 1); + prop = obs_properties_add_int(props, "cut_top", obs_module_text("CropTop"), 0, 4096, 1); obs_property_int_set_suffix(prop, " px"); - prop = obs_properties_add_int(props, "cut_left", - obs_module_text("CropLeft"), 0, 4096, 1); + prop = obs_properties_add_int(props, "cut_left", obs_module_text("CropLeft"), 0, 4096, 1); obs_property_int_set_suffix(prop, " px"); - prop = obs_properties_add_int(props, "cut_right", - obs_module_text("CropRight"), 0, 4096, 1); + prop = obs_properties_add_int(props, "cut_right", obs_module_text("CropRight"), 0, 4096, 1); obs_property_int_set_suffix(prop, " px"); - prop = obs_properties_add_int( - props, "cut_bot", obs_module_text("CropBottom"), 0, 4096, 1); + prop = obs_properties_add_int(props, "cut_bot", obs_module_text("CropBottom"), 0, 4096, 1); obs_property_int_set_suffix(prop, " px"); - obs_properties_add_bool(props, "show_cursor", - obs_module_text("CaptureCursor")); + obs_properties_add_bool(props, "show_cursor", obs_module_text("CaptureCursor")); - obs_properties_add_bool(props, "include_border", - obs_module_text("IncludeXBorder")); + obs_properties_add_bool(props, "include_border", obs_module_text("IncludeXBorder")); - obs_properties_add_bool(props, "exclude_alpha", - obs_module_text("ExcludeAlpha")); + obs_properties_add_bool(props, "exclude_alpha", obs_module_text("ExcludeAlpha")); return props; } @@ -986,8 +909,7 @@ static void xcompcap_update(void *data, obs_data_t *settings) xcomp_cleanup_pixmap(disp, s); xcomp_create_pixmap(conn, s, LOG_ERROR); xcb_xcursor_offset_win(conn, s->cursor, s->win); - xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left, - s->cursor->y_org + s->crop_top); + xcb_xcursor_offset(s->cursor, s->cursor->x_org + s->crop_left, s->cursor->y_org + s->crop_top); pthread_mutex_unlock(&s->lock); obs_leave_graphics(); @@ -1008,20 +930,17 @@ void xcomposite_load(void) return; } - const xcb_query_extension_reply_t *xcomp_ext = - xcb_get_extension_data(conn, &xcb_composite_id); + const xcb_query_extension_reply_t *xcomp_ext = xcb_get_extension_data(conn, &xcb_composite_id); if (!xcomp_ext->present) { blog(LOG_ERROR, "Xcomposite extension not supported"); return; } - xcb_composite_query_version_cookie_t version_cookie = - xcb_composite_query_version(conn, 0, 2); - xcb_composite_query_version_reply_t *version = - xcb_composite_query_version_reply(conn, version_cookie, NULL); + xcb_composite_query_version_cookie_t version_cookie = xcb_composite_query_version(conn, 0, 2); + xcb_composite_query_version_reply_t *version = xcb_composite_query_version_reply(conn, version_cookie, NULL); if (version->major_version == 0 && version->minor_version < 2) { - blog(LOG_ERROR, "Xcomposite extension is too old: %d.%d < 0.2", - version->major_version, version->minor_version); + blog(LOG_ERROR, "Xcomposite extension is too old: %d.%d < 0.2", version->major_version, + version->minor_version); free(version); return; } @@ -1030,8 +949,7 @@ void xcomposite_load(void) // Must be done before other helpers called. xcomp_gather_atoms(conn); - xcb_screen_t *screen_default = - xcb_get_screen(conn, DefaultScreen(disp)); + xcb_screen_t *screen_default = xcb_get_screen(conn, DefaultScreen(disp)); if (!screen_default || !xcomp_check_ewmh(conn, screen_default->root)) { blog(LOG_ERROR, "window manager does not support Extended Window Manager Hints (EWMH).\nXComposite capture disabled."); @@ -1040,8 +958,7 @@ void xcomposite_load(void) struct obs_source_info sinfo = { .id = "xcomposite_input", - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE, .get_name = xcompcap_getname, .create = xcompcap_create, .destroy = xcompcap_destroy, diff --git a/plugins/linux-capture/xcursor-xcb.c b/plugins/linux-capture/xcursor-xcb.c index b66fdfaf2..2eb159c35 100644 --- a/plugins/linux-capture/xcursor-xcb.c +++ b/plugins/linux-capture/xcursor-xcb.c @@ -26,24 +26,19 @@ along with this program. If not, see . * Create the cursor texture, either by updating if the new cursor has the same * size or by creating a new texture if the size is different */ -static void xcb_xcursor_create(xcb_xcursor_t *data, - xcb_xfixes_get_cursor_image_reply_t *xc) +static void xcb_xcursor_create(xcb_xcursor_t *data, xcb_xfixes_get_cursor_image_reply_t *xc) { uint32_t *pixels = xcb_xfixes_get_cursor_image_cursor_image(xc); if (!pixels) return; - if (data->tex && data->last_height == xc->width && - data->last_width == xc->height) { - gs_texture_set_image(data->tex, (const uint8_t *)pixels, - xc->width * sizeof(uint32_t), false); + if (data->tex && data->last_height == xc->width && data->last_width == xc->height) { + gs_texture_set_image(data->tex, (const uint8_t *)pixels, xc->width * sizeof(uint32_t), false); } else { if (data->tex) gs_texture_destroy(data->tex); - data->tex = gs_texture_create(xc->width, xc->height, GS_BGRA, 1, - (const uint8_t **)&pixels, - GS_DYNAMIC); + data->tex = gs_texture_create(xc->width, xc->height, GS_BGRA, 1, (const uint8_t **)&pixels, GS_DYNAMIC); } data->last_serial = xc->cursor_serial; @@ -60,8 +55,7 @@ xcb_xcursor_t *xcb_xcursor_init(xcb_connection_t *xcb) xcb_xfixes_query_version_cookie_t xfix_c; - xfix_c = xcb_xfixes_query_version_unchecked( - xcb, XCB_XFIXES_MAJOR_VERSION, XCB_XFIXES_MINOR_VERSION); + xfix_c = xcb_xfixes_query_version_unchecked(xcb, XCB_XFIXES_MAJOR_VERSION, XCB_XFIXES_MINOR_VERSION); free(xcb_xfixes_query_version_reply(xcb, xfix_c, NULL)); return data; @@ -76,10 +70,8 @@ void xcb_xcursor_destroy(xcb_xcursor_t *data) void xcb_xcursor_update(xcb_connection_t *xcb, xcb_xcursor_t *data) { - xcb_xfixes_get_cursor_image_cookie_t xc_c = - xcb_xfixes_get_cursor_image_unchecked(xcb); - xcb_xfixes_get_cursor_image_reply_t *xc = - xcb_xfixes_get_cursor_image_reply(xcb, xc_c, NULL); + xcb_xfixes_get_cursor_image_cookie_t xc_c = xcb_xfixes_get_cursor_image_unchecked(xcb); + xcb_xfixes_get_cursor_image_reply_t *xc = xcb_xfixes_get_cursor_image_reply(xcb, xc_c, NULL); if (!data || !xc) return; @@ -132,25 +124,21 @@ void xcb_xcursor_offset(xcb_xcursor_t *data, const int x_org, const int y_org) data->y_org = y_org; } -void xcb_xcursor_offset_win(xcb_connection_t *xcb, xcb_xcursor_t *data, - xcb_window_t win) +void xcb_xcursor_offset_win(xcb_connection_t *xcb, xcb_xcursor_t *data, xcb_window_t win) { if (!win) return; xcb_generic_error_t *err = NULL; xcb_get_geometry_cookie_t geom_cookie = xcb_get_geometry(xcb, win); - xcb_get_geometry_reply_t *geom = - xcb_get_geometry_reply(xcb, geom_cookie, &err); + xcb_get_geometry_reply_t *geom = xcb_get_geometry_reply(xcb, geom_cookie, &err); if (err) { free(geom); return; } - xcb_translate_coordinates_cookie_t coords_cookie = - xcb_translate_coordinates(xcb, win, geom->root, 0, 0); - xcb_translate_coordinates_reply_t *coords = - xcb_translate_coordinates_reply(xcb, coords_cookie, &err); + xcb_translate_coordinates_cookie_t coords_cookie = xcb_translate_coordinates(xcb, win, geom->root, 0, 0); + xcb_translate_coordinates_reply_t *coords = xcb_translate_coordinates_reply(xcb, coords_cookie, &err); if (!err) xcb_xcursor_offset(data, coords->dst_x, coords->dst_y); diff --git a/plugins/linux-capture/xcursor-xcb.h b/plugins/linux-capture/xcursor-xcb.h index 1b177be4d..853098a21 100644 --- a/plugins/linux-capture/xcursor-xcb.h +++ b/plugins/linux-capture/xcursor-xcb.h @@ -76,8 +76,7 @@ void xcb_xcursor_offset(xcb_xcursor_t *data, const int x_org, const int y_org); /** * Update the offset to match the window's origin. */ -void xcb_xcursor_offset_win(xcb_connection_t *xcb, xcb_xcursor_t *data, - xcb_window_t win); +void xcb_xcursor_offset_win(xcb_connection_t *xcb, xcb_xcursor_t *data, xcb_window_t win); #ifdef __cplusplus } diff --git a/plugins/linux-capture/xhelpers.c b/plugins/linux-capture/xhelpers.c index d37596fe2..c5ffd9353 100644 --- a/plugins/linux-capture/xhelpers.c +++ b/plugins/linux-capture/xhelpers.c @@ -59,8 +59,7 @@ int xinerama_screen_count(xcb_connection_t *xcb) return screens; } -int xinerama_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, - int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, +int xinerama_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, int_fast32_t *h) { if (!xcb) @@ -109,8 +108,7 @@ static bool randr_has_monitors(xcb_connection_t *xcb) xcb_randr_query_version_cookie_t ver_c; xcb_randr_query_version_reply_t *ver_r; - ver_c = xcb_randr_query_version(xcb, XCB_RANDR_MAJOR_VERSION, - XCB_RANDR_MINOR_VERSION); + ver_c = xcb_randr_query_version(xcb, XCB_RANDR_MAJOR_VERSION, XCB_RANDR_MINOR_VERSION); ver_r = xcb_randr_query_version_reply(xcb, ver_c, 0); if (!ver_r) return 0; @@ -151,8 +149,7 @@ int randr_screen_count(xcb_connection_t *xcb) return xcb_randr_get_screen_resources_crtcs_length(res_r); } -int randr_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, - int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, +int randr_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, int_fast32_t *h, xcb_screen_t **rscreen, char **name) { xcb_screen_t *xscreen; @@ -196,9 +193,7 @@ int randr_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, atom_c = xcb_get_atom_name(xcb, mon->name); atom_r = xcb_get_atom_name_reply(xcb, atom_c, 0); if (atom_r) { - *name = strndup( - xcb_get_atom_name_name(atom_r), - xcb_get_atom_name_name_length(atom_r)); + *name = strndup(xcb_get_atom_name_name(atom_r), xcb_get_atom_name_name_length(atom_r)); free(atom_r); } } @@ -242,8 +237,7 @@ fail: return -1; } -int x11_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *w, - int_fast32_t *h) +int x11_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *w, int_fast32_t *h) { if (!xcb) goto fail; @@ -322,8 +316,7 @@ xcb_screen_t *xcb_get_screen(xcb_connection_t *xcb, int screen) int xcb_get_screen_for_root(xcb_connection_t *conn, xcb_window_t root) { - xcb_screen_iterator_t iter = - xcb_setup_roots_iterator(xcb_get_setup(conn)); + xcb_screen_iterator_t iter = xcb_setup_roots_iterator(xcb_get_setup(conn)); for (int i = 0; iter.rem > 0; xcb_screen_next(&iter)) { if (iter.data->root == root) return i; diff --git a/plugins/linux-capture/xhelpers.h b/plugins/linux-capture/xhelpers.h index caaaa954f..73a10c433 100644 --- a/plugins/linux-capture/xhelpers.h +++ b/plugins/linux-capture/xhelpers.h @@ -60,8 +60,7 @@ int xinerama_screen_count(xcb_connection_t *xcb); * * @return < 0 on error */ -int xinerama_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, - int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, +int xinerama_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, int_fast32_t *h); /** @@ -92,8 +91,7 @@ int randr_screen_count(xcb_connection_t *xcb); * * @return < 0 on error */ -int randr_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, - int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, +int randr_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *x, int_fast32_t *y, int_fast32_t *w, int_fast32_t *h, xcb_screen_t **rscreen, char **name); /** @@ -108,8 +106,7 @@ int randr_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, * * @return < 0 on error */ -int x11_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *w, - int_fast32_t *h); +int x11_screen_geo(xcb_connection_t *xcb, int_fast32_t screen, int_fast32_t *w, int_fast32_t *h); /** * Attach a shared memory segment to the X-Server diff --git a/plugins/linux-capture/xshm-input.c b/plugins/linux-capture/xshm-input.c index cc11ebe17..c927209d0 100644 --- a/plugins/linux-capture/xshm-input.c +++ b/plugins/linux-capture/xshm-input.c @@ -78,8 +78,7 @@ static inline void xshm_resize_texture(struct xshm_data *data) { if (data->texture) gs_texture_destroy(data->texture); - data->texture = gs_texture_create(data->adj_width, data->adj_height, - GS_BGRA, 1, NULL, GS_DYNAMIC); + data->texture = gs_texture_create(data->adj_width, data->adj_height, GS_BGRA, 1, NULL, GS_DYNAMIC); } /** @@ -114,23 +113,20 @@ static int_fast32_t xshm_update_geometry(struct xshm_data *data) int_fast32_t prev_height = data->adj_height; if (data->use_randr) { - if (randr_screen_geo(data->xcb, data->screen_id, &data->x_org, - &data->y_org, &data->width, &data->height, - &data->xcb_screen, NULL) < 0) { + if (randr_screen_geo(data->xcb, data->screen_id, &data->x_org, &data->y_org, &data->width, + &data->height, &data->xcb_screen, NULL) < 0) { return -1; } } else if (data->use_xinerama) { - if (xinerama_screen_geo(data->xcb, data->screen_id, - &data->x_org, &data->y_org, - &data->width, &data->height) < 0) { + if (xinerama_screen_geo(data->xcb, data->screen_id, &data->x_org, &data->y_org, &data->width, + &data->height) < 0) { return -1; } data->xcb_screen = xcb_get_screen(data->xcb, 0); } else { data->x_org = 0; data->y_org = 0; - if (x11_screen_geo(data->xcb, data->screen_id, &data->width, - &data->height) < 0) { + if (x11_screen_geo(data->xcb, data->screen_id, &data->width, &data->height) < 0) { return -1; } data->xcb_screen = xcb_get_screen(data->xcb, data->screen_id); @@ -165,10 +161,8 @@ static int_fast32_t xshm_update_geometry(struct xshm_data *data) if (data->cut_bot != 0) data->adj_height = data->adj_height - data->cut_bot; - blog(LOG_INFO, - "Geometry %" PRIdFAST32 "x%" PRIdFAST32 " @ %" PRIdFAST32 - ",%" PRIdFAST32, - data->width, data->height, data->x_org, data->y_org); + blog(LOG_INFO, "Geometry %" PRIdFAST32 "x%" PRIdFAST32 " @ %" PRIdFAST32 ",%" PRIdFAST32, data->width, + data->height, data->x_org, data->y_org); if (prev_width == data->adj_width && prev_height == data->adj_height) return 0; @@ -224,8 +218,7 @@ static void xshm_capture_stop(struct xshm_data *data) */ static void xshm_capture_start(struct xshm_data *data) { - const char *server = (data->advanced && *data->server) ? data->server - : NULL; + const char *server = (data->advanced && *data->server) ? data->server : NULL; if (data->screen_id == -1) { if (data->texture) { @@ -254,8 +247,7 @@ static void xshm_capture_start(struct xshm_data *data) goto fail; } - data->xshm = - xshm_xcb_attach(data->xcb, data->adj_width, data->adj_height); + data->xshm = xshm_xcb_attach(data->xcb, data->adj_width, data->adj_height); if (!data->xshm) { blog(LOG_ERROR, "failed to attach shm !"); goto fail; @@ -302,8 +294,7 @@ static void xshm_update(void *vptr, obs_data_t *settings) */ static void xshm_defaults(obs_data_t *defaults, int ver) { - obs_data_set_default_int(defaults, "screen", - ver == 1 ? 0 : INVALID_DISPLAY); + obs_data_set_default_int(defaults, "screen", ver == 1 ? 0 : INVALID_DISPLAY); obs_data_set_default_bool(defaults, "show_cursor", true); obs_data_set_default_bool(defaults, "advanced", false); obs_data_set_default_int(defaults, "cut_top", 0); @@ -325,8 +316,7 @@ static void xshm_defaults_v2(obs_data_t *defaults) /** * Toggle visibility of advanced settings */ -static bool xshm_toggle_advanced(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool xshm_toggle_advanced(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); const bool visible = obs_data_get_bool(settings, "advanced"); @@ -343,8 +333,7 @@ static bool xshm_toggle_advanced(obs_properties_t *props, obs_property_t *p, /** * The x server was changed */ -static bool xshm_server_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool xshm_server_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); @@ -359,9 +348,7 @@ static bool xshm_server_changed(obs_properties_t *props, obs_property_t *p, obs_property_list_clear(screens); if (old_screen == INVALID_DISPLAY) { - obs_property_list_add_int(screens, - obs_module_text("SelectADisplay"), - INVALID_DISPLAY); + obs_property_list_add_int(screens, obs_module_text("SelectADisplay"), INVALID_DISPLAY); obs_property_list_item_disable(screens, 0, true); } @@ -377,8 +364,7 @@ static bool xshm_server_changed(obs_properties_t *props, obs_property_t *p, bool xinerama = xinerama_is_active(xcb); int_fast32_t count = randr ? randr_screen_count(xcb) - : (xinerama ? xinerama_screen_count(xcb) - : xcb_setup_roots_length(xcb_get_setup(xcb))); + : (xinerama ? xinerama_screen_count(xcb) : xcb_setup_roots_length(xcb_get_setup(xcb))); for (int_fast32_t i = 0; i < count; ++i) { char *name; @@ -395,35 +381,28 @@ static bool xshm_server_changed(obs_properties_t *props, obs_property_t *p, x11_screen_geo(xcb, i, &w, &h); if (name == NULL) { - int ret = snprintf(name_tmp, sizeof(name_tmp), - "%" PRIuFAST32, i); + int ret = snprintf(name_tmp, sizeof(name_tmp), "%" PRIuFAST32, i); if (ret >= (int)sizeof(name_tmp)) - blog(LOG_DEBUG, - "linux-capture: A format truncation may have occurred." - " This can be ignored since it is quite improbable."); + blog(LOG_DEBUG, "linux-capture: A format truncation may have occurred." + " This can be ignored since it is quite improbable."); name = name_tmp; } - dstr_printf(&screen_info, - "%s (%" PRIuFAST32 "x%" PRIuFAST32 " @ %" PRIuFAST32 - ",%" PRIuFAST32 ")", + dstr_printf(&screen_info, "%s (%" PRIuFAST32 "x%" PRIuFAST32 " @ %" PRIuFAST32 ",%" PRIuFAST32 ")", name, w, h, x, y); if (name != name_tmp) free(name); if (h > 0 && w > 0) - obs_property_list_add_int(screens, screen_info.array, - i); + obs_property_list_add_int(screens, screen_info.array, i); } /* handle missing screen */ if (old_screen + 1 > count) { - dstr_printf(&screen_info, "Display %" PRIuFAST32 " (not found)", - old_screen); - size_t index = obs_property_list_add_int( - screens, screen_info.array, old_screen); + dstr_printf(&screen_info, "Display %" PRIuFAST32 " (not found)", old_screen); + size_t index = obs_property_list_add_int(screens, screen_info.array, old_screen); obs_property_list_item_disable(screens, index, true); } @@ -445,31 +424,23 @@ static obs_properties_t *xshm_properties(void *vptr) obs_properties_t *props = obs_properties_create(); obs_property_t *prop; - obs_properties_add_list(props, "screen", obs_module_text("Display"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_bool(props, "show_cursor", - obs_module_text("CaptureCursor")); - obs_property_t *advanced = obs_properties_add_bool( - props, "advanced", obs_module_text("AdvancedSettings")); + obs_properties_add_list(props, "screen", obs_module_text("Display"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_properties_add_bool(props, "show_cursor", obs_module_text("CaptureCursor")); + obs_property_t *advanced = obs_properties_add_bool(props, "advanced", obs_module_text("AdvancedSettings")); - prop = obs_properties_add_int( - props, "cut_top", obs_module_text("CropTop"), -4096, 4096, 1); + prop = obs_properties_add_int(props, "cut_top", obs_module_text("CropTop"), -4096, 4096, 1); obs_property_int_set_suffix(prop, " px"); - prop = obs_properties_add_int( - props, "cut_left", obs_module_text("CropLeft"), -4096, 4096, 1); + prop = obs_properties_add_int(props, "cut_left", obs_module_text("CropLeft"), -4096, 4096, 1); obs_property_int_set_suffix(prop, " px"); - prop = obs_properties_add_int(props, "cut_right", - obs_module_text("CropRight"), 0, 4096, 1); + prop = obs_properties_add_int(props, "cut_right", obs_module_text("CropRight"), 0, 4096, 1); obs_property_int_set_suffix(prop, " px"); - prop = obs_properties_add_int( - props, "cut_bot", obs_module_text("CropBottom"), 0, 4096, 1); + prop = obs_properties_add_int(props, "cut_bot", obs_module_text("CropBottom"), 0, 4096, 1); obs_property_int_set_suffix(prop, " px"); - obs_property_t *server = obs_properties_add_text( - props, "server", obs_module_text("XServer"), OBS_TEXT_DEFAULT); + obs_property_t *server = obs_properties_add_text(props, "server", obs_module_text("XServer"), OBS_TEXT_DEFAULT); obs_property_set_modified_callback(advanced, xshm_toggle_advanced); obs_property_set_modified_callback(server, xshm_server_changed); @@ -526,10 +497,8 @@ static void xshm_video_tick(void *vptr, float seconds) xcb_shm_get_image_cookie_t img_c; xcb_shm_get_image_reply_t *img_r; - img_c = xcb_shm_get_image_unchecked(data->xcb, data->xcb_screen->root, - data->adj_x_org, data->adj_y_org, - data->adj_width, data->adj_height, - ~0, XCB_IMAGE_FORMAT_Z_PIXMAP, + img_c = xcb_shm_get_image_unchecked(data->xcb, data->xcb_screen->root, data->adj_x_org, data->adj_y_org, + data->adj_width, data->adj_height, ~0, XCB_IMAGE_FORMAT_Z_PIXMAP, data->xshm->seg, 0); img_r = xcb_shm_get_image_reply(data->xcb, img_c, NULL); @@ -539,8 +508,7 @@ static void xshm_video_tick(void *vptr, float seconds) obs_enter_graphics(); - gs_texture_set_image(data->texture, (void *)data->xshm->data, - data->adj_width * 4, false); + gs_texture_set_image(data->texture, (void *)data->xshm->data, data->adj_width * 4, false); xcb_xcursor_update(data->xcb, data->cursor); obs_leave_graphics(); @@ -608,8 +576,7 @@ static uint32_t xshm_getheight(void *vptr) struct obs_source_info xshm_input = { .id = "xshm_input", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB | + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB | OBS_SOURCE_CAP_OBSOLETE, .get_name = xshm_getname, .create = xshm_create, @@ -627,8 +594,7 @@ struct obs_source_info xshm_input = { struct obs_source_info xshm_input_v2 = { .id = "xshm_input_v2", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, .get_name = xshm_getname, .create = xshm_create, .destroy = xshm_destroy, diff --git a/plugins/linux-jack/jack-input.c b/plugins/linux-jack/jack-input.c index a7353d053..9e8670e97 100644 --- a/plugins/linux-jack/jack-input.c +++ b/plugins/linux-jack/jack-input.c @@ -135,10 +135,8 @@ static obs_properties_t *jack_input_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_int(props, "channels", obs_module_text("Channels"), - 1, 8, 1); - obs_properties_add_bool(props, "startjack", - obs_module_text("StartJACKServer")); + obs_properties_add_int(props, "channels", obs_module_text("Channels"), 1, 8, 1); + obs_properties_add_bool(props, "startjack", obs_module_text("StartJACKServer")); return props; } diff --git a/plugins/linux-jack/jack-wrapper.c b/plugins/linux-jack/jack-wrapper.c index ca7302197..2b89bde8b 100644 --- a/plugins/linux-jack/jack-wrapper.c +++ b/plugins/linux-jack/jack-wrapper.c @@ -78,20 +78,16 @@ int jack_process_callback(jack_nframes_t nframes, void *arg) for (unsigned int i = 0; i < data->channels; ++i) { jack_default_audio_sample_t *jack_buffer = - (jack_default_audio_sample_t *)jack_port_get_buffer( - data->jack_ports[i], nframes); + (jack_default_audio_sample_t *)jack_port_get_buffer(data->jack_ports[i], nframes); out.data[i] = (uint8_t *)jack_buffer; } out.frames = nframes; - if (!jack_get_cycle_times(data->jack_client, ¤t_frames, - ¤t_usecs, &next_usecs, &period_usecs)) { + if (!jack_get_cycle_times(data->jack_client, ¤t_frames, ¤t_usecs, &next_usecs, &period_usecs)) { out.timestamp = now - (int64_t)(period_usecs * 1000); } else { - out.timestamp = now - util_mul_div64(nframes, 1000000000ULL, - data->samples_per_sec); - blog(LOG_WARNING, - "jack_get_cycle_times error: guessing timestamp"); + out.timestamp = now - util_mul_div64(nframes, 1000000000ULL, data->samples_per_sec); + blog(LOG_WARNING, "jack_get_cycle_times error: guessing timestamp"); } /* FIXME: this function is not realtime-safe, we should do something @@ -107,8 +103,7 @@ int_fast32_t jack_init(struct jack_data *data) if (data->jack_client != NULL) goto good; - jack_options_t jack_option = - data->start_jack_server ? JackNullOption : JackNoStartServer; + jack_options_t jack_option = data->start_jack_server ? JackNullOption : JackNoStartServer; data->jack_client = jack_client_open(data->device, jack_option, 0); if (data->jack_client == NULL) { @@ -119,15 +114,13 @@ int_fast32_t jack_init(struct jack_data *data) goto error; } - data->jack_ports = - (jack_port_t **)bzalloc(sizeof(jack_port_t *) * data->channels); + data->jack_ports = (jack_port_t **)bzalloc(sizeof(jack_port_t *) * data->channels); for (unsigned int i = 0; i < data->channels; ++i) { char port_name[10] = {'\0'}; snprintf(port_name, sizeof(port_name), "in_%u", i + 1); - data->jack_ports[i] = jack_port_register( - data->jack_client, port_name, JACK_DEFAULT_AUDIO_TYPE, - JackPortIsInput | JackPortIsTerminal, 0); + data->jack_ports[i] = jack_port_register(data->jack_client, port_name, JACK_DEFAULT_AUDIO_TYPE, + JackPortIsInput | JackPortIsTerminal, 0); if (data->jack_ports[i] == NULL) { blog(LOG_ERROR, "jack_port_register Error:" @@ -137,8 +130,7 @@ int_fast32_t jack_init(struct jack_data *data) } } - if (jack_set_process_callback(data->jack_client, jack_process_callback, - data) != 0) { + if (jack_set_process_callback(data->jack_client, jack_process_callback, data) != 0) { blog(LOG_ERROR, "jack_set_process_callback Error"); goto error; } diff --git a/plugins/linux-pipewire/camera-portal.c b/plugins/linux-pipewire/camera-portal.c index bf5f435ae..8c3b1915e 100644 --- a/plugins/linux-pipewire/camera-portal.c +++ b/plugins/linux-pipewire/camera-portal.c @@ -87,16 +87,13 @@ static void ensure_camera_portal_proxy(void) { g_autoptr(GError) error = NULL; if (!camera_proxy) { - camera_proxy = g_dbus_proxy_new_sync( - portal_get_dbus_connection(), G_DBUS_PROXY_FLAGS_NONE, - NULL, "org.freedesktop.portal.Desktop", - "/org/freedesktop/portal/desktop", - "org.freedesktop.portal.Camera", NULL, &error); + camera_proxy = g_dbus_proxy_new_sync(portal_get_dbus_connection(), G_DBUS_PROXY_FLAGS_NONE, NULL, + "org.freedesktop.portal.Desktop", + "/org/freedesktop/portal/desktop", "org.freedesktop.portal.Camera", + NULL, &error); if (error) { - blog(LOG_WARNING, - "[portals] Error retrieving D-Bus proxy: %s", - error->message); + blog(LOG_WARNING, "[portals] Error retrieving D-Bus proxy: %s", error->message); return; } } @@ -150,8 +147,7 @@ static uint32_t clear_params(struct spa_list *param_list, uint32_t id) return count; } -static struct param *add_param(struct spa_list *params, int seq, uint32_t id, - const struct spa_pod *param) +static struct param *add_param(struct spa_list *params, int seq, uint32_t id, const struct spa_pod *param) { struct param *p; @@ -181,9 +177,7 @@ static struct param *add_param(struct spa_list *params, int seq, uint32_t id, return p; } -static void object_update_params(struct spa_list *param_list, - struct spa_list *pending_list, - uint32_t n_params, +static void object_update_params(struct spa_list *param_list, struct spa_list *pending_list, uint32_t n_params, struct spa_param_info *params) { struct param *p, *t; @@ -192,8 +186,7 @@ static void object_update_params(struct spa_list *param_list, for (i = 0; i < n_params; i++) { spa_list_for_each_safe(p, t, pending_list, link) { - if (p->id == params[i].id && p->seq != params[i].seq && - p->param != NULL) { + if (p->id == params[i].id && p->seq != params[i].seq && p->param != NULL) { spa_list_remove(&p->link); free(p); } @@ -211,13 +204,11 @@ static void object_update_params(struct spa_list *param_list, } } -static struct camera_device * -camera_device_new(uint32_t id, const struct spa_dict *properties) +static struct camera_device *camera_device_new(uint32_t id, const struct spa_dict *properties) { struct camera_device *device = bzalloc(sizeof(struct camera_device)); device->id = id; - device->properties = properties ? pw_properties_new_dict(properties) - : NULL; + device->properties = properties ? pw_properties_new_dict(properties) : NULL; spa_list_init(&device->pending_list); spa_list_init(&device->param_list); return device; @@ -237,8 +228,7 @@ static void camera_device_free(struct camera_device *device) /* ------------------------------------------------- */ -static bool update_device_id(struct camera_portal_source *camera_source, - const char *new_device_id) +static bool update_device_id(struct camera_portal_source *camera_source, const char *new_device_id) { if (strcmp(camera_source->device_id, new_device_id) == 0) return false; @@ -256,17 +246,14 @@ static void stream_camera(struct camera_portal_source *camera_source) const struct spa_fraction *framerate = NULL; struct camera_device *device; - g_clear_pointer(&camera_source->obs_pw_stream, - obs_pipewire_stream_destroy); + g_clear_pointer(&camera_source->obs_pw_stream, obs_pipewire_stream_destroy); - device = g_hash_table_lookup(connection->devices, - camera_source->device_id); + device = g_hash_table_lookup(connection->devices, camera_source->device_id); if (!device) return; - blog(LOG_INFO, "[camera-portal] streaming camera '%s'", - camera_source->device_id); + blog(LOG_INFO, "[camera-portal] streaming camera '%s'", camera_source->device_id); if (camera_source->resolution.set) resolution = &camera_source->resolution.rect; @@ -275,17 +262,15 @@ static void stream_camera(struct camera_portal_source *camera_source) connect_info = (struct obs_pipwire_connect_stream_info){ .stream_name = "OBS PipeWire Camera", - .stream_properties = pw_properties_new( - PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, - "Capture", PW_KEY_MEDIA_ROLE, "Camera", NULL), + .stream_properties = pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", + PW_KEY_MEDIA_ROLE, "Camera", NULL), .video = { .resolution = resolution, .framerate = framerate, }}; - camera_source->obs_pw_stream = obs_pipewire_connect_stream( - connection->obs_pw, camera_source->source, device->id, - &connect_info); + camera_source->obs_pw_stream = + obs_pipewire_connect_stream(connection->obs_pw, camera_source->source, device->id, &connect_info); } static void camera_format_list(struct camera_device *dev, obs_property_t *prop) @@ -308,17 +293,14 @@ static void camera_format_list(struct camera_device *dev, obs_property_t *prop) if (media_type != SPA_MEDIA_TYPE_video) continue; if (media_subtype == SPA_MEDIA_SUBTYPE_raw) { - if (spa_pod_parse_object(p->param, - SPA_TYPE_OBJECT_Format, NULL, - SPA_FORMAT_VIDEO_format, + if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_format, SPA_POD_Id(&format)) < 0) continue; } else { format = SPA_VIDEO_FORMAT_ENCODED; } - if (!obs_pw_video_format_from_spa_format(format, - &obs_pw_video_format)) + if (!obs_pw_video_format_from_spa_format(format, &obs_pw_video_format)) continue; if (obs_pw_video_format.video_format == last_format) @@ -326,13 +308,11 @@ static void camera_format_list(struct camera_device *dev, obs_property_t *prop) last_format = obs_pw_video_format.video_format; - obs_property_list_add_int(prop, obs_pw_video_format.pretty_name, - format); + obs_property_list_add_int(prop, obs_pw_video_format.pretty_name, format); } } -static bool control_changed(void *data, obs_properties_t *props, - obs_property_t *prop, obs_data_t *settings) +static bool control_changed(void *data, obs_properties_t *props, obs_property_t *prop, obs_data_t *settings) { UNUSED_PARAMETER(props); @@ -354,8 +334,7 @@ static bool control_changed(void *data, obs_properties_t *props, id = SPA_PTR_TO_UINT32(data); - spa_pod_builder_push_object(&b, &f[0], SPA_TYPE_OBJECT_Props, - SPA_PARAM_Props); + spa_pod_builder_push_object(&b, &f[0], SPA_TYPE_OBJECT_Props, SPA_PARAM_Props); switch (obs_property_get_type(prop)) { case OBS_PROPERTY_BOOL: { @@ -364,8 +343,7 @@ static bool control_changed(void *data, obs_properties_t *props, break; } case OBS_PROPERTY_FLOAT: { - float val = - obs_data_get_double(settings, obs_property_name(prop)); + float val = obs_data_get_double(settings, obs_property_name(prop)); spa_pod_builder_add(&b, id, SPA_POD_Float(val), 0); break; } @@ -376,21 +354,17 @@ static bool control_changed(void *data, obs_properties_t *props, break; } default: - blog(LOG_ERROR, "unknown property type for %s", - obs_property_name(prop)); + blog(LOG_ERROR, "unknown property type for %s", obs_property_name(prop)); return false; } param = spa_pod_builder_pop(&b, &f[0]); - pw_node_set_param((struct pw_node *)dev->proxy, SPA_PARAM_Props, 0, - param); + pw_node_set_param((struct pw_node *)dev->proxy, SPA_PARAM_Props, 0, param); return true; } -static inline void add_control_property(obs_properties_t *props, - obs_data_t *settings, - struct camera_device *dev, +static inline void add_control_property(obs_properties_t *props, obs_data_t *settings, struct camera_device *dev, struct param *p) { UNUSED_PARAMETER(dev); @@ -400,13 +374,10 @@ static inline void add_control_property(obs_properties_t *props, obs_property_t *prop = NULL; const char *name; - if (spa_pod_parse_object( - p->param, SPA_TYPE_OBJECT_PropInfo, NULL, SPA_PROP_INFO_id, - SPA_POD_Id(&id), SPA_PROP_INFO_description, - SPA_POD_OPT_String(&name), SPA_PROP_INFO_type, - SPA_POD_PodChoice(&type), SPA_PROP_INFO_container, - SPA_POD_OPT_Id(&container), SPA_PROP_INFO_labels, - SPA_POD_OPT_PodStruct(&labels)) < 0) + if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_PropInfo, NULL, SPA_PROP_INFO_id, SPA_POD_Id(&id), + SPA_PROP_INFO_description, SPA_POD_OPT_String(&name), SPA_PROP_INFO_type, + SPA_POD_PodChoice(&type), SPA_PROP_INFO_container, SPA_POD_OPT_Id(&container), + SPA_PROP_INFO_labels, SPA_POD_OPT_PodStruct(&labels)) < 0) return; pod = spa_pod_get_values(type, &n_vals, &choice); @@ -427,9 +398,7 @@ static inline void add_control_property(obs_properties_t *props, if (labels == NULL) return; - prop = obs_properties_add_list(props, (char *)name, - (char *)name, - OBS_COMBO_TYPE_LIST, + prop = obs_properties_add_list(props, (char *)name, (char *)name, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); spa_pod_parser_pod(&prs, (struct spa_pod *)labels); @@ -439,35 +408,27 @@ static inline void add_control_property(obs_properties_t *props, while (1) { int32_t id; const char *desc; - if (spa_pod_parser_get_int(&prs, &id) < 0 || - spa_pod_parser_get_string(&prs, &desc) < 0) + if (spa_pod_parser_get_int(&prs, &id) < 0 || spa_pod_parser_get_string(&prs, &desc) < 0) break; - obs_property_list_add_int(prop, (char *)desc, - id); + obs_property_list_add_int(prop, (char *)desc, id); } } else { min = n_vals > 1 ? vals[1] : def; max = n_vals > 2 ? vals[2] : def; step = n_vals > 3 ? vals[3] : (max - min) / 256.0f; - prop = obs_properties_add_int_slider(props, - (char *)name, - (char *)name, min, - max, step); + prop = obs_properties_add_int_slider(props, (char *)name, (char *)name, min, max, step); } obs_data_set_default_int(settings, (char *)name, def); - obs_property_set_modified_callback2(prop, control_changed, - SPA_UINT32_TO_PTR(id)); + obs_property_set_modified_callback2(prop, control_changed, SPA_UINT32_TO_PTR(id)); break; } case SPA_TYPE_Bool: { int32_t *vals = SPA_POD_BODY(pod); if (n_vals < 1) return; - prop = obs_properties_add_bool(props, (char *)name, - (char *)name); + prop = obs_properties_add_bool(props, (char *)name, (char *)name); obs_data_set_default_bool(settings, (char *)name, vals[0]); - obs_property_set_modified_callback2(prop, control_changed, - SPA_UINT32_TO_PTR(id)); + obs_property_set_modified_callback2(prop, control_changed, SPA_UINT32_TO_PTR(id)); break; } case SPA_TYPE_Float: { @@ -479,11 +440,9 @@ static inline void add_control_property(obs_properties_t *props, min = n_vals > 1 ? vals[1] : def; max = n_vals > 2 ? vals[2] : def; step = n_vals > 3 ? vals[3] : (max - min) / 256.0f; - prop = obs_properties_add_float_slider( - props, (char *)name, (char *)name, min, max, step); + prop = obs_properties_add_float_slider(props, (char *)name, (char *)name, min, max, step); obs_data_set_default_double(settings, (char *)name, def); - obs_property_set_modified_callback2(prop, control_changed, - SPA_UINT32_TO_PTR(id)); + obs_property_set_modified_callback2(prop, control_changed, SPA_UINT32_TO_PTR(id)); break; } default: @@ -491,9 +450,7 @@ static inline void add_control_property(obs_properties_t *props, } } -static void camera_update_controls(struct camera_device *dev, - obs_properties_t *props, - obs_data_t *settings) +static void camera_update_controls(struct camera_device *dev, obs_properties_t *props, obs_data_t *settings) { struct param *p; spa_list_for_each(p, &dev->param_list, link) @@ -504,8 +461,7 @@ static void camera_update_controls(struct camera_device *dev, } } -static bool device_selected(void *data, obs_properties_t *props, - obs_property_t *property, obs_data_t *settings) +static bool device_selected(void *data, obs_properties_t *props, obs_property_t *property, obs_data_t *settings) { UNUSED_PARAMETER(props); UNUSED_PARAMETER(property); @@ -534,9 +490,8 @@ static bool device_selected(void *data, obs_properties_t *props, camera_format_list(device, property); camera_update_controls(device, new_control_properties, settings); - obs_properties_add_group(props, "controls", - obs_module_text("CameraControls"), - OBS_GROUP_NORMAL, new_control_properties); + obs_properties_add_group(props, "controls", obs_module_text("CameraControls"), OBS_GROUP_NORMAL, + new_control_properties); obs_property_modified(property, settings); @@ -553,8 +508,7 @@ static int sort_resolutions(gconstpointer a, gconstpointer b) return area_a - area_b; } -static void resolution_list(struct camera_device *dev, uint32_t pixelformat, - obs_property_t *prop) +static void resolution_list(struct camera_device *dev, uint32_t pixelformat, obs_property_t *prop) { struct spa_rectangle last_resolution = SPA_RECTANGLE(0, 0); g_autoptr(GArray) resolutions = NULL; @@ -577,30 +531,24 @@ static void resolution_list(struct camera_device *dev, uint32_t pixelformat, if (media_type != SPA_MEDIA_TYPE_video) continue; if (media_subtype == SPA_MEDIA_SUBTYPE_raw) { - if (spa_pod_parse_object(p->param, - SPA_TYPE_OBJECT_Format, NULL, - SPA_FORMAT_VIDEO_format, + if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_format, SPA_POD_Id(&format)) < 0) continue; } else { format = SPA_VIDEO_FORMAT_ENCODED; } - if (!obs_pw_video_format_from_spa_format(format, - &obs_pw_video_format)) + if (!obs_pw_video_format_from_spa_format(format, &obs_pw_video_format)) continue; if (obs_pw_video_format.video_format != pixelformat) continue; - if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, - SPA_FORMAT_VIDEO_size, - SPA_POD_OPT_Rectangle(&resolution)) < - 0) + if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_size, + SPA_POD_OPT_Rectangle(&resolution)) < 0) continue; - if (resolution.width == last_resolution.width && - resolution.height == last_resolution.height) + if (resolution.width == last_resolution.width && resolution.height == last_resolution.height) continue; last_resolution = resolution; @@ -613,18 +561,15 @@ static void resolution_list(struct camera_device *dev, uint32_t pixelformat, data = obs_data_create(); for (size_t i = 0; i < resolutions->len; i++) { - const struct spa_rectangle *resolution = - &g_array_index(resolutions, struct spa_rectangle, i); + const struct spa_rectangle *resolution = &g_array_index(resolutions, struct spa_rectangle, i); struct dstr str = {}; - dstr_printf(&str, "%ux%u", resolution->width, - resolution->height); + dstr_printf(&str, "%ux%u", resolution->width, resolution->height); obs_data_set_int(data, "width", resolution->width); obs_data_set_int(data, "height", resolution->height); - obs_property_list_add_string(prop, str.array, - obs_data_get_json(data)); + obs_property_list_add_string(prop, str.array, obs_data_get_json(data)); dstr_free(&str); } @@ -634,8 +579,7 @@ static void resolution_list(struct camera_device *dev, uint32_t pixelformat, /* * Format selected callback */ -static bool format_selected(void *data, obs_properties_t *properties, - obs_property_t *property, obs_data_t *settings) +static bool format_selected(void *data, obs_properties_t *properties, obs_property_t *property, obs_data_t *settings) { UNUSED_PARAMETER(property); UNUSED_PARAMETER(settings); @@ -644,17 +588,14 @@ static bool format_selected(void *data, obs_properties_t *properties, struct camera_device *device; obs_property_t *resolution; - blog(LOG_INFO, "[camera-portal] Selected format for '%s'", - camera_source->device_id); + blog(LOG_INFO, "[camera-portal] Selected format for '%s'", camera_source->device_id); - device = g_hash_table_lookup(connection->devices, - camera_source->device_id); + device = g_hash_table_lookup(connection->devices, camera_source->device_id); if (device == NULL) return false; resolution = obs_properties_get(properties, "resolution"); - resolution_list(device, obs_data_get_int(settings, "pixelformat"), - resolution); + resolution_list(device, obs_data_get_int(settings, "pixelformat"), resolution); return true; } @@ -669,8 +610,7 @@ static int compare_framerates(gconstpointer a, gconstpointer b) return da - db; } -static void framerate_list(struct camera_device *dev, uint32_t pixelformat, - const struct spa_rectangle *resolution, +static void framerate_list(struct camera_device *dev, uint32_t pixelformat, const struct spa_rectangle *resolution, obs_property_t *prop) { g_autoptr(GArray) framerates = NULL; @@ -700,42 +640,33 @@ static void framerate_list(struct camera_device *dev, uint32_t pixelformat, if (media_type != SPA_MEDIA_TYPE_video) continue; if (media_subtype == SPA_MEDIA_SUBTYPE_raw) { - if (spa_pod_parse_object(p->param, - SPA_TYPE_OBJECT_Format, NULL, - SPA_FORMAT_VIDEO_format, + if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_format, SPA_POD_Id(&format)) < 0) continue; } else { format = SPA_VIDEO_FORMAT_ENCODED; } - if (!obs_pw_video_format_from_spa_format(format, - &obs_pw_video_format)) + if (!obs_pw_video_format_from_spa_format(format, &obs_pw_video_format)) continue; if (obs_pw_video_format.video_format != pixelformat) continue; - if (spa_pod_parse_object( - p->param, SPA_TYPE_OBJECT_Format, NULL, - SPA_FORMAT_VIDEO_size, - SPA_POD_OPT_Rectangle(&this_resolution)) < 0) + if (spa_pod_parse_object(p->param, SPA_TYPE_OBJECT_Format, NULL, SPA_FORMAT_VIDEO_size, + SPA_POD_OPT_Rectangle(&this_resolution)) < 0) continue; - if (this_resolution.width != resolution->width || - this_resolution.height != resolution->height) + if (this_resolution.width != resolution->width || this_resolution.height != resolution->height) continue; - prop = spa_pod_find_prop(p->param, NULL, - SPA_FORMAT_VIDEO_framerate); + prop = spa_pod_find_prop(p->param, NULL, SPA_FORMAT_VIDEO_framerate); if (!prop) continue; - framerate_pod = spa_pod_get_values(&prop->value, &n_framerates, - &choice); + framerate_pod = spa_pod_get_values(&prop->value, &n_framerates, &choice); if (framerate_pod->type != SPA_TYPE_Fraction) { - blog(LOG_WARNING, - "Framerate is not a fraction - something is wrong"); + blog(LOG_WARNING, "Framerate is not a fraction - something is wrong"); continue; } @@ -754,8 +685,7 @@ static void framerate_list(struct camera_device *dev, uint32_t pixelformat, case SPA_CHOICE_Enum: /* i=0 is the default framerate, skip it */ for (uint32_t i = 1; i < n_framerates; i++) - g_array_append_val(framerates, - framerate_values[i]); + g_array_append_val(framerates, framerate_values[i]); break; default: break; @@ -768,8 +698,7 @@ static void framerate_list(struct camera_device *dev, uint32_t pixelformat, data = obs_data_create(); for (size_t i = 0; i < framerates->len; i++) { - const struct spa_fraction *framerate = - &g_array_index(framerates, struct spa_fraction, i); + const struct spa_fraction *framerate = &g_array_index(framerates, struct spa_fraction, i); struct media_frames_per_second fps; struct dstr str = {}; @@ -779,10 +708,8 @@ static void framerate_list(struct camera_device *dev, uint32_t pixelformat, }; obs_data_set_frames_per_second(data, "framerate", fps, NULL); - dstr_printf(&str, "%.2f", - framerate->num / (double)framerate->denom); - obs_property_list_add_string(prop, str.array, - obs_data_get_json(data)); + dstr_printf(&str, "%.2f", framerate->num / (double)framerate->denom); + obs_property_list_add_string(prop, str.array, obs_data_get_json(data)); dstr_free(&str); } @@ -809,8 +736,7 @@ static bool parse_framerate(struct spa_fraction *dest, const char *json) return true; } -static bool framerate_selected(void *data, obs_properties_t *properties, - obs_property_t *property, obs_data_t *settings) +static bool framerate_selected(void *data, obs_properties_t *properties, obs_property_t *property, obs_data_t *settings) { UNUSED_PARAMETER(properties); UNUSED_PARAMETER(property); @@ -819,18 +745,15 @@ static bool framerate_selected(void *data, obs_properties_t *properties, struct camera_device *device; struct spa_fraction framerate; - device = g_hash_table_lookup(connection->devices, - camera_source->device_id); + device = g_hash_table_lookup(connection->devices, camera_source->device_id); if (device == NULL) return false; - if (!parse_framerate(&framerate, - obs_data_get_string(settings, "framerate"))) + if (!parse_framerate(&framerate, obs_data_get_string(settings, "framerate"))) return false; if (camera_source->obs_pw_stream) - obs_pipewire_stream_set_framerate(camera_source->obs_pw_stream, - &framerate); + obs_pipewire_stream_set_framerate(camera_source->obs_pw_stream, &framerate); return true; } @@ -852,8 +775,8 @@ static bool parse_resolution(struct spa_rectangle *dest, const char *json) return true; } -static bool resolution_selected(void *data, obs_properties_t *properties, - obs_property_t *property, obs_data_t *settings) +static bool resolution_selected(void *data, obs_properties_t *properties, obs_property_t *property, + obs_data_t *settings) { UNUSED_PARAMETER(properties); UNUSED_PARAMETER(property); @@ -863,31 +786,25 @@ static bool resolution_selected(void *data, obs_properties_t *properties, struct spa_rectangle resolution; struct camera_device *device; - blog(LOG_INFO, "[camera-portal] Selected resolution for '%s'", - camera_source->device_id); + blog(LOG_INFO, "[camera-portal] Selected resolution for '%s'", camera_source->device_id); - device = g_hash_table_lookup(connection->devices, - camera_source->device_id); + device = g_hash_table_lookup(connection->devices, camera_source->device_id); if (device == NULL) return false; - if (!parse_resolution(&resolution, - obs_data_get_string(settings, "resolution"))) + if (!parse_resolution(&resolution, obs_data_get_string(settings, "resolution"))) return false; if (camera_source->obs_pw_stream) - obs_pipewire_stream_set_resolution(camera_source->obs_pw_stream, - &resolution); + obs_pipewire_stream_set_resolution(camera_source->obs_pw_stream, &resolution); property = obs_properties_get(properties, "framerate"); - framerate_list(device, obs_data_get_int(settings, "pixelformat"), - &resolution, property); + framerate_list(device, obs_data_get_int(settings, "pixelformat"), &resolution, property); return true; } -static void populate_cameras_list(struct camera_portal_source *camera_source, - obs_property_t *device_list) +static void populate_cameras_list(struct camera_portal_source *camera_source, obs_property_t *device_list) { struct camera_device *device; GHashTableIter iter; @@ -901,25 +818,20 @@ static void populate_cameras_list(struct camera_portal_source *camera_source, device_found = false; g_hash_table_iter_init(&iter, connection->devices); - while (g_hash_table_iter_next(&iter, (gpointer *)&device_id, - (gpointer *)&device)) { + while (g_hash_table_iter_next(&iter, (gpointer *)&device_id, (gpointer *)&device)) { const char *device_name; - device_name = pw_properties_get(device->properties, - PW_KEY_NODE_DESCRIPTION); + device_name = pw_properties_get(device->properties, PW_KEY_NODE_DESCRIPTION); - obs_property_list_add_string(device_list, device_name, - device_id); + obs_property_list_add_string(device_list, device_name, device_id); - device_found |= strcmp(device_id, camera_source->device_id) == - 0; + device_found |= strcmp(device_id, camera_source->device_id) == 0; } if (!device_found && camera_source->device_id) { size_t device_index; - device_index = obs_property_list_add_string( - device_list, camera_source->device_id, - camera_source->device_id); + device_index = + obs_property_list_add_string(device_list, camera_source->device_id, camera_source->device_id); obs_property_list_item_disable(device_list, device_index, true); } } @@ -949,9 +861,8 @@ static void node_info(void *data, const struct pw_node_info *info) if (!(info->params[i].flags & SPA_PARAM_INFO_READ)) continue; - res = pw_node_enum_params( - (struct pw_node *)device->proxy, - ++info->params[i].seq, id, 0, -1, NULL); + res = pw_node_enum_params((struct pw_node *)device->proxy, ++info->params[i].seq, id, 0, -1, + NULL); if (SPA_RESULT_IS_ASYNC(res)) info->params[i].seq = res; } @@ -959,13 +870,11 @@ static void node_info(void *data, const struct pw_node_info *info) if (changed) { device->changed += changed; - device->pending_sync = - pw_proxy_sync(device->proxy, device->pending_sync); + device->pending_sync = pw_proxy_sync(device->proxy, device->pending_sync); } } -static void node_param(void *data, int seq, uint32_t id, uint32_t index, - uint32_t next, const struct spa_pod *param) +static void node_param(void *data, int seq, uint32_t id, uint32_t index, uint32_t next, const struct spa_pod *param) { UNUSED_PARAMETER(index); UNUSED_PARAMETER(next); @@ -998,8 +907,7 @@ static void on_done_proxy_cb(void *data, int seq) { struct camera_device *device = data; if (device->info != NULL && device->pending_sync == seq) { - object_update_params(&device->param_list, &device->pending_list, - device->info->n_params, + object_update_params(&device->param_list, &device->pending_list, device->info->n_params, device->info->params); } } @@ -1011,10 +919,8 @@ static const struct pw_proxy_events proxy_events = { .done = on_done_proxy_cb, }; -static void on_registry_global_cb(void *user_data, uint32_t id, - uint32_t permissions, const char *type, - uint32_t version, - const struct spa_dict *props) +static void on_registry_global_cb(void *user_data, uint32_t id, uint32_t permissions, const char *type, + uint32_t version, const struct spa_dict *props) { UNUSED_PARAMETER(user_data); UNUSED_PARAMETER(permissions); @@ -1035,22 +941,18 @@ static void on_registry_global_cb(void *user_data, uint32_t id, device = camera_device_new(id, props); device->proxy = pw_registry_bind(registry, id, type, version, 0); if (!device->proxy) { - blog(LOG_WARNING, "[camera-portal] Failed to bind device %s", - device_id); + blog(LOG_WARNING, "[camera-portal] Failed to bind device %s", device_id); bfree(device); return; } - pw_proxy_add_listener(device->proxy, &device->proxy_listener, - &proxy_events, device); + pw_proxy_add_listener(device->proxy, &device->proxy_listener, &proxy_events, device); device->node = (struct pw_node *)device->proxy; - pw_node_add_listener(device->node, &device->node_listener, &node_events, - device); + pw_node_add_listener(device->node, &device->node_listener, &node_events, device); g_hash_table_insert(connection->devices, bstrdup(device_id), device); for (size_t i = 0; i < connection->sources->len; i++) { - struct camera_portal_source *camera_source = - g_ptr_array_index(connection->sources, i); + struct camera_portal_source *camera_source = g_ptr_array_index(connection->sources, i); obs_source_update_properties(camera_source->source); if (strcmp(camera_source->device_id, device_id) == 0) stream_camera(camera_source); @@ -1066,17 +968,14 @@ static void on_registry_global_remove_cb(void *user_data, uint32_t id) GHashTableIter iter; g_hash_table_iter_init(&iter, connection->devices); - while (g_hash_table_iter_next(&iter, (gpointer *)&device_id, - (gpointer *)&device)) { + while (g_hash_table_iter_next(&iter, (gpointer *)&device_id, (gpointer *)&device)) { if (device->id != id) continue; g_hash_table_iter_remove(&iter); - blog(LOG_INFO, "[pipewire-camera] Removed device %s", - device_id); + blog(LOG_INFO, "[pipewire-camera] Removed device %s", device_id); } for (size_t i = 0; i < connection->sources->len; i++) { - struct camera_portal_source *camera_source = - g_ptr_array_index(connection->sources, i); + struct camera_portal_source *camera_source = g_ptr_array_index(connection->sources, i); obs_source_update_properties(camera_source->source); } } @@ -1089,8 +988,7 @@ static const struct pw_registry_events registry_events = { /* ------------------------------------------------- */ -static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, - void *user_data) +static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, void *user_data) { UNUSED_PARAMETER(user_data); @@ -1100,13 +998,10 @@ static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, int pipewire_fd; int fd_index; - result = g_dbus_proxy_call_with_unix_fd_list_finish( - G_DBUS_PROXY(source), &fd_list, res, &error); + result = g_dbus_proxy_call_with_unix_fd_list_finish(G_DBUS_PROXY(source), &fd_list, res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[camera-portal] Error retrieving PipeWire fd: %s", - error->message); + blog(LOG_ERROR, "[camera-portal] Error retrieving PipeWire fd: %s", error->message); return; } @@ -1115,14 +1010,11 @@ static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, pipewire_fd = g_unix_fd_list_get(fd_list, fd_index, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[camera-portal] Error retrieving PipeWire fd: %s", - error->message); + blog(LOG_ERROR, "[camera-portal] Error retrieving PipeWire fd: %s", error->message); return; } - connection->obs_pw = obs_pipewire_connect_fd( - pipewire_fd, ®istry_events, connection); + connection->obs_pw = obs_pipewire_connect_fd(pipewire_fd, ®istry_events, connection); obs_pipewire_roundtrip(connection->obs_pw); } @@ -1133,18 +1025,14 @@ static void open_pipewire_remote(void) g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_dbus_proxy_call_with_unix_fd_list(get_camera_portal_proxy(), - "OpenPipeWireRemote", - g_variant_new("(a{sv})", &builder), - G_DBUS_CALL_FLAGS_NONE, -1, NULL, - connection->cancellable, - on_pipewire_remote_opened_cb, NULL); + g_dbus_proxy_call_with_unix_fd_list(get_camera_portal_proxy(), "OpenPipeWireRemote", + g_variant_new("(a{sv})", &builder), G_DBUS_CALL_FLAGS_NONE, -1, NULL, + connection->cancellable, on_pipewire_remote_opened_cb, NULL); } /* ------------------------------------------------- */ -static void on_access_camera_response_received_cb(GVariant *parameters, - void *user_data) +static void on_access_camera_response_received_cb(GVariant *parameters, void *user_data) { UNUSED_PARAMETER(user_data); @@ -1154,8 +1042,7 @@ static void on_access_camera_response_received_cb(GVariant *parameters, g_variant_get(parameters, "(u@a{sv})", &response, &result); if (response != 0) { - blog(LOG_WARNING, - "[camera-portal] Failed to create session, denied or cancelled by user"); + blog(LOG_WARNING, "[camera-portal] Failed to create session, denied or cancelled by user"); return; } @@ -1164,8 +1051,7 @@ static void on_access_camera_response_received_cb(GVariant *parameters, open_pipewire_remote(); } -static void on_access_camera_finished_cb(GObject *source, GAsyncResult *res, - void *user_data) +static void on_access_camera_finished_cb(GObject *source, GAsyncResult *res, void *user_data) { UNUSED_PARAMETER(user_data); @@ -1175,9 +1061,7 @@ static void on_access_camera_finished_cb(GObject *source, GAsyncResult *res, result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[camera-portal] Error accessing camera: %s", - error->message); + blog(LOG_ERROR, "[camera-portal] Error accessing camera: %s", error->message); return; } } @@ -1195,9 +1079,8 @@ static void access_camera(struct camera_portal_source *camera_source) if (!connection) { connection = bzalloc(sizeof(struct pw_portal_connection)); - connection->devices = g_hash_table_new_full( - g_str_hash, g_str_equal, bfree, - (GDestroyNotify)camera_device_free); + connection->devices = + g_hash_table_new_full(g_str_hash, g_str_equal, bfree, (GDestroyNotify)camera_device_free); connection->cancellable = g_cancellable_new(); connection->sources = g_ptr_array_new(); connection->initializing = false; @@ -1210,17 +1093,13 @@ static void access_camera(struct camera_portal_source *camera_source) portal_create_request_path(&request_path, &request_token); - portal_signal_subscribe(request_path, NULL, - on_access_camera_response_received_cb, NULL); + portal_signal_subscribe(request_path, NULL, on_access_camera_response_received_cb, NULL); g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_variant_builder_add(&builder, "{sv}", "handle_token", - g_variant_new_string(request_token)); + g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token)); - g_dbus_proxy_call(get_camera_portal_proxy(), "AccessCamera", - g_variant_new("(a{sv})", &builder), - G_DBUS_CALL_FLAGS_NONE, -1, connection->cancellable, - on_access_camera_finished_cb, NULL); + g_dbus_proxy_call(get_camera_portal_proxy(), "AccessCamera", g_variant_new("(a{sv})", &builder), + G_DBUS_CALL_FLAGS_NONE, -1, connection->cancellable, on_access_camera_finished_cb, NULL); connection->initializing = true; @@ -1242,14 +1121,11 @@ static void *pipewire_camera_create(obs_data_t *settings, obs_source_t *source) camera_source = bzalloc(sizeof(struct camera_portal_source)); camera_source->source = source; - camera_source->device_id = - bstrdup(obs_data_get_string(settings, "device_id")); + camera_source->device_id = bstrdup(obs_data_get_string(settings, "device_id")); camera_source->framerate.set = - parse_framerate(&camera_source->framerate.fraction, - obs_data_get_string(settings, "framerate")); + parse_framerate(&camera_source->framerate.fraction, obs_data_get_string(settings, "framerate")); camera_source->resolution.set = - parse_resolution(&camera_source->resolution.rect, - obs_data_get_string(settings, "resolution")); + parse_resolution(&camera_source->resolution.rect, obs_data_get_string(settings, "resolution")); access_camera(camera_source); @@ -1263,8 +1139,7 @@ static void pipewire_camera_destroy(void *data) if (connection) g_ptr_array_remove(connection->sources, camera_source); - g_clear_pointer(&camera_source->obs_pw_stream, - obs_pipewire_stream_destroy); + g_clear_pointer(&camera_source->obs_pw_stream, obs_pipewire_stream_destroy); g_clear_pointer(&camera_source->device_id, bfree); bfree(camera_source); @@ -1287,41 +1162,29 @@ static obs_properties_t *pipewire_camera_get_properties(void *data) props = obs_properties_create(); - device_list = obs_properties_add_list( - props, "device_id", obs_module_text("PipeWireCameraDevice"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + device_list = obs_properties_add_list(props, "device_id", obs_module_text("PipeWireCameraDevice"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - format_list = obs_properties_add_list(props, "pixelformat", - obs_module_text("VideoFormat"), - OBS_COMBO_TYPE_LIST, + format_list = obs_properties_add_list(props, "pixelformat", obs_module_text("VideoFormat"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - resolution_list = obs_properties_add_list(props, "resolution", - obs_module_text("Resolution"), - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + resolution_list = obs_properties_add_list(props, "resolution", obs_module_text("Resolution"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - framerate_list = obs_properties_add_list(props, "framerate", - obs_module_text("FrameRate"), - OBS_COMBO_TYPE_LIST, + framerate_list = obs_properties_add_list(props, "framerate", obs_module_text("FrameRate"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); // a group to contain the camera control controls_props = obs_properties_create(); - obs_properties_add_group(props, "controls", - obs_module_text("CameraControls"), - OBS_GROUP_NORMAL, controls_props); + obs_properties_add_group(props, "controls", obs_module_text("CameraControls"), OBS_GROUP_NORMAL, + controls_props); populate_cameras_list(camera_source, device_list); - obs_property_set_modified_callback2(device_list, device_selected, - camera_source); - obs_property_set_modified_callback2(format_list, format_selected, - camera_source); - obs_property_set_modified_callback2(resolution_list, - resolution_selected, camera_source); - obs_property_set_modified_callback2(framerate_list, framerate_selected, - camera_source); + obs_property_set_modified_callback2(device_list, device_selected, camera_source); + obs_property_set_modified_callback2(format_list, format_selected, camera_source); + obs_property_set_modified_callback2(resolution_list, resolution_selected, camera_source); + obs_property_set_modified_callback2(framerate_list, framerate_selected, camera_source); return props; } @@ -1360,8 +1223,7 @@ static uint32_t pipewire_camera_get_width(void *data) struct camera_portal_source *camera_source = data; if (camera_source->obs_pw_stream) - return obs_pipewire_stream_get_width( - camera_source->obs_pw_stream); + return obs_pipewire_stream_get_width(camera_source->obs_pw_stream); else return 0; } @@ -1371,8 +1233,7 @@ static uint32_t pipewire_camera_get_height(void *data) struct camera_portal_source *camera_source = data; if (camera_source->obs_pw_stream) - return obs_pipewire_stream_get_height( - camera_source->obs_pw_stream); + return obs_pipewire_stream_get_height(camera_source->obs_pw_stream); else return 0; } diff --git a/plugins/linux-pipewire/formats.c b/plugins/linux-pipewire/formats.c index 1b3212da0..e1d6706aa 100644 --- a/plugins/linux-pipewire/formats.c +++ b/plugins/linux-pipewire/formats.c @@ -103,11 +103,9 @@ static const struct obs_pw_video_format supported_formats[] = { #endif }; -#define N_SUPPORTED_FORMATS \ - (sizeof(supported_formats) / sizeof(supported_formats[0])) +#define N_SUPPORTED_FORMATS (sizeof(supported_formats) / sizeof(supported_formats[0])) -bool obs_pw_video_format_from_spa_format( - uint32_t spa_format, struct obs_pw_video_format *out_video_format) +bool obs_pw_video_format_from_spa_format(uint32_t spa_format, struct obs_pw_video_format *out_video_format) { for (size_t i = 0; i < N_SUPPORTED_FORMATS; i++) { if (supported_formats[i].spa_format != spa_format) diff --git a/plugins/linux-pipewire/formats.h b/plugins/linux-pipewire/formats.h index dbea8579b..3d3359478 100644 --- a/plugins/linux-pipewire/formats.h +++ b/plugins/linux-pipewire/formats.h @@ -35,5 +35,4 @@ struct obs_pw_video_format { const char *pretty_name; }; -bool obs_pw_video_format_from_spa_format( - uint32_t spa_format, struct obs_pw_video_format *out_format_info); +bool obs_pw_video_format_from_spa_format(uint32_t spa_format, struct obs_pw_video_format *out_format_info); diff --git a/plugins/linux-pipewire/pipewire.c b/plugins/linux-pipewire/pipewire.c index 0bf2d2ece..bb822d999 100644 --- a/plugins/linux-pipewire/pipewire.c +++ b/plugins/linux-pipewire/pipewire.c @@ -42,14 +42,14 @@ #if !PW_CHECK_VERSION(0, 3, 62) enum spa_meta_videotransform_value { - SPA_META_TRANSFORMATION_None = 0, /**< no transform */ - SPA_META_TRANSFORMATION_90, /**< 90 degree counter-clockwise */ - SPA_META_TRANSFORMATION_180, /**< 180 degree counter-clockwise */ - SPA_META_TRANSFORMATION_270, /**< 270 degree counter-clockwise */ - SPA_META_TRANSFORMATION_Flipped, /**< 180 degree flipped around the vertical axis. Equivalent + SPA_META_TRANSFORMATION_None = 0, /**< no transform */ + SPA_META_TRANSFORMATION_90, /**< 90 degree counter-clockwise */ + SPA_META_TRANSFORMATION_180, /**< 180 degree counter-clockwise */ + SPA_META_TRANSFORMATION_270, /**< 270 degree counter-clockwise */ + SPA_META_TRANSFORMATION_Flipped, /**< 180 degree flipped around the vertical axis. Equivalent * to a reflexion through the vertical line splitting the * bufffer in two equal sized parts */ - SPA_META_TRANSFORMATION_Flipped90, /**< flip then rotate around 90 degree counter-clockwise */ + SPA_META_TRANSFORMATION_Flipped90, /**< flip then rotate around 90 degree counter-clockwise */ SPA_META_TRANSFORMATION_Flipped180, /**< flip then rotate around 180 degree counter-clockwise */ SPA_META_TRANSFORMATION_Flipped270, /**< flip then rotate around 270 degree counter-clockwise */ }; @@ -61,9 +61,8 @@ struct spa_meta_videotransform { }; #endif -#define CURSOR_META_SIZE(width, height) \ - (sizeof(struct spa_meta_cursor) + sizeof(struct spa_meta_bitmap) + \ - width * height * 4) +#define CURSOR_META_SIZE(width, height) \ + (sizeof(struct spa_meta_cursor) + sizeof(struct spa_meta_bitmap) + width * height * 4) struct obs_pw_version { int major; @@ -144,13 +143,11 @@ struct _obs_pipewire_stream { static bool parse_pw_version(struct obs_pw_version *dst, const char *version) { - int n_matches = sscanf(version, "%d.%d.%d", &dst->major, &dst->minor, - &dst->micro); + int n_matches = sscanf(version, "%d.%d.%d", &dst->major, &dst->minor, &dst->micro); return n_matches == 3; } -static bool check_pw_version(const struct obs_pw_version *pw_version, int major, - int minor, int micro) +static bool check_pw_version(const struct obs_pw_version *pw_version, int major, int minor, int micro) { if (pw_version->major != major) return pw_version->major > major; @@ -162,10 +159,8 @@ static bool check_pw_version(const struct obs_pw_version *pw_version, int major, static void update_pw_versions(obs_pipewire *obs_pw, const char *version) { blog(LOG_INFO, "[pipewire] Server version: %s", version); - blog(LOG_INFO, "[pipewire] Library version: %s", - pw_get_library_version()); - blog(LOG_INFO, "[pipewire] Header version: %s", - pw_get_headers_version()); + blog(LOG_INFO, "[pipewire] Library version: %s", pw_get_library_version()); + blog(LOG_INFO, "[pipewire] Header version: %s", pw_get_headers_version()); if (!parse_pw_version(&obs_pw->server_version, version)) blog(LOG_WARNING, "[pipewire] failed to parse server version"); @@ -189,12 +184,9 @@ static void teardown_pipewire(obs_pipewire *obs_pw) static inline bool has_effective_crop(obs_pipewire_stream *obs_pw_stream) { - return obs_pw_stream->crop.valid && - (obs_pw_stream->crop.x != 0 || obs_pw_stream->crop.y != 0 || - obs_pw_stream->crop.width < - obs_pw_stream->format.info.raw.size.width || - obs_pw_stream->crop.height < - obs_pw_stream->format.info.raw.size.height); + return obs_pw_stream->crop.valid && (obs_pw_stream->crop.x != 0 || obs_pw_stream->crop.y != 0 || + obs_pw_stream->crop.width < obs_pw_stream->format.info.raw.size.width || + obs_pw_stream->crop.height < obs_pw_stream->format.info.raw.size.height); } static int get_buffer_flip(obs_pipewire_stream *obs_pw_stream) @@ -238,24 +230,18 @@ static bool push_rotation(obs_pipewire_stream *obs_pw_stream) case SPA_META_TRANSFORMATION_90: rotation = 90; offset_x = 0; - offset_y = has_crop - ? obs_pw_stream->crop.height - : obs_pw_stream->format.info.raw.size.height; + offset_y = has_crop ? obs_pw_stream->crop.height : obs_pw_stream->format.info.raw.size.height; break; case SPA_META_TRANSFORMATION_Flipped180: case SPA_META_TRANSFORMATION_180: rotation = 180; - offset_x = has_crop ? obs_pw_stream->crop.width - : obs_pw_stream->format.info.raw.size.width; - offset_y = has_crop - ? obs_pw_stream->crop.height - : obs_pw_stream->format.info.raw.size.height; + offset_x = has_crop ? obs_pw_stream->crop.width : obs_pw_stream->format.info.raw.size.width; + offset_y = has_crop ? obs_pw_stream->crop.height : obs_pw_stream->format.info.raw.size.height; break; case SPA_META_TRANSFORMATION_Flipped270: case SPA_META_TRANSFORMATION_270: rotation = 270; - offset_x = has_crop ? obs_pw_stream->crop.width - : obs_pw_stream->format.info.raw.size.width; + offset_x = has_crop ? obs_pw_stream->crop.width : obs_pw_stream->format.info.raw.size.width; offset_y = 0; break; } @@ -274,19 +260,16 @@ static const uint32_t supported_formats_async[] = { SPA_VIDEO_FORMAT_YUY2, }; -#define N_SUPPORTED_FORMATS_ASYNC \ - (sizeof(supported_formats_async) / sizeof(supported_formats_async[0])) +#define N_SUPPORTED_FORMATS_ASYNC (sizeof(supported_formats_async) / sizeof(supported_formats_async[0])) static const uint32_t supported_formats_sync[] = { - SPA_VIDEO_FORMAT_BGRA, SPA_VIDEO_FORMAT_RGBA, - SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_RGBx, + SPA_VIDEO_FORMAT_BGRA, SPA_VIDEO_FORMAT_RGBA, SPA_VIDEO_FORMAT_BGRx, SPA_VIDEO_FORMAT_RGBx, #if PW_CHECK_VERSION(0, 3, 41) SPA_VIDEO_FORMAT_ABGR_210LE, SPA_VIDEO_FORMAT_xBGR_210LE, #endif }; -#define N_SUPPORTED_FORMATS_SYNC \ - (sizeof(supported_formats_sync) / sizeof(supported_formats_sync[0])) +#define N_SUPPORTED_FORMATS_SYNC (sizeof(supported_formats_sync) / sizeof(supported_formats_sync[0])) static void swap_texture_red_blue(gs_texture_t *texture) { @@ -298,10 +281,8 @@ static void swap_texture_red_blue(gs_texture_t *texture) glBindTexture(GL_TEXTURE_2D, 0); } -static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, - struct spa_pod_builder *b, - uint32_t format, uint64_t *modifiers, - size_t modifier_count) +static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, struct spa_pod_builder *b, + uint32_t format, uint64_t *modifiers, size_t modifier_count) { struct spa_rectangle max_resolution = SPA_RECTANGLE(8192, 4320); struct spa_rectangle min_resolution = SPA_RECTANGLE(1, 1); @@ -316,8 +297,7 @@ static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, min_framerate = obs_pw_stream->framerate.fraction; max_framerate = obs_pw_stream->framerate.fraction; } else { - framerate = SPA_FRACTION(obs_pw_stream->video_info.fps_num, - obs_pw_stream->video_info.fps_den); + framerate = SPA_FRACTION(obs_pw_stream->video_info.fps_num, obs_pw_stream->video_info.fps_den); min_framerate = SPA_FRACTION(0, 1); max_framerate = SPA_FRACTION(360, 1); } @@ -328,8 +308,7 @@ static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, max_resolution = obs_pw_stream->resolution.rect; } else { resolution = - SPA_RECTANGLE(obs_pw_stream->video_info.output_width, - obs_pw_stream->video_info.output_height); + SPA_RECTANGLE(obs_pw_stream->video_info.output_width, obs_pw_stream->video_info.output_height); min_resolution = SPA_RECTANGLE(1, 1); max_resolution = SPA_RECTANGLE(8192, 4320); } @@ -338,13 +317,10 @@ static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, * The object type is important because it defines the properties that are * acceptable. The id gives more context about what the object is meant to * contain. In this case we enumerate supported formats. */ - spa_pod_builder_push_object(b, &format_frame, SPA_TYPE_OBJECT_Format, - SPA_PARAM_EnumFormat); + spa_pod_builder_push_object(b, &format_frame, SPA_TYPE_OBJECT_Format, SPA_PARAM_EnumFormat); /* add media type and media subtype properties */ - spa_pod_builder_add(b, SPA_FORMAT_mediaType, - SPA_POD_Id(SPA_MEDIA_TYPE_video), 0); - spa_pod_builder_add(b, SPA_FORMAT_mediaSubtype, - SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), 0); + spa_pod_builder_add(b, SPA_FORMAT_mediaType, SPA_POD_Id(SPA_MEDIA_TYPE_video), 0); + spa_pod_builder_add(b, SPA_FORMAT_mediaSubtype, SPA_POD_Id(SPA_MEDIA_SUBTYPE_raw), 0); /* formats */ spa_pod_builder_add(b, SPA_FORMAT_VIDEO_format, SPA_POD_Id(format), 0); @@ -355,11 +331,9 @@ static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, /* build an enumeration of modifiers */ spa_pod_builder_prop(b, SPA_FORMAT_VIDEO_modifier, - SPA_POD_PROP_FLAG_MANDATORY | - SPA_POD_PROP_FLAG_DONT_FIXATE); + SPA_POD_PROP_FLAG_MANDATORY | SPA_POD_PROP_FLAG_DONT_FIXATE); - spa_pod_builder_push_choice(b, &modifier_frame, SPA_CHOICE_Enum, - 0); + spa_pod_builder_push_choice(b, &modifier_frame, SPA_CHOICE_Enum, 0); /* The first element of choice pods is the preferred value. Here * we arbitrarily pick the first modifier as the preferred one. @@ -373,32 +347,24 @@ static inline struct spa_pod *build_format(obs_pipewire_stream *obs_pw_stream, spa_pod_builder_pop(b, &modifier_frame); } /* add size and framerate ranges */ - spa_pod_builder_add( - b, SPA_FORMAT_VIDEO_size, - SPA_POD_CHOICE_RANGE_Rectangle(&resolution, &min_resolution, - &max_resolution), - SPA_FORMAT_VIDEO_framerate, - SPA_POD_CHOICE_RANGE_Fraction(&framerate, &min_framerate, - &max_framerate), - 0); + spa_pod_builder_add(b, SPA_FORMAT_VIDEO_size, + SPA_POD_CHOICE_RANGE_Rectangle(&resolution, &min_resolution, &max_resolution), + SPA_FORMAT_VIDEO_framerate, + SPA_POD_CHOICE_RANGE_Fraction(&framerate, &min_framerate, &max_framerate), 0); return spa_pod_builder_pop(b, &format_frame); } -static bool build_format_params(obs_pipewire_stream *obs_pw_stream, - struct spa_pod_builder *pod_builder, - const struct spa_pod ***param_list, - uint32_t *n_params) +static bool build_format_params(obs_pipewire_stream *obs_pw_stream, struct spa_pod_builder *pod_builder, + const struct spa_pod ***param_list, uint32_t *n_params) { obs_pipewire *obs_pw = obs_pw_stream->obs_pw; uint32_t params_count = 0; const struct spa_pod **params; - params = bzalloc(2 * obs_pw_stream->format_info.num * - sizeof(struct spa_pod *)); + params = bzalloc(2 * obs_pw_stream->format_info.num * sizeof(struct spa_pod *)); if (!params) { - blog(LOG_ERROR, - "[pipewire] Failed to allocate memory for param pointers"); + blog(LOG_ERROR, "[pipewire] Failed to allocate memory for param pointers"); return false; } @@ -409,27 +375,23 @@ static bool build_format_params(obs_pipewire_stream *obs_pw_stream, if (obs_pw_stream->format_info.array[i].modifiers.num == 0) { continue; } - params[params_count++] = build_format( - obs_pw_stream, pod_builder, - obs_pw_stream->format_info.array[i].spa_format, - obs_pw_stream->format_info.array[i].modifiers.array, - obs_pw_stream->format_info.array[i].modifiers.num); + params[params_count++] = build_format(obs_pw_stream, pod_builder, + obs_pw_stream->format_info.array[i].spa_format, + obs_pw_stream->format_info.array[i].modifiers.array, + obs_pw_stream->format_info.array[i].modifiers.num); } build_shm: for (size_t i = 0; i < obs_pw_stream->format_info.num; i++) { - params[params_count++] = build_format( - obs_pw_stream, pod_builder, - obs_pw_stream->format_info.array[i].spa_format, NULL, - 0); + params[params_count++] = build_format(obs_pw_stream, pod_builder, + obs_pw_stream->format_info.array[i].spa_format, NULL, 0); } *param_list = params; *n_params = params_count; return true; } -static bool drm_format_available(uint32_t drm_format, uint32_t *drm_formats, - size_t n_drm_formats) +static bool drm_format_available(uint32_t drm_format, uint32_t *drm_formats, size_t n_drm_formats) { for (size_t j = 0; j < n_drm_formats; j++) { if (drm_format == drm_formats[j]) { @@ -446,8 +408,7 @@ static void init_format_info_async(obs_pipewire_stream *obs_pw_stream) for (size_t i = 0; i < N_SUPPORTED_FORMATS_ASYNC; i++) { struct obs_pw_video_format obs_pw_video_format; struct format_info *info; - if (!obs_pw_video_format_from_spa_format( - supported_formats_async[i], &obs_pw_video_format)) + if (!obs_pw_video_format_from_spa_format(supported_formats_async[i], &obs_pw_video_format)) continue; info = da_push_back_new(obs_pw_stream->format_info); @@ -467,14 +428,12 @@ static void init_format_info_sync(obs_pipewire_stream *obs_pw_stream) uint32_t *drm_formats = NULL; size_t n_drm_formats = 0; - bool capabilities_queried = gs_query_dmabuf_capabilities( - &dmabuf_flags, &drm_formats, &n_drm_formats); + bool capabilities_queried = gs_query_dmabuf_capabilities(&dmabuf_flags, &drm_formats, &n_drm_formats); for (size_t i = 0; i < N_SUPPORTED_FORMATS_SYNC; i++) { struct obs_pw_video_format obs_pw_video_format; struct format_info *info; - if (!obs_pw_video_format_from_spa_format( - supported_formats_sync[i], &obs_pw_video_format) || + if (!obs_pw_video_format_from_spa_format(supported_formats_sync[i], &obs_pw_video_format) || obs_pw_video_format.gs_format == GS_UNKNOWN) continue; @@ -484,22 +443,17 @@ static void init_format_info_sync(obs_pipewire_stream *obs_pw_stream) info->drm_format = obs_pw_video_format.drm_format; if (!capabilities_queried || - !drm_format_available(obs_pw_video_format.drm_format, - drm_formats, n_drm_formats)) + !drm_format_available(obs_pw_video_format.drm_format, drm_formats, n_drm_formats)) continue; size_t n_modifiers; uint64_t *modifiers = NULL; - if (gs_query_dmabuf_modifiers_for_format( - obs_pw_video_format.drm_format, &modifiers, - &n_modifiers)) { - da_push_back_array(info->modifiers, modifiers, - n_modifiers); + if (gs_query_dmabuf_modifiers_for_format(obs_pw_video_format.drm_format, &modifiers, &n_modifiers)) { + da_push_back_array(info->modifiers, modifiers, n_modifiers); } bfree(modifiers); - if (dmabuf_flags & - GS_DMABUF_FLAG_IMPLICIT_MODIFIERS_SUPPORTED) { + if (dmabuf_flags & GS_DMABUF_FLAG_IMPLICIT_MODIFIERS_SUPPORTED) { uint64_t modifier_implicit = DRM_FORMAT_MOD_INVALID; da_push_back(info->modifiers, &modifier_implicit); } @@ -531,34 +485,24 @@ static void clear_format_info(obs_pipewire_stream *obs_pw_stream) da_free(obs_pw_stream->format_info); } -static void remove_modifier_from_format(obs_pipewire_stream *obs_pw_stream, - uint32_t spa_format, uint64_t modifier) +static void remove_modifier_from_format(obs_pipewire_stream *obs_pw_stream, uint32_t spa_format, uint64_t modifier) { obs_pipewire *obs_pw = obs_pw_stream->obs_pw; for (size_t i = 0; i < obs_pw_stream->format_info.num; i++) { - if (obs_pw_stream->format_info.array[i].spa_format != - spa_format) + if (obs_pw_stream->format_info.array[i].spa_format != spa_format) continue; if (!check_pw_version(&obs_pw->server_version, 0, 3, 40)) { - da_erase_range( - obs_pw_stream->format_info.array[i].modifiers, - 0, - obs_pw_stream->format_info.array[i] - .modifiers.num - - 1); + da_erase_range(obs_pw_stream->format_info.array[i].modifiers, 0, + obs_pw_stream->format_info.array[i].modifiers.num - 1); continue; } - int idx = da_find(obs_pw_stream->format_info.array[i].modifiers, - &modifier, 0); + int idx = da_find(obs_pw_stream->format_info.array[i].modifiers, &modifier, 0); while (idx != -1) { - da_erase(obs_pw_stream->format_info.array[i].modifiers, - idx); - idx = da_find( - obs_pw_stream->format_info.array[i].modifiers, - &modifier, 0); + da_erase(obs_pw_stream->format_info.array[i].modifiers, idx); + idx = da_find(obs_pw_stream->format_info.array[i].modifiers, &modifier, 0); } } } @@ -575,11 +519,9 @@ static void renegotiate_format(void *data, uint64_t expirations) pw_thread_loop_lock(obs_pw->thread_loop); uint8_t params_buffer[4096]; - struct spa_pod_builder pod_builder = - SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer)); + struct spa_pod_builder pod_builder = SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer)); uint32_t n_params; - if (!build_format_params(obs_pw_stream, &pod_builder, ¶ms, - &n_params)) { + if (!build_format_params(obs_pw_stream, &pod_builder, ¶ms, &n_params)) { teardown_pipewire(obs_pw); pw_thread_loop_unlock(obs_pw->thread_loop); return; @@ -610,8 +552,7 @@ static inline struct pw_buffer *find_latest_buffer(struct pw_stream *stream) return b; } -static enum video_colorspace -video_colorspace_from_spa_color_matrix(enum spa_video_color_matrix matrix) +static enum video_colorspace video_colorspace_from_spa_color_matrix(enum spa_video_color_matrix matrix) { switch (matrix) { case SPA_VIDEO_COLOR_MATRIX_RGB: @@ -625,8 +566,7 @@ video_colorspace_from_spa_color_matrix(enum spa_video_color_matrix matrix) } } -static enum video_range_type -video_color_range_from_spa_color_range(enum spa_video_color_range colorrange) +static enum video_range_type video_color_range_from_spa_color_range(enum spa_video_color_range colorrange) { switch (colorrange) { case SPA_VIDEO_COLOR_RANGE_0_255: @@ -638,31 +578,23 @@ video_color_range_from_spa_color_range(enum spa_video_color_range colorrange) } } -static bool prepare_obs_frame(obs_pipewire_stream *obs_pw_stream, - struct obs_source_frame *frame) +static bool prepare_obs_frame(obs_pipewire_stream *obs_pw_stream, struct obs_source_frame *frame) { struct obs_pw_video_format obs_pw_video_format; frame->width = obs_pw_stream->format.info.raw.size.width; frame->height = obs_pw_stream->format.info.raw.size.height; - video_format_get_parameters( - video_colorspace_from_spa_color_matrix( - obs_pw_stream->format.info.raw.color_matrix), - video_color_range_from_spa_color_range( - obs_pw_stream->format.info.raw.color_range), - frame->color_matrix, frame->color_range_min, - frame->color_range_max); + video_format_get_parameters(video_colorspace_from_spa_color_matrix(obs_pw_stream->format.info.raw.color_matrix), + video_color_range_from_spa_color_range(obs_pw_stream->format.info.raw.color_range), + frame->color_matrix, frame->color_range_min, frame->color_range_max); - if (!obs_pw_video_format_from_spa_format( - obs_pw_stream->format.info.raw.format, - &obs_pw_video_format) || + if (!obs_pw_video_format_from_spa_format(obs_pw_stream->format.info.raw.format, &obs_pw_video_format) || obs_pw_video_format.video_format == VIDEO_FORMAT_NONE) return false; frame->format = obs_pw_video_format.video_format; - frame->linesize[0] = - SPA_ROUND_UP_N(frame->width * obs_pw_video_format.bpp, 4); + frame->linesize[0] = SPA_ROUND_UP_N(frame->width * obs_pw_video_format.bpp, 4); return true; } @@ -703,11 +635,10 @@ static void process_video_async(obs_pipewire_stream *obs_pw_stream) } #ifdef DEBUG_PIPEWIRE - blog(LOG_DEBUG, "[pipewire] Frame info: Format: %s, Planes: %u", - get_video_format_name(out.format), buffer->n_datas); + blog(LOG_DEBUG, "[pipewire] Frame info: Format: %s, Planes: %u", get_video_format_name(out.format), + buffer->n_datas); for (uint32_t i = 0; i < buffer->n_datas && i < MAX_AV_PLANES; i++) { - blog(LOG_DEBUG, "[pipewire] Plane %u: Dataptr:%p, Linesize:%d", - i, out.data[i], out.linesize[i]); + blog(LOG_DEBUG, "[pipewire] Plane %u: Dataptr:%p, Linesize:%d", i, out.data[i], out.linesize[i]); } #endif @@ -736,8 +667,7 @@ static void process_video_sync(obs_pipewire_stream *obs_pw_stream) } buffer = b->buffer; - header = spa_buffer_find_meta_data(buffer, SPA_META_Header, - sizeof(*header)); + header = spa_buffer_find_meta_data(buffer, SPA_META_Header, sizeof(*header)); if (header && (header->flags & SPA_META_HEADER_FLAG_CORRUPTED) > 0) { blog(LOG_ERROR, "[pipewire] buffer is corrupt"); pw_stream_queue_buffer(obs_pw_stream->stream, b); @@ -763,20 +693,14 @@ static void process_video_sync(obs_pipewire_stream *obs_pw_stream) bool corrupt = false; #ifdef DEBUG_PIPEWIRE - blog(LOG_DEBUG, - "[pipewire] DMA-BUF info: fd:%ld, stride:%d, offset:%u, size:%dx%d", - buffer->datas[0].fd, buffer->datas[0].chunk->stride, - buffer->datas[0].chunk->offset, - obs_pw_stream->format.info.raw.size.width, - obs_pw_stream->format.info.raw.size.height); + blog(LOG_DEBUG, "[pipewire] DMA-BUF info: fd:%ld, stride:%d, offset:%u, size:%dx%d", + buffer->datas[0].fd, buffer->datas[0].chunk->stride, buffer->datas[0].chunk->offset, + obs_pw_stream->format.info.raw.size.width, obs_pw_stream->format.info.raw.size.height); #endif - if (!obs_pw_video_format_from_spa_format( - obs_pw_stream->format.info.raw.format, - &obs_pw_video_format) || + if (!obs_pw_video_format_from_spa_format(obs_pw_stream->format.info.raw.format, &obs_pw_video_format) || obs_pw_video_format.gs_format == GS_UNKNOWN) { - blog(LOG_ERROR, - "[pipewire] unsupported DMA buffer format: %d", + blog(LOG_ERROR, "[pipewire] unsupported DMA buffer format: %d", obs_pw_stream->format.info.raw.format); goto read_metadata; } @@ -785,84 +709,66 @@ static void process_video_sync(obs_pipewire_stream *obs_pw_stream) fds[plane] = buffer->datas[plane].fd; offsets[plane] = buffer->datas[plane].chunk->offset; strides[plane] = buffer->datas[plane].chunk->stride; - modifiers[plane] = - obs_pw_stream->format.info.raw.modifier; - corrupt |= (buffer->datas[plane].chunk->flags & - SPA_CHUNK_FLAG_CORRUPTED) > 0; + modifiers[plane] = obs_pw_stream->format.info.raw.modifier; + corrupt |= (buffer->datas[plane].chunk->flags & SPA_CHUNK_FLAG_CORRUPTED) > 0; } if (corrupt) { - blog(LOG_DEBUG, - "[pipewire] buffer contains corrupted data"); + blog(LOG_DEBUG, "[pipewire] buffer contains corrupted data"); goto read_metadata; } g_clear_pointer(&obs_pw_stream->texture, gs_texture_destroy); - use_modifiers = obs_pw_stream->format.info.raw.modifier != - DRM_FORMAT_MOD_INVALID; - obs_pw_stream->texture = gs_texture_create_from_dmabuf( - obs_pw_stream->format.info.raw.size.width, - obs_pw_stream->format.info.raw.size.height, - obs_pw_video_format.drm_format, GS_BGRX, planes, fds, - strides, offsets, use_modifiers ? modifiers : NULL); + use_modifiers = obs_pw_stream->format.info.raw.modifier != DRM_FORMAT_MOD_INVALID; + obs_pw_stream->texture = gs_texture_create_from_dmabuf(obs_pw_stream->format.info.raw.size.width, + obs_pw_stream->format.info.raw.size.height, + obs_pw_video_format.drm_format, GS_BGRX, planes, + fds, strides, offsets, + use_modifiers ? modifiers : NULL); if (obs_pw_stream->texture == NULL) { - remove_modifier_from_format( - obs_pw_stream, - obs_pw_stream->format.info.raw.format, - obs_pw_stream->format.info.raw.modifier); - pw_loop_signal_event( - pw_thread_loop_get_loop(obs_pw->thread_loop), - obs_pw_stream->reneg); + remove_modifier_from_format(obs_pw_stream, obs_pw_stream->format.info.raw.format, + obs_pw_stream->format.info.raw.modifier); + pw_loop_signal_event(pw_thread_loop_get_loop(obs_pw->thread_loop), obs_pw_stream->reneg); goto read_metadata; } } else { blog(LOG_DEBUG, "[pipewire] Buffer has memory texture"); - if (!obs_pw_video_format_from_spa_format( - obs_pw_stream->format.info.raw.format, - &obs_pw_video_format) || + if (!obs_pw_video_format_from_spa_format(obs_pw_stream->format.info.raw.format, &obs_pw_video_format) || obs_pw_video_format.gs_format == GS_UNKNOWN) { - blog(LOG_ERROR, - "[pipewire] unsupported buffer format: %d", + blog(LOG_ERROR, "[pipewire] unsupported buffer format: %d", obs_pw_stream->format.info.raw.format); goto read_metadata; } - if ((buffer->datas[0].chunk->flags & SPA_CHUNK_FLAG_CORRUPTED) > - 0) { - blog(LOG_DEBUG, - "[pipewire] buffer contains corrupted data"); + if ((buffer->datas[0].chunk->flags & SPA_CHUNK_FLAG_CORRUPTED) > 0) { + blog(LOG_DEBUG, "[pipewire] buffer contains corrupted data"); goto read_metadata; } if (buffer->datas[0].chunk->size == 0) { - blog(LOG_DEBUG, - "[pipewire] buffer contains empty data"); + blog(LOG_DEBUG, "[pipewire] buffer contains empty data"); goto read_metadata; } g_clear_pointer(&obs_pw_stream->texture, gs_texture_destroy); - obs_pw_stream->texture = gs_texture_create( - obs_pw_stream->format.info.raw.size.width, - obs_pw_stream->format.info.raw.size.height, - obs_pw_video_format.gs_format, 1, - (const uint8_t **)&buffer->datas[0].data, GS_DYNAMIC); + obs_pw_stream->texture = gs_texture_create(obs_pw_stream->format.info.raw.size.width, + obs_pw_stream->format.info.raw.size.height, + obs_pw_video_format.gs_format, 1, + (const uint8_t **)&buffer->datas[0].data, GS_DYNAMIC); } if (obs_pw_video_format.swap_red_blue) swap_texture_red_blue(obs_pw_stream->texture); /* Video Crop */ - region = spa_buffer_find_meta_data(buffer, SPA_META_VideoCrop, - sizeof(*region)); + region = spa_buffer_find_meta_data(buffer, SPA_META_VideoCrop, sizeof(*region)); if (region && spa_meta_region_is_valid(region)) { #ifdef DEBUG_PIPEWIRE - blog(LOG_DEBUG, - "[pipewire] Crop Region available (%dx%d+%d+%d)", - region->region.position.x, region->region.position.y, - region->region.size.width, region->region.size.height); + blog(LOG_DEBUG, "[pipewire] Crop Region available (%dx%d+%d+%d)", region->region.position.x, + region->region.position.y, region->region.size.width, region->region.size.height); #endif obs_pw_stream->crop.x = region->region.position.x; @@ -875,8 +781,7 @@ static void process_video_sync(obs_pipewire_stream *obs_pw_stream) } /* Video Transform */ - video_transform = spa_buffer_find_meta_data( - buffer, SPA_META_VideoTransform, sizeof(*video_transform)); + video_transform = spa_buffer_find_meta_data(buffer, SPA_META_VideoTransform, sizeof(*video_transform)); if (video_transform) obs_pw_stream->transform = video_transform->transform; else @@ -885,30 +790,23 @@ static void process_video_sync(obs_pipewire_stream *obs_pw_stream) read_metadata: /* Cursor */ - cursor = spa_buffer_find_meta_data(buffer, SPA_META_Cursor, - sizeof(*cursor)); - obs_pw_stream->cursor.valid = cursor && - spa_meta_cursor_is_valid(cursor); + cursor = spa_buffer_find_meta_data(buffer, SPA_META_Cursor, sizeof(*cursor)); + obs_pw_stream->cursor.valid = cursor && spa_meta_cursor_is_valid(cursor); if (obs_pw_stream->cursor.visible && obs_pw_stream->cursor.valid) { struct spa_meta_bitmap *bitmap = NULL; if (cursor->bitmap_offset) - bitmap = SPA_MEMBER(cursor, cursor->bitmap_offset, - struct spa_meta_bitmap); + bitmap = SPA_MEMBER(cursor, cursor->bitmap_offset, struct spa_meta_bitmap); if (bitmap) - g_clear_pointer(&obs_pw_stream->cursor.texture, - gs_texture_destroy); + g_clear_pointer(&obs_pw_stream->cursor.texture, gs_texture_destroy); - if (bitmap && bitmap->size.width > 0 && - bitmap->size.height > 0 && - obs_pw_video_format_from_spa_format(bitmap->format, - &obs_pw_video_format) && + if (bitmap && bitmap->size.width > 0 && bitmap->size.height > 0 && + obs_pw_video_format_from_spa_format(bitmap->format, &obs_pw_video_format) && obs_pw_video_format.gs_format != GS_UNKNOWN) { const uint8_t *bitmap_data; - bitmap_data = - SPA_MEMBER(bitmap, bitmap->offset, uint8_t); + bitmap_data = SPA_MEMBER(bitmap, bitmap->offset, uint8_t); obs_pw_stream->cursor.hotspot_x = cursor->hotspot.x; obs_pw_stream->cursor.hotspot_y = cursor->hotspot.y; obs_pw_stream->cursor.width = bitmap->size.width; @@ -916,14 +814,11 @@ read_metadata: assert(obs_pw_stream->cursor.texture == NULL); obs_pw_stream->cursor.texture = - gs_texture_create(obs_pw_stream->cursor.width, - obs_pw_stream->cursor.height, - obs_pw_video_format.gs_format, - 1, &bitmap_data, GS_DYNAMIC); + gs_texture_create(obs_pw_stream->cursor.width, obs_pw_stream->cursor.height, + obs_pw_video_format.gs_format, 1, &bitmap_data, GS_DYNAMIC); if (obs_pw_video_format.swap_red_blue) - swap_texture_red_blue( - obs_pw_stream->cursor.texture); + swap_texture_red_blue(obs_pw_stream->cursor.texture); } obs_pw_stream->cursor.x = cursor->position.x; @@ -950,8 +845,7 @@ static void on_process_cb(void *user_data) } } -static void on_param_changed_cb(void *user_data, uint32_t id, - const struct spa_pod *param) +static void on_param_changed_cb(void *user_data, uint32_t id, const struct spa_pod *param) { obs_pipewire_stream *obs_pw_stream = user_data; obs_pipewire *obs_pw = obs_pw_stream->obs_pw; @@ -967,8 +861,7 @@ static void on_param_changed_cb(void *user_data, uint32_t id, if (!param || id != SPA_PARAM_Format) return; - result = spa_format_parse(param, &obs_pw_stream->format.media_type, - &obs_pw_stream->format.media_subtype); + result = spa_format_parse(param, &obs_pw_stream->format.media_type, &obs_pw_stream->format.media_subtype); if (result < 0) return; @@ -981,90 +874,74 @@ static void on_param_changed_cb(void *user_data, uint32_t id, output_flags = obs_source_get_output_flags(obs_pw_stream->source); buffer_types = 1 << SPA_DATA_MemPtr; - bool has_modifier = - spa_pod_find_prop(param, NULL, SPA_FORMAT_VIDEO_modifier) != - NULL; - if ((has_modifier || - check_pw_version(&obs_pw->server_version, 0, 3, 24)) && + bool has_modifier = spa_pod_find_prop(param, NULL, SPA_FORMAT_VIDEO_modifier) != NULL; + if ((has_modifier || check_pw_version(&obs_pw->server_version, 0, 3, 24)) && (output_flags & OBS_SOURCE_ASYNC_VIDEO) != OBS_SOURCE_ASYNC_VIDEO) buffer_types |= 1 << SPA_DATA_DmaBuf; blog(LOG_INFO, "[pipewire] Negotiated format:"); - format_name = spa_debug_type_find_name( - spa_type_video_format, obs_pw_stream->format.info.raw.format); - blog(LOG_INFO, "[pipewire] Format: %d (%s)", - obs_pw_stream->format.info.raw.format, + format_name = spa_debug_type_find_name(spa_type_video_format, obs_pw_stream->format.info.raw.format); + blog(LOG_INFO, "[pipewire] Format: %d (%s)", obs_pw_stream->format.info.raw.format, format_name ? format_name : "unknown format"); if (has_modifier) { - blog(LOG_INFO, "[pipewire] Modifier: 0x%" PRIx64, - obs_pw_stream->format.info.raw.modifier); + blog(LOG_INFO, "[pipewire] Modifier: 0x%" PRIx64, obs_pw_stream->format.info.raw.modifier); } - blog(LOG_INFO, "[pipewire] Size: %dx%d", - obs_pw_stream->format.info.raw.size.width, + blog(LOG_INFO, "[pipewire] Size: %dx%d", obs_pw_stream->format.info.raw.size.width, obs_pw_stream->format.info.raw.size.height); - blog(LOG_INFO, "[pipewire] Framerate: %d/%d", - obs_pw_stream->format.info.raw.framerate.num, + blog(LOG_INFO, "[pipewire] Framerate: %d/%d", obs_pw_stream->format.info.raw.framerate.num, obs_pw_stream->format.info.raw.framerate.denom); /* Video crop */ - pod_builder = - SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer)); - params[n_params++] = spa_pod_builder_add_object( - &pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, - SPA_PARAM_META_type, SPA_POD_Id(SPA_META_VideoCrop), - SPA_PARAM_META_size, - SPA_POD_Int(sizeof(struct spa_meta_region))); + pod_builder = SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer)); + params[n_params++] = spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, + SPA_PARAM_META_type, SPA_POD_Id(SPA_META_VideoCrop), + SPA_PARAM_META_size, + SPA_POD_Int(sizeof(struct spa_meta_region))); /* Cursor */ - params[n_params++] = spa_pod_builder_add_object( - &pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, - SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Cursor), - SPA_PARAM_META_size, - SPA_POD_CHOICE_RANGE_Int(CURSOR_META_SIZE(64, 64), - CURSOR_META_SIZE(1, 1), - CURSOR_META_SIZE(1024, 1024))); + params[n_params++] = + spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, SPA_PARAM_META_type, + SPA_POD_Id(SPA_META_Cursor), SPA_PARAM_META_size, + SPA_POD_CHOICE_RANGE_Int(CURSOR_META_SIZE(64, 64), CURSOR_META_SIZE(1, 1), + CURSOR_META_SIZE(1024, 1024))); /* Buffer options */ - params[n_params++] = spa_pod_builder_add_object( - &pod_builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, - SPA_PARAM_BUFFERS_dataType, SPA_POD_Int(buffer_types)); + params[n_params++] = spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamBuffers, SPA_PARAM_Buffers, + SPA_PARAM_BUFFERS_dataType, SPA_POD_Int(buffer_types)); /* Meta header */ - params[n_params++] = spa_pod_builder_add_object( - &pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, - SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header), - SPA_PARAM_META_size, - SPA_POD_Int(sizeof(struct spa_meta_header))); + params[n_params++] = spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, + SPA_PARAM_META_type, SPA_POD_Id(SPA_META_Header), + SPA_PARAM_META_size, + SPA_POD_Int(sizeof(struct spa_meta_header))); #if PW_CHECK_VERSION(0, 3, 62) if (check_pw_version(&obs_pw->server_version, 0, 3, 62)) { /* Video transformation */ - params[n_params++] = spa_pod_builder_add_object( - &pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, - SPA_PARAM_META_type, - SPA_POD_Id(SPA_META_VideoTransform), - SPA_PARAM_META_size, - SPA_POD_Int(sizeof(struct spa_meta_videotransform))); + params[n_params++] = spa_pod_builder_add_object(&pod_builder, SPA_TYPE_OBJECT_ParamMeta, SPA_PARAM_Meta, + SPA_PARAM_META_type, + SPA_POD_Id(SPA_META_VideoTransform), + SPA_PARAM_META_size, + SPA_POD_Int(sizeof(struct spa_meta_videotransform))); } #endif pw_stream_update_params(obs_pw_stream->stream, params, n_params); obs_pw_stream->negotiated = true; } -static void on_state_changed_cb(void *user_data, enum pw_stream_state old, - enum pw_stream_state state, const char *error) +static void on_state_changed_cb(void *user_data, enum pw_stream_state old, enum pw_stream_state state, + const char *error) { UNUSED_PARAMETER(old); obs_pipewire_stream *obs_pw_stream = user_data; - blog(LOG_INFO, "[pipewire] Stream %p state: \"%s\" (error: %s)", - obs_pw_stream->stream, pw_stream_state_as_string(state), - error ? error : "none"); + blog(LOG_INFO, "[pipewire] Stream %p state: \"%s\" (error: %s)", obs_pw_stream->stream, + pw_stream_state_as_string(state), error ? error : "none"); } static const struct pw_stream_events stream_events = { @@ -1081,13 +958,11 @@ static void on_core_info_cb(void *user_data, const struct pw_core_info *info) update_pw_versions(obs_pw, info->version); } -static void on_core_error_cb(void *user_data, uint32_t id, int seq, int res, - const char *message) +static void on_core_error_cb(void *user_data, uint32_t id, int seq, int res, const char *message) { obs_pipewire *obs_pw = user_data; - blog(LOG_ERROR, "[pipewire] Error id:%u seq:%d res:%d (%s): %s", id, - seq, res, spa_strerror(res), message); + blog(LOG_ERROR, "[pipewire] Error id:%u seq:%d res:%d (%s): %s", id, seq, res, spa_strerror(res), message); pw_thread_loop_signal(obs_pw->thread_loop, FALSE); } @@ -1109,18 +984,15 @@ static const struct pw_core_events core_events = { /* obs_source_info methods */ -obs_pipewire * -obs_pipewire_connect_fd(int pipewire_fd, - const struct pw_registry_events *registry_events, - void *user_data) +obs_pipewire *obs_pipewire_connect_fd(int pipewire_fd, const struct pw_registry_events *registry_events, + void *user_data) { obs_pipewire *obs_pw; obs_pw = bzalloc(sizeof(obs_pipewire)); obs_pw->pipewire_fd = pipewire_fd; obs_pw->thread_loop = pw_thread_loop_new("PipeWire thread loop", NULL); - obs_pw->context = pw_context_new( - pw_thread_loop_get_loop(obs_pw->thread_loop), NULL, 0); + obs_pw->context = pw_context_new(pw_thread_loop_get_loop(obs_pw->thread_loop), NULL, 0); if (pw_thread_loop_start(obs_pw->thread_loop) < 0) { blog(LOG_WARNING, "Error starting threaded mainloop"); @@ -1131,9 +1003,7 @@ obs_pipewire_connect_fd(int pipewire_fd, pw_thread_loop_lock(obs_pw->thread_loop); /* Core */ - obs_pw->core = pw_context_connect_fd( - obs_pw->context, fcntl(obs_pw->pipewire_fd, F_DUPFD_CLOEXEC, 5), - NULL, 0); + obs_pw->core = pw_context_connect_fd(obs_pw->context, fcntl(obs_pw->pipewire_fd, F_DUPFD_CLOEXEC, 5), NULL, 0); if (!obs_pw->core) { blog(LOG_WARNING, "Error creating PipeWire core: %m"); pw_thread_loop_unlock(obs_pw->thread_loop); @@ -1141,23 +1011,17 @@ obs_pipewire_connect_fd(int pipewire_fd, return NULL; } - pw_core_add_listener(obs_pw->core, &obs_pw->core_listener, &core_events, - obs_pw); + pw_core_add_listener(obs_pw->core, &obs_pw->core_listener, &core_events, obs_pw); // Dispatch to receive the info core event - obs_pw->sync_id = - pw_core_sync(obs_pw->core, PW_ID_CORE, obs_pw->sync_id); + obs_pw->sync_id = pw_core_sync(obs_pw->core, PW_ID_CORE, obs_pw->sync_id); pw_thread_loop_wait(obs_pw->thread_loop); /* Registry */ if (registry_events) { - obs_pw->registry = pw_core_get_registry(obs_pw->core, - PW_VERSION_REGISTRY, 0); - pw_registry_add_listener(obs_pw->registry, - &obs_pw->registry_listener, - registry_events, user_data); - blog(LOG_INFO, "[pipewire] Created registry %p", - obs_pw->registry); + obs_pw->registry = pw_core_get_registry(obs_pw->core, PW_VERSION_REGISTRY, 0); + pw_registry_add_listener(obs_pw->registry, &obs_pw->registry_listener, registry_events, user_data); + blog(LOG_INFO, "[pipewire] Created registry %p", obs_pw->registry); } pw_thread_loop_unlock(obs_pw->thread_loop); @@ -1176,8 +1040,7 @@ void obs_pipewire_roundtrip(obs_pipewire *obs_pw) { pw_thread_loop_lock(obs_pw->thread_loop); - obs_pw->sync_id = - pw_core_sync(obs_pw->core, PW_ID_CORE, obs_pw->sync_id); + obs_pw->sync_id = pw_core_sync(obs_pw->core, PW_ID_CORE, obs_pw->sync_id); pw_thread_loop_wait(obs_pw->thread_loop); pw_thread_loop_unlock(obs_pw->thread_loop); @@ -1189,8 +1052,7 @@ void obs_pipewire_destroy(obs_pipewire *obs_pw) return; while (obs_pw->streams->len > 0) { - obs_pipewire_stream *obs_pw_stream = - g_ptr_array_index(obs_pw->streams, 0); + obs_pipewire_stream *obs_pw_stream = g_ptr_array_index(obs_pw->streams, 0); obs_pipewire_stream_destroy(obs_pw_stream); } g_clear_pointer(&obs_pw->streams, g_ptr_array_unref); @@ -1198,9 +1060,8 @@ void obs_pipewire_destroy(obs_pipewire *obs_pw) bfree(obs_pw); } -obs_pipewire_stream *obs_pipewire_connect_stream( - obs_pipewire *obs_pw, obs_source_t *source, int pipewire_node, - const struct obs_pipwire_connect_stream_info *connect_info) +obs_pipewire_stream *obs_pipewire_connect_stream(obs_pipewire *obs_pw, obs_source_t *source, int pipewire_node, + const struct obs_pipwire_connect_stream_info *connect_info) { struct spa_pod_builder pod_builder; const struct spa_pod **params = NULL; @@ -1218,12 +1079,10 @@ obs_pipewire_stream *obs_pipewire_connect_stream( obs_pw_stream->resolution.set = connect_info->video.resolution != NULL; if (obs_pw_stream->framerate.set) - obs_pw_stream->framerate.fraction = - *connect_info->video.framerate; + obs_pw_stream->framerate.fraction = *connect_info->video.framerate; if (obs_pw_stream->resolution.set) - obs_pw_stream->resolution.rect = - *connect_info->video.resolution; + obs_pw_stream->resolution.rect = *connect_info->video.resolution; init_format_info(obs_pw_stream); @@ -1231,36 +1090,27 @@ obs_pipewire_stream *obs_pipewire_connect_stream( /* Signal to renegotiate */ obs_pw_stream->reneg = - pw_loop_add_event(pw_thread_loop_get_loop(obs_pw->thread_loop), - renegotiate_format, obs_pw_stream); + pw_loop_add_event(pw_thread_loop_get_loop(obs_pw->thread_loop), renegotiate_format, obs_pw_stream); blog(LOG_DEBUG, "[pipewire] registered event %p", obs_pw_stream->reneg); /* Stream */ - obs_pw_stream->stream = pw_stream_new(obs_pw->core, - connect_info->stream_name, - connect_info->stream_properties); - pw_stream_add_listener(obs_pw_stream->stream, - &obs_pw_stream->stream_listener, &stream_events, - obs_pw_stream); + obs_pw_stream->stream = pw_stream_new(obs_pw->core, connect_info->stream_name, connect_info->stream_properties); + pw_stream_add_listener(obs_pw_stream->stream, &obs_pw_stream->stream_listener, &stream_events, obs_pw_stream); blog(LOG_INFO, "[pipewire] Created stream %p", obs_pw_stream->stream); /* Stream parameters */ - pod_builder = - SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer)); + pod_builder = SPA_POD_BUILDER_INIT(params_buffer, sizeof(params_buffer)); obs_get_video_info(&obs_pw_stream->video_info); - if (!build_format_params(obs_pw_stream, &pod_builder, ¶ms, - &n_params)) { + if (!build_format_params(obs_pw_stream, &pod_builder, ¶ms, &n_params)) { pw_thread_loop_unlock(obs_pw->thread_loop); bfree(obs_pw_stream); return NULL; } - pw_stream_connect( - obs_pw_stream->stream, PW_DIRECTION_INPUT, pipewire_node, - PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS, params, - n_params); + pw_stream_connect(obs_pw_stream->stream, PW_DIRECTION_INPUT, pipewire_node, + PW_STREAM_FLAG_AUTOCONNECT | PW_STREAM_FLAG_MAP_BUFFERS, params, n_params); blog(LOG_INFO, "[pipewire] Playing stream %p", obs_pw_stream->stream); @@ -1304,14 +1154,12 @@ uint32_t obs_pipewire_stream_get_width(obs_pipewire_stream *obs_pw_stream) case SPA_META_TRANSFORMATION_None: case SPA_META_TRANSFORMATION_Flipped180: case SPA_META_TRANSFORMATION_180: - return has_crop ? obs_pw_stream->crop.width - : obs_pw_stream->format.info.raw.size.width; + return has_crop ? obs_pw_stream->crop.width : obs_pw_stream->format.info.raw.size.width; case SPA_META_TRANSFORMATION_Flipped90: case SPA_META_TRANSFORMATION_90: case SPA_META_TRANSFORMATION_Flipped270: case SPA_META_TRANSFORMATION_270: - return has_crop ? obs_pw_stream->crop.height - : obs_pw_stream->format.info.raw.size.height; + return has_crop ? obs_pw_stream->crop.height : obs_pw_stream->format.info.raw.size.height; default: return 0; } @@ -1331,21 +1179,18 @@ uint32_t obs_pipewire_stream_get_height(obs_pipewire_stream *obs_pw_stream) case SPA_META_TRANSFORMATION_None: case SPA_META_TRANSFORMATION_Flipped180: case SPA_META_TRANSFORMATION_180: - return has_crop ? obs_pw_stream->crop.height - : obs_pw_stream->format.info.raw.size.height; + return has_crop ? obs_pw_stream->crop.height : obs_pw_stream->format.info.raw.size.height; case SPA_META_TRANSFORMATION_Flipped90: case SPA_META_TRANSFORMATION_90: case SPA_META_TRANSFORMATION_Flipped270: case SPA_META_TRANSFORMATION_270: - return has_crop ? obs_pw_stream->crop.width - : obs_pw_stream->format.info.raw.size.width; + return has_crop ? obs_pw_stream->crop.width : obs_pw_stream->format.info.raw.size.width; default: return 0; } } -void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, - gs_effect_t *effect) +void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, gs_effect_t *effect) { bool rotated; int flip = 0; @@ -1374,11 +1219,8 @@ void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); if (has_effective_crop(obs_pw_stream)) { - gs_draw_sprite_subregion(obs_pw_stream->texture, flip, - obs_pw_stream->crop.x, - obs_pw_stream->crop.y, - obs_pw_stream->crop.width, - obs_pw_stream->crop.height); + gs_draw_sprite_subregion(obs_pw_stream->texture, flip, obs_pw_stream->crop.x, obs_pw_stream->crop.y, + obs_pw_stream->crop.width, obs_pw_stream->crop.height); } else { gs_draw_sprite(obs_pw_stream->texture, flip, 0, 0); } @@ -1386,20 +1228,15 @@ void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, if (rotated) gs_matrix_pop(); - if (obs_pw_stream->cursor.visible && obs_pw_stream->cursor.valid && - obs_pw_stream->cursor.texture) { - float cursor_x = obs_pw_stream->cursor.x - - obs_pw_stream->cursor.hotspot_x; - float cursor_y = obs_pw_stream->cursor.y - - obs_pw_stream->cursor.hotspot_y; + if (obs_pw_stream->cursor.visible && obs_pw_stream->cursor.valid && obs_pw_stream->cursor.texture) { + float cursor_x = obs_pw_stream->cursor.x - obs_pw_stream->cursor.hotspot_x; + float cursor_y = obs_pw_stream->cursor.y - obs_pw_stream->cursor.hotspot_y; gs_matrix_push(); gs_matrix_translate3f(cursor_x, cursor_y, 0.0f); gs_effect_set_texture(image, obs_pw_stream->cursor.texture); - gs_draw_sprite(obs_pw_stream->texture, 0, - obs_pw_stream->cursor.width, - obs_pw_stream->cursor.height); + gs_draw_sprite(obs_pw_stream->texture, 0, obs_pw_stream->cursor.width, obs_pw_stream->cursor.height); gs_matrix_pop(); } @@ -1407,8 +1244,7 @@ void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, gs_blend_state_pop(); } -void obs_pipewire_stream_set_cursor_visible(obs_pipewire_stream *obs_pw_stream, - bool cursor_visible) +void obs_pipewire_stream_set_cursor_visible(obs_pipewire_stream *obs_pw_stream, bool cursor_visible) { obs_pw_stream->cursor.visible = cursor_visible; } @@ -1441,14 +1277,12 @@ void obs_pipewire_stream_destroy(obs_pipewire_stream *obs_pw_stream) bfree(obs_pw_stream); } -void obs_pipewire_stream_set_framerate(obs_pipewire_stream *obs_pw_stream, - const struct spa_fraction *framerate) +void obs_pipewire_stream_set_framerate(obs_pipewire_stream *obs_pw_stream, const struct spa_fraction *framerate) { obs_pipewire *obs_pw = obs_pw_stream->obs_pw; if ((!obs_pw_stream->framerate.set && !framerate) || - (obs_pw_stream->framerate.set && framerate && - obs_pw_stream->framerate.fraction.num == framerate->num && + (obs_pw_stream->framerate.set && framerate && obs_pw_stream->framerate.fraction.num == framerate->num && obs_pw_stream->framerate.fraction.denom == framerate->denom)) return; @@ -1461,18 +1295,15 @@ void obs_pipewire_stream_set_framerate(obs_pipewire_stream *obs_pw_stream, } /* Signal to renegotiate */ - pw_loop_signal_event(pw_thread_loop_get_loop(obs_pw->thread_loop), - obs_pw_stream->reneg); + pw_loop_signal_event(pw_thread_loop_get_loop(obs_pw->thread_loop), obs_pw_stream->reneg); } -void obs_pipewire_stream_set_resolution(obs_pipewire_stream *obs_pw_stream, - const struct spa_rectangle *resolution) +void obs_pipewire_stream_set_resolution(obs_pipewire_stream *obs_pw_stream, const struct spa_rectangle *resolution) { obs_pipewire *obs_pw = obs_pw_stream->obs_pw; if ((!obs_pw_stream->resolution.set && !resolution) || - (obs_pw_stream->resolution.set && resolution && - obs_pw_stream->resolution.rect.width == resolution->width && + (obs_pw_stream->resolution.set && resolution && obs_pw_stream->resolution.rect.width == resolution->width && obs_pw_stream->resolution.rect.height == resolution->height)) return; @@ -1485,6 +1316,5 @@ void obs_pipewire_stream_set_resolution(obs_pipewire_stream *obs_pw_stream, } /* Signal to renegotiate */ - pw_loop_signal_event(pw_thread_loop_get_loop(obs_pw->thread_loop), - obs_pw_stream->reneg); + pw_loop_signal_event(pw_thread_loop_get_loop(obs_pw->thread_loop), obs_pw_stream->reneg); } diff --git a/plugins/linux-pipewire/pipewire.h b/plugins/linux-pipewire/pipewire.h index 83c04cd4b..1705ca696 100644 --- a/plugins/linux-pipewire/pipewire.h +++ b/plugins/linux-pipewire/pipewire.h @@ -39,30 +39,23 @@ struct obs_pipwire_connect_stream_info { } video; }; -obs_pipewire * -obs_pipewire_connect_fd(int pipewire_fd, - const struct pw_registry_events *registry_events, - void *user_data); +obs_pipewire *obs_pipewire_connect_fd(int pipewire_fd, const struct pw_registry_events *registry_events, + void *user_data); struct pw_registry *obs_pipewire_get_registry(obs_pipewire *obs_pw); void obs_pipewire_roundtrip(obs_pipewire *obs_pw); void obs_pipewire_destroy(obs_pipewire *obs_pw); -obs_pipewire_stream *obs_pipewire_connect_stream( - obs_pipewire *obs_pw, obs_source_t *source, int pipewire_node, - const struct obs_pipwire_connect_stream_info *connect_info); +obs_pipewire_stream *obs_pipewire_connect_stream(obs_pipewire *obs_pw, obs_source_t *source, int pipewire_node, + const struct obs_pipwire_connect_stream_info *connect_info); void obs_pipewire_stream_show(obs_pipewire_stream *obs_pw_stream); void obs_pipewire_stream_hide(obs_pipewire_stream *obs_pw_stream); uint32_t obs_pipewire_stream_get_width(obs_pipewire_stream *obs_pw_stream); uint32_t obs_pipewire_stream_get_height(obs_pipewire_stream *obs_pw_stream); -void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, - gs_effect_t *effect); +void obs_pipewire_stream_video_render(obs_pipewire_stream *obs_pw_stream, gs_effect_t *effect); -void obs_pipewire_stream_set_cursor_visible(obs_pipewire_stream *obs_pw_stream, - bool cursor_visible); +void obs_pipewire_stream_set_cursor_visible(obs_pipewire_stream *obs_pw_stream, bool cursor_visible); void obs_pipewire_stream_destroy(obs_pipewire_stream *obs_pw_stream); -void obs_pipewire_stream_set_framerate(obs_pipewire_stream *obs_pw_stream, - const struct spa_fraction *framerate); -void obs_pipewire_stream_set_resolution(obs_pipewire_stream *obs_pw, - const struct spa_rectangle *resolution); +void obs_pipewire_stream_set_framerate(obs_pipewire_stream *obs_pw_stream, const struct spa_fraction *framerate); +void obs_pipewire_stream_set_resolution(obs_pipewire_stream *obs_pw, const struct spa_rectangle *resolution); diff --git a/plugins/linux-pipewire/portal.c b/plugins/linux-pipewire/portal.c index 8398bd8c3..b904123f4 100644 --- a/plugins/linux-pipewire/portal.c +++ b/plugins/linux-pipewire/portal.c @@ -44,9 +44,7 @@ static void ensure_connection(void) connection = g_bus_get_sync(G_BUS_TYPE_SESSION, NULL, &error); if (error) { - blog(LOG_WARNING, - "[portals] Error retrieving D-Bus connection: %s", - error->message); + blog(LOG_WARNING, "[portals] Error retrieving D-Bus connection: %s", error->message); return; } } @@ -59,8 +57,7 @@ char *get_sender_name(void) ensure_connection(); - sender_name = - bstrdup(g_dbus_connection_get_unique_name(connection) + 1); + sender_name = bstrdup(g_dbus_connection_get_unique_name(connection) + 1); /* Replace dots by underscores */ while ((aux = strstr(sender_name, ".")) != NULL) @@ -95,8 +92,7 @@ void portal_create_request_path(char **out_path, char **out_token) sender_name = get_sender_name(); dstr_init(&str); - dstr_printf(&str, REQUEST_PATH, sender_name, - request_token_count); + dstr_printf(&str, REQUEST_PATH, sender_name, request_token_count); *out_path = str.array; bfree(sender_name); @@ -123,8 +119,7 @@ void portal_create_session_path(char **out_path, char **out_token) sender_name = get_sender_name(); dstr_init(&str); - dstr_printf(&str, SESSION_PATH, sender_name, - session_token_count); + dstr_printf(&str, SESSION_PATH, sender_name, session_token_count); *out_path = str.array; bfree(sender_name); @@ -134,12 +129,10 @@ void portal_create_session_path(char **out_path, char **out_token) static void portal_signal_call_free(struct portal_signal_call *call) { if (call->signal_id) - g_dbus_connection_signal_unsubscribe( - portal_get_dbus_connection(), call->signal_id); + g_dbus_connection_signal_unsubscribe(portal_get_dbus_connection(), call->signal_id); if (call->cancelled_id > 0) - g_signal_handler_disconnect(call->cancellable, - call->cancelled_id); + g_signal_handler_disconnect(call->cancellable, call->cancelled_id); g_clear_pointer(&call->request_path, bfree); bfree(call); @@ -153,20 +146,16 @@ static void on_cancelled_cb(GCancellable *cancellable, void *data) blog(LOG_INFO, "[portals] Request cancelled"); - g_dbus_connection_call( - portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", - call->request_path, "org.freedesktop.portal.Request", "Close", - NULL, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL); + g_dbus_connection_call(portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", call->request_path, + "org.freedesktop.portal.Request", "Close", NULL, NULL, G_DBUS_CALL_FLAGS_NONE, -1, NULL, + NULL, NULL); portal_signal_call_free(call); } -static void on_response_received_cb(GDBusConnection *connection, - const char *sender_name, - const char *object_path, - const char *interface_name, - const char *signal_name, - GVariant *parameters, void *user_data) +static void on_response_received_cb(GDBusConnection *connection, const char *sender_name, const char *object_path, + const char *interface_name, const char *signal_name, GVariant *parameters, + void *user_data) { UNUSED_PARAMETER(connection); UNUSED_PARAMETER(sender_name); @@ -182,8 +171,7 @@ static void on_response_received_cb(GDBusConnection *connection, portal_signal_call_free(call); } -void portal_signal_subscribe(const char *path, GCancellable *cancellable, - portal_signal_callback callback, +void portal_signal_subscribe(const char *path, GCancellable *cancellable, portal_signal_callback callback, gpointer user_data) { struct portal_signal_call *call; @@ -193,14 +181,10 @@ void portal_signal_subscribe(const char *path, GCancellable *cancellable, call->callback = callback; call->user_data = user_data; call->cancellable = cancellable ? g_object_ref(cancellable) : NULL; - call->cancelled_id = - cancellable - ? g_signal_connect(cancellable, "cancelled", - G_CALLBACK(on_cancelled_cb), call) - : 0; + call->cancelled_id = cancellable ? g_signal_connect(cancellable, "cancelled", G_CALLBACK(on_cancelled_cb), call) + : 0; call->signal_id = g_dbus_connection_signal_subscribe( - portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", - "org.freedesktop.portal.Request", "Response", - call->request_path, NULL, G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, - on_response_received_cb, call, NULL); + portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", "org.freedesktop.portal.Request", + "Response", call->request_path, NULL, G_DBUS_SIGNAL_FLAGS_NO_MATCH_RULE, on_response_received_cb, call, + NULL); } diff --git a/plugins/linux-pipewire/portal.h b/plugins/linux-pipewire/portal.h index 5f19ec360..c32d2895c 100644 --- a/plugins/linux-pipewire/portal.h +++ b/plugins/linux-pipewire/portal.h @@ -30,5 +30,5 @@ GDBusConnection *portal_get_dbus_connection(void); void portal_create_request_path(char **out_path, char **out_token); void portal_create_session_path(char **out_path, char **out_token); -void portal_signal_subscribe(const char *path, GCancellable *cancellable, - portal_signal_callback callback, void *user_data); +void portal_signal_subscribe(const char *path, GCancellable *cancellable, portal_signal_callback callback, + void *user_data); diff --git a/plugins/linux-pipewire/screencast-portal.c b/plugins/linux-pipewire/screencast-portal.c index a5cdec726..99c7c5506 100644 --- a/plugins/linux-pipewire/screencast-portal.c +++ b/plugins/linux-pipewire/screencast-portal.c @@ -38,8 +38,7 @@ enum portal_cursor_mode { enum obs_portal_capture_type { OBS_PORTAL_CAPTURE_TYPE_MONITOR = PORTAL_CAPTURE_TYPE_MONITOR, OBS_PORTAL_CAPTURE_TYPE_WINDOW = PORTAL_CAPTURE_TYPE_WINDOW, - OBS_PORTAL_CAPTURE_TYPE_UNIFIED = PORTAL_CAPTURE_TYPE_MONITOR | - PORTAL_CAPTURE_TYPE_WINDOW, + OBS_PORTAL_CAPTURE_TYPE_UNIFIED = PORTAL_CAPTURE_TYPE_MONITOR | PORTAL_CAPTURE_TYPE_WINDOW, }; struct screencast_portal_capture { @@ -68,16 +67,13 @@ static void ensure_screencast_portal_proxy(void) { g_autoptr(GError) error = NULL; if (!screencast_proxy) { - screencast_proxy = g_dbus_proxy_new_sync( - portal_get_dbus_connection(), G_DBUS_PROXY_FLAGS_NONE, - NULL, "org.freedesktop.portal.Desktop", - "/org/freedesktop/portal/desktop", - "org.freedesktop.portal.ScreenCast", NULL, &error); + screencast_proxy = g_dbus_proxy_new_sync(portal_get_dbus_connection(), G_DBUS_PROXY_FLAGS_NONE, NULL, + "org.freedesktop.portal.Desktop", + "/org/freedesktop/portal/desktop", + "org.freedesktop.portal.ScreenCast", NULL, &error); if (error) { - blog(LOG_WARNING, - "[portals] Error retrieving D-Bus proxy: %s", - error->message); + blog(LOG_WARNING, "[portals] Error retrieving D-Bus proxy: %s", error->message); return; } } @@ -99,11 +95,8 @@ static uint32_t get_available_capture_types(void) if (!screencast_proxy) return 0; - cached_source_types = g_dbus_proxy_get_cached_property( - screencast_proxy, "AvailableSourceTypes"); - available_source_types = - cached_source_types ? g_variant_get_uint32(cached_source_types) - : 0; + cached_source_types = g_dbus_proxy_get_cached_property(screencast_proxy, "AvailableSourceTypes"); + available_source_types = cached_source_types ? g_variant_get_uint32(cached_source_types) : 0; return available_source_types; } @@ -118,11 +111,8 @@ static uint32_t get_available_cursor_modes(void) if (!screencast_proxy) return 0; - cached_cursor_modes = g_dbus_proxy_get_cached_property( - screencast_proxy, "AvailableCursorModes"); - available_cursor_modes = - cached_cursor_modes ? g_variant_get_uint32(cached_cursor_modes) - : 0; + cached_cursor_modes = g_dbus_proxy_get_cached_property(screencast_proxy, "AvailableCursorModes"); + available_cursor_modes = cached_cursor_modes ? g_variant_get_uint32(cached_cursor_modes) : 0; return available_cursor_modes; } @@ -137,8 +127,7 @@ static uint32_t get_screencast_version(void) if (!screencast_proxy) return 0; - cached_version = - g_dbus_proxy_get_cached_property(screencast_proxy, "version"); + cached_version = g_dbus_proxy_get_cached_property(screencast_proxy, "version"); version = cached_version ? g_variant_get_uint32(cached_version) : 0; return version; @@ -146,8 +135,7 @@ static uint32_t get_screencast_version(void) /* ------------------------------------------------- */ -static const char * -capture_type_to_string(enum obs_portal_capture_type capture_type) +static const char *capture_type_to_string(enum obs_portal_capture_type capture_type) { switch (capture_type) { case OBS_PORTAL_CAPTURE_TYPE_MONITOR: @@ -163,8 +151,7 @@ capture_type_to_string(enum obs_portal_capture_type capture_type) /* ------------------------------------------------- */ -static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, - void *user_data) +static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, void *user_data) { struct obs_pipwire_connect_stream_info connect_info; struct screencast_portal_capture *capture; @@ -175,13 +162,10 @@ static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, int fd_index; capture = user_data; - result = g_dbus_proxy_call_with_unix_fd_list_finish( - G_DBUS_PROXY(source), &fd_list, res, &error); + result = g_dbus_proxy_call_with_unix_fd_list_finish(G_DBUS_PROXY(source), &fd_list, res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[pipewire] Error retrieving pipewire fd: %s", - error->message); + blog(LOG_ERROR, "[pipewire] Error retrieving pipewire fd: %s", error->message); return; } @@ -190,9 +174,7 @@ static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, pipewire_fd = g_unix_fd_list_get(fd_list, fd_index, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[pipewire] Error retrieving pipewire fd: %s", - error->message); + blog(LOG_ERROR, "[pipewire] Error retrieving pipewire fd: %s", error->message); return; } @@ -203,18 +185,16 @@ static void on_pipewire_remote_opened_cb(GObject *source, GAsyncResult *res, connect_info = (struct obs_pipwire_connect_stream_info){ .stream_name = "OBS Studio", - .stream_properties = pw_properties_new( - PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, - "Capture", PW_KEY_MEDIA_ROLE, "Screen", NULL), + .stream_properties = pw_properties_new(PW_KEY_MEDIA_TYPE, "Video", PW_KEY_MEDIA_CATEGORY, "Capture", + PW_KEY_MEDIA_ROLE, "Screen", NULL), .screencast = { .cursor_visible = capture->cursor_visible, }, }; - capture->obs_pw_stream = obs_pipewire_connect_stream( - capture->obs_pw, capture->source, capture->pipewire_node, - &connect_info); + capture->obs_pw_stream = + obs_pipewire_connect_stream(capture->obs_pw, capture->source, capture->pipewire_node, &connect_info); } static void open_pipewire_remote(struct screencast_portal_capture *capture) @@ -223,11 +203,10 @@ static void open_pipewire_remote(struct screencast_portal_capture *capture) g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_dbus_proxy_call_with_unix_fd_list( - get_screencast_portal_proxy(), "OpenPipeWireRemote", - g_variant_new("(oa{sv})", capture->session_handle, &builder), - G_DBUS_CALL_FLAGS_NONE, -1, NULL, capture->cancellable, - on_pipewire_remote_opened_cb, capture); + g_dbus_proxy_call_with_unix_fd_list(get_screencast_portal_proxy(), "OpenPipeWireRemote", + g_variant_new("(oa{sv})", capture->session_handle, &builder), + G_DBUS_CALL_FLAGS_NONE, -1, NULL, capture->cancellable, + on_pipewire_remote_opened_cb, capture); } /* ------------------------------------------------- */ @@ -245,22 +224,19 @@ static void on_start_response_received_cb(GVariant *parameters, void *user_data) g_variant_get(parameters, "(u@a{sv})", &response, &result); if (response != 0) { - blog(LOG_WARNING, - "[pipewire] Failed to start screencast, denied or cancelled by user"); + blog(LOG_WARNING, "[pipewire] Failed to start screencast, denied or cancelled by user"); return; } - streams = - g_variant_lookup_value(result, "streams", G_VARIANT_TYPE_ARRAY); + streams = g_variant_lookup_value(result, "streams", G_VARIANT_TYPE_ARRAY); g_variant_iter_init(&iter, streams); n_streams = g_variant_iter_n_children(&iter); if (n_streams != 1) { - blog(LOG_WARNING, - "[pipewire] Received more than one stream when only one was expected. " - "This is probably a bug in the desktop portal implementation you are " - "using."); + blog(LOG_WARNING, "[pipewire] Received more than one stream when only one was expected. " + "This is probably a bug in the desktop portal implementation you are " + "using."); // The KDE Desktop portal implementation sometimes sends an invalid // response where more than one stream is attached, and only the @@ -270,25 +246,20 @@ static void on_start_response_received_cb(GVariant *parameters, void *user_data) g_autoptr(GVariant) throwaway_properties = NULL; uint32_t throwaway_pipewire_node; - g_variant_iter_loop(&iter, "(u@a{sv})", - &throwaway_pipewire_node, - &throwaway_properties); + g_variant_iter_loop(&iter, "(u@a{sv})", &throwaway_pipewire_node, &throwaway_properties); } } - g_variant_iter_loop(&iter, "(u@a{sv})", &capture->pipewire_node, - &stream_properties); + g_variant_iter_loop(&iter, "(u@a{sv})", &capture->pipewire_node, &stream_properties); if (get_screencast_version() >= 4) { g_autoptr(GVariant) restore_token = NULL; g_clear_pointer(&capture->restore_token, bfree); - restore_token = g_variant_lookup_value(result, "restore_token", - G_VARIANT_TYPE_STRING); + restore_token = g_variant_lookup_value(result, "restore_token", G_VARIANT_TYPE_STRING); if (restore_token) - capture->restore_token = bstrdup( - g_variant_get_string(restore_token, NULL)); + capture->restore_token = bstrdup(g_variant_get_string(restore_token, NULL)); obs_source_save(capture->source); } @@ -308,9 +279,7 @@ static void on_started_cb(GObject *source, GAsyncResult *res, void *user_data) result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[pipewire] Error selecting screencast source: %s", - error->message); + blog(LOG_ERROR, "[pipewire] Error selecting screencast source: %s", error->message); return; } } @@ -323,21 +292,16 @@ static void start(struct screencast_portal_capture *capture) portal_create_request_path(&request_path, &request_token); - blog(LOG_INFO, "[pipewire] Asking for %s", - capture_type_to_string(capture->capture_type)); + blog(LOG_INFO, "[pipewire] Asking for %s", capture_type_to_string(capture->capture_type)); - portal_signal_subscribe(request_path, capture->cancellable, - on_start_response_received_cb, capture); + portal_signal_subscribe(request_path, capture->cancellable, on_start_response_received_cb, capture); g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_variant_builder_add(&builder, "{sv}", "handle_token", - g_variant_new_string(request_token)); + g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token)); g_dbus_proxy_call(get_screencast_portal_proxy(), "Start", - g_variant_new("(osa{sv})", capture->session_handle, - "", &builder), - G_DBUS_CALL_FLAGS_NONE, -1, capture->cancellable, - on_started_cb, NULL); + g_variant_new("(osa{sv})", capture->session_handle, "", &builder), G_DBUS_CALL_FLAGS_NONE, -1, + capture->cancellable, on_started_cb, NULL); bfree(request_token); bfree(request_path); @@ -345,8 +309,7 @@ static void start(struct screencast_portal_capture *capture) /* ------------------------------------------------- */ -static void on_select_source_response_received_cb(GVariant *parameters, - void *user_data) +static void on_select_source_response_received_cb(GVariant *parameters, void *user_data) { struct screencast_portal_capture *capture = user_data; g_autoptr(GVariant) ret = NULL; @@ -357,16 +320,14 @@ static void on_select_source_response_received_cb(GVariant *parameters, g_variant_get(parameters, "(u@a{sv})", &response, &ret); if (response != 0) { - blog(LOG_WARNING, - "[pipewire] Failed to select source, denied or cancelled by user"); + blog(LOG_WARNING, "[pipewire] Failed to select source, denied or cancelled by user"); return; } start(capture); } -static void on_source_selected_cb(GObject *source, GAsyncResult *res, - void *user_data) +static void on_source_selected_cb(GObject *source, GAsyncResult *res, void *user_data) { UNUSED_PARAMETER(user_data); @@ -376,9 +337,7 @@ static void on_source_selected_cb(GObject *source, GAsyncResult *res, result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[pipewire] Error selecting screencast source: %s", - error->message); + blog(LOG_ERROR, "[pipewire] Error selecting screencast source: %s", error->message); return; } } @@ -392,48 +351,35 @@ static void select_source(struct screencast_portal_capture *capture) portal_create_request_path(&request_path, &request_token); - portal_signal_subscribe(request_path, capture->cancellable, - on_select_source_response_received_cb, capture); + portal_signal_subscribe(request_path, capture->cancellable, on_select_source_response_received_cb, capture); g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_variant_builder_add(&builder, "{sv}", "types", - g_variant_new_uint32(capture->capture_type)); - g_variant_builder_add(&builder, "{sv}", "multiple", - g_variant_new_boolean(FALSE)); - g_variant_builder_add(&builder, "{sv}", "handle_token", - g_variant_new_string(request_token)); + g_variant_builder_add(&builder, "{sv}", "types", g_variant_new_uint32(capture->capture_type)); + g_variant_builder_add(&builder, "{sv}", "multiple", g_variant_new_boolean(FALSE)); + g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token)); available_cursor_modes = get_available_cursor_modes(); if (available_cursor_modes & PORTAL_CURSOR_MODE_METADATA) - g_variant_builder_add( - &builder, "{sv}", "cursor_mode", - g_variant_new_uint32(PORTAL_CURSOR_MODE_METADATA)); - else if ((available_cursor_modes & PORTAL_CURSOR_MODE_EMBEDDED) && - capture->cursor_visible) - g_variant_builder_add( - &builder, "{sv}", "cursor_mode", - g_variant_new_uint32(PORTAL_CURSOR_MODE_EMBEDDED)); + g_variant_builder_add(&builder, "{sv}", "cursor_mode", + g_variant_new_uint32(PORTAL_CURSOR_MODE_METADATA)); + else if ((available_cursor_modes & PORTAL_CURSOR_MODE_EMBEDDED) && capture->cursor_visible) + g_variant_builder_add(&builder, "{sv}", "cursor_mode", + g_variant_new_uint32(PORTAL_CURSOR_MODE_EMBEDDED)); else - g_variant_builder_add( - &builder, "{sv}", "cursor_mode", - g_variant_new_uint32(PORTAL_CURSOR_MODE_HIDDEN)); + g_variant_builder_add(&builder, "{sv}", "cursor_mode", g_variant_new_uint32(PORTAL_CURSOR_MODE_HIDDEN)); if (get_screencast_version() >= 4) { - g_variant_builder_add(&builder, "{sv}", "persist_mode", - g_variant_new_uint32(2)); + g_variant_builder_add(&builder, "{sv}", "persist_mode", g_variant_new_uint32(2)); if (capture->restore_token && *capture->restore_token) { - g_variant_builder_add( - &builder, "{sv}", "restore_token", - g_variant_new_string(capture->restore_token)); + g_variant_builder_add(&builder, "{sv}", "restore_token", + g_variant_new_string(capture->restore_token)); } } g_dbus_proxy_call(get_screencast_portal_proxy(), "SelectSources", - g_variant_new("(oa{sv})", capture->session_handle, - &builder), - G_DBUS_CALL_FLAGS_NONE, -1, capture->cancellable, - on_source_selected_cb, NULL); + g_variant_new("(oa{sv})", capture->session_handle, &builder), G_DBUS_CALL_FLAGS_NONE, -1, + capture->cancellable, on_source_selected_cb, NULL); bfree(request_token); bfree(request_path); @@ -441,8 +387,7 @@ static void select_source(struct screencast_portal_capture *capture) /* ------------------------------------------------- */ -static void on_create_session_response_received_cb(GVariant *parameters, - void *user_data) +static void on_create_session_response_received_cb(GVariant *parameters, void *user_data) { struct screencast_portal_capture *capture = user_data; g_autoptr(GVariant) session_handle_variant = NULL; @@ -452,23 +397,19 @@ static void on_create_session_response_received_cb(GVariant *parameters, g_variant_get(parameters, "(u@a{sv})", &response, &result); if (response != 0) { - blog(LOG_WARNING, - "[pipewire] Failed to create session, denied or cancelled by user"); + blog(LOG_WARNING, "[pipewire] Failed to create session, denied or cancelled by user"); return; } blog(LOG_INFO, "[pipewire] Screencast session created"); - session_handle_variant = - g_variant_lookup_value(result, "session_handle", NULL); - capture->session_handle = - g_variant_dup_string(session_handle_variant, NULL); + session_handle_variant = g_variant_lookup_value(result, "session_handle", NULL); + capture->session_handle = g_variant_dup_string(session_handle_variant, NULL); select_source(capture); } -static void on_session_created_cb(GObject *source, GAsyncResult *res, - void *user_data) +static void on_session_created_cb(GObject *source, GAsyncResult *res, void *user_data) { UNUSED_PARAMETER(user_data); @@ -478,9 +419,7 @@ static void on_session_created_cb(GObject *source, GAsyncResult *res, result = g_dbus_proxy_call_finish(G_DBUS_PROXY(source), res, &error); if (error) { if (!g_error_matches(error, G_IO_ERROR, G_IO_ERROR_CANCELLED)) - blog(LOG_ERROR, - "[pipewire] Error creating screencast session: %s", - error->message); + blog(LOG_ERROR, "[pipewire] Error creating screencast session: %s", error->message); return; } } @@ -495,20 +434,14 @@ static void create_session(struct screencast_portal_capture *capture) portal_create_request_path(&request_path, &request_token); portal_create_session_path(NULL, &session_token); - portal_signal_subscribe(request_path, capture->cancellable, - on_create_session_response_received_cb, - capture); + portal_signal_subscribe(request_path, capture->cancellable, on_create_session_response_received_cb, capture); g_variant_builder_init(&builder, G_VARIANT_TYPE_VARDICT); - g_variant_builder_add(&builder, "{sv}", "handle_token", - g_variant_new_string(request_token)); - g_variant_builder_add(&builder, "{sv}", "session_handle_token", - g_variant_new_string(session_token)); + g_variant_builder_add(&builder, "{sv}", "handle_token", g_variant_new_string(request_token)); + g_variant_builder_add(&builder, "{sv}", "session_handle_token", g_variant_new_string(session_token)); - g_dbus_proxy_call(get_screencast_portal_proxy(), "CreateSession", - g_variant_new("(a{sv})", &builder), - G_DBUS_CALL_FLAGS_NONE, -1, capture->cancellable, - on_session_created_cb, NULL); + g_dbus_proxy_call(get_screencast_portal_proxy(), "CreateSession", g_variant_new("(a{sv})", &builder), + G_DBUS_CALL_FLAGS_NONE, -1, capture->cancellable, on_session_created_cb, NULL); bfree(session_token); bfree(request_token); @@ -517,8 +450,7 @@ static void create_session(struct screencast_portal_capture *capture) /* ------------------------------------------------- */ -static gboolean -init_screencast_capture(struct screencast_portal_capture *capture) +static gboolean init_screencast_capture(struct screencast_portal_capture *capture) { GDBusConnection *connection; GDBusProxy *proxy; @@ -538,8 +470,7 @@ init_screencast_capture(struct screencast_portal_capture *capture) return TRUE; } -static bool reload_session_cb(obs_properties_t *properties, - obs_property_t *property, void *data) +static bool reload_session_cb(obs_properties_t *properties, obs_property_t *property, void *data) { UNUSED_PARAMETER(properties); UNUSED_PARAMETER(property); @@ -551,15 +482,10 @@ static bool reload_session_cb(obs_properties_t *properties, g_clear_pointer(&capture->obs_pw, obs_pipewire_destroy); if (capture->session_handle) { - blog(LOG_DEBUG, "[pipewire] Cleaning previous session %s", - capture->session_handle); - g_dbus_connection_call(portal_get_dbus_connection(), - "org.freedesktop.portal.Desktop", - capture->session_handle, - "org.freedesktop.portal.Session", - "Close", NULL, NULL, - G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, - NULL); + blog(LOG_DEBUG, "[pipewire] Cleaning previous session %s", capture->session_handle); + g_dbus_connection_call(portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", + capture->session_handle, "org.freedesktop.portal.Session", "Close", NULL, NULL, + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL); g_clear_pointer(&capture->session_handle, g_free); } @@ -583,32 +509,28 @@ static const char *screencast_portal_window_capture_get_name(void *data) return obs_module_text("PipeWireWindowCapture"); } -static void *screencast_portal_desktop_capture_create(obs_data_t *settings, - obs_source_t *source) +static void *screencast_portal_desktop_capture_create(obs_data_t *settings, obs_source_t *source) { struct screencast_portal_capture *capture; capture = bzalloc(sizeof(struct screencast_portal_capture)); capture->capture_type = OBS_PORTAL_CAPTURE_TYPE_MONITOR; capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor"); - capture->restore_token = - bstrdup(obs_data_get_string(settings, "RestoreToken")); + capture->restore_token = bstrdup(obs_data_get_string(settings, "RestoreToken")); capture->source = source; init_screencast_capture(capture); return capture; } -static void *screencast_portal_window_capture_create(obs_data_t *settings, - obs_source_t *source) +static void *screencast_portal_window_capture_create(obs_data_t *settings, obs_source_t *source) { struct screencast_portal_capture *capture; capture = bzalloc(sizeof(struct screencast_portal_capture)); capture->capture_type = OBS_PORTAL_CAPTURE_TYPE_WINDOW; capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor"); - capture->restore_token = - bstrdup(obs_data_get_string(settings, "RestoreToken")); + capture->restore_token = bstrdup(obs_data_get_string(settings, "RestoreToken")); capture->source = source; init_screencast_capture(capture); @@ -616,16 +538,14 @@ static void *screencast_portal_window_capture_create(obs_data_t *settings, return capture; } -static void *screencast_portal_capture_create(obs_data_t *settings, - obs_source_t *source) +static void *screencast_portal_capture_create(obs_data_t *settings, obs_source_t *source) { struct screencast_portal_capture *capture; capture = bzalloc(sizeof(struct screencast_portal_capture)); capture->capture_type = OBS_PORTAL_CAPTURE_TYPE_UNIFIED; capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor"); - capture->restore_token = - bstrdup(obs_data_get_string(settings, "RestoreToken")); + capture->restore_token = bstrdup(obs_data_get_string(settings, "RestoreToken")); capture->source = source; init_screencast_capture(capture); @@ -641,13 +561,9 @@ static void screencast_portal_capture_destroy(void *data) return; if (capture->session_handle) { - g_dbus_connection_call(portal_get_dbus_connection(), - "org.freedesktop.portal.Desktop", - capture->session_handle, - "org.freedesktop.portal.Session", - "Close", NULL, NULL, - G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, - NULL); + g_dbus_connection_call(portal_get_dbus_connection(), "org.freedesktop.portal.Desktop", + capture->session_handle, "org.freedesktop.portal.Session", "Close", NULL, NULL, + G_DBUS_CALL_FLAGS_NONE, -1, NULL, NULL, NULL); g_clear_pointer(&capture->session_handle, g_free); } @@ -695,11 +611,8 @@ static obs_properties_t *screencast_portal_capture_get_properties(void *data) } properties = obs_properties_create(); - obs_properties_add_button2(properties, "Reload", - obs_module_text(reload_string_id), - reload_session_cb, capture); - obs_properties_add_bool(properties, "ShowCursor", - obs_module_text("ShowCursor")); + obs_properties_add_button2(properties, "Reload", obs_module_text(reload_string_id), reload_session_cb, capture); + obs_properties_add_bool(properties, "ShowCursor", obs_module_text("ShowCursor")); return properties; } @@ -711,8 +624,7 @@ static void screencast_portal_capture_update(void *data, obs_data_t *settings) capture->cursor_visible = obs_data_get_bool(settings, "ShowCursor"); if (capture->obs_pw_stream) - obs_pipewire_stream_set_cursor_visible(capture->obs_pw_stream, - capture->cursor_visible); + obs_pipewire_stream_set_cursor_visible(capture->obs_pw_stream, capture->cursor_visible); } static void screencast_portal_capture_show(void *data) @@ -751,23 +663,19 @@ static uint32_t screencast_portal_capture_get_height(void *data) return 0; } -static void screencast_portal_capture_video_render(void *data, - gs_effect_t *effect) +static void screencast_portal_capture_video_render(void *data, gs_effect_t *effect) { struct screencast_portal_capture *capture = data; if (capture->obs_pw_stream) - obs_pipewire_stream_video_render(capture->obs_pw_stream, - effect); + obs_pipewire_stream_video_render(capture->obs_pw_stream, effect); } void screencast_portal_load(void) { uint32_t available_capture_types = get_available_capture_types(); - bool desktop_capture_available = - (available_capture_types & PORTAL_CAPTURE_TYPE_MONITOR) != 0; - bool window_capture_available = - (available_capture_types & PORTAL_CAPTURE_TYPE_WINDOW) != 0; + bool desktop_capture_available = (available_capture_types & PORTAL_CAPTURE_TYPE_MONITOR) != 0; + bool window_capture_available = (available_capture_types & PORTAL_CAPTURE_TYPE_WINDOW) != 0; if (available_capture_types == 0) { blog(LOG_INFO, "[pipewire] No capture sources available"); diff --git a/plugins/linux-pulseaudio/pulse-input.c b/plugins/linux-pulseaudio/pulse-input.c index 218584d0f..61c6227c9 100644 --- a/plugins/linux-pulseaudio/pulse-input.c +++ b/plugins/linux-pulseaudio/pulse-input.c @@ -83,8 +83,7 @@ static enum audio_format pulse_to_obs_audio_format(pa_sample_format_t format) * @note This *might* not work for some rather unusual setups, but should work * fine for the majority of cases. */ -static enum speaker_layout -pulse_channels_to_obs_speakers(uint_fast32_t channels) +static enum speaker_layout pulse_channels_to_obs_speakers(uint_fast32_t channels) { switch (channels) { case 1: @@ -197,8 +196,7 @@ static void pulse_stream_read(pa_stream *p, size_t nbytes, void *userdata) goto exit; if (!frames) { - blog(LOG_ERROR, "Got audio hole of %u bytes", - (unsigned int)bytes); + blog(LOG_ERROR, "Got audio hole of %u bytes", (unsigned int)bytes); pa_stream_drop(data->stream); goto exit; } @@ -228,32 +226,27 @@ exit: /** * Server info callback */ -static void pulse_server_info(pa_context *c, const pa_server_info *i, - void *userdata) +static void pulse_server_info(pa_context *c, const pa_server_info *i, void *userdata) { UNUSED_PARAMETER(c); PULSE_DATA(userdata); - blog(LOG_INFO, "Server name: '%s %s'", i->server_name, - i->server_version); + blog(LOG_INFO, "Server name: '%s %s'", i->server_name, i->server_version); if (data->is_default) { bfree(data->device); if (data->input) { data->device = bstrdup(i->default_source_name); - blog(LOG_DEBUG, "Default input device: '%s'", - data->device); + blog(LOG_DEBUG, "Default input device: '%s'", data->device); } else { - char *monitor = - bzalloc(strlen(i->default_sink_name) + 9); + char *monitor = bzalloc(strlen(i->default_sink_name) + 9); strcat(monitor, i->default_sink_name); strcat(monitor, ".monitor"); data->device = bstrdup(monitor); - blog(LOG_DEBUG, "Default output device: '%s'", - data->device); + blog(LOG_DEBUG, "Default output device: '%s'", data->device); bfree(monitor); } } @@ -267,8 +260,7 @@ static void pulse_server_info(pa_context *c, const pa_server_info *i, * We use the default stream settings for recording here unless pulse is * configured to something obs can't deal with. */ -static void pulse_source_info(pa_context *c, const pa_source_info *i, int eol, - void *userdata) +static void pulse_source_info(pa_context *c, const pa_source_info *i, int eol, void *userdata) { UNUSED_PARAMETER(c); PULSE_DATA(userdata); @@ -284,8 +276,7 @@ static void pulse_source_info(pa_context *c, const pa_source_info *i, int eol, blog(LOG_INFO, "Audio format: %s, %" PRIu32 " Hz" ", %" PRIu8 " channels", - pa_sample_format_to_string(i->sample_spec.format), - i->sample_spec.rate, i->sample_spec.channels); + pa_sample_format_to_string(i->sample_spec.format), i->sample_spec.rate, i->sample_spec.channels); pa_sample_format_t format = i->sample_spec.format; if (pulse_to_obs_audio_format(format) == AUDIO_FORMAT_UNKNOWN) { @@ -294,8 +285,7 @@ static void pulse_source_info(pa_context *c, const pa_source_info *i, int eol, blog(LOG_INFO, "Sample format %s not supported by OBS," "using %s instead for recording", - pa_sample_format_to_string(i->sample_spec.format), - pa_sample_format_to_string(format)); + pa_sample_format_to_string(i->sample_spec.format), pa_sample_format_to_string(format)); } uint8_t channels = i->sample_spec.channels; @@ -333,14 +323,12 @@ static int_fast32_t pulse_start_recording(struct pulse_data *data) return -1; } - if (pulse_get_source_info(pulse_source_info, data->device, - (void *)data) < 0) { + if (pulse_get_source_info(pulse_source_info, data->device, (void *)data) < 0) { blog(LOG_ERROR, "Unable to get source info !"); return -1; } if (data->format == PA_SAMPLE_INVALID) { - blog(LOG_ERROR, - "An error occurred while getting the source info!"); + blog(LOG_ERROR, "An error occurred while getting the source info!"); return -1; } @@ -359,16 +347,14 @@ static int_fast32_t pulse_start_recording(struct pulse_data *data) pa_channel_map channel_map = pulse_channel_map(data->speakers); - data->stream = pulse_stream_new(obs_source_get_name(data->source), - &spec, &channel_map); + data->stream = pulse_stream_new(obs_source_get_name(data->source), &spec, &channel_map); if (!data->stream) { blog(LOG_ERROR, "Unable to create stream"); return -1; } pulse_lock(); - pa_stream_set_read_callback(data->stream, pulse_stream_read, - (void *)data); + pa_stream_set_read_callback(data->stream, pulse_stream_read, (void *)data); pulse_unlock(); pa_buffer_attr attr; @@ -383,8 +369,7 @@ static int_fast32_t pulse_start_recording(struct pulse_data *data) flags |= PA_STREAM_DONT_MOVE; pulse_lock(); - int_fast32_t ret = pa_stream_connect_record(data->stream, data->device, - &attr, flags); + int_fast32_t ret = pa_stream_connect_record(data->stream, data->device, &attr, flags); pulse_unlock(); if (ret < 0) { pulse_stop_recording(data); @@ -393,8 +378,7 @@ static int_fast32_t pulse_start_recording(struct pulse_data *data) } if (data->is_default) - blog(LOG_INFO, "Started recording from '%s' (default)", - data->device); + blog(LOG_INFO, "Started recording from '%s' (default)", data->device); else blog(LOG_INFO, "Started recording from '%s'", data->device); @@ -415,9 +399,7 @@ static void pulse_stop_recording(struct pulse_data *data) } blog(LOG_INFO, "Stopped recording from '%s'", data->device); - blog(LOG_INFO, - "Got %" PRIuFAST32 " packets with %" PRIuFAST64 " frames", - data->packets, data->frames); + blog(LOG_INFO, "Got %" PRIuFAST32 " packets with %" PRIuFAST64 " frames", data->packets, data->frames); data->first_ts = 0; data->packets = 0; @@ -427,15 +409,13 @@ static void pulse_stop_recording(struct pulse_data *data) /** * input info callback */ -static void pulse_input_info(pa_context *c, const pa_source_info *i, int eol, - void *userdata) +static void pulse_input_info(pa_context *c, const pa_source_info *i, int eol, void *userdata) { UNUSED_PARAMETER(c); if (eol != 0 || i->monitor_of_sink != PA_INVALID_INDEX) goto skip; - obs_property_list_add_string((obs_property_t *)userdata, i->description, - i->name); + obs_property_list_add_string((obs_property_t *)userdata, i->description, i->name); skip: pulse_signal(0); @@ -444,15 +424,13 @@ skip: /** * output info callback */ -static void pulse_output_info(pa_context *c, const pa_sink_info *i, int eol, - void *userdata) +static void pulse_output_info(pa_context *c, const pa_sink_info *i, int eol, void *userdata) { UNUSED_PARAMETER(c); if (eol != 0 || i->monitor_source == PA_INVALID_INDEX) goto skip; - obs_property_list_add_string((obs_property_t *)userdata, i->description, - i->monitor_source_name); + obs_property_list_add_string((obs_property_t *)userdata, i->description, i->monitor_source_name); skip: pulse_signal(0); @@ -464,9 +442,8 @@ skip: static obs_properties_t *pulse_properties(bool input) { obs_properties_t *props = obs_properties_create(); - obs_property_t *devices = obs_properties_add_list( - props, "device_id", obs_module_text("Device"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *devices = obs_properties_add_list(props, "device_id", obs_module_text("Device"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); pulse_init(); if (input) @@ -478,8 +455,7 @@ static obs_properties_t *pulse_properties(bool input) size_t count = obs_property_list_item_count(devices); if (count > 0) - obs_property_list_insert_string( - devices, 0, obs_module_text("Default"), "default"); + obs_property_list_insert_string(devices, 0, obs_module_text("Default"), "default"); return props; } @@ -569,8 +545,7 @@ static void pulse_update(void *vptr, obs_data_t *settings) /** * Create the plugin object */ -static void *pulse_create(obs_data_t *settings, obs_source_t *source, - bool input) +static void *pulse_create(obs_data_t *settings, obs_source_t *source, bool input) { struct pulse_data *data = bzalloc(sizeof(struct pulse_data)); @@ -609,8 +584,7 @@ struct obs_source_info pulse_input_capture = { struct obs_source_info pulse_output_capture = { .id = "pulse_output_capture", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | - OBS_SOURCE_DO_NOT_SELF_MONITOR, + .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_DO_NOT_SELF_MONITOR, .get_name = pulse_output_getname, .create = pulse_output_create, .destroy = pulse_destroy, diff --git a/plugins/linux-pulseaudio/pulse-wrapper.c b/plugins/linux-pulseaudio/pulse-wrapper.c index bb65148bd..ff383e601 100644 --- a/plugins/linux-pulseaudio/pulse-wrapper.c +++ b/plugins/linux-pulseaudio/pulse-wrapper.c @@ -66,11 +66,9 @@ static void pulse_init_context() pulse_lock(); pa_proplist *p = pulse_properties(); - pulse_context = pa_context_new_with_proplist( - pa_threaded_mainloop_get_api(pulse_mainloop), "OBS", p); + pulse_context = pa_context_new_with_proplist(pa_threaded_mainloop_get_api(pulse_mainloop), "OBS", p); - pa_context_set_state_callback(pulse_context, - pulse_context_state_changed, NULL); + pa_context_set_state_callback(pulse_context, pulse_context_state_changed, NULL); pa_context_connect(pulse_context, NULL, PA_CONTEXT_NOAUTOSPAWN, NULL); pa_proplist_free(p); @@ -170,8 +168,7 @@ int_fast32_t pulse_get_source_info_list(pa_source_info_cb_t cb, void *userdata) pulse_lock(); - pa_operation *op = - pa_context_get_source_info_list(pulse_context, cb, userdata); + pa_operation *op = pa_context_get_source_info_list(pulse_context, cb, userdata); if (!op) { pulse_unlock(); return -1; @@ -192,8 +189,7 @@ int_fast32_t pulse_get_sink_info_list(pa_sink_info_cb_t cb, void *userdata) pulse_lock(); - pa_operation *op = - pa_context_get_sink_info_list(pulse_context, cb, userdata); + pa_operation *op = pa_context_get_sink_info_list(pulse_context, cb, userdata); if (!op) { pulse_unlock(); return -1; @@ -207,16 +203,14 @@ int_fast32_t pulse_get_sink_info_list(pa_sink_info_cb_t cb, void *userdata) return 0; } -int_fast32_t pulse_get_source_info(pa_source_info_cb_t cb, const char *name, - void *userdata) +int_fast32_t pulse_get_source_info(pa_source_info_cb_t cb, const char *name, void *userdata) { if (pulse_context_ready() < 0) return -1; pulse_lock(); - pa_operation *op = pa_context_get_source_info_by_name( - pulse_context, name, cb, userdata); + pa_operation *op = pa_context_get_source_info_by_name(pulse_context, name, cb, userdata); if (!op) { pulse_unlock(); return -1; @@ -237,8 +231,7 @@ int_fast32_t pulse_get_server_info(pa_server_info_cb_t cb, void *userdata) pulse_lock(); - pa_operation *op = - pa_context_get_server_info(pulse_context, cb, userdata); + pa_operation *op = pa_context_get_server_info(pulse_context, cb, userdata); if (!op) { pulse_unlock(); return -1; @@ -251,8 +244,7 @@ int_fast32_t pulse_get_server_info(pa_server_info_cb_t cb, void *userdata) return 0; } -pa_stream *pulse_stream_new(const char *name, const pa_sample_spec *ss, - const pa_channel_map *map) +pa_stream *pulse_stream_new(const char *name, const pa_sample_spec *ss, const pa_channel_map *map) { if (pulse_context_ready() < 0) return NULL; @@ -260,8 +252,7 @@ pa_stream *pulse_stream_new(const char *name, const pa_sample_spec *ss, pulse_lock(); pa_proplist *p = pulse_properties(); - pa_stream *s = - pa_stream_new_with_proplist(pulse_context, name, ss, map, p); + pa_stream *s = pa_stream_new_with_proplist(pulse_context, name, ss, map, p); pa_proplist_free(p); pulse_unlock(); diff --git a/plugins/linux-pulseaudio/pulse-wrapper.h b/plugins/linux-pulseaudio/pulse-wrapper.h index afd738e1c..9c0b0ac2a 100644 --- a/plugins/linux-pulseaudio/pulse-wrapper.h +++ b/plugins/linux-pulseaudio/pulse-wrapper.h @@ -123,8 +123,7 @@ int_fast32_t pulse_get_sink_info_list(pa_sink_info_cb_t cb, void *userdata); * * @warning call without active locks */ -int_fast32_t pulse_get_source_info(pa_source_info_cb_t cb, const char *name, - void *userdata); +int_fast32_t pulse_get_source_info(pa_source_info_cb_t cb, const char *name, void *userdata); /** * Request server information @@ -147,5 +146,4 @@ int_fast32_t pulse_get_server_info(pa_server_info_cb_t cb, void *userdata); * * @warning call without active locks */ -pa_stream *pulse_stream_new(const char *name, const pa_sample_spec *ss, - const pa_channel_map *map); +pa_stream *pulse_stream_new(const char *name, const pa_sample_spec *ss, const pa_channel_map *map); diff --git a/plugins/linux-v4l2/linux-v4l2.c b/plugins/linux-v4l2/linux-v4l2.c index b0b581ef6..c9d89fad5 100644 --- a/plugins/linux-v4l2/linux-v4l2.c +++ b/plugins/linux-v4l2/linux-v4l2.c @@ -35,8 +35,7 @@ bool obs_module_load(void) if (loopback_module_available()) { obs_register_output(&virtualcam_info); } else { - blog(LOG_WARNING, - "v4l2loopback not installed, virtual camera not registered"); + blog(LOG_WARNING, "v4l2loopback not installed, virtual camera not registered"); } return true; diff --git a/plugins/linux-v4l2/v4l2-controls.c b/plugins/linux-v4l2/v4l2-controls.c index 58d4daaf8..928a6b37e 100644 --- a/plugins/linux-v4l2/v4l2-controls.c +++ b/plugins/linux-v4l2/v4l2-controls.c @@ -32,11 +32,9 @@ along with this program. If not, see . #define POINTER_TO_UINT(p) ((unsigned int)(unsigned int)(p)) #endif -static bool v4l2_control_changed(void *data, obs_properties_t *props, - obs_property_t *prop, obs_data_t *settings) +static bool v4l2_control_changed(void *data, obs_properties_t *props, obs_property_t *prop, obs_data_t *settings) { - int dev = v4l2_open(obs_data_get_string(settings, "device_id"), - O_RDWR | O_NONBLOCK); + int dev = v4l2_open(obs_data_get_string(settings, "device_id"), O_RDWR | O_NONBLOCK); bool ret = false; (void)props; @@ -49,17 +47,14 @@ static bool v4l2_control_changed(void *data, obs_properties_t *props, switch (obs_property_get_type(prop)) { case OBS_PROPERTY_BOOL: - control.value = - obs_data_get_bool(settings, obs_property_name(prop)); + control.value = obs_data_get_bool(settings, obs_property_name(prop)); break; case OBS_PROPERTY_INT: case OBS_PROPERTY_LIST: - control.value = - obs_data_get_int(settings, obs_property_name(prop)); + control.value = obs_data_get_int(settings, obs_property_name(prop)); break; default: - blog(LOG_ERROR, "unknown property type for %s", - obs_property_name(prop)); + blog(LOG_ERROR, "unknown property type for %s", obs_property_name(prop)); v4l2_close(dev); return ret; } @@ -73,28 +68,22 @@ static bool v4l2_control_changed(void *data, obs_properties_t *props, return ret; } -static bool v4l2_update_controls_menu(int_fast32_t dev, obs_properties_t *props, - struct v4l2_queryctrl *qctrl) +static bool v4l2_update_controls_menu(int_fast32_t dev, obs_properties_t *props, struct v4l2_queryctrl *qctrl) { obs_property_t *prop; struct v4l2_querymenu qmenu; - prop = obs_properties_add_list(props, (char *)qctrl->name, - (char *)qctrl->name, OBS_COMBO_TYPE_LIST, + prop = obs_properties_add_list(props, (char *)qctrl->name, (char *)qctrl->name, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_set_modified_callback2(prop, v4l2_control_changed, - UINT_TO_POINTER(qctrl->id)); + obs_property_set_modified_callback2(prop, v4l2_control_changed, UINT_TO_POINTER(qctrl->id)); memset(&qmenu, 0, sizeof(qmenu)); qmenu.id = qctrl->id; - for (qmenu.index = qctrl->minimum; - qmenu.index <= (uint32_t)qctrl->maximum; - qmenu.index += qctrl->step) { + for (qmenu.index = qctrl->minimum; qmenu.index <= (uint32_t)qctrl->maximum; qmenu.index += qctrl->step) { if (0 == v4l2_ioctl(dev, VIDIOC_QUERYMENU, &qmenu)) { - obs_property_list_add_int(prop, (char *)qmenu.name, - qmenu.index); + obs_property_list_add_int(prop, (char *)qmenu.name, qmenu.index); } } @@ -106,17 +95,14 @@ static bool v4l2_update_controls_menu(int_fast32_t dev, obs_properties_t *props, return true; } -#define INVALID_CONTROL_FLAGS \ - (V4L2_CTRL_FLAG_DISABLED | V4L2_CTRL_FLAG_READ_ONLY | \ - V4L2_CTRL_FLAG_VOLATILE) +#define INVALID_CONTROL_FLAGS (V4L2_CTRL_FLAG_DISABLED | V4L2_CTRL_FLAG_READ_ONLY | V4L2_CTRL_FLAG_VOLATILE) static inline bool valid_control(struct v4l2_queryctrl *qctrl) { return (qctrl->flags & INVALID_CONTROL_FLAGS) == 0; } -static inline void add_control_property(obs_properties_t *props, - obs_data_t *settings, int_fast32_t dev, +static inline void add_control_property(obs_properties_t *props, obs_data_t *settings, int_fast32_t dev, struct v4l2_queryctrl *qctrl) { obs_property_t *prop = NULL; @@ -127,36 +113,27 @@ static inline void add_control_property(obs_properties_t *props, switch (qctrl->type) { case V4L2_CTRL_TYPE_INTEGER: - prop = obs_properties_add_int_slider( - props, (char *)qctrl->name, (char *)qctrl->name, - qctrl->minimum, qctrl->maximum, qctrl->step); - obs_data_set_default_int(settings, (char *)qctrl->name, - qctrl->default_value); - obs_property_set_modified_callback2(prop, v4l2_control_changed, - UINT_TO_POINTER(qctrl->id)); + prop = obs_properties_add_int_slider(props, (char *)qctrl->name, (char *)qctrl->name, qctrl->minimum, + qctrl->maximum, qctrl->step); + obs_data_set_default_int(settings, (char *)qctrl->name, qctrl->default_value); + obs_property_set_modified_callback2(prop, v4l2_control_changed, UINT_TO_POINTER(qctrl->id)); break; case V4L2_CTRL_TYPE_BOOLEAN: - prop = obs_properties_add_bool(props, (char *)qctrl->name, - (char *)qctrl->name); - obs_data_set_default_bool(settings, (char *)qctrl->name, - qctrl->default_value); - obs_property_set_modified_callback2(prop, v4l2_control_changed, - UINT_TO_POINTER(qctrl->id)); + prop = obs_properties_add_bool(props, (char *)qctrl->name, (char *)qctrl->name); + obs_data_set_default_bool(settings, (char *)qctrl->name, qctrl->default_value); + obs_property_set_modified_callback2(prop, v4l2_control_changed, UINT_TO_POINTER(qctrl->id)); break; case V4L2_CTRL_TYPE_MENU: case V4L2_CTRL_TYPE_INTEGER_MENU: if (v4l2_update_controls_menu(dev, props, qctrl)) { - obs_data_set_default_int(settings, (char *)qctrl->name, - qctrl->default_value); - blog(LOG_INFO, "setting default for %s to %d", - (char *)qctrl->name, qctrl->default_value); + obs_data_set_default_int(settings, (char *)qctrl->name, qctrl->default_value); + blog(LOG_INFO, "setting default for %s to %d", (char *)qctrl->name, qctrl->default_value); } break; } } -int_fast32_t v4l2_update_controls(int_fast32_t dev, obs_properties_t *props, - obs_data_t *settings) +int_fast32_t v4l2_update_controls(int_fast32_t dev, obs_properties_t *props, obs_data_t *settings) { struct v4l2_queryctrl qctrl; diff --git a/plugins/linux-v4l2/v4l2-controls.h b/plugins/linux-v4l2/v4l2-controls.h index 8f082c448..2470ac910 100644 --- a/plugins/linux-v4l2/v4l2-controls.h +++ b/plugins/linux-v4l2/v4l2-controls.h @@ -32,8 +32,7 @@ extern "C" { * * @return negative on failure */ -int_fast32_t v4l2_update_controls(int_fast32_t dev, obs_properties_t *props, - obs_data_t *settings); +int_fast32_t v4l2_update_controls(int_fast32_t dev, obs_properties_t *props, obs_data_t *settings); #ifdef __cplusplus } diff --git a/plugins/linux-v4l2/v4l2-decoder.c b/plugins/linux-v4l2/v4l2-decoder.c index 89089219a..b58f6bb3f 100644 --- a/plugins/linux-v4l2/v4l2-decoder.c +++ b/plugins/linux-v4l2/v4l2-decoder.c @@ -20,8 +20,7 @@ along with this program. If not, see . #include "v4l2-decoder.h" -#define blog(level, msg, ...) \ - blog(level, "v4l2-input: decoder: " msg, ##__VA_ARGS__) +#define blog(level, msg, ...) blog(level, "v4l2-input: decoder: " msg, ##__VA_ARGS__) int v4l2_init_decoder(struct v4l2_decoder *decoder, int pixfmt) { @@ -85,8 +84,7 @@ void v4l2_destroy_decoder(struct v4l2_decoder *decoder) } } -int v4l2_decode_frame(struct obs_source_frame *out, uint8_t *data, - size_t length, struct v4l2_decoder *decoder) +int v4l2_decode_frame(struct obs_source_frame *out, uint8_t *data, size_t length, struct v4l2_decoder *decoder) { decoder->packet->data = data; decoder->packet->size = length; diff --git a/plugins/linux-v4l2/v4l2-decoder.h b/plugins/linux-v4l2/v4l2-decoder.h index f6ae815de..5bd64baf7 100644 --- a/plugins/linux-v4l2/v4l2-decoder.h +++ b/plugins/linux-v4l2/v4l2-decoder.h @@ -61,8 +61,7 @@ void v4l2_destroy_decoder(struct v4l2_decoder *decoder); * @param decoder the decoder as initialized by v4l2_init_decoder * @return non-zero on failure */ -int v4l2_decode_frame(struct obs_source_frame *out, uint8_t *data, - size_t length, struct v4l2_decoder *decoder); +int v4l2_decode_frame(struct obs_source_frame *out, uint8_t *data, size_t length, struct v4l2_decoder *decoder); #ifdef __cplusplus } diff --git a/plugins/linux-v4l2/v4l2-helpers.c b/plugins/linux-v4l2/v4l2-helpers.c index a40b13269..d8128950d 100644 --- a/plugins/linux-v4l2/v4l2-helpers.c +++ b/plugins/linux-v4l2/v4l2-helpers.c @@ -73,26 +73,22 @@ int_fast32_t v4l2_reset_capture(int_fast32_t dev, struct v4l2_buffer_data *buf) } #ifdef _DEBUG -int_fast32_t v4l2_query_all_buffers(int_fast32_t dev, - struct v4l2_buffer_data *buf_data) +int_fast32_t v4l2_query_all_buffers(int_fast32_t dev, struct v4l2_buffer_data *buf_data) { struct v4l2_buffer buf; - blog(LOG_DEBUG, "attempting to read buffer data for %ld buffers", - buf_data->count); + blog(LOG_DEBUG, "attempting to read buffer data for %ld buffers", buf_data->count); for (uint_fast32_t i = 0; i < buf_data->count; i++) { buf.index = i; buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE; buf.memory = V4L2_MEMORY_MMAP; if (v4l2_ioctl(dev, VIDIOC_QUERYBUF, &buf) < 0) { - blog(LOG_DEBUG, - "failed to read buffer data for buffer #%ld", i); + blog(LOG_DEBUG, "failed to read buffer data for buffer #%ld", i); } else { blog(LOG_DEBUG, - "query buf #%ld info: ts: %06ld buf id #%d, flags 0x%08X, seq #%d, len %d, used %d", - i, buf.timestamp.tv_usec, buf.index, buf.flags, - buf.sequence, buf.length, buf.bytesused); + "query buf #%ld info: ts: %06ld buf id #%d, flags 0x%08X, seq #%d, len %d, used %d", i, + buf.timestamp.tv_usec, buf.index, buf.flags, buf.sequence, buf.length, buf.bytesused); } } @@ -135,8 +131,7 @@ int_fast32_t v4l2_create_mmap(int_fast32_t dev, struct v4l2_buffer_data *buf) buf->info[map.index].length = map.length; buf->info[map.index].start = - v4l2_mmap(NULL, map.length, PROT_READ | PROT_WRITE, - MAP_SHARED, dev, map.m.offset); + v4l2_mmap(NULL, map.length, PROT_READ | PROT_WRITE, MAP_SHARED, dev, map.m.offset); if (buf->info[map.index].start == MAP_FAILED) { blog(LOG_ERROR, "mmap for buffer failed"); @@ -167,8 +162,7 @@ int_fast32_t v4l2_set_input(int_fast32_t dev, int *input) if (!dev || !input) return -1; - return (*input == -1) ? v4l2_ioctl(dev, VIDIOC_G_INPUT, input) - : v4l2_ioctl(dev, VIDIOC_S_INPUT, input); + return (*input == -1) ? v4l2_ioctl(dev, VIDIOC_G_INPUT, input) : v4l2_ioctl(dev, VIDIOC_S_INPUT, input); } int_fast32_t v4l2_get_input_caps(int_fast32_t dev, int input, uint32_t *caps) @@ -192,8 +186,7 @@ int_fast32_t v4l2_get_input_caps(int_fast32_t dev, int input, uint32_t *caps) return 0; } -int_fast32_t v4l2_set_format(int_fast32_t dev, int64_t *resolution, - int *pixelformat, int *bytesperline) +int_fast32_t v4l2_set_format(int_fast32_t dev, int64_t *resolution, int *pixelformat, int *bytesperline) { bool set = false; int width, height; @@ -254,8 +247,8 @@ int_fast32_t v4l2_set_framerate(int_fast32_t dev, int64_t *framerate) if (set && (v4l2_ioctl(dev, VIDIOC_S_PARM, &par) < 0)) return -1; - *framerate = v4l2_pack_tuple(par.parm.capture.timeperframe.numerator, - par.parm.capture.timeperframe.denominator); + *framerate = + v4l2_pack_tuple(par.parm.capture.timeperframe.numerator, par.parm.capture.timeperframe.denominator); return 0; } @@ -275,8 +268,7 @@ int_fast32_t v4l2_set_standard(int_fast32_t dev, int *standard) return 0; } -int_fast32_t v4l2_enum_dv_timing(int_fast32_t dev, struct v4l2_dv_timings *dvt, - int index) +int_fast32_t v4l2_enum_dv_timing(int_fast32_t dev, struct v4l2_dv_timings *dvt, int index) { #if !defined(VIDIOC_ENUM_DV_TIMINGS) || !defined(V4L2_IN_CAP_DV_TIMINGS) UNUSED_PARAMETER(dev); diff --git a/plugins/linux-v4l2/v4l2-helpers.h b/plugins/linux-v4l2/v4l2-helpers.h index a53bf17d4..058429aa1 100644 --- a/plugins/linux-v4l2/v4l2-helpers.h +++ b/plugins/linux-v4l2/v4l2-helpers.h @@ -96,22 +96,19 @@ static inline enum video_format v4l2_to_obs_video_format(uint_fast32_t format) */ static const int64_t v4l2_framesizes[] = { /* 4:3 */ - PACK64(160, 120), PACK64(320, 240), PACK64(480, 320), PACK64(640, 480), - PACK64(800, 600), PACK64(1024, 768), PACK64(1280, 960), - PACK64(1440, 1050), PACK64(1440, 1080), PACK64(1600, 1200), + PACK64(160, 120), PACK64(320, 240), PACK64(480, 320), PACK64(640, 480), PACK64(800, 600), PACK64(1024, 768), + PACK64(1280, 960), PACK64(1440, 1050), PACK64(1440, 1080), PACK64(1600, 1200), /* 16:9 */ - PACK64(640, 360), PACK64(960, 540), PACK64(1280, 720), - PACK64(1600, 900), PACK64(1920, 1080), PACK64(1920, 1200), - PACK64(2560, 1440), PACK64(3840, 2160), + PACK64(640, 360), PACK64(960, 540), PACK64(1280, 720), PACK64(1600, 900), PACK64(1920, 1080), + PACK64(1920, 1200), PACK64(2560, 1440), PACK64(3840, 2160), /* 21:9 */ PACK64(2560, 1080), PACK64(3440, 1440), PACK64(5120, 2160), /* tv */ - PACK64(432, 520), PACK64(480, 320), PACK64(480, 530), PACK64(486, 440), - PACK64(576, 310), PACK64(576, 520), PACK64(576, 570), PACK64(720, 576), - PACK64(1024, 576), + PACK64(432, 520), PACK64(480, 320), PACK64(480, 530), PACK64(486, 440), PACK64(576, 310), PACK64(576, 520), + PACK64(576, 570), PACK64(720, 576), PACK64(1024, 576), 0}; @@ -217,8 +214,7 @@ int_fast32_t v4l2_reset_capture(int_fast32_t dev, struct v4l2_buffer_data *buf); * * @return negative on failure */ -int_fast32_t v4l2_query_all_buffers(int_fast32_t dev, - struct v4l2_buffer_data *buf_data); +int_fast32_t v4l2_query_all_buffers(int_fast32_t dev, struct v4l2_buffer_data *buf_data); #endif /** @@ -278,8 +274,7 @@ int_fast32_t v4l2_get_input_caps(int_fast32_t dev, int input, uint32_t *caps); * * @return negative on failure */ -int_fast32_t v4l2_set_format(int_fast32_t dev, int64_t *resolution, - int *pixelformat, int *bytesperline); +int_fast32_t v4l2_set_format(int_fast32_t dev, int64_t *resolution, int *pixelformat, int *bytesperline); /** * Set the framerate on the device. @@ -314,8 +309,7 @@ int_fast32_t v4l2_set_standard(int_fast32_t dev, int *standard); * * @return negative on failure */ -int_fast32_t v4l2_enum_dv_timing(int_fast32_t dev, struct v4l2_dv_timings *dvt, - int index); +int_fast32_t v4l2_enum_dv_timing(int_fast32_t dev, struct v4l2_dv_timings *dvt, int index); /** * Set a dv timing on the device * diff --git a/plugins/linux-v4l2/v4l2-input.c b/plugins/linux-v4l2/v4l2-input.c index 3ba95cc04..80971cfec 100644 --- a/plugins/linux-v4l2/v4l2-input.c +++ b/plugins/linux-v4l2/v4l2-input.c @@ -53,14 +53,12 @@ along with this program. If not, see . #define V4L2_DATA(voidptr) struct v4l2_data *data = voidptr; -#define timeval2ns(tv) \ - (((uint64_t)tv.tv_sec * 1000000000) + ((uint64_t)tv.tv_usec * 1000)) +#define timeval2ns(tv) (((uint64_t)tv.tv_sec * 1000000000) + ((uint64_t)tv.tv_usec * 1000)) -#define V4L2_FOURCC_STR(code) \ - (char[5]) \ - { \ - code & 0xFF, (code >> 8) & 0xFF, (code >> 16) & 0xFF, \ - (code >> 24) & 0xFF, 0 \ +#define V4L2_FOURCC_STR(code) \ + (char[5]) \ + { \ + code & 0xFF, (code >> 8) & 0xFF, (code >> 16) & 0xFF, (code >> 24) & 0xFF, 0 \ } #define blog(level, msg, ...) blog(level, "v4l2-input: " msg, ##__VA_ARGS__) @@ -116,9 +114,7 @@ static void v4l2_update(void *vptr, obs_data_t *settings); * pointers for the individual planes. * */ -static void v4l2_prep_obs_frame(struct v4l2_data *data, - struct obs_source_frame *frame, - size_t *plane_offsets) +static void v4l2_prep_obs_frame(struct v4l2_data *data, struct obs_source_frame *frame, size_t *plane_offsets) { memset(frame, 0, sizeof(struct obs_source_frame)); memset(plane_offsets, 0, sizeof(size_t) * MAX_AV_PLANES); @@ -129,11 +125,8 @@ static void v4l2_prep_obs_frame(struct v4l2_data *data, frame->width = data->width; frame->height = data->height; frame->format = format; - video_format_get_parameters_for_format(VIDEO_CS_DEFAULT, - data->color_range, format, - frame->color_matrix, - frame->color_range_min, - frame->color_range_max); + video_format_get_parameters_for_format(VIDEO_CS_DEFAULT, data->color_range, format, frame->color_matrix, + frame->color_range_min, frame->color_range_max); switch (data->pixfmt) { case V4L2_PIX_FMT_NV12: @@ -189,9 +182,8 @@ static void *v4l2_thread(void *vptr) blog(LOG_DEBUG, "%s: framerate: %.2f fps", data->device_id, ffps); /* Timeout set to 5 frame periods. */ timeout_usec = (1000000 * data->timeout_frames) / ffps; - blog(LOG_INFO, - "%s: select timeout set to %" PRIu64 " (%dx frame periods)", - data->device_id, timeout_usec, data->timeout_frames); + blog(LOG_INFO, "%s: select timeout set to %" PRIu64 " (%dx frame periods)", data->device_id, timeout_usec, + data->timeout_frames); if (v4l2_start_capture(data->dev, &data->buffers) < 0) goto exit; @@ -219,27 +211,21 @@ static void *v4l2_thread(void *vptr) blog(LOG_ERROR, "%s: select failed", data->device_id); break; } else if (r == 0) { - blog(LOG_ERROR, "%s: select timed out", - data->device_id); + blog(LOG_ERROR, "%s: select timed out", data->device_id); #ifdef _DEBUG v4l2_query_all_buffers(data->dev, &data->buffers); #endif if (v4l2_ioctl(data->dev, VIDIOC_LOG_STATUS) < 0) { - blog(LOG_ERROR, "%s: failed to log status", - data->device_id); + blog(LOG_ERROR, "%s: failed to log status", data->device_id); } if (data->auto_reset) { - if (v4l2_reset_capture(data->dev, - &data->buffers) == 0) - blog(LOG_INFO, - "%s: stream reset successful", - data->device_id); + if (v4l2_reset_capture(data->dev, &data->buffers) == 0) + blog(LOG_INFO, "%s: stream reset successful", data->device_id); else - blog(LOG_ERROR, "%s: failed to reset", - data->device_id); + blog(LOG_ERROR, "%s: failed to reset", data->device_id); } continue; @@ -250,19 +236,15 @@ static void *v4l2_thread(void *vptr) if (v4l2_ioctl(data->dev, VIDIOC_DQBUF, &buf) < 0) { if (errno == EAGAIN) { - blog(LOG_DEBUG, "%s: ioctl dqbuf eagain", - data->device_id); + blog(LOG_DEBUG, "%s: ioctl dqbuf eagain", data->device_id); continue; } - blog(LOG_ERROR, "%s: failed to dequeue buffer", - data->device_id); + blog(LOG_ERROR, "%s: failed to dequeue buffer", data->device_id); break; } - blog(LOG_DEBUG, - "%s: ts: %06ld buf id #%d, flags 0x%08X, seq #%d, len %d, used %d", - data->device_id, buf.timestamp.tv_usec, buf.index, - buf.flags, buf.sequence, buf.length, buf.bytesused); + blog(LOG_DEBUG, "%s: ts: %06ld buf id #%d, flags 0x%08X, seq #%d, len %d, used %d", data->device_id, + buf.timestamp.tv_usec, buf.index, buf.flags, buf.sequence, buf.length, buf.bytesused); out.timestamp = timeval2ns(buf.timestamp); if (!frames) @@ -271,12 +253,9 @@ static void *v4l2_thread(void *vptr) start = (uint8_t *)data->buffers.info[buf.index].start; - if (data->pixfmt == V4L2_PIX_FMT_MJPEG || - data->pixfmt == V4L2_PIX_FMT_H264) { - if (v4l2_decode_frame(&out, start, buf.bytesused, - &data->decoder) < 0) { - blog(LOG_ERROR, - "failed to unpack jpeg or h264"); + if (data->pixfmt == V4L2_PIX_FMT_MJPEG || data->pixfmt == V4L2_PIX_FMT_H264) { + if (v4l2_decode_frame(&out, start, buf.bytesused, &data->decoder) < 0) { + blog(LOG_ERROR, "failed to unpack jpeg or h264"); break; } } else { @@ -286,16 +265,14 @@ static void *v4l2_thread(void *vptr) obs_source_output_video(data->source, &out); if (v4l2_ioctl(data->dev, VIDIOC_QBUF, &buf) < 0) { - blog(LOG_ERROR, "%s: failed to enqueue buffer", - data->device_id); + blog(LOG_ERROR, "%s: failed to enqueue buffer", data->device_id); break; } frames++; } - blog(LOG_INFO, "%s: Stopped capture after %" PRIu64 " frames", - data->device_id, frames); + blog(LOG_INFO, "%s: Stopped capture after %" PRIu64 " frames", data->device_id, frames); exit: v4l2_stop_capture(data->dev); @@ -331,14 +308,12 @@ static void v4l2_defaults(obs_data_t *settings) * @param ignore ignore this property * @param enable enable/disable all properties */ -static void v4l2_props_set_enabled(obs_properties_t *props, - obs_property_t *ignore, bool enable) +static void v4l2_props_set_enabled(obs_properties_t *props, obs_property_t *ignore, bool enable) { if (!props) return; - for (obs_property_t *prop = obs_properties_first(props); prop != NULL; - obs_property_next(&prop)) { + for (obs_property_t *prop = obs_properties_first(props); prop != NULL; obs_property_next(&prop)) { if (prop == ignore) continue; @@ -395,8 +370,7 @@ static void v4l2_device_list(obs_property_t *prop, obs_data_t *settings) } if (v4l2_ioctl(fd, VIDIOC_QUERYCAP, &video_cap) == -1) { - blog(LOG_INFO, "Failed to query capabilities for %s", - device.array); + blog(LOG_INFO, "Failed to query capabilities for %s", device.array); v4l2_close(fd); continue; } @@ -405,32 +379,25 @@ static void v4l2_device_list(obs_property_t *prop, obs_data_t *settings) caps = video_cap.capabilities; #else /* ... since Linux 3.3 */ - caps = (video_cap.capabilities & V4L2_CAP_DEVICE_CAPS) - ? video_cap.device_caps - : video_cap.capabilities; + caps = (video_cap.capabilities & V4L2_CAP_DEVICE_CAPS) ? video_cap.device_caps : video_cap.capabilities; #endif if (!(caps & V4L2_CAP_VIDEO_CAPTURE)) { - blog(LOG_INFO, "%s seems to not support video capture", - device.array); + blog(LOG_INFO, "%s seems to not support video capture", device.array); v4l2_close(fd); continue; } /* make sure device names are unique */ char unique_device_name[68]; - int ret = snprintf(unique_device_name, - sizeof(unique_device_name), "%s (%s)", - video_cap.card, video_cap.bus_info); + int ret = snprintf(unique_device_name, sizeof(unique_device_name), "%s (%s)", video_cap.card, + video_cap.bus_info); if (ret >= (int)sizeof(unique_device_name)) - blog(LOG_DEBUG, - "linux-v4l2: A format truncation may have occurred." - " This can be ignored since it is quite improbable."); + blog(LOG_DEBUG, "linux-v4l2: A format truncation may have occurred." + " This can be ignored since it is quite improbable."); - obs_property_list_add_string(prop, unique_device_name, - device.array); - blog(LOG_INFO, "Found device '%s' at %s", video_cap.card, - device.array); + obs_property_list_add_string(prop, unique_device_name, device.array); + blog(LOG_INFO, "Found device '%s' at %s", video_cap.card, device.array); /* check if this is the currently used device */ if (cur_device_name && !strcmp(cur_device_name, device.array)) @@ -441,8 +408,7 @@ static void v4l2_device_list(obs_property_t *prop, obs_data_t *settings) /* add currently selected device if not present, but disable it ... */ if (!cur_device_found && cur_device_name && strlen(cur_device_name)) { - cur_device_index = obs_property_list_add_string( - prop, cur_device_name, cur_device_name); + cur_device_index = obs_property_list_add_string(prop, cur_device_name, cur_device_name); obs_property_list_item_disable(prop, cur_device_index, true); } @@ -462,8 +428,7 @@ static void v4l2_input_list(int_fast32_t dev, obs_property_t *prop) while (v4l2_ioctl(dev, VIDIOC_ENUMINPUT, &in) == 0) { obs_property_list_add_int(prop, (char *)in.name, in.index); - blog(LOG_INFO, "Found input '%s' (Index %d)", in.name, - in.index); + blog(LOG_INFO, "Found input '%s' (Index %d)", in.name, in.index); in.index++; } } @@ -486,17 +451,12 @@ static void v4l2_format_list(int dev, obs_property_t *prop) if (fmt.flags & V4L2_FMT_FLAG_EMULATED) dstr_cat(&buffer, " (Emulated)"); - if (v4l2_to_obs_video_format(fmt.pixelformat) != - VIDEO_FORMAT_NONE || - fmt.pixelformat == V4L2_PIX_FMT_MJPEG || - fmt.pixelformat == V4L2_PIX_FMT_H264) { - obs_property_list_add_int(prop, buffer.array, - fmt.pixelformat); - blog(LOG_INFO, "Pixelformat: %s (available)", - buffer.array); + if (v4l2_to_obs_video_format(fmt.pixelformat) != VIDEO_FORMAT_NONE || + fmt.pixelformat == V4L2_PIX_FMT_MJPEG || fmt.pixelformat == V4L2_PIX_FMT_H264) { + obs_property_list_add_int(prop, buffer.array, fmt.pixelformat); + blog(LOG_INFO, "Pixelformat: %s (available)", buffer.array); } else { - blog(LOG_INFO, "Pixelformat: %s (unavailable)", - buffer.array); + blog(LOG_INFO, "Pixelformat: %s (unavailable)", buffer.array); } fmt.index++; } @@ -538,17 +498,13 @@ static void v4l2_dv_timing_list(int dev, obs_property_t *prop) while (v4l2_enum_dv_timing(dev, &dvt, index) == 0) { /* i do not pretend to understand, this is from qv4l2 ... */ - double h = (double)dvt.bt.height + dvt.bt.vfrontporch + - dvt.bt.vsync + dvt.bt.vbackporch + - dvt.bt.il_vfrontporch + dvt.bt.il_vsync + - dvt.bt.il_vbackporch; - double w = (double)dvt.bt.width + dvt.bt.hfrontporch + - dvt.bt.hsync + dvt.bt.hbackporch; + double h = (double)dvt.bt.height + dvt.bt.vfrontporch + dvt.bt.vsync + dvt.bt.vbackporch + + dvt.bt.il_vfrontporch + dvt.bt.il_vsync + dvt.bt.il_vbackporch; + double w = (double)dvt.bt.width + dvt.bt.hfrontporch + dvt.bt.hsync + dvt.bt.hbackporch; double i = (dvt.bt.interlaced) ? 2.0f : 1.0f; double rate = (double)dvt.bt.pixelclock / (w * (h / i)); - dstr_printf(&buf, "%ux%u%c %.2f", dvt.bt.width, dvt.bt.height, - (dvt.bt.interlaced) ? 'i' : 'p', rate); + dstr_printf(&buf, "%ux%u%c %.2f", dvt.bt.width, dvt.bt.height, (dvt.bt.interlaced) ? 'i' : 'p', rate); obs_property_list_add_int(prop, buf.array, index); @@ -561,8 +517,7 @@ static void v4l2_dv_timing_list(int dev, obs_property_t *prop) /* * List resolutions for device and format */ -static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat, - obs_property_t *prop) +static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat, obs_property_t *prop) { struct v4l2_frmsizeenum frmsize; frmsize.pixel_format = pixelformat; @@ -579,12 +534,9 @@ static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat, switch (frmsize.type) { case V4L2_FRMSIZE_TYPE_DISCRETE: while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMESIZES, &frmsize) == 0) { - dstr_printf(&buffer, "%dx%d", frmsize.discrete.width, - frmsize.discrete.height); - obs_property_list_add_int( - prop, buffer.array, - v4l2_pack_tuple(frmsize.discrete.width, - frmsize.discrete.height)); + dstr_printf(&buffer, "%dx%d", frmsize.discrete.width, frmsize.discrete.height); + obs_property_list_add_int(prop, buffer.array, + v4l2_pack_tuple(frmsize.discrete.width, frmsize.discrete.height)); frmsize.index++; } break; @@ -592,8 +544,7 @@ static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat, blog(LOG_INFO, "Stepwise and Continuous framesizes " "are currently hardcoded"); - for (const int64_t *packed = v4l2_framesizes; *packed; - ++packed) { + for (const int64_t *packed = v4l2_framesizes; *packed; ++packed) { int width; int height; v4l2_unpack_tuple(&width, &height, *packed); @@ -609,8 +560,7 @@ static void v4l2_resolution_list(int dev, uint_fast32_t pixelformat, /* * List framerates for device and resolution */ -static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat, - uint_fast32_t width, uint_fast32_t height, +static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat, uint_fast32_t width, uint_fast32_t height, obs_property_t *prop) { struct v4l2_frmivalenum frmival; @@ -629,13 +579,9 @@ static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat, switch (frmival.type) { case V4L2_FRMIVAL_TYPE_DISCRETE: - while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS, &frmival) == - 0) { - float fps = (float)frmival.discrete.denominator / - frmival.discrete.numerator; - int pack = - v4l2_pack_tuple(frmival.discrete.numerator, - frmival.discrete.denominator); + while (v4l2_ioctl(dev, VIDIOC_ENUM_FRAMEINTERVALS, &frmival) == 0) { + float fps = (float)frmival.discrete.denominator / frmival.discrete.numerator; + int pack = v4l2_pack_tuple(frmival.discrete.numerator, frmival.discrete.denominator); dstr_printf(&buffer, "%.2f", fps); obs_property_list_add_int(prop, buffer.array, pack); frmival.index++; @@ -645,8 +591,7 @@ static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat, blog(LOG_INFO, "Stepwise and Continuous framerates " "are currently hardcoded"); - for (const int64_t *packed = v4l2_framerates; *packed; - ++packed) { + for (const int64_t *packed = v4l2_framerates; *packed; ++packed) { int num; int denom; v4l2_unpack_tuple(&num, &denom, *packed); @@ -663,11 +608,9 @@ static void v4l2_framerate_list(int dev, uint_fast32_t pixelformat, /* * Device selected callback */ -static bool device_selected(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool device_selected(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { - int dev = v4l2_open(obs_data_get_string(settings, "device_id"), - O_RDWR | O_NONBLOCK); + int dev = v4l2_open(obs_data_get_string(settings, "device_id"), O_RDWR | O_NONBLOCK); v4l2_props_set_enabled(props, p, (dev == -1) ? false : true); @@ -683,9 +626,7 @@ static bool device_selected(obs_properties_t *props, obs_property_t *p, v4l2_update_controls(dev, ctrl_props_new, settings); v4l2_close(dev); - obs_properties_add_group(props, "controls", - obs_module_text("CameraCtrls"), - OBS_GROUP_NORMAL, ctrl_props_new); + obs_properties_add_group(props, "controls", obs_module_text("CameraCtrls"), OBS_GROUP_NORMAL, ctrl_props_new); obs_property_modified(prop, settings); @@ -695,12 +636,10 @@ static bool device_selected(obs_properties_t *props, obs_property_t *p, /* * Input selected callback */ -static bool input_selected(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool input_selected(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); - int dev = v4l2_open(obs_data_get_string(settings, "device_id"), - O_RDWR | O_NONBLOCK); + int dev = v4l2_open(obs_data_get_string(settings, "device_id"), O_RDWR | O_NONBLOCK); if (dev == -1) return false; @@ -716,12 +655,10 @@ static bool input_selected(obs_properties_t *props, obs_property_t *p, /* * Format selected callback */ -static bool format_selected(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool format_selected(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); - int dev = v4l2_open(obs_data_get_string(settings, "device_id"), - O_RDWR | O_NONBLOCK); + int dev = v4l2_open(obs_data_get_string(settings, "device_id"), O_RDWR | O_NONBLOCK); if (dev == -1) return false; @@ -738,15 +675,11 @@ static bool format_selected(obs_properties_t *props, obs_property_t *p, obs_property_set_visible(resolution, (!caps) ? true : false); obs_property_set_visible(framerate, (!caps) ? true : false); - obs_property_set_visible(standard, - (caps & V4L2_IN_CAP_STD) ? true : false); - obs_property_set_visible( - dv_timing, (caps & V4L2_IN_CAP_DV_TIMINGS) ? true : false); + obs_property_set_visible(standard, (caps & V4L2_IN_CAP_STD) ? true : false); + obs_property_set_visible(dv_timing, (caps & V4L2_IN_CAP_DV_TIMINGS) ? true : false); if (!caps) { - v4l2_resolution_list(dev, - obs_data_get_int(settings, "pixelformat"), - resolution); + v4l2_resolution_list(dev, obs_data_get_int(settings, "pixelformat"), resolution); } if (caps & V4L2_IN_CAP_STD) v4l2_standard_list(dev, standard); @@ -768,21 +701,17 @@ static bool format_selected(obs_properties_t *props, obs_property_t *p, /* * Resolution selected callback */ -static bool resolution_selected(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool resolution_selected(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); int width, height; - int dev = v4l2_open(obs_data_get_string(settings, "device_id"), - O_RDWR | O_NONBLOCK); + int dev = v4l2_open(obs_data_get_string(settings, "device_id"), O_RDWR | O_NONBLOCK); if (dev == -1) return false; obs_property_t *prop = obs_properties_get(props, "framerate"); - v4l2_unpack_tuple(&width, &height, - obs_data_get_int(settings, "resolution")); - v4l2_framerate_list(dev, obs_data_get_int(settings, "pixelformat"), - width, height, prop); + v4l2_unpack_tuple(&width, &height, obs_data_get_int(settings, "resolution")); + v4l2_framerate_list(dev, obs_data_get_int(settings, "pixelformat"), width, height, prop); v4l2_close(dev); obs_property_modified(prop, settings); @@ -843,64 +772,44 @@ static obs_properties_t *v4l2_properties(void *vptr) obs_properties_t *props = obs_properties_create(); - obs_property_t *device_list = obs_properties_add_list( - props, "device_id", obs_module_text("Device"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *device_list = obs_properties_add_list(props, "device_id", obs_module_text("Device"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_t *input_list = obs_properties_add_list( - props, "input", obs_module_text("Input"), OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + obs_property_t *input_list = obs_properties_add_list(props, "input", obs_module_text("Input"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_t *format_list = obs_properties_add_list( - props, "pixelformat", obs_module_text("VideoFormat"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *format_list = obs_properties_add_list(props, "pixelformat", obs_module_text("VideoFormat"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_t *standard_list = obs_properties_add_list( - props, "standard", obs_module_text("VideoStandard"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *standard_list = obs_properties_add_list(props, "standard", obs_module_text("VideoStandard"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_visible(standard_list, false); - obs_property_t *dv_timing_list = obs_properties_add_list( - props, "dv_timing", obs_module_text("DVTiming"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *dv_timing_list = obs_properties_add_list(props, "dv_timing", obs_module_text("DVTiming"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_visible(dv_timing_list, false); - obs_property_t *resolution_list = obs_properties_add_list( - props, "resolution", obs_module_text("Resolution"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_t *resolution_list = obs_properties_add_list(props, "resolution", obs_module_text("Resolution"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_properties_add_list(props, "framerate", - obs_module_text("FrameRate"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_properties_add_list(props, "framerate", obs_module_text("FrameRate"), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); - obs_property_t *color_range_list = obs_properties_add_list( - props, "color_range", obs_module_text("ColorRange"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(color_range_list, - obs_module_text("ColorRange.Default"), - VIDEO_RANGE_DEFAULT); - obs_property_list_add_int(color_range_list, - obs_module_text("ColorRange.Partial"), - VIDEO_RANGE_PARTIAL); - obs_property_list_add_int(color_range_list, - obs_module_text("ColorRange.Full"), - VIDEO_RANGE_FULL); + obs_property_t *color_range_list = obs_properties_add_list(props, "color_range", obs_module_text("ColorRange"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(color_range_list, obs_module_text("ColorRange.Default"), VIDEO_RANGE_DEFAULT); + obs_property_list_add_int(color_range_list, obs_module_text("ColorRange.Partial"), VIDEO_RANGE_PARTIAL); + obs_property_list_add_int(color_range_list, obs_module_text("ColorRange.Full"), VIDEO_RANGE_FULL); - obs_properties_add_bool(props, "buffering", - obs_module_text("UseBuffering")); + obs_properties_add_bool(props, "buffering", obs_module_text("UseBuffering")); - obs_properties_add_bool(props, "auto_reset", - obs_module_text("AutoresetOnTimeout")); + obs_properties_add_bool(props, "auto_reset", obs_module_text("AutoresetOnTimeout")); - obs_properties_add_int(props, "timeout_frames", - obs_module_text("FramesUntilTimeout"), 2, 120, - 1); + obs_properties_add_int(props, "timeout_frames", obs_module_text("FramesUntilTimeout"), 2, 120, 1); // a group to contain the camera control obs_properties_t *ctrl_props = obs_properties_create(); - obs_properties_add_group(props, "controls", - obs_module_text("CameraCtrls"), - OBS_GROUP_NORMAL, ctrl_props); + obs_properties_add_group(props, "controls", obs_module_text("CameraCtrls"), OBS_GROUP_NORMAL, ctrl_props); obs_data_t *settings = obs_source_get_settings(data->source); v4l2_device_list(device_list, settings); @@ -909,8 +818,7 @@ static obs_properties_t *v4l2_properties(void *vptr) obs_property_set_modified_callback(device_list, device_selected); obs_property_set_modified_callback(input_list, input_selected); obs_property_set_modified_callback(format_list, format_selected); - obs_property_set_modified_callback(resolution_list, - resolution_selected); + obs_property_set_modified_callback(resolution_list, resolution_selected); return props; } @@ -924,8 +832,7 @@ static void v4l2_terminate(struct v4l2_data *data) data->thread = 0; } - if (data->pixfmt == V4L2_PIX_FMT_MJPEG || - data->pixfmt == V4L2_PIX_FMT_H264) { + if (data->pixfmt == V4L2_PIX_FMT_MJPEG || data->pixfmt == V4L2_PIX_FMT_H264) { v4l2_destroy_decoder(&data->decoder); } v4l2_destroy_mmap(&data->buffers); @@ -1013,13 +920,11 @@ static void v4l2_init(struct v4l2_data *data) } /* set pixel format and resolution */ - if (v4l2_set_format(data->dev, &data->resolution, &data->pixfmt, - &data->linesize) < 0) { + if (v4l2_set_format(data->dev, &data->resolution, &data->pixfmt, &data->linesize) < 0) { blog(LOG_ERROR, "Unable to set format"); goto fail; } - if (v4l2_to_obs_video_format(data->pixfmt) == VIDEO_FORMAT_NONE && - data->pixfmt != V4L2_PIX_FMT_MJPEG && + if (v4l2_to_obs_video_format(data->pixfmt) == VIDEO_FORMAT_NONE && data->pixfmt != V4L2_PIX_FMT_MJPEG && data->pixfmt != V4L2_PIX_FMT_H264) { blog(LOG_ERROR, "Selected video format not supported"); goto fail; @@ -1035,8 +940,7 @@ static void v4l2_init(struct v4l2_data *data) goto fail; } if (data->framerate == 0) { - blog(LOG_ERROR, "Framerate is not set, falling back to %i", - FALLBACK_FRAMERATE); + blog(LOG_ERROR, "Framerate is not set, falling back to %i", FALLBACK_FRAMERATE); data->framerate = v4l2_pack_tuple(1, FALLBACK_FRAMERATE); } v4l2_unpack_tuple(&fps_num, &fps_denom, data->framerate); @@ -1048,8 +952,7 @@ static void v4l2_init(struct v4l2_data *data) goto fail; } - if (data->pixfmt == V4L2_PIX_FMT_MJPEG || - data->pixfmt == V4L2_PIX_FMT_H264) { + if (data->pixfmt == V4L2_PIX_FMT_MJPEG || data->pixfmt == V4L2_PIX_FMT_H264) { if (v4l2_init_decoder(&data->decoder, data->pixfmt) < 0) { blog(LOG_ERROR, "Failed to initialize decoder"); goto fail; @@ -1068,11 +971,9 @@ fail: } /** Update source flags depending on the settings */ -static void v4l2_update_source_flags(struct v4l2_data *data, - obs_data_t *settings) +static void v4l2_update_source_flags(struct v4l2_data *data, obs_data_t *settings) { - obs_source_set_async_unbuffered( - data->source, !obs_data_get_bool(settings, "buffering")); + obs_source_set_async_unbuffered(data->source, !obs_data_get_bool(settings, "buffering")); } /** @@ -1083,47 +984,36 @@ static bool v4l2_settings_changed(struct v4l2_data *data, obs_data_t *settings) { bool res = false; - if (obs_data_get_string(settings, "device_id") != NULL && - data->device_id != NULL) { - res |= strcmp(data->device_id, - obs_data_get_string(settings, "device_id")) != 0; + if (obs_data_get_string(settings, "device_id") != NULL && data->device_id != NULL) { + res |= strcmp(data->device_id, obs_data_get_string(settings, "device_id")) != 0; res |= data->input != obs_data_get_int(settings, "input"); - res |= data->pixfmt != - obs_data_get_int(settings, "pixelformat"); + res |= data->pixfmt != obs_data_get_int(settings, "pixelformat"); res |= data->standard != obs_data_get_int(settings, "standard"); - res |= data->dv_timing != - obs_data_get_int(settings, "dv_timing"); + res |= data->dv_timing != obs_data_get_int(settings, "dv_timing"); - if (obs_data_get_int(settings, "resolution") == -1 && - !data->resolution_unchanged) { + if (obs_data_get_int(settings, "resolution") == -1 && !data->resolution_unchanged) { data->resolution_unchanged = true; res |= true; - } else if (obs_data_get_int(settings, "resolution") == -1 && - data->resolution_unchanged) { + } else if (obs_data_get_int(settings, "resolution") == -1 && data->resolution_unchanged) { res |= false; } else { data->resolution_unchanged = false; - res |= (data->resolution != - obs_data_get_int(settings, "resolution")) && + res |= (data->resolution != obs_data_get_int(settings, "resolution")) && (obs_data_get_int(settings, "resolution") != -1); } - if (obs_data_get_int(settings, "framerate") == -1 && - !data->framerate_unchanged) { + if (obs_data_get_int(settings, "framerate") == -1 && !data->framerate_unchanged) { data->framerate_unchanged = true; res |= true; - } else if (obs_data_get_int(settings, "framerate") == -1 && - data->framerate_unchanged) { + } else if (obs_data_get_int(settings, "framerate") == -1 && data->framerate_unchanged) { res |= false; } else { data->framerate_unchanged = false; - res |= (data->framerate != - obs_data_get_int(settings, "framerate")) && + res |= (data->framerate != obs_data_get_int(settings, "framerate")) && (obs_data_get_int(settings, "framerate") != -1); } - res |= data->color_range != - obs_data_get_int(settings, "color_range"); + res |= data->color_range != obs_data_get_int(settings, "color_range"); } else { res = true; } diff --git a/plugins/linux-v4l2/v4l2-output.c b/plugins/linux-v4l2/v4l2-output.c index 0d07d0d8a..366fc474f 100644 --- a/plugins/linux-v4l2/v4l2-output.c +++ b/plugins/linux-v4l2/v4l2-output.c @@ -103,8 +103,7 @@ static int loopback_module_load() static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) { - struct virtualcam_data *vcam = - (struct virtualcam_data *)bzalloc(sizeof(*vcam)); + struct virtualcam_data *vcam = (struct virtualcam_data *)bzalloc(sizeof(*vcam)); vcam->output = output; UNUSED_PARAMETER(settings); @@ -167,8 +166,7 @@ static bool try_connect(void *data, const char *device) parm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT; if (ioctl(vcam->device, VIDIOC_STREAMON, &parm) < 0) { - blog(LOG_ERROR, "Failed to start streaming on '%s' (%s)", - device, strerror(errno)); + blog(LOG_ERROR, "Failed to start streaming on '%s' (%s)", device, strerror(errno)); goto fail_close_device; } @@ -216,9 +214,8 @@ static bool virtualcam_start(void *data) // Use the return value of snprintf to prevent truncation warning. int written = snprintf(device, 32, "/dev/%s", list[i]->d_name); if (written >= 32) - blog(LOG_DEBUG, - "v4l2-output: A format truncation may have occurred." - " This can be ignored since it is quite improbable."); + blog(LOG_DEBUG, "v4l2-output: A format truncation may have occurred." + " This can be ignored since it is quite improbable."); if (try_connect(vcam, device)) { success = true; @@ -245,9 +242,7 @@ static void virtualcam_stop(void *data, uint64_t ts) parm.type = V4L2_BUF_TYPE_VIDEO_OUTPUT; if (ioctl(vcam->device, VIDIOC_STREAMOFF, &parm) < 0) { - blog(LOG_WARNING, - "Failed to stop streaming on video device %d (%s)", - vcam->device, strerror(errno)); + blog(LOG_WARNING, "Failed to stop streaming on video device %d (%s)", vcam->device, strerror(errno)); } close(vcam->device); @@ -261,8 +256,7 @@ static void virtual_video(void *param, struct video_data *frame) struct virtualcam_data *vcam = (struct virtualcam_data *)param; uint32_t frame_size = vcam->frame_size; while (frame_size > 0) { - ssize_t written = - write(vcam->device, frame->data[0], vcam->frame_size); + ssize_t written = write(vcam->device, frame->data[0], vcam->frame_size); if (written == -1) break; frame_size -= written; diff --git a/plugins/linux-v4l2/v4l2-udev.c b/plugins/linux-v4l2/v4l2-udev.c index 4ab6fa740..f8e699e14 100644 --- a/plugins/linux-v4l2/v4l2-udev.c +++ b/plugins/linux-v4l2/v4l2-udev.c @@ -27,15 +27,9 @@ along with this program. If not, see . #include "v4l2-udev.h" /** udev action enum */ -enum udev_action { - UDEV_ACTION_ADDED, - UDEV_ACTION_REMOVED, - UDEV_ACTION_UNKNOWN -}; +enum udev_action { UDEV_ACTION_ADDED, UDEV_ACTION_REMOVED, UDEV_ACTION_UNKNOWN }; -static const char *udev_signals[] = {"void device_added(string device)", - "void device_removed(string device)", - NULL}; +static const char *udev_signals[] = {"void device_added(string device)", "void device_removed(string device)", NULL}; /* global data */ static uint_fast32_t udev_refs = 0; @@ -88,12 +82,10 @@ static inline void udev_signal_event(struct udev_device *dev) switch (action) { case UDEV_ACTION_ADDED: - signal_handler_signal(udev_signalhandler, "device_added", - &data); + signal_handler_signal(udev_signalhandler, "device_added", &data); break; case UDEV_ACTION_REMOVED: - signal_handler_signal(udev_signalhandler, "device_removed", - &data); + signal_handler_signal(udev_signalhandler, "device_removed", &data); break; default: break; @@ -120,8 +112,7 @@ static void *udev_event_thread(void *vptr) os_set_thread_name("v4l2: udev"); udev = udev_new(); mon = udev_monitor_new_from_netlink(udev, "udev"); - udev_monitor_filter_add_match_subsystem_devtype(mon, "video4linux", - NULL); + udev_monitor_filter_add_match_subsystem_devtype(mon, "video4linux", NULL); if (udev_monitor_enable_receiving(mon) < 0) return NULL; @@ -168,8 +159,7 @@ void v4l2_init_udev(void) goto fail; if ((udev_event_fd = eventfd(0, EFD_CLOEXEC)) < 0) goto fail; - if (pthread_create(&udev_thread, NULL, udev_event_thread, - NULL) != 0) { + if (pthread_create(&udev_thread, NULL, udev_event_thread, NULL) != 0) { close(udev_event_fd); goto fail; } diff --git a/plugins/mac-avcapture/legacy/scope-guard.hpp b/plugins/mac-avcapture/legacy/scope-guard.hpp index 81dab6c9c..cb1dc4e95 100644 --- a/plugins/mac-avcapture/legacy/scope-guard.hpp +++ b/plugins/mac-avcapture/legacy/scope-guard.hpp @@ -16,9 +16,7 @@ public: explicit ScopeGuard(FunctionType &&fn) : function_(std::move(fn)) {} - ScopeGuard(ScopeGuard &&other) - : dismissed_(other.dismissed_), - function_(std::move(other.function_)) + ScopeGuard(ScopeGuard &&other) : dismissed_(other.dismissed_), function_(std::move(other.function_)) { other.dismissed_ = true; } @@ -38,12 +36,9 @@ private: FunctionType function_; }; -template -ScopeGuard::type> -make_guard(FunctionType &&fn) +template ScopeGuard::type> make_guard(FunctionType &&fn) { - return ScopeGuard::type>{ - std::forward(fn)}; + return ScopeGuard::type>{std::forward(fn)}; } namespace detail { @@ -51,11 +46,9 @@ namespace detail { enum class ScopeGuardOnExit {}; template -ScopeGuard::type> -operator+(detail::ScopeGuardOnExit, FunctionType &&fn) +ScopeGuard::type> operator+(detail::ScopeGuardOnExit, FunctionType &&fn) { - return ScopeGuard::type>( - std::forward(fn)); + return ScopeGuard::type>(std::forward(fn)); } } // namespace detail diff --git a/plugins/mac-capture/audio-device-enum.c b/plugins/mac-capture/audio-device-enum.c index 24f0edbca..8c6ce310b 100644 --- a/plugins/mac-capture/audio-device-enum.c +++ b/plugins/mac-capture/audio-device-enum.c @@ -9,32 +9,25 @@ * mark soundflower, wavtap and sound siphon as output devices. */ static inline bool device_is_input(char *device) { - return astrstri(device, "soundflower") == NULL && - astrstri(device, "wavtap") == NULL && - astrstri(device, "soundsiphon") == NULL && - astrstri(device, "ishowu") == NULL && - astrstri(device, "blackhole") == NULL && - astrstri(device, "loopback") == NULL && - astrstri(device, "groundcontrol") == NULL && - astrstri(device, "vbcable") == NULL; + return astrstri(device, "soundflower") == NULL && astrstri(device, "wavtap") == NULL && + astrstri(device, "soundsiphon") == NULL && astrstri(device, "ishowu") == NULL && + astrstri(device, "blackhole") == NULL && astrstri(device, "loopback") == NULL && + astrstri(device, "groundcontrol") == NULL && astrstri(device, "vbcable") == NULL; } static inline bool enum_success(OSStatus stat, const char *msg) { if (stat != noErr) { - blog(LOG_WARNING, "[coreaudio_enum_devices] %s failed: %d", msg, - (int)stat); + blog(LOG_WARNING, "[coreaudio_enum_devices] %s failed: %d", msg, (int)stat); return false; } return true; } -typedef bool (*enum_device_proc_t)(void *param, CFStringRef cf_name, - CFStringRef cf_uid, AudioDeviceID id); +typedef bool (*enum_device_proc_t)(void *param, CFStringRef cf_name, CFStringRef cf_uid, AudioDeviceID id); -static bool coreaudio_enum_device(enum_device_proc_t proc, void *param, - AudioDeviceID id) +static bool coreaudio_enum_device(enum_device_proc_t proc, void *param, AudioDeviceID id) { UInt32 size = 0; CFStringRef cf_name = NULL; @@ -42,8 +35,7 @@ static bool coreaudio_enum_device(enum_device_proc_t proc, void *param, bool enum_next = true; OSStatus stat; - AudioObjectPropertyAddress addr = {kAudioDevicePropertyStreams, - kAudioDevicePropertyScopeInput, + AudioObjectPropertyAddress addr = {kAudioDevicePropertyStreams, kAudioDevicePropertyScopeInput, kAudioObjectPropertyElementMain}; /* check to see if it's a mac input device */ @@ -75,8 +67,7 @@ fail: static void enum_devices(enum_device_proc_t proc, void *param) { - AudioObjectPropertyAddress addr = {kAudioHardwarePropertyDevices, - kAudioObjectPropertyScopeGlobal, + AudioObjectPropertyAddress addr = {kAudioHardwarePropertyDevices, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; UInt32 size = 0; @@ -84,16 +75,14 @@ static void enum_devices(enum_device_proc_t proc, void *param) OSStatus stat; AudioDeviceID *ids; - stat = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, - 0, NULL, &size); + stat = AudioObjectGetPropertyDataSize(kAudioObjectSystemObject, &addr, 0, NULL, &size); if (!enum_success(stat, "get kAudioObjectSystemObject data size")) return; ids = bmalloc(size); count = size / sizeof(AudioDeviceID); - stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, - NULL, &size, ids); + stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, 0, NULL, &size, ids); if (enum_success(stat, "get kAudioObjectSystemObject data")) for (UInt32 i = 0; i < count; i++) @@ -108,8 +97,7 @@ struct add_data { bool input; }; -static bool coreaudio_enum_add_device(void *param, CFStringRef cf_name, - CFStringRef cf_uid, AudioDeviceID id) +static bool coreaudio_enum_add_device(void *param, CFStringRef cf_name, CFStringRef cf_uid, AudioDeviceID id) { struct add_data *data = param; struct device_item item; @@ -139,17 +127,13 @@ void coreaudio_enum_devices(struct device_list *list, bool input) bool coreaudio_get_device_id(CFStringRef uid, AudioDeviceID *id) { - AudioObjectPropertyAddress propertyAddress = { - kAudioHardwarePropertyDeviceForUID, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMain}; + AudioObjectPropertyAddress propertyAddress = {kAudioHardwarePropertyDeviceForUID, + kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; - AudioValueTranslation translation = {&uid, sizeof(CFStringRef), id, - sizeof(AudioDeviceID)}; + AudioValueTranslation translation = {&uid, sizeof(CFStringRef), id, sizeof(AudioDeviceID)}; UInt32 size = sizeof(translation); - OSStatus result = AudioObjectGetPropertyData(kAudioObjectSystemObject, - &propertyAddress, 0, NULL, - &size, &translation); + OSStatus result = + AudioObjectGetPropertyData(kAudioObjectSystemObject, &propertyAddress, 0, NULL, &size, &translation); return result == noErr; } diff --git a/plugins/mac-capture/audio-device-enum.h b/plugins/mac-capture/audio-device-enum.h index 899684585..3e7174ca9 100644 --- a/plugins/mac-capture/audio-device-enum.h +++ b/plugins/mac-capture/audio-device-enum.h @@ -25,8 +25,7 @@ static inline void device_list_free(struct device_list *list) da_free(list->items); } -static inline void device_list_add(struct device_list *list, - struct device_item *item) +static inline void device_list_add(struct device_list *list, struct device_item *item) { da_push_back(list->items, item); memset(item, 0, sizeof(struct device_item)); diff --git a/plugins/mac-capture/mac-audio.c b/plugins/mac-capture/mac-audio.c index 05d30cadb..cc03c3bc2 100644 --- a/plugins/mac-capture/mac-audio.c +++ b/plugins/mac-capture/mac-audio.c @@ -85,9 +85,8 @@ static bool find_device_id_by_uid(struct coreaudio_data *ca) OSStatus stat; bool success; - AudioObjectPropertyAddress addr = { - .mScope = kAudioObjectPropertyScopeGlobal, - .mElement = kAudioObjectPropertyElementMain}; + AudioObjectPropertyAddress addr = {.mScope = kAudioObjectPropertyScopeGlobal, + .mElement = kAudioObjectPropertyElementMain}; if (!ca->device_uid) ca->device_uid = bstrdup("default"); @@ -107,14 +106,12 @@ static bool find_device_id_by_uid(struct coreaudio_data *ca) } } - cf_uid = CFStringCreateWithCString(NULL, ca->device_uid, - kCFStringEncodingUTF8); + cf_uid = CFStringCreateWithCString(NULL, ca->device_uid, kCFStringEncodingUTF8); if (ca->default_device) { addr.mSelector = kAudioHardwarePropertyDefaultInputDevice; - stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, - &addr, qual_size, &qual, - &size, &ca->device_id); + stat = AudioObjectGetPropertyData(kAudioObjectSystemObject, &addr, qual_size, &qual, &size, + &ca->device_id); success = (stat == noErr); } else { success = coreaudio_get_device_id(cf_uid, &ca->device_id); @@ -126,8 +123,7 @@ static bool find_device_id_by_uid(struct coreaudio_data *ca) return success; } -static inline void ca_warn(struct coreaudio_data *ca, const char *func, - const char *format, ...) +static inline void ca_warn(struct coreaudio_data *ca, const char *func, const char *format, ...) { va_list args; struct dstr str = {0}; @@ -142,12 +138,10 @@ static inline void ca_warn(struct coreaudio_data *ca, const char *func, va_end(args); } -static inline bool ca_success(OSStatus stat, struct coreaudio_data *ca, - const char *func, const char *action) +static inline bool ca_success(OSStatus stat, struct coreaudio_data *ca, const char *func, const char *action) { if (stat != noErr) { - blog(LOG_WARNING, "[%s]:[device '%s'] %s failed: %d", func, - ca->device_name, action, (int)stat); + blog(LOG_WARNING, "[%s]:[device '%s'] %s failed: %d", func, ca->device_name, action, (int)stat); return false; } @@ -159,15 +153,12 @@ enum coreaudio_io_type { IO_TYPE_OUTPUT, }; -static inline bool enable_io(struct coreaudio_data *ca, - enum coreaudio_io_type type, bool enable) +static inline bool enable_io(struct coreaudio_data *ca, enum coreaudio_io_type type, bool enable) { UInt32 enable_int = enable; return set_property(ca->unit, kAudioOutputUnitProperty_EnableIO, - (type == IO_TYPE_INPUT) ? SCOPE_INPUT - : SCOPE_OUTPUT, - (type == IO_TYPE_INPUT) ? BUS_INPUT : BUS_OUTPUT, - &enable_int, sizeof(enable_int)); + (type == IO_TYPE_INPUT) ? SCOPE_INPUT : SCOPE_OUTPUT, + (type == IO_TYPE_INPUT) ? BUS_INPUT : BUS_OUTPUT, &enable_int, sizeof(enable_int)); } static inline enum speaker_layout convert_ca_speaker_layout(UInt32 channels) @@ -191,8 +182,7 @@ static inline enum speaker_layout convert_ca_speaker_layout(UInt32 channels) return SPEAKERS_UNKNOWN; } -static inline enum audio_format convert_ca_format(UInt32 format_flags, - UInt32 bits) +static inline enum audio_format convert_ca_format(UInt32 format_flags, UInt32 bits) { bool planar = (format_flags & kAudioFormatFlagIsNonInterleaved) != 0; @@ -244,17 +234,14 @@ static char **coreaudio_get_channel_names(struct coreaudio_data *ca) pa.mSelector = kAudioObjectPropertyElementName; pa.mScope = kAudioDevicePropertyScopeInput; pa.mElement = i + 1; - OSStatus stat = AudioObjectGetPropertyData( - ca->device_id, &pa, 0, NULL, &dataSize, &cf_chan_name); + OSStatus stat = AudioObjectGetPropertyData(ca->device_id, &pa, 0, NULL, &dataSize, &cf_chan_name); struct dstr name; dstr_init(&name); - if (ca_success(stat, ca, "coreaudio_init_format", - "get channel names") && + if (ca_success(stat, ca, "coreaudio_init_format", "get channel names") && CFStringGetLength(cf_chan_name)) { - char *channelName = cfstr_copy_cstr( - cf_chan_name, kCFStringEncodingUTF8); + char *channelName = cfstr_copy_cstr(cf_chan_name, kCFStringEncodingUTF8); dstr_printf(&name, "%s", channelName); @@ -262,9 +249,7 @@ static char **coreaudio_get_channel_names(struct coreaudio_data *ca) bfree(channelName); } } else { - dstr_printf(&name, "%s %d", - obs_module_text("CoreAudio.Channel.Device"), - i + 1); + dstr_printf(&name, "%s %d", obs_module_text("CoreAudio.Channel.Device"), i + 1); } channel_names[i] = bstrdup_n(name.array, name.len); dstr_free(&name); @@ -291,15 +276,13 @@ static bool coreaudio_init_format(struct coreaudio_data *ca) uint32_t channels = get_audio_channels(ca->speakers); size = sizeof(inputDescription); - stat = get_property(ca->unit, kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Input, 1, &inputDescription, &size); + stat = get_property(ca->unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Input, 1, &inputDescription, + &size); - if (!ca_success(stat, ca, "coreaudio_init_format", - "get input device format")) + if (!ca_success(stat, ca, "coreaudio_init_format", "get input device format")) return false; - stat = get_property(ca->unit, kAudioUnitProperty_StreamFormat, - SCOPE_OUTPUT, BUS_INPUT, &desc, &size); + stat = get_property(ca->unit, kAudioUnitProperty_StreamFormat, SCOPE_OUTPUT, BUS_INPUT, &desc, &size); if (!ca_success(stat, ca, "coreaudio_init_format", "get input format")) return false; @@ -311,8 +294,7 @@ static bool coreaudio_init_format(struct coreaudio_data *ca) ca->channel_names = coreaudio_get_channel_names(ca); if (ca->enable_downmix) { - blog(LOG_INFO, "Downmix enabled: %d to %d channels.", - ca->available_channels, channels); + blog(LOG_INFO, "Downmix enabled: %d to %d channels.", ca->available_channels, channels); desc.mChannelsPerFrame = ca->available_channels; } else { // Mute any channels mapped in config that we don't really have @@ -321,24 +303,19 @@ static bool coreaudio_init_format(struct coreaudio_data *ca) dstr_init(&cm_str); for (size_t i = 0; i < channels; i++) { dstr_cat(&cm_str, sep); - if (ca->channel_map[i] >= - (int32_t)ca->available_channels) { + if (ca->channel_map[i] >= (int32_t)ca->available_channels) { ca->channel_map[i] = -1; } dstr_catf(&cm_str, "%d", ca->channel_map[i]); sep = ","; } - blog(LOG_INFO, - "Channel map enabled: [%s] (%d channels available)", - cm_str.array, ca->available_channels); + blog(LOG_INFO, "Channel map enabled: [%s] (%d channels available)", cm_str.array, + ca->available_channels); dstr_free(&cm_str); - stat = set_property(ca->unit, - kAudioOutputUnitProperty_ChannelMap, - SCOPE_OUTPUT, BUS_INPUT, ca->channel_map, - sizeof(SInt32) * channels); - if (!ca_success(stat, ca, "coreaudio_init_format", - "set channel map")) { + stat = set_property(ca->unit, kAudioOutputUnitProperty_ChannelMap, SCOPE_OUTPUT, BUS_INPUT, + ca->channel_map, sizeof(SInt32) * channels); + if (!ca_success(stat, ca, "coreaudio_init_format", "set channel map")) { return false; } @@ -347,8 +324,7 @@ static bool coreaudio_init_format(struct coreaudio_data *ca) desc.mSampleRate = inputDescription.mSampleRate; - stat = set_property(ca->unit, kAudioUnitProperty_StreamFormat, - SCOPE_OUTPUT, BUS_INPUT, &desc, size); + stat = set_property(ca->unit, kAudioUnitProperty_StreamFormat, SCOPE_OUTPUT, BUS_INPUT, &desc, size); if (!ca_success(stat, ca, "coreaudio_init_format", "set output format")) return false; @@ -362,8 +338,7 @@ static bool coreaudio_init_format(struct coreaudio_data *ca) ca_warn(ca, "coreaudio_init_format", "unknown format flags: " "%u, bits: %u", - (unsigned int)desc.mFormatFlags, - (unsigned int)desc.mBitsPerChannel); + (unsigned int)desc.mFormatFlags, (unsigned int)desc.mBitsPerChannel); return false; } @@ -380,13 +355,10 @@ static bool coreaudio_init_buffer(struct coreaudio_data *ca) OSStatus err = noErr; propertySize = sizeof(bufferSizeFrames); - err = AudioUnitGetProperty(ca->unit, - kAudioDevicePropertyBufferFrameSize, - kAudioUnitScope_Global, 0, &bufferSizeFrames, - &propertySize); + err = AudioUnitGetProperty(ca->unit, kAudioDevicePropertyBufferFrameSize, kAudioUnitScope_Global, 0, + &bufferSizeFrames, &propertySize); - if (!ca_success(err, ca, "coreaudio_init_buffer", - "get buffer frame size")) { + if (!ca_success(err, ca, "coreaudio_init_buffer", "get buffer frame size")) { return false; } @@ -394,43 +366,34 @@ static bool coreaudio_init_buffer(struct coreaudio_data *ca) AudioStreamBasicDescription streamDescription; propertySize = sizeof(streamDescription); - err = AudioUnitGetProperty(ca->unit, kAudioUnitProperty_StreamFormat, - kAudioUnitScope_Output, 1, + err = AudioUnitGetProperty(ca->unit, kAudioUnitProperty_StreamFormat, kAudioUnitScope_Output, 1, &streamDescription, &propertySize); - if (!ca_success(err, ca, "coreaudio_init_buffer", - "get stream format")) { + if (!ca_success(err, ca, "coreaudio_init_buffer", "get stream format")) { return false; } if (!ca->enable_downmix) { - streamDescription.mChannelsPerFrame = - get_audio_channels(ca->speakers); + streamDescription.mChannelsPerFrame = get_audio_channels(ca->speakers); } Float64 rate = 0.0; propertySize = sizeof(Float64); - AudioObjectPropertyAddress propertyAddress = { - kAudioDevicePropertyNominalSampleRate, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMain}; + AudioObjectPropertyAddress propertyAddress = {kAudioDevicePropertyNominalSampleRate, + kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; - err = AudioObjectGetPropertyData(ca->device_id, &propertyAddress, 0, - NULL, &propertySize, &rate); + err = AudioObjectGetPropertyData(ca->device_id, &propertyAddress, 0, NULL, &propertySize, &rate); - if (!ca_success(err, ca, "coreaudio_init_buffer", - "get input sample rate")) { + if (!ca_success(err, ca, "coreaudio_init_buffer", "get input sample rate")) { return false; } streamDescription.mSampleRate = rate; int bufferPropertySize = - offsetof(AudioBufferList, mBuffers[0]) + - (sizeof(AudioBuffer) * streamDescription.mChannelsPerFrame); + offsetof(AudioBufferList, mBuffers[0]) + (sizeof(AudioBuffer) * streamDescription.mChannelsPerFrame); - AudioBufferList *inputBuffer = - (AudioBufferList *)bmalloc(bufferPropertySize); + AudioBufferList *inputBuffer = (AudioBufferList *)bmalloc(bufferPropertySize); inputBuffer->mNumberBuffers = streamDescription.mChannelsPerFrame; for (UInt32 i = 0; i < inputBuffer->mNumberBuffers; i++) { @@ -453,17 +416,14 @@ static void buf_list_free(AudioBufferList *buf_list) } } -static OSStatus input_callback(void *data, - AudioUnitRenderActionFlags *action_flags, - const AudioTimeStamp *ts_data, UInt32 bus_num, - UInt32 frames, AudioBufferList *ignored_buffers) +static OSStatus input_callback(void *data, AudioUnitRenderActionFlags *action_flags, const AudioTimeStamp *ts_data, + UInt32 bus_num, UInt32 frames, AudioBufferList *ignored_buffers) { struct coreaudio_data *ca = data; OSStatus stat; struct obs_source_audio audio; - stat = AudioUnitRender(ca->unit, action_flags, ts_data, bus_num, frames, - ca->buf_list); + stat = AudioUnitRender(ca->unit, action_flags, ts_data, bus_num, frames, ca->buf_list); if (!ca_success(stat, ca, "input_callback", "audio retrieval")) return noErr; @@ -474,9 +434,8 @@ static OSStatus input_callback(void *data, } audio.frames = frames; - audio.speakers = (ca->buf_list->mNumberBuffers > MAX_AUDIO_CHANNELS) - ? MAX_AUDIO_CHANNELS - : ca->buf_list->mNumberBuffers; + audio.speakers = (ca->buf_list->mNumberBuffers > MAX_AUDIO_CHANNELS) ? MAX_AUDIO_CHANNELS + : ca->buf_list->mNumberBuffers; audio.format = ca->format; audio.samples_per_sec = ca->sample_rate; static double factor = 0.; @@ -506,8 +465,7 @@ static void *reconnect_thread(void *param) ca->reconnecting = true; - while (os_event_timedwait(ca->exit_event, ca->retry_time) == - ETIMEDOUT) { + while (os_event_timedwait(ca->exit_event, ca->retry_time) == ETIMEDOUT) { if (coreaudio_init(ca)) break; } @@ -532,9 +490,8 @@ static void coreaudio_begin_reconnect(struct coreaudio_data *ca) ret); } -static OSStatus -notification_callback(AudioObjectID id, UInt32 num_addresses, - const AudioObjectPropertyAddress addresses[], void *data) +static OSStatus notification_callback(AudioObjectID id, UInt32 num_addresses, + const AudioObjectPropertyAddress addresses[], void *data) { struct coreaudio_data *ca = data; @@ -561,47 +518,34 @@ notification_callback(AudioObjectID id, UInt32 num_addresses, static OSStatus add_listener(struct coreaudio_data *ca, UInt32 property) { - AudioObjectPropertyAddress addr = {property, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMain}; + AudioObjectPropertyAddress addr = {property, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; - return AudioObjectAddPropertyListener(ca->device_id, &addr, - notification_callback, ca); + return AudioObjectAddPropertyListener(ca->device_id, &addr, notification_callback, ca); } static bool coreaudio_init_hooks(struct coreaudio_data *ca) { OSStatus stat; - AURenderCallbackStruct callback_info = {.inputProc = input_callback, - .inputProcRefCon = ca}; + AURenderCallbackStruct callback_info = {.inputProc = input_callback, .inputProcRefCon = ca}; stat = add_listener(ca, kAudioDevicePropertyDeviceIsAlive); - if (!ca_success(stat, ca, "coreaudio_init_hooks", - "set disconnect callback")) + if (!ca_success(stat, ca, "coreaudio_init_hooks", "set disconnect callback")) return false; stat = add_listener(ca, PROPERTY_FORMATS); - if (!ca_success(stat, ca, "coreaudio_init_hooks", - "set format change callback")) + if (!ca_success(stat, ca, "coreaudio_init_hooks", "set format change callback")) return false; if (ca->default_device) { - AudioObjectPropertyAddress addr = { - PROPERTY_DEFAULT_DEVICE, - kAudioObjectPropertyScopeGlobal, - kAudioObjectPropertyElementMain}; + AudioObjectPropertyAddress addr = {PROPERTY_DEFAULT_DEVICE, kAudioObjectPropertyScopeGlobal, + kAudioObjectPropertyElementMain}; - stat = AudioObjectAddPropertyListener(kAudioObjectSystemObject, - &addr, - notification_callback, - ca); - if (!ca_success(stat, ca, "coreaudio_init_hooks", - "set device change callback")) + stat = AudioObjectAddPropertyListener(kAudioObjectSystemObject, &addr, notification_callback, ca); + if (!ca_success(stat, ca, "coreaudio_init_hooks", "set device change callback")) return false; } - stat = set_property(ca->unit, kAudioOutputUnitProperty_SetInputCallback, - SCOPE_GLOBAL, 0, &callback_info, + stat = set_property(ca->unit, kAudioOutputUnitProperty_SetInputCallback, SCOPE_GLOBAL, 0, &callback_info, sizeof(callback_info)); if (!ca_success(stat, ca, "coreaudio_init_hooks", "set input callback")) return false; @@ -611,29 +555,23 @@ static bool coreaudio_init_hooks(struct coreaudio_data *ca) static void coreaudio_remove_hooks(struct coreaudio_data *ca) { - AURenderCallbackStruct callback_info = {.inputProc = NULL, - .inputProcRefCon = NULL}; + AURenderCallbackStruct callback_info = {.inputProc = NULL, .inputProcRefCon = NULL}; - AudioObjectPropertyAddress addr = {kAudioDevicePropertyDeviceIsAlive, - kAudioObjectPropertyScopeGlobal, + AudioObjectPropertyAddress addr = {kAudioDevicePropertyDeviceIsAlive, kAudioObjectPropertyScopeGlobal, kAudioObjectPropertyElementMain}; - AudioObjectRemovePropertyListener(ca->device_id, &addr, - notification_callback, ca); + AudioObjectRemovePropertyListener(ca->device_id, &addr, notification_callback, ca); addr.mSelector = PROPERTY_FORMATS; - AudioObjectRemovePropertyListener(ca->device_id, &addr, - notification_callback, ca); + AudioObjectRemovePropertyListener(ca->device_id, &addr, notification_callback, ca); if (ca->default_device) { addr.mSelector = PROPERTY_DEFAULT_DEVICE; - AudioObjectRemovePropertyListener(kAudioObjectSystemObject, - &addr, notification_callback, - ca); + AudioObjectRemovePropertyListener(kAudioObjectSystemObject, &addr, notification_callback, ca); } - set_property(ca->unit, kAudioOutputUnitProperty_SetInputCallback, - SCOPE_GLOBAL, 0, &callback_info, sizeof(callback_info)); + set_property(ca->unit, kAudioOutputUnitProperty_SetInputCallback, SCOPE_GLOBAL, 0, &callback_info, + sizeof(callback_info)); } static bool coreaudio_get_device_name(struct coreaudio_data *ca) @@ -642,13 +580,10 @@ static bool coreaudio_get_device_name(struct coreaudio_data *ca) UInt32 size = sizeof(CFStringRef); char *name = NULL; - const AudioObjectPropertyAddress addr = { - kAudioDevicePropertyDeviceNameCFString, - kAudioObjectPropertyScopeInput, - kAudioObjectPropertyElementMain}; + const AudioObjectPropertyAddress addr = {kAudioDevicePropertyDeviceNameCFString, kAudioObjectPropertyScopeInput, + kAudioObjectPropertyElementMain}; - OSStatus stat = AudioObjectGetPropertyData(ca->device_id, &addr, 0, - NULL, &size, &cf_name); + OSStatus stat = AudioObjectGetPropertyData(ca->device_id, &addr, 0, NULL, &size, &cf_name); if (stat != noErr) { blog(LOG_WARNING, "[coreaudio_get_device_name] failed to " @@ -699,9 +634,8 @@ static void coreaudio_stop(struct coreaudio_data *ca) static bool coreaudio_init_unit(struct coreaudio_data *ca) { - AudioComponentDescription desc = { - .componentType = kAudioUnitType_Output, - .componentSubType = kAudioUnitSubType_HALOutput}; + AudioComponentDescription desc = {.componentType = kAudioUnitType_Output, + .componentSubType = kAudioUnitSubType_HALOutput}; AudioComponent component = AudioComponentFindNext(NULL, &desc); if (!component) { @@ -739,8 +673,7 @@ static bool coreaudio_init(struct coreaudio_data *ca) if (!ca_success(stat, ca, "coreaudio_init", "disable output io")) goto fail; - stat = set_property(ca->unit, kAudioOutputUnitProperty_CurrentDevice, - SCOPE_GLOBAL, 0, &ca->device_id, + stat = set_property(ca->unit, kAudioOutputUnitProperty_CurrentDevice, SCOPE_GLOBAL, 0, &ca->device_id, sizeof(ca->device_id)); if (!ca_success(stat, ca, "coreaudio_init", "set current device")) goto fail; @@ -759,8 +692,7 @@ static bool coreaudio_init(struct coreaudio_data *ca) if (!coreaudio_start(ca)) goto fail; - blog(LOG_INFO, "coreaudio: Device '%s' [%" PRIu32 " Hz] initialized", - ca->device_name, ca->sample_rate); + blog(LOG_INFO, "coreaudio: Device '%s' [%" PRIu32 " Hz] initialized", ca->device_name, ca->sample_rate); return ca->au_initialized; fail: @@ -866,20 +798,17 @@ static void coreaudio_destroy(void *data) } } -static void coreaudio_set_channels(struct coreaudio_data *ca, - obs_data_t *settings) +static void coreaudio_set_channels(struct coreaudio_data *ca, obs_data_t *settings) { ca->channel_map = bzalloc(sizeof(SInt32) * MAX_AUDIO_CHANNELS); char *device_config_name = sanitize_device_name(ca->device_uid); for (uint8_t i = 0; i < MAX_AUDIO_CHANNELS; i++) { char setting_name[128]; - snprintf(setting_name, 128, "output-%s-%i", device_config_name, - i + 1); - int64_t found = - obs_data_has_user_value(settings, setting_name) - ? obs_data_get_int(settings, setting_name) - : -1L; + snprintf(setting_name, 128, "output-%s-%i", device_config_name, i + 1); + int64_t found = obs_data_has_user_value(settings, setting_name) + ? obs_data_get_int(settings, setting_name) + : -1L; int64_t adjusted = found > 0 ? found - 1 : -1; ca->channel_map[i] = (int32_t)adjusted; } @@ -910,8 +839,7 @@ static void coreaudio_defaults(obs_data_t *settings) obs_data_set_default_bool(settings, "enable_downmix", true); } -static void *coreaudio_create(obs_data_t *settings, obs_source_t *source, - bool input) +static void *coreaudio_create(obs_data_t *settings, obs_source_t *source, bool input) { struct coreaudio_data *ca = bzalloc(sizeof(struct coreaudio_data)); @@ -940,55 +868,43 @@ static void *coreaudio_create(obs_data_t *settings, obs_source_t *source, return ca; } -static void *coreaudio_create_input_capture(obs_data_t *settings, - obs_source_t *source) +static void *coreaudio_create_input_capture(obs_data_t *settings, obs_source_t *source) { return coreaudio_create(settings, source, true); } -static void *coreaudio_create_output_capture(obs_data_t *settings, - obs_source_t *source) +static void *coreaudio_create_output_capture(obs_data_t *settings, obs_source_t *source) { return coreaudio_create(settings, source, false); } -static void coreaudio_fill_combo_with_inputs(const struct coreaudio_data *ca, - obs_property_t *input_combo, +static void coreaudio_fill_combo_with_inputs(const struct coreaudio_data *ca, obs_property_t *input_combo, uint32_t output_channel) { bool hasMutedChannel = false; obs_property_list_clear(input_combo); if (output_channel < ca->available_channels) { - obs_property_list_add_int(input_combo, - ca->channel_names[output_channel], - output_channel + 1); + obs_property_list_add_int(input_combo, ca->channel_names[output_channel], output_channel + 1); } else { - obs_property_list_add_int( - input_combo, obs_module_text("CoreAudio.None"), -1); + obs_property_list_add_int(input_combo, obs_module_text("CoreAudio.None"), -1); hasMutedChannel = true; } - for (uint32_t input_chan = 0; input_chan < ca->available_channels; - input_chan++) { + for (uint32_t input_chan = 0; input_chan < ca->available_channels; input_chan++) { if (input_chan != output_channel) { - obs_property_list_add_int(input_combo, - ca->channel_names[input_chan], - input_chan + 1); + obs_property_list_add_int(input_combo, ca->channel_names[input_chan], input_chan + 1); } } if (!hasMutedChannel) { - obs_property_list_add_int( - input_combo, obs_module_text("CoreAudio.None"), -1); + obs_property_list_add_int(input_combo, obs_module_text("CoreAudio.None"), -1); } } -static void ensure_output_channel_prop(const struct coreaudio_data *ca, - obs_properties_t *props, - const char *device_config_name, - uint32_t out_chan) +static void ensure_output_channel_prop(const struct coreaudio_data *ca, obs_properties_t *props, + const char *device_config_name, uint32_t out_chan) { struct dstr name; dstr_init(&name); @@ -1001,33 +917,27 @@ static void ensure_output_channel_prop(const struct coreaudio_data *ca, } else { struct dstr label; dstr_init(&label); - dstr_printf(&label, "%s %i", - obs_module_text("CoreAudio.Channel"), out_chan + 1); - obs_property_t *input_combo = obs_properties_add_list( - props, name.array, label.array, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + dstr_printf(&label, "%s %i", obs_module_text("CoreAudio.Channel"), out_chan + 1); + obs_property_t *input_combo = obs_properties_add_list(props, name.array, label.array, + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); dstr_free(&label); coreaudio_fill_combo_with_inputs(ca, input_combo, out_chan); } dstr_free(&name); } -static void ensure_output_channels_visible(obs_properties_t *props, - const struct coreaudio_data *ca, - uint32_t channels) +static void ensure_output_channels_visible(obs_properties_t *props, const struct coreaudio_data *ca, uint32_t channels) { char *device_config_name = sanitize_device_name(ca->device_uid); for (uint32_t out_chan = 0; out_chan < channels; out_chan++) { - ensure_output_channel_prop(ca, props, device_config_name, - out_chan); + ensure_output_channel_prop(ca, props, device_config_name, out_chan); } bfree(device_config_name); } static void hide_all_output_channels(obs_properties_t *props) { - for (obs_property_t *prop = obs_properties_first(props); prop != NULL; - obs_property_next(&prop)) { + for (obs_property_t *prop = obs_properties_first(props); prop != NULL; obs_property_next(&prop)) { const char *prop_name = obs_property_name(prop); if (strncmp("output-", prop_name, 7) == 0) { obs_property_set_visible(prop, false); @@ -1035,8 +945,7 @@ static void hide_all_output_channels(obs_properties_t *props) } } -static bool coreaudio_device_changed(void *data, obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) +static bool coreaudio_device_changed(void *data, obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { struct coreaudio_data *ca = data; if (ca != NULL) { @@ -1052,14 +961,12 @@ static bool coreaudio_device_changed(void *data, obs_properties_t *props, return true; } -static bool coreaudio_downmix_changed(void *data, obs_properties_t *props, - obs_property_t *p __unused, +static bool coreaudio_downmix_changed(void *data, obs_properties_t *props, obs_property_t *p __unused, obs_data_t *settings) { struct coreaudio_data *ca = data; if (ca != NULL) { - bool enable_downmix = - obs_data_get_bool(settings, "enable_downmix"); + bool enable_downmix = obs_data_get_bool(settings, "enable_downmix"); ca->enable_downmix = enable_downmix; hide_all_output_channels(props); @@ -1082,29 +989,23 @@ static obs_properties_t *coreaudio_properties(bool input, void *data) memset(&devices, 0, sizeof(struct device_list)); - property = obs_properties_add_list(props, "device_id", TEXT_DEVICE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + property = + obs_properties_add_list(props, "device_id", TEXT_DEVICE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); coreaudio_enum_devices(&devices, input); if (devices.items.num) - obs_property_list_add_string(property, TEXT_DEVICE_DEFAULT, - "default"); + obs_property_list_add_string(property, TEXT_DEVICE_DEFAULT, "default"); for (size_t i = 0; i < devices.items.num; i++) { struct device_item *item = devices.items.array + i; - obs_property_list_add_string(property, item->name.array, - item->value.array); + obs_property_list_add_string(property, item->name.array, item->value.array); } - obs_property_set_modified_callback2(property, coreaudio_device_changed, - ca); + obs_property_set_modified_callback2(property, coreaudio_device_changed, ca); - property = obs_properties_add_bool( - props, "enable_downmix", obs_module_text("CoreAudio.Downmix")); - obs_property_set_modified_callback2(property, coreaudio_downmix_changed, - ca); + property = obs_properties_add_bool(props, "enable_downmix", obs_module_text("CoreAudio.Downmix")); + obs_property_set_modified_callback2(property, coreaudio_downmix_changed, ca); if (ca != NULL) { uint32_t channels = get_audio_channels(ca->speakers); @@ -1145,8 +1046,7 @@ struct obs_source_info coreaudio_input_capture_info = { struct obs_source_info coreaudio_output_capture_info = { .id = "coreaudio_output_capture", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | - OBS_SOURCE_DO_NOT_SELF_MONITOR, + .output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_DO_NOT_SELF_MONITOR, .get_name = coreaudio_output_getname, .create = coreaudio_create_output_capture, .destroy = coreaudio_destroy, diff --git a/plugins/mac-capture/plugin-main.c b/plugins/mac-capture/plugin-main.c index fd28a5525..e82e034f6 100644 --- a/plugins/mac-capture/plugin-main.c +++ b/plugins/mac-capture/plugin-main.c @@ -20,12 +20,9 @@ bool obs_module_load(void) extern struct obs_source_info sck_video_capture_info; obs_register_source(&sck_video_capture_info); if (__builtin_available(macOS 13.0, *)) { - display_capture_info.output_flags |= - OBS_SOURCE_DEPRECATED; - window_capture_info.output_flags |= - OBS_SOURCE_DEPRECATED; - coreaudio_output_capture_info.output_flags |= - OBS_SOURCE_DEPRECATED; + display_capture_info.output_flags |= OBS_SOURCE_DEPRECATED; + window_capture_info.output_flags |= OBS_SOURCE_DEPRECATED; + coreaudio_output_capture_info.output_flags |= OBS_SOURCE_DEPRECATED; extern struct obs_source_info sck_audio_capture_info; obs_register_source(&sck_audio_capture_info); } diff --git a/plugins/mac-videotoolbox/encoder.c b/plugins/mac-videotoolbox/encoder.c index 9603634a0..bad9043fe 100644 --- a/plugins/mac-videotoolbox/encoder.c +++ b/plugins/mac-videotoolbox/encoder.c @@ -12,15 +12,11 @@ #include -#define VT_LOG(level, format, ...) \ - blog(level, "[VideoToolbox encoder]: " format, ##__VA_ARGS__) -#define VT_LOG_ENCODER(encoder, codec_type, level, format, ...) \ - blog(level, "[VideoToolbox %s: '%s']: " format, \ - obs_encoder_get_name(encoder), \ +#define VT_LOG(level, format, ...) blog(level, "[VideoToolbox encoder]: " format, ##__VA_ARGS__) +#define VT_LOG_ENCODER(encoder, codec_type, level, format, ...) \ + blog(level, "[VideoToolbox %s: '%s']: " format, obs_encoder_get_name(encoder), \ codec_type_to_print_fmt(codec_type), ##__VA_ARGS__) -#define VT_BLOG(level, format, ...) \ - VT_LOG_ENCODER(enc->encoder, enc->codec_type, level, format, \ - ##__VA_ARGS__) +#define VT_BLOG(level, format, ...) VT_LOG_ENCODER(enc->encoder, enc->codec_type, level, format, ##__VA_ARGS__) struct vt_encoder_type_data { const char *disp_name; @@ -95,12 +91,10 @@ static const char *codec_type_to_print_fmt(CMVideoCodecType codec_type) } } -static void log_osstatus(int log_level, struct vt_encoder *enc, - const char *context, OSStatus code) +static void log_osstatus(int log_level, struct vt_encoder *enc, const char *context, OSStatus code) { char *c_str = NULL; - CFErrorRef err = CFErrorCreate(kCFAllocatorDefault, - kCFErrorDomainOSStatus, code, NULL); + CFErrorRef err = CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, code, NULL); CFStringRef str = CFErrorCopyDescription(err); c_str = cfstr_copy_cstr(str, kCFStringEncodingUTF8); @@ -116,9 +110,7 @@ static void log_osstatus(int log_level, struct vt_encoder *enc, CFRelease(err); } -static CFStringRef obs_to_vt_profile(CMVideoCodecType codec_type, - const char *profile, - enum video_format format) +static CFStringRef obs_to_vt_profile(CMVideoCodecType codec_type, const char *profile, enum video_format format) { if (codec_type == kCMVideoCodecType_H264) { if (strcmp(profile, "baseline") == 0) @@ -203,8 +195,7 @@ static CFDataRef obs_to_vt_masteringdisplay(uint32_t hdr_nominal_peak_level) uint32_t max_display_mastering_luminance; uint32_t min_display_mastering_luminance; }; - static_assert(sizeof(struct mastering_display_colour_volume) == 24, - "May need to adjust struct packing"); + static_assert(sizeof(struct mastering_display_colour_volume) == 24, "May need to adjust struct packing"); struct mastering_display_colour_volume mdcv; mdcv.display_primaries[0][0] = __builtin_bswap16(13250); @@ -215,8 +206,7 @@ static CFDataRef obs_to_vt_masteringdisplay(uint32_t hdr_nominal_peak_level) mdcv.display_primaries[2][1] = __builtin_bswap16(16000); mdcv.white_point[0] = __builtin_bswap16(15635); mdcv.white_point[1] = __builtin_bswap16(16450); - mdcv.max_display_mastering_luminance = - __builtin_bswap32(hdr_nominal_peak_level * 10000); + mdcv.max_display_mastering_luminance = __builtin_bswap32(hdr_nominal_peak_level * 10000); mdcv.min_display_mastering_luminance = 0; UInt8 bytes[sizeof(struct mastering_display_colour_volume)]; @@ -225,29 +215,24 @@ static CFDataRef obs_to_vt_masteringdisplay(uint32_t hdr_nominal_peak_level) } /* Adapted from Chromium GenerateContentLightLevelInfo */ -static CFDataRef -obs_to_vt_contentlightlevelinfo(uint16_t hdr_nominal_peak_level) +static CFDataRef obs_to_vt_contentlightlevelinfo(uint16_t hdr_nominal_peak_level) { struct content_light_level_info { uint16_t max_content_light_level; uint16_t max_pic_average_light_level; }; - static_assert(sizeof(struct content_light_level_info) == 4, - "May need to adjust struct packing"); + static_assert(sizeof(struct content_light_level_info) == 4, "May need to adjust struct packing"); struct content_light_level_info clli; - clli.max_content_light_level = - __builtin_bswap16(hdr_nominal_peak_level); - clli.max_pic_average_light_level = - __builtin_bswap16(hdr_nominal_peak_level); + clli.max_content_light_level = __builtin_bswap16(hdr_nominal_peak_level); + clli.max_pic_average_light_level = __builtin_bswap16(hdr_nominal_peak_level); UInt8 bytes[sizeof(struct content_light_level_info)]; memcpy(bytes, &clli, sizeof(bytes)); return CFDataCreate(kCFAllocatorDefault, bytes, sizeof(bytes)); } -static OSStatus session_set_prop_float(VTCompressionSessionRef session, - CFStringRef key, float val) +static OSStatus session_set_prop_float(VTCompressionSessionRef session, CFStringRef key, float val) { CFNumberRef n = CFNumberCreate(NULL, kCFNumberFloat32Type, &val); OSStatus code = VTSessionSetProperty(session, key, n); @@ -256,8 +241,7 @@ static OSStatus session_set_prop_float(VTCompressionSessionRef session, return code; } -static OSStatus session_set_prop_int(VTCompressionSessionRef session, - CFStringRef key, int32_t val) +static OSStatus session_set_prop_int(VTCompressionSessionRef session, CFStringRef key, int32_t val) { CFNumberRef n = CFNumberCreate(NULL, kCFNumberSInt32Type, &val); OSStatus code = VTSessionSetProperty(session, key, n); @@ -266,8 +250,7 @@ static OSStatus session_set_prop_int(VTCompressionSessionRef session, return code; } -static OSStatus session_set_prop_str(VTCompressionSessionRef session, - CFStringRef key, char *val) +static OSStatus session_set_prop_str(VTCompressionSessionRef session, CFStringRef key, char *val) { CFStringRef s = CFStringCreateWithFileSystemRepresentation(NULL, val); OSStatus code = VTSessionSetProperty(session, key, s); @@ -276,16 +259,13 @@ static OSStatus session_set_prop_str(VTCompressionSessionRef session, return code; } -static OSStatus session_set_prop(VTCompressionSessionRef session, - CFStringRef key, CFTypeRef val) +static OSStatus session_set_prop(VTCompressionSessionRef session, CFStringRef key, CFTypeRef val) { return VTSessionSetProperty(session, key, val); } -static OSStatus session_set_bitrate(VTCompressionSessionRef session, - const char *rate_control, int new_bitrate, - float quality, bool limit_bitrate, - int max_bitrate, double max_bitrate_window) +static OSStatus session_set_bitrate(VTCompressionSessionRef session, const char *rate_control, int new_bitrate, + float quality, bool limit_bitrate, int max_bitrate, double max_bitrate_window) { OSStatus code; @@ -293,56 +273,44 @@ static OSStatus session_set_bitrate(VTCompressionSessionRef session, CFStringRef compressionPropertyKey; if (strcmp(rate_control, "CBR") == 0) { - compressionPropertyKey = - kVTCompressionPropertyKey_AverageBitRate; + compressionPropertyKey = kVTCompressionPropertyKey_AverageBitRate; can_limit_bitrate = true; if (__builtin_available(macOS 13.0, *)) { if (is_apple_silicon) { - compressionPropertyKey = - kVTCompressionPropertyKey_ConstantBitRate; + compressionPropertyKey = kVTCompressionPropertyKey_ConstantBitRate; can_limit_bitrate = false; } else { - VT_LOG(LOG_WARNING, - "CBR support for VideoToolbox encoder requires Apple Silicon. " - "Will use ABR instead."); + VT_LOG(LOG_WARNING, "CBR support for VideoToolbox encoder requires Apple Silicon. " + "Will use ABR instead."); } } else { - VT_LOG(LOG_WARNING, - "CBR support for VideoToolbox encoder requires macOS 13 or newer. " - "Will use ABR instead."); + VT_LOG(LOG_WARNING, "CBR support for VideoToolbox encoder requires macOS 13 or newer. " + "Will use ABR instead."); } } else if (strcmp(rate_control, "ABR") == 0) { - compressionPropertyKey = - kVTCompressionPropertyKey_AverageBitRate; + compressionPropertyKey = kVTCompressionPropertyKey_AverageBitRate; can_limit_bitrate = true; } else if (strcmp(rate_control, "CRF") == 0) { if (is_apple_silicon) { - compressionPropertyKey = - kVTCompressionPropertyKey_Quality; - code = session_set_prop_float( - session, compressionPropertyKey, quality); + compressionPropertyKey = kVTCompressionPropertyKey_Quality; + code = session_set_prop_float(session, compressionPropertyKey, quality); if (code != noErr) { return code; } } else { - VT_LOG(LOG_WARNING, - "CRF support for VideoToolbox encoder requires Apple Silicon. " - "Will use ABR instead."); - compressionPropertyKey = - kVTCompressionPropertyKey_AverageBitRate; + VT_LOG(LOG_WARNING, "CRF support for VideoToolbox encoder requires Apple Silicon. " + "Will use ABR instead."); + compressionPropertyKey = kVTCompressionPropertyKey_AverageBitRate; } can_limit_bitrate = true; } else { - VT_LOG(LOG_ERROR, - "Selected rate control method is not supported: %s", - rate_control); + VT_LOG(LOG_ERROR, "Selected rate control method is not supported: %s", rate_control); return kVTParameterErr; } if (compressionPropertyKey != kVTCompressionPropertyKey_Quality) { - code = session_set_prop_int(session, compressionPropertyKey, - new_bitrate * 1000); + code = session_set_prop_int(session, compressionPropertyKey, new_bitrate * 1000); if (code != noErr) { return code; } @@ -351,28 +319,22 @@ static OSStatus session_set_bitrate(VTCompressionSessionRef session, if (limit_bitrate && can_limit_bitrate) { double cpb_size = max_bitrate * 125 * max_bitrate_window; - CFNumberRef cf_cpb_size = CFNumberCreate( - kCFAllocatorDefault, kCFNumberIntType, &cpb_size); + CFNumberRef cf_cpb_size = CFNumberCreate(kCFAllocatorDefault, kCFNumberIntType, &cpb_size); CFNumberRef cf_cpb_window_size = - CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, - &max_bitrate_window); + CFNumberCreate(kCFAllocatorDefault, kCFNumberFloatType, &max_bitrate_window); CFTypeRef values[2] = {cf_cpb_size, cf_cpb_window_size}; - CFArrayRef rate_control_data = CFArrayCreate( - kCFAllocatorDefault, values, 2, &kCFTypeArrayCallBacks); + CFArrayRef rate_control_data = CFArrayCreate(kCFAllocatorDefault, values, 2, &kCFTypeArrayCallBacks); - code = session_set_prop( - session, kVTCompressionPropertyKey_DataRateLimits, - rate_control_data); + code = session_set_prop(session, kVTCompressionPropertyKey_DataRateLimits, rate_control_data); CFRelease(cf_cpb_size); CFRelease(cf_cpb_window_size); CFRelease(rate_control_data); if (code == kVTPropertyNotSupportedErr) { - log_osstatus(LOG_WARNING, NULL, - "setting DataRateLimits on session", code); + log_osstatus(LOG_WARNING, NULL, "setting DataRateLimits on session", code); return noErr; } } @@ -380,29 +342,23 @@ static OSStatus session_set_bitrate(VTCompressionSessionRef session, return noErr; } -static OSStatus session_set_colorspace(VTCompressionSessionRef session, - enum video_colorspace cs) +static OSStatus session_set_colorspace(VTCompressionSessionRef session, enum video_colorspace cs) { OSStatus code; - CFTypeRef keys[5] = {kVTCompressionPropertyKey_ColorPrimaries, - kVTCompressionPropertyKey_TransferFunction, + CFTypeRef keys[5] = {kVTCompressionPropertyKey_ColorPrimaries, kVTCompressionPropertyKey_TransferFunction, kVTCompressionPropertyKey_YCbCrMatrix, NULL, NULL}; - CFTypeRef values[5] = {obs_to_vt_primaries(cs), obs_to_vt_transfer(cs), - obs_to_vt_colorspace(cs), NULL, NULL}; + CFTypeRef values[5] = {obs_to_vt_primaries(cs), obs_to_vt_transfer(cs), obs_to_vt_colorspace(cs), NULL, NULL}; CFDataRef masteringDisplayColorVolume = NULL; CFDataRef contentLightLevel = NULL; if (cs == VIDEO_CS_2100_PQ) { - const uint16_t hdr_nominal_peak_level = - (uint16_t)obs_get_video_hdr_nominal_peak_level(); + const uint16_t hdr_nominal_peak_level = (uint16_t)obs_get_video_hdr_nominal_peak_level(); - masteringDisplayColorVolume = - obs_to_vt_masteringdisplay(hdr_nominal_peak_level); - contentLightLevel = - obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level); + masteringDisplayColorVolume = obs_to_vt_masteringdisplay(hdr_nominal_peak_level); + contentLightLevel = obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level); keys[3] = kVTCompressionPropertyKey_MasteringDisplayColorVolume; keys[4] = kVTCompressionPropertyKey_ContentLightLevelInfo; @@ -418,10 +374,8 @@ static OSStatus session_set_colorspace(VTCompressionSessionRef session, values[4] = contentLightLevel; } - CFDictionaryRef session_properties = - CFDictionaryCreate(kCFAllocatorDefault, keys, values, 5, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef session_properties = CFDictionaryCreate( + kCFAllocatorDefault, keys, values, 5, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); code = VTSessionSetProperties(session, session_properties); @@ -438,8 +392,7 @@ static OSStatus session_set_colorspace(VTCompressionSessionRef session, return code; } -void sample_encoded_callback(void *data, void *source, OSStatus status, - VTEncodeInfoFlags info_flags, +void sample_encoded_callback(void *data, void *source, OSStatus status, VTEncodeInfoFlags info_flags, CMSampleBufferRef buffer) { @@ -463,25 +416,20 @@ void sample_encoded_callback(void *data, void *source, OSStatus status, static inline CFDictionaryRef create_encoder_spec(const char *vt_encoder_id) { - CFStringRef id = - CFStringCreateWithFileSystemRepresentation(NULL, vt_encoder_id); + CFStringRef id = CFStringCreateWithFileSystemRepresentation(NULL, vt_encoder_id); CFTypeRef keys[1] = {kVTVideoEncoderSpecification_EncoderID}; CFTypeRef values[1] = {id}; - CFDictionaryRef encoder_spec = - CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef encoder_spec = CFDictionaryCreate( + kCFAllocatorDefault, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(id); return encoder_spec; } -static inline CFDictionaryRef -create_prores_encoder_spec(CMVideoCodecType target_codec_type, - bool hardware_accelerated) +static inline CFDictionaryRef create_prores_encoder_spec(CMVideoCodecType target_codec_type, bool hardware_accelerated) { CFStringRef encoder_id = NULL; @@ -504,31 +452,23 @@ create_prores_encoder_spec(CMVideoCodecType target_codec_type, CFTypeRef keys[1] = {kVTVideoEncoderSpecification_EncoderID}; CFTypeRef values[1] = {encoder_id}; - CFDictionaryRef encoder_spec = - CFDictionaryCreate(kCFAllocatorDefault, keys, values, 1, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef encoder_spec = CFDictionaryCreate( + kCFAllocatorDefault, keys, values, 1, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); return encoder_spec; } static inline CFDictionaryRef create_pixbuf_spec(struct vt_encoder *enc) { - CFNumberRef PixelFormat = CFNumberCreate( - kCFAllocatorDefault, kCFNumberSInt32Type, &enc->vt_pix_fmt); - CFNumberRef Width = CFNumberCreate(kCFAllocatorDefault, - kCFNumberSInt32Type, &enc->width); - CFNumberRef Height = CFNumberCreate(kCFAllocatorDefault, - kCFNumberSInt32Type, &enc->height); + CFNumberRef PixelFormat = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &enc->vt_pix_fmt); + CFNumberRef Width = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &enc->width); + CFNumberRef Height = CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &enc->height); - CFTypeRef keys[3] = {kCVPixelBufferPixelFormatTypeKey, - kCVPixelBufferWidthKey, kCVPixelBufferHeightKey}; + CFTypeRef keys[3] = {kCVPixelBufferPixelFormatTypeKey, kCVPixelBufferWidthKey, kCVPixelBufferHeightKey}; CFTypeRef values[3] = {PixelFormat, Width, Height}; - CFDictionaryRef pixbuf_spec = - CFDictionaryCreate(kCFAllocatorDefault, keys, values, 3, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef pixbuf_spec = CFDictionaryCreate( + kCFAllocatorDefault, keys, values, 3, &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); CFRelease(PixelFormat); CFRelease(Width); @@ -548,35 +488,26 @@ static OSStatus create_encoder(struct vt_encoder *enc) CFDictionaryRef encoder_spec; if (strcmp(codec_name, "prores") == 0) { struct vt_encoder_type_data *type_data = - (struct vt_encoder_type_data *) - obs_encoder_get_type_data(enc->encoder); - encoder_spec = create_prores_encoder_spec( - enc->codec_type, type_data->hardware_accelerated); + (struct vt_encoder_type_data *)obs_encoder_get_type_data(enc->encoder); + encoder_spec = create_prores_encoder_spec(enc->codec_type, type_data->hardware_accelerated); } else { encoder_spec = create_encoder_spec(enc->vt_encoder_id); } CFDictionaryRef pixbuf_spec = create_pixbuf_spec(enc); - code = VTCompressionSessionCreate(kCFAllocatorDefault, enc->width, - enc->height, enc->codec_type, - encoder_spec, pixbuf_spec, NULL, - &sample_encoded_callback, enc->queue, - &s); + code = VTCompressionSessionCreate(kCFAllocatorDefault, enc->width, enc->height, enc->codec_type, encoder_spec, + pixbuf_spec, NULL, &sample_encoded_callback, enc->queue, &s); if (code != noErr) { - log_osstatus(LOG_ERROR, enc, "VTCompressionSessionCreate", - code); + log_osstatus(LOG_ERROR, enc, "VTCompressionSessionCreate", code); } CFRelease(encoder_spec); CFRelease(pixbuf_spec); CFBooleanRef b = NULL; - code = VTSessionCopyProperty( - s, - kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder, - NULL, &b); + code = VTSessionCopyProperty(s, kVTCompressionPropertyKey_UsingHardwareAcceleratedVideoEncoder, NULL, &b); if (code == noErr && (enc->hw_enc = CFBooleanGetValue(b))) VT_BLOG(LOG_INFO, "session created with hardware encoding"); @@ -586,54 +517,38 @@ static OSStatus create_encoder(struct vt_encoder *enc) if (b != NULL) CFRelease(b); - if (enc->codec_type == kCMVideoCodecType_H264 || - enc->codec_type == kCMVideoCodecType_HEVC) { + if (enc->codec_type == kCMVideoCodecType_H264 || enc->codec_type == kCMVideoCodecType_HEVC) { // This can fail when using GPU hardware encoding - code = session_set_prop_int( - s, - kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, - enc->keyint); + code = session_set_prop_int(s, kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration, enc->keyint); if (code != noErr) - log_osstatus( - LOG_WARNING, enc, - "setting kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration failed, " - "keyframe interval might be incorrect", - code); + log_osstatus(LOG_WARNING, enc, + "setting kVTCompressionPropertyKey_MaxKeyFrameIntervalDuration failed, " + "keyframe interval might be incorrect", + code); - CFTypeRef session_keys[4] = { - kVTCompressionPropertyKey_MaxKeyFrameInterval, - kVTCompressionPropertyKey_ExpectedFrameRate, - kVTCompressionPropertyKey_AllowFrameReordering, - kVTCompressionPropertyKey_ProfileLevel}; + CFTypeRef session_keys[4] = {kVTCompressionPropertyKey_MaxKeyFrameInterval, + kVTCompressionPropertyKey_ExpectedFrameRate, + kVTCompressionPropertyKey_AllowFrameReordering, + kVTCompressionPropertyKey_ProfileLevel}; - SInt32 key_frame_interval = - (SInt32)(enc->keyint * - ((float)enc->fps_num / enc->fps_den)); + SInt32 key_frame_interval = (SInt32)(enc->keyint * ((float)enc->fps_num / enc->fps_den)); float expected_framerate = (float)enc->fps_num / enc->fps_den; CFNumberRef MaxKeyFrameInterval = - CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, - &key_frame_interval); - CFNumberRef ExpectedFrameRate = CFNumberCreate( - kCFAllocatorDefault, kCFNumberFloat32Type, - &expected_framerate); - CFTypeRef AllowFrameReordering = enc->bframes ? kCFBooleanTrue - : kCFBooleanFalse; + CFNumberCreate(kCFAllocatorDefault, kCFNumberSInt32Type, &key_frame_interval); + CFNumberRef ExpectedFrameRate = + CFNumberCreate(kCFAllocatorDefault, kCFNumberFloat32Type, &expected_framerate); + CFTypeRef AllowFrameReordering = enc->bframes ? kCFBooleanTrue : kCFBooleanFalse; video_t *video = obs_encoder_video(enc->encoder); - const struct video_output_info *voi = - video_output_get_info(video); - CFTypeRef ProfileLevel = obs_to_vt_profile( - enc->codec_type, enc->profile, voi->format); + const struct video_output_info *voi = video_output_get_info(video); + CFTypeRef ProfileLevel = obs_to_vt_profile(enc->codec_type, enc->profile, voi->format); - CFTypeRef session_values[4] = {MaxKeyFrameInterval, - ExpectedFrameRate, - AllowFrameReordering, + CFTypeRef session_values[4] = {MaxKeyFrameInterval, ExpectedFrameRate, AllowFrameReordering, ProfileLevel}; - CFDictionaryRef session_properties = CFDictionaryCreate( - kCFAllocatorDefault, session_keys, session_values, 4, - &kCFTypeDictionaryKeyCallBacks, - &kCFTypeDictionaryValueCallBacks); + CFDictionaryRef session_properties = + CFDictionaryCreate(kCFAllocatorDefault, session_keys, session_values, 4, + &kCFTypeDictionaryKeyCallBacks, &kCFTypeDictionaryValueCallBacks); code = VTSessionSetProperties(s, session_properties); @@ -647,24 +562,20 @@ static OSStatus create_encoder(struct vt_encoder *enc) return code; } - code = session_set_bitrate(s, enc->rate_control, enc->bitrate, - enc->quality, enc->limit_bitrate, - enc->rc_max_bitrate, - enc->rc_max_bitrate_window); + code = session_set_bitrate(s, enc->rate_control, enc->bitrate, enc->quality, enc->limit_bitrate, + enc->rc_max_bitrate, enc->rc_max_bitrate_window); if (code != noErr) { return code; } } // This can fail depending on hardware configuration - code = session_set_prop(s, kVTCompressionPropertyKey_RealTime, - kCFBooleanFalse); + code = session_set_prop(s, kVTCompressionPropertyKey_RealTime, kCFBooleanFalse); if (code != noErr) - log_osstatus( - LOG_WARNING, enc, - "setting kVTCompressionPropertyKey_RealTime failed, " - "frame delay might be increased", - code); + log_osstatus(LOG_WARNING, enc, + "setting kVTCompressionPropertyKey_RealTime failed, " + "frame delay might be increased", + code); code = session_set_colorspace(s, enc->colorspace); if (code != noErr) { @@ -715,13 +626,10 @@ static void dump_encoder_info(struct vt_encoder *enc) "\thw_enc: %s\n" "\tprofile: %s\n" "\tcodec_type: %.4s\n", - enc->vt_encoder_id, enc->rate_control, enc->bitrate, - enc->quality, enc->fps_num, enc->fps_den, enc->width, - enc->height, enc->keyint, enc->limit_bitrate ? "on" : "off", - enc->rc_max_bitrate, enc->rc_max_bitrate_window, - enc->hw_enc ? "on" : "off", - (enc->profile != NULL && !!strlen(enc->profile)) ? enc->profile - : "default", + enc->vt_encoder_id, enc->rate_control, enc->bitrate, enc->quality, enc->fps_num, enc->fps_den, + enc->width, enc->height, enc->keyint, enc->limit_bitrate ? "on" : "off", enc->rc_max_bitrate, + enc->rc_max_bitrate_window, enc->hw_enc ? "on" : "off", + (enc->profile != NULL && !!strlen(enc->profile)) ? enc->profile : "default", codec_type_to_print_fmt(enc->codec_type)); } @@ -731,37 +639,29 @@ typedef enum { kResultFullRangeUnsupported = 2, } SetVideoFormatResult; -static SetVideoFormatResult set_video_format(struct vt_encoder *enc, - enum video_format format, +static SetVideoFormatResult set_video_format(struct vt_encoder *enc, enum video_format format, enum video_range_type range) { bool full_range = range == VIDEO_RANGE_FULL; switch (format) { case VIDEO_FORMAT_I420: - enc->vt_pix_fmt = - full_range - ? kCVPixelFormatType_420YpCbCr8PlanarFullRange - : kCVPixelFormatType_420YpCbCr8Planar; + enc->vt_pix_fmt = full_range ? kCVPixelFormatType_420YpCbCr8PlanarFullRange + : kCVPixelFormatType_420YpCbCr8Planar; return kResultSuccess; case VIDEO_FORMAT_NV12: - enc->vt_pix_fmt = - full_range - ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange - : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; + enc->vt_pix_fmt = full_range ? kCVPixelFormatType_420YpCbCr8BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange; return kResultSuccess; case VIDEO_FORMAT_P010: if (enc->codec_type == kCMVideoCodecType_HEVC) { - enc->vt_pix_fmt = - full_range - ? kCVPixelFormatType_420YpCbCr10BiPlanarFullRange - : kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange; + enc->vt_pix_fmt = full_range ? kCVPixelFormatType_420YpCbCr10BiPlanarFullRange + : kCVPixelFormatType_420YpCbCr10BiPlanarVideoRange; return kResultSuccess; } break; case VIDEO_FORMAT_P216: if (!full_range) { - enc->vt_pix_fmt = - kCVPixelFormatType_422YpCbCr16BiPlanarVideoRange; + enc->vt_pix_fmt = kCVPixelFormatType_422YpCbCr16BiPlanarVideoRange; return kResultSuccess; } else { return kResultFullRangeUnsupported; @@ -769,8 +669,7 @@ static SetVideoFormatResult set_video_format(struct vt_encoder *enc, break; case VIDEO_FORMAT_P416: if (!full_range) { - enc->vt_pix_fmt = - kCVPixelFormatType_444YpCbCr16BiPlanarVideoRange; + enc->vt_pix_fmt = kCVPixelFormatType_444YpCbCr16BiPlanarVideoRange; return kResultSuccess; } else { return kResultFullRangeUnsupported; @@ -797,21 +696,16 @@ static bool update_params(struct vt_encoder *enc, obs_data_t *settings) obs_data_set_int(settings, "codec_type", enc->codec_type); #endif } else { - enc->codec_type = (CMVideoCodecType)obs_data_get_int( - settings, "codec_type"); + enc->codec_type = (CMVideoCodecType)obs_data_get_int(settings, "codec_type"); } - SetVideoFormatResult res = - set_video_format(enc, voi->format, voi->range); + SetVideoFormatResult res = set_video_format(enc, voi->format, voi->range); if (res == kResultColorFormatUnsupported) { - obs_encoder_set_last_error( - enc->encoder, - obs_module_text("ColorFormatUnsupported")); + obs_encoder_set_last_error(enc->encoder, obs_module_text("ColorFormatUnsupported")); VT_BLOG(LOG_WARNING, "Unsupported color format selected"); return false; } else if (res == kResultFullRangeUnsupported) { - obs_encoder_set_last_error( - enc->encoder, obs_module_text("FullRangeUnsupported")); + obs_encoder_set_last_error(enc->encoder, obs_module_text("FullRangeUnsupported")); VT_BLOG(LOG_WARNING, "Unsupported color range (full) selected"); return false; } @@ -826,10 +720,8 @@ static bool update_params(struct vt_encoder *enc, obs_data_t *settings) enc->quality = ((float)obs_data_get_int(settings, "quality")) / 100; enc->profile = obs_data_get_string(settings, "profile"); enc->limit_bitrate = obs_data_get_bool(settings, "limit_bitrate"); - enc->rc_max_bitrate = - (uint32_t)obs_data_get_int(settings, "max_bitrate"); - enc->rc_max_bitrate_window = - obs_data_get_double(settings, "max_bitrate_window"); + enc->rc_max_bitrate = (uint32_t)obs_data_get_int(settings, "max_bitrate"); + enc->rc_max_bitrate_window = obs_data_get_double(settings, "max_bitrate_window"); enc->bframes = obs_data_get_bool(settings, "bframes"); return true; @@ -844,15 +736,11 @@ static bool vt_update(void *data, obs_data_t *settings) update_params(enc, settings); - if (old_bitrate == enc->bitrate && - old_limit_bitrate == enc->limit_bitrate) + if (old_bitrate == enc->bitrate && old_limit_bitrate == enc->limit_bitrate) return true; - OSStatus code = session_set_bitrate(enc->session, enc->rate_control, - enc->bitrate, enc->quality, - enc->limit_bitrate, - enc->rc_max_bitrate, - enc->rc_max_bitrate_window); + OSStatus code = session_set_bitrate(enc->session, enc->rate_control, enc->bitrate, enc->quality, + enc->limit_bitrate, enc->rc_max_bitrate, enc->rc_max_bitrate_window); if (code != noErr) VT_BLOG(LOG_WARNING, "Failed to set bitrate to session"); @@ -905,8 +793,7 @@ static void packet_put_startcode(struct darray *packet, int size) packet_put(packet, &annexb_startcode[4 - size], size); } -static bool handle_prores_packet(struct vt_encoder *enc, - CMSampleBufferRef buffer) +static bool handle_prores_packet(struct vt_encoder *enc, CMSampleBufferRef buffer) { OSStatus err = 0; size_t block_size = 0; @@ -914,15 +801,12 @@ static bool handle_prores_packet(struct vt_encoder *enc, CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer); if (block == NULL) { - VT_BLOG(LOG_ERROR, - "Failed to get block buffer for ProRes frame."); + VT_BLOG(LOG_ERROR, "Failed to get block buffer for ProRes frame."); return false; } - err = CMBlockBufferGetDataPointer(block, 0, NULL, &block_size, - (char **)&block_buf); + err = CMBlockBufferGetDataPointer(block, 0, NULL, &block_size, (char **)&block_buf); if (err != 0) { - VT_BLOG(LOG_ERROR, - "Failed to get data buffer pointer for ProRes frame."); + VT_BLOG(LOG_ERROR, "Failed to get data buffer pointer for ProRes frame."); return false; } @@ -931,16 +815,13 @@ static bool handle_prores_packet(struct vt_encoder *enc, return true; } -static void convert_block_nals_to_annexb(struct vt_encoder *enc, - struct darray *packet, - CMBlockBufferRef block, +static void convert_block_nals_to_annexb(struct vt_encoder *enc, struct darray *packet, CMBlockBufferRef block, int nal_length_bytes) { size_t block_size; uint8_t *block_buf; - CMBlockBufferGetDataPointer(block, 0, NULL, &block_size, - (char **)&block_buf); + CMBlockBufferGetDataPointer(block, 0, NULL, &block_size, (char **)&block_buf); size_t bytes_remaining = block_size; @@ -949,11 +830,9 @@ static void convert_block_nals_to_annexb(struct vt_encoder *enc, if (nal_length_bytes == 1) nal_size = block_buf[0]; else if (nal_length_bytes == 2) - nal_size = CFSwapInt16BigToHost( - ((uint16_t *)block_buf)[0]); + nal_size = CFSwapInt16BigToHost(((uint16_t *)block_buf)[0]); else if (nal_length_bytes == 4) - nal_size = CFSwapInt32BigToHost( - ((uint32_t *)block_buf)[0]); + nal_size = CFSwapInt32BigToHost(((uint32_t *)block_buf)[0]); else return; @@ -973,10 +852,8 @@ static void convert_block_nals_to_annexb(struct vt_encoder *enc, } } -static bool handle_keyframe(struct vt_encoder *enc, - CMFormatDescriptionRef format_desc, - size_t param_count, struct darray *packet, - struct darray *extra_data) +static bool handle_keyframe(struct vt_encoder *enc, CMFormatDescriptionRef format_desc, size_t param_count, + struct darray *packet, struct darray *extra_data) { OSStatus code; const uint8_t *param; @@ -984,14 +861,12 @@ static bool handle_keyframe(struct vt_encoder *enc, for (size_t i = 0; i < param_count; i++) { if (enc->codec_type == kCMVideoCodecType_H264) { - code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( - format_desc, i, ¶m, ¶m_size, NULL, - NULL); + code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format_desc, i, ¶m, ¶m_size, + NULL, NULL); #ifdef ENABLE_HEVC } else if (enc->codec_type == kCMVideoCodecType_HEVC) { - code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex( - format_desc, i, ¶m, ¶m_size, NULL, - NULL); + code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(format_desc, i, ¶m, ¶m_size, + NULL, NULL); #endif } if (code != noErr) { @@ -1014,30 +889,24 @@ static bool handle_keyframe(struct vt_encoder *enc, return true; } -static bool convert_sample_to_annexb(struct vt_encoder *enc, - struct darray *packet, - struct darray *extra_data, +static bool convert_sample_to_annexb(struct vt_encoder *enc, struct darray *packet, struct darray *extra_data, CMSampleBufferRef buffer, bool keyframe) { OSStatus code; - CMFormatDescriptionRef format_desc = - CMSampleBufferGetFormatDescription(buffer); + CMFormatDescriptionRef format_desc = CMSampleBufferGetFormatDescription(buffer); size_t param_count; int nal_length_bytes; if (enc->codec_type == kCMVideoCodecType_H264) { - code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( - format_desc, 0, NULL, NULL, ¶m_count, - &nal_length_bytes); + code = CMVideoFormatDescriptionGetH264ParameterSetAtIndex(format_desc, 0, NULL, NULL, ¶m_count, + &nal_length_bytes); #ifdef ENABLE_HEVC } else if (enc->codec_type == kCMVideoCodecType_HEVC) { - code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex( - format_desc, 0, NULL, NULL, ¶m_count, - &nal_length_bytes); + code = CMVideoFormatDescriptionGetHEVCParameterSetAtIndex(format_desc, 0, NULL, NULL, ¶m_count, + &nal_length_bytes); #endif } else { - log_osstatus(LOG_ERROR, enc, "invalid codec type", - kCMFormatDescriptionError_ValueNotAvailable); + log_osstatus(LOG_ERROR, enc, "invalid codec type", kCMFormatDescriptionError_ValueNotAvailable); return false; } // it is not clear what errors this function can return @@ -1050,13 +919,11 @@ static bool convert_sample_to_annexb(struct vt_encoder *enc, nal_length_bytes = 4; } else if (code != noErr) { - log_osstatus(LOG_ERROR, enc, - "getting parameter count from sample", code); + log_osstatus(LOG_ERROR, enc, "getting parameter count from sample", code); return false; } - if (keyframe && - !handle_keyframe(enc, format_desc, param_count, packet, extra_data)) + if (keyframe && !handle_keyframe(enc, format_desc, param_count, packet, extra_data)) return false; CMBlockBufferRef block = CMSampleBufferGetDataBuffer(buffer); @@ -1067,23 +934,20 @@ static bool convert_sample_to_annexb(struct vt_encoder *enc, static bool is_sample_keyframe(CMSampleBufferRef buffer) { - CFArrayRef attachments = - CMSampleBufferGetSampleAttachmentsArray(buffer, false); + CFArrayRef attachments = CMSampleBufferGetSampleAttachmentsArray(buffer, false); if (attachments != NULL) { CFDictionaryRef attachment; CFBooleanRef has_dependencies; - attachment = - (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0); - has_dependencies = (CFBooleanRef)CFDictionaryGetValue( - attachment, kCMSampleAttachmentKey_DependsOnOthers); + attachment = (CFDictionaryRef)CFArrayGetValueAtIndex(attachments, 0); + has_dependencies = + (CFBooleanRef)CFDictionaryGetValue(attachment, kCMSampleAttachmentKey_DependsOnOthers); return has_dependencies == kCFBooleanFalse; } return false; } -static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer, - struct encoder_packet *packet, CMTime off) +static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer, struct encoder_packet *packet, CMTime off) { CMTime pts = CMSampleBufferGetPresentationTimeStamp(buffer); CMTime dts = CMSampleBufferGetDecodeTimeStamp(buffer); @@ -1098,8 +962,7 @@ static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer, dts = CMTimeMultiply(dts, enc->fps_num); const bool is_avc = enc->codec_type == kCMVideoCodecType_H264; - const bool has_annexb = is_avc || - (enc->codec_type == kCMVideoCodecType_HEVC); + const bool has_annexb = is_avc || (enc->codec_type == kCMVideoCodecType_HEVC); // All ProRes frames are "keyframes" const bool keyframe = !has_annexb || is_sample_keyframe(buffer); @@ -1112,8 +975,7 @@ static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer, extra_data = &enc->extra_data.da; if (has_annexb) { - if (!convert_sample_to_annexb(enc, &enc->packet_data.da, - extra_data, buffer, keyframe)) + if (!convert_sample_to_annexb(enc, &enc->packet_data.da, extra_data, buffer, keyframe)) goto fail; } else { if (!handle_prores_packet(enc, buffer)) @@ -1143,17 +1005,13 @@ static bool parse_sample(struct vt_encoder *enc, CMSampleBufferRef buffer, break; const int type = start[0] & 0x1F; - if (type == OBS_NAL_SLICE_IDR || - type == OBS_NAL_SLICE) { + if (type == OBS_NAL_SLICE_IDR || type == OBS_NAL_SLICE) { uint8_t prev_type = (start[0] >> 5) & 0x3; start[0] &= ~(3 << 5); if (type == OBS_NAL_SLICE_IDR) - start[0] |= OBS_NAL_PRIORITY_HIGHEST - << 5; - else if (type == OBS_NAL_SLICE && - prev_type != - OBS_NAL_PRIORITY_DISPOSABLE) + start[0] |= OBS_NAL_PRIORITY_HIGHEST << 5; + else if (type == OBS_NAL_SLICE && prev_type != OBS_NAL_PRIORITY_DISPOSABLE) start[0] |= OBS_NAL_PRIORITY_HIGH << 5; else start[0] |= prev_type << 5; @@ -1174,8 +1032,7 @@ fail: bool get_cached_pixel_buffer(struct vt_encoder *enc, CVPixelBufferRef *buf) { OSStatus code; - CVPixelBufferPoolRef pool = - VTCompressionSessionGetPixelBufferPool(enc->session); + CVPixelBufferPoolRef pool = VTCompressionSessionGetPixelBufferPool(enc->session); if (!pool) return kCVReturnError; @@ -1190,33 +1047,23 @@ bool get_cached_pixel_buffer(struct vt_encoder *enc, CVPixelBufferRef *buf) // pool to have the correct color space stuff set const enum video_colorspace cs = enc->colorspace; - CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey, - obs_to_vt_colorspace(cs), + CVBufferSetAttachment(pixbuf, kCVImageBufferYCbCrMatrixKey, obs_to_vt_colorspace(cs), kCVAttachmentMode_ShouldPropagate); - CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey, - obs_to_vt_primaries(cs), + CVBufferSetAttachment(pixbuf, kCVImageBufferColorPrimariesKey, obs_to_vt_primaries(cs), kCVAttachmentMode_ShouldPropagate); - CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey, - obs_to_vt_transfer(cs), + CVBufferSetAttachment(pixbuf, kCVImageBufferTransferFunctionKey, obs_to_vt_transfer(cs), kCVAttachmentMode_ShouldPropagate); const bool pq = cs == VIDEO_CS_2100_PQ; const bool hlg = cs == VIDEO_CS_2100_HLG; if (pq || hlg) { - const uint16_t hdr_nominal_peak_level = - pq ? (uint16_t)obs_get_video_hdr_nominal_peak_level() - : (hlg ? 1000 : 0); - CFDataRef masteringDisplayColorVolume = - obs_to_vt_masteringdisplay(hdr_nominal_peak_level); - CFDataRef contentLightLevel = - obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level); + const uint16_t hdr_nominal_peak_level = pq ? (uint16_t)obs_get_video_hdr_nominal_peak_level() + : (hlg ? 1000 : 0); + CFDataRef masteringDisplayColorVolume = obs_to_vt_masteringdisplay(hdr_nominal_peak_level); + CFDataRef contentLightLevel = obs_to_vt_contentlightlevelinfo(hdr_nominal_peak_level); - CVBufferSetAttachment( - pixbuf, kCVImageBufferMasteringDisplayColorVolumeKey, - masteringDisplayColorVolume, - kCVAttachmentMode_ShouldPropagate); - CVBufferSetAttachment(pixbuf, - kCVImageBufferContentLightLevelInfoKey, - contentLightLevel, + CVBufferSetAttachment(pixbuf, kCVImageBufferMasteringDisplayColorVolumeKey, masteringDisplayColorVolume, + kCVAttachmentMode_ShouldPropagate); + CVBufferSetAttachment(pixbuf, kCVImageBufferContentLightLevelInfoKey, contentLightLevel, kCVAttachmentMode_ShouldPropagate); CFRelease(masteringDisplayColorVolume); @@ -1230,8 +1077,7 @@ fail: return false; } -static bool vt_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool vt_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct vt_encoder *enc = data; @@ -1256,11 +1102,9 @@ static bool vt_encode(void *data, struct encoder_frame *frame, for (int i = 0; i < MAX_AV_PLANES; i++) { if (frame->data[i] == NULL) break; - uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane( - pixbuf, i); + uint8_t *p = (uint8_t *)CVPixelBufferGetBaseAddressOfPlane(pixbuf, i); uint8_t *f = frame->data[i]; - size_t plane_linesize = - CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i); + size_t plane_linesize = CVPixelBufferGetBytesPerRowOfPlane(pixbuf, i); size_t plane_height = CVPixelBufferGetHeightOfPlane(pixbuf, i); for (size_t j = 0; j < plane_height; j++) { @@ -1275,14 +1119,12 @@ static bool vt_encode(void *data, struct encoder_frame *frame, goto fail; } - code = VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts, dur, - NULL, pixbuf, NULL); + code = VTCompressionSessionEncodeFrame(enc->session, pixbuf, pts, dur, NULL, pixbuf, NULL); if (code != noErr) { goto fail; } - CMSampleBufferRef buffer = - (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue); + CMSampleBufferRef buffer = (CMSampleBufferRef)CMSimpleQueueDequeue(enc->queue); // No samples waiting in the queue if (buffer == NULL) @@ -1327,15 +1169,12 @@ static const char *vt_getname(void *data) return type_data->disp_name; } -static bool rate_control_limit_bitrate_modified(obs_properties_t *ppts, - obs_property_t *p, - obs_data_t *settings) +static bool rate_control_limit_bitrate_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { bool has_bitrate = true; bool can_limit_bitrate = true; bool use_limit_bitrate = obs_data_get_bool(settings, "limit_bitrate"); - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); if (strcmp(rate_control, "CBR") == 0) { can_limit_bitrate = false; @@ -1362,22 +1201,18 @@ static bool rate_control_limit_bitrate_modified(obs_properties_t *ppts, return true; } -static obs_properties_t *vt_properties_h26x(void *data __unused, - void *type_data) +static obs_properties_t *vt_properties_h26x(void *data __unused, void *type_data) { struct vt_encoder_type_data *encoder_type_data = type_data; obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); if (__builtin_available(macOS 13.0, *)) { - if (encoder_type_data->hardware_accelerated && - is_apple_silicon) { + if (encoder_type_data->hardware_accelerated && is_apple_silicon) { obs_property_list_add_string(p, "CBR", "CBR"); } } @@ -1388,38 +1223,26 @@ static obs_properties_t *vt_properties_h26x(void *data __unused, obs_property_list_add_string(p, "CRF", "CRF"); } - obs_property_set_modified_callback(p, - rate_control_limit_bitrate_modified); + obs_property_set_modified_callback(p, rate_control_limit_bitrate_modified); - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 50, 10000000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 10000000, 50); obs_property_int_set_suffix(p, " Kbps"); - obs_properties_add_int_slider(props, "quality", - obs_module_text("Quality"), 0, 100, 1); + obs_properties_add_int_slider(props, "quality", obs_module_text("Quality"), 0, 100, 1); - p = obs_properties_add_bool(props, "limit_bitrate", - obs_module_text("UseMaxBitrate")); - obs_property_set_modified_callback(p, - rate_control_limit_bitrate_modified); + p = obs_properties_add_bool(props, "limit_bitrate", obs_module_text("UseMaxBitrate")); + obs_property_set_modified_callback(p, rate_control_limit_bitrate_modified); - p = obs_properties_add_int(props, "max_bitrate", - obs_module_text("MaxBitrate"), 50, 10000000, - 50); + p = obs_properties_add_int(props, "max_bitrate", obs_module_text("MaxBitrate"), 50, 10000000, 50); obs_property_int_set_suffix(p, " Kbps"); - p = obs_properties_add_float(props, "max_bitrate_window", - obs_module_text("MaxBitrateWindow"), 0.10f, - 10.0f, 0.25f); + p = obs_properties_add_float(props, "max_bitrate_window", obs_module_text("MaxBitrateWindow"), 0.10f, 10.0f, + 0.25f); obs_property_float_set_suffix(p, " s"); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 20, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 20, 1); obs_property_int_set_suffix(p, " s"); - p = obs_properties_add_list(props, "profile", - obs_module_text("Profile"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); if (encoder_type_data->codec_type == kCMVideoCodecType_H264) { @@ -1431,29 +1254,25 @@ static obs_properties_t *vt_properties_h26x(void *data __unused, obs_property_list_add_string(p, "main", "main"); obs_property_list_add_string(p, "main10", "main10"); if (__builtin_available(macOS 12.3, *)) { - obs_property_list_add_string(p, "main 4:2:2 10", - "main42210"); + obs_property_list_add_string(p, "main 4:2:2 10", "main42210"); } #endif } - obs_properties_add_bool(props, "bframes", - obs_module_text("UseBFrames")); + obs_properties_add_bool(props, "bframes", obs_module_text("UseBFrames")); return props; } -static obs_properties_t *vt_properties_prores(void *data __unused, - void *type_data) +static obs_properties_t *vt_properties_prores(void *data __unused, void *type_data) { struct vt_encoder_type_data *encoder_type_data = type_data; obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(props, "codec_type", - obs_module_text("ProResCodec"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(props, "codec_type", obs_module_text("ProResCodec"), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); uint32_t codec_availability_flags = 0; @@ -1492,24 +1311,17 @@ static obs_properties_t *vt_properties_prores(void *data __unused, } if (codec_availability_flags & (1 << 0)) - obs_property_list_add_int(p, obs_module_text("ProRes4444XQ"), - kCMVideoCodecType_AppleProRes4444XQ); + obs_property_list_add_int(p, obs_module_text("ProRes4444XQ"), kCMVideoCodecType_AppleProRes4444XQ); if (codec_availability_flags & (1 << 1)) - obs_property_list_add_int(p, obs_module_text("ProRes4444"), - kCMVideoCodecType_AppleProRes4444); + obs_property_list_add_int(p, obs_module_text("ProRes4444"), kCMVideoCodecType_AppleProRes4444); if (codec_availability_flags & (1 << 2)) - obs_property_list_add_int( - p, obs_module_text("ProRes422Proxy"), - kCMVideoCodecType_AppleProRes422Proxy); + obs_property_list_add_int(p, obs_module_text("ProRes422Proxy"), kCMVideoCodecType_AppleProRes422Proxy); if (codec_availability_flags & (1 << 3)) - obs_property_list_add_int(p, obs_module_text("ProRes422LT"), - kCMVideoCodecType_AppleProRes422LT); + obs_property_list_add_int(p, obs_module_text("ProRes422LT"), kCMVideoCodecType_AppleProRes422LT); if (codec_availability_flags & (1 << 4)) - obs_property_list_add_int(p, obs_module_text("ProRes422"), - kCMVideoCodecType_AppleProRes422); + obs_property_list_add_int(p, obs_module_text("ProRes422"), kCMVideoCodecType_AppleProRes422); if (codec_availability_flags & (1 << 5)) - obs_property_list_add_int(p, obs_module_text("ProRes422HQ"), - kCMVideoCodecType_AppleProRes422HQ); + obs_property_list_add_int(p, obs_module_text("ProRes422HQ"), kCMVideoCodecType_AppleProRes422HQ); return props; } @@ -1521,8 +1333,7 @@ static void vt_defaults(obs_data_t *settings, void *data) obs_data_set_default_string(settings, "rate_control", "ABR"); if (__builtin_available(macOS 13.0, *)) { if (type_data->hardware_accelerated && is_apple_silicon) { - obs_data_set_default_string(settings, "rate_control", - "CBR"); + obs_data_set_default_string(settings, "rate_control", "CBR"); } } obs_data_set_default_int(settings, "bitrate", 2500); @@ -1531,12 +1342,9 @@ static void vt_defaults(obs_data_t *settings, void *data) obs_data_set_default_int(settings, "max_bitrate", 2500); obs_data_set_default_double(settings, "max_bitrate_window", 1.5f); obs_data_set_default_int(settings, "keyint_sec", 2); - obs_data_set_default_string( - settings, "profile", - type_data->codec_type == kCMVideoCodecType_H264 ? "high" - : "main"); - obs_data_set_default_int(settings, "codec_type", - kCMVideoCodecType_AppleProRes422); + obs_data_set_default_string(settings, "profile", + type_data->codec_type == kCMVideoCodecType_H264 ? "high" : "main"); + obs_data_set_default_int(settings, "codec_type", kCMVideoCodecType_AppleProRes422); obs_data_set_default_bool(settings, "bframes", true); } @@ -1549,23 +1357,18 @@ static void vt_free_type_data(void *data) bfree(type_data); } -static inline void -vt_add_prores_encoder_data_to_list(CFDictionaryRef encoder_dict, - FourCharCode codec_type) +static inline void vt_add_prores_encoder_data_to_list(CFDictionaryRef encoder_dict, FourCharCode codec_type) { struct vt_prores_encoder_data *encoder_data = NULL; - CFBooleanRef hardware_accelerated = CFDictionaryGetValue( - encoder_dict, kVTVideoEncoderList_IsHardwareAccelerated); + CFBooleanRef hardware_accelerated = + CFDictionaryGetValue(encoder_dict, kVTVideoEncoderList_IsHardwareAccelerated); if (hardware_accelerated == kCFBooleanTrue) - encoder_data = - da_push_back_new(vt_prores_hardware_encoder_list); + encoder_data = da_push_back_new(vt_prores_hardware_encoder_list); else - encoder_data = - da_push_back_new(vt_prores_software_encoder_list); + encoder_data = da_push_back_new(vt_prores_software_encoder_list); - encoder_data->encoder_id = CFDictionaryGetValue( - encoder_dict, kVTVideoEncoderList_EncoderID); + encoder_data->encoder_id = CFDictionaryGetValue(encoder_dict, kVTVideoEncoderList_EncoderID); encoder_data->codec_type = codec_type; } @@ -1577,8 +1380,7 @@ CFArrayRef encoder_list; bool obs_module_load(void) { - dispatch_queue_t queue = - dispatch_queue_create("Encoder list load queue", NULL); + dispatch_queue_t queue = dispatch_queue_create("Encoder list load queue", NULL); encoder_list_dispatch_group = dispatch_group_create(); dispatch_group_async(encoder_list_dispatch_group, queue, ^{ VTCopyVideoEncoderList(NULL, &encoder_list); @@ -1615,15 +1417,12 @@ void obs_module_post_load(void) CFIndex size = CFArrayGetCount(encoder_list); for (CFIndex i = 0; i < size; i++) { - CFDictionaryRef encoder_dict = - CFArrayGetValueAtIndex(encoder_list, i); + CFDictionaryRef encoder_dict = CFArrayGetValueAtIndex(encoder_list, i); CMVideoCodecType codec_type = 0; { - CFNumberRef codec_type_num = CFDictionaryGetValue( - encoder_dict, kVTVideoEncoderList_CodecType); - CFNumberGetValue(codec_type_num, kCFNumberSInt32Type, - &codec_type); + CFNumberRef codec_type_num = CFDictionaryGetValue(encoder_dict, kVTVideoEncoderList_CodecType); + CFNumberGetValue(codec_type_num, kCFNumberSInt32Type, &codec_type); } switch (codec_type) { @@ -1642,8 +1441,7 @@ void obs_module_post_load(void) case kCMVideoCodecType_AppleProRes422: info.get_properties2 = vt_properties_prores; info.codec = "prores"; - vt_add_prores_encoder_data_to_list(encoder_dict, - codec_type); + vt_add_prores_encoder_data_to_list(encoder_dict, codec_type); break; case kCMVideoCodecType_AppleProRes4444XQ: @@ -1651,42 +1449,30 @@ void obs_module_post_load(void) case kCMVideoCodecType_AppleProRes422Proxy: case kCMVideoCodecType_AppleProRes422LT: case kCMVideoCodecType_AppleProRes422HQ: - vt_add_prores_encoder_data_to_list(encoder_dict, - codec_type); + vt_add_prores_encoder_data_to_list(encoder_dict, codec_type); continue; default: continue; } - CFStringRef EncoderID = CFDictionaryGetValue( - encoder_dict, kVTVideoEncoderList_EncoderID); - CFIndex id_len = - CFStringGetMaximumSizeOfFileSystemRepresentation( - EncoderID); + CFStringRef EncoderID = CFDictionaryGetValue(encoder_dict, kVTVideoEncoderList_EncoderID); + CFIndex id_len = CFStringGetMaximumSizeOfFileSystemRepresentation(EncoderID); char *id = bzalloc(id_len + 1); CFStringGetFileSystemRepresentation(EncoderID, id, id_len); - CFStringRef DisplayName = CFDictionaryGetValue( - encoder_dict, kVTVideoEncoderList_DisplayName); - CFIndex disp_name_len = - CFStringGetMaximumSizeOfFileSystemRepresentation( - DisplayName); + CFStringRef DisplayName = CFDictionaryGetValue(encoder_dict, kVTVideoEncoderList_DisplayName); + CFIndex disp_name_len = CFStringGetMaximumSizeOfFileSystemRepresentation(DisplayName); char *disp_name = bzalloc(disp_name_len + 1); - CFStringGetFileSystemRepresentation(DisplayName, disp_name, - disp_name_len); + CFStringGetFileSystemRepresentation(DisplayName, disp_name, disp_name_len); - CFBooleanRef hardware_ref = CFDictionaryGetValue( - encoder_dict, - kVTVideoEncoderList_IsHardwareAccelerated); + CFBooleanRef hardware_ref = + CFDictionaryGetValue(encoder_dict, kVTVideoEncoderList_IsHardwareAccelerated); - bool hardware_accelerated = - (hardware_ref) ? CFBooleanGetValue(hardware_ref) - : false; + bool hardware_accelerated = (hardware_ref) ? CFBooleanGetValue(hardware_ref) : false; info.id = id; - struct vt_encoder_type_data *type_data = - bzalloc(sizeof(struct vt_encoder_type_data)); + struct vt_encoder_type_data *type_data = bzalloc(sizeof(struct vt_encoder_type_data)); type_data->disp_name = disp_name; type_data->id = id; type_data->codec_type = codec_type; diff --git a/plugins/mac-virtualcam/src/dal-plugin/CMSampleBufferUtils.h b/plugins/mac-virtualcam/src/dal-plugin/CMSampleBufferUtils.h index 556470088..b7b20896a 100644 --- a/plugins/mac-virtualcam/src/dal-plugin/CMSampleBufferUtils.h +++ b/plugins/mac-virtualcam/src/dal-plugin/CMSampleBufferUtils.h @@ -7,6 +7,5 @@ #include -CMSampleTimingInfo CMSampleTimingInfoForTimestamp(uint64_t timestampNanos, - uint32_t fpsNumerator, +CMSampleTimingInfo CMSampleTimingInfoForTimestamp(uint64_t timestampNanos, uint32_t fpsNumerator, uint32_t fpsDenominator); diff --git a/plugins/mac-virtualcam/src/obs-plugin/Defines.h b/plugins/mac-virtualcam/src/obs-plugin/Defines.h index 4a3fee054..f9292e01c 100644 --- a/plugins/mac-virtualcam/src/obs-plugin/Defines.h +++ b/plugins/mac-virtualcam/src/obs-plugin/Defines.h @@ -19,5 +19,4 @@ #define PLUGIN_NAME "mac-virtualcam" -#define blog(level, msg, ...) \ - blog(level, "[" PLUGIN_NAME "] " msg, ##__VA_ARGS__) +#define blog(level, msg, ...) blog(level, "[" PLUGIN_NAME "] " msg, ##__VA_ARGS__) diff --git a/plugins/nv-filters/nvafx-load.h b/plugins/nv-filters/nvafx-load.h index 8cd4eecda..2789920b1 100644 --- a/plugins/nv-filters/nvafx-load.h +++ b/plugins/nv-filters/nvafx-load.h @@ -24,21 +24,14 @@ static HMODULE nv_cuda = NULL; /** Model paths */ #define NVAFX_EFFECT_DENOISER_MODEL "\\models\\denoiser_48k.trtpkg" #define NVAFX_EFFECT_DEREVERB_MODEL "\\models\\dereverb_48k.trtpkg" -#define NVAFX_EFFECT_DEREVERB_DENOISER_MODEL \ - "\\models\\dereverb_denoiser_48k.trtpkg" +#define NVAFX_EFFECT_DEREVERB_DENOISER_MODEL "\\models\\dereverb_denoiser_48k.trtpkg" -#define NVAFX_CHAINED_EFFECT_DENOISER_16k_SUPERRES_16k_TO_48k \ - "denoiser16k_superres16kto48k" -#define NVAFX_CHAINED_EFFECT_DEREVERB_16k_SUPERRES_16k_TO_48k \ - "dereverb16k_superres16kto48k" -#define NVAFX_CHAINED_EFFECT_DEREVERB_DENOISER_16k_SUPERRES_16k_TO_48k \ - "dereverb_denoiser16k_superres16kto48k" -#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DENOISER_16k \ - "superres8kto16k_denoiser16k" -#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_16k \ - "superres8kto16k_dereverb16k" -#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_DENOISER_16k \ - "superres8kto16k_dereverb_denoiser16k" +#define NVAFX_CHAINED_EFFECT_DENOISER_16k_SUPERRES_16k_TO_48k "denoiser16k_superres16kto48k" +#define NVAFX_CHAINED_EFFECT_DEREVERB_16k_SUPERRES_16k_TO_48k "dereverb16k_superres16kto48k" +#define NVAFX_CHAINED_EFFECT_DEREVERB_DENOISER_16k_SUPERRES_16k_TO_48k "dereverb_denoiser16k_superres16kto48k" +#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DENOISER_16k "superres8kto16k_denoiser16k" +#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_16k "superres8kto16k_dereverb16k" +#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_DENOISER_16k "superres8kto16k_dereverb_denoiser16k" /** Parameter selectors */ @@ -62,8 +55,7 @@ static HMODULE nv_cuda = NULL; #pragma deprecated(NVAFX_PARAM_DENOISER_SAMPLE_RATE) #define NVAFX_PARAM_DENOISER_SAMPLE_RATE NVAFX_PARAM_SAMPLE_RATE #pragma deprecated(NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME) -#define NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME \ - NVAFX_PARAM_NUM_SAMPLES_PER_FRAME +#define NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME NVAFX_PARAM_NUM_SAMPLES_PER_FRAME #pragma deprecated(NVAFX_PARAM_DENOISER_NUM_CHANNELS) #define NVAFX_PARAM_DENOISER_NUM_CHANNELS NVAFX_PARAM_NUM_CHANNELS #pragma deprecated(NVAFX_PARAM_DENOISER_INTENSITY_RATIO) @@ -114,64 +106,34 @@ typedef const char *NvAFX_EffectSelector; typedef const char *NvAFX_ParameterSelector; typedef void *NvAFX_Handle; -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetEffectList_t)(int *num_effects, - NvAFX_EffectSelector *effects[]); -typedef NvAFX_Status - NVAFX_API (*NvAFX_CreateEffect_t)(NvAFX_EffectSelector code, - NvAFX_Handle *effect); -typedef NvAFX_Status - NVAFX_API (*NvAFX_CreateChainedEffect_t)(NvAFX_EffectSelector code, - NvAFX_Handle *effect); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetEffectList_t)(int *num_effects, NvAFX_EffectSelector *effects[]); +typedef NvAFX_Status NVAFX_API (*NvAFX_CreateEffect_t)(NvAFX_EffectSelector code, NvAFX_Handle *effect); +typedef NvAFX_Status NVAFX_API (*NvAFX_CreateChainedEffect_t)(NvAFX_EffectSelector code, NvAFX_Handle *effect); typedef NvAFX_Status NVAFX_API (*NvAFX_DestroyEffect_t)(NvAFX_Handle effect); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetU32_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - unsigned int val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetU32List_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - unsigned int *val, unsigned int size); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetString_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - const char *val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetStringList_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - const char **val, unsigned int size); -typedef NvAFX_Status NVAFX_API (*NvAFX_SetFloat_t)( - NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetFloatList_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - float *val, unsigned int size); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetU32_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - unsigned int *val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetString_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - char *val, int max_length); -typedef NvAFX_Status NVAFX_API (*NvAFX_GetStringList_t)( - NvAFX_Handle effect, NvAFX_ParameterSelector param_name, char **val, - int *max_length, unsigned int size); -typedef NvAFX_Status NVAFX_API (*NvAFX_GetFloat_t)( - NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float *val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetFloatList_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - float *val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetU32_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + unsigned int val); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetU32List_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + unsigned int *val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetString_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + const char *val); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetStringList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + const char **val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetFloat_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float val); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetFloatList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + float *val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetU32_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + unsigned int *val); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetString_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, char *val, + int max_length); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetStringList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + char **val, int *max_length, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetFloat_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float *val); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetFloatList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + float *val, unsigned int size); typedef NvAFX_Status NVAFX_API (*NvAFX_Load_t)(NvAFX_Handle effect); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetSupportedDevices_t)(NvAFX_Handle effect, int *num, - int *devices); -typedef NvAFX_Status NVAFX_API (*NvAFX_Run_t)(NvAFX_Handle effect, - const float **input, - float **output, - unsigned num_samples, - unsigned num_channels); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetSupportedDevices_t)(NvAFX_Handle effect, int *num, int *devices); +typedef NvAFX_Status NVAFX_API (*NvAFX_Run_t)(NvAFX_Handle effect, const float **input, float **output, + unsigned num_samples, unsigned num_channels); typedef NvAFX_Status NVAFX_API (*NvAFX_Reset_t)(NvAFX_Handle effect); /* cuda */ @@ -289,8 +251,7 @@ void release_lib(void) static bool nvafx_get_sdk_path(char *buffer, const size_t len) { - DWORD ret = - GetEnvironmentVariableA("NVAFX_SDK_DIR", buffer, (DWORD)len); + DWORD ret = GetEnvironmentVariableA("NVAFX_SDK_DIR", buffer, (DWORD)len); if (!ret || ret >= len - 1) return false; @@ -329,8 +290,7 @@ static unsigned int get_lib_version(void) struct win_version_info nto_ver = {0}; if (get_dll_ver(L"NVAudioEffects.dll", &nto_ver)) - version = nto_ver.major << 24 | nto_ver.minor << 16 | - nto_ver.build << 8 | nto_ver.revis << 0; + version = nto_ver.major << 24 | nto_ver.minor << 16 | nto_ver.build << 8 | nto_ver.revis << 0; SetDllDirectoryA(NULL); return version; diff --git a/plugins/nv-filters/nvidia-audiofx-filter.c b/plugins/nv-filters/nvidia-audiofx-filter.c index c63e687f6..b80592892 100644 --- a/plugins/nv-filters/nvidia-audiofx-filter.c +++ b/plugins/nv-filters/nvidia-audiofx-filter.c @@ -8,9 +8,8 @@ #include /* -------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[NVIDIA Audio Effects: '%s'] " format, \ - obs_source_get_name(ng->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[NVIDIA Audio Effects: '%s'] " format, obs_source_get_name(ng->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -33,8 +32,7 @@ #define TEXT_METHOD MT_("Nvafx.Method") #define TEXT_METHOD_NVAFX_DENOISER MT_("Nvafx.Method.Denoiser") #define TEXT_METHOD_NVAFX_DEREVERB MT_("Nvafx.Method.Dereverb") -#define TEXT_METHOD_NVAFX_DEREVERB_DENOISER \ - MT_("Nvafx.Method.DenoiserPlusDereverb") +#define TEXT_METHOD_NVAFX_DEREVERB_DENOISER MT_("Nvafx.Method.DenoiserPlusDereverb") #define TEXT_METHOD_NVAFX_DEPRECATION MT_("Nvafx.OutdatedSDK") #define MAX_PREPROC_CHANNELS 8 @@ -131,11 +129,9 @@ static void nvidia_audio_destroy(void *data) for (size_t i = 0; i < ng->channels; i++) { if (ng->handle[0]) { if (NvAFX_DestroyEffect) { - NvAFX_Status err = - NvAFX_DestroyEffect(ng->handle[i]); + NvAFX_Status err = NvAFX_DestroyEffect(ng->handle[i]); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_Release() failed"); + do_log(LOG_ERROR, "NvAFX_Release() failed"); } } } @@ -213,17 +209,13 @@ bool load_nvidia_afx(void) uint8_t build = (version >> 8) & 0x0000ff; uint8_t revision = (version >> 0) & 0x000000ff; if (version) { - blog(LOG_INFO, "[NVIDIA Audio Effects:] version: %i.%i.%i.%i", - major, minor, build, revision); + blog(LOG_INFO, "[NVIDIA Audio Effects:] version: %i.%i.%i.%i", major, minor, build, revision); if (version < MIN_AFX_SDK_VERSION) { blog(LOG_INFO, "[NVIDIA Audio Effects:]: SDK is outdated. Please update both audio & video SDK.\nRequired SDK versions, audio: %i.%i.%i; video: %i.%i.%i", - (MIN_AFX_SDK_VERSION >> 24) & 0xff, - (MIN_AFX_SDK_VERSION >> 16) & 0x00ff, - (MIN_AFX_SDK_VERSION >> 8) & 0x0000ff, - (MIN_VFX_SDK_VERSION >> 24) & 0xff, - (MIN_VFX_SDK_VERSION >> 16) & 0x00ff, - (MIN_VFX_SDK_VERSION >> 8) & 0x0000ff); + (MIN_AFX_SDK_VERSION >> 24) & 0xff, (MIN_AFX_SDK_VERSION >> 16) & 0x00ff, + (MIN_AFX_SDK_VERSION >> 8) & 0x0000ff, (MIN_VFX_SDK_VERSION >> 24) & 0xff, + (MIN_VFX_SDK_VERSION >> 16) & 0x00ff, (MIN_VFX_SDK_VERSION >> 8) & 0x0000ff); } } if (!load_lib()) { @@ -232,16 +224,13 @@ bool load_nvidia_afx(void) return false; } - nvidia_afx_initializer_mutex_initialized = - pthread_mutex_init(&nvidia_afx_initializer_mutex, NULL) == 0; + nvidia_afx_initializer_mutex_initialized = pthread_mutex_init(&nvidia_afx_initializer_mutex, NULL) == 0; -#define LOAD_SYM_FROM_LIB(sym, lib, dll) \ - if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ - DWORD err = GetLastError(); \ - printf("[noise suppress]: Couldn't load " #sym " from " dll \ - ": %lu (0x%lx)", \ - err, err); \ - goto unload_everything; \ +#define LOAD_SYM_FROM_LIB(sym, lib, dll) \ + if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ + DWORD err = GetLastError(); \ + printf("[noise suppress]: Couldn't load " #sym " from " dll ": %lu (0x%lx)", err, err); \ + goto unload_everything; \ } #define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_audiofx, "NVAudioEffects.dll") @@ -301,19 +290,16 @@ bool load_nvidia_afx(void) if (err != NVAFX_STATUS_SUCCESS) { if (err == NVAFX_STATUS_GPU_UNSUPPORTED) { - blog(LOG_INFO, - "[NVIDIA Audio Effects:] disabled: unsupported GPU"); + blog(LOG_INFO, "[NVIDIA Audio Effects:] disabled: unsupported GPU"); } else { - blog(LOG_ERROR, - "[NVIDIA Audio Effects:] disabled, error %i", err); + blog(LOG_ERROR, "[NVIDIA Audio Effects:] disabled, error %i", err); } goto unload_everything; } err = NvAFX_DestroyEffect(h); if (err != NVAFX_STATUS_SUCCESS) { - blog(LOG_ERROR, "[NVIDIA Audio Effects:]: disabled, error %i", - err); + blog(LOG_ERROR, "[NVIDIA Audio Effects:]: disabled, error %i", err); goto unload_everything; } @@ -322,8 +308,7 @@ bool load_nvidia_afx(void) return true; cuda_errors: - blog(LOG_ERROR, "[NVIDIA Audio Effects:] disabled, CUDA error %i", - cudaerr); + blog(LOG_ERROR, "[NVIDIA Audio Effects:] disabled, CUDA error %i", cudaerr); unload_everything: release_afxlib(); @@ -359,9 +344,7 @@ static bool nvidia_audio_initialize_internal(void *data) } err = NvAFX_CreateEffect(ng->fx, &ng->handle[i]); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "%s FX creation failed, error %i", - ng->fx, err); + do_log(LOG_ERROR, "%s FX creation failed, error %i", ng->fx, err); goto failure; } if (cuCtxGetCurrent(&curr) != CUDA_SUCCESS) { @@ -371,44 +354,32 @@ static bool nvidia_audio_initialize_internal(void *data) cuCtxPopCurrent(NULL); } // Set sample rate of FX - err = NvAFX_SetU32(ng->handle[i], - NVAFX_PARAM_INPUT_SAMPLE_RATE, - ng->sample_rate); + err = NvAFX_SetU32(ng->handle[i], NVAFX_PARAM_INPUT_SAMPLE_RATE, ng->sample_rate); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_SetU32(Sample Rate: %u) failed, error %i", - ng->sample_rate, err); + do_log(LOG_ERROR, "NvAFX_SetU32(Sample Rate: %u) failed, error %i", ng->sample_rate, + err); goto failure; } // Set intensity of FX - err = NvAFX_SetFloat(ng->handle[i], - NVAFX_PARAM_INTENSITY_RATIO, - ng->intensity_ratio); + err = NvAFX_SetFloat(ng->handle[i], NVAFX_PARAM_INTENSITY_RATIO, ng->intensity_ratio); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i", + do_log(LOG_ERROR, "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i", ng->intensity_ratio, err); goto failure; } // Set AI models path - err = NvAFX_SetString(ng->handle[i], - NVAFX_PARAM_MODEL_PATH, - ng->model); + err = NvAFX_SetString(ng->handle[i], NVAFX_PARAM_MODEL_PATH, ng->model); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_SetString() failed, error %i", - err); + do_log(LOG_ERROR, "NvAFX_SetString() failed, error %i", err); goto failure; } // Load FX (this is a very long step, about 2 seconds) err = NvAFX_Load(ng->handle[i]); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_Load() failed with error %i", - err); + do_log(LOG_ERROR, "NvAFX_Load() failed with error %i", err); goto failure; } os_atomic_set_bool(&ng->reinit_done, true); @@ -435,26 +406,19 @@ static void *nvidia_audio_initialize(void *data) goto failure; } if (ng->use_nvafx) { - err = NvAFX_GetU32(ng->handle[0], - NVAFX_PARAM_NUM_INPUT_CHANNELS, - &ng->num_channels); + err = NvAFX_GetU32(ng->handle[0], NVAFX_PARAM_NUM_INPUT_CHANNELS, &ng->num_channels); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_GetU32() failed to get the number of channels, error %i", - err); + do_log(LOG_ERROR, "NvAFX_GetU32() failed to get the number of channels, error %i", err); goto failure; } if (ng->num_channels != 1) { - do_log(LOG_ERROR, - "The number of channels is not 1 in the sdk any more ==> update code"); + do_log(LOG_ERROR, "The number of channels is not 1 in the sdk any more ==> update code"); goto failure; } - NvAFX_Status err = NvAFX_GetU32( - ng->handle[0], NVAFX_PARAM_NUM_INPUT_SAMPLES_PER_FRAME, - &ng->num_samples_per_frame); + NvAFX_Status err = NvAFX_GetU32(ng->handle[0], NVAFX_PARAM_NUM_INPUT_SAMPLES_PER_FRAME, + &ng->num_samples_per_frame); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_GetU32() failed to get the number of samples per frame, error %i", + do_log(LOG_ERROR, "NvAFX_GetU32() failed to get the number of samples per frame, error %i", err); goto failure; } @@ -540,27 +504,21 @@ static void nvidia_audio_update(void *data, obs_data_t *s) if (!ng->nvafx_initialized && !ng->nvafx_loading) { ng->intensity_ratio = intensity; ng->nvafx_loading = true; - pthread_create(&ng->nvafx_thread, NULL, nvidia_audio_initialize, - ng); + pthread_create(&ng->nvafx_thread, NULL, nvidia_audio_initialize, ng); } /*-------------------------------------------------------------------*/ /* STAGE 2 : this is executed only after the FX has been initialized */ if (ng->nvafx_initialized) { /* updating the intensity of the FX */ - if (intensity != ng->intensity_ratio && - (strcmp(ng->fx, method) == 0)) { + if (intensity != ng->intensity_ratio && (strcmp(ng->fx, method) == 0)) { NvAFX_Status err; ng->intensity_ratio = intensity; pthread_mutex_lock(&ng->nvafx_mutex); for (size_t i = 0; i < ng->channels; i++) { - err = NvAFX_SetFloat( - ng->handle[i], - NVAFX_PARAM_INTENSITY_RATIO, - ng->intensity_ratio); + err = NvAFX_SetFloat(ng->handle[i], NVAFX_PARAM_INTENSITY_RATIO, ng->intensity_ratio); if (err != NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i", + do_log(LOG_ERROR, "NvAFX_SetFloat(Intensity Ratio: %f) failed, error %i", ng->intensity_ratio, err); nvidia_audio_destroy(ng); } @@ -577,10 +535,8 @@ static void nvidia_audio_update(void *data, obs_data_t *s) os_atomic_set_bool(&ng->reinit_done, false); for (int i = 0; i < (int)ng->channels; i++) { /* Destroy previous FX */ - if (NvAFX_DestroyEffect(ng->handle[i]) != - NVAFX_STATUS_SUCCESS) { - do_log(LOG_ERROR, - "FX failed to be destroyed."); + if (NvAFX_DestroyEffect(ng->handle[i]) != NVAFX_STATUS_SUCCESS) { + do_log(LOG_ERROR, "FX failed to be destroyed."); nvidia_audio_destroy(ng); } else { ng->handle[i] = NULL; @@ -596,8 +552,7 @@ static void nvidia_audio_update(void *data, obs_data_t *s) static void *nvidia_audio_create(obs_data_t *settings, obs_source_t *filter) { - struct nvidia_audio_data *ng = - bzalloc(sizeof(struct nvidia_audio_data)); + struct nvidia_audio_data *ng = bzalloc(sizeof(struct nvidia_audio_data)); ng->context = filter; @@ -638,12 +593,10 @@ static void *nvidia_audio_create(obs_data_t *settings, obs_source_t *filter) /* allocate buffers */ ng->copy_buffers[0] = bmalloc(frames * channels * sizeof(float)); - ng->nvafx_segment_buffers[0] = - bmalloc(NVAFX_FRAME_SIZE * channels * sizeof(float)); + ng->nvafx_segment_buffers[0] = bmalloc(NVAFX_FRAME_SIZE * channels * sizeof(float)); for (size_t c = 1; c < channels; ++c) { ng->copy_buffers[c] = ng->copy_buffers[c - 1] + frames; - ng->nvafx_segment_buffers[c] = - ng->nvafx_segment_buffers[c - 1] + NVAFX_FRAME_SIZE; + ng->nvafx_segment_buffers[c] = ng->nvafx_segment_buffers[c - 1] + NVAFX_FRAME_SIZE; } /* reserve circular buffers */ @@ -681,19 +634,14 @@ static inline void process_fx(struct nvidia_audio_data *ng) float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; - audio_resampler_resample(ng->nvafx_resampler, - (uint8_t **)output, &out_frames, - &ts_offset, - (const uint8_t **)ng->copy_buffers, - (uint32_t)ng->frames); + audio_resampler_resample(ng->nvafx_resampler, (uint8_t **)output, &out_frames, &ts_offset, + (const uint8_t **)ng->copy_buffers, (uint32_t)ng->frames); for (size_t i = 0; i < ng->channels; i++) { - for (ssize_t j = 0, - k = (ssize_t)out_frames - NVAFX_FRAME_SIZE; - j < NVAFX_FRAME_SIZE; ++j, ++k) { + for (ssize_t j = 0, k = (ssize_t)out_frames - NVAFX_FRAME_SIZE; j < NVAFX_FRAME_SIZE; + ++j, ++k) { if (k >= 0) { - ng->nvafx_segment_buffers[i][j] = - output[i][k]; + ng->nvafx_segment_buffers[i][j] = output[i][k]; } else { ng->nvafx_segment_buffers[i][j] = 0; } @@ -702,8 +650,7 @@ static inline void process_fx(struct nvidia_audio_data *ng) } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < NVAFX_FRAME_SIZE; ++j) { - ng->nvafx_segment_buffers[i][j] = - ng->copy_buffers[i][j]; + ng->nvafx_segment_buffers[i][j] = ng->copy_buffers[i][j]; } } } @@ -713,47 +660,36 @@ static inline void process_fx(struct nvidia_audio_data *ng) if (ng->reinit_done) { pthread_mutex_lock(&ng->nvafx_mutex); for (size_t i = 0; i < runs; i++) { - NvAFX_Status err = NvAFX_Run( - ng->handle[i], &ng->nvafx_segment_buffers[i], - &ng->nvafx_segment_buffers[i], - ng->num_samples_per_frame, ng->num_channels); + NvAFX_Status err = NvAFX_Run(ng->handle[i], &ng->nvafx_segment_buffers[i], + &ng->nvafx_segment_buffers[i], ng->num_samples_per_frame, + ng->num_channels); if (err != NVAFX_STATUS_SUCCESS) { if (err == NVAFX_STATUS_FAILED) { do_log(LOG_DEBUG, "NvAFX_Run() failed, error NVAFX_STATUS_FAILED.\n" "This can occur when changing the FX and is not consequential."); // stop all processing; this will be reset at new init - os_atomic_set_bool(&ng->reinit_done, - false); + os_atomic_set_bool(&ng->reinit_done, false); } else { - do_log(LOG_ERROR, - "NvAFX_Run() failed, error %i.\n", - err); + do_log(LOG_ERROR, "NvAFX_Run() failed, error %i.\n", err); } } } pthread_mutex_unlock(&ng->nvafx_mutex); } if (ng->has_mono_src) { - memcpy(ng->nvafx_segment_buffers[1], - ng->nvafx_segment_buffers[0], - NVAFX_FRAME_SIZE * sizeof(float)); + memcpy(ng->nvafx_segment_buffers[1], ng->nvafx_segment_buffers[0], NVAFX_FRAME_SIZE * sizeof(float)); } /* Revert signal level adjustment, resample back if necessary */ if (ng->nvafx_resampler) { float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; - audio_resampler_resample( - ng->nvafx_resampler_back, (uint8_t **)output, - &out_frames, &ts_offset, - (const uint8_t **)ng->nvafx_segment_buffers, - NVAFX_FRAME_SIZE); + audio_resampler_resample(ng->nvafx_resampler_back, (uint8_t **)output, &out_frames, &ts_offset, + (const uint8_t **)ng->nvafx_segment_buffers, NVAFX_FRAME_SIZE); for (size_t i = 0; i < ng->channels; i++) { - for (ssize_t j = 0, - k = (ssize_t)out_frames - ng->frames; - j < (ssize_t)ng->frames; ++j, ++k) { + for (ssize_t j = 0, k = (ssize_t)out_frames - ng->frames; j < (ssize_t)ng->frames; ++j, ++k) { if (k >= 0) { ng->copy_buffers[i][j] = output[i][k]; } else { @@ -764,8 +700,7 @@ static inline void process_fx(struct nvidia_audio_data *ng) } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < NVAFX_FRAME_SIZE; ++j) { - ng->copy_buffers[i][j] = - ng->nvafx_segment_buffers[i][j]; + ng->copy_buffers[i][j] = ng->nvafx_segment_buffers[i][j]; } } } @@ -775,8 +710,7 @@ static inline void process(struct nvidia_audio_data *ng) { /* Pop from input deque */ for (size_t i = 0; i < ng->channels; i++) - deque_pop_front(&ng->input_buffers[i], ng->copy_buffers[i], - ng->frames * sizeof(float)); + deque_pop_front(&ng->input_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float)); if (ng->use_nvafx && nvidia_afx_loaded && ng->nvafx_initialized) { process_fx(ng); @@ -784,8 +718,7 @@ static inline void process(struct nvidia_audio_data *ng) /* Push to output deque */ for (size_t i = 0; i < ng->channels; i++) - deque_push_back(&ng->output_buffers[i], ng->copy_buffers[i], - ng->frames * sizeof(float)); + deque_push_back(&ng->output_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float)); } struct nv_audio_info { @@ -808,8 +741,7 @@ static void reset_data(struct nvidia_audio_data *ng) clear_deque(&ng->info_buffer); } -static struct obs_audio_data * -nvidia_audio_filter_audio(void *data, struct obs_audio_data *audio) +static struct obs_audio_data *nvidia_audio_filter_audio(void *data, struct obs_audio_data *audio) { struct nvidia_audio_data *ng = data; struct nv_audio_info info; @@ -826,8 +758,7 @@ nvidia_audio_filter_audio(void *data, struct obs_audio_data *audio) * audio data. Clear all circular buffers to prevent old audio data * from being processed as part of the new data. */ if (ng->last_timestamp) { - int64_t diff = llabs((int64_t)ng->last_timestamp - - (int64_t)audio->timestamp); + int64_t diff = llabs((int64_t)ng->last_timestamp - (int64_t)audio->timestamp); if (diff > 1000000000LL) reset_data(ng); @@ -844,8 +775,7 @@ nvidia_audio_filter_audio(void *data, struct obs_audio_data *audio) /* ----------------------------------------------- * push back current audio data to input deque */ for (size_t i = 0; i < ng->channels; i++) - deque_push_back(&ng->input_buffers[i], audio->data[i], - audio->frames * sizeof(float)); + deque_push_back(&ng->input_buffers[i], audio->data[i], audio->frames * sizeof(float)); /* ----------------------------------------------- * pop/process each 10ms segments, push back to output deque */ @@ -869,11 +799,9 @@ nvidia_audio_filter_audio(void *data, struct obs_audio_data *audio) da_resize(ng->output_data, out_size * ng->channels); for (size_t i = 0; i < ng->channels; i++) { - ng->output_audio.data[i] = - (uint8_t *)&ng->output_data.array[i * out_size]; + ng->output_audio.data[i] = (uint8_t *)&ng->output_data.array[i * out_size]; - deque_pop_front(&ng->output_buffers[i], - ng->output_audio.data[i], out_size); + deque_pop_front(&ng->output_buffers[i], ng->output_audio.data[i], out_size); } ng->output_audio.frames = info.frames; @@ -891,29 +819,21 @@ static obs_properties_t *nvidia_audio_properties(void *data) { obs_properties_t *ppts = obs_properties_create(); struct nvidia_audio_data *ng = (struct nvidia_audio_data *)data; - obs_property_t *method = obs_properties_add_list( - ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *method = + obs_properties_add_list(ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); if (ng->nvidia_sdk_dir_found) { - obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DENOISER, - S_METHOD_NVAFX_DENOISER); - obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB, - S_METHOD_NVAFX_DEREVERB); - obs_property_list_add_string( - method, TEXT_METHOD_NVAFX_DEREVERB_DENOISER, - S_METHOD_NVAFX_DEREVERB_DENOISER); - obs_property_t *slider = obs_properties_add_float_slider( - ppts, S_NVAFX_INTENSITY, TEXT_NVAFX_INTENSITY, 0.0f, - 1.0f, 0.01f); + obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DENOISER, S_METHOD_NVAFX_DENOISER); + obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB, S_METHOD_NVAFX_DEREVERB); + obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB_DENOISER, + S_METHOD_NVAFX_DEREVERB_DENOISER); + obs_property_t *slider = obs_properties_add_float_slider(ppts, S_NVAFX_INTENSITY, TEXT_NVAFX_INTENSITY, + 0.0f, 1.0f, 0.01f); unsigned int version = get_lib_version(); - obs_property_t *warning = obs_properties_add_text( - ppts, "deprecation", NULL, OBS_TEXT_INFO); + obs_property_t *warning = obs_properties_add_text(ppts, "deprecation", NULL, OBS_TEXT_INFO); if (version && version < MIN_AFX_SDK_VERSION) { - obs_property_text_set_info_type(warning, - OBS_TEXT_INFO_WARNING); - obs_property_set_long_description( - warning, TEXT_METHOD_NVAFX_DEPRECATION); + obs_property_text_set_info_type(warning, OBS_TEXT_INFO_WARNING); + obs_property_set_long_description(warning, TEXT_METHOD_NVAFX_DEPRECATION); } else { obs_property_set_visible(warning, 0); } diff --git a/plugins/nv-filters/nvidia-videofx-filter.c b/plugins/nv-filters/nvidia-videofx-filter.c index ad6cd646f..15a974dd9 100644 --- a/plugins/nv-filters/nvidia-videofx-filter.c +++ b/plugins/nv-filters/nvidia-videofx-filter.c @@ -6,9 +6,8 @@ #include "nvvfx-load.h" /* -------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[NVIDIA Video Effect: '%s'] " format, \ - obs_source_get_name(filter->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[NVIDIA Video Effect: '%s'] " format, obs_source_get_name(filter->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -130,27 +129,22 @@ static void nvvfx_filter_update(void *data, obs_data_t *settings) enum nvvfx_fx_id id = filter->filter_id; filter->threshold = (float)obs_data_get_double(settings, S_THRESHOLDFX); - filter->processing_interval = - (int)obs_data_get_int(settings, S_PROCESSING); + filter->processing_interval = (int)obs_data_get_int(settings, S_PROCESSING); float strength = (float)obs_data_get_double(settings, S_STRENGTH); if (id == S_FX_AIGS || id == S_FX_BG_BLUR) { - int mode = id == S_FX_BG_BLUR - ? (int)S_MODE_QUALITY - : (int)obs_data_get_int(settings, S_MODE); + int mode = id == S_FX_BG_BLUR ? (int)S_MODE_QUALITY : (int)obs_data_get_int(settings, S_MODE); if (filter->mode != mode) { filter->mode = mode; vfxErr = NvVFX_SetU32(filter->handle, NVVFX_MODE, mode); vfxErr = NvVFX_Load(filter->handle); if (NVCV_SUCCESS != vfxErr) - error("Error loading AI Greenscreen FX %i", - vfxErr); + error("Error loading AI Greenscreen FX %i", vfxErr); } } if (id == S_FX_BLUR || id == S_FX_BG_BLUR) { if (filter->strength != strength) { filter->strength = strength; - vfxErr = NvVFX_SetF32(filter->handle_blur, - NVVFX_STRENGTH, filter->strength); + vfxErr = NvVFX_SetF32(filter->handle_blur, NVVFX_STRENGTH, filter->strength); } vfxErr = NvVFX_Load(filter->handle_blur); if (NVCV_SUCCESS != vfxErr) @@ -196,8 +190,7 @@ static void nvvfx_filter_actual_destroy(void *data) if (filter->handle) { if (filter->stateObjectHandle) { - NvVFX_DeallocateState(filter->handle, - filter->stateObjectHandle); + NvVFX_DeallocateState(filter->handle, filter->stateObjectHandle); } NvVFX_DestroyEffect(filter->handle); } @@ -216,15 +209,13 @@ static void nvvfx_filter_actual_destroy(void *data) static void nvvfx_filter_destroy(void *data) { - obs_queue_task(OBS_TASK_GRAPHICS, nvvfx_filter_actual_destroy, data, - false); + obs_queue_task(OBS_TASK_GRAPHICS, nvvfx_filter_actual_destroy, data, false); } static void *log_nverror_destroy(struct nvvfx_data *filter, NvCV_Status vfxErr) { const char *errString = NvCV_GetErrorStringFromCode(vfxErr); - error("Error creating NVIDIA Video FX; error %i: %s", vfxErr, - errString); + error("Error creating NVIDIA Video FX; error %i: %s", vfxErr, errString); nvvfx_filter_destroy(filter); return NULL; } @@ -239,20 +230,16 @@ static bool nvvfx_filter_create_internal(struct nvvfx_data *filter) /* 1. Create FX */ switch (id) { case S_FX_AIGS: - vfxErr = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, - &filter->handle); + vfxErr = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, &filter->handle); break; case S_FX_BLUR: - vfxErr = NvVFX_CreateEffect(NVVFX_FX_BGBLUR, - &filter->handle_blur); + vfxErr = NvVFX_CreateEffect(NVVFX_FX_BGBLUR, &filter->handle_blur); break; case S_FX_BG_BLUR: - vfxErr = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, - &filter->handle); + vfxErr = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, &filter->handle); if (NVCV_SUCCESS != vfxErr) log_nverror_destroy(filter, vfxErr); - vfxErr = NvVFX_CreateEffect(NVVFX_FX_BGBLUR, - &filter->handle_blur); + vfxErr = NvVFX_CreateEffect(NVVFX_FX_BGBLUR, &filter->handle_blur); break; default: return false; @@ -272,13 +259,11 @@ static bool nvvfx_filter_create_internal(struct nvvfx_data *filter) nvvfx_get_sdk_path(buffer, MAX_PATH); size_t max_len = sizeof(buffer) / sizeof(char); snprintf(modelDir, max_len, "%s\\models", buffer); - vfxErr = NvVFX_SetString(filter->handle, NVVFX_MODEL_DIRECTORY, - modelDir); + vfxErr = NvVFX_SetString(filter->handle, NVVFX_MODEL_DIRECTORY, modelDir); vfxErr = NvVFX_CudaStreamCreate(&filter->stream); if (NVCV_SUCCESS != vfxErr) log_nverror_destroy(filter, vfxErr); - vfxErr = NvVFX_SetCudaStream(filter->handle, NVVFX_CUDA_STREAM, - filter->stream); + vfxErr = NvVFX_SetCudaStream(filter->handle, NVVFX_CUDA_STREAM, filter->stream); if (NVCV_SUCCESS != vfxErr) log_nverror_destroy(filter, vfxErr); } @@ -286,20 +271,16 @@ static bool nvvfx_filter_create_internal(struct nvvfx_data *filter) vfxErr = NvVFX_CudaStreamCreate(&filter->stream_blur); if (NVCV_SUCCESS != vfxErr) log_nverror_destroy(filter, vfxErr); - vfxErr = NvVFX_SetCudaStream(filter->handle_blur, - NVVFX_CUDA_STREAM, - filter->stream_blur); + vfxErr = NvVFX_SetCudaStream(filter->handle_blur, NVVFX_CUDA_STREAM, filter->stream_blur); if (NVCV_SUCCESS != vfxErr) log_nverror_destroy(filter, vfxErr); } return true; } -static void *nvvfx_filter_create(obs_data_t *settings, obs_source_t *context, - enum nvvfx_fx_id id) +static void *nvvfx_filter_create(obs_data_t *settings, obs_source_t *context, enum nvvfx_fx_id id) { - struct nvvfx_data *filter = - (struct nvvfx_data *)bzalloc(sizeof(*filter)); + struct nvvfx_data *filter = (struct nvvfx_data *)bzalloc(sizeof(*filter)); if (!nvvfx_loaded) { nvvfx_filter_destroy(filter); return NULL; @@ -329,8 +310,7 @@ static void *nvvfx_filter_create(obs_data_t *settings, obs_source_t *context, uint8_t minor = (filter->version >> 16) & 0x00ff; uint8_t build = (filter->version >> 8) & 0x0000ff; uint8_t revision = (filter->version >> 0) & 0x000000ff; - nvvfx_new_sdk = filter->version >= MIN_VFX_SDK_VERSION && - nvvfx_new_sdk; + nvvfx_new_sdk = filter->version >= MIN_VFX_SDK_VERSION && nvvfx_new_sdk; } #endif /* 1. Create FX */ @@ -339,38 +319,29 @@ static void *nvvfx_filter_create(obs_data_t *settings, obs_source_t *context, return NULL; /* 3. Load effect. */ - char *effect_path = obs_module_file( - id != S_FX_AIGS ? "rtx_blur.effect" : "rtx_greenscreen.effect"); + char *effect_path = obs_module_file(id != S_FX_AIGS ? "rtx_blur.effect" : "rtx_greenscreen.effect"); obs_enter_graphics(); filter->effect = gs_effect_create_from_file(effect_path, NULL); bfree(effect_path); if (filter->effect) { if (id == S_FX_AIGS) { - filter->mask_param = gs_effect_get_param_by_name( - filter->effect, "mask"); - filter->threshold_param = gs_effect_get_param_by_name( - filter->effect, "threshold"); + filter->mask_param = gs_effect_get_param_by_name(filter->effect, "mask"); + filter->threshold_param = gs_effect_get_param_by_name(filter->effect, "threshold"); } else { - filter->blur_param = gs_effect_get_param_by_name( - filter->effect, "blurred"); + filter->blur_param = gs_effect_get_param_by_name(filter->effect, "blurred"); } - filter->image_param = - gs_effect_get_param_by_name(filter->effect, "image"); + filter->image_param = gs_effect_get_param_by_name(filter->effect, "image"); - filter->multiplier_param = gs_effect_get_param_by_name( - filter->effect, "multiplier"); + filter->multiplier_param = gs_effect_get_param_by_name(filter->effect, "multiplier"); } obs_leave_graphics(); /* 4. Allocate state for the AIGS & background blur */ if (nvvfx_new_sdk && id != S_FX_BLUR) { - vfxErr = NvVFX_AllocateState(filter->handle, - &filter->stateObjectHandle); + vfxErr = NvVFX_AllocateState(filter->handle, &filter->stateObjectHandle); if (NVCV_SUCCESS != vfxErr) return log_nverror_destroy(filter, vfxErr); - vfxErr = NvVFX_SetStateObjectHandleArray( - filter->handle, NVVFX_STATE, - &filter->stateObjectHandle); + vfxErr = NvVFX_SetStateObjectHandleArray(filter->handle, NVVFX_STATE, &filter->stateObjectHandle); if (NVCV_SUCCESS != vfxErr) return log_nverror_destroy(filter, vfxErr); } @@ -385,8 +356,7 @@ static void *nvvfx_filter_create(obs_data_t *settings, obs_source_t *context, return filter; } -static void *nv_greenscreen_filter_create(obs_data_t *settings, - obs_source_t *context) +static void *nv_greenscreen_filter_create(obs_data_t *settings, obs_source_t *context) { return nvvfx_filter_create(settings, context, S_FX_AIGS); } @@ -396,8 +366,7 @@ static void *nv_blur_filter_create(obs_data_t *settings, obs_source_t *context) return nvvfx_filter_create(settings, context, S_FX_BLUR); } -static void *nv_background_blur_filter_create(obs_data_t *settings, - obs_source_t *context) +static void *nv_background_blur_filter_create(obs_data_t *settings, obs_source_t *context) { return nvvfx_filter_create(settings, context, S_FX_BG_BLUR); } @@ -417,8 +386,7 @@ static void nvvfx_filter_reset(void *data, calldata_t *calldata) } if (filter->handle) { if (filter->stateObjectHandle) { - NvVFX_DeallocateState(filter->handle, - filter->stateObjectHandle); + NvVFX_DeallocateState(filter->handle, filter->stateObjectHandle); } NvVFX_DestroyEffect(filter->handle); } @@ -439,12 +407,10 @@ static void nvvfx_filter_reset(void *data, calldata_t *calldata) vfxErr = NvVFX_Load(filter->handle); if (NVCV_SUCCESS != vfxErr) error("Error loading NVIDIA Video FX %i", vfxErr); - vfxErr = NvVFX_ResetState(filter->handle, - filter->stateObjectHandle); + vfxErr = NvVFX_ResetState(filter->handle, filter->stateObjectHandle); } if (filter->filter_id != S_FX_AIGS) { - vfxErr = NvVFX_SetF32(filter->handle_blur, NVVFX_STRENGTH, - filter->strength); + vfxErr = NvVFX_SetF32(filter->handle_blur, NVVFX_STRENGTH, filter->strength); if (NVCV_SUCCESS != vfxErr) error("Error loading NVIDIA Video FX %i", vfxErr); vfxErr = NvVFX_Load(filter->handle_blur); @@ -469,25 +435,20 @@ static bool create_alpha_texture(struct nvvfx_data *filter) if (filter->alpha_texture) { gs_texture_destroy(filter->alpha_texture); } - filter->alpha_texture = - gs_texture_create(width, height, GS_A8, 1, NULL, 0); + filter->alpha_texture = gs_texture_create(width, height, GS_A8, 1, NULL, 0); if (filter->alpha_texture == NULL) { error("Alpha texture couldn't be created"); return false; } - struct ID3D11Texture2D *d11texture = - (struct ID3D11Texture2D *)gs_texture_get_obj( - filter->alpha_texture); + struct ID3D11Texture2D *d11texture = (struct ID3D11Texture2D *)gs_texture_get_obj(filter->alpha_texture); /* 2. Create NvCVImage which will hold final alpha texture. */ if (!filter->dst_img) - NvCVImage_Create(width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, - NVCV_GPU, 1, &filter->dst_img); + NvCVImage_Create(width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->dst_img); vfxErr = NvCVImage_InitFromD3D11Texture(filter->dst_img, d11texture); if (vfxErr != NVCV_SUCCESS) { const char *errString = NvCV_GetErrorStringFromCode(vfxErr); - error("Error passing dst ID3D11Texture to img; error %i: %s", - vfxErr, errString); + error("Error passing dst ID3D11Texture to img; error %i: %s", vfxErr, errString); return false; } @@ -504,26 +465,20 @@ static bool create_blur_texture(struct nvvfx_data *filter) if (filter->blur_texture) { gs_texture_destroy(filter->blur_texture); } - filter->blur_texture = - gs_texture_create(width, height, GS_RGBA_UNORM, 1, NULL, 0); + filter->blur_texture = gs_texture_create(width, height, GS_RGBA_UNORM, 1, NULL, 0); if (filter->blur_texture == NULL) { error("Blur texture couldn't be created"); return false; } - struct ID3D11Texture2D *d11texture = - (struct ID3D11Texture2D *)gs_texture_get_obj( - filter->blur_texture); + struct ID3D11Texture2D *d11texture = (struct ID3D11Texture2D *)gs_texture_get_obj(filter->blur_texture); /* 2. Create NvCVImage which will hold final blur texture */ if (!filter->blur_dst_img) - NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, - NVCV_GPU, 1, &filter->blur_dst_img); - vfxErr = NvCVImage_InitFromD3D11Texture(filter->blur_dst_img, - d11texture); + NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->blur_dst_img); + vfxErr = NvCVImage_InitFromD3D11Texture(filter->blur_dst_img, d11texture); if (vfxErr != NVCV_SUCCESS) { const char *errString = NvCV_GetErrorStringFromCode(vfxErr); - error("Error passing dst ID3D11Texture to img; error %i: %s", - vfxErr, errString); + error("Error passing dst ID3D11Texture to img; error %i: %s", vfxErr, errString); return false; } @@ -534,8 +489,7 @@ static bool create_texrenders(struct nvvfx_data *filter) { if (filter->render) gs_texrender_destroy(filter->render); - filter->render = gs_texrender_create( - gs_get_format_from_space(filter->space), GS_ZS_NONE); + filter->render = gs_texrender_create(gs_get_format_from_space(filter->space), GS_ZS_NONE); if (!filter->render) { error("Failed to create render texrenderer"); return false; @@ -557,29 +511,21 @@ static bool init_blur_images(struct nvvfx_data *filter) uint32_t height = filter->height; /* 1. Create and allocate Blur BGR NvCVimage (blur FX dst) */ - NvCVImage_Create(width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, - NVCV_GPU, 1, &filter->blur_BGR_dst_img); - NvCVImage_Alloc(filter->blur_BGR_dst_img, width, height, NVCV_BGR, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Create(width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->blur_BGR_dst_img); + NvCVImage_Alloc(filter->blur_BGR_dst_img, width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); /* 2. Create dst NvCVImage */ if (filter->RGBA_dst_img) { - NvCVImage_Realloc(filter->RGBA_dst_img, width, height, - NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Realloc(filter->RGBA_dst_img, width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); } else { - NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, - NVCV_GPU, 1, &filter->RGBA_dst_img); - NvCVImage_Alloc(filter->RGBA_dst_img, width, height, NVCV_RGBA, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->RGBA_dst_img); + NvCVImage_Alloc(filter->RGBA_dst_img, width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); } /* 3. Set input & output images for nv blur FX */ - NvVFX_SetImage(filter->handle_blur, NVVFX_INPUT_IMAGE, - filter->BGR_src_img); - NvVFX_SetImage(filter->handle_blur, NVVFX_INPUT_IMAGE_1, - filter->A_dst_img); - NvVFX_SetImage(filter->handle_blur, NVVFX_OUTPUT_IMAGE, - filter->blur_BGR_dst_img); + NvVFX_SetImage(filter->handle_blur, NVVFX_INPUT_IMAGE, filter->BGR_src_img); + NvVFX_SetImage(filter->handle_blur, NVVFX_INPUT_IMAGE_1, filter->A_dst_img); + NvVFX_SetImage(filter->handle_blur, NVVFX_OUTPUT_IMAGE, filter->blur_BGR_dst_img); if (NvVFX_Load(filter->handle_blur) != NVCV_SUCCESS) { error("Error loading blur FX"); @@ -596,14 +542,12 @@ static void init_images(struct nvvfx_data *filter) uint32_t height = filter->height; /* 1. Create alpha texture & associated NvCVImage */ - if (filter->filter_id == S_FX_BG_BLUR || - filter->filter_id == S_FX_AIGS) { + if (filter->filter_id == S_FX_BG_BLUR || filter->filter_id == S_FX_AIGS) { if (!create_alpha_texture(filter)) goto fail; } /* 2. Create blur texture & associated NvCVImage */ - if (filter->filter_id == S_FX_BG_BLUR || - filter->filter_id == S_FX_BLUR) { + if (filter->filter_id == S_FX_BG_BLUR || filter->filter_id == S_FX_BLUR) { if (!create_blur_texture(filter)) goto fail; } @@ -613,55 +557,41 @@ static void init_images(struct nvvfx_data *filter) /* 4. Create and allocate BGR NvCVImage (alpha mask FX src) */ if (filter->BGR_src_img) { - NvCVImage_Realloc(filter->BGR_src_img, width, height, NVCV_BGR, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Realloc(filter->BGR_src_img, width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); } else { - NvCVImage_Create(width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, - NVCV_GPU, 1, &filter->BGR_src_img); - NvCVImage_Alloc(filter->BGR_src_img, width, height, NVCV_BGR, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Create(width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->BGR_src_img); + NvCVImage_Alloc(filter->BGR_src_img, width, height, NVCV_BGR, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); } /* 5. Create and allocate Alpha NvCVimage (mask fx dst). */ if (filter->A_dst_img) { - NvCVImage_Realloc(filter->A_dst_img, width, height, NVCV_A, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Realloc(filter->A_dst_img, width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); } else { - NvCVImage_Create(width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, - NVCV_GPU, 1, &filter->A_dst_img); - NvCVImage_Alloc(filter->A_dst_img, width, height, NVCV_A, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + NvCVImage_Create(width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->A_dst_img); + NvCVImage_Alloc(filter->A_dst_img, width, height, NVCV_A, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); } /* 6. Create stage NvCVImage which will be used as buffer for transfer */ - vfxErr = NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, - NVCV_CHUNKY, NVCV_GPU, 1, &filter->stage); - vfxErr = NvCVImage_Alloc(filter->stage, width, height, NVCV_RGBA, - NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); + vfxErr = NvCVImage_Create(width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1, &filter->stage); + vfxErr = NvCVImage_Alloc(filter->stage, width, height, NVCV_RGBA, NVCV_U8, NVCV_CHUNKY, NVCV_GPU, 1); if (vfxErr != NVCV_SUCCESS) { goto fail; } /* 7. Init blur images */ - if (filter->filter_id == S_FX_BLUR || - filter->filter_id == S_FX_BG_BLUR) { + if (filter->filter_id == S_FX_BLUR || filter->filter_id == S_FX_BG_BLUR) { if (!init_blur_images(filter)) goto fail; } /* 8. Pass settings for AIGS (AI Greenscreen) FX */ - if (filter->filter_id == S_FX_BG_BLUR || - filter->filter_id == S_FX_AIGS) { - NvVFX_SetImage(filter->handle, NVVFX_INPUT_IMAGE, - filter->BGR_src_img); - NvVFX_SetImage(filter->handle, NVVFX_OUTPUT_IMAGE, - filter->A_dst_img); + if (filter->filter_id == S_FX_BG_BLUR || filter->filter_id == S_FX_AIGS) { + NvVFX_SetImage(filter->handle, NVVFX_INPUT_IMAGE, filter->BGR_src_img); + NvVFX_SetImage(filter->handle, NVVFX_OUTPUT_IMAGE, filter->A_dst_img); if (filter->width) - NvVFX_SetU32(filter->handle, NVVFX_MAX_INPUT_WIDTH, - filter->width); + NvVFX_SetU32(filter->handle, NVVFX_MAX_INPUT_WIDTH, filter->width); if (filter->height) - NvVFX_SetU32(filter->handle, NVVFX_MAX_INPUT_HEIGHT, - filter->height); + NvVFX_SetU32(filter->handle, NVVFX_MAX_INPUT_HEIGHT, filter->height); vfxErr = NvVFX_Load(filter->handle); if (NVCV_SUCCESS != vfxErr) error("Error loading AI Greenscreen FX %i", vfxErr); @@ -694,29 +624,24 @@ static bool process_texture(struct nvvfx_data *filter) default: process_stream = NULL; } - NvCV_Status vfxErr = - NvCVImage_MapResource(filter->src_img, process_stream); + NvCV_Status vfxErr = NvCVImage_MapResource(filter->src_img, process_stream); if (vfxErr != NVCV_SUCCESS) { const char *errString = NvCV_GetErrorStringFromCode(vfxErr); - error("Error mapping resource for source texture; error %i : %s", - vfxErr, errString); + error("Error mapping resource for source texture; error %i : %s", vfxErr, errString); goto fail; } /* 2. Convert to BGR. */ - vfxErr = NvCVImage_Transfer(filter->src_img, filter->BGR_src_img, 1.0f, - filter->stream_blur, filter->stage); + vfxErr = NvCVImage_Transfer(filter->src_img, filter->BGR_src_img, 1.0f, filter->stream_blur, filter->stage); if (vfxErr != NVCV_SUCCESS) { const char *errString = NvCV_GetErrorStringFromCode(vfxErr); - error("Error converting src to BGR img; error %i: %s", vfxErr, - errString); + error("Error converting src to BGR img; error %i: %s", vfxErr, errString); goto fail; } vfxErr = NvCVImage_UnmapResource(filter->src_img, process_stream); if (vfxErr != NVCV_SUCCESS) { const char *errString = NvCV_GetErrorStringFromCode(vfxErr); - error("Error unmapping resource for src texture; error %i: %s", - vfxErr, errString); + error("Error unmapping resource for src texture; error %i: %s", vfxErr, errString); goto fail; } @@ -724,10 +649,8 @@ static bool process_texture(struct nvvfx_data *filter) if (id != S_FX_BLUR) { vfxErr = NvVFX_Run(filter->handle, 1); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error running the AIGS FX; error %i: %s", vfxErr, - errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error running the AIGS FX; error %i: %s", vfxErr, errString); if (vfxErr == NVCV_ERR_CUDA) nvvfx_filter_reset(filter, NULL); } @@ -738,82 +661,60 @@ static bool process_texture(struct nvvfx_data *filter) /* 4a. Run BLUR FX except for AIGS */ vfxErr = NvVFX_Run(filter->handle_blur, 1); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error running the BLUR FX; error %i: %s", vfxErr, - errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error running the BLUR FX; error %i: %s", vfxErr, errString); if (vfxErr == NVCV_ERR_CUDA) nvvfx_filter_reset(filter, NULL); } /* 4b. Transfer blur result to an intermediate dst [RGBA, chunky, u8] */ - vfxErr = NvCVImage_Transfer(filter->blur_BGR_dst_img, - filter->RGBA_dst_img, 1.0f, - filter->stream_blur, filter->stage); + vfxErr = NvCVImage_Transfer(filter->blur_BGR_dst_img, filter->RGBA_dst_img, 1.0f, filter->stream_blur, + filter->stage); if (vfxErr != NVCV_SUCCESS) { - error("Error transferring blurred to intermediate img [RGBA, chunky, u8], error %i, ", - vfxErr); + error("Error transferring blurred to intermediate img [RGBA, chunky, u8], error %i, ", vfxErr); goto fail; } /* 5. Map blur dst texture before transfer from dst img provided by FX */ - vfxErr = NvCVImage_MapResource(filter->blur_dst_img, - filter->stream_blur); + vfxErr = NvCVImage_MapResource(filter->blur_dst_img, filter->stream_blur); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error mapping resource for dst texture; error %i: %s", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error mapping resource for dst texture; error %i: %s", vfxErr, errString); goto fail; } - vfxErr = NvCVImage_Transfer(filter->RGBA_dst_img, - filter->blur_dst_img, 1.0f, - filter->stream_blur, filter->stage); + vfxErr = NvCVImage_Transfer(filter->RGBA_dst_img, filter->blur_dst_img, 1.0f, filter->stream_blur, + filter->stage); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error transferring mask to alpha texture; error %i: %s ", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error transferring mask to alpha texture; error %i: %s ", vfxErr, errString); goto fail; } - vfxErr = NvCVImage_UnmapResource(filter->blur_dst_img, - filter->stream_blur); + vfxErr = NvCVImage_UnmapResource(filter->blur_dst_img, filter->stream_blur); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error unmapping resource for dst texture; error %i: %s", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error unmapping resource for dst texture; error %i: %s", vfxErr, errString); goto fail; } } else { /* 4. Map dst texture before transfer from dst img provided by AIGS FX */ vfxErr = NvCVImage_MapResource(filter->dst_img, filter->stream); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error mapping resource for dst texture; error %i: %s", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error mapping resource for dst texture; error %i: %s", vfxErr, errString); goto fail; } - vfxErr = NvCVImage_Transfer(filter->A_dst_img, filter->dst_img, - 1.0f, filter->stream, - filter->stage); + vfxErr = NvCVImage_Transfer(filter->A_dst_img, filter->dst_img, 1.0f, filter->stream, filter->stage); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error transferring mask to alpha texture; error %i: %s ", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error transferring mask to alpha texture; error %i: %s ", vfxErr, errString); goto fail; } - vfxErr = NvCVImage_UnmapResource(filter->dst_img, - filter->stream); + vfxErr = NvCVImage_UnmapResource(filter->dst_img, filter->stream); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error unmapping resource for dst texture; error %i: %s", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error unmapping resource for dst texture; error %i: %s", vfxErr, errString); goto fail; } } @@ -824,8 +725,7 @@ fail: return false; } -static struct obs_source_frame * -nvvfx_filter_video(void *data, struct obs_source_frame *frame) +static struct obs_source_frame *nvvfx_filter_video(void *data, struct obs_source_frame *frame) { struct nvvfx_data *filter = (struct nvvfx_data *)data; filter->got_new_frame = true; @@ -881,10 +781,8 @@ static void nvvfx_filter_tick(void *data, float t) filter->processed_frame = false; } -static const char * -get_tech_name_and_multiplier(enum gs_color_space current_space, - enum gs_color_space source_space, - float *multiplier) +static const char *get_tech_name_and_multiplier(enum gs_color_space current_space, enum gs_color_space source_space, + float *multiplier) { const char *tech_name = "Draw"; *multiplier = 1.f; @@ -928,33 +826,24 @@ static void draw_greenscreen_blur(struct nvvfx_data *filter, bool has_blur) { const enum gs_color_space source_space = filter->space; float multiplier; - const char *technique = get_tech_name_and_multiplier( - gs_get_color_space(), source_space, &multiplier); - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { + const char *technique = get_tech_name_and_multiplier(gs_get_color_space(), source_space, &multiplier); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { if (has_blur) { - gs_effect_set_texture_srgb(filter->blur_param, - filter->blur_texture); + gs_effect_set_texture_srgb(filter->blur_param, filter->blur_texture); } else { - gs_effect_set_texture(filter->mask_param, - filter->alpha_texture); - gs_effect_set_float(filter->threshold_param, - filter->threshold); + gs_effect_set_texture(filter->mask_param, filter->alpha_texture); + gs_effect_set_float(filter->threshold_param, filter->threshold); } - gs_effect_set_texture_srgb( - filter->image_param, - gs_texrender_get_texture(filter->render)); + gs_effect_set_texture_srgb(filter->image_param, gs_texrender_get_texture(filter->render)); gs_effect_set_float(filter->multiplier_param, multiplier); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_tech_end( - filter->context, filter->effect, 0, 0, technique); + obs_source_process_filter_tech_end(filter->context, filter->effect, 0, 0, technique); gs_blend_state_pop(); } @@ -987,8 +876,7 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) if (parent && !filter->handler) { filter->handler = obs_source_get_signal_handler(parent); - signal_handler_connect(filter->handler, "update", - nvvfx_filter_reset, filter); + signal_handler_connect(filter->handler, "update", nvvfx_filter_reset, filter); } /* 1. Render to retrieve texture. */ @@ -1009,8 +897,8 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) GS_CS_709_EXTENDED, }; - const enum gs_color_space source_space = obs_source_get_color_space( - target, OBS_COUNTOF(preferred_spaces), preferred_spaces); + const enum gs_color_space source_space = + obs_source_get_color_space(target, OBS_COUNTOF(preferred_spaces), preferred_spaces); if (filter->space != source_space) { filter->space = source_space; @@ -1023,14 +911,12 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO); - if (gs_texrender_begin_with_color_space(render, filter->width, - filter->height, source_space)) { + if (gs_texrender_begin_with_color_space(render, filter->width, filter->height, source_space)) { struct vec4 clear_color; vec4_zero(&clear_color); gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0); - gs_ortho(0.0f, (float)filter->width, 0.0f, - (float)filter->height, -100.0f, 100.0f); + gs_ortho(0.0f, (float)filter->width, 0.0f, (float)filter->height, -100.0f, 100.0f); if (target == parent && !custom_draw && !async) obs_source_default_render(target); @@ -1041,15 +927,12 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) gs_texrender_t *const render_unorm = filter->render_unorm; gs_texrender_reset(render_unorm); - if (gs_texrender_begin_with_color_space( - render_unorm, filter->width, filter->height, - GS_CS_SRGB)) { + if (gs_texrender_begin_with_color_space(render_unorm, filter->width, filter->height, GS_CS_SRGB)) { const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(true); gs_enable_blending(false); - gs_ortho(0.0f, (float)filter->width, 0.0f, - (float)filter->height, -100.0f, 100.0f); + gs_ortho(0.0f, (float)filter->width, 0.0f, (float)filter->height, -100.0f, 100.0f); const char *tech_name = "ConvertUnorm"; float multiplier = 1.f; @@ -1059,26 +942,18 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) tech_name = "ConvertUnormTonemap"; break; case GS_CS_709_SCRGB: - tech_name = - "ConvertUnormMultiplyTonemap"; - multiplier = - 80.0f / - obs_get_video_sdr_white_level(); + tech_name = "ConvertUnormMultiplyTonemap"; + multiplier = 80.0f / obs_get_video_sdr_white_level(); } } else { switch (source_space) { case GS_CS_709_SCRGB: tech_name = "ConvertUnormMultiply"; - multiplier = - 80.0f / - obs_get_video_sdr_white_level(); + multiplier = 80.0f / obs_get_video_sdr_white_level(); } } - gs_effect_set_texture_srgb( - filter->image_param, - gs_texrender_get_texture(render)); - gs_effect_set_float(filter->multiplier_param, - multiplier); + gs_effect_set_texture_srgb(filter->image_param, gs_texrender_get_texture(render)); + gs_effect_set_float(filter->multiplier_param, multiplier); while (gs_effect_loop(filter->effect, tech_name)) { gs_draw(GS_TRIS, 0, 3); @@ -1096,36 +971,27 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) /* 2. Initialize src_texture (only at startup or reset) */ if (!filter->initial_render) { struct ID3D11Texture2D *d11texture2 = - (struct ID3D11Texture2D *)gs_texture_get_obj( - gs_texrender_get_texture(filter->render_unorm)); + (struct ID3D11Texture2D *)gs_texture_get_obj(gs_texrender_get_texture(filter->render_unorm)); if (!d11texture2) { error("Couldn't retrieve d3d11texture2d."); return; } if (!filter->src_img) { - vfxErr = NvCVImage_Create(filter->width, filter->height, - NVCV_BGRA, NVCV_U8, - NVCV_CHUNKY, NVCV_GPU, 1, - &filter->src_img); + vfxErr = NvCVImage_Create(filter->width, filter->height, NVCV_BGRA, NVCV_U8, NVCV_CHUNKY, + NVCV_GPU, 1, &filter->src_img); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error creating src img; error %i: %s", - vfxErr, errString); - os_atomic_set_bool(&filter->processing_stop, - true); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error creating src img; error %i: %s", vfxErr, errString); + os_atomic_set_bool(&filter->processing_stop, true); return; } } - vfxErr = NvCVImage_InitFromD3D11Texture(filter->src_img, - d11texture2); + vfxErr = NvCVImage_InitFromD3D11Texture(filter->src_img, d11texture2); if (vfxErr != NVCV_SUCCESS) { - const char *errString = - NvCV_GetErrorStringFromCode(vfxErr); - error("Error passing src ID3D11Texture to img; error %i: %s", - vfxErr, errString); + const char *errString = NvCV_GetErrorStringFromCode(vfxErr); + error("Error passing src ID3D11Texture to img; error %i: %s", vfxErr, errString); os_atomic_set_bool(&filter->processing_stop, true); return; } @@ -1138,9 +1004,7 @@ static void nvvfx_filter_render(void *data, gs_effect_t *effect, bool has_blur) bool draw = true; if (!async || filter->got_new_frame) { if (!has_blur) { - if (filter->processing_counter % - filter->processing_interval == - 0) { + if (filter->processing_counter % filter->processing_interval == 0) { draw = process_texture(filter); filter->processing_counter = 1; } else { @@ -1172,9 +1036,8 @@ static void nv_blur_filter_render(void *data, gs_effect_t *effect) nvvfx_filter_render(data, effect, true); } -static enum gs_color_space -nvvfx_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space nvvfx_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { const enum gs_color_space potential_spaces[] = { GS_CS_SRGB, @@ -1184,8 +1047,7 @@ nvvfx_filter_get_color_space(void *data, size_t count, struct nvvfx_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); enum gs_color_space space = source_space; for (size_t i = 0; i < count; ++i) { @@ -1202,26 +1064,21 @@ static obs_properties_t *nvvfx_filter_properties(void *data) struct nvvfx_data *filter = (struct nvvfx_data *)data; obs_properties_t *props = obs_properties_create(); if (filter->filter_id != S_FX_AIGS) { - obs_property_t *strength = obs_properties_add_float_slider( - props, S_STRENGTH, TEXT_MODE_BLUR_STRENGTH, 0, 1, 0.05); + obs_property_t *strength = + obs_properties_add_float_slider(props, S_STRENGTH, TEXT_MODE_BLUR_STRENGTH, 0, 1, 0.05); } else { - obs_property_t *mode = obs_properties_add_list( - props, S_MODE, TEXT_MODE, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(mode, TEXT_MODE_QUALITY, - S_MODE_QUALITY); + obs_property_t *mode = + obs_properties_add_list(props, S_MODE, TEXT_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(mode, TEXT_MODE_QUALITY, S_MODE_QUALITY); obs_property_list_add_int(mode, TEXT_MODE_PERF, S_MODE_PERF); - obs_property_t *threshold = obs_properties_add_float_slider( - props, S_THRESHOLDFX, TEXT_MODE_THRESHOLD, 0, 1, 0.05); - obs_property_t *partial = obs_properties_add_int_slider( - props, S_PROCESSING, TEXT_PROCESSING, 1, 4, 1); - obs_property_set_long_description(partial, - TEXT_PROCESSING_HINT); + obs_property_t *threshold = + obs_properties_add_float_slider(props, S_THRESHOLDFX, TEXT_MODE_THRESHOLD, 0, 1, 0.05); + obs_property_t *partial = obs_properties_add_int_slider(props, S_PROCESSING, TEXT_PROCESSING, 1, 4, 1); + obs_property_set_long_description(partial, TEXT_PROCESSING_HINT); } unsigned int version = get_lib_version(); if (version && version < MIN_VFX_SDK_VERSION) { - obs_property_t *warning = obs_properties_add_text( - props, "deprecation", NULL, OBS_TEXT_INFO); + obs_property_t *warning = obs_properties_add_text(props, "deprecation", NULL, OBS_TEXT_INFO); obs_property_text_set_info_type(warning, OBS_TEXT_INFO_WARNING); obs_property_set_long_description(warning, TEXT_DEPRECATION); } @@ -1232,8 +1089,7 @@ static obs_properties_t *nvvfx_filter_properties(void *data) static void nvvfx_filter_defaults(obs_data_t *settings) { obs_data_set_default_int(settings, S_MODE, S_MODE_QUALITY); - obs_data_set_default_double(settings, S_THRESHOLDFX, - S_THRESHOLDFX_DEFAULT); + obs_data_set_default_double(settings, S_THRESHOLDFX, S_THRESHOLDFX_DEFAULT); obs_data_set_default_int(settings, S_PROCESSING, 1); obs_data_set_default_double(settings, S_STRENGTH, S_STRENGTH_DEFAULT); } @@ -1247,39 +1103,33 @@ bool load_nvidia_vfx(void) uint8_t build = (version >> 8) & 0x0000ff; uint8_t revision = (version >> 0) & 0x000000ff; if (version) { - blog(LOG_INFO, - "[NVIDIA VIDEO FX]: NVIDIA VIDEO FX version: %i.%i.%i.%i", - major, minor, build, revision); + blog(LOG_INFO, "[NVIDIA VIDEO FX]: NVIDIA VIDEO FX version: %i.%i.%i.%i", major, minor, build, + revision); if (version < MIN_VFX_SDK_VERSION) { blog(LOG_INFO, "[NVIDIA VIDEO FX]: NVIDIA VIDEO Effects SDK is outdated. Please update both audio & video SDK."); } } if (!load_nv_vfx_libs()) { - blog(LOG_INFO, - "[NVIDIA VIDEO FX]: FX disabled, redistributable not found or could not be loaded."); + blog(LOG_INFO, "[NVIDIA VIDEO FX]: FX disabled, redistributable not found or could not be loaded."); return false; } -#define LOAD_SYM_FROM_LIB(sym, lib, dll) \ - if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ - DWORD err = GetLastError(); \ - printf("[NVIDIA VIDEO FX]: Couldn't load " #sym " from " dll \ - ": %lu (0x%lx)", \ - err, err); \ - release_nv_vfx(); \ - goto unload_everything; \ +#define LOAD_SYM_FROM_LIB(sym, lib, dll) \ + if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ + DWORD err = GetLastError(); \ + printf("[NVIDIA VIDEO FX]: Couldn't load " #sym " from " dll ": %lu (0x%lx)", err, err); \ + release_nv_vfx(); \ + goto unload_everything; \ } -#define LOAD_SYM_FROM_LIB2(sym, lib, dll) \ - if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ - DWORD err = GetLastError(); \ - printf("[NVIDIA VIDEO FX]: Couldn't load " #sym " from " dll \ - ": %lu (0x%lx)", \ - err, err); \ - nvvfx_new_sdk = false; \ - } else { \ - nvvfx_new_sdk = true; \ +#define LOAD_SYM_FROM_LIB2(sym, lib, dll) \ + if (!(sym = (sym##_t)GetProcAddress(lib, #sym))) { \ + DWORD err = GetLastError(); \ + printf("[NVIDIA VIDEO FX]: Couldn't load " #sym " from " dll ": %lu (0x%lx)", err, err); \ + nvvfx_new_sdk = false; \ + } else { \ + nvvfx_new_sdk = true; \ } #define LOAD_SYM(sym) LOAD_SYM_FROM_LIB(sym, nv_videofx, "NVVideoEffects.dll") @@ -1353,8 +1203,7 @@ bool load_nvidia_vfx(void) LOAD_SYM(NvVFX_DeallocateState); LOAD_SYM(NvVFX_ResetState); if (!nvvfx_new_sdk) { - blog(LOG_INFO, - "[NVIDIA VIDEO FX]: sdk loaded but old redistributable detected; please upgrade."); + blog(LOG_INFO, "[NVIDIA VIDEO FX]: sdk loaded but old redistributable detected; please upgrade."); } #undef LOAD_SYM @@ -1365,11 +1214,9 @@ bool load_nvidia_vfx(void) err = NvVFX_CreateEffect(NVVFX_FX_GREEN_SCREEN, &h); if (err != NVCV_SUCCESS) { if (err == NVCV_ERR_UNSUPPORTEDGPU) { - blog(LOG_INFO, - "[NVIDIA VIDEO FX]: disabled, unsupported GPU"); + blog(LOG_INFO, "[NVIDIA VIDEO FX]: disabled, unsupported GPU"); } else { - blog(LOG_ERROR, "[NVIDIA VIDEO FX]: disabled, error %i", - err); + blog(LOG_ERROR, "[NVIDIA VIDEO FX]: disabled, error %i", err); } goto unload_everything; } @@ -1380,8 +1227,7 @@ bool load_nvidia_vfx(void) unload_everything: nvvfx_loaded = false; - blog(LOG_INFO, - "[NVIDIA VIDEO FX]: disabled, redistributable not found"); + blog(LOG_INFO, "[NVIDIA VIDEO FX]: disabled, redistributable not found"); release_nv_vfx(); return false; } diff --git a/plugins/nv-filters/nvvfx-load.h b/plugins/nv-filters/nvvfx-load.h index 3ef4c0587..ff8bef7f3 100644 --- a/plugins/nv-filters/nvvfx-load.h +++ b/plugins/nv-filters/nvvfx-load.h @@ -47,78 +47,53 @@ static HMODULE nv_cuda = NULL; //! Status codes returned from APIs. typedef enum NvCV_Status { - NVCV_SUCCESS = 0, //!< The procedure returned successfully. - NVCV_ERR_GENERAL = -1, //!< An otherwise unspecified error has occurred. - NVCV_ERR_UNIMPLEMENTED = - -2, //!< The requested feature is not yet implemented. - NVCV_ERR_MEMORY = - -3, //!< There is not enough memory for the requested operation. - NVCV_ERR_EFFECT = -4, //!< An invalid effect handle has been supplied. - NVCV_ERR_SELECTOR = - -5, //!< The given parameter selector is not valid in this effect filter. - NVCV_ERR_BUFFER = -6, //!< An image buffer has not been specified. - NVCV_ERR_PARAMETER = - -7, //!< An invalid parameter value has been supplied for this effect+selector. - NVCV_ERR_MISMATCH = - -8, //!< Some parameters are not appropriately matched. - NVCV_ERR_PIXELFORMAT = - -9, //!< The specified pixel format is not accommodated. - NVCV_ERR_MODEL = -10, //!< Error while loading the TRT model. - NVCV_ERR_LIBRARY = -11, //!< Error loading the dynamic library. - NVCV_ERR_INITIALIZATION = - -12, //!< The effect has not been properly initialized. - NVCV_ERR_FILE = -13, //!< The file could not be found. - NVCV_ERR_FEATURENOTFOUND = -14, //!< The requested feature was not found - NVCV_ERR_MISSINGINPUT = -15, //!< A required parameter was not set - NVCV_ERR_RESOLUTION = - -16, //!< The specified image resolution is not supported. - NVCV_ERR_UNSUPPORTEDGPU = -17, //!< The GPU is not supported - NVCV_ERR_WRONGGPU = -18, //!< The current GPU is not the one selected. - NVCV_ERR_UNSUPPORTEDDRIVER = - -19, //!< The currently installed graphics driver is not supported - NVCV_ERR_MODELDEPENDENCIES = - -20, //!< There is no model with dependencies that match this system - NVCV_ERR_PARSE = - -21, //!< There has been a parsing or syntax error while reading a file - NVCV_ERR_MODELSUBSTITUTION = - -22, //!< The specified model does not exist and has been substituted. - NVCV_ERR_READ = -23, //!< An error occurred while reading a file. - NVCV_ERR_WRITE = -24, //!< An error occurred while writing a file. - NVCV_ERR_PARAMREADONLY = -25, //!< The selected parameter is read-only. - NVCV_ERR_TRT_ENQUEUE = -26, //!< TensorRT enqueue failed. - NVCV_ERR_TRT_BINDINGS = -27, //!< Unexpected TensorRT bindings. - NVCV_ERR_TRT_CONTEXT = - -28, //!< An error occurred while creating a TensorRT context. - NVCV_ERR_TRT_INFER = - -29, ///< The was a problem creating the inference engine. - NVCV_ERR_TRT_ENGINE = - -30, ///< There was a problem deserializing the inference runtime engine. - NVCV_ERR_NPP = -31, //!< An error has occurred in the NPP library. - NVCV_ERR_CONFIG = - -32, //!< No suitable model exists for the specified parameter configuration. + NVCV_SUCCESS = 0, //!< The procedure returned successfully. + NVCV_ERR_GENERAL = -1, //!< An otherwise unspecified error has occurred. + NVCV_ERR_UNIMPLEMENTED = -2, //!< The requested feature is not yet implemented. + NVCV_ERR_MEMORY = -3, //!< There is not enough memory for the requested operation. + NVCV_ERR_EFFECT = -4, //!< An invalid effect handle has been supplied. + NVCV_ERR_SELECTOR = -5, //!< The given parameter selector is not valid in this effect filter. + NVCV_ERR_BUFFER = -6, //!< An image buffer has not been specified. + NVCV_ERR_PARAMETER = -7, //!< An invalid parameter value has been supplied for this effect+selector. + NVCV_ERR_MISMATCH = -8, //!< Some parameters are not appropriately matched. + NVCV_ERR_PIXELFORMAT = -9, //!< The specified pixel format is not accommodated. + NVCV_ERR_MODEL = -10, //!< Error while loading the TRT model. + NVCV_ERR_LIBRARY = -11, //!< Error loading the dynamic library. + NVCV_ERR_INITIALIZATION = -12, //!< The effect has not been properly initialized. + NVCV_ERR_FILE = -13, //!< The file could not be found. + NVCV_ERR_FEATURENOTFOUND = -14, //!< The requested feature was not found + NVCV_ERR_MISSINGINPUT = -15, //!< A required parameter was not set + NVCV_ERR_RESOLUTION = -16, //!< The specified image resolution is not supported. + NVCV_ERR_UNSUPPORTEDGPU = -17, //!< The GPU is not supported + NVCV_ERR_WRONGGPU = -18, //!< The current GPU is not the one selected. + NVCV_ERR_UNSUPPORTEDDRIVER = -19, //!< The currently installed graphics driver is not supported + NVCV_ERR_MODELDEPENDENCIES = -20, //!< There is no model with dependencies that match this system + NVCV_ERR_PARSE = -21, //!< There has been a parsing or syntax error while reading a file + NVCV_ERR_MODELSUBSTITUTION = -22, //!< The specified model does not exist and has been substituted. + NVCV_ERR_READ = -23, //!< An error occurred while reading a file. + NVCV_ERR_WRITE = -24, //!< An error occurred while writing a file. + NVCV_ERR_PARAMREADONLY = -25, //!< The selected parameter is read-only. + NVCV_ERR_TRT_ENQUEUE = -26, //!< TensorRT enqueue failed. + NVCV_ERR_TRT_BINDINGS = -27, //!< Unexpected TensorRT bindings. + NVCV_ERR_TRT_CONTEXT = -28, //!< An error occurred while creating a TensorRT context. + NVCV_ERR_TRT_INFER = -29, ///< The was a problem creating the inference engine. + NVCV_ERR_TRT_ENGINE = -30, ///< There was a problem deserializing the inference runtime engine. + NVCV_ERR_NPP = -31, //!< An error has occurred in the NPP library. + NVCV_ERR_CONFIG = -32, //!< No suitable model exists for the specified parameter configuration. NVCV_ERR_DIRECT3D = -99, //!< A Direct3D error has occurred. - NVCV_ERR_CUDA_BASE = -100, //!< CUDA errors are offset from this value. - NVCV_ERR_CUDA_VALUE = - -101, //!< A CUDA parameter is not within the acceptable range. - NVCV_ERR_CUDA_MEMORY = - -102, //!< There is not enough CUDA memory for the requested operation. - NVCV_ERR_CUDA_PITCH = - -112, //!< A CUDA pitch is not within the acceptable range. - NVCV_ERR_CUDA_INIT = - -127, //!< The CUDA driver and runtime could not be initialized. - NVCV_ERR_CUDA_LAUNCH = -819, //!< The CUDA kernel launch has failed. - NVCV_ERR_CUDA_KERNEL = - -309, //!< No suitable kernel image is available for the device. - NVCV_ERR_CUDA_DRIVER = - -135, //!< The installed NVIDIA CUDA driver is older than the CUDA runtime library. - NVCV_ERR_CUDA_UNSUPPORTED = - -901, //!< The CUDA operation is not supported on the current system or device. - NVCV_ERR_CUDA_ILLEGAL_ADDRESS = - -800, //!< CUDA tried to load or store on an invalid memory address. - NVCV_ERR_CUDA = - -1099, //!< An otherwise unspecified CUDA error has been reported. + NVCV_ERR_CUDA_BASE = -100, //!< CUDA errors are offset from this value. + NVCV_ERR_CUDA_VALUE = -101, //!< A CUDA parameter is not within the acceptable range. + NVCV_ERR_CUDA_MEMORY = -102, //!< There is not enough CUDA memory for the requested operation. + NVCV_ERR_CUDA_PITCH = -112, //!< A CUDA pitch is not within the acceptable range. + NVCV_ERR_CUDA_INIT = -127, //!< The CUDA driver and runtime could not be initialized. + NVCV_ERR_CUDA_LAUNCH = -819, //!< The CUDA kernel launch has failed. + NVCV_ERR_CUDA_KERNEL = -309, //!< No suitable kernel image is available for the device. + NVCV_ERR_CUDA_DRIVER = -135, //!< The installed NVIDIA CUDA driver is older than the CUDA runtime library. + NVCV_ERR_CUDA_UNSUPPORTED = -901, //!< The CUDA operation is not supported on the current system or device. + NVCV_ERR_CUDA_ILLEGAL_ADDRESS = -800, //!< CUDA tried to load or store on an invalid memory address. + NVCV_ERR_CUDA = -1099, //!< An otherwise unspecified CUDA error has been reported. } NvCV_Status; /** Filter selectors */ @@ -137,27 +112,23 @@ typedef enum NvCV_Status { #define NVVFX_OUTPUT_IMAGE_0 "DstImage0" #define NVVFX_OUTPUT_IMAGE NVVFX_OUTPUT_IMAGE_0 #define NVVFX_MODEL_DIRECTORY "ModelDir" -#define NVVFX_CUDA_STREAM "CudaStream" //!< The CUDA stream to use -#define NVVFX_CUDA_GRAPH "CudaGraph" //!< Enable CUDA graph to use -#define NVVFX_INFO "Info" //!< Get info about the effects -#define NVVFX_MAX_INPUT_WIDTH \ - "MaxInputWidth" //!< Maximum width of the input supported -#define NVVFX_MAX_INPUT_HEIGHT \ - "MaxInputHeight" //!< Maximum height of the input supported -#define NVVFX_MAX_NUMBER_STREAMS \ - "MaxNumberStreams" //!< Maximum number of concurrent input streams -#define NVVFX_SCALE "Scale" //!< Scale factor -#define NVVFX_STRENGTH "Strength" //!< Strength for different filters -#define NVVFX_STRENGTH_LEVELS "StrengthLevels" //!< Number of strength levels -#define NVVFX_MODE "Mode" //!< Mode for different filters -#define NVVFX_TEMPORAL "Temporal" //!< Temporal mode: 0=image, 1=video -#define NVVFX_GPU "GPU" //!< Preferred GPU (optional) -#define NVVFX_BATCH_SIZE "BatchSize" //!< Batch Size (default 1) +#define NVVFX_CUDA_STREAM "CudaStream" //!< The CUDA stream to use +#define NVVFX_CUDA_GRAPH "CudaGraph" //!< Enable CUDA graph to use +#define NVVFX_INFO "Info" //!< Get info about the effects +#define NVVFX_MAX_INPUT_WIDTH "MaxInputWidth" //!< Maximum width of the input supported +#define NVVFX_MAX_INPUT_HEIGHT "MaxInputHeight" //!< Maximum height of the input supported +#define NVVFX_MAX_NUMBER_STREAMS "MaxNumberStreams" //!< Maximum number of concurrent input streams +#define NVVFX_SCALE "Scale" //!< Scale factor +#define NVVFX_STRENGTH "Strength" //!< Strength for different filters +#define NVVFX_STRENGTH_LEVELS "StrengthLevels" //!< Number of strength levels +#define NVVFX_MODE "Mode" //!< Mode for different filters +#define NVVFX_TEMPORAL "Temporal" //!< Temporal mode: 0=image, 1=video +#define NVVFX_GPU "GPU" //!< Preferred GPU (optional) +#define NVVFX_BATCH_SIZE "BatchSize" //!< Batch Size (default 1) #define NVVFX_MODEL_BATCH "ModelBatch" -#define NVVFX_STATE "State" //!< State variable -#define NVVFX_STATE_SIZE "StateSize" //!< Number of bytes needed to store state -#define NVVFX_STATE_COUNT \ - "NumStateObjects" //!< Number of active state object handles +#define NVVFX_STATE "State" //!< State variable +#define NVVFX_STATE_SIZE "StateSize" //!< Number of bytes needed to store state +#define NVVFX_STATE_COUNT "NumStateObjects" //!< Number of active state object handles //! The format of pixels in an image. typedef enum NvCVImage_PixelFormat { @@ -171,12 +142,9 @@ typedef enum NvCVImage_PixelFormat { NVCV_BGRA = 7, //!< { Red, Green, Blue, Alpha } NVCV_ARGB = 8, //!< { Red, Green, Blue, Alpha } NVCV_ABGR = 9, //!< { Red, Green, Blue, Alpha } - NVCV_YUV420 = - 10, //!< Luminance and subsampled Chrominance { Y, Cb, Cr } - NVCV_YUV422 = - 11, //!< Luminance and subsampled Chrominance { Y, Cb, Cr } - NVCV_YUV444 = - 12, //!< Luminance and full bandwidth Chrominance { Y, Cb, Cr } + NVCV_YUV420 = 10, //!< Luminance and subsampled Chrominance { Y, Cb, Cr } + NVCV_YUV422 = 11, //!< Luminance and subsampled Chrominance { Y, Cb, Cr } + NVCV_YUV444 = 12, //!< Luminance and full bandwidth Chrominance { Y, Cb, Cr } } NvCVImage_PixelFormat; //! The data type used to represent each component of an image. @@ -204,22 +172,19 @@ typedef enum NvCVImage_ComponentType { //! 4:2:0 can be planar or semi-planar, with different orderings. //! Aliases are provided for FOURCCs defined at fourcc.org. //! Note: the LSB can be used to distinguish between chunky and planar formats. -#define NVCV_INTERLEAVED \ - 0 //!< All components of pixel(x,y) are adjacent (same as chunky) (default for non-YUV). -#define NVCV_CHUNKY \ - 0 //!< All components of pixel(x,y) are adjacent (same as interleaved). -#define NVCV_PLANAR 1 //!< The same component of all pixels are adjacent. -#define NVCV_UYVY 2 //!< [UYVY] Chunky 4:2:2 (default for 4:2:2) -#define NVCV_VYUY 4 //!< [VYUY] Chunky 4:2:2 -#define NVCV_YUYV 6 //!< [YUYV] Chunky 4:2:2 -#define NVCV_YVYU 8 //!< [YVYU] Chunky 4:2:2 -#define NVCV_CYUV 10 //!< [YUV] Chunky 4:4:4 -#define NVCV_CYVU 12 //!< [YVU] Chunky 4:4:4 -#define NVCV_YUV 3 //!< [Y][U][V] Planar 4:2:2 or 4:2:0 or 4:4:4 -#define NVCV_YVU 5 //!< [Y][V][U] Planar 4:2:2 or 4:2:0 or 4:4:4 -#define NVCV_YCUV \ - 7 //!< [Y][UV] Semi-planar 4:2:2 or 4:2:0 (default for 4:2:0) -#define NVCV_YCVU 9 //!< [Y][VU] Semi-planar 4:2:2 or 4:2:0 +#define NVCV_INTERLEAVED 0 //!< All components of pixel(x,y) are adjacent (same as chunky) (default for non-YUV). +#define NVCV_CHUNKY 0 //!< All components of pixel(x,y) are adjacent (same as interleaved). +#define NVCV_PLANAR 1 //!< The same component of all pixels are adjacent. +#define NVCV_UYVY 2 //!< [UYVY] Chunky 4:2:2 (default for 4:2:2) +#define NVCV_VYUY 4 //!< [VYUY] Chunky 4:2:2 +#define NVCV_YUYV 6 //!< [YUYV] Chunky 4:2:2 +#define NVCV_YVYU 8 //!< [YVYU] Chunky 4:2:2 +#define NVCV_CYUV 10 //!< [YUV] Chunky 4:4:4 +#define NVCV_CYVU 12 //!< [YVU] Chunky 4:4:4 +#define NVCV_YUV 3 //!< [Y][U][V] Planar 4:2:2 or 4:2:0 or 4:4:4 +#define NVCV_YVU 5 //!< [Y][V][U] Planar 4:2:2 or 4:2:0 or 4:4:4 +#define NVCV_YCUV 7 //!< [Y][UV] Semi-planar 4:2:2 or 4:2:0 (default for 4:2:0) +#define NVCV_YCVU 9 //!< [Y][VU] Semi-planar 4:2:2 or 4:2:0 //! The following are FOURCC aliases for specific layouts. Note that it is still required to specify the format as well //! as the layout, e.g. NVCV_YUV420 and NVCV_NV12, even though the NV12 layout is only associated with YUV420 sampling. @@ -239,15 +204,13 @@ typedef enum NvCVImage_ComponentType { //! NVCV_601 and NVCV_709 describe the color axes of YUV. //! NVCV_VIDEO_RANGE and NVCV_VIDEO_RANGE describe the range, [16, 235] or [0, 255], respectively. //! NVCV_CHROMA_COSITED and NVCV_CHROMA_INTSTITIAL describe the location of the chroma samples. -#define NVCV_601 0x00 //!< The Rec.601 YUV colorspace, typically used for SD. -#define NVCV_709 0x01 //!< The Rec.709 YUV colorspace, typically used for HD. -#define NVCV_2020 0x02 //!< The Rec.2020 YUV colorspace. -#define NVCV_VIDEO_RANGE 0x00 //!< The video range is [16, 235]. -#define NVCV_FULL_RANGE 0x04 //!< The video range is [ 0, 255]. -#define NVCV_CHROMA_COSITED \ - 0x00 //!< The chroma is sampled at the same location as the luma samples horizontally. -#define NVCV_CHROMA_INTSTITIAL \ - 0x08 //!< The chroma is sampled between luma samples horizontally. +#define NVCV_601 0x00 //!< The Rec.601 YUV colorspace, typically used for SD. +#define NVCV_709 0x01 //!< The Rec.709 YUV colorspace, typically used for HD. +#define NVCV_2020 0x02 //!< The Rec.2020 YUV colorspace. +#define NVCV_VIDEO_RANGE 0x00 //!< The video range is [16, 235]. +#define NVCV_FULL_RANGE 0x04 //!< The video range is [ 0, 255]. +#define NVCV_CHROMA_COSITED 0x00 //!< The chroma is sampled at the same location as the luma samples horizontally. +#define NVCV_CHROMA_INTSTITIAL 0x08 //!< The chroma is sampled between luma samples horizontally. #define NVCV_CHROMA_TOPLEFT \ 0x10 //!< The chroma is sampled at the same location as the luma samples horizontally and vertically. #define NVCV_CHROMA_MPEG2 NVCV_CHROMA_COSITED //!< As is most video. @@ -270,16 +233,16 @@ typedef enum NvCVImage_ComponentType { #define NVVFX_OUTPUT_IMAGE_0 "DstImage0" #define NVVFX_OUTPUT_IMAGE NVVFX_OUTPUT_IMAGE_0 #define NVVFX_MODEL_DIRECTORY "ModelDir" -#define NVVFX_CUDA_STREAM "CudaStream" //!< The CUDA stream to use -#define NVVFX_CUDA_GRAPH "CudaGraph" //!< Enable CUDA graph to use -#define NVVFX_INFO "Info" //!< Get info about the effects -#define NVVFX_SCALE "Scale" //!< Scale factor -#define NVVFX_STRENGTH "Strength" //!< Strength for different filters +#define NVVFX_CUDA_STREAM "CudaStream" //!< The CUDA stream to use +#define NVVFX_CUDA_GRAPH "CudaGraph" //!< Enable CUDA graph to use +#define NVVFX_INFO "Info" //!< Get info about the effects +#define NVVFX_SCALE "Scale" //!< Scale factor +#define NVVFX_STRENGTH "Strength" //!< Strength for different filters #define NVVFX_STRENGTH_LEVELS "StrengthLevels" //!< Number of strength levels #define NVVFX_MODE "Mode" //!< Mode for different filters -#define NVVFX_TEMPORAL "Temporal" //!< Temporal mode: 0=image, 1=video -#define NVVFX_GPU "GPU" //!< Preferred GPU (optional) -#define NVVFX_BATCH_SIZE "BatchSize" //!< Batch Size (default 1) +#define NVVFX_TEMPORAL "Temporal" //!< Temporal mode: 0=image, 1=video +#define NVVFX_GPU "GPU" //!< Preferred GPU (optional) +#define NVVFX_BATCH_SIZE "BatchSize" //!< Batch Size (default 1) #define NVVFX_MODEL_BATCH "ModelBatch" #define NVVFX_STATE "State" //!< State variable #define NVVFX_STATE_SIZE "StateSize" //!< Number of bytes needed to store state @@ -290,29 +253,22 @@ typedef struct __declspec(dllexport) #endif // _MSC_VER NvCVImage { - unsigned int width; //!< The number of pixels horizontally in the image. - unsigned int height; //!< The number of pixels vertically in the image. - signed int pitch; //!< The byte stride between pixels vertically. - NvCVImage_PixelFormat - pixelFormat; //!< The format of the pixels in the image. - NvCVImage_ComponentType - componentType; //!< The data type used to represent each component of the image. - unsigned char pixelBytes; //!< The number of bytes in a chunky pixel. - unsigned char - componentBytes; //!< The number of bytes in each pixel component. - unsigned char numComponents; //!< The number of components in each pixel. - unsigned char planar; //!< NVCV_CHUNKY, NVCV_PLANAR, NVCV_UYVY, .... - unsigned char gpuMem; //!< NVCV_CPU, NVCV_CPU_PINNED, NVCV_CUDA, NVCV_GPU - unsigned char - colorspace; //!< An OR of colorspace, range and chroma phase. - unsigned char reserved - [2]; //!< For structure padding and future expansion. Set to 0. - void *pixels; //!< Pointer to pixel(0,0) in the image. - void *deletePtr; //!< Buffer memory to be deleted (can be NULL). - void (*deleteProc)( - void *p); //!< Delete procedure to call rather than free(). - unsigned long long - bufferBytes; //!< The maximum amount of memory available through pixels. + unsigned int width; //!< The number of pixels horizontally in the image. + unsigned int height; //!< The number of pixels vertically in the image. + signed int pitch; //!< The byte stride between pixels vertically. + NvCVImage_PixelFormat pixelFormat; //!< The format of the pixels in the image. + NvCVImage_ComponentType componentType; //!< The data type used to represent each component of the image. + unsigned char pixelBytes; //!< The number of bytes in a chunky pixel. + unsigned char componentBytes; //!< The number of bytes in each pixel component. + unsigned char numComponents; //!< The number of components in each pixel. + unsigned char planar; //!< NVCV_CHUNKY, NVCV_PLANAR, NVCV_UYVY, .... + unsigned char gpuMem; //!< NVCV_CPU, NVCV_CPU_PINNED, NVCV_CUDA, NVCV_GPU + unsigned char colorspace; //!< An OR of colorspace, range and chroma phase. + unsigned char reserved[2]; //!< For structure padding and future expansion. Set to 0. + void *pixels; //!< Pointer to pixel(0,0) in the image. + void *deletePtr; //!< Buffer memory to be deleted (can be NULL). + void (*deleteProc)(void *p); //!< Delete procedure to call rather than free(). + unsigned long long bufferBytes; //!< The maximum amount of memory available through pixels. } NvCVImage; //! Integer rectangle. @@ -338,171 +294,113 @@ typedef void *NvVFX_StateObjectHandle; /* nvvfx functions */ typedef NvCV_Status NvVFX_API (*NvVFX_GetVersion_t)(unsigned int *version); -typedef NvCV_Status NvVFX_API (*NvVFX_CreateEffect_t)(NvVFX_EffectSelector code, - NvVFX_Handle *effect); +typedef NvCV_Status NvVFX_API (*NvVFX_CreateEffect_t)(NvVFX_EffectSelector code, NvVFX_Handle *effect); typedef NvCV_Status NvVFX_API (*NvVFX_DestroyEffect_t)(NvVFX_Handle effect); -typedef NvCV_Status - NvVFX_API (*NvVFX_SetU32_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - unsigned int val); -typedef NvCV_Status NvVFX_API (*NvVFX_SetS32_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, int val); -typedef NvCV_Status NvVFX_API (*NvVFX_SetF32_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, float val); -typedef NvCV_Status NvVFX_API (*NvVFX_SetF64_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, double val); -typedef NvCV_Status - NvVFX_API (*NvVFX_SetU64_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - unsigned long long val); -typedef NvCV_Status NvVFX_API (*NvVFX_SetObject_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, void *ptr); +typedef NvCV_Status NvVFX_API (*NvVFX_SetU32_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + unsigned int val); +typedef NvCV_Status NvVFX_API (*NvVFX_SetS32_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, int val); +typedef NvCV_Status NvVFX_API (*NvVFX_SetF32_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, float val); +typedef NvCV_Status NvVFX_API (*NvVFX_SetF64_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, double val); +typedef NvCV_Status NvVFX_API (*NvVFX_SetU64_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + unsigned long long val); +typedef NvCV_Status NvVFX_API (*NvVFX_SetObject_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, void *ptr); /* requires sdk version >= 0.7.0 */ -typedef NvCV_Status NvVFX_API (*NvVFX_SetStateObjectHandleArray_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, - NvVFX_StateObjectHandle *handle); +typedef NvCV_Status NvVFX_API (*NvVFX_SetStateObjectHandleArray_t)(NvVFX_Handle effect, + NvVFX_ParameterSelector param_name, + NvVFX_StateObjectHandle *handle); /* ----------------------------- */ -typedef NvCV_Status - NvVFX_API (*NvVFX_SetCudaStream_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - CUstream stream); -typedef NvCV_Status NvVFX_API (*NvVFX_SetImage_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, NvCVImage *im); -typedef NvCV_Status - NvVFX_API (*NvVFX_SetString_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - const char *str); -typedef NvCV_Status - NvVFX_API (*NvVFX_GetU32_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - unsigned int *val); -typedef NvCV_Status NvVFX_API (*NvVFX_GetS32_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, int *val); -typedef NvCV_Status NvVFX_API (*NvVFX_GetF32_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, float *val); -typedef NvCV_Status NvVFX_API (*NvVFX_GetF64_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, double *val); -typedef NvCV_Status - NvVFX_API (*NvVFX_GetU64_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - unsigned long long *val); -typedef NvCV_Status NvVFX_API (*NvVFX_GetObject_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, void **ptr); -typedef NvCV_Status - NvVFX_API (*NvVFX_GetCudaStream_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - CUstream *stream); -typedef NvCV_Status NvVFX_API (*NvVFX_GetImage_t)( - NvVFX_Handle effect, NvVFX_ParameterSelector param_name, NvCVImage *im); -typedef NvCV_Status - NvVFX_API (*NvVFX_GetString_t)(NvVFX_Handle effect, - NvVFX_ParameterSelector param_name, - const char **str); +typedef NvCV_Status NvVFX_API (*NvVFX_SetCudaStream_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + CUstream stream); +typedef NvCV_Status NvVFX_API (*NvVFX_SetImage_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + NvCVImage *im); +typedef NvCV_Status NvVFX_API (*NvVFX_SetString_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + const char *str); +typedef NvCV_Status NvVFX_API (*NvVFX_GetU32_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + unsigned int *val); +typedef NvCV_Status NvVFX_API (*NvVFX_GetS32_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, int *val); +typedef NvCV_Status NvVFX_API (*NvVFX_GetF32_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, float *val); +typedef NvCV_Status NvVFX_API (*NvVFX_GetF64_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, double *val); +typedef NvCV_Status NvVFX_API (*NvVFX_GetU64_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + unsigned long long *val); +typedef NvCV_Status NvVFX_API (*NvVFX_GetObject_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, void **ptr); +typedef NvCV_Status NvVFX_API (*NvVFX_GetCudaStream_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + CUstream *stream); +typedef NvCV_Status NvVFX_API (*NvVFX_GetImage_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + NvCVImage *im); +typedef NvCV_Status NvVFX_API (*NvVFX_GetString_t)(NvVFX_Handle effect, NvVFX_ParameterSelector param_name, + const char **str); typedef NvCV_Status NvVFX_API (*NvVFX_Run_t)(NvVFX_Handle effect, int async); typedef NvCV_Status NvVFX_API (*NvVFX_Load_t)(NvVFX_Handle effect); typedef NvCV_Status NvVFX_API (*NvVFX_CudaStreamCreate_t)(CUstream *stream); typedef NvCV_Status NvVFX_API (*NvVFX_CudaStreamDestroy_t)(CUstream stream); /* requires sdk version >= 0.7.0 */ -typedef NvCV_Status - NvVFX_API (*NvVFX_AllocateState_t)(NvVFX_Handle effect, - NvVFX_StateObjectHandle *handle); -typedef NvCV_Status - NvVFX_API (*NvVFX_DeallocateState_t)(NvVFX_Handle effect, - NvVFX_StateObjectHandle handle); -typedef NvCV_Status - NvVFX_API (*NvVFX_ResetState_t)(NvVFX_Handle effect, - NvVFX_StateObjectHandle handle); +typedef NvCV_Status NvVFX_API (*NvVFX_AllocateState_t)(NvVFX_Handle effect, NvVFX_StateObjectHandle *handle); +typedef NvCV_Status NvVFX_API (*NvVFX_DeallocateState_t)(NvVFX_Handle effect, NvVFX_StateObjectHandle handle); +typedef NvCV_Status NvVFX_API (*NvVFX_ResetState_t)(NvVFX_Handle effect, NvVFX_StateObjectHandle handle); /* NvCVImage functions */ -typedef NvCV_Status NvCV_API (*NvCVImage_Init_t)( - NvCVImage *im, unsigned width, unsigned height, int pitch, void *pixels, - NvCVImage_PixelFormat format, NvCVImage_ComponentType type, - unsigned layout, unsigned memSpace); -typedef NvCV_Status NvCV_API (*NvCVImage_InitView_t)(NvCVImage *subImg, - NvCVImage *fullImg, int x, - int y, unsigned width, - unsigned height); -typedef NvCV_Status NvCV_API (*NvCVImage_Alloc_t)( - NvCVImage *im, unsigned width, unsigned height, - NvCVImage_PixelFormat format, NvCVImage_ComponentType type, - unsigned layout, unsigned memSpace, unsigned alignment); -typedef NvCV_Status NvCV_API (*NvCVImage_Realloc_t)( - NvCVImage *im, unsigned width, unsigned height, - NvCVImage_PixelFormat format, NvCVImage_ComponentType type, - unsigned layout, unsigned memSpace, unsigned alignment); +typedef NvCV_Status NvCV_API (*NvCVImage_Init_t)(NvCVImage *im, unsigned width, unsigned height, int pitch, + void *pixels, NvCVImage_PixelFormat format, + NvCVImage_ComponentType type, unsigned layout, unsigned memSpace); +typedef NvCV_Status NvCV_API (*NvCVImage_InitView_t)(NvCVImage *subImg, NvCVImage *fullImg, int x, int y, + unsigned width, unsigned height); +typedef NvCV_Status NvCV_API (*NvCVImage_Alloc_t)(NvCVImage *im, unsigned width, unsigned height, + NvCVImage_PixelFormat format, NvCVImage_ComponentType type, + unsigned layout, unsigned memSpace, unsigned alignment); +typedef NvCV_Status NvCV_API (*NvCVImage_Realloc_t)(NvCVImage *im, unsigned width, unsigned height, + NvCVImage_PixelFormat format, NvCVImage_ComponentType type, + unsigned layout, unsigned memSpace, unsigned alignment); typedef NvCV_Status NvCV_API (*NvCVImage_Dealloc_t)(NvCVImage *im); -typedef NvCV_Status NvCV_API (*NvCVImage_Create_t)( - unsigned width, unsigned height, NvCVImage_PixelFormat format, - NvCVImage_ComponentType type, unsigned layout, unsigned memSpace, - unsigned alignment, NvCVImage **out); +typedef NvCV_Status NvCV_API (*NvCVImage_Create_t)(unsigned width, unsigned height, NvCVImage_PixelFormat format, + NvCVImage_ComponentType type, unsigned layout, unsigned memSpace, + unsigned alignment, NvCVImage **out); typedef NvCV_Status NvCV_API (*NvCVImage_Destroy_t)(NvCVImage *im); -typedef NvCV_Status NvCV_API (*NvCVImage_ComponentOffsets_t)( - NvCVImage_PixelFormat format, int *rOff, int *gOff, int *bOff, - int *aOff, int *yOff); -typedef NvCV_Status NvCV_API (*NvCVImage_Transfer_t)(const NvCVImage *src, - NvCVImage *dst, - float scale, - struct CUstream_st *stream, - NvCVImage *tmp); -typedef NvCV_Status NvCV_API (*NvCVImage_TransferRect_t)( - const NvCVImage *src, const NvCVRect2i *srcRect, NvCVImage *dst, - const NvCVPoint2i *dstPt, float scale, struct CUstream_st *stream, - NvCVImage *tmp); +typedef NvCV_Status NvCV_API (*NvCVImage_ComponentOffsets_t)(NvCVImage_PixelFormat format, int *rOff, int *gOff, + int *bOff, int *aOff, int *yOff); +typedef NvCV_Status NvCV_API (*NvCVImage_Transfer_t)(const NvCVImage *src, NvCVImage *dst, float scale, + struct CUstream_st *stream, NvCVImage *tmp); +typedef NvCV_Status NvCV_API (*NvCVImage_TransferRect_t)(const NvCVImage *src, const NvCVRect2i *srcRect, + NvCVImage *dst, const NvCVPoint2i *dstPt, float scale, + struct CUstream_st *stream, NvCVImage *tmp); typedef NvCV_Status NvCV_API (*NvCVImage_TransferFromYUV_t)( - const void *y, int yPixBytes, int yPitch, const void *u, const void *v, - int uvPixBytes, int uvPitch, NvCVImage_PixelFormat yuvFormat, - NvCVImage_ComponentType yuvType, unsigned yuvColorSpace, - unsigned yuvMemSpace, NvCVImage *dst, const NvCVRect2i *dstRect, - float scale, struct CUstream_st *stream, NvCVImage *tmp); + const void *y, int yPixBytes, int yPitch, const void *u, const void *v, int uvPixBytes, int uvPitch, + NvCVImage_PixelFormat yuvFormat, NvCVImage_ComponentType yuvType, unsigned yuvColorSpace, unsigned yuvMemSpace, + NvCVImage *dst, const NvCVRect2i *dstRect, float scale, struct CUstream_st *stream, NvCVImage *tmp); typedef NvCV_Status NvCV_API (*NvCVImage_TransferToYUV_t)( - const NvCVImage *src, const NvCVRect2i *srcRect, const void *y, - int yPixBytes, int yPitch, const void *u, const void *v, int uvPixBytes, - int uvPitch, NvCVImage_PixelFormat yuvFormat, - NvCVImage_ComponentType yuvType, unsigned yuvColorSpace, - unsigned yuvMemSpace, float scale, struct CUstream_st *stream, - NvCVImage *tmp); -typedef NvCV_Status - NvCV_API (*NvCVImage_MapResource_t)(NvCVImage *im, - struct CUstream_st *stream); + const NvCVImage *src, const NvCVRect2i *srcRect, const void *y, int yPixBytes, int yPitch, const void *u, + const void *v, int uvPixBytes, int uvPitch, NvCVImage_PixelFormat yuvFormat, NvCVImage_ComponentType yuvType, + unsigned yuvColorSpace, unsigned yuvMemSpace, float scale, struct CUstream_st *stream, NvCVImage *tmp); +typedef NvCV_Status NvCV_API (*NvCVImage_MapResource_t)(NvCVImage *im, struct CUstream_st *stream); -typedef NvCV_Status - NvCV_API (*NvCVImage_UnmapResource_t)(NvCVImage *im, - struct CUstream_st *stream); -typedef NvCV_Status NvCV_API (*NvCVImage_Composite_t)( - const NvCVImage *fg, const NvCVImage *bg, const NvCVImage *mat, - NvCVImage *dst, struct CUstream_st *stream); -typedef NvCV_Status NvCV_API (*NvCVImage_CompositeRect_t)( - const NvCVImage *fg, const NvCVPoint2i *fgOrg, const NvCVImage *bg, - const NvCVPoint2i *bgOrg, const NvCVImage *mat, unsigned mode, - NvCVImage *dst, const NvCVPoint2i *dstOrg, struct CUstream_st *stream); -typedef NvCV_Status NvCV_API (*NvCVImage_CompositeOverConstant_t)( - const NvCVImage *src, const NvCVImage *mat, const void *bgColor, - NvCVImage *dst, struct CUstream_st *stream); -typedef NvCV_Status NvCV_API (*NvCVImage_FlipY_t)(const NvCVImage *src, - NvCVImage *dst); -typedef NvCV_Status NvCV_API (*NvCVImage_GetYUVPointers_t)( - NvCVImage *im, unsigned char **y, unsigned char **u, unsigned char **v, - int *yPixBytes, int *cPixBytes, int *yRowBytes, int *cRowBytes); +typedef NvCV_Status NvCV_API (*NvCVImage_UnmapResource_t)(NvCVImage *im, struct CUstream_st *stream); +typedef NvCV_Status NvCV_API (*NvCVImage_Composite_t)(const NvCVImage *fg, const NvCVImage *bg, const NvCVImage *mat, + NvCVImage *dst, struct CUstream_st *stream); +typedef NvCV_Status NvCV_API (*NvCVImage_CompositeRect_t)(const NvCVImage *fg, const NvCVPoint2i *fgOrg, + const NvCVImage *bg, const NvCVPoint2i *bgOrg, + const NvCVImage *mat, unsigned mode, NvCVImage *dst, + const NvCVPoint2i *dstOrg, struct CUstream_st *stream); +typedef NvCV_Status NvCV_API (*NvCVImage_CompositeOverConstant_t)(const NvCVImage *src, const NvCVImage *mat, + const void *bgColor, NvCVImage *dst, + struct CUstream_st *stream); +typedef NvCV_Status NvCV_API (*NvCVImage_FlipY_t)(const NvCVImage *src, NvCVImage *dst); +typedef NvCV_Status NvCV_API (*NvCVImage_GetYUVPointers_t)(NvCVImage *im, unsigned char **y, unsigned char **u, + unsigned char **v, int *yPixBytes, int *cPixBytes, + int *yRowBytes, int *cRowBytes); typedef const char *(*NvCV_GetErrorStringFromCode_t)(NvCV_Status code); /* beware: this is experimental : D3D functions */ -typedef NvCV_Status NvCV_API (*NvCVImage_ToD3DFormat_t)( - NvCVImage_PixelFormat format, NvCVImage_ComponentType type, - unsigned layout, DXGI_FORMAT *d3dFormat); -typedef NvCV_Status NvCV_API (*NvCVImage_FromD3DFormat_t)( - DXGI_FORMAT d3dFormat, NvCVImage_PixelFormat *format, - NvCVImage_ComponentType *type, unsigned char *layout); -typedef NvCV_Status NvCV_API (*NvCVImage_ToD3DColorSpace_t)( - unsigned char nvcvColorSpace, DXGI_COLOR_SPACE_TYPE *pD3dColorSpace); -typedef NvCV_Status NvCV_API (*NvCVImage_FromD3DColorSpace_t)( - DXGI_COLOR_SPACE_TYPE d3dColorSpace, unsigned char *pNvcvColorSpace); -typedef NvCV_Status NvCV_API (*NvCVImage_InitFromD3D11Texture_t)( - NvCVImage *im, struct ID3D11Texture2D *tx); -typedef NvCV_Status - NvCV_API (*NvCVImage_InitFromD3DTexture_t)(NvCVImage *im, - struct ID3D11Texture2D *tx); +typedef NvCV_Status NvCV_API (*NvCVImage_ToD3DFormat_t)(NvCVImage_PixelFormat format, NvCVImage_ComponentType type, + unsigned layout, DXGI_FORMAT *d3dFormat); +typedef NvCV_Status NvCV_API (*NvCVImage_FromD3DFormat_t)(DXGI_FORMAT d3dFormat, NvCVImage_PixelFormat *format, + NvCVImage_ComponentType *type, unsigned char *layout); +typedef NvCV_Status NvCV_API (*NvCVImage_ToD3DColorSpace_t)(unsigned char nvcvColorSpace, + DXGI_COLOR_SPACE_TYPE *pD3dColorSpace); +typedef NvCV_Status NvCV_API (*NvCVImage_FromD3DColorSpace_t)(DXGI_COLOR_SPACE_TYPE d3dColorSpace, + unsigned char *pNvcvColorSpace); +typedef NvCV_Status NvCV_API (*NvCVImage_InitFromD3D11Texture_t)(NvCVImage *im, struct ID3D11Texture2D *tx); +typedef NvCV_Status NvCV_API (*NvCVImage_InitFromD3DTexture_t)(NvCVImage *im, struct ID3D11Texture2D *tx); /* cuda runtime */ typedef enum cudaError { cudaSuccess = 0, @@ -636,12 +534,8 @@ typedef enum cudaError cudaError_t; typedef cudaError_t CUDARTAPI (*cudaMalloc_t)(void **devPtr, size_t size); typedef cudaError_t CUDARTAPI (*cudaStreamSynchronize_t)(CUstream stream); typedef cudaError_t CUDARTAPI (*cudaFree_t)(void *devPtr); -typedef cudaError_t CUDARTAPI (*cudaMemsetAsync_t)(void *devPtr, int value, - size_t count, - CUstream stream); -typedef cudaError_t CUDARTAPI (*cudaMemcpy_t)(void *dst, const void *src, - size_t count, - enum cudaMemcpyKind kind); +typedef cudaError_t CUDARTAPI (*cudaMemsetAsync_t)(void *devPtr, int value, size_t count, CUstream stream); +typedef cudaError_t CUDARTAPI (*cudaMemcpy_t)(void *dst, const void *src, size_t count, enum cudaMemcpyKind kind); /* nvvfx */ static NvVFX_GetVersion_t NvVFX_GetVersion = NULL; @@ -789,16 +683,14 @@ static inline void release_nv_vfx() static inline void nvvfx_get_sdk_path(char *buffer, const size_t len) { - DWORD ret = GetEnvironmentVariableA("NV_VIDEO_EFFECTS_PATH", buffer, - (DWORD)len); + DWORD ret = GetEnvironmentVariableA("NV_VIDEO_EFFECTS_PATH", buffer, (DWORD)len); if (!ret || ret >= len - 1) { char path[MAX_PATH]; GetEnvironmentVariableA("ProgramFiles", path, MAX_PATH); size_t max_len = sizeof(path) / sizeof(char); - snprintf(buffer, max_len, - "%s\\NVIDIA Corporation\\NVIDIA Video Effects", path); + snprintf(buffer, max_len, "%s\\NVIDIA Corporation\\NVIDIA Video Effects", path); } } @@ -832,8 +724,7 @@ static unsigned int get_lib_version(void) struct win_version_info nto_ver = {0}; if (get_dll_ver(L"NVVideoEffects.dll", &nto_ver)) - version = nto_ver.major << 24 | nto_ver.minor << 16 | - nto_ver.build << 8 | nto_ver.revis << 0; + version = nto_ver.major << 24 | nto_ver.minor << 16 | nto_ver.build << 8 | nto_ver.revis << 0; SetDllDirectoryA(NULL); return version; diff --git a/plugins/obs-ffmpeg/ffmpeg-mux/ffmpeg-mux.c b/plugins/obs-ffmpeg/ffmpeg-mux/ffmpeg-mux.c index 28632621f..cd25b3394 100644 --- a/plugins/obs-ffmpeg/ffmpeg-mux/ffmpeg-mux.c +++ b/plugins/obs-ffmpeg/ffmpeg-mux/ffmpeg-mux.c @@ -250,8 +250,7 @@ static void ffmpeg_mux_free(struct ffmpeg_mux *ffm) memset(ffm, 0, sizeof(*ffm)); } -static bool get_opt_str(int *p_argc, char ***p_argv, char **str, - const char *opt) +static bool get_opt_str(int *p_argc, char ***p_argv, char **str, const char *opt) { int argc = *p_argc; char **argv = *p_argv; @@ -279,8 +278,7 @@ static bool get_opt_int(int *p_argc, char ***p_argv, int *i, const char *opt) return true; } -static bool get_audio_params(struct audio_params *audio, int *argc, - char ***argv) +static bool get_audio_params(struct audio_params *audio, int *argc, char ***argv) { if (!get_opt_str(argc, argv, &audio->name, "audio track name")) return false; @@ -295,8 +293,7 @@ static bool get_audio_params(struct audio_params *audio, int *argc, return true; } -static void ffmpeg_log_callback(void *param, int level, const char *format, - va_list args) +static void ffmpeg_log_callback(void *param, int level, const char *format, va_list args) { #ifdef ENABLE_FFMPEG_MUX_DEBUG char out_buffer[4096]; @@ -315,14 +312,12 @@ static void ffmpeg_log_callback(void *param, int level, const char *format, break; case AV_LOG_WARNING: - fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s", - ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET); + fprintf(stdout, "%swarning: [ffmpeg_muxer] %s%s", ANSI_COLOR_MAGENTA, out.array, ANSI_COLOR_RESET); fflush(stdout); break; case AV_LOG_ERROR: - fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED, - out.array, ANSI_COLOR_RESET); + fprintf(stderr, "%serror: [ffmpeg_muxer] %s%s", ANSI_COLOR_RED, out.array, ANSI_COLOR_RESET); fflush(stderr); } @@ -335,8 +330,7 @@ static void ffmpeg_log_callback(void *param, int level, const char *format, UNUSED_PARAMETER(param); } -static bool init_params(int *argc, char ***argv, struct main_params *params, - struct audio_params **p_audio) +static bool init_params(int *argc, char ***argv, struct main_params *params, struct audio_params **p_audio) { struct audio_params *audio = NULL; @@ -363,37 +357,29 @@ static bool init_params(int *argc, char ***argv, struct main_params *params, if (params->has_video) { if (!get_opt_str(argc, argv, ¶ms->vcodec, "video codec")) return false; - if (!get_opt_int(argc, argv, ¶ms->vbitrate, - "video bitrate")) + if (!get_opt_int(argc, argv, ¶ms->vbitrate, "video bitrate")) return false; if (!get_opt_int(argc, argv, ¶ms->width, "video width")) return false; if (!get_opt_int(argc, argv, ¶ms->height, "video height")) return false; - if (!get_opt_int(argc, argv, ¶ms->color_primaries, - "video color primaries")) + if (!get_opt_int(argc, argv, ¶ms->color_primaries, "video color primaries")) return false; - if (!get_opt_int(argc, argv, ¶ms->color_trc, - "video color trc")) + if (!get_opt_int(argc, argv, ¶ms->color_trc, "video color trc")) return false; - if (!get_opt_int(argc, argv, ¶ms->colorspace, - "video colorspace")) + if (!get_opt_int(argc, argv, ¶ms->colorspace, "video colorspace")) return false; - if (!get_opt_int(argc, argv, ¶ms->color_range, - "video color range")) + if (!get_opt_int(argc, argv, ¶ms->color_range, "video color range")) return false; - if (!get_opt_int(argc, argv, ¶ms->chroma_sample_location, - "video chroma sample location")) + if (!get_opt_int(argc, argv, ¶ms->chroma_sample_location, "video chroma sample location")) return false; - if (!get_opt_int(argc, argv, ¶ms->max_luminance, - "video max luminance")) + if (!get_opt_int(argc, argv, ¶ms->max_luminance, "video max luminance")) return false; if (!get_opt_int(argc, argv, ¶ms->fps_num, "video fps num")) return false; if (!get_opt_int(argc, argv, ¶ms->fps_den, "video fps den")) return false; - if (!get_opt_int(argc, argv, ¶ms->codec_tag, - "video codec tag")) + if (!get_opt_int(argc, argv, ¶ms->codec_tag, "video codec tag")) params->codec_tag = 0; } @@ -417,8 +403,7 @@ static bool init_params(int *argc, char ***argv, struct main_params *params, get_opt_str(argc, argv, &global_stream_key, "stream key"); if (strcmp(global_stream_key, "") != 0) { - dstr_replace(¶ms->printable_file, global_stream_key, - "{stream_key}"); + dstr_replace(¶ms->printable_file, global_stream_key, "{stream_key}"); } av_log_set_callback(ffmpeg_log_callback); @@ -428,13 +413,11 @@ static bool init_params(int *argc, char ***argv, struct main_params *params, return true; } -static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream, - const char *name) +static bool new_stream(struct ffmpeg_mux *ffm, AVStream **stream, const char *name) { *stream = avformat_new_stream(ffm->output, NULL); if (!*stream) { - fprintf(stderr, "Couldn't create stream for encoder '%s'\n", - name); + fprintf(stderr, "Couldn't create stream for encoder '%s'\n", name); return false; } @@ -458,8 +441,7 @@ static void create_video_stream(struct ffmpeg_mux *ffm) return; if (ffm->video_header.size) { - extradata = av_memdup(ffm->video_header.data, - ffm->video_header.size); + extradata = av_memdup(ffm->video_header.data, ffm->video_header.size); } context = avcodec_alloc_context3(NULL); @@ -478,8 +460,7 @@ static void create_video_stream(struct ffmpeg_mux *ffm) context->chroma_sample_location = ffm->params.chroma_sample_location; context->extradata = extradata; context->extradata_size = ffm->video_header.size; - context->time_base = - (AVRational){ffm->params.fps_den, ffm->params.fps_num}; + context->time_base = (AVRational){ffm->params.fps_den, ffm->params.fps_num}; ffm->video_stream->time_base = context->time_base; ffm->video_stream->avg_frame_rate = av_inv_q(context->time_base); @@ -492,18 +473,14 @@ static void create_video_stream(struct ffmpeg_mux *ffm) const int max_luminance = ffm->params.max_luminance; if (max_luminance > 0) { size_t content_size; - AVContentLightMetadata *const content = - av_content_light_metadata_alloc(&content_size); + AVContentLightMetadata *const content = av_content_light_metadata_alloc(&content_size); content->MaxCLL = max_luminance; content->MaxFALL = max_luminance; - av_packet_side_data_add( - &ffm->video_stream->codecpar->coded_side_data, - &ffm->video_stream->codecpar->nb_coded_side_data, - AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)content, - content_size, 0); + av_packet_side_data_add(&ffm->video_stream->codecpar->coded_side_data, + &ffm->video_stream->codecpar->nb_coded_side_data, + AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)content, content_size, 0); - AVMasteringDisplayMetadata *const mastering = - av_mastering_display_metadata_alloc(); + AVMasteringDisplayMetadata *const mastering = av_mastering_display_metadata_alloc(); mastering->display_primaries[0][0] = av_make_q(17, 25); mastering->display_primaries[0][1] = av_make_q(8, 25); mastering->display_primaries[1][0] = av_make_q(53, 200); @@ -516,11 +493,10 @@ static void create_video_stream(struct ffmpeg_mux *ffm) mastering->max_luminance = av_make_q(max_luminance, 1); mastering->has_primaries = 1; mastering->has_luminance = 1; - av_packet_side_data_add( - &ffm->video_stream->codecpar->coded_side_data, - &ffm->video_stream->codecpar->nb_coded_side_data, - AV_PKT_DATA_MASTERING_DISPLAY_METADATA, - (uint8_t *)mastering, sizeof(*mastering), 0); + av_packet_side_data_add(&ffm->video_stream->codecpar->coded_side_data, + &ffm->video_stream->codecpar->nb_coded_side_data, + AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)mastering, + sizeof(*mastering), 0); } ffm->video_ctx = context; @@ -534,8 +510,7 @@ static void create_audio_stream(struct ffmpeg_mux *ffm, int idx) const char *name = ffm->params.acodec; int channels; - const AVCodecDescriptor *codec_desc = - avcodec_descriptor_get_by_name(name); + const AVCodecDescriptor *codec_desc = avcodec_descriptor_get_by_name(name); if (!codec_desc) { fprintf(stderr, "Couldn't find codec descriptor '%s'\n", name); return; @@ -555,8 +530,7 @@ static void create_audio_stream(struct ffmpeg_mux *ffm, int idx) stream->time_base = (AVRational){1, ffm->audio[idx].sample_rate}; if (ffm->audio_header[idx].size) { - extradata = av_memdup(ffm->audio_header[idx].data, - ffm->audio_header[idx].size); + extradata = av_memdup(ffm->audio_header[idx].data, ffm->audio_header[idx].size); } context = avcodec_alloc_context3(NULL); @@ -593,8 +567,7 @@ static bool init_streams(struct ffmpeg_mux *ffm) create_video_stream(ffm); if (ffm->params.tracks) { - ffm->audio_infos = - calloc(ffm->params.tracks, sizeof(*ffm->audio_infos)); + ffm->audio_infos = calloc(ffm->params.tracks, sizeof(*ffm->audio_infos)); for (int i = 0; i < ffm->params.tracks; i++) create_audio_stream(ffm, i); @@ -613,14 +586,12 @@ static void set_header(struct header *header, uint8_t *data, size_t size) memcpy(header->data, data, size); } -static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data, - struct ffm_packet_info *info) +static void ffmpeg_mux_header(struct ffmpeg_mux *ffm, uint8_t *data, struct ffm_packet_info *info) { if (info->type == FFM_PACKET_VIDEO) { set_header(&ffm->video_header, data, (size_t)info->size); } else { - set_header(&ffm->audio_header[info->index], data, - (size_t)info->size); + set_header(&ffm->audio_header[info->index], data, (size_t)info->size); } } @@ -715,8 +686,7 @@ static void *ffmpeg_mux_io_thread(void *data) // Loop to write in chunk_size chunks for (;;) { - shutting_down = os_atomic_load_bool( - &ffm->io.shutdown_requested); + shutting_down = os_atomic_load_bool(&ffm->io.shutdown_requested); pthread_mutex_lock(&ffm->io.data_mutex); @@ -733,12 +703,10 @@ static void *ffmpeg_mux_io_thread(void *data) // Get seek offset and data size struct io_header header; - deque_peek_front(&ffm->io.data, &header, - sizeof(header)); + deque_peek_front(&ffm->io.data, &header, sizeof(header)); // Do we need to seek? - if (header.seek_offset != - current_seek_position) { + if (header.seek_offset != current_seek_position) { // If there's already part of a chunk pending, // flush it at the current offset. Similarly, @@ -753,26 +721,21 @@ static void *ffmpeg_mux_io_thread(void *data) next_seek_position = header.seek_offset; // Update our virtual position - current_seek_position = - header.seek_offset; + current_seek_position = header.seek_offset; } // Make sure there's enough room for the data, if // not then force a flush - if (header.data_length + chunk_used > - CHUNK_SIZE) { + if (header.data_length + chunk_used > CHUNK_SIZE) { force_flush_chunk = true; break; } // Remove header that we already read - deque_pop_front(&ffm->io.data, NULL, - sizeof(header)); + deque_pop_front(&ffm->io.data, NULL, sizeof(header)); // Copy from the buffer to our local chunk - deque_pop_front(&ffm->io.data, - chunk + chunk_used, - header.data_length); + deque_pop_front(&ffm->io.data, chunk + chunk_used, header.data_length); // Update offsets chunk_used += header.data_length; @@ -785,11 +748,8 @@ static void *ffmpeg_mux_io_thread(void *data) // Try to avoid lots of small writes unless this was the final // data left in the buffer. The buffer might be entirely empty // if we were woken up to exit. - if (!force_flush_chunk && - (!chunk_used || - (chunk_used < 65536 && !shutting_down))) { - os_event_reset( - ffm->io.new_data_available_event); + if (!force_flush_chunk && (!chunk_used || (chunk_used < 65536 && !shutting_down))) { + os_event_reset(ffm->io.new_data_available_event); pthread_mutex_unlock(&ffm->io.data_mutex); break; } @@ -798,23 +758,19 @@ static void *ffmpeg_mux_io_thread(void *data) // Seek if we need to if (want_seek) { - os_fseeki64(ffm->io.output_file, - next_seek_position, SEEK_SET); + os_fseeki64(ffm->io.output_file, next_seek_position, SEEK_SET); // Update the next virtual position, making sure to take // into account the size of the chunk we're about to write. - current_seek_position = - next_seek_position + chunk_used; + current_seek_position = next_seek_position + chunk_used; want_seek = false; } // Write the current chunk to the output file - if (fwrite(chunk, chunk_used, 1, ffm->io.output_file) != - 1) { + if (fwrite(chunk, chunk_used, 1, ffm->io.output_file) != 1) { os_atomic_set_bool(&ffm->io.output_error, true); - fprintf(stderr, "Error writing to '%s', %s\n", - ffm->params.printable_file.array, + fprintf(stderr, "Error writing to '%s', %s\n", ffm->params.printable_file.array, strerror(errno)); goto error; } @@ -836,8 +792,7 @@ error: return NULL; } -static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset, - int whence) +static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset, int whence) { struct ffmpeg_mux *ffm = opaque; @@ -857,8 +812,7 @@ static int64_t ffmpeg_mux_seek_av_buffer(void *opaque, int64_t offset, } #if LIBAVFORMAT_VERSION_MAJOR >= 61 -static int ffmpeg_mux_write_av_buffer(void *opaque, const uint8_t *buf, - int buf_size) +static int ffmpeg_mux_write_av_buffer(void *opaque, const uint8_t *buf, int buf_size) #else static int ffmpeg_mux_write_av_buffer(void *opaque, uint8_t *buf, int buf_size) #endif @@ -874,8 +828,7 @@ static int ffmpeg_mux_write_av_buffer(void *opaque, uint8_t *buf, int buf_size) // Avoid unbounded growth of the deque, cap to 256 MB if (ffm->io.data.capacity >= 256 * 1048576 && - ffm->io.data.capacity - ffm->io.data.size < - buf_size + sizeof(struct io_header)) { + ffm->io.data.capacity - ffm->io.data.size < buf_size + sizeof(struct io_header)) { // No space, wait for the I/O thread to make space os_event_reset(ffm->io.buffer_space_available_event); pthread_mutex_unlock(&ffm->io.data_mutex); @@ -920,8 +873,7 @@ static inline int open_output_file(struct ffmpeg_mux *ffm) // We're in charge of managing the actual file now ffm->io.output_file = os_fopen(ffm->params.file, "wb"); if (!ffm->io.output_file) { - fprintf(stderr, "Couldn't open '%s', %s\n", - ffm->params.printable_file.array, + fprintf(stderr, "Couldn't open '%s', %s\n", ffm->params.printable_file.array, strerror(errno)); return FFM_ERROR; } @@ -933,29 +885,21 @@ static inline int open_output_file(struct ffmpeg_mux *ffm) pthread_mutex_init(&ffm->io.data_mutex, NULL); - os_event_init(&ffm->io.buffer_space_available_event, - OS_EVENT_TYPE_AUTO); - os_event_init(&ffm->io.new_data_available_event, - OS_EVENT_TYPE_AUTO); + os_event_init(&ffm->io.buffer_space_available_event, OS_EVENT_TYPE_AUTO); + os_event_init(&ffm->io.new_data_available_event, OS_EVENT_TYPE_AUTO); - pthread_create(&ffm->io.io_thread, NULL, - ffmpeg_mux_io_thread, ffm); + pthread_create(&ffm->io.io_thread, NULL, ffmpeg_mux_io_thread, ffm); - unsigned char *avio_ctx_buffer = - av_malloc(AVIO_BUFFER_SIZE); + unsigned char *avio_ctx_buffer = av_malloc(AVIO_BUFFER_SIZE); - ffm->output->pb = avio_alloc_context( - avio_ctx_buffer, AVIO_BUFFER_SIZE, 1, ffm, NULL, - ffmpeg_mux_write_av_buffer, - ffmpeg_mux_seek_av_buffer); + ffm->output->pb = avio_alloc_context(avio_ctx_buffer, AVIO_BUFFER_SIZE, 1, ffm, NULL, + ffmpeg_mux_write_av_buffer, ffmpeg_mux_seek_av_buffer); ffm->io.active = true; } else { - ret = avio_open(&ffm->output->pb, ffm->params.file, - AVIO_FLAG_WRITE); + ret = avio_open(&ffm->output->pb, ffm->params.file, AVIO_FLAG_WRITE); if (ret < 0) { - fprintf(stderr, "Couldn't open '%s', %s\n", - ffm->params.printable_file.array, + fprintf(stderr, "Couldn't open '%s', %s\n", ffm->params.printable_file.array, av_err2str(ret)); return FFM_ERROR; } @@ -963,10 +907,9 @@ static inline int open_output_file(struct ffmpeg_mux *ffm) } AVDictionary *dict = NULL; - if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=", - " ", 0))) { - fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n", - av_err2str(ret), ffm->params.muxer_settings); + if ((ret = av_dict_parse_string(&dict, ffm->params.muxer_settings, "=", " ", 0))) { + fprintf(stderr, "Failed to parse muxer settings: %s\n%s\n", av_err2str(ret), + ffm->params.muxer_settings); av_dict_free(&dict); } @@ -975,8 +918,7 @@ static inline int open_output_file(struct ffmpeg_mux *ffm) printf("Using muxer settings:"); AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) printf("\n\t%s=%s", entry->key, entry->value); printf("\n"); @@ -984,8 +926,7 @@ static inline int open_output_file(struct ffmpeg_mux *ffm) ret = avformat_write_header(ffm->output, &dict); if (ret < 0) { - fprintf(stderr, "Error opening '%s': %s", - ffm->params.printable_file.array, av_err2str(ret)); + fprintf(stderr, "Error opening '%s': %s", ffm->params.printable_file.array, av_err2str(ret)); av_dict_free(&dict); @@ -1002,8 +943,7 @@ static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm) const AVOutputFormat *output_format; int ret; bool is_http = false; - is_http = (strncmp(ffm->params.file, HTTP_PROTO, - sizeof(HTTP_PROTO) - 1) == 0); + is_http = (strncmp(ffm->params.file, HTTP_PROTO, sizeof(HTTP_PROTO) - 1) == 0); bool is_network = ffmpeg_mux_is_network(ffm); @@ -1017,8 +957,7 @@ static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm) output_format = av_guess_format(NULL, ffm->params.file, NULL); if (output_format == NULL) { - fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n", - ffm->params.printable_file.array); + fprintf(stderr, "Couldn't find an appropriate muxer for '%s'\n", ffm->params.printable_file.array); return FFM_ERROR; } @@ -1028,11 +967,9 @@ static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm) output_format->long_name ? output_format->long_name : "unknown"); #endif - ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL, - ffm->params.file); + ret = avformat_alloc_output_context2(&ffm->output, output_format, NULL, ffm->params.file); if (ret < 0) { - fprintf(stderr, "Couldn't initialize output context: %s\n", - av_err2str(ret)); + fprintf(stderr, "Couldn't initialize output context: %s\n", av_err2str(ret)); return FFM_ERROR; } @@ -1050,8 +987,7 @@ static int ffmpeg_mux_init_context(struct ffmpeg_mux *ffm) return FFM_SUCCESS; } -static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc, - char *argv[]) +static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc, char *argv[]) { argc--; argv++; @@ -1059,8 +995,7 @@ static int ffmpeg_mux_init_internal(struct ffmpeg_mux *ffm, int argc, return FFM_ERROR; if (ffm->params.tracks) { - ffm->audio_header = - calloc(ffm->params.tracks, sizeof(*ffm->audio_header)); + ffm->audio_header = calloc(ffm->params.tracks, sizeof(*ffm->audio_header)); } if (!ffmpeg_mux_get_extra_data(ffm)) @@ -1085,8 +1020,7 @@ static int ffmpeg_mux_init(struct ffmpeg_mux *ffm, int argc, char *argv[]) return ret; } -static inline int get_index(struct ffmpeg_mux *ffm, - struct ffm_packet_info *info) +static inline int get_index(struct ffmpeg_mux *ffm, struct ffm_packet_info *info) { if (info->type == FFM_PACKET_VIDEO) { if (ffm->video_stream) { @@ -1101,8 +1035,7 @@ static inline int get_index(struct ffmpeg_mux *ffm, return -1; } -static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm, - struct ffm_packet_info *info) +static AVCodecContext *get_codec_context(struct ffmpeg_mux *ffm, struct ffm_packet_info *info) { if (info->type == FFM_PACKET_VIDEO) { if (ffm->video_stream) { @@ -1122,19 +1055,15 @@ static inline AVStream *get_stream(struct ffmpeg_mux *ffm, int idx) return ffm->output->streams[idx]; } -static inline int64_t rescale_ts(struct ffmpeg_mux *ffm, - AVRational codec_time_base, int64_t val, - int idx) +static inline int64_t rescale_ts(struct ffmpeg_mux *ffm, AVRational codec_time_base, int64_t val, int idx) { AVStream *stream = get_stream(ffm, idx); - return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base, - stream->time_base, + return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base, stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); } -static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf, - struct ffm_packet_info *info) +static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf, struct ffm_packet_info *info) { int idx = get_index(ffm, info); @@ -1143,8 +1072,7 @@ static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf, return true; } - const AVRational codec_time_base = - get_codec_context(ffm, info)->time_base; + const AVRational codec_time_base = get_codec_context(ffm, info)->time_base; ffm->packet->data = buf; ffm->packet->size = (int)info->size; @@ -1163,15 +1091,13 @@ static inline bool ffmpeg_mux_packet(struct ffmpeg_mux *ffm, uint8_t *buf, } if (ret < 0) { - fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n", - ret, av_err2str(ret)); + fprintf(stderr, "av_interleaved_write_frame failed: %d: %s\n", ret, av_err2str(ret)); } return ret >= 0; } -static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size, - struct resize_buf *filename, int argc, +static inline bool read_change_file(struct ffmpeg_mux *ffm, uint32_t size, struct resize_buf *filename, int argc, char **argv) { resize_buf_resize(filename, size + 1); @@ -1226,11 +1152,9 @@ int main(int argc, char *argv[]) size_t len = wcslen(argv_w[i]); int size; - size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, - NULL, 0, NULL, NULL); + size = WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, NULL, 0, NULL, NULL); argv[i] = malloc(size + 1); - WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i], - size + 1, NULL, NULL); + WideCharToMultiByte(CP_UTF8, 0, argv_w[i], (int)len, argv[i], size + 1, NULL, NULL); argv[i][size] = 0; } @@ -1246,8 +1170,7 @@ int main(int argc, char *argv[]) while (!fail && safe_read(&info, sizeof(info)) == sizeof(info)) { if (info.type == FFM_PACKET_CHANGE_FILE) { - fail = !read_change_file(&ffm, info.size, &rb_filename, - argc, argv); + fail = !read_change_file(&ffm, info.size, &rb_filename, argc, argv); continue; } diff --git a/plugins/obs-ffmpeg/obs-amf-test/obs-amf-test.cpp b/plugins/obs-ffmpeg/obs-amf-test/obs-amf-test.cpp index f67a22322..1a1604f3a 100644 --- a/plugins/obs-ffmpeg/obs-amf-test/obs-amf-test.cpp +++ b/plugins/obs-ffmpeg/obs-amf-test/obs-amf-test.cpp @@ -36,8 +36,7 @@ static std::map adapter_info; static bool has_encoder(AMFContextPtr &amf_context, const wchar_t *encoder_name) { AMFComponentPtr encoder; - AMF_RESULT res = amf_factory->CreateComponent(amf_context, encoder_name, - &encoder); + AMF_RESULT res = amf_factory->CreateComponent(amf_context, encoder_name, &encoder); return res == AMF_OK; } @@ -75,9 +74,8 @@ static bool get_adapter_caps(IDXGIFactory *factory, uint32_t adapter_idx) ComPtr device; ComPtr context; - hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, - nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, - &context); + hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &device, + nullptr, &context); if (FAILED(hr)) return true; @@ -117,13 +115,11 @@ try { HRESULT hr; HANDLE hMainThread; - DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), - GetCurrentProcess(), &hMainThread, 0, FALSE, + DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hMainThread, 0, FALSE, DUPLICATE_SAME_ACCESS); DWORD threadId; HANDLE hThread; - hThread = - CreateThread(NULL, 0, TimeoutThread, hMainThread, 0, &threadId); + hThread = CreateThread(NULL, 0, TimeoutThread, hMainThread, 0, &threadId); CloseHandle(hThread); /* --------------------------------------------------------- */ @@ -133,8 +129,7 @@ try { if (!amf_module) throw "Failed to load AMF lib"; - auto init = - (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME); + auto init = (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME); if (!init) throw "Failed to get init func"; @@ -163,12 +158,9 @@ try { for (auto &[idx, caps] : adapter_info) { printf("[%u]\n", idx); printf("is_amd=%s\n", caps.is_amd ? "true" : "false"); - printf("supports_avc=%s\n", - caps.supports_avc ? "true" : "false"); - printf("supports_hevc=%s\n", - caps.supports_hevc ? "true" : "false"); - printf("supports_av1=%s\n", - caps.supports_av1 ? "true" : "false"); + printf("supports_avc=%s\n", caps.supports_avc ? "true" : "false"); + printf("supports_hevc=%s\n", caps.supports_hevc ? "true" : "false"); + printf("supports_av1=%s\n", caps.supports_av1 ? "true" : "false"); } return 0; diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-audio-encoders.c b/plugins/obs-ffmpeg/obs-ffmpeg-audio-encoders.c index 55ead3700..00d693451 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-audio-encoders.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-audio-encoders.c @@ -27,9 +27,8 @@ #include "obs-ffmpeg-formats.h" #include "obs-ffmpeg-compat.h" -#define do_log(level, format, ...) \ - blog(level, "[FFmpeg %s encoder: '%s'] " format, enc->type, \ - obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[FFmpeg %s encoder: '%s'] " format, enc->type, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -129,8 +128,7 @@ static bool initialize_codec(struct enc_encoder *enc) ret = avcodec_open2(enc->context, enc->codec, NULL); if (ret < 0) { struct dstr error_message = {0}; - dstr_printf(&error_message, "Failed to open AAC codec: %s", - av_err2str(ret)); + dstr_printf(&error_message, "Failed to open AAC codec: %s", av_err2str(ret)); obs_encoder_set_last_error(enc->encoder, error_message.array); dstr_free(&error_message); warn("Failed to open AAC codec: %s", av_err2str(ret)); @@ -147,8 +145,7 @@ static bool initialize_codec(struct enc_encoder *enc) enc->frame_size_bytes = enc->frame_size * (int)enc->audio_size; - ret = av_samples_alloc(enc->samples, NULL, channels, enc->frame_size, - enc->context->sample_fmt, 0); + ret = av_samples_alloc(enc->samples, NULL, channels, enc->frame_size, enc->context->sample_fmt, 0); if (ret < 0) { warn("Failed to create audio buffer: %s", av_err2str(ret)); return false; @@ -173,8 +170,7 @@ static void init_sizes(struct enc_encoder *enc, audio_t *audio) #define MIN(x, y) ((x) < (y) ? (x) : (y)) #endif -static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder, - const char *type, const char *alt, +static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder, const char *type, const char *alt, enum AVSampleFormat sample_format) { struct enc_encoder *enc; @@ -198,8 +194,7 @@ static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder, goto fail; } - const AVCodecDescriptor *codec_desc = - avcodec_descriptor_get(enc->codec->id); + const AVCodecDescriptor *codec_desc = avcodec_descriptor_get(enc->codec->id); if (!codec_desc) { warn("Failed to get codec descriptor"); @@ -226,23 +221,18 @@ static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder, const struct audio_output_info *aoi; aoi = audio_output_get_info(audio); - av_channel_layout_default(&enc->context->ch_layout, - (int)audio_output_get_channels(audio)); + av_channel_layout_default(&enc->context->ch_layout, (int)audio_output_get_channels(audio)); /* The avutil default channel layout for 5 channels is 5.0, which OBS * does not support. Manually set 5 channels to 4.1. */ if (aoi->speakers == SPEAKERS_4POINT1) - enc->context->ch_layout = - (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; + enc->context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; /* AAC, ALAC, & FLAC default to 3.0 for 3 channels instead of 2.1. * Tell the encoder to deal with 2.1 as if it were 3.0. */ if (aoi->speakers == SPEAKERS_2POINT1) - enc->context->ch_layout = - (AVChannelLayout)AV_CHANNEL_LAYOUT_SURROUND; + enc->context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_SURROUND; // ALAC supports 7.1 wide instead of regular 7.1. - if (aoi->speakers == SPEAKERS_7POINT1 && - astrcmpi(enc->type, "alac") == 0) - enc->context->ch_layout = - (AVChannelLayout)AV_CHANNEL_LAYOUT_7POINT1_WIDE_BACK; + if (aoi->speakers == SPEAKERS_7POINT1 && astrcmpi(enc->type, "alac") == 0) + enc->context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_7POINT1_WIDE_BACK; enc->context->sample_rate = audio_output_get_sample_rate(audio); @@ -288,10 +278,8 @@ static void *enc_create(obs_data_t *settings, obs_encoder_t *encoder, char buf[256]; av_channel_layout_describe(&enc->context->ch_layout, buf, 256); - info("bitrate: %" PRId64 - ", channels: %d, channel_layout: %s, track: %d\n", - (int64_t)enc->context->bit_rate / 1000, - (int)enc->context->ch_layout.nb_channels, buf, + info("bitrate: %" PRId64 ", channels: %d, channel_layout: %s, track: %d\n", + (int64_t)enc->context->bit_rate / 1000, (int)enc->context->ch_layout.nb_channels, buf, (int)obs_encoder_get_mixer_index(enc->encoder) + 1); init_sizes(enc, audio); @@ -315,26 +303,22 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) static void *opus_create(obs_data_t *settings, obs_encoder_t *encoder) { - return enc_create(settings, encoder, "libopus", "opus", - AV_SAMPLE_FMT_FLT); + return enc_create(settings, encoder, "libopus", "opus", AV_SAMPLE_FMT_FLT); } static void *pcm_create(obs_data_t *settings, obs_encoder_t *encoder) { - return enc_create(settings, encoder, "pcm_s16le", NULL, - AV_SAMPLE_FMT_NONE); + return enc_create(settings, encoder, "pcm_s16le", NULL, AV_SAMPLE_FMT_NONE); } static void *pcm24_create(obs_data_t *settings, obs_encoder_t *encoder) { - return enc_create(settings, encoder, "pcm_s24le", NULL, - AV_SAMPLE_FMT_NONE); + return enc_create(settings, encoder, "pcm_s24le", NULL, AV_SAMPLE_FMT_NONE); } static void *pcm32_create(obs_data_t *settings, obs_encoder_t *encoder) { - return enc_create(settings, encoder, "pcm_f32le", NULL, - AV_SAMPLE_FMT_NONE); + return enc_create(settings, encoder, "pcm_f32le", NULL, AV_SAMPLE_FMT_NONE); } static void *alac_create(obs_data_t *settings, obs_encoder_t *encoder) @@ -347,8 +331,7 @@ static void *flac_create(obs_data_t *settings, obs_encoder_t *encoder) return enc_create(settings, encoder, "flac", NULL, AV_SAMPLE_FMT_S16); } -static bool do_encode(struct enc_encoder *enc, struct encoder_packet *packet, - bool *received_packet) +static bool do_encode(struct enc_encoder *enc, struct encoder_packet *packet, bool *received_packet) { AVRational time_base = {1, enc->context->sample_rate}; AVPacket avpacket = {0}; @@ -357,14 +340,11 @@ static bool do_encode(struct enc_encoder *enc, struct encoder_packet *packet, int channels; enc->aframe->nb_samples = enc->frame_size; - enc->aframe->pts = av_rescale_q( - enc->total_samples, (AVRational){1, enc->context->sample_rate}, - enc->context->time_base); + enc->aframe->pts = + av_rescale_q(enc->total_samples, (AVRational){1, enc->context->sample_rate}, enc->context->time_base); enc->aframe->ch_layout = enc->context->ch_layout; channels = enc->context->ch_layout.nb_channels; - ret = avcodec_fill_audio_frame(enc->aframe, channels, - enc->context->sample_fmt, - enc->samples[0], + ret = avcodec_fill_audio_frame(enc->aframe, channels, enc->context->sample_fmt, enc->samples[0], enc->frame_size_bytes * channels, 1); if (ret < 0) { warn("avcodec_fill_audio_frame failed: %s", av_err2str(ret)); @@ -405,8 +385,7 @@ static bool do_encode(struct enc_encoder *enc, struct encoder_packet *packet, return true; } -static bool enc_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool enc_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct enc_encoder *enc = data; @@ -426,8 +405,7 @@ static obs_properties_t *enc_properties(void *unused) UNUSED_PARAMETER(unused); obs_properties_t *props = obs_properties_create(); - obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 64, - 1024, 32); + obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 64, 1024, 32); return props; } diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-av1.c b/plugins/obs-ffmpeg/obs-ffmpeg-av1.c index 4cf5f9b43..6ca582ea8 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-av1.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-av1.c @@ -17,9 +17,8 @@ #include "obs-ffmpeg-video-encoders.h" -#define do_log(level, format, ...) \ - blog(level, "[AV1 encoder: '%s'] " format, \ - obs_encoder_get_name(enc->ffve.encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[AV1 encoder: '%s'] " format, obs_encoder_get_name(enc->ffve.encoder), ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -86,20 +85,16 @@ static bool av1_update(struct av1_encoder *enc, obs_data_t *settings) av1_video_info(enc, &info); if (enc->type == AV1_ENCODER_TYPE_SVT) { - av_opt_set_int(enc->ffve.context->priv_data, "preset", preset, - 0); + av_opt_set_int(enc->ffve.context->priv_data, "preset", preset, 0); av_dict_set_int(&svtav1_opts, "rc", 1, 0); } else if (enc->type == AV1_ENCODER_TYPE_AOM) { - av_opt_set_int(enc->ffve.context->priv_data, "cpu-used", preset, - 0); - av_opt_set(enc->ffve.context->priv_data, "usage", "realtime", - 0); + av_opt_set_int(enc->ffve.context->priv_data, "cpu-used", preset, 0); + av_opt_set(enc->ffve.context->priv_data, "usage", "realtime", 0); #if 0 av_opt_set_int(enc->ffve.context->priv_data, "tile-columns", 4, 0); //av_opt_set_int(enc->ffve.context->priv_data, "tile-rows", 4, 0); #else - av_opt_set_int(enc->ffve.context->priv_data, "tile-columns", 2, - 0); + av_opt_set_int(enc->ffve.context->priv_data, "tile-columns", 2, 0); av_opt_set_int(enc->ffve.context->priv_data, "tile-rows", 2, 0); #endif av_opt_set_int(enc->ffve.context->priv_data, "row-mt", 1, 0); @@ -111,8 +106,7 @@ static bool av1_update(struct av1_encoder *enc, obs_data_t *settings) if (enc->type == AV1_ENCODER_TYPE_SVT) { av_dict_set_int(&svtav1_opts, "rc", 0, 0); - av_opt_set_int(enc->ffve.context->priv_data, "qp", cqp, - 0); + av_opt_set_int(enc->ffve.context->priv_data, "qp", cqp, 0); } } else if (astrcmpi(rc, "vbr") != 0) { /* CBR by default */ @@ -131,13 +125,11 @@ static bool av1_update(struct av1_encoder *enc, obs_data_t *settings) } if (enc->type == AV1_ENCODER_TYPE_SVT) { - av_opt_set_dict_val(enc->ffve.context->priv_data, "svtav1_opts", - svtav1_opts, 0); + av_opt_set_dict_val(enc->ffve.context->priv_data, "svtav1_opts", svtav1_opts, 0); } const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts"); - ffmpeg_video_encoder_update(&enc->ffve, bitrate, keyint_sec, voi, &info, - ffmpeg_opts); + ffmpeg_video_encoder_update(&enc->ffve, bitrate, keyint_sec, voi, &info, ffmpeg_opts); av_dict_free(&svtav1_opts); info("settings:\n" @@ -150,8 +142,8 @@ static bool av1_update(struct av1_encoder *enc, obs_data_t *settings) "\twidth: %d\n" "\theight: %d\n" "\tffmpeg opts: %s\n", - enc->ffve.enc_name, rc, bitrate, cqp, enc->ffve.context->gop_size, - preset, enc->ffve.context->width, enc->ffve.height, ffmpeg_opts); + enc->ffve.enc_name, rc, bitrate, cqp, enc->ffve.context->gop_size, preset, enc->ffve.context->width, + enc->ffve.height, ffmpeg_opts); enc->ffve.context->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; return ffmpeg_video_encoder_init_codec(&enc->ffve); @@ -171,14 +163,12 @@ static void on_first_packet(void *data, AVPacket *pkt, struct darray *da) struct av1_encoder *enc = data; if (enc->type == AV1_ENCODER_TYPE_SVT) { - da_copy_array(enc->header, enc->ffve.context->extradata, - enc->ffve.context->extradata_size); + da_copy_array(enc->header, enc->ffve.context->extradata, enc->ffve.context->extradata_size); } else { for (int i = 0; i < pkt->side_data_elems; i++) { AVPacketSideData *side_data = pkt->side_data + i; if (side_data->type == AV_PKT_DATA_NEW_EXTRADATA) { - da_copy_array(enc->header, side_data->data, - side_data->size); + da_copy_array(enc->header, side_data->data, side_data->size); break; } } @@ -187,18 +177,15 @@ static void on_first_packet(void *data, AVPacket *pkt, struct darray *da) darray_copy_array(1, da, pkt->data, pkt->size); } -static void *av1_create_internal(obs_data_t *settings, obs_encoder_t *encoder, - const char *enc_lib, const char *enc_name) +static void *av1_create_internal(obs_data_t *settings, obs_encoder_t *encoder, const char *enc_lib, + const char *enc_name) { video_t *video = obs_encoder_video(encoder); const struct video_output_info *voi = video_output_get_info(video); - if (voi->format != VIDEO_FORMAT_P010 && - voi->format != VIDEO_FORMAT_I010) { - if (voi->colorspace == VIDEO_CS_2100_PQ || - voi->colorspace == VIDEO_CS_2100_HLG) { - const char *const text = - obs_module_text("AV1.8bitUnsupportedHdr"); + if (voi->format != VIDEO_FORMAT_P010 && voi->format != VIDEO_FORMAT_I010) { + if (voi->colorspace == VIDEO_CS_2100_PQ || voi->colorspace == VIDEO_CS_2100_HLG) { + const char *const text = obs_module_text("AV1.8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[AV1 encoder] %s", text); return NULL; @@ -212,8 +199,7 @@ static void *av1_create_internal(obs_data_t *settings, obs_encoder_t *encoder, else if (strcmp(enc_lib, "libaom-av1") == 0) enc->type = AV1_ENCODER_TYPE_AOM; - if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, enc_lib, NULL, - enc_name, NULL, on_first_packet)) + if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, enc_lib, NULL, enc_name, NULL, on_first_packet)) goto fail; if (!av1_update(enc, settings)) goto fail; @@ -235,8 +221,7 @@ static void *aom_av1_create(obs_data_t *settings, obs_encoder_t *encoder) return av1_create_internal(settings, encoder, "libaom-av1", "AOM AV1"); } -static bool av1_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool av1_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct av1_encoder *enc = data; return ffmpeg_video_encode(&enc->ffve, frame, packet, received_packet); @@ -251,8 +236,7 @@ void av1_defaults(obs_data_t *settings) obs_data_set_default_int(settings, "preset", 8); } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *rc = obs_data_get_string(settings, "rate_control"); bool cqp = astrcmpi(rc, "CQP") == 0; @@ -273,9 +257,7 @@ obs_properties_t *av1_properties(enum av1_encoder_type type) obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, "CBR", "CBR"); obs_property_list_add_string(p, "CQP", "CQP"); @@ -283,20 +265,16 @@ obs_properties_t *av1_properties(enum av1_encoder_type type) obs_property_set_modified_callback(p, rate_control_modified); - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 50, 300000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); - obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), - 1, 63, 1); + obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), 1, 63, 1); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 10, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1); obs_property_int_set_suffix(p, " s"); - p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); if (type == AV1_ENCODER_TYPE_SVT) { obs_property_list_add_int(p, "Very likely too slow (6)", 6); @@ -305,9 +283,7 @@ obs_properties_t *av1_properties(enum av1_encoder_type type) obs_property_list_add_int(p, "Might be better (9)", 9); obs_property_list_add_int(p, "A little bit faster? (10)", 10); obs_property_list_add_int(p, "Hmm, not bad speed (11)", 11); - obs_property_list_add_int( - p, "Whoa, although quality might be not so great (12)", - 12); + obs_property_list_add_int(p, "Whoa, although quality might be not so great (12)", 12); } else if (type == AV1_ENCODER_TYPE_AOM) { obs_property_list_add_int(p, "Probably too slow (7)", 7); obs_property_list_add_int(p, "Okay (8)", 8); @@ -315,9 +291,7 @@ obs_properties_t *av1_properties(enum av1_encoder_type type) obs_property_list_add_int(p, "Fastest (10)", 10); } - obs_properties_add_text(props, "ffmpeg_opts", - obs_module_text("FFmpegOpts"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "ffmpeg_opts", obs_module_text("FFmpegOpts"), OBS_TEXT_DEFAULT); return props; } diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-compat.h b/plugins/obs-ffmpeg/obs-ffmpeg-compat.h index ee37583ea..81701d6c5 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-compat.h +++ b/plugins/obs-ffmpeg/obs-ffmpeg-compat.h @@ -6,8 +6,6 @@ * a is the major version * b and c the minor and micro versions of libav * d and e the minor and micro versions of FFmpeg */ -#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \ - ((LIBAVCODEC_VERSION_MICRO < 100 && \ - LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \ - (LIBAVCODEC_VERSION_MICRO >= 100 && \ - LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e))) +#define LIBAVCODEC_VERSION_CHECK(a, b, c, d, e) \ + ((LIBAVCODEC_VERSION_MICRO < 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, b, c)) || \ + (LIBAVCODEC_VERSION_MICRO >= 100 && LIBAVCODEC_VERSION_INT >= AV_VERSION_INT(a, d, e))) diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-formats.h b/plugins/obs-ffmpeg/obs-ffmpeg-formats.h index b6500e0fd..89263d419 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-formats.h +++ b/plugins/obs-ffmpeg/obs-ffmpeg-formats.h @@ -3,15 +3,12 @@ #include #include -static inline int64_t rescale_ts(int64_t val, AVCodecContext *context, - AVRational new_base) +static inline int64_t rescale_ts(int64_t val, AVCodecContext *context, AVRational new_base) { - return av_rescale_q_rnd(val, context->time_base, new_base, - AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); + return av_rescale_q_rnd(val, context->time_base, new_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); } -static inline enum AVPixelFormat -obs_to_ffmpeg_video_format(enum video_format format) +static inline enum AVPixelFormat obs_to_ffmpeg_video_format(enum video_format format) { switch (format) { case VIDEO_FORMAT_I444: @@ -65,9 +62,7 @@ obs_to_ffmpeg_video_format(enum video_format format) } } -static inline enum AVChromaLocation -determine_chroma_location(enum AVPixelFormat pix_fmt, - enum AVColorSpace colorspace) +static inline enum AVChromaLocation determine_chroma_location(enum AVPixelFormat pix_fmt, enum AVColorSpace colorspace) { const AVPixFmtDescriptor *const desc = av_pix_fmt_desc_get(pix_fmt); if (desc) { @@ -87,9 +82,7 @@ determine_chroma_location(enum AVPixelFormat pix_fmt, case 1: if (log_chroma_w == 1) { /* 4:2:0 */ - return (colorspace == AVCOL_SPC_BT2020_NCL) - ? AVCHROMA_LOC_TOPLEFT - : AVCHROMA_LOC_LEFT; + return (colorspace == AVCOL_SPC_BT2020_NCL) ? AVCHROMA_LOC_TOPLEFT : AVCHROMA_LOC_LEFT; } } } @@ -97,8 +90,7 @@ determine_chroma_location(enum AVPixelFormat pix_fmt, return AVCHROMA_LOC_UNSPECIFIED; } -static inline enum audio_format -convert_ffmpeg_sample_format(enum AVSampleFormat format) +static inline enum audio_format convert_ffmpeg_sample_format(enum AVSampleFormat format) { switch (format) { case AV_SAMPLE_FMT_U8: diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-hls-mux.c b/plugins/obs-ffmpeg/obs-ffmpeg-hls-mux.c index 7fc984973..54e8792d7 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-hls-mux.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-hls-mux.c @@ -4,9 +4,8 @@ #include #endif -#define do_log(level, format, ...) \ - blog(level, "[ffmpeg hls muxer: '%s'] " format, \ - obs_output_get_name(stream->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[ffmpeg hls muxer: '%s'] " format, obs_output_get_name(stream->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -126,17 +125,13 @@ bool ffmpeg_hls_mux_start(void *data) service = obs_output_get_service(stream->output); if (!service) return false; - path_str = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); - stream_key = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_STREAM_KEY); + path_str = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); + stream_key = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_STREAM_KEY); dstr_copy(&stream->stream_key, stream_key); dstr_copy(&path, path_str); dstr_replace(&path, "{stream_key}", stream_key); - dstr_copy(&stream->muxer_settings, - "method=PUT http_persistent=1 ignore_io_errors=1 "); - dstr_catf(&stream->muxer_settings, "http_user_agent=libobs/%s", - obs_get_version_string()); + dstr_copy(&stream->muxer_settings, "method=PUT http_persistent=1 ignore_io_errors=1 "); + dstr_catf(&stream->muxer_settings, "http_user_agent=libobs/%s", obs_get_version_string()); vencoder = obs_output_get_video_encoder(stream->output); settings = obs_encoder_get_settings(vencoder); @@ -152,13 +147,11 @@ bool ffmpeg_hls_mux_start(void *data) dstr_free(&path); if (!stream->pipe) { - obs_output_set_last_error( - stream->output, obs_module_text("HelperProcessFailed")); + obs_output_set_last_error(stream->output, obs_module_text("HelperProcessFailed")); warn("Failed to create process pipe"); return false; } - stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL, - write_thread, stream) == 0; + stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL, write_thread, stream) == 0; if (!stream->mux_thread_joinable) return false; @@ -177,11 +170,9 @@ bool ffmpeg_hls_mux_start(void *data) return true; } -static bool write_packet_to_buf(struct ffmpeg_muxer *stream, - struct encoder_packet *packet) +static bool write_packet_to_buf(struct ffmpeg_muxer *stream, struct encoder_packet *packet) { - deque_push_back(&stream->packets, packet, - sizeof(struct encoder_packet)); + deque_push_back(&stream->packets, packet, sizeof(struct encoder_packet)); return true; } @@ -197,8 +188,7 @@ static void drop_frames(struct ffmpeg_muxer *stream, int highest_priority) deque_pop_front(&stream->packets, &packet, sizeof(packet)); /* do not drop audio data or video keyframes */ - if (packet.type == OBS_ENCODER_AUDIO || - packet.drop_priority >= highest_priority) { + if (packet.type == OBS_ENCODER_AUDIO || packet.drop_priority >= highest_priority) { deque_push_back(&new_buf, &packet, sizeof(packet)); } else { num_frames_dropped++; @@ -215,14 +205,12 @@ static void drop_frames(struct ffmpeg_muxer *stream, int highest_priority) stream->dropped_frames += num_frames_dropped; } -static bool find_first_video_packet(struct ffmpeg_muxer *stream, - struct encoder_packet *first) +static bool find_first_video_packet(struct ffmpeg_muxer *stream, struct encoder_packet *first) { size_t count = stream->packets.size / sizeof(*first); for (size_t i = 0; i < count; i++) { - struct encoder_packet *cur = - deque_data(&stream->packets, i * sizeof(*first)); + struct encoder_packet *cur = deque_data(&stream->packets, i * sizeof(*first)); if (cur->type == OBS_ENCODER_VIDEO && !cur->keyframe) { *first = *cur; return true; @@ -235,8 +223,7 @@ void check_to_drop_frames(struct ffmpeg_muxer *stream, bool pframes) { struct encoder_packet first; int64_t buffer_duration_usec; - int priority = pframes ? OBS_NAL_PRIORITY_HIGHEST - : OBS_NAL_PRIORITY_HIGH; + int priority = pframes ? OBS_NAL_PRIORITY_HIGHEST : OBS_NAL_PRIORITY_HIGH; int keyint_sec = stream->keyint_sec; int64_t drop_threshold_sec = keyint_sec ? 2 * keyint_sec : 10; @@ -249,8 +236,7 @@ void check_to_drop_frames(struct ffmpeg_muxer *stream, bool pframes) drop_frames(stream, priority); } -static bool add_video_packet(struct ffmpeg_muxer *stream, - struct encoder_packet *packet) +static bool add_video_packet(struct ffmpeg_muxer *stream, struct encoder_packet *packet) { check_to_drop_frames(stream, false); check_to_drop_frames(stream, true); @@ -297,16 +283,13 @@ void ffmpeg_hls_mux_data(void *data, struct encoder_packet *packet) } if (packet->type == OBS_ENCODER_VIDEO) { - const char *const codec = - obs_encoder_get_codec(packet->encoder); + const char *const codec = obs_encoder_get_codec(packet->encoder); if (strcmp(codec, "h264") == 0) { - packet->drop_priority = - obs_parse_avc_packet_priority(packet); + packet->drop_priority = obs_parse_avc_packet_priority(packet); } #ifdef ENABLE_HEVC else if (strcmp(codec, "hevc") == 0) { - packet->drop_priority = - obs_parse_hevc_packet_priority(packet); + packet->drop_priority = obs_parse_hevc_packet_priority(packet); } #endif } @@ -315,10 +298,8 @@ void ffmpeg_hls_mux_data(void *data, struct encoder_packet *packet) pthread_mutex_lock(&stream->write_mutex); if (active(stream)) { - added_packet = - (packet->type == OBS_ENCODER_VIDEO) - ? add_video_packet(stream, &new_packet) - : write_packet_to_buf(stream, &new_packet); + added_packet = (packet->type == OBS_ENCODER_VIDEO) ? add_video_packet(stream, &new_packet) + : write_packet_to_buf(stream, &new_packet); } pthread_mutex_unlock(&stream->write_mutex); @@ -331,8 +312,7 @@ void ffmpeg_hls_mux_data(void *data, struct encoder_packet *packet) struct obs_output_info ffmpeg_hls_muxer = { .id = "ffmpeg_hls_muxer", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | - OBS_OUTPUT_SERVICE, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_SERVICE, .protocols = "HLS", #ifdef ENABLE_HEVC .encoded_video_codecs = "h264;hevc", diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-logging.c b/plugins/obs-ffmpeg/obs-ffmpeg-logging.c index 4a45a1283..c8bb0170b 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-logging.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-logging.c @@ -51,8 +51,7 @@ static void destroy_log_context(struct log_context *log_context) pthread_mutex_unlock(&log_contexts_mutex); } -static void ffmpeg_log_callback(void *context, int level, const char *format, - va_list args) +static void ffmpeg_log_callback(void *context, int level, const char *format, va_list args) { if (format == NULL) return; @@ -62,8 +61,7 @@ static void ffmpeg_log_callback(void *context, int level, const char *format, char *str = log_context->str; av_log_format_line(context, level, format, args, str + strlen(str), - (int)(sizeof(log_context->str) - strlen(str)), - &log_context->print_prefix); + (int)(sizeof(log_context->str) - strlen(str)), &log_context->print_prefix); int obs_level; switch (level) { diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-mpegts.c b/plugins/obs-ffmpeg/obs-ffmpeg-mpegts.c index e2892d3a7..913728e73 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-mpegts.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-mpegts.c @@ -31,16 +31,14 @@ #include /* ------------------------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[obs-ffmpeg mpegts muxer: '%s']: " format, \ - obs_output_get_name(stream->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[obs-ffmpeg mpegts muxer: '%s']: " format, obs_output_get_name(stream->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) -static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data, - const char *error) +static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data, const char *error) { if (data->last_error) bfree(data->last_error); @@ -48,8 +46,7 @@ static void ffmpeg_mpegts_set_last_error(struct ffmpeg_data *data, data->last_error = bstrdup(error); } -void ffmpeg_mpegts_log_error(int log_level, struct ffmpeg_data *data, - const char *format, ...) +void ffmpeg_mpegts_log_error(int log_level, struct ffmpeg_data *data, const char *format, ...) { va_list args; char out[4096]; @@ -75,23 +72,17 @@ static bool is_srt(const char *url) static bool proto_is_allowed(struct ffmpeg_output *stream) { - return !strncmp(stream->ff_data.config.url, UDP_PROTO, - sizeof(UDP_PROTO) - 1) || - !strncmp(stream->ff_data.config.url, TCP_PROTO, - sizeof(TCP_PROTO) - 1) || - !strncmp(stream->ff_data.config.url, HTTP_PROTO, - sizeof(HTTP_PROTO) - 1); + return !strncmp(stream->ff_data.config.url, UDP_PROTO, sizeof(UDP_PROTO) - 1) || + !strncmp(stream->ff_data.config.url, TCP_PROTO, sizeof(TCP_PROTO) - 1) || + !strncmp(stream->ff_data.config.url, HTTP_PROTO, sizeof(HTTP_PROTO) - 1); } -static bool new_stream(struct ffmpeg_data *data, AVStream **stream, - const char *name) +static bool new_stream(struct ffmpeg_data *data, AVStream **stream, const char *name) { *stream = avformat_new_stream(data->output, NULL); if (!*stream) { - ffmpeg_mpegts_log_error( - LOG_WARNING, data, - "Couldn't create stream for encoder '%s'", name); + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Couldn't create stream for encoder '%s'", name); return false; } @@ -99,15 +90,11 @@ static bool new_stream(struct ffmpeg_data *data, AVStream **stream, return true; } -static bool get_audio_headers(struct ffmpeg_output *stream, - struct ffmpeg_data *data, int idx) +static bool get_audio_headers(struct ffmpeg_output *stream, struct ffmpeg_data *data, int idx) { AVCodecParameters *par = data->audio_infos[idx].stream->codecpar; - obs_encoder_t *aencoder = - obs_output_get_audio_encoder(stream->output, idx); - struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, - .timebase_den = 1, - .track_idx = idx}; + obs_encoder_t *aencoder = obs_output_get_audio_encoder(stream->output, idx); + struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, .timebase_den = 1, .track_idx = idx}; if (obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size)) { par->extradata = av_memdup(packet.data, packet.size); @@ -118,26 +105,22 @@ static bool get_audio_headers(struct ffmpeg_output *stream, return 0; } -static bool get_video_headers(struct ffmpeg_output *stream, - struct ffmpeg_data *data) +static bool get_video_headers(struct ffmpeg_output *stream, struct ffmpeg_data *data) { AVCodecParameters *par = data->video->codecpar; obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output); - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1}; if (obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size)) { par->extradata = av_memdup(packet.data, packet.size); par->extradata_size = (int)packet.size; - avcodec_parameters_to_context(data->video_ctx, - data->video->codecpar); + avcodec_parameters_to_context(data->video_ctx, data->video->codecpar); return 1; } return 0; } -static bool create_video_stream(struct ffmpeg_output *stream, - struct ffmpeg_data *data) +static bool create_video_stream(struct ffmpeg_output *stream, struct ffmpeg_data *data) { AVCodecContext *context; struct obs_video_info ovi; @@ -170,8 +153,7 @@ static bool create_video_stream(struct ffmpeg_output *stream, context->color_primaries = data->config.color_primaries; context->color_trc = data->config.color_trc; context->colorspace = data->config.colorspace; - context->chroma_sample_location = determine_chroma_location( - data->config.format, data->config.colorspace); + context->chroma_sample_location = determine_chroma_location(data->config.format, data->config.colorspace); context->thread_count = 0; data->video->time_base = context->time_base; @@ -186,23 +168,17 @@ static bool create_video_stream(struct ffmpeg_output *stream, const bool pq = data->config.color_trc == AVCOL_TRC_SMPTE2084; const bool hlg = data->config.color_trc == AVCOL_TRC_ARIB_STD_B67; if (pq || hlg) { - const int hdr_nominal_peak_level = - pq ? (int)obs_get_video_hdr_nominal_peak_level() - : (hlg ? 1000 : 0); + const int hdr_nominal_peak_level = pq ? (int)obs_get_video_hdr_nominal_peak_level() : (hlg ? 1000 : 0); size_t content_size; - AVContentLightMetadata *const content = - av_content_light_metadata_alloc(&content_size); + AVContentLightMetadata *const content = av_content_light_metadata_alloc(&content_size); content->MaxCLL = hdr_nominal_peak_level; content->MaxFALL = hdr_nominal_peak_level; - av_packet_side_data_add( - &data->video->codecpar->coded_side_data, - &data->video->codecpar->nb_coded_side_data, - AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)content, - content_size, 0); + av_packet_side_data_add(&data->video->codecpar->coded_side_data, + &data->video->codecpar->nb_coded_side_data, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, + (uint8_t *)content, content_size, 0); - AVMasteringDisplayMetadata *const mastering = - av_mastering_display_metadata_alloc(); + AVMasteringDisplayMetadata *const mastering = av_mastering_display_metadata_alloc(); mastering->display_primaries[0][0] = av_make_q(17, 25); mastering->display_primaries[0][1] = av_make_q(8, 25); mastering->display_primaries[1][0] = av_make_q(53, 200); @@ -215,18 +191,16 @@ static bool create_video_stream(struct ffmpeg_output *stream, mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1); mastering->has_primaries = 1; mastering->has_luminance = 1; - av_packet_side_data_add( - &data->video->codecpar->coded_side_data, - &data->video->codecpar->nb_coded_side_data, - AV_PKT_DATA_MASTERING_DISPLAY_METADATA, - (uint8_t *)mastering, sizeof(*mastering), 0); + av_packet_side_data_add(&data->video->codecpar->coded_side_data, + &data->video->codecpar->nb_coded_side_data, + AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)mastering, + sizeof(*mastering), 0); } return true; } -static bool create_audio_stream(struct ffmpeg_output *stream, - struct ffmpeg_data *data, int idx) +static bool create_audio_stream(struct ffmpeg_output *stream, struct ffmpeg_data *data, int idx) { AVCodecContext *context; AVStream *avstream; @@ -272,20 +246,17 @@ static bool create_audio_stream(struct ffmpeg_output *stream, data->audio_infos[idx].stream = avstream; data->audio_infos[idx].ctx = context; - avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar, - context); + avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar, context); return true; } -static inline bool init_streams(struct ffmpeg_output *stream, - struct ffmpeg_data *data) +static inline bool init_streams(struct ffmpeg_output *stream, struct ffmpeg_data *data) { if (!create_video_stream(stream, data)) return false; if (data->num_audio_streams) { - data->audio_infos = calloc(data->num_audio_streams, - sizeof(*data->audio_infos)); + data->audio_infos = calloc(data->num_audio_streams, sizeof(*data->audio_infos)); for (int i = 0; i < data->num_audio_streams; i++) { if (!create_audio_stream(stream, data, i)) return false; @@ -311,25 +282,20 @@ static inline int connect_mpegts_url(struct ffmpeg_output *stream, bool is_rist) int err = 0; const char *url = stream->ff_data.config.url; if (!ff_network_init()) { - ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data, - "Couldn't initialize network"); + ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data, "Couldn't initialize network"); return AVERROR(EIO); } URLContext *uc = av_mallocz(sizeof(URLContext) + strlen(url) + 1); if (!uc) { - ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data, - "Couldn't allocate memory"); + ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data, "Couldn't allocate memory"); goto fail; } uc->url = (char *)url; - uc->max_packet_size = is_rist ? RIST_MAX_PAYLOAD_SIZE - : SRT_LIVE_DEFAULT_PAYLOAD_SIZE; - uc->priv_data = is_rist ? av_mallocz(sizeof(RISTContext)) - : av_mallocz(sizeof(SRTContext)); + uc->max_packet_size = is_rist ? RIST_MAX_PAYLOAD_SIZE : SRT_LIVE_DEFAULT_PAYLOAD_SIZE; + uc->priv_data = is_rist ? av_mallocz(sizeof(RISTContext)) : av_mallocz(sizeof(SRTContext)); if (!uc->priv_data) { - ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data, - "Couldn't allocate memory"); + ffmpeg_mpegts_log_error(LOG_ERROR, &stream->ff_data, "Couldn't allocate memory"); goto fail; } /* For SRT, pass streamid & passphrase; for RIST, pass passphrase, username @@ -340,36 +306,29 @@ static inline int connect_mpegts_url(struct ffmpeg_output *stream, bool is_rist) context->streamid = NULL; if (stream->ff_data.config.stream_id != NULL) { if (strlen(stream->ff_data.config.stream_id)) - context->streamid = av_strdup( - stream->ff_data.config.stream_id); + context->streamid = av_strdup(stream->ff_data.config.stream_id); } context->passphrase = NULL; if (stream->ff_data.config.encrypt_passphrase != NULL) { if (strlen(stream->ff_data.config.encrypt_passphrase)) - context->passphrase = - av_strdup(stream->ff_data.config - .encrypt_passphrase); + context->passphrase = av_strdup(stream->ff_data.config.encrypt_passphrase); } } else { RISTContext *context = (RISTContext *)uc->priv_data; context->secret = NULL; if (stream->ff_data.config.encrypt_passphrase != NULL) { if (strlen(stream->ff_data.config.encrypt_passphrase)) - context->secret = - bstrdup(stream->ff_data.config - .encrypt_passphrase); + context->secret = bstrdup(stream->ff_data.config.encrypt_passphrase); } context->username = NULL; if (stream->ff_data.config.username != NULL) { if (strlen(stream->ff_data.config.username)) - context->username = bstrdup( - stream->ff_data.config.username); + context->username = bstrdup(stream->ff_data.config.username); } context->password = NULL; if (stream->ff_data.config.password != NULL) { if (strlen(stream->ff_data.config.password)) - context->password = bstrdup( - stream->ff_data.config.password); + context->password = bstrdup(stream->ff_data.config.password); } } stream->h = uc; @@ -397,8 +356,7 @@ typedef int (*write_packet_cb)(void *, const uint8_t *, int); typedef int (*write_packet_cb)(void *, uint8_t *, int); #endif -static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream, - bool is_rist) +static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream, bool is_rist) { /* allocate buffers */ uint8_t *buffer = NULL; @@ -413,12 +371,10 @@ static inline int allocate_custom_aviocontext(struct ffmpeg_output *stream, return AVERROR(ENOMEM); /* allocate custom avio_context */ if (is_rist) - s = avio_alloc_context(buffer, buffer_size, AVIO_FLAG_WRITE, h, - NULL, (write_packet_cb)librist_write, + s = avio_alloc_context(buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL, (write_packet_cb)librist_write, NULL); else - s = avio_alloc_context(buffer, buffer_size, AVIO_FLAG_WRITE, h, - NULL, (write_packet_cb)libsrt_write, + s = avio_alloc_context(buffer, buffer_size, AVIO_FLAG_WRITE, h, NULL, (write_packet_cb)libsrt_write, NULL); if (!s) goto fail; @@ -433,8 +389,7 @@ fail: return AVERROR(ENOMEM); } -static inline int open_output_file(struct ffmpeg_output *stream, - struct ffmpeg_data *data) +static inline int open_output_file(struct ffmpeg_output *stream, struct ffmpeg_data *data) { int ret; bool rist = data->config.is_rist; @@ -446,14 +401,9 @@ static inline int open_output_file(struct ffmpeg_output *stream, * These options will be passed to protocol by avio_open2 through dict. * The invalid options will be left in dict. */ if (!rist && !srt) { - if ((ret = av_dict_parse_string(&dict, - data->config.protocol_settings, - "=", " ", 0))) { - ffmpeg_mpegts_log_error( - LOG_WARNING, data, - "Failed to parse protocol settings: %s, %s", - data->config.protocol_settings, - av_err2str(ret)); + if ((ret = av_dict_parse_string(&dict, data->config.protocol_settings, "=", " ", 0))) { + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Failed to parse protocol settings: %s, %s", + data->config.protocol_settings, av_err2str(ret)); av_dict_free(&dict); return OBS_OUTPUT_INVALID_STREAM; @@ -463,10 +413,8 @@ static inline int open_output_file(struct ffmpeg_output *stream, struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) - dstr_catf(&str, "\n\t%s=%s", entry->key, - entry->value); + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) + dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); info("Using protocol settings: %s", str.array); dstr_free(&str); @@ -484,22 +432,17 @@ static inline int open_output_file(struct ffmpeg_output *stream, } else if (srt) { ret = connect_mpegts_url(stream, false); } else if (allowed_proto) { - ret = avio_open2(&data->output->pb, data->config.url, - AVIO_FLAG_WRITE, NULL, &dict); + ret = avio_open2(&data->output->pb, data->config.url, AVIO_FLAG_WRITE, NULL, &dict); } else { - info("[ffmpeg mpegts muxer]: Invalid protocol: %s", - data->config.url); + info("[ffmpeg mpegts muxer]: Invalid protocol: %s", data->config.url); return OBS_OUTPUT_BAD_PATH; } if (ret < 0) { - if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED || - ret == OBS_OUTPUT_INVALID_STREAM)) { + if ((rist || srt) && (ret == OBS_OUTPUT_CONNECT_FAILED || ret == OBS_OUTPUT_INVALID_STREAM)) { error("Failed to open the url or invalid stream"); } else { - ffmpeg_mpegts_log_error(LOG_WARNING, data, - "Couldn't open '%s', %s", - data->config.url, + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Couldn't open '%s', %s", data->config.url, av_err2str(ret)); av_dict_free(&dict); } @@ -515,21 +458,18 @@ static inline int open_output_file(struct ffmpeg_output *stream, struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) - dstr_catf(&str, "\n\t%s=%s", entry->key, - entry->value); + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) + dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); - info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s", - str.array); + info("[ffmpeg mpegts muxer]: Invalid protocol settings: %s", str.array); dstr_free(&str); } av_dict_free(&dict); } else { ret = allocate_custom_aviocontext(stream, rist); if (ret < 0) { - info("Couldn't allocate custom avio_context for url: '%s', %s", - data->config.url, av_err2str(ret)); + info("Couldn't allocate custom avio_context for url: '%s', %s", data->config.url, + av_err2str(ret)); return OBS_OUTPUT_INVALID_STREAM; } } @@ -585,12 +525,10 @@ static void close_mpegts_url(struct ffmpeg_output *stream, bool is_rist) avio_context_free(&s); if (err) - info("[ffmpeg mpegts muxer]: Error closing URL %s", - stream->ff_data.config.url); + info("[ffmpeg mpegts muxer]: Error closing URL %s", stream->ff_data.config.url); } -void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream, - struct ffmpeg_data *data) +void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream, struct ffmpeg_data *data) { if (data->initialized) av_write_trailer(data->output); @@ -621,9 +559,7 @@ void ffmpeg_mpegts_data_free(struct ffmpeg_output *stream, memset(data, 0, sizeof(struct ffmpeg_data)); } -bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream, - struct ffmpeg_data *data, - struct ffmpeg_cfg *config) +bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream, struct ffmpeg_data *data, struct ffmpeg_cfg *config) { memset(data, 0, sizeof(struct ffmpeg_data)); data->config = *config; @@ -634,30 +570,22 @@ bool ffmpeg_mpegts_data_init(struct ffmpeg_output *stream, avformat_network_init(); - const AVOutputFormat *output_format = - av_guess_format("mpegts", NULL, "video/M2PT"); + const AVOutputFormat *output_format = av_guess_format("mpegts", NULL, "video/M2PT"); if (output_format == NULL) { - ffmpeg_mpegts_log_error(LOG_WARNING, data, - "Couldn't set output format to mpegts"); + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Couldn't set output format to mpegts"); goto fail; } else { - info("Output format name and long_name: %s, %s", - output_format->name ? output_format->name : "unknown", - output_format->long_name ? output_format->long_name - : "unknown"); + info("Output format name and long_name: %s, %s", output_format->name ? output_format->name : "unknown", + output_format->long_name ? output_format->long_name : "unknown"); } - avformat_alloc_output_context2(&data->output, output_format, NULL, - data->config.url); - av_dict_set(&data->output->metadata, "service_provider", "obs-studio", - 0); - av_dict_set(&data->output->metadata, "service_name", "mpegts output", - 0); + avformat_alloc_output_context2(&data->output, output_format, NULL, data->config.url); + av_dict_set(&data->output->metadata, "service_provider", "obs-studio", 0); + av_dict_set(&data->output->metadata, "service_name", "mpegts output", 0); if (!data->output) { - ffmpeg_mpegts_log_error(LOG_WARNING, data, - "Couldn't create avformat context"); + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Couldn't create avformat context"); goto fail; } @@ -681,8 +609,7 @@ static const char *ffmpeg_mpegts_getname(void *unused) return obs_module_text("FFmpegMpegts"); } -static void ffmpeg_mpegts_log_callback(void *param, int level, - const char *format, va_list args) +static void ffmpeg_mpegts_log_callback(void *param, int level, const char *format, va_list args) { if (level <= AV_LOG_INFO) blogva(LOG_DEBUG, format, args); @@ -734,8 +661,7 @@ static void ffmpeg_mpegts_destroy(void *data) } } -static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, - AVPacket *packet) +static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, AVPacket *packet) { struct ffmpeg_data *data = &output->ff_data; uint64_t pause_offset = obs_output_get_pause_offset(output->output); @@ -751,9 +677,7 @@ static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, start_ts = output->audio_start_ts; } - return start_ts + pause_offset + - (uint64_t)av_rescale_q(packet->dts, time_base, - (AVRational){1, 1000000000}); + return start_ts + pause_offset + (uint64_t)av_rescale_q(packet->dts, time_base, (AVRational){1, 1000000000}); } static int mpegts_process_packet(struct ffmpeg_output *output) @@ -790,10 +714,8 @@ static int mpegts_process_packet(struct ffmpeg_output *output) av_freep(&buf); if (ret < 0) { - ffmpeg_mpegts_log_error( - LOG_WARNING, &output->ff_data, - "process_packet: Error writing packet: %s", - av_err2str(ret)); + ffmpeg_mpegts_log_error(LOG_WARNING, &output->ff_data, "process_packet: Error writing packet: %s", + av_err2str(ret)); /* Treat "Invalid data found when processing input" and * "Invalid argument" as non-fatal */ @@ -863,16 +785,11 @@ static bool set_config(struct ffmpeg_output *stream) service = obs_output_get_service(stream->output); if (!service) return false; - config.url = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); - config.username = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_USERNAME); - config.password = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_PASSWORD); - config.stream_id = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_STREAM_ID); - config.encrypt_passphrase = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_ENCRYPT_PASSPHRASE); + config.url = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); + config.username = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_USERNAME); + config.password = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_PASSWORD); + config.stream_id = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_STREAM_ID); + config.encrypt_passphrase = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_ENCRYPT_PASSPHRASE); config.format_name = "mpegts"; config.format_mime_type = "video/M2PT"; config.is_rist = is_rist(config.url); @@ -895,21 +812,17 @@ static bool set_config(struct ffmpeg_output *stream) // 2.c) set video format from OBS to FFmpeg video_t *video = obs_encoder_video(vencoder); - config.format = - obs_to_ffmpeg_video_format(video_output_get_format(video)); + config.format = obs_to_ffmpeg_video_format(video_output_get_format(video)); if (config.format == AV_PIX_FMT_NONE) { - blog(LOG_WARNING, - "Invalid pixel format used for mpegts output"); + blog(LOG_WARNING, "Invalid pixel format used for mpegts output"); return false; } // 2.d) set colorspace, color_range & transfer characteristic (from voi) const struct video_output_info *voi = video_output_get_info(video); - config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG - : AVCOL_RANGE_MPEG; - config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709 - : AVCOL_SPC_RGB; + config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; + config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709 : AVCOL_SPC_RGB; switch (voi->colorspace) { case VIDEO_CS_601: config.color_primaries = AVCOL_PRI_SMPTE170M; @@ -941,8 +854,7 @@ static bool set_config(struct ffmpeg_output *stream) obs_data_t *settings = obs_encoder_get_settings(vencoder); config.video_bitrate = (int)obs_data_get_int(settings, "bitrate"); int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); - config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den - : 250; + config.gop_size = keyint_sec ? keyint_sec * voi->fps_num / voi->fps_den : 250; obs_data_release(settings); /* 3. Audio settings */ @@ -951,8 +863,7 @@ static bool set_config(struct ffmpeg_output *stream) int num_tracks = 0; for (;;) { - obs_encoder_t *aencoder = obs_output_get_audio_encoder( - stream->output, num_tracks); + obs_encoder_t *aencoder = obs_output_get_audio_encoder(stream->output, num_tracks); if (!aencoder) break; @@ -971,8 +882,7 @@ static bool set_config(struct ffmpeg_output *stream) // 3.c) get audio bitrate from the audio encoder. for (int idx = 0; idx < num_tracks; idx++) { settings = obs_encoder_get_settings(aencoders[idx]); - config.audio_bitrates[idx] = - (int)obs_data_get_int(settings, "bitrate"); + config.audio_bitrates[idx] = (int)obs_data_get_int(settings, "bitrate"); obs_data_release(settings); } @@ -995,8 +905,7 @@ static bool set_config(struct ffmpeg_output *stream) success = ffmpeg_mpegts_data_init(stream, &stream->ff_data, &config); if (!success) { if (stream->ff_data.last_error) { - obs_output_set_last_error(stream->output, - stream->ff_data.last_error); + obs_output_set_last_error(stream->output, stream->ff_data.last_error); } ffmpeg_mpegts_data_free(stream, &stream->ff_data); code = OBS_OUTPUT_INVALID_STREAM; @@ -1023,10 +932,9 @@ static bool set_config(struct ffmpeg_output *stream) ret = pthread_create(&stream->write_thread, NULL, write_thread, stream); if (ret != 0) { - ffmpeg_mpegts_log_error( - LOG_WARNING, &stream->ff_data, - "ffmpeg_output_start: Failed to create write " - "thread."); + ffmpeg_mpegts_log_error(LOG_WARNING, &stream->ff_data, + "ffmpeg_output_start: Failed to create write " + "thread."); code = OBS_OUTPUT_ERROR; goto fail; } @@ -1119,22 +1027,18 @@ static uint64_t ffmpeg_mpegts_total_bytes(void *data) return output->total_bytes; } -static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base, - int64_t val) +static inline int64_t rescale_ts2(AVStream *stream, AVRational codec_time_base, int64_t val) { - return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base, - stream->time_base, + return av_rescale_q_rnd(val / codec_time_base.num, codec_time_base, stream->time_base, AV_ROUND_NEAR_INF | AV_ROUND_PASS_MINMAX); } /* Convert obs encoder_packet to FFmpeg AVPacket and write to circular buffer * where it will be processed in the write_thread by process_packet. */ -void mpegts_write_packet(struct ffmpeg_output *stream, - struct encoder_packet *encpacket) +void mpegts_write_packet(struct ffmpeg_output *stream, struct encoder_packet *encpacket) { - if (stopping(stream) || !stream->ff_data.video || - !stream->ff_data.video_ctx || !stream->ff_data.audio_infos) + if (stopping(stream) || !stream->ff_data.video || !stream->ff_data.video_ctx || !stream->ff_data.audio_infos) return; bool is_video = encpacket->type == OBS_ENCODER_VIDEO; if (!is_video) { @@ -1142,16 +1046,12 @@ void mpegts_write_packet(struct ffmpeg_output *stream, return; } - AVStream *avstream = - is_video ? stream->ff_data.video - : stream->ff_data.audio_infos[encpacket->track_idx] - .stream; + AVStream *avstream = is_video ? stream->ff_data.video + : stream->ff_data.audio_infos[encpacket->track_idx].stream; AVPacket *packet = NULL; - const AVRational codec_time_base = - is_video ? stream->ff_data.video_ctx->time_base - : stream->ff_data.audio_infos[encpacket->track_idx] - .ctx->time_base; + const AVRational codec_time_base = is_video ? stream->ff_data.video_ctx->time_base + : stream->ff_data.audio_infos[encpacket->track_idx].ctx->time_base; packet = av_packet_alloc(); @@ -1182,12 +1082,9 @@ static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data) AVDictionary *dict = NULL; int ret; /* get mpegts muxer settings (can be used with rist, srt, rtp, etc ... */ - if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=", - " ", 0))) { - ffmpeg_mpegts_log_error( - LOG_WARNING, data, - "Failed to parse muxer settings: %s, %s", - data->config.muxer_settings, av_err2str(ret)); + if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=", " ", 0))) { + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Failed to parse muxer settings: %s, %s", + data->config.muxer_settings, av_err2str(ret)); av_dict_free(&dict); return false; @@ -1197,8 +1094,7 @@ static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data) struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); info("Using muxer settings: %s", str.array); @@ -1208,10 +1104,8 @@ static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data) /* Allocate the stream private data and write the stream header. */ ret = avformat_write_header(data->output, &dict); if (ret < 0) { - ffmpeg_mpegts_log_error( - LOG_WARNING, data, - "Error setting stream header for '%s': %s", - data->config.url, av_err2str(ret)); + ffmpeg_mpegts_log_error(LOG_WARNING, data, "Error setting stream header for '%s': %s", data->config.url, + av_err2str(ret)); return false; } @@ -1220,12 +1114,10 @@ static bool write_header(struct ffmpeg_output *stream, struct ffmpeg_data *data) struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); - info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s", - str.array); + info("[ffmpeg mpegts muxer]: Invalid mpegts muxer settings: %s", str.array); dstr_free(&str); } av_dict_free(&dict); @@ -1285,15 +1177,13 @@ static obs_properties_t *ffmpeg_mpegts_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "path", obs_module_text("FilePath"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "path", obs_module_text("FilePath"), OBS_TEXT_DEFAULT); return props; } struct obs_output_info ffmpeg_mpegts_muxer = { .id = "ffmpeg_mpegts_muxer", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | - OBS_OUTPUT_SERVICE, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_SERVICE, .protocols = "SRT;RIST", #ifdef ENABLE_HEVC .encoded_video_codecs = "h264;hevc", diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-mux.c b/plugins/obs-ffmpeg/obs-ffmpeg-mux.c index 111b48336..8a03c045a 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-mux.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-mux.c @@ -24,9 +24,8 @@ #include -#define do_log(level, format, ...) \ - blog(level, "[ffmpeg muxer: '%s'] " format, \ - obs_output_get_name(stream->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[ffmpeg muxer: '%s'] " format, obs_output_get_name(stream->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -105,8 +104,7 @@ static void *ffmpeg_mux_create(obs_data_t *settings, obs_output_t *output) signal_handler_add(sh, "void file_changed(string next_file)"); proc_handler_t *ph = obs_output_get_proc_handler(output); - proc_handler_add(ph, "void split_file(out bool split_file_enabled)", - split_file_proc, stream); + proc_handler_add(ph, "void split_file(out bool split_file_enabled)", split_file_proc, stream); UNUSED_PARAMETER(settings); return stream; @@ -133,9 +131,7 @@ bool active(struct ffmpeg_muxer *stream) return os_atomic_load_bool(&stream->active); } -static void add_video_encoder_params(struct ffmpeg_muxer *stream, - os_process_args_t *args, - obs_encoder_t *vencoder) +static void add_video_encoder_params(struct ffmpeg_muxer *stream, os_process_args_t *args, obs_encoder_t *vencoder) { obs_data_t *settings = obs_encoder_get_settings(vencoder); int bitrate = (int)obs_data_get_int(settings, "bitrate"); @@ -144,10 +140,8 @@ static void add_video_encoder_params(struct ffmpeg_muxer *stream, int codec_tag = (int)obs_data_get_int(settings, "codec_type"); #if __BYTE_ORDER == __LITTLE_ENDIAN - codec_tag = ((codec_tag >> 24) & 0x000000FF) | - ((codec_tag << 8) & 0x00FF0000) | - ((codec_tag >> 8) & 0x0000FF00) | - ((codec_tag << 24) & 0xFF000000); + codec_tag = ((codec_tag >> 24) & 0x000000FF) | ((codec_tag << 8) & 0x00FF0000) | + ((codec_tag >> 8) & 0x0000FF00) | ((codec_tag << 24) & 0xFF000000); #endif obs_data_release(settings); @@ -183,23 +177,17 @@ static void add_video_encoder_params(struct ffmpeg_muxer *stream, spc = AVCOL_SPC_BT2020_NCL; } - const enum AVColorRange range = (info->range == VIDEO_RANGE_FULL) - ? AVCOL_RANGE_JPEG - : AVCOL_RANGE_MPEG; - const enum AVChromaLocation chroma_location = determine_chroma_location( - obs_to_ffmpeg_video_format(info->format), spc); + const enum AVColorRange range = (info->range == VIDEO_RANGE_FULL) ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; + const enum AVChromaLocation chroma_location = + determine_chroma_location(obs_to_ffmpeg_video_format(info->format), spc); - const int max_luminance = - (trc == AVCOL_TRC_SMPTE2084) - ? (int)obs_get_video_hdr_nominal_peak_level() - : ((trc == AVCOL_TRC_ARIB_STD_B67) ? 1000 : 0); + const int max_luminance = (trc == AVCOL_TRC_SMPTE2084) ? (int)obs_get_video_hdr_nominal_peak_level() + : ((trc == AVCOL_TRC_ARIB_STD_B67) ? 1000 : 0); os_process_args_add_arg(args, obs_encoder_get_codec(vencoder)); os_process_args_add_argf(args, "%d", bitrate); - os_process_args_add_argf(args, "%d", - obs_output_get_width(stream->output)); - os_process_args_add_argf(args, "%d", - obs_output_get_height(stream->output)); + os_process_args_add_argf(args, "%d", obs_output_get_width(stream->output)); + os_process_args_add_argf(args, "%d", obs_output_get_height(stream->output)); os_process_args_add_argf(args, "%d", (int)pri); os_process_args_add_argf(args, "%d", (int)trc); os_process_args_add_argf(args, "%d", (int)spc); @@ -211,8 +199,7 @@ static void add_video_encoder_params(struct ffmpeg_muxer *stream, os_process_args_add_argf(args, "%d", codec_tag); } -static void add_audio_encoder_params(os_process_args_t *args, - obs_encoder_t *aencoder) +static void add_audio_encoder_params(os_process_args_t *args, obs_encoder_t *aencoder) { obs_data_t *settings = obs_encoder_get_settings(aencoder); int bitrate = (int)obs_data_get_int(settings, "bitrate"); @@ -222,12 +209,9 @@ static void add_audio_encoder_params(os_process_args_t *args, os_process_args_add_arg(args, obs_encoder_get_name(aencoder)); os_process_args_add_argf(args, "%d", bitrate); - os_process_args_add_argf(args, "%d", - (int)obs_encoder_get_sample_rate(aencoder)); - os_process_args_add_argf(args, "%d", - (int)obs_encoder_get_frame_size(aencoder)); - os_process_args_add_argf(args, "%d", - (int)audio_output_get_channels(audio)); + os_process_args_add_argf(args, "%d", (int)obs_encoder_get_sample_rate(aencoder)); + os_process_args_add_argf(args, "%d", (int)obs_encoder_get_frame_size(aencoder)); + os_process_args_add_argf(args, "%d", (int)audio_output_get_channels(audio)); } static void log_muxer_params(struct ffmpeg_muxer *stream, const char *settings) @@ -236,8 +220,7 @@ static void log_muxer_params(struct ffmpeg_muxer *stream, const char *settings) AVDictionary *dict = NULL; if ((ret = av_dict_parse_string(&dict, settings, "=", " ", 0))) { - warn("Failed to parse muxer settings: %s\n%s", av_err2str(ret), - settings); + warn("Failed to parse muxer settings: %s\n%s", av_err2str(ret), settings); av_dict_free(&dict); return; @@ -247,8 +230,7 @@ static void log_muxer_params(struct ffmpeg_muxer *stream, const char *settings) struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); info("Using muxer settings:%s", str.array); @@ -260,20 +242,16 @@ static void log_muxer_params(struct ffmpeg_muxer *stream, const char *settings) static void add_stream_key(os_process_args_t *args, struct ffmpeg_muxer *stream) { - os_process_args_add_arg(args, dstr_is_empty(&stream->stream_key) - ? "" - : stream->stream_key.array); + os_process_args_add_arg(args, dstr_is_empty(&stream->stream_key) ? "" : stream->stream_key.array); } -static void add_muxer_params(os_process_args_t *args, - struct ffmpeg_muxer *stream) +static void add_muxer_params(os_process_args_t *args, struct ffmpeg_muxer *stream) { struct dstr mux = {0}; if (dstr_is_empty(&stream->muxer_settings)) { obs_data_t *settings = obs_output_get_settings(stream->output); - dstr_copy(&mux, - obs_data_get_string(settings, "muxer_settings")); + dstr_copy(&mux, obs_data_get_string(settings, "muxer_settings")); obs_data_release(settings); } else { dstr_copy(&mux, stream->muxer_settings.array); @@ -285,16 +263,14 @@ static void add_muxer_params(os_process_args_t *args, dstr_free(&mux); } -static void build_command_line(struct ffmpeg_muxer *stream, - os_process_args_t **args, const char *path) +static void build_command_line(struct ffmpeg_muxer *stream, os_process_args_t **args, const char *path) { obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output); obs_encoder_t *aencoders[MAX_AUDIO_MIXES]; int num_tracks = 0; for (;;) { - obs_encoder_t *aencoder = obs_output_get_audio_encoder( - stream->output, num_tracks); + obs_encoder_t *aencoder = obs_output_get_audio_encoder(stream->output, num_tracks); if (!aencoder) break; @@ -315,8 +291,7 @@ static void build_command_line(struct ffmpeg_muxer *stream, add_video_encoder_params(stream, *args, vencoder); if (num_tracks) { - os_process_args_add_arg(*args, - obs_encoder_get_codec(aencoders[0])); + os_process_args_add_arg(*args, obs_encoder_get_codec(aencoders[0])); for (int i = 0; i < num_tracks; i++) { add_audio_encoder_params(*args, aencoders[i]); @@ -335,8 +310,7 @@ void start_pipe(struct ffmpeg_muxer *stream, const char *path) os_process_args_destroy(args); } -static void set_file_not_readable_error(struct ffmpeg_muxer *stream, - obs_data_t *settings, const char *path) +static void set_file_not_readable_error(struct ffmpeg_muxer *stream, obs_data_t *settings, const char *path) { struct dstr error_message; dstr_init_copy(&error_message, obs_module_text("UnableToWritePath")); @@ -346,8 +320,7 @@ static void set_file_not_readable_error(struct ffmpeg_muxer *stream, get_win_ver(&ver); if (ver.major >= 10) { dstr_cat(&error_message, "\n\n"); - dstr_cat(&error_message, - obs_module_text("WarnWindowsDefender")); + dstr_cat(&error_message, obs_module_text("WarnWindowsDefender")); } #endif dstr_replace(&error_message, "%1", path); @@ -372,8 +345,7 @@ static inline int64_t packet_pts_usec(struct encoder_packet *packet) return packet->pts * 1000000 / packet->timebase_den; } -inline static void ts_offset_update(struct ffmpeg_muxer *stream, - struct encoder_packet *packet) +inline static void ts_offset_update(struct ffmpeg_muxer *stream, struct encoder_packet *packet) { if (packet->type == OBS_ENCODER_VIDEO) { if (!stream->found_video) { @@ -390,8 +362,7 @@ inline static void ts_offset_update(struct ffmpeg_muxer *stream, stream->found_audio[packet->track_idx] = true; } -static inline void update_encoder_settings(struct ffmpeg_muxer *stream, - const char *path) +static inline void update_encoder_settings(struct ffmpeg_muxer *stream, const char *path) { obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output); const char *ext = strrchr(path, '.'); @@ -405,8 +376,7 @@ static inline void update_encoder_settings(struct ffmpeg_muxer *stream, } } -static inline bool ffmpeg_mux_start_internal(struct ffmpeg_muxer *stream, - obs_data_t *settings) +static inline bool ffmpeg_mux_start_internal(struct ffmpeg_muxer *stream, obs_data_t *settings) { const char *path = obs_data_get_string(settings, "path"); @@ -422,18 +392,14 @@ static inline bool ffmpeg_mux_start_internal(struct ffmpeg_muxer *stream, service = obs_output_get_service(stream->output); if (!service) return false; - path = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); + path = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); stream->split_file = false; } else { - stream->max_time = - obs_data_get_int(settings, "max_time_sec") * 1000000LL; - stream->max_size = obs_data_get_int(settings, "max_size_mb") * - (1024 * 1024); + stream->max_time = obs_data_get_int(settings, "max_time_sec") * 1000000LL; + stream->max_size = obs_data_get_int(settings, "max_size_mb") * (1024 * 1024); stream->split_file = obs_data_get_bool(settings, "split_file"); - stream->allow_overwrite = - obs_data_get_bool(settings, "allow_overwrite"); + stream->allow_overwrite = obs_data_get_bool(settings, "allow_overwrite"); stream->cur_size = 0; stream->sent_headers = false; } @@ -459,8 +425,7 @@ static inline bool ffmpeg_mux_start_internal(struct ffmpeg_muxer *stream, start_pipe(stream, path); if (!stream->pipe) { - obs_output_set_last_error( - stream->output, obs_module_text("HelperProcessFailed")); + obs_output_set_last_error(stream->output, obs_module_text("HelperProcessFailed")); warn("Failed to create process pipe"); return false; } @@ -508,9 +473,7 @@ int deactivate(struct ffmpeg_muxer *stream, int code) os_atomic_set_bool(&stream->sent_headers, false); info("Output of file '%s' stopped", - dstr_is_empty(&stream->printable_path) - ? stream->path.array - : stream->printable_path.array); + dstr_is_empty(&stream->printable_path) ? stream->path.array : stream->printable_path.array); } if (code) { @@ -524,8 +487,7 @@ int deactivate(struct ffmpeg_muxer *stream, int code) while (stream->packets.size) { struct encoder_packet packet; - deque_pop_front(&stream->packets, &packet, - sizeof(packet)); + deque_pop_front(&stream->packets, &packet, sizeof(packet)); obs_encoder_packet_release(&packet); } @@ -555,8 +517,7 @@ static void signal_failure(struct ffmpeg_muxer *stream) size_t len; - len = os_process_pipe_read_err(stream->pipe, (uint8_t *)error, - sizeof(error) - 1); + len = os_process_pipe_read_err(stream->pipe, (uint8_t *)error, sizeof(error) - 1); if (len > 0) { error[len] = 0; @@ -609,8 +570,7 @@ static void find_best_filename(struct dstr *path, bool space) } } -static void generate_filename(struct ffmpeg_muxer *stream, struct dstr *dst, - bool overwrite) +static void generate_filename(struct ffmpeg_muxer *stream, struct dstr *dst, bool overwrite) { obs_data_t *settings = obs_output_get_settings(stream->output); const char *dir = obs_data_get_string(settings, "directory"); @@ -649,8 +609,7 @@ bool write_packet(struct ffmpeg_muxer *stream, struct encoder_packet *packet) .dts = packet->dts, .size = (uint32_t)packet->size, .index = (int)packet->track_idx, - .type = is_video ? FFM_PACKET_VIDEO - : FFM_PACKET_AUDIO, + .type = is_video ? FFM_PACKET_VIDEO : FFM_PACKET_AUDIO, .keyframe = packet->keyframe}; if (stream->split_file) { @@ -663,8 +622,7 @@ bool write_packet(struct ffmpeg_muxer *stream, struct encoder_packet *packet) } } - ret = os_process_pipe_write(stream->pipe, (const uint8_t *)&info, - sizeof(info)); + ret = os_process_pipe_write(stream->pipe, (const uint8_t *)&info, sizeof(info)); if (ret != sizeof(info)) { warn("os_process_pipe_write for info structure failed"); signal_failure(stream); @@ -686,12 +644,9 @@ bool write_packet(struct ffmpeg_muxer *stream, struct encoder_packet *packet) return true; } -static bool send_audio_headers(struct ffmpeg_muxer *stream, - obs_encoder_t *aencoder, size_t idx) +static bool send_audio_headers(struct ffmpeg_muxer *stream, obs_encoder_t *aencoder, size_t idx) { - struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, - .timebase_den = 1, - .track_idx = idx}; + struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, .timebase_den = 1, .track_idx = idx}; if (!obs_encoder_get_extra_data(aencoder, &packet.data, &packet.size)) return false; @@ -702,8 +657,7 @@ static bool send_video_headers(struct ffmpeg_muxer *stream) { obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output); - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1}; if (!obs_encoder_get_extra_data(vencoder, &packet.data, &packet.size)) return false; @@ -731,8 +685,7 @@ bool send_headers(struct ffmpeg_muxer *stream) return true; } -static inline bool should_split(struct ffmpeg_muxer *stream, - struct encoder_packet *packet) +static inline bool should_split(struct ffmpeg_muxer *stream, struct encoder_packet *packet) { /* split at video frame */ if (packet->type != OBS_ENCODER_VIDEO) @@ -746,13 +699,11 @@ static inline bool should_split(struct ffmpeg_muxer *stream, return true; /* reached maximum file size */ - if (stream->max_size > 0 && - stream->cur_size + (int64_t)packet->size >= stream->max_size) + if (stream->max_size > 0 && stream->cur_size + (int64_t)packet->size >= stream->max_size) return true; /* reached maximum duration */ - if (stream->max_time > 0 && - packet->dts_usec - stream->cur_time >= stream->max_time) + if (stream->max_time > 0 && packet->dts_usec - stream->cur_time >= stream->max_time) return true; return false; @@ -762,19 +713,16 @@ static bool send_new_filename(struct ffmpeg_muxer *stream, const char *filename) { size_t ret; uint32_t size = (uint32_t)strlen(filename); - struct ffm_packet_info info = {.type = FFM_PACKET_CHANGE_FILE, - .size = size}; + struct ffm_packet_info info = {.type = FFM_PACKET_CHANGE_FILE, .size = size}; - ret = os_process_pipe_write(stream->pipe, (const uint8_t *)&info, - sizeof(info)); + ret = os_process_pipe_write(stream->pipe, (const uint8_t *)&info, sizeof(info)); if (ret != sizeof(info)) { warn("os_process_pipe_write for info structure failed"); signal_failure(stream); return false; } - ret = os_process_pipe_write(stream->pipe, (const uint8_t *)filename, - size); + ret = os_process_pipe_write(stream->pipe, (const uint8_t *)filename, size); if (ret != size) { warn("os_process_pipe_write for packet data failed"); signal_failure(stream); @@ -784,8 +732,7 @@ static bool send_new_filename(struct ffmpeg_muxer *stream, const char *filename) return true; } -static bool prepare_split_file(struct ffmpeg_muxer *stream, - struct encoder_packet *packet) +static bool prepare_split_file(struct ffmpeg_muxer *stream, struct encoder_packet *packet) { generate_filename(stream, &stream->path, stream->allow_overwrite); info("Changing output file to '%s'", stream->path.array); @@ -816,8 +763,7 @@ static inline bool has_audio(struct ffmpeg_muxer *stream) return !!obs_output_get_audio_encoder(stream->output, 0); } -static void push_back_packet(mux_packets_t *packets, - struct encoder_packet *packet) +static void push_back_packet(mux_packets_t *packets, struct encoder_packet *packet) { struct encoder_packet pkt; obs_encoder_packet_ref(&pkt, packet); @@ -882,8 +828,7 @@ static void ffmpeg_mux_data(void *data, struct encoder_packet *packet) if (stream->split_file && stream->split_file_ready) { for (size_t i = 0; i < stream->mux_packets.num; i++) { - struct encoder_packet *pkt = - &stream->mux_packets.array[i]; + struct encoder_packet *pkt = &stream->mux_packets.array[i]; ts_offset_update(stream, pkt); write_packet(stream, pkt); obs_encoder_packet_release(pkt); @@ -905,8 +850,7 @@ static obs_properties_t *ffmpeg_mux_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "path", obs_module_text("FilePath"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "path", obs_module_text("FilePath"), OBS_TEXT_DEFAULT); return props; } @@ -918,8 +862,7 @@ uint64_t ffmpeg_mux_total_bytes(void *data) struct obs_output_info ffmpeg_muxer = { .id = "ffmpeg_muxer", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | - OBS_OUTPUT_CAN_PAUSE, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_CAN_PAUSE, .get_name = ffmpeg_mux_getname, .create = ffmpeg_mux_create, .destroy = ffmpeg_mux_destroy, @@ -947,8 +890,7 @@ static int ffmpeg_mpegts_mux_connect_time(void *data) struct obs_output_info ffmpeg_mpegts_muxer = { .id = "ffmpeg_mpegts_muxer", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | - OBS_OUTPUT_SERVICE, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_SERVICE, .protocols = "SRT;RIST", .encoded_video_codecs = "h264", .encoded_audio_codecs = "aac;opus", @@ -971,8 +913,7 @@ static const char *replay_buffer_getname(void *type) return obs_module_text("ReplayBuffer"); } -static void replay_buffer_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void replay_buffer_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -983,8 +924,7 @@ static void replay_buffer_hotkey(void *data, obs_hotkey_id id, struct ffmpeg_muxer *stream = data; if (os_atomic_load_bool(&stream->active)) { - obs_encoder_t *vencoder = - obs_output_get_video_encoder(stream->output); + obs_encoder_t *vencoder = obs_output_get_video_encoder(stream->output); if (obs_encoder_paused(vencoder)) { info("Could not save buffer because encoders paused"); return; @@ -1013,15 +953,12 @@ static void *replay_buffer_create(obs_data_t *settings, obs_output_t *output) struct ffmpeg_muxer *stream = bzalloc(sizeof(*stream)); stream->output = output; - stream->hotkey = - obs_hotkey_register_output(output, "ReplayBuffer.Save", - obs_module_text("ReplayBuffer.Save"), - replay_buffer_hotkey, stream); + stream->hotkey = obs_hotkey_register_output(output, "ReplayBuffer.Save", obs_module_text("ReplayBuffer.Save"), + replay_buffer_hotkey, stream); proc_handler_t *ph = obs_output_get_proc_handler(output); proc_handler_add(ph, "void save()", save_replay_proc, stream); - proc_handler_add(ph, "void get_last_replay(out string path)", - get_last_replay, stream); + proc_handler_add(ph, "void get_last_replay(out string path)", get_last_replay, stream); signal_handler_t *sh = obs_output_get_signal_handler(output); signal_handler_add(sh, "void saved()"); @@ -1105,15 +1042,13 @@ static inline void purge(struct ffmpeg_muxer *stream) } } -static inline void replay_buffer_purge(struct ffmpeg_muxer *stream, - struct encoder_packet *pkt) +static inline void replay_buffer_purge(struct ffmpeg_muxer *stream, struct encoder_packet *pkt) { if (stream->max_size) { if (!stream->packets.size || stream->keyframes <= 2) return; - while ((stream->cur_size + (int64_t)pkt->size) > - stream->max_size) + while ((stream->cur_size + (int64_t)pkt->size) > stream->max_size) purge(stream); } @@ -1124,9 +1059,8 @@ static inline void replay_buffer_purge(struct ffmpeg_muxer *stream, purge(stream); } -static void insert_packet(mux_packets_t *packets, struct encoder_packet *packet, - int64_t video_offset, int64_t *audio_offsets, - int64_t video_pts_offset, int64_t *audio_dts_offsets) +static void insert_packet(mux_packets_t *packets, struct encoder_packet *packet, int64_t video_offset, + int64_t *audio_offsets, int64_t video_pts_offset, int64_t *audio_dts_offsets) { struct encoder_packet pkt; size_t idx; @@ -1166,8 +1100,7 @@ static void *replay_buffer_mux_thread(void *data) } if (!send_headers(stream)) { - warn("Could not write headers for file '%s'", - stream->path.array); + warn("Could not write headers for file '%s'", stream->path.array); error = true; goto error; } @@ -1175,8 +1108,7 @@ static void *replay_buffer_mux_thread(void *data) for (size_t i = 0; i < stream->mux_packets.num; i++) { struct encoder_packet *pkt = &stream->mux_packets.array[i]; if (!write_packet(stream, pkt)) { - warn("Could not write packet for file '%s'", - stream->path.array); + warn("Could not write packet for file '%s'", stream->path.array); error = true; goto error; } @@ -1190,16 +1122,14 @@ error: stream->pipe = NULL; if (error) { for (size_t i = 0; i < stream->mux_packets.num; i++) - obs_encoder_packet_release( - &stream->mux_packets.array[i]); + obs_encoder_packet_release(&stream->mux_packets.array[i]); } da_free(stream->mux_packets); os_atomic_set_bool(&stream->muxing, false); if (!error) { calldata_t cd = {0}; - signal_handler_t *sh = - obs_output_get_signal_handler(stream->output); + signal_handler_t *sh = obs_output_get_signal_handler(stream->output); signal_handler_signal(sh, "saved", &cd); } @@ -1230,8 +1160,7 @@ static void replay_buffer_save(struct ffmpeg_muxer *stream) if (pkt->type == OBS_ENCODER_VIDEO) { if (!found_video) { video_pts_offset = pkt->pts; - video_offset = video_pts_offset * 1000000 / - pkt->timebase_den; + video_offset = video_pts_offset * 1000000 / pkt->timebase_den; found_video = true; } } else { @@ -1242,17 +1171,14 @@ static void replay_buffer_save(struct ffmpeg_muxer *stream) } } - insert_packet(&stream->mux_packets, pkt, video_offset, - audio_offsets, video_pts_offset, + insert_packet(&stream->mux_packets, pkt, video_offset, audio_offsets, video_pts_offset, audio_dts_offsets); } generate_filename(stream, &stream->path, true); os_atomic_set_bool(&stream->muxing, true); - stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL, - replay_buffer_mux_thread, - stream) == 0; + stream->mux_thread_joinable = pthread_create(&stream->mux_thread, NULL, replay_buffer_mux_thread, stream) == 0; if (!stream->mux_thread_joinable) { warn("Failed to create muxer thread"); os_atomic_set_bool(&stream->muxing, false); @@ -1331,8 +1257,7 @@ static void replay_buffer_defaults(obs_data_t *s) struct obs_output_info replay_buffer = { .id = "replay_buffer", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | - OBS_OUTPUT_CAN_PAUSE, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_CAN_PAUSE, .get_name = replay_buffer_getname, .create = replay_buffer_create, .destroy = replay_buffer_destroy, diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-nvenc.c b/plugins/obs-ffmpeg/obs-ffmpeg-nvenc.c index ba151b834..573d048cc 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-nvenc.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-nvenc.c @@ -22,9 +22,8 @@ #include "obs-ffmpeg-video-encoders.h" -#define do_log(level, format, ...) \ - blog(level, "[FFmpeg NVENC encoder: '%s'] " format, \ - obs_encoder_get_name(enc->ffve.encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[FFmpeg NVENC encoder: '%s'] " format, obs_encoder_get_name(enc->ffve.encoder), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -79,8 +78,7 @@ static void nvenc_video_info(void *data, struct video_scale_info *info) pref_format = obs_encoder_get_preferred_video_format(enc->ffve.encoder); if (!valid_format(pref_format)) { - pref_format = valid_format(info->format) ? info->format - : VIDEO_FORMAT_NV12; + pref_format = valid_format(info->format) ? info->format : VIDEO_FORMAT_NV12; } info->format = pref_format; @@ -88,14 +86,11 @@ static void nvenc_video_info(void *data, struct video_scale_info *info) static void set_psycho_aq(struct nvenc_encoder *enc, bool psycho_aq) { - av_opt_set_int(enc->ffve.context->priv_data, "spatial-aq", psycho_aq, - 0); - av_opt_set_int(enc->ffve.context->priv_data, "temporal-aq", psycho_aq, - 0); + av_opt_set_int(enc->ffve.context->priv_data, "spatial-aq", psycho_aq, 0); + av_opt_set_int(enc->ffve.context->priv_data, "temporal-aq", psycho_aq, 0); } -static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, - bool psycho_aq) +static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, bool psycho_aq) { const char *rc = obs_data_get_string(settings, "rate_control"); int bitrate = (int)obs_data_get_int(settings, "bitrate"); @@ -134,8 +129,7 @@ static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, av_opt_set_int(enc->ffve.context->priv_data, "cbr", false, 0); av_opt_set(enc->ffve.context->priv_data, "profile", profile, 0); - if (obs_data_has_user_value(settings, "preset") && - !obs_data_has_user_value(settings, "preset2")) { + if (obs_data_has_user_value(settings, "preset") && !obs_data_has_user_value(settings, "preset2")) { if (astrcmpi(preset, "mq") == 0) { preset = "hq"; @@ -144,8 +138,7 @@ static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, } else { av_opt_set(enc->ffve.context->priv_data, "preset", preset2, 0); av_opt_set(enc->ffve.context->priv_data, "tune", tuning, 0); - av_opt_set(enc->ffve.context->priv_data, "multipass", multipass, - 0); + av_opt_set(enc->ffve.context->priv_data, "multipass", multipass, 0); } if (astrcmpi(rc, "cqp") == 0) { @@ -157,8 +150,7 @@ static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, cqp = 0; av_opt_set(enc->ffve.context->priv_data, "tune", "lossless", 0); - av_opt_set(enc->ffve.context->priv_data, "multipass", - "disabled", 0); + av_opt_set(enc->ffve.context->priv_data, "multipass", "disabled", 0); } else if (astrcmpi(rc, "vbr") != 0) { /* CBR by default */ av_opt_set_int(enc->ffve.context->priv_data, "cbr", true, 0); @@ -171,8 +163,7 @@ static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, av_opt_set(enc->ffve.context->priv_data, "level", "auto", 0); av_opt_set_int(enc->ffve.context->priv_data, "gpu", gpu, 0); - av_opt_set_int(enc->ffve.context->priv_data, "no-scenecut", - disable_scenecut, 0); + av_opt_set_int(enc->ffve.context->priv_data, "no-scenecut", disable_scenecut, 0); // This is ugly but ffmpeg wipes priv_data on error and we need // to know this to show a proper error message. @@ -183,8 +174,7 @@ static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, enc->ffve.context->max_b_frames = bf; const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts"); - ffmpeg_video_encoder_update(&enc->ffve, bitrate, keyint_sec, voi, &info, - ffmpeg_opts); + ffmpeg_video_encoder_update(&enc->ffve, bitrate, keyint_sec, voi, &info, ffmpeg_opts); info("settings:\n" "\tencoder: %s\n" @@ -201,9 +191,8 @@ static bool nvenc_update(struct nvenc_encoder *enc, obs_data_t *settings, "\tb-frames: %d\n" "\tpsycho-aq: %d\n" "\tGPU: %d\n", - enc->ffve.enc_name, rc, bitrate, cqp, enc->ffve.context->gop_size, - preset2, tuning, multipass, profile, enc->ffve.context->width, - enc->ffve.height, enc->ffve.context->max_b_frames, psycho_aq, gpu); + enc->ffve.enc_name, rc, bitrate, cqp, enc->ffve.context->gop_size, preset2, tuning, multipass, profile, + enc->ffve.context->width, enc->ffve.height, enc->ffve.context->max_b_frames, psycho_aq, gpu); return ffmpeg_video_encoder_init_codec(&enc->ffve); } @@ -269,23 +258,18 @@ static void on_first_packet(void *data, AVPacket *pkt, struct darray *da) darray_free(da); #ifdef ENABLE_HEVC if (enc->hevc) { - obs_extract_hevc_headers(pkt->data, pkt->size, - (uint8_t **)&da->array, &da->num, - &enc->header.array, &enc->header.num, - &enc->sei.array, &enc->sei.num); + obs_extract_hevc_headers(pkt->data, pkt->size, (uint8_t **)&da->array, &da->num, &enc->header.array, + &enc->header.num, &enc->sei.array, &enc->sei.num); } else #endif { - obs_extract_avc_headers(pkt->data, pkt->size, - (uint8_t **)&da->array, &da->num, - &enc->header.array, &enc->header.num, - &enc->sei.array, &enc->sei.num); + obs_extract_avc_headers(pkt->data, pkt->size, (uint8_t **)&da->array, &da->num, &enc->header.array, + &enc->header.num, &enc->sei.array, &enc->sei.num); } da->capacity = da->num; if (enc->ffve.context->max_b_frames != 0) { - int64_t expected_dts = -(enc->ffve.context->max_b_frames * - enc->ffve.context->time_base.num); + int64_t expected_dts = -(enc->ffve.context->max_b_frames * enc->ffve.context->time_base.num); if (pkt->dts != expected_dts) { // Unpatched FFmpeg enc->dts_offset = expected_dts - pkt->dts; info("Applying DTS value corrections"); @@ -293,28 +277,23 @@ static void on_first_packet(void *data, AVPacket *pkt, struct darray *da) } } -static void *nvenc_create_internal(obs_data_t *settings, obs_encoder_t *encoder, - bool psycho_aq, bool hevc) +static void *nvenc_create_internal(obs_data_t *settings, obs_encoder_t *encoder, bool psycho_aq, bool hevc) { struct nvenc_encoder *enc = bzalloc(sizeof(*enc)); #ifdef ENABLE_HEVC enc->hevc = hevc; if (hevc) { - if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, - "hevc_nvenc", "nvenc_hevc", - ENCODER_NAME_HEVC, on_init_error, - on_first_packet)) + if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, "hevc_nvenc", "nvenc_hevc", ENCODER_NAME_HEVC, + on_init_error, on_first_packet)) goto fail; } else #else UNUSED_PARAMETER(hevc); #endif { - if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, - "h264_nvenc", "nvenc_h264", - ENCODER_NAME_H264, on_init_error, - on_first_packet)) + if (!ffmpeg_video_encoder_init(&enc->ffve, enc, encoder, "h264_nvenc", "nvenc_h264", ENCODER_NAME_H264, + on_init_error, on_first_packet)) goto fail; } @@ -335,25 +314,21 @@ static void *h264_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) switch (voi->format) { case VIDEO_FORMAT_I010: case VIDEO_FORMAT_P010: { - const char *const text = - obs_module_text("NVENC.10bitUnsupported"); + const char *const text = obs_module_text("NVENC.10bitUnsupported"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[NVENC encoder] %s", text); return NULL; } case VIDEO_FORMAT_P216: case VIDEO_FORMAT_P416: { - const char *const text = - obs_module_text("NVENC.16bitUnsupported"); + const char *const text = obs_module_text("NVENC.16bitUnsupported"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[NVENC encoder] %s", text); return NULL; } default: - if (voi->colorspace == VIDEO_CS_2100_PQ || - voi->colorspace == VIDEO_CS_2100_HLG) { - const char *const text = - obs_module_text("NVENC.8bitUnsupportedHdr"); + if (voi->colorspace == VIDEO_CS_2100_PQ || voi->colorspace == VIDEO_CS_2100_HLG) { + const char *const text = obs_module_text("NVENC.8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[NVENC encoder] %s", text); return NULL; @@ -364,9 +339,8 @@ static void *h264_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) bool psycho_aq = obs_data_get_bool(settings, "psycho_aq"); void *enc = nvenc_create_internal(settings, encoder, psycho_aq, false); if ((enc == NULL) && psycho_aq) { - blog(LOG_WARNING, - "[NVENC encoder] nvenc_create_internal failed, " - "trying again without Psycho Visual Tuning"); + blog(LOG_WARNING, "[NVENC encoder] nvenc_create_internal failed, " + "trying again without Psycho Visual Tuning"); enc = nvenc_create_internal(settings, encoder, false, false); } @@ -380,8 +354,7 @@ static void *hevc_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) const struct video_output_info *voi = video_output_get_info(video); switch (voi->format) { case VIDEO_FORMAT_I010: { - const char *const text = - obs_module_text("NVENC.I010Unsupported"); + const char *const text = obs_module_text("NVENC.I010Unsupported"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[NVENC encoder] %s", text); return NULL; @@ -390,17 +363,14 @@ static void *hevc_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) break; case VIDEO_FORMAT_P216: case VIDEO_FORMAT_P416: { - const char *const text = - obs_module_text("NVENC.16bitUnsupported"); + const char *const text = obs_module_text("NVENC.16bitUnsupported"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[NVENC encoder] %s", text); return NULL; } default: - if (voi->colorspace == VIDEO_CS_2100_PQ || - voi->colorspace == VIDEO_CS_2100_HLG) { - const char *const text = - obs_module_text("NVENC.8bitUnsupportedHdr"); + if (voi->colorspace == VIDEO_CS_2100_PQ || voi->colorspace == VIDEO_CS_2100_HLG) { + const char *const text = obs_module_text("NVENC.8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); blog(LOG_ERROR, "[NVENC encoder] %s", text); return NULL; @@ -411,9 +381,8 @@ static void *hevc_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) bool psycho_aq = obs_data_get_bool(settings, "psycho_aq"); void *enc = nvenc_create_internal(settings, encoder, psycho_aq, true); if ((enc == NULL) && psycho_aq) { - blog(LOG_WARNING, - "[NVENC encoder] nvenc_create_internal failed, " - "trying again without Psycho Visual Tuning"); + blog(LOG_WARNING, "[NVENC encoder] nvenc_create_internal failed, " + "trying again without Psycho Visual Tuning"); enc = nvenc_create_internal(settings, encoder, false, true); } @@ -421,8 +390,7 @@ static void *hevc_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) } #endif -static bool nvenc_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool nvenc_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct nvenc_encoder *enc = data; @@ -449,8 +417,7 @@ static void nvenc_defaults_base(enum codec_type codec, obs_data_t *settings) obs_data_set_default_string(settings, "preset2", "p5"); obs_data_set_default_string(settings, "multipass", "qres"); obs_data_set_default_string(settings, "tune", "hq"); - obs_data_set_default_string(settings, "profile", - codec != CODEC_H264 ? "main" : "high"); + obs_data_set_default_string(settings, "profile", codec != CODEC_H264 ? "main" : "high"); obs_data_set_default_bool(settings, "psycho_aq", true); obs_data_set_default_int(settings, "gpu", 0); obs_data_set_default_int(settings, "bf", 2); @@ -472,8 +439,7 @@ void av1_nvenc_defaults(obs_data_t *settings) nvenc_defaults_base(CODEC_AV1, settings); } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *rc = obs_data_get_string(settings, "rate_control"); bool cqp = astrcmpi(rc, "CQP") == 0; @@ -499,41 +465,29 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, "CBR", "CBR"); obs_property_list_add_string(p, "CQP", "CQP"); obs_property_list_add_string(p, "VBR", "VBR"); - obs_property_list_add_string(p, obs_module_text("Lossless"), - "lossless"); + obs_property_list_add_string(p, obs_module_text("Lossless"), "lossless"); obs_property_set_modified_callback(p, rate_control_modified); - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 50, 300000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); - p = obs_properties_add_int(props, "max_bitrate", - obs_module_text("MaxBitrate"), 50, 300000, - 50); + p = obs_properties_add_int(props, "max_bitrate", obs_module_text("MaxBitrate"), 50, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); - obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), - 1, codec == CODEC_AV1 ? 63 : 51, 1); + obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), 1, codec == CODEC_AV1 ? 63 : 51, 1); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 10, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1); obs_property_int_set_suffix(p, " s"); - p = obs_properties_add_list(props, "preset2", obs_module_text("Preset"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "preset2", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_preset(val) \ - obs_property_list_add_string(p, obs_module_text("NVENC.Preset2." val), \ - val) +#define add_preset(val) obs_property_list_add_string(p, obs_module_text("NVENC.Preset2." val), val) add_preset("p1"); add_preset("p2"); @@ -544,34 +498,25 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) add_preset("p7"); #undef add_preset - p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_tune(val) \ - obs_property_list_add_string(p, obs_module_text("NVENC.Tuning." val), \ - val) +#define add_tune(val) obs_property_list_add_string(p, obs_module_text("NVENC.Tuning." val), val) add_tune("hq"); add_tune("ll"); add_tune("ull"); #undef add_tune - p = obs_properties_add_list(props, "multipass", - obs_module_text("NVENC.Multipass"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "multipass", obs_module_text("NVENC.Multipass"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_multipass(val) \ - obs_property_list_add_string( \ - p, obs_module_text("NVENC.Multipass." val), val) +#define add_multipass(val) obs_property_list_add_string(p, obs_module_text("NVENC.Multipass." val), val) add_multipass("disabled"); add_multipass("qres"); add_multipass("fullres"); #undef add_multipass - p = obs_properties_add_list(props, "profile", - obs_module_text("Profile"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); #define add_profile(val) obs_property_list_add_string(p, val, val) @@ -587,16 +532,12 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) } #undef add_profile - p = obs_properties_add_bool( - props, "psycho_aq", - obs_module_text("NVENC.PsychoVisualTuning")); - obs_property_set_long_description( - p, obs_module_text("NVENC.PsychoVisualTuning.ToolTip")); + p = obs_properties_add_bool(props, "psycho_aq", obs_module_text("NVENC.PsychoVisualTuning")); + obs_property_set_long_description(p, obs_module_text("NVENC.PsychoVisualTuning.ToolTip")); obs_properties_add_int(props, "gpu", obs_module_text("GPU"), 0, 8, 1); - obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, - 1); + obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, 1); return props; } diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-output.c b/plugins/obs-ffmpeg/obs-ffmpeg-output.c index 5b42566bb..28a0dda03 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-output.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-output.c @@ -30,8 +30,7 @@ /* ------------------------------------------------------------------------- */ -static void ffmpeg_output_set_last_error(struct ffmpeg_data *data, - const char *error) +static void ffmpeg_output_set_last_error(struct ffmpeg_data *data, const char *error) { if (data->last_error) bfree(data->last_error); @@ -39,8 +38,7 @@ static void ffmpeg_output_set_last_error(struct ffmpeg_data *data, data->last_error = bstrdup(error); } -void ffmpeg_log_error(int log_level, struct ffmpeg_data *data, - const char *format, ...) +void ffmpeg_log_error(int log_level, struct ffmpeg_data *data, const char *format, ...) { va_list args; char out[4096]; @@ -54,25 +52,19 @@ void ffmpeg_log_error(int log_level, struct ffmpeg_data *data, blog(log_level, "%s", out); } -static bool new_stream(struct ffmpeg_data *data, AVStream **stream, - const AVCodec **codec, enum AVCodecID id, +static bool new_stream(struct ffmpeg_data *data, AVStream **stream, const AVCodec **codec, enum AVCodecID id, const char *name) { - *codec = (!!name && *name) ? avcodec_find_encoder_by_name(name) - : avcodec_find_encoder(id); + *codec = (!!name && *name) ? avcodec_find_encoder_by_name(name) : avcodec_find_encoder(id); if (!*codec) { - ffmpeg_log_error(LOG_WARNING, data, - "Couldn't find encoder '%s'", - avcodec_get_name(id)); + ffmpeg_log_error(LOG_WARNING, data, "Couldn't find encoder '%s'", avcodec_get_name(id)); return false; } *stream = avformat_new_stream(data->output, *codec); if (!*stream) { - ffmpeg_log_error(LOG_WARNING, data, - "Couldn't create stream for encoder '%s'", - avcodec_get_name(id)); + ffmpeg_log_error(LOG_WARNING, data, "Couldn't create stream for encoder '%s'", avcodec_get_name(id)); return false; } @@ -98,10 +90,8 @@ static bool parse_params(AVCodecContext *context, char **opts) *assign = 0; value = assign + 1; - if (av_opt_set(context, name, value, - AV_OPT_SEARCH_CHILDREN)) { - blog(LOG_WARNING, "Failed to set %s=%s", name, - value); + if (av_opt_set(context, name, value, AV_OPT_SEARCH_CHILDREN)) { + blog(LOG_WARNING, "Failed to set %s=%s", name, value); ret = false; } } @@ -123,8 +113,7 @@ static bool open_video_codec(struct ffmpeg_data *data) if (opts) { // libav requires x264 parameters in a special format which may be non-obvious - if (!parse_params(context, opts) && - strcmp(data->vcodec->name, "libx264") == 0) + if (!parse_params(context, opts) && strcmp(data->vcodec->name, "libx264") == 0) blog(LOG_WARNING, "If you're trying to set x264 parameters, use x264-params=name=value:name=value"); strlist_free(opts); @@ -132,16 +121,13 @@ static bool open_video_codec(struct ffmpeg_data *data) ret = avcodec_open2(context, data->vcodec, NULL); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to open video codec: %s", - av_err2str(ret)); + ffmpeg_log_error(LOG_WARNING, data, "Failed to open video codec: %s", av_err2str(ret)); return false; } data->vframe = av_frame_alloc(); if (!data->vframe) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to allocate video frame"); + ffmpeg_log_error(LOG_WARNING, data, "Failed to allocate video frame"); return false; } @@ -152,14 +138,11 @@ static bool open_video_codec(struct ffmpeg_data *data) data->vframe->color_primaries = data->config.color_primaries; data->vframe->color_trc = data->config.color_trc; data->vframe->colorspace = data->config.colorspace; - data->vframe->chroma_location = determine_chroma_location( - context->pix_fmt, data->config.colorspace); + data->vframe->chroma_location = determine_chroma_location(context->pix_fmt, data->config.colorspace); ret = av_frame_get_buffer(data->vframe, base_get_alignment()); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to allocate vframe: %s", - av_err2str(ret)); + ffmpeg_log_error(LOG_WARNING, data, "Failed to allocate vframe: %s", av_err2str(ret)); return false; } @@ -170,14 +153,12 @@ static bool open_video_codec(struct ffmpeg_data *data) static bool init_swscale(struct ffmpeg_data *data, AVCodecContext *context) { - data->swscale = sws_getContext( - data->config.width, data->config.height, data->config.format, - data->config.scale_width, data->config.scale_height, - context->pix_fmt, SWS_BICUBIC, NULL, NULL, NULL); + data->swscale = sws_getContext(data->config.width, data->config.height, data->config.format, + data->config.scale_width, data->config.scale_height, context->pix_fmt, + SWS_BICUBIC, NULL, NULL, NULL); if (!data->swscale) { - ffmpeg_log_error(LOG_WARNING, data, - "Could not initialize swscale"); + ffmpeg_log_error(LOG_WARNING, data, "Could not initialize swscale"); return false; } @@ -195,17 +176,15 @@ static bool create_video_stream(struct ffmpeg_data *data) return false; } - if (!new_stream(data, &data->video, &data->vcodec, - data->output->oformat->video_codec, + if (!new_stream(data, &data->video, &data->vcodec, data->output->oformat->video_codec, data->config.video_encoder)) return false; closest_format = data->config.format; if (data->vcodec->pix_fmts) { const int has_alpha = closest_format == AV_PIX_FMT_BGRA; - closest_format = avcodec_find_best_pix_fmt_of_list( - data->vcodec->pix_fmts, closest_format, has_alpha, - NULL); + closest_format = + avcodec_find_best_pix_fmt_of_list(data->vcodec->pix_fmts, closest_format, has_alpha, NULL); } context = avcodec_alloc_context3(data->vcodec); @@ -220,8 +199,7 @@ static bool create_video_stream(struct ffmpeg_data *data) context->color_primaries = data->config.color_primaries; context->color_trc = data->config.color_trc; context->colorspace = data->config.colorspace; - context->chroma_sample_location = determine_chroma_location( - closest_format, data->config.colorspace); + context->chroma_sample_location = determine_chroma_location(closest_format, data->config.colorspace); context->thread_count = 0; data->video->time_base = context->time_base; @@ -239,23 +217,17 @@ static bool create_video_stream(struct ffmpeg_data *data) const bool pq = trc == AVCOL_TRC_SMPTE2084; const bool hlg = trc == AVCOL_TRC_ARIB_STD_B67; if (pq || hlg) { - const int hdr_nominal_peak_level = - pq ? (int)obs_get_video_hdr_nominal_peak_level() - : (hlg ? 1000 : 0); + const int hdr_nominal_peak_level = pq ? (int)obs_get_video_hdr_nominal_peak_level() : (hlg ? 1000 : 0); size_t content_size; - AVContentLightMetadata *const content = - av_content_light_metadata_alloc(&content_size); + AVContentLightMetadata *const content = av_content_light_metadata_alloc(&content_size); content->MaxCLL = hdr_nominal_peak_level; content->MaxFALL = hdr_nominal_peak_level; - av_packet_side_data_add( - &data->video->codecpar->coded_side_data, - &data->video->codecpar->nb_coded_side_data, - AV_PKT_DATA_CONTENT_LIGHT_LEVEL, (uint8_t *)content, - content_size, 0); + av_packet_side_data_add(&data->video->codecpar->coded_side_data, + &data->video->codecpar->nb_coded_side_data, AV_PKT_DATA_CONTENT_LIGHT_LEVEL, + (uint8_t *)content, content_size, 0); - AVMasteringDisplayMetadata *const mastering = - av_mastering_display_metadata_alloc(); + AVMasteringDisplayMetadata *const mastering = av_mastering_display_metadata_alloc(); mastering->display_primaries[0][0] = av_make_q(17, 25); mastering->display_primaries[0][1] = av_make_q(8, 25); mastering->display_primaries[1][0] = av_make_q(53, 200); @@ -268,15 +240,13 @@ static bool create_video_stream(struct ffmpeg_data *data) mastering->max_luminance = av_make_q(hdr_nominal_peak_level, 1); mastering->has_primaries = 1; mastering->has_luminance = 1; - av_packet_side_data_add( - &data->video->codecpar->coded_side_data, - &data->video->codecpar->nb_coded_side_data, - AV_PKT_DATA_MASTERING_DISPLAY_METADATA, - (uint8_t *)mastering, sizeof(*mastering), 0); + av_packet_side_data_add(&data->video->codecpar->coded_side_data, + &data->video->codecpar->nb_coded_side_data, + AV_PKT_DATA_MASTERING_DISPLAY_METADATA, (uint8_t *)mastering, + sizeof(*mastering), 0); } - if (context->pix_fmt != data->config.format || - data->config.width != data->config.scale_width || + if (context->pix_fmt != data->config.format || data->config.width != data->config.scale_width || data->config.height != data->config.scale_height) { if (!init_swscale(data, context)) @@ -300,8 +270,7 @@ static bool open_audio_codec(struct ffmpeg_data *data, int idx) data->aframe[idx] = av_frame_alloc(); if (!data->aframe[idx]) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to allocate audio frame"); + ffmpeg_log_error(LOG_WARNING, data, "Failed to allocate audio frame"); return false; } @@ -313,25 +282,19 @@ static bool open_audio_codec(struct ffmpeg_data *data, int idx) ret = avcodec_open2(context, data->acodec, NULL); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to open audio codec: %s", - av_err2str(ret)); + ffmpeg_log_error(LOG_WARNING, data, "Failed to open audio codec: %s", av_err2str(ret)); return false; } data->frame_size = context->frame_size ? context->frame_size : 1024; - ret = av_samples_alloc(data->samples[idx], NULL, channels, - data->frame_size, context->sample_fmt, 0); + ret = av_samples_alloc(data->samples[idx], NULL, channels, data->frame_size, context->sample_fmt, 0); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to create audio buffer: %s", - av_err2str(ret)); + ffmpeg_log_error(LOG_WARNING, data, "Failed to create audio buffer: %s", av_err2str(ret)); return false; } - avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar, - context); + avcodec_parameters_from_context(data->audio_infos[idx].stream->codecpar, context); return true; } @@ -348,9 +311,7 @@ static bool create_audio_stream(struct ffmpeg_data *data, int idx) return false; } - if (!new_stream(data, &stream, &data->acodec, - data->output->oformat->audio_codec, - data->config.audio_encoder)) + if (!new_stream(data, &stream, &data->acodec, data->output->oformat->audio_codec, data->config.audio_encoder)) return false; context = avcodec_alloc_context3(data->acodec); @@ -363,9 +324,7 @@ static bool create_audio_stream(struct ffmpeg_data *data, int idx) if (aoi.speakers == SPEAKERS_4POINT1) context->ch_layout = (AVChannelLayout)AV_CHANNEL_LAYOUT_4POINT1; - context->sample_fmt = data->acodec->sample_fmts - ? data->acodec->sample_fmts[0] - : AV_SAMPLE_FMT_FLTP; + context->sample_fmt = data->acodec->sample_fmts ? data->acodec->sample_fmts[0] : AV_SAMPLE_FMT_FLTP; stream->time_base = context->time_base; @@ -380,10 +339,8 @@ static bool create_audio_stream(struct ffmpeg_data *data, int idx) data->audio_infos[idx].stream = stream; data->audio_infos[idx].ctx = context; - if (data->config.audio_stream_names[idx] && - *data->config.audio_stream_names[idx] != '\0') - av_dict_set(&stream->metadata, "title", - data->config.audio_stream_names[idx], 0); + if (data->config.audio_stream_names[idx] && *data->config.audio_stream_names[idx] != '\0') + av_dict_set(&stream->metadata, "title", data->config.audio_stream_names[idx], 0); return open_audio_codec(data, idx); } @@ -396,10 +353,8 @@ static inline bool init_streams(struct ffmpeg_data *data) if (!create_video_stream(data)) return false; - if (format->audio_codec != AV_CODEC_ID_NONE && - data->num_audio_streams) { - data->audio_infos = calloc(data->num_audio_streams, - sizeof(*data->audio_infos)); + if (format->audio_codec != AV_CODEC_ID_NONE && data->num_audio_streams) { + data->audio_infos = calloc(data->num_audio_streams, sizeof(*data->audio_infos)); for (int i = 0; i < data->num_audio_streams; i++) { if (!create_audio_stream(data, i)) return false; @@ -415,11 +370,9 @@ static inline bool open_output_file(struct ffmpeg_data *data) int ret; AVDictionary *dict = NULL; - if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=", - " ", 0))) { - ffmpeg_log_error(LOG_WARNING, data, - "Failed to parse muxer settings: %s\n%s", - av_err2str(ret), data->config.muxer_settings); + if ((ret = av_dict_parse_string(&dict, data->config.muxer_settings, "=", " ", 0))) { + ffmpeg_log_error(LOG_WARNING, data, "Failed to parse muxer settings: %s\n%s", av_err2str(ret), + data->config.muxer_settings); av_dict_free(&dict); return false; @@ -429,8 +382,7 @@ static inline bool open_output_file(struct ffmpeg_data *data) struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); blog(LOG_INFO, "Using muxer settings: %s", str.array); @@ -438,12 +390,10 @@ static inline bool open_output_file(struct ffmpeg_data *data) } if ((format->flags & AVFMT_NOFILE) == 0) { - ret = avio_open2(&data->output->pb, data->config.url, - AVIO_FLAG_WRITE, NULL, &dict); + ret = avio_open2(&data->output->pb, data->config.url, AVIO_FLAG_WRITE, NULL, &dict); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, data, - "Couldn't open '%s', %s", - data->config.url, av_err2str(ret)); + ffmpeg_log_error(LOG_WARNING, data, "Couldn't open '%s', %s", data->config.url, + av_err2str(ret)); av_dict_free(&dict); return false; } @@ -451,8 +401,7 @@ static inline bool open_output_file(struct ffmpeg_data *data) ret = avformat_write_header(data->output, &dict); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, data, "Error opening '%s': %s", - data->config.url, av_err2str(ret)); + ffmpeg_log_error(LOG_WARNING, data, "Error opening '%s': %s", data->config.url, av_err2str(ret)); return false; } @@ -460,8 +409,7 @@ static inline bool open_output_file(struct ffmpeg_data *data) struct dstr str = {0}; AVDictionaryEntry *entry = NULL; - while ((entry = av_dict_get(dict, "", entry, - AV_DICT_IGNORE_SUFFIX))) + while ((entry = av_dict_get(dict, "", entry, AV_DICT_IGNORE_SUFFIX))) dstr_catf(&str, "\n\t%s=%s", entry->key, entry->value); blog(LOG_INFO, "Invalid muxer settings: %s", str.array); @@ -480,8 +428,7 @@ static void close_video(struct ffmpeg_data *data) // This format for some reason derefs video frame // too many times - if (data->vcodec->id == AV_CODEC_ID_A64_MULTI || - data->vcodec->id == AV_CODEC_ID_A64_MULTI5) + if (data->vcodec->id == AV_CODEC_ID_A64_MULTI || data->vcodec->id == AV_CODEC_ID_A64_MULTI5) return; av_frame_free(&data->vframe); @@ -551,29 +498,24 @@ bool ffmpeg_data_init(struct ffmpeg_data *data, struct ffmpeg_cfg *config) is_rtmp = (astrcmpi_n(config->url, "rtmp://", 7) == 0); - const AVOutputFormat *output_format = av_guess_format( - is_rtmp ? "flv" : data->config.format_name, data->config.url, - is_rtmp ? NULL : data->config.format_mime_type); + const AVOutputFormat *output_format = av_guess_format(is_rtmp ? "flv" : data->config.format_name, + data->config.url, + is_rtmp ? NULL : data->config.format_mime_type); if (output_format == NULL) { - ffmpeg_log_error( - LOG_WARNING, data, - "Couldn't find matching output format with " - "parameters: name=%s, url=%s, mime=%s", - safe_str(is_rtmp ? "flv" : data->config.format_name), - safe_str(data->config.url), - safe_str(is_rtmp ? NULL - : data->config.format_mime_type)); + ffmpeg_log_error(LOG_WARNING, data, + "Couldn't find matching output format with " + "parameters: name=%s, url=%s, mime=%s", + safe_str(is_rtmp ? "flv" : data->config.format_name), safe_str(data->config.url), + safe_str(is_rtmp ? NULL : data->config.format_mime_type)); goto fail; } - avformat_alloc_output_context2(&data->output, output_format, NULL, - data->config.url); + avformat_alloc_output_context2(&data->output, output_format, NULL, data->config.url); if (!data->output) { - ffmpeg_log_error(LOG_WARNING, data, - "Couldn't create avformat context"); + ffmpeg_log_error(LOG_WARNING, data, "Couldn't create avformat context"); goto fail; } @@ -610,8 +552,7 @@ static const char *ffmpeg_output_getname(void *unused) return obs_module_text("FFmpegOutput"); } -static void ffmpeg_log_callback(void *param, int level, const char *format, - va_list args) +static void ffmpeg_log_callback(void *param, int level, const char *format, va_list args) { if (level <= AV_LOG_INFO) blogva(LOG_DEBUG, format, args); @@ -664,28 +605,24 @@ static void ffmpeg_output_destroy(void *data) } } -static inline void copy_data(AVFrame *pic, const struct video_data *frame, - int height, enum AVPixelFormat format) +static inline void copy_data(AVFrame *pic, const struct video_data *frame, int height, enum AVPixelFormat format) { int h_chroma_shift, v_chroma_shift; - av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, - &v_chroma_shift); + av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, &v_chroma_shift); for (int plane = 0; plane < MAX_AV_PLANES; plane++) { if (!frame->data[plane]) continue; int frame_rowsize = (int)frame->linesize[plane]; int pic_rowsize = pic->linesize[plane]; - int bytes = frame_rowsize < pic_rowsize ? frame_rowsize - : pic_rowsize; + int bytes = frame_rowsize < pic_rowsize ? frame_rowsize : pic_rowsize; int plane_height = height >> (plane ? v_chroma_shift : 0); for (int y = 0; y < plane_height; y++) { int pos_frame = y * frame_rowsize; int pos_pic = y * pic_rowsize; - memcpy(pic->data[plane] + pos_pic, - frame->data[plane] + pos_frame, bytes); + memcpy(pic->data[plane] + pos_pic, frame->data[plane] + pos_frame, bytes); } } } @@ -718,12 +655,10 @@ static void receive_video(void *param, struct video_data *frame) return; } if (!!data->swscale) - sws_scale(data->swscale, (const uint8_t *const *)frame->data, - (const int *)frame->linesize, 0, data->config.height, - data->vframe->data, data->vframe->linesize); + sws_scale(data->swscale, (const uint8_t *const *)frame->data, (const int *)frame->linesize, 0, + data->config.height, data->vframe->data, data->vframe->linesize); else - copy_data(data->vframe, frame, context->height, - context->pix_fmt); + copy_data(data->vframe, frame, context->height, context->pix_fmt); packet = av_packet_alloc(); @@ -747,13 +682,9 @@ static void receive_video(void *param, struct video_data *frame) } if (!ret && got_packet && packet->size) { - packet->pts = rescale_ts(packet->pts, context, - data->video->time_base); - packet->dts = rescale_ts(packet->dts, context, - data->video->time_base); - packet->duration = (int)av_rescale_q(packet->duration, - context->time_base, - data->video->time_base); + packet->pts = rescale_ts(packet->pts, context, data->video->time_base); + packet->dts = rescale_ts(packet->dts, context, data->video->time_base); + packet->duration = (int)av_rescale_q(packet->duration, context->time_base, data->video->time_base); pthread_mutex_lock(&output->write_mutex); da_push_back(output->packets, &packet); @@ -765,8 +696,7 @@ static void receive_video(void *param, struct video_data *frame) } if (ret != 0) { - blog(LOG_WARNING, "receive_video: Error writing video: %s", - av_err2str(ret)); + blog(LOG_WARNING, "receive_video: Error writing video: %s", av_err2str(ret)); //FIXME: stop the encode with an error } @@ -776,8 +706,7 @@ fail: av_packet_free(&packet); } -static void encode_audio(struct ffmpeg_output *output, int idx, - struct AVCodecContext *context, size_t block_size) +static void encode_audio(struct ffmpeg_output *output, int idx, struct AVCodecContext *context, size_t block_size) { struct ffmpeg_data *data = &output->ff_data; @@ -787,14 +716,11 @@ static void encode_audio(struct ffmpeg_output *output, int idx, size_t total_size = data->frame_size * block_size * channels; data->aframe[idx]->nb_samples = data->frame_size; - data->aframe[idx]->pts = av_rescale_q( - data->total_samples[idx], (AVRational){1, context->sample_rate}, - context->time_base); + data->aframe[idx]->pts = + av_rescale_q(data->total_samples[idx], (AVRational){1, context->sample_rate}, context->time_base); - ret = avcodec_fill_audio_frame(data->aframe[idx], channels, - context->sample_fmt, - data->samples[idx][0], (int)total_size, - 1); + ret = avcodec_fill_audio_frame(data->aframe[idx], channels, context->sample_fmt, data->samples[idx][0], + (int)total_size, 1); if (ret < 0) { blog(LOG_WARNING, "encode_audio: avcodec_fill_audio_frame " @@ -818,8 +744,7 @@ static void encode_audio(struct ffmpeg_output *output, int idx, ret = 0; if (ret < 0) { - blog(LOG_WARNING, "encode_audio: Error encoding audio: %s", - av_err2str(ret)); + blog(LOG_WARNING, "encode_audio: Error encoding audio: %s", av_err2str(ret)); //FIXME: stop the encode with an error goto fail; } @@ -827,13 +752,10 @@ static void encode_audio(struct ffmpeg_output *output, int idx, if (!got_packet) goto fail; - packet->pts = rescale_ts(packet->pts, context, - data->audio_infos[idx].stream->time_base); - packet->dts = rescale_ts(packet->dts, context, - data->audio_infos[idx].stream->time_base); + packet->pts = rescale_ts(packet->pts, context, data->audio_infos[idx].stream->time_base); + packet->dts = rescale_ts(packet->dts, context, data->audio_infos[idx].stream->time_base); packet->duration = - (int)av_rescale_q(packet->duration, context->time_base, - data->audio_infos[idx].stream->time_base); + (int)av_rescale_q(packet->duration, context->time_base, data->audio_infos[idx].stream->time_base); packet->stream_index = data->audio_infos[idx].stream->index; pthread_mutex_lock(&output->write_mutex); @@ -888,21 +810,18 @@ static void receive_audio(void *param, size_t mix_idx, struct audio_data *frame) frame_size_bytes = (size_t)data->frame_size * data->audio_size; for (size_t i = 0; i < data->audio_planes; i++) - deque_push_back(&data->excess_frames[track_order][i], - in.data[i], in.frames * data->audio_size); + deque_push_back(&data->excess_frames[track_order][i], in.data[i], in.frames * data->audio_size); while (data->excess_frames[track_order][0].size >= frame_size_bytes) { for (size_t i = 0; i < data->audio_planes; i++) - deque_pop_front(&data->excess_frames[track_order][i], - data->samples[track_order][i], + deque_pop_front(&data->excess_frames[track_order][i], data->samples[track_order][i], frame_size_bytes); encode_audio(output, track_order, context, data->audio_size); } } -static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, - AVPacket *packet) +static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, AVPacket *packet) { struct ffmpeg_data *data = &output->ff_data; uint64_t pause_offset = obs_output_get_pause_offset(output->output); @@ -918,9 +837,7 @@ static uint64_t get_packet_sys_dts(struct ffmpeg_output *output, start_ts = output->audio_start_ts; } - return start_ts + pause_offset + - (uint64_t)av_rescale_q(packet->dts, time_base, - (AVRational){1, 1000000000}); + return start_ts + pause_offset + (uint64_t)av_rescale_q(packet->dts, time_base, (AVRational){1, 1000000000}); } static int process_packet(struct ffmpeg_output *output) @@ -955,8 +872,7 @@ static int process_packet(struct ffmpeg_output *output) ret = av_interleaved_write_frame(output->ff_data.output, packet); if (ret < 0) { - ffmpeg_log_error(LOG_WARNING, &output->ff_data, - "process_packet: Error writing packet: %s", + ffmpeg_log_error(LOG_WARNING, &output->ff_data, "process_packet: Error writing packet: %s", av_err2str(ret)); } @@ -994,8 +910,7 @@ static void *write_thread(void *data) return NULL; } -static inline const char *get_string_or_null(obs_data_t *settings, - const char *name) +static inline const char *get_string_or_null(obs_data_t *settings, const char *name) { const char *value = obs_data_get_string(settings, name); if (!value || !strlen(value)) @@ -1030,33 +945,27 @@ static bool try_connect(struct ffmpeg_output *output) config.url = obs_data_get_string(settings, "url"); config.format_name = get_string_or_null(settings, "format_name"); - config.format_mime_type = - get_string_or_null(settings, "format_mime_type"); + config.format_mime_type = get_string_or_null(settings, "format_mime_type"); config.muxer_settings = obs_data_get_string(settings, "muxer_settings"); config.video_bitrate = (int)obs_data_get_int(settings, "video_bitrate"); config.audio_bitrate = (int)obs_data_get_int(settings, "audio_bitrate"); config.gop_size = (int)obs_data_get_int(settings, "gop_size"); config.video_encoder = get_string_or_null(settings, "video_encoder"); - config.video_encoder_id = - (int)obs_data_get_int(settings, "video_encoder_id"); + config.video_encoder_id = (int)obs_data_get_int(settings, "video_encoder_id"); config.audio_encoder = get_string_or_null(settings, "audio_encoder"); - config.audio_encoder_id = - (int)obs_data_get_int(settings, "audio_encoder_id"); + config.audio_encoder_id = (int)obs_data_get_int(settings, "audio_encoder_id"); config.video_settings = obs_data_get_string(settings, "video_settings"); config.audio_settings = obs_data_get_string(settings, "audio_settings"); config.scale_width = (int)obs_data_get_int(settings, "scale_width"); config.scale_height = (int)obs_data_get_int(settings, "scale_height"); config.width = (int)obs_output_get_width(output->output); config.height = (int)obs_output_get_height(output->output); - config.format = - obs_to_ffmpeg_video_format(video_output_get_format(video)); + config.format = obs_to_ffmpeg_video_format(video_output_get_format(video)); config.audio_tracks = (int)obs_output_get_mixers(output->output); config.audio_mix_count = get_audio_mix_count(config.audio_tracks); - config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG - : AVCOL_RANGE_MPEG; - config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709 - : AVCOL_SPC_RGB; + config.color_range = voi->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; + config.colorspace = format_is_yuv(voi->format) ? AVCOL_SPC_BT709 : AVCOL_SPC_RGB; switch (voi->colorspace) { case VIDEO_CS_601: config.color_primaries = AVCOL_PRI_SMPTE170M; @@ -1096,17 +1005,14 @@ static bool try_connect(struct ffmpeg_output *output) if (!config.scale_height) config.scale_height = config.height; - obs_data_array_t *audioNames = - obs_data_get_array(settings, "audio_names"); + obs_data_array_t *audioNames = obs_data_get_array(settings, "audio_names"); if (audioNames) { for (size_t i = 0, idx = 0; i < MAX_AUDIO_MIXES; i++) { if ((config.audio_tracks & (1 << i)) == 0) continue; - obs_data_t *item_data = - obs_data_array_item(audioNames, i); - config.audio_stream_names[idx] = - obs_data_get_string(item_data, "name"); + obs_data_t *item_data = obs_data_array_item(audioNames, i); + config.audio_stream_names[idx] = obs_data_get_string(item_data, "name"); obs_data_release(item_data); idx++; @@ -1122,15 +1028,13 @@ static bool try_connect(struct ffmpeg_output *output) if (!success) { if (output->ff_data.last_error) { - obs_output_set_last_error(output->output, - output->ff_data.last_error); + obs_output_set_last_error(output->output, output->ff_data.last_error); } ffmpeg_data_free(&output->ff_data); return false; } - struct audio_convert_info aci = {.format = - output->ff_data.audio_format}; + struct audio_convert_info aci = {.format = output->ff_data.audio_format}; output->active = true; @@ -1158,8 +1062,7 @@ static void *start_thread(void *data) struct ffmpeg_output *output = data; if (!try_connect(output)) - obs_output_signal_stop(output->output, - OBS_OUTPUT_CONNECT_FAILED); + obs_output_signal_stop(output->output, OBS_OUTPUT_CONNECT_FAILED); output->connecting = false; return NULL; @@ -1234,8 +1137,7 @@ static uint64_t ffmpeg_output_total_bytes(void *data) struct obs_output_info ffmpeg_output = { .id = "ffmpeg_output", - .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK | - OBS_OUTPUT_CAN_PAUSE, + .flags = OBS_OUTPUT_AUDIO | OBS_OUTPUT_VIDEO | OBS_OUTPUT_MULTI_TRACK | OBS_OUTPUT_CAN_PAUSE, .get_name = ffmpeg_output_getname, .create = ffmpeg_output_create, .destroy = ffmpeg_output_destroy, diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-rist.h b/plugins/obs-ffmpeg/obs-ffmpeg-rist.h index 18326d649..e32524d20 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-rist.h +++ b/plugins/obs-ffmpeg/obs-ffmpeg-rist.h @@ -24,12 +24,9 @@ // RIST_MAX_PACKET_SIZE - 28 minimum protocol overhead #define RIST_MAX_PAYLOAD_SIZE (10000 - 28) -#define FF_LIBRIST_MAKE_VERSION(major, minor, patch) \ - ((patch) + ((minor) * 0x100) + ((major) * 0x10000)) -#define FF_LIBRIST_VERSION \ - FF_LIBRIST_MAKE_VERSION(LIBRIST_API_VERSION_MAJOR, \ - LIBRIST_API_VERSION_MINOR, \ - LIBRIST_API_VERSION_PATCH) +#define FF_LIBRIST_MAKE_VERSION(major, minor, patch) ((patch) + ((minor) * 0x100) + ((major) * 0x10000)) +#define FF_LIBRIST_VERSION \ + FF_LIBRIST_MAKE_VERSION(LIBRIST_API_VERSION_MAJOR, LIBRIST_API_VERSION_MINOR, LIBRIST_API_VERSION_PATCH) #define FF_LIBRIST_VERSION_41 FF_LIBRIST_MAKE_VERSION(4, 1, 0) #define FF_LIBRIST_VERSION_42 FF_LIBRIST_MAKE_VERSION(4, 2, 0) @@ -112,9 +109,7 @@ static int librist_close(URLContext *h) if (s->ctx) ret = rist_destroy(s->ctx); if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Failed to close properly %s", - h->url); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to close properly %s", h->url); return -1; } s->ctx = NULL; @@ -125,8 +120,7 @@ static int librist_close(URLContext *h) static int cb_stats(void *arg, const struct rist_stats *stats_container) { RISTContext *s = (RISTContext *)arg; - rist_log(&s->logging_settings, RIST_LOG_INFO, "%s\n", - stats_container->stats_json); + rist_log(&s->logging_settings, RIST_LOG_INFO, "%s\n", stats_container->stats_json); if (stats_container->stats_type == RIST_STATS_SENDER_PEER) { blog(LOG_INFO, "---------------------------------"); blog(LOG_DEBUG, @@ -137,12 +131,9 @@ static int cb_stats(void *arg, const struct rist_stats *stats_container) "\tpkts retransmitted [%" PRIu64 "]\n" "\tquality (pkt sent over sent+retransmitted+skipped) [%.2f]\n" "\trtt [%" PRIu32 " ms]\n", - (double)(stats_container->stats.sender_peer.bandwidth) / - 1000000.0, - stats_container->stats.sender_peer.sent, - stats_container->stats.sender_peer.received, - stats_container->stats.sender_peer.retransmitted, - stats_container->stats.sender_peer.quality, + (double)(stats_container->stats.sender_peer.bandwidth) / 1000000.0, + stats_container->stats.sender_peer.sent, stats_container->stats.sender_peer.received, + stats_container->stats.sender_peer.retransmitted, stats_container->stats.sender_peer.quality, stats_container->stats.sender_peer.rtt); } rist_stats_free(stats_container); @@ -162,64 +153,52 @@ static int librist_open(URLContext *h, const char *uri) s->encryption = 0; s->overrun_nonfatal = 0; s->fifo_shift = FF_LIBRIST_FIFO_DEFAULT_SHIFT; - s->logging_settings = - (struct rist_logging_settings)LOGGING_SETTINGS_INITIALIZER; + s->logging_settings = (struct rist_logging_settings)LOGGING_SETTINGS_INITIALIZER; s->statsinterval = 60000; // log stats every 60 seconds - ret = rist_logging_set(&logging_settings, s->log_level, log_cb, h, NULL, - NULL); + ret = rist_logging_set(&logging_settings, s->log_level, log_cb, h, NULL, NULL); if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Failed to initialize logging settings"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to initialize logging settings"); return OBS_OUTPUT_CONNECT_FAILED; } - blog(LOG_INFO, - "[obs-ffmpeg mpegts muxer / librist]: libRIST version: %s, API: %s", - librist_version(), librist_api_version()); + blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / librist]: libRIST version: %s, API: %s", librist_version(), + librist_api_version()); h->max_packet_size = s->packet_size; ret = rist_sender_create(&s->ctx, s->profile, 0, logging_settings); if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Failed to create a sender"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to create a sender"); goto err; } ret = rist_peer_config_defaults_set(peer_config); if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Failed to set peer config defaults"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to set peer config defaults"); goto err; } #if FF_LIBRIST_VERSION < FF_LIBRIST_VERSION_41 - ret = rist_parse_address( - uri, (const struct rist_peer_config **)&peer_config); + ret = rist_parse_address(uri, (const struct rist_peer_config **)&peer_config); #else ret = rist_parse_address2(uri, &peer_config); #endif if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Failed to parse url: %s", - uri); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to parse url: %s", uri); librist_close(h); return OBS_OUTPUT_INVALID_STREAM; } if (((s->encryption == 128 || s->encryption == 256) && !s->secret) || - ((peer_config->key_size == 128 || peer_config->key_size == 256) && - !peer_config->secret[0])) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Secret is mandatory if encryption is enabled"); + ((peer_config->key_size == 128 || peer_config->key_size == 256) && !peer_config->secret[0])) { + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Secret is mandatory if encryption is enabled"); librist_close(h); return OBS_OUTPUT_INVALID_STREAM; } if (s->secret && peer_config->secret[0] == 0) - av_strlcpy(peer_config->secret, s->secret, - RIST_MAX_STRING_SHORT); + av_strlcpy(peer_config->secret, s->secret, RIST_MAX_STRING_SHORT); if (s->secret && (s->encryption == 128 || s->encryption == 256)) peer_config->key_size = s->encryption; @@ -229,29 +208,23 @@ static int librist_open(URLContext *h, const char *uri) peer_config->recovery_length_max = s->buffer_size; } if (s->username && peer_config->srp_username[0] == 0) - av_strlcpy(peer_config->srp_username, s->username, - RIST_MAX_STRING_LONG); + av_strlcpy(peer_config->srp_username, s->username, RIST_MAX_STRING_LONG); if (s->password && peer_config->srp_password[0] == 0) - av_strlcpy(peer_config->srp_password, s->password, - RIST_MAX_STRING_LONG); + av_strlcpy(peer_config->srp_password, s->password, RIST_MAX_STRING_LONG); ret = rist_peer_create(s->ctx, &s->peer, &s->peer_config); if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: Failed to create a peer."); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: Failed to create a peer."); goto err; } ret = rist_start(s->ctx); if (ret < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / librist]: RIST failed to start"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / librist]: RIST failed to start"); goto err; } - if (rist_stats_callback_set(s->ctx, s->statsinterval, cb_stats, - (void *)s) == -1) - rist_log(&s->logging_settings, RIST_LOG_ERROR, - "Could not enable stats callback"); + if (rist_stats_callback_set(s->ctx, s->statsinterval, cb_stats, (void *)s) == -1) + rist_log(&s->logging_settings, RIST_LOG_ERROR, "Could not enable stats callback"); return 0; err: @@ -272,9 +245,7 @@ static int librist_write(URLContext *h, const uint8_t *buf, int size) ret = rist_sender_data_write(s->ctx, &data_block); if (ret < 0) { - blog(LOG_WARNING, - "[obs-ffmpeg mpegts muxer / librist]: Failed to send %i bytes", - size); + blog(LOG_WARNING, "[obs-ffmpeg mpegts muxer / librist]: Failed to send %i bytes", size); return risterr2ret(ret); } diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-source.c b/plugins/obs-ffmpeg/obs-ffmpeg-source.c index eef1cddd9..26241152a 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-source.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-source.c @@ -24,11 +24,9 @@ #include -#define FF_LOG_S(source, level, format, ...) \ - blog(level, "[Media Source '%s']: " format, \ - obs_source_get_name(source), ##__VA_ARGS__) -#define FF_BLOG(level, format, ...) \ - FF_LOG_S(s->source, level, format, ##__VA_ARGS__) +#define FF_LOG_S(source, level, format, ...) \ + blog(level, "[Media Source '%s']: " format, obs_source_get_name(source), ##__VA_ARGS__) +#define FF_BLOG(level, format, ...) FF_LOG_S(s->source, level, format, ##__VA_ARGS__) struct ffmpeg_source { media_playback_t *media; @@ -91,22 +89,19 @@ static void set_media_state(void *data, enum obs_media_state state) s->state = state; } -static bool is_local_file_modified(obs_properties_t *props, - obs_property_t *prop, obs_data_t *settings) +static bool is_local_file_modified(obs_properties_t *props, obs_property_t *prop, obs_data_t *settings) { UNUSED_PARAMETER(prop); bool enabled = obs_data_get_bool(settings, "is_local_file"); obs_property_t *input = obs_properties_get(props, "input"); - obs_property_t *input_format = - obs_properties_get(props, "input_format"); + obs_property_t *input_format = obs_properties_get(props, "input_format"); obs_property_t *local_file = obs_properties_get(props, "local_file"); obs_property_t *looping = obs_properties_get(props, "looping"); obs_property_t *buffering = obs_properties_get(props, "buffering_mb"); obs_property_t *seekable = obs_properties_get(props, "seekable"); obs_property_t *speed = obs_properties_get(props, "speed_percent"); - obs_property_t *reconnect_delay_sec = - obs_properties_get(props, "reconnect_delay_sec"); + obs_property_t *reconnect_delay_sec = obs_properties_get(props, "reconnect_delay_sec"); obs_property_set_visible(input, !enabled); obs_property_set_visible(input_format, !enabled); obs_property_set_visible(buffering, !enabled); @@ -134,8 +129,7 @@ static void ffmpeg_source_defaults(obs_data_t *settings) static const char *media_filter = " (*.mp4 *.m4v *.ts *.mov *.mxf *.flv *.mkv *.avi *.mp3 *.ogg *.aac *.wav *.gif *.webm);;"; -static const char *video_filter = - " (*.mp4 *.m4v *.ts *.mov *.mxf *.flv *.mkv *.avi *.gif *.webm);;"; +static const char *video_filter = " (*.mp4 *.m4v *.ts *.mov *.mxf *.flv *.mkv *.avi *.gif *.webm);;"; static const char *audio_filter = " (*.mp3 *.aac *.ogg *.wav);;"; static obs_properties_t *ffmpeg_source_getproperties(void *data) @@ -150,8 +144,7 @@ static obs_properties_t *ffmpeg_source_getproperties(void *data) obs_property_t *prop; // use this when obs allows non-readonly paths - prop = obs_properties_add_bool(props, "is_local_file", - obs_module_text("LocalFile")); + prop = obs_properties_add_bool(props, "is_local_file", obs_module_text("LocalFile")); obs_property_set_modified_callback(prop, is_local_file_modified); @@ -174,79 +167,54 @@ static obs_properties_t *ffmpeg_source_getproperties(void *data) dstr_resize(&path, slash - path.array + 1); } - obs_properties_add_path(props, "local_file", - obs_module_text("LocalFile"), OBS_PATH_FILE, - filter.array, path.array); + obs_properties_add_path(props, "local_file", obs_module_text("LocalFile"), OBS_PATH_FILE, filter.array, + path.array); dstr_free(&filter); dstr_free(&path); obs_properties_add_bool(props, "looping", obs_module_text("Looping")); - obs_properties_add_bool(props, "restart_on_activate", - obs_module_text("RestartWhenActivated")); + obs_properties_add_bool(props, "restart_on_activate", obs_module_text("RestartWhenActivated")); - prop = obs_properties_add_int_slider(props, "buffering_mb", - obs_module_text("BufferingMB"), 0, - 16, 1); + prop = obs_properties_add_int_slider(props, "buffering_mb", obs_module_text("BufferingMB"), 0, 16, 1); obs_property_int_set_suffix(prop, " MB"); - obs_properties_add_text(props, "input", obs_module_text("Input"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "input", obs_module_text("Input"), OBS_TEXT_DEFAULT); - obs_properties_add_text(props, "input_format", - obs_module_text("InputFormat"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "input_format", obs_module_text("InputFormat"), OBS_TEXT_DEFAULT); - prop = obs_properties_add_int_slider( - props, "reconnect_delay_sec", - obs_module_text("ReconnectDelayTime"), 1, 60, 1); + prop = obs_properties_add_int_slider(props, "reconnect_delay_sec", obs_module_text("ReconnectDelayTime"), 1, 60, + 1); obs_property_int_set_suffix(prop, " S"); - obs_properties_add_bool(props, "hw_decode", - obs_module_text("HardwareDecode")); + obs_properties_add_bool(props, "hw_decode", obs_module_text("HardwareDecode")); - obs_properties_add_bool(props, "clear_on_media_end", - obs_module_text("ClearOnMediaEnd")); + obs_properties_add_bool(props, "clear_on_media_end", obs_module_text("ClearOnMediaEnd")); - prop = obs_properties_add_bool( - props, "close_when_inactive", - obs_module_text("CloseFileWhenInactive")); + prop = obs_properties_add_bool(props, "close_when_inactive", obs_module_text("CloseFileWhenInactive")); - obs_property_set_long_description( - prop, obs_module_text("CloseFileWhenInactive.ToolTip")); + obs_property_set_long_description(prop, obs_module_text("CloseFileWhenInactive.ToolTip")); - prop = obs_properties_add_int_slider(props, "speed_percent", - obs_module_text("SpeedPercentage"), - 1, 200, 1); + prop = obs_properties_add_int_slider(props, "speed_percent", obs_module_text("SpeedPercentage"), 1, 200, 1); obs_property_int_set_suffix(prop, "%"); - prop = obs_properties_add_list(props, "color_range", - obs_module_text("ColorRange"), - OBS_COMBO_TYPE_LIST, + prop = obs_properties_add_list(props, "color_range", obs_module_text("ColorRange"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(prop, obs_module_text("ColorRange.Auto"), - VIDEO_RANGE_DEFAULT); - obs_property_list_add_int(prop, obs_module_text("ColorRange.Partial"), - VIDEO_RANGE_PARTIAL); - obs_property_list_add_int(prop, obs_module_text("ColorRange.Full"), - VIDEO_RANGE_FULL); + obs_property_list_add_int(prop, obs_module_text("ColorRange.Auto"), VIDEO_RANGE_DEFAULT); + obs_property_list_add_int(prop, obs_module_text("ColorRange.Partial"), VIDEO_RANGE_PARTIAL); + obs_property_list_add_int(prop, obs_module_text("ColorRange.Full"), VIDEO_RANGE_FULL); - obs_properties_add_bool(props, "linear_alpha", - obs_module_text("LinearAlpha")); + obs_properties_add_bool(props, "linear_alpha", obs_module_text("LinearAlpha")); obs_properties_add_bool(props, "seekable", obs_module_text("Seekable")); - prop = obs_properties_add_text(props, "ffmpeg_options", - obs_module_text("FFmpegOpts"), - OBS_TEXT_DEFAULT); - obs_property_set_long_description( - prop, obs_module_text("FFmpegOpts.ToolTip.Source")); + prop = obs_properties_add_text(props, "ffmpeg_options", obs_module_text("FFmpegOpts"), OBS_TEXT_DEFAULT); + obs_property_set_long_description(prop, obs_module_text("FFmpegOpts.ToolTip.Source")); return props; } -static void dump_source_info(struct ffmpeg_source *s, const char *input, - const char *input_format) +static void dump_source_info(struct ffmpeg_source *s, const char *input, const char *input_format) { if (!s->log_changes) return; @@ -263,14 +231,10 @@ static void dump_source_info(struct ffmpeg_source *s, const char *input, "\tclose_when_inactive: %s\n" "\tfull_decode: %s\n" "\tffmpeg_options: %s", - input ? input : "(null)", - input_format ? input_format : "(null)", s->speed_percent, - s->is_looping ? "yes" : "no", s->is_linear_alpha ? "yes" : "no", - s->is_hw_decoding ? "yes" : "no", - s->is_clear_on_media_end ? "yes" : "no", - s->restart_on_activate ? "yes" : "no", - s->close_when_inactive ? "yes" : "no", - s->full_decode ? "yes" : "no", s->ffmpeg_options); + input ? input : "(null)", input_format ? input_format : "(null)", s->speed_percent, + s->is_looping ? "yes" : "no", s->is_linear_alpha ? "yes" : "no", s->is_hw_decoding ? "yes" : "no", + s->is_clear_on_media_end ? "yes" : "no", s->restart_on_activate ? "yes" : "no", + s->close_when_inactive ? "yes" : "no", s->full_decode ? "yes" : "no", s->ffmpeg_options); } static void get_frame(void *opaque, struct obs_source_frame *f) @@ -360,8 +324,7 @@ static void ffmpeg_source_start(struct ffmpeg_source *s) return; media_playback_play(s->media, s->is_looping, s->reconnecting); - if (s->is_local_file && media_playback_has_video(s->media) && - (s->is_clear_on_media_end || s->is_looping)) + if (s->is_local_file && media_playback_has_video(s->media) && (s->is_clear_on_media_end || s->is_looping)) obs_source_show_preloaded_video(s->source); else obs_source_output_video(s->source, NULL); @@ -373,8 +336,7 @@ static void *ffmpeg_source_reconnect(void *data) { struct ffmpeg_source *s = data; - int ret = os_event_timedwait(s->reconnect_stop_event, - s->reconnect_delay_sec * 1000); + int ret = os_event_timedwait(s->reconnect_stop_event, s->reconnect_delay_sec * 1000); if (ret == 0 || s->media) return NULL; @@ -412,8 +374,7 @@ static void ffmpeg_source_tick(void *data, float seconds) s->reconnect_thread_valid = false; os_event_reset(s->reconnect_stop_event); } - if (pthread_create(&s->reconnect_thread, NULL, - ffmpeg_source_reconnect, s) != 0) { + if (pthread_create(&s->reconnect_thread, NULL, ffmpeg_source_reconnect, s) != 0) { FF_BLOG(LOG_WARNING, "Could not create " "reconnect thread"); pthread_mutex_unlock(&s->reconnect_mutex); @@ -435,8 +396,7 @@ static void ffmpeg_source_update(void *data, obs_data_t *settings) bool is_local_file = obs_data_get_bool(settings, "is_local_file"); bool is_stinger = obs_data_get_bool(settings, "is_stinger"); bool is_track_matte = obs_data_get_bool(settings, "is_track_matte"); - bool should_restart_media = (is_local_file != s->is_local_file) || - (is_stinger != s->is_stinger); + bool should_restart_media = (is_local_file != s->is_local_file) || (is_stinger != s->is_stinger); const char *input; const char *input_format; @@ -461,11 +421,8 @@ static void ffmpeg_source_update(void *data, obs_data_t *settings) should_restart_media = true; input = obs_data_get_string(settings, "input"); input_format = obs_data_get_string(settings, "input_format"); - s->reconnect_delay_sec = - (int)obs_data_get_int(settings, "reconnect_delay_sec"); - s->reconnect_delay_sec = s->reconnect_delay_sec == 0 - ? 10 - : s->reconnect_delay_sec; + s->reconnect_delay_sec = (int)obs_data_get_int(settings, "reconnect_delay_sec"); + s->reconnect_delay_sec = s->reconnect_delay_sec == 0 ? 10 : s->reconnect_delay_sec; is_looping = false; } @@ -479,17 +436,14 @@ static void ffmpeg_source_update(void *data, obs_data_t *settings) ffmpeg_options = obs_data_get_string(settings, "ffmpeg_options"); /* Restart media source if these properties are changed */ - if (s->is_hw_decoding != is_hw_decoding || s->range != range || - s->speed_percent != speed_percent || - (s->ffmpeg_options && - strcmp(s->ffmpeg_options, ffmpeg_options) != 0)) + if (s->is_hw_decoding != is_hw_decoding || s->range != range || s->speed_percent != speed_percent || + (s->ffmpeg_options && strcmp(s->ffmpeg_options, ffmpeg_options) != 0)) should_restart_media = true; /* If media has ended and user enables looping, user expects that it restarts. * Should still check if is_looping was changed, because users may stop them * intentionally, which is why we only check for ENDED and not STOPPED. */ - if (active && s->state == OBS_MEDIA_STATE_ENDED && is_looping == true && - s->is_looping == false) { + if (active && s->state == OBS_MEDIA_STATE_ENDED && is_looping == true && s->is_looping == false) { should_restart_media = true; } @@ -497,18 +451,15 @@ static void ffmpeg_source_update(void *data, obs_data_t *settings) bfree(s->ffmpeg_options); s->is_looping = is_looping; - s->close_when_inactive = - obs_data_get_bool(settings, "close_when_inactive"); + s->close_when_inactive = obs_data_get_bool(settings, "close_when_inactive"); s->input = input ? bstrdup(input) : NULL; s->input_format = input_format ? bstrdup(input_format) : NULL; s->is_hw_decoding = is_hw_decoding; s->full_decode = obs_data_get_bool(settings, "full_decode"); - s->is_clear_on_media_end = - obs_data_get_bool(settings, "clear_on_media_end"); - s->restart_on_activate = - !astrcmpi_n(input, RIST_PROTO, sizeof(RIST_PROTO) - 1) - ? false - : obs_data_get_bool(settings, "restart_on_activate"); + s->is_clear_on_media_end = obs_data_get_bool(settings, "clear_on_media_end"); + s->restart_on_activate = !astrcmpi_n(input, RIST_PROTO, sizeof(RIST_PROTO) - 1) + ? false + : obs_data_get_bool(settings, "restart_on_activate"); s->range = range; is_linear_alpha = obs_data_get_bool(settings, "linear_alpha"); s->is_linear_alpha = is_linear_alpha; @@ -548,8 +499,7 @@ static const char *ffmpeg_source_getname(void *unused) return obs_module_text("FFmpegSource"); } -static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -594,8 +544,7 @@ static void get_nb_frames(void *data, calldata_t *cd) calldata_set_int(cd, "num_frames", frames); } -static bool ffmpeg_source_play_hotkey(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *hotkey, bool pressed) +static bool ffmpeg_source_play_hotkey(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -605,16 +554,14 @@ static bool ffmpeg_source_play_hotkey(void *data, obs_hotkey_pair_id id, struct ffmpeg_source *s = data; - if (s->state == OBS_MEDIA_STATE_PLAYING || - !obs_source_showing(s->source)) + if (s->state == OBS_MEDIA_STATE_PLAYING || !obs_source_showing(s->source)) return false; obs_source_media_play_pause(s->source, false); return true; } -static bool ffmpeg_source_pause_hotkey(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *hotkey, bool pressed) +static bool ffmpeg_source_pause_hotkey(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -624,16 +571,14 @@ static bool ffmpeg_source_pause_hotkey(void *data, obs_hotkey_pair_id id, struct ffmpeg_source *s = data; - if (s->state != OBS_MEDIA_STATE_PLAYING || - !obs_source_showing(s->source)) + if (s->state != OBS_MEDIA_STATE_PLAYING || !obs_source_showing(s->source)) return false; obs_source_media_play_pause(s->source, true); return true; } -static void ffmpeg_source_stop_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void ffmpeg_source_stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -666,28 +611,22 @@ static void *ffmpeg_source_create(obs_data_t *settings, obs_source_t *source) return NULL; } - s->hotkey = obs_hotkey_register_source(source, "MediaSource.Restart", - obs_module_text("RestartMedia"), + s->hotkey = obs_hotkey_register_source(source, "MediaSource.Restart", obs_module_text("RestartMedia"), restart_hotkey, s); - s->play_pause_hotkey = obs_hotkey_pair_register_source( - s->source, "MediaSource.Play", obs_module_text("Play"), - "MediaSource.Pause", obs_module_text("Pause"), - ffmpeg_source_play_hotkey, ffmpeg_source_pause_hotkey, s, s); + s->play_pause_hotkey = obs_hotkey_pair_register_source(s->source, "MediaSource.Play", obs_module_text("Play"), + "MediaSource.Pause", obs_module_text("Pause"), + ffmpeg_source_play_hotkey, ffmpeg_source_pause_hotkey, s, + s); - s->stop_hotkey = obs_hotkey_register_source(source, "MediaSource.Stop", - obs_module_text("Stop"), - ffmpeg_source_stop_hotkey, - s); + s->stop_hotkey = obs_hotkey_register_source(source, "MediaSource.Stop", obs_module_text("Stop"), + ffmpeg_source_stop_hotkey, s); proc_handler_t *ph = obs_source_get_proc_handler(source); proc_handler_add(ph, "void restart()", restart_proc, s); - proc_handler_add(ph, "void preload_first_frame()", - preload_first_frame_proc, s); - proc_handler_add(ph, "void get_duration(out int duration)", - get_duration, s); - proc_handler_add(ph, "void get_nb_frames(out int num_frames)", - get_nb_frames, s); + proc_handler_add(ph, "void preload_first_frame()", preload_first_frame_proc, s); + proc_handler_add(ph, "void get_duration(out int duration)", get_duration, s); + proc_handler_add(ph, "void get_nb_frames(out int num_frames)", get_nb_frames, s); ffmpeg_source_update(s, settings); return s; @@ -832,9 +771,8 @@ static obs_missing_files_t *ffmpeg_source_missingfiles(void *data) if (s->is_local_file && strcmp(s->input, "") != 0) { if (!os_file_exists(s->input)) { - obs_missing_file_t *file = obs_missing_file_create( - s->input, missing_file_callback, - OBS_MISSING_FILE_SOURCE, s->source, NULL); + obs_missing_file_t *file = obs_missing_file_create(s->input, missing_file_callback, + OBS_MISSING_FILE_SOURCE, s->source, NULL); obs_missing_files_add_file(files, file); } @@ -846,8 +784,7 @@ static obs_missing_files_t *ffmpeg_source_missingfiles(void *data) struct obs_source_info ffmpeg_source = { .id = "ffmpeg_source", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_DO_NOT_DUPLICATE | + .output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_CONTROLLABLE_MEDIA, .get_name = ffmpeg_source_getname, .create = ffmpeg_source_create, diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-srt.h b/plugins/obs-ffmpeg/obs-ffmpeg-srt.h index d6d6c9cd4..576f8e7a6 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-srt.h +++ b/plugins/obs-ffmpeg/obs-ffmpeg-srt.h @@ -31,11 +31,7 @@ #define SRT_LIVE_DEFAULT_PAYLOAD_SIZE 1316 #endif -enum SRTMode { - SRT_MODE_CALLER = 0, - SRT_MODE_LISTENER = 1, - SRT_MODE_RENDEZVOUS = 2 -}; +enum SRTMode { SRT_MODE_CALLER = 0, SRT_MODE_LISTENER = 1, SRT_MODE_RENDEZVOUS = 2 }; typedef struct SRTContext { SRTSOCKET fd; @@ -88,33 +84,29 @@ static int libsrt_neterrno(URLContext *h) SRTContext *s = (SRTContext *)h->priv_data; int os_errno; int err = srt_getlasterror(&os_errno); - blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: %s", - srt_getlasterror_str()); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: %s", srt_getlasterror_str()); if (err == SRT_EASYNCRCV || err == SRT_EASYNCSND) return AVERROR(EAGAIN); if (err == SRT_ECONNREJ) { int errj = srt_getrejectreason(s->fd); if (errj == SRT_REJ_BADSECRET) - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Wrong password"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Wrong password"); else - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, %s", + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, %s", srt_rejectreason_str(errj)); } return os_errno ? AVERROR(os_errno) : AVERROR_UNKNOWN; } -static int libsrt_getsockopt(URLContext *h, SRTSOCKET fd, SRT_SOCKOPT optname, - const char *optnamestr, void *optval, int *optlen) +static int libsrt_getsockopt(URLContext *h, SRTSOCKET fd, SRT_SOCKOPT optname, const char *optnamestr, void *optval, + int *optlen) { UNUSED_PARAMETER(h); if (srt_getsockopt(fd, 0, optname, optval, optlen) < 0) { - blog(LOG_INFO, - "[obs-ffmpeg mpegts muxer / libsrt]: Failed to get option %s on socket: %s", - optnamestr, srt_getlasterror_str()); + blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: Failed to get option %s on socket: %s", optnamestr, + srt_getlasterror_str()); return AVERROR(EIO); } return 0; @@ -124,12 +116,10 @@ static int libsrt_socket_nonblock(SRTSOCKET socket, int enable) { int ret, blocking = enable ? 0 : 1; /* Setting SRTO_{SND,RCV}SYN options to 1 enable blocking mode, setting them to 0 enable non-blocking mode. */ - ret = srt_setsockopt(socket, 0, SRTO_SNDSYN, &blocking, - sizeof(blocking)); + ret = srt_setsockopt(socket, 0, SRTO_SNDSYN, &blocking, sizeof(blocking)); if (ret < 0) return ret; - return srt_setsockopt(socket, 0, SRTO_RCVSYN, &blocking, - sizeof(blocking)); + return srt_setsockopt(socket, 0, SRTO_RCVSYN, &blocking, sizeof(blocking)); } static int libsrt_epoll_create(URLContext *h, SRTSOCKET fd, int write) @@ -152,24 +142,20 @@ static int libsrt_network_wait_fd(URLContext *h, int eid, int write) SRTSOCKET error[1]; SRTContext *s = (SRTContext *)h->priv_data; if (write) { - ret = srt_epoll_wait(eid, error, &errlen, ready, &len, - POLLING_TIME, 0, 0, 0, 0); + ret = srt_epoll_wait(eid, error, &errlen, ready, &len, POLLING_TIME, 0, 0, 0, 0); } else { - ret = srt_epoll_wait(eid, ready, &len, error, &errlen, - POLLING_TIME, 0, 0, 0, 0); + ret = srt_epoll_wait(eid, ready, &len, error, &errlen, POLLING_TIME, 0, 0, 0, 0); } if (len == 1 && errlen == 1 && s->mode == SRT_MODE_CALLER) { /* Socket reported in wsock AND rsock signifies an error. */ int reason = srt_getrejectreason(*ready); - if (reason == SRT_REJ_BADSECRET || reason == SRT_REJ_UNSECURE || - reason == SRT_REJ_TIMEOUT) { + if (reason == SRT_REJ_BADSECRET || reason == SRT_REJ_UNSECURE || reason == SRT_REJ_TIMEOUT) { blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, wrong password or invalid URL"); return OBS_OUTPUT_INVALID_STREAM; } else { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, %s", + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection rejected, %s", srt_rejectreason_str(reason)); } } @@ -191,9 +177,7 @@ int check_interrupt(AVIOInterruptCB *cb) return 0; } -static int libsrt_network_wait_fd_timeout(URLContext *h, int eid, int write, - int64_t timeout, - AVIOInterruptCB *int_cb) +static int libsrt_network_wait_fd_timeout(URLContext *h, int eid, int write, int64_t timeout, AVIOInterruptCB *int_cb) { int ret; int64_t wait_start = 0; @@ -213,18 +197,16 @@ static int libsrt_network_wait_fd_timeout(URLContext *h, int eid, int write, } } -static int libsrt_listen(int eid, SRTSOCKET fd, const struct sockaddr *addr, - socklen_t addrlen, URLContext *h, int64_t timeout) +static int libsrt_listen(int eid, SRTSOCKET fd, const struct sockaddr *addr, socklen_t addrlen, URLContext *h, + int64_t timeout) { int ret; int reuse = 1; /* Max streamid length plus an extra space for the terminating null character */ char streamid[513]; int streamid_len = sizeof(streamid); - if (srt_setsockopt(fd, SOL_SOCKET, SRTO_REUSEADDR, &reuse, - sizeof(reuse))) { - blog(LOG_WARNING, - "[obs-ffmpeg mpegts muxer / libsrt]: setsockopt(SRTO_REUSEADDR) failed"); + if (srt_setsockopt(fd, SOL_SOCKET, SRTO_REUSEADDR, &reuse, sizeof(reuse))) { + blog(LOG_WARNING, "[obs-ffmpeg mpegts muxer / libsrt]: setsockopt(SRTO_REUSEADDR) failed"); } if (srt_bind(fd, addr, addrlen)) return libsrt_neterrno(h); @@ -232,8 +214,7 @@ static int libsrt_listen(int eid, SRTSOCKET fd, const struct sockaddr *addr, if (srt_listen(fd, 1)) return libsrt_neterrno(h); - ret = libsrt_network_wait_fd_timeout(h, eid, 0, timeout, - &h->interrupt_callback); + ret = libsrt_network_wait_fd_timeout(h, eid, 0, timeout, &h->interrupt_callback); if (ret < 0) return ret; @@ -241,53 +222,44 @@ static int libsrt_listen(int eid, SRTSOCKET fd, const struct sockaddr *addr, if (ret < 0) return libsrt_neterrno(h); if (libsrt_socket_nonblock(ret, 1) < 0) - blog(LOG_DEBUG, - "[obs-ffmpeg mpegts muxer / libsrt]: libsrt_socket_nonblock failed"); - if (!libsrt_getsockopt(h, ret, SRTO_STREAMID, "SRTO_STREAMID", streamid, - &streamid_len)) + blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt_socket_nonblock failed"); + if (!libsrt_getsockopt(h, ret, SRTO_STREAMID, "SRTO_STREAMID", streamid, &streamid_len)) /* Note: returned streamid_len doesn't count the terminating null character */ - blog(LOG_INFO, - "[obs-ffmpeg mpegts muxer / libsrt]: Accept streamid [%s], length %d", - streamid, streamid_len); + blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: Accept streamid [%s], length %d", streamid, + streamid_len); return ret; } -static int libsrt_listen_connect(int eid, SRTSOCKET fd, - const struct sockaddr *addr, socklen_t addrlen, - int64_t timeout, URLContext *h, - int will_try_next) +static int libsrt_listen_connect(int eid, SRTSOCKET fd, const struct sockaddr *addr, socklen_t addrlen, int64_t timeout, + URLContext *h, int will_try_next) { int ret; if (srt_connect(fd, addr, addrlen) < 0) return libsrt_neterrno(h); - ret = libsrt_network_wait_fd_timeout(h, eid, 1, timeout, - &h->interrupt_callback); + ret = libsrt_network_wait_fd_timeout(h, eid, 1, timeout, &h->interrupt_callback); if (ret < 0) { if (will_try_next) { blog(LOG_WARNING, "[obs-ffmpeg mpegts muxer / libsrt]: Connection to %s failed (%s), trying next address", h->url, av_err2str(ret)); } else { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Connection to %s failed: %s", - h->url, av_err2str(ret)); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Connection to %s failed: %s", h->url, + av_err2str(ret)); } } return ret; } -static int libsrt_setsockopt(URLContext *h, SRTSOCKET fd, SRT_SOCKOPT optname, - const char *optnamestr, const void *optval, - int optlen) +static int libsrt_setsockopt(URLContext *h, SRTSOCKET fd, SRT_SOCKOPT optname, const char *optnamestr, + const void *optval, int optlen) { UNUSED_PARAMETER(h); if (srt_setsockopt(fd, 0, optname, optval, optlen) < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Failed to set option %s on socket: %s", - optnamestr, srt_getlasterror_str()); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Failed to set option %s on socket: %s", optnamestr, + srt_getlasterror_str()); return AVERROR(EIO); } return 0; @@ -302,11 +274,9 @@ static int libsrt_set_options_post(URLContext *h, SRTSOCKET fd) SRTContext *s = (SRTContext *)h->priv_data; if ((s->inputbw >= 0 && - libsrt_setsockopt(h, fd, SRTO_INPUTBW, "SRTO_INPUTBW", &s->inputbw, - sizeof(s->inputbw)) < 0) || + libsrt_setsockopt(h, fd, SRTO_INPUTBW, "SRTO_INPUTBW", &s->inputbw, sizeof(s->inputbw)) < 0) || (s->oheadbw >= 0 && - libsrt_setsockopt(h, fd, SRTO_OHEADBW, "SRTO_OHEADBW", &s->oheadbw, - sizeof(s->oheadbw)) < 0)) { + libsrt_setsockopt(h, fd, SRTO_OHEADBW, "SRTO_OHEADBW", &s->oheadbw, sizeof(s->oheadbw)) < 0)) { return AVERROR(EIO); } return 0; @@ -323,119 +293,78 @@ static int libsrt_set_options_pre(URLContext *h, SRTSOCKET fd) int rcvlatency = (int)(s->rcvlatency / 1000); int peerlatency = (int)(s->peerlatency / 1000); #if SRT_VERSION_VALUE >= 0x010302 - int snddropdelay = s->snddropdelay > 0 ? (int)(s->snddropdelay / 1000) - : (int)(s->snddropdelay); + int snddropdelay = s->snddropdelay > 0 ? (int)(s->snddropdelay / 1000) : (int)(s->snddropdelay); #endif int connect_timeout = (int)(s->connect_timeout); if ((s->mode == SRT_MODE_RENDEZVOUS && - libsrt_setsockopt(h, fd, SRTO_RENDEZVOUS, "SRTO_RENDEZVOUS", &yes, - sizeof(yes)) < 0) || + libsrt_setsockopt(h, fd, SRTO_RENDEZVOUS, "SRTO_RENDEZVOUS", &yes, sizeof(yes)) < 0) || (s->transtype != SRTT_INVALID && - libsrt_setsockopt(h, fd, SRTO_TRANSTYPE, "SRTO_TRANSTYPE", - &s->transtype, sizeof(s->transtype)) < 0) || - (s->maxbw >= 0 && - libsrt_setsockopt(h, fd, SRTO_MAXBW, "SRTO_MAXBW", &s->maxbw, - sizeof(s->maxbw)) < 0) || + libsrt_setsockopt(h, fd, SRTO_TRANSTYPE, "SRTO_TRANSTYPE", &s->transtype, sizeof(s->transtype)) < 0) || + (s->maxbw >= 0 && libsrt_setsockopt(h, fd, SRTO_MAXBW, "SRTO_MAXBW", &s->maxbw, sizeof(s->maxbw)) < 0) || (s->pbkeylen >= 0 && - libsrt_setsockopt(h, fd, SRTO_PBKEYLEN, "SRTO_PBKEYLEN", - &s->pbkeylen, sizeof(s->pbkeylen)) < 0) || - (s->passphrase && - libsrt_setsockopt(h, fd, SRTO_PASSPHRASE, "SRTO_PASSPHRASE", - s->passphrase, - (int)strlen(s->passphrase)) < 0) || + libsrt_setsockopt(h, fd, SRTO_PBKEYLEN, "SRTO_PBKEYLEN", &s->pbkeylen, sizeof(s->pbkeylen)) < 0) || + (s->passphrase && libsrt_setsockopt(h, fd, SRTO_PASSPHRASE, "SRTO_PASSPHRASE", s->passphrase, + (int)strlen(s->passphrase)) < 0) || #if SRT_VERSION_VALUE >= 0x010302 #if SRT_VERSION_VALUE >= 0x010401 (s->enforced_encryption >= 0 && - libsrt_setsockopt(h, fd, SRTO_ENFORCEDENCRYPTION, - "SRTO_ENFORCEDENCRYPTION", - &s->enforced_encryption, + libsrt_setsockopt(h, fd, SRTO_ENFORCEDENCRYPTION, "SRTO_ENFORCEDENCRYPTION", &s->enforced_encryption, sizeof(s->enforced_encryption)) < 0) || #else /* SRTO_STRICTENC == SRTO_ENFORCEDENCRYPTION (53), but for compatibility, we used SRTO_STRICTENC */ (s->enforced_encryption >= 0 && - libsrt_setsockopt(h, fd, SRTO_STRICTENC, "SRTO_STRICTENC", - &s->enforced_encryption, + libsrt_setsockopt(h, fd, SRTO_STRICTENC, "SRTO_STRICTENC", &s->enforced_encryption, sizeof(s->enforced_encryption)) < 0) || #endif - (s->kmrefreshrate >= 0 && - libsrt_setsockopt(h, fd, SRTO_KMREFRESHRATE, "SRTO_KMREFRESHRATE", - &s->kmrefreshrate, - sizeof(s->kmrefreshrate)) < 0) || - (s->kmpreannounce >= 0 && - libsrt_setsockopt(h, fd, SRTO_KMPREANNOUNCE, "SRTO_KMPREANNOUNCE", - &s->kmpreannounce, - sizeof(s->kmpreannounce)) < 0) || - (s->snddropdelay >= -1 && - libsrt_setsockopt(h, fd, SRTO_SNDDROPDELAY, "SRTO_SNDDROPDELAY", - &snddropdelay, sizeof(snddropdelay)) < 0) || + (s->kmrefreshrate >= 0 && libsrt_setsockopt(h, fd, SRTO_KMREFRESHRATE, "SRTO_KMREFRESHRATE", + &s->kmrefreshrate, sizeof(s->kmrefreshrate)) < 0) || + (s->kmpreannounce >= 0 && libsrt_setsockopt(h, fd, SRTO_KMPREANNOUNCE, "SRTO_KMPREANNOUNCE", + &s->kmpreannounce, sizeof(s->kmpreannounce)) < 0) || + (s->snddropdelay >= -1 && libsrt_setsockopt(h, fd, SRTO_SNDDROPDELAY, "SRTO_SNDDROPDELAY", &snddropdelay, + sizeof(snddropdelay)) < 0) || #endif - (s->mss >= 0 && libsrt_setsockopt(h, fd, SRTO_MSS, "SRTO_MSS", - &s->mss, sizeof(s->mss)) < 0) || - (s->ffs >= 0 && libsrt_setsockopt(h, fd, SRTO_FC, "SRTO_FC", - &s->ffs, sizeof(s->ffs)) < 0) || - (s->ipttl >= 0 && - libsrt_setsockopt(h, fd, SRTO_IPTTL, "SRTO_IPTTL", &s->ipttl, - sizeof(s->ipttl)) < 0) || - (s->iptos >= 0 && - libsrt_setsockopt(h, fd, SRTO_IPTOS, "SRTO_IPTOS", &s->iptos, - sizeof(s->iptos)) < 0) || + (s->mss >= 0 && libsrt_setsockopt(h, fd, SRTO_MSS, "SRTO_MSS", &s->mss, sizeof(s->mss)) < 0) || + (s->ffs >= 0 && libsrt_setsockopt(h, fd, SRTO_FC, "SRTO_FC", &s->ffs, sizeof(s->ffs)) < 0) || + (s->ipttl >= 0 && libsrt_setsockopt(h, fd, SRTO_IPTTL, "SRTO_IPTTL", &s->ipttl, sizeof(s->ipttl)) < 0) || + (s->iptos >= 0 && libsrt_setsockopt(h, fd, SRTO_IPTOS, "SRTO_IPTOS", &s->iptos, sizeof(s->iptos)) < 0) || (s->latency >= 0 && - libsrt_setsockopt(h, fd, SRTO_LATENCY, "SRTO_LATENCY", &latency, - sizeof(latency)) < 0) || + libsrt_setsockopt(h, fd, SRTO_LATENCY, "SRTO_LATENCY", &latency, sizeof(latency)) < 0) || (s->rcvlatency >= 0 && - libsrt_setsockopt(h, fd, SRTO_RCVLATENCY, "SRTO_RCVLATENCY", - &rcvlatency, sizeof(rcvlatency)) < 0) || + libsrt_setsockopt(h, fd, SRTO_RCVLATENCY, "SRTO_RCVLATENCY", &rcvlatency, sizeof(rcvlatency)) < 0) || (s->peerlatency >= 0 && - libsrt_setsockopt(h, fd, SRTO_PEERLATENCY, "SRTO_PEERLATENCY", - &peerlatency, sizeof(peerlatency)) < 0) || + libsrt_setsockopt(h, fd, SRTO_PEERLATENCY, "SRTO_PEERLATENCY", &peerlatency, sizeof(peerlatency)) < 0) || (s->tlpktdrop >= 0 && - libsrt_setsockopt(h, fd, SRTO_TLPKTDROP, "SRTO_TLPKTDROP", - &s->tlpktdrop, sizeof(s->tlpktdrop)) < 0) || + libsrt_setsockopt(h, fd, SRTO_TLPKTDROP, "SRTO_TLPKTDROP", &s->tlpktdrop, sizeof(s->tlpktdrop)) < 0) || (s->nakreport >= 0 && - libsrt_setsockopt(h, fd, SRTO_NAKREPORT, "SRTO_NAKREPORT", - &s->nakreport, sizeof(s->nakreport)) < 0) || - (connect_timeout >= 0 && - libsrt_setsockopt(h, fd, SRTO_CONNTIMEO, "SRTO_CONNTIMEO", - &connect_timeout, - sizeof(connect_timeout)) < 0) || + libsrt_setsockopt(h, fd, SRTO_NAKREPORT, "SRTO_NAKREPORT", &s->nakreport, sizeof(s->nakreport)) < 0) || + (connect_timeout >= 0 && libsrt_setsockopt(h, fd, SRTO_CONNTIMEO, "SRTO_CONNTIMEO", &connect_timeout, + sizeof(connect_timeout)) < 0) || (s->sndbuf >= 0 && - libsrt_setsockopt(h, fd, SRTO_SNDBUF, "SRTO_SNDBUF", &s->sndbuf, - sizeof(s->sndbuf)) < 0) || + libsrt_setsockopt(h, fd, SRTO_SNDBUF, "SRTO_SNDBUF", &s->sndbuf, sizeof(s->sndbuf)) < 0) || (s->rcvbuf >= 0 && - libsrt_setsockopt(h, fd, SRTO_RCVBUF, "SRTO_RCVBUF", &s->rcvbuf, - sizeof(s->rcvbuf)) < 0) || + libsrt_setsockopt(h, fd, SRTO_RCVBUF, "SRTO_RCVBUF", &s->rcvbuf, sizeof(s->rcvbuf)) < 0) || (s->lossmaxttl >= 0 && - libsrt_setsockopt(h, fd, SRTO_LOSSMAXTTL, "SRTO_LOSSMAXTTL", - &s->lossmaxttl, sizeof(s->lossmaxttl)) < 0) || + libsrt_setsockopt(h, fd, SRTO_LOSSMAXTTL, "SRTO_LOSSMAXTTL", &s->lossmaxttl, sizeof(s->lossmaxttl)) < 0) || (s->minversion >= 0 && - libsrt_setsockopt(h, fd, SRTO_MINVERSION, "SRTO_MINVERSION", - &s->minversion, sizeof(s->minversion)) < 0) || + libsrt_setsockopt(h, fd, SRTO_MINVERSION, "SRTO_MINVERSION", &s->minversion, sizeof(s->minversion)) < 0) || (s->streamid && - libsrt_setsockopt(h, fd, SRTO_STREAMID, "SRTO_STREAMID", - s->streamid, (int)strlen(s->streamid)) < 0) || + libsrt_setsockopt(h, fd, SRTO_STREAMID, "SRTO_STREAMID", s->streamid, (int)strlen(s->streamid)) < 0) || #if SRT_VERSION_VALUE >= 0x010401 (s->smoother && - libsrt_setsockopt(h, fd, SRTO_CONGESTION, "SRTO_CONGESTION", - s->smoother, (int)strlen(s->smoother)) < 0) || + libsrt_setsockopt(h, fd, SRTO_CONGESTION, "SRTO_CONGESTION", s->smoother, (int)strlen(s->smoother)) < 0) || #else (s->smoother && - libsrt_setsockopt(h, fd, SRTO_SMOOTHER, "SRTO_SMOOTHER", - s->smoother, (int)strlen(s->smoother)) < 0) || + libsrt_setsockopt(h, fd, SRTO_SMOOTHER, "SRTO_SMOOTHER", s->smoother, (int)strlen(s->smoother)) < 0) || #endif (s->messageapi >= 0 && - libsrt_setsockopt(h, fd, SRTO_MESSAGEAPI, "SRTO_MESSAGEAPI", - &s->messageapi, sizeof(s->messageapi)) < 0) || - (s->payload_size >= 0 && - libsrt_setsockopt(h, fd, SRTO_PAYLOADSIZE, "SRTO_PAYLOADSIZE", - &s->payload_size, - sizeof(s->payload_size)) < 0) || + libsrt_setsockopt(h, fd, SRTO_MESSAGEAPI, "SRTO_MESSAGEAPI", &s->messageapi, sizeof(s->messageapi)) < 0) || + (s->payload_size >= 0 && libsrt_setsockopt(h, fd, SRTO_PAYLOADSIZE, "SRTO_PAYLOADSIZE", &s->payload_size, + sizeof(s->payload_size)) < 0) || (/*(h->flags & AVIO_FLAG_WRITE) &&*/ - libsrt_setsockopt(h, fd, SRTO_SENDER, "SRTO_SENDER", &yes, - sizeof(yes)) < 0) || + libsrt_setsockopt(h, fd, SRTO_SENDER, "SRTO_SENDER", &yes, sizeof(yes)) < 0) || (s->tsbpd >= 0 && - libsrt_setsockopt(h, fd, SRTO_TSBPDMODE, "SRTO_TSBPDMODE", - &s->tsbpd, sizeof(s->tsbpd)) < 0)) { + libsrt_setsockopt(h, fd, SRTO_TSBPDMODE, "SRTO_TSBPDMODE", &s->tsbpd, sizeof(s->tsbpd)) < 0)) { return AVERROR(EIO); } @@ -443,8 +372,7 @@ static int libsrt_set_options_pre(URLContext *h, SRTSOCKET fd) struct linger lin; lin.l_linger = s->linger; lin.l_onoff = lin.l_linger > 0 ? 1 : 0; - if (libsrt_setsockopt(h, fd, SRTO_LINGER, "SRTO_LINGER", &lin, - sizeof(lin)) < 0) + if (libsrt_setsockopt(h, fd, SRTO_LINGER, "SRTO_LINGER", &lin, sizeof(lin)) < 0) return AVERROR(EIO); } return 0; @@ -465,13 +393,11 @@ static int libsrt_setup(URLContext *h, const char *uri) int eid; struct sockaddr_in la; - av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), - &port, path, sizeof(path), uri); + av_url_split(proto, sizeof(proto), NULL, 0, hostname, sizeof(hostname), &port, path, sizeof(path), uri); if (strcmp(proto, "srt")) // should not happen ! return AVERROR(EINVAL); if (port <= 0 || port >= 65536) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Port missing in uri"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Port missing in uri"); return OBS_OUTPUT_CONNECT_FAILED; } p = strchr(uri, '?'); @@ -493,9 +419,7 @@ static int libsrt_setup(URLContext *h, const char *uri) hints.ai_flags |= AI_PASSIVE; ret = getaddrinfo(hostname[0] ? hostname : NULL, portstr, &hints, &ai); if (ret) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Failed to resolve hostname %s: %s", - hostname, + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Failed to resolve hostname %s: %s", hostname, #ifdef _WIN32 gai_strerrorA(ret) #else @@ -511,13 +435,11 @@ static int libsrt_setup(URLContext *h, const char *uri) blog(LOG_ERROR, "Invalid adapter configuration\n"); return OBS_OUTPUT_CONNECT_FAILED; } - blog(LOG_DEBUG, - "[obs-ffmpeg mpegts muxer / libsrt]: Adapter options %s:%s\n", - s->localip, s->localport); + blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: Adapter options %s:%s\n", s->localip, + s->localport); int lp = strtol(s->localport, NULL, 10); if (lp <= 0 || lp >= 65536) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: Local port missing in URL\n"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: Local port missing in URL\n"); return OBS_OUTPUT_CONNECT_FAILED; } la.sin_family = AF_INET; @@ -539,27 +461,20 @@ restart: /* Set the socket's send or receive buffer sizes, if specified. If unspecified or setting fails, system default is used. */ if (s->recv_buffer_size > 0) { - srt_setsockopt(fd, SOL_SOCKET, SRTO_UDP_RCVBUF, - &s->recv_buffer_size, - sizeof(s->recv_buffer_size)); + srt_setsockopt(fd, SOL_SOCKET, SRTO_UDP_RCVBUF, &s->recv_buffer_size, sizeof(s->recv_buffer_size)); } if (s->send_buffer_size > 0) { - srt_setsockopt(fd, SOL_SOCKET, SRTO_UDP_SNDBUF, - &s->send_buffer_size, - sizeof(s->send_buffer_size)); + srt_setsockopt(fd, SOL_SOCKET, SRTO_UDP_SNDBUF, &s->send_buffer_size, sizeof(s->send_buffer_size)); } if (libsrt_socket_nonblock(fd, 1) < 0) - blog(LOG_DEBUG, - "[obs-ffmpeg mpegts muxer / libsrt]: libsrt_socket_nonblock failed"); + blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt_socket_nonblock failed"); if (s->mode == SRT_MODE_LISTENER) { int read_eid = ret = libsrt_epoll_create(h, fd, 0); if (ret < 0) goto fail1; // multi-client - ret = libsrt_listen(read_eid, fd, cur_ai->ai_addr, - (socklen_t)cur_ai->ai_addrlen, h, - s->listen_timeout); + ret = libsrt_listen(read_eid, fd, cur_ai->ai_addr, (socklen_t)cur_ai->ai_addrlen, h, s->listen_timeout); srt_epoll_release(read_eid); if (ret < 0) goto fail1; @@ -570,16 +485,14 @@ restart: if (ret < 0) goto fail1; if (s->mode == SRT_MODE_RENDEZVOUS) { - if (srt_bind(fd, (struct sockaddr *)&la, - sizeof(struct sockaddr_in))) { + if (srt_bind(fd, (struct sockaddr *)&la, sizeof(struct sockaddr_in))) { ret = libsrt_neterrno(h); srt_epoll_release(write_eid); goto fail1; } } - ret = libsrt_listen_connect(write_eid, fd, cur_ai->ai_addr, - (socklen_t)(cur_ai->ai_addrlen), + ret = libsrt_listen_connect(write_eid, fd, cur_ai->ai_addr, (socklen_t)(cur_ai->ai_addrlen), open_timeout, h, !!cur_ai->ai_next); srt_epoll_release(write_eid); if (ret < 0) { @@ -595,8 +508,7 @@ restart: int packet_size = 0; int optlen = sizeof(packet_size); - ret = libsrt_getsockopt(h, fd, SRTO_PAYLOADSIZE, "SRTO_PAYLOADSIZE", - &packet_size, &optlen); + ret = libsrt_getsockopt(h, fd, SRTO_PAYLOADSIZE, "SRTO_PAYLOADSIZE", &packet_size, &optlen); if (ret < 0) goto fail1; if (packet_size > 0) @@ -669,13 +581,10 @@ static int libsrt_open(URLContext *h, const char *uri) int ret = 0; if (srt_startup() < 0) { - blog(LOG_ERROR, - "[obs-ffmpeg mpegts muxer / libsrt]: libsrt failed to load"); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt failed to load"); return OBS_OUTPUT_CONNECT_FAILED; } else { - blog(LOG_INFO, - "[obs-ffmpeg mpegts muxer / libsrt]: libsrt version %s loaded", - SRT_VERSION_STRING); + blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: libsrt version %s loaded", SRT_VERSION_STRING); } libsrt_set_defaults(s); @@ -693,8 +602,7 @@ static int libsrt_open(URLContext *h, const char *uri) s->passphrase = av_strndup(buf, strlen(buf)); } #if SRT_VERSION_VALUE >= 0x010302 - if (av_find_info_tag(buf, sizeof(buf), "enforced_encryption", - p)) { + if (av_find_info_tag(buf, sizeof(buf), "enforced_encryption", p)) { s->enforced_encryption = strtol(buf, NULL, 10); } if (av_find_info_tag(buf, sizeof(buf), "kmrefreshrate", p)) { @@ -842,8 +750,7 @@ static int libsrt_write(URLContext *h, const uint8_t *buf, int size) int ret; SRT_TRACEBSTATS perf; - ret = libsrt_network_wait_fd_timeout(h, s->eid, 1, h->rw_timeout, - &h->interrupt_callback); + ret = libsrt_network_wait_fd_timeout(h, s->eid, 1, h->rw_timeout, &h->interrupt_callback); if (ret) return ret; @@ -858,18 +765,15 @@ static int libsrt_write(URLContext *h, const uint8_t *buf, int size) #ifdef _WIN32 struct timeb timebuffer; ftime(&timebuffer); - double time = (double)timebuffer.time + - 0.001 * (double)timebuffer.millitm; + double time = (double)timebuffer.time + 0.001 * (double)timebuffer.millitm; #else struct timespec timesp; clock_gettime(CLOCK_REALTIME, ×p); - double time = (double)timesp.tv_sec + - 0.000000001 * (double)timesp.tv_nsec; + double time = (double)timesp.tv_sec + 0.000000001 * (double)timesp.tv_nsec; #endif if (time > (s->time + 60.0)) { srt_bistats(s->fd, &perf, 0, 1); - blog(LOG_DEBUG, - "[obs-ffmpeg mpegts muxer / libsrt]: RTT [%.2f ms], Link Bandwidth [%.1f Mbps]", + blog(LOG_DEBUG, "[obs-ffmpeg mpegts muxer / libsrt]: RTT [%.2f ms], Link Bandwidth [%.1f Mbps]", perf.msRTT, perf.mbpsBandwidth); s->time = time; } @@ -898,26 +802,19 @@ static int libsrt_close(URLContext *h) "\ttotal bytes sent [%.1f MB]\n" "\tbytes retransmitted [%.1f %%]\n" "\tbytes dropped [%.1f %%]\n", - (double)perf.msTimeStamp / 1000.0, perf.mbpsSendRate, - (double)perf.byteSentTotal / 1000000.0, - perf.byteSentTotal - ? perf.byteRetransTotal / perf.byteSentTotal * 100.0 - : 0, - perf.byteSentTotal - ? perf.byteSndDropTotal / perf.byteSentTotal * 100.0 - : 0); + (double)perf.msTimeStamp / 1000.0, perf.mbpsSendRate, (double)perf.byteSentTotal / 1000000.0, + perf.byteSentTotal ? perf.byteRetransTotal / perf.byteSentTotal * 100.0 : 0, + perf.byteSentTotal ? perf.byteSndDropTotal / perf.byteSentTotal * 100.0 : 0); srt_epoll_release(s->eid); int err = srt_close(s->fd); if (err < 0) { - blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: %s", - srt_getlasterror_str()); + blog(LOG_ERROR, "[obs-ffmpeg mpegts muxer / libsrt]: %s", srt_getlasterror_str()); return -1; } srt_cleanup(); - blog(LOG_INFO, - "[obs-ffmpeg mpegts muxer / libsrt]: SRT connection closed"); + blog(LOG_INFO, "[obs-ffmpeg mpegts muxer / libsrt]: SRT connection closed"); return 0; } diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-url.h b/plugins/obs-ffmpeg/obs-ffmpeg-url.h index 32fc1f5ef..57e527b01 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-url.h +++ b/plugins/obs-ffmpeg/obs-ffmpeg-url.h @@ -109,8 +109,7 @@ typedef struct URLContext { #define SRT_LOGF_DISABLE_EOL 8 // Handler type -typedef void SRT_LOG_HANDLER_FN(void *opaque, int level, const char *file, - int line, const char *area, +typedef void SRT_LOG_HANDLER_FN(void *opaque, int level, const char *file, int line, const char *area, const char *message); #ifdef __cplusplus diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-vaapi.c b/plugins/obs-ffmpeg/obs-ffmpeg-vaapi.c index 96d08f29f..7777cdfe6 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-vaapi.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-vaapi.c @@ -48,9 +48,8 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[FFmpeg VAAPI encoder: '%s'] " format, \ - obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[FFmpeg VAAPI encoder: '%s'] " format, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -116,14 +115,12 @@ static const char *hevc_vaapi_getname(void *unused) } #endif -static inline bool vaapi_valid_format(struct vaapi_encoder *enc, - enum video_format format) +static inline bool vaapi_valid_format(struct vaapi_encoder *enc, enum video_format format) { if (enc->codec == CODEC_H264) { return format == VIDEO_FORMAT_NV12; } else if (enc->codec == CODEC_HEVC || enc->codec == CODEC_AV1) { - return (format == VIDEO_FORMAT_NV12) || - (format == VIDEO_FORMAT_P010); + return (format == VIDEO_FORMAT_NV12) || (format == VIDEO_FORMAT_P010); } else { return false; } @@ -137,9 +134,7 @@ static void vaapi_video_info(void *data, struct video_scale_info *info) pref_format = obs_encoder_get_preferred_video_format(enc->encoder); if (!vaapi_valid_format(enc, pref_format)) { - pref_format = vaapi_valid_format(enc, info->format) - ? info->format - : VIDEO_FORMAT_NV12; + pref_format = vaapi_valid_format(enc, info->format) ? info->format : VIDEO_FORMAT_NV12; } info->format = pref_format; @@ -149,16 +144,13 @@ static bool vaapi_init_codec(struct vaapi_encoder *enc, const char *path) { int ret; - ret = av_hwdevice_ctx_create(&enc->vadevice_ref, AV_HWDEVICE_TYPE_VAAPI, - path, NULL, 0); + ret = av_hwdevice_ctx_create(&enc->vadevice_ref, AV_HWDEVICE_TYPE_VAAPI, path, NULL, 0); if (ret < 0) { - warn("Failed to create VAAPI device context: %s", - av_err2str(ret)); + warn("Failed to create VAAPI device context: %s", av_err2str(ret)); return false; } - AVHWDeviceContext *vahwctx = - (AVHWDeviceContext *)enc->vadevice_ref->data; + AVHWDeviceContext *vahwctx = (AVHWDeviceContext *)enc->vadevice_ref->data; AVVAAPIDeviceContext *vadevctx = vahwctx->hwctx; enc->va_dpy = vadevctx->display; @@ -168,8 +160,7 @@ static bool vaapi_init_codec(struct vaapi_encoder *enc, const char *path) return false; } - AVHWFramesContext *frames_ctx = - (AVHWFramesContext *)enc->vaframes_ref->data; + AVHWFramesContext *frames_ctx = (AVHWFramesContext *)enc->vaframes_ref->data; frames_ctx->format = AV_PIX_FMT_VAAPI; frames_ctx->sw_format = enc->context->pix_fmt; frames_ctx->width = enc->context->width; @@ -230,11 +221,10 @@ typedef struct { static const rc_mode_t *get_rc_mode(const char *name) { /* Set "allowed" options per Rate Control */ - static const rc_mode_t RC_MODES[] = { - {.name = "CBR", .qp = false, .bitrate = true, .maxrate = false}, - {.name = "CQP", .qp = true, .bitrate = false, .maxrate = false}, - {.name = "VBR", .qp = false, .bitrate = true, .maxrate = true}, - {0}}; + static const rc_mode_t RC_MODES[] = {{.name = "CBR", .qp = false, .bitrate = true, .maxrate = false}, + {.name = "CQP", .qp = true, .bitrate = false, .maxrate = false}, + {.name = "VBR", .qp = false, .bitrate = true, .maxrate = true}, + {0}}; const rc_mode_t *rc_mode = RC_MODES; @@ -250,8 +240,7 @@ static bool vaapi_update(void *data, obs_data_t *settings) const char *device = obs_data_get_string(settings, "vaapi_device"); - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); const rc_mode_t *rc_mode = get_rc_mode(rate_control); bool cbr = strcmp(rc_mode->name, "CBR") == 0; @@ -262,12 +251,8 @@ static bool vaapi_update(void *data, obs_data_t *settings) enc->context->global_quality = enc->codec == CODEC_AV1 ? qp * 5 : qp; int level = (int)obs_data_get_int(settings, "level"); - int bitrate = rc_mode->bitrate - ? (int)obs_data_get_int(settings, "bitrate") - : 0; - int maxrate = rc_mode->maxrate - ? (int)obs_data_get_int(settings, "maxrate") - : 0; + int bitrate = rc_mode->bitrate ? (int)obs_data_get_int(settings, "bitrate") : 0; + int maxrate = rc_mode->maxrate ? (int)obs_data_get_int(settings, "maxrate") : 0; int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); /* For Rate Control which allows maxrate, FFMPEG will give @@ -290,8 +275,7 @@ static bool vaapi_update(void *data, obs_data_t *settings) #ifdef ENABLE_HEVC if (enc->codec == CODEC_HEVC) { - if ((profile == FF_PROFILE_HEVC_MAIN) && - (info.format == VIDEO_FORMAT_P010)) { + if ((profile == FF_PROFILE_HEVC_MAIN) && (info.format == VIDEO_FORMAT_P010)) { warn("Forcing Main10 for P010"); profile = FF_PROFILE_HEVC_MAIN_10; } @@ -304,19 +288,15 @@ static bool vaapi_update(void *data, obs_data_t *settings) enc->context->level = level; enc->context->bit_rate = bitrate * 1000; enc->context->rc_max_rate = maxrate * 1000; - enc->context->rc_initial_buffer_occupancy = - (maxrate ? maxrate : bitrate) * 1000; + enc->context->rc_initial_buffer_occupancy = (maxrate ? maxrate : bitrate) * 1000; enc->context->width = obs_encoder_get_width(enc->encoder); enc->context->height = obs_encoder_get_height(enc->encoder); enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num}; - const enum AVPixelFormat pix_fmt = - obs_to_ffmpeg_video_format(info.format); + const enum AVPixelFormat pix_fmt = obs_to_ffmpeg_video_format(info.format); enc->context->pix_fmt = pix_fmt; - enc->context->color_range = info.range == VIDEO_RANGE_FULL - ? AVCOL_RANGE_JPEG - : AVCOL_RANGE_MPEG; + enc->context->color_range = info.range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; enum AVColorSpace colorspace = AVCOL_SPC_UNSPECIFIED; switch (info.colorspace) { @@ -351,12 +331,10 @@ static bool vaapi_update(void *data, obs_data_t *settings) } enc->context->colorspace = colorspace; - enc->context->chroma_sample_location = - determine_chroma_location(pix_fmt, colorspace); + enc->context->chroma_sample_location = determine_chroma_location(pix_fmt, colorspace); if (keyint_sec > 0) { - enc->context->gop_size = - keyint_sec * voi->fps_num / voi->fps_den; + enc->context->gop_size = keyint_sec * voi->fps_num / voi->fps_den; } else { enc->context->gop_size = 120; } @@ -384,9 +362,8 @@ static bool vaapi_update(void *data, obs_data_t *settings) "\theight: %d\n" "\tb-frames: %d\n" "\tffmpeg opts: %s\n", - device, rate_control, profile, level, qp, bitrate, maxrate, - enc->context->gop_size, enc->context->width, enc->context->height, - enc->context->max_b_frames, ffmpeg_opts); + device, rate_control, profile, level, qp, bitrate, maxrate, enc->context->gop_size, enc->context->width, + enc->context->height, enc->context->max_b_frames, ffmpeg_opts); return vaapi_init_codec(enc, device); } @@ -420,8 +397,7 @@ static void vaapi_destroy_surface(struct vaapi_surface *out) av_frame_free(&out->frame); } -static bool vaapi_create_surface(struct vaapi_encoder *enc, - struct vaapi_surface *out) +static bool vaapi_create_surface(struct vaapi_encoder *enc, struct vaapi_surface *out) { int ret; VAStatus vas; @@ -449,11 +425,8 @@ static bool vaapi_create_surface(struct vaapi_encoder *enc, goto fail; } - vas = vaExportSurfaceHandle(enc->va_dpy, (uintptr_t)out->frame->data[3], - VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, - VA_EXPORT_SURFACE_WRITE_ONLY | - VA_EXPORT_SURFACE_SEPARATE_LAYERS, - &desc); + vas = vaExportSurfaceHandle(enc->va_dpy, (uintptr_t)out->frame->data[3], VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, + VA_EXPORT_SURFACE_WRITE_ONLY | VA_EXPORT_SURFACE_SEPARATE_LAYERS, &desc); if (vas != VA_STATUS_SUCCESS) { warn("Failed to export VA surface handle: %s", vaErrorStr(vas)); goto fail; @@ -468,12 +441,9 @@ static bool vaapi_create_surface(struct vaapi_encoder *enc, } out->textures[i] = gs_texture_create_from_dmabuf( - width, height, desc.layers[i].drm_format, - drm_to_gs_color_format(desc.layers[i].drm_format), 1, - &desc.objects[desc.layers[i].object_index[0]].fd, - &desc.layers[i].pitch[0], &desc.layers[i].offset[0], - &desc.objects[desc.layers[i].object_index[0]] - .drm_format_modifier); + width, height, desc.layers[i].drm_format, drm_to_gs_color_format(desc.layers[i].drm_format), 1, + &desc.objects[desc.layers[i].object_index[0]].fd, &desc.layers[i].pitch[0], + &desc.layers[i].offset[0], &desc.objects[desc.layers[i].object_index[0]].drm_format_modifier); if (!out->textures[i]) { warn("Failed to import VA surface texture"); @@ -539,8 +509,7 @@ static inline const char *vaapi_encoder_name(enum codec_type codec) return NULL; } -static void *vaapi_create_internal(obs_data_t *settings, obs_encoder_t *encoder, - enum codec_type codec) +static void *vaapi_create_internal(obs_data_t *settings, obs_encoder_t *encoder, enum codec_type codec) { struct vaapi_encoder *enc; @@ -579,8 +548,7 @@ static inline bool vaapi_test_texencode(struct vaapi_encoder *enc) { struct vaapi_surface surface; - if (obs_encoder_scaling_enabled(enc->encoder) && - !obs_encoder_gpu_scaling_enabled(enc->encoder)) + if (obs_encoder_scaling_enabled(enc->encoder) && !obs_encoder_gpu_scaling_enabled(enc->encoder)) return false; obs_enter_graphics(); @@ -590,9 +558,7 @@ static inline bool vaapi_test_texencode(struct vaapi_encoder *enc) return success; } -static void *vaapi_create_tex_internal(obs_data_t *settings, - obs_encoder_t *encoder, - enum codec_type codec, +static void *vaapi_create_tex_internal(obs_data_t *settings, obs_encoder_t *encoder, enum codec_type codec, const char *fallback) { void *enc = vaapi_create_internal(settings, encoder, codec); @@ -601,8 +567,7 @@ static void *vaapi_create_tex_internal(obs_data_t *settings, } if (!vaapi_test_texencode(enc)) { vaapi_destroy(enc); - blog(LOG_WARNING, "VAAPI: Falling back to %s encoder", - fallback); + blog(LOG_WARNING, "VAAPI: Falling back to %s encoder", fallback); return obs_encoder_create_rerouted(encoder, fallback); } return enc; @@ -615,8 +580,7 @@ static void *h264_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder) static void *h264_vaapi_create_tex(obs_data_t *settings, obs_encoder_t *encoder) { - return vaapi_create_tex_internal(settings, encoder, CODEC_H264, - "ffmpeg_vaapi"); + return vaapi_create_tex_internal(settings, encoder, CODEC_H264, "ffmpeg_vaapi"); } static void *av1_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder) @@ -626,8 +590,7 @@ static void *av1_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder) static void *av1_vaapi_create_tex(obs_data_t *settings, obs_encoder_t *encoder) { - return vaapi_create_tex_internal(settings, encoder, CODEC_AV1, - "av1_ffmpeg_vaapi"); + return vaapi_create_tex_internal(settings, encoder, CODEC_AV1, "av1_ffmpeg_vaapi"); } #ifdef ENABLE_HEVC @@ -638,39 +601,33 @@ static void *hevc_vaapi_create(obs_data_t *settings, obs_encoder_t *encoder) static void *hevc_vaapi_create_tex(obs_data_t *settings, obs_encoder_t *encoder) { - return vaapi_create_tex_internal(settings, encoder, CODEC_HEVC, - "hevc_ffmpeg_vaapi"); + return vaapi_create_tex_internal(settings, encoder, CODEC_HEVC, "hevc_ffmpeg_vaapi"); } #endif -static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame, - int height, enum AVPixelFormat format) +static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame, int height, enum AVPixelFormat format) { int h_chroma_shift, v_chroma_shift; - av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, - &v_chroma_shift); + av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, &v_chroma_shift); for (int plane = 0; plane < MAX_AV_PLANES; plane++) { if (!frame->data[plane]) continue; int frame_rowsize = (int)frame->linesize[plane]; int pic_rowsize = pic->linesize[plane]; - int bytes = frame_rowsize < pic_rowsize ? frame_rowsize - : pic_rowsize; + int bytes = frame_rowsize < pic_rowsize ? frame_rowsize : pic_rowsize; int plane_height = height >> (plane ? v_chroma_shift : 0); for (int y = 0; y < plane_height; y++) { int pos_frame = y * frame_rowsize; int pos_pic = y * pic_rowsize; - memcpy(pic->data[plane] + pos_pic, - frame->data[plane] + pos_frame, bytes); + memcpy(pic->data[plane] + pos_pic, frame->data[plane] + pos_frame, bytes); } } } -static bool vaapi_encode_internal(struct vaapi_encoder *enc, AVFrame *frame, - struct encoder_packet *packet, +static bool vaapi_encode_internal(struct vaapi_encoder *enc, AVFrame *frame, struct encoder_packet *packet, bool *received_packet) { int got_packet; @@ -700,38 +657,28 @@ static bool vaapi_encode_internal(struct vaapi_encoder *enc, AVFrame *frame, switch (enc->codec) { case CODEC_HEVC: #ifdef ENABLE_HEVC - obs_extract_hevc_headers( - enc->packet->data, enc->packet->size, - &new_packet, &size, &enc->header, - &enc->header_size, &enc->sei, - &enc->sei_size); + obs_extract_hevc_headers(enc->packet->data, enc->packet->size, &new_packet, &size, + &enc->header, &enc->header_size, &enc->sei, &enc->sei_size); break; #else warn("vaapi_encode: HEVC codec is not supported"); goto fail; #endif case CODEC_H264: - obs_extract_avc_headers( - enc->packet->data, enc->packet->size, - &new_packet, &size, &enc->header, - &enc->header_size, &enc->sei, - &enc->sei_size); + obs_extract_avc_headers(enc->packet->data, enc->packet->size, &new_packet, &size, + &enc->header, &enc->header_size, &enc->sei, &enc->sei_size); break; case CODEC_AV1: - obs_extract_av1_headers(enc->packet->data, - enc->packet->size, - &new_packet, &size, - &enc->header, - &enc->header_size); + obs_extract_av1_headers(enc->packet->data, enc->packet->size, &new_packet, &size, + &enc->header, &enc->header_size); break; } da_copy_array(enc->buffer, new_packet, size); bfree(new_packet); } else { - da_copy_array(enc->buffer, enc->packet->data, - enc->packet->size); + da_copy_array(enc->buffer, enc->packet->data, enc->packet->size); } packet->pts = enc->packet->pts; @@ -741,16 +688,13 @@ static bool vaapi_encode_internal(struct vaapi_encoder *enc, AVFrame *frame, packet->type = OBS_ENCODER_VIDEO; #ifdef ENABLE_HEVC if (enc->codec == CODEC_HEVC) { - packet->keyframe = - obs_hevc_keyframe(packet->data, packet->size); + packet->keyframe = obs_hevc_keyframe(packet->data, packet->size); } else #endif if (enc->codec == CODEC_H264) { - packet->keyframe = - obs_avc_keyframe(packet->data, packet->size); + packet->keyframe = obs_avc_keyframe(packet->data, packet->size); } else if (enc->codec == CODEC_AV1) { - packet->keyframe = - obs_av1_keyframe(packet->data, packet->size); + packet->keyframe = obs_av1_keyframe(packet->data, packet->size); } *received_packet = true; } @@ -763,8 +707,7 @@ fail: return false; } -static bool vaapi_encode_copy(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, +static bool vaapi_encode_copy(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct vaapi_encoder *enc = data; @@ -781,8 +724,7 @@ static bool vaapi_encode_copy(void *data, struct encoder_frame *frame, ret = av_hwframe_get_buffer(enc->vaframes_ref, hwframe, 0); if (ret < 0) { - warn("vaapi_encode_copy: failed to get buffer for hw frame: %s", - av_err2str(ret)); + warn("vaapi_encode_copy: failed to get buffer for hw frame: %s", av_err2str(ret)); goto fail; } @@ -795,15 +737,13 @@ static bool vaapi_encode_copy(void *data, struct encoder_frame *frame, ret = av_hwframe_transfer_data(hwframe, enc->vframe, 0); if (ret < 0) { - warn("vaapi_encode_copy: failed to upload hw frame: %s", - av_err2str(ret)); + warn("vaapi_encode_copy: failed to upload hw frame: %s", av_err2str(ret)); goto fail; } ret = av_frame_copy_props(hwframe, enc->vframe); if (ret < 0) { - warn("vaapi_encode_copy: failed to copy props to hw frame: %s", - av_err2str(ret)); + warn("vaapi_encode_copy: failed to copy props to hw frame: %s", av_err2str(ret)); goto fail; } @@ -818,10 +758,8 @@ fail: return false; } -static bool vaapi_encode_tex(void *data, struct encoder_texture *texture, - int64_t pts, uint64_t lock_key, uint64_t *next_key, - struct encoder_packet *packet, - bool *received_packet) +static bool vaapi_encode_tex(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key, + uint64_t *next_key, struct encoder_packet *packet, bool *received_packet) { UNUSED_PARAMETER(lock_key); UNUSED_PARAMETER(next_key); @@ -859,8 +797,7 @@ static bool vaapi_encode_tex(void *data, struct encoder_texture *texture, ret = av_frame_copy_props(surface.frame, enc->vframe); if (ret < 0) { - warn("vaapi_encode_tex: failed to copy props to hw frame: %s", - av_err2str(ret)); + warn("vaapi_encode_tex: failed to copy props to hw frame: %s", av_err2str(ret)); goto fail; } @@ -915,16 +852,13 @@ static void vaapi_defaults_internal(obs_data_t *settings, enum codec_type codec) obs_data_set_default_string(settings, "vaapi_device", device); #ifdef ENABLE_HEVC if (codec == CODEC_HEVC) - obs_data_set_default_int(settings, "profile", - FF_PROFILE_HEVC_MAIN); + obs_data_set_default_int(settings, "profile", FF_PROFILE_HEVC_MAIN); else #endif if (codec == CODEC_H264) - obs_data_set_default_int(settings, "profile", - FF_PROFILE_H264_HIGH); + obs_data_set_default_int(settings, "profile", FF_PROFILE_H264_HIGH); else if (codec == CODEC_AV1) - obs_data_set_default_int(settings, "profile", - FF_PROFILE_AV1_MAIN); + obs_data_set_default_int(settings, "profile", FF_PROFILE_AV1_MAIN); obs_data_set_default_int(settings, "level", FF_LEVEL_UNKNOWN); obs_data_set_default_int(settings, "bitrate", 2500); obs_data_set_default_int(settings, "keyint_sec", 0); @@ -963,15 +897,13 @@ static void hevc_vaapi_defaults(obs_data_t *settings) vaapi_defaults_internal(settings, CODEC_HEVC); } -static bool vaapi_device_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool vaapi_device_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); const char *device = obs_data_get_string(settings, "vaapi_device"); int drm_fd = -1; - VADisplay va_dpy = - vaapi_open_device(&drm_fd, device, "vaapi_device_modified"); + VADisplay va_dpy = vaapi_open_device(&drm_fd, device, "vaapi_device_modified"); int profile = obs_data_get_int(settings, "profile"); obs_property_t *rc_p = obs_properties_get(ppts, "rate_control"); @@ -1031,13 +963,11 @@ fail: return true; } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); const rc_mode_t *rc_mode = get_rc_mode(rate_control); @@ -1049,8 +979,7 @@ static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, return true; } -static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot, - char *buf, int size) +static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot, char *buf, int size) { struct pci_filter filter; struct pci_dev *dev; @@ -1064,9 +993,7 @@ static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot, for (dev = pacc->devices; dev; dev = dev->next) { if (pci_filter_match(&filter, dev)) { pci_fill_info(dev, PCI_FILL_IDENT); - name = pci_lookup_name(pacc, buf, size, - PCI_LOOKUP_DEVICE, - dev->vendor_id, dev->device_id); + name = pci_lookup_name(pacc, buf, size, PCI_LOOKUP_DEVICE, dev->vendor_id, dev->device_id); strcpy(buf, name); return true; } @@ -1074,8 +1001,7 @@ static bool get_device_name_from_pci(struct pci_access *pacc, char *pci_slot, return false; } -static bool vaapi_device_codec_supported(const char *path, - enum codec_type codec) +static bool vaapi_device_codec_supported(const char *path, enum codec_type codec) { switch (codec) { case CODEC_H264: @@ -1094,9 +1020,7 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) obs_properties_t *props = obs_properties_create(); obs_property_t *list; - list = obs_properties_add_list(props, "vaapi_device", - obs_module_text("VAAPI.Device"), - OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, "vaapi_device", obs_module_text("VAAPI.Device"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); if (os_file_exists("/dev/dri/by-path")) { os_dir_t *by_path_dir = os_opendir("/dev/dri/by-path"); @@ -1110,19 +1034,16 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) while ((file = os_readdir(by_path_dir)) != NULL) { // file_name pattern: pci-- char *file_name = file->d_name; - if (strcmp(file_name, ".") == 0 || - strcmp(file_name, "..") == 0) + if (strcmp(file_name, ".") == 0 || strcmp(file_name, "..") == 0) continue; char path[64] = {0}; // Use the return value of snprintf to prevent truncation warning. - int written = snprintf(path, 64, "/dev/dri/by-path/%s", - file_name); + int written = snprintf(path, 64, "/dev/dri/by-path/%s", file_name); if (written >= 64) - blog(LOG_DEBUG, - "obs-ffmpeg-vaapi: A format truncation may have occurred." - " This can be ignored since it is quite improbable."); + blog(LOG_DEBUG, "obs-ffmpeg-vaapi: A format truncation may have occurred." + " This can be ignored since it is quite improbable."); type = strrchr(file_name, '-'); if (type == NULL) @@ -1133,19 +1054,15 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) if (strcmp(type, "render") == 0) { strncpy(pci_slot, file_name + 4, 12); pci_slot[12] = 0; - bool name_found = get_device_name_from_pci( - pacc, pci_slot, namebuf, - sizeof(namebuf)); + bool name_found = get_device_name_from_pci(pacc, pci_slot, namebuf, sizeof(namebuf)); if (!vaapi_device_codec_supported(path, codec)) continue; if (!name_found) - obs_property_list_add_string(list, path, - path); + obs_property_list_add_string(list, path, path); else - obs_property_list_add_string( - list, namebuf, path); + obs_property_list_add_string(list, namebuf, path); } } pci_cleanup(pacc); @@ -1157,12 +1074,10 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) snprintf(path, sizeof(path), "/dev/dri/renderD1%d", i); if (access(path, F_OK) == 0) { char card[128]; - int ret = snprintf(card, sizeof(card), - "Card%d: %s", i - 28, path); + int ret = snprintf(card, sizeof(card), "Card%d: %s", i - 28, path); if (ret >= (int)sizeof(card)) - blog(LOG_DEBUG, - "obs-ffmpeg-vaapi: A format truncation may have occurred." - " This can be ignored since it is quite improbable."); + blog(LOG_DEBUG, "obs-ffmpeg-vaapi: A format truncation may have occurred." + " This can be ignored since it is quite improbable."); if (!vaapi_device_h264_supported(path)) continue; @@ -1176,17 +1091,13 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) obs_property_set_modified_callback(list, vaapi_device_modified); - list = obs_properties_add_list(props, "profile", - obs_module_text("Profile"), - OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); if (codec == CODEC_HEVC) { obs_property_list_add_int(list, "Main", FF_PROFILE_HEVC_MAIN); - obs_property_list_add_int(list, "Main10", - FF_PROFILE_HEVC_MAIN_10); + obs_property_list_add_int(list, "Main10", FF_PROFILE_HEVC_MAIN_10); } else if (codec == CODEC_H264) { - obs_property_list_add_int(list, "Constrained Baseline", - FF_PROFILE_H264_CONSTRAINED_BASELINE); + obs_property_list_add_int(list, "Constrained Baseline", FF_PROFILE_H264_CONSTRAINED_BASELINE); obs_property_list_add_int(list, "Main", FF_PROFILE_H264_MAIN); obs_property_list_add_int(list, "High", FF_PROFILE_H264_HIGH); } else if (codec == CODEC_AV1) { @@ -1195,8 +1106,7 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) obs_property_set_modified_callback(list, vaapi_device_modified); - list = obs_properties_add_list(props, "level", obs_module_text("Level"), - OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, "level", obs_module_text("Level"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(list, "Auto", FF_LEVEL_UNKNOWN); if (codec == CODEC_H264) { @@ -1227,35 +1137,26 @@ static obs_properties_t *vaapi_properties_internal(enum codec_type codec) obs_property_list_add_int(list, "5.3", 15); } - list = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(list, rate_control_modified); obs_property_t *p; - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 0, 300000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 0, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); - p = obs_properties_add_int( - props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50); + p = obs_properties_add_int(props, "maxrate", obs_module_text("MaxBitrate"), 0, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); obs_properties_add_int(props, "qp", "QP", 0, 51, 1); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 20, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 20, 1); obs_property_int_set_suffix(p, " s"); - obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, - 1); + obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, 1); - obs_properties_add_text(props, "ffmpeg_opts", - obs_module_text("FFmpegOpts"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "ffmpeg_opts", obs_module_text("FFmpegOpts"), OBS_TEXT_DEFAULT); return props; } diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.c b/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.c index 872818cef..90cddb8ce 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.c @@ -1,8 +1,7 @@ #include "obs-ffmpeg-video-encoders.h" -#define do_log(level, format, ...) \ - blog(level, "[%s encoder: '%s'] " format, enc->enc_name, \ - obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[%s encoder: '%s'] " format, enc->enc_name, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -20,16 +19,12 @@ bool ffmpeg_video_encoder_init_codec(struct ffmpeg_video_encoder *enc) } else { struct dstr error_message = {0}; - dstr_copy(&error_message, - obs_module_text("Encoder.Error")); - dstr_replace(&error_message, "%1", - enc->enc_name); - dstr_replace(&error_message, "%2", - av_err2str(ret)); + dstr_copy(&error_message, obs_module_text("Encoder.Error")); + dstr_replace(&error_message, "%1", enc->enc_name); + dstr_replace(&error_message, "%2", av_err2str(ret)); dstr_cat(&error_message, "

"); - obs_encoder_set_last_error(enc->encoder, - error_message.array); + obs_encoder_set_last_error(enc->encoder, error_message.array); dstr_free(&error_message); } } @@ -61,15 +56,12 @@ bool ffmpeg_video_encoder_init_codec(struct ffmpeg_video_encoder *enc) return true; } -void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, - int keyint_sec, - const struct video_output_info *voi, - const struct video_scale_info *info, +void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, int keyint_sec, + const struct video_output_info *voi, const struct video_scale_info *info, const char *ffmpeg_opts) { const int rate = bitrate * 1000; - const enum AVPixelFormat pix_fmt = - obs_to_ffmpeg_video_format(info->format); + const enum AVPixelFormat pix_fmt = obs_to_ffmpeg_video_format(info->format); enc->context->bit_rate = rate; enc->context->rc_buffer_size = rate; enc->context->width = obs_encoder_get_width(enc->encoder); @@ -77,9 +69,7 @@ void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, enc->context->time_base = (AVRational){voi->fps_den, voi->fps_num}; enc->context->framerate = (AVRational){voi->fps_num, voi->fps_den}; enc->context->pix_fmt = pix_fmt; - enc->context->color_range = info->range == VIDEO_RANGE_FULL - ? AVCOL_RANGE_JPEG - : AVCOL_RANGE_MPEG; + enc->context->color_range = info->range == VIDEO_RANGE_FULL ? AVCOL_RANGE_JPEG : AVCOL_RANGE_MPEG; enum AVColorSpace colorspace = AVCOL_SPC_UNSPECIFIED; switch (info->colorspace) { @@ -111,12 +101,10 @@ void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, } enc->context->colorspace = colorspace; - enc->context->chroma_sample_location = - determine_chroma_location(pix_fmt, colorspace); + enc->context->chroma_sample_location = determine_chroma_location(pix_fmt, colorspace); if (keyint_sec) - enc->context->gop_size = - keyint_sec * voi->fps_num / voi->fps_den; + enc->context->gop_size = keyint_sec * voi->fps_num / voi->fps_den; enc->height = enc->context->height; @@ -152,11 +140,9 @@ void ffmpeg_video_encoder_free(struct ffmpeg_video_encoder *enc) da_free(enc->buffer); } -bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, - obs_encoder_t *encoder, const char *enc_lib, - const char *enc_lib2, const char *enc_name, - init_error_cb on_init_error, - first_packet_cb on_first_packet) +bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, obs_encoder_t *encoder, + const char *enc_lib, const char *enc_lib2, const char *enc_name, + init_error_cb on_init_error, first_packet_cb on_first_packet) { enc->encoder = encoder; enc->parent = parent; @@ -172,8 +158,7 @@ bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, if (!enc->avcodec) { struct dstr error_message; - dstr_printf(&error_message, "Couldn't find encoder: %s", - enc_lib); + dstr_printf(&error_message, "Couldn't find encoder: %s", enc_lib); obs_encoder_set_last_error(encoder, error_message.array); dstr_free(&error_message); @@ -190,28 +175,24 @@ bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, return true; } -static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame, - int height, enum AVPixelFormat format) +static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame, int height, enum AVPixelFormat format) { int h_chroma_shift, v_chroma_shift; - av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, - &v_chroma_shift); + av_pix_fmt_get_chroma_sub_sample(format, &h_chroma_shift, &v_chroma_shift); for (int plane = 0; plane < MAX_AV_PLANES; plane++) { if (!frame->data[plane]) continue; int frame_rowsize = (int)frame->linesize[plane]; int pic_rowsize = pic->linesize[plane]; - int bytes = frame_rowsize < pic_rowsize ? frame_rowsize - : pic_rowsize; + int bytes = frame_rowsize < pic_rowsize ? frame_rowsize : pic_rowsize; int plane_height = height >> (plane ? v_chroma_shift : 0); for (int y = 0; y < plane_height; y++) { int pos_frame = y * frame_rowsize; int pos_pic = y * pic_rowsize; - memcpy(pic->data[plane] + pos_pic, - frame->data[plane] + pos_frame, bytes); + memcpy(pic->data[plane] + pos_pic, frame->data[plane] + pos_frame, bytes); } } } @@ -220,15 +201,13 @@ static inline void copy_data(AVFrame *pic, const struct encoder_frame *frame, #define TIMEOUT_MAX_SEC 5 #define TIMEOUT_MAX_NSEC (TIMEOUT_MAX_SEC * SEC_TO_NSEC) -bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, - struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, struct encoder_frame *frame, struct encoder_packet *packet, + bool *received_packet) { AVPacket av_pkt = {0}; bool timeout = false; const int64_t cur_ts = (int64_t)os_gettime_ns(); - const int64_t pause_offset = - (int64_t)obs_encoder_get_pause_offset(enc->encoder); + const int64_t pause_offset = (int64_t)obs_encoder_get_pause_offset(enc->encoder); int got_packet; int ret; @@ -253,8 +232,7 @@ bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, if (got_packet && av_pkt.size) { if (enc->on_first_packet && enc->first_packet) { - enc->on_first_packet(enc->parent, &av_pkt, - &enc->buffer.da); + enc->on_first_packet(enc->parent, &av_pkt, &enc->buffer.da); enc->first_packet = false; } else { da_copy_array(enc->buffer, av_pkt.data, av_pkt.size); @@ -268,11 +246,9 @@ bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, packet->keyframe = !!(av_pkt.flags & AV_PKT_FLAG_KEY); *received_packet = true; - const int64_t recv_ts_nsec = - (int64_t)util_mul_div64( - (uint64_t)av_pkt.pts, (uint64_t)SEC_TO_NSEC, - (uint64_t)enc->context->time_base.den) + - enc->start_ts; + const int64_t recv_ts_nsec = (int64_t)util_mul_div64((uint64_t)av_pkt.pts, (uint64_t)SEC_TO_NSEC, + (uint64_t)enc->context->time_base.den) + + enc->start_ts; #if 0 debug("cur: %lld, packet: %lld, diff: %lld", cur_ts, @@ -280,16 +256,13 @@ bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, #endif if ((cur_ts - recv_ts_nsec - pause_offset) > TIMEOUT_MAX_NSEC) { char timeout_str[16]; - snprintf(timeout_str, sizeof(timeout_str), "%d", - TIMEOUT_MAX_SEC); + snprintf(timeout_str, sizeof(timeout_str), "%d", TIMEOUT_MAX_SEC); struct dstr error_text = {0}; - dstr_copy(&error_text, - obs_module_text("Encoder.Timeout")); + dstr_copy(&error_text, obs_module_text("Encoder.Timeout")); dstr_replace(&error_text, "%1", enc->enc_name); dstr_replace(&error_text, "%2", timeout_str); - obs_encoder_set_last_error(enc->encoder, - error_text.array); + obs_encoder_set_last_error(enc->encoder, error_text.array); dstr_free(&error_text); error("Encoding queue duration surpassed %d " diff --git a/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.h b/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.h index db2f21bdd..7d9d90b4c 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.h +++ b/plugins/obs-ffmpeg/obs-ffmpeg-video-encoders.h @@ -38,20 +38,13 @@ struct ffmpeg_video_encoder { first_packet_cb on_first_packet; }; -extern bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, - void *parent, obs_encoder_t *encoder, - const char *enc_lib, const char *enc_lib2, - const char *enc_name, - init_error_cb on_init_error, - first_packet_cb on_first_packet); +extern bool ffmpeg_video_encoder_init(struct ffmpeg_video_encoder *enc, void *parent, obs_encoder_t *encoder, + const char *enc_lib, const char *enc_lib2, const char *enc_name, + init_error_cb on_init_error, first_packet_cb on_first_packet); extern void ffmpeg_video_encoder_free(struct ffmpeg_video_encoder *enc); extern bool ffmpeg_video_encoder_init_codec(struct ffmpeg_video_encoder *enc); -extern void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, - int bitrate, int keyint_sec, - const struct video_output_info *voi, - const struct video_scale_info *info, +extern void ffmpeg_video_encoder_update(struct ffmpeg_video_encoder *enc, int bitrate, int keyint_sec, + const struct video_output_info *voi, const struct video_scale_info *info, const char *ffmpeg_opts); -extern bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, - struct encoder_frame *frame, - struct encoder_packet *packet, - bool *received_packet); +extern bool ffmpeg_video_encode(struct ffmpeg_video_encoder *enc, struct encoder_frame *frame, + struct encoder_packet *packet, bool *received_packet); diff --git a/plugins/obs-ffmpeg/obs-ffmpeg.c b/plugins/obs-ffmpeg/obs-ffmpeg.c index 83651e95d..df631a672 100644 --- a/plugins/obs-ffmpeg/obs-ffmpeg.c +++ b/plugins/obs-ffmpeg/obs-ffmpeg.c @@ -108,8 +108,7 @@ static const int blacklisted_adapters[] = { 0x137a, // GM108GLM [Quadro K620M / Quadro M500M] }; -static const size_t num_blacklisted = - sizeof(blacklisted_adapters) / sizeof(blacklisted_adapters[0]); +static const size_t num_blacklisted = sizeof(blacklisted_adapters) / sizeof(blacklisted_adapters[0]); static bool is_blacklisted(const int device_id) { @@ -147,8 +146,7 @@ static bool nvenc_device_available(void) } if (!create) { - create = (create_dxgi_proc)GetProcAddress(dxgi, - "CreateDXGIFactory1"); + create = (create_dxgi_proc)GetProcAddress(dxgi, "CreateDXGIFactory1"); if (!create) { return true; } @@ -189,8 +187,7 @@ static int get_id_from_sys(char *d_name, char *type) char *c; int id; - snprintf(file_name, sizeof(file_name), "/sys/bus/pci/devices/%s/%s", - d_name, type); + snprintf(file_name, sizeof(file_name), "/sys/bus/pci/devices/%s/%s", d_name, type); if ((c = os_quick_read_utf8_file(file_name)) == NULL) { return -1; } @@ -214,19 +211,16 @@ static bool nvenc_device_available(void) int id; if (get_id_from_sys(dirent->d_name, "class") != 0x030000 && - get_id_from_sys(dirent->d_name, "class") != - 0x030200) { // 0x030000 = VGA compatible controller - // 0x030200 = 3D controller + get_id_from_sys(dirent->d_name, "class") != 0x030200) { // 0x030000 = VGA compatible controller + // 0x030200 = 3D controller continue; } - if (get_id_from_sys(dirent->d_name, "vendor") != - 0x10de) { // 0x10de = NVIDIA Corporation + if (get_id_from_sys(dirent->d_name, "vendor") != 0x10de) { // 0x10de = NVIDIA Corporation continue; } - if ((id = get_id_from_sys(dirent->d_name, "device")) > 0 && - !is_blacklisted(id)) { + if ((id = get_id_from_sys(dirent->d_name, "device")) > 0 && !is_blacklisted(id)) { available = true; break; } @@ -338,8 +332,7 @@ extern void obs_ffmpeg_load_logging(void); extern void obs_ffmpeg_unload_logging(void); #endif -static void register_encoder_if_available(struct obs_encoder_info *info, - const char *id) +static void register_encoder_if_available(struct obs_encoder_info *info, const char *id) { const AVCodec *c = avcodec_find_encoder_by_name(id); if (c) { @@ -386,9 +379,8 @@ bool obs_module_load(void) #ifdef LIBAVUTIL_VAAPI_AVAILABLE const char *libva_env = getenv("LIBVA_DRIVER_NAME"); if (!!libva_env) - blog(LOG_WARNING, - "LIBVA_DRIVER_NAME variable is set," - " this could prevent FFmpeg VAAPI from working correctly"); + blog(LOG_WARNING, "LIBVA_DRIVER_NAME variable is set," + " this could prevent FFmpeg VAAPI from working correctly"); if (h264_vaapi_supported()) { blog(LOG_INFO, "FFmpeg VAAPI H264 encoding supported"); diff --git a/plugins/obs-ffmpeg/texture-amf-opts.hpp b/plugins/obs-ffmpeg/texture-amf-opts.hpp index b1c37d200..c052bd78b 100644 --- a/plugins/obs-ffmpeg/texture-amf-opts.hpp +++ b/plugins/obs-ffmpeg/texture-amf-opts.hpp @@ -39,8 +39,7 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) else if (hevc) set_hevc_enum(USAGE, ULTRA_LOW_LATENCY); else - warn("Invalid value for %s: %s", opt->name, - opt->value); + warn("Invalid value for %s: %s", opt->name, opt->value); } else if (strcmp(opt->value, "lowlatency") == 0) { set_enum_opt(USAGE, LOW_LATENCY); } else if (strcmp(opt->value, "webcam") == 0) { @@ -49,8 +48,7 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) else if (hevc) set_hevc_enum(USAGE, WEBCAM); else - warn("Invalid value for %s: %s", opt->name, - opt->value); + warn("Invalid value for %s: %s", opt->name, opt->value); } else { warn("Invalid value for %s: %s", opt->name, opt->value); } @@ -67,11 +65,9 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) if (strcmp(opt->value, "high") == 0) { set_opt(PROFILE, AMF_VIDEO_ENCODER_PROFILE_HIGH); } else if (strcmp(opt->value, "constrained_baseline") == 0) { - set_opt(PROFILE, - AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE); + set_opt(PROFILE, AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE); } else if (strcmp(opt->value, "constrained_high") == 0) { - set_opt(PROFILE, - AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH); + set_opt(PROFILE, AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH); } else { warn("Invalid value for %s: %s", opt->name, opt->value); } @@ -112,8 +108,7 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) } else if (strcmp(opt->value, "vbr_peak") == 0) { set_enum_opt(RATE_CONTROL_METHOD, PEAK_CONSTRAINED_VBR); } else if (strcmp(opt->value, "vbr_latency") == 0) { - set_enum_opt(RATE_CONTROL_METHOD, - LATENCY_CONSTRAINED_VBR); + set_enum_opt(RATE_CONTROL_METHOD, LATENCY_CONSTRAINED_VBR); } else { warn("Invalid value for %s: %s", opt->name, opt->value); } diff --git a/plugins/obs-ffmpeg/texture-amf.cpp b/plugins/obs-ffmpeg/texture-amf.cpp index 763382345..efe2d154f 100644 --- a/plugins/obs-ffmpeg/texture-amf.cpp +++ b/plugins/obs-ffmpeg/texture-amf.cpp @@ -35,9 +35,8 @@ using namespace amf; /* ========================================================================= */ /* Junk */ -#define do_log(level, format, ...) \ - blog(level, "[%s: '%s'] " format, enc->encoder_str, \ - obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[%s: '%s'] " format, enc->encoder_str, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -48,9 +47,7 @@ struct amf_error { const char *str; AMF_RESULT res; - inline amf_error(const char *str, AMF_RESULT res) : str(str), res(res) - { - } + inline amf_error(const char *str, AMF_RESULT res) : str(str), res(res) {} }; struct handle_tex { @@ -199,54 +196,40 @@ struct amf_fallback : amf_base, public AMFSurfaceObserver { /* ------------------------------------------------------------------------- */ /* More garbage */ -template -static bool get_amf_property(amf_base *enc, const wchar_t *name, T *value) +template static bool get_amf_property(amf_base *enc, const wchar_t *name, T *value) { AMF_RESULT res = enc->amf_encoder->GetProperty(name, value); return res == AMF_OK; } -template -static void set_amf_property(amf_base *enc, const wchar_t *name, const T &value) +template static void set_amf_property(amf_base *enc, const wchar_t *name, const T &value) { AMF_RESULT res = enc->amf_encoder->SetProperty(name, value); if (res != AMF_OK) - error("Failed to set property '%ls': %ls", name, - amf_trace->GetResultText(res)); + error("Failed to set property '%ls': %ls", name, amf_trace->GetResultText(res)); } -#define set_avc_property(enc, name, value) \ - set_amf_property(enc, AMF_VIDEO_ENCODER_##name, value) -#define set_hevc_property(enc, name, value) \ - set_amf_property(enc, AMF_VIDEO_ENCODER_HEVC_##name, value) -#define set_av1_property(enc, name, value) \ - set_amf_property(enc, AMF_VIDEO_ENCODER_AV1_##name, value) +#define set_avc_property(enc, name, value) set_amf_property(enc, AMF_VIDEO_ENCODER_##name, value) +#define set_hevc_property(enc, name, value) set_amf_property(enc, AMF_VIDEO_ENCODER_HEVC_##name, value) +#define set_av1_property(enc, name, value) set_amf_property(enc, AMF_VIDEO_ENCODER_AV1_##name, value) -#define get_avc_property(enc, name, value) \ - get_amf_property(enc, AMF_VIDEO_ENCODER_##name, value) -#define get_hevc_property(enc, name, value) \ - get_amf_property(enc, AMF_VIDEO_ENCODER_HEVC_##name, value) -#define get_av1_property(enc, name, value) \ - get_amf_property(enc, AMF_VIDEO_ENCODER_AV1_##name, value) +#define get_avc_property(enc, name, value) get_amf_property(enc, AMF_VIDEO_ENCODER_##name, value) +#define get_hevc_property(enc, name, value) get_amf_property(enc, AMF_VIDEO_ENCODER_HEVC_##name, value) +#define get_av1_property(enc, name, value) get_amf_property(enc, AMF_VIDEO_ENCODER_AV1_##name, value) -#define get_opt_name(name) \ - ((enc->codec == amf_codec_type::AVC) ? AMF_VIDEO_ENCODER_##name \ - : (enc->codec == amf_codec_type::HEVC) \ - ? AMF_VIDEO_ENCODER_HEVC_##name \ - : AMF_VIDEO_ENCODER_AV1_##name) +#define get_opt_name(name) \ + ((enc->codec == amf_codec_type::AVC) ? AMF_VIDEO_ENCODER_##name \ + : (enc->codec == amf_codec_type::HEVC) ? AMF_VIDEO_ENCODER_HEVC_##name \ + : AMF_VIDEO_ENCODER_AV1_##name) #define set_opt(name, value) set_amf_property(enc, get_opt_name(name), value) #define get_opt(name, value) get_amf_property(enc, get_opt_name(name), value) #define set_avc_opt(name, value) set_avc_property(enc, name, value) #define set_hevc_opt(name, value) set_hevc_property(enc, name, value) #define set_av1_opt(name, value) set_av1_property(enc, name, value) -#define set_enum_opt(name, value) \ - set_amf_property(enc, get_opt_name(name), get_opt_name(name##_##value)) -#define set_avc_enum(name, value) \ - set_avc_property(enc, name, AMF_VIDEO_ENCODER_##name##_##value) -#define set_hevc_enum(name, value) \ - set_hevc_property(enc, name, AMF_VIDEO_ENCODER_HEVC_##name##_##value) -#define set_av1_enum(name, value) \ - set_av1_property(enc, name, AMF_VIDEO_ENCODER_AV1_##name##_##value) +#define set_enum_opt(name, value) set_amf_property(enc, get_opt_name(name), get_opt_name(name##_##value)) +#define set_avc_enum(name, value) set_avc_property(enc, name, AMF_VIDEO_ENCODER_##name##_##value) +#define set_hevc_enum(name, value) set_hevc_property(enc, name, AMF_VIDEO_ENCODER_HEVC_##name##_##value) +#define set_av1_enum(name, value) set_av1_property(enc, name, AMF_VIDEO_ENCODER_AV1_##name##_##value) /* ------------------------------------------------------------------------- */ /* Implementation */ @@ -281,10 +264,8 @@ try { throw "Couldn't get D3D11/DXGI libraries? " "That definitely shouldn't be possible."; - create_dxgi = (CREATEDXGIFACTORY1PROC)GetProcAddress( - dxgi, "CreateDXGIFactory1"); - create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress( - d3d11, "D3D11CreateDevice"); + create_dxgi = (CREATEDXGIFACTORY1PROC)GetProcAddress(dxgi, "CreateDXGIFactory1"); + create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(d3d11, "D3D11CreateDevice"); if (!create_dxgi || !create_device) throw "Failed to load D3D11/DXGI procedures"; @@ -305,9 +286,8 @@ try { throw "Seems somehow AMF is trying to initialize " "on a non-AMD adapter"; - hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, - nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, - &context); + hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &device, + nullptr, &context); if (FAILED(hr)) throw HRError("D3D11CreateDevice failed", hr); @@ -324,9 +304,7 @@ try { return false; } -static void add_output_tex(amf_texencode *enc, - ComPtr &output_tex, - ID3D11Texture2D *from) +static void add_output_tex(amf_texencode *enc, ComPtr &output_tex, ID3D11Texture2D *from) { ID3D11Device *device = enc->device; HRESULT hr; @@ -341,8 +319,7 @@ static void add_output_tex(amf_texencode *enc, throw HRError("Failed to create texture", hr); } -static inline bool get_available_tex(amf_texencode *enc, - ComPtr &output_tex) +static inline bool get_available_tex(amf_texencode *enc, ComPtr &output_tex) { std::scoped_lock lock(enc->textures_mutex); if (enc->available_textures.size()) { @@ -354,16 +331,13 @@ static inline bool get_available_tex(amf_texencode *enc, return false; } -static inline void get_output_tex(amf_texencode *enc, - ComPtr &output_tex, - ID3D11Texture2D *from) +static inline void get_output_tex(amf_texencode *enc, ComPtr &output_tex, ID3D11Texture2D *from) { if (!get_available_tex(enc, output_tex)) add_output_tex(enc, output_tex, from); } -static void get_tex_from_handle(amf_texencode *enc, uint32_t handle, - IDXGIKeyedMutex **km_out, +static void get_tex_from_handle(amf_texencode *enc, uint32_t handle, IDXGIKeyedMutex **km_out, ID3D11Texture2D **tex_out) { ID3D11Device *device = enc->device; @@ -379,9 +353,7 @@ static void get_tex_from_handle(amf_texencode *enc, uint32_t handle, } } - hr = device->OpenSharedResource((HANDLE)(uintptr_t)handle, - __uuidof(ID3D11Resource), - (void **)&tex); + hr = device->OpenSharedResource((HANDLE)(uintptr_t)handle, __uuidof(ID3D11Resource), (void **)&tex); if (FAILED(hr)) throw HRError("OpenSharedResource failed", hr); @@ -402,14 +374,11 @@ static constexpr amf_int64 macroblock_size = 16; static inline void calc_throughput(amf_base *enc) { - amf_int64 mb_cx = - ((amf_int64)enc->cx + (macroblock_size - 1)) / macroblock_size; - amf_int64 mb_cy = - ((amf_int64)enc->cy + (macroblock_size - 1)) / macroblock_size; + amf_int64 mb_cx = ((amf_int64)enc->cx + (macroblock_size - 1)) / macroblock_size; + amf_int64 mb_cy = ((amf_int64)enc->cy + (macroblock_size - 1)) / macroblock_size; amf_int64 mb_frame = mb_cx * mb_cy; - enc->throughput = - mb_frame * (amf_int64)enc->fps_num / (amf_int64)enc->fps_den; + enc->throughput = mb_frame * (amf_int64)enc->fps_num / (amf_int64)enc->fps_den; } static inline int get_avc_preset(amf_base *enc, const char *preset); @@ -442,15 +411,12 @@ static inline void refresh_throughput_caps(amf_base *enc, const char *&preset) set_opt(QUALITY_PRESET, get_preset(enc, preset)); res = enc->amf_encoder->GetCaps(&caps); if (res == AMF_OK) { - caps->GetProperty(get_opt_name(CAP_MAX_THROUGHPUT), - &enc->max_throughput); - caps->GetProperty(get_opt_name(CAP_REQUESTED_THROUGHPUT), - &enc->requested_throughput); + caps->GetProperty(get_opt_name(CAP_MAX_THROUGHPUT), &enc->max_throughput); + caps->GetProperty(get_opt_name(CAP_REQUESTED_THROUGHPUT), &enc->requested_throughput); } } -static inline void check_preset_compatibility(amf_base *enc, - const char *&preset) +static inline void check_preset_compatibility(amf_base *enc, const char *&preset) { /* The throughput depends on the current preset and the other static * encoder properties. If the throughput is lower than the max @@ -461,8 +427,7 @@ static inline void check_preset_compatibility(amf_base *enc, preset = "quality"; set_opt(QUALITY_PRESET, get_preset(enc, preset)); } else { - if (enc->max_throughput - enc->requested_throughput < - enc->throughput) { + if (enc->max_throughput - enc->requested_throughput < enc->throughput) { preset = "quality"; refresh_throughput_caps(enc, preset); } @@ -474,8 +439,7 @@ static inline void check_preset_compatibility(amf_base *enc, preset = "balanced"; set_opt(QUALITY_PRESET, get_preset(enc, preset)); } else { - if (enc->max_throughput - enc->requested_throughput < - enc->throughput) { + if (enc->max_throughput - enc->requested_throughput < enc->throughput) { preset = "balanced"; refresh_throughput_caps(enc, preset); } @@ -483,9 +447,7 @@ static inline void check_preset_compatibility(amf_base *enc, } if (astrcmpi(preset, "balanced") == 0) { - if (enc->max_throughput && - enc->max_throughput - enc->requested_throughput < - enc->throughput) { + if (enc->max_throughput && enc->max_throughput - enc->requested_throughput < enc->throughput) { preset = "speed"; refresh_throughput_caps(enc, preset); } @@ -504,8 +466,7 @@ static inline int64_t convert_to_obs_ts(amf_base *enc, int64_t ts) return ts * (int64_t)enc->fps_den / amf_timebase; } -static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data, - encoder_packet *packet) +static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data, encoder_packet *packet) { if (!data) return; @@ -533,8 +494,7 @@ static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data, "data type", res); - if (enc->codec == amf_codec_type::AVC || - enc->codec == amf_codec_type::HEVC) { + if (enc->codec == amf_codec_type::AVC || enc->codec == amf_codec_type::HEVC) { switch (type) { case AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR: packet->priority = OBS_NAL_PRIORITY_HIGHEST; @@ -615,8 +575,7 @@ static void roi_cb(void *param, obs_encoder_roi *roi) if (mb_x < roi_left || mb_x > roi_right) continue; - rp->buf[mb_y * rp->pitch / sizeof(amf_uint32) + mb_x] = - priority; + rp->buf[mb_y * rp->pitch / sizeof(amf_uint32) + mb_x] = priority; } } } @@ -624,8 +583,7 @@ static void roi_cb(void *param, obs_encoder_roi *roi) static void create_roi(amf_base *enc, AMFSurface *amf_surf) { uint32_t mb_size = 16; /* H.264 is always 16x16 */ - if (enc->codec == amf_codec_type::HEVC || - enc->codec == amf_codec_type::AV1) + if (enc->codec == amf_codec_type::HEVC || enc->codec == amf_codec_type::AV1) mb_size = 64; /* AMF HEVC & AV1 use 64x64 blocks */ const uint32_t mb_width = (enc->cx + mb_size - 1) / mb_size; @@ -633,11 +591,9 @@ static void create_roi(amf_base *enc, AMFSurface *amf_surf) if (!enc->roi_map) { AMFContext1Ptr context1(enc->amf_context); - AMF_RESULT res = context1->AllocSurfaceEx( - AMF_MEMORY_HOST, AMF_SURFACE_GRAY32, mb_width, - mb_height, - AMF_SURFACE_USAGE_DEFAULT | AMF_SURFACE_USAGE_LINEAR, - AMF_MEMORY_CPU_DEFAULT, &enc->roi_map); + AMF_RESULT res = context1->AllocSurfaceEx(AMF_MEMORY_HOST, AMF_SURFACE_GRAY32, mb_width, mb_height, + AMF_SURFACE_USAGE_DEFAULT | AMF_SURFACE_USAGE_LINEAR, + AMF_MEMORY_CPU_DEFAULT, &enc->roi_map); if (res != AMF_OK) { warn("Failed allocating surface for ROI map!"); @@ -648,13 +604,11 @@ static void create_roi(amf_base *enc, AMFSurface *amf_surf) } /* This is just following the SimpleROI example. */ - amf_uint32 *pBuf = - (amf_uint32 *)enc->roi_map->GetPlaneAt(0)->GetNative(); + amf_uint32 *pBuf = (amf_uint32 *)enc->roi_map->GetPlaneAt(0)->GetNative(); amf_int32 pitch = enc->roi_map->GetPlaneAt(0)->GetHPitch(); memset(pBuf, 0, pitch * mb_height); - roi_params par{mb_width, mb_height, pitch, - enc->codec == amf_codec_type::AVC, pBuf}; + roi_params par{mb_width, mb_height, pitch, enc->codec == amf_codec_type::AVC, pBuf}; obs_encoder_enum_roi(enc->encoder, roi_cb, &par); enc->roi_increment = obs_encoder_get_roi_increment(enc->encoder); @@ -670,15 +624,12 @@ static void add_roi(amf_base *enc, AMFSurface *amf_surf) if (enc->codec == amf_codec_type::AVC) amf_surf->SetProperty(AMF_VIDEO_ENCODER_ROI_DATA, enc->roi_map); else if (enc->codec == amf_codec_type::HEVC) - amf_surf->SetProperty(AMF_VIDEO_ENCODER_HEVC_ROI_DATA, - enc->roi_map); + amf_surf->SetProperty(AMF_VIDEO_ENCODER_HEVC_ROI_DATA, enc->roi_map); else if (enc->codec == amf_codec_type::AV1) - amf_surf->SetProperty(AMF_VIDEO_ENCODER_AV1_ROI_DATA, - enc->roi_map); + amf_surf->SetProperty(AMF_VIDEO_ENCODER_AV1_ROI_DATA, enc->roi_map); } -static void amf_encode_base(amf_base *enc, AMFSurface *amf_surf, - encoder_packet *packet, bool *received_packet) +static void amf_encode_base(amf_base *enc, AMFSurface *amf_surf, encoder_packet *packet, bool *received_packet) { auto &queued_packets = enc->queued_packets; uint64_t ts_start = os_gettime_ns(); @@ -743,8 +694,7 @@ static void amf_encode_base(amf_base *enc, AMFSurface *amf_surf, } } -static bool amf_encode_tex(void *data, uint32_t handle, int64_t pts, - uint64_t lock_key, uint64_t *next_key, +static bool amf_encode_tex(void *data, uint32_t handle, int64_t pts, uint64_t lock_key, uint64_t *next_key, encoder_packet *packet, bool *received_packet) try { amf_texencode *enc = (amf_texencode *)data; @@ -774,16 +724,14 @@ try { /* copy to output tex */ km->AcquireSync(lock_key, INFINITE); - context->CopyResource((ID3D11Resource *)output_tex.Get(), - (ID3D11Resource *)input_tex.Get()); + context->CopyResource((ID3D11Resource *)output_tex.Get(), (ID3D11Resource *)input_tex.Get()); context->Flush(); km->ReleaseSync(*next_key); /* ------------------------------------ */ /* map output tex to amf surface */ - res = enc->amf_context->CreateSurfaceFromDX11Native(output_tex, - &amf_surf, enc); + res = enc->amf_context->CreateSurfaceFromDX11Native(output_tex, &amf_surf, enc); if (res != AMF_OK) throw amf_error("CreateSurfaceFromDX11Native failed", res); @@ -811,8 +759,7 @@ try { } catch (const amf_error &err) { amf_texencode *enc = (amf_texencode *)data; - error("%s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + error("%s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); *received_packet = false; return false; @@ -857,13 +804,11 @@ static buf_t get_buf(amf_fallback *enc) return buf; } -static inline void copy_frame_data(amf_fallback *enc, buf_t &buf, - struct encoder_frame *frame) +static inline void copy_frame_data(amf_fallback *enc, buf_t &buf, struct encoder_frame *frame) { uint8_t *dst = &buf[0]; - if (enc->amf_format == AMF_SURFACE_NV12 || - enc->amf_format == AMF_SURFACE_P010) { + if (enc->amf_format == AMF_SURFACE_NV12 || enc->amf_format == AMF_SURFACE_P010) { size_t size = enc->linesize * enc->cy; memcpy(&buf[0], frame->data[0], size); memcpy(&buf[size], frame->data[1], size / 2); @@ -873,8 +818,7 @@ static inline void copy_frame_data(amf_fallback *enc, buf_t &buf, } } -static bool amf_encode_fallback(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, +static bool amf_encode_fallback(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) try { amf_fallback *enc = (amf_fallback *)data; @@ -889,9 +833,8 @@ try { copy_frame_data(enc, buf, frame); - res = enc->amf_context->CreateSurfaceFromHostNative( - enc->amf_format, enc->cx, enc->cy, enc->linesize, 0, &buf[0], - &amf_surf, enc); + res = enc->amf_context->CreateSurfaceFromHostNative(enc->amf_format, enc->cx, enc->cy, enc->linesize, 0, + &buf[0], &amf_surf, enc); if (res != AMF_OK) throw amf_error("CreateSurfaceFromHostNative failed", res); @@ -914,8 +857,7 @@ try { } catch (const amf_error &err) { amf_fallback *enc = (amf_fallback *)data; - error("%s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + error("%s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); *received_packet = false; return false; } catch (const char *err) { @@ -1016,50 +958,35 @@ try { switch (info.colorspace) { case VIDEO_CS_601: - enc->amf_color_profile = - enc->full_range - ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_601 - : AMF_VIDEO_CONVERTER_COLOR_PROFILE_601; + enc->amf_color_profile = enc->full_range ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_601 + : AMF_VIDEO_CONVERTER_COLOR_PROFILE_601; enc->amf_primaries = AMF_COLOR_PRIMARIES_SMPTE170M; - enc->amf_characteristic = - AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE170M; + enc->amf_characteristic = AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE170M; break; case VIDEO_CS_DEFAULT: case VIDEO_CS_709: - enc->amf_color_profile = - enc->full_range - ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_709 - : AMF_VIDEO_CONVERTER_COLOR_PROFILE_709; + enc->amf_color_profile = enc->full_range ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_709 + : AMF_VIDEO_CONVERTER_COLOR_PROFILE_709; enc->amf_primaries = AMF_COLOR_PRIMARIES_BT709; - enc->amf_characteristic = - AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709; + enc->amf_characteristic = AMF_COLOR_TRANSFER_CHARACTERISTIC_BT709; break; case VIDEO_CS_SRGB: - enc->amf_color_profile = - enc->full_range - ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_709 - : AMF_VIDEO_CONVERTER_COLOR_PROFILE_709; + enc->amf_color_profile = enc->full_range ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_709 + : AMF_VIDEO_CONVERTER_COLOR_PROFILE_709; enc->amf_primaries = AMF_COLOR_PRIMARIES_BT709; - enc->amf_characteristic = - AMF_COLOR_TRANSFER_CHARACTERISTIC_IEC61966_2_1; + enc->amf_characteristic = AMF_COLOR_TRANSFER_CHARACTERISTIC_IEC61966_2_1; break; case VIDEO_CS_2100_HLG: - enc->amf_color_profile = - enc->full_range - ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_2020 - : AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020; + enc->amf_color_profile = enc->full_range ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_2020 + : AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020; enc->amf_primaries = AMF_COLOR_PRIMARIES_BT2020; - enc->amf_characteristic = - AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67; + enc->amf_characteristic = AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67; break; case VIDEO_CS_2100_PQ: - enc->amf_color_profile = - enc->full_range - ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_2020 - : AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020; + enc->amf_color_profile = enc->full_range ? AMF_VIDEO_CONVERTER_COLOR_PROFILE_FULL_2020 + : AMF_VIDEO_CONVERTER_COLOR_PROFILE_2020; enc->amf_primaries = AMF_COLOR_PRIMARIES_BT2020; - enc->amf_characteristic = - AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084; + enc->amf_characteristic = AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084; break; } @@ -1098,8 +1025,7 @@ try { default: codec = AMFVideoEncoder_HEVC; } - res = amf_factory->CreateComponent(enc->amf_context, codec, - &enc->amf_encoder); + res = amf_factory->CreateComponent(enc->amf_context, codec, &enc->amf_encoder); if (res != AMF_OK) throw amf_error("CreateComponent failed", res); @@ -1107,8 +1033,7 @@ try { return true; } catch (const amf_error &err) { - error("%s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + error("%s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return false; } @@ -1118,8 +1043,7 @@ static void amf_destroy(void *data) delete enc; } -static void check_texture_encode_capability(obs_encoder_t *encoder, - amf_codec_type codec) +static void check_texture_encode_capability(obs_encoder_t *encoder, amf_codec_type codec) { obs_video_info ovi; obs_get_video_info(&ovi); @@ -1127,8 +1051,7 @@ static void check_texture_encode_capability(obs_encoder_t *encoder, bool hevc = amf_codec_type::HEVC == codec; bool av1 = amf_codec_type::AV1 == codec; - if (obs_encoder_scaling_enabled(encoder) && - !obs_encoder_gpu_scaling_enabled(encoder)) + if (obs_encoder_scaling_enabled(encoder) && !obs_encoder_gpu_scaling_enabled(encoder)) throw "Encoder scaling is active"; if (hevc || av1) { @@ -1152,8 +1075,7 @@ static void check_texture_encode_capability(obs_encoder_t *encoder, } } - if ((avc && !caps[ovi.adapter].supports_avc) || - (hevc && !caps[ovi.adapter].supports_hevc) || + if ((avc && !caps[ovi.adapter].supports_avc) || (hevc && !caps[ovi.adapter].supports_hevc) || (av1 && !caps[ovi.adapter].supports_av1)) throw "Wrong adapter"; } @@ -1170,8 +1092,7 @@ static void amf_defaults(obs_data_t *settings) obs_data_set_default_int(settings, "bf", 3); } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *rc = obs_data_get_string(settings, "rate_control"); bool cqp = astrcmpi(rc, "CQP") == 0; @@ -1189,9 +1110,7 @@ static obs_properties_t *amf_properties_internal(amf_codec_type codec) obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, "CBR", "CBR"); obs_property_list_add_string(p, "CQP", "CQP"); @@ -1203,24 +1122,19 @@ static obs_properties_t *amf_properties_internal(amf_codec_type codec) obs_property_set_modified_callback(p, rate_control_modified); - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 50, 100000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 100000, 50); obs_property_int_set_suffix(p, " Kbps"); - obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), - 0, codec == amf_codec_type::AV1 ? 63 : 51, 1); + obs_properties_add_int(props, "cqp", obs_module_text("NVENC.CQLevel"), 0, + codec == amf_codec_type::AV1 ? 63 : 51, 1); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 10, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1); obs_property_int_set_suffix(p, " s"); - p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_preset(val) \ - obs_property_list_add_string(p, obs_module_text("AMF.Preset." val), val) +#define add_preset(val) obs_property_list_add_string(p, obs_module_text("AMF.Preset." val), val) if (amf_codec_type::AV1 == codec) { add_preset("highQuality"); } @@ -1230,9 +1144,7 @@ static obs_properties_t *amf_properties_internal(amf_codec_type codec) #undef add_preset if (amf_codec_type::AVC == codec || amf_codec_type::AV1 == codec) { - p = obs_properties_add_list(props, "profile", - obs_module_text("Profile"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); #define add_profile(val) obs_property_list_add_string(p, val, val) @@ -1245,15 +1157,11 @@ static obs_properties_t *amf_properties_internal(amf_codec_type codec) } if (amf_codec_type::AVC == codec) { - obs_properties_add_int(props, "bf", obs_module_text("BFrames"), - 0, 5, 1); + obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 5, 1); } - p = obs_properties_add_text(props, "ffmpeg_opts", - obs_module_text("AMFOpts"), - OBS_TEXT_DEFAULT); - obs_property_set_long_description(p, - obs_module_text("AMFOpts.ToolTip")); + p = obs_properties_add_text(props, "ffmpeg_opts", obs_module_text("AMFOpts"), OBS_TEXT_DEFAULT); + obs_property_set_long_description(p, obs_module_text("AMFOpts.ToolTip")); return props; } @@ -1330,8 +1238,7 @@ static inline int get_avc_profile(obs_data_t *settings) return AMF_VIDEO_ENCODER_PROFILE_HIGH; } -static void amf_avc_update_data(amf_base *enc, int rc, int64_t bitrate, - int64_t qp) +static void amf_avc_update_data(amf_base *enc, int rc, int64_t bitrate, int64_t qp) { if (rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP && rc != AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_QUALITY_VBR) { @@ -1379,8 +1286,7 @@ try { } catch (const amf_error &err) { amf_base *enc = (amf_base *)data; - error("%s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + error("%s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return false; } @@ -1426,8 +1332,7 @@ static bool amf_avc_init(void *data, obs_data_t *settings) set_avc_property(enc, HIGH_MOTION_QUALITY_BOOST_ENABLE, false); int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); - int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den - : 250; + int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den : 250; set_avc_property(enc, IDR_PERIOD, gop_size); @@ -1462,8 +1367,7 @@ static bool amf_avc_init(void *data, obs_data_t *settings) "\twidth: %d\n" "\theight: %d\n" "\tparams: %s", - rc_str, bitrate, qp, gop_size, preset, profile, bf, enc->cx, - enc->cy, ffmpeg_opts); + rc_str, bitrate, qp, gop_size, preset, profile, bf, enc->cx, enc->cy, ffmpeg_opts); return true; } @@ -1481,14 +1385,10 @@ static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings) AMFCapsPtr caps; res = enc->amf_encoder->GetCaps(&caps); if (res == AMF_OK) { - caps->GetProperty(AMF_VIDEO_ENCODER_CAP_BFRAMES, - &enc->bframes_supported); - caps->GetProperty(AMF_VIDEO_ENCODER_CAP_MAX_THROUGHPUT, - &enc->max_throughput); - caps->GetProperty(AMF_VIDEO_ENCODER_CAP_REQUESTED_THROUGHPUT, - &enc->requested_throughput); - caps->GetProperty(AMF_VIDEO_ENCODER_CAP_ROI, - &enc->roi_supported); + caps->GetProperty(AMF_VIDEO_ENCODER_CAP_BFRAMES, &enc->bframes_supported); + caps->GetProperty(AMF_VIDEO_ENCODER_CAP_MAX_THROUGHPUT, &enc->max_throughput); + caps->GetProperty(AMF_VIDEO_ENCODER_CAP_REQUESTED_THROUGHPUT, &enc->requested_throughput); + caps->GetProperty(AMF_VIDEO_ENCODER_CAP_ROI, &enc->roi_supported); } const char *preset = obs_data_get_string(settings, "preset"); @@ -1501,8 +1401,7 @@ static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings) set_avc_property(enc, CABAC_ENABLE, AMF_VIDEO_ENCODER_UNDEFINED); set_avc_property(enc, PREENCODE_ENABLE, true); set_avc_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile); - set_avc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC, - enc->amf_characteristic); + set_avc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC, enc->amf_characteristic); set_avc_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries); set_avc_property(enc, FULL_RANGE_COLOR, enc->full_range); set_avc_property(enc, FRAMERATE, enc->amf_frame_rate); @@ -1529,8 +1428,7 @@ static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings) } } -static void *amf_avc_create_texencode(obs_data_t *settings, - obs_encoder_t *encoder) +static void *amf_avc_create_texencode(obs_data_t *settings, obs_encoder_t *encoder) try { check_texture_encode_capability(encoder, amf_codec_type::AVC); @@ -1545,8 +1443,7 @@ try { return enc.release(); } catch (const amf_error &err) { - blog(LOG_ERROR, "[texture-amf-h264] %s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + blog(LOG_ERROR, "[texture-amf-h264] %s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return obs_encoder_create_rerouted(encoder, "h264_fallback_amf"); } catch (const char *err) { @@ -1554,8 +1451,7 @@ try { return obs_encoder_create_rerouted(encoder, "h264_fallback_amf"); } -static void *amf_avc_create_fallback(obs_data_t *settings, - obs_encoder_t *encoder) +static void *amf_avc_create_fallback(obs_data_t *settings, obs_encoder_t *encoder) try { std::unique_ptr enc = std::make_unique(); enc->encoder = encoder; @@ -1566,15 +1462,13 @@ try { switch (voi->format) { case VIDEO_FORMAT_I010: case VIDEO_FORMAT_P010: { - const char *const text = - obs_module_text("AMF.10bitUnsupportedAvc"); + const char *const text = obs_module_text("AMF.10bitUnsupportedAvc"); obs_encoder_set_last_error(encoder, text); throw text; } case VIDEO_FORMAT_P216: case VIDEO_FORMAT_P416: { - const char *const text = - obs_module_text("AMF.16bitUnsupported"); + const char *const text = obs_module_text("AMF.16bitUnsupported"); obs_encoder_set_last_error(encoder, text); throw text; } @@ -1582,8 +1476,7 @@ try { switch (voi->colorspace) { case VIDEO_CS_2100_PQ: case VIDEO_CS_2100_HLG: { - const char *const text = - obs_module_text("AMF.8bitUnsupportedHdr"); + const char *const text = obs_module_text("AMF.8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); throw text; } @@ -1594,8 +1487,7 @@ try { return enc.release(); } catch (const amf_error &err) { - blog(LOG_ERROR, "[fallback-amf-h264] %s: %s: %ls", __FUNCTION__, - err.str, amf_trace->GetResultText(err.res)); + blog(LOG_ERROR, "[fallback-amf-h264] %s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return nullptr; } catch (const char *err) { @@ -1617,16 +1509,12 @@ static void register_avc() amf_encoder_info.get_defaults = amf_defaults; amf_encoder_info.get_properties = amf_avc_properties; amf_encoder_info.get_extra_data = amf_extra_data; - amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI; + amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI; obs_register_encoder(&amf_encoder_info); amf_encoder_info.id = "h264_fallback_amf"; - amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI; + amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI; amf_encoder_info.encode_texture = nullptr; amf_encoder_info.create = amf_avc_create_fallback; amf_encoder_info.encode = amf_encode_fallback; @@ -1675,8 +1563,7 @@ static inline int get_hevc_rate_control(const char *rc_str) return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR; } -static void amf_hevc_update_data(amf_base *enc, int rc, int64_t bitrate, - int64_t qp) +static void amf_hevc_update_data(amf_base *enc, int rc, int64_t bitrate, int64_t qp) { if (rc != AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP && rc != AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_QUALITY_VBR) { @@ -1723,8 +1610,7 @@ try { } catch (const amf_error &err) { amf_base *enc = (amf_base *)data; - error("%s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + error("%s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return false; } @@ -1749,8 +1635,7 @@ static bool amf_hevc_init(void *data, obs_data_t *settings) set_hevc_property(enc, HIGH_MOTION_QUALITY_BOOST_ENABLE, false); int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); - int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den - : 250; + int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den : 250; set_hevc_property(enc, GOP_SIZE, gop_size); @@ -1778,22 +1663,19 @@ static bool amf_hevc_init(void *data, obs_data_t *settings) "\twidth: %d\n" "\theight: %d\n" "\tparams: %s", - rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy, - ffmpeg_opts); + rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy, ffmpeg_opts); return true; } static inline bool is_hlg(amf_base *enc) { - return enc->amf_characteristic == - AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67; + return enc->amf_characteristic == AMF_COLOR_TRANSFER_CHARACTERISTIC_ARIB_STD_B67; } static inline bool is_pq(amf_base *enc) { - return enc->amf_characteristic == - AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084; + return enc->amf_characteristic == AMF_COLOR_TRANSFER_CHARACTERISTIC_SMPTE2084; } constexpr amf_uint16 amf_hdr_primary(uint32_t num, uint32_t den) @@ -1821,13 +1703,9 @@ static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings) AMFCapsPtr caps; res = enc->amf_encoder->GetCaps(&caps); if (res == AMF_OK) { - caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_MAX_THROUGHPUT, - &enc->max_throughput); - caps->GetProperty( - AMF_VIDEO_ENCODER_HEVC_CAP_REQUESTED_THROUGHPUT, - &enc->requested_throughput); - caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_ROI, - &enc->roi_supported); + caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_MAX_THROUGHPUT, &enc->max_throughput); + caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_REQUESTED_THROUGHPUT, &enc->requested_throughput); + caps->GetProperty(AMF_VIDEO_ENCODER_HEVC_CAP_ROI, &enc->roi_supported); } const bool is10bit = enc->amf_format == AMF_SURFACE_P010; @@ -1839,28 +1717,21 @@ static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings) set_hevc_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy)); set_hevc_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING); set_hevc_property(enc, QUALITY_PRESET, get_hevc_preset(enc, preset)); - set_hevc_property(enc, COLOR_BIT_DEPTH, - is10bit ? AMF_COLOR_BIT_DEPTH_10 - : AMF_COLOR_BIT_DEPTH_8); + set_hevc_property(enc, COLOR_BIT_DEPTH, is10bit ? AMF_COLOR_BIT_DEPTH_10 : AMF_COLOR_BIT_DEPTH_8); set_hevc_property(enc, PROFILE, - is10bit ? AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN_10 - : AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN); + is10bit ? AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN_10 : AMF_VIDEO_ENCODER_HEVC_PROFILE_MAIN); set_hevc_property(enc, LOWLATENCY_MODE, false); set_hevc_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile); - set_hevc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC, - enc->amf_characteristic); + set_hevc_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC, enc->amf_characteristic); set_hevc_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries); set_hevc_property(enc, NOMINAL_RANGE, enc->full_range); set_hevc_property(enc, FRAMERATE, enc->amf_frame_rate); if (is_hdr) { - const int hdr_nominal_peak_level = - pq ? (int)obs_get_video_hdr_nominal_peak_level() - : (hlg ? 1000 : 0); + const int hdr_nominal_peak_level = pq ? (int)obs_get_video_hdr_nominal_peak_level() : (hlg ? 1000 : 0); AMFBufferPtr buf; - enc->amf_context->AllocBuffer(AMF_MEMORY_HOST, - sizeof(AMFHDRMetadata), &buf); + enc->amf_context->AllocBuffer(AMF_MEMORY_HOST, sizeof(AMFHDRMetadata), &buf); AMFHDRMetadata *md = (AMFHDRMetadata *)buf->GetNative(); md->redPrimary[0] = amf_hdr_primary(17, 25); md->redPrimary[1] = amf_hdr_primary(8, 25); @@ -1871,8 +1742,7 @@ static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings) md->whitePoint[0] = amf_hdr_primary(3127, 10000); md->whitePoint[1] = amf_hdr_primary(329, 1000); md->minMasteringLuminance = 0; - md->maxMasteringLuminance = - amf_make_lum(hdr_nominal_peak_level); + md->maxMasteringLuminance = amf_make_lum(hdr_nominal_peak_level); md->maxContentLightLevel = hdr_nominal_peak_level; md->maxFrameAverageLightLevel = hdr_nominal_peak_level; set_hevc_property(enc, INPUT_HDR_METADATA, buf); @@ -1884,14 +1754,12 @@ static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings) if (res != AMF_OK) throw amf_error("AMFComponent::Init failed", res); - res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_HEVC_EXTRADATA, - &p); + res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_HEVC_EXTRADATA, &p); if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) enc->header = AMFBufferPtr(p.pInterface); } -static void *amf_hevc_create_texencode(obs_data_t *settings, - obs_encoder_t *encoder) +static void *amf_hevc_create_texencode(obs_data_t *settings, obs_encoder_t *encoder) try { check_texture_encode_capability(encoder, amf_codec_type::HEVC); @@ -1906,8 +1774,7 @@ try { return enc.release(); } catch (const amf_error &err) { - blog(LOG_ERROR, "[texture-amf-h265] %s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + blog(LOG_ERROR, "[texture-amf-h265] %s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return obs_encoder_create_rerouted(encoder, "h265_fallback_amf"); } catch (const char *err) { @@ -1915,8 +1782,7 @@ try { return obs_encoder_create_rerouted(encoder, "h265_fallback_amf"); } -static void *amf_hevc_create_fallback(obs_data_t *settings, - obs_encoder_t *encoder) +static void *amf_hevc_create_fallback(obs_data_t *settings, obs_encoder_t *encoder) try { std::unique_ptr enc = std::make_unique(); enc->encoder = encoder; @@ -1930,8 +1796,7 @@ try { break; case VIDEO_FORMAT_P216: case VIDEO_FORMAT_P416: { - const char *const text = - obs_module_text("AMF.16bitUnsupported"); + const char *const text = obs_module_text("AMF.16bitUnsupported"); obs_encoder_set_last_error(encoder, text); throw text; } @@ -1939,8 +1804,7 @@ try { switch (voi->colorspace) { case VIDEO_CS_2100_PQ: case VIDEO_CS_2100_HLG: { - const char *const text = - obs_module_text("AMF.8bitUnsupportedHdr"); + const char *const text = obs_module_text("AMF.8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); throw text; } @@ -1951,8 +1815,7 @@ try { return enc.release(); } catch (const amf_error &err) { - blog(LOG_ERROR, "[fallback-amf-h265] %s: %s: %ls", __FUNCTION__, - err.str, amf_trace->GetResultText(err.res)); + blog(LOG_ERROR, "[fallback-amf-h265] %s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return nullptr; } catch (const char *err) { @@ -1974,16 +1837,12 @@ static void register_hevc() amf_encoder_info.get_defaults = amf_defaults; amf_encoder_info.get_properties = amf_hevc_properties; amf_encoder_info.get_extra_data = amf_extra_data; - amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI; + amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI; obs_register_encoder(&amf_encoder_info); amf_encoder_info.id = "h265_fallback_amf"; - amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI; + amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI; amf_encoder_info.encode_texture = nullptr; amf_encoder_info.create = amf_hevc_create_fallback; amf_encoder_info.encode = amf_encode_fallback; @@ -2046,8 +1905,7 @@ static inline int get_av1_profile(obs_data_t *settings) return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN; } -static void amf_av1_update_data(amf_base *enc, int rc, int64_t bitrate, - int64_t cq_value) +static void amf_av1_update_data(amf_base *enc, int rc, int64_t bitrate, int64_t cq_value) { if (rc != AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP && rc != AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_QUALITY_VBR) { @@ -2057,9 +1915,8 @@ static void amf_av1_update_data(amf_base *enc, int rc, int64_t bitrate, if (rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR) { set_av1_property(enc, FILLER_DATA, true); - } else if ( - rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR || - rc == AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR) { + } else if (rc == AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR || + rc == AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR) { set_av1_property(enc, PEAK_BITRATE, bitrate * 1.5); } } else { @@ -2099,8 +1956,7 @@ try { } catch (const amf_error &err) { amf_base *enc = (amf_base *)data; - error("%s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + error("%s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return false; } @@ -2122,8 +1978,7 @@ static bool amf_av1_init(void *data, obs_data_t *settings) set_av1_property(enc, ENFORCE_HRD, true); int keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); - int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den - : 250; + int gop_size = (keyint_sec) ? keyint_sec * enc->fps_num / enc->fps_den : 250; set_av1_property(enc, GOP_SIZE, gop_size); const char *ffmpeg_opts = obs_data_get_string(settings, "ffmpeg_opts"); @@ -2150,8 +2005,7 @@ static bool amf_av1_init(void *data, obs_data_t *settings) "\twidth: %d\n" "\theight: %d\n" "\tparams: %s", - rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy, - ffmpeg_opts); + rc_str, bitrate, qp, gop_size, preset, profile, enc->cx, enc->cy, ffmpeg_opts); return true; } @@ -2166,11 +2020,8 @@ static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings) AMFCapsPtr caps; AMF_RESULT res = enc->amf_encoder->GetCaps(&caps); if (res == AMF_OK) { - caps->GetProperty(AMF_VIDEO_ENCODER_AV1_CAP_MAX_THROUGHPUT, - &enc->max_throughput); - caps->GetProperty( - AMF_VIDEO_ENCODER_AV1_CAP_REQUESTED_THROUGHPUT, - &enc->requested_throughput); + caps->GetProperty(AMF_VIDEO_ENCODER_AV1_CAP_MAX_THROUGHPUT, &enc->max_throughput); + caps->GetProperty(AMF_VIDEO_ENCODER_AV1_CAP_REQUESTED_THROUGHPUT, &enc->requested_throughput); /* For some reason there's no specific CAP for AV1, but should always be supported */ enc->roi_supported = true; } @@ -2180,19 +2031,14 @@ static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings) set_av1_property(enc, FRAMESIZE, AMFConstructSize(enc->cx, enc->cy)); set_av1_property(enc, USAGE, AMF_VIDEO_ENCODER_USAGE_TRANSCODING); - set_av1_property(enc, ALIGNMENT_MODE, - AMF_VIDEO_ENCODER_AV1_ALIGNMENT_MODE_NO_RESTRICTIONS); + set_av1_property(enc, ALIGNMENT_MODE, AMF_VIDEO_ENCODER_AV1_ALIGNMENT_MODE_NO_RESTRICTIONS); set_av1_property(enc, QUALITY_PRESET, get_av1_preset(enc, preset)); - set_av1_property(enc, COLOR_BIT_DEPTH, - is10bit ? AMF_COLOR_BIT_DEPTH_10 - : AMF_COLOR_BIT_DEPTH_8); + set_av1_property(enc, COLOR_BIT_DEPTH, is10bit ? AMF_COLOR_BIT_DEPTH_10 : AMF_COLOR_BIT_DEPTH_8); set_av1_property(enc, PROFILE, get_av1_profile(settings)); - set_av1_property(enc, ENCODING_LATENCY_MODE, - AMF_VIDEO_ENCODER_AV1_ENCODING_LATENCY_MODE_NONE); + set_av1_property(enc, ENCODING_LATENCY_MODE, AMF_VIDEO_ENCODER_AV1_ENCODING_LATENCY_MODE_NONE); // set_av1_property(enc, RATE_CONTROL_PREENCODE, true); set_av1_property(enc, OUTPUT_COLOR_PROFILE, enc->amf_color_profile); - set_av1_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC, - enc->amf_characteristic); + set_av1_property(enc, OUTPUT_TRANSFER_CHARACTERISTIC, enc->amf_characteristic); set_av1_property(enc, OUTPUT_COLOR_PRIMARIES, enc->amf_primaries); set_av1_property(enc, FRAMERATE, enc->amf_frame_rate); @@ -2203,14 +2049,12 @@ static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings) throw amf_error("AMFComponent::Init failed", res); AMFVariant p; - res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_AV1_EXTRA_DATA, - &p); + res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_AV1_EXTRA_DATA, &p); if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) enc->header = AMFBufferPtr(p.pInterface); } -static void *amf_av1_create_texencode(obs_data_t *settings, - obs_encoder_t *encoder) +static void *amf_av1_create_texencode(obs_data_t *settings, obs_encoder_t *encoder) try { check_texture_encode_capability(encoder, amf_codec_type::AV1); @@ -2225,8 +2069,7 @@ try { return enc.release(); } catch (const amf_error &err) { - blog(LOG_ERROR, "[texture-amf-av1] %s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + blog(LOG_ERROR, "[texture-amf-av1] %s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return obs_encoder_create_rerouted(encoder, "av1_fallback_amf"); } catch (const char *err) { @@ -2234,8 +2077,7 @@ try { return obs_encoder_create_rerouted(encoder, "av1_fallback_amf"); } -static void *amf_av1_create_fallback(obs_data_t *settings, - obs_encoder_t *encoder) +static void *amf_av1_create_fallback(obs_data_t *settings, obs_encoder_t *encoder) try { std::unique_ptr enc = std::make_unique(); enc->encoder = encoder; @@ -2250,8 +2092,7 @@ try { } case VIDEO_FORMAT_P216: case VIDEO_FORMAT_P416: { - const char *const text = - obs_module_text("AMF.16bitUnsupported"); + const char *const text = obs_module_text("AMF.16bitUnsupported"); obs_encoder_set_last_error(encoder, text); throw text; } @@ -2259,8 +2100,7 @@ try { switch (voi->colorspace) { case VIDEO_CS_2100_PQ: case VIDEO_CS_2100_HLG: { - const char *const text = - obs_module_text("AMF.8bitUnsupportedHdr"); + const char *const text = obs_module_text("AMF.8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); throw text; } @@ -2271,8 +2111,7 @@ try { return enc.release(); } catch (const amf_error &err) { - blog(LOG_ERROR, "[fallback-amf-av1] %s: %s: %ls", __FUNCTION__, err.str, - amf_trace->GetResultText(err.res)); + blog(LOG_ERROR, "[fallback-amf-av1] %s: %s: %ls", __FUNCTION__, err.str, amf_trace->GetResultText(err.res)); return nullptr; } catch (const char *err) { @@ -2303,16 +2142,12 @@ static void register_av1() amf_encoder_info.get_defaults = amf_av1_defaults; amf_encoder_info.get_properties = amf_av1_properties; amf_encoder_info.get_extra_data = amf_extra_data; - amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI; + amf_encoder_info.caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI; obs_register_encoder(&amf_encoder_info); amf_encoder_info.id = "av1_fallback_amf"; - amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI; + amf_encoder_info.caps = OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI; amf_encoder_info.encode_texture = nullptr; amf_encoder_info.create = amf_av1_create_fallback; amf_encoder_info.encode = amf_encode_fallback; @@ -2339,8 +2174,7 @@ try { /* Check if the DLL is present before running the more expensive */ /* obs-amf-test.exe, but load it as data so it can't crash us */ - amf_module_test = - LoadLibraryExW(AMF_DLL_NAME, nullptr, LOAD_LIBRARY_AS_DATAFILE); + amf_module_test = LoadLibraryExW(AMF_DLL_NAME, nullptr, LOAD_LIBRARY_AS_DATAFILE); if (!amf_module_test) throw "No AMF library"; FreeLibrary(amf_module_test); @@ -2363,8 +2197,7 @@ try { for (;;) { char data[2048]; - size_t len = - os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); + size_t len = os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); if (!len) break; @@ -2395,14 +2228,10 @@ try { std::string section = std::to_string(i); adapter_caps &info = caps[i]; - info.is_amd = - config_get_bool(config, section.c_str(), "is_amd"); - info.supports_avc = config_get_bool(config, section.c_str(), - "supports_avc"); - info.supports_hevc = config_get_bool(config, section.c_str(), - "supports_hevc"); - info.supports_av1 = config_get_bool(config, section.c_str(), - "supports_av1"); + info.is_amd = config_get_bool(config, section.c_str(), "is_amd"); + info.supports_avc = config_get_bool(config, section.c_str(), "supports_avc"); + info.supports_hevc = config_get_bool(config, section.c_str(), "supports_hevc"); + info.supports_av1 = config_get_bool(config, section.c_str(), "supports_av1"); avc_supported |= info.supports_avc; hevc_supported |= info.supports_hevc; @@ -2419,8 +2248,7 @@ try { if (!amf_module) throw "AMF library failed to load"; - AMFInit_Fn init = - (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME); + AMFInit_Fn init = (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME); if (!init) throw "Failed to get AMFInit address"; @@ -2432,8 +2260,7 @@ try { if (res != AMF_OK) throw amf_error("GetTrace failed", res); - AMFQueryVersion_Fn get_ver = (AMFQueryVersion_Fn)GetProcAddress( - amf_module, AMF_QUERY_VERSION_FUNCTION_NAME); + AMFQueryVersion_Fn get_ver = (AMFQueryVersion_Fn)GetProcAddress(amf_module, AMF_QUERY_VERSION_FUNCTION_NAME); if (!get_ver) throw "Failed to get AMFQueryVersion address"; @@ -2471,8 +2298,7 @@ try { } catch (const amf_error &err) { /* doing an error here because it means at least the library has loaded * successfully, so they probably have AMD at this point */ - blog(LOG_ERROR, "%s: %s: 0x%lX", __FUNCTION__, err.str, - (uint32_t)err.res); + blog(LOG_ERROR, "%s: %s: 0x%lX", __FUNCTION__, err.str, (uint32_t)err.res); } extern "C" void amf_unload(void) diff --git a/plugins/obs-ffmpeg/vaapi-utils.c b/plugins/obs-ffmpeg/vaapi-utils.c index 46ac79c18..7fb8322c2 100644 --- a/plugins/obs-ffmpeg/vaapi-utils.c +++ b/plugins/obs-ffmpeg/vaapi-utils.c @@ -25,8 +25,7 @@ inline static VADisplay vaapi_open_display_drm(int *fd, const char *device_path) *fd = open(device_path, O_RDWR); if (*fd < 0) { - blog(LOG_ERROR, "VAAPI: Failed to open device '%s'", - device_path); + blog(LOG_ERROR, "VAAPI: Failed to open device '%s'", device_path); return NULL; } @@ -77,8 +76,7 @@ static void vaapi_log_error_cb(void *user_context, const char *message) dstr_free(&m); } -VADisplay vaapi_open_device(int *fd, const char *device_path, - const char *func_name) +VADisplay vaapi_open_device(int *fd, const char *device_path, const char *func_name) { VADisplay va_dpy; VAStatus va_status; @@ -97,8 +95,7 @@ VADisplay vaapi_open_device(int *fd, const char *device_path, va_status = vaInitialize(va_dpy, &major, &minor); if (va_status != VA_STATUS_SUCCESS) { - blog(LOG_ERROR, "VAAPI: Failed to initialize display in %s", - func_name); + blog(LOG_ERROR, "VAAPI: Failed to initialize display in %s", func_name); vaapi_close_device(fd, va_dpy); return NULL; } @@ -112,8 +109,7 @@ VADisplay vaapi_open_device(int *fd, const char *device_path, driver = vaQueryVendorString(va_dpy); - blog(LOG_DEBUG, "VAAPI: '%s' in use for device '%s'", driver, - device_path); + blog(LOG_DEBUG, "VAAPI: '%s' in use for device '%s'", driver, device_path); return va_dpy; } @@ -124,9 +120,7 @@ void vaapi_close_device(int *fd, VADisplay dpy) vaapi_close_display_drm(fd); } -static uint32_t vaapi_display_ep_combo_rate_controls(VAProfile profile, - VAEntrypoint entrypoint, - VADisplay dpy, +static uint32_t vaapi_display_ep_combo_rate_controls(VAProfile profile, VAEntrypoint entrypoint, VADisplay dpy, const char *device_path) { VAStatus va_status; @@ -139,55 +133,42 @@ static uint32_t vaapi_display_ep_combo_rate_controls(VAProfile profile, case VA_STATUS_SUCCESS: return attrib->value; case VA_STATUS_ERROR_UNSUPPORTED_PROFILE: - blog(LOG_DEBUG, "VAAPI: %s is not supported by the device '%s'", - vaProfileStr(profile), device_path); + blog(LOG_DEBUG, "VAAPI: %s is not supported by the device '%s'", vaProfileStr(profile), device_path); return 0; case VA_STATUS_ERROR_UNSUPPORTED_ENTRYPOINT: - blog(LOG_DEBUG, - "VAAPI: %s %s is not supported by the device '%s'", - vaProfileStr(profile), vaEntrypointStr(entrypoint), - device_path); + blog(LOG_DEBUG, "VAAPI: %s %s is not supported by the device '%s'", vaProfileStr(profile), + vaEntrypointStr(entrypoint), device_path); return 0; default: - blog(LOG_ERROR, - "VAAPI: Fail to get RC attribute from the %s %s of the device '%s'", - vaProfileStr(profile), vaEntrypointStr(entrypoint), - device_path); + blog(LOG_ERROR, "VAAPI: Fail to get RC attribute from the %s %s of the device '%s'", + vaProfileStr(profile), vaEntrypointStr(entrypoint), device_path); return 0; } } -static bool vaapi_display_ep_combo_supported(VAProfile profile, - VAEntrypoint entrypoint, - VADisplay dpy, +static bool vaapi_display_ep_combo_supported(VAProfile profile, VAEntrypoint entrypoint, VADisplay dpy, const char *device_path) { - uint32_t ret = vaapi_display_ep_combo_rate_controls(profile, entrypoint, - dpy, device_path); + uint32_t ret = vaapi_display_ep_combo_rate_controls(profile, entrypoint, dpy, device_path); if (ret & VA_RC_CBR || ret & VA_RC_CQP || ret & VA_RC_VBR) return true; return false; } -bool vaapi_device_rc_supported(VAProfile profile, VADisplay dpy, uint32_t rc, - const char *device_path) +bool vaapi_device_rc_supported(VAProfile profile, VADisplay dpy, uint32_t rc, const char *device_path) { - uint32_t ret = vaapi_display_ep_combo_rate_controls( - profile, VAEntrypointEncSlice, dpy, device_path); + uint32_t ret = vaapi_display_ep_combo_rate_controls(profile, VAEntrypointEncSlice, dpy, device_path); if (ret & rc) return true; - ret = vaapi_display_ep_combo_rate_controls( - profile, VAEntrypointEncSliceLP, dpy, device_path); + ret = vaapi_display_ep_combo_rate_controls(profile, VAEntrypointEncSliceLP, dpy, device_path); if (ret & rc) return true; return false; } -static bool vaapi_display_ep_bframe_supported(VAProfile profile, - VAEntrypoint entrypoint, - VADisplay dpy) +static bool vaapi_display_ep_bframe_supported(VAProfile profile, VAEntrypoint entrypoint, VADisplay dpy) { VAStatus va_status; VAConfigAttrib attrib[1]; @@ -195,8 +176,7 @@ static bool vaapi_display_ep_bframe_supported(VAProfile profile, va_status = vaGetConfigAttributes(dpy, profile, entrypoint, attrib, 1); - if (va_status == VA_STATUS_SUCCESS && - attrib->value != VA_ATTRIB_NOT_SUPPORTED) + if (va_status == VA_STATUS_SUCCESS && attrib->value != VA_ATTRIB_NOT_SUPPORTED) return attrib->value >> 16; return false; @@ -204,32 +184,26 @@ static bool vaapi_display_ep_bframe_supported(VAProfile profile, bool vaapi_device_bframe_supported(VAProfile profile, VADisplay dpy) { - bool ret = vaapi_display_ep_bframe_supported(profile, - VAEntrypointEncSlice, dpy); + bool ret = vaapi_display_ep_bframe_supported(profile, VAEntrypointEncSlice, dpy); if (ret) return true; - ret = vaapi_display_ep_bframe_supported(profile, VAEntrypointEncSliceLP, - dpy); + ret = vaapi_display_ep_bframe_supported(profile, VAEntrypointEncSliceLP, dpy); if (ret) return true; return false; } -#define CHECK_PROFILE(ret, profile, va_dpy, device_path) \ - if (vaapi_display_ep_combo_supported(profile, VAEntrypointEncSlice, \ - va_dpy, device_path)) { \ - blog(LOG_DEBUG, "'%s' support encoding with %s", device_path, \ - vaProfileStr(profile)); \ - ret |= true; \ +#define CHECK_PROFILE(ret, profile, va_dpy, device_path) \ + if (vaapi_display_ep_combo_supported(profile, VAEntrypointEncSlice, va_dpy, device_path)) { \ + blog(LOG_DEBUG, "'%s' support encoding with %s", device_path, vaProfileStr(profile)); \ + ret |= true; \ } -#define CHECK_PROFILE_LP(ret, profile, va_dpy, device_path) \ - if (vaapi_display_ep_combo_supported(profile, VAEntrypointEncSliceLP, \ - va_dpy, device_path)) { \ - blog(LOG_DEBUG, "'%s' support low power encoding with %s", \ - device_path, vaProfileStr(profile)); \ - ret |= true; \ +#define CHECK_PROFILE_LP(ret, profile, va_dpy, device_path) \ + if (vaapi_display_ep_combo_supported(profile, VAEntrypointEncSliceLP, va_dpy, device_path)) { \ + blog(LOG_DEBUG, "'%s' support low power encoding with %s", device_path, vaProfileStr(profile)); \ + ret |= true; \ } bool vaapi_display_h264_supported(VADisplay dpy, const char *device_path) @@ -241,8 +215,7 @@ bool vaapi_display_h264_supported(VADisplay dpy, const char *device_path) CHECK_PROFILE(ret, VAProfileH264High, dpy, device_path); if (!ret) { - CHECK_PROFILE_LP(ret, VAProfileH264ConstrainedBaseline, dpy, - device_path); + CHECK_PROFILE_LP(ret, VAProfileH264ConstrainedBaseline, dpy, device_path); CHECK_PROFILE_LP(ret, VAProfileH264Main, dpy, device_path); CHECK_PROFILE_LP(ret, VAProfileH264High, dpy, device_path); } @@ -257,8 +230,7 @@ bool vaapi_device_h264_supported(const char *device_path) int drm_fd = -1; - va_dpy = vaapi_open_device(&drm_fd, device_path, - "vaapi_device_h264_supported"); + va_dpy = vaapi_open_device(&drm_fd, device_path, "vaapi_device_h264_supported"); if (!va_dpy) return false; @@ -312,8 +284,7 @@ bool vaapi_device_av1_supported(const char *device_path) int drm_fd = -1; - va_dpy = vaapi_open_device(&drm_fd, device_path, - "vaapi_device_av1_supported"); + va_dpy = vaapi_open_device(&drm_fd, device_path, "vaapi_device_av1_supported"); if (!va_dpy) return false; @@ -371,8 +342,7 @@ bool vaapi_device_hevc_supported(const char *device_path) int drm_fd = -1; - va_dpy = vaapi_open_device(&drm_fd, device_path, - "vaapi_device_hevc_supported"); + va_dpy = vaapi_open_device(&drm_fd, device_path, "vaapi_device_hevc_supported"); if (!va_dpy) return false; diff --git a/plugins/obs-ffmpeg/vaapi-utils.h b/plugins/obs-ffmpeg/vaapi-utils.h index d458bad2c..6594a0013 100644 --- a/plugins/obs-ffmpeg/vaapi-utils.h +++ b/plugins/obs-ffmpeg/vaapi-utils.h @@ -8,12 +8,10 @@ #include -VADisplay vaapi_open_device(int *fd, const char *device_path, - const char *func_name); +VADisplay vaapi_open_device(int *fd, const char *device_path, const char *func_name); void vaapi_close_device(int *fd, VADisplay dpy); -bool vaapi_device_rc_supported(VAProfile profile, VADisplay dpy, uint32_t rc, - const char *device_path); +bool vaapi_device_rc_supported(VAProfile profile, VADisplay dpy, uint32_t rc, const char *device_path); bool vaapi_device_bframe_supported(VAProfile profile, VADisplay dpy); bool vaapi_display_h264_supported(VADisplay dpy, const char *device_path); diff --git a/plugins/obs-filters/async-delay-filter.c b/plugins/obs-filters/async-delay-filter.c index d727b43f5..7883b0777 100644 --- a/plugins/obs-filters/async-delay-filter.c +++ b/plugins/obs-filters/async-delay-filter.c @@ -46,14 +46,12 @@ static const char *async_delay_filter_name(void *unused) return obs_module_text("AsyncDelayFilter"); } -static void free_video_data(struct async_delay_data *filter, - obs_source_t *parent) +static void free_video_data(struct async_delay_data *filter, obs_source_t *parent) { while (filter->video_frames.size) { struct obs_source_frame *frame; - deque_pop_front(&filter->video_frames, &frame, - sizeof(struct obs_source_frame *)); + deque_pop_front(&filter->video_frames, &frame, sizeof(struct obs_source_frame *)); obs_source_release_frame(parent, frame); } } @@ -71,8 +69,7 @@ static void free_audio_data(struct async_delay_data *filter) while (filter->audio_frames.size) { struct obs_audio_data audio; - deque_pop_front(&filter->audio_frames, &audio, - sizeof(struct obs_audio_data)); + deque_pop_front(&filter->audio_frames, &audio, sizeof(struct obs_audio_data)); free_audio_packet(&audio); } } @@ -81,9 +78,7 @@ static void free_audio_data(struct async_delay_data *filter) static void async_delay_filter_update(void *data, obs_data_t *settings) { struct async_delay_data *filter = data; - uint64_t new_interval = - (uint64_t)obs_data_get_int(settings, SETTING_DELAY_MS) * - MSEC_TO_NSEC; + uint64_t new_interval = (uint64_t)obs_data_get_int(settings, SETTING_DELAY_MS) * MSEC_TO_NSEC; if (new_interval < filter->interval) free_video_data(filter, obs_filter_get_parent(filter->context)); @@ -95,8 +90,7 @@ static void async_delay_filter_update(void *data, obs_data_t *settings) filter->audio_delay_reached = false; } -static void *async_delay_filter_create(obs_data_t *settings, - obs_source_t *context) +static void *async_delay_filter_create(obs_data_t *settings, obs_source_t *context) { struct async_delay_data *filter = bzalloc(sizeof(*filter)); struct obs_audio_info oai; @@ -126,8 +120,7 @@ static obs_properties_t *async_delay_filter_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *p = obs_properties_add_int(props, SETTING_DELAY_MS, - TEXT_DELAY_MS, 0, 20000, 1); + obs_property_t *p = obs_properties_add_int(props, SETTING_DELAY_MS, TEXT_DELAY_MS, 0, 20000, 1); obs_property_int_set_suffix(p, " ms"); UNUSED_PARAMETER(data); @@ -153,16 +146,14 @@ static inline bool is_timestamp_jump(uint64_t ts, uint64_t prev_ts) return ts < prev_ts || (ts - prev_ts) > SEC_TO_NSEC; } -static struct obs_source_frame * -async_delay_filter_video(void *data, struct obs_source_frame *frame) +static struct obs_source_frame *async_delay_filter_video(void *data, struct obs_source_frame *frame) { struct async_delay_data *filter = data; obs_source_t *parent = obs_filter_get_parent(filter->context); struct obs_source_frame *output; uint64_t cur_interval; - if (filter->reset_video || - is_timestamp_jump(frame->timestamp, filter->last_video_ts)) { + if (filter->reset_video || is_timestamp_jump(frame->timestamp, filter->last_video_ts)) { free_video_data(filter, parent); filter->video_delay_reached = false; filter->reset_video = false; @@ -170,17 +161,14 @@ async_delay_filter_video(void *data, struct obs_source_frame *frame) filter->last_video_ts = frame->timestamp; - deque_push_back(&filter->video_frames, &frame, - sizeof(struct obs_source_frame *)); - deque_peek_front(&filter->video_frames, &output, - sizeof(struct obs_source_frame *)); + deque_push_back(&filter->video_frames, &frame, sizeof(struct obs_source_frame *)); + deque_peek_front(&filter->video_frames, &output, sizeof(struct obs_source_frame *)); cur_interval = frame->timestamp - output->timestamp; if (!filter->video_delay_reached && cur_interval < filter->interval) return NULL; - deque_pop_front(&filter->video_frames, NULL, - sizeof(struct obs_source_frame *)); + deque_pop_front(&filter->video_frames, NULL, sizeof(struct obs_source_frame *)); if (!filter->video_delay_reached) filter->video_delay_reached = true; @@ -189,8 +177,7 @@ async_delay_filter_video(void *data, struct obs_source_frame *frame) } #ifdef DELAY_AUDIO -static struct obs_audio_data * -async_delay_filter_audio(void *data, struct obs_audio_data *audio) +static struct obs_audio_data *async_delay_filter_audio(void *data, struct obs_audio_data *audio) { struct async_delay_data *filter = data; struct obs_audio_data cached = *audio; @@ -198,8 +185,7 @@ async_delay_filter_audio(void *data, struct obs_audio_data *audio) uint64_t duration; uint64_t end_ts; - if (filter->reset_audio || - is_timestamp_jump(audio->timestamp, filter->last_audio_ts)) { + if (filter->reset_audio || is_timestamp_jump(audio->timestamp, filter->last_audio_ts)) { free_audio_data(filter); filter->audio_delay_reached = false; filter->reset_audio = false; @@ -207,16 +193,14 @@ async_delay_filter_audio(void *data, struct obs_audio_data *audio) filter->last_audio_ts = audio->timestamp; - duration = - util_mul_div64(audio->frames, SEC_TO_NSEC, filter->samplerate); + duration = util_mul_div64(audio->frames, SEC_TO_NSEC, filter->samplerate); end_ts = audio->timestamp + duration; for (size_t i = 0; i < MAX_AV_PLANES; i++) { if (!audio->data[i]) break; - cached.data[i] = - bmemdup(audio->data[i], audio->frames * sizeof(float)); + cached.data[i] = bmemdup(audio->data[i], audio->frames * sizeof(float)); } free_audio_packet(&filter->audio_output); diff --git a/plugins/obs-filters/chroma-key-filter.c b/plugins/obs-filters/chroma-key-filter.c index 2a5a6557a..036fcc6f3 100644 --- a/plugins/obs-filters/chroma-key-filter.c +++ b/plugins/obs-filters/chroma-key-filter.c @@ -92,19 +92,15 @@ static const char *chroma_key_name(void *unused) static const float cb_vec[] = {-0.100644f, -0.338572f, 0.439216f, 0.501961f}; static const float cr_vec[] = {0.439216f, -0.398942f, -0.040274f, 0.501961f}; -static inline void -color_settings_update_v1(struct chroma_key_filter_data *filter, - obs_data_t *settings) +static inline void color_settings_update_v1(struct chroma_key_filter_data *filter, obs_data_t *settings) { - uint32_t opacity = - (uint32_t)obs_data_get_int(settings, SETTING_OPACITY); + uint32_t opacity = (uint32_t)obs_data_get_int(settings, SETTING_OPACITY); uint32_t color = 0xFFFFFF | (((opacity * 255) / 100) << 24); double contrast = obs_data_get_double(settings, SETTING_CONTRAST); double brightness = obs_data_get_double(settings, SETTING_BRIGHTNESS); double gamma = obs_data_get_double(settings, SETTING_GAMMA); - contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) - : (contrast + 1.0); + contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) : (contrast + 1.0); brightness *= 0.5; @@ -117,36 +113,28 @@ color_settings_update_v1(struct chroma_key_filter_data *filter, vec4_from_rgba(&filter->color, color); } -static inline void -color_settings_update_v2(struct chroma_key_filter_data_v2 *filter, - obs_data_t *settings) +static inline void color_settings_update_v2(struct chroma_key_filter_data_v2 *filter, obs_data_t *settings) { filter->opacity = (float)obs_data_get_double(settings, SETTING_OPACITY); double contrast = obs_data_get_double(settings, SETTING_CONTRAST); - contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) - : (contrast + 1.0); + contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) : (contrast + 1.0); filter->contrast = (float)contrast; - filter->brightness = - (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); + filter->brightness = (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); double gamma = obs_data_get_double(settings, SETTING_GAMMA); gamma = (gamma < 0.0) ? (-gamma + 1.0) : (1.0 / (gamma + 1.0)); filter->gamma = (float)gamma; } -static inline void -chroma_settings_update_v1(struct chroma_key_filter_data *filter, - obs_data_t *settings) +static inline void chroma_settings_update_v1(struct chroma_key_filter_data *filter, obs_data_t *settings) { int64_t similarity = obs_data_get_int(settings, SETTING_SIMILARITY); int64_t smoothness = obs_data_get_int(settings, SETTING_SMOOTHNESS); int64_t spill = obs_data_get_int(settings, SETTING_SPILL); - uint32_t key_color = - (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); - const char *key_type = - obs_data_get_string(settings, SETTING_COLOR_TYPE); + uint32_t key_color = (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); + const char *key_type = obs_data_get_string(settings, SETTING_COLOR_TYPE); struct vec4 key_rgb; struct vec4 cb_v4; struct vec4 cr_v4; @@ -170,17 +158,13 @@ chroma_settings_update_v1(struct chroma_key_filter_data *filter, filter->spill = (float)spill / 1000.0f; } -static inline void -chroma_settings_update_v2(struct chroma_key_filter_data_v2 *filter, - obs_data_t *settings) +static inline void chroma_settings_update_v2(struct chroma_key_filter_data_v2 *filter, obs_data_t *settings) { int64_t similarity = obs_data_get_int(settings, SETTING_SIMILARITY); int64_t smoothness = obs_data_get_int(settings, SETTING_SMOOTHNESS); int64_t spill = obs_data_get_int(settings, SETTING_SPILL); - uint32_t key_color = - (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); - const char *key_type = - obs_data_get_string(settings, SETTING_COLOR_TYPE); + uint32_t key_color = (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); + const char *key_type = obs_data_get_string(settings, SETTING_COLOR_TYPE); struct vec4 key_rgb; struct vec4 cb_v4; struct vec4 cr_v4; @@ -248,8 +232,7 @@ static void chroma_key_destroy_v2(void *data) static void *chroma_key_create_v1(obs_data_t *settings, obs_source_t *context) { - struct chroma_key_filter_data *filter = - bzalloc(sizeof(struct chroma_key_filter_data)); + struct chroma_key_filter_data *filter = bzalloc(sizeof(struct chroma_key_filter_data)); char *effect_path = obs_module_file("chroma_key_filter.effect"); filter->context = context; @@ -258,24 +241,15 @@ static void *chroma_key_create_v1(obs_data_t *settings, obs_source_t *context) filter->effect = gs_effect_create_from_file(effect_path, NULL); if (filter->effect) { - filter->color_param = - gs_effect_get_param_by_name(filter->effect, "color"); - filter->contrast_param = - gs_effect_get_param_by_name(filter->effect, "contrast"); - filter->brightness_param = gs_effect_get_param_by_name( - filter->effect, "brightness"); - filter->gamma_param = - gs_effect_get_param_by_name(filter->effect, "gamma"); - filter->chroma_param = gs_effect_get_param_by_name( - filter->effect, "chroma_key"); - filter->pixel_size_param = gs_effect_get_param_by_name( - filter->effect, "pixel_size"); - filter->similarity_param = gs_effect_get_param_by_name( - filter->effect, "similarity"); - filter->smoothness_param = gs_effect_get_param_by_name( - filter->effect, "smoothness"); - filter->spill_param = - gs_effect_get_param_by_name(filter->effect, "spill"); + filter->color_param = gs_effect_get_param_by_name(filter->effect, "color"); + filter->contrast_param = gs_effect_get_param_by_name(filter->effect, "contrast"); + filter->brightness_param = gs_effect_get_param_by_name(filter->effect, "brightness"); + filter->gamma_param = gs_effect_get_param_by_name(filter->effect, "gamma"); + filter->chroma_param = gs_effect_get_param_by_name(filter->effect, "chroma_key"); + filter->pixel_size_param = gs_effect_get_param_by_name(filter->effect, "pixel_size"); + filter->similarity_param = gs_effect_get_param_by_name(filter->effect, "similarity"); + filter->smoothness_param = gs_effect_get_param_by_name(filter->effect, "smoothness"); + filter->spill_param = gs_effect_get_param_by_name(filter->effect, "spill"); } obs_leave_graphics(); @@ -293,8 +267,7 @@ static void *chroma_key_create_v1(obs_data_t *settings, obs_source_t *context) static void *chroma_key_create_v2(obs_data_t *settings, obs_source_t *context) { - struct chroma_key_filter_data_v2 *filter = - bzalloc(sizeof(struct chroma_key_filter_data_v2)); + struct chroma_key_filter_data_v2 *filter = bzalloc(sizeof(struct chroma_key_filter_data_v2)); char *effect_path = obs_module_file("chroma_key_filter_v2.effect"); filter->context = context; @@ -303,24 +276,15 @@ static void *chroma_key_create_v2(obs_data_t *settings, obs_source_t *context) filter->effect = gs_effect_create_from_file(effect_path, NULL); if (filter->effect) { - filter->opacity_param = - gs_effect_get_param_by_name(filter->effect, "opacity"); - filter->contrast_param = - gs_effect_get_param_by_name(filter->effect, "contrast"); - filter->brightness_param = gs_effect_get_param_by_name( - filter->effect, "brightness"); - filter->gamma_param = - gs_effect_get_param_by_name(filter->effect, "gamma"); - filter->chroma_param = gs_effect_get_param_by_name( - filter->effect, "chroma_key"); - filter->pixel_size_param = gs_effect_get_param_by_name( - filter->effect, "pixel_size"); - filter->similarity_param = gs_effect_get_param_by_name( - filter->effect, "similarity"); - filter->smoothness_param = gs_effect_get_param_by_name( - filter->effect, "smoothness"); - filter->spill_param = - gs_effect_get_param_by_name(filter->effect, "spill"); + filter->opacity_param = gs_effect_get_param_by_name(filter->effect, "opacity"); + filter->contrast_param = gs_effect_get_param_by_name(filter->effect, "contrast"); + filter->brightness_param = gs_effect_get_param_by_name(filter->effect, "brightness"); + filter->gamma_param = gs_effect_get_param_by_name(filter->effect, "gamma"); + filter->chroma_param = gs_effect_get_param_by_name(filter->effect, "chroma_key"); + filter->pixel_size_param = gs_effect_get_param_by_name(filter->effect, "pixel_size"); + filter->similarity_param = gs_effect_get_param_by_name(filter->effect, "similarity"); + filter->smoothness_param = gs_effect_get_param_by_name(filter->effect, "smoothness"); + filter->spill_param = gs_effect_get_param_by_name(filter->effect, "spill"); } obs_leave_graphics(); @@ -344,8 +308,7 @@ static void chroma_key_render_v1(void *data, gs_effect_t *effect) uint32_t height = obs_source_get_base_height(target); struct vec2 pixel_size; - if (!obs_source_process_filter_begin(filter->context, GS_RGBA, - OBS_ALLOW_DIRECT_RENDERING)) + if (!obs_source_process_filter_begin(filter->context, GS_RGBA, OBS_ALLOW_DIRECT_RENDERING)) return; vec2_set(&pixel_size, 1.0f / (float)width, 1.0f / (float)height); @@ -382,55 +345,41 @@ static void chroma_key_render_v2(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { - vec2_set(&pixel_size, 1.0f / (float)width, - 1.0f / (float)height); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { + vec2_set(&pixel_size, 1.0f / (float)width, 1.0f / (float)height); - gs_effect_set_float(filter->opacity_param, - filter->opacity); - gs_effect_set_float(filter->contrast_param, - filter->contrast); - gs_effect_set_float(filter->brightness_param, - filter->brightness); + gs_effect_set_float(filter->opacity_param, filter->opacity); + gs_effect_set_float(filter->contrast_param, filter->contrast); + gs_effect_set_float(filter->brightness_param, filter->brightness); gs_effect_set_float(filter->gamma_param, filter->gamma); - gs_effect_set_vec2(filter->chroma_param, - &filter->chroma); - gs_effect_set_vec2(filter->pixel_size_param, - &pixel_size); - gs_effect_set_float(filter->similarity_param, - filter->similarity); - gs_effect_set_float(filter->smoothness_param, - filter->smoothness); + gs_effect_set_vec2(filter->chroma_param, &filter->chroma); + gs_effect_set_vec2(filter->pixel_size_param, &pixel_size); + gs_effect_set_float(filter->similarity_param, filter->similarity); + gs_effect_set_float(filter->smoothness_param, filter->smoothness); gs_effect_set_float(filter->spill_param, filter->spill); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_end(filter->context, - filter->effect, 0, 0); + obs_source_process_filter_end(filter->context, filter->effect, 0, 0); gs_blend_state_pop(); } } } -static bool key_type_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool key_type_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { const char *type = obs_data_get_string(settings, SETTING_COLOR_TYPE); bool custom = strcmp(type, "custom") == 0; - obs_property_set_visible(obs_properties_get(props, SETTING_KEY_COLOR), - custom); + obs_property_set_visible(obs_properties_get(props, SETTING_KEY_COLOR), custom); UNUSED_PARAMETER(p); return true; @@ -440,34 +389,24 @@ static obs_properties_t *chroma_key_properties_v1(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, - TEXT_COLOR_TYPE, - OBS_COMBO_TYPE_LIST, + obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, TEXT_COLOR_TYPE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("Green"), "green"); obs_property_list_add_string(p, obs_module_text("Blue"), "blue"); obs_property_list_add_string(p, obs_module_text("Magenta"), "magenta"); - obs_property_list_add_string(p, obs_module_text("CustomColor"), - "custom"); + obs_property_list_add_string(p, obs_module_text("CustomColor"), "custom"); obs_property_set_modified_callback(p, key_type_changed); obs_properties_add_color(props, SETTING_KEY_COLOR, TEXT_KEY_COLOR); - obs_properties_add_int_slider(props, SETTING_SIMILARITY, - TEXT_SIMILARITY, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, - TEXT_SMOOTHNESS, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_SPILL, TEXT_SPILL, 1, 1000, - 1); + obs_properties_add_int_slider(props, SETTING_SIMILARITY, TEXT_SIMILARITY, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, TEXT_SMOOTHNESS, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SPILL, TEXT_SPILL, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, - 100, 1); - obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, - -1.0, 1.0, 0.01); - obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, - TEXT_BRIGHTNESS, -1.0, 1.0, 0.01); - obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, - 1.0, 0.01); + obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, 100, 1); + obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, -1.0, 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, TEXT_BRIGHTNESS, -1.0, 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, 1.0, 0.01); UNUSED_PARAMETER(data); return props; @@ -477,37 +416,26 @@ static obs_properties_t *chroma_key_properties_v2(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, - TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); + obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); - obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, - TEXT_COLOR_TYPE, - OBS_COMBO_TYPE_LIST, + obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, TEXT_COLOR_TYPE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("Green"), "green"); obs_property_list_add_string(p, obs_module_text("Blue"), "blue"); obs_property_list_add_string(p, obs_module_text("Magenta"), "magenta"); - obs_property_list_add_string(p, obs_module_text("CustomColor"), - "custom"); + obs_property_list_add_string(p, obs_module_text("CustomColor"), "custom"); obs_property_set_modified_callback(p, key_type_changed); obs_properties_add_color(props, SETTING_KEY_COLOR, TEXT_KEY_COLOR); - obs_properties_add_int_slider(props, SETTING_SIMILARITY, - TEXT_SIMILARITY, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, - TEXT_SMOOTHNESS, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_SPILL, TEXT_SPILL, 1, 1000, - 1); + obs_properties_add_int_slider(props, SETTING_SIMILARITY, TEXT_SIMILARITY, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, TEXT_SMOOTHNESS, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SPILL, TEXT_SPILL, 1, 1000, 1); - obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, - 0.0, 1.0, 0.0001); - obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, - -4.0, 4.0, 0.01); - obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, - TEXT_BRIGHTNESS, -1.0, 1.0, 0.0001); - obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, - 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, -4.0, 4.0, 0.01); + obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, TEXT_BRIGHTNESS, -1.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, 1.0, 0.01); UNUSED_PARAMETER(data); return props; @@ -539,9 +467,8 @@ static void chroma_key_defaults_v2(obs_data_t *settings) obs_data_set_default_int(settings, SETTING_SPILL, 100); } -static enum gs_color_space -chroma_key_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space chroma_key_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -554,8 +481,7 @@ chroma_key_get_color_space(void *data, size_t count, struct chroma_key_filter_data_v2 *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-filters/color-correction-filter.c b/plugins/obs-filters/color-correction-filter.c index fdfb4c052..3d945a753 100644 --- a/plugins/obs-filters/color-correction-filter.c +++ b/plugins/obs-filters/color-correction-filter.c @@ -117,20 +117,16 @@ static void color_correction_filter_update_v1(void *data, obs_data_t *settings) filter->gamma = (float)gamma; /* Build our contrast number. */ - float contrast = - (float)obs_data_get_double(settings, SETTING_CONTRAST) + 1.0f; + float contrast = (float)obs_data_get_double(settings, SETTING_CONTRAST) + 1.0f; float one_minus_con = (1.0f - contrast) / 2.0f; /* Now let's build our Contrast matrix. */ - filter->con_matrix = (struct matrix4){ - contrast, 0.0f, 0.0f, 0.0f, - 0.0f, contrast, 0.0f, 0.0f, - 0.0f, 0.0f, contrast, 0.0f, - one_minus_con, one_minus_con, one_minus_con, 1.0f}; + filter->con_matrix = (struct matrix4){contrast, 0.0f, 0.0f, 0.0f, 0.0f, contrast, + 0.0f, 0.0f, 0.0f, 0.0f, contrast, 0.0f, + one_minus_con, one_minus_con, one_minus_con, 1.0f}; /* Build our brightness number. */ - float brightness = - (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); + float brightness = (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); /* * Now let's build our Brightness matrix. @@ -143,8 +139,7 @@ static void color_correction_filter_update_v1(void *data, obs_data_t *settings) filter->bright_matrix.t.z = brightness; /* Build our Saturation number. */ - float saturation = - (float)obs_data_get_double(settings, SETTING_SATURATION) + 1.0f; + float saturation = (float)obs_data_get_double(settings, SETTING_SATURATION) + 1.0f; /* Factor in the selected color weights. */ float one_minus_sat_red = (1.0f - saturation) * red_weight; @@ -173,12 +168,10 @@ static void color_correction_filter_update_v1(void *data, obs_data_t *settings) 1.0f}; /* Build our Hue number. */ - float hue_shift = - (float)obs_data_get_double(settings, SETTING_HUESHIFT); + float hue_shift = (float)obs_data_get_double(settings, SETTING_HUESHIFT); /* Build our Transparency number. */ - float opacity = - (float)obs_data_get_int(settings, SETTING_OPACITY) * 0.01f; + float opacity = (float)obs_data_get_int(settings, SETTING_OPACITY) * 0.01f; /* Hue is the radian of 0 to 360 degrees. */ float half_angle = 0.5f * (float)(hue_shift / (180.0f / M_PI)); @@ -245,17 +238,13 @@ static void color_correction_filter_update_v1(void *data, obs_data_t *settings) filter->color_matrix.t.z = color_v4.w * color_v4.z; /* First we apply the Contrast & Brightness matrix. */ - matrix4_mul(&filter->final_matrix, &filter->bright_matrix, - &filter->con_matrix); + matrix4_mul(&filter->final_matrix, &filter->bright_matrix, &filter->con_matrix); /* Now we apply the Saturation matrix. */ - matrix4_mul(&filter->final_matrix, &filter->final_matrix, - &filter->sat_matrix); + matrix4_mul(&filter->final_matrix, &filter->final_matrix, &filter->sat_matrix); /* Next we apply the Hue+Opacity matrix. */ - matrix4_mul(&filter->final_matrix, &filter->final_matrix, - &filter->hue_op_matrix); + matrix4_mul(&filter->final_matrix, &filter->final_matrix, &filter->hue_op_matrix); /* Lastly we apply the Color Wash matrix. */ - matrix4_mul(&filter->final_matrix, &filter->final_matrix, - &filter->color_matrix); + matrix4_mul(&filter->final_matrix, &filter->final_matrix, &filter->color_matrix); } static void color_correction_filter_update_v2(void *data, obs_data_t *settings) @@ -269,18 +258,14 @@ static void color_correction_filter_update_v2(void *data, obs_data_t *settings) /* Build our contrast number. */ float contrast = (float)obs_data_get_double(settings, SETTING_CONTRAST); - contrast = (contrast < 0.0f) ? (1.0f / (-contrast + 1.0f)) - : (contrast + 1.0f); + contrast = (contrast < 0.0f) ? (1.0f / (-contrast + 1.0f)) : (contrast + 1.0f); /* Now let's build our Contrast matrix. */ - filter->con_matrix = (struct matrix4){contrast, 0.0f, 0.0f, 0.0f, 0.0f, - contrast, 0.0f, 0.0f, 0.0f, 0.0f, - contrast, 0.0f, 0.0f, 0.0f, 0.0f, - 1.0f}; + filter->con_matrix = (struct matrix4){contrast, 0.0f, 0.0f, 0.0f, 0.0f, contrast, 0.0f, 0.0f, + 0.0f, 0.0f, contrast, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f}; /* Build our brightness number. */ - float brightness = - (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); + float brightness = (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); /* * Now let's build our Brightness matrix. @@ -293,8 +278,7 @@ static void color_correction_filter_update_v2(void *data, obs_data_t *settings) filter->bright_matrix.t.z = brightness; /* Build our Saturation number. */ - float saturation = - (float)obs_data_get_double(settings, SETTING_SATURATION) + 1.0f; + float saturation = (float)obs_data_get_double(settings, SETTING_SATURATION) + 1.0f; /* Factor in the selected color weights. */ float one_minus_sat_red = (1.0f - saturation) * red_weight; @@ -323,8 +307,7 @@ static void color_correction_filter_update_v2(void *data, obs_data_t *settings) 1.0f}; /* Build our Hue number. */ - float hue_shift = - (float)obs_data_get_double(settings, SETTING_HUESHIFT); + float hue_shift = (float)obs_data_get_double(settings, SETTING_HUESHIFT); /* Build our Transparency number. */ float opacity = (float)obs_data_get_double(settings, SETTING_OPACITY); @@ -375,14 +358,12 @@ static void color_correction_filter_update_v2(void *data, obs_data_t *settings) opacity}; /* Now get the overlay color multiply data. */ - uint32_t color_multiply = - (uint32_t)obs_data_get_int(settings, SETTING_COLOR_MULTIPLY); + uint32_t color_multiply = (uint32_t)obs_data_get_int(settings, SETTING_COLOR_MULTIPLY); struct vec4 color_multiply_v4; vec4_from_rgba_srgb(&color_multiply_v4, color_multiply); /* Now get the overlay color add data. */ - uint32_t color_add = - (uint32_t)obs_data_get_int(settings, SETTING_COLOR_ADD); + uint32_t color_add = (uint32_t)obs_data_get_int(settings, SETTING_COLOR_ADD); struct vec4 color_add_v4; vec4_from_rgba_srgb(&color_add_v4, color_add); @@ -401,17 +382,13 @@ static void color_correction_filter_update_v2(void *data, obs_data_t *settings) filter->color_matrix.t.z = color_add_v4.z; /* First we apply the Contrast & Brightness matrix. */ - matrix4_mul(&filter->final_matrix, &filter->con_matrix, - &filter->bright_matrix); + matrix4_mul(&filter->final_matrix, &filter->con_matrix, &filter->bright_matrix); /* Now we apply the Saturation matrix. */ - matrix4_mul(&filter->final_matrix, &filter->final_matrix, - &filter->sat_matrix); + matrix4_mul(&filter->final_matrix, &filter->final_matrix, &filter->sat_matrix); /* Next we apply the Hue+Opacity matrix. */ - matrix4_mul(&filter->final_matrix, &filter->final_matrix, - &filter->hue_op_matrix); + matrix4_mul(&filter->final_matrix, &filter->final_matrix, &filter->hue_op_matrix); /* Lastly we apply the Color Wash matrix. */ - matrix4_mul(&filter->final_matrix, &filter->final_matrix, - &filter->color_matrix); + matrix4_mul(&filter->final_matrix, &filter->final_matrix, &filter->color_matrix); } /* @@ -451,8 +428,7 @@ static void color_correction_filter_destroy_v2(void *data) * filter, it also calls the render function (farther below) that contains the * actual rendering code. */ -static void *color_correction_filter_create_v1(obs_data_t *settings, - obs_source_t *context) +static void *color_correction_filter_create_v1(obs_data_t *settings, obs_source_t *context) { /* * Because of limitations of pre-c99 compilers, you can't create an @@ -460,8 +436,7 @@ static void *color_correction_filter_create_v1(obs_data_t *settings, * function calculates the size needed and allocates memory to * handle the source. */ - struct color_correction_filter_data *filter = - bzalloc(sizeof(struct color_correction_filter_data)); + struct color_correction_filter_data *filter = bzalloc(sizeof(struct color_correction_filter_data)); /* * By default the effect file is stored in the ./data directory that @@ -484,10 +459,8 @@ static void *color_correction_filter_create_v1(obs_data_t *settings, /* If the filter is active pass the parameters to the filter. */ if (filter->effect) { - filter->gamma_param = gs_effect_get_param_by_name( - filter->effect, SETTING_GAMMA); - filter->final_matrix_param = gs_effect_get_param_by_name( - filter->effect, "color_matrix"); + filter->gamma_param = gs_effect_get_param_by_name(filter->effect, SETTING_GAMMA); + filter->final_matrix_param = gs_effect_get_param_by_name(filter->effect, "color_matrix"); } obs_leave_graphics(); @@ -513,8 +486,7 @@ static void *color_correction_filter_create_v1(obs_data_t *settings, return filter; } -static void *color_correction_filter_create_v2(obs_data_t *settings, - obs_source_t *context) +static void *color_correction_filter_create_v2(obs_data_t *settings, obs_source_t *context) { /* * Because of limitations of pre-c99 compilers, you can't create an @@ -522,8 +494,7 @@ static void *color_correction_filter_create_v2(obs_data_t *settings, * function calculates the size needed and allocates memory to * handle the source. */ - struct color_correction_filter_data_v2 *filter = - bzalloc(sizeof(struct color_correction_filter_data_v2)); + struct color_correction_filter_data_v2 *filter = bzalloc(sizeof(struct color_correction_filter_data_v2)); /* * By default the effect file is stored in the ./data directory that @@ -546,10 +517,8 @@ static void *color_correction_filter_create_v2(obs_data_t *settings, /* If the filter is active pass the parameters to the filter. */ if (filter->effect) { - filter->gamma_param = gs_effect_get_param_by_name( - filter->effect, SETTING_GAMMA); - filter->final_matrix_param = gs_effect_get_param_by_name( - filter->effect, "color_matrix"); + filter->gamma_param = gs_effect_get_param_by_name(filter->effect, SETTING_GAMMA); + filter->final_matrix_param = gs_effect_get_param_by_name(filter->effect, "color_matrix"); } obs_leave_graphics(); @@ -580,14 +549,12 @@ static void color_correction_filter_render_v1(void *data, gs_effect_t *effect) { struct color_correction_filter_data *filter = data; - if (!obs_source_process_filter_begin(filter->context, GS_RGBA, - OBS_ALLOW_DIRECT_RENDERING)) + if (!obs_source_process_filter_begin(filter->context, GS_RGBA, OBS_ALLOW_DIRECT_RENDERING)) return; /* Now pass the interface variables to the .effect file. */ gs_effect_set_float(filter->gamma_param, filter->gamma); - gs_effect_set_matrix4(filter->final_matrix_param, - &filter->final_matrix); + gs_effect_set_matrix4(filter->final_matrix_param, &filter->final_matrix); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); @@ -612,26 +579,21 @@ static void color_correction_filter_render_v2(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { /* Now pass the interface variables to the .effect file. */ gs_effect_set_float(filter->gamma_param, filter->gamma); - gs_effect_set_matrix4(filter->final_matrix_param, - &filter->final_matrix); + gs_effect_set_matrix4(filter->final_matrix_param, &filter->final_matrix); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_end(filter->context, - filter->effect, 0, 0); + obs_source_process_filter_end(filter->context, filter->effect, 0, 0); gs_blend_state_pop(); } @@ -648,19 +610,13 @@ static obs_properties_t *color_correction_filter_properties_v1(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -3.0, - 3.0, 0.01); + obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -3.0, 3.0, 0.01); - obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, - -2.0, 2.0, 0.01); - obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, - TEXT_BRIGHTNESS, -1.0, 1.0, 0.01); - obs_properties_add_float_slider(props, SETTING_SATURATION, - TEXT_SATURATION, -1.0, 5.0, 0.01); - obs_properties_add_float_slider(props, SETTING_HUESHIFT, TEXT_HUESHIFT, - -180.0, 180.0, 0.01); - obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, - 100, 1); + obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, -2.0, 2.0, 0.01); + obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, TEXT_BRIGHTNESS, -1.0, 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_SATURATION, TEXT_SATURATION, -1.0, 5.0, 0.01); + obs_properties_add_float_slider(props, SETTING_HUESHIFT, TEXT_HUESHIFT, -180.0, 180.0, 0.01); + obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, 100, 1); obs_properties_add_color_alpha(props, SETTING_COLOR, TEXT_COLOR); @@ -672,25 +628,17 @@ static obs_properties_t *color_correction_filter_properties_v2(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, - TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); + obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); - obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -3.0, - 3.0, 0.01); + obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -3.0, 3.0, 0.01); - obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, - -4.0, 4.0, 0.01); - obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, - TEXT_BRIGHTNESS, -1.0, 1.0, 0.0001); - obs_properties_add_float_slider(props, SETTING_SATURATION, - TEXT_SATURATION, -1.0, 5.0, 0.01); - obs_properties_add_float_slider(props, SETTING_HUESHIFT, TEXT_HUESHIFT, - -180.0, 180.0, 0.01); - obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, - 0.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, -4.0, 4.0, 0.01); + obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, TEXT_BRIGHTNESS, -1.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_SATURATION, TEXT_SATURATION, -1.0, 5.0, 0.01); + obs_properties_add_float_slider(props, SETTING_HUESHIFT, TEXT_HUESHIFT, -180.0, 180.0, 0.01); + obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0.0, 1.0, 0.0001); - obs_properties_add_color(props, SETTING_COLOR_MULTIPLY, - TEXT_COLOR_MULTIPLY); + obs_properties_add_color(props, SETTING_COLOR_MULTIPLY, TEXT_COLOR_MULTIPLY); obs_properties_add_color(props, SETTING_COLOR_ADD, TEXT_COLOR_ADD); UNUSED_PARAMETER(data); @@ -727,8 +675,8 @@ static void color_correction_filter_defaults_v2(obs_data_t *settings) obs_data_set_default_int(settings, SETTING_COLOR_ADD, 0x00000000); } -static enum gs_color_space color_correction_filter_get_color_space( - void *data, size_t count, const enum gs_color_space *preferred_spaces) +static enum gs_color_space color_correction_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -741,8 +689,7 @@ static enum gs_color_space color_correction_filter_get_color_space( struct color_correction_filter_data_v2 *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-filters/color-grade-filter.c b/plugins/obs-filters/color-grade-filter.c index b15709e84..4c9cb06c7 100644 --- a/plugins/obs-filters/color-grade-filter.c +++ b/plugins/obs-filters/color-grade-filter.c @@ -51,10 +51,8 @@ static const char *color_grade_filter_get_name(void *unused) return obs_module_text("ColorGradeFilter"); } -static gs_texture_t *make_clut_texture_png(const enum gs_color_format format, - const uint32_t image_width, - const uint32_t image_height, - const uint8_t *data) +static gs_texture_t *make_clut_texture_png(const enum gs_color_format format, const uint32_t image_width, + const uint32_t image_height, const uint8_t *data) { if (image_width % LUT_WIDTH != 0) return NULL; @@ -83,8 +81,7 @@ static gs_texture_t *make_clut_texture_png(const enum gs_color_format format, const uint32_t row_index = image_width * (z_y + y); for (uint32_t x = 0; x < LUT_WIDTH; ++x) { const uint32_t index = row_index + z_x + x; - memcpy(cursor, &data[pixel_size * index], - pixel_size); + memcpy(cursor, &data[pixel_size * index], pixel_size); cursor += pixel_size; } @@ -92,15 +89,13 @@ static gs_texture_t *make_clut_texture_png(const enum gs_color_format format, } gs_texture_t *const texture = - gs_voltexture_create(LUT_WIDTH, LUT_WIDTH, LUT_WIDTH, format, 1, - (const uint8_t **)&buffer, 0); + gs_voltexture_create(LUT_WIDTH, LUT_WIDTH, LUT_WIDTH, format, 1, (const uint8_t **)&buffer, 0); bfree(buffer); return texture; } -static bool get_cube_entry(FILE *const file, float *const red, - float *const green, float *const blue) +static bool get_cube_entry(FILE *const file, float *const red, float *const green, float *const blue) { bool data_found = false; @@ -115,11 +110,9 @@ static bool get_cube_entry(FILE *const file, float *const red, return data_found; } -static void *load_1d_lut(FILE *const file, const uint32_t width, float red, - float green, float blue) +static void *load_1d_lut(FILE *const file, const uint32_t width, float red, float green, float blue) { - const uint32_t data_size = - 4 * width * width * width * sizeof(struct half); + const uint32_t data_size = 4 * width * width * width * sizeof(struct half); struct half *values = bmalloc(data_size); size_t offset = 0; @@ -131,12 +124,9 @@ static void *load_1d_lut(FILE *const file, const uint32_t width, float red, break; } - values[offset++] = - half_from_float(gs_srgb_nonlinear_to_linear(red)); - values[offset++] = - half_from_float(gs_srgb_nonlinear_to_linear(green)); - values[offset++] = - half_from_float(gs_srgb_nonlinear_to_linear(blue)); + values[offset++] = half_from_float(gs_srgb_nonlinear_to_linear(red)); + values[offset++] = half_from_float(gs_srgb_nonlinear_to_linear(green)); + values[offset++] = half_from_float(gs_srgb_nonlinear_to_linear(blue)); values[offset++] = half_from_bits(0x3c00); // 1.0 data_found = get_cube_entry(file, &red, &green, &blue); @@ -145,11 +135,9 @@ static void *load_1d_lut(FILE *const file, const uint32_t width, float red, return values; } -static void *load_3d_lut(FILE *const file, const uint32_t width, float red, - float green, float blue) +static void *load_3d_lut(FILE *const file, const uint32_t width, float red, float green, float blue) { - const uint32_t data_size = - 4 * width * width * width * sizeof(struct half); + const uint32_t data_size = 4 * width * width * width * sizeof(struct half); struct half *values = bmalloc(data_size); size_t offset = 0; @@ -163,17 +151,12 @@ static void *load_3d_lut(FILE *const file, const uint32_t width, float red, break; } - values[offset++] = half_from_float( - gs_srgb_nonlinear_to_linear(red)); - values[offset++] = half_from_float( - gs_srgb_nonlinear_to_linear(green)); - values[offset++] = half_from_float( - gs_srgb_nonlinear_to_linear(blue)); - values[offset++] = - half_from_bits(0x3c00); // 1.0 + values[offset++] = half_from_float(gs_srgb_nonlinear_to_linear(red)); + values[offset++] = half_from_float(gs_srgb_nonlinear_to_linear(green)); + values[offset++] = half_from_float(gs_srgb_nonlinear_to_linear(blue)); + values[offset++] = half_from_bits(0x3c00); // 1.0 - data_found = get_cube_entry(file, &red, &green, - &blue); + data_found = get_cube_entry(file, &red, &green, &blue); } } } @@ -181,9 +164,8 @@ static void *load_3d_lut(FILE *const file, const uint32_t width, float red, return values; } -static void *load_cube_file(const char *const path, uint32_t *const width, - struct vec3 *domain_min, struct vec3 *domain_max, - enum clut_dimension *dim) +static void *load_cube_file(const char *const path, uint32_t *const width, struct vec3 *domain_min, + struct vec3 *domain_max, enum clut_dimension *dim) { void *data = NULL; @@ -199,16 +181,13 @@ static void *load_cube_file(const char *const path, uint32_t *const width, unsigned u; float f[3]; while (fgets(line, sizeof(line), file)) { - if (sscanf(line, "%f %f %f", &red, &green, &blue) == - 3) { + if (sscanf(line, "%f %f %f", &red, &green, &blue) == 3) { /* no more metadata */ data_found = true; break; - } else if (sscanf(line, "DOMAIN_MIN %f %f %f", &f[0], - &f[1], &f[2]) == 3) { + } else if (sscanf(line, "DOMAIN_MIN %f %f %f", &f[0], &f[1], &f[2]) == 3) { vec3_set(domain_min, f[0], f[1], f[2]); - } else if (sscanf(line, "DOMAIN_MAX %f %f %f", &f[0], - &f[1], &f[2]) == 3) { + } else if (sscanf(line, "DOMAIN_MAX %f %f %f", &f[0], &f[1], &f[2]) == 3) { vec3_set(domain_max, f[0], f[1], f[2]); } else if (sscanf(line, "LUT_1D_SIZE %u", &u) == 1) { width_1d = u; @@ -217,24 +196,19 @@ static void *load_cube_file(const char *const path, uint32_t *const width, } } - if (domain_min->x >= domain_max->x || - domain_min->y >= domain_max->y || + if (domain_min->x >= domain_max->x || domain_min->y >= domain_max->y || domain_min->z >= domain_max->z) { - blog(LOG_WARNING, - "Invalid CUBE LUT domain: [%f, %f], [%f, %f], [%f, %f]", - domain_min->x, domain_max->x, domain_min->y, - domain_max->y, domain_min->z, domain_max->z); + blog(LOG_WARNING, "Invalid CUBE LUT domain: [%f, %f], [%f, %f], [%f, %f]", domain_min->x, + domain_max->x, domain_min->y, domain_max->y, domain_min->z, domain_max->z); } else if (data_found) { if (width_1d > 0) { - data = load_1d_lut(file, width_1d, red, green, - blue); + data = load_1d_lut(file, width_1d, red, green, blue); if (data) { *width = width_1d; *dim = CLUT_1D; } } else if (width_3d > 0) { - data = load_3d_lut(file, width_3d, red, green, - blue); + data = load_3d_lut(file, width_3d, red, green, blue); if (data) { *width = width_3d; *dim = CLUT_3D; @@ -256,10 +230,8 @@ static void color_grade_filter_update(void *data, obs_data_t *settings) if (path && (*path == '\0')) path = NULL; - const double clut_amount = - obs_data_get_double(settings, SETTING_CLUT_AMOUNT); - const bool passthrough_alpha = - obs_data_get_bool(settings, SETTING_PASSTHROUGH_ALPHA); + const double clut_amount = obs_data_get_double(settings, SETTING_CLUT_AMOUNT); + const bool passthrough_alpha = obs_data_get_bool(settings, SETTING_PASSTHROUGH_ALPHA); bfree(filter->file); if (path) @@ -286,9 +258,8 @@ static void color_grade_filter_update(void *data, obs_data_t *settings) const char *const ext = os_get_path_extension(path); if (ext && astrcmpi(ext, ".cube") == 0) { - filter->cube_data = load_cube_file( - path, &filter->cube_width, &filter->domain_min, - &filter->domain_max, &clut_dim); + filter->cube_data = load_cube_file(path, &filter->cube_width, &filter->domain_min, + &filter->domain_max, &clut_dim); } else { gs_image_file_init(&filter->image, path); filter->cube_width = LUT_WIDTH; @@ -297,12 +268,9 @@ static void color_grade_filter_update(void *data, obs_data_t *settings) if (clut_dim == CLUT_1D) { clut_texture_name = "clut_1d"; tech_name = "Draw1D"; - } else if ((filter->domain_min.x > 0.f) || - (filter->domain_min.y > 0.f) || - (filter->domain_min.z > 0.f) || - (filter->domain_max.x < 1.f) || - (filter->domain_max.y < 1.f) || - (filter->domain_max.z < 1.f)) { + } else if ((filter->domain_min.x > 0.f) || (filter->domain_min.y > 0.f) || + (filter->domain_min.z > 0.f) || (filter->domain_max.x < 1.f) || + (filter->domain_max.y < 1.f) || (filter->domain_max.z < 1.f)) { tech_name = "DrawDomain3D"; } else if (clut_amount < 1.0) { tech_name = "DrawAmount3D"; @@ -315,50 +283,37 @@ static void color_grade_filter_update(void *data, obs_data_t *settings) if (path) { if (filter->image.loaded) { - filter->target = make_clut_texture_png( - filter->image.format, filter->image.cx, - filter->image.cy, filter->image.texture_data); + filter->target = make_clut_texture_png(filter->image.format, filter->image.cx, filter->image.cy, + filter->image.texture_data); const float width_i = 1.0f / (float)LUT_WIDTH; const float clut_scale = 1.0f - width_i; const float offset = 0.5f * width_i; - vec3_set(&filter->clut_scale, clut_scale, clut_scale, - clut_scale); + vec3_set(&filter->clut_scale, clut_scale, clut_scale, clut_scale); vec3_set(&filter->clut_offset, offset, offset, offset); } else if (filter->cube_data) { const uint32_t width = filter->cube_width; if (clut_dim == CLUT_1D) { - filter->target = gs_texture_create( - width, 1, GS_RGBA16F, 1, - (const uint8_t **)&filter->cube_data, - 0); + filter->target = gs_texture_create(width, 1, GS_RGBA16F, 1, + (const uint8_t **)&filter->cube_data, 0); } else { - filter->target = gs_voltexture_create( - width, width, width, GS_RGBA16F, 1, - (const uint8_t **)&filter->cube_data, - 0); + filter->target = gs_voltexture_create(width, width, width, GS_RGBA16F, 1, + (const uint8_t **)&filter->cube_data, 0); } struct vec3 domain_scale; - vec3_sub(&domain_scale, &filter->domain_max, - &filter->domain_min); + vec3_sub(&domain_scale, &filter->domain_max, &filter->domain_min); const float width_minus_one = (float)(width - 1); - vec3_set(&filter->clut_scale, width_minus_one, - width_minus_one, width_minus_one); - vec3_div(&filter->clut_scale, &filter->clut_scale, - &domain_scale); + vec3_set(&filter->clut_scale, width_minus_one, width_minus_one, width_minus_one); + vec3_div(&filter->clut_scale, &filter->clut_scale, &domain_scale); vec3_neg(&filter->clut_offset, &filter->domain_min); - vec3_mul(&filter->clut_offset, &filter->clut_offset, - &filter->clut_scale); + vec3_mul(&filter->clut_offset, &filter->clut_offset, &filter->clut_scale); /* want normalized UVW */ - vec3_divf(&filter->clut_scale, &filter->clut_scale, - (float)width); - vec3_addf(&filter->clut_offset, &filter->clut_offset, - 0.5f); - vec3_divf(&filter->clut_offset, &filter->clut_offset, - (float)width); + vec3_divf(&filter->clut_scale, &filter->clut_scale, (float)width); + vec3_addf(&filter->clut_offset, &filter->clut_offset, 0.5f); + vec3_divf(&filter->clut_offset, &filter->clut_offset, (float)width); } } @@ -401,14 +356,11 @@ static obs_properties_t *color_grade_filter_properties(void *data) if (slash) dstr_resize(&path, slash - path.array + 1); - obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, - TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); - obs_properties_add_path(props, SETTING_IMAGE_PATH, TEXT_IMAGE_PATH, - OBS_PATH_FILE, filter_str.array, path.array); - obs_properties_add_float_slider(props, SETTING_CLUT_AMOUNT, TEXT_AMOUNT, - 0, 1, 0.0001); - obs_properties_add_bool(props, SETTING_PASSTHROUGH_ALPHA, - TEXT_PASSTHROUGH_ALPHA); + obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); + obs_properties_add_path(props, SETTING_IMAGE_PATH, TEXT_IMAGE_PATH, OBS_PATH_FILE, filter_str.array, + path.array); + obs_properties_add_float_slider(props, SETTING_CLUT_AMOUNT, TEXT_AMOUNT, 0, 1, 0.0001); + obs_properties_add_bool(props, SETTING_PASSTHROUGH_ALPHA, TEXT_PASSTHROUGH_ALPHA); dstr_free(&filter_str); dstr_free(&path); @@ -416,11 +368,9 @@ static obs_properties_t *color_grade_filter_properties(void *data) return props; } -static void *color_grade_filter_create(obs_data_t *settings, - obs_source_t *context) +static void *color_grade_filter_create(obs_data_t *settings, obs_source_t *context) { - struct lut_filter_data *filter = - bzalloc(sizeof(struct lut_filter_data)); + struct lut_filter_data *filter = bzalloc(sizeof(struct lut_filter_data)); filter->context = context; obs_source_update(context, settings); @@ -461,55 +411,43 @@ static void color_grade_filter_render(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { - gs_eparam_t *param = gs_effect_get_param_by_name( - filter->effect, filter->clut_texture_name); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { + gs_eparam_t *param = gs_effect_get_param_by_name(filter->effect, filter->clut_texture_name); gs_effect_set_texture_srgb(param, filter->target); - param = gs_effect_get_param_by_name(filter->effect, - "clut_amount"); + param = gs_effect_get_param_by_name(filter->effect, "clut_amount"); gs_effect_set_float(param, filter->clut_amount); - param = gs_effect_get_param_by_name(filter->effect, - "clut_scale"); + param = gs_effect_get_param_by_name(filter->effect, "clut_scale"); gs_effect_set_vec3(param, &filter->clut_scale); - param = gs_effect_get_param_by_name(filter->effect, - "clut_offset"); + param = gs_effect_get_param_by_name(filter->effect, "clut_offset"); gs_effect_set_vec3(param, &filter->clut_offset); - param = gs_effect_get_param_by_name(filter->effect, - "domain_min"); + param = gs_effect_get_param_by_name(filter->effect, "domain_min"); gs_effect_set_vec3(param, &filter->domain_min); - param = gs_effect_get_param_by_name(filter->effect, - "domain_max"); + param = gs_effect_get_param_by_name(filter->effect, "domain_max"); gs_effect_set_vec3(param, &filter->domain_max); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_tech_end(filter->context, - filter->effect, 0, 0, - filter->tech_name); + obs_source_process_filter_tech_end(filter->context, filter->effect, 0, 0, filter->tech_name); gs_blend_state_pop(); } } } -static enum gs_color_space -color_grade_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space color_grade_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -522,8 +460,7 @@ color_grade_filter_get_color_space(void *data, size_t count, struct lut_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-filters/color-key-filter.c b/plugins/obs-filters/color-key-filter.c index 52374c2a4..1edecfebc 100644 --- a/plugins/obs-filters/color-key-filter.c +++ b/plugins/obs-filters/color-key-filter.c @@ -81,19 +81,15 @@ static const char *color_key_name(void *unused) return obs_module_text("ColorKeyFilter"); } -static inline void -color_settings_update_v1(struct color_key_filter_data *filter, - obs_data_t *settings) +static inline void color_settings_update_v1(struct color_key_filter_data *filter, obs_data_t *settings) { - uint32_t opacity = - (uint32_t)obs_data_get_int(settings, SETTING_OPACITY); + uint32_t opacity = (uint32_t)obs_data_get_int(settings, SETTING_OPACITY); uint32_t color = 0xFFFFFF | (((opacity * 255) / 100) << 24); double contrast = obs_data_get_double(settings, SETTING_CONTRAST); double brightness = obs_data_get_double(settings, SETTING_BRIGHTNESS); double gamma = obs_data_get_double(settings, SETTING_GAMMA); - contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) - : (contrast + 1.0); + contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) : (contrast + 1.0); brightness *= 0.5; @@ -106,34 +102,27 @@ color_settings_update_v1(struct color_key_filter_data *filter, vec4_from_rgba(&filter->color, color); } -static inline void -color_settings_update_v2(struct color_key_filter_data_v2 *filter, - obs_data_t *settings) +static inline void color_settings_update_v2(struct color_key_filter_data_v2 *filter, obs_data_t *settings) { filter->opacity = (float)obs_data_get_double(settings, SETTING_OPACITY); double contrast = obs_data_get_double(settings, SETTING_CONTRAST); - contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) - : (contrast + 1.0); + contrast = (contrast < 0.0) ? (1.0 / (-contrast + 1.0)) : (contrast + 1.0); filter->contrast = (float)contrast; - filter->brightness = - (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); + filter->brightness = (float)obs_data_get_double(settings, SETTING_BRIGHTNESS); double gamma = obs_data_get_double(settings, SETTING_GAMMA); gamma = (gamma < 0.0) ? (-gamma + 1.0) : (1.0 / (gamma + 1.0)); filter->gamma = (float)gamma; } -static inline void key_settings_update_v1(struct color_key_filter_data *filter, - obs_data_t *settings) +static inline void key_settings_update_v1(struct color_key_filter_data *filter, obs_data_t *settings) { int64_t similarity = obs_data_get_int(settings, SETTING_SIMILARITY); int64_t smoothness = obs_data_get_int(settings, SETTING_SMOOTHNESS); - uint32_t key_color = - (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); - const char *key_type = - obs_data_get_string(settings, SETTING_COLOR_TYPE); + uint32_t key_color = (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); + const char *key_type = obs_data_get_string(settings, SETTING_COLOR_TYPE); if (strcmp(key_type, "green") == 0) key_color = 0x00FF00; @@ -150,16 +139,12 @@ static inline void key_settings_update_v1(struct color_key_filter_data *filter, filter->smoothness = (float)smoothness / 1000.0f; } -static inline void -key_settings_update_v2(struct color_key_filter_data_v2 *filter, - obs_data_t *settings) +static inline void key_settings_update_v2(struct color_key_filter_data_v2 *filter, obs_data_t *settings) { int64_t similarity = obs_data_get_int(settings, SETTING_SIMILARITY); int64_t smoothness = obs_data_get_int(settings, SETTING_SMOOTHNESS); - uint32_t key_color = - (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); - const char *key_type = - obs_data_get_string(settings, SETTING_COLOR_TYPE); + uint32_t key_color = (uint32_t)obs_data_get_int(settings, SETTING_KEY_COLOR); + const char *key_type = obs_data_get_string(settings, SETTING_COLOR_TYPE); if (strcmp(key_type, "green") == 0) key_color = 0x00FF00; @@ -220,8 +205,7 @@ static void color_key_destroy_v2(void *data) static void *color_key_create_v1(obs_data_t *settings, obs_source_t *context) { - struct color_key_filter_data *filter = - bzalloc(sizeof(struct color_key_filter_data)); + struct color_key_filter_data *filter = bzalloc(sizeof(struct color_key_filter_data)); char *effect_path = obs_module_file("color_key_filter.effect"); filter->context = context; @@ -230,20 +214,13 @@ static void *color_key_create_v1(obs_data_t *settings, obs_source_t *context) filter->effect = gs_effect_create_from_file(effect_path, NULL); if (filter->effect) { - filter->color_param = - gs_effect_get_param_by_name(filter->effect, "color"); - filter->contrast_param = - gs_effect_get_param_by_name(filter->effect, "contrast"); - filter->brightness_param = gs_effect_get_param_by_name( - filter->effect, "brightness"); - filter->gamma_param = - gs_effect_get_param_by_name(filter->effect, "gamma"); - filter->key_color_param = gs_effect_get_param_by_name( - filter->effect, "key_color"); - filter->similarity_param = gs_effect_get_param_by_name( - filter->effect, "similarity"); - filter->smoothness_param = gs_effect_get_param_by_name( - filter->effect, "smoothness"); + filter->color_param = gs_effect_get_param_by_name(filter->effect, "color"); + filter->contrast_param = gs_effect_get_param_by_name(filter->effect, "contrast"); + filter->brightness_param = gs_effect_get_param_by_name(filter->effect, "brightness"); + filter->gamma_param = gs_effect_get_param_by_name(filter->effect, "gamma"); + filter->key_color_param = gs_effect_get_param_by_name(filter->effect, "key_color"); + filter->similarity_param = gs_effect_get_param_by_name(filter->effect, "similarity"); + filter->smoothness_param = gs_effect_get_param_by_name(filter->effect, "smoothness"); } obs_leave_graphics(); @@ -261,8 +238,7 @@ static void *color_key_create_v1(obs_data_t *settings, obs_source_t *context) static void *color_key_create_v2(obs_data_t *settings, obs_source_t *context) { - struct color_key_filter_data_v2 *filter = - bzalloc(sizeof(struct color_key_filter_data_v2)); + struct color_key_filter_data_v2 *filter = bzalloc(sizeof(struct color_key_filter_data_v2)); char *effect_path = obs_module_file("color_key_filter_v2.effect"); filter->context = context; @@ -271,20 +247,13 @@ static void *color_key_create_v2(obs_data_t *settings, obs_source_t *context) filter->effect = gs_effect_create_from_file(effect_path, NULL); if (filter->effect) { - filter->opacity_param = - gs_effect_get_param_by_name(filter->effect, "opacity"); - filter->contrast_param = - gs_effect_get_param_by_name(filter->effect, "contrast"); - filter->brightness_param = gs_effect_get_param_by_name( - filter->effect, "brightness"); - filter->gamma_param = - gs_effect_get_param_by_name(filter->effect, "gamma"); - filter->key_color_param = gs_effect_get_param_by_name( - filter->effect, "key_color"); - filter->similarity_param = gs_effect_get_param_by_name( - filter->effect, "similarity"); - filter->smoothness_param = gs_effect_get_param_by_name( - filter->effect, "smoothness"); + filter->opacity_param = gs_effect_get_param_by_name(filter->effect, "opacity"); + filter->contrast_param = gs_effect_get_param_by_name(filter->effect, "contrast"); + filter->brightness_param = gs_effect_get_param_by_name(filter->effect, "brightness"); + filter->gamma_param = gs_effect_get_param_by_name(filter->effect, "gamma"); + filter->key_color_param = gs_effect_get_param_by_name(filter->effect, "key_color"); + filter->similarity_param = gs_effect_get_param_by_name(filter->effect, "similarity"); + filter->smoothness_param = gs_effect_get_param_by_name(filter->effect, "smoothness"); } obs_leave_graphics(); @@ -304,8 +273,7 @@ static void color_key_render_v1(void *data, gs_effect_t *effect) { struct color_key_filter_data *filter = data; - if (!obs_source_process_filter_begin(filter->context, GS_RGBA, - OBS_ALLOW_DIRECT_RENDERING)) + if (!obs_source_process_filter_begin(filter->context, GS_RGBA, OBS_ALLOW_DIRECT_RENDERING)) return; gs_effect_set_vec4(filter->color_param, &filter->color); @@ -334,49 +302,37 @@ static void color_key_render_v2(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { - gs_effect_set_float(filter->opacity_param, - filter->opacity); - gs_effect_set_float(filter->contrast_param, - filter->contrast); - gs_effect_set_float(filter->brightness_param, - filter->brightness); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { + gs_effect_set_float(filter->opacity_param, filter->opacity); + gs_effect_set_float(filter->contrast_param, filter->contrast); + gs_effect_set_float(filter->brightness_param, filter->brightness); gs_effect_set_float(filter->gamma_param, filter->gamma); - gs_effect_set_vec4(filter->key_color_param, - &filter->key_color); - gs_effect_set_float(filter->similarity_param, - filter->similarity); - gs_effect_set_float(filter->smoothness_param, - filter->smoothness); + gs_effect_set_vec4(filter->key_color_param, &filter->key_color); + gs_effect_set_float(filter->similarity_param, filter->similarity); + gs_effect_set_float(filter->smoothness_param, filter->smoothness); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_end(filter->context, - filter->effect, 0, 0); + obs_source_process_filter_end(filter->context, filter->effect, 0, 0); gs_blend_state_pop(); } } } -static bool key_type_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool key_type_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { const char *type = obs_data_get_string(settings, SETTING_COLOR_TYPE); bool custom = strcmp(type, "custom") == 0; - obs_property_set_visible(obs_properties_get(props, SETTING_KEY_COLOR), - custom); + obs_property_set_visible(obs_properties_get(props, SETTING_KEY_COLOR), custom); UNUSED_PARAMETER(p); return true; @@ -386,33 +342,24 @@ static obs_properties_t *color_key_properties_v1(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, - TEXT_COLOR_TYPE, - OBS_COMBO_TYPE_LIST, + obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, TEXT_COLOR_TYPE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("Green"), "green"); obs_property_list_add_string(p, obs_module_text("Blue"), "blue"); obs_property_list_add_string(p, obs_module_text("Red"), "red"); obs_property_list_add_string(p, obs_module_text("Magenta"), "magenta"); - obs_property_list_add_string(p, obs_module_text("CustomColor"), - "custom"); + obs_property_list_add_string(p, obs_module_text("CustomColor"), "custom"); obs_property_set_modified_callback(p, key_type_changed); obs_properties_add_color(props, SETTING_KEY_COLOR, TEXT_KEY_COLOR); - obs_properties_add_int_slider(props, SETTING_SIMILARITY, - TEXT_SIMILARITY, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, - TEXT_SMOOTHNESS, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SIMILARITY, TEXT_SIMILARITY, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, TEXT_SMOOTHNESS, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, - 100, 1); - obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, - -1.0, 1.0, 0.01); - obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, - TEXT_BRIGHTNESS, -1.0, 1.0, 0.01); - obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, - 1.0, 0.01); + obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, 100, 1); + obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, -1.0, 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, TEXT_BRIGHTNESS, -1.0, 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, 1.0, 0.01); UNUSED_PARAMETER(data); return props; @@ -422,36 +369,26 @@ static obs_properties_t *color_key_properties_v2(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, - TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); + obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); - obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, - TEXT_COLOR_TYPE, - OBS_COMBO_TYPE_LIST, + obs_property_t *p = obs_properties_add_list(props, SETTING_COLOR_TYPE, TEXT_COLOR_TYPE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("Green"), "green"); obs_property_list_add_string(p, obs_module_text("Blue"), "blue"); obs_property_list_add_string(p, obs_module_text("Red"), "red"); obs_property_list_add_string(p, obs_module_text("Magenta"), "magenta"); - obs_property_list_add_string(p, obs_module_text("CustomColor"), - "custom"); + obs_property_list_add_string(p, obs_module_text("CustomColor"), "custom"); obs_property_set_modified_callback(p, key_type_changed); obs_properties_add_color(props, SETTING_KEY_COLOR, TEXT_KEY_COLOR); - obs_properties_add_int_slider(props, SETTING_SIMILARITY, - TEXT_SIMILARITY, 1, 1000, 1); - obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, - TEXT_SMOOTHNESS, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SIMILARITY, TEXT_SIMILARITY, 1, 1000, 1); + obs_properties_add_int_slider(props, SETTING_SMOOTHNESS, TEXT_SMOOTHNESS, 1, 1000, 1); - obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, - 0.0, 1.0, 0.0001); - obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, - -4.0, 4.0, 0.01); - obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, - TEXT_BRIGHTNESS, -1.0, 1.0, 0.0001); - obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, - 1.0, 0.01); + obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_CONTRAST, TEXT_CONTRAST, -4.0, 4.0, 0.01); + obs_properties_add_float_slider(props, SETTING_BRIGHTNESS, TEXT_BRIGHTNESS, -1.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_GAMMA, TEXT_GAMMA, -1.0, 1.0, 0.01); UNUSED_PARAMETER(data); return props; @@ -481,9 +418,8 @@ static void color_key_defaults_v2(obs_data_t *settings) obs_data_set_default_int(settings, SETTING_SMOOTHNESS, 50); } -static enum gs_color_space -color_key_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space color_key_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -496,8 +432,7 @@ color_key_get_color_space(void *data, size_t count, struct color_key_filter_data_v2 *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-filters/compressor-filter.c b/plugins/obs-filters/compressor-filter.c index 11b9a635b..649952b6d 100644 --- a/plugins/obs-filters/compressor-filter.c +++ b/plugins/obs-filters/compressor-filter.c @@ -10,9 +10,8 @@ /* -------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[compressor: '%s'] " format, \ - obs_source_get_name(cd->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[compressor: '%s'] " format, obs_source_get_name(cd->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -96,8 +95,7 @@ static inline obs_source_t *get_sidechain(struct compressor_data *cd) return NULL; } -static inline void get_sidechain_data(struct compressor_data *cd, - const uint32_t num_samples) +static inline void get_sidechain_data(struct compressor_data *cd, const uint32_t num_samples) { size_t data_size = cd->envelope_buf_len * sizeof(float); if (!data_size) @@ -113,8 +111,7 @@ static inline void get_sidechain_data(struct compressor_data *cd, } for (size_t i = 0; i < cd->num_channels; i++) - deque_pop_front(&cd->sidechain_data[i], cd->sidechain_buf[i], - data_size); + deque_pop_front(&cd->sidechain_data[i], cd->sidechain_buf[i], data_size); pthread_mutex_unlock(&cd->sidechain_mutex); return; @@ -130,8 +127,7 @@ static void resize_env_buffer(struct compressor_data *cd, size_t len) cd->envelope_buf = brealloc(cd->envelope_buf, len * sizeof(float)); for (size_t i = 0; i < cd->num_channels; i++) - cd->sidechain_buf[i] = - brealloc(cd->sidechain_buf[i], len * sizeof(float)); + cd->sidechain_buf[i] = brealloc(cd->sidechain_buf[i], len * sizeof(float)); } static inline float gain_coefficient(uint32_t sample_rate, float time) @@ -145,8 +141,7 @@ static const char *compressor_name(void *unused) return obs_module_text("Compressor"); } -static void sidechain_capture(void *param, obs_source_t *source, - const struct audio_data *audio_data, bool muted) +static void sidechain_capture(void *param, obs_source_t *source, const struct audio_data *audio_data, bool muted) { struct compressor_data *cd = param; @@ -164,21 +159,17 @@ static void sidechain_capture(void *param, obs_source_t *source, if (cd->sidechain_data[0].size > expected_size * 2) { for (size_t i = 0; i < cd->num_channels; i++) { - deque_pop_front(&cd->sidechain_data[i], NULL, - expected_size); + deque_pop_front(&cd->sidechain_data[i], NULL, expected_size); } } if (muted) { for (size_t i = 0; i < cd->num_channels; i++) { - deque_push_back_zero(&cd->sidechain_data[i], - audio_data->frames * - sizeof(float)); + deque_push_back_zero(&cd->sidechain_data[i], audio_data->frames * sizeof(float)); } } else { for (size_t i = 0; i < cd->num_channels; i++) { - deque_push_back(&cd->sidechain_data[i], - audio_data->data[i], + deque_push_back(&cd->sidechain_data[i], audio_data->data[i], audio_data->frames * sizeof(float)); } } @@ -191,29 +182,23 @@ static void compressor_update(void *data, obs_data_t *s) { struct compressor_data *cd = data; - const uint32_t sample_rate = - audio_output_get_sample_rate(obs_get_audio()); + const uint32_t sample_rate = audio_output_get_sample_rate(obs_get_audio()); const size_t num_channels = audio_output_get_channels(obs_get_audio()); const float attack_time_ms = (float)obs_data_get_int(s, S_ATTACK_TIME); - const float release_time_ms = - (float)obs_data_get_int(s, S_RELEASE_TIME); - const float output_gain_db = - (float)obs_data_get_double(s, S_OUTPUT_GAIN); + const float release_time_ms = (float)obs_data_get_int(s, S_RELEASE_TIME); + const float output_gain_db = (float)obs_data_get_double(s, S_OUTPUT_GAIN); const char *sidechain_name = obs_data_get_string(s, S_SIDECHAIN_SOURCE); cd->ratio = (float)obs_data_get_double(s, S_RATIO); cd->threshold = (float)obs_data_get_double(s, S_THRESHOLD); - cd->attack_gain = - gain_coefficient(sample_rate, attack_time_ms / MS_IN_S_F); - cd->release_gain = - gain_coefficient(sample_rate, release_time_ms / MS_IN_S_F); + cd->attack_gain = gain_coefficient(sample_rate, attack_time_ms / MS_IN_S_F); + cd->release_gain = gain_coefficient(sample_rate, release_time_ms / MS_IN_S_F); cd->output_gain = db_to_mul(output_gain_db); cd->num_channels = num_channels; cd->sample_rate = sample_rate; cd->slope = 1.0f - (1.0f / cd->ratio); - bool valid_sidechain = *sidechain_name && - strcmp(sidechain_name, "none") != 0; + bool valid_sidechain = *sidechain_name && strcmp(sidechain_name, "none") != 0; obs_weak_source_t *old_weak_sidechain = NULL; pthread_mutex_lock(&cd->sidechain_update_mutex); @@ -228,8 +213,7 @@ static void compressor_update(void *data, obs_data_t *s) cd->sidechain_name = NULL; } else { - if (!cd->sidechain_name || - strcmp(cd->sidechain_name, sidechain_name) != 0) { + if (!cd->sidechain_name || strcmp(cd->sidechain_name, sidechain_name) != 0) { if (cd->weak_sidechain) { old_weak_sidechain = cd->weak_sidechain; cd->weak_sidechain = NULL; @@ -244,12 +228,10 @@ static void compressor_update(void *data, obs_data_t *s) pthread_mutex_unlock(&cd->sidechain_update_mutex); if (old_weak_sidechain) { - obs_source_t *old_sidechain = - obs_weak_source_get_source(old_weak_sidechain); + obs_source_t *old_sidechain = obs_weak_source_get_source(old_weak_sidechain); if (old_sidechain) { - obs_source_remove_audio_capture_callback( - old_sidechain, sidechain_capture, cd); + obs_source_remove_audio_capture_callback(old_sidechain, sidechain_capture, cd); obs_source_release(old_sidechain); } @@ -290,8 +272,7 @@ static void compressor_destroy(void *data) if (cd->weak_sidechain) { obs_source_t *sidechain = get_sidechain(cd); if (sidechain) { - obs_source_remove_audio_capture_callback( - sidechain, sidechain_capture, cd); + obs_source_remove_audio_capture_callback(sidechain, sidechain_capture, cd); obs_source_release(sidechain); } @@ -310,8 +291,7 @@ static void compressor_destroy(void *data) bfree(cd); } -static void analyze_envelope(struct compressor_data *cd, float **samples, - const uint32_t num_samples) +static void analyze_envelope(struct compressor_data *cd, float **samples, const uint32_t num_samples) { if (cd->envelope_buf_len < num_samples) { resize_env_buffer(cd, num_samples); @@ -340,8 +320,7 @@ static void analyze_envelope(struct compressor_data *cd, float **samples, cd->envelope = cd->envelope_buf[num_samples - 1]; } -static void analyze_sidechain(struct compressor_data *cd, - const uint32_t num_samples) +static void analyze_sidechain(struct compressor_data *cd, const uint32_t num_samples) { if (cd->envelope_buf_len < num_samples) { resize_env_buffer(cd, num_samples); @@ -374,8 +353,7 @@ static void analyze_sidechain(struct compressor_data *cd, cd->envelope = cd->envelope_buf[num_samples - 1]; } -static inline void process_compression(const struct compressor_data *cd, - float **samples, uint32_t num_samples) +static inline void process_compression(const struct compressor_data *cd, float **samples, uint32_t num_samples) { for (size_t i = 0; i < num_samples; ++i) { const float env_db = mul_to_db(cd->envelope_buf[i]); @@ -409,16 +387,12 @@ static void compressor_tick(void *data, float seconds) pthread_mutex_unlock(&cd->sidechain_update_mutex); if (new_name) { - obs_source_t *sidechain = - *new_name ? obs_get_source_by_name(new_name) : NULL; - obs_weak_source_t *weak_sidechain = - sidechain ? obs_source_get_weak_source(sidechain) - : NULL; + obs_source_t *sidechain = *new_name ? obs_get_source_by_name(new_name) : NULL; + obs_weak_source_t *weak_sidechain = sidechain ? obs_source_get_weak_source(sidechain) : NULL; pthread_mutex_lock(&cd->sidechain_update_mutex); - if (cd->sidechain_name && - strcmp(cd->sidechain_name, new_name) == 0) { + if (cd->sidechain_name && strcmp(cd->sidechain_name, new_name) == 0) { cd->weak_sidechain = weak_sidechain; weak_sidechain = NULL; } @@ -426,8 +400,7 @@ static void compressor_tick(void *data, float seconds) pthread_mutex_unlock(&cd->sidechain_update_mutex); if (sidechain) { - obs_source_add_audio_capture_callback( - sidechain, sidechain_capture, cd); + obs_source_add_audio_capture_callback(sidechain, sidechain_capture, cd); obs_weak_source_release(weak_sidechain); obs_source_release(sidechain); @@ -439,8 +412,7 @@ static void compressor_tick(void *data, float seconds) UNUSED_PARAMETER(seconds); } -static struct obs_audio_data * -compressor_filter_audio(void *data, struct obs_audio_data *audio) +static struct obs_audio_data *compressor_filter_audio(void *data, struct obs_audio_data *audio) { struct compressor_data *cd = data; @@ -503,30 +475,21 @@ static obs_properties_t *compressor_properties(void *data) if (cd) parent = obs_filter_get_parent(cd->context); - p = obs_properties_add_float_slider(props, S_RATIO, TEXT_RATIO, - MIN_RATIO, MAX_RATIO, 0.5); + p = obs_properties_add_float_slider(props, S_RATIO, TEXT_RATIO, MIN_RATIO, MAX_RATIO, 0.5); obs_property_float_set_suffix(p, ":1"); - p = obs_properties_add_float_slider(props, S_THRESHOLD, TEXT_THRESHOLD, - MIN_THRESHOLD_DB, MAX_THRESHOLD_DB, + p = obs_properties_add_float_slider(props, S_THRESHOLD, TEXT_THRESHOLD, MIN_THRESHOLD_DB, MAX_THRESHOLD_DB, 0.1); obs_property_float_set_suffix(p, " dB"); - p = obs_properties_add_int_slider(props, S_ATTACK_TIME, - TEXT_ATTACK_TIME, MIN_ATK_RLS_MS, - MAX_ATK_MS, 1); + p = obs_properties_add_int_slider(props, S_ATTACK_TIME, TEXT_ATTACK_TIME, MIN_ATK_RLS_MS, MAX_ATK_MS, 1); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_int_slider(props, S_RELEASE_TIME, - TEXT_RELEASE_TIME, MIN_ATK_RLS_MS, - MAX_RLS_MS, 1); + p = obs_properties_add_int_slider(props, S_RELEASE_TIME, TEXT_RELEASE_TIME, MIN_ATK_RLS_MS, MAX_RLS_MS, 1); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_float_slider(props, S_OUTPUT_GAIN, - TEXT_OUTPUT_GAIN, - MIN_OUTPUT_GAIN_DB, + p = obs_properties_add_float_slider(props, S_OUTPUT_GAIN, TEXT_OUTPUT_GAIN, MIN_OUTPUT_GAIN_DB, MAX_OUTPUT_GAIN_DB, 0.1); obs_property_float_set_suffix(p, " dB"); - obs_property_t *sources = obs_properties_add_list( - props, S_SIDECHAIN_SOURCE, TEXT_SIDECHAIN_SOURCE, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *sources = obs_properties_add_list(props, S_SIDECHAIN_SOURCE, TEXT_SIDECHAIN_SOURCE, + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(sources, obs_module_text("None"), "none"); diff --git a/plugins/obs-filters/crop-filter.c b/plugins/obs-filters/crop-filter.c index ea2df3efa..106346e62 100644 --- a/plugins/obs-filters/crop-filter.c +++ b/plugins/obs-filters/crop-filter.c @@ -47,12 +47,9 @@ static void *crop_filter_create(obs_data_t *settings, obs_source_t *context) return NULL; } - filter->param_mul = - gs_effect_get_param_by_name(filter->effect, "mul_val"); - filter->param_add = - gs_effect_get_param_by_name(filter->effect, "add_val"); - filter->param_multiplier = - gs_effect_get_param_by_name(filter->effect, "multiplier"); + filter->param_mul = gs_effect_get_param_by_name(filter->effect, "mul_val"); + filter->param_add = gs_effect_get_param_by_name(filter->effect, "add_val"); + filter->param_multiplier = gs_effect_get_param_by_name(filter->effect, "multiplier"); obs_source_update(context, settings); return filter; @@ -82,17 +79,12 @@ static void crop_filter_update(void *data, obs_data_t *settings) filter->abs_cy = (int)obs_data_get_int(settings, "cy"); } -static bool relative_clicked(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool relative_clicked(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { bool relative = obs_data_get_bool(settings, "relative"); - obs_property_set_description(obs_properties_get(props, "left"), - relative ? obs_module_text("Crop.Left") - : "X"); - obs_property_set_description(obs_properties_get(props, "top"), - relative ? obs_module_text("Crop.Top") - : "Y"); + obs_property_set_description(obs_properties_get(props, "left"), relative ? obs_module_text("Crop.Left") : "X"); + obs_property_set_description(obs_properties_get(props, "top"), relative ? obs_module_text("Crop.Top") : "Y"); obs_property_set_visible(obs_properties_get(props, "right"), relative); obs_property_set_visible(obs_properties_get(props, "bottom"), relative); @@ -107,23 +99,16 @@ static obs_properties_t *crop_filter_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *p = obs_properties_add_bool( - props, "relative", obs_module_text("Crop.Relative")); + obs_property_t *p = obs_properties_add_bool(props, "relative", obs_module_text("Crop.Relative")); obs_property_set_modified_callback(p, relative_clicked); - obs_properties_add_int(props, "left", obs_module_text("Crop.Left"), - -8192, 8192, 1); - obs_properties_add_int(props, "top", obs_module_text("Crop.Top"), -8192, - 8192, 1); - obs_properties_add_int(props, "right", obs_module_text("Crop.Right"), - -8192, 8192, 1); - obs_properties_add_int(props, "bottom", obs_module_text("Crop.Bottom"), - -8192, 8192, 1); - obs_properties_add_int(props, "cx", obs_module_text("Crop.Width"), 0, - 8192, 1); - obs_properties_add_int(props, "cy", obs_module_text("Crop.Height"), 0, - 8192, 1); + obs_properties_add_int(props, "left", obs_module_text("Crop.Left"), -8192, 8192, 1); + obs_properties_add_int(props, "top", obs_module_text("Crop.Top"), -8192, 8192, 1); + obs_properties_add_int(props, "right", obs_module_text("Crop.Right"), -8192, 8192, 1); + obs_properties_add_int(props, "bottom", obs_module_text("Crop.Bottom"), -8192, 8192, 1); + obs_properties_add_int(props, "cx", obs_module_text("Crop.Width"), 0, 8192, 1); + obs_properties_add_int(props, "cy", obs_module_text("Crop.Height"), 0, 8192, 1); UNUSED_PARAMETER(data); return props; @@ -134,8 +119,7 @@ static void crop_filter_defaults(obs_data_t *settings) obs_data_set_default_bool(settings, "relative", true); } -static void calc_crop_dimensions(struct crop_filter_data *filter, - struct vec2 *mul_val, struct vec2 *add_val) +static void calc_crop_dimensions(struct crop_filter_data *filter, struct vec2 *mul_val, struct vec2 *add_val) { obs_source_t *target = obs_filter_get_target(filter->context); uint32_t width; @@ -183,10 +167,8 @@ static void crop_filter_tick(void *data, float seconds) UNUSED_PARAMETER(seconds); } -static const char * -get_tech_name_and_multiplier(enum gs_color_space current_space, - enum gs_color_space source_space, - float *multiplier) +static const char *get_tech_name_and_multiplier(enum gs_color_space current_space, enum gs_color_space source_space, + float *multiplier) { const char *tech_name = "Draw"; *multiplier = 1.f; @@ -245,16 +227,12 @@ static void crop_filter_render(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); float multiplier; - const char *technique = get_tech_name_and_multiplier( - gs_get_color_space(), source_space, &multiplier); - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_NO_DIRECT_RENDERING)) { + const char *technique = get_tech_name_and_multiplier(gs_get_color_space(), source_space, &multiplier); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_NO_DIRECT_RENDERING)) { gs_effect_set_vec2(filter->param_mul, &filter->mul_val); gs_effect_set_vec2(filter->param_add, &filter->add_val); gs_effect_set_float(filter->param_multiplier, multiplier); @@ -262,10 +240,8 @@ static void crop_filter_render(void *data, gs_effect_t *effect) gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_tech_end(filter->context, - filter->effect, - filter->width, - filter->height, technique); + obs_source_process_filter_tech_end(filter->context, filter->effect, filter->width, filter->height, + technique); gs_blend_state_pop(); } @@ -283,9 +259,8 @@ static uint32_t crop_filter_height(void *data) return (uint32_t)crop->height; } -static enum gs_color_space -crop_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space crop_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { const enum gs_color_space potential_spaces[] = { GS_CS_SRGB, @@ -295,8 +270,7 @@ crop_filter_get_color_space(void *data, size_t count, struct crop_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); enum gs_color_space space = source_space; for (size_t i = 0; i < count; ++i) { diff --git a/plugins/obs-filters/eq-filter.c b/plugins/obs-filters/eq-filter.c index 6091a4a37..ad0e56b64 100644 --- a/plugins/obs-filters/eq-filter.c +++ b/plugins/obs-filters/eq-filter.c @@ -61,10 +61,8 @@ static obs_properties_t *eq_properties(void *unused) obs_properties_t *props = obs_properties_create(); obs_property_t *p; -#define make_db_slider(name) \ - p = obs_properties_add_float_slider(props, name, \ - obs_module_text("3BandEq." name), \ - -20.0f, 20.0, 0.1); \ +#define make_db_slider(name) \ + p = obs_properties_add_float_slider(props, name, obs_module_text("3BandEq." name), -20.0f, 20.0, 0.1); \ obs_property_float_set_suffix(p, " dB"); make_db_slider("high"); @@ -98,8 +96,7 @@ static void eq_destroy(void *data) #define EQ_EPSILON (1.0f / 4294967295.0f) -static inline float eq_process(struct eq_data *eq, struct eq_channel_state *c, - float sample) +static inline float eq_process(struct eq_data *eq, struct eq_channel_state *c, float sample) { float l, m, h; @@ -129,8 +126,7 @@ static inline float eq_process(struct eq_data *eq, struct eq_channel_state *c, return l + m + h; } -static struct obs_audio_data *eq_filter_audio(void *data, - struct obs_audio_data *audio) +static struct obs_audio_data *eq_filter_audio(void *data, struct obs_audio_data *audio) { struct eq_data *eq = data; const uint32_t frames = audio->frames; diff --git a/plugins/obs-filters/expander-filter.c b/plugins/obs-filters/expander-filter.c index e6779d2e8..e5aaf6dfd 100644 --- a/plugins/obs-filters/expander-filter.c +++ b/plugins/obs-filters/expander-filter.c @@ -10,9 +10,8 @@ /* -------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[expander/gate/upward compressor: '%s'] " format, \ - obs_source_get_name(cd->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[expander/gate/upward compressor: '%s'] " format, obs_source_get_name(cd->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -111,17 +110,14 @@ static void resize_env_buffer(struct expander_data *cd, size_t len) { cd->envelope_buf_len = len; for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) - cd->envelope_buf[i] = - brealloc(cd->envelope_buf[i], - cd->envelope_buf_len * sizeof(float)); + cd->envelope_buf[i] = brealloc(cd->envelope_buf[i], cd->envelope_buf_len * sizeof(float)); } static void resize_runaverage_buffer(struct expander_data *cd, size_t len) { cd->runaverage_len = len; for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) - cd->runaverage[i] = brealloc( - cd->runaverage[i], cd->runaverage_len * sizeof(float)); + cd->runaverage[i] = brealloc(cd->runaverage[i], cd->runaverage_len * sizeof(float)); } static void resize_env_in_buffer(struct expander_data *cd, size_t len) @@ -134,8 +130,7 @@ static void resize_gain_db_buffer(struct expander_data *cd, size_t len) { cd->gain_db_len = len; for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) - cd->gain_db[i] = brealloc(cd->gain_db[i], - cd->gain_db_len * sizeof(float)); + cd->gain_db[i] = brealloc(cd->gain_db[i], cd->gain_db_len * sizeof(float)); } static inline float gain_coefficient(uint32_t sample_rate, float time) @@ -161,14 +156,11 @@ static void expander_defaults(obs_data_t *s) bool is_expander_preset = true; if (strcmp(presets, "gate") == 0) is_expander_preset = false; - obs_data_set_default_string(s, S_PRESETS, - is_expander_preset ? "expander" : "gate"); - obs_data_set_default_double(s, S_RATIO, - is_expander_preset ? 2.0 : 10.0); + obs_data_set_default_string(s, S_PRESETS, is_expander_preset ? "expander" : "gate"); + obs_data_set_default_double(s, S_RATIO, is_expander_preset ? 2.0 : 10.0); obs_data_set_default_double(s, S_THRESHOLD, -40.0f); obs_data_set_default_int(s, S_ATTACK_TIME, 10); - obs_data_set_default_int(s, S_RELEASE_TIME, - is_expander_preset ? 50 : 125); + obs_data_set_default_int(s, S_RELEASE_TIME, is_expander_preset ? 50 : 125); obs_data_set_default_double(s, S_OUTPUT_GAIN, 0.0); obs_data_set_default_string(s, S_DETECTOR, "RMS"); } @@ -203,24 +195,18 @@ static void expander_update(void *data, obs_data_t *s) } } - const uint32_t sample_rate = - audio_output_get_sample_rate(obs_get_audio()); + const uint32_t sample_rate = audio_output_get_sample_rate(obs_get_audio()); const size_t num_channels = audio_output_get_channels(obs_get_audio()); const float attack_time_ms = (float)obs_data_get_int(s, S_ATTACK_TIME); - const float release_time_ms = - (float)obs_data_get_int(s, S_RELEASE_TIME); - const float output_gain_db = - (float)obs_data_get_double(s, S_OUTPUT_GAIN); - const float knee = cd->is_upwcomp ? (float)obs_data_get_int(s, S_KNEE) - : 0.0f; + const float release_time_ms = (float)obs_data_get_int(s, S_RELEASE_TIME); + const float output_gain_db = (float)obs_data_get_double(s, S_OUTPUT_GAIN); + const float knee = cd->is_upwcomp ? (float)obs_data_get_int(s, S_KNEE) : 0.0f; cd->ratio = (float)obs_data_get_double(s, S_RATIO); cd->threshold = (float)obs_data_get_double(s, S_THRESHOLD); - cd->attack_gain = - gain_coefficient(sample_rate, attack_time_ms / MS_IN_S_F); - cd->release_gain = - gain_coefficient(sample_rate, release_time_ms / MS_IN_S_F); + cd->attack_gain = gain_coefficient(sample_rate, attack_time_ms / MS_IN_S_F); + cd->release_gain = gain_coefficient(sample_rate, release_time_ms / MS_IN_S_F); cd->output_gain = db_to_mul(output_gain_db); cd->num_channels = num_channels; cd->sample_rate = sample_rate; @@ -244,9 +230,7 @@ static void expander_update(void *data, obs_data_t *s) resize_gain_db_buffer(cd, sample_len); } -static void *compressor_expander_create(obs_data_t *settings, - obs_source_t *filter, - bool is_compressor) +static void *compressor_expander_create(obs_data_t *settings, obs_source_t *filter, bool is_compressor) { struct expander_data *cd = bzalloc(sizeof(struct expander_data)); cd->context = filter; @@ -269,8 +253,7 @@ static void *expander_create(obs_data_t *settings, obs_source_t *filter) return compressor_expander_create(settings, filter, false); } -static void *upward_compressor_create(obs_data_t *settings, - obs_source_t *filter) +static void *upward_compressor_create(obs_data_t *settings, obs_source_t *filter) { return compressor_expander_create(settings, filter, true); } @@ -289,8 +272,7 @@ static void expander_destroy(void *data) } // detection stage -static void analyze_envelope(struct expander_data *cd, float **samples, - const uint32_t num_samples) +static void analyze_envelope(struct expander_data *cd, float **samples, const uint32_t num_samples) { if (cd->envelope_buf_len < num_samples) resize_env_buffer(cd, num_samples); @@ -303,10 +285,8 @@ static void analyze_envelope(struct expander_data *cd, float **samples, const float rmscoef = exp2f(-100.0f / cd->sample_rate); for (int i = 0; i < MAX_AUDIO_CHANNELS; i++) { - memset(cd->envelope_buf[i], 0, - num_samples * sizeof(cd->envelope_buf[i][0])); - memset(cd->runaverage[i], 0, - num_samples * sizeof(cd->runaverage[i][0])); + memset(cd->envelope_buf[i], 0, num_samples * sizeof(cd->envelope_buf[i][0])); + memset(cd->runaverage[i], 0, num_samples * sizeof(cd->runaverage[i][0])); } memset(cd->env_in, 0, num_samples * sizeof(cd->env_in[0])); @@ -319,15 +299,10 @@ static void analyze_envelope(struct expander_data *cd, float **samples, float *env_in = cd->env_in; if (cd->detector == RMS_DETECT) { - runave[0] = - rmscoef * cd->runave[chan] + - (1 - rmscoef) * powf(samples[chan][0], 2.0f); + runave[0] = rmscoef * cd->runave[chan] + (1 - rmscoef) * powf(samples[chan][0], 2.0f); env_in[0] = sqrtf(fmaxf(runave[0], 0)); for (uint32_t i = 1; i < num_samples; ++i) { - runave[i] = - rmscoef * runave[i - 1] + - (1 - rmscoef) * - powf(samples[chan][i], 2.0f); + runave[i] = rmscoef * runave[i - 1] + (1 - rmscoef) * powf(samples[chan][i], 2.0f); env_in[i] = sqrtf(runave[i]); } } else if (cd->detector == PEAK_DETECT) { @@ -344,12 +319,9 @@ static void analyze_envelope(struct expander_data *cd, float **samples, } } -static inline void process_sample(size_t idx, float *samples, float *env_buf, - float *gain_db, bool is_upwcomp, - float channel_gain, float threshold, - float slope, float attack_gain, - float inv_attack_gain, float release_gain, - float inv_release_gain, float output_gain, +static inline void process_sample(size_t idx, float *samples, float *env_buf, float *gain_db, bool is_upwcomp, + float channel_gain, float threshold, float slope, float attack_gain, + float inv_attack_gain, float release_gain, float inv_release_gain, float output_gain, float knee) { /* --------------------------------- */ @@ -366,8 +338,7 @@ static inline void process_sample(size_t idx, float *samples, float *env_buf, // Note that the gain is always >= 0 for the upward compressor // but is always <=0 for the expander. if (is_upwcomp) { - prev_gain = idx > 0 ? fmaxf(gain_db[idx - 1], 0) - : fmaxf(channel_gain, 0); + prev_gain = idx > 0 ? fmaxf(gain_db[idx - 1], 0) : fmaxf(channel_gain, 0); // gain above knee (included for clarity): if (env_db >= threshold + knee / 2) gain = 0.0f; @@ -375,8 +346,7 @@ static inline void process_sample(size_t idx, float *samples, float *env_buf, if (threshold - knee / 2 >= env_db) gain = slope * diff; // gain in knee: - if (env_db > threshold - knee / 2 && - threshold + knee / 2 > env_db) + if (env_db > threshold - knee / 2 && threshold + knee / 2 > env_db) gain = slope * powf(diff + knee / 2, 2) / (2.0f * knee); } else { prev_gain = idx > 0 ? gain_db[idx - 1] : channel_gain; @@ -389,8 +359,7 @@ static inline void process_sample(size_t idx, float *samples, float *env_buf, if (gain > prev_gain) gain_db[idx] = attack_gain * prev_gain + inv_attack_gain * gain; else - gain_db[idx] = - release_gain * prev_gain + inv_release_gain * gain; + gain_db[idx] = release_gain * prev_gain + inv_release_gain * gain; /* --------------------------------- */ /* output */ @@ -405,8 +374,7 @@ static inline void process_sample(size_t idx, float *samples, float *env_buf, } // gain stage and ballistics in dB domain -static inline void process_expansion(struct expander_data *cd, float **samples, - uint32_t num_samples) +static inline void process_expansion(struct expander_data *cd, float **samples, uint32_t num_samples) { const float attack_gain = cd->attack_gain; const float release_gain = cd->release_gain; @@ -422,8 +390,7 @@ static inline void process_expansion(struct expander_data *cd, float **samples, resize_gain_db_buffer(cd, num_samples); for (size_t i = 0; i < cd->num_channels; i++) - memset(cd->gain_db[i], 0, - num_samples * sizeof(cd->gain_db[i][0])); + memset(cd->gain_db[i], 0, num_samples * sizeof(cd->gain_db[i][0])); for (size_t chan = 0; chan < cd->num_channels; chan++) { float *channel_samples = samples[chan]; @@ -432,18 +399,14 @@ static inline void process_expansion(struct expander_data *cd, float **samples, float channel_gain = cd->gain_db_buf[chan]; for (size_t i = 0; i < num_samples; ++i) { - process_sample(i, channel_samples, env_buf, gain_db, - is_upwcomp, channel_gain, threshold, - slope, attack_gain, inv_attack_gain, - release_gain, inv_release_gain, - output_gain, knee); + process_sample(i, channel_samples, env_buf, gain_db, is_upwcomp, channel_gain, threshold, slope, + attack_gain, inv_attack_gain, release_gain, inv_release_gain, output_gain, knee); } cd->gain_db_buf[chan] = gain_db[num_samples - 1]; } } -static struct obs_audio_data * -expander_filter_audio(void *data, struct obs_audio_data *audio) +static struct obs_audio_data *expander_filter_audio(void *data, struct obs_audio_data *audio) { struct expander_data *cd = data; @@ -458,8 +421,7 @@ expander_filter_audio(void *data, struct obs_audio_data *audio) return audio; } -static bool presets_changed(obs_properties_t *props, obs_property_t *prop, - obs_data_t *settings) +static bool presets_changed(obs_properties_t *props, obs_property_t *prop, obs_data_t *settings) { UNUSED_PARAMETER(props); UNUSED_PARAMETER(prop); @@ -473,47 +435,33 @@ static obs_properties_t *expander_properties(void *data) obs_properties_t *props = obs_properties_create(); obs_property_t *p; if (!cd->is_upwcomp) { - obs_property_t *presets = obs_properties_add_list( - props, S_PRESETS, TEXT_PRESETS, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(presets, TEXT_PRESETS_EXP, - "expander"); - obs_property_list_add_string(presets, TEXT_PRESETS_GATE, - "gate"); + obs_property_t *presets = obs_properties_add_list(props, S_PRESETS, TEXT_PRESETS, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); + obs_property_list_add_string(presets, TEXT_PRESETS_EXP, "expander"); + obs_property_list_add_string(presets, TEXT_PRESETS_GATE, "gate"); obs_property_set_modified_callback(presets, presets_changed); } - p = obs_properties_add_float_slider( - props, S_RATIO, TEXT_RATIO, - !cd->is_upwcomp ? MIN_RATIO : MIN_RATIO_UPW, - !cd->is_upwcomp ? MAX_RATIO : MAX_RATIO_UPW, 0.1); + p = obs_properties_add_float_slider(props, S_RATIO, TEXT_RATIO, !cd->is_upwcomp ? MIN_RATIO : MIN_RATIO_UPW, + !cd->is_upwcomp ? MAX_RATIO : MAX_RATIO_UPW, 0.1); obs_property_float_set_suffix(p, ":1"); - p = obs_properties_add_float_slider(props, S_THRESHOLD, TEXT_THRESHOLD, - MIN_THRESHOLD_DB, MAX_THRESHOLD_DB, + p = obs_properties_add_float_slider(props, S_THRESHOLD, TEXT_THRESHOLD, MIN_THRESHOLD_DB, MAX_THRESHOLD_DB, 0.1); obs_property_float_set_suffix(p, " dB"); - p = obs_properties_add_int_slider(props, S_ATTACK_TIME, - TEXT_ATTACK_TIME, MIN_ATK_RLS_MS, - MAX_ATK_MS, 1); + p = obs_properties_add_int_slider(props, S_ATTACK_TIME, TEXT_ATTACK_TIME, MIN_ATK_RLS_MS, MAX_ATK_MS, 1); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_int_slider(props, S_RELEASE_TIME, - TEXT_RELEASE_TIME, MIN_ATK_RLS_MS, - MAX_RLS_MS, 1); + p = obs_properties_add_int_slider(props, S_RELEASE_TIME, TEXT_RELEASE_TIME, MIN_ATK_RLS_MS, MAX_RLS_MS, 1); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_float_slider(props, S_OUTPUT_GAIN, - TEXT_OUTPUT_GAIN, - MIN_OUTPUT_GAIN_DB, + p = obs_properties_add_float_slider(props, S_OUTPUT_GAIN, TEXT_OUTPUT_GAIN, MIN_OUTPUT_GAIN_DB, MAX_OUTPUT_GAIN_DB, 0.1); obs_property_float_set_suffix(p, " dB"); if (!cd->is_upwcomp) { - obs_property_t *detect = obs_properties_add_list( - props, S_DETECTOR, TEXT_DETECTOR, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *detect = obs_properties_add_list(props, S_DETECTOR, TEXT_DETECTOR, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(detect, TEXT_RMS, "RMS"); obs_property_list_add_string(detect, TEXT_PEAK, "peak"); } else { - p = obs_properties_add_int_slider(props, S_KNEE, TEXT_KNEE, 0, - 20, 1); + p = obs_properties_add_int_slider(props, S_KNEE, TEXT_KNEE, 0, 20, 1); obs_property_float_set_suffix(p, " dB"); } return props; diff --git a/plugins/obs-filters/gain-filter.c b/plugins/obs-filters/gain-filter.c index 458abce56..ab7823091 100644 --- a/plugins/obs-filters/gain-filter.c +++ b/plugins/obs-filters/gain-filter.c @@ -2,9 +2,8 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[gain filter: '%s'] " format, \ - obs_source_get_name(gf->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[gain filter: '%s'] " format, obs_source_get_name(gf->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -48,8 +47,7 @@ static void *gain_create(obs_data_t *settings, obs_source_t *filter) return gf; } -static struct obs_audio_data *gain_filter_audio(void *data, - struct obs_audio_data *audio) +static struct obs_audio_data *gain_filter_audio(void *data, struct obs_audio_data *audio) { struct gain_data *gf = data; const size_t channels = gf->channels; @@ -76,8 +74,7 @@ static obs_properties_t *gain_properties(void *data) { obs_properties_t *ppts = obs_properties_create(); - obs_property_t *p = obs_properties_add_float_slider( - ppts, S_GAIN_DB, TEXT_GAIN_DB, -30.0, 30.0, 0.1); + obs_property_t *p = obs_properties_add_float_slider(ppts, S_GAIN_DB, TEXT_GAIN_DB, -30.0, 30.0, 0.1); obs_property_float_set_suffix(p, " dB"); UNUSED_PARAMETER(data); diff --git a/plugins/obs-filters/gpu-delay.c b/plugins/obs-filters/gpu-delay.c index 7c2c62fd1..2e69f61b0 100644 --- a/plugins/obs-filters/gpu-delay.c +++ b/plugins/obs-filters/gpu-delay.c @@ -45,8 +45,7 @@ static size_t num_frames(struct deque *buf) return buf->size / sizeof(struct frame); } -static void update_interval(struct gpu_delay_filter_data *f, - uint64_t new_interval_ns) +static void update_interval(struct gpu_delay_filter_data *f, uint64_t new_interval_ns) { if (!f->target_valid) { free_textures(f); @@ -64,10 +63,8 @@ static void update_interval(struct gpu_delay_filter_data *f, deque_upsize(&f->frames, num * sizeof(struct frame)); for (size_t i = prev_num; i < num; i++) { - struct frame *frame = - deque_data(&f->frames, i * sizeof(*frame)); - frame->render = - gs_texrender_create(GS_RGBA, GS_ZS_NONE); + struct frame *frame = deque_data(&f->frames, i * sizeof(*frame)); + frame->render = gs_texrender_create(GS_RGBA, GS_ZS_NONE); } obs_leave_graphics(); @@ -149,16 +146,14 @@ static obs_properties_t *gpu_delay_filter_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *p = obs_properties_add_int(props, S_DELAY_MS, - T_DELAY_MS, 0, 500, 1); + obs_property_t *p = obs_properties_add_int(props, S_DELAY_MS, T_DELAY_MS, 0, 500, 1); obs_property_int_set_suffix(p, " ms"); UNUSED_PARAMETER(data); return props; } -static void *gpu_delay_filter_create(obs_data_t *settings, - obs_source_t *context) +static void *gpu_delay_filter_create(obs_data_t *settings, obs_source_t *context) { struct gpu_delay_filter_data *f = bzalloc(sizeof(*f)); f->context = context; @@ -188,10 +183,8 @@ static void gpu_delay_filter_tick(void *data, float t) check_interval(f); } -static const char * -get_tech_name_and_multiplier(enum gs_color_space current_space, - enum gs_color_space source_space, - float *multiplier) +static const char *get_tech_name_and_multiplier(enum gs_color_space current_space, enum gs_color_space source_space, + float *multiplier) { const char *tech_name = "Draw"; *multiplier = 1.f; @@ -244,8 +237,7 @@ static void draw_frame(struct gpu_delay_filter_data *f) const enum gs_color_space current_space = gs_get_color_space(); float multiplier; - const char *technique = get_tech_name_and_multiplier( - current_space, frame.space, &multiplier); + const char *technique = get_tech_name_and_multiplier(current_space, frame.space, &multiplier); gs_effect_t *effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); gs_texture_t *tex = gs_texrender_get_texture(frame.render); @@ -253,11 +245,8 @@ static void draw_frame(struct gpu_delay_filter_data *f) const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(true); - gs_effect_set_texture_srgb( - gs_effect_get_param_by_name(effect, "image"), tex); - gs_effect_set_float(gs_effect_get_param_by_name(effect, - "multiplier"), - multiplier); + gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), tex); + gs_effect_set_float(gs_effect_get_param_by_name(effect, "multiplier"), multiplier); while (gs_effect_loop(effect, technique)) gs_draw_sprite(tex, 0, f->cx, f->cy); @@ -290,8 +279,8 @@ static void gpu_delay_filter_render(void *data, gs_effect_t *effect) GS_CS_SRGB_16F, GS_CS_709_EXTENDED, }; - const enum gs_color_space space = obs_source_get_color_space( - target, OBS_COUNTOF(preferred_spaces), preferred_spaces); + const enum gs_color_space space = + obs_source_get_color_space(target, OBS_COUNTOF(preferred_spaces), preferred_spaces); const enum gs_color_format format = gs_get_format_from_space(space); if (gs_texrender_get_format(frame.render) != format) { gs_texrender_destroy(frame.render); @@ -303,8 +292,7 @@ static void gpu_delay_filter_render(void *data, gs_effect_t *effect) gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_ZERO); - if (gs_texrender_begin_with_color_space(frame.render, f->cx, f->cy, - space)) { + if (gs_texrender_begin_with_color_space(frame.render, f->cx, f->cy, space)) { uint32_t parent_flags = obs_source_get_output_flags(target); bool custom_draw = (parent_flags & OBS_SOURCE_CUSTOM_DRAW) != 0; bool async = (parent_flags & OBS_SOURCE_ASYNC) != 0; @@ -312,8 +300,7 @@ static void gpu_delay_filter_render(void *data, gs_effect_t *effect) vec4_zero(&clear_color); gs_clear(GS_CLEAR_COLOR, &clear_color, 0.0f, 0); - gs_ortho(0.0f, (float)f->cx, 0.0f, (float)f->cy, -100.0f, - 100.0f); + gs_ortho(0.0f, (float)f->cx, 0.0f, (float)f->cy, -100.0f, 100.0f); if (target == parent && !custom_draw && !async) obs_source_default_render(target); @@ -334,9 +321,8 @@ static void gpu_delay_filter_render(void *data, gs_effect_t *effect) UNUSED_PARAMETER(effect); } -static enum gs_color_space -gpu_delay_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space gpu_delay_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { struct gpu_delay_filter_data *const f = data; obs_source_t *target = obs_filter_get_target(f->context); diff --git a/plugins/obs-filters/hdr-tonemap-filter.c b/plugins/obs-filters/hdr-tonemap-filter.c index daf4315d5..e3ce050ad 100644 --- a/plugins/obs-filters/hdr-tonemap-filter.c +++ b/plugins/obs-filters/hdr-tonemap-filter.c @@ -28,8 +28,7 @@ static const char *hdr_tonemap_filter_get_name(void *unused) return obs_module_text("HdrTonemapFilter"); } -static void *hdr_tonemap_filter_create(obs_data_t *settings, - obs_source_t *context) +static void *hdr_tonemap_filter_create(obs_data_t *settings, obs_source_t *context) { struct hdr_tonemap_filter_data *filter = bzalloc(sizeof(*filter)); char *effect_path = obs_module_file("hdr_tonemap_filter.effect"); @@ -47,12 +46,9 @@ static void *hdr_tonemap_filter_create(obs_data_t *settings, return NULL; } - filter->param_multiplier = - gs_effect_get_param_by_name(filter->effect, "multiplier"); - filter->param_input_maximum_nits = gs_effect_get_param_by_name( - filter->effect, "input_maximum_nits"); - filter->param_output_maximum_nits = gs_effect_get_param_by_name( - filter->effect, "output_maximum_nits"); + filter->param_multiplier = gs_effect_get_param_by_name(filter->effect, "multiplier"); + filter->param_input_maximum_nits = gs_effect_get_param_by_name(filter->effect, "input_maximum_nits"); + filter->param_output_maximum_nits = gs_effect_get_param_by_name(filter->effect, "output_maximum_nits"); obs_source_update(context, settings); return filter; @@ -74,41 +70,25 @@ static void hdr_tonemap_filter_update(void *data, obs_data_t *settings) struct hdr_tonemap_filter_data *filter = data; filter->transform = obs_data_get_int(settings, "transform"); - filter->sdr_white_level_nits_i = - 1.f / (float)obs_data_get_int(settings, "sdr_white_level_nits"); - filter->hdr_input_maximum_nits = - (float)obs_data_get_int(settings, "hdr_input_maximum_nits"); - filter->hdr_output_maximum_nits = - (float)obs_data_get_int(settings, "hdr_output_maximum_nits"); - filter->sdr_input_maximum_nits = - (float)obs_data_get_int(settings, "sdr_input_maximum_nits"); - filter->sdr_output_maximum_nits = - (float)obs_data_get_int(settings, "sdr_output_maximum_nits"); + filter->sdr_white_level_nits_i = 1.f / (float)obs_data_get_int(settings, "sdr_white_level_nits"); + filter->hdr_input_maximum_nits = (float)obs_data_get_int(settings, "hdr_input_maximum_nits"); + filter->hdr_output_maximum_nits = (float)obs_data_get_int(settings, "hdr_output_maximum_nits"); + filter->sdr_input_maximum_nits = (float)obs_data_get_int(settings, "sdr_input_maximum_nits"); + filter->sdr_output_maximum_nits = (float)obs_data_get_int(settings, "sdr_output_maximum_nits"); } -static bool transform_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool transform_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { - enum hdr_tonemap_transform transform = - obs_data_get_int(settings, "transform"); + enum hdr_tonemap_transform transform = obs_data_get_int(settings, "transform"); const bool reinhard = transform == TRANSFORM_SDR_REINHARD; const bool maxrgb_hdr = transform == TRANSFORM_HDR_MAXRGB; const bool maxrgb_sdr = transform == TRANSFORM_SDR_MAXRGB; - obs_property_set_visible( - obs_properties_get(props, "sdr_white_level_nits"), reinhard); - obs_property_set_visible(obs_properties_get(props, - "hdr_input_maximum_nits"), - maxrgb_hdr); - obs_property_set_visible(obs_properties_get(props, - "hdr_output_maximum_nits"), - maxrgb_hdr); - obs_property_set_visible(obs_properties_get(props, - "sdr_input_maximum_nits"), - maxrgb_sdr); - obs_property_set_visible(obs_properties_get(props, - "sdr_output_maximum_nits"), - maxrgb_sdr); + obs_property_set_visible(obs_properties_get(props, "sdr_white_level_nits"), reinhard); + obs_property_set_visible(obs_properties_get(props, "hdr_input_maximum_nits"), maxrgb_hdr); + obs_property_set_visible(obs_properties_get(props, "hdr_output_maximum_nits"), maxrgb_hdr); + obs_property_set_visible(obs_properties_get(props, "sdr_input_maximum_nits"), maxrgb_sdr); + obs_property_set_visible(obs_properties_get(props, "sdr_output_maximum_nits"), maxrgb_sdr); UNUSED_PARAMETER(p); return true; @@ -118,40 +98,29 @@ static obs_properties_t *hdr_tonemap_filter_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "override_info", - obs_module_text("HdrTonemap.Description"), - OBS_TEXT_INFO); + obs_properties_add_text(props, "override_info", obs_module_text("HdrTonemap.Description"), OBS_TEXT_INFO); - obs_property_t *p = obs_properties_add_list( - props, "transform", obs_module_text("HdrTonemap.ToneTransform"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(p, obs_module_text("HdrTonemap.SdrReinhard"), - TRANSFORM_SDR_REINHARD); - obs_property_list_add_int(p, obs_module_text("HdrTonemap.HdrMaxrgb"), - TRANSFORM_HDR_MAXRGB); - obs_property_list_add_int(p, obs_module_text("HdrTonemap.SdrMaxrgb"), - TRANSFORM_SDR_MAXRGB); + obs_property_t *p = obs_properties_add_list(props, "transform", obs_module_text("HdrTonemap.ToneTransform"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(p, obs_module_text("HdrTonemap.SdrReinhard"), TRANSFORM_SDR_REINHARD); + obs_property_list_add_int(p, obs_module_text("HdrTonemap.HdrMaxrgb"), TRANSFORM_HDR_MAXRGB); + obs_property_list_add_int(p, obs_module_text("HdrTonemap.SdrMaxrgb"), TRANSFORM_SDR_MAXRGB); obs_property_set_modified_callback(p, transform_changed); - p = obs_properties_add_int(props, "sdr_white_level_nits", - obs_module_text("HdrTonemap.SdrWhiteLevel"), - 80, 480, 1); + p = obs_properties_add_int(props, "sdr_white_level_nits", obs_module_text("HdrTonemap.SdrWhiteLevel"), 80, 480, + 1); obs_property_int_set_suffix(p, " nits"); - p = obs_properties_add_int( - props, "hdr_input_maximum_nits", - obs_module_text("HdrTonemap.HdrInputMaximum"), 5, 10000, 1); + p = obs_properties_add_int(props, "hdr_input_maximum_nits", obs_module_text("HdrTonemap.HdrInputMaximum"), 5, + 10000, 1); obs_property_int_set_suffix(p, " nits"); - p = obs_properties_add_int( - props, "hdr_output_maximum_nits", - obs_module_text("HdrTonemap.HdrOutputMaximum"), 5, 10000, 1); + p = obs_properties_add_int(props, "hdr_output_maximum_nits", obs_module_text("HdrTonemap.HdrOutputMaximum"), 5, + 10000, 1); obs_property_int_set_suffix(p, " nits"); - p = obs_properties_add_int( - props, "sdr_input_maximum_nits", - obs_module_text("HdrTonemap.SdrInputMaximum"), 5, 10000, 1); + p = obs_properties_add_int(props, "sdr_input_maximum_nits", obs_module_text("HdrTonemap.SdrInputMaximum"), 5, + 10000, 1); obs_property_int_set_suffix(p, " nits"); - p = obs_properties_add_int( - props, "sdr_output_maximum_nits", - obs_module_text("HdrTonemap.SdrOutputMaximum"), 5, 10000, 1); + p = obs_properties_add_int(props, "sdr_output_maximum_nits", obs_module_text("HdrTonemap.SdrOutputMaximum"), 5, + 10000, 1); obs_property_int_set_suffix(p, " nits"); UNUSED_PARAMETER(data); @@ -180,36 +149,26 @@ static void hdr_tonemap_filter_render(void *data, gs_effect_t *effect) GS_CS_709_EXTENDED, }; - enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + enum gs_color_space source_space = obs_source_get_color_space(obs_filter_get_target(filter->context), + OBS_COUNTOF(preferred_spaces), preferred_spaces); switch (source_space) { case GS_CS_709_EXTENDED: case GS_CS_709_SCRGB: { - float multiplier = (source_space == GS_CS_709_EXTENDED) - ? obs_get_video_sdr_white_level() - : 80.f; - multiplier *= (filter->transform == TRANSFORM_SDR_REINHARD) - ? filter->sdr_white_level_nits_i - : 0.0001f; + float multiplier = (source_space == GS_CS_709_EXTENDED) ? obs_get_video_sdr_white_level() : 80.f; + multiplier *= (filter->transform == TRANSFORM_SDR_REINHARD) ? filter->sdr_white_level_nits_i : 0.0001f; - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_NO_DIRECT_RENDERING)) { - gs_effect_set_float(filter->param_multiplier, - multiplier); - gs_effect_set_float( - filter->param_input_maximum_nits, - (filter->transform == TRANSFORM_SDR_MAXRGB) - ? filter->sdr_input_maximum_nits - : filter->hdr_input_maximum_nits); - gs_effect_set_float( - filter->param_output_maximum_nits, - (filter->transform == TRANSFORM_SDR_MAXRGB) - ? filter->sdr_output_maximum_nits - : filter->hdr_output_maximum_nits); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_NO_DIRECT_RENDERING)) { + gs_effect_set_float(filter->param_multiplier, multiplier); + gs_effect_set_float(filter->param_input_maximum_nits, + (filter->transform == TRANSFORM_SDR_MAXRGB) + ? filter->sdr_input_maximum_nits + : filter->hdr_input_maximum_nits); + gs_effect_set_float(filter->param_output_maximum_nits, + (filter->transform == TRANSFORM_SDR_MAXRGB) + ? filter->sdr_output_maximum_nits + : filter->hdr_output_maximum_nits); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); @@ -217,13 +176,8 @@ static void hdr_tonemap_filter_render(void *data, gs_effect_t *effect) const char *const tech_name = (filter->transform == TRANSFORM_SDR_REINHARD) ? "Reinhard" - : ((filter->transform == - TRANSFORM_HDR_MAXRGB) - ? "MaxRGB" - : "MaxRGBSDR"); - obs_source_process_filter_tech_end(filter->context, - filter->effect, 0, 0, - tech_name); + : ((filter->transform == TRANSFORM_HDR_MAXRGB) ? "MaxRGB" : "MaxRGBSDR"); + obs_source_process_filter_tech_end(filter->context, filter->effect, 0, 0, tech_name); gs_blend_state_pop(); } @@ -234,9 +188,8 @@ static void hdr_tonemap_filter_render(void *data, gs_effect_t *effect) } } -static enum gs_color_space -hdr_tonemap_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space hdr_tonemap_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { const enum gs_color_space potential_spaces[] = { GS_CS_SRGB, @@ -246,14 +199,12 @@ hdr_tonemap_filter_get_color_space(void *data, size_t count, struct hdr_tonemap_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); enum gs_color_space space = source_space; if (source_space == GS_CS_709_EXTENDED || source_space == GS_CS_SRGB) { - if ((filter->transform == TRANSFORM_SDR_REINHARD) || - filter->transform == TRANSFORM_SDR_MAXRGB) { + if ((filter->transform == TRANSFORM_SDR_REINHARD) || filter->transform == TRANSFORM_SDR_MAXRGB) { space = GS_CS_SRGB; for (size_t i = 0; i < count; ++i) { if (preferred_spaces[i] != GS_CS_SRGB) { diff --git a/plugins/obs-filters/invert-audio-polarity.c b/plugins/obs-filters/invert-audio-polarity.c index 5c225cfa4..aa34f7e9d 100644 --- a/plugins/obs-filters/invert-audio-polarity.c +++ b/plugins/obs-filters/invert-audio-polarity.c @@ -17,8 +17,7 @@ static void *invert_polarity_create(obs_data_t *settings, obs_source_t *filter) return filter; } -static struct obs_audio_data * -invert_polarity_filter_audio(void *unused, struct obs_audio_data *audio) +static struct obs_audio_data *invert_polarity_filter_audio(void *unused, struct obs_audio_data *audio) { float **adata = (float **)audio->data; diff --git a/plugins/obs-filters/limiter-filter.c b/plugins/obs-filters/limiter-filter.c index ec3ed05a5..86b0484c4 100644 --- a/plugins/obs-filters/limiter-filter.c +++ b/plugins/obs-filters/limiter-filter.c @@ -8,9 +8,8 @@ /* -------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[limiter: '%s'] " format, \ - obs_source_get_name(cd->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[limiter: '%s'] " format, obs_source_get_name(cd->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -84,21 +83,17 @@ static void limiter_update(void *data, obs_data_t *s) { struct limiter_data *cd = data; - const uint32_t sample_rate = - audio_output_get_sample_rate(obs_get_audio()); + const uint32_t sample_rate = audio_output_get_sample_rate(obs_get_audio()); const size_t num_channels = audio_output_get_channels(obs_get_audio()); float attack_time_ms = ATK_TIME; - const float release_time_ms = - (float)obs_data_get_int(s, S_RELEASE_TIME); + const float release_time_ms = (float)obs_data_get_int(s, S_RELEASE_TIME); const float output_gain_db = 0; cd->threshold = (float)obs_data_get_double(s, S_THRESHOLD); - cd->attack_gain = - gain_coefficient(sample_rate, attack_time_ms / MS_IN_S_F); - cd->release_gain = - gain_coefficient(sample_rate, release_time_ms / MS_IN_S_F); + cd->attack_gain = gain_coefficient(sample_rate, attack_time_ms / MS_IN_S_F); + cd->release_gain = gain_coefficient(sample_rate, release_time_ms / MS_IN_S_F); cd->output_gain = db_to_mul(output_gain_db); cd->num_channels = num_channels; cd->sample_rate = sample_rate; @@ -126,8 +121,7 @@ static void limiter_destroy(void *data) bfree(cd); } -static void analyze_envelope(struct limiter_data *cd, float **samples, - const uint32_t num_samples) +static void analyze_envelope(struct limiter_data *cd, float **samples, const uint32_t num_samples) { if (cd->envelope_buf_len < num_samples) { resize_env_buffer(cd, num_samples); @@ -156,8 +150,7 @@ static void analyze_envelope(struct limiter_data *cd, float **samples, cd->envelope = cd->envelope_buf[num_samples - 1]; } -static inline void process_compression(const struct limiter_data *cd, - float **samples, uint32_t num_samples) +static inline void process_compression(const struct limiter_data *cd, float **samples, uint32_t num_samples) { for (size_t i = 0; i < num_samples; ++i) { const float env_db = mul_to_db(cd->envelope_buf[i]); @@ -172,8 +165,7 @@ static inline void process_compression(const struct limiter_data *cd, } } -static struct obs_audio_data *limiter_filter_audio(void *data, - struct obs_audio_data *audio) +static struct obs_audio_data *limiter_filter_audio(void *data, struct obs_audio_data *audio) { struct limiter_data *cd = data; @@ -198,13 +190,10 @@ static obs_properties_t *limiter_properties(void *data) obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_float_slider(props, S_THRESHOLD, TEXT_THRESHOLD, - MIN_THRESHOLD_DB, MAX_THRESHOLD_DB, + p = obs_properties_add_float_slider(props, S_THRESHOLD, TEXT_THRESHOLD, MIN_THRESHOLD_DB, MAX_THRESHOLD_DB, 0.1); obs_property_float_set_suffix(p, " dB"); - p = obs_properties_add_int_slider(props, S_RELEASE_TIME, - TEXT_RELEASE_TIME, MIN_ATK_RLS_MS, - MAX_RLS_MS, 1); + p = obs_properties_add_int_slider(props, S_RELEASE_TIME, TEXT_RELEASE_TIME, MIN_ATK_RLS_MS, MAX_RLS_MS, 1); obs_property_int_set_suffix(p, " ms"); UNUSED_PARAMETER(data); diff --git a/plugins/obs-filters/luma-key-filter.c b/plugins/obs-filters/luma-key-filter.c index 772ab8214..cfd431c3e 100644 --- a/plugins/obs-filters/luma-key-filter.c +++ b/plugins/obs-filters/luma-key-filter.c @@ -44,10 +44,8 @@ static void luma_key_update(void *data, obs_data_t *settings) double lumaMax = obs_data_get_double(settings, SETTING_LUMA_MAX); double lumaMin = obs_data_get_double(settings, SETTING_LUMA_MIN); - double lumaMaxSmooth = - obs_data_get_double(settings, SETTING_LUMA_MAX_SMOOTH); - double lumaMinSmooth = - obs_data_get_double(settings, SETTING_LUMA_MIN_SMOOTH); + double lumaMaxSmooth = obs_data_get_double(settings, SETTING_LUMA_MAX_SMOOTH); + double lumaMinSmooth = obs_data_get_double(settings, SETTING_LUMA_MIN_SMOOTH); filter->luma_max = (float)lumaMax; filter->luma_min = (float)lumaMin; @@ -68,12 +66,9 @@ static void luma_key_destroy(void *data) bfree(data); } -static void *luma_key_create_internal(obs_data_t *settings, - obs_source_t *context, - const char *effect_name) +static void *luma_key_create_internal(obs_data_t *settings, obs_source_t *context, const char *effect_name) { - struct luma_key_filter_data *filter = - bzalloc(sizeof(struct luma_key_filter_data)); + struct luma_key_filter_data *filter = bzalloc(sizeof(struct luma_key_filter_data)); char *effect_path = obs_module_file(effect_name); filter->context = context; @@ -82,14 +77,10 @@ static void *luma_key_create_internal(obs_data_t *settings, filter->effect = gs_effect_create_from_file(effect_path, NULL); if (filter->effect) { - filter->luma_max_param = - gs_effect_get_param_by_name(filter->effect, "lumaMax"); - filter->luma_min_param = - gs_effect_get_param_by_name(filter->effect, "lumaMin"); - filter->luma_max_smooth_param = gs_effect_get_param_by_name( - filter->effect, "lumaMaxSmooth"); - filter->luma_min_smooth_param = gs_effect_get_param_by_name( - filter->effect, "lumaMinSmooth"); + filter->luma_max_param = gs_effect_get_param_by_name(filter->effect, "lumaMax"); + filter->luma_min_param = gs_effect_get_param_by_name(filter->effect, "lumaMin"); + filter->luma_max_smooth_param = gs_effect_get_param_by_name(filter->effect, "lumaMaxSmooth"); + filter->luma_min_smooth_param = gs_effect_get_param_by_name(filter->effect, "lumaMinSmooth"); } obs_leave_graphics(); @@ -107,14 +98,12 @@ static void *luma_key_create_internal(obs_data_t *settings, static void *luma_key_create_v1(obs_data_t *settings, obs_source_t *context) { - return luma_key_create_internal(settings, context, - "luma_key_filter.effect"); + return luma_key_create_internal(settings, context, "luma_key_filter.effect"); } static void *luma_key_create_v2(obs_data_t *settings, obs_source_t *context) { - return luma_key_create_internal(settings, context, - "luma_key_filter_v2.effect"); + return luma_key_create_internal(settings, context, "luma_key_filter_v2.effect"); } static void luma_key_render_internal(void *data, bool premultiplied) @@ -128,33 +117,24 @@ static void luma_key_render_internal(void *data, bool premultiplied) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { - gs_effect_set_float(filter->luma_max_param, - filter->luma_max); - gs_effect_set_float(filter->luma_min_param, - filter->luma_min); - gs_effect_set_float(filter->luma_max_smooth_param, - filter->luma_max_smooth); - gs_effect_set_float(filter->luma_min_smooth_param, - filter->luma_min_smooth); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { + gs_effect_set_float(filter->luma_max_param, filter->luma_max); + gs_effect_set_float(filter->luma_min_param, filter->luma_min); + gs_effect_set_float(filter->luma_max_smooth_param, filter->luma_max_smooth); + gs_effect_set_float(filter->luma_min_smooth_param, filter->luma_min_smooth); if (premultiplied) { gs_blend_state_push(); - gs_blend_function(GS_BLEND_ONE, - GS_BLEND_INVSRCALPHA); + gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); } - obs_source_process_filter_end(filter->context, - filter->effect, 0, 0); + obs_source_process_filter_end(filter->context, filter->effect, 0, 0); if (premultiplied) { gs_blend_state_pop(); @@ -181,16 +161,11 @@ static obs_properties_t *luma_key_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, - TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); - obs_properties_add_float_slider(props, SETTING_LUMA_MAX, TEXT_LUMA_MAX, - 0, 1, 0.0001); - obs_properties_add_float_slider(props, SETTING_LUMA_MAX_SMOOTH, - TEXT_LUMA_MAX_SMOOTH, 0, 1, 0.0001); - obs_properties_add_float_slider(props, SETTING_LUMA_MIN, TEXT_LUMA_MIN, - 0, 1, 0.0001); - obs_properties_add_float_slider(props, SETTING_LUMA_MIN_SMOOTH, - TEXT_LUMA_MIN_SMOOTH, 0, 1, 0.0001); + obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); + obs_properties_add_float_slider(props, SETTING_LUMA_MAX, TEXT_LUMA_MAX, 0, 1, 0.0001); + obs_properties_add_float_slider(props, SETTING_LUMA_MAX_SMOOTH, TEXT_LUMA_MAX_SMOOTH, 0, 1, 0.0001); + obs_properties_add_float_slider(props, SETTING_LUMA_MIN, TEXT_LUMA_MIN, 0, 1, 0.0001); + obs_properties_add_float_slider(props, SETTING_LUMA_MIN_SMOOTH, TEXT_LUMA_MIN_SMOOTH, 0, 1, 0.0001); UNUSED_PARAMETER(data); return props; @@ -204,9 +179,8 @@ static void luma_key_defaults(obs_data_t *settings) obs_data_set_default_double(settings, SETTING_LUMA_MIN_SMOOTH, 0.0); } -static enum gs_color_space -luma_key_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space luma_key_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -219,8 +193,7 @@ luma_key_get_color_space(void *data, size_t count, struct luma_key_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-filters/mask-filter.c b/plugins/obs-filters/mask-filter.c index 6d2817bbe..fff6ee5cd 100644 --- a/plugins/obs-filters/mask-filter.c +++ b/plugins/obs-filters/mask-filter.c @@ -82,8 +82,7 @@ static void mask_filter_image_load(struct mask_filter_data *filter) filter->target = filter->image.texture; } -static void mask_filter_update_internal(void *data, obs_data_t *settings, - float opacity, bool srgb) +static void mask_filter_update_internal(void *data, obs_data_t *settings, float opacity, bool srgb) { struct mask_filter_data *filter = data; @@ -117,30 +116,26 @@ static void mask_filter_update_internal(void *data, obs_data_t *settings, static void mask_filter_update_v1(void *data, obs_data_t *settings) { - const float opacity = - (float)(obs_data_get_int(settings, SETTING_OPACITY) * 0.01); + const float opacity = (float)(obs_data_get_int(settings, SETTING_OPACITY) * 0.01); mask_filter_update_internal(data, settings, opacity, false); } static void mask_filter_update_v2(void *data, obs_data_t *settings) { - const float opacity = - (float)obs_data_get_double(settings, SETTING_OPACITY); + const float opacity = (float)obs_data_get_double(settings, SETTING_OPACITY); mask_filter_update_internal(data, settings, opacity, true); } static void mask_filter_defaults_v1(obs_data_t *settings) { - obs_data_set_default_string(settings, SETTING_TYPE, - "mask_color_filter.effect"); + obs_data_set_default_string(settings, SETTING_TYPE, "mask_color_filter.effect"); obs_data_set_default_int(settings, SETTING_COLOR, 0xFFFFFF); obs_data_set_default_int(settings, SETTING_OPACITY, 100); } static void mask_filter_defaults_v2(obs_data_t *settings) { - obs_data_set_default_string(settings, SETTING_TYPE, - "mask_color_filter.effect"); + obs_data_set_default_string(settings, SETTING_TYPE, "mask_color_filter.effect"); obs_data_set_default_int(settings, SETTING_COLOR, 0xFFFFFF); obs_data_set_default_double(settings, SETTING_OPACITY, 1.0); } @@ -158,38 +153,22 @@ static obs_properties_t *mask_filter_properties_internal(bool use_float_opacity) dstr_cat(&filter_str, TEXT_PATH_ALL_FILES); dstr_cat(&filter_str, " (*.*)"); - obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, - TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); + obs_properties_add_text(props, SETTING_SDR_ONLY_INFO, TEXT_SDR_ONLY_INFO, OBS_TEXT_INFO); - p = obs_properties_add_list(props, SETTING_TYPE, TEXT_TYPE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(props, SETTING_TYPE, TEXT_TYPE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, - obs_module_text("MaskBlendType.MaskColor"), - "mask_color_filter.effect"); - obs_property_list_add_string(p, - obs_module_text("MaskBlendType.MaskAlpha"), - "mask_alpha_filter.effect"); - obs_property_list_add_string( - p, obs_module_text("MaskBlendType.BlendMultiply"), - "blend_mul_filter.effect"); - obs_property_list_add_string( - p, obs_module_text("MaskBlendType.BlendAddition"), - "blend_add_filter.effect"); - obs_property_list_add_string( - p, obs_module_text("MaskBlendType.BlendSubtraction"), - "blend_sub_filter.effect"); + obs_property_list_add_string(p, obs_module_text("MaskBlendType.MaskColor"), "mask_color_filter.effect"); + obs_property_list_add_string(p, obs_module_text("MaskBlendType.MaskAlpha"), "mask_alpha_filter.effect"); + obs_property_list_add_string(p, obs_module_text("MaskBlendType.BlendMultiply"), "blend_mul_filter.effect"); + obs_property_list_add_string(p, obs_module_text("MaskBlendType.BlendAddition"), "blend_add_filter.effect"); + obs_property_list_add_string(p, obs_module_text("MaskBlendType.BlendSubtraction"), "blend_sub_filter.effect"); - obs_properties_add_path(props, SETTING_IMAGE_PATH, TEXT_IMAGE_PATH, - OBS_PATH_FILE, filter_str.array, NULL); + obs_properties_add_path(props, SETTING_IMAGE_PATH, TEXT_IMAGE_PATH, OBS_PATH_FILE, filter_str.array, NULL); obs_properties_add_color(props, SETTING_COLOR, TEXT_COLOR); if (use_float_opacity) { - obs_properties_add_float_slider(props, SETTING_OPACITY, - TEXT_OPACITY, 0.0, 1.0, 0.0001); + obs_properties_add_float_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0.0, 1.0, 0.0001); } else { - obs_properties_add_int_slider(props, SETTING_OPACITY, - TEXT_OPACITY, 0, 100, 1); + obs_properties_add_int_slider(props, SETTING_OPACITY, TEXT_OPACITY, 0, 100, 1); } obs_properties_add_bool(props, SETTING_STRETCH, TEXT_STRETCH); @@ -214,8 +193,7 @@ static obs_properties_t *mask_filter_properties_v2(void *data) static void *mask_filter_create(obs_data_t *settings, obs_source_t *context) { - struct mask_filter_data *filter = - bzalloc(sizeof(struct mask_filter_data)); + struct mask_filter_data *filter = bzalloc(sizeof(struct mask_filter_data)); filter->context = context; obs_source_update(context, settings); @@ -257,8 +235,7 @@ static void mask_filter_tick(void *data, float seconds) if (!filter->last_time) filter->last_time = cur_time; - gs_image_file_tick(&filter->image, - cur_time - filter->last_time); + gs_image_file_tick(&filter->image, cur_time - filter->last_time); obs_enter_graphics(); gs_image_file_update_texture(&filter->image); obs_leave_graphics(); @@ -289,8 +266,7 @@ static void mask_filter_render(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { @@ -303,21 +279,16 @@ static void mask_filter_render(void *data, gs_effect_t *effect) bool size_to_x; float fix; - source_size.x = - (float)obs_source_get_base_width(target); - source_size.y = - (float)obs_source_get_base_height(target); - mask_size.x = - (float)gs_texture_get_width(filter->target); - mask_size.y = - (float)gs_texture_get_height(filter->target); + source_size.x = (float)obs_source_get_base_width(target); + source_size.y = (float)obs_source_get_base_height(target); + mask_size.x = (float)gs_texture_get_width(filter->target); + mask_size.y = (float)gs_texture_get_height(filter->target); source_aspect = source_size.x / source_size.y; mask_aspect = mask_size.x / mask_size.y; size_to_x = (source_aspect < mask_aspect); - fix = size_to_x ? (source_size.x / mask_size.x) - : (source_size.y / mask_size.y); + fix = size_to_x ? (source_size.x / mask_size.x) : (source_size.y / mask_size.y); vec2_mulf(&mask_size, &mask_size, fix); vec2_div(&mul_val, &source_size, &mask_size); @@ -328,41 +299,33 @@ static void mask_filter_render(void *data, gs_effect_t *effect) vec2_div(&add_val, &add_val, &mask_size); } - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { - param = gs_effect_get_param_by_name(filter->effect, - "target"); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { + param = gs_effect_get_param_by_name(filter->effect, "target"); gs_effect_set_texture_srgb(param, filter->target); - param = gs_effect_get_param_by_name(filter->effect, - "color"); + param = gs_effect_get_param_by_name(filter->effect, "color"); gs_effect_set_vec4(param, &filter->color); - param = gs_effect_get_param_by_name(filter->effect, - "mul_val"); + param = gs_effect_get_param_by_name(filter->effect, "mul_val"); gs_effect_set_vec2(param, &mul_val); - param = gs_effect_get_param_by_name(filter->effect, - "add_val"); + param = gs_effect_get_param_by_name(filter->effect, "add_val"); gs_effect_set_vec2(param, &add_val); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_end(filter->context, - filter->effect, 0, 0); + obs_source_process_filter_end(filter->context, filter->effect, 0, 0); gs_blend_state_pop(); } } } -static enum gs_color_space -mask_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space mask_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -375,8 +338,7 @@ mask_filter_get_color_space(void *data, size_t count, struct mask_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-filters/noise-gate-filter.c b/plugins/obs-filters/noise-gate-filter.c index a8664097e..6a98af32c 100644 --- a/plugins/obs-filters/noise-gate-filter.c +++ b/plugins/obs-filters/noise-gate-filter.c @@ -2,9 +2,8 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[noise gate: '%s'] " format, \ - obs_source_get_name(ng->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[noise gate: '%s'] " format, obs_source_get_name(ng->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -108,8 +107,7 @@ static void *noise_gate_create(obs_data_t *settings, obs_source_t *filter) return ng; } -static struct obs_audio_data * -noise_gate_filter_audio(void *data, struct obs_audio_data *audio) +static struct obs_audio_data *noise_gate_filter_audio(void *data, struct obs_audio_data *audio) { struct noise_gate_data *ng = data; @@ -140,13 +138,11 @@ noise_gate_filter_audio(void *data, struct obs_audio_data *audio) ng->level = fmaxf(ng->level, cur_level) - decay_rate; if (ng->is_open) { - ng->attenuation = - fminf(1.0f, ng->attenuation + attack_rate); + ng->attenuation = fminf(1.0f, ng->attenuation + attack_rate); } else { ng->held_time += sample_rate_i; if (ng->held_time > hold_time) { - ng->attenuation = fmaxf( - 0.0f, ng->attenuation - release_rate); + ng->attenuation = fmaxf(0.0f, ng->attenuation - release_rate); } } @@ -171,22 +167,15 @@ static obs_properties_t *noise_gate_properties(void *data) obs_properties_t *ppts = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_float_slider(ppts, S_CLOSE_THRESHOLD, - TEXT_CLOSE_THRESHOLD, VOL_MIN, - VOL_MAX, 1.0); + p = obs_properties_add_float_slider(ppts, S_CLOSE_THRESHOLD, TEXT_CLOSE_THRESHOLD, VOL_MIN, VOL_MAX, 1.0); obs_property_float_set_suffix(p, " dB"); - p = obs_properties_add_float_slider(ppts, S_OPEN_THRESHOLD, - TEXT_OPEN_THRESHOLD, VOL_MIN, - VOL_MAX, 1.0); + p = obs_properties_add_float_slider(ppts, S_OPEN_THRESHOLD, TEXT_OPEN_THRESHOLD, VOL_MIN, VOL_MAX, 1.0); obs_property_float_set_suffix(p, " dB"); - p = obs_properties_add_int(ppts, S_ATTACK_TIME, TEXT_ATTACK_TIME, 0, - 10000, 1); + p = obs_properties_add_int(ppts, S_ATTACK_TIME, TEXT_ATTACK_TIME, 0, 10000, 1); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_int(ppts, S_HOLD_TIME, TEXT_HOLD_TIME, 0, 10000, - 1); + p = obs_properties_add_int(ppts, S_HOLD_TIME, TEXT_HOLD_TIME, 0, 10000, 1); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_int(ppts, S_RELEASE_TIME, TEXT_RELEASE_TIME, 0, - 10000, 1); + p = obs_properties_add_int(ppts, S_RELEASE_TIME, TEXT_RELEASE_TIME, 0, 10000, 1); obs_property_int_set_suffix(p, " ms"); UNUSED_PARAMETER(data); diff --git a/plugins/obs-filters/noise-suppress-filter.c b/plugins/obs-filters/noise-suppress-filter.c index cde1c7b9b..ce9bb6629 100644 --- a/plugins/obs-filters/noise-suppress-filter.c +++ b/plugins/obs-filters/noise-suppress-filter.c @@ -25,9 +25,8 @@ bool nvafx_loaded = false; /* -------------------------------------------------------- */ -#define do_log(level, format, ...) \ - blog(level, "[noise suppress: '%s'] " format, \ - obs_source_get_name(ng->context), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[noise suppress: '%s'] " format, obs_source_get_name(ng->context), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -57,12 +56,9 @@ bool nvafx_loaded = false; #define TEXT_METHOD_RNN MT_("NoiseSuppress.Method.RNNoise") #define TEXT_METHOD_NVAFX_DENOISER MT_("NoiseSuppress.Method.Nvafx.Denoiser") #define TEXT_METHOD_NVAFX_DEREVERB MT_("NoiseSuppress.Method.Nvafx.Dereverb") -#define TEXT_METHOD_NVAFX_DEREVERB_DENOISER \ - MT_("NoiseSuppress.Method.Nvafx.DenoiserPlusDereverb") -#define TEXT_METHOD_NVAFX_DEPRECATION \ - MT_("NoiseSuppress.Method.Nvafx.Deprecation") -#define TEXT_METHOD_NVAFX_DEPRECATION2 \ - MT_("NoiseSuppress.Method.Nvafx.Deprecation2") +#define TEXT_METHOD_NVAFX_DEREVERB_DENOISER MT_("NoiseSuppress.Method.Nvafx.DenoiserPlusDereverb") +#define TEXT_METHOD_NVAFX_DEPRECATION MT_("NoiseSuppress.Method.Nvafx.Deprecation") +#define TEXT_METHOD_NVAFX_DEPRECATION2 MT_("NoiseSuppress.Method.Nvafx.Deprecation2") #define MAX_PREPROC_CHANNELS 8 @@ -72,8 +68,7 @@ bool nvafx_loaded = false; /* nvafx constants, these can't be changed */ #define NVAFX_SAMPLE_RATE 48000 -#define NVAFX_FRAME_SIZE \ - 480 /* the sdk does not explicitly set this as a constant though it relies on it*/ +#define NVAFX_FRAME_SIZE 480 /* the sdk does not explicitly set this as a constant though it relies on it*/ /* If the following constant changes, RNNoise breaks */ #define BUFFER_SIZE_MSEC 10 @@ -178,13 +173,10 @@ static void noise_suppress_destroy(void *data) bfree(ng); } -static inline void alloc_channel(struct noise_suppress_data *ng, - uint32_t sample_rate, size_t channel, - size_t frames) +static inline void alloc_channel(struct noise_suppress_data *ng, uint32_t sample_rate, size_t channel, size_t frames) { #ifdef LIBSPEEXDSP_ENABLED - ng->spx_states[channel] = - speex_preprocess_state_init((int)frames, sample_rate); + ng->spx_states[channel] = speex_preprocess_state_init((int)frames, sample_rate); #else UNUSED_PARAMETER(sample_rate); #endif @@ -249,22 +241,18 @@ static void noise_suppress_update(void *data, obs_data_t *s) /* One speex/rnnoise state for each channel (limit 2) */ ng->copy_buffers[0] = bmalloc(frames * channels * sizeof(float)); #ifdef LIBSPEEXDSP_ENABLED - ng->spx_segment_buffers[0] = - bmalloc(frames * channels * sizeof(spx_int16_t)); + ng->spx_segment_buffers[0] = bmalloc(frames * channels * sizeof(spx_int16_t)); #endif #ifdef LIBRNNOISE_ENABLED - ng->rnn_segment_buffers[0] = - bmalloc(RNNOISE_FRAME_SIZE * channels * sizeof(float)); + ng->rnn_segment_buffers[0] = bmalloc(RNNOISE_FRAME_SIZE * channels * sizeof(float)); #endif for (size_t c = 1; c < channels; ++c) { ng->copy_buffers[c] = ng->copy_buffers[c - 1] + frames; #ifdef LIBSPEEXDSP_ENABLED - ng->spx_segment_buffers[c] = - ng->spx_segment_buffers[c - 1] + frames; + ng->spx_segment_buffers[c] = ng->spx_segment_buffers[c - 1] + frames; #endif #ifdef LIBRNNOISE_ENABLED - ng->rnn_segment_buffers[c] = - ng->rnn_segment_buffers[c - 1] + RNNOISE_FRAME_SIZE; + ng->rnn_segment_buffers[c] = ng->rnn_segment_buffers[c - 1] + RNNOISE_FRAME_SIZE; #endif } for (size_t i = 0; i < channels; i++) @@ -292,8 +280,7 @@ static void noise_suppress_update(void *data, obs_data_t *s) static void *noise_suppress_create(obs_data_t *settings, obs_source_t *filter) { - struct noise_suppress_data *ng = - bzalloc(sizeof(struct noise_suppress_data)); + struct noise_suppress_data *ng = bzalloc(sizeof(struct noise_suppress_data)); ng->context = filter; ng->nvafx_enabled = false; @@ -304,22 +291,18 @@ static void *noise_suppress_create(obs_data_t *settings, obs_source_t *filter) const char *method = obs_data_get_string(settings, S_METHOD); ng->nvafx_enabled = strcmp(method, S_METHOD_NVAFX_DENOISER) == 0 || strcmp(method, S_METHOD_NVAFX_DEREVERB) == 0 || - strcmp(method, S_METHOD_NVAFX_DEREVERB_DENOISER) == - 0; + strcmp(method, S_METHOD_NVAFX_DEREVERB_DENOISER) == 0; if (ng->nvafx_enabled) { const char *str1 = obs_source_get_name(filter); char *str2 = "_ported"; - char *new_name = - (char *)malloc(1 + strlen(str1) + strlen(str2)); + char *new_name = (char *)malloc(1 + strlen(str1) + strlen(str2)); strcpy(new_name, str1); strcat(new_name, str2); obs_data_t *new_settings = obs_data_create(); obs_data_set_string(new_settings, S_METHOD, method); - double intensity = - obs_data_get_double(settings, S_NVAFX_INTENSITY); + double intensity = obs_data_get_double(settings, S_NVAFX_INTENSITY); obs_data_set_double(new_settings, S_NVAFX_INTENSITY, intensity); - ng->migrated_filter = obs_source_create( - "nvidia_audiofx_filter", new_name, new_settings, NULL); + ng->migrated_filter = obs_source_create("nvidia_audiofx_filter", new_name, new_settings, NULL); obs_data_release(new_settings); } #endif @@ -332,9 +315,7 @@ static inline void process_speexdsp(struct noise_suppress_data *ng) #ifdef LIBSPEEXDSP_ENABLED /* Set args */ for (size_t i = 0; i < ng->channels; i++) - speex_preprocess_ctl(ng->spx_states[i], - SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, - &ng->suppress_level); + speex_preprocess_ctl(ng->spx_states[i], SPEEX_PREPROCESS_SET_NOISE_SUPPRESS, &ng->suppress_level); /* Convert to 16bit */ for (size_t i = 0; i < ng->channels; i++) @@ -344,21 +325,17 @@ static inline void process_speexdsp(struct noise_suppress_data *ng) s = 1.0f; else if (s < -1.0f) s = -1.0f; - ng->spx_segment_buffers[i][j] = - (spx_int16_t)(s * c_32_to_16); + ng->spx_segment_buffers[i][j] = (spx_int16_t)(s * c_32_to_16); } /* Execute */ for (size_t i = 0; i < ng->channels; i++) - speex_preprocess_run(ng->spx_states[i], - ng->spx_segment_buffers[i]); + speex_preprocess_run(ng->spx_states[i], ng->spx_segment_buffers[i]); /* Convert back to 32bit */ for (size_t i = 0; i < ng->channels; i++) for (size_t j = 0; j < ng->frames; j++) - ng->copy_buffers[i][j] = - (float)ng->spx_segment_buffers[i][j] / - c_16_to_32; + ng->copy_buffers[i][j] = (float)ng->spx_segment_buffers[i][j] / c_16_to_32; #else UNUSED_PARAMETER(ng); #endif @@ -372,18 +349,14 @@ static inline void process_rnnoise(struct noise_suppress_data *ng) float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; - audio_resampler_resample(ng->rnn_resampler, (uint8_t **)output, - &out_frames, &ts_offset, - (const uint8_t **)ng->copy_buffers, - (uint32_t)ng->frames); + audio_resampler_resample(ng->rnn_resampler, (uint8_t **)output, &out_frames, &ts_offset, + (const uint8_t **)ng->copy_buffers, (uint32_t)ng->frames); for (size_t i = 0; i < ng->channels; i++) { - for (ssize_t j = 0, k = (ssize_t)out_frames - - RNNOISE_FRAME_SIZE; - j < RNNOISE_FRAME_SIZE; ++j, ++k) { + for (ssize_t j = 0, k = (ssize_t)out_frames - RNNOISE_FRAME_SIZE; j < RNNOISE_FRAME_SIZE; + ++j, ++k) { if (k >= 0) { - ng->rnn_segment_buffers[i][j] = - output[i][k] * 32768.0f; + ng->rnn_segment_buffers[i][j] = output[i][k] * 32768.0f; } else { ng->rnn_segment_buffers[i][j] = 0; } @@ -392,17 +365,14 @@ static inline void process_rnnoise(struct noise_suppress_data *ng) } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) { - ng->rnn_segment_buffers[i][j] = - ng->copy_buffers[i][j] * 32768.0f; + ng->rnn_segment_buffers[i][j] = ng->copy_buffers[i][j] * 32768.0f; } } } /* Execute */ for (size_t i = 0; i < ng->channels; i++) { - rnnoise_process_frame(ng->rnn_states[i], - ng->rnn_segment_buffers[i], - ng->rnn_segment_buffers[i]); + rnnoise_process_frame(ng->rnn_states[i], ng->rnn_segment_buffers[i], ng->rnn_segment_buffers[i]); } /* Revert signal level adjustment, resample back if necessary */ @@ -410,18 +380,13 @@ static inline void process_rnnoise(struct noise_suppress_data *ng) float *output[MAX_PREPROC_CHANNELS]; uint32_t out_frames; uint64_t ts_offset; - audio_resampler_resample( - ng->rnn_resampler_back, (uint8_t **)output, &out_frames, - &ts_offset, (const uint8_t **)ng->rnn_segment_buffers, - RNNOISE_FRAME_SIZE); + audio_resampler_resample(ng->rnn_resampler_back, (uint8_t **)output, &out_frames, &ts_offset, + (const uint8_t **)ng->rnn_segment_buffers, RNNOISE_FRAME_SIZE); for (size_t i = 0; i < ng->channels; i++) { - for (ssize_t j = 0, - k = (ssize_t)out_frames - ng->frames; - j < (ssize_t)ng->frames; ++j, ++k) { + for (ssize_t j = 0, k = (ssize_t)out_frames - ng->frames; j < (ssize_t)ng->frames; ++j, ++k) { if (k >= 0) { - ng->copy_buffers[i][j] = - output[i][k] / 32768.0f; + ng->copy_buffers[i][j] = output[i][k] / 32768.0f; } else { ng->copy_buffers[i][j] = 0; } @@ -430,9 +395,7 @@ static inline void process_rnnoise(struct noise_suppress_data *ng) } else { for (size_t i = 0; i < ng->channels; i++) { for (size_t j = 0; j < RNNOISE_FRAME_SIZE; ++j) { - ng->copy_buffers[i][j] = - ng->rnn_segment_buffers[i][j] / - 32768.0f; + ng->copy_buffers[i][j] = ng->rnn_segment_buffers[i][j] / 32768.0f; } } } @@ -447,8 +410,7 @@ static inline void process(struct noise_suppress_data *ng) return; /* Pop from input deque */ for (size_t i = 0; i < ng->channels; i++) - deque_pop_front(&ng->input_buffers[i], ng->copy_buffers[i], - ng->frames * sizeof(float)); + deque_pop_front(&ng->input_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float)); if (ng->use_rnnoise) { process_rnnoise(ng); @@ -458,8 +420,7 @@ static inline void process(struct noise_suppress_data *ng) /* Push to output deque */ for (size_t i = 0; i < ng->channels; i++) - deque_push_back(&ng->output_buffers[i], ng->copy_buffers[i], - ng->frames * sizeof(float)); + deque_push_back(&ng->output_buffers[i], ng->copy_buffers[i], ng->frames * sizeof(float)); } struct ng_audio_info { @@ -482,8 +443,7 @@ static void reset_data(struct noise_suppress_data *ng) clear_deque(&ng->info_buffer); } -static struct obs_audio_data * -noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) +static struct obs_audio_data *noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) { struct noise_suppress_data *ng = data; struct ng_audio_info info; @@ -518,8 +478,7 @@ noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) * audio data. clear all circular buffers to prevent old audio data * from being processed as part of the new data. */ if (ng->last_timestamp) { - int64_t diff = llabs((int64_t)ng->last_timestamp - - (int64_t)audio->timestamp); + int64_t diff = llabs((int64_t)ng->last_timestamp - (int64_t)audio->timestamp); if (diff > 1000000000LL) reset_data(ng); @@ -536,8 +495,7 @@ noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) /* ----------------------------------------------- * push back current audio data to input deque */ for (size_t i = 0; i < ng->channels; i++) - deque_push_back(&ng->input_buffers[i], audio->data[i], - audio->frames * sizeof(float)); + deque_push_back(&ng->input_buffers[i], audio->data[i], audio->frames * sizeof(float)); /* ----------------------------------------------- * pop/process each 10ms segments, push back to output deque */ @@ -561,11 +519,9 @@ noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) da_resize(ng->output_data, out_size * ng->channels); for (size_t i = 0; i < ng->channels; i++) { - ng->output_audio.data[i] = - (uint8_t *)&ng->output_data.array[i * out_size]; + ng->output_audio.data[i] = (uint8_t *)&ng->output_data.array[i * out_size]; - deque_pop_front(&ng->output_buffers[i], - ng->output_audio.data[i], out_size); + deque_pop_front(&ng->output_buffers[i], ng->output_audio.data[i], out_size); } ng->output_audio.frames = info.frames; @@ -573,21 +529,16 @@ noise_suppress_filter_audio(void *data, struct obs_audio_data *audio) return &ng->output_audio; } -static bool noise_suppress_method_modified(obs_properties_t *props, - obs_property_t *property, - obs_data_t *settings) +static bool noise_suppress_method_modified(obs_properties_t *props, obs_property_t *property, obs_data_t *settings) { - obs_property_t *p_suppress_level = - obs_properties_get(props, S_SUPPRESS_LEVEL); - obs_property_t *p_navfx_intensity = - obs_properties_get(props, S_NVAFX_INTENSITY); + obs_property_t *p_suppress_level = obs_properties_get(props, S_SUPPRESS_LEVEL); + obs_property_t *p_navfx_intensity = obs_properties_get(props, S_NVAFX_INTENSITY); const char *method = obs_data_get_string(settings, S_METHOD); bool enable_level = strcmp(method, S_METHOD_SPEEX) == 0; - bool enable_intensity = - strcmp(method, S_METHOD_NVAFX_DENOISER) == 0 || - strcmp(method, S_METHOD_NVAFX_DEREVERB) == 0 || - strcmp(method, S_METHOD_NVAFX_DEREVERB_DENOISER) == 0; + bool enable_intensity = strcmp(method, S_METHOD_NVAFX_DENOISER) == 0 || + strcmp(method, S_METHOD_NVAFX_DEREVERB) == 0 || + strcmp(method, S_METHOD_NVAFX_DEREVERB_DENOISER) == 0; obs_property_set_visible(p_suppress_level, enable_level); obs_property_set_visible(p_navfx_intensity, enable_intensity); @@ -631,48 +582,37 @@ static obs_properties_t *noise_suppress_properties(void *data) #endif #if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED) - obs_property_t *method = obs_properties_add_list( - ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *method = + obs_properties_add_list(ppts, S_METHOD, TEXT_METHOD, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(method, TEXT_METHOD_SPEEX, S_METHOD_SPEEX); obs_property_list_add_string(method, TEXT_METHOD_RNN, S_METHOD_RNN); #ifdef LIBNVAFX_ENABLED if (ng->nvafx_enabled) { - obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DENOISER, - S_METHOD_NVAFX_DENOISER); - obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB, - S_METHOD_NVAFX_DEREVERB); - obs_property_list_add_string( - method, TEXT_METHOD_NVAFX_DEREVERB_DENOISER, - S_METHOD_NVAFX_DEREVERB_DENOISER); + obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DENOISER, S_METHOD_NVAFX_DENOISER); + obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB, S_METHOD_NVAFX_DEREVERB); + obs_property_list_add_string(method, TEXT_METHOD_NVAFX_DEREVERB_DENOISER, + S_METHOD_NVAFX_DEREVERB_DENOISER); obs_property_list_item_disable(method, 2, true); obs_property_list_item_disable(method, 3, true); obs_property_list_item_disable(method, 4, true); } #endif - obs_property_set_modified_callback(method, - noise_suppress_method_modified); + obs_property_set_modified_callback(method, noise_suppress_method_modified); #endif #ifdef LIBSPEEXDSP_ENABLED - obs_property_t *speex_slider = obs_properties_add_int_slider( - ppts, S_SUPPRESS_LEVEL, TEXT_SUPPRESS_LEVEL, SUP_MIN, SUP_MAX, - 1); + obs_property_t *speex_slider = + obs_properties_add_int_slider(ppts, S_SUPPRESS_LEVEL, TEXT_SUPPRESS_LEVEL, SUP_MIN, SUP_MAX, 1); obs_property_int_set_suffix(speex_slider, " dB"); #endif #ifdef LIBNVAFX_ENABLED if (ng->nvafx_enabled) { - obs_properties_add_float_slider(ppts, S_NVAFX_INTENSITY, - TEXT_NVAFX_INTENSITY, 0.0f, - 1.0f, 0.01f); - obs_property_t *warning2 = obs_properties_add_text( - ppts, "deprecation2", NULL, OBS_TEXT_INFO); - obs_property_text_set_info_type(warning2, - OBS_TEXT_INFO_WARNING); - obs_property_set_long_description( - warning2, TEXT_METHOD_NVAFX_DEPRECATION2); + obs_properties_add_float_slider(ppts, S_NVAFX_INTENSITY, TEXT_NVAFX_INTENSITY, 0.0f, 1.0f, 0.01f); + obs_property_t *warning2 = obs_properties_add_text(ppts, "deprecation2", NULL, OBS_TEXT_INFO); + obs_property_text_set_info_type(warning2, OBS_TEXT_INFO_WARNING); + obs_property_set_long_description(warning2, TEXT_METHOD_NVAFX_DEPRECATION2); } #if defined(LIBRNNOISE_ENABLED) && defined(LIBSPEEXDSP_ENABLED) diff --git a/plugins/obs-filters/nvafx-load.h b/plugins/obs-filters/nvafx-load.h index ca79d40cd..5e8a0e9c9 100644 --- a/plugins/obs-filters/nvafx-load.h +++ b/plugins/obs-filters/nvafx-load.h @@ -23,21 +23,14 @@ static HMODULE nv_cuda = NULL; /** Model paths */ #define NVAFX_EFFECT_DENOISER_MODEL "\\models\\denoiser_48k.trtpkg" #define NVAFX_EFFECT_DEREVERB_MODEL "\\models\\dereverb_48k.trtpkg" -#define NVAFX_EFFECT_DEREVERB_DENOISER_MODEL \ - "\\models\\dereverb_denoiser_48k.trtpkg" +#define NVAFX_EFFECT_DEREVERB_DENOISER_MODEL "\\models\\dereverb_denoiser_48k.trtpkg" -#define NVAFX_CHAINED_EFFECT_DENOISER_16k_SUPERRES_16k_TO_48k \ - "denoiser16k_superres16kto48k" -#define NVAFX_CHAINED_EFFECT_DEREVERB_16k_SUPERRES_16k_TO_48k \ - "dereverb16k_superres16kto48k" -#define NVAFX_CHAINED_EFFECT_DEREVERB_DENOISER_16k_SUPERRES_16k_TO_48k \ - "dereverb_denoiser16k_superres16kto48k" -#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DENOISER_16k \ - "superres8kto16k_denoiser16k" -#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_16k \ - "superres8kto16k_dereverb16k" -#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_DENOISER_16k \ - "superres8kto16k_dereverb_denoiser16k" +#define NVAFX_CHAINED_EFFECT_DENOISER_16k_SUPERRES_16k_TO_48k "denoiser16k_superres16kto48k" +#define NVAFX_CHAINED_EFFECT_DEREVERB_16k_SUPERRES_16k_TO_48k "dereverb16k_superres16kto48k" +#define NVAFX_CHAINED_EFFECT_DEREVERB_DENOISER_16k_SUPERRES_16k_TO_48k "dereverb_denoiser16k_superres16kto48k" +#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DENOISER_16k "superres8kto16k_denoiser16k" +#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_16k "superres8kto16k_dereverb16k" +#define NVAFX_CHAINED_EFFECT_SUPERRES_8k_TO_16k_DEREVERB_DENOISER_16k "superres8kto16k_dereverb_denoiser16k" /** Parameter selectors */ @@ -61,8 +54,7 @@ static HMODULE nv_cuda = NULL; #pragma deprecated(NVAFX_PARAM_DENOISER_SAMPLE_RATE) #define NVAFX_PARAM_DENOISER_SAMPLE_RATE NVAFX_PARAM_SAMPLE_RATE #pragma deprecated(NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME) -#define NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME \ - NVAFX_PARAM_NUM_SAMPLES_PER_FRAME +#define NVAFX_PARAM_DENOISER_NUM_SAMPLES_PER_FRAME NVAFX_PARAM_NUM_SAMPLES_PER_FRAME #pragma deprecated(NVAFX_PARAM_DENOISER_NUM_CHANNELS) #define NVAFX_PARAM_DENOISER_NUM_CHANNELS NVAFX_PARAM_NUM_CHANNELS #pragma deprecated(NVAFX_PARAM_DENOISER_INTENSITY_RATIO) @@ -113,64 +105,34 @@ typedef const char *NvAFX_EffectSelector; typedef const char *NvAFX_ParameterSelector; typedef void *NvAFX_Handle; -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetEffectList_t)(int *num_effects, - NvAFX_EffectSelector *effects[]); -typedef NvAFX_Status - NVAFX_API (*NvAFX_CreateEffect_t)(NvAFX_EffectSelector code, - NvAFX_Handle *effect); -typedef NvAFX_Status - NVAFX_API (*NvAFX_CreateChainedEffect_t)(NvAFX_EffectSelector code, - NvAFX_Handle *effect); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetEffectList_t)(int *num_effects, NvAFX_EffectSelector *effects[]); +typedef NvAFX_Status NVAFX_API (*NvAFX_CreateEffect_t)(NvAFX_EffectSelector code, NvAFX_Handle *effect); +typedef NvAFX_Status NVAFX_API (*NvAFX_CreateChainedEffect_t)(NvAFX_EffectSelector code, NvAFX_Handle *effect); typedef NvAFX_Status NVAFX_API (*NvAFX_DestroyEffect_t)(NvAFX_Handle effect); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetU32_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - unsigned int val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetU32List_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - unsigned int *val, unsigned int size); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetString_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - const char *val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetStringList_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - const char **val, unsigned int size); -typedef NvAFX_Status NVAFX_API (*NvAFX_SetFloat_t)( - NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_SetFloatList_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - float *val, unsigned int size); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetU32_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - unsigned int *val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetString_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - char *val, int max_length); -typedef NvAFX_Status NVAFX_API (*NvAFX_GetStringList_t)( - NvAFX_Handle effect, NvAFX_ParameterSelector param_name, char **val, - int *max_length, unsigned int size); -typedef NvAFX_Status NVAFX_API (*NvAFX_GetFloat_t)( - NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float *val); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetFloatList_t)(NvAFX_Handle effect, - NvAFX_ParameterSelector param_name, - float *val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetU32_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + unsigned int val); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetU32List_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + unsigned int *val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetString_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + const char *val); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetStringList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + const char **val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetFloat_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float val); +typedef NvAFX_Status NVAFX_API (*NvAFX_SetFloatList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + float *val, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetU32_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + unsigned int *val); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetString_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, char *val, + int max_length); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetStringList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + char **val, int *max_length, unsigned int size); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetFloat_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, float *val); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetFloatList_t)(NvAFX_Handle effect, NvAFX_ParameterSelector param_name, + float *val, unsigned int size); typedef NvAFX_Status NVAFX_API (*NvAFX_Load_t)(NvAFX_Handle effect); -typedef NvAFX_Status - NVAFX_API (*NvAFX_GetSupportedDevices_t)(NvAFX_Handle effect, int *num, - int *devices); -typedef NvAFX_Status NVAFX_API (*NvAFX_Run_t)(NvAFX_Handle effect, - const float **input, - float **output, - unsigned num_samples, - unsigned num_channels); +typedef NvAFX_Status NVAFX_API (*NvAFX_GetSupportedDevices_t)(NvAFX_Handle effect, int *num, int *devices); +typedef NvAFX_Status NVAFX_API (*NvAFX_Run_t)(NvAFX_Handle effect, const float **input, float **output, + unsigned num_samples, unsigned num_channels); typedef NvAFX_Status NVAFX_API (*NvAFX_Reset_t)(NvAFX_Handle effect); /* cuda */ @@ -288,8 +250,7 @@ void release_lib(void) static bool nvafx_get_sdk_path(char *buffer, const size_t len) { - DWORD ret = - GetEnvironmentVariableA("NVAFX_SDK_DIR", buffer, (DWORD)len); + DWORD ret = GetEnvironmentVariableA("NVAFX_SDK_DIR", buffer, (DWORD)len); if (!ret || ret >= len - 1) return false; @@ -328,8 +289,7 @@ static unsigned int get_lib_version(void) struct win_version_info nto_ver = {0}; if (get_dll_ver(L"NVAudioEffects.dll", &nto_ver)) - version = nto_ver.major << 24 | nto_ver.minor << 16 | - nto_ver.build << 8 | nto_ver.revis << 0; + version = nto_ver.major << 24 | nto_ver.minor << 16 | nto_ver.build << 8 | nto_ver.revis << 0; SetDllDirectoryA(NULL); return version; diff --git a/plugins/obs-filters/scale-filter.c b/plugins/obs-filters/scale-filter.c index eecb31f1a..215669114 100644 --- a/plugins/obs-filters/scale-filter.c +++ b/plugins/obs-filters/scale-filter.c @@ -86,8 +86,7 @@ static void scale_filter_update(void *data, obs_data_t *settings) if (ret == 2) { filter->aspect_ratio_only = false; } else { - ret = sscanf(res_str, "%d:%d", &filter->cx_in, - &filter->cy_in); + ret = sscanf(res_str, "%d:%d", &filter->cx_in, &filter->cy_in); if (ret != 2) { filter->valid = false; return; @@ -128,8 +127,7 @@ static void scale_filter_destroy(void *data) static void *scale_filter_create(obs_data_t *settings, obs_source_t *context) { - struct scale_filter_data *filter = - bzalloc(sizeof(struct scale_filter_data)); + struct scale_filter_data *filter = bzalloc(sizeof(struct scale_filter_data)); struct gs_sampler_info sampler_info = {0}; filter->context = context; @@ -241,41 +239,33 @@ static void scale_filter_tick(void *data, float seconds) } } - filter->undistort_factor = filter->undistort ? (new_aspect / old_aspect) - : 1.0; + filter->undistort_factor = filter->undistort ? (new_aspect / old_aspect) : 1.0; filter->effect = obs_get_base_effect(type); - filter->image_param = - gs_effect_get_param_by_name(filter->effect, "image"); + filter->image_param = gs_effect_get_param_by_name(filter->effect, "image"); if (type != OBS_EFFECT_DEFAULT) { - filter->dimension_param = gs_effect_get_param_by_name( - filter->effect, "base_dimension"); - filter->dimension_i_param = gs_effect_get_param_by_name( - filter->effect, "base_dimension_i"); + filter->dimension_param = gs_effect_get_param_by_name(filter->effect, "base_dimension"); + filter->dimension_i_param = gs_effect_get_param_by_name(filter->effect, "base_dimension_i"); } else { filter->dimension_param = NULL; filter->dimension_i_param = NULL; } if (type == OBS_EFFECT_BICUBIC || type == OBS_EFFECT_LANCZOS) { - filter->undistort_factor_param = gs_effect_get_param_by_name( - filter->effect, "undistort_factor"); + filter->undistort_factor_param = gs_effect_get_param_by_name(filter->effect, "undistort_factor"); } else { filter->undistort_factor_param = NULL; } - filter->multiplier_param = - gs_effect_get_param_by_name(filter->effect, "multiplier"); + filter->multiplier_param = gs_effect_get_param_by_name(filter->effect, "multiplier"); UNUSED_PARAMETER(seconds); } -static const char * -get_tech_name_and_multiplier(const struct scale_filter_data *filter, - enum gs_color_space current_space, - enum gs_color_space source_space, - float *multiplier) +static const char *get_tech_name_and_multiplier(const struct scale_filter_data *filter, + enum gs_color_space current_space, enum gs_color_space source_space, + float *multiplier) { *multiplier = 1.f; switch (source_space) { @@ -422,51 +412,38 @@ static void scale_filter_render(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); float multiplier; - const char *technique = get_tech_name_and_multiplier( - filter, gs_get_color_space(), source_space, &multiplier); - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_NO_DIRECT_RENDERING)) { + const char *technique = get_tech_name_and_multiplier(filter, gs_get_color_space(), source_space, &multiplier); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_NO_DIRECT_RENDERING)) { if (filter->dimension_param) - gs_effect_set_vec2(filter->dimension_param, - &filter->dimension); + gs_effect_set_vec2(filter->dimension_param, &filter->dimension); if (filter->dimension_i_param) - gs_effect_set_vec2(filter->dimension_i_param, - &filter->dimension_i); + gs_effect_set_vec2(filter->dimension_i_param, &filter->dimension_i); if (filter->undistort_factor_param) - gs_effect_set_float(filter->undistort_factor_param, - (float)filter->undistort_factor); + gs_effect_set_float(filter->undistort_factor_param, (float)filter->undistort_factor); if (filter->multiplier_param) - gs_effect_set_float(filter->multiplier_param, - multiplier); + gs_effect_set_float(filter->multiplier_param, multiplier); if (filter->sampling == OBS_SCALE_POINT) - gs_effect_set_next_sampler(filter->image_param, - filter->point_sampler); + gs_effect_set_next_sampler(filter->image_param, filter->point_sampler); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_tech_end(filter->context, - filter->effect, - filter->cx_out, - filter->cy_out, technique); + obs_source_process_filter_tech_end(filter->context, filter->effect, filter->cx_out, filter->cy_out, + technique); gs_blend_state_pop(); } } -static const double downscale_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, - (1.0 / 0.6), 1.75, 2.0, 2.25, - 2.5, 2.75, 3.0}; +static const double downscale_vals[] = {1.0, 1.25, (1.0 / 0.75), 1.5, (1.0 / 0.6), 1.75, 2.0, 2.25, 2.5, 2.75, 3.0}; #define NUM_DOWNSCALES (sizeof(downscale_vals) / sizeof(double)) @@ -474,8 +451,7 @@ static const char *aspects[] = {"16:9", "16:10", "4:3", "1:1"}; #define NUM_ASPECTS (sizeof(aspects) / sizeof(const char *)) -static bool sampling_modified(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool sampling_modified(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { const char *sampling = obs_data_get_string(settings, S_SAMPLING); @@ -492,8 +468,7 @@ static bool sampling_modified(obs_properties_t *props, obs_property_t *p, has_undistort = true; } - obs_property_set_visible(obs_properties_get(props, S_UNDISTORT), - has_undistort); + obs_property_set_visible(obs_properties_get(props, S_UNDISTORT), has_undistort); UNUSED_PARAMETER(p); return true; @@ -523,21 +498,17 @@ static obs_properties_t *scale_filter_properties(void *data) downscales[i].cy = (int)((double)cy / downscale_vals[i]); } - p = obs_properties_add_list(props, S_SAMPLING, T_SAMPLING, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(props, S_SAMPLING, T_SAMPLING, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(p, sampling_modified); obs_property_list_add_string(p, T_SAMPLING_POINT, S_SAMPLING_POINT); - obs_property_list_add_string(p, T_SAMPLING_BILINEAR, - S_SAMPLING_BILINEAR); + obs_property_list_add_string(p, T_SAMPLING_BILINEAR, S_SAMPLING_BILINEAR); obs_property_list_add_string(p, T_SAMPLING_BICUBIC, S_SAMPLING_BICUBIC); obs_property_list_add_string(p, T_SAMPLING_LANCZOS, S_SAMPLING_LANCZOS); obs_property_list_add_string(p, T_SAMPLING_AREA, S_SAMPLING_AREA); /* ----------------- */ - p = obs_properties_add_list(props, S_RESOLUTION, T_RESOLUTION, - OBS_COMBO_TYPE_EDITABLE, + p = obs_properties_add_list(props, S_RESOLUTION, T_RESOLUTION, OBS_COMBO_TYPE_EDITABLE, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_NONE, T_NONE); @@ -548,8 +519,7 @@ static obs_properties_t *scale_filter_properties(void *data) for (size_t i = 0; i < NUM_DOWNSCALES; i++) { char str[32]; - snprintf(str, sizeof(str), "%dx%d", downscales[i].cx, - downscales[i].cy); + snprintf(str, sizeof(str), "%dx%d", downscales[i].cx, downscales[i].cy); obs_property_list_add_string(p, str, str); } @@ -580,9 +550,8 @@ static uint32_t scale_filter_height(void *data) return (uint32_t)filter->cy_out; } -static enum gs_color_space -scale_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space scale_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { const enum gs_color_space potential_spaces[] = { GS_CS_SRGB, @@ -592,8 +561,7 @@ scale_filter_get_color_space(void *data, size_t count, struct scale_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); enum gs_color_space space = source_space; for (size_t i = 0; i < count; ++i) { diff --git a/plugins/obs-filters/scroll-filter.c b/plugins/obs-filters/scroll-filter.c index 589898e74..c12d94f88 100644 --- a/plugins/obs-filters/scroll-filter.c +++ b/plugins/obs-filters/scroll-filter.c @@ -47,14 +47,10 @@ static void *scroll_filter_create(obs_data_t *settings, obs_source_t *context) return NULL; } - filter->param_add = - gs_effect_get_param_by_name(filter->effect, "add_val"); - filter->param_mul = - gs_effect_get_param_by_name(filter->effect, "mul_val"); - filter->param_image = - gs_effect_get_param_by_name(filter->effect, "image"); - filter->param_multiplier = - gs_effect_get_param_by_name(filter->effect, "multiplier"); + filter->param_add = gs_effect_get_param_by_name(filter->effect, "add_val"); + filter->param_mul = gs_effect_get_param_by_name(filter->effect, "mul_val"); + filter->param_image = gs_effect_get_param_by_name(filter->effect, "image"); + filter->param_multiplier = gs_effect_get_param_by_name(filter->effect, "multiplier"); obs_source_update(context, settings); return filter; @@ -81,10 +77,8 @@ static void scroll_filter_update(void *data, obs_data_t *settings) filter->cx = (uint32_t)obs_data_get_int(settings, "cx"); filter->cy = (uint32_t)obs_data_get_int(settings, "cy"); - filter->scroll_speed.x = - (float)obs_data_get_double(settings, "speed_x"); - filter->scroll_speed.y = - (float)obs_data_get_double(settings, "speed_y"); + filter->scroll_speed.x = (float)obs_data_get_double(settings, "speed_x"); + filter->scroll_speed.y = (float)obs_data_get_double(settings, "speed_y"); filter->loop = obs_data_get_bool(settings, "loop"); @@ -105,8 +99,7 @@ static void scroll_filter_update(void *data, obs_data_t *settings) filter->offset.y = 0.0f; } -static bool limit_cx_clicked(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool limit_cx_clicked(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { bool limit_size = obs_data_get_bool(settings, "limit_cx"); obs_property_set_visible(obs_properties_get(props, "cx"), limit_size); @@ -115,8 +108,7 @@ static bool limit_cx_clicked(obs_properties_t *props, obs_property_t *p, return true; } -static bool limit_cy_clicked(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool limit_cy_clicked(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { bool limit_size = obs_data_get_bool(settings, "limit_cy"); obs_property_set_visible(obs_properties_get(props, "cy"), limit_size); @@ -130,27 +122,18 @@ static obs_properties_t *scroll_filter_properties(void *data) obs_properties_t *props = obs_properties_create(); obs_property_t *p; - obs_properties_add_float_slider(props, "speed_x", - obs_module_text("ScrollFilter.SpeedX"), - -500.0, 500.0, 1.0); - obs_properties_add_float_slider(props, "speed_y", - obs_module_text("ScrollFilter.SpeedY"), - -500.0, 500.0, 1.0); + obs_properties_add_float_slider(props, "speed_x", obs_module_text("ScrollFilter.SpeedX"), -500.0, 500.0, 1.0); + obs_properties_add_float_slider(props, "speed_y", obs_module_text("ScrollFilter.SpeedY"), -500.0, 500.0, 1.0); - p = obs_properties_add_bool(props, "limit_cx", - obs_module_text("ScrollFilter.LimitWidth")); + p = obs_properties_add_bool(props, "limit_cx", obs_module_text("ScrollFilter.LimitWidth")); obs_property_set_modified_callback(p, limit_cx_clicked); - obs_properties_add_int(props, "cx", obs_module_text("Crop.Width"), 1, - 8192, 1); + obs_properties_add_int(props, "cx", obs_module_text("Crop.Width"), 1, 8192, 1); - p = obs_properties_add_bool( - props, "limit_cy", obs_module_text("ScrollFilter.LimitHeight")); + p = obs_properties_add_bool(props, "limit_cy", obs_module_text("ScrollFilter.LimitHeight")); obs_property_set_modified_callback(p, limit_cy_clicked); - obs_properties_add_int(props, "cy", obs_module_text("Crop.Height"), 1, - 8192, 1); + obs_properties_add_int(props, "cy", obs_module_text("Crop.Height"), 1, 8192, 1); - obs_properties_add_bool(props, "loop", - obs_module_text("ScrollFilter.Loop")); + obs_properties_add_bool(props, "loop", obs_module_text("ScrollFilter.Loop")); UNUSED_PARAMETER(data); return props; @@ -184,10 +167,8 @@ static void scroll_filter_tick(void *data, float seconds) } } -static const char * -get_tech_name_and_multiplier(enum gs_color_space current_space, - enum gs_color_space source_space, - float *multiplier) +static const char *get_tech_name_and_multiplier(enum gs_color_space current_space, enum gs_color_space source_space, + float *multiplier) { const char *tech_name = "Draw"; *multiplier = 1.f; @@ -252,16 +233,14 @@ static void scroll_filter_render(void *data, gs_effect_t *effect) cy = filter->limit_cy ? filter->cy : base_cy; if (base_cx && base_cy) { - vec2_set(&filter->size_i, 1.0f / (float)base_cx, - 1.0f / (float)base_cy); + vec2_set(&filter->size_i, 1.0f / (float)base_cx, 1.0f / (float)base_cy); } else { vec2_zero(&filter->size_i); obs_source_skip_video_filter(filter->context); return; } - vec2_set(&mul_val, (float)cx / (float)base_cx, - (float)cy / (float)base_cy); + vec2_set(&mul_val, (float)cx / (float)base_cx, (float)cy / (float)base_cy); const enum gs_color_space preferred_spaces[] = { GS_CS_SRGB, @@ -270,28 +249,22 @@ static void scroll_filter_render(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); float multiplier; - const char *technique = get_tech_name_and_multiplier( - gs_get_color_space(), source_space, &multiplier); - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_NO_DIRECT_RENDERING)) { + const char *technique = get_tech_name_and_multiplier(gs_get_color_space(), source_space, &multiplier); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_NO_DIRECT_RENDERING)) { gs_effect_set_vec2(filter->param_add, &filter->offset); gs_effect_set_vec2(filter->param_mul, &mul_val); gs_effect_set_float(filter->param_multiplier, multiplier); - gs_effect_set_next_sampler(filter->param_image, - filter->sampler); + gs_effect_set_next_sampler(filter->param_image, filter->sampler); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_tech_end( - filter->context, filter->effect, cx, cy, technique); + obs_source_process_filter_tech_end(filter->context, filter->effect, cx, cy, technique); gs_blend_state_pop(); } @@ -302,8 +275,7 @@ static uint32_t scroll_filter_width(void *data) struct scroll_filter_data *filter = data; obs_source_t *target = obs_filter_get_target(filter->context); - return filter->limit_cx ? filter->cx - : obs_source_get_base_width(target); + return filter->limit_cx ? filter->cx : obs_source_get_base_width(target); } static uint32_t scroll_filter_height(void *data) @@ -311,8 +283,7 @@ static uint32_t scroll_filter_height(void *data) struct scroll_filter_data *filter = data; obs_source_t *target = obs_filter_get_target(filter->context); - return filter->limit_cy ? filter->cy - : obs_source_get_base_height(target); + return filter->limit_cy ? filter->cy : obs_source_get_base_height(target); } static void scroll_filter_show(void *data) @@ -322,9 +293,8 @@ static void scroll_filter_show(void *data) filter->offset.y = 0.0f; } -static enum gs_color_space -scroll_filter_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space scroll_filter_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { const enum gs_color_space potential_spaces[] = { GS_CS_SRGB, @@ -334,8 +304,7 @@ scroll_filter_get_color_space(void *data, size_t count, struct scroll_filter_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); enum gs_color_space space = source_space; for (size_t i = 0; i < count; ++i) { diff --git a/plugins/obs-filters/sharpness-filter.c b/plugins/obs-filters/sharpness-filter.c index 8d1a933e4..ec127fd82 100644 --- a/plugins/obs-filters/sharpness-filter.c +++ b/plugins/obs-filters/sharpness-filter.c @@ -52,12 +52,9 @@ static void *sharpness_create(obs_data_t *settings, obs_source_t *context) filter->effect = gs_effect_create_from_file(effect_path, NULL); if (filter->effect) { - filter->sharpness_param = gs_effect_get_param_by_name( - filter->effect, "sharpness"); - filter->texture_width = gs_effect_get_param_by_name( - filter->effect, "texture_width"); - filter->texture_height = gs_effect_get_param_by_name( - filter->effect, "texture_height"); + filter->sharpness_param = gs_effect_get_param_by_name(filter->effect, "sharpness"); + filter->texture_width = gs_effect_get_param_by_name(filter->effect, "texture_width"); + filter->texture_height = gs_effect_get_param_by_name(filter->effect, "texture_height"); } obs_leave_graphics(); @@ -86,33 +83,24 @@ static void sharpness_render(void *data, gs_effect_t *effect) }; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(preferred_spaces), preferred_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(preferred_spaces), preferred_spaces); if (source_space == GS_CS_709_EXTENDED) { obs_source_skip_video_filter(filter->context); } else { - const enum gs_color_format format = - gs_get_format_from_space(source_space); - if (obs_source_process_filter_begin_with_color_space( - filter->context, format, source_space, - OBS_ALLOW_DIRECT_RENDERING)) { - filter->texwidth = (float)obs_source_get_width( - obs_filter_get_target(filter->context)); - filter->texheight = (float)obs_source_get_height( - obs_filter_get_target(filter->context)); + const enum gs_color_format format = gs_get_format_from_space(source_space); + if (obs_source_process_filter_begin_with_color_space(filter->context, format, source_space, + OBS_ALLOW_DIRECT_RENDERING)) { + filter->texwidth = (float)obs_source_get_width(obs_filter_get_target(filter->context)); + filter->texheight = (float)obs_source_get_height(obs_filter_get_target(filter->context)); - gs_effect_set_float(filter->sharpness_param, - filter->sharpness); - gs_effect_set_float(filter->texture_width, - filter->texwidth); - gs_effect_set_float(filter->texture_height, - filter->texheight); + gs_effect_set_float(filter->sharpness_param, filter->sharpness); + gs_effect_set_float(filter->texture_width, filter->texwidth); + gs_effect_set_float(filter->texture_height, filter->texheight); gs_blend_state_push(); gs_blend_function(GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); - obs_source_process_filter_end(filter->context, - filter->effect, 0, 0); + obs_source_process_filter_end(filter->context, filter->effect, 0, 0); gs_blend_state_pop(); } @@ -123,11 +111,8 @@ static obs_properties_t *sharpness_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "sdr_only_info", - obs_module_text("SdrOnlyInfo"), OBS_TEXT_INFO); - obs_properties_add_float_slider(props, "sharpness", - obs_module_text("Sharpness"), 0.0, 1.0, - 0.01); + obs_properties_add_text(props, "sdr_only_info", obs_module_text("SdrOnlyInfo"), OBS_TEXT_INFO); + obs_properties_add_float_slider(props, "sharpness", obs_module_text("Sharpness"), 0.0, 1.0, 0.01); UNUSED_PARAMETER(data); return props; @@ -138,9 +123,8 @@ static void sharpness_defaults(obs_data_t *settings) obs_data_set_default_double(settings, "sharpness", 0.08); } -static enum gs_color_space -sharpness_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space sharpness_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); @@ -153,8 +137,7 @@ sharpness_get_color_space(void *data, size_t count, struct sharpness_data *const filter = data; const enum gs_color_space source_space = obs_source_get_color_space( - obs_filter_get_target(filter->context), - OBS_COUNTOF(potential_spaces), potential_spaces); + obs_filter_get_target(filter->context), OBS_COUNTOF(potential_spaces), potential_spaces); return source_space; } diff --git a/plugins/obs-libfdk/obs-libfdk.c b/plugins/obs-libfdk/obs-libfdk.c index 0e0e34fb8..f60921402 100644 --- a/plugins/obs-libfdk/obs-libfdk.c +++ b/plugins/obs-libfdk/obs-libfdk.c @@ -69,10 +69,8 @@ static obs_properties_t *libfdk_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 32, - 1024, 32); - obs_properties_add_bool(props, "afterburner", - obs_module_text("Afterburner")); + obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 32, 1024, 32); + obs_properties_add_bool(props, "afterburner", obs_module_text("Afterburner")); return props; } @@ -146,21 +144,14 @@ static void *libfdk_create(obs_data_t *settings, obs_encoder_t *encoder) CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_AOT, 2)); // MPEG-4 AAC-LC - CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_SAMPLERATE, - enc->sample_rate)); - CHECK_LIBFDK( - aacEncoder_SetParam(enc->fdkhandle, AACENC_CHANNELMODE, mode)); - CHECK_LIBFDK( - aacEncoder_SetParam(enc->fdkhandle, AACENC_CHANNELORDER, 1)); - CHECK_LIBFDK( - aacEncoder_SetParam(enc->fdkhandle, AACENC_BITRATEMODE, 0)); - CHECK_LIBFDK( - aacEncoder_SetParam(enc->fdkhandle, AACENC_BITRATE, bitrate)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_SAMPLERATE, enc->sample_rate)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_CHANNELMODE, mode)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_CHANNELORDER, 1)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_BITRATEMODE, 0)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_BITRATE, bitrate)); - CHECK_LIBFDK( - aacEncoder_SetParam(enc->fdkhandle, AACENC_TRANSMUX, transmux)); - CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_AFTERBURNER, - afterburner)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_TRANSMUX, transmux)); + CHECK_LIBFDK(aacEncoder_SetParam(enc->fdkhandle, AACENC_AFTERBURNER, afterburner)); CHECK_LIBFDK(aacEncEncode(enc->fdkhandle, NULL, NULL, NULL, NULL)); @@ -176,8 +167,7 @@ static void *libfdk_create(obs_data_t *settings, obs_encoder_t *encoder) blog(LOG_INFO, "libfdk_aac encoder created"); - blog(LOG_INFO, "libfdk_aac bitrate: %d, channels: %d", bitrate / 1000, - enc->channels); + blog(LOG_INFO, "libfdk_aac bitrate: %d, channels: %d", bitrate / 1000, enc->channels); return enc; @@ -209,8 +199,7 @@ static void libfdk_destroy(void *data) blog(LOG_INFO, "libfdk_aac encoder destroyed"); } -static bool libfdk_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool libfdk_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { libfdk_encoder_t *enc = data; @@ -248,10 +237,8 @@ static bool libfdk_encode(void *data, struct encoder_frame *frame, out_buf.bufSizes = &out_size; out_buf.bufElSizes = &out_elem_size; - if ((err = aacEncEncode(enc->fdkhandle, &in_buf, &out_buf, &in_args, - &out_args)) != AACENC_OK) { - blog(LOG_ERROR, "Failed to encode frame: %s", - libfdk_get_error(err)); + if ((err = aacEncEncode(enc->fdkhandle, &in_buf, &out_buf, &in_args, &out_args)) != AACENC_OK) { + blog(LOG_ERROR, "Failed to encode frame: %s", libfdk_get_error(err)); return false; } diff --git a/plugins/obs-nvenc/cuda-helpers.c b/plugins/obs-nvenc/cuda-helpers.c index 430a4d5d8..12ddee3dd 100644 --- a/plugins/obs-nvenc/cuda-helpers.c +++ b/plugins/obs-nvenc/cuda-helpers.c @@ -27,8 +27,7 @@ static void *load_cuda_func(const char *func) { void *func_ptr = os_dlsym(cuda_lib, func); if (!func_ptr) { - blog(LOG_ERROR, "[obs-nvenc] Could not load function: %s", - func); + blog(LOG_ERROR, "[obs-nvenc] Could not load function: %s", func); } return func_ptr; } @@ -62,21 +61,15 @@ static const cuda_function cuda_functions[] = { #ifndef _WIN32 {offsetof(CudaFunctions, cuGLGetDevices), "cuGLGetDevices_v2"}, - {offsetof(CudaFunctions, cuGraphicsGLRegisterImage), - "cuGraphicsGLRegisterImage"}, - {offsetof(CudaFunctions, cuGraphicsUnregisterResource), - "cuGraphicsUnregisterResource"}, - {offsetof(CudaFunctions, cuGraphicsMapResources), - "cuGraphicsMapResources"}, - {offsetof(CudaFunctions, cuGraphicsUnmapResources), - "cuGraphicsUnmapResources"}, - {offsetof(CudaFunctions, cuGraphicsSubResourceGetMappedArray), - "cuGraphicsSubResourceGetMappedArray"}, + {offsetof(CudaFunctions, cuGraphicsGLRegisterImage), "cuGraphicsGLRegisterImage"}, + {offsetof(CudaFunctions, cuGraphicsUnregisterResource), "cuGraphicsUnregisterResource"}, + {offsetof(CudaFunctions, cuGraphicsMapResources), "cuGraphicsMapResources"}, + {offsetof(CudaFunctions, cuGraphicsUnmapResources), "cuGraphicsUnmapResources"}, + {offsetof(CudaFunctions, cuGraphicsSubResourceGetMappedArray), "cuGraphicsSubResourceGetMappedArray"}, #endif }; -static const size_t num_cuda_funcs = - sizeof(cuda_functions) / sizeof(cuda_function); +static const size_t num_cuda_funcs = sizeof(cuda_functions) / sizeof(cuda_function); static bool init_cuda_internal(obs_encoder_t *encoder) { @@ -88,8 +81,7 @@ static bool init_cuda_internal(obs_encoder_t *encoder) initialized = true; if (!load_cuda_lib()) { - obs_encoder_set_last_error(encoder, - "Loading CUDA library failed."); + obs_encoder_set_last_error(encoder, "Loading CUDA library failed."); return false; } @@ -100,11 +92,8 @@ static bool init_cuda_internal(obs_encoder_t *encoder) void *fptr = load_cuda_func(func.name); if (!fptr) { - blog(LOG_ERROR, - "[obs-nvenc] Failed to find CUDA function: %s", - func.name); - obs_encoder_set_last_error( - encoder, "Loading CUDA functions failed."); + blog(LOG_ERROR, "[obs-nvenc] Failed to find CUDA function: %s", func.name); + obs_encoder_set_last_error(encoder, "Loading CUDA functions failed."); return false; } @@ -117,15 +106,13 @@ static bool init_cuda_internal(obs_encoder_t *encoder) bool cuda_get_error_desc(CUresult res, const char **name, const char **desc) { - if (cu->cuGetErrorName(res, name) != CUDA_SUCCESS || - cu->cuGetErrorString(res, desc) != CUDA_SUCCESS) + if (cu->cuGetErrorName(res, name) != CUDA_SUCCESS || cu->cuGetErrorString(res, desc) != CUDA_SUCCESS) return false; return true; } -bool cuda_error_check(struct nvenc_data *enc, CUresult res, const char *func, - const char *call) +bool cuda_error_check(struct nvenc_data *enc, CUresult res, const char *func, const char *call) { if (res == CUDA_SUCCESS) return true; @@ -134,12 +121,9 @@ bool cuda_error_check(struct nvenc_data *enc, CUresult res, const char *func, const char *name, *desc; if (cuda_get_error_desc(res, &name, &desc)) { - dstr_printf(&message, - "%s: CUDA call \"%s\" failed with %s (%d): %s", - func, call, name, res, desc); + dstr_printf(&message, "%s: CUDA call \"%s\" failed with %s (%d): %s", func, call, name, res, desc); } else { - dstr_printf(&message, "%s: CUDA call \"%s\" failed with %d", - func, call, res); + dstr_printf(&message, "%s: CUDA call \"%s\" failed with %d", func, call, res); } error("%s", message.array); diff --git a/plugins/obs-nvenc/cuda-helpers.h b/plugins/obs-nvenc/cuda-helpers.h index be76261fe..7d83bad37 100644 --- a/plugins/obs-nvenc/cuda-helpers.h +++ b/plugins/obs-nvenc/cuda-helpers.h @@ -5,8 +5,7 @@ #include /* Missing from FFmpeg headers */ -typedef CUresult CUDAAPI tcuMemHostRegister(void *p, size_t bytesize, - unsigned int Flags); +typedef CUresult CUDAAPI tcuMemHostRegister(void *p, size_t bytesize, unsigned int Flags); typedef CUresult CUDAAPI tcuMemHostUnregister(void *p); #define CUDA_ERROR_INVALID_GRAPHICS_CONTEXT 219 @@ -40,8 +39,7 @@ typedef struct CudaFunctions { tcuGraphicsUnregisterResource *cuGraphicsUnregisterResource; tcuGraphicsMapResources *cuGraphicsMapResources; tcuGraphicsUnmapResources *cuGraphicsUnmapResources; - tcuGraphicsSubResourceGetMappedArray - *cuGraphicsSubResourceGetMappedArray; + tcuGraphicsSubResourceGetMappedArray *cuGraphicsSubResourceGetMappedArray; #endif } CudaFunctions; @@ -51,8 +49,7 @@ bool init_cuda(obs_encoder_t *encoder); bool cuda_get_error_desc(CUresult res, const char **name, const char **desc); struct nvenc_data; -bool cuda_error_check(struct nvenc_data *enc, CUresult res, const char *func, - const char *call); +bool cuda_error_check(struct nvenc_data *enc, CUresult res, const char *func, const char *call); /* CUDA error handling */ #define CU_FAILED(call) \ diff --git a/plugins/obs-nvenc/nvenc-compat.c b/plugins/obs-nvenc/nvenc-compat.c index b4a0d0d69..24ec152a6 100644 --- a/plugins/obs-nvenc/nvenc-compat.c +++ b/plugins/obs-nvenc/nvenc-compat.c @@ -20,35 +20,25 @@ static void migrate_settings(obs_data_t *settings) const char *preset = obs_data_get_string(settings, "preset2"); obs_data_set_string(settings, "preset", preset); - obs_data_set_bool(settings, "adaptive_quantization", - obs_data_get_bool(settings, "psycho_aq")); + obs_data_set_bool(settings, "adaptive_quantization", obs_data_get_bool(settings, "psycho_aq")); - if (obs_data_has_user_value(settings, "gpu") && - num_encoder_devices() > 1) { - obs_data_set_int(settings, "device", - obs_data_get_int(settings, "gpu")); + if (obs_data_has_user_value(settings, "gpu") && num_encoder_devices() > 1) { + obs_data_set_int(settings, "device", obs_data_get_int(settings, "gpu")); } } -static void *nvenc_reroute(enum codec_type codec, obs_data_t *settings, - obs_encoder_t *encoder, bool texture) +static void *nvenc_reroute(enum codec_type codec, obs_data_t *settings, obs_encoder_t *encoder, bool texture) { /* Update settings object to v2 encoder configuration */ migrate_settings(settings); switch (codec) { case CODEC_H264: - return obs_encoder_create_rerouted( - encoder, - texture ? "obs_nvenc_h264_tex" : "obs_nvenc_h264_soft"); + return obs_encoder_create_rerouted(encoder, texture ? "obs_nvenc_h264_tex" : "obs_nvenc_h264_soft"); case CODEC_HEVC: - return obs_encoder_create_rerouted( - encoder, - texture ? "obs_nvenc_hevc_tex" : "obs_nvenc_hevc_soft"); + return obs_encoder_create_rerouted(encoder, texture ? "obs_nvenc_hevc_tex" : "obs_nvenc_hevc_soft"); case CODEC_AV1: - return obs_encoder_create_rerouted( - encoder, - texture ? "obs_nvenc_av1_tex" : "obs_nvenc_av1_soft"); + return obs_encoder_create_rerouted(encoder, texture ? "obs_nvenc_av1_tex" : "obs_nvenc_av1_soft"); } return NULL; @@ -93,15 +83,13 @@ static void *av1_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) return nvenc_reroute(CODEC_AV1, settings, encoder, true); } -static void *h264_nvenc_soft_create(obs_data_t *settings, - obs_encoder_t *encoder) +static void *h264_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder) { return nvenc_reroute(CODEC_H264, settings, encoder, false); } #ifdef ENABLE_HEVC -static void *hevc_nvenc_soft_create(obs_data_t *settings, - obs_encoder_t *encoder) +static void *hevc_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder) { return nvenc_reroute(CODEC_HEVC, settings, encoder, false); } @@ -123,8 +111,7 @@ static void nvenc_defaults_base(enum codec_type codec, obs_data_t *settings) obs_data_set_default_string(settings, "preset2", "p5"); obs_data_set_default_string(settings, "multipass", "qres"); obs_data_set_default_string(settings, "tune", "hq"); - obs_data_set_default_string(settings, "profile", - codec != CODEC_H264 ? "main" : "high"); + obs_data_set_default_string(settings, "profile", codec != CODEC_H264 ? "main" : "high"); obs_data_set_default_bool(settings, "psycho_aq", true); obs_data_set_default_int(settings, "gpu", 0); obs_data_set_default_int(settings, "bf", 2); @@ -148,8 +135,7 @@ static void av1_nvenc_defaults(obs_data_t *settings) nvenc_defaults_base(CODEC_AV1, settings); } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *rc = obs_data_get_string(settings, "rate_control"); bool cqp = astrcmpi(rc, "CQP") == 0; @@ -175,40 +161,29 @@ static obs_properties_t *nvenc_properties_internal(enum codec_type codec) obs_properties_t *props = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, "CBR", "CBR"); obs_property_list_add_string(p, "CQP", "CQP"); obs_property_list_add_string(p, "VBR", "VBR"); - obs_property_list_add_string(p, obs_module_text("Lossless"), - "lossless"); + obs_property_list_add_string(p, obs_module_text("Lossless"), "lossless"); obs_property_set_modified_callback(p, rate_control_modified); - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 50, 300000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); - p = obs_properties_add_int(props, "max_bitrate", - obs_module_text("MaxBitrate"), 50, 300000, - 50); + p = obs_properties_add_int(props, "max_bitrate", obs_module_text("MaxBitrate"), 50, 300000, 50); obs_property_int_set_suffix(p, " Kbps"); - obs_properties_add_int(props, "cqp", obs_module_text("CQLevel"), 1, - codec == CODEC_AV1 ? 63 : 51, 1); + obs_properties_add_int(props, "cqp", obs_module_text("CQLevel"), 1, codec == CODEC_AV1 ? 63 : 51, 1); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 10, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1); obs_property_int_set_suffix(p, " s"); - p = obs_properties_add_list(props, "preset2", obs_module_text("Preset"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "preset2", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_preset(val) \ - obs_property_list_add_string(p, obs_module_text("Preset." val), val) +#define add_preset(val) obs_property_list_add_string(p, obs_module_text("Preset." val), val) add_preset("p1"); add_preset("p2"); @@ -219,32 +194,25 @@ static obs_properties_t *nvenc_properties_internal(enum codec_type codec) add_preset("p7"); #undef add_preset - p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_tune(val) \ - obs_property_list_add_string(p, obs_module_text("Tuning." val), val) +#define add_tune(val) obs_property_list_add_string(p, obs_module_text("Tuning." val), val) add_tune("hq"); add_tune("ll"); add_tune("ull"); #undef add_tune - p = obs_properties_add_list(props, "multipass", - obs_module_text("Multipass"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "multipass", obs_module_text("Multipass"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_multipass(val) \ - obs_property_list_add_string(p, obs_module_text("Multipass." val), val) +#define add_multipass(val) obs_property_list_add_string(p, obs_module_text("Multipass." val), val) add_multipass("disabled"); add_multipass("qres"); add_multipass("fullres"); #undef add_multipass - p = obs_properties_add_list(props, "profile", - obs_module_text("Profile"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); #define add_profile(val) obs_property_list_add_string(p, val, val) @@ -260,22 +228,17 @@ static obs_properties_t *nvenc_properties_internal(enum codec_type codec) } #undef add_profile - p = obs_properties_add_bool(props, "lookahead", - obs_module_text("LookAhead")); - obs_property_set_long_description(p, - obs_module_text("LookAhead.ToolTip")); + p = obs_properties_add_bool(props, "lookahead", obs_module_text("LookAhead")); + obs_property_set_long_description(p, obs_module_text("LookAhead.ToolTip")); p = obs_properties_add_bool(props, "repeat_headers", "repeat_headers"); obs_property_set_visible(p, false); - p = obs_properties_add_bool(props, "psycho_aq", - obs_module_text("PsychoVisualTuning")); - obs_property_set_long_description( - p, obs_module_text("PsychoVisualTuning.ToolTip")); + p = obs_properties_add_bool(props, "psycho_aq", obs_module_text("PsychoVisualTuning")); + obs_property_set_long_description(p, obs_module_text("PsychoVisualTuning.ToolTip")); obs_properties_add_int(props, "gpu", obs_module_text("GPU"), 0, 8, 1); - obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, - 1); + obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, 4, 1); return props; } @@ -308,8 +271,7 @@ static void fake_nvenc_destroy(void *p) UNUSED_PARAMETER(p); } -static bool fake_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool fake_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(frame); @@ -319,10 +281,8 @@ static bool fake_encode(void *data, struct encoder_frame *frame, return true; } -static bool fake_encode_tex2(void *data, struct encoder_texture *texture, - int64_t pts, uint64_t lock_key, uint64_t *next_key, - struct encoder_packet *packet, - bool *received_packet) +static bool fake_encode_tex2(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key, + uint64_t *next_key, struct encoder_packet *packet, bool *received_packet) { UNUSED_PARAMETER(data); UNUSED_PARAMETER(texture); @@ -339,8 +299,8 @@ struct obs_encoder_info compat_h264_nvenc_info = { .id = "jim_nvenc", .codec = "h264", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | + OBS_ENCODER_CAP_DEPRECATED, .get_name = h264_nvenc_get_name, .create = h264_nvenc_create, .destroy = fake_nvenc_destroy, @@ -354,8 +314,8 @@ struct obs_encoder_info compat_hevc_nvenc_info = { .id = "jim_hevc_nvenc", .codec = "hevc", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | + OBS_ENCODER_CAP_DEPRECATED, .get_name = hevc_nvenc_get_name, .create = hevc_nvenc_create, .destroy = fake_nvenc_destroy, @@ -369,8 +329,8 @@ struct obs_encoder_info compat_av1_nvenc_info = { .id = "jim_av1_nvenc", .codec = "av1", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | + OBS_ENCODER_CAP_DEPRECATED, .get_name = av1_nvenc_get_name, .create = av1_nvenc_create, .destroy = fake_nvenc_destroy, @@ -383,8 +343,7 @@ struct obs_encoder_info compat_h264_nvenc_soft_info = { .id = "obs_nvenc_h264_cuda", .codec = "h264", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | - OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED, .get_name = h264_nvenc_get_name, .create = h264_nvenc_soft_create, .destroy = fake_nvenc_destroy, @@ -398,8 +357,7 @@ struct obs_encoder_info compat_hevc_nvenc_soft_info = { .id = "obs_nvenc_hevc_cuda", .codec = "hevc", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | - OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED, .get_name = hevc_nvenc_get_name, .create = hevc_nvenc_soft_create, .destroy = fake_nvenc_destroy, @@ -413,8 +371,7 @@ struct obs_encoder_info compat_av1_nvenc_soft_info = { .id = "obs_nvenc_av1_cuda", .codec = "av1", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | - OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_DEPRECATED, .get_name = av1_nvenc_get_name, .create = av1_nvenc_soft_create, .destroy = fake_nvenc_destroy, diff --git a/plugins/obs-nvenc/nvenc-cuda.c b/plugins/obs-nvenc/nvenc-cuda.c index 5cdbca45e..c292da575 100644 --- a/plugins/obs-nvenc/nvenc-cuda.c +++ b/plugins/obs-nvenc/nvenc-cuda.c @@ -8,8 +8,7 @@ /* ------------------------------------------------------------------------- */ /* CUDA Context management */ -bool cuda_ctx_init(struct nvenc_data *enc, obs_data_t *settings, - const bool texture) +bool cuda_ctx_init(struct nvenc_data *enc, obs_data_t *settings, const bool texture) { #ifdef _WIN32 if (texture) @@ -45,8 +44,7 @@ bool cuda_ctx_init(struct nvenc_data *enc, obs_data_t *settings, CUdevice devices[2]; obs_enter_graphics(); - CUresult res = cu->cuGLGetDevices(&ctx_count, devices, 2, - CU_GL_DEVICE_LIST_ALL); + CUresult res = cu->cuGLGetDevices(&ctx_count, devices, 2, CU_GL_DEVICE_LIST_ALL); obs_leave_graphics(); if (res != CUDA_SUCCESS || !ctx_count) { @@ -99,8 +97,7 @@ void cuda_ctx_free(struct nvenc_data *enc) /* ------------------------------------------------------------------------- */ /* CUDA Surface management */ -static bool cuda_surface_init(struct nvenc_data *enc, - struct nv_cuda_surface *nvsurf) +static bool cuda_surface_init(struct nvenc_data *enc, struct nv_cuda_surface *nvsurf) { const bool p010 = obs_p010_tex_active(); CUDA_ARRAY3D_DESCRIPTOR desc; @@ -111,8 +108,7 @@ static bool cuda_surface_init(struct nvenc_data *enc, desc.NumChannels = 1; if (!enc->non_texture) { - desc.Format = p010 ? CU_AD_FORMAT_UNSIGNED_INT16 - : CU_AD_FORMAT_UNSIGNED_INT8; + desc.Format = p010 ? CU_AD_FORMAT_UNSIGNED_INT16 : CU_AD_FORMAT_UNSIGNED_INT8; desc.Height = enc->cy + enc->cy / 2; } else { switch (enc->surface_format) { @@ -146,8 +142,7 @@ static bool cuda_surface_init(struct nvenc_data *enc, res.height = enc->cy; res.pitch = (uint32_t)(desc.Width * desc.NumChannels); if (!enc->non_texture) { - res.bufferFormat = p010 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT - : NV_ENC_BUFFER_FORMAT_NV12; + res.bufferFormat = p010 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT : NV_ENC_BUFFER_FORMAT_NV12; } else { res.bufferFormat = enc->surface_format; } @@ -190,13 +185,11 @@ bool cuda_init_surfaces(struct nvenc_data *enc) return true; } -static void cuda_surface_free(struct nvenc_data *enc, - struct nv_cuda_surface *nvsurf) +static void cuda_surface_free(struct nvenc_data *enc, struct nv_cuda_surface *nvsurf) { if (nvsurf->res) { if (nvsurf->mapped_res) { - nv.nvEncUnmapInputResource(enc->session, - nvsurf->mapped_res); + nv.nvEncUnmapInputResource(enc->session, nvsurf->mapped_res); } nv.nvEncUnregisterResource(enc->session, nvsurf->res); cu->cuArrayDestroy(nvsurf->tex); @@ -218,9 +211,7 @@ void cuda_free_surfaces(struct nvenc_data *enc) /* ------------------------------------------------------------------------- */ /* Actual encoding stuff */ -static inline bool copy_frame(struct nvenc_data *enc, - struct encoder_frame *frame, - struct nv_cuda_surface *surf) +static inline bool copy_frame(struct nvenc_data *enc, struct encoder_frame *frame, struct nv_cuda_surface *surf) { bool success = true; size_t height = enc->cy; @@ -239,10 +230,8 @@ static inline bool copy_frame(struct nvenc_data *enc, /* Page-locks the host memory so that it can be DMAd directly * rather than CUDA doing an internal copy to page-locked * memory before actually DMA-ing to the GPU. */ - CU_CHECK(cu->cuMemHostRegister(frame->data[0], - frame->linesize[0] * height, 0)) - CU_CHECK(cu->cuMemHostRegister( - frame->data[1], frame->linesize[1] * height / 2, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[0], frame->linesize[0] * height, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[1], frame->linesize[1] * height / 2, 0)) m.srcPitch = frame->linesize[0]; m.srcHost = frame->data[0]; @@ -254,10 +243,8 @@ static inline bool copy_frame(struct nvenc_data *enc, m.Height /= 2; CU_FAILED(cu->cuMemcpy2D(&m)) } else if (enc->surface_format == NV_ENC_BUFFER_FORMAT_YUV420_10BIT) { - CU_CHECK(cu->cuMemHostRegister(frame->data[0], - frame->linesize[0] * height, 0)) - CU_CHECK(cu->cuMemHostRegister( - frame->data[1], frame->linesize[1] * height / 2, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[0], frame->linesize[0] * height, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[1], frame->linesize[1] * height / 2, 0)) // P010 lines are double the size (16 bit per pixel) m.WidthInBytes *= 2; @@ -272,12 +259,9 @@ static inline bool copy_frame(struct nvenc_data *enc, m.Height /= 2; CU_FAILED(cu->cuMemcpy2D(&m)) } else { // I444 - CU_CHECK(cu->cuMemHostRegister(frame->data[0], - frame->linesize[0] * height, 0)) - CU_CHECK(cu->cuMemHostRegister(frame->data[1], - frame->linesize[1] * height, 0)) - CU_CHECK(cu->cuMemHostRegister(frame->data[2], - frame->linesize[2] * height, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[0], frame->linesize[0] * height, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[1], frame->linesize[1] * height, 0)) + CU_CHECK(cu->cuMemHostRegister(frame->data[2], frame->linesize[2] * height, 0)) m.srcPitch = frame->linesize[0]; m.srcHost = frame->data[0]; @@ -307,8 +291,7 @@ unmap: return success; } -bool cuda_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +bool cuda_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct nvenc_data *enc = data; struct nv_cuda_surface *surf; @@ -340,6 +323,5 @@ bool cuda_encode(void *data, struct encoder_frame *frame, /* ------------------------------------ */ /* do actual encode call */ - return nvenc_encode_base(enc, bs, surf->mapped_res, frame->pts, packet, - received_packet); + return nvenc_encode_base(enc, bs, surf->mapped_res, frame->pts, packet, received_packet); } diff --git a/plugins/obs-nvenc/nvenc-d3d11.c b/plugins/obs-nvenc/nvenc-d3d11.c index 3ebe23014..4b01a10ae 100644 --- a/plugins/obs-nvenc/nvenc-d3d11.c +++ b/plugins/obs-nvenc/nvenc-d3d11.c @@ -38,10 +38,8 @@ bool d3d11_init(struct nvenc_data *enc, obs_data_t *settings) return false; } - create_dxgi = (CREATEDXGIFACTORY1PROC)GetProcAddress( - dxgi, "CreateDXGIFactory1"); - create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress( - d3d11, "D3D11CreateDevice"); + create_dxgi = (CREATEDXGIFACTORY1PROC)GetProcAddress(dxgi, "CreateDXGIFactory1"); + create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(d3d11, "D3D11CreateDevice"); if (!create_dxgi || !create_device) { error("Failed to load D3D11/DXGI procedures"); @@ -61,8 +59,8 @@ bool d3d11_init(struct nvenc_data *enc, obs_data_t *settings) return false; } - hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, NULL, 0, - D3D11_SDK_VERSION, &device, NULL, &context); + hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, NULL, 0, D3D11_SDK_VERSION, &device, NULL, + &context); adapter->lpVtbl->Release(adapter); if (FAILED(hr)) { error_hr("D3D11CreateDevice failed"); @@ -121,8 +119,7 @@ static bool d3d11_texture_init(struct nvenc_data *enc, struct nv_texture *nvtex) res.resourceToRegister = tex; res.width = enc->cx; res.height = enc->cy; - res.bufferFormat = p010 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT - : NV_ENC_BUFFER_FORMAT_NV12; + res.bufferFormat = p010 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT : NV_ENC_BUFFER_FORMAT_NV12; if (NV_FAILED(nv.nvEncRegisterResource(enc->session, &res))) { tex->lpVtbl->Release(tex); @@ -156,8 +153,7 @@ static void d3d11_texture_free(struct nvenc_data *enc, struct nv_texture *nvtex) if (nvtex->res) { if (nvtex->mapped_res) { - nv.nvEncUnmapInputResource(enc->session, - nvtex->mapped_res); + nv.nvEncUnmapInputResource(enc->session, nvtex->mapped_res); } nv.nvEncUnregisterResource(enc->session, nvtex->res); nvtex->tex->lpVtbl->Release(nvtex->tex); @@ -174,9 +170,7 @@ void d3d11_free_textures(struct nvenc_data *enc) /* ------------------------------------------------------------------------- */ /* Actual encoding stuff */ -static ID3D11Texture2D *get_tex_from_handle(struct nvenc_data *enc, - uint32_t handle, - IDXGIKeyedMutex **km_out) +static ID3D11Texture2D *get_tex_from_handle(struct nvenc_data *enc, uint32_t handle, IDXGIKeyedMutex **km_out) { ID3D11Device *device = enc->device; IDXGIKeyedMutex *km; @@ -191,25 +185,20 @@ static ID3D11Texture2D *get_tex_from_handle(struct nvenc_data *enc, } } - hr = device->lpVtbl->OpenSharedResource(device, - (HANDLE)(uintptr_t)handle, - &IID_ID3D11Texture2D, - &input_tex); + hr = device->lpVtbl->OpenSharedResource(device, (HANDLE)(uintptr_t)handle, &IID_ID3D11Texture2D, &input_tex); if (FAILED(hr)) { error_hr("OpenSharedResource failed"); return NULL; } - hr = input_tex->lpVtbl->QueryInterface(input_tex, &IID_IDXGIKeyedMutex, - &km); + hr = input_tex->lpVtbl->QueryInterface(input_tex, &IID_IDXGIKeyedMutex, &km); if (FAILED(hr)) { error_hr("QueryInterface(IDXGIKeyedMutex) failed"); input_tex->lpVtbl->Release(input_tex); return NULL; } - input_tex->lpVtbl->SetEvictionPriority(input_tex, - DXGI_RESOURCE_PRIORITY_MAXIMUM); + input_tex->lpVtbl->SetEvictionPriority(input_tex, DXGI_RESOURCE_PRIORITY_MAXIMUM); *km_out = km; @@ -218,8 +207,7 @@ static ID3D11Texture2D *get_tex_from_handle(struct nvenc_data *enc, return input_tex; } -bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, - uint64_t lock_key, uint64_t *next_key, +bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key, uint64_t *next_key, struct encoder_packet *packet, bool *received_packet) { struct nvenc_data *enc = data; @@ -254,8 +242,7 @@ bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, km->lpVtbl->AcquireSync(km, lock_key, INFINITE); - context->lpVtbl->CopyResource(context, (ID3D11Resource *)output_tex, - (ID3D11Resource *)input_tex); + context->lpVtbl->CopyResource(context, (ID3D11Resource *)output_tex, (ID3D11Resource *)input_tex); km->lpVtbl->ReleaseSync(km, *next_key); @@ -273,6 +260,5 @@ bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, /* ------------------------------------ */ /* do actual encode call */ - return nvenc_encode_base(enc, bs, nvtex->mapped_res, pts, packet, - received_packet); + return nvenc_encode_base(enc, bs, nvtex->mapped_res, pts, packet, received_packet); } diff --git a/plugins/obs-nvenc/nvenc-helpers.c b/plugins/obs-nvenc/nvenc-helpers.c index 024fc7fe9..f99067962 100644 --- a/plugins/obs-nvenc/nvenc-helpers.c +++ b/plugins/obs-nvenc/nvenc-helpers.c @@ -43,8 +43,7 @@ bool nv_fail2(obs_encoder_t *encoder, void *session, const char *format, ...) return true; } -bool nv_failed2(obs_encoder_t *encoder, void *session, NVENCSTATUS err, - const char *func, const char *call) +bool nv_failed2(obs_encoder_t *encoder, void *session, NVENCSTATUS err, const char *func, const char *call) { struct dstr error_message = {0}; const char *nvenc_error = NULL; @@ -65,30 +64,25 @@ bool nv_failed2(obs_encoder_t *encoder, void *session, NVENCSTATUS err, switch (err) { case NV_ENC_ERR_OUT_OF_MEMORY: case NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY: - obs_encoder_set_last_error(encoder, - obs_module_text("TooManySessions")); + obs_encoder_set_last_error(encoder, obs_module_text("TooManySessions")); break; case NV_ENC_ERR_NO_ENCODE_DEVICE: case NV_ENC_ERR_UNSUPPORTED_DEVICE: - obs_encoder_set_last_error( - encoder, obs_module_text("UnsupportedDevice")); + obs_encoder_set_last_error(encoder, obs_module_text("UnsupportedDevice")); break; case NV_ENC_ERR_INVALID_VERSION: - obs_encoder_set_last_error(encoder, - obs_module_text("OutdatedDriver")); + obs_encoder_set_last_error(encoder, obs_module_text("OutdatedDriver")); break; default: if (nvenc_error && *nvenc_error) { - dstr_printf(&error_message, "NVENC Error: %s (%s)", - nvenc_error, nv_error_name(err)); + dstr_printf(&error_message, "NVENC Error: %s (%s)", nvenc_error, nv_error_name(err)); } else { - dstr_printf(&error_message, - "NVENC Error: %s: %s failed: %d (%s)", func, - call, (int)err, nv_error_name(err)); + dstr_printf(&error_message, "NVENC Error: %s: %s failed: %d (%s)", func, call, (int)err, + nv_error_name(err)); } obs_encoder_set_last_error(encoder, error_message.array); dstr_free(&error_message); @@ -96,11 +90,9 @@ bool nv_failed2(obs_encoder_t *encoder, void *session, NVENCSTATUS err, } if (nvenc_error && *nvenc_error) { - error("%s: %s failed: %d (%s): %s", func, call, (int)err, - nv_error_name(err), nvenc_error); + error("%s: %s failed: %d (%s): %s", func, call, (int)err, nv_error_name(err), nvenc_error); } else { - error("%s: %s failed: %d (%s)", func, call, (int)err, - nv_error_name(err)); + error("%s: %s failed: %d (%s)", func, call, (int)err, nv_error_name(err)); } return true; } @@ -141,8 +133,7 @@ static uint32_t get_nvenc_ver(void) if (failed) return 0; - nv_max_ver = (NV_MAX_VER_FUNC)load_nv_func( - "NvEncodeAPIGetMaxSupportedVersion"); + nv_max_ver = (NV_MAX_VER_FUNC)load_nv_func("NvEncodeAPIGetMaxSupportedVersion"); if (!nv_max_ver) { failed = true; return 0; @@ -205,28 +196,23 @@ static inline bool init_nvenc_internal(obs_encoder_t *encoder) uint32_t ver = get_nvenc_ver(); if (ver == 0) { - obs_encoder_set_last_error( - encoder, - "Missing NvEncodeAPIGetMaxSupportedVersion, check " - "your video card drivers are up to date."); + obs_encoder_set_last_error(encoder, "Missing NvEncodeAPIGetMaxSupportedVersion, check " + "your video card drivers are up to date."); return false; } if (ver < NVCODEC_CONFIGURED_VERSION) { - obs_encoder_set_last_error(encoder, - obs_module_text("OutdatedDriver")); + obs_encoder_set_last_error(encoder, obs_module_text("OutdatedDriver")); error("Current driver version does not support this NVENC " "version, please upgrade your driver"); return false; } - nv_create_instance = (NV_CREATE_INSTANCE_FUNC)load_nv_func( - "NvEncodeAPICreateInstance"); + nv_create_instance = (NV_CREATE_INSTANCE_FUNC)load_nv_func("NvEncodeAPICreateInstance"); if (!nv_create_instance) { - obs_encoder_set_last_error( - encoder, "Missing NvEncodeAPICreateInstance, check " - "your video card drivers are up to date."); + obs_encoder_set_last_error(encoder, "Missing NvEncodeAPICreateInstance, check " + "your video card drivers are up to date."); return false; } @@ -272,13 +258,11 @@ bool has_broken_split_encoding(void) return driver_version_major < 555; } -static void read_codec_caps(config_t *config, enum codec_type codec, - const char *section) +static void read_codec_caps(config_t *config, enum codec_type codec, const char *section) { struct encoder_caps *caps = &encoder_capabilities[codec]; - codec_supported[codec] = - config_get_bool(config, section, "codec_supported"); + codec_supported[codec] = config_get_bool(config, section, "codec_supported"); if (!codec_supported[codec]) return; @@ -287,10 +271,8 @@ static void read_codec_caps(config_t *config, enum codec_type codec, caps->engines = (int)config_get_int(config, section, "engines"); caps->max_width = (int)config_get_int(config, section, "max_width"); caps->max_height = (int)config_get_int(config, section, "max_height"); - caps->temporal_filter = - (int)config_get_int(config, section, "temporal_filter"); - caps->lookahead_level = - (int)config_get_int(config, section, "lookahead_level"); + caps->temporal_filter = (int)config_get_int(config, section, "temporal_filter"); + caps->lookahead_level = (int)config_get_int(config, section, "lookahead_level"); caps->dyn_bitrate = config_get_bool(config, section, "dynamic_bitrate"); caps->lookahead = config_get_bool(config, section, "lookahead"); @@ -323,8 +305,7 @@ static bool nvenc_check(void) for (;;) { char data[2048]; - size_t len = - os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); + size_t len = os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); if (!len) break; @@ -334,9 +315,8 @@ static bool nvenc_check(void) os_process_pipe_destroy(pp); if (dstr_is_empty(&caps_str)) { - blog(LOG_WARNING, - "[NVENC] Seems the NVENC test subprocess crashed. " - "Better there than here I guess. "); + blog(LOG_WARNING, "[NVENC] Seems the NVENC test subprocess crashed. " + "Better there than here I guess. "); goto fail; } @@ -347,10 +327,8 @@ static bool nvenc_check(void) success = config_get_bool(config, "general", "nvenc_supported"); if (!success) { - const char *error = - config_get_string(config, "general", "reason"); - blog(LOG_WARNING, "[NVENC] Test process failed: %s", - error ? error : "unknown"); + const char *error = config_get_string(config, "general", "reason"); + blog(LOG_WARNING, "[NVENC] Test process failed: %s", error ? error : "unknown"); goto fail; } @@ -359,20 +337,16 @@ static bool nvenc_check(void) read_codec_caps(config, CODEC_HEVC, "hevc"); read_codec_caps(config, CODEC_AV1, "av1"); - const char *nvenc_ver = - config_get_string(config, "general", "nvenc_ver"); + const char *nvenc_ver = config_get_string(config, "general", "nvenc_ver"); const char *cuda_ver = config_get_string(config, "general", "cuda_ver"); - const char *driver_ver = - config_get_string(config, "general", "driver_ver"); + const char *driver_ver = config_get_string(config, "general", "driver_ver"); /* Parse out major/minor for some brokenness checks */ - sscanf(driver_ver, "%d.%d", &driver_version_major, - &driver_version_minor); + sscanf(driver_ver, "%d.%d", &driver_version_major, &driver_version_minor); blog(LOG_INFO, "[obs-nvenc] NVENC version: %d.%d (compiled) / %s (driver), " "CUDA driver version: %s, AV1 supported: %s", - NVCODEC_CONFIGURED_VERSION >> 4, NVCODEC_CONFIGURED_VERSION & 0xf, - nvenc_ver, cuda_ver, + NVCODEC_CONFIGURED_VERSION >> 4, NVCODEC_CONFIGURED_VERSION & 0xf, nvenc_ver, cuda_ver, codec_supported[CODEC_AV1] ? "true" : "false"); fail: diff --git a/plugins/obs-nvenc/nvenc-helpers.h b/plugins/obs-nvenc/nvenc-helpers.h index ab3cd3bca..c3c027507 100644 --- a/plugins/obs-nvenc/nvenc-helpers.h +++ b/plugins/obs-nvenc/nvenc-helpers.h @@ -8,8 +8,7 @@ #include #include -#define NVCODEC_CONFIGURED_VERSION \ - ((NVENCAPI_MAJOR_VERSION << 4) | NVENCAPI_MINOR_VERSION) +#define NVCODEC_CONFIGURED_VERSION ((NVENCAPI_MAJOR_VERSION << 4) | NVENCAPI_MINOR_VERSION) #if NVENCAPI_MAJOR_VERSION > 12 || NVENCAPI_MINOR_VERSION >= 1 #define NVENC_12_1_OR_LATER @@ -61,8 +60,7 @@ struct encoder_caps { bool four_four_four; }; -typedef NVENCSTATUS(NVENCAPI *NV_CREATE_INSTANCE_FUNC)( - NV_ENCODE_API_FUNCTION_LIST *); +typedef NVENCSTATUS(NVENCAPI *NV_CREATE_INSTANCE_FUNC)(NV_ENCODE_API_FUNCTION_LIST *); extern NV_ENCODE_API_FUNCTION_LIST nv; extern NV_CREATE_INSTANCE_FUNC nv_create_instance; @@ -71,8 +69,7 @@ const char *nv_error_name(NVENCSTATUS err); bool init_nvenc(obs_encoder_t *encoder); bool nv_fail2(obs_encoder_t *encoder, void *session, const char *format, ...); -bool nv_failed2(obs_encoder_t *encoder, void *session, NVENCSTATUS err, - const char *func, const char *call); +bool nv_failed2(obs_encoder_t *encoder, void *session, NVENCSTATUS err, const char *func, const char *call); struct encoder_caps *get_encoder_caps(enum codec_type codec); int num_encoder_devices(void); @@ -82,8 +79,6 @@ bool has_broken_split_encoding(void); void register_encoders(void); void register_compat_encoders(void); -#define nv_fail(encoder, format, ...) \ - nv_fail2(encoder, enc->session, format, ##__VA_ARGS__) +#define nv_fail(encoder, format, ...) nv_fail2(encoder, enc->session, format, ##__VA_ARGS__) -#define nv_failed(encoder, err, func, call) \ - nv_failed2(encoder, enc->session, err, func, call) +#define nv_failed(encoder, err, func, call) nv_failed2(encoder, enc->session, err, func, call) diff --git a/plugins/obs-nvenc/nvenc-internal.h b/plugins/obs-nvenc/nvenc-internal.h index efaaef9d1..6ca33461c 100644 --- a/plugins/obs-nvenc/nvenc-internal.h +++ b/plugins/obs-nvenc/nvenc-internal.h @@ -15,9 +15,8 @@ #include #endif -#define do_log(level, format, ...) \ - blog(level, "[obs-nvenc: '%s'] " format, \ - obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[obs-nvenc: '%s'] " format, obs_encoder_get_name(enc->encoder), ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -155,9 +154,8 @@ struct nv_texture { /* ------------------------------------------------------------------------- */ /* Shared functions */ -bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, - void *pic, int64_t pts, struct encoder_packet *packet, - bool *received_packet); +bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, void *pic, int64_t pts, + struct encoder_packet *packet, bool *received_packet); /* ------------------------------------------------------------------------- */ /* Backend-specific functions */ @@ -170,8 +168,7 @@ void d3d11_free(struct nvenc_data *enc); bool d3d11_init_textures(struct nvenc_data *enc); void d3d11_free_textures(struct nvenc_data *enc); -bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, - uint64_t lock_key, uint64_t *next_key, +bool d3d11_encode(void *data, struct encoder_texture *texture, int64_t pts, uint64_t lock_key, uint64_t *next_key, struct encoder_packet *packet, bool *received_packet); #endif @@ -182,14 +179,12 @@ void cuda_ctx_free(struct nvenc_data *enc); bool cuda_init_surfaces(struct nvenc_data *enc); void cuda_free_surfaces(struct nvenc_data *enc); -bool cuda_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet); +bool cuda_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet); #ifndef _WIN32 /** CUDA OpenGL **/ void cuda_opengl_free(struct nvenc_data *enc); -bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, - uint64_t lock_key, uint64_t *next_key, +bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, uint64_t lock_key, uint64_t *next_key, struct encoder_packet *packet, bool *received_packet); #endif diff --git a/plugins/obs-nvenc/nvenc-opengl.c b/plugins/obs-nvenc/nvenc-opengl.c index c8b10d3f3..808845f49 100644 --- a/plugins/obs-nvenc/nvenc-opengl.c +++ b/plugins/obs-nvenc/nvenc-opengl.c @@ -23,10 +23,8 @@ void cuda_opengl_free(struct nvenc_data *enc) /* ------------------------------------------------------------------------- */ /* Actual encoding stuff */ -static inline bool get_res_for_tex_ids(struct nvenc_data *enc, GLuint tex_id_y, - GLuint tex_id_uv, - CUgraphicsResource *tex_y, - CUgraphicsResource *tex_uv) +static inline bool get_res_for_tex_ids(struct nvenc_data *enc, GLuint tex_id_y, GLuint tex_id_uv, + CUgraphicsResource *tex_y, CUgraphicsResource *tex_uv) { bool success = true; @@ -40,12 +38,8 @@ static inline bool get_res_for_tex_ids(struct nvenc_data *enc, GLuint tex_id_y, return success; } - CU_CHECK(cu->cuGraphicsGLRegisterImage( - tex_y, tex_id_y, GL_TEXTURE_2D, - CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY)) - CU_CHECK(cu->cuGraphicsGLRegisterImage( - tex_uv, tex_id_uv, GL_TEXTURE_2D, - CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY)) + CU_CHECK(cu->cuGraphicsGLRegisterImage(tex_y, tex_id_y, GL_TEXTURE_2D, CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY)) + CU_CHECK(cu->cuGraphicsGLRegisterImage(tex_uv, tex_id_uv, GL_TEXTURE_2D, CU_GRAPHICS_REGISTER_FLAGS_READ_ONLY)) struct handle_tex ht = {tex_id_y, *tex_y, *tex_uv}; da_push_back(enc->input_textures, &ht); @@ -59,15 +53,13 @@ unmap: return success; } -static inline bool copy_tex_data(struct nvenc_data *enc, const bool p010, - GLuint tex[2], struct nv_cuda_surface *surf) +static inline bool copy_tex_data(struct nvenc_data *enc, const bool p010, GLuint tex[2], struct nv_cuda_surface *surf) { bool success = true; CUgraphicsResource mapped_tex[2] = {0}; CUarray mapped_cuda; - if (!get_res_for_tex_ids(enc, tex[0], tex[1], &mapped_tex[0], - &mapped_tex[1])) + if (!get_res_for_tex_ids(enc, tex[0], tex[1], &mapped_tex[0], &mapped_tex[1])) return false; CU_CHECK(cu->cuGraphicsMapResources(2, mapped_tex, 0)) @@ -80,14 +72,12 @@ static inline bool copy_tex_data(struct nvenc_data *enc, const bool p010, m.Height = enc->cy; // Map and copy Y texture - CU_CHECK(cu->cuGraphicsSubResourceGetMappedArray(&mapped_cuda, - mapped_tex[0], 0, 0)); + CU_CHECK(cu->cuGraphicsSubResourceGetMappedArray(&mapped_cuda, mapped_tex[0], 0, 0)); m.srcArray = mapped_cuda; CU_CHECK(cu->cuMemcpy2D(&m)) // Map and copy UV texture - CU_CHECK(cu->cuGraphicsSubResourceGetMappedArray(&mapped_cuda, - mapped_tex[1], 0, 0)) + CU_CHECK(cu->cuGraphicsSubResourceGetMappedArray(&mapped_cuda, mapped_tex[1], 0, 0)) m.srcArray = mapped_cuda; m.dstY += enc->cy; m.Height = enc->cy / 2; @@ -100,8 +90,7 @@ unmap: return success; } -bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, - uint64_t lock_key, uint64_t *next_key, +bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, uint64_t lock_key, uint64_t *next_key, struct encoder_packet *packet, bool *received_packet) { struct nvenc_data *enc = data; @@ -142,8 +131,7 @@ bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, NV_ENC_MAP_INPUT_RESOURCE map = {NV_ENC_MAP_INPUT_RESOURCE_VER}; map.registeredResource = surf->res; - map.mappedBufferFmt = p010 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT - : NV_ENC_BUFFER_FORMAT_NV12; + map.mappedBufferFmt = p010 ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT : NV_ENC_BUFFER_FORMAT_NV12; if (NV_FAILED(nv.nvEncMapInputResource(enc->session, &map))) return false; @@ -153,6 +141,5 @@ bool cuda_opengl_encode(void *data, struct encoder_texture *tex, int64_t pts, /* ------------------------------------ */ /* do actual encode call */ - return nvenc_encode_base(enc, bs, surf->mapped_res, pts, packet, - received_packet); + return nvenc_encode_base(enc, bs, surf->mapped_res, pts, packet, received_packet); } diff --git a/plugins/obs-nvenc/nvenc-opts-parser.c b/plugins/obs-nvenc/nvenc-opts-parser.c index 397f3dc63..001015332 100644 --- a/plugins/obs-nvenc/nvenc-opts-parser.c +++ b/plugins/obs-nvenc/nvenc-opts-parser.c @@ -7,25 +7,22 @@ * use offsetof() or similar with those we resort to macros here to avoid too * much boilerplate. */ -#define APPLY_BIT_OPT(opt_name, bits) \ - if (strcmp(opt->name, #opt_name) == 0) { \ - uint32_t old_val = nv_conf->opt_name; \ - nv_conf->opt_name = strtol(opt->value, NULL, 10); \ - blog(LOG_DEBUG, \ - "[obs-nvenc] Changing parameter: \"%s\": %u -> %u (%d bit(s))", \ - #opt_name, old_val, nv_conf->opt_name, bits); \ - return true; \ +#define APPLY_BIT_OPT(opt_name, bits) \ + if (strcmp(opt->name, #opt_name) == 0) { \ + uint32_t old_val = nv_conf->opt_name; \ + nv_conf->opt_name = strtol(opt->value, NULL, 10); \ + blog(LOG_DEBUG, "[obs-nvenc] Changing parameter: \"%s\": %u -> %u (%d bit(s))", #opt_name, old_val, \ + nv_conf->opt_name, bits); \ + return true; \ } -#define APPLY_INT_OPT(opt_name, type, format) \ - if (strcmp(opt->name, #opt_name) == 0) { \ - type old_val = nv_conf->opt_name; \ - nv_conf->opt_name = (type)strtol(opt->value, NULL, 10); \ - blog(LOG_DEBUG, \ - "[obs-nvenc] Changing parameter: \"%s\": %" format \ - " -> %" format " (%s)", \ - #opt_name, old_val, nv_conf->opt_name, #type); \ - return true; \ +#define APPLY_INT_OPT(opt_name, type, format) \ + if (strcmp(opt->name, #opt_name) == 0) { \ + type old_val = nv_conf->opt_name; \ + nv_conf->opt_name = (type)strtol(opt->value, NULL, 10); \ + blog(LOG_DEBUG, "[obs-nvenc] Changing parameter: \"%s\": %" format " -> %" format " (%s)", #opt_name, \ + old_val, nv_conf->opt_name, #type); \ + return true; \ } static void parse_qp_opt(const char *name, const char *val, NV_ENC_QP *qp_opt) @@ -38,9 +35,7 @@ static void parse_qp_opt(const char *name, const char *val, NV_ENC_QP *qp_opt) p = b = i = atoi(val); } - blog(LOG_DEBUG, - "[obs-nvenc] Applying custom %s = %d / %d / %d (P / B / I)", name, - p, b, i); + blog(LOG_DEBUG, "[obs-nvenc] Applying custom %s = %d / %d / %d (P / B / I)", name, p, b, i); /* Values should be treated as int32_t but are passed in as uint32_t * for legacy reasons, see comment in nvEncodeAPI.h */ @@ -55,8 +50,7 @@ static void parse_qp_opt(const char *name, const char *val, NV_ENC_QP *qp_opt) return true; \ } -static bool apply_rc_opt(const struct obs_option *opt, - NV_ENC_RC_PARAMS *nv_conf) +static bool apply_rc_opt(const struct obs_option *opt, NV_ENC_RC_PARAMS *nv_conf) { APPLY_QP_OPT(constQP) APPLY_QP_OPT(minQP) @@ -122,8 +116,7 @@ static void parse_level_opt(const char *val, uint32_t *level, bool hevc) if (hevc) int_val *= 3; - blog(LOG_DEBUG, "[obs-nvenc] Applying custom level = %s (%u)", val, - int_val); + blog(LOG_DEBUG, "[obs-nvenc] Applying custom level = %s (%u)", val, int_val); *level = int_val; } @@ -175,8 +168,7 @@ static bool apply_av1_opt(struct obs_option *opt, NV_ENC_CONFIG_AV1 *nv_conf) return false; } -static bool apply_codec_opt(enum codec_type codec, struct obs_option *opt, - NV_ENC_CODEC_CONFIG *enc_config) +static bool apply_codec_opt(enum codec_type codec, struct obs_option *opt, NV_ENC_CODEC_CONFIG *enc_config) { if (codec == CODEC_H264) return apply_h264_opt(opt, &enc_config->h264Config); @@ -194,16 +186,14 @@ void apply_user_args(struct nvenc_data *enc) struct obs_option *opt = &enc->props.opts.options[idx]; /* Special options handled elsewhere */ - if (strcmp(opt->name, "lookaheadDepth") == 0 || - strcmp(opt->name, "keyint") == 0) + if (strcmp(opt->name, "lookaheadDepth") == 0 || strcmp(opt->name, "keyint") == 0) continue; if (apply_rc_opt(opt, &enc->config.rcParams)) continue; if (apply_conf_opt(opt, &enc->config)) continue; - if (apply_codec_opt(enc->codec, opt, - &enc->config.encodeCodecConfig)) + if (apply_codec_opt(enc->codec, opt, &enc->config.encodeCodecConfig)) continue; warn("Unknown custom option: \"%s\"", opt->name); diff --git a/plugins/obs-nvenc/nvenc-properties.c b/plugins/obs-nvenc/nvenc-properties.c index 486b80a2b..5e18c10b9 100644 --- a/plugins/obs-nvenc/nvenc-properties.c +++ b/plugins/obs-nvenc/nvenc-properties.c @@ -18,11 +18,9 @@ void nvenc_properties_read(struct nvenc_properties *props, obs_data_t *settings) props->tune = obs_data_get_string(settings, "tune"); props->multipass = obs_data_get_string(settings, "multipass"); - props->adaptive_quantization = - obs_data_get_bool(settings, "adaptive_quantization"); + props->adaptive_quantization = obs_data_get_bool(settings, "adaptive_quantization"); props->lookahead = obs_data_get_bool(settings, "lookahead"); - props->disable_scenecut = - obs_data_get_bool(settings, "disable_scenecut"); + props->disable_scenecut = obs_data_get_bool(settings, "disable_scenecut"); props->repeat_headers = obs_data_get_bool(settings, "repeat_headers"); props->force_cuda_tex = obs_data_get_bool(settings, "force_cuda_tex"); @@ -52,8 +50,7 @@ static void nvenc_defaults_base(enum codec_type codec, obs_data_t *settings) obs_data_set_default_string(settings, "preset", "p5"); obs_data_set_default_string(settings, "multipass", "qres"); obs_data_set_default_string(settings, "tune", "hq"); - obs_data_set_default_string(settings, "profile", - codec != CODEC_H264 ? "main" : "high"); + obs_data_set_default_string(settings, "profile", codec != CODEC_H264 ? "main" : "high"); obs_data_set_default_bool(settings, "adaptive_quantization", true); obs_data_set_default_bool(settings, "lookahead", caps->lookahead); @@ -81,8 +78,7 @@ void av1_nvenc_defaults(obs_data_t *settings) nvenc_defaults_base(CODEC_AV1, settings); } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *rc = obs_data_get_string(settings, "rate_control"); bool cqp = strcmp(rc, "CQP") == 0; @@ -115,49 +111,37 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) struct encoder_caps *caps = get_encoder_caps(codec); - p = obs_properties_add_list(props, "rate_control", - obs_module_text("RateControl"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "rate_control", obs_module_text("RateControl"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("CBR"), "CBR"); obs_property_list_add_string(p, obs_module_text("CQP"), "CQP"); obs_property_list_add_string(p, obs_module_text("VBR"), "VBR"); obs_property_list_add_string(p, obs_module_text("CQVBR"), "CQVBR"); if (caps->lossless) { - obs_property_list_add_string(p, obs_module_text("Lossless"), - "lossless"); + obs_property_list_add_string(p, obs_module_text("Lossless"), "lossless"); } obs_property_set_modified_callback(p, rate_control_modified); - p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), - 50, UINT32_MAX / 1000, 50); + p = obs_properties_add_int(props, "bitrate", obs_module_text("Bitrate"), 50, UINT32_MAX / 1000, 50); obs_property_int_set_suffix(p, " Kbps"); - obs_properties_add_int(props, "target_quality", - obs_module_text("TargetQuality"), 1, 51, 1); + obs_properties_add_int(props, "target_quality", obs_module_text("TargetQuality"), 1, 51, 1); - p = obs_properties_add_int(props, "max_bitrate", - obs_module_text("MaxBitrate"), 0, - UINT32_MAX / 1000, 50); + p = obs_properties_add_int(props, "max_bitrate", obs_module_text("MaxBitrate"), 0, UINT32_MAX / 1000, 50); obs_property_int_set_suffix(p, " Kbps"); /* AV1 uses 0-255 instead of 0-51 for QP, and most implementations just * multiply the value by 4 to keep the range smaller. */ - obs_properties_add_int(props, "cqp", obs_module_text("CQP"), 1, - codec == CODEC_AV1 ? 63 : 51, 1); + obs_properties_add_int(props, "cqp", obs_module_text("CQP"), 1, codec == CODEC_AV1 ? 63 : 51, 1); - p = obs_properties_add_int(props, "keyint_sec", - obs_module_text("KeyframeIntervalSec"), 0, - 10, 1); + p = obs_properties_add_int(props, "keyint_sec", obs_module_text("KeyframeIntervalSec"), 0, 10, 1); obs_property_int_set_suffix(p, " s"); - p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "preset", obs_module_text("Preset"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_preset(val) \ - obs_property_list_add_string(p, obs_module_text("Preset." val), val) +#define add_preset(val) obs_property_list_add_string(p, obs_module_text("Preset." val), val) add_preset("p1"); add_preset("p2"); @@ -168,12 +152,10 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) add_preset("p7"); #undef add_preset - p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "tune", obs_module_text("Tuning"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_tune(val) \ - obs_property_list_add_string(p, obs_module_text("Tuning." val), val) +#define add_tune(val) obs_property_list_add_string(p, obs_module_text("Tuning." val), val) #ifdef NVENC_12_2_OR_LATER /* The UHQ tune is only supported on Turing or later. * It uses the temporal filtering feature, so we can use its @@ -186,21 +168,16 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) add_tune("ull"); #undef add_tune - p = obs_properties_add_list(props, "multipass", - obs_module_text("Multipass"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "multipass", obs_module_text("Multipass"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); -#define add_multipass(val) \ - obs_property_list_add_string(p, obs_module_text("Multipass." val), val) +#define add_multipass(val) obs_property_list_add_string(p, obs_module_text("Multipass." val), val) add_multipass("disabled"); add_multipass("qres"); add_multipass("fullres"); #undef add_multipass - p = obs_properties_add_list(props, "profile", - obs_module_text("Profile"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "profile", obs_module_text("Profile"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); #define add_profile(val) obs_property_list_add_string(p, val, val) @@ -217,47 +194,36 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) } #undef add_profile - p = obs_properties_add_bool(props, "lookahead", - obs_module_text("LookAhead")); - obs_property_set_long_description(p, - obs_module_text("LookAhead.ToolTip")); + p = obs_properties_add_bool(props, "lookahead", obs_module_text("LookAhead")); + obs_property_set_long_description(p, obs_module_text("LookAhead.ToolTip")); - p = obs_properties_add_bool(props, "adaptive_quantization", - obs_module_text("AdaptiveQuantization")); - obs_property_set_long_description( - p, obs_module_text("AdaptiveQuantization.ToolTip")); + p = obs_properties_add_bool(props, "adaptive_quantization", obs_module_text("AdaptiveQuantization")); + obs_property_set_long_description(p, obs_module_text("AdaptiveQuantization.ToolTip")); if (num_encoder_devices() > 1) { - obs_properties_add_int(props, "device", obs_module_text("GPU"), - -1, num_encoder_devices(), 1); + obs_properties_add_int(props, "device", obs_module_text("GPU"), -1, num_encoder_devices(), 1); } if (caps->bframes > 0) { - obs_properties_add_int(props, "bf", obs_module_text("BFrames"), - 0, caps->bframes, 1); + obs_properties_add_int(props, "bf", obs_module_text("BFrames"), 0, caps->bframes, 1); } /* H.264 supports this, but seems to cause issues with some decoders, * so restrict it to the custom options field for now. */ if (caps->bref_modes && codec != CODEC_H264) { - p = obs_properties_add_list(props, "bframe_ref_mode", - obs_module_text("BFrameRefMode"), - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(props, "bframe_ref_mode", obs_module_text("BFrameRefMode"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int( - p, obs_module_text("BframeRefMode.Disabled"), - NV_ENC_BFRAME_REF_MODE_DISABLED); + obs_property_list_add_int(p, obs_module_text("BframeRefMode.Disabled"), + NV_ENC_BFRAME_REF_MODE_DISABLED); if (caps->bref_modes & 1) { - obs_property_list_add_int( - p, obs_module_text("BframeRefMode.Each"), - NV_ENC_BFRAME_REF_MODE_EACH); + obs_property_list_add_int(p, obs_module_text("BframeRefMode.Each"), + NV_ENC_BFRAME_REF_MODE_EACH); } if (caps->bref_modes & 2) { - obs_property_list_add_int( - p, obs_module_text("BframeRefMode.Middle"), - NV_ENC_BFRAME_REF_MODE_MIDDLE); + obs_property_list_add_int(p, obs_module_text("BframeRefMode.Middle"), + NV_ENC_BFRAME_REF_MODE_MIDDLE); } } @@ -265,33 +231,22 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) /* Some older GPUs such as the 1080 Ti have 2 NVENC chips, but do not * support split encoding. Therefore, we check for AV1 support here to * make sure this option is only presented on 40-series and later. */ - if (is_codec_supported(CODEC_AV1) && caps->engines > 1 && - !has_broken_split_encoding() && + if (is_codec_supported(CODEC_AV1) && caps->engines > 1 && !has_broken_split_encoding() && (codec == CODEC_HEVC || codec == CODEC_AV1)) { - p = obs_properties_add_list(props, "split_encode", - obs_module_text("SplitEncode"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, "split_encode", obs_module_text("SplitEncode"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(p, - obs_module_text("SplitEncode.Auto"), - NV_ENC_SPLIT_AUTO_MODE); - obs_property_list_add_int( - p, obs_module_text("SplitEncode.Disabled"), - NV_ENC_SPLIT_DISABLE_MODE); - obs_property_list_add_int( - p, obs_module_text("SplitEncode.Enabled"), - NV_ENC_SPLIT_TWO_FORCED_MODE); + obs_property_list_add_int(p, obs_module_text("SplitEncode.Auto"), NV_ENC_SPLIT_AUTO_MODE); + obs_property_list_add_int(p, obs_module_text("SplitEncode.Disabled"), NV_ENC_SPLIT_DISABLE_MODE); + obs_property_list_add_int(p, obs_module_text("SplitEncode.Enabled"), NV_ENC_SPLIT_TWO_FORCED_MODE); if (caps->engines > 2) { - obs_property_list_add_int( - p, obs_module_text("SplitEncode.ThreeWay"), - NV_ENC_SPLIT_THREE_FORCED_MODE); + obs_property_list_add_int(p, obs_module_text("SplitEncode.ThreeWay"), + NV_ENC_SPLIT_THREE_FORCED_MODE); } } #endif - p = obs_properties_add_text(props, "opts", obs_module_text("Opts"), - OBS_TEXT_DEFAULT); + p = obs_properties_add_text(props, "opts", obs_module_text("Opts"), OBS_TEXT_DEFAULT); obs_property_set_long_description(p, obs_module_text("Opts.TT")); /* Invisible properties */ @@ -299,8 +254,7 @@ obs_properties_t *nvenc_properties_internal(enum codec_type codec) obs_property_set_visible(p, false); p = obs_properties_add_bool(props, "force_cuda_tex", "force_cuda_tex"); obs_property_set_visible(p, false); - p = obs_properties_add_bool(props, "disable_scenecut", - "disable_scenecut"); + p = obs_properties_add_bool(props, "disable_scenecut", "disable_scenecut"); obs_property_set_visible(p, false); return props; diff --git a/plugins/obs-nvenc/nvenc.c b/plugins/obs-nvenc/nvenc.c index bf6d16472..43ec356f8 100644 --- a/plugins/obs-nvenc/nvenc.c +++ b/plugins/obs-nvenc/nvenc.c @@ -17,8 +17,7 @@ static bool nv_bitstream_init(struct nvenc_data *enc, struct nv_bitstream *bs) { - NV_ENC_CREATE_BITSTREAM_BUFFER buf = { - NV_ENC_CREATE_BITSTREAM_BUFFER_VER}; + NV_ENC_CREATE_BITSTREAM_BUFFER buf = {NV_ENC_CREATE_BITSTREAM_BUFFER_VER}; if (NV_FAILED(nv.nvEncCreateBitstreamBuffer(enc->session, &buf))) { return false; @@ -96,16 +95,12 @@ static bool nvenc_update(void *data, obs_data_t *settings) /* Only support reconfiguration of CBR bitrate */ if (enc->can_change_bitrate) { enc->props.bitrate = obs_data_get_int(settings, "bitrate"); - enc->props.max_bitrate = - obs_data_get_int(settings, "max_bitrate"); + enc->props.max_bitrate = obs_data_get_int(settings, "max_bitrate"); - bool vbr = (enc->config.rcParams.rateControlMode == - NV_ENC_PARAMS_RC_VBR); - enc->config.rcParams.averageBitRate = - (uint32_t)enc->props.bitrate * 1000; - enc->config.rcParams.maxBitRate = - vbr ? (uint32_t)enc->props.max_bitrate * 1000 - : (uint32_t)enc->props.bitrate * 1000; + bool vbr = (enc->config.rcParams.rateControlMode == NV_ENC_PARAMS_RC_VBR); + enc->config.rcParams.averageBitRate = (uint32_t)enc->props.bitrate * 1000; + enc->config.rcParams.maxBitRate = vbr ? (uint32_t)enc->props.max_bitrate * 1000 + : (uint32_t)enc->props.bitrate * 1000; NV_ENC_RECONFIGURE_PARAMS params = {0}; params.version = NV_ENC_RECONFIGURE_PARAMS_VER; @@ -113,8 +108,7 @@ static bool nvenc_update(void *data, obs_data_t *settings) params.resetEncoder = 1; params.forceIDR = 1; - if (NV_FAILED(nv.nvEncReconfigureEncoder(enc->session, - ¶ms))) { + if (NV_FAILED(nv.nvEncReconfigureEncoder(enc->session, ¶ms))) { return false; } } @@ -124,8 +118,7 @@ static bool nvenc_update(void *data, obs_data_t *settings) static bool init_session(struct nvenc_data *enc) { - NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = { - NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER}; + NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS params = {NV_ENC_OPEN_ENCODE_SESSION_EX_PARAMS_VER}; params.apiVersion = NVENCAPI_VERSION; #ifdef _WIN32 if (enc->non_texture) { @@ -146,10 +139,8 @@ static bool init_session(struct nvenc_data *enc) return true; } -static void initialize_params(struct nvenc_data *enc, const GUID *nv_preset, - NV_ENC_TUNING_INFO nv_tuning, uint32_t width, - uint32_t height, uint32_t fps_num, - uint32_t fps_den) +static void initialize_params(struct nvenc_data *enc, const GUID *nv_preset, NV_ENC_TUNING_INFO nv_tuning, + uint32_t width, uint32_t height, uint32_t fps_num, uint32_t fps_den) { NV_ENC_INITIALIZE_PARAMS *params = &enc->params; memset(params, 0, sizeof(*params)); @@ -167,8 +158,7 @@ static void initialize_params(struct nvenc_data *enc, const GUID *nv_preset, params->encodeConfig = &enc->config; params->tuningInfo = nv_tuning; #ifdef NVENC_12_1_OR_LATER - params->splitEncodeMode = - (NV_ENC_SPLIT_ENCODE_MODE)enc->props.split_encode; + params->splitEncodeMode = (NV_ENC_SPLIT_ENCODE_MODE)enc->props.split_encode; #endif } @@ -219,8 +209,7 @@ static inline NV_ENC_MULTI_PASS get_nv_multipass(const char *multipass) static bool is_10_bit(const struct nvenc_data *enc) { - return enc->non_texture ? enc->in_format == VIDEO_FORMAT_P010 - : obs_p010_tex_active(); + return enc->non_texture ? enc->in_format == VIDEO_FORMAT_P010 : obs_p010_tex_active(); } static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) @@ -266,11 +255,8 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) preset_config.version = NV_ENC_PRESET_CONFIG_VER; preset_config.presetCfg.version = NV_ENC_CONFIG_VER; - err = nv.nvEncGetEncodePresetConfigEx(enc->session, enc->codec_guid, - nv_preset, nv_tuning, - &preset_config); - if (nv_failed(enc->encoder, err, __FUNCTION__, - "nvEncGetEncodePresetConfig")) { + err = nv.nvEncGetEncodePresetConfigEx(enc->session, enc->codec_guid, nv_preset, nv_tuning, &preset_config); + if (nv_failed(enc->encoder, err, __FUNCTION__, "nvEncGetEncodePresetConfig")) { return false; } @@ -286,8 +272,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) NV_ENC_CONFIG *config = &enc->config; - initialize_params(enc, &nv_preset, nv_tuning, voi->width, voi->height, - voi->fps_num, voi->fps_den); + initialize_params(enc, &nv_preset, nv_tuning, voi->width, voi->height, voi->fps_num, voi->fps_den); config->gopLength = gop_size; config->frameIntervalP = gop_size == 1 ? 0 : (int32_t)enc->props.bf + 1; @@ -299,9 +284,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) (enc->props.lookahead || use_profile_lookahead); if (lookahead) { - rc_lookahead = use_profile_lookahead - ? config->rcParams.lookaheadDepth - : 8; + rc_lookahead = use_profile_lookahead ? config->rcParams.lookaheadDepth : 8; /* Due to the additional calculations required to handle lookahead, * get the user override here (if any). */ @@ -310,9 +293,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) int buf_count = max(4, config->frameIntervalP * 2 * 2); if (lookahead) { - buf_count = - max(buf_count, config->frameIntervalP + rc_lookahead + - EXTRA_BUFFERS); + buf_count = max(buf_count, config->frameIntervalP + rc_lookahead + EXTRA_BUFFERS); } buf_count = min(64, buf_count); @@ -325,8 +306,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) const int lkd_bound = output_delay - config->frameIntervalP - 4; if (lkd_bound >= 0) { config->rcParams.enableLookahead = 1; - config->rcParams.lookaheadDepth = - min(rc_lookahead, lkd_bound); + config->rcParams.lookaheadDepth = min(rc_lookahead, lkd_bound); config->rcParams.disableIadapt = 0; config->rcParams.disableBadapt = 0; } else { @@ -341,15 +321,13 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) if (enc->props.adaptive_quantization) { config->rcParams.enableAQ = 1; config->rcParams.aqStrength = 8; - config->rcParams.enableTemporalAQ = - nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ); + config->rcParams.enableTemporalAQ = nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_TEMPORAL_AQ); } /* -------------------------- */ /* rate control */ - enc->can_change_bitrate = - nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE); + enc->can_change_bitrate = nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_DYN_BITRATE_CHANGE); config->rcParams.rateControlMode = NV_ENC_PARAMS_RC_VBR; config->rcParams.averageBitRate = bitrate * 1000; @@ -357,8 +335,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) config->rcParams.vbvBufferSize = bitrate * 1000; if (cqp || lossless) { - int cqp_val = enc->codec == CODEC_AV1 ? (int)enc->props.cqp * 4 - : (int)enc->props.cqp; + int cqp_val = enc->codec == CODEC_AV1 ? (int)enc->props.cqp * 4 : (int)enc->props.cqp; config->rcParams.rateControlMode = NV_ENC_PARAMS_RC_CONSTQP; config->rcParams.constQP.qpInterP = cqp_val; @@ -372,8 +349,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) } else if (!vbr) { /* CBR by default */ config->rcParams.rateControlMode = NV_ENC_PARAMS_RC_CBR; } else if (cqvbr) { - config->rcParams.targetQuality = - (uint8_t)enc->props.target_quality; + config->rcParams.targetQuality = (uint8_t)enc->props.target_quality; config->rcParams.averageBitRate = 0; config->rcParams.vbvBufferSize = 0; } @@ -396,8 +372,7 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) if (cqp) dstr_catf(&log, "\tcqp: %ld\n", enc->props.cqp); if (cqvbr) { - dstr_catf(&log, "\tcq: %ld\n", - enc->props.target_quality); + dstr_catf(&log, "\tcq: %ld\n", enc->props.target_quality); } dstr_catf(&log, "\tkeyint: %d\n", gop_size); @@ -409,14 +384,11 @@ static bool init_encoder_base(struct nvenc_data *enc, obs_data_t *settings) dstr_catf(&log, "\theight: %d\n", enc->cy); dstr_catf(&log, "\tb-frames: %ld\n", enc->props.bf); dstr_catf(&log, "\tb-ref-mode: %ld\n", enc->props.bframe_ref_mode); - dstr_catf(&log, "\tlookahead: %s (%d frames)\n", - lookahead ? "true" : "false", rc_lookahead); - dstr_catf(&log, "\taq: %s\n", - enc->props.adaptive_quantization ? "true" : "false"); + dstr_catf(&log, "\tlookahead: %s (%d frames)\n", lookahead ? "true" : "false", rc_lookahead); + dstr_catf(&log, "\taq: %s\n", enc->props.adaptive_quantization ? "true" : "false"); if (enc->props.split_encode) { - dstr_catf(&log, "\tsplit encode: %ld\n", - enc->props.split_encode); + dstr_catf(&log, "\tsplit encode: %ld\n", enc->props.split_encode); } if (enc->props.opts.count) dstr_catf(&log, "\tuser opts: %s\n", enc->props.opts_str); @@ -437,8 +409,7 @@ static bool init_encoder_h264(struct nvenc_data *enc, obs_data_t *settings) NV_ENC_CONFIG *config = &enc->config; NV_ENC_CONFIG_H264 *h264_config = &config->encodeCodecConfig.h264Config; - NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui_params = - &h264_config->h264VUIParameters; + NV_ENC_CONFIG_H264_VUI_PARAMETERS *vui_params = &h264_config->h264VUIParameters; video_t *video = obs_encoder_video(enc->encoder); const struct video_output_info *voi = video_output_get_info(video); @@ -454,8 +425,7 @@ static bool init_encoder_h264(struct nvenc_data *enc, obs_data_t *settings) h264_config->sliceMode = 3; h264_config->sliceModeData = 1; - h264_config->useBFramesAsRef = - (NV_ENC_BFRAME_REF_MODE)enc->props.bframe_ref_mode; + h264_config->useBFramesAsRef = (NV_ENC_BFRAME_REF_MODE)enc->props.bframe_ref_mode; /* Enable CBR padding */ if (config->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR) @@ -525,8 +495,7 @@ static bool init_encoder_hevc(struct nvenc_data *enc, obs_data_t *settings) NV_ENC_CONFIG *config = &enc->config; NV_ENC_CONFIG_HEVC *hevc_config = &config->encodeCodecConfig.hevcConfig; - NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui_params = - &hevc_config->hevcVUIParameters; + NV_ENC_CONFIG_HEVC_VUI_PARAMETERS *vui_params = &hevc_config->hevcVUIParameters; video_t *video = obs_encoder_video(enc->encoder); const struct video_output_info *voi = video_output_get_info(video); @@ -542,8 +511,7 @@ static bool init_encoder_hevc(struct nvenc_data *enc, obs_data_t *settings) hevc_config->sliceMode = 3; hevc_config->sliceModeData = 1; - hevc_config->useBFramesAsRef = - (NV_ENC_BFRAME_REF_MODE)enc->props.bframe_ref_mode; + hevc_config->useBFramesAsRef = (NV_ENC_BFRAME_REF_MODE)enc->props.bframe_ref_mode; /* Enable CBR padding */ if (config->rcParams.rateControlMode == NV_ENC_PARAMS_RC_CBR) @@ -615,10 +583,8 @@ static bool init_encoder_hevc(struct nvenc_data *enc, obs_data_t *settings) #ifndef NVENC_12_2_OR_LATER hevc_config->pixelBitDepthMinus8 = is_10_bit(enc) ? 2 : 0; #else - hevc_config->inputBitDepth = is_10_bit(enc) ? NV_ENC_BIT_DEPTH_10 - : NV_ENC_BIT_DEPTH_8; - hevc_config->outputBitDepth = profile_is_10bpc ? NV_ENC_BIT_DEPTH_10 - : NV_ENC_BIT_DEPTH_8; + hevc_config->inputBitDepth = is_10_bit(enc) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8; + hevc_config->outputBitDepth = profile_is_10bpc ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8; #endif apply_user_args(enc); @@ -644,8 +610,7 @@ static bool init_encoder_av1(struct nvenc_data *enc, obs_data_t *settings) av1_config->idrPeriod = config->gopLength; - av1_config->useBFramesAsRef = - (NV_ENC_BFRAME_REF_MODE)enc->props.bframe_ref_mode; + av1_config->useBFramesAsRef = (NV_ENC_BFRAME_REF_MODE)enc->props.bframe_ref_mode; av1_config->colorRange = (voi->range == VIDEO_RANGE_FULL); @@ -699,8 +664,7 @@ static bool init_encoder_av1(struct nvenc_data *enc, obs_data_t *settings) av1_config->pixelBitDepthMinus8 = is_10_bit(enc) ? 2 : 0; av1_config->inputPixelBitDepthMinus8 = av1_config->pixelBitDepthMinus8; #else - av1_config->inputBitDepth = is_10_bit(enc) ? NV_ENC_BIT_DEPTH_10 - : NV_ENC_BIT_DEPTH_8; + av1_config->inputBitDepth = is_10_bit(enc) ? NV_ENC_BIT_DEPTH_10 : NV_ENC_BIT_DEPTH_8; av1_config->outputBitDepth = av1_config->inputBitDepth; #endif av1_config->numFwdRefs = 1; @@ -749,21 +713,17 @@ static enum video_format get_preferred_format(enum video_format format) static void nvenc_destroy(void *data); -static bool init_encoder(struct nvenc_data *enc, enum codec_type codec, - obs_data_t *settings, obs_encoder_t *encoder) +static bool init_encoder(struct nvenc_data *enc, enum codec_type codec, obs_data_t *settings, obs_encoder_t *encoder) { UNUSED_PARAMETER(codec); UNUSED_PARAMETER(encoder); - const bool support_10bit = - nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE); - const bool support_444 = - nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE); + const bool support_10bit = nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_10BIT_ENCODE); + const bool support_444 = nv_get_cap(enc, NV_ENC_CAPS_SUPPORT_YUV444_ENCODE); video_t *video = obs_encoder_video(enc->encoder); const struct video_output_info *voi = video_output_get_info(video); - enum video_format pref_format = - obs_encoder_get_preferred_video_format(enc->encoder); + enum video_format pref_format = obs_encoder_get_preferred_video_format(enc->encoder); if (pref_format == VIDEO_FORMAT_NONE) pref_format = voi->format; @@ -806,8 +766,7 @@ static bool init_encoder(struct nvenc_data *enc, enum codec_type codec, return false; } -static void *nvenc_create_internal(enum codec_type codec, obs_data_t *settings, - obs_encoder_t *encoder, bool texture) +static void *nvenc_create_internal(enum codec_type codec, obs_data_t *settings, obs_encoder_t *encoder, bool texture) { struct nvenc_data *enc = bzalloc(sizeof(*enc)); enc->encoder = encoder; @@ -875,8 +834,7 @@ fail: return NULL; } -static void *nvenc_create_base(enum codec_type codec, obs_data_t *settings, - obs_encoder_t *encoder, bool texture) +static void *nvenc_create_base(enum codec_type codec, obs_data_t *settings, obs_encoder_t *encoder, bool texture) { /* This encoder requires shared textures, this cannot be used on a * gpu other than the one OBS is currently running on. @@ -896,9 +854,8 @@ static void *nvenc_create_base(enum codec_type codec, obs_data_t *settings, #endif if (gpu_set && gpu != -1 && texture && !force_tex) { - blog(LOG_INFO, - "[obs-nvenc] different GPU selected by user, falling back " - "to non-texture encoder"); + blog(LOG_INFO, "[obs-nvenc] different GPU selected by user, falling back " + "to non-texture encoder"); goto reroute; } @@ -906,22 +863,19 @@ static void *nvenc_create_base(enum codec_type codec, obs_data_t *settings, if (obs_encoder_gpu_scaling_enabled(encoder)) { blog(LOG_INFO, "[obs-nvenc] GPU scaling enabled"); } else if (texture) { - blog(LOG_INFO, - "[obs-nvenc] CPU scaling enabled, falling back to" - " non-texture encoder"); + blog(LOG_INFO, "[obs-nvenc] CPU scaling enabled, falling back to" + " non-texture encoder"); goto reroute; } } if (texture && !obs_p010_tex_active() && !obs_nv12_tex_active()) { - blog(LOG_INFO, - "[obs-nvenc] nv12/p010 not active, falling back to " - "non-texture encoder"); + blog(LOG_INFO, "[obs-nvenc] nv12/p010 not active, falling back to " + "non-texture encoder"); goto reroute; } - struct nvenc_data *enc = - nvenc_create_internal(codec, settings, encoder, texture); + struct nvenc_data *enc = nvenc_create_internal(codec, settings, encoder, texture); if (enc) { return enc; @@ -929,21 +883,17 @@ static void *nvenc_create_base(enum codec_type codec, obs_data_t *settings, reroute: if (!texture) { - blog(LOG_ERROR, - "Already in non_texture encoder, can't fall back further!"); + blog(LOG_ERROR, "Already in non_texture encoder, can't fall back further!"); return NULL; } switch (codec) { case CODEC_H264: - return obs_encoder_create_rerouted(encoder, - "obs_nvenc_h264_soft"); + return obs_encoder_create_rerouted(encoder, "obs_nvenc_h264_soft"); case CODEC_HEVC: - return obs_encoder_create_rerouted(encoder, - "obs_nvenc_hevc_soft"); + return obs_encoder_create_rerouted(encoder, "obs_nvenc_hevc_soft"); case CODEC_AV1: - return obs_encoder_create_rerouted(encoder, - "obs_nvenc_av1_soft"); + return obs_encoder_create_rerouted(encoder, "obs_nvenc_av1_soft"); } return NULL; @@ -966,15 +916,13 @@ static void *av1_nvenc_create(obs_data_t *settings, obs_encoder_t *encoder) return nvenc_create_base(CODEC_AV1, settings, encoder, true); } -static void *h264_nvenc_soft_create(obs_data_t *settings, - obs_encoder_t *encoder) +static void *h264_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder) { return nvenc_create_base(CODEC_H264, settings, encoder, false); } #ifdef ENABLE_HEVC -static void *hevc_nvenc_soft_create(obs_data_t *settings, - obs_encoder_t *encoder) +static void *hevc_nvenc_soft_create(obs_data_t *settings, obs_encoder_t *encoder) { return nvenc_create_base(CODEC_HEVC, settings, encoder, false); } @@ -1050,12 +998,8 @@ static bool get_encoded_packet(struct nvenc_data *enc, bool finalize) size_t cur_bs_idx = enc->cur_bitstream; struct nv_bitstream *bs = &enc->bitstreams.array[cur_bs_idx]; #ifdef _WIN32 - struct nv_texture *nvtex = - enc->non_texture ? NULL - : &enc->textures.array[cur_bs_idx]; - struct nv_cuda_surface *surf = - enc->non_texture ? &enc->surfaces.array[cur_bs_idx] - : NULL; + struct nv_texture *nvtex = enc->non_texture ? NULL : &enc->textures.array[cur_bs_idx]; + struct nv_cuda_surface *surf = enc->non_texture ? &enc->surfaces.array[cur_bs_idx] : NULL; #else struct nv_cuda_surface *surf = &enc->surfaces.array[cur_bs_idx]; #endif @@ -1086,8 +1030,7 @@ static bool get_encoded_packet(struct nvenc_data *enc, bool finalize) enc->first_packet = false; } - da_copy_array(enc->packet_data, lock.bitstreamBufferPtr, - lock.bitstreamSizeInBytes); + da_copy_array(enc->packet_data, lock.bitstreamBufferPtr, lock.bitstreamSizeInBytes); enc->packet_pts = (int64_t)lock.outputTimeStamp; enc->packet_keyframe = lock.pictureType == NV_ENC_PIC_TYPE_IDR; @@ -1101,8 +1044,7 @@ static bool get_encoded_packet(struct nvenc_data *enc, bool finalize) if (nvtex && nvtex->mapped_res) { NVENCSTATUS err; err = nv.nvEncUnmapInputResource(s, nvtex->mapped_res); - if (nv_failed(enc->encoder, err, __FUNCTION__, - "unmap")) { + if (nv_failed(enc->encoder, err, __FUNCTION__, "unmap")) { return false; } nvtex->mapped_res = NULL; @@ -1113,8 +1055,7 @@ static bool get_encoded_packet(struct nvenc_data *enc, bool finalize) if (surf && surf->mapped_res) { NVENCSTATUS err; err = nv.nvEncUnmapInputResource(s, surf->mapped_res); - if (nv_failed(enc->encoder, err, __FUNCTION__, - "unmap")) { + if (nv_failed(enc->encoder, err, __FUNCTION__, "unmap")) { return false; } surf->mapped_res = NULL; @@ -1221,9 +1162,8 @@ static void add_roi(struct nvenc_data *enc, NV_ENC_PIC_PARAMS *params) params->qpDeltaMapSize = (uint32_t)map_size; } -bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, - void *pic, int64_t pts, struct encoder_packet *packet, - bool *received_packet) +bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, void *pic, int64_t pts, + struct encoder_packet *packet, bool *received_packet) { NV_ENC_PIC_PARAMS params = {0}; params.version = NV_ENC_PIC_PARAMS_VER; @@ -1239,9 +1179,8 @@ bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, if (enc->non_texture) { params.bufferFmt = enc->surface_format; } else { - params.bufferFmt = obs_p010_tex_active() - ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT - : NV_ENC_BUFFER_FORMAT_NV12; + params.bufferFmt = obs_p010_tex_active() ? NV_ENC_BUFFER_FORMAT_YUV420_10BIT + : NV_ENC_BUFFER_FORMAT_NV12; } /* Add ROI map if enabled */ @@ -1250,8 +1189,7 @@ bool nvenc_encode_base(struct nvenc_data *enc, struct nv_bitstream *bs, NVENCSTATUS err = nv.nvEncEncodePicture(enc->session, ¶ms); if (err != NV_ENC_SUCCESS && err != NV_ENC_ERR_NEED_MORE_INPUT) { - nv_failed(enc->encoder, err, __FUNCTION__, - "nvEncEncodePicture"); + nv_failed(enc->encoder, err, __FUNCTION__, "nvEncEncodePicture"); return false; } @@ -1330,8 +1268,7 @@ struct obs_encoder_info h264_nvenc_info = { .id = "obs_nvenc_h264_tex", .codec = "h264", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI, .get_name = h264_nvenc_get_name, .create = h264_nvenc_create, .destroy = nvenc_destroy, @@ -1352,8 +1289,7 @@ struct obs_encoder_info hevc_nvenc_info = { .id = "obs_nvenc_hevc_tex", .codec = "hevc", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI, .get_name = hevc_nvenc_get_name, .create = hevc_nvenc_create, .destroy = nvenc_destroy, @@ -1374,8 +1310,7 @@ struct obs_encoder_info av1_nvenc_info = { .id = "obs_nvenc_av1_tex", .codec = "av1", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI, .get_name = av1_nvenc_get_name, .create = av1_nvenc_create, .destroy = nvenc_destroy, @@ -1394,8 +1329,7 @@ struct obs_encoder_info h264_nvenc_soft_info = { .id = "obs_nvenc_h264_soft", .codec = "h264", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | - OBS_ENCODER_CAP_INTERNAL, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_INTERNAL, .get_name = h264_nvenc_soft_get_name, .create = h264_nvenc_soft_create, .destroy = nvenc_destroy, @@ -1413,8 +1347,7 @@ struct obs_encoder_info hevc_nvenc_soft_info = { .id = "obs_nvenc_hevc_soft", .codec = "hevc", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | - OBS_ENCODER_CAP_INTERNAL, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_INTERNAL, .get_name = hevc_nvenc_soft_get_name, .create = hevc_nvenc_soft_create, .destroy = nvenc_destroy, @@ -1432,8 +1365,7 @@ struct obs_encoder_info av1_nvenc_soft_info = { .id = "obs_nvenc_av1_soft", .codec = "av1", .type = OBS_ENCODER_VIDEO, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | - OBS_ENCODER_CAP_INTERNAL, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_ROI | OBS_ENCODER_CAP_INTERNAL, .get_name = av1_nvenc_soft_get_name, .create = av1_nvenc_soft_create, .destroy = nvenc_destroy, diff --git a/plugins/obs-nvenc/obs-nvenc-test/obs-nvenc-test.cpp b/plugins/obs-nvenc/obs-nvenc-test/obs-nvenc-test.cpp index 91cfbb9cf..211f6f15e 100644 --- a/plugins/obs-nvenc/obs-nvenc-test/obs-nvenc-test.cpp +++ b/plugins/obs-nvenc/obs-nvenc-test/obs-nvenc-test.cpp @@ -20,8 +20,7 @@ static CudaFunctions *cu = nullptr; static NvencFunctions *nvenc = nullptr; NV_ENCODE_API_FUNCTION_LIST nv = {NV_ENCODE_API_FUNCTION_LIST_VER}; -static constexpr uint32_t NVENC_CONFIGURED_VERSION = - (NVENCAPI_MAJOR_VERSION << 4) | NVENCAPI_MINOR_VERSION; +static constexpr uint32_t NVENC_CONFIGURED_VERSION = (NVENCAPI_MAJOR_VERSION << 4) | NVENCAPI_MINOR_VERSION; /* NVML stuff */ #define NVML_SUCCESS 0 @@ -48,12 +47,9 @@ typedef nvmlReturn_t (*NVML_GET_DEVICE_NAME)(nvmlDevice_t, char *, unsigned); typedef nvmlReturn_t (*NVML_GET_DEVICE_PCIE_GEN)(nvmlDevice_t, unsigned *); typedef nvmlReturn_t (*NVML_GET_DEVICE_PCIE_WIDTH)(nvmlDevice_t, unsigned *); typedef nvmlReturn_t (*NVML_GET_DEVICE_NAME)(nvmlDevice_t, char *, unsigned); -typedef nvmlReturn_t (*NVML_GET_ENCODER_SESSIONS)(nvmlDevice_t, unsigned *, - void *); -typedef nvmlReturn_t (*NVML_GET_ENCODER_CAPACITY)(nvmlDevice_t, nvmlEncoderType, - unsigned *); -typedef nvmlReturn_t (*NVML_GET_ENCODER_UTILISATION)(nvmlDevice_t, unsigned *, - unsigned *); +typedef nvmlReturn_t (*NVML_GET_ENCODER_SESSIONS)(nvmlDevice_t, unsigned *, void *); +typedef nvmlReturn_t (*NVML_GET_ENCODER_CAPACITY)(nvmlDevice_t, nvmlEncoderType, unsigned *); +typedef nvmlReturn_t (*NVML_GET_ENCODER_UTILISATION)(nvmlDevice_t, unsigned *, unsigned *); /* List of capabilities to be queried per codec */ static const vector> capabilities = { {NV_ENC_CAPS_NUM_MAX_BFRAMES, "bframes"}, @@ -74,10 +70,9 @@ static const vector> capabilities = { #endif }; -static const vector> codecs = { - {"h264", NV_ENC_CODEC_H264_GUID}, - {"hevc", NV_ENC_CODEC_HEVC_GUID}, - {"av1", NV_ENC_CODEC_AV1_GUID}}; +static const vector> codecs = {{"h264", NV_ENC_CODEC_H264_GUID}, + {"hevc", NV_ENC_CODEC_HEVC_GUID}, + {"av1", NV_ENC_CODEC_AV1_GUID}}; typedef unordered_map> codec_caps_map; @@ -131,31 +126,19 @@ struct NVML { init = (NVML_INIT_V2)load_nvml_func("nvmlInit_v2"); shutdown = (NVML_SHUTDOWN)load_nvml_func("nvmlShutdown"); - getDriverVersion = (NVML_GET_DRIVER_VER_FUNC)load_nvml_func( - "nvmlSystemGetDriverVersion"); + getDriverVersion = (NVML_GET_DRIVER_VER_FUNC)load_nvml_func("nvmlSystemGetDriverVersion"); getDeviceHandleByPCIBusId = - (NVML_GET_HANDLE_BY_BUS_ID)load_nvml_func( - "nvmlDeviceGetHandleByPciBusId_v2"); - getDeviceUUID = (NVML_GET_DEVICE_UUID)load_nvml_func( - "nvmlDeviceGetUUID"); - getDeviceName = (NVML_GET_DEVICE_NAME)load_nvml_func( - "nvmlDeviceGetName"); - getDevicePCIeGen = (NVML_GET_DEVICE_PCIE_GEN)load_nvml_func( - "nvmlDeviceGetCurrPcieLinkGeneration"); - getDevicePCIeWidth = (NVML_GET_DEVICE_PCIE_WIDTH)load_nvml_func( - "nvmlDeviceGetCurrPcieLinkWidth"); - getEncoderSessions = (NVML_GET_ENCODER_SESSIONS)load_nvml_func( - "nvmlDeviceGetEncoderSessions"); - getEncoderCapacity = (NVML_GET_ENCODER_CAPACITY)load_nvml_func( - "nvmlDeviceGetEncoderCapacity"); - getEncoderUtilisation = - (NVML_GET_ENCODER_UTILISATION)load_nvml_func( - "nvmlDeviceGetEncoderUtilization"); + (NVML_GET_HANDLE_BY_BUS_ID)load_nvml_func("nvmlDeviceGetHandleByPciBusId_v2"); + getDeviceUUID = (NVML_GET_DEVICE_UUID)load_nvml_func("nvmlDeviceGetUUID"); + getDeviceName = (NVML_GET_DEVICE_NAME)load_nvml_func("nvmlDeviceGetName"); + getDevicePCIeGen = (NVML_GET_DEVICE_PCIE_GEN)load_nvml_func("nvmlDeviceGetCurrPcieLinkGeneration"); + getDevicePCIeWidth = (NVML_GET_DEVICE_PCIE_WIDTH)load_nvml_func("nvmlDeviceGetCurrPcieLinkWidth"); + getEncoderSessions = (NVML_GET_ENCODER_SESSIONS)load_nvml_func("nvmlDeviceGetEncoderSessions"); + getEncoderCapacity = (NVML_GET_ENCODER_CAPACITY)load_nvml_func("nvmlDeviceGetEncoderCapacity"); + getEncoderUtilisation = (NVML_GET_ENCODER_UTILISATION)load_nvml_func("nvmlDeviceGetEncoderUtilization"); - if (!init || !shutdown || !getDriverVersion || - !getDeviceHandleByPCIBusId || !getDeviceUUID || - !getDeviceName || !getDevicePCIeGen || - !getDevicePCIeWidth || !getEncoderSessions || + if (!init || !shutdown || !getDriverVersion || !getDeviceHandleByPCIBusId || !getDeviceUUID || + !getDeviceName || !getDevicePCIeGen || !getDevicePCIeWidth || !getEncoderSessions || !getEncoderCapacity || !getEncoderUtilisation) { return false; } @@ -187,8 +170,7 @@ private: static void *load_nvml_func(const char *func) { #ifdef _WIN32 - void *func_ptr = - (void *)GetProcAddress((HMODULE)nvml_lib, func); + void *func_ptr = (void *)GetProcAddress((HMODULE)nvml_lib, func); #else void *func_ptr = dlsym(nvml_lib, func); #endif @@ -219,8 +201,7 @@ struct CUDACtx { bus_id.resize(16); cu->cuCtxGetDevice(&dev); - cu->cuDeviceGetPCIBusId(bus_id.data(), (int)bus_id.capacity(), - dev); + cu->cuDeviceGetPCIBusId(bus_id.data(), (int)bus_id.capacity(), dev); return bus_id; } @@ -235,8 +216,7 @@ struct CUDACtx { uuid_str.resize(32); for (size_t idx = 0; idx < 16; idx++) { - sprintf(uuid_str.data() + idx * 2, "%02x", - uuid.bytes[idx] & 0xFF); + sprintf(uuid_str.data() + idx * 2, "%02x", uuid.bytes[idx] & 0xFF); } return uuid_str; @@ -258,8 +238,7 @@ struct NVSession { params.device = ctx.ctx; params.deviceType = NV_ENC_DEVICE_TYPE_CUDA; - return nv.nvEncOpenEncodeSessionEx(¶ms, &ptr) == - NV_ENC_SUCCESS; + return nv.nvEncOpenEncodeSessionEx(¶ms, &ptr) == NV_ENC_SUCCESS; } }; @@ -295,8 +274,7 @@ static bool init_cuda() return true; } -static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, - device_info &device_info, NVML &nvml) +static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, device_info &device_info, NVML &nvml) { CUDACtx cudaCtx; NVSession nvSession; @@ -308,8 +286,7 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, device_info.cuda_uuid = cudaCtx.GetUUID(); nvmlDevice_t dev; - if (nvml.getDeviceHandleByPCIBusId(device_info.pci_id.data(), &dev) == - NVML_SUCCESS) { + if (nvml.getDeviceHandleByPCIBusId(device_info.pci_id.data(), &dev) == NVML_SUCCESS) { char uuid[NVML_DEVICE_UUID_V2_BUFFER_SIZE]; nvml.getDeviceUUID(dev, uuid, sizeof(uuid)); device_info.nvml_uuid = uuid; @@ -320,30 +297,23 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, nvml.getDevicePCIeGen(dev, &device_info.pcie_gen); nvml.getDevicePCIeWidth(dev, &device_info.pcie_width); - nvml.getEncoderSessions(dev, &device_info.encoder_sessions, - nullptr); - nvml.getEncoderUtilisation(dev, &device_info.utilisation, - &device_info.sample_period); - nvml.getEncoderCapacity(dev, NVML_ENCODER_QUERY_H264, - &device_info.capacity_h264); - nvml.getEncoderCapacity(dev, NVML_ENCODER_QUERY_HEVC, - &device_info.capacity_hevc); - nvml.getEncoderCapacity(dev, NVML_ENCODER_QUERY_AV1, - &device_info.capacity_av1); + nvml.getEncoderSessions(dev, &device_info.encoder_sessions, nullptr); + nvml.getEncoderUtilisation(dev, &device_info.utilisation, &device_info.sample_period); + nvml.getEncoderCapacity(dev, NVML_ENCODER_QUERY_H264, &device_info.capacity_h264); + nvml.getEncoderCapacity(dev, NVML_ENCODER_QUERY_HEVC, &device_info.capacity_hevc); + nvml.getEncoderCapacity(dev, NVML_ENCODER_QUERY_AV1, &device_info.capacity_av1); } if (!nvSession.OpenSession(cudaCtx)) return false; uint32_t guid_count = 0; - if (nv.nvEncGetEncodeGUIDCount(nvSession.ptr, &guid_count) != - NV_ENC_SUCCESS) + if (nv.nvEncGetEncodeGUIDCount(nvSession.ptr, &guid_count) != NV_ENC_SUCCESS) return false; vector guids; guids.resize(guid_count); - NVENCSTATUS stat = nv.nvEncGetEncodeGUIDs(nvSession.ptr, guids.data(), - guid_count, &guid_count); + NVENCSTATUS stat = nv.nvEncGetEncodeGUIDs(nvSession.ptr, guids.data(), guid_count, &guid_count); if (stat != NV_ENC_SUCCESS) return false; @@ -366,8 +336,7 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, for (const auto &[cap, name] : capabilities) { int v; param.capsToQuery = cap; - if (nv.nvEncGetEncodeCaps(nvSession.ptr, *guid, ¶m, - &v) != NV_ENC_SUCCESS) + if (nv.nvEncGetEncodeCaps(nvSession.ptr, *guid, ¶m, &v) != NV_ENC_SUCCESS) continue; device_info.caps[codec_name][name] = v; @@ -403,8 +372,7 @@ bool nvenc_checks(codec_caps_map &caps, vector &device_infos) char driver_ver[NVML_SYSTEM_DRIVER_VERSION_BUFFER_SIZE]; /* NVIDIA driver version */ - if (nvml.getDriverVersion(driver_ver, sizeof(driver_ver)) == - NVML_SUCCESS) { + if (nvml.getDriverVersion(driver_ver, sizeof(driver_ver)) == NVML_SUCCESS) { printf("driver_ver=%s\n", driver_ver); } else { // Treat this as a non-fatal failure @@ -413,15 +381,13 @@ bool nvenc_checks(codec_caps_map &caps, vector &device_infos) /* CUDA driver version and devices */ if (cu->cuDriverGetVersion(&cuda_driver_ver) == CUDA_SUCCESS) { - printf("cuda_ver=%d.%d\n", cuda_driver_ver / 1000, - cuda_driver_ver % 1000); + printf("cuda_ver=%d.%d\n", cuda_driver_ver / 1000, cuda_driver_ver % 1000); } else { printf("reason=no_cuda_version\n"); return false; } - if (cu->cuDeviceGetCount(&cuda_devices) == CUDA_SUCCESS && - cuda_devices) { + if (cu->cuDeviceGetCount(&cuda_devices) == CUDA_SUCCESS && cuda_devices) { printf("cuda_devices=%d\n", cuda_devices); } else { printf("reason=no_devices\n"); @@ -429,8 +395,7 @@ bool nvenc_checks(codec_caps_map &caps, vector &device_infos) } /* NVENC API version */ - if (nvenc->NvEncodeAPIGetMaxSupportedVersion(&nvenc_ver) == - NV_ENC_SUCCESS) { + if (nvenc->NvEncodeAPIGetMaxSupportedVersion(&nvenc_ver) == NV_ENC_SUCCESS) { printf("nvenc_ver=%d.%d\n", nvenc_ver >> 4, nvenc_ver & 0xf); } else { printf("reason=no_nvenc_version\n"); @@ -502,11 +467,9 @@ int check_thread() "capacity_h264=%u\n" "capacity_hevc=%u\n" "capacity_av1=%u\n", - idx, info.pci_id.c_str(), info.nvml_uuid.c_str(), - info.cuda_uuid.c_str(), info.name.c_str(), - info.pcie_width, info.pcie_gen, info.encoder_sessions, - info.utilisation, info.sample_period, info.capacity_h264, - info.capacity_hevc, info.capacity_av1); + idx, info.pci_id.c_str(), info.nvml_uuid.c_str(), info.cuda_uuid.c_str(), info.name.c_str(), + info.pcie_width, info.pcie_gen, info.encoder_sessions, info.utilisation, info.sample_period, + info.capacity_h264, info.capacity_hevc, info.capacity_av1); for (const auto &[codec, codec_caps] : info.caps) { printf("\n[device.%zu.%s]\n", idx, codec.c_str()); diff --git a/plugins/obs-outputs/flv-mux.c b/plugins/obs-outputs/flv-mux.c index 2b323e684..6b6357e05 100644 --- a/plugins/obs-outputs/flv-mux.c +++ b/plugins/obs-outputs/flv-mux.c @@ -187,8 +187,7 @@ void write_file_info(FILE *file, int64_t duration_ms, int64_t size) fwrite(buf, 1, enc - buf, file); } -static void build_flv_meta_data(obs_output_t *context, uint8_t **output, - size_t *size) +static void build_flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size) { obs_encoder_t *vencoder = obs_output_get_video_encoder(context); obs_encoder_t *aencoder = obs_output_get_audio_encoder(context, 0); @@ -208,10 +207,8 @@ static void build_flv_meta_data(obs_output_t *context, uint8_t **output, enc_num_val(&enc, end, "duration", 0.0); enc_num_val(&enc, end, "fileSize", 0.0); - enc_num_val(&enc, end, "width", - (double)obs_encoder_get_width(vencoder)); - enc_num_val(&enc, end, "height", - (double)obs_encoder_get_height(vencoder)); + enc_num_val(&enc, end, "width", (double)obs_encoder_get_width(vencoder)); + enc_num_val(&enc, end, "height", (double)obs_encoder_get_height(vencoder)); enc_num_val(&enc, end, "videocodecid", encoder_video_codec(vencoder)); enc_num_val(&enc, end, "videodatarate", encoder_bitrate(vencoder)); @@ -219,14 +216,11 @@ static void build_flv_meta_data(obs_output_t *context, uint8_t **output, enc_num_val(&enc, end, "audiocodecid", AUDIODATA_AAC); enc_num_val(&enc, end, "audiodatarate", encoder_bitrate(aencoder)); - enc_num_val(&enc, end, "audiosamplerate", - (double)obs_encoder_get_sample_rate(aencoder)); + enc_num_val(&enc, end, "audiosamplerate", (double)obs_encoder_get_sample_rate(aencoder)); enc_num_val(&enc, end, "audiosamplesize", 16.0); - enc_num_val(&enc, end, "audiochannels", - (double)audio_output_get_channels(audio)); + enc_num_val(&enc, end, "audiochannels", (double)audio_output_get_channels(audio)); - enc_bool_val(&enc, end, "stereo", - audio_output_get_channels(audio) == 2); + enc_bool_val(&enc, end, "stereo", audio_output_get_channels(audio) == 2); enc_bool_val(&enc, end, "2.1", audio_output_get_channels(audio) == 3); enc_bool_val(&enc, end, "3.1", audio_output_get_channels(audio) == 4); enc_bool_val(&enc, end, "4.0", audio_output_get_channels(audio) == 4); @@ -239,8 +233,7 @@ static void build_flv_meta_data(obs_output_t *context, uint8_t **output, #ifdef HAVE_OBSCONFIG_H dstr_cat(&encoder_name, obs_get_version_string()); #else - dstr_catf(&encoder_name, "%d.%d.%d", LIBOBS_API_MAJOR_VER, - LIBOBS_API_MINOR_VER, LIBOBS_API_PATCH_VER); + dstr_catf(&encoder_name, "%d.%d.%d", LIBOBS_API_MAJOR_VER, LIBOBS_API_MINOR_VER, LIBOBS_API_PATCH_VER); #endif dstr_cat(&encoder_name, ")"); @@ -256,8 +249,7 @@ static void build_flv_meta_data(obs_output_t *context, uint8_t **output, *output = bmemdup(buf, *size); } -static inline void write_previous_tag_size_without_header(struct serializer *s, - uint32_t header_size) +static inline void write_previous_tag_size_without_header(struct serializer *s, uint32_t header_size) { assert(serializer_get_pos(s) >= header_size); assert(serializer_get_pos(s) >= 11); @@ -276,8 +268,7 @@ static inline void write_previous_tag_size(struct serializer *s) write_previous_tag_size_without_header(s, 0); } -void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, - bool write_header) +void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, bool write_header) { struct array_output_data data; struct serializer s; @@ -318,8 +309,7 @@ void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, static int32_t last_time = 0; #endif -static void flv_video(struct serializer *s, int32_t dts_offset, - struct encoder_packet *packet, bool is_header) +static void flv_video(struct serializer *s, int32_t dts_offset, struct encoder_packet *packet, bool is_header) { int64_t offset = packet->pts - packet->dts; int32_t time_ms = get_ms_time(packet, packet->dts) - dts_offset; @@ -352,8 +342,7 @@ static void flv_video(struct serializer *s, int32_t dts_offset, write_previous_tag_size(s); } -static void flv_audio(struct serializer *s, int32_t dts_offset, - struct encoder_packet *packet, bool is_header) +static void flv_audio(struct serializer *s, int32_t dts_offset, struct encoder_packet *packet, bool is_header) { int32_t time_ms = get_ms_time(packet, packet->dts) - dts_offset; @@ -384,8 +373,7 @@ static void flv_audio(struct serializer *s, int32_t dts_offset, write_previous_tag_size(s); } -void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, - uint8_t **output, size_t *size, bool is_header) +void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, uint8_t **output, size_t *size, bool is_header) { struct array_output_data data; struct serializer s; @@ -401,9 +389,8 @@ void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, *size = data.bytes.num; } -void flv_packet_audio_ex(struct encoder_packet *packet, - enum audio_id_t codec_id, int32_t dts_offset, - uint8_t **output, size_t *size, int type, size_t idx) +void flv_packet_audio_ex(struct encoder_packet *packet, enum audio_id_t codec_id, int32_t dts_offset, uint8_t **output, + size_t *size, int type, size_t idx) { struct array_output_data data; struct serializer s; @@ -439,8 +426,7 @@ void flv_packet_audio_ex(struct encoder_packet *packet, s_w8(&s, (time_ms >> 24) & 0x7F); s_wb24(&s, 0); - s_w8(&s, AUDIO_HEADER_EX | - (is_multitrack ? AUDIO_PACKETTYPE_MULTITRACK : type)); + s_w8(&s, AUDIO_HEADER_EX | (is_multitrack ? AUDIO_PACKETTYPE_MULTITRACK : type)); if (is_multitrack) { s_w8(&s, MULTITRACKTYPE_ONE_TRACK | type); s_wa4cc(&s, codec_id); @@ -458,9 +444,8 @@ void flv_packet_audio_ex(struct encoder_packet *packet, } // Y2023 spec -void flv_packet_ex(struct encoder_packet *packet, enum video_id_t codec_id, - int32_t dts_offset, uint8_t **output, size_t *size, int type, - size_t idx) +void flv_packet_ex(struct encoder_packet *packet, enum video_id_t codec_id, int32_t dts_offset, uint8_t **output, + size_t *size, int type, size_t idx) { struct array_output_data data; struct serializer s; @@ -475,8 +460,7 @@ void flv_packet_ex(struct encoder_packet *packet, enum video_id_t codec_id, // packet head int header_metadata_size = 5; // w8+w4cc // 3 extra bytes for composition time offset - if ((codec_id == CODEC_H264 || codec_id == CODEC_HEVC) && - type == PACKETTYPE_FRAMES) { + if ((codec_id == CODEC_H264 || codec_id == CODEC_HEVC) && type == PACKETTYPE_FRAMES) { header_metadata_size += 3; // w24 } if (is_multitrack) @@ -505,8 +489,7 @@ void flv_packet_ex(struct encoder_packet *packet, enum video_id_t codec_id, } // H.264/HEVC composition time offset - if ((codec_id == CODEC_H264 || codec_id == CODEC_HEVC) && - type == PACKETTYPE_FRAMES) { + if ((codec_id == CODEC_H264 || codec_id == CODEC_HEVC) && type == PACKETTYPE_FRAMES) { s_wb24(&s, get_ms_time(packet, packet->pts - packet->dts)); } @@ -520,53 +503,41 @@ void flv_packet_ex(struct encoder_packet *packet, enum video_id_t codec_id, *size = data.bytes.num; } -void flv_packet_start(struct encoder_packet *packet, enum video_id_t codec, - uint8_t **output, size_t *size, size_t idx) +void flv_packet_start(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size, size_t idx) { - flv_packet_ex(packet, codec, 0, output, size, PACKETTYPE_SEQ_START, - idx); + flv_packet_ex(packet, codec, 0, output, size, PACKETTYPE_SEQ_START, idx); } -void flv_packet_frames(struct encoder_packet *packet, enum video_id_t codec, - int32_t dts_offset, uint8_t **output, size_t *size, - size_t idx) +void flv_packet_frames(struct encoder_packet *packet, enum video_id_t codec, int32_t dts_offset, uint8_t **output, + size_t *size, size_t idx) { int packet_type = PACKETTYPE_FRAMES; // PACKETTYPE_FRAMESX is an optimization to avoid sending composition // time offsets of 0. See Enhanced RTMP spec. - if ((codec == CODEC_H264 || codec == CODEC_HEVC) && - packet->dts == packet->pts) + if ((codec == CODEC_H264 || codec == CODEC_HEVC) && packet->dts == packet->pts) packet_type = PACKETTYPE_FRAMESX; - flv_packet_ex(packet, codec, dts_offset, output, size, packet_type, - idx); + flv_packet_ex(packet, codec, dts_offset, output, size, packet_type, idx); } -void flv_packet_end(struct encoder_packet *packet, enum video_id_t codec, - uint8_t **output, size_t *size, size_t idx) +void flv_packet_end(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size, size_t idx) { flv_packet_ex(packet, codec, 0, output, size, PACKETTYPE_SEQ_END, idx); } -void flv_packet_audio_start(struct encoder_packet *packet, - enum audio_id_t codec, uint8_t **output, - size_t *size, size_t idx) +void flv_packet_audio_start(struct encoder_packet *packet, enum audio_id_t codec, uint8_t **output, size_t *size, + size_t idx) { - flv_packet_audio_ex(packet, codec, 0, output, size, - AUDIO_PACKETTYPE_SEQ_START, idx); + flv_packet_audio_ex(packet, codec, 0, output, size, AUDIO_PACKETTYPE_SEQ_START, idx); } -void flv_packet_audio_frames(struct encoder_packet *packet, - enum audio_id_t codec, int32_t dts_offset, - uint8_t **output, size_t *size, size_t idx) +void flv_packet_audio_frames(struct encoder_packet *packet, enum audio_id_t codec, int32_t dts_offset, uint8_t **output, + size_t *size, size_t idx) { - flv_packet_audio_ex(packet, codec, dts_offset, output, size, - AUDIO_PACKETTYPE_FRAMES, idx); + flv_packet_audio_ex(packet, codec, dts_offset, output, size, AUDIO_PACKETTYPE_FRAMES, idx); } -void flv_packet_metadata(enum video_id_t codec_id, uint8_t **output, - size_t *size, int bits_per_raw_sample, - uint8_t color_primaries, int color_trc, - int color_space, int min_luminance, int max_luminance, +void flv_packet_metadata(enum video_id_t codec_id, uint8_t **output, size_t *size, int bits_per_raw_sample, + uint8_t color_primaries, int color_trc, int color_space, int min_luminance, int max_luminance, size_t idx) { // metadata array @@ -648,8 +619,7 @@ void flv_packet_metadata(enum video_id_t codec_id, uint8_t **output, // packet ext header // these are the 5 extra bytes mentioned above - s_w8(&s, FRAME_HEADER_EX | (is_multitrack ? PACKETTYPE_MULTITRACK - : PACKETTYPE_METADATA)); + s_w8(&s, FRAME_HEADER_EX | (is_multitrack ? PACKETTYPE_MULTITRACK : PACKETTYPE_METADATA)); /* * We only add explicitly emit trackIds iff idx > 0. diff --git a/plugins/obs-outputs/flv-mux.h b/plugins/obs-outputs/flv-mux.h index e5cab0ddf..2c694fabe 100644 --- a/plugins/obs-outputs/flv-mux.h +++ b/plugins/obs-outputs/flv-mux.h @@ -60,27 +60,20 @@ static int32_t get_ms_time(struct encoder_packet *packet, int64_t val) extern void write_file_info(FILE *file, int64_t duration_ms, int64_t size); -extern void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, - bool write_header); -extern void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, - uint8_t **output, size_t *size, bool is_header); +extern void flv_meta_data(obs_output_t *context, uint8_t **output, size_t *size, bool write_header); +extern void flv_packet_mux(struct encoder_packet *packet, int32_t dts_offset, uint8_t **output, size_t *size, + bool is_header); // Y2023 spec -extern void flv_packet_start(struct encoder_packet *packet, - enum video_id_t codec, uint8_t **output, - size_t *size, size_t idx); -extern void flv_packet_frames(struct encoder_packet *packet, - enum video_id_t codec, int32_t dts_offset, +extern void flv_packet_start(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size, + size_t idx); +extern void flv_packet_frames(struct encoder_packet *packet, enum video_id_t codec, int32_t dts_offset, uint8_t **output, size_t *size, size_t idx); -extern void flv_packet_end(struct encoder_packet *packet, enum video_id_t codec, - uint8_t **output, size_t *size, size_t idx); -extern void flv_packet_metadata(enum video_id_t codec, uint8_t **output, - size_t *size, int bits_per_raw_sample, - uint8_t color_primaries, int color_trc, - int color_space, int min_luminance, +extern void flv_packet_end(struct encoder_packet *packet, enum video_id_t codec, uint8_t **output, size_t *size, + size_t idx); +extern void flv_packet_metadata(enum video_id_t codec, uint8_t **output, size_t *size, int bits_per_raw_sample, + uint8_t color_primaries, int color_trc, int color_space, int min_luminance, int max_luminance, size_t idx); -extern void flv_packet_audio_start(struct encoder_packet *packet, - enum audio_id_t codec, uint8_t **output, - size_t *size, size_t idx); -extern void flv_packet_audio_frames(struct encoder_packet *packet, - enum audio_id_t codec, int32_t dts_offset, +extern void flv_packet_audio_start(struct encoder_packet *packet, enum audio_id_t codec, uint8_t **output, size_t *size, + size_t idx); +extern void flv_packet_audio_frames(struct encoder_packet *packet, enum audio_id_t codec, int32_t dts_offset, uint8_t **output, size_t *size, size_t idx); diff --git a/plugins/obs-outputs/flv-output.c b/plugins/obs-outputs/flv-output.c index 9681f2794..c47a1b95f 100644 --- a/plugins/obs-outputs/flv-output.c +++ b/plugins/obs-outputs/flv-output.c @@ -29,9 +29,8 @@ #include #include "flv-mux.h" -#define do_log(level, format, ...) \ - blog(level, "[flv output: '%s'] " format, \ - obs_output_get_name(stream->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[flv output: '%s'] " format, obs_output_get_name(stream->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -179,8 +178,7 @@ static void *flv_output_create(obs_data_t *settings, obs_output_t *output) return stream; } -static int write_packet(struct flv_output *stream, - struct encoder_packet *packet, bool is_header) +static int write_packet(struct flv_output *stream, struct encoder_packet *packet, bool is_header) { uint8_t *data; size_t size; @@ -188,31 +186,26 @@ static int write_packet(struct flv_output *stream, stream->last_packet_ts = get_ms_time(packet, packet->dts); - flv_packet_mux(packet, is_header ? 0 : stream->start_dts_offset, &data, - &size, is_header); + flv_packet_mux(packet, is_header ? 0 : stream->start_dts_offset, &data, &size, is_header); fwrite(data, 1, size, stream->file); bfree(data); return ret; } -static int write_packet_ex(struct flv_output *stream, - struct encoder_packet *packet, bool is_header, - bool is_footer, size_t idx) +static int write_packet_ex(struct flv_output *stream, struct encoder_packet *packet, bool is_header, bool is_footer, + size_t idx) { uint8_t *data; size_t size = 0; int ret = 0; if (is_header) { - flv_packet_start(packet, stream->video_codec[idx], &data, &size, - idx); + flv_packet_start(packet, stream->video_codec[idx], &data, &size, idx); } else if (is_footer) { - flv_packet_end(packet, stream->video_codec[idx], &data, &size, - idx); + flv_packet_end(packet, stream->video_codec[idx], &data, &size, idx); } else { - flv_packet_frames(packet, stream->video_codec[idx], - stream->start_dts_offset, &data, &size, idx); + flv_packet_frames(packet, stream->video_codec[idx], stream->start_dts_offset, &data, &size, idx); } fwrite(data, 1, size, stream->file); @@ -227,21 +220,16 @@ static int write_packet_ex(struct flv_output *stream, return ret; } -static int write_audio_packet_ex(struct flv_output *stream, - struct encoder_packet *packet, bool is_header, - size_t idx) +static int write_audio_packet_ex(struct flv_output *stream, struct encoder_packet *packet, bool is_header, size_t idx) { uint8_t *data; size_t size = 0; int ret = 0; if (is_header) { - flv_packet_audio_start(packet, stream->audio_codec[idx], &data, - &size, idx); + flv_packet_audio_start(packet, stream->audio_codec[idx], &data, &size, idx); } else { - flv_packet_audio_frames(packet, stream->audio_codec[idx], - stream->start_dts_offset, &data, &size, - idx); + flv_packet_audio_frames(packet, stream->audio_codec[idx], stream->start_dts_offset, &data, &size, idx); } fwrite(data, 1, size, stream->file); @@ -265,8 +253,7 @@ static bool write_audio_header(struct flv_output *stream, size_t idx) obs_output_t *context = stream->output; obs_encoder_t *aencoder = obs_output_get_audio_encoder(context, idx); - struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, - .timebase_den = 1}; + struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, .timebase_den = 1}; if (!aencoder) return false; @@ -289,9 +276,7 @@ static bool write_video_header(struct flv_output *stream, size_t idx) uint8_t *header; size_t size; - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = true}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true}; if (!vencoder) return false; @@ -301,9 +286,7 @@ static bool write_video_header(struct flv_output *stream, size_t idx) switch (stream->video_codec[idx]) { case CODEC_NONE: - do_log(LOG_ERROR, - "Codec not initialized for track %zu while sending header", - idx); + do_log(LOG_ERROR, "Codec not initialized for track %zu while sending header", idx); return false; case CODEC_H264: @@ -335,8 +318,7 @@ static bool write_video_header(struct flv_output *stream, size_t idx) static bool write_video_metadata(struct flv_output *stream, size_t idx) { // send metadata only if HDR - obs_encoder_t *encoder = - obs_output_get_video_encoder2(stream->output, idx); + obs_encoder_t *encoder = obs_output_get_video_encoder2(stream->output, idx); if (!encoder) return false; @@ -346,8 +328,7 @@ static bool write_video_metadata(struct flv_output *stream, size_t idx) const struct video_output_info *info = video_output_get_info(video); enum video_colorspace colorspace = info->colorspace; - if (!(colorspace == VIDEO_CS_2100_PQ || - colorspace == VIDEO_CS_2100_HLG)) + if (!(colorspace == VIDEO_CS_2100_PQ || colorspace == VIDEO_CS_2100_HLG)) return true; // Y2023 spec @@ -411,8 +392,7 @@ static bool write_video_metadata(struct flv_output *stream, size_t idx) else if (trc == OBSCOL_TRC_SMPTE2084) max_luminance = (int)obs_get_video_hdr_nominal_peak_level(); - flv_packet_metadata(stream->video_codec[idx], &data, &size, - bits_per_raw_sample, pri, trc, spc, 0, + flv_packet_metadata(stream->video_codec[idx], &data, &size, bits_per_raw_sample, pri, trc, spc, 0, max_luminance, idx); fwrite(data, 1, size, stream->file); @@ -424,8 +404,7 @@ static bool write_video_metadata(struct flv_output *stream, size_t idx) static void write_headers(struct flv_output *stream) { for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { - obs_encoder_t *enc = - obs_output_get_audio_encoder(stream->output, i); + obs_encoder_t *enc = obs_output_get_audio_encoder(stream->output, i); if (!enc) break; @@ -434,8 +413,7 @@ static void write_headers(struct flv_output *stream) } for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - obs_encoder_t *enc = - obs_output_get_video_encoder2(stream->output, i); + obs_encoder_t *enc = obs_output_get_video_encoder2(stream->output, i); if (!enc) break; @@ -447,13 +425,11 @@ static void write_headers(struct flv_output *stream) write_audio_header(stream, 0); for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - obs_encoder_t *enc = - obs_output_get_video_encoder2(stream->output, i); + obs_encoder_t *enc = obs_output_get_video_encoder2(stream->output, i); if (!enc) continue; - if (!write_video_header(stream, i) || - !write_video_metadata(stream, i)) + if (!write_video_header(stream, i) || !write_video_metadata(stream, i)) return; } @@ -463,9 +439,7 @@ static void write_headers(struct flv_output *stream) static bool write_video_footer(struct flv_output *stream, size_t idx) { - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = false}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = false}; packet.size = 0; return write_packet_ex(stream, &packet, false, true, idx) >= 0; @@ -474,8 +448,7 @@ static bool write_video_footer(struct flv_output *stream, size_t idx) static inline bool write_footers(struct flv_output *stream) { for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - obs_encoder_t *encoder = - obs_output_get_video_encoder2(stream->output, i); + obs_encoder_t *encoder = obs_output_get_video_encoder2(stream->output, i); if (!encoder) continue; @@ -537,8 +510,7 @@ static void flv_output_actual_stop(struct flv_output *stream, int code) if (stream->file) { write_footers(stream); - write_file_info(stream->file, stream->last_packet_ts, - os_ftelli64(stream->file)); + write_file_info(stream->file, stream->last_packet_ts, os_ftelli64(stream->file)); fclose(stream->file); } @@ -580,15 +552,13 @@ static void flv_output_data(void *data, struct encoder_packet *packet) if (packet->type == OBS_ENCODER_VIDEO) { if (!stream->got_first_packet) { - stream->start_dts_offset = - get_ms_time(packet, packet->dts); + stream->start_dts_offset = get_ms_time(packet, packet->dts); stream->got_first_packet = true; } switch (stream->video_codec[packet->track_idx]) { case CODEC_NONE: - do_log(LOG_ERROR, "Codec not initialized for track %zu", - packet->track_idx); + do_log(LOG_ERROR, "Codec not initialized for track %zu", packet->track_idx); goto unlock; case CODEC_H264: @@ -607,24 +577,20 @@ static void flv_output_data(void *data, struct encoder_packet *packet) } if (stream->video_codec[packet->track_idx] != CODEC_H264 || - (stream->video_codec[packet->track_idx] == CODEC_H264 && - packet->track_idx != 0)) { - write_packet_ex(stream, &parsed_packet, false, false, - packet->track_idx); + (stream->video_codec[packet->track_idx] == CODEC_H264 && packet->track_idx != 0)) { + write_packet_ex(stream, &parsed_packet, false, false, packet->track_idx); } else { write_packet(stream, &parsed_packet, false); } obs_encoder_packet_release(&parsed_packet); } else { if (!stream->got_first_packet) { - stream->start_dts_offset = - get_ms_time(packet, packet->dts); + stream->start_dts_offset = get_ms_time(packet, packet->dts); stream->got_first_packet = true; } if (packet->track_idx != 0) { - write_audio_packet_ex(stream, packet, false, - packet->track_idx); + write_audio_packet_ex(stream, packet, false, packet->track_idx); } else { write_packet(stream, packet, false); } @@ -640,9 +606,7 @@ static obs_properties_t *flv_output_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "path", - obs_module_text("FLVOutput.FilePath"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "path", obs_module_text("FLVOutput.FilePath"), OBS_TEXT_DEFAULT); return props; } diff --git a/plugins/obs-outputs/mp4-mux-internal.h b/plugins/obs-outputs/mp4-mux-internal.h index 40856df8a..85393f2c6 100644 --- a/plugins/obs-outputs/mp4-mux-internal.h +++ b/plugins/obs-outputs/mp4-mux-internal.h @@ -211,9 +211,7 @@ static inline size_t min(size_t a, size_t b) } #endif -static inline void get_speaker_positions(enum speaker_layout layout, - uint8_t *arr, uint8_t *size, - uint8_t *iso_layout) +static inline void get_speaker_positions(enum speaker_layout layout, uint8_t *arr, uint8_t *size, uint8_t *iso_layout) { switch (layout) { case SPEAKERS_MONO: @@ -274,8 +272,7 @@ static inline void get_speaker_positions(enum speaker_layout layout, } } -static inline void get_colour_information(obs_encoder_t *enc, uint16_t *pri, - uint16_t *trc, uint16_t *spc, +static inline void get_colour_information(obs_encoder_t *enc, uint16_t *pri, uint16_t *trc, uint16_t *spc, uint8_t *full_range) { video_t *video = obs_encoder_video(enc); diff --git a/plugins/obs-outputs/mp4-mux.c b/plugins/obs-outputs/mp4-mux.c index ea86d8ee5..1f253cc41 100644 --- a/plugins/obs-outputs/mp4-mux.c +++ b/plugins/obs-outputs/mp4-mux.c @@ -37,9 +37,8 @@ * Standard identifier is included if not referring to ISO/IEC 14496-12. */ -#define do_log(level, format, ...) \ - blog(level, "[mp4 muxer: '%s'] " format, \ - obs_output_get_name(mux->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[mp4 muxer: '%s'] " format, obs_output_get_name(mux->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -58,8 +57,7 @@ static inline size_t write_box_size(struct serializer *s, int64_t start) } /// 4.2 Box header with size and char[4] name -static inline void write_box(struct serializer *s, const size_t size, - const char name[4]) +static inline void write_box(struct serializer *s, const size_t size, const char name[4]) { if (size <= UINT32_MAX) { s_wb32(s, (uint32_t)size); // size @@ -72,8 +70,7 @@ static inline void write_box(struct serializer *s, const size_t size, } /// 4.2 FullBox extended header with u8 version and u24 flags -static inline void write_fullbox(struct serializer *s, const size_t size, - const char name[4], uint8_t version, +static inline void write_fullbox(struct serializer *s, const size_t size, const char name[4], uint8_t version, uint32_t flags) { write_box(s, size, name); @@ -156,8 +153,7 @@ static size_t mp4_write_mvhd(struct mp4_mux *mux) for (size_t i = 0; i < mux->tracks.num; i++) { struct mp4_track *track = &mux->tracks.array[i]; if (track->type == TRACK_VIDEO) { - duration = util_mul_div64(track->duration, 1000, - track->timebase_den); + duration = util_mul_div64(track->duration, 1000, track->timebase_den); break; } } @@ -173,7 +169,7 @@ static size_t mp4_write_mvhd(struct mp4_mux *mux) s_wb32(s, (uint32_t)mux->creation_time); // creation time s_wb32(s, (uint32_t)mux->creation_time); // modification time s_wb32(s, 1000); // timescale - s_wb32(s, (uint32_t)duration); // duration (0 for fragmented) + s_wb32(s, (uint32_t)duration); // duration (0 for fragmented) } s_wb32(s, 0x00010000); // rate, 16.16 fixed float (1 << 16) @@ -206,8 +202,7 @@ static size_t mp4_write_tkhd(struct mp4_mux *mux, struct mp4_track *track) struct serializer *s = mux->serializer; size_t start = serializer_get_pos(s); - uint64_t duration = - util_mul_div64(track->duration, 1000, track->timebase_den); + uint64_t duration = util_mul_div64(track->duration, 1000, track->timebase_den); /* Flags are 0x1 (enabled) | 0x2 (in movie) */ static const uint32_t flags = 0x1 | 0x2; @@ -224,7 +219,7 @@ static size_t mp4_write_tkhd(struct mp4_mux *mux, struct mp4_track *track) s_wb32(s, (uint32_t)mux->creation_time); // modification time s_wb32(s, track->track_id); // track_id s_wb32(s, 0); // reserved - s_wb32(s, (uint32_t)duration); // duration in movie timescale + s_wb32(s, (uint32_t)duration); // duration in movie timescale } s_wb32(s, 0); // reserved @@ -265,8 +260,7 @@ static size_t mp4_write_mdhd(struct mp4_mux *mux, struct mp4_track *track) if (track->type == TRACK_VIDEO) { /* Update to track timescale */ - duration = util_mul_div64(duration, track->timescale, - track->timebase_den); + duration = util_mul_div64(duration, track->timescale, track->timebase_den); } /* use 64-bit duration if necessary */ @@ -424,9 +418,7 @@ static size_t mp4_write_avcC(struct mp4_mux *mux, obs_encoder_t *enc) uint8_t *header; size_t size; - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = true}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true}; if (!obs_encoder_get_extra_data(enc, &header, &size)) return 0; @@ -450,9 +442,7 @@ static size_t mp4_write_hvcC(struct mp4_mux *mux, obs_encoder_t *enc) uint8_t *header; size_t size; - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = true}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true}; if (!obs_encoder_get_extra_data(enc, &header, &size)) return 0; @@ -476,9 +466,7 @@ static size_t mp4_write_av1C(struct mp4_mux *mux, obs_encoder_t *enc) uint8_t *header; size_t size; - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = true}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true}; if (!obs_encoder_get_extra_data(enc, &header, &size)) return 0; @@ -529,8 +517,7 @@ static size_t mp4_write_pasp(struct mp4_mux *mux) } /// 12.1.3 Visual Sample Entry -static inline void mp4_write_visual_sample_entry(struct mp4_mux *mux, - obs_encoder_t *enc) +static inline void mp4_write_visual_sample_entry(struct mp4_mux *mux, obs_encoder_t *enc) { struct serializer *s = mux->serializer; @@ -587,8 +574,7 @@ static size_t mp4_write_clli(struct mp4_mux *mux, obs_encoder_t *enc) const struct video_output_info *info = video_output_get_info(video); /* Only write box for HDR video */ - if (info->colorspace != VIDEO_CS_2100_PQ && - info->colorspace != VIDEO_CS_2100_HLG) + if (info->colorspace != VIDEO_CS_2100_PQ && info->colorspace != VIDEO_CS_2100_HLG) return 0; write_box(s, 12, "clli"); @@ -610,8 +596,7 @@ static size_t mp4_write_mdcv(struct mp4_mux *mux, obs_encoder_t *enc) const struct video_output_info *info = video_output_get_info(video); // Only write atom for HDR video - if (info->colorspace != VIDEO_CS_2100_PQ && - info->colorspace != VIDEO_CS_2100_HLG) + if (info->colorspace != VIDEO_CS_2100_PQ && info->colorspace != VIDEO_CS_2100_HLG) return 0; write_box(s, 32, "mdcv"); @@ -736,16 +721,14 @@ static size_t mp4_write_esds(struct mp4_mux *mux, struct mp4_track *track) /* Encoder extradata will be used as DecoderSpecificInfo */ uint8_t *extradata; size_t extradata_size; - if (!obs_encoder_get_extra_data(track->encoder, &extradata, - &extradata_size)) { + if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size)) { extradata_size = 0; } /// ISO/IEC 14496-1 // ES_Descriptor - size_t decoder_specific_info_len = extradata_size ? extradata_size + 5 - : 0; + size_t decoder_specific_info_len = extradata_size ? extradata_size + 5 : 0; put_descr(s, 0x03, 3 + 5 + 13 + decoder_specific_info_len + 5 + 1); s_wb16(s, track->track_id); @@ -786,9 +769,7 @@ static size_t mp4_write_esds(struct mp4_mux *mux, struct mp4_track *track) } /// 12.2.3 Audio Sample Entry -static inline void mp4_write_audio_sample_entry(struct mp4_mux *mux, - struct mp4_track *track, - uint8_t version) +static inline void mp4_write_audio_sample_entry(struct mp4_mux *mux, struct mp4_track *track, uint8_t version) { struct serializer *s = mux->serializer; @@ -868,8 +849,7 @@ static size_t mp4_write_chnl(struct mp4_mux *mux, struct mp4_track *track) } /// ISO/IEC 14496-14 5.6 MP4AudioSampleEntry -static size_t mp4_write_mp4a(struct mp4_mux *mux, struct mp4_track *track, - uint8_t version) +static size_t mp4_write_mp4a(struct mp4_mux *mux, struct mp4_track *track, uint8_t version) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -897,8 +877,7 @@ static size_t mp4_write_dfLa(struct mp4_mux *mux, struct mp4_track *track) uint8_t *extradata; size_t extradata_size; - if (!obs_encoder_get_extra_data(track->encoder, &extradata, - &extradata_size)) + if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size)) return 0; write_fullbox(s, 0, "dfLa", 0, 0); @@ -916,8 +895,7 @@ static size_t mp4_write_dfLa(struct mp4_mux *mux, struct mp4_track *track) } /// Encapsulation of FLAC in ISO Base Media File Format 3.3.1 FLACSampleEntry -static size_t mp4_write_fLaC(struct mp4_mux *mux, struct mp4_track *track, - uint8_t version) +static size_t mp4_write_fLaC(struct mp4_mux *mux, struct mp4_track *track, uint8_t version) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -936,8 +914,7 @@ static size_t mp4_write_fLaC(struct mp4_mux *mux, struct mp4_track *track, } /// Apple Lossless Format "Magic Cookie" Description - MP4/M4A File -static size_t mp4_write_alac(struct mp4_mux *mux, struct mp4_track *track, - uint8_t version) +static size_t mp4_write_alac(struct mp4_mux *mux, struct mp4_track *track, uint8_t version) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -945,8 +922,7 @@ static size_t mp4_write_alac(struct mp4_mux *mux, struct mp4_track *track, uint8_t *extradata; size_t extradata_size; - if (!obs_encoder_get_extra_data(track->encoder, &extradata, - &extradata_size)) + if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size)) return 0; write_box(s, 0, "alac"); @@ -984,8 +960,7 @@ static size_t mp4_write_pcmc(struct mp4_mux *mux, struct mp4_track *track) } /// ISO/IEC 23003-5 5.1 PCM configuration -static size_t mp4_write_xpcm(struct mp4_mux *mux, struct mp4_track *track, - uint8_t version) +static size_t mp4_write_xpcm(struct mp4_mux *mux, struct mp4_track *track, uint8_t version) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1039,8 +1014,7 @@ static size_t mp4_write_dOps(struct mp4_mux *mux, struct mp4_track *track) uint8_t *extradata; size_t extradata_size; - if (!obs_encoder_get_extra_data(track->encoder, &extradata, - &extradata_size)) + if (!obs_encoder_get_extra_data(track->encoder, &extradata, &extradata_size)) return 0; write_box(s, 0, "dOps"); @@ -1063,8 +1037,7 @@ static size_t mp4_write_dOps(struct mp4_mux *mux, struct mp4_track *track) } /// Encapsulation of Opus in ISO Base Media File Format 4.3.1 Sample entry format -static size_t mp4_write_Opus(struct mp4_mux *mux, struct mp4_track *track, - uint8_t version) +static size_t mp4_write_Opus(struct mp4_mux *mux, struct mp4_track *track, uint8_t version) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1118,8 +1091,7 @@ static size_t mp4_write_stsd(struct mp4_mux *mux, struct mp4_track *track) mp4_write_fLaC(mux, track, version); else if (track->codec == CODEC_ALAC) mp4_write_alac(mux, track, version); - else if (track->codec == CODEC_PCM_I16 || - track->codec == CODEC_PCM_I24 || + else if (track->codec == CODEC_PCM_I16 || track->codec == CODEC_PCM_I24 || track->codec == CODEC_PCM_F32) mp4_write_xpcm(mux, track, version); } else if (track->type == TRACK_CHAPTERS) { @@ -1130,8 +1102,7 @@ static size_t mp4_write_stsd(struct mp4_mux *mux, struct mp4_track *track) } /// 8.6.1.2 Decoding Time to Sample Box -static size_t mp4_write_stts(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_stts(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; @@ -1152,8 +1123,7 @@ static size_t mp4_write_stts(struct mp4_mux *mux, struct mp4_track *track, for (size_t idx = 0; idx < num; idx++) { struct sample_delta *smp = &arr[idx]; - uint64_t delta = util_mul_div64(smp->delta, track->timescale, - track->timebase_den); + uint64_t delta = util_mul_div64(smp->delta, track->timescale, track->timebase_den); s_wb32(s, smp->count); // sample_count s_wb32(s, (uint32_t)delta); // sample_delta @@ -1198,8 +1168,7 @@ static size_t mp4_write_ctts(struct mp4_mux *mux, struct mp4_track *track) s_wb32(s, num); // entry_count for (size_t idx = 0; idx < num; idx++) { - int64_t offset = (int64_t)track->offsets.array[idx].offset * - (int64_t)track->timescale / + int64_t offset = (int64_t)track->offsets.array[idx].offset * (int64_t)track->timescale / (int64_t)track->timebase_den; s_wb32(s, track->offsets.array[idx].count); // sample_count @@ -1210,8 +1179,7 @@ static size_t mp4_write_ctts(struct mp4_mux *mux, struct mp4_track *track) } /// 8.7.4 Sample To Chunk Box -static size_t mp4_write_stsc(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_stsc(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; @@ -1235,9 +1203,7 @@ static size_t mp4_write_stsc(struct mp4_mux *mux, struct mp4_track *track, for (size_t idx = 0; idx < arr_num; idx++) { struct chunk *chk = &arr[idx]; - if (!chunk_runs.num || - chunk_runs.array[chunk_runs.num - 1].samples != - chk->samples) { + if (!chunk_runs.num || chunk_runs.array[chunk_runs.num - 1].samples != chk->samples) { struct chunk_run *cr = da_push_back_new(chunk_runs); cr->samples = chk->samples; cr->first = (uint32_t)idx + 1; // ISO-BMFF is 1-indexed @@ -1265,8 +1231,7 @@ static size_t mp4_write_stsc(struct mp4_mux *mux, struct mp4_track *track, } /// 8.7.3 Sample Size Boxes -static size_t mp4_write_stsz(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_stsz(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; @@ -1308,8 +1273,7 @@ static size_t mp4_write_stsz(struct mp4_mux *mux, struct mp4_track *track, } /// 8.7.5 Chunk Offset Box -static size_t mp4_write_stco(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_stco(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; @@ -1386,8 +1350,7 @@ static size_t mp4_write_sbgp_aac(struct mp4_mux *mux, struct mp4_track *track) return write_box_size(s, start); } -static size_t mp4_write_sbgp_sbgp_opus(struct mp4_mux *mux, - struct mp4_track *track) +static size_t mp4_write_sbgp_sbgp_opus(struct mp4_mux *mux, struct mp4_track *track) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1405,11 +1368,8 @@ static size_t mp4_write_sbgp_sbgp_opus(struct mp4_mux *mux, uint16_t preroll_count = 0; int64_t preroll_remaining = opus_preroll; - for (size_t i = 0; i < track->deltas.num && preroll_remaining > 0; - i++) { - for (uint32_t j = 0; - j < track->deltas.array[i].count && preroll_remaining > 0; - j++) { + for (size_t i = 0; i < track->deltas.num && preroll_remaining > 0; i++) { + for (uint32_t j = 0; j < track->deltas.array[i].count && preroll_remaining > 0; j++) { preroll_remaining -= track->deltas.array[i].delta; preroll_count++; } @@ -1435,14 +1395,13 @@ static size_t mp4_write_sbgp_sbgp_opus(struct mp4_mux *mux, s_wb32(s, 0); // group_description_index // entry 1 s_wb32(s, (uint32_t)track->samples - preroll_count); // sample_count - s_wb32(s, 1); // group_description_index + s_wb32(s, 1); // group_description_index return size_sgpd + write_box_size(s, start); } /// 8.5.1 Sample Table Box -static size_t mp4_write_stbl(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_stbl(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; @@ -1532,8 +1491,7 @@ static size_t mp4_write_dinf(struct mp4_mux *mux) } /// 8.4.4 Media Information Box -static size_t mp4_write_minf(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_minf(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1558,8 +1516,7 @@ static size_t mp4_write_minf(struct mp4_mux *mux, struct mp4_track *track, } /// 8.4.1 Media Box -static size_t mp4_write_mdia(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_mdia(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1579,8 +1536,7 @@ static size_t mp4_write_mdia(struct mp4_mux *mux, struct mp4_track *track, } /// (QTFF/Apple) User data atom -static size_t mp4_write_udta_atom(struct mp4_mux *mux, const char tag[4], - const char *val) +static size_t mp4_write_udta_atom(struct mp4_mux *mux, const char tag[4], const char *val) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1613,8 +1569,7 @@ static size_t mp4_write_track_udta(struct mp4_mux *mux, struct mp4_track *track) obs_data_t *settings = obs_encoder_get_settings(track->encoder); if (settings) { - const char *json = - obs_data_get_json_with_defaults(settings); + const char *json = obs_data_get_json_with_defaults(settings); mp4_write_udta_atom(mux, "json", json); obs_data_release(settings); } @@ -1633,12 +1588,10 @@ static size_t mp4_write_elst(struct mp4_mux *mux, struct mp4_track *track) s_wb32(s, 1); // entry count - uint64_t duration = - util_mul_div64(track->duration, 1000, track->timebase_den); + uint64_t duration = util_mul_div64(track->duration, 1000, track->timebase_den); uint64_t delay = 0; - if (track->type == TRACK_VIDEO && - !(mux->flags & MP4_USE_NEGATIVE_CTS)) { + if (track->type == TRACK_VIDEO && !(mux->flags & MP4_USE_NEGATIVE_CTS)) { /* Compensate for frame-reordering delay (for example, when * using b-frames). */ int64_t dts_offset = 0; @@ -1655,11 +1608,9 @@ static size_t mp4_write_elst(struct mp4_mux *mux, struct mp4_track *track) dts_offset = pkt.pts - pkt.dts; } - delay = util_mul_div64(dts_offset, track->timescale, - track->timebase_den); + delay = util_mul_div64(dts_offset, track->timescale, track->timebase_den); } else if (track->type == TRACK_AUDIO && track->first_pts < 0) { - delay = util_mul_div64(llabs(track->first_pts), - track->timescale, track->timebase_den); + delay = util_mul_div64(llabs(track->first_pts), track->timescale, track->timebase_den); /* Subtract priming delay from total duration */ duration -= util_mul_div64(delay, 1000, track->timescale); } @@ -1712,8 +1663,7 @@ static size_t mp4_write_tref(struct mp4_mux *mux) } /// 8.3.1 Track Box -static size_t mp4_write_trak(struct mp4_mux *mux, struct mp4_track *track, - bool fragmented) +static size_t mp4_write_trak(struct mp4_mux *mux, struct mp4_track *track, bool fragmented) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1811,8 +1761,7 @@ static size_t mp4_write_data_atom(struct mp4_mux *mux, const char *data) } /// (QTFF/Apple) Metadata item atom -static size_t mp4_write_ilst_item_atom(struct mp4_mux *mux, const char name[4], - const char *value) +static size_t mp4_write_ilst_item_atom(struct mp4_mux *mux, const char name[4], const char *value) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -1900,8 +1849,7 @@ static size_t mp4_write_mdta_keys(struct mp4_mux *mux, obs_data_t *meta) } /// (QTFF/Apple) Metadata item atom, but name is an index instead -static inline void write_key_entry(struct mp4_mux *mux, obs_data_item_t *item, - uint32_t idx) +static inline void write_key_entry(struct mp4_mux *mux, obs_data_item_t *item, uint32_t idx) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -2038,14 +1986,12 @@ static size_t mp4_write_mfhd(struct mp4_mux *mux) } /// 8.8.7 Track Fragment Header Box -static size_t mp4_write_tfhd(struct mp4_mux *mux, struct mp4_track *track, - size_t moof_start) +static size_t mp4_write_tfhd(struct mp4_mux *mux, struct mp4_track *track, size_t moof_start) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); - uint32_t flags = BASE_DATA_OFFSET_PRESENT | - DEFAULT_SAMPLE_FLAGS_PRESENT; + uint32_t flags = BASE_DATA_OFFSET_PRESENT | DEFAULT_SAMPLE_FLAGS_PRESENT; /* Add default size/duration if all samples match. */ bool durations_match = true; @@ -2061,10 +2007,8 @@ static size_t mp4_write_tfhd(struct mp4_mux *mux, struct mp4_track *track, sample_size = track->fragment_samples.array[0].size; for (size_t idx = 1; idx < track->fragment_samples.num; idx++) { - uint32_t frag_duration = - track->fragment_samples.array[idx].duration; - uint32_t frag_size = - track->fragment_samples.array[idx].size; + uint32_t frag_duration = track->fragment_samples.array[idx].duration; + uint32_t frag_size = track->fragment_samples.array[idx].size; durations_match = frag_duration == duration; sizes_match = frag_size == sample_size; @@ -2085,9 +2029,7 @@ static size_t mp4_write_tfhd(struct mp4_mux *mux, struct mp4_track *track, if (durations_match) { if (track->type == TRACK_VIDEO) { /* Convert duration to track timescale */ - duration = (uint32_t)util_mul_div64( - duration, track->timescale, - track->timebase_den); + duration = (uint32_t)util_mul_div64(duration, track->timescale, track->timebase_den); } s_wb32(s, duration); @@ -2119,9 +2061,7 @@ static size_t mp4_write_tfdt(struct mp4_mux *mux, struct mp4_track *track) if (track->type == TRACK_VIDEO) { /* Convert to track timescale */ - duration_written = util_mul_div64(duration_written, - track->timescale, - track->timebase_den); + duration_written = util_mul_div64(duration_written, track->timescale, track->timebase_den); } s_wb64(s, duration_written); // baseMediaDecodeTime @@ -2130,8 +2070,8 @@ static size_t mp4_write_tfdt(struct mp4_mux *mux, struct mp4_track *track) } /// 8.8.8 Track Fragment Run Box -static size_t mp4_write_trun(struct mp4_mux *mux, struct mp4_track *track, - uint32_t moof_size, uint64_t *samples_mdat_offset) +static size_t mp4_write_trun(struct mp4_mux *mux, struct mp4_track *track, uint32_t moof_size, + uint64_t *samples_mdat_offset) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -2176,16 +2116,14 @@ static size_t mp4_write_trun(struct mp4_mux *mux, struct mp4_track *track, s_wb32(s, SAMPLE_FLAG_DEPENDS_NO); // first_sample_flags for (size_t idx = 0; idx < sample_count; idx++) { - struct fragment_sample *smp = - &track->fragment_samples.array[idx]; + struct fragment_sample *smp = &track->fragment_samples.array[idx]; s_wb32(s, smp->size); // sample_size if (track->type == TRACK_VIDEO) { // sample_composition_time_offset - int64_t offset = (int64_t)smp->offset * - (int64_t)track->timescale / - (int64_t)track->timebase_den; + int64_t offset = + (int64_t)smp->offset * (int64_t)track->timescale / (int64_t)track->timebase_den; s_wb32(s, (uint32_t)offset); } @@ -2196,8 +2134,7 @@ static size_t mp4_write_trun(struct mp4_mux *mux, struct mp4_track *track, } /// 8.8.6 Track Fragment Box -static size_t mp4_write_traf(struct mp4_mux *mux, struct mp4_track *track, - int64_t moof_start, uint32_t moof_size, +static size_t mp4_write_traf(struct mp4_mux *mux, struct mp4_track *track, int64_t moof_start, uint32_t moof_size, uint64_t *samples_mdat_offset) { struct serializer *s = mux->serializer; @@ -2218,8 +2155,7 @@ static size_t mp4_write_traf(struct mp4_mux *mux, struct mp4_track *track, } /// 8.8.4 Movie Fragment Box -static size_t mp4_write_moof(struct mp4_mux *mux, uint32_t moof_size, - int64_t moof_start) +static size_t mp4_write_moof(struct mp4_mux *mux, uint32_t moof_size, int64_t moof_start) { struct serializer *s = mux->serializer; int64_t start = serializer_get_pos(s); @@ -2238,8 +2174,7 @@ static size_t mp4_write_moof(struct mp4_mux *mux, uint32_t moof_size, if (!track->fragment_samples.num) continue; - mp4_write_traf(mux, track, moof_start, moof_size, - &samples_mdat_offset); + mp4_write_traf(mux, track, moof_start, moof_size, &samples_mdat_offset); } return write_box_size(s, start); @@ -2248,8 +2183,7 @@ static size_t mp4_write_moof(struct mp4_mux *mux, uint32_t moof_size, /* ========================================================================== */ /* Chapter packets */ -static void mp4_create_chapter_pkt(struct encoder_packet *pkt, int64_t dts_usec, - const char *name) +static void mp4_create_chapter_pkt(struct encoder_packet *pkt, int64_t dts_usec, const char *name) { int64_t dts = dts_usec / 1000; // chapter track uses a ms timebase @@ -2297,8 +2231,7 @@ static inline uint64_t get_longest_track_duration(struct mp4_mux *mux) for (size_t i = 0; i < mux->tracks.num; i++) { struct mp4_track *track = &mux->tracks.array[i]; - uint64_t track_dur = util_mul_div64(track->duration, 1000, - track->timebase_den); + uint64_t track_dur = util_mul_div64(track->duration, 1000, track->timebase_den); if (track_dur > dur) dur = track_dur; @@ -2307,8 +2240,7 @@ static inline uint64_t get_longest_track_duration(struct mp4_mux *mux) return dur; } -static void process_packets(struct mp4_mux *mux, struct mp4_track *track, - uint64_t *mdat_size) +static void process_packets(struct mp4_mux *mux, struct mp4_track *track, uint64_t *mdat_size) { size_t count = track->packets.size / sizeof(struct encoder_packet); @@ -2320,12 +2252,10 @@ static void process_packets(struct mp4_mux *mux, struct mp4_track *track, for (size_t i = 0; i < count - 1; i++) { struct encoder_packet *pkt = get_pkt_at(&track->packets, i); - if (mux->next_frag_pts && - packet_pts_usec(pkt) >= mux->next_frag_pts) + if (mux->next_frag_pts && packet_pts_usec(pkt) >= mux->next_frag_pts) break; - struct encoder_packet *next = - get_pkt_at(&track->packets, i + 1); + struct encoder_packet *next = get_pkt_at(&track->packets, i + 1); /* Duration is just distance between current and next DTS. */ uint32_t duration = (uint32_t)(next->dts - pkt->dts); @@ -2334,8 +2264,7 @@ static void process_packets(struct mp4_mux *mux, struct mp4_track *track, int32_t offset = (int32_t)(pkt->pts - pkt->dts); /* When using negative CTS, subtract DTS-PTS offset. */ - if (track->type == TRACK_VIDEO && - mux->flags & MP4_USE_NEGATIVE_CTS) { + if (track->type == TRACK_VIDEO && mux->flags & MP4_USE_NEGATIVE_CTS) { if (!track->offsets.num) track->dts_offset = offset; @@ -2343,8 +2272,7 @@ static void process_packets(struct mp4_mux *mux, struct mp4_track *track, } /* Create temporary sample information for moof */ - struct fragment_sample *smp = - da_push_back_new(track->fragment_samples); + struct fragment_sample *smp = da_push_back_new(track->fragment_samples); smp->size = size; smp->offset = offset; smp->duration = duration; @@ -2367,16 +2295,12 @@ static void process_packets(struct mp4_mux *mux, struct mp4_track *track, /* If delta (duration) matche sprevious, increment counter, * otherwise create a new entry. */ - if (track->deltas.num == 0 || - track->deltas.array[track->deltas.num - 1].delta != - duration) { - struct sample_delta *new = - da_push_back_new(track->deltas); + if (track->deltas.num == 0 || track->deltas.array[track->deltas.num - 1].delta != duration) { + struct sample_delta *new = da_push_back_new(track->deltas); new->delta = duration; new->count = sample_count; } else { - track->deltas.array[track->deltas.num - 1].count += - sample_count; + track->deltas.array[track->deltas.num - 1].count += sample_count; } if (!track->sample_size) @@ -2394,11 +2318,8 @@ static void process_packets(struct mp4_mux *mux, struct mp4_track *track, /* If dts-pts offset matche sprevious, increment counter, * otherwise create a new entry. */ - if (track->offsets.num == 0 || - track->offsets.array[track->offsets.num - 1].offset != - offset) { - struct sample_offset *new = - da_push_back_new(track->offsets); + if (track->offsets.num == 0 || track->offsets.array[track->offsets.num - 1].offset != offset) { + struct sample_offset *new = da_push_back_new(track->offsets); new->offset = offset; new->count = 1; } else { @@ -2422,8 +2343,7 @@ static void write_packets(struct mp4_mux *mux, struct mp4_track *track) for (size_t i = 0; i < track->fragment_samples.num; i++) { struct encoder_packet pkt; - deque_pop_front(&track->packets, &pkt, - sizeof(struct encoder_packet)); + deque_pop_front(&track->packets, &pkt, sizeof(struct encoder_packet)); s_write(s, pkt.data, pkt.size); obs_encoder_packet_release(&pkt); } @@ -2479,8 +2399,7 @@ static void mp4_flush_fragment(struct mp4_mux *mux) uint64_t duration = get_longest_track_duration(mux); struct encoder_packet pkt; mp4_create_chapter_pkt(&pkt, (int64_t)duration * 1000, "Dummy"); - deque_push_back(&mux->chapter_track->packets, &pkt, - sizeof(struct encoder_packet)); + deque_push_back(&mux->chapter_track->packets, &pkt, sizeof(struct encoder_packet)); process_packets(mux, mux->chapter_track, &mdat_size); } @@ -2526,8 +2445,7 @@ static void mp4_flush_fragment(struct mp4_mux *mux) /* ========================================================================== */ /* Track object functions */ -static inline void track_insert_packet(struct mp4_track *track, - struct encoder_packet *pkt) +static inline void track_insert_packet(struct mp4_track *track, struct encoder_packet *pkt) { int64_t pts_usec = packet_pts_usec(pkt); if (pts_usec > track->last_pts_usec) @@ -2589,9 +2507,7 @@ static inline void add_track(struct mp4_mux *mux, obs_encoder_t *enc) { struct mp4_track *track = da_push_back_new(mux->tracks); - track->type = obs_encoder_get_type(enc) == OBS_ENCODER_VIDEO - ? TRACK_VIDEO - : TRACK_AUDIO; + track->type = obs_encoder_get_type(enc) == OBS_ENCODER_VIDEO ? TRACK_VIDEO : TRACK_AUDIO; track->encoder = obs_encoder_get_ref(enc); track->codec = get_codec(enc); track->track_id = ++mux->track_ctr; @@ -2599,8 +2515,7 @@ static inline void add_track(struct mp4_mux *mux, obs_encoder_t *enc) /* Set timebase/timescale */ if (track->type == TRACK_VIDEO) { video_t *video = obs_encoder_video(enc); - const struct video_output_info *info = - video_output_get_info(video); + const struct video_output_info *info = video_output_get_info(video); track->timebase_num = info->fps_den; track->timebase_den = info->fps_num; @@ -2668,9 +2583,7 @@ static inline void free_track(struct mp4_track *track) /* ===========================================================================*/ /* API */ -struct mp4_mux *mp4_mux_create(obs_output_t *output, - struct serializer *serializer, - enum mp4_mux_flags flags) +struct mp4_mux *mp4_mux_create(obs_output_t *output, struct serializer *serializer, enum mp4_mux_flags flags) { struct mp4_mux *mux = bzalloc(sizeof(struct mp4_mux)); @@ -2718,8 +2631,7 @@ bool mp4_mux_submit_packet(struct mp4_mux *mux, struct encoder_packet *pkt) for (size_t i = 0; i < mux->tracks.num; i++) { struct mp4_track *tmp = &mux->tracks.array[i]; - fragment_ready = fragment_ready && - tmp->last_pts_usec >= mux->next_frag_pts; + fragment_ready = fragment_ready && tmp->last_pts_usec >= mux->next_frag_pts; if (tmp->encoder == pkt->encoder) track = tmp; @@ -2728,8 +2640,7 @@ bool mp4_mux_submit_packet(struct mp4_mux *mux, struct encoder_packet *pkt) if (!track) { warn("Could not find track for packet of type %s with " "track id %zu!", - type == OBS_ENCODER_VIDEO ? "video" : "audio", - pkt->track_idx); + type == OBS_ENCODER_VIDEO ? "video" : "audio", pkt->track_idx); return false; } @@ -2759,8 +2670,7 @@ bool mp4_mux_submit_packet(struct mp4_mux *mux, struct encoder_packet *pkt) return true; } -bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, - const char *name) +bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, const char *name) { if (dts_usec < 0) return false; @@ -2770,8 +2680,7 @@ bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, /* To work correctly there needs to be a chapter at PTS 0, * create that here if necessary. */ if (dts_usec > 0 && mux->chapter_track->packets.size == 0) { - mp4_mux_add_chapter(mux, 0, - obs_module_text("MP4Output.StartChapter")); + mp4_mux_add_chapter(mux, 0, obs_module_text("MP4Output.StartChapter")); } /* Create packets that will be muxed on final flush */ @@ -2828,8 +2737,7 @@ bool mp4_mux_finalise(struct mp4_mux *mux) mp4_write_ftyp(mux, false); size_t data_size = data_end - mux->placeholder_offset; - serializer_seek(s, (int64_t)mux->placeholder_offset, - SERIALIZE_SEEK_START); + serializer_seek(s, (int64_t)mux->placeholder_offset, SERIALIZE_SEEK_START); /* If data is more than 4 GiB the mdat header becomes 16 bytes, hence * why we create a 16-byte placeholder "free" box at the start. */ diff --git a/plugins/obs-outputs/mp4-mux.h b/plugins/obs-outputs/mp4-mux.h index e791b5a08..ccb7b7f4b 100644 --- a/plugins/obs-outputs/mp4-mux.h +++ b/plugins/obs-outputs/mp4-mux.h @@ -33,11 +33,8 @@ enum mp4_mux_flags { MP4_USE_NEGATIVE_CTS = 1 << 3, }; -struct mp4_mux *mp4_mux_create(obs_output_t *output, - struct serializer *serializer, - enum mp4_mux_flags flags); +struct mp4_mux *mp4_mux_create(obs_output_t *output, struct serializer *serializer, enum mp4_mux_flags flags); void mp4_mux_destroy(struct mp4_mux *mux); bool mp4_mux_submit_packet(struct mp4_mux *mux, struct encoder_packet *pkt); -bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, - const char *name); +bool mp4_mux_add_chapter(struct mp4_mux *mux, int64_t dts_usec, const char *name); bool mp4_mux_finalise(struct mp4_mux *mux); diff --git a/plugins/obs-outputs/mp4-output.c b/plugins/obs-outputs/mp4-output.c index 1ca777f88..130ca01ba 100644 --- a/plugins/obs-outputs/mp4-output.c +++ b/plugins/obs-outputs/mp4-output.c @@ -27,9 +27,8 @@ #include -#define do_log(level, format, ...) \ - blog(level, "[mp4 output: '%s'] " format, \ - obs_output_get_name(out->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[mp4 output: '%s'] " format, obs_output_get_name(out->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -108,8 +107,7 @@ static inline void ts_offset_clear(struct mp4_output *out) } } -static inline void ts_offset_update(struct mp4_output *out, - struct encoder_packet *packet) +static inline void ts_offset_update(struct mp4_output *out, struct encoder_packet *packet) { int64_t *offset; int64_t ts; @@ -160,9 +158,7 @@ static void mp4_add_chapter_proc(void *data, calldata_t *cd) if (name.len == 0) { /* Generate name if none provided. */ - dstr_catf(&name, "%s %zu", - obs_module_text("MP4Output.UnnamedChapter"), - out->chapters.num + 1); + dstr_catf(&name, "%s %zu", obs_module_text("MP4Output.UnnamedChapter"), out->chapters.num + 1); } int64_t totalRecordSeconds = out->last_dts_usec / 1000 / 1000; @@ -171,8 +167,7 @@ static void mp4_add_chapter_proc(void *data, calldata_t *cd) int minutes = totalMinutes % 60; int hours = totalMinutes / 60; - info("Adding chapter \"%s\" at %02d:%02d:%02d", name.array, hours, - minutes, seconds); + info("Adding chapter \"%s\" at %02d:%02d:%02d", name.array, hours, minutes, seconds); pthread_mutex_lock(&out->mutex); struct chapter *chap = da_push_back_new(out->chapters); @@ -202,10 +197,8 @@ static void *mp4_output_create(obs_data_t *settings, obs_output_t *output) signal_handler_add(sh, "void file_changed(string next_file)"); proc_handler_t *ph = obs_output_get_proc_handler(output); - proc_handler_add(ph, "void split_file(out bool split_file_enabled)", - split_file_proc, out); - proc_handler_add(ph, "void add_chapter(string chapter_name)", - mp4_add_chapter_proc, out); + proc_handler_add(ph, "void split_file(out bool split_file_enabled)", split_file_proc, out); + proc_handler_add(ph, "void add_chapter(string chapter_name)", mp4_add_chapter_proc, out); UNUSED_PARAMETER(settings); return out; @@ -237,8 +230,7 @@ static int parse_custom_options(const char *opts_str) } else if (strcmp(opt.name, "use_negative_cts") == 0) { apply_flag(&flags, opt.value, MP4_USE_NEGATIVE_CTS); } else { - blog(LOG_WARNING, "Unknown muxer option: %s = %s", - opt.name, opt.value); + blog(LOG_WARNING, "Unknown muxer option: %s = %s", opt.name, opt.value); } } @@ -270,14 +262,12 @@ static bool mp4_output_start(void *data) out->cur_size = 0; /* Allow skipping the remux step for debugging purposes. */ - const char *muxer_settings = - obs_data_get_string(settings, "muxer_settings"); + const char *muxer_settings = obs_data_get_string(settings, "muxer_settings"); out->flags = parse_custom_options(muxer_settings); obs_data_release(settings); - if (!buffered_file_serializer_init_defaults(&out->serializer, - out->path.array)) { + if (!buffered_file_serializer_init_defaults(&out->serializer, out->path.array)) { warn("Unable to open MP4 file '%s'", out->path.array); return false; } @@ -291,8 +281,7 @@ static bool mp4_output_start(void *data) return true; } -static inline bool should_split(struct mp4_output *out, - struct encoder_packet *packet) +static inline bool should_split(struct mp4_output *out, struct encoder_packet *packet) { /* split at video frame on primary track */ if (packet->type != OBS_ENCODER_VIDEO || packet->track_idx > 0) @@ -306,13 +295,11 @@ static inline bool should_split(struct mp4_output *out, return true; /* reached maximum file size */ - if (out->max_size > 0 && - out->cur_size + (int64_t)packet->size >= out->max_size) + if (out->max_size > 0 && out->cur_size + (int64_t)packet->size >= out->max_size) return true; /* reached maximum duration */ - if (out->max_time > 0 && - packet->dts_usec - out->start_time >= out->max_time) + if (out->max_time > 0 && packet->dts_usec - out->start_time >= out->max_time) return true; return false; @@ -345,8 +332,7 @@ static void find_best_filename(struct dstr *path, bool space) } } -static void generate_filename(struct mp4_output *out, struct dstr *dst, - bool overwrite) +static void generate_filename(struct mp4_output *out, struct dstr *dst, bool overwrite) { obs_data_t *settings = obs_output_get_settings(out->output); const char *dir = obs_data_get_string(settings, "directory"); @@ -399,15 +385,13 @@ static bool change_file(struct mp4_output *out, struct encoder_packet *pkt) da_clear(out->chapters); - info("MP4 file split complete. Finalization took %" PRIu64 " ms.", - (os_gettime_ns() - start_time) / 1000000); + info("MP4 file split complete. Finalization took %" PRIu64 " ms.", (os_gettime_ns() - start_time) / 1000000); /* open new file */ generate_filename(out, &out->path, out->allow_overwrite); info("Changing output file to '%s'", out->path.array); - if (!buffered_file_serializer_init_defaults(&out->serializer, - out->path.array)) { + if (!buffered_file_serializer_init_defaults(&out->serializer, out->path.array)) { warn("Unable to open MP4 file '%s'", out->path.array); return false; } @@ -463,8 +447,7 @@ static void mp4_output_actual_stop(struct mp4_output *out, int code) /* Flush/close output file and destroy muxer */ buffered_file_serializer_free(&out->serializer); - obs_queue_task(OBS_TASK_DESTROY, mp4_mux_destroy_task, out->muxer, - false); + obs_queue_task(OBS_TASK_DESTROY, mp4_mux_destroy_task, out->muxer, false); out->muxer = NULL; /* Clear chapter data */ @@ -473,20 +456,17 @@ static void mp4_output_actual_stop(struct mp4_output *out, int code) da_clear(out->chapters); - info("MP4 file output complete. Finalization took %" PRIu64 " ms.", - (os_gettime_ns() - start_time) / 1000000); + info("MP4 file output complete. Finalization took %" PRIu64 " ms.", (os_gettime_ns() - start_time) / 1000000); } -static void push_back_packet(struct mp4_output *out, - struct encoder_packet *packet) +static void push_back_packet(struct mp4_output *out, struct encoder_packet *packet) { struct encoder_packet pkt; obs_encoder_packet_ref(&pkt, packet); da_push_back(out->split_buffer, &pkt); } -static inline bool submit_packet(struct mp4_output *out, - struct encoder_packet *pkt) +static inline bool submit_packet(struct mp4_output *out, struct encoder_packet *pkt) { out->total_bytes += pkt->size; @@ -533,8 +513,7 @@ static void mp4_output_packet(void *data, struct encoder_packet *packet) if (out->split_file_enabled) { if (out->split_buffer.num) { int64_t pts_usec = packet_pts_usec(packet); - struct encoder_packet *first_pkt = - out->split_buffer.array; + struct encoder_packet *first_pkt = out->split_buffer.array; int64_t first_pts_usec = packet_pts_usec(first_pkt); if (pts_usec >= first_pts_usec) { @@ -544,8 +523,7 @@ static void mp4_output_packet(void *data, struct encoder_packet *packet) } if (!change_file(out, first_pkt)) { - mp4_output_actual_stop( - out, OBS_OUTPUT_ERROR); + mp4_output_actual_stop(out, OBS_OUTPUT_ERROR); goto unlock; } out->split_file_ready = true; @@ -558,8 +536,7 @@ static void mp4_output_packet(void *data, struct encoder_packet *packet) if (out->split_file_ready) { for (size_t i = 0; i < out->split_buffer.num; i++) { - struct encoder_packet *pkt = - &out->split_buffer.array[i]; + struct encoder_packet *pkt = &out->split_buffer.array[i]; ts_offset_update(out, pkt); submit_packet(out, pkt); obs_encoder_packet_release(pkt); @@ -592,11 +569,8 @@ static obs_properties_t *mp4_output_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "path", - obs_module_text("MP4Output.FilePath"), - OBS_TEXT_DEFAULT); - obs_properties_add_text(props, "muxer_settings", "muxer_settings", - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "path", obs_module_text("MP4Output.FilePath"), OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "muxer_settings", "muxer_settings", OBS_TEXT_DEFAULT); return props; } @@ -608,8 +582,7 @@ uint64_t mp4_output_total_bytes(void *data) struct obs_output_info mp4_output_info = { .id = "mp4_output", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | - OBS_OUTPUT_MULTI_TRACK_AV | OBS_OUTPUT_CAN_PAUSE, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_MULTI_TRACK_AV | OBS_OUTPUT_CAN_PAUSE, .encoded_video_codecs = "h264;hevc;av1", .encoded_audio_codecs = "aac", .get_name = mp4_output_name, diff --git a/plugins/obs-outputs/net-if.c b/plugins/obs-outputs/net-if.c index 6ffb2679a..43ad31691 100644 --- a/plugins/obs-outputs/net-if.c +++ b/plugins/obs-outputs/net-if.c @@ -21,16 +21,13 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[net if] " format, ##__VA_ARGS__) +#define do_log(level, format, ...) blog(level, "[net if] " format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__) -static inline void netif_saddr_data_push_back(struct netif_saddr_data *sd, - const char *ip, - const char *adapter) +static inline void netif_saddr_data_push_back(struct netif_saddr_data *sd, const char *ip, const char *adapter) { struct netif_saddr_item item; struct dstr full_name = {0}; @@ -47,34 +44,26 @@ static inline void netif_saddr_data_push_back(struct netif_saddr_data *sd, da_push_back(sd->addrs, &item); } -static void netif_convert_to_string(char *dest, - struct sockaddr_storage *byte_address) +static void netif_convert_to_string(char *dest, struct sockaddr_storage *byte_address) { int family = byte_address->ss_family; char temp_char[INET6_ADDRSTRLEN] = {0}; #ifndef _WIN32 if (family == AF_INET) - inet_ntop(family, - &(((struct sockaddr_in *)byte_address)->sin_addr), - temp_char, INET6_ADDRSTRLEN); + inet_ntop(family, &(((struct sockaddr_in *)byte_address)->sin_addr), temp_char, INET6_ADDRSTRLEN); else if (family == AF_INET6) - inet_ntop(family, - &(((struct sockaddr_in6 *)byte_address)->sin6_addr), - temp_char, INET6_ADDRSTRLEN); + inet_ntop(family, &(((struct sockaddr_in6 *)byte_address)->sin6_addr), temp_char, INET6_ADDRSTRLEN); #else if (family == AF_INET) - InetNtopA(family, &(((SOCKADDR_IN *)byte_address)->sin_addr), - temp_char, INET6_ADDRSTRLEN); + InetNtopA(family, &(((SOCKADDR_IN *)byte_address)->sin_addr), temp_char, INET6_ADDRSTRLEN); else if (family == AF_INET6) - InetNtopA(family, &(((SOCKADDR_IN6 *)byte_address)->sin6_addr), - temp_char, INET6_ADDRSTRLEN); + InetNtopA(family, &(((SOCKADDR_IN6 *)byte_address)->sin6_addr), temp_char, INET6_ADDRSTRLEN); #endif strncpy(dest, temp_char, INET6_ADDRSTRLEN); } -static void netif_push(struct sockaddr *copy_source, - struct netif_saddr_data *saddr_d, const char *adapter) +static void netif_push(struct sockaddr *copy_source, struct netif_saddr_data *saddr_d, const char *adapter) { char temp_char[INET6_ADDRSTRLEN] = {0}; struct sockaddr_storage sa = {0}; @@ -109,8 +98,7 @@ bool netif_addr_to_str(struct sockaddr_storage *in, char *addr, int addr_len) return true; } -bool netif_str_to_addr(struct sockaddr_storage *out, int *addr_len, - const char *addr) +bool netif_str_to_addr(struct sockaddr_storage *out, int *addr_len, const char *addr) { bool ipv6; @@ -125,14 +113,12 @@ bool netif_str_to_addr(struct sockaddr_storage *out, int *addr_len, *addr_len = sizeof(*out); #ifdef _WIN32 - int ret = WSAStringToAddressA((LPSTR)addr, out->ss_family, NULL, - (LPSOCKADDR)out, addr_len); + int ret = WSAStringToAddressA((LPSTR)addr, out->ss_family, NULL, (LPSOCKADDR)out, addr_len); if (ret == SOCKET_ERROR) warn("Could not parse address, error code: %d", GetLastError()); return ret != SOCKET_ERROR; #else - *addr_len = ipv6 ? sizeof(struct sockaddr_in6) - : sizeof(struct sockaddr_in); + *addr_len = ipv6 ? sizeof(struct sockaddr_in6) : sizeof(struct sockaddr_in); void *dst = NULL; if (ipv6) @@ -173,14 +159,10 @@ static inline void netif_get_addrs_nix(struct netif_saddr_data *ifaddrs) if ((family == AF_INET) || (family == AF_INET6)) { s = getnameinfo(ifa->ifa_addr, - (family == AF_INET) - ? sizeof(struct sockaddr_in) - : sizeof(struct sockaddr_in6), - host, NI_MAXHOST, NULL, 0, - NI_NUMERICHOST); + (family == AF_INET) ? sizeof(struct sockaddr_in) : sizeof(struct sockaddr_in6), + host, NI_MAXHOST, NULL, 0, NI_NUMERICHOST); if (s != 0) { - warn("getnameinfo() failed: %s", - gai_strerror(s)); + warn("getnameinfo() failed: %s", gai_strerror(s)); continue; } @@ -198,8 +180,7 @@ static inline PIP_ADAPTER_ADDRESSES get_adapters(void) PIP_ADAPTER_ADDRESSES adapter = NULL; unsigned long ret = 0; unsigned long out_buf_len = 16384; - unsigned long flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | - GAA_FLAG_SKIP_DNS_SERVER; + unsigned long flags = GAA_FLAG_SKIP_ANYCAST | GAA_FLAG_SKIP_MULTICAST | GAA_FLAG_SKIP_DNS_SERVER; const int max_tries = 3; int i = 0; @@ -208,8 +189,7 @@ static inline PIP_ADAPTER_ADDRESSES get_adapters(void) if (!adapter) return NULL; - ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapter, - &out_buf_len); + ret = GetAdaptersAddresses(AF_UNSPEC, flags, NULL, adapter, &out_buf_len); if (ret == ERROR_BUFFER_OVERFLOW) { bfree(adapter); adapter = NULL; @@ -225,15 +205,11 @@ static inline PIP_ADAPTER_ADDRESSES get_adapters(void) bfree(adapter); adapter = NULL; - FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_FROM_SYSTEM | + FormatMessageA(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, ret, - MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), - (LPSTR)&msg_buf, 0, NULL); + NULL, ret, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPSTR)&msg_buf, 0, NULL); if (msg_buf) { - warn("Call to GetAdaptersAddresses failed: %s (%d)", - msg_buf, ret); + warn("Call to GetAdaptersAddresses failed: %s (%d)", msg_buf, ret); LocalFree(msg_buf); } } @@ -255,8 +231,7 @@ static inline void netif_get_addrs_win32(struct netif_saddr_data *ifaddrs) for (cur_adap = adapter; !!cur_adap; cur_adap = cur_adap->Next) { char *adap_name = NULL; - if (cur_adap->OperStatus != IfOperStatusUp || - cur_adap->IfType == IF_TYPE_SOFTWARE_LOOPBACK) + if (cur_adap->OperStatus != IfOperStatusUp || cur_adap->IfType == IF_TYPE_SOFTWARE_LOOPBACK) continue; os_wcs_to_utf8_ptr(cur_adap->FriendlyName, 0, &adap_name); @@ -268,8 +243,7 @@ static inline void netif_get_addrs_win32(struct netif_saddr_data *ifaddrs) family = socket_addr.lpSockaddr->sa_family; if (family == AF_INET || family == AF_INET6) - netif_push(socket_addr.lpSockaddr, ifaddrs, - adap_name); + netif_push(socket_addr.lpSockaddr, ifaddrs, adap_name); } bfree(adap_name); diff --git a/plugins/obs-outputs/net-if.h b/plugins/obs-outputs/net-if.h index fe30eb7f2..ff428fcaa 100644 --- a/plugins/obs-outputs/net-if.h +++ b/plugins/obs-outputs/net-if.h @@ -71,9 +71,7 @@ static inline void netif_saddr_data_free(struct netif_saddr_data *data) da_free(data->addrs); } -extern bool netif_str_to_addr(struct sockaddr_storage *out, int *addr_len, - const char *addr); -extern bool netif_addr_to_str(struct sockaddr_storage *in, char *addr, - int addr_len); +extern bool netif_str_to_addr(struct sockaddr_storage *out, int *addr_len, const char *addr); +extern bool netif_addr_to_str(struct sockaddr_storage *in, char *addr, int addr_len); extern void netif_get_addrs(struct netif_saddr_data *ifaddrs); extern void netif_log_saddrs(struct netif_saddr_data *sd); diff --git a/plugins/obs-outputs/null-output.c b/plugins/obs-outputs/null-output.c index cd38fb113..f09c4a55b 100644 --- a/plugins/obs-outputs/null-output.c +++ b/plugins/obs-outputs/null-output.c @@ -76,9 +76,7 @@ static void null_output_stop(void *data, uint64_t ts) struct null_output *context = data; UNUSED_PARAMETER(ts); - context->stop_thread_active = pthread_create(&context->stop_thread, - NULL, stop_thread, - data) == 0; + context->stop_thread_active = pthread_create(&context->stop_thread, NULL, stop_thread, data) == 0; } static void null_output_data(void *data, struct encoder_packet *packet) diff --git a/plugins/obs-outputs/obs-outputs.c b/plugins/obs-outputs/obs-outputs.c index dde358f3e..c3adc5d2f 100644 --- a/plugins/obs-outputs/obs-outputs.c +++ b/plugins/obs-outputs/obs-outputs.c @@ -56,8 +56,7 @@ bool obs_module_load(void) #endif #if defined(_WIN32) && defined(MBEDTLS_THREADING_ALT) - mbedtls_threading_set_alt(mbed_mutex_init, mbed_mutex_free, - mbed_mutex_lock, mbed_mutex_unlock); + mbedtls_threading_set_alt(mbed_mutex_init, mbed_mutex_free, mbed_mutex_lock, mbed_mutex_unlock); #endif obs_register_output(&rtmp_output_info); diff --git a/plugins/obs-outputs/rtmp-av1.c b/plugins/obs-outputs/rtmp-av1.c index 0aca20e06..9fd37a961 100644 --- a/plugins/obs-outputs/rtmp-av1.c +++ b/plugins/obs-outputs/rtmp-av1.c @@ -71,8 +71,7 @@ typedef struct Av1GetBitContext { int size_in_bits_plus8; } Av1GetBitContext; -static inline int init_get_bits_xe(Av1GetBitContext *s, const uint8_t *buffer, - int bit_size) +static inline int init_get_bits_xe(Av1GetBitContext *s, const uint8_t *buffer, int bit_size) { int buffer_size; int ret = 0; @@ -94,14 +93,12 @@ static inline int init_get_bits_xe(Av1GetBitContext *s, const uint8_t *buffer, return ret; } -static inline int init_get_bits(Av1GetBitContext *s, const uint8_t *buffer, - int bit_size) +static inline int init_get_bits(Av1GetBitContext *s, const uint8_t *buffer, int bit_size) { return init_get_bits_xe(s, buffer, bit_size); } -static inline int init_get_bits8(Av1GetBitContext *s, const uint8_t *buffer, - int byte_size) +static inline int init_get_bits8(Av1GetBitContext *s, const uint8_t *buffer, int byte_size) { if (byte_size > INT_MAX / 8 || byte_size < 0) byte_size = -1; @@ -176,8 +173,7 @@ static inline void uvlc(Av1GetBitContext *gb) skip_bits_long(gb, leading_zeros); } -static inline int parse_obu_header(const uint8_t *buf, int buf_size, - int64_t *obu_size, int *start_pos, int *type, +static inline int parse_obu_header(const uint8_t *buf, int buf_size, int64_t *obu_size, int *start_pos, int *type, int *temporal_id, int *spatial_id) { Av1GetBitContext gb; @@ -225,8 +221,7 @@ static inline int get_obu_bit_length(const uint8_t *buf, int size, int type) int v; /* There are no trailing bits on these */ - if (type == AV1_OBU_TILE_GROUP || type == AV1_OBU_TILE_LIST || - type == AV1_OBU_FRAME) { + if (type == AV1_OBU_TILE_GROUP || type == AV1_OBU_TILE_LIST || type == AV1_OBU_FRAME) { if (size > INT_MAX / 8) return -1; else @@ -252,8 +247,7 @@ static inline int get_obu_bit_length(const uint8_t *buf, int size, int type) return size; } -static int parse_color_config(AV1SequenceParameters *seq_params, - Av1GetBitContext *gb) +static int parse_color_config(AV1SequenceParameters *seq_params, Av1GetBitContext *gb) { int twelve_bit = 0; int high_bitdepth = get_bits(gb, 1); @@ -284,8 +278,7 @@ static int parse_color_config(AV1SequenceParameters *seq_params, seq_params->chroma_subsampling_y = 1; seq_params->chroma_sample_position = 0; return 0; - } else if (seq_params->color_primaries == 1 && - seq_params->transfer_characteristics == 13 && + } else if (seq_params->color_primaries == 1 && seq_params->transfer_characteristics == 13 && seq_params->matrix_coefficients == 0) { seq_params->chroma_subsampling_x = 0; seq_params->chroma_subsampling_y = 0; @@ -300,11 +293,9 @@ static int parse_color_config(AV1SequenceParameters *seq_params, seq_params->chroma_subsampling_y = 0; } else { if (twelve_bit) { - seq_params->chroma_subsampling_x = - get_bits(gb, 1); + seq_params->chroma_subsampling_x = get_bits(gb, 1); if (seq_params->chroma_subsampling_x) - seq_params->chroma_subsampling_y = - get_bits(gb, 1); + seq_params->chroma_subsampling_y = get_bits(gb, 1); else seq_params->chroma_subsampling_y = 0; } else { @@ -312,8 +303,7 @@ static int parse_color_config(AV1SequenceParameters *seq_params, seq_params->chroma_subsampling_y = 0; } } - if (seq_params->chroma_subsampling_x && - seq_params->chroma_subsampling_y) + if (seq_params->chroma_subsampling_x && seq_params->chroma_subsampling_y) seq_params->chroma_sample_position = get_bits(gb, 2); } @@ -322,8 +312,7 @@ static int parse_color_config(AV1SequenceParameters *seq_params, return 0; } -static int parse_sequence_header(AV1SequenceParameters *seq_params, - const uint8_t *buf, int size) +static int parse_sequence_header(AV1SequenceParameters *seq_params, const uint8_t *buf, int size) { Av1GetBitContext gb; int reduced_still_picture_header; @@ -349,10 +338,8 @@ static int parse_sequence_header(AV1SequenceParameters *seq_params, seq_params->level = get_bits(&gb, 5); seq_params->tier = 0; } else { - int initial_display_delay_present_flag, - operating_points_cnt_minus_1; - int decoder_model_info_present_flag, - buffer_delay_length_minus_1; + int initial_display_delay_present_flag, operating_points_cnt_minus_1; + int decoder_model_info_present_flag, buffer_delay_length_minus_1; if (get_bits(&gb, 1)) { // timing_info_present_flag skip_bits_long(&gb, 32); // num_units_in_display_tick @@ -386,14 +373,8 @@ static int parse_sequence_header(AV1SequenceParameters *seq_params, if (decoder_model_info_present_flag) { if (get_bits(&gb, 1)) { - skip_bits_long( - &gb, - buffer_delay_length_minus_1 + - 1); - skip_bits_long( - &gb, - buffer_delay_length_minus_1 + - 1); + skip_bits_long(&gb, buffer_delay_length_minus_1 + 1); + skip_bits_long(&gb, buffer_delay_length_minus_1 + 1); skip_bits(&gb, 1); } } @@ -422,9 +403,8 @@ static int parse_sequence_header(AV1SequenceParameters *seq_params, skip_bits(&gb, 7); } - skip_bits( - &gb, - 3); // use_128x128_superblock (1), enable_filter_intra (1), enable_intra_edge_filter (1) + skip_bits(&gb, + 3); // use_128x128_superblock (1), enable_filter_intra (1), enable_intra_edge_filter (1) if (!reduced_still_picture_header) { int enable_order_hint, seq_force_screen_content_tools; @@ -482,9 +462,7 @@ size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size) int64_t obu_size; int start_pos, type, temporal_id, spatial_id; assert(size <= INT_MAX); - int len = parse_obu_header(buf, (int)size, &obu_size, - &start_pos, &type, &temporal_id, - &spatial_id); + int len = parse_obu_header(buf, (int)size, &obu_size, &start_pos, &type, &temporal_id, &spatial_id); if (len < 0) return 0; @@ -495,8 +473,7 @@ size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size) return 0; } assert(obu_size <= INT_MAX); - if (parse_sequence_header(&seq_params, buf + start_pos, - (int)obu_size) < 0) + if (parse_sequence_header(&seq_params, buf + start_pos, (int)obu_size) < 0) return 0; seq = buf; @@ -521,12 +498,9 @@ size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size) uint8_t av1header[4]; av1header[0] = (1 << 7) | 1; // marker and version av1header[1] = (seq_params.profile << 5) | (seq_params.level); - av1header[2] = (seq_params.tier << 7) | (seq_params.bitdepth > 8) << 6 | - (seq_params.bitdepth == 12) << 5 | - (seq_params.monochrome) << 4 | - (seq_params.chroma_subsampling_x) << 3 | - (seq_params.chroma_subsampling_y) << 2 | - (seq_params.chroma_sample_position); + av1header[2] = (seq_params.tier << 7) | (seq_params.bitdepth > 8) << 6 | (seq_params.bitdepth == 12) << 5 | + (seq_params.monochrome) << 4 | (seq_params.chroma_subsampling_x) << 3 | + (seq_params.chroma_subsampling_y) << 2 | (seq_params.chroma_sample_position); av1header[3] = 0; struct array_output_data output; @@ -544,8 +518,7 @@ size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size) return output.bytes.num; } -static void compute_av1_keyframe_priority(const uint8_t *buf, bool *is_keyframe, - int *priority) +static void compute_av1_keyframe_priority(const uint8_t *buf, bool *is_keyframe, int *priority) { /* Skip if the packet already has a priority, e.g., assigned by the * encoder implementation (currently QSV/AMF). */ @@ -580,8 +553,7 @@ static void compute_av1_keyframe_priority(const uint8_t *buf, bool *is_keyframe, } } -static void serialize_av1_data(struct serializer *s, const uint8_t *data, - size_t size, bool *is_keyframe, int *priority) +static void serialize_av1_data(struct serializer *s, const uint8_t *data, size_t size, bool *is_keyframe, int *priority) { uint8_t *buf = (uint8_t *)data; uint8_t *end = (uint8_t *)data + size; @@ -590,8 +562,7 @@ static void serialize_av1_data(struct serializer *s, const uint8_t *data, int64_t obu_size; int start_pos, type, temporal_id, spatial_id; assert(end - buf <= INT_MAX); - int len = parse_obu_header(buf, (int)(end - buf), &obu_size, - &start_pos, &type, &temporal_id, + int len = parse_obu_header(buf, (int)(end - buf), &obu_size, &start_pos, &type, &temporal_id, &spatial_id); if (len < 0) return; @@ -603,8 +574,7 @@ static void serialize_av1_data(struct serializer *s, const uint8_t *data, break; case AV1_OBU_FRAME: case AV1_OBU_FRAME_HEADER: - compute_av1_keyframe_priority(buf + start_pos, - is_keyframe, priority); + compute_av1_keyframe_priority(buf + start_pos, is_keyframe, priority); /* Falls through. */ default: s_write(s, buf, len); @@ -615,8 +585,7 @@ static void serialize_av1_data(struct serializer *s, const uint8_t *data, } } -void obs_parse_av1_packet(struct encoder_packet *av1_packet, - const struct encoder_packet *src) +void obs_parse_av1_packet(struct encoder_packet *av1_packet, const struct encoder_packet *src) { struct array_output_data output; struct serializer s; @@ -626,8 +595,7 @@ void obs_parse_av1_packet(struct encoder_packet *av1_packet, serialize(&s, &ref, sizeof(ref)); *av1_packet = *src; - serialize_av1_data(&s, src->data, src->size, &av1_packet->keyframe, - &av1_packet->priority); + serialize_av1_data(&s, src->data, src->size, &av1_packet->keyframe, &av1_packet->priority); av1_packet->data = output.bytes.array + sizeof(ref); av1_packet->size = output.bytes.num - sizeof(ref); diff --git a/plugins/obs-outputs/rtmp-av1.h b/plugins/obs-outputs/rtmp-av1.h index 76fb7bcbe..a8aedb133 100644 --- a/plugins/obs-outputs/rtmp-av1.h +++ b/plugins/obs-outputs/rtmp-av1.h @@ -22,7 +22,5 @@ struct encoder_packet; -extern void obs_parse_av1_packet(struct encoder_packet *avc_packet, - const struct encoder_packet *src); -extern size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, - size_t size); +extern void obs_parse_av1_packet(struct encoder_packet *avc_packet, const struct encoder_packet *src); +extern size_t obs_parse_av1_header(uint8_t **header, const uint8_t *data, size_t size); diff --git a/plugins/obs-outputs/rtmp-helpers.h b/plugins/obs-outputs/rtmp-helpers.h index 1228f2090..2767cac97 100644 --- a/plugins/obs-outputs/rtmp-helpers.h +++ b/plugins/obs-outputs/rtmp-helpers.h @@ -26,26 +26,22 @@ static inline AVal *flv_str(AVal *out, const char *str) return out; } -static inline void enc_num_val(char **enc, char *end, const char *name, - double val) +static inline void enc_num_val(char **enc, char *end, const char *name, double val) { AVal s; *enc = AMF_EncodeNamedNumber(*enc, end, flv_str(&s, name), val); } -static inline void enc_bool_val(char **enc, char *end, const char *name, - bool val) +static inline void enc_bool_val(char **enc, char *end, const char *name, bool val) { AVal s; *enc = AMF_EncodeNamedBoolean(*enc, end, flv_str(&s, name), val); } -static inline void enc_str_val(char **enc, char *end, const char *name, - const char *val) +static inline void enc_str_val(char **enc, char *end, const char *name, const char *val) { AVal s1, s2; - *enc = AMF_EncodeNamedString(*enc, end, flv_str(&s1, name), - flv_str(&s2, val)); + *enc = AMF_EncodeNamedString(*enc, end, flv_str(&s1, name), flv_str(&s2, val)); } static inline void enc_str(char **enc, char *end, const char *str) diff --git a/plugins/obs-outputs/rtmp-hevc.c b/plugins/obs-outputs/rtmp-hevc.c index 5047bf254..42648a7a6 100644 --- a/plugins/obs-outputs/rtmp-hevc.c +++ b/plugins/obs-outputs/rtmp-hevc.c @@ -25,14 +25,7 @@ /* Adapted from FFmpeg's libavformat/hevc.c for our FLV muxer. */ -enum { - OBS_VPS_INDEX, - OBS_SPS_INDEX, - OBS_PPS_INDEX, - OBS_SEI_PREFIX_INDEX, - OBS_SEI_SUFFIX_INDEX, - OBS_NB_ARRAYS -}; +enum { OBS_VPS_INDEX, OBS_SPS_INDEX, OBS_PPS_INDEX, OBS_SEI_PREFIX_INDEX, OBS_SEI_SUFFIX_INDEX, OBS_NB_ARRAYS }; enum { OBS_HEVC_MAX_VPS_COUNT = 16, @@ -94,8 +87,7 @@ static inline uint32_t rb32(const uint8_t *ptr) static inline void refill_32(HevcGetBitContext *s) { - s->cache = s->cache | (uint64_t)rb32(s->buffer + (s->index >> 3)) - << (32 - s->bits_left); + s->cache = s->cache | (uint64_t)rb32(s->buffer + (s->index >> 3)) << (32 - s->bits_left); s->index += 32; s->bits_left += 32; } @@ -109,8 +101,7 @@ static inline uint64_t get_val(HevcGetBitContext *s, unsigned n) return ret; } -static inline int init_get_bits_xe(HevcGetBitContext *s, const uint8_t *buffer, - int bit_size) +static inline int init_get_bits_xe(HevcGetBitContext *s, const uint8_t *buffer, int bit_size) { int buffer_size; int ret = 0; @@ -136,14 +127,12 @@ static inline int init_get_bits_xe(HevcGetBitContext *s, const uint8_t *buffer, return ret; } -static inline int init_get_bits(HevcGetBitContext *s, const uint8_t *buffer, - int bit_size) +static inline int init_get_bits(HevcGetBitContext *s, const uint8_t *buffer, int bit_size) { return init_get_bits_xe(s, buffer, bit_size); } -static inline int init_get_bits8(HevcGetBitContext *s, const uint8_t *buffer, - int byte_size) +static inline int init_get_bits8(HevcGetBitContext *s, const uint8_t *buffer, int byte_size) { if (byte_size > INT_MAX / 8 || byte_size < 0) byte_size = -1; @@ -239,15 +228,13 @@ static inline bool has_start_code(const uint8_t *data, size_t size) if (size > 3 && data[0] == 0 && data[1] == 0 && data[2] == 1) return true; - if (size > 4 && data[0] == 0 && data[1] == 0 && data[2] == 0 && - data[3] == 1) + if (size > 4 && data[0] == 0 && data[1] == 0 && data[2] == 0 && data[3] == 1) return true; return false; } -uint8_t *ff_nal_unit_extract_rbsp(uint8_t *dst, const uint8_t *src, int src_len, - uint32_t *dst_len, int header_len) +uint8_t *ff_nal_unit_extract_rbsp(uint8_t *dst, const uint8_t *src, int src_len, uint32_t *dst_len, int header_len) { int i, len; @@ -273,8 +260,7 @@ uint8_t *ff_nal_unit_extract_rbsp(uint8_t *dst, const uint8_t *src, int src_len, return dst; } -static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, - uint8_t nal_type, int ps_array_completeness, +static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, uint8_t nal_type, int ps_array_completeness, HVCCNALUnitArray *array) { s_wb16(&array->nalUnit, nal_size); @@ -282,8 +268,7 @@ static int hvcc_array_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, array->NAL_unit_type = nal_type; array->numNalus++; - if (nal_type == OBS_HEVC_NAL_VPS || nal_type == OBS_HEVC_NAL_SPS || - nal_type == OBS_HEVC_NAL_PPS) + if (nal_type == OBS_HEVC_NAL_VPS || nal_type == OBS_HEVC_NAL_SPS || nal_type == OBS_HEVC_NAL_PPS) array->array_completeness = ps_array_completeness; return 0; @@ -296,27 +281,20 @@ static void nal_unit_parse_header(HevcGetBitContext *gb, uint8_t *nal_type) get_bits(gb, 9); } -static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc, - HVCCProfileTierLevel *ptl) +static void hvcc_update_ptl(HEVCDecoderConfigurationRecord *hvcc, HVCCProfileTierLevel *ptl) { hvcc->general_profile_space = ptl->profile_space; if (hvcc->general_tier_flag < ptl->tier_flag) hvcc->general_level_idc = ptl->level_idc; else - hvcc->general_level_idc = - max_u8(hvcc->general_level_idc, ptl->level_idc); - hvcc->general_tier_flag = - max_u8(hvcc->general_tier_flag, ptl->tier_flag); - hvcc->general_profile_idc = - max_u8(hvcc->general_profile_idc, ptl->profile_idc); - hvcc->general_profile_compatibility_flags &= - ptl->profile_compatibility_flags; - hvcc->general_constraint_indicator_flags &= - ptl->constraint_indicator_flags; + hvcc->general_level_idc = max_u8(hvcc->general_level_idc, ptl->level_idc); + hvcc->general_tier_flag = max_u8(hvcc->general_tier_flag, ptl->tier_flag); + hvcc->general_profile_idc = max_u8(hvcc->general_profile_idc, ptl->profile_idc); + hvcc->general_profile_compatibility_flags &= ptl->profile_compatibility_flags; + hvcc->general_constraint_indicator_flags &= ptl->constraint_indicator_flags; } -static void hvcc_parse_ptl(HevcGetBitContext *gb, - HEVCDecoderConfigurationRecord *hvcc, +static void hvcc_parse_ptl(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc, unsigned int max_sub_layers_minus1) { unsigned int i; @@ -354,14 +332,12 @@ static void hvcc_parse_ptl(HevcGetBitContext *gb, } } -static int hvcc_parse_vps(HevcGetBitContext *gb, - HEVCDecoderConfigurationRecord *hvcc) +static int hvcc_parse_vps(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc) { unsigned int vps_max_sub_layers_minus1; skip_bits(gb, 12); vps_max_sub_layers_minus1 = get_bits(gb, 3); - hvcc->numTemporalLayers = - max_u8(hvcc->numTemporalLayers, vps_max_sub_layers_minus1 + 1); + hvcc->numTemporalLayers = max_u8(hvcc->numTemporalLayers, vps_max_sub_layers_minus1 + 1); skip_bits(gb, 17); hvcc_parse_ptl(gb, hvcc, vps_max_sub_layers_minus1); return 0; @@ -389,9 +365,8 @@ static void skip_scaling_list_data(HevcGetBitContext *gb) } } -static int -parse_rps(HevcGetBitContext *gb, unsigned int rps_idx, unsigned int num_rps, - unsigned int num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS]) +static int parse_rps(HevcGetBitContext *gb, unsigned int rps_idx, unsigned int num_rps, + unsigned int num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS]) { unsigned int i; @@ -418,30 +393,27 @@ parse_rps(HevcGetBitContext *gb, unsigned int rps_idx, unsigned int num_rps, unsigned int num_negative_pics = get_ue_golomb_long(gb); unsigned int num_positive_pics = get_ue_golomb_long(gb); - if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > - (uint64_t)get_bits_left(gb)) + if ((num_positive_pics + (uint64_t)num_negative_pics) * 2 > (uint64_t)get_bits_left(gb)) return -1; num_delta_pocs[rps_idx] = num_negative_pics + num_positive_pics; for (i = 0; i < num_negative_pics; i++) { get_ue_golomb_long(gb); // delta_poc_s0_minus1[rps_idx] - get_bits(gb, 1); // used_by_curr_pic_s0_flag[rps_idx] + get_bits(gb, 1); // used_by_curr_pic_s0_flag[rps_idx] } for (i = 0; i < num_positive_pics; i++) { get_ue_golomb_long(gb); // delta_poc_s1_minus1[rps_idx] - get_bits(gb, 1); // used_by_curr_pic_s1_flag[rps_idx] + get_bits(gb, 1); // used_by_curr_pic_s1_flag[rps_idx] } } return 0; } -static void -skip_sub_layer_hrd_parameters(HevcGetBitContext *gb, - unsigned int cpb_cnt_minus1, - uint8_t sub_pic_hrd_params_present_flag) +static void skip_sub_layer_hrd_parameters(HevcGetBitContext *gb, unsigned int cpb_cnt_minus1, + uint8_t sub_pic_hrd_params_present_flag) { unsigned int i; @@ -458,9 +430,7 @@ skip_sub_layer_hrd_parameters(HevcGetBitContext *gb, } } -static int skip_hrd_parameters(HevcGetBitContext *gb, - uint8_t cprms_present_flag, - unsigned int max_sub_layers_minus1) +static int skip_hrd_parameters(HevcGetBitContext *gb, uint8_t cprms_present_flag, unsigned int max_sub_layers_minus1) { unsigned int i; uint8_t sub_pic_hrd_params_present_flag = 0; @@ -471,8 +441,7 @@ static int skip_hrd_parameters(HevcGetBitContext *gb, nal_hrd_parameters_present_flag = get_bits(gb, 1); vcl_hrd_parameters_present_flag = get_bits(gb, 1); - if (nal_hrd_parameters_present_flag || - vcl_hrd_parameters_present_flag) { + if (nal_hrd_parameters_present_flag || vcl_hrd_parameters_present_flag) { sub_pic_hrd_params_present_flag = get_bits(gb, 1); if (sub_pic_hrd_params_present_flag) @@ -507,21 +476,16 @@ static int skip_hrd_parameters(HevcGetBitContext *gb, } if (nal_hrd_parameters_present_flag) - skip_sub_layer_hrd_parameters( - gb, cpb_cnt_minus1, - sub_pic_hrd_params_present_flag); + skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1, sub_pic_hrd_params_present_flag); if (vcl_hrd_parameters_present_flag) - skip_sub_layer_hrd_parameters( - gb, cpb_cnt_minus1, - sub_pic_hrd_params_present_flag); + skip_sub_layer_hrd_parameters(gb, cpb_cnt_minus1, sub_pic_hrd_params_present_flag); } return 0; } -static void hvcc_parse_vui(HevcGetBitContext *gb, - HEVCDecoderConfigurationRecord *hvcc, +static void hvcc_parse_vui(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc, unsigned int max_sub_layers_minus1) { unsigned int min_spatial_segmentation_idc; @@ -561,7 +525,7 @@ static void hvcc_parse_vui(HevcGetBitContext *gb, get_bits_long(gb, 32); // num_units_in_tick get_bits_long(gb, 32); // time_scale - if (get_bits(gb, 1)) // poc_proportional_to_timing_flag + if (get_bits(gb, 1)) // poc_proportional_to_timing_flag get_ue_golomb_long(gb); // num_ticks_poc_diff_one_minus1 if (get_bits(gb, 1)) // vui_hrd_parameters_present_flag @@ -573,8 +537,7 @@ static void hvcc_parse_vui(HevcGetBitContext *gb, min_spatial_segmentation_idc = get_ue_golomb_long(gb); hvcc->min_spatial_segmentation_idc = - min_u16(hvcc->min_spatial_segmentation_idc, - min_spatial_segmentation_idc); + min_u16(hvcc->min_spatial_segmentation_idc, min_spatial_segmentation_idc); get_ue_golomb_long(gb); // max_bytes_per_pic_denom get_ue_golomb_long(gb); // max_bits_per_min_cu_denom @@ -583,19 +546,15 @@ static void hvcc_parse_vui(HevcGetBitContext *gb, } } -static int hvcc_parse_sps(HevcGetBitContext *gb, - HEVCDecoderConfigurationRecord *hvcc) +static int hvcc_parse_sps(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc) { - unsigned int i, sps_max_sub_layers_minus1, - log2_max_pic_order_cnt_lsb_minus4; - unsigned int num_short_term_ref_pic_sets, - num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS]; + unsigned int i, sps_max_sub_layers_minus1, log2_max_pic_order_cnt_lsb_minus4; + unsigned int num_short_term_ref_pic_sets, num_delta_pocs[HEVC_MAX_SHORT_TERM_REF_PIC_SETS]; get_bits(gb, 4); // sps_video_parameter_set_id sps_max_sub_layers_minus1 = get_bits(gb, 3); - hvcc->numTemporalLayers = - max_u8(hvcc->numTemporalLayers, sps_max_sub_layers_minus1 + 1); + hvcc->numTemporalLayers = max_u8(hvcc->numTemporalLayers, sps_max_sub_layers_minus1 + 1); hvcc->temporalIdNested = get_bits(gb, 1); @@ -644,14 +603,12 @@ static int hvcc_parse_sps(HevcGetBitContext *gb, get_bits(gb, 1); // amp_enabled_flag get_bits(gb, 1); // sample_adaptive_offset_enabled_flag - if (get_bits(gb, 1)) { // pcm_enabled_flag - get_bits(gb, 4); // pcm_sample_bit_depth_luma_minus1 - get_bits(gb, 4); // pcm_sample_bit_depth_chroma_minus1 - get_ue_golomb_long( - gb); // log2_min_pcm_luma_coding_block_size_minus3 - get_ue_golomb_long( - gb); // log2_diff_max_min_pcm_luma_coding_block_size - get_bits(gb, 1); // pcm_loop_filter_disabled_flag + if (get_bits(gb, 1)) { // pcm_enabled_flag + get_bits(gb, 4); // pcm_sample_bit_depth_luma_minus1 + get_bits(gb, 4); // pcm_sample_bit_depth_chroma_minus1 + get_ue_golomb_long(gb); // log2_min_pcm_luma_coding_block_size_minus3 + get_ue_golomb_long(gb); // log2_diff_max_min_pcm_luma_coding_block_size + get_bits(gb, 1); // pcm_loop_filter_disabled_flag } num_short_term_ref_pic_sets = get_ue_golomb_long(gb); @@ -659,8 +616,7 @@ static int hvcc_parse_sps(HevcGetBitContext *gb, return -1; for (i = 0; i < num_short_term_ref_pic_sets; i++) { - int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, - num_delta_pocs); + int ret = parse_rps(gb, i, num_short_term_ref_pic_sets, num_delta_pocs); if (ret < 0) return ret; } @@ -669,10 +625,8 @@ static int hvcc_parse_sps(HevcGetBitContext *gb, unsigned num_long_term_ref_pics_sps = get_ue_golomb_long(gb); if (num_long_term_ref_pics_sps > 31U) return -1; - for (i = 0; i < num_long_term_ref_pics_sps; - i++) { // num_long_term_ref_pics_sps - int len = min_i32(log2_max_pic_order_cnt_lsb_minus4 + 4, - 16); + for (i = 0; i < num_long_term_ref_pics_sps; i++) { // num_long_term_ref_pics_sps + int len = min_i32(log2_max_pic_order_cnt_lsb_minus4 + 4, 16); get_bits(gb, len); // lt_ref_pic_poc_lsb_sps[i] get_bits(gb, 1); // used_by_curr_pic_lt_sps_flag[i] } @@ -688,8 +642,7 @@ static int hvcc_parse_sps(HevcGetBitContext *gb, return 0; } -static int hvcc_parse_pps(HevcGetBitContext *gb, - HEVCDecoderConfigurationRecord *hvcc) +static int hvcc_parse_pps(HevcGetBitContext *gb, HEVCDecoderConfigurationRecord *hvcc) { uint8_t tiles_enabled_flag, entropy_coding_sync_enabled_flag; @@ -728,10 +681,8 @@ static int hvcc_parse_pps(HevcGetBitContext *gb, return 0; } -static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, - int ps_array_completeness, - HEVCDecoderConfigurationRecord *hvcc, - unsigned array_idx) +static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, int ps_array_completeness, + HEVCDecoderConfigurationRecord *hvcc, unsigned array_idx) { int ret = 0; HevcGetBitContext gbc; @@ -742,8 +693,7 @@ static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, uint8_t *dst; dst = bmalloc(nal_size + 64); - rbsp_buf = - ff_nal_unit_extract_rbsp(dst, nal_buf, nal_size, &rbsp_size, 2); + rbsp_buf = ff_nal_unit_extract_rbsp(dst, nal_buf, nal_size, &rbsp_size, 2); if (!rbsp_buf) { ret = -1; goto end; @@ -755,9 +705,7 @@ static int hvcc_add_nal_unit(uint8_t *nal_buf, uint32_t nal_size, nal_unit_parse_header(&gbc, &nal_type); - ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type, - ps_array_completeness, - &hvcc->arrays[array_idx]); + ret = hvcc_array_add_nal_unit(nal_buf, nal_size, nal_type, ps_array_completeness, &hvcc->arrays[array_idx]); if (ret < 0) goto end; if (hvcc->arrays[array_idx].numNalus == 1) @@ -825,15 +773,13 @@ size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size) // HVCC init HEVCDecoderConfigurationRecord hvcc; memset(&hvcc, 0, sizeof(HEVCDecoderConfigurationRecord)); - hvcc.lengthSizeMinusOne = 3; // 4 bytes - hvcc.general_profile_compatibility_flags = 0xffffffff; // all bits set - hvcc.general_constraint_indicator_flags = - 0xffffffffffff; // all bits set - hvcc.min_spatial_segmentation_idc = 4096 + 1; // assume invalid value + hvcc.lengthSizeMinusOne = 3; // 4 bytes + hvcc.general_profile_compatibility_flags = 0xffffffff; // all bits set + hvcc.general_constraint_indicator_flags = 0xffffffffffff; // all bits set + hvcc.min_spatial_segmentation_idc = 4096 + 1; // assume invalid value for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) { HVCCNALUnitArray *const array = &hvcc.arrays[i]; - array_output_serializer_init(&array->nalUnit, - &array->nalUnitData); + array_output_serializer_init(&array->nalUnit, &array->nalUnitData); } uint8_t *buf = (uint8_t *)start; @@ -846,16 +792,13 @@ size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size) buf += 4; for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) { - static const uint8_t array_idx_to_type[] = { - OBS_HEVC_NAL_VPS, OBS_HEVC_NAL_SPS, - OBS_HEVC_NAL_PPS, OBS_HEVC_NAL_SEI_PREFIX, - OBS_HEVC_NAL_SEI_SUFFIX}; + static const uint8_t array_idx_to_type[] = {OBS_HEVC_NAL_VPS, OBS_HEVC_NAL_SPS, + OBS_HEVC_NAL_PPS, OBS_HEVC_NAL_SEI_PREFIX, + OBS_HEVC_NAL_SEI_SUFFIX}; if (type == array_idx_to_type[i]) { int ps_array_completeness = 1; - int ret = hvcc_add_nal_unit( - buf, len, ps_array_completeness, &hvcc, - i); + int ret = hvcc_add_nal_unit(buf, len, ps_array_completeness, &hvcc, i); if (ret < 0) goto free; break; @@ -877,9 +820,8 @@ size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size) vps_count = hvcc.arrays[OBS_VPS_INDEX].numNalus; sps_count = hvcc.arrays[OBS_SPS_INDEX].numNalus; pps_count = hvcc.arrays[OBS_PPS_INDEX].numNalus; - if (!vps_count || vps_count > OBS_HEVC_MAX_VPS_COUNT || !sps_count || - sps_count > OBS_HEVC_MAX_SPS_COUNT || !pps_count || - pps_count > OBS_HEVC_MAX_PPS_COUNT) + if (!vps_count || vps_count > OBS_HEVC_MAX_VPS_COUNT || !sps_count || sps_count > OBS_HEVC_MAX_SPS_COUNT || + !pps_count || pps_count > OBS_HEVC_MAX_PPS_COUNT) goto free; struct array_output_data output; @@ -887,8 +829,7 @@ size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size) array_output_serializer_init(&s, &output); s_w8(&s, 1); // configurationVersion, always 1 - s_w8(&s, hvcc.general_profile_space << 6 | hvcc.general_tier_flag << 5 | - hvcc.general_profile_idc); + s_w8(&s, hvcc.general_profile_space << 6 | hvcc.general_tier_flag << 5 | hvcc.general_profile_idc); s_wb32(&s, hvcc.general_profile_compatibility_flags); @@ -904,8 +845,8 @@ size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size) s_w8(&s, hvcc.bitDepthChromaMinus8 | 0xf8); s_wb16(&s, hvcc.avgFrameRate); - s_w8(&s, hvcc.constantFrameRate << 6 | hvcc.numTemporalLayers << 3 | - hvcc.temporalIdNested << 2 | hvcc.lengthSizeMinusOne); + s_w8(&s, hvcc.constantFrameRate << 6 | hvcc.numTemporalLayers << 3 | hvcc.temporalIdNested << 2 | + hvcc.lengthSizeMinusOne); s_w8(&s, hvcc.numOfArrays); for (unsigned i = 0; i < OBS_NB_ARRAYS; i++) { @@ -914,12 +855,10 @@ size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size) if (!array->numNalus) continue; - s_w8(&s, (array->array_completeness << 7) | - (array->NAL_unit_type & 0x3f)); + s_w8(&s, (array->array_completeness << 7) | (array->NAL_unit_type & 0x3f)); s_wb16(&s, array->numNalus); - s_write(&s, array->nalUnitData.bytes.array, - array->nalUnitData.bytes.num); + s_write(&s, array->nalUnitData.bytes.array, array->nalUnitData.bytes.num); } *header = output.bytes.array; diff --git a/plugins/obs-outputs/rtmp-hevc.h b/plugins/obs-outputs/rtmp-hevc.h index d13432dbb..c0379068e 100644 --- a/plugins/obs-outputs/rtmp-hevc.h +++ b/plugins/obs-outputs/rtmp-hevc.h @@ -20,5 +20,4 @@ #include #include -extern size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, - size_t size); +extern size_t obs_parse_hevc_header(uint8_t **header, const uint8_t *data, size_t size); diff --git a/plugins/obs-outputs/rtmp-stream.c b/plugins/obs-outputs/rtmp-stream.c index da5980072..2f722fc39 100644 --- a/plugins/obs-outputs/rtmp-stream.c +++ b/plugins/obs-outputs/rtmp-stream.c @@ -172,23 +172,19 @@ static void *rtmp_stream_create(obs_data_t *settings, obs_output_t *output) goto fail; } - if (os_event_init(&stream->buffer_space_available_event, - OS_EVENT_TYPE_AUTO) != 0) { + if (os_event_init(&stream->buffer_space_available_event, OS_EVENT_TYPE_AUTO) != 0) { warn("Failed to initialize write buffer event"); goto fail; } - if (os_event_init(&stream->buffer_has_data_event, OS_EVENT_TYPE_AUTO) != - 0) { + if (os_event_init(&stream->buffer_has_data_event, OS_EVENT_TYPE_AUTO) != 0) { warn("Failed to initialize data buffer event"); goto fail; } - if (os_event_init(&stream->socket_available_event, - OS_EVENT_TYPE_AUTO) != 0) { + if (os_event_init(&stream->socket_available_event, OS_EVENT_TYPE_AUTO) != 0) { warn("Failed to initialize socket buffer event"); goto fail; } - if (os_event_init(&stream->send_thread_signaled_exit, - OS_EVENT_TYPE_MANUAL) != 0) { + if (os_event_init(&stream->send_thread_signaled_exit, OS_EVENT_TYPE_MANUAL) != 0) { warn("Failed to initialize socket exit event"); goto fail; } @@ -214,9 +210,7 @@ static void rtmp_stream_stop(void *data, uint64_t ts) stream->stop_ts = ts / 1000ULL; if (ts) - stream->shutdown_timeout_ts = - ts + - (uint64_t)stream->max_shutdown_time_sec * 1000000000ULL; + stream->shutdown_timeout_ts = ts + (uint64_t)stream->max_shutdown_time_sec * 1000000000ULL; if (active(stream)) { os_event_signal(stream->stop_event); @@ -234,15 +228,13 @@ static inline void set_rtmp_dstr(AVal *val, struct dstr *str) val->av_len = valid ? (int)str->len : 0; } -static inline bool get_next_packet(struct rtmp_stream *stream, - struct encoder_packet *packet) +static inline bool get_next_packet(struct rtmp_stream *stream, struct encoder_packet *packet) { bool new_packet = false; pthread_mutex_lock(&stream->packets_mutex); if (stream->packets.size) { - deque_pop_front(&stream->packets, packet, - sizeof(struct encoder_packet)); + deque_pop_front(&stream->packets, packet, sizeof(struct encoder_packet)); new_packet = true; } pthread_mutex_unlock(&stream->packets_mutex); @@ -341,8 +333,7 @@ static void droptest_cap_data_rate(struct rtmp_stream *stream, size_t size) } while (stream->droptest_size > stream->droptest_max) { - deque_pop_front(&stream->droptest_info, &info, - sizeof(info)); + deque_pop_front(&stream->droptest_info, &info, sizeof(info)); stream->droptest_size -= info.size; } } @@ -351,8 +342,7 @@ static void droptest_cap_data_rate(struct rtmp_stream *stream, size_t size) #endif #ifdef _WIN32 -static int socket_queue_data(RTMPSockBuf *sb, const char *data, int len, - void *arg) +static int socket_queue_data(RTMPSockBuf *sb, const char *data, int len, void *arg) { UNUSED_PARAMETER(sb); @@ -393,8 +383,7 @@ static int handle_socket_read(struct rtmp_stream *stream) int recv_size = 0; if (!stream->new_socket_loop) { #ifdef _WIN32 - ret = ioctlsocket(stream->rtmp.m_sb.sb_socket, FIONREAD, - (u_long *)&recv_size); + ret = ioctlsocket(stream->rtmp.m_sb.sb_socket, FIONREAD, (u_long *)&recv_size); #else ret = ioctl(stream->rtmp.m_sb.sb_socket, FIONREAD, &recv_size); #endif @@ -407,8 +396,7 @@ static int handle_socket_read(struct rtmp_stream *stream) return 0; } -static int send_packet(struct rtmp_stream *stream, - struct encoder_packet *packet, bool is_header) +static int send_packet(struct rtmp_stream *stream, struct encoder_packet *packet, bool is_header) { uint8_t *data; size_t size; @@ -417,8 +405,7 @@ static int send_packet(struct rtmp_stream *stream, if (handle_socket_read(stream)) return -1; - flv_packet_mux(packet, is_header ? 0 : stream->start_dts_offset, &data, - &size, is_header); + flv_packet_mux(packet, is_header ? 0 : stream->start_dts_offset, &data, &size, is_header); #ifdef TEST_FRAMEDROPS droptest_cap_data_rate(stream, size); @@ -436,9 +423,8 @@ static int send_packet(struct rtmp_stream *stream, return ret; } -static int send_packet_ex(struct rtmp_stream *stream, - struct encoder_packet *packet, bool is_header, - bool is_footer, size_t idx) +static int send_packet_ex(struct rtmp_stream *stream, struct encoder_packet *packet, bool is_header, bool is_footer, + size_t idx) { uint8_t *data; size_t size = 0; @@ -448,14 +434,11 @@ static int send_packet_ex(struct rtmp_stream *stream, return -1; if (is_header) { - flv_packet_start(packet, stream->video_codec[idx], &data, &size, - idx); + flv_packet_start(packet, stream->video_codec[idx], &data, &size, idx); } else if (is_footer) { - flv_packet_end(packet, stream->video_codec[idx], &data, &size, - idx); + flv_packet_end(packet, stream->video_codec[idx], &data, &size, idx); } else { - flv_packet_frames(packet, stream->video_codec[idx], - stream->start_dts_offset, &data, &size, idx); + flv_packet_frames(packet, stream->video_codec[idx], stream->start_dts_offset, &data, &size, idx); } #ifdef TEST_FRAMEDROPS @@ -474,9 +457,7 @@ static int send_packet_ex(struct rtmp_stream *stream, return ret; } -static int send_audio_packet_ex(struct rtmp_stream *stream, - struct encoder_packet *packet, bool is_header, - size_t idx) +static int send_audio_packet_ex(struct rtmp_stream *stream, struct encoder_packet *packet, bool is_header, size_t idx) { uint8_t *data; size_t size = 0; @@ -486,12 +467,9 @@ static int send_audio_packet_ex(struct rtmp_stream *stream, return -1; if (is_header) { - flv_packet_audio_start(packet, stream->audio_codec[idx], &data, - &size, idx); + flv_packet_audio_start(packet, stream->audio_codec[idx], &data, &size, idx); } else { - flv_packet_audio_frames(packet, stream->audio_codec[idx], - stream->start_dts_offset, &data, &size, - idx); + flv_packet_audio_frames(packet, stream->audio_codec[idx], stream->start_dts_offset, &data, &size, idx); } ret = RTMP_Write(&stream->rtmp, (char *)data, (int)size, 0); @@ -508,15 +486,13 @@ static int send_audio_packet_ex(struct rtmp_stream *stream, static inline bool send_headers(struct rtmp_stream *stream); static inline bool send_footers(struct rtmp_stream *stream); -static inline bool can_shutdown_stream(struct rtmp_stream *stream, - struct encoder_packet *packet) +static inline bool can_shutdown_stream(struct rtmp_stream *stream, struct encoder_packet *packet) { uint64_t cur_time = os_gettime_ns(); bool timeout = cur_time >= stream->shutdown_timeout_ts; if (timeout) - info("Stream shutdown timeout reached (%d second(s))", - stream->max_shutdown_time_sec); + info("Stream shutdown timeout reached (%d second(s))", stream->max_shutdown_time_sec); return timeout || packet->sys_dts_usec >= (int64_t)stream->stop_ts; } @@ -623,10 +599,7 @@ static void dbr_add_frame(struct rtmp_stream *stream, struct dbr_frame *back) deque_pop_front(&stream->dbr_frames, NULL, sizeof(front)); } - stream->dbr_est_bitrate = - (dur >= MIN_ESTIMATE_DURATION_MS) - ? (long)(stream->dbr_data_size * 1000 / dur) - : 0; + stream->dbr_est_bitrate = (dur >= MIN_ESTIMATE_DURATION_MS) ? (long)(stream->dbr_data_size * 1000 / dur) : 0; stream->dbr_est_bitrate *= 8; stream->dbr_est_bitrate /= 1000; @@ -647,8 +620,7 @@ static void log_sndbuf_size(struct rtmp_stream *stream) int cur_sendbuf_size; socklen_t int_size = sizeof(int); - if (!getsockopt(stream->rtmp.m_sb.sb_socket, SOL_SOCKET, SO_SNDBUF, - (char *)&cur_sendbuf_size, &int_size)) { + if (!getsockopt(stream->rtmp.m_sb.sb_socket, SOL_SOCKET, SO_SNDBUF, (char *)&cur_sendbuf_size, &int_size)) { info("Socket send buffer is %d bytes", cur_sendbuf_size); } } @@ -697,14 +669,10 @@ static void *send_thread(void *data) int sent; if (packet.type == OBS_ENCODER_VIDEO && (stream->video_codec[packet.track_idx] != CODEC_H264 || - (stream->video_codec[packet.track_idx] == CODEC_H264 && - packet.track_idx != 0))) { - sent = send_packet_ex(stream, &packet, false, false, - packet.track_idx); - } else if (packet.type == OBS_ENCODER_AUDIO && - packet.track_idx != 0) { - sent = send_audio_packet_ex(stream, &packet, false, - packet.track_idx); + (stream->video_codec[packet.track_idx] == CODEC_H264 && packet.track_idx != 0))) { + sent = send_packet_ex(stream, &packet, false, false, packet.track_idx); + } else if (packet.type == OBS_ENCODER_AUDIO && packet.track_idx != 0) { + sent = send_audio_packet_ex(stream, &packet, false, packet.track_idx); } else { sent = send_packet(stream, &packet, false); } @@ -783,22 +751,19 @@ static bool send_meta_data(struct rtmp_stream *stream) bool success = true; flv_meta_data(stream->output, &meta_data, &meta_data_size, false); - success = RTMP_Write(&stream->rtmp, (char *)meta_data, - (int)meta_data_size, 0) >= 0; + success = RTMP_Write(&stream->rtmp, (char *)meta_data, (int)meta_data_size, 0) >= 0; bfree(meta_data); return success; } -static bool send_audio_header(struct rtmp_stream *stream, size_t idx, - bool *next) +static bool send_audio_header(struct rtmp_stream *stream, size_t idx, bool *next) { obs_output_t *context = stream->output; obs_encoder_t *aencoder = obs_output_get_audio_encoder(context, idx); uint8_t *header; - struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, - .timebase_den = 1}; + struct encoder_packet packet = {.type = OBS_ENCODER_AUDIO, .timebase_den = 1}; if (!aencoder) { *next = false; @@ -810,8 +775,7 @@ static bool send_audio_header(struct rtmp_stream *stream, size_t idx, if (idx == 0) { return send_packet(stream, &packet, true) >= 0; } else { - return send_audio_packet_ex(stream, &packet, true, - idx) >= 0; + return send_audio_packet_ex(stream, &packet, true, idx) >= 0; } } return false; @@ -824,9 +788,7 @@ static bool send_video_header(struct rtmp_stream *stream, size_t idx) uint8_t *header; size_t size; - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = true}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = true}; if (!vencoder) return false; @@ -836,9 +798,7 @@ static bool send_video_header(struct rtmp_stream *stream, size_t idx) switch (stream->video_codec[idx]) { case CODEC_NONE: - do_log(LOG_ERROR, - "Codec not initialized for track %zu while sending header", - idx); + do_log(LOG_ERROR, "Codec not initialized for track %zu while sending header", idx); return false; case CODEC_H264: @@ -847,8 +807,7 @@ static bool send_video_header(struct rtmp_stream *stream, size_t idx) if (idx == 0) { return send_packet(stream, &packet, true) >= 0; } else { - return send_packet_ex(stream, &packet, true, false, - idx) >= 0; + return send_packet_ex(stream, &packet, true, false, idx) >= 0; } case CODEC_HEVC: #ifdef ENABLE_HEVC @@ -869,8 +828,7 @@ static bool send_video_header(struct rtmp_stream *stream, size_t idx) static bool send_video_metadata(struct rtmp_stream *stream, size_t idx) { // send metadata only if HDR - obs_encoder_t *encoder = - obs_output_get_video_encoder2(stream->output, idx); + obs_encoder_t *encoder = obs_output_get_video_encoder2(stream->output, idx); if (!encoder) return false; @@ -880,8 +838,7 @@ static bool send_video_metadata(struct rtmp_stream *stream, size_t idx) const struct video_output_info *info = video_output_get_info(video); enum video_colorspace colorspace = info->colorspace; - if (!(colorspace == VIDEO_CS_2100_PQ || - colorspace == VIDEO_CS_2100_HLG)) + if (!(colorspace == VIDEO_CS_2100_PQ || colorspace == VIDEO_CS_2100_HLG)) return true; if (handle_socket_read(stream)) @@ -893,8 +850,7 @@ static bool send_video_metadata(struct rtmp_stream *stream, size_t idx) size_t size; video_t *video = obs_get_video(); - const struct video_output_info *info = - video_output_get_info(video); + const struct video_output_info *info = video_output_get_info(video); enum video_format format = info->format; enum video_colorspace colorspace = info->colorspace; @@ -946,11 +902,9 @@ static bool send_video_metadata(struct rtmp_stream *stream, size_t idx) if (trc == OBSCOL_TRC_ARIB_STD_B67) max_luminance = 1000; else if (trc == OBSCOL_TRC_SMPTE2084) - max_luminance = - (int)obs_get_video_hdr_nominal_peak_level(); + max_luminance = (int)obs_get_video_hdr_nominal_peak_level(); - flv_packet_metadata(stream->video_codec[idx], &data, &size, - bits_per_raw_sample, pri, trc, spc, 0, + flv_packet_metadata(stream->video_codec[idx], &data, &size, bits_per_raw_sample, pri, trc, spc, 0, max_luminance, idx); int ret = RTMP_Write(&stream->rtmp, (char *)data, (int)size, 0); @@ -965,9 +919,7 @@ static bool send_video_metadata(struct rtmp_stream *stream, size_t idx) static bool send_video_footer(struct rtmp_stream *stream, size_t idx) { - struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, - .timebase_den = 1, - .keyframe = false}; + struct encoder_packet packet = {.type = OBS_ENCODER_VIDEO, .timebase_den = 1, .keyframe = false}; packet.size = 0; return send_packet_ex(stream, &packet, false, true, idx) >= 0; @@ -983,13 +935,11 @@ static inline bool send_headers(struct rtmp_stream *stream) return false; for (size_t j = 0; j < MAX_OUTPUT_VIDEO_ENCODERS; j++) { - obs_encoder_t *enc = - obs_output_get_video_encoder2(stream->output, j); + obs_encoder_t *enc = obs_output_get_video_encoder2(stream->output, j); if (!enc) continue; - if (!send_video_metadata(stream, j) || - !send_video_header(stream, j)) + if (!send_video_metadata(stream, j) || !send_video_header(stream, j)) return false; } @@ -1004,8 +954,7 @@ static inline bool send_headers(struct rtmp_stream *stream) static inline bool send_footers(struct rtmp_stream *stream) { for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - obs_encoder_t *encoder = - obs_output_get_video_encoder2(stream->output, i); + obs_encoder_t *encoder = obs_output_get_video_encoder2(stream->output, i); if (!encoder) continue; @@ -1064,15 +1013,13 @@ static int init_send(struct rtmp_stream *stream) int total_bitrate = 0; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - obs_encoder_t *vencoder = - obs_output_get_video_encoder2(context, i); + obs_encoder_t *vencoder = obs_output_get_video_encoder2(context, i); if (!vencoder) continue; obs_data_t *params = obs_encoder_get_settings(vencoder); if (params) { - int bitrate = - obs_data_get_int(params, "bitrate"); + int bitrate = obs_data_get_int(params, "bitrate"); if (!bitrate) { warn("Video encoder didn't return a " "valid bitrate, new network " @@ -1086,13 +1033,11 @@ static int init_send(struct rtmp_stream *stream) } } - obs_encoder_t *aencoder = - obs_output_get_audio_encoder(context, 0); + obs_encoder_t *aencoder = obs_output_get_audio_encoder(context, 0); if (aencoder) { obs_data_t *params = obs_encoder_get_settings(aencoder); if (params) { - int bitrate = - obs_data_get_int(params, "bitrate"); + int bitrate = obs_data_get_int(params, "bitrate"); if (!bitrate) bitrate = 160; total_bitrate += bitrate; @@ -1113,8 +1058,7 @@ static int init_send(struct rtmp_stream *stream) warn("New socket loop not supported on this platform"); return OBS_OUTPUT_ERROR; #else - ret = pthread_create(&stream->socket_thread, NULL, - socket_thread_windows, stream); + ret = pthread_create(&stream->socket_thread, NULL, socket_thread_windows, stream); if (ret != 0) { RTMP_Close(&stream->rtmp); @@ -1166,8 +1110,7 @@ static void win32_log_interface_type(struct rtmp_stream *stream) if (rtmp->m_bindIP.addrLen == 0) source_addr = 0; else if (rtmp->m_bindIP.addr.ss_family == AF_INET) - source_addr = (*(struct sockaddr_in *)&rtmp->m_bindIP.addr) - .sin_addr.S_un.S_addr; + source_addr = (*(struct sockaddr_in *)&rtmp->m_bindIP.addr).sin_addr.S_un.S_addr; else return; @@ -1191,8 +1134,7 @@ static void win32_log_interface_type(struct rtmp_stream *stream) type = "802.11"; break; default: - dstr_printf(&other, "type %d", - (int)row.PhysicalMediumType); + dstr_printf(&other, "type %d", (int)row.PhysicalMediumType); type = other.array; break; } @@ -1200,17 +1142,14 @@ static void win32_log_interface_type(struct rtmp_stream *stream) char *desc; os_wcs_to_utf8_ptr(row.Description, 0, &desc); - info("Interface: %s (%s, %lu↓/%lu↑ mbps)", desc, type, - rxSpeed, txSpeed); + info("Interface: %s (%s, %lu↓/%lu↑ mbps)", desc, type, rxSpeed, txSpeed); bfree(desc); if (row.InErrors || row.OutErrors) { - warn("Interface has non-zero error counters (%" PRIu64 - "/%" PRIu64 " errors, %" PRIu64 "/%" PRIu64 - " discards)", - row.InErrors, row.OutErrors, - row.InDiscards, row.OutDiscards); + warn("Interface has non-zero error counters (%" PRIu64 "/%" PRIu64 " errors, %" PRIu64 + "/%" PRIu64 " discards)", + row.InErrors, row.OutErrors, row.InDiscards, row.OutDiscards); } dstr_free(&other); @@ -1245,13 +1184,10 @@ static int try_connect(struct rtmp_stream *stream) set_rtmp_dstr(&stream->rtmp.Link.flashVer, &stream->encoder_name); stream->rtmp.Link.swfUrl = stream->rtmp.Link.tcUrl; - if (dstr_is_empty(&stream->bind_ip) || - dstr_cmp(&stream->bind_ip, "default") == 0) { - memset(&stream->rtmp.m_bindIP, 0, - sizeof(stream->rtmp.m_bindIP)); + if (dstr_is_empty(&stream->bind_ip) || dstr_cmp(&stream->bind_ip, "default") == 0) { + memset(&stream->rtmp.m_bindIP, 0, sizeof(stream->rtmp.m_bindIP)); } else { - bool success = netif_str_to_addr(&stream->rtmp.m_bindIP.addr, - &stream->rtmp.m_bindIP.addrLen, + bool success = netif_str_to_addr(&stream->rtmp.m_bindIP.addr, &stream->rtmp.m_bindIP.addrLen, stream->bind_ip.array); if (success) { int len = stream->rtmp.m_bindIP.addrLen; @@ -1283,10 +1219,8 @@ static int try_connect(struct rtmp_stream *stream) return OBS_OUTPUT_INVALID_STREAM; char ip_address[INET6_ADDRSTRLEN] = {0}; - netif_addr_to_str(&stream->rtmp.m_sb.sb_addr, ip_address, - INET6_ADDRSTRLEN); - info("Connection to %s (%s) successful", stream->path.array, - ip_address); + netif_addr_to_str(&stream->rtmp.m_sb.sb_addr, ip_address, INET6_ADDRSTRLEN); + info("Connection to %s (%s) successful", stream->path.array, ip_address); return init_send(stream); } @@ -1319,32 +1253,22 @@ static bool init_connect(struct rtmp_stream *stream) stream->got_first_packet = false; settings = obs_output_get_settings(stream->output); - dstr_copy(&stream->path, - obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_SERVER_URL)); - dstr_copy(&stream->key, - obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_STREAM_KEY)); - dstr_copy(&stream->username, - obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_USERNAME)); - dstr_copy(&stream->password, - obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_PASSWORD)); + dstr_copy(&stream->path, obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_SERVER_URL)); + dstr_copy(&stream->key, obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_STREAM_KEY)); + dstr_copy(&stream->username, obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_USERNAME)); + dstr_copy(&stream->password, obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_PASSWORD)); dstr_depad(&stream->path); dstr_depad(&stream->key); drop_b = (int64_t)obs_data_get_int(settings, OPT_DROP_THRESHOLD); drop_p = (int64_t)obs_data_get_int(settings, OPT_PFRAME_DROP_THRESHOLD); - stream->max_shutdown_time_sec = - (int)obs_data_get_int(settings, OPT_MAX_SHUTDOWN_TIME_SEC); + stream->max_shutdown_time_sec = (int)obs_data_get_int(settings, OPT_MAX_SHUTDOWN_TIME_SEC); obs_encoder_t *venc = obs_output_get_video_encoder(stream->output); obs_encoder_t *aenc = obs_output_get_audio_encoder(stream->output, 0); obs_data_t *vsettings = obs_encoder_get_settings(venc); obs_data_t *asettings = obs_encoder_get_settings(aenc); for (size_t i = 0; i < MAX_OUTPUT_AUDIO_ENCODERS; i++) { - obs_encoder_t *enc = - obs_output_get_audio_encoder(stream->output, i); + obs_encoder_t *enc = obs_output_get_audio_encoder(stream->output, i); if (enc) { const char *codec = obs_encoder_get_codec(enc); stream->audio_codec[i] = to_audio_type(codec); @@ -1352,8 +1276,7 @@ static bool init_connect(struct rtmp_stream *stream) } for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - obs_encoder_t *enc = - obs_output_get_video_encoder2(stream->output, i); + obs_encoder_t *enc = obs_output_get_video_encoder2(stream->output, i); if (enc) { const char *codec = obs_encoder_get_codec(enc); @@ -1411,14 +1334,11 @@ static bool init_connect(struct rtmp_stream *stream) } #ifdef _WIN32 - stream->new_socket_loop = - obs_data_get_bool(settings, OPT_NEWSOCKETLOOP_ENABLED); - stream->low_latency_mode = - obs_data_get_bool(settings, OPT_LOWLATENCY_ENABLED); + stream->new_socket_loop = obs_data_get_bool(settings, OPT_NEWSOCKETLOOP_ENABLED); + stream->low_latency_mode = obs_data_get_bool(settings, OPT_LOWLATENCY_ENABLED); // ugly hack for now, can be removed once new loop is reworked - if (stream->new_socket_loop && - !strncmp(stream->path.array, "rtmps://", 8)) { + if (stream->new_socket_loop && !strncmp(stream->path.array, "rtmps://", 8)) { warn("Disabling network optimizations, not compatible with RTMPS"); stream->new_socket_loop = false; } @@ -1445,17 +1365,13 @@ static void *connect_thread(void *data) // HDR streaming disabled for AV1 for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { - if (stream->video_codec[i] && - stream->video_codec[i] != CODEC_H264 && + if (stream->video_codec[i] && stream->video_codec[i] != CODEC_H264 && stream->video_codec[i] != CODEC_HEVC) { video_t *video = obs_get_video(); - const struct video_output_info *info = - video_output_get_info(video); + const struct video_output_info *info = video_output_get_info(video); - if (info->colorspace == VIDEO_CS_2100_HLG || - info->colorspace == VIDEO_CS_2100_PQ) { - obs_output_signal_stop(stream->output, - OBS_OUTPUT_HDR_DISABLED); + if (info->colorspace == VIDEO_CS_2100_HLG || info->colorspace == VIDEO_CS_2100_PQ) { + obs_output_signal_stop(stream->output, OBS_OUTPUT_HDR_DISABLED); return NULL; } } @@ -1485,15 +1401,12 @@ static bool rtmp_stream_start(void *data) return false; os_atomic_set_bool(&stream->connecting, true); - return pthread_create(&stream->connect_thread, NULL, connect_thread, - stream) == 0; + return pthread_create(&stream->connect_thread, NULL, connect_thread, stream) == 0; } -static inline bool add_packet(struct rtmp_stream *stream, - struct encoder_packet *packet) +static inline bool add_packet(struct rtmp_stream *stream, struct encoder_packet *packet) { - deque_push_back(&stream->packets, packet, - sizeof(struct encoder_packet)); + deque_push_back(&stream->packets, packet, sizeof(struct encoder_packet)); return true; } @@ -1502,8 +1415,7 @@ static inline size_t num_buffered_packets(struct rtmp_stream *stream) return stream->packets.size / sizeof(struct encoder_packet); } -static void drop_frames(struct rtmp_stream *stream, const char *name, - int highest_priority, bool pframes) +static void drop_frames(struct rtmp_stream *stream, const char *name, int highest_priority, bool pframes) { UNUSED_PARAMETER(pframes); @@ -1523,8 +1435,7 @@ static void drop_frames(struct rtmp_stream *stream, const char *name, deque_pop_front(&stream->packets, &packet, sizeof(packet)); /* do not drop audio data or video keyframes */ - if (packet.type == OBS_ENCODER_AUDIO || - packet.drop_priority >= highest_priority) { + if (packet.type == OBS_ENCODER_AUDIO || packet.drop_priority >= highest_priority) { deque_push_back(&new_buf, &packet, sizeof(packet)); } else { @@ -1543,19 +1454,17 @@ static void drop_frames(struct rtmp_stream *stream, const char *name, stream->dropped_frames += num_frames_dropped; #ifdef _DEBUG - debug("Dropped %s, prev packet count: %d, new packet count: %d", name, - start_packets, (int)num_buffered_packets(stream)); + debug("Dropped %s, prev packet count: %d, new packet count: %d", name, start_packets, + (int)num_buffered_packets(stream)); #endif } -static bool find_first_video_packet(struct rtmp_stream *stream, - struct encoder_packet *first) +static bool find_first_video_packet(struct rtmp_stream *stream, struct encoder_packet *first) { size_t count = stream->packets.size / sizeof(*first); for (size_t i = 0; i < count; i++) { - struct encoder_packet *cur = - deque_data(&stream->packets, i * sizeof(*first)); + struct encoder_packet *cur = deque_data(&stream->packets, i * sizeof(*first)); if (cur->type == OBS_ENCODER_VIDEO && !cur->keyframe) { *first = *cur; return true; @@ -1571,11 +1480,9 @@ static bool dbr_bitrate_lowered(struct rtmp_stream *stream) long est_bitrate = 0; long new_bitrate; - if (stream->dbr_est_bitrate && - stream->dbr_est_bitrate < stream->dbr_cur_bitrate) { + if (stream->dbr_est_bitrate && stream->dbr_est_bitrate < stream->dbr_cur_bitrate) { stream->dbr_data_size = 0; - deque_pop_front(&stream->dbr_frames, NULL, - stream->dbr_frames.size); + deque_pop_front(&stream->dbr_frames, NULL, stream->dbr_frames.size); est_bitrate = stream->dbr_est_bitrate / 100 * 100; if (est_bitrate < 50) { est_bitrate = 50; @@ -1646,12 +1553,10 @@ static void dbr_inc_bitrate(struct rtmp_stream *stream) if (stream->dbr_cur_bitrate >= stream->dbr_orig_bitrate) { stream->dbr_cur_bitrate = stream->dbr_orig_bitrate; - info("bitrate increased to: %ld, done", - stream->dbr_cur_bitrate); + info("bitrate increased to: %ld, done", stream->dbr_cur_bitrate); } else if (stream->dbr_cur_bitrate < stream->dbr_orig_bitrate) { stream->dbr_inc_timeout = os_gettime_ns() + DBR_INC_TIMER; - info("bitrate increased to: %ld, waiting", - stream->dbr_cur_bitrate); + info("bitrate increased to: %ld, waiting", stream->dbr_cur_bitrate); } } @@ -1661,10 +1566,8 @@ static void check_to_drop_frames(struct rtmp_stream *stream, bool pframes) int64_t buffer_duration_usec; size_t num_packets = num_buffered_packets(stream); const char *name = pframes ? "p-frames" : "b-frames"; - int priority = pframes ? OBS_NAL_PRIORITY_HIGHEST - : OBS_NAL_PRIORITY_HIGH; - int64_t drop_threshold = pframes ? stream->pframe_drop_threshold_usec - : stream->drop_threshold_usec; + int priority = pframes ? OBS_NAL_PRIORITY_HIGHEST : OBS_NAL_PRIORITY_HIGH; + int64_t drop_threshold = pframes ? stream->pframe_drop_threshold_usec : stream->drop_threshold_usec; if (!pframes && stream->dbr_enabled) { if (stream->dbr_inc_timeout) { @@ -1692,8 +1595,7 @@ static void check_to_drop_frames(struct rtmp_stream *stream, bool pframes) buffer_duration_usec = stream->last_dts_usec - first.dts_usec; if (!pframes) { - stream->congestion = - (float)buffer_duration_usec / (float)drop_threshold; + stream->congestion = (float)buffer_duration_usec / (float)drop_threshold; } /* alternatively, drop only pframes: @@ -1714,8 +1616,7 @@ static void check_to_drop_frames(struct rtmp_stream *stream, bool pframes) } if (bitrate_changed) { - debug("buffer_duration_msec: %" PRId64, - buffer_duration_usec / 1000); + debug("buffer_duration_msec: %" PRId64, buffer_duration_usec / 1000); dbr_set_bitrate(stream); } return; @@ -1727,8 +1628,7 @@ static void check_to_drop_frames(struct rtmp_stream *stream, bool pframes) } } -static bool add_video_packet(struct rtmp_stream *stream, - struct encoder_packet *packet) +static bool add_video_packet(struct rtmp_stream *stream, struct encoder_packet *packet) { check_to_drop_frames(stream, false); check_to_drop_frames(stream, true); @@ -1764,15 +1664,13 @@ static void rtmp_stream_data(void *data, struct encoder_packet *packet) if (packet->type == OBS_ENCODER_VIDEO) { if (!stream->got_first_packet) { - stream->start_dts_offset = - get_ms_time(packet, packet->dts); + stream->start_dts_offset = get_ms_time(packet, packet->dts); stream->got_first_packet = true; } switch (stream->video_codec[packet->track_idx]) { case CODEC_NONE: - do_log(LOG_ERROR, "Codec not initialized for track %zu", - packet->track_idx); + do_log(LOG_ERROR, "Codec not initialized for track %zu", packet->track_idx); return; case CODEC_H264: @@ -1791,8 +1689,7 @@ static void rtmp_stream_data(void *data, struct encoder_packet *packet) } } else { if (!stream->got_first_packet) { - stream->start_dts_offset = - get_ms_time(packet, packet->dts); + stream->start_dts_offset = get_ms_time(packet, packet->dts); stream->got_first_packet = true; } @@ -1802,9 +1699,8 @@ static void rtmp_stream_data(void *data, struct encoder_packet *packet) pthread_mutex_lock(&stream->packets_mutex); if (!disconnected(stream)) { - added_packet = (packet->type == OBS_ENCODER_VIDEO) - ? add_video_packet(stream, &new_packet) - : add_packet(stream, &new_packet); + added_packet = (packet->type == OBS_ENCODER_VIDEO) ? add_video_packet(stream, &new_packet) + : add_packet(stream, &new_packet); } pthread_mutex_unlock(&stream->packets_mutex); @@ -1835,26 +1731,18 @@ static obs_properties_t *rtmp_stream_properties(void *unused) struct netif_saddr_data addrs = {0}; obs_property_t *p; - p = obs_properties_add_int(props, OPT_DROP_THRESHOLD, - obs_module_text("RTMPStream.DropThreshold"), - 200, 10000, 100); + p = obs_properties_add_int(props, OPT_DROP_THRESHOLD, obs_module_text("RTMPStream.DropThreshold"), 200, 10000, + 100); obs_property_int_set_suffix(p, " ms"); - p = obs_properties_add_list(props, OPT_IP_FAMILY, - obs_module_text("IPFamily"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, OPT_IP_FAMILY, obs_module_text("IPFamily"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, obs_module_text("IPFamily.Both"), - "IPv4+IPv6"); - obs_property_list_add_string(p, obs_module_text("IPFamily.V4Only"), - "IPv4"); - obs_property_list_add_string(p, obs_module_text("IPFamily.V6Only"), - "IPv6"); + obs_property_list_add_string(p, obs_module_text("IPFamily.Both"), "IPv4+IPv6"); + obs_property_list_add_string(p, obs_module_text("IPFamily.V4Only"), "IPv4"); + obs_property_list_add_string(p, obs_module_text("IPFamily.V6Only"), "IPv6"); - p = obs_properties_add_list(props, OPT_BIND_IP, - obs_module_text("RTMPStream.BindIP"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(props, OPT_BIND_IP, obs_module_text("RTMPStream.BindIP"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, obs_module_text("Default"), "default"); @@ -1867,10 +1755,8 @@ static obs_properties_t *rtmp_stream_properties(void *unused) netif_saddr_data_free(&addrs); #ifdef _WIN32 - obs_properties_add_bool(props, OPT_NEWSOCKETLOOP_ENABLED, - obs_module_text("RTMPStream.NewSocketLoop")); - obs_properties_add_bool(props, OPT_LOWLATENCY_ENABLED, - obs_module_text("RTMPStream.LowLatencyMode")); + obs_properties_add_bool(props, OPT_NEWSOCKETLOOP_ENABLED, obs_module_text("RTMPStream.NewSocketLoop")); + obs_properties_add_bool(props, OPT_LOWLATENCY_ENABLED, obs_module_text("RTMPStream.LowLatencyMode")); #endif return props; @@ -1893,8 +1779,7 @@ static float rtmp_stream_congestion(void *data) struct rtmp_stream *stream = data; if (stream->new_socket_loop) - return (float)stream->write_buf_len / - (float)stream->write_buf_size; + return (float)stream->write_buf_len / (float)stream->write_buf_size; else return stream->min_priority > 0 ? 1.0f : stream->congestion; } @@ -1907,8 +1792,7 @@ static int rtmp_stream_connect_time(void *data) struct obs_output_info rtmp_output_info = { .id = "rtmp_output", - .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_SERVICE | - OBS_OUTPUT_MULTI_TRACK_AV, + .flags = OBS_OUTPUT_AV | OBS_OUTPUT_ENCODED | OBS_OUTPUT_SERVICE | OBS_OUTPUT_MULTI_TRACK_AV, #ifdef NO_CRYPTO .protocols = "RTMP", #else diff --git a/plugins/obs-outputs/rtmp-stream.h b/plugins/obs-outputs/rtmp-stream.h index 3ef0cf9a4..d5bf60616 100644 --- a/plugins/obs-outputs/rtmp-stream.h +++ b/plugins/obs-outputs/rtmp-stream.h @@ -15,9 +15,8 @@ #include #endif -#define do_log(level, format, ...) \ - blog(level, "[rtmp stream: '%s'] " format, \ - obs_output_get_name(stream->output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[rtmp stream: '%s'] " format, obs_output_get_name(stream->output), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -150,27 +149,20 @@ void *socket_thread_windows(void *data); */ enum OBSColorPrimaries { OBSCOL_PRI_RESERVED0 = 0, - OBSCOL_PRI_BT709 = - 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP 177 Annex B + OBSCOL_PRI_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 / SMPTE RP 177 Annex B OBSCOL_PRI_UNSPECIFIED = 2, OBSCOL_PRI_RESERVED = 3, - OBSCOL_PRI_BT470M = - 4, ///< also FCC Title 47 Code of Federal Regulations 73.682 (a)(20) - OBSCOL_PRI_BT470BG = - 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM - OBSCOL_PRI_SMPTE170M = - 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC - OBSCOL_PRI_SMPTE240M = - 7, ///< identical to above, also called "SMPTE C" even though it uses D65 + OBSCOL_PRI_BT470M = 4, ///< also FCC Title 47 Code of Federal Regulations 73.682 (a)(20) + OBSCOL_PRI_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM + OBSCOL_PRI_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC + OBSCOL_PRI_SMPTE240M = 7, ///< identical to above, also called "SMPTE C" even though it uses D65 OBSCOL_PRI_FILM = 8, ///< colour filters using Illuminant C OBSCOL_PRI_BT2020 = 9, ///< ITU-R BT2020 OBSCOL_PRI_SMPTE428 = 10, ///< SMPTE ST 428-1 (CIE 1931 XYZ) OBSCOL_PRI_SMPTEST428_1 = OBSCOL_PRI_SMPTE428, OBSCOL_PRI_SMPTE431 = 11, ///< SMPTE ST 431-2 (2011) / DCI P3 - OBSCOL_PRI_SMPTE432 = - 12, ///< SMPTE ST 432-1 (2010) / P3 D65 / Display P3 - OBSCOL_PRI_EBU3213 = - 22, ///< EBU Tech. 3213-E (nothing there) / one of JEDEC P22 group phosphors + OBSCOL_PRI_SMPTE432 = 12, ///< SMPTE ST 432-1 (2010) / P3 D65 / Display P3 + OBSCOL_PRI_EBU3213 = 22, ///< EBU Tech. 3213-E (nothing there) / one of JEDEC P22 group phosphors OBSCOL_PRI_JEDEC_P22 = OBSCOL_PRI_EBU3213, OBSCOL_PRI_NB ///< Not part of ABI }; @@ -184,30 +176,24 @@ enum OBSColorTransferCharacteristic { OBSCOL_TRC_BT709 = 1, ///< also ITU-R BT1361 OBSCOL_TRC_UNSPECIFIED = 2, OBSCOL_TRC_RESERVED = 3, - OBSCOL_TRC_GAMMA22 = - 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM - OBSCOL_TRC_GAMMA28 = 5, ///< also ITU-R BT470BG - OBSCOL_TRC_SMPTE170M = - 6, ///< also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC + OBSCOL_TRC_GAMMA22 = 4, ///< also ITU-R BT470M / ITU-R BT1700 625 PAL & SECAM + OBSCOL_TRC_GAMMA28 = 5, ///< also ITU-R BT470BG + OBSCOL_TRC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 or 625 / ITU-R BT1358 525 or 625 / ITU-R BT1700 NTSC OBSCOL_TRC_SMPTE240M = 7, - OBSCOL_TRC_LINEAR = 8, ///< "Linear transfer characteristics" - OBSCOL_TRC_LOG = - 9, ///< "Logarithmic transfer characteristic (100:1 range)" - OBSCOL_TRC_LOG_SQRT = - 10, ///< "Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)" + OBSCOL_TRC_LINEAR = 8, ///< "Linear transfer characteristics" + OBSCOL_TRC_LOG = 9, ///< "Logarithmic transfer characteristic (100:1 range)" + OBSCOL_TRC_LOG_SQRT = 10, ///< "Logarithmic transfer characteristic (100 * Sqrt(10) : 1 range)" OBSCOL_TRC_IEC61966_2_4 = 11, ///< IEC 61966-2-4 OBSCOL_TRC_BT1361_ECG = 12, ///< ITU-R BT1361 Extended Colour Gamut OBSCOL_TRC_IEC61966_2_1 = 13, ///< IEC 61966-2-1 (sRGB or sYCC) OBSCOL_TRC_BT2020_10 = 14, ///< ITU-R BT2020 for 10-bit system OBSCOL_TRC_BT2020_12 = 15, ///< ITU-R BT2020 for 12-bit system - OBSCOL_TRC_SMPTE2084 = - 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems + OBSCOL_TRC_SMPTE2084 = 16, ///< SMPTE ST 2084 for 10-, 12-, 14- and 16-bit systems OBSCOL_TRC_SMPTEST2084 = OBSCOL_TRC_SMPTE2084, OBSCOL_TRC_SMPTE428 = 17, ///< SMPTE ST 428-1 OBSCOL_TRC_SMPTEST428_1 = OBSCOL_TRC_SMPTE428, - OBSCOL_TRC_ARIB_STD_B67 = - 18, ///< ARIB STD-B67, known as "Hybrid log-gamma" - OBSCOL_TRC_NB ///< Not part of ABI + OBSCOL_TRC_ARIB_STD_B67 = 18, ///< ARIB STD-B67, known as "Hybrid log-gamma" + OBSCOL_TRC_NB ///< Not part of ABI }; /** @@ -215,32 +201,24 @@ enum OBSColorTransferCharacteristic { * These values match the ones defined by ISO/IEC 23091-2_2019 subclause 8.3. */ enum OBSColorSpace { - OBSCOL_SPC_RGB = - 0, ///< order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1 - OBSCOL_SPC_BT709 = - 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / derived in SMPTE RP 177 Annex B + OBSCOL_SPC_RGB = 0, ///< order of coefficients is actually GBR, also IEC 61966-2-1 (sRGB), YZX and ST 428-1 + OBSCOL_SPC_BT709 = 1, ///< also ITU-R BT1361 / IEC 61966-2-4 xvYCC709 / derived in SMPTE RP 177 Annex B OBSCOL_SPC_UNSPECIFIED = 2, - OBSCOL_SPC_RESERVED = - 3, ///< reserved for future use by ITU-T and ISO/IEC just like 15-255 are - OBSCOL_SPC_FCC = - 4, ///< FCC Title 47 Code of Federal Regulations 73.682 (a)(20) + OBSCOL_SPC_RESERVED = 3, ///< reserved for future use by ITU-T and ISO/IEC just like 15-255 are + OBSCOL_SPC_FCC = 4, ///< FCC Title 47 Code of Federal Regulations 73.682 (a)(20) OBSCOL_SPC_BT470BG = 5, ///< also ITU-R BT601-6 625 / ITU-R BT1358 625 / ITU-R BT1700 625 PAL & SECAM / IEC 61966-2-4 xvYCC601 OBSCOL_SPC_SMPTE170M = 6, ///< also ITU-R BT601-6 525 / ITU-R BT1358 525 / ITU-R BT1700 NTSC / functionally identical to above OBSCOL_SPC_SMPTE240M = 7, ///< derived from 170M primaries and D65 white point, 170M is derived from BT470 System M's primaries - OBSCOL_SPC_YCGCO = - 8, ///< used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16 + OBSCOL_SPC_YCGCO = 8, ///< used by Dirac / VC-2 and H.264 FRext, see ITU-T SG16 OBSCOL_SPC_YCOCG = OBSCOL_SPC_YCGCO, - OBSCOL_SPC_BT2020_NCL = - 9, ///< ITU-R BT2020 non-constant luminance system - OBSCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system - OBSCOL_SPC_SMPTE2085 = 11, ///< SMPTE 2085, Y'D'zD'x - OBSCOL_SPC_CHROMA_DERIVED_NCL = - 12, ///< Chromaticity-derived non-constant luminance system - OBSCOL_SPC_CHROMA_DERIVED_CL = - 13, ///< Chromaticity-derived constant luminance system - OBSCOL_SPC_ICTCP = 14, ///< ITU-R BT.2100-0, ICtCp - OBSCOL_SPC_NB ///< Not part of ABI + OBSCOL_SPC_BT2020_NCL = 9, ///< ITU-R BT2020 non-constant luminance system + OBSCOL_SPC_BT2020_CL = 10, ///< ITU-R BT2020 constant luminance system + OBSCOL_SPC_SMPTE2085 = 11, ///< SMPTE 2085, Y'D'zD'x + OBSCOL_SPC_CHROMA_DERIVED_NCL = 12, ///< Chromaticity-derived non-constant luminance system + OBSCOL_SPC_CHROMA_DERIVED_CL = 13, ///< Chromaticity-derived constant luminance system + OBSCOL_SPC_ICTCP = 14, ///< ITU-R BT.2100-0, ICtCp + OBSCOL_SPC_NB ///< Not part of ABI }; diff --git a/plugins/obs-outputs/rtmp-windows.c b/plugins/obs-outputs/rtmp-windows.c index 9f421d69b..50b90e380 100644 --- a/plugins/obs-outputs/rtmp-windows.c +++ b/plugins/obs-outputs/rtmp-windows.c @@ -9,14 +9,12 @@ static void fatal_sock_shutdown(struct rtmp_stream *stream) os_event_signal(stream->buffer_space_available_event); } -static bool socket_event(struct rtmp_stream *stream, bool *can_write, - uint64_t last_send_time) +static bool socket_event(struct rtmp_stream *stream, bool *can_write, uint64_t last_send_time) { WSANETWORKEVENTS net_events; bool success; - success = !WSAEnumNetworkEvents(stream->rtmp.m_sb.sb_socket, NULL, - &net_events); + success = !WSAEnumNetworkEvents(stream->rtmp.m_sb.sb_socket, NULL, &net_events); if (!success) { blog(LOG_ERROR, "socket_thread_windows: Aborting due to " @@ -31,15 +29,13 @@ static bool socket_event(struct rtmp_stream *stream, bool *can_write, if (net_events.lNetworkEvents & FD_CLOSE) { if (last_send_time) { - uint32_t diff = - (os_gettime_ns() / 1000000) - last_send_time; + uint32_t diff = (os_gettime_ns() / 1000000) - last_send_time; blog(LOG_ERROR, "socket_thread_windows: Received " "FD_CLOSE, %u ms since last send " "(buffer: %d / %d)", - diff, stream->write_buf_len, - stream->write_buf_size); + diff, stream->write_buf_len, stream->write_buf_size); } if (os_event_try(stream->stop_event) != EAGAIN) @@ -47,8 +43,7 @@ static bool socket_event(struct rtmp_stream *stream, bool *can_write, "socket_thread_windows: Aborting due " "to FD_CLOSE during shutdown, " "%d bytes lost, error %d", - stream->write_buf_len, - net_events.iErrorCode[FD_CLOSE_BIT]); + stream->write_buf_len, net_events.iErrorCode[FD_CLOSE_BIT]); else blog(LOG_ERROR, "socket_thread_windows: Aborting due " @@ -65,8 +60,7 @@ static bool socket_event(struct rtmp_stream *stream, bool *can_write, bool fatal = false; for (;;) { - int ret = recv(stream->rtmp.m_sb.sb_socket, discard, - sizeof(discard), 0); + int ret = recv(stream->rtmp.m_sb.sb_socket, discard, sizeof(discard), 0); if (ret == -1) { err_code = WSAGetLastError(); if (err_code == WSAEWOULDBLOCK) @@ -94,34 +88,28 @@ static bool socket_event(struct rtmp_stream *stream, bool *can_write, return true; } -static void ideal_send_backlog_event(struct rtmp_stream *stream, - bool *can_write) +static void ideal_send_backlog_event(struct rtmp_stream *stream, bool *can_write) { ULONG ideal_send_backlog; int ret; - ret = idealsendbacklogquery(stream->rtmp.m_sb.sb_socket, - &ideal_send_backlog); + ret = idealsendbacklogquery(stream->rtmp.m_sb.sb_socket, &ideal_send_backlog); if (ret == 0) { int cur_tcp_bufsize; int size = sizeof(cur_tcp_bufsize); - ret = getsockopt(stream->rtmp.m_sb.sb_socket, SOL_SOCKET, - SO_SNDBUF, (char *)&cur_tcp_bufsize, &size); + ret = getsockopt(stream->rtmp.m_sb.sb_socket, SOL_SOCKET, SO_SNDBUF, (char *)&cur_tcp_bufsize, &size); if (ret == 0) { if (cur_tcp_bufsize < (int)ideal_send_backlog) { int bufsize = (int)ideal_send_backlog; - setsockopt(stream->rtmp.m_sb.sb_socket, - SOL_SOCKET, SO_SNDBUF, - (const char *)&bufsize, + setsockopt(stream->rtmp.m_sb.sb_socket, SOL_SOCKET, SO_SNDBUF, (const char *)&bufsize, sizeof(bufsize)); blog(LOG_INFO, "socket_thread_windows: " "Increasing send buffer to " "ISB %d (buffer: %d / %d)", - ideal_send_backlog, stream->write_buf_len, - stream->write_buf_size); + ideal_send_backlog, stream->write_buf_len, stream->write_buf_size); } } else { blog(LOG_ERROR, @@ -141,8 +129,7 @@ static void ideal_send_backlog_event(struct rtmp_stream *stream, enum data_ret { RET_BREAK, RET_FATAL, RET_CONTINUE }; -static enum data_ret write_data(struct rtmp_stream *stream, bool *can_write, - uint64_t *last_send_time, +static enum data_ret write_data(struct rtmp_stream *stream, bool *can_write, uint64_t *last_send_time, size_t latency_packet_size, int delay_time) { bool exit_loop = false; @@ -162,22 +149,16 @@ static enum data_ret write_data(struct rtmp_stream *stream, bool *can_write, int ret; if (stream->low_latency_mode) { - size_t send_len = - min(latency_packet_size, stream->write_buf_len); + size_t send_len = min(latency_packet_size, stream->write_buf_len); - ret = RTMPSockBuf_Send(&stream->rtmp.m_sb, - (const char *)stream->write_buf, - (int)send_len); + ret = RTMPSockBuf_Send(&stream->rtmp.m_sb, (const char *)stream->write_buf, (int)send_len); } else { - ret = RTMPSockBuf_Send(&stream->rtmp.m_sb, - (const char *)stream->write_buf, - (int)stream->write_buf_len); + ret = RTMPSockBuf_Send(&stream->rtmp.m_sb, (const char *)stream->write_buf, (int)stream->write_buf_len); } if (ret > 0) { if (stream->write_buf_len - ret) - memmove(stream->write_buf, stream->write_buf + ret, - stream->write_buf_len - ret); + memmove(stream->write_buf, stream->write_buf + ret, stream->write_buf_len - ret); stream->write_buf_len -= ret; *last_send_time = os_gettime_ns() / 1000000; @@ -245,27 +226,22 @@ static inline void socket_thread_windows_internal(struct rtmp_stream *stream) SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL); - WSAEventSelect(stream->rtmp.m_sb.sb_socket, - stream->socket_available_event, - FD_READ | FD_WRITE | FD_CLOSE); + WSAEventSelect(stream->rtmp.m_sb.sb_socket, stream->socket_available_event, FD_READ | FD_WRITE | FD_CLOSE); send_backlog_event = CreateEvent(NULL, true, false, NULL); if (stream->low_latency_mode) { delay_time = 1000 / LATENCY_FACTOR; - latency_packet_size = - stream->write_buf_size / (LATENCY_FACTOR - 2); + latency_packet_size = stream->write_buf_size / (LATENCY_FACTOR - 2); } else { latency_packet_size = stream->write_buf_size; delay_time = 0; } if (!stream->disable_send_window_optimization) { - memset(&send_backlog_overlapped, 0, - sizeof(send_backlog_overlapped)); + memset(&send_backlog_overlapped, 0, sizeof(send_backlog_overlapped)); send_backlog_overlapped.hEvent = send_backlog_event; - idealsendbacklognotify(stream->rtmp.m_sb.sb_socket, - &send_backlog_overlapped, NULL); + idealsendbacklognotify(stream->rtmp.m_sb.sb_socket, &send_backlog_overlapped, NULL); } else { blog(LOG_INFO, "socket_thread_windows: Send window " "optimization disabled by user."); @@ -283,8 +259,7 @@ static inline void socket_thread_windows_internal(struct rtmp_stream *stream) if (stream->write_buf_len == 0) { //blog(LOG_DEBUG, "Exiting on empty buffer"); pthread_mutex_unlock(&stream->write_buf_mutex); - os_event_reset( - stream->send_thread_signaled_exit); + os_event_reset(stream->send_thread_signaled_exit); break; } @@ -309,16 +284,14 @@ static inline void socket_thread_windows_internal(struct rtmp_stream *stream) ideal_send_backlog_event(stream, &can_write); ResetEvent(send_backlog_event); - idealsendbacklognotify(stream->rtmp.m_sb.sb_socket, - &send_backlog_overlapped, NULL); + idealsendbacklognotify(stream->rtmp.m_sb.sb_socket, &send_backlog_overlapped, NULL); continue; } if (can_write) { for (;;) { - enum data_ret ret = write_data( - stream, &can_write, &last_send_time, - latency_packet_size, delay_time); + enum data_ret ret = write_data(stream, &can_write, &last_send_time, latency_packet_size, + delay_time); switch (ret) { case RET_BREAK: @@ -333,8 +306,7 @@ static inline void socket_thread_windows_internal(struct rtmp_stream *stream) } if (stream->rtmp.m_sb.sb_socket != INVALID_SOCKET) - WSAEventSelect(stream->rtmp.m_sb.sb_socket, - stream->socket_available_event, 0); + WSAEventSelect(stream->rtmp.m_sb.sb_socket, stream->socket_available_event, 0); blog(LOG_INFO, "socket_thread_windows: Normal exit"); } diff --git a/plugins/obs-qsv11/QSV_Encoder.cpp b/plugins/obs-qsv11/QSV_Encoder.cpp index a9e6483be..67bf59346 100644 --- a/plugins/obs-qsv11/QSV_Encoder.cpp +++ b/plugins/obs-qsv11/QSV_Encoder.cpp @@ -64,8 +64,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define do_log(level, format, ...) \ - blog(level, "[qsv encoder: '%s'] " format, "msdk_impl", ##__VA_ARGS__) +#define do_log(level, format, ...) blog(level, "[qsv encoder: '%s'] " format, "msdk_impl", ##__VA_ARGS__) mfxIMPL impl = MFX_IMPL_HARDWARE_ANY; mfxVersion ver = {{0, 1}}; // for backward compatibility @@ -77,11 +76,9 @@ void qsv_encoder_version(unsigned short *major, unsigned short *minor) *minor = ver.Minor; } -qsv_t *qsv_encoder_open(qsv_param_t *pParams, enum qsv_codec codec, - bool useTexAlloc) +qsv_t *qsv_encoder_open(qsv_param_t *pParams, enum qsv_codec codec, bool useTexAlloc) { - QSV_Encoder_Internal *pEncoder = - new QSV_Encoder_Internal(ver, useTexAlloc); + QSV_Encoder_Internal *pEncoder = new QSV_Encoder_Internal(ver, useTexAlloc); mfxStatus sts = pEncoder->Open(pParams, codec); if (sts != MFX_ERR_NONE) { @@ -93,69 +90,37 @@ qsv_t *qsv_encoder_open(qsv_param_t *pParams, enum qsv_codec codec, switch (sts) { WARN_ERR(MFX_ERR_UNKNOWN, "Unknown QSV error"); - WARN_ERR( - MFX_ERR_NOT_INITIALIZED, - "Member functions called without initialization"); - WARN_ERR(MFX_ERR_INVALID_HANDLE, - "Invalid session or MemId handle"); - WARN_ERR( - MFX_ERR_NULL_PTR, - "NULL pointer in the input or output arguments"); - WARN_ERR(MFX_ERR_UNDEFINED_BEHAVIOR, - "Undefined behavior"); - WARN_ERR(MFX_ERR_NOT_ENOUGH_BUFFER, - "Insufficient buffer for input or output."); - WARN_ERR(MFX_ERR_NOT_FOUND, - "Specified object/item/sync point not found."); - WARN_ERR(MFX_ERR_MEMORY_ALLOC, - "Failed to allocate memory"); - WARN_ERR(MFX_ERR_LOCK_MEMORY, - "failed to lock the memory block " - "(external allocator)."); - WARN_ERR( - MFX_ERR_UNSUPPORTED, - "Unsupported configurations, parameters, or features"); - WARN_ERR(MFX_ERR_INVALID_VIDEO_PARAM, - "Incompatible video parameters detected"); - WARN_ERR( - MFX_WRN_VIDEO_PARAM_CHANGED, - "The decoder detected a new sequence header in the " - "bitstream. Video parameters may have changed."); - WARN_ERR( - MFX_WRN_VALUE_NOT_CHANGED, - "The parameter has been clipped to its value range"); - WARN_ERR(MFX_WRN_OUT_OF_RANGE, - "The parameter is out of valid value range"); - WARN_ERR(MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, - "Incompatible video parameters detected"); - WARN_ERR( - MFX_WRN_FILTER_SKIPPED, - "The SDK VPP has skipped one or more optional filters " - "requested by the application"); - WARN_ERR(MFX_ERR_ABORTED, - "The asynchronous operation aborted"); - WARN_ERR( - MFX_ERR_MORE_DATA, - "Need more bitstream at decoding input, encoding " - "input, or video processing input frames"); - WARN_ERR(MFX_ERR_MORE_SURFACE, - "Need more frame surfaces at " - "decoding or video processing output"); - WARN_ERR( - MFX_ERR_MORE_BITSTREAM, - "Need more bitstream buffers at the encoding output"); - WARN_ERR(MFX_WRN_IN_EXECUTION, - "Synchronous operation still running"); - WARN_ERR(MFX_ERR_DEVICE_FAILED, - "Hardware device returned unexpected errors"); - WARN_ERR(MFX_ERR_DEVICE_LOST, - "Hardware device was lost"); - WARN_ERR(MFX_WRN_DEVICE_BUSY, - "Hardware device is currently busy"); - WARN_ERR(MFX_WRN_PARTIAL_ACCELERATION, - "The hardware does not support the specified " - "configuration. Encoding, decoding, or video " - "processing may be partially accelerated"); + WARN_ERR(MFX_ERR_NOT_INITIALIZED, "Member functions called without initialization"); + WARN_ERR(MFX_ERR_INVALID_HANDLE, "Invalid session or MemId handle"); + WARN_ERR(MFX_ERR_NULL_PTR, "NULL pointer in the input or output arguments"); + WARN_ERR(MFX_ERR_UNDEFINED_BEHAVIOR, "Undefined behavior"); + WARN_ERR(MFX_ERR_NOT_ENOUGH_BUFFER, "Insufficient buffer for input or output."); + WARN_ERR(MFX_ERR_NOT_FOUND, "Specified object/item/sync point not found."); + WARN_ERR(MFX_ERR_MEMORY_ALLOC, "Failed to allocate memory"); + WARN_ERR(MFX_ERR_LOCK_MEMORY, "failed to lock the memory block " + "(external allocator)."); + WARN_ERR(MFX_ERR_UNSUPPORTED, "Unsupported configurations, parameters, or features"); + WARN_ERR(MFX_ERR_INVALID_VIDEO_PARAM, "Incompatible video parameters detected"); + WARN_ERR(MFX_WRN_VIDEO_PARAM_CHANGED, "The decoder detected a new sequence header in the " + "bitstream. Video parameters may have changed."); + WARN_ERR(MFX_WRN_VALUE_NOT_CHANGED, "The parameter has been clipped to its value range"); + WARN_ERR(MFX_WRN_OUT_OF_RANGE, "The parameter is out of valid value range"); + WARN_ERR(MFX_WRN_INCOMPATIBLE_VIDEO_PARAM, "Incompatible video parameters detected"); + WARN_ERR(MFX_WRN_FILTER_SKIPPED, "The SDK VPP has skipped one or more optional filters " + "requested by the application"); + WARN_ERR(MFX_ERR_ABORTED, "The asynchronous operation aborted"); + WARN_ERR(MFX_ERR_MORE_DATA, "Need more bitstream at decoding input, encoding " + "input, or video processing input frames"); + WARN_ERR(MFX_ERR_MORE_SURFACE, "Need more frame surfaces at " + "decoding or video processing output"); + WARN_ERR(MFX_ERR_MORE_BITSTREAM, "Need more bitstream buffers at the encoding output"); + WARN_ERR(MFX_WRN_IN_EXECUTION, "Synchronous operation still running"); + WARN_ERR(MFX_ERR_DEVICE_FAILED, "Hardware device returned unexpected errors"); + WARN_ERR(MFX_ERR_DEVICE_LOST, "Hardware device was lost"); + WARN_ERR(MFX_WRN_DEVICE_BUSY, "Hardware device is currently busy"); + WARN_ERR(MFX_WRN_PARTIAL_ACCELERATION, "The hardware does not support the specified " + "configuration. Encoding, decoding, or video " + "processing may be partially accelerated"); } #undef WARN_ERR @@ -170,8 +135,7 @@ qsv_t *qsv_encoder_open(qsv_param_t *pParams, enum qsv_codec codec, return (qsv_t *)pEncoder; } -int qsv_encoder_headers(qsv_t *pContext, uint8_t **pSPS, uint8_t **pPPS, - uint16_t *pnSPS, uint16_t *pnPPS) +int qsv_encoder_headers(qsv_t *pContext, uint8_t **pSPS, uint8_t **pPPS, uint16_t *pnSPS, uint16_t *pnPPS) { QSV_Encoder_Internal *pEncoder = (QSV_Encoder_Internal *)pContext; pEncoder->GetSPSPPS(pSPS, pPPS, pnSPS, pnPPS); @@ -195,16 +159,14 @@ void qsv_encoder_clear_roi(qsv_t *pContext) pEncoder->ClearROI(); } -int qsv_encoder_encode(qsv_t *pContext, uint64_t ts, uint8_t *pDataY, - uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV, - mfxBitstream **pBS) +int qsv_encoder_encode(qsv_t *pContext, uint64_t ts, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, + uint32_t strideUV, mfxBitstream **pBS) { QSV_Encoder_Internal *pEncoder = (QSV_Encoder_Internal *)pContext; mfxStatus sts = MFX_ERR_NONE; if (pDataY != NULL && pDataUV != NULL) - sts = pEncoder->Encode(ts, pDataY, pDataUV, strideY, strideUV, - pBS); + sts = pEncoder->Encode(ts, pDataY, pDataUV, strideY, strideUV, pBS); if (sts == MFX_ERR_NONE) return 0; @@ -214,8 +176,7 @@ int qsv_encoder_encode(qsv_t *pContext, uint64_t ts, uint8_t *pDataY, return -1; } -int qsv_encoder_encode_tex(qsv_t *pContext, uint64_t ts, void *tex, - uint64_t lock_key, uint64_t *next_key, +int qsv_encoder_encode_tex(qsv_t *pContext, uint64_t ts, void *tex, uint64_t lock_key, uint64_t *next_key, mfxBitstream **pBS) { QSV_Encoder_Internal *pEncoder = (QSV_Encoder_Internal *)pContext; @@ -288,8 +249,7 @@ enum qsv_cpu_platform qsv_get_cpu_platform() util_cpuid(cpuInfo, 1); uint8_t model = ((cpuInfo[0] >> 4) & 0xF) + ((cpuInfo[0] >> 12) & 0xF0); - uint8_t family = - ((cpuInfo[0] >> 8) & 0xF) + ((cpuInfo[0] >> 20) & 0xFF); + uint8_t family = ((cpuInfo[0] >> 8) & 0xF) + ((cpuInfo[0] >> 20) & 0xFF); // See Intel 64 and IA-32 Architectures Software Developer's Manual, // Vol 3C Table 35-1 @@ -354,9 +314,8 @@ enum qsv_cpu_platform qsv_get_cpu_platform() return QSV_CPU_PLATFORM_INTEL; } -int qsv_hevc_encoder_headers(qsv_t *pContext, uint8_t **pVPS, uint8_t **pSPS, - uint8_t **pPPS, uint16_t *pnVPS, uint16_t *pnSPS, - uint16_t *pnPPS) +int qsv_hevc_encoder_headers(qsv_t *pContext, uint8_t **pVPS, uint8_t **pSPS, uint8_t **pPPS, uint16_t *pnVPS, + uint16_t *pnSPS, uint16_t *pnPPS) { QSV_Encoder_Internal *pEncoder = (QSV_Encoder_Internal *)pContext; pEncoder->GetVpsSpsPps(pVPS, pSPS, pPPS, pnVPS, pnSPS, pnPPS); diff --git a/plugins/obs-qsv11/QSV_Encoder.h b/plugins/obs-qsv11/QSV_Encoder.h index c69d20aba..3a39261b1 100644 --- a/plugins/obs-qsv11/QSV_Encoder.h +++ b/plugins/obs-qsv11/QSV_Encoder.h @@ -82,15 +82,12 @@ static const struct qsv_rate_control_info qsv_ratecontrols[] = {{"CBR", false}, static const char *const qsv_profile_names[] = {"high", "main", "baseline", 0}; static const char *const qsv_profile_names_av1[] = {"main", 0}; static const char *const qsv_profile_names_hevc[] = {"main", "main10", 0}; -static const char *const qsv_usage_translation_keys[] = { - "TargetUsage.TU1", "TargetUsage.TU2", - "TargetUsage.TU3", "TargetUsage.TU4", - "TargetUsage.TU5", "TargetUsage.TU6", - "TargetUsage.TU7", 0}; -static const char *const qsv_usage_names[] = {"TU1", "TU2", "TU3", "TU4", - "TU5", "TU6", "TU7", 0}; -static const char *const qsv_latency_names[] = {"ultra-low", "low", "normal", - 0}; +static const char *const qsv_usage_translation_keys[] = {"TargetUsage.TU1", "TargetUsage.TU2", + "TargetUsage.TU3", "TargetUsage.TU4", + "TargetUsage.TU5", "TargetUsage.TU6", + "TargetUsage.TU7", 0}; +static const char *const qsv_usage_names[] = {"TU1", "TU2", "TU3", "TU4", "TU5", "TU6", "TU7", 0}; +static const char *const qsv_latency_names[] = {"ultra-low", "low", "normal", 0}; typedef struct qsv_t qsv_t; typedef struct { @@ -154,25 +151,20 @@ enum qsv_cpu_platform { int qsv_encoder_close(qsv_t *); int qsv_param_parse(qsv_param_t *, const char *name, const char *value); int qsv_param_apply_profile(qsv_param_t *, const char *profile); -int qsv_param_default_preset(qsv_param_t *, const char *preset, - const char *tune); +int qsv_param_default_preset(qsv_param_t *, const char *preset, const char *tune); int qsv_encoder_reconfig(qsv_t *, qsv_param_t *); void qsv_encoder_version(unsigned short *major, unsigned short *minor); qsv_t *qsv_encoder_open(qsv_param_t *, enum qsv_codec codec, bool useTexAlloc); void qsv_encoder_add_roi(qsv_t *, const struct obs_encoder_roi *roi); void qsv_encoder_clear_roi(qsv_t *pContext); -int qsv_encoder_encode(qsv_t *, uint64_t, uint8_t *, uint8_t *, uint32_t, - uint32_t, mfxBitstream **pBS); -int qsv_encoder_encode_tex(qsv_t *, uint64_t, void *, uint64_t, uint64_t *, - mfxBitstream **pBS); -int qsv_encoder_headers(qsv_t *, uint8_t **pSPS, uint8_t **pPPS, - uint16_t *pnSPS, uint16_t *pnPPS); +int qsv_encoder_encode(qsv_t *, uint64_t, uint8_t *, uint8_t *, uint32_t, uint32_t, mfxBitstream **pBS); +int qsv_encoder_encode_tex(qsv_t *, uint64_t, void *, uint64_t, uint64_t *, mfxBitstream **pBS); +int qsv_encoder_headers(qsv_t *, uint8_t **pSPS, uint8_t **pPPS, uint16_t *pnSPS, uint16_t *pnPPS); enum qsv_cpu_platform qsv_get_cpu_platform(); bool prefer_igpu_enc(int *iGPUIndex); -int qsv_hevc_encoder_headers(qsv_t *pContext, uint8_t **vVPS, uint8_t **pSPS, - uint8_t **pPPS, uint16_t *pnVPS, uint16_t *pnSPS, - uint16_t *pnPPS); +int qsv_hevc_encoder_headers(qsv_t *pContext, uint8_t **vVPS, uint8_t **pSPS, uint8_t **pPPS, uint16_t *pnVPS, + uint16_t *pnSPS, uint16_t *pnPPS); #ifdef __cplusplus } diff --git a/plugins/obs-qsv11/QSV_Encoder_Internal.cpp b/plugins/obs-qsv11/QSV_Encoder_Internal.cpp index 17dac34a9..bd00d1ca1 100644 --- a/plugins/obs-qsv11/QSV_Encoder_Internal.cpp +++ b/plugins/obs-qsv11/QSV_Encoder_Internal.cpp @@ -61,8 +61,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include #include -#define do_log(level, format, ...) \ - blog(level, "[qsv encoder: '%s'] " format, "msdk_impl", ##__VA_ARGS__) +#define do_log(level, format, ...) blog(level, "[qsv encoder: '%s'] " format, "msdk_impl", ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -71,8 +70,7 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. mfxHDL QSV_Encoder_Internal::g_GFX_Handle = NULL; mfxU16 QSV_Encoder_Internal::g_numEncodersOpen = 0; -QSV_Encoder_Internal::QSV_Encoder_Internal(mfxVersion &version, - bool useTexAlloc) +QSV_Encoder_Internal::QSV_Encoder_Internal(mfxVersion &version, bool useTexAlloc) : m_pmfxSurfaces(NULL), m_pmfxENC(NULL), m_nSPSBufferSize(1024), @@ -95,28 +93,22 @@ QSV_Encoder_Internal::QSV_Encoder_Internal(mfxVersion &version, tempImpl.Type = MFX_VARIANT_TYPE_U32; tempImpl.Data.U32 = MFX_IMPL_TYPE_HARDWARE; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.Impl", tempImpl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.Impl", tempImpl); tempImpl.Type = MFX_VARIANT_TYPE_U32; tempImpl.Data.U32 = INTEL_VENDOR_ID; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.VendorID", tempImpl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.VendorID", tempImpl); #if defined(_WIN32) m_bUseD3D11 = true; m_bUseTexAlloc = true; tempImpl.Type = MFX_VARIANT_TYPE_U32; tempImpl.Data.U32 = MFX_ACCEL_MODE_VIA_D3D11; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", - tempImpl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", tempImpl); #else tempImpl.Type = MFX_VARIANT_TYPE_U32; tempImpl.Data.U32 = MFX_ACCEL_MODE_VIA_VAAPI; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", - tempImpl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", tempImpl); #endif sts = MFXCreateSession(loader, 0, &m_session); if (sts == MFX_ERR_NONE) { @@ -124,8 +116,7 @@ QSV_Encoder_Internal::QSV_Encoder_Internal(mfxVersion &version, MFXClose(m_session); MFXUnload(loader); - blog(LOG_INFO, "\tsurf: %s", - m_bUseTexAlloc ? "Texture" : "SysMem"); + blog(LOG_INFO, "\tsurf: %s", m_bUseTexAlloc ? "Texture" : "SysMem"); m_ver = version; return; @@ -144,11 +135,9 @@ mfxStatus QSV_Encoder_Internal::Open(qsv_param_t *pParams, enum qsv_codec codec) if (m_bUseD3D11 | m_bUseTexAlloc) // Use texture surface - sts = Initialize(m_ver, &m_session, &m_mfxAllocator, - &g_GFX_Handle, false, codec, &m_sessionData); + sts = Initialize(m_ver, &m_session, &m_mfxAllocator, &g_GFX_Handle, false, codec, &m_sessionData); else - sts = Initialize(m_ver, &m_session, NULL, NULL, false, codec, - &m_sessionData); + sts = Initialize(m_ver, &m_session, NULL, NULL, false, codec, &m_sessionData); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); @@ -179,15 +168,12 @@ mfxStatus QSV_Encoder_Internal::Open(qsv_param_t *pParams, enum qsv_codec codec) PRAGMA_WARN_PUSH PRAGMA_WARN_DEPRECATION -static inline bool HasOptimizedBRCSupport(const mfxPlatform &platform, - const mfxVersion &version, - mfxU16 rateControl) +static inline bool HasOptimizedBRCSupport(const mfxPlatform &platform, const mfxVersion &version, mfxU16 rateControl) { #if (MFX_VERSION_MAJOR >= 2 && MFX_VERSION_MINOR >= 12) || MFX_VERSION_MAJOR > 2 if ((version.Major >= 2 && version.Minor >= 12) || version.Major > 2) if (rateControl == MFX_RATECONTROL_CBR && - (platform.CodeName >= MFX_PLATFORM_LUNARLAKE && - platform.CodeName != MFX_PLATFORM_ALDERLAKE_N)) + (platform.CodeName >= MFX_PLATFORM_LUNARLAKE && platform.CodeName != MFX_PLATFORM_ALDERLAKE_N)) return true; #endif UNUSED_PARAMETER(platform); @@ -196,14 +182,12 @@ static inline bool HasOptimizedBRCSupport(const mfxPlatform &platform, return false; } -static inline bool HasAV1ScreenContentSupport(const mfxPlatform &platform, - const mfxVersion &version) +static inline bool HasAV1ScreenContentSupport(const mfxPlatform &platform, const mfxVersion &version) { #if (MFX_VERSION_MAJOR >= 2 && MFX_VERSION_MINOR >= 12) || MFX_VERSION_MAJOR > 2 // Platform enums needed are introduced in VPL version 2.12 if ((version.Major >= 2 && version.Minor >= 12) || version.Major > 2) - if (platform.CodeName >= MFX_PLATFORM_LUNARLAKE && - platform.CodeName != MFX_PLATFORM_ALDERLAKE_N && + if (platform.CodeName >= MFX_PLATFORM_LUNARLAKE && platform.CodeName != MFX_PLATFORM_ALDERLAKE_N && platform.CodeName != MFX_PLATFORM_ARROWLAKE) return true; #endif @@ -213,8 +197,7 @@ static inline bool HasAV1ScreenContentSupport(const mfxPlatform &platform, } PRAGMA_WARN_POP -mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, - enum qsv_codec codec) +mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, enum qsv_codec codec) { memset(&m_mfxEncParams, 0, sizeof(m_mfxEncParams)); @@ -270,25 +253,19 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, case MFX_RATECONTROL_CBR: m_mfxEncParams.mfx.TargetKbps = pParams->nTargetBitRate; - if (HasOptimizedBRCSupport(platform, m_ver, - pParams->nRateControl)) { - m_mfxEncParams.mfx.BufferSizeInKB = - (pParams->nTargetBitRate / 8) * 1; + if (HasOptimizedBRCSupport(platform, m_ver, pParams->nRateControl)) { + m_mfxEncParams.mfx.BufferSizeInKB = (pParams->nTargetBitRate / 8) * 1; } else { - m_mfxEncParams.mfx.BufferSizeInKB = - (pParams->nTargetBitRate / 8) * 2; + m_mfxEncParams.mfx.BufferSizeInKB = (pParams->nTargetBitRate / 8) * 2; } - m_mfxEncParams.mfx.InitialDelayInKB = - m_mfxEncParams.mfx.BufferSizeInKB / 2; + m_mfxEncParams.mfx.InitialDelayInKB = m_mfxEncParams.mfx.BufferSizeInKB / 2; break; case MFX_RATECONTROL_VBR: m_mfxEncParams.mfx.TargetKbps = pParams->nTargetBitRate; m_mfxEncParams.mfx.MaxKbps = pParams->nMaxBitRate; - m_mfxEncParams.mfx.BufferSizeInKB = - (pParams->nTargetBitRate / 8) * 2; - m_mfxEncParams.mfx.InitialDelayInKB = - (pParams->nTargetBitRate / 8) * 1; + m_mfxEncParams.mfx.BufferSizeInKB = (pParams->nTargetBitRate / 8) * 2; + m_mfxEncParams.mfx.InitialDelayInKB = (pParams->nTargetBitRate / 8) * 1; break; case MFX_RATECONTROL_CQP: m_mfxEncParams.mfx.QPI = pParams->nQPI; @@ -304,10 +281,8 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, m_mfxEncParams.AsyncDepth = pParams->nAsyncDepth; m_mfxEncParams.mfx.GopPicSize = - (pParams->nKeyIntSec) - ? (mfxU16)(pParams->nKeyIntSec * pParams->nFpsNum / - (float)pParams->nFpsDen) - : 240; + (pParams->nKeyIntSec) ? (mfxU16)(pParams->nKeyIntSec * pParams->nFpsNum / (float)pParams->nFpsDen) + : 240; memset(&m_co2, 0, sizeof(mfxExtCodingOption2)); m_co2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2; @@ -323,8 +298,7 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, PRAGMA_WARN_PUSH PRAGMA_WARN_DEPRECATION // LA VME/ENC case for older platforms - if (pParams->nLADEPTH && codec == QSV_CODEC_AVC && - m_mfxEncParams.mfx.LowPower != MFX_CODINGOPTION_ON && + if (pParams->nLADEPTH && codec == QSV_CODEC_AVC && m_mfxEncParams.mfx.LowPower != MFX_CODINGOPTION_ON && platform.CodeName >= MFX_PLATFORM_ICELAKE) { if (pParams->nRateControl == MFX_RATECONTROL_CBR) { pParams->nRateControl = MFX_RATECONTROL_LA_HRD; @@ -338,10 +312,8 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, PRAGMA_WARN_POP // LA VDENC case for newer platform, works only under CBR / VBR - if (pParams->nRateControl == MFX_RATECONTROL_CBR || - pParams->nRateControl == MFX_RATECONTROL_VBR) { - if (pParams->nLADEPTH && - m_mfxEncParams.mfx.LowPower == MFX_CODINGOPTION_ON) { + if (pParams->nRateControl == MFX_RATECONTROL_CBR || pParams->nRateControl == MFX_RATECONTROL_VBR) { + if (pParams->nLADEPTH && m_mfxEncParams.mfx.LowPower == MFX_CODINGOPTION_ON) { m_co2.LookAheadDepth = pParams->nLADEPTH; } } @@ -355,11 +327,9 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, m_co3.WinBRCSize = pParams->nFpsNum / pParams->nFpsDen; if (codec == QSV_CODEC_AVC || codec == QSV_CODEC_HEVC) { - m_co3.WinBRCMaxAvgKbps = - mfxU16(1.3 * pParams->nTargetBitRate); + m_co3.WinBRCMaxAvgKbps = mfxU16(1.3 * pParams->nTargetBitRate); } else if (codec == QSV_CODEC_AV1) { - m_co3.WinBRCMaxAvgKbps = - mfxU16(1.2 * pParams->nTargetBitRate); + m_co3.WinBRCMaxAvgKbps = mfxU16(1.2 * pParams->nTargetBitRate); } extendedBuffers.push_back((mfxExtBuffer *)&m_co3); } @@ -370,17 +340,14 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, m_ExtHEVCParam.Header.BufferId = MFX_EXTBUFF_HEVC_PARAM; m_ExtHEVCParam.Header.BufferSz = sizeof(m_ExtHEVCParam); m_ExtHEVCParam.PicWidthInLumaSamples = pParams->nWidth; - m_ExtHEVCParam.PicHeightInLumaSamples = - pParams->nHeight; - extendedBuffers.push_back( - (mfxExtBuffer *)&m_ExtHEVCParam); + m_ExtHEVCParam.PicHeightInLumaSamples = pParams->nHeight; + extendedBuffers.push_back((mfxExtBuffer *)&m_ExtHEVCParam); } } constexpr uint32_t pixelcount_4k = 3840 * 2160; /* If size is 4K+, set tile columns per frame to 2. */ - if (codec == QSV_CODEC_AV1 && - (pParams->nWidth * pParams->nHeight) >= pixelcount_4k) { + if (codec == QSV_CODEC_AV1 && (pParams->nWidth * pParams->nHeight) >= pixelcount_4k) { memset(&m_ExtAv1TileParam, 0, sizeof(m_ExtAv1TileParam)); m_ExtAv1TileParam.Header.BufferId = MFX_EXTBUFF_AV1_TILE_PARAM; m_ExtAv1TileParam.Header.BufferSz = sizeof(m_ExtAv1TileParam); @@ -390,17 +357,12 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, // AV1_SCREEN_CONTENT_TOOLS API is introduced in VPL version 2.11 #if (MFX_VERSION_MAJOR >= 2 && MFX_VERSION_MINOR >= 11) || MFX_VERSION_MAJOR > 2 - if (codec == QSV_CODEC_AV1 && - HasAV1ScreenContentSupport(platform, m_ver)) { - memset(&m_ExtAV1ScreenContentTools, 0, - sizeof(m_ExtAV1ScreenContentTools)); - m_ExtAV1ScreenContentTools.Header.BufferId = - MFX_EXTBUFF_AV1_SCREEN_CONTENT_TOOLS; - m_ExtAV1ScreenContentTools.Header.BufferSz = - sizeof(m_ExtAV1ScreenContentTools); + if (codec == QSV_CODEC_AV1 && HasAV1ScreenContentSupport(platform, m_ver)) { + memset(&m_ExtAV1ScreenContentTools, 0, sizeof(m_ExtAV1ScreenContentTools)); + m_ExtAV1ScreenContentTools.Header.BufferId = MFX_EXTBUFF_AV1_SCREEN_CONTENT_TOOLS; + m_ExtAV1ScreenContentTools.Header.BufferSz = sizeof(m_ExtAV1ScreenContentTools); m_ExtAV1ScreenContentTools.Palette = MFX_CODINGOPTION_ON; - extendedBuffers.push_back( - (mfxExtBuffer *)&m_ExtAV1ScreenContentTools); + extendedBuffers.push_back((mfxExtBuffer *)&m_ExtAV1ScreenContentTools); } #endif @@ -413,8 +375,7 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, m_ExtVideoSignalInfo.VideoFullRange = pParams->VideoFullRange; m_ExtVideoSignalInfo.ColourDescriptionPresent = 1; m_ExtVideoSignalInfo.ColourPrimaries = pParams->ColourPrimaries; - m_ExtVideoSignalInfo.TransferCharacteristics = - pParams->TransferCharacteristics; + m_ExtVideoSignalInfo.TransferCharacteristics = pParams->TransferCharacteristics; m_ExtVideoSignalInfo.MatrixCoefficients = pParams->MatrixCoefficients; extendedBuffers.push_back((mfxExtBuffer *)&m_ExtVideoSignalInfo); #endif @@ -423,69 +384,41 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, if (m_ver.Major >= 2) { // Chroma location is HEVC only if (codec == QSV_CODEC_HEVC) { - memset(&m_ExtChromaLocInfo, 0, - sizeof(m_ExtChromaLocInfo)); - m_ExtChromaLocInfo.Header.BufferId = - MFX_EXTBUFF_CHROMA_LOC_INFO; - m_ExtChromaLocInfo.Header.BufferSz = - sizeof(m_ExtChromaLocInfo); + memset(&m_ExtChromaLocInfo, 0, sizeof(m_ExtChromaLocInfo)); + m_ExtChromaLocInfo.Header.BufferId = MFX_EXTBUFF_CHROMA_LOC_INFO; + m_ExtChromaLocInfo.Header.BufferSz = sizeof(m_ExtChromaLocInfo); m_ExtChromaLocInfo.ChromaLocInfoPresentFlag = 1; - m_ExtChromaLocInfo.ChromaSampleLocTypeTopField = - pParams->ChromaSampleLocTypeTopField; - m_ExtChromaLocInfo.ChromaSampleLocTypeBottomField = - pParams->ChromaSampleLocTypeBottomField; - extendedBuffers.push_back( - (mfxExtBuffer *)&m_ExtChromaLocInfo); + m_ExtChromaLocInfo.ChromaSampleLocTypeTopField = pParams->ChromaSampleLocTypeTopField; + m_ExtChromaLocInfo.ChromaSampleLocTypeBottomField = pParams->ChromaSampleLocTypeBottomField; + extendedBuffers.push_back((mfxExtBuffer *)&m_ExtChromaLocInfo); } } // AV1 HDR meta data is now supported by VPL. if (pParams->MaxContentLightLevel > 0) { - memset(&m_ExtMasteringDisplayColourVolume, 0, - sizeof(m_ExtMasteringDisplayColourVolume)); - m_ExtMasteringDisplayColourVolume.Header.BufferId = - MFX_EXTBUFF_MASTERING_DISPLAY_COLOUR_VOLUME; - m_ExtMasteringDisplayColourVolume.Header.BufferSz = - sizeof(m_ExtMasteringDisplayColourVolume); - m_ExtMasteringDisplayColourVolume.InsertPayloadToggle = - MFX_PAYLOAD_IDR; - m_ExtMasteringDisplayColourVolume.DisplayPrimariesX[0] = - pParams->DisplayPrimariesX[0]; - m_ExtMasteringDisplayColourVolume.DisplayPrimariesX[1] = - pParams->DisplayPrimariesX[1]; - m_ExtMasteringDisplayColourVolume.DisplayPrimariesX[2] = - pParams->DisplayPrimariesX[2]; - m_ExtMasteringDisplayColourVolume.DisplayPrimariesY[0] = - pParams->DisplayPrimariesY[0]; - m_ExtMasteringDisplayColourVolume.DisplayPrimariesY[1] = - pParams->DisplayPrimariesY[1]; - m_ExtMasteringDisplayColourVolume.DisplayPrimariesY[2] = - pParams->DisplayPrimariesY[2]; - m_ExtMasteringDisplayColourVolume.WhitePointX = - pParams->WhitePointX; - m_ExtMasteringDisplayColourVolume.WhitePointY = - pParams->WhitePointY; - m_ExtMasteringDisplayColourVolume.MaxDisplayMasteringLuminance = - pParams->MaxDisplayMasteringLuminance; - m_ExtMasteringDisplayColourVolume.MinDisplayMasteringLuminance = - pParams->MinDisplayMasteringLuminance; - extendedBuffers.push_back( - (mfxExtBuffer *)&m_ExtMasteringDisplayColourVolume); + memset(&m_ExtMasteringDisplayColourVolume, 0, sizeof(m_ExtMasteringDisplayColourVolume)); + m_ExtMasteringDisplayColourVolume.Header.BufferId = MFX_EXTBUFF_MASTERING_DISPLAY_COLOUR_VOLUME; + m_ExtMasteringDisplayColourVolume.Header.BufferSz = sizeof(m_ExtMasteringDisplayColourVolume); + m_ExtMasteringDisplayColourVolume.InsertPayloadToggle = MFX_PAYLOAD_IDR; + m_ExtMasteringDisplayColourVolume.DisplayPrimariesX[0] = pParams->DisplayPrimariesX[0]; + m_ExtMasteringDisplayColourVolume.DisplayPrimariesX[1] = pParams->DisplayPrimariesX[1]; + m_ExtMasteringDisplayColourVolume.DisplayPrimariesX[2] = pParams->DisplayPrimariesX[2]; + m_ExtMasteringDisplayColourVolume.DisplayPrimariesY[0] = pParams->DisplayPrimariesY[0]; + m_ExtMasteringDisplayColourVolume.DisplayPrimariesY[1] = pParams->DisplayPrimariesY[1]; + m_ExtMasteringDisplayColourVolume.DisplayPrimariesY[2] = pParams->DisplayPrimariesY[2]; + m_ExtMasteringDisplayColourVolume.WhitePointX = pParams->WhitePointX; + m_ExtMasteringDisplayColourVolume.WhitePointY = pParams->WhitePointY; + m_ExtMasteringDisplayColourVolume.MaxDisplayMasteringLuminance = pParams->MaxDisplayMasteringLuminance; + m_ExtMasteringDisplayColourVolume.MinDisplayMasteringLuminance = pParams->MinDisplayMasteringLuminance; + extendedBuffers.push_back((mfxExtBuffer *)&m_ExtMasteringDisplayColourVolume); - memset(&m_ExtContentLightLevelInfo, 0, - sizeof(m_ExtContentLightLevelInfo)); - m_ExtContentLightLevelInfo.Header.BufferId = - MFX_EXTBUFF_CONTENT_LIGHT_LEVEL_INFO; - m_ExtContentLightLevelInfo.Header.BufferSz = - sizeof(m_ExtContentLightLevelInfo); - m_ExtContentLightLevelInfo.InsertPayloadToggle = - MFX_PAYLOAD_IDR; - m_ExtContentLightLevelInfo.MaxContentLightLevel = - pParams->MaxContentLightLevel; - m_ExtContentLightLevelInfo.MaxPicAverageLightLevel = - pParams->MaxPicAverageLightLevel; - extendedBuffers.push_back( - (mfxExtBuffer *)&m_ExtContentLightLevelInfo); + memset(&m_ExtContentLightLevelInfo, 0, sizeof(m_ExtContentLightLevelInfo)); + m_ExtContentLightLevelInfo.Header.BufferId = MFX_EXTBUFF_CONTENT_LIGHT_LEVEL_INFO; + m_ExtContentLightLevelInfo.Header.BufferSz = sizeof(m_ExtContentLightLevelInfo); + m_ExtContentLightLevelInfo.InsertPayloadToggle = MFX_PAYLOAD_IDR; + m_ExtContentLightLevelInfo.MaxContentLightLevel = pParams->MaxContentLightLevel; + m_ExtContentLightLevelInfo.MaxPicAverageLightLevel = pParams->MaxPicAverageLightLevel; + extendedBuffers.push_back((mfxExtBuffer *)&m_ExtContentLightLevelInfo); } // Width must be a multiple of 16 @@ -553,8 +486,7 @@ mfxStatus QSV_Encoder_Internal::AllocateSurfaces() // Allocate required surfaces if (m_bUseTexAlloc) { - sts = m_mfxAllocator.Alloc(m_mfxAllocator.pthis, &EncRequest, - &m_mfxResponse); + sts = m_mfxAllocator.Alloc(m_mfxAllocator.pthis, &EncRequest, &m_mfxResponse); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); m_nSurfNum = m_mfxResponse.NumFrameActual; @@ -565,9 +497,7 @@ mfxStatus QSV_Encoder_Internal::AllocateSurfaces() for (int i = 0; i < m_nSurfNum; i++) { m_pmfxSurfaces[i] = new mfxFrameSurface1; memset(m_pmfxSurfaces[i], 0, sizeof(mfxFrameSurface1)); - memcpy(&(m_pmfxSurfaces[i]->Info), - &(m_mfxEncParams.mfx.FrameInfo), - sizeof(mfxFrameInfo)); + memcpy(&(m_pmfxSurfaces[i]->Info), &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo)); m_pmfxSurfaces[i]->Data.MemId = m_mfxResponse.mids[i]; } } else { @@ -581,15 +511,12 @@ mfxStatus QSV_Encoder_Internal::AllocateSurfaces() for (int i = 0; i < m_nSurfNum; i++) { m_pmfxSurfaces[i] = new mfxFrameSurface1; memset(m_pmfxSurfaces[i], 0, sizeof(mfxFrameSurface1)); - memcpy(&(m_pmfxSurfaces[i]->Info), - &(m_mfxEncParams.mfx.FrameInfo), - sizeof(mfxFrameInfo)); + memcpy(&(m_pmfxSurfaces[i]->Info), &(m_mfxEncParams.mfx.FrameInfo), sizeof(mfxFrameInfo)); mfxU8 *pSurface = (mfxU8 *)new mfxU8[surfaceSize]; m_pmfxSurfaces[i]->Data.Y = pSurface; m_pmfxSurfaces[i]->Data.U = pSurface + width * height; - m_pmfxSurfaces[i]->Data.V = - pSurface + width * height + 1; + m_pmfxSurfaces[i]->Data.V = pSurface + width * height + 1; m_pmfxSurfaces[i]->Data.Pitch = width; } } @@ -641,8 +568,7 @@ mfxStatus QSV_Encoder_Internal::GetVideoParam(enum qsv_codec codec) return sts; } -void QSV_Encoder_Internal::GetSPSPPS(mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, - mfxU16 *pnSPSBuf, mfxU16 *pnPPSBuf) +void QSV_Encoder_Internal::GetSPSPPS(mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, mfxU16 *pnSPSBuf, mfxU16 *pnPPSBuf) { *pSPSBuf = m_SPSBuffer; *pPPSBuf = m_PPSBuffer; @@ -650,8 +576,7 @@ void QSV_Encoder_Internal::GetSPSPPS(mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, *pnPPSBuf = m_nPPSBufferSize; } -void QSV_Encoder_Internal::GetVpsSpsPps(mfxU8 **pVPSBuf, mfxU8 **pSPSBuf, - mfxU8 **pPPSBuf, mfxU16 *pnVPSBuf, +void QSV_Encoder_Internal::GetVpsSpsPps(mfxU8 **pVPSBuf, mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, mfxU16 *pnVPSBuf, mfxU16 *pnSPSBuf, mfxU16 *pnPPSBuf) { *pVPSBuf = m_VPSBuffer; @@ -673,15 +598,12 @@ mfxStatus QSV_Encoder_Internal::InitBitstream() memset(m_pTaskPool, 0, sizeof(Task) * m_nTaskPool); for (int i = 0; i < m_nTaskPool; i++) { - m_pTaskPool[i].mfxBS.MaxLength = - m_parameter.mfx.BufferSizeInKB * 1000; - m_pTaskPool[i].mfxBS.Data = - new mfxU8[m_pTaskPool[i].mfxBS.MaxLength]; + m_pTaskPool[i].mfxBS.MaxLength = m_parameter.mfx.BufferSizeInKB * 1000; + m_pTaskPool[i].mfxBS.Data = new mfxU8[m_pTaskPool[i].mfxBS.MaxLength]; m_pTaskPool[i].mfxBS.DataOffset = 0; m_pTaskPool[i].mfxBS.DataLength = 0; - MSDK_CHECK_POINTER(m_pTaskPool[i].mfxBS.Data, - MFX_ERR_MEMORY_ALLOC); + MSDK_CHECK_POINTER(m_pTaskPool[i].mfxBS.Data, MFX_ERR_MEMORY_ALLOC); } memset(&m_outBitstream, 0, sizeof(mfxBitstream)); @@ -695,8 +617,7 @@ mfxStatus QSV_Encoder_Internal::InitBitstream() return MFX_ERR_NONE; } -mfxStatus QSV_Encoder_Internal::LoadP010(mfxFrameSurface1 *pSurface, - uint8_t *pDataY, uint8_t *pDataUV, +mfxStatus QSV_Encoder_Internal::LoadP010(mfxFrameSurface1 *pSurface, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV) { mfxU16 w, h, i, pitch; @@ -730,8 +651,7 @@ mfxStatus QSV_Encoder_Internal::LoadP010(mfxFrameSurface1 *pSurface, return MFX_ERR_NONE; } -mfxStatus QSV_Encoder_Internal::LoadNV12(mfxFrameSurface1 *pSurface, - uint8_t *pDataY, uint8_t *pDataUV, +mfxStatus QSV_Encoder_Internal::LoadNV12(mfxFrameSurface1 *pSurface, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV) { mfxU16 w, h, i, pitch; @@ -773,8 +693,7 @@ int QSV_Encoder_Internal::GetFreeTaskIndex(Task *pTaskPool, mfxU16 nPoolSize) return MFX_ERR_NOT_FOUND; } -mfxStatus QSV_Encoder_Internal::Encode(uint64_t ts, uint8_t *pDataY, - uint8_t *pDataUV, uint32_t strideY, +mfxStatus QSV_Encoder_Internal::Encode(uint64_t ts, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV, mfxBitstream **pBS) { mfxStatus sts = MFX_ERR_NONE; @@ -796,13 +715,11 @@ mfxStatus QSV_Encoder_Internal::Encode(uint64_t ts, uint8_t *pDataY, while (MFX_ERR_NOT_FOUND == nTaskIdx || MFX_ERR_NOT_FOUND == nSurfIdx) { // No more free tasks or surfaces, need to sync - sts = MFXVideoCORE_SyncOperation( - m_session, m_pTaskPool[m_nFirstSyncTask].syncp, 60000); + sts = MFXVideoCORE_SyncOperation(m_session, m_pTaskPool[m_nFirstSyncTask].syncp, 60000); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); mfxU8 *pTemp = m_outBitstream.Data; - memcpy(&m_outBitstream, &m_pTaskPool[m_nFirstSyncTask].mfxBS, - sizeof(mfxBitstream)); + memcpy(&m_outBitstream, &m_pTaskPool[m_nFirstSyncTask].mfxBS, sizeof(mfxBitstream)); m_pTaskPool[m_nFirstSyncTask].mfxBS.Data = pTemp; m_pTaskPool[m_nFirstSyncTask].mfxBS.DataLength = 0; @@ -830,37 +747,30 @@ mfxStatus QSV_Encoder_Internal::Encode(uint64_t ts, uint8_t *pDataY, mfxFrameSurface1 *pSurface = m_pmfxSurfaces[nSurfIdx]; if (m_bUseTexAlloc) { - sts = m_mfxAllocator.Lock(m_mfxAllocator.pthis, - pSurface->Data.MemId, - &(pSurface->Data)); + sts = m_mfxAllocator.Lock(m_mfxAllocator.pthis, pSurface->Data.MemId, &(pSurface->Data)); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); } - sts = (pSurface->Info.FourCC == MFX_FOURCC_P010) - ? LoadP010(pSurface, pDataY, pDataUV, strideY, strideUV) - : LoadNV12(pSurface, pDataY, pDataUV, strideY, strideUV); + sts = (pSurface->Info.FourCC == MFX_FOURCC_P010) ? LoadP010(pSurface, pDataY, pDataUV, strideY, strideUV) + : LoadNV12(pSurface, pDataY, pDataUV, strideY, strideUV); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); pSurface->Data.TimeStamp = ts; if (m_bUseTexAlloc) { - sts = m_mfxAllocator.Unlock(m_mfxAllocator.pthis, - pSurface->Data.MemId, - &(pSurface->Data)); + sts = m_mfxAllocator.Unlock(m_mfxAllocator.pthis, pSurface->Data.MemId, &(pSurface->Data)); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); } for (;;) { // Encode a frame asynchronously (returns immediately) - sts = m_pmfxENC->EncodeFrameAsync(&m_ctrl, pSurface, - &m_pTaskPool[nTaskIdx].mfxBS, + sts = m_pmfxENC->EncodeFrameAsync(&m_ctrl, pSurface, &m_pTaskPool[nTaskIdx].mfxBS, &m_pTaskPool[nTaskIdx].syncp); if (MFX_ERR_NONE < sts && !m_pTaskPool[nTaskIdx].syncp) { // Repeat the call if warning and no output if (MFX_WRN_DEVICE_BUSY == sts) - MSDK_SLEEP( - 1); // Wait if device is busy, then repeat the same call + MSDK_SLEEP(1); // Wait if device is busy, then repeat the same call } else if (MFX_ERR_NONE < sts && m_pTaskPool[nTaskIdx].syncp) { sts = MFX_ERR_NONE; // Ignore warnings if output is available break; @@ -874,9 +784,7 @@ mfxStatus QSV_Encoder_Internal::Encode(uint64_t ts, uint8_t *pDataY, return sts; } -mfxStatus QSV_Encoder_Internal::Encode_tex(uint64_t ts, void *tex, - uint64_t lock_key, - uint64_t *next_key, +mfxStatus QSV_Encoder_Internal::Encode_tex(uint64_t ts, void *tex, uint64_t lock_key, uint64_t *next_key, mfxBitstream **pBS) { mfxStatus sts = MFX_ERR_NONE; @@ -886,13 +794,11 @@ mfxStatus QSV_Encoder_Internal::Encode_tex(uint64_t ts, void *tex, while (MFX_ERR_NOT_FOUND == nTaskIdx || MFX_ERR_NOT_FOUND == nSurfIdx) { // No more free tasks or surfaces, need to sync - sts = MFXVideoCORE_SyncOperation( - m_session, m_pTaskPool[m_nFirstSyncTask].syncp, 60000); + sts = MFXVideoCORE_SyncOperation(m_session, m_pTaskPool[m_nFirstSyncTask].syncp, 60000); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); mfxU8 *pTemp = m_outBitstream.Data; - memcpy(&m_outBitstream, &m_pTaskPool[m_nFirstSyncTask].mfxBS, - sizeof(mfxBitstream)); + memcpy(&m_outBitstream, &m_pTaskPool[m_nFirstSyncTask].mfxBS, sizeof(mfxBitstream)); m_pTaskPool[m_nFirstSyncTask].mfxBS.Data = pTemp; m_pTaskPool[m_nFirstSyncTask].mfxBS.DataLength = 0; @@ -910,22 +816,19 @@ mfxStatus QSV_Encoder_Internal::Encode_tex(uint64_t ts, void *tex, pSurface->Data.TimeStamp = ts; if (m_bUseTexAlloc) { // mfxU64 isn't consistent with stdint, requiring a cast to be multi-platform. - sts = simple_copytex(m_mfxAllocator.pthis, pSurface->Data.MemId, - tex, lock_key, (mfxU64 *)next_key); + sts = simple_copytex(m_mfxAllocator.pthis, pSurface->Data.MemId, tex, lock_key, (mfxU64 *)next_key); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); } for (;;) { // Encode a frame asynchronously (returns immediately) - sts = m_pmfxENC->EncodeFrameAsync(&m_ctrl, pSurface, - &m_pTaskPool[nTaskIdx].mfxBS, + sts = m_pmfxENC->EncodeFrameAsync(&m_ctrl, pSurface, &m_pTaskPool[nTaskIdx].mfxBS, &m_pTaskPool[nTaskIdx].syncp); if (MFX_ERR_NONE < sts && !m_pTaskPool[nTaskIdx].syncp) { // Repeat the call if warning and no output if (MFX_WRN_DEVICE_BUSY == sts) - MSDK_SLEEP( - 1); // Wait if device is busy, then repeat the same call + MSDK_SLEEP(1); // Wait if device is busy, then repeat the same call } else if (MFX_ERR_NONE < sts && m_pTaskPool[nTaskIdx].syncp) { sts = MFX_ERR_NONE; // Ignore warnings if output is available break; @@ -944,8 +847,7 @@ mfxStatus QSV_Encoder_Internal::Drain() mfxStatus sts = MFX_ERR_NONE; while (m_pTaskPool && m_pTaskPool[m_nFirstSyncTask].syncp) { - sts = MFXVideoCORE_SyncOperation( - m_session, m_pTaskPool[m_nFirstSyncTask].syncp, 60000); + sts = MFXVideoCORE_SyncOperation(m_session, m_pTaskPool[m_nFirstSyncTask].syncp, 60000); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); m_pTaskPool[m_nFirstSyncTask].syncp = NULL; @@ -1004,8 +906,7 @@ mfxStatus QSV_Encoder_Internal::ClearData() return sts; } -mfxStatus QSV_Encoder_Internal::Reset(qsv_param_t *pParams, - enum qsv_codec codec) +mfxStatus QSV_Encoder_Internal::Reset(qsv_param_t *pParams, enum qsv_codec codec) { mfxStatus sts = ClearData(); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); @@ -1016,8 +917,7 @@ mfxStatus QSV_Encoder_Internal::Reset(qsv_param_t *pParams, return sts; } -void QSV_Encoder_Internal::AddROI(mfxU32 left, mfxU32 top, mfxU32 right, - mfxU32 bottom, mfxI16 delta) +void QSV_Encoder_Internal::AddROI(mfxU32 left, mfxU32 top, mfxU32 right, mfxU32 bottom, mfxI16 delta) { if (m_roi.NumROI == 256) { warn("Maximum number of ROIs hit, ignoring additional ROI!"); diff --git a/plugins/obs-qsv11/QSV_Encoder_Internal.h b/plugins/obs-qsv11/QSV_Encoder_Internal.h index 3fd06e6d3..550cf18d5 100644 --- a/plugins/obs-qsv11/QSV_Encoder_Internal.h +++ b/plugins/obs-qsv11/QSV_Encoder_Internal.h @@ -68,21 +68,17 @@ public: ~QSV_Encoder_Internal(); mfxStatus Open(qsv_param_t *pParams, enum qsv_codec codec); - void GetSPSPPS(mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, mfxU16 *pnSPSBuf, - mfxU16 *pnPPSBuf); - void GetVpsSpsPps(mfxU8 **pVPSBuf, mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, - mfxU16 *pnVPSBuf, mfxU16 *pnSPSBuf, mfxU16 *pnPPSBuf); - mfxStatus Encode(uint64_t ts, uint8_t *pDataY, uint8_t *pDataUV, - uint32_t strideY, uint32_t strideUV, + void GetSPSPPS(mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, mfxU16 *pnSPSBuf, mfxU16 *pnPPSBuf); + void GetVpsSpsPps(mfxU8 **pVPSBuf, mfxU8 **pSPSBuf, mfxU8 **pPPSBuf, mfxU16 *pnVPSBuf, mfxU16 *pnSPSBuf, + mfxU16 *pnPPSBuf); + mfxStatus Encode(uint64_t ts, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV, mfxBitstream **pBS); - mfxStatus Encode_tex(uint64_t ts, void *tex, uint64_t lock_key, - uint64_t *next_key, mfxBitstream **pBS); + mfxStatus Encode_tex(uint64_t ts, void *tex, uint64_t lock_key, uint64_t *next_key, mfxBitstream **pBS); mfxStatus ClearData(); mfxStatus Reset(qsv_param_t *pParams, enum qsv_codec codec); mfxStatus ReconfigureEncoder(); bool UpdateParams(qsv_param_t *pParams); - void AddROI(mfxU32 left, mfxU32 top, mfxU32 right, mfxU32 bottom, - mfxI16 delta); + void AddROI(mfxU32 left, mfxU32 top, mfxU32 right, mfxU32 bottom, mfxI16 delta); void ClearROI(); protected: @@ -90,11 +86,9 @@ protected: mfxStatus AllocateSurfaces(); mfxStatus GetVideoParam(enum qsv_codec codec); mfxStatus InitBitstream(); - mfxStatus LoadNV12(mfxFrameSurface1 *pSurface, uint8_t *pDataY, - uint8_t *pDataUV, uint32_t strideY, + mfxStatus LoadNV12(mfxFrameSurface1 *pSurface, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV); - mfxStatus LoadP010(mfxFrameSurface1 *pSurface, uint8_t *pDataY, - uint8_t *pDataUV, uint32_t strideY, + mfxStatus LoadP010(mfxFrameSurface1 *pSurface, uint8_t *pDataY, uint8_t *pDataUV, uint32_t strideY, uint32_t strideUV); mfxStatus Drain(); int GetFreeTaskIndex(Task *pTaskPool, mfxU16 nPoolSize); @@ -137,8 +131,7 @@ private: bool m_bUseD3D11; bool m_bUseTexAlloc; static mfxU16 g_numEncodersOpen; - static mfxHDL - g_GFX_Handle; // we only want one handle for all instances to use; + static mfxHDL g_GFX_Handle; // we only want one handle for all instances to use; mfxEncodeCtrl m_ctrl; mfxExtEncoderROI m_roi; diff --git a/plugins/obs-qsv11/common_directx11.cpp b/plugins/obs-qsv11/common_directx11.cpp index 8793cbc09..013a82175 100644 --- a/plugins/obs-qsv11/common_directx11.cpp +++ b/plugins/obs-qsv11/common_directx11.cpp @@ -22,10 +22,7 @@ typedef struct { const struct { mfxIMPL impl; // actual implementation mfxU32 adapterID; // device adapter number -} implTypes[] = {{MFX_IMPL_HARDWARE, 0}, - {MFX_IMPL_HARDWARE2, 1}, - {MFX_IMPL_HARDWARE3, 2}, - {MFX_IMPL_HARDWARE4, 3}}; +} implTypes[] = {{MFX_IMPL_HARDWARE, 0}, {MFX_IMPL_HARDWARE2, 1}, {MFX_IMPL_HARDWARE3, 2}, {MFX_IMPL_HARDWARE4, 3}}; // ================================================================= // DirectX functionality required to manage DX11 device and surfaces @@ -38,8 +35,7 @@ IDXGIAdapter *GetIntelDeviceAdapterHandle(mfxSession session) MFXQueryIMPL(session, &impl); - mfxIMPL baseImpl = MFX_IMPL_BASETYPE( - impl); // Extract Media SDK base implementation type + mfxIMPL baseImpl = MFX_IMPL_BASETYPE(impl); // Extract Media SDK base implementation type // get corresponding adapter number for (mfxU8 i = 0; i < sizeof(implTypes) / sizeof(implTypes[0]); i++) { @@ -49,8 +45,7 @@ IDXGIAdapter *GetIntelDeviceAdapterHandle(mfxSession session) } } - HRESULT hres = CreateDXGIFactory1(__uuidof(IDXGIFactory2), - (void **)(&g_pDXGIFactory)); + HRESULT hres = CreateDXGIFactory1(__uuidof(IDXGIFactory2), (void **)(&g_pDXGIFactory)); if (FAILED(hres)) return NULL; @@ -63,19 +58,16 @@ IDXGIAdapter *GetIntelDeviceAdapterHandle(mfxSession session) } // Create HW device context -mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, - bool bCreateSharedHandles) +mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, bool bCreateSharedHandles) { //Note: not using bCreateSharedHandles for DX11 -- for API consistency only - hWnd; // Window handle not required by DX11 since we do not showcase rendering. + hWnd; // Window handle not required by DX11 since we do not showcase rendering. bCreateSharedHandles; // For rendering, not used here. Just for consistencies sake. HRESULT hres = S_OK; - static D3D_FEATURE_LEVEL FeatureLevels[] = {D3D_FEATURE_LEVEL_11_1, - D3D_FEATURE_LEVEL_11_0, - D3D_FEATURE_LEVEL_10_1, - D3D_FEATURE_LEVEL_10_0}; + static D3D_FEATURE_LEVEL FeatureLevels[] = {D3D_FEATURE_LEVEL_11_1, D3D_FEATURE_LEVEL_11_0, + D3D_FEATURE_LEVEL_10_1, D3D_FEATURE_LEVEL_10_0}; D3D_FEATURE_LEVEL pFeatureLevelsOut; g_pAdapter = GetIntelDeviceAdapterHandle(session); @@ -85,12 +77,9 @@ mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, UINT dxFlags = 0; //UINT dxFlags = D3D11_CREATE_DEVICE_DEBUG; - hres = D3D11CreateDevice( - g_pAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, dxFlags, - FeatureLevels, - (sizeof(FeatureLevels) / sizeof(FeatureLevels[0])), - D3D11_SDK_VERSION, &g_pD3D11Device, &pFeatureLevelsOut, - &g_pD3D11Ctx); + hres = D3D11CreateDevice(g_pAdapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, dxFlags, FeatureLevels, + (sizeof(FeatureLevels) / sizeof(FeatureLevels[0])), D3D11_SDK_VERSION, &g_pD3D11Device, + &pFeatureLevelsOut, &g_pD3D11Ctx); if (FAILED(hres)) return MFX_ERR_DEVICE_FAILED; @@ -154,8 +143,7 @@ void ClearRGBSurfaceD3D(mfxMemId memId) // // Intel Media SDK memory allocator entrypoints.... // -mfxStatus _simple_alloc(mfxFrameAllocRequest *request, - mfxFrameAllocResponse *response) +mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *response) { HRESULT hRes; @@ -167,9 +155,7 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, format = DXGI_FORMAT_B8G8R8A8_UNORM; else if (MFX_FOURCC_YUY2 == request->Info.FourCC) format = DXGI_FORMAT_YUY2; - else if (MFX_FOURCC_P8 == - request->Info - .FourCC) //|| MFX_FOURCC_P8_TEXTURE == request->Info.FourCC + else if (MFX_FOURCC_P8 == request->Info.FourCC) //|| MFX_FOURCC_P8_TEXTURE == request->Info.FourCC format = DXGI_FORMAT_P8; else if (MFX_FOURCC_P010 == request->Info.FourCC) format = DXGI_FORMAT_P010; @@ -181,8 +167,7 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, // Allocate custom container to keep texture and stage buffers for each surface // Container also stores the intended read and/or write operation. - CustomMemId **mids = (CustomMemId **)calloc(request->NumFrameSuggested, - sizeof(CustomMemId *)); + CustomMemId **mids = (CustomMemId **)calloc(request->NumFrameSuggested, sizeof(CustomMemId *)); if (!mids) return MFX_ERR_MEMORY_ALLOC; @@ -191,8 +176,7 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, if (!mids[i]) { return MFX_ERR_MEMORY_ALLOC; } - mids[i]->rw = request->Type & - 0xF000; // Set intended read/write operation + mids[i]->rw = request->Type & 0xF000; // Set intended read/write operation } request->Type = request->Type & 0x0FFF; @@ -232,16 +216,14 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, desc.MiscFlags = 0; //desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; - if ((MFX_MEMTYPE_FROM_VPPIN & request->Type) && - (DXGI_FORMAT_B8G8R8A8_UNORM == desc.Format)) { + if ((MFX_MEMTYPE_FROM_VPPIN & request->Type) && (DXGI_FORMAT_B8G8R8A8_UNORM == desc.Format)) { desc.BindFlags = D3D11_BIND_RENDER_TARGET; if (desc.ArraySize > 2) return MFX_ERR_MEMORY_ALLOC; } if ((MFX_MEMTYPE_FROM_VPPOUT & request->Type) || - (MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET & - request->Type)) { + (MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET & request->Type)) { desc.BindFlags = D3D11_BIND_RENDER_TARGET; if (desc.ArraySize > 2) return MFX_ERR_MEMORY_ALLOC; @@ -253,10 +235,8 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, ID3D11Texture2D *pTexture2D; // Create surface textures - for (size_t i = 0; - i < request->NumFrameSuggested / desc.ArraySize; i++) { - hRes = g_pD3D11Device->CreateTexture2D(&desc, NULL, - &pTexture2D); + for (size_t i = 0; i < request->NumFrameSuggested / desc.ArraySize; i++) { + hRes = g_pD3D11Device->CreateTexture2D(&desc, NULL, &pTexture2D); if (FAILED(hRes)) return MFX_ERR_MEMORY_ALLOC; @@ -266,16 +246,14 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, desc.ArraySize = 1; desc.Usage = D3D11_USAGE_STAGING; - desc.CPUAccessFlags = - D3D11_CPU_ACCESS_READ; // | D3D11_CPU_ACCESS_WRITE; + desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ; // | D3D11_CPU_ACCESS_WRITE; desc.BindFlags = 0; desc.MiscFlags = 0; //desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; // Create surface staging textures for (size_t i = 0; i < request->NumFrameSuggested; i++) { - hRes = g_pD3D11Device->CreateTexture2D(&desc, NULL, - &pTexture2D); + hRes = g_pD3D11Device->CreateTexture2D(&desc, NULL, &pTexture2D); if (FAILED(hRes)) return MFX_ERR_MEMORY_ALLOC; @@ -290,8 +268,7 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, return MFX_ERR_NONE; } -mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, - mfxFrameAllocResponse *response) +mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllocResponse *response) { mfxStatus sts = MFX_ERR_NONE; @@ -299,8 +276,7 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, return MFX_ERR_UNSUPPORTED; if (allocDecodeResponses.find(pthis) != allocDecodeResponses.end() && - MFX_MEMTYPE_EXTERNAL_FRAME & request->Type && - MFX_MEMTYPE_FROM_DECODE & request->Type) { + MFX_MEMTYPE_EXTERNAL_FRAME & request->Type && MFX_MEMTYPE_FROM_DECODE & request->Type) { // Memory for this request was already allocated during manual allocation stage. Return saved response // When decode acceleration device (DXVA) is created it requires a list of d3d surfaces to be passed. // Therefore Media SDK will ask for the surface info/mids again at Init() stage, thus requiring us to return the saved response @@ -311,8 +287,7 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, sts = _simple_alloc(request, response); if (MFX_ERR_NONE == sts) { - if (MFX_MEMTYPE_EXTERNAL_FRAME & request->Type && - MFX_MEMTYPE_FROM_DECODE & request->Type) { + if (MFX_MEMTYPE_EXTERNAL_FRAME & request->Type && MFX_MEMTYPE_FROM_DECODE & request->Type) { // Decode alloc response handling allocDecodeResponses[pthis] = *response; allocDecodeRefCount[pthis]++; @@ -343,22 +318,18 @@ mfxStatus simple_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) UINT mapFlags = D3D11_MAP_FLAG_DO_NOT_WAIT; if (NULL == pStage) { - hRes = g_pD3D11Ctx->Map(pSurface, 0, mapType, mapFlags, - &lockedRect); + hRes = g_pD3D11Ctx->Map(pSurface, 0, mapType, mapFlags, &lockedRect); desc.Format = DXGI_FORMAT_P8; } else { pSurface->GetDesc(&desc); // copy data only in case of user wants to read from stored surface if (memId->rw & WILL_READ) - g_pD3D11Ctx->CopySubresourceRegion(pStage, 0, 0, 0, 0, - pSurface, 0, NULL); + g_pD3D11Ctx->CopySubresourceRegion(pStage, 0, 0, 0, 0, pSurface, 0, NULL); do { - hRes = g_pD3D11Ctx->Map(pStage, 0, mapType, mapFlags, - &lockedRect); - if (S_OK != hRes && - DXGI_ERROR_WAS_STILL_DRAWING != hRes) + hRes = g_pD3D11Ctx->Map(pStage, 0, mapType, mapFlags, &lockedRect); + if (S_OK != hRes && DXGI_ERROR_WAS_STILL_DRAWING != hRes) return MFX_ERR_LOCK_MEMORY; } while (DXGI_ERROR_WAS_STILL_DRAWING == hRes); } @@ -370,8 +341,7 @@ mfxStatus simple_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) case DXGI_FORMAT_NV12: ptr->Pitch = (mfxU16)lockedRect.RowPitch; ptr->Y = (mfxU8 *)lockedRect.pData; - ptr->U = (mfxU8 *)lockedRect.pData + - desc.Height * lockedRect.RowPitch; + ptr->U = (mfxU8 *)lockedRect.pData + desc.Height * lockedRect.RowPitch; ptr->V = ptr->U + 1; break; case DXGI_FORMAT_B8G8R8A8_UNORM: @@ -397,8 +367,7 @@ mfxStatus simple_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) ptr->Pitch = (mfxU16)lockedRect.RowPitch; ptr->PitchHigh = 0; ptr->Y = (mfxU8 *)lockedRect.pData; - ptr->U = (mfxU8 *)lockedRect.pData + - desc.Height * lockedRect.RowPitch; + ptr->U = (mfxU8 *)lockedRect.pData + desc.Height * lockedRect.RowPitch; ptr->V = ptr->U + 2; break; default: @@ -422,8 +391,7 @@ mfxStatus simple_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) g_pD3D11Ctx->Unmap(pStage, 0); // copy data only in case of user wants to write to stored surface if (memId->rw & WILL_WRITE) - g_pD3D11Ctx->CopySubresourceRegion(pSurface, 0, 0, 0, 0, - pStage, 0, NULL); + g_pD3D11Ctx->CopySubresourceRegion(pSurface, 0, 0, 0, 0, pStage, 0, NULL); } if (ptr) { @@ -435,8 +403,7 @@ mfxStatus simple_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) return MFX_ERR_NONE; } -mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, - mfxU64 *next_key) +mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, mfxU64 *next_key) { pthis; // To suppress warning for this unused parameter struct encoder_texture *ptex = (struct encoder_texture *)tex; @@ -448,8 +415,7 @@ mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, ID3D11Texture2D *input_tex; HRESULT hr; - hr = g_pD3D11Device->OpenSharedResource((HANDLE)(uintptr_t)ptex->handle, - IID_ID3D11Texture2D, + hr = g_pD3D11Device->OpenSharedResource((HANDLE)(uintptr_t)ptex->handle, IID_ID3D11Texture2D, (void **)&input_tex); if (FAILED(hr)) { return MFX_ERR_INVALID_HANDLE; @@ -468,8 +434,7 @@ mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, D3D11_TEXTURE2D_DESC desc = {0}; input_tex->GetDesc(&desc); D3D11_BOX SrcBox = {0, 0, 0, desc.Width, desc.Height, 1}; - g_pD3D11Ctx->CopySubresourceRegion(pSurface, 0, 0, 0, 0, input_tex, 0, - &SrcBox); + g_pD3D11Ctx->CopySubresourceRegion(pSurface, 0, 0, 0, 0, input_tex, 0, &SrcBox); km->ReleaseSync(*next_key); @@ -500,12 +465,9 @@ mfxStatus _simple_free(mfxFrameAllocResponse *response) if (response->mids) { for (mfxU32 i = 0; i < response->NumFrameActual; i++) { if (response->mids[i]) { - CustomMemId *mid = - (CustomMemId *)response->mids[i]; - ID3D11Texture2D *pSurface = - (ID3D11Texture2D *)mid->memId; - ID3D11Texture2D *pStage = - (ID3D11Texture2D *)mid->memIdStage; + CustomMemId *mid = (CustomMemId *)response->mids[i]; + ID3D11Texture2D *pSurface = (ID3D11Texture2D *)mid->memId; + ID3D11Texture2D *pStage = (ID3D11Texture2D *)mid->memIdStage; if (pSurface) pSurface->Release(); diff --git a/plugins/obs-qsv11/common_directx11.h b/plugins/obs-qsv11/common_directx11.h index b01e6b212..e127dc40d 100644 --- a/plugins/obs-qsv11/common_directx11.h +++ b/plugins/obs-qsv11/common_directx11.h @@ -21,8 +21,7 @@ // - Device must be active (but monitor does NOT have to be attached) // - Device must be enabled in BIOS. Required for the case when used together with a discrete graphics card // - For switchable graphics solutions (mobile) make sure that Intel device is the active device -mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, - bool bCreateSharedHandles); +mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, bool bCreateSharedHandles); void CleanupHWDevice(); void SetHWDeviceContext(CComPtr devCtx); CComPtr GetHWDeviceContext(); diff --git a/plugins/obs-qsv11/common_utils.cpp b/plugins/obs-qsv11/common_utils.cpp index bec75c26d..57e5161d9 100644 --- a/plugins/obs-qsv11/common_utils.cpp +++ b/plugins/obs-qsv11/common_utils.cpp @@ -18,12 +18,10 @@ void PrintErrString(int err, const char *filestr, int line) printf("\n Unknown error: %s %d\n", filestr, line); break; case -2: - printf("\n Null pointer. Check filename/path + permissions? %s %d\n", - filestr, line); + printf("\n Null pointer. Check filename/path + permissions? %s %d\n", filestr, line); break; case -3: - printf("\n Unsupported feature/library load error. %s %d\n", - filestr, line); + printf("\n Unsupported feature/library load error. %s %d\n", filestr, line); break; case -4: printf("\n Could not allocate memory. %s %d\n", filestr, line); @@ -38,8 +36,7 @@ void PrintErrString(int err, const char *filestr, int line) printf("\n Memory lock failure. %s %d\n", filestr, line); break; case -8: - printf("\n Function called before initialization. %s %d\n", - filestr, line); + printf("\n Function called before initialization. %s %d\n", filestr, line); break; case -9: printf("\n Specified object not found. %s %d\n", filestr, line); @@ -48,8 +45,7 @@ void PrintErrString(int err, const char *filestr, int line) printf("\n More input data expected. %s %d\n", filestr, line); break; case -11: - printf("\n More output surfaces expected. %s %d\n", filestr, - line); + printf("\n More output surfaces expected. %s %d\n", filestr, line); break; case -12: printf("\n Operation aborted. %s %d\n", filestr, line); @@ -58,8 +54,7 @@ void PrintErrString(int err, const char *filestr, int line) printf("\n HW device lost. %s %d\n", filestr, line); break; case -14: - printf("\n Incompatible video parameters. %s %d\n", filestr, - line); + printf("\n Incompatible video parameters. %s %d\n", filestr, line); break; case -15: printf("\n Invalid video parameters. %s %d\n", filestr, line); @@ -71,12 +66,10 @@ void PrintErrString(int err, const char *filestr, int line) printf("\n Device operation failure. %s %d\n", filestr, line); break; case -18: - printf("\n More bitstream data expected. %s %d\n", filestr, - line); + printf("\n More bitstream data expected. %s %d\n", filestr, line); break; case -19: - printf("\n Incompatible audio parameters. %s %d\n", filestr, - line); + printf("\n Incompatible audio parameters. %s %d\n", filestr, line); break; case -20: printf("\n Invalid audio parameters. %s %d\n", filestr, line); @@ -86,8 +79,7 @@ void PrintErrString(int err, const char *filestr, int line) } } -mfxStatus ReadPlaneData(mfxU16 w, mfxU16 h, mfxU8 *buf, mfxU8 *ptr, - mfxU16 pitch, mfxU16 offset, FILE *fSource) +mfxStatus ReadPlaneData(mfxU16 w, mfxU16 h, mfxU8 *buf, mfxU8 *ptr, mfxU16 pitch, mfxU16 offset, FILE *fSource) { mfxU32 nBytesRead; for (mfxU16 i = 0; i < h; i++) { @@ -179,8 +171,7 @@ mfxStatus LoadRawRGBFrame(mfxFrameSurface1 *pSurface, FILE *fSource) } for (mfxU16 i = 0; i < h; i++) { - nBytesRead = fread(pSurface->Data.B + i * pSurface->Data.Pitch, - 1, w * 4, fSource); + nBytesRead = fread(pSurface->Data.B + i * pSurface->Data.Pitch, 1, w * 4, fSource); if ((size_t)(w * 4) != nBytesRead) return MFX_ERR_MORE_DATA; } @@ -191,8 +182,7 @@ mfxStatus LoadRawRGBFrame(mfxFrameSurface1 *pSurface, FILE *fSource) mfxStatus WriteBitStreamFrame(mfxBitstream *pMfxBitstream, FILE *fSink) { mfxU32 nBytesWritten = - (mfxU32)fwrite(pMfxBitstream->Data + pMfxBitstream->DataOffset, - 1, pMfxBitstream->DataLength, fSink); + (mfxU32)fwrite(pMfxBitstream->Data + pMfxBitstream->DataOffset, 1, pMfxBitstream->DataLength, fSink); if (nBytesWritten != pMfxBitstream->DataLength) return MFX_ERR_UNDEFINED_BEHAVIOR; @@ -206,9 +196,7 @@ mfxStatus ReadBitStreamData(mfxBitstream *pBS, FILE *fSource) memmove(pBS->Data, pBS->Data + pBS->DataOffset, pBS->DataLength); pBS->DataOffset = 0; - mfxU32 nBytesRead = (mfxU32)fread(pBS->Data + pBS->DataLength, 1, - pBS->MaxLength - pBS->DataLength, - fSource); + mfxU32 nBytesRead = (mfxU32)fread(pBS->Data + pBS->DataLength, 1, pBS->MaxLength - pBS->DataLength, fSource); if (0 == nBytesRead) return MFX_ERR_MORE_DATA; @@ -218,15 +206,11 @@ mfxStatus ReadBitStreamData(mfxBitstream *pBS, FILE *fSource) return MFX_ERR_NONE; } -mfxStatus WriteSection(mfxU8 *plane, mfxU16 factor, mfxU16 chunksize, - mfxFrameInfo *pInfo, mfxFrameData *pData, mfxU32 i, - mfxU32 j, FILE *fSink) +mfxStatus WriteSection(mfxU8 *plane, mfxU16 factor, mfxU16 chunksize, mfxFrameInfo *pInfo, mfxFrameData *pData, + mfxU32 i, mfxU32 j, FILE *fSink) { - if (chunksize != fwrite(plane + - (pInfo->CropY * pData->Pitch / factor + - pInfo->CropX) + - i * pData->Pitch + j, - 1, chunksize, fSink)) + if (chunksize != fwrite(plane + (pInfo->CropY * pData->Pitch / factor + pInfo->CropX) + i * pData->Pitch + j, 1, + chunksize, fSink)) return MFX_ERR_UNDEFINED_BEHAVIOR; return MFX_ERR_NONE; } @@ -239,19 +223,16 @@ mfxStatus WriteRawFrame(mfxFrameSurface1 *pSurface, FILE *fSink) mfxStatus sts = MFX_ERR_NONE; for (i = 0; i < pInfo->CropH; i++) - sts = WriteSection(pData->Y, 1, pInfo->CropW, pInfo, pData, i, - 0, fSink); + sts = WriteSection(pData->Y, 1, pInfo->CropW, pInfo, pData, i, 0, fSink); h = pInfo->CropH / 2; w = pInfo->CropW; for (i = 0; i < h; i++) for (j = 0; j < w; j += 2) - sts = WriteSection(pData->UV, 2, 1, pInfo, pData, i, j, - fSink); + sts = WriteSection(pData->UV, 2, 1, pInfo, pData, i, j, fSink); for (i = 0; i < h; i++) for (j = 1; j < w; j += 2) - sts = WriteSection(pData->UV, 2, 1, pInfo, pData, i, j, - fSink); + sts = WriteSection(pData->UV, 2, 1, pInfo, pData, i, j, fSink); return sts; } diff --git a/plugins/obs-qsv11/common_utils.h b/plugins/obs-qsv11/common_utils.h index 2c4251205..30ceeaf83 100644 --- a/plugins/obs-qsv11/common_utils.h +++ b/plugins/obs-qsv11/common_utils.h @@ -111,14 +111,12 @@ constexpr inline int INTEL_VENDOR_ID = 0x8086; // ================================================================= // Intel VPL memory allocator entrypoints.... // Implementation of this functions is OS/Memory type specific. -mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, - mfxFrameAllocResponse *response); +mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllocResponse *response); mfxStatus simple_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr); mfxStatus simple_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr); mfxStatus simple_gethdl(mfxHDL pthis, mfxMemId mid, mfxHDL *handle); mfxStatus simple_free(mfxHDL pthis, mfxFrameAllocResponse *response); -mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, - mfxU64 *next_key); +mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, mfxU64 *next_key); // ================================================================= // Utility functions, not directly tied to VPL functionality @@ -160,10 +158,8 @@ typedef struct { int GetFreeTaskIndex(Task *pTaskPool, mfxU16 nPoolSize); // Initialize Intel VPL Session, device/display and memory manager -mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, - mfxFrameAllocator *pmfxAllocator, mfxHDL *deviceHandle, - bool bCreateSharedHandles, enum qsv_codec codec, - void **data); +mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, mfxFrameAllocator *pmfxAllocator, mfxHDL *deviceHandle, + bool bCreateSharedHandles, enum qsv_codec codec, void **data); // Release global shared resources (device/display) void Release(); diff --git a/plugins/obs-qsv11/common_utils_linux.cpp b/plugins/obs-qsv11/common_utils_linux.cpp index 430fea115..47fe9c908 100644 --- a/plugins/obs-qsv11/common_utils_linux.cpp +++ b/plugins/obs-qsv11/common_utils_linux.cpp @@ -44,11 +44,9 @@ struct surface_info { gs_texture_t *tex_uv; }; -mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, - mfxFrameAllocResponse *response) +mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllocResponse *response) { - if (request->Type & (MFX_MEMTYPE_SYSTEM_MEMORY | - MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET)) + if (request->Type & (MFX_MEMTYPE_SYSTEM_MEMORY | MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET)) return MFX_ERR_UNSUPPORTED; response->mids = (mfxMemId *)nullptr; @@ -56,8 +54,7 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mfxSession *session = (mfxSession *)pthis; VADisplay display; - mfxStatus sts = - MFXVideoCORE_GetHandle(*session, DEVICE_MGR_TYPE, &display); + mfxStatus sts = MFXVideoCORE_GetHandle(*session, DEVICE_MGR_TYPE, &display); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); // https://ffmpeg.org/doxygen/5.1/hwcontext__vaapi_8c_source.html#l00109 @@ -77,44 +74,38 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, } int num_attrs = 2; - VASurfaceAttrib attrs[2] = { - { - .type = VASurfaceAttribMemoryType, - .flags = VA_SURFACE_ATTRIB_SETTABLE, - .value = - { - .type = VAGenericValueTypeInteger, - .value = - {.i = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2}, - }, - }, - { - .type = VASurfaceAttribPixelFormat, - .flags = VA_SURFACE_ATTRIB_SETTABLE, - .value = - { - .type = VAGenericValueTypeInteger, - .value = {.i = (int)pix_format}, - }, - }}; + VASurfaceAttrib attrs[2] = {{ + .type = VASurfaceAttribMemoryType, + .flags = VA_SURFACE_ATTRIB_SETTABLE, + .value = + { + .type = VAGenericValueTypeInteger, + .value = {.i = VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2}, + }, + }, + { + .type = VASurfaceAttribPixelFormat, + .flags = VA_SURFACE_ATTRIB_SETTABLE, + .value = + { + .type = VAGenericValueTypeInteger, + .value = {.i = (int)pix_format}, + }, + }}; unsigned int num_surfaces = request->NumFrameSuggested; VASurfaceID temp_surfaces[MAX_ALLOCABLE_SURFACES] = {0}; assert(num_surfaces < MAX_ALLOCABLE_SURFACES); VAStatus vasts; - if ((vasts = vaCreateSurfaces(display, rt_format, request->Info.Width, - request->Info.Height, temp_surfaces, - num_surfaces, attrs, num_attrs)) != - VA_STATUS_SUCCESS) { + if ((vasts = vaCreateSurfaces(display, rt_format, request->Info.Width, request->Info.Height, temp_surfaces, + num_surfaces, attrs, num_attrs)) != VA_STATUS_SUCCESS) { blog(LOG_ERROR, "failed to create surfaces: %d", vasts); return MFX_ERR_MEMORY_ALLOC; } // Follow the FFmpeg trick and stuff our pointer at the end. - mfxMemId *mids = - (mfxMemId *)bmalloc(sizeof(mfxMemId) * num_surfaces + 1); - struct surface_info *surfaces = (struct surface_info *)bmalloc( - sizeof(struct surface_info) * num_surfaces); + mfxMemId *mids = (mfxMemId *)bmalloc(sizeof(mfxMemId) * num_surfaces + 1); + struct surface_info *surfaces = (struct surface_info *)bmalloc(sizeof(struct surface_info) * num_surfaces); mids[num_surfaces] = surfaces; // stuff it for (uint64_t i = 0; i < num_surfaces; i++) { @@ -124,10 +115,8 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mids[i] = &surfaces[i]; VADRMPRIMESurfaceDescriptor surfDesc = {0}; - if (vaExportSurfaceHandle(display, surfaces[i].id, - VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, - VA_EXPORT_SURFACE_READ_WRITE, - &surfDesc) != VA_STATUS_SUCCESS) + if (vaExportSurfaceHandle(display, surfaces[i].id, VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2, + VA_EXPORT_SURFACE_READ_WRITE, &surfDesc) != VA_STATUS_SUCCESS) return MFX_ERR_MEMORY_ALLOC; obs_enter_graphics(); @@ -137,29 +126,21 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, uint32_t strides[4] = {0}; uint32_t offsets[4] = {0}; uint64_t modifiers[4] = {0}; - fds[0] = - surfDesc.objects[surfDesc.layers[0].object_index[0]].fd; - fds[1] = - surfDesc.objects[surfDesc.layers[1].object_index[0]].fd; + fds[0] = surfDesc.objects[surfDesc.layers[0].object_index[0]].fd; + fds[1] = surfDesc.objects[surfDesc.layers[1].object_index[0]].fd; strides[0] = surfDesc.layers[0].pitch[0]; strides[1] = surfDesc.layers[1].pitch[0]; offsets[0] = surfDesc.layers[0].offset[0]; offsets[1] = surfDesc.layers[1].offset[0]; - modifiers[0] = - surfDesc.objects[surfDesc.layers[0].object_index[0]] - .drm_format_modifier; - modifiers[1] = - surfDesc.objects[surfDesc.layers[1].object_index[0]] - .drm_format_modifier; + modifiers[0] = surfDesc.objects[surfDesc.layers[0].object_index[0]].drm_format_modifier; + modifiers[1] = surfDesc.objects[surfDesc.layers[1].object_index[0]].drm_format_modifier; - surfaces[i].tex_y = gs_texture_create_from_dmabuf( - surfDesc.width, surfDesc.height, - surfDesc.layers[0].drm_format, GS_R8, 1, fds, strides, - offsets, modifiers); - surfaces[i].tex_uv = gs_texture_create_from_dmabuf( - surfDesc.width / 2, surfDesc.height, - surfDesc.layers[1].drm_format, GS_R8G8, 1, fds + 1, - strides + 1, offsets + 1, modifiers + 1); + surfaces[i].tex_y = gs_texture_create_from_dmabuf(surfDesc.width, surfDesc.height, + surfDesc.layers[0].drm_format, GS_R8, 1, fds, strides, + offsets, modifiers); + surfaces[i].tex_uv = gs_texture_create_from_dmabuf(surfDesc.width / 2, surfDesc.height, + surfDesc.layers[1].drm_format, GS_R8G8, 1, fds + 1, + strides + 1, offsets + 1, modifiers + 1); obs_leave_graphics(); close(surfDesc.objects[surfDesc.layers[0].object_index[0]].fd); @@ -218,12 +199,10 @@ mfxStatus simple_free(mfxHDL pthis, mfxFrameAllocResponse *response) mfxSession *session = (mfxSession *)pthis; VADisplay display; - mfxStatus sts = - MFXVideoCORE_GetHandle(*session, DEVICE_MGR_TYPE, &display); + mfxStatus sts = MFXVideoCORE_GetHandle(*session, DEVICE_MGR_TYPE, &display); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); - struct surface_info *surfs = - (struct surface_info *)response->mids[response->NumFrameActual]; + struct surface_info *surfs = (struct surface_info *)response->mids[response->NumFrameActual]; VASurfaceID temp_surfaces[MAX_ALLOCABLE_SURFACES] = {0}; obs_enter_graphics(); for (int i = 0; i < response->NumFrameActual; i++) { @@ -235,15 +214,13 @@ mfxStatus simple_free(mfxHDL pthis, mfxFrameAllocResponse *response) bfree(surfs); bfree(response->mids); - if (vaDestroySurfaces(display, temp_surfaces, - response->NumFrameActual) != VA_STATUS_SUCCESS) + if (vaDestroySurfaces(display, temp_surfaces, response->NumFrameActual) != VA_STATUS_SUCCESS) return MFX_ERR_MEMORY_ALLOC; return MFX_ERR_NONE; } -mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, - mfxU64 *next_key) +mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, mfxU64 *next_key) { UNUSED_PARAMETER(lock_key); UNUSED_PARAMETER(next_key); @@ -252,8 +229,7 @@ mfxStatus simple_copytex(mfxHDL pthis, mfxMemId mid, void *tex, mfxU64 lock_key, mfxSession *session = (mfxSession *)pthis; VADisplay display; - mfxStatus sts = - MFXVideoCORE_GetHandle(*session, DEVICE_MGR_TYPE, &display); + mfxStatus sts = MFXVideoCORE_GetHandle(*session, DEVICE_MGR_TYPE, &display); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); struct encoder_texture *ptex = (struct encoder_texture *)tex; @@ -284,10 +260,8 @@ bool get_drm_device(void *param, const char *node, uint32_t idx) } // Initialize Intel VPL Session, device/display and memory manager -mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, - mfxFrameAllocator *pmfxAllocator, mfxHDL *deviceHandle, - bool bCreateSharedHandles, enum qsv_codec codec, - void **data) +mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, mfxFrameAllocator *pmfxAllocator, mfxHDL *deviceHandle, + bool bCreateSharedHandles, enum qsv_codec codec, void **data) { UNUSED_PARAMETER(ver); UNUSED_PARAMETER(deviceHandle); @@ -301,27 +275,22 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_IMPL_TYPE_HARDWARE; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = INTEL_VENDOR_ID; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.VendorID", impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.VendorID", impl); impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_ACCEL_MODE_VIA_VAAPI_DRM_RENDER_NODE; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", - impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", impl); const char *device_path = NULL; int fd = -1; if (pmfxAllocator) { obs_video_info ovi; obs_get_video_info(&ovi); - struct get_drm_device_params params = {&device_path, - (uint32_t)ovi.adapter}; + struct get_drm_device_params params = {&device_path, (uint32_t)ovi.adapter}; obs_enter_graphics(); gs_enum_adapters(get_drm_device, ¶ms); obs_leave_graphics(); @@ -378,8 +347,7 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); } - struct linux_data *d = - (struct linux_data *)bmalloc(sizeof(struct linux_data)); + struct linux_data *d = (struct linux_data *)bmalloc(sizeof(struct linux_data)); d->fd = fd; d->vaDisplay = (VADisplay)vaDisplay; *data = d; @@ -415,8 +383,7 @@ double TimeDiffMsec(mfxTime tfinish, mfxTime tstart) extern "C" void util_cpuid(int cpuinfo[4], int level) { - __get_cpuid(level, (unsigned int *)&cpuinfo[0], - (unsigned int *)&cpuinfo[1], (unsigned int *)&cpuinfo[2], + __get_cpuid(level, (unsigned int *)&cpuinfo[0], (unsigned int *)&cpuinfo[1], (unsigned int *)&cpuinfo[2], (unsigned int *)&cpuinfo[3]); } @@ -453,8 +420,7 @@ static void vaapi_open(const char *device_path, struct vaapi_device *device) const char *driver = vaQueryVendorString(display); if (strstr(driver, "Intel i965 driver") != nullptr) { - blog(LOG_WARNING, - "Legacy intel-vaapi-driver detected, incompatible with QSV"); + blog(LOG_WARNING, "Legacy intel-vaapi-driver detected, incompatible with QSV"); vaTerminate(display); close(fd); return; @@ -471,14 +437,12 @@ static void vaapi_close(struct vaapi_device *device) close(device->fd); } -static uint32_t vaapi_check_support(VADisplay display, VAProfile profile, - VAEntrypoint entrypoint) +static uint32_t vaapi_check_support(VADisplay display, VAProfile profile, VAEntrypoint entrypoint) { VAConfigAttrib attrib[1]; attrib->type = VAConfigAttribRateControl; - VAStatus va_status = - vaGetConfigAttributes(display, profile, entrypoint, attrib, 1); + VAStatus va_status = vaGetConfigAttributes(display, profile, entrypoint, attrib, 1); uint32_t rc = 0; switch (va_status) { @@ -498,20 +462,16 @@ static bool vaapi_supports_av1(VADisplay display) { bool ret = false; // Are there any devices with non-LowPower entrypoints? - ret |= vaapi_check_support(display, VAProfileAV1Profile0, - VAEntrypointEncSlice); - ret |= vaapi_check_support(display, VAProfileAV1Profile0, - VAEntrypointEncSliceLP); + ret |= vaapi_check_support(display, VAProfileAV1Profile0, VAEntrypointEncSlice); + ret |= vaapi_check_support(display, VAProfileAV1Profile0, VAEntrypointEncSliceLP); return ret; } static bool vaapi_supports_hevc(VADisplay display) { bool ret = false; - ret |= vaapi_check_support(display, VAProfileHEVCMain, - VAEntrypointEncSlice); - ret |= vaapi_check_support(display, VAProfileHEVCMain, - VAEntrypointEncSliceLP); + ret |= vaapi_check_support(display, VAProfileHEVCMain, VAEntrypointEncSlice); + ret |= vaapi_check_support(display, VAProfileHEVCMain, VAEntrypointEncSliceLP); return ret; } @@ -534,12 +494,10 @@ bool check_adapter(void *param, const char *node, uint32_t idx) if (adapter->is_intel && default_h264_device == nullptr) default_h264_device = strdup(node); - if (adapter->is_intel && adapter->supports_av1 && - default_av1_device == nullptr) + if (adapter->is_intel && adapter->supports_av1 && default_av1_device == nullptr) default_av1_device = strdup(node); - if (adapter->is_intel && adapter->supports_hevc && - default_hevc_device == nullptr) + if (adapter->is_intel && adapter->supports_hevc && default_hevc_device == nullptr) default_hevc_device = strdup(node); vaapi_close(&device); @@ -551,8 +509,7 @@ void check_adapters(struct adapter_info *adapters, size_t *adapter_count) obs_enter_graphics(); uint32_t gs_count = gs_get_adapter_count(); if (*adapter_count < gs_count) { - blog(LOG_WARNING, "Too many video adapters: %ld < %d", - *adapter_count, gs_count); + blog(LOG_WARNING, "Too many video adapters: %ld < %d", *adapter_count, gs_count); obs_leave_graphics(); return; } diff --git a/plugins/obs-qsv11/common_utils_windows.cpp b/plugins/obs-qsv11/common_utils_windows.cpp index 1b4326f35..f34875b91 100644 --- a/plugins/obs-qsv11/common_utils_windows.cpp +++ b/plugins/obs-qsv11/common_utils_windows.cpp @@ -22,10 +22,8 @@ * Windows implementation of OS-specific utility functions */ -mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, - mfxFrameAllocator *pmfxAllocator, mfxHDL *deviceHandle, - bool bCreateSharedHandles, enum qsv_codec codec, - void **data) +mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, mfxFrameAllocator *pmfxAllocator, mfxHDL *deviceHandle, + bool bCreateSharedHandles, enum qsv_codec codec, void **data) { UNUSED_PARAMETER(codec); UNUSED_PARAMETER(data); @@ -69,29 +67,22 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_IMPL_TYPE_HARDWARE; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = INTEL_VENDOR_ID; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.VendorID", - impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.VendorID", impl); impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_ACCEL_MODE_VIA_D3D11; - MFXSetConfigFilterProperty( - cfg, - (const mfxU8 *)"mfxImplDescription.AccelerationMode", - impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", impl); sts = MFXCreateSession(loader, adapter_idx, pSession); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); // Create DirectX device context if (deviceHandle == NULL || *deviceHandle == NULL) { - sts = CreateHWDevice(*pSession, deviceHandle, NULL, - bCreateSharedHandles); + sts = CreateHWDevice(*pSession, deviceHandle, NULL, bCreateSharedHandles); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); } @@ -99,12 +90,10 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, return MFX_ERR_DEVICE_FAILED; // Provide device manager to VPL - sts = MFXVideoCORE_SetHandle(*pSession, DEVICE_MGR_TYPE, - *deviceHandle); + sts = MFXVideoCORE_SetHandle(*pSession, DEVICE_MGR_TYPE, *deviceHandle); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); - pmfxAllocator->pthis = - *pSession; // We use VPL session ID as the allocation identifier + pmfxAllocator->pthis = *pSession; // We use VPL session ID as the allocation identifier pmfxAllocator->Alloc = simple_alloc; pmfxAllocator->Free = simple_free; pmfxAllocator->Lock = simple_lock; @@ -122,21 +111,15 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_IMPL_TYPE_HARDWARE; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = INTEL_VENDOR_ID; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.VendorID", - impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.VendorID", impl); impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_ACCEL_MODE_VIA_D3D9; - MFXSetConfigFilterProperty( - cfg, - (const mfxU8 *)"mfxImplDescription.AccelerationMode", - impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.AccelerationMode", impl); sts = MFXCreateSession(loader, adapter_idx, pSession); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); @@ -166,8 +149,7 @@ double TimeDiffMsec(mfxTime tfinish, mfxTime tstart) QueryPerformanceFrequency(&tFreq); double freq = (double)tFreq.QuadPart; - return 1000.0 * ((double)tfinish.QuadPart - (double)tstart.QuadPart) / - freq; + return 1000.0 * ((double)tfinish.QuadPart - (double)tstart.QuadPart) / freq; } void util_cpuid(int cpuinfo[4], int flags) @@ -207,8 +189,7 @@ void check_adapters(struct adapter_info *adapters, size_t *adapter_count) for (;;) { char data[2048]; - size_t len = - os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); + size_t len = os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); if (!len) break; @@ -243,13 +224,10 @@ void check_adapters(struct adapter_info *adapters, size_t *adapter_count) snprintf(section, sizeof(section), "%d", (int)i); struct adapter_info *adapter = &adapters[i]; - adapter->is_intel = - config_get_bool(config, section, "is_intel"); + adapter->is_intel = config_get_bool(config, section, "is_intel"); adapter->is_dgpu = config_get_bool(config, section, "is_dgpu"); - adapter->supports_av1 = - config_get_bool(config, section, "supports_av1"); - adapter->supports_hevc = - config_get_bool(config, section, "supports_hevc"); + adapter->supports_av1 = config_get_bool(config, section, "supports_av1"); + adapter->supports_hevc = config_get_bool(config, section, "supports_hevc"); } fail: diff --git a/plugins/obs-qsv11/obs-qsv-test/obs-qsv-test.cpp b/plugins/obs-qsv11/obs-qsv-test/obs-qsv-test.cpp index 14d3d07bd..5a2567375 100644 --- a/plugins/obs-qsv11/obs-qsv-test/obs-qsv-test.cpp +++ b/plugins/obs-qsv11/obs-qsv-test/obs-qsv-test.cpp @@ -57,8 +57,7 @@ static inline uint32_t get_adapter_idx(uint32_t adapter_idx, LUID luid) return adapter_idx; } -static bool get_adapter_caps(IDXGIFactory *factory, mfxLoader loader, - mfxSession m_session, uint32_t adapter_idx) +static bool get_adapter_caps(IDXGIFactory *factory, mfxLoader loader, mfxSession m_session, uint32_t adapter_idx) { HRESULT hr; static uint32_t idx_adjustment = 0; @@ -81,10 +80,8 @@ static bool get_adapter_caps(IDXGIFactory *factory, mfxLoader loader, caps.is_intel = true; mfxImplDescription *idesc; - mfxStatus sts = - MFXEnumImplementations(loader, adapter_idx - idx_adjustment, - MFX_IMPLCAPS_IMPLDESCSTRUCTURE, - reinterpret_cast(&idesc)); + mfxStatus sts = MFXEnumImplementations(loader, adapter_idx - idx_adjustment, MFX_IMPLCAPS_IMPLDESCSTRUCTURE, + reinterpret_cast(&idesc)); if (sts != MFX_ERR_NONE) return false; @@ -139,13 +136,11 @@ try { HRESULT hr; HANDLE hMainThread; - DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), - GetCurrentProcess(), &hMainThread, 0, FALSE, + DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), &hMainThread, 0, FALSE, DUPLICATE_SAME_ACCESS); DWORD threadId; HANDLE hThread; - hThread = - CreateThread(NULL, 0, TimeoutThread, hMainThread, 0, &threadId); + hThread = CreateThread(NULL, 0, TimeoutThread, hMainThread, 0, &threadId); CloseHandle(hThread); /* --------------------------------------------------------- */ @@ -175,8 +170,7 @@ try { // Low latency is disabled due to encoding capabilities not being provided before TGL for VPL impl.Type = MFX_VARIANT_TYPE_U32; impl.Data.U32 = MFX_IMPL_TYPE_HARDWARE; - MFXSetConfigFilterProperty( - cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); + MFXSetConfigFilterProperty(cfg, (const mfxU8 *)"mfxImplDescription.Impl", impl); mfxSession m_session = nullptr; mfxStatus sts = MFXCreateSession(loader, 0, &m_session); @@ -194,10 +188,8 @@ try { printf("[%u]\n", idx); printf("is_intel=%s\n", caps.is_intel ? "true" : "false"); printf("is_dgpu=%s\n", caps.is_dgpu ? "true" : "false"); - printf("supports_av1=%s\n", - caps.supports_av1 ? "true" : "false"); - printf("supports_hevc=%s\n", - caps.supports_hevc ? "true" : "false"); + printf("supports_av1=%s\n", caps.supports_av1 ? "true" : "false"); + printf("supports_hevc=%s\n", caps.supports_hevc ? "true" : "false"); } return 0; diff --git a/plugins/obs-qsv11/obs-qsv11.c b/plugins/obs-qsv11/obs-qsv11.c index 6b42c88ad..f8ef3248e 100644 --- a/plugins/obs-qsv11/obs-qsv11.c +++ b/plugins/obs-qsv11/obs-qsv11.c @@ -67,9 +67,8 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "QSV_Encoder.h" #include "common_utils.h" -#define do_log(level, format, ...) \ - blog(level, "[qsv encoder: '%s'] " format, \ - obs_encoder_get_name(obsqsv->encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[qsv encoder: '%s'] " format, obs_encoder_get_name(obsqsv->encoder), ##__VA_ARGS__) #define error(format, ...) do_log(LOG_ERROR, format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -164,14 +163,12 @@ static void obs_qsv_destroy(void *data) } } -static void obs_qsv_defaults(obs_data_t *settings, int ver, - enum qsv_codec codec) +static void obs_qsv_defaults(obs_data_t *settings, int ver, enum qsv_codec codec) { obs_data_set_default_string(settings, "target_usage", "TU4"); obs_data_set_default_int(settings, "bitrate", 2500); obs_data_set_default_int(settings, "max_bitrate", 3000); - obs_data_set_default_string(settings, "profile", - codec == QSV_CODEC_AVC ? "high" : "main"); + obs_data_set_default_string(settings, "profile", codec == QSV_CODEC_AVC ? "high" : "main"); obs_data_set_default_string(settings, "rate_control", "CBR"); obs_data_set_default_int(settings, "__ver", ver); @@ -216,13 +213,10 @@ static inline void add_strings(obs_property_t *list, const char *const *strings) } } -static inline void add_translated_strings(obs_property_t *list, - const char *const *keys, - const char *const *strings) +static inline void add_translated_strings(obs_property_t *list, const char *const *keys, const char *const *strings) { while (*keys && *strings) { - obs_property_list_add_string(list, obs_module_text(*keys), - *strings); + obs_property_list_add_string(list, obs_module_text(*keys), *strings); keys++; strings++; } @@ -255,8 +249,7 @@ static bool update_latency(obs_data_t *settings) update = true; } - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); bool lookahead = false; if (astrcmpi(rate_control, "LA_CBR") == 0) { @@ -273,17 +266,14 @@ static bool update_latency(obs_data_t *settings) if (update) { if (lookahead) { if (la_depth == 0 || la_depth >= 15) - obs_data_set_string(settings, "latency", - "normal"); + obs_data_set_string(settings, "latency", "normal"); else obs_data_set_string(settings, "latency", "low"); } else { if (async_depth != 1) - obs_data_set_string(settings, "latency", - "normal"); + obs_data_set_string(settings, "latency", "normal"); else - obs_data_set_string(settings, "latency", - "ultra-low"); + obs_data_set_string(settings, "latency", "ultra-low"); } } @@ -292,8 +282,7 @@ static bool update_latency(obs_data_t *settings) static bool update_ratecontrol(obs_data_t *settings) { - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); if (astrcmpi(rate_control, "VCM") == 0) { obs_data_set_string(settings, "rate_control", "CBR"); @@ -306,40 +295,33 @@ static bool update_ratecontrol(obs_data_t *settings) static void update_targetusage(obs_data_t *settings) { - const char *target_usage = - obs_data_get_string(settings, "target_usage"); + const char *target_usage = obs_data_get_string(settings, "target_usage"); - if (astrcmpi(target_usage, "veryslow") == 0 || - astrcmpi(target_usage, "quality") == 0) + if (astrcmpi(target_usage, "veryslow") == 0 || astrcmpi(target_usage, "quality") == 0) obs_data_set_string(settings, "target_usage", "TU1"); else if (astrcmpi(target_usage, "slower") == 0) obs_data_set_string(settings, "target_usage", "TU2"); else if (astrcmpi(target_usage, "slow") == 0) obs_data_set_string(settings, "target_usage", "TU3"); - else if (astrcmpi(target_usage, "medium") == 0 || - astrcmpi(target_usage, "balanced") == 0) + else if (astrcmpi(target_usage, "medium") == 0 || astrcmpi(target_usage, "balanced") == 0) obs_data_set_string(settings, "target_usage", "TU4"); else if (astrcmpi(target_usage, "fast") == 0) obs_data_set_string(settings, "target_usage", "TU5"); else if (astrcmpi(target_usage, "faster") == 0) obs_data_set_string(settings, "target_usage", "TU6"); - else if (astrcmpi(target_usage, "veryfast") == 0 || - astrcmpi(target_usage, "speed") == 0) + else if (astrcmpi(target_usage, "veryfast") == 0 || astrcmpi(target_usage, "speed") == 0) obs_data_set_string(settings, "target_usage", "TU7"); } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); bool bVisible = astrcmpi(rate_control, "VBR") == 0; p = obs_properties_get(ppts, "max_bitrate"); obs_property_set_visible(p, bVisible); - bVisible = astrcmpi(rate_control, "CQP") == 0 || - astrcmpi(rate_control, "ICQ") == 0; + bVisible = astrcmpi(rate_control, "CQP") == 0 || astrcmpi(rate_control, "ICQ") == 0; p = obs_properties_get(ppts, "bitrate"); obs_property_set_visible(p, !bVisible); @@ -368,77 +350,61 @@ static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, return true; } -static bool profile_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool profile_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *profile = obs_data_get_string(settings, "profile"); enum qsv_cpu_platform plat = qsv_get_cpu_platform(); bool bVisible = ((astrcmpi(profile, "high") == 0) && - (plat >= QSV_CPU_PLATFORM_ICL || - plat == QSV_CPU_PLATFORM_UNKNOWN)); + (plat >= QSV_CPU_PLATFORM_ICL || plat == QSV_CPU_PLATFORM_UNKNOWN)); p = obs_properties_get(ppts, "CQM"); obs_property_set_visible(p, bVisible); return true; } -static inline void add_rate_controls(obs_property_t *list, - const struct qsv_rate_control_info *rc) +static inline void add_rate_controls(obs_property_t *list, const struct qsv_rate_control_info *rc) { enum qsv_cpu_platform plat = qsv_get_cpu_platform(); while (rc->name) { - if (!rc->haswell_or_greater || - (plat >= QSV_CPU_PLATFORM_HSW || - plat == QSV_CPU_PLATFORM_UNKNOWN)) + if (!rc->haswell_or_greater || (plat >= QSV_CPU_PLATFORM_HSW || plat == QSV_CPU_PLATFORM_UNKNOWN)) obs_property_list_add_string(list, rc->name, rc->name); rc++; } } -static obs_properties_t *obs_qsv_props(enum qsv_codec codec, void *unused, - int ver) +static obs_properties_t *obs_qsv_props(enum qsv_codec codec, void *unused, int ver) { UNUSED_PARAMETER(unused); obs_properties_t *props = obs_properties_create(); obs_property_t *prop; - prop = obs_properties_add_list(props, "rate_control", TEXT_RATE_CONTROL, - OBS_COMBO_TYPE_LIST, + prop = obs_properties_add_list(props, "rate_control", TEXT_RATE_CONTROL, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); add_rate_controls(prop, qsv_ratecontrols); obs_property_set_modified_callback(prop, rate_control_modified); - prop = obs_properties_add_int(props, "bitrate", TEXT_TARGET_BITRATE, 50, - 10000000, 50); + prop = obs_properties_add_int(props, "bitrate", TEXT_TARGET_BITRATE, 50, 10000000, 50); obs_property_int_set_suffix(prop, " Kbps"); - prop = obs_properties_add_int(props, "max_bitrate", TEXT_MAX_BITRATE, - 50, 10000000, 50); + prop = obs_properties_add_int(props, "max_bitrate", TEXT_MAX_BITRATE, 50, 10000000, 50); obs_property_int_set_suffix(prop, " Kbps"); if (ver >= 2) { - obs_properties_add_int(props, "cqp", "CQP", 1, - codec == QSV_CODEC_AV1 ? 63 : 51, 1); + obs_properties_add_int(props, "cqp", "CQP", 1, codec == QSV_CODEC_AV1 ? 63 : 51, 1); } else { obs_properties_add_int(props, "qpi", "QPI", 1, 51, 1); obs_properties_add_int(props, "qpp", "QPP", 1, 51, 1); obs_properties_add_int(props, "qpb", "QPB", 1, 51, 1); } - obs_properties_add_int(props, "icq_quality", TEXT_ICQ_QUALITY, 1, 51, - 1); + obs_properties_add_int(props, "icq_quality", TEXT_ICQ_QUALITY, 1, 51, 1); - prop = obs_properties_add_list(props, "target_usage", TEXT_SPEED, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); - add_translated_strings(prop, qsv_usage_translation_keys, - qsv_usage_names); + prop = obs_properties_add_list(props, "target_usage", TEXT_SPEED, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + add_translated_strings(prop, qsv_usage_translation_keys, qsv_usage_names); - prop = obs_properties_add_list(props, "profile", TEXT_PROFILE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + prop = obs_properties_add_list(props, "profile", TEXT_PROFILE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); if (codec == QSV_CODEC_AVC) add_strings(prop, qsv_profile_names); @@ -449,16 +415,12 @@ static obs_properties_t *obs_qsv_props(enum qsv_codec codec, void *unused, obs_property_set_modified_callback(prop, profile_modified); - prop = obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, - 20, 1); + prop = obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, 1); obs_property_int_set_suffix(prop, " s"); - prop = obs_properties_add_list(props, "latency", TEXT_LATENCY, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + prop = obs_properties_add_list(props, "latency", TEXT_LATENCY, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); add_strings(prop, qsv_latency_names); - obs_property_set_long_description(prop, - obs_module_text("Latency.ToolTip")); + obs_property_set_long_description(prop, obs_module_text("Latency.ToolTip")); obs_properties_add_int(props, "bframes", TEXT_BFRAMES, 0, 3, 1); @@ -496,11 +458,9 @@ static void update_params(struct obs_qsv *obsqsv, obs_data_t *settings) update_latency(settings); update_targetusage(settings); - const char *target_usage = - obs_data_get_string(settings, "target_usage"); + const char *target_usage = obs_data_get_string(settings, "target_usage"); const char *profile = obs_data_get_string(settings, "profile"); - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); const char *latency = obs_data_get_string(settings, "latency"); int target_bitrate = (int)obs_data_get_int(settings, "bitrate"); int max_bitrate = (int)obs_data_get_int(settings, "max_bitrate"); @@ -554,10 +514,8 @@ static void update_params(struct obs_qsv *obsqsv, obs_data_t *settings) if (astrcmpi(profile, "main") == 0) { obsqsv->params.nCodecProfile = MFX_PROFILE_HEVC_MAIN; if (obs_p010_tex_active()) { - blog(LOG_WARNING, - "[qsv encoder] Forcing main10 for P010"); - obsqsv->params.nCodecProfile = - MFX_PROFILE_HEVC_MAIN10; + blog(LOG_WARNING, "[qsv encoder] Forcing main10 for P010"); + obsqsv->params.nCodecProfile = MFX_PROFILE_HEVC_MAIN10; } } else if (astrcmpi(profile, "main10") == 0) { @@ -613,9 +571,7 @@ static void update_params(struct obs_qsv *obsqsv, obs_data_t *settings) const bool pq = voi->colorspace == VIDEO_CS_2100_PQ; const bool hlg = voi->colorspace == VIDEO_CS_2100_HLG; if (pq || hlg) { - const int hdr_nominal_peak_level = - pq ? (int)obs_get_video_hdr_nominal_peak_level() - : (hlg ? 1000 : 0); + const int hdr_nominal_peak_level = pq ? (int)obs_get_video_hdr_nominal_peak_level() : (hlg ? 1000 : 0); obsqsv->params.DisplayPrimariesX[0] = 13250; obsqsv->params.DisplayPrimariesX[1] = 7500; @@ -625,8 +581,7 @@ static void update_params(struct obs_qsv *obsqsv, obs_data_t *settings) obsqsv->params.DisplayPrimariesY[2] = 16000; obsqsv->params.WhitePointX = 15635; obsqsv->params.WhitePointY = 16450; - obsqsv->params.MaxDisplayMasteringLuminance = - hdr_nominal_peak_level * 10000; + obsqsv->params.MaxDisplayMasteringLuminance = hdr_nominal_peak_level * 10000; obsqsv->params.MinDisplayMasteringLuminance = 0; obsqsv->params.MaxContentLightLevel = hdr_nominal_peak_level; @@ -703,22 +658,17 @@ static void update_params(struct obs_qsv *obsqsv, obs_data_t *settings) "\trate_control: %s", codec, rate_control); - if (obsqsv->params.nRateControl != MFX_RATECONTROL_ICQ && - obsqsv->params.nRateControl != MFX_RATECONTROL_CQP) - blog(LOG_INFO, "\ttarget_bitrate: %d", - (int)obsqsv->params.nTargetBitRate); + if (obsqsv->params.nRateControl != MFX_RATECONTROL_ICQ && obsqsv->params.nRateControl != MFX_RATECONTROL_CQP) + blog(LOG_INFO, "\ttarget_bitrate: %d", (int)obsqsv->params.nTargetBitRate); if (obsqsv->params.nRateControl == MFX_RATECONTROL_VBR) - blog(LOG_INFO, "\tmax_bitrate: %d", - (int)obsqsv->params.nMaxBitRate); + blog(LOG_INFO, "\tmax_bitrate: %d", (int)obsqsv->params.nMaxBitRate); if (obsqsv->params.nRateControl == MFX_RATECONTROL_ICQ) - blog(LOG_INFO, "\tICQ Quality: %d", - (int)obsqsv->params.nICQQuality); + blog(LOG_INFO, "\tICQ Quality: %d", (int)obsqsv->params.nICQQuality); if (obsqsv->params.nLADEPTH) - blog(LOG_INFO, "\tLookahead Depth:%d", - (int)obsqsv->params.nLADEPTH); + blog(LOG_INFO, "\tLookahead Depth:%d", (int)obsqsv->params.nLADEPTH); if (obsqsv->params.nRateControl == MFX_RATECONTROL_CQP) blog(LOG_INFO, @@ -737,8 +687,7 @@ static void update_params(struct obs_qsv *obsqsv, obs_data_t *settings) "\tfps_den: %d\n" "\twidth: %d\n" "\theight: %d", - target_usage, profile, keyint_sec, latency, bFrames, voi->fps_num, - voi->fps_den, width, height); + target_usage, profile, keyint_sec, latency, bFrames, voi->fps_num, voi->fps_den, width, height); info("debug info:"); } @@ -759,8 +708,7 @@ static void load_hevc_headers(struct obs_qsv *obsqsv) uint8_t *pVPS, *pSPS, *pPPS; uint16_t nVPS, nSPS, nPPS; - qsv_hevc_encoder_headers(obsqsv->context, &pVPS, &pSPS, &pPPS, &nVPS, - &nSPS, &nPPS); + qsv_hevc_encoder_headers(obsqsv->context, &pVPS, &pSPS, &pPPS, &nVPS, &nSPS, &nPPS); da_push_back_array(header, pVPS, nVPS); da_push_back_array(header, pSPS, nSPS); da_push_back_array(header, pPPS, nPPS); @@ -803,8 +751,7 @@ static void load_headers(struct obs_qsv *obsqsv) static bool obs_qsv_update(void *data, obs_data_t *settings) { struct obs_qsv *obsqsv = data; - obsqsv->params.nTargetBitRate = - (mfxU16)obs_data_get_int(settings, "bitrate"); + obsqsv->params.nTargetBitRate = (mfxU16)obs_data_get_int(settings, "bitrate"); if (!qsv_encoder_reconfig(obsqsv->context, &obsqsv->params)) { warn("Failed to reconfigure"); @@ -814,8 +761,7 @@ static bool obs_qsv_update(void *data, obs_data_t *settings) return true; } -static void *obs_qsv_create(enum qsv_codec codec, obs_data_t *settings, - obs_encoder_t *encoder, bool useTexAlloc) +static void *obs_qsv_create(enum qsv_codec codec, obs_data_t *settings, obs_encoder_t *encoder, bool useTexAlloc) { struct obs_qsv *obsqsv = bzalloc(sizeof(struct obs_qsv)); obsqsv->encoder = encoder; @@ -827,8 +773,7 @@ static void *obs_qsv_create(enum qsv_codec codec, obs_data_t *settings, case VIDEO_FORMAT_I010: case VIDEO_FORMAT_P010: if (codec == QSV_CODEC_AVC) { - const char *const text = - obs_module_text("10bitUnsupportedAvc"); + const char *const text = obs_module_text("10bitUnsupportedAvc"); obs_encoder_set_last_error(encoder, text); error("%s", text); bfree(obsqsv); @@ -848,8 +793,7 @@ static void *obs_qsv_create(enum qsv_codec codec, obs_data_t *settings, switch (voi->colorspace) { case VIDEO_CS_2100_PQ: case VIDEO_CS_2100_HLG: { - const char *const text = - obs_module_text("8bitUnsupportedHdr"); + const char *const text = obs_module_text("8bitUnsupportedHdr"); obs_encoder_set_last_error(encoder, text); error("%s", text); bfree(obsqsv); @@ -860,8 +804,7 @@ static void *obs_qsv_create(enum qsv_codec codec, obs_data_t *settings, if (update_settings(obsqsv, settings)) { pthread_mutex_lock(&g_QsvLock); - obsqsv->context = - qsv_encoder_open(&obsqsv->params, codec, useTexAlloc); + obsqsv->context = qsv_encoder_open(&obsqsv->params, codec, useTexAlloc); pthread_mutex_unlock(&g_QsvLock); if (obsqsv->context == NULL) @@ -886,11 +829,9 @@ static void *obs_qsv_create(enum qsv_codec codec, obs_data_t *settings, // Need to add manual DTS from PTS. if (g_verMajor == 1 && g_verMinor < 7) { int64_t interval = obsqsv->params.nbFrames + 1; - int64_t GopPicSize = (int64_t)(obsqsv->params.nKeyIntSec * - obsqsv->params.nFpsNum / - (float)obsqsv->params.nFpsDen); - g_pts2dtsShift = - GopPicSize - (GopPicSize / interval) * interval; + int64_t GopPicSize = + (int64_t)(obsqsv->params.nKeyIntSec * obsqsv->params.nFpsNum / (float)obsqsv->params.nFpsDen); + g_pts2dtsShift = GopPicSize - (GopPicSize / interval) * interval; blog(LOG_INFO, "\tinterval: %" PRId64 "\n" @@ -927,45 +868,36 @@ static void *obs_qsv_create_hevc(obs_data_t *settings, obs_encoder_t *encoder) return obs_qsv_create(QSV_CODEC_HEVC, settings, encoder, false); } -static void *obs_qsv_create_tex(enum qsv_codec codec, obs_data_t *settings, - obs_encoder_t *encoder, const char *fallback_id) +static void *obs_qsv_create_tex(enum qsv_codec codec, obs_data_t *settings, obs_encoder_t *encoder, + const char *fallback_id) { struct obs_video_info ovi; obs_get_video_info(&ovi); if (!adapters[ovi.adapter].is_intel) { - blog(LOG_INFO, - ">>> app not on intel GPU, fall back to old qsv encoder"); - return obs_encoder_create_rerouted(encoder, - (const char *)fallback_id); + blog(LOG_INFO, ">>> app not on intel GPU, fall back to old qsv encoder"); + return obs_encoder_create_rerouted(encoder, (const char *)fallback_id); } if (codec == QSV_CODEC_AV1 && !adapters[ovi.adapter].supports_av1) { - blog(LOG_INFO, - ">>> cap on different device, fall back to non-texture sharing AV1 qsv encoder"); - return obs_encoder_create_rerouted(encoder, - (const char *)fallback_id); + blog(LOG_INFO, ">>> cap on different device, fall back to non-texture sharing AV1 qsv encoder"); + return obs_encoder_create_rerouted(encoder, (const char *)fallback_id); } bool gpu_texture_active = obs_nv12_tex_active(); if (codec != QSV_CODEC_AVC) - gpu_texture_active = gpu_texture_active || - obs_p010_tex_active(); + gpu_texture_active = gpu_texture_active || obs_p010_tex_active(); if (!gpu_texture_active) { - blog(LOG_INFO, - ">>> gpu tex not active, fall back to old qsv encoder"); - return obs_encoder_create_rerouted(encoder, - (const char *)fallback_id); + blog(LOG_INFO, ">>> gpu tex not active, fall back to old qsv encoder"); + return obs_encoder_create_rerouted(encoder, (const char *)fallback_id); } if (obs_encoder_scaling_enabled(encoder)) { if (!obs_encoder_gpu_scaling_enabled(encoder)) { - blog(LOG_INFO, - ">>> encoder CPU scaling active, fall back to old qsv encoder"); - return obs_encoder_create_rerouted( - encoder, (const char *)fallback_id); + blog(LOG_INFO, ">>> encoder CPU scaling active, fall back to old qsv encoder"); + return obs_encoder_create_rerouted(encoder, (const char *)fallback_id); } blog(LOG_INFO, ">>> encoder GPU scaling active"); } @@ -974,32 +906,24 @@ static void *obs_qsv_create_tex(enum qsv_codec codec, obs_data_t *settings, return obs_qsv_create(codec, settings, encoder, true); } -static void *obs_qsv_create_tex_h264(obs_data_t *settings, - obs_encoder_t *encoder) +static void *obs_qsv_create_tex_h264(obs_data_t *settings, obs_encoder_t *encoder) { - return obs_qsv_create_tex(QSV_CODEC_AVC, settings, encoder, - "obs_qsv11_soft"); + return obs_qsv_create_tex(QSV_CODEC_AVC, settings, encoder, "obs_qsv11_soft"); } -static void *obs_qsv_create_tex_h264_v2(obs_data_t *settings, - obs_encoder_t *encoder) +static void *obs_qsv_create_tex_h264_v2(obs_data_t *settings, obs_encoder_t *encoder) { - return obs_qsv_create_tex(QSV_CODEC_AVC, settings, encoder, - "obs_qsv11_soft_v2"); + return obs_qsv_create_tex(QSV_CODEC_AVC, settings, encoder, "obs_qsv11_soft_v2"); } -static void *obs_qsv_create_tex_av1(obs_data_t *settings, - obs_encoder_t *encoder) +static void *obs_qsv_create_tex_av1(obs_data_t *settings, obs_encoder_t *encoder) { - return obs_qsv_create_tex(QSV_CODEC_AV1, settings, encoder, - "obs_qsv11_av1_soft"); + return obs_qsv_create_tex(QSV_CODEC_AV1, settings, encoder, "obs_qsv11_av1_soft"); } -static void *obs_qsv_create_tex_hevc(obs_data_t *settings, - obs_encoder_t *encoder) +static void *obs_qsv_create_tex_hevc(obs_data_t *settings, obs_encoder_t *encoder) { - return obs_qsv_create_tex(QSV_CODEC_HEVC, settings, encoder, - "obs_qsv11_hevc_soft"); + return obs_qsv_create_tex(QSV_CODEC_HEVC, settings, encoder, "obs_qsv11_hevc_soft"); } static bool obs_qsv_extra_data(void *data, uint8_t **extra_data, size_t *size) @@ -1036,8 +960,7 @@ static inline bool valid_av1_format(enum video_format format) return format == VIDEO_FORMAT_NV12 || format == VIDEO_FORMAT_P010; } -static inline void cap_resolution(struct obs_qsv *obsqsv, - struct video_scale_info *info) +static inline void cap_resolution(struct obs_qsv *obsqsv, struct video_scale_info *info) { enum qsv_cpu_platform qsv_platform = qsv_get_cpu_platform(); uint32_t width = obs_encoder_get_width(obsqsv->encoder); @@ -1049,8 +972,7 @@ static inline void cap_resolution(struct obs_qsv *obsqsv, info->height = height; info->width = width; - if (qsv_platform <= QSV_CPU_PLATFORM_IVB && - qsv_platform != QSV_CPU_PLATFORM_UNKNOWN) { + if (qsv_platform <= QSV_CPU_PLATFORM_IVB && qsv_platform != QSV_CPU_PLATFORM_UNKNOWN) { if (width > 1920) { info->width = 1920; } @@ -1069,16 +991,14 @@ static void obs_qsv_video_info(void *data, struct video_scale_info *info) pref_format = obs_encoder_get_preferred_video_format(obsqsv->encoder); if (!valid_format(pref_format)) { - pref_format = valid_format(info->format) ? info->format - : VIDEO_FORMAT_NV12; + pref_format = valid_format(info->format) ? info->format : VIDEO_FORMAT_NV12; } info->format = pref_format; cap_resolution(obsqsv, info); } -static void obs_qsv_video_plus_hdr_info(void *data, - struct video_scale_info *info) +static void obs_qsv_video_plus_hdr_info(void *data, struct video_scale_info *info) { struct obs_qsv *obsqsv = data; enum video_format pref_format; @@ -1086,9 +1006,7 @@ static void obs_qsv_video_plus_hdr_info(void *data, pref_format = obs_encoder_get_preferred_video_format(obsqsv->encoder); if (!valid_av1_format(pref_format)) { - pref_format = valid_av1_format(info->format) - ? info->format - : VIDEO_FORMAT_NV12; + pref_format = valid_av1_format(info->format) ? info->format : VIDEO_FORMAT_NV12; } info->format = pref_format; @@ -1110,9 +1028,8 @@ static int64_t ts_mfx_to_obs(mfxI64 ts, const struct video_output_info *voi) return (ts * voi->fps_num + div / 2) / div * voi->fps_den; } -static void parse_packet(struct obs_qsv *obsqsv, struct encoder_packet *packet, - mfxBitstream *pBS, const struct video_output_info *voi, - bool *received_packet) +static void parse_packet(struct obs_qsv *obsqsv, struct encoder_packet *packet, mfxBitstream *pBS, + const struct video_output_info *voi, bool *received_packet) { uint8_t *start, *end; int type; @@ -1123,8 +1040,7 @@ static void parse_packet(struct obs_qsv *obsqsv, struct encoder_packet *packet, } da_resize(obsqsv->packet_data, 0); - da_push_back_array(obsqsv->packet_data, &pBS->Data[pBS->DataOffset], - pBS->DataLength); + da_push_back_array(obsqsv->packet_data, &pBS->Data[pBS->DataOffset], pBS->DataLength); packet->data = obsqsv->packet_data.array; packet->size = obsqsv->packet_data.num; @@ -1137,8 +1053,7 @@ static void parse_packet(struct obs_qsv *obsqsv, struct encoder_packet *packet, if (frameType & MFX_FRAMETYPE_I) priority = OBS_NAL_PRIORITY_HIGHEST; - else if ((frameType & MFX_FRAMETYPE_P) || - (frameType & MFX_FRAMETYPE_REF)) + else if ((frameType & MFX_FRAMETYPE_P) || (frameType & MFX_FRAMETYPE_REF)) priority = OBS_NAL_PRIORITY_HIGH; else priority = 0; @@ -1161,9 +1076,7 @@ static void parse_packet(struct obs_qsv *obsqsv, struct encoder_packet *packet, type = start[0] & 0x1F; if (type == OBS_NAL_SLICE_IDR || type == OBS_NAL_SLICE) { start[0] &= ~(3 << 5); - start[0] |= - priority - << 5; //0 for non-ref frames and not equal to 0 for ref frames + start[0] |= priority << 5; //0 for non-ref frames and not equal to 0 for ref frames } start = (uint8_t *)obs_avc_find_startcode(start, end); @@ -1207,10 +1120,8 @@ static void parse_packet(struct obs_qsv *obsqsv, struct encoder_packet *packet, g_bFirst = false; } -static void parse_packet_av1(struct obs_qsv *obsqsv, - struct encoder_packet *packet, mfxBitstream *pBS, - const struct video_output_info *voi, - bool *received_packet) +static void parse_packet_av1(struct obs_qsv *obsqsv, struct encoder_packet *packet, mfxBitstream *pBS, + const struct video_output_info *voi, bool *received_packet) { if (pBS == NULL || pBS->DataLength == 0) { *received_packet = false; @@ -1218,8 +1129,7 @@ static void parse_packet_av1(struct obs_qsv *obsqsv, } da_resize(obsqsv->packet_data, 0); - da_push_back_array(obsqsv->packet_data, &pBS->Data[pBS->DataOffset], - pBS->DataLength); + da_push_back_array(obsqsv->packet_data, &pBS->Data[pBS->DataOffset], pBS->DataLength); packet->data = obsqsv->packet_data.array; packet->size = obsqsv->packet_data.num; @@ -1232,8 +1142,7 @@ static void parse_packet_av1(struct obs_qsv *obsqsv, if (frameType & MFX_FRAMETYPE_I) priority = OBS_NAL_PRIORITY_HIGHEST; - else if ((frameType & MFX_FRAMETYPE_P) || - (frameType & MFX_FRAMETYPE_REF)) + else if ((frameType & MFX_FRAMETYPE_P) || (frameType & MFX_FRAMETYPE_REF)) priority = OBS_NAL_PRIORITY_HIGH; else priority = OBS_NAL_PRIORITY_DISPOSABLE; @@ -1256,10 +1165,8 @@ static void parse_packet_av1(struct obs_qsv *obsqsv, g_bFirst = false; } -static void parse_packet_hevc(struct obs_qsv *obsqsv, - struct encoder_packet *packet, mfxBitstream *pBS, - const struct video_output_info *voi, - bool *received_packet) +static void parse_packet_hevc(struct obs_qsv *obsqsv, struct encoder_packet *packet, mfxBitstream *pBS, + const struct video_output_info *voi, bool *received_packet) { if (pBS == NULL || pBS->DataLength == 0) { *received_packet = false; @@ -1267,8 +1174,7 @@ static void parse_packet_hevc(struct obs_qsv *obsqsv, } da_resize(obsqsv->packet_data, 0); - da_push_back_array(obsqsv->packet_data, &pBS->Data[pBS->DataOffset], - pBS->DataLength); + da_push_back_array(obsqsv->packet_data, &pBS->Data[pBS->DataOffset], pBS->DataLength); packet->data = obsqsv->packet_data.array; packet->size = obsqsv->packet_data.num; @@ -1281,8 +1187,7 @@ static void parse_packet_hevc(struct obs_qsv *obsqsv, if (frameType & MFX_FRAMETYPE_I) priority = OBS_NAL_PRIORITY_HIGHEST; - else if ((frameType & MFX_FRAMETYPE_P) || - (frameType & MFX_FRAMETYPE_REF)) + else if ((frameType & MFX_FRAMETYPE_P) || (frameType & MFX_FRAMETYPE_REF)) priority = OBS_NAL_PRIORITY_HIGH; packet->priority = priority; @@ -1333,8 +1238,7 @@ static void roi_cb(void *param, struct obs_encoder_roi *roi) static void obs_qsv_setup_rois(struct obs_qsv *obsqsv) { - const uint32_t increment = - obs_encoder_get_roi_increment(obsqsv->encoder); + const uint32_t increment = obs_encoder_get_roi_increment(obsqsv->encoder); if (obsqsv->roi_increment == increment) return; @@ -1356,8 +1260,8 @@ static void obs_qsv_setup_rois(struct obs_qsv *obsqsv) obsqsv->roi_increment = increment; } -static bool obs_qsv_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool obs_qsv_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, + bool *received_packet) { struct obs_qsv *obsqsv = data; @@ -1381,13 +1285,10 @@ static bool obs_qsv_encode(void *data, struct encoder_frame *frame, // FIXME: remove null check from the top of this function // if we actually do expect null frames to complete output. if (frame) - ret = qsv_encoder_encode(obsqsv->context, qsvPTS, - frame->data[0], frame->data[1], - frame->linesize[0], frame->linesize[1], - &pBS); + ret = qsv_encoder_encode(obsqsv->context, qsvPTS, frame->data[0], frame->data[1], frame->linesize[0], + frame->linesize[1], &pBS); else - ret = qsv_encoder_encode(obsqsv->context, qsvPTS, NULL, NULL, 0, - 0, &pBS); + ret = qsv_encoder_encode(obsqsv->context, qsvPTS, NULL, NULL, 0, 0, &pBS); if (ret < 0) { warn("encode failed"); @@ -1407,11 +1308,8 @@ static bool obs_qsv_encode(void *data, struct encoder_frame *frame, return true; } -static bool obs_qsv_encode_tex(void *data, struct encoder_texture *tex, - int64_t pts, uint64_t lock_key, - uint64_t *next_key, - struct encoder_packet *packet, - bool *received_packet) +static bool obs_qsv_encode_tex(void *data, struct encoder_texture *tex, int64_t pts, uint64_t lock_key, + uint64_t *next_key, struct encoder_packet *packet, bool *received_packet) { struct obs_qsv *obsqsv = data; @@ -1442,8 +1340,7 @@ static bool obs_qsv_encode_tex(void *data, struct encoder_texture *tex, if (obs_encoder_has_roi(obsqsv->encoder)) obs_qsv_setup_rois(obsqsv); - ret = qsv_encoder_encode_tex(obsqsv->context, qsvPTS, (void *)tex, - lock_key, next_key, &pBS); + ret = qsv_encoder_encode_tex(obsqsv->context, qsvPTS, (void *)tex, lock_key, next_key, &pBS); if (ret < 0) { warn("encode failed"); @@ -1470,8 +1367,7 @@ struct obs_encoder_info obs_qsv_encoder_tex = { .get_name = obs_qsv_getname_v1, .create = obs_qsv_create_tex_h264, .destroy = obs_qsv_destroy, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_DEPRECATED, .encode_texture2 = obs_qsv_encode_tex, .update = obs_qsv_update, .get_properties = obs_qsv_props_h264, @@ -1495,8 +1391,7 @@ struct obs_encoder_info obs_qsv_encoder = { .get_extra_data = obs_qsv_extra_data, .get_sei_data = obs_qsv_sei, .get_video_info = obs_qsv_video_info, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_DEPRECATED, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_DEPRECATED, }; struct obs_encoder_info obs_qsv_encoder_tex_v2 = { @@ -1506,8 +1401,7 @@ struct obs_encoder_info obs_qsv_encoder_tex_v2 = { .get_name = obs_qsv_getname, .create = obs_qsv_create_tex_h264_v2, .destroy = obs_qsv_destroy, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_ROI, .encode_texture2 = obs_qsv_encode_tex, .update = obs_qsv_update, .get_properties = obs_qsv_props_h264_v2, @@ -1531,8 +1425,7 @@ struct obs_encoder_info obs_qsv_encoder_v2 = { .get_extra_data = obs_qsv_extra_data, .get_sei_data = obs_qsv_sei, .get_video_info = obs_qsv_video_info, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_ROI, }; struct obs_encoder_info obs_qsv_av1_encoder_tex = { @@ -1542,8 +1435,7 @@ struct obs_encoder_info obs_qsv_av1_encoder_tex = { .get_name = obs_qsv_getname_av1, .create = obs_qsv_create_tex_av1, .destroy = obs_qsv_destroy, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_ROI, .encode_texture2 = obs_qsv_encode_tex, .update = obs_qsv_update, .get_properties = obs_qsv_props_av1, @@ -1565,8 +1457,7 @@ struct obs_encoder_info obs_qsv_av1_encoder = { .get_defaults = obs_qsv_defaults_av1, .get_extra_data = obs_qsv_extra_data, .get_video_info = obs_qsv_video_plus_hdr_info, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_ROI, }; struct obs_encoder_info obs_qsv_hevc_encoder_tex = { @@ -1576,8 +1467,7 @@ struct obs_encoder_info obs_qsv_hevc_encoder_tex = { .get_name = obs_qsv_getname_hevc, .create = obs_qsv_create_tex_hevc, .destroy = obs_qsv_destroy, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_PASS_TEXTURE | OBS_ENCODER_CAP_ROI, .encode_texture2 = obs_qsv_encode_tex, .update = obs_qsv_update, .get_properties = obs_qsv_props_hevc, @@ -1599,6 +1489,5 @@ struct obs_encoder_info obs_qsv_hevc_encoder = { .get_defaults = obs_qsv_defaults_hevc, .get_extra_data = obs_qsv_extra_data, .get_video_info = obs_qsv_video_plus_hdr_info, - .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | - OBS_ENCODER_CAP_ROI, + .caps = OBS_ENCODER_CAP_DYN_BITRATE | OBS_ENCODER_CAP_INTERNAL | OBS_ENCODER_CAP_ROI, }; diff --git a/plugins/obs-text/gdiplus/obs-text.cpp b/plugins/obs-text/gdiplus/obs-text.cpp index 2317ce179..d140c162f 100644 --- a/plugins/obs-text/gdiplus/obs-text.cpp +++ b/plugins/obs-text/gdiplus/obs-text.cpp @@ -13,15 +13,12 @@ using namespace std; using namespace Gdiplus; -#define warning(format, ...) \ - blog(LOG_WARNING, "[%s] " format, obs_source_get_name(source), \ - ##__VA_ARGS__) +#define warning(format, ...) blog(LOG_WARNING, "[%s] " format, obs_source_get_name(source), ##__VA_ARGS__) -#define warn_stat(call) \ - do { \ - if (stat != Ok) \ - warning("%s: %s failed (%d)", __FUNCTION__, call, \ - (int)stat); \ +#define warn_stat(call) \ + do { \ + if (stat != Ok) \ + warning("%s: %s failed (%d)", __FUNCTION__, call, (int)stat); \ } while (false) #ifndef clamp @@ -265,8 +262,7 @@ struct TextSource { /* --------------------------- */ - inline TextSource(obs_source_t *source_, obs_data_t *settings, - bool old_extents_) + inline TextSource(obs_source_t *source_, obs_data_t *settings, bool old_extents_) : source(source_), hdc(CreateCompatibleDC(nullptr)), graphics(hdc), @@ -287,10 +283,8 @@ struct TextSource { void UpdateFont(); void GetStringFormat(StringFormat &format); void RemoveNewlinePadding(const StringFormat &format, RectF &box); - void CalculateTextSizes(const StringFormat &format, RectF &bounding_box, - SIZE &text_size); - void RenderOutlineText(Graphics &graphics, const GraphicsPath &path, - const Brush &brush); + void CalculateTextSizes(const StringFormat &format, RectF &bounding_box, SIZE &text_size); + void RenderOutlineText(Graphics &graphics, const GraphicsPath &path, const Brush &brush); void RenderText(); void LoadFileText(); void TransformText(); @@ -347,8 +341,7 @@ void TextSource::GetStringFormat(StringFormat &format) flags |= StringFormatFlagsMeasureTrailingSpaces; if (vertical) - flags |= StringFormatFlagsDirectionVertical | - StringFormatFlagsDirectionRightToLeft; + flags |= StringFormatFlagsDirectionVertical | StringFormatFlagsDirectionRightToLeft; format.SetFormatFlags(flags); format.SetTrimming(StringTrimmingWord); @@ -404,12 +397,10 @@ void TextSource::RemoveNewlinePadding(const StringFormat &format, RectF &box) RectF after; Status stat; - stat = graphics.MeasureString(L"W", 2, font.get(), PointF(0.0f, 0.0f), - &format, &before); + stat = graphics.MeasureString(L"W", 2, font.get(), PointF(0.0f, 0.0f), &format, &before); warn_stat("MeasureString (without newline)"); - stat = graphics.MeasureString(L"W\n", 3, font.get(), PointF(0.0f, 0.0f), - &format, &after); + stat = graphics.MeasureString(L"W\n", 3, font.get(), PointF(0.0f, 0.0f), &format, &after); warn_stat("MeasureString (with newline)"); float offset_cx = after.Width - before.Width; @@ -437,8 +428,7 @@ void TextSource::RemoveNewlinePadding(const StringFormat &format, RectF &box) box.Height -= offset_cy; } -void TextSource::CalculateTextSizes(const StringFormat &format, - RectF &bounding_box, SIZE &text_size) +void TextSource::CalculateTextSizes(const StringFormat &format, RectF &bounding_box, SIZE &text_size) { RectF layout_box; RectF temp_box; @@ -455,17 +445,14 @@ void TextSource::CalculateTextSizes(const StringFormat &format, layout_box.Height -= outline_size; } - stat = graphics.MeasureString(text.c_str(), - (int)text.size() + 1, - font.get(), layout_box, + stat = graphics.MeasureString(text.c_str(), (int)text.size() + 1, font.get(), layout_box, &format, &bounding_box); warn_stat("MeasureString (wrapped)"); temp_box = bounding_box; } else { - stat = graphics.MeasureString( - text.c_str(), (int)text.size() + 1, font.get(), - PointF(0.0f, 0.0f), &format, &bounding_box); + stat = graphics.MeasureString(text.c_str(), (int)text.size() + 1, font.get(), + PointF(0.0f, 0.0f), &format, &bounding_box); warn_stat("MeasureString (non-wrapped)"); temp_box = bounding_box; @@ -508,19 +495,15 @@ void TextSource::CalculateTextSizes(const StringFormat &format, if (!old_extents && !wrap) { if (align == Align::Center) { - bounding_box.X += - (extents_cx - bounding_box.Width) / 2; + bounding_box.X += (extents_cx - bounding_box.Width) / 2; } else if (align == Align::Right) { - bounding_box.X += - extents_cx - bounding_box.Width; + bounding_box.X += extents_cx - bounding_box.Width; } if (valign == VAlign::Center) { - bounding_box.Y += - (extents_cy - bounding_box.Height) / 2; + bounding_box.Y += (extents_cy - bounding_box.Height) / 2; } else if (valign == VAlign::Bottom) { - bounding_box.Y += - extents_cy - bounding_box.Height; + bounding_box.Y += extents_cy - bounding_box.Height; } } } @@ -548,8 +531,7 @@ void TextSource::CalculateTextSizes(const StringFormat &format, bounding_box.Height = temp_box.Height; } -void TextSource::RenderOutlineText(Graphics &graphics, const GraphicsPath &path, - const Brush &brush) +void TextSource::RenderOutlineText(Graphics &graphics, const GraphicsPath &path, const Brush &brush) { DWORD outline_rgba = calc_color(outline_color, outline_opacity); Status stat; @@ -577,14 +559,11 @@ void TextSource::RenderText() CalculateTextSizes(format, box, size); unique_ptr bits(new uint8_t[size.cx * size.cy * 4]); - Bitmap bitmap(size.cx, size.cy, 4 * size.cx, PixelFormat32bppARGB, - bits.get()); + Bitmap bitmap(size.cx, size.cy, 4 * size.cx, PixelFormat32bppARGB, bits.get()); Graphics graphics_bitmap(&bitmap); - LinearGradientBrush brush(RectF(0, 0, (float)size.cx, (float)size.cy), - Color(calc_color(color, opacity)), - Color(calc_color(color2, opacity2)), - gradient_dir, 1); + LinearGradientBrush brush(RectF(0, 0, (float)size.cx, (float)size.cy), Color(calc_color(color, opacity)), + Color(calc_color(color2, opacity2)), gradient_dir, 1); DWORD full_bk_color = bk_color & 0xFFFFFF; if (!text.empty() || use_extents) @@ -613,17 +592,14 @@ void TextSource::RenderText() GraphicsPath path; font->GetFamily(&family); - stat = path.AddString(text.c_str(), (int)text.size(), - &family, font->GetStyle(), + stat = path.AddString(text.c_str(), (int)text.size(), &family, font->GetStyle(), font->GetSize(), box, &format); warn_stat("path.AddString"); RenderOutlineText(graphics_bitmap, path, brush); } else { - stat = graphics_bitmap.DrawString(text.c_str(), - (int)text.size(), - font.get(), box, - &format, &brush); + stat = graphics_bitmap.DrawString(text.c_str(), (int)text.size(), font.get(), box, &format, + &brush); warn_stat("graphics_bitmap.DrawString"); } } @@ -634,8 +610,7 @@ void TextSource::RenderText() gs_texture_destroy(tex); const uint8_t *data = (uint8_t *)bits.get(); - tex = gs_texture_create(size.cx, size.cy, GS_BGRA, 1, &data, - GS_DYNAMIC); + tex = gs_texture_create(size.cx, size.cy, GS_BGRA, 1, &data, GS_DYNAMIC); obs_leave_graphics(); @@ -694,8 +669,7 @@ void TextSource::TransformText() f.tolower(&text[0], &text[0] + text.size()); else if (text_transform == S_TRANSFORM_STARTCASE) { bool upper = true; - for (wstring::iterator it = text.begin(); it != text.end(); - ++it) { + for (wstring::iterator it = text.begin(); it != text.end(); ++it) { const wchar_t upper_char = f.toupper(*it); const wchar_t lower_char = f.tolower(*it); if (upper && lower_char != upper_char) { @@ -713,8 +687,7 @@ void TextSource::TransformText() void TextSource::SetAntiAliasing(Graphics &graphics_bitmap) { if (!antialiasing) { - graphics_bitmap.SetTextRenderingHint( - TextRenderingHintSingleBitPerPixel); + graphics_bitmap.SetTextRenderingHint(TextRenderingHintSingleBitPerPixel); graphics_bitmap.SetSmoothingMode(SmoothingModeNone); return; } @@ -768,9 +741,8 @@ inline void TextSource::Update(obs_data_t *s) wstring new_face = to_wide(font_face); - if (new_face != face || face_size != font_size || new_bold != bold || - new_italic != italic || new_underline != underline || - new_strikeout != strikeout) { + if (new_face != face || face_size != font_size || new_bold != bold || new_italic != italic || + new_underline != underline || new_strikeout != strikeout) { face = new_face; face_size = font_size; @@ -897,8 +869,7 @@ inline void TextSource::Render() gs_technique_begin(tech); gs_technique_begin_pass(tech, 0); - gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), - tex); + gs_effect_set_texture_srgb(gs_effect_get_param_by_name(effect, "image"), tex); gs_draw_sprite(tex, 0, cx, cy); gs_technique_end_pass(tech); @@ -924,8 +895,7 @@ MODULE_EXPORT const char *obs_module_description(void) obs_property_set_visible(p, var == show); \ } while (false) -static bool use_file_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *s) +static bool use_file_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s) { bool use_file = obs_data_get_bool(s, S_USE_FILE); @@ -934,8 +904,7 @@ static bool use_file_changed(obs_properties_t *props, obs_property_t *p, return true; } -static bool outline_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *s) +static bool outline_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s) { bool outline = obs_data_get_bool(s, S_OUTLINE); @@ -945,8 +914,7 @@ static bool outline_changed(obs_properties_t *props, obs_property_t *p, return true; } -static bool chatlog_mode_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *s) +static bool chatlog_mode_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s) { bool chatlog_mode = obs_data_get_bool(s, S_CHATLOG_MODE); @@ -954,8 +922,7 @@ static bool chatlog_mode_changed(obs_properties_t *props, obs_property_t *p, return true; } -static bool gradient_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *s) +static bool gradient_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *s) { bool gradient = obs_data_get_bool(s, S_GRADIENT); @@ -965,8 +932,7 @@ static bool gradient_changed(obs_properties_t *props, obs_property_t *p, return true; } -static bool extents_modified(obs_properties_t *props, obs_property_t *p, - obs_data_t *s) +static bool extents_modified(obs_properties_t *props, obs_property_t *p, obs_data_t *s) { bool use_extents = obs_data_get_bool(s, S_EXTENTS); @@ -1008,53 +974,40 @@ static obs_properties_t *get_properties(void *data) } obs_properties_add_text(props, S_TEXT, T_TEXT, OBS_TEXT_MULTILINE); - obs_properties_add_path(props, S_FILE, T_FILE, OBS_PATH_FILE, - filter.c_str(), path.c_str()); + obs_properties_add_path(props, S_FILE, T_FILE, OBS_PATH_FILE, filter.c_str(), path.c_str()); obs_properties_add_bool(props, S_ANTIALIASING, T_ANTIALIASING); - p = obs_properties_add_list(props, S_TRANSFORM, T_TRANSFORM, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(props, S_TRANSFORM, T_TRANSFORM, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(p, T_TRANSFORM_NONE, S_TRANSFORM_NONE); - obs_property_list_add_int(p, T_TRANSFORM_UPPERCASE, - S_TRANSFORM_UPPERCASE); - obs_property_list_add_int(p, T_TRANSFORM_LOWERCASE, - S_TRANSFORM_LOWERCASE); - obs_property_list_add_int(p, T_TRANSFORM_STARTCASE, - S_TRANSFORM_STARTCASE); + obs_property_list_add_int(p, T_TRANSFORM_UPPERCASE, S_TRANSFORM_UPPERCASE); + obs_property_list_add_int(p, T_TRANSFORM_LOWERCASE, S_TRANSFORM_LOWERCASE); + obs_property_list_add_int(p, T_TRANSFORM_STARTCASE, S_TRANSFORM_STARTCASE); obs_properties_add_bool(props, S_VERTICAL, T_VERTICAL); obs_properties_add_color(props, S_COLOR, T_COLOR); - p = obs_properties_add_int_slider(props, S_OPACITY, T_OPACITY, 0, 100, - 1); + p = obs_properties_add_int_slider(props, S_OPACITY, T_OPACITY, 0, 100, 1); obs_property_int_set_suffix(p, "%"); p = obs_properties_add_bool(props, S_GRADIENT, T_GRADIENT); obs_property_set_modified_callback(p, gradient_changed); obs_properties_add_color(props, S_GRADIENT_COLOR, T_GRADIENT_COLOR); - p = obs_properties_add_int_slider(props, S_GRADIENT_OPACITY, - T_GRADIENT_OPACITY, 0, 100, 1); + p = obs_properties_add_int_slider(props, S_GRADIENT_OPACITY, T_GRADIENT_OPACITY, 0, 100, 1); obs_property_int_set_suffix(p, "%"); - obs_properties_add_float_slider(props, S_GRADIENT_DIR, T_GRADIENT_DIR, - 0, 360, 0.1); + obs_properties_add_float_slider(props, S_GRADIENT_DIR, T_GRADIENT_DIR, 0, 360, 0.1); obs_properties_add_color(props, S_BKCOLOR, T_BKCOLOR); - p = obs_properties_add_int_slider(props, S_BKOPACITY, T_BKOPACITY, 0, - 100, 1); + p = obs_properties_add_int_slider(props, S_BKOPACITY, T_BKOPACITY, 0, 100, 1); obs_property_int_set_suffix(p, "%"); - p = obs_properties_add_list(props, S_ALIGN, T_ALIGN, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(props, S_ALIGN, T_ALIGN, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_ALIGN_LEFT, S_ALIGN_LEFT); obs_property_list_add_string(p, T_ALIGN_CENTER, S_ALIGN_CENTER); obs_property_list_add_string(p, T_ALIGN_RIGHT, S_ALIGN_RIGHT); - p = obs_properties_add_list(props, S_VALIGN, T_VALIGN, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(props, S_VALIGN, T_VALIGN, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, T_VALIGN_TOP, S_VALIGN_TOP); obs_property_list_add_string(p, T_VALIGN_CENTER, S_VALIGN_CENTER); obs_property_list_add_string(p, T_VALIGN_BOTTOM, S_VALIGN_BOTTOM); @@ -1064,15 +1017,13 @@ static obs_properties_t *get_properties(void *data) obs_properties_add_int(props, S_OUTLINE_SIZE, T_OUTLINE_SIZE, 1, 20, 1); obs_properties_add_color(props, S_OUTLINE_COLOR, T_OUTLINE_COLOR); - p = obs_properties_add_int_slider(props, S_OUTLINE_OPACITY, - T_OUTLINE_OPACITY, 0, 100, 1); + p = obs_properties_add_int_slider(props, S_OUTLINE_OPACITY, T_OUTLINE_OPACITY, 0, 100, 1); obs_property_int_set_suffix(p, "%"); p = obs_properties_add_bool(props, S_CHATLOG_MODE, T_CHATLOG_MODE); obs_property_set_modified_callback(p, chatlog_mode_changed); - obs_properties_add_int(props, S_CHATLOG_LINES, T_CHATLOG_LINES, 1, 1000, - 1); + obs_properties_add_int(props, S_CHATLOG_LINES, T_CHATLOG_LINES, 1, 1000, 1); p = obs_properties_add_bool(props, S_EXTENTS, T_EXTENTS); obs_property_set_modified_callback(p, extents_modified); @@ -1131,8 +1082,7 @@ bool obs_module_load(void) obs_source_info si = {}; si.id = "text_gdiplus"; si.type = OBS_SOURCE_TYPE_INPUT; - si.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_CAP_OBSOLETE | OBS_SOURCE_SRGB; + si.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_CAP_OBSOLETE | OBS_SOURCE_SRGB; si.get_properties = get_properties; si.icon_type = OBS_ICON_TYPE_TEXT; @@ -1175,11 +1125,8 @@ bool obs_module_load(void) if (read && strcmp(path, "") != 0) { if (!os_file_exists(path)) { - obs_missing_file_t *file = - obs_missing_file_create( - path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, - s->source, NULL); + obs_missing_file_t *file = obs_missing_file_create( + path, missing_file_callback, OBS_MISSING_FILE_SOURCE, s->source, NULL); obs_missing_files_add_file(files, file); } diff --git a/plugins/obs-transitions/transition-cut.c b/plugins/obs-transitions/transition-cut.c index 1400eeace..4637f037e 100644 --- a/plugins/obs-transitions/transition-cut.c +++ b/plugins/obs-transitions/transition-cut.c @@ -47,19 +47,15 @@ static float mix_b(void *data, float t) return t; } -static bool cut_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool cut_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) { struct cut_info *cut = data; - return obs_transition_audio_render(cut->source, ts_out, audio, mixers, - channels, sample_rate, mix_a, mix_b); + return obs_transition_audio_render(cut->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } -static enum gs_color_space -cut_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space cut_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); diff --git a/plugins/obs-transitions/transition-fade-to-color.c b/plugins/obs-transitions/transition-fade-to-color.c index eba57d839..f926cfcc4 100644 --- a/plugins/obs-transitions/transition-fade-to-color.c +++ b/plugins/obs-transitions/transition-fade-to-color.c @@ -72,8 +72,7 @@ static void *fade_to_color_create(obs_data_t *settings, obs_source_t *source) bfree(file); if (!effect) { - blog(LOG_ERROR, - "Could not find fade_to_color_transition.effect"); + blog(LOG_ERROR, "Could not find fade_to_color_transition.effect"); return NULL; } @@ -97,8 +96,7 @@ static void fade_to_color_destroy(void *data) bfree(fade_to_color); } -static void fade_to_color_callback(void *data, gs_texture_t *a, gs_texture_t *b, - float t, uint32_t cx, uint32_t cy) +static void fade_to_color_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct fade_to_color_info *fade_to_color = data; @@ -116,12 +114,10 @@ static void fade_to_color_callback(void *data, gs_texture_t *a, gs_texture_t *b, if (nonlinear_fade) { gs_effect_set_texture(fade_to_color->ep_tex, tex); - gs_effect_set_vec4(fade_to_color->ep_color, - &fade_to_color->color); + gs_effect_set_vec4(fade_to_color->ep_color, &fade_to_color->color); } else { gs_effect_set_texture_srgb(fade_to_color->ep_tex, tex); - gs_effect_set_vec4(fade_to_color->ep_color, - &fade_to_color->color_srgb); + gs_effect_set_vec4(fade_to_color->ep_color, &fade_to_color->color_srgb); } gs_effect_set_float(fade_to_color->ep_swp, swp); @@ -139,8 +135,7 @@ static void fade_to_color_video_render(void *data, gs_effect_t *effect) const bool previous = gs_set_linear_srgb(true); struct fade_to_color_info *fade_to_color = data; - obs_transition_video_render(fade_to_color->source, - fade_to_color_callback); + obs_transition_video_render(fade_to_color->source, fade_to_color_callback); gs_set_linear_srgb(previous); } @@ -161,14 +156,11 @@ static float mix_b(void *data, float t) return lerp(0.0f, t, smoothstep(sp, 1.0f, t)); } -static bool fade_to_color_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool fade_to_color_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, + uint32_t mixers, size_t channels, size_t sample_rate) { struct fade_to_color_info *fade_to_color = data; - return obs_transition_audio_render(fade_to_color->source, ts_out, audio, - mixers, channels, sample_rate, mix_a, + return obs_transition_audio_render(fade_to_color->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } @@ -177,8 +169,7 @@ static obs_properties_t *fade_to_color_properties(void *data) obs_properties_t *props = obs_properties_create(); obs_properties_add_color(props, S_COLOR, S_COLOR_TEXT); - obs_property_t *p = obs_properties_add_int_slider( - props, S_SWITCH_POINT, S_SWITCH_POINT_TEXT, 0, 100, 1); + obs_property_t *p = obs_properties_add_int_slider(props, S_SWITCH_POINT, S_SWITCH_POINT_TEXT, 0, 100, 1); obs_property_int_set_suffix(p, "%"); UNUSED_PARAMETER(data); @@ -191,13 +182,11 @@ static void fade_to_color_defaults(obs_data_t *settings) obs_data_set_default_int(settings, S_SWITCH_POINT, 50); } -static enum gs_color_space -fade_to_color_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space fade_to_color_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { struct fade_to_color_info *fade_to_color = data; - const enum gs_color_space transition_space = - obs_transition_video_get_color_space(fade_to_color->source); + const enum gs_color_space transition_space = obs_transition_video_get_color_space(fade_to_color->source); enum gs_color_space space = transition_space; for (size_t i = 0; i < count; ++i) { diff --git a/plugins/obs-transitions/transition-fade.c b/plugins/obs-transitions/transition-fade.c index 947c911a9..1634f1b9a 100644 --- a/plugins/obs-transitions/transition-fade.c +++ b/plugins/obs-transitions/transition-fade.c @@ -48,8 +48,7 @@ static void fade_destroy(void *data) bfree(fade); } -static void fade_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, - uint32_t cx, uint32_t cy) +static void fade_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { if (a || b) { struct fade_info *fade = data; @@ -114,23 +113,18 @@ static float mix_b(void *data, float t) return t; } -static bool fade_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool fade_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) { struct fade_info *fade = data; - return obs_transition_audio_render(fade->source, ts_out, audio, mixers, - channels, sample_rate, mix_a, mix_b); + return obs_transition_audio_render(fade->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } -static enum gs_color_space -fade_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space fade_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { struct fade_info *const fade = data; - const enum gs_color_space transition_space = - obs_transition_video_get_color_space(fade->source); + const enum gs_color_space transition_space = obs_transition_video_get_color_space(fade->source); enum gs_color_space space = transition_space; for (size_t i = 0; i < count; ++i) { diff --git a/plugins/obs-transitions/transition-luma-wipe.c b/plugins/obs-transitions/transition-luma-wipe.c index 3c0f3b43a..b2c04efeb 100644 --- a/plugins/obs-transitions/transition-luma-wipe.c +++ b/plugins/obs-transitions/transition-luma-wipe.c @@ -131,9 +131,7 @@ static obs_properties_t *luma_wipe_properties(void *data) obs_property_t *p; - p = obs_properties_add_list(props, S_LUMA_IMG, T_LUMA_IMG, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(props, S_LUMA_IMG, T_LUMA_IMG, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); if (data) { struct luma_wipe_info *lwipe = data; @@ -143,13 +141,11 @@ static obs_properties_t *luma_wipe_properties(void *data) for (; item != NULL; obs_data_item_next(&item)) { const char *name = obs_data_item_get_name(item); const char *path = obs_data_item_get_string(item); - obs_property_list_add_string(p, obs_module_text(name), - path); + obs_property_list_add_string(p, obs_module_text(name), path); } } - obs_properties_add_float(props, S_LUMA_SOFT, T_LUMA_SOFT, 0.0, 1.0, - 0.05); + obs_properties_add_float(props, S_LUMA_SOFT, T_LUMA_SOFT, 0.0, 1.0, 0.05); obs_properties_add_bool(props, S_LUMA_INV, T_LUMA_INV); return props; @@ -162,8 +158,7 @@ static void luma_wipe_defaults(obs_data_t *settings) obs_data_set_default_bool(settings, S_LUMA_INV, false); } -static void luma_wipe_callback(void *data, gs_texture_t *a, gs_texture_t *b, - float t, uint32_t cx, uint32_t cy) +static void luma_wipe_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct luma_wipe_info *lwipe = data; @@ -203,18 +198,15 @@ static float mix_b(void *data, float t) return t; } -bool luma_wipe_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, uint32_t mixers, +bool luma_wipe_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, size_t channels, size_t sample_rate) { struct luma_wipe_info *lwipe = data; - return obs_transition_audio_render(lwipe->source, ts_out, audio, mixers, - channels, sample_rate, mix_a, mix_b); + return obs_transition_audio_render(lwipe->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } -static enum gs_color_space -luma_wipe_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space luma_wipe_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); diff --git a/plugins/obs-transitions/transition-slide.c b/plugins/obs-transitions/transition-slide.c index 799cc6a3e..a4fad37da 100644 --- a/plugins/obs-transitions/transition-slide.c +++ b/plugins/obs-transitions/transition-slide.c @@ -64,10 +64,8 @@ void *slide_create(obs_data_t *settings, obs_source_t *source) slide->a_param = gs_effect_get_param_by_name(effect, "tex_a"); slide->b_param = gs_effect_get_param_by_name(effect, "tex_b"); - slide->tex_a_dir_param = - gs_effect_get_param_by_name(effect, "tex_a_dir"); - slide->tex_b_dir_param = - gs_effect_get_param_by_name(effect, "tex_b_dir"); + slide->tex_a_dir_param = gs_effect_get_param_by_name(effect, "tex_a_dir"); + slide->tex_b_dir_param = gs_effect_get_param_by_name(effect, "tex_b_dir"); obs_source_update(source, settings); @@ -80,8 +78,7 @@ void slide_destroy(void *data) bfree(slide); } -static void slide_callback(void *data, gs_texture_t *a, gs_texture_t *b, - float t, uint32_t cx, uint32_t cy) +static void slide_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct slide_info *slide = data; @@ -127,13 +124,11 @@ static float mix_b(void *data, float t) return cubic_ease_in_out(t); } -bool slide_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, uint32_t mixers, +bool slide_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, size_t channels, size_t sample_rate) { struct slide_info *slide = data; - return obs_transition_audio_render(slide->source, ts_out, audio, mixers, - channels, sample_rate, mix_a, mix_b); + return obs_transition_audio_render(slide->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } static obs_properties_t *slide_properties(void *data) @@ -141,25 +136,19 @@ static obs_properties_t *slide_properties(void *data) obs_properties_t *ppts = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(ppts, S_DIRECTION, - obs_module_text("Direction"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, S_DIRECTION, obs_module_text("Direction"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, obs_module_text("Direction.Left"), - "left"); - obs_property_list_add_string(p, obs_module_text("Direction.Right"), - "right"); + obs_property_list_add_string(p, obs_module_text("Direction.Left"), "left"); + obs_property_list_add_string(p, obs_module_text("Direction.Right"), "right"); obs_property_list_add_string(p, obs_module_text("Direction.Up"), "up"); - obs_property_list_add_string(p, obs_module_text("Direction.Down"), - "down"); + obs_property_list_add_string(p, obs_module_text("Direction.Down"), "down"); UNUSED_PARAMETER(data); return ppts; } -static enum gs_color_space -slide_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space slide_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); diff --git a/plugins/obs-transitions/transition-stinger.c b/plugins/obs-transitions/transition-stinger.c index ce41b4d92..38ad40a8d 100644 --- a/plugins/obs-transitions/transition-stinger.c +++ b/plugins/obs-transitions/transition-stinger.c @@ -77,22 +77,19 @@ static void stinger_update(void *data, obs_data_t *settings) obs_data_set_bool(media_settings, "looping", false); obs_data_set_bool(media_settings, "full_decode", preload); obs_data_set_bool(media_settings, "is_stinger", true); - obs_data_set_bool(media_settings, "is_track_matte", - s->track_matte_enabled); + obs_data_set_bool(media_settings, "is_track_matte", s->track_matte_enabled); obs_source_release(s->media_source); struct dstr name; dstr_init_copy(&name, obs_source_get_name(s->source)); dstr_cat(&name, " (Stinger)"); - s->media_source = obs_source_create_private("ffmpeg_source", name.array, - media_settings); + s->media_source = obs_source_create_private("ffmpeg_source", name.array, media_settings); dstr_free(&name); obs_data_release(media_settings); int64_t point = obs_data_get_int(settings, "transition_point"); - s->transition_point_is_frame = obs_data_get_int(settings, "tp_type") == - TIMING_FRAME; + s->transition_point_is_frame = obs_data_get_int(settings, "tp_type") == TIMING_FRAME; if (s->transition_point_is_frame) s->transition_point_frame = (uint64_t)point; @@ -101,46 +98,37 @@ static void stinger_update(void *data, obs_data_t *settings) bool track_matte_was_enabled = s->track_matte_enabled; - s->track_matte_enabled = - obs_data_get_bool(settings, "track_matte_enabled"); + s->track_matte_enabled = obs_data_get_bool(settings, "track_matte_enabled"); s->matte_layout = (int)obs_data_get_int(settings, "track_matte_layout"); - s->matte_width_factor = - (s->matte_layout == MATTE_LAYOUT_HORIZONTAL ? 2.0f : 1.0f); - s->matte_height_factor = - (s->matte_layout == MATTE_LAYOUT_VERTICAL ? 2.0f : 1.0f); + s->matte_width_factor = (s->matte_layout == MATTE_LAYOUT_HORIZONTAL ? 2.0f : 1.0f); + s->matte_height_factor = (s->matte_layout == MATTE_LAYOUT_VERTICAL ? 2.0f : 1.0f); s->invert_matte = obs_data_get_bool(settings, "invert_matte"); - s->do_texrender = s->track_matte_enabled && - s->matte_layout < MATTE_LAYOUT_SEPARATE_FILE; + s->do_texrender = s->track_matte_enabled && s->matte_layout < MATTE_LAYOUT_SEPARATE_FILE; if (s->matte_source) { obs_source_release(s->matte_source); s->matte_source = NULL; } - if (s->track_matte_enabled && - s->matte_layout == MATTE_LAYOUT_SEPARATE_FILE) { - const char *tm_path = - obs_data_get_string(settings, "track_matte_path"); + if (s->track_matte_enabled && s->matte_layout == MATTE_LAYOUT_SEPARATE_FILE) { + const char *tm_path = obs_data_get_string(settings, "track_matte_path"); obs_data_t *tm_media_settings = obs_data_create(); obs_data_set_string(tm_media_settings, "local_file", tm_path); obs_data_set_bool(tm_media_settings, "looping", false); - s->matte_source = obs_source_create_private( - "ffmpeg_source", NULL, tm_media_settings); + s->matte_source = obs_source_create_private("ffmpeg_source", NULL, tm_media_settings); obs_data_release(tm_media_settings); // no need to output sound from the matte video obs_source_set_muted(s->matte_source, true); } - s->monitoring_type = - (int)obs_data_get_int(settings, "audio_monitoring"); + s->monitoring_type = (int)obs_data_get_int(settings, "audio_monitoring"); obs_source_set_monitoring_type(s->media_source, s->monitoring_type); - s->fade_style = - (enum fade_style)obs_data_get_int(settings, "audio_fade_style"); + s->fade_style = (enum fade_style)obs_data_get_int(settings, "audio_fade_style"); switch (s->fade_style) { default: @@ -164,8 +152,7 @@ static void stinger_update(void *data, obs_data_t *settings) if (s->track_matte_enabled) { s->matte_tex = gs_texrender_create(GS_RGBA, GS_ZS_NONE); - s->stinger_tex = - gs_texrender_create(GS_RGBA, GS_ZS_NONE); + s->stinger_tex = gs_texrender_create(GS_RGBA, GS_ZS_NONE); } obs_leave_graphics(); @@ -183,14 +170,11 @@ static void *stinger_create(obs_data_t *settings, obs_source_t *source) char *effect_file = obs_module_file("stinger_matte_transition.effect"); char *error_string = NULL; obs_enter_graphics(); - s->matte_effect = - gs_effect_create_from_file(effect_file, &error_string); + s->matte_effect = gs_effect_create_from_file(effect_file, &error_string); obs_leave_graphics(); if (!s->matte_effect) { - blog(LOG_ERROR, - "Could not open stinger_matte_transition.effect: %s", - error_string); + blog(LOG_ERROR, "Could not open stinger_matte_transition.effect: %s", error_string); bfree(error_string); bfree(s); return NULL; @@ -200,10 +184,8 @@ static void *stinger_create(obs_data_t *settings, obs_source_t *source) s->ep_a_tex = gs_effect_get_param_by_name(s->matte_effect, "a_tex"); s->ep_b_tex = gs_effect_get_param_by_name(s->matte_effect, "b_tex"); - s->ep_matte_tex = - gs_effect_get_param_by_name(s->matte_effect, "matte_tex"); - s->ep_invert_matte = - gs_effect_get_param_by_name(s->matte_effect, "invert_matte"); + s->ep_matte_tex = gs_effect_get_param_by_name(s->matte_effect, "matte_tex"); + s->ep_invert_matte = gs_effect_get_param_by_name(s->matte_effect, "invert_matte"); obs_transition_enable_fixed(s->source, true, 0); obs_source_update(source, settings); @@ -232,8 +214,7 @@ static void stinger_defaults(obs_data_t *settings) obs_data_set_default_bool(settings, "hw_decode", true); } -static void stinger_matte_render(void *data, gs_texture_t *a, gs_texture_t *b, - float t, uint32_t cx, uint32_t cy) +static void stinger_matte_render(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct stinger_info *s = data; @@ -241,42 +222,31 @@ static void stinger_matte_render(void *data, gs_texture_t *a, gs_texture_t *b, vec4_zero(&background); obs_source_t *matte_source = - (s->matte_layout == MATTE_LAYOUT_SEPARATE_FILE - ? s->matte_source - : s->media_source); + (s->matte_layout == MATTE_LAYOUT_SEPARATE_FILE ? s->matte_source : s->media_source); - float matte_cx = (float)obs_source_get_width(matte_source) / - s->matte_width_factor; - float matte_cy = (float)obs_source_get_height(matte_source) / - s->matte_height_factor; + float matte_cx = (float)obs_source_get_width(matte_source) / s->matte_width_factor; + float matte_cy = (float)obs_source_get_height(matte_source) / s->matte_height_factor; - float width_offset = (s->matte_layout == MATTE_LAYOUT_HORIZONTAL - ? (-matte_cx) - : 0.0f); - float height_offset = - (s->matte_layout == MATTE_LAYOUT_VERTICAL ? (-matte_cy) : 0.0f); + float width_offset = (s->matte_layout == MATTE_LAYOUT_HORIZONTAL ? (-matte_cx) : 0.0f); + float height_offset = (s->matte_layout == MATTE_LAYOUT_VERTICAL ? (-matte_cy) : 0.0f); // Track matte media render if (matte_cx > 0 && matte_cy > 0) { float scale_x = (float)cx / matte_cx; float scale_y = (float)cy / matte_cy; - const enum gs_color_space space = - obs_source_get_color_space(matte_source, 0, NULL); + const enum gs_color_space space = obs_source_get_color_space(matte_source, 0, NULL); enum gs_color_format format = gs_get_format_from_space(space); if (gs_texrender_get_format(s->matte_tex) != format) { gs_texrender_destroy(s->matte_tex); s->matte_tex = gs_texrender_create(format, GS_ZS_NONE); } - if (gs_texrender_begin_with_color_space(s->matte_tex, cx, cy, - space)) { + if (gs_texrender_begin_with_color_space(s->matte_tex, cx, cy, space)) { gs_matrix_scale3f(scale_x, scale_y, 1.0f); - gs_matrix_translate3f(width_offset, height_offset, - 0.0f); + gs_matrix_translate3f(width_offset, height_offset, 0.0f); gs_clear(GS_CLEAR_COLOR, &background, 0.0f, 0); - gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, - 100.0f); + gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); obs_source_video_render(matte_source); @@ -299,8 +269,7 @@ static void stinger_matte_render(void *data, gs_texture_t *a, gs_texture_t *b, gs_effect_set_texture_srgb(s->ep_b_tex, b); tech_name = "StingerMatteLinear"; } - gs_effect_set_texture(s->ep_matte_tex, - gs_texrender_get_texture(s->matte_tex)); + gs_effect_set_texture(s->ep_matte_tex, gs_texrender_get_texture(s->matte_tex)); gs_effect_set_bool(s->ep_invert_matte, s->invert_matte); while (gs_effect_loop(s->matte_effect, tech_name)) @@ -311,8 +280,7 @@ static void stinger_matte_render(void *data, gs_texture_t *a, gs_texture_t *b, UNUSED_PARAMETER(t); } -static void stinger_texrender(struct stinger_info *s, uint32_t source_cx, - uint32_t source_cy, uint32_t media_cx, +static void stinger_texrender(struct stinger_info *s, uint32_t source_cx, uint32_t source_cy, uint32_t media_cx, uint32_t media_cy, enum gs_color_space space) { enum gs_color_format format = gs_get_format_from_space(space); @@ -321,8 +289,7 @@ static void stinger_texrender(struct stinger_info *s, uint32_t source_cx, s->stinger_tex = gs_texrender_create(format, GS_ZS_NONE); } - if (gs_texrender_begin_with_color_space(s->stinger_tex, source_cx, - source_cy, space)) { + if (gs_texrender_begin_with_color_space(s->stinger_tex, source_cx, source_cy, space)) { float cx = (float)media_cx / s->matte_width_factor; float cy = (float)media_cy / s->matte_height_factor; @@ -337,10 +304,8 @@ static void stinger_texrender(struct stinger_info *s, uint32_t source_cx, } } -static const char * -get_tech_name_and_multiplier(enum gs_color_space current_space, - enum gs_color_space source_space, - float *multiplier) +static const char *get_tech_name_and_multiplier(enum gs_color_space current_space, enum gs_color_space source_space, + float *multiplier) { const char *tech_name = "Draw"; *multiplier = 1.f; @@ -394,18 +359,14 @@ static void stinger_video_render(void *data, gs_effect_t *effect) uint32_t media_cy = obs_source_get_height(s->media_source); if (s->track_matte_enabled) { - bool ready = obs_source_active(s->media_source) && !!media_cx && - !!media_cy; + bool ready = obs_source_active(s->media_source) && !!media_cx && !!media_cy; if (ready) { if (!s->matte_rendered) s->matte_rendered = true; - obs_transition_video_render(s->source, - stinger_matte_render); + obs_transition_video_render(s->source, stinger_matte_render); } else { - obs_transition_video_render_direct( - s->source, s->matte_rendered - ? OBS_TRANSITION_SOURCE_B - : OBS_TRANSITION_SOURCE_A); + obs_transition_video_render_direct(s->source, s->matte_rendered ? OBS_TRANSITION_SOURCE_B + : OBS_TRANSITION_SOURCE_A); } if (s->matte_layout == MATTE_LAYOUT_MASK) return; @@ -413,9 +374,7 @@ static void stinger_video_render(void *data, gs_effect_t *effect) float t = obs_transition_get_time(s->source); bool use_a = t < s->transition_point; - enum obs_transition_target target = - use_a ? OBS_TRANSITION_SOURCE_A - : OBS_TRANSITION_SOURCE_B; + enum obs_transition_target target = use_a ? OBS_TRANSITION_SOURCE_A : OBS_TRANSITION_SOURCE_B; if (!obs_transition_video_render_direct(s->source, target)) return; @@ -433,22 +392,18 @@ static void stinger_video_render(void *data, gs_effect_t *effect) return; if (s->do_texrender) { - const enum gs_color_space space = - obs_source_get_color_space(s->media_source, 0, NULL); - stinger_texrender(s, source_cx, source_cy, media_cx, media_cy, - space); + const enum gs_color_space space = obs_source_get_color_space(s->media_source, 0, NULL); + stinger_texrender(s, source_cx, source_cy, media_cx, media_cy, space); const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(true); float multiplier; - const char *technique = get_tech_name_and_multiplier( - gs_get_color_space(), space, &multiplier); + const char *technique = get_tech_name_and_multiplier(gs_get_color_space(), space, &multiplier); gs_effect_t *e = obs_get_base_effect(OBS_EFFECT_DEFAULT); gs_eparam_t *p_image = gs_effect_get_param_by_name(e, "image"); - gs_eparam_t *p_multiplier = - gs_effect_get_param_by_name(e, "multiplier"); + gs_eparam_t *p_multiplier = gs_effect_get_param_by_name(e, "multiplier"); gs_texture_t *tex = gs_texrender_get_texture(s->stinger_tex); gs_effect_set_texture_srgb(p_image, tex); @@ -460,8 +415,7 @@ static void stinger_video_render(void *data, gs_effect_t *effect) } else { const bool previous = gs_set_linear_srgb(true); gs_matrix_push(); - gs_matrix_scale3f(source_cxf / (float)media_cx, - source_cyf / (float)media_cy, 1.0f); + gs_matrix_scale3f(source_cxf / (float)media_cx, source_cyf / (float)media_cy, 1.0f); obs_source_video_render(s->media_source); gs_matrix_pop(); gs_set_linear_srgb(previous); @@ -512,10 +466,8 @@ static float mix_b_cross_fade(void *data, float t) return t; } -static bool stinger_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool stinger_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) { struct stinger_info *s = data; uint64_t ts = 0; @@ -530,9 +482,7 @@ static bool stinger_audio_render(void *data, uint64_t *ts_out, return false; } - bool success = obs_transition_audio_render(s->source, ts_out, audio, - mixers, channels, - sample_rate, s->mix_a, + bool success = obs_transition_audio_render(s->source, ts_out, audio, mixers, channels, sample_rate, s->mix_a, s->mix_b); if (!ts) return success; @@ -567,12 +517,8 @@ static void stinger_transition_start(void *data) if (s->media_source) { calldata_t cd = {0}; - proc_handler_t *ph = - obs_source_get_proc_handler(s->media_source); - proc_handler_t *matte_ph = - s->matte_source - ? obs_source_get_proc_handler(s->matte_source) - : NULL; + proc_handler_t *ph = obs_source_get_proc_handler(s->media_source); + proc_handler_t *matte_ph = s->matte_source ? obs_source_get_proc_handler(s->matte_source) : NULL; if (s->transitioning) { proc_handler_call(ph, "restart", &cd); @@ -586,18 +532,15 @@ static void stinger_transition_start(void *data) proc_handler_call(ph, "get_duration", &cd); proc_handler_call(ph, "get_nb_frames", &cd); - s->duration_ns = - (uint64_t)calldata_int(&cd, "duration") + 250000000ULL; + s->duration_ns = (uint64_t)calldata_int(&cd, "duration") + 250000000ULL; s->duration_frames = (uint64_t)calldata_int(&cd, "num_frames"); if (s->transition_point_is_frame) s->transition_point = - (float)((long double)s->transition_point_frame / - (long double)s->duration_frames); + (float)((long double)s->transition_point_frame / (long double)s->duration_frames); else s->transition_point = - (float)((long double)s->transition_point_ns / - (long double)s->duration_ns); + (float)((long double)s->transition_point_ns / (long double)s->duration_ns); if (s->transition_point > 0.999f) s->transition_point = 0.999f; @@ -609,18 +552,14 @@ static void stinger_transition_start(void *data) if (s->track_matte_enabled && s->matte_source) { proc_handler_call(matte_ph, "get_duration", &cd); - uint64_t tm_duration_ns = - (uint64_t)calldata_int(&cd, "duration"); + uint64_t tm_duration_ns = (uint64_t)calldata_int(&cd, "duration"); - s->duration_ns = ((tm_duration_ns > s->duration_ns) - ? (tm_duration_ns) - : (s->duration_ns)); + s->duration_ns = ((tm_duration_ns > s->duration_ns) ? (tm_duration_ns) : (s->duration_ns)); obs_source_add_active_child(s->source, s->matte_source); } - obs_transition_enable_fixed( - s->source, true, (uint32_t)(s->duration_ns / 1000000)); + obs_transition_enable_fixed(s->source, true, (uint32_t)(s->duration_ns / 1000000)); calldata_free(&cd); @@ -648,9 +587,7 @@ static void stinger_transition_stop(void *data) s->transitioning = false; } -static void stinger_enum_active_sources(void *data, - obs_source_enum_proc_t enum_callback, - void *param) +static void stinger_enum_active_sources(void *data, obs_source_enum_proc_t enum_callback, void *param) { struct stinger_info *s = data; if (s->media_source && s->transitioning) @@ -660,9 +597,7 @@ static void stinger_enum_active_sources(void *data, enum_callback(s->source, s->matte_source, param); } -static void stinger_enum_all_sources(void *data, - obs_source_enum_proc_t enum_callback, - void *param) +static void stinger_enum_all_sources(void *data, obs_source_enum_proc_t enum_callback, void *param) { struct stinger_info *s = data; if (s->media_source) @@ -674,23 +609,17 @@ static void stinger_enum_all_sources(void *data, #define FILE_FILTER " (*.mp4 *.ts *.mov *.wmv *.flv *.mkv *.avi *.gif *.webm);;" -static bool transition_point_type_modified(obs_properties_t *ppts, - obs_property_t *p, obs_data_t *s) +static bool transition_point_type_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *s) { int64_t type = obs_data_get_int(s, "tp_type"); - obs_property_t *prop_transition_point = - obs_properties_get(ppts, "transition_point"); + obs_property_t *prop_transition_point = obs_properties_get(ppts, "transition_point"); if (type == TIMING_TIME) { - obs_property_set_description( - prop_transition_point, - obs_module_text("TransitionPoint")); + obs_property_set_description(prop_transition_point, obs_module_text("TransitionPoint")); obs_property_int_set_suffix(prop_transition_point, " ms"); } else { - obs_property_set_description( - prop_transition_point, - obs_module_text("TransitionPointFrame")); + obs_property_set_description(prop_transition_point, obs_module_text("TransitionPointFrame")); obs_property_int_set_suffix(prop_transition_point, ""); } @@ -698,12 +627,10 @@ static bool transition_point_type_modified(obs_properties_t *ppts, return true; } -static bool track_matte_layout_modified(obs_properties_t *ppts, - obs_property_t *p, obs_data_t *s) +static bool track_matte_layout_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *s) { int matte_layout = (int)obs_data_get_int(s, "track_matte_layout"); - obs_property_t *prop_matte_path = - obs_properties_get(ppts, "track_matte_path"); + obs_property_t *prop_matte_path = obs_properties_get(ppts, "track_matte_path"); bool uses_separate_file = (matte_layout == MATTE_LAYOUT_SEPARATE_FILE); obs_property_set_visible(prop_matte_path, uses_separate_file); @@ -712,19 +639,15 @@ static bool track_matte_layout_modified(obs_properties_t *ppts, return true; } -static bool track_matte_enabled_modified(obs_properties_t *ppts, - obs_property_t *p, obs_data_t *s) +static bool track_matte_enabled_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *s) { bool track_matte_enabled = obs_data_get_bool(s, "track_matte_enabled"); obs_property_t *prop_tp_type = obs_properties_get(ppts, "tp_type"); if (track_matte_enabled) { - obs_property_set_description( - prop_tp_type, - obs_module_text("AudioTransitionPointType")); + obs_property_set_description(prop_tp_type, obs_module_text("AudioTransitionPointType")); } else { - obs_property_set_description( - prop_tp_type, obs_module_text("TransitionPointType")); + obs_property_set_description(prop_tp_type, obs_module_text("TransitionPointType")); } UNUSED_PARAMETER(p); @@ -744,45 +667,30 @@ static obs_properties_t *stinger_properties(void *data) dstr_cat(&filter, " (*.*)"); // main stinger settings - obs_properties_add_path(ppts, "path", obs_module_text("VideoFile"), - OBS_PATH_FILE, filter.array, NULL); + obs_properties_add_path(ppts, "path", obs_module_text("VideoFile"), OBS_PATH_FILE, filter.array, NULL); - obs_property_t *p = obs_properties_add_list( - ppts, "tp_type", obs_module_text("TransitionPointType"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(p, obs_module_text("TransitionPointTypeTime"), - TIMING_TIME); - obs_property_list_add_int( - p, obs_module_text("TransitionPointTypeFrame"), TIMING_FRAME); + obs_property_t *p = obs_properties_add_list(ppts, "tp_type", obs_module_text("TransitionPointType"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(p, obs_module_text("TransitionPointTypeTime"), TIMING_TIME); + obs_property_list_add_int(p, obs_module_text("TransitionPointTypeFrame"), TIMING_FRAME); obs_property_set_modified_callback(p, transition_point_type_modified); - obs_properties_add_bool(ppts, "hw_decode", - obs_module_text("HardwareDecode")); - p = obs_properties_add_bool(ppts, "preload", - obs_module_text("PreloadVideoToRam")); - obs_property_set_long_description( - p, obs_module_text("PreloadVideoToRam.Description")); + obs_properties_add_bool(ppts, "hw_decode", obs_module_text("HardwareDecode")); + p = obs_properties_add_bool(ppts, "preload", obs_module_text("PreloadVideoToRam")); + obs_property_set_long_description(p, obs_module_text("PreloadVideoToRam.Description")); - obs_properties_add_int(ppts, "transition_point", - obs_module_text("TransitionPoint"), 0, 120000, - 1); + obs_properties_add_int(ppts, "transition_point", obs_module_text("TransitionPoint"), 0, 120000, 1); // track matte properties { obs_properties_t *track_matte_group = obs_properties_create(); - p = obs_properties_add_list(track_matte_group, - "track_matte_layout", - obs_module_text("TrackMatteLayout"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(track_matte_group, "track_matte_layout", + obs_module_text("TrackMatteLayout"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int( - p, obs_module_text("TrackMatteLayoutHorizontal"), - MATTE_LAYOUT_HORIZONTAL); - obs_property_list_add_int( - p, obs_module_text("TrackMatteLayoutVertical"), - MATTE_LAYOUT_VERTICAL); + obs_property_list_add_int(p, obs_module_text("TrackMatteLayoutHorizontal"), MATTE_LAYOUT_HORIZONTAL); + obs_property_list_add_int(p, obs_module_text("TrackMatteLayoutVertical"), MATTE_LAYOUT_VERTICAL); /* TODO: Requires way to synchronize or combine two media files * together */ @@ -791,55 +699,38 @@ static obs_properties_t *stinger_properties(void *data) p, obs_module_text("TrackMatteLayoutSeparateFile"), MATTE_LAYOUT_SEPARATE_FILE); #endif - obs_property_list_add_int( - p, obs_module_text("TrackMatteLayoutMask"), - MATTE_LAYOUT_MASK); + obs_property_list_add_int(p, obs_module_text("TrackMatteLayoutMask"), MATTE_LAYOUT_MASK); - obs_property_set_modified_callback(p, - track_matte_layout_modified); + obs_property_set_modified_callback(p, track_matte_layout_modified); - obs_properties_add_path(track_matte_group, "track_matte_path", - obs_module_text("TrackMatteVideoFile"), + obs_properties_add_path(track_matte_group, "track_matte_path", obs_module_text("TrackMatteVideoFile"), OBS_PATH_FILE, filter.array, NULL); - obs_properties_add_bool(track_matte_group, "invert_matte", - obs_module_text("InvertTrackMatte")); + obs_properties_add_bool(track_matte_group, "invert_matte", obs_module_text("InvertTrackMatte")); - p = obs_properties_add_group( - ppts, "track_matte_enabled", - obs_module_text("TrackMatteEnabled"), - OBS_GROUP_CHECKABLE, track_matte_group); + p = obs_properties_add_group(ppts, "track_matte_enabled", obs_module_text("TrackMatteEnabled"), + OBS_GROUP_CHECKABLE, track_matte_group); - obs_property_set_modified_callback( - p, track_matte_enabled_modified); + obs_property_set_modified_callback(p, track_matte_enabled_modified); } dstr_free(&filter); // audio output settings - obs_property_t *monitor_list = obs_properties_add_list( - ppts, "audio_monitoring", obs_module_text("AudioMonitoring"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(monitor_list, - obs_module_text("AudioMonitoring.None"), - OBS_MONITORING_TYPE_NONE); - obs_property_list_add_int( - monitor_list, obs_module_text("AudioMonitoring.MonitorOnly"), - OBS_MONITORING_TYPE_MONITOR_ONLY); - obs_property_list_add_int(monitor_list, - obs_module_text("AudioMonitoring.Both"), + obs_property_t *monitor_list = obs_properties_add_list(ppts, "audio_monitoring", + obs_module_text("AudioMonitoring"), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(monitor_list, obs_module_text("AudioMonitoring.None"), OBS_MONITORING_TYPE_NONE); + obs_property_list_add_int(monitor_list, obs_module_text("AudioMonitoring.MonitorOnly"), + OBS_MONITORING_TYPE_MONITOR_ONLY); + obs_property_list_add_int(monitor_list, obs_module_text("AudioMonitoring.Both"), OBS_MONITORING_TYPE_MONITOR_AND_OUTPUT); // audio fade settings obs_property_t *audio_fade_style = obs_properties_add_list( - ppts, "audio_fade_style", obs_module_text("AudioFadeStyle"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int( - audio_fade_style, - obs_module_text("AudioFadeStyle.FadeOutFadeIn"), - FADE_STYLE_FADE_OUT_FADE_IN); - obs_property_list_add_int(audio_fade_style, - obs_module_text("AudioFadeStyle.CrossFade"), - FADE_STYLE_CROSS_FADE); + ppts, "audio_fade_style", obs_module_text("AudioFadeStyle"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(audio_fade_style, obs_module_text("AudioFadeStyle.FadeOutFadeIn"), + FADE_STYLE_FADE_OUT_FADE_IN); + obs_property_list_add_int(audio_fade_style, obs_module_text("AudioFadeStyle.CrossFade"), FADE_STYLE_CROSS_FADE); UNUSED_PARAMETER(data); return ppts; @@ -872,24 +763,21 @@ static obs_missing_files_t *stinger_missing_files(void *data) if (strcmp(path, "") != 0) { if (!os_file_exists(path)) { - obs_missing_file_t *file = obs_missing_file_create( - path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, s->source, - (void *)"media_source"); + obs_missing_file_t *file = obs_missing_file_create(path, missing_file_callback, + OBS_MISSING_FILE_SOURCE, s->source, + (void *)"media_source"); obs_missing_files_add_file(files, file); } } - const char *track_matte_path = - obs_data_get_string(settings, "track_matte_path"); + const char *track_matte_path = obs_data_get_string(settings, "track_matte_path"); if (strcmp(track_matte_path, "") != 0) { if (!os_file_exists(track_matte_path)) { - obs_missing_file_t *file = obs_missing_file_create( - track_matte_path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, s->source, - (void *)"matte_source"); + obs_missing_file_t *file = obs_missing_file_create(track_matte_path, missing_file_callback, + OBS_MISSING_FILE_SOURCE, s->source, + (void *)"matte_source"); obs_missing_files_add_file(files, file); } @@ -899,9 +787,8 @@ static obs_missing_files_t *stinger_missing_files(void *data) return files; } -static enum gs_color_space -stinger_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space stinger_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); diff --git a/plugins/obs-transitions/transition-swipe.c b/plugins/obs-transitions/transition-swipe.c index 8a2890960..edebd80bf 100644 --- a/plugins/obs-transitions/transition-swipe.c +++ b/plugins/obs-transitions/transition-swipe.c @@ -74,8 +74,7 @@ static void swipe_update(void *data, obs_data_t *settings) swipe->dir = (struct vec2){1.0f, 0.0f}; } -static void swipe_callback(void *data, gs_texture_t *a, gs_texture_t *b, - float t, uint32_t cx, uint32_t cy) +static void swipe_callback(void *data, gs_texture_t *a, gs_texture_t *b, float t, uint32_t cx, uint32_t cy) { struct swipe_info *swipe = data; struct vec2 swipe_val = swipe->dir; @@ -119,14 +118,11 @@ static float mix_b(void *data, float t) return cubic_ease_in_out(t); } -static bool swipe_audio_render(void *data, uint64_t *ts_out, - struct obs_source_audio_mix *audio, - uint32_t mixers, size_t channels, - size_t sample_rate) +static bool swipe_audio_render(void *data, uint64_t *ts_out, struct obs_source_audio_mix *audio, uint32_t mixers, + size_t channels, size_t sample_rate) { struct swipe_info *swipe = data; - return obs_transition_audio_render(swipe->source, ts_out, audio, mixers, - channels, sample_rate, mix_a, mix_b); + return obs_transition_audio_render(swipe->source, ts_out, audio, mixers, channels, sample_rate, mix_a, mix_b); } static obs_properties_t *swipe_properties(void *data) @@ -134,17 +130,12 @@ static obs_properties_t *swipe_properties(void *data) obs_properties_t *ppts = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(ppts, S_DIRECTION, - obs_module_text("Direction"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, S_DIRECTION, obs_module_text("Direction"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, obs_module_text("Direction.Left"), - "left"); - obs_property_list_add_string(p, obs_module_text("Direction.Right"), - "right"); + obs_property_list_add_string(p, obs_module_text("Direction.Left"), "left"); + obs_property_list_add_string(p, obs_module_text("Direction.Right"), "right"); obs_property_list_add_string(p, obs_module_text("Direction.Up"), "up"); - obs_property_list_add_string(p, obs_module_text("Direction.Down"), - "down"); + obs_property_list_add_string(p, obs_module_text("Direction.Down"), "down"); obs_properties_add_bool(ppts, S_SWIPE_IN, obs_module_text("SwipeIn")); @@ -152,9 +143,8 @@ static obs_properties_t *swipe_properties(void *data) return ppts; } -static enum gs_color_space -swipe_video_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +static enum gs_color_space swipe_video_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { UNUSED_PARAMETER(count); UNUSED_PARAMETER(preferred_spaces); diff --git a/plugins/obs-vst/EditorWidget.cpp b/plugins/obs-vst/EditorWidget.cpp index 5a0bfd04f..d2dc624e5 100644 --- a/plugins/obs-vst/EditorWidget.cpp +++ b/plugins/obs-vst/EditorWidget.cpp @@ -19,9 +19,7 @@ along with this program. If not, see . #include "headers/EditorWidget.h" #include -EditorWidget::EditorWidget(QWidget *parent, VSTPlugin *plugin) - : QWidget(parent), - plugin(plugin) +EditorWidget::EditorWidget(QWidget *parent, VSTPlugin *plugin) : QWidget(parent), plugin(plugin) { setWindowFlags(this->windowFlags() |= Qt::MSWindowsFixedSizeDialogHint); } diff --git a/plugins/obs-vst/VSTPlugin.cpp b/plugins/obs-vst/VSTPlugin.cpp index 08d4dd432..a1d19b367 100644 --- a/plugins/obs-vst/VSTPlugin.cpp +++ b/plugins/obs-vst/VSTPlugin.cpp @@ -19,9 +19,8 @@ along with this program. If not, see . #include "headers/VSTPlugin.h" #include -intptr_t VSTPlugin::hostCallback_static(AEffect *effect, int32_t opcode, - int32_t index, intptr_t value, - void *ptr, float opt) +intptr_t VSTPlugin::hostCallback_static(AEffect *effect, int32_t opcode, int32_t index, intptr_t value, void *ptr, + float opt) { UNUSED_PARAMETER(opt); @@ -80,9 +79,7 @@ float VSTPlugin::GetSampleRate() return mTimeInfo.sampleRate; } -VSTPlugin::VSTPlugin(obs_source_t *sourceContext) : sourceContext{sourceContext} -{ -} +VSTPlugin::VSTPlugin(obs_source_t *sourceContext) : sourceContext{sourceContext} {} VSTPlugin::~VSTPlugin() { @@ -103,10 +100,8 @@ void VSTPlugin::createChannelBuffers(size_t count) outputs = (float **)bmalloc(sizeof(float *) * numChannels); channelrefs = (float **)bmalloc(sizeof(float *) * numChannels); for (size_t channel = 0; channel < numChannels; channel++) { - inputs[channel] = - (float *)bmalloc(sizeof(float) * blocksize); - outputs[channel] = - (float *)bmalloc(sizeof(float) * blocksize); + inputs[channel] = (float *)bmalloc(sizeof(float) * blocksize); + outputs[channel] = (float *)bmalloc(sizeof(float) * blocksize); } } } @@ -142,8 +137,7 @@ void VSTPlugin::loadEffectFromPath(const std::string &path) { if (this->pluginPath.compare(path) != 0) { unloadEffect(); - blog(LOG_INFO, "User selected new VST plugin: '%s'", - path.c_str()); + blog(LOG_INFO, "User selected new VST plugin: '%s'", path.c_str()); } if (!effect) { @@ -173,25 +167,19 @@ void VSTPlugin::loadEffectFromPath(const std::string &path) int maxchans = std::max(effect->numInputs, effect->numOutputs); // sanity check if (maxchans < 0 || maxchans > 256) { - blog(LOG_WARNING, - "VST Plug-in has invalid number of channels"); + blog(LOG_WARNING, "VST Plug-in has invalid number of channels"); return; } createChannelBuffers(maxchans); // It is better to invoke this code after checking magic number - effect->dispatcher(effect, effGetEffectName, 0, 0, effectName, - 0); - effect->dispatcher(effect, effGetVendorString, 0, 0, - vendorString, 0); + effect->dispatcher(effect, effGetEffectName, 0, 0, effectName, 0); + effect->dispatcher(effect, effGetVendorString, 0, 0, vendorString, 0); // This check logic is refer to open source project : Audacity - if ((effect->flags & effFlagsIsSynth) || - !(effect->flags & effFlagsCanReplacing)) { - blog(LOG_WARNING, - "VST Plug-in can't support replacing. '%s'", - path.c_str()); + if ((effect->flags & effFlagsIsSynth) || !(effect->flags & effFlagsCanReplacing)) { + blog(LOG_WARNING, "VST Plug-in can't support replacing. '%s'", path.c_str()); return; } @@ -201,8 +189,7 @@ void VSTPlugin::loadEffectFromPath(const std::string &path) effect->dispatcher(effect, effOpen, 0, 0, nullptr, 0.0f); // Set some default properties - size_t sampleRate = - audio_output_get_sample_rate(obs_get_audio()); + size_t sampleRate = audio_output_get_sample_rate(obs_get_audio()); // Initialize time info memset(&mTimeInfo, 0, sizeof(mTimeInfo)); @@ -211,14 +198,11 @@ void VSTPlugin::loadEffectFromPath(const std::string &path) mTimeInfo.tempo = 120.0; mTimeInfo.timeSigNumerator = 4; mTimeInfo.timeSigDenominator = 4; - mTimeInfo.flags = kVstTempoValid | kVstNanosValid | - kVstTransportPlaying; + mTimeInfo.flags = kVstTempoValid | kVstNanosValid | kVstTransportPlaying; - effect->dispatcher(effect, effSetSampleRate, 0, 0, nullptr, - sampleRate); + effect->dispatcher(effect, effSetSampleRate, 0, 0, nullptr, sampleRate); int blocksize = BLOCK_SIZE; - effect->dispatcher(effect, effSetBlockSize, 0, blocksize, - nullptr, 0.0f); + effect->dispatcher(effect, effSetBlockSize, 0, blocksize, nullptr, 0.0f); effect->dispatcher(effect, effMainsChanged, 0, 1, nullptr, 0); @@ -230,8 +214,7 @@ void VSTPlugin::loadEffectFromPath(const std::string &path) } } -static void silenceChannel(float **channelData, size_t numChannels, - long numFrames) +static void silenceChannel(float **channelData, size_t numChannels, long numFrames) { for (size_t channel = 0; channel < numChannels; ++channel) { for (long frame = 0; frame < numFrames; ++frame) { @@ -254,32 +237,24 @@ obs_audio_data *VSTPlugin::process(struct obs_audio_data *audio) uint passes = (audio->frames + BLOCK_SIZE - 1) / BLOCK_SIZE; uint extra = audio->frames % BLOCK_SIZE; for (uint pass = 0; pass < passes; pass++) { - uint frames = pass == passes - 1 && extra ? extra - : BLOCK_SIZE; + uint frames = pass == passes - 1 && extra ? extra : BLOCK_SIZE; silenceChannel(outputs, numChannels, BLOCK_SIZE); for (size_t d = 0; d < numChannels; d++) { - if (d < MAX_AV_PLANES && - audio->data[d] != nullptr) { - channelrefs[d] = - ((float *)audio->data[d]) + - (pass * BLOCK_SIZE); + if (d < MAX_AV_PLANES && audio->data[d] != nullptr) { + channelrefs[d] = ((float *)audio->data[d]) + (pass * BLOCK_SIZE); } else { channelrefs[d] = inputs[d]; } }; - effect->processReplacing(effect, channelrefs, outputs, - frames); + effect->processReplacing(effect, channelrefs, outputs, frames); // only copy back the channels the plugin may have generated - for (size_t c = 0; c < (size_t)effect->numOutputs && - c < MAX_AV_PLANES; - c++) { + for (size_t c = 0; c < (size_t)effect->numOutputs && c < MAX_AV_PLANES; c++) { if (audio->data[c]) { for (size_t i = 0; i < frames; i++) { - channelrefs[c][i] = - outputs[c][i]; + channelrefs[c][i] = outputs[c][i]; } } } @@ -300,10 +275,8 @@ void VSTPlugin::unloadEffect() effectReady = false; if (effect) { - effect->dispatcher(effect, effMainsChanged, 0, 0, - nullptr, 0); - effect->dispatcher(effect, effClose, 0, 0, nullptr, - 0.0f); + effect->dispatcher(effect, effMainsChanged, 0, 0, nullptr, 0); + effect->dispatcher(effect, effClose, 0, 0, nullptr, 0.0f); } effect = nullptr; @@ -338,9 +311,7 @@ void VSTPlugin::openEditor() if (effect && !editorWidget) { // This check logic is refer to open source project : Audacity if (!(effect->flags & effFlagsHasEditor)) { - blog(LOG_WARNING, - "VST Plug-in: Can't support edit feature. '%s'", - pluginPath.c_str()); + blog(LOG_WARNING, "VST Plug-in: Can't support edit feature. '%s'", pluginPath.c_str()); return; } @@ -353,13 +324,10 @@ void VSTPlugin::openEditor() } if (filterName.empty()) { - editorWidget->setWindowTitle(QString("%1 - %2").arg( - sourceName.c_str(), effectName)); + editorWidget->setWindowTitle(QString("%1 - %2").arg(sourceName.c_str(), effectName)); } else { editorWidget->setWindowTitle( - QString("%1: %2 - %3") - .arg(sourceName.c_str(), - filterName.c_str(), effectName)); + QString("%1: %2 - %3").arg(sourceName.c_str(), filterName.c_str(), effectName)); } editorWidget->show(); } @@ -385,8 +353,7 @@ std::string VSTPlugin::getChunk() if (effect->flags & effFlagsProgramChunks) { void *buf = nullptr; - intptr_t chunkSize = effect->dispatcher(effect, effGetChunk, 1, - 0, &buf, 0.0); + intptr_t chunkSize = effect->dispatcher(effect, effGetChunk, 1, 0, &buf, 0.0); QByteArray data = QByteArray((char *)buf, chunkSize); return QString(data.toBase64()).toStdString(); @@ -398,8 +365,7 @@ std::string VSTPlugin::getChunk() } const char *bytes = reinterpret_cast(¶ms[0]); - QByteArray data = - QByteArray(bytes, (int)(sizeof(float) * params.size())); + QByteArray data = QByteArray(bytes, (int)(sizeof(float) * params.size())); std::string encoded = QString(data.toBase64()).toStdString(); return encoded; } @@ -412,21 +378,17 @@ void VSTPlugin::setChunk(const std::string &data) } if (effect->flags & effFlagsProgramChunks) { - QByteArray base64Data = - QByteArray(data.c_str(), (int)data.length()); + QByteArray base64Data = QByteArray(data.c_str(), (int)data.length()); QByteArray chunkData = QByteArray::fromBase64(base64Data); void *buf = nullptr; buf = chunkData.data(); - effect->dispatcher(effect, effSetChunk, 1, chunkData.length(), - buf, 0); + effect->dispatcher(effect, effSetChunk, 1, chunkData.length(), buf, 0); } else { - QByteArray base64Data = - QByteArray(data.c_str(), (int)data.length()); + QByteArray base64Data = QByteArray(data.c_str(), (int)data.length()); QByteArray paramData = QByteArray::fromBase64(base64Data); const char *p_chars = paramData.data(); - const float *p_floats = - reinterpret_cast(p_chars); + const float *p_floats = reinterpret_cast(p_chars); const size_t size = paramData.length() / sizeof(float); @@ -445,11 +407,9 @@ void VSTPlugin::setChunk(const std::string &data) void VSTPlugin::setProgram(const int programNumber) { if (programNumber < effect->numPrograms) { - effect->dispatcher(effect, effSetProgram, 0, programNumber, - NULL, 0.0f); + effect->dispatcher(effect, effSetProgram, 0, programNumber, NULL, 0.0f); } else { - blog(LOG_ERROR, - "Failed to load program, number was outside possible program range."); + blog(LOG_ERROR, "Failed to load program, number was outside possible program range."); } } diff --git a/plugins/obs-vst/headers/VSTPlugin.h b/plugins/obs-vst/headers/VSTPlugin.h index 26bb64dda..350885cad 100644 --- a/plugins/obs-vst/headers/VSTPlugin.h +++ b/plugins/obs-vst/headers/VSTPlugin.h @@ -79,9 +79,8 @@ class VSTPlugin : public QObject { void unloadLibrary(); - static intptr_t hostCallback_static(AEffect *effect, int32_t opcode, - int32_t index, intptr_t value, - void *ptr, float opt); + static intptr_t hostCallback_static(AEffect *effect, int32_t opcode, int32_t index, intptr_t value, void *ptr, + float opt); VstTimeInfo *GetTimeInfo(); float GetSampleRate(); diff --git a/plugins/obs-vst/linux/EditorWidget-linux.cpp b/plugins/obs-vst/linux/EditorWidget-linux.cpp index 08a6d8a3e..04cadae1d 100644 --- a/plugins/obs-vst/linux/EditorWidget-linux.cpp +++ b/plugins/obs-vst/linux/EditorWidget-linux.cpp @@ -26,8 +26,7 @@ void EditorWidget::buildEffectContainer(AEffect *effect) effect->dispatcher(effect, effEditGetRect, 0, 0, &vstRect, 0); if (vstRect) { - setFixedSize(vstRect->right - vstRect->left, - vstRect->bottom - vstRect->top); + setFixedSize(vstRect->right - vstRect->left, vstRect->bottom - vstRect->top); } } diff --git a/plugins/obs-vst/linux/VSTPlugin-linux.cpp b/plugins/obs-vst/linux/VSTPlugin-linux.cpp index 2d52229da..f825a4732 100644 --- a/plugins/obs-vst/linux/VSTPlugin-linux.cpp +++ b/plugins/obs-vst/linux/VSTPlugin-linux.cpp @@ -37,8 +37,7 @@ AEffect *VSTPlugin::loadEffect() mainEntryPoint = (vstPluginMain)os_dlsym(soHandle, "VSTPluginMain"); if (mainEntryPoint == nullptr) { - mainEntryPoint = - (vstPluginMain)os_dlsym(soHandle, "VstPluginMain()"); + mainEntryPoint = (vstPluginMain)os_dlsym(soHandle, "VstPluginMain()"); } if (mainEntryPoint == nullptr) { diff --git a/plugins/obs-vst/obs-vst.cpp b/plugins/obs-vst/obs-vst.cpp index f2c6afe67..1a4eebe0e 100644 --- a/plugins/obs-vst/obs-vst.cpp +++ b/plugins/obs-vst/obs-vst.cpp @@ -35,8 +35,7 @@ MODULE_EXPORT const char *obs_module_description(void) return "VST 2.x Plug-in filter"; } -static bool open_editor_button_clicked(obs_properties_t *props, - obs_property_t *property, void *data) +static bool open_editor_button_clicked(obs_properties_t *props, obs_property_t *property, void *data) { VSTPlugin *vstPlugin = (VSTPlugin *)data; @@ -44,10 +43,8 @@ static bool open_editor_button_clicked(obs_properties_t *props, QMetaObject::invokeMethod(vstPlugin, "openEditor"); - obs_property_set_visible( - obs_properties_get(props, OPEN_VST_SETTINGS), false); - obs_property_set_visible( - obs_properties_get(props, CLOSE_VST_SETTINGS), true); + obs_property_set_visible(obs_properties_get(props, OPEN_VST_SETTINGS), false); + obs_property_set_visible(obs_properties_get(props, CLOSE_VST_SETTINGS), true); } UNUSED_PARAMETER(props); @@ -57,8 +54,7 @@ static bool open_editor_button_clicked(obs_properties_t *props, return true; } -static bool close_editor_button_clicked(obs_properties_t *props, - obs_property_t *property, void *data) +static bool close_editor_button_clicked(obs_properties_t *props, obs_property_t *property, void *data) { VSTPlugin *vstPlugin = (VSTPlugin *)data; @@ -66,10 +62,8 @@ static bool close_editor_button_clicked(obs_properties_t *props, QMetaObject::invokeMethod(vstPlugin, "closeEditor"); - obs_property_set_visible( - obs_properties_get(props, OPEN_VST_SETTINGS), true); - obs_property_set_visible( - obs_properties_get(props, CLOSE_VST_SETTINGS), false); + obs_property_set_visible(obs_properties_get(props, OPEN_VST_SETTINGS), true); + obs_property_set_visible(obs_properties_get(props, CLOSE_VST_SETTINGS), false); } UNUSED_PARAMETER(property); @@ -106,20 +100,16 @@ static void vst_update(void *data, obs_data_t *settings) { VSTPlugin *vstPlugin = (VSTPlugin *)data; - vstPlugin->openInterfaceWhenActive = - obs_data_get_bool(settings, OPEN_WHEN_ACTIVE_VST_SETTINGS); + vstPlugin->openInterfaceWhenActive = obs_data_get_bool(settings, OPEN_WHEN_ACTIVE_VST_SETTINGS); const char *path = obs_data_get_string(settings, "plugin_path"); #ifdef __linux__ // Migrate freedesktop.org Flatpak runtime 21.08 VST paths to 22.08. - if (QFile::exists("/.flatpak-info") && - QString(path).startsWith("/app/extensions/Plugins/lxvst")) { + if (QFile::exists("/.flatpak-info") && QString(path).startsWith("/app/extensions/Plugins/lxvst")) { QString newPath(path); - newPath.replace("/app/extensions/Plugins/lxvst", - "/app/extensions/Plugins/vst"); - obs_data_set_string(settings, "plugin_path", - newPath.toStdString().c_str()); + newPath.replace("/app/extensions/Plugins/lxvst", "/app/extensions/Plugins/vst"); + obs_data_set_string(settings, "plugin_path", newPath.toStdString().c_str()); path = obs_data_get_string(settings, "plugin_path"); } #endif @@ -134,10 +124,8 @@ static void vst_update(void *data, obs_data_t *settings) const char *chunkHash = obs_data_get_string(settings, "chunk_hash"); const char *chunkData = obs_data_get_string(settings, "chunk_data"); - bool chunkHashesMatch = chunkHash && *chunkHash && - hash.compare(chunkHash) == 0; - if (chunkData && *chunkData && - (chunkHashesMatch || !chunkHash || !*chunkHash)) { + bool chunkHashesMatch = chunkHash && *chunkHash && hash.compare(chunkHash) == 0; + if (chunkData && *chunkData && (chunkHashesMatch || !chunkHash || !*chunkHash)) { vstPlugin->setChunk(std::string(chunkData)); } } @@ -153,15 +141,11 @@ static void *vst_create(obs_data_t *settings, obs_source_t *filter) static void vst_save(void *data, obs_data_t *settings) { VSTPlugin *vstPlugin = (VSTPlugin *)data; - obs_data_set_string(settings, "chunk_data", - vstPlugin->getChunk().c_str()); - obs_data_set_string( - settings, "chunk_hash", - getFileMD5(vstPlugin->getEffectPath().c_str()).c_str()); + obs_data_set_string(settings, "chunk_data", vstPlugin->getChunk().c_str()); + obs_data_set_string(settings, "chunk_hash", getFileMD5(vstPlugin->getEffectPath().c_str()).c_str()); } -static struct obs_audio_data *vst_filter_audio(void *data, - struct obs_audio_data *audio) +static struct obs_audio_data *vst_filter_audio(void *data, struct obs_audio_data *audio) { VSTPlugin *vstPlugin = (VSTPlugin *)data; vstPlugin->process(audio); @@ -192,29 +176,19 @@ static void fill_out_plugins(obs_property_t *list) if (!isWow64) { #endif - dir_list << qEnvironmentVariable("ProgramFiles") + - "/Steinberg/VstPlugins/" - << qEnvironmentVariable("CommonProgramFiles") + - "/Steinberg/Shared Components/" + dir_list << qEnvironmentVariable("ProgramFiles") + "/Steinberg/VstPlugins/" + << qEnvironmentVariable("CommonProgramFiles") + "/Steinberg/Shared Components/" << qEnvironmentVariable("CommonProgramFiles") + "/VST2" - << qEnvironmentVariable("CommonProgramFiles") + - "/Steinberg/VST2" - << qEnvironmentVariable("CommonProgramFiles") + - "/VSTPlugins/" - << qEnvironmentVariable("ProgramFiles") + - "/VSTPlugins/"; + << qEnvironmentVariable("CommonProgramFiles") + "/Steinberg/VST2" + << qEnvironmentVariable("CommonProgramFiles") + "/VSTPlugins/" + << qEnvironmentVariable("ProgramFiles") + "/VSTPlugins/"; #ifndef _WIN64 } else { - dir_list << qEnvironmentVariable("ProgramFiles(x86)") + - "/Steinberg/VstPlugins/" - << qEnvironmentVariable("CommonProgramFiles(x86)") + - "/Steinberg/Shared Components/" - << qEnvironmentVariable("CommonProgramFiles(x86)") + - "/VST2" - << qEnvironmentVariable("CommonProgramFiles(x86)") + - "/VSTPlugins/" - << qEnvironmentVariable("ProgramFiles(x86)") + - "/VSTPlugins/"; + dir_list << qEnvironmentVariable("ProgramFiles(x86)") + "/Steinberg/VstPlugins/" + << qEnvironmentVariable("CommonProgramFiles(x86)") + "/Steinberg/Shared Components/" + << qEnvironmentVariable("CommonProgramFiles(x86)") + "/VST2" + << qEnvironmentVariable("CommonProgramFiles(x86)") + "/VSTPlugins/" + << qEnvironmentVariable("ProgramFiles(x86)") + "/VSTPlugins/"; } #endif #elif __linux__ @@ -263,9 +237,7 @@ static void fill_out_plugins(obs_property_t *list) for (int a = 0; a < dir_list.size(); ++a) { QDir search_dir(dir_list[a]); search_dir.setNameFilters(filters); - QDirIterator it(search_dir, - QDirIterator::Subdirectories | - QDirIterator::FollowSymlinks); + QDirIterator it(search_dir, QDirIterator::Subdirectories | QDirIterator::FollowSymlinks); while (it.hasNext()) { QString path = it.next(); QString name = it.fileName(); @@ -285,27 +257,18 @@ static void fill_out_plugins(obs_property_t *list) } // Now sort list alphabetically (still case-sensitive though). - std::stable_sort(vst_list.begin(), vst_list.end(), - std::less()); + std::stable_sort(vst_list.begin(), vst_list.end(), std::less()); // Now add said list to the plug-in list of OBS - obs_property_list_add_string(list, "{Please select a plug-in}", - nullptr); + obs_property_list_add_string(list, "{Please select a plug-in}", nullptr); for (int b = 0; b < vst_list.size(); ++b) { QString vst_sorted = vst_list[b]; - obs_property_list_add_string( - list, - vst_sorted.left(vst_sorted.indexOf('=')) - .toStdString() - .c_str(), - vst_sorted.mid(vst_sorted.indexOf('=') + 1) - .toStdString() - .c_str()); + obs_property_list_add_string(list, vst_sorted.left(vst_sorted.indexOf('=')).toStdString().c_str(), + vst_sorted.mid(vst_sorted.indexOf('=') + 1).toStdString().c_str()); } } -static bool vst_changed(void *data, obs_properties_t *props, - obs_property_t *list, obs_data_t *settings) +static bool vst_changed(void *data, obs_properties_t *props, obs_property_t *list, obs_data_t *settings) { UNUSED_PARAMETER(settings); UNUSED_PARAMETER(list); @@ -325,10 +288,8 @@ static bool vst_changed(void *data, obs_properties_t *props, } } - obs_property_set_visible(obs_properties_get(props, OPEN_VST_SETTINGS), - open_settings_vis); - obs_property_set_visible(obs_properties_get(props, CLOSE_VST_SETTINGS), - close_settings_vis); + obs_property_set_visible(obs_properties_get(props, OPEN_VST_SETTINGS), open_settings_vis); + obs_property_set_visible(obs_properties_get(props, CLOSE_VST_SETTINGS), close_settings_vis); return true; } @@ -336,17 +297,13 @@ static bool vst_changed(void *data, obs_properties_t *props, static obs_properties_t *vst_properties(void *data) { obs_properties_t *props = obs_properties_create(); - obs_property_t *list = obs_properties_add_list(props, "plugin_path", - PLUG_IN_NAME, - OBS_COMBO_TYPE_LIST, + obs_property_t *list = obs_properties_add_list(props, "plugin_path", PLUG_IN_NAME, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); fill_out_plugins(list); - obs_properties_add_button(props, OPEN_VST_SETTINGS, OPEN_VST_TEXT, - open_editor_button_clicked); - obs_properties_add_button(props, CLOSE_VST_SETTINGS, CLOSE_VST_TEXT, - close_editor_button_clicked); + obs_properties_add_button(props, OPEN_VST_SETTINGS, OPEN_VST_TEXT, open_editor_button_clicked); + obs_properties_add_button(props, CLOSE_VST_SETTINGS, CLOSE_VST_TEXT, close_editor_button_clicked); bool open_settings_vis = true; bool close_settings_vis = false; @@ -363,13 +320,10 @@ static obs_properties_t *vst_properties(void *data) } } - obs_property_set_visible(obs_properties_get(props, OPEN_VST_SETTINGS), - open_settings_vis); - obs_property_set_visible(obs_properties_get(props, CLOSE_VST_SETTINGS), - close_settings_vis); + obs_property_set_visible(obs_properties_get(props, OPEN_VST_SETTINGS), open_settings_vis); + obs_property_set_visible(obs_properties_get(props, CLOSE_VST_SETTINGS), close_settings_vis); - obs_properties_add_bool(props, OPEN_WHEN_ACTIVE_VST_SETTINGS, - OPEN_WHEN_ACTIVE_VST_TEXT); + obs_properties_add_bool(props, OPEN_WHEN_ACTIVE_VST_SETTINGS, OPEN_WHEN_ACTIVE_VST_TEXT); obs_property_set_modified_callback2(list, vst_changed, data); diff --git a/plugins/obs-vst/win/EditorWidget-win.cpp b/plugins/obs-vst/win/EditorWidget-win.cpp index a645de585..f5b231bcd 100644 --- a/plugins/obs-vst/win/EditorWidget-win.cpp +++ b/plugins/obs-vst/win/EditorWidget-win.cpp @@ -28,15 +28,14 @@ void EditorWidget::buildEffectContainer(AEffect *effect) RegisterClassExW(&wcex); const auto style = WS_CAPTION | WS_THICKFRAME | WS_OVERLAPPEDWINDOW; - windowHandle = CreateWindowW(wcex.lpszClassName, TEXT(""), style, 0, 0, - 0, 0, nullptr, nullptr, nullptr, nullptr); + windowHandle = + CreateWindowW(wcex.lpszClassName, TEXT(""), style, 0, 0, 0, 0, nullptr, nullptr, nullptr, nullptr); // set pointer to vst effect for window long LONG_PTR wndPtr = (LONG_PTR)effect; SetWindowLongPtr(windowHandle, -21 /*GWLP_USERDATA*/, wndPtr); - QWidget *widget = QWidget::createWindowContainer( - QWindow::fromWinId((WId)windowHandle), nullptr); + QWidget *widget = QWidget::createWindowContainer(QWindow::fromWinId((WId)windowHandle), nullptr); widget->move(0, 0); QGridLayout *layout = new QGridLayout(); layout->setContentsMargins(0, 0, 0, 0); @@ -70,8 +69,7 @@ void EditorWidget::handleResizeRequest(int, int) // so we must resize window manually // get pointer to vst effect from window long - LONG_PTR wndPtr = (LONG_PTR)GetWindowLongPtrW(windowHandle, - -21 /*GWLP_USERDATA*/); + LONG_PTR wndPtr = (LONG_PTR)GetWindowLongPtrW(windowHandle, -21 /*GWLP_USERDATA*/); AEffect *effect = (AEffect *)(wndPtr); VstRect *rec = nullptr; diff --git a/plugins/obs-vst/win/VSTPlugin-win.cpp b/plugins/obs-vst/win/VSTPlugin-win.cpp index 91c2587e0..818a10aab 100644 --- a/plugins/obs-vst/win/VSTPlugin-win.cpp +++ b/plugins/obs-vst/win/VSTPlugin-win.cpp @@ -46,17 +46,14 @@ AEffect *VSTPlugin::loadEffect() return nullptr; } - vstPluginMain mainEntryPoint = - (vstPluginMain)GetProcAddress(dllHandle, "VSTPluginMain"); + vstPluginMain mainEntryPoint = (vstPluginMain)GetProcAddress(dllHandle, "VSTPluginMain"); if (mainEntryPoint == nullptr) { - mainEntryPoint = (vstPluginMain)GetProcAddress( - dllHandle, "VstPluginMain()"); + mainEntryPoint = (vstPluginMain)GetProcAddress(dllHandle, "VstPluginMain()"); } if (mainEntryPoint == nullptr) { - mainEntryPoint = - (vstPluginMain)GetProcAddress(dllHandle, "main"); + mainEntryPoint = (vstPluginMain)GetProcAddress(dllHandle, "main"); } if (mainEntryPoint == nullptr) { @@ -73,8 +70,7 @@ AEffect *VSTPlugin::loadEffect() } if (plugin == nullptr) { - blog(LOG_WARNING, "Couldn't create instance for '%s'", - pluginPath.c_str()); + blog(LOG_WARNING, "Couldn't create instance for '%s'", pluginPath.c_str()); return nullptr; } diff --git a/plugins/obs-webrtc/whip-output.cpp b/plugins/obs-webrtc/whip-output.cpp index 8a92a3bd1..739161af4 100644 --- a/plugins/obs-webrtc/whip-output.cpp +++ b/plugins/obs-webrtc/whip-output.cpp @@ -88,23 +88,19 @@ void WHIPOutput::Data(struct encoder_packet *packet) if (audio_track && packet->type == OBS_ENCODER_AUDIO) { int64_t duration = packet->dts_usec - last_audio_timestamp; - Send(packet->data, packet->size, duration, audio_track, - audio_sr_reporter); + Send(packet->data, packet->size, duration, audio_track, audio_sr_reporter); last_audio_timestamp = packet->dts_usec; } else if (video_track && packet->type == OBS_ENCODER_VIDEO) { int64_t duration = packet->dts_usec - last_video_timestamp; - Send(packet->data, packet->size, duration, video_track, - video_sr_reporter); + Send(packet->data, packet->size, duration, video_track, video_sr_reporter); last_video_timestamp = packet->dts_usec; } } -void WHIPOutput::ConfigureAudioTrack(std::string media_stream_id, - std::string cname) +void WHIPOutput::ConfigureAudioTrack(std::string media_stream_id, std::string cname) { if (!obs_output_get_audio_encoder(output, 0)) { - do_log(LOG_DEBUG, - "Not configuring audio track: Audio encoder not assigned"); + do_log(LOG_DEBUG, "Not configuring audio track: Audio encoder not assigned"); return; } @@ -112,16 +108,13 @@ void WHIPOutput::ConfigureAudioTrack(std::string media_stream_id, uint32_t ssrc = base_ssrc; - rtc::Description::Audio audio_description( - audio_mid, rtc::Description::Direction::SendOnly); + rtc::Description::Audio audio_description(audio_mid, rtc::Description::Direction::SendOnly); audio_description.addOpusCodec(audio_payload_type); - audio_description.addSSRC(ssrc, cname, media_stream_id, - media_stream_track_id); + audio_description.addSSRC(ssrc, cname, media_stream_id, media_stream_track_id); audio_track = peer_connection->addTrack(audio_description); - auto rtp_config = std::make_shared( - ssrc, cname, audio_payload_type, - rtc::OpusRtpPacketizer::DefaultClockRate); + auto rtp_config = std::make_shared(ssrc, cname, audio_payload_type, + rtc::OpusRtpPacketizer::DefaultClockRate); auto packetizer = std::make_shared(rtp_config); audio_sr_reporter = std::make_shared(rtp_config); auto nack_responder = std::make_shared(); @@ -131,12 +124,10 @@ void WHIPOutput::ConfigureAudioTrack(std::string media_stream_id, audio_track->setMediaHandler(packetizer); } -void WHIPOutput::ConfigureVideoTrack(std::string media_stream_id, - std::string cname) +void WHIPOutput::ConfigureVideoTrack(std::string media_stream_id, std::string cname) { if (!obs_output_get_video_encoder(output)) { - do_log(LOG_DEBUG, - "Not configuring video track: Video encoder not assigned"); + do_log(LOG_DEBUG, "Not configuring video track: Video encoder not assigned"); return; } @@ -146,14 +137,11 @@ void WHIPOutput::ConfigureVideoTrack(std::string media_stream_id, // More predictable SSRC values between audio and video uint32_t ssrc = base_ssrc + 1; - rtc::Description::Video video_description( - video_mid, rtc::Description::Direction::SendOnly); - video_description.addSSRC(ssrc, cname, media_stream_id, - media_stream_track_id); + rtc::Description::Video video_description(video_mid, rtc::Description::Direction::SendOnly); + video_description.addSSRC(ssrc, cname, media_stream_id, media_stream_track_id); - auto rtp_config = std::make_shared( - ssrc, cname, video_payload_type, - rtc::H264RtpPacketizer::defaultClockRate); + auto rtp_config = std::make_shared(ssrc, cname, video_payload_type, + rtc::H264RtpPacketizer::defaultClockRate); const obs_encoder_t *encoder = obs_output_get_video_encoder2(output, 0); if (!encoder) @@ -162,21 +150,18 @@ void WHIPOutput::ConfigureVideoTrack(std::string media_stream_id, const char *codec = obs_encoder_get_codec(encoder); if (strcmp("h264", codec) == 0) { video_description.addH264Codec(video_payload_type); - packetizer = std::make_shared( - rtc::H264RtpPacketizer::Separator::StartSequence, - rtp_config, MAX_VIDEO_FRAGMENT_SIZE); + packetizer = std::make_shared(rtc::H264RtpPacketizer::Separator::StartSequence, + rtp_config, MAX_VIDEO_FRAGMENT_SIZE); #ifdef ENABLE_HEVC } else if (strcmp("hevc", codec) == 0) { video_description.addH265Codec(video_payload_type); - packetizer = std::make_shared( - rtc::H265RtpPacketizer::Separator::StartSequence, - rtp_config, MAX_VIDEO_FRAGMENT_SIZE); + packetizer = std::make_shared(rtc::H265RtpPacketizer::Separator::StartSequence, + rtp_config, MAX_VIDEO_FRAGMENT_SIZE); #endif } else if (strcmp("av1", codec) == 0) { video_description.addAV1Codec(video_payload_type); - packetizer = std::make_shared( - rtc::AV1RtpPacketizer::Packetization::TemporalUnit, - rtp_config, MAX_VIDEO_FRAGMENT_SIZE); + packetizer = std::make_shared(rtc::AV1RtpPacketizer::Packetization::TemporalUnit, + rtp_config, MAX_VIDEO_FRAGMENT_SIZE); } else { do_log(LOG_ERROR, "Video codec not supported: %s", codec); return; @@ -184,8 +169,7 @@ void WHIPOutput::ConfigureVideoTrack(std::string media_stream_id, video_sr_reporter = std::make_shared(rtp_config); packetizer->addToChain(video_sr_reporter); - packetizer->addToChain(std::make_shared( - video_nack_buffer_size)); + packetizer->addToChain(std::make_shared(video_nack_buffer_size)); video_track = peer_connection->addTrack(video_description); video_track->setMediaHandler(packetizer); @@ -204,15 +188,13 @@ bool WHIPOutput::Init() return false; } - endpoint_url = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); + endpoint_url = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_SERVER_URL); if (endpoint_url.empty()) { obs_output_signal_stop(output, OBS_OUTPUT_BAD_PATH); return false; } - bearer_token = obs_service_get_connect_info( - service, OBS_SERVICE_CONNECT_INFO_BEARER_TOKEN); + bearer_token = obs_service_get_connect_info(service, OBS_SERVICE_CONNECT_INFO_BEARER_TOKEN); return true; } @@ -238,22 +220,16 @@ bool WHIPOutput::Setup() do_log(LOG_INFO, "PeerConnection state is now: New"); break; case rtc::PeerConnection::State::Connecting: - do_log(LOG_INFO, - "PeerConnection state is now: Connecting"); + do_log(LOG_INFO, "PeerConnection state is now: Connecting"); start_time_ns = os_gettime_ns(); break; case rtc::PeerConnection::State::Connected: - do_log(LOG_INFO, - "PeerConnection state is now: Connected"); - connect_time_ms = - (int)((os_gettime_ns() - start_time_ns) / - 1000000.0); - do_log(LOG_INFO, "Connect time: %dms", - connect_time_ms.load()); + do_log(LOG_INFO, "PeerConnection state is now: Connected"); + connect_time_ms = (int)((os_gettime_ns() - start_time_ns) / 1000000.0); + do_log(LOG_INFO, "Connect time: %dms", connect_time_ms.load()); break; case rtc::PeerConnection::State::Disconnected: - do_log(LOG_INFO, - "PeerConnection state is now: Disconnected"); + do_log(LOG_INFO, "PeerConnection state is now: Disconnected"); Stop(false); obs_output_signal_stop(output, OBS_OUTPUT_DISCONNECTED); break; @@ -273,11 +249,9 @@ bool WHIPOutput::Setup() cname.reserve(signaling_media_id_length); for (int i = 0; i < signaling_media_id_length; ++i) { - media_stream_id += signaling_media_id_valid_char - [rand() % (sizeof(signaling_media_id_valid_char) - 1)]; + media_stream_id += signaling_media_id_valid_char[rand() % (sizeof(signaling_media_id_valid_char) - 1)]; - cname += signaling_media_id_valid_char - [rand() % (sizeof(signaling_media_id_valid_char) - 1)]; + cname += signaling_media_id_valid_char[rand() % (sizeof(signaling_media_id_valid_char) - 1)]; } ConfigureAudioTrack(media_stream_id, cname); @@ -292,8 +266,7 @@ bool WHIPOutput::Setup() // ; username="user"; credential="myPassword"; // // https://www.ietf.org/archive/id/draft-ietf-wish-whip-13.html#section-4.4 -void WHIPOutput::ParseLinkHeader(std::string val, - std::vector &iceServers) +void WHIPOutput::ParseLinkHeader(std::string val, std::vector &iceServers) { std::string url, username, password; @@ -324,8 +297,7 @@ void WHIPOutput::ParseLinkHeader(std::string val, token = val.substr(0, pos); } - if ((token.find(" http_headers; - auto offer_sdp = - std::string(peer_connection->localDescription().value()); + auto offer_sdp = std::string(peer_connection->localDescription().value()); #ifdef DEBUG_SDP do_log(LOG_DEBUG, "Offer SDP:\n%s", offer_sdp.c_str()); @@ -398,9 +365,7 @@ bool WHIPOutput::Connect() CURLcode res = curl_easy_perform(c); if (res != CURLE_OK) { - do_log(LOG_ERROR, "Connect failed: %s", - error_buffer[0] ? error_buffer - : curl_easy_strerror(res)); + do_log(LOG_ERROR, "Connect failed: %s", error_buffer[0] ? error_buffer : curl_easy_strerror(res)); cleanup(); obs_output_signal_stop(output, OBS_OUTPUT_CONNECT_FAILED); return false; @@ -409,17 +374,14 @@ bool WHIPOutput::Connect() long response_code; curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &response_code); if (response_code != 201) { - do_log(LOG_ERROR, - "Connect failed: HTTP endpoint returned response code %ld", - response_code); + do_log(LOG_ERROR, "Connect failed: HTTP endpoint returned response code %ld", response_code); cleanup(); obs_output_signal_stop(output, OBS_OUTPUT_INVALID_STREAM); return false; } if (read_buffer.empty()) { - do_log(LOG_ERROR, - "Connect failed: No data returned from HTTP endpoint request"); + do_log(LOG_ERROR, "Connect failed: No data returned from HTTP endpoint request"); cleanup(); obs_output_signal_stop(output, OBS_OUTPUT_CONNECT_FAILED); return false; @@ -440,8 +402,7 @@ bool WHIPOutput::Connect() } if (location_header_count < static_cast(redirect_count) + 1) { - do_log(LOG_ERROR, - "WHIP server did not provide a resource URL via the Location header"); + do_log(LOG_ERROR, "WHIP server did not provide a resource URL via the Location header"); cleanup(); obs_output_signal_stop(output, OBS_OUTPUT_CONNECT_FAILED); return false; @@ -457,8 +418,7 @@ bool WHIPOutput::Connect() continue; // Parse multiple links separated by ',' - for (auto end = value.find(","); end != std::string::npos; - end = value.find(",")) { + for (auto end = value.find(","); end != std::string::npos; end = value.find(",")) { this->ParseLinkHeader(value.substr(0, end), iceServers); value = value.substr(end + 1); } @@ -473,26 +433,21 @@ bool WHIPOutput::Connect() if (effective_url == nullptr) { do_log(LOG_ERROR, "Failed to build Resource URL"); cleanup(); - obs_output_signal_stop(output, - OBS_OUTPUT_CONNECT_FAILED); + obs_output_signal_stop(output, OBS_OUTPUT_CONNECT_FAILED); return false; } curl_url_set(url_builder, CURLUPART_URL, effective_url, 0); - curl_url_set(url_builder, CURLUPART_PATH, - last_location_header.c_str(), 0); + curl_url_set(url_builder, CURLUPART_PATH, last_location_header.c_str(), 0); curl_url_set(url_builder, CURLUPART_QUERY, "", 0); } else { - curl_url_set(url_builder, CURLUPART_URL, - last_location_header.c_str(), 0); + curl_url_set(url_builder, CURLUPART_URL, last_location_header.c_str(), 0); } char *url = nullptr; - CURLUcode rc = curl_url_get(url_builder, CURLUPART_URL, &url, - CURLU_NO_DEFAULT_PORT); + CURLUcode rc = curl_url_get(url_builder, CURLUPART_URL, &url, CURLU_NO_DEFAULT_PORT); if (rc) { - do_log(LOG_ERROR, - "WHIP server provided a invalid resource URL via the Location header"); + do_log(LOG_ERROR, "WHIP server provided a invalid resource URL via the Location header"); cleanup(); obs_output_signal_stop(output, OBS_OUTPUT_CONNECT_FAILED); return false; @@ -514,24 +469,20 @@ bool WHIPOutput::Connect() try { peer_connection->setRemoteDescription(answer); } catch (const std::invalid_argument &err) { - do_log(LOG_ERROR, "WHIP server responded with invalid SDP: %s", - err.what()); + do_log(LOG_ERROR, "WHIP server responded with invalid SDP: %s", err.what()); cleanup(); struct dstr error_message; - dstr_init_copy(&error_message, - obs_module_text("Error.InvalidSDP")); + dstr_init_copy(&error_message, obs_module_text("Error.InvalidSDP")); dstr_replace(&error_message, "%1", err.what()); obs_output_set_last_error(output, error_message.array); dstr_free(&error_message); obs_output_signal_stop(output, OBS_OUTPUT_CONNECT_FAILED); return false; } catch (const std::exception &err) { - do_log(LOG_ERROR, "Failed to set remote description: %s", - err.what()); + do_log(LOG_ERROR, "Failed to set remote description: %s", err.what()); cleanup(); struct dstr error_message; - dstr_init_copy(&error_message, - obs_module_text("Error.NoRemoteDescription")); + dstr_init_copy(&error_message, obs_module_text("Error.NoRemoteDescription")); dstr_replace(&error_message, "%1", err.what()); obs_output_set_last_error(output, error_message.array); dstr_free(&error_message); @@ -570,17 +521,14 @@ void WHIPOutput::StartThread() void WHIPOutput::SendDelete() { if (resource_url.empty()) { - do_log(LOG_DEBUG, - "No resource URL available, not sending DELETE"); + do_log(LOG_DEBUG, "No resource URL available, not sending DELETE"); return; } struct curl_slist *headers = NULL; if (!bearer_token.empty()) { - auto bearer_token_header = - std::string("Authorization: Bearer ") + bearer_token; - headers = - curl_slist_append(headers, bearer_token_header.c_str()); + auto bearer_token_header = std::string("Authorization: Bearer ") + bearer_token; + headers = curl_slist_append(headers, bearer_token_header.c_str()); } // Add user-agent to our requests @@ -602,10 +550,8 @@ void WHIPOutput::SendDelete() CURLcode res = curl_easy_perform(c); if (res != CURLE_OK) { - do_log(LOG_WARNING, - "DELETE request for resource URL failed: %s", - error_buffer[0] ? error_buffer - : curl_easy_strerror(res)); + do_log(LOG_WARNING, "DELETE request for resource URL failed: %s", + error_buffer[0] ? error_buffer : curl_easy_strerror(res)); cleanup(); return; } @@ -613,15 +559,12 @@ void WHIPOutput::SendDelete() long response_code; curl_easy_getinfo(c, CURLINFO_RESPONSE_CODE, &response_code); if (response_code != 200) { - do_log(LOG_WARNING, - "DELETE request for resource URL failed. HTTP Code: %ld", - response_code); + do_log(LOG_WARNING, "DELETE request for resource URL failed. HTTP Code: %ld", response_code); cleanup(); return; } - do_log(LOG_DEBUG, - "Successfully performed DELETE request for resource URL"); + do_log(LOG_DEBUG, "Successfully performed DELETE request for resource URL"); resource_url.clear(); cleanup(); } @@ -657,15 +600,13 @@ void WHIPOutput::StopThread(bool signal) last_video_timestamp = 0; } -void WHIPOutput::Send(void *data, uintptr_t size, uint64_t duration, - std::shared_ptr track, +void WHIPOutput::Send(void *data, uintptr_t size, uint64_t duration, std::shared_ptr track, std::shared_ptr rtcp_sr_reporter) { if (track == nullptr || !track->isOpen()) return; - std::vector sample{(rtc::byte *)data, - (rtc::byte *)data + size}; + std::vector sample{(rtc::byte *)data, (rtc::byte *)data + size}; auto rtp_config = rtcp_sr_reporter->rtpConfig; @@ -673,16 +614,13 @@ void WHIPOutput::Send(void *data, uintptr_t size, uint64_t duration, auto elapsed_seconds = double(duration) / (1000.0 * 1000.0); // Get elapsed time in clock rate - uint32_t elapsed_timestamp = - rtp_config->secondsToTimestamp(elapsed_seconds); + uint32_t elapsed_timestamp = rtp_config->secondsToTimestamp(elapsed_seconds); // Set new timestamp rtp_config->timestamp = rtp_config->timestamp + elapsed_timestamp; // Get elapsed time in clock rate from last RTCP sender report - auto report_elapsed_timestamp = - rtp_config->timestamp - - rtcp_sr_reporter->lastReportedTimestamp(); + auto report_elapsed_timestamp = rtp_config->timestamp - rtcp_sr_reporter->lastReportedTimestamp(); // Check if last report was at least 1 second ago if (rtp_config->timestampToSeconds(report_elapsed_timestamp) > 1) @@ -725,8 +663,7 @@ void register_whip_output() info.stop = [](void *priv_data, uint64_t) { static_cast(priv_data)->Stop(); }; - info.encoded_packet = [](void *priv_data, - struct encoder_packet *packet) { + info.encoded_packet = [](void *priv_data, struct encoder_packet *packet) { static_cast(priv_data)->Data(packet); }; info.get_defaults = [](obs_data_t *) { @@ -735,8 +672,7 @@ void register_whip_output() return obs_properties_create(); }; info.get_total_bytes = [](void *priv_data) -> uint64_t { - return (uint64_t) static_cast(priv_data) - ->GetTotalBytes(); + return (uint64_t) static_cast(priv_data)->GetTotalBytes(); }; info.get_connect_time_ms = [](void *priv_data) -> int { return static_cast(priv_data)->GetConnectTime(); diff --git a/plugins/obs-webrtc/whip-output.h b/plugins/obs-webrtc/whip-output.h index 88fd433ee..2db60d655 100644 --- a/plugins/obs-webrtc/whip-output.h +++ b/plugins/obs-webrtc/whip-output.h @@ -27,21 +27,17 @@ public: inline int GetConnectTime() { return connect_time_ms; } private: - void ConfigureAudioTrack(std::string media_stream_id, - std::string cname); - void ConfigureVideoTrack(std::string media_stream_id, - std::string cname); + void ConfigureAudioTrack(std::string media_stream_id, std::string cname); + void ConfigureVideoTrack(std::string media_stream_id, std::string cname); bool Init(); bool Setup(); bool Connect(); void StartThread(); void SendDelete(); void StopThread(bool signal); - void ParseLinkHeader(std::string linkHeader, - std::vector &iceServers); + void ParseLinkHeader(std::string linkHeader, std::vector &iceServers); - void Send(void *data, uintptr_t size, uint64_t duration, - std::shared_ptr track, + void Send(void *data, uintptr_t size, uint64_t duration, std::shared_ptr track, std::shared_ptr rtcp_sr_reporter); obs_output_t *output; diff --git a/plugins/obs-webrtc/whip-service.cpp b/plugins/obs-webrtc/whip-service.cpp index d8b2dab98..33690fb39 100644 --- a/plugins/obs-webrtc/whip-service.cpp +++ b/plugins/obs-webrtc/whip-service.cpp @@ -3,9 +3,7 @@ const char *audio_codecs[] = {"opus", nullptr}; const char *video_codecs[] = {"h264", "hevc", "av1", nullptr}; -WHIPService::WHIPService(obs_data_t *settings, obs_service_t *) - : server(), - bearer_token() +WHIPService::WHIPService(obs_data_t *settings, obs_service_t *) : server(), bearer_token() { Update(settings); } @@ -21,9 +19,7 @@ obs_properties_t *WHIPService::Properties() obs_properties_t *ppts = obs_properties_create(); obs_properties_add_text(ppts, "server", "URL", OBS_TEXT_DEFAULT); - obs_properties_add_text(ppts, "bearer_token", - obs_module_text("Service.BearerToken"), - OBS_TEXT_PASSWORD); + obs_properties_add_text(ppts, "bearer_token", obs_module_text("Service.BearerToken"), OBS_TEXT_PASSWORD); return ppts; } @@ -62,8 +58,7 @@ void register_whip_service() info.get_name = [](void *) -> const char * { return obs_module_text("Service.Name"); }; - info.create = [](obs_data_t *settings, - obs_service_t *service) -> void * { + info.create = [](obs_data_t *settings, obs_service_t *service) -> void * { return new WHIPService(settings, service); }; info.destroy = [](void *priv_data) { @@ -84,10 +79,8 @@ void register_whip_service() info.get_output_type = [](void *) -> const char * { return "whip_output"; }; - info.apply_encoder_settings = [](void *, obs_data_t *video_settings, - obs_data_t *audio_settings) { - WHIPService::ApplyEncoderSettings(video_settings, - audio_settings); + info.apply_encoder_settings = [](void *, obs_data_t *video_settings, obs_data_t *audio_settings) { + WHIPService::ApplyEncoderSettings(video_settings, audio_settings); }; info.get_supported_video_codecs = [](void *) -> const char ** { return video_codecs; @@ -98,10 +91,8 @@ void register_whip_service() info.can_try_to_connect = [](void *priv_data) -> bool { return static_cast(priv_data)->CanTryToConnect(); }; - info.get_connect_info = [](void *priv_data, - uint32_t type) -> const char * { - return static_cast(priv_data)->GetConnectInfo( - (enum obs_service_connect_info)type); + info.get_connect_info = [](void *priv_data, uint32_t type) -> const char * { + return static_cast(priv_data)->GetConnectInfo((enum obs_service_connect_info)type); }; obs_register_service(&info); } diff --git a/plugins/obs-webrtc/whip-service.h b/plugins/obs-webrtc/whip-service.h index e5ecd63e1..50ad6385a 100644 --- a/plugins/obs-webrtc/whip-service.h +++ b/plugins/obs-webrtc/whip-service.h @@ -10,8 +10,7 @@ struct WHIPService { void Update(obs_data_t *settings); static obs_properties_t *Properties(); - static void ApplyEncoderSettings(obs_data_t *video_settings, - obs_data_t *audio_settings); + static void ApplyEncoderSettings(obs_data_t *video_settings, obs_data_t *audio_settings); bool CanTryToConnect(); const char *GetConnectInfo(enum obs_service_connect_info type); }; diff --git a/plugins/obs-webrtc/whip-utils.h b/plugins/obs-webrtc/whip-utils.h index 64338d6ed..353cab65b 100644 --- a/plugins/obs-webrtc/whip-utils.h +++ b/plugins/obs-webrtc/whip-utils.h @@ -6,9 +6,8 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[obs-webrtc] [whip_output: '%s'] " format, \ - obs_output_get_name(output), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[obs-webrtc] [whip_output: '%s'] " format, obs_output_get_name(output), ##__VA_ARGS__) static uint32_t generate_random_u32() { @@ -26,11 +25,9 @@ static std::string trim_string(const std::string &source) return ret; } -static std::string value_for_header(const std::string &header, - const std::string &val) +static std::string value_for_header(const std::string &header, const std::string &val) { - if (val.size() <= header.size() || - astrcmpi_n(header.c_str(), val.c_str(), header.size()) != 0) { + if (val.size() <= header.size() || astrcmpi_n(header.c_str(), val.c_str(), header.size()) != 0) { return ""; } @@ -42,8 +39,7 @@ static std::string value_for_header(const std::string &header, return val.substr(delimiter + 1); } -static size_t curl_writefunction(char *data, size_t size, size_t nmemb, - void *priv_data) +static size_t curl_writefunction(char *data, size_t size, size_t nmemb, void *priv_data) { auto read_buffer = static_cast(priv_data); @@ -53,8 +49,7 @@ static size_t curl_writefunction(char *data, size_t size, size_t nmemb, return real_size; } -static size_t curl_header_function(char *data, size_t size, size_t nmemb, - void *priv_data) +static size_t curl_header_function(char *data, size_t size, size_t nmemb, void *priv_data) { auto header_buffer = static_cast *>(priv_data); header_buffer->push_back(trim_string(std::string(data, size * nmemb))); diff --git a/plugins/obs-x264/obs-x264-test.c b/plugins/obs-x264/obs-x264-test.c index 10a9d4b56..78ebfc7cd 100644 --- a/plugins/obs-x264/obs-x264-test.c +++ b/plugins/obs-x264/obs-x264-test.c @@ -3,13 +3,12 @@ #include #include -#define CHECK(condition) \ - do { \ - if (!(condition)) { \ - fprintf(stderr, "%s:%d: error: check failed: %s\n", \ - __FILE__, __LINE__, #condition); \ - exit(1); \ - } \ +#define CHECK(condition) \ + do { \ + if (!(condition)) { \ + fprintf(stderr, "%s:%d: error: check failed: %s\n", __FILE__, __LINE__, #condition); \ + exit(1); \ + } \ } while (0) static void test_obs_parse_options() @@ -43,16 +42,14 @@ static void test_obs_parse_options() obs_free_options(options); // Invalid options are ignored. - options = obs_parse_options( - "ref=3 option_with_no_equal_sign bframes=8 1234"); + options = obs_parse_options("ref=3 option_with_no_equal_sign bframes=8 1234"); CHECK(options.count == 2); CHECK(strcmp(options.options[0].name, "ref") == 0); CHECK(strcmp(options.options[0].value, "3") == 0); CHECK(strcmp(options.options[1].name, "bframes") == 0); CHECK(strcmp(options.options[1].value, "8") == 0); CHECK(options.ignored_word_count == 2); - CHECK(strcmp(options.ignored_words[0], "option_with_no_equal_sign") == - 0); + CHECK(strcmp(options.ignored_words[0], "option_with_no_equal_sign") == 0); CHECK(strcmp(options.ignored_words[1], "1234") == 0); obs_free_options(options); diff --git a/plugins/obs-x264/obs-x264.c b/plugins/obs-x264/obs-x264.c index 23b019fe1..a6e972c76 100644 --- a/plugins/obs-x264/obs-x264.c +++ b/plugins/obs-x264/obs-x264.c @@ -30,15 +30,12 @@ #include -#define do_log_enc(level, encoder, format, ...) \ - blog(level, "[x264 encoder: '%s'] " format, \ - obs_encoder_get_name(encoder), ##__VA_ARGS__) -#define do_log(level, format, ...) \ - do_log_enc(level, obsx264->encoder, format, ##__VA_ARGS__) +#define do_log_enc(level, encoder, format, ...) \ + blog(level, "[x264 encoder: '%s'] " format, obs_encoder_get_name(encoder), ##__VA_ARGS__) +#define do_log(level, format, ...) do_log_enc(level, obsx264->encoder, format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) -#define warn_enc(encoder, format, ...) \ - do_log_enc(LOG_WARNING, encoder, format, ##__VA_ARGS__) +#define warn_enc(encoder, format, ...) do_log_enc(LOG_WARNING, encoder, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) #define debug(format, ...) do_log(LOG_DEBUG, format, ##__VA_ARGS__) @@ -140,8 +137,7 @@ static inline void add_strings(obs_property_t *list, const char *const *strings) #define TEXT_NONE obs_module_text("None") #define TEXT_X264_OPTS obs_module_text("EncoderOptions") -static bool use_bufsize_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool use_bufsize_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { bool use_bufsize = obs_data_get_bool(settings, "use_bufsize"); const char *rc = obs_data_get_string(settings, "rate_control"); @@ -152,8 +148,7 @@ static bool use_bufsize_modified(obs_properties_t *ppts, obs_property_t *p, return true; } -static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool rate_control_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *rc = obs_data_get_string(settings, "rate_control"); bool use_bufsize = obs_data_get_bool(settings, "use_bufsize"); @@ -181,8 +176,7 @@ static obs_properties_t *obs_x264_props(void *unused) obs_property_t *p; obs_property_t *headers; - list = obs_properties_add_list(props, "rate_control", TEXT_RATE_CONTROL, - OBS_COMBO_TYPE_LIST, + list = obs_properties_add_list(props, "rate_control", TEXT_RATE_CONTROL, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(list, "CBR", "CBR"); obs_property_list_add_string(list, "ABR", "ABR"); @@ -191,37 +185,28 @@ static obs_properties_t *obs_x264_props(void *unused) obs_property_set_modified_callback(list, rate_control_modified); - p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000, - 50); + p = obs_properties_add_int(props, "bitrate", TEXT_BITRATE, 50, 10000000, 50); obs_property_int_set_suffix(p, " Kbps"); p = obs_properties_add_bool(props, "use_bufsize", TEXT_CUSTOM_BUF); obs_property_set_modified_callback(p, use_bufsize_modified); - obs_properties_add_int(props, "buffer_size", TEXT_BUF_SIZE, 0, 10000000, - 1); + obs_properties_add_int(props, "buffer_size", TEXT_BUF_SIZE, 0, 10000000, 1); obs_properties_add_int(props, "crf", TEXT_CRF, 0, 51, 1); - p = obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, - 1); + p = obs_properties_add_int(props, "keyint_sec", TEXT_KEYINT_SEC, 0, 20, 1); obs_property_int_set_suffix(p, " s"); - list = obs_properties_add_list(props, "preset", TEXT_PRESET, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + list = obs_properties_add_list(props, "preset", TEXT_PRESET, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); add_strings(list, x264_preset_names); - list = obs_properties_add_list(props, "profile", TEXT_PROFILE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + list = obs_properties_add_list(props, "profile", TEXT_PROFILE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(list, TEXT_NONE, ""); obs_property_list_add_string(list, "baseline", "baseline"); obs_property_list_add_string(list, "main", "main"); obs_property_list_add_string(list, "high", "high"); - list = obs_properties_add_list(props, "tune", TEXT_TUNE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + list = obs_properties_add_list(props, "tune", TEXT_TUNE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(list, TEXT_NONE, ""); add_strings(list, x264_tune_names); @@ -229,18 +214,15 @@ static obs_properties_t *obs_x264_props(void *unused) obs_properties_add_bool(props, "vfr", TEXT_VFR); #endif - obs_properties_add_text(props, "x264opts", TEXT_X264_OPTS, - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "x264opts", TEXT_X264_OPTS, OBS_TEXT_DEFAULT); - headers = obs_properties_add_bool(props, "repeat_headers", - "repeat_headers"); + headers = obs_properties_add_bool(props, "repeat_headers", "repeat_headers"); obs_property_set_visible(headers, false); return props; } -static const char *validate(struct obs_x264 *obsx264, const char *val, - const char *name, const char *const *list) +static const char *validate(struct obs_x264 *obsx264, const char *val, const char *name, const char *const *list) { if (!val || !*val) return val; @@ -256,31 +238,27 @@ static const char *validate(struct obs_x264 *obsx264, const char *val, return NULL; } -static void override_base_param(struct obs_x264 *obsx264, - struct obs_option option, char **preset, - char **profile, char **tune) +static void override_base_param(struct obs_x264 *obsx264, struct obs_option option, char **preset, char **profile, + char **tune) { const char *name = option.name; const char *val = option.value; if (astrcmpi(name, "preset") == 0) { - const char *valid_name = - validate(obsx264, val, "preset", x264_preset_names); + const char *valid_name = validate(obsx264, val, "preset", x264_preset_names); if (valid_name) { bfree(*preset); *preset = bstrdup(val); } } else if (astrcmpi(name, "profile") == 0) { - const char *valid_name = - validate(obsx264, val, "profile", x264_profile_names); + const char *valid_name = validate(obsx264, val, "profile", x264_profile_names); if (valid_name) { bfree(*profile); *profile = bstrdup(val); } } else if (astrcmpi(name, "tune") == 0) { - const char *valid_name = - validate(obsx264, val, "tune", x264_tune_names); + const char *valid_name = validate(obsx264, val, "tune", x264_tune_names); if (valid_name) { bfree(*tune); *tune = bstrdup(val); @@ -288,14 +266,11 @@ static void override_base_param(struct obs_x264 *obsx264, } } -static inline void override_base_params(struct obs_x264 *obsx264, - const struct obs_options *options, - char **preset, char **profile, - char **tune) +static inline void override_base_params(struct obs_x264 *obsx264, const struct obs_options *options, char **preset, + char **profile, char **tune) { for (size_t i = 0; i < options->count; ++i) - override_base_param(obsx264, options->options[i], preset, - profile, tune); + override_base_param(obsx264, options->options[i], preset, profile, tune); } #define OPENCL_ALIAS "opencl_is_experimental_and_potentially_unstable" @@ -304,12 +279,10 @@ static inline void set_param(struct obs_x264 *obsx264, struct obs_option option) { const char *name = option.name; const char *val = option.value; - if (strcmp(name, "preset") != 0 && strcmp(name, "profile") != 0 && - strcmp(name, "tune") != 0 && strcmp(name, "fps") != 0 && - strcmp(name, "force-cfr") != 0 && strcmp(name, "width") != 0 && - strcmp(name, "height") != 0 && strcmp(name, "opencl") != 0 && - strcmp(name, "stats") != 0 && strcmp(name, "qpfile") != 0 && - strcmp(name, "pass") != 0) { + if (strcmp(name, "preset") != 0 && strcmp(name, "profile") != 0 && strcmp(name, "tune") != 0 && + strcmp(name, "fps") != 0 && strcmp(name, "force-cfr") != 0 && strcmp(name, "width") != 0 && + strcmp(name, "height") != 0 && strcmp(name, "opencl") != 0 && strcmp(name, "stats") != 0 && + strcmp(name, "qpfile") != 0 && strcmp(name, "pass") != 0) { if (strcmp(option.name, OPENCL_ALIAS) == 0) name = "opencl"; if (x264_param_parse(&obsx264->params, name, val) != 0) @@ -317,8 +290,7 @@ static inline void set_param(struct obs_x264 *obsx264, struct obs_option option) } } -static inline void apply_x264_profile(struct obs_x264 *obsx264, - const char *profile) +static inline void apply_x264_profile(struct obs_x264 *obsx264, const char *profile) { if (!obsx264->context && profile && *profile) { int ret = x264_param_apply_profile(&obsx264->params, profile); @@ -327,20 +299,16 @@ static inline void apply_x264_profile(struct obs_x264 *obsx264, } } -static inline const char *validate_preset(struct obs_x264 *obsx264, - const char *preset) +static inline const char *validate_preset(struct obs_x264 *obsx264, const char *preset) { - const char *new_preset = - validate(obsx264, preset, "preset", x264_preset_names); + const char *new_preset = validate(obsx264, preset, "preset", x264_preset_names); return new_preset ? new_preset : "veryfast"; } -static bool reset_x264_params(struct obs_x264 *obsx264, const char *preset, - const char *tune) +static bool reset_x264_params(struct obs_x264 *obsx264, const char *preset, const char *tune) { - int ret = x264_param_default_preset( - &obsx264->params, validate_preset(obsx264, preset), - validate(obsx264, tune, "tune", x264_tune_names)); + int ret = x264_param_default_preset(&obsx264->params, validate_preset(obsx264, preset), + validate(obsx264, tune, "tune", x264_tune_names)); return ret == 0; } @@ -362,8 +330,7 @@ static void log_x264(void *param, int level, const char *format, va_list args) blogva(level_map[level], format, args); } -static inline int get_x264_cs_val(const char *const name, - const char *const names[]) +static inline int get_x264_cs_val(const char *const name, const char *const names[]) { int idx = 0; do { @@ -376,15 +343,10 @@ static inline int get_x264_cs_val(const char *const name, static void obs_x264_video_info(void *data, struct video_scale_info *info); -enum rate_control { - RATE_CONTROL_CBR, - RATE_CONTROL_VBR, - RATE_CONTROL_ABR, - RATE_CONTROL_CRF -}; +enum rate_control { RATE_CONTROL_CBR, RATE_CONTROL_VBR, RATE_CONTROL_ABR, RATE_CONTROL_CRF }; -static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, - const struct obs_options *options, bool update) +static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, const struct obs_options *options, + bool update) { video_t *video = obs_encoder_video(obsx264->encoder); const struct video_output_info *voi = video_output_get_info(video); @@ -396,8 +358,7 @@ static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, obs_x264_video_info(obsx264, &info); - const char *rate_control = - obs_data_get_string(settings, "rate_control"); + const char *rate_control = obs_data_get_string(settings, "rate_control"); int bitrate = (int)obs_data_get_int(settings, "bitrate"); int buffer_size = (int)obs_data_get_int(settings, "buffer_size"); @@ -442,8 +403,7 @@ static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, } if (keyint_sec) - obsx264->params.i_keyint_max = - keyint_sec * voi->fps_num / voi->fps_den; + obsx264->params.i_keyint_max = keyint_sec * voi->fps_num / voi->fps_den; if (!use_bufsize) buffer_size = bitrate; @@ -498,12 +458,9 @@ static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, obsx264->params.vui.i_sar_height = 1; obsx264->params.vui.i_sar_width = 1; obsx264->params.vui.b_fullrange = info.range == VIDEO_RANGE_FULL; - obsx264->params.vui.i_colorprim = - get_x264_cs_val(colorprim, x264_colorprim_names); - obsx264->params.vui.i_transfer = - get_x264_cs_val(transfer, x264_transfer_names); - obsx264->params.vui.i_colmatrix = - get_x264_cs_val(colmatrix, x264_colmatrix_names); + obsx264->params.vui.i_colorprim = get_x264_cs_val(colorprim, x264_colorprim_names); + obsx264->params.vui.i_transfer = get_x264_cs_val(transfer, x264_transfer_names); + obsx264->params.vui.i_colmatrix = get_x264_cs_val(colmatrix, x264_colmatrix_names); /* use the new filler method for CBR to allow real-time adjusting of * the bitrate */ @@ -532,8 +489,7 @@ static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, obsx264->params.i_csp = X264_CSP_NV12; for (size_t i = 0; i < options->ignored_word_count; ++i) - warn("ignoring invalid x264 option: %s", - options->ignored_words[i]); + warn("ignoring invalid x264 option: %s", options->ignored_words[i]); for (size_t i = 0; i < options->count; ++i) set_param(obsx264, options->options[i]); @@ -548,31 +504,26 @@ static void update_params(struct obs_x264 *obsx264, obs_data_t *settings, "\twidth: %d\n" "\theight: %d\n" "\tkeyint: %d\n", - rate_control, obsx264->params.rc.i_vbv_max_bitrate, - obsx264->params.rc.i_vbv_buffer_size, - (int)obsx264->params.rc.f_rf_constant, voi->fps_num, - voi->fps_den, width, height, obsx264->params.i_keyint_max); + rate_control, obsx264->params.rc.i_vbv_max_bitrate, obsx264->params.rc.i_vbv_buffer_size, + (int)obsx264->params.rc.f_rf_constant, voi->fps_num, voi->fps_den, width, height, + obsx264->params.i_keyint_max); } } -static void log_custom_options(struct obs_x264 *obsx264, - const struct obs_options *options) +static void log_custom_options(struct obs_x264 *obsx264, const struct obs_options *options) { if (options->count == 0) { return; } size_t settings_string_length = 0; for (size_t i = 0; i < options->count; ++i) - settings_string_length += strlen(options->options[i].name) + - strlen(options->options[i].value) + 5; + settings_string_length += strlen(options->options[i].name) + strlen(options->options[i].value) + 5; size_t buffer_size = settings_string_length + 1; char *settings_string = bmalloc(settings_string_length + 1); char *p = settings_string; size_t remaining_buffer_size = buffer_size; for (size_t i = 0; i < options->count; ++i) { - int chars_written = snprintf(p, remaining_buffer_size, - "\n\t%s = %s", - options->options[i].name, + int chars_written = snprintf(p, remaining_buffer_size, "\n\t%s = %s", options->options[i].name, options->options[i].value); assert(chars_written >= 0); assert((size_t)chars_written <= remaining_buffer_size); @@ -585,14 +536,12 @@ static void log_custom_options(struct obs_x264 *obsx264, bfree(settings_string); } -static bool update_settings(struct obs_x264 *obsx264, obs_data_t *settings, - bool update) +static bool update_settings(struct obs_x264 *obsx264, obs_data_t *settings, bool update) { char *preset = bstrdup(obs_data_get_string(settings, "preset")); char *profile = bstrdup(obs_data_get_string(settings, "profile")); char *tune = bstrdup(obs_data_get_string(settings, "tune")); - struct obs_options options = - obs_parse_options(obs_data_get_string(settings, "x264opts")); + struct obs_options options = obs_parse_options(obs_data_get_string(settings, "x264opts")); bool repeat_headers = obs_data_get_bool(settings, "repeat_headers"); bool success = true; @@ -601,8 +550,7 @@ static bool update_settings(struct obs_x264 *obsx264, obs_data_t *settings, blog(LOG_INFO, "---------------------------------"); if (!obsx264->context) { - override_base_params(obsx264, &options, &preset, &profile, - &tune); + override_base_params(obsx264, &options, &preset, &profile, &tune); if (preset && *preset) info("preset: %s", preset); @@ -672,8 +620,7 @@ static void load_headers(struct obs_x264 *obsx264) if (nal->i_type == NAL_SEI) da_push_back_array(sei, nal->p_payload, nal->i_payload); else - da_push_back_array(header, nal->p_payload, - nal->i_payload); + da_push_back_array(header, nal->p_payload, nal->i_payload); } obsx264->extra_data = header.array; @@ -691,20 +638,13 @@ static void *obs_x264_create(obs_data_t *settings, obs_encoder_t *encoder) case VIDEO_FORMAT_P010: case VIDEO_FORMAT_P216: case VIDEO_FORMAT_P416: - obs_encoder_set_last_error( - encoder, obs_module_text("HighPrecisionUnsupported")); - warn_enc( - encoder, - "OBS does not support using x264 with high-precision formats"); + obs_encoder_set_last_error(encoder, obs_module_text("HighPrecisionUnsupported")); + warn_enc(encoder, "OBS does not support using x264 with high-precision formats"); return NULL; default: - if (voi->colorspace == VIDEO_CS_2100_PQ || - voi->colorspace == VIDEO_CS_2100_HLG) { - obs_encoder_set_last_error( - encoder, obs_module_text("HdrUnsupported")); - warn_enc( - encoder, - "OBS does not support using x264 with Rec. 2100"); + if (voi->colorspace == VIDEO_CS_2100_PQ || voi->colorspace == VIDEO_CS_2100_HLG) { + obs_encoder_set_last_error(encoder, obs_module_text("HdrUnsupported")); + warn_enc(encoder, "OBS does not support using x264 with Rec. 2100"); return NULL; } break; @@ -729,15 +669,13 @@ static void *obs_x264_create(obs_data_t *settings, obs_encoder_t *encoder) return NULL; } - obsx264->performance_token = - os_request_high_performance("x264 encoding"); + obsx264->performance_token = os_request_high_performance("x264 encoding"); return obsx264; } -static void parse_packet(struct obs_x264 *obsx264, - struct encoder_packet *packet, x264_nal_t *nals, - int nal_count, x264_picture_t *pic_out) +static void parse_packet(struct obs_x264 *obsx264, struct encoder_packet *packet, x264_nal_t *nals, int nal_count, + x264_picture_t *pic_out) { if (!nal_count) return; @@ -746,8 +684,7 @@ static void parse_packet(struct obs_x264 *obsx264, for (int i = 0; i < nal_count; i++) { x264_nal_t *nal = nals + i; - da_push_back_array(obsx264->packet_data, nal->p_payload, - nal->i_payload); + da_push_back_array(obsx264->packet_data, nal->p_payload, nal->i_payload); } packet->data = obsx264->packet_data.array; @@ -758,8 +695,7 @@ static void parse_packet(struct obs_x264 *obsx264, packet->keyframe = pic_out->b_keyframe != 0; } -static inline void init_pic_data(struct obs_x264 *obsx264, x264_picture_t *pic, - struct encoder_frame *frame) +static inline void init_pic_data(struct obs_x264 *obsx264, x264_picture_t *pic, struct encoder_frame *frame) { x264_picture_init(pic); @@ -814,8 +750,7 @@ static void roi_cb(void *param, struct obs_encoder_roi *roi) static void add_roi(struct obs_x264 *obsx264, x264_picture_t *pic) { - const uint32_t increment = - obs_encoder_get_roi_increment(obsx264->encoder); + const uint32_t increment = obs_encoder_get_roi_increment(obsx264->encoder); if (obsx264->quant_offsets && obsx264->roi_increment == increment) { pic->prop.quant_offsets = obsx264->quant_offsets; @@ -839,8 +774,7 @@ static void add_roi(struct obs_x264 *obsx264, x264_picture_t *pic) obsx264->roi_increment = increment; } -static bool obs_x264_encode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, +static bool obs_x264_encode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { struct obs_x264 *obsx264 = data; @@ -858,8 +792,7 @@ static bool obs_x264_encode(void *data, struct encoder_frame *frame, if (obs_encoder_has_roi(obsx264->encoder)) add_roi(obsx264, &pic); - ret = x264_encoder_encode(obsx264->context, &nals, &nal_count, - (frame ? &pic : NULL), &pic_out); + ret = x264_encoder_encode(obsx264->context, &nals, &nal_count, (frame ? &pic : NULL), &pic_out); if (ret < 0) { warn("encode failed"); return false; @@ -897,8 +830,7 @@ static bool obs_x264_sei(void *data, uint8_t **sei, size_t *size) static inline bool valid_format(enum video_format format) { - return format == VIDEO_FORMAT_I420 || format == VIDEO_FORMAT_NV12 || - format == VIDEO_FORMAT_I444; + return format == VIDEO_FORMAT_I420 || format == VIDEO_FORMAT_NV12 || format == VIDEO_FORMAT_I444; } static void obs_x264_video_info(void *data, struct video_scale_info *info) @@ -909,8 +841,7 @@ static void obs_x264_video_info(void *data, struct video_scale_info *info) pref_format = obs_encoder_get_preferred_video_format(obsx264->encoder); if (!valid_format(pref_format)) { - pref_format = valid_format(info->format) ? info->format - : VIDEO_FORMAT_NV12; + pref_format = valid_format(info->format) ? info->format : VIDEO_FORMAT_NV12; } info->format = pref_format; diff --git a/plugins/oss-audio/oss-input.c b/plugins/oss-audio/oss-input.c index 04581529e..d00c816f1 100644 --- a/plugins/oss-audio/oss-input.c +++ b/plugins/oss-audio/oss-input.c @@ -75,10 +75,8 @@ struct rate_option { int rate; char *desc; } rate_table[] = { - {8000, "8000 Hz"}, {11025, "11025 Hz"}, {16000, "16000 Hz"}, - {22050, "22050 Hz"}, {32000, "32000 Hz"}, {44100, "44100 Hz"}, - {48000, "48000 Hz"}, {96000, "96000 Hz"}, {192000, "192000 Hz"}, - {384000, "384000 Hz"}, + {8000, "8000 Hz"}, {11025, "11025 Hz"}, {16000, "16000 Hz"}, {22050, "22050 Hz"}, {32000, "32000 Hz"}, + {44100, "44100 Hz"}, {48000, "48000 Hz"}, {96000, "96000 Hz"}, {192000, "192000 Hz"}, {384000, "384000 Hz"}, }; static unsigned int oss_sample_size(unsigned int sample_fmt) @@ -161,28 +159,24 @@ static int oss_setup_device(struct oss_input_data *handle) int val = handle->channels; err = ioctl(fd, SNDCTL_DSP_CHANNELS, &val); if (err) { - blog(LOG_ERROR, "Failed to set number of channels on DSP '%s'.", - handle->device); + blog(LOG_ERROR, "Failed to set number of channels on DSP '%s'.", handle->device); goto failed_state; } val = handle->sample_fmt; err = ioctl(fd, SNDCTL_DSP_SETFMT, &val); if (err) { - blog(LOG_ERROR, "Failed to set format on DSP '%s'.", - handle->device); + blog(LOG_ERROR, "Failed to set format on DSP '%s'.", handle->device); goto failed_state; } val = handle->rate; err = ioctl(fd, SNDCTL_DSP_SPEED, &val); if (err) { - blog(LOG_ERROR, "Failed to set sample rate on DSP '%s'.", - handle->device); + blog(LOG_ERROR, "Failed to set sample rate on DSP '%s'.", handle->device); goto failed_state; } err = ioctl(fd, SNDCTL_DSP_GETISPACE, &bi); if (err) { - blog(LOG_ERROR, "Failed to get fragment size on DSP '%s'.", - handle->device); + blog(LOG_ERROR, "Failed to get fragment size on DSP '%s'.", handle->device); goto failed_state; } @@ -238,32 +232,24 @@ static void *oss_reader_thr(void *vptr) ssize_t nbytes; do { - nbytes = read(handle->dsp_fd, handle->dsp_buf, - handle->dsp_fragsize); + nbytes = read(handle->dsp_fd, handle->dsp_buf, handle->dsp_fragsize); } while (nbytes < 0 && errno == EINTR); if (nbytes < 0) { - blog(LOG_ERROR, - "%s: Failed to read buffer on DSP '%s'. Errno %d", - __func__, handle->device, errno); + blog(LOG_ERROR, "%s: Failed to read buffer on DSP '%s'. Errno %d", __func__, + handle->device, errno); break; } else if (!nbytes) { - blog(LOG_ERROR, - "%s: Unexpected EOF on DSP '%s'.", - __func__, handle->device); + blog(LOG_ERROR, "%s: Unexpected EOF on DSP '%s'.", __func__, handle->device); break; } out.data[0] = handle->dsp_buf; - out.format = - oss_fmt_to_obs_audio_format(handle->sample_fmt); - out.speakers = - oss_channels_to_obs_speakers(handle->channels); + out.format = oss_fmt_to_obs_audio_format(handle->sample_fmt); + out.speakers = oss_channels_to_obs_speakers(handle->channels); out.samples_per_sec = handle->rate; out.frames = nbytes / framesize; - out.timestamp = os_gettime_ns() - - util_mul_div64(out.frames, NSEC_PER_SEC, - handle->rate); + out.timestamp = os_gettime_ns() - util_mul_div64(out.frames, NSEC_PER_SEC, handle->rate); obs_source_output_audio(handle->source, &out); } if (fds[1].revents & POLLIN) { @@ -416,8 +402,7 @@ static void oss_update(void *vptr, obs_data_t *settings) oss_close_device(handle); const char *dsp = obs_data_get_string(settings, OBS_PROPS_DSP); - const char *custom_dsp = - obs_data_get_string(settings, OBS_PROPS_CUSTOM_DSP); + const char *custom_dsp = obs_data_get_string(settings, OBS_PROPS_CUSTOM_DSP); if (dsp == NULL) { bfree(handle->device); handle->device = NULL; @@ -471,8 +456,7 @@ static void oss_prop_add_devices(obs_property_t *p) fp = fopen(OSS_SNDSTAT_PATH, "r"); if (fp == NULL) { - blog(LOG_ERROR, "Failed to open sndstat at '%s'.", - OSS_SNDSTAT_PATH); + blog(LOG_ERROR, "Failed to open sndstat at '%s'.", OSS_SNDSTAT_PATH); return; } @@ -486,14 +470,12 @@ static void oss_prop_add_devices(obs_property_t *p) skipall = true; continue; } - if (!strncmp(line, OSS_DEVICE_BEGIN, - strlen(OSS_DEVICE_BEGIN))) { + if (!strncmp(line, OSS_DEVICE_BEGIN, strlen(OSS_DEVICE_BEGIN))) { ud_matching = false; skipall = false; continue; } - if (!strncmp(line, OSS_USERDEVICE_BEGIN, - strlen(OSS_USERDEVICE_BEGIN))) { + if (!strncmp(line, OSS_USERDEVICE_BEGIN, strlen(OSS_USERDEVICE_BEGIN))) { ud_matching = true; skipall = false; continue; @@ -526,13 +508,11 @@ static void oss_prop_add_devices(obs_property_t *p) goto free_all_str; *ptr++ = '\0'; if (!isdigit(pmode[0])) { - if (strcmp(pmode, "rec") != 0 && - strcmp(pmode, "play/rec") != 0) + if (strcmp(pmode, "rec") != 0 && strcmp(pmode, "play/rec") != 0) goto free_all_str; } else { int npcs, nrcs; - if (sscanf(pmode, "%dp:%*dv/%dr:%*dv", &npcs, &nrcs) != - 2) + if (sscanf(pmode, "%dp:%*dv/%dr:%*dv", &npcs, &nrcs) != 2) goto free_all_str; if (nrcs < 1) goto free_all_str; @@ -567,8 +547,7 @@ static void oss_prop_add_devices(obs_property_t *p) */ static void oss_defaults(obs_data_t *settings) { - obs_data_set_default_int(settings, OBS_PROPS_CHANNELS, - OSS_CHANNELS_DEFAULT); + obs_data_set_default_int(settings, OBS_PROPS_CHANNELS, OSS_CHANNELS_DEFAULT); obs_data_set_default_int(settings, OBS_PROPS_RATE, OSS_RATE_DEFAULT); obs_data_set_default_int(settings, OBS_PROPS_SAMPLE_FMT, AFMT_S16_LE); obs_data_set_default_string(settings, OBS_PROPS_DSP, OSS_DSP_DEFAULT); @@ -579,8 +558,7 @@ static void oss_defaults(obs_data_t *settings) * * Fetch the engine information of the corresponding DSP */ -static bool oss_fill_device_info(obs_property_t *rate, obs_property_t *channels, - const char *device) +static bool oss_fill_device_info(obs_property_t *rate, obs_property_t *channels, const char *device) { oss_audioinfo ai; int fd = -1; @@ -601,14 +579,11 @@ static bool oss_fill_device_info(obs_property_t *rate, obs_property_t *channels, ai.dev = -1; err = ioctl(fd, SNDCTL_ENGINEINFO, &ai); if (err) { - blog(LOG_ERROR, - "Failed to issue ioctl(SNDCTL_ENGINEINFO) on device '%s'. Errno: %d", - device, errno); + blog(LOG_ERROR, "Failed to issue ioctl(SNDCTL_ENGINEINFO) on device '%s'. Errno: %d", device, errno); goto cleanup; } - for (int i = ai.min_channels; - i <= ai.max_channels && i <= OSS_MAX_CHANNELS; i++) { + for (int i = ai.min_channels; i <= ai.max_channels && i <= OSS_MAX_CHANNELS; i++) { enum speaker_layout layout = oss_channels_to_obs_speakers(i); if (layout != SPEAKERS_UNKNOWN) { @@ -618,12 +593,9 @@ static bool oss_fill_device_info(obs_property_t *rate, obs_property_t *channels, } } - for (size_t i = 0; i < sizeof(rate_table) / sizeof(rate_table[0]); - i++) { - if (ai.min_rate <= rate_table[i].rate && - ai.max_rate >= rate_table[i].rate) - obs_property_list_add_int(rate, rate_table[i].desc, - rate_table[i].rate); + for (size_t i = 0; i < sizeof(rate_table) / sizeof(rate_table[0]); i++) { + if (ai.min_rate <= rate_table[i].rate && ai.max_rate >= rate_table[i].rate) + obs_property_list_add_int(rate, rate_table[i].desc, rate_table[i].rate); } cleanup: @@ -639,8 +611,7 @@ cleanup: /** * Get plugin properties */ -static bool oss_on_devices_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool oss_on_devices_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { obs_property_t *rate, *channels; obs_property_t *custom_dsp; @@ -681,35 +652,23 @@ static obs_properties_t *oss_properties(void *unused) props = obs_properties_create(); - devices = obs_properties_add_list(props, OBS_PROPS_DSP, - obs_module_text("DSP"), - OBS_COMBO_TYPE_LIST, + devices = obs_properties_add_list(props, OBS_PROPS_DSP, obs_module_text("DSP"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(devices, obs_module_text("Default"), - OSS_DSP_DEFAULT); - obs_property_list_add_string(devices, obs_module_text("Custom"), - OBS_PATH_DSP_CUSTOM); + obs_property_list_add_string(devices, obs_module_text("Default"), OSS_DSP_DEFAULT); + obs_property_list_add_string(devices, obs_module_text("Custom"), OBS_PATH_DSP_CUSTOM); obs_property_set_modified_callback(devices, oss_on_devices_changed); - obs_properties_add_text(props, OBS_PROPS_CUSTOM_DSP, - obs_module_text("CustomDSPPath"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, OBS_PROPS_CUSTOM_DSP, obs_module_text("CustomDSPPath"), OBS_TEXT_DEFAULT); - rate = obs_properties_add_list(props, OBS_PROPS_RATE, - obs_module_text("SampleRate"), - OBS_COMBO_TYPE_LIST, + rate = obs_properties_add_list(props, OBS_PROPS_RATE, obs_module_text("SampleRate"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - channels = obs_properties_add_list(props, OBS_PROPS_CHANNELS, - obs_module_text("Channels"), - OBS_COMBO_TYPE_LIST, + channels = obs_properties_add_list(props, OBS_PROPS_CHANNELS, obs_module_text("Channels"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); oss_fill_device_info(rate, channels, OSS_DSP_DEFAULT); - sample_fmt = obs_properties_add_list(props, OBS_PROPS_SAMPLE_FMT, - obs_module_text("SampleFormat"), - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + sample_fmt = obs_properties_add_list(props, OBS_PROPS_SAMPLE_FMT, obs_module_text("SampleFormat"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(sample_fmt, "pcm8", AFMT_U8); obs_property_list_add_int(sample_fmt, "pcm16le", AFMT_S16_LE); diff --git a/plugins/rtmp-services/rtmp-common.c b/plugins/rtmp-services/rtmp-common.c index 363ed33a4..980103da1 100644 --- a/plugins/rtmp-services/rtmp-common.c +++ b/plugins/rtmp-services/rtmp-common.c @@ -34,8 +34,7 @@ static const char *rtmp_common_getname(void *unused) } static json_t *open_services_file(void); -static inline json_t *find_service(json_t *root, const char *name, - const char **p_new_name); +static inline json_t *find_service(json_t *root, const char *name, const char **p_new_name); static inline bool get_bool_val(json_t *service, const char *key); static inline const char *get_string_val(json_t *service, const char *key); static inline int get_int_val(json_t *service, const char *key); @@ -43,8 +42,7 @@ static inline int get_int_val(json_t *service, const char *key); extern void twitch_ingests_refresh(int seconds); extern void amazon_ivs_ingests_refresh(int seconds); -static void ensure_valid_url(struct rtmp_common *service, json_t *json, - obs_data_t *settings) +static void ensure_valid_url(struct rtmp_common *service, json_t *json, obs_data_t *settings) { json_t *servers = json_object_get(json, "servers"); const char *top_url = NULL; @@ -171,11 +169,9 @@ static void rtmp_common_update(void *data, obs_data_t *settings) service->service = bstrdup(new_name); } - if ((service->protocol == NULL || - service->protocol[0] == '\0')) { + if ((service->protocol == NULL || service->protocol[0] == '\0')) { bfree(service->protocol); - service->protocol = - bstrdup(get_protocol(serv, settings)); + service->protocol = bstrdup(get_protocol(serv, settings)); } if (serv) { @@ -186,8 +182,8 @@ static void rtmp_common_update(void *data, obs_data_t *settings) update_recommendations(service, rec); } - service->supports_additional_audio_track = get_bool_val( - serv, "supports_additional_audio_track"); + service->supports_additional_audio_track = + get_bool_val(serv, "supports_additional_audio_track"); ensure_valid_url(service, serv, settings); } } @@ -272,8 +268,7 @@ static bool is_protocol_available(json_t *service) return ret; } -static void add_service(obs_property_t *list, json_t *service, bool show_all, - const char *cur_service) +static void add_service(obs_property_t *list, json_t *service, bool show_all, const char *cur_service) { json_t *servers; const char *name; @@ -309,8 +304,7 @@ static void add_service(obs_property_t *list, json_t *service, bool show_all, obs_property_list_add_string(list, name, name); } -static void add_services(obs_property_t *list, json_t *root, bool show_all, - const char *cur_service) +static void add_services(obs_property_t *list, json_t *root, bool show_all, const char *cur_service) { json_t *service; size_t index; @@ -330,8 +324,7 @@ static void add_services(obs_property_t *list, json_t *root, bool show_all, service = find_service(root, cur_service, NULL); if (!service && cur_service && *cur_service) { - obs_property_list_insert_string(list, 0, cur_service, - cur_service); + obs_property_list_insert_string(list, 0, cur_service, cur_service); obs_property_list_item_disable(list, 0, true); } } @@ -405,8 +398,7 @@ static json_t *open_services_file(void) return root; } -static void build_service_list(obs_property_t *list, json_t *root, - bool show_all, const char *cur_service) +static void build_service_list(obs_property_t *list, json_t *root, bool show_all, const char *cur_service) { obs_property_list_clear(list); add_services(list, root, show_all, cur_service); @@ -423,16 +415,14 @@ static bool fill_twitch_servers_locked(obs_property_t *servers_prop) { size_t count = twitch_ingest_count(); - obs_property_list_add_string(servers_prop, - obs_module_text("Server.Auto"), "auto"); + obs_property_list_add_string(servers_prop, obs_module_text("Server.Auto"), "auto"); if (count <= 1) return false; for (size_t i = 0; i < count; i++) { struct ingest twitch_ing = twitch_ingest(i); - obs_property_list_add_string(servers_prop, twitch_ing.name, - twitch_ing.url); + obs_property_list_add_string(servers_prop, twitch_ing.name, twitch_ing.url); } return true; @@ -456,12 +446,9 @@ static bool fill_amazon_ivs_servers_locked(obs_property_t *servers_prop) bool rtmps_available = obs_is_output_protocol_registered("RTMPS"); if (rtmps_available) { - obs_property_list_add_string( - servers_prop, obs_module_text("Server.AutoRTMPS"), - "auto-rtmps"); + obs_property_list_add_string(servers_prop, obs_module_text("Server.AutoRTMPS"), "auto-rtmps"); } - obs_property_list_add_string( - servers_prop, obs_module_text("Server.AutoRTMP"), "auto-rtmp"); + obs_property_list_add_string(servers_prop, obs_module_text("Server.AutoRTMP"), "auto-rtmp"); if (count <= 1) return false; @@ -469,19 +456,15 @@ static bool fill_amazon_ivs_servers_locked(obs_property_t *servers_prop) if (rtmps_available) { for (size_t i = 0; i < count; i++) { struct ingest amazon_ivs_ing = amazon_ivs_ingest(i); - dstr_printf(&name_buffer, "%s (RTMPS)", - amazon_ivs_ing.name); - obs_property_list_add_string(servers_prop, - name_buffer.array, - amazon_ivs_ing.rtmps_url); + dstr_printf(&name_buffer, "%s (RTMPS)", amazon_ivs_ing.name); + obs_property_list_add_string(servers_prop, name_buffer.array, amazon_ivs_ing.rtmps_url); } } for (size_t i = 0; i < count; i++) { struct ingest amazon_ivs_ing = amazon_ivs_ingest(i); dstr_printf(&name_buffer, "%s (RTMP)", amazon_ivs_ing.name); - obs_property_list_add_string(servers_prop, name_buffer.array, - amazon_ivs_ing.url); + obs_property_list_add_string(servers_prop, name_buffer.array, amazon_ivs_ing.url); } dstr_free(&name_buffer); @@ -500,8 +483,7 @@ static inline bool fill_amazon_ivs_servers(obs_property_t *servers_prop) return success; } -static void fill_servers(obs_property_t *servers_prop, json_t *service, - const char *name) +static void fill_servers(obs_property_t *servers_prop, json_t *service, const char *name) { json_t *servers, *server; size_t index; @@ -526,8 +508,7 @@ static void fill_servers(obs_property_t *servers_prop, json_t *service, /* Assumption: Nimo TV should be RTMP only, so no RTMPS check in the ingest */ if (strcmp(name, "Nimo TV") == 0) { - obs_property_list_add_string( - servers_prop, obs_module_text("Server.Auto"), "auto"); + obs_property_list_add_string(servers_prop, obs_module_text("Server.Auto"), "auto"); } if (strcmp(name, "Amazon IVS") == 0) { @@ -543,17 +524,14 @@ static void fill_servers(obs_property_t *servers_prop, json_t *service, continue; /* Skip RTMPS server if protocol not registered */ - if ((!obs_is_output_protocol_registered("RTMPS")) && - (strncmp(url, "rtmps://", 8) == 0)) + if ((!obs_is_output_protocol_registered("RTMPS")) && (strncmp(url, "rtmps://", 8) == 0)) continue; obs_property_list_add_string(servers_prop, server_name, url); } } -static void copy_string_from_json_if_available(json_t *service, - obs_data_t *settings, - const char *name) +static void copy_string_from_json_if_available(json_t *service, obs_data_t *settings, const char *name) { const char *string = get_string_val(service, name); if (string) @@ -567,8 +545,7 @@ static void fill_more_info_link(json_t *service, obs_data_t *settings) static void fill_stream_key_link(json_t *service, obs_data_t *settings) { - copy_string_from_json_if_available(service, settings, - "stream_key_link"); + copy_string_from_json_if_available(service, settings, "stream_key_link"); } static void update_protocol(json_t *service, obs_data_t *settings) @@ -600,29 +577,22 @@ static void copy_info_to_settings(json_t *service, obs_data_t *settings) fill_more_info_link(service, settings); fill_stream_key_link(service, settings); - copy_string_from_json_if_available( - service, settings, "multitrack_video_configuration_url"); - copy_string_from_json_if_available(service, settings, - "multitrack_video_name"); + copy_string_from_json_if_available(service, settings, "multitrack_video_configuration_url"); + copy_string_from_json_if_available(service, settings, "multitrack_video_name"); if (!obs_data_has_user_value(settings, "multitrack_video_name")) { - obs_data_set_string(settings, "multitrack_video_name", - "Multitrack Video"); + obs_data_set_string(settings, "multitrack_video_name", "Multitrack Video"); } - const char *learn_more_link_url = - get_string_val(service, "multitrack_video_learn_more_link"); + const char *learn_more_link_url = get_string_val(service, "multitrack_video_learn_more_link"); struct dstr learn_more_link = {0}; if (learn_more_link_url) { - dstr_init_copy( - &learn_more_link, - obs_module_text("MultitrackVideo.LearnMoreLink")); + dstr_init_copy(&learn_more_link, obs_module_text("MultitrackVideo.LearnMoreLink")); dstr_replace(&learn_more_link, "%1", learn_more_link_url); } struct dstr str; dstr_init_copy(&str, obs_module_text("MultitrackVideo.Disclaimer")); - dstr_replace(&str, "%1", - obs_data_get_string(settings, "multitrack_video_name")); + dstr_replace(&str, "%1", obs_data_get_string(settings, "multitrack_video_name")); dstr_replace(&str, "%2", name); if (learn_more_link.array) { dstr_cat(&str, learn_more_link.array); @@ -634,8 +604,7 @@ static void copy_info_to_settings(json_t *service, obs_data_t *settings) update_protocol(service, settings); } -static inline json_t *find_service(json_t *root, const char *name, - const char **p_new_name) +static inline json_t *find_service(json_t *root, const char *name, const char **p_new_name) { size_t index; json_t *service; @@ -671,8 +640,7 @@ static inline json_t *find_service(json_t *root, const char *name, return NULL; } -static bool service_selected(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool service_selected(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { const char *name = obs_data_get_string(settings, "service"); json_t *root = obs_properties_get_param(props); @@ -705,8 +673,7 @@ static bool service_selected(obs_properties_t *props, obs_property_t *p, return true; } -static bool show_all_services_toggled(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool show_all_services_toggled(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { const char *cur_service = obs_data_get_string(settings, "service"); bool show_all = obs_data_get_bool(settings, "show_all"); @@ -715,8 +682,7 @@ static bool show_all_services_toggled(obs_properties_t *ppts, obs_property_t *p, if (!root) return false; - build_service_list(obs_properties_get(ppts, "service"), root, show_all, - cur_service); + build_service_list(obs_properties_get(ppts, "service"), root, show_all, cur_service); UNUSED_PARAMETER(p); return true; @@ -734,29 +700,25 @@ static obs_properties_t *rtmp_common_properties(void *unused) if (root) obs_properties_set_param(ppts, root, properties_data_destroy); - p = obs_properties_add_list(ppts, "service", obs_module_text("Service"), - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, "service", obs_module_text("Service"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(p, service_selected); - p = obs_properties_add_bool(ppts, "show_all", - obs_module_text("ShowAll")); + p = obs_properties_add_bool(ppts, "show_all", obs_module_text("ShowAll")); obs_property_set_modified_callback(p, show_all_services_toggled); - obs_properties_add_list(ppts, "server", obs_module_text("Server"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_properties_add_list(ppts, "server", obs_module_text("Server"), OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); - obs_properties_add_text(ppts, "key", obs_module_text("StreamKey"), - OBS_TEXT_PASSWORD); + obs_properties_add_text(ppts, "key", obs_module_text("StreamKey"), OBS_TEXT_PASSWORD); return ppts; } static int get_bitrate_matrix_max(json_t *array); -static void apply_video_encoder_settings(obs_data_t *settings, - json_t *recommended) +static void apply_video_encoder_settings(obs_data_t *settings, json_t *recommended) { json_t *item = json_object_get(recommended, "keyint"); if (json_is_integer(item)) { @@ -768,8 +730,7 @@ static void apply_video_encoder_settings(obs_data_t *settings, item = json_object_get(recommended, "profile"); obs_data_item_t *enc_item = obs_data_item_byname(settings, "profile"); - if (json_is_string(item) && - obs_data_item_gettype(enc_item) == OBS_DATA_STRING) { + if (json_is_string(item) && obs_data_item_gettype(enc_item) == OBS_DATA_STRING) { const char *profile = json_string_value(item); obs_data_set_string(settings, "profile", profile); } @@ -787,8 +748,7 @@ static void apply_video_encoder_settings(obs_data_t *settings, max_bitrate = (int)json_integer_value(item); } - if (max_bitrate && - obs_data_get_int(settings, "bitrate") > max_bitrate) { + if (max_bitrate && obs_data_get_int(settings, "bitrate") > max_bitrate) { obs_data_set_int(settings, "bitrate", max_bitrate); obs_data_set_int(settings, "buffer_size", max_bitrate); } @@ -802,8 +762,7 @@ static void apply_video_encoder_settings(obs_data_t *settings, item = json_object_get(recommended, "x264opts"); if (json_is_string(item)) { const char *x264_settings = json_string_value(item); - const char *cur_settings = - obs_data_get_string(settings, "x264opts"); + const char *cur_settings = obs_data_get_string(settings, "x264opts"); struct dstr opts; dstr_init_copy(&opts, cur_settings); @@ -816,8 +775,7 @@ static void apply_video_encoder_settings(obs_data_t *settings, } } -static void apply_audio_encoder_settings(obs_data_t *settings, - json_t *recommended) +static void apply_audio_encoder_settings(obs_data_t *settings, json_t *recommended) { json_t *item = json_object_get(recommended, "max audio bitrate"); if (json_is_integer(item)) { @@ -827,8 +785,7 @@ static void apply_audio_encoder_settings(obs_data_t *settings, } } -static void initialize_output(struct rtmp_common *service, json_t *root, - obs_data_t *video_settings, +static void initialize_output(struct rtmp_common *service, json_t *root, obs_data_t *video_settings, obs_data_t *audio_settings) { json_t *json_service = find_service(root, service->service, NULL); @@ -853,15 +810,13 @@ static void initialize_output(struct rtmp_common *service, json_t *root, apply_audio_encoder_settings(audio_settings, recommended); } -static void rtmp_common_apply_settings(void *data, obs_data_t *video_settings, - obs_data_t *audio_settings) +static void rtmp_common_apply_settings(void *data, obs_data_t *video_settings, obs_data_t *audio_settings) { struct rtmp_common *service = data; json_t *root = open_services_file(); if (root) { - initialize_output(service, root, video_settings, - audio_settings); + initialize_output(service, root, video_settings, audio_settings); json_decref(root); } } @@ -885,8 +840,7 @@ static const char *rtmp_common_url(void *data) } if (service->service && strcmp(service->service, "Amazon IVS") == 0) { - if (service->server && - strncmp(service->server, "auto", 4) == 0) { + if (service->server && strncmp(service->server, "auto", 4) == 0) { struct ingest amazon_ivs_ing; bool rtmp = strcmp(service->server, "auto-rtmp") == 0; @@ -896,8 +850,7 @@ static const char *rtmp_common_url(void *data) amazon_ivs_ing = amazon_ivs_ingest(0); amazon_ivs_ingests_unlock(); - return rtmp ? amazon_ivs_ing.url - : amazon_ivs_ing.rtmps_url; + return rtmp ? amazon_ivs_ing.url : amazon_ivs_ing.rtmps_url; } } @@ -910,8 +863,7 @@ static const char *rtmp_common_url(void *data) if (service->service && strcmp(service->service, "SHOWROOM") == 0) { if (service->server && service->key) { struct showroom_ingest *ingest; - ingest = showroom_get_ingest(service->server, - service->key); + ingest = showroom_get_ingest(service->server, service->key); return ingest->url; } } @@ -934,8 +886,7 @@ static const char *rtmp_common_key(void *data) if (service->service && strcmp(service->service, "SHOWROOM") == 0) { if (service->server && service->key) { struct showroom_ingest *ingest; - ingest = showroom_get_ingest(service->server, - service->key); + ingest = showroom_get_ingest(service->server, service->key); return ingest->key; } } @@ -950,16 +901,14 @@ static const char *rtmp_common_key(void *data) return service->key; } -static void rtmp_common_get_supported_resolutions( - void *data, struct obs_service_resolution **resolutions, size_t *count) +static void rtmp_common_get_supported_resolutions(void *data, struct obs_service_resolution **resolutions, + size_t *count) { struct rtmp_common *service = data; if (service->supported_resolutions_count) { *count = service->supported_resolutions_count; - *resolutions = - bmemdup(service->supported_resolutions, - *count * sizeof(struct obs_service_resolution)); + *resolutions = bmemdup(service->supported_resolutions, *count * sizeof(struct obs_service_resolution)); } else { *count = 0; *resolutions = NULL; @@ -999,16 +948,14 @@ static int get_bitrate_matrix_max(json_t *array) if (c != 2) continue; - if ((int)ovi.output_width == cx && - (int)ovi.output_height == cy && cur_fps <= fps) + if ((int)ovi.output_width == cx && (int)ovi.output_height == cy && cur_fps <= fps) return bitrate; } return 0; } -static void rtmp_common_get_max_bitrate(void *data, int *video_bitrate, - int *audio_bitrate) +static void rtmp_common_get_max_bitrate(void *data, int *video_bitrate, int *audio_bitrate) { struct rtmp_common *service = data; json_t *root = open_services_file(); @@ -1040,8 +987,7 @@ static void rtmp_common_get_max_bitrate(void *data, int *video_bitrate, bitrate = get_bitrate_matrix_max(item); } if (!bitrate) { - item = json_object_get(recommended, - "max video bitrate"); + item = json_object_get(recommended, "max video bitrate"); if (json_is_integer(item)) bitrate = (int)json_integer_value(item); } @@ -1070,8 +1016,7 @@ static const char **rtmp_common_get_supported_video_codecs(void *data) goto fail; } - json_t *json_video_codecs = - json_object_get(json_service, "supported video codecs"); + json_t *json_video_codecs = json_object_get(json_service, "supported video codecs"); if (!json_is_array(json_video_codecs)) { goto fail; } @@ -1113,8 +1058,7 @@ static const char **rtmp_common_get_supported_audio_codecs(void *data) goto fail; } - json_t *json_audio_codecs = - json_object_get(json_service, "supported audio codecs"); + json_t *json_audio_codecs = json_object_get(json_service, "supported audio codecs"); if (!json_is_array(json_audio_codecs)) { goto fail; } @@ -1210,8 +1154,7 @@ static bool rtmp_common_can_try_to_connect(void *data) const char *url = rtmp_common_url(data); - return (url != NULL && url[0] != '\0') && - (key != NULL && key[0] != '\0'); + return (url != NULL && url[0] != '\0') && (key != NULL && key[0] != '\0'); } struct obs_service_info rtmp_common_service = { diff --git a/plugins/rtmp-services/rtmp-custom.c b/plugins/rtmp-services/rtmp-custom.c index 9c5b1c88d..984d862f8 100644 --- a/plugins/rtmp-services/rtmp-custom.c +++ b/plugins/rtmp-services/rtmp-custom.c @@ -49,8 +49,7 @@ static void *rtmp_custom_create(obs_data_t *settings, obs_service_t *service) return data; } -static bool use_auth_modified(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool use_auth_modified(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { bool use_auth = obs_data_get_bool(settings, "use_auth"); p = obs_properties_get(ppts, "username"); @@ -69,15 +68,11 @@ static obs_properties_t *rtmp_custom_properties(void *unused) obs_properties_add_text(ppts, "server", "URL", OBS_TEXT_DEFAULT); - obs_properties_add_text(ppts, "key", obs_module_text("StreamKey"), - OBS_TEXT_PASSWORD); + obs_properties_add_text(ppts, "key", obs_module_text("StreamKey"), OBS_TEXT_PASSWORD); - p = obs_properties_add_bool(ppts, "use_auth", - obs_module_text("UseAuth")); - obs_properties_add_text(ppts, "username", obs_module_text("Username"), - OBS_TEXT_DEFAULT); - obs_properties_add_text(ppts, "password", obs_module_text("Password"), - OBS_TEXT_PASSWORD); + p = obs_properties_add_bool(ppts, "use_auth", obs_module_text("UseAuth")); + obs_properties_add_text(ppts, "username", obs_module_text("Username"), OBS_TEXT_DEFAULT); + obs_properties_add_text(ppts, "password", obs_module_text("Password"), OBS_TEXT_PASSWORD); obs_property_set_modified_callback(p, use_auth_modified); return ppts; } @@ -130,8 +125,7 @@ static const char *rtmp_custom_get_protocol(void *data) return "RTMP"; } -static void rtmp_custom_apply_settings(void *data, obs_data_t *video_settings, - obs_data_t *audio_settings) +static void rtmp_custom_apply_settings(void *data, obs_data_t *video_settings, obs_data_t *audio_settings) { struct rtmp_custom *service = data; const char *protocol = rtmp_custom_get_protocol(service); diff --git a/plugins/rtmp-services/rtmp-services-main.c b/plugins/rtmp-services/rtmp-services-main.c index 815beae6a..f86cd05f5 100644 --- a/plugins/rtmp-services/rtmp-services-main.c +++ b/plugins/rtmp-services/rtmp-services-main.c @@ -101,23 +101,18 @@ bool obs_module_load(void) dstr_cat(&module_name, ")"); proc_handler_t *ph = obs_get_proc_handler(); - proc_handler_add(ph, "void twitch_ingests_refresh(int seconds)", - refresh_callback, NULL); - proc_handler_add(ph, "void amazon_ivs_ingests_refresh(int seconds)", - amazon_ivs_refresh_callback, NULL); + proc_handler_add(ph, "void twitch_ingests_refresh(int seconds)", refresh_callback, NULL); + proc_handler_add(ph, "void amazon_ivs_ingests_refresh(int seconds)", amazon_ivs_refresh_callback, NULL); #if defined(ENABLE_SERVICE_UPDATES) char *local_dir = obs_module_file(""); char *cache_dir = obs_module_config_path(""); char update_url[128]; - snprintf(update_url, sizeof(update_url), "%s/v%d", RTMP_SERVICES_URL, - RTMP_SERVICES_FORMAT_VERSION); + snprintf(update_url, sizeof(update_url), "%s/v%d", RTMP_SERVICES_URL, RTMP_SERVICES_FORMAT_VERSION); if (cache_dir) { - update_info = update_info_create(RTMP_SERVICES_LOG_STR, - module_name.array, update_url, - local_dir, cache_dir, - confirm_service_file, NULL); + update_info = update_info_create(RTMP_SERVICES_LOG_STR, module_name.array, update_url, local_dir, + cache_dir, confirm_service_file, NULL); } load_twitch_data(); diff --git a/plugins/rtmp-services/service-specific/amazon-ivs.c b/plugins/rtmp-services/service-specific/amazon-ivs.c index 5a021cbf4..b0b30747e 100644 --- a/plugins/rtmp-services/service-specific/amazon-ivs.c +++ b/plugins/rtmp-services/service-specific/amazon-ivs.c @@ -1,15 +1,14 @@ #include "service-ingest.h" #include "amazon-ivs.h" -static struct service_ingests amazon_ivs = { - .update_info = NULL, - .mutex = PTHREAD_MUTEX_INITIALIZER, - .ingests_refreshed = false, - .ingests_refreshing = false, - .ingests_loaded = false, - .cur_ingests = {0}, - .cache_old_filename = "amazon_ivs_ingests.json", - .cache_new_filename = "amazon_ivs_ingests.new.json"}; +static struct service_ingests amazon_ivs = {.update_info = NULL, + .mutex = PTHREAD_MUTEX_INITIALIZER, + .ingests_refreshed = false, + .ingests_refreshing = false, + .ingests_loaded = false, + .cur_ingests = {0}, + .cache_old_filename = "amazon_ivs_ingests.json", + .cache_new_filename = "amazon_ivs_ingests.new.json"}; void init_amazon_ivs_data(void) { @@ -18,10 +17,8 @@ void init_amazon_ivs_data(void) void load_amazon_ivs_data(void) { - struct ingest def = { - .name = bstrdup("Default"), - .url = bstrdup( - "rtmps://ingest.global-contribute.live-video.net:443/app/")}; + struct ingest def = {.name = bstrdup("Default"), + .url = bstrdup("rtmps://ingest.global-contribute.live-video.net:443/app/")}; load_service_data(&amazon_ivs, "amazon_ivs_ingests.json", &def); } @@ -32,9 +29,8 @@ void unload_amazon_ivs_data(void) void amazon_ivs_ingests_refresh(int seconds) { - service_ingests_refresh( - &amazon_ivs, seconds, "[amazon ivs ingest update] ", - "https://ingest.contribute.live-video.net/ingests"); + service_ingests_refresh(&amazon_ivs, seconds, "[amazon ivs ingest update] ", + "https://ingest.contribute.live-video.net/ingests"); } void amazon_ivs_ingests_lock(void) diff --git a/plugins/rtmp-services/service-specific/dacast.c b/plugins/rtmp-services/service-specific/dacast.c index 3f5e737e9..a51d61ea4 100644 --- a/plugins/rtmp-services/service-specific/dacast.c +++ b/plugins/rtmp-services/service-specific/dacast.c @@ -20,8 +20,7 @@ struct dacast_ingest_info { struct dacast_ingest ingest; }; -struct dacast_ingest dacast_invalid_ingest = {"rtmp://dacast", "", "", - "fake_key"}; +struct dacast_ingest dacast_invalid_ingest = {"rtmp://dacast", "", "", "fake_key"}; static DARRAY(struct dacast_ingest_info) cur_ingests; @@ -110,8 +109,7 @@ static bool dacast_ingest_update(void *param, struct file_download_data *data) bool success; pthread_mutex_lock(&mutex); - success = load_ingests((const char *)data->buffer.array, - (const char *)param); + success = load_ingests((const char *)data->buffer.array, (const char *)param); pthread_mutex_unlock(&mutex); if (success) { @@ -153,9 +151,8 @@ void dacast_ingests_load_data(const char *server, const char *key) dacast_update_info = NULL; } - dacast_update_info = update_info_create_single( - "[dacast ingest load data] ", get_module_name(), uri.array, - dacast_ingest_update, (void *)key); + dacast_update_info = update_info_create_single("[dacast ingest load data] ", get_module_name(), uri.array, + dacast_ingest_update, (void *)key); if (!os_atomic_load_bool(&ingests_loaded)) { for (int i = 0; i < TIMEOUT_SEC * 100; i++) { diff --git a/plugins/rtmp-services/service-specific/nimotv.c b/plugins/rtmp-services/service-specific/nimotv.c index 4e26ab888..2fc9c7778 100644 --- a/plugins/rtmp-services/service-specific/nimotv.c +++ b/plugins/rtmp-services/service-specific/nimotv.c @@ -14,8 +14,7 @@ struct nimotv_mem_struct { static char *current_ingest = NULL; static time_t last_time = -1; -static size_t nimotv_write_cb(void *contents, size_t size, size_t nmemb, - void *userp) +static size_t nimotv_write_cb(void *contents, size_t size, size_t nmemb, void *userp) { size_t realsize = size * nmemb; struct nimotv_mem_struct *mem = (struct nimotv_mem_struct *)userp; @@ -63,9 +62,7 @@ const char *nimotv_get_ingest(const char *key) time_t now = time(NULL); double diff = difftime(now, last_time); if (diff < 2) { - blog(LOG_INFO, - "nimotv_get_ingest: returning ingest from cache: %s", - current_ingest); + blog(LOG_INFO, "nimotv_get_ingest: returning ingest from cache: %s", current_ingest); return current_ingest; } } @@ -98,9 +95,7 @@ const char *nimotv_get_ingest(const char *key) dstr_free(&uri); if (res != CURLE_OK) { - blog(LOG_WARNING, - "nimotv_get_ingest: curl_easy_perform() failed: %s", - curl_easy_strerror(res)); + blog(LOG_WARNING, "nimotv_get_ingest: curl_easy_perform() failed: %s", curl_easy_strerror(res)); curl_easy_cleanup(curl_handle); free(chunk.memory); return NULL; @@ -108,9 +103,7 @@ const char *nimotv_get_ingest(const char *key) curl_easy_getinfo(curl_handle, CURLINFO_RESPONSE_CODE, &response_code); if (response_code != 200) { - blog(LOG_WARNING, - "nimotv_get_ingest: curl_easy_perform() returned code: %ld", - response_code); + blog(LOG_WARNING, "nimotv_get_ingest: curl_easy_perform() returned code: %ld", response_code); curl_easy_cleanup(curl_handle); free(chunk.memory); return NULL; @@ -119,8 +112,7 @@ const char *nimotv_get_ingest(const char *key) curl_easy_cleanup(curl_handle); if (chunk.size == 0) { - blog(LOG_WARNING, - "nimotv_get_ingest: curl_easy_perform() returned empty response"); + blog(LOG_WARNING, "nimotv_get_ingest: curl_easy_perform() returned empty response"); free(chunk.memory); return NULL; } @@ -133,8 +125,7 @@ const char *nimotv_get_ingest(const char *key) last_time = time(NULL); free(chunk.memory); - blog(LOG_INFO, "nimotv_get_ingest: returning ingest: %s", - current_ingest); + blog(LOG_INFO, "nimotv_get_ingest: returning ingest: %s", current_ingest); return current_ingest; } diff --git a/plugins/rtmp-services/service-specific/service-ingest.c b/plugins/rtmp-services/service-specific/service-ingest.c index b3d2bad2a..477af061a 100644 --- a/plugins/rtmp-services/service-specific/service-ingest.c +++ b/plugins/rtmp-services/service-specific/service-ingest.c @@ -24,8 +24,7 @@ static void free_ingests(struct service_ingests *si) da_free(si->cur_ingests); } -static bool load_ingests(struct service_ingests *si, const char *json, - bool write_file) +static bool load_ingests(struct service_ingests *si, const char *json, bool write_file) { json_t *root; json_t *ingests; @@ -52,8 +51,7 @@ static bool load_ingests(struct service_ingests *si, const char *json, json_t *item = json_array_get(ingests, i); json_t *item_name = json_object_get(item, "name"); json_t *item_url = json_object_get(item, "url_template"); - json_t *item_rtmps_url = - json_object_get(item, "url_template_secure"); + json_t *item_rtmps_url = json_object_get(item, "url_template_secure"); struct ingest ingest = {0}; struct dstr url = {0}; struct dstr rtmps_url = {0}; @@ -67,8 +65,7 @@ static bool load_ingests(struct service_ingests *si, const char *json, /* At the moment they currently mis-spell "deprecated", * but that may change in the future, so blacklist both */ - if (strstr(name_str, "deprecated") != NULL || - strstr(name_str, "depracated") != NULL) + if (strstr(name_str, "deprecated") != NULL || strstr(name_str, "depracated") != NULL) continue; dstr_copy(&url, url_str); @@ -124,8 +121,7 @@ static bool ingest_update(void *param, struct file_download_data *data) return true; } -void service_ingests_refresh(struct service_ingests *si, int seconds, - const char *log_prefix, const char *file_url) +void service_ingests_refresh(struct service_ingests *si, int seconds, const char *log_prefix, const char *file_url) { if (os_atomic_load_bool(&si->ingests_refreshed)) return; @@ -133,9 +129,7 @@ void service_ingests_refresh(struct service_ingests *si, int seconds, if (!os_atomic_load_bool(&si->ingests_refreshing)) { os_atomic_set_bool(&si->ingests_refreshing, true); - si->update_info = - update_info_create_single(log_prefix, get_module_name(), - file_url, ingest_update, si); + si->update_info = update_info_create_single(log_prefix, get_module_name(), file_url, ingest_update, si); } /* wait five seconds max when loading ingests for the first time */ @@ -149,8 +143,7 @@ void service_ingests_refresh(struct service_ingests *si, int seconds, } } -void load_service_data(struct service_ingests *si, const char *cache_filename, - struct ingest *def) +void load_service_data(struct service_ingests *si, const char *cache_filename, struct ingest *def) { char *service_cache = obs_module_config_path(cache_filename); diff --git a/plugins/rtmp-services/service-specific/service-ingest.h b/plugins/rtmp-services/service-specific/service-ingest.h index 95d47bc4a..512798165 100644 --- a/plugins/rtmp-services/service-specific/service-ingest.h +++ b/plugins/rtmp-services/service-specific/service-ingest.h @@ -24,9 +24,7 @@ struct service_ingests { }; void init_service_data(struct service_ingests *si); -void service_ingests_refresh(struct service_ingests *si, int seconds, - const char *log_prefix, const char *file_url); -void load_service_data(struct service_ingests *si, const char *cache_filename, - struct ingest *def); +void service_ingests_refresh(struct service_ingests *si, int seconds, const char *log_prefix, const char *file_url); +void load_service_data(struct service_ingests *si, const char *cache_filename, struct ingest *def); void unload_service_data(struct service_ingests *si); struct ingest get_ingest(struct service_ingests *si, size_t idx); diff --git a/plugins/rtmp-services/service-specific/showroom.c b/plugins/rtmp-services/service-specific/showroom.c index f10b5c9f2..361ba5d43 100644 --- a/plugins/rtmp-services/service-specific/showroom.c +++ b/plugins/rtmp-services/service-specific/showroom.c @@ -32,8 +32,7 @@ void free_showroom_data(void) da_free(cur_ingests); } -static size_t showroom_write_cb(void *data, size_t size, size_t nmemb, - void *user_pointer) +static size_t showroom_write_cb(void *data, size_t size, size_t nmemb, void *user_pointer) { struct dstr *json = user_pointer; size_t realsize = size * nmemb; @@ -59,8 +58,7 @@ static struct showroom_ingest_info *find_ingest(const char *access_key) #define SEC_TO_NSEC 1000000000ULL #endif -static struct showroom_ingest_info *get_ingest_from_json(char *str, - const char *access_key) +static struct showroom_ingest_info *get_ingest_from_json(char *str, const char *access_key) { json_error_t error; json_t *root; @@ -69,10 +67,8 @@ static struct showroom_ingest_info *get_ingest_from_json(char *str, return NULL; } - const char *url_str = - json_string_value(json_object_get(root, "streaming_url_rtmp")); - const char *key_str = - json_string_value(json_object_get(root, "streaming_key")); + const char *url_str = json_string_value(json_object_get(root, "streaming_url_rtmp")); + const char *key_str = json_string_value(json_object_get(root, "streaming_key")); struct showroom_ingest_info *info = find_ingest(access_key); if (!info) { @@ -90,8 +86,7 @@ static struct showroom_ingest_info *get_ingest_from_json(char *str, return info; } -struct showroom_ingest *showroom_get_ingest(const char *server, - const char *access_key) +struct showroom_ingest *showroom_get_ingest(const char *server, const char *access_key) { struct showroom_ingest_info *info = find_ingest(access_key); CURL *curl_handle; @@ -128,9 +123,7 @@ struct showroom_ingest *showroom_get_ingest(const char *server, res = curl_easy_perform(curl_handle); dstr_free(&uri); if (res != CURLE_OK) { - blog(LOG_WARNING, - "showroom_get_ingest: curl_easy_perform() failed: %s", - curl_easy_strerror(res)); + blog(LOG_WARNING, "showroom_get_ingest: curl_easy_perform() failed: %s", curl_easy_strerror(res)); goto cleanup; } @@ -144,9 +137,8 @@ struct showroom_ingest *showroom_get_ingest(const char *server, } if (json.len == 0) { - blog(LOG_WARNING, - "showroom_get_ingest: curl_easy_perform() returned " - "empty response"); + blog(LOG_WARNING, "showroom_get_ingest: curl_easy_perform() returned " + "empty response"); goto cleanup; } diff --git a/plugins/rtmp-services/service-specific/showroom.h b/plugins/rtmp-services/service-specific/showroom.h index f10ad1900..0312b39b7 100644 --- a/plugins/rtmp-services/service-specific/showroom.h +++ b/plugins/rtmp-services/service-specific/showroom.h @@ -5,7 +5,6 @@ struct showroom_ingest { const char *key; }; -extern struct showroom_ingest *showroom_get_ingest(const char *server, - const char *access_key); +extern struct showroom_ingest *showroom_get_ingest(const char *server, const char *access_key); extern void free_showroom_data(); diff --git a/plugins/rtmp-services/service-specific/twitch.c b/plugins/rtmp-services/service-specific/twitch.c index 6c11b112b..dbf28d325 100644 --- a/plugins/rtmp-services/service-specific/twitch.c +++ b/plugins/rtmp-services/service-specific/twitch.c @@ -1,15 +1,14 @@ #include "service-ingest.h" #include "twitch.h" -static struct service_ingests twitch = { - .update_info = NULL, - .mutex = PTHREAD_MUTEX_INITIALIZER, - .ingests_refreshed = false, - .ingests_refreshing = false, - .ingests_loaded = false, - .cur_ingests = {0}, - .cache_old_filename = "twitch_ingests.json", - .cache_new_filename = "twitch_ingests.new.json"}; +static struct service_ingests twitch = {.update_info = NULL, + .mutex = PTHREAD_MUTEX_INITIALIZER, + .ingests_refreshed = false, + .ingests_refreshing = false, + .ingests_loaded = false, + .cur_ingests = {0}, + .cache_old_filename = "twitch_ingests.json", + .cache_new_filename = "twitch_ingests.new.json"}; void twitch_ingests_lock(void) { @@ -38,14 +37,12 @@ void init_twitch_data(void) void twitch_ingests_refresh(int seconds) { - service_ingests_refresh(&twitch, seconds, "[twitch ingest update] ", - "https://ingest.twitch.tv/ingests"); + service_ingests_refresh(&twitch, seconds, "[twitch ingest update] ", "https://ingest.twitch.tv/ingests"); } void load_twitch_data(void) { - struct ingest def = {.name = bstrdup("Default"), - .url = bstrdup("rtmp://live.twitch.tv/app")}; + struct ingest def = {.name = bstrdup("Default"), .url = bstrdup("rtmp://live.twitch.tv/app")}; load_service_data(&twitch, "twitch_ingests.json", &def); } diff --git a/plugins/sndio/sndio-input.c b/plugins/sndio/sndio-input.c index f0adbf09d..da3724221 100644 --- a/plugins/sndio/sndio-input.c +++ b/plugins/sndio/sndio-input.c @@ -33,8 +33,7 @@ along with this program. If not, see . #include "sndio-input.h" -#define blog(level, msg, ...) \ - blog(level, "sndio-input: %s: " msg, __func__, ##__VA_ARGS__); +#define blog(level, msg, ...) blog(level, "sndio-input: %s: " msg, __func__, ##__VA_ARGS__); #define berr(level, msg, ...) \ do { \ @@ -109,8 +108,7 @@ static void *sndio_thread(void *attr) bufsz = thrdata->par.appbufsz * thrdata->par.bps * 2; if ((buf = bmalloc(bufsz * 2)) == NULL) { - blog(LOG_ERROR, "could not allocate record buffer of %zu bytes", - bufsz); + blog(LOG_ERROR, "could not allocate record buffer of %zu bytes", bufsz); goto finish; } @@ -130,24 +128,20 @@ static void *sndio_thread(void *attr) } if ((pfd[0].revents & POLLHUP) == POLLHUP) { - blog(LOG_INFO, - "exiting upon receiving EOF at IPC socket"); + blog(LOG_INFO, "exiting upon receiving EOF at IPC socket"); goto finish; } if ((pfd[0].revents & POLLIN) == POLLIN) { - nread = read(pfd[0].fd, ((uint8_t *)&par) + msgread, - sizeof(par) - msgread); + nread = read(pfd[0].fd, ((uint8_t *)&par) + msgread, sizeof(par) - msgread); switch (nread) { case -1: if (errno == EAGAIN) goto proceed_sio; - berr(LOG_ERROR, - "reading from IPC socket failed"); + berr(LOG_ERROR, "reading from IPC socket failed"); goto finish; case 0: - blog(LOG_INFO, - "exiting upon receiving EOF at IPC socket"); + blog(LOG_INFO, "exiting upon receiving EOF at IPC socket"); goto finish; default: @@ -159,21 +153,14 @@ static void *sndio_thread(void *attr) msgread = 0; sio_stop(thrdata->hdl); if (!sio_setpar(thrdata->hdl, &par)) { - blog(LOG_WARNING, - "sio_setpar failed, keeping old params"); + blog(LOG_WARNING, "sio_setpar failed, keeping old params"); } - blog(LOG_INFO, - "after sio_setpar(): appbufsz=%u bps=%u", - par.appbufsz, par.bps); - memcpy(&thrdata->par, &par, - sizeof(struct sio_par)); + blog(LOG_INFO, "after sio_setpar(): appbufsz=%u bps=%u", par.appbufsz, par.bps); + memcpy(&thrdata->par, &par, sizeof(struct sio_par)); - tbufsz = thrdata->par.appbufsz * - thrdata->par.bps * 2; - if ((tbuf = brealloc(buf, tbufsz)) == - NULL) { - blog(LOG_ERROR, - "could not reallocate record buffer of %zu bytes", + tbufsz = thrdata->par.appbufsz * thrdata->par.bps * 2; + if ((tbuf = brealloc(buf, tbufsz)) == NULL) { + blog(LOG_ERROR, "could not reallocate record buffer of %zu bytes", tbufsz); goto finish; } @@ -181,8 +168,7 @@ static void *sndio_thread(void *attr) bufsz = tbufsz; if (!sio_start(thrdata->hdl)) { - blog(LOG_ERROR, - "sio_start failed, exiting"); + blog(LOG_ERROR, "sio_start failed, exiting"); goto finish; } ts = os_gettime_ns(); @@ -206,8 +192,7 @@ static void *sndio_thread(void *attr) nread = (ssize_t)sio_read(thrdata->hdl, buf, bufsz); if (nread == 0) { if (sio_eof(thrdata->hdl)) { - blog(LOG_ERROR, - "sndio device EOF happened, exiting"); + blog(LOG_ERROR, "sndio device EOF happened, exiting"); goto finish; } continue; @@ -219,13 +204,11 @@ static void *sndio_thread(void *attr) out.data[0] = buf; out.frames = nframes; out.format = sndio_to_obs_audio_format(&thrdata->par); - out.speakers = sndio_channels_to_obs_speakers( - thrdata->par.rchan); + out.speakers = sndio_channels_to_obs_speakers(thrdata->par.rchan); out.samples_per_sec = thrdata->par.rate; out.timestamp = ts; - ts += util_mul_div64(nframes, NSEC_PER_SEC, - thrdata->par.rate); + ts += util_mul_div64(nframes, NSEC_PER_SEC, thrdata->par.rate); obs_source_output_audio(thrdata->source, &out); } @@ -271,8 +254,7 @@ static void sndio_apply(struct sndio_data *data, obs_data_t *settings) blog(LOG_ERROR, "malloc"); return; } - if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, - socks) == -1) { + if (socketpair(AF_UNIX, SOCK_STREAM | SOCK_NONBLOCK | SOCK_CLOEXEC, 0, socks) == -1) { berr(LOG_ERROR, "socketpair"); goto error; } @@ -298,16 +280,13 @@ static void sndio_apply(struct sndio_data *data, obs_data_t *settings) thrdata->par.rchan = obs_data_get_int(settings, "channels"); thrdata->par.xrun = SIO_SYNC; // makes timestamping easy if (!sio_setpar(thrdata->hdl, &thrdata->par)) { - berr(LOG_ERROR, "could not set parameters for %s sndio device", - devname); + berr(LOG_ERROR, "could not set parameters for %s sndio device", devname); goto error; } - blog(LOG_INFO, "after initial sio_setpar(): appbufsz=%u bps=%u", - thrdata->par.appbufsz, thrdata->par.bps); + blog(LOG_INFO, "after initial sio_setpar(): appbufsz=%u bps=%u", thrdata->par.appbufsz, thrdata->par.bps); if (!sio_start(thrdata->hdl)) { - berr(LOG_ERROR, "could not start recording on %s sndio device", - devname); + berr(LOG_ERROR, "could not start recording on %s sndio device", devname); goto error; } @@ -372,11 +351,9 @@ static obs_properties_t *sndio_input_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_properties_add_text(props, "device", obs_module_text("Device"), - OBS_TEXT_DEFAULT); + obs_properties_add_text(props, "device", obs_module_text("Device"), OBS_TEXT_DEFAULT); - rate = obs_properties_add_list(props, "rate", obs_module_text("Rate"), - OBS_COMBO_TYPE_LIST, + rate = obs_properties_add_list(props, "rate", obs_module_text("Rate"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(rate, "11025 Hz", 11025); obs_property_list_add_int(rate, "22050 Hz", 22050); @@ -386,16 +363,13 @@ static obs_properties_t *sndio_input_properties(void *unused) obs_property_list_add_int(rate, "96000 Hz", 96000); obs_property_list_add_int(rate, "192000 Hz", 192000); - bits = obs_properties_add_list(props, "bits", - obs_module_text("BitsPerSample"), - OBS_COMBO_TYPE_LIST, + bits = obs_properties_add_list(props, "bits", obs_module_text("BitsPerSample"), OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(bits, "8", 8); obs_property_list_add_int(bits, "16", 16); obs_property_list_add_int(bits, "32", 32); - obs_properties_add_int(props, "channels", obs_module_text("Channels"), - 1, 8, 1); + obs_properties_add_int(props, "channels", obs_module_text("Channels"), 1, 8, 1); return props; } diff --git a/plugins/text-freetype2/find-font-iconv.c b/plugins/text-freetype2/find-font-iconv.c index 2265432c1..6d68ae3c9 100644 --- a/plugins/text-freetype2/find-font-iconv.c +++ b/plugins/text-freetype2/find-font-iconv.c @@ -34,18 +34,14 @@ static const struct mac_font_mapping mac_codes[] = { {TT_MAC_ID_DEVANAGARI, TT_MAC_LANGID_ANY, "x-mac-devanagari"}, {TT_MAC_ID_GURMUKHI, TT_MAC_LANGID_ANY, "x-mac-gurmukhi"}, {TT_MAC_ID_GUJARATI, TT_MAC_LANGID_ANY, "x-mac-gujarati"}, - {TT_MAC_ID_TRADITIONAL_CHINESE, TT_MAC_LANGID_CHINESE_SIMPLIFIED, - "Big5"}, + {TT_MAC_ID_TRADITIONAL_CHINESE, TT_MAC_LANGID_CHINESE_SIMPLIFIED, "Big5"}, {TT_MAC_ID_TRADITIONAL_CHINESE, TT_MAC_LANGID_ANY, "Big5"}, - {TT_MAC_ID_SIMPLIFIED_CHINESE, TT_MAC_LANGID_CHINESE_SIMPLIFIED, - "GB2312"}, + {TT_MAC_ID_SIMPLIFIED_CHINESE, TT_MAC_LANGID_CHINESE_SIMPLIFIED, "GB2312"}, {TT_MAC_ID_SIMPLIFIED_CHINESE, TT_MAC_LANGID_ANY, "GB2312"}}; const char *iso_codes[] = {"us-ascii", NULL, "iso-8859-1"}; -const char *ms_codes[] = {"UTF-16BE", "UTF-16BE", "Shift_JIS", NULL, - "Big5", NULL, NULL, NULL, - NULL, NULL, "UTF-16BE"}; +const char *ms_codes[] = {"UTF-16BE", "UTF-16BE", "Shift_JIS", NULL, "Big5", NULL, NULL, NULL, NULL, NULL, "UTF-16BE"}; static const size_t mac_code_count = sizeof(mac_codes) / sizeof(mac_codes[0]); static const size_t iso_code_count = sizeof(iso_codes) / sizeof(iso_codes[0]); @@ -56,17 +52,14 @@ static const char *get_mac_code(uint16_t encoding_id, uint16_t language_id) for (size_t i = 0; i < mac_code_count; i++) { const struct mac_font_mapping *mac_code = &mac_codes[i]; - if (mac_code->encoding_id == encoding_id && - mac_code->language_id == language_id) + if (mac_code->encoding_id == encoding_id && mac_code->language_id == language_id) return mac_code->code_page; } return NULL; } -static const char *get_code_page_for_font(uint16_t platform_id, - uint16_t encoding_id, - uint16_t language_id) +static const char *get_code_page_for_font(uint16_t platform_id, uint16_t encoding_id, uint16_t language_id) { const char *ret; @@ -93,9 +86,8 @@ static const char *get_code_page_for_font(uint16_t platform_id, char *sfnt_name_to_utf8(FT_SfntName *sfnt_name) { - const char *charset = get_code_page_for_font(sfnt_name->platform_id, - sfnt_name->encoding_id, - sfnt_name->language_id); + const char *charset = + get_code_page_for_font(sfnt_name->platform_id, sfnt_name->encoding_id, sfnt_name->language_id); char utf8[256]; char *conv_in, *conv_out; size_t in_len, out_len; @@ -105,8 +97,7 @@ char *sfnt_name_to_utf8(FT_SfntName *sfnt_name) "invalid character set found, " "platform_id: %d, encoding_id: %d, " "language_id: %d", - sfnt_name->platform_id, sfnt_name->encoding_id, - sfnt_name->language_id); + sfnt_name->platform_id, sfnt_name->encoding_id, sfnt_name->language_id); return NULL; } @@ -126,8 +117,7 @@ char *sfnt_name_to_utf8(FT_SfntName *sfnt_name) size_t n = iconv(ic, &conv_in, &in_len, &conv_out, &out_len); if (n == (size_t)-1) { - blog(LOG_WARNING, "couldn't convert font name text: errno = %d", - (int)errno); + blog(LOG_WARNING, "couldn't convert font name text: errno = %d", (int)errno); iconv_close(ic); return NULL; } diff --git a/plugins/text-freetype2/find-font-unix.c b/plugins/text-freetype2/find-font-unix.c index 668aa5d2c..cbf588574 100644 --- a/plugins/text-freetype2/find-font-unix.c +++ b/plugins/text-freetype2/find-font-unix.c @@ -31,8 +31,7 @@ bool load_cached_os_font_list(void) void load_os_font_list(void) {} -const char *get_font_path(const char *family, uint16_t size, const char *style, - uint32_t flags, FT_Long *idx) +const char *get_font_path(const char *family, uint16_t size, const char *style, uint32_t flags, FT_Long *idx) { bool bold = !!(flags & OBS_FONT_BOLD); bool italic = !!(flags & OBS_FONT_ITALIC); @@ -46,10 +45,8 @@ const char *get_font_path(const char *family, uint16_t size, const char *style, FcPatternAddString(pattern, FC_FAMILY, (const FcChar8 *)family); FcPatternAddString(pattern, FC_STYLE, (const FcChar8 *)style); - FcPatternAddInteger(pattern, FC_WEIGHT, - bold ? FC_WEIGHT_BOLD : FC_WEIGHT_REGULAR); - FcPatternAddInteger(pattern, FC_SLANT, - italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN); + FcPatternAddInteger(pattern, FC_WEIGHT, bold ? FC_WEIGHT_BOLD : FC_WEIGHT_REGULAR); + FcPatternAddInteger(pattern, FC_SLANT, italic ? FC_SLANT_ITALIC : FC_SLANT_ROMAN); FcPatternAddDouble(pattern, FC_SIZE, (double)size); FcConfigSubstitute(NULL, pattern, FcMatchPattern); @@ -57,8 +54,7 @@ const char *get_font_path(const char *family, uint16_t size, const char *style, match = FcFontMatch(NULL, pattern, &match_result); if (match) { - FcChar8 *path = - FcPatternFormat(match, (const FcChar8 *)"%{file}"); + FcChar8 *path = FcPatternFormat(match, (const FcChar8 *)"%{file}"); strncpy(result, (char *)path, 511); FcStrFree(path); diff --git a/plugins/text-freetype2/find-font-windows.c b/plugins/text-freetype2/find-font-windows.c index 71fe6b43b..6c9fcd297 100644 --- a/plugins/text-freetype2/find-font-windows.c +++ b/plugins/text-freetype2/find-font-windows.c @@ -62,17 +62,14 @@ static unsigned int get_mac_code(uint16_t encoding_id, uint16_t language_id) for (size_t i = 0; i < mac_code_count; i++) { const struct mac_font_mapping *mac_code = &mac_codes[i]; - if (mac_code->encoding_id == encoding_id && - mac_code->language_id == language_id) + if (mac_code->encoding_id == encoding_id && mac_code->language_id == language_id) return mac_code->code_page; } return 0; } -static unsigned int get_code_page_for_font(uint16_t platform_id, - uint16_t encoding_id, - uint16_t language_id) +static unsigned int get_code_page_for_font(uint16_t platform_id, uint16_t encoding_id, uint16_t language_id) { unsigned int ret; @@ -102,13 +99,10 @@ static char *wide_to_utf8(const wchar_t *str, size_t len) size_t utf8_len; char *utf8_str = NULL; - utf8_len = (size_t)WideCharToMultiByte(CP_UTF8, 0, str, (int)len, NULL, - 0, NULL, false); + utf8_len = (size_t)WideCharToMultiByte(CP_UTF8, 0, str, (int)len, NULL, 0, NULL, false); if (utf8_len) { utf8_str = bzalloc(utf8_len + 1); - utf8_len = (size_t)WideCharToMultiByte(CP_UTF8, 0, str, - (int)len, utf8_str, - (int)utf8_len + 1, NULL, + utf8_len = (size_t)WideCharToMultiByte(CP_UTF8, 0, str, (int)len, utf8_str, (int)utf8_len + 1, NULL, false); if (!utf8_len) { @@ -144,9 +138,8 @@ static char *convert_utf16_be_to_utf8(FT_SfntName *sfnt_name) char *sfnt_name_to_utf8(FT_SfntName *sfnt_name) { - unsigned int code_page = get_code_page_for_font(sfnt_name->platform_id, - sfnt_name->encoding_id, - sfnt_name->language_id); + unsigned int code_page = + get_code_page_for_font(sfnt_name->platform_id, sfnt_name->encoding_id, sfnt_name->language_id); char *utf8_str = NULL; wchar_t *utf16_str; @@ -157,13 +150,10 @@ char *sfnt_name_to_utf8(FT_SfntName *sfnt_name) else if (code_page == 0) return NULL; - utf16_len = MultiByteToWideChar(code_page, 0, (char *)sfnt_name->string, - sfnt_name->string_len, NULL, 0); + utf16_len = MultiByteToWideChar(code_page, 0, (char *)sfnt_name->string, sfnt_name->string_len, NULL, 0); if (utf16_len) { utf16_str = malloc((utf16_len + 1) * sizeof(wchar_t)); - utf16_len = MultiByteToWideChar(code_page, 0, - (char *)sfnt_name->string, - sfnt_name->string_len, + utf16_len = MultiByteToWideChar(code_page, 0, (char *)sfnt_name->string, sfnt_name->string_len, utf16_str, (int)utf16_len); if (utf16_len) { @@ -186,8 +176,7 @@ uint32_t get_font_checksum(void) dstr_reserve(&path, MAX_PATH); - HRESULT res = SHGetFolderPathA(NULL, CSIDL_FONTS, NULL, - SHGFP_TYPE_CURRENT, path.array); + HRESULT res = SHGetFolderPathA(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, path.array); if (res != S_OK) { blog(LOG_WARNING, "Error finding windows font folder"); return 0; @@ -203,10 +192,8 @@ uint32_t get_font_checksum(void) dstr_resize(&path, path.len - 4); do { - checksum = calc_crc32(checksum, &wfd.ftLastWriteTime, - sizeof(FILETIME)); - checksum = calc_crc32(checksum, wfd.cFileName, - strlen(wfd.cFileName)); + checksum = calc_crc32(checksum, &wfd.ftLastWriteTime, sizeof(FILETIME)); + checksum = calc_crc32(checksum, wfd.cFileName, strlen(wfd.cFileName)); } while (FindNextFileA(handle, &wfd)); FindClose(handle); @@ -224,8 +211,7 @@ void load_os_font_list(void) dstr_reserve(&path, MAX_PATH); - HRESULT res = SHGetFolderPathA(NULL, CSIDL_FONTS, NULL, - SHGFP_TYPE_CURRENT, path.array); + HRESULT res = SHGetFolderPathA(NULL, CSIDL_FONTS, NULL, SHGFP_TYPE_CURRENT, path.array); if (res != S_OK) { blog(LOG_WARNING, "Error finding windows font folder"); return; @@ -254,8 +240,7 @@ void load_os_font_list(void) dstr_cat(&full_path, wfd.cFileName); while (idx < max_faces) { - FT_Error ret = FT_New_Face(ft2_lib, full_path.array, - idx, &face); + FT_Error ret = FT_New_Face(ft2_lib, full_path.array, idx, &face); if (ret != 0) break; diff --git a/plugins/text-freetype2/find-font.c b/plugins/text-freetype2/find-font.c index 065649668..79312528a 100644 --- a/plugins/text-freetype2/find-font.c +++ b/plugins/text-freetype2/find-font.c @@ -11,8 +11,7 @@ static inline bool read_data(struct serializer *s, void *data, size_t size) return s_read(s, data, size) == size; } -static inline bool write_data(struct serializer *s, const void *data, - size_t size) +static inline bool write_data(struct serializer *s, const void *data, size_t size) { return s_write(s, data, size) == size; } @@ -81,8 +80,7 @@ static bool load_cached_font_list(struct serializer *s) if (info->num_sizes) { info->sizes = bmalloc(sizeof(int) * info->num_sizes); - success = read_data(s, info->sizes, - sizeof(int) * info->num_sizes); + success = read_data(s, info->sizes, sizeof(int) * info->num_sizes); if (!success) break; } @@ -156,8 +154,7 @@ void save_font_list(void) bool success = false; if (font_checksum) - success = - file_output_serializer_init_safe(&s, file_name, "tmp"); + success = file_output_serializer_init_safe(&s, file_name, "tmp"); bfree(file_name); if (!success) @@ -191,8 +188,7 @@ void save_font_list(void) do_write(info->num_sizes); if (info->num_sizes) { - success = write_data(&s, info->sizes, - sizeof(int) * info->num_sizes); + success = write_data(&s, info->sizes, sizeof(int) * info->num_sizes); if (!success) break; } @@ -234,8 +230,7 @@ static void create_bitmap_sizes(struct font_path_info *info, FT_Face face) info->num_sizes = (uint32_t)face->num_fixed_sizes; } -static void add_font_path(FT_Face face, FT_Long idx, const char *family_in, - const char *style_in, const char *path) +static void add_font_path(FT_Face face, FT_Long idx, const char *family_in, const char *style_in, const char *path) { struct dstr face_and_style = {0}; struct font_path_info info; @@ -314,8 +309,7 @@ void build_font_path_info(FT_Face face, FT_Long idx, const char *path) } for (size_t i = 0; i < family_names.num; i++) { - add_font_path(face, idx, family_names.array[i], - face->style_name, path); + add_font_path(face, idx, family_names.array[i], face->style_name, path); /* first item isn't our allocation */ if (i > 0) @@ -351,8 +345,7 @@ static inline size_t get_rating(struct font_path_info *info, struct dstr *cmp) return num; } -const char *get_font_path(const char *family, uint16_t size, const char *style, - uint32_t flags, FT_Long *idx) +const char *get_font_path(const char *family, uint16_t size, const char *style, uint32_t flags, FT_Long *idx) { const char *best_path = NULL; double best_rating = 0.0; diff --git a/plugins/text-freetype2/find-font.h b/plugins/text-freetype2/find-font.h index 3b4eba208..4af959fc5 100644 --- a/plugins/text-freetype2/find-font.h +++ b/plugins/text-freetype2/find-font.h @@ -38,6 +38,4 @@ extern char *sfnt_name_to_utf8(FT_SfntName *sfnt_name); extern bool load_cached_os_font_list(void); extern void load_os_font_list(void); extern void free_os_font_list(void); -extern const char *get_font_path(const char *family, uint16_t size, - const char *style, uint32_t flags, - FT_Long *idx); +extern const char *get_font_path(const char *family, uint16_t size, const char *style, uint32_t flags, FT_Long *idx); diff --git a/plugins/text-freetype2/obs-convenience.c b/plugins/text-freetype2/obs-convenience.c index 38a842d76..ee95c1c41 100644 --- a/plugins/text-freetype2/obs-convenience.c +++ b/plugins/text-freetype2/obs-convenience.c @@ -32,13 +32,11 @@ gs_vertbuffer_t *create_uv_vbuffer(uint32_t num_verts, bool add_color) vrect->num = num_verts; vrect->points = (struct vec3 *)bmalloc(sizeof(struct vec3) * num_verts); vrect->num_tex = 1; - vrect->tvarray = - (struct gs_tvertarray *)bmalloc(sizeof(struct gs_tvertarray)); + vrect->tvarray = (struct gs_tvertarray *)bmalloc(sizeof(struct gs_tvertarray)); vrect->tvarray[0].width = 2; vrect->tvarray[0].array = bmalloc(sizeof(struct vec2) * num_verts); if (add_color) - vrect->colors = - (uint32_t *)bmalloc(sizeof(uint32_t) * num_verts); + vrect->colors = (uint32_t *)bmalloc(sizeof(uint32_t) * num_verts); memset(vrect->points, 0, sizeof(struct vec3) * num_verts); memset(vrect->tvarray[0].array, 0, sizeof(struct vec2) * num_verts); @@ -56,8 +54,7 @@ gs_vertbuffer_t *create_uv_vbuffer(uint32_t num_verts, bool add_color) return tmp; } -void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex, - gs_effect_t *effect, uint32_t num_verts, bool use_color) +void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex, gs_effect_t *effect, uint32_t num_verts, bool use_color) { gs_texture_t *texture = tex; gs_technique_t *tech = gs_effect_get_technique(effect, "Draw"); @@ -84,9 +81,7 @@ void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex, else gs_effect_set_texture(image, texture); - gs_effect_set_bool(gs_effect_get_param_by_name( - effect, "use_color"), - use_color); + gs_effect_set_bool(gs_effect_get_param_by_name(effect, "use_color"), use_color); gs_draw(GS_TRIS, 0, num_verts); diff --git a/plugins/text-freetype2/obs-convenience.h b/plugins/text-freetype2/obs-convenience.h index ebcffafc0..6786cb8de 100644 --- a/plugins/text-freetype2/obs-convenience.h +++ b/plugins/text-freetype2/obs-convenience.h @@ -20,8 +20,7 @@ along with this program. If not, see . #include gs_vertbuffer_t *create_uv_vbuffer(uint32_t num_verts, bool add_color); -void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex, - gs_effect_t *effect, uint32_t num_verts, bool use_color); +void draw_uv_vbuffer(gs_vertbuffer_t *vbuf, gs_texture_t *tex, gs_effect_t *effect, uint32_t num_verts, bool use_color); #define set_v3_rect(a, x, y, w, h) \ vec3_set(a, x, y, 0.0f); \ diff --git a/plugins/text-freetype2/text-freetype2.c b/plugins/text-freetype2/text-freetype2.c index ac97c6cc6..0e92bf0ea 100644 --- a/plugins/text-freetype2/text-freetype2.c +++ b/plugins/text-freetype2/text-freetype2.c @@ -53,8 +53,7 @@ static obs_properties_t *ft2_source_properties(void *unused); static struct obs_source_info freetype2_source_info_v1 = { .id = "text_ft2_source", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CAP_OBSOLETE | - OBS_SOURCE_CUSTOM_DRAW, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CAP_OBSOLETE | OBS_SOURCE_CUSTOM_DRAW, .get_name = ft2_source_get_name, .create = ft2_source_create, .destroy = ft2_source_destroy, @@ -153,8 +152,7 @@ static uint32_t ft2_source_get_height(void *data) return srcdata->cy + srcdata->outline_width; } -static bool from_file_modified(obs_properties_t *props, obs_property_t *prop, - obs_data_t *settings) +static bool from_file_modified(obs_properties_t *props, obs_property_t *prop, obs_data_t *settings) { UNUSED_PARAMETER(prop); @@ -184,49 +182,35 @@ static obs_properties_t *ft2_source_properties(void *unused) obs_properties_add_font(props, "font", obs_module_text("Font")); - obs_property_t *from_file = obs_properties_add_list( - props, "from_file", obs_module_text("TextInputMode"), - OBS_COMBO_TYPE_RADIO, OBS_COMBO_FORMAT_BOOL); - obs_property_list_add_bool( - from_file, obs_module_text("TextInputMode.Manual"), false); - obs_property_list_add_bool( - from_file, obs_module_text("TextInputMode.FromFile"), true); + obs_property_t *from_file = obs_properties_add_list(props, "from_file", obs_module_text("TextInputMode"), + OBS_COMBO_TYPE_RADIO, OBS_COMBO_FORMAT_BOOL); + obs_property_list_add_bool(from_file, obs_module_text("TextInputMode.Manual"), false); + obs_property_list_add_bool(from_file, obs_module_text("TextInputMode.FromFile"), true); obs_property_set_modified_callback(from_file, from_file_modified); - obs_property_t *text_file = obs_properties_add_path( - props, "text_file", obs_module_text("TextFile"), OBS_PATH_FILE, - obs_module_text("TextFileFilter"), NULL); - obs_property_set_long_description(text_file, - obs_module_text("TextFile.Encoding")); + obs_property_t *text_file = obs_properties_add_path(props, "text_file", obs_module_text("TextFile"), + OBS_PATH_FILE, obs_module_text("TextFileFilter"), NULL); + obs_property_set_long_description(text_file, obs_module_text("TextFile.Encoding")); - obs_properties_add_text(props, "text", obs_module_text("Text"), - OBS_TEXT_MULTILINE); + obs_properties_add_text(props, "text", obs_module_text("Text"), OBS_TEXT_MULTILINE); - obs_properties_add_bool(props, "antialiasing", - obs_module_text("Antialiasing")); + obs_properties_add_bool(props, "antialiasing", obs_module_text("Antialiasing")); - obs_properties_add_bool(props, "log_mode", - obs_module_text("ChatLogMode")); + obs_properties_add_bool(props, "log_mode", obs_module_text("ChatLogMode")); - obs_properties_add_int(props, "log_lines", - obs_module_text("ChatLogLines"), 1, 1000, 1); + obs_properties_add_int(props, "log_lines", obs_module_text("ChatLogLines"), 1, 1000, 1); - obs_properties_add_color_alpha(props, "color1", - obs_module_text("Color1")); + obs_properties_add_color_alpha(props, "color1", obs_module_text("Color1")); - obs_properties_add_color_alpha(props, "color2", - obs_module_text("Color2")); + obs_properties_add_color_alpha(props, "color2", obs_module_text("Color2")); obs_properties_add_bool(props, "outline", obs_module_text("Outline")); - obs_properties_add_bool(props, "drop_shadow", - obs_module_text("DropShadow")); + obs_properties_add_bool(props, "drop_shadow", obs_module_text("DropShadow")); - obs_properties_add_int(props, "custom_width", - obs_module_text("CustomWidth"), 0, 4096, 1); + obs_properties_add_int(props, "custom_width", obs_module_text("CustomWidth"), 0, 4096, 1); - obs_properties_add_bool(props, "word_wrap", - obs_module_text("WordWrap")); + obs_properties_add_bool(props, "word_wrap", obs_module_text("WordWrap")); return props; } @@ -295,8 +279,7 @@ static void ft2_source_render(void *data, gs_effect_t *effect) if (srcdata->drop_shadow) draw_drop_shadow(srcdata); - draw_uv_vbuffer(srcdata->vbuf, srcdata->tex, srcdata->draw_effect, - (uint32_t)wcslen(srcdata->text) * 6, true); + draw_uv_vbuffer(srcdata->vbuf, srcdata->tex, srcdata->draw_effect, (uint32_t)wcslen(srcdata->text) * 6, true); UNUSED_PARAMETER(effect); } @@ -317,8 +300,7 @@ static void ft2_video_tick(void *data, float seconds) if (srcdata->log_mode) read_from_end(srcdata, srcdata->text_file); else - load_text_from_file(srcdata, - srcdata->text_file); + load_text_from_file(srcdata, srcdata->text_file); cache_glyphs(srcdata, srcdata->text); set_up_vertex_buffer(srcdata); srcdata->update_file = false; @@ -336,9 +318,8 @@ static void ft2_video_tick(void *data, float seconds) static bool init_font(struct ft2_source *srcdata) { FT_Long index; - const char *path = get_font_path(srcdata->font_name, srcdata->font_size, - srcdata->font_style, - srcdata->font_flags, &index); + const char *path = + get_font_path(srcdata->font_name, srcdata->font_size, srcdata->font_style, srcdata->font_flags, &index); if (!path) return false; @@ -431,8 +412,7 @@ static void ft2_source_update(void *data, obs_data_t *settings) if (effect_file) { obs_enter_graphics(); - srcdata->draw_effect = gs_effect_create_from_file( - effect_file, &error_string); + srcdata->draw_effect = gs_effect_create_from_file(effect_file, &error_string); obs_leave_graphics(); bfree(effect_file); @@ -458,10 +438,8 @@ static void ft2_source_update(void *data, obs_data_t *settings) srcdata->from_file = from_file; if (srcdata->font_name != NULL) { - if (strcmp(font_name, srcdata->font_name) == 0 && - strcmp(font_style, srcdata->font_style) == 0 && - font_flags == srcdata->font_flags && - font_size == srcdata->font_size) + if (strcmp(font_name, srcdata->font_name) == 0 && strcmp(font_style, srcdata->font_style) == 0 && + font_flags == srcdata->font_flags && font_size == srcdata->font_size) goto skip_font_load; bfree(srcdata->font_name); @@ -478,8 +456,7 @@ static void ft2_source_update(void *data, obs_data_t *settings) srcdata->font_flags = font_flags; if (!init_font(srcdata) || srcdata->font_face == NULL) { - blog(LOG_WARNING, "FT2-text: Failed to load font %s", - srcdata->font_name); + blog(LOG_WARNING, "FT2-text: Failed to load font %s", srcdata->font_name); goto error; } else { FT_Set_Pixel_Sizes(srcdata->font_face, 0, srcdata->font_size); @@ -505,16 +482,13 @@ skip_font_load: bfree(srcdata->text); srcdata->text = NULL; - os_utf8_to_wcs_ptr(emptystr, strlen(emptystr), - &srcdata->text); + os_utf8_to_wcs_ptr(emptystr, strlen(emptystr), &srcdata->text); blog(LOG_WARNING, "FT2-text: Failed to open %s for " "reading", tmp); } else { - if (srcdata->text_file != NULL && - strcmp(srcdata->text_file, tmp) == 0 && - !vbuf_needs_update) + if (srcdata->text_file != NULL && strcmp(srcdata->text_file, tmp) == 0 && !vbuf_needs_update) goto error; bfree(srcdata->text_file); @@ -596,9 +570,8 @@ static obs_missing_files_t *ft2_missing_files(void *data) if (read && strcmp(path, "") != 0) { if (!os_file_exists(path)) { - obs_missing_file_t *file = obs_missing_file_create( - path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, s->src, NULL); + obs_missing_file_t *file = obs_missing_file_create(path, missing_file_callback, + OBS_MISSING_FILE_SOURCE, s->src, NULL); obs_missing_files_add_file(files, file); } diff --git a/plugins/text-freetype2/text-functionality.c b/plugins/text-freetype2/text-functionality.c index 08eb96e72..7e031e5ad 100644 --- a/plugins/text-freetype2/text-functionality.c +++ b/plugins/text-freetype2/text-functionality.c @@ -35,11 +35,9 @@ void draw_outlines(struct ft2_source *srcdata) gs_matrix_push(); for (int32_t i = 0; i < 8; i++) { - gs_matrix_translate3f(offsets[i * 2], offsets[(i * 2) + 1], - 0.0f); - draw_uv_vbuffer(srcdata->vbuf, srcdata->tex, - srcdata->draw_effect, - (uint32_t)wcslen(srcdata->text) * 6, false); + gs_matrix_translate3f(offsets[i * 2], offsets[(i * 2) + 1], 0.0f); + draw_uv_vbuffer(srcdata->vbuf, srcdata->tex, srcdata->draw_effect, (uint32_t)wcslen(srcdata->text) * 6, + false); } gs_matrix_identity(); gs_matrix_pop(); @@ -52,8 +50,7 @@ void draw_drop_shadow(struct ft2_source *srcdata) gs_matrix_push(); gs_matrix_translate3f(4.0f, 4.0f, 0.0f); - draw_uv_vbuffer(srcdata->vbuf, srcdata->tex, srcdata->draw_effect, - (uint32_t)wcslen(srcdata->text) * 6, false); + draw_uv_vbuffer(srcdata->vbuf, srcdata->tex, srcdata->draw_effect, (uint32_t)wcslen(srcdata->text) * 6, false); gs_matrix_identity(); gs_matrix_pop(); } @@ -85,8 +82,7 @@ void set_up_vertex_buffer(struct ft2_source *srcdata) return; } - srcdata->vbuf = - create_uv_vbuffer((uint32_t)wcslen(srcdata->text) * 6, true); + srcdata->vbuf = create_uv_vbuffer((uint32_t)wcslen(srcdata->text) * 6, true); if (srcdata->custom_width <= 100) goto skip_word_wrap; @@ -118,8 +114,7 @@ void set_up_vertex_buffer(struct ft2_source *srcdata) if (srcdata->text[i] == L' ') space_pos = i; next_char:; - glyph_index = - FT_Get_Char_Index(srcdata->font_face, srcdata->text[i]); + glyph_index = FT_Get_Char_Index(srcdata->font_face, srcdata->text[i]); if (src_glyph) word_width += src_glyph->xadv; eos_skip:; @@ -168,8 +163,7 @@ void fill_vertex_buffer(struct ft2_source *srcdata) if (srcdata->text[i] == L'\r') goto skip_glyph; - glyph_index = - FT_Get_Char_Index(srcdata->font_face, srcdata->text[i]); + glyph_index = FT_Get_Char_Index(srcdata->font_face, srcdata->text[i]); if (src_glyph == NULL) goto skip_glyph; @@ -183,14 +177,10 @@ void fill_vertex_buffer(struct ft2_source *srcdata) skip_custom_width:; - set_v3_rect(vdata->points + (cur_glyph * 6), - (float)dx + (float)src_glyph->xoff, - (float)dy - (float)src_glyph->yoff, - (float)src_glyph->w, (float)src_glyph->h); - set_v2_uv(tvarray + (cur_glyph * 6), src_glyph->u, src_glyph->v, - src_glyph->u2, src_glyph->v2); - set_rect_colors2(col + (cur_glyph * 6), srcdata->color[0], - srcdata->color[1]); + set_v3_rect(vdata->points + (cur_glyph * 6), (float)dx + (float)src_glyph->xoff, + (float)dy - (float)src_glyph->yoff, (float)src_glyph->w, (float)src_glyph->h); + set_v2_uv(tvarray + (cur_glyph * 6), src_glyph->u, src_glyph->v, src_glyph->u2, src_glyph->v2); + set_rect_colors2(col + (cur_glyph * 6), srcdata->color[0], srcdata->color[1]); dx += src_glyph->xadv; if (dy - (float)src_glyph->yoff + src_glyph->h > max_y) max_y = dy - src_glyph->yoff + src_glyph->h; @@ -220,21 +210,16 @@ void cache_standard_glyphs(struct ft2_source *srcdata) FT_Render_Mode get_render_mode(struct ft2_source *srcdata) { - return srcdata->antialiasing ? FT_RENDER_MODE_NORMAL - : FT_RENDER_MODE_MONO; + return srcdata->antialiasing ? FT_RENDER_MODE_NORMAL : FT_RENDER_MODE_MONO; } -void load_glyph(struct ft2_source *srcdata, const FT_UInt glyph_index, - const FT_Render_Mode render_mode) +void load_glyph(struct ft2_source *srcdata, const FT_UInt glyph_index, const FT_Render_Mode render_mode) { - const FT_Int32 load_mode = render_mode == FT_RENDER_MODE_MONO - ? FT_LOAD_TARGET_MONO - : FT_LOAD_DEFAULT; + const FT_Int32 load_mode = render_mode == FT_RENDER_MODE_MONO ? FT_LOAD_TARGET_MONO : FT_LOAD_DEFAULT; FT_Load_Glyph(srcdata->font_face, glyph_index, load_mode); } -struct glyph_info *init_glyph(FT_GlyphSlot slot, const uint32_t dx, - const uint32_t dy, const uint32_t g_w, +struct glyph_info *init_glyph(FT_GlyphSlot slot, const uint32_t dx, const uint32_t dy, const uint32_t g_w, const uint32_t g_h) { struct glyph_info *glyph = bzalloc(sizeof(struct glyph_info)); @@ -251,8 +236,7 @@ struct glyph_info *init_glyph(FT_GlyphSlot slot, const uint32_t dx, return glyph; } -uint8_t get_pixel_value(const unsigned char *buf_row, - FT_Render_Mode render_mode, const uint32_t x) +uint8_t get_pixel_value(const unsigned char *buf_row, FT_Render_Mode render_mode, const uint32_t x) { if (render_mode == FT_RENDER_MODE_NORMAL) { return buf_row[x]; @@ -264,8 +248,7 @@ uint8_t get_pixel_value(const unsigned char *buf_row, return pixel_set ? 255 : 0; } -void rasterize(struct ft2_source *srcdata, FT_GlyphSlot slot, - const FT_Render_Mode render_mode, const uint32_t dx, +void rasterize(struct ft2_source *srcdata, FT_GlyphSlot slot, const FT_Render_Mode render_mode, const uint32_t dx, const uint32_t dy) { /** @@ -282,9 +265,7 @@ void rasterize(struct ft2_source *srcdata, FT_GlyphSlot slot, for (uint32_t x = 0; x < slot->bitmap.width; x++) { const uint32_t row_pixel_position = dx + x; - const uint8_t pixel_value = - get_pixel_value(&slot->bitmap.buffer[row_start], - render_mode, x); + const uint8_t pixel_value = get_pixel_value(&slot->bitmap.buffer[row_start], render_mode, x); srcdata->texbuf[row_pixel_position + row] = pixel_value; } } @@ -306,8 +287,7 @@ void cache_glyphs(struct ft2_source *srcdata, wchar_t *cache_glyphs) const FT_Render_Mode render_mode = get_render_mode(srcdata); for (size_t i = 0; i < len; i++) { - const FT_UInt glyph_index = - FT_Get_Char_Index(srcdata->font_face, cache_glyphs[i]); + const FT_UInt glyph_index = FT_Get_Char_Index(srcdata->font_face, cache_glyphs[i]); if (src_glyph != NULL) { continue; @@ -329,8 +309,7 @@ void cache_glyphs(struct ft2_source *srcdata, wchar_t *cache_glyphs) } if (dy + g_h >= texbuf_h) { - blog(LOG_WARNING, - "Out of space trying to render glyphs"); + blog(LOG_WARNING, "Out of space trying to render glyphs"); break; } @@ -359,9 +338,7 @@ void cache_glyphs(struct ft2_source *srcdata, wchar_t *cache_glyphs) gs_texture_destroy(tmp_texture); } - srcdata->tex = gs_texture_create( - texbuf_w, texbuf_h, GS_A8, 1, - (const uint8_t **)&srcdata->texbuf, 0); + srcdata->tex = gs_texture_create(texbuf_w, texbuf_h, GS_A8, 1, (const uint8_t **)&srcdata->texbuf, 0); obs_leave_graphics(); } @@ -437,8 +414,7 @@ void load_text_from_file(struct ft2_source *srcdata, const char *filename) srcdata->text = NULL; } srcdata->text = bzalloc((strlen(tmp_read) + 1) * sizeof(wchar_t)); - os_utf8_to_wcs(tmp_read, strlen(tmp_read), srcdata->text, - (strlen(tmp_read) + 1)); + os_utf8_to_wcs(tmp_read, strlen(tmp_read), srcdata->text, (strlen(tmp_read) + 1)); remove_cr(srcdata->text); bfree(tmp_read); @@ -502,8 +478,7 @@ void read_from_end(struct ft2_source *srcdata, const char *filename) srcdata->text = NULL; } srcdata->text = bzalloc(filesize - cur_pos); - bytes_read = - fread(srcdata->text, (filesize - cur_pos), 1, tmp_file); + bytes_read = fread(srcdata->text, (filesize - cur_pos), 1, tmp_file); remove_cr(srcdata->text); bfree(tmp_read); @@ -521,8 +496,7 @@ void read_from_end(struct ft2_source *srcdata, const char *filename) srcdata->text = NULL; } srcdata->text = bzalloc((strlen(tmp_read) + 1) * sizeof(wchar_t)); - os_utf8_to_wcs(tmp_read, strlen(tmp_read), srcdata->text, - (strlen(tmp_read) + 1)); + os_utf8_to_wcs(tmp_read, strlen(tmp_read), srcdata->text, (strlen(tmp_read) + 1)); remove_cr(srcdata->text); bfree(tmp_read); @@ -538,8 +512,7 @@ uint32_t get_ft2_text_width(wchar_t *text, struct ft2_source *srcdata) uint32_t w = 0, max_w = 0; const size_t len = wcslen(text); for (size_t i = 0; i < len; i++) { - const FT_UInt glyph_index = - FT_Get_Char_Index(srcdata->font_face, text[i]); + const FT_UInt glyph_index = FT_Get_Char_Index(srcdata->font_face, text[i]); if (text[i] == L'\n') w = 0; @@ -548,8 +521,7 @@ uint32_t get_ft2_text_width(wchar_t *text, struct ft2_source *srcdata) // Use the cached values. w += src_glyph->xadv; } else { - load_glyph(srcdata, glyph_index, - get_render_mode(srcdata)); + load_glyph(srcdata, glyph_index, get_render_mode(srcdata)); w += slot->advance.x >> 6; } if (w > max_w) diff --git a/plugins/vlc-video/vlc-video-plugin.c b/plugins/vlc-video/vlc-video-plugin.c index ab1b91bc2..d92397538 100644 --- a/plugins/vlc-video/vlc-video-plugin.c +++ b/plugins/vlc-video/vlc-video-plugin.c @@ -161,14 +161,12 @@ static bool load_libvlc_module(void) memset(path, 0, 1024 * sizeof(wchar_t)); - status = RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\VideoLAN\\VLC", - &key); + status = RegOpenKeyW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\VideoLAN\\VLC", &key); if (status != ERROR_SUCCESS) return false; size = 1024; - status = RegQueryValueExW(key, L"InstallDir", NULL, NULL, (LPBYTE)path, - &size); + status = RegQueryValueExW(key, L"InstallDir", NULL, NULL, (LPBYTE)path, &size); if (status == ERROR_SUCCESS) { wcscat(path, L"\\libvlc.dll"); os_wcs_to_utf8_ptr(path, 0, &path_utf8); @@ -227,8 +225,7 @@ bool obs_module_load(void) if (!load_vlc_funcs()) return true; - blog(LOG_INFO, "[vlc-video]: VLC %s found, VLC video source enabled", - libvlc_get_version_()); + blog(LOG_INFO, "[vlc-video]: VLC %s found, VLC video source enabled", libvlc_get_version_()); obs_register_source(&vlc_source_info); return true; diff --git a/plugins/vlc-video/vlc-video-plugin.h b/plugins/vlc-video/vlc-video-plugin.h index b3ecce54f..b4f5183ce 100644 --- a/plugins/vlc-video/vlc-video-plugin.h +++ b/plugins/vlc-video/vlc-video-plugin.h @@ -22,96 +22,66 @@ typedef libvlc_instance_t *(*LIBVLC_NEW)(int argc, const char *const *argv); typedef void (*LIBVLC_RELEASE)(libvlc_instance_t *p_instance); typedef const char *(*LIBVLC_GET_VERSION)(void); typedef int64_t (*LIBVLC_CLOCK)(void); -typedef int (*LIBVLC_EVENT_ATTACH)(libvlc_event_manager_t *p_event_manager, - libvlc_event_type_t i_event_type, - libvlc_callback_t f_callback, - void *user_data); +typedef int (*LIBVLC_EVENT_ATTACH)(libvlc_event_manager_t *p_event_manager, libvlc_event_type_t i_event_type, + libvlc_callback_t f_callback, void *user_data); /* libvlc media */ -typedef libvlc_media_t *(*LIBVLC_MEDIA_NEW_PATH)(libvlc_instance_t *p_instance, - const char *path); -typedef libvlc_media_t *(*LIBVLC_MEDIA_NEW_LOCATION)( - libvlc_instance_t *p_instance, const char *location); -typedef void (*LIBVLC_MEDIA_ADD_OPTION)(libvlc_media_t *p_md, - const char *options); +typedef libvlc_media_t *(*LIBVLC_MEDIA_NEW_PATH)(libvlc_instance_t *p_instance, const char *path); +typedef libvlc_media_t *(*LIBVLC_MEDIA_NEW_LOCATION)(libvlc_instance_t *p_instance, const char *location); +typedef void (*LIBVLC_MEDIA_ADD_OPTION)(libvlc_media_t *p_md, const char *options); typedef void (*LIBVLC_MEDIA_RETAIN)(libvlc_media_t *p_md); typedef void (*LIBVLC_MEDIA_RELEASE)(libvlc_media_t *p_md); -typedef char *(*LIBVLC_MEDIA_GET_META)(libvlc_media_t *p_md, - libvlc_meta_t e_meta); -typedef unsigned (*LIBVLC_MEDIA_TRACKS_GET)(libvlc_media_t *p_md, - libvlc_media_track_t ***pp_es); -typedef void (*LIBVLC_MEDIA_TRACKS_RELEASE)(libvlc_media_track_t **p_tracks, - unsigned i_count); +typedef char *(*LIBVLC_MEDIA_GET_META)(libvlc_media_t *p_md, libvlc_meta_t e_meta); +typedef unsigned (*LIBVLC_MEDIA_TRACKS_GET)(libvlc_media_t *p_md, libvlc_media_track_t ***pp_es); +typedef void (*LIBVLC_MEDIA_TRACKS_RELEASE)(libvlc_media_track_t **p_tracks, unsigned i_count); /* libvlc media player */ -typedef libvlc_media_player_t *(*LIBVLC_MEDIA_PLAYER_NEW)( - libvlc_instance_t *p_libvlc); -typedef libvlc_media_player_t *(*LIBVLC_MEDIA_PLAYER_NEW_FROM_MEDIA)( - libvlc_media_t *p_md); +typedef libvlc_media_player_t *(*LIBVLC_MEDIA_PLAYER_NEW)(libvlc_instance_t *p_libvlc); +typedef libvlc_media_player_t *(*LIBVLC_MEDIA_PLAYER_NEW_FROM_MEDIA)(libvlc_media_t *p_md); typedef void (*LIBVLC_MEDIA_PLAYER_RELEASE)(libvlc_media_player_t *p_mi); -typedef void (*LIBVLC_VIDEO_SET_CALLBACKS)(libvlc_media_player_t *mp, - libvlc_video_lock_cb lock, - libvlc_video_unlock_cb unlock, - libvlc_video_display_cb display, +typedef void (*LIBVLC_VIDEO_SET_CALLBACKS)(libvlc_media_player_t *mp, libvlc_video_lock_cb lock, + libvlc_video_unlock_cb unlock, libvlc_video_display_cb display, void *opaque); -typedef void (*LIBVLC_VIDEO_SET_FORMAT_CALLBACKS)( - libvlc_media_player_t *mp, libvlc_video_format_cb setup, - libvlc_video_cleanup_cb cleanup); -typedef void (*LIBVLC_AUDIO_SET_CALLBACKS)( - libvlc_media_player_t *mp, libvlc_audio_play_cb play, - libvlc_audio_pause_cb pause, libvlc_audio_resume_cb resume, - libvlc_audio_flush_cb flush, libvlc_audio_drain_cb drain, void *opaque); -typedef void (*LIBVLC_AUDIO_SET_FORMAT_CALLBACKS)( - libvlc_media_player_t *mp, libvlc_audio_setup_cb setup, - libvlc_audio_cleanup_cb cleanup); +typedef void (*LIBVLC_VIDEO_SET_FORMAT_CALLBACKS)(libvlc_media_player_t *mp, libvlc_video_format_cb setup, + libvlc_video_cleanup_cb cleanup); +typedef void (*LIBVLC_AUDIO_SET_CALLBACKS)(libvlc_media_player_t *mp, libvlc_audio_play_cb play, + libvlc_audio_pause_cb pause, libvlc_audio_resume_cb resume, + libvlc_audio_flush_cb flush, libvlc_audio_drain_cb drain, void *opaque); +typedef void (*LIBVLC_AUDIO_SET_FORMAT_CALLBACKS)(libvlc_media_player_t *mp, libvlc_audio_setup_cb setup, + libvlc_audio_cleanup_cb cleanup); typedef int (*LIBVLC_MEDIA_PLAYER_PLAY)(libvlc_media_player_t *p_mi); typedef void (*LIBVLC_MEDIA_PLAYER_STOP)(libvlc_media_player_t *p_mi); -typedef libvlc_time_t (*LIBVLC_MEDIA_PLAYER_GET_TIME)( - libvlc_media_player_t *p_mi); -typedef void (*LIBVLC_MEDIA_PLAYER_SET_TIME)(libvlc_media_player_t *p_mi, - libvlc_time_t i_time); -typedef int (*LIBVLC_VIDEO_GET_SIZE)(libvlc_media_player_t *p_mi, unsigned num, - unsigned *px, unsigned *py); -typedef libvlc_event_manager_t *(*LIBVLC_MEDIA_PLAYER_EVENT_MANAGER)( - libvlc_media_player_t *p_mp); -typedef libvlc_state_t (*LIBVLC_MEDIA_PLAYER_GET_STATE)( - libvlc_media_player_t *p_mi); -typedef libvlc_time_t (*LIBVLC_MEDIA_PLAYER_GET_LENGTH)( - libvlc_media_player_t *p_mi); -typedef libvlc_media_t *(*LIBVLC_MEDIA_PLAYER_GET_MEDIA)( - libvlc_media_player_t *p_mi); +typedef libvlc_time_t (*LIBVLC_MEDIA_PLAYER_GET_TIME)(libvlc_media_player_t *p_mi); +typedef void (*LIBVLC_MEDIA_PLAYER_SET_TIME)(libvlc_media_player_t *p_mi, libvlc_time_t i_time); +typedef int (*LIBVLC_VIDEO_GET_SIZE)(libvlc_media_player_t *p_mi, unsigned num, unsigned *px, unsigned *py); +typedef libvlc_event_manager_t *(*LIBVLC_MEDIA_PLAYER_EVENT_MANAGER)(libvlc_media_player_t *p_mp); +typedef libvlc_state_t (*LIBVLC_MEDIA_PLAYER_GET_STATE)(libvlc_media_player_t *p_mi); +typedef libvlc_time_t (*LIBVLC_MEDIA_PLAYER_GET_LENGTH)(libvlc_media_player_t *p_mi); +typedef libvlc_media_t *(*LIBVLC_MEDIA_PLAYER_GET_MEDIA)(libvlc_media_player_t *p_mi); /* libvlc media list */ -typedef libvlc_media_list_t *(*LIBVLC_MEDIA_LIST_NEW)( - libvlc_instance_t *p_instance); +typedef libvlc_media_list_t *(*LIBVLC_MEDIA_LIST_NEW)(libvlc_instance_t *p_instance); typedef void (*LIBVLC_MEDIA_LIST_RELEASE)(libvlc_media_list_t *p_ml); -typedef int (*LIBVLC_MEDIA_LIST_ADD_MEDIA)(libvlc_media_list_t *p_ml, - libvlc_media_t *p_md); +typedef int (*LIBVLC_MEDIA_LIST_ADD_MEDIA)(libvlc_media_list_t *p_ml, libvlc_media_t *p_md); typedef void (*LIBVLC_MEDIA_LIST_LOCK)(libvlc_media_list_t *p_ml); typedef void (*LIBVLC_MEDIA_LIST_UNLOCK)(libvlc_media_list_t *p_ml); -typedef libvlc_event_manager_t *(*LIBVLC_MEDIA_LIST_EVENT_MANAGER)( - libvlc_media_list_t *p_ml); +typedef libvlc_event_manager_t *(*LIBVLC_MEDIA_LIST_EVENT_MANAGER)(libvlc_media_list_t *p_ml); /* libvlc media list player */ -typedef libvlc_media_list_player_t *(*LIBVLC_MEDIA_LIST_PLAYER_NEW)( - libvlc_instance_t *p_instance); -typedef void (*LIBVLC_MEDIA_LIST_PLAYER_RELEASE)( - libvlc_media_list_player_t *p_mlp); +typedef libvlc_media_list_player_t *(*LIBVLC_MEDIA_LIST_PLAYER_NEW)(libvlc_instance_t *p_instance); +typedef void (*LIBVLC_MEDIA_LIST_PLAYER_RELEASE)(libvlc_media_list_player_t *p_mlp); typedef void (*LIBVLC_MEDIA_LIST_PLAYER_PLAY)(libvlc_media_list_player_t *p_mlp); -typedef void (*LIBVLC_MEDIA_LIST_PLAYER_PAUSE)( - libvlc_media_list_player_t *p_mlp); +typedef void (*LIBVLC_MEDIA_LIST_PLAYER_PAUSE)(libvlc_media_list_player_t *p_mlp); typedef void (*LIBVLC_MEDIA_LIST_PLAYER_STOP)(libvlc_media_list_player_t *p_mlp); -typedef void (*LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_PLAYER)( - libvlc_media_list_player_t *p_mlp, libvlc_media_player_t *p_mp); -typedef void (*LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_LIST)( - libvlc_media_list_player_t *p_mlp, libvlc_media_list_t *p_mlist); -typedef libvlc_event_manager_t *(*LIBVLC_MEDIA_LIST_PLAYER_EVENT_MANAGER)( - libvlc_media_list_player_t *p_mlp); -typedef void (*LIBVLC_MEDIA_LIST_PLAYER_SET_PLAYBACK_MODE)( - libvlc_media_list_player_t *p_mlp, libvlc_playback_mode_t e_mode); +typedef void (*LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_PLAYER)(libvlc_media_list_player_t *p_mlp, + libvlc_media_player_t *p_mp); +typedef void (*LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_LIST)(libvlc_media_list_player_t *p_mlp, + libvlc_media_list_t *p_mlist); +typedef libvlc_event_manager_t *(*LIBVLC_MEDIA_LIST_PLAYER_EVENT_MANAGER)(libvlc_media_list_player_t *p_mlp); +typedef void (*LIBVLC_MEDIA_LIST_PLAYER_SET_PLAYBACK_MODE)(libvlc_media_list_player_t *p_mlp, + libvlc_playback_mode_t e_mode); typedef int (*LIBVLC_MEDIA_LIST_PLAYER_NEXT)(libvlc_media_list_player_t *p_mlp); -typedef int (*LIBVLC_MEDIA_LIST_PLAYER_PREVIOUS)( - libvlc_media_list_player_t *p_mlp); +typedef int (*LIBVLC_MEDIA_LIST_PLAYER_PREVIOUS)(libvlc_media_list_player_t *p_mlp); /* -------------------------------------------------------------------- */ @@ -164,14 +134,10 @@ extern LIBVLC_MEDIA_LIST_PLAYER_RELEASE libvlc_media_list_player_release_; extern LIBVLC_MEDIA_LIST_PLAYER_PLAY libvlc_media_list_player_play_; extern LIBVLC_MEDIA_LIST_PLAYER_PAUSE libvlc_media_list_player_pause_; extern LIBVLC_MEDIA_LIST_PLAYER_STOP libvlc_media_list_player_stop_; -extern LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_PLAYER - libvlc_media_list_player_set_media_player_; -extern LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_LIST - libvlc_media_list_player_set_media_list_; -extern LIBVLC_MEDIA_LIST_PLAYER_EVENT_MANAGER - libvlc_media_list_player_event_manager_; -extern LIBVLC_MEDIA_LIST_PLAYER_SET_PLAYBACK_MODE - libvlc_media_list_player_set_playback_mode_; +extern LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_PLAYER libvlc_media_list_player_set_media_player_; +extern LIBVLC_MEDIA_LIST_PLAYER_SET_MEDIA_LIST libvlc_media_list_player_set_media_list_; +extern LIBVLC_MEDIA_LIST_PLAYER_EVENT_MANAGER libvlc_media_list_player_event_manager_; +extern LIBVLC_MEDIA_LIST_PLAYER_SET_PLAYBACK_MODE libvlc_media_list_player_set_playback_mode_; extern LIBVLC_MEDIA_LIST_PLAYER_NEXT libvlc_media_list_player_next_; extern LIBVLC_MEDIA_LIST_PLAYER_PREVIOUS libvlc_media_list_player_previous_; @@ -247,5 +213,4 @@ extern LIBVLC_MEDIA_LIST_PLAYER_PREVIOUS libvlc_media_list_player_previous_; "*.asx;*.b4s;*.cue;*.ifo;*.m3u;*.m3u8;*.pls;" \ "*.ram;*.rar;*.sdp;*.vlc;*.xspf;*.wax;*.wvx;*.zip;*.conf" -#define EXTENSIONS_MEDIA \ - EXTENSIONS_VIDEO ";" EXTENSIONS_AUDIO ";" EXTENSIONS_PLAYLIST +#define EXTENSIONS_MEDIA EXTENSIONS_VIDEO ";" EXTENSIONS_AUDIO ";" EXTENSIONS_PLAYLIST diff --git a/plugins/vlc-video/vlc-video-source.c b/plugins/vlc-video/vlc-video-source.c index 94f7b01b5..0be3ced53 100644 --- a/plugins/vlc-video/vlc-video-source.c +++ b/plugins/vlc-video/vlc-video-source.c @@ -4,9 +4,8 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[vlc_source: '%s'] " format, \ - obs_source_get_name(ss->source), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[vlc_source: '%s'] " format, obs_source_get_name(ss->source), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) @@ -96,9 +95,8 @@ static libvlc_media_t *get_media(media_file_array_t *files, const char *path) static inline libvlc_media_t *create_media_from_file(const char *file) { - return (file && strstr(file, "://") != NULL) - ? libvlc_media_new_location_(libvlc, file) - : libvlc_media_new_path_(libvlc, file); + return (file && strstr(file, "://") != NULL) ? libvlc_media_new_location_(libvlc, file) + : libvlc_media_new_path_(libvlc, file); } static void free_files(media_file_array_t *files) @@ -111,9 +109,9 @@ static void free_files(media_file_array_t *files) da_free(*files); } -#define MAKEFORMAT(ch0, ch1, ch2, ch3) \ - ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | \ - ((uint32_t)(uint8_t)(ch2) << 16) | ((uint32_t)(uint8_t)(ch3) << 24)) +#define MAKEFORMAT(ch0, ch1, ch2, ch3) \ + ((uint32_t)(uint8_t)(ch0) | ((uint32_t)(uint8_t)(ch1) << 8) | ((uint32_t)(uint8_t)(ch2) << 16) | \ + ((uint32_t)(uint8_t)(ch3) << 24)) static inline bool chroma_is(const char *chroma, const char *val) { @@ -153,8 +151,7 @@ static enum video_format convert_vlc_video_format(char *chroma, bool *full) CHROMA_CONV("YV12", MAKEFORMAT('N', 'V', '1', '2'), VIDEO_FORMAT_NV12); CHROMA_CONV("yv12", MAKEFORMAT('N', 'V', '1', '2'), VIDEO_FORMAT_NV12); - CHROMA_CONV_FULL("J420", MAKEFORMAT('J', '4', '2', '0'), - VIDEO_FORMAT_I420); + CHROMA_CONV_FULL("J420", MAKEFORMAT('J', '4', '2', '0'), VIDEO_FORMAT_I420); /* 4:2:2 formats */ CHROMA_TEST("UYVY", VIDEO_FORMAT_UYVY); @@ -188,8 +185,7 @@ static enum video_format convert_vlc_video_format(char *chroma, bool *full) /* 4:4:4 formats */ CHROMA_TEST("I444", VIDEO_FORMAT_I444); - CHROMA_CONV_FULL("J444", MAKEFORMAT('R', 'G', 'B', 'A'), - VIDEO_FORMAT_RGBA); + CHROMA_CONV_FULL("J444", MAKEFORMAT('R', 'G', 'B', 'A'), VIDEO_FORMAT_RGBA); CHROMA_CONV("YUVA", MAKEFORMAT('R', 'G', 'B', 'A'), VIDEO_FORMAT_RGBA); /* 4:4:0 formats */ @@ -216,8 +212,7 @@ static enum video_format convert_vlc_video_format(char *chroma, bool *full) return VIDEO_FORMAT_BGRA; } -static inline unsigned get_format_lines(enum video_format format, - unsigned height, size_t plane) +static inline unsigned get_format_lines(enum video_format format, unsigned height, size_t plane) { switch (format) { case VIDEO_FORMAT_I420: @@ -285,23 +280,19 @@ static void vlcs_get_metadata(void *data, calldata_t *cd) if (!vlcs || !data_id) return; - libvlc_media_t *media = - libvlc_media_player_get_media_(vlcs->media_player); + libvlc_media_t *media = libvlc_media_player_get_media_(vlcs->media_player); if (!media) return; -#define VLC_META(media, cd, did, tid, tag) \ - else if (strcmp(did, tid) == 0) \ - { \ - calldata_set_string(cd, "tag_data", \ - libvlc_media_get_meta_(media, tag)); \ +#define VLC_META(media, cd, did, tid, tag) \ + else if (strcmp(did, tid) == 0) \ + { \ + calldata_set_string(cd, "tag_data", libvlc_media_get_meta_(media, tag)); \ } if (strcmp(data_id, "title") == 0) - calldata_set_string(cd, "tag_data", - libvlc_media_get_meta_(media, - libvlc_meta_Title)); + calldata_set_string(cd, "tag_data", libvlc_media_get_meta_(media, libvlc_meta_Title)); VLC_META(media, cd, data_id, "artist", libvlc_meta_Artist) VLC_META(media, cd, data_id, "genre", libvlc_meta_Genre) @@ -378,8 +369,7 @@ static void vlcs_video_display(void *data, void *picture) UNUSED_PARAMETER(picture); } -static void calculate_display_size(struct vlc_source *c, unsigned *width, - unsigned *height) +static void calculate_display_size(struct vlc_source *c, unsigned *width, unsigned *height) { libvlc_media_t *media = libvlc_media_player_get_media_(c->media_player); @@ -404,11 +394,9 @@ static void calculate_display_size(struct vlc_source *c, unsigned *width, continue; /* Adjust for Sample Aspect Ratio (SAR) */ - if (track->video->i_sar_num > 0 && - track->video->i_sar_den > 0) { - display_width = (unsigned)util_mul_div64( - display_width, track->video->i_sar_num, - track->video->i_sar_den); + if (track->video->i_sar_num > 0 && track->video->i_sar_den > 0) { + display_width = (unsigned)util_mul_div64(display_width, track->video->i_sar_num, + track->video->i_sar_den); } switch (track->video->i_orientation) { @@ -434,8 +422,7 @@ static void calculate_display_size(struct vlc_source *c, unsigned *width, libvlc_media_release_(media); } -static unsigned vlcs_video_format(void **p_data, char *chroma, unsigned *width, - unsigned *height, unsigned *pitches, +static unsigned vlcs_video_format(void **p_data, char *chroma, unsigned *width, unsigned *height, unsigned *pitches, unsigned *lines) { struct vlc_source *c = *p_data; @@ -454,19 +441,15 @@ static unsigned vlcs_video_format(void **p_data, char *chroma, unsigned *width, calculate_display_size(c, width, height); /* don't allocate a new frame if format/width/height hasn't changed */ - if (c->frame.format != new_format || c->frame.width != *width || - c->frame.height != *height) { + if (c->frame.format != new_format || c->frame.width != *width || c->frame.height != *height) { obs_source_frame_free(&c->frame); obs_source_frame_init(&c->frame, new_format, *width, *height); c->frame.format = new_format; c->frame.full_range = new_range; - range = c->frame.full_range ? VIDEO_RANGE_FULL - : VIDEO_RANGE_PARTIAL; - video_format_get_parameters_for_format( - VIDEO_CS_DEFAULT, range, new_format, - c->frame.color_matrix, c->frame.color_range_min, - c->frame.color_range_max); + range = c->frame.full_range ? VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL; + video_format_get_parameters_for_format(VIDEO_CS_DEFAULT, range, new_format, c->frame.color_matrix, + c->frame.color_range_min, c->frame.color_range_max); } while (c->frame.data[i]) { @@ -478,8 +461,7 @@ static unsigned vlcs_video_format(void **p_data, char *chroma, unsigned *width, return 1; } -static void vlcs_audio_play(void *data, const void *samples, unsigned count, - int64_t pts) +static void vlcs_audio_play(void *data, const void *samples, unsigned count, int64_t pts) { struct vlc_source *c = data; size_t size = get_audio_size(c->audio.format, c->audio.speakers, count); @@ -496,8 +478,7 @@ static void vlcs_audio_play(void *data, const void *samples, unsigned count, obs_source_output_audio(c->source, &c->audio); } -static int vlcs_audio_setup(void **p_data, char *format, unsigned *rate, - unsigned *channels) +static int vlcs_audio_setup(void **p_data, char *format, unsigned *rate, unsigned *channels) { struct vlc_source *c = *p_data; enum audio_format new_audio_format; @@ -510,8 +491,7 @@ static int vlcs_audio_setup(void **p_data, char *format, unsigned *rate, *channels = out_channels; /* don't free audio data if the data is the same format */ - if (c->audio.format == new_audio_format && - c->audio.samples_per_sec == *rate && + if (c->audio.format == new_audio_format && c->audio.samples_per_sec == *rate && c->audio.speakers == (enum speaker_layout) * channels) return 0; @@ -525,9 +505,8 @@ static int vlcs_audio_setup(void **p_data, char *format, unsigned *rate, return 0; } -static void add_file(struct vlc_source *c, media_file_array_t *new_files, - const char *path, int network_caching, int track_index, - int subtitle_index, bool subtitle_enable) +static void add_file(struct vlc_source *c, media_file_array_t *new_files, const char *path, int network_caching, + int track_index, int subtitle_index, bool subtitle_enable) { struct media_file_data data; struct dstr new_path = {0}; @@ -551,10 +530,8 @@ static void add_file(struct vlc_source *c, media_file_array_t *new_files, if (new_media) { if (is_url) { struct dstr network_caching_option = {0}; - dstr_catf(&network_caching_option, - ":network-caching=%d", network_caching); - libvlc_media_add_option_(new_media, - network_caching_option.array); + dstr_catf(&network_caching_option, ":network-caching=%d", network_caching); + libvlc_media_add_option_(new_media, network_caching_option.array); dstr_free(&network_caching_option); } struct dstr track_option = {0}; @@ -564,8 +541,7 @@ static void add_file(struct vlc_source *c, media_file_array_t *new_files, struct dstr sub_option = {0}; if (subtitle_enable) { - dstr_catf(&sub_option, ":sub-track=%d", - subtitle_index - 1); + dstr_catf(&sub_option, ":sub-track=%d", subtitle_index - 1); } libvlc_media_add_option_(new_media, sub_option.array); dstr_free(&sub_option); @@ -685,16 +661,14 @@ static void vlcs_update(void *data, obs_data_t *settings) dstr_copy(&dir_path, path); dstr_cat_ch(&dir_path, '/'); dstr_cat(&dir_path, ent->d_name); - add_file(c, &new_files, dir_path.array, - network_caching, track_index, - subtitle_index, subtitle_enable); + add_file(c, &new_files, dir_path.array, network_caching, track_index, subtitle_index, + subtitle_enable); } dstr_free(&dir_path); os_closedir(dir); } else { - add_file(c, &new_files, path, network_caching, - track_index, subtitle_index, subtitle_enable); + add_file(c, &new_files, path, network_caching, track_index, subtitle_index, subtitle_enable); } obs_data_release(item); @@ -748,20 +722,16 @@ static void vlcs_update(void *data, obs_data_t *settings) libvlc_media_list_lock_(media_list); for (size_t i = 0; i < c->files.num; i++) - libvlc_media_list_add_media_(media_list, - c->files.array[i].media); + libvlc_media_list_add_media_(media_list, c->files.array[i].media); libvlc_media_list_unlock_(media_list); - libvlc_media_list_player_set_media_list_(c->media_list_player, - media_list); + libvlc_media_list_player_set_media_list_(c->media_list_player, media_list); libvlc_media_list_release_(media_list); - libvlc_media_list_player_set_playback_mode_( - c->media_list_player, c->loop ? libvlc_playback_mode_loop - : libvlc_playback_mode_default); + libvlc_media_list_player_set_playback_mode_(c->media_list_player, + c->loop ? libvlc_playback_mode_loop : libvlc_playback_mode_default); - if (c->files.num && (c->behavior == BEHAVIOR_ALWAYS_PLAY || - obs_source_active(c->source))) + if (c->files.num && (c->behavior == BEHAVIOR_ALWAYS_PLAY || obs_source_active(c->source))) libvlc_media_list_player_play_(c->media_list_player); else obs_source_output_video(c->source, NULL); @@ -880,8 +850,7 @@ static void vlcs_set_time(void *data, int64_t ms) libvlc_media_player_set_time_(c->media_player, (libvlc_time_t)ms); } -static void vlcs_play_pause_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void vlcs_play_pause_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -898,8 +867,7 @@ static void vlcs_play_pause_hotkey(void *data, obs_hotkey_id id, } } -static void vlcs_restart_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void vlcs_restart_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -910,8 +878,7 @@ static void vlcs_restart_hotkey(void *data, obs_hotkey_id id, obs_source_media_restart(c->source); } -static void vlcs_stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void vlcs_stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -922,8 +889,7 @@ static void vlcs_stop_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, obs_source_media_stop(c->source); } -static void vlcs_playlist_next_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void vlcs_playlist_next_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -934,8 +900,7 @@ static void vlcs_playlist_next_hotkey(void *data, obs_hotkey_id id, obs_source_media_next(c->source); } -static void vlcs_playlist_prev_hotkey(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void vlcs_playlist_prev_hotkey(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -951,25 +916,20 @@ static void *vlcs_create(obs_data_t *settings, obs_source_t *source) struct vlc_source *c = bzalloc(sizeof(*c)); c->source = source; - c->play_pause_hotkey = obs_hotkey_register_source( - source, "VLCSource.PlayPause", obs_module_text("PlayPause"), - vlcs_play_pause_hotkey, c); + c->play_pause_hotkey = obs_hotkey_register_source(source, "VLCSource.PlayPause", obs_module_text("PlayPause"), + vlcs_play_pause_hotkey, c); - c->restart_hotkey = obs_hotkey_register_source( - source, "VLCSource.Restart", obs_module_text("Restart"), - vlcs_restart_hotkey, c); + c->restart_hotkey = obs_hotkey_register_source(source, "VLCSource.Restart", obs_module_text("Restart"), + vlcs_restart_hotkey, c); - c->stop_hotkey = obs_hotkey_register_source(source, "VLCSource.Stop", - obs_module_text("Stop"), - vlcs_stop_hotkey, c); + c->stop_hotkey = + obs_hotkey_register_source(source, "VLCSource.Stop", obs_module_text("Stop"), vlcs_stop_hotkey, c); c->playlist_next_hotkey = obs_hotkey_register_source( - source, "VLCSource.PlaylistNext", - obs_module_text("PlaylistNext"), vlcs_playlist_next_hotkey, c); + source, "VLCSource.PlaylistNext", obs_module_text("PlaylistNext"), vlcs_playlist_next_hotkey, c); c->playlist_prev_hotkey = obs_hotkey_register_source( - source, "VLCSource.PlaylistPrev", - obs_module_text("PlaylistPrev"), vlcs_playlist_prev_hotkey, c); + source, "VLCSource.PlaylistPrev", obs_module_text("PlaylistPrev"), vlcs_playlist_prev_hotkey, c); pthread_mutex_init_value(&c->mutex); if (pthread_mutex_init(&c->mutex, NULL) != 0) @@ -986,30 +946,21 @@ static void *vlcs_create(obs_data_t *settings, obs_source_t *source) if (!c->media_player) goto error; - libvlc_media_list_player_set_media_player_(c->media_list_player, - c->media_player); + libvlc_media_list_player_set_media_player_(c->media_list_player, c->media_player); - libvlc_video_set_callbacks_(c->media_player, vlcs_video_lock, NULL, - vlcs_video_display, c); - libvlc_video_set_format_callbacks_(c->media_player, vlcs_video_format, - NULL); + libvlc_video_set_callbacks_(c->media_player, vlcs_video_lock, NULL, vlcs_video_display, c); + libvlc_video_set_format_callbacks_(c->media_player, vlcs_video_format, NULL); - libvlc_audio_set_callbacks_(c->media_player, vlcs_audio_play, NULL, - NULL, NULL, NULL, c); - libvlc_audio_set_format_callbacks_(c->media_player, vlcs_audio_setup, - NULL); + libvlc_audio_set_callbacks_(c->media_player, vlcs_audio_play, NULL, NULL, NULL, NULL, c); + libvlc_audio_set_format_callbacks_(c->media_player, vlcs_audio_setup, NULL); libvlc_event_manager_t *event_manager; event_manager = libvlc_media_player_event_manager_(c->media_player); - libvlc_event_attach_(event_manager, libvlc_MediaPlayerEndReached, - vlcs_stopped, c); - libvlc_event_attach_(event_manager, libvlc_MediaPlayerOpening, - vlcs_started, c); + libvlc_event_attach_(event_manager, libvlc_MediaPlayerEndReached, vlcs_stopped, c); + libvlc_event_attach_(event_manager, libvlc_MediaPlayerOpening, vlcs_started, c); proc_handler_t *ph = obs_source_get_proc_handler(source); - proc_handler_add( - ph, "void get_metadata(in string tag_id out string tag_data)", - vlcs_get_metadata, c); + proc_handler_add(ph, "void get_metadata(in string tag_id out string tag_data)", vlcs_get_metadata, c); obs_source_update(source, NULL); @@ -1050,8 +1001,7 @@ static void vlcs_defaults(obs_data_t *settings) { obs_data_set_default_bool(settings, S_LOOP, true); obs_data_set_default_bool(settings, S_SHUFFLE, false); - obs_data_set_default_string(settings, S_BEHAVIOR, - S_BEHAVIOR_STOP_RESTART); + obs_data_set_default_string(settings, S_BEHAVIOR, S_BEHAVIOR_STOP_RESTART); obs_data_set_default_int(settings, S_NETWORK_CACHING, 400); obs_data_set_default_int(settings, S_TRACK, 1); obs_data_set_default_bool(settings, S_SUBTITLE_ENABLE, false); @@ -1086,15 +1036,10 @@ static obs_properties_t *vlcs_properties(void *data) pthread_mutex_unlock(&c->mutex); } - p = obs_properties_add_list(ppts, S_BEHAVIOR, T_BEHAVIOR, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, T_BEHAVIOR_STOP_RESTART, - S_BEHAVIOR_STOP_RESTART); - obs_property_list_add_string(p, T_BEHAVIOR_PAUSE_UNPAUSE, - S_BEHAVIOR_PAUSE_UNPAUSE); - obs_property_list_add_string(p, T_BEHAVIOR_ALWAYS_PLAY, - S_BEHAVIOR_ALWAYS_PLAY); + p = obs_properties_add_list(ppts, S_BEHAVIOR, T_BEHAVIOR, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_list_add_string(p, T_BEHAVIOR_STOP_RESTART, S_BEHAVIOR_STOP_RESTART); + obs_property_list_add_string(p, T_BEHAVIOR_PAUSE_UNPAUSE, S_BEHAVIOR_PAUSE_UNPAUSE); + obs_property_list_add_string(p, T_BEHAVIOR_ALWAYS_PLAY, S_BEHAVIOR_ALWAYS_PLAY); dstr_cat(&filter, "Media Files ("); dstr_copy(&exts, EXTENSIONS_MEDIA); @@ -1117,21 +1062,18 @@ static obs_properties_t *vlcs_properties(void *data) dstr_cat_dstr(&filter, &exts); dstr_cat(&filter, ")"); - obs_properties_add_editable_list(ppts, S_PLAYLIST, T_PLAYLIST, - OBS_EDITABLE_LIST_TYPE_FILES_AND_URLS, + obs_properties_add_editable_list(ppts, S_PLAYLIST, T_PLAYLIST, OBS_EDITABLE_LIST_TYPE_FILES_AND_URLS, filter.array, path.array); dstr_free(&path); dstr_free(&filter); dstr_free(&exts); - p = obs_properties_add_int(ppts, S_NETWORK_CACHING, T_NETWORK_CACHING, - 100, 60000, 10); + p = obs_properties_add_int(ppts, S_NETWORK_CACHING, T_NETWORK_CACHING, 100, 60000, 10); obs_property_int_set_suffix(p, " ms"); obs_properties_add_int(ppts, S_TRACK, T_TRACK, 1, 10, 1); obs_properties_add_bool(ppts, S_SUBTITLE_ENABLE, T_SUBTITLE_ENABLE); - obs_properties_add_int(ppts, S_SUBTITLE_TRACK, T_SUBTITLE_TRACK, 1, - 1000, 1); + obs_properties_add_int(ppts, S_SUBTITLE_TRACK, T_SUBTITLE_TRACK, 1, 1000, 1); return ppts; } @@ -1184,13 +1126,9 @@ static obs_missing_files_t *vlcs_missingfiles(void *data) const char *path = obs_data_get_string(item, "value"); if (strcmp(path, "") != 0) { - if (!os_file_exists(path) && - strstr(path, "://") == NULL) { - obs_missing_file_t *file = - obs_missing_file_create( - path, missing_file_callback, - OBS_MISSING_FILE_SOURCE, source, - (void *)path); + if (!os_file_exists(path) && strstr(path, "://") == NULL) { + obs_missing_file_t *file = obs_missing_file_create( + path, missing_file_callback, OBS_MISSING_FILE_SOURCE, source, (void *)path); obs_missing_files_add_file(missing_files, file); } @@ -1208,8 +1146,7 @@ static obs_missing_files_t *vlcs_missingfiles(void *data) struct obs_source_info vlc_source_info = { .id = "vlc_source", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_DO_NOT_DUPLICATE | + .output_flags = OBS_SOURCE_ASYNC_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_CONTROLLABLE_MEDIA, .get_name = vlcs_get_name, .create = vlcs_create, diff --git a/plugins/win-capture/app-helpers.c b/plugins/win-capture/app-helpers.c index 564dfb014..f34b5dead 100644 --- a/plugins/win-capture/app-helpers.c +++ b/plugins/win-capture/app-helpers.c @@ -13,14 +13,10 @@ bool is_app(HANDLE process) HANDLE token; if (OpenProcessToken(process, TOKEN_QUERY, &token)) { - BOOL success = GetTokenInformation(token, TokenIsAppContainer, - &ret, sizeof(ret), - &size_ret); + BOOL success = GetTokenInformation(token, TokenIsAppContainer, &ret, sizeof(ret), &size_ret); if (!success) { const DWORD error = GetLastError(); - blog(LOG_ERROR, - "is_app GetTokenInformation failed: 0x%08lX", - error); + blog(LOG_ERROR, "is_app GetTokenInformation failed: 0x%08lX", error); } CloseHandle(token); @@ -36,13 +32,11 @@ wchar_t *get_app_sid(HANDLE process) HANDLE token; if (OpenProcessToken(process, TOKEN_QUERY, &token)) { - DWORD info_len = GetSidLengthRequired(12) + - sizeof(TOKEN_APPCONTAINER_INFORMATION); + DWORD info_len = GetSidLengthRequired(12) + sizeof(TOKEN_APPCONTAINER_INFORMATION); PTOKEN_APPCONTAINER_INFORMATION info = malloc(info_len); - success = GetTokenInformation(token, TokenAppContainerSid, info, - info_len, &size_ret); + success = GetTokenInformation(token, TokenAppContainerSid, info, info_len, &size_ret); if (success) ConvertSidToStringSidW(info->TokenAppContainer, &ret); @@ -53,8 +47,7 @@ wchar_t *get_app_sid(HANDLE process) return ret; } -static const wchar_t *path_format = - L"\\Sessions\\%lu\\AppContainerNamedObjects\\%s\\%s"; +static const wchar_t *path_format = L"\\Sessions\\%lu\\AppContainerNamedObjects\\%s\\%s"; HANDLE create_app_mutex(const wchar_t *sid, const wchar_t *name) { diff --git a/plugins/win-capture/audio-helpers.c b/plugins/win-capture/audio-helpers.c index dab320bab..99c7ba8b6 100644 --- a/plugins/win-capture/audio-helpers.c +++ b/plugins/win-capture/audio-helpers.c @@ -2,24 +2,19 @@ #include -static inline bool settings_changed(obs_data_t *old_settings, - obs_data_t *new_settings) +static inline bool settings_changed(obs_data_t *old_settings, obs_data_t *new_settings) { const char *old_window = obs_data_get_string(old_settings, "window"); const char *new_window = obs_data_get_string(new_settings, "window"); - enum window_priority old_priority = - obs_data_get_int(old_settings, "priority"); - enum window_priority new_priority = - obs_data_get_int(new_settings, "priority"); + enum window_priority old_priority = obs_data_get_int(old_settings, "priority"); + enum window_priority new_priority = obs_data_get_int(new_settings, "priority"); // Changes to priority only matter if a window is set - return (old_priority != new_priority && *new_window) || - strcmp(old_window, new_window) != 0; + return (old_priority != new_priority && *new_window) || strcmp(old_window, new_window) != 0; } -static inline void reroute_wasapi_source(obs_source_t *wasapi, - obs_source_t *target) +static inline void reroute_wasapi_source(obs_source_t *wasapi, obs_source_t *target) { proc_handler_t *ph = obs_source_get_proc_handler(wasapi); calldata_t cd = {0}; @@ -28,8 +23,7 @@ static inline void reroute_wasapi_source(obs_source_t *wasapi, calldata_free(&cd); } -void setup_audio_source(obs_source_t *parent, obs_source_t **child, - const char *window, bool enabled, +void setup_audio_source(obs_source_t *parent, obs_source_t **child, const char *window, bool enabled, enum window_priority priority) { if (enabled) { @@ -43,12 +37,9 @@ void setup_audio_source(obs_source_t *parent, obs_source_t **child, if (!*child) { struct dstr name = {0}; - dstr_printf(&name, "%s (%s)", - obs_source_get_name(parent), - TEXT_CAPTURE_AUDIO_SUFFIX); + dstr_printf(&name, "%s (%s)", obs_source_get_name(parent), TEXT_CAPTURE_AUDIO_SUFFIX); - *child = obs_source_create_private( - AUDIO_SOURCE_TYPE, name.array, wasapi_settings); + *child = obs_source_create_private(AUDIO_SOURCE_TYPE, name.array, wasapi_settings); // Ensure child gets activated/deactivated properly obs_source_add_active_child(parent, *child); @@ -59,8 +50,7 @@ void setup_audio_source(obs_source_t *parent, obs_source_t **child, dstr_free(&name); } else if (wasapi_settings) { - obs_data_t *old_settings = - obs_source_get_settings(*child); + obs_data_t *old_settings = obs_source_get_settings(*child); // Only bother updating if settings changed if (settings_changed(old_settings, wasapi_settings)) obs_source_update(*child, wasapi_settings); @@ -128,8 +118,7 @@ void rename_audio_source(void *param, calldata_t *data) return; struct dstr name = {0}; - dstr_printf(&name, "%s (%s)", calldata_string(data, "new_name"), - TEXT_CAPTURE_AUDIO_SUFFIX); + dstr_printf(&name, "%s (%s)", calldata_string(data, "new_name"), TEXT_CAPTURE_AUDIO_SUFFIX); obs_source_set_name(src, name.array); dstr_free(&name); diff --git a/plugins/win-capture/audio-helpers.h b/plugins/win-capture/audio-helpers.h index e3e7e5358..03cd83236 100644 --- a/plugins/win-capture/audio-helpers.h +++ b/plugins/win-capture/audio-helpers.h @@ -11,8 +11,7 @@ #define TEXT_CAPTURE_AUDIO_SUFFIX obs_module_text("AudioSuffix") #define AUDIO_SOURCE_TYPE "wasapi_process_output_capture" -void setup_audio_source(obs_source_t *parent, obs_source_t **child, - const char *window, bool enabled, +void setup_audio_source(obs_source_t *parent, obs_source_t **child, const char *window, bool enabled, enum window_priority priority); void reconfigure_audio_source(obs_source_t *source, HWND window); void rename_audio_source(void *param, calldata_t *data); diff --git a/plugins/win-capture/compat-helpers.c b/plugins/win-capture/compat-helpers.c index f4d5565ec..bb777fa6b 100644 --- a/plugins/win-capture/compat-helpers.c +++ b/plugins/win-capture/compat-helpers.c @@ -111,9 +111,7 @@ static json_t *open_compat_file(void) } static json_t *compat_entries; -struct compat_result *check_compatibility(const char *win_title, - const char *win_class, - const char *exe, +struct compat_result *check_compatibility(const char *win_title, const char *win_class, const char *exe, enum source_type type) { if (!compat_entries) { @@ -130,14 +128,11 @@ struct compat_result *check_compatibility(const char *win_title, size_t index; json_array_foreach (compat_entries, index, entry) { - if (type == GAME_CAPTURE && - !get_bool_val(entry, "game_capture")) + if (type == GAME_CAPTURE && !get_bool_val(entry, "game_capture")) continue; - if (type == WINDOW_CAPTURE_WGC && - !get_bool_val(entry, "window_capture_wgc")) + if (type == WINDOW_CAPTURE_WGC && !get_bool_val(entry, "window_capture_wgc")) continue; - if (type == WINDOW_CAPTURE_BITBLT && - !get_bool_val(entry, "window_capture")) + if (type == WINDOW_CAPTURE_BITBLT && !get_bool_val(entry, "window_capture")) continue; int match_flags = get_int_val(entry, "match_flags"); @@ -145,17 +140,13 @@ struct compat_result *check_compatibility(const char *win_title, const char *j_title = get_string_val(entry, "window_title"); const char *j_class = get_string_val(entry, "window_class"); - if ((match_flags & MATCH_CLASS) && - (!win_class || strcmp(win_class, j_class) != 0)) + if ((match_flags & MATCH_CLASS) && (!win_class || strcmp(win_class, j_class) != 0)) continue; - if ((match_flags & MATCH_EXE) && - (!exe || astrcmpi(exe, j_exe) != 0)) + if ((match_flags & MATCH_EXE) && (!exe || astrcmpi(exe, j_exe) != 0)) continue; /* Title supports partial matches as some games append additional * information after the title, e.g., "Minecraft 1.18". */ - if ((match_flags & MATCH_TITLE) && - (!win_title || - astrcmpi_n(win_title, j_title, strlen(j_title)) != 0)) + if ((match_flags & MATCH_TITLE) && (!win_title || astrcmpi_n(win_title, j_title, strlen(j_title)) != 0)) continue; /* Attempt to translate and compile message */ @@ -174,8 +165,7 @@ struct compat_result *check_compatibility(const char *win_title, const char *url = get_string_val(entry, "url"); /* Append clickable URL in Qt rich text */ if (url && strncmp(url, "https://", 8) == 0) { - dstr_catf(&message, "
\n%s", url, - url + 8); + dstr_catf(&message, "
\n%s", url, url + 8); } res = bzalloc(sizeof(struct compat_result)); diff --git a/plugins/win-capture/compat-helpers.h b/plugins/win-capture/compat-helpers.h index 341775147..3cff441c3 100644 --- a/plugins/win-capture/compat-helpers.h +++ b/plugins/win-capture/compat-helpers.h @@ -11,9 +11,7 @@ struct compat_result { enum obs_text_info_type severity; }; -extern struct compat_result *check_compatibility(const char *win_title, - const char *win_class, - const char *exe, +extern struct compat_result *check_compatibility(const char *win_title, const char *win_class, const char *exe, enum source_type type); extern void compat_result_free(struct compat_result *res); extern void compat_json_free(); diff --git a/plugins/win-capture/cursor-capture.c b/plugins/win-capture/cursor-capture.c index a360336ec..a85bf7799 100644 --- a/plugins/win-capture/cursor-capture.c +++ b/plugins/win-capture/cursor-capture.c @@ -46,14 +46,12 @@ static inline void apply_mask(uint8_t *color, uint8_t *mask, BITMAP *bmp_mask) for (long y = 0; y < bmp_mask->bmHeight; y++) { for (long x = 0; x < bmp_mask->bmWidth; x++) { mask_pix_offs = y * (bmp_mask->bmWidthBytes * 8) + x; - color[(y * bmp_mask->bmWidth + x) * 4 + 3] = - bit_to_alpha(mask, mask_pix_offs, false); + color[(y * bmp_mask->bmWidth + x) * 4 + 3] = bit_to_alpha(mask, mask_pix_offs, false); } } } -static inline uint8_t *copy_from_color(ICONINFO *ii, uint32_t *width, - uint32_t *height) +static inline uint8_t *copy_from_color(ICONINFO *ii, uint32_t *width, uint32_t *height) { BITMAP bmp_color; BITMAP bmp_mask; @@ -85,8 +83,7 @@ static inline uint8_t *copy_from_color(ICONINFO *ii, uint32_t *width, return color; } -static inline uint8_t *copy_from_mask(ICONINFO *ii, uint32_t *width, - uint32_t *height) +static inline uint8_t *copy_from_mask(ICONINFO *ii, uint32_t *width, uint32_t *height) { uint8_t *output; uint8_t *mask; @@ -112,14 +109,12 @@ static inline uint8_t *copy_from_mask(ICONINFO *ii, uint32_t *width, if (!andMask) { // black in the AND mask - *(uint32_t *)&output[i * 4] = - !!xorMask ? 0x00FFFFFF /*always white*/ - : 0xFF000000 /*always black*/; + *(uint32_t *)&output[i * 4] = !!xorMask ? 0x00FFFFFF /*always white*/ + : 0xFF000000 /*always black*/; } else { // white in the AND mask - *(uint32_t *)&output[i * 4] = - !!xorMask ? 0xFFFFFFFF /*source inverted*/ - : 0 /*transparent*/; + *(uint32_t *)&output[i * 4] = !!xorMask ? 0xFFFFFFFF /*source inverted*/ + : 0 /*transparent*/; } } @@ -130,9 +125,7 @@ static inline uint8_t *copy_from_mask(ICONINFO *ii, uint32_t *width, return output; } -static inline uint8_t *cursor_capture_icon_bitmap(ICONINFO *ii, uint32_t *width, - uint32_t *height, - bool *monochrome) +static inline uint8_t *cursor_capture_icon_bitmap(ICONINFO *ii, uint32_t *width, uint32_t *height, bool *monochrome) { uint8_t *output; *monochrome = false; @@ -145,8 +138,7 @@ static inline uint8_t *cursor_capture_icon_bitmap(ICONINFO *ii, uint32_t *width, return output; } -static gs_texture_t *get_cached_texture(struct cursor_data *data, uint32_t cx, - uint32_t cy) +static gs_texture_t *get_cached_texture(struct cursor_data *data, uint32_t cx, uint32_t cy) { struct cached_cursor cc; @@ -178,8 +170,7 @@ static inline bool cursor_capture_icon(struct cursor_data *data, HICON icon) return false; } - bitmap = cursor_capture_icon_bitmap(&ii, &width, &height, - &data->monochrome); + bitmap = cursor_capture_icon_bitmap(&ii, &width, &height, &data->monochrome); if (bitmap) { if (data->last_cx != width || data->last_cy != height) { data->texture = get_cached_texture(data, width, height); @@ -224,8 +215,7 @@ void cursor_capture(struct cursor_data *data) DestroyIcon(icon); } -void cursor_draw(struct cursor_data *data, long x_offset, long y_offset, - long width, long height) +void cursor_draw(struct cursor_data *data, long x_offset, long y_offset, long width, long height) { long x = data->cursor_pos.x + x_offset; long y = data->cursor_pos.y + y_offset; @@ -237,12 +227,9 @@ void cursor_draw(struct cursor_data *data, long x_offset, long y_offset, if (data->visible && !!data->texture) { gs_blend_state_push(); - enum gs_blend_type blendMode = data->monochrome - ? GS_BLEND_INVDSTCOLOR - : GS_BLEND_SRCALPHA; + enum gs_blend_type blendMode = data->monochrome ? GS_BLEND_INVDSTCOLOR : GS_BLEND_SRCALPHA; gs_blend_function_separate(blendMode, /*src_color*/ - GS_BLEND_INVSRCALPHA /*dest_color*/, - GS_BLEND_ONE /*src_alpha*/, + GS_BLEND_INVSRCALPHA /*dest_color*/, GS_BLEND_ONE /*src_alpha*/, GS_BLEND_INVSRCALPHA /*dest_alpha*/); gs_matrix_push(); diff --git a/plugins/win-capture/cursor-capture.h b/plugins/win-capture/cursor-capture.h index e52ee2fb3..3356c545d 100644 --- a/plugins/win-capture/cursor-capture.h +++ b/plugins/win-capture/cursor-capture.h @@ -24,6 +24,5 @@ struct cursor_data { }; extern void cursor_capture(struct cursor_data *data); -extern void cursor_draw(struct cursor_data *data, long x_offset, long y_offset, - long width, long height); +extern void cursor_draw(struct cursor_data *data, long x_offset, long y_offset, long width, long height); extern void cursor_data_free(struct cursor_data *data); diff --git a/plugins/win-capture/dc-capture.c b/plugins/win-capture/dc-capture.c index 7f71a9fa3..7a911554e 100644 --- a/plugins/win-capture/dc-capture.c +++ b/plugins/win-capture/dc-capture.c @@ -6,17 +6,13 @@ static inline void init_textures(struct dc_capture *capture) { if (capture->compatibility) { - capture->texture = gs_texture_create(capture->width, - capture->height, GS_BGRA, - 1, NULL, GS_DYNAMIC); + capture->texture = gs_texture_create(capture->width, capture->height, GS_BGRA, 1, NULL, GS_DYNAMIC); } else { - capture->texture = - gs_texture_create_gdi(capture->width, capture->height); + capture->texture = gs_texture_create_gdi(capture->width, capture->height); if (capture->texture) { - capture->extra_texture = gs_texture_create( - capture->width, capture->height, GS_BGRA, 1, - NULL, 0); + capture->extra_texture = + gs_texture_create(capture->width, capture->height, GS_BGRA, 1, NULL, 0); if (!capture->extra_texture) { blog(LOG_WARNING, "[dc_capture_init] Failed to " "create textures"); @@ -35,8 +31,8 @@ static inline void init_textures(struct dc_capture *capture) capture->valid = true; } -void dc_capture_init(struct dc_capture *capture, int x, int y, uint32_t width, - uint32_t height, bool cursor, bool compatibility) +void dc_capture_init(struct dc_capture *capture, int x, int y, uint32_t width, uint32_t height, bool cursor, + bool compatibility) { memset(capture, 0, sizeof(struct dc_capture)); @@ -71,14 +67,12 @@ void dc_capture_init(struct dc_capture *capture, int x, int y, uint32_t width, const HDC hdc = CreateCompatibleDC(NULL); if (hdc) { - const HBITMAP bmp = CreateDIBSection( - capture->hdc, &bi, DIB_RGB_COLORS, - (void **)&capture->bits, NULL, 0); + const HBITMAP bmp = + CreateDIBSection(capture->hdc, &bi, DIB_RGB_COLORS, (void **)&capture->bits, NULL, 0); if (bmp) { capture->hdc = hdc; capture->bmp = bmp; - capture->old_bmp = SelectObject(capture->hdc, - capture->bmp); + capture->old_bmp = SelectObject(capture->hdc, capture->bmp); } else { DeleteDC(hdc); } @@ -148,8 +142,7 @@ static inline HDC dc_capture_get_dc(struct dc_capture *capture) static inline void dc_capture_release_dc(struct dc_capture *capture) { if (capture->compatibility) { - gs_texture_set_image(capture->texture, capture->bits, - capture->width * 4, false); + gs_texture_set_image(capture->texture, capture->bits, capture->width * 4, false); } else { gs_texture_release_dc(capture->texture); } @@ -175,8 +168,7 @@ void dc_capture_capture(struct dc_capture *capture, HWND window) hdc_target = GetDC(window); - BitBlt(hdc, 0, 0, capture->width, capture->height, hdc_target, - capture->x, capture->y, SRCCOPY); + BitBlt(hdc, 0, 0, capture->width, capture->height, hdc_target, capture->x, capture->y, SRCCOPY); ReleaseDC(NULL, hdc_target); @@ -195,8 +187,7 @@ void dc_capture_render(struct dc_capture *capture, bool texcoords_centered) const bool compatibility = capture->compatibility; bool linear_sample = compatibility; if (!linear_sample && !texcoords_centered) { - gs_texture_t *const extra_texture = - capture->extra_texture; + gs_texture_t *const extra_texture = capture->extra_texture; gs_copy_texture(extra_texture, texture); texture = extra_texture; linear_sample = true; @@ -219,10 +210,8 @@ void dc_capture_render(struct dc_capture *capture, bool texcoords_centered) } gs_effect_t *effect = obs_get_base_effect(OBS_EFFECT_OPAQUE); - gs_technique_t *tech = - gs_effect_get_technique(effect, tech_name); - gs_eparam_t *image = - gs_effect_get_param_by_name(effect, "image"); + gs_technique_t *tech = gs_effect_get_technique(effect, tech_name); + gs_eparam_t *image = gs_effect_get_param_by_name(effect, "image"); const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(linear_sample); @@ -233,8 +222,7 @@ void dc_capture_render(struct dc_capture *capture, bool texcoords_centered) else gs_effect_set_texture(image, texture); - gs_eparam_t *multiplier_param = - gs_effect_get_param_by_name(effect, "multiplier"); + gs_eparam_t *multiplier_param = gs_effect_get_param_by_name(effect, "multiplier"); gs_effect_set_float(multiplier_param, multiplier); const uint32_t flip = compatibility ? GS_FLIP_V : 0; diff --git a/plugins/win-capture/dc-capture.h b/plugins/win-capture/dc-capture.h index 15c08090f..a0fd164fe 100644 --- a/plugins/win-capture/dc-capture.h +++ b/plugins/win-capture/dc-capture.h @@ -26,11 +26,9 @@ struct dc_capture { bool valid; }; -extern void dc_capture_init(struct dc_capture *capture, int x, int y, - uint32_t width, uint32_t height, bool cursor, +extern void dc_capture_init(struct dc_capture *capture, int x, int y, uint32_t width, uint32_t height, bool cursor, bool compatibility); extern void dc_capture_free(struct dc_capture *capture); extern void dc_capture_capture(struct dc_capture *capture, HWND window); -extern void dc_capture_render(struct dc_capture *capture, - bool texcoords_centered); +extern void dc_capture_render(struct dc_capture *capture, bool texcoords_centered); diff --git a/plugins/win-capture/duplicator-monitor-capture.c b/plugins/win-capture/duplicator-monitor-capture.c index fce26c722..6f320284d 100644 --- a/plugins/win-capture/duplicator-monitor-capture.c +++ b/plugins/win-capture/duplicator-monitor-capture.c @@ -13,9 +13,8 @@ #include #endif -#define do_log(level, format, ...) \ - blog(level, "[duplicator-monitor-capture: '%s'] " format, \ - obs_source_get_name(capture->source), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[duplicator-monitor-capture: '%s'] " format, obs_source_get_name(capture->source), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -42,22 +41,18 @@ typedef BOOL (*PFN_winrt_capture_supported)(); typedef BOOL (*PFN_winrt_capture_cursor_toggle_supported)(); -typedef struct winrt_capture *(*PFN_winrt_capture_init_monitor)( - BOOL cursor, HMONITOR monitor, BOOL force_sdr); +typedef struct winrt_capture *(*PFN_winrt_capture_init_monitor)(BOOL cursor, HMONITOR monitor, BOOL force_sdr); typedef void (*PFN_winrt_capture_free)(struct winrt_capture *capture); typedef BOOL (*PFN_winrt_capture_active)(const struct winrt_capture *capture); -typedef enum gs_color_space (*PFN_winrt_capture_get_color_space)( - const struct winrt_capture *capture); +typedef enum gs_color_space (*PFN_winrt_capture_get_color_space)(const struct winrt_capture *capture); typedef void (*PFN_winrt_capture_render)(struct winrt_capture *capture); typedef uint32_t (*PFN_winrt_capture_width)(const struct winrt_capture *capture); -typedef uint32_t (*PFN_winrt_capture_height)( - const struct winrt_capture *capture); +typedef uint32_t (*PFN_winrt_capture_height)(const struct winrt_capture *capture); struct winrt_exports { PFN_winrt_capture_supported winrt_capture_supported; - PFN_winrt_capture_cursor_toggle_supported - winrt_capture_cursor_toggle_supported; + PFN_winrt_capture_cursor_toggle_supported winrt_capture_cursor_toggle_supported; PFN_winrt_capture_init_monitor winrt_capture_init_monitor; PFN_winrt_capture_free winrt_capture_free; PFN_winrt_capture_active winrt_capture_active; @@ -129,46 +124,32 @@ static const char *get_method_name(int method) return method_name; } -static bool GetMonitorTarget(LPCWSTR device, - DISPLAYCONFIG_TARGET_DEVICE_NAME *target) +static bool GetMonitorTarget(LPCWSTR device, DISPLAYCONFIG_TARGET_DEVICE_NAME *target) { bool found = false; UINT32 numPath, numMode; - if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath, - &numMode) == ERROR_SUCCESS) { - DISPLAYCONFIG_PATH_INFO *paths = - bmalloc(numPath * sizeof(DISPLAYCONFIG_PATH_INFO)); - DISPLAYCONFIG_MODE_INFO *modes = - bmalloc(numMode * sizeof(DISPLAYCONFIG_MODE_INFO)); - if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath, paths, - &numMode, modes, - NULL) == ERROR_SUCCESS) { + if (GetDisplayConfigBufferSizes(QDC_ONLY_ACTIVE_PATHS, &numPath, &numMode) == ERROR_SUCCESS) { + DISPLAYCONFIG_PATH_INFO *paths = bmalloc(numPath * sizeof(DISPLAYCONFIG_PATH_INFO)); + DISPLAYCONFIG_MODE_INFO *modes = bmalloc(numMode * sizeof(DISPLAYCONFIG_MODE_INFO)); + if (QueryDisplayConfig(QDC_ONLY_ACTIVE_PATHS, &numPath, paths, &numMode, modes, NULL) == + ERROR_SUCCESS) { for (size_t i = 0; i < numPath; ++i) { - const DISPLAYCONFIG_PATH_INFO *const path = - &paths[i]; + const DISPLAYCONFIG_PATH_INFO *const path = &paths[i]; DISPLAYCONFIG_SOURCE_DEVICE_NAME source; - source.header.type = - DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; + source.header.type = DISPLAYCONFIG_DEVICE_INFO_GET_SOURCE_NAME; source.header.size = sizeof(source); - source.header.adapterId = - path->sourceInfo.adapterId; + source.header.adapterId = path->sourceInfo.adapterId; source.header.id = path->sourceInfo.id; - if (DisplayConfigGetDeviceInfo( - &source.header) == ERROR_SUCCESS && - wcscmp(device, source.viewGdiDeviceName) == - 0) { - target->header.type = - DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME; + if (DisplayConfigGetDeviceInfo(&source.header) == ERROR_SUCCESS && + wcscmp(device, source.viewGdiDeviceName) == 0) { + target->header.type = DISPLAYCONFIG_DEVICE_INFO_GET_TARGET_NAME; target->header.size = sizeof(*target); - target->header.adapterId = - path->sourceInfo.adapterId; + target->header.adapterId = path->sourceInfo.adapterId; target->header.id = path->targetInfo.id; - found = DisplayConfigGetDeviceInfo( - &target->header) == - ERROR_SUCCESS; + found = DisplayConfigGetDeviceInfo(&target->header) == ERROR_SUCCESS; break; } } @@ -187,11 +168,9 @@ static void GetMonitorName(HMONITOR handle, char *name, size_t count) DISPLAYCONFIG_TARGET_DEVICE_NAME target; mi.cbSize = sizeof(mi); - if (GetMonitorInfoW(handle, (LPMONITORINFO)&mi) && - GetMonitorTarget(mi.szDevice, &target)) { + if (GetMonitorInfoW(handle, (LPMONITORINFO)&mi) && GetMonitorTarget(mi.szDevice, &target)) { char *friendly_name; - os_wcs_to_utf8_ptr(target.monitorFriendlyDeviceName, 0, - &friendly_name); + os_wcs_to_utf8_ptr(target.monitorFriendlyDeviceName, 0, &friendly_name); strcpy_s(name, count, friendly_name); bfree(friendly_name); @@ -200,13 +179,11 @@ static void GetMonitorName(HMONITOR handle, char *name, size_t count) } } -static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, - LPARAM param) +static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) { UNUSED_PARAMETER(hdc); - struct duplicator_monitor_info *monitor = - (struct duplicator_monitor_info *)param; + struct duplicator_monitor_info *monitor = (struct duplicator_monitor_info *)param; bool match = false; @@ -215,18 +192,12 @@ static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, if (GetMonitorInfoA(handle, (LPMONITORINFO)&mi)) { DISPLAY_DEVICEA device; device.cb = sizeof(device); - if (EnumDisplayDevicesA(mi.szDevice, 0, &device, - EDD_GET_DEVICE_INTERFACE_NAME)) { - match = strcmp(monitor->device_id, device.DeviceID) == - 0; + if (EnumDisplayDevicesA(mi.szDevice, 0, &device, EDD_GET_DEVICE_INTERFACE_NAME)) { + match = strcmp(monitor->device_id, device.DeviceID) == 0; if (match) { - strcpy_s(monitor->id, _countof(monitor->id), - device.DeviceID); - strcpy_s(monitor->alt_id, - _countof(monitor->alt_id), - mi.szDevice); - GetMonitorName(handle, monitor->name, - _countof(monitor->name)); + strcpy_s(monitor->id, _countof(monitor->id), device.DeviceID); + strcpy_s(monitor->alt_id, _countof(monitor->alt_id), mi.szDevice); + GetMonitorName(handle, monitor->name, _countof(monitor->name)); monitor->rect = *rect; monitor->handle = handle; } @@ -236,13 +207,11 @@ static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, return !match; } -static BOOL CALLBACK enum_monitor_fallback(HMONITOR handle, HDC hdc, - LPRECT rect, LPARAM param) +static BOOL CALLBACK enum_monitor_fallback(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) { UNUSED_PARAMETER(hdc); - struct duplicator_monitor_info *monitor = - (struct duplicator_monitor_info *)param; + struct duplicator_monitor_info *monitor = (struct duplicator_monitor_info *)param; bool match = false; @@ -251,10 +220,8 @@ static BOOL CALLBACK enum_monitor_fallback(HMONITOR handle, HDC hdc, if (GetMonitorInfoA(handle, (LPMONITORINFO)&mi)) { match = strcmp(monitor->device_id, mi.szDevice) == 0; if (match) { - strcpy_s(monitor->alt_id, _countof(monitor->alt_id), - mi.szDevice); - GetMonitorName(handle, monitor->name, - _countof(monitor->name)); + strcpy_s(monitor->alt_id, _countof(monitor->alt_id), mi.szDevice); + GetMonitorName(handle, monitor->name, _countof(monitor->name)); monitor->rect = *rect; monitor->handle = handle; } @@ -263,8 +230,7 @@ static BOOL CALLBACK enum_monitor_fallback(HMONITOR handle, HDC hdc, return !match; } -static void log_settings(struct duplicator_capture *capture, - const char *monitor, LONG width, LONG height) +static void log_settings(struct duplicator_capture *capture, const char *monitor, LONG width, LONG height) { info("update settings:\n" "\tdisplay: %s (%ldx%ld)\n" @@ -274,14 +240,12 @@ static void log_settings(struct duplicator_capture *capture, "\talt_id: %s\n" "\tsetting_id: %s\n" "\tforce SDR: %s", - monitor, width, height, capture->capture_cursor ? "true" : "false", - get_method_name(capture->method), capture->id, capture->alt_id, - capture->monitor_id, capture->force_sdr ? "true" : "false"); + monitor, width, height, capture->capture_cursor ? "true" : "false", get_method_name(capture->method), + capture->id, capture->alt_id, capture->monitor_id, capture->force_sdr ? "true" : "false"); } -static enum display_capture_method -choose_method(enum display_capture_method method, bool wgc_supported, - HMONITOR monitor) +static enum display_capture_method choose_method(enum display_capture_method method, bool wgc_supported, + HMONITOR monitor) { if (!wgc_supported) method = METHOD_DXGI; @@ -297,8 +261,7 @@ choose_method(enum display_capture_method method, bool wgc_supported, method = METHOD_WGC; } else { SYSTEM_POWER_STATUS status; - if (GetSystemPowerStatus(&status) && - status.BatteryFlag < 128) { + if (GetSystemPowerStatus(&status) && status.BatteryFlag < 128) { obs_enter_graphics(); const uint32_t count = gs_get_adapter_count(); obs_leave_graphics(); @@ -319,31 +282,24 @@ static struct duplicator_monitor_info find_monitor(const char *monitor_id) strcpy_s(monitor.device_id, _countof(monitor.device_id), monitor_id); EnumDisplayMonitors(NULL, NULL, &enum_monitor, (LPARAM)&monitor); if (monitor.handle == NULL) { - EnumDisplayMonitors(NULL, NULL, &enum_monitor_fallback, - (LPARAM)&monitor); + EnumDisplayMonitors(NULL, NULL, &enum_monitor_fallback, (LPARAM)&monitor); } return monitor; } -static inline void update_settings(struct duplicator_capture *capture, - obs_data_t *settings) +static inline void update_settings(struct duplicator_capture *capture, obs_data_t *settings) { pthread_mutex_lock(&capture->update_mutex); - struct duplicator_monitor_info monitor = - find_monitor(obs_data_get_string(settings, "monitor_id")); + struct duplicator_monitor_info monitor = find_monitor(obs_data_get_string(settings, "monitor_id")); - capture->method = - choose_method((int)obs_data_get_int(settings, "method"), - wgc_supported, monitor.handle); + capture->method = choose_method((int)obs_data_get_int(settings, "method"), wgc_supported, monitor.handle); - strcpy_s(capture->monitor_id, _countof(capture->monitor_id), - monitor.device_id); + strcpy_s(capture->monitor_id, _countof(capture->monitor_id), monitor.device_id); strcpy_s(capture->id, _countof(capture->id), monitor.id); strcpy_s(capture->alt_id, _countof(capture->alt_id), monitor.alt_id); - strcpy_s(capture->monitor_name, _countof(capture->monitor_name), - monitor.name); + strcpy_s(capture->monitor_name, _countof(capture->monitor_name), monitor.name); capture->handle = monitor.handle; capture->capture_cursor = obs_data_get_bool(settings, "capture_cursor"); @@ -411,8 +367,7 @@ static void duplicator_actual_destroy(void *data) static void duplicator_capture_destroy(void *data) { - obs_queue_task(OBS_TASK_GRAPHICS, duplicator_actual_destroy, data, - false); + obs_queue_task(OBS_TASK_GRAPHICS, duplicator_actual_destroy, data, false); } static void duplicator_capture_defaults(obs_data_t *settings) @@ -445,8 +400,7 @@ static void duplicator_capture_update(void *data, obs_data_t *settings) } \ } while (false) -static bool load_winrt_imports(struct winrt_exports *exports, void *module, - const char *module_name) +static bool load_winrt_imports(struct winrt_exports *exports, void *module, const char *module_name) { bool success = true; @@ -465,8 +419,7 @@ static bool load_winrt_imports(struct winrt_exports *exports, void *module, extern bool graphics_uses_d3d11; -static void *duplicator_capture_create(obs_data_t *settings, - obs_source_t *source) +static void *duplicator_capture_create(obs_data_t *settings, obs_source_t *source) { struct duplicator_capture *capture; @@ -479,14 +432,12 @@ static void *duplicator_capture_create(obs_data_t *settings, static const char *const module = "libobs-winrt"; capture->winrt_module = os_dlopen(module); if (capture->winrt_module) { - load_winrt_imports(&capture->exports, - capture->winrt_module, module); + load_winrt_imports(&capture->exports, capture->winrt_module, module); } } update_settings(capture, settings); - log_settings(capture, capture->monitor_name, capture->logged_width, - capture->logged_height); + log_settings(capture, capture->monitor_name, capture->logged_width, capture->logged_height); return capture; } @@ -564,8 +515,7 @@ static void duplicator_capture_tick(void *data, float seconds) if (capture->method == METHOD_WGC) { if (capture->reset_wgc && capture->capture_winrt) { - capture->exports.winrt_capture_free( - capture->capture_winrt); + capture->exports.winrt_capture_free(capture->capture_winrt); capture->capture_winrt = NULL; capture->reset_wgc = false; capture->reset_timeout = RESET_INTERVAL_SEC; @@ -579,19 +529,15 @@ static void duplicator_capture_tick(void *data, float seconds) update_monitor_handle(capture); if (capture->handle) { - capture->capture_winrt = - capture->exports.winrt_capture_init_monitor( - capture->capture_cursor, - capture->handle, - capture->force_sdr); + capture->capture_winrt = capture->exports.winrt_capture_init_monitor( + capture->capture_cursor, capture->handle, capture->force_sdr); if (!capture->capture_winrt) { update_monitor_handle(capture); if (capture->handle) { capture->capture_winrt = capture->exports.winrt_capture_init_monitor( - capture->capture_cursor, - capture->handle, + capture->capture_cursor, capture->handle, capture->force_sdr); } } @@ -602,8 +548,7 @@ static void duplicator_capture_tick(void *data, float seconds) } } else { if (capture->capture_winrt) { - capture->exports.winrt_capture_free( - capture->capture_winrt); + capture->exports.winrt_capture_free(capture->capture_winrt); capture->capture_winrt = NULL; } @@ -615,23 +560,18 @@ static void duplicator_capture_tick(void *data, float seconds) update_monitor_handle(capture); if (capture->handle) { - int dxgi_index = - gs_duplicator_get_monitor_index( - capture->handle); + int dxgi_index = gs_duplicator_get_monitor_index(capture->handle); if (dxgi_index == -1) { update_monitor_handle(capture); if (capture->handle) { - dxgi_index = gs_duplicator_get_monitor_index( - capture->handle); + dxgi_index = gs_duplicator_get_monitor_index(capture->handle); } } if (dxgi_index != -1) { - capture->duplicator = - gs_duplicator_create( - dxgi_index); + capture->duplicator = gs_duplicator_create(dxgi_index); } } @@ -661,21 +601,15 @@ static void duplicator_capture_tick(void *data, float seconds) static uint32_t duplicator_capture_width(void *data) { struct duplicator_capture *capture = data; - return (capture->method == METHOD_WGC) - ? capture->exports.winrt_capture_width( - capture->capture_winrt) - : (capture->rot % 180 == 0 ? capture->width - : capture->height); + return (capture->method == METHOD_WGC) ? capture->exports.winrt_capture_width(capture->capture_winrt) + : (capture->rot % 180 == 0 ? capture->width : capture->height); } static uint32_t duplicator_capture_height(void *data) { struct duplicator_capture *capture = data; - return (capture->method == METHOD_WGC) - ? capture->exports.winrt_capture_height( - capture->capture_winrt) - : (capture->rot % 180 == 0 ? capture->height - : capture->width); + return (capture->method == METHOD_WGC) ? capture->exports.winrt_capture_height(capture->capture_winrt) + : (capture->rot % 180 == 0 ? capture->height : capture->width); } static void draw_cursor(struct duplicator_capture *capture) @@ -693,13 +627,10 @@ static void duplicator_capture_render(void *data, gs_effect_t *unused) if (capture->method == METHOD_WGC) { if (capture->capture_winrt) { - if (capture->exports.winrt_capture_active( - capture->capture_winrt)) { - capture->exports.winrt_capture_render( - capture->capture_winrt); + if (capture->exports.winrt_capture_active(capture->capture_winrt)) { + capture->exports.winrt_capture_render(capture->capture_winrt); } else { - capture->exports.winrt_capture_free( - capture->capture_winrt); + capture->exports.winrt_capture_free(capture->capture_winrt); capture->capture_winrt = NULL; } } @@ -707,8 +638,7 @@ static void duplicator_capture_render(void *data, gs_effect_t *unused) if (!capture->duplicator) return; - gs_texture_t *const texture = - gs_duplicator_get_texture(capture->duplicator); + gs_texture_t *const texture = gs_duplicator_get_texture(capture->duplicator); if (!texture) return; @@ -742,31 +672,22 @@ static void duplicator_capture_render(void *data, gs_effect_t *unused) const char *tech_name = "Draw"; float multiplier = 1.f; const enum gs_color_space current_space = gs_get_color_space(); - if (gs_duplicator_get_color_space(capture->duplicator) == - GS_CS_709_SCRGB) { + if (gs_duplicator_get_color_space(capture->duplicator) == GS_CS_709_SCRGB) { if (capture->force_sdr) { tech_name = "DrawMultiply"; const float target_nits = - (current_space == GS_CS_709_SCRGB) - ? obs_get_video_sdr_white_level() - : 80.f; - multiplier = target_nits / - gs_duplicator_get_sdr_white_level( - capture->duplicator); + (current_space == GS_CS_709_SCRGB) ? obs_get_video_sdr_white_level() : 80.f; + multiplier = target_nits / gs_duplicator_get_sdr_white_level(capture->duplicator); } else { switch (current_space) { case GS_CS_SRGB: case GS_CS_SRGB_16F: tech_name = "DrawMultiplyTonemap"; - multiplier = - 80.f / - obs_get_video_sdr_white_level(); + multiplier = 80.f / obs_get_video_sdr_white_level(); break; case GS_CS_709_EXTENDED: tech_name = "DrawMultiply"; - multiplier = - 80.f / - obs_get_video_sdr_white_level(); + multiplier = 80.f / obs_get_video_sdr_white_level(); } } } else if (current_space == GS_CS_709_SCRGB) { @@ -774,13 +695,10 @@ static void duplicator_capture_render(void *data, gs_effect_t *unused) multiplier = obs_get_video_sdr_white_level() / 80.f; } - gs_effect_t *const opaque_effect = - obs_get_base_effect(OBS_EFFECT_OPAQUE); - gs_eparam_t *multiplier_param = gs_effect_get_param_by_name( - opaque_effect, "multiplier"); + gs_effect_t *const opaque_effect = obs_get_base_effect(OBS_EFFECT_OPAQUE); + gs_eparam_t *multiplier_param = gs_effect_get_param_by_name(opaque_effect, "multiplier"); gs_effect_set_float(multiplier_param, multiplier); - gs_eparam_t *image_param = - gs_effect_get_param_by_name(opaque_effect, "image"); + gs_eparam_t *image_param = gs_effect_get_param_by_name(opaque_effect, "image"); gs_effect_set_texture_srgb(image_param, texture); while (gs_effect_loop(opaque_effect, tech_name)) { @@ -794,8 +712,7 @@ static void duplicator_capture_render(void *data, gs_effect_t *unused) gs_enable_framebuffer_srgb(previous); if (capture->capture_cursor) { - gs_effect_t *const default_effect = - obs_get_base_effect(OBS_EFFECT_DEFAULT); + gs_effect_t *const default_effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); while (gs_effect_loop(default_effect, "Draw")) { draw_cursor(capture); @@ -804,8 +721,7 @@ static void duplicator_capture_render(void *data, gs_effect_t *unused) } } -static BOOL CALLBACK enum_monitor_props(HMONITOR handle, HDC hdc, LPRECT rect, - LPARAM param) +static BOOL CALLBACK enum_monitor_props(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) { UNUSED_PARAMETER(hdc); UNUSED_PARAMETER(rect); @@ -818,40 +734,31 @@ static BOOL CALLBACK enum_monitor_props(HMONITOR handle, HDC hdc, LPRECT rect, if (GetMonitorInfoA(handle, (LPMONITORINFO)&mi)) { obs_property_t *monitor_list = (obs_property_t *)param; struct dstr monitor_desc = {0}; - dstr_printf(&monitor_desc, "%s: %dx%d @ %d,%d", monitor_name, - mi.rcMonitor.right - mi.rcMonitor.left, - mi.rcMonitor.bottom - mi.rcMonitor.top, - mi.rcMonitor.left, mi.rcMonitor.top); + dstr_printf(&monitor_desc, "%s: %dx%d @ %d,%d", monitor_name, mi.rcMonitor.right - mi.rcMonitor.left, + mi.rcMonitor.bottom - mi.rcMonitor.top, mi.rcMonitor.left, mi.rcMonitor.top); if (mi.dwFlags == MONITORINFOF_PRIMARY) dstr_catf(&monitor_desc, " (%s)", TEXT_PRIMARY_MONITOR); DISPLAY_DEVICEA device; device.cb = sizeof(device); - if (EnumDisplayDevicesA(mi.szDevice, 0, &device, - EDD_GET_DEVICE_INTERFACE_NAME)) { - obs_property_list_add_string(monitor_list, - monitor_desc.array, - device.DeviceID); + if (EnumDisplayDevicesA(mi.szDevice, 0, &device, EDD_GET_DEVICE_INTERFACE_NAME)) { + obs_property_list_add_string(monitor_list, monitor_desc.array, device.DeviceID); } else { blog(LOG_WARNING, "[duplicator-monitor-capture] EnumDisplayDevices failed for monitor (%s), falling back to szDevice", monitor_name); - obs_property_list_add_string( - monitor_list, monitor_desc.array, mi.szDevice); + obs_property_list_add_string(monitor_list, monitor_desc.array, mi.szDevice); } dstr_free(&monitor_desc); } else { - blog(LOG_WARNING, - "[duplicator-monitor-capture] GetMonitorInfo failed for monitor: %s", - monitor_name); + blog(LOG_WARNING, "[duplicator-monitor-capture] GetMonitorInfo failed for monitor: %s", monitor_name); } return TRUE; } -static void update_settings_visibility(obs_properties_t *props, - struct duplicator_capture *capture) +static void update_settings_visibility(obs_properties_t *props, struct duplicator_capture *capture) { pthread_mutex_lock(&capture->update_mutex); @@ -859,9 +766,7 @@ static void update_settings_visibility(obs_properties_t *props, const bool dxgi_options = method == METHOD_DXGI; const bool wgc_options = method == METHOD_WGC; - const bool wgc_cursor_toggle = - wgc_options && - capture->exports.winrt_capture_cursor_toggle_supported(); + const bool wgc_cursor_toggle = wgc_options && capture->exports.winrt_capture_cursor_toggle_supported(); obs_property_t *p = obs_properties_get(props, "cursor"); obs_property_set_visible(p, dxgi_options || wgc_cursor_toggle); @@ -869,9 +774,7 @@ static void update_settings_visibility(obs_properties_t *props, pthread_mutex_unlock(&capture->update_mutex); } -static bool display_capture_method_changed(obs_properties_t *props, - obs_property_t *p, - obs_data_t *settings) +static bool display_capture_method_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); @@ -893,24 +796,19 @@ static obs_properties_t *duplicator_capture_properties(void *data) obs_properties_t *props = obs_properties_create(); obs_properties_set_param(props, capture, NULL); - obs_property_t *p = obs_properties_add_list(props, "method", - TEXT_METHOD, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + obs_property_t *p = + obs_properties_add_list(props, "method", TEXT_METHOD, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(p, TEXT_METHOD_AUTO, METHOD_AUTO); obs_property_list_add_int(p, TEXT_METHOD_DXGI, METHOD_DXGI); obs_property_list_add_int(p, TEXT_METHOD_WGC, METHOD_WGC); obs_property_list_item_disable(p, 2, !wgc_supported); obs_property_set_modified_callback(p, display_capture_method_changed); - obs_property_t *monitors = obs_properties_add_list( - props, "monitor_id", TEXT_MONITOR, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + obs_property_t *monitors = obs_properties_add_list(props, "monitor_id", TEXT_MONITOR, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_STRING); if (capture && strcmp(capture->monitor_id, INVALID_DISPLAY) == 0) { - obs_property_list_add_string(monitors, - obs_module_text("SelectADisplay"), - INVALID_DISPLAY); + obs_property_list_add_string(monitors, obs_module_text("SelectADisplay"), INVALID_DISPLAY); obs_property_list_item_disable(monitors, 0, true); } @@ -922,22 +820,18 @@ static obs_properties_t *duplicator_capture_properties(void *data) return props; } -enum gs_color_space -duplicator_capture_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +enum gs_color_space duplicator_capture_get_color_space(void *data, size_t count, + const enum gs_color_space *preferred_spaces) { enum gs_color_space capture_space = GS_CS_SRGB; struct duplicator_capture *capture = data; if (capture->method == METHOD_WGC) { if (capture->capture_winrt) { - capture_space = - capture->exports.winrt_capture_get_color_space( - capture->capture_winrt); + capture_space = capture->exports.winrt_capture_get_color_space(capture->capture_winrt); } } else if (capture->duplicator && !capture->force_sdr) { - capture_space = - gs_duplicator_get_color_space(capture->duplicator); + capture_space = gs_duplicator_get_color_space(capture->duplicator); } enum gs_color_space space = capture_space; @@ -954,8 +848,7 @@ duplicator_capture_get_color_space(void *data, size_t count, struct obs_source_info duplicator_capture_info = { .id = "monitor_capture", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, .get_name = duplicator_capture_getname, .create = duplicator_capture_create, .destroy = duplicator_capture_destroy, diff --git a/plugins/win-capture/game-capture-file-init.c b/plugins/win-capture/game-capture-file-init.c index 77790615d..fdfa95e63 100644 --- a/plugins/win-capture/game-capture-file-init.c +++ b/plugins/win-capture/game-capture-file-init.c @@ -19,9 +19,8 @@ static bool has_elevation_internal() BOOL elevated = false; BOOL success; - success = AllocateAndInitializeSid(&sia, 2, SECURITY_BUILTIN_DOMAIN_RID, - DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, - 0, 0, &sid); + success = AllocateAndInitializeSid(&sia, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, + 0, &sid); if (success && sid) { CheckTokenMembership(NULL, sid, &elevated); FreeSid(sid); @@ -52,9 +51,8 @@ static bool add_aap_perms(const wchar_t *dir) bool success = false; PACL dacl; - if (GetNamedSecurityInfoW(dir, SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, - NULL, &sd) != ERROR_SUCCESS) { + if (GetNamedSecurityInfoW(dir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, &dacl, NULL, &sd) != + ERROR_SUCCESS) { goto fail; } @@ -72,8 +70,7 @@ static bool add_aap_perms(const wchar_t *dir) goto fail; } - ea.grfAccessPermissions = GENERIC_READ | GENERIC_WRITE | - GENERIC_EXECUTE; + ea.grfAccessPermissions = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE; /* BUILTIN_USERS */ ConvertStringSidToSidW(L"S-1-5-32-545", &bu_sid); @@ -84,9 +81,8 @@ static bool add_aap_perms(const wchar_t *dir) goto fail; } - if (SetNamedSecurityInfoW((wchar_t *)dir, SE_FILE_OBJECT, - DACL_SECURITY_INFORMATION, NULL, NULL, - new_dacl2, NULL) != ERROR_SUCCESS) { + if (SetNamedSecurityInfoW((wchar_t *)dir, SE_FILE_OBJECT, DACL_SECURITY_INFORMATION, NULL, NULL, new_dacl2, + NULL) != ERROR_SUCCESS) { goto fail; } @@ -125,19 +121,17 @@ static LSTATUS get_reg(HKEY hkey, LPCWSTR sub_key, LPCWSTR value_name, bool b64) status = RegOpenKeyEx(hkey, sub_key, 0, KEY_READ | flags, &key); if (status == ERROR_SUCCESS) { - status = RegQueryValueExW(key, value_name, NULL, NULL, - (LPBYTE)&val, &size); + status = RegQueryValueExW(key, value_name, NULL, NULL, (LPBYTE)&val, &size); RegCloseKey(key); } return status; } -#define get_programdata_path(path, subpath) \ - do { \ - SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, \ - SHGFP_TYPE_CURRENT, path); \ - StringCbCatW(path, sizeof(path), L"\\"); \ - StringCbCatW(path, sizeof(path), subpath); \ +#define get_programdata_path(path, subpath) \ + do { \ + SHGetFolderPathW(NULL, CSIDL_COMMON_APPDATA, NULL, SHGFP_TYPE_CURRENT, path); \ + StringCbCatW(path, sizeof(path), L"\\"); \ + StringCbCatW(path, sizeof(path), subpath); \ } while (false) #define make_filename(str, name, ext) \ @@ -160,15 +154,13 @@ char *get_hook_path(bool b64) get_programdata_path(path, L"obs-studio-hook\\"); make_filename(path, L"graphics-hook", L".dll"); - if ((b64 && programdata64_hook_exists) || - (!b64 && programdata32_hook_exists)) { + if ((b64 && programdata64_hook_exists) || (!b64 && programdata32_hook_exists)) { char *path_utf8 = NULL; os_wcs_to_utf8_ptr(path, 0, &path_utf8); return path_utf8; } - return obs_module_file(b64 ? "graphics-hook64.dll" - : "graphics-hook32.dll"); + return obs_module_file(b64 ? "graphics-hook64.dll" : "graphics-hook32.dll"); } /* ------------------------------------------------------------------------- */ @@ -255,8 +247,7 @@ static bool update_hook_file(bool b64) return true; } -#define warn(format, ...) \ - blog(LOG_WARNING, "%s: " format, "[Vulkan Capture Init]", ##__VA_ARGS__) +#define warn(format, ...) blog(LOG_WARNING, "%s: " format, "[Vulkan Capture Init]", ##__VA_ARGS__) /* Sets vulkan layer registry if it doesn't already exist */ static void init_vulkan_registry(bool b64) @@ -280,8 +271,7 @@ static void init_vulkan_registry(bool b64) } if (s == ERROR_SUCCESS && has_elevation()) { - s = RegOpenKeyEx(HKEY_CURRENT_USER, IMPLICIT_LAYERS, 0, - KEY_WRITE | flags, &key); + s = RegOpenKeyEx(HKEY_CURRENT_USER, IMPLICIT_LAYERS, 0, KEY_WRITE | flags, &key); if (s == ERROR_SUCCESS) { RegDeleteValueW(key, path); RegCloseKey(key); @@ -301,16 +291,14 @@ static void init_vulkan_registry(bool b64) HKEY type = has_elevation() ? HKEY_LOCAL_MACHINE : HKEY_CURRENT_USER; DWORD temp; - s = RegCreateKeyExW(type, IMPLICIT_LAYERS, 0, NULL, 0, - KEY_WRITE | flags, NULL, &key, &temp); + s = RegCreateKeyExW(type, IMPLICIT_LAYERS, 0, NULL, 0, KEY_WRITE | flags, NULL, &key, &temp); if (s != ERROR_SUCCESS) { warn("Failed to create registry key"); goto finish; } DWORD zero = 0; - s = RegSetValueExW(key, path, 0, REG_DWORD, (const BYTE *)&zero, - sizeof(zero)); + s = RegSetValueExW(key, path, 0, REG_DWORD, (const BYTE *)&zero, sizeof(zero)); if (s != ERROR_SUCCESS) { warn("Failed to set registry value"); } diff --git a/plugins/win-capture/game-capture.c b/plugins/win-capture/game-capture.c index 0c27047ff..e0cba57b0 100644 --- a/plugins/win-capture/game-capture.c +++ b/plugins/win-capture/game-capture.c @@ -20,9 +20,8 @@ #include "audio-helpers.h" #include "nt-stuff.h" -#define do_log(level, format, ...) \ - blog(level, "[game-capture: '%s'] " format, \ - obs_source_get_name(gc->source), ##__VA_ARGS__) +#define do_log(level, format, ...) \ + blog(level, "[game-capture: '%s'] " format, obs_source_get_name(gc->source), ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -90,18 +89,9 @@ #define DEFAULT_RETRY_INTERVAL 2.0f #define ERROR_RETRY_INTERVAL 4.0f -enum capture_mode { - CAPTURE_MODE_ANY, - CAPTURE_MODE_WINDOW, - CAPTURE_MODE_HOTKEY -}; +enum capture_mode { CAPTURE_MODE_ANY, CAPTURE_MODE_WINDOW, CAPTURE_MODE_HOTKEY }; -enum hook_rate { - HOOK_RATE_SLOW, - HOOK_RATE_NORMAL, - HOOK_RATE_FAST, - HOOK_RATE_FASTEST -}; +enum hook_rate { HOOK_RATE_SLOW, HOOK_RATE_NORMAL, HOOK_RATE_FAST, HOOK_RATE_FASTEST }; #define RGBA10A2_SPACE_SRGB "srgb" #define RGBA10A2_SPACE_2100PQ "2100pq" @@ -124,8 +114,7 @@ struct game_capture_config { bool capture_audio; }; -typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_SetThreadDpiAwarenessContext)( - DPI_AWARENESS_CONTEXT); +typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_GetThreadDpiAwarenessContext)(VOID); typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_GetWindowDpiAwarenessContext)(HWND); @@ -214,13 +203,11 @@ static inline bool use_anticheat(struct game_capture *gc) return gc->config.anticheat_hook && !gc->is_app; } -static inline HANDLE open_mutex_plus_id(struct game_capture *gc, - const wchar_t *name, DWORD id) +static inline HANDLE open_mutex_plus_id(struct game_capture *gc, const wchar_t *name, DWORD id) { wchar_t new_name[64]; _snwprintf(new_name, 64, L"%s%lu", name, id); - return gc->is_app ? open_app_mutex(gc->app_sid, new_name) - : open_mutex(new_name); + return gc->is_app ? open_app_mutex(gc->app_sid, new_name) : open_mutex(new_name); } static inline HANDLE open_mutex_gc(struct game_capture *gc, const wchar_t *name) @@ -228,13 +215,11 @@ static inline HANDLE open_mutex_gc(struct game_capture *gc, const wchar_t *name) return open_mutex_plus_id(gc, name, gc->process_id); } -static inline HANDLE open_event_plus_id(struct game_capture *gc, - const wchar_t *name, DWORD id) +static inline HANDLE open_event_plus_id(struct game_capture *gc, const wchar_t *name, DWORD id) { wchar_t new_name[64]; _snwprintf(new_name, 64, L"%s%lu", name, id); - return gc->is_app ? open_app_event(gc->app_sid, new_name) - : open_event(new_name); + return gc->is_app ? open_app_event(gc->app_sid, new_name) : open_event(new_name); } static inline HANDLE open_event_gc(struct game_capture *gc, const wchar_t *name) @@ -242,16 +227,14 @@ static inline HANDLE open_event_gc(struct game_capture *gc, const wchar_t *name) return open_event_plus_id(gc, name, gc->process_id); } -static inline HANDLE open_map_plus_id(struct game_capture *gc, - const wchar_t *name, DWORD id) +static inline HANDLE open_map_plus_id(struct game_capture *gc, const wchar_t *name, DWORD id) { wchar_t new_name[64]; swprintf(new_name, 64, L"%s%lu", name, id); debug("map id: %S", new_name); - return gc->is_app ? open_app_map(gc->app_sid, new_name) - : OpenFileMappingW(GC_MAPPING_FLAGS, false, new_name); + return gc->is_app ? open_app_map(gc->app_sid, new_name) : OpenFileMappingW(GC_MAPPING_FLAGS, false, new_name); } static inline HANDLE open_hook_info(struct game_capture *gc) @@ -299,14 +282,13 @@ static inline HMODULE kernel32(void) return kernel32_handle; } -static inline HANDLE open_process(DWORD desired_access, bool inherit_handle, - DWORD process_id) +static inline HANDLE open_process(DWORD desired_access, bool inherit_handle, DWORD process_id) { typedef HANDLE(WINAPI * PFN_OpenProcess)(DWORD, BOOL, DWORD); static PFN_OpenProcess open_process_proc = NULL; if (!open_process_proc) - open_process_proc = (PFN_OpenProcess)ms_get_obfuscated_func( - kernel32(), "NuagUykjcxr", 0x1B694B59451ULL); + open_process_proc = + (PFN_OpenProcess)ms_get_obfuscated_func(kernel32(), "NuagUykjcxr", 0x1B694B59451ULL); return open_process_proc(desired_access, inherit_handle, process_id); } @@ -374,8 +356,7 @@ static void stop_capture(struct game_capture *gc) // if it was previously capturing, send an unhooked signal if (gc->capturing) { - signal_handler_t *sh = - obs_source_get_signal_handler(gc->source); + signal_handler_t *sh = obs_source_get_signal_handler(gc->source); calldata_t data = {0}; calldata_set_ptr(&data, "source", gc->source); signal_handler_signal(sh, "unhooked", &data); @@ -412,8 +393,7 @@ static void game_capture_destroy(void *data) destroy_audio_source(gc->source, &gc->audio_source); signal_handler_t *sh = obs_source_get_signal_handler(gc->source); - signal_handler_disconnect(sh, "rename", rename_audio_source, - &gc->audio_source); + signal_handler_disconnect(sh, "rename", rename_audio_source, &gc->audio_source); if (gc->hotkey_pair) obs_hotkey_pair_unregister(gc->hotkey_pair); @@ -435,13 +415,11 @@ static inline bool using_older_non_mode_format(obs_data_t *settings) !obs_data_has_user_value(settings, SETTING_MODE); } -static inline void get_config(struct game_capture_config *cfg, - obs_data_t *settings, const char *window) +static inline void get_config(struct game_capture_config *cfg, obs_data_t *settings, const char *window) { const char *mode_str = NULL; - ms_build_window_strings(window, &cfg->class, &cfg->title, - &cfg->executable); + ms_build_window_strings(window, &cfg->class, &cfg->title, &cfg->executable); if (using_older_non_mode_format(settings)) { bool any = obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN); @@ -457,25 +435,16 @@ static inline void get_config(struct game_capture_config *cfg, else cfg->mode = CAPTURE_MODE_ANY; - cfg->priority = (enum window_priority)obs_data_get_int( - settings, SETTING_WINDOW_PRIORITY); + cfg->priority = (enum window_priority)obs_data_get_int(settings, SETTING_WINDOW_PRIORITY); cfg->force_shmem = obs_data_get_bool(settings, SETTING_COMPATIBILITY); cfg->cursor = obs_data_get_bool(settings, SETTING_CURSOR); - cfg->allow_transparency = - obs_data_get_bool(settings, SETTING_TRANSPARENCY); - cfg->premultiplied_alpha = - obs_data_get_bool(settings, SETTING_PREMULTIPLIED_ALPHA); - cfg->limit_framerate = - obs_data_get_bool(settings, SETTING_LIMIT_FRAMERATE); - cfg->capture_overlays = - obs_data_get_bool(settings, SETTING_CAPTURE_OVERLAYS); - cfg->anticheat_hook = - obs_data_get_bool(settings, SETTING_ANTI_CHEAT_HOOK); - cfg->hook_rate = - (enum hook_rate)obs_data_get_int(settings, SETTING_HOOK_RATE); - cfg->is_10a2_2100pq = - strcmp(obs_data_get_string(settings, SETTING_RGBA10A2_SPACE), - "2100pq") == 0; + cfg->allow_transparency = obs_data_get_bool(settings, SETTING_TRANSPARENCY); + cfg->premultiplied_alpha = obs_data_get_bool(settings, SETTING_PREMULTIPLIED_ALPHA); + cfg->limit_framerate = obs_data_get_bool(settings, SETTING_LIMIT_FRAMERATE); + cfg->capture_overlays = obs_data_get_bool(settings, SETTING_CAPTURE_OVERLAYS); + cfg->anticheat_hook = obs_data_get_bool(settings, SETTING_ANTI_CHEAT_HOOK); + cfg->hook_rate = (enum hook_rate)obs_data_get_int(settings, SETTING_HOOK_RATE); + cfg->is_10a2_2100pq = strcmp(obs_data_get_string(settings, SETTING_RGBA10A2_SPACE), "2100pq") == 0; cfg->capture_audio = obs_data_get_bool(settings, SETTING_CAPTURE_AUDIO); } @@ -487,17 +456,14 @@ static inline int s_cmp(const char *str1, const char *str2) return strcmp(str1, str2); } -static inline bool capture_needs_reset(struct game_capture_config *cfg1, - struct game_capture_config *cfg2) +static inline bool capture_needs_reset(struct game_capture_config *cfg1, struct game_capture_config *cfg2) { if (cfg1->mode != cfg2->mode) { return true; } else if (cfg1->mode == CAPTURE_MODE_WINDOW && - (s_cmp(cfg1->class, cfg2->class) != 0 || - s_cmp(cfg1->title, cfg2->title) != 0 || - s_cmp(cfg1->executable, cfg2->executable) != 0 || - cfg1->priority != cfg2->priority)) { + (s_cmp(cfg1->class, cfg2->class) != 0 || s_cmp(cfg1->title, cfg2->title) != 0 || + s_cmp(cfg1->executable, cfg2->executable) != 0 || cfg1->priority != cfg2->priority)) { return true; } else if (cfg1->force_shmem != cfg2->force_shmem) { @@ -513,8 +479,7 @@ static inline bool capture_needs_reset(struct game_capture_config *cfg1, return false; } -static bool hotkey_start(void *data, obs_hotkey_pair_id id, - obs_hotkey_t *hotkey, bool pressed) +static bool hotkey_start(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -523,8 +488,7 @@ static bool hotkey_start(void *data, obs_hotkey_pair_id id, if (pressed && gc->config.mode == CAPTURE_MODE_HOTKEY) { info("Activate hotkey pressed"); - os_atomic_set_long(&gc->hotkey_window, - (long)(uintptr_t)GetForegroundWindow()); + os_atomic_set_long(&gc->hotkey_window, (long)(uintptr_t)GetForegroundWindow()); os_atomic_set_bool(&gc->deactivate_hook, true); os_atomic_set_bool(&gc->activate_hook_now, true); } @@ -532,8 +496,7 @@ static bool hotkey_start(void *data, obs_hotkey_pair_id id, return true; } -static bool hotkey_stop(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, - bool pressed) +static bool hotkey_stop(void *data, obs_hotkey_pair_id id, obs_hotkey_t *hotkey, bool pressed) { UNUSED_PARAMETER(id); UNUSED_PARAMETER(hotkey); @@ -572,16 +535,14 @@ static void game_capture_update(void *data, obs_data_t *settings) struct game_capture *gc = data; struct game_capture_config cfg; bool reset_capture = false; - const char *window = - obs_data_get_string(settings, SETTING_CAPTURE_WINDOW); + const char *window = obs_data_get_string(settings, SETTING_CAPTURE_WINDOW); get_config(&cfg, settings, window); reset_capture = capture_needs_reset(&cfg, &gc->config); gc->error_acquiring = false; - if (cfg.mode == CAPTURE_MODE_HOTKEY && - gc->config.mode != CAPTURE_MODE_HOTKEY) { + if (cfg.mode == CAPTURE_MODE_HOTKEY && gc->config.mode != CAPTURE_MODE_HOTKEY) { gc->activate_hook = false; } else { gc->activate_hook = !!window && !!*window; @@ -589,8 +550,7 @@ static void game_capture_update(void *data, obs_data_t *settings) free_config(&gc->config); gc->config = cfg; - gc->retry_interval = DEFAULT_RETRY_INTERVAL * - hook_rate_to_float(gc->config.hook_rate); + gc->retry_interval = DEFAULT_RETRY_INTERVAL * hook_rate_to_float(gc->config.hook_rate); gc->wait_for_target_startup = false; gc->is_10a2_2100pq = gc->config.is_10a2_2100pq; @@ -614,8 +574,7 @@ static void game_capture_update(void *data, obs_data_t *settings) } /* Linked audio capture source stuff */ - setup_audio_source(gc->source, &gc->audio_source, - cfg.mode == CAPTURE_MODE_WINDOW ? window : NULL, + setup_audio_source(gc->source, &gc->audio_source, cfg.mode == CAPTURE_MODE_WINDOW ? window : NULL, cfg.capture_audio, cfg.priority); } @@ -629,55 +588,36 @@ static void *game_capture_create(obs_data_t *settings, obs_source_t *source) gc->source = source; gc->initial_config = true; - gc->retry_interval = DEFAULT_RETRY_INTERVAL * - hook_rate_to_float(gc->config.hook_rate); - gc->hotkey_pair = obs_hotkey_pair_register_source( - gc->source, HOTKEY_START, TEXT_HOTKEY_START, HOTKEY_STOP, - TEXT_HOTKEY_STOP, hotkey_start, hotkey_stop, gc, gc); + gc->retry_interval = DEFAULT_RETRY_INTERVAL * hook_rate_to_float(gc->config.hook_rate); + gc->hotkey_pair = obs_hotkey_pair_register_source(gc->source, HOTKEY_START, TEXT_HOTKEY_START, HOTKEY_STOP, + TEXT_HOTKEY_STOP, hotkey_start, hotkey_stop, gc, gc); const HMODULE hModuleUser32 = GetModuleHandle(L"User32.dll"); if (hModuleUser32) { - PFN_SetThreadDpiAwarenessContext - set_thread_dpi_awareness_context = - (PFN_SetThreadDpiAwarenessContext)GetProcAddress( - hModuleUser32, - "SetThreadDpiAwarenessContext"); - PFN_GetThreadDpiAwarenessContext - get_thread_dpi_awareness_context = - (PFN_GetThreadDpiAwarenessContext)GetProcAddress( - hModuleUser32, - "GetThreadDpiAwarenessContext"); - PFN_GetWindowDpiAwarenessContext - get_window_dpi_awareness_context = - (PFN_GetWindowDpiAwarenessContext)GetProcAddress( - hModuleUser32, - "GetWindowDpiAwarenessContext"); - if (set_thread_dpi_awareness_context && - get_thread_dpi_awareness_context && + PFN_SetThreadDpiAwarenessContext set_thread_dpi_awareness_context = + (PFN_SetThreadDpiAwarenessContext)GetProcAddress(hModuleUser32, "SetThreadDpiAwarenessContext"); + PFN_GetThreadDpiAwarenessContext get_thread_dpi_awareness_context = + (PFN_GetThreadDpiAwarenessContext)GetProcAddress(hModuleUser32, "GetThreadDpiAwarenessContext"); + PFN_GetWindowDpiAwarenessContext get_window_dpi_awareness_context = + (PFN_GetWindowDpiAwarenessContext)GetProcAddress(hModuleUser32, "GetWindowDpiAwarenessContext"); + if (set_thread_dpi_awareness_context && get_thread_dpi_awareness_context && get_window_dpi_awareness_context) { - gc->set_thread_dpi_awareness_context = - set_thread_dpi_awareness_context; - gc->get_thread_dpi_awareness_context = - get_thread_dpi_awareness_context; - gc->get_window_dpi_awareness_context = - get_window_dpi_awareness_context; + gc->set_thread_dpi_awareness_context = set_thread_dpi_awareness_context; + gc->get_thread_dpi_awareness_context = get_thread_dpi_awareness_context; + gc->get_window_dpi_awareness_context = get_window_dpi_awareness_context; } } signal_handler_t *sh = obs_source_get_signal_handler(source); signal_handler_add(sh, "void unhooked(ptr source)"); - signal_handler_add( - sh, - "void hooked(ptr source, string title, string class, string executable)"); + signal_handler_add(sh, "void hooked(ptr source, string title, string class, string executable)"); proc_handler_t *ph = obs_source_get_proc_handler(source); - proc_handler_add( - ph, - "void get_hooked(out bool hooked, out string title, out string class, out string executable)", - game_capture_get_hooked, gc); + proc_handler_add(ph, + "void get_hooked(out bool hooked, out string title, out string class, out string executable)", + game_capture_get_hooked, gc); - signal_handler_connect(sh, "rename", rename_audio_source, - &gc->audio_source); + signal_handler_connect(sh, "rename", rename_audio_source, &gc->audio_source); game_capture_update(gc, settings); return gc; @@ -688,8 +628,7 @@ static void *game_capture_create(obs_data_t *settings, obs_source_t *source) "that the OBS installation folder is excluded/ignored in the " \ "settings of the security software you are using." -static bool check_file_integrity(struct game_capture *gc, const char *file, - const char *name) +static bool check_file_integrity(struct game_capture *gc, const char *file, const char *name) { DWORD error; HANDLE handle; @@ -705,8 +644,7 @@ static bool check_file_integrity(struct game_capture *gc, const char *file, return false; } - handle = CreateFileW(w_file, GENERIC_READ | GENERIC_EXECUTE, - FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); + handle = CreateFileW(w_file, GENERIC_READ | GENERIC_EXECUTE, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL); bfree(w_file); @@ -719,11 +657,9 @@ static bool check_file_integrity(struct game_capture *gc, const char *file, if (error == ERROR_FILE_NOT_FOUND) { warn("Game capture file '%s' not found." STOP_BEING_BAD, file); } else if (error == ERROR_ACCESS_DENIED) { - warn("Game capture file '%s' could not be loaded." STOP_BEING_BAD, - file); + warn("Game capture file '%s' could not be loaded." STOP_BEING_BAD, file); } else { - warn("Game capture file '%s' could not be loaded: %lu." STOP_BEING_BAD, - file, error); + warn("Game capture file '%s' could not be loaded: %lu." STOP_BEING_BAD, file, error); } return false; @@ -755,8 +691,7 @@ static inline bool is_64bit_process(HANDLE process) static inline bool open_target_process(struct game_capture *gc) { - gc->target_process = open_process( - PROCESS_QUERY_INFORMATION | SYNCHRONIZE, false, gc->process_id); + gc->target_process = open_process(PROCESS_QUERY_INFORMATION | SYNCHRONIZE, false, gc->process_id); if (!gc->target_process) { warn("could not open process: %s", gc->config.executable); return false; @@ -775,9 +710,8 @@ static inline bool init_keepalive(struct game_capture *gc) wchar_t new_name[64]; swprintf(new_name, 64, WINDOW_HOOK_KEEPALIVE L"%lu", gc->process_id); - gc->keepalive_mutex = gc->is_app - ? create_app_mutex(gc->app_sid, new_name) - : CreateMutexW(NULL, false, new_name); + gc->keepalive_mutex = gc->is_app ? create_app_mutex(gc->app_sid, new_name) + : CreateMutexW(NULL, false, new_name); if (!gc->keepalive_mutex) { warn("Failed to create keepalive mutex: %lu", GetLastError()); return false; @@ -799,8 +733,7 @@ static inline bool init_texture_mutexes(struct game_capture *gc) info("hook not loaded yet, retrying.."); } } else { - warn("failed to open texture mutexes: %lu", - GetLastError()); + warn("failed to open texture mutexes: %lu", GetLastError()); } return false; } @@ -813,8 +746,7 @@ static inline bool attempt_existing_hook(struct game_capture *gc) { gc->hook_restart = open_event_gc(gc, EVENT_CAPTURE_RESTART); if (gc->hook_restart) { - debug("existing hook found, signaling process: %s", - gc->config.executable); + debug("existing hook found, signaling process: %s", gc->config.executable); SetEvent(gc->hook_restart); return true; } @@ -828,8 +760,7 @@ static inline void reset_frame_interval(struct game_capture *gc) uint64_t interval = 0; if (obs_get_video_info(&ovi)) { - interval = - util_mul_div64(ovi.fps_den, 1000000000ULL, ovi.fps_num); + interval = util_mul_div64(ovi.fps_den, 1000000000ULL, ovi.fps_num); /* Always limit capture framerate to some extent. If a game * running at 900 FPS is being captured without some sort of @@ -846,17 +777,14 @@ static inline bool init_hook_info(struct game_capture *gc) { gc->global_hook_info_map = open_hook_info(gc); if (!gc->global_hook_info_map) { - warn("init_hook_info: get_hook_info failed: %lu", - GetLastError()); + warn("init_hook_info: get_hook_info failed: %lu", GetLastError()); return false; } - gc->global_hook_info = MapViewOfFile(gc->global_hook_info_map, - FILE_MAP_ALL_ACCESS, 0, 0, - sizeof(*gc->global_hook_info)); + gc->global_hook_info = + MapViewOfFile(gc->global_hook_info_map, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(*gc->global_hook_info)); if (!gc->global_hook_info) { - warn("init_hook_info: failed to map data view: %lu", - GetLastError()); + warn("init_hook_info: failed to map data view: %lu", GetLastError()); return false; } @@ -865,8 +793,7 @@ static inline bool init_hook_info(struct game_capture *gc) "(multi-adapter compatibility mode)"); } - gc->global_hook_info->offsets = gc->process_is_64bit ? offsets64 - : offsets32; + gc->global_hook_info->offsets = gc->process_is_64bit ? offsets64 : offsets32; gc->global_hook_info->capture_overlay = gc->config.capture_overlays; gc->global_hook_info->force_shmem = gc->config.force_shmem; gc->global_hook_info->UNUSED_use_scale = false; @@ -905,16 +832,12 @@ static inline bool init_pipe(struct game_capture *gc) static inline int inject_library(HANDLE process, const wchar_t *dll) { - return inject_library_obf(process, dll, "D|hkqkW`kl{k\\osofj", - 0xa178ef3655e5ade7, "[uawaRzbhh{tIdkj~~", - 0x561478dbd824387c, "[fr}pboIe`dlN}", - 0x395bfbc9833590fd, "\\`zs}gmOzhhBq", - 0x12897dd89168789a, "GbfkDaezbp~X", - 0x76aff7238788f7db); + return inject_library_obf(process, dll, "D|hkqkW`kl{k\\osofj", 0xa178ef3655e5ade7, "[uawaRzbhh{tIdkj~~", + 0x561478dbd824387c, "[fr}pboIe`dlN}", 0x395bfbc9833590fd, "\\`zs}gmOzhhBq", + 0x12897dd89168789a, "GbfkDaezbp~X", 0x76aff7238788f7db); } -static inline bool hook_direct(struct game_capture *gc, - const char *hook_path_rel) +static inline bool hook_direct(struct game_capture *gc, const char *hook_path_rel) { wchar_t hook_path_abs_w[MAX_PATH]; wchar_t *hook_path_rel_w; @@ -938,8 +861,7 @@ static inline bool hook_direct(struct game_capture *gc, process = open_process(PROCESS_ALL_ACCESS, false, gc->process_id); if (!process) { - warn("hook_direct: could not open process: %s (%lu)", - gc->config.executable, GetLastError()); + warn("hook_direct: could not open process: %s (%lu)", gc->config.executable, GetLastError()); return false; } @@ -954,9 +876,7 @@ static inline bool hook_direct(struct game_capture *gc, return true; } -static inline bool create_inject_process(struct game_capture *gc, - const char *inject_path, - const char *hook_dll) +static inline bool create_inject_process(struct game_capture *gc, const char *inject_path, const char *hook_dll) { wchar_t *command_line_w = malloc(4096 * sizeof(wchar_t)); wchar_t *inject_path_w; @@ -971,19 +891,16 @@ static inline bool create_inject_process(struct game_capture *gc, si.cb = sizeof(si); - swprintf(command_line_w, 4096, L"\"%s\" \"%s\" %lu %lu", inject_path_w, - hook_dll_w, (unsigned long)anti_cheat, + swprintf(command_line_w, 4096, L"\"%s\" \"%s\" %lu %lu", inject_path_w, hook_dll_w, (unsigned long)anti_cheat, anti_cheat ? gc->thread_id : gc->process_id); - success = !!CreateProcessW(inject_path_w, command_line_w, NULL, NULL, - false, CREATE_NO_WINDOW, NULL, NULL, &si, + success = !!CreateProcessW(inject_path_w, command_line_w, NULL, NULL, false, CREATE_NO_WINDOW, NULL, NULL, &si, &pi); if (success) { CloseHandle(pi.hThread); gc->injector_process = pi.hProcess; } else { - warn("Failed to create inject helper process: %lu", - GetLastError()); + warn("Failed to create inject helper process: %lu", GetLastError()); } free(command_line_w); @@ -1026,8 +943,7 @@ static inline bool inject_hook(struct game_capture *gc) info("using direct hook"); success = hook_direct(gc, hook_path); } else { - info("using helper (%s hook)", - use_anticheat(gc) ? "compatibility" : "direct"); + info("using helper (%s hook)", use_anticheat(gc) ? "compatibility" : "direct"); success = create_inject_process(gc, inject_path, hook_path); } @@ -1093,8 +1009,7 @@ static bool init_hook(struct game_capture *gc) if (gc->config.mode == CAPTURE_MODE_ANY) { if (ms_get_window_exe(&exe, gc->next_window)) { - info("attempting to hook fullscreen process: %s", - exe.array); + info("attempting to hook fullscreen process: %s", exe.array); } } else { if (ms_get_window_exe(&exe, gc->next_window)) { @@ -1153,8 +1068,7 @@ static void setup_window(struct game_capture *gc, HWND window) GetWindowThreadProcessId(window, &gc->process_id); if (gc->process_id) { - process = open_process(PROCESS_QUERY_INFORMATION, false, - gc->process_id); + process = open_process(PROCESS_QUERY_INFORMATION, false, gc->process_id); if (process) { gc->is_app = is_app(process); if (gc->is_app) { @@ -1177,8 +1091,7 @@ static void setup_window(struct game_capture *gc, HWND window) * (such as steam) need a little bit of time to load. ultimately this * helps prevent crashes */ if (gc->wait_for_target_startup) { - gc->retry_interval = - 3.0f * hook_rate_to_float(gc->config.hook_rate); + gc->retry_interval = 3.0f * hook_rate_to_float(gc->config.hook_rate); gc->wait_for_target_startup = false; } else { gc->next_window = window; @@ -1218,9 +1131,7 @@ static void get_fullscreen_window(struct game_capture *gc) return; } - if (rect.left == mi.rcMonitor.left && - rect.right == mi.rcMonitor.right && - rect.bottom == mi.rcMonitor.bottom && + if (rect.left == mi.rcMonitor.left && rect.right == mi.rcMonitor.right && rect.bottom == mi.rcMonitor.bottom && rect.top == mi.rcMonitor.top) { setup_window(gc, window); } else { @@ -1237,8 +1148,7 @@ static void get_selected_window(struct game_capture *gc) os_utf8_to_wcs(gc->class.array, 0, class_w, 512); window = FindWindowW(class_w, NULL); } else { - window = ms_find_window(INCLUDE_MINIMIZED, gc->priority, - gc->class.array, gc->title.array, + window = ms_find_window(INCLUDE_MINIMIZED, gc->priority, gc->class.array, gc->title.array, gc->executable.array); } @@ -1258,8 +1168,7 @@ static void try_hook(struct game_capture *gc) } if (gc->next_window) { - gc->thread_id = GetWindowThreadProcessId(gc->next_window, - &gc->process_id); + gc->thread_id = GetWindowThreadProcessId(gc->next_window, &gc->process_id); // Make sure we never try to hook ourselves (projector) if (gc->process_id == GetCurrentProcessId()) @@ -1298,8 +1207,7 @@ static inline bool init_events(struct game_capture *gc) if (!gc->hook_stop) { gc->hook_stop = open_event_gc(gc, EVENT_CAPTURE_STOP); if (!gc->hook_stop) { - warn("init_events: failed to get hook_stop event: %lu", - GetLastError()); + warn("init_events: failed to get hook_stop event: %lu", GetLastError()); return false; } } @@ -1307,8 +1215,7 @@ static inline bool init_events(struct game_capture *gc) if (!gc->hook_init) { gc->hook_init = open_event_gc(gc, EVENT_HOOK_INIT); if (!gc->hook_init) { - warn("init_events: failed to get hook_init event: %lu", - GetLastError()); + warn("init_events: failed to get hook_init event: %lu", GetLastError()); return false; } } @@ -1316,8 +1223,7 @@ static inline bool init_events(struct game_capture *gc) if (!gc->hook_ready) { gc->hook_ready = open_event_gc(gc, EVENT_HOOK_READY); if (!gc->hook_ready) { - warn("init_events: failed to get hook_ready event: %lu", - GetLastError()); + warn("init_events: failed to get hook_ready event: %lu", GetLastError()); return false; } } @@ -1325,8 +1231,7 @@ static inline bool init_events(struct game_capture *gc) if (!gc->hook_exit) { gc->hook_exit = open_event_gc(gc, EVENT_HOOK_EXIT); if (!gc->hook_exit) { - warn("init_events: failed to get hook_exit event: %lu", - GetLastError()); + warn("init_events: failed to get hook_exit event: %lu", GetLastError()); return false; } } @@ -1339,11 +1244,9 @@ enum capture_result { CAPTURE_FAIL, CAPTURE_RETRY, CAPTURE_SUCCESS }; static inline bool init_data_map(struct game_capture *gc, HWND window) { wchar_t name[64]; - swprintf(name, 64, SHMEM_TEXTURE "_%" PRIu64 "_", - (uint64_t)(uintptr_t)window); + swprintf(name, 64, SHMEM_TEXTURE "_%" PRIu64 "_", (uint64_t)(uintptr_t)window); - gc->hook_data_map = - open_map_plus_id(gc, name, gc->global_hook_info->map_id); + gc->hook_data_map = open_map_plus_id(gc, name, gc->global_hook_info->map_id); return !!gc->hook_data_map; } @@ -1383,11 +1286,9 @@ static inline enum capture_result init_capture_data(struct game_capture *gc) return CAPTURE_FAIL; } - gc->data = MapViewOfFile(gc->hook_data_map, FILE_MAP_ALL_ACCESS, 0, 0, - gc->global_hook_info->map_size); + gc->data = MapViewOfFile(gc->hook_data_map, FILE_MAP_ALL_ACCESS, 0, 0, gc->global_hook_info->map_size); if (!gc->data) { - warn("init_capture_data: failed to map data view: %lu", - GetLastError()); + warn("init_capture_data: failed to map data view: %lu", GetLastError()); return CAPTURE_FAIL; } @@ -1404,8 +1305,7 @@ static inline uint32_t convert_6_to_8bit(uint16_t val) return (uint32_t)((double)(val & 0x3F) * (255.0 / 63.0)); } -static void copy_b5g6r5_tex(struct game_capture *gc, int cur_texture, - uint8_t *data, uint32_t pitch) +static void copy_b5g6r5_tex(struct game_capture *gc, int cur_texture, uint8_t *data, uint32_t pitch) { uint8_t *input = gc->texture_buffers[cur_texture]; uint32_t gc_cx = gc->cx; @@ -1421,8 +1321,7 @@ static void copy_b5g6r5_tex(struct game_capture *gc, int cur_texture, __m128i pixels_result; __m128i *pixels_dest; - __m128i *pixels_src = - (__m128i *)(row + x * sizeof(uint16_t)); + __m128i *pixels_src = (__m128i *)(row + x * sizeof(uint16_t)); __m128i pixels = _mm_load_si128(pixels_src); __m128i zero = _mm_setzero_si128(); @@ -1436,64 +1335,50 @@ static void copy_b5g6r5_tex(struct game_capture *gc, int cur_texture, __m128i red_channel_mask = _mm_set1_epi32(0x0000F800); __m128i red_offset = _mm_set1_epi32(0x00000300); - pixels_blue = - _mm_and_si128(pixels_low, blue_channel_mask); + pixels_blue = _mm_and_si128(pixels_low, blue_channel_mask); pixels_blue = _mm_slli_epi32(pixels_blue, 3); pixels_blue = _mm_add_epi32(pixels_blue, blue_offset); - pixels_green = - _mm_and_si128(pixels_low, green_channel_mask); - pixels_green = - _mm_add_epi32(pixels_green, green_offset); + pixels_green = _mm_and_si128(pixels_low, green_channel_mask); + pixels_green = _mm_add_epi32(pixels_green, green_offset); pixels_green = _mm_slli_epi32(pixels_green, 5); - pixels_red = - _mm_and_si128(pixels_low, red_channel_mask); + pixels_red = _mm_and_si128(pixels_low, red_channel_mask); pixels_red = _mm_add_epi32(pixels_red, red_offset); pixels_red = _mm_slli_epi32(pixels_red, 8); pixels_result = _mm_set1_epi32(0xFF000000); - pixels_result = - _mm_or_si128(pixels_result, pixels_blue); - pixels_result = - _mm_or_si128(pixels_result, pixels_green); + pixels_result = _mm_or_si128(pixels_result, pixels_blue); + pixels_result = _mm_or_si128(pixels_result, pixels_green); pixels_result = _mm_or_si128(pixels_result, pixels_red); pixels_dest = (__m128i *)(out + x * sizeof(uint32_t)); _mm_store_si128(pixels_dest, pixels_result); - pixels_blue = - _mm_and_si128(pixels_high, blue_channel_mask); + pixels_blue = _mm_and_si128(pixels_high, blue_channel_mask); pixels_blue = _mm_slli_epi32(pixels_blue, 3); pixels_blue = _mm_add_epi32(pixels_blue, blue_offset); - pixels_green = - _mm_and_si128(pixels_high, green_channel_mask); - pixels_green = - _mm_add_epi32(pixels_green, green_offset); + pixels_green = _mm_and_si128(pixels_high, green_channel_mask); + pixels_green = _mm_add_epi32(pixels_green, green_offset); pixels_green = _mm_slli_epi32(pixels_green, 5); - pixels_red = - _mm_and_si128(pixels_high, red_channel_mask); + pixels_red = _mm_and_si128(pixels_high, red_channel_mask); pixels_red = _mm_add_epi32(pixels_red, red_offset); pixels_red = _mm_slli_epi32(pixels_red, 8); pixels_result = _mm_set1_epi32(0xFF000000); - pixels_result = - _mm_or_si128(pixels_result, pixels_blue); - pixels_result = - _mm_or_si128(pixels_result, pixels_green); + pixels_result = _mm_or_si128(pixels_result, pixels_blue); + pixels_result = _mm_or_si128(pixels_result, pixels_green); pixels_result = _mm_or_si128(pixels_result, pixels_red); - pixels_dest = - (__m128i *)(out + (x + 4) * sizeof(uint32_t)); + pixels_dest = (__m128i *)(out + (x + 4) * sizeof(uint32_t)); _mm_store_si128(pixels_dest, pixels_result); } } } -static void copy_b5g5r5a1_tex(struct game_capture *gc, int cur_texture, - uint8_t *data, uint32_t pitch) +static void copy_b5g5r5a1_tex(struct game_capture *gc, int cur_texture, uint8_t *data, uint32_t pitch) { uint8_t *input = gc->texture_buffers[cur_texture]; uint32_t gc_cx = gc->cx; @@ -1505,13 +1390,11 @@ static void copy_b5g5r5a1_tex(struct game_capture *gc, int cur_texture, uint8_t *out = data + (pitch * y); for (size_t x = 0; x < gc_cx; x += 8) { - __m128i pixels_blue, pixels_green, pixels_red, - pixels_alpha; + __m128i pixels_blue, pixels_green, pixels_red, pixels_alpha; __m128i pixels_result; __m128i *pixels_dest; - __m128i *pixels_src = - (__m128i *)(row + x * sizeof(uint16_t)); + __m128i *pixels_src = (__m128i *)(row + x * sizeof(uint16_t)); __m128i pixels = _mm_load_si128(pixels_src); __m128i zero = _mm_setzero_si128(); @@ -1528,82 +1411,60 @@ static void copy_b5g5r5a1_tex(struct game_capture *gc, int cur_texture, __m128i alpha_offset = _mm_set1_epi32(0x00000001); __m128i alpha_mask32 = _mm_set1_epi32(0xFF000000); - pixels_blue = - _mm_and_si128(pixels_low, blue_channel_mask); + pixels_blue = _mm_and_si128(pixels_low, blue_channel_mask); pixels_blue = _mm_slli_epi32(pixels_blue, 3); pixels_blue = _mm_add_epi32(pixels_blue, blue_offset); - pixels_green = - _mm_and_si128(pixels_low, green_channel_mask); - pixels_green = - _mm_add_epi32(pixels_green, green_offset); + pixels_green = _mm_and_si128(pixels_low, green_channel_mask); + pixels_green = _mm_add_epi32(pixels_green, green_offset); pixels_green = _mm_slli_epi32(pixels_green, 6); - pixels_red = - _mm_and_si128(pixels_low, red_channel_mask); + pixels_red = _mm_and_si128(pixels_low, red_channel_mask); pixels_red = _mm_add_epi32(pixels_red, red_offset); pixels_red = _mm_slli_epi32(pixels_red, 9); - pixels_alpha = - _mm_and_si128(pixels_low, alpha_channel_mask); + pixels_alpha = _mm_and_si128(pixels_low, alpha_channel_mask); pixels_alpha = _mm_srli_epi32(pixels_alpha, 15); - pixels_alpha = - _mm_sub_epi32(pixels_alpha, alpha_offset); - pixels_alpha = - _mm_andnot_si128(pixels_alpha, alpha_mask32); + pixels_alpha = _mm_sub_epi32(pixels_alpha, alpha_offset); + pixels_alpha = _mm_andnot_si128(pixels_alpha, alpha_mask32); pixels_result = pixels_red; - pixels_result = - _mm_or_si128(pixels_result, pixels_alpha); - pixels_result = - _mm_or_si128(pixels_result, pixels_blue); - pixels_result = - _mm_or_si128(pixels_result, pixels_green); + pixels_result = _mm_or_si128(pixels_result, pixels_alpha); + pixels_result = _mm_or_si128(pixels_result, pixels_blue); + pixels_result = _mm_or_si128(pixels_result, pixels_green); pixels_dest = (__m128i *)(out + x * sizeof(uint32_t)); _mm_store_si128(pixels_dest, pixels_result); - pixels_blue = - _mm_and_si128(pixels_high, blue_channel_mask); + pixels_blue = _mm_and_si128(pixels_high, blue_channel_mask); pixels_blue = _mm_slli_epi32(pixels_blue, 3); pixels_blue = _mm_add_epi32(pixels_blue, blue_offset); - pixels_green = - _mm_and_si128(pixels_high, green_channel_mask); - pixels_green = - _mm_add_epi32(pixels_green, green_offset); + pixels_green = _mm_and_si128(pixels_high, green_channel_mask); + pixels_green = _mm_add_epi32(pixels_green, green_offset); pixels_green = _mm_slli_epi32(pixels_green, 6); - pixels_red = - _mm_and_si128(pixels_high, red_channel_mask); + pixels_red = _mm_and_si128(pixels_high, red_channel_mask); pixels_red = _mm_add_epi32(pixels_red, red_offset); pixels_red = _mm_slli_epi32(pixels_red, 9); - pixels_alpha = - _mm_and_si128(pixels_high, alpha_channel_mask); + pixels_alpha = _mm_and_si128(pixels_high, alpha_channel_mask); pixels_alpha = _mm_srli_epi32(pixels_alpha, 15); - pixels_alpha = - _mm_sub_epi32(pixels_alpha, alpha_offset); - pixels_alpha = - _mm_andnot_si128(pixels_alpha, alpha_mask32); + pixels_alpha = _mm_sub_epi32(pixels_alpha, alpha_offset); + pixels_alpha = _mm_andnot_si128(pixels_alpha, alpha_mask32); pixels_result = pixels_red; - pixels_result = - _mm_or_si128(pixels_result, pixels_alpha); - pixels_result = - _mm_or_si128(pixels_result, pixels_blue); - pixels_result = - _mm_or_si128(pixels_result, pixels_green); + pixels_result = _mm_or_si128(pixels_result, pixels_alpha); + pixels_result = _mm_or_si128(pixels_result, pixels_blue); + pixels_result = _mm_or_si128(pixels_result, pixels_green); - pixels_dest = - (__m128i *)(out + (x + 4) * sizeof(uint32_t)); + pixels_dest = (__m128i *)(out + (x + 4) * sizeof(uint32_t)); _mm_store_si128(pixels_dest, pixels_result); } } } -static inline void copy_16bit_tex(struct game_capture *gc, int cur_texture, - uint8_t *data, uint32_t pitch) +static inline void copy_16bit_tex(struct game_capture *gc, int cur_texture, uint8_t *data, uint32_t pitch) { if (gc->global_hook_info->format == DXGI_FORMAT_B5G5R5A1_UNORM) { copy_b5g5r5a1_tex(gc, cur_texture, data, pitch); @@ -1647,12 +1508,10 @@ static void copy_shmem_tex(struct game_capture *gc) copy_16bit_tex(gc, cur_texture, data, pitch); } else if (pitch == gc->pitch) { - memcpy(data, gc->texture_buffers[cur_texture], - (size_t)pitch * (size_t)gc->cy); + memcpy(data, gc->texture_buffers[cur_texture], (size_t)pitch * (size_t)gc->cy); } else { uint8_t *input = gc->texture_buffers[cur_texture]; - uint32_t best_pitch = pitch < gc->pitch ? pitch - : gc->pitch; + uint32_t best_pitch = pitch < gc->pitch ? pitch : gc->pitch; for (size_t y = 0; y < gc->cy; y++) { uint8_t *line_in = input + gc->pitch * y; @@ -1669,16 +1528,14 @@ static void copy_shmem_tex(struct game_capture *gc) static inline bool is_16bit_format(uint32_t format) { - return format == DXGI_FORMAT_B5G5R5A1_UNORM || - format == DXGI_FORMAT_B5G6R5_UNORM; + return format == DXGI_FORMAT_B5G5R5A1_UNORM || format == DXGI_FORMAT_B5G6R5_UNORM; } static inline bool init_shmem_capture(struct game_capture *gc) { const uint32_t dxgi_format = gc->global_hook_info->format; const bool convert_16bit = is_16bit_format(dxgi_format); - const enum gs_color_format format = - convert_16bit ? GS_BGRA : convert_format(dxgi_format); + const enum gs_color_format format = convert_16bit ? GS_BGRA : convert_format(dxgi_format); obs_enter_graphics(); gs_texrender_destroy(gc->extra_texrender); @@ -1687,8 +1544,7 @@ static inline bool init_shmem_capture(struct game_capture *gc) gc->extra_texture = NULL; gs_texture_destroy(gc->texture); gc->texture = NULL; - gs_texture_t *const texture = - gs_texture_create(gc->cx, gc->cy, format, 1, NULL, GS_DYNAMIC); + gs_texture_t *const texture = gs_texture_create(gc->cx, gc->cy, format, 1, NULL, GS_DYNAMIC); obs_leave_graphics(); bool success = texture != NULL; @@ -1697,18 +1553,15 @@ static inline bool init_shmem_capture(struct game_capture *gc) gs_texrender_t *extra_texrender = NULL; if (!linear_sample) { - extra_texrender = - gs_texrender_create(GS_RGBA16F, GS_ZS_NONE); + extra_texrender = gs_texrender_create(GS_RGBA16F, GS_ZS_NONE); success = extra_texrender != NULL; if (!success) warn("init_shmem_capture: failed to create extra texrender"); } if (success) { - gc->texture_buffers[0] = (uint8_t *)gc->data + - gc->shmem_data->tex1_offset; - gc->texture_buffers[1] = (uint8_t *)gc->data + - gc->shmem_data->tex2_offset; + gc->texture_buffers[0] = (uint8_t *)gc->data + gc->shmem_data->tex1_offset; + gc->texture_buffers[1] = (uint8_t *)gc->data + gc->shmem_data->tex2_offset; gc->convert_16bit = convert_16bit; gc->texture = texture; @@ -1735,31 +1588,25 @@ static inline bool init_shtex_capture(struct game_capture *gc) gc->extra_texture = NULL; gs_texture_destroy(gc->texture); gc->texture = NULL; - gs_texture_t *const texture = - gs_texture_open_shared(gc->shtex_data->tex_handle); + gs_texture_t *const texture = gs_texture_open_shared(gc->shtex_data->tex_handle); bool success = texture != NULL; if (success) { - enum gs_color_format format = - gs_texture_get_color_format(texture); + enum gs_color_format format = gs_texture_get_color_format(texture); const bool ten_bit_srgb = (format == GS_R10G10B10A2); - enum gs_color_format linear_format = - ten_bit_srgb ? GS_RGBA16F - : gs_generalize_format(format); + enum gs_color_format linear_format = ten_bit_srgb ? GS_RGBA16F : gs_generalize_format(format); const bool linear_sample = (linear_format == format); gs_texture_t *extra_texture = NULL; gs_texrender_t *extra_texrender = NULL; if (!linear_sample) { if (ten_bit_srgb) { - extra_texrender = gs_texrender_create( - linear_format, GS_ZS_NONE); + extra_texrender = gs_texrender_create(linear_format, GS_ZS_NONE); success = extra_texrender != NULL; if (!success) warn("init_shtex_capture: failed to create extra texrender"); } else { - extra_texture = gs_texture_create( - gs_texture_get_width(texture), - gs_texture_get_height(texture), - linear_format, 1, NULL, 0); + extra_texture = gs_texture_create(gs_texture_get_width(texture), + gs_texture_get_height(texture), linear_format, 1, + NULL, 0); success = extra_texture != NULL; if (!success) warn("init_shtex_capture: failed to create extra texture"); @@ -1789,10 +1636,8 @@ static bool start_capture(struct game_capture *gc) /* prevent from using a DLL version that's higher than current */ if (gc->global_hook_info->hook_ver_major > HOOK_VER_MAJOR) { warn("cannot initialize hook, DLL hook version is " - "%" PRIu32 ".%" PRIu32 - ", current plugin hook major version is %d.%d", - gc->global_hook_info->hook_ver_major, - gc->global_hook_info->hook_ver_minor, HOOK_VER_MAJOR, + "%" PRIu32 ".%" PRIu32 ", current plugin hook major version is %d.%d", + gc->global_hook_info->hook_ver_major, gc->global_hook_info->hook_ver_minor, HOOK_VER_MAJOR, HOOK_VER_MINOR); return false; } @@ -1828,8 +1673,7 @@ static void check_foreground_window(struct game_capture *gc, float seconds) gc->cursor_check_time += seconds; if (gc->cursor_check_time >= 0.1f) { DWORD foreground_process_id; - GetWindowThreadProcessId(GetForegroundWindow(), - &foreground_process_id); + GetWindowThreadProcessId(GetForegroundWindow(), &foreground_process_id); if (gc->process_id != foreground_process_id) gc->cursor_hidden = true; else @@ -1845,8 +1689,7 @@ static void game_capture_tick(void *data, float seconds) bool activate_now = os_atomic_set_bool(&gc->activate_hook_now, false); if (activate_now) { - HWND hwnd = (HWND)(uintptr_t)os_atomic_load_long( - &gc->hotkey_window); + HWND hwnd = (HWND)(uintptr_t)os_atomic_load_long(&gc->hotkey_window); if (ms_is_uwp_window(hwnd)) hwnd = ms_get_uwp_actual_window(hwnd); @@ -1856,8 +1699,7 @@ static void game_capture_tick(void *data, float seconds) ms_get_window_class(&gc->class, hwnd); gc->priority = WINDOW_PRIORITY_CLASS; - gc->retry_time = 10.0f * hook_rate_to_float( - gc->config.hook_rate); + gc->retry_time = 10.0f * hook_rate_to_float(gc->config.hook_rate); gc->activate_hook = true; } else { deactivate = false; @@ -1876,8 +1718,7 @@ static void game_capture_tick(void *data, float seconds) return; } else if (!gc->showing) { - gc->retry_time = - 10.0f * hook_rate_to_float(gc->config.hook_rate); + gc->retry_time = 10.0f * hook_rate_to_float(gc->config.hook_rate); } if (gc->hook_stop && object_signalled(gc->hook_stop)) { @@ -1903,9 +1744,7 @@ static void game_capture_tick(void *data, float seconds) gc->error_acquiring = true; } else if (!gc->capturing) { - gc->retry_interval = - ERROR_RETRY_INTERVAL * - hook_rate_to_float(gc->config.hook_rate); + gc->retry_interval = ERROR_RETRY_INTERVAL * hook_rate_to_float(gc->config.hook_rate); stop_capture(gc); } } @@ -1926,28 +1765,23 @@ static void game_capture_tick(void *data, float seconds) ms_get_window_title(&gc->title, gc->window); ms_get_window_class(&gc->class, gc->window); } - signal_handler_t *sh = - obs_source_get_signal_handler(gc->source); + signal_handler_t *sh = obs_source_get_signal_handler(gc->source); calldata_t data = {0}; calldata_set_ptr(&data, "source", gc->source); calldata_set_string(&data, "title", gc->title.array); calldata_set_string(&data, "class", gc->class.array); - calldata_set_string(&data, "executable", - gc->executable.array); + calldata_set_string(&data, "executable", gc->executable.array); signal_handler_signal(sh, "hooked", &data); calldata_free(&data); if (gc->audio_source) { - reconfigure_audio_source(gc->audio_source, - gc->window); + reconfigure_audio_source(gc->audio_source, gc->window); } } if (result != CAPTURE_RETRY && !gc->capturing) { - gc->retry_interval = - ERROR_RETRY_INTERVAL * - hook_rate_to_float(gc->config.hook_rate); + gc->retry_interval = ERROR_RETRY_INTERVAL * hook_rate_to_float(gc->config.hook_rate); stop_capture(gc); } } @@ -1955,10 +1789,8 @@ static void game_capture_tick(void *data, float seconds) gc->retry_time += seconds; if (!gc->active) { - if (!gc->error_acquiring && - gc->retry_time > gc->retry_interval) { - if (gc->config.mode == CAPTURE_MODE_ANY || - gc->activate_hook) { + if (!gc->error_acquiring && gc->retry_time > gc->retry_interval) { + if (gc->config.mode == CAPTURE_MODE_ANY || gc->activate_hook) { try_hook(gc); gc->retry_time = 0.0f; } @@ -1977,14 +1809,10 @@ static void game_capture_tick(void *data, float seconds) if (gc->config.cursor) { DPI_AWARENESS_CONTEXT previous = NULL; - if (gc->get_window_dpi_awareness_context != - NULL) { + if (gc->get_window_dpi_awareness_context != NULL) { const DPI_AWARENESS_CONTEXT context = - gc->get_window_dpi_awareness_context( - gc->window); - previous = - gc->set_thread_dpi_awareness_context( - context); + gc->get_window_dpi_awareness_context(gc->window); + previous = gc->set_thread_dpi_awareness_context(context); } check_foreground_window(gc, seconds); @@ -1993,8 +1821,7 @@ static void game_capture_tick(void *data, float seconds) obs_leave_graphics(); if (previous) { - gc->set_thread_dpi_awareness_context( - previous); + gc->set_thread_dpi_awareness_context(previous); } } @@ -2018,14 +1845,11 @@ static inline void game_capture_render_cursor(struct game_capture *gc) if (!gc->global_hook_info->cx || !gc->global_hook_info->cy) return; - window = !!gc->global_hook_info->window - ? (HWND)(uintptr_t)gc->global_hook_info->window - : gc->window; + window = !!gc->global_hook_info->window ? (HWND)(uintptr_t)gc->global_hook_info->window : gc->window; DPI_AWARENESS_CONTEXT previous = NULL; if (gc->get_window_dpi_awareness_context != NULL) { - const DPI_AWARENESS_CONTEXT context = - gc->get_window_dpi_awareness_context(gc->window); + const DPI_AWARENESS_CONTEXT context = gc->get_window_dpi_awareness_context(gc->window); previous = gc->set_thread_dpi_awareness_context(context); } @@ -2034,8 +1858,7 @@ static inline void game_capture_render_cursor(struct game_capture *gc) if (previous) gc->set_thread_dpi_awareness_context(previous); - cursor_draw(&gc->cursor_data, -p.x, -p.y, gc->global_hook_info->cx, - gc->global_hook_info->cy); + cursor_draw(&gc->cursor_data, -p.x, -p.y, gc->global_hook_info->cx, gc->global_hook_info->cy); } static void game_capture_render(void *data, gs_effect_t *unused) @@ -2047,24 +1870,21 @@ static void game_capture_render(void *data, gs_effect_t *unused) return; const bool allow_transparency = gc->config.allow_transparency; - gs_effect_t *const effect = obs_get_base_effect( - allow_transparency ? OBS_EFFECT_DEFAULT : OBS_EFFECT_OPAQUE); + gs_effect_t *const effect = obs_get_base_effect(allow_transparency ? OBS_EFFECT_DEFAULT : OBS_EFFECT_OPAQUE); gs_texture_t *texture = gc->texture; enum gs_color_space source_space = GS_CS_SRGB; bool is_10a2_compressed = false; if (gs_texture_get_color_format(texture) == GS_R10G10B10A2) { is_10a2_compressed = true; - source_space = gc->is_10a2_2100pq ? GS_CS_709_EXTENDED - : GS_CS_SRGB_16F; + source_space = gc->is_10a2_2100pq ? GS_CS_709_EXTENDED : GS_CS_SRGB_16F; } else if (gs_texture_get_color_format(texture) == GS_RGBA16F) { source_space = GS_CS_709_SCRGB; } bool linear_sample = gc->linear_sample; const enum gs_color_space current_space = gs_get_color_space(); - const bool texcoords_centered = - obs_source_get_texcoords_centered(gc->source); + const bool texcoords_centered = obs_source_get_texcoords_centered(gc->source); if (!linear_sample && !texcoords_centered) { if (gs_texture_get_color_format(texture) == GS_R10G10B10A2) { gs_texrender_t *const texrender = gc->extra_texrender; @@ -2072,32 +1892,22 @@ static void game_capture_render(void *data, gs_effect_t *unused) const uint32_t cx = gs_texture_get_width(texture); const uint32_t cy = gs_texture_get_height(texture); if (gs_texrender_begin(texrender, cx, cy)) { - gs_effect_t *const default_effect = - obs_get_base_effect(OBS_EFFECT_DEFAULT); + gs_effect_t *const default_effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); gs_enable_blending(false); - gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, - -100.0f, 100.0f); - gs_eparam_t *const image = - gs_effect_get_param_by_name( - default_effect, "image"); + gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); + gs_eparam_t *const image = gs_effect_get_param_by_name(default_effect, "image"); gs_effect_set_texture(image, texture); const char *tech_name = "DrawSrgbDecompress"; if (gc->is_10a2_2100pq) { tech_name = "DrawPQ"; - const float multiplier = - 10000.f / - obs_get_video_sdr_white_level(); - gs_effect_set_float( - gs_effect_get_param_by_name( - default_effect, - "multiplier"), - multiplier); + const float multiplier = 10000.f / obs_get_video_sdr_white_level(); + gs_effect_set_float(gs_effect_get_param_by_name(default_effect, "multiplier"), + multiplier); } - while (gs_effect_loop(default_effect, - tech_name)) { + while (gs_effect_loop(default_effect, tech_name)) { gs_draw_sprite(texture, 0, 0, 0); } gs_enable_blending(true); @@ -2114,40 +1924,27 @@ static void game_capture_render(void *data, gs_effect_t *unused) gs_copy_texture(extra_texture, texture); texture = extra_texture; } else { - gs_texrender_t *const texrender = - gc->extra_texrender; + gs_texrender_t *const texrender = gc->extra_texrender; gs_texrender_reset(texrender); - const uint32_t cx = - gs_texture_get_width(texture); - const uint32_t cy = - gs_texture_get_height(texture); + const uint32_t cx = gs_texture_get_width(texture); + const uint32_t cy = gs_texture_get_height(texture); if (gs_texrender_begin(texrender, cx, cy)) { - gs_effect_t *const default_effect = - obs_get_base_effect( - OBS_EFFECT_DEFAULT); - const bool previous = - gs_framebuffer_srgb_enabled(); + gs_effect_t *const default_effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); + const bool previous = gs_framebuffer_srgb_enabled(); gs_enable_framebuffer_srgb(false); gs_enable_blending(false); - gs_ortho(0.0f, (float)cx, 0.0f, - (float)cy, -100.0f, 100.0f); - gs_eparam_t *const image = - gs_effect_get_param_by_name( - default_effect, - "image"); + gs_ortho(0.0f, (float)cx, 0.0f, (float)cy, -100.0f, 100.0f); + gs_eparam_t *const image = gs_effect_get_param_by_name(default_effect, "image"); gs_effect_set_texture(image, texture); - while (gs_effect_loop(default_effect, - "Draw")) { - gs_draw_sprite(texture, 0, 0, - 0); + while (gs_effect_loop(default_effect, "Draw")) { + gs_draw_sprite(texture, 0, 0, 0); } gs_enable_blending(true); gs_enable_framebuffer_srgb(previous); gs_texrender_end(texrender); - texture = gs_texrender_get_texture( - texrender); + texture = gs_texrender_get_texture(texrender); } } } @@ -2186,13 +1983,10 @@ static void game_capture_render(void *data, gs_effect_t *unused) case GS_CS_SRGB: case GS_CS_SRGB_16F: case GS_CS_709_EXTENDED: - tech_name = is_10a2_compressed ? "DrawSrgbDecompress" - : "Draw"; + tech_name = is_10a2_compressed ? "DrawSrgbDecompress" : "Draw"; break; case GS_CS_709_SCRGB: - tech_name = is_10a2_compressed - ? "DrawSrgbDecompressMultiply" - : "DrawMultiply"; + tech_name = is_10a2_compressed ? "DrawSrgbDecompressMultiply" : "DrawMultiply"; multiplier = obs_get_video_sdr_white_level() / 80.f; } break; @@ -2203,13 +1997,11 @@ static void game_capture_render(void *data, gs_effect_t *unused) case GS_CS_SRGB: case GS_CS_SRGB_16F: tech_name = "DrawTonemapPQ"; - multiplier = 10000.f / - obs_get_video_sdr_white_level(); + multiplier = 10000.f / obs_get_video_sdr_white_level(); break; case GS_CS_709_EXTENDED: tech_name = "DrawPQ"; - multiplier = 10000.f / - obs_get_video_sdr_white_level(); + multiplier = 10000.f / obs_get_video_sdr_white_level(); break; case GS_CS_709_SCRGB: tech_name = "DrawPQ"; @@ -2223,8 +2015,7 @@ static void game_capture_render(void *data, gs_effect_t *unused) break; case GS_CS_709_SCRGB: tech_name = "DrawMultiply"; - multiplier = - obs_get_video_sdr_white_level() / 80.f; + multiplier = obs_get_video_sdr_white_level() / 80.f; } } break; @@ -2247,41 +2038,32 @@ static void game_capture_render(void *data, gs_effect_t *unused) gs_enable_framebuffer_srgb(allow_transparency || linear_sample); gs_blend_state_push(); gs_enable_blending(allow_transparency); - gs_blend_function_separate(gc->config.premultiplied_alpha - ? GS_BLEND_ONE - : GS_BLEND_SRCALPHA, - GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, - GS_BLEND_INVSRCALPHA); + gs_blend_function_separate(gc->config.premultiplied_alpha ? GS_BLEND_ONE : GS_BLEND_SRCALPHA, + GS_BLEND_INVSRCALPHA, GS_BLEND_ONE, GS_BLEND_INVSRCALPHA); if (linear_sample) gs_effect_set_texture_srgb(image, texture); else gs_effect_set_texture(image, texture); - gs_effect_set_float(gs_effect_get_param_by_name(effect, - "multiplier"), - multiplier); + gs_effect_set_float(gs_effect_get_param_by_name(effect, "multiplier"), multiplier); gs_draw_sprite(texture, flip, 0, 0); gs_blend_state_pop(); gs_enable_framebuffer_srgb(previous); } if (gc->config.cursor && !gc->cursor_hidden) { - gs_effect_t *const default_effect = - obs_get_base_effect(OBS_EFFECT_DEFAULT); + gs_effect_t *const default_effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); const char *cursor_tech_name = "Draw"; float cursor_multiplier = 1.f; if (current_space == GS_CS_709_SCRGB) { cursor_tech_name = "DrawMultiply"; - cursor_multiplier = - obs_get_video_sdr_white_level() / 80.f; + cursor_multiplier = obs_get_video_sdr_white_level() / 80.f; } const bool previous = gs_set_linear_srgb(true); while (gs_effect_loop(default_effect, cursor_tech_name)) { - gs_effect_set_float(gs_effect_get_param_by_name( - effect, "multiplier"), - cursor_multiplier); + gs_effect_set_float(gs_effect_get_param_by_name(effect, "multiplier"), cursor_multiplier); game_capture_render_cursor(gc); } @@ -2310,8 +2092,7 @@ static const char *game_capture_name(void *unused) static void game_capture_defaults(obs_data_t *settings) { obs_data_set_default_string(settings, SETTING_MODE, SETTING_MODE_ANY); - obs_data_set_default_int(settings, SETTING_WINDOW_PRIORITY, - (int)WINDOW_PRIORITY_EXE); + obs_data_set_default_int(settings, SETTING_WINDOW_PRIORITY, (int)WINDOW_PRIORITY_EXE); obs_data_set_default_bool(settings, SETTING_COMPATIBILITY, false); obs_data_set_default_bool(settings, SETTING_CURSOR, true); obs_data_set_default_bool(settings, SETTING_TRANSPARENCY, false); @@ -2319,20 +2100,16 @@ static void game_capture_defaults(obs_data_t *settings) obs_data_set_default_bool(settings, SETTING_LIMIT_FRAMERATE, false); obs_data_set_default_bool(settings, SETTING_CAPTURE_OVERLAYS, false); obs_data_set_default_bool(settings, SETTING_ANTI_CHEAT_HOOK, true); - obs_data_set_default_int(settings, SETTING_HOOK_RATE, - (int)HOOK_RATE_NORMAL); - obs_data_set_default_string(settings, SETTING_RGBA10A2_SPACE, - RGBA10A2_SPACE_SRGB); + obs_data_set_default_int(settings, SETTING_HOOK_RATE, (int)HOOK_RATE_NORMAL); + obs_data_set_default_string(settings, SETTING_RGBA10A2_SPACE, RGBA10A2_SPACE_SRGB); } -static bool mode_callback(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool mode_callback(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { bool capture_window; if (using_older_non_mode_format(settings)) { - capture_window = - !obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN); + capture_window = !obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN); } else { const char *mode = obs_data_get_string(settings, SETTING_MODE); capture_window = strcmp(mode, SETTING_MODE_WINDOW) == 0; @@ -2347,34 +2124,28 @@ static bool mode_callback(obs_properties_t *ppts, obs_property_t *p, return true; } -static bool window_changed_callback(obs_properties_t *ppts, obs_property_t *p, - obs_data_t *settings) +static bool window_changed_callback(obs_properties_t *ppts, obs_property_t *p, obs_data_t *settings) { - bool modified = ms_check_window_property_setting( - ppts, p, settings, SETTING_CAPTURE_WINDOW, 1); + bool modified = ms_check_window_property_setting(ppts, p, settings, SETTING_CAPTURE_WINDOW, 1); bool capture_any; if (using_older_non_mode_format(settings)) { - capture_any = - obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN); + capture_any = obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN); } else { const char *mode = obs_data_get_string(settings, SETTING_MODE); - capture_any = strcmp(mode, SETTING_MODE_ANY) == 0 || - strcmp(mode, SETTING_MODE_HOTKEY) == 0; + capture_any = strcmp(mode, SETTING_MODE_ANY) == 0 || strcmp(mode, SETTING_MODE_HOTKEY) == 0; } if (capture_any) return modified; - const char *window = - obs_data_get_string(settings, SETTING_CAPTURE_WINDOW); + const char *window = obs_data_get_string(settings, SETTING_CAPTURE_WINDOW); char *class; char *exe; char *title; ms_build_window_strings(window, &class, &title, &exe); - struct compat_result *compat = - check_compatibility(title, class, exe, GAME_CAPTURE); + struct compat_result *compat = check_compatibility(title, class, exe, GAME_CAPTURE); bfree(title); bfree(exe); bfree(class); @@ -2396,8 +2167,7 @@ static bool window_changed_callback(obs_properties_t *ppts, obs_property_t *p, return true; } -static BOOL CALLBACK EnumFirstMonitor(HMONITOR monitor, HDC hdc, LPRECT rc, - LPARAM data) +static BOOL CALLBACK EnumFirstMonitor(HMONITOR monitor, HDC hdc, LPRECT rc, LPARAM data) { *(HMONITOR *)data = monitor; @@ -2406,8 +2176,7 @@ static BOOL CALLBACK EnumFirstMonitor(HMONITOR monitor, HDC hdc, LPRECT rc, return false; } -static bool window_not_blacklisted(const char *title, const char *class, - const char *exe) +static bool window_not_blacklisted(const char *title, const char *class, const char *exe) { UNUSED_PARAMETER(title); UNUSED_PARAMETER(class); @@ -2423,8 +2192,7 @@ static obs_properties_t *game_capture_properties(void *data) /* scaling is free form, this is mostly just to provide some common * values */ - bool success = !!EnumDisplayMonitors(NULL, NULL, EnumFirstMonitor, - (LPARAM)&monitor); + bool success = !!EnumDisplayMonitors(NULL, NULL, EnumFirstMonitor, (LPARAM)&monitor); if (success) { MONITORINFO mi = {0}; mi.cbSize = sizeof(mi); @@ -2440,10 +2208,8 @@ static obs_properties_t *game_capture_properties(void *data) struct game_capture *gc = data; obs_data_t *settings = obs_source_get_settings(gc->source); if (using_older_non_mode_format(settings)) { - bool any = obs_data_get_bool(settings, - SETTING_ANY_FULLSCREEN); - const char *mode = any ? SETTING_MODE_ANY - : SETTING_MODE_WINDOW; + bool any = obs_data_get_bool(settings, SETTING_ANY_FULLSCREEN); + const char *mode = any ? SETTING_MODE_ANY : SETTING_MODE_WINDOW; obs_data_set_string(settings, SETTING_MODE, mode); } @@ -2453,9 +2219,7 @@ static obs_properties_t *game_capture_properties(void *data) obs_properties_t *ppts = obs_properties_create(); obs_property_t *p; - p = obs_properties_add_list(ppts, SETTING_MODE, TEXT_MODE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, SETTING_MODE, TEXT_MODE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, TEXT_MODE_ANY, SETTING_MODE_ANY); obs_property_list_add_string(p, TEXT_MODE_WINDOW, SETTING_MODE_WINDOW); @@ -2463,81 +2227,63 @@ static obs_properties_t *game_capture_properties(void *data) obs_property_set_modified_callback(p, mode_callback); - p = obs_properties_add_list(ppts, SETTING_CAPTURE_WINDOW, TEXT_WINDOW, - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, SETTING_CAPTURE_WINDOW, TEXT_WINDOW, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, "", ""); ms_fill_window_list(p, INCLUDE_MINIMIZED, window_not_blacklisted); obs_property_set_modified_callback(p, window_changed_callback); - p = obs_properties_add_list(ppts, SETTING_WINDOW_PRIORITY, - TEXT_MATCH_PRIORITY, OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, SETTING_WINDOW_PRIORITY, TEXT_MATCH_PRIORITY, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(p, TEXT_MATCH_TITLE, WINDOW_PRIORITY_TITLE); obs_property_list_add_int(p, TEXT_MATCH_CLASS, WINDOW_PRIORITY_CLASS); obs_property_list_add_int(p, TEXT_MATCH_EXE, WINDOW_PRIORITY_EXE); - p = obs_properties_add_text(ppts, SETTINGS_COMPAT_INFO, NULL, - OBS_TEXT_INFO); + p = obs_properties_add_text(ppts, SETTINGS_COMPAT_INFO, NULL, OBS_TEXT_INFO); obs_property_set_enabled(p, false); if (audio_capture_available()) { - p = obs_properties_add_bool(ppts, SETTING_CAPTURE_AUDIO, - TEXT_CAPTURE_AUDIO); + p = obs_properties_add_bool(ppts, SETTING_CAPTURE_AUDIO, TEXT_CAPTURE_AUDIO); obs_property_set_long_description(p, TEXT_CAPTURE_AUDIO_TT); } - obs_properties_add_bool(ppts, SETTING_COMPATIBILITY, - TEXT_SLI_COMPATIBILITY); + obs_properties_add_bool(ppts, SETTING_COMPATIBILITY, TEXT_SLI_COMPATIBILITY); - obs_properties_add_bool(ppts, SETTING_TRANSPARENCY, - TEXT_ALLOW_TRANSPARENCY); + obs_properties_add_bool(ppts, SETTING_TRANSPARENCY, TEXT_ALLOW_TRANSPARENCY); - obs_properties_add_bool(ppts, SETTING_PREMULTIPLIED_ALPHA, - TEXT_PREMULTIPLIED_ALPHA); + obs_properties_add_bool(ppts, SETTING_PREMULTIPLIED_ALPHA, TEXT_PREMULTIPLIED_ALPHA); - obs_properties_add_bool(ppts, SETTING_LIMIT_FRAMERATE, - TEXT_LIMIT_FRAMERATE); + obs_properties_add_bool(ppts, SETTING_LIMIT_FRAMERATE, TEXT_LIMIT_FRAMERATE); obs_properties_add_bool(ppts, SETTING_CURSOR, TEXT_CAPTURE_CURSOR); - obs_properties_add_bool(ppts, SETTING_ANTI_CHEAT_HOOK, - TEXT_ANTI_CHEAT_HOOK); + obs_properties_add_bool(ppts, SETTING_ANTI_CHEAT_HOOK, TEXT_ANTI_CHEAT_HOOK); - obs_properties_add_bool(ppts, SETTING_CAPTURE_OVERLAYS, - TEXT_CAPTURE_OVERLAYS); + obs_properties_add_bool(ppts, SETTING_CAPTURE_OVERLAYS, TEXT_CAPTURE_OVERLAYS); - p = obs_properties_add_list(ppts, SETTING_HOOK_RATE, TEXT_HOOK_RATE, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(ppts, SETTING_HOOK_RATE, TEXT_HOOK_RATE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(p, TEXT_HOOK_RATE_SLOW, HOOK_RATE_SLOW); obs_property_list_add_int(p, TEXT_HOOK_RATE_NORMAL, HOOK_RATE_NORMAL); obs_property_list_add_int(p, TEXT_HOOK_RATE_FAST, HOOK_RATE_FAST); obs_property_list_add_int(p, TEXT_HOOK_RATE_FASTEST, HOOK_RATE_FASTEST); - p = obs_properties_add_list(ppts, SETTING_RGBA10A2_SPACE, - TEXT_RGBA10A2_SPACE, OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, SETTING_RGBA10A2_SPACE, TEXT_RGBA10A2_SPACE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); - obs_property_list_add_string(p, TEXT_RGBA10A2_SPACE_SRGB, - RGBA10A2_SPACE_SRGB); - obs_property_list_add_string(p, TEXT_RGBA10A2_SPACE_2100PQ, - RGBA10A2_SPACE_2100PQ); + obs_property_list_add_string(p, TEXT_RGBA10A2_SPACE_SRGB, RGBA10A2_SPACE_SRGB); + obs_property_list_add_string(p, TEXT_RGBA10A2_SPACE_2100PQ, RGBA10A2_SPACE_2100PQ); return ppts; } -enum gs_color_space -game_capture_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +enum gs_color_space game_capture_get_color_space(void *data, size_t count, const enum gs_color_space *preferred_spaces) { enum gs_color_space capture_space = GS_CS_SRGB; struct game_capture *const gc = data; if (gc->texture) { - const enum gs_color_format format = - gs_texture_get_color_format(gc->texture); - if (((format == GS_R10G10B10A2) && gc->is_10a2_2100pq) || - (format == GS_RGBA16F)) { + const enum gs_color_format format = gs_texture_get_color_format(gc->texture); + if (((format == GS_R10G10B10A2) && gc->is_10a2_2100pq) || (format == GS_RGBA16F)) { for (size_t i = 0; i < count; ++i) { if (preferred_spaces[i] == GS_CS_709_SCRGB) return GS_CS_709_SCRGB; @@ -2565,8 +2311,7 @@ game_capture_get_color_space(void *data, size_t count, return space; } -static void game_capture_enum(void *data, obs_source_enum_proc_t cb, - void *param) +static void game_capture_enum(void *data, obs_source_enum_proc_t cb, void *param) { struct game_capture *gc = data; if (gc->audio_source) @@ -2576,8 +2321,7 @@ static void game_capture_enum(void *data, obs_source_enum_proc_t cb, struct obs_source_info game_capture_info = { .id = "game_capture", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE | + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, .get_name = game_capture_name, .create = game_capture_create, diff --git a/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp b/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp index 7f488b058..f7f7855fb 100644 --- a/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp +++ b/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp @@ -21,8 +21,7 @@ static inline bool d3d8_init(d3d8_info &info) d3d8create_t create; HRESULT hr; - info.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, "d3d8 get-addr window", - WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, + info.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, "d3d8 get-addr window", WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, GetModuleHandleA(nullptr), nullptr); if (!info.hwnd) { return false; @@ -52,10 +51,8 @@ static inline bool d3d8_init(d3d8_info &info) pp.BackBufferCount = 1; pp.hDeviceWindow = info.hwnd; - hr = info.d3d8->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, - info.hwnd, - D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, - &info.device); + hr = info.d3d8->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, info.hwnd, D3DCREATE_HARDWARE_VERTEXPROCESSING, + &pp, &info.device); if (FAILED(hr)) { return false; } diff --git a/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp b/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp index 1d57bb69b..f28451d91 100644 --- a/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp +++ b/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp @@ -18,8 +18,7 @@ static inline bool d3d9_init(d3d9_info &info) d3d9createex_t create; HRESULT hr; - info.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, "d3d9 get-offset window", - WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, + info.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, "d3d9 get-offset window", WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, GetModuleHandleA(nullptr), nullptr); if (!info.hwnd) { return false; @@ -30,8 +29,7 @@ static inline bool d3d9_init(d3d9_info &info) return false; } - create = (d3d9createex_t)GetProcAddress(info.module, - "Direct3DCreate9Ex"); + create = (d3d9createex_t)GetProcAddress(info.module, "Direct3DCreate9Ex"); if (!create) { return false; } @@ -51,10 +49,9 @@ static inline bool d3d9_init(d3d9_info &info) pp.hDeviceWindow = info.hwnd; pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - hr = info.d3d9ex->CreateDeviceEx( - D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, info.hwnd, - D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_NOWINDOWCHANGES, - &pp, nullptr, &info.device); + hr = info.d3d9ex->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, info.hwnd, + D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_NOWINDOWCHANGES, &pp, nullptr, + &info.device); if (FAILED(hr)) { return false; } @@ -276,8 +273,7 @@ static const uint32_t code_offsets[][2] = { #define MAX_FUNC_SCAN_BYTES 200 -static inline bool pattern_matches(uint8_t *byte, uint32_t *offset1, - uint32_t *offset2) +static inline bool pattern_matches(uint8_t *byte, uint32_t *offset1, uint32_t *offset2) { for (size_t j = 0; j < sizeof(mask) / sizeof(mask[0]); j++) { for (size_t i = 0; i < MAX_CMP_SIZE; i++) { @@ -306,10 +302,8 @@ void get_d3d9_offsets(struct d3d9_offsets *offsets) uint8_t *crr = vt[125]; offsets->present = vtable_offset(info.module, info.device, 17); - offsets->present_ex = - vtable_offset(info.module, info.device, 121); - offsets->present_swap = - vtable_offset(info.module, info.swap, 3); + offsets->present_ex = vtable_offset(info.module, info.device, 121); + offsets->present_swap = vtable_offset(info.module, info.swap, 3); uint32_t offset1, offset2; for (size_t i = 0; i < MAX_FUNC_SCAN_BYTES; i++) { @@ -329,13 +323,11 @@ void get_d3d9_offsets(struct d3d9_offsets *offsets) __try { uint8_t *ptr = (uint8_t *)(info.device); - uint8_t *d3d9_ptr = - *(uint8_t **)(ptr + off1); + uint8_t *d3d9_ptr = *(uint8_t **)(ptr + off1); if (d3d9_ptr != (uint8_t *)info.d3d9ex) break; - BOOL &is_d3d9ex = - *(BOOL *)(d3d9_ptr + off2); + BOOL &is_d3d9ex = *(BOOL *)(d3d9_ptr + off2); if (is_d3d9ex != TRUE) break; diff --git a/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp b/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp index dc48293b5..296134f2b 100644 --- a/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp +++ b/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp @@ -4,9 +4,7 @@ #include #include "get-graphics-offsets.h" -typedef HRESULT(WINAPI *d3d10create_t)(IDXGIAdapter *, D3D10_DRIVER_TYPE, - HMODULE, UINT, UINT, - DXGI_SWAP_CHAIN_DESC *, +typedef HRESULT(WINAPI *d3d10create_t)(IDXGIAdapter *, D3D10_DRIVER_TYPE, HMODULE, UINT, UINT, DXGI_SWAP_CHAIN_DESC *, IDXGISwapChain **, IUnknown **); typedef HRESULT(WINAPI *create_fac_t)(IID *id, void **); @@ -16,11 +14,7 @@ struct dxgi_info { IDXGISwapChain *swap; }; -static const IID dxgiFactory2 = {0x50c83a1c, - 0xe072, - 0x4c48, - {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, - 0xd0}}; +static const IID dxgiFactory2 = {0x50c83a1c, 0xe072, 0x4c48, {0x87, 0xb0, 0x36, 0x30, 0xfa, 0x36, 0xa6, 0xd0}}; static inline bool dxgi_init(dxgi_info &info) { @@ -32,10 +26,8 @@ static inline bool dxgi_init(dxgi_info &info) IUnknown *device; HRESULT hr; - info.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, - "d3d10 get-offset window", WS_POPUP, 0, 0, - 2, 2, nullptr, nullptr, - GetModuleHandleA(nullptr), nullptr); + info.hwnd = CreateWindowExA(0, DUMMY_WNDCLASS, "d3d10 get-offset window", WS_POPUP, 0, 0, 2, 2, nullptr, + nullptr, GetModuleHandleA(nullptr), nullptr); if (!info.hwnd) { return false; } @@ -45,22 +37,19 @@ static inline bool dxgi_init(dxgi_info &info) return false; } - create_factory = - (create_fac_t)GetProcAddress(info.module, "CreateDXGIFactory1"); + create_factory = (create_fac_t)GetProcAddress(info.module, "CreateDXGIFactory1"); d3d10_module = LoadLibraryA("d3d10.dll"); if (!d3d10_module) { return false; } - create = (d3d10create_t)GetProcAddress(d3d10_module, - "D3D10CreateDeviceAndSwapChain"); + create = (d3d10create_t)GetProcAddress(d3d10_module, "D3D10CreateDeviceAndSwapChain"); if (!create) { return false; } - IID factory_iid = IsWindows8OrGreater() ? dxgiFactory2 - : __uuidof(IDXGIFactory1); + IID factory_iid = IsWindows8OrGreater() ? dxgiFactory2 : __uuidof(IDXGIFactory1); hr = create_factory(&factory_iid, (void **)&factory); if (FAILED(hr)) { @@ -83,8 +72,7 @@ static inline bool dxgi_init(dxgi_info &info) desc.SampleDesc.Count = 1; desc.Windowed = true; - hr = create(adapter, D3D10_DRIVER_TYPE_HARDWARE, nullptr, 0, - D3D10_SDK_VERSION, &desc, &info.swap, &device); + hr = create(adapter, D3D10_DRIVER_TYPE_HARDWARE, nullptr, 0, D3D10_SDK_VERSION, &desc, &info.swap, &device); adapter->Release(); if (FAILED(hr)) { return false; @@ -102,8 +90,7 @@ static inline void dxgi_free(dxgi_info &info) DestroyWindow(info.hwnd); } -void get_dxgi_offsets(struct dxgi_offsets *offsets, - struct dxgi_offsets2 *offsets2) +void get_dxgi_offsets(struct dxgi_offsets *offsets, struct dxgi_offsets2 *offsets2) { dxgi_info info = {}; bool success = dxgi_init(info); @@ -114,11 +101,9 @@ void get_dxgi_offsets(struct dxgi_offsets *offsets, offsets->resize = vtable_offset(info.module, info.swap, 13); IDXGISwapChain1 *swap1; - hr = info.swap->QueryInterface(__uuidof(IDXGISwapChain1), - (void **)&swap1); + hr = info.swap->QueryInterface(__uuidof(IDXGISwapChain1), (void **)&swap1); if (SUCCEEDED(hr)) { - offsets->present1 = - vtable_offset(info.module, swap1, 22); + offsets->present1 = vtable_offset(info.module, swap1, 22); swap1->Release(); } diff --git a/plugins/win-capture/get-graphics-offsets/get-graphics-offsets.h b/plugins/win-capture/get-graphics-offsets/get-graphics-offsets.h index 3a4173e30..98b609f9c 100644 --- a/plugins/win-capture/get-graphics-offsets/get-graphics-offsets.h +++ b/plugins/win-capture/get-graphics-offsets/get-graphics-offsets.h @@ -18,15 +18,13 @@ extern "C" { #endif #endif -static inline uint32_t vtable_offset(HMODULE module, void *cls, - unsigned int offset) +static inline uint32_t vtable_offset(HMODULE module, void *cls, unsigned int offset) { uintptr_t *vtable = *(uintptr_t **)cls; return (uint32_t)(vtable[offset] - (uintptr_t)module); } -extern void get_dxgi_offsets(struct dxgi_offsets *offsets, - struct dxgi_offsets2 *offsets2); +extern void get_dxgi_offsets(struct dxgi_offsets *offsets, struct dxgi_offsets2 *offsets2); extern void get_d3d9_offsets(struct d3d9_offsets *offsets); extern void get_d3d8_offsets(struct d3d8_offsets *offsets); diff --git a/plugins/win-capture/graphics-hook/d3d10-capture.cpp b/plugins/win-capture/graphics-hook/d3d10-capture.cpp index 1b03f8277..a8a621200 100644 --- a/plugins/win-capture/graphics-hook/d3d10-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d10-capture.cpp @@ -107,16 +107,14 @@ static bool create_d3d10_stage_surface(ID3D10Texture2D **tex) hr = data.device->CreateTexture2D(&desc, nullptr, tex); if (FAILED(hr)) { - hlog_hr("create_d3d10_stage_surface: failed to create texture", - hr); + hlog_hr("create_d3d10_stage_surface: failed to create texture", hr); return false; } return true; } -static bool create_d3d10_tex(uint32_t cx, uint32_t cy, ID3D10Texture2D **tex, - HANDLE *handle) +static bool create_d3d10_tex(uint32_t cx, uint32_t cy, ID3D10Texture2D **tex, HANDLE *handle) { HRESULT hr; @@ -125,8 +123,7 @@ static bool create_d3d10_tex(uint32_t cx, uint32_t cy, ID3D10Texture2D **tex, desc.Height = cy; desc.MipLevels = 1; desc.ArraySize = 1; - desc.Format = apply_dxgi_format_typeless( - data.format, global_hook_info->allow_srgb_alias); + desc.Format = apply_dxgi_format_typeless(data.format, global_hook_info->allow_srgb_alias); desc.BindFlags = D3D10_BIND_SHADER_RESOURCE; desc.SampleDesc.Count = 1; desc.Usage = D3D10_USAGE_DEFAULT; @@ -140,8 +137,7 @@ static bool create_d3d10_tex(uint32_t cx, uint32_t cy, ID3D10Texture2D **tex, if (!!handle) { IDXGIResource *dxgi_res; - hr = (*tex)->QueryInterface(__uuidof(IDXGIResource), - (void **)&dxgi_res); + hr = (*tex)->QueryInterface(__uuidof(IDXGIResource), (void **)&dxgi_res); if (FAILED(hr)) { hlog_hr("create_d3d10_tex: failed to query " "IDXGIResource interface from texture", @@ -152,8 +148,7 @@ static bool create_d3d10_tex(uint32_t cx, uint32_t cy, ID3D10Texture2D **tex, hr = dxgi_res->GetSharedHandle(handle); dxgi_res->Release(); if (FAILED(hr)) { - hlog_hr("create_d3d10_tex: failed to get shared handle", - hr); + hlog_hr("create_d3d10_tex: failed to get shared handle", hr); return false; } } @@ -221,8 +216,7 @@ static bool d3d10_shmem_init(HWND window) return false; } } - if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, - data.pitch, data.format, false)) { + if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, data.pitch, data.format, false)) { return false; } @@ -236,15 +230,14 @@ static bool d3d10_shtex_init(HWND window) data.using_shtex = true; - success = - create_d3d10_tex(data.cx, data.cy, &data.texture, &data.handle); + success = create_d3d10_tex(data.cx, data.cy, &data.texture, &data.handle); if (!success) { hlog("d3d10_shtex_init: failed to create texture"); return false; } - if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, - data.format, false, (uintptr_t)data.handle)) { + if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, data.format, false, + (uintptr_t)data.handle)) { return false; } @@ -270,9 +263,7 @@ static void d3d10_init(IDXGISwapChain *swap) return; } - const bool success = global_hook_info->force_shmem - ? d3d10_shmem_init(window) - : d3d10_shtex_init(window); + const bool success = global_hook_info->force_shmem ? d3d10_shmem_init(window) : d3d10_shtex_init(window); if (!success) d3d10_free(); } @@ -323,8 +314,7 @@ static inline void d3d10_shmem_capture(ID3D10Resource *backbuffer) shmem_texture_data_unlock(data.cur_tex); } - d3d10_copy_texture(data.copy_surfaces[data.cur_tex], - backbuffer); + d3d10_copy_texture(data.copy_surfaces[data.cur_tex], backbuffer); data.texture_ready[data.cur_tex] = true; } @@ -346,8 +336,7 @@ void d3d10_capture(void *swap_ptr, void *backbuffer_ptr) if (capture_ready()) { ID3D10Resource *backbuffer; - hr = dxgi_backbuffer->QueryInterface(__uuidof(ID3D10Resource), - (void **)&backbuffer); + hr = dxgi_backbuffer->QueryInterface(__uuidof(ID3D10Resource), (void **)&backbuffer); if (FAILED(hr)) { hlog_hr("d3d10_shtex_capture: failed to get " "backbuffer", diff --git a/plugins/win-capture/graphics-hook/d3d11-capture.cpp b/plugins/win-capture/graphics-hook/d3d11-capture.cpp index 56bc46633..b896170a7 100644 --- a/plugins/win-capture/graphics-hook/d3d11-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d11-capture.cpp @@ -46,8 +46,7 @@ void d3d11_free(void) for (size_t i = 0; i < NUM_BUFFERS; i++) { if (data.copy_surfaces[i]) { if (data.texture_mapped[i]) - data.context->Unmap( - data.copy_surfaces[i], 0); + data.context->Unmap(data.copy_surfaces[i], 0); data.copy_surfaces[i]->Release(); } } @@ -74,16 +73,14 @@ static bool create_d3d11_stage_surface(ID3D11Texture2D **tex) hr = data.device->CreateTexture2D(&desc, nullptr, tex); if (FAILED(hr)) { - hlog_hr("create_d3d11_stage_surface: failed to create texture", - hr); + hlog_hr("create_d3d11_stage_surface: failed to create texture", hr); return false; } return true; } -static bool create_d3d11_tex(uint32_t cx, uint32_t cy, ID3D11Texture2D **tex, - HANDLE *handle) +static bool create_d3d11_tex(uint32_t cx, uint32_t cy, ID3D11Texture2D **tex, HANDLE *handle) { HRESULT hr; @@ -92,8 +89,7 @@ static bool create_d3d11_tex(uint32_t cx, uint32_t cy, ID3D11Texture2D **tex, desc.Height = cy; desc.MipLevels = 1; desc.ArraySize = 1; - desc.Format = apply_dxgi_format_typeless( - data.format, global_hook_info->allow_srgb_alias); + desc.Format = apply_dxgi_format_typeless(data.format, global_hook_info->allow_srgb_alias); desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc.SampleDesc.Count = 1; desc.Usage = D3D11_USAGE_DEFAULT; @@ -107,8 +103,7 @@ static bool create_d3d11_tex(uint32_t cx, uint32_t cy, ID3D11Texture2D **tex, if (!!handle) { IDXGIResource *dxgi_res; - hr = (*tex)->QueryInterface(__uuidof(IDXGIResource), - (void **)&dxgi_res); + hr = (*tex)->QueryInterface(__uuidof(IDXGIResource), (void **)&dxgi_res); if (FAILED(hr)) { hlog_hr("create_d3d11_tex: failed to query " "IDXGIResource interface from texture", @@ -119,8 +114,7 @@ static bool create_d3d11_tex(uint32_t cx, uint32_t cy, ID3D11Texture2D **tex, hr = dxgi_res->GetSharedHandle(handle); dxgi_res->Release(); if (FAILED(hr)) { - hlog_hr("create_d3d11_tex: failed to get shared handle", - hr); + hlog_hr("create_d3d11_tex: failed to get shared handle", hr); return false; } } @@ -164,8 +158,7 @@ static bool d3d11_shmem_init_buffers(size_t idx) D3D11_MAPPED_SUBRESOURCE map = {}; HRESULT hr; - hr = data.context->Map(data.copy_surfaces[idx], 0, - D3D11_MAP_READ, 0, &map); + hr = data.context->Map(data.copy_surfaces[idx], 0, D3D11_MAP_READ, 0, &map); if (FAILED(hr)) { hlog_hr("d3d11_shmem_init_buffers: failed to get " "pitch", @@ -189,8 +182,7 @@ static bool d3d11_shmem_init(HWND window) return false; } } - if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, - data.pitch, data.format, false)) { + if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, data.pitch, data.format, false)) { return false; } @@ -204,15 +196,14 @@ static bool d3d11_shtex_init(HWND window) data.using_shtex = true; - success = - create_d3d11_tex(data.cx, data.cy, &data.texture, &data.handle); + success = create_d3d11_tex(data.cx, data.cy, &data.texture, &data.handle); if (!success) { hlog("d3d11_shtex_init: failed to create texture"); return false; } - if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, - data.format, false, (uintptr_t)data.handle)) { + if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, data.format, false, + (uintptr_t)data.handle)) { return false; } @@ -240,9 +231,7 @@ static void d3d11_init(IDXGISwapChain *swap) return; } - const bool success = global_hook_info->force_shmem - ? d3d11_shmem_init(window) - : d3d11_shtex_init(window); + const bool success = global_hook_info->force_shmem ? d3d11_shmem_init(window) : d3d11_shtex_init(window); if (!success) d3d11_free(); } @@ -269,8 +258,7 @@ static void d3d11_shmem_capture_copy(int i) if (data.texture_ready[i]) { data.texture_ready[i] = false; - hr = data.context->Map(data.copy_surfaces[i], 0, D3D11_MAP_READ, - 0, &map); + hr = data.context->Map(data.copy_surfaces[i], 0, D3D11_MAP_READ, 0, &map); if (SUCCEEDED(hr)) { data.texture_mapped[i] = true; shmem_copy_data(i, map.pData); @@ -289,14 +277,12 @@ static inline void d3d11_shmem_capture(ID3D11Resource *backbuffer) data.copy_wait++; } else { if (shmem_texture_data_lock(data.cur_tex)) { - data.context->Unmap(data.copy_surfaces[data.cur_tex], - 0); + data.context->Unmap(data.copy_surfaces[data.cur_tex], 0); data.texture_mapped[data.cur_tex] = false; shmem_texture_data_unlock(data.cur_tex); } - d3d11_copy_texture(data.copy_surfaces[data.cur_tex], - backbuffer); + d3d11_copy_texture(data.copy_surfaces[data.cur_tex], backbuffer); data.texture_ready[data.cur_tex] = true; } @@ -318,8 +304,7 @@ void d3d11_capture(void *swap_ptr, void *backbuffer_ptr) if (capture_ready()) { ID3D11Resource *backbuffer; - hr = dxgi_backbuffer->QueryInterface(__uuidof(ID3D11Resource), - (void **)&backbuffer); + hr = dxgi_backbuffer->QueryInterface(__uuidof(ID3D11Resource), (void **)&backbuffer); if (FAILED(hr)) { hlog_hr("d3d11_shtex_capture: failed to get " "backbuffer", diff --git a/plugins/win-capture/graphics-hook/d3d12-capture.cpp b/plugins/win-capture/graphics-hook/d3d12-capture.cpp index 63b150d1f..1da7c7f14 100644 --- a/plugins/win-capture/graphics-hook/d3d12-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d12-capture.cpp @@ -14,8 +14,7 @@ #define MAX_BACKBUFFERS 8 -typedef HRESULT(STDMETHODCALLTYPE *PFN_ExecuteCommandLists)( - ID3D12CommandQueue *, UINT, ID3D12CommandList *const *); +typedef HRESULT(STDMETHODCALLTYPE *PFN_ExecuteCommandLists)(ID3D12CommandQueue *, UINT, ID3D12CommandList *const *); static PFN_ExecuteCommandLists RealExecuteCommandLists = nullptr; @@ -81,16 +80,14 @@ static bool create_d3d12_tex(UINT count) desc11.Height = data.cy; desc11.MipLevels = 1; desc11.ArraySize = 1; - desc11.Format = apply_dxgi_format_typeless( - data.format, global_hook_info->allow_srgb_alias); + desc11.Format = apply_dxgi_format_typeless(data.format, global_hook_info->allow_srgb_alias); desc11.SampleDesc.Count = 1; desc11.BindFlags = D3D11_BIND_SHADER_RESOURCE; desc11.MiscFlags = D3D11_RESOURCE_MISC_SHARED; hr = data.device11->CreateTexture2D(&desc11, nullptr, &data.copy_tex); if (FAILED(hr)) { - hlog_hr("create_d3d12_tex: creation of d3d11 copy tex failed", - hr); + hlog_hr("create_d3d12_tex: creation of d3d11 copy tex failed", hr); return false; } @@ -133,8 +130,7 @@ static bool d3d12_init_11on12(ID3D12Device *device) } if (!initialized_func && !create_11_on_12) { - create_11_on_12 = (PFN_D3D11ON12_CREATE_DEVICE)GetProcAddress( - d3d11, "D3D11On12CreateDevice"); + create_11_on_12 = (PFN_D3D11ON12_CREATE_DEVICE)GetProcAddress(d3d11, "D3D11On12CreateDevice"); if (!create_11_on_12) { hlog("d3d12_init_11on12: Failed to get " "D3D11On12CreateDevice address"); @@ -153,9 +149,8 @@ static bool d3d12_init_11on12(ID3D12Device *device) hlog("d3d12_init_11on12: creating 11 device: queue=0x%" PRIX64, (uint64_t)(uintptr_t)dxgi_possible_swap_queues[i]); IUnknown *const queue = dxgi_possible_swap_queues[i]; - const HRESULT hr = create_11_on_12(device, 0, nullptr, 0, - &queue, 1, 0, &data.device11, - &data.context11, nullptr); + const HRESULT hr = + create_11_on_12(device, 0, nullptr, 0, &queue, 1, 0, &data.device11, &data.context11, nullptr); created = SUCCEEDED(hr); if (created) { break; @@ -172,8 +167,7 @@ static bool d3d12_init_11on12(ID3D12Device *device) dxgi_possible_swap_queue_count = 0; dxgi_present_attempted = false; - const HRESULT hr = - data.device11->QueryInterface(IID_PPV_ARGS(&data.device11on12)); + const HRESULT hr = data.device11->QueryInterface(IID_PPV_ARGS(&data.device11on12)); if (FAILED(hr)) { hlog_hr("d3d12_init_11on12: failed to query 11on12 device", hr); return false; @@ -190,8 +184,8 @@ static bool d3d12_shtex_init(ID3D12Device *device, HWND window, UINT count) if (!create_d3d12_tex(count)) { return false; } - if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, - data.format, false, (uintptr_t)data.handle)) { + if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, data.format, false, + (uintptr_t)data.handle)) { return false; } @@ -226,9 +220,7 @@ static inline UINT d3d12_init_format(IDXGISwapChain *swap, HWND &window) swap3->Release(); } - UINT count = desc.SwapEffect == DXGI_SWAP_EFFECT_DISCARD - ? 1 - : desc.BufferCount; + UINT count = desc.SwapEffect == DXGI_SWAP_EFFECT_DISCARD ? 1 : desc.BufferCount; if (count == 1) data.dxgi_1_4 = false; @@ -248,8 +240,7 @@ static void d3d12_init(IDXGISwapChain *swap) ID3D12Device *device = nullptr; const HRESULT hr = swap->GetDevice(IID_PPV_ARGS(&device)); if (SUCCEEDED(hr)) { - hlog("d3d12_init: device=0x%" PRIX64, - (uint64_t)(uintptr_t)device); + hlog("d3d12_init: device=0x%" PRIX64, (uint64_t)(uintptr_t)device); HWND window; UINT count = d3d12_init_format(swap, window); @@ -284,8 +275,7 @@ static inline void d3d12_shtex_capture(IDXGISwapChain *swap) UINT cur_idx; if (dxgi_1_4) { - IDXGISwapChain3 *swap3 = - reinterpret_cast(swap); + IDXGISwapChain3 *swap3 = reinterpret_cast(swap); cur_idx = swap3->GetCurrentBackBufferIndex(); } else { cur_idx = data.cur_backbuffer; @@ -296,19 +286,15 @@ static inline void d3d12_shtex_capture(IDXGISwapChain *swap) D3D11_RESOURCE_FLAGS rf11 = {}; ID3D11Resource *backbuffer; if (SUCCEEDED(data.device11on12->CreateWrappedResource( - backbuffer12, &rf11, D3D12_RESOURCE_STATE_PRESENT, - D3D12_RESOURCE_STATE_PRESENT, + backbuffer12, &rf11, D3D12_RESOURCE_STATE_PRESENT, D3D12_RESOURCE_STATE_PRESENT, IID_PPV_ARGS(&backbuffer)))) { - data.device11on12->AcquireWrappedResources(&backbuffer, - 1); + data.device11on12->AcquireWrappedResources(&backbuffer, 1); d3d12_copy_texture(data.copy_tex, backbuffer); - data.device11on12->ReleaseWrappedResources(&backbuffer, - 1); + data.device11on12->ReleaseWrappedResources(&backbuffer, 1); data.context11->Flush(); if (!dxgi_1_4) { - if (++data.cur_backbuffer >= - data.backbuffer_count) + if (++data.cur_backbuffer >= data.backbuffer_count) data.cur_backbuffer = 0; } @@ -346,44 +332,33 @@ static bool try_append_queue_if_unique(ID3D12CommandQueue *queue) return true; } -static HRESULT STDMETHODCALLTYPE -hook_execute_command_lists(ID3D12CommandQueue *queue, UINT NumCommandLists, - ID3D12CommandList *const *ppCommandLists) +static HRESULT STDMETHODCALLTYPE hook_execute_command_lists(ID3D12CommandQueue *queue, UINT NumCommandLists, + ID3D12CommandList *const *ppCommandLists) { - hlog_verbose("ExecuteCommandLists callback: queue=0x%" PRIX64, - (uint64_t)(uintptr_t)queue); + hlog_verbose("ExecuteCommandLists callback: queue=0x%" PRIX64, (uint64_t)(uintptr_t)queue); - if (dxgi_possible_swap_queue_count < - _countof(dxgi_possible_swap_queues)) { - if ((dxgi_presenting > 0) && - (queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT)) { + if (dxgi_possible_swap_queue_count < _countof(dxgi_possible_swap_queues)) { + if ((dxgi_presenting > 0) && (queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT)) { if (try_append_queue_if_unique(queue)) { hlog("Remembering D3D12 queue from present: queue=0x%" PRIX64, (uint64_t)(uintptr_t)queue); } - } else if (dxgi_present_attempted && - (queue->GetDesc().Type == - D3D12_COMMAND_LIST_TYPE_DIRECT)) { + } else if (dxgi_present_attempted && (queue->GetDesc().Type == D3D12_COMMAND_LIST_TYPE_DIRECT)) { if (try_append_queue_if_unique(queue)) { hlog("Remembering D3D12 queue from first direct submit after present: queue=0x%" PRIX64, (uint64_t)(uintptr_t)queue); } } else { - hlog_verbose("Ignoring D3D12 queue=0x%" PRIX64, - (uint64_t)(uintptr_t)queue); + hlog_verbose("Ignoring D3D12 queue=0x%" PRIX64, (uint64_t)(uintptr_t)queue); } } return RealExecuteCommandLists(queue, NumCommandLists, ppCommandLists); } -static bool -manually_get_d3d12_addrs(HMODULE d3d12_module, - PFN_ExecuteCommandLists *execute_command_lists_addr) +static bool manually_get_d3d12_addrs(HMODULE d3d12_module, PFN_ExecuteCommandLists *execute_command_lists_addr) { - PFN_D3D12_CREATE_DEVICE create = - (PFN_D3D12_CREATE_DEVICE)GetProcAddress(d3d12_module, - "D3D12CreateDevice"); + PFN_D3D12_CREATE_DEVICE create = (PFN_D3D12_CREATE_DEVICE)GetProcAddress(d3d12_module, "D3D12CreateDevice"); if (!create) { hlog("Failed to load D3D12CreateDevice"); return false; @@ -391,17 +366,14 @@ manually_get_d3d12_addrs(HMODULE d3d12_module, bool success = false; ID3D12Device *device; - if (SUCCEEDED(create(NULL, D3D_FEATURE_LEVEL_11_0, - IID_PPV_ARGS(&device)))) { + if (SUCCEEDED(create(NULL, D3D_FEATURE_LEVEL_11_0, IID_PPV_ARGS(&device)))) { D3D12_COMMAND_QUEUE_DESC desc{}; ID3D12CommandQueue *queue; - HRESULT hr = - device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)); + HRESULT hr = device->CreateCommandQueue(&desc, IID_PPV_ARGS(&queue)); success = SUCCEEDED(hr); if (success) { void **queue_vtable = *(void ***)queue; - *execute_command_lists_addr = - (PFN_ExecuteCommandLists)queue_vtable[10]; + *execute_command_lists_addr = (PFN_ExecuteCommandLists)queue_vtable[10]; queue->Release(); } else { @@ -420,14 +392,12 @@ bool hook_d3d12(void) { HMODULE d3d12_module = get_system_module("d3d12.dll"); if (!d3d12_module) { - hlog_verbose( - "Failed to find d3d12.dll. Skipping hook attempt."); + hlog_verbose("Failed to find d3d12.dll. Skipping hook attempt."); return false; } PFN_ExecuteCommandLists execute_command_lists_addr = nullptr; - if (!manually_get_d3d12_addrs(d3d12_module, - &execute_command_lists_addr)) { + if (!manually_get_d3d12_addrs(d3d12_module, &execute_command_lists_addr)) { hlog("Failed to get D3D12 values"); return true; } @@ -440,8 +410,7 @@ bool hook_d3d12(void) DetourTransactionBegin(); RealExecuteCommandLists = execute_command_lists_addr; - DetourAttach(&(PVOID &)RealExecuteCommandLists, - hook_execute_command_lists); + DetourAttach(&(PVOID &)RealExecuteCommandLists, hook_execute_command_lists); const LONG error = DetourTransactionCommit(); const bool success = error == NO_ERROR; diff --git a/plugins/win-capture/graphics-hook/d3d8-capture.cpp b/plugins/win-capture/graphics-hook/d3d8-capture.cpp index 36d363bbd..3e6a743c1 100644 --- a/plugins/win-capture/graphics-hook/d3d8-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d8-capture.cpp @@ -9,11 +9,8 @@ #include -typedef HRESULT(STDMETHODCALLTYPE *reset_t)(IDirect3DDevice8 *, - D3DPRESENT_PARAMETERS *); -typedef HRESULT(STDMETHODCALLTYPE *present_t)(IDirect3DDevice8 *, CONST RECT *, - CONST RECT *, HWND, - CONST RGNDATA *); +typedef HRESULT(STDMETHODCALLTYPE *reset_t)(IDirect3DDevice8 *, D3DPRESENT_PARAMETERS *); +typedef HRESULT(STDMETHODCALLTYPE *present_t)(IDirect3DDevice8 *, CONST RECT *, CONST RECT *, HWND, CONST RGNDATA *); reset_t RealReset = NULL; present_t RealPresent = NULL; @@ -119,8 +116,7 @@ static bool d3d8_shmem_init_buffer(IDirect3DDevice8 *device, int idx) { HRESULT hr; - hr = device->CreateImageSurface(data.cx, data.cy, data.d3d8_format, - &data.copy_surfaces[idx]); + hr = device->CreateImageSurface(data.cx, data.cy, data.d3d8_format, &data.copy_surfaces[idx]); if (FAILED(hr)) { hlog_hr("d3d8_shmem_init_buffer: Failed to create surface", hr); return false; @@ -128,11 +124,9 @@ static bool d3d8_shmem_init_buffer(IDirect3DDevice8 *device, int idx) if (idx == 0) { D3DLOCKED_RECT rect; - hr = data.copy_surfaces[0]->LockRect(&rect, nullptr, - D3DLOCK_READONLY); + hr = data.copy_surfaces[0]->LockRect(&rect, nullptr, D3DLOCK_READONLY); if (FAILED(hr)) { - hlog_hr("d3d8_shmem_init_buffer: Failed to lock buffer", - hr); + hlog_hr("d3d8_shmem_init_buffer: Failed to lock buffer", hr); return false; } @@ -150,8 +144,7 @@ static bool d3d8_shmem_init(IDirect3DDevice8 *device) return false; } } - if (!capture_init_shmem(&data.shmem_info, data.window, data.cx, data.cy, - data.pitch, data.dxgi_format, false)) { + if (!capture_init_shmem(&data.shmem_info, data.window, data.cx, data.cy, data.pitch, data.dxgi_format, false)) { return false; } @@ -204,8 +197,7 @@ static void d3d8_shmem_capture_copy(int idx) } } -static void d3d8_shmem_capture(IDirect3DDevice8 *device, - IDirect3DSurface8 *backbuffer) +static void d3d8_shmem_capture(IDirect3DDevice8 *device, IDirect3DSurface8 *backbuffer) { int next_surface; HRESULT hr; @@ -238,8 +230,7 @@ static void d3d8_shmem_capture(IDirect3DDevice8 *device, data.cur_surface = next_surface; } -static void d3d8_capture(IDirect3DDevice8 *device, - IDirect3DSurface8 *backbuffer) +static void d3d8_capture(IDirect3DDevice8 *device, IDirect3DSurface8 *backbuffer) { if (capture_should_stop()) { d3d8_free(); @@ -252,8 +243,7 @@ static void d3d8_capture(IDirect3DDevice8 *device, } } -static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice8 *device, - D3DPRESENT_PARAMETERS *parameters) +static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice8 *device, D3DPRESENT_PARAMETERS *parameters) { if (capture_active()) d3d8_free(); @@ -282,11 +272,8 @@ static void setup_reset_hooks(IDirect3DDevice8 *device) } } -static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice8 *device, - CONST RECT *src_rect, - CONST RECT *dst_rect, - HWND override_window, - CONST RGNDATA *dirty_region) +static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice8 *device, CONST RECT *src_rect, CONST RECT *dst_rect, + HWND override_window, CONST RGNDATA *dirty_region) { IDirect3DSurface8 *backbuffer; @@ -299,14 +286,12 @@ static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice8 *device, backbuffer->Release(); } - return RealPresent(device, src_rect, dst_rect, override_window, - dirty_region); + return RealPresent(device, src_rect, dst_rect, override_window, dirty_region); } typedef IDirect3D8 *(WINAPI *d3d8create_t)(UINT); -static bool manually_get_d3d8_present_addr(HMODULE d3d8_module, - void **present_addr) +static bool manually_get_d3d8_present_addr(HMODULE d3d8_module, void **present_addr) { d3d8create_t create; D3DPRESENT_PARAMETERS pp; @@ -338,10 +323,8 @@ static bool manually_get_d3d8_present_addr(HMODULE d3d8_module, pp.BackBufferCount = 1; pp.hDeviceWindow = dummy_window; - hr = d3d8->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, - dummy_window, - D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp, - &device); + hr = d3d8->CreateDevice(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, dummy_window, D3DCREATE_HARDWARE_VERTEXPROCESSING, + &pp, &device); d3d8->Release(); if (SUCCEEDED(hr)) { @@ -370,15 +353,13 @@ bool hook_d3d8(void) d3d8_size = module_size(d3d8_module); if (global_hook_info->offsets.d3d8.present < d3d8_size) { - present_addr = get_offset_addr( - d3d8_module, global_hook_info->offsets.d3d8.present); + present_addr = get_offset_addr(d3d8_module, global_hook_info->offsets.d3d8.present); } else { if (!dummy_window) { return false; } - if (!manually_get_d3d8_present_addr(d3d8_module, - &present_addr)) { + if (!manually_get_d3d8_present_addr(d3d8_module, &present_addr)) { hlog("Failed to get D3D8 value"); return true; } diff --git a/plugins/win-capture/graphics-hook/d3d9-capture.cpp b/plugins/win-capture/graphics-hook/d3d9-capture.cpp index cf537435b..81b7a0461 100644 --- a/plugins/win-capture/graphics-hook/d3d9-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d9-capture.cpp @@ -7,21 +7,13 @@ #include -typedef HRESULT(STDMETHODCALLTYPE *present_t)(IDirect3DDevice9 *, CONST RECT *, - CONST RECT *, HWND, - CONST RGNDATA *); -typedef HRESULT(STDMETHODCALLTYPE *present_ex_t)(IDirect3DDevice9Ex *, - CONST RECT *, CONST RECT *, - HWND, CONST RGNDATA *, DWORD); -typedef HRESULT(STDMETHODCALLTYPE *present_swap_t)(IDirect3DSwapChain9 *, - CONST RECT *, CONST RECT *, - HWND, CONST RGNDATA *, - DWORD); -typedef HRESULT(STDMETHODCALLTYPE *reset_t)(IDirect3DDevice9 *, - D3DPRESENT_PARAMETERS *); -typedef HRESULT(STDMETHODCALLTYPE *reset_ex_t)(IDirect3DDevice9 *, - D3DPRESENT_PARAMETERS *, - D3DDISPLAYMODEEX *); +typedef HRESULT(STDMETHODCALLTYPE *present_t)(IDirect3DDevice9 *, CONST RECT *, CONST RECT *, HWND, CONST RGNDATA *); +typedef HRESULT(STDMETHODCALLTYPE *present_ex_t)(IDirect3DDevice9Ex *, CONST RECT *, CONST RECT *, HWND, + CONST RGNDATA *, DWORD); +typedef HRESULT(STDMETHODCALLTYPE *present_swap_t)(IDirect3DSwapChain9 *, CONST RECT *, CONST RECT *, HWND, + CONST RGNDATA *, DWORD); +typedef HRESULT(STDMETHODCALLTYPE *reset_t)(IDirect3DDevice9 *, D3DPRESENT_PARAMETERS *); +typedef HRESULT(STDMETHODCALLTYPE *reset_ex_t)(IDirect3DDevice9 *, D3DPRESENT_PARAMETERS *, D3DDISPLAYMODEEX *); typedef HRESULT(WINAPI *createfactory1_t)(REFIID, void **); @@ -135,15 +127,13 @@ static inline bool shex_init_d3d11() return false; } - create_factory = - (createfactory1_t)GetProcAddress(dxgi, "CreateDXGIFactory1"); + create_factory = (createfactory1_t)GetProcAddress(dxgi, "CreateDXGIFactory1"); if (!create_factory) { hlog("d3d9_init: Failed to get CreateDXGIFactory1 address"); return false; } - create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress( - d3d11, "D3D11CreateDevice"); + create_device = (PFN_D3D11_CREATE_DEVICE)GetProcAddress(d3d11, "D3D11CreateDevice"); if (!create_device) { hlog("d3d9_init: Failed to get D3D11CreateDevice address"); return false; @@ -163,11 +153,9 @@ static inline bool shex_init_d3d11() return false; } - hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, - feature_levels, - sizeof(feature_levels) / sizeof(D3D_FEATURE_LEVEL), - D3D11_SDK_VERSION, &data.d3d11_device, &level_used, - &data.d3d11_context); + hr = create_device(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, feature_levels, + sizeof(feature_levels) / sizeof(D3D_FEATURE_LEVEL), D3D11_SDK_VERSION, &data.d3d11_device, + &level_used, &data.d3d11_context); adapter->Release(); if (FAILED(hr)) { @@ -194,19 +182,15 @@ static inline bool d3d9_shtex_init_shtex() desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; desc.BindFlags = D3D11_BIND_RENDER_TARGET | D3D11_BIND_SHADER_RESOURCE; - hr = data.d3d11_device->CreateTexture2D( - &desc, nullptr, (ID3D11Texture2D **)&data.d3d11_tex); + hr = data.d3d11_device->CreateTexture2D(&desc, nullptr, (ID3D11Texture2D **)&data.d3d11_tex); if (FAILED(hr)) { - hlog_hr("d3d9_shtex_init_shtex: Failed to create D3D11 texture", - hr); + hlog_hr("d3d9_shtex_init_shtex: Failed to create D3D11 texture", hr); return false; } - hr = data.d3d11_tex->QueryInterface(__uuidof(IDXGIResource), - (void **)&res); + hr = data.d3d11_tex->QueryInterface(__uuidof(IDXGIResource), (void **)&res); if (FAILED(hr)) { - hlog_hr("d3d9_shtex_init_shtex: Failed to query IDXGIResource", - hr); + hlog_hr("d3d9_shtex_init_shtex: Failed to query IDXGIResource", hr); return false; } @@ -214,8 +198,7 @@ static inline bool d3d9_shtex_init_shtex() res->Release(); if (FAILED(hr)) { - hlog_hr("d3d9_shtex_init_shtex: Failed to get shared handle", - hr); + hlog_hr("d3d9_shtex_init_shtex: Failed to get shared handle", hr); return false; } @@ -236,8 +219,7 @@ static inline bool d3d9_shtex_init_copytex() if (offsets.d3d9_clsoff && offsets.is_d3d9ex_clsoff) { uint8_t *device_ptr = (uint8_t *)(data.device); - uint8_t *d3d9_ptr = - *(uint8_t **)(device_ptr + offsets.d3d9_clsoff); + uint8_t *d3d9_ptr = *(uint8_t **)(device_ptr + offsets.d3d9_clsoff); p_is_d3d9 = (BOOL *)(d3d9_ptr + offsets.is_d3d9ex_clsoff); } else { patch_addr = get_d3d9_patch_addr(data.d3d9, data.patch); @@ -249,28 +231,24 @@ static inline bool d3d9_shtex_init_copytex() } else if (patch_addr) { patch_size = patch[data.patch].size; - VirtualProtect(patch_addr, patch_size, PAGE_EXECUTE_READWRITE, - &protect_val); + VirtualProtect(patch_addr, patch_size, PAGE_EXECUTE_READWRITE, &protect_val); memcpy(saved_data, patch_addr, patch_size); memcpy(patch_addr, patch[data.patch].data, patch_size); } - hr = data.device->CreateTexture(data.cx, data.cy, 1, - D3DUSAGE_RENDERTARGET, data.d3d9_format, - D3DPOOL_DEFAULT, &tex, &data.handle); + hr = data.device->CreateTexture(data.cx, data.cy, 1, D3DUSAGE_RENDERTARGET, data.d3d9_format, D3DPOOL_DEFAULT, + &tex, &data.handle); if (p_is_d3d9) { *p_is_d3d9 = was_d3d9ex; } else if (patch_addr && patch_size) { memcpy(patch_addr, saved_data, patch_size); - VirtualProtect(patch_addr, patch_size, protect_val, - &protect_val); + VirtualProtect(patch_addr, patch_size, protect_val, &protect_val); } if (FAILED(hr)) { - hlog_hr("d3d9_shtex_init_copytex: Failed to create shared texture", - hr); + hlog_hr("d3d9_shtex_init_copytex: Failed to create shared texture", hr); return false; } @@ -278,8 +256,7 @@ static inline bool d3d9_shtex_init_copytex() tex->Release(); if (FAILED(hr)) { - hlog_hr("d3d9_shtex_init_copytex: Failed to get surface level", - hr); + hlog_hr("d3d9_shtex_init_copytex: Failed to get surface level", hr); return false; } @@ -299,8 +276,7 @@ static bool d3d9_shtex_init(HWND window) if (!d3d9_shtex_init_copytex()) { return false; } - if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, - data.dxgi_format, false, + if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, data.dxgi_format, false, (uintptr_t)data.handle)) { return false; } @@ -313,19 +289,16 @@ static bool d3d9_shmem_init_buffers(size_t buffer) { HRESULT hr; - hr = data.device->CreateOffscreenPlainSurface( - data.cx, data.cy, data.d3d9_format, D3DPOOL_SYSTEMMEM, - &data.copy_surfaces[buffer], nullptr); + hr = data.device->CreateOffscreenPlainSurface(data.cx, data.cy, data.d3d9_format, D3DPOOL_SYSTEMMEM, + &data.copy_surfaces[buffer], nullptr); if (FAILED(hr)) { - hlog_hr("d3d9_shmem_init_buffers: Failed to create surface", - hr); + hlog_hr("d3d9_shmem_init_buffers: Failed to create surface", hr); return false; } if (buffer == 0) { D3DLOCKED_RECT rect; - hr = data.copy_surfaces[buffer]->LockRect(&rect, nullptr, - D3DLOCK_READONLY); + hr = data.copy_surfaces[buffer]->LockRect(&rect, nullptr, D3DLOCK_READONLY); if (FAILED(hr)) { hlog_hr("d3d9_shmem_init_buffers: Failed to lock " "buffer", @@ -337,8 +310,7 @@ static bool d3d9_shmem_init_buffers(size_t buffer) data.copy_surfaces[buffer]->UnlockRect(); } - hr = data.device->CreateQuery(D3DQUERYTYPE_EVENT, - &data.queries[buffer]); + hr = data.device->CreateQuery(D3DQUERYTYPE_EVENT, &data.queries[buffer]); if (FAILED(hr)) { hlog_hr("d3d9_shmem_init_buffers: Failed to create query", hr); return false; @@ -356,8 +328,7 @@ static bool d3d9_shmem_init(HWND window) return false; } } - if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, - data.pitch, data.dxgi_format, false)) { + if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, data.pitch, data.dxgi_format, false)) { return false; } @@ -446,9 +417,8 @@ static bool d3d9_init_format_swapchain(HWND &window) static void d3d9_init(IDirect3DDevice9 *device) { IDirect3DDevice9Ex *d3d9ex = nullptr; - bool has_d3d9ex_bool_offset = - global_hook_info->offsets.d3d9.d3d9_clsoff && - global_hook_info->offsets.d3d9.is_d3d9ex_clsoff; + bool has_d3d9ex_bool_offset = global_hook_info->offsets.d3d9.d3d9_clsoff && + global_hook_info->offsets.d3d9.is_d3d9ex_clsoff; bool success; HWND window = nullptr; HRESULT hr; @@ -456,8 +426,7 @@ static void d3d9_init(IDirect3DDevice9 *device) data.d3d9 = get_system_module("d3d9.dll"); data.device = device; - hr = device->QueryInterface(__uuidof(IDirect3DDevice9Ex), - (void **)&d3d9ex); + hr = device->QueryInterface(__uuidof(IDirect3DDevice9Ex), (void **)&d3d9ex); if (SUCCEEDED(hr)) { d3d9ex->Release(); data.patch = -1; @@ -473,8 +442,7 @@ static void d3d9_init(IDirect3DDevice9 *device) } } - if (global_hook_info->force_shmem || - (!d3d9ex && data.patch == -1 && !has_d3d9ex_bool_offset)) { + if (global_hook_info->force_shmem || (!d3d9ex && data.patch == -1 && !has_d3d9ex_bool_offset)) { success = d3d9_shmem_init(window); } else { success = d3d9_shtex_init(window); @@ -484,8 +452,7 @@ static void d3d9_init(IDirect3DDevice9 *device) d3d9_free(); } -static inline HRESULT get_backbuffer(IDirect3DDevice9 *device, - IDirect3DSurface9 **surface) +static inline HRESULT get_backbuffer(IDirect3DDevice9 *device, IDirect3DSurface9 **surface) { static bool use_backbuffer = false; static bool checked_exceptions = false; @@ -497,8 +464,7 @@ static inline HRESULT get_backbuffer(IDirect3DDevice9 *device, } if (use_backbuffer) { - return device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, - surface); + return device->GetBackBuffer(0, 0, D3DBACKBUFFER_TYPE_MONO, surface); } else { return device->GetRenderTarget(0, surface); } @@ -508,8 +474,7 @@ static inline void d3d9_shtex_capture(IDirect3DSurface9 *backbuffer) { HRESULT hr; - hr = data.device->StretchRect(backbuffer, nullptr, data.d3d9_copytex, - nullptr, D3DTEXF_NONE); + hr = data.device->StretchRect(backbuffer, nullptr, data.d3d9_copytex, nullptr, D3DTEXF_NONE); if (FAILED(hr)) hlog_hr("d3d9_shtex_capture: StretchRect failed", hr); } @@ -570,8 +535,7 @@ static inline void d3d9_shmem_capture(IDirect3DSurface9 *backbuffer) data.cur_tex = next_tex; } -static void d3d9_capture(IDirect3DDevice9 *device, - IDirect3DSurface9 *backbuffer) +static void d3d9_capture(IDirect3DDevice9 *device, IDirect3DSurface9 *backbuffer) { if (capture_should_stop()) { d3d9_free(); @@ -595,8 +559,7 @@ static void d3d9_capture(IDirect3DDevice9 *device, /* this is used just in case Present calls PresentEx or vise versa. */ static int present_recurse = 0; -static inline void present_begin(IDirect3DDevice9 *device, - IDirect3DSurface9 *&backbuffer) +static inline void present_begin(IDirect3DDevice9 *device, IDirect3DSurface9 *&backbuffer) { HRESULT hr; @@ -616,8 +579,7 @@ static inline void present_begin(IDirect3DDevice9 *device, present_recurse++; } -static inline void present_end(IDirect3DDevice9 *device, - IDirect3DSurface9 *backbuffer) +static inline void present_end(IDirect3DDevice9 *device, IDirect3DSurface9 *backbuffer) { present_recurse--; @@ -635,11 +597,8 @@ static inline void present_end(IDirect3DDevice9 *device, static bool hooked_reset = false; static void setup_reset_hooks(IDirect3DDevice9 *device); -static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice9 *device, - CONST RECT *src_rect, - CONST RECT *dst_rect, - HWND override_window, - CONST RGNDATA *dirty_region) +static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice9 *device, CONST RECT *src_rect, CONST RECT *dst_rect, + HWND override_window, CONST RGNDATA *dirty_region) { IDirect3DSurface9 *backbuffer = nullptr; @@ -648,17 +607,15 @@ static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice9 *device, present_begin(device, backbuffer); - const HRESULT hr = RealPresent(device, src_rect, dst_rect, - override_window, dirty_region); + const HRESULT hr = RealPresent(device, src_rect, dst_rect, override_window, dirty_region); present_end(device, backbuffer); return hr; } -static HRESULT STDMETHODCALLTYPE hook_present_ex( - IDirect3DDevice9Ex *device, CONST RECT *src_rect, CONST RECT *dst_rect, - HWND override_window, CONST RGNDATA *dirty_region, DWORD flags) +static HRESULT STDMETHODCALLTYPE hook_present_ex(IDirect3DDevice9Ex *device, CONST RECT *src_rect, CONST RECT *dst_rect, + HWND override_window, CONST RGNDATA *dirty_region, DWORD flags) { IDirect3DSurface9 *backbuffer = nullptr; @@ -667,17 +624,16 @@ static HRESULT STDMETHODCALLTYPE hook_present_ex( present_begin(device, backbuffer); - const HRESULT hr = RealPresentEx(device, src_rect, dst_rect, - override_window, dirty_region, flags); + const HRESULT hr = RealPresentEx(device, src_rect, dst_rect, override_window, dirty_region, flags); present_end(device, backbuffer); return hr; } -static HRESULT STDMETHODCALLTYPE hook_present_swap( - IDirect3DSwapChain9 *swap, CONST RECT *src_rect, CONST RECT *dst_rect, - HWND override_window, CONST RGNDATA *dirty_region, DWORD flags) +static HRESULT STDMETHODCALLTYPE hook_present_swap(IDirect3DSwapChain9 *swap, CONST RECT *src_rect, + CONST RECT *dst_rect, HWND override_window, + CONST RGNDATA *dirty_region, DWORD flags) { IDirect3DSurface9 *backbuffer = nullptr; IDirect3DDevice9 *device = nullptr; @@ -696,8 +652,7 @@ static HRESULT STDMETHODCALLTYPE hook_present_swap( present_begin(device, backbuffer); } - const HRESULT hr = RealPresentSwap( - swap, src_rect, dst_rect, override_window, dirty_region, flags); + const HRESULT hr = RealPresentSwap(swap, src_rect, dst_rect, override_window, dirty_region, flags); if (device) { present_end(device, backbuffer); @@ -707,8 +662,7 @@ static HRESULT STDMETHODCALLTYPE hook_present_swap( return hr; } -static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice9 *device, - D3DPRESENT_PARAMETERS *params) +static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice9 *device, D3DPRESENT_PARAMETERS *params) { if (capture_active()) d3d9_free(); @@ -716,8 +670,7 @@ static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice9 *device, return RealReset(device, params); } -static HRESULT STDMETHODCALLTYPE hook_reset_ex(IDirect3DDevice9 *device, - D3DPRESENT_PARAMETERS *params, +static HRESULT STDMETHODCALLTYPE hook_reset_ex(IDirect3DDevice9 *device, D3DPRESENT_PARAMETERS *params, D3DDISPLAYMODEEX *dmex) { if (capture_active()) @@ -760,8 +713,7 @@ static void setup_reset_hooks(IDirect3DDevice9 *device) typedef HRESULT(WINAPI *d3d9create_ex_t)(UINT, IDirect3D9Ex **); -static bool manually_get_d3d9_addrs(HMODULE d3d9_module, void **present_addr, - void **present_ex_addr, +static bool manually_get_d3d9_addrs(HMODULE d3d9_module, void **present_addr, void **present_ex_addr, void **present_swap_addr) { d3d9create_ex_t create_ex; @@ -773,8 +725,7 @@ static bool manually_get_d3d9_addrs(HMODULE d3d9_module, void **present_addr, hlog("D3D9 values invalid, manually obtaining"); - create_ex = (d3d9create_ex_t)GetProcAddress(d3d9_module, - "Direct3DCreate9Ex"); + create_ex = (d3d9create_ex_t)GetProcAddress(d3d9_module, "Direct3DCreate9Ex"); if (!create_ex) { hlog("Failed to load Direct3DCreate9Ex"); return false; @@ -792,10 +743,9 @@ static bool manually_get_d3d9_addrs(HMODULE d3d9_module, void **present_addr, pp.hDeviceWindow = (HWND)dummy_window; pp.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE; - hr = d3d9ex->CreateDeviceEx( - D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, dummy_window, - D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_NOWINDOWCHANGES, - &pp, NULL, &device); + hr = d3d9ex->CreateDeviceEx(D3DADAPTER_DEFAULT, D3DDEVTYPE_HAL, dummy_window, + D3DCREATE_HARDWARE_VERTEXPROCESSING | D3DCREATE_NOWINDOWCHANGES, &pp, NULL, + &device); d3d9ex->Release(); if (SUCCEEDED(hr)) { @@ -840,21 +790,15 @@ bool hook_d3d9(void) global_hook_info->offsets.d3d9.present_ex < d3d9_size && global_hook_info->offsets.d3d9.present_swap < d3d9_size) { - present_addr = get_offset_addr( - d3d9_module, global_hook_info->offsets.d3d9.present); - present_ex_addr = get_offset_addr( - d3d9_module, global_hook_info->offsets.d3d9.present_ex); - present_swap_addr = get_offset_addr( - d3d9_module, - global_hook_info->offsets.d3d9.present_swap); + present_addr = get_offset_addr(d3d9_module, global_hook_info->offsets.d3d9.present); + present_ex_addr = get_offset_addr(d3d9_module, global_hook_info->offsets.d3d9.present_ex); + present_swap_addr = get_offset_addr(d3d9_module, global_hook_info->offsets.d3d9.present_swap); } else { if (!dummy_window) { return false; } - if (!manually_get_d3d9_addrs(d3d9_module, &present_addr, - &present_ex_addr, - &present_swap_addr)) { + if (!manually_get_d3d9_addrs(d3d9_module, &present_addr, &present_ex_addr, &present_swap_addr)) { hlog("Failed to get D3D9 values"); return true; } diff --git a/plugins/win-capture/graphics-hook/d3d9-patches.hpp b/plugins/win-capture/graphics-hook/d3d9-patches.hpp index eadcefbfe..79d136a10 100644 --- a/plugins/win-capture/graphics-hook/d3d9-patches.hpp +++ b/plugins/win-capture/graphics-hook/d3d9-patches.hpp @@ -83,47 +83,29 @@ static const uintptr_t patch_offset[NUM_VERS] = { }; static const uint8_t patch_cmp[NUM_VERS][CMP_SIZE] = { - {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x98, 0x68, 0x50, 0x00, - 0x00}, - {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x98, 0x68, 0x50, 0x00, - 0x00}, - {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x98, 0x68, 0x50, 0x00, - 0x00}, - {0x8b, 0x81, 0x18, 0x3e, 0x00, 0x00, 0x44, 0x39, 0x98, 0x90, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0x18, 0x3e, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0x18, 0x3e, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, - 0x00}, - {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0xB0, 0x28, 0x51, 0x00, - 0x00}, - {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0xA8, 0x28, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, - 0x00}, - {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, - 0x00}, - {0x49, 0x8b, 0x85, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x88, 0xc8, 0x50, 0x00, - 0x00}, + {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x98, 0x68, 0x50, 0x00, 0x00}, + {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x98, 0x68, 0x50, 0x00, 0x00}, + {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x98, 0x68, 0x50, 0x00, 0x00}, + {0x8b, 0x81, 0x18, 0x3e, 0x00, 0x00, 0x44, 0x39, 0x98, 0x90, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0x18, 0x3e, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0x18, 0x3e, 0x00, 0x00, 0x44, 0x39, 0x98, 0x88, 0x51, 0x00, 0x00}, + {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0xB0, 0x28, 0x51, 0x00, 0x00}, + {0x48, 0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0xA8, 0x28, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, 0x00}, + {0x8b, 0x81, 0xb8, 0x3d, 0x00, 0x00, 0x44, 0x39, 0xA0, 0x28, 0x51, 0x00, 0x00}, + {0x49, 0x8b, 0x85, 0xb8, 0x3d, 0x00, 0x00, 0x39, 0x88, 0xc8, 0x50, 0x00, 0x00}, }; static const struct patch_info patch[NUM_VERS] = { - NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), - NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), - NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), - NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), - NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), - NEW_PATCH(ignore_jump), + NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), + NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), + NEW_PATCH(force_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), + NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), }; #else @@ -151,47 +133,29 @@ static const uintptr_t patch_offset[NUM_VERS] = { }; static const uint8_t patch_cmp[NUM_VERS][CMP_SIZE] = { - {0x8b, 0x89, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb9, 0x80, 0x4b, 0x00, - 0x00}, - {0x8b, 0x89, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb9, 0x80, 0x4b, 0x00, - 0x00}, - {0x8b, 0x89, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb9, 0x80, 0x4b, 0x00, - 0x00}, - {0x8b, 0x80, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb0, 0x40, 0x4c, 0x00, - 0x00}, - {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, - 0x00}, - {0x81, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, - 0x00}, - {0x81, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, - 0x00}, - {0x81, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, - 0x00}, - {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, - 0x00}, - {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, - 0x00}, - {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, - 0x00}, - {0x87, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, - 0x00}, - {0x81, 0x18, 0x2a, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, - 0x00}, - {0x81, 0x18, 0x2a, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, - 0x00}, - {0x81, 0x18, 0x2a, 0x00, 0x00, 0x83, 0xb8, 0xa8, 0x4c, 0x00, 0x00, - 0x00}, - {0x8b, 0x80, 0xe8, 0x29, 0x00, 0x00, 0x39, 0x90, 0xb0, 0x4b, 0x00, - 0x00}, + {0x8b, 0x89, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb9, 0x80, 0x4b, 0x00, 0x00}, + {0x8b, 0x89, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb9, 0x80, 0x4b, 0x00, 0x00}, + {0x8b, 0x89, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb9, 0x80, 0x4b, 0x00, 0x00}, + {0x8b, 0x80, 0xe8, 0x29, 0x00, 0x00, 0x39, 0xb0, 0x40, 0x4c, 0x00, 0x00}, + {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, 0x00}, + {0x81, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, 0x00}, + {0x81, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, 0x00}, + {0x81, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, 0x00}, + {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, 0x00}, + {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, 0x00}, + {0x80, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, 0x00}, + {0x87, 0xe8, 0x29, 0x00, 0x00, 0x83, 0xb8, 0x40, 0x4c, 0x00, 0x00, 0x00}, + {0x81, 0x18, 0x2a, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, 0x00}, + {0x81, 0x18, 0x2a, 0x00, 0x00, 0x83, 0xb8, 0xa0, 0x4c, 0x00, 0x00, 0x00}, + {0x81, 0x18, 0x2a, 0x00, 0x00, 0x83, 0xb8, 0xa8, 0x4c, 0x00, 0x00, 0x00}, + {0x8b, 0x80, 0xe8, 0x29, 0x00, 0x00, 0x39, 0x90, 0xb0, 0x4b, 0x00, 0x00}, }; static const struct patch_info patch[NUM_VERS] = { - NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), - NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(ignore_jump), - NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(force_jump), - NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(ignore_jump), - NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), - NEW_PATCH(force_jump), + NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), + NEW_PATCH(force_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), + NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(force_jump), NEW_PATCH(ignore_jump), + NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(ignore_jump), NEW_PATCH(force_jump), }; #endif @@ -200,8 +164,7 @@ static inline int get_d3d9_patch(HMODULE d3d9) { uint8_t *addr = (uint8_t *)d3d9; for (int i = 0; i < NUM_VERS; i++) { - int ret = safe_memcmp(addr + patch_offset[i], patch_cmp[i], - CMP_SIZE); + int ret = safe_memcmp(addr + patch_offset[i], patch_cmp[i], CMP_SIZE); if (ret == 0) return i; } diff --git a/plugins/win-capture/graphics-hook/dxgi-capture.cpp b/plugins/win-capture/graphics-hook/dxgi-capture.cpp index d175aa565..c5a5b6bae 100644 --- a/plugins/win-capture/graphics-hook/dxgi-capture.cpp +++ b/plugins/win-capture/graphics-hook/dxgi-capture.cpp @@ -12,12 +12,9 @@ #include #endif -typedef HRESULT(STDMETHODCALLTYPE *resize_buffers_t)(IDXGISwapChain *, UINT, - UINT, UINT, DXGI_FORMAT, - UINT); +typedef HRESULT(STDMETHODCALLTYPE *resize_buffers_t)(IDXGISwapChain *, UINT, UINT, UINT, DXGI_FORMAT, UINT); typedef HRESULT(STDMETHODCALLTYPE *present_t)(IDXGISwapChain *, UINT, UINT); -typedef HRESULT(STDMETHODCALLTYPE *present1_t)(IDXGISwapChain1 *, UINT, UINT, - const DXGI_PRESENT_PARAMETERS *); +typedef HRESULT(STDMETHODCALLTYPE *present1_t)(IDXGISwapChain1 *, UINT, UINT, const DXGI_PRESENT_PARAMETERS *); resize_buffers_t RealResizeBuffers = nullptr; present_t RealPresent = nullptr; @@ -43,8 +40,7 @@ static void STDMETHODCALLTYPE SwapChainDestructed(void *pData) if (pData == data.swap) { data.swap = nullptr; data.capture = nullptr; - memset(dxgi_possible_swap_queues, 0, - sizeof(dxgi_possible_swap_queues)); + memset(dxgi_possible_swap_queues, 0, sizeof(dxgi_possible_swap_queues)); dxgi_possible_swap_queue_count = 0; dxgi_present_attempted = false; @@ -54,19 +50,16 @@ static void STDMETHODCALLTYPE SwapChainDestructed(void *pData) } } -static void init_swap_data(IDXGISwapChain *swap, - void (*capture)(void *, void *), void (*free)(void)) +static void init_swap_data(IDXGISwapChain *swap, void (*capture)(void *, void *), void (*free)(void)) { data.swap = swap; data.capture = capture; data.free = free; ID3DDestructionNotifier *notifier; - if (SUCCEEDED( - swap->QueryInterface(¬ifier))) { + if (SUCCEEDED(swap->QueryInterface(¬ifier))) { UINT callbackID; - notifier->RegisterDestructionCallback(&SwapChainDestructed, - swap, &callbackID); + notifier->RegisterDestructionCallback(&SwapChainDestructed, swap, &callbackID); notifier->Release(); } } @@ -115,12 +108,10 @@ static bool setup_dxgi(IDXGISwapChain *swap) if (SUCCEEDED(hr)) { device->Release(); - hlog("Found D3D12 device on swap chain: swap=0x%" PRIX64 - ", device=0x%" PRIX64, + hlog("Found D3D12 device on swap chain: swap=0x%" PRIX64 ", device=0x%" PRIX64, (uint64_t)(uintptr_t)swap, (uint64_t)(uintptr_t)device); for (size_t i = 0; i < dxgi_possible_swap_queue_count; ++i) { - hlog(" queue=0x%" PRIX64, - (uint64_t)(uintptr_t)dxgi_possible_swap_queues[i]); + hlog(" queue=0x%" PRIX64, (uint64_t)(uintptr_t)dxgi_possible_swap_queues[i]); } if (dxgi_possible_swap_queue_count > 0) { @@ -136,11 +127,8 @@ static bool setup_dxgi(IDXGISwapChain *swap) static bool resize_buffers_called = false; -static HRESULT STDMETHODCALLTYPE hook_resize_buffers(IDXGISwapChain *swap, - UINT buffer_count, - UINT width, UINT height, - DXGI_FORMAT format, - UINT flags) +static HRESULT STDMETHODCALLTYPE hook_resize_buffers(IDXGISwapChain *swap, UINT buffer_count, UINT width, UINT height, + DXGI_FORMAT format, UINT flags) { hlog_verbose("ResizeBuffers callback"); @@ -154,8 +142,7 @@ static HRESULT STDMETHODCALLTYPE hook_resize_buffers(IDXGISwapChain *swap, data.free(); data.free = nullptr; - const HRESULT hr = RealResizeBuffers(swap, buffer_count, width, height, - format, flags); + const HRESULT hr = RealResizeBuffers(swap, buffer_count, width, height, format, flags); resize_buffers_called = true; @@ -183,8 +170,7 @@ static void update_mismatch_count(bool match) if (swap_chain_mismatch_count == swap_chain_mismtach_limit) { data.swap = nullptr; data.capture = nullptr; - memset(dxgi_possible_swap_queues, 0, - sizeof(dxgi_possible_swap_queues)); + memset(dxgi_possible_swap_queues, 0, sizeof(dxgi_possible_swap_queues)); dxgi_possible_swap_queue_count = 0; dxgi_present_attempted = false; @@ -197,8 +183,7 @@ static void update_mismatch_count(bool match) } } -static HRESULT STDMETHODCALLTYPE hook_present(IDXGISwapChain *swap, - UINT sync_interval, UINT flags) +static HRESULT STDMETHODCALLTYPE hook_present(IDXGISwapChain *swap, UINT sync_interval, UINT flags) { if (should_passthrough()) { dxgi_presenting = true; @@ -218,10 +203,9 @@ static HRESULT STDMETHODCALLTYPE hook_present(IDXGISwapChain *swap, setup_dxgi(swap); } - hlog_verbose( - "Present callback: sync_interval=%u, flags=%u, current_swap=0x%" PRIX64 - ", expected_swap=0x%" PRIX64, - sync_interval, flags, swap, data.swap); + hlog_verbose("Present callback: sync_interval=%u, flags=%u, current_swap=0x%" PRIX64 + ", expected_swap=0x%" PRIX64, + sync_interval, flags, swap, data.swap); const bool capture = !test_draw && swap == data.swap && data.capture; if (capture && !capture_overlay) { IUnknown *backbuffer = get_dxgi_backbuffer(swap); @@ -260,14 +244,12 @@ static HRESULT STDMETHODCALLTYPE hook_present(IDXGISwapChain *swap, return hr; } -static HRESULT STDMETHODCALLTYPE -hook_present1(IDXGISwapChain1 *swap, UINT sync_interval, UINT flags, - const DXGI_PRESENT_PARAMETERS *params) +static HRESULT STDMETHODCALLTYPE hook_present1(IDXGISwapChain1 *swap, UINT sync_interval, UINT flags, + const DXGI_PRESENT_PARAMETERS *params) { if (should_passthrough()) { dxgi_presenting = true; - const HRESULT hr = - RealPresent1(swap, sync_interval, flags, params); + const HRESULT hr = RealPresent1(swap, sync_interval, flags, params); dxgi_presenting = false; return hr; } @@ -283,10 +265,9 @@ hook_present1(IDXGISwapChain1 *swap, UINT sync_interval, UINT flags, setup_dxgi(swap); } - hlog_verbose( - "Present1 callback: sync_interval=%u, flags=%u, current_swap=0x%" PRIX64 - ", expected_swap=0x%" PRIX64, - sync_interval, flags, swap, data.swap); + hlog_verbose("Present1 callback: sync_interval=%u, flags=%u, current_swap=0x%" PRIX64 + ", expected_swap=0x%" PRIX64, + sync_interval, flags, swap, data.swap); const bool capture = !test_draw && swap == data.swap && !!data.capture; if (capture && !capture_overlay) { IUnknown *backbuffer = get_dxgi_backbuffer(swap); @@ -328,14 +309,11 @@ bool hook_dxgi(void) /* ---------------------- */ - void *present_addr = get_offset_addr( - dxgi_module, global_hook_info->offsets.dxgi.present); - void *resize_addr = get_offset_addr( - dxgi_module, global_hook_info->offsets.dxgi.resize); + void *present_addr = get_offset_addr(dxgi_module, global_hook_info->offsets.dxgi.present); + void *resize_addr = get_offset_addr(dxgi_module, global_hook_info->offsets.dxgi.resize); void *present1_addr = nullptr; if (global_hook_info->offsets.dxgi.present1) - present1_addr = get_offset_addr( - dxgi_module, global_hook_info->offsets.dxgi.present1); + present1_addr = get_offset_addr(dxgi_module, global_hook_info->offsets.dxgi.present1); DetourTransactionBegin(); diff --git a/plugins/win-capture/graphics-hook/dxgi-helpers.hpp b/plugins/win-capture/graphics-hook/dxgi-helpers.hpp index c9b10ff04..a29b59fa6 100644 --- a/plugins/win-capture/graphics-hook/dxgi-helpers.hpp +++ b/plugins/win-capture/graphics-hook/dxgi-helpers.hpp @@ -14,8 +14,7 @@ static inline DXGI_FORMAT strip_dxgi_format_srgb(DXGI_FORMAT format) return format; } -static inline DXGI_FORMAT apply_dxgi_format_typeless(DXGI_FORMAT format, - bool allow_srgb_alias) +static inline DXGI_FORMAT apply_dxgi_format_typeless(DXGI_FORMAT format, bool allow_srgb_alias) { if (allow_srgb_alias) { switch (format) { @@ -46,11 +45,8 @@ static void print_swap_desc(const DXGI_SWAP_CHAIN_DESC *desc) " Windowed: %u\n" " SwapEffect: %u\n" " Flags: %u", - desc->BufferDesc.Width, desc->BufferDesc.Height, - desc->BufferDesc.RefreshRate.Numerator, - desc->BufferDesc.RefreshRate.Denominator, desc->BufferDesc.Format, - desc->BufferDesc.ScanlineOrdering, desc->BufferDesc.Scaling, - desc->SampleDesc.Count, desc->SampleDesc.Quality, - desc->BufferUsage, desc->BufferCount, desc->Windowed, - desc->SwapEffect, desc->Flags); + desc->BufferDesc.Width, desc->BufferDesc.Height, desc->BufferDesc.RefreshRate.Numerator, + desc->BufferDesc.RefreshRate.Denominator, desc->BufferDesc.Format, desc->BufferDesc.ScanlineOrdering, + desc->BufferDesc.Scaling, desc->SampleDesc.Count, desc->SampleDesc.Quality, desc->BufferUsage, + desc->BufferCount, desc->Windowed, desc->SwapEffect, desc->Flags); } diff --git a/plugins/win-capture/graphics-hook/gl-capture.c b/plugins/win-capture/graphics-hook/gl-capture.c index c30ac0679..61d4efad9 100644 --- a/plugins/win-capture/graphics-hook/gl-capture.c +++ b/plugins/win-capture/graphics-hook/gl-capture.c @@ -96,8 +96,7 @@ static void gl_free(void) if (data.using_shtex) { if (data.gl_dxobj) - obsglDXUnregisterObjectNV(data.gl_device, - data.gl_dxobj); + obsglDXUnregisterObjectNV(data.gl_device, data.gl_dxobj); if (data.gl_device) obsglDXCloseDeviceNV(data.gl_device); if (data.texture) @@ -116,8 +115,7 @@ static void gl_free(void) for (size_t i = 0; i < NUM_BUFFERS; i++) { if (data.pbos[i]) { if (data.texture_mapped[i]) { - glBindBuffer(GL_PIXEL_PACK_BUFFER, - data.pbos[i]); + glBindBuffer(GL_PIXEL_PACK_BUFFER, data.pbos[i]); glUnmapBuffer(GL_PIXEL_PACK_BUFFER); glBindBuffer(GL_PIXEL_PACK_BUFFER, 0); } @@ -161,8 +159,7 @@ static inline void *get_proc(const char *name) static void init_nv_functions(void) { - obsglDXSetResourceShareHandleNV = - get_proc("wglDXSetResourceShareHandleNV"); + obsglDXSetResourceShareHandleNV = get_proc("wglDXSetResourceShareHandleNV"); obsglDXOpenDeviceNV = get_proc("wglDXOpenDeviceNV"); obsglDXCloseDeviceNV = get_proc("wglDXCloseDeviceNV"); obsglDXRegisterObjectNV = get_proc("wglDXRegisterObjectNV"); @@ -171,24 +168,21 @@ static void init_nv_functions(void) obsglDXLockObjectsNV = get_proc("wglDXLockObjectsNV"); obsglDXUnlockObjectsNV = get_proc("wglDXUnlockObjectsNV"); - nv_capture_available = - !!obsglDXSetResourceShareHandleNV && !!obsglDXOpenDeviceNV && - !!obsglDXCloseDeviceNV && !!obsglDXRegisterObjectNV && - !!obsglDXUnregisterObjectNV && !!obsglDXObjectAccessNV && - !!obsglDXLockObjectsNV && !!obsglDXUnlockObjectsNV; + nv_capture_available = !!obsglDXSetResourceShareHandleNV && !!obsglDXOpenDeviceNV && !!obsglDXCloseDeviceNV && + !!obsglDXRegisterObjectNV && !!obsglDXUnregisterObjectNV && !!obsglDXObjectAccessNV && + !!obsglDXLockObjectsNV && !!obsglDXUnlockObjectsNV; if (nv_capture_available) hlog("Shared-texture OpenGL capture available"); } -#define GET_PROC(cur_func, ptr, func) \ - do { \ - ptr = get_proc(#func); \ - if (!ptr) { \ - hlog("%s: failed to get function '%s'", #cur_func, \ - #func); \ - success = false; \ - } \ +#define GET_PROC(cur_func, ptr, func) \ + do { \ + ptr = get_proc(#func); \ + if (!ptr) { \ + hlog("%s: failed to get function '%s'", #cur_func, #func); \ + success = false; \ + } \ } while (false) static bool init_gl_functions(void) @@ -203,8 +197,7 @@ static bool init_gl_functions(void) GET_PROC(init_gl_functions, obsglMakeCurrent, wglMakeCurrent); GET_PROC(init_gl_functions, obsglGetCurrentDC, wglGetCurrentDC); - GET_PROC(init_gl_functions, obsglGetCurrentContext, - wglGetCurrentContext); + GET_PROC(init_gl_functions, obsglGetCurrentContext, wglGetCurrentContext); GET_PROC(init_gl_functions, glTexImage2D, glTexImage2D); GET_PROC(init_gl_functions, glReadBuffer, glReadBuffer); GET_PROC(init_gl_functions, glGetTexImage, glGetTexImage); @@ -224,8 +217,7 @@ static bool init_gl_functions(void) GET_PROC(init_gl_functions, glDeleteFramebuffers, glDeleteFramebuffers); GET_PROC(init_gl_functions, glBindFramebuffer, glBindFramebuffer); GET_PROC(init_gl_functions, glBlitFramebuffer, glBlitFramebuffer); - GET_PROC(init_gl_functions, glFramebufferTexture2D, - glFramebufferTexture2D); + GET_PROC(init_gl_functions, glFramebufferTexture2D, glFramebufferTexture2D); init_nv_functions(); return success; @@ -248,13 +240,11 @@ static void get_window_size(HDC hdc, uint32_t *cx, uint32_t *cy) static inline bool gl_shtex_init_window(void) { - data.hwnd = CreateWindowExW( - 0, DUMMY_WINDOW_CLASS_NAME, L"Dummy GL window, ignore", - WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 2, 2, NULL, - NULL, GetModuleHandle(NULL), NULL); + data.hwnd = CreateWindowExW(0, DUMMY_WINDOW_CLASS_NAME, L"Dummy GL window, ignore", + WS_POPUP | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 2, 2, NULL, NULL, + GetModuleHandle(NULL), NULL); if (!data.hwnd) { - hlog("gl_shtex_init_window: failed to create window: %d", - GetLastError()); + hlog("gl_shtex_init_window: failed to create window: %d", GetLastError()); return false; } @@ -278,15 +268,13 @@ static inline bool gl_shtex_init_d3d11(void) HMODULE d3d11 = load_system_library("d3d11.dll"); if (!d3d11) { - hlog("gl_shtex_init_d3d11: failed to load D3D11.dll: %d", - GetLastError()); + hlog("gl_shtex_init_d3d11: failed to load D3D11.dll: %d", GetLastError()); return false; } HMODULE dxgi = load_system_library("dxgi.dll"); if (!dxgi) { - hlog("gl_shtex_init_d3d11: failed to load DXGI.dll: %d", - GetLastError()); + hlog("gl_shtex_init_d3d11: failed to load DXGI.dll: %d", GetLastError()); return false; } @@ -300,8 +288,7 @@ static inline bool gl_shtex_init_d3d11(void) desc.Windowed = true; desc.OutputWindow = data.hwnd; - create_dxgi_factory1_t create_factory = - (void *)GetProcAddress(dxgi, "CreateDXGIFactory1"); + create_dxgi_factory1_t create_factory = (void *)GetProcAddress(dxgi, "CreateDXGIFactory1"); if (!create_factory) { hlog("gl_shtex_init_d3d11: failed to load CreateDXGIFactory1 " "procedure: %d", @@ -309,8 +296,7 @@ static inline bool gl_shtex_init_d3d11(void) return false; } - PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN create = - (void *)GetProcAddress(d3d11, "D3D11CreateDeviceAndSwapChain"); + PFN_D3D11_CREATE_DEVICE_AND_SWAP_CHAIN create = (void *)GetProcAddress(d3d11, "D3D11CreateDeviceAndSwapChain"); if (!create) { hlog("gl_shtex_init_d3d11: failed to load " "D3D11CreateDeviceAndSwapChain procedure: %d", @@ -324,8 +310,7 @@ static inline bool gl_shtex_init_d3d11(void) return false; } - hr = IDXGIFactory1_EnumAdapters1(factory, 0, - (IDXGIAdapter1 **)&adapter); + hr = IDXGIFactory1_EnumAdapters1(factory, 0, (IDXGIAdapter1 **)&adapter); IDXGIFactory1_Release(factory); if (FAILED(hr)) { @@ -334,8 +319,7 @@ static inline bool gl_shtex_init_d3d11(void) } hr = create(adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, feature_levels, - sizeof(feature_levels) / sizeof(D3D_FEATURE_LEVEL), - D3D11_SDK_VERSION, &desc, &data.dxgi_swap, + sizeof(feature_levels) / sizeof(D3D_FEATURE_LEVEL), D3D11_SDK_VERSION, &desc, &data.dxgi_swap, &data.d3d11_device, &level_used, &data.d3d11_context); IDXGIAdapter_Release(adapter); @@ -363,19 +347,15 @@ static inline bool gl_shtex_init_d3d11_tex(void) desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - hr = ID3D11Device_CreateTexture2D(data.d3d11_device, &desc, NULL, - &data.d3d11_tex); + hr = ID3D11Device_CreateTexture2D(data.d3d11_device, &desc, NULL, &data.d3d11_tex); if (FAILED(hr)) { - hlog_hr("gl_shtex_init_d3d11_tex: failed to create texture", - hr); + hlog_hr("gl_shtex_init_d3d11_tex: failed to create texture", hr); return false; } - hr = ID3D11Device_QueryInterface(data.d3d11_tex, &GUID_IDXGIResource, - (void **)&dxgi_res); + hr = ID3D11Device_QueryInterface(data.d3d11_tex, &GUID_IDXGIResource, (void **)&dxgi_res); if (FAILED(hr)) { - hlog_hr("gl_shtex_init_d3d11_tex: failed to get IDXGIResource", - hr); + hlog_hr("gl_shtex_init_d3d11_tex: failed to get IDXGIResource", hr); return false; } @@ -383,8 +363,7 @@ static inline bool gl_shtex_init_d3d11_tex(void) IDXGIResource_Release(dxgi_res); if (FAILED(hr)) { - hlog_hr("gl_shtex_init_d3d11_tex: failed to get shared handle", - hr); + hlog_hr("gl_shtex_init_d3d11_tex: failed to get shared handle", hr); return false; } @@ -404,8 +383,7 @@ static inline bool gl_shtex_init_gl_tex(void) return false; } - data.gl_dxobj = obsglDXRegisterObjectNV(data.gl_device, data.d3d11_tex, - data.texture, GL_TEXTURE_2D, + data.gl_dxobj = obsglDXRegisterObjectNV(data.gl_device, data.d3d11_tex, data.texture, GL_TEXTURE_2D, WGL_ACCESS_WRITE_DISCARD_NV); if (!data.gl_dxobj) { hlog("gl_shtex_init_gl_tex: failed to register object"); @@ -438,8 +416,8 @@ static bool gl_shtex_init(HWND window) if (!gl_init_fbo()) { return false; } - if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, - data.format, true, (uintptr_t)data.handle)) { + if (!capture_init_shtex(&data.shtex_info, window, data.cx, data.cy, data.format, true, + (uintptr_t)data.handle)) { return false; } @@ -464,8 +442,7 @@ static inline bool gl_shmem_init_data(size_t idx, size_t size) return false; } - glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data.cx, data.cy, 0, GL_BGRA, - GL_UNSIGNED_BYTE, NULL); + glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, data.cx, data.cy, 0, GL_BGRA, GL_UNSIGNED_BYTE, NULL); if (gl_error("gl_shmem_init_data", "failed to set texture data")) { return false; } @@ -490,8 +467,7 @@ static inline bool gl_shmem_init_buffers(void) } glGetIntegerv(GL_PIXEL_PACK_BUFFER_BINDING, &last_pbo); - if (gl_error("gl_shmem_init_buffers", - "failed to save pixel pack buffer")) { + if (gl_error("gl_shmem_init_buffers", "failed to save pixel pack buffer")) { return false; } @@ -519,8 +495,7 @@ static bool gl_shmem_init(HWND window) if (!gl_init_fbo()) { return false; } - if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, - data.cx * 4, data.format, true)) { + if (!capture_init_shmem(&data.shmem_info, window, data.cx, data.cy, data.cx * 4, data.format, true)) { return false; } @@ -550,9 +525,7 @@ static int gl_init(HDC hdc) data.hdc = hdc; data.format = DXGI_FORMAT_B8G8R8A8_UNORM; - data.using_shtex = nv_capture_available && - !global_hook_info->force_shmem && - !data.shmem_fallback; + data.using_shtex = nv_capture_available && !global_hook_info->force_shmem && !data.shmem_fallback; if (data.using_shtex) { success = gl_shtex_init(window); @@ -582,8 +555,7 @@ static void gl_copy_backbuffer(GLuint dst) return; } - glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, - GL_TEXTURE_2D, dst, 0); + glFramebufferTexture2D(GL_DRAW_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, dst, 0); if (gl_error("gl_copy_backbuffer", "failed to set frame buffer")) { return; } @@ -591,16 +563,14 @@ static void gl_copy_backbuffer(GLuint dst) glReadBuffer(GL_BACK); /* darkest dungeon fix */ - darkest_dungeon_fix = glGetError() == GL_INVALID_OPERATION && - _strcmpi(process_name, "Darkest.exe") == 0; + darkest_dungeon_fix = glGetError() == GL_INVALID_OPERATION && _strcmpi(process_name, "Darkest.exe") == 0; glDrawBuffer(GL_COLOR_ATTACHMENT0); if (gl_error("gl_copy_backbuffer", "failed to set draw buffer")) { return; } - glBlitFramebuffer(0, 0, data.cx, data.cy, 0, 0, data.cx, data.cy, - GL_COLOR_BUFFER_BIT, GL_LINEAR); + glBlitFramebuffer(0, 0, data.cx, data.cy, 0, 0, data.cx, data.cy, GL_COLOR_BUFFER_BIT, GL_LINEAR); gl_error("gl_copy_backbuffer", "failed to blit"); } @@ -639,8 +609,7 @@ static void gl_shmem_capture_copy(int i) data.texture_ready[i] = false; glBindBuffer(GL_PIXEL_PACK_BUFFER, data.pbos[i]); - if (gl_error("gl_shmem_capture_queue_copy", - "failed to bind pbo")) { + if (gl_error("gl_shmem_capture_queue_copy", "failed to bind pbo")) { return; } @@ -699,16 +668,14 @@ static void gl_shmem_capture(void) data.copy_wait++; } else { if (shmem_texture_data_lock(data.cur_tex)) { - glBindBuffer(GL_PIXEL_PACK_BUFFER, - data.pbos[data.cur_tex]); + glBindBuffer(GL_PIXEL_PACK_BUFFER, data.pbos[data.cur_tex]); glUnmapBuffer(GL_PIXEL_PACK_BUFFER); data.texture_mapped[data.cur_tex] = false; shmem_texture_data_unlock(data.cur_tex); } gl_copy_backbuffer(data.textures[data.cur_tex]); - gl_shmem_capture_stage(data.pbos[data.cur_tex], - data.textures[data.cur_tex]); + gl_shmem_capture_stage(data.pbos[data.cur_tex], data.textures[data.cur_tex]); data.texture_ready[data.cur_tex] = true; } @@ -840,8 +807,7 @@ static bool gl_register_window(void) wc.lpszClassName = DUMMY_WINDOW_CLASS_NAME; if (!RegisterClassW(&wc)) { - hlog("gl_register_window: failed to register window class: %d", - GetLastError()); + hlog("gl_register_window: failed to register window class: %d", GetLastError()); return false; } @@ -862,8 +828,7 @@ bool hook_gl(void) /* "life is feudal: your own" somehow uses both opengl and directx at * the same time, so blacklist it from capturing opengl */ const char *process_name = get_process_name(); - if (_strcmpi(process_name, "yo_cm_client.exe") == 0 || - _strcmpi(process_name, "cm_client.exe") == 0) { + if (_strcmpi(process_name, "yo_cm_client.exe") == 0 || _strcmpi(process_name, "cm_client.exe") == 0) { hlog("Ignoring opengl for game: %s", process_name); return true; } @@ -882,18 +847,15 @@ bool hook_gl(void) DetourAttach((PVOID *)&RealSwapBuffers, hook_swap_buffers); if (wgl_dc_proc) { RealWglDeleteContext = (PFN_WglDeleteContext)wgl_dc_proc; - DetourAttach((PVOID *)&RealWglDeleteContext, - hook_wgl_delete_context); + DetourAttach((PVOID *)&RealWglDeleteContext, hook_wgl_delete_context); } if (wgl_slb_proc) { RealWglSwapLayerBuffers = (PFN_WglSwapLayerBuffers)wgl_slb_proc; - DetourAttach((PVOID *)&RealWglSwapLayerBuffers, - hook_wgl_swap_layer_buffers); + DetourAttach((PVOID *)&RealWglSwapLayerBuffers, hook_wgl_swap_layer_buffers); } if (wgl_sb_proc) { RealWglSwapBuffers = (PFN_WglSwapBuffers)wgl_sb_proc; - DetourAttach((PVOID *)&RealWglSwapBuffers, - hook_wgl_swap_buffers); + DetourAttach((PVOID *)&RealWglSwapBuffers, hook_wgl_swap_buffers); } const LONG error = DetourTransactionCommit(); diff --git a/plugins/win-capture/graphics-hook/gl-decs.h b/plugins/win-capture/graphics-hook/gl-decs.h index d6a124ccd..3ad1ae021 100644 --- a/plugins/win-capture/graphics-hook/gl-decs.h +++ b/plugins/win-capture/graphics-hook/gl-decs.h @@ -69,14 +69,9 @@ typedef ptrdiff_t GLsizeiptrARB; #define GL_COLOR_ATTACHMENT0 0x8CE0 #define GL_COLOR_ATTACHMENT1 0x8CE1 -typedef void(WINAPI *GLTEXIMAGE2DPROC)(GLenum target, GLint level, - GLint internal_format, GLsizei width, - GLsizei height, GLint border, - GLenum format, GLenum type, - const GLvoid *data); -typedef void(WINAPI *GLGETTEXIMAGEPROC)(GLenum target, GLint level, - GLenum format, GLenum type, - GLvoid *img); +typedef void(WINAPI *GLTEXIMAGE2DPROC)(GLenum target, GLint level, GLint internal_format, GLsizei width, GLsizei height, + GLint border, GLenum format, GLenum type, const GLvoid *data); +typedef void(WINAPI *GLGETTEXIMAGEPROC)(GLenum target, GLint level, GLenum format, GLenum type, GLvoid *img); typedef void(WINAPI *GLREADBUFFERPROC)(GLenum); typedef void(WINAPI *GLDRAWBUFFERPROC)(GLenum mode); typedef void(WINAPI *GLGETINTEGERVPROC)(GLenum pname, GLint *params); @@ -89,8 +84,7 @@ typedef BOOL(WINAPI *WGLMAKECURRENTPROC)(HDC, HGLRC); typedef HDC(WINAPI *WGLGETCURRENTDCPROC)(); typedef HGLRC(WINAPI *WGLGETCURRENTCONTEXTPROC)(); typedef HGLRC(WINAPI *WGLCREATECONTEXTPROC)(HDC); -typedef void(WINAPI *GLBUFFERDATAARBPROC)(GLenum target, GLsizeiptrARB size, - const GLvoid *data, GLenum usage); +typedef void(WINAPI *GLBUFFERDATAARBPROC)(GLenum target, GLsizeiptrARB size, const GLvoid *data, GLenum usage); typedef void(WINAPI *GLDELETEBUFFERSARBPROC)(GLsizei n, const GLuint *buffers); typedef void(WINAPI *GLDELETETEXTURESPROC)(GLsizei n, const GLuint *buffers); typedef void(WINAPI *GLGENBUFFERSARBPROC)(GLsizei n, GLuint *buffers); @@ -102,20 +96,14 @@ typedef void(WINAPI *GLBINDTEXTUREPROC)(GLenum target, GLuint texture); typedef void(WINAPI *GLGENFRAMEBUFFERSPROC)(GLsizei n, GLuint *buffers); typedef void(WINAPI *GLDELETEFRAMEBUFFERSPROC)(GLsizei n, GLuint *framebuffers); typedef void(WINAPI *GLBINDFRAMEBUFFERPROC)(GLenum target, GLuint framebuffer); -typedef void(WINAPI *GLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, - GLint srcX1, GLint srcY1, - GLint dstX0, GLint dstY0, - GLint dstX1, GLint dstY1, - GLbitfield mask, GLenum filter); -typedef void(WINAPI *GLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, - GLenum attachment, - GLenum textarget, - GLuint texture, GLint level); +typedef void(WINAPI *GLBLITFRAMEBUFFERPROC)(GLint srcX0, GLint srcY0, GLint srcX1, GLint srcY1, GLint dstX0, + GLint dstY0, GLint dstX1, GLint dstY1, GLbitfield mask, GLenum filter); +typedef void(WINAPI *GLFRAMEBUFFERTEXTURE2DPROC)(GLenum target, GLenum attachment, GLenum textarget, GLuint texture, + GLint level); typedef BOOL(WINAPI *WGLSETRESOURCESHAREHANDLENVPROC)(void *, HANDLE); typedef HANDLE(WINAPI *WGLDXOPENDEVICENVPROC)(void *); typedef BOOL(WINAPI *WGLDXCLOSEDEVICENVPROC)(HANDLE); -typedef HANDLE(WINAPI *WGLDXREGISTEROBJECTNVPROC)(HANDLE, void *, GLuint, - GLenum, GLenum); +typedef HANDLE(WINAPI *WGLDXREGISTEROBJECTNVPROC)(HANDLE, void *, GLuint, GLenum, GLenum); typedef BOOL(WINAPI *WGLDXUNREGISTEROBJECTNVPROC)(HANDLE, HANDLE); typedef BOOL(WINAPI *WGLDXOBJECTACCESSNVPROC)(HANDLE, GLenum); typedef BOOL(WINAPI *WGLDXLOCKOBJECTSNVPROC)(HANDLE, GLint, HANDLE *); diff --git a/plugins/win-capture/graphics-hook/graphics-hook.c b/plugins/win-capture/graphics-hook/graphics-hook.c index d7c5dfa3a..b6b3e9ec1 100644 --- a/plugins/win-capture/graphics-hook/graphics-hook.c +++ b/plugins/win-capture/graphics-hook/graphics-hook.c @@ -70,8 +70,7 @@ static inline void wait_for_dll_main_finish(HANDLE thread_handle) bool init_pipe(void) { char new_name[64]; - snprintf(new_name, sizeof(new_name), "%s%lu", PIPE_NAME, - GetCurrentProcessId()); + snprintf(new_name, sizeof(new_name), "%s%lu", PIPE_NAME, GetCurrentProcessId()); const bool success = ipc_pipe_client_open(&pipe, new_name); if (!success) { @@ -159,12 +158,10 @@ static inline bool init_system_path(void) static inline void log_current_process(void) { - DWORD len = GetModuleBaseNameA(GetCurrentProcess(), NULL, process_name, - MAX_PATH); + DWORD len = GetModuleBaseNameA(GetCurrentProcess(), NULL, process_name, MAX_PATH); if (len > 0) { process_name[len] = 0; - hlog("graphics-hook.dll loaded against process: %s", - process_name); + hlog("graphics-hook.dll loaded against process: %s", process_name); } else { hlog("graphics-hook.dll loaded"); } @@ -176,16 +173,13 @@ static inline bool init_hook_info(void) { filemap_hook_info = create_hook_info(GetCurrentProcessId()); if (!filemap_hook_info) { - hlog("Failed to create hook info file mapping: %lu", - GetLastError()); + hlog("Failed to create hook info file mapping: %lu", GetLastError()); return false; } - global_hook_info = MapViewOfFile(filemap_hook_info, FILE_MAP_ALL_ACCESS, - 0, 0, sizeof(struct hook_info)); + global_hook_info = MapViewOfFile(filemap_hook_info, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(struct hook_info)); if (!global_hook_info) { - hlog("Failed to map the hook info file mapping: %lu", - GetLastError()); + hlog("Failed to map the hook info file mapping: %lu", GetLastError()); return false; } @@ -207,13 +201,11 @@ static DWORD WINAPI dummy_window_thread(LPVOID *unused) wc.lpszClassName = dummy_window_class; if (!RegisterClass(&wc)) { - hlog("Failed to create temp D3D window class: %lu", - GetLastError()); + hlog("Failed to create temp D3D window class: %lu", GetLastError()); return 0; } - dummy_window = CreateWindowExW(0, dummy_window_class, L"Temp Window", - DEF_FLAGS, 0, 0, 1, 1, NULL, NULL, + dummy_window = CreateWindowExW(0, dummy_window_class, L"Temp Window", DEF_FLAGS, 0, 0, 1, 1, NULL, NULL, dll_inst, NULL); if (!dummy_window) { hlog("Failed to create temp D3D window: %lu", GetLastError()); @@ -231,11 +223,9 @@ static DWORD WINAPI dummy_window_thread(LPVOID *unused) static inline void init_dummy_window_thread(void) { - HANDLE thread = - CreateThread(NULL, 0, dummy_window_thread, NULL, 0, NULL); + HANDLE thread = CreateThread(NULL, 0, dummy_window_thread, NULL, 0, NULL); if (!thread) { - hlog("Failed to create temp D3D window thread: %lu", - GetLastError()); + hlog("Failed to create temp D3D window thread: %lu", GetLastError()); return; } @@ -246,8 +236,8 @@ static inline bool init_hook(HANDLE thread_handle) { wait_for_dll_main_finish(thread_handle); - _snwprintf(keepalive_name, sizeof(keepalive_name) / sizeof(wchar_t), - L"%s%lu", WINDOW_HOOK_KEEPALIVE, GetCurrentProcessId()); + _snwprintf(keepalive_name, sizeof(keepalive_name) / sizeof(wchar_t), L"%s%lu", WINDOW_HOOK_KEEPALIVE, + GetCurrentProcessId()); init_dummy_window_thread(); log_current_process(); @@ -292,27 +282,22 @@ static inline bool d3d8_hookable(void) static inline bool ddraw_hookable(void) { - return !!global_hook_info->offsets.ddraw.surface_create && - !!global_hook_info->offsets.ddraw.surface_restore && - !!global_hook_info->offsets.ddraw.surface_release && - !!global_hook_info->offsets.ddraw.surface_unlock && - !!global_hook_info->offsets.ddraw.surface_blt && - !!global_hook_info->offsets.ddraw.surface_flip && + return !!global_hook_info->offsets.ddraw.surface_create && !!global_hook_info->offsets.ddraw.surface_restore && + !!global_hook_info->offsets.ddraw.surface_release && !!global_hook_info->offsets.ddraw.surface_unlock && + !!global_hook_info->offsets.ddraw.surface_blt && !!global_hook_info->offsets.ddraw.surface_flip && !!global_hook_info->offsets.ddraw.surface_set_palette && !!global_hook_info->offsets.ddraw.palette_set_entries; } static inline bool d3d9_hookable(void) { - return !!global_hook_info->offsets.d3d9.present && - !!global_hook_info->offsets.d3d9.present_ex && + return !!global_hook_info->offsets.d3d9.present && !!global_hook_info->offsets.d3d9.present_ex && !!global_hook_info->offsets.d3d9.present_swap; } static inline bool dxgi_hookable(void) { - return !!global_hook_info->offsets.dxgi.present && - !!global_hook_info->offsets.dxgi.resize; + return !!global_hook_info->offsets.dxgi.present && !!global_hook_info->offsets.dxgi.resize; } static inline bool attempt_hook(void) @@ -470,11 +455,8 @@ void hlog_hr(const char *text, HRESULT hr) { LPSTR buffer = NULL; - FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | - FORMAT_MESSAGE_ALLOCATE_BUFFER | - FORMAT_MESSAGE_IGNORE_INSERTS, - NULL, hr, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), - (LPSTR)&buffer, 0, NULL); + FormatMessageA(FORMAT_MESSAGE_FROM_SYSTEM | FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_IGNORE_INSERTS, + NULL, hr, MAKELANGID(LANG_ENGLISH, SUBLANG_ENGLISH_US), (LPSTR)&buffer, 0, NULL); if (buffer) { hlog("%s (0x%08lX): %s", text, hr, buffer); @@ -540,31 +522,24 @@ static inline bool init_shared_info(size_t size, HWND window) wchar_t name[64]; HWND top = GetAncestor(window, GA_ROOT); - swprintf(name, 64, SHMEM_TEXTURE "_%" PRIu64 "_%u", - (uint64_t)(uintptr_t)top, ++shmem_id_counter); + swprintf(name, 64, SHMEM_TEXTURE "_%" PRIu64 "_%u", (uint64_t)(uintptr_t)top, ++shmem_id_counter); - shmem_file_handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, - PAGE_READWRITE, 0, (DWORD)size, - name); + shmem_file_handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, (DWORD)size, name); if (!shmem_file_handle) { - hlog("init_shared_info: Failed to create shared memory: %d", - GetLastError()); + hlog("init_shared_info: Failed to create shared memory: %d", GetLastError()); return false; } - shmem_info = MapViewOfFile(shmem_file_handle, FILE_MAP_ALL_ACCESS, 0, 0, - size); + shmem_info = MapViewOfFile(shmem_file_handle, FILE_MAP_ALL_ACCESS, 0, 0, size); if (!shmem_info) { - hlog("init_shared_info: Failed to map shared memory: %d", - GetLastError()); + hlog("init_shared_info: Failed to map shared memory: %d", GetLastError()); return false; } return true; } -bool capture_init_shtex(struct shtex_data **data, HWND window, uint32_t cx, - uint32_t cy, uint32_t format, bool flip, +bool capture_init_shtex(struct shtex_data **data, HWND window, uint32_t cx, uint32_t cy, uint32_t format, bool flip, uintptr_t handle) { if (!init_shared_info(sizeof(struct shtex_data), window)) { @@ -589,8 +564,7 @@ bool capture_init_shtex(struct shtex_data **data, HWND window, uint32_t cx, global_hook_info->UNUSED_base_cy = cy; if (!SetEvent(signal_ready)) { - hlog("capture_init_shtex: Failed to signal ready: %d", - GetLastError()); + hlog("capture_init_shtex: Failed to signal ready: %d", GetLastError()); return false; } @@ -606,14 +580,12 @@ static DWORD CALLBACK copy_thread(LPVOID unused) int shmem_id = 0; if (!duplicate_handle(&events[0], thread_data.copy_event)) { - hlog_hr("copy_thread: Failed to duplicate copy event: %d", - GetLastError()); + hlog_hr("copy_thread: Failed to duplicate copy event: %d", GetLastError()); return 0; } if (!duplicate_handle(&events[1], thread_data.stop_event)) { - hlog_hr("copy_thread: Failed to duplicate stop event: %d", - GetLastError()); + hlog_hr("copy_thread: Failed to duplicate stop event: %d", GetLastError()); goto finish; } @@ -636,12 +608,10 @@ static DWORD CALLBACK copy_thread(LPVOID unused) int lock_id = try_lock_shmem_tex(shmem_id); if (lock_id != -1) { - memcpy(thread_data.shmem_textures[lock_id], - cur_data, (size_t)pitch * (size_t)cy); + memcpy(thread_data.shmem_textures[lock_id], cur_data, (size_t)pitch * (size_t)cy); unlock_shmem_tex(lock_id); - ((struct shmem_data *)shmem_info)->last_tex = - lock_id; + ((struct shmem_data *)shmem_info)->last_tex = lock_id; shmem_id = lock_id == 0 ? 1 : 0; } @@ -708,15 +678,13 @@ static inline bool init_shmem_thread(uint32_t pitch, uint32_t cy) thread_data.copy_event = CreateEvent(NULL, false, false, NULL); if (!thread_data.copy_event) { - hlog("init_shmem_thread: Failed to create copy event: %d", - GetLastError()); + hlog("init_shmem_thread: Failed to create copy event: %d", GetLastError()); return false; } thread_data.stop_event = CreateEvent(NULL, true, false, NULL); if (!thread_data.stop_event) { - hlog("init_shmem_thread: Failed to create stop event: %d", - GetLastError()); + hlog("init_shmem_thread: Failed to create stop event: %d", GetLastError()); return false; } @@ -726,11 +694,9 @@ static inline bool init_shmem_thread(uint32_t pitch, uint32_t cy) InitializeCriticalSection(&thread_data.data_mutex); - thread_data.copy_thread = - CreateThread(NULL, 0, copy_thread, NULL, 0, NULL); + thread_data.copy_thread = CreateThread(NULL, 0, copy_thread, NULL, 0, NULL); if (!thread_data.copy_thread) { - hlog("init_shmem_thread: Failed to create thread: %d", - GetLastError()); + hlog("init_shmem_thread: Failed to create thread: %d", GetLastError()); return false; } return true; @@ -740,8 +706,8 @@ static inline bool init_shmem_thread(uint32_t pitch, uint32_t cy) #define ALIGN(bytes, align) (((bytes) + ((align)-1)) & ~((align)-1)) #endif -bool capture_init_shmem(struct shmem_data **data, HWND window, uint32_t cx, - uint32_t cy, uint32_t pitch, uint32_t format, bool flip) +bool capture_init_shmem(struct shmem_data **data, HWND window, uint32_t cx, uint32_t cy, uint32_t pitch, + uint32_t format, bool flip) { uint32_t tex_size = cy * pitch; uint32_t aligned_header = ALIGN(sizeof(struct shmem_data), 32); @@ -788,8 +754,7 @@ bool capture_init_shmem(struct shmem_data **data, HWND window, uint32_t cx, } if (!SetEvent(signal_ready)) { - hlog("capture_init_shmem: Failed to signal ready: %d", - GetLastError()); + hlog("capture_init_shmem: Failed to signal ready: %d", GetLastError()); return false; } @@ -873,10 +838,8 @@ BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID unused1) } HANDLE cur_thread; - bool success = DuplicateHandle(GetCurrentProcess(), - GetCurrentThread(), - GetCurrentProcess(), &cur_thread, - SYNCHRONIZE, false, 0); + bool success = DuplicateHandle(GetCurrentProcess(), GetCurrentThread(), GetCurrentProcess(), + &cur_thread, SYNCHRONIZE, false, 0); if (!success) DbgOut("[OBS] Failed to get current thread handle"); @@ -899,9 +862,8 @@ BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID unused1) GetModuleFileNameW(hinst, name, MAX_PATH); LoadLibraryW(name); - capture_thread = CreateThread( - NULL, 0, (LPTHREAD_START_ROUTINE)main_capture_thread, - (LPVOID)cur_thread, 0, 0); + capture_thread = + CreateThread(NULL, 0, (LPTHREAD_START_ROUTINE)main_capture_thread, (LPVOID)cur_thread, 0, 0); if (!capture_thread) { CloseHandle(cur_thread); return false; @@ -925,8 +887,7 @@ BOOL WINAPI DllMain(HINSTANCE hinst, DWORD reason, LPVOID unused1) return true; } -__declspec(dllexport) LRESULT CALLBACK - dummy_debug_proc(int code, WPARAM wparam, LPARAM lparam) +__declspec(dllexport) LRESULT CALLBACK dummy_debug_proc(int code, WPARAM wparam, LPARAM lparam) { static bool hooking = true; MSG *msg = (MSG *)lparam; @@ -935,8 +896,7 @@ __declspec(dllexport) LRESULT CALLBACK HMODULE user32 = GetModuleHandleW(L"USER32"); BOOL(WINAPI * unhook_windows_hook_ex)(HHOOK) = NULL; - unhook_windows_hook_ex = ms_get_obfuscated_func( - user32, "VojeleY`bdgxvM`hhDz", 0x7F55F80C9EE3A213ULL); + unhook_windows_hook_ex = ms_get_obfuscated_func(user32, "VojeleY`bdgxvM`hhDz", 0x7F55F80C9EE3A213ULL); if (unhook_windows_hook_ex) unhook_windows_hook_ex((HHOOK)msg->lParam); diff --git a/plugins/win-capture/graphics-hook/graphics-hook.h b/plugins/win-capture/graphics-hook/graphics-hook.h index 4ebf25ae1..1958ae3bb 100644 --- a/plugins/win-capture/graphics-hook/graphics-hook.h +++ b/plugins/win-capture/graphics-hook/graphics-hook.h @@ -71,11 +71,9 @@ extern void d3d12_free(void); extern bool rehook_gl(void); -extern bool capture_init_shtex(struct shtex_data **data, HWND window, - uint32_t cx, uint32_t cy, uint32_t format, +extern bool capture_init_shtex(struct shtex_data **data, HWND window, uint32_t cx, uint32_t cy, uint32_t format, bool flip, uintptr_t handle); -extern bool capture_init_shmem(struct shmem_data **data, HWND window, - uint32_t cx, uint32_t cy, uint32_t pitch, +extern bool capture_init_shmem(struct shmem_data **data, HWND window, uint32_t cx, uint32_t cy, uint32_t pitch, uint32_t format, bool flip); extern void capture_free(void); @@ -92,8 +90,7 @@ struct vertex { static inline bool duplicate_handle(HANDLE *dst, HANDLE src) { - return !!DuplicateHandle(GetCurrentProcess(), src, GetCurrentProcess(), - dst, 0, false, DUPLICATE_SAME_ACCESS); + return !!DuplicateHandle(GetCurrentProcess(), src, GetCurrentProcess(), dst, 0, false, DUPLICATE_SAME_ACCESS); } static inline void *get_offset_addr(HMODULE module, uint32_t offset) @@ -133,8 +130,7 @@ static inline HMODULE get_system_module(const char *module) static inline uint32_t module_size(HMODULE module) { MODULEINFO info; - bool success = !!GetModuleInformation(GetCurrentProcess(), module, - &info, sizeof(info)); + bool success = !!GetModuleInformation(GetCurrentProcess(), module, &info, sizeof(info)); return success ? info.SizeOfImage : 0; } @@ -191,8 +187,7 @@ static inline bool frame_ready(uint64_t interval) static inline bool capture_ready(void) { - return capture_active() && - frame_ready(global_hook_info->frame_interval); + return capture_active() && frame_ready(global_hook_info->frame_interval); } static inline bool capture_stopped(void) @@ -240,12 +235,10 @@ static inline bool capture_should_init(void) should_init = true; } else { - hlog_verbose( - "capture_should_init: inactive, restarted, not alive"); + hlog_verbose("capture_should_init: inactive, restarted, not alive"); } } else { - hlog_verbose( - "capture_should_init: inactive, not restarted"); + hlog_verbose("capture_should_init: inactive, not restarted"); } } diff --git a/plugins/win-capture/graphics-hook/vulkan-capture.c b/plugins/win-capture/graphics-hook/vulkan-capture.c index e6266f3e9..b4ff8b633 100644 --- a/plugins/win-capture/graphics-hook/vulkan-capture.c +++ b/plugins/win-capture/graphics-hook/vulkan-capture.c @@ -133,11 +133,10 @@ __declspec(thread) int vk_presenting = 0; /* ------------------------------------------------------------------------- */ -static void *vk_alloc(const VkAllocationCallbacks *ac, size_t size, - size_t alignment, enum VkSystemAllocationScope scope) +static void *vk_alloc(const VkAllocationCallbacks *ac, size_t size, size_t alignment, + enum VkSystemAllocationScope scope) { - return ac ? ac->pfnAllocation(ac->pUserData, size, alignment, scope) - : _aligned_malloc(size, alignment); + return ac ? ac->pfnAllocation(ac->pUserData, size, alignment, scope) : _aligned_malloc(size, alignment); } static void vk_free(const VkAllocationCallbacks *ac, void *memory) @@ -181,8 +180,7 @@ static struct vk_obj_node *get_obj_data(struct vk_obj_list *list, uint64_t obj) return data; } -static struct vk_obj_node *remove_obj_data(struct vk_obj_list *list, - uint64_t obj) +static struct vk_obj_node *remove_obj_data(struct vk_obj_list *list, uint64_t obj) { struct vk_obj_node *data = NULL; @@ -237,9 +235,8 @@ static struct vk_obj_list devices; static struct vk_data *alloc_device_data(const VkAllocationCallbacks *ac) { - struct vk_data *data = vk_alloc(ac, sizeof(struct vk_data), - _Alignof(struct vk_data), - VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); + struct vk_data *data = + vk_alloc(ac, sizeof(struct vk_data), _Alignof(struct vk_data), VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); return data; } @@ -251,46 +248,36 @@ static void init_device_data(struct vk_data *data, VkDevice device) static struct vk_data *get_device_data(VkDevice device) { - return (struct vk_data *)get_obj_data(&devices, - (uint64_t)GET_LDT(device)); + return (struct vk_data *)get_obj_data(&devices, (uint64_t)GET_LDT(device)); } static struct vk_data *get_device_data_by_queue(VkQueue queue) { - return (struct vk_data *)get_obj_data(&devices, - (uint64_t)GET_LDT(queue)); + return (struct vk_data *)get_obj_data(&devices, (uint64_t)GET_LDT(queue)); } -static struct vk_data * -get_device_data_by_command_buffer(VkCommandBuffer commandBuffer) +static struct vk_data *get_device_data_by_command_buffer(VkCommandBuffer commandBuffer) { - return (struct vk_data *)get_obj_data(&devices, - (uint64_t)GET_LDT(commandBuffer)); + return (struct vk_data *)get_obj_data(&devices, (uint64_t)GET_LDT(commandBuffer)); } static struct vk_data *remove_device_data(VkDevice device) { - return (struct vk_data *)remove_obj_data(&devices, - (uint64_t)GET_LDT(device)); + return (struct vk_data *)remove_obj_data(&devices, (uint64_t)GET_LDT(device)); } -static void free_device_data(struct vk_data *data, - const VkAllocationCallbacks *ac) +static void free_device_data(struct vk_data *data, const VkAllocationCallbacks *ac) { vk_free(ac, data); } /* ------------------------------------------------------------------------- */ -static struct vk_queue_data *add_queue_data(struct vk_data *data, VkQueue queue, - uint32_t fam_idx, - bool supports_transfer, - const VkAllocationCallbacks *ac) +static struct vk_queue_data *add_queue_data(struct vk_data *data, VkQueue queue, uint32_t fam_idx, + bool supports_transfer, const VkAllocationCallbacks *ac) { - struct vk_queue_data *const queue_data = - vk_alloc(ac, sizeof(struct vk_queue_data), - _Alignof(struct vk_queue_data), - VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); + struct vk_queue_data *const queue_data = vk_alloc( + ac, sizeof(struct vk_queue_data), _Alignof(struct vk_queue_data), VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); add_obj_data(&data->queues, (uint64_t)queue, queue_data); queue_data->fam_idx = fam_idx; queue_data->supports_transfer = supports_transfer; @@ -302,15 +289,12 @@ static struct vk_queue_data *add_queue_data(struct vk_data *data, VkQueue queue, static struct vk_queue_data *get_queue_data(struct vk_data *data, VkQueue queue) { - return (struct vk_queue_data *)get_obj_data(&data->queues, - (uint64_t)queue); + return (struct vk_queue_data *)get_obj_data(&data->queues, (uint64_t)queue); } -static void remove_free_queue_all(struct vk_data *data, - const VkAllocationCallbacks *ac) +static void remove_free_queue_all(struct vk_data *data, const VkAllocationCallbacks *ac) { - struct vk_queue_data *queue_data = - (struct vk_queue_data *)data->queues.root; + struct vk_queue_data *queue_data = (struct vk_queue_data *)data->queues.root; while (data->queues.root) { remove_obj_data(&data->queues, queue_data->node.obj); vk_free(ac, queue_data); @@ -326,8 +310,7 @@ static struct vk_queue_data *queue_walk_begin(struct vk_data *data) static struct vk_queue_data *queue_walk_next(struct vk_queue_data *queue_data) { - return (struct vk_queue_data *)obj_walk_next( - (struct vk_obj_node *)queue_data); + return (struct vk_queue_data *)obj_walk_next((struct vk_obj_node *)queue_data); } static void queue_walk_end(struct vk_data *data) @@ -337,47 +320,37 @@ static void queue_walk_end(struct vk_data *data) /* ------------------------------------------------------------------------- */ -static struct vk_swap_view_data * -add_swap_view_data(struct vk_data *data, VkImageView imageView, - const VkAllocationCallbacks *ac) +static struct vk_swap_view_data *add_swap_view_data(struct vk_data *data, VkImageView imageView, + const VkAllocationCallbacks *ac) { - struct vk_swap_view_data *const swap_view_data = - vk_alloc(ac, sizeof(struct vk_swap_view_data), - _Alignof(struct vk_swap_view_data), - VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); + struct vk_swap_view_data *const swap_view_data = vk_alloc(ac, sizeof(struct vk_swap_view_data), + _Alignof(struct vk_swap_view_data), + VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); add_obj_data(&data->swap_views, (uint64_t)imageView, swap_view_data); return swap_view_data; } -static struct vk_swap_view_data *get_swap_view_data(struct vk_data *data, - VkImageView imageView) +static struct vk_swap_view_data *get_swap_view_data(struct vk_data *data, VkImageView imageView) { - return (struct vk_swap_view_data *)get_obj_data(&data->swap_views, - (uint64_t)imageView); + return (struct vk_swap_view_data *)get_obj_data(&data->swap_views, (uint64_t)imageView); } -static void remove_free_swap_view_data(struct vk_data *data, - VkImageView imageView, - const VkAllocationCallbacks *ac) +static void remove_free_swap_view_data(struct vk_data *data, VkImageView imageView, const VkAllocationCallbacks *ac) { struct vk_swap_data *const swap_view_data = - (struct vk_swap_data *)remove_obj_data(&data->swap_views, - (uint64_t)imageView); + (struct vk_swap_data *)remove_obj_data(&data->swap_views, (uint64_t)imageView); vk_free(ac, swap_view_data); } /* ------------------------------------------------------------------------- */ -static struct vk_framebuffer_data * -add_framebuffer_data(struct vk_data *data, VkFramebuffer framebuffer, - const VkAllocationCallbacks *ac) +static struct vk_framebuffer_data *add_framebuffer_data(struct vk_data *data, VkFramebuffer framebuffer, + const VkAllocationCallbacks *ac) { - struct vk_framebuffer_data *const framebuffer_data = - vk_alloc(ac, sizeof(struct vk_framebuffer_data), - _Alignof(struct vk_framebuffer_data), - VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); - add_obj_data(&data->framebuffers, (uint64_t)framebuffer, - framebuffer_data); + struct vk_framebuffer_data *const framebuffer_data = vk_alloc(ac, sizeof(struct vk_framebuffer_data), + _Alignof(struct vk_framebuffer_data), + VK_SYSTEM_ALLOCATION_SCOPE_DEVICE); + add_obj_data(&data->framebuffers, (uint64_t)framebuffer, framebuffer_data); for (size_t i = 0; i < _countof(framebuffer_data->alternates); ++i) { framebuffer_data->alternates[i] = VK_NULL_HANDLE; } @@ -385,20 +358,16 @@ add_framebuffer_data(struct vk_data *data, VkFramebuffer framebuffer, return framebuffer_data; } -static struct vk_framebuffer_data * -get_framebuffer_data(struct vk_data *data, VkFramebuffer framebuffer) +static struct vk_framebuffer_data *get_framebuffer_data(struct vk_data *data, VkFramebuffer framebuffer) { - return (struct vk_framebuffer_data *)get_obj_data( - &data->framebuffers, (uint64_t)framebuffer); + return (struct vk_framebuffer_data *)get_obj_data(&data->framebuffers, (uint64_t)framebuffer); } -static void remove_free_framebuffer_data(struct vk_data *data, - VkFramebuffer framebuffer, +static void remove_free_framebuffer_data(struct vk_data *data, VkFramebuffer framebuffer, const VkAllocationCallbacks *ac) { struct vk_swap_data *const framebuffer_data = - (struct vk_swap_data *)remove_obj_data(&data->framebuffers, - (uint64_t)framebuffer); + (struct vk_swap_data *)remove_obj_data(&data->framebuffers, (uint64_t)framebuffer); vk_free(ac, framebuffer_data); } @@ -406,30 +375,24 @@ static void remove_free_framebuffer_data(struct vk_data *data, static struct vk_swap_data *alloc_swap_data(const VkAllocationCallbacks *ac) { - struct vk_swap_data *const swap_data = vk_alloc( - ac, sizeof(struct vk_swap_data), _Alignof(struct vk_swap_data), - VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); + struct vk_swap_data *const swap_data = vk_alloc(ac, sizeof(struct vk_swap_data), _Alignof(struct vk_swap_data), + VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); return swap_data; } -static void init_swap_data(struct vk_swap_data *swap_data, struct vk_data *data, - VkSwapchainKHR sc) +static void init_swap_data(struct vk_swap_data *swap_data, struct vk_data *data, VkSwapchainKHR sc) { add_obj_data(&data->swaps, (uint64_t)sc, swap_data); } -static struct vk_swap_data *get_swap_data(struct vk_data *data, - VkSwapchainKHR sc) +static struct vk_swap_data *get_swap_data(struct vk_data *data, VkSwapchainKHR sc) { return (struct vk_swap_data *)get_obj_data(&data->swaps, (uint64_t)sc); } -static void remove_free_swap_data(struct vk_data *data, VkSwapchainKHR sc, - const VkAllocationCallbacks *ac) +static void remove_free_swap_data(struct vk_data *data, VkSwapchainKHR sc, const VkAllocationCallbacks *ac) { - struct vk_swap_data *const swap_data = - (struct vk_swap_data *)remove_obj_data(&data->swaps, - (uint64_t)sc); + struct vk_swap_data *const swap_data = (struct vk_swap_data *)remove_obj_data(&data->swaps, (uint64_t)sc); vk_free(ac, swap_data); } @@ -440,8 +403,7 @@ static struct vk_swap_data *swap_walk_begin(struct vk_data *data) static struct vk_swap_data *swap_walk_next(struct vk_swap_data *swap_data) { - return (struct vk_swap_data *)obj_walk_next( - (struct vk_obj_node *)swap_data); + return (struct vk_swap_data *)obj_walk_next((struct vk_obj_node *)swap_data); } static void swap_walk_end(struct vk_data *data) @@ -451,8 +413,7 @@ static void swap_walk_end(struct vk_data *data) /* ------------------------------------------------------------------------- */ -static void vk_shtex_clear_fence(const struct vk_data *data, - struct vk_frame_data *frame_data) +static void vk_shtex_clear_fence(const struct vk_data *data, struct vk_frame_data *frame_data) { const VkFence fence = frame_data->fence; if (frame_data->cmd_buffer_busy) { @@ -464,13 +425,10 @@ static void vk_shtex_clear_fence(const struct vk_data *data, } } -static void vk_shtex_wait_until_pool_idle(struct vk_data *data, - struct vk_queue_data *queue_data) +static void vk_shtex_wait_until_pool_idle(struct vk_data *data, struct vk_queue_data *queue_data) { - for (uint32_t frame_idx = 0; frame_idx < queue_data->frame_count; - frame_idx++) { - struct vk_frame_data *frame_data = - &queue_data->frames[frame_idx]; + for (uint32_t frame_idx = 0; frame_idx < queue_data->frame_count; frame_idx++) { + struct vk_frame_data *frame_data = &queue_data->frames[frame_idx]; if (frame_data->cmd_pool != VK_NULL_HANDLE) vk_shtex_clear_fence(data, frame_data); } @@ -500,8 +458,7 @@ static void vk_shtex_free(struct vk_data *data) while (swap) { VkDevice device = data->device; if (swap->export_image) - data->funcs.DestroyImage(device, swap->export_image, - data->ac); + data->funcs.DestroyImage(device, swap->export_image, data->ac); if (swap->export_mem) data->funcs.FreeMemory(device, swap->export_mem, NULL); @@ -538,12 +495,10 @@ static void vk_shtex_free(struct vk_data *data) /* ------------------------------------------------------------------------- */ -static void add_surf_data(struct vk_inst_data *idata, VkSurfaceKHR surf, - HWND hwnd, const VkAllocationCallbacks *ac) +static void add_surf_data(struct vk_inst_data *idata, VkSurfaceKHR surf, HWND hwnd, const VkAllocationCallbacks *ac) { - struct vk_surf_data *surf_data = vk_alloc( - ac, sizeof(struct vk_surf_data), _Alignof(struct vk_surf_data), - VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); + struct vk_surf_data *surf_data = vk_alloc(ac, sizeof(struct vk_surf_data), _Alignof(struct vk_surf_data), + VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); if (surf_data) { surf_data->hwnd = hwnd; @@ -553,16 +508,13 @@ static void add_surf_data(struct vk_inst_data *idata, VkSurfaceKHR surf, static HWND find_surf_hwnd(struct vk_inst_data *idata, VkSurfaceKHR surf) { - struct vk_surf_data *surf_data = (struct vk_surf_data *)get_obj_data( - &idata->surfaces, (uint64_t)surf); + struct vk_surf_data *surf_data = (struct vk_surf_data *)get_obj_data(&idata->surfaces, (uint64_t)surf); return surf_data->hwnd; } -static void remove_free_surf_data(struct vk_inst_data *idata, VkSurfaceKHR surf, - const VkAllocationCallbacks *ac) +static void remove_free_surf_data(struct vk_inst_data *idata, VkSurfaceKHR surf, const VkAllocationCallbacks *ac) { - struct vk_surf_data *surf_data = (struct vk_surf_data *)remove_obj_data( - &idata->surfaces, (uint64_t)surf); + struct vk_surf_data *surf_data = (struct vk_surf_data *)remove_obj_data(&idata->surfaces, (uint64_t)surf); vk_free(ac, surf_data); } @@ -572,9 +524,8 @@ static struct vk_obj_list instances; static struct vk_inst_data *alloc_inst_data(const VkAllocationCallbacks *ac) { - struct vk_inst_data *idata = vk_alloc( - ac, sizeof(struct vk_inst_data), _Alignof(struct vk_inst_data), - VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE); + struct vk_inst_data *idata = vk_alloc(ac, sizeof(struct vk_inst_data), _Alignof(struct vk_inst_data), + VK_SYSTEM_ALLOCATION_SCOPE_INSTANCE); return idata; } @@ -586,38 +537,29 @@ static void init_inst_data(struct vk_inst_data *idata, VkInstance instance) static struct vk_inst_data *get_inst_data(VkInstance instance) { - return (struct vk_inst_data *)get_obj_data(&instances, - (uint64_t)GET_LDT(instance)); + return (struct vk_inst_data *)get_obj_data(&instances, (uint64_t)GET_LDT(instance)); } static struct vk_inst_funcs *get_inst_funcs(VkInstance instance) { - struct vk_inst_data *idata = - (struct vk_inst_data *)get_inst_data(instance); + struct vk_inst_data *idata = (struct vk_inst_data *)get_inst_data(instance); return &idata->funcs; } -static struct vk_inst_data * -get_inst_data_by_physical_device(VkPhysicalDevice physicalDevice) +static struct vk_inst_data *get_inst_data_by_physical_device(VkPhysicalDevice physicalDevice) { - return (struct vk_inst_data *)get_obj_data( - &instances, (uint64_t)GET_LDT(physicalDevice)); + return (struct vk_inst_data *)get_obj_data(&instances, (uint64_t)GET_LDT(physicalDevice)); } -static struct vk_inst_funcs * -get_inst_funcs_by_physical_device(VkPhysicalDevice physicalDevice) +static struct vk_inst_funcs *get_inst_funcs_by_physical_device(VkPhysicalDevice physicalDevice) { - struct vk_inst_data *idata = - (struct vk_inst_data *)get_inst_data_by_physical_device( - physicalDevice); + struct vk_inst_data *idata = (struct vk_inst_data *)get_inst_data_by_physical_device(physicalDevice); return &idata->funcs; } -static void remove_free_inst_data(VkInstance inst, - const VkAllocationCallbacks *ac) +static void remove_free_inst_data(VkInstance inst, const VkAllocationCallbacks *ac) { - struct vk_inst_data *idata = (struct vk_inst_data *)remove_obj_data( - &instances, (uint64_t)GET_LDT(inst)); + struct vk_inst_data *idata = (struct vk_inst_data *)remove_obj_data(&instances, (uint64_t)GET_LDT(inst)); vk_free(ac, idata); } @@ -646,16 +588,13 @@ static inline bool vk_shtex_init_d3d11(struct vk_data *data) HRESULT(WINAPI * create_factory) (REFIID, void **) = (void *)GetProcAddress(dxgi, "CreateDXGIFactory1"); if (!create_factory) { - flog("failed to get CreateDXGIFactory1 address: %d", - GetLastError()); + flog("failed to get CreateDXGIFactory1 address: %d", GetLastError()); return false; } - PFN_D3D11_CREATE_DEVICE create = - (void *)GetProcAddress(d3d11, "D3D11CreateDevice"); + PFN_D3D11_CREATE_DEVICE create = (void *)GetProcAddress(d3d11, "D3D11CreateDevice"); if (!create) { - flog("failed to get D3D11CreateDevice address: %d", - GetLastError()); + flog("failed to get D3D11CreateDevice address: %d", GetLastError()); return false; } @@ -680,11 +619,9 @@ static inline bool vk_shtex_init_d3d11(struct vk_data *data) D3D_FEATURE_LEVEL_9_3, }; - hr = create((IDXGIAdapter *)adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, - feature_levels, - sizeof(feature_levels) / sizeof(D3D_FEATURE_LEVEL), - D3D11_SDK_VERSION, &data->d3d11_device, &level_used, - &data->d3d11_context); + hr = create((IDXGIAdapter *)adapter, D3D_DRIVER_TYPE_UNKNOWN, NULL, 0, feature_levels, + sizeof(feature_levels) / sizeof(D3D_FEATURE_LEVEL), D3D11_SDK_VERSION, &data->d3d11_device, + &level_used, &data->d3d11_context); IDXGIAdapter1_Release(adapter); if (FAILED(hr)) { @@ -695,8 +632,7 @@ static inline bool vk_shtex_init_d3d11(struct vk_data *data) return true; } -static inline bool vk_shtex_init_d3d11_tex(struct vk_data *data, - struct vk_swap_data *swap) +static inline bool vk_shtex_init_d3d11_tex(struct vk_data *data, struct vk_swap_data *swap) { IDXGIResource *dxgi_res; HRESULT hr; @@ -704,8 +640,8 @@ static inline bool vk_shtex_init_d3d11_tex(struct vk_data *data, const UINT width = swap->image_extent.width; const UINT height = swap->image_extent.height; - flog("OBS requesting %s texture format. capture dimensions: %ux%u", - vk_format_to_str(swap->format), width, height); + flog("OBS requesting %s texture format. capture dimensions: %ux%u", vk_format_to_str(swap->format), width, + height); const DXGI_FORMAT format = vk_format_to_dxgi(swap->format); if (format == DXGI_FORMAT_UNKNOWN) { @@ -718,23 +654,20 @@ static inline bool vk_shtex_init_d3d11_tex(struct vk_data *data, desc.Height = height; desc.MipLevels = 1; desc.ArraySize = 1; - desc.Format = apply_dxgi_format_typeless( - format, global_hook_info->allow_srgb_alias); + desc.Format = apply_dxgi_format_typeless(format, global_hook_info->allow_srgb_alias); desc.SampleDesc.Count = 1; desc.SampleDesc.Quality = 0; desc.Usage = D3D11_USAGE_DEFAULT; desc.MiscFlags = D3D11_RESOURCE_MISC_SHARED; desc.BindFlags = D3D11_BIND_SHADER_RESOURCE; - hr = ID3D11Device_CreateTexture2D(data->d3d11_device, &desc, NULL, - &swap->d3d11_tex); + hr = ID3D11Device_CreateTexture2D(data->d3d11_device, &desc, NULL, &swap->d3d11_tex); if (FAILED(hr)) { flog_hr("failed to create texture", hr); return false; } - hr = ID3D11Texture2D_QueryInterface(swap->d3d11_tex, &IID_IDXGIResource, - &dxgi_res); + hr = ID3D11Texture2D_QueryInterface(swap->d3d11_tex, &IID_IDXGIResource, &dxgi_res); if (FAILED(hr)) { flog_hr("failed to get IDXGIResource", hr); return false; @@ -751,12 +684,10 @@ static inline bool vk_shtex_init_d3d11_tex(struct vk_data *data, return true; } -static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, - struct vk_swap_data *swap) +static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, struct vk_swap_data *swap) { struct vk_device_funcs *funcs = &data->funcs; - VkExternalMemoryFeatureFlags f = - data->external_mem_props.externalMemoryFeatures; + VkExternalMemoryFeatureFlags f = data->external_mem_props.externalMemoryFeatures; /* -------------------------------------------------------- */ /* create texture */ @@ -764,8 +695,7 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, VkExternalMemoryImageCreateInfo emici; emici.sType = VK_STRUCTURE_TYPE_EXTERNAL_MEMORY_IMAGE_CREATE_INFO; emici.pNext = NULL; - emici.handleTypes = - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT; + emici.handleTypes = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT; VkImageCreateInfo ici; ici.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO; @@ -780,8 +710,7 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, ici.arrayLayers = 1; ici.samples = VK_SAMPLE_COUNT_1_BIT; ici.tiling = VK_IMAGE_TILING_OPTIMAL; - ici.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | - VK_IMAGE_USAGE_SAMPLED_BIT; + ici.usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT | VK_IMAGE_USAGE_SAMPLED_BIT; ici.sharingMode = VK_SHARING_MODE_EXCLUSIVE; ici.queueFamilyIndexCount = 0; ici.pQueueFamilyIndices = 0; @@ -815,23 +744,20 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, mr2.pNext = &mdr; VkImageMemoryRequirementsInfo2 imri2 = {0}; - imri2.sType = - VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2; + imri2.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_REQUIREMENTS_INFO_2; imri2.pNext = NULL; imri2.image = swap->export_image; funcs->GetImageMemoryRequirements2(device, &imri2, &mr2); mr = mr2.memoryRequirements; } else { - funcs->GetImageMemoryRequirements(device, swap->export_image, - &mr); + funcs->GetImageMemoryRequirements(device, swap->export_image, &mr); } /* -------------------------------------------------------- */ /* get memory type index */ - struct vk_inst_funcs *ifuncs = - get_inst_funcs_by_physical_device(data->phy_device); + struct vk_inst_funcs *ifuncs = get_inst_funcs_by_physical_device(data->phy_device); VkPhysicalDeviceMemoryProperties pdmp; ifuncs->GetPhysicalDeviceMemoryProperties(data->phy_device, &pdmp); @@ -843,8 +769,7 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, imw32hi.sType = VK_STRUCTURE_TYPE_IMPORT_MEMORY_WIN32_HANDLE_INFO_KHR; imw32hi.pNext = NULL; imw32hi.name = NULL; - imw32hi.handleType = - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT; + imw32hi.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT; imw32hi.handle = swap->handle; VkMemoryAllocateInfo mai; @@ -857,8 +782,7 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, mdai.pNext = NULL; mdai.buffer = VK_NULL_HANDLE; - if (data->external_mem_props.externalMemoryFeatures & - VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT) { + if (data->external_mem_props.externalMemoryFeatures & VK_EXTERNAL_MEMORY_FEATURE_DEDICATED_ONLY_BIT) { mdai.image = swap->export_image; imw32hi.pNext = &mdai; } @@ -866,18 +790,15 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, bool allocated = false; for (uint32_t i = 0; i < pdmp.memoryTypeCount; ++i) { if ((mr.memoryTypeBits & (1 << i)) && - (pdmp.memoryTypes[i].propertyFlags & - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == + (pdmp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) == VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { mai.memoryTypeIndex = i; - res = funcs->AllocateMemory(device, &mai, NULL, - &swap->export_mem); + res = funcs->AllocateMemory(device, &mai, NULL, &swap->export_mem); allocated = res == VK_SUCCESS; if (allocated) break; - flog("failed to AllocateMemory (DEVICE_LOCAL): %s (%d)", - result_to_str(res), (int)res); + flog("failed to AllocateMemory (DEVICE_LOCAL): %s (%d)", result_to_str(res), (int)res); } } @@ -885,18 +806,16 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, /* Try again without DEVICE_LOCAL */ for (uint32_t i = 0; i < pdmp.memoryTypeCount; ++i) { if ((mr.memoryTypeBits & (1 << i)) && - (pdmp.memoryTypes[i].propertyFlags & - VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != + (pdmp.memoryTypes[i].propertyFlags & VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) != VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT) { mai.memoryTypeIndex = i; - res = funcs->AllocateMemory(device, &mai, NULL, - &swap->export_mem); + res = funcs->AllocateMemory(device, &mai, NULL, &swap->export_mem); allocated = res == VK_SUCCESS; if (allocated) break; - flog("failed to AllocateMemory (not DEVICE_LOCAL): %s (%d)", - result_to_str(res), (int)res); + flog("failed to AllocateMemory (not DEVICE_LOCAL): %s (%d)", result_to_str(res), + (int)res); } } } @@ -921,13 +840,10 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, bimi.memoryOffset = 0; res = funcs->BindImageMemory2(device, 1, &bimi); } else { - res = funcs->BindImageMemory(device, swap->export_image, - swap->export_mem, 0); + res = funcs->BindImageMemory(device, swap->export_image, swap->export_mem, 0); } if (VK_SUCCESS != res) { - flog("%s failed: %s", - use_bi2 ? "BindImageMemory2" : "BindImageMemory", - result_to_str(res)); + flog("%s failed: %s", use_bi2 ? "BindImageMemory2" : "BindImageMemory", result_to_str(res)); funcs->DestroyImage(device, swap->export_image, data->ac); swap->export_image = VK_NULL_HANDLE; return false; @@ -935,8 +851,7 @@ static inline bool vk_shtex_init_vulkan_tex(struct vk_data *data, return true; } -static bool vk_shtex_init(struct vk_data *data, HWND window, - struct vk_swap_data *swap) +static bool vk_shtex_init(struct vk_data *data, HWND window, struct vk_swap_data *swap) { if (!vk_shtex_init_d3d11(data)) { return false; @@ -950,10 +865,8 @@ static bool vk_shtex_init(struct vk_data *data, HWND window, data->cur_swap = swap; - swap->captured = capture_init_shtex(&swap->shtex_info, window, - swap->image_extent.width, - swap->image_extent.height, - (uint32_t)swap->format, false, + swap->captured = capture_init_shtex(&swap->shtex_info, window, swap->image_extent.width, + swap->image_extent.height, (uint32_t)swap->format, false, (uintptr_t)swap->handle); if (!swap->captured) @@ -968,24 +881,17 @@ static bool vk_shtex_init(struct vk_data *data, HWND window, return true; } -static void vk_shtex_create_frame_objects(struct vk_data *data, - struct vk_queue_data *queue_data, - uint32_t image_count) +static void vk_shtex_create_frame_objects(struct vk_data *data, struct vk_queue_data *queue_data, uint32_t image_count) { - queue_data->frames = - vk_alloc(data->ac, image_count * sizeof(struct vk_frame_data), - _Alignof(struct vk_frame_data), - VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); - memset(queue_data->frames, 0, - image_count * sizeof(struct vk_frame_data)); + queue_data->frames = vk_alloc(data->ac, image_count * sizeof(struct vk_frame_data), + _Alignof(struct vk_frame_data), VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); + memset(queue_data->frames, 0, image_count * sizeof(struct vk_frame_data)); queue_data->frame_index = 0; queue_data->frame_count = image_count; VkDevice device = data->device; - for (uint32_t image_index = 0; image_index < image_count; - image_index++) { - struct vk_frame_data *frame_data = - &queue_data->frames[image_index]; + for (uint32_t image_index = 0; image_index < image_count; image_index++) { + struct vk_frame_data *frame_data = &queue_data->frames[image_index]; VkCommandPoolCreateInfo cpci; cpci.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO; @@ -993,8 +899,7 @@ static void vk_shtex_create_frame_objects(struct vk_data *data, cpci.flags = 0; cpci.queueFamilyIndex = queue_data->fam_idx; - VkResult res = data->funcs.CreateCommandPool( - device, &cpci, data->ac, &frame_data->cmd_pool); + VkResult res = data->funcs.CreateCommandPool(device, &cpci, data->ac, &frame_data->cmd_pool); debug_res("CreateCommandPool", res); VkCommandBufferAllocateInfo cbai; @@ -1004,8 +909,7 @@ static void vk_shtex_create_frame_objects(struct vk_data *data, cbai.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY; cbai.commandBufferCount = 1; - res = data->funcs.AllocateCommandBuffers( - device, &cbai, &frame_data->cmd_buffer); + res = data->funcs.AllocateCommandBuffers(device, &cbai, &frame_data->cmd_buffer); debug_res("AllocateCommandBuffers", res); GET_LDT(frame_data->cmd_buffer) = GET_LDT(device); @@ -1013,14 +917,12 @@ static void vk_shtex_create_frame_objects(struct vk_data *data, fci.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO; fci.pNext = NULL; fci.flags = 0; - res = data->funcs.CreateFence(device, &fci, data->ac, - &frame_data->fence); + res = data->funcs.CreateFence(device, &fci, data->ac, &frame_data->fence); debug_res("CreateFence", res); } } -static void vk_shtex_destroy_fence(struct vk_data *data, bool *cmd_buffer_busy, - VkFence *fence) +static void vk_shtex_destroy_fence(struct vk_data *data, bool *cmd_buffer_busy, VkFence *fence) { VkDevice device = data->device; @@ -1033,21 +935,17 @@ static void vk_shtex_destroy_fence(struct vk_data *data, bool *cmd_buffer_busy, *fence = VK_NULL_HANDLE; } -static void vk_shtex_destroy_frame_objects(struct vk_data *data, - struct vk_queue_data *queue_data) +static void vk_shtex_destroy_frame_objects(struct vk_data *data, struct vk_queue_data *queue_data) { VkDevice device = data->device; - for (uint32_t frame_idx = 0; frame_idx < queue_data->frame_count; - frame_idx++) { - struct vk_frame_data *frame_data = - &queue_data->frames[frame_idx]; + for (uint32_t frame_idx = 0; frame_idx < queue_data->frame_count; frame_idx++) { + struct vk_frame_data *frame_data = &queue_data->frames[frame_idx]; bool *cmd_buffer_busy = &frame_data->cmd_buffer_busy; VkFence *fence = &frame_data->fence; vk_shtex_destroy_fence(data, cmd_buffer_busy, fence); - data->funcs.DestroyCommandPool(device, frame_data->cmd_pool, - data->ac); + data->funcs.DestroyCommandPool(device, frame_data->cmd_pool, data->ac); frame_data->cmd_pool = VK_NULL_HANDLE; } @@ -1056,10 +954,8 @@ static void vk_shtex_destroy_frame_objects(struct vk_data *data, queue_data->frame_count = 0; } -static void vk_shtex_capture(struct vk_data *data, - struct vk_device_funcs *funcs, - struct vk_swap_data *swap, uint32_t idx, - VkQueue queue, const VkPresentInfoKHR *info) +static void vk_shtex_capture(struct vk_data *data, struct vk_device_funcs *funcs, struct vk_swap_data *swap, + uint32_t idx, VkQueue queue, const VkPresentInfoKHR *info) { VkResult res = VK_SUCCESS; @@ -1129,10 +1025,8 @@ static void vk_shtex_capture(struct vk_data *data, imb.subresourceRange.baseArrayLayer = 0; imb.subresourceRange.layerCount = 1; - funcs->CmdPipelineBarrier(cmd_buffer, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, - 0, NULL, 0, NULL, 1, &imb); + funcs->CmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT, 0, 0, NULL, 0, NULL, 1, &imb); swap->layout_initialized = true; } @@ -1173,10 +1067,8 @@ static void vk_shtex_capture(struct vk_data *data, dst_mb->subresourceRange.baseArrayLayer = 0; dst_mb->subresourceRange.layerCount = 1; - funcs->CmdPipelineBarrier(cmd_buffer, - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - VK_PIPELINE_STAGE_TRANSFER_BIT, 0, 0, NULL, 0, - NULL, 2, mb); + funcs->CmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, VK_PIPELINE_STAGE_TRANSFER_BIT, 0, + 0, NULL, 0, NULL, 2, mb); /* ------------------------------------------------------ */ /* copy cur_backbuffer's content to our interop image */ @@ -1199,9 +1091,7 @@ static void vk_shtex_capture(struct vk_data *data, cpy.extent.width = swap->image_extent.width; cpy.extent.height = swap->image_extent.height; cpy.extent.depth = 1; - funcs->CmdCopyImage(cmd_buffer, cur_backbuffer, - VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, - swap->export_image, + funcs->CmdCopyImage(cmd_buffer, cur_backbuffer, VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, swap->export_image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &cpy); /* ------------------------------------------------------ */ @@ -1223,9 +1113,8 @@ static void vk_shtex_capture(struct vk_data *data, dst_mb->dstQueueFamilyIndex = VK_QUEUE_FAMILY_EXTERNAL; funcs->CmdPipelineBarrier(cmd_buffer, VK_PIPELINE_STAGE_TRANSFER_BIT, - VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | - VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, - 0, 0, NULL, 0, NULL, 2, mb); + VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT | VK_PIPELINE_STAGE_BOTTOM_OF_PIPE_BIT, 0, 0, NULL, + 0, NULL, 2, mb); funcs->EndCommandBuffer(cmd_buffer); @@ -1258,8 +1147,7 @@ static inline bool valid_rect(struct vk_swap_data *swap) return !!swap->image_extent.width && !!swap->image_extent.height; } -static void vk_capture(struct vk_data *data, VkQueue queue, - const VkPresentInfoKHR *info) +static void vk_capture(struct vk_data *data, VkQueue queue, const VkPresentInfoKHR *info) { struct vk_swap_data *swap = NULL; HWND window = NULL; @@ -1273,8 +1161,7 @@ static void vk_capture(struct vk_data *data, VkQueue queue, /* use first swap chain associated with a window */ for (; idx < info->swapchainCount; idx++) { - struct vk_swap_data *cur_swap = - get_swap_data(data, info->pSwapchains[idx]); + struct vk_swap_data *cur_swap = get_swap_data(data, info->pSwapchains[idx]); if (cur_swap) { window = cur_swap->hwnd; if (window != NULL) { @@ -1308,8 +1195,7 @@ static void vk_capture(struct vk_data *data, VkQueue queue, } } -static VkResult VKAPI_CALL OBS_QueuePresentKHR(VkQueue queue, - const VkPresentInfoKHR *info) +static VkResult VKAPI_CALL OBS_QueuePresentKHR(VkQueue queue, const VkPresentInfoKHR *info) { struct vk_data *const data = get_device_data_by_queue(queue); struct vk_queue_data *const queue_data = get_queue_data(data, queue); @@ -1334,12 +1220,10 @@ static VkResult VKAPI_CALL OBS_QueuePresentKHR(VkQueue queue, static inline bool is_inst_link_info(VkLayerInstanceCreateInfo *lici) { - return lici->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && - lici->function == VK_LAYER_LINK_INFO; + return lici->sType == VK_STRUCTURE_TYPE_LOADER_INSTANCE_CREATE_INFO && lici->function == VK_LAYER_LINK_INFO; } -static VkResult VKAPI_CALL OBS_CreateInstance(const VkInstanceCreateInfo *cinfo, - const VkAllocationCallbacks *ac, +static VkResult VKAPI_CALL OBS_CreateInstance(const VkInstanceCreateInfo *cinfo, const VkAllocationCallbacks *ac, VkInstance *p_inst) { VkInstanceCreateInfo info = *cinfo; @@ -1356,8 +1240,7 @@ static VkResult VKAPI_CALL OBS_CreateInstance(const VkInstanceCreateInfo *cinfo, return VK_ERROR_INITIALIZATION_FAILED; } - PFN_vkGetInstanceProcAddr gpa = - lici->u.pLayerInfo->pfnNextGetInstanceProcAddr; + PFN_vkGetInstanceProcAddr gpa = lici->u.pLayerInfo->pfnNextGetInstanceProcAddr; /* -------------------------------------------------------- */ /* move chain on for next layer */ @@ -1446,8 +1329,7 @@ static VkResult VKAPI_CALL OBS_CreateInstance(const VkInstanceCreateInfo *cinfo, return res; } -static void VKAPI_CALL OBS_DestroyInstance(VkInstance instance, - const VkAllocationCallbacks *ac) +static void VKAPI_CALL OBS_DestroyInstance(VkInstance instance, const VkAllocationCallbacks *ac) { struct vk_inst_funcs *ifuncs = get_inst_funcs(instance); PFN_vkDestroyInstance destroy_instance = ifuncs->DestroyInstance; @@ -1457,20 +1339,15 @@ static void VKAPI_CALL OBS_DestroyInstance(VkInstance instance, destroy_instance(instance, ac); } -static bool -vk_shared_tex_supported(struct vk_inst_funcs *funcs, - VkPhysicalDevice phy_device, VkFormat format, - VkImageUsageFlags usage, - VkExternalMemoryProperties *external_mem_props) +static bool vk_shared_tex_supported(struct vk_inst_funcs *funcs, VkPhysicalDevice phy_device, VkFormat format, + VkImageUsageFlags usage, VkExternalMemoryProperties *external_mem_props) { VkPhysicalDeviceImageFormatInfo2 info; VkPhysicalDeviceExternalImageFormatInfo external_info; - external_info.sType = - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO; + external_info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_IMAGE_FORMAT_INFO; external_info.pNext = NULL; - external_info.handleType = - VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT; + external_info.handleType = VK_EXTERNAL_MEMORY_HANDLE_TYPE_D3D11_TEXTURE_KMT_BIT; info.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_IMAGE_FORMAT_INFO_2; info.pNext = &external_info; @@ -1481,39 +1358,31 @@ vk_shared_tex_supported(struct vk_inst_funcs *funcs, info.usage = usage; VkExternalImageFormatProperties external_props = {0}; - external_props.sType = - VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES; + external_props.sType = VK_STRUCTURE_TYPE_EXTERNAL_IMAGE_FORMAT_PROPERTIES; external_props.pNext = NULL; VkImageFormatProperties2 props = {0}; props.sType = VK_STRUCTURE_TYPE_IMAGE_FORMAT_PROPERTIES_2; props.pNext = &external_props; - VkResult result = funcs->GetPhysicalDeviceImageFormatProperties2( - phy_device, &info, &props); + VkResult result = funcs->GetPhysicalDeviceImageFormatProperties2(phy_device, &info, &props); *external_mem_props = external_props.externalMemoryProperties; - const VkExternalMemoryFeatureFlags features = - external_mem_props->externalMemoryFeatures; + const VkExternalMemoryFeatureFlags features = external_mem_props->externalMemoryFeatures; - return ((VK_SUCCESS == result) && - (features & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)); + return ((VK_SUCCESS == result) && (features & VK_EXTERNAL_MEMORY_FEATURE_IMPORTABLE_BIT)); } static inline bool is_device_link_info(VkLayerDeviceCreateInfo *lici) { - return lici->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && - lici->function == VK_LAYER_LINK_INFO; + return lici->sType == VK_STRUCTURE_TYPE_LOADER_DEVICE_CREATE_INFO && lici->function == VK_LAYER_LINK_INFO; } -static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, - const VkDeviceCreateInfo *info, - const VkAllocationCallbacks *ac, - VkDevice *p_device) +static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, const VkDeviceCreateInfo *info, + const VkAllocationCallbacks *ac, VkDevice *p_device) { - struct vk_inst_data *idata = - get_inst_data_by_physical_device(phy_device); + struct vk_inst_data *idata = get_inst_data_by_physical_device(phy_device); struct vk_inst_funcs *ifuncs = &idata->funcs; struct vk_data *data = NULL; @@ -1557,8 +1426,7 @@ static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, /* -------------------------------------------------------- */ /* create device and initialize hook data */ - PFN_vkCreateDevice createFunc = - (PFN_vkCreateDevice)gipa(idata->instance, "vkCreateDevice"); + PFN_vkCreateDevice createFunc = (PFN_vkCreateDevice)gipa(idata->instance, "vkCreateDevice"); ret = createFunc(phy_device, info, ac, p_device); if (ret != VK_SUCCESS) { @@ -1639,19 +1507,15 @@ static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, goto fail; } - const char *required_device_extensions[] = { - VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME}; + const char *required_device_extensions[] = {VK_KHR_EXTERNAL_MEMORY_WIN32_EXTENSION_NAME}; uint32_t device_extension_count = 0; - ret = ifuncs->EnumerateDeviceExtensionProperties( - phy_device, NULL, &device_extension_count, NULL); + ret = ifuncs->EnumerateDeviceExtensionProperties(phy_device, NULL, &device_extension_count, NULL); if (ret != VK_SUCCESS) goto fail; - VkExtensionProperties *device_extensions = _malloca( - sizeof(VkExtensionProperties) * device_extension_count); - ret = ifuncs->EnumerateDeviceExtensionProperties( - phy_device, NULL, &device_extension_count, device_extensions); + VkExtensionProperties *device_extensions = _malloca(sizeof(VkExtensionProperties) * device_extension_count); + ret = ifuncs->EnumerateDeviceExtensionProperties(phy_device, NULL, &device_extension_count, device_extensions); if (ret != VK_SUCCESS) { _freea(device_extensions); goto fail; @@ -1659,21 +1523,18 @@ static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, bool extensions_found = true; for (uint32_t i = 0; i < _countof(required_device_extensions); i++) { - const char *const required_extension = - required_device_extensions[i]; + const char *const required_extension = required_device_extensions[i]; bool found = false; for (uint32_t j = 0; j < device_extension_count; j++) { - if (!strcmp(required_extension, - device_extensions[j].extensionName)) { + if (!strcmp(required_extension, device_extensions[j].extensionName)) { found = true; break; } } if (!found) { - flog("missing device extension: %s", - required_extension); + flog("missing device extension: %s", required_extension); extensions_found = false; } } @@ -1684,11 +1545,9 @@ static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, goto fail; VkFormat format = VK_FORMAT_R8G8B8A8_UNORM; - VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | - VK_IMAGE_USAGE_TRANSFER_DST_BIT; + VkImageUsageFlags usage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (!vk_shared_tex_supported(ifuncs, phy_device, format, usage, - &data->external_mem_props)) { + if (!vk_shared_tex_supported(ifuncs, phy_device, format, usage, &data->external_mem_props)) { flog("texture sharing is not supported"); goto fail; } @@ -1702,33 +1561,23 @@ static VkResult VKAPI_CALL OBS_CreateDevice(VkPhysicalDevice phy_device, } uint32_t queue_family_property_count = 0; - ifuncs->GetPhysicalDeviceQueueFamilyProperties( - phy_device, &queue_family_property_count, NULL); - VkQueueFamilyProperties *queue_family_properties = _malloca( - sizeof(VkQueueFamilyProperties) * queue_family_property_count); - ifuncs->GetPhysicalDeviceQueueFamilyProperties( - phy_device, &queue_family_property_count, - queue_family_properties); + ifuncs->GetPhysicalDeviceQueueFamilyProperties(phy_device, &queue_family_property_count, NULL); + VkQueueFamilyProperties *queue_family_properties = + _malloca(sizeof(VkQueueFamilyProperties) * queue_family_property_count); + ifuncs->GetPhysicalDeviceQueueFamilyProperties(phy_device, &queue_family_property_count, + queue_family_properties); - for (uint32_t info_index = 0, info_count = info->queueCreateInfoCount; - info_index < info_count; ++info_index) { - const VkDeviceQueueCreateInfo *queue_info = - &info->pQueueCreateInfos[info_index]; - for (uint32_t queue_index = 0, - queue_count = queue_info->queueCount; - queue_index < queue_count; ++queue_index) { - const uint32_t family_index = - queue_info->queueFamilyIndex; + for (uint32_t info_index = 0, info_count = info->queueCreateInfoCount; info_index < info_count; ++info_index) { + const VkDeviceQueueCreateInfo *queue_info = &info->pQueueCreateInfos[info_index]; + for (uint32_t queue_index = 0, queue_count = queue_info->queueCount; queue_index < queue_count; + ++queue_index) { + const uint32_t family_index = queue_info->queueFamilyIndex; VkQueue queue; - data->funcs.GetDeviceQueue(device, family_index, - queue_index, &queue); + data->funcs.GetDeviceQueue(device, family_index, queue_index, &queue); const bool supports_transfer = - (queue_family_properties[family_index] - .queueFlags & - (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | - VK_QUEUE_TRANSFER_BIT)) != 0; - add_queue_data(data, queue, family_index, - supports_transfer, ac); + (queue_family_properties[family_index].queueFlags & + (VK_QUEUE_GRAPHICS_BIT | VK_QUEUE_COMPUTE_BIT | VK_QUEUE_TRANSFER_BIT)) != 0; + add_queue_data(data, queue, family_index, supports_transfer, ac); } } @@ -1745,8 +1594,7 @@ fail: return ret; } -static void VKAPI_CALL OBS_DestroyDevice(VkDevice device, - const VkAllocationCallbacks *ac) +static void VKAPI_CALL OBS_DestroyDevice(VkDevice device, const VkAllocationCallbacks *ac) { struct vk_data *data = remove_device_data(device); @@ -1771,9 +1619,8 @@ static void VKAPI_CALL OBS_DestroyDevice(VkDevice device, destroy_device(device, ac); } -static VkResult VKAPI_CALL -OBS_CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *cinfo, - const VkAllocationCallbacks *ac, VkSwapchainKHR *p_sc) +static VkResult VKAPI_CALL OBS_CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *cinfo, + const VkAllocationCallbacks *ac, VkSwapchainKHR *p_sc) { struct vk_data *data = get_device_data(device); struct vk_device_funcs *funcs = &data->funcs; @@ -1796,17 +1643,14 @@ OBS_CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *cinfo, if ((res == VK_SUCCESS) && (count > 0)) { struct vk_swap_data *swap_data = alloc_swap_data(ac); if (swap_data) { - swap_data->swap_images = vk_alloc( - ac, count * sizeof(VkImage), _Alignof(VkImage), - VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); - res = funcs->GetSwapchainImagesKHR( - device, sc, &count, swap_data->swap_images); + swap_data->swap_images = vk_alloc(ac, count * sizeof(VkImage), _Alignof(VkImage), + VK_SYSTEM_ALLOCATION_SCOPE_OBJECT); + res = funcs->GetSwapchainImagesKHR(device, sc, &count, swap_data->swap_images); debug_res("GetSwapchainImagesKHR", res); swap_data->image_extent = cinfo->imageExtent; swap_data->format = cinfo->imageFormat; - swap_data->hwnd = - find_surf_hwnd(data->inst_data, cinfo->surface); + swap_data->hwnd = find_surf_hwnd(data->inst_data, cinfo->surface); swap_data->export_image = VK_NULL_HANDLE; swap_data->layout_initialized = false; swap_data->export_mem = VK_NULL_HANDLE; @@ -1822,9 +1666,8 @@ OBS_CreateSwapchainKHR(VkDevice device, const VkSwapchainCreateInfoKHR *cinfo, return VK_SUCCESS; } -static VkResult VKAPI_CALL -OBS_CreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo, - const VkAllocationCallbacks *pAllocator, VkImageView *pView) +static VkResult VKAPI_CALL OBS_CreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo, + const VkAllocationCallbacks *pAllocator, VkImageView *pView) { bool from_swap_chain = false; @@ -1833,10 +1676,8 @@ OBS_CreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo, struct vk_swap_data *swap = swap_walk_begin(data); while (swap) { - for (uint32_t i = 0, count = swap->image_count; - i < count; ++i) { - from_swap_chain = swap->swap_images[i] == - pCreateInfo->image; + for (uint32_t i = 0, count = swap->image_count; i < count; ++i) { + from_swap_chain = swap->swap_images[i] == pCreateInfo->image; if (from_swap_chain) break; } @@ -1854,11 +1695,8 @@ OBS_CreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo, while (pCurrent) { VkBaseInStructure baseIn; memcpy(&baseIn, pCurrent, sizeof(baseIn)); - if (baseIn.sType == - VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO) { - ((VkImageViewUsageCreateInfo *)pCurrent) - ->usage |= - VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + if (baseIn.sType == VK_STRUCTURE_TYPE_IMAGE_VIEW_USAGE_CREATE_INFO) { + ((VkImageViewUsageCreateInfo *)pCurrent)->usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; break; } @@ -1873,15 +1711,13 @@ OBS_CreateImageView(VkDevice device, const VkImageViewCreateInfo *pCreateInfo, return result; } -static void VKAPI_CALL -OBS_DestroyImageView(VkDevice device, VkImageView imageView, - const VkAllocationCallbacks *pAllocator) +static void VKAPI_CALL OBS_DestroyImageView(VkDevice device, VkImageView imageView, + const VkAllocationCallbacks *pAllocator) { struct vk_data *const data = get_device_data(device); if (data->valid && (imageView != VK_NULL_HANDLE)) { - struct vk_swap_view_data *swap_view_data = - get_swap_view_data(data, imageView); + struct vk_swap_view_data *swap_view_data = get_swap_view_data(data, imageView); if (swap_view_data) remove_free_swap_view_data(data, imageView, pAllocator); } @@ -1889,32 +1725,24 @@ OBS_DestroyImageView(VkDevice device, VkImageView imageView, data->funcs.DestroyImageView(device, imageView, pAllocator); } -static void generate_framebuffer_variants( - PFN_vkCreateFramebuffer func, VkDevice device, - const VkFramebufferCreateInfo *pCreateInfo, - const VkAllocationCallbacks *pAllocator, - struct vk_framebuffer_data *framebuffer_data, - const VkFramebufferAttachmentsCreateInfo *pAttachmentsCreateInfo, - uint32_t colorCount) +static void +generate_framebuffer_variants(PFN_vkCreateFramebuffer func, VkDevice device, const VkFramebufferCreateInfo *pCreateInfo, + const VkAllocationCallbacks *pAllocator, struct vk_framebuffer_data *framebuffer_data, + const VkFramebufferAttachmentsCreateInfo *pAttachmentsCreateInfo, uint32_t colorCount) { const uint32_t variantCount = 1 << colorCount; for (uint32_t colorMask = 0; colorMask < variantCount; ++colorMask) { VkImageUsageFlags pPreviousUsage[OBS_COLOR_ATTACHMENT_LIMIT]; uint32_t colorIndex = 0; - for (uint32_t infoIndex = 0, - count = pAttachmentsCreateInfo - ->attachmentImageInfoCount; + for (uint32_t infoIndex = 0, count = pAttachmentsCreateInfo->attachmentImageInfoCount; infoIndex < count; ++infoIndex) { const VkFramebufferAttachmentImageInfo *const pInfo = - &pAttachmentsCreateInfo - ->pAttachmentImageInfos[infoIndex]; + &pAttachmentsCreateInfo->pAttachmentImageInfos[infoIndex]; const VkImageUsageFlags usage = pInfo->usage; if (usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { pPreviousUsage[colorIndex] = usage; if (colorMask & (1 << colorIndex)) { - ((VkFramebufferAttachmentImageInfo *) - pInfo) - ->usage |= + ((VkFramebufferAttachmentImageInfo *)pInfo)->usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; } @@ -1925,26 +1753,18 @@ static void generate_framebuffer_variants( } VkFramebuffer framebuffer; - const VkResult result = - func(device, pCreateInfo, pAllocator, &framebuffer); + const VkResult result = func(device, pCreateInfo, pAllocator, &framebuffer); if (result == VK_SUCCESS) framebuffer_data->alternates[colorMask] = framebuffer; colorIndex = 0; - for (uint32_t infoIndex = 0, - count = pAttachmentsCreateInfo - ->attachmentImageInfoCount; + for (uint32_t infoIndex = 0, count = pAttachmentsCreateInfo->attachmentImageInfoCount; infoIndex < count; ++infoIndex) { const VkFramebufferAttachmentImageInfo *const pInfo = - &pAttachmentsCreateInfo - ->pAttachmentImageInfos[infoIndex]; - if (pInfo->usage & - VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { + &pAttachmentsCreateInfo->pAttachmentImageInfos[infoIndex]; + if (pInfo->usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { if (colorMask & (1 << colorIndex)) { - ((VkFramebufferAttachmentImageInfo *) - pInfo) - ->usage = - pPreviousUsage[colorIndex]; + ((VkFramebufferAttachmentImageInfo *)pInfo)->usage = pPreviousUsage[colorIndex]; } ++colorIndex; @@ -1955,54 +1775,39 @@ static void generate_framebuffer_variants( } } -static VkResult VKAPI_CALL OBS_CreateFramebuffer( - VkDevice device, const VkFramebufferCreateInfo *pCreateInfo, - const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer) +static VkResult VKAPI_CALL OBS_CreateFramebuffer(VkDevice device, const VkFramebufferCreateInfo *pCreateInfo, + const VkAllocationCallbacks *pAllocator, VkFramebuffer *pFramebuffer) { struct vk_data *const data = get_device_data(device); const PFN_vkCreateFramebuffer func = data->funcs.CreateFramebuffer; VkResult result = func(device, pCreateInfo, pAllocator, pFramebuffer); - if (data->valid && (result == VK_SUCCESS) && - (pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) { + if (data->valid && (result == VK_SUCCESS) && (pCreateInfo->flags & VK_FRAMEBUFFER_CREATE_IMAGELESS_BIT)) { struct vk_framebuffer_data *const framebuffer_data = add_framebuffer_data(data, *pFramebuffer, pAllocator); const void *pCurrent = pCreateInfo->pNext; while (pCurrent) { VkBaseInStructure baseIn; memcpy(&baseIn, pCurrent, sizeof(baseIn)); - if (baseIn.sType == - VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO) { + if (baseIn.sType == VK_STRUCTURE_TYPE_FRAMEBUFFER_ATTACHMENTS_CREATE_INFO) { uint32_t attachmentMask = 0; uint32_t colorCount = 0; - const VkFramebufferAttachmentsCreateInfo *const - pAttachmentsCreateInfo = pCurrent; - for (uint32_t - infoIndex = 0, - count = min( - sizeof(attachmentMask) * 8, - pAttachmentsCreateInfo - ->attachmentImageInfoCount); + const VkFramebufferAttachmentsCreateInfo *const pAttachmentsCreateInfo = pCurrent; + for (uint32_t infoIndex = 0, + count = min(sizeof(attachmentMask) * 8, + pAttachmentsCreateInfo->attachmentImageInfoCount); infoIndex < count; ++infoIndex) { - if (pAttachmentsCreateInfo - ->pAttachmentImageInfos - [infoIndex] - .usage & + if (pAttachmentsCreateInfo->pAttachmentImageInfos[infoIndex].usage & VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT) { - attachmentMask |= 1 - << infoIndex; + attachmentMask |= 1 << infoIndex; ++colorCount; - if (colorCount == - OBS_COLOR_ATTACHMENT_LIMIT) + if (colorCount == OBS_COLOR_ATTACHMENT_LIMIT) break; } } - generate_framebuffer_variants( - func, device, pCreateInfo, pAllocator, - framebuffer_data, - pAttachmentsCreateInfo, colorCount); - framebuffer_data->color_attachment_mask = - attachmentMask; + generate_framebuffer_variants(func, device, pCreateInfo, pAllocator, framebuffer_data, + pAttachmentsCreateInfo, colorCount); + framebuffer_data->color_attachment_mask = attachmentMask; break; } @@ -2013,91 +1818,64 @@ static VkResult VKAPI_CALL OBS_CreateFramebuffer( return result; } -static void VKAPI_CALL -OBS_DestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer, - const VkAllocationCallbacks *pAllocator) +static void VKAPI_CALL OBS_DestroyFramebuffer(VkDevice device, VkFramebuffer framebuffer, + const VkAllocationCallbacks *pAllocator) { struct vk_data *const data = get_device_data(device); struct vk_device_funcs *const funcs = &data->funcs; if (data->valid && (framebuffer != VK_NULL_HANDLE)) { - struct vk_framebuffer_data *framebuffer_data = - get_framebuffer_data(data, framebuffer); + struct vk_framebuffer_data *framebuffer_data = get_framebuffer_data(data, framebuffer); if (framebuffer_data) { - for (size_t i = 0; - i < _countof(framebuffer_data->alternates); ++i) { - if (framebuffer_data->alternates[i] != - VK_NULL_HANDLE) { - funcs->DestroyFramebuffer( - device, - framebuffer_data->alternates[i], - pAllocator); - framebuffer_data->alternates[i] = - VK_NULL_HANDLE; + for (size_t i = 0; i < _countof(framebuffer_data->alternates); ++i) { + if (framebuffer_data->alternates[i] != VK_NULL_HANDLE) { + funcs->DestroyFramebuffer(device, framebuffer_data->alternates[i], pAllocator); + framebuffer_data->alternates[i] = VK_NULL_HANDLE; } } - remove_free_framebuffer_data(data, framebuffer, - pAllocator); + remove_free_framebuffer_data(data, framebuffer, pAllocator); } } funcs->DestroyFramebuffer(device, framebuffer, pAllocator); } -static const VkRenderPassBeginInfo * -process_render_pass_begin_info(const VkRenderPassBeginInfo *pRenderPassBegin, - VkRenderPassBeginInfo *pAlternateBegin, - struct vk_data *data) +static const VkRenderPassBeginInfo *process_render_pass_begin_info(const VkRenderPassBeginInfo *pRenderPassBegin, + VkRenderPassBeginInfo *pAlternateBegin, + struct vk_data *data) { const void *pCurrent = pRenderPassBegin->pNext; while (pCurrent) { VkBaseInStructure baseIn; memcpy(&baseIn, pCurrent, sizeof(baseIn)); - if (baseIn.sType == - VK_STRUCTURE_TYPE_RENDER_PASS_ATTACHMENT_BEGIN_INFO) { + if (baseIn.sType == VK_STRUCTURE_TYPE_RENDER_PASS_ATTACHMENT_BEGIN_INFO) { struct vk_framebuffer_data *const framebuffer_data = - get_framebuffer_data( - data, pRenderPassBegin->framebuffer); + get_framebuffer_data(data, pRenderPassBegin->framebuffer); if (framebuffer_data) { - const VkRenderPassAttachmentBeginInfo - *const pAttachmentInfo = pCurrent; + const VkRenderPassAttachmentBeginInfo *const pAttachmentInfo = pCurrent; uint32_t swapMask = 0; uint32_t colorIndex = 0; - for (uint32_t infoIndex = 0, - count = pAttachmentInfo - ->attachmentCount; + for (uint32_t infoIndex = 0, count = pAttachmentInfo->attachmentCount; infoIndex < count; ++infoIndex) { - if (framebuffer_data - ->color_attachment_mask & - (1 << infoIndex)) { - if (get_swap_view_data( - data, - pAttachmentInfo->pAttachments - [infoIndex])) { - swapMask |= - 1 << colorIndex; + if (framebuffer_data->color_attachment_mask & (1 << infoIndex)) { + if (get_swap_view_data(data, + pAttachmentInfo->pAttachments[infoIndex])) { + swapMask |= 1 << colorIndex; } ++colorIndex; - if (colorIndex == - OBS_COLOR_ATTACHMENT_LIMIT) + if (colorIndex == OBS_COLOR_ATTACHMENT_LIMIT) break; } } if (swapMask > 0) { - VkFramebuffer alternate = - framebuffer_data - ->alternates[swapMask]; + VkFramebuffer alternate = framebuffer_data->alternates[swapMask]; if (alternate != VK_NULL_HANDLE) { - *pAlternateBegin = - *pRenderPassBegin; - pAlternateBegin->framebuffer = - framebuffer_data->alternates - [swapMask]; - pRenderPassBegin = - pAlternateBegin; + *pAlternateBegin = *pRenderPassBegin; + pAlternateBegin->framebuffer = framebuffer_data->alternates[swapMask]; + pRenderPassBegin = pAlternateBegin; } } } @@ -2111,65 +1889,49 @@ process_render_pass_begin_info(const VkRenderPassBeginInfo *pRenderPassBegin, return pRenderPassBegin; } -static void VKAPI_CALL -OBS_CmdBeginRenderPass(VkCommandBuffer commandBuffer, - const VkRenderPassBeginInfo *pRenderPassBegin, - VkSubpassContents contents) +static void VKAPI_CALL OBS_CmdBeginRenderPass(VkCommandBuffer commandBuffer, + const VkRenderPassBeginInfo *pRenderPassBegin, VkSubpassContents contents) { - struct vk_data *const data = - get_device_data_by_command_buffer(commandBuffer); + struct vk_data *const data = get_device_data_by_command_buffer(commandBuffer); VkRenderPassBeginInfo alternateBegin; if (data->valid) { - pRenderPassBegin = process_render_pass_begin_info( - pRenderPassBegin, &alternateBegin, data); + pRenderPassBegin = process_render_pass_begin_info(pRenderPassBegin, &alternateBegin, data); } - data->funcs.CmdBeginRenderPass(commandBuffer, pRenderPassBegin, - contents); + data->funcs.CmdBeginRenderPass(commandBuffer, pRenderPassBegin, contents); } -static void VKAPI_CALL -OBS_CmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, - const VkRenderPassBeginInfo *pRenderPassBegin, - const VkSubpassBeginInfo *pSubpassBeginInfo) +static void VKAPI_CALL OBS_CmdBeginRenderPass2KHR(VkCommandBuffer commandBuffer, + const VkRenderPassBeginInfo *pRenderPassBegin, + const VkSubpassBeginInfo *pSubpassBeginInfo) { - struct vk_data *const data = - get_device_data_by_command_buffer(commandBuffer); + struct vk_data *const data = get_device_data_by_command_buffer(commandBuffer); VkRenderPassBeginInfo alternateBegin; if (data->valid) { - pRenderPassBegin = process_render_pass_begin_info( - pRenderPassBegin, &alternateBegin, data); + pRenderPassBegin = process_render_pass_begin_info(pRenderPassBegin, &alternateBegin, data); } - data->funcs.CmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, - pSubpassBeginInfo); + data->funcs.CmdBeginRenderPass2KHR(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); } -static void VKAPI_CALL -OBS_CmdBeginRenderPass2(VkCommandBuffer commandBuffer, - const VkRenderPassBeginInfo *pRenderPassBegin, - const VkSubpassBeginInfo *pSubpassBeginInfo) +static void VKAPI_CALL OBS_CmdBeginRenderPass2(VkCommandBuffer commandBuffer, + const VkRenderPassBeginInfo *pRenderPassBegin, + const VkSubpassBeginInfo *pSubpassBeginInfo) { - struct vk_data *const data = - get_device_data_by_command_buffer(commandBuffer); + struct vk_data *const data = get_device_data_by_command_buffer(commandBuffer); VkRenderPassBeginInfo alternateBegin; if (data->valid) { - pRenderPassBegin = process_render_pass_begin_info( - pRenderPassBegin, &alternateBegin, data); + pRenderPassBegin = process_render_pass_begin_info(pRenderPassBegin, &alternateBegin, data); } - data->funcs.CmdBeginRenderPass2(commandBuffer, pRenderPassBegin, - pSubpassBeginInfo); + data->funcs.CmdBeginRenderPass2(commandBuffer, pRenderPassBegin, pSubpassBeginInfo); } -static void VKAPI_CALL OBS_DestroySwapchainKHR(VkDevice device, - VkSwapchainKHR sc, - const VkAllocationCallbacks *ac) +static void VKAPI_CALL OBS_DestroySwapchainKHR(VkDevice device, VkSwapchainKHR sc, const VkAllocationCallbacks *ac) { struct vk_data *data = get_device_data(device); struct vk_device_funcs *funcs = &data->funcs; - PFN_vkDestroySwapchainKHR destroy_swapchain = - funcs->DestroySwapchainKHR; + PFN_vkDestroySwapchainKHR destroy_swapchain = funcs->DestroySwapchainKHR; if ((sc != VK_NULL_HANDLE) && data->valid) { struct vk_swap_data *swap = get_swap_data(data, sc); @@ -2187,9 +1949,8 @@ static void VKAPI_CALL OBS_DestroySwapchainKHR(VkDevice device, destroy_swapchain(device, sc, ac); } -static VkResult VKAPI_CALL OBS_CreateWin32SurfaceKHR( - VkInstance inst, const VkWin32SurfaceCreateInfoKHR *info, - const VkAllocationCallbacks *ac, VkSurfaceKHR *surf) +static VkResult VKAPI_CALL OBS_CreateWin32SurfaceKHR(VkInstance inst, const VkWin32SurfaceCreateInfoKHR *info, + const VkAllocationCallbacks *ac, VkSurfaceKHR *surf) { struct vk_inst_data *idata = get_inst_data(inst); struct vk_inst_funcs *ifuncs = &idata->funcs; @@ -2200,8 +1961,7 @@ static VkResult VKAPI_CALL OBS_CreateWin32SurfaceKHR( return res; } -static void VKAPI_CALL OBS_DestroySurfaceKHR(VkInstance inst, VkSurfaceKHR surf, - const VkAllocationCallbacks *ac) +static void VKAPI_CALL OBS_DestroySurfaceKHR(VkInstance inst, VkSurfaceKHR surf, const VkAllocationCallbacks *ac) { struct vk_inst_data *idata = get_inst_data(inst); struct vk_inst_funcs *ifuncs = &idata->funcs; @@ -2223,8 +1983,7 @@ static void VKAPI_CALL OBS_DestroySurfaceKHR(VkInstance inst, VkSurfaceKHR surf, return funcs->func ? (PFN_vkVoidFunction)&OBS_##func : NULL; /* clang-format on */ -static PFN_vkVoidFunction VKAPI_CALL OBS_GetDeviceProcAddr(VkDevice device, - const char *pName) +static PFN_vkVoidFunction VKAPI_CALL OBS_GetDeviceProcAddr(VkDevice device, const char *pName) { struct vk_data *data = get_device_data(device); struct vk_device_funcs *funcs = &data->funcs; @@ -2252,8 +2011,7 @@ static PFN_vkVoidFunction VKAPI_CALL OBS_GetDeviceProcAddr(VkDevice device, /* bad layers require spec violation */ #define RETURN_FP_FOR_NULL_INSTANCE 1 -static PFN_vkVoidFunction VKAPI_CALL -OBS_GetInstanceProcAddr(VkInstance instance, const char *pName) +static PFN_vkVoidFunction VKAPI_CALL OBS_GetInstanceProcAddr(VkInstance instance, const char *pName) { debug_procaddr("vkGetInstanceProcAddr(%p, \"%s\")", instance, pName); @@ -2303,8 +2061,7 @@ OBS_GetInstanceProcAddr(VkInstance instance, const char *pName) #pragma comment(linker, "/EXPORT:OBS_Negotiate=_OBS_Negotiate@4") #endif -__declspec(dllexport) VkResult VKAPI_CALL - OBS_Negotiate(VkNegotiateLayerInterface *nli) +__declspec(dllexport) VkResult VKAPI_CALL OBS_Negotiate(VkNegotiateLayerInterface *nli) { if (nli->loaderLayerInterfaceVersion >= 2) { nli->sType = LAYER_NEGOTIATE_INTERFACE_STRUCT; diff --git a/plugins/win-capture/graphics-hook/vulkan-capture.h b/plugins/win-capture/graphics-hook/vulkan-capture.h index 0bb3af45b..b59f2d1f2 100644 --- a/plugins/win-capture/graphics-hook/vulkan-capture.h +++ b/plugins/win-capture/graphics-hook/vulkan-capture.h @@ -854,12 +854,11 @@ DXGI_FORMAT vk_format_to_dxgi(VkFormat format) #ifdef DEBUG_PRINT #include -#define debug(format, ...) \ - do { \ - char str[256]; \ - snprintf(str, sizeof(str) - 1, "%s " format "\n", \ - "[OBS graphics-hook]", ##__VA_ARGS__); \ - OutputDebugStringA(str); \ +#define debug(format, ...) \ + do { \ + char str[256]; \ + snprintf(str, sizeof(str) - 1, "%s " format "\n", "[OBS graphics-hook]", ##__VA_ARGS__); \ + OutputDebugStringA(str); \ } while (false) #define debug_res(x, y) debug("%s result: %s", x, result_to_str(y)) diff --git a/plugins/win-capture/inject-helper/inject-helper.c b/plugins/win-capture/inject-helper/inject-helper.c index ee161288d..ce21f2d70 100644 --- a/plugins/win-capture/inject-helper/inject-helper.c +++ b/plugins/win-capture/inject-helper/inject-helper.c @@ -32,38 +32,30 @@ static void load_debug_privilege(void) tp.Privileges[0].Luid = val; tp.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED; - AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, - NULL); + AdjustTokenPrivileges(token, false, &tp, sizeof(tp), NULL, NULL); } CloseHandle(token); } -static inline HANDLE open_process(DWORD desired_access, bool inherit_handle, - DWORD process_id) +static inline HANDLE open_process(DWORD desired_access, bool inherit_handle, DWORD process_id) { HANDLE(WINAPI * open_process_proc)(DWORD, BOOL, DWORD); - open_process_proc = - ms_get_obfuscated_func(GetModuleHandleW(L"KERNEL32"), - "HxjcQrmkb|~", 0xc82efdf78201df87); + open_process_proc = ms_get_obfuscated_func(GetModuleHandleW(L"KERNEL32"), "HxjcQrmkb|~", 0xc82efdf78201df87); return open_process_proc(desired_access, inherit_handle, process_id); } static inline int inject_library(HANDLE process, const wchar_t *dll) { - return inject_library_obf(process, dll, "E}mo|d[cefubWk~bgk", - 0x7c3371986918e8f6, "Rqbr`T{cnor{Bnlgwz", - 0x81bf81adc9456b35, "]`~wrl`KeghiCt", - 0xadc6a7b9acd73c9b, "Zh}{}agHzfd@{", - 0x57135138eb08ff1c, "DnafGhj}l~sX", - 0x350bfacdf81b2018); + return inject_library_obf(process, dll, "E}mo|d[cefubWk~bgk", 0x7c3371986918e8f6, "Rqbr`T{cnor{Bnlgwz", + 0x81bf81adc9456b35, "]`~wrl`KeghiCt", 0xadc6a7b9acd73c9b, "Zh}{}agHzfd@{", + 0x57135138eb08ff1c, "DnafGhj}l~sX", 0x350bfacdf81b2018); } static inline int inject_library_safe(DWORD thread_id, const wchar_t *dll) { - return inject_library_safe_obf(thread_id, dll, "[bs^fbkmwuKfmfOvI", - 0xEAD293602FCF9778ULL); + return inject_library_safe_obf(thread_id, dll, "[bs^fbkmwuKfmfOvI", 0xEAD293602FCF9778ULL); } static inline int inject_library_full(DWORD process_id, const wchar_t *dll) @@ -93,8 +85,7 @@ static int inject_helper(wchar_t *argv[], const wchar_t *dll) return INJECT_ERROR_INVALID_PARAMS; } - return use_safe_inject ? inject_library_safe(id, dll) - : inject_library_full(id, dll); + return use_safe_inject ? inject_library_safe(id, dll) : inject_library_full(id, dll); } int main(void) diff --git a/plugins/win-capture/load-graphics-offsets.c b/plugins/win-capture/load-graphics-offsets.c index b713ea121..1e54f4ebc 100644 --- a/plugins/win-capture/load-graphics-offsets.c +++ b/plugins/win-capture/load-graphics-offsets.c @@ -11,8 +11,7 @@ extern struct graphics_offsets offsets32; extern struct graphics_offsets offsets64; -static inline bool load_offsets_from_string(struct graphics_offsets *offsets, - const char *str) +static inline bool load_offsets_from_string(struct graphics_offsets *offsets, const char *str) { config_t *config; @@ -20,35 +19,24 @@ static inline bool load_offsets_from_string(struct graphics_offsets *offsets, return false; } - offsets->d3d8.present = - (uint32_t)config_get_uint(config, "d3d8", "present"); + offsets->d3d8.present = (uint32_t)config_get_uint(config, "d3d8", "present"); - offsets->d3d9.present = - (uint32_t)config_get_uint(config, "d3d9", "present"); - offsets->d3d9.present_ex = - (uint32_t)config_get_uint(config, "d3d9", "present_ex"); - offsets->d3d9.present_swap = - (uint32_t)config_get_uint(config, "d3d9", "present_swap"); - offsets->d3d9.d3d9_clsoff = - (uint32_t)config_get_uint(config, "d3d9", "d3d9_clsoff"); - offsets->d3d9.is_d3d9ex_clsoff = - (uint32_t)config_get_uint(config, "d3d9", "is_d3d9ex_clsoff"); + offsets->d3d9.present = (uint32_t)config_get_uint(config, "d3d9", "present"); + offsets->d3d9.present_ex = (uint32_t)config_get_uint(config, "d3d9", "present_ex"); + offsets->d3d9.present_swap = (uint32_t)config_get_uint(config, "d3d9", "present_swap"); + offsets->d3d9.d3d9_clsoff = (uint32_t)config_get_uint(config, "d3d9", "d3d9_clsoff"); + offsets->d3d9.is_d3d9ex_clsoff = (uint32_t)config_get_uint(config, "d3d9", "is_d3d9ex_clsoff"); - offsets->dxgi.present = - (uint32_t)config_get_uint(config, "dxgi", "present"); - offsets->dxgi.present1 = - (uint32_t)config_get_uint(config, "dxgi", "present1"); - offsets->dxgi.resize = - (uint32_t)config_get_uint(config, "dxgi", "resize"); - offsets->dxgi2.release = - (uint32_t)config_get_uint(config, "dxgi", "release"); + offsets->dxgi.present = (uint32_t)config_get_uint(config, "dxgi", "present"); + offsets->dxgi.present1 = (uint32_t)config_get_uint(config, "dxgi", "present1"); + offsets->dxgi.resize = (uint32_t)config_get_uint(config, "dxgi", "resize"); + offsets->dxgi2.release = (uint32_t)config_get_uint(config, "dxgi", "release"); config_close(config); return true; } -static inline bool load_offsets_from_file(struct graphics_offsets *offsets, - const char *file) +static inline bool load_offsets_from_file(struct graphics_offsets *offsets, const char *file) { char *str = os_quick_read_utf8_file(file); bool success = false; @@ -58,9 +46,7 @@ static inline bool load_offsets_from_file(struct graphics_offsets *offsets, return success; } -static inline bool config_ver_mismatch(config_t *ver_config, - const char *section, - struct win_version_info *ver) +static inline bool config_ver_mismatch(config_t *ver_config, const char *section, struct win_version_info *ver) { struct win_version_info config_ver; bool mismatch = false; @@ -79,11 +65,9 @@ static inline bool config_ver_mismatch(config_t *ver_config, return mismatch; } -static inline void write_config_ver(config_t *ver_config, const char *section, - struct win_version_info *ver) +static inline void write_config_ver(config_t *ver_config, const char *section, struct win_version_info *ver) { -#define set_sub_ver(subver) \ - config_set_int(ver_config, section, #subver, ver->subver); +#define set_sub_ver(subver) config_set_int(ver_config, section, #subver, ver->subver); set_sub_ver(major); set_sub_ver(minor); @@ -93,8 +77,7 @@ static inline void write_config_ver(config_t *ver_config, const char *section, #undef set_sub_ver } -static bool get_32bit_system_dll_ver(const wchar_t *system_lib, - struct win_version_info *ver) +static bool get_32bit_system_dll_ver(const wchar_t *system_lib, struct win_version_info *ver) { wchar_t path[MAX_PATH]; UINT ret; @@ -156,8 +139,7 @@ failed: return !ver_mismatch; } -bool load_graphics_offsets(bool is32bit, bool use_hook_address_cache, - const char *config_path) +bool load_graphics_offsets(bool is32bit, bool use_hook_address_cache, const char *config_path) { char *offset_exe_path = NULL; struct dstr config_ini = {0}; @@ -184,14 +166,12 @@ bool load_graphics_offsets(bool is32bit, bool use_hook_address_cache, pp = os_process_pipe_create(cmd.array, "r"); if (!pp) { - blog(LOG_INFO, "load_graphics_offsets: Failed to start '%s'", - offset_exe.array); + blog(LOG_INFO, "load_graphics_offsets: Failed to start '%s'", offset_exe.array); goto error; } for (;;) { - size_t len = - os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); + size_t len = os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); if (!len) break; @@ -210,13 +190,11 @@ bool load_graphics_offsets(bool is32bit, bool use_hook_address_cache, dstr_copy(&config_ini, config_path); dstr_cat(&config_ini, is32bit ? "32.ini" : "64.ini"); - os_quick_write_utf8_file_safe(config_ini.array, str.array, - str.len, false, "tmp", NULL); + os_quick_write_utf8_file_safe(config_ini.array, str.array, str.len, false, "tmp", NULL); dstr_free(&config_ini); } - success = load_offsets_from_string(is32bit ? &offsets32 : &offsets64, - str.array); + success = load_offsets_from_string(is32bit ? &offsets32 : &offsets64, str.array); if (!success) { blog(LOG_INFO, "load_graphics_offsets: Failed to load string"); } @@ -237,8 +215,7 @@ bool load_cached_graphics_offsets(bool is32bit, const char *config_path) dstr_copy(&config_ini, config_path); dstr_cat(&config_ini, is32bit ? "32.ini" : "64.ini"); - success = load_offsets_from_file(is32bit ? &offsets32 : &offsets64, - config_ini.array); + success = load_offsets_from_file(is32bit ? &offsets32 : &offsets64, config_ini.array); if (!success) success = load_graphics_offsets(is32bit, true, config_path); diff --git a/plugins/win-capture/monitor-capture.c b/plugins/win-capture/monitor-capture.c index 0e12345fe..133b6fd72 100644 --- a/plugins/win-capture/monitor-capture.c +++ b/plugins/win-capture/monitor-capture.c @@ -45,8 +45,7 @@ static inline void do_log(int level, const char *msg, ...) va_end(args); } -static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, - LPARAM param) +static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) { struct monitor_info *monitor = (struct monitor_info *)param; @@ -60,8 +59,7 @@ static BOOL CALLBACK enum_monitor(HMONITOR handle, HDC hdc, LPRECT rect, return (monitor->desired_id > monitor->cur_id++); } -static void update_monitor(struct monitor_capture *capture, - obs_data_t *settings) +static void update_monitor(struct monitor_capture *capture, obs_data_t *settings) { struct monitor_info monitor = {0}; uint32_t width, height; @@ -74,13 +72,11 @@ static void update_monitor(struct monitor_capture *capture, width = monitor.rect.right - monitor.rect.left; height = monitor.rect.bottom - monitor.rect.top; - dc_capture_init(&capture->data, monitor.rect.left, monitor.rect.top, - width, height, capture->capture_cursor, + dc_capture_init(&capture->data, monitor.rect.left, monitor.rect.top, width, height, capture->capture_cursor, capture->compatibility); } -static inline void update_settings(struct monitor_capture *capture, - obs_data_t *settings) +static inline void update_settings(struct monitor_capture *capture, obs_data_t *settings) { capture->monitor = (int)obs_data_get_int(settings, "monitor"); capture->capture_cursor = obs_data_get_bool(settings, "capture_cursor"); @@ -151,8 +147,7 @@ static void monitor_capture_tick(void *data, float seconds) static void monitor_capture_render(void *data, gs_effect_t *effect) { struct monitor_capture *capture = data; - dc_capture_render(&capture->data, - obs_source_get_texcoords_centered(capture->source)); + dc_capture_render(&capture->data, obs_source_get_texcoords_centered(capture->source)); UNUSED_PARAMETER(effect); } @@ -169,8 +164,7 @@ static uint32_t monitor_capture_height(void *data) return capture->data.height; } -static BOOL CALLBACK enum_monitor_props(HMONITOR handle, HDC hdc, LPRECT rect, - LPARAM param) +static BOOL CALLBACK enum_monitor_props(HMONITOR handle, HDC hdc, LPRECT rect, LPARAM param) { UNUSED_PARAMETER(hdc); UNUSED_PARAMETER(rect); @@ -187,21 +181,17 @@ static BOOL CALLBACK enum_monitor_props(HMONITOR handle, HDC hdc, LPRECT rect, mi.cbSize = sizeof(mi); GetMonitorInfo(handle, &mi); - dstr_catf(&resolution, "%dx%d @ %d,%d", - mi.rcMonitor.right - mi.rcMonitor.left, - mi.rcMonitor.bottom - mi.rcMonitor.top, mi.rcMonitor.left, - mi.rcMonitor.top); + dstr_catf(&resolution, "%dx%d @ %d,%d", mi.rcMonitor.right - mi.rcMonitor.left, + mi.rcMonitor.bottom - mi.rcMonitor.top, mi.rcMonitor.left, mi.rcMonitor.top); dstr_copy(&format_string, "%s %d: %s"); if (mi.dwFlags == MONITORINFOF_PRIMARY) { dstr_catf(&format_string, " (%s)", TEXT_PRIMARY_MONITOR); } - dstr_catf(&monitor_desc, format_string.array, TEXT_MONITOR, - monitor_id + 1, resolution.array); + dstr_catf(&monitor_desc, format_string.array, TEXT_MONITOR, monitor_id + 1, resolution.array); - obs_property_list_add_int(monitor_list, monitor_desc.array, - (int)monitor_id); + obs_property_list_add_int(monitor_list, monitor_desc.array, (int)monitor_id); dstr_free(&monitor_desc); dstr_free(&resolution); @@ -216,9 +206,8 @@ static obs_properties_t *monitor_capture_properties(void *unused) obs_properties_t *props = obs_properties_create(); - obs_property_t *monitors = obs_properties_add_list( - props, "monitor", TEXT_MONITOR, OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_INT); + obs_property_t *monitors = + obs_properties_add_list(props, "monitor", TEXT_MONITOR, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_properties_add_bool(props, "compatibility", TEXT_COMPATIBILITY); obs_properties_add_bool(props, "capture_cursor", TEXT_CAPTURE_CURSOR); @@ -231,8 +220,7 @@ static obs_properties_t *monitor_capture_properties(void *unused) struct obs_source_info monitor_capture_info = { .id = "monitor_capture", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | - OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_SRGB, .get_name = monitor_capture_getname, .create = monitor_capture_create, .destroy = monitor_capture_destroy, diff --git a/plugins/win-capture/nt-stuff.c b/plugins/win-capture/nt-stuff.c index 03ec201ae..61d38b724 100644 --- a/plugins/win-capture/nt-stuff.c +++ b/plugins/win-capture/nt-stuff.c @@ -52,16 +52,12 @@ typedef struct _OBS_SYSTEM_THREAD_INFORMATION { (o)->SecurityQualityOfService = NULL; \ } while (false) -typedef void(WINAPI *RTLINITUNICODESTRINGFUNC)(PCUNICODE_STRING pstr, - const wchar_t *lpstrName); -typedef NTSTATUS(WINAPI *NTOPENFUNC)(PHANDLE phandle, ACCESS_MASK access, - POBJECT_ATTRIBUTES objattr); -typedef NTSTATUS(WINAPI *NTCREATEMUTANT)(PHANDLE phandle, ACCESS_MASK access, - POBJECT_ATTRIBUTES objattr, +typedef void(WINAPI *RTLINITUNICODESTRINGFUNC)(PCUNICODE_STRING pstr, const wchar_t *lpstrName); +typedef NTSTATUS(WINAPI *NTOPENFUNC)(PHANDLE phandle, ACCESS_MASK access, POBJECT_ATTRIBUTES objattr); +typedef NTSTATUS(WINAPI *NTCREATEMUTANT)(PHANDLE phandle, ACCESS_MASK access, POBJECT_ATTRIBUTES objattr, BOOLEAN isowner); typedef ULONG(WINAPI *RTLNTSTATUSTODOSERRORFUNC)(NTSTATUS status); -typedef NTSTATUS(WINAPI *NTQUERYSYSTEMINFORMATIONFUNC)(SYSTEM_INFORMATION_CLASS, - PVOID, ULONG, PULONG); +typedef NTSTATUS(WINAPI *NTQUERYSYSTEMINFORMATIONFUNC)(SYSTEM_INFORMATION_CLASS, PVOID, ULONG, PULONG); FARPROC get_nt_func(const char *name) { @@ -81,8 +77,7 @@ void nt_set_last_error(NTSTATUS status) static RTLNTSTATUSTODOSERRORFUNC func = NULL; if (!initialized) { - func = (RTLNTSTATUSTODOSERRORFUNC)get_nt_func( - "RtlNtStatusToDosError"); + func = (RTLNTSTATUSTODOSERRORFUNC)get_nt_func("RtlNtStatusToDosError"); initialized = true; } @@ -96,8 +91,7 @@ void rtl_init_str(UNICODE_STRING *unistr, const wchar_t *str) static RTLINITUNICODESTRINGFUNC func = NULL; if (!initialized) { - func = (RTLINITUNICODESTRINGFUNC)get_nt_func( - "RtlInitUnicodeString"); + func = (RTLINITUNICODESTRINGFUNC)get_nt_func("RtlInitUnicodeString"); initialized = true; } @@ -137,15 +131,13 @@ MAKE_NT_OPEN_FUNC(nt_open_mutex, NtOpenMutant, SYNCHRONIZE) MAKE_NT_OPEN_FUNC(nt_open_event, NtOpenEvent, EVENT_MODIFY_STATE | SYNCHRONIZE) MAKE_NT_OPEN_FUNC(nt_open_map, NtOpenSection, FILE_MAP_READ | FILE_MAP_WRITE) -NTSTATUS nt_query_information(SYSTEM_INFORMATION_CLASS info_class, PVOID info, - ULONG info_len, PULONG ret_len) +NTSTATUS nt_query_information(SYSTEM_INFORMATION_CLASS info_class, PVOID info, ULONG info_len, PULONG ret_len) { static bool initialized = false; static NTQUERYSYSTEMINFORMATIONFUNC func = NULL; if (!initialized) { - func = (NTQUERYSYSTEMINFORMATIONFUNC)get_nt_func( - "NtQuerySystemInformation"); + func = (NTQUERYSYSTEMINFORMATIONFUNC)get_nt_func("NtQuerySystemInformation"); initialized = true; } @@ -163,8 +155,7 @@ bool thread_is_suspended(DWORD process_id, DWORD thread_id) return false; for (;;) { - NTSTATUS stat = nt_query_information(SystemProcessInformation, - data, size, &size); + NTSTATUS stat = nt_query_information(SystemProcessInformation, data, size, &size); if (NT_SUCCESS(stat)) break; diff --git a/plugins/win-capture/plugin-main.c b/plugins/win-capture/plugin-main.c index d379a1413..98a38efc4 100644 --- a/plugins/win-capture/plugin-main.c +++ b/plugins/win-capture/plugin-main.c @@ -32,8 +32,7 @@ static update_info_t *update_info = NULL; extern bool cached_versions_match(void); extern bool load_cached_graphics_offsets(bool is32bit, const char *config_path); -extern bool load_graphics_offsets(bool is32bit, bool use_hook_address_cache, - const char *config_path); +extern bool load_graphics_offsets(bool is32bit, bool use_hook_address_cache, const char *config_path); /* temporary, will eventually be erased once we figure out how to create both * 32bit and 64bit versions of the helpers/hook */ @@ -49,16 +48,13 @@ static DWORD WINAPI init_hooks(LPVOID param) { char *config_path = param; - if (use_hook_address_cache && cached_versions_match() && - load_cached_graphics_offsets(IS32BIT, config_path)) { + if (use_hook_address_cache && cached_versions_match() && load_cached_graphics_offsets(IS32BIT, config_path)) { load_cached_graphics_offsets(!IS32BIT, config_path); obs_register_source(&game_capture_info); - } else if (load_graphics_offsets(IS32BIT, use_hook_address_cache, - config_path)) { - load_graphics_offsets(!IS32BIT, use_hook_address_cache, - config_path); + } else if (load_graphics_offsets(IS32BIT, use_hook_address_cache, config_path)) { + load_graphics_offsets(!IS32BIT, use_hook_address_cache, config_path); } bfree(config_path); @@ -113,13 +109,9 @@ bool obs_module_load(void) char *config_dir; char update_url[128]; - snprintf(update_url, sizeof(update_url), "%s/v%d", COMPAT_URL, - COMPAT_FORMAT_VERSION); + snprintf(update_url, sizeof(update_url), "%s/v%d", COMPAT_URL, COMPAT_FORMAT_VERSION); - struct win_version_info win1903 = {.major = 10, - .minor = 0, - .build = 18362, - .revis = 0}; + struct win_version_info win1903 = {.major = 10, .minor = 0, .build = 18362, .revis = 0}; local_dir = obs_module_file(NULL); config_dir = obs_module_config_path(NULL); @@ -127,10 +119,8 @@ bool obs_module_load(void) os_mkdirs(config_dir); if (local_dir) { - update_info = update_info_create( - WIN_CAPTURE_LOG_STRING, WIN_CAPTURE_VER_STRING, - update_url, local_dir, config_dir, - confirm_compat_file, NULL); + update_info = update_info_create(WIN_CAPTURE_LOG_STRING, WIN_CAPTURE_VER_STRING, update_url, + local_dir, config_dir, confirm_compat_file, NULL); } } bfree(config_dir); @@ -157,8 +147,7 @@ bool obs_module_load(void) char *config_path = obs_module_config_path(NULL); init_hook_files(); - init_hooks_thread = - CreateThread(NULL, 0, init_hooks, config_path, 0, NULL); + init_hooks_thread = CreateThread(NULL, 0, init_hooks, config_path, 0, NULL); obs_register_source(&game_capture_info); return true; diff --git a/plugins/win-capture/window-capture.c b/plugins/win-capture/window-capture.c index 0c49e8b56..472c59533 100644 --- a/plugins/win-capture/window-capture.c +++ b/plugins/win-capture/window-capture.c @@ -39,26 +39,20 @@ typedef BOOL (*PFN_winrt_capture_supported)(); typedef BOOL (*PFN_winrt_capture_cursor_toggle_supported)(); -typedef struct winrt_capture *(*PFN_winrt_capture_init_window)(BOOL cursor, - HWND window, - BOOL client_area, +typedef struct winrt_capture *(*PFN_winrt_capture_init_window)(BOOL cursor, HWND window, BOOL client_area, BOOL force_sdr); typedef void (*PFN_winrt_capture_free)(struct winrt_capture *capture); typedef BOOL (*PFN_winrt_capture_active)(const struct winrt_capture *capture); -typedef BOOL (*PFN_winrt_capture_show_cursor)(struct winrt_capture *capture, - BOOL visible); -typedef enum gs_color_space (*PFN_winrt_capture_get_color_space)( - const struct winrt_capture *capture); +typedef BOOL (*PFN_winrt_capture_show_cursor)(struct winrt_capture *capture, BOOL visible); +typedef enum gs_color_space (*PFN_winrt_capture_get_color_space)(const struct winrt_capture *capture); typedef void (*PFN_winrt_capture_render)(struct winrt_capture *capture); typedef uint32_t (*PFN_winrt_capture_width)(const struct winrt_capture *capture); -typedef uint32_t (*PFN_winrt_capture_height)( - const struct winrt_capture *capture); +typedef uint32_t (*PFN_winrt_capture_height)(const struct winrt_capture *capture); struct winrt_exports { PFN_winrt_capture_supported winrt_capture_supported; - PFN_winrt_capture_cursor_toggle_supported - winrt_capture_cursor_toggle_supported; + PFN_winrt_capture_cursor_toggle_supported winrt_capture_cursor_toggle_supported; PFN_winrt_capture_init_window winrt_capture_init_window; PFN_winrt_capture_free winrt_capture_free; PFN_winrt_capture_active winrt_capture_active; @@ -75,8 +69,7 @@ enum window_capture_method { METHOD_WGC, }; -typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_SetThreadDpiAwarenessContext)( - DPI_AWARENESS_CONTEXT); +typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_SetThreadDpiAwarenessContext)(DPI_AWARENESS_CONTEXT); typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_GetThreadDpiAwarenessContext)(VOID); typedef DPI_AWARENESS_CONTEXT(WINAPI *PFN_GetWindowDpiAwarenessContext)(HWND); @@ -142,9 +135,8 @@ static const char *wgc_whole_match_classes[] = { NULL, }; -static enum window_capture_method -choose_method(enum window_capture_method method, bool wgc_supported, - const char *current_class) +static enum window_capture_method choose_method(enum window_capture_method method, bool wgc_supported, + const char *current_class) { if (!wgc_supported) return METHOD_BITBLT; @@ -203,10 +195,8 @@ static void log_settings(struct window_capture *wc, obs_data_t *s) "\tmethod selected: %s\n" "\tmethod chosen: %s\n" "\tforce SDR: %s", - obs_source_get_name(wc->source), wc->executable, - get_method_name(method), get_method_name(wc->method), - (wc->force_sdr && (wc->method == METHOD_WGC)) ? "true" - : "false"); + obs_source_get_name(wc->source), wc->executable, get_method_name(method), + get_method_name(wc->method), (wc->force_sdr && (wc->method == METHOD_WGC)) ? "true" : "false"); blog(LOG_DEBUG, "\tclass: %s", wc->class); } } @@ -225,8 +215,7 @@ static void update_settings(struct window_capture *wc, obs_data_t *s) bfree(wc->class); bfree(wc->executable); - ms_build_window_strings(window, &wc->class, &wc->title, - &wc->executable); + ms_build_window_strings(window, &wc->class, &wc->title, &wc->executable); wc->method = choose_method(method, wgc_supported, wc->class); wc->priority = (enum window_priority)priority; @@ -236,8 +225,7 @@ static void update_settings(struct window_capture *wc, obs_data_t *s) wc->compatibility = obs_data_get_bool(s, "compatibility"); wc->client_area = obs_data_get_bool(s, "client_area"); - setup_audio_source(wc->source, &wc->audio_source, window, - wc->capture_audio, wc->priority); + setup_audio_source(wc->source, &wc->audio_source, window, wc->capture_audio, wc->priority); pthread_mutex_unlock(&wc->update_mutex); } @@ -290,8 +278,7 @@ static const char *wc_getname(void *unused) } \ } while (false) -static bool load_winrt_imports(struct winrt_exports *exports, void *module, - const char *module_name) +static bool load_winrt_imports(struct winrt_exports *exports, void *module, const char *module_name) { bool success = true; @@ -322,55 +309,37 @@ static void *wc_create(obs_data_t *settings, obs_source_t *source) static const char *const module = "libobs-winrt"; wc->winrt_module = os_dlopen(module); if (wc->winrt_module) { - load_winrt_imports(&wc->exports, wc->winrt_module, - module); + load_winrt_imports(&wc->exports, wc->winrt_module, module); } } const HMODULE hModuleUser32 = GetModuleHandle(L"User32.dll"); if (hModuleUser32) { - PFN_SetThreadDpiAwarenessContext - set_thread_dpi_awareness_context = - (PFN_SetThreadDpiAwarenessContext)GetProcAddress( - hModuleUser32, - "SetThreadDpiAwarenessContext"); - PFN_GetThreadDpiAwarenessContext - get_thread_dpi_awareness_context = - (PFN_GetThreadDpiAwarenessContext)GetProcAddress( - hModuleUser32, - "GetThreadDpiAwarenessContext"); - PFN_GetWindowDpiAwarenessContext - get_window_dpi_awareness_context = - (PFN_GetWindowDpiAwarenessContext)GetProcAddress( - hModuleUser32, - "GetWindowDpiAwarenessContext"); - if (set_thread_dpi_awareness_context && - get_thread_dpi_awareness_context && + PFN_SetThreadDpiAwarenessContext set_thread_dpi_awareness_context = + (PFN_SetThreadDpiAwarenessContext)GetProcAddress(hModuleUser32, "SetThreadDpiAwarenessContext"); + PFN_GetThreadDpiAwarenessContext get_thread_dpi_awareness_context = + (PFN_GetThreadDpiAwarenessContext)GetProcAddress(hModuleUser32, "GetThreadDpiAwarenessContext"); + PFN_GetWindowDpiAwarenessContext get_window_dpi_awareness_context = + (PFN_GetWindowDpiAwarenessContext)GetProcAddress(hModuleUser32, "GetWindowDpiAwarenessContext"); + if (set_thread_dpi_awareness_context && get_thread_dpi_awareness_context && get_window_dpi_awareness_context) { - wc->set_thread_dpi_awareness_context = - set_thread_dpi_awareness_context; - wc->get_thread_dpi_awareness_context = - get_thread_dpi_awareness_context; - wc->get_window_dpi_awareness_context = - get_window_dpi_awareness_context; + wc->set_thread_dpi_awareness_context = set_thread_dpi_awareness_context; + wc->get_thread_dpi_awareness_context = get_thread_dpi_awareness_context; + wc->get_window_dpi_awareness_context = get_window_dpi_awareness_context; } } wc->hooked = false; signal_handler_t *sh = obs_source_get_signal_handler(source); signal_handler_add(sh, "void unhooked(ptr source)"); - signal_handler_add( - sh, - "void hooked(ptr source, string title, string class, string executable)"); + signal_handler_add(sh, "void hooked(ptr source, string title, string class, string executable)"); proc_handler_t *ph = obs_source_get_proc_handler(source); - proc_handler_add( - ph, - "void get_hooked(out bool hooked, out string title, out string class, out string executable)", - wc_get_hooked, wc); + proc_handler_add(ph, + "void get_hooked(out bool hooked, out string title, out string class, out string executable)", + wc_get_hooked, wc); - signal_handler_connect(sh, "rename", rename_audio_source, - &wc->audio_source); + signal_handler_connect(sh, "rename", rename_audio_source, &wc->audio_source); update_settings(wc, settings); log_settings(wc, settings); @@ -408,8 +377,7 @@ static void wc_destroy(void *data) destroy_audio_source(wc->source, &wc->audio_source); signal_handler_t *sh = obs_source_get_signal_handler(wc->source); - signal_handler_disconnect(sh, "rename", rename_audio_source, - &wc->audio_source); + signal_handler_disconnect(sh, "rename", rename_audio_source, &wc->audio_source); obs_queue_task(OBS_TASK_GRAPHICS, wc_actual_destroy, wc, false); } @@ -445,9 +413,7 @@ static uint32_t wc_width(void *data) if (!window_normal(wc)) return 0; - return (wc->method == METHOD_WGC) - ? wc->exports.winrt_capture_width(wc->capture_winrt) - : wc->capture.width; + return (wc->method == METHOD_WGC) ? wc->exports.winrt_capture_width(wc->capture_winrt) : wc->capture.width; } static uint32_t wc_height(void *data) @@ -457,9 +423,7 @@ static uint32_t wc_height(void *data) if (!window_normal(wc)) return 0; - return (wc->method == METHOD_WGC) - ? wc->exports.winrt_capture_height(wc->capture_winrt) - : wc->capture.height; + return (wc->method == METHOD_WGC) ? wc->exports.winrt_capture_height(wc->capture_winrt) : wc->capture.height; } static void wc_defaults(obs_data_t *defaults) @@ -471,8 +435,7 @@ static void wc_defaults(obs_data_t *defaults) obs_data_set_default_bool(defaults, "client_area", true); } -static void update_settings_visibility(obs_properties_t *props, - struct window_capture *wc) +static void update_settings_visibility(obs_properties_t *props, struct window_capture *wc) { pthread_mutex_lock(&wc->update_mutex); @@ -480,9 +443,7 @@ static void update_settings_visibility(obs_properties_t *props, const bool bitblt_options = method == METHOD_BITBLT; const bool wgc_options = method == METHOD_WGC; - const bool wgc_cursor_toggle = - wgc_options && - wc->exports.winrt_capture_cursor_toggle_supported(); + const bool wgc_cursor_toggle = wgc_options && wc->exports.winrt_capture_cursor_toggle_supported(); obs_property_t *p = obs_properties_get(props, "cursor"); obs_property_set_visible(p, bitblt_options || wgc_cursor_toggle); @@ -499,14 +460,12 @@ static void update_settings_visibility(obs_properties_t *props, pthread_mutex_unlock(&wc->update_mutex); } -static void wc_check_compatibility(struct window_capture *wc, - obs_properties_t *props) +static void wc_check_compatibility(struct window_capture *wc, obs_properties_t *props) { obs_property_t *p_warn = obs_properties_get(props, "compat_info"); struct compat_result *compat = - check_compatibility(wc->title, wc->class, wc->executable, - (enum source_type)wc->method); + check_compatibility(wc->title, wc->class, wc->executable, (enum source_type)wc->method); if (!compat) { obs_property_set_visible(p_warn, false); return; @@ -519,8 +478,7 @@ static void wc_check_compatibility(struct window_capture *wc, compat_result_free(compat); } -static bool wc_capture_method_changed(obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) +static bool wc_capture_method_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); @@ -537,8 +495,7 @@ static bool wc_capture_method_changed(obs_properties_t *props, return true; } -static bool wc_window_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool wc_window_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { struct window_capture *wc = obs_properties_get_param(props); if (!wc) @@ -564,31 +521,26 @@ static obs_properties_t *wc_properties(void *data) obs_property_t *p; - p = obs_properties_add_list(ppts, "window", TEXT_WINDOW, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, "window", TEXT_WINDOW, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); /* Add "[Select a window]" on first use to prevent the properties list * widget from selecting the first one in the list automatically */ if (wc && (!wc->title || !wc->class || !wc->executable)) { - obs_property_list_add_string( - p, obs_module_text("SelectAWindow"), ""); + obs_property_list_add_string(p, obs_module_text("SelectAWindow"), ""); obs_property_list_item_disable(p, 0, true); } ms_fill_window_list(p, EXCLUDE_MINIMIZED, NULL); obs_property_set_modified_callback(p, wc_window_changed); - p = obs_properties_add_list(ppts, "method", TEXT_METHOD, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(ppts, "method", TEXT_METHOD, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(p, TEXT_METHOD_AUTO, METHOD_AUTO); obs_property_list_add_int(p, TEXT_METHOD_BITBLT, METHOD_BITBLT); obs_property_list_add_int(p, TEXT_METHOD_WGC, METHOD_WGC); obs_property_list_item_disable(p, 2, !wgc_supported); obs_property_set_modified_callback(p, wc_capture_method_changed); - p = obs_properties_add_list(ppts, "priority", TEXT_MATCH_PRIORITY, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(ppts, "priority", TEXT_MATCH_PRIORITY, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_list_add_int(p, TEXT_MATCH_TITLE, WINDOW_PRIORITY_TITLE); obs_property_list_add_int(p, TEXT_MATCH_CLASS, WINDOW_PRIORITY_CLASS); obs_property_list_add_int(p, TEXT_MATCH_EXE, WINDOW_PRIORITY_EXE); @@ -597,8 +549,7 @@ static obs_properties_t *wc_properties(void *data) obs_property_set_enabled(p, false); if (audio_capture_available()) { - p = obs_properties_add_bool(ppts, "capture_audio", - TEXT_CAPTURE_AUDIO); + p = obs_properties_add_bool(ppts, "capture_audio", TEXT_CAPTURE_AUDIO); obs_property_set_long_description(p, TEXT_CAPTURE_AUDIO_TT); } @@ -627,8 +578,7 @@ static void wc_hide(void *data) if (wc->hooked) { wc->hooked = false; - signal_handler_t *sh = - obs_source_get_signal_handler(wc->source); + signal_handler_t *sh = obs_source_get_signal_handler(wc->source); calldata_t data = {0}; calldata_set_ptr(&data, "source", wc->source); signal_handler_signal(sh, "unhooked", &data); @@ -649,8 +599,7 @@ static void wc_tick(void *data, float seconds) if (wc->hooked) { wc->hooked = false; - signal_handler_t *sh = - obs_source_get_signal_handler(wc->source); + signal_handler_t *sh = obs_source_get_signal_handler(wc->source); calldata_t data = {0}; calldata_set_ptr(&data, "source", wc->source); signal_handler_signal(sh, "unhooked", &data); @@ -678,15 +627,10 @@ static void wc_tick(void *data, float seconds) wc->check_window_timer = 0.0f; - wc->window = - (wc->method == METHOD_WGC) - ? ms_find_window_top_level(INCLUDE_MINIMIZED, - wc->priority, - wc->class, wc->title, - wc->executable) - : ms_find_window(INCLUDE_MINIMIZED, - wc->priority, wc->class, - wc->title, wc->executable); + wc->window = (wc->method == METHOD_WGC) ? ms_find_window_top_level(INCLUDE_MINIMIZED, wc->priority, + wc->class, wc->title, wc->executable) + : ms_find_window(INCLUDE_MINIMIZED, wc->priority, wc->class, + wc->title, wc->executable); if (!wc->window) { if (wc->capture.valid) dc_capture_free(&wc->capture); @@ -705,26 +649,20 @@ static void wc_tick(void *data, float seconds) DWORD foreground_pid, target_pid; // Can't just compare the window handle in case of app with child windows - if (!GetWindowThreadProcessId(GetForegroundWindow(), - &foreground_pid)) + if (!GetWindowThreadProcessId(GetForegroundWindow(), &foreground_pid)) foreground_pid = 0; if (!GetWindowThreadProcessId(wc->window, &target_pid)) target_pid = 0; - const bool cursor_hidden = foreground_pid && target_pid && - foreground_pid != target_pid; + const bool cursor_hidden = foreground_pid && target_pid && foreground_pid != target_pid; wc->capture.cursor_hidden = cursor_hidden; - if (wc->capture_winrt && - !wc->exports.winrt_capture_show_cursor(wc->capture_winrt, - !cursor_hidden)) { + if (wc->capture_winrt && !wc->exports.winrt_capture_show_cursor(wc->capture_winrt, !cursor_hidden)) { force_reset(wc); if (wc->hooked) { wc->hooked = false; - signal_handler_t *sh = - obs_source_get_signal_handler( - wc->source); + signal_handler_t *sh = obs_source_get_signal_handler(wc->source); calldata_t data = {0}; calldata_set_ptr(&data, "source", wc->source); signal_handler_signal(sh, "unhooked", &data); @@ -741,11 +679,8 @@ static void wc_tick(void *data, float seconds) if (wc->method == METHOD_BITBLT) { DPI_AWARENESS_CONTEXT previous = NULL; if (wc->get_window_dpi_awareness_context != NULL) { - const DPI_AWARENESS_CONTEXT context = - wc->get_window_dpi_awareness_context( - wc->window); - previous = - wc->set_thread_dpi_awareness_context(context); + const DPI_AWARENESS_CONTEXT context = wc->get_window_dpi_awareness_context(wc->window); + previous = wc->set_thread_dpi_awareness_context(context); } GetClientRect(wc->window, &rect); @@ -754,12 +689,8 @@ static void wc_tick(void *data, float seconds) wc->resize_timer += seconds; if (wc->resize_timer >= RESIZE_CHECK_TIME) { - if ((rect.bottom - rect.top) != - (wc->last_rect.bottom - - wc->last_rect.top) || - (rect.right - rect.left) != - (wc->last_rect.right - - wc->last_rect.left)) + if ((rect.bottom - rect.top) != (wc->last_rect.bottom - wc->last_rect.top) || + (rect.right - rect.left) != (wc->last_rect.right - wc->last_rect.left)) reset_capture = true; wc->resize_timer = 0.0f; @@ -770,16 +701,12 @@ static void wc_tick(void *data, float seconds) wc->resize_timer = 0.0f; wc->last_rect = rect; dc_capture_free(&wc->capture); - dc_capture_init(&wc->capture, 0, 0, - rect.right - rect.left, - rect.bottom - rect.top, wc->cursor, + dc_capture_init(&wc->capture, 0, 0, rect.right - rect.left, rect.bottom - rect.top, wc->cursor, wc->compatibility); if (!wc->hooked && wc->capture.valid) { wc->hooked = true; - signal_handler_t *sh = - obs_source_get_signal_handler( - wc->source); + signal_handler_t *sh = obs_source_get_signal_handler(wc->source); calldata_t data = {0}; struct dstr title = {0}; struct dstr class = {0}; @@ -790,12 +717,9 @@ static void wc_tick(void *data, float seconds) ms_get_window_exe(&executable, wc->window); calldata_set_ptr(&data, "source", wc->source); - calldata_set_string(&data, "title", - title.array); - calldata_set_string(&data, "class", - class.array); - calldata_set_string(&data, "executable", - executable.array); + calldata_set_string(&data, "title", title.array); + calldata_set_string(&data, "class", class.array); + calldata_set_string(&data, "executable", executable.array); signal_handler_signal(sh, "hooked", &data); dstr_free(&title); @@ -812,19 +736,15 @@ static void wc_tick(void *data, float seconds) } else if (wc->method == METHOD_WGC) { if (wc->window && (wc->capture_winrt == NULL)) { if (!wc->previously_failed) { - wc->capture_winrt = - wc->exports.winrt_capture_init_window( - wc->cursor, wc->window, - wc->client_area, wc->force_sdr); + wc->capture_winrt = wc->exports.winrt_capture_init_window( + wc->cursor, wc->window, wc->client_area, wc->force_sdr); if (!wc->capture_winrt) { wc->previously_failed = true; } else if (!wc->hooked) { wc->hooked = true; - signal_handler_t *sh = - obs_source_get_signal_handler( - wc->source); + signal_handler_t *sh = obs_source_get_signal_handler(wc->source); calldata_t data = {0}; struct dstr title = {0}; struct dstr class = {0}; @@ -832,19 +752,13 @@ static void wc_tick(void *data, float seconds) ms_get_window_title(&title, wc->window); ms_get_window_class(&class, wc->window); - ms_get_window_exe(&executable, - wc->window); + ms_get_window_exe(&executable, wc->window); - calldata_set_ptr(&data, "source", - wc->source); - calldata_set_string(&data, "title", - title.array); - calldata_set_string(&data, "class", - class.array); - calldata_set_string(&data, "executable", - executable.array); - signal_handler_signal(sh, "hooked", - &data); + calldata_set_ptr(&data, "source", wc->source); + calldata_set_string(&data, "title", title.array); + calldata_set_string(&data, "class", class.array); + calldata_set_string(&data, "executable", executable.array); + signal_handler_signal(sh, "hooked", &data); dstr_free(&title); dstr_free(&class); @@ -867,36 +781,28 @@ static void wc_render(void *data, gs_effect_t *effect) if (wc->method == METHOD_WGC) { if (wc->capture_winrt) { - if (wc->exports.winrt_capture_active( - wc->capture_winrt)) { - wc->exports.winrt_capture_render( - wc->capture_winrt); + if (wc->exports.winrt_capture_active(wc->capture_winrt)) { + wc->exports.winrt_capture_render(wc->capture_winrt); } else { - wc->exports.winrt_capture_free( - wc->capture_winrt); + wc->exports.winrt_capture_free(wc->capture_winrt); wc->capture_winrt = NULL; } } } else { - dc_capture_render( - &wc->capture, - obs_source_get_texcoords_centered(wc->source)); + dc_capture_render(&wc->capture, obs_source_get_texcoords_centered(wc->source)); } UNUSED_PARAMETER(effect); } -enum gs_color_space -wc_get_color_space(void *data, size_t count, - const enum gs_color_space *preferred_spaces) +enum gs_color_space wc_get_color_space(void *data, size_t count, const enum gs_color_space *preferred_spaces) { struct window_capture *wc = data; enum gs_color_space capture_space = GS_CS_SRGB; if ((wc->method == METHOD_WGC) && wc->capture_winrt) { - capture_space = wc->exports.winrt_capture_get_color_space( - wc->capture_winrt); + capture_space = wc->exports.winrt_capture_get_color_space(wc->capture_winrt); } enum gs_color_space space = capture_space; @@ -920,8 +826,7 @@ static void wc_child_enum(void *data, obs_source_enum_proc_t cb, void *param) struct obs_source_info window_capture_info = { .id = "window_capture", .type = OBS_SOURCE_TYPE_INPUT, - .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_SRGB, + .output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_CUSTOM_DRAW | OBS_SOURCE_SRGB, .get_name = wc_getname, .create = wc_create, .destroy = wc_destroy, diff --git a/plugins/win-dshow/encode-dstr.hpp b/plugins/win-dshow/encode-dstr.hpp index 9115f6d9b..4f2f5b167 100644 --- a/plugins/win-dshow/encode-dstr.hpp +++ b/plugins/win-dshow/encode-dstr.hpp @@ -14,9 +14,7 @@ static inline void decode_dstr(struct dstr *str) dstr_replace(str, "#22", "#"); } -static inline void EncodeDeviceId(struct dstr *encodedStr, - const wchar_t *name_str, - const wchar_t *path_str) +static inline void EncodeDeviceId(struct dstr *encodedStr, const wchar_t *name_str, const wchar_t *path_str) { DStr name; DStr path; @@ -32,8 +30,7 @@ static inline void EncodeDeviceId(struct dstr *encodedStr, dstr_cat_dstr(encodedStr, path); } -static inline bool DecodeDeviceDStr(DStr &name, DStr &path, - const char *device_id) +static inline bool DecodeDeviceDStr(DStr &name, DStr &path, const char *device_id) { const char *path_str; diff --git a/plugins/win-dshow/ffmpeg-decode.c b/plugins/win-dshow/ffmpeg-decode.c index 9cd611866..339b347ec 100644 --- a/plugins/win-dshow/ffmpeg-decode.c +++ b/plugins/win-dshow/ffmpeg-decode.c @@ -37,8 +37,7 @@ static bool has_hw_type(const AVCodec *c, enum AVHWDeviceType type) break; } - if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && - config->device_type == type) + if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == type) return true; } @@ -52,8 +51,7 @@ static void init_hw_decoder(struct ffmpeg_decode *d) while (*priority != AV_HWDEVICE_TYPE_NONE) { if (has_hw_type(d->codec, *priority)) { - int ret = av_hwdevice_ctx_create(&hw_ctx, *priority, - NULL, NULL, 0); + int ret = av_hwdevice_ctx_create(&hw_ctx, *priority, NULL, NULL, 0); if (ret == 0) break; } @@ -68,8 +66,7 @@ static void init_hw_decoder(struct ffmpeg_decode *d) } } -int ffmpeg_decode_init(struct ffmpeg_decode *decode, enum AVCodecID id, - bool use_hw) +int ffmpeg_decode_init(struct ffmpeg_decode *decode, enum AVCodecID id, bool use_hw) { int ret; @@ -201,14 +198,12 @@ static inline enum speaker_layout convert_speaker_layout(uint8_t channels) } } -static inline void copy_data(struct ffmpeg_decode *decode, uint8_t *data, - size_t size) +static inline void copy_data(struct ffmpeg_decode *decode, uint8_t *data, size_t size) { size_t new_size = size + INPUT_BUFFER_PADDING_SIZE; if (decode->packet_size < new_size) { - decode->packet_buffer = - brealloc(decode->packet_buffer, new_size); + decode->packet_buffer = brealloc(decode->packet_buffer, new_size); decode->packet_size = new_size; } @@ -216,8 +211,7 @@ static inline void copy_data(struct ffmpeg_decode *decode, uint8_t *data, memcpy(decode->packet_buffer, data, size); } -bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data, - size_t size, struct obs_source_audio *audio, +bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data, size_t size, struct obs_source_audio *audio, bool *got_output) { int got_frame = false; @@ -260,8 +254,7 @@ bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data, audio->samples_per_sec = decode->frame->sample_rate; audio->format = convert_sample_format(decode->frame->format); - audio->speakers = convert_speaker_layout( - (uint8_t)decode->decoder->ch_layout.nb_channels); + audio->speakers = convert_speaker_layout((uint8_t)decode->decoder->ch_layout.nb_channels); audio->frames = decode->frame->nb_samples; @@ -272,35 +265,29 @@ bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data, return true; } -static enum video_colorspace -convert_color_space(enum AVColorSpace s, enum AVColorTransferCharacteristic trc, - enum AVColorPrimaries color_primaries) +static enum video_colorspace convert_color_space(enum AVColorSpace s, enum AVColorTransferCharacteristic trc, + enum AVColorPrimaries color_primaries) { switch (s) { case AVCOL_SPC_BT709: - return (trc == AVCOL_TRC_IEC61966_2_1) ? VIDEO_CS_SRGB - : VIDEO_CS_709; + return (trc == AVCOL_TRC_IEC61966_2_1) ? VIDEO_CS_SRGB : VIDEO_CS_709; case AVCOL_SPC_FCC: case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: case AVCOL_SPC_SMPTE240M: return VIDEO_CS_601; case AVCOL_SPC_BT2020_NCL: - return (trc == AVCOL_TRC_ARIB_STD_B67) ? VIDEO_CS_2100_HLG - : VIDEO_CS_2100_PQ; + return (trc == AVCOL_TRC_ARIB_STD_B67) ? VIDEO_CS_2100_HLG : VIDEO_CS_2100_PQ; default: return (color_primaries == AVCOL_PRI_BT2020) - ? ((trc == AVCOL_TRC_ARIB_STD_B67) - ? VIDEO_CS_2100_HLG - : VIDEO_CS_2100_PQ) + ? ((trc == AVCOL_TRC_ARIB_STD_B67) ? VIDEO_CS_2100_HLG : VIDEO_CS_2100_PQ) : VIDEO_CS_DEFAULT; } } -bool ffmpeg_decode_video(struct ffmpeg_decode *decode, uint8_t *data, - size_t size, long long *ts, enum video_colorspace cs, - enum video_range_type range, - struct obs_source_frame2 *frame, bool *got_output) +bool ffmpeg_decode_video(struct ffmpeg_decode *decode, uint8_t *data, size_t size, long long *ts, + enum video_colorspace cs, enum video_range_type range, struct obs_source_frame2 *frame, + bool *got_output) { int got_frame = false; AVFrame *out_frame; @@ -370,25 +357,20 @@ bool ffmpeg_decode_video(struct ffmpeg_decode *decode, uint8_t *data, frame->linesize[i] = decode->frame->linesize[i]; } - const enum video_format format = - convert_pixel_format(decode->frame->format); + const enum video_format format = convert_pixel_format(decode->frame->format); frame->format = format; if (range == VIDEO_RANGE_DEFAULT) { - range = (decode->frame->color_range == AVCOL_RANGE_JPEG) - ? VIDEO_RANGE_FULL - : VIDEO_RANGE_PARTIAL; + range = (decode->frame->color_range == AVCOL_RANGE_JPEG) ? VIDEO_RANGE_FULL : VIDEO_RANGE_PARTIAL; } if (cs == VIDEO_CS_DEFAULT) { - cs = convert_color_space(decode->frame->colorspace, - decode->frame->color_trc, + cs = convert_color_space(decode->frame->colorspace, decode->frame->color_trc, decode->frame->color_primaries); } - const bool success = video_format_get_parameters_for_format( - cs, range, format, frame->color_matrix, frame->color_range_min, - frame->color_range_max); + const bool success = video_format_get_parameters_for_format(cs, range, format, frame->color_matrix, + frame->color_range_min, frame->color_range_max); if (!success) { blog(LOG_ERROR, "Failed to get video format " diff --git a/plugins/win-dshow/ffmpeg-decode.h b/plugins/win-dshow/ffmpeg-decode.h index f67bbd28a..bda972cb6 100644 --- a/plugins/win-dshow/ffmpeg-decode.h +++ b/plugins/win-dshow/ffmpeg-decode.h @@ -49,19 +49,14 @@ struct ffmpeg_decode { size_t packet_size; }; -extern int ffmpeg_decode_init(struct ffmpeg_decode *decode, enum AVCodecID id, - bool use_hw); +extern int ffmpeg_decode_init(struct ffmpeg_decode *decode, enum AVCodecID id, bool use_hw); extern void ffmpeg_decode_free(struct ffmpeg_decode *decode); -extern bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data, - size_t size, struct obs_source_audio *audio, - bool *got_output); +extern bool ffmpeg_decode_audio(struct ffmpeg_decode *decode, uint8_t *data, size_t size, + struct obs_source_audio *audio, bool *got_output); -extern bool ffmpeg_decode_video(struct ffmpeg_decode *decode, uint8_t *data, - size_t size, long long *ts, - enum video_colorspace cs, - enum video_range_type range, - struct obs_source_frame2 *frame, +extern bool ffmpeg_decode_video(struct ffmpeg_decode *decode, uint8_t *data, size_t size, long long *ts, + enum video_colorspace cs, enum video_range_type range, struct obs_source_frame2 *frame, bool *got_output); static inline bool ffmpeg_decode_valid(struct ffmpeg_decode *decode) diff --git a/plugins/win-dshow/shared-memory-queue.c b/plugins/win-dshow/shared-memory-queue.c index f1cdbf7ae..2a6b6cbe7 100644 --- a/plugins/win-dshow/shared-memory-queue.c +++ b/plugins/win-dshow/shared-memory-queue.c @@ -82,14 +82,12 @@ video_queue_t *video_queue_create(uint32_t cx, uint32_t cy, uint64_t interval) return NULL; } - vq.handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, - PAGE_READWRITE, 0, size, VIDEO_NAME); + vq.handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, VIDEO_NAME); if (!vq.handle) { return NULL; } - vq.header = (struct queue_header *)MapViewOfFile( - vq.handle, FILE_MAP_ALL_ACCESS, 0, 0, 0); + vq.header = (struct queue_header *)MapViewOfFile(vq.handle, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (!vq.header) { CloseHandle(vq.handle); return NULL; @@ -119,8 +117,7 @@ video_queue_t *video_queue_open() return NULL; } - vq.header = (struct queue_header *)MapViewOfFile( - vq.handle, FILE_MAP_READ, 0, 0, 0); + vq.header = (struct queue_header *)MapViewOfFile(vq.handle, FILE_MAP_READ, 0, 0, 0); if (!vq.header) { CloseHandle(vq.handle); return NULL; @@ -149,8 +146,7 @@ void video_queue_close(video_queue_t *vq) free(vq); } -void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, - uint64_t *interval) +void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, uint64_t *interval) { struct queue_header *qh = vq->header; *cx = qh->cx; @@ -160,8 +156,7 @@ void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, #define get_idx(inc) ((unsigned long)inc % 3) -void video_queue_write(video_queue_t *vq, uint8_t **data, uint32_t *linesize, - uint64_t timestamp) +void video_queue_write(video_queue_t *vq, uint8_t **data, uint32_t *linesize, uint64_t timestamp) { struct queue_header *qh = vq->header; long inc = ++qh->write_idx; @@ -188,8 +183,7 @@ enum queue_state video_queue_state(video_queue_t *vq) for (size_t i = 0; i < 3; i++) { size_t off = vq->header->offsets[i]; vq->ts[i] = (uint64_t *)(((uint8_t *)vq->header) + off); - vq->frame[i] = ((uint8_t *)vq->header) + off + - FRAME_HEADER_SIZE; + vq->frame[i] = ((uint8_t *)vq->header) + off + FRAME_HEADER_SIZE; } vq->ready_to_read = true; } @@ -197,8 +191,7 @@ enum queue_state video_queue_state(video_queue_t *vq) return state; } -bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, - uint64_t *ts) +bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, uint64_t *ts) { struct queue_header *qh = vq->header; long inc = qh->read_idx; diff --git a/plugins/win-dshow/shared-memory-queue.h b/plugins/win-dshow/shared-memory-queue.h index 5e6435299..a1f1a0778 100644 --- a/plugins/win-dshow/shared-memory-queue.h +++ b/plugins/win-dshow/shared-memory-queue.h @@ -19,18 +19,14 @@ enum queue_state { SHARED_QUEUE_STATE_STOPPING, }; -extern video_queue_t *video_queue_create(uint32_t cx, uint32_t cy, - uint64_t interval); +extern video_queue_t *video_queue_create(uint32_t cx, uint32_t cy, uint64_t interval); extern video_queue_t *video_queue_open(); extern void video_queue_close(video_queue_t *vq); -extern void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, - uint64_t *interval); -extern void video_queue_write(video_queue_t *vq, uint8_t **data, - uint32_t *linesize, uint64_t timestamp); +extern void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, uint64_t *interval); +extern void video_queue_write(video_queue_t *vq, uint8_t **data, uint32_t *linesize, uint64_t timestamp); extern enum queue_state video_queue_state(video_queue_t *vq); -extern bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, - uint64_t *ts); +extern bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, uint64_t *ts); #ifdef __cplusplus } diff --git a/plugins/win-dshow/tiny-nv12-scale.c b/plugins/win-dshow/tiny-nv12-scale.c index 697267b09..503f2a273 100644 --- a/plugins/win-dshow/tiny-nv12-scale.c +++ b/plugins/win-dshow/tiny-nv12-scale.c @@ -6,8 +6,7 @@ * it's nearest neighbor so not really a huge deal. at the very least it * should be sse2 at some point. */ -void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, - int dst_cy, int src_cx, int src_cy) +void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, int dst_cy, int src_cx, int src_cy) { s->format = format; @@ -18,8 +17,7 @@ void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, s->dst_cy = dst_cy; } -static void nv12_scale_nearest(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src) +static void nv12_scale_nearest(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src) { register uint8_t *dst = dst_start; const int src_cx = s->src_cx; @@ -57,8 +55,7 @@ static void nv12_scale_nearest(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_scale_nearest_to_i420(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src) +static void nv12_scale_nearest_to_i420(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src) { register uint8_t *dst = dst_start; const int src_cx = s->src_cx; @@ -99,8 +96,7 @@ static void nv12_scale_nearest_to_i420(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_convert_to_i420(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src_start) +static void nv12_convert_to_i420(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src_start) { const int size = s->src_cx * s->src_cy; const int size_d4 = size / 4; @@ -118,8 +114,7 @@ static void nv12_convert_to_i420(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src) +static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src) { register uint8_t *dst = dst_start; const int src_cx = s->src_cx; @@ -138,8 +133,7 @@ static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, for (int y = 0; y < dst_cy; y++) { const int src_line = y * src_cy / dst_cy * s->src_cx; - const int src_line_d2 = - y / 2 * src_cy_d2 / dst_cy_d2 * s->src_cx; + const int src_line_d2 = y / 2 * src_cy_d2 / dst_cy_d2 * s->src_cx; for (int x = 0; x < dst_cx; x++) { const int src_x = x * src_cx / dst_cx; @@ -155,8 +149,7 @@ static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_convert_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src_start) +static void nv12_convert_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src_start) { const int size = s->src_cx * s->src_cy; const int size_dst_line = s->src_cx * 2; diff --git a/plugins/win-dshow/tiny-nv12-scale.h b/plugins/win-dshow/tiny-nv12-scale.h index fb8bc580a..5b3f48ede 100644 --- a/plugins/win-dshow/tiny-nv12-scale.h +++ b/plugins/win-dshow/tiny-nv12-scale.h @@ -25,8 +25,7 @@ struct nv12_scale { typedef struct nv12_scale nv12_scale_t; -extern void nv12_scale_init(nv12_scale_t *s, enum target_format format, - int dst_cx, int dst_cy, int src_cx, int src_cy); +extern void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, int dst_cy, int src_cx, int src_cy); extern void nv12_do_scale(nv12_scale_t *s, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus diff --git a/plugins/win-dshow/virtualcam-module/placeholder.cpp b/plugins/win-dshow/virtualcam-module/placeholder.cpp index 65066adb6..98597b63e 100644 --- a/plugins/win-dshow/virtualcam-module/placeholder.cpp +++ b/plugins/win-dshow/virtualcam-module/placeholder.cpp @@ -31,12 +31,9 @@ static void convert_placeholder(const uint8_t *rgb_in, int width, int height) const int16_t g = *(in++); const int16_t r = *(in++); - *(out++) = (uint8_t)(((66 * r + 129 * g + 25 * b + 128) >> 8) + - 16); - *(out++) = (uint8_t)(((-38 * r - 74 * g + 112 * b + 128) >> 8) + - 128); - *(out++) = (uint8_t)(((112 * r - 94 * g - 18 * b + 128) >> 8) + - 128); + *(out++) = (uint8_t)(((66 * r + 129 * g + 25 * b + 128) >> 8) + 16); + *(out++) = (uint8_t)(((-38 * r - 74 * g + 112 * b + 128) >> 8) + 128); + *(out++) = (uint8_t)(((112 * r - 94 * g - 18 * b + 128) >> 8) + 128); } placeholder.resize(width * height * 3 / 2); diff --git a/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp b/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp index 3a53d4ee7..89702b357 100644 --- a/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp +++ b/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp @@ -49,8 +49,7 @@ VCamFilter::VCamFilter() : OutputFilter() vq = video_queue_open(); if (vq) { if (video_queue_state(vq) == SHARED_QUEUE_STATE_READY) { - video_queue_get_info(vq, &new_obs_cx, &new_obs_cy, - &new_obs_interval); + video_queue_get_info(vq, &new_obs_cx, &new_obs_cy, &new_obs_interval); } /* don't keep it open until the filter actually starts */ @@ -58,24 +57,17 @@ VCamFilter::VCamFilter() : OutputFilter() vq = nullptr; } else { wchar_t res_file[MAX_PATH]; - SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr, - SHGFP_TYPE_CURRENT, res_file); - StringCbCat(res_file, sizeof(res_file), - L"\\obs-virtualcam.txt"); + SHGetFolderPathW(nullptr, CSIDL_APPDATA, nullptr, SHGFP_TYPE_CURRENT, res_file); + StringCbCat(res_file, sizeof(res_file), L"\\obs-virtualcam.txt"); - HANDLE file = CreateFileW(res_file, GENERIC_READ, 0, nullptr, - OPEN_EXISTING, 0, nullptr); + HANDLE file = CreateFileW(res_file, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr); if (file) { char res[128]; DWORD len = 0; - if (ReadFile(file, res, sizeof(res) - 1, &len, - nullptr)) { + if (ReadFile(file, res, sizeof(res) - 1, &len, nullptr)) { res[len] = 0; - int vals = sscanf(res, - "%" PRIu32 "x%" PRIu32 - "x%" PRIu64, - &new_obs_cx, &new_obs_cy, + int vals = sscanf(res, "%" PRIu32 "x%" PRIu32 "x%" PRIu64, &new_obs_cx, &new_obs_cy, &new_obs_interval); if (vals != 3) { new_obs_cx = obs_cx; @@ -88,16 +80,11 @@ VCamFilter::VCamFilter() : OutputFilter() } } - if (new_obs_cx != obs_cx || new_obs_cy != obs_cy || - new_obs_interval != obs_interval) { - AddVideoFormat(VideoFormat::NV12, new_obs_cx, new_obs_cy, - new_obs_interval); - AddVideoFormat(VideoFormat::I420, new_obs_cx, new_obs_cy, - new_obs_interval); - AddVideoFormat(VideoFormat::YUY2, new_obs_cx, new_obs_cy, - new_obs_interval); - SetVideoFormat(VideoFormat::NV12, new_obs_cx, new_obs_cy, - new_obs_interval); + if (new_obs_cx != obs_cx || new_obs_cy != obs_cy || new_obs_interval != obs_interval) { + AddVideoFormat(VideoFormat::NV12, new_obs_cx, new_obs_cy, new_obs_interval); + AddVideoFormat(VideoFormat::I420, new_obs_cx, new_obs_cy, new_obs_interval); + AddVideoFormat(VideoFormat::YUY2, new_obs_cx, new_obs_cy, new_obs_interval); + SetVideoFormat(VideoFormat::NV12, new_obs_cx, new_obs_cy, new_obs_interval); obs_cx = new_obs_cx; obs_cy = new_obs_cy; @@ -198,10 +185,8 @@ void VCamFilter::Thread() /* Created dynamically based on output resolution changes */ placeholder.scaled_data = nullptr; - nv12_scale_init(&scaler, TARGET_FORMAT_NV12, obs_cx, obs_cy, obs_cx, - obs_cy); - nv12_scale_init(&placeholder.scaler, TARGET_FORMAT_NV12, obs_cx, obs_cy, - placeholder.cx, placeholder.cy); + nv12_scale_init(&scaler, TARGET_FORMAT_NV12, obs_cx, obs_cy, obs_cx, obs_cy); + nv12_scale_init(&placeholder.scaler, TARGET_FORMAT_NV12, obs_cx, obs_cy, placeholder.cx, placeholder.cy); UpdatePlaceholder(); @@ -233,8 +218,7 @@ void VCamFilter::Frame(uint64_t ts) if (state == SHARED_QUEUE_STATE_READY) { /* The virtualcam output from OBS has started, get the actual cx / cy of the data stream */ - video_queue_get_info(vq, &new_obs_cx, &new_obs_cy, - &new_obs_interval); + video_queue_get_info(vq, &new_obs_cx, &new_obs_cy, &new_obs_interval); } else if (state == SHARED_QUEUE_STATE_STOPPING) { video_queue_close(vq); vq = nullptr; @@ -254,15 +238,13 @@ void VCamFilter::Frame(uint64_t ts) new_obs_interval = GetInterval(); } - if (new_obs_cx != obs_cx || new_obs_cy != obs_cy || - new_obs_interval != obs_interval) { + if (new_obs_cx != obs_cx || new_obs_cy != obs_cy || new_obs_interval != obs_interval) { /* The res / FPS of the video coming from OBS has changed, update parameters as needed */ if (in_obs) { /* If the vcam is being used inside obs, adjust the format we present to match */ - SetVideoFormat(GetVideoFormat(), new_obs_cx, new_obs_cy, - new_obs_interval); + SetVideoFormat(GetVideoFormat(), new_obs_cx, new_obs_cy, new_obs_interval); /* Update the new filter size immediately since we know it just changed above */ @@ -271,8 +253,7 @@ void VCamFilter::Frame(uint64_t ts) } /* Re-initialize the main scaler to use the new resolution */ - nv12_scale_init(&scaler, scaler.format, new_filter_cx, - new_filter_cy, new_obs_cx, new_obs_cy); + nv12_scale_init(&scaler, scaler.format, new_filter_cx, new_filter_cy, new_obs_cx, new_obs_cy); obs_cx = new_obs_cx; obs_cy = new_obs_cy; @@ -287,8 +268,7 @@ void VCamFilter::Frame(uint64_t ts) filter_cy = new_filter_cy; /* Re-initialize the main scaler to use the new resolution */ - nv12_scale_init(&scaler, scaler.format, new_filter_cx, - new_filter_cy, new_obs_cx, new_obs_cy); + nv12_scale_init(&scaler, scaler.format, new_filter_cx, new_filter_cy, new_obs_cx, new_obs_cy); UpdatePlaceholder(); } @@ -298,14 +278,11 @@ void VCamFilter::Frame(uint64_t ts) if (current_format != format) { /* The output format changed, update the scalers */ if (current_format == VideoFormat::I420) - scaler.format = placeholder.scaler.format = - TARGET_FORMAT_I420; + scaler.format = placeholder.scaler.format = TARGET_FORMAT_I420; else if (current_format == VideoFormat::YUY2) - scaler.format = placeholder.scaler.format = - TARGET_FORMAT_YUY2; + scaler.format = placeholder.scaler.format = TARGET_FORMAT_YUY2; else - scaler.format = placeholder.scaler.format = - TARGET_FORMAT_NV12; + scaler.format = placeholder.scaler.format = TARGET_FORMAT_NV12; format = current_format; @@ -356,17 +333,13 @@ void VCamFilter::UpdatePlaceholder(void) if (!placeholder.scaled_data) return; - if (placeholder.cx == GetCX() && placeholder.cy == GetCY() && - placeholder.scaler.format == TARGET_FORMAT_NV12) { + if (placeholder.cx == GetCX() && placeholder.cy == GetCY() && placeholder.scaler.format == TARGET_FORMAT_NV12) { /* No scaling necessary if it matches exactly */ - memcpy(placeholder.scaled_data, placeholder.source_data, - GetOutputBufferSize()); + memcpy(placeholder.scaled_data, placeholder.source_data, GetOutputBufferSize()); } else { - nv12_scale_init(&placeholder.scaler, placeholder.scaler.format, - GetCX(), GetCY(), placeholder.cx, + nv12_scale_init(&placeholder.scaler, placeholder.scaler.format, GetCX(), GetCY(), placeholder.cx, placeholder.cy); - nv12_do_scale(&placeholder.scaler, placeholder.scaled_data, - placeholder.source_data); + nv12_do_scale(&placeholder.scaler, placeholder.scaled_data, placeholder.source_data); } } diff --git a/plugins/win-dshow/virtualcam-module/virtualcam-filter.hpp b/plugins/win-dshow/virtualcam-module/virtualcam-filter.hpp index 09d0c9c35..f11213f87 100644 --- a/plugins/win-dshow/virtualcam-module/virtualcam-filter.hpp +++ b/plugins/win-dshow/virtualcam-module/virtualcam-filter.hpp @@ -48,10 +48,7 @@ class VCamFilter : public DShow::OutputFilter { nv12_scale_t scaler = {}; - inline bool stopped() const - { - return WaitForSingleObject(thread_stop, 0) != WAIT_TIMEOUT; - } + inline bool stopped() const { return WaitForSingleObject(thread_stop, 0) != WAIT_TIMEOUT; } inline uint64_t GetTime(); diff --git a/plugins/win-dshow/virtualcam-module/virtualcam-module.cpp b/plugins/win-dshow/virtualcam-module/virtualcam-module.cpp index 937fb57df..23e0ee424 100644 --- a/plugins/win-dshow/virtualcam-module/virtualcam-module.cpp +++ b/plugins/win-dshow/virtualcam-module/virtualcam-module.cpp @@ -3,12 +3,9 @@ /* ========================================================================= */ -static const REGPINTYPES AMSMediaTypesV = {&MEDIATYPE_Video, - &MEDIASUBTYPE_NV12}; +static const REGPINTYPES AMSMediaTypesV = {&MEDIATYPE_Video, &MEDIASUBTYPE_NV12}; -static const REGFILTERPINS AMSPinVideo = {nullptr, false, true, - false, false, &CLSID_NULL, - nullptr, 1, &AMSMediaTypesV}; +static const REGFILTERPINS AMSPinVideo = {nullptr, false, true, false, false, &CLSID_NULL, nullptr, 1, &AMSMediaTypesV}; HINSTANCE dll_inst = nullptr; volatile long locks = 0; @@ -28,8 +25,7 @@ public: STDMETHODIMP_(ULONG) Release(); // IClassFactory - STDMETHODIMP CreateInstance(LPUNKNOWN parent, REFIID riid, - void **p_ptr); + STDMETHODIMP CreateInstance(LPUNKNOWN parent, REFIID riid, void **p_ptr); STDMETHODIMP LockServer(BOOL lock); }; @@ -104,8 +100,7 @@ static inline DWORD string_size(const wchar_t *str) return (DWORD)(wcslen(str) + 1) * sizeof(wchar_t); } -static bool RegServer(const CLSID &cls, const wchar_t *desc, - const wchar_t *file, const wchar_t *model = L"Both", +static bool RegServer(const CLSID &cls, const wchar_t *desc, const wchar_t *file, const wchar_t *model = L"Both", const wchar_t *type = L"InprocServer32") { wchar_t cls_str[CHARS_IN_GUID]; @@ -129,8 +124,7 @@ static bool RegServer(const CLSID &cls, const wchar_t *desc, } RegSetValueW(subkey, nullptr, REG_SZ, file, string_size(file)); - RegSetValueExW(subkey, L"ThreadingModel", 0, REG_SZ, - (const BYTE *)model, string_size(model)); + RegSetValueExW(subkey, L"ThreadingModel", 0, REG_SZ, (const BYTE *)model, string_size(model)); success = true; @@ -165,8 +159,7 @@ static bool RegServers(bool reg) } if (reg) { - return RegServer(CLSID_OBS_VirtualVideo, L"OBS Virtual Camera", - file); + return RegServer(CLSID_OBS_VirtualVideo, L"OBS Virtual Camera", file); } else { return UnregServer(CLSID_OBS_VirtualVideo); } @@ -177,9 +170,7 @@ static bool RegFilters(bool reg) ComPtr fm; HRESULT hr; - hr = CoCreateInstance(CLSID_FilterMapper2, nullptr, - CLSCTX_INPROC_SERVER, IID_IFilterMapper2, - (void **)&fm); + hr = CoCreateInstance(CLSID_FilterMapper2, nullptr, CLSCTX_INPROC_SERVER, IID_IFilterMapper2, (void **)&fm); if (FAILED(hr)) { return false; } @@ -192,16 +183,13 @@ static bool RegFilters(bool reg) rf2.cPins = 1; rf2.rgPins = &AMSPinVideo; - hr = fm->RegisterFilter(CLSID_OBS_VirtualVideo, - L"OBS Virtual Camera", &moniker, - &CLSID_VideoInputDeviceCategory, - nullptr, &rf2); + hr = fm->RegisterFilter(CLSID_OBS_VirtualVideo, L"OBS Virtual Camera", &moniker, + &CLSID_VideoInputDeviceCategory, nullptr, &rf2); if (FAILED(hr)) { return false; } } else { - hr = fm->UnregisterFilter(&CLSID_VideoInputDeviceCategory, 0, - CLSID_OBS_VirtualVideo); + hr = fm->UnregisterFilter(&CLSID_VideoInputDeviceCategory, 0, CLSID_OBS_VirtualVideo); if (FAILED(hr)) { return false; } diff --git a/plugins/win-dshow/virtualcam.c b/plugins/win-dshow/virtualcam.c index ded9fabf9..0fbf04bf0 100644 --- a/plugins/win-dshow/virtualcam.c +++ b/plugins/win-dshow/virtualcam.c @@ -25,8 +25,7 @@ static void virtualcam_destroy(void *data) static void *virtualcam_create(obs_data_t *settings, obs_output_t *output) { - struct virtualcam_data *vcam = - (struct virtualcam_data *)bzalloc(sizeof(*vcam)); + struct virtualcam_data *vcam = (struct virtualcam_data *)bzalloc(sizeof(*vcam)); vcam->output = output; UNUSED_PARAMETER(settings); @@ -45,12 +44,10 @@ static bool virtualcam_start(void *data) uint64_t interval = ovi.fps_den * 10000000ULL / ovi.fps_num; char res[64]; - snprintf(res, sizeof(res), "%dx%dx%lld", (int)width, (int)height, - (long long)interval); + snprintf(res, sizeof(res), "%dx%dx%lld", (int)width, (int)height, (long long)interval); char *res_file = os_get_config_path_ptr("obs-virtualcam.txt"); - os_quick_write_utf8_file_safe(res_file, res, strlen(res), false, "tmp", - NULL); + os_quick_write_utf8_file_safe(res_file, res, strlen(res), false, "tmp", NULL); bfree(res_file); vcam->vq = video_queue_create(width, height, interval); @@ -109,8 +106,7 @@ static void virtual_video(void *param, struct video_data *frame) return; } - video_queue_write(vcam->vq, frame->data, frame->linesize, - frame->timestamp); + video_queue_write(vcam->vq, frame->data, frame->linesize, frame->timestamp); } struct obs_output_info virtualcam_info = { diff --git a/plugins/win-dshow/win-dshow-encoder.cpp b/plugins/win-dshow/win-dshow-encoder.cpp index 4fc8fb30d..724359d9a 100644 --- a/plugins/win-dshow/win-dshow-encoder.cpp +++ b/plugins/win-dshow/win-dshow-encoder.cpp @@ -25,9 +25,7 @@ struct DShowEncoder { DARRAY(uint8_t) firstPacket; DARRAY(uint8_t) header; - inline DShowEncoder(obs_encoder_t *context_, const wchar_t *device_) - : context(context_), - device(device_) + inline DShowEncoder(obs_encoder_t *context_, const wchar_t *device_) : context(context_), device(device_) { da_init(firstPacket); da_init(header); @@ -42,9 +40,7 @@ struct DShowEncoder { inline void ParseFirstPacket(const uint8_t *data, size_t size); inline bool Update(obs_data_t *settings); - inline bool Encode(struct encoder_frame *frame, - struct encoder_packet *packet, - bool *received_packet); + inline bool Encode(struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet); }; static const char *GetC985EncoderName(void *) @@ -135,8 +131,7 @@ inline bool DShowEncoder::Update(obs_data_t *settings) "\theight: %d\n" "\tfps_num: %d\n" "\tfps_den: %d", - deviceName->array, (int)width, (int)height, (int)voi->fps_num, - (int)voi->fps_den); + deviceName->array, (int)width, (int)height, (int)voi->fps_num, (int)voi->fps_den); return encoder.SetConfig(config); } @@ -151,9 +146,7 @@ static bool UpdateDShowEncoder(void *data, obs_data_t *settings) return true; } -static inline void *CreateDShowEncoder(obs_data_t *settings, - obs_encoder_t *context, - const wchar_t *device) +static inline void *CreateDShowEncoder(obs_data_t *settings, obs_encoder_t *context, const wchar_t *device) { DShowEncoder *encoder = nullptr; @@ -162,8 +155,7 @@ static inline void *CreateDShowEncoder(obs_data_t *settings, UpdateDShowEncoder(encoder, settings); } catch (const char *error) { - blog(LOG_ERROR, "Could not create DirectShow encoder '%s': %s", - obs_encoder_get_name(context), error); + blog(LOG_ERROR, "Could not create DirectShow encoder '%s': %s", obs_encoder_get_name(context), error); } return encoder; @@ -210,21 +202,17 @@ inline void DShowEncoder::ParseFirstPacket(const uint8_t *data, size_t size) nal_end = end; if (type == OBS_NAL_SPS || type == OBS_NAL_PPS) { - da_push_back_array(header, nal_codestart, - nal_end - nal_codestart); + da_push_back_array(header, nal_codestart, nal_end - nal_codestart); } else { - da_push_back_array(firstPacket, nal_codestart, - nal_end - nal_codestart); + da_push_back_array(firstPacket, nal_codestart, nal_end - nal_codestart); } nal_start = nal_end; } } -inline bool DShowEncoder::Encode(struct encoder_frame *frame, - struct encoder_packet *packet, - bool *received_packet) +inline bool DShowEncoder::Encode(struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { unsigned char *frame_data[DSHOW_MAX_PLANES] = {}; size_t frame_sizes[DSHOW_MAX_PLANES] = {}; @@ -243,9 +231,8 @@ inline bool DShowEncoder::Encode(struct encoder_frame *frame, long long actualPTS = frame->pts * frameInterval; - bool success = encoder.Encode(frame_data, frame_sizes, actualPTS, - actualPTS + frameInterval, dshowPacket, - new_packet); + bool success = + encoder.Encode(frame_data, frame_sizes, actualPTS, actualPTS + frameInterval, dshowPacket, new_packet); if (!success) return false; @@ -271,11 +258,9 @@ inline bool DShowEncoder::Encode(struct encoder_frame *frame, return true; } -static bool DShowEncode(void *data, struct encoder_frame *frame, - struct encoder_packet *packet, bool *received_packet) +static bool DShowEncode(void *data, struct encoder_frame *frame, struct encoder_packet *packet, bool *received_packet) { - return reinterpret_cast(data)->Encode(frame, packet, - received_packet); + return reinterpret_cast(data)->Encode(frame, packet, received_packet); } static bool GetDShowExtraData(void *data, uint8_t **extra_data, size_t *size) @@ -290,8 +275,7 @@ static bool GetDShowExtraData(void *data, uint8_t **extra_data, size_t *size) static inline bool ValidResolution(uint32_t width, uint32_t height) { - return (width == 1280 && height == 720) || - (width == 1024 && height == 768); + return (width == 1280 && height == 720) || (width == 1024 && height == 768); } static void GetDShowVideoInfo(void *data, struct video_scale_info *info) @@ -299,8 +283,7 @@ static void GetDShowVideoInfo(void *data, struct video_scale_info *info) DShowEncoder *encoder = reinterpret_cast(data); encoder->format = VIDEO_FORMAT_I420; - if (info->format == VIDEO_FORMAT_I420 && - ValidResolution(info->width, info->height)) + if (info->format == VIDEO_FORMAT_I420 && ValidResolution(info->width, info->height)) return; info->format = VIDEO_FORMAT_I420; @@ -329,8 +312,7 @@ static obs_properties_t *GetDShowEncoderProperties(void *data) { obs_properties_t *ppts = obs_properties_create(); - obs_properties_add_int(ppts, "bitrate", obs_module_text("Bitrate"), - 1000, 60000, 1); + obs_properties_add_int(ppts, "bitrate", obs_module_text("Bitrate"), 1000, 60000, 1); UNUSED_PARAMETER(data); return ppts; diff --git a/plugins/win-dshow/win-dshow.cpp b/plugins/win-dshow/win-dshow.cpp index 438158c72..8833180cb 100644 --- a/plugins/win-dshow/win-dshow.cpp +++ b/plugins/win-dshow/win-dshow.cpp @@ -163,10 +163,7 @@ class CriticalScope { CriticalScope &operator=(CriticalScope &cs) = delete; public: - inline CriticalScope(CriticalSection &mutex_) : mutex(mutex_) - { - EnterCriticalSection(mutex); - } + inline CriticalScope(CriticalSection &mutex_) : mutex(mutex_) { EnterCriticalSection(mutex); } inline ~CriticalScope() { LeaveCriticalSection(mutex); } }; @@ -222,8 +219,7 @@ struct DShowInput { inline void QueueActivate(obs_data_t *settings) { - bool block = - obs_data_get_bool(settings, "synchronous_activate"); + bool block = obs_data_get_bool(settings, "synchronous_activate"); QueueAction(block ? Action::ActivateBlock : Action::Activate); if (block) { obs_data_erase(settings, "synchronous_activate"); @@ -231,9 +227,7 @@ struct DShowInput { } } - inline DShowInput(obs_source_t *source_, obs_data_t *settings) - : source(source_), - device(InitGraph::False) + inline DShowInput(obs_source_t *source_, obs_data_t *settings) : source(source_), device(InitGraph::False) { memset(&audio, 0, sizeof(audio)); memset(&frame, 0, sizeof(frame)); @@ -249,13 +243,11 @@ struct DShowInput { if (!activated_event) throw "Failed to create activated_event"; - thread = - CreateThread(nullptr, 0, DShowThread, this, 0, nullptr); + thread = CreateThread(nullptr, 0, DShowThread, this, 0, nullptr); if (!thread) throw "Failed to create thread"; - deactivateWhenNotShowing = - obs_data_get_bool(settings, DEACTIVATE_WNS); + deactivateWhenNotShowing = obs_data_get_bool(settings, DEACTIVATE_WNS); if (obs_data_get_bool(settings, "active")) { bool showing = obs_source_showing(source); @@ -279,17 +271,14 @@ struct DShowInput { WaitForSingleObject(thread, INFINITE); } - void OnEncodedVideoData(enum AVCodecID id, unsigned char *data, - size_t size, long long ts); - void OnEncodedAudioData(enum AVCodecID id, unsigned char *data, - size_t size, long long ts); + void OnEncodedVideoData(enum AVCodecID id, unsigned char *data, size_t size, long long ts); + void OnEncodedAudioData(enum AVCodecID id, unsigned char *data, size_t size, long long ts); void OnReactivate(); - void OnVideoData(const VideoConfig &config, unsigned char *data, - size_t size, long long startTime, long long endTime, - long rotation); - void OnAudioData(const AudioConfig &config, unsigned char *data, - size_t size, long long startTime, long long endTime); + void OnVideoData(const VideoConfig &config, unsigned char *data, size_t size, long long startTime, + long long endTime, long rotation); + void OnAudioData(const AudioConfig &config, unsigned char *data, size_t size, long long startTime, + long long endTime); bool UpdateVideoConfig(obs_data_t *settings); bool UpdateAudioConfig(obs_data_t *settings); @@ -329,8 +318,7 @@ static inline void ProcessMessages() void DShowInput::DShowLoop() { while (true) { - DWORD ret = MsgWaitForMultipleObjects(1, &semaphore, false, - INFINITE, QS_ALLINPUT); + DWORD ret = MsgWaitForMultipleObjects(1, &semaphore, false, INFINITE, QS_ALLINPUT); if (ret == (WAIT_OBJECT_0 + 1)) { ProcessMessages(); continue; @@ -395,16 +383,14 @@ void DShowInput::DShowLoop() #define FPS_HIGHEST 0LL #define FPS_MATCHING -1LL -template -static bool between(T &&lower, U &&value, V &&upper) +template static bool between(T &&lower, U &&value, V &&upper) { return value >= lower && value <= upper; } static bool ResolutionAvailable(const VideoInfo &cap, int cx, int cy) { - return between(cap.minCX, cx, cap.maxCX) && - between(cap.minCY, cy, cap.maxCY); + return between(cap.minCX, cx, cap.maxCX) && between(cap.minCY, cy, cap.maxCY); } #define DEVICE_INTERVAL_DIFF_LIMIT 20 @@ -416,12 +402,9 @@ static bool FrameRateAvailable(const VideoInfo &cap, long long interval) cap.maxInterval + DEVICE_INTERVAL_DIFF_LIMIT); } -static long long FrameRateInterval(const VideoInfo &cap, - long long desired_interval) +static long long FrameRateInterval(const VideoInfo &cap, long long desired_interval) { - return desired_interval < cap.minInterval - ? cap.minInterval - : min(desired_interval, cap.maxInterval); + return desired_interval < cap.minInterval ? cap.minInterval : min(desired_interval, cap.maxInterval); } static inline video_format ConvertVideoFormat(VideoFormat format) @@ -493,31 +476,25 @@ static inline enum speaker_layout convert_speaker_layout(uint8_t channels) //#define LOG_ENCODED_VIDEO_TS 1 //#define LOG_ENCODED_AUDIO_TS 1 -void DShowInput::OnEncodedVideoData(enum AVCodecID id, unsigned char *data, - size_t size, long long ts) +void DShowInput::OnEncodedVideoData(enum AVCodecID id, unsigned char *data, size_t size, long long ts) { /* If format or hw decode changes, recreate the decoder */ if (ffmpeg_decode_valid(video_decoder) && - ((video_decoder->codec->id != id) || - (video_decoder->hw != hw_decode))) { + ((video_decoder->codec->id != id) || (video_decoder->hw != hw_decode))) { ffmpeg_decode_free(video_decoder); } if (!ffmpeg_decode_valid(video_decoder)) { if (ffmpeg_decode_init(video_decoder, id, hw_decode) < 0) { - blog(LOG_WARNING, - "%s: Could not initialize video decoder", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: Could not initialize video decoder", obs_source_get_name(source)); return; } } bool got_output; - bool success = ffmpeg_decode_video(video_decoder, data, size, &ts, cs, - frame.range, &frame, &got_output); + bool success = ffmpeg_decode_video(video_decoder, data, size, &ts, cs, frame.range, &frame, &got_output); if (!success) { - blog(LOG_WARNING, "%s: Error decoding video", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: Error decoding video", obs_source_get_name(source)); return; } @@ -537,8 +514,7 @@ void DShowInput::OnReactivate() SetActive(true); } -void DShowInput::OnVideoData(const VideoConfig &config, unsigned char *data, - size_t size, long long startTime, +void DShowInput::OnVideoData(const VideoConfig &config, unsigned char *data, size_t size, long long startTime, long long endTime, long rotation) { if (autorotation && rotation != lastRotation) { @@ -574,22 +550,18 @@ void DShowInput::OnVideoData(const VideoConfig &config, unsigned char *data, frame.flags = OBS_SOURCE_FRAME_LINEAR_ALPHA; /* YUV DIBS are always top-down */ - if (config.format == VideoFormat::XRGB || - config.format == VideoFormat::ARGB) { + if (config.format == VideoFormat::XRGB || config.format == VideoFormat::ARGB) { /* RGB DIBs are bottom-up by default */ if (!config.cy_flip) frame.flip = !frame.flip; } - if (videoConfig.format == VideoFormat::XRGB || - videoConfig.format == VideoFormat::ARGB) { + if (videoConfig.format == VideoFormat::XRGB || videoConfig.format == VideoFormat::ARGB) { frame.data[0] = data; frame.linesize[0] = cx * 4; - } else if (videoConfig.format == VideoFormat::YVYU || - videoConfig.format == VideoFormat::YUY2 || - videoConfig.format == VideoFormat::HDYC || - videoConfig.format == VideoFormat::UYVY) { + } else if (videoConfig.format == VideoFormat::YVYU || videoConfig.format == VideoFormat::YUY2 || + videoConfig.format == VideoFormat::HDYC || videoConfig.format == VideoFormat::UYVY) { frame.data[0] = data; frame.linesize[0] = cx * 2; @@ -635,25 +607,20 @@ void DShowInput::OnVideoData(const VideoConfig &config, unsigned char *data, UNUSED_PARAMETER(endTime); /* it's the enndd tiimmes! */ } -void DShowInput::OnEncodedAudioData(enum AVCodecID id, unsigned char *data, - size_t size, long long ts) +void DShowInput::OnEncodedAudioData(enum AVCodecID id, unsigned char *data, size_t size, long long ts) { if (!ffmpeg_decode_valid(audio_decoder)) { if (ffmpeg_decode_init(audio_decoder, id, false) < 0) { - blog(LOG_WARNING, - "%s: Could not initialize audio decoder", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: Could not initialize audio decoder", obs_source_get_name(source)); return; } } bool got_output = false; do { - bool success = ffmpeg_decode_audio(audio_decoder, data, size, - &audio, &got_output); + bool success = ffmpeg_decode_audio(audio_decoder, data, size, &audio, &got_output); if (!success) { - blog(LOG_WARNING, "%s: Error decoding audio", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: Error decoding audio", obs_source_get_name(source)); return; } @@ -674,8 +641,7 @@ void DShowInput::OnEncodedAudioData(enum AVCodecID id, unsigned char *data, } while (got_output); } -void DShowInput::OnAudioData(const AudioConfig &config, unsigned char *data, - size_t size, long long startTime, +void DShowInput::OnAudioData(const AudioConfig &config, unsigned char *data, size_t size, long long startTime, long long endTime) { size_t block_size; @@ -696,8 +662,7 @@ void DShowInput::OnAudioData(const AudioConfig &config, unsigned char *data, audio.samples_per_sec = (uint32_t)config.sampleRate; audio.data[0] = data; - block_size = get_audio_bytes_per_channel(audio.format) * - get_audio_channels(audio.speakers); + block_size = get_audio_bytes_per_channel(audio.format) * get_audio_channels(audio.speakers); audio.frames = (uint32_t)(size / block_size); audio.timestamp = (uint64_t)startTime * 100; @@ -719,8 +684,7 @@ struct PropertiesData { DecodeDeviceId(deviceId, encoded_id); for (const VideoDevice &curDevice : devices) { - if (deviceId.name == curDevice.name && - deviceId.path == curDevice.path) { + if (deviceId.name == curDevice.name && deviceId.path == curDevice.path) { device = curDevice; return true; } @@ -737,8 +701,7 @@ static inline bool ConvertRes(int &cx, int &cy, const char *res) static inline bool FormatMatches(VideoFormat left, VideoFormat right) { - return left == VideoFormat::Any || right == VideoFormat::Any || - left == right; + return left == VideoFormat::Any || right == VideoFormat::Any || left == right; } static inline bool ResolutionValid(const string &res, int &cx, int &cy) @@ -756,8 +719,7 @@ static inline bool CapsMatch(const VideoInfo &) template static bool CapsMatch(const VideoDevice &dev, F... fs); -template -static inline bool CapsMatch(const VideoInfo &info, F &&f, Fs... fs) +template static inline bool CapsMatch(const VideoInfo &info, F &&f, Fs... fs) { return f(info) && CapsMatch(info, fs...); } @@ -772,17 +734,14 @@ template static bool CapsMatch(const VideoDevice &dev, F... fs) return match; } -static inline bool MatcherMatchVideoFormat(VideoFormat format, bool &did_match, - const VideoInfo &info) +static inline bool MatcherMatchVideoFormat(VideoFormat format, bool &did_match, const VideoInfo &info) { bool match = FormatMatches(format, info.format); did_match = did_match || match; return match; } -static inline bool MatcherClosestFrameRateSelector(long long interval, - long long &best_match, - const VideoInfo &info) +static inline bool MatcherClosestFrameRateSelector(long long interval, long long &best_match, const VideoInfo &info) { long long current = FrameRateInterval(info, interval); if (llabs(interval - best_match) > llabs(interval - current)) @@ -835,10 +794,9 @@ auto ClosestFrameRateSelector = [](long long interval, long long &best_match) [format, &did_match](const VideoInfo &info) mutable -> bool { \ return MatcherMatchVideoFormat(format, did_match, info); \ } -#define ClosestFrameRateSelector(interval, best_match) \ - [interval, &best_match](const VideoInfo &info) mutable -> bool { \ - return MatcherClosestFrameRateSelector(interval, best_match, \ - info); \ +#define ClosestFrameRateSelector(interval, best_match) \ + [interval, &best_match](const VideoInfo &info) mutable -> bool { \ + return MatcherClosestFrameRateSelector(interval, best_match, info); \ } #endif @@ -847,12 +805,11 @@ static bool ResolutionAvailable(const VideoDevice &dev, int cx, int cy) return CapsMatch(dev, ResolutionMatcher(cx, cy)); } -static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings, - VideoDevice &dev) +static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings, VideoDevice &dev) { const char *res = obs_data_get_autoselect_string(settings, RESOLUTION); - if (obs_data_has_autoselect_value(settings, RESOLUTION) && - ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy)) + if (obs_data_has_autoselect_value(settings, RESOLUTION) && ConvertRes(cx, cy, res) && + ResolutionAvailable(dev, cx, cy)) return true; res = obs_data_get_string(settings, RESOLUTION); @@ -871,8 +828,7 @@ static long long GetOBSFPS(); static inline bool IsDelayedDevice(const VideoConfig &config) { return config.format > VideoFormat::MJPEG || - wstrstri(config.name.c_str(), L"elgato game capture hd") != - nullptr || + wstrstri(config.name.c_str(), L"elgato game capture hd") != nullptr || wstrstri(config.name.c_str(), L"stream engine") != nullptr; } @@ -909,8 +865,7 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) DeviceId id; if (!DecodeDeviceId(id, video_device_id.c_str())) { - blog(LOG_WARNING, "%s: DecodeDeviceId failed", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: DecodeDeviceId failed", obs_source_get_name(source)); return false; } @@ -918,8 +873,7 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) Device::EnumVideoDevices(data.devices); VideoDevice dev; if (!data.GetDevice(dev, video_device_id.c_str())) { - blog(LOG_WARNING, "%s: data.GetDevice failed", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: data.GetDevice failed", obs_source_get_name(source)); return false; } @@ -932,17 +886,13 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) bool has_autosel_val; string resolution = obs_data_get_string(settings, RESOLUTION); if (!ResolutionValid(resolution, cx, cy)) { - blog(LOG_WARNING, "%s: ResolutionValid failed", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: ResolutionValid failed", obs_source_get_name(source)); return false; } - has_autosel_val = - obs_data_has_autoselect_value(settings, FRAME_INTERVAL); - interval = has_autosel_val - ? obs_data_get_autoselect_int(settings, - FRAME_INTERVAL) - : obs_data_get_int(settings, FRAME_INTERVAL); + has_autosel_val = obs_data_has_autoselect_value(settings, FRAME_INTERVAL); + interval = has_autosel_val ? obs_data_get_autoselect_int(settings, FRAME_INTERVAL) + : obs_data_get_int(settings, FRAME_INTERVAL); if (interval == FPS_MATCHING) interval = GetOBSFPS(); @@ -951,15 +901,12 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) long long best_interval = numeric_limits::max(); bool video_format_match = false; - bool caps_match = CapsMatch( - dev, ResolutionMatcher(cx, cy), - VideoFormatMatcher(format, video_format_match), - ClosestFrameRateSelector(interval, best_interval), - FrameRateMatcher(interval)); + bool caps_match = + CapsMatch(dev, ResolutionMatcher(cx, cy), VideoFormatMatcher(format, video_format_match), + ClosestFrameRateSelector(interval, best_interval), FrameRateMatcher(interval)); if (!caps_match && !video_format_match) { - blog(LOG_WARNING, "%s: Video format match failed", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: Video format match failed", obs_source_get_name(source)); return false; } @@ -978,18 +925,14 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) deviceHasAudio = dev.audioAttached; deviceHasSeparateAudioFilter = dev.separateAudioFilter; - videoConfig.callback = std::bind(&DShowInput::OnVideoData, this, - placeholders::_1, placeholders::_2, - placeholders::_3, placeholders::_4, - placeholders::_5, placeholders::_6); - videoConfig.reactivateCallback = - std::bind(&DShowInput::OnReactivate, this); + videoConfig.callback = std::bind(&DShowInput::OnVideoData, this, placeholders::_1, placeholders::_2, + placeholders::_3, placeholders::_4, placeholders::_5, placeholders::_6); + videoConfig.reactivateCallback = std::bind(&DShowInput::OnReactivate, this); videoConfig.format = videoConfig.internalFormat; if (!device.SetVideoConfig(&videoConfig)) { - blog(LOG_WARNING, "%s: device.SetVideoConfig failed", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: device.SetVideoConfig failed", obs_source_get_name(source)); return false; } @@ -1002,10 +945,8 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) BPtr name_utf8; BPtr path_utf8; - os_wcs_to_utf8_ptr(videoConfig.name.c_str(), videoConfig.name.size(), - &name_utf8); - os_wcs_to_utf8_ptr(videoConfig.path.c_str(), videoConfig.path.size(), - &path_utf8); + os_wcs_to_utf8_ptr(videoConfig.name.c_str(), videoConfig.name.size(), &name_utf8); + os_wcs_to_utf8_ptr(videoConfig.path.c_str(), videoConfig.path.size(), &path_utf8); SetupBuffering(settings); @@ -1020,12 +961,9 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) "\tformat: %s\n" "\tbuffering: %s\n" "\thardware decode: %s", - obs_source_get_name(source), (const char *)name_utf8, - (const char *)path_utf8, videoConfig.cx, videoConfig.cy_abs, - (int)videoConfig.cy_flip, fps, videoConfig.frameInterval, - formatName->array, - obs_source_async_unbuffered(source) ? "disabled" : "enabled", - hw_decode ? "enabled" : "disabled"); + obs_source_get_name(source), (const char *)name_utf8, (const char *)path_utf8, videoConfig.cx, + videoConfig.cy_abs, (int)videoConfig.cy_flip, fps, videoConfig.frameInterval, formatName->array, + obs_source_async_unbuffered(source) ? "disabled" : "enabled", hw_decode ? "enabled" : "disabled"); return true; } @@ -1050,17 +988,13 @@ bool DShowInput::UpdateAudioConfig(obs_data_t *settings) return true; } - audioConfig.useVideoDevice = !useCustomAudio && - !deviceHasSeparateAudioFilter; + audioConfig.useVideoDevice = !useCustomAudio && !deviceHasSeparateAudioFilter; audioConfig.useSeparateAudioFilter = deviceHasSeparateAudioFilter; - audioConfig.callback = std::bind(&DShowInput::OnAudioData, this, - placeholders::_1, placeholders::_2, - placeholders::_3, placeholders::_4, - placeholders::_5); + audioConfig.callback = std::bind(&DShowInput::OnAudioData, this, placeholders::_1, placeholders::_2, + placeholders::_3, placeholders::_4, placeholders::_5); - audioConfig.mode = - (AudioMode)obs_data_get_int(settings, AUDIO_OUTPUT_MODE); + audioConfig.mode = (AudioMode)obs_data_get_int(settings, AUDIO_OUTPUT_MODE); bool success = device.SetAudioConfig(&audioConfig); if (!success) { @@ -1071,18 +1005,15 @@ bool DShowInput::UpdateAudioConfig(obs_data_t *settings) obs_source_set_audio_active(source, true); BPtr name_utf8; - os_wcs_to_utf8_ptr(audioConfig.name.c_str(), audioConfig.name.size(), - &name_utf8); + os_wcs_to_utf8_ptr(audioConfig.name.c_str(), audioConfig.name.size(), &name_utf8); - blog(LOG_INFO, "\tusing video device audio: %s", - audioConfig.useVideoDevice ? "yes" : "no"); + blog(LOG_INFO, "\tusing video device audio: %s", audioConfig.useVideoDevice ? "yes" : "no"); if (!audioConfig.useVideoDevice) { if (audioConfig.useSeparateAudioFilter) blog(LOG_INFO, "\tseparate audio filter"); else - blog(LOG_INFO, "\taudio device: %s", - (const char *)name_utf8); + blog(LOG_INFO, "\taudio device: %s", (const char *)name_utf8); } const char *mode = ""; @@ -1116,8 +1047,7 @@ void DShowInput::SetActive(bool active_) obs_data_release(settings); } -inline enum video_colorspace -DShowInput::GetColorSpace(obs_data_t *settings) const +inline enum video_colorspace DShowInput::GetColorSpace(obs_data_t *settings) const { const char *space = obs_data_get_string(settings, COLOR_SPACE); @@ -1139,8 +1069,7 @@ DShowInput::GetColorSpace(obs_data_t *settings) const return VIDEO_CS_DEFAULT; } -inline enum video_range_type -DShowInput::GetColorRange(obs_data_t *settings) const +inline enum video_range_type DShowInput::GetColorRange(obs_data_t *settings) const { const char *range = obs_data_get_string(settings, COLOR_RANGE); @@ -1159,8 +1088,7 @@ inline bool DShowInput::Activate(obs_data_t *settings) } if (!UpdateVideoConfig(settings)) { - blog(LOG_WARNING, "%s: Video configuration failed", - obs_source_get_name(source)); + blog(LOG_WARNING, "%s: Video configuration failed", obs_source_get_name(source)); obs_source_set_audio_active(source, false); return false; } @@ -1198,10 +1126,9 @@ inline bool DShowInput::Activate(obs_data_t *settings) frame.range = range; frame.trc = trc; - bool success = video_format_get_parameters_for_format( - cs, range, ConvertVideoFormat(videoConfig.format), - frame.color_matrix, frame.color_range_min, - frame.color_range_max); + bool success = video_format_get_parameters_for_format(cs, range, ConvertVideoFormat(videoConfig.format), + frame.color_matrix, frame.color_range_min, + frame.color_range_max); if (!success) { blog(LOG_ERROR, "Failed to get video format parameters for " @@ -1239,11 +1166,9 @@ static void *CreateDShowInput(obs_data_t *settings, obs_source_t *source) try { dshow = new DShowInput(source, settings); proc_handler_t *ph = obs_source_get_proc_handler(source); - proc_handler_add(ph, "void activate(bool active)", - proc_activate, dshow); + proc_handler_add(ph, "void activate(bool active)", proc_activate, dshow); } catch (const char *error) { - blog(LOG_ERROR, "Could not create device '%s': %s", - obs_source_get_name(source), error); + blog(LOG_ERROR, "Could not create device '%s': %s", obs_source_get_name(source), error); } return dshow; @@ -1269,8 +1194,7 @@ static void GetDShowDefaults(obs_data_t *settings) obs_data_set_default_bool(settings, "active", true); obs_data_set_default_string(settings, COLOR_SPACE, "default"); obs_data_set_default_string(settings, COLOR_RANGE, "default"); - obs_data_set_default_int(settings, AUDIO_OUTPUT_MODE, - (int)AudioMode::Capture); + obs_data_set_default_int(settings, AUDIO_OUTPUT_MODE, (int)AudioMode::Capture); obs_data_set_default_bool(settings, AUTOROTATION, true); obs_data_set_default_bool(settings, HW_DECODE, false); } @@ -1354,8 +1278,7 @@ static const FPSFormat validFPSFormats[] = { {"1", MAKE_DSHOW_FPS(1)}, }; -static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings); +static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings); static bool TryResolution(const VideoDevice &dev, const string &res) { @@ -1366,30 +1289,25 @@ static bool TryResolution(const VideoDevice &dev, const string &res) return ResolutionAvailable(dev, cx, cy); } -static bool SetResolution(obs_properties_t *props, obs_data_t *settings, - const string &res, bool autoselect = false) +static bool SetResolution(obs_properties_t *props, obs_data_t *settings, const string &res, bool autoselect = false) { if (autoselect) - obs_data_set_autoselect_string(settings, RESOLUTION, - res.c_str()); + obs_data_set_autoselect_string(settings, RESOLUTION, res.c_str()); else obs_data_unset_autoselect_value(settings, RESOLUTION); - DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL), - settings); + DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL), settings); if (!autoselect) obs_data_set_string(settings, LAST_RESOLUTION, res.c_str()); return true; } -static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { UNUSED_PARAMETER(p); - PropertiesData *data = - (PropertiesData *)obs_properties_get_param(props); + PropertiesData *data = (PropertiesData *)obs_properties_get_param(props); const char *id; VideoDevice device; @@ -1443,8 +1361,7 @@ static const VideoFormatName videoFormatNames[] = { #endif }; -static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings); +static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings); static size_t AddDevice(obs_property_t *device_list, const string &id) { @@ -1490,11 +1407,9 @@ static bool UpdateDeviceList(obs_property_t *list, const string &id) return true; } -static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { - PropertiesData *data = - (PropertiesData *)obs_properties_get_param(props); + PropertiesData *data = (PropertiesData *)obs_properties_get_param(props); VideoDevice device; string id = obs_data_get_string(settings, VIDEO_DEVICE_ID); @@ -1533,8 +1448,7 @@ static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p, return true; } -static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p, - void *data) +static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p, void *data) { DShowInput *input = reinterpret_cast(data); input->QueueAction(Action::ConfigVideo); @@ -1555,8 +1469,7 @@ static bool VideoConfigClicked(obs_properties_t *props, obs_property_t *p, return false; }*/ -static bool CrossbarConfigClicked(obs_properties_t *props, obs_property_t *p, - void *data) +static bool CrossbarConfigClicked(obs_properties_t *props, obs_property_t *p, void *data) { DShowInput *input = reinterpret_cast(data); input->QueueAction(Action::ConfigCrossbar1); @@ -1596,8 +1509,7 @@ static bool AddDevice(obs_property_t *device_list, const VideoDevice &device) return true; } -static bool AddAudioDevice(obs_property_t *device_list, - const AudioDevice &device) +static bool AddAudioDevice(obs_property_t *device_list, const AudioDevice &device) { DStr name, path, device_id; @@ -1621,8 +1533,7 @@ static void PropertiesDataDestroy(void *data) delete reinterpret_cast(data); } -static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { int val = (int)obs_data_get_int(settings, RES_TYPE); bool enabled = (val != ResType_Preferred); @@ -1672,8 +1583,7 @@ static DStr GetFPSName(long long interval) return name; } -static void UpdateFPS(VideoDevice &device, VideoFormat format, - long long interval, int cx, int cy, +static void UpdateFPS(VideoDevice &device, VideoFormat format, long long interval, int cx, int cy, obs_properties_t *props) { obs_property_t *list = obs_properties_get(props, FRAME_INTERVAL); @@ -1683,16 +1593,14 @@ static void UpdateFPS(VideoDevice &device, VideoFormat format, obs_property_list_add_int(list, TEXT_FPS_MATCHING, FPS_MATCHING); obs_property_list_add_int(list, TEXT_FPS_HIGHEST, FPS_HIGHEST); - bool interval_added = interval == FPS_HIGHEST || - interval == FPS_MATCHING; + bool interval_added = interval == FPS_HIGHEST || interval == FPS_MATCHING; for (const FPSFormat &fps_format : validFPSFormats) { bool video_format_match = false; long long format_interval = fps_format.interval; - bool available = CapsMatch( - device, ResolutionMatcher(cx, cy), - VideoFormatMatcher(format, video_format_match), - FrameRateMatcher(format_interval)); + bool available = CapsMatch(device, ResolutionMatcher(cx, cy), + VideoFormatMatcher(format, video_format_match), + FrameRateMatcher(format_interval)); if (!available && interval != fps_format.interval) continue; @@ -1700,16 +1608,14 @@ static void UpdateFPS(VideoDevice &device, VideoFormat format, if (interval == fps_format.interval) interval_added = true; - size_t idx = obs_property_list_add_int(list, fps_format.text, - fps_format.interval); + size_t idx = obs_property_list_add_int(list, fps_format.text, fps_format.interval); obs_property_list_item_disable(list, idx, !available); } if (interval_added) return; - size_t idx = - obs_property_list_add_int(list, GetFPSName(interval), interval); + size_t idx = obs_property_list_add_int(list, GetFPSName(interval), interval); obs_property_list_item_disable(list, idx, true); } @@ -1728,19 +1634,16 @@ static DStr GetVideoFormatName(VideoFormat format) return name; } -static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_, int cx, - int cy, long long interval, +static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_, int cx, int cy, long long interval, obs_properties_t *props) { set formats = {VideoFormat::Any}; - auto format_gatherer = - [&formats](const VideoInfo &info) mutable -> bool { + auto format_gatherer = [&formats](const VideoInfo &info) mutable -> bool { formats.insert(info.format); return false; }; - CapsMatch(device, ResolutionMatcher(cx, cy), FrameRateMatcher(interval), - format_gatherer); + CapsMatch(device, ResolutionMatcher(cx, cy), FrameRateMatcher(interval), format_gatherer); obs_property_t *list = obs_properties_get(props, VIDEO_FORMAT); obs_property_list_clear(list); @@ -1755,17 +1658,14 @@ static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_, int cx, if (format.format == format_) format_added = true; - size_t idx = obs_property_list_add_int( - list, obs_module_text(format.name), - (long long)format.format); + size_t idx = obs_property_list_add_int(list, obs_module_text(format.name), (long long)format.format); obs_property_list_item_disable(list, idx, !available); } if (format_added) return; - size_t idx = obs_property_list_add_int( - list, GetVideoFormatName(format_), (long long)format_); + size_t idx = obs_property_list_add_int(list, GetVideoFormatName(format_), (long long)format_); obs_property_list_item_disable(list, idx, true); } @@ -1797,13 +1697,11 @@ static bool UpdateFPS(long long interval, obs_property_t *list) return true; } -static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { long long val = obs_data_get_int(settings, FRAME_INTERVAL); - PropertiesData *data = - (PropertiesData *)obs_properties_get_param(props); + PropertiesData *data = (PropertiesData *)obs_properties_get_param(props); const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID); VideoDevice device; @@ -1824,19 +1722,15 @@ static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, if (val == FPS_MATCHING) val = GetOBSFPS(); - VideoFormat format = - (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); + VideoFormat format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); bool video_format_matches = false; long long best_interval = numeric_limits::max(); - bool frameRateSupported = - CapsMatch(device, ResolutionMatcher(cx, cy), - VideoFormatMatcher(format, video_format_matches), - ClosestFrameRateSelector(val, best_interval), - FrameRateMatcher(val)); + bool frameRateSupported = CapsMatch(device, ResolutionMatcher(cx, cy), + VideoFormatMatcher(format, video_format_matches), + ClosestFrameRateSelector(val, best_interval), FrameRateMatcher(val)); - if (video_format_matches && !frameRateSupported && - best_interval != val) { + if (video_format_matches && !frameRateSupported && best_interval != val) { long long listed_val = 0; for (const FPSFormat &format : validFPSFormats) { long long diff = llabs(format.interval - best_interval); @@ -1847,8 +1741,7 @@ static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, } if (listed_val != val) { - obs_data_set_autoselect_int(settings, FRAME_INTERVAL, - listed_val); + obs_data_set_autoselect_int(settings, FRAME_INTERVAL, listed_val); val = listed_val; } @@ -1889,16 +1782,13 @@ static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list) return true; } -static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { - PropertiesData *data = - (PropertiesData *)obs_properties_get_param(props); + PropertiesData *data = (PropertiesData *)obs_properties_get_param(props); const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID); VideoDevice device; - VideoFormat curFormat = - (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); + VideoFormat curFormat = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); if (!data->GetDevice(device, id)) return UpdateVideoFormats(curFormat, p); @@ -1917,8 +1807,7 @@ static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p, return true; } -static bool CustomAudioClicked(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool CustomAudioClicked(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { bool useCustomAudio = obs_data_get_bool(settings, USE_CUSTOM_AUDIO); p = obs_properties_get(props, AUDIO_DEVICE_ID); @@ -1951,9 +1840,7 @@ static obs_properties_t *GetDShowProperties(void *obj) obs_properties_set_param(ppts, data, PropertiesDataDestroy); - obs_property_t *p = obs_properties_add_list(ppts, VIDEO_DEVICE_ID, - TEXT_DEVICE, - OBS_COMBO_TYPE_LIST, + obs_property_t *p = obs_properties_add_list(ppts, VIDEO_DEVICE_ID, TEXT_DEVICE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(p, DeviceSelectionChanged); @@ -1968,69 +1855,53 @@ static obs_properties_t *GetDShowProperties(void *obj) activateText = TEXT_DEACTIVATE; } - obs_properties_add_button(ppts, "activate", activateText, - ActivateClicked); - obs_properties_add_button(ppts, "video_config", TEXT_CONFIG_VIDEO, - VideoConfigClicked); - obs_properties_add_button(ppts, "xbar_config", TEXT_CONFIG_XBAR, - CrossbarConfigClicked); + obs_properties_add_button(ppts, "activate", activateText, ActivateClicked); + obs_properties_add_button(ppts, "video_config", TEXT_CONFIG_VIDEO, VideoConfigClicked); + obs_properties_add_button(ppts, "xbar_config", TEXT_CONFIG_XBAR, CrossbarConfigClicked); obs_properties_add_bool(ppts, DEACTIVATE_WNS, TEXT_DWNS); /* ------------------------------------- */ /* video settings */ - p = obs_properties_add_list(ppts, RES_TYPE, TEXT_RES_FPS_TYPE, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(ppts, RES_TYPE, TEXT_RES_FPS_TYPE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(p, ResTypeChanged); obs_property_list_add_int(p, TEXT_PREFERRED_RES, ResType_Preferred); obs_property_list_add_int(p, TEXT_CUSTOM_RES, ResType_Custom); - p = obs_properties_add_list(ppts, RESOLUTION, TEXT_RESOLUTION, - OBS_COMBO_TYPE_EDITABLE, + p = obs_properties_add_list(ppts, RESOLUTION, TEXT_RESOLUTION, OBS_COMBO_TYPE_EDITABLE, OBS_COMBO_FORMAT_STRING); obs_property_set_modified_callback(p, DeviceResolutionChanged); - p = obs_properties_add_list(ppts, FRAME_INTERVAL, "FPS", - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(ppts, FRAME_INTERVAL, "FPS", OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(p, DeviceIntervalChanged); - p = obs_properties_add_list(ppts, VIDEO_FORMAT, TEXT_VIDEO_FORMAT, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + p = obs_properties_add_list(ppts, VIDEO_FORMAT, TEXT_VIDEO_FORMAT, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); obs_property_set_modified_callback(p, VideoFormatChanged); - p = obs_properties_add_list(ppts, COLOR_SPACE, TEXT_COLOR_SPACE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, COLOR_SPACE, TEXT_COLOR_SPACE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, TEXT_COLOR_DEFAULT, "default"); obs_property_list_add_string(p, TEXT_COLOR_709, "709"); obs_property_list_add_string(p, TEXT_COLOR_601, "601"); obs_property_list_add_string(p, TEXT_COLOR_2100PQ, "2100PQ"); obs_property_list_add_string(p, TEXT_COLOR_2100HLG, "2100HLG"); - p = obs_properties_add_list(ppts, COLOR_RANGE, TEXT_COLOR_RANGE, - OBS_COMBO_TYPE_LIST, - OBS_COMBO_FORMAT_STRING); + p = obs_properties_add_list(ppts, COLOR_RANGE, TEXT_COLOR_RANGE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); obs_property_list_add_string(p, TEXT_RANGE_DEFAULT, "default"); obs_property_list_add_string(p, TEXT_RANGE_PARTIAL, "partial"); obs_property_list_add_string(p, TEXT_RANGE_FULL, "full"); - p = obs_properties_add_list(ppts, BUFFERING_VAL, TEXT_BUFFERING, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(p, TEXT_BUFFERING_AUTO, - (int64_t)BufferingType::Auto); - obs_property_list_add_int(p, TEXT_BUFFERING_ON, - (int64_t)BufferingType::On); - obs_property_list_add_int(p, TEXT_BUFFERING_OFF, - (int64_t)BufferingType::Off); + p = obs_properties_add_list(ppts, BUFFERING_VAL, TEXT_BUFFERING, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(p, TEXT_BUFFERING_AUTO, (int64_t)BufferingType::Auto); + obs_property_list_add_int(p, TEXT_BUFFERING_ON, (int64_t)BufferingType::On); + obs_property_list_add_int(p, TEXT_BUFFERING_OFF, (int64_t)BufferingType::Off); - obs_property_set_long_description(p, - obs_module_text("Buffering.ToolTip")); + obs_property_set_long_description(p, obs_module_text("Buffering.ToolTip")); obs_properties_add_bool(ppts, FLIP_IMAGE, TEXT_FLIP_IMAGE); @@ -2043,14 +1914,11 @@ static obs_properties_t *GetDShowProperties(void *obj) Device::EnumAudioDevices(data->audioDevices); - p = obs_properties_add_list(ppts, AUDIO_OUTPUT_MODE, TEXT_AUDIO_MODE, - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(p, TEXT_MODE_CAPTURE, - (int64_t)AudioMode::Capture); - obs_property_list_add_int(p, TEXT_MODE_DSOUND, - (int64_t)AudioMode::DirectSound); - obs_property_list_add_int(p, TEXT_MODE_WAVEOUT, - (int64_t)AudioMode::WaveOut); + p = obs_properties_add_list(ppts, AUDIO_OUTPUT_MODE, TEXT_AUDIO_MODE, OBS_COMBO_TYPE_LIST, + OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(p, TEXT_MODE_CAPTURE, (int64_t)AudioMode::Capture); + obs_property_list_add_int(p, TEXT_MODE_DSOUND, (int64_t)AudioMode::DirectSound); + obs_property_list_add_int(p, TEXT_MODE_WAVEOUT, (int64_t)AudioMode::WaveOut); if (!data->audioDevices.size()) return ppts; @@ -2059,8 +1927,7 @@ static obs_properties_t *GetDShowProperties(void *obj) obs_property_set_modified_callback(p, CustomAudioClicked); - p = obs_properties_add_list(ppts, AUDIO_DEVICE_ID, TEXT_AUDIO_DEVICE, - OBS_COMBO_TYPE_LIST, + p = obs_properties_add_list(ppts, AUDIO_DEVICE_ID, TEXT_AUDIO_DEVICE, OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); for (const AudioDevice &device : data->audioDevices) @@ -2119,8 +1986,7 @@ void RegisterDShowSource() obs_source_info info = {}; info.id = "dshow_input"; info.type = OBS_SOURCE_TYPE_INPUT; - info.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | - OBS_SOURCE_ASYNC | OBS_SOURCE_DO_NOT_DUPLICATE; + info.output_flags = OBS_SOURCE_VIDEO | OBS_SOURCE_AUDIO | OBS_SOURCE_ASYNC | OBS_SOURCE_DO_NOT_DUPLICATE; info.show = ShowDShowInput; info.hide = HideDShowInput; info.get_name = GetDShowInputName; diff --git a/plugins/win-wasapi/enum-wasapi.cpp b/plugins/win-wasapi/enum-wasapi.cpp index 11f3f0d19..697834390 100644 --- a/plugins/win-wasapi/enum-wasapi.cpp +++ b/plugins/win-wasapi/enum-wasapi.cpp @@ -24,12 +24,9 @@ string GetDeviceName(IMMDevice *device) size_t len = wcslen(nameVar.pwszVal); size_t size; - size = os_wcs_to_utf8(nameVar.pwszVal, len, nullptr, - 0) + - 1; + size = os_wcs_to_utf8(nameVar.pwszVal, len, nullptr, 0) + 1; device_name.resize(size); - os_wcs_to_utf8(nameVar.pwszVal, len, &device_name[0], - size); + os_wcs_to_utf8(nameVar.pwszVal, len, &device_name[0], size); PropVariantClear(&nameVar); } } @@ -44,15 +41,12 @@ static void GetWASAPIAudioDevices_(vector &devices, bool input) UINT count; HRESULT res; - res = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, - __uuidof(IMMDeviceEnumerator), + res = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void **)enumerator.Assign()); if (FAILED(res)) throw HRError("Failed to create enumerator", res); - res = enumerator->EnumAudioEndpoints(input ? eCapture : eRender, - DEVICE_STATE_ACTIVE, - collection.Assign()); + res = enumerator->EnumAudioEndpoints(input ? eCapture : eRender, DEVICE_STATE_ACTIVE, collection.Assign()); if (FAILED(res)) throw HRError("Failed to enumerate devices", res); @@ -93,7 +87,6 @@ void GetWASAPIAudioDevices(vector &devices, bool input) GetWASAPIAudioDevices_(devices, input); } catch (HRError &error) { - blog(LOG_WARNING, "[GetWASAPIAudioDevices] %s: %lX", error.str, - error.hr); + blog(LOG_WARNING, "[GetWASAPIAudioDevices] %s: %lX", error.str, error.hr); } } diff --git a/plugins/win-wasapi/plugin-main.cpp b/plugins/win-wasapi/plugin-main.cpp index 10c005f4e..6278e8ccc 100644 --- a/plugins/win-wasapi/plugin-main.cpp +++ b/plugins/win-wasapi/plugin-main.cpp @@ -46,8 +46,7 @@ bool obs_module_load(void) minimum.minor = 0; minimum.build = 19041; minimum.revis = 0; - const bool process_filter_supported = - win_version_compare(&ver, &minimum) >= 0; + const bool process_filter_supported = win_version_compare(&ver, &minimum) >= 0; RegisterWASAPIInput(); RegisterWASAPIDeviceOutput(); @@ -55,8 +54,7 @@ bool obs_module_load(void) RegisterWASAPIProcessOutput(); notify = new WASAPINotify(); - notify->AddDefaultDeviceChangedCallback( - obs_current_module(), default_device_changed_callback); + notify->AddDefaultDeviceChangedCallback(obs_current_module(), default_device_changed_callback); return true; } diff --git a/plugins/win-wasapi/wasapi-notify.cpp b/plugins/win-wasapi/wasapi-notify.cpp index 33d96935a..529dc4ae0 100644 --- a/plugins/win-wasapi/wasapi-notify.cpp +++ b/plugins/win-wasapi/wasapi-notify.cpp @@ -10,15 +10,9 @@ class NotificationClient : public IMMNotificationClient { WASAPINotifyDefaultDeviceChangedCallback cb; public: - NotificationClient(WASAPINotifyDefaultDeviceChangedCallback cb) : cb(cb) - { - assert(cb); - } + NotificationClient(WASAPINotifyDefaultDeviceChangedCallback cb) : cb(cb) { assert(cb); } - STDMETHODIMP_(ULONG) AddRef() - { - return (ULONG)os_atomic_inc_long(&refs); - } + STDMETHODIMP_(ULONG) AddRef() { return (ULONG)os_atomic_inc_long(&refs); } STDMETHODIMP_(ULONG) STDMETHODCALLTYPE Release() { @@ -49,13 +43,9 @@ public: STDMETHODIMP OnDeviceStateChanged(LPCWSTR, DWORD) { return S_OK; } - STDMETHODIMP OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY) - { - return S_OK; - } + STDMETHODIMP OnPropertyValueChanged(LPCWSTR, const PROPERTYKEY) { return S_OK; } - STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, - LPCWSTR id) + STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR id) { if (cb && id) cb(flow, role, id); @@ -66,17 +56,13 @@ public: WASAPINotify::WASAPINotify() { - HRESULT res = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, - CLSCTX_ALL, - __uuidof(IMMDeviceEnumerator), + HRESULT res = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (LPVOID *)enumerator.Assign()); if (SUCCEEDED(res)) { - notificationClient = new NotificationClient( - std::bind(&WASAPINotify::OnDefaultDeviceChanged, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)); - enumerator->RegisterEndpointNotificationCallback( - notificationClient); + notificationClient = new NotificationClient(std::bind(&WASAPINotify::OnDefaultDeviceChanged, this, + std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)); + enumerator->RegisterEndpointNotificationCallback(notificationClient); } else { enumerator.Clear(); } @@ -85,16 +71,14 @@ WASAPINotify::WASAPINotify() WASAPINotify::~WASAPINotify() { if (enumerator) { - enumerator->UnregisterEndpointNotificationCallback( - notificationClient); + enumerator->UnregisterEndpointNotificationCallback(notificationClient); enumerator.Clear(); } notificationClient.Clear(); } -void WASAPINotify::AddDefaultDeviceChangedCallback( - void *handle, WASAPINotifyDefaultDeviceChangedCallback cb) +void WASAPINotify::AddDefaultDeviceChangedCallback(void *handle, WASAPINotifyDefaultDeviceChangedCallback cb) { if (!handle) return; @@ -112,8 +96,7 @@ void WASAPINotify::RemoveDefaultDeviceChangedCallback(void *handle) defaultDeviceChangedCallbacks.erase(handle); } -void WASAPINotify::OnDefaultDeviceChanged(EDataFlow flow, ERole role, - LPCWSTR id) +void WASAPINotify::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR id) { std::lock_guard l(mutex); for (const auto &cb : defaultDeviceChangedCallbacks) diff --git a/plugins/win-wasapi/wasapi-notify.hpp b/plugins/win-wasapi/wasapi-notify.hpp index e82fc1520..1e991ba49 100644 --- a/plugins/win-wasapi/wasapi-notify.hpp +++ b/plugins/win-wasapi/wasapi-notify.hpp @@ -7,8 +7,7 @@ #include #include -typedef std::function - WASAPINotifyDefaultDeviceChangedCallback; +typedef std::function WASAPINotifyDefaultDeviceChangedCallback; class NotificationClient; @@ -17,8 +16,7 @@ public: WASAPINotify(); ~WASAPINotify(); - void AddDefaultDeviceChangedCallback( - void *handle, WASAPINotifyDefaultDeviceChangedCallback cb); + void AddDefaultDeviceChangedCallback(void *handle, WASAPINotifyDefaultDeviceChangedCallback cb); void RemoveDefaultDeviceChangedCallback(void *handle); private: @@ -29,6 +27,5 @@ private: ComPtr enumerator; ComPtr notificationClient; - std::unordered_map - defaultDeviceChangedCallbacks; + std::unordered_map defaultDeviceChangedCallbacks; }; diff --git a/plugins/win-wasapi/win-wasapi.cpp b/plugins/win-wasapi/win-wasapi.cpp index d3cbae5dd..e68d7c39b 100644 --- a/plugins/win-wasapi/win-wasapi.cpp +++ b/plugins/win-wasapi/win-wasapi.cpp @@ -32,34 +32,23 @@ using namespace std; WASAPINotify *GetNotify(); static void GetWASAPIDefaults(obs_data_t *settings); -#define OBS_KSAUDIO_SPEAKER_4POINT1 \ - (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY) +#define OBS_KSAUDIO_SPEAKER_4POINT1 (KSAUDIO_SPEAKER_SURROUND | SPEAKER_LOW_FREQUENCY) -typedef HRESULT(STDAPICALLTYPE *PFN_ActivateAudioInterfaceAsync)( - LPCWSTR, REFIID, PROPVARIANT *, - IActivateAudioInterfaceCompletionHandler *, - IActivateAudioInterfaceAsyncOperation **); +typedef HRESULT(STDAPICALLTYPE *PFN_ActivateAudioInterfaceAsync)(LPCWSTR, REFIID, PROPVARIANT *, + IActivateAudioInterfaceCompletionHandler *, + IActivateAudioInterfaceAsyncOperation **); typedef HRESULT(STDAPICALLTYPE *PFN_RtwqUnlockWorkQueue)(DWORD); -typedef HRESULT(STDAPICALLTYPE *PFN_RtwqLockSharedWorkQueue)(PCWSTR usageClass, - LONG basePriority, - DWORD *taskId, +typedef HRESULT(STDAPICALLTYPE *PFN_RtwqLockSharedWorkQueue)(PCWSTR usageClass, LONG basePriority, DWORD *taskId, DWORD *id); -typedef HRESULT(STDAPICALLTYPE *PFN_RtwqCreateAsyncResult)(IUnknown *, - IRtwqAsyncCallback *, - IUnknown *, +typedef HRESULT(STDAPICALLTYPE *PFN_RtwqCreateAsyncResult)(IUnknown *, IRtwqAsyncCallback *, IUnknown *, IRtwqAsyncResult **); -typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWorkItem)(DWORD, LONG, - IRtwqAsyncResult *); -typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWaitingWorkItem)(HANDLE, LONG, - IRtwqAsyncResult *, - RTWQWORKITEM_KEY *); +typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWorkItem)(DWORD, LONG, IRtwqAsyncResult *); +typedef HRESULT(STDAPICALLTYPE *PFN_RtwqPutWaitingWorkItem)(HANDLE, LONG, IRtwqAsyncResult *, RTWQWORKITEM_KEY *); class WASAPIActivateAudioInterfaceCompletionHandler - : public Microsoft::WRL::RuntimeClass< - Microsoft::WRL::RuntimeClassFlags, - Microsoft::WRL::FtmBase, - IActivateAudioInterfaceCompletionHandler> { + : public Microsoft::WRL::RuntimeClass, + Microsoft::WRL::FtmBase, IActivateAudioInterfaceCompletionHandler> { IUnknown *unknown; HRESULT activationResult; WinHandle activationSignal; @@ -69,13 +58,11 @@ public: HRESULT GetActivateResult(IAudioClient **client); private: - virtual HRESULT STDMETHODCALLTYPE ActivateCompleted( - IActivateAudioInterfaceAsyncOperation *activateOperation) - override final; + virtual HRESULT STDMETHODCALLTYPE + ActivateCompleted(IActivateAudioInterfaceAsyncOperation *activateOperation) override final; }; -WASAPIActivateAudioInterfaceCompletionHandler:: - WASAPIActivateAudioInterfaceCompletionHandler() +WASAPIActivateAudioInterfaceCompletionHandler::WASAPIActivateAudioInterfaceCompletionHandler() { activationSignal = CreateEvent(nullptr, false, false, nullptr); if (!activationSignal.Valid()) @@ -83,8 +70,7 @@ WASAPIActivateAudioInterfaceCompletionHandler:: } HRESULT -WASAPIActivateAudioInterfaceCompletionHandler::GetActivateResult( - IAudioClient **client) +WASAPIActivateAudioInterfaceCompletionHandler::GetActivateResult(IAudioClient **client) { WaitForSingleObject(activationSignal, INFINITE); *client = static_cast(unknown); @@ -123,8 +109,7 @@ public: { HRESULT hr = E_NOINTERFACE; - if (riid == __uuidof(IRtwqAsyncCallback) || - riid == __uuidof(IUnknown)) { + if (riid == __uuidof(IRtwqAsyncCallback) || riid == __uuidof(IUnknown)) { *ppvObject = this; AddRef(); hr = S_OK; @@ -190,10 +175,7 @@ class WASAPISource { class CallbackStartCapture : public ARtwqAsyncCallback { public: - CallbackStartCapture(WASAPISource *source) - : ARtwqAsyncCallback(source) - { - } + CallbackStartCapture(WASAPISource *source) : ARtwqAsyncCallback(source) {} STDMETHOD(Invoke) (IRtwqAsyncResult *) override @@ -207,10 +189,7 @@ class WASAPISource { class CallbackSampleReady : public ARtwqAsyncCallback { public: - CallbackSampleReady(WASAPISource *source) - : ARtwqAsyncCallback(source) - { - } + CallbackSampleReady(WASAPISource *source) : ARtwqAsyncCallback(source) {} STDMETHOD(Invoke) (IRtwqAsyncResult *) override @@ -223,10 +202,7 @@ class WASAPISource { class CallbackRestart : public ARtwqAsyncCallback { public: - CallbackRestart(WASAPISource *source) - : ARtwqAsyncCallback(source) - { - } + CallbackRestart(WASAPISource *source) : ARtwqAsyncCallback(source) {} STDMETHOD(Invoke) (IRtwqAsyncResult *) override @@ -262,21 +238,15 @@ class WASAPISource { void Start(); void Stop(); - static ComPtr InitDevice(IMMDeviceEnumerator *enumerator, - bool isDefaultDevice, - SourceType type, + static ComPtr InitDevice(IMMDeviceEnumerator *enumerator, bool isDefaultDevice, SourceType type, const string device_id); - static ComPtr InitClient( - IMMDevice *device, SourceType type, DWORD process_id, - PFN_ActivateAudioInterfaceAsync activate_audio_interface_async, - speaker_layout &speakers, audio_format &format, - uint32_t &sampleRate); - static void InitFormat(const WAVEFORMATEX *wfex, - enum speaker_layout &speakers, - enum audio_format &format, uint32_t &sampleRate); + static ComPtr InitClient(IMMDevice *device, SourceType type, DWORD process_id, + PFN_ActivateAudioInterfaceAsync activate_audio_interface_async, + speaker_layout &speakers, audio_format &format, uint32_t &sampleRate); + static void InitFormat(const WAVEFORMATEX *wfex, enum speaker_layout &speakers, enum audio_format &format, + uint32_t &sampleRate); static void ClearBuffer(IMMDevice *device); - static ComPtr InitCapture(IAudioClient *client, - HANDLE receiveSignal); + static ComPtr InitCapture(IAudioClient *client, HANDLE receiveSignal); void Initialize(); bool TryInitialize(); @@ -296,8 +266,7 @@ class WASAPISource { void LogSettings(); public: - WASAPISource(obs_data_t *settings, obs_source_t *source_, - SourceType type); + WASAPISource(obs_data_t *settings, obs_source_t *source_, SourceType type); ~WASAPISource(); void Update(obs_data_t *settings); @@ -322,8 +291,7 @@ public: } }; -WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, - SourceType type) +WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, SourceType type) : source(source_), sourceType(type), startCapture(this), @@ -333,8 +301,7 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, mmdevapi_module = LoadLibrary(L"Mmdevapi"); if (mmdevapi_module) { activate_audio_interface_async = - (PFN_ActivateAudioInterfaceAsync)GetProcAddress( - mmdevapi_module, "ActivateAudioInterfaceAsync"); + (PFN_ActivateAudioInterfaceAsync)GetProcAddress(mmdevapi_module, "ActivateAudioInterfaceAsync"); } UpdateSettings(BuildUpdateParams(settings)); @@ -372,9 +339,8 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, if (!reconnectSignal.Valid()) throw "Could not create reconnect signal"; - HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, - CLSCTX_ALL, - IID_PPV_ARGS(enumerator.Assign())); + HRESULT hr = + CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(enumerator.Assign())); if (FAILED(hr)) throw HRError("Failed to create enumerator", hr); @@ -394,72 +360,49 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, rtwq_supported = rtwq_module != NULL; if (rtwq_supported) { - rtwq_unlock_work_queue = - (PFN_RtwqUnlockWorkQueue)GetProcAddress( - rtwq_module, "RtwqUnlockWorkQueue"); + rtwq_unlock_work_queue = (PFN_RtwqUnlockWorkQueue)GetProcAddress(rtwq_module, "RtwqUnlockWorkQueue"); rtwq_lock_shared_work_queue = - (PFN_RtwqLockSharedWorkQueue)GetProcAddress( - rtwq_module, "RtwqLockSharedWorkQueue"); + (PFN_RtwqLockSharedWorkQueue)GetProcAddress(rtwq_module, "RtwqLockSharedWorkQueue"); rtwq_create_async_result = - (PFN_RtwqCreateAsyncResult)GetProcAddress( - rtwq_module, "RtwqCreateAsyncResult"); - rtwq_put_work_item = (PFN_RtwqPutWorkItem)GetProcAddress( - rtwq_module, "RtwqPutWorkItem"); + (PFN_RtwqCreateAsyncResult)GetProcAddress(rtwq_module, "RtwqCreateAsyncResult"); + rtwq_put_work_item = (PFN_RtwqPutWorkItem)GetProcAddress(rtwq_module, "RtwqPutWorkItem"); rtwq_put_waiting_work_item = - (PFN_RtwqPutWaitingWorkItem)GetProcAddress( - rtwq_module, "RtwqPutWaitingWorkItem"); + (PFN_RtwqPutWaitingWorkItem)GetProcAddress(rtwq_module, "RtwqPutWaitingWorkItem"); try { - hr = rtwq_create_async_result(nullptr, &startCapture, - nullptr, - &startCaptureAsyncResult); + hr = rtwq_create_async_result(nullptr, &startCapture, nullptr, &startCaptureAsyncResult); if (FAILED(hr)) { - throw HRError( - "Could not create startCaptureAsyncResult", - hr); + throw HRError("Could not create startCaptureAsyncResult", hr); } - hr = rtwq_create_async_result(nullptr, &sampleReady, - nullptr, - &sampleReadyAsyncResult); + hr = rtwq_create_async_result(nullptr, &sampleReady, nullptr, &sampleReadyAsyncResult); if (FAILED(hr)) { - throw HRError( - "Could not create sampleReadyAsyncResult", - hr); + throw HRError("Could not create sampleReadyAsyncResult", hr); } - hr = rtwq_create_async_result(nullptr, &restart, - nullptr, - &restartAsyncResult); + hr = rtwq_create_async_result(nullptr, &restart, nullptr, &restartAsyncResult); if (FAILED(hr)) { - throw HRError( - "Could not create restartAsyncResult", - hr); + throw HRError("Could not create restartAsyncResult", hr); } DWORD taskId = 0; DWORD id = 0; - hr = rtwq_lock_shared_work_queue(L"Capture", 0, &taskId, - &id); + hr = rtwq_lock_shared_work_queue(L"Capture", 0, &taskId, &id); if (FAILED(hr)) { - throw HRError("RtwqLockSharedWorkQueue failed", - hr); + throw HRError("RtwqLockSharedWorkQueue failed", hr); } startCapture.SetQueueId(id); sampleReady.SetQueueId(id); restart.SetQueueId(id); } catch (HRError &err) { - blog(LOG_ERROR, "RTWQ setup failed: %s (0x%08X)", - err.str, err.hr); + blog(LOG_ERROR, "RTWQ setup failed: %s (0x%08X)", err.str, err.hr); rtwq_supported = false; } } if (!rtwq_supported) { - captureThread = CreateThread(nullptr, 0, - WASAPISource::CaptureThread, this, - 0, nullptr); + captureThread = CreateThread(nullptr, 0, WASAPISource::CaptureThread, this, 0, nullptr); if (!captureThread.Valid()) { throw "Failed to create capture thread"; } @@ -467,11 +410,9 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, auto notify = GetNotify(); if (notify) { - notify->AddDefaultDeviceChangedCallback( - this, - std::bind(&WASAPISource::SetDefaultDevice, this, - std::placeholders::_1, std::placeholders::_2, - std::placeholders::_3)); + notify->AddDefaultDeviceChangedCallback(this, std::bind(&WASAPISource::SetDefaultDevice, this, + std::placeholders::_1, std::placeholders::_2, + std::placeholders::_3)); } Start(); @@ -480,8 +421,7 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, void WASAPISource::Start() { if (rtwq_supported) { - rtwq_put_work_item(startCapture.GetQueueId(), 0, - startCaptureAsyncResult); + rtwq_put_work_item(startCapture.GetQueueId(), 0, startCaptureAsyncResult); } else { SetEvent(initSignal); } @@ -532,23 +472,18 @@ WASAPISource::UpdateParams WASAPISource::BuildUpdateParams(obs_data_t *settings) { WASAPISource::UpdateParams params; params.device_id = obs_data_get_string(settings, OPT_DEVICE_ID); - params.useDeviceTiming = - obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING); - params.isDefaultDevice = - _strcmpi(params.device_id.c_str(), "default") == 0; - params.priority = - (window_priority)obs_data_get_int(settings, "priority"); + params.useDeviceTiming = obs_data_get_bool(settings, OPT_USE_DEVICE_TIMING); + params.isDefaultDevice = _strcmpi(params.device_id.c_str(), "default") == 0; + params.priority = (window_priority)obs_data_get_int(settings, "priority"); params.window_class.clear(); params.title.clear(); params.executable.clear(); if (sourceType != SourceType::Input) { - const char *const window = - obs_data_get_string(settings, OPT_WINDOW); + const char *const window = obs_data_get_string(settings, OPT_WINDOW); char *window_class = nullptr; char *title = nullptr; char *executable = nullptr; - ms_build_window_strings(window, &window_class, &title, - &executable); + ms_build_window_strings(window, &window_class, &title, &executable); if (window_class) { params.window_class = window_class; bfree(window_class); @@ -586,15 +521,14 @@ void WASAPISource::LogSettings() "\ttitle: %s\n" "\tclass: %s\n" "\tpriority: %d", - obs_source_get_name(source), executable.c_str(), - title.c_str(), window_class.c_str(), (int)priority); + obs_source_get_name(source), executable.c_str(), title.c_str(), window_class.c_str(), + (int)priority); } else { blog(LOG_INFO, "[win-wasapi: '%s'] update settings:\n" "\tdevice id: %s\n" "\tuse device timing: %d", - obs_source_get_name(source), device_id.c_str(), - (int)useDeviceTiming); + obs_source_get_name(source), device_id.c_str(), (int)useDeviceTiming); } } @@ -602,13 +536,10 @@ void WASAPISource::Update(obs_data_t *settings) { UpdateParams params = BuildUpdateParams(settings); - const bool restart = - (sourceType == SourceType::ProcessOutput) - ? ((priority != params.priority) || - (window_class != params.window_class) || - (title != params.title) || - (executable != params.executable)) - : (device_id.compare(params.device_id) != 0); + const bool restart = (sourceType == SourceType::ProcessOutput) + ? ((priority != params.priority) || (window_class != params.window_class) || + (title != params.title) || (executable != params.executable)) + : (device_id.compare(params.device_id) != 0); UpdateSettings(std::move(params)); LogSettings(); @@ -621,13 +552,10 @@ void WASAPISource::OnWindowChanged(obs_data_t *settings) { UpdateParams params = BuildUpdateParams(settings); - const bool restart = - (sourceType == SourceType::ProcessOutput) - ? ((priority != params.priority) || - (window_class != params.window_class) || - (title != params.title) || - (executable != params.executable)) - : (device_id.compare(params.device_id) != 0); + const bool restart = (sourceType == SourceType::ProcessOutput) + ? ((priority != params.priority) || (window_class != params.window_class) || + (title != params.title) || (executable != params.executable)) + : (device_id.compare(params.device_id) != 0); UpdateSettings(std::move(params)); @@ -639,9 +567,7 @@ void WASAPISource::Activate() { if (!reconnectThread.Valid()) { ResetEvent(reconnectExitSignal); - reconnectThread = CreateThread(nullptr, 0, - WASAPISource::ReconnectThread, - this, 0, nullptr); + reconnectThread = CreateThread(nullptr, 0, WASAPISource::ReconnectThread, this, 0, nullptr); } } @@ -654,18 +580,15 @@ void WASAPISource::Deactivate() } } -ComPtr WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator, - bool isDefaultDevice, - SourceType type, +ComPtr WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator, bool isDefaultDevice, SourceType type, const string device_id) { ComPtr device; if (isDefaultDevice) { const bool input = type == SourceType::Input; - HRESULT res = enumerator->GetDefaultAudioEndpoint( - input ? eCapture : eRender, - input ? eCommunications : eConsole, device.Assign()); + HRESULT res = enumerator->GetDefaultAudioEndpoint(input ? eCapture : eRender, + input ? eCommunications : eConsole, device.Assign()); if (FAILED(res)) throw HRError("Failed GetDefaultAudioEndpoint", res); } else { @@ -674,8 +597,7 @@ ComPtr WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator, if (!w_id) throw "Failed to widen device id string"; - const HRESULT res = - enumerator->GetDevice(w_id, device.Assign()); + const HRESULT res = enumerator->GetDevice(w_id, device.Assign()); bfree(w_id); @@ -708,11 +630,9 @@ static DWORD GetSpeakerChannelMask(speaker_layout layout) return (DWORD)layout; } -ComPtr WASAPISource::InitClient( - IMMDevice *device, SourceType type, DWORD process_id, - PFN_ActivateAudioInterfaceAsync activate_audio_interface_async, - speaker_layout &speakers, audio_format &format, - uint32_t &samples_per_sec) +ComPtr WASAPISource::InitClient(IMMDevice *device, SourceType type, DWORD process_id, + PFN_ActivateAudioInterfaceAsync activate_audio_interface_async, + speaker_layout &speakers, audio_format &format, uint32_t &samples_per_sec) { WAVEFORMATEXTENSIBLE wfextensible; CoTaskMemPtr wfex; @@ -741,39 +661,28 @@ ComPtr WASAPISource::InitClient( wf.wBitsPerSample = wBitsPerSample; wf.cbSize = sizeof(wfextensible) - sizeof(wf); wfextensible.Samples.wValidBitsPerSample = wBitsPerSample; - wfextensible.dwChannelMask = - GetSpeakerChannelMask(oai.speakers); + wfextensible.dwChannelMask = GetSpeakerChannelMask(oai.speakers); wfextensible.SubFormat = KSDATAFORMAT_SUBTYPE_IEEE_FLOAT; AUDIOCLIENT_ACTIVATION_PARAMS audioclientActivationParams; - audioclientActivationParams.ActivationType = - AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK; - audioclientActivationParams.ProcessLoopbackParams - .TargetProcessId = process_id; - audioclientActivationParams.ProcessLoopbackParams - .ProcessLoopbackMode = + audioclientActivationParams.ActivationType = AUDIOCLIENT_ACTIVATION_TYPE_PROCESS_LOOPBACK; + audioclientActivationParams.ProcessLoopbackParams.TargetProcessId = process_id; + audioclientActivationParams.ProcessLoopbackParams.ProcessLoopbackMode = PROCESS_LOOPBACK_MODE_INCLUDE_TARGET_PROCESS_TREE; PROPVARIANT activateParams{}; activateParams.vt = VT_BLOB; - activateParams.blob.cbSize = - sizeof(audioclientActivationParams); - activateParams.blob.pBlobData = - reinterpret_cast(&audioclientActivationParams); + activateParams.blob.cbSize = sizeof(audioclientActivationParams); + activateParams.blob.pBlobData = reinterpret_cast(&audioclientActivationParams); { - Microsoft::WRL::ComPtr< - WASAPIActivateAudioInterfaceCompletionHandler> - handler = Microsoft::WRL::Make< - WASAPIActivateAudioInterfaceCompletionHandler>(); + Microsoft::WRL::ComPtr handler = + Microsoft::WRL::Make(); ComPtr asyncOp; - res = activate_audio_interface_async( - VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, - __uuidof(IAudioClient), &activateParams, - handler.Get(), &asyncOp); + res = activate_audio_interface_async(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, + __uuidof(IAudioClient), &activateParams, handler.Get(), + &asyncOp); if (FAILED(res)) - throw HRError( - "Failed to get activate audio client", - res); + throw HRError("Failed to get activate audio client", res); res = handler->GetActivateResult(client.Assign()); if (FAILED(res)) @@ -782,8 +691,7 @@ ComPtr WASAPISource::InitClient( pFormat = &wf; } else { - res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, - nullptr, (void **)client.Assign()); + res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void **)client.Assign()); if (FAILED(res)) throw HRError("Failed to activate client context", res); @@ -799,8 +707,7 @@ ComPtr WASAPISource::InitClient( DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK; if (type != SourceType::Input) flags |= AUDCLNT_STREAMFLAGS_LOOPBACK; - res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags, - BUFFER_TIME_100NS, 0, pFormat, nullptr); + res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags, BUFFER_TIME_100NS, 0, pFormat, nullptr); if (FAILED(res)) throw HRError("Failed to initialize audio client", res); @@ -815,8 +722,7 @@ void WASAPISource::ClearBuffer(IMMDevice *device) UINT32 frames; ComPtr client; - res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, - (void **)client.Assign()); + res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void **)client.Assign()); if (FAILED(res)) throw HRError("Failed to activate client context", res); @@ -824,8 +730,7 @@ void WASAPISource::ClearBuffer(IMMDevice *device) if (FAILED(res)) throw HRError("Failed to get mix format", res); - res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS, - 0, wfex, nullptr); + res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS, 0, wfex, nullptr); if (FAILED(res)) throw HRError("Failed to initialize audio client", res); @@ -869,9 +774,8 @@ static speaker_layout ConvertSpeakerLayout(DWORD layout, WORD channels) return (speaker_layout)channels; } -void WASAPISource::InitFormat(const WAVEFORMATEX *wfex, - enum speaker_layout &speakers, - enum audio_format &format, uint32_t &sampleRate) +void WASAPISource::InitFormat(const WAVEFORMATEX *wfex, enum speaker_layout &speakers, enum audio_format &format, + uint32_t &sampleRate) { DWORD layout = 0; @@ -886,8 +790,7 @@ void WASAPISource::InitFormat(const WAVEFORMATEX *wfex, sampleRate = wfex->nSamplesPerSec; } -ComPtr WASAPISource::InitCapture(IAudioClient *client, - HANDLE receiveSignal) +ComPtr WASAPISource::InitCapture(IAudioClient *client, HANDLE receiveSignal) { ComPtr capture; HRESULT res = client->GetService(IID_PPV_ARGS(capture.Assign())); @@ -911,8 +814,7 @@ void WASAPISource::Initialize() if (sourceType == SourceType::ProcessOutput) { device_name = "[VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK]"; - hwnd = ms_find_window(INCLUDE_MINIMIZED, priority, - window_class.c_str(), title.c_str(), + hwnd = ms_find_window(INCLUDE_MINIMIZED, priority, window_class.c_str(), title.c_str(), executable.c_str()); if (!hwnd) throw "Failed to find window"; @@ -925,36 +827,31 @@ void WASAPISource::Initialize() process_id = dwProcessId; } else { - device = InitDevice(enumerator, isDefaultDevice, sourceType, - device_id); + device = InitDevice(enumerator, isDefaultDevice, sourceType, device_id); device_name = GetDeviceName(device); } ResetEvent(receiveSignal); - ComPtr temp_client = InitClient( - device, sourceType, process_id, activate_audio_interface_async, - speakers, format, sampleRate); + ComPtr temp_client = InitClient(device, sourceType, process_id, activate_audio_interface_async, + speakers, format, sampleRate); if (sourceType == SourceType::DeviceOutput) ClearBuffer(device); - ComPtr temp_capture = - InitCapture(temp_client, receiveSignal); + ComPtr temp_capture = InitCapture(temp_client, receiveSignal); client = std::move(temp_client); capture = std::move(temp_capture); if (rtwq_supported) { - HRESULT hr = rtwq_put_waiting_work_item( - receiveSignal, 0, sampleReadyAsyncResult, nullptr); + HRESULT hr = rtwq_put_waiting_work_item(receiveSignal, 0, sampleReadyAsyncResult, nullptr); if (FAILED(hr)) { capture.Clear(); client.Clear(); throw HRError("RtwqPutWaitingWorkItem failed", hr); } - hr = rtwq_put_waiting_work_item(restartSignal, 0, - restartAsyncResult, nullptr); + hr = rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult, nullptr); if (FAILED(hr)) { capture.Clear(); client.Clear(); @@ -962,9 +859,8 @@ void WASAPISource::Initialize() } } - blog(LOG_INFO, - "WASAPI: Device '%s' [%" PRIu32 " Hz] initialized (source: %s)", - device_name.c_str(), sampleRate, obs_source_get_name(source)); + blog(LOG_INFO, "WASAPI: Device '%s' [%" PRIu32 " Hz] initialized (source: %s)", device_name.c_str(), sampleRate, + obs_source_get_name(source)); if (sourceType == SourceType::ProcessOutput && !hooked) { hooked = true; @@ -1001,19 +897,13 @@ bool WASAPISource::TryInitialize() } catch (HRError &error) { if (!previouslyFailed) { - blog(LOG_WARNING, - "[WASAPISource::TryInitialize]:[%s] %s: %lX", - device_name.empty() ? device_id.c_str() - : device_name.c_str(), - error.str, error.hr); + blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s: %lX", + device_name.empty() ? device_id.c_str() : device_name.c_str(), error.str, error.hr); } } catch (const char *error) { if (!previouslyFailed) { - blog(LOG_WARNING, - "[WASAPISource::TryInitialize]:[%s] %s", - device_name.empty() ? device_id.c_str() - : device_name.c_str(), - error); + blog(LOG_WARNING, "[WASAPISource::TryInitialize]:[%s] %s", + device_name.empty() ? device_id.c_str() : device_name.c_str(), error); } } @@ -1039,8 +929,7 @@ DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param) bool exit = false; while (!exit) { - const DWORD ret = WaitForMultipleObjects(_countof(sigs), sigs, - false, INFINITE); + const DWORD ret = WaitForMultipleObjects(_countof(sigs), sigs, false, INFINITE); switch (ret) { case WAIT_OBJECT_0: exit = true; @@ -1048,10 +937,8 @@ DWORD WINAPI WASAPISource::ReconnectThread(LPVOID param) default: assert(ret == (WAIT_OBJECT_0 + 1)); if (source->reconnectDuration > 0) { - WaitForMultipleObjects( - _countof(reconnect_sigs), - reconnect_sigs, false, - source->reconnectDuration); + WaitForMultipleObjects(_countof(reconnect_sigs), reconnect_sigs, false, + source->reconnectDuration); } source->Start(); } @@ -1070,10 +957,8 @@ bool WASAPISource::ProcessCaptureData() UINT captureSize = 0; while (true) { - if ((sourceType == SourceType::ProcessOutput) && - !IsWindow(hwnd)) { - blog(LOG_WARNING, - "[WASAPISource::ProcessCaptureData] window disappeared"); + if ((sourceType == SourceType::ProcessOutput) && !IsWindow(hwnd)) { + blog(LOG_WARNING, "[WASAPISource::ProcessCaptureData] window disappeared"); return false; } @@ -1102,8 +987,7 @@ bool WASAPISource::ProcessCaptureData() return false; } - if (!sawBadTimestamp && - flags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR) { + if (!sawBadTimestamp && flags & AUDCLNT_BUFFERFLAGS_TIMESTAMP_ERROR) { blog(LOG_WARNING, "[WASAPISource::ProcessCaptureData]" " Timestamp error!"); sawBadTimestamp = true; @@ -1113,8 +997,7 @@ bool WASAPISource::ProcessCaptureData() /* buffer size = frame size * number of frames * frame size = channels * sample size * sample size = 4 bytes (always float per InitFormat) */ - uint32_t requiredBufSize = - get_audio_channels(speakers) * frames * 4; + uint32_t requiredBufSize = get_audio_channels(speakers) * frames * 4; if (silence.size() < requiredBufSize) silence.resize(requiredBufSize); @@ -1130,18 +1013,14 @@ bool WASAPISource::ProcessCaptureData() if (sourceType == SourceType::ProcessOutput) { data.timestamp = ts * 100; } else { - data.timestamp = useDeviceTiming ? ts * 100 - : os_gettime_ns(); + data.timestamp = useDeviceTiming ? ts * 100 : os_gettime_ns(); if (!useDeviceTiming) - data.timestamp -= util_mul_div64( - frames, UINT64_C(1000000000), - sampleRate); + data.timestamp -= util_mul_div64(frames, UINT64_C(1000000000), sampleRate); } if (reroute_target) { - obs_source_t *target = - obs_weak_source_get_source(reroute_target); + obs_source_t *target = obs_weak_source_get_source(reroute_target); if (target) { obs_source_output_audio(target, &data); @@ -1201,13 +1080,9 @@ DWORD WINAPI WASAPISource::CaptureThread(LPVOID param) do { /* Windows 7 does not seem to wake up for LOOPBACK */ const DWORD dwMilliseconds = - ((sigs == active_sigs) && - (source->sourceType != SourceType::Input)) - ? 10 - : INFINITE; + ((sigs == active_sigs) && (source->sourceType != SourceType::Input)) ? 10 : INFINITE; - const DWORD ret = WaitForMultipleObjects( - sig_count, sigs, false, dwMilliseconds); + const DWORD ret = WaitForMultipleObjects(sig_count, sigs, false, dwMilliseconds); switch (ret) { case WAIT_OBJECT_0: { exit = true; @@ -1227,53 +1102,36 @@ DWORD WINAPI WASAPISource::CaptureThread(LPVOID param) assert(ret != WAIT_TIMEOUT); if (source->TryInitialize()) { - sig_count = - _countof(active_sigs); + sig_count = _countof(active_sigs); sigs = active_sigs; } else { - if (source->reconnectDuration == - 0) { + if (source->reconnectDuration == 0) { blog(LOG_INFO, "WASAPI: Device '%s' failed to start (source: %s)", - source->device_id - .c_str(), - obs_source_get_name( - source->source)); + source->device_id.c_str(), + obs_source_get_name(source->source)); } stop = true; reconnect = true; - source->reconnectDuration = - RECONNECT_INTERVAL; + source->reconnectDuration = RECONNECT_INTERVAL; } } else { stop = !source->ProcessCaptureData(); if (stop) { - blog(LOG_INFO, - "Device '%s' invalidated. Retrying (source: %s)", - source->device_name.c_str(), - obs_source_get_name( - source->source)); - if (source->sourceType == - SourceType:: - ProcessOutput && - source->hooked) { + blog(LOG_INFO, "Device '%s' invalidated. Retrying (source: %s)", + source->device_name.c_str(), obs_source_get_name(source->source)); + if (source->sourceType == SourceType::ProcessOutput && source->hooked) { source->hooked = false; signal_handler_t *sh = - obs_source_get_signal_handler( - source->source); + obs_source_get_signal_handler(source->source); calldata_t data = {0}; - calldata_set_ptr( - &data, "source", - source->source); - signal_handler_signal( - sh, "unhooked", - &data); + calldata_set_ptr(&data, "source", source->source); + signal_handler_signal(sh, "unhooked", &data); calldata_free(&data); } stop = true; reconnect = true; - source->reconnectDuration = - RECONNECT_INTERVAL; + source->reconnectDuration = RECONNECT_INTERVAL; } } break; @@ -1301,19 +1159,13 @@ DWORD WINAPI WASAPISource::CaptureThread(LPVOID param) if (idle) { SetEvent(source->idleSignal); } else if (reconnect) { - blog(LOG_INFO, - "Device '%s' invalidated. Retrying (source: %s)", - source->device_name.c_str(), + blog(LOG_INFO, "Device '%s' invalidated. Retrying (source: %s)", source->device_name.c_str(), obs_source_get_name(source->source)); - if (source->sourceType == SourceType::ProcessOutput && - source->hooked) { + if (source->sourceType == SourceType::ProcessOutput && source->hooked) { source->hooked = false; - signal_handler_t *sh = - obs_source_get_signal_handler( - source->source); + signal_handler_t *sh = obs_source_get_signal_handler(source->source); calldata_t data = {0}; - calldata_set_ptr(&data, "source", - source->source); + calldata_set_ptr(&data, "source", source->source); signal_handler_signal(sh, "unhooked", &data); calldata_free(&data); } @@ -1351,8 +1203,7 @@ void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id) default_id.clear(); } - blog(LOG_INFO, "WASAPI: Default %s device changed", - input ? "input" : "output"); + blog(LOG_INFO, "WASAPI: Default %s device changed", input ? "input" : "output"); SetEvent(restartSignal); } @@ -1370,9 +1221,7 @@ void WASAPISource::OnStartCapture() if (!TryInitialize()) { if (reconnectDuration == 0) { - blog(LOG_INFO, - "WASAPI: Device '%s' failed to start (source: %s)", - device_id.c_str(), + blog(LOG_INFO, "WASAPI: Device '%s' failed to start (source: %s)", device_id.c_str(), obs_source_get_name(source)); } reconnectDuration = RECONNECT_INTERVAL; @@ -1398,8 +1247,7 @@ void WASAPISource::OnSampleReady() reconnectDuration = 0; ResetEvent(restartSignal); - rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult, - nullptr); + rtwq_put_waiting_work_item(restartSignal, 0, restartAsyncResult, nullptr); } if (WaitForSingleObject(stopSignal, 0) == WAIT_OBJECT_0) { @@ -1408,11 +1256,8 @@ void WASAPISource::OnSampleReady() } if (!stop) { - if (FAILED(rtwq_put_waiting_work_item(receiveSignal, 0, - sampleReadyAsyncResult, - nullptr))) { - blog(LOG_ERROR, - "Could not requeue sample receive work"); + if (FAILED(rtwq_put_waiting_work_item(receiveSignal, 0, sampleReadyAsyncResult, nullptr))) { + blog(LOG_ERROR, "Could not requeue sample receive work"); stop = true; reconnect = true; reconnectDuration = RECONNECT_INTERVAL; @@ -1426,14 +1271,12 @@ void WASAPISource::OnSampleReady() client.Clear(); if (reconnect) { - blog(LOG_INFO, - "Device '%s' invalidated. Retrying (source: %s)", - device_name.c_str(), obs_source_get_name(source)); + blog(LOG_INFO, "Device '%s' invalidated. Retrying (source: %s)", device_name.c_str(), + obs_source_get_name(source)); SetEvent(reconnectSignal); if (sourceType == SourceType::ProcessOutput && hooked) { hooked = false; - signal_handler_t *sh = - obs_source_get_signal_handler(source); + signal_handler_t *sh = obs_source_get_signal_handler(source); calldata_t data = {0}; calldata_set_ptr(&data, "source", source); signal_handler_signal(sh, "unhooked", &data); @@ -1534,34 +1377,27 @@ static void wasapi_reroute_audio(void *data, calldata_t *cd) wasapi_source->SetRerouteTarget(target); } -static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source, - SourceType type) +static void *CreateWASAPISource(obs_data_t *settings, obs_source_t *source, SourceType type) { try { if (type != SourceType::ProcessOutput) { return new WASAPISource(settings, source, type); } else { - WASAPISource *wasapi_source = - new WASAPISource(settings, source, type); + WASAPISource *wasapi_source = new WASAPISource(settings, source, type); if (wasapi_source) { - signal_handler_t *sh = - obs_source_get_signal_handler(source); - signal_handler_add(sh, - "void unhooked(ptr source)"); + signal_handler_t *sh = obs_source_get_signal_handler(source); + signal_handler_add(sh, "void unhooked(ptr source)"); signal_handler_add( - sh, - "void hooked(ptr source, string title, string class, string executable)"); + sh, "void hooked(ptr source, string title, string class, string executable)"); - proc_handler_t *ph = - obs_source_get_proc_handler(source); + proc_handler_t *ph = obs_source_get_proc_handler(source); proc_handler_add( ph, "void get_hooked(out bool hooked, out string title, out string class, out string executable)", wasapi_get_hooked, wasapi_source); - proc_handler_add( - ph, "void reroute_audio(in ptr target)", - wasapi_reroute_audio, wasapi_source); + proc_handler_add(ph, "void reroute_audio(in ptr target)", wasapi_reroute_audio, + wasapi_source); } return wasapi_source; } @@ -1577,14 +1413,12 @@ static void *CreateWASAPIInput(obs_data_t *settings, obs_source_t *source) return CreateWASAPISource(settings, source, SourceType::Input); } -static void *CreateWASAPIDeviceOutput(obs_data_t *settings, - obs_source_t *source) +static void *CreateWASAPIDeviceOutput(obs_data_t *settings, obs_source_t *source) { return CreateWASAPISource(settings, source, SourceType::DeviceOutput); } -static void *CreateWASAPIProcessOutput(obs_data_t *settings, - obs_source_t *source) +static void *CreateWASAPIProcessOutput(obs_data_t *settings, obs_source_t *source) { return CreateWASAPISource(settings, source, SourceType::ProcessOutput); } @@ -1609,8 +1443,7 @@ static void DeactivateWASAPISource(void *obj) static_cast(obj)->Deactivate(); } -static bool UpdateWASAPIMethod(obs_properties_t *props, obs_property_t *, - obs_data_t *settings) +static bool UpdateWASAPIMethod(obs_properties_t *props, obs_property_t *, obs_data_t *settings) { WASAPISource *source = (WASAPISource *)obs_properties_get_param(props); if (!source) @@ -1626,24 +1459,20 @@ static obs_properties_t *GetWASAPIPropertiesInput(void *) obs_properties_t *props = obs_properties_create(); vector devices; - obs_property_t *device_prop = obs_properties_add_list( - props, OPT_DEVICE_ID, obs_module_text("Device"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *device_prop = obs_properties_add_list(props, OPT_DEVICE_ID, obs_module_text("Device"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); GetWASAPIAudioDevices(devices, true); if (devices.size()) - obs_property_list_add_string( - device_prop, obs_module_text("Default"), "default"); + obs_property_list_add_string(device_prop, obs_module_text("Default"), "default"); for (size_t i = 0; i < devices.size(); i++) { AudioDeviceInfo &device = devices[i]; - obs_property_list_add_string(device_prop, device.name.c_str(), - device.id.c_str()); + obs_property_list_add_string(device_prop, device.name.c_str(), device.id.c_str()); } - obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING, - obs_module_text("UseDeviceTiming")); + obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING, obs_module_text("UseDeviceTiming")); return props; } @@ -1653,30 +1482,25 @@ static obs_properties_t *GetWASAPIPropertiesDeviceOutput(void *) obs_properties_t *props = obs_properties_create(); vector devices; - obs_property_t *device_prop = obs_properties_add_list( - props, OPT_DEVICE_ID, obs_module_text("Device"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *device_prop = obs_properties_add_list(props, OPT_DEVICE_ID, obs_module_text("Device"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); GetWASAPIAudioDevices(devices, false); if (devices.size()) - obs_property_list_add_string( - device_prop, obs_module_text("Default"), "default"); + obs_property_list_add_string(device_prop, obs_module_text("Default"), "default"); for (size_t i = 0; i < devices.size(); i++) { AudioDeviceInfo &device = devices[i]; - obs_property_list_add_string(device_prop, device.name.c_str(), - device.id.c_str()); + obs_property_list_add_string(device_prop, device.name.c_str(), device.id.c_str()); } - obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING, - obs_module_text("UseDeviceTiming")); + obs_properties_add_bool(props, OPT_USE_DEVICE_TIMING, obs_module_text("UseDeviceTiming")); return props; } -static bool wasapi_window_changed(obs_properties_t *props, obs_property_t *p, - obs_data_t *settings) +static bool wasapi_window_changed(obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { WASAPISource *source = (WASAPISource *)obs_properties_get_param(props); if (!source) @@ -1693,24 +1517,16 @@ static obs_properties_t *GetWASAPIPropertiesProcessOutput(void *data) obs_properties_t *props = obs_properties_create(); obs_properties_set_param(props, data, NULL); - obs_property_t *const window_prop = obs_properties_add_list( - props, OPT_WINDOW, obs_module_text("Window"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); + obs_property_t *const window_prop = obs_properties_add_list(props, OPT_WINDOW, obs_module_text("Window"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_STRING); ms_fill_window_list(window_prop, INCLUDE_MINIMIZED, nullptr); obs_property_set_modified_callback(window_prop, wasapi_window_changed); - obs_property_t *const priority_prop = obs_properties_add_list( - props, OPT_PRIORITY, obs_module_text("Priority"), - OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); - obs_property_list_add_int(priority_prop, - obs_module_text("Priority.Title"), - WINDOW_PRIORITY_TITLE); - obs_property_list_add_int(priority_prop, - obs_module_text("Priority.Class"), - WINDOW_PRIORITY_CLASS); - obs_property_list_add_int(priority_prop, - obs_module_text("Priority.Exe"), - WINDOW_PRIORITY_EXE); + obs_property_t *const priority_prop = obs_properties_add_list(props, OPT_PRIORITY, obs_module_text("Priority"), + OBS_COMBO_TYPE_LIST, OBS_COMBO_FORMAT_INT); + obs_property_list_add_int(priority_prop, obs_module_text("Priority.Title"), WINDOW_PRIORITY_TITLE); + obs_property_list_add_int(priority_prop, obs_module_text("Priority.Class"), WINDOW_PRIORITY_CLASS); + obs_property_list_add_int(priority_prop, obs_module_text("Priority.Exe"), WINDOW_PRIORITY_EXE); return props; } @@ -1738,8 +1554,7 @@ void RegisterWASAPIDeviceOutput() obs_source_info info = {}; info.id = "wasapi_output_capture"; info.type = OBS_SOURCE_TYPE_INPUT; - info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | - OBS_SOURCE_DO_NOT_SELF_MONITOR; + info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_DO_NOT_SELF_MONITOR; info.get_name = GetWASAPIDeviceOutputName; info.create = CreateWASAPIDeviceOutput; info.destroy = DestroyWASAPISource; @@ -1757,8 +1572,7 @@ void RegisterWASAPIProcessOutput() obs_source_info info = {}; info.id = "wasapi_process_output_capture"; info.type = OBS_SOURCE_TYPE_INPUT; - info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | - OBS_SOURCE_DO_NOT_SELF_MONITOR; + info.output_flags = OBS_SOURCE_AUDIO | OBS_SOURCE_DO_NOT_DUPLICATE | OBS_SOURCE_DO_NOT_SELF_MONITOR; info.get_name = GetWASAPIProcessOutputName; info.create = CreateWASAPIProcessOutput; info.destroy = DestroyWASAPISource; diff --git a/shared/bpm/bpm-internal.h b/shared/bpm/bpm-internal.h index 5017a7504..1e624a38d 100644 --- a/shared/bpm/bpm-internal.h +++ b/shared/bpm/bpm-internal.h @@ -32,18 +32,12 @@ enum bpm_sei_types { }; #define SEI_UUID_SIZE 16 -static const uint8_t bpm_ts_uuid[SEI_UUID_SIZE] = {0x0a, 0xec, 0xff, 0xe7, - 0x52, 0x72, 0x4e, 0x2f, - 0xa6, 0x2f, 0xd1, 0x9c, - 0xd6, 0x1a, 0x93, 0xb5}; -static const uint8_t bpm_sm_uuid[SEI_UUID_SIZE] = {0xca, 0x60, 0xe7, 0x1c, - 0x6a, 0x8b, 0x43, 0x88, - 0xa3, 0x77, 0x15, 0x1d, - 0xf7, 0xbf, 0x8a, 0xc2}; -static const uint8_t bpm_erm_uuid[SEI_UUID_SIZE] = {0xf1, 0xfb, 0xc1, 0xd5, - 0x10, 0x1e, 0x4f, 0xb5, - 0xa6, 0x1e, 0xb8, 0xce, - 0x3c, 0x07, 0xb8, 0xc0}; +static const uint8_t bpm_ts_uuid[SEI_UUID_SIZE] = {0x0a, 0xec, 0xff, 0xe7, 0x52, 0x72, 0x4e, 0x2f, + 0xa6, 0x2f, 0xd1, 0x9c, 0xd6, 0x1a, 0x93, 0xb5}; +static const uint8_t bpm_sm_uuid[SEI_UUID_SIZE] = {0xca, 0x60, 0xe7, 0x1c, 0x6a, 0x8b, 0x43, 0x88, + 0xa3, 0x77, 0x15, 0x1d, 0xf7, 0xbf, 0x8a, 0xc2}; +static const uint8_t bpm_erm_uuid[SEI_UUID_SIZE] = {0xf1, 0xfb, 0xc1, 0xd5, 0x10, 0x1e, 0x4f, 0xb5, + 0xa6, 0x1e, 0xb8, 0xce, 0x3c, 0x07, 0xb8, 0xc0}; // Broadcast Performance Metrics timestamp types enum bpm_ts_type { @@ -65,14 +59,14 @@ enum bpm_sm_type { BPM_SM_FRAMES_RENDERED = 1, // Frames rendered by compositor BPM_SM_FRAMES_LAGGED, // Frames lagged by compositor BPM_SM_FRAMES_DROPPED, // Frames dropped due to network congestion - BPM_SM_FRAMES_OUTPUT // Total frames output (sum of all video encoder rendition sinks) + BPM_SM_FRAMES_OUTPUT // Total frames output (sum of all video encoder rendition sinks) }; // Broadcast Performance Encoded Rendition Metrics types enum bpm_erm_type { BPM_ERM_FRAMES_INPUT = 1, // Frames input to the encoder rendition BPM_ERM_FRAMES_SKIPPED, // Frames skippped by the encoder rendition - BPM_ERM_FRAMES_OUTPUT // Frames output (encoded) by the encoder rendition + BPM_ERM_FRAMES_OUTPUT // Frames output (encoded) by the encoder rendition }; struct metrics_data { @@ -86,8 +80,7 @@ struct metrics_data { struct counter_data session_frames_lagged; struct array_output_data sei_payload[BPM_MAX_SEI]; bool sei_rendered[BPM_MAX_SEI]; - struct metrics_time - cts; // Composition timestamp (i.e. when the frame was created) + struct metrics_time cts; // Composition timestamp (i.e. when the frame was created) struct metrics_time ferts; // Frame encode request timestamp struct metrics_time fercts; // Frame encode request complete timestamp struct metrics_time pirts; // Packet Interleave Request timestamp diff --git a/shared/bpm/bpm.c b/shared/bpm/bpm.c index 38a8a60b1..e2d17b70f 100644 --- a/shared/bpm/bpm.c +++ b/shared/bpm/bpm.c @@ -8,29 +8,22 @@ static void render_metrics_time(struct metrics_time *m_time) * "2024-05-31T12:26:03.591Z" */ memset(&m_time->rfc3339_str, 0, sizeof(m_time->rfc3339_str)); - strftime(m_time->rfc3339_str, sizeof(m_time->rfc3339_str), - "%Y-%m-%dT%T", gmtime(&m_time->tspec.tv_sec)); - sprintf(m_time->rfc3339_str + strlen(m_time->rfc3339_str), ".%03ldZ", - m_time->tspec.tv_nsec / 1000000); + strftime(m_time->rfc3339_str, sizeof(m_time->rfc3339_str), "%Y-%m-%dT%T", gmtime(&m_time->tspec.tv_sec)); + sprintf(m_time->rfc3339_str + strlen(m_time->rfc3339_str), ".%03ldZ", m_time->tspec.tv_nsec / 1000000); m_time->valid = true; } -static bool update_metrics(obs_output_t *output, - const struct encoder_packet *pkt, - const struct encoder_packet_time *ept, - struct metrics_data *m_track) +static bool update_metrics(obs_output_t *output, const struct encoder_packet *pkt, + const struct encoder_packet_time *ept, struct metrics_data *m_track) { if (!output || !pkt || !ept || !m_track) { - blog(LOG_DEBUG, "%s: Null arguments for track %lu", - __FUNCTION__, pkt->track_idx); + blog(LOG_DEBUG, "%s: Null arguments for track %lu", __FUNCTION__, pkt->track_idx); return false; } // Perform reads on all the counters as close together as possible - m_track->session_frames_output.curr = - obs_output_get_total_frames(output); - m_track->session_frames_dropped.curr = - obs_output_get_frames_dropped(output); + m_track->session_frames_output.curr = obs_output_get_total_frames(output); + m_track->session_frames_dropped.curr = obs_output_get_frames_dropped(output); m_track->session_frames_rendered.curr = obs_get_total_frames(); m_track->session_frames_lagged.curr = obs_get_lagged_frames(); @@ -43,15 +36,12 @@ static bool update_metrics(obs_output_t *output, * For metrics we will consider this value to be the number of * frames input to the obs_encoder_t instance. */ - m_track->rendition_frames_input.curr = - video_output_get_total_frames(video); - m_track->rendition_frames_skipped.curr = - video_output_get_skipped_frames(video); + m_track->rendition_frames_input.curr = video_output_get_total_frames(video); + m_track->rendition_frames_skipped.curr = video_output_get_skipped_frames(video); /* obs_encoder_get_encoded_frames() returns the number of frames * successfully encoded by the obs_encoder_t instance. */ - m_track->rendition_frames_output.curr = - obs_encoder_get_encoded_frames(pkt->encoder); + m_track->rendition_frames_output.curr = obs_encoder_get_encoded_frames(pkt->encoder); } else { m_track->rendition_frames_input.curr = 0; m_track->rendition_frames_skipped.curr = 0; @@ -72,43 +62,29 @@ static bool update_metrics(obs_output_t *output, } else { // Calculate diff's m_track->session_frames_output.diff = - m_track->session_frames_output.curr - - m_track->session_frames_output.ref; + m_track->session_frames_output.curr - m_track->session_frames_output.ref; m_track->session_frames_dropped.diff = - m_track->session_frames_dropped.curr - - m_track->session_frames_dropped.ref; + m_track->session_frames_dropped.curr - m_track->session_frames_dropped.ref; m_track->session_frames_rendered.diff = - m_track->session_frames_rendered.curr - - m_track->session_frames_rendered.ref; + m_track->session_frames_rendered.curr - m_track->session_frames_rendered.ref; m_track->session_frames_lagged.diff = - m_track->session_frames_lagged.curr - - m_track->session_frames_lagged.ref; + m_track->session_frames_lagged.curr - m_track->session_frames_lagged.ref; m_track->rendition_frames_input.diff = - m_track->rendition_frames_input.curr - - m_track->rendition_frames_input.ref; + m_track->rendition_frames_input.curr - m_track->rendition_frames_input.ref; m_track->rendition_frames_skipped.diff = - m_track->rendition_frames_skipped.curr - - m_track->rendition_frames_skipped.ref; + m_track->rendition_frames_skipped.curr - m_track->rendition_frames_skipped.ref; m_track->rendition_frames_output.diff = - m_track->rendition_frames_output.curr - - m_track->rendition_frames_output.ref; + m_track->rendition_frames_output.curr - m_track->rendition_frames_output.ref; } // Update the reference values - m_track->session_frames_output.ref = - m_track->session_frames_output.curr; - m_track->session_frames_dropped.ref = - m_track->session_frames_dropped.curr; - m_track->session_frames_rendered.ref = - m_track->session_frames_rendered.curr; - m_track->session_frames_lagged.ref = - m_track->session_frames_lagged.curr; - m_track->rendition_frames_input.ref = - m_track->rendition_frames_input.curr; - m_track->rendition_frames_skipped.ref = - m_track->rendition_frames_skipped.curr; - m_track->rendition_frames_output.ref = - m_track->rendition_frames_output.curr; + m_track->session_frames_output.ref = m_track->session_frames_output.curr; + m_track->session_frames_dropped.ref = m_track->session_frames_dropped.curr; + m_track->session_frames_rendered.ref = m_track->session_frames_rendered.curr; + m_track->session_frames_lagged.ref = m_track->session_frames_lagged.curr; + m_track->rendition_frames_input.ref = m_track->rendition_frames_input.curr; + m_track->rendition_frames_skipped.ref = m_track->rendition_frames_skipped.curr; + m_track->rendition_frames_output.ref = m_track->rendition_frames_output.curr; /* BPM Timestamp Message */ m_track->cts.valid = false; @@ -127,8 +103,7 @@ static bool update_metrics(obs_output_t *output, os_nstime_to_timespec(ept->fer, &m_track->ferts.tspec); render_metrics_time(&m_track->ferts); if (ept->ferc && (ept->ferc > ept->fer)) { - os_nstime_to_timespec(ept->ferc, - &m_track->fercts.tspec); + os_nstime_to_timespec(ept->ferc, &m_track->fercts.tspec); render_metrics_time(&m_track->fercts); } } @@ -143,19 +118,13 @@ static bool update_metrics(obs_output_t *output, * with "--verbose" and "--unfiltered_log". */ blog(LOG_DEBUG, - "BPM: %s, trk %lu: [CTS|FER-CTS|FERC-FER|PIR-CTS]:[%" PRIu64 - " ms|%" PRIu64 " ms|%" PRIu64 " us|%" PRIu64 - " ms], [dts|pts]:[%" PRId64 "|%" PRId64 - "], S[R:O:D:L],R[I:S:O]:%d:%d:%d:%d:%d:%d:%d", - obs_encoder_get_name(pkt->encoder), pkt->track_idx, - ept->cts / 1000000, (ept->fer - ept->cts) / 1000000, - (ept->ferc - ept->fer) / 1000, (ept->pir - ept->cts) / 1000000, - pkt->dts, pkt->pts, m_track->session_frames_rendered.diff, - m_track->session_frames_output.diff, - m_track->session_frames_dropped.diff, - m_track->session_frames_lagged.diff, - m_track->rendition_frames_input.diff, - m_track->rendition_frames_skipped.diff, + "BPM: %s, trk %lu: [CTS|FER-CTS|FERC-FER|PIR-CTS]:[%" PRIu64 " ms|%" PRIu64 " ms|%" PRIu64 " us|%" PRIu64 + " ms], [dts|pts]:[%" PRId64 "|%" PRId64 "], S[R:O:D:L],R[I:S:O]:%d:%d:%d:%d:%d:%d:%d", + obs_encoder_get_name(pkt->encoder), pkt->track_idx, ept->cts / 1000000, (ept->fer - ept->cts) / 1000000, + (ept->ferc - ept->fer) / 1000, (ept->pir - ept->cts) / 1000000, pkt->dts, pkt->pts, + m_track->session_frames_rendered.diff, m_track->session_frames_output.diff, + m_track->session_frames_dropped.diff, m_track->session_frames_lagged.diff, + m_track->rendition_frames_input.diff, m_track->rendition_frames_skipped.diff, m_track->rendition_frames_output.diff); return true; @@ -194,8 +163,7 @@ void bpm_ts_sei_render(struct metrics_data *m_track) // Write the timestamp event tag (Composition Time Event) s_w8(&s, BPM_TS_EVENT_CTS); // Write the RFC3339-formatted string, including the null terminator - s_write(&s, m_track->cts.rfc3339_str, - strlen(m_track->cts.rfc3339_str) + 1); + s_write(&s, m_track->cts.rfc3339_str, strlen(m_track->cts.rfc3339_str) + 1); } if (m_track->ferts.valid) { @@ -204,8 +172,7 @@ void bpm_ts_sei_render(struct metrics_data *m_track) // Write the timestamp event tag (Frame Encode Request Event) s_w8(&s, BPM_TS_EVENT_FER); // Write the RFC3339-formatted string, including the null terminator - s_write(&s, m_track->ferts.rfc3339_str, - strlen(m_track->ferts.rfc3339_str) + 1); + s_write(&s, m_track->ferts.rfc3339_str, strlen(m_track->ferts.rfc3339_str) + 1); } if (m_track->fercts.valid) { @@ -214,8 +181,7 @@ void bpm_ts_sei_render(struct metrics_data *m_track) // Write the timestamp event tag (Frame Encode Request Complete Event) s_w8(&s, BPM_TS_EVENT_FERC); // Write the RFC3339-formatted string, including the null terminator - s_write(&s, m_track->fercts.rfc3339_str, - strlen(m_track->fercts.rfc3339_str) + 1); + s_write(&s, m_track->fercts.rfc3339_str, strlen(m_track->fercts.rfc3339_str) + 1); } if (m_track->pirts.valid) { @@ -224,8 +190,7 @@ void bpm_ts_sei_render(struct metrics_data *m_track) // Write the timestamp event tag (Packet Interleave Request Event) s_w8(&s, BPM_TS_EVENT_PIR); // Write the RFC3339-formatted string, including the null terminator - s_write(&s, m_track->pirts.rfc3339_str, - strlen(m_track->pirts.rfc3339_str) + 1); + s_write(&s, m_track->pirts.rfc3339_str, strlen(m_track->pirts.rfc3339_str) + 1); } m_track->sei_rendered[BPM_TS_SEI] = true; } @@ -256,8 +221,7 @@ void bpm_sm_sei_render(struct metrics_data *m_track) */ s_w8(&s, BPM_TS_EVENT_PIR); // Write the RFC3339-formatted string, including the null terminator - s_write(&s, m_track->pirts.rfc3339_str, - strlen(m_track->pirts.rfc3339_str) + 1); + s_write(&s, m_track->pirts.rfc3339_str, strlen(m_track->pirts.rfc3339_str) + 1); // Session metrics has 4 counters num_counters = 4; @@ -303,8 +267,7 @@ void bpm_erm_sei_render(struct metrics_data *m_track) */ s_w8(&s, BPM_TS_EVENT_PIR); // Write the RFC3339-formatted string, including the null terminator - s_write(&s, m_track->pirts.rfc3339_str, - strlen(m_track->pirts.rfc3339_str) + 1); + s_write(&s, m_track->pirts.rfc3339_str, strlen(m_track->pirts.rfc3339_str) + 1); // Encoder rendition metrics has 3 counters num_counters = 3; @@ -347,8 +310,7 @@ static const uint8_t nal_start[4] = {0, 0, 0, 1}; * SEI (AVC/HEVC) or OBU (AV1) messages into the encoded * video bitstream. */ -static bool process_metrics(obs_output_t *output, struct encoder_packet *out, - struct encoder_packet_time *ept, +static bool process_metrics(obs_output_t *output, struct encoder_packet *out, struct encoder_packet_time *ept, struct metrics_data *m_track) { struct encoder_packet backup = *out; @@ -361,17 +323,14 @@ static bool process_metrics(obs_output_t *output, struct encoder_packet *out, bool av1 = false; if (!m_track) { - blog(LOG_DEBUG, - "Metrics track for index: %lu had not be initialized", - out->track_idx); + blog(LOG_DEBUG, "Metrics track for index: %lu had not be initialized", out->track_idx); return false; } // Update the metrics for this track if (!update_metrics(output, out, ept, m_track)) { // Something went wrong; log it and return - blog(LOG_DEBUG, "update_metrics() for track index: %lu failed", - out->track_idx); + blog(LOG_DEBUG, "update_metrics() for track index: %lu failed", out->track_idx); return false; } @@ -398,10 +357,9 @@ static bool process_metrics(obs_output_t *output, struct encoder_packet *out, } else { /* We shouldn't ever see this unless we start getting * packets without annex-b start codes. */ - blog(LOG_DEBUG, - "Annex-B start code not found, we may not " - "generate a valid hevc nal unit header " - "for our caption"); + blog(LOG_DEBUG, "Annex-B start code not found, we may not " + "generate a valid hevc nal unit header " + "for our caption"); return false; } /* We will use the same 2 byte NAL unit header for the SEI, @@ -431,10 +389,9 @@ static bool process_metrics(obs_output_t *output, struct encoder_packet *out, sei_init(&sei, 0.0); // Generate the formatted SEI message - sei_message_t *msg = sei_message_new( - sei_type_user_data_unregistered, - m_track->sei_payload[i].bytes.array, - m_track->sei_payload[i].bytes.num); + sei_message_t *msg = sei_message_new(sei_type_user_data_unregistered, + m_track->sei_payload[i].bytes.array, + m_track->sei_payload[i].bytes.num); sei_message_append(&sei, msg); // Free the SEI payload buffer in the metrics track @@ -455,16 +412,13 @@ static bool process_metrics(obs_output_t *output, struct encoder_packet *out, if (avc) { /* TODO: SEI should come after AUD/SPS/PPS, * but before any VCL */ - da_push_back_array(out_data, nal_start, - 4); - da_push_back_array(out_data, data, - size); + da_push_back_array(out_data, nal_start, 4); + da_push_back_array(out_data, data, size); #ifdef ENABLE_HEVC } else if (hevc) { /* Only first NAL (VPS/PPS/SPS) should use the 4 byte * start code. SEIs use 3 byte version */ - da_push_back_array(out_data, - nal_start + 1, 3); + da_push_back_array(out_data, nal_start + 1, 3); /* nal_unit_header( ) { * forbidden_zero_bit f(1) * nal_unit_type u(6) @@ -476,31 +430,22 @@ static bool process_metrics(obs_output_t *output, struct encoder_packet *out, /* The first bit is always 0, so we just need to * save the last bit off the original header and * add the SEI NAL type. */ - uint8_t first_byte = - (prefix_sei_nal_type << 1) | - (0x01 & hevc_nal_header[0]); + uint8_t first_byte = (prefix_sei_nal_type << 1) | (0x01 & hevc_nal_header[0]); hevc_nal_header[0] = first_byte; /* The HEVC NAL unit header is 2 byte instead of * one, otherwise everything else is the * same. */ - da_push_back_array(out_data, - hevc_nal_header, 2); - da_push_back_array(out_data, &data[1], - size - 1); + da_push_back_array(out_data, hevc_nal_header, 2); + da_push_back_array(out_data, &data[1], size - 1); #endif } else if (av1) { uint8_t *obu_buffer = NULL; size_t obu_buffer_size = 0; - size = extract_buffer_from_sei(&sei, - &data); - metadata_obu( - data, size, &obu_buffer, - &obu_buffer_size, - METADATA_TYPE_USER_PRIVATE_6); + size = extract_buffer_from_sei(&sei, &data); + metadata_obu(data, size, &obu_buffer, &obu_buffer_size, + METADATA_TYPE_USER_PRIVATE_6); if (obu_buffer) { - da_push_back_array( - out_data, obu_buffer, - obu_buffer_size); + da_push_back_array(out_data, obu_buffer, obu_buffer_size); bfree(obu_buffer); } } @@ -535,16 +480,14 @@ static struct metrics_data *bpm_create_metrics_track(void) return rval; } -static bool bpm_get_track(obs_output_t *output, size_t track, - struct metrics_data **m_track) +static bool bpm_get_track(obs_output_t *output, size_t track, struct metrics_data **m_track) { bool found = false; // Walk the DARRAY looking for the output pointer pthread_mutex_lock(&bpm_metrics_mutex); for (size_t i = bpm_metrics.num; i > 0; i--) { if (output == bpm_metrics.array[i - 1].output) { - *m_track = - bpm_metrics.array[i - 1].metrics_tracks[track]; + *m_track = bpm_metrics.array[i - 1].metrics_tracks[track]; found = true; break; } @@ -589,11 +532,9 @@ void bpm_destroy(obs_output_t *output) struct output_metrics_link *oml = &bpm_metrics.array[idx]; for (size_t i = 0; i < MAX_OUTPUT_VIDEO_ENCODERS; i++) { if (oml->metrics_tracks[i]) { - struct metrics_data *m_track = - oml->metrics_tracks[i]; + struct metrics_data *m_track = oml->metrics_tracks[i]; for (uint8_t j = 0; j < BPM_MAX_SEI; ++j) { - array_output_serializer_free( - &m_track->sei_payload[j]); + array_output_serializer_free(&m_track->sei_payload[j]); } pthread_mutex_destroy(&m_track->metrics_mutex); bfree(m_track); @@ -611,17 +552,14 @@ void bpm_destroy(obs_output_t *output) * with each output needing Broadcast Performance Metrics injected * into the video bitstream, using SEI (AVC/HEVC) and OBU (AV1) syntax. */ -void bpm_inject(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param) +void bpm_inject(obs_output_t *output, struct encoder_packet *pkt, struct encoder_packet_time *pkt_time, void *param) { UNUSED_PARAMETER(param); pthread_once(&bpm_once, bpm_init); if (!output || !pkt) { - blog(LOG_DEBUG, - "%s: Null pointer arguments supplied, returning", - __FUNCTION__); + blog(LOG_DEBUG, "%s: Null pointer arguments supplied, returning", __FUNCTION__); return; } @@ -631,9 +569,8 @@ void bpm_inject(obs_output_t *output, struct encoder_packet *pkt, if (pkt->type == OBS_ENCODER_VIDEO && pkt->keyframe) { /* Video packet must have pkt_timing supplied for BPM */ if (!pkt_time) { - blog(LOG_DEBUG, - "%s: Packet timing missing for track %ld, PTS %" PRId64, - __FUNCTION__, pkt->track_idx, pkt->pts); + blog(LOG_DEBUG, "%s: Packet timing missing for track %ld, PTS %" PRId64, __FUNCTION__, + pkt->track_idx, pkt->pts); return; } @@ -642,16 +579,14 @@ void bpm_inject(obs_output_t *output, struct encoder_packet *pkt, */ struct metrics_data *m_track = NULL; if (!bpm_get_track(output, pkt->track_idx, &m_track)) { - blog(LOG_DEBUG, "%s: BPM metrics track not found!", - __FUNCTION__); + blog(LOG_DEBUG, "%s: BPM metrics track not found!", __FUNCTION__); return; } pthread_mutex_lock(&m_track->metrics_mutex); /* Update the metrics and generate BPM messages. */ if (!process_metrics(output, pkt, pkt_time, m_track)) { - blog(LOG_DEBUG, "%s: BPM injection processing failed", - __FUNCTION__); + blog(LOG_DEBUG, "%s: BPM injection processing failed", __FUNCTION__); } pthread_mutex_unlock(&m_track->metrics_mutex); } diff --git a/shared/bpm/bpm.h b/shared/bpm/bpm.h index 33d6466df..93cb4a6c2 100644 --- a/shared/bpm/bpm.h +++ b/shared/bpm/bpm.h @@ -14,8 +14,7 @@ extern "C" { * obs_output_add_packet_callback() and obs_output_remove_packet_callback(), * respectively. */ -void bpm_inject(obs_output_t *output, struct encoder_packet *pkt, - struct encoder_packet_time *pkt_time, void *param); +void bpm_inject(obs_output_t *output, struct encoder_packet *pkt, struct encoder_packet_time *pkt_time, void *param); /* BPM function to destroy all allocations for a given output. */ void bpm_destroy(obs_output_t *output); diff --git a/shared/file-updater/file-updater/file-updater.c b/shared/file-updater/file-updater/file-updater.c index a0cb6fea3..a1d81ad8f 100644 --- a/shared/file-updater/file-updater/file-updater.c +++ b/shared/file-updater/file-updater/file-updater.c @@ -6,8 +6,7 @@ #include #include "file-updater.h" -#define warn(msg, ...) \ - blog(LOG_WARNING, "%s" msg, info->log_prefix, ##__VA_ARGS__) +#define warn(msg, ...) blog(LOG_WARNING, "%s" msg, info->log_prefix, ##__VA_ARGS__) #define info(msg, ...) blog(LOG_INFO, "%s" msg, info->log_prefix, ##__VA_ARGS__) struct update_info { @@ -68,8 +67,7 @@ void update_info_destroy(struct update_info *info) bfree(info); } -static size_t http_write(uint8_t *ptr, size_t size, size_t nmemb, - struct update_info *info) +static size_t http_write(uint8_t *ptr, size_t size, size_t nmemb, struct update_info *info) { size_t total = size * nmemb; if (total) @@ -78,8 +76,7 @@ static size_t http_write(uint8_t *ptr, size_t size, size_t nmemb, return total; } -static size_t http_header(char *buffer, size_t size, size_t nitems, - struct update_info *info) +static size_t http_header(char *buffer, size_t size, size_t nitems, struct update_info *info) { if (!strncmp(buffer, "ETag: ", 6)) { char *etag = buffer + 6; @@ -102,8 +99,7 @@ static size_t http_header(char *buffer, size_t size, size_t nitems, return nitems * size; } -static bool do_http_request(struct update_info *info, const char *url, - long *response_code) +static bool do_http_request(struct update_info *info, const char *url, long *response_code) { CURLcode code; uint8_t null_terminator = 0; @@ -121,25 +117,21 @@ static bool do_http_request(struct update_info *info, const char *url, if (!info->remote_url) { // We only care about headers from the main package file - curl_easy_setopt(info->curl, CURLOPT_HEADERFUNCTION, - http_header); + curl_easy_setopt(info->curl, CURLOPT_HEADERFUNCTION, http_header); curl_easy_setopt(info->curl, CURLOPT_HEADERDATA, info); } code = curl_easy_perform(info->curl); if (code != CURLE_OK) { - warn("Remote update of URL \"%s\" failed: %s", url, - info->error); + warn("Remote update of URL \"%s\" failed: %s", url, info->error); return false; } - if (curl_easy_getinfo(info->curl, CURLINFO_RESPONSE_CODE, - response_code) != CURLE_OK) + if (curl_easy_getinfo(info->curl, CURLINFO_RESPONSE_CODE, response_code) != CURLE_OK) return false; if (*response_code >= 400) { - warn("Remote update of URL \"%s\" failed: HTTP/%ld", url, - *response_code); + warn("Remote update of URL \"%s\" failed: HTTP/%ld", url, *response_code); return false; } @@ -192,8 +184,7 @@ static bool init_update(struct update_info *info) info->etag_local = bstrdup(etag); - info->header = curl_slist_append(info->header, - if_none_match.array); + info->header = curl_slist_append(info->header, if_none_match.array); dstr_free(&if_none_match); } @@ -225,9 +216,7 @@ static void copy_local_to_cache(struct update_info *info, const char *file) bfree(temp_file_path); } -static void enum_files(obs_data_t *package, - bool (*enum_func)(void *param, obs_data_t *file), - void *param) +static void enum_files(obs_data_t *package, bool (*enum_func)(void *param, obs_data_t *file), void *param) { obs_data_array_t *array = obs_data_get_array(package, "files"); size_t num; @@ -274,9 +263,8 @@ static bool newer_than_cache(void *param, obs_data_t *cache_file) static bool update_files_to_local(void *param, obs_data_t *local_file) { struct update_info *info = param; - struct file_update_data data = { - .name = obs_data_get_string(local_file, "name"), - .version = (int)obs_data_get_int(local_file, "version")}; + struct file_update_data data = {.name = obs_data_get_string(local_file, "name"), + .version = (int)obs_data_get_int(local_file, "version")}; enum_files(info->cache_package, newer_than_cache, &data); if (data.newer || !data.found) @@ -308,8 +296,7 @@ static int update_local_version(struct update_info *info) return cache_version; } -static inline bool do_relative_http_request(struct update_info *info, - const char *url, const char *file) +static inline bool do_relative_http_request(struct update_info *info, const char *url, const char *file) { long response_code; char *full_url = get_path(url, file); @@ -318,17 +305,14 @@ static inline bool do_relative_http_request(struct update_info *info, return success && response_code == 200; } -static inline void write_file_data(struct update_info *info, - const char *base_path, const char *file) +static inline void write_file_data(struct update_info *info, const char *base_path, const char *file) { char *full_path = get_path(base_path, file); - os_quick_write_utf8_file(full_path, (char *)info->file_data.array, - info->file_data.num - 1, false); + os_quick_write_utf8_file(full_path, (char *)info->file_data.array, info->file_data.num - 1, false); bfree(full_path); } -static inline void replace_file(const char *src_base_path, - const char *dst_base_path, const char *file) +static inline void replace_file(const char *src_base_path, const char *dst_base_path, const char *file) { char *src_path = get_path(src_base_path, file); char *dst_path = get_path(dst_base_path, file); @@ -346,9 +330,8 @@ static bool update_remote_files(void *param, obs_data_t *remote_file) { struct update_info *info = param; - struct file_update_data data = { - .name = obs_data_get_string(remote_file, "name"), - .version = (int)obs_data_get_int(remote_file, "version")}; + struct file_update_data data = {.name = obs_data_get_string(remote_file, "name"), + .version = (int)obs_data_get_int(remote_file, "version")}; enum_files(info->cache_package, newer_than_cache, &data); if (!data.newer && data.found) @@ -370,8 +353,7 @@ static bool update_remote_files(void *param, obs_data_t *remote_file) info->file_data.da = download_data.buffer.da; if (!confirm) { - info("Update file '%s' (version %d) rejected", - data.name, data.version); + info("Update file '%s' (version %d) rejected", data.name, data.version); return true; } } @@ -379,8 +361,7 @@ static bool update_remote_files(void *param, obs_data_t *remote_file) write_file_data(info, info->temp, data.name); replace_file(info->temp, info->cache, data.name); - info("Successfully updated file '%s' (version %d)", data.name, - data.version); + info("Successfully updated file '%s' (version %d)", data.name, data.version); return true; } @@ -421,8 +402,7 @@ static void update_remote_version(struct update_info *info, int cur_version) update_save_metadata(info); - info->remote_package = - obs_data_create_from_json((char *)info->file_data.array); + info->remote_package = obs_data_create_from_json((char *)info->file_data.array); if (!info->remote_package) { warn("Failed to initialize remote package json"); return; @@ -469,12 +449,9 @@ static void *update_thread(void *data) return NULL; } -update_info_t *update_info_create(const char *log_prefix, - const char *user_agent, - const char *update_url, const char *local_dir, - const char *cache_dir, - confirm_file_callback_t confirm_callback, - void *param) +update_info_t *update_info_create(const char *log_prefix, const char *user_agent, const char *update_url, + const char *local_dir, const char *cache_dir, + confirm_file_callback_t confirm_callback, void *param) { struct update_info *info; struct dstr dir = {0}; @@ -483,8 +460,7 @@ update_info_t *update_info_create(const char *log_prefix, log_prefix = ""; if (os_mkdir(cache_dir) < 0) { - blog(LOG_WARNING, "%sCould not create cache directory %s", - log_prefix, cache_dir); + blog(LOG_WARNING, "%sCould not create cache directory %s", log_prefix, cache_dir); return NULL; } @@ -494,8 +470,7 @@ update_info_t *update_info_create(const char *log_prefix, dstr_cat(&dir, ".temp"); if (os_mkdir(dir.array) < 0) { - blog(LOG_WARNING, "%sCould not create temp directory %s", - log_prefix, cache_dir); + blog(LOG_WARNING, "%sCould not create temp directory %s", log_prefix, cache_dir); dstr_free(&dir); return NULL; } @@ -541,10 +516,8 @@ static void *single_file_thread(void *data) return NULL; } -update_info_t * -update_info_create_single(const char *log_prefix, const char *user_agent, - const char *file_url, - confirm_file_callback_t confirm_callback, void *param) +update_info_t *update_info_create_single(const char *log_prefix, const char *user_agent, const char *file_url, + confirm_file_callback_t confirm_callback, void *param) { struct update_info *info; diff --git a/shared/file-updater/file-updater/file-updater.h b/shared/file-updater/file-updater/file-updater.h index e50b12671..0f2253a5b 100644 --- a/shared/file-updater/file-updater/file-updater.h +++ b/shared/file-updater/file-updater/file-updater.h @@ -12,16 +12,11 @@ struct file_download_data { DARRAY(uint8_t) buffer; }; -typedef bool (*confirm_file_callback_t)(void *param, - struct file_download_data *file); +typedef bool (*confirm_file_callback_t)(void *param, struct file_download_data *file); -update_info_t *update_info_create(const char *log_prefix, - const char *user_agent, - const char *update_url, const char *local_dir, - const char *cache_dir, - confirm_file_callback_t confirm_callback, - void *param); -update_info_t *update_info_create_single( - const char *log_prefix, const char *user_agent, const char *file_url, - confirm_file_callback_t confirm_callback, void *param); +update_info_t *update_info_create(const char *log_prefix, const char *user_agent, const char *update_url, + const char *local_dir, const char *cache_dir, + confirm_file_callback_t confirm_callback, void *param); +update_info_t *update_info_create_single(const char *log_prefix, const char *user_agent, const char *file_url, + confirm_file_callback_t confirm_callback, void *param); void update_info_destroy(update_info_t *info); diff --git a/shared/happy-eyeballs/happy-eyeballs.c b/shared/happy-eyeballs/happy-eyeballs.c index 126bae55a..ab5cfcb07 100644 --- a/shared/happy-eyeballs/happy-eyeballs.c +++ b/shared/happy-eyeballs/happy-eyeballs.c @@ -172,12 +172,11 @@ static int check_comodo(struct happy_eyeballs_ctx *context) HOSTENT *h = gethostbyname("localhost"); if (!h && GetLastError() == WSAHOST_NOT_FOUND) { context->error = WSAHOST_NOT_FOUND; - context->error_message = - "happy-eyeballs: Connection test failed. " - "This error is likely caused by Comodo Internet " - "Security running OBS in sandbox mode. Please add " - "OBS to the Comodo automatic sandbox exclusion list, " - "restart OBS and try again (11001)."; + context->error_message = "happy-eyeballs: Connection test failed. " + "This error is likely caused by Comodo Internet " + "Security running OBS in sandbox mode. Please add " + "OBS to the Comodo automatic sandbox exclusion list, " + "restart OBS and try again (11001)."; return STATUS_FAILURE; } #else @@ -186,8 +185,7 @@ static int check_comodo(struct happy_eyeballs_ctx *context) return STATUS_SUCCESS; } -static int build_addr_list(const char *hostname, int port, - struct happy_eyeballs_ctx *context) +static int build_addr_list(const char *hostname, int port, struct happy_eyeballs_ctx *context) { struct addrinfo hints = {0}; @@ -206,8 +204,7 @@ static int build_addr_list(const char *hostname, int port, dstr_printf(&port_str, "%d", port); uint64_t start_time = os_gettime_ns(); - int err = getaddrinfo(hostname, port_str.array, &hints, - &context->addresses); + int err = getaddrinfo(hostname, port_str.array, &hints, &context->addresses); context->name_resolution_time_ns = os_gettime_ns() - start_time; dstr_free(&port_str); if (err) { @@ -221,12 +218,10 @@ static int build_addr_list(const char *hostname, int port, struct addrinfo *cur = prev->ai_next; while (cur) { - if (prev->ai_family == cur->ai_family && - (cur->ai_family == AF_INET || cur->ai_family == AF_INET6)) { + if (prev->ai_family == cur->ai_family && (cur->ai_family == AF_INET || cur->ai_family == AF_INET6)) { /* If the current protocol family matches the previous * one, look for the next instance of the other kind */ - const int target_family = - prev->ai_family == AF_INET ? AF_INET6 : AF_INET; + const int target_family = prev->ai_family == AF_INET ? AF_INET6 : AF_INET; struct addrinfo *it = cur->ai_next; struct addrinfo *prev_it = cur; @@ -334,8 +329,7 @@ static int coalesce_errors(struct happy_eyeballs_ctx *context) static void *happy_connect_worker(void *arg) { - struct happy_connect_worker_args *args = - (struct happy_connect_worker_args *)arg; + struct happy_connect_worker_args *args = (struct happy_connect_worker_args *)arg; struct happy_eyeballs_ctx *context = args->context; if (args->sockfd == INVALID_SOCKET) { @@ -347,17 +341,14 @@ static void *happy_connect_worker(void *arg) } #if !defined(_WIN32) && defined(SO_NOSIGPIPE) - setsockopt(args->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &(int){1}, - sizeof(int)); + setsockopt(args->sockfd, SOL_SOCKET, SO_NOSIGPIPE, &(int){1}, sizeof(int)); #endif if (context->bind_addr.ss_family != 0 && - bind(args->sockfd, (const struct sockaddr *)&context->bind_addr, - context->bind_addr_len) < 0) { + bind(args->sockfd, (const struct sockaddr *)&context->bind_addr, context->bind_addr_len) < 0) { goto failure; } - if (connect(args->sockfd, args->address->ai_addr, - (int)args->address->ai_addrlen) == 0) { + if (connect(args->sockfd, args->address->ai_addr, (int)args->address->ai_addrlen) == 0) { /* success, check if we're the winner. */ pthread_mutex_lock(&context->winner_mutex); @@ -366,10 +357,8 @@ static void *happy_connect_worker(void *arg) if (os_event_try(context->race_completed_event) == EAGAIN) { /* We are the winner. */ context->socket_fd = args->sockfd; - memcpy(&context->winner_addr, args->address->ai_addr, - args->address->ai_addrlen); - context->winner_addr_len = - (socklen_t)args->address->ai_addrlen; + memcpy(&context->winner_addr, args->address->ai_addr, args->address->ai_addrlen); + context->winner_addr_len = (socklen_t)args->address->ai_addrlen; signal_end(context); } @@ -391,9 +380,7 @@ failure: * status and signal the completion event. */ pthread_mutex_lock(&context->candidate_mutex); for (size_t i = 0; i < context->candidates.num && !active; i++) { - active = os_event_try(context->candidates.array[i] - .socket_completed_event) == - EAGAIN; + active = os_event_try(context->candidates.array[i].socket_completed_event) == EAGAIN; } pthread_mutex_unlock(&context->candidate_mutex); @@ -414,12 +401,10 @@ success: return NULL; } -static int launch_worker(struct happy_eyeballs_ctx *context, - struct addrinfo *addr) +static int launch_worker(struct happy_eyeballs_ctx *context, struct addrinfo *addr) { #ifdef _WIN32 - SOCKET fd = WSASocket(addr->ai_family, SOCK_STREAM, IPPROTO_TCP, NULL, - 0, WSA_FLAG_OVERLAPPED); + SOCKET fd = WSASocket(addr->ai_family, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); #else SOCKET fd = socket(addr->ai_family, SOCK_STREAM, IPPROTO_TCP); #endif @@ -430,12 +415,10 @@ static int launch_worker(struct happy_eyeballs_ctx *context, pthread_mutex_lock(&context->candidate_mutex); - struct happy_eyeballs_candidate *candidate = - da_push_back_new(context->candidates); + struct happy_eyeballs_candidate *candidate = da_push_back_new(context->candidates); candidate->sockfd = fd; struct happy_connect_worker_args *args = - (struct happy_connect_worker_args *)malloc( - sizeof(struct happy_connect_worker_args)); + (struct happy_connect_worker_args *)malloc(sizeof(struct happy_connect_worker_args)); if (args == NULL) { context->error = ENOMEM; context->error_message = "happy-eyeballs: Failed to allocate " @@ -444,8 +427,7 @@ static int launch_worker(struct happy_eyeballs_ctx *context, return STATUS_FAILURE; } - int result = os_event_init(&candidate->socket_completed_event, - OS_EVENT_TYPE_MANUAL); + int result = os_event_init(&candidate->socket_completed_event, OS_EVENT_TYPE_MANUAL); if (result != 0) { /* failure to create the socket completed event */ context->error = result; @@ -463,8 +445,7 @@ static int launch_worker(struct happy_eyeballs_ctx *context, pthread_mutex_unlock(&context->candidate_mutex); /* Launch worker thread; `args` ownership is passed to this thread */ - result = pthread_create(&candidate->thread, NULL, happy_connect_worker, - args); + result = pthread_create(&candidate->thread, NULL, happy_connect_worker, args); if (result != 0) { /* failure to start the worker thread */ context->error = result; @@ -488,8 +469,7 @@ int happy_eyeballs_create(struct happy_eyeballs_ctx **context) if (context == NULL) return STATUS_INVALID_ARGUMENT; - struct happy_eyeballs_ctx *ctx = (struct happy_eyeballs_ctx *)malloc( - sizeof(struct happy_eyeballs_ctx)); + struct happy_eyeballs_ctx *ctx = (struct happy_eyeballs_ctx *)malloc(sizeof(struct happy_eyeballs_ctx)); if (ctx == NULL) return -ENOMEM; @@ -502,8 +482,7 @@ int happy_eyeballs_create(struct happy_eyeballs_ctx **context) /* race_completed_event will be signalled when there is a winner or all * attempts have failed */ - int result = - os_event_init(&ctx->race_completed_event, OS_EVENT_TYPE_MANUAL); + int result = os_event_init(&ctx->race_completed_event, OS_EVENT_TYPE_MANUAL); /* this mutex is used to avoid the situation where we may have two * simultaneous winners and inconsistent values set to the context. */ @@ -541,8 +520,7 @@ int happy_eyeballs_create(struct happy_eyeballs_ctx **context) return -abs(result); } -int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, - const char *hostname, int port) +int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, const char *hostname, int port) { if (hostname == NULL || context == NULL || port == 0) return STATUS_INVALID_ARGUMENT; @@ -564,9 +542,7 @@ int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, * null) * 3. We have seen two candidates of the same family in a row, stop * happy eyeballs and let the previous attempt go it alone. */ - for (int i = 0; i < HAPPY_EYEBALLS_MAX_ATTEMPTS && next && - next->ai_family != prev_family; - i++) { + for (int i = 0; i < HAPPY_EYEBALLS_MAX_ATTEMPTS && next && next->ai_family != prev_family; i++) { /* Launch a worker thread for this address */ int result = launch_worker(context, next); if (result != STATUS_SUCCESS) @@ -574,8 +550,7 @@ int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, /* Wait until the delay between attempts times out or we get * signalled... */ - result = os_event_timedwait(context->race_completed_event, - HAPPY_EYEBALLS_DELAY_MS); + result = os_event_timedwait(context->race_completed_event, HAPPY_EYEBALLS_DELAY_MS); if (result == 0) { /* signalled. Break out of the loop. */ break; @@ -598,13 +573,8 @@ int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, if (happy_eyeballs_try(context) == EAGAIN) { int active_count = 0; for (size_t i = 0; i < context->candidates.num; i++) - active_count += - (os_event_try( - context->candidates.array[i] - .socket_completed_event) == - EAGAIN); - if (active_count == 0 && - coalesce_errors(context) == STATUS_SUCCESS) + active_count += (os_event_try(context->candidates.array[i].socket_completed_event) == EAGAIN); + if (active_count == 0 && coalesce_errors(context) == STATUS_SUCCESS) signal_end(context); } @@ -628,18 +598,15 @@ int happy_eyeballs_try(struct happy_eyeballs_ctx *context) int happy_eyeballs_timedwait_default(struct happy_eyeballs_ctx *context) { - return happy_eyeballs_timedwait(context, - HAPPY_EYEBALLS_CONNECTION_TIMEOUT_MS); + return happy_eyeballs_timedwait(context, HAPPY_EYEBALLS_CONNECTION_TIMEOUT_MS); } -int happy_eyeballs_timedwait(struct happy_eyeballs_ctx *context, - unsigned long time_in_millis) +int happy_eyeballs_timedwait(struct happy_eyeballs_ctx *context, unsigned long time_in_millis) { if (context == NULL) return STATUS_INVALID_ARGUMENT; - int status = os_event_timedwait(context->race_completed_event, - time_in_millis); + int status = os_event_timedwait(context->race_completed_event, time_in_millis); if (context->error != 0) return STATUS_FAILURE; @@ -671,16 +638,14 @@ static void *destroy_thread(void *param) for (size_t i = 0; i < context->candidates.num; i++) { if (context->candidates.array[i].sockfd != INVALID_SOCKET && context->candidates.array[i].sockfd != context->socket_fd) { - shutdown(context->candidates.array[i].sockfd, - SHUT_RDWR); + shutdown(context->candidates.array[i].sockfd, SHUT_RDWR); } } /* Join threads */ for (size_t i = 0; i < context->candidates.num; i++) { pthread_join(context->candidates.array[i].thread, NULL); - os_event_destroy( - context->candidates.array[i].socket_completed_event); + os_event_destroy(context->candidates.array[i].socket_completed_event); } /* Close sockets */ @@ -720,16 +685,14 @@ int happy_eyeballs_destroy(struct happy_eyeballs_ctx *context) /* ------------------------------------------------------------------------- */ /* Setters & Getters */ -int happy_eyeballs_set_bind_addr(struct happy_eyeballs_ctx *context, - socklen_t addr_len, +int happy_eyeballs_set_bind_addr(struct happy_eyeballs_ctx *context, socklen_t addr_len, struct sockaddr_storage *addr_storage) { if (!context) return STATUS_INVALID_ARGUMENT; if (addr_storage && addr_len > 0) { - memcpy(&context->bind_addr, addr_storage, - sizeof(struct sockaddr_storage)); + memcpy(&context->bind_addr, addr_storage, sizeof(struct sockaddr_storage)); context->bind_addr_len = addr_len; } else { context->bind_addr_len = 0; @@ -743,8 +706,7 @@ SOCKET happy_eyeballs_get_socket_fd(const struct happy_eyeballs_ctx *context) return context ? context->socket_fd : STATUS_INVALID_ARGUMENT; } -int happy_eyeballs_get_remote_addr(const struct happy_eyeballs_ctx *context, - struct sockaddr_storage *addr) +int happy_eyeballs_get_remote_addr(const struct happy_eyeballs_ctx *context, struct sockaddr_storage *addr) { if (!context || !addr) return STATUS_INVALID_ARGUMENT; @@ -758,23 +720,19 @@ int happy_eyeballs_get_error_code(const struct happy_eyeballs_ctx *context) return context ? context->error : STATUS_INVALID_ARGUMENT; } -const char * -happy_eyeballs_get_error_message(const struct happy_eyeballs_ctx *context) +const char *happy_eyeballs_get_error_message(const struct happy_eyeballs_ctx *context) { return context ? context->error_message : NULL; } -uint64_t happy_eyeballs_get_name_resolution_time_ns( - const struct happy_eyeballs_ctx *context) +uint64_t happy_eyeballs_get_name_resolution_time_ns(const struct happy_eyeballs_ctx *context) { return context ? context->name_resolution_time_ns : 0; } -uint64_t -happy_eyeballs_get_connection_time_ns(const struct happy_eyeballs_ctx *context) +uint64_t happy_eyeballs_get_connection_time_ns(const struct happy_eyeballs_ctx *context) { - if (!context || - context->connection_time_start > context->connection_time_end) + if (!context || context->connection_time_start > context->connection_time_end) return 0; return context->connection_time_end - context->connection_time_start; diff --git a/shared/happy-eyeballs/happy-eyeballs.h b/shared/happy-eyeballs/happy-eyeballs.h index 3ef62e2de..7bf68e70e 100644 --- a/shared/happy-eyeballs/happy-eyeballs.h +++ b/shared/happy-eyeballs/happy-eyeballs.h @@ -79,8 +79,7 @@ int happy_eyeballs_create(struct happy_eyeballs_ctx **context); * * This function will return -EINVAL if context, hostname, or port are not set. */ -int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, - const char *hostname, int port); +int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, const char *hostname, int port); /** * Optionally set the interface address. You may pass 0 and NULL for these @@ -89,8 +88,7 @@ int happy_eyeballs_connect(struct happy_eyeballs_ctx *context, * * Returns 0 on success or -EINVAL if context is not set. */ -int happy_eyeballs_set_bind_addr(struct happy_eyeballs_ctx *context, - socklen_t addr_len, +int happy_eyeballs_set_bind_addr(struct happy_eyeballs_ctx *context, socklen_t addr_len, struct sockaddr_storage *addr_storage); /** @@ -113,8 +111,7 @@ SOCKET happy_eyeballs_get_socket_fd(const struct happy_eyeballs_ctx *context); * On success, returns the address length of the sockaddr or -EINVAL if context * is not set. */ -int happy_eyeballs_get_remote_addr(const struct happy_eyeballs_ctx *context, - struct sockaddr_storage *addr); +int happy_eyeballs_get_remote_addr(const struct happy_eyeballs_ctx *context, struct sockaddr_storage *addr); /** * Returns the current error code for the context or -EINVAL if context is not @@ -126,21 +123,18 @@ int happy_eyeballs_get_error_code(const struct happy_eyeballs_ctx *context); * Returns the current error message for the context. The returned value may be * NULL if there is no error message. */ -const char * -happy_eyeballs_get_error_message(const struct happy_eyeballs_ctx *context); +const char *happy_eyeballs_get_error_message(const struct happy_eyeballs_ctx *context); /** * Returns the amount of time domain name resolution took, in nanoseconds */ -uint64_t happy_eyeballs_get_name_resolution_time_ns( - const struct happy_eyeballs_ctx *context); +uint64_t happy_eyeballs_get_name_resolution_time_ns(const struct happy_eyeballs_ctx *context); /** * Returns the amount of time connection (or failure) took, in nanoseconds, or * 0 if happy eyeballs has not yet completed. */ -uint64_t -happy_eyeballs_get_connection_time_ns(const struct happy_eyeballs_ctx *context); +uint64_t happy_eyeballs_get_connection_time_ns(const struct happy_eyeballs_ctx *context); /** * Test if the process has completed without blocking. This function will @@ -169,8 +163,7 @@ int happy_eyeballs_try(struct happy_eyeballs_ctx *context); * continue to wait by calling this function again, or call * happy_eyeballs_destroy to close the session. */ -int happy_eyeballs_timedwait(struct happy_eyeballs_ctx *context, - unsigned long time_in_millis); +int happy_eyeballs_timedwait(struct happy_eyeballs_ctx *context, unsigned long time_in_millis); /** * Call timedwait with a default wait duration of 25 seconds. diff --git a/shared/ipc-util/ipc-util/pipe-windows.c b/shared/ipc-util/ipc-util/pipe-windows.c index cdecf9cf3..e19585beb 100644 --- a/shared/ipc-util/ipc-util/pipe-windows.c +++ b/shared/ipc-util/ipc-util/pipe-windows.c @@ -60,15 +60,13 @@ error: return NULL; } -static inline bool ipc_pipe_internal_create_pipe(ipc_pipe_server_t *pipe, - const char *name) +static inline bool ipc_pipe_internal_create_pipe(ipc_pipe_server_t *pipe, const char *name) { SECURITY_ATTRIBUTES sa; char new_name[512]; void *sd; const DWORD access = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED; - const DWORD flags = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | - PIPE_WAIT; + const DWORD flags = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE | PIPE_WAIT; strcpy_s(new_name, sizeof(new_name), "\\\\.\\pipe\\"); strcat_s(new_name, sizeof(new_name), name); @@ -82,16 +80,13 @@ static inline bool ipc_pipe_internal_create_pipe(ipc_pipe_server_t *pipe, sa.lpSecurityDescriptor = sd; sa.bInheritHandle = false; - pipe->handle = CreateNamedPipeA(new_name, access, flags, 1, - IPC_PIPE_BUF_SIZE, IPC_PIPE_BUF_SIZE, 0, - &sa); + pipe->handle = CreateNamedPipeA(new_name, access, flags, 1, IPC_PIPE_BUF_SIZE, IPC_PIPE_BUF_SIZE, 0, &sa); free(sd); return pipe->handle != INVALID_HANDLE_VALUE; } -static inline void ipc_pipe_internal_ensure_capacity(ipc_pipe_server_t *pipe, - size_t new_size) +static inline void ipc_pipe_internal_ensure_capacity(ipc_pipe_server_t *pipe, size_t new_size) { if (pipe->capacity >= new_size) { return; @@ -101,8 +96,7 @@ static inline void ipc_pipe_internal_ensure_capacity(ipc_pipe_server_t *pipe, pipe->capacity = new_size; } -static inline void ipc_pipe_internal_append_bytes(ipc_pipe_server_t *pipe, - uint8_t *bytes, size_t size) +static inline void ipc_pipe_internal_append_bytes(ipc_pipe_server_t *pipe, uint8_t *bytes, size_t size) { size_t new_size = pipe->size + size; ipc_pipe_internal_ensure_capacity(pipe, new_size); @@ -132,20 +126,17 @@ static DWORD CALLBACK ipc_pipe_internal_server_thread(LPVOID param) DWORD bytes = 0; bool success; - success = !!ReadFile(pipe->handle, buf, IPC_PIPE_BUF_SIZE, NULL, - &pipe->overlap); + success = !!ReadFile(pipe->handle, buf, IPC_PIPE_BUF_SIZE, NULL, &pipe->overlap); if (!success && !ipc_pipe_internal_io_pending()) { break; } - DWORD wait = WaitForMultipleObjects(_countof(handles), handles, - FALSE, INFINITE); + DWORD wait = WaitForMultipleObjects(_countof(handles), handles, FALSE, INFINITE); if (wait != WAIT_OBJECT_0) { break; } - success = !!GetOverlappedResult(pipe->handle, &pipe->overlap, - &bytes, true); + success = !!GetOverlappedResult(pipe->handle, &pipe->overlap, &bytes, true); if (!success || !bytes) { break; } @@ -153,8 +144,7 @@ static DWORD CALLBACK ipc_pipe_internal_server_thread(LPVOID param) ipc_pipe_internal_append_bytes(pipe, buf, (size_t)bytes); if (success) { - pipe->read_callback(pipe->param, pipe->read_data, - pipe->size); + pipe->read_callback(pipe->param, pipe->read_data, pipe->size); pipe->size = 0; } } @@ -163,16 +153,13 @@ static DWORD CALLBACK ipc_pipe_internal_server_thread(LPVOID param) return 0; } -static inline bool -ipc_pipe_internal_start_server_thread(ipc_pipe_server_t *pipe) +static inline bool ipc_pipe_internal_start_server_thread(ipc_pipe_server_t *pipe) { - pipe->thread = CreateThread(NULL, 0, ipc_pipe_internal_server_thread, - pipe, 0, NULL); + pipe->thread = CreateThread(NULL, 0, ipc_pipe_internal_server_thread, pipe, 0, NULL); return pipe->thread != NULL; } -static inline bool -ipc_pipe_internal_wait_for_connection(ipc_pipe_server_t *pipe) +static inline bool ipc_pipe_internal_wait_for_connection(ipc_pipe_server_t *pipe) { bool success; @@ -181,8 +168,7 @@ ipc_pipe_internal_wait_for_connection(ipc_pipe_server_t *pipe) return success || (!success && ipc_pipe_internal_io_pending()); } -static inline bool ipc_pipe_internal_open_pipe(ipc_pipe_client_t *pipe, - const char *name) +static inline bool ipc_pipe_internal_open_pipe(ipc_pipe_client_t *pipe, const char *name) { DWORD mode = PIPE_READMODE_MESSAGE; char new_name[512]; @@ -190,8 +176,7 @@ static inline bool ipc_pipe_internal_open_pipe(ipc_pipe_client_t *pipe, strcpy_s(new_name, sizeof(new_name), "\\\\.\\pipe\\"); strcat_s(new_name, sizeof(new_name), name); - pipe->handle = CreateFileA(new_name, GENERIC_READ | GENERIC_WRITE, 0, - NULL, OPEN_EXISTING, 0, NULL); + pipe->handle = CreateFileA(new_name, GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, 0, NULL); if (pipe->handle == INVALID_HANDLE_VALUE) { return false; } @@ -201,8 +186,7 @@ static inline bool ipc_pipe_internal_open_pipe(ipc_pipe_client_t *pipe, /* ------------------------------------------------------------------------- */ -bool ipc_pipe_server_start(ipc_pipe_server_t *pipe, const char *name, - ipc_pipe_read_t read_callback, void *param) +bool ipc_pipe_server_start(ipc_pipe_server_t *pipe, const char *name, ipc_pipe_read_t read_callback, void *param) { pipe->read_callback = read_callback; pipe->param = param; @@ -271,8 +255,7 @@ void ipc_pipe_client_free(ipc_pipe_client_t *pipe) memset(pipe, 0, sizeof(*pipe)); } -bool ipc_pipe_client_write(ipc_pipe_client_t *pipe, const void *data, - size_t size) +bool ipc_pipe_client_write(ipc_pipe_client_t *pipe, const void *data, size_t size) { DWORD bytes; diff --git a/shared/ipc-util/ipc-util/pipe.h b/shared/ipc-util/ipc-util/pipe.h index 348e7103a..13684a39b 100644 --- a/shared/ipc-util/ipc-util/pipe.h +++ b/shared/ipc-util/ipc-util/pipe.h @@ -34,14 +34,12 @@ typedef struct ipc_pipe_client ipc_pipe_client_t; typedef void (*ipc_pipe_read_t)(void *param, uint8_t *data, size_t size); -bool ipc_pipe_server_start(ipc_pipe_server_t *pipe, const char *name, - ipc_pipe_read_t read_callback, void *param); +bool ipc_pipe_server_start(ipc_pipe_server_t *pipe, const char *name, ipc_pipe_read_t read_callback, void *param); void ipc_pipe_server_free(ipc_pipe_server_t *pipe); bool ipc_pipe_client_open(ipc_pipe_client_t *pipe, const char *name); void ipc_pipe_client_free(ipc_pipe_client_t *pipe); -bool ipc_pipe_client_write(ipc_pipe_client_t *pipe, const void *data, - size_t size); +bool ipc_pipe_client_write(ipc_pipe_client_t *pipe, const void *data, size_t size); static inline bool ipc_pipe_client_valid(ipc_pipe_client_t *pipe); #ifdef _WIN32 diff --git a/shared/media-playback/media-playback/cache.c b/shared/media-playback/media-playback/cache.c index dc5a5eb7d..d2c9e7b26 100644 --- a/shared/media-playback/media-playback/cache.c +++ b/shared/media-playback/media-playback/cache.c @@ -78,8 +78,7 @@ static inline bool mp_cache_sleep(mp_cache_t *c) } else { const uint64_t t = os_gettime_ns(); if (c->next_ns > t) { - const uint32_t delta_ms = - (uint32_t)((c->next_ns - t + 500000) / 1000000); + const uint32_t delta_ms = (uint32_t)((c->next_ns - t + 500000) / 1000000); if (delta_ms > 0) { static const uint32_t timeout_ms = 200; timeout = delta_ms > timeout_ms; @@ -164,11 +163,9 @@ static void seek_to(mp_cache_t *c, int64_t pos) size_t next_idx = new_v_idx + 1; if (next_idx == c->video_frames.num) { - c->next_v_ts = - (int64_t)v->timestamp + c->final_v_duration; + c->next_v_ts = (int64_t)v->timestamp + c->final_v_duration; } else { - struct obs_source_frame *next = - &c->video_frames.array[next_idx]; + struct obs_source_frame *next = &c->video_frames.array[next_idx]; c->next_v_ts = (int64_t)next->timestamp; } } @@ -184,11 +181,9 @@ static void seek_to(mp_cache_t *c, int64_t pos) size_t next_idx = new_a_idx + 1; if (next_idx == c->audio_segments.num) { - c->next_a_ts = - (int64_t)a->timestamp + c->final_a_duration; + c->next_a_ts = (int64_t)a->timestamp + c->final_a_duration; } else { - struct obs_source_audio *next = - &c->audio_segments.array[next_idx]; + struct obs_source_audio *next = &c->audio_segments.array[next_idx]; c->next_a_ts = (int64_t)next->timestamp; } } @@ -202,22 +197,19 @@ static void seek_to(mp_cache_t *c, int64_t pos) static inline bool mp_media_can_play_video(mp_cache_t *c) { - return !v_eof(c) && (c->next_v_ts <= c->next_pts_ns || - (c->next_v_ts - c->next_pts_ns > MAX_TS_VAR)); + return !v_eof(c) && (c->next_v_ts <= c->next_pts_ns || (c->next_v_ts - c->next_pts_ns > MAX_TS_VAR)); } static inline bool mp_media_can_play_audio(mp_cache_t *c) { - return !a_eof(c) && (c->next_a_ts <= c->next_pts_ns || - (c->next_a_ts - c->next_pts_ns > MAX_TS_VAR)); + return !a_eof(c) && (c->next_a_ts <= c->next_pts_ns || (c->next_a_ts - c->next_pts_ns > MAX_TS_VAR)); } static inline void calc_next_v_ts(mp_cache_t *c, struct obs_source_frame *frame) { int64_t offset; if (c->next_v_idx < c->video_frames.num) { - struct obs_source_frame *next = - &c->video_frames.array[c->next_v_idx]; + struct obs_source_frame *next = &c->video_frames.array[c->next_v_idx]; offset = (int64_t)(next->timestamp - frame->timestamp); } else { offset = c->final_v_duration; @@ -230,8 +222,7 @@ static inline void calc_next_a_ts(mp_cache_t *c, struct obs_source_audio *audio) { int64_t offset; if (c->next_a_idx < c->audio_segments.num) { - struct obs_source_audio *next = - &c->audio_segments.array[c->next_a_idx]; + struct obs_source_audio *next = &c->audio_segments.array[c->next_a_idx]; offset = (int64_t)(next->timestamp - audio->timestamp); } else { offset = c->final_a_duration; @@ -252,8 +243,7 @@ static void mp_cache_next_video(mp_cache_t *c, bool preload) struct obs_source_frame *frame = &c->video_frames.array[c->next_v_idx]; struct obs_source_frame dup = *frame; - dup.timestamp = c->base_ts + dup.timestamp - c->start_ts + - c->play_sys_ts - base_sys_ts; + dup.timestamp = c->base_ts + dup.timestamp - c->start_ts + c->play_sys_ts - base_sys_ts; if (!preload) { if (!mp_media_can_play_video(c)) @@ -287,12 +277,10 @@ static void mp_cache_next_audio(mp_cache_t *c) if (!mp_media_can_play_audio(c)) return; - struct obs_source_audio *audio = - &c->audio_segments.array[c->next_a_idx]; + struct obs_source_audio *audio = &c->audio_segments.array[c->next_a_idx]; struct obs_source_audio dup = *audio; - dup.timestamp = c->base_ts + dup.timestamp - c->start_ts + - c->play_sys_ts - base_sys_ts; + dup.timestamp = c->base_ts + dup.timestamp - c->start_ts + c->play_sys_ts - base_sys_ts; if (c->a_cb) c->a_cb(c->opaque, &dup); @@ -386,8 +374,7 @@ static inline bool mp_cache_thread(mp_cache_t *c) } for (;;) { - bool reset, kill, is_active, seek, pause, reset_time, - preload_frame; + bool reset, kill, is_active, seek, pause, reset_time, preload_frame; int64_t seek_pos; bool timeout = false; @@ -498,8 +485,7 @@ static void fill_audio(void *data, struct obs_source_audio *audio) mp_cache_t *c = data; struct obs_source_audio dup = *audio; - size_t size = - get_total_audio_size(dup.format, dup.speakers, dup.frames); + size_t size = get_total_audio_size(dup.format, dup.speakers, dup.frames); dup.data[0] = bmalloc(size); size_t planes = get_audio_planes(dup.format, dup.speakers); @@ -523,8 +509,7 @@ static void fill_audio(void *data, struct obs_source_audio *audio) da_push_back(c->audio_segments, &dup); } -static inline bool mp_cache_init_internal(mp_cache_t *c, - const struct mp_media_info *info) +static inline bool mp_cache_init_internal(mp_cache_t *c, const struct mp_media_info *info) { if (pthread_mutex_init(&c->mutex, NULL) != 0) { blog(LOG_WARNING, "MP: Failed to init mutex"); diff --git a/shared/media-playback/media-playback/decode.c b/shared/media-playback/media-playback/decode.c index 1d64f9060..d57013c08 100644 --- a/shared/media-playback/media-playback/decode.c +++ b/shared/media-playback/media-playback/decode.c @@ -21,14 +21,11 @@ #include enum AVHWDeviceType hw_priority[] = { - AV_HWDEVICE_TYPE_CUDA, AV_HWDEVICE_TYPE_D3D11VA, - AV_HWDEVICE_TYPE_DXVA2, AV_HWDEVICE_TYPE_VAAPI, - AV_HWDEVICE_TYPE_VDPAU, AV_HWDEVICE_TYPE_QSV, - AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_HWDEVICE_TYPE_NONE, + AV_HWDEVICE_TYPE_CUDA, AV_HWDEVICE_TYPE_D3D11VA, AV_HWDEVICE_TYPE_DXVA2, AV_HWDEVICE_TYPE_VAAPI, + AV_HWDEVICE_TYPE_VDPAU, AV_HWDEVICE_TYPE_QSV, AV_HWDEVICE_TYPE_VIDEOTOOLBOX, AV_HWDEVICE_TYPE_NONE, }; -static bool has_hw_type(const AVCodec *c, enum AVHWDeviceType type, - enum AVPixelFormat *hw_format) +static bool has_hw_type(const AVCodec *c, enum AVHWDeviceType type, enum AVPixelFormat *hw_format) { for (int i = 0;; i++) { const AVCodecHWConfig *config = avcodec_get_hw_config(c, i); @@ -36,8 +33,7 @@ static bool has_hw_type(const AVCodec *c, enum AVHWDeviceType type, break; } - if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && - config->device_type == type) { + if (config->methods & AV_CODEC_HW_CONFIG_METHOD_HW_DEVICE_CTX && config->device_type == type) { *hw_format = config->pix_fmt; return true; } @@ -53,8 +49,7 @@ static void init_hw_decoder(struct mp_decode *d, AVCodecContext *c) while (*priority != AV_HWDEVICE_TYPE_NONE) { if (has_hw_type(d->codec, *priority, &d->hw_format)) { - int ret = av_hwdevice_ctx_create(&hw_ctx, *priority, - NULL, NULL, 0); + int ret = av_hwdevice_ctx_create(&hw_ctx, *priority, NULL, NULL, 0); if (ret == 0) break; } @@ -90,10 +85,8 @@ static int mp_open_codec(struct mp_decode *d, bool hw) if (hw) init_hw_decoder(d, c); - if (c->thread_count == 1 && c->codec_id != AV_CODEC_ID_PNG && - c->codec_id != AV_CODEC_ID_TIFF && - c->codec_id != AV_CODEC_ID_JPEG2000 && - c->codec_id != AV_CODEC_ID_MPEG4 && c->codec_id != AV_CODEC_ID_WEBP) + if (c->thread_count == 1 && c->codec_id != AV_CODEC_ID_PNG && c->codec_id != AV_CODEC_ID_TIFF && + c->codec_id != AV_CODEC_ID_JPEG2000 && c->codec_id != AV_CODEC_ID_MPEG4 && c->codec_id != AV_CODEC_ID_WEBP) c->thread_count = 0; ret = avcodec_open2(c, d->codec, NULL); @@ -115,24 +108,18 @@ static uint16_t get_max_luminance(const AVStream *stream) uint32_t max_luminance = 0; for (int i = 0; i < stream->codecpar->nb_coded_side_data; i++) { - const AVPacketSideData *const sd = - &stream->codecpar->coded_side_data[i]; + const AVPacketSideData *const sd = &stream->codecpar->coded_side_data[i]; switch (sd->type) { case AV_PKT_DATA_MASTERING_DISPLAY_METADATA: { - const AVMasteringDisplayMetadata *mastering = - (AVMasteringDisplayMetadata *)sd->data; + const AVMasteringDisplayMetadata *mastering = (AVMasteringDisplayMetadata *)sd->data; if (mastering->has_luminance) { - max_luminance = - (uint32_t)(av_q2d(mastering - ->max_luminance) + - 0.5); + max_luminance = (uint32_t)(av_q2d(mastering->max_luminance) + 0.5); } break; } case AV_PKT_DATA_CONTENT_LIGHT_LEVEL: { - const AVContentLightMetadata *const md = - (AVContentLightMetadata *)&sd->data; + const AVContentLightMetadata *const md = (AVContentLightMetadata *)&sd->data; max_luminance = md->MaxCLL; break; } @@ -166,12 +153,10 @@ bool mp_decode_init(mp_media_t *m, enum AVMediaType type, bool hw) if (id == AV_CODEC_ID_VP8 || id == AV_CODEC_ID_VP9) { AVDictionaryEntry *tag = NULL; - tag = av_dict_get(stream->metadata, "alpha_mode", tag, - AV_DICT_IGNORE_SUFFIX); + tag = av_dict_get(stream->metadata, "alpha_mode", tag, AV_DICT_IGNORE_SUFFIX); if (tag && strcmp(tag->value, "1") == 0) { - char *codec = (id == AV_CODEC_ID_VP8) ? "libvpx" - : "libvpx-vp9"; + char *codec = (id == AV_CODEC_ID_VP8) ? "libvpx" : "libvpx-vp9"; d->codec = avcodec_find_decoder_by_name(codec); } } @@ -180,30 +165,26 @@ bool mp_decode_init(mp_media_t *m, enum AVMediaType type, bool hw) d->codec = avcodec_find_decoder(id); if (!d->codec) { - blog(LOG_WARNING, "MP: Failed to find %s codec", - av_get_media_type_string(type)); + blog(LOG_WARNING, "MP: Failed to find %s codec", av_get_media_type_string(type)); return false; } ret = mp_open_codec(d, hw); if (ret < 0) { - blog(LOG_WARNING, "MP: Failed to open %s decoder: %s", - av_get_media_type_string(type), av_err2str(ret)); + blog(LOG_WARNING, "MP: Failed to open %s decoder: %s", av_get_media_type_string(type), av_err2str(ret)); return false; } d->sw_frame = av_frame_alloc(); if (!d->sw_frame) { - blog(LOG_WARNING, "MP: Failed to allocate %s frame", - av_get_media_type_string(type)); + blog(LOG_WARNING, "MP: Failed to allocate %s frame", av_get_media_type_string(type)); return false; } if (d->hw) { d->hw_frame = av_frame_alloc(); if (!d->hw_frame) { - blog(LOG_WARNING, "MP: Failed to allocate %s hw frame", - av_get_media_type_string(type)); + blog(LOG_WARNING, "MP: Failed to allocate %s hw frame", av_get_media_type_string(type)); return false; } @@ -267,12 +248,10 @@ void mp_decode_push_packet(struct mp_decode *decode, AVPacket *packet) deque_push_back(&decode->packets, &packet, sizeof(packet)); } -static inline int64_t get_estimated_duration(struct mp_decode *d, - int64_t last_pts) +static inline int64_t get_estimated_duration(struct mp_decode *d, int64_t last_pts) { if (d->audio) { - return av_rescale_q(d->in_frame->nb_samples, - (AVRational){1, d->in_frame->sample_rate}, + return av_rescale_q(d->in_frame->nb_samples, (AVRational){1, d->in_frame->sample_rate}, (AVRational){1, 1000000000}); } else { if (last_pts) @@ -281,9 +260,7 @@ static inline int64_t get_estimated_duration(struct mp_decode *d, if (d->last_duration) return d->last_duration; - return av_rescale_q(d->decoder->time_base.num, - d->decoder->time_base, - (AVRational){1, 1000000000}); + return av_rescale_q(d->decoder->time_base.num, d->decoder->time_base, (AVRational){1, 1000000000}); } } @@ -365,8 +342,7 @@ bool mp_decode_next(struct mp_decode *d) } } else { mp_media_free_packet(d->m, d->orig_pkt); - deque_pop_front(&d->packets, &d->orig_pkt, - sizeof(d->orig_pkt)); + deque_pop_front(&d->packets, &d->orig_pkt, sizeof(d->orig_pkt)); av_packet_ref(d->pkt, d->orig_pkt); d->packet_pending = true; } @@ -380,8 +356,7 @@ bool mp_decode_next(struct mp_decode *d) } if (ret < 0) { #ifdef DETAILED_DEBUG_INFO - blog(LOG_DEBUG, "MP: decode failed: %s", - av_err2str(ret)); + blog(LOG_DEBUG, "MP: decode failed: %s", av_err2str(ret)); #endif if (d->packet_pending) { @@ -414,25 +389,18 @@ bool mp_decode_next(struct mp_decode *d) if (d->in_frame->best_effort_timestamp == AV_NOPTS_VALUE) d->frame_pts = d->next_pts; else - d->frame_pts = - av_rescale_q(d->in_frame->best_effort_timestamp, - d->stream->time_base, - (AVRational){1, 1000000000}); + d->frame_pts = av_rescale_q(d->in_frame->best_effort_timestamp, d->stream->time_base, + (AVRational){1, 1000000000}); int64_t duration = d->in_frame->duration; if (!duration) duration = get_estimated_duration(d, last_pts); else - duration = av_rescale_q(duration, d->stream->time_base, - (AVRational){1, 1000000000}); + duration = av_rescale_q(duration, d->stream->time_base, (AVRational){1, 1000000000}); if (d->m->speed != 100) { - d->frame_pts = av_rescale_q( - d->frame_pts, (AVRational){1, d->m->speed}, - (AVRational){1, 100}); - duration = av_rescale_q(duration, - (AVRational){1, d->m->speed}, - (AVRational){1, 100}); + d->frame_pts = av_rescale_q(d->frame_pts, (AVRational){1, d->m->speed}, (AVRational){1, 100}); + duration = av_rescale_q(duration, (AVRational){1, d->m->speed}, (AVRational){1, 100}); } d->last_duration = duration; diff --git a/shared/media-playback/media-playback/decode.h b/shared/media-playback/media-playback/decode.h index 97830c336..02b1acbd5 100644 --- a/shared/media-playback/media-playback/decode.h +++ b/shared/media-playback/media-playback/decode.h @@ -67,8 +67,7 @@ struct mp_decode { struct deque packets; }; -extern bool mp_decode_init(struct mp_media *media, enum AVMediaType type, - bool hw); +extern bool mp_decode_init(struct mp_media *media, enum AVMediaType type, bool hw); extern void mp_decode_free(struct mp_decode *decode); extern void mp_decode_clear_packets(struct mp_decode *decode); diff --git a/shared/media-playback/media-playback/media-playback.c b/shared/media-playback/media-playback/media-playback.c index a105040a4..41ae9d242 100644 --- a/shared/media-playback/media-playback/media-playback.c +++ b/shared/media-playback/media-playback/media-playback.c @@ -93,8 +93,7 @@ void media_playback_set_looping(media_playback_t *mp, bool looping) mp->media.looping = looping; } -void media_playback_set_is_linear_alpha(media_playback_t *mp, - bool is_linear_alpha) +void media_playback_set_is_linear_alpha(media_playback_t *mp, bool is_linear_alpha) { if (mp->is_cached) mp->cache.m.is_linear_alpha = is_linear_alpha; diff --git a/shared/media-playback/media-playback/media-playback.h b/shared/media-playback/media-playback/media-playback.h index db3948a58..812287b84 100644 --- a/shared/media-playback/media-playback/media-playback.h +++ b/shared/media-playback/media-playback/media-playback.h @@ -48,17 +48,14 @@ struct mp_media_info { bool full_decode; }; -extern media_playback_t * -media_playback_create(const struct mp_media_info *info); +extern media_playback_t *media_playback_create(const struct mp_media_info *info); extern void media_playback_destroy(media_playback_t *mp); -extern void media_playback_play(media_playback_t *mp, bool looping, - bool reconnecting); +extern void media_playback_play(media_playback_t *mp, bool looping, bool reconnecting); extern void media_playback_play_pause(media_playback_t *mp, bool pause); extern void media_playback_stop(media_playback_t *mp); extern void media_playback_set_looping(media_playback_t *mp, bool looping); -extern void media_playback_set_is_linear_alpha(media_playback_t *mp, - bool is_linear_alpha); +extern void media_playback_set_is_linear_alpha(media_playback_t *mp, bool is_linear_alpha); extern void media_playback_preload_frame(media_playback_t *mp); extern int64_t media_playback_get_current_time(media_playback_t *mp); extern void media_playback_seek(media_playback_t *mp, int64_t pos); diff --git a/shared/media-playback/media-playback/media.c b/shared/media-playback/media-playback/media.c index e03f843b2..ea2ee923e 100644 --- a/shared/media-playback/media-playback/media.c +++ b/shared/media-playback/media-playback/media.c @@ -123,27 +123,22 @@ static inline enum speaker_layout convert_speaker_layout(uint8_t channels) } } -static inline enum video_colorspace -convert_color_space(enum AVColorSpace s, enum AVColorTransferCharacteristic trc, - enum AVColorPrimaries color_primaries) +static inline enum video_colorspace convert_color_space(enum AVColorSpace s, enum AVColorTransferCharacteristic trc, + enum AVColorPrimaries color_primaries) { switch (s) { case AVCOL_SPC_BT709: - return (trc == AVCOL_TRC_IEC61966_2_1) ? VIDEO_CS_SRGB - : VIDEO_CS_709; + return (trc == AVCOL_TRC_IEC61966_2_1) ? VIDEO_CS_SRGB : VIDEO_CS_709; case AVCOL_SPC_FCC: case AVCOL_SPC_BT470BG: case AVCOL_SPC_SMPTE170M: case AVCOL_SPC_SMPTE240M: return VIDEO_CS_601; case AVCOL_SPC_BT2020_NCL: - return (trc == AVCOL_TRC_ARIB_STD_B67) ? VIDEO_CS_2100_HLG - : VIDEO_CS_2100_PQ; + return (trc == AVCOL_TRC_ARIB_STD_B67) ? VIDEO_CS_2100_HLG : VIDEO_CS_2100_PQ; default: return (color_primaries == AVCOL_PRI_BT2020) - ? ((trc == AVCOL_TRC_ARIB_STD_B67) - ? VIDEO_CS_2100_HLG - : VIDEO_CS_2100_PQ) + ? ((trc == AVCOL_TRC_ARIB_STD_B67) ? VIDEO_CS_2100_HLG : VIDEO_CS_2100_PQ) : VIDEO_CS_DEFAULT; } } @@ -153,8 +148,7 @@ static inline enum video_range_type convert_color_range(enum AVColorRange r) return r == AVCOL_RANGE_JPEG ? VIDEO_RANGE_FULL : VIDEO_RANGE_DEFAULT; } -static inline struct mp_decode *get_packet_decoder(mp_media_t *media, - const AVPacket *pkt) +static inline struct mp_decode *get_packet_decoder(mp_media_t *media, const AVPacket *pkt) { if (media->has_audio && pkt->stream_index == media->a.stream->index) return &media->a; @@ -184,8 +178,7 @@ static int mp_media_next_packet(mp_media_t *media) int ret = av_read_frame(media->fmt, pkt); if (ret < 0) { if (ret != AVERROR_EOF && ret != AVERROR_EXIT) - blog(LOG_WARNING, "MP: av_read_frame failed: %s (%d)", - av_err2str(ret), ret); + blog(LOG_WARNING, "MP: av_read_frame failed: %s (%d)", av_err2str(ret), ret); return ret; } @@ -248,21 +241,17 @@ static bool mp_media_init_scaling(mp_media_t *m) int range = get_sws_range(m->v.frame->color_range); const int *coeff = sws_getCoefficients(space); - m->swscale = sws_getCachedContext(NULL, m->v.frame->width, - m->v.frame->height, - m->v.frame->format, m->v.frame->width, - m->v.frame->height, m->scale_format, - SWS_POINT, NULL, NULL, NULL); + m->swscale = sws_getCachedContext(NULL, m->v.frame->width, m->v.frame->height, m->v.frame->format, + m->v.frame->width, m->v.frame->height, m->scale_format, SWS_POINT, NULL, NULL, + NULL); if (!m->swscale) { blog(LOG_WARNING, "MP: Failed to initialize scaler"); return false; } - sws_setColorspaceDetails(m->swscale, coeff, range, coeff, range, 0, - FIXED_1_0, FIXED_1_0); + sws_setColorspaceDetails(m->swscale, coeff, range, coeff, range, 0, FIXED_1_0, FIXED_1_0); - int ret = av_image_alloc(m->scale_pic, m->scale_linesizes, - m->v.frame->width, m->v.frame->height, + int ret = av_image_alloc(m->scale_pic, m->scale_linesizes, m->v.frame->width, m->v.frame->height, m->scale_format, 32); if (ret < 0) { blog(LOG_WARNING, "MP: Failed to create scale pic data"); @@ -351,8 +340,7 @@ static inline bool mp_media_can_play_frame(mp_media_t *m, struct mp_decode *d) { if (m->full_decode) return d->frame_ready; - return d->frame_ready && (d->frame_pts <= m->next_pts_ns || - (d->frame_pts - m->next_pts_ns > MAX_TS_VAR)); + return d->frame_ready && (d->frame_pts <= m->next_pts_ns || (d->frame_pts - m->next_pts_ns > MAX_TS_VAR)); } void mp_media_next_audio(mp_media_t *m) @@ -376,10 +364,8 @@ void mp_media_next_audio(mp_media_t *m) audio.speakers = convert_speaker_layout(channels); audio.format = convert_sample_format(f->format); audio.frames = f->nb_samples; - audio.timestamp = m->full_decode - ? d->frame_pts - : m->base_ts + d->frame_pts - m->start_ts + - m->play_sys_ts - base_sys_ts; + audio.timestamp = m->full_decode ? d->frame_pts + : m->base_ts + d->frame_pts - m->start_ts + m->play_sys_ts - base_sys_ts; if (audio.format == AUDIO_FORMAT_UNKNOWN) return; @@ -410,9 +396,8 @@ void mp_media_next_video(mp_media_t *m, bool preload) bool flip = false; if (m->swscale) { - int ret = sws_scale(m->swscale, (const uint8_t *const *)f->data, - f->linesize, 0, f->height, m->scale_pic, - m->scale_linesizes); + int ret = sws_scale(m->swscale, (const uint8_t *const *)f->data, f->linesize, 0, f->height, + m->scale_pic, m->scale_linesizes); if (ret < 0) return; @@ -435,22 +420,17 @@ void mp_media_next_video(mp_media_t *m, bool preload) frame->data[0] -= frame->linesize[0] * ((size_t)f->height - 1); new_format = convert_pixel_format(m->scale_format); - new_space = convert_color_space(f->colorspace, f->color_trc, - f->color_primaries); - new_range = m->force_range == VIDEO_RANGE_DEFAULT - ? convert_color_range(f->color_range) - : m->force_range; + new_space = convert_color_space(f->colorspace, f->color_trc, f->color_primaries); + new_range = m->force_range == VIDEO_RANGE_DEFAULT ? convert_color_range(f->color_range) : m->force_range; - if (new_format != frame->format || new_space != m->cur_space || - new_range != m->cur_range) { + if (new_format != frame->format || new_space != m->cur_space || new_range != m->cur_range) { bool success; frame->format = new_format; frame->full_range = new_range == VIDEO_RANGE_FULL; - success = video_format_get_parameters_for_format( - new_space, new_range, new_format, frame->color_matrix, - frame->color_range_min, frame->color_range_max); + success = video_format_get_parameters_for_format(new_space, new_range, new_format, frame->color_matrix, + frame->color_range_min, frame->color_range_max); frame->format = new_format; m->cur_space = new_space; @@ -465,10 +445,8 @@ void mp_media_next_video(mp_media_t *m, bool preload) if (frame->format == VIDEO_FORMAT_NONE) return; - frame->timestamp = m->full_decode - ? d->frame_pts - : (m->base_ts + d->frame_pts - m->start_ts + - m->play_sys_ts - base_sys_ts); + frame->timestamp = m->full_decode ? d->frame_pts + : (m->base_ts + d->frame_pts - m->start_ts + m->play_sys_ts - base_sys_ts); frame->width = f->width; frame->height = f->height; @@ -546,22 +524,19 @@ static void seek_to(mp_media_t *m, int64_t pos) seek_flags = AVSEEK_FLAG_BACKWARD; int64_t seek_target = seek_flags == AVSEEK_FLAG_BACKWARD - ? av_rescale_q(seek_pos, AV_TIME_BASE_Q, - stream->time_base) + ? av_rescale_q(seek_pos, AV_TIME_BASE_Q, stream->time_base) : seek_pos; if (m->is_local_file) { int ret = av_seek_frame(m->fmt, 0, seek_target, seek_flags); if (ret < 0) { - blog(LOG_WARNING, "MP: Failed to seek: %s", - av_err2str(ret)); + blog(LOG_WARNING, "MP: Failed to seek: %s", av_err2str(ret)); } } if (m->has_video && m->is_local_file) { mp_decode_flush(&m->v); - if (m->seek_next_ts && m->pause && m->v_preload_cb && - mp_media_prepare_frames(m)) + if (m->seek_next_ts && m->pause && m->v_preload_cb && mp_media_prepare_frames(m)) mp_media_next_video(m, true); } if (m->has_audio && m->is_local_file) @@ -624,8 +599,7 @@ static inline bool mp_media_sleep(mp_media_t *m) } else { const uint64_t t = os_gettime_ns(); if (m->next_ns > t) { - const uint32_t delta_ms = - (uint32_t)((m->next_ns - t + 500000) / 1000000); + const uint32_t delta_ms = (uint32_t)((m->next_ns - t + 500000) / 1000000); if (delta_ms > 0) { static const uint32_t timeout_ms = 200; timeout = delta_ms > timeout_ms; @@ -698,12 +672,9 @@ static bool init_avformat(mp_media_t *m) av_dict_set_int(&opts, "buffer_size", m->buffering, 0); if (m->ffmpeg_options) { - int ret = av_dict_parse_string(&opts, m->ffmpeg_options, "=", - " ", 0); + int ret = av_dict_parse_string(&opts, m->ffmpeg_options, "=", " ", 0); if (ret) - blog(LOG_WARNING, - "Failed to parse FFmpeg options: %s\n%s", - av_err2str(ret), m->ffmpeg_options); + blog(LOG_WARNING, "Failed to parse FFmpeg options: %s\n%s", av_err2str(ret), m->ffmpeg_options); } m->fmt = avformat_alloc_context(); @@ -716,20 +687,17 @@ static bool init_avformat(mp_media_t *m) m->fmt->interrupt_callback.opaque = m; } - int ret = avformat_open_input(&m->fmt, m->path, format, - opts ? &opts : NULL); + int ret = avformat_open_input(&m->fmt, m->path, format, opts ? &opts : NULL); av_dict_free(&opts); if (ret < 0) { if (!m->reconnecting) - blog(LOG_WARNING, "MP: Failed to open media: '%s'", - m->path); + blog(LOG_WARNING, "MP: Failed to open media: '%s'", m->path); return false; } if (avformat_find_stream_info(m->fmt, NULL) < 0) { - blog(LOG_WARNING, "MP: Failed to find stream info for '%s'", - m->path); + blog(LOG_WARNING, "MP: Failed to find stream info for '%s'", m->path); return false; } @@ -776,8 +744,7 @@ static inline bool mp_media_thread(mp_media_t *m) } for (;;) { - bool reset, kill, is_active, seek, pause, reset_time, - preload_frame; + bool reset, kill, is_active, seek, pause, reset_time, preload_frame; int64_t seek_pos; bool timeout = false; @@ -873,8 +840,7 @@ static void *mp_media_thread_start(void *opaque) return NULL; } -static inline bool mp_media_init_internal(mp_media_t *m, - const struct mp_media_info *info) +static inline bool mp_media_init_internal(mp_media_t *m, const struct mp_media_info *info) { if (pthread_mutex_init(&m->mutex, NULL) != 0) { blog(LOG_WARNING, "MP: Failed to init mutex"); @@ -1040,8 +1006,7 @@ int64_t mp_media_get_frames(mp_media_t *m) return 0; } - int video_stream_index = av_find_best_stream(m->fmt, AVMEDIA_TYPE_VIDEO, - -1, -1, NULL, 0); + int video_stream_index = av_find_best_stream(m->fmt, AVMEDIA_TYPE_VIDEO, -1, -1, NULL, 0); if (video_stream_index < 0) { blog(LOG_WARNING, "MP: Getting number of frames failed: No " @@ -1057,9 +1022,7 @@ int64_t mp_media_get_frames(mp_media_t *m) blog(LOG_DEBUG, "MP: nb_frames not set, estimating using frame " "rate and duration"); AVRational avg_frame_rate = stream->avg_frame_rate; - frames = (int64_t)ceil((double)m->fmt->duration / - (double)AV_TIME_BASE * - (double)avg_frame_rate.num / + frames = (int64_t)ceil((double)m->fmt->duration / (double)AV_TIME_BASE * (double)avg_frame_rate.num / (double)avg_frame_rate.den); } diff --git a/shared/obs-hook-config/graphics-hook-info.h b/shared/obs-hook-config/graphics-hook-info.h index f449afa98..b936b830a 100644 --- a/shared/obs-hook-config/graphics-hook-info.h +++ b/shared/obs-hook-config/graphics-hook-info.h @@ -131,12 +131,10 @@ static inline HANDLE create_hook_info(DWORD id) HANDLE handle = NULL; wchar_t new_name[64]; - const int len = swprintf(new_name, _countof(new_name), - SHMEM_HOOK_INFO L"%lu", id); + const int len = swprintf(new_name, _countof(new_name), SHMEM_HOOK_INFO L"%lu", id); if (len > 0) { - handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, - PAGE_READWRITE, 0, - sizeof(struct hook_info), new_name); + handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(struct hook_info), + new_name); } return handle; diff --git a/shared/obs-hook-config/graphics-hook-ver.h b/shared/obs-hook-config/graphics-hook-ver.h index 518629664..3fcdee85c 100644 --- a/shared/obs-hook-config/graphics-hook-ver.h +++ b/shared/obs-hook-config/graphics-hook-ver.h @@ -19,7 +19,5 @@ #define STRINGIFY(s) #s #endif -#define MAKE_VERSION_NAME(major, minor, patch) \ - STRINGIFY(major) "." STRINGIFY(minor) "." STRINGIFY(patch) ".0" -#define HOOK_VERSION_NAME \ - MAKE_VERSION_NAME(HOOK_VER_MAJOR, HOOK_VER_MINOR, HOOK_VER_PATCH) +#define MAKE_VERSION_NAME(major, minor, patch) STRINGIFY(major) "." STRINGIFY(minor) "." STRINGIFY(patch) ".0" +#define HOOK_VERSION_NAME MAKE_VERSION_NAME(HOOK_VER_MAJOR, HOOK_VER_MINOR, HOOK_VER_PATCH) diff --git a/shared/obs-inject-library/inject-library.c b/shared/obs-inject-library/inject-library.c index 6e9bdfc75..16f82c7e6 100644 --- a/shared/obs-inject-library/inject-library.c +++ b/shared/obs-inject-library/inject-library.c @@ -3,21 +3,16 @@ #include #include "inject-library.h" -typedef HANDLE(WINAPI *create_remote_thread_t)(HANDLE, LPSECURITY_ATTRIBUTES, - SIZE_T, LPTHREAD_START_ROUTINE, - LPVOID, DWORD, LPDWORD); -typedef BOOL(WINAPI *write_process_memory_t)(HANDLE, LPVOID, LPCVOID, SIZE_T, - SIZE_T *); -typedef LPVOID(WINAPI *virtual_alloc_ex_t)(HANDLE, LPVOID, SIZE_T, DWORD, - DWORD); +typedef HANDLE(WINAPI *create_remote_thread_t)(HANDLE, LPSECURITY_ATTRIBUTES, SIZE_T, LPTHREAD_START_ROUTINE, LPVOID, + DWORD, LPDWORD); +typedef BOOL(WINAPI *write_process_memory_t)(HANDLE, LPVOID, LPCVOID, SIZE_T, SIZE_T *); +typedef LPVOID(WINAPI *virtual_alloc_ex_t)(HANDLE, LPVOID, SIZE_T, DWORD, DWORD); typedef BOOL(WINAPI *virtual_free_ex_t)(HANDLE, LPVOID, SIZE_T, DWORD); -int inject_library_obf(HANDLE process, const wchar_t *dll, - const char *create_remote_thread_obf, uint64_t obf1, - const char *write_process_memory_obf, uint64_t obf2, - const char *virtual_alloc_ex_obf, uint64_t obf3, - const char *virtual_free_ex_obf, uint64_t obf4, - const char *load_library_w_obf, uint64_t obf5) +int inject_library_obf(HANDLE process, const wchar_t *dll, const char *create_remote_thread_obf, uint64_t obf1, + const char *write_process_memory_obf, uint64_t obf2, const char *virtual_alloc_ex_obf, + uint64_t obf3, const char *virtual_free_ex_obf, uint64_t obf4, const char *load_library_w_obf, + uint64_t obf5) { int ret = INJECT_ERROR_UNLIKELY_FAIL; DWORD last_error = 0; @@ -37,22 +32,16 @@ int inject_library_obf(HANDLE process, const wchar_t *dll, virtual_free_ex_t virtual_free_ex; FARPROC load_library_w; - create_remote_thread = (create_remote_thread_t)ms_get_obfuscated_func( - kernel32, create_remote_thread_obf, obf1); - write_process_memory = (write_process_memory_t)ms_get_obfuscated_func( - kernel32, write_process_memory_obf, obf2); - virtual_alloc_ex = (virtual_alloc_ex_t)ms_get_obfuscated_func( - kernel32, virtual_alloc_ex_obf, obf3); - virtual_free_ex = (virtual_free_ex_t)ms_get_obfuscated_func( - kernel32, virtual_free_ex_obf, obf4); - load_library_w = (FARPROC)ms_get_obfuscated_func( - kernel32, load_library_w_obf, obf5); + create_remote_thread = (create_remote_thread_t)ms_get_obfuscated_func(kernel32, create_remote_thread_obf, obf1); + write_process_memory = (write_process_memory_t)ms_get_obfuscated_func(kernel32, write_process_memory_obf, obf2); + virtual_alloc_ex = (virtual_alloc_ex_t)ms_get_obfuscated_func(kernel32, virtual_alloc_ex_obf, obf3); + virtual_free_ex = (virtual_free_ex_t)ms_get_obfuscated_func(kernel32, virtual_free_ex_obf, obf4); + load_library_w = (FARPROC)ms_get_obfuscated_func(kernel32, load_library_w_obf, obf5); /* -------------------------------- */ size = (wcslen(dll) + 1) * sizeof(wchar_t); - mem = virtual_alloc_ex(process, NULL, size, MEM_RESERVE | MEM_COMMIT, - PAGE_READWRITE); + mem = virtual_alloc_ex(process, NULL, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); if (!mem) { goto fail; } @@ -62,9 +51,7 @@ int inject_library_obf(HANDLE process, const wchar_t *dll, goto fail; } - thread = create_remote_thread(process, NULL, 0, - (LPTHREAD_START_ROUTINE)load_library_w, - mem, 0, &thread_id); + thread = create_remote_thread(process, NULL, 0, (LPTHREAD_START_ROUTINE)load_library_w, mem, 0, &thread_id); if (!thread) { goto fail; } @@ -102,8 +89,7 @@ typedef HHOOK(WINAPI *set_windows_hook_ex_t)(int, HOOKPROC, HINSTANCE, DWORD); #define TOTAL_RETRY_TIME_MS 4000 #define RETRY_COUNT (TOTAL_RETRY_TIME_MS / RETRY_INTERVAL_MS) -int inject_library_safe_obf(DWORD thread_id, const wchar_t *dll, - const char *set_windows_hook_ex_obf, uint64_t obf1) +int inject_library_safe_obf(DWORD thread_id, const wchar_t *dll, const char *set_windows_hook_ex_obf, uint64_t obf1) { HMODULE user32 = GetModuleHandleW(L"USER32"); set_windows_hook_ex_t set_windows_hook_ex; @@ -126,8 +112,7 @@ int inject_library_safe_obf(DWORD thread_id, const wchar_t *dll, return INJECT_ERROR_UNLIKELY_FAIL; } - set_windows_hook_ex = (set_windows_hook_ex_t)ms_get_obfuscated_func( - user32, set_windows_hook_ex_obf, obf1); + set_windows_hook_ex = (set_windows_hook_ex_t)ms_get_obfuscated_func(user32, set_windows_hook_ex_obf, obf1); hook = set_windows_hook_ex(WH_GETMESSAGE, proc, lib, thread_id); if (!hook) { diff --git a/shared/obs-inject-library/inject-library.h b/shared/obs-inject-library/inject-library.h index f65a129bd..d2003ee34 100644 --- a/shared/obs-inject-library/inject-library.h +++ b/shared/obs-inject-library/inject-library.h @@ -6,15 +6,10 @@ #define INJECT_ERROR_OPEN_PROCESS_FAIL -3 #define INJECT_ERROR_UNLIKELY_FAIL -4 -extern int inject_library_obf(HANDLE process, const wchar_t *dll, - const char *create_remote_thread_obf, - uint64_t obf1, - const char *write_process_memory_obf, - uint64_t obf2, const char *virtual_alloc_ex_obf, - uint64_t obf3, const char *virtual_free_ex_obf, - uint64_t obf4, const char *load_library_w_obf, - uint64_t obf5); +extern int inject_library_obf(HANDLE process, const wchar_t *dll, const char *create_remote_thread_obf, uint64_t obf1, + const char *write_process_memory_obf, uint64_t obf2, const char *virtual_alloc_ex_obf, + uint64_t obf3, const char *virtual_free_ex_obf, uint64_t obf4, + const char *load_library_w_obf, uint64_t obf5); -extern int inject_library_safe_obf(DWORD thread_id, const wchar_t *dll, - const char *set_windows_hook_ex_obf, +extern int inject_library_safe_obf(DWORD thread_id, const wchar_t *dll, const char *set_windows_hook_ex_obf, uint64_t obf1); diff --git a/shared/obs-scripting/obs-scripting-callback.h b/shared/obs-scripting/obs-scripting-callback.h index b6975ac00..3b5452245 100644 --- a/shared/obs-scripting/obs-scripting-callback.h +++ b/shared/obs-scripting/obs-scripting-callback.h @@ -41,8 +41,7 @@ static inline bool script_callback_removed(struct script_callback *cb) return os_atomic_load_bool(&cb->removed); } -static inline void *add_script_callback(struct script_callback **first, - obs_script_t *script, size_t extra_size) +static inline void *add_script_callback(struct script_callback **first, obs_script_t *script, size_t extra_size) { struct script_callback *cb = bzalloc(sizeof(*cb) + extra_size); cb->script = script; diff --git a/shared/obs-scripting/obs-scripting-internal.h b/shared/obs-scripting/obs-scripting-internal.h index d7806ea6d..a645f7a67 100644 --- a/shared/obs-scripting/obs-scripting-internal.h +++ b/shared/obs-scripting/obs-scripting-internal.h @@ -37,16 +37,10 @@ typedef void (*defer_call_cb)(void *param); extern void defer_call_post(defer_call_cb call, void *cb); -extern void script_log(obs_script_t *script, int level, const char *format, - ...); -extern void script_log_va(obs_script_t *script, int level, const char *format, - va_list args); +extern void script_log(obs_script_t *script, int level, const char *format, ...); +extern void script_log_va(obs_script_t *script, int level, const char *format, va_list args); -#define script_error(script, format, ...) \ - script_log(script, LOG_ERROR, format, ##__VA_ARGS__) -#define script_warn(script, format, ...) \ - script_log(script, LOG_WARNING, format, ##__VA_ARGS__) -#define script_info(script, format, ...) \ - script_log(script, LOG_INFO, format, ##__VA_ARGS__) -#define script_debug(script, format, ...) \ - script_log(script, LOG_DEBUG, format, ##__VA_ARGS__) +#define script_error(script, format, ...) script_log(script, LOG_ERROR, format, ##__VA_ARGS__) +#define script_warn(script, format, ...) script_log(script, LOG_WARNING, format, ##__VA_ARGS__) +#define script_info(script, format, ...) script_log(script, LOG_INFO, format, ##__VA_ARGS__) +#define script_debug(script, format, ...) script_log(script, LOG_DEBUG, format, ##__VA_ARGS__) diff --git a/shared/obs-scripting/obs-scripting-logging.c b/shared/obs-scripting/obs-scripting-logging.c index 3bd2d5d32..a31199c4c 100644 --- a/shared/obs-scripting/obs-scripting-logging.c +++ b/shared/obs-scripting/obs-scripting-logging.c @@ -21,8 +21,7 @@ static scripting_log_handler_t callback = NULL; static void *param = NULL; -void script_log_va(obs_script_t *script, int level, const char *format, - va_list args) +void script_log_va(obs_script_t *script, int level, const char *format, va_list args) { char msg[2048]; const char *lang = "(Unknown)"; @@ -41,8 +40,7 @@ void script_log_va(obs_script_t *script, int level, const char *format, break; } - start_len = snprintf(msg, sizeof(msg), "[%s: %s] ", lang, - script->file.array); + start_len = snprintf(msg, sizeof(msg), "[%s: %s] ", lang, script->file.array); } else { start_len = snprintf(msg, sizeof(msg), "[Unknown Script] "); } @@ -62,8 +60,7 @@ void script_log(obs_script_t *script, int level, const char *format, ...) va_end(args); } -void obs_scripting_set_log_callback(scripting_log_handler_t handler, - void *log_param) +void obs_scripting_set_log_callback(scripting_log_handler_t handler, void *log_param) { callback = handler; param = log_param; diff --git a/shared/obs-scripting/obs-scripting-lua-frontend.c b/shared/obs-scripting/obs-scripting-lua-frontend.c index a818a8dfc..77a3f516d 100644 --- a/shared/obs-scripting/obs-scripting-lua-frontend.c +++ b/shared/obs-scripting/obs-scripting-lua-frontend.c @@ -20,14 +20,11 @@ #include "obs-scripting-lua.h" -#define ls_get_libobs_obj(type, lua_index, obs_obj) \ - ls_get_libobs_obj_(script, #type " *", lua_index, obs_obj, NULL, \ - __FUNCTION__, __LINE__) -#define ls_push_libobs_obj(type, obs_obj, ownership) \ - ls_push_libobs_obj_(script, #type " *", obs_obj, ownership, NULL, \ - __FUNCTION__, __LINE__) -#define call_func(func, args, rets) \ - call_func_(script, cb->reg_idx, args, rets, #func, "frontend API") +#define ls_get_libobs_obj(type, lua_index, obs_obj) \ + ls_get_libobs_obj_(script, #type " *", lua_index, obs_obj, NULL, __FUNCTION__, __LINE__) +#define ls_push_libobs_obj(type, obs_obj, ownership) \ + ls_push_libobs_obj_(script, #type " *", obs_obj, ownership, NULL, __FUNCTION__, __LINE__) +#define call_func(func, args, rets) call_func_(script, cb->reg_idx, args, rets, #func, "frontend API") /* ----------------------------------- */ @@ -248,8 +245,7 @@ static int add_event_callback(lua_State *script) /* ----------------------------------- */ -static void frontend_save_callback(obs_data_t *save_data, bool saving, - void *priv) +static void frontend_save_callback(obs_data_t *save_data, bool saving, void *priv) { struct lua_obs_callback *cb = priv; lua_State *script = cb->script; @@ -305,38 +301,23 @@ typedef struct lua_function_tuple { static const obs_frontend_func functions[] = { {.name = "obs_frontend_get_scene_names", .function = get_scene_names}, {.name = "obs_frontend_get_scenes", .function = get_scenes}, - {.name = "obs_frontend_get_current_scene", - .function = get_current_scene}, - {.name = "obs_frontend_set_current_scene", - .function = set_current_scene}, + {.name = "obs_frontend_get_current_scene", .function = get_current_scene}, + {.name = "obs_frontend_set_current_scene", .function = set_current_scene}, {.name = "obs_frontend_get_transitions", .function = get_transitions}, - {.name = "obs_frontend_get_current_transition", - .function = get_current_transition}, - {.name = "obs_frontend_set_current_transition", - .function = set_current_transition}, - {.name = "obs_frontend_get_transition_duration", - .function = get_transition_duration}, - {.name = "obs_frontend_set_transition_duration", - .function = set_transition_duration}, - {.name = "obs_frontend_get_scene_collections", - .function = get_scene_collections}, - {.name = "obs_frontend_get_current_scene_collection", - .function = get_current_scene_collection}, - {.name = "obs_frontend_set_current_scene_collection", - .function = set_current_scene_collection}, + {.name = "obs_frontend_get_current_transition", .function = get_current_transition}, + {.name = "obs_frontend_set_current_transition", .function = set_current_transition}, + {.name = "obs_frontend_get_transition_duration", .function = get_transition_duration}, + {.name = "obs_frontend_set_transition_duration", .function = set_transition_duration}, + {.name = "obs_frontend_get_scene_collections", .function = get_scene_collections}, + {.name = "obs_frontend_get_current_scene_collection", .function = get_current_scene_collection}, + {.name = "obs_frontend_set_current_scene_collection", .function = set_current_scene_collection}, {.name = "obs_frontend_get_profiles", .function = get_profiles}, - {.name = "obs_frontend_get_current_profile", - .function = get_current_profile}, - {.name = "obs_frontend_set_current_profile", - .function = set_current_profile}, - {.name = "obs_frontend_remove_event_callback", - .function = remove_event_callback}, - {.name = "obs_frontend_add_event_callback", - .function = add_event_callback}, - {.name = "obs_frontend_remove_save_callback", - .function = remove_save_callback}, - {.name = "obs_frontend_add_save_callback", - .function = add_save_callback}, + {.name = "obs_frontend_get_current_profile", .function = get_current_profile}, + {.name = "obs_frontend_set_current_profile", .function = set_current_profile}, + {.name = "obs_frontend_remove_event_callback", .function = remove_event_callback}, + {.name = "obs_frontend_add_event_callback", .function = add_event_callback}, + {.name = "obs_frontend_remove_save_callback", .function = remove_save_callback}, + {.name = "obs_frontend_add_save_callback", .function = add_save_callback}, }; void add_lua_frontend_funcs(lua_State *script) diff --git a/shared/obs-scripting/obs-scripting-lua-source.c b/shared/obs-scripting/obs-scripting-lua-source.c index 2be90ed41..904d5fa4b 100644 --- a/shared/obs-scripting/obs-scripting-lua-source.c +++ b/shared/obs-scripting/obs-scripting-lua-source.c @@ -22,8 +22,7 @@ /* ========================================================================= */ -static inline const char *get_table_string_(lua_State *script, int idx, - const char *name, const char *func) +static inline const char *get_table_string_(lua_State *script, int idx, const char *name, const char *func) { const char *str = ""; @@ -38,8 +37,7 @@ static inline const char *get_table_string_(lua_State *script, int idx, return str; } -static inline int get_table_int_(lua_State *script, int idx, const char *name, - const char *func) +static inline int get_table_int_(lua_State *script, int idx, const char *name, const char *func) { int val = 0; @@ -53,8 +51,7 @@ static inline int get_table_int_(lua_State *script, int idx, const char *name, return val; } -static inline void get_callback_from_table_(lua_State *script, int idx, - const char *name, int *p_reg_idx, +static inline void get_callback_from_table_(lua_State *script, int idx, const char *name, int *p_reg_idx, const char *func) { *p_reg_idx = LUA_REFNIL; @@ -71,21 +68,17 @@ static inline void get_callback_from_table_(lua_State *script, int idx, } } -#define get_table_string(script, idx, name) \ - get_table_string_(script, idx, name, __FUNCTION__) -#define get_table_int(script, idx, name) \ - get_table_int_(script, idx, name, __FUNCTION__) +#define get_table_string(script, idx, name) get_table_string_(script, idx, name, __FUNCTION__) +#define get_table_int(script, idx, name) get_table_int_(script, idx, name, __FUNCTION__) #define get_callback_from_table(script, idx, name, p_reg_idx) \ get_callback_from_table_(script, idx, name, p_reg_idx, __FUNCTION__) -bool ls_get_libobs_obj_(lua_State *script, const char *type, int lua_idx, - void *libobs_out, const char *id, const char *func, - int line) +bool ls_get_libobs_obj_(lua_State *script, const char *type, int lua_idx, void *libobs_out, const char *id, + const char *func, int line) { swig_type_info *info = SWIG_TypeQuery(script, type); if (info == NULL) { - warn("%s:%d: SWIG could not find type: %s%s%s", func, line, - id ? id : "", id ? "::" : "", type); + warn("%s:%d: SWIG could not find type: %s%s%s", func, line, id ? id : "", id ? "::" : "", type); return false; } @@ -100,18 +93,15 @@ bool ls_get_libobs_obj_(lua_State *script, const char *type, int lua_idx, return true; } -#define ls_get_libobs_obj(type, lua_index, obs_obj) \ - ls_get_libobs_obj_(ls->script, #type " *", lua_index, obs_obj, ls->id, \ - __FUNCTION__, __LINE__) +#define ls_get_libobs_obj(type, lua_index, obs_obj) \ + ls_get_libobs_obj_(ls->script, #type " *", lua_index, obs_obj, ls->id, __FUNCTION__, __LINE__) -bool ls_push_libobs_obj_(lua_State *script, const char *type, void *libobs_in, - bool ownership, const char *id, const char *func, - int line) +bool ls_push_libobs_obj_(lua_State *script, const char *type, void *libobs_in, bool ownership, const char *id, + const char *func, int line) { swig_type_info *info = SWIG_TypeQuery(script, type); if (info == NULL) { - warn("%s:%d: SWIG could not find type: %s%s%s", func, line, - id ? id : "", id ? "::" : "", type); + warn("%s:%d: SWIG could not find type: %s%s%s", func, line, id ? id : "", id ? "::" : "", type); return false; } @@ -119,9 +109,8 @@ bool ls_push_libobs_obj_(lua_State *script, const char *type, void *libobs_in, return true; } -#define ls_push_libobs_obj(type, obs_obj, ownership) \ - ls_push_libobs_obj_(ls->script, #type " *", obs_obj, ownership, \ - ls->id, __FUNCTION__, __LINE__) +#define ls_push_libobs_obj(type, obs_obj, ownership) \ + ls_push_libobs_obj_(ls->script, #type " *", obs_obj, ownership, ls->id, __FUNCTION__, __LINE__) /* ========================================================================= */ @@ -168,12 +157,9 @@ struct obs_lua_data { struct obs_lua_data **p_prev_next; }; -#define call_func(name, args, rets) \ - call_func_(ls->script, ls->func_##name, args, rets, #name, \ - ls->display_name) +#define call_func(name, args, rets) call_func_(ls->script, ls->func_##name, args, rets, #name, ls->display_name) #define have_func(name) (ls->func_##name != LUA_REFNIL) -#define ls_push_data() \ - lua_rawgeti(ls->script, LUA_REGISTRYINDEX, ld->lua_data_ref) +#define ls_push_data() lua_rawgeti(ls->script, LUA_REGISTRYINDEX, ld->lua_data_ref) #define ls_pop(count) lua_pop(ls->script, count) #define lock_script() \ struct obs_lua_script *__data = ls->data; \ @@ -609,8 +595,7 @@ static int obs_lua_register_source(lua_State *script) lua_pop(script, 1); } - if (!v->display_name || !*v->display_name || !*info.id || - !info.output_flags) + if (!v->display_name || !*v->display_name || !*info.id || !info.output_flags) goto fail; #define get_callback(val) \ @@ -635,8 +620,7 @@ static int obs_lua_register_source(lua_State *script) get_callback(load); #undef get_callback - get_callback_from_table(script, -1, "get_defaults", - &v->func_get_defaults); + get_callback_from_table(script, -1, "get_defaults", &v->func_get_defaults); if (!existing) { ls.data = current_lua_script; @@ -671,15 +655,13 @@ static int obs_lua_register_source(lua_State *script) if (have_func(create)) { obs_source_t *source = ld->source; - obs_data_t *settings = - obs_source_get_settings(source); + obs_data_t *settings = obs_source_get_settings(source); ls_push_libobs_obj(obs_data_t, settings, false); ls_push_libobs_obj(obs_source_t, source, false); call_func(create, 2, 1); - ld->lua_data_ref = - luaL_ref(ls->script, LUA_REGISTRYINDEX); + ld->lua_data_ref = luaL_ref(ls->script, LUA_REGISTRYINDEX); obs_data_release(settings); } @@ -707,8 +689,7 @@ void add_lua_source_functions(lua_State *script) lua_pop(script, 1); } -static inline void undef_source_type(struct obs_lua_script *data, - struct obs_lua_source *ls) +static inline void undef_source_type(struct obs_lua_script *data, struct obs_lua_source *ls) { pthread_mutex_lock(&ls->definition_mutex); pthread_mutex_lock(&data->mutex); diff --git a/shared/obs-scripting/obs-scripting-lua.c b/shared/obs-scripting/obs-scripting-lua.c index b0cb540e7..912b128bf 100644 --- a/shared/obs-scripting/obs-scripting-lua.c +++ b/shared/obs-scripting/obs-scripting-lua.c @@ -60,14 +60,11 @@ static struct obs_lua_script *first_tick_script = NULL; pthread_mutex_t lua_source_def_mutex; -#define ls_get_libobs_obj(type, lua_index, obs_obj) \ - ls_get_libobs_obj_(script, #type " *", lua_index, obs_obj, NULL, \ - __FUNCTION__, __LINE__) -#define ls_push_libobs_obj(type, obs_obj, ownership) \ - ls_push_libobs_obj_(script, #type " *", obs_obj, ownership, NULL, \ - __FUNCTION__, __LINE__) -#define call_func(name, args, rets) \ - call_func_(script, cb->reg_idx, args, rets, #name, __FUNCTION__) +#define ls_get_libobs_obj(type, lua_index, obs_obj) \ + ls_get_libobs_obj_(script, #type " *", lua_index, obs_obj, NULL, __FUNCTION__, __LINE__) +#define ls_push_libobs_obj(type, obs_obj, ownership) \ + ls_push_libobs_obj_(script, #type " *", obs_obj, ownership, NULL, __FUNCTION__, __LINE__) +#define call_func(name, args, rets) call_func_(script, cb->reg_idx, args, rets, #name, __FUNCTION__) /* ========================================================================= */ @@ -98,8 +95,7 @@ static bool load_lua_script(struct obs_lua_script *data) luaopen_ffi(script); if (luaL_dostring(script, startup_script) != 0) { - script_warn(&data->base, "Error executing startup script 1: %s", - lua_tostring(script, -1)); + script_warn(&data->base, "Error executing startup script 1: %s", lua_tostring(script, -1)); goto fail; } @@ -108,8 +104,7 @@ static bool load_lua_script(struct obs_lua_script *data) dstr_free(&str); if (ret != 0) { - script_warn(&data->base, "Error executing startup script 2: %s", - lua_tostring(script, -1)); + script_warn(&data->base, "Error executing startup script 2: %s", lua_tostring(script, -1)); goto fail; } @@ -123,23 +118,19 @@ static bool load_lua_script(struct obs_lua_script *data) file_data = os_quick_read_utf8_file(data->base.path.array); if (!file_data) { - script_warn(&data->base, "Error opening file: %s", - lua_tostring(script, -1)); + script_warn(&data->base, "Error opening file: %s", lua_tostring(script, -1)); goto fail; } - if (luaL_loadbuffer(script, file_data, strlen(file_data), - data->base.path.array) != 0) { - script_warn(&data->base, "Error loading file: %s", - lua_tostring(script, -1)); + if (luaL_loadbuffer(script, file_data, strlen(file_data), data->base.path.array) != 0) { + script_warn(&data->base, "Error loading file: %s", lua_tostring(script, -1)); bfree(file_data); goto fail; } bfree(file_data); if (lua_pcall(script, 0, LUA_MULTRET, 0) != 0) { - script_warn(&data->base, "Error running file: %s", - lua_tostring(script, -1)); + script_warn(&data->base, "Error running file: %s", lua_tostring(script, -1)); goto fail; } @@ -279,8 +270,7 @@ static inline void lua_obs_timer_remove(struct lua_obs_timer *timer) *timer->p_prev_next = timer->next; } -static inline struct lua_obs_callback * -lua_obs_timer_cb(struct lua_obs_timer *timer) +static inline struct lua_obs_callback *lua_obs_timer_cb(struct lua_obs_timer *timer) { return &((struct lua_obs_callback *)timer)[-1]; } @@ -323,8 +313,7 @@ static int timer_add(lua_State *script) if (!ms) return 0; - struct lua_obs_callback *cb = add_lua_obs_callback_extra( - script, 1, sizeof(struct lua_obs_timer)); + struct lua_obs_callback *cb = add_lua_obs_callback_extra(script, 1, sizeof(struct lua_obs_timer)); struct lua_obs_timer *timer = lua_obs_callback_extra_data(cb); timer->interval = (uint64_t)ms * 1000000ULL; @@ -342,8 +331,7 @@ static void obs_lua_main_render_callback(void *priv, uint32_t cx, uint32_t cy) lua_State *script = cb->script; if (script_callback_removed(&cb->base)) { - obs_remove_main_render_callback(obs_lua_main_render_callback, - cb); + obs_remove_main_render_callback(obs_lua_main_render_callback, cb); return; } @@ -463,13 +451,10 @@ static int obs_lua_signal_handler_disconnect(lua_State *script) struct lua_obs_callback *cb = find_lua_obs_callback(script, 3); while (cb) { - signal_handler_t *cb_handler = - calldata_ptr(&cb->base.extra, "handler"); - const char *cb_signal = - calldata_string(&cb->base.extra, "signal"); + signal_handler_t *cb_handler = calldata_ptr(&cb->base.extra, "handler"); + const char *cb_signal = calldata_string(&cb->base.extra, "signal"); - if (cb_signal && strcmp(signal, cb_signal) == 0 && - handler == cb_handler) + if (cb_signal && strcmp(signal, cb_signal) == 0 && handler == cb_handler) break; cb = find_next_lua_obs_callback(script, cb, 3); @@ -511,8 +496,7 @@ static int obs_lua_signal_handler_connect(lua_State *script) /* -------------------------------------------- */ -static void calldata_signal_callback_global(void *priv, const char *signal, - calldata_t *cd) +static void calldata_signal_callback_global(void *priv, const char *signal, calldata_t *cd) { struct lua_obs_callback *cb = priv; lua_State *script = cb->script; @@ -542,8 +526,7 @@ static int obs_lua_signal_handler_disconnect_global(lua_State *script) struct lua_obs_callback *cb = find_lua_obs_callback(script, 3); while (cb) { - signal_handler_t *cb_handler = - calldata_ptr(&cb->base.extra, "handler"); + signal_handler_t *cb_handler = calldata_ptr(&cb->base.extra, "handler"); if (handler == cb_handler) break; @@ -561,8 +544,7 @@ static void defer_connect_global(void *p_cb) struct script_callback *cb = p_cb; signal_handler_t *handler = calldata_ptr(&cb->extra, "handler"); - signal_handler_connect_global(handler, calldata_signal_callback_global, - cb); + signal_handler_connect_global(handler, calldata_signal_callback_global, cb); } static int obs_lua_signal_handler_connect_global(lua_State *script) @@ -603,8 +585,7 @@ static int enum_sources(lua_State *script) /* -------------------------------------------- */ -static void source_enum_filters_proc(obs_source_t *source, obs_source_t *filter, - void *param) +static void source_enum_filters_proc(obs_source_t *source, obs_source_t *filter, void *param) { UNUSED_PARAMETER(source); @@ -630,8 +611,7 @@ static int source_enum_filters(lua_State *script) /* -------------------------------------------- */ -static bool enum_items_proc(obs_scene_t *scene, obs_sceneitem_t *item, - void *param) +static bool enum_items_proc(obs_scene_t *scene, obs_sceneitem_t *item, void *param) { lua_State *script = param; @@ -707,8 +687,7 @@ static void defer_hotkey_unpressed(void *p_cb) hotkey_pressed(p_cb, false); } -static void hotkey_callback(void *p_cb, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void hotkey_callback(void *p_cb, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { struct lua_obs_callback *cb = p_cb; @@ -761,8 +740,7 @@ static int hotkey_register_frontend(lua_State *script) /* -------------------------------------------- */ -static bool button_prop_clicked(obs_properties_t *props, obs_property_t *p, - void *p_cb) +static bool button_prop_clicked(obs_properties_t *props, obs_property_t *p, void *p_cb) { struct lua_obs_callback *cb = p_cb; lua_State *script = cb->script; @@ -807,8 +785,7 @@ static int properties_add_button(lua_State *script) return 0; struct lua_obs_callback *cb = add_lua_obs_callback(script, 4); - p = obs_properties_add_button2(props, name, text, button_prop_clicked, - cb); + p = obs_properties_add_button2(props, name, text, button_prop_clicked, cb); if (!p || !ls_push_libobs_obj(obs_property_t, p, false)) return 0; @@ -817,8 +794,7 @@ static int properties_add_button(lua_State *script) /* -------------------------------------------- */ -static bool modified_callback(void *p_cb, obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) +static bool modified_callback(void *p_cb, obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { struct lua_obs_callback *cb = p_cb; lua_State *script = cb->script; @@ -1040,24 +1016,18 @@ static void add_hook_functions(lua_State *script) add_func("sceneitem_list_release", sceneitem_list_release); add_func("calldata_source", calldata_source); add_func("calldata_sceneitem", calldata_sceneitem); - add_func("obs_add_main_render_callback", - obs_lua_add_main_render_callback); - add_func("obs_remove_main_render_callback", - obs_lua_remove_main_render_callback); + add_func("obs_add_main_render_callback", obs_lua_add_main_render_callback); + add_func("obs_remove_main_render_callback", obs_lua_remove_main_render_callback); add_func("obs_add_tick_callback", obs_lua_add_tick_callback); add_func("obs_remove_tick_callback", obs_lua_remove_tick_callback); add_func("signal_handler_connect", obs_lua_signal_handler_connect); - add_func("signal_handler_disconnect", - obs_lua_signal_handler_disconnect); - add_func("signal_handler_connect_global", - obs_lua_signal_handler_connect_global); - add_func("signal_handler_disconnect_global", - obs_lua_signal_handler_disconnect_global); + add_func("signal_handler_disconnect", obs_lua_signal_handler_disconnect); + add_func("signal_handler_connect_global", obs_lua_signal_handler_connect_global); + add_func("signal_handler_disconnect_global", obs_lua_signal_handler_disconnect_global); add_func("obs_hotkey_unregister", hotkey_unregister); add_func("obs_hotkey_register_frontend", hotkey_register_frontend); add_func("obs_properties_add_button", properties_add_button); - add_func("obs_property_set_modified_callback", - property_set_modified_callback); + add_func("obs_property_set_modified_callback", property_set_modified_callback); add_func("remove_current_callback", remove_current_callback); lua_pop(script, 1); @@ -1130,8 +1100,7 @@ bool obs_lua_script_load(obs_script_t *s) if (!data->base.loaded) { data->base.loaded = load_lua_script(data); if (data->base.loaded) { - blog(LOG_INFO, "[obs-scripting]: Loaded lua script: %s", - data->base.file.array); + blog(LOG_INFO, "[obs-scripting]: Loaded lua script: %s", data->base.file.array); obs_lua_script_update(s, NULL); } } @@ -1193,8 +1162,7 @@ void obs_lua_script_unload(obs_script_t *s) * processor or operating system is going to schedule things. a more * ideal method would be to reference count the script objects and * atomically share ownership with callbacks when they're called. */ - struct lua_obs_callback *cb = - (struct lua_obs_callback *)data->first_callback; + struct lua_obs_callback *cb = (struct lua_obs_callback *)data->first_callback; while (cb) { os_atomic_set_bool(&cb->base.removed, true); cb = (struct lua_obs_callback *)cb->base.next; @@ -1240,8 +1208,7 @@ void obs_lua_script_unload(obs_script_t *s) cb = (struct lua_obs_callback *)data->first_callback; while (cb) { - struct lua_obs_callback *next = - (struct lua_obs_callback *)cb->base.next; + struct lua_obs_callback *next = (struct lua_obs_callback *)cb->base.next; remove_lua_obs_callback(cb); cb = next; } @@ -1254,8 +1221,7 @@ void obs_lua_script_unload(obs_script_t *s) lua_close(script); s->loaded = false; - blog(LOG_INFO, "[obs-scripting]: Unloaded lua script: %s", - data->base.file.array); + blog(LOG_INFO, "[obs-scripting]: Unloaded lua script: %s", data->base.file.array); } void obs_lua_script_destroy(obs_script_t *s) @@ -1311,8 +1277,7 @@ obs_properties_t *obs_lua_script_get_properties(obs_script_t *s) current_lua_script = data; pthread_mutex_lock(&data->mutex); - call_func_(script, data->get_properties, 0, 1, "script_properties", - __FUNCTION__); + call_func_(script, data->get_properties, 0, 1, "script_properties", __FUNCTION__); ls_get_libobs_obj(obs_properties_t, -1, &props); pthread_mutex_unlock(&data->mutex); @@ -1386,8 +1351,7 @@ void obs_lua_load(void) add_package_cpath(&package_cpath, import_path); #if !defined(_WIN32) && !defined(__APPLE__) - char *relative_script_path = - os_get_executable_path_ptr("../" SCRIPT_DIR); + char *relative_script_path = os_get_executable_path_ptr("../" SCRIPT_DIR); if (relative_script_path) add_package_cpath(&package_cpath, relative_script_path); bfree(relative_script_path); diff --git a/shared/obs-scripting/obs-scripting-lua.h b/shared/obs-scripting/obs-scripting-lua.h index 2631d292e..1eaf684a7 100644 --- a/shared/obs-scripting/obs-scripting-lua.h +++ b/shared/obs-scripting/obs-scripting-lua.h @@ -106,13 +106,11 @@ struct lua_obs_callback { int reg_idx; }; -static inline struct lua_obs_callback * -add_lua_obs_callback_extra(lua_State *script, int stack_idx, size_t extra_size) +static inline struct lua_obs_callback *add_lua_obs_callback_extra(lua_State *script, int stack_idx, size_t extra_size) { struct obs_lua_script *data = current_lua_script; struct lua_obs_callback *cb = - add_script_callback(&data->first_callback, (obs_script_t *)data, - sizeof(*cb) + extra_size); + add_script_callback(&data->first_callback, (obs_script_t *)data, sizeof(*cb) + extra_size); lua_pushvalue(script, stack_idx); cb->reg_idx = luaL_ref(script, LUA_REGISTRYINDEX); @@ -120,8 +118,7 @@ add_lua_obs_callback_extra(lua_State *script, int stack_idx, size_t extra_size) return cb; } -static inline struct lua_obs_callback *add_lua_obs_callback(lua_State *script, - int stack_idx) +static inline struct lua_obs_callback *add_lua_obs_callback(lua_State *script, int stack_idx) { return add_lua_obs_callback_extra(script, stack_idx, 0); } @@ -131,20 +128,17 @@ static inline void *lua_obs_callback_extra_data(struct lua_obs_callback *cb) return (void *)&cb[1]; } -static inline struct obs_lua_script * -lua_obs_callback_script(struct lua_obs_callback *cb) +static inline struct obs_lua_script *lua_obs_callback_script(struct lua_obs_callback *cb) { return (struct obs_lua_script *)cb->base.script; } -static inline struct lua_obs_callback * -find_next_lua_obs_callback(lua_State *script, struct lua_obs_callback *cb, - int stack_idx) +static inline struct lua_obs_callback *find_next_lua_obs_callback(lua_State *script, struct lua_obs_callback *cb, + int stack_idx) { struct obs_lua_script *data = current_lua_script; - cb = cb ? (struct lua_obs_callback *)cb->base.next - : (struct lua_obs_callback *)data->first_callback; + cb = cb ? (struct lua_obs_callback *)cb->base.next : (struct lua_obs_callback *)data->first_callback; while (cb) { lua_rawgeti(script, LUA_REGISTRYINDEX, cb->reg_idx); @@ -160,8 +154,7 @@ find_next_lua_obs_callback(lua_State *script, struct lua_obs_callback *cb, return cb; } -static inline struct lua_obs_callback *find_lua_obs_callback(lua_State *script, - int stack_idx) +static inline struct lua_obs_callback *find_lua_obs_callback(lua_State *script, int stack_idx) { return find_next_lua_obs_callback(script, NULL, stack_idx); } @@ -201,8 +194,7 @@ static inline int is_function(lua_State *script, int idx) typedef int (*param_cb)(lua_State *script, int idx); -static inline bool verify_args1_(lua_State *script, param_cb param1_check, - const char *func) +static inline bool verify_args1_(lua_State *script, param_cb param1_check, const char *func) { if (lua_gettop(script) != 1) { warn("Wrong number of parameters for %s", func); @@ -216,11 +208,9 @@ static inline bool verify_args1_(lua_State *script, param_cb param1_check, return true; } -#define verify_args1(script, param1_check) \ - verify_args1_(script, param1_check, __FUNCTION__) +#define verify_args1(script, param1_check) verify_args1_(script, param1_check, __FUNCTION__) -static inline bool call_func_(lua_State *script, int reg_idx, int args, - int rets, const char *func, +static inline bool call_func_(lua_State *script, int reg_idx, int args, int rets, const char *func, const char *display_name) { if (reg_idx == LUA_REFNIL) @@ -232,8 +222,7 @@ static inline bool call_func_(lua_State *script, int reg_idx, int args, lua_insert(script, -1 - args); if (lua_pcall(script, args, rets, 0) != 0) { - script_warn(&data->base, "Failed to call %s for %s: %s", func, - display_name, lua_tostring(script, -1)); + script_warn(&data->base, "Failed to call %s for %s: %s", func, display_name, lua_tostring(script, -1)); lua_pop(script, 1); return false; } @@ -241,11 +230,9 @@ static inline bool call_func_(lua_State *script, int reg_idx, int args, return true; } -bool ls_get_libobs_obj_(lua_State *script, const char *type, int lua_idx, - void *libobs_out, const char *id, const char *func, - int line); -bool ls_push_libobs_obj_(lua_State *script, const char *type, void *libobs_in, - bool ownership, const char *id, const char *func, - int line); +bool ls_get_libobs_obj_(lua_State *script, const char *type, int lua_idx, void *libobs_out, const char *id, + const char *func, int line); +bool ls_push_libobs_obj_(lua_State *script, const char *type, void *libobs_in, bool ownership, const char *id, + const char *func, int line); extern void add_lua_source_functions(lua_State *script); diff --git a/shared/obs-scripting/obs-scripting-python-frontend.c b/shared/obs-scripting/obs-scripting-python-frontend.c index 61e5a5858..a1d6ee807 100644 --- a/shared/obs-scripting/obs-scripting-python-frontend.c +++ b/shared/obs-scripting/obs-scripting-python-frontend.c @@ -20,11 +20,9 @@ #include "obs-scripting-python.h" -#define libobs_to_py(type, obs_obj, ownership, py_obj) \ - libobs_to_py_(#type " *", obs_obj, ownership, py_obj, NULL, __func__, \ - __LINE__) -#define py_to_libobs(type, py_obj, libobs_out) \ - py_to_libobs_(#type " *", py_obj, libobs_out, NULL, __func__, __LINE__) +#define libobs_to_py(type, obs_obj, ownership, py_obj) \ + libobs_to_py_(#type " *", obs_obj, ownership, py_obj, NULL, __func__, __LINE__) +#define py_to_libobs(type, py_obj, libobs_out) py_to_libobs_(#type " *", py_obj, libobs_out, NULL, __func__, __LINE__) /* ----------------------------------- */ @@ -275,8 +273,7 @@ static PyObject *set_current_profile(PyObject *self, PyObject *args) /* ----------------------------------- */ -static void frontend_save_callback(obs_data_t *save_data, bool saving, - void *priv) +static void frontend_save_callback(obs_data_t *save_data, bool saving, void *priv) { struct python_obs_callback *cb = priv; @@ -290,8 +287,7 @@ static void frontend_save_callback(obs_data_t *save_data, bool saving, PyObject *py_save_data; if (libobs_to_py(obs_data_t, save_data, false, &py_save_data)) { - PyObject *args = Py_BuildValue("(ON)", py_save_data, - PyBool_FromLong(saving)); + PyObject *args = Py_BuildValue("(ON)", py_save_data, PyBool_FromLong(saving)); struct python_obs_callback *last_cb = cur_python_cb; cur_python_cb = cb; @@ -323,8 +319,7 @@ static PyObject *remove_save_callback(PyObject *self, PyObject *args) if (!py_cb || !PyFunction_Check(py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); if (cb) remove_python_obs_callback(cb); return python_none(); @@ -393,8 +388,7 @@ static PyObject *remove_event_callback(PyObject *self, PyObject *args) if (!py_cb || !PyFunction_Check(py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); if (cb) remove_python_obs_callback(cb); return python_none(); diff --git a/shared/obs-scripting/obs-scripting-python-import.c b/shared/obs-scripting/obs-scripting-python-import.c index be6342b2c..9981669cc 100644 --- a/shared/obs-scripting/obs-scripting-python-import.c +++ b/shared/obs-scripting/obs-scripting-python-import.c @@ -51,8 +51,7 @@ bool import_python(const char *python_path, python_version_t *python_version) python_path = ""; if (!python_version) { - blog(LOG_DEBUG, - "[Python] Invalid python_version pointer provided."); + blog(LOG_DEBUG, "[Python] Invalid python_version pointer provided."); goto fail; } @@ -68,8 +67,7 @@ bool import_python(const char *python_path, python_version_t *python_version) char cur_version[5]; char next_version[5]; - snprintf(cur_version, sizeof(cur_version), VERSION_PATTERN, - PY_MAJOR_VERSION_MAX, PY_MINOR_VERSION_MAX); + snprintf(cur_version, sizeof(cur_version), VERSION_PATTERN, PY_MAJOR_VERSION_MAX, PY_MINOR_VERSION_MAX); struct dstr temp; dstr_init(&temp); @@ -77,8 +75,7 @@ bool import_python(const char *python_path, python_version_t *python_version) int minor_version = PY_MINOR_VERSION_MAX; do { - dstr_printf(&lib_candidate_path, "%s%s", lib_path.array, - temp.array); + dstr_printf(&lib_candidate_path, "%s%s", lib_path.array, temp.array); if (access(lib_candidate_path.array, F_OK) == 0) { lib = os_dlopen(lib_candidate_path.array); } @@ -87,10 +84,8 @@ bool import_python(const char *python_path, python_version_t *python_version) break; } - snprintf(cur_version, sizeof(cur_version), VERSION_PATTERN, - PY_MAJOR_VERSION_MAX, minor_version); - snprintf(next_version, sizeof(next_version), VERSION_PATTERN, - PY_MAJOR_VERSION_MAX, --minor_version); + snprintf(cur_version, sizeof(cur_version), VERSION_PATTERN, PY_MAJOR_VERSION_MAX, minor_version); + snprintf(next_version, sizeof(next_version), VERSION_PATTERN, PY_MAJOR_VERSION_MAX, --minor_version); dstr_replace(&temp, cur_version, next_version); } while (minor_version > 5); @@ -98,22 +93,20 @@ bool import_python(const char *python_path, python_version_t *python_version) dstr_free(&lib_candidate_path); if (!lib) { - blog(LOG_WARNING, "[Python] Could not load library: %s", - lib_path.array); + blog(LOG_WARNING, "[Python] Could not load library: %s", lib_path.array); goto fail; } python_version->major = PY_MAJOR_VERSION_MAX; python_version->minor = minor_version; -#define IMPORT_FUNC(x) \ - do { \ - Import_##x = os_dlsym(lib, #x); \ - if (!Import_##x) { \ - blog(LOG_WARNING, "[Python] Failed to import: %s", \ - #x); \ - goto fail; \ - } \ +#define IMPORT_FUNC(x) \ + do { \ + Import_##x = os_dlsym(lib, #x); \ + if (!Import_##x) { \ + blog(LOG_WARNING, "[Python] Failed to import: %s", #x); \ + goto fail; \ + } \ } while (false) IMPORT_FUNC(PyType_Ready); diff --git a/shared/obs-scripting/obs-scripting-python-import.h b/shared/obs-scripting/obs-scripting-python-import.h index 580957df7..3887ce48e 100644 --- a/shared/obs-scripting/obs-scripting-python-import.h +++ b/shared/obs-scripting/obs-scripting-python-import.h @@ -71,17 +71,14 @@ PY_EXTERN PyObject *(*Import_PyLong_FromLong)(long); PY_EXTERN PyObject *(*Import_PyBool_FromLong)(long); PY_EXTERN PyGILState_STATE (*Import_PyGILState_Ensure)(void); PY_EXTERN PyThreadState *(*Import_PyGILState_GetThisThreadState)(void); -PY_EXTERN void (*Import_PyErr_SetString)(PyObject *exception, - const char *string); +PY_EXTERN void (*Import_PyErr_SetString)(PyObject *exception, const char *string); PY_EXTERN PyObject *(*Import_PyErr_Occurred)(void); PY_EXTERN void (*Import_PyErr_Fetch)(PyObject **, PyObject **, PyObject **); PY_EXTERN void (*Import_PyErr_Restore)(PyObject *, PyObject *, PyObject *); PY_EXTERN void (*Import_PyErr_WriteUnraisable)(PyObject *); -PY_EXTERN int (*Import_PyArg_UnpackTuple)(PyObject *, const char *, Py_ssize_t, - Py_ssize_t, ...); +PY_EXTERN int (*Import_PyArg_UnpackTuple)(PyObject *, const char *, Py_ssize_t, Py_ssize_t, ...); PY_EXTERN PyObject *(*Import_Py_BuildValue)(const char *, ...); -PY_EXTERN int (*Import_PyRun_SimpleStringFlags)(const char *, - PyCompilerFlags *); +PY_EXTERN int (*Import_PyRun_SimpleStringFlags)(const char *, PyCompilerFlags *); PY_EXTERN void (*Import_PyErr_Print)(void); PY_EXTERN void (*Import_Py_SetPythonHome)(wchar_t *); PY_EXTERN void (*Import_Py_Initialize)(void); @@ -92,31 +89,23 @@ PY_EXTERN int (*Import_PyEval_ThreadsInitialized)(void); PY_EXTERN void (*Import_PyEval_ReleaseThread)(PyThreadState *tstate); PY_EXTERN void (*Import_PySys_SetArgv)(int, wchar_t **); PY_EXTERN PyObject *(*Import_PyImport_ImportModule)(const char *name); -PY_EXTERN PyObject *(*Import_PyObject_CallFunctionObjArgs)(PyObject *callable, - ...); +PY_EXTERN PyObject *(*Import_PyObject_CallFunctionObjArgs)(PyObject *callable, ...); PY_EXTERN PyObject(*Import__Py_NotImplementedStruct); PY_EXTERN PyObject *(*Import_PyExc_TypeError); PY_EXTERN PyObject *(*Import_PyExc_RuntimeError); PY_EXTERN PyObject *(*Import_PyObject_GetAttr)(PyObject *, PyObject *); PY_EXTERN PyObject *(*Import_PyUnicode_FromString)(const char *u); PY_EXTERN PyObject *(*Import_PyDict_New)(void); -PY_EXTERN PyObject *(*Import_PyDict_GetItemString)(PyObject *dp, - const char *key); -PY_EXTERN int (*Import_PyDict_SetItemString)(PyObject *dp, const char *key, - PyObject *item); -PY_EXTERN PyObject *(*Import_PyCFunction_NewEx)(PyMethodDef *, PyObject *, - PyObject *); -PY_EXTERN PyObject *(*Import_PyCMethod_New)(PyMethodDef *, PyObject *, - PyObject *, PyTypeObject *); +PY_EXTERN PyObject *(*Import_PyDict_GetItemString)(PyObject *dp, const char *key); +PY_EXTERN int (*Import_PyDict_SetItemString)(PyObject *dp, const char *key, PyObject *item); +PY_EXTERN PyObject *(*Import_PyCFunction_NewEx)(PyMethodDef *, PyObject *, PyObject *); +PY_EXTERN PyObject *(*Import_PyCMethod_New)(PyMethodDef *, PyObject *, PyObject *, PyTypeObject *); PY_EXTERN PyObject *(*Import_PyModule_GetDict)(PyObject *); PY_EXTERN PyObject *(*Import_PyModule_GetNameObject)(PyObject *); -PY_EXTERN int (*Import_PyModule_AddObject)(PyObject *, const char *, - PyObject *); -PY_EXTERN int (*Import_PyModule_AddStringConstant)(PyObject *, const char *, - const char *); +PY_EXTERN int (*Import_PyModule_AddObject)(PyObject *, const char *, PyObject *); +PY_EXTERN int (*Import_PyModule_AddStringConstant)(PyObject *, const char *, const char *); PY_EXTERN PyObject *(*Import_PyImport_Import)(PyObject *name); -PY_EXTERN PyObject *(*Import_PyObject_CallObject)(PyObject *callable_object, - PyObject *args); +PY_EXTERN PyObject *(*Import_PyObject_CallObject)(PyObject *callable_object, PyObject *args); PY_EXTERN struct _longobject(*Import__Py_FalseStruct); PY_EXTERN struct _longobject(*Import__Py_TrueStruct); PY_EXTERN void (*Import_PyGILState_Release)(PyGILState_STATE); @@ -124,18 +113,15 @@ PY_EXTERN int (*Import_PyList_Append)(PyObject *, PyObject *); PY_EXTERN PyObject *(*Import_PySys_GetObject)(const char *); PY_EXTERN PyObject *(*Import_PyImport_ReloadModule)(PyObject *m); PY_EXTERN PyObject *(*Import_PyObject_GetAttrString)(PyObject *, const char *); -PY_EXTERN PyObject *(*Import_PyCapsule_New)(void *pointer, const char *name, - PyCapsule_Destructor destructor); -PY_EXTERN void *(*Import_PyCapsule_GetPointer)(PyObject *capsule, - const char *name); +PY_EXTERN PyObject *(*Import_PyCapsule_New)(void *pointer, const char *name, PyCapsule_Destructor destructor); +PY_EXTERN void *(*Import_PyCapsule_GetPointer)(PyObject *capsule, const char *name); PY_EXTERN int (*Import_PyArg_ParseTuple)(PyObject *, const char *, ...); PY_EXTERN PyTypeObject(*Import_PyFunction_Type); PY_EXTERN int (*Import_PyObject_SetAttr)(PyObject *, PyObject *, PyObject *); PY_EXTERN PyObject *(*Import__PyObject_New)(PyTypeObject *); PY_EXTERN void *(*Import_PyCapsule_Import)(const char *name, int no_block); PY_EXTERN void (*Import_PyErr_Clear)(void); -PY_EXTERN PyObject *(*Import_PyObject_Call)(PyObject *callable_object, - PyObject *args, PyObject *kwargs); +PY_EXTERN PyObject *(*Import_PyObject_Call)(PyObject *callable_object, PyObject *args, PyObject *kwargs); PY_EXTERN PyObject *(*Import_PyList_New)(Py_ssize_t size); PY_EXTERN Py_ssize_t (*Import_PyList_Size)(PyObject *); PY_EXTERN PyObject *(*Import_PyList_GetItem)(PyObject *, Py_ssize_t); @@ -151,8 +137,7 @@ PY_EXTERN void (*Import__Py_Dealloc)(PyObject *obj); PY_EXTERN PyTypeObject PyCFunction_Type; -extern bool import_python(const char *python_path, - python_version_t *python_version); +extern bool import_python(const char *python_path, python_version_t *python_version); #ifndef NO_REDEFS #define PyType_Ready Import_PyType_Ready @@ -239,8 +224,7 @@ extern bool import_python(const char *python_path, #endif #if PY_VERSION_HEX >= 0x030800f0 -static inline void Import__Py_DECREF(const char *filename, int lineno, - PyObject *op) +static inline void Import__Py_DECREF(const char *filename, int lineno, PyObject *op) { UNUSED_PARAMETER(filename); UNUSED_PARAMETER(lineno); @@ -271,8 +255,7 @@ static inline void Import__Py_XDECREF(PyObject *op) #endif // PY_VERSION_HEX >= 0x030800f0 #if PY_VERSION_HEX >= 0x030900b0 -static inline int Import_PyType_HasFeature(PyTypeObject *type, - unsigned long feature) +static inline int Import_PyType_HasFeature(PyTypeObject *type, unsigned long feature) { return ((PyType_GetFlags(type) & feature) != 0); } diff --git a/shared/obs-scripting/obs-scripting-python.c b/shared/obs-scripting/obs-scripting-python.c index f7a37f2d8..c5a581cc8 100644 --- a/shared/obs-scripting/obs-scripting-python.c +++ b/shared/obs-scripting/obs-scripting-python.c @@ -64,13 +64,11 @@ struct python_obs_callback *cur_python_cb = NULL; /* -------------------------------------------- */ -bool py_to_libobs_(const char *type, PyObject *py_in, void *libobs_out, - const char *id, const char *func, int line) +bool py_to_libobs_(const char *type, PyObject *py_in, void *libobs_out, const char *id, const char *func, int line) { swig_type_info *info = SWIG_TypeQuery(type); if (info == NULL) { - warn("%s:%d: SWIG could not find type: %s%s%s", func, line, - id ? id : "", id ? "::" : "", type); + warn("%s:%d: SWIG could not find type: %s%s%s", func, line, id ? id : "", id ? "::" : "", type); return false; } @@ -85,14 +83,12 @@ bool py_to_libobs_(const char *type, PyObject *py_in, void *libobs_out, return true; } -bool libobs_to_py_(const char *type, void *libobs_in, bool ownership, - PyObject **py_out, const char *id, const char *func, - int line) +bool libobs_to_py_(const char *type, void *libobs_in, bool ownership, PyObject **py_out, const char *id, + const char *func, int line) { swig_type_info *info = SWIG_TypeQuery(type); if (info == NULL) { - warn("%s:%d: SWIG could not find type: %s%s%s", func, line, - id ? id : "", id ? "::" : "", type); + warn("%s:%d: SWIG could not find type: %s%s%s", func, line, id ? id : "", id ? "::" : "", type); return false; } @@ -107,11 +103,9 @@ bool libobs_to_py_(const char *type, void *libobs_in, bool ownership, return true; } -#define libobs_to_py(type, obs_obj, ownership, py_obj) \ - libobs_to_py_(#type " *", obs_obj, ownership, py_obj, NULL, __func__, \ - __LINE__) -#define py_to_libobs(type, py_obj, libobs_out) \ - py_to_libobs_(#type " *", py_obj, libobs_out, NULL, __func__, __LINE__) +#define libobs_to_py(type, obs_obj, ownership, py_obj) \ + libobs_to_py_(#type " *", obs_obj, ownership, py_obj, NULL, __func__, __LINE__) +#define py_to_libobs(type, py_obj, libobs_out) py_to_libobs_(#type " *", py_obj, libobs_out, NULL, __func__, __LINE__) #define lock_callback(cb) \ lock_python(); \ @@ -201,8 +195,7 @@ static bool load_python_script(struct obs_python_script *data) if (py_error() || ret != 0) goto fail; - ret = PyModule_AddStringConstant(py_module, "__script_dir__", - data->dir.array); + ret = PyModule_AddStringConstant(py_module, "__script_dir__", data->dir.array); if (py_error() || ret != 0) goto fail; @@ -211,10 +204,9 @@ static bool load_python_script(struct obs_python_script *data) if (py_error() || ret != 0) goto fail; - static PyMethodDef global_funcs[] = { - {"script_path", py_get_current_script_path, METH_NOARGS, - "Gets the script path"}, - {0}}; + static PyMethodDef global_funcs[] = {{"script_path", py_get_current_script_path, METH_NOARGS, + "Gets the script path"}, + {0}}; add_functions_to_py_module(py_module, global_funcs); @@ -226,8 +218,7 @@ static bool load_python_script(struct obs_python_script *data) if (!data->save) PyErr_Clear(); - data->get_properties = - PyObject_GetAttrString(py_module, "script_properties"); + data->get_properties = PyObject_GetAttrString(py_module, "script_properties"); if (!data->get_properties) PyErr_Clear(); @@ -404,8 +395,7 @@ static inline void python_obs_timer_remove(struct python_obs_timer *timer) *timer->p_prev_next = timer->next; } -static inline struct python_obs_callback * -python_obs_timer_cb(struct python_obs_timer *timer) +static inline struct python_obs_callback *python_obs_timer_cb(struct python_obs_timer *timer) { return &((struct python_obs_callback *)timer)[-1]; } @@ -420,8 +410,7 @@ static PyObject *timer_remove(PyObject *self, PyObject *args) if (!parse_args(args, "O", &py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); if (cb) remove_python_obs_callback(cb); return python_none(); @@ -459,8 +448,7 @@ static PyObject *timer_add(PyObject *self, PyObject *args) if (!parse_args(args, "Oi", &py_cb, &ms)) return python_none(); - struct python_obs_callback *cb = add_python_obs_callback_extra( - script, py_cb, sizeof(struct python_obs_timer)); + struct python_obs_callback *cb = add_python_obs_callback_extra(script, py_cb, sizeof(struct python_obs_timer)); struct python_obs_timer *timer = python_obs_callback_extra_data(cb); timer->interval = (uint64_t)ms * 1000000ULL; @@ -498,8 +486,7 @@ static PyObject *obs_python_remove_tick_callback(PyObject *self, PyObject *args) PyObject *py_cb = NULL; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -510,8 +497,7 @@ static PyObject *obs_python_remove_tick_callback(PyObject *self, PyObject *args) if (!py_cb || !PyFunction_Check(py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); if (cb) remove_python_obs_callback(cb); return python_none(); @@ -523,8 +509,7 @@ static PyObject *obs_python_add_tick_callback(PyObject *self, PyObject *args) PyObject *py_cb = NULL; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -567,8 +552,7 @@ static void calldata_signal_callback(void *priv, calldata_t *cd) unlock_callback(); } -static PyObject *obs_python_signal_handler_disconnect(PyObject *self, - PyObject *args) +static PyObject *obs_python_signal_handler_disconnect(PyObject *self, PyObject *args) { struct obs_python_script *script = cur_python_script; PyObject *py_sh = NULL; @@ -576,8 +560,7 @@ static PyObject *obs_python_signal_handler_disconnect(PyObject *self, const char *signal; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -593,16 +576,12 @@ static PyObject *obs_python_signal_handler_disconnect(PyObject *self, if (!py_cb || !PyFunction_Check(py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); while (cb) { - signal_handler_t *cb_handler = - calldata_ptr(&cb->base.extra, "handler"); - const char *cb_signal = - calldata_string(&cb->base.extra, "signal"); + signal_handler_t *cb_handler = calldata_ptr(&cb->base.extra, "handler"); + const char *cb_signal = calldata_string(&cb->base.extra, "signal"); - if (cb_signal && strcmp(signal, cb_signal) == 0 && - handler == cb_handler) + if (cb_signal && strcmp(signal, cb_signal) == 0 && handler == cb_handler) break; cb = find_next_python_obs_callback(script, cb, py_cb); @@ -613,8 +592,7 @@ static PyObject *obs_python_signal_handler_disconnect(PyObject *self, return python_none(); } -static PyObject *obs_python_signal_handler_connect(PyObject *self, - PyObject *args) +static PyObject *obs_python_signal_handler_connect(PyObject *self, PyObject *args) { struct obs_python_script *script = cur_python_script; PyObject *py_sh = NULL; @@ -622,8 +600,7 @@ static PyObject *obs_python_signal_handler_connect(PyObject *self, const char *signal; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -647,8 +624,7 @@ static PyObject *obs_python_signal_handler_connect(PyObject *self, /* -------------------------------------------- */ -static void calldata_signal_callback_global(void *priv, const char *signal, - calldata_t *cd) +static void calldata_signal_callback_global(void *priv, const char *signal, calldata_t *cd) { struct python_obs_callback *cb = priv; @@ -673,16 +649,14 @@ static void calldata_signal_callback_global(void *priv, const char *signal, unlock_callback(); } -static PyObject *obs_python_signal_handler_disconnect_global(PyObject *self, - PyObject *args) +static PyObject *obs_python_signal_handler_disconnect_global(PyObject *self, PyObject *args) { struct obs_python_script *script = cur_python_script; PyObject *py_sh = NULL; PyObject *py_cb = NULL; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -698,11 +672,9 @@ static PyObject *obs_python_signal_handler_disconnect_global(PyObject *self, if (!py_cb || !PyFunction_Check(py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); while (cb) { - signal_handler_t *cb_handler = - calldata_ptr(&cb->base.extra, "handler"); + signal_handler_t *cb_handler = calldata_ptr(&cb->base.extra, "handler"); if (handler == cb_handler) break; @@ -715,16 +687,14 @@ static PyObject *obs_python_signal_handler_disconnect_global(PyObject *self, return python_none(); } -static PyObject *obs_python_signal_handler_connect_global(PyObject *self, - PyObject *args) +static PyObject *obs_python_signal_handler_connect_global(PyObject *self, PyObject *args) { struct obs_python_script *script = cur_python_script; PyObject *py_sh = NULL; PyObject *py_cb = NULL; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -742,8 +712,7 @@ static PyObject *obs_python_signal_handler_connect_global(PyObject *self, struct python_obs_callback *cb = add_python_obs_callback(script, py_cb); calldata_set_ptr(&cb->base.extra, "handler", handler); - signal_handler_connect_global(handler, calldata_signal_callback_global, - cb); + signal_handler_connect_global(handler, calldata_signal_callback_global, cb); return python_none(); } @@ -798,8 +767,7 @@ static inline PyObject *py_invalid_hotkey_id() return PyLong_FromUnsignedLongLong(OBS_INVALID_HOTKEY_ID); } -static void hotkey_callback(void *p_cb, obs_hotkey_id id, obs_hotkey_t *hotkey, - bool pressed) +static void hotkey_callback(void *p_cb, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { struct python_obs_callback *cb = p_cb; @@ -821,8 +789,7 @@ static PyObject *hotkey_unregister(PyObject *self, PyObject *args) PyObject *py_cb = NULL; if (!script) { - PyErr_SetString(PyExc_RuntimeError, - "No active script, report this to Lain"); + PyErr_SetString(PyExc_RuntimeError, "No active script, report this to Lain"); return NULL; } @@ -831,8 +798,7 @@ static PyObject *hotkey_unregister(PyObject *self, PyObject *args) if (!py_cb || !PyFunction_Check(py_cb)) return python_none(); - struct python_obs_callback *cb = - find_python_obs_callback(script, py_cb); + struct python_obs_callback *cb = find_python_obs_callback(script, py_cb); if (cb) remove_python_obs_callback(cb); @@ -867,8 +833,7 @@ static PyObject *hotkey_register_frontend(PyObject *self, PyObject *args) /* -------------------------------------------- */ -static bool button_prop_clicked(obs_properties_t *props, obs_property_t *p, - void *p_cb) +static bool button_prop_clicked(obs_properties_t *props, obs_property_t *p, void *p_cb) { struct python_obs_callback *cb = p_cb; bool ret = false; @@ -881,8 +846,7 @@ static bool button_prop_clicked(obs_properties_t *props, obs_property_t *p, PyObject *py_props = NULL; PyObject *py_p = NULL; - if (libobs_to_py(obs_properties_t, props, false, &py_props) && - libobs_to_py(obs_property_t, p, false, &py_p)) { + if (libobs_to_py(obs_properties_t, props, false, &py_props) && libobs_to_py(obs_property_t, p, false, &py_p)) { PyObject *args = Py_BuildValue("(OO)", py_props, py_p); PyObject *py_ret = PyObject_CallObject(cb->func, args); @@ -919,8 +883,7 @@ static PyObject *properties_add_button(PyObject *self, PyObject *args) return python_none(); struct python_obs_callback *cb = add_python_obs_callback(script, py_cb); - p = obs_properties_add_button2(props, name, text, button_prop_clicked, - cb); + p = obs_properties_add_button2(props, name, text, button_prop_clicked, cb); if (!p || !libobs_to_py(obs_property_t, p, false, &py_ret)) return python_none(); @@ -931,8 +894,7 @@ static PyObject *properties_add_button(PyObject *self, PyObject *args) /* -------------------------------------------- */ -static bool modified_callback(void *p_cb, obs_properties_t *props, - obs_property_t *p, obs_data_t *settings) +static bool modified_callback(void *p_cb, obs_properties_t *props, obs_property_t *p, obs_data_t *settings) { struct python_obs_callback *cb = p_cb; bool ret = false; @@ -946,12 +908,10 @@ static bool modified_callback(void *p_cb, obs_properties_t *props, PyObject *py_p = NULL; PyObject *py_settings = NULL; - if (libobs_to_py(obs_properties_t, props, false, &py_props) && - libobs_to_py(obs_property_t, p, false, &py_p) && + if (libobs_to_py(obs_properties_t, props, false, &py_props) && libobs_to_py(obs_property_t, p, false, &py_p) && libobs_to_py(obs_data_t, settings, false, &py_settings)) { - PyObject *args = - Py_BuildValue("(OOO)", py_props, py_p, py_settings); + PyObject *args = Py_BuildValue("(OOO)", py_props, py_p, py_settings); PyObject *py_ret = PyObject_CallObject(cb->func, args); if (!py_error()) ret = py_ret == Py_True; @@ -1074,8 +1034,7 @@ static PyObject *enum_sources(PyObject *self, PyObject *args) /* -------------------------------------------- */ -static bool enum_items_proc(obs_scene_t *scene, obs_sceneitem_t *item, - void *param) +static bool enum_items_proc(obs_scene_t *scene, obs_sceneitem_t *item, void *param) { PyObject *list = param; PyObject *py_item; @@ -1170,8 +1129,7 @@ static PyObject *sceneitem_list_release(PyObject *self, PyObject *args) struct dstr cur_py_log_chunk = {0}; -static PyObject *py_script_log_internal(PyObject *self, PyObject *args, - bool add_endl) +static PyObject *py_script_log_internal(PyObject *self, PyObject *args, bool add_endl) { static bool calling_self = false; int log_level; @@ -1200,8 +1158,7 @@ static PyObject *py_script_log_internal(PyObject *self, PyObject *args, while (endl) { *endl = 0; if (cur_python_script) - script_log(&cur_python_script->base, log_level, "%s", - start); + script_log(&cur_python_script->base, log_level, "%s", start); else script_log(NULL, log_level, "%s", start); *endl = '\n'; @@ -1251,25 +1208,17 @@ static void add_hook_functions(PyObject *module) DEF_FUNC("sceneitem_list_release", sceneitem_list_release), DEF_FUNC("obs_enum_sources", enum_sources), DEF_FUNC("obs_scene_enum_items", scene_enum_items), - DEF_FUNC("obs_sceneitem_group_enum_items", - sceneitem_group_enum_items), - DEF_FUNC("obs_remove_tick_callback", - obs_python_remove_tick_callback), + DEF_FUNC("obs_sceneitem_group_enum_items", sceneitem_group_enum_items), + DEF_FUNC("obs_remove_tick_callback", obs_python_remove_tick_callback), DEF_FUNC("obs_add_tick_callback", obs_python_add_tick_callback), - DEF_FUNC("signal_handler_disconnect", - obs_python_signal_handler_disconnect), - DEF_FUNC("signal_handler_connect", - obs_python_signal_handler_connect), - DEF_FUNC("signal_handler_disconnect_global", - obs_python_signal_handler_disconnect_global), - DEF_FUNC("signal_handler_connect_global", - obs_python_signal_handler_connect_global), + DEF_FUNC("signal_handler_disconnect", obs_python_signal_handler_disconnect), + DEF_FUNC("signal_handler_connect", obs_python_signal_handler_connect), + DEF_FUNC("signal_handler_disconnect_global", obs_python_signal_handler_disconnect_global), + DEF_FUNC("signal_handler_connect_global", obs_python_signal_handler_connect_global), DEF_FUNC("obs_hotkey_unregister", hotkey_unregister), - DEF_FUNC("obs_hotkey_register_frontend", - hotkey_register_frontend), + DEF_FUNC("obs_hotkey_register_frontend", hotkey_register_frontend), DEF_FUNC("obs_properties_add_button", properties_add_button), - DEF_FUNC("obs_property_set_modified_callback", - property_set_modified_callback), + DEF_FUNC("obs_property_set_modified_callback", property_set_modified_callback), DEF_FUNC("remove_current_callback", remove_current_callback), #undef DEF_FUNC @@ -1293,9 +1242,7 @@ bool obs_python_script_load(obs_script_t *s) unlock_python(); if (data->base.loaded) { - blog(LOG_INFO, - "[obs-scripting]: Loaded python script: %s", - data->base.file.array); + blog(LOG_INFO, "[obs-scripting]: Loaded python script: %s", data->base.file.array); obs_python_script_update(s, NULL); } } @@ -1340,8 +1287,7 @@ obs_script_t *obs_python_script_create(const char *path, obs_data_t *settings) add_to_python_path(data->dir.array); data->base.loaded = load_python_script(data); if (data->base.loaded) { - blog(LOG_INFO, "[obs-scripting]: Loaded python script: %s", - data->base.file.array); + blog(LOG_INFO, "[obs-scripting]: Loaded python script: %s", data->base.file.array); cur_python_script = data; obs_python_script_update(&data->base, NULL); cur_python_script = NULL; @@ -1422,8 +1368,7 @@ void obs_python_script_unload(obs_script_t *s) s->loaded = false; - blog(LOG_INFO, "[obs-scripting]: Unloaded python script: %s", - data->base.file.array); + blog(LOG_INFO, "[obs-scripting]: Unloaded python script: %s", data->base.file.array); } void obs_python_script_destroy(obs_script_t *s) @@ -1562,8 +1507,7 @@ static void python_tick(void *param, float seconds) while (data) { cur_python_script = data; - PyObject *py_ret = - PyObject_CallObject(data->tick, args); + PyObject *py_ret = PyObject_CallObject(data->tick, args); Py_XDECREF(py_ret); py_error(); @@ -1625,11 +1569,9 @@ bool obs_scripting_python_runtime_linked(void) void obs_scripting_python_version(char *version, size_t version_length) { #if RUNTIME_LINK - snprintf(version, version_length, "%d.%d", python_version.major, - python_version.minor); + snprintf(version, version_length, "%d.%d", python_version.major, python_version.minor); #else - snprintf(version, version_length, "%d.%d", PY_MAJOR_VERSION, - PY_MINOR_VERSION); + snprintf(version, version_length, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION); #endif } @@ -1665,8 +1607,7 @@ bool obs_scripting_load_python(const char *python_path) if (python_path && *python_path) { #ifdef __APPLE__ char temp[PATH_MAX]; - snprintf(temp, sizeof(temp), - "%s/Python.framework/Versions/Current", python_path); + snprintf(temp, sizeof(temp), "%s/Python.framework/Versions/Current", python_path); os_utf8_to_wcs(temp, 0, home_path, PATH_MAX); Py_SetPythonHome(home_path); #else @@ -1750,8 +1691,7 @@ bool obs_scripting_load_python(const char *python_path) } dstr_free(&resource_path); #else - char *relative_script_path = - os_get_executable_path_ptr("../" SCRIPT_DIR); + char *relative_script_path = os_get_executable_path_ptr("../" SCRIPT_DIR); if (relative_script_path) { add_to_python_path(relative_script_path); } diff --git a/shared/obs-scripting/obs-scripting-python.h b/shared/obs-scripting/obs-scripting-python.h index 93ff2a150..2d754dc76 100644 --- a/shared/obs-scripting/obs-scripting-python.h +++ b/shared/obs-scripting/obs-scripting-python.h @@ -52,8 +52,7 @@ #include #include -#define do_log(level, format, ...) \ - blog(level, "[Python] " format, ##__VA_ARGS__) +#define do_log(level, format, ...) blog(level, "[Python] " format, ##__VA_ARGS__) #define warn(format, ...) do_log(LOG_WARNING, format, ##__VA_ARGS__) #define info(format, ...) do_log(LOG_INFO, format, ##__VA_ARGS__) @@ -90,43 +89,36 @@ struct python_obs_callback { PyObject *func; }; -static inline struct python_obs_callback * -add_python_obs_callback_extra(struct obs_python_script *script, PyObject *func, - size_t extra_size) +static inline struct python_obs_callback *add_python_obs_callback_extra(struct obs_python_script *script, + PyObject *func, size_t extra_size) { - struct python_obs_callback *cb = add_script_callback( - &script->first_callback, (obs_script_t *)script, - sizeof(*cb) + extra_size); + struct python_obs_callback *cb = + add_script_callback(&script->first_callback, (obs_script_t *)script, sizeof(*cb) + extra_size); Py_XINCREF(func); cb->func = func; return cb; } -static inline struct python_obs_callback * -add_python_obs_callback(struct obs_python_script *script, PyObject *func) +static inline struct python_obs_callback *add_python_obs_callback(struct obs_python_script *script, PyObject *func) { return add_python_obs_callback_extra(script, func, 0); } -static inline void * -python_obs_callback_extra_data(struct python_obs_callback *cb) +static inline void *python_obs_callback_extra_data(struct python_obs_callback *cb) { return (void *)&cb[1]; } -static inline struct obs_python_script * -python_obs_callback_script(struct python_obs_callback *cb) +static inline struct obs_python_script *python_obs_callback_script(struct python_obs_callback *cb) { return (struct obs_python_script *)cb->base.script; } -static inline struct python_obs_callback * -find_next_python_obs_callback(struct obs_python_script *script, - struct python_obs_callback *cb, PyObject *func) +static inline struct python_obs_callback *find_next_python_obs_callback(struct obs_python_script *script, + struct python_obs_callback *cb, PyObject *func) { - cb = cb ? (struct python_obs_callback *)cb->base.next - : (struct python_obs_callback *)script->first_callback; + cb = cb ? (struct python_obs_callback *)cb->base.next : (struct python_obs_callback *)script->first_callback; while (cb) { if (cb->func == func) @@ -137,8 +129,7 @@ find_next_python_obs_callback(struct obs_python_script *script, return cb; } -static inline struct python_obs_callback * -find_python_obs_callback(struct obs_python_script *script, PyObject *func) +static inline struct python_obs_callback *find_python_obs_callback(struct obs_python_script *script, PyObject *func) { return find_next_python_obs_callback(script, NULL, func); } @@ -163,8 +154,7 @@ static inline void free_python_obs_callback(struct python_obs_callback *cb) /* ------------------------------------------------------------ */ -static int parse_args_(PyObject *args, const char *func, const char *format, - ...) +static int parse_args_(PyObject *args, const char *func, const char *format, ...) { char new_format[128]; va_list va_args; @@ -179,8 +169,7 @@ static int parse_args_(PyObject *args, const char *func, const char *format, return ret; } -#define parse_args(args, format, ...) \ - parse_args_(args, __FUNCTION__, format, ##__VA_ARGS__) +#define parse_args(args, format, ...) parse_args_(args, __FUNCTION__, format, ##__VA_ARGS__) static inline bool py_error_(const char *func, int line) { @@ -208,19 +197,17 @@ extern struct obs_python_script *cur_python_script; extern void py_to_obs_source_info(py_source_t *py_info); extern PyObject *py_obs_register_source(PyObject *self, PyObject *args); extern PyObject *py_obs_get_script_config_path(PyObject *self, PyObject *args); -extern void add_functions_to_py_module(PyObject *module, - PyMethodDef *method_list); +extern void add_functions_to_py_module(PyObject *module, PyMethodDef *method_list); /* ------------------------------------------------------------ */ /* Warning: the following functions expect python to be locked! */ -extern bool py_to_libobs_(const char *type, PyObject *py_in, void *libobs_out, - const char *id, const char *func, int line); - -extern bool libobs_to_py_(const char *type, void *libobs_in, bool ownership, - PyObject **py_out, const char *id, const char *func, +extern bool py_to_libobs_(const char *type, PyObject *py_in, void *libobs_out, const char *id, const char *func, int line); +extern bool libobs_to_py_(const char *type, void *libobs_in, bool ownership, PyObject **py_out, const char *id, + const char *func, int line); + extern bool py_call(PyObject *call, PyObject **ret, const char *arg_def, ...); extern bool py_import_script(const char *name); diff --git a/shared/obs-scripting/obs-scripting.c b/shared/obs-scripting/obs-scripting.c index 541116c67..2e67cfe9c 100644 --- a/shared/obs-scripting/obs-scripting.c +++ b/shared/obs-scripting/obs-scripting.c @@ -25,8 +25,7 @@ #include "obs-scripting-callback.h" #if defined(LUAJIT_FOUND) -extern obs_script_t *obs_lua_script_create(const char *path, - obs_data_t *settings); +extern obs_script_t *obs_lua_script_create(const char *path, obs_data_t *settings); extern bool obs_lua_script_load(obs_script_t *s); extern void obs_lua_script_unload(obs_script_t *s); extern void obs_lua_script_destroy(obs_script_t *s); @@ -39,8 +38,7 @@ extern void obs_lua_script_save(obs_script_t *script); #endif #if defined(Python_FOUND) -extern obs_script_t *obs_python_script_create(const char *path, - obs_data_t *settings); +extern obs_script_t *obs_python_script_create(const char *path, obs_data_t *settings); extern bool obs_python_script_load(obs_script_t *s); extern void obs_python_script_unload(obs_script_t *s); extern void obs_python_script_destroy(obs_script_t *s); @@ -48,8 +46,7 @@ extern void obs_python_load(void); extern void obs_python_unload(void); extern obs_properties_t *obs_python_script_get_properties(obs_script_t *script); -extern void obs_python_script_update(obs_script_t *script, - obs_data_t *settings); +extern void obs_python_script_update(obs_script_t *script, obs_data_t *settings); extern void obs_python_script_save(obs_script_t *script); #endif @@ -150,9 +147,7 @@ bool obs_scripting_load(void) #if defined(Python_FOUND) obs_python_load(); -#if !defined(_WIN32) && \ - !defined( \ - __APPLE__) /* Win32 and macOS need user-provided Python library paths */ +#if !defined(_WIN32) && !defined(__APPLE__) /* Win32 and macOS need user-provided Python library paths */ obs_scripting_load_python(NULL); #endif #endif @@ -196,8 +191,7 @@ void obs_scripting_unload(void) pthread_mutex_unlock(&detach_mutex); pthread_mutex_destroy(&detach_mutex); - blog(LOG_INFO, "[Scripting] Total detached callbacks: %d", - total_detached); + blog(LOG_INFO, "[Scripting] Total detached callbacks: %d", total_detached); /* ---------------------- */ @@ -224,8 +218,7 @@ const char **obs_scripting_supported_formats(void) return supported_formats; } -static inline bool pointer_valid(const void *x, const char *name, - const char *func) +static inline bool pointer_valid(const void *x, const char *name, const char *func) { if (!x) { blog(LOG_WARNING, "obs-scripting: [%s] %s is null", func, name); diff --git a/shared/obs-scripting/obs-scripting.h b/shared/obs-scripting/obs-scripting.h index 5a691c103..bf346bf79 100644 --- a/shared/obs-scripting/obs-scripting.h +++ b/shared/obs-scripting/obs-scripting.h @@ -29,21 +29,15 @@ extern "C" { struct obs_script; typedef struct obs_script obs_script_t; -enum obs_script_lang { - OBS_SCRIPT_LANG_UNKNOWN, - OBS_SCRIPT_LANG_LUA, - OBS_SCRIPT_LANG_PYTHON -}; +enum obs_script_lang { OBS_SCRIPT_LANG_UNKNOWN, OBS_SCRIPT_LANG_LUA, OBS_SCRIPT_LANG_PYTHON }; EXPORT bool obs_scripting_load(void); EXPORT void obs_scripting_unload(void); EXPORT const char **obs_scripting_supported_formats(void); -typedef void (*scripting_log_handler_t)(void *p, obs_script_t *script, int lvl, - const char *msg); +typedef void (*scripting_log_handler_t)(void *p, obs_script_t *script, int lvl, const char *msg); -EXPORT void obs_scripting_set_log_callback(scripting_log_handler_t handler, - void *param); +EXPORT void obs_scripting_set_log_callback(scripting_log_handler_t handler, void *param); EXPORT bool obs_scripting_python_runtime_linked(void); EXPORT void obs_scripting_python_version(char *version, size_t version_length); diff --git a/shared/obs-shared-memory-queue/shared-memory-queue.c b/shared/obs-shared-memory-queue/shared-memory-queue.c index f1cdbf7ae..2a6b6cbe7 100644 --- a/shared/obs-shared-memory-queue/shared-memory-queue.c +++ b/shared/obs-shared-memory-queue/shared-memory-queue.c @@ -82,14 +82,12 @@ video_queue_t *video_queue_create(uint32_t cx, uint32_t cy, uint64_t interval) return NULL; } - vq.handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, - PAGE_READWRITE, 0, size, VIDEO_NAME); + vq.handle = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, size, VIDEO_NAME); if (!vq.handle) { return NULL; } - vq.header = (struct queue_header *)MapViewOfFile( - vq.handle, FILE_MAP_ALL_ACCESS, 0, 0, 0); + vq.header = (struct queue_header *)MapViewOfFile(vq.handle, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (!vq.header) { CloseHandle(vq.handle); return NULL; @@ -119,8 +117,7 @@ video_queue_t *video_queue_open() return NULL; } - vq.header = (struct queue_header *)MapViewOfFile( - vq.handle, FILE_MAP_READ, 0, 0, 0); + vq.header = (struct queue_header *)MapViewOfFile(vq.handle, FILE_MAP_READ, 0, 0, 0); if (!vq.header) { CloseHandle(vq.handle); return NULL; @@ -149,8 +146,7 @@ void video_queue_close(video_queue_t *vq) free(vq); } -void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, - uint64_t *interval) +void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, uint64_t *interval) { struct queue_header *qh = vq->header; *cx = qh->cx; @@ -160,8 +156,7 @@ void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, #define get_idx(inc) ((unsigned long)inc % 3) -void video_queue_write(video_queue_t *vq, uint8_t **data, uint32_t *linesize, - uint64_t timestamp) +void video_queue_write(video_queue_t *vq, uint8_t **data, uint32_t *linesize, uint64_t timestamp) { struct queue_header *qh = vq->header; long inc = ++qh->write_idx; @@ -188,8 +183,7 @@ enum queue_state video_queue_state(video_queue_t *vq) for (size_t i = 0; i < 3; i++) { size_t off = vq->header->offsets[i]; vq->ts[i] = (uint64_t *)(((uint8_t *)vq->header) + off); - vq->frame[i] = ((uint8_t *)vq->header) + off + - FRAME_HEADER_SIZE; + vq->frame[i] = ((uint8_t *)vq->header) + off + FRAME_HEADER_SIZE; } vq->ready_to_read = true; } @@ -197,8 +191,7 @@ enum queue_state video_queue_state(video_queue_t *vq) return state; } -bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, - uint64_t *ts) +bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, uint64_t *ts) { struct queue_header *qh = vq->header; long inc = qh->read_idx; diff --git a/shared/obs-shared-memory-queue/shared-memory-queue.h b/shared/obs-shared-memory-queue/shared-memory-queue.h index 5e6435299..a1f1a0778 100644 --- a/shared/obs-shared-memory-queue/shared-memory-queue.h +++ b/shared/obs-shared-memory-queue/shared-memory-queue.h @@ -19,18 +19,14 @@ enum queue_state { SHARED_QUEUE_STATE_STOPPING, }; -extern video_queue_t *video_queue_create(uint32_t cx, uint32_t cy, - uint64_t interval); +extern video_queue_t *video_queue_create(uint32_t cx, uint32_t cy, uint64_t interval); extern video_queue_t *video_queue_open(); extern void video_queue_close(video_queue_t *vq); -extern void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, - uint64_t *interval); -extern void video_queue_write(video_queue_t *vq, uint8_t **data, - uint32_t *linesize, uint64_t timestamp); +extern void video_queue_get_info(video_queue_t *vq, uint32_t *cx, uint32_t *cy, uint64_t *interval); +extern void video_queue_write(video_queue_t *vq, uint8_t **data, uint32_t *linesize, uint64_t timestamp); extern enum queue_state video_queue_state(video_queue_t *vq); -extern bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, - uint64_t *ts); +extern bool video_queue_read(video_queue_t *vq, nv12_scale_t *scale, void *dst, uint64_t *ts); #ifdef __cplusplus } diff --git a/shared/obs-tiny-nv12-scale/tiny-nv12-scale.c b/shared/obs-tiny-nv12-scale/tiny-nv12-scale.c index 697267b09..503f2a273 100644 --- a/shared/obs-tiny-nv12-scale/tiny-nv12-scale.c +++ b/shared/obs-tiny-nv12-scale/tiny-nv12-scale.c @@ -6,8 +6,7 @@ * it's nearest neighbor so not really a huge deal. at the very least it * should be sse2 at some point. */ -void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, - int dst_cy, int src_cx, int src_cy) +void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, int dst_cy, int src_cx, int src_cy) { s->format = format; @@ -18,8 +17,7 @@ void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, s->dst_cy = dst_cy; } -static void nv12_scale_nearest(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src) +static void nv12_scale_nearest(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src) { register uint8_t *dst = dst_start; const int src_cx = s->src_cx; @@ -57,8 +55,7 @@ static void nv12_scale_nearest(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_scale_nearest_to_i420(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src) +static void nv12_scale_nearest_to_i420(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src) { register uint8_t *dst = dst_start; const int src_cx = s->src_cx; @@ -99,8 +96,7 @@ static void nv12_scale_nearest_to_i420(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_convert_to_i420(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src_start) +static void nv12_convert_to_i420(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src_start) { const int size = s->src_cx * s->src_cy; const int size_d4 = size / 4; @@ -118,8 +114,7 @@ static void nv12_convert_to_i420(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src) +static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src) { register uint8_t *dst = dst_start; const int src_cx = s->src_cx; @@ -138,8 +133,7 @@ static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, for (int y = 0; y < dst_cy; y++) { const int src_line = y * src_cy / dst_cy * s->src_cx; - const int src_line_d2 = - y / 2 * src_cy_d2 / dst_cy_d2 * s->src_cx; + const int src_line_d2 = y / 2 * src_cy_d2 / dst_cy_d2 * s->src_cx; for (int x = 0; x < dst_cx; x++) { const int src_x = x * src_cx / dst_cx; @@ -155,8 +149,7 @@ static void nv12_scale_nearest_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, } } -static void nv12_convert_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, - const uint8_t *src_start) +static void nv12_convert_to_yuy2(nv12_scale_t *s, uint8_t *dst_start, const uint8_t *src_start) { const int size = s->src_cx * s->src_cy; const int size_dst_line = s->src_cx * 2; diff --git a/shared/obs-tiny-nv12-scale/tiny-nv12-scale.h b/shared/obs-tiny-nv12-scale/tiny-nv12-scale.h index fb8bc580a..5b3f48ede 100644 --- a/shared/obs-tiny-nv12-scale/tiny-nv12-scale.h +++ b/shared/obs-tiny-nv12-scale/tiny-nv12-scale.h @@ -25,8 +25,7 @@ struct nv12_scale { typedef struct nv12_scale nv12_scale_t; -extern void nv12_scale_init(nv12_scale_t *s, enum target_format format, - int dst_cx, int dst_cy, int src_cx, int src_cy); +extern void nv12_scale_init(nv12_scale_t *s, enum target_format format, int dst_cx, int dst_cy, int src_cx, int src_cy); extern void nv12_do_scale(nv12_scale_t *s, uint8_t *dst, const uint8_t *src); #ifdef __cplusplus diff --git a/shared/opts-parser/opts-parser.c b/shared/opts-parser/opts-parser.c index 5183fdcd5..b9d3c4d55 100644 --- a/shared/opts-parser/opts-parser.c +++ b/shared/opts-parser/opts-parser.c @@ -34,15 +34,12 @@ struct obs_options obs_parse_options(const char *options_string) size_t input_option_count = 0; for (char **input_word = input_words; *input_word; ++input_word) input_option_count += 1; - char **ignored_words = - bmalloc(input_option_count * sizeof(*ignored_words)); + char **ignored_words = bmalloc(input_option_count * sizeof(*ignored_words)); char **ignored_word = ignored_words; - struct obs_option *out_options = - bmalloc(input_option_count * sizeof(*out_options)); + struct obs_option *out_options = bmalloc(input_option_count * sizeof(*out_options)); struct obs_option *out_option = out_options; for (char **input_word = input_words; *input_word; ++input_word) { - if (getparam(*input_word, &out_option->name, - (const char **)&out_option->value)) { + if (getparam(*input_word, &out_option->name, (const char **)&out_option->value)) { ++out_option; } else { *ignored_word = *input_word; diff --git a/shared/properties-view/double-slider.cpp b/shared/properties-view/double-slider.cpp index 8996de12c..bd287e50b 100644 --- a/shared/properties-view/double-slider.cpp +++ b/shared/properties-view/double-slider.cpp @@ -4,13 +4,11 @@ DoubleSlider::DoubleSlider(QWidget *parent) : SliderIgnoreScroll(parent) { - connect(this, &DoubleSlider::valueChanged, [this](int val) { - emit doubleValChanged((minVal / minStep + val) * minStep); - }); + connect(this, &DoubleSlider::valueChanged, + [this](int val) { emit doubleValChanged((minVal / minStep + val) * minStep); }); } -void DoubleSlider::setDoubleConstraints(double newMin, double newMax, - double newStep, double val) +void DoubleSlider::setDoubleConstraints(double newMin, double newMax, double newStep, double val) { minVal = newMin; maxVal = newMax; diff --git a/shared/properties-view/double-slider.hpp b/shared/properties-view/double-slider.hpp index 8274506d0..6a6f5c3d5 100644 --- a/shared/properties-view/double-slider.hpp +++ b/shared/properties-view/double-slider.hpp @@ -11,8 +11,7 @@ class DoubleSlider : public SliderIgnoreScroll { public: DoubleSlider(QWidget *parent = nullptr); - void setDoubleConstraints(double newMin, double newMax, double newStep, - double val); + void setDoubleConstraints(double newMin, double newMax, double newStep, double val); signals: void doubleValChanged(double val); diff --git a/shared/properties-view/properties-view.cpp b/shared/properties-view/properties-view.cpp index ba3af5f28..54c14ce75 100644 --- a/shared/properties-view/properties-view.cpp +++ b/shared/properties-view/properties-view.cpp @@ -46,8 +46,7 @@ using namespace std; static inline QColor color_from_int(long long val) { - return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, - (val >> 24) & 0xff); + return QColor(val & 0xff, (val >> 8) & 0xff, (val >> 16) & 0xff, (val >> 24) & 0xff); } static inline long long color_to_int(QColor color) @@ -56,8 +55,7 @@ static inline long long color_to_int(QColor color) return ((val & 0xff) << shift); }; - return shift(color.red(), 0) | shift(color.green(), 8) | - shift(color.blue(), 16) | shift(color.alpha(), 24); + return shift(color.red(), 0) | shift(color.green(), 8) | shift(color.blue(), 16) | shift(color.alpha(), 24); } namespace { @@ -126,8 +124,7 @@ void OBSPropertiesView::RefreshProperties() layout->setFieldGrowthPolicy(QFormLayout::AllNonFixedFieldsGrow); widget->setLayout(layout); - QSizePolicy mainPolicy(QSizePolicy::MinimumExpanding, - QSizePolicy::MinimumExpanding); + QSizePolicy mainPolicy(QSizePolicy::MinimumExpanding, QSizePolicy::MinimumExpanding); layout->setLabelAlignment(Qt::AlignRight); @@ -194,10 +191,8 @@ void OBSPropertiesView::GetScrollPos(int &h, int &v, int &hend, int &vend) } } -OBSPropertiesView::OBSPropertiesView(OBSData settings_, obs_object_t *obj, - PropertiesReloadCallback reloadCallback, - PropertiesUpdateCallback callback_, - PropertiesVisualUpdateCb visUpdateCb_, +OBSPropertiesView::OBSPropertiesView(OBSData settings_, obs_object_t *obj, PropertiesReloadCallback reloadCallback, + PropertiesUpdateCallback callback_, PropertiesVisualUpdateCb visUpdateCb_, int minSize_) : VScrollArea(nullptr), properties(nullptr, obs_properties_destroy), @@ -209,14 +204,11 @@ OBSPropertiesView::OBSPropertiesView(OBSData settings_, obs_object_t *obj, minSize(minSize_) { setFrameShape(QFrame::NoFrame); - QMetaObject::invokeMethod(this, "ReloadProperties", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "ReloadProperties", Qt::QueuedConnection); } -OBSPropertiesView::OBSPropertiesView(OBSData settings_, void *obj, - PropertiesReloadCallback reloadCallback, - PropertiesUpdateCallback callback_, - PropertiesVisualUpdateCb visUpdateCb_, +OBSPropertiesView::OBSPropertiesView(OBSData settings_, void *obj, PropertiesReloadCallback reloadCallback, + PropertiesUpdateCallback callback_, PropertiesVisualUpdateCb visUpdateCb_, int minSize_) : VScrollArea(nullptr), properties(nullptr, obs_properties_destroy), @@ -228,12 +220,10 @@ OBSPropertiesView::OBSPropertiesView(OBSData settings_, void *obj, minSize(minSize_) { setFrameShape(QFrame::NoFrame); - QMetaObject::invokeMethod(this, "ReloadProperties", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "ReloadProperties", Qt::QueuedConnection); } -OBSPropertiesView::OBSPropertiesView(OBSData settings_, const char *type_, - PropertiesReloadCallback reloadCallback_, +OBSPropertiesView::OBSPropertiesView(OBSData settings_, const char *type_, PropertiesReloadCallback reloadCallback_, int minSize_) : VScrollArea(nullptr), properties(nullptr, obs_properties_destroy), @@ -243,8 +233,7 @@ OBSPropertiesView::OBSPropertiesView(OBSData settings_, const char *type_, minSize(minSize_) { setFrameShape(QFrame::NoFrame); - QMetaObject::invokeMethod(this, "ReloadProperties", - Qt::QueuedConnection); + QMetaObject::invokeMethod(this, "ReloadProperties", Qt::QueuedConnection); } void OBSPropertiesView::SetDisabled(bool disabled) @@ -261,8 +250,7 @@ void OBSPropertiesView::resizeEvent(QResizeEvent *event) } template -QWidget *OBSPropertiesView::NewWidget(obs_property_t *prop, Sender *widget, - void (SenderParent::*signal)(Args...)) +QWidget *OBSPropertiesView::NewWidget(obs_property_t *prop, Sender *widget, void (SenderParent::*signal)(Args...)) { const char *long_desc = obs_property_long_description(prop); @@ -285,8 +273,7 @@ QWidget *OBSPropertiesView::AddCheckbox(obs_property_t *prop) checkbox->setCheckState(val ? Qt::Checked : Qt::Unchecked); #if QT_VERSION >= QT_VERSION_CHECK(6, 7, 0) - QWidget *widget = - NewWidget(prop, checkbox, &QCheckBox::checkStateChanged); + QWidget *widget = NewWidget(prop, checkbox, &QCheckBox::checkStateChanged); #else QWidget *widget = NewWidget(prop, checkbox, &QCheckBox::stateChanged); #endif @@ -295,9 +282,7 @@ QWidget *OBSPropertiesView::AddCheckbox(obs_property_t *prop) return widget; } - QString file = !obs_frontend_is_theme_dark() - ? ":/res/images/help.svg" - : ":/res/images/help_light.svg"; + QString file = !obs_frontend_is_theme_dark() ? ":/res/images/help.svg" : ":/res/images/help_light.svg"; IconLabel *help = new IconLabel(checkbox); help->setIcon(QIcon(file)); @@ -320,8 +305,7 @@ QWidget *OBSPropertiesView::AddCheckbox(obs_property_t *prop) return widget; } -QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, - QLabel *&label) +QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, QLabel *&label) { const char *name = obs_property_name(prop); const char *val = obs_data_get_string(settings, name); @@ -348,11 +332,9 @@ QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, subLayout->addWidget(show); WidgetInfo *info = new WidgetInfo(this, prop, edit); - connect(show, &QAbstractButton::toggled, info, - &WidgetInfo::TogglePasswordText); - connect(show, &QAbstractButton::toggled, [=](bool hide) { - show->setText(hide ? tr("Hide") : tr("Show")); - }); + connect(show, &QAbstractButton::toggled, info, &WidgetInfo::TogglePasswordText); + connect(show, &QAbstractButton::toggled, + [=](bool hide) { show->setText(hide ? tr("Hide") : tr("Show")); }); children.emplace_back(info); label = new QLabel(QT_UTF8(obs_property_description(prop))); @@ -360,14 +342,12 @@ QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, edit->setToolTip(QT_UTF8(obs_property_long_description(prop))); - connect(edit, &QLineEdit::textEdited, info, - &WidgetInfo::ControlChanged); + connect(edit, &QLineEdit::textEdited, info, &WidgetInfo::ControlChanged); return nullptr; } else if (type == OBS_TEXT_INFO) { QString desc = QT_UTF8(obs_property_description(prop)); const char *long_desc = obs_property_long_description(prop); - obs_text_info_type info_type = - obs_property_text_info_type(prop); + obs_text_info_type info_type = obs_property_text_info_type(prop); QLabel *info_label = new QLabel(QT_UTF8(val)); @@ -378,9 +358,8 @@ QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, label = new QLabel(desc); if (long_desc != NULL && !info_label->text().isEmpty()) { - QString file = !obs_frontend_is_theme_dark() - ? ":/res/images/help.svg" - : ":/res/images/help_light.svg"; + QString file = !obs_frontend_is_theme_dark() ? ":/res/images/help.svg" + : ":/res/images/help_light.svg"; QString lStr = "%1 "; @@ -417,8 +396,7 @@ QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, return NewWidget(prop, edit, &QLineEdit::textEdited); } -void OBSPropertiesView::AddPath(obs_property_t *prop, QFormLayout *layout, - QLabel **label) +void OBSPropertiesView::AddPath(obs_property_t *prop, QFormLayout *layout, QLabel **label) { const char *name = obs_property_name(prop); const char *val = obs_data_get_string(settings, name); @@ -439,16 +417,14 @@ void OBSPropertiesView::AddPath(obs_property_t *prop, QFormLayout *layout, subLayout->addWidget(button); WidgetInfo *info = new WidgetInfo(this, prop, edit); - connect(button, &QPushButton::clicked, info, - &WidgetInfo::ControlChanged); + connect(button, &QPushButton::clicked, info, &WidgetInfo::ControlChanged); children.emplace_back(info); *label = new QLabel(QT_UTF8(obs_property_description(prop))); layout->addRow(*label, subLayout); } -void OBSPropertiesView::AddInt(obs_property_t *prop, QFormLayout *layout, - QLabel **label) +void OBSPropertiesView::AddInt(obs_property_t *prop, QFormLayout *layout, QLabel **label) { obs_number_type type = obs_property_int_type(prop); QLayout *subLayout = new QHBoxLayout(); @@ -484,14 +460,11 @@ void OBSPropertiesView::AddInt(obs_property_t *prop, QFormLayout *layout, slider->setEnabled(obs_property_enabled(prop)); subLayout->addWidget(slider); - connect(slider, &QSlider::valueChanged, spin, - &QSpinBox::setValue); - connect(spin, &QSpinBox::valueChanged, slider, - &QSlider::setValue); + connect(slider, &QSlider::valueChanged, spin, &QSpinBox::setValue); + connect(spin, &QSpinBox::valueChanged, slider, &QSlider::setValue); } - connect(spin, &QSpinBox::valueChanged, info, - &WidgetInfo::ControlChanged); + connect(spin, &QSpinBox::valueChanged, info, &WidgetInfo::ControlChanged); subLayout->addWidget(spin); @@ -499,8 +472,7 @@ void OBSPropertiesView::AddInt(obs_property_t *prop, QFormLayout *layout, layout->addRow(*label, subLayout); } -void OBSPropertiesView::AddFloat(obs_property_t *prop, QFormLayout *layout, - QLabel **label) +void OBSPropertiesView::AddFloat(obs_property_t *prop, QFormLayout *layout, QLabel **label) { obs_number_type type = obs_property_float_type(prop); QLayout *subLayout = new QHBoxLayout(); @@ -519,8 +491,7 @@ void OBSPropertiesView::AddFloat(obs_property_t *prop, QFormLayout *layout, if (stepVal < 1.0) { constexpr int sane_limit = 8; - const int decimals = - std::min(log10(1.0 / stepVal) + 0.99, sane_limit); + const int decimals = std::min(log10(1.0 / stepVal) + 0.99, sane_limit); if (decimals > spin->decimals()) spin->setDecimals(decimals); } @@ -541,14 +512,11 @@ void OBSPropertiesView::AddFloat(obs_property_t *prop, QFormLayout *layout, slider->setOrientation(Qt::Horizontal); subLayout->addWidget(slider); - connect(slider, &DoubleSlider::doubleValChanged, spin, - &QDoubleSpinBox::setValue); - connect(spin, &QDoubleSpinBox::valueChanged, slider, - &DoubleSlider::setDoubleVal); + connect(slider, &DoubleSlider::doubleValChanged, spin, &QDoubleSpinBox::setValue); + connect(spin, &QDoubleSpinBox::valueChanged, slider, &DoubleSlider::setDoubleVal); } - connect(spin, &QDoubleSpinBox::valueChanged, info, - &WidgetInfo::ControlChanged); + connect(spin, &QDoubleSpinBox::valueChanged, info, &WidgetInfo::ControlChanged); subLayout->addWidget(spin); @@ -590,8 +558,7 @@ static void AddComboItem(QComboBox *combo, obs_property_t *prop, size_t idx) if (index < 0) return; - QStandardItemModel *model = - dynamic_cast(combo->model()); + QStandardItemModel *model = dynamic_cast(combo->model()); if (!model) return; @@ -599,8 +566,8 @@ static void AddComboItem(QComboBox *combo, obs_property_t *prop, size_t idx) item->setFlags(Qt::NoItemFlags); } -static void AddRadioItem(QButtonGroup *buttonGroup, QFormLayout *layout, - obs_property_t *prop, QVariant value, size_t idx) +static void AddRadioItem(QButtonGroup *buttonGroup, QFormLayout *layout, obs_property_t *prop, QVariant value, + size_t idx) { const char *name = obs_property_list_item_name(prop, idx); @@ -612,12 +579,9 @@ static void AddRadioItem(QButtonGroup *buttonGroup, QFormLayout *layout, layout->addRow(button); } -template -static QVariant from_obs_data(obs_data_t *data, const char *name, - obs_combo_format format) +template +static QVariant from_obs_data(obs_data_t *data, const char *name, obs_combo_format format) { switch (format) { case OBS_COMBO_FORMAT_INT: @@ -633,21 +597,16 @@ static QVariant from_obs_data(obs_data_t *data, const char *name, } } -static QVariant from_obs_data(obs_data_t *data, const char *name, - obs_combo_format format) +static QVariant from_obs_data(obs_data_t *data, const char *name, obs_combo_format format) { - return from_obs_data(data, name, - format); + return from_obs_data(data, name, + format); } -static QVariant from_obs_data_autoselect(obs_data_t *data, const char *name, - obs_combo_format format) +static QVariant from_obs_data_autoselect(obs_data_t *data, const char *name, obs_combo_format format) { - return from_obs_data< - obs_data_get_autoselect_int, obs_data_get_autoselect_double, - obs_data_get_autoselect_string, obs_data_get_autoselect_bool>( - data, name, format); + return from_obs_data(data, name, format); } QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) @@ -669,11 +628,9 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) if (count > 0) { buttonGroup->setExclusive(true); - WidgetInfo *info = new WidgetInfo( - this, prop, buttonGroup->buttons()[0]); + WidgetInfo *info = new WidgetInfo(this, prop, buttonGroup->buttons()[0]); children.emplace_back(info); - connect(buttonGroup, &QButtonGroup::buttonClicked, info, - &WidgetInfo::ControlChanged); + connect(buttonGroup, &QButtonGroup::buttonClicked, info, &WidgetInfo::ControlChanged); } QWidget *widget = new QWidget(); @@ -693,8 +650,7 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) combo->setMaxVisibleItems(40); combo->setToolTip(QT_UTF8(obs_property_long_description(prop))); - if (format == OBS_COMBO_FORMAT_STRING && - type == OBS_COMBO_TYPE_EDITABLE) { + if (format == OBS_COMBO_FORMAT_STRING && type == OBS_COMBO_TYPE_EDITABLE) { combo->lineEdit()->setText(value.toString()); } else { idx = combo->findData(value); @@ -707,27 +663,22 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) combo->setCurrentIndex(idx); if (obs_data_has_autoselect_value(settings, name)) { - QVariant autoselect = - from_obs_data_autoselect(settings, name, format); + QVariant autoselect = from_obs_data_autoselect(settings, name, format); int id = combo->findData(autoselect); if (id != -1 && id != idx) { QString actual = combo->itemText(id); QString selected = combo->itemText(idx); - QString combined = - tr("Basic.PropertiesWindow.AutoSelectFormat"); - combo->setItemText(idx, - combined.arg(selected).arg(actual)); + QString combined = tr("Basic.PropertiesWindow.AutoSelectFormat"); + combo->setItemText(idx, combined.arg(selected).arg(actual)); } } QAbstractItemModel *model = combo->model(); - warning = idx != -1 && - model->flags(model->index(idx, 0)) == Qt::NoItemFlags; + warning = idx != -1 && model->flags(model->index(idx, 0)) == Qt::NoItemFlags; WidgetInfo *info = new WidgetInfo(this, prop, combo); - connect(combo, &QComboBox::currentIndexChanged, info, - &WidgetInfo::ControlChanged); + connect(combo, &QComboBox::currentIndexChanged, info, &WidgetInfo::ControlChanged); children.emplace_back(info); /* trigger a settings update if the index was not found */ @@ -737,8 +688,7 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) return combo; } -static void NewButton(QLayout *layout, WidgetInfo *info, const char *themeIcon, - void (WidgetInfo::*method)()) +static void NewButton(QLayout *layout, WidgetInfo *info, const char *themeIcon, void (WidgetInfo::*method)()) { QPushButton *button = new QPushButton(); button->setProperty("class", themeIcon); @@ -750,8 +700,7 @@ static void NewButton(QLayout *layout, WidgetInfo *info, const char *themeIcon, layout->addWidget(button); } -void OBSPropertiesView::AddEditableList(obs_property_t *prop, - QFormLayout *layout, QLabel *&label) +void OBSPropertiesView::AddEditableList(obs_property_t *prop, QFormLayout *layout, QLabel *&label) { const char *name = obs_property_name(prop); OBSDataArrayAutoRelease array = obs_data_get_array(settings, name); @@ -775,8 +724,7 @@ void OBSPropertiesView::AddEditableList(obs_property_t *prop, QString uuid = QT_UTF8(obs_data_get_string(item, "uuid")); /* for backwards compatibility */ if (uuid.isEmpty()) { - uuid = QUuid::createUuid().toString( - QUuid::WithoutBraces); + uuid = QUuid::createUuid().toString(QUuid::WithoutBraces); obs_data_set_string(item, "uuid", uuid.toUtf8()); } list_item->setData(Qt::UserRole, uuid); @@ -785,8 +733,7 @@ void OBSPropertiesView::AddEditableList(obs_property_t *prop, WidgetInfo *info = new WidgetInfo(this, prop, list); list->setDragDropMode(QAbstractItemView::InternalMove); - connect(list->model(), &QAbstractItemModel::rowsMoved, - [info]() { info->EditableListChanged(); }); + connect(list->model(), &QAbstractItemModel::rowsMoved, [info]() { info->EditableListChanged(); }); QVBoxLayout *sideLayout = new QVBoxLayout(); NewButton(sideLayout, info, "icon-plus", &WidgetInfo::EditListAdd); @@ -815,9 +762,7 @@ QWidget *OBSPropertiesView::AddButton(obs_property_t *prop) return NewWidget(prop, button, &QPushButton::clicked); } -void OBSPropertiesView::AddColorInternal(obs_property_t *prop, - QFormLayout *layout, QLabel *&label, - bool supportAlpha) +void OBSPropertiesView::AddColorInternal(obs_property_t *prop, QFormLayout *layout, QLabel *&label, bool supportAlpha) { QPushButton *button = new QPushButton; QLabel *colorLabel = new QLabel; @@ -845,10 +790,9 @@ void OBSPropertiesView::AddColorInternal(obs_property_t *prop, colorLabel->setFrameStyle(QFrame::Sunken | QFrame::Panel); colorLabel->setText(color.name(format)); colorLabel->setPalette(palette); - colorLabel->setStyleSheet( - QString("background-color :%1; color: %2;") - .arg(palette.color(QPalette::Window).name(format)) - .arg(palette.color(QPalette::WindowText).name(format))); + colorLabel->setStyleSheet(QString("background-color :%1; color: %2;") + .arg(palette.color(QPalette::Window).name(format)) + .arg(palette.color(QPalette::WindowText).name(format))); colorLabel->setAutoFillBackground(true); colorLabel->setAlignment(Qt::AlignCenter); colorLabel->setToolTip(QT_UTF8(obs_property_long_description(prop))); @@ -860,22 +804,19 @@ void OBSPropertiesView::AddColorInternal(obs_property_t *prop, subLayout->addWidget(button); WidgetInfo *info = new WidgetInfo(this, prop, colorLabel); - connect(button, &QPushButton::clicked, info, - &WidgetInfo::ControlChanged); + connect(button, &QPushButton::clicked, info, &WidgetInfo::ControlChanged); children.emplace_back(info); label = new QLabel(QT_UTF8(obs_property_description(prop))); layout->addRow(label, subLayout); } -void OBSPropertiesView::AddColor(obs_property_t *prop, QFormLayout *layout, - QLabel *&label) +void OBSPropertiesView::AddColor(obs_property_t *prop, QFormLayout *layout, QLabel *&label) { AddColorInternal(prop, layout, label, false); } -void OBSPropertiesView::AddColorAlpha(obs_property_t *prop, QFormLayout *layout, - QLabel *&label) +void OBSPropertiesView::AddColorAlpha(obs_property_t *prop, QFormLayout *layout, QLabel *&label) { AddColorInternal(prop, layout, label, true); } @@ -913,8 +854,7 @@ void MakeQFont(obs_data_t *font_obj, QFont &font, bool limit = false) font.setStrikeOut(true); } -void OBSPropertiesView::AddFont(obs_property_t *prop, QFormLayout *layout, - QLabel *&label) +void OBSPropertiesView::AddFont(obs_property_t *prop, QFormLayout *layout, QLabel *&label) { const char *name = obs_property_name(prop); OBSDataAutoRelease font_obj = obs_data_get_obj(settings, name); @@ -948,8 +888,7 @@ void OBSPropertiesView::AddFont(obs_property_t *prop, QFormLayout *layout, subLayout->addWidget(button); WidgetInfo *info = new WidgetInfo(this, prop, fontLabel); - connect(button, &QPushButton::clicked, info, - &WidgetInfo::ControlChanged); + connect(button, &QPushButton::clicked, info, &WidgetInfo::ControlChanged); children.emplace_back(info); label = new QLabel(QT_UTF8(obs_property_description(prop))); @@ -973,9 +912,7 @@ template static double make_epsilon(T val) return val * 0.00001; } -static bool matches_range(media_frames_per_second &match, - media_frames_per_second fps, - const frame_rate_range_t &pair) +static bool matches_range(media_frames_per_second &match, media_frames_per_second fps, const frame_rate_range_t &pair) { auto val = media_frames_per_second_to_frame_interval(fps); auto max_ = media_frames_per_second_to_frame_interval(pair.first); @@ -989,10 +926,8 @@ static bool matches_range(media_frames_per_second &match, return false; } -static bool matches_ranges(media_frames_per_second &best_match, - media_frames_per_second fps, - const frame_rate_ranges_t &fps_ranges, - bool exact = false) +static bool matches_ranges(media_frames_per_second &best_match, media_frames_per_second fps, + const frame_rate_ranges_t &fps_ranges, bool exact = false) { auto convert_fn = media_frames_per_second_to_frame_interval; auto val = convert_fn(fps); @@ -1043,17 +978,13 @@ static media_frames_per_second make_fps(uint32_t num, uint32_t den) } static const common_frame_rate common_fps[] = { - {"240", {240, 1}}, {"144", {144, 1}}, - {"120", {120, 1}}, {"119.88", {120000, 1001}}, - {"60", {60, 1}}, {"59.94", {60000, 1001}}, - {"50", {50, 1}}, {"48", {48, 1}}, - {"30", {30, 1}}, {"29.97", {30000, 1001}}, - {"25", {25, 1}}, {"24", {24, 1}}, + {"240", {240, 1}}, {"144", {144, 1}}, {"120", {120, 1}}, {"119.88", {120000, 1001}}, + {"60", {60, 1}}, {"59.94", {60000, 1001}}, {"50", {50, 1}}, {"48", {48, 1}}, + {"30", {30, 1}}, {"29.97", {30000, 1001}}, {"25", {25, 1}}, {"24", {24, 1}}, {"23.976", {24000, 1001}}, }; -static void UpdateSimpleFPSSelection(OBSFrameRatePropertyWidget *fpsProps, - const media_frames_per_second *current_fps) +static void UpdateSimpleFPSSelection(OBSFrameRatePropertyWidget *fpsProps, const media_frames_per_second *current_fps) { if (!current_fps || !media_frames_per_second_is_valid(*current_fps)) { fpsProps->simpleFPS->setCurrentIndex(0); @@ -1078,8 +1009,7 @@ static void UpdateSimpleFPSSelection(OBSFrameRatePropertyWidget *fpsProps, combo->setCurrentIndex(0); } -static void AddFPSRanges(vector &items, - const frame_rate_ranges_t &ranges) +static void AddFPSRanges(vector &items, const frame_rate_ranges_t &ranges) { auto InsertFPS = [&](media_frames_per_second fps) { auto fps_val = media_frames_per_second_to_fps(fps); @@ -1106,9 +1036,8 @@ static void AddFPSRanges(vector &items, } } -static QWidget * -CreateSimpleFPSValues(OBSFrameRatePropertyWidget *fpsProps, bool &selected, - const media_frames_per_second *current_fps) +static QWidget *CreateSimpleFPSValues(OBSFrameRatePropertyWidget *fpsProps, bool &selected, + const media_frames_per_second *current_fps) { auto widget = new QWidget{}; widget->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); @@ -1134,11 +1063,8 @@ CreateSimpleFPSValues(OBSFrameRatePropertyWidget *fpsProps, bool &selected, for (const auto &item : items) { auto var = QVariant::fromValue(item.fps); - auto name = item.fps_name - ? QString(item.fps_name) - : QString("%1").arg( - media_frames_per_second_to_fps( - item.fps)); + auto name = item.fps_name ? QString(item.fps_name) + : QString("%1").arg(media_frames_per_second_to_fps(item.fps)); combo->addItem(name, var); bool select = current_fps && *current_fps == item.fps; @@ -1154,8 +1080,7 @@ CreateSimpleFPSValues(OBSFrameRatePropertyWidget *fpsProps, bool &selected, return widget; } -static void UpdateRationalFPSWidgets(OBSFrameRatePropertyWidget *fpsProps, - const media_frames_per_second *current_fps) +static void UpdateRationalFPSWidgets(OBSFrameRatePropertyWidget *fpsProps, const media_frames_per_second *current_fps) { if (!current_fps || !media_frames_per_second_is_valid(*current_fps)) { fpsProps->numEdit->setValue(0); @@ -1175,8 +1100,7 @@ static void UpdateRationalFPSWidgets(OBSFrameRatePropertyWidget *fpsProps, continue; media_frames_per_second match{}; - if (!matches_range(match, *current_fps, - fpsProps->fps_ranges[idx])) + if (!matches_range(match, *current_fps, fpsProps->fps_ranges[idx])) continue; combo->setCurrentIndex(i); @@ -1187,8 +1111,7 @@ static void UpdateRationalFPSWidgets(OBSFrameRatePropertyWidget *fpsProps, fpsProps->denEdit->setValue(current_fps->denominator); } -static QWidget *CreateRationalFPS(OBSFrameRatePropertyWidget *fpsProps, - bool &selected, +static QWidget *CreateRationalFPS(OBSFrameRatePropertyWidget *fpsProps, bool &selected, const media_frames_per_second *current_fps) { auto widget = new QWidget{}; @@ -1207,9 +1130,7 @@ static QWidget *CreateRationalFPS(OBSFrameRatePropertyWidget *fpsProps, for (size_t i = 0; i < fpsProps->fps_ranges.size(); i++) { auto &pair = fpsProps->fps_ranges[i]; - combo->addItem(QString{"%1 - %2"} - .arg(convert_fps(pair.first)) - .arg(convert_fps(pair.second)), + combo->addItem(QString{"%1 - %2"}.arg(convert_fps(pair.first)).arg(convert_fps(pair.second)), QVariant::fromValue(i)); media_frames_per_second match; @@ -1234,18 +1155,16 @@ static QWidget *CreateRationalFPS(OBSFrameRatePropertyWidget *fpsProps, } layout->addRow(QObject::tr("Basic.Settings.Video.Numerator"), num_edit); - layout->addRow(QObject::tr("Basic.Settings.Video.Denominator"), - den_edit); + layout->addRow(QObject::tr("Basic.Settings.Video.Denominator"), den_edit); widget->setLayout(layout); return widget; } -static OBSFrameRatePropertyWidget * -CreateFrameRateWidget(obs_property_t *prop, bool &warning, const char *option, - media_frames_per_second *current_fps, - frame_rate_ranges_t &fps_ranges) +static OBSFrameRatePropertyWidget *CreateFrameRateWidget(obs_property_t *prop, bool &warning, const char *option, + media_frames_per_second *current_fps, + frame_rate_ranges_t &fps_ranges) { auto widget = new OBSFrameRatePropertyWidget{}; auto hlayout = new QHBoxLayout{}; @@ -1254,8 +1173,7 @@ CreateFrameRateWidget(obs_property_t *prop, bool &warning, const char *option, swap(widget->fps_ranges, fps_ranges); auto combo = widget->modeSelect = new QComboBox(); - combo->addItem(QObject::tr("Basic.PropertiesView.FPS.Simple"), - QVariant::fromValue(frame_rate_tag::simple())); + combo->addItem(QObject::tr("Basic.PropertiesView.FPS.Simple"), QVariant::fromValue(frame_rate_tag::simple())); combo->addItem(QObject::tr("Basic.PropertiesView.FPS.Rational"), QVariant::fromValue(frame_rate_tag::rational())); @@ -1313,15 +1231,13 @@ CreateFrameRateWidget(obs_property_t *prop, bool &warning, const char *option, hlayout->addWidget(stack, 0, Qt::AlignTop); auto label_area = widget->labels = new QWidget{}; - label_area->setSizePolicy(QSizePolicy::Expanding, - QSizePolicy::Expanding); + label_area->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); auto vlayout = new QVBoxLayout{}; vlayout->setContentsMargins(0, 0, 0, 0); auto fps_label = widget->currentFPS = new QLabel{"FPS: 22"}; - auto time_label = widget->timePerFrame = - new QLabel{"Frame Interval: 0.123 ms"}; + auto time_label = widget->timePerFrame = new QLabel{"Frame Interval: 0.123 ms"}; auto min_label = widget->minLabel = new QLabel{"Min FPS: 1/1"}; auto max_label = widget->maxLabel = new QLabel{"Max FPS: 2/1"}; @@ -1353,8 +1269,7 @@ static void UpdateMinMaxLabels(OBSFrameRatePropertyWidget *w) }; auto variant = w->modeSelect->currentData(); - if (!variant.canConvert() || - variant.value().type != frame_rate_tag::RATIONAL) { + if (!variant.canConvert() || variant.value().type != frame_rate_tag::RATIONAL) { Hide(true); return; } @@ -1376,25 +1291,19 @@ static void UpdateMinMaxLabels(OBSFrameRatePropertyWidget *w) auto min = w->fps_ranges[idx].first; auto max = w->fps_ranges[idx].second; - w->minLabel->setText(QString("Min FPS: %1/%2") - .arg(min.numerator) - .arg(min.denominator)); - w->maxLabel->setText(QString("Max FPS: %1/%2") - .arg(max.numerator) - .arg(max.denominator)); + w->minLabel->setText(QString("Min FPS: %1/%2").arg(min.numerator).arg(min.denominator)); + w->maxLabel->setText(QString("Max FPS: %1/%2").arg(max.numerator).arg(max.denominator)); } static void UpdateFPSLabels(OBSFrameRatePropertyWidget *w) { UpdateMinMaxLabels(w); - unique_ptr obj{ - obs_data_item_byname(w->settings, w->name)}; + unique_ptr obj{obs_data_item_byname(w->settings, w->name)}; media_frames_per_second fps{}; media_frames_per_second *valid_fps = nullptr; - if (obs_data_item_get_autoselect_frames_per_second(obj.get(), &fps, - nullptr) || + if (obs_data_item_get_autoselect_frames_per_second(obj.get(), &fps, nullptr) || obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) valid_fps = &fps; @@ -1420,18 +1329,13 @@ static void UpdateFPSLabels(OBSFrameRatePropertyWidget *w) w->warningLabel->setProperty("class", ""); auto convert_to_fps = media_frames_per_second_to_fps; - auto convert_to_frame_interval = - media_frames_per_second_to_frame_interval; + auto convert_to_frame_interval = media_frames_per_second_to_frame_interval; - w->currentFPS->setText( - QString("FPS: %1").arg(convert_to_fps(*valid_fps))); - w->timePerFrame->setText( - QString("Frame Interval: %1 ms") - .arg(convert_to_frame_interval(*valid_fps) * 1000)); + w->currentFPS->setText(QString("FPS: %1").arg(convert_to_fps(*valid_fps))); + w->timePerFrame->setText(QString("Frame Interval: %1 ms").arg(convert_to_frame_interval(*valid_fps) * 1000)); } -void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, - QFormLayout *layout, QLabel *&label) +void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, QFormLayout *layout, QLabel *&label) { const char *name = obs_property_name(prop); bool enabled = obs_property_enabled(prop); @@ -1449,12 +1353,10 @@ void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, size_t num = obs_property_frame_rate_fps_ranges_count(prop); fps_ranges.reserve(num); for (size_t i = 0; i < num; i++) - fps_ranges.emplace_back( - obs_property_frame_rate_fps_range_min(prop, i), - obs_property_frame_rate_fps_range_max(prop, i)); + fps_ranges.emplace_back(obs_property_frame_rate_fps_range_min(prop, i), + obs_property_frame_rate_fps_range_max(prop, i)); - auto widget = CreateFrameRateWidget(prop, warning, option, valid_fps, - fps_ranges); + auto widget = CreateFrameRateWidget(prop, warning, option, valid_fps, fps_ranges); auto info = new WidgetInfo(this, prop, widget); widget->setToolTip(QT_UTF8(obs_property_long_description(prop))); @@ -1468,8 +1370,7 @@ void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, widget->numEdit->setEnabled(enabled); widget->denEdit->setEnabled(enabled); - label = widget->warningLabel = - new QLabel{obs_property_description(prop)}; + label = widget->warningLabel = new QLabel{obs_property_description(prop)}; layout->addRow(label, widget); @@ -1483,8 +1384,7 @@ void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, stack->setToolTip(QT_UTF8(obs_property_long_description(prop))); combo->setToolTip(QT_UTF8(obs_property_long_description(prop))); - auto comboIndexChanged = static_cast( - &QComboBox::currentIndexChanged); + auto comboIndexChanged = static_cast(&QComboBox::currentIndexChanged); connect(combo, comboIndexChanged, stack, [=](int index) { bool out_of_bounds = index >= stack->count(); auto idx = out_of_bounds ? stack->count() - 1 : index; @@ -1511,8 +1411,7 @@ void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, UpdateFPSLabels(widget); }); - auto sbValueChanged = - static_cast(&QSpinBox::valueChanged); + auto sbValueChanged = static_cast(&QSpinBox::valueChanged); connect(widget->numEdit, sbValueChanged, [=](int) { if (widget->updating) return; @@ -1555,20 +1454,17 @@ void OBSPropertiesView::AddGroup(obs_property_t *prop, QFormLayout *layout) } // Insert into UI - layout->setWidget(layout->rowCount(), - QFormLayout::ItemRole::SpanningRole, groupBox); + layout->setWidget(layout->rowCount(), QFormLayout::ItemRole::SpanningRole, groupBox); // Register Group Widget WidgetInfo *info = new WidgetInfo(this, prop, groupBox); children.emplace_back(info); // Signals - connect(groupBox, &QGroupBox::toggled, info, - &WidgetInfo::ControlChanged); + connect(groupBox, &QGroupBox::toggled, info, &WidgetInfo::ControlChanged); } -void OBSPropertiesView::AddProperty(obs_property_t *property, - QFormLayout *layout) +void OBSPropertiesView::AddProperty(obs_property_t *property, QFormLayout *layout) { const char *name = obs_property_name(property); obs_property_type type = obs_property_get_type(property); @@ -1626,8 +1522,7 @@ void OBSPropertiesView::AddProperty(obs_property_t *property, if (!widget && !label) return; - if (!label && type != OBS_PROPERTY_BOOL && - type != OBS_PROPERTY_BUTTON && type != OBS_PROPERTY_GROUP) + if (!label && type != OBS_PROPERTY_BOOL && type != OBS_PROPERTY_BUTTON && type != OBS_PROPERTY_GROUP) label = new QLabel(QT_UTF8(obs_property_description(property))); if (label) { @@ -1651,9 +1546,7 @@ void OBSPropertiesView::AddProperty(obs_property_t *property, QWidget *leftWidget = label; if (obs_property_long_description(property) && label) { - QString file = !obs_frontend_is_theme_dark() - ? ":/res/images/help.svg" - : ":/res/images/help_light.svg"; + QString file = !obs_frontend_is_theme_dark() ? ":/res/images/help.svg" : ":/res/images/help_light.svg"; QWidget *newWidget = new QWidget(); newWidget->setToolTip(obs_property_long_description(property)); @@ -1684,9 +1577,7 @@ void OBSPropertiesView::SignalChanged() emit Changed(); } -static bool FrameRateChangedVariant(const QVariant &variant, - media_frames_per_second &fps, - obs_data_item_t *&obj, +static bool FrameRateChangedVariant(const QVariant &variant, media_frames_per_second &fps, obs_data_item_t *&obj, const media_frames_per_second *valid_fps) { if (!variant.canConvert()) @@ -1700,29 +1591,25 @@ static bool FrameRateChangedVariant(const QVariant &variant, return true; } -static bool FrameRateChangedCommon(OBSFrameRatePropertyWidget *w, - obs_data_item_t *&obj, +static bool FrameRateChangedCommon(OBSFrameRatePropertyWidget *w, obs_data_item_t *&obj, const media_frames_per_second *valid_fps) { media_frames_per_second fps{}; - if (!FrameRateChangedVariant(w->simpleFPS->currentData(), fps, obj, - valid_fps)) + if (!FrameRateChangedVariant(w->simpleFPS->currentData(), fps, obj, valid_fps)) return false; UpdateRationalFPSWidgets(w, &fps); return true; } -static bool FrameRateChangedRational(OBSFrameRatePropertyWidget *w, - obs_data_item_t *&obj, +static bool FrameRateChangedRational(OBSFrameRatePropertyWidget *w, obs_data_item_t *&obj, const media_frames_per_second *valid_fps) { auto num = w->numEdit->value(); auto den = w->denEdit->value(); auto fps = make_fps(num, den); - if (valid_fps && media_frames_per_second_is_valid(fps) && - fps == *valid_fps) + if (valid_fps && media_frames_per_second_is_valid(fps) && fps == *valid_fps) return false; obs_data_item_set_frames_per_second(&obj, fps, nullptr); @@ -1730,8 +1617,7 @@ static bool FrameRateChangedRational(OBSFrameRatePropertyWidget *w, return true; } -static bool FrameRateChanged(QWidget *widget, const char *name, - OBSData &settings) +static bool FrameRateChanged(QWidget *widget, const char *name, OBSData &settings) { auto w = qobject_cast(widget); if (!w) @@ -1744,8 +1630,7 @@ static bool FrameRateChanged(QWidget *widget, const char *name, auto StopUpdating = [&](void *) { w->updating = false; }; - unique_ptr signalGuard( - static_cast(w), StopUpdating); + unique_ptr signalGuard(static_cast(w), StopUpdating); w->updating = true; if (!obs_data_has_user_value(settings, name)) @@ -1794,8 +1679,7 @@ static bool FrameRateChanged(QWidget *widget, const char *name, void WidgetInfo::BoolChanged(const char *setting) { QCheckBox *checkbox = static_cast(widget); - obs_data_set_bool(view->settings, setting, - checkbox->checkState() == Qt::Checked); + obs_data_set_bool(view->settings, setting, checkbox->checkState() == Qt::Checked); } void WidgetInfo::IntChanged(const char *setting) @@ -1815,10 +1699,8 @@ void WidgetInfo::TextChanged(const char *setting) obs_text_type type = obs_property_text_type(property); if (type == OBS_TEXT_MULTILINE) { - OBSPlainTextEdit *edit = - static_cast(widget); - obs_data_set_string(view->settings, setting, - QT_TO_UTF8(edit->toPlainText())); + OBSPlainTextEdit *edit = static_cast(widget); + obs_data_set_string(view->settings, setting, QT_TO_UTF8(edit->toPlainText())); return; } @@ -1868,8 +1750,7 @@ void WidgetInfo::ListChanged(const char *setting) QVariant data; if (type == OBS_COMBO_TYPE_RADIO) { - QButtonGroup *group = - static_cast(widget)->group(); + QButtonGroup *group = static_cast(widget)->group(); QAbstractButton *button = group->checkedButton(); data = button->property("value"); } else if (type == OBS_COMBO_TYPE_EDITABLE) { @@ -1887,20 +1768,16 @@ void WidgetInfo::ListChanged(const char *setting) case OBS_COMBO_FORMAT_INVALID: return; case OBS_COMBO_FORMAT_INT: - obs_data_set_int(view->settings, setting, - data.value()); + obs_data_set_int(view->settings, setting, data.value()); break; case OBS_COMBO_FORMAT_FLOAT: - obs_data_set_double(view->settings, setting, - data.value()); + obs_data_set_double(view->settings, setting, data.value()); break; case OBS_COMBO_FORMAT_STRING: - obs_data_set_string(view->settings, setting, - data.toByteArray().constData()); + obs_data_set_string(view->settings, setting, data.toByteArray().constData()); break; case OBS_COMBO_FORMAT_BOOL: - obs_data_set_bool(view->settings, setting, - data.value()); + obs_data_set_bool(view->settings, setting, data.value()); break; } } @@ -1944,10 +1821,9 @@ bool WidgetInfo::ColorChangedInternal(const char *setting, bool supportAlpha) label->setText(color.name(format)); QPalette palette = QPalette(color); label->setPalette(palette); - label->setStyleSheet( - QString("background-color :%1; color: %2;") - .arg(palette.color(QPalette::Window).name(format)) - .arg(palette.color(QPalette::WindowText).name(format))); + label->setStyleSheet(QString("background-color :%1; color: %2;") + .arg(palette.color(QPalette::Window).name(format)) + .arg(palette.color(QPalette::WindowText).name(format))); obs_data_set_int(view->settings, setting, color_to_int(color)); @@ -1979,16 +1855,12 @@ bool WidgetInfo::FontChanged(const char *setting) if (!font_obj) { QFont initial; - font = QFontDialog::getFont( - &success, initial, view, - tr("Basic.PropertiesWindow.SelectFont.WindowTitle"), - options); + font = QFontDialog::getFont(&success, initial, view, + tr("Basic.PropertiesWindow.SelectFont.WindowTitle"), options); } else { MakeQFont(font_obj, font); - font = QFontDialog::getFont( - &success, font, view, - tr("Basic.PropertiesWindow.SelectFont.WindowTitle"), - options); + font = QFontDialog::getFont(&success, font, view, tr("Basic.PropertiesWindow.SelectFont.WindowTitle"), + options); } if (!success) @@ -2018,9 +1890,7 @@ bool WidgetInfo::FontChanged(const char *setting) void WidgetInfo::GroupChanged(const char *setting) { QGroupBox *groupbox = static_cast(widget); - obs_data_set_bool(view->settings, setting, - groupbox->isCheckable() ? groupbox->isChecked() - : true); + obs_data_set_bool(view->settings, setting, groupbox->isCheckable() ? groupbox->isChecked() : true); } void WidgetInfo::EditableListChanged() @@ -2032,11 +1902,8 @@ void WidgetInfo::EditableListChanged() for (int i = 0; i < list->count(); i++) { QListWidgetItem *item = list->item(i); OBSDataAutoRelease arrayItem = obs_data_create(); - obs_data_set_string(arrayItem, "value", - QT_TO_UTF8(item->text())); - obs_data_set_string( - arrayItem, "uuid", - QT_TO_UTF8(item->data(Qt::UserRole).toString())); + obs_data_set_string(arrayItem, "value", QT_TO_UTF8(item->text())); + obs_data_set_string(arrayItem, "uuid", QT_TO_UTF8(item->data(Qt::UserRole).toString())); obs_data_set_bool(arrayItem, "selected", item->isSelected()); obs_data_set_bool(arrayItem, "hidden", item->isHidden()); obs_data_array_push_back(array, arrayItem); @@ -2054,18 +1921,14 @@ void WidgetInfo::ButtonClicked() if (type == OBS_BUTTON_URL && strcmp(savedUrl, "") != 0) { QUrl url(savedUrl, QUrl::StrictMode); - if (url.isValid() && (url.scheme().compare("http") == 0 || - url.scheme().compare("https") == 0)) { + if (url.isValid() && (url.scheme().compare("http") == 0 || url.scheme().compare("https") == 0)) { QString msg(tr("Basic.PropertiesView.UrlButton.Text")); msg += "\n\n"; - msg += QString(tr("Basic.PropertiesView.UrlButton.Text.Url")) - .arg(savedUrl); + msg += QString(tr("Basic.PropertiesView.UrlButton.Text.Url")).arg(savedUrl); - QMessageBox::StandardButton button = OBSMessageBox::question( - view->window(), - tr("Basic.PropertiesView.UrlButton.OpenUrl"), - msg, QMessageBox::Yes | QMessageBox::No, - QMessageBox::No); + QMessageBox::StandardButton button = + OBSMessageBox::question(view->window(), tr("Basic.PropertiesView.UrlButton.OpenUrl"), + msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::No); if (button == QMessageBox::Yes) QDesktopServices::openUrl(url); @@ -2076,15 +1939,13 @@ void WidgetInfo::ButtonClicked() OBSObject strongObj = view->GetObject(); void *obj = strongObj ? strongObj.Get() : view->rawObj; if (obs_property_button_clicked(property, obj)) { - QMetaObject::invokeMethod(view, "RefreshProperties", - Qt::QueuedConnection); + QMetaObject::invokeMethod(view, "RefreshProperties", Qt::QueuedConnection); } } void WidgetInfo::TogglePasswordText(bool show) { - reinterpret_cast(widget)->setEchoMode( - show ? QLineEdit::Normal : QLineEdit::Password); + reinterpret_cast(widget)->setEchoMode(show ? QLineEdit::Normal : QLineEdit::Password); } void WidgetInfo::ControlChanged() @@ -2149,19 +2010,15 @@ void WidgetInfo::ControlChanged() if (!recently_updated) { recently_updated = true; update_timer = new QTimer; - connect(update_timer, &QTimer::timeout, - [this, &ru = recently_updated]() { - OBSObject strongObj = view->GetObject(); - void *obj = strongObj ? strongObj.Get() - : view->rawObj; - if (obj && view->callback && - !view->deferUpdate) { - view->callback(obj, old_settings_cache, - view->settings); - } + connect(update_timer, &QTimer::timeout, [this, &ru = recently_updated]() { + OBSObject strongObj = view->GetObject(); + void *obj = strongObj ? strongObj.Get() : view->rawObj; + if (obj && view->callback && !view->deferUpdate) { + view->callback(obj, old_settings_cache, view->settings); + } - ru = false; - }); + ru = false; + }); connect(update_timer, &QTimer::timeout, &QTimer::deleteLater); update_timer->setSingleShot(true); } @@ -2184,8 +2041,7 @@ void WidgetInfo::ControlChanged() if (obs_property_modified(property, view->settings)) { view->lastFocused = setting; - QMetaObject::invokeMethod(view, "RefreshProperties", - Qt::QueuedConnection); + QMetaObject::invokeMethod(view, "RefreshProperties", Qt::QueuedConnection); } } @@ -2209,8 +2065,7 @@ class EditableItemDialog : public QDialog { } public: - EditableItemDialog(QWidget *parent, const QString &text, bool browse, - const char *filter_ = nullptr, + EditableItemDialog(QWidget *parent, const QString &text, bool browse, const char *filter_ = nullptr, const char *default_path_ = nullptr) : QDialog(parent), filter(QT_UTF8(filter_)), @@ -2225,17 +2080,14 @@ public: topLayout->setAlignment(edit, Qt::AlignVCenter); if (browse) { - QPushButton *browseButton = - new QPushButton(tr("Browse")); + QPushButton *browseButton = new QPushButton(tr("Browse")); topLayout->addWidget(browseButton); topLayout->setAlignment(browseButton, Qt::AlignVCenter); - connect(browseButton, &QPushButton::clicked, this, - &EditableItemDialog::BrowseClicked); + connect(browseButton, &QPushButton::clicked, this, &EditableItemDialog::BrowseClicked); } - QDialogButtonBox::StandardButtons buttons = - QDialogButtonBox::Ok | QDialogButtonBox::Cancel; + QDialogButtonBox::StandardButtons buttons = QDialogButtonBox::Ok | QDialogButtonBox::Cancel; QDialogButtonBox *buttonBox = new QDialogButtonBox(buttons); buttonBox->setCenterButtons(true); @@ -2246,10 +2098,8 @@ public: setLayout(mainLayout); resize(QSize(400, 80)); - connect(buttonBox, &QDialogButtonBox::accepted, this, - &EditableItemDialog::accept); - connect(buttonBox, &QDialogButtonBox::rejected, this, - &EditableItemDialog::reject); + connect(buttonBox, &QDialogButtonBox::accepted, this, &EditableItemDialog::accept); + connect(buttonBox, &QDialogButtonBox::rejected, this, &EditableItemDialog::reject); } inline QString GetText() const { return edit->text(); } @@ -2257,8 +2107,7 @@ public: void WidgetInfo::EditListAdd() { - enum obs_editable_list_type type = - obs_property_editable_list_type(property); + enum obs_editable_list_type type = obs_property_editable_list_type(property); if (type == OBS_EDITABLE_LIST_TYPE_STRINGS) { EditListAddText(); @@ -2271,8 +2120,7 @@ void WidgetInfo::EditListAdd() QAction *action; action = new QAction(tr("Basic.PropertiesWindow.AddFiles"), this); - connect(action, &QAction::triggered, this, - &WidgetInfo::EditListAddFiles); + connect(action, &QAction::triggered, this, &WidgetInfo::EditListAddFiles); popup.addAction(action); action = new QAction(tr("Basic.PropertiesWindow.AddDir"), this); @@ -2281,8 +2129,7 @@ void WidgetInfo::EditListAdd() if (type == OBS_EDITABLE_LIST_TYPE_FILES_AND_URLS) { action = new QAction(tr("Basic.PropertiesWindow.AddURL"), this); - connect(action, &QAction::triggered, this, - &WidgetInfo::EditListAddText); + connect(action, &QAction::triggered, this, &WidgetInfo::EditListAddText); popup.addAction(action); } @@ -2295,8 +2142,7 @@ void WidgetInfo::EditListAddText() const char *desc = obs_property_description(property); EditableItemDialog dialog(widget->window(), QString(), false); - auto title = tr("Basic.PropertiesWindow.AddEditableListEntry") - .arg(QT_UTF8(desc)); + auto title = tr("Basic.PropertiesWindow.AddEditableListEntry").arg(QT_UTF8(desc)); dialog.setWindowTitle(title); if (dialog.exec() == QDialog::Rejected) return; @@ -2306,8 +2152,7 @@ void WidgetInfo::EditListAddText() return; QListWidgetItem *item = new QListWidgetItem(text); - item->setData(Qt::UserRole, - QUuid::createUuid().toString(QUuid::WithoutBraces)); + item->setData(Qt::UserRole, QUuid::createUuid().toString(QUuid::WithoutBraces)); list->addItem(item); EditableListChanged(); @@ -2318,14 +2163,11 @@ void WidgetInfo::EditListAddFiles() QListWidget *list = reinterpret_cast(widget); const char *desc = obs_property_description(property); const char *filter = obs_property_editable_list_filter(property); - const char *default_path = - obs_property_editable_list_default_path(property); + const char *default_path = obs_property_editable_list_default_path(property); - QString title = tr("Basic.PropertiesWindow.AddEditableListFiles") - .arg(QT_UTF8(desc)); + QString title = tr("Basic.PropertiesWindow.AddEditableListFiles").arg(QT_UTF8(desc)); - QStringList files = - OpenFiles(list, title, QT_UTF8(default_path), QT_UTF8(filter)); + QStringList files = OpenFiles(list, title, QT_UTF8(default_path), QT_UTF8(filter)); #ifdef __APPLE__ // TODO: Revisit when QTBUG-42661 is fixed widget->window()->raise(); @@ -2336,8 +2178,7 @@ void WidgetInfo::EditListAddFiles() for (QString file : files) { QListWidgetItem *item = new QListWidgetItem(file); - item->setData(Qt::UserRole, QUuid::createUuid().toString( - QUuid::WithoutBraces)); + item->setData(Qt::UserRole, QUuid::createUuid().toString(QUuid::WithoutBraces)); list->addItem(item); } @@ -2348,11 +2189,9 @@ void WidgetInfo::EditListAddDir() { QListWidget *list = reinterpret_cast(widget); const char *desc = obs_property_description(property); - const char *default_path = - obs_property_editable_list_default_path(property); + const char *default_path = obs_property_editable_list_default_path(property); - QString title = tr("Basic.PropertiesWindow.AddEditableListDir") - .arg(QT_UTF8(desc)); + QString title = tr("Basic.PropertiesWindow.AddEditableListDir").arg(QT_UTF8(desc)); QString dir = SelectDirectory(list, title, QT_UTF8(default_path)); #ifdef __APPLE__ @@ -2364,8 +2203,7 @@ void WidgetInfo::EditListAddDir() return; QListWidgetItem *item = new QListWidgetItem(dir); - item->setData(Qt::UserRole, - QUuid::createUuid().toString(QUuid::WithoutBraces)); + item->setData(Qt::UserRole, QUuid::createUuid().toString(QUuid::WithoutBraces)); list->addItem(item); EditableListChanged(); @@ -2384,8 +2222,7 @@ void WidgetInfo::EditListRemove() void WidgetInfo::EditListEdit() { QListWidget *list = reinterpret_cast(widget); - enum obs_editable_list_type type = - obs_property_editable_list_type(property); + enum obs_editable_list_type type = obs_property_editable_list_type(property); const char *desc = obs_property_description(property); const char *filter = obs_property_editable_list_filter(property); QList selectedItems = list->selectedItems(); @@ -2400,11 +2237,9 @@ void WidgetInfo::EditListEdit() QString path; if (pathDir.exists()) - path = SelectDirectory(list, tr("Browse"), - item->text()); + path = SelectDirectory(list, tr("Browse"), item->text()); else - path = OpenFile(list, tr("Browse"), item->text(), - QT_UTF8(filter)); + path = OpenFile(list, tr("Browse"), item->text(), QT_UTF8(filter)); if (path.isEmpty()) return; @@ -2414,11 +2249,8 @@ void WidgetInfo::EditListEdit() return; } - EditableItemDialog dialog(widget->window(), item->text(), - type != OBS_EDITABLE_LIST_TYPE_STRINGS, - filter); - auto title = tr("Basic.PropertiesWindow.EditEditableListEntry") - .arg(QT_UTF8(desc)); + EditableItemDialog dialog(widget->window(), item->text(), type != OBS_EDITABLE_LIST_TYPE_STRINGS, filter); + auto title = tr("Basic.PropertiesWindow.EditEditableListEntry").arg(QT_UTF8(desc)); dialog.setWindowTitle(title); if (dialog.exec() == QDialog::Rejected) return; diff --git a/shared/properties-view/properties-view.hpp b/shared/properties-view/properties-view.hpp index dcf90347b..eacec0a73 100644 --- a/shared/properties-view/properties-view.hpp +++ b/shared/properties-view/properties-view.hpp @@ -13,8 +13,7 @@ class OBSPropertiesView; class QLabel; typedef obs_properties_t *(*PropertiesReloadCallback)(void *obj); -typedef void (*PropertiesUpdateCallback)(void *obj, obs_data_t *old_settings, - obs_data_t *new_settings); +typedef void (*PropertiesUpdateCallback)(void *obj, obs_data_t *old_settings, obs_data_t *new_settings); typedef void (*PropertiesVisualUpdateCb)(void *obj, obs_data_t *settings); /* ------------------------------------------------------------------------- */ @@ -49,8 +48,7 @@ private: void TogglePasswordText(bool checked); public: - inline WidgetInfo(OBSPropertiesView *view_, obs_property_t *prop, - QWidget *widget_) + inline WidgetInfo(OBSPropertiesView *view_, obs_property_t *prop, QWidget *widget_) : view(view_), property(prop), widget(widget_) @@ -89,8 +87,7 @@ class OBSPropertiesView : public VScrollArea { friend class WidgetInfo; using properties_delete_t = decltype(&obs_properties_destroy); - using properties_t = - std::unique_ptr; + using properties_t = std::unique_ptr; private: QWidget *widget = nullptr; @@ -111,29 +108,21 @@ private: bool disableScrolling = false; template - QWidget *NewWidget(obs_property_t *prop, Sender *widget, - void (SenderParent::*signal)(Args...)); + QWidget *NewWidget(obs_property_t *prop, Sender *widget, void (SenderParent::*signal)(Args...)); QWidget *AddCheckbox(obs_property_t *prop); - QWidget *AddText(obs_property_t *prop, QFormLayout *layout, - QLabel *&label); + QWidget *AddText(obs_property_t *prop, QFormLayout *layout, QLabel *&label); void AddPath(obs_property_t *prop, QFormLayout *layout, QLabel **label); void AddInt(obs_property_t *prop, QFormLayout *layout, QLabel **label); - void AddFloat(obs_property_t *prop, QFormLayout *layout, - QLabel **label); + void AddFloat(obs_property_t *prop, QFormLayout *layout, QLabel **label); QWidget *AddList(obs_property_t *prop, bool &warning); - void AddEditableList(obs_property_t *prop, QFormLayout *layout, - QLabel *&label); + void AddEditableList(obs_property_t *prop, QFormLayout *layout, QLabel *&label); QWidget *AddButton(obs_property_t *prop); - void AddColorInternal(obs_property_t *prop, QFormLayout *layout, - QLabel *&label, bool supportAlpha); - void AddColor(obs_property_t *prop, QFormLayout *layout, - QLabel *&label); - void AddColorAlpha(obs_property_t *prop, QFormLayout *layout, - QLabel *&label); + void AddColorInternal(obs_property_t *prop, QFormLayout *layout, QLabel *&label, bool supportAlpha); + void AddColor(obs_property_t *prop, QFormLayout *layout, QLabel *&label); + void AddColorAlpha(obs_property_t *prop, QFormLayout *layout, QLabel *&label); void AddFont(obs_property_t *prop, QFormLayout *layout, QLabel *&label); - void AddFrameRate(obs_property_t *prop, bool &warning, - QFormLayout *layout, QLabel *&label); + void AddFrameRate(obs_property_t *prop, bool &warning, QFormLayout *layout, QLabel *&label); void AddGroup(obs_property_t *prop, QFormLayout *layout); @@ -157,29 +146,18 @@ signals: void PropertiesRefreshed(); public: - OBSPropertiesView(OBSData settings, obs_object_t *obj, - PropertiesReloadCallback reloadCallback, - PropertiesUpdateCallback callback, - PropertiesVisualUpdateCb cb = nullptr, - int minSize = 0); - OBSPropertiesView(OBSData settings, void *obj, - PropertiesReloadCallback reloadCallback, - PropertiesUpdateCallback callback, - PropertiesVisualUpdateCb cb = nullptr, - int minSize = 0); - OBSPropertiesView(OBSData settings, const char *type, - PropertiesReloadCallback reloadCallback, - int minSize = 0); + OBSPropertiesView(OBSData settings, obs_object_t *obj, PropertiesReloadCallback reloadCallback, + PropertiesUpdateCallback callback, PropertiesVisualUpdateCb cb = nullptr, int minSize = 0); + OBSPropertiesView(OBSData settings, void *obj, PropertiesReloadCallback reloadCallback, + PropertiesUpdateCallback callback, PropertiesVisualUpdateCb cb = nullptr, int minSize = 0); + OBSPropertiesView(OBSData settings, const char *type, PropertiesReloadCallback reloadCallback, int minSize = 0); -#define obj_constructor(type) \ - inline OBSPropertiesView(OBSData settings, obs_##type##_t *type, \ - PropertiesReloadCallback reloadCallback, \ - PropertiesUpdateCallback callback, \ - PropertiesVisualUpdateCb cb = nullptr, \ - int minSize = 0) \ - : OBSPropertiesView(settings, (obs_object_t *)type, \ - reloadCallback, callback, cb, minSize) \ - { \ +#define obj_constructor(type) \ + inline OBSPropertiesView(OBSData settings, obs_##type##_t *type, PropertiesReloadCallback reloadCallback, \ + PropertiesUpdateCallback callback, PropertiesVisualUpdateCb cb = nullptr, \ + int minSize = 0) \ + : OBSPropertiesView(settings, (obs_object_t *)type, reloadCallback, callback, cb, minSize) \ + { \ } obj_constructor(source); diff --git a/shared/properties-view/properties-view.moc.hpp b/shared/properties-view/properties-view.moc.hpp index 39f32a77f..bf3c1af8b 100644 --- a/shared/properties-view/properties-view.moc.hpp +++ b/shared/properties-view/properties-view.moc.hpp @@ -15,20 +15,17 @@ #pragma warning(disable : 4505) #endif -static bool operator!=(const media_frames_per_second &a, - const media_frames_per_second &b) +static bool operator!=(const media_frames_per_second &a, const media_frames_per_second &b) { return a.numerator != b.numerator || a.denominator != b.denominator; } -static bool operator==(const media_frames_per_second &a, - const media_frames_per_second &b) +static bool operator==(const media_frames_per_second &a, const media_frames_per_second &b) { return !(a != b); } -using frame_rate_range_t = - std::pair; +using frame_rate_range_t = std::pair; using frame_rate_ranges_t = std::vector; class OBSFrameRatePropertyWidget : public QWidget { diff --git a/shared/qt/icon-label/icon-label.hpp b/shared/qt/icon-label/icon-label.hpp index 856d34a52..b75842e64 100644 --- a/shared/qt/icon-label/icon-label.hpp +++ b/shared/qt/icon-label/icon-label.hpp @@ -32,12 +32,7 @@ class IconLabel : public QLabel { Q_PROPERTY(int iconSize READ iconSize WRITE setIconSize) public: - inline IconLabel(QWidget *parent = nullptr) - : QLabel(parent), - m_icon(), - m_iconSize(16) - { - } + inline IconLabel(QWidget *parent = nullptr) : QLabel(parent), m_icon(), m_iconSize(16) {} inline QIcon icon() const { return m_icon; } void setIcon(const QIcon &icon) diff --git a/shared/qt/plain-text-edit/plain-text-edit.cpp b/shared/qt/plain-text-edit/plain-text-edit.cpp index b2a600e30..e43e6eff8 100644 --- a/shared/qt/plain-text-edit/plain-text-edit.cpp +++ b/shared/qt/plain-text-edit/plain-text-edit.cpp @@ -1,19 +1,15 @@ #include "moc_plain-text-edit.cpp" #include -OBSPlainTextEdit::OBSPlainTextEdit(QWidget *parent, bool monospace) - : QPlainTextEdit(parent) +OBSPlainTextEdit::OBSPlainTextEdit(QWidget *parent, bool monospace) : QPlainTextEdit(parent) { // Fix display of tabs & multiple spaces document()->setDefaultStyleSheet("font { white-space: pre; }"); if (monospace) { - const QFont fixedFont = - QFontDatabase::systemFont(QFontDatabase::FixedFont); + const QFont fixedFont = QFontDatabase::systemFont(QFontDatabase::FixedFont); - setStyleSheet( - QString("font-family: %1; font-size: %2pt;") - .arg(fixedFont.family(), - QString::number(fixedFont.pointSize()))); + setStyleSheet(QString("font-family: %1; font-size: %2pt;") + .arg(fixedFont.family(), QString::number(fixedFont.pointSize()))); } } diff --git a/shared/qt/plain-text-edit/plain-text-edit.hpp b/shared/qt/plain-text-edit/plain-text-edit.hpp index 4e3a4bc26..ff21bb325 100644 --- a/shared/qt/plain-text-edit/plain-text-edit.hpp +++ b/shared/qt/plain-text-edit/plain-text-edit.hpp @@ -6,6 +6,5 @@ class OBSPlainTextEdit : public QPlainTextEdit { Q_OBJECT public: - explicit OBSPlainTextEdit(QWidget *parent = nullptr, - bool monospace = true); + explicit OBSPlainTextEdit(QWidget *parent = nullptr, bool monospace = true); }; diff --git a/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp b/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp index 36d602a3f..2740ca728 100644 --- a/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp +++ b/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp @@ -5,9 +5,7 @@ SliderIgnoreScroll::SliderIgnoreScroll(QWidget *parent) : QSlider(parent) setFocusPolicy(Qt::StrongFocus); } -SliderIgnoreScroll::SliderIgnoreScroll(Qt::Orientation orientation, - QWidget *parent) - : QSlider(parent) +SliderIgnoreScroll::SliderIgnoreScroll(Qt::Orientation orientation, QWidget *parent) : QSlider(parent) { setFocusPolicy(Qt::StrongFocus); setOrientation(orientation); @@ -25,8 +23,7 @@ void SliderIgnoreClick::mousePressEvent(QMouseEvent *event) { QStyleOptionSlider styleOption; initStyleOption(&styleOption); - QRect handle = style()->subControlRect(QStyle::CC_Slider, &styleOption, - QStyle::SC_SliderHandle, this); + QRect handle = style()->subControlRect(QStyle::CC_Slider, &styleOption, QStyle::SC_SliderHandle, this); if (handle.contains(event->position().toPoint())) { SliderIgnoreScroll::mousePressEvent(event); dragging = true; diff --git a/shared/qt/slider-ignorewheel/slider-ignorewheel.hpp b/shared/qt/slider-ignorewheel/slider-ignorewheel.hpp index 32b52db64..68c10323f 100644 --- a/shared/qt/slider-ignorewheel/slider-ignorewheel.hpp +++ b/shared/qt/slider-ignorewheel/slider-ignorewheel.hpp @@ -10,8 +10,7 @@ class SliderIgnoreScroll : public QSlider { public: SliderIgnoreScroll(QWidget *parent = nullptr); - SliderIgnoreScroll(Qt::Orientation orientation, - QWidget *parent = nullptr); + SliderIgnoreScroll(Qt::Orientation orientation, QWidget *parent = nullptr); protected: virtual void wheelEvent(QWheelEvent *event) override; @@ -19,8 +18,7 @@ protected: class SliderIgnoreClick : public SliderIgnoreScroll { public: - inline SliderIgnoreClick(Qt::Orientation orientation, - QWidget *parent = nullptr) + inline SliderIgnoreClick(Qt::Orientation orientation, QWidget *parent = nullptr) : SliderIgnoreScroll(orientation, parent) { } diff --git a/shared/qt/wrappers/qt-wrappers.cpp b/shared/qt/wrappers/qt-wrappers.cpp index a183c6a61..490f59bb1 100644 --- a/shared/qt/wrappers/qt-wrappers.cpp +++ b/shared/qt/wrappers/qt-wrappers.cpp @@ -46,14 +46,11 @@ void OBSErrorBox(QWidget *parent, const char *msg, ...) va_end(args); } -QMessageBox::StandardButton -OBSMessageBox::question(QWidget *parent, const QString &title, - const QString &text, - QMessageBox::StandardButtons buttons, - QMessageBox::StandardButton defaultButton) +QMessageBox::StandardButton OBSMessageBox::question(QWidget *parent, const QString &title, const QString &text, + QMessageBox::StandardButtons buttons, + QMessageBox::StandardButton defaultButton) { - QMessageBox mb(QMessageBox::Question, title, text, - QMessageBox::NoButton, parent); + QMessageBox mb(QMessageBox::Question, title, text, QMessageBox::NoButton, parent); mb.setDefaultButton(defaultButton); if (buttons & QMessageBox::Ok) { @@ -81,31 +78,25 @@ OBSMessageBox::question(QWidget *parent, const QString &title, return (QMessageBox::StandardButton)mb.exec(); } -void OBSMessageBox::information(QWidget *parent, const QString &title, - const QString &text) +void OBSMessageBox::information(QWidget *parent, const QString &title, const QString &text) { - QMessageBox mb(QMessageBox::Information, title, text, - QMessageBox::NoButton, parent); + QMessageBox mb(QMessageBox::Information, title, text, QMessageBox::NoButton, parent); mb.addButton(tr("OK"), QMessageBox::AcceptRole); mb.exec(); } -void OBSMessageBox::warning(QWidget *parent, const QString &title, - const QString &text, bool enableRichText) +void OBSMessageBox::warning(QWidget *parent, const QString &title, const QString &text, bool enableRichText) { - QMessageBox mb(QMessageBox::Warning, title, text, QMessageBox::NoButton, - parent); + QMessageBox mb(QMessageBox::Warning, title, text, QMessageBox::NoButton, parent); if (enableRichText) mb.setTextFormat(Qt::RichText); mb.addButton(tr("OK"), QMessageBox::AcceptRole); mb.exec(); } -void OBSMessageBox::critical(QWidget *parent, const QString &title, - const QString &text) +void OBSMessageBox::critical(QWidget *parent, const QString &title, const QString &text) { - QMessageBox mb(QMessageBox::Critical, title, text, - QMessageBox::NoButton, parent); + QMessageBox mb(QMessageBox::Critical, title, text, QMessageBox::NoButton, parent); mb.addButton(tr("OK"), QMessageBox::AcceptRole); mb.exec(); } @@ -136,14 +127,12 @@ uint32_t TranslateQtKeyboardEventModifiers(Qt::KeyboardModifiers mods) return obsModifiers; } -QDataStream &operator<<(QDataStream &out, - const std::vector> &) +QDataStream &operator<<(QDataStream &out, const std::vector> &) { return out; } -QDataStream &operator>>(QDataStream &in, - std::vector> &) +QDataStream &operator>>(QDataStream &in, std::vector> &) { return in; } @@ -206,9 +195,7 @@ void DeleteLayout(QLayout *layout) class QuickThread : public QThread { public: - explicit inline QuickThread(std::function func_) : func(func_) - { - } + explicit inline QuickThread(std::function func_) : func(func_) {} private: virtual void run() override { func(); } @@ -229,8 +216,7 @@ void ExecuteFuncSafeBlock(std::function func) auto wait = [&]() { func(); - QMetaObject::invokeMethod(&eventLoop, "quit", - Qt::QueuedConnection); + QMetaObject::invokeMethod(&eventLoop, "quit", Qt::QueuedConnection); }; os_atomic_inc_long(&insideEventLoop); @@ -241,8 +227,7 @@ void ExecuteFuncSafeBlock(std::function func) os_atomic_dec_long(&insideEventLoop); } -void ExecuteFuncSafeBlockMsgBox(std::function func, - const QString &title, const QString &text) +void ExecuteFuncSafeBlockMsgBox(std::function func, const QString &title, const QString &text) { QMessageBox dlg; dlg.setWindowFlags(dlg.windowFlags() & ~Qt::WindowCloseButtonHint); @@ -270,8 +255,7 @@ void EnableThreadedMessageBoxes(bool enable) enable_message_boxes = enable; } -void ExecThreadedWithoutBlocking(std::function func, - const QString &title, const QString &text) +void ExecThreadedWithoutBlocking(std::function func, const QString &title, const QString &text) { if (!enable_message_boxes) ExecuteFuncSafeBlock(func); @@ -310,11 +294,9 @@ bool LineEditChanged(QEvent *event) void SetComboItemEnabled(QComboBox *c, int idx, bool enabled) { - QStandardItemModel *model = - dynamic_cast(c->model()); + QStandardItemModel *model = dynamic_cast(c->model()); QStandardItem *item = model->item(idx); - item->setFlags(enabled ? Qt::ItemIsSelectable | Qt::ItemIsEnabled - : Qt::NoItemFlags); + item->setFlags(enabled ? Qt::ItemIsSelectable | Qt::ItemIsEnabled : Qt::NoItemFlags); } void setClasses(QWidget *widget, const QString &newClasses) @@ -331,36 +313,29 @@ void setClasses(QWidget *widget, const QString &newClasses) QString SelectDirectory(QWidget *parent, QString title, QString path) { - QString dir = QFileDialog::getExistingDirectory( - parent, title, path, - QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); + QString dir = QFileDialog::getExistingDirectory(parent, title, path, + QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks); return dir; } -QString SaveFile(QWidget *parent, QString title, QString path, - QString extensions) +QString SaveFile(QWidget *parent, QString title, QString path, QString extensions) { - QString file = - QFileDialog::getSaveFileName(parent, title, path, extensions); + QString file = QFileDialog::getSaveFileName(parent, title, path, extensions); return file; } -QString OpenFile(QWidget *parent, QString title, QString path, - QString extensions) +QString OpenFile(QWidget *parent, QString title, QString path, QString extensions) { - QString file = - QFileDialog::getOpenFileName(parent, title, path, extensions); + QString file = QFileDialog::getOpenFileName(parent, title, path, extensions); return file; } -QStringList OpenFiles(QWidget *parent, QString title, QString path, - QString extensions) +QStringList OpenFiles(QWidget *parent, QString title, QString path, QString extensions) { - QStringList files = - QFileDialog::getOpenFileNames(parent, title, path, extensions); + QStringList files = QFileDialog::getOpenFileNames(parent, title, path, extensions); return files; } diff --git a/shared/qt/wrappers/qt-wrappers.hpp b/shared/qt/wrappers/qt-wrappers.hpp index 536711f7b..be688d0ef 100644 --- a/shared/qt/wrappers/qt-wrappers.hpp +++ b/shared/qt/wrappers/qt-wrappers.hpp @@ -43,30 +43,21 @@ class QToolBar; class OBSMessageBox : QObject { Q_OBJECT public: - static QMessageBox::StandardButton - question(QWidget *parent, const QString &title, const QString &text, - QMessageBox::StandardButtons buttons = - QMessageBox::StandardButtons(QMessageBox::Yes | - QMessageBox::No), - QMessageBox::StandardButton defaultButton = - QMessageBox::NoButton); - static void information(QWidget *parent, const QString &title, - const QString &text); - static void warning(QWidget *parent, const QString &title, - const QString &text, bool enableRichText = false); - static void critical(QWidget *parent, const QString &title, - const QString &text); + static QMessageBox::StandardButton question( + QWidget *parent, const QString &title, const QString &text, + QMessageBox::StandardButtons buttons = QMessageBox::StandardButtons(QMessageBox::Yes | QMessageBox::No), + QMessageBox::StandardButton defaultButton = QMessageBox::NoButton); + static void information(QWidget *parent, const QString &title, const QString &text); + static void warning(QWidget *parent, const QString &title, const QString &text, bool enableRichText = false); + static void critical(QWidget *parent, const QString &title, const QString &text); }; void OBSErrorBox(QWidget *parent, const char *msg, ...); uint32_t TranslateQtKeyboardEventModifiers(Qt::KeyboardModifiers mods); -QDataStream & -operator<<(QDataStream &out, - const std::vector> &signal_vec); -QDataStream &operator>>(QDataStream &in, - std::vector> &signal_vec); +QDataStream &operator<<(QDataStream &out, const std::vector> &signal_vec); +QDataStream &operator>>(QDataStream &in, std::vector> &signal_vec); QDataStream &operator<<(QDataStream &out, const OBSScene &scene); QDataStream &operator>>(QDataStream &in, OBSScene &scene); QDataStream &operator<<(QDataStream &out, const OBSSource &source); @@ -75,22 +66,18 @@ QDataStream &operator>>(QDataStream &in, OBSSource &source); QThread *CreateQThread(std::function func); void ExecuteFuncSafeBlock(std::function func); -void ExecuteFuncSafeBlockMsgBox(std::function func, - const QString &title, const QString &text); +void ExecuteFuncSafeBlockMsgBox(std::function func, const QString &title, const QString &text); /* allows executing without message boxes if starting up, otherwise with a * message box */ void EnableThreadedMessageBoxes(bool enable); -void ExecThreadedWithoutBlocking(std::function func, - const QString &title, const QString &text); +void ExecThreadedWithoutBlocking(std::function func, const QString &title, const QString &text); void DeleteLayout(QLayout *layout); static inline Qt::ConnectionType WaitConnection() { - return QThread::currentThread() == qApp->thread() - ? Qt::DirectConnection - : Qt::BlockingQueuedConnection; + return QThread::currentThread() == qApp->thread() ? Qt::DirectConnection : Qt::BlockingQueuedConnection; } bool LineEditCanceled(QEvent *event); @@ -101,14 +88,10 @@ void SetComboItemEnabled(QComboBox *c, int idx, bool enabled); void setClasses(QWidget *widget, const QString &newClasses); QString SelectDirectory(QWidget *parent, QString title, QString path); -QString SaveFile(QWidget *parent, QString title, QString path, - QString extensions); -QString OpenFile(QWidget *parent, QString title, QString path, - QString extensions); -QStringList OpenFiles(QWidget *parent, QString title, QString path, - QString extensions); +QString SaveFile(QWidget *parent, QString title, QString path, QString extensions); +QString OpenFile(QWidget *parent, QString title, QString path, QString extensions); +QStringList OpenFiles(QWidget *parent, QString title, QString path, QString extensions); -void TruncateLabel(QLabel *label, QString newText, - int length = MAX_LABEL_LENGTH); +void TruncateLabel(QLabel *label, QString newText, int length = MAX_LABEL_LENGTH); void RefreshToolBarStyling(QToolBar *toolBar); diff --git a/test/cmocka/test_os_path.c b/test/cmocka/test_os_path.c index 5385f4632..05a7ebc16 100644 --- a/test/cmocka/test_os_path.c +++ b/test/cmocka/test_os_path.c @@ -29,17 +29,16 @@ static void os_get_path_extension_test(void **state) { UNUSED_PARAMETER(state); - static struct testcase testcases[] = { - {"/home/user/a.txt", ".txt"}, - {"C:\\Users\\user\\Documents\\video.mp4", ".mp4"}, - {"./\\", NULL}, - {".\\/", NULL}, - {"/.\\", NULL}, - {"/\\.", "."}, - {"\\/.", "."}, - {"\\./", NULL}, - {"", NULL}, - {NULL, NULL}}; + static struct testcase testcases[] = {{"/home/user/a.txt", ".txt"}, + {"C:\\Users\\user\\Documents\\video.mp4", ".mp4"}, + {"./\\", NULL}, + {".\\/", NULL}, + {"/.\\", NULL}, + {"/\\.", "."}, + {"\\/.", "."}, + {"\\./", NULL}, + {"", NULL}, + {NULL, NULL}}; run_testcases(testcases); } diff --git a/test/osx/test.mm b/test/osx/test.mm index f65f99e37..bfb72a6eb 100644 --- a/test/osx/test.mm +++ b/test/osx/test.mm @@ -18,8 +18,7 @@ static const int cy = 600; template struct OBSUniqueHandle : std::unique_ptr> { using base = std::unique_ptr>; - explicit OBSUniqueHandle(T *obj = nullptr) : base(obj, D) - {} + explicit OBSUniqueHandle(T *obj = nullptr) : base(obj, D) {} operator T *() { return base::get(); diff --git a/test/test-input/sync-audio-buffering.c b/test/test-input/sync-audio-buffering.c index b0b2a82c6..dd1d7473d 100644 --- a/test/test-input/sync-audio-buffering.c +++ b/test/test-input/sync-audio-buffering.c @@ -24,8 +24,7 @@ static const double aud_rates[CYCLE_COUNT] = { }; #define MAKE_COL_CHAN(x, y) (((0xFF / 7) * x) << (y * 8)) -#define MAKE_GRAYSCALE(x) \ - (MAKE_COL_CHAN(x, 0) | MAKE_COL_CHAN(x, 1) | MAKE_COL_CHAN(x, 2)) +#define MAKE_GRAYSCALE(x) (MAKE_COL_CHAN(x, 0) | MAKE_COL_CHAN(x, 1) | MAKE_COL_CHAN(x, 2)) static const uint32_t vid_colors[CYCLE_COUNT] = { 0xFF000000, @@ -120,8 +119,7 @@ static void *video_thread(void *data) /* should cause approximately 750 milliseconds of audio * buffering */ frame.timestamp = cur_time - start_time; - audio.timestamp = cur_time - start_time - - (audio_buffering_enabled ? 1000000000 : 0); + audio.timestamp = cur_time - start_time - (audio_buffering_enabled ? 1000000000 : 0); const double rate = aud_rates[cur_aud_pos]; @@ -150,8 +148,7 @@ static void *video_thread(void *data) return NULL; } -static void bast_buffer_audio(void *data, obs_hotkey_id id, - obs_hotkey_t *hotkey, bool pressed) +static void bast_buffer_audio(void *data, obs_hotkey_id id, obs_hotkey_t *hotkey, bool pressed) { struct buffering_async_sync_test *bast = data; @@ -177,8 +174,7 @@ static void *bast_create(obs_data_t *settings, obs_source_t *source) return NULL; } - obs_hotkey_register_source(source, "AudioBufferingSyncTest.Buffer", - "Buffer Audio", bast_buffer_audio, bast); + obs_hotkey_register_source(source, "AudioBufferingSyncTest.Buffer", "Buffer Audio", bast_buffer_audio, bast); bast->initialized = true; diff --git a/test/test-input/sync-pair-aud.c b/test/test-input/sync-pair-aud.c index 1ff0b7c81..a270c29b8 100644 --- a/test/test-input/sync-pair-aud.c +++ b/test/test-input/sync-pair-aud.c @@ -23,8 +23,7 @@ static const double rate = 261.63 / 48000.0; extern uint64_t starting_time; -static inline bool whitelist_time(uint64_t ts, uint64_t interval, - uint64_t fps_num, uint64_t fps_den) +static inline bool whitelist_time(uint64_t ts, uint64_t interval, uint64_t fps_num, uint64_t fps_den) { if (!starting_time) return false; @@ -44,8 +43,7 @@ static void *sync_pair_aud_thread(void *pdata) float *samples = malloc(frames * sizeof(float)); uint64_t interval = video_output_get_frame_time(obs_get_video()); - const struct video_output_info *voi = - video_output_get_info(obs_get_video()); + const struct video_output_info *voi = video_output_get_info(obs_get_video()); uint64_t fps_num = voi->fps_num; uint64_t fps_den = voi->fps_den; @@ -54,9 +52,7 @@ static void *sync_pair_aud_thread(void *pdata) last_time = obs_get_video_frame_time(); for (uint64_t i = 0; i < frames; i++) { - uint64_t ts = - last_time + - util_mul_div64(i, 1000000000ULL, sample_rate); + uint64_t ts = last_time + util_mul_div64(i, 1000000000ULL, sample_rate); if (whitelist_time(ts, interval, fps_num, fps_den)) { cos_val += rate * M_PI_X2; diff --git a/test/test-input/sync-pair-vid.c b/test/test-input/sync-pair-vid.c index bcc34c46a..05e20140b 100644 --- a/test/test-input/sync-pair-vid.c +++ b/test/test-input/sync-pair-vid.c @@ -71,8 +71,7 @@ static void *sync_pair_vid_create(obs_data_t *settings, obs_source_t *source) return spv; } -static inline bool whitelist_time(uint64_t ts, uint64_t interval, - uint64_t fps_num, uint64_t fps_den) +static inline bool whitelist_time(uint64_t ts, uint64_t interval, uint64_t fps_num, uint64_t fps_den) { if (!starting_time) return false; @@ -92,8 +91,7 @@ static void sync_pair_vid_render(void *data, gs_effect_t *effect) starting_time = ts; uint64_t interval = video_output_get_frame_time(obs_get_video()); - const struct video_output_info *voi = - video_output_get_info(obs_get_video()); + const struct video_output_info *voi = video_output_get_info(obs_get_video()); uint64_t fps_num = voi->fps_num; uint64_t fps_den = voi->fps_den; diff --git a/test/test-input/test-filter.c b/test/test-input/test-filter.c index 35c114d0a..6833d0b8e 100644 --- a/test/test-input/test-filter.c +++ b/test/test-input/test-filter.c @@ -52,8 +52,7 @@ static void filter_render(void *data, gs_effect_t *effect) { struct test_filter *tf = data; - if (!obs_source_process_filter_begin(tf->source, GS_RGBA, - OBS_ALLOW_DIRECT_RENDERING)) + if (!obs_source_process_filter_begin(tf->source, GS_RGBA, OBS_ALLOW_DIRECT_RENDERING)) return; obs_source_process_filter_end(tf->source, tf->whatever, 0, 0); diff --git a/test/win/test.cpp b/test/win/test.cpp index 1f1dd1879..f642a4a12 100644 --- a/test/win/test.cpp +++ b/test/win/test.cpp @@ -47,8 +47,7 @@ public: /* --------------------------------------------------- */ -static LRESULT CALLBACK sceneProc(HWND hwnd, UINT message, WPARAM wParam, - LPARAM lParam) +static LRESULT CALLBACK sceneProc(HWND hwnd, UINT message, WPARAM wParam, LPARAM lParam) { switch (message) { @@ -140,10 +139,8 @@ static HWND CreateTestWindow(HINSTANCE instance) if (!RegisterClass(&wc)) return 0; - return CreateWindow(TEXT("bla"), TEXT("bla"), - WS_OVERLAPPEDWINDOW | WS_VISIBLE, 1920 / 2 - cx / 2, - 1080 / 2 - cy / 2, cx, cy, NULL, NULL, instance, - NULL); + return CreateWindow(TEXT("bla"), TEXT("bla"), WS_OVERLAPPEDWINDOW | WS_VISIBLE, 1920 / 2 - cx / 2, + 1080 / 2 - cy / 2, cx, cy, NULL, NULL, instance, NULL); } /* --------------------------------------------------- */ @@ -159,8 +156,7 @@ static void RenderWindow(void *data, uint32_t cx, uint32_t cy) /* --------------------------------------------------- */ -int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, - int numCmd) +int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, int numCmd) { HWND hwnd = NULL; base_set_log_handler(do_log, nullptr); @@ -180,15 +176,13 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, /* ------------------------------------------------------ */ /* create source */ - SourceContext source = obs_source_create( - "random", "some randon source", NULL, nullptr); + SourceContext source = obs_source_create("random", "some randon source", NULL, nullptr); if (!source) throw "Couldn't create random test source"; /* ------------------------------------------------------ */ /* create filter */ - SourceContext filter = obs_source_create( - "test_filter", "a nice green filter", NULL, nullptr); + SourceContext filter = obs_source_create("test_filter", "a nice green filter", NULL, nullptr); if (!filter) throw "Couldn't create test filter"; obs_source_filter_add(source, filter);