From 5fb7699f05bc1b4905367bb8cf7124d42bb1f845 Mon Sep 17 00:00:00 2001 From: Warchamp7 Date: Tue, 5 May 2026 18:32:49 -0400 Subject: [PATCH 1/2] Update clang-format to insert braces in C++ --- .clang-format | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/.clang-format b/.clang-format index 73c5b0faaebf0d..ee640426a58fa9 100644 --- a/.clang-format +++ b/.clang-format @@ -1,6 +1,5 @@ # please use clang-format version 16 or later -Standard: c++17 AccessModifierOffset: -8 AlignAfterOpenBracket: Align AlignConsecutiveAssignments: false @@ -106,6 +105,10 @@ TypenameMacros: - 'DARRAY' UseTab: ForContinuationAndIndentation --- +Language: Cpp +Standard: c++17 +InsertBraces: true +--- Language: ObjC AccessModifierOffset: 2 AlignArrayOfStructures: Right @@ -207,3 +210,4 @@ SpacesInLineCommentPrefix: Standard: c++17 TabWidth: 4 UseTab: Never +... From 23f4c1e63bd584042dbca4a85c3a3743c338000d Mon Sep 17 00:00:00 2001 From: Warchamp7 Date: Tue, 5 May 2026 18:32:52 -0400 Subject: [PATCH 2/2] Update C++ files with braces --- frontend/OBSApp.cpp | 214 +++-- frontend/OBSApp.hpp | 15 +- frontend/OBSApp_Themes.cpp | 228 +++-- frontend/OBSStudioAPI.cpp | 51 +- frontend/api/obs-frontend-api.cpp | 168 ++-- frontend/components/AbsoluteSlider.cpp | 5 +- frontend/components/AudioCaptureToolbar.cpp | 3 +- frontend/components/ComboSelectToolbar.cpp | 3 +- frontend/components/DeviceCaptureToolbar.cpp | 3 +- frontend/components/DisplayCaptureToolbar.cpp | 3 +- frontend/components/FocusList.cpp | 5 +- frontend/components/GameCaptureToolbar.cpp | 3 +- frontend/components/ImageSourceToolbar.cpp | 3 +- frontend/components/MediaControls.cpp | 39 +- frontend/components/MenuButton.cpp | 5 +- frontend/components/Multiview.cpp | 82 +- frontend/components/MuteCheckBox.hpp | 5 +- frontend/components/OBSAdvAudioCtrl.cpp | 47 +- .../components/OBSPreviewScalingComboBox.cpp | 6 +- frontend/components/SceneTree.cpp | 9 +- frontend/components/SourceToolbar.cpp | 6 +- frontend/components/SourceTree.cpp | 46 +- frontend/components/SourceTreeDelegate.cpp | 3 +- frontend/components/SourceTreeItem.cpp | 42 +- frontend/components/SourceTreeModel.cpp | 50 +- frontend/components/TextSourceToolbar.cpp | 3 +- frontend/components/UIValidation.cpp | 26 +- frontend/components/UrlPushButton.cpp | 3 +- .../components/VisibilityItemDelegate.cpp | 14 +- frontend/components/VisibilityItemWidget.cpp | 6 +- .../components/VolumeAccessibleInterface.cpp | 5 +- frontend/components/WindowCaptureToolbar.cpp | 3 +- frontend/dialogs/NameDialog.cpp | 9 +- frontend/dialogs/OAuthLogin.cpp | 11 +- frontend/dialogs/OBSAbout.cpp | 14 +- frontend/dialogs/OBSBasicAdvAudio.cpp | 32 +- frontend/dialogs/OBSBasicFilters.cpp | 136 ++- frontend/dialogs/OBSBasicFilters.hpp | 3 +- frontend/dialogs/OBSBasicInteraction.cpp | 58 +- frontend/dialogs/OBSBasicProperties.cpp | 26 +- frontend/dialogs/OBSBasicSourceSelect.cpp | 77 +- frontend/dialogs/OBSBasicTransform.cpp | 33 +- frontend/dialogs/OBSBasicVCamConfig.cpp | 15 +- frontend/dialogs/OBSLogViewer.cpp | 9 +- frontend/dialogs/OBSRemux.cpp | 23 +- frontend/dialogs/OBSYoutubeActions.cpp | 73 +- frontend/docks/YouTubeAppDock.cpp | 36 +- .../ImporterEntryPathItemDelegate.cpp | 3 +- frontend/importer/ImporterModel.cpp | 10 +- frontend/importer/OBSImporter.cpp | 9 +- frontend/importers/classic.cpp | 64 +- frontend/importers/importers.hpp | 15 +- frontend/importers/sl.cpp | 36 +- frontend/importers/studio.cpp | 44 +- frontend/importers/xsplit.cpp | 68 +- frontend/oauth/Auth.cpp | 3 +- frontend/oauth/AuthListener.cpp | 3 +- frontend/oauth/OAuth.cpp | 29 +- frontend/oauth/RestreamAuth.cpp | 33 +- frontend/oauth/TwitchAuth.cpp | 63 +- frontend/oauth/YoutubeAuth.cpp | 18 +- frontend/obs-main.cpp | 123 ++- frontend/plugin-manager/PluginManager.cpp | 3 +- .../plugins/aja-output-ui/AJAOutputUI.cpp | 18 +- .../plugins/aja-output-ui/aja-ui-main.cpp | 58 +- .../decklink-captions/decklink-captions.cpp | 15 +- .../decklink-output-ui/DecklinkOutputUI.cpp | 18 +- .../decklink-output-ui/decklink-ui-main.cpp | 85 +- .../auto-scene-switcher-nix.cpp | 12 +- .../auto-scene-switcher-win.cpp | 18 +- .../frontend-tools/auto-scene-switcher.cpp | 60 +- .../frontend-tools/captions-handler.cpp | 12 +- .../frontend-tools/captions-mssapi-stream.cpp | 66 +- .../frontend-tools/captions-mssapi.cpp | 57 +- frontend/plugins/frontend-tools/captions.cpp | 54 +- .../plugins/frontend-tools/output-timer.cpp | 41 +- frontend/plugins/frontend-tools/scripts.cpp | 42 +- frontend/settings/OBSBasicSettings.cpp | 903 ++++++++++++------ frontend/settings/OBSBasicSettings_A11y.cpp | 27 +- .../settings/OBSBasicSettings_Appearance.cpp | 21 +- frontend/settings/OBSBasicSettings_Stream.cpp | 236 +++-- frontend/settings/OBSHotkeyEdit.cpp | 18 +- frontend/settings/OBSHotkeyLabel.cpp | 12 +- frontend/settings/OBSHotkeyWidget.cpp | 36 +- frontend/settings/OBSHotkeyWidget.hpp | 3 +- frontend/updater/hash.cpp | 18 +- frontend/updater/helpers.hpp | 6 +- frontend/updater/http.cpp | 30 +- frontend/updater/patch.cpp | 30 +- frontend/updater/updater.cpp | 258 +++-- frontend/utility/AdvancedOutput.cpp | 165 ++-- frontend/utility/AutoUpdateThread.cpp | 61 +- frontend/utility/BasicOutputHandler.cpp | 62 +- frontend/utility/BasicOutputHandler.hpp | 3 +- frontend/utility/ExtraBrowsersDelegate.cpp | 3 +- frontend/utility/ExtraBrowsersModel.cpp | 15 +- frontend/utility/FFmpegCodec.cpp | 18 +- frontend/utility/FFmpegCodec.hpp | 3 +- frontend/utility/FFmpegFormat.cpp | 12 +- frontend/utility/FFmpegFormat.hpp | 3 +- frontend/utility/FFmpegShared.hpp | 12 +- frontend/utility/GoLiveAPI_CensoredJson.cpp | 3 +- frontend/utility/GoLiveAPI_Network.cpp | 15 +- frontend/utility/GoLiveAPI_PostData.cpp | 9 +- frontend/utility/MacUpdateThread.cpp | 9 +- frontend/utility/MissingFilesModel.cpp | 6 +- .../utility/MissingFilesPathItemDelegate.cpp | 6 +- frontend/utility/MultitrackVideoOutput.cpp | 102 +- frontend/utility/OBSCanvas.cpp | 15 +- frontend/utility/OBSProxyStyle.cpp | 9 +- frontend/utility/OBSTranslator.cpp | 3 +- frontend/utility/QuickTransition.cpp | 8 +- frontend/utility/RemoteTextThread.cpp | 36 +- .../utility/RemuxEntryPathItemDelegate.cpp | 12 +- frontend/utility/RemuxQueueModel.cpp | 25 +- frontend/utility/RemuxWorker.cpp | 3 +- frontend/utility/SceneRenameDelegate.cpp | 6 +- frontend/utility/ScreenshotObj.cpp | 48 +- frontend/utility/SimpleOutput.cpp | 148 +-- frontend/utility/WHIPSimulcastEncoders.hpp | 6 +- frontend/utility/WhatsNewInfoThread.cpp | 63 +- frontend/utility/YoutubeApiWrappers.cpp | 51 +- frontend/utility/audio-encoders.cpp | 111 ++- frontend/utility/display-helpers.hpp | 6 +- frontend/utility/item-widget-helpers.cpp | 6 +- frontend/utility/models/whatsnew.hpp | 5 +- frontend/utility/platform-windows.cpp | 76 +- frontend/utility/platform-x11.cpp | 26 +- frontend/utility/system-info-posix.cpp | 12 +- frontend/utility/system-info-windows.cpp | 36 +- frontend/utility/undo_stack.cpp | 24 +- frontend/utility/update-helpers.cpp | 3 +- frontend/widgets/OBSBasic.cpp | 220 +++-- frontend/widgets/OBSBasic.hpp | 9 +- frontend/widgets/OBSBasicControls.cpp | 6 +- frontend/widgets/OBSBasicPreview.cpp | 378 +++++--- frontend/widgets/OBSBasicPreview.hpp | 3 +- frontend/widgets/OBSBasicStats.cpp | 84 +- frontend/widgets/OBSBasicStatusBar.cpp | 96 +- frontend/widgets/OBSBasic_Browser.cpp | 24 +- frontend/widgets/OBSBasic_Canvases.cpp | 6 +- frontend/widgets/OBSBasic_Clipboard.cpp | 21 +- frontend/widgets/OBSBasic_ContextToolbar.cpp | 33 +- frontend/widgets/OBSBasic_Docks.cpp | 26 +- frontend/widgets/OBSBasic_Dropfiles.cpp | 15 +- frontend/widgets/OBSBasic_Hotkeys.cpp | 24 +- frontend/widgets/OBSBasic_MainControls.cpp | 85 +- frontend/widgets/OBSBasic_OutputHandler.cpp | 18 +- frontend/widgets/OBSBasic_Preview.cpp | 30 +- frontend/widgets/OBSBasic_Profiles.cpp | 34 +- frontend/widgets/OBSBasic_Projectors.cpp | 39 +- frontend/widgets/OBSBasic_Recording.cpp | 75 +- frontend/widgets/OBSBasic_ReplayBuffer.cpp | 56 +- .../widgets/OBSBasic_SceneCollections.cpp | 108 ++- frontend/widgets/OBSBasic_SceneItems.cpp | 165 ++-- frontend/widgets/OBSBasic_Scenes.cpp | 92 +- frontend/widgets/OBSBasic_Service.cpp | 18 +- frontend/widgets/OBSBasic_Streaming.cpp | 77 +- frontend/widgets/OBSBasic_StudioMode.cpp | 27 +- frontend/widgets/OBSBasic_SysTray.cpp | 20 +- frontend/widgets/OBSBasic_Transitions.cpp | 240 +++-- frontend/widgets/OBSBasic_Updater.cpp | 24 +- frontend/widgets/OBSBasic_VirtualCam.cpp | 39 +- frontend/widgets/OBSBasic_YouTube.cpp | 33 +- frontend/widgets/OBSProjector.cpp | 88 +- frontend/widgets/OBSQTDisplay.cpp | 18 +- frontend/wizards/AutoConfig.cpp | 39 +- frontend/wizards/AutoConfigStreamPage.cpp | 55 +- frontend/wizards/AutoConfigTestPage.cpp | 187 ++-- frontend/wizards/AutoConfigVideoPage.cpp | 3 +- frontend/wizards/TestMode.hpp | 6 +- libobs-d3d11/d3d11-duplicator.cpp | 30 +- libobs-d3d11/d3d11-indexbuffer.cpp | 3 +- libobs-d3d11/d3d11-rebuild.cpp | 132 ++- libobs-d3d11/d3d11-samplerstate.cpp | 3 +- libobs-d3d11/d3d11-shader.cpp | 88 +- libobs-d3d11/d3d11-shaderprocessor.cpp | 51 +- libobs-d3d11/d3d11-stagesurf.cpp | 6 +- libobs-d3d11/d3d11-subsystem.cpp | 433 ++++++--- libobs-d3d11/d3d11-subsystem.hpp | 21 +- libobs-d3d11/d3d11-texture2d.cpp | 59 +- libobs-d3d11/d3d11-texture3d.cpp | 35 +- libobs-d3d11/d3d11-vertexbuffer.cpp | 36 +- libobs-d3d11/d3d11-zstencilbuffer.cpp | 6 +- libobs-winrt/winrt-capture.cpp | 36 +- libobs/obs.hpp | 6 +- libobs/util/profiler.hpp | 3 +- libobs/util/util.hpp | 3 +- libobs/util/windows/CoTaskMemPtr.hpp | 3 +- libobs/util/windows/ComPtr.hpp | 21 +- libobs/util/windows/WinHandle.hpp | 6 +- plugins/aja/aja-card-manager.cpp | 36 +- plugins/aja/aja-common.cpp | 73 +- plugins/aja/aja-output.cpp | 54 +- plugins/aja/aja-presets.cpp | 9 +- plugins/aja/aja-props.cpp | 30 +- plugins/aja/aja-routing.cpp | 29 +- plugins/aja/aja-source.cpp | 68 +- plugins/coreaudio-encoder/encoder.cpp | 99 +- plugins/decklink/DecklinkInput.cpp | 27 +- plugins/decklink/DecklinkOutput.cpp | 18 +- plugins/decklink/OBSVideoFrame.cpp | 14 +- .../decklink/decklink-device-discovery.cpp | 24 +- .../decklink/decklink-device-discovery.hpp | 3 +- plugins/decklink/decklink-device-instance.cpp | 71 +- plugins/decklink/decklink-device-mode.cpp | 24 +- plugins/decklink/decklink-device.cpp | 40 +- plugins/decklink/decklink-output.cpp | 27 +- plugins/decklink/decklink-source.cpp | 8 +- plugins/decklink/linux/platform.cpp | 3 +- plugins/decklink/mac/platform.cpp | 3 +- plugins/decklink/plugin-main.cpp | 6 +- plugins/decklink/win/platform.cpp | 3 +- plugins/mac-avcapture/legacy/left-right.hpp | 9 +- plugins/mac-avcapture/legacy/scope-guard.hpp | 3 +- .../obs-ffmpeg/obs-amf-test/obs-amf-test.cpp | 30 +- plugins/obs-ffmpeg/texture-amf-opts.hpp | 102 +- plugins/obs-ffmpeg/texture-amf.cpp | 334 ++++--- .../obs-nvenc-test/obs-nvenc-test.cpp | 45 +- plugins/obs-qsv11/QSV_Encoder.cpp | 32 +- plugins/obs-qsv11/QSV_Encoder_Internal.cpp | 91 +- plugins/obs-qsv11/common_directx11.cpp | 84 +- plugins/obs-qsv11/common_utils.cpp | 73 +- plugins/obs-qsv11/common_utils_linux.cpp | 37 +- plugins/obs-qsv11/common_utils_windows.cpp | 12 +- .../obs-qsv11/obs-qsv-test/obs-qsv-test.cpp | 30 +- plugins/obs-text/gdiplus/obs-text.cpp | 122 ++- plugins/obs-vst/VSTPlugin.cpp | 9 +- plugins/obs-vst/obs-vst.cpp | 3 +- plugins/obs-webrtc/whip-output.cpp | 36 +- .../get-graphics-offsets/d3d8-offsets.cpp | 9 +- .../get-graphics-offsets/d3d9-offsets.cpp | 24 +- .../get-graphics-offsets/dxgi-offsets.cpp | 6 +- .../graphics-hook/d3d10-capture.cpp | 44 +- .../graphics-hook/d3d11-capture.cpp | 14 +- .../graphics-hook/d3d12-capture.cpp | 27 +- .../graphics-hook/d3d8-capture.cpp | 21 +- .../graphics-hook/d3d9-capture.cpp | 65 +- .../graphics-hook/d3d9-patches.hpp | 6 +- .../graphics-hook/dxgi-capture.cpp | 18 +- plugins/win-dshow/dshow-plugin.cpp | 3 +- plugins/win-dshow/encode-dstr.hpp | 9 +- .../virtualcam-module/placeholder.cpp | 6 +- .../virtualcam-module/virtualcam-filter.cpp | 33 +- plugins/win-dshow/win-dshow-encoder.cpp | 18 +- plugins/win-dshow/win-dshow.cpp | 218 +++-- plugins/win-wasapi/enum-wasapi.cpp | 15 +- plugins/win-wasapi/plugin-main.cpp | 9 +- plugins/win-wasapi/wasapi-notify.cpp | 15 +- plugins/win-wasapi/win-wasapi.cpp | 167 ++-- shared/obs-scripting/cstrcache.cpp | 3 +- shared/properties-view/properties-view.cpp | 304 ++++-- shared/properties-view/properties-view.hpp | 5 +- .../properties-view/spinbox-ignorewheel.cpp | 5 +- shared/qt/idian/components/ToggleSwitch.cpp | 21 +- shared/qt/idian/widgets/PropertiesList.cpp | 9 +- shared/qt/idian/widgets/Row.cpp | 33 +- .../slider-ignorewheel/slider-ignorewheel.cpp | 5 +- .../vertical-scroll-area.cpp | 3 +- shared/qt/wrappers/qt-wrappers.cpp | 38 +- test/win/test.cpp | 24 +- 261 files changed, 7839 insertions(+), 4143 deletions(-) diff --git a/frontend/OBSApp.cpp b/frontend/OBSApp.cpp index 6ade93c5d7ad95..89fa3ee435d6d6 100644 --- a/frontend/OBSApp.cpp +++ b/frontend/OBSApp.cpp @@ -143,8 +143,9 @@ UncleanLaunchAction handleUncleanShutdown(bool enableCrashUpload) QAccessibleInterface *alignmentSelectorFactory(const QString &classname, QObject *object) { if (classname == QLatin1String("AlignmentSelector")) { - if (auto *w = qobject_cast(object)) + if (auto *w = qobject_cast(object)) { return new AccessibleAlignmentSelector(w); + } } return nullptr; } @@ -154,8 +155,9 @@ 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}; bool pressed = event.type() == QEvent::MouseButtonPress; @@ -407,39 +409,51 @@ static bool MakeUserDirs() { char path[512]; - if (GetAppConfigPath(path, sizeof(path), "obs-studio/basic") <= 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/basic") <= 0) { return false; - if (!do_mkdir(path)) + } + if (!do_mkdir(path)) { return false; + } - if (GetAppConfigPath(path, sizeof(path), "obs-studio/logs") <= 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/logs") <= 0) { return false; - if (!do_mkdir(path)) + } + 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)) + } + if (!do_mkdir(path)) { return false; + } #ifdef _WIN32 - if (GetAppConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/crashes") <= 0) { return false; - if (!do_mkdir(path)) + } + if (!do_mkdir(path)) { return false; + } #endif #ifdef WHATSNEW_ENABLED - if (GetAppConfigPath(path, sizeof(path), "obs-studio/updates") <= 0) + if (GetAppConfigPath(path, sizeof(path), "obs-studio/updates") <= 0) { return false; - if (!do_mkdir(path)) + } + if (!do_mkdir(path)) { 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)) + } + if (!do_mkdir(path)) { return false; + } return true; } @@ -492,8 +506,9 @@ static bool MakeUserProfileDirs() bool OBSApp::UpdatePre22MultiviewLayout(const char *layout) { - if (!layout) + if (!layout) { return false; + } if (astrcmpi(layout, "horizontaltop") == 0) { config_set_int(userConfig, "BasicWindow", "MultiviewLayout", @@ -705,14 +720,16 @@ bool OBSApp::InitLocale() const char *lang = config_get_string(userConfig, "General", "Language"); bool userLocale = config_has_user_value(userConfig, "General", "Language"); - if (!userLocale || !lang || lang[0] == '\0') + if (!userLocale || !lang || lang[0] == '\0') { lang = DEFAULT_LANG; + } locale = lang; // set basic default application locale - if (!locale.empty()) + if (!locale.empty()) { QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_'))); + } string englishPath; if (!GetDataFilePath("locale/" DEFAULT_LANG ".ini", englishPath)) { @@ -728,30 +745,35 @@ bool OBSApp::InitLocale() bool defaultLang = astrcmpi(lang, DEFAULT_LANG) == 0; - if (userLocale && defaultLang) + if (userLocale && defaultLang) { return true; + } if (!userLocale && defaultLang) { for (auto &locale_ : GetPreferredLocales()) { - if (locale_ == lang) + if (locale_ == lang) { return true; + } stringstream file; file << "locale/" << locale_ << ".ini"; string path; - if (!GetDataFilePath(file.str().c_str(), path)) + if (!GetDataFilePath(file.str().c_str(), path)) { continue; + } - if (!text_lookup_add(textLookup, path.c_str())) + if (!text_lookup_add(textLookup, path.c_str())) { continue; + } blog(LOG_INFO, "Using preferred locale '%s'", locale_.c_str()); locale = locale_; // set application default locale to the new chosen one - if (!locale.empty()) + if (!locale.empty()) { QLocale::setDefault(QLocale(QString::fromStdString(locale).replace('-', '_'))); + } return true; } @@ -764,8 +786,9 @@ bool OBSApp::InitLocale() string path; if (GetDataFilePath(file.str().c_str(), path)) { - if (!text_lookup_add(textLookup, path.c_str())) + if (!text_lookup_add(textLookup, 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()); } @@ -788,11 +811,13 @@ void ParseBranchesJson(const std::string &jsonString, vector &out, for (const JsonBranch &json_branch : branches) { #ifdef _WIN32 - if (!json_branch.windows) + if (!json_branch.windows) { continue; + } #elif defined(__APPLE__) - if (!json_branch.macos) + if (!json_branch.macos) { continue; + } #endif UpdateBranch branch = { @@ -826,8 +851,9 @@ bool LoadBranchesFile(vector &out) } ParseBranchesJson(branchesText, out, error); - if (error.empty()) + if (error.empty()) { return !out.empty(); + } fail: blog(LOG_WARNING, "Loading branches from file failed: %s", error.c_str()); @@ -848,8 +874,9 @@ void OBSApp::SetBranchData(const string &data) return; } - if (!result.empty()) + if (!result.empty()) { updateBranches = result; + } branches_loaded = true; #else @@ -866,16 +893,18 @@ std::vector OBSApp::GetBranches() #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) if (!branches_loaded) { vector result; - if (LoadBranchesFile(result)) + if (LoadBranchesFile(result)) { updateBranches = result; + } branches_loaded = true; } #endif /* Copy additional branches to result (if any) */ - if (!updateBranches.empty()) + if (!updateBranches.empty()) { out.insert(out.end(), updateBranches.begin(), updateBranches.end()); + } return out; } @@ -889,8 +918,9 @@ OBSApp::OBSApp(int &argc, char **argv, profiler_name_store_t *store) /* fix float handling */ #if defined(Q_OS_UNIX) - if (!setlocale(LC_NUMERIC, "C")) + if (!setlocale(LC_NUMERIC, "C")) { blog(LOG_WARNING, "Failed to set LC_NUMERIC to C locale"); + } #endif #ifndef _WIN32 @@ -1051,14 +1081,18 @@ void OBSApp::AppInit() QAccessible::installFactory(alignmentSelectorFactory); - if (!MakeUserDirs()) + if (!MakeUserDirs()) { throw "Failed to create required user directories"; - if (!InitGlobalConfig()) + } + if (!InitGlobalConfig()) { throw "Failed to initialize global config"; - if (!InitLocale()) + } + if (!InitLocale()) { throw "Failed to load locale"; - if (!InitTheme()) + } + 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")); @@ -1082,13 +1116,15 @@ void OBSApp::AppInit() #ifdef _WIN32 bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking"); - if (disableAudioDucking) + if (disableAudioDucking) { DisableAudioDucking(true); + } #endif #ifdef __APPLE__ - if (config_get_bool(appConfig, "Video", "DisableOSXVSync")) + if (config_get_bool(appConfig, "Video", "DisableOSXVSync")) { EnableOSXVSync(false); + } #endif UpdateHotkeyFocusSetting(false); @@ -1096,8 +1132,9 @@ void OBSApp::AppInit() move_basic_to_profiles(); move_basic_to_scene_collections(); - if (!MakeUserProfileDirs()) + if (!MakeUserProfileDirs()) { throw "Failed to create profile directories"; + } } void OBSApp::checkForUncleanShutdown() @@ -1135,8 +1172,9 @@ 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); } @@ -1159,8 +1197,9 @@ void OBSApp::UpdateHotkeyFocusSetting(bool resetState) enableHotkeysOutOfFocus = false; } - if (resetState) + if (resetState) { ResetHotkeyState(applicationState() == Qt::ApplicationActive); + } } void OBSApp::DisableHotkeys() @@ -1228,8 +1267,9 @@ bool OBSApp::OBSInit() setAttribute(Qt::AA_DontCreateNativeWidgetSiblings); #endif - if (!StartupOBS(locale.c_str(), GetProfilerNameStore())) + if (!StartupOBS(locale.c_str(), GetProfilerNameStore())) { return false; + } libobs_initialized = true; @@ -1309,10 +1349,11 @@ string OBSApp::GetVersionString(bool platform) const if (platform) { ver << " ("; #ifdef _WIN32 - if (sizeof(void *) == 8) + if (sizeof(void *) == 8) { ver << "64-bit, "; - else + } else { ver << "32-bit, "; + } ver << "windows)"; #elif __APPLE__ @@ -1427,8 +1468,9 @@ OBS::LogFileState OBSApp::getLogFileState(OBS::LogFileType type) const bool OBSApp::TranslateString(const char *lookupVal, const char **out) const { for (obs_frontend_translate_ui_cb cb : translatorHooks) { - if (cb(lookupVal, out)) + if (cb(lookupVal, out)) { return true; + } } return text_lookup_getstr(App()->GetTextLookup(), lookupVal, out); @@ -1451,28 +1493,33 @@ bool OBSApp::notify(QObject *receiver, QEvent *e) QWindow *window; int windowType; - if (!receiver->isWidgetType()) + if (!receiver->isWidgetType()) { goto skip; + } - if (e->type() != QEvent::Show) + if (e->type() != QEvent::Show) { goto skip; + } w = qobject_cast(receiver); - if (!w->isWindow()) + if (!w->isWindow()) { goto skip; + } window = w->windowHandle(); - if (!window) + if (!window) { goto skip; + } windowType = window->flags() & Qt::WindowType::WindowType_Mask; if (windowType == Qt::WindowType::Dialog || windowType == Qt::WindowType::Window || windowType == Qt::WindowType::Tool) { OBSBasic *main = OBSBasic::Get(); - if (main) + if (main) { main->SetDisplayAffinity(window); + } } skip: @@ -1503,12 +1550,14 @@ static void FindBestFilename(string &strPath, bool noSpace) { int num = 2; - if (!os_file_exists(strPath.c_str())) + if (!os_file_exists(strPath.c_str())) { return; + } const char *ext = strrchr(strPath.c_str(), '.'); - if (!ext) + if (!ext) { return; + } int extStart = int(ext - strPath.c_str()); for (;;) { @@ -1517,8 +1566,9 @@ static void FindBestFilename(string &strPath, bool noSpace) numStr = noSpace ? "_" : " ("; numStr += to_string(num++); - if (!noSpace) + if (!noSpace) { numStr += ")"; + } testPath.insert(extStart, numStr); @@ -1534,8 +1584,9 @@ static void ensure_directory_exists(string &path) replace(path.begin(), path.end(), '\\', '/'); size_t last = path.rfind('/'); - if (last == string::npos) + if (last == string::npos) { return; + } string directory = path.substr(0, last); os_mkdirs(directory.c_str()); @@ -1562,26 +1613,30 @@ string GetFormatString(const char *format, const char *prefix, const char *suffi if (prefix && *prefix) { string str_prefix = prefix; - if (str_prefix.back() != ' ') + if (str_prefix.back() != ' ') { str_prefix += " "; + } size_t insert_pos = 0; size_t tmp; tmp = f.find_last_of('/'); - if (tmp != string::npos && tmp > insert_pos) + if (tmp != string::npos && tmp > insert_pos) { insert_pos = tmp + 1; + } tmp = f.find_last_of('\\'); - if (tmp != string::npos && tmp > insert_pos) + if (tmp != string::npos && tmp > insert_pos) { insert_pos = tmp + 1; + } f.insert(insert_pos, str_prefix); } if (suffix && *suffix) { - if (*suffix != ' ') + if (*suffix != ' ') { f += " "; + } f += suffix; } @@ -1593,14 +1648,15 @@ string GetFormatString(const char *format, const char *prefix, const char *suffi string GetFormatExt(const char *container) { string ext = container; - if (ext == "fragmented_mp4" || ext == "hybrid_mp4") + if (ext == "fragmented_mp4" || ext == "hybrid_mp4") { ext = "mp4"; - else if (ext == "fragmented_mov" || ext == "hybrid_mov") + } else if (ext == "fragmented_mov" || ext == "hybrid_mov") { ext = "mov"; - else if (ext == "hls") + } else if (ext == "hls") { ext = "m3u8"; - else if (ext == "mpegts") + } else if (ext == "mpegts") { ext = "ts"; + } return ext; } @@ -1612,10 +1668,11 @@ string GetOutputFilename(const char *path, const char *container, bool noSpace, os_dir_t *dir = path && path[0] ? os_opendir(path) : nullptr; if (!dir) { - if (main->isVisible()) + if (main->isVisible()) { OBSMessageBox::warning(main, QTStr("Output.BadPath.Title"), QTStr("Output.BadPath.Text")); - else + } else { main->SysTrayNotify(QTStr("Output.BadPath.Text"), QSystemTrayIcon::Warning); + } return ""; } @@ -1625,14 +1682,16 @@ string GetOutputFilename(const char *path, const char *container, bool noSpace, strPath += path; char lastChar = strPath.back(); - if (lastChar != '/' && lastChar != '\\') + if (lastChar != '/' && lastChar != '\\') { strPath += "/"; + } string ext = GetFormatExt(container); strPath += GenerateSpecifiedFilename(ext.c_str(), noSpace, format); ensure_directory_exists(strPath); - if (!overwrite) + if (!overwrite) { FindBestFilename(strPath, noSpace); + } return strPath; } @@ -1640,12 +1699,14 @@ string GetOutputFilename(const char *path, const char *container, bool noSpace, vector> GetLocaleNames() { string path; - if (!GetDataFilePath("locale.ini", path)) + if (!GetDataFilePath("locale.ini", path)) { throw "Could not find locale.ini path"; + } ConfigFile ini; - if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0) + if (ini.Open(path.c_str(), CONFIG_OPEN_EXISTING) != 0) { throw "Could not open locale.ini"; + } size_t sections = config_num_sections(ini); @@ -1726,8 +1787,9 @@ bool GetFileSafeName(const char *name, std::string &file) size_t len = os_utf8_to_wcs(name, base_len, nullptr, 0); std::wstring wfile; - if (!len) + if (!len) { return false; + } wfile.resize(len); os_utf8_to_wcs(name, base_len, &wfile[0], len + 1); @@ -1742,12 +1804,14 @@ bool GetFileSafeName(const char *name, std::string &file) } } - if (wfile.size() == 0) + if (wfile.size() == 0) { wfile = L"characters_only"; + } len = os_wcs_to_utf8(wfile.c_str(), wfile.size(), nullptr, 0); - if (!len) + if (!len) { return false; + } file.resize(len); os_wcs_to_utf8(wfile.c_str(), wfile.size(), &file[0], len + 1); @@ -1762,8 +1826,9 @@ bool GetClosestUnusedFileName(std::string &path, const char *extension) path += extension; } - if (!os_file_exists(path.c_str())) + if (!os_file_exists(path.c_str())) { return true; + } int index = 1; @@ -1782,8 +1847,9 @@ bool GetClosestUnusedFileName(std::string &path, const char *extension) bool WindowPositionValid(QRect rect) { for (QScreen *screen : QGuiApplication::screens()) { - if (screen->availableGeometry().intersects(rect)) + if (screen->availableGeometry().intersects(rect)) { return true; + } } return false; } @@ -1943,8 +2009,9 @@ void OBSApp::applicationShutdown() noexcept { #ifdef _WIN32 bool disableAudioDucking = config_get_bool(appConfig, "Audio", "DisableAudioDucking"); - if (disableAudioDucking) + if (disableAudioDucking) { DisableAudioDucking(false); + } #else auto disconnectSignal = [this](std::array &fileDescriptor, QPointer ¬ifier) -> void { @@ -1964,8 +2031,9 @@ void OBSApp::applicationShutdown() noexcept #ifdef __APPLE__ bool vsyncDisabled = config_get_bool(appConfig, "Video", "DisableOSXVSync"); bool resetVSync = config_get_bool(appConfig, "Video", "ResetOSXVSyncOnExit"); - if (vsyncDisabled && resetVSync) + if (vsyncDisabled && resetVSync) { EnableOSXVSync(true); + } #endif os_inhibit_sleep_set_active(sleepInhibitor, false); diff --git a/frontend/OBSApp.hpp b/frontend/OBSApp.hpp index 8620730846aec5..1bbd2ceeb6dcfa 100644 --- a/frontend/OBSApp.hpp +++ b/frontend/OBSApp.hpp @@ -201,20 +201,25 @@ private slots: inline void IncrementSleepInhibition() { - if (!sleepInhibitor) + if (!sleepInhibitor) { return; - if (sleepInhibitRefs++ == 0) + } + if (sleepInhibitRefs++ == 0) { os_inhibit_sleep_set_active(sleepInhibitor, true); + } } inline void DecrementSleepInhibition() { - if (!sleepInhibitor) + if (!sleepInhibitor) { return; - if (sleepInhibitRefs == 0) + } + if (sleepInhibitRefs == 0) { return; - if (--sleepInhibitRefs == 0) + } + if (--sleepInhibitRefs == 0) { os_inhibit_sleep_set_active(sleepInhibitor, false); + } } inline void PushUITranslation(obs_frontend_translate_ui_cb cb) { translatorHooks.emplace_front(cb); } diff --git a/frontend/OBSApp_Themes.cpp b/frontend/OBSApp_Themes.cpp index 94b8d69d5d53c8..62ce6729af90fb 100644 --- a/frontend/OBSApp_Themes.cpp +++ b/frontend/OBSApp_Themes.cpp @@ -45,16 +45,18 @@ struct CFParser { static optional ParseThemeMeta(const QString &path) { QFile themeFile(path); - if (!themeFile.open(QIODeviceBase::ReadOnly)) + if (!themeFile.open(QIODeviceBase::ReadOnly)) { return nullopt; + } OBSTheme meta; const QByteArray data = themeFile.readAll(); CFParser cfp; int ret; - if (!cf_parser_parse(cfp, data.constData(), QT_TO_UTF8(path))) + if (!cf_parser_parse(cfp, data.constData(), QT_TO_UTF8(path))) { return nullopt; + } if (cf_token_is(cfp, "@") || cf_go_to_token(cfp, "@", nullptr)) { while (cf_next_token(cfp)) { @@ -62,58 +64,69 @@ static optional ParseThemeMeta(const QString &path) break; } - if (!cf_go_to_token(cfp, "@", nullptr)) + if (!cf_go_to_token(cfp, "@", nullptr)) { return nullopt; + } } - if (!cf_token_is(cfp, "OBSThemeMeta")) + if (!cf_token_is(cfp, "OBSThemeMeta")) { return nullopt; + } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return nullopt; + } - if (!cf_token_is(cfp, "{")) + if (!cf_token_is(cfp, "{")) { return nullopt; + } for (;;) { - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return nullopt; + } ret = cf_token_is_type(cfp, CFTOKEN_NAME, "name", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { break; + } string name(cfp->cur_token->str.array, cfp->cur_token->str.len); ret = cf_next_token_should_be(cfp, ":", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { continue; + } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return nullopt; + } ret = cf_token_is_type(cfp, CFTOKEN_STRING, "value", ";"); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { continue; + } BPtr str = cf_literal_to_str(cfp->cur_token->str.array, cfp->cur_token->str.len); if (str) { - if (name == "dark") + if (name == "dark") { meta.isDark = strcmp(str, "true") == 0; - else if (name == "extends") + } else if (name == "extends") { meta.extends = str; - else if (name == "author") + } else if (name == "author") { meta.author = str; - else if (name == "id") + } else if (name == "id") { meta.id = str; - else if (name == "name") + } else if (name == "name") { meta.name = str; + } } - if (!cf_go_to_token(cfp, ";", nullptr)) + if (!cf_go_to_token(cfp, ";", nullptr)) { return nullopt; + } } } @@ -138,22 +151,27 @@ static bool ParseVarName(CFParser &cfp, QString &value) int ret; ret = cf_next_token_should_be(cfp, "(", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { return false; + } ret = cf_next_token_should_be(cfp, "-", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { return false; + } ret = cf_next_token_should_be(cfp, "-", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { return false; - if (!cf_next_token(cfp)) + } + if (!cf_next_token(cfp)) { return false; + } 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) + if (ret != PARSE_SUCCESS) { return false; + } return !value.isEmpty(); } @@ -165,35 +183,40 @@ static QColor ParseColor(CFParser &cfp) QColor res(QColor::Invalid); if (cf_token_is(cfp, "#")) { - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return res; + } color = strtol(cfp->cur_token->str.array, nullptr, 16); } else if (cf_token_is(cfp, "rgb")) { int ret = cf_next_token_should_be(cfp, "(", ";", nullptr); - if (ret != PARSE_SUCCESS || !cf_next_token(cfp)) + if (ret != PARSE_SUCCESS || !cf_next_token(cfp)) { return res; + } array = cfp->cur_token->str.array; color |= strtol(array, nullptr, 10) << 16; ret = cf_next_token_should_be(cfp, ",", ";", nullptr); - if (ret != PARSE_SUCCESS || !cf_next_token(cfp)) + if (ret != PARSE_SUCCESS || !cf_next_token(cfp)) { return res; + } array = cfp->cur_token->str.array; color |= strtol(array, nullptr, 10) << 8; ret = cf_next_token_should_be(cfp, ",", ";", nullptr); - if (ret != PARSE_SUCCESS || !cf_next_token(cfp)) + if (ret != PARSE_SUCCESS || !cf_next_token(cfp)) { return res; + } array = cfp->cur_token->str.array; color |= strtol(array, nullptr, 10); ret = cf_next_token_should_be(cfp, ")", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { return res; + } } else if (cf_token_is(cfp, "bikeshed")) { color |= QRandomGenerator::global()->bounded(INT8_MAX) << 16; color |= QRandomGenerator::global()->bounded(INT8_MAX) << 8; @@ -207,14 +230,17 @@ static QColor ParseColor(CFParser &cfp) static bool ParseMath(CFParser &cfp, QStringList &values, vector &vars) { int ret = cf_next_token_should_be(cfp, "(", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { return false; - if (!cf_next_token(cfp)) + } + if (!cf_next_token(cfp)) { return false; + } while (!cf_token_is(cfp, ")")) { - if (cf_token_is(cfp, ";")) + if (cf_token_is(cfp, ";")) { break; + } if (cf_token_is(cfp, "calc") || cf_token_is(cfp, "max") || cf_token_is(cfp, "min")) { /* Internal math operations do not have proper names. @@ -225,15 +251,17 @@ static bool ParseMath(CFParser &cfp, QStringList &values, vectorgenerate64()); OBSThemeVariable::VariableType varType; - if (cf_token_is(cfp, "calc")) + if (cf_token_is(cfp, "calc")) { varType = OBSThemeVariable::Calc; - else if (cf_token_is(cfp, "max")) + } else if (cf_token_is(cfp, "max")) { varType = OBSThemeVariable::Max; - else if (cf_token_is(cfp, "min")) + } else if (cf_token_is(cfp, "min")) { varType = OBSThemeVariable::Min; + } - if (!ParseMath(cfp, subvalues, vars)) + if (!ParseMath(cfp, subvalues, vars)) { return false; + } var.type = varType; var.value = subvalues; @@ -241,16 +269,18 @@ static bool ParseMath(CFParser &cfp, QStringList &values, vectorcur_token->str.array, cfp->cur_token->str.len); } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return false; + } } return !values.isEmpty(); @@ -263,43 +293,54 @@ static vector ParseThemeVariables(const char *themeData) std::vector vars; - if (!cf_parser_parse(cfp, themeData, nullptr)) + if (!cf_parser_parse(cfp, themeData, nullptr)) { return vars; + } - if (!cf_token_is(cfp, "@") && !cf_go_to_token(cfp, "@", nullptr)) + if (!cf_token_is(cfp, "@") && !cf_go_to_token(cfp, "@", nullptr)) { return vars; + } while (cf_next_token(cfp)) { - if (cf_token_is(cfp, "OBSThemeVars")) + if (cf_token_is(cfp, "OBSThemeVars")) { break; + } - if (!cf_go_to_token(cfp, "@", nullptr)) + if (!cf_go_to_token(cfp, "@", nullptr)) { return vars; + } } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return {}; + } - if (!cf_token_is(cfp, "{")) + if (!cf_token_is(cfp, "{")) { return {}; + } for (;;) { - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return vars; + } - if (!cf_token_is(cfp, "-")) + if (!cf_token_is(cfp, "-")) { return vars; + } ret = cf_next_token_should_be(cfp, "-", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { continue; + } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return vars; + } ret = cf_token_is_type(cfp, CFTOKEN_NAME, "key", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { break; + } QString key = QString::fromUtf8(cfp->cur_token->str.array, cfp->cur_token->str.len); OBSThemeVariable var; @@ -318,16 +359,19 @@ static vector ParseThemeVariables(const char *themeData) } ret = cf_next_token_should_be(cfp, ":", ";", nullptr); - if (ret != PARSE_SUCCESS) + if (ret != PARSE_SUCCESS) { continue; + } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return vars; + } /* Special values passed to the theme by OBS are prefixed with 'obs', so we * prevent theme variables from using it as a prefix. */ - if (key.startsWith("obs")) + if (key.startsWith("obs")) { continue; + } if (cfp->cur_token->type == CFTOKEN_NUM) { const char *ch = cfp->cur_token->str.array; @@ -348,31 +392,35 @@ static vector ParseThemeVariables(const char *themeData) } } else if (cf_token_is(cfp, "rgb") || cf_token_is(cfp, "#") || cf_token_is(cfp, "bikeshed")) { QColor color = ParseColor(cfp); - if (!color.isValid()) + if (!color.isValid()) { continue; + } var.value = color; var.type = OBSThemeVariable::Color; } else if (cf_token_is(cfp, "var")) { QString value; - if (!ParseVarName(cfp, value)) + if (!ParseVarName(cfp, value)) { continue; + } var.value = value; var.type = OBSThemeVariable::Alias; } else if (cf_token_is(cfp, "calc") || cf_token_is(cfp, "max") || cf_token_is(cfp, "min")) { QStringList values; - if (cf_token_is(cfp, "calc")) + if (cf_token_is(cfp, "calc")) { var.type = OBSThemeVariable::Calc; - else if (cf_token_is(cfp, "max")) + } else if (cf_token_is(cfp, "max")) { var.type = OBSThemeVariable::Max; - else if (cf_token_is(cfp, "min")) + } else if (cf_token_is(cfp, "min")) { var.type = OBSThemeVariable::Min; + } - if (!ParseMath(cfp, values, vars)) + if (!ParseMath(cfp, values, vars)) { continue; + } var.value = values; } else { @@ -381,8 +429,9 @@ static vector ParseThemeVariables(const char *themeData) var.value = QString::fromUtf8(strVal.Get()); } - if (!cf_next_token(cfp)) + if (!cf_next_token(cfp)) { return vars; + } if (cf_token_is(cfp, "!") && cf_next_token_should_be(cfp, "editable", nullptr, nullptr) == PARSE_SUCCESS) { @@ -397,8 +446,9 @@ 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; + } } return vars; @@ -419,8 +469,9 @@ void OBSApp::FindThemes() QDirIterator it(QString::fromStdString(themeDir), filters, QDir::Files); while (it.hasNext()) { auto theme = ParseThemeMeta(it.next()); - if (theme && !themes.contains(theme->id)) + if (theme && !themes.contains(theme->id)) { themes[theme->id] = std::move(*theme); + } } } @@ -431,8 +482,9 @@ void OBSApp::FindThemes() while (it.hasNext()) { auto theme = ParseThemeMeta(it.next()); - if (theme && !themes.contains(theme->id)) + if (theme && !themes.contains(theme->id)) { themes[theme->id] = std::move(*theme); + } } } @@ -475,8 +527,9 @@ void OBSApp::FindThemes() } /* 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; @@ -497,8 +550,9 @@ void OBSApp::FindThemes() static bool ResolveVariable(const QHash &vars, OBSThemeVariable &var) { - if (var.type != OBSThemeVariable::Alias) + if (var.type != OBSThemeVariable::Alias) { return true; + } QString key = var.value.toString(); while (vars[key].type == OBSThemeVariable::Alias) { @@ -626,14 +680,15 @@ static QString EvalMath(const QHash &vars, const OBST double val = numeric_limits::quiet_NaN(); if (type == OBSThemeVariable::Calc) { - if (opt == "+") + if (opt == "+") { val = d1 + d2; - else if (opt == "-") + } else if (opt == "-") { val = d1 - d2; - else if (opt == "*") + } else if (opt == "*") { val = d1 * d2; - else if (opt == "/") + } else if (opt == "/") { val = d1 / d2; + } if (!isnormal(val)) { blog(LOG_ERROR, "Invalid calc() resulted in non-normal number: %f %s %f = %f", d1, @@ -650,10 +705,11 @@ static QString EvalMath(const QHash &vars, const OBST QString result = QString::number(val, 'f', isInteger ? 0 : -1); /* Carry-over suffix */ - if (!val1.suffix.isEmpty()) + if (!val1.suffix.isEmpty()) { result += val1.suffix; - else if (!val2.suffix.isEmpty()) + } else if (!val2.suffix.isEmpty()) { result += val2.suffix; + } return result; } @@ -689,8 +745,9 @@ static QString PrepareQSS(const QHash &vars, const QS for (const OBSThemeVariable &var_ : vars) { OBSThemeVariable var(var_); - if (!ResolveVariable(vars, var)) + if (!ResolveVariable(vars, var)) { continue; + } QString needle = needleTemplate.arg(var_.name); QString replace; @@ -708,8 +765,9 @@ static QString PrepareQSS(const QHash &vars, const QS bool isInteger = ceill(val) == val; replace = QString::number(val, 'f', isInteger ? 0 : -1); - if (!var.suffix.isEmpty()) + if (!var.suffix.isEmpty()) { replace += var.suffix; + } } else { replace = value.toString(); } @@ -746,22 +804,27 @@ static QPalette PreparePalette(const QHash &vars, con static QHash roleMap; static QHash groupMap; - if (roleMap.empty()) + if (roleMap.empty()) { FillEnumMap(roleMap); - if (groupMap.empty()) + } + if (groupMap.empty()) { FillEnumMap(groupMap); + } QPalette pal(defaultPalette); for (const OBSThemeVariable &var_ : vars) { - if (!var_.name.startsWith("palette_")) + if (!var_.name.startsWith("palette_")) { continue; - if (var_.name.count("_") < 1 || var_.name.count("_") > 2) + } + if (var_.name.count("_") < 1 || var_.name.count("_") > 2) { 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. * Format is: palette_[_] */ @@ -815,8 +878,9 @@ static double getPaddingForDensityId(int id) OBSTheme *OBSApp::GetTheme(const QString &name) { - if (!themes.contains(name)) + if (!themes.contains(name)) { return nullptr; + } return &themes[name]; } @@ -824,8 +888,9 @@ OBSTheme *OBSApp::GetTheme(const QString &name) bool OBSApp::SetTheme(const QString &name) { OBSTheme *theme = GetTheme(name); - if (!theme) + if (!theme) { return false; + } if (themeWatcher) { themeWatcher->blockSignals(true); @@ -860,10 +925,12 @@ bool OBSApp::SetTheme(const QString &name) /* Find and add high contrast adjustment layer if available */ if (HighContrastEnabled()) { for (const OBSTheme &theme_ : themes) { - if (!theme_.isHighContrast) + if (!theme_.isHighContrast) { continue; - if (theme_.parent != theme->id) + } + if (theme_.parent != theme->id) { continue; + } themeIds << theme_.id; break; } @@ -876,8 +943,9 @@ bool OBSApp::SetTheme(const QString &name) QFile file(cur->location); filenames << file.fileName(); - if (!file.open(QIODeviceBase::ReadOnly)) + if (!file.open(QIODeviceBase::ReadOnly)) { return false; + } const QByteArray content = file.readAll(); for (OBSThemeVariable &var : ParseThemeVariables(content.constData())) { diff --git a/frontend/OBSStudioAPI.cpp b/frontend/OBSStudioAPI.cpp index 76678992f305cf..80e8f88d860fd0 100644 --- a/frontend/OBSStudioAPI.cpp +++ b/frontend/OBSStudioAPI.cpp @@ -17,8 +17,9 @@ inline size_t GetCallbackIdx(std::vector> &callbacks, T cal { 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; + } } return (size_t)-1; @@ -46,8 +47,9 @@ void OBSStudioAPI::obs_frontend_get_scenes(struct obs_frontend_source_list *sour OBSScene scene = GetOBSRef(item); obs_source_t *source = obs_scene_get_source(scene); - if (obs_source_get_ref(source) != nullptr) + if (obs_source_get_ref(source) != nullptr) { da_push_back(sources->sources, &source); + } } } @@ -77,8 +79,9 @@ void OBSStudioAPI::obs_frontend_get_transitions(struct obs_frontend_source_list for (const auto &[uuid, transition] : main->transitions) { obs_source_t *source = transition; - if (obs_source_get_ref(source) != nullptr) + if (obs_source_get_ref(source) != nullptr) { da_push_back(sources->sources, &source); + } } } @@ -275,8 +278,9 @@ bool OBSStudioAPI::obs_frontend_recording_split_file() bool OBSStudioAPI::obs_frontend_recording_add_chapter(const char *name) { - 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); @@ -378,15 +382,17 @@ bool OBSStudioAPI::obs_frontend_add_custom_qdock(const char *id, void *dock) void OBSStudioAPI::obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data) { size_t idx = GetCallbackIdx(callbacks, callback, private_data); - if (idx == (size_t)-1) + if (idx == (size_t)-1) { callbacks.emplace_back(callback, private_data); + } } void OBSStudioAPI::obs_frontend_remove_event_callback(obs_frontend_event_cb callback, void *private_data) { size_t idx = GetCallbackIdx(callbacks, callback, private_data); - if (idx == (size_t)-1) + if (idx == (size_t)-1) { return; + } callbacks.erase(callbacks.begin() + idx); } @@ -395,8 +401,9 @@ obs_output_t *OBSStudioAPI::obs_frontend_get_streaming_output() { auto multitrackVideo = main->outputHandler->multitrackVideo.get(); auto mtvOutput = multitrackVideo ? obs_output_get_ref(multitrackVideo->StreamingOutput()) : nullptr; - if (mtvOutput) + if (mtvOutput) { return mtvOutput; + } OBSOutput output = main->outputHandler->streamOutput.Get(); return obs_output_get_ref(output); @@ -438,14 +445,15 @@ void OBSStudioAPI::obs_frontend_open_projector(const char *type, int monitor, co name ? name : "", }; if (type) { - if (astrcmpi(type, "Source") == 0) + if (astrcmpi(type, "Source") == 0) { proj.type = ProjectorType::Source; - else if (astrcmpi(type, "Scene") == 0) + } else if (astrcmpi(type, "Scene") == 0) { proj.type = ProjectorType::Scene; - else if (astrcmpi(type, "StudioProgram") == 0) + } else if (astrcmpi(type, "StudioProgram") == 0) { proj.type = ProjectorType::StudioProgram; - else if (astrcmpi(type, "Multiview") == 0) + } else if (astrcmpi(type, "Multiview") == 0) { proj.type = ProjectorType::Multiview; + } } QMetaObject::invokeMethod(main, "OpenSavedProjector", WaitConnection(), Q_ARG(SavedProjectorInfo *, &proj)); } @@ -468,15 +476,17 @@ void OBSStudioAPI::obs_frontend_defer_save_end() void OBSStudioAPI::obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data) { size_t idx = GetCallbackIdx(saveCallbacks, callback, private_data); - if (idx == (size_t)-1) + if (idx == (size_t)-1) { saveCallbacks.emplace_back(callback, private_data); + } } void OBSStudioAPI::obs_frontend_remove_save_callback(obs_frontend_save_cb callback, void *private_data) { size_t idx = GetCallbackIdx(saveCallbacks, callback, private_data); - if (idx == (size_t)-1) + if (idx == (size_t)-1) { return; + } saveCallbacks.erase(saveCallbacks.begin() + idx); } @@ -484,15 +494,17 @@ void OBSStudioAPI::obs_frontend_remove_save_callback(obs_frontend_save_cb callba void OBSStudioAPI::obs_frontend_add_preload_callback(obs_frontend_save_cb callback, void *private_data) { size_t idx = GetCallbackIdx(preloadCallbacks, callback, private_data); - if (idx == (size_t)-1) + if (idx == (size_t)-1) { preloadCallbacks.emplace_back(callback, private_data); + } } void OBSStudioAPI::obs_frontend_remove_preload_callback(obs_frontend_save_cb callback, void *private_data) { size_t idx = GetCallbackIdx(preloadCallbacks, callback, private_data); - if (idx == (size_t)-1) + if (idx == (size_t)-1) { return; + } preloadCallbacks.erase(preloadCallbacks.begin() + idx); } @@ -544,8 +556,9 @@ bool OBSStudioAPI::obs_frontend_preview_enabled() void OBSStudioAPI::obs_frontend_set_preview_enabled(bool enable) { - if (main->previewEnabled != enable) + if (main->previewEnabled != enable) { main->EnablePreviewDisplay(enable); + } } obs_source_t *OBSStudioAPI::obs_frontend_get_current_preview_scene() @@ -666,8 +679,9 @@ void OBSStudioAPI::obs_frontend_get_canvases(obs_frontend_canvas_list *canvas_li { for (const auto &canvas : main->canvases) { obs_canvas_t *ref = obs_canvas_get_ref(canvas); - if (ref) + if (ref) { da_push_back(canvas_list->canvases, &ref); + } } } @@ -709,8 +723,9 @@ void OBSStudioAPI::on_save(obs_data_t *settings) void OBSStudioAPI::on_event(enum obs_frontend_event event) { if (main->disableSaving && event != OBS_FRONTEND_EVENT_SCENE_COLLECTION_CLEANUP && - event != OBS_FRONTEND_EVENT_EXIT) + event != OBS_FRONTEND_EVENT_EXIT) { return; + } for (size_t i = callbacks.size(); i > 0; i--) { auto cb = callbacks[i - 1]; diff --git a/frontend/api/obs-frontend-api.cpp b/frontend/api/obs-frontend-api.cpp index fa72ba7968e2c0..9c6b5eac12cbfd 100644 --- a/frontend/api/obs-frontend-api.cpp +++ b/frontend/api/obs-frontend-api.cpp @@ -32,11 +32,13 @@ static char **convert_string_list(vector &strings) size += string_data_offset; - for (auto &str : strings) + for (auto &str : strings) { size += str.size() + 1; + } - if (!size) + if (!size) { return 0; + } out = (uint8_t *)bmalloc(size); ptr_list = (char **)out; @@ -73,8 +75,9 @@ void *obs_frontend_get_system_tray(void) char **obs_frontend_get_scene_names(void) { - if (!callbacks_valid()) + if (!callbacks_valid()) { return NULL; + } struct obs_frontend_source_list sources = {}; vector names; @@ -92,8 +95,9 @@ char **obs_frontend_get_scene_names(void) void obs_frontend_get_scenes(struct obs_frontend_source_list *sources) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_get_scenes(sources); + } } obs_source_t *obs_frontend_get_current_scene(void) @@ -103,14 +107,16 @@ obs_source_t *obs_frontend_get_current_scene(void) void obs_frontend_set_current_scene(obs_source_t *scene) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_current_scene(scene); + } } void obs_frontend_get_transitions(struct obs_frontend_source_list *sources) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_get_transitions(sources); + } } obs_source_t *obs_frontend_get_current_transition(void) @@ -120,8 +126,9 @@ obs_source_t *obs_frontend_get_current_transition(void) void obs_frontend_set_current_transition(obs_source_t *transition) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_current_transition(transition); + } } int obs_frontend_get_transition_duration(void) @@ -131,14 +138,16 @@ int obs_frontend_get_transition_duration(void) void obs_frontend_set_transition_duration(int duration) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_transition_duration(duration); + } } void obs_frontend_release_tbar(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_release_tbar(); + } } int obs_frontend_get_tbar_position(void) @@ -148,14 +157,16 @@ int obs_frontend_get_tbar_position(void) void obs_frontend_set_tbar_position(int position) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_tbar_position(position); + } } char **obs_frontend_get_scene_collections(void) { - if (!callbacks_valid()) + if (!callbacks_valid()) { return nullptr; + } vector strings; c->obs_frontend_get_scene_collections(strings); @@ -169,8 +180,9 @@ char *obs_frontend_get_current_scene_collection(void) void obs_frontend_set_current_scene_collection(const char *collection) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_current_scene_collection(collection); + } } bool obs_frontend_add_scene_collection(const char *name) @@ -180,8 +192,9 @@ bool obs_frontend_add_scene_collection(const char *name) char **obs_frontend_get_profiles(void) { - if (!callbacks_valid()) + if (!callbacks_valid()) { return nullptr; + } vector strings; c->obs_frontend_get_profiles(strings); @@ -200,38 +213,44 @@ char *obs_frontend_get_current_profile_path(void) void obs_frontend_set_current_profile(const char *profile) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_current_profile(profile); + } } void obs_frontend_create_profile(const char *name) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_create_profile(name); + } } void obs_frontend_duplicate_profile(const char *name) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_duplicate_profile(name); + } } void obs_frontend_delete_profile(const char *profile) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_delete_profile(profile); + } } void obs_frontend_streaming_start(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_streaming_start(); + } } void obs_frontend_streaming_stop(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_streaming_stop(); + } } bool obs_frontend_streaming_active(void) @@ -241,14 +260,16 @@ bool obs_frontend_streaming_active(void) void obs_frontend_recording_start(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_recording_start(); + } } void obs_frontend_recording_stop(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_recording_stop(); + } } bool obs_frontend_recording_active(void) @@ -258,8 +279,9 @@ bool obs_frontend_recording_active(void) void obs_frontend_recording_pause(bool pause) { - if (!!callbacks_valid()) + if (!!callbacks_valid()) { c->obs_frontend_recording_pause(pause); + } } bool obs_frontend_recording_paused(void) @@ -279,20 +301,23 @@ bool obs_frontend_recording_add_chapter(const char *name) void obs_frontend_replay_buffer_start(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_replay_buffer_start(); + } } void obs_frontend_replay_buffer_save(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_replay_buffer_save(); + } } void obs_frontend_replay_buffer_stop(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_replay_buffer_stop(); + } } bool obs_frontend_replay_buffer_active(void) @@ -307,8 +332,9 @@ void *obs_frontend_add_tools_menu_qaction(const char *name) void obs_frontend_add_tools_menu_item(const char *name, obs_frontend_cb callback, void *private_data) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_add_tools_menu_item(name, callback, private_data); + } } bool obs_frontend_add_dock_by_id(const char *id, const char *title, void *widget) @@ -318,8 +344,9 @@ bool obs_frontend_add_dock_by_id(const char *id, const char *title, void *widget void obs_frontend_remove_dock(const char *id) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_remove_dock(id); + } } bool obs_frontend_add_custom_qdock(const char *id, void *dock) @@ -329,14 +356,16 @@ bool obs_frontend_add_custom_qdock(const char *id, void *dock) void obs_frontend_add_event_callback(obs_frontend_event_cb callback, void *private_data) { - if (callbacks_valid()) + 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) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_remove_event_callback(callback, private_data); + } } obs_output_t *obs_frontend_get_streaming_output(void) @@ -378,62 +407,72 @@ config_t *obs_frontend_get_global_config(void) void obs_frontend_open_projector(const char *type, int monitor, const char *geometry, const char *name) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_open_projector(type, monitor, geometry, name); + } } void obs_frontend_save(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_save(); + } } void obs_frontend_defer_save_begin(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_defer_save_begin(); + } } void obs_frontend_defer_save_end(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_defer_save_end(); + } } void obs_frontend_add_save_callback(obs_frontend_save_cb callback, void *private_data) { - if (callbacks_valid()) + 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) { - if (callbacks_valid()) + 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) { - if (callbacks_valid()) + 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) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_remove_preload_callback(callback, private_data); + } } void obs_frontend_push_ui_translation(obs_frontend_translate_ui_cb translate) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_push_ui_translation(translate); + } } void obs_frontend_pop_ui_translation(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_pop_ui_translation(); + } } obs_service_t *obs_frontend_get_streaming_service(void) @@ -443,14 +482,16 @@ obs_service_t *obs_frontend_get_streaming_service(void) void obs_frontend_set_streaming_service(obs_service_t *service) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_streaming_service(service); + } } void obs_frontend_save_streaming_service(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_save_streaming_service(); + } } bool obs_frontend_preview_program_mode_active(void) @@ -460,14 +501,16 @@ bool obs_frontend_preview_program_mode_active(void) void obs_frontend_set_preview_program_mode(bool enable) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_preview_program_mode(enable); + } } void obs_frontend_preview_program_trigger_transition(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_preview_program_trigger_transition(); + } } bool obs_frontend_preview_enabled(void) @@ -477,8 +520,9 @@ bool obs_frontend_preview_enabled(void) void obs_frontend_set_preview_enabled(bool enable) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_preview_enabled(enable); + } } obs_source_t *obs_frontend_get_current_preview_scene(void) @@ -488,20 +532,23 @@ obs_source_t *obs_frontend_get_current_preview_scene(void) void obs_frontend_set_current_preview_scene(obs_source_t *scene) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_set_current_preview_scene(scene); + } } void obs_frontend_take_screenshot(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_take_screenshot(); + } } void obs_frontend_take_source_screenshot(obs_source_t *source) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_take_source_screenshot(source); + } } obs_output_t *obs_frontend_get_virtualcam_output(void) @@ -511,14 +558,16 @@ obs_output_t *obs_frontend_get_virtualcam_output(void) void obs_frontend_start_virtualcam(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_start_virtualcam(); + } } void obs_frontend_stop_virtualcam(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_stop_virtualcam(); + } } bool obs_frontend_virtualcam_active(void) @@ -528,32 +577,37 @@ bool obs_frontend_virtualcam_active(void) void obs_frontend_reset_video(void) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_reset_video(); + } } void obs_frontend_open_source_properties(obs_source_t *source) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_open_source_properties(source); + } } void obs_frontend_open_source_filters(obs_source_t *source) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_open_source_filters(source); + } } void obs_frontend_open_source_interaction(obs_source_t *source) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_open_source_interaction(source); + } } void obs_frontend_open_sceneitem_edit_transform(obs_sceneitem_t *item) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_open_sceneitem_edit_transform(item); + } } char *obs_frontend_get_current_record_output_path(void) @@ -589,14 +643,16 @@ char *obs_frontend_get_last_replay(void) 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()) + if (callbacks_valid()) { c->obs_frontend_add_undo_redo_action(name, undo, redo, undo_data, redo_data, repeatable); + } } void obs_frontend_get_canvases(obs_frontend_canvas_list *canvas_list) { - if (callbacks_valid()) + if (callbacks_valid()) { c->obs_frontend_get_canvases(canvas_list); + } } obs_canvas_t *obs_frontend_add_canvas(const char *name, obs_video_info *ovi, int flags) diff --git a/frontend/components/AbsoluteSlider.cpp b/frontend/components/AbsoluteSlider.cpp index 12eec4898426f9..7767c9292a8c6c 100644 --- a/frontend/components/AbsoluteSlider.cpp +++ b/frontend/components/AbsoluteSlider.cpp @@ -44,10 +44,11 @@ void AbsoluteSlider::mouseMoveEvent(QMouseEvent *event) { int val = posToRangeValue(event); - if (val > maximum()) + if (val > maximum()) { val = maximum(); - else if (val < minimum()) + } else if (val < minimum()) { val = minimum(); + } emit absoluteSliderHovered(val); diff --git a/frontend/components/AudioCaptureToolbar.cpp b/frontend/components/AudioCaptureToolbar.cpp index f61eb6eae1d738..edfc5ea34b1d47 100644 --- a/frontend/components/AudioCaptureToolbar.cpp +++ b/frontend/components/AudioCaptureToolbar.cpp @@ -21,8 +21,9 @@ void AudioCaptureToolbar::Init() ui->activateButton = nullptr; obs_module_t *mod = get_os_module("win-wasapi", "mac-capture", "linux-pulseaudio"); - if (!mod) + if (!mod) { return; + } const char *device_str = get_os_text(mod, "Device", "CoreAudio.Device", "Device"); ui->deviceLabel->setText(device_str); diff --git a/frontend/components/ComboSelectToolbar.cpp b/frontend/components/ComboSelectToolbar.cpp index 77a0364d721280..7eccf6e2fd45da 100644 --- a/frontend/components/ComboSelectToolbar.cpp +++ b/frontend/components/ComboSelectToolbar.cpp @@ -31,8 +31,9 @@ int FillPropertyCombo(QComboBox *c, obs_property_t *p, const std::string &cur_id id = val ? val : ""; } - if (cur_id == id) + if (cur_id == id) { cur_idx = (int)i; + } c->addItem(name, id.c_str()); } diff --git a/frontend/components/DeviceCaptureToolbar.cpp b/frontend/components/DeviceCaptureToolbar.cpp index c6917945340cd3..76bef26ab8bb52 100644 --- a/frontend/components/DeviceCaptureToolbar.cpp +++ b/frontend/components/DeviceCaptureToolbar.cpp @@ -18,8 +18,9 @@ DeviceCaptureToolbar::DeviceCaptureToolbar(QWidget *parent, OBSSource source) active = obs_data_get_bool(settings, "active"); obs_module_t *mod = obs_get_module("win-dshow"); - if (!mod) + if (!mod) { return; + } activateText = obs_module_get_locale_text(mod, "Activate"); deactivateText = obs_module_get_locale_text(mod, "Deactivate"); diff --git a/frontend/components/DisplayCaptureToolbar.cpp b/frontend/components/DisplayCaptureToolbar.cpp index d32bdea847b3ec..8ce256e642000a 100644 --- a/frontend/components/DisplayCaptureToolbar.cpp +++ b/frontend/components/DisplayCaptureToolbar.cpp @@ -21,8 +21,9 @@ void DisplayCaptureToolbar::Init() ui->activateButton = nullptr; obs_module_t *mod = get_os_module("win-capture", "mac-capture", "linux-capture"); - if (!mod) + if (!mod) { return; + } const char *device_str = get_os_text(mod, "Monitor", "DisplayCapture.Display", "Screen"); ui->deviceLabel->setText(device_str); diff --git a/frontend/components/FocusList.cpp b/frontend/components/FocusList.cpp index ea65cf207ca7ce..23e62d49f8e679 100644 --- a/frontend/components/FocusList.cpp +++ b/frontend/components/FocusList.cpp @@ -18,8 +18,9 @@ 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 + } else { QListWidget::dragMoveEvent(event); + } } diff --git a/frontend/components/GameCaptureToolbar.cpp b/frontend/components/GameCaptureToolbar.cpp index 2a9f8afdf8d2d4..924fb5c2bcd037 100644 --- a/frontend/components/GameCaptureToolbar.cpp +++ b/frontend/components/GameCaptureToolbar.cpp @@ -17,8 +17,9 @@ GameCaptureToolbar::GameCaptureToolbar(QWidget *parent, OBSSource source) ui->setupUi(this); obs_module_t *mod = obs_get_module("win-capture"); - if (!mod) + if (!mod) { return; + } ui->modeLabel->setText(obs_module_get_locale_text(mod, "Mode")); ui->windowLabel->setText(obs_module_get_locale_text(mod, "WindowCapture.Window")); diff --git a/frontend/components/ImageSourceToolbar.cpp b/frontend/components/ImageSourceToolbar.cpp index 71458cef293252..3346990d7e9b37 100644 --- a/frontend/components/ImageSourceToolbar.cpp +++ b/frontend/components/ImageSourceToolbar.cpp @@ -35,8 +35,9 @@ void ImageSourceToolbar::on_browse_clicked() const char *default_path = obs_property_path_default_path(p); QString startDir = ui->path->text(); - if (startDir.isEmpty()) + if (startDir.isEmpty()) { startDir = default_path; + } QString path = OpenFile(this, desc, startDir, filter); if (path.isEmpty()) { diff --git a/frontend/components/MediaControls.cpp b/frontend/components/MediaControls.cpp index a3777a5977ff29..6933ad542f063b 100644 --- a/frontend/components/MediaControls.cpp +++ b/frontend/components/MediaControls.cpp @@ -180,17 +180,20 @@ void MediaControls::SeekTimerCallback() void MediaControls::StartMediaTimer() { - if (isSlideshow) + if (isSlideshow) { return; + } - if (!mediaTimer.isActive()) + if (!mediaTimer.isActive()) { mediaTimer.start(16); + } } void MediaControls::StopMediaTimer() { - if (mediaTimer.isActive()) + if (mediaTimer.isActive()) { mediaTimer.stop(); + } } void MediaControls::SetPlayingState() @@ -288,10 +291,11 @@ void MediaControls::RefreshControls() break; } - if (isSlideshow) + if (isSlideshow) { UpdateSlideCounter(); - else + } else { SetSliderPosition(); + } } OBSSource MediaControls::GetSource() @@ -333,10 +337,11 @@ void MediaControls::SetSliderPosition() float sliderPosition; - if (duration) + if (duration) { sliderPosition = (time / duration) * (float)ui->slider->maximum(); - else + } else { sliderPosition = 0.0f; + } ui->slider->setValue((int)sliderPosition); UpdateLabels((int)sliderPosition); @@ -446,16 +451,18 @@ void MediaControls::on_durationLabel_clicked() config_set_bool(App()->GetUserConfig(), "BasicWindow", "MediaControlsCountdownTimer", countDownTimer); - if (MediaPaused()) + if (MediaPaused()) { SetSliderPosition(); + } } void MediaControls::MoveSliderFoward(int seconds) { OBSSource source = OBSGetStrongRef(weakSource); - if (!source) + if (!source) { return; + } int ms = obs_source_media_get_time(source); ms += seconds * 1000; @@ -468,8 +475,9 @@ void MediaControls::MoveSliderBackwards(int seconds) { OBSSource source = OBSGetStrongRef(weakSource); - if (!source) + if (!source) { return; + } int ms = obs_source_media_get_time(source); ms -= seconds * 1000; @@ -480,13 +488,15 @@ void MediaControls::MoveSliderBackwards(int seconds) void MediaControls::UpdateSlideCounter() { - if (!isSlideshow) + if (!isSlideshow) { return; + } OBSSource source = OBSGetStrongRef(weakSource); - if (!source) + if (!source) { return; + } proc_handler_t *ph = obs_source_get_proc_handler(source); calldata_t cd = {}; @@ -521,8 +531,9 @@ void MediaControls::UpdateLabels(int val) ui->timerLabel->setText(FormatSeconds((int)(time / 1000.0f))); - if (!countDownTimer) + if (!countDownTimer) { ui->durationLabel->setText(FormatSeconds((int)(duration / 1000.0f))); - else + } else { ui->durationLabel->setText(QString("-") + FormatSeconds((int)((duration - time) / 1000.0f))); + } } diff --git a/frontend/components/MenuButton.cpp b/frontend/components/MenuButton.cpp index b674595633d410..f041de74ca6198 100644 --- a/frontend/components/MenuButton.cpp +++ b/frontend/components/MenuButton.cpp @@ -26,10 +26,11 @@ void MenuButton::keyPressEvent(QKeyEvent *event) void MenuButton::mousePressEvent(QMouseEvent *event) { if (menu()) { - if (width() - event->pos().x() <= 30) + if (width() - event->pos().x() <= 30) { showMenu(); - else + } else { setDown(true); + } } else { QPushButton::mousePressEvent(event); } diff --git a/frontend/components/Multiview.cpp b/frontend/components/Multiview.cpp index ed41110ec1cecd..9bac0c71dd4bba 100644 --- a/frontend/components/Multiview.cpp +++ b/frontend/components/Multiview.cpp @@ -14,8 +14,9 @@ Multiview::~Multiview() { for (OBSWeakSource &weakSrc : multiviewScenes) { OBSSource src = OBSGetStrongRef(weakSrc); - if (src) + if (src) { obs_source_dec_showing(src); + } } obs_enter_graphics(); @@ -161,8 +162,9 @@ void Multiview::Update(MultiviewLayout multiviewLayout, bool drawLabel, bool dra OBSDataAutoRelease data = obs_source_get_private_settings(src); obs_data_set_default_bool(data, "show_in_multiview", true); - if (!obs_data_get_bool(data, "show_in_multiview")) + if (!obs_data_get_bool(data, "show_in_multiview")) { continue; + } updatedScenes.emplace_back(OBSGetWeakRef(src)); obs_source_inc_showing(src); @@ -174,8 +176,9 @@ void Multiview::Update(MultiviewLayout multiviewLayout, bool drawLabel, bool dra for (OBSWeakSource &weakSrc : multiviewScenes) { OBSSource src = OBSGetStrongRef(weakSrc); - if (src) + if (src) { obs_source_dec_showing(src); + } } multiviewScenes = std::move(updatedScenes); @@ -234,8 +237,9 @@ void Multiview::Render(uint32_t cx, uint32_t cy) gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color"); gs_effect_set_color(color, colorVal); - while (gs_effect_loop(solid, "Solid")) + while (gs_effect_loop(solid, "Solid")) { gs_draw_sprite(nullptr, 0, (uint32_t)cx, (uint32_t)cy); + } }; auto setRegion = [&](float bx, float by, float cx, float cy) { @@ -265,14 +269,16 @@ void Multiview::Render(uint32_t cx, uint32_t cy) case MultiviewLayout::VERTICAL_LEFT_8_SCENES: sourceX = pvwprgCX; sourceY = (i / 2) * scenesCY; - if (i % 2 != 0) + if (i % 2 != 0) { sourceX += scenesCX; + } break; case MultiviewLayout::VERTICAL_RIGHT_8_SCENES: sourceX = 0; sourceY = (i / 2) * scenesCY; - if (i % 2 != 0) + if (i % 2 != 0) { sourceX = scenesCX; + } break; case MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES: if (i < 4) { @@ -404,10 +410,11 @@ void Multiview::Render(uint32_t cx, uint32_t cy) // We have a source. Now chose the proper highlight color uint32_t colorVal = outerColor; - if (src == programSrc) + if (src == programSrc) { colorVal = programColor; - else if (src == previewSrc) + } else if (src == previewSrc) { colorVal = studioMode ? previewColor : programColor; + } // Paint the background paintAreaWithColor(sourceX, sourceY, scenesCX, scenesCY, colorVal); @@ -427,12 +434,14 @@ void Multiview::Render(uint32_t cx, uint32_t cy) /* ----------- */ // Render the label - if (!drawLabel) + if (!drawLabel) { continue; + } obs_source *label = multiviewLabels[i + 2]; - if (!label) + if (!label) { continue; + } offset = labelOffset(multiviewLayout, label, scenesCX); @@ -470,10 +479,11 @@ void Multiview::Render(uint32_t cx, uint32_t cy) gs_matrix_translate3f(sourceX, sourceY, 0.0f); gs_matrix_scale3f(ppiScaleX, ppiScaleY, 1.0f); setRegion(sourceX, sourceY, ppiCX, ppiCY); - if (studioMode) + if (studioMode) { obs_source_video_render(previewSrc); - else + } else { obs_render_main_texture(); + } if (drawSafeArea) { RenderSafeAreas(actionSafeMargin, targetCX, targetCY); @@ -550,8 +560,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) { int pos = -1; QWidget *rec = QApplication::activeWindow(); - if (!rec) + if (!rec) { return nullptr; + } int cx = rec->width(); int cy = rec->height(); int minX = 0; @@ -571,8 +582,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) } minY = cy / 2; - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 6); pos += ((y - minY) / ((maxY - minY) / 3)) * 6; @@ -590,8 +602,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minY = (cy / 2) - (validY / 6); } - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 6); pos += ((y - minY) / ((maxY - minY) / 4)) * 6; @@ -609,12 +622,14 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minX = cx / 2; - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = 2 * ((y - minY) / ((maxY - minY) / 4)); - if (x > minX + ((maxX - minX) / 2)) + if (x > minX + ((maxX - minX) / 2)) { pos++; + } break; case MultiviewLayout::VERTICAL_RIGHT_8_SCENES: if (float(cx) / float(cy) > ratio) { @@ -628,12 +643,14 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) maxX = (cx / 2); - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = 2 * ((y - minY) / ((maxY - minY) / 4)); - if (x > minX + ((maxX - minX) / 2)) + if (x > minX + ((maxX - minX) / 2)) { pos++; + } break; case MultiviewLayout::HORIZONTAL_BOTTOM_8_SCENES: if (float(cx) / float(cy) > ratio) { @@ -647,12 +664,14 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) maxY = (cy / 2); - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 4); - if (y > minY + ((maxY - minY) / 2)) + if (y > minY + ((maxY - minY) / 2)) { pos += 4; + } break; case MultiviewLayout::SCENES_ONLY_4_SCENES: if (float(cx) / float(cy) > ratio) { @@ -665,8 +684,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minY = (cy / 2) - (validY / 2); } - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 2); pos += ((y - minY) / ((maxY - minY) / 2)) * 2; @@ -683,8 +703,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minY = (cy / 2) - (validY / 2); } - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 3); pos += ((y - minY) / ((maxY - minY) / 3)) * 3; @@ -701,8 +722,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minY = (cy / 2) - (validY / 2); } - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 4); pos += ((y - minY) / ((maxY - minY) / 4)) * 4; @@ -719,8 +741,9 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minY = (cy / 2) - (validY / 2); } - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 5); pos += ((y - minY) / ((maxY - minY) / 5)) * 5; @@ -738,16 +761,19 @@ OBSSource Multiview::GetSourceByPosition(int x, int y) minY = (cy / 2); - if (x < minX || x > maxX || y < minY || y > maxY) + if (x < minX || x > maxX || y < minY || y > maxY) { break; + } pos = (x - minX) / ((maxX - minX) / 4); - if (y > minY + ((maxY - minY) / 2)) + if (y > minY + ((maxY - minY) / 2)) { pos += 4; + } } - if (pos < 0 || pos >= (int)multiviewScenes.size()) + if (pos < 0 || pos >= (int)multiviewScenes.size()) { return nullptr; + } return OBSGetStrongRef(multiviewScenes[pos]); } diff --git a/frontend/components/MuteCheckBox.hpp b/frontend/components/MuteCheckBox.hpp index f4f53ac12af6b7..b65077f8f49442 100644 --- a/frontend/components/MuteCheckBox.hpp +++ b/frontend/components/MuteCheckBox.hpp @@ -17,9 +17,10 @@ class MuteCheckBox : public QCheckBox { * able to manually get into the partial state. */ void nextCheckState() override { - if (checkState() != Qt::Checked) + if (checkState() != Qt::Checked) { setCheckState(Qt::Checked); - else + } else { setCheckState(Qt::Unchecked); + } } }; diff --git a/frontend/components/OBSAdvAudioCtrl.cpp b/frontend/components/OBSAdvAudioCtrl.cpp index b4c83c84e624ff..2f3766f4e5fd7b 100644 --- a/frontend/components/OBSAdvAudioCtrl.cpp +++ b/frontend/components/OBSAdvAudioCtrl.cpp @@ -40,8 +40,9 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source( percent = new QSpinBox(); forceMono = new QCheckBox(); balance = new BalanceSlider(); - if (obs_audio_monitoring_available()) + if (obs_audio_monitoring_available()) { monitoringType = new QComboBox(); + } syncOffset = new QSpinBox(); mixer1 = new QCheckBox(); mixer2 = new QCheckBox(); @@ -57,8 +58,9 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source( 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()) + 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, "rename", OBSSourceRenamed, this); @@ -87,8 +89,9 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source( 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) + if (isActive) { setClasses(active, "text-danger"); + } active->setSizePolicy(QSizePolicy::Maximum, QSizePolicy::Fixed); volume->setMinimum(MIN_DB - 0.1); @@ -132,10 +135,11 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source( const char *speakers = config_get_string(main->Config(), "Audio", "ChannelSetup"); - if (strcmp(speakers, "Mono") == 0) + if (strcmp(speakers, "Mono") == 0) { balance->setEnabled(false); - else + } else { balance->setEnabled(true); + } float bal = obs_source_get_balance_value(source) * 100.0f; balance->setValue((int)bal); @@ -187,8 +191,9 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source( speaker_layout sl = obs_source_get_speaker_layout(source); - if (sl != SPEAKERS_STEREO) + if (sl != SPEAKERS_STEREO) { balanceContainer->setEnabled(false); + } mixerContainer->layout()->addWidget(mixer1); mixerContainer->layout()->addWidget(mixer2); @@ -204,8 +209,9 @@ OBSAdvAudioCtrl::OBSAdvAudioCtrl(QGridLayout *, obs_source_t *source_) : source( 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()) + if (obs_audio_monitoring_available()) { connect(monitoringType, &QComboBox::currentIndexChanged, this, &OBSAdvAudioCtrl::monitoringTypeChanged); + } auto connectMixer = [this](QCheckBox *mixer, int num) { connect(mixer, &QCheckBox::clicked, this, @@ -230,8 +236,9 @@ OBSAdvAudioCtrl::~OBSAdvAudioCtrl() forceMono->deleteLater(); balanceContainer->deleteLater(); syncOffset->deleteLater(); - if (obs_audio_monitoring_available()) + if (obs_audio_monitoring_available()) { monitoringType->deleteLater(); + } mixerContainer->deleteLater(); } @@ -247,8 +254,9 @@ void OBSAdvAudioCtrl::ShowAudioControl(QGridLayout *layout) layout->addWidget(forceMono, lastRow, idx++); layout->addWidget(balanceContainer, lastRow, idx++); layout->addWidget(syncOffset, lastRow, idx++); - if (obs_audio_monitoring_available()) + if (obs_audio_monitoring_available()) { layout->addWidget(monitoringType, lastRow, idx++); + } layout->addWidget(mixerContainer, lastRow, idx++); layout->layout()->setAlignment(mixerContainer, Qt::AlignVCenter); layout->setHorizontalSpacing(15); @@ -431,10 +439,11 @@ void OBSAdvAudioCtrl::percentChanged(int percent) static inline void set_mono(obs_source_t *source, bool mono) { uint32_t flags = obs_source_get_flags(source); - if (mono) + if (mono) { flags |= OBS_SOURCE_FLAG_FORCE_MONO; - else + } else { flags &= ~OBS_SOURCE_FLAG_FORCE_MONO; + } obs_source_set_flags(source, flags); } @@ -443,13 +452,15 @@ void OBSAdvAudioCtrl::downmixMonoChanged(bool val) uint32_t flags = obs_source_get_flags(source); bool forceMonoActive = (flags & OBS_SOURCE_FLAG_FORCE_MONO) != 0; - if (forceMonoActive == val) + if (forceMonoActive == val) { return; + } - if (val) + if (val) { flags |= OBS_SOURCE_FLAG_FORCE_MONO; - else + } else { flags &= ~OBS_SOURCE_FLAG_FORCE_MONO; + } obs_source_set_flags(source, flags); @@ -502,8 +513,9 @@ void OBSAdvAudioCtrl::syncOffsetChanged(int milliseconds) int64_t prev = obs_source_get_sync_offset(source); int64_t val = int64_t(milliseconds) * NSEC_PER_MSEC; - if (prev / NSEC_PER_MSEC == milliseconds) + if (prev / NSEC_PER_MSEC == milliseconds) { return; + } obs_source_set_sync_offset(source, val); @@ -559,10 +571,11 @@ static inline void setMixer(obs_source_t *source, const int mixerIdx, const bool uint32_t mixers = obs_source_get_audio_mixers(source); uint32_t new_mixers = mixers; - if (checked) + if (checked) { new_mixers |= (1 << mixerIdx); - else + } else { new_mixers &= ~(1 << mixerIdx); + } obs_source_set_audio_mixers(source, new_mixers); diff --git a/frontend/components/OBSPreviewScalingComboBox.cpp b/frontend/components/OBSPreviewScalingComboBox.cpp index c1a08fcb6a1efc..4c3e2c33d0a53e 100644 --- a/frontend/components/OBSPreviewScalingComboBox.cpp +++ b/frontend/components/OBSPreviewScalingComboBox.cpp @@ -23,8 +23,9 @@ void OBSPreviewScalingComboBox::PreviewFixedScalingChanged(bool fixed) { - if (fixedScaling == fixed) + if (fixedScaling == fixed) { return; + } fixedScaling = fixed; UpdateSelection(); @@ -60,8 +61,9 @@ void OBSPreviewScalingComboBox::PreviewScaleChanged(float scale) void OBSPreviewScalingComboBox::SetScaleOutputEnabled(bool show) { - if (scaleOutputEnabled == show) + if (scaleOutputEnabled == show) { return; + } scaleOutputEnabled = show; diff --git a/frontend/components/SceneTree.cpp b/frontend/components/SceneTree.cpp index f96dce68c6fdc3..a5d9a7f2967d77 100644 --- a/frontend/components/SceneTree.cpp +++ b/frontend/components/SceneTree.cpp @@ -175,8 +175,9 @@ void SceneTree::RepositionGrid(QDragMoveEvent *event) for (int i = 0; i < count(); i++) { auto *wItem = item(i); - if (wItem->isSelected()) + if (wItem->isSelected()) { continue; + } QModelIndex index = indexFromItem(wItem); @@ -193,8 +194,9 @@ void SceneTree::RepositionGrid(QDragMoveEvent *event) for (int i = 0; i < count(); i++) { auto *wItem = item(i); - if (wItem->isSelected()) + if (wItem->isSelected()) { continue; + } QModelIndex index = indexFromItem(wItem); @@ -238,7 +240,8 @@ void SceneTree::rowsInserted(const QModelIndex &parent, int start, int end) // Workaround for QTBUG-105870. Remove once that is solved upstream. 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/frontend/components/SourceToolbar.cpp b/frontend/components/SourceToolbar.cpp index aee57f29798b17..27c69ae91f9893 100644 --- a/frontend/components/SourceToolbar.cpp +++ b/frontend/components/SourceToolbar.cpp @@ -30,8 +30,9 @@ void SourceToolbar::SetUndoProperties(obs_source_t *source, bool repeatable) OBSBasic *main = OBSBasic::Get(); OBSSource currentSceneSource = main->GetCurrentSceneSource(); - if (!currentSceneSource) + 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()); @@ -52,9 +53,10 @@ void SourceToolbar::SetUndoProperties(obs_source_t *source, bool repeatable) 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) + 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); + } oldData = nullptr; } diff --git a/frontend/components/SourceTree.cpp b/frontend/components/SourceTree.cpp index 9ffb7da3580ebe..b7cd6f5a815e60 100644 --- a/frontend/components/SourceTree.cpp +++ b/frontend/components/SourceTree.cpp @@ -95,22 +95,26 @@ void SourceTree::SelectItem(obs_sceneitem_t *sceneitem, bool select) int i = 0; for (; i < stm->items.count(); i++) { - if (stm->items[i] == sceneitem) + if (stm->items[i] == sceneitem) { break; + } } - if (i == stm->items.count()) + if (i == stm->items.count()) { return; + } QModelIndex index = stm->createIndex(i, 0); - if (index.isValid() && select != selectionModel()->isSelected(index)) + if (index.isValid() && select != selectionModel()->isSelected(index)) { selectionModel()->select(index, select ? QItemSelectionModel::Select : QItemSelectionModel::Deselect); + } } void SourceTree::mouseDoubleClickEvent(QMouseEvent *event) { - if (event->button() == Qt::LeftButton) + if (event->button() == Qt::LeftButton) { QListView::mouseDoubleClickEvent(event); + } } void SourceTree::dropEvent(QDropEvent *event) @@ -152,10 +156,12 @@ void SourceTree::dropEvent(QDropEvent *event) 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) + if (indicator == QAbstractItemView::AboveItem && itemIsGroup) { dropGroup = nullptr; - if (emptyDrop) + } + if (emptyDrop) { dropGroup = nullptr; + } /* --------------------------------------- */ /* remember to remove list items if */ @@ -169,8 +175,9 @@ void SourceTree::dropEvent(QDropEvent *event) } if (indicator == QAbstractItemView::BelowItem || indicator == QAbstractItemView::OnItem || - indicator == QAbstractItemView::OnViewport) + indicator == QAbstractItemView::OnViewport) { row++; + } if (row < 0 || row > stm->items.count()) { QListView::dropEvent(event); @@ -194,10 +201,11 @@ void SourceTree::dropEvent(QDropEvent *event) /* below another group */ obs_sceneitem_t *itemBelow; - if (row == stm->items.count()) + if (row == stm->items.count()) { itemBelow = nullptr; - else + } else { itemBelow = stm->items[row]; + } if (hasGroups) { if (!itemBelow || obs_sceneitem_get_group(scene, itemBelow) != dropGroup) { @@ -220,11 +228,13 @@ void SourceTree::dropEvent(QDropEvent *event) std::vector sources; for (int i = 0; i < indices.size(); i++) { obs_sceneitem_t *item = items[indices[i].row()]; - if (obs_sceneitem_get_scene(item) != scene) + if (obs_sceneitem_get_scene(item) != scene) { sources.push_back(obs_scene_get_source(obs_sceneitem_get_scene(item))); + } } - if (dropGroup) + if (dropGroup) { sources.push_back(obs_sceneitem_get_source(dropGroup)); + } OBSData undo_data = main->BackupScene(scene, &sources); /* --------------------------------------- */ @@ -266,8 +276,9 @@ void SourceTree::dropEvent(QDropEvent *event) QList persistentIndices; persistentIndices.reserve(indices.count()); - for (QModelIndex &index : indices) + for (QModelIndex &index : indices) { persistentIndices.append(index); + } std::sort(persistentIndices.begin(), persistentIndices.end()); /* --------------------------------------- */ @@ -279,8 +290,9 @@ void SourceTree::dropEvent(QDropEvent *event) int to = r; int itemTo = to; - if (itemTo > from) + if (itemTo > from) { itemTo--; + } if (itemTo != from) { stm->beginMoveRows(QModelIndex(), from, from, QModelIndex(), to); @@ -347,10 +359,11 @@ void SourceTree::dropEvent(QDropEvent *event) continue; } - if (!hasGroups && i >= firstIdx && i <= lastIdx) + if (!hasGroups && i >= firstIdx && i <= lastIdx) { group = dropGroup; - else + } else { group = obs_sceneitem_get_group(scene, item); + } if (lastGroup && lastGroup != group) { insertLastGroup(); @@ -471,8 +484,9 @@ void SourceTree::NewGroupEdit(int row) bool SourceTree::Edit(int row) { SourceTreeModel *stm = GetStm(); - if (row < 0 || row >= stm->items.count()) + if (row < 0 || row >= stm->items.count()) { return false; + } QModelIndex index = stm->createIndex(row, 0); QWidget *widget = indexWidget(index); diff --git a/frontend/components/SourceTreeDelegate.cpp b/frontend/components/SourceTreeDelegate.cpp index 6f130880605611..b7a2003acb1181 100644 --- a/frontend/components/SourceTreeDelegate.cpp +++ b/frontend/components/SourceTreeDelegate.cpp @@ -9,8 +9,9 @@ QSize SourceTreeDelegate::sizeHint(const QStyleOptionViewItem &option, const QMo SourceTree *tree = qobject_cast(parent()); QWidget *item = tree->indexWidget(index); - if (!item) + if (!item) { return QStyledItemDelegate::sizeHint(option, index); + } return (QSize(item->sizeHint())); } diff --git a/frontend/components/SourceTreeItem.cpp b/frontend/components/SourceTreeItem.cpp index 97236a2a47ec09..9efc85bb708671 100644 --- a/frontend/components/SourceTreeItem.cpp +++ b/frontend/components/SourceTreeItem.cpp @@ -55,12 +55,13 @@ SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) : tre if (tree->iconsVisible) { QIcon icon; - if (strcmp(id, "scene") == 0) + if (strcmp(id, "scene") == 0) { icon = main->GetSceneIcon(); - else if (strcmp(id, "group") == 0) + } else if (strcmp(id, "group") == 0) { icon = main->GetGroupIcon(); - else + } else { icon = main->GetSourceIcon(id); + } QPixmap pixmap = icon.pixmap(QSize(16, 16)); @@ -136,8 +137,9 @@ SourceTreeItem::SourceTreeItem(SourceTree *tree_, OBSSceneItem sceneitem_) : tre 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); - if (si) + if (si) { obs_sceneitem_set_visible(si, val); + } }; QString str = QTStr(val ? "Undo.ShowSceneItem" : "Undo.HideSceneItem"); @@ -183,8 +185,9 @@ void SourceTreeItem::Clear() void SourceTreeItem::ReconnectSignals() { - if (!sceneitem) + if (!sceneitem) { return; + } DisconnectSignals(); @@ -200,8 +203,9 @@ void SourceTreeItem::ReconnectSignals() Q_ARG(OBSScene, curScene)); curItem = nullptr; } - if (!curItem) + if (!curItem) { QMetaObject::invokeMethod(this_, "Clear"); + } }; auto itemVisible = [](void *data, calldata_t *cd) { @@ -209,8 +213,9 @@ void SourceTreeItem::ReconnectSignals() obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); bool visible = calldata_bool(cd, "visible"); - if (curItem == this_->sceneitem) + if (curItem == this_->sceneitem) { QMetaObject::invokeMethod(this_, "VisibilityChanged", Q_ARG(bool, visible)); + } }; auto itemLocked = [](void *data, calldata_t *cd) { @@ -218,24 +223,27 @@ void SourceTreeItem::ReconnectSignals() obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); bool locked = calldata_bool(cd, "locked"); - if (curItem == this_->sceneitem) + if (curItem == this_->sceneitem) { QMetaObject::invokeMethod(this_, "LockedChanged", Q_ARG(bool, locked)); + } }; auto itemSelect = [](void *data, calldata_t *cd) { SourceTreeItem *this_ = static_cast(data); obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); - if (curItem == this_->sceneitem) + if (curItem == this_->sceneitem) { QMetaObject::invokeMethod(this_, "Select"); + } }; auto itemDeselect = [](void *data, calldata_t *cd) { SourceTreeItem *this_ = static_cast(data); obs_sceneitem_t *curItem = (obs_sceneitem_t *)calldata_ptr(cd, "item"); - if (curItem == this_->sceneitem) + if (curItem == this_->sceneitem) { QMetaObject::invokeMethod(this_, "Deselect"); + } }; auto reorderGroup = [](void *data, calldata_t *) { @@ -384,8 +392,9 @@ void SourceTreeItem::ExitEditModeInternal(bool save) /* ----------------------------------------- */ /* check for empty string */ - if (!save) + if (!save) { return; + } if (newName.empty()) { OBSMessageBox::information(main, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); @@ -396,8 +405,9 @@ void SourceTreeItem::ExitEditModeInternal(bool save) /* Check for same name */ obs_source_t *source = obs_sceneitem_get_source(sceneitem); - if (newName == obs_source_get_name(source)) + if (newName == obs_source_get_name(source)) { return; + } /* ----------------------------------------- */ /* check for existing source */ @@ -442,8 +452,9 @@ void SourceTreeItem::ExitEditModeInternal(bool save) bool SourceTreeItem::eventFilter(QObject *object, QEvent *event) { - if (editor != object) + if (editor != object) { return false; + } if (LineEditCanceled(event)) { QMetaObject::invokeMethod(this, "ExitEditMode", Qt::QueuedConnection, Q_ARG(bool, false)); @@ -554,10 +565,11 @@ void SourceTreeItem::ExpandClicked(bool checked) obs_data_set_bool(data, "collapsed", checked); - if (!checked) + if (!checked) { tree->GetStm()->ExpandGroup(sceneitem); - else + } else { tree->GetStm()->CollapseGroup(sceneitem); + } } void SourceTreeItem::Select() diff --git a/frontend/components/SourceTreeModel.cpp b/frontend/components/SourceTreeModel.cpp index fca69e9a135d4d..d11e88c9941879 100644 --- a/frontend/components/SourceTreeModel.cpp +++ b/frontend/components/SourceTreeModel.cpp @@ -163,8 +163,9 @@ void SourceTreeModel::ReorderItems() beginMoveRows(QModelIndex(), idx1Old, idx1Old + count - 1, QModelIndex(), idx1New + count); for (i = 0; i < count; i++) { int to = idx1New + count; - if (to > idx1Old) + if (to > idx1Old) { to--; + } MoveItem(items, idx1Old, to); } endMoveRows(); @@ -194,8 +195,9 @@ void SourceTreeModel::Remove(obs_sceneitem_t *item) } } - if (idx == -1) + if (idx == -1) { return; + } int startIdx = idx; int endIdx = idx; @@ -208,10 +210,11 @@ void SourceTreeModel::Remove(obs_sceneitem_t *item) obs_sceneitem_t *subitem = items[i]; obs_scene_t *subscene = obs_sceneitem_get_scene(subitem); - if (subscene == scene) + if (subscene == scene) { endIdx = i; - else + } else { break; + } } } @@ -219,16 +222,18 @@ void SourceTreeModel::Remove(obs_sceneitem_t *item) items.remove(idx, endIdx - startIdx + 1); endRemoveRows(); - if (is_group) + if (is_group) { UpdateGroupState(true); + } OBSBasic::Get()->UpdateContextBarDeferred(); } OBSSceneItem SourceTreeModel::Get(int idx) { - if (idx == -1 || idx >= items.count()) + if (idx == -1 || idx >= items.count()) { return OBSSceneItem(); + } return items[idx]; } @@ -255,8 +260,9 @@ QVariant SourceTreeModel::data(const QModelIndex &index, int role) const Qt::ItemFlags SourceTreeModel::flags(const QModelIndex &index) const { - if (!index.isValid()) + if (!index.isValid()) { return QAbstractListModel::flags(index) | Qt::ItemIsDropEnabled; + } obs_sceneitem_t *item = items[index.row()]; bool is_group = obs_sceneitem_is_group(item); @@ -278,8 +284,9 @@ QString SourceTreeModel::GetNewGroupName() int i = 2; for (;;) { OBSSourceAutoRelease group = obs_get_source_by_name(QT_TO_UTF8(name)); - if (!group) + if (!group) { break; + } name = QTStr("Basic.Main.Group").arg(QString::number(i++)); } @@ -290,8 +297,9 @@ void SourceTreeModel::AddGroup() { QString name = GetNewGroupName(); obs_sceneitem_t *group = obs_scene_add_group(GetCurrentScene(), QT_TO_UTF8(name)); - if (!group) + if (!group) { return; + } beginInsertRows(QModelIndex(), 0, 0); items.insert(0, group); @@ -305,8 +313,9 @@ void SourceTreeModel::AddGroup() void SourceTreeModel::GroupSelectedItems(QModelIndexList &indices) { - if (indices.count() == 0) + if (indices.count() == 0) { return; + } OBSBasic *main = OBSBasic::Get(); OBSScene scene = GetCurrentScene(); @@ -329,8 +338,9 @@ void SourceTreeModel::GroupSelectedItems(QModelIndexList &indices) main->undo_s.push_disabled(); - for (obs_sceneitem_t *item : item_order) + for (obs_sceneitem_t *item : item_order) { obs_sceneitem_select(item, false); + } hasGroups = true; st->UpdateWidgets(true); @@ -349,8 +359,9 @@ void SourceTreeModel::GroupSelectedItems(QModelIndexList &indices) void SourceTreeModel::UngroupSelectedGroups(QModelIndexList &indices) { OBSBasic *main = OBSBasic::Get(); - if (indices.count() == 0) + if (indices.count() == 0) { return; + } OBSScene scene = main->GetCurrentScene(); OBSData undoData = main->BackupScene(scene); @@ -369,8 +380,9 @@ void SourceTreeModel::UngroupSelectedGroups(QModelIndexList &indices) void SourceTreeModel::ExpandGroup(obs_sceneitem_t *item) { int itemIdx = items.indexOf(item); - if (itemIdx == -1) + if (itemIdx == -1) { return; + } itemIdx++; @@ -379,12 +391,14 @@ void SourceTreeModel::ExpandGroup(obs_sceneitem_t *item) QVector subItems; obs_scene_enum_items(scene, enumItem, &subItems); - if (!subItems.size()) + if (!subItems.size()) { return; + } beginInsertRows(QModelIndex(), itemIdx, itemIdx + subItems.size() - 1); - for (int i = 0; i < subItems.size(); i++) + for (int i = 0; i < subItems.size(); i++) { items.insert(i + itemIdx, subItems[i]); + } endInsertRows(); st->UpdateWidgets(); @@ -401,14 +415,16 @@ void SourceTreeModel::CollapseGroup(obs_sceneitem_t *item) obs_scene_t *itemScene = obs_sceneitem_get_scene(items[i]); if (itemScene == scene) { - if (startIdx == -1) + if (startIdx == -1) { startIdx = i; + } endIdx = i; } } - if (startIdx == -1) + if (startIdx == -1) { return; + } beginRemoveRows(QModelIndex(), startIdx, endIdx); items.remove(startIdx, endIdx - startIdx + 1); diff --git a/frontend/components/TextSourceToolbar.cpp b/frontend/components/TextSourceToolbar.cpp index be2d46525175ea..d370fcea3d446a 100644 --- a/frontend/components/TextSourceToolbar.cpp +++ b/frontend/components/TextSourceToolbar.cpp @@ -40,8 +40,9 @@ TextSourceToolbar::TextSourceToolbar(QWidget *parent, OBSSource source) bool single_line = !read_from_file && (!text || (strchr(text, '\n') == nullptr)); ui->emptySpace->setVisible(!single_line); ui->text->setVisible(single_line); - if (single_line) + if (single_line) { ui->text->setText(text); + } } TextSourceToolbar::~TextSourceToolbar() {} diff --git a/frontend/components/UIValidation.cpp b/frontend/components/UIValidation.cpp index bb24004b408784..01758cbcc8e026 100644 --- a/frontend/components/UIValidation.cpp +++ b/frontend/components/UIValidation.cpp @@ -11,12 +11,14 @@ static int CountVideoSources() { int count = 0; auto countSources = [](void *param, obs_source_t *source) { - if (!source) + if (!source) { return true; + } uint32_t flags = obs_source_get_output_flags(source); - if ((flags & OBS_SOURCE_VIDEO) != 0) + if ((flags & OBS_SOURCE_VIDEO) != 0) { (*static_cast(param))++; + } return true; }; @@ -28,12 +30,14 @@ static int CountVideoSources() bool UIValidation::NoSourcesConfirmation(QWidget *parent) { // There are sources, don't need confirmation - if (CountVideoSources() != 0) + if (CountVideoSources() != 0) { return true; + } // Ignore no video if no parent is visible to alert on - if (!parent->isVisible()) + if (!parent->isVisible()) { return true; + } QString msg = QTStr("NoSources.Text"); msg += "\n\n"; @@ -48,16 +52,18 @@ bool UIValidation::NoSourcesConfirmation(QWidget *parent) messageBox.setIcon(QMessageBox::Question); messageBox.exec(); - if (messageBox.clickedButton() != yesButton) + if (messageBox.clickedButton() != yesButton) { return false; - else + } else { return true; + } } StreamSettingsAction UIValidation::StreamSettingsConfirmation(QWidget *parent, OBSService service) { - if (obs_service_can_try_to_connect(service)) + if (obs_service_can_try_to_connect(service)) { return StreamSettingsAction::ContinueStream; + } char const *serviceType = obs_service_get_type(service); bool isCustomService = (strcmp(serviceType, "rtmp_custom") == 0); @@ -100,10 +106,12 @@ StreamSettingsAction UIValidation::StreamSettingsConfirmation(QWidget *parent, O messageBox.setIcon(QMessageBox::Warning); messageBox.exec(); - if (messageBox.clickedButton() == settings) + if (messageBox.clickedButton() == settings) { return StreamSettingsAction::OpenSettings; - if (messageBox.clickedButton() == cancel) + } + if (messageBox.clickedButton() == cancel) { return StreamSettingsAction::Cancel; + } return StreamSettingsAction::ContinueStream; } diff --git a/frontend/components/UrlPushButton.cpp b/frontend/components/UrlPushButton.cpp index 1e7b68d0465628..8a96e75b78b4f6 100644 --- a/frontend/components/UrlPushButton.cpp +++ b/frontend/components/UrlPushButton.cpp @@ -19,8 +19,9 @@ void UrlPushButton::mousePressEvent(QMouseEvent *event) { Q_UNUSED(event) QUrl openUrl = m_targetUrl; - if (openUrl.isEmpty()) + if (openUrl.isEmpty()) { return; + } QDesktopServices::openUrl(openUrl); } diff --git a/frontend/components/VisibilityItemDelegate.cpp b/frontend/components/VisibilityItemDelegate.cpp index d9e76ee5cc9a61..443468cddeb766 100644 --- a/frontend/components/VisibilityItemDelegate.cpp +++ b/frontend/components/VisibilityItemDelegate.cpp @@ -14,13 +14,15 @@ void VisibilityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem QObject *parentObj = parent(); QListWidget *list = qobject_cast(parentObj); - if (!list) + if (!list) { return; + } QListWidgetItem *item = list->item(index.row()); VisibilityItemWidget *widget = qobject_cast(list->itemWidget(item)); - if (!widget) + if (!widget) { return; + } bool selected = option.state.testFlag(QStyle::State_Selected); bool active = option.state.testFlag(QStyle::State_Active); @@ -40,10 +42,11 @@ void VisibilityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem QPalette::ColorRole role; - if (selected && active) + if (selected && active) { role = highlightRole; - else + } else { role = QPalette::WindowText; + } widget->SetColor(palette.color(group, role), active, selected); } @@ -51,8 +54,9 @@ void VisibilityItemDelegate::paint(QPainter *painter, const QStyleOptionViewItem bool VisibilityItemDelegate::eventFilter(QObject *object, QEvent *event) { QWidget *editor = qobject_cast(object); - if (!editor) + if (!editor) { return false; + } if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast(event); diff --git a/frontend/components/VisibilityItemWidget.cpp b/frontend/components/VisibilityItemWidget.cpp index 42af71813672fd..48f17d5f3aba41 100644 --- a/frontend/components/VisibilityItemWidget.cpp +++ b/frontend/components/VisibilityItemWidget.cpp @@ -41,15 +41,17 @@ void VisibilityItemWidget::OBSSourceEnabled(void *param, calldata_t *data) void VisibilityItemWidget::SourceEnabled(bool enabled) { - if (vis->isChecked() != enabled) + if (vis->isChecked() != enabled) { vis->setChecked(enabled); + } } void VisibilityItemWidget::SetColor(const QColor &color, bool active_, bool selected_) { /* Do not update unless the state has actually changed */ - if (active_ == active && selected_ == selected) + if (active_ == active && selected_ == selected) { return; + } QPalette pal = vis->palette(); pal.setColor(QPalette::WindowText, color); diff --git a/frontend/components/VolumeAccessibleInterface.cpp b/frontend/components/VolumeAccessibleInterface.cpp index ce7e496ab328a3..b78845cac40e4a 100644 --- a/frontend/components/VolumeAccessibleInterface.cpp +++ b/frontend/components/VolumeAccessibleInterface.cpp @@ -27,10 +27,11 @@ QVariant VolumeAccessibleInterface::currentValue() const QString text; float db = obs_fader_get_db(slider()->fad); - if (db < -96.0f) + if (db < -96.0f) { text = "-inf dB"; - else + } else { text = QString::number(db, 'f', 1).append(" dB"); + } return text; } diff --git a/frontend/components/WindowCaptureToolbar.cpp b/frontend/components/WindowCaptureToolbar.cpp index 3f1e4ebba3fb36..e7fa548fa4d295 100644 --- a/frontend/components/WindowCaptureToolbar.cpp +++ b/frontend/components/WindowCaptureToolbar.cpp @@ -21,8 +21,9 @@ void WindowCaptureToolbar::Init() ui->activateButton = nullptr; obs_module_t *mod = get_os_module("win-capture", "mac-capture", "linux-capture"); - if (!mod) + if (!mod) { return; + } const char *device_str = get_os_text(mod, "WindowCapture.Window", "WindowUtils.Window", "Window"); ui->deviceLabel->setText(device_str); diff --git a/frontend/dialogs/NameDialog.cpp b/frontend/dialogs/NameDialog.cpp index d374b3aed343da..a3ed39582264bf 100644 --- a/frontend/dialogs/NameDialog.cpp +++ b/frontend/dialogs/NameDialog.cpp @@ -68,17 +68,20 @@ static bool IsWhitespace(char ch) static void CleanWhitespace(std::string &str) { - while (str.size() && IsWhitespace(str.back())) + while (str.size() && IsWhitespace(str.back())) { str.erase(str.end() - 1); - while (str.size() && IsWhitespace(str.front())) + } + while (str.size() && IsWhitespace(str.front())) { str.erase(str.begin()); + } } bool NameDialog::AskForName(QWidget *parent, const QString &title, const QString &text, std::string &userTextInput, const QString &placeHolder, int maxSize) { - if (maxSize <= 0 || maxSize > 32767) + if (maxSize <= 0 || maxSize > 32767) { maxSize = 170; + } NameDialog dialog(parent); dialog.setWindowTitle(title); diff --git a/frontend/dialogs/OAuthLogin.cpp b/frontend/dialogs/OAuthLogin.cpp index dd7d50bbc4a395..88e78c12831551 100644 --- a/frontend/dialogs/OAuthLogin.cpp +++ b/frontend/dialogs/OAuthLogin.cpp @@ -92,19 +92,22 @@ void OAuthLogin::urlChanged(const QString &url) { std::string uri = get_token ? "access_token=" : "code="; int code_idx = url.indexOf(uri.c_str()); - if (code_idx == -1) + if (code_idx == -1) { return; + } - if (!url.startsWith(OAUTH_BASE_URL)) + if (!url.startsWith(OAUTH_BASE_URL)) { return; + } code_idx += (int)uri.size(); int next_idx = url.indexOf("&", code_idx); - if (next_idx != -1) + if (next_idx != -1) { code = url.mid(code_idx, next_idx - code_idx); - else + } else { code = url.right(url.size() - code_idx); + } accept(); } diff --git a/frontend/dialogs/OBSAbout.cpp b/frontend/dialogs/OBSAbout.cpp index 951ac7e52dc0e7..9660008c16eb74 100644 --- a/frontend/dialogs/OBSAbout.cpp +++ b/frontend/dialogs/OBSAbout.cpp @@ -21,10 +21,11 @@ OBSAbout::OBSAbout(QWidget *parent) : QDialog(parent), ui(new Ui::OBSAbout) QString bitness; - if (sizeof(void *) == 4) + if (sizeof(void *) == 4) { bitness = " (32 bit)"; - else if (sizeof(void *) == 8) + } else if (sizeof(void *) == 8) { bitness = " (64 bit)"; + } QString ver = obs_get_version_string(); @@ -80,8 +81,9 @@ void OBSAbout::ShowAbout() { OBSBasic *main = OBSBasic::Get(); - if (main->patronJson.empty()) + if (main->patronJson.empty()) { return; + } std::string error; Json json = Json::parse(main->patronJson, error); @@ -111,11 +113,13 @@ void OBSAbout::ShowAbout() text += "\">"; } text += QT_UTF8(name.c_str()).toHtmlEscaped(); - if (!link.empty()) + if (!link.empty()) { text += ""; + } - if (first) + if (first) { first = false; + } } ui->textBrowser->setHtml(text); diff --git a/frontend/dialogs/OBSBasicAdvAudio.cpp b/frontend/dialogs/OBSBasicAdvAudio.cpp index 860be203092aed..17e0f6ac687ddd 100644 --- a/frontend/dialogs/OBSBasicAdvAudio.cpp +++ b/frontend/dialogs/OBSBasicAdvAudio.cpp @@ -19,8 +19,9 @@ OBSBasicAdvAudio::OBSBasicAdvAudio(QWidget *parent) : QDialog(parent), ui(new Ui VolumeType volType = (VolumeType)config_get_int(App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType"); - if (volType == VolumeType::Percent) + if (volType == VolumeType::Percent) { ui->usePercent->setChecked(true); + } installEventFilter(CreateShortcutFilter()); @@ -35,8 +36,9 @@ OBSBasicAdvAudio::~OBSBasicAdvAudio() { OBSBasic *main = OBSBasic::Get(); - for (size_t i = 0; i < controls.size(); ++i) + for (size_t i = 0; i < controls.size(); ++i) { delete controls[i]; + } main->SaveProject(); } @@ -47,8 +49,9 @@ 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; } @@ -71,16 +74,18 @@ void OBSBasicAdvAudio::OBSSourceActivated(void *param, calldata_t *calldata) { OBSSource source((obs_source_t *)calldata_ptr(calldata, "source")); - if (obs_source_audio_active(source)) + if (obs_source_audio_active(source)) { QMetaObject::invokeMethod(static_cast(param), "SourceAdded", Q_ARG(OBSSource, source)); + } } inline void OBSBasicAdvAudio::AddAudioSource(obs_source_t *source) { for (size_t i = 0; i < controls.size(); i++) { - if (controls[i]->GetSource() == source) + if (controls[i]->GetSource() == source) { return; + } } OBSAdvAudioCtrl *control = new OBSAdvAudioCtrl(ui->mainLayout, source); @@ -95,8 +100,9 @@ void OBSBasicAdvAudio::SourceAdded(OBSSource source) { uint32_t flags = obs_source_get_output_flags(source); - if ((flags & OBS_SOURCE_AUDIO) == 0) + if ((flags & OBS_SOURCE_AUDIO) == 0) { return; + } AddAudioSource(source); } @@ -105,8 +111,9 @@ void OBSBasicAdvAudio::SourceRemoved(OBSSource source) { uint32_t flags = obs_source_get_output_flags(source); - if ((flags & OBS_SOURCE_AUDIO) == 0) + if ((flags & OBS_SOURCE_AUDIO) == 0) { return; + } for (size_t i = 0; i < controls.size(); i++) { if (controls[i]->GetSource() == source) { @@ -121,13 +128,15 @@ void OBSBasicAdvAudio::on_usePercent_toggled(bool checked) { VolumeType type; - if (checked) + if (checked) { type = VolumeType::Percent; - else + } else { type = VolumeType::dB; + } - for (size_t i = 0; i < controls.size(); i++) + for (size_t i = 0; i < controls.size(); i++) { controls[i]->SetVolumeWidget(type); + } config_set_int(App()->GetUserConfig(), "BasicWindow", "AdvAudioVolumeType", (int)type); } @@ -139,8 +148,9 @@ void OBSBasicAdvAudio::on_activeOnly_toggled(bool checked) void OBSBasicAdvAudio::SetShowInactive(bool show) { - if (showInactive == show) + if (showInactive == show) { return; + } showInactive = show; diff --git a/frontend/dialogs/OBSBasicFilters.cpp b/frontend/dialogs/OBSBasicFilters.cpp index cbc2f7654ff0a2..6c41f54b3a4cc7 100644 --- a/frontend/dialogs/OBSBasicFilters.cpp +++ b/frontend/dialogs/OBSBasicFilters.cpp @@ -111,8 +111,9 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) ui->effectFilters->setFocus(); } - if (audioOnly || (audio && !async)) + if (audioOnly || (audio && !async)) { ui->asyncLabel->setText(QTStr("Basic.Filters.AudioFilters")); + } if (async && audio && ui->asyncFilters->count() == 0) { UpdateSplitter(false); @@ -132,8 +133,9 @@ OBSBasicFilters::OBSBasicFilters(QWidget *parent, OBSSource source_) if ((caps & OBS_SOURCE_VIDEO) != 0) { ui->rightLayout->setContentsMargins(0, 0, 0, 0); ui->preview->show(); - if (drawable_type) + if (drawable_type) { connect(ui->preview, &OBSQTDisplay::DisplayCreated, this, addDrawCallback); + } } else { ui->rightLayout->setContentsMargins(0, noPreviewMargin, 0, 0); ui->preview->hide(); @@ -162,13 +164,15 @@ void OBSBasicFilters::Init() inline OBSSource OBSBasicFilters::GetFilter(int row, bool async) { - if (row == -1) + if (row == -1) { return OBSSource(); + } QListWidget *list = async ? ui->asyncFilters : ui->effectFilters; QListWidgetItem *item = list->item(row); - if (!item) + if (!item) { return OBSSource(); + } QVariant v = item->data(Qt::UserRole); return v.value(); @@ -244,8 +248,9 @@ void OBSBasicFilters::UpdatePropertiesView(int row, bool async) } } - if (!filter) + if (!filter) { return; + } OBSDataAutoRelease settings = obs_source_get_settings(filter); @@ -287,8 +292,9 @@ void OBSBasicFilters::AddFilter(OBSSource filter, bool focus) item->setData(Qt::UserRole, QVariant::fromValue(filter)); list->addItem(item); - if (focus) + if (focus) { list->setCurrentItem(item); + } SetupVisibilityItem(list, item, filter); } @@ -312,8 +318,9 @@ void OBSBasicFilters::RemoveFilter(OBSSource filter) const char *filterName = obs_source_get_name(filter); const char *sourceName = obs_source_get_name(source); - if (!sourceName || !filterName) + if (!sourceName || !filterName) { return; + } const char *filterId = obs_source_get_id(filter); @@ -348,8 +355,9 @@ void OBSBasicFilters::ReorderFilter(QListWidget *list, obs_source_t *filter, siz list->insertItem((int)idx, listItem); SetupVisibilityItem(list, listItem, filterItem); - if (sel) + if (sel) { list->setCurrentRow((int)idx); + } } } @@ -383,8 +391,9 @@ void OBSBasicFilters::ReorderFilters() void OBSBasicFilters::UpdateFilters() { - if (!source) + if (!source) { return; + } ClearListItems(ui->effectFilters); ClearListItems(ui->asyncFilters); @@ -417,8 +426,9 @@ void OBSBasicFilters::UpdateSplitter(bool show_splitter_frame) { bool show_splitter_handle = show_splitter_frame; uint32_t caps = obs_source_get_output_flags(source); - if ((caps & OBS_SOURCE_VIDEO) == 0) + if ((caps & OBS_SOURCE_VIDEO) == 0) { show_splitter_handle = false; + } for (int i = 0; i < ui->rightLayout->count(); i++) { QSplitterHandle *hndl = ui->rightLayout->handle(i); @@ -438,8 +448,9 @@ static bool filter_compatible(bool async, uint32_t sourceFlags, uint32_t filterF bool asyncSource = (sourceFlags & OBS_SOURCE_ASYNC) != 0; if (async && ((audioOnly && filterVideo) || (!audio && !asyncSource) || (filterAudio && !audio) || - (!asyncSource && !filterAudio))) + (!asyncSource && !filterAudio))) { return false; + } return (async && (filterAudio || filterAsync)) || (!async && !filterAudio && !filterAsync); } @@ -465,12 +476,15 @@ QMenu *OBSBasicFilters::CreateAddFilterPopupMenu(bool async) const char *name = obs_source_get_display_name(type_str); uint32_t caps = obs_get_source_output_flags(type_str); - if ((caps & OBS_SOURCE_DEPRECATED) != 0) + if ((caps & OBS_SOURCE_DEPRECATED) != 0) { continue; - if ((caps & OBS_SOURCE_CAP_DISABLED) != 0) + } + if ((caps & OBS_SOURCE_CAP_DISABLED) != 0) { continue; - if ((caps & OBS_SOURCE_CAP_OBSOLETE) != 0) + } + if ((caps & OBS_SOURCE_CAP_OBSOLETE) != 0) { continue; + } types.emplace_back(type_str, name); } @@ -481,8 +495,9 @@ QMenu *OBSBasicFilters::CreateAddFilterPopupMenu(bool async) for (FilterInfo &type : types) { uint32_t filterFlags = obs_get_source_output_flags(type.type.c_str()); - if (!filter_compatible(async, sourceFlags, filterFlags)) + if (!filter_compatible(async, sourceFlags, filterFlags)) { continue; + } QAction *popupItem = new QAction(QT_UTF8(type.name.c_str()), this); popupItem->setData(QT_UTF8(type.type.c_str())); @@ -515,8 +530,9 @@ void OBSBasicFilters::AddNewFilter(const char *id) bool success = NameDialog::AskForName(this, QTStr("Basic.Filters.AddFilter.Title"), QTStr("Basic.Filters.AddFilter.Text"), name, text); - if (!success) + if (!success) { return; + } if (name.empty()) { OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); @@ -586,8 +602,9 @@ void OBSBasicFilters::AddNewFilter(const char *id) void OBSBasicFilters::closeEvent(QCloseEvent *event) { QDialog::closeEvent(event); - if (!event->isAccepted()) + if (!event->isAccepted()) { return; + } obs_display_remove_draw_callback(ui->preview->GetDisplay(), OBSBasicFilters::DrawPreview, this); @@ -656,8 +673,9 @@ void OBSBasicFilters::DrawPreview(void *data, uint32_t cx, uint32_t cy) { OBSBasicFilters *window = static_cast(data); - if (!window->source) + if (!window->source) { return; + } uint32_t sourceCX = max(obs_source_get_width(window->source), 1u); uint32_t sourceCY = max(obs_source_get_height(window->source), 1u); @@ -707,31 +725,35 @@ void OBSBasicFilters::on_addAsyncFilter_clicked() { ui->asyncFilters->setFocus(); QScopedPointer popup(CreateAddFilterPopupMenu(true)); - if (popup) + if (popup) { popup->exec(QCursor::pos()); + } } void OBSBasicFilters::on_removeAsyncFilter_clicked() { OBSSource filter = GetFilter(ui->asyncFilters->currentRow(), true); if (filter) { - if (QueryRemove(this, filter)) + if (QueryRemove(this, filter)) { delete_filter(filter); + } } } void OBSBasicFilters::on_moveAsyncFilterUp_clicked() { OBSSource filter = GetFilter(ui->asyncFilters->currentRow(), true); - if (filter) + if (filter) { obs_source_filter_set_order(source, filter, OBS_ORDER_MOVE_UP); + } } void OBSBasicFilters::on_moveAsyncFilterDown_clicked() { OBSSource filter = GetFilter(ui->asyncFilters->currentRow(), true); - if (filter) + if (filter) { obs_source_filter_set_order(source, filter, OBS_ORDER_MOVE_DOWN); + } } void OBSBasicFilters::on_asyncFilters_GotFocus() @@ -749,8 +771,9 @@ void OBSBasicFilters::on_addEffectFilter_clicked() { ui->effectFilters->setFocus(); QScopedPointer popup(CreateAddFilterPopupMenu(false)); - if (popup) + if (popup) { popup->exec(QCursor::pos()); + } } void OBSBasicFilters::on_removeEffectFilter_clicked() @@ -766,15 +789,17 @@ void OBSBasicFilters::on_removeEffectFilter_clicked() void OBSBasicFilters::on_moveEffectFilterUp_clicked() { OBSSource filter = GetFilter(ui->effectFilters->currentRow(), false); - if (filter) + if (filter) { obs_source_filter_set_order(source, filter, OBS_ORDER_MOVE_UP); + } } void OBSBasicFilters::on_moveEffectFilterDown_clicked() { OBSSource filter = GetFilter(ui->effectFilters->currentRow(), false); - if (filter) + if (filter) { obs_source_filter_set_order(source, filter, OBS_ORDER_MOVE_DOWN); + } } void OBSBasicFilters::on_effectFilters_GotFocus() @@ -790,34 +815,38 @@ void OBSBasicFilters::on_effectFilters_currentRowChanged(int row) void OBSBasicFilters::on_actionRemoveFilter_triggered() { - if (ui->asyncFilters->hasFocus()) + if (ui->asyncFilters->hasFocus()) { on_removeAsyncFilter_clicked(); - else if (ui->effectFilters->hasFocus()) + } else if (ui->effectFilters->hasFocus()) { on_removeEffectFilter_clicked(); + } } void OBSBasicFilters::on_actionMoveUp_triggered() { - if (ui->asyncFilters->hasFocus()) + if (ui->asyncFilters->hasFocus()) { on_moveAsyncFilterUp_clicked(); - else if (ui->effectFilters->hasFocus()) + } else if (ui->effectFilters->hasFocus()) { on_moveEffectFilterUp_clicked(); + } } void OBSBasicFilters::on_actionMoveDown_triggered() { - if (ui->asyncFilters->hasFocus()) + if (ui->asyncFilters->hasFocus()) { on_moveAsyncFilterDown_clicked(); - else if (ui->effectFilters->hasFocus()) + } else if (ui->effectFilters->hasFocus()) { on_moveEffectFilterDown_clicked(); + } } void OBSBasicFilters::on_actionRenameFilter_triggered() { - if (ui->asyncFilters->hasFocus()) + if (ui->asyncFilters->hasFocus()) { RenameAsyncFilter(); - else if (ui->effectFilters->hasFocus()) + } else if (ui->effectFilters->hasFocus()) { RenameEffectFilter(); + } } void OBSBasicFilters::CustomContextMenu(const QPoint &pos, bool async) @@ -828,8 +857,9 @@ void OBSBasicFilters::CustomContextMenu(const QPoint &pos, bool async) QMenu popup(window()); QPointer addMenu = CreateAddFilterPopupMenu(async); - if (addMenu) + if (addMenu) { popup.addMenu(addMenu); + } if (item) { popup.addSeparator(); @@ -862,8 +892,9 @@ void OBSBasicFilters::CustomContextMenu(const QPoint &pos, bool async) void OBSBasicFilters::EditItem(QListWidgetItem *item, bool async) { - if (editActive) + if (editActive) { return; + } Qt::ItemFlags flags = item->flags(); OBSSource filter = item->data(Qt::UserRole).value(); @@ -893,8 +924,9 @@ void OBSBasicFilters::DuplicateItem(QListWidgetItem *item) bool success = NameDialog::AskForName(this, QTStr("Basic.Filters.AddFilter.Title"), QTStr("Basic.Filters.AddFilter.Text"), name, text); - if (!success) + if (!success) { return; + } if (name.empty()) { OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); @@ -953,8 +985,9 @@ void OBSBasicFilters::FilterNameEdited(QWidget *editor, QListWidget *list) bool sameName = (name == prevName); OBSSourceAutoRelease foundFilter = nullptr; - if (!sameName) + if (!sameName) { foundFilter = obs_source_get_filter_by_name(source, name.c_str()); + } if (foundFilter || name.empty() || sameName) { listItem->setText(QT_UTF8(prevName)); @@ -1015,11 +1048,13 @@ void OBSBasicFilters::ResetFilters() OBSSource filter = GetFilter(row, isAsync); - if (!filter) + if (!filter) { return; + } - if (!ConfirmReset(this)) + if (!ConfirmReset(this)) { return; + } OBSDataAutoRelease settings = obs_source_get_settings(filter); @@ -1028,8 +1063,9 @@ void OBSBasicFilters::ResetFilters() obs_data_clear(settings); - if (!view->DeferUpdate()) + if (!view->DeferUpdate()) { obs_source_update(filter, nullptr); + } view->ReloadProperties(); } @@ -1038,10 +1074,11 @@ void OBSBasicFilters::CopyFilter() { OBSSource filter = nullptr; - if (isAsync) + if (isAsync) { filter = GetFilter(ui->asyncFilters->currentRow(), true); - else + } else { filter = GetFilter(ui->effectFilters->currentRow(), false); + } main->copyFilter = OBSGetWeakRef(filter); } @@ -1049,8 +1086,9 @@ void OBSBasicFilters::CopyFilter() void OBSBasicFilters::PasteFilter() { OBSSource filter = OBSGetStrongRef(main->copyFilter); - if (!filter) + if (!filter) { return; + } OBSDataArrayAutoRelease undo_array = obs_source_backup_filters(source); obs_source_copy_single_filter(source, filter); @@ -1105,17 +1143,19 @@ void OBSBasicFilters::FiltersMoved(const QModelIndex &, int srcIdxStart, int, co QListWidget *list = isAsync ? ui->asyncFilters : ui->effectFilters; int neighborIdx = 0; - if (srcIdxStart < list->currentRow()) + if (srcIdxStart < list->currentRow()) { neighborIdx = list->currentRow() - 1; - else if (srcIdxStart > list->currentRow()) + } else if (srcIdxStart > list->currentRow()) { neighborIdx = list->currentRow() + 1; - else + } else { return; + } - if (neighborIdx > list->count() - 1) + if (neighborIdx > list->count() - 1) { neighborIdx = list->count() - 1; - else if (neighborIdx < 0) + } else if (neighborIdx < 0) { neighborIdx = 0; + } OBSSource neighbor = GetFilter(neighborIdx, isAsync); int idx = obs_source_filter_get_index(source, neighbor); diff --git a/frontend/dialogs/OBSBasicFilters.hpp b/frontend/dialogs/OBSBasicFilters.hpp index a02d519140cc03..068d458f7c3be9 100644 --- a/frontend/dialogs/OBSBasicFilters.hpp +++ b/frontend/dialogs/OBSBasicFilters.hpp @@ -120,8 +120,9 @@ private slots: inline void UpdateSource(obs_source_t *target) { - if (source == target) + if (source == target) { UpdateFilters(); + } } protected: diff --git a/frontend/dialogs/OBSBasicInteraction.cpp b/frontend/dialogs/OBSBasicInteraction.cpp index 0deeb652510d81..278b0cfc0bdde8 100644 --- a/frontend/dialogs/OBSBasicInteraction.cpp +++ b/frontend/dialogs/OBSBasicInteraction.cpp @@ -59,8 +59,9 @@ OBSBasicInteraction::OBSBasicInteraction(QWidget *parent, OBSSource source_) ui->preview->setFocusPolicy(Qt::StrongFocus); ui->preview->installEventFilter(eventFilter.get()); - if (cx > 400 && cy > 400) + if (cx > 400 && cy > 400) { resize(cx, cy); + } const char *name = obs_source_get_name(source); setWindowTitle(QTStr("Basic.InteractionWindow").arg(QT_UTF8(name))); @@ -123,8 +124,9 @@ void OBSBasicInteraction::DrawPreview(void *data, uint32_t cx, uint32_t cy) { OBSBasicInteraction *window = static_cast(data); - if (!window->source) + if (!window->source) { return; + } uint32_t sourceCX = max(obs_source_get_width(window->source), 1u); uint32_t sourceCY = max(obs_source_get_height(window->source), 1u); @@ -154,8 +156,9 @@ void OBSBasicInteraction::DrawPreview(void *data, uint32_t cx, uint32_t cy) void OBSBasicInteraction::closeEvent(QCloseEvent *event) { QDialog::closeEvent(event); - if (!event->isAccepted()) + if (!event->isAccepted()) { return; + } config_set_int(App()->GetAppConfig(), "InteractionWindow", "cx", width()); config_set_int(App()->GetAppConfig(), "InteractionWindow", "cy", height()); @@ -189,25 +192,31 @@ static int TranslateQtKeyboardEventModifiers(QInputEvent *event, bool mouseEvent { int obsModifiers = INTERACT_NONE; - if (event->modifiers().testFlag(Qt::ShiftModifier)) + if (event->modifiers().testFlag(Qt::ShiftModifier)) { obsModifiers |= INTERACT_SHIFT_KEY; - if (event->modifiers().testFlag(Qt::AltModifier)) + } + if (event->modifiers().testFlag(Qt::AltModifier)) { obsModifiers |= INTERACT_ALT_KEY; + } #ifdef __APPLE__ // Mac: Meta = Control, Control = Command - if (event->modifiers().testFlag(Qt::ControlModifier)) + if (event->modifiers().testFlag(Qt::ControlModifier)) { obsModifiers |= INTERACT_COMMAND_KEY; - if (event->modifiers().testFlag(Qt::MetaModifier)) + } + if (event->modifiers().testFlag(Qt::MetaModifier)) { obsModifiers |= INTERACT_CONTROL_KEY; + } #else // Handle windows key? Can a browser even trap that key? - if (event->modifiers().testFlag(Qt::ControlModifier)) + if (event->modifiers().testFlag(Qt::ControlModifier)) { obsModifiers |= INTERACT_CONTROL_KEY; + } #endif if (!mouseEvent) { - if (event->modifiers().testFlag(Qt::KeypadModifier)) + if (event->modifiers().testFlag(Qt::KeypadModifier)) { obsModifiers |= INTERACT_IS_KEY_PAD; + } } return obsModifiers; @@ -217,12 +226,15 @@ static int TranslateQtMouseEventModifiers(QMouseEvent *event) { int modifiers = TranslateQtKeyboardEventModifiers(event, true); - if (event->buttons().testFlag(Qt::LeftButton)) + if (event->buttons().testFlag(Qt::LeftButton)) { modifiers |= INTERACT_MOUSE_LEFT; - if (event->buttons().testFlag(Qt::MiddleButton)) + } + if (event->buttons().testFlag(Qt::MiddleButton)) { modifiers |= INTERACT_MOUSE_MIDDLE; - if (event->buttons().testFlag(Qt::RightButton)) + } + if (event->buttons().testFlag(Qt::RightButton)) { modifiers |= INTERACT_MOUSE_RIGHT; + } return modifiers; } @@ -252,10 +264,12 @@ bool OBSBasicInteraction::GetSourceRelativeXY(int mouseX, int mouseY, int &relX, } // Confirm mouse is inside the source - if (relX < 0 || relX > int(sourceCX)) + if (relX < 0 || relX > int(sourceCX)) { return false; - if (relY < 0 || relY > int(sourceCY)) + } + if (relY < 0 || relY > int(sourceCY)) { return false; + } return true; } @@ -264,8 +278,9 @@ bool OBSBasicInteraction::HandleMouseClickEvent(QMouseEvent *event) { bool mouseUp = event->type() == QEvent::MouseButtonRelease; int clickCount = 1; - if (event->type() == QEvent::MouseButtonDblClick) + if (event->type() == QEvent::MouseButtonDblClick) { clickCount = 2; + } struct obs_mouse_event mouseEvent = {}; @@ -295,8 +310,9 @@ bool OBSBasicInteraction::HandleMouseClickEvent(QMouseEvent *event) QPoint pos = event->pos(); bool insideSource = GetSourceRelativeXY(pos.x(), pos.y(), mouseEvent.x, mouseEvent.y); - if (mouseUp || insideSource) + if (mouseUp || insideSource) { obs_source_send_mouse_click(source, &mouseEvent, button, mouseUp, clickCount); + } return true; } @@ -329,15 +345,17 @@ bool OBSBasicInteraction::HandleMouseWheelEvent(QWheelEvent *event) const QPoint angleDelta = event->angleDelta(); if (!event->pixelDelta().isNull()) { - if (angleDelta.x()) + if (angleDelta.x()) { xDelta = event->pixelDelta().x(); - else + } else { yDelta = event->pixelDelta().y(); + } } else { - if (angleDelta.x()) + if (angleDelta.x()) { xDelta = angleDelta.x(); - else + } else { yDelta = angleDelta.y(); + } } const QPointF position = event->position(); diff --git a/frontend/dialogs/OBSBasicProperties.cpp b/frontend/dialogs/OBSBasicProperties.cpp index f38cc742be3937..f57162c3691b88 100644 --- a/frontend/dialogs/OBSBasicProperties.cpp +++ b/frontend/dialogs/OBSBasicProperties.cpp @@ -59,8 +59,9 @@ OBSBasicProperties::OBSBasicProperties(QWidget *parent, OBSSource source_) ui->setupUi(this); ui->buttonBox->button(QDialogButtonBox::Ok)->setFocus(); - if (cx > 400 && cy > 400) + if (cx > 400 && cy > 400) { resize(cx, cy); + } /* The OBSData constructor increments the reference once */ obs_data_release(oldSettings); @@ -321,24 +322,27 @@ void OBSBasicProperties::on_buttonBox_clicked(QAbstractButton *button) 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) + 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); + } acceptClicked = true; close(); - if (view->DeferUpdate()) + if (view->DeferUpdate()) { view->UpdateSettings(); + } } else if (val == QDialogButtonBox::RejectRole) { OBSDataAutoRelease settings = obs_source_get_settings(source); obs_data_clear(settings); - if (view->DeferUpdate()) + if (view->DeferUpdate()) { obs_data_apply(settings, oldSettings); - else + } else { obs_source_update(source, oldSettings); + } close(); } @@ -348,8 +352,9 @@ void OBSBasicProperties::DrawPreview(void *data, uint32_t cx, uint32_t cy) { OBSBasicProperties *window = static_cast(data); - if (!window->source) + if (!window->source) { return; + } uint32_t sourceCX = max(obs_source_get_width(window->source), 1u); uint32_t sourceCY = max(obs_source_get_height(window->source), 1u); @@ -380,8 +385,9 @@ void OBSBasicProperties::DrawTransitionPreview(void *data, uint32_t cx, uint32_t { OBSBasicProperties *window = static_cast(data); - if (!window->sourceClone) + if (!window->sourceClone) { return; + } uint32_t sourceCX = max(obs_source_get_width(window->sourceClone), 1u); uint32_t sourceCY = max(obs_source_get_height(window->sourceClone), 1u); @@ -430,8 +436,9 @@ void OBSBasicProperties::reject() void OBSBasicProperties::closeEvent(QCloseEvent *event) { QDialog::closeEvent(event); - if (event->isAccepted()) + if (event->isAccepted()) { Cleanup(); + } } bool OBSBasicProperties::nativeEvent(const QByteArray &, void *message, qintptr *) @@ -481,8 +488,9 @@ bool OBSBasicProperties::ConfirmQuit() switch (button) { case QMessageBox::Save: acceptClicked = true; - if (view->DeferUpdate()) + if (view->DeferUpdate()) { view->UpdateSettings(); + } // Do nothing because the settings are already updated break; case QMessageBox::Discard: diff --git a/frontend/dialogs/OBSBasicSourceSelect.cpp b/frontend/dialogs/OBSBasicSourceSelect.cpp index 44c4ee766879d4..17fe2b5c11a03a 100644 --- a/frontend/dialogs/OBSBasicSourceSelect.cpp +++ b/frontend/dialogs/OBSBasicSourceSelect.cpp @@ -44,15 +44,17 @@ struct AddSourceData { bool OBSBasicSourceSelect::EnumSources(void *data, obs_source_t *source) { - if (obs_source_is_hidden(source)) + if (obs_source_is_hidden(source)) { return true; + } 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) + if (strcmp(id, window->id) == 0) { window->ui->sourceList->addItem(QT_UTF8(name)); + } return true; } @@ -68,8 +70,9 @@ bool OBSBasicSourceSelect::EnumGroups(void *data, obs_source_t *source) OBSScene scene = main->GetCurrentScene(); obs_sceneitem_t *existing = obs_scene_get_group(scene, name); - if (!existing) + if (!existing) { window->ui->sourceList->addItem(QT_UTF8(name)); + } } return true; @@ -96,8 +99,9 @@ void OBSBasicSourceSelect::SourceAdded(OBSSource source) const char *name = obs_source_get_name(source); const char *sourceId = obs_source_get_unversioned_id(source); - if (strcmp(sourceId, id) != 0) + if (strcmp(sourceId, id) != 0) { return; + } ui->sourceList->addItem(name); } @@ -107,13 +111,15 @@ void OBSBasicSourceSelect::SourceRemoved(OBSSource source) const char *name = obs_source_get_name(source); const char *sourceId = obs_source_get_unversioned_id(source); - if (strcmp(sourceId, id) != 0) + if (strcmp(sourceId, id) != 0) { return; + } QList items = ui->sourceList->findItems(name, Qt::MatchFixedString); - if (!items.count()) + if (!items.count()) { return; + } delete items[0]; } @@ -125,31 +131,38 @@ static void AddSource(void *_data, obs_scene_t *scene) sceneitem = obs_scene_add(scene, data->source); - if (data->transform != nullptr) + if (data->transform != nullptr) { obs_sceneitem_set_info2(sceneitem, data->transform); - if (data->crop != nullptr) + } + if (data->crop != nullptr) { obs_sceneitem_set_crop(sceneitem, data->crop); - if (data->blend_method != nullptr) + } + if (data->blend_method != nullptr) { obs_sceneitem_set_blending_method(sceneitem, *data->blend_method); - if (data->blend_mode != nullptr) + } + if (data->blend_mode != nullptr) { obs_sceneitem_set_blending_mode(sceneitem, *data->blend_mode); - if (data->scale_type != nullptr) + } + if (data->scale_type != nullptr) { obs_sceneitem_set_scale_filter(sceneitem, *data->scale_type); + } if (data->show_transition_id && *data->show_transition_id) { OBSSourceAutoRelease source = obs_source_create(data->show_transition_id, data->show_transition_id, data->show_transition_settings, nullptr); - if (source) + if (source) { obs_sceneitem_set_transition(sceneitem, true, source); + } } if (data->hide_transition_id && *data->hide_transition_id) { OBSSourceAutoRelease source = obs_source_create(data->hide_transition_id, data->hide_transition_id, data->hide_transition_settings, nullptr); - if (source) + if (source) { obs_sceneitem_set_transition(sceneitem, false, source); + } } obs_sceneitem_set_transition_duration(sceneitem, true, data->show_transition_duration); @@ -174,8 +187,9 @@ char *get_new_source_name(const char *name, const char *format) for (;;) { OBSSourceAutoRelease existing_source = obs_get_source_by_name(new_name.array); - if (!existing_source) + if (!existing_source) { break; + } dstr_printf(&new_name, format, name, ++inc + 1); } @@ -187,8 +201,9 @@ static void AddExisting(OBSSource source, bool visible, bool duplicate, SourceCo { OBSBasic *main = OBSBasic::Get(); OBSScene scene = main->GetCurrentScene(); - if (!scene) + if (!scene) { return; + } if (duplicate) { OBSSource from = source; @@ -197,8 +212,9 @@ static void AddExisting(OBSSource source, bool visible, bool duplicate, SourceCo obs_source_release(source); bfree(new_name); - if (!source) + if (!source) { return; + } } AddSourceData data; @@ -239,8 +255,9 @@ bool AddNew(QWidget *parent, const char *id, const char *name, const bool visibl OBSBasic *main = OBSBasic::Get(); OBSScene scene = main->GetCurrentScene(); bool success = false; - if (!scene) + if (!scene) { return false; + } OBSSourceAutoRelease source = obs_get_source_by_name(name); if (source && parent) { @@ -282,8 +299,9 @@ void OBSBasicSourceSelect::on_buttonBox_accepted() if (useExisting) { QListWidgetItem *item = ui->sourceList->currentItem(); - if (!item) + if (!item) { return; + } QString source_name = item->text(); AddExisting(QT_TO_UTF8(source_name), visible, false); @@ -324,8 +342,9 @@ void OBSBasicSourceSelect::on_buttonBox_accepted() } 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()); @@ -367,10 +386,11 @@ void OBSBasicSourceSelect::on_buttonBox_rejected() static inline const char *GetSourceDisplayName(const char *id) { - if (strcmp(id, "scene") == 0) + if (strcmp(id, "scene") == 0) { return Str("Basic.Scene"); - else if (strcmp(id, "group") == 0) + } else if (strcmp(id, "group") == 0) { return Str("Group"); + } const char *v_id = obs_get_latest_input_type_id(id); return obs_source_get_display_name(v_id); } @@ -404,19 +424,22 @@ OBSBasicSourceSelect::OBSBasicSourceSelect(OBSBasic *parent, const char *id_, un connect(ui->createNew, &QRadioButton::pressed, this, [&]() { QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok); - if (!button->isEnabled()) + if (!button->isEnabled()) { button->setEnabled(true); + } }); connect(ui->selectExisting, &QRadioButton::pressed, this, [&]() { QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok); bool enabled = ui->sourceList->selectedItems().size() != 0; - if (button->isEnabled() != enabled) + if (button->isEnabled() != enabled) { button->setEnabled(enabled); + } }); connect(ui->sourceList, &QListWidget::itemSelectionChanged, this, [&]() { QPushButton *button = ui->buttonBox->button(QDialogButtonBox::Ok); - if (!button->isEnabled()) + if (!button->isEnabled()) { button->setEnabled(true); + } }); if (strcmp(id_, "scene") == 0) { @@ -435,8 +458,9 @@ OBSBasicSourceSelect::OBSBasicSourceSelect(OBSBasic *parent, const char *id_, un OBSScene scene = GetOBSRef(item); OBSSource sceneSource = obs_scene_get_source(scene); - if (curSceneSource == sceneSource) + if (curSceneSource == sceneSource) { continue; + } const char *name = obs_source_get_name(sceneSource); ui->sourceList->addItem(QT_UTF8(name)); @@ -451,8 +475,9 @@ OBSBasicSourceSelect::OBSBasicSourceSelect(OBSBasic *parent, const char *id_, un void OBSBasicSourceSelect::SourcePaste(SourceCopyInfo &info, bool dup) { OBSSource source = OBSGetStrongRef(info.weak_source); - if (!source) + if (!source) { return; + } AddExisting(source, info.visible, dup, &info); } diff --git a/frontend/dialogs/OBSBasicTransform.cpp b/frontend/dialogs/OBSBasicTransform.cpp index 828aa9acc6b0db..773b6f7201826c 100644 --- a/frontend/dialogs/OBSBasicTransform.cpp +++ b/frontend/dialogs/OBSBasicTransform.cpp @@ -130,10 +130,11 @@ OBSBasicTransform::~OBSBasicTransform() }; std::string redo_data(obs_data_get_json(wrapper)); - if (undo_data.compare(redo_data) != 0) + 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()))), undo_redo, undo_redo, undo_data, redo_data); + } } void OBSBasicTransform::setScene(OBSScene scene) @@ -168,8 +169,9 @@ void OBSBasicTransform::setEnabled(bool enable) void OBSBasicTransform::setItemQt(OBSSceneItem newItem) { item = newItem; - if (item) + if (item) { refreshControls(); + } bool enable = !!item && !obs_sceneitem_locked(item); setEnabled(enable); @@ -180,8 +182,9 @@ void OBSBasicTransform::OBSSceneItemTransform(void *param, calldata_t *data) OBSBasicTransform *window = static_cast(param); OBSSceneItem item = (obs_sceneitem_t *)calldata_ptr(data, "item"); - if (item == window->item && !window->ignoreTransformSignal) + if (item == window->item && !window->ignoreTransformSignal) { QMetaObject::invokeMethod(window, "refreshControls"); + } } void OBSBasicTransform::OBSSceneItemRemoved(void *param, calldata_t *data) @@ -190,8 +193,9 @@ void OBSBasicTransform::OBSSceneItemRemoved(void *param, calldata_t *data) 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) + if (item == window->item) { window->setItem(FindASelectedItem(scene)); + } } void OBSBasicTransform::OBSSceneItemSelect(void *param, calldata_t *data) @@ -199,8 +203,9 @@ void OBSBasicTransform::OBSSceneItemSelect(void *param, calldata_t *data) OBSBasicTransform *window = static_cast(param); OBSSceneItem item = (obs_sceneitem_t *)calldata_ptr(data, "item"); - if (item != window->item) + if (item != window->item) { window->setItem(item); + } } void OBSBasicTransform::OBSSceneItemDeselect(void *param, calldata_t *data) @@ -237,8 +242,9 @@ static int alignToIndex(uint32_t align) { int index = 0; for (uint32_t curAlign : indexToAlign) { - if (curAlign == align) + if (curAlign == align) { return index; + } index++; } @@ -248,8 +254,9 @@ static int alignToIndex(uint32_t align) void OBSBasicTransform::refreshControls() { - if (!item) + if (!item) { return; + } obs_transform_info oti; obs_sceneitem_crop crop; @@ -333,8 +340,9 @@ void OBSBasicTransform::onAlignChanged(int index) void OBSBasicTransform::onBoundsType(int index) { - if (index == -1) + if (index == -1) { return; + } obs_bounds_type type = (obs_bounds_type)index; bool enable = (type != OBS_BOUNDS_NONE); @@ -405,8 +413,9 @@ void OBSBasicTransform::onBoundsType(int index) void OBSBasicTransform::onControlChanged() { - if (ignoreItemChange) + if (ignoreItemChange) { return; + } obs_source_t *source = obs_sceneitem_get_source(item); uint32_t source_cx = obs_source_get_width(source); @@ -441,8 +450,9 @@ void OBSBasicTransform::onControlChanged() void OBSBasicTransform::onCropChanged() { - if (ignoreItemChange) + if (ignoreItemChange) { return; + } obs_sceneitem_crop crop; crop.left = uint32_t(ui->cropLeft->value()); @@ -457,8 +467,9 @@ void OBSBasicTransform::onCropChanged() void OBSBasicTransform::onSceneChanged(QListWidgetItem *current, QListWidgetItem *) { - if (!current) + if (!current) { return; + } OBSScene scene = GetOBSRef(current); this->setScene(scene); diff --git a/frontend/dialogs/OBSBasicVCamConfig.cpp b/frontend/dialogs/OBSBasicVCamConfig.cpp index 3f710749928aac..5242def315e448 100644 --- a/frontend/dialogs/OBSBasicVCamConfig.cpp +++ b/frontend/dialogs/OBSBasicVCamConfig.cpp @@ -48,8 +48,9 @@ void OBSBasicVCamConfig::OutputTypeChanged() for (char **temp = scenes; *temp; temp++) { list->addItem(*temp); - if (config.scene.compare(*temp) == 0) + if (config.scene.compare(*temp) == 0) { list->setCurrentIndex(list->count() - 1); + } } break; } @@ -59,8 +60,9 @@ 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); }; @@ -69,8 +71,9 @@ void OBSBasicVCamConfig::OutputTypeChanged() obs_enum_sources( [](void *data, obs_source_t *source) { auto &AddSource = *static_cast(data); - if (!obs_source_removed(source)) + if (!obs_source_removed(source)) { AddSource(source); + } return true; }, static_cast(&AddSource)); @@ -80,15 +83,17 @@ void OBSBasicVCamConfig::OutputTypeChanged() for (auto &&source : sources) { list->addItem(source.c_str()); - if (config.source == source) + if (config.source == source) { list->setCurrentIndex(list->count() - 1); + } } break; } } - if (!vcamActive) + if (!vcamActive) { return; + } requireRestart = (activeType == VCamOutputType::ProgramView && type != VCamOutputType::ProgramView) || (activeType != VCamOutputType::ProgramView && type == VCamOutputType::ProgramView); diff --git a/frontend/dialogs/OBSLogViewer.cpp b/frontend/dialogs/OBSLogViewer.cpp index 71f16e5cb223e0..74b3e583b98fe4 100644 --- a/frontend/dialogs/OBSLogViewer.cpp +++ b/frontend/dialogs/OBSLogViewer.cpp @@ -95,8 +95,9 @@ void OBSLogViewer::AddLine(int type, const QString &str) QScrollBar *scroll = ui->textArea->verticalScrollBar(); bool bottomScrolled = scroll->value() >= scroll->maximum() - 10; - if (bottomScrolled) + if (bottomScrolled) { scroll->setValue(scroll->maximum()); + } QTextDocument *doc = ui->textArea->document(); QTextCursor cursor(doc); @@ -106,15 +107,17 @@ void OBSLogViewer::AddLine(int type, const QString &str) cursor.insertBlock(); cursor.endEditBlock(); - if (bottomScrolled) + if (bottomScrolled) { scroll->setValue(scroll->maximum()); + } } void OBSLogViewer::on_openButton_clicked() { char logDir[512]; - if (GetAppConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0) + if (GetAppConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0) { return; + } const char *log = App()->GetCurrentLog(); diff --git a/frontend/dialogs/OBSRemux.cpp b/frontend/dialogs/OBSRemux.cpp index 84b28372ec93fb..eb77f788745e44 100644 --- a/frontend/dialogs/OBSRemux.cpp +++ b/frontend/dialogs/OBSRemux.cpp @@ -103,8 +103,9 @@ OBSRemux::OBSRemux(const char *path, QWidget *parent, bool autoRemux_) bool OBSRemux::stopRemux() { - if (!worker->isWorking) + if (!worker->isWorking) { return true; + } // By locking the worker thread's mutex, we ensure that its // update poll will be blocked as long as we're in here with @@ -190,8 +191,9 @@ void OBSRemux::dropEvent(QDropEvent *ev) void OBSRemux::dragEnterEvent(QDragEnterEvent *ev) { - if (ev->mimeData()->hasUrls() && !worker->isWorking) + if (ev->mimeData()->hasUrls() && !worker->isWorking) { ev->accept(); + } } void OBSRemux::beginRemux() @@ -208,15 +210,18 @@ void OBSRemux::beginRemux() QString message = QTStr("Remux.FileExists"); message += "\n\n"; - for (QFileInfo fileInfo : overwriteFiles) + 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; + } } - if (!proceedWithRemux) + if (!proceedWithRemux) { return; + } // Set all jobs to "pending" first. queueModel->beginProcessing(); @@ -264,16 +269,18 @@ void OBSRemux::remuxNextEntry() void OBSRemux::closeEvent(QCloseEvent *event) { - if (!stopRemux()) + if (!stopRemux()) { event->ignore(); - else + } else { QDialog::closeEvent(event); + } } void OBSRemux::reject() { - if (!stopRemux()) + if (!stopRemux()) { return; + } QDialog::reject(); } diff --git a/frontend/dialogs/OBSYoutubeActions.cpp b/frontend/dialogs/OBSYoutubeActions.cpp index cf1c1843082a84..699d6dc4adab13 100644 --- a/frontend/dialogs/OBSYoutubeActions.cpp +++ b/frontend/dialogs/OBSYoutubeActions.cpp @@ -171,11 +171,13 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, bool broadcast connect(workerThread, &WorkerThread::failed, this, [&]() { auto last_error = apiYouTube->GetLastError(); - if (last_error.isEmpty()) + if (last_error.isEmpty()) { last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); + } - if (!apiYouTube->GetTranslatedError(last_error)) + if (!apiYouTube->GetTranslatedError(last_error)) { last_error = QTStr("YouTube.Actions.Error.Text").arg(last_error); + } ShowErrorDialog(this, last_error); QDialog::reject(); @@ -227,15 +229,17 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, bool broadcast }); ui->scrollAreaWidgetContents->layout()->addWidget(label); - if (selectedBroadcast == broadcast) + if (selectedBroadcast == broadcast) { label->clicked(); + } }); workerThread->start(); OBSBasic *main = OBSBasic::Get(); bool rememberSettings = config_get_bool(main->activeConfiguration, "YouTube", "RememberSettings"); - if (rememberSettings) + if (rememberSettings) { LoadSettings(); + } // Switch to events page and select readied broadcast once loaded if (broadcastReady) { @@ -253,8 +257,9 @@ OBSYoutubeActions::OBSYoutubeActions(QWidget *parent, Auth *auth, bool broadcast void OBSYoutubeActions::showEvent(QShowEvent *event) { QDialog::showEvent(event); - if (thumbnailFile.isEmpty()) + if (thumbnailFile.isEmpty()) { ui->thumbnailPreview->setPixmap(GetPlaceholder().pixmap(QSize(16, 16))); + } } OBSYoutubeActions::~OBSYoutubeActions() @@ -267,8 +272,9 @@ OBSYoutubeActions::~OBSYoutubeActions() void WorkerThread::run() { - if (!pending) + if (!pending) { return; + } json11::Json broadcasts; for (QString broadcastStatus : {"active", "upcoming"}) { @@ -288,10 +294,12 @@ void WorkerThread::run() QString stream_id = QString::fromStdString( 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()); @@ -317,11 +325,12 @@ void WorkerThread::run() } auto nextPageToken = broadcasts["nextPageToken"].string_value(); - if (nextPageToken.empty() || items.empty()) + if (nextPageToken.empty() || items.empty()) { break; - else { - if (!pending) + } else { + if (!pending) { return; + } if (!apiYouTube->GetBroadcastsList(broadcasts, QString::fromStdString(nextPageToken), broadcastStatus)) { emit failed(); @@ -420,8 +429,9 @@ bool OBSYoutubeActions::CreateEventAction(YoutubeApiWrappers *api, BroadcastDesc } #ifdef YOUTUBE_ENABLED - if (OBSBasic::Get()->GetYouTubeAppDock()) + if (OBSBasic::Get()->GetYouTubeAppDock()) { OBSBasic::Get()->GetYouTubeAppDock()->BroadcastCreated(broadcast.id.toStdString().c_str()); + } #endif return true; @@ -461,14 +471,16 @@ bool OBSYoutubeActions::ChooseAnEventAction(YoutubeApiWrappers *api, StreamDescr } } - if (broadcastPrivacy != "private") + if (broadcastPrivacy != "private") { apiYouTube->SetChatId(selectedBroadcast); - else + } else { apiYouTube->ResetChat(); + } #ifdef YOUTUBE_ENABLED - if (OBSBasic::Get()->GetYouTubeAppDock()) + if (OBSBasic::Get()->GetYouTubeAppDock()) { OBSBasic::Get()->GetYouTubeAppDock()->BroadcastSelected(selectedBroadcast.toStdString().c_str()); + } #endif return true; @@ -503,8 +515,9 @@ void OBSYoutubeActions::InitBroadcast() ui->checkScheduledLater->isChecked()); } else { success = this->ChooseAnEventAction(apiYouTube, stream); - if (success) + if (success) { broadcast.id = this->selectedBroadcast; + } }; QMetaObject::invokeMethod(&msgBox, "accept", Qt::QueuedConnection); }; @@ -540,10 +553,12 @@ void OBSYoutubeActions::InitBroadcast() } else { // Fail. auto last_error = apiYouTube->GetLastError(); - if (last_error.isEmpty()) + if (last_error.isEmpty()) { last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); - if (!apiYouTube->GetTranslatedError(last_error)) + } + if (!apiYouTube->GetTranslatedError(last_error)) { last_error = QTStr("YouTube.Actions.Error.NoBroadcastCreated").arg(last_error); + } ShowErrorDialog(this, last_error); } @@ -566,8 +581,9 @@ void OBSYoutubeActions::ReadyBroadcast() ui->checkScheduledLater->isChecked(), true); } else { success = this->ChooseAnEventAction(apiYouTube, stream); - if (success) + if (success) { broadcast.id = this->selectedBroadcast; + } }; QMetaObject::invokeMethod(&msgBox, "accept", Qt::QueuedConnection); }; @@ -583,10 +599,12 @@ void OBSYoutubeActions::ReadyBroadcast() } else { // Fail. auto last_error = apiYouTube->GetLastError(); - if (last_error.isEmpty()) + if (last_error.isEmpty()) { last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); - if (!apiYouTube->GetTranslatedError(last_error)) + } + if (!apiYouTube->GetTranslatedError(last_error)) { last_error = QTStr("YouTube.Actions.Error.NoBroadcastCreated").arg(last_error); + } ShowErrorDialog(this, last_error); } @@ -608,8 +626,9 @@ void OBSYoutubeActions::UiToBroadcast(BroadcastDescription &broadcast) broadcast.schedul_for_later = ui->checkScheduledLater->isChecked(); broadcast.projection = ui->check360Video->isChecked() ? "360" : "rectangular"; - if (ui->checkRememberSettings->isChecked()) + if (ui->checkRememberSettings->isChecked()) { SaveSettings(broadcast); + } } void OBSYoutubeActions::SaveSettings(BroadcastDescription &broadcast) @@ -657,10 +676,11 @@ void OBSYoutubeActions::LoadSettings() ui->checkDVR->setChecked(dvr); bool forKids = config_get_bool(main->activeConfiguration, "YouTube", "MadeForKids"); - if (forKids) + if (forKids) { ui->yesMakeForKids->setChecked(true); - else + } else { ui->notMakeForKids->setChecked(true); + } bool schedLater = config_get_bool(main->activeConfiguration, "YouTube", "ScheduleForLater"); ui->checkScheduledLater->setChecked(schedLater); @@ -673,10 +693,11 @@ void OBSYoutubeActions::LoadSettings() const char *projection = config_get_string(main->activeConfiguration, "YouTube", "Projection"); if (projection && *projection) { - if (strcmp(projection, "360") == 0) + if (strcmp(projection, "360") == 0) { ui->check360Video->setChecked(true); - else + } else { ui->check360Video->setChecked(false); + } } const char *thumbFile = config_get_string(main->activeConfiguration, "YouTube", "ThumbnailFile"); diff --git a/frontend/docks/YouTubeAppDock.cpp b/frontend/docks/YouTubeAppDock.cpp index a5b283484da1a7..78a528f38cf23e 100644 --- a/frontend/docks/YouTubeAppDock.cpp +++ b/frontend/docks/YouTubeAppDock.cpp @@ -41,8 +41,9 @@ YouTubeAppDock::YouTubeAppDock(const QString &title) : BrowserDock(title), dockB bool YouTubeAppDock::IsYTServiceSelected() { - if (!cef_js_avail) + if (!cef_js_avail) { return false; + } obs_service_t *service_obj = OBSBasic::Get()->GetService(); OBSDataAutoRelease settings = obs_service_get_settings(service_obj); @@ -74,8 +75,9 @@ void YouTubeAppDock::SettingsUpdated(bool cleanup) } } - if (ytservice) + if (ytservice) { Update(); + } } std::string YouTubeAppDock::InitYTUserUrl() @@ -124,14 +126,17 @@ void YouTubeAppDock::AddYouTubeAppDock() void YouTubeAppDock::CreateBrowserWidget(const std::string &url) { - if (dockBrowser) + if (dockBrowser) { delete dockBrowser; + } dockBrowser = cef->create_widget(this, url, panel_cookies); - if (!dockBrowser) + if (!dockBrowser) { return; + } - if (obs_browser_qcef_version() >= 1) + if (obs_browser_qcef_version() >= 1) { dockBrowser->allowAllPopups(true); + } this->SetWidget(dockBrowser); @@ -142,8 +147,9 @@ void YouTubeAppDock::CreateBrowserWidget(const std::string &url) void YouTubeAppDock::SetVisibleYTAppDockInMenu(bool visible) { - if (visible && toggleViewAction()->isVisible()) + if (visible && toggleViewAction()->isVisible()) { return; + } toggleViewAction()->setVisible(visible); this->setVisible(visible); @@ -208,8 +214,9 @@ void YouTubeAppDock::IngestionStopped(const char *stream_id, streaming_mode_t mo void YouTubeAppDock::showEvent(QShowEvent *) { - if (!dockBrowser) + if (!dockBrowser) { Update(); + } } void YouTubeAppDock::closeEvent(QCloseEvent *event) @@ -220,8 +227,9 @@ void YouTubeAppDock::closeEvent(QCloseEvent *event) void YouTubeAppDock::DispatchYTEvent(const char *event, const char *video_id, streaming_mode_t mode) { - if (!dockBrowser) + if (!dockBrowser) { return; + } // update channelId if empty: UpdateChannelId(); @@ -395,26 +403,30 @@ YoutubeApiWrappers *YouTubeAppDock::GetYTApi() void YouTubeAppDock::CleanupYouTubeUrls() { - if (!cef_js_avail) + if (!cef_js_avail) { return; + } 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"); - if (youtube_cleanup_done) + if (youtube_cleanup_done) { return; + } config_set_bool(App()->GetUserConfig(), "General", "YtDockCleanupDone", true); const char *jsonStr = config_get_string(App()->GetUserConfig(), "BasicWindow", "ExtraBrowserDocks"); - if (!jsonStr) + if (!jsonStr) { return; + } json array = json::parse(jsonStr); - if (!array.is_array()) + if (!array.is_array()) { return; + } json save_array; std::string removedYTUrl; diff --git a/frontend/importer/ImporterEntryPathItemDelegate.cpp b/frontend/importer/ImporterEntryPathItemDelegate.cpp index 520dc5ef90e17f..9d6e592b114835 100644 --- a/frontend/importer/ImporterEntryPathItemDelegate.cpp +++ b/frontend/importer/ImporterEntryPathItemDelegate.cpp @@ -139,8 +139,9 @@ void ImporterEntryPathItemDelegate::handleBrowse(QWidget *container) isSet = true; } - if (isSet) + if (isSet) { emit commitData(container); + } } void ImporterEntryPathItemDelegate::handleClear(QWidget *container) diff --git a/frontend/importer/ImporterModel.cpp b/frontend/importer/ImporterModel.cpp index a4f9cf958cbb0c..eadf63d36be929 100644 --- a/frontend/importer/ImporterModel.cpp +++ b/frontend/importer/ImporterModel.cpp @@ -37,10 +37,11 @@ QVariant ImporterModel::data(const QModelIndex &index, int role) const QVariant result = QVariant(); if (index.row() >= options.length()) { - if (role == ImporterEntryRole::CheckEmpty) + if (role == ImporterEntryRole::CheckEmpty) { result = true; - else + } else { return QVariant(); + } } else if (role == Qt::DisplayRole) { switch (index.column()) { case ImporterColumn::Path: @@ -59,10 +60,11 @@ QVariant ImporterModel::data(const QModelIndex &index, int role) const } else if (role == Qt::CheckStateRole) { switch (index.column()) { case ImporterColumn::Selected: - if (options[index.row()].program != "") + if (options[index.row()].program != "") { result = options[index.row()].selected ? Qt::Checked : Qt::Unchecked; - else + } else { result = Qt::Unchecked; + } } } else if (role == ImporterEntryRole::CheckEmpty) { result = options[index.row()].empty; diff --git a/frontend/importer/OBSImporter.cpp b/frontend/importer/OBSImporter.cpp index 0270388da15aeb..4a90722b769588 100644 --- a/frontend/importer/OBSImporter.cpp +++ b/frontend/importer/OBSImporter.cpp @@ -77,8 +77,9 @@ OBSImporter::OBSImporter(QWidget *parent) : QDialog(parent), optionsModel(new Im bool autoSearch = config_get_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch"); OBSImporterFiles f; - if (autoSearch) + if (autoSearch) { f = ImportersFindFiles(); + } for (size_t i = 0; i < f.size(); i++) { QString path = f[i].c_str(); @@ -125,8 +126,9 @@ void OBSImporter::dropEvent(QDropEvent *ev) void OBSImporter::dragEnterEvent(QDragEnterEvent *ev) { - if (ev->mimeData()->hasUrls()) + if (ev->mimeData()->hasUrls()) { ev->accept(); + } } void OBSImporter::browseImport() @@ -175,8 +177,9 @@ void OBSImporter::importCollections() for (int i = 0; i < optionsModel->rowCount() - 1; i++) { int selected = optionsModel->index(i, ImporterColumn::Selected).data(Qt::CheckStateRole).value(); - if (selected == Qt::Unchecked) + if (selected == Qt::Unchecked) { continue; + } std::string pathStr = optionsModel->index(i, ImporterColumn::Path) .data(Qt::DisplayRole) diff --git a/frontend/importers/classic.cpp b/frontend/importers/classic.cpp index 17d625213665d1..5125e5d3b914ee 100644 --- a/frontend/importers/classic.cpp +++ b/frontend/importers/classic.cpp @@ -26,8 +26,9 @@ static bool source_name_exists(const Json::array &sources, const string &name) { for (size_t i = 0; i < sources.size(); i++) { Json source = sources[i]; - if (name == source["name"].string_value()) + if (name == source["name"].string_value()) { return true; + } } return false; @@ -208,8 +209,9 @@ static Json::object translate_source(const Json &in, const Json &sources) Json browser = Json::parse(browser_dec, err); - if (err != "") + if (err != "") { return Json::object{}; + } Json::object obj = browser.object_items(); @@ -277,8 +279,9 @@ static void translate_sc(const Json &in, Json &out) for (size_t i = 0; i < scenes.size(); i++) { Json in_scene = scenes[i]; - if (first_name.empty()) + if (first_name.empty()) { first_name = in_scene["name"].string_value(); + } Json::array items = Json::array{}; @@ -294,8 +297,9 @@ static void translate_sc(const Json &in, Json &out) items.push_back(out_item); - if (out_source.find("preexist") == out_source.end()) + if (out_source.find("preexist") == out_source.end()) { out_sources.push_back(out_source); + } } out_sources.push_back( @@ -341,12 +345,14 @@ static void create_data_item(Json::object &out, const string &line) { size_t end_pos = line.find(':') - 1; - if (end_pos == string::npos) + if (end_pos == string::npos) { return; + } size_t start_pos = 0; - while (line[start_pos] == ' ') + while (line[start_pos] == ' ') { start_pos++; + } string name = line.substr(start_pos, end_pos - start_pos); const char *c_name = name.c_str(); @@ -404,12 +410,14 @@ static Json::array create_sources(Json::object &out, string &line, string &src) while (!line.empty() && line[l_len - 1] != '}') { size_t end_pos = line.find(':'); - if (end_pos == string::npos) + if (end_pos == string::npos) { return Json::array{}; + } size_t start_pos = 0; - while (line[start_pos] == ' ') + while (line[start_pos] == ' ') { start_pos++; + } string name = line.substr(start_pos, end_pos - start_pos - 1); @@ -423,8 +431,9 @@ static Json::array create_sources(Json::object &out, string &line, string &src) l_len = line.size(); } - if (!out.empty()) + if (!out.empty()) { out["sources"] = res; + } return res; } @@ -433,12 +442,14 @@ static Json::object create_object(Json::object &out, string &line, string &src) { size_t end_pos = line.find(':'); - if (end_pos == string::npos) + if (end_pos == string::npos) { return Json::object{}; + } size_t start_pos = 0; - while (line[start_pos] == ' ') + while (line[start_pos] == ' ') { start_pos++; + } string name = line.substr(start_pos, end_pos - start_pos - 1); @@ -450,22 +461,25 @@ static Json::object create_object(Json::object &out, string &line, string &src) while (!line.empty() && line[l_len] != '}') { start_pos = 0; - while (line[start_pos] == ' ') + while (line[start_pos] == ' ') { start_pos++; + } - if (line.substr(start_pos, 7) == "sources") + if (line.substr(start_pos, 7) == "sources") { create_sources(res, line, src); - else if (line[l_len] == '{') + } else if (line[l_len] == '{') { create_object(res, line, src); - else + } else { create_data_item(res, line); + } line = ReadLine(src); l_len = line.size() - 1; } - if (!out.empty()) + if (!out.empty()) { out[name] = res; + } return res; } @@ -478,11 +492,13 @@ string ClassicImporter::Name(const string &path) int ClassicImporter::ImportScenes(const string &path, string &name, Json &res) { BPtr file_data = os_quick_read_utf8_file(path.c_str()); - if (!file_data) + if (!file_data) { return IMPORTER_FILE_WONT_OPEN; + } - if (name.empty()) + if (name.empty()) { name = GetFilenameFromPath(path); + } Json::object data = Json::object{}; data["name"] = name; @@ -514,13 +530,15 @@ bool ClassicImporter::Check(const string &path) { BPtr file_data = os_quick_read_utf8_file(path.c_str()); - if (!file_data) + if (!file_data) { return false; + } bool check = false; - if (strncmp(file_data, "scenes : {\r\n", 12) == 0) + if (strncmp(file_data, "scenes : {\r\n", 12) == 0) { check = true; + } return check; } @@ -532,14 +550,16 @@ OBSImporterFiles ClassicImporter::FindFiles() #ifdef _WIN32 char dst[512]; int found = os_get_config_path(dst, 512, "OBS\\sceneCollection\\"); - if (found == -1) + if (found == -1) { return res; + } os_dir_t *dir = os_opendir(dst); struct os_dirent *ent; while ((ent = os_readdir(dir)) != NULL) { - if (ent->directory || *ent->d_name == '.') + if (ent->directory || *ent->d_name == '.') { continue; + } string name = ent->d_name; size_t pos = name.find(".xconfig"); diff --git a/frontend/importers/importers.hpp b/frontend/importers/importers.hpp index 8160f793e10893..007d4ca7520de9 100644 --- a/frontend/importers/importers.hpp +++ b/frontend/importers/importers.hpp @@ -103,8 +103,9 @@ static inline std::string GetFilenameFromPath(const std::string &path) { #ifdef _WIN32 size_t pos = path.find_last_of('\\'); - if (pos == -1 || pos < path.find_last_of('/')) + if (pos == -1 || pos < path.find_last_of('/')) { pos = path.find_last_of('/'); + } #else size_t pos = path.find_last_of('/'); #endif @@ -121,8 +122,9 @@ static inline std::string GetFolderFromPath(const std::string &path) { #ifdef _WIN32 size_t pos = path.find_last_of('\\'); - if (pos == -1 || pos < path.find_last_of('/')) + if (pos == -1 || pos < path.find_last_of('/')) { pos = path.find_last_of('/'); + } #else size_t pos = path.find_last_of('/'); #endif @@ -147,14 +149,17 @@ static inline std::string ReadLine(std::string &str) size_t pos = str.find('\n'); - if (pos == std::string::npos) + if (pos == std::string::npos) { pos = str.find(EOF); + } - if (pos == std::string::npos) + if (pos == std::string::npos) { pos = str.find('\0'); + } - if (pos == std::string::npos) + if (pos == std::string::npos) { return ""; + } std::string res = str.substr(0, pos); str = str.substr(pos + 1); diff --git a/frontend/importers/sl.cpp b/frontend/importers/sl.cpp index ac8e473efadafa..7f1b2554b9b085 100644 --- a/frontend/importers/sl.cpp +++ b/frontend/importers/sl.cpp @@ -114,8 +114,9 @@ static bool source_name_exists(const Json::array &sources, const string &name) Json item = sources[i]; string source_name = item["name"].string_value(); - if (source_name == name) + if (source_name == name) { return true; + } } return false; @@ -127,8 +128,9 @@ static string get_source_name_from_id(const Json &root, const Json::array &sourc Json item = sources[i]; string source_id = item["sl_id"].string_value(); - if (source_id == id) + if (source_id == id) { return item["name"].string_value(); + } } Json::array scene_arr = root["scenes"]["items"].array_items(); @@ -143,8 +145,9 @@ static string get_source_name_from_id(const Json &root, const Json::array &sourc int copy = 1; string out_name = name; - while (source_name_exists(sources, out_name)) + while (source_name_exists(sources, out_name)) { out_name = name + "(" + to_string(copy++) + ")"; + } return out_name; } @@ -169,8 +172,9 @@ static void get_hotkey_bindings(Json::object &out_hotkeys, const Json &in_hotkey string key = translate_key(binding["key"].string_value()); - if (key == "IGNORE") + if (key == "IGNORE") { continue; + } out_hotkey.push_back(Json::object{{"control", modifiers["ctrl"]}, {"shift", modifiers["shift"]}, @@ -285,8 +289,9 @@ static int attempt_import(const Json &root, const string &name, Json &res) int copy = 1; string out_name = name; - while (source_name_exists(out_sources, out_name)) + while (source_name_exists(out_sources, out_name)) { out_name = name + "(" + to_string(copy++) + ")"; + } string sl_id = source["id"].string_value(); @@ -336,11 +341,13 @@ static int attempt_import(const Json &root, const string &name, Json &res) int copy = 1; string out_name = name; - while (source_name_exists(out_sources, out_name)) + while (source_name_exists(out_sources, out_name)) { out_name = name + "(" + to_string(copy++) + ")"; + } - if (scene_name.empty()) + if (scene_name.empty()) { scene_name = out_name; + } string sl_id = scene["id"].string_value(); @@ -368,8 +375,9 @@ static int attempt_import(const Json &root, const string &name, Json &res) string name = transition["name"].string_value(); string id = transition["id"].string_value(); - if (id == t_id) + if (id == t_id) { transition_name = name; + } out_transitions.push_back(Json::object{{"id", transition["type"]}, {"settings", in_settings}, @@ -436,8 +444,9 @@ int SLImporter::ImportScenes(const string &path, string &name, Json &res) std::string err; Json data = Json::parse(file_data, err); - if (err != "") + if (err != "") { return IMPORTER_ERROR_DURING_CONVERSION; + } string node_type = data["nodeType"].string_value(); @@ -473,8 +482,9 @@ bool SLImporter::Check(const string &path) if (!root.is_null()) { string node_type = root["nodeType"].string_value(); - if (node_type == "RootNode") + if (node_type == "RootNode") { check = true; + } } } @@ -489,16 +499,18 @@ OBSImporterFiles SLImporter::FindFiles() int found = os_get_config_path(dst, 512, "slobs-client/SceneCollections/"); - if (found == -1) + if (found == -1) { return res; + } os_dir_t *dir = os_opendir(dst); struct os_dirent *ent; while ((ent = os_readdir(dir)) != NULL) { string name = ent->d_name; - if (ent->directory || name[0] == '.' || name == "manifest.json") + if (ent->directory || name[0] == '.' || name == "manifest.json") { continue; + } size_t pos = name.find_last_of(".json"); size_t end_pos = name.size() - 1; diff --git a/frontend/importers/studio.cpp b/frontend/importers/studio.cpp index 30d72fa6c3c5f2..45c8fc102a384d 100644 --- a/frontend/importers/studio.cpp +++ b/frontend/importers/studio.cpp @@ -151,14 +151,17 @@ static string CheckPath(const string &path, const string &rootDir) *absPath = 0; size_t len = os_get_abs_path((rootDir + path).c_str(), absPath, sizeof(absPath)); - if (len == 0) + if (len == 0) { return path; + } - if (strstr(absPath, root) != absPath) + if (strstr(absPath, root) != absPath) { return path; + } - if (*(absPath + rootLen) != QDir::separator().toLatin1()) + if (*(absPath + rootLen) != QDir::separator().toLatin1()) { return path; + } return absPath; } @@ -172,8 +175,9 @@ void TranslatePaths(Json &res, const string &rootDir) Json val = it->second; if (val.is_string()) { - if (val.string_value().rfind("./", 0) != 0) + if (val.string_value().rfind("./", 0) != 0) { continue; + } out[it->first] = CheckPath(val.string_value(), rootDir); } else if (val.is_array() || val.is_object()) { @@ -190,8 +194,9 @@ void TranslatePaths(Json &res, const string &rootDir) Json val = out[i]; if (val.is_string()) { - if (val.string_value().rfind("./", 0) != 0) + if (val.string_value().rfind("./", 0) != 0) { continue; + } out[i] = CheckPath(val.string_value(), rootDir); } else if (val.is_array() || val.is_object()) { @@ -210,20 +215,25 @@ bool StudioImporter::Check(const string &path) string err; Json collection = Json::parse(file_data, err); - if (err != "") + if (err != "") { return false; + } - if (collection.is_null()) + if (collection.is_null()) { return false; + } - if (collection["sources"].is_null()) + if (collection["sources"].is_null()) { return false; + } - if (collection["name"].is_null()) + if (collection["name"].is_null()) { return false; + } - if (collection["current_scene"].is_null()) + if (collection["current_scene"].is_null()) { return false; + } return true; } @@ -242,18 +252,21 @@ string StudioImporter::Name(const string &path) int StudioImporter::ImportScenes(const string &path, string &name, Json &res) { - if (!os_file_exists(path.c_str())) + if (!os_file_exists(path.c_str())) { return IMPORTER_FILE_NOT_FOUND; + } - if (!Check(path.c_str())) + if (!Check(path.c_str())) { return IMPORTER_FILE_NOT_RECOGNISED; + } BPtr file_data = os_quick_read_utf8_file(path.c_str()); string err; Json d = Json::parse(file_data, err); - if (err != "") + if (err != "") { return IMPORTER_ERROR_DURING_CONVERSION; + } QDir dir(path.c_str()); @@ -262,10 +275,11 @@ int StudioImporter::ImportScenes(const string &path, string &name, Json &res) Json::object obj = d.object_items(); - if (name != "") + if (name != "") { obj["name"] = name; - else + } else { obj["name"] = "OBS Studio Import"; + } res = obj; diff --git a/frontend/importers/xsplit.cpp b/frontend/importers/xsplit.cpp index 516da73ed0d362..f5bab6b04c8007 100644 --- a/frontend/importers/xsplit.cpp +++ b/frontend/importers/xsplit.cpp @@ -27,16 +27,18 @@ static int hex_string_to_int(string str) { int res = 0; - if (str[0] == '#') + if (str[0] == '#') { str = str.substr(1); + } for (size_t i = 0, l = str.size(); i < l; i++) { res *= 16; - if (str[0] >= '0' && str[0] <= '9') + if (str[0] >= '0' && str[0] <= '9') { res += str[0] - '0'; - else + } else { res += str[0] - 'A' + 10; + } str = str.substr(1); } @@ -53,24 +55,27 @@ static Json::object parse_text(QString &config) string err; Json data = Json::parse(config.toStdString(), err); - if (err != "") + if (err != "") { return Json::object{}; + } string outline = data["outline"].string_value(); int out = 0; - if (outline == "thick") + if (outline == "thick") { out = 20; - else if (outline == "thicker") + } else if (outline == "thicker") { out = 40; - else if (outline == "thinner") + } else if (outline == "thinner") { out = 5; - else if (outline == "thin") + } else if (outline == "thin") { out = 10; + } string valign = data["vertAlign"].string_value(); - if (valign == "middle") + if (valign == "middle") { valign = "center"; + } Json font = Json::object{{"face", data["fontStyle"]}, {"size", 200}}; @@ -96,8 +101,9 @@ static Json::array parse_playlist(QString &playlist) out.push_back(Json::object{{"value", path.toStdString()}}); int next = playlist.indexOf('|'); - if (next == -1) + if (next == -1) { break; + } playlist = playlist.mid(next + 1); } @@ -114,8 +120,9 @@ static void parse_media_types(QDomNamedNodeMap &attr, Json::object &source, Json settings["playlist"] = parse_playlist(playlist); QString end_op = attr.namedItem("OpWhenFinished").nodeValue(); - if (end_op == "2") + if (end_op == "2") { settings["loop"] = true; + } } else { QString url = attr.namedItem("item").nodeValue(); int sep = url.indexOf("://"); @@ -149,22 +156,25 @@ static void parse_media_types(QDomNamedNodeMap &attr, Json::object &source, Json static Json::object parse_slideshow(QString &config) { int start = config.indexOf("images\":["); - if (start == -1) + if (start == -1) { return Json::object{}; + } config = config.mid(start + 8); config.replace("\\\\", "/"); int end = config.indexOf(']'); - if (end == -1) + if (end == -1) { return Json::object{}; + } string arr = config.left(end + 1).toStdString(); string err; Json::array files = Json::parse(arr, err).array_items(); - if (err != "") + if (err != "") { return Json::object{}; + } Json::array files_out = Json::array{}; @@ -178,8 +188,9 @@ static Json::object parse_slideshow(QString &config) Json opt = Json::parse(options.toStdString(), err); - if (err != "") + if (err != "") { return Json::object{}; + } return Json::object{{"randomize", opt["random"]}, {"slide_time", opt["delay"].number_value() * 1000 + 700}, @@ -189,8 +200,9 @@ static Json::object parse_slideshow(QString &config) static bool source_name_exists(const string &name, const Json::array &sources) { for (size_t i = 0; i < sources.size(); i++) { - if (sources.at(i)["name"].string_value() == name) + if (sources.at(i)["name"].string_value() == name) { return true; + } } return false; @@ -199,8 +211,9 @@ static bool source_name_exists(const string &name, const Json::array &sources) static Json get_source_with_id(const string &src_id, const Json::array &sources) { for (size_t i = 0; i < sources.size(); i++) { - if (sources.at(i)["src_id"].string_value() == src_id) + if (sources.at(i)["src_id"].string_value() == src_id) { return sources.at(i); + } } return nullptr; @@ -227,8 +240,9 @@ static void parse_items(QDomNode &item, Json::array &items, Json::array &sources } name = attr.namedItem("cname").nodeValue().toStdString(); - if (name.empty() || name[0] == '\0') + if (name.empty() || name[0] == '\0') { name = attr.namedItem("name").nodeValue().toStdString(); + } temp_name = name; while (source_name_exists(temp_name, sources)) { @@ -394,8 +408,9 @@ static Json::object parse_scenes(QDomElement &scenes) QString name = attr.namedItem("name").nodeValue(); QString id = attr.namedItem("id").nodeValue(); - if (first.isEmpty()) + if (first.isEmpty()) { first = name; + } Json out = Json::object{{"id", "scene"}, {"name", name.toStdString().c_str()}, @@ -429,13 +444,15 @@ static Json::object parse_scenes(QDomElement &scenes) int XSplitImporter::ImportScenes(const string &path, string &name, json11::Json &res) { - if (name == "") + if (name == "") { name = "XSplit Import"; + } BPtr file_data = os_quick_read_utf8_file(path.c_str()); - if (!file_data) + if (!file_data) { return IMPORTER_FILE_WONT_OPEN; + } QDomDocument doc; doc.setContent(QString(file_data)); @@ -461,8 +478,9 @@ bool XSplitImporter::Check(const string &path) BPtr file_data = os_quick_read_utf8_file(path.c_str()); - if (!file_data) + if (!file_data) { return false; + } string pos = file_data.Get(); @@ -488,8 +506,9 @@ OBSImporterFiles XSplitImporter::FindFiles() char dst[512]; int found = os_get_program_data_path(dst, 512, "SplitMediaLabs\\XSplit\\Presentation2.0\\"); - if (found == -1) + if (found == -1) { return res; + } os_dir_t *dir = os_opendir(dst); struct os_dirent *ent; @@ -497,8 +516,9 @@ OBSImporterFiles XSplitImporter::FindFiles() while ((ent = os_readdir(dir)) != NULL) { string name = ent->d_name; - if (ent->directory || name[0] == '.') + if (ent->directory || name[0] == '.') { continue; + } if (name == "Placements.bpres") { string str = dst + name; diff --git a/frontend/oauth/Auth.cpp b/frontend/oauth/Auth.cpp index 89b579f8ee149c..5a197fdb65d16f 100644 --- a/frontend/oauth/Auth.cpp +++ b/frontend/oauth/Auth.cpp @@ -54,8 +54,9 @@ void Auth::Load() { OBSBasic *main = OBSBasic::Get(); const char *typeStr = config_get_string(main->Config(), "Auth", "Type"); - if (!typeStr) + if (!typeStr) { typeStr = ""; + } main->auth = Create(typeStr); if (main->auth) { diff --git a/frontend/oauth/AuthListener.cpp b/frontend/oauth/AuthListener.cpp index 9298a18e5e3b6f..1c955ccdbeeb8b 100644 --- a/frontend/oauth/AuthListener.cpp +++ b/frontend/oauth/AuthListener.cpp @@ -72,10 +72,11 @@ void AuthListener::NewConnection() if (match.hasMatch()) { if (state == match.captured("state")) { match = re_code.match(redirect); - if (!match.hasMatch()) + if (!match.hasMatch()) { blog(LOG_DEBUG, "no 'code' " "in server " "redirect"); + } code = match.captured("code"); } else { diff --git a/frontend/oauth/OAuth.cpp b/frontend/oauth/OAuth.cpp index a7d6f60d6a2431..aead7c0545d17b 100644 --- a/frontend/oauth/OAuth.cpp +++ b/frontend/oauth/OAuth.cpp @@ -73,10 +73,12 @@ bool OAuth::LoadInternal() bool OAuth::TokenExpired() { - if (token.empty()) + if (token.empty()) { return true; - if ((uint64_t)time(nullptr) > expire_time - 5) + } + if ((uint64_t)time(nullptr) > expire_time - 5) { return true; + } return false; } @@ -142,12 +144,14 @@ try { }; ExecThreadedWithoutBlocking(func, QTStr("Auth.Authing.Title"), QTStr("Auth.Authing.Text").arg(service())); - if (!success || output.empty()) + if (!success || output.empty()) { throw ErrorInfo("Failed to get token from remote", error); + } Json json = Json::parse(output, error); - if (!error.empty()) + if (!error.empty()) { throw ErrorInfo("Failed to parse json", error); + } /* -------------------------- */ /* error handling */ @@ -158,23 +162,26 @@ try { return true; } } - if (!error.empty()) + if (!error.empty()) { throw ErrorInfo(error, json["error_description"].string_value()); + } /* -------------------------- */ /* success! */ expire_time = (uint64_t)time(nullptr) + json["expires_in"].int_value(); token = json["access_token"].string_value(); - if (token.empty()) + if (token.empty()) { throw ErrorInfo("Failed to get token from remote", error); + } if (!auth_code.empty()) { refresh_token = json["refresh_token"].string_value(); - if (refresh_token.empty()) + if (refresh_token.empty()) { throw ErrorInfo("Failed to get refresh token from " "remote", error); + } currentScopeVer = scope_ver; } @@ -195,8 +202,9 @@ try { void OAuthStreamKey::OnStreamConfig() { - if (key_.empty()) + if (key_.empty()) { return; + } OBSBasic *main = OBSBasic::Get(); obs_service_t *service = main->GetService(); @@ -205,10 +213,11 @@ void OAuthStreamKey::OnStreamConfig() bool bwtest = obs_data_get_bool(settings, "bwtest"); - if (bwtest && strcmp(this->service(), "Twitch") == 0) + if (bwtest && strcmp(this->service(), "Twitch") == 0) { obs_data_set_string(settings, "key", (key_ + "?bandwidthtest=true").c_str()); - else + } else { obs_data_set_string(settings, "key", key_.c_str()); + } obs_service_update(service, settings); } diff --git a/frontend/oauth/RestreamAuth.cpp b/frontend/oauth/RestreamAuth.cpp index 92beb9c1d36742..d0e745b1cdbe3f 100644 --- a/frontend/oauth/RestreamAuth.cpp +++ b/frontend/oauth/RestreamAuth.cpp @@ -34,8 +34,9 @@ RestreamAuth::RestreamAuth(const Def &d) : OAuthStreamKey(d) {} RestreamAuth::~RestreamAuth() { - if (!uiLoaded) + if (!uiLoaded) { return; + } OBSBasic *main = OBSBasic::Get(); @@ -49,12 +50,15 @@ try { std::string client_id = RESTREAM_CLIENTID; deobfuscate_str(&client_id[0], RESTREAM_HASH); - if (!GetToken(RESTREAM_TOKEN_URL, client_id, RESTREAM_SCOPE_VERSION)) + if (!GetToken(RESTREAM_TOKEN_URL, client_id, RESTREAM_SCOPE_VERSION)) { return false; - if (token.empty()) + } + if (token.empty()) { return false; - if (!key_.empty()) + } + if (!key_.empty()) { return true; + } std::string auth; auth += "Authorization: Bearer "; @@ -76,16 +80,19 @@ try { ExecThreadedWithoutBlocking(func, QTStr("Auth.LoadingChannel.Title"), QTStr("Auth.LoadingChannel.Text").arg(service())); - if (!success || output.empty()) + if (!success || output.empty()) { throw ErrorInfo("Failed to get stream key from remote", error); + } json = Json::parse(output, error); - if (!error.empty()) + if (!error.empty()) { throw ErrorInfo("Failed to parse json", error); + } error = json["error"].string_value(); - if (!error.empty()) + if (!error.empty()) { throw ErrorInfo(error, json["error_description"].string_value()); + } key_ = json["streamKey"].string_value(); @@ -121,12 +128,15 @@ bool RestreamAuth::LoadInternal() void RestreamAuth::LoadUI() { - if (!cef) + if (!cef) { return; - if (uiLoaded) + } + if (uiLoaded) { return; - if (!GetChannelInfo()) + } + if (!GetChannelInfo()) { return; + } OBSBasic::InitBrowserPanelSafeBlock(); OBSBasic *main = OBSBasic::Get(); @@ -266,8 +276,9 @@ static void DeleteCookies() void RegisterRestreamAuth() { #if !defined(__APPLE__) && !defined(_WIN32) - if (QApplication::platformName().contains("wayland")) + if (QApplication::platformName().contains("wayland")) { return; + } #endif OAuth::RegisterOAuth(restreamDef, CreateRestreamAuth, RestreamAuth::Login, DeleteCookies); diff --git a/frontend/oauth/TwitchAuth.cpp b/frontend/oauth/TwitchAuth.cpp index 3b35e7291545c7..bcd6d37cd9d9ac 100644 --- a/frontend/oauth/TwitchAuth.cpp +++ b/frontend/oauth/TwitchAuth.cpp @@ -33,8 +33,9 @@ static Auth::Def twitchDef = {"Twitch", Auth::Type::OAuth_StreamKey}; TwitchAuth::TwitchAuth(const Def &d) : OAuthStreamKey(d) { - if (!cef) + if (!cef) { return; + } cef->add_popup_whitelist_url("https://twitch.tv/popout/frankerfacez/chat?ffz-settings", this); @@ -48,8 +49,9 @@ TwitchAuth::TwitchAuth(const Def &d) : OAuthStreamKey(d) TwitchAuth::~TwitchAuth() { - if (!uiLoaded) + if (!uiLoaded) { return; + } OBSBasic *main = OBSBasic::Get(); @@ -95,16 +97,19 @@ bool TwitchAuth::MakeApiRequest(const char *path, Json &json_out) return false; } - if (!success || output.empty()) + if (!success || output.empty()) { throw ErrorInfo("Failed to get text from remote", error); + } json_out = Json::parse(output, error); - if (!error.empty()) + if (!error.empty()) { throw ErrorInfo("Failed to parse json", error); + } error = json_out["error"].string_value(); - if (!error.empty()) + if (!error.empty()) { throw ErrorInfo(error, json_out["message"].string_value()); + } return true; } @@ -114,25 +119,30 @@ try { std::string client_id = TWITCH_CLIENTID; deobfuscate_str(&client_id[0], TWITCH_HASH); - if (!GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION)) + if (!GetToken(TWITCH_TOKEN_URL, client_id, TWITCH_SCOPE_VERSION)) { return false; - if (token.empty()) + } + if (token.empty()) { return false; - if (!key_.empty()) + } + if (!key_.empty()) { return true; + } Json json; bool success = MakeApiRequest("users", json); - if (!success) + if (!success) { return false; + } name = json["data"][0]["login"].string_value(); std::string path = "streams/key?broadcaster_id=" + json["data"][0]["id"].string_value(); success = MakeApiRequest(path.c_str(), json); - if (!success) + if (!success) { return false; + } key_ = json["data"][0]["stream_key"].string_value(); @@ -167,8 +177,9 @@ static inline std::string get_config_str(OBSBasic *main, const char *section, co bool TwitchAuth::LoadInternal() { - if (!cef) + if (!cef) { return false; + } OBSBasic *main = OBSBasic::Get(); name = get_config_str(main, service(), "Name"); @@ -197,12 +208,15 @@ static const char *referrer_script2 = "'; }});"; void TwitchAuth::LoadUI() { - if (!cef) + if (!cef) { return; - if (uiLoaded) + } + if (uiLoaded) { return; - if (!GetChannelInfo()) + } + if (!GetChannelInfo()) { return; + } OBSBasic::InitBrowserPanelSafeBlock(); OBSBasic *main = OBSBasic::Get(); @@ -253,10 +267,12 @@ void TwitchAuth::LoadUI() const int twAddonChoice = config_get_int(main->Config(), service(), "AddonChoice"); if (twAddonChoice) { - if (twAddonChoice & 0x1) + if (twAddonChoice & 0x1) { script += bttv_script; - if (twAddonChoice & 0x2) + } + if (twAddonChoice & 0x2) { script += ffz_script; + } } browser->setStartupScript(script); @@ -305,10 +321,12 @@ void TwitchAuth::LoadSecondaryUIPanes() const int twAddonChoice = config_get_int(main->Config(), service(), "AddonChoice"); if (twAddonChoice) { - if (twAddonChoice & 0x1) + if (twAddonChoice & 0x1) { script += bttv_script; - if (twAddonChoice & 0x2) + } + if (twAddonChoice & 0x2) { script += ffz_script; + } } /* ----------------------------------- */ @@ -396,8 +414,9 @@ void TwitchAuth::LoadSecondaryUIPanes() const char *dockStateStr = config_get_string(main->Config(), service(), "DockState"); QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); - if (main->isVisible() || !main->isMaximized()) + if (main->isVisible() || !main->isMaximized()) { main->restoreState(dockState); + } } } @@ -474,15 +493,17 @@ static std::shared_ptr CreateTwitchAuth() static void DeleteCookies() { - if (panel_cookies) + if (panel_cookies) { panel_cookies->DeleteCookies("twitch.tv", std::string()); + } } void RegisterTwitchAuth() { #if !defined(__APPLE__) && !defined(_WIN32) - if (QApplication::platformName().contains("wayland")) + if (QApplication::platformName().contains("wayland")) { return; + } #endif OAuth::RegisterOAuth(twitchDef, CreateTwitchAuth, TwitchAuth::Login, DeleteCookies); diff --git a/frontend/oauth/YoutubeAuth.cpp b/frontend/oauth/YoutubeAuth.cpp index 399cab11c8af43..2e02f3202a5210 100644 --- a/frontend/oauth/YoutubeAuth.cpp +++ b/frontend/oauth/YoutubeAuth.cpp @@ -58,8 +58,9 @@ YoutubeAuth::YoutubeAuth(const Def &d) : OAuthStreamKey(d), section(SECTION_NAME YoutubeAuth::~YoutubeAuth() { - if (!uiLoaded) + if (!uiLoaded) { return; + } #ifdef BROWSER_AVAILABLE OBSBasic *main = OBSBasic::Get(); @@ -107,12 +108,14 @@ bool YoutubeAuth::LoadInternal() void YoutubeAuth::LoadUI() { - if (uiLoaded) + if (uiLoaded) { return; + } #ifdef BROWSER_AVAILABLE - if (!cef) + if (!cef) { return; + } OBSBasic::InitBrowserPanelSafeBlock(); OBSBasic *main = OBSBasic::Get(); @@ -191,8 +194,9 @@ QString YoutubeAuth::GenerateState() QRandomGenerator *rng = QRandomGenerator::system(); int i; - for (i = 0; i < YOUTUBE_API_STATE_LENGTH; i++) + for (i = 0; i < YOUTUBE_API_STATE_LENGTH; i++) { state[i] = allowedChars[rng->bounded(0, allowedCount)]; + } state[i] = 0; return state; @@ -285,8 +289,9 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, const std::string &serv 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, QT_TO_UTF8(auth_code), true)) { @@ -297,8 +302,9 @@ std::shared_ptr YoutubeAuth::Login(QWidget *owner, const std::string &serv config_remove_value(config, "YouTube", "ChannelName"); ChannelDescription cd; - if (auth->GetChannelDescription(cd)) + if (auth->GetChannelDescription(cd)) { config_set_string(config, "YouTube", "ChannelName", QT_TO_UTF8(cd.title)); + } config_save_safe(config, "tmp", nullptr); return auth; diff --git a/frontend/obs-main.cpp b/frontend/obs-main.cpp index 93601058f7bf23..ca60f7a9ce054e 100644 --- a/frontend/obs-main.cpp +++ b/frontend/obs-main.cpp @@ -127,8 +127,9 @@ static inline void LogStringChunk(fstream &logFile, char *str, int log_level) while (*nextLine) { char *nextLine = strchr(str, '\n'); - if (!nextLine) + if (!nextLine) { break; + } if (nextLine != str && nextLine[-1] == '\r') { nextLine[-1] = 0; @@ -150,8 +151,9 @@ static inline void LogStringChunk(fstream &logFile, char *str, int log_level) static inline int sum_chars(const char *str) { int val = 0; - for (; *str != 0; str++) + for (; *str != 0; str++) { val += *str; + } return val; } @@ -228,13 +230,15 @@ static void do_log(int log_level, const char *msg, va_list args, void *param) #if !defined(_WIN32) && !defined(_DEBUG) def_log_handler(log_level, msg, args2, nullptr); #endif - if (!too_many_repeated_entries(logFile, msg, str)) + if (!too_many_repeated_entries(logFile, msg, str)) { LogStringChunk(logFile, str, log_level); + } } #if defined(_WIN32) && defined(OBS_DEBUGBREAK_ON_ERROR) - if (log_level <= LOG_ERROR && IsDebuggerPresent()) + if (log_level <= LOG_ERROR && IsDebuggerPresent()) { __debugbreak(); + } #endif #ifndef _WIN32 @@ -245,10 +249,12 @@ static void do_log(int log_level, const char *msg, va_list args, void *param) static bool get_token(lexer *lex, string &str, base_token_type type) { base_token token; - if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) { return false; - if (token.type != type) + } + if (token.type != type) { return false; + } str.assign(token.text.array, token.text.len); return true; @@ -257,10 +263,12 @@ static bool get_token(lexer *lex, string &str, base_token_type type) static bool expect_token(lexer *lex, const char *str, base_token_type type) { base_token token; - if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) { return false; - if (token.type != type) + } + if (token.type != type) { return false; + } return strref_cmp(&token.text, str) == 0; } @@ -274,30 +282,41 @@ static uint64_t convert_log_name(bool has_prefix, const char *name) if (has_prefix) { string temp; - if (!get_token(lex, temp, BASETOKEN_ALPHA)) + if (!get_token(lex, temp, BASETOKEN_ALPHA)) { return 0; + } } - if (!get_token(lex, year, BASETOKEN_DIGIT)) + if (!get_token(lex, year, BASETOKEN_DIGIT)) { return 0; - if (!expect_token(lex, "-", BASETOKEN_OTHER)) + } + if (!expect_token(lex, "-", BASETOKEN_OTHER)) { return 0; - if (!get_token(lex, month, BASETOKEN_DIGIT)) + } + if (!get_token(lex, month, BASETOKEN_DIGIT)) { return 0; - if (!expect_token(lex, "-", BASETOKEN_OTHER)) + } + if (!expect_token(lex, "-", BASETOKEN_OTHER)) { return 0; - if (!get_token(lex, day, BASETOKEN_DIGIT)) + } + if (!get_token(lex, day, BASETOKEN_DIGIT)) { return 0; - if (!get_token(lex, hour, BASETOKEN_DIGIT)) + } + if (!get_token(lex, hour, BASETOKEN_DIGIT)) { return 0; - if (!expect_token(lex, "-", BASETOKEN_OTHER)) + } + if (!expect_token(lex, "-", BASETOKEN_OTHER)) { return 0; - if (!get_token(lex, minute, BASETOKEN_DIGIT)) + } + if (!get_token(lex, minute, BASETOKEN_DIGIT)) { return 0; - if (!expect_token(lex, "-", BASETOKEN_OTHER)) + } + if (!expect_token(lex, "-", BASETOKEN_OTHER)) { return 0; - if (!get_token(lex, second, BASETOKEN_DIGIT)) + } + if (!get_token(lex, second, BASETOKEN_DIGIT)) { return 0; + } stringstream timestring; timestring << year << month << day << hour << minute << second; @@ -312,20 +331,25 @@ static void move_to_xdg(void) char old_path[512]; char new_path[512]; char *home = getenv("HOME"); - if (!home) + if (!home) { return; + } - if (snprintf(old_path, sizeof(old_path), "%s/.obs-studio", home) <= 0) + if (snprintf(old_path, sizeof(old_path), "%s/.obs-studio", home) <= 0) { return; + } /* make base xdg path if it doesn't already exist */ - if (GetAppConfigPath(new_path, sizeof(new_path), "") <= 0) + if (GetAppConfigPath(new_path, sizeof(new_path), "") <= 0) { return; - if (os_mkdirs(new_path) == MKDIR_ERROR) + } + if (os_mkdirs(new_path) == MKDIR_ERROR) { return; + } - if (GetAppConfigPath(new_path, sizeof(new_path), "obs-studio") <= 0) + if (GetAppConfigPath(new_path, sizeof(new_path), "obs-studio") <= 0) { return; + } if (os_file_exists(old_path) && !os_file_exists(new_path)) { rename(old_path, new_path); @@ -347,8 +371,9 @@ static void delete_oldest_file(bool has_prefix, const char *location) unsigned int count = 0; while ((entry = os_readdir(dir)) != NULL) { - if (entry->directory || *entry->d_name == '.') + if (entry->directory || *entry->d_name == '.') { continue; + } uint64_t ts = convert_log_name(has_prefix, entry->d_name); @@ -382,8 +407,9 @@ static void get_last_log(bool has_prefix, const char *subdir_to_use, std::string if (dir) { while ((entry = os_readdir(dir)) != NULL) { - if (entry->directory || *entry->d_name == '.') + if (entry->directory || *entry->d_name == '.') { continue; + } uint64_t ts = convert_log_name(has_prefix, entry->d_name); @@ -448,12 +474,14 @@ ProfilerSnapshot GetSnapshot() static void SaveProfilerData(const ProfilerSnapshot &snap) { - if (currentLogFile.empty()) + if (currentLogFile.empty()) { return; + } auto pos = currentLogFile.rfind('.'); - if (pos == currentLogFile.npos) + if (pos == currentLogFile.npos) { return; + } #define LITERAL_SIZE(x) x, (sizeof(x) - 1) ostringstream dst; @@ -463,8 +491,9 @@ static void SaveProfilerData(const ProfilerSnapshot &snap) #undef LITERAL_SIZE BPtr path = GetAppConfigPathPtr(dst.str().c_str()); - if (!profiler_snapshot_dump_csv_gz(snap.get(), path)) + if (!profiler_snapshot_dump_csv_gz(snap.get(), path)) { blog(LOG_WARNING, "Could not save profiler data to '%s'", static_cast(path)); + } } static auto ProfilerFree = [](void *) { @@ -482,8 +511,9 @@ static auto ProfilerFree = [](void *) { QAccessibleInterface *accessibleFactory(const QString &classname, QObject *object) { - if (classname == QLatin1String("VolumeSlider") && object && object->isWidgetType()) + if (classname == QLatin1String("VolumeSlider") && object && object->isWidgetType()) { return new VolumeAccessibleInterface(static_cast(object)); + } return nullptr; } @@ -524,8 +554,9 @@ static int run_program(fstream &logFile, int argc, char *argv[]) * crashes loading saved geometry. Just turn off this theme and let users complain OBS * looks ugly instead of crashing. */ const char *platform_theme = getenv("QT_QPA_PLATFORMTHEME"); - if (platform_theme && strcmp(platform_theme, "qt5ct") == 0) + if (platform_theme && strcmp(platform_theme, "qt5ct") == 0) { unsetenv("QT_QPA_PLATFORMTHEME"); + } #endif /* NOTE: This disables an optimisation in Qt that attempts to determine if @@ -576,8 +607,9 @@ static int run_program(fstream &logFile, int argc, char *argv[]) cancel_launch = mb.clickedButton() == cancelButton; } - if (cancel_launch) + if (cancel_launch) { return 0; + } if (!created_log) { create_log_file(logFile); @@ -616,8 +648,9 @@ static int run_program(fstream &logFile, int argc, char *argv[]) } #endif - if (!created_log) + if (!created_log) { create_log_file(logFile); + } program.checkForUncleanShutdown(); @@ -669,8 +702,9 @@ static int run_program(fstream &logFile, int argc, char *argv[]) mb.setDefaultButton(closeButton); mb.exec(); - if (mb.clickedButton() == closeButton) + if (mb.clickedButton() == closeButton) { return 0; + } } #endif @@ -683,8 +717,9 @@ static int run_program(fstream &logFile, int argc, char *argv[]) blog(LOG_INFO, "Command Line Arguments: %s", stor.str().c_str()); } - if (!program.OBSInit()) + if (!program.OBSInit()) { return 0; + } prof.Stop(); @@ -826,11 +861,13 @@ static constexpr char vcRunInstallerUrl[] = "https://obsproject.com/visual-studi static bool vc_runtime_outdated() { win_version_info ver; - if (!get_dll_ver(L"msvcp140.dll", &ver)) + if (!get_dll_ver(L"msvcp140.dll", &ver)) { return true; + } /* Major is always 14 (hence 140.dll), so we only care about minor. */ - if (ver.minor >= 40) + if (ver.minor >= 40) { return false; + } int choice = MessageBoxA(NULL, vcRunErrorMsg, vcRunErrorTitle, MB_OKCANCEL | MB_ICONERROR | MB_TASKMODAL); if (choice == IDOK) { @@ -892,8 +929,9 @@ int main(int argc, char *argv[]) #ifdef _WIN32 // Abort as early as possible if MSVC runtime is outdated - if (vc_runtime_outdated()) + if (vc_runtime_outdated()) { return 1; + } // Try to keep this as early as possible install_dll_blocklist_hook(); @@ -963,16 +1001,19 @@ int main(int argc, char *argv[]) opt_start_virtualcam = true; } else if (arg_is(argv[i], "--collection", nullptr)) { - if (++i < argc) + if (++i < argc) { opt_starting_collection = argv[i]; + } } else if (arg_is(argv[i], "--profile", nullptr)) { - if (++i < argc) + if (++i < argc) { opt_starting_profile = argv[i]; + } } else if (arg_is(argv[i], "--scene", nullptr)) { - if (++i < argc) + if (++i < argc) { opt_starting_scene = argv[i]; + } } else if (arg_is(argv[i], "--minimize-to-tray", nullptr)) { opt_minimize_tray = true; diff --git a/frontend/plugin-manager/PluginManager.cpp b/frontend/plugin-manager/PluginManager.cpp index 30805c387b95e1..5cd351d453bdc2 100644 --- a/frontend/plugin-manager/PluginManager.cpp +++ b/frontend/plugin-manager/PluginManager.cpp @@ -39,8 +39,9 @@ void addModuleToPluginManagerImpl(void *param, obs_module_t *newModule) std::string moduleName = obs_get_module_file_name(newModule); moduleName = moduleName.substr(0, moduleName.rfind(".")); - if (!obs_get_module_allow_disable(moduleName.c_str())) + if (!obs_get_module_allow_disable(moduleName.c_str())) { return; + } const char *display_name = obs_get_module_name(newModule); std::string module_name = moduleName; diff --git a/frontend/plugins/aja-output-ui/AJAOutputUI.cpp b/frontend/plugins/aja-output-ui/AJAOutputUI.cpp index d457067d69ec8b..6f0bbd0f8c62f9 100644 --- a/frontend/plugins/aja-output-ui/AJAOutputUI.cpp +++ b/frontend/plugins/aja-output-ui/AJAOutputUI.cpp @@ -37,8 +37,9 @@ void AJAOutputUI::ShowHideDialog() void AJAOutputUI::SetupPropertiesView() { - if (propertiesView) + if (propertiesView) { delete propertiesView; + } obs_data_t *settings = obs_data_create(); OBSData data = load_settings(kProgramPropsFilename); @@ -77,14 +78,16 @@ void AJAOutputUI::SaveSettings(const char *filename, obs_data_t *settings) BPtr path = obs_module_get_config_path(obs_current_module(), filename); - if (settings) + if (settings) { obs_data_save_json_safe(settings, path, "tmp", "bak"); + } } void AJAOutputUI::SetupPreviewPropertiesView() { - if (previewPropertiesView) + if (previewPropertiesView) { delete previewPropertiesView; + } obs_data_t *settings = obs_data_create(); @@ -167,11 +170,13 @@ void AJAOutputUI::PreviewOutputStateChanged(bool active) static obs_properties_t *create_misc_props_ui(void *vp) { AJAOutputUI *outputUI = (AJAOutputUI *)vp; - if (!outputUI) + if (!outputUI) { return nullptr; + } aja::CardManager *cardManager = outputUI->GetCardManager(); - if (!cardManager) + if (!cardManager) { return nullptr; + } bool haveMultiView = false; for (auto &c : *cardManager) { @@ -229,8 +234,9 @@ aja::CardManager *AJAOutputUI::GetCardManager() void AJAOutputUI::SetupMiscPropertiesView() { - if (miscPropertiesView) + if (miscPropertiesView) { delete miscPropertiesView; + } obs_data_t *settings = obs_data_create(); OBSData data = load_settings(kMiscPropsFilename); diff --git a/frontend/plugins/aja-output-ui/aja-ui-main.cpp b/frontend/plugins/aja-output-ui/aja-ui-main.cpp index 587ab879d3c726..2b479051fc8cfe 100644 --- a/frontend/plugins/aja-output-ui/aja-ui-main.cpp +++ b/frontend/plugins/aja-output-ui/aja-ui-main.cpp @@ -78,17 +78,19 @@ void output_start() ajaOutputUI->OutputStateChanged(started); - if (!started) + if (!started) { output_stop(); + } } } void output_toggle() { - if (main_output_running) + if (main_output_running) { output_stop(); - else + } else { output_start(); + } } void on_preview_scene_changed(enum obs_frontend_event event, void *param); @@ -163,26 +165,30 @@ void preview_output_start() preview_output_running = started; ajaOutputUI->PreviewOutputStateChanged(started); - if (!started) + if (!started) { preview_output_stop(); + } } } void preview_output_toggle() { - if (preview_output_running) + if (preview_output_running) { preview_output_stop(); - else + } else { preview_output_start(); + } } void populate_misc_device_list(obs_property_t *list, aja::CardManager *cardManager, NTV2DeviceID &firstDeviceID) { for (const auto &iter : *cardManager) { - if (!iter.second) + if (!iter.second) { continue; - if (firstDeviceID == DEVICE_ID_NOTFOUND) + } + 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()); } @@ -208,14 +214,17 @@ 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 *, obs_data_t *settings) { const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return false; + } aja::CardManager *cardManager = (aja::CardManager *)data; - if (!cardManager) + if (!cardManager) { return false; + } auto cardEntry = cardManager->GetCardEntry(cardID); - if (!cardEntry) + if (!cardEntry) { return false; + } NTV2DeviceID deviceID = cardEntry->GetDeviceID(); bool enableMultiViewUI = NTV2DeviceCanDoHDMIMultiView(deviceID); @@ -270,14 +279,17 @@ bool on_multi_view_toggle(void *data, obs_properties_t *, obs_property_t *, obs_ !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]) + if (!cardID || !cardID[0]) { return false; + } aja::CardManager *cardManager = (aja::CardManager *)data; - if (!cardManager) + if (!cardManager) { return false; + } CNTV2Card *card = cardManager->GetCard(cardID); - if (!card) + if (!card) { return false; + } NTV2InputSource inputSource = (NTV2InputSource)audioInputSource; toggle_multi_view(card, inputSource, multiViewEnabled); @@ -315,8 +327,9 @@ void render_preview_source(void *param, uint32_t, uint32_t) { auto ctx = (struct preview_output *)param; - if (!ctx->current_source) + if (!ctx->current_source) { return; + } uint32_t width = obs_source_get_base_width(ctx->current_source); uint32_t height = obs_source_get_base_height(ctx->current_source); @@ -381,22 +394,26 @@ 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); } } else if (event == OBS_FRONTEND_EVENT_EXIT) { - if (main_output_running) + if (main_output_running) { output_stop(); - if (preview_output_running) + } + if (preview_output_running) { preview_output_stop(); + } } } @@ -404,8 +421,9 @@ static void aja_loaded(void * /* data */, calldata_t *calldata) { // Receive CardManager pointer from the main AJA plugin calldata_get_ptr(calldata, "card_manager", &cardManager); - if (ajaOutputUI) + if (ajaOutputUI) { ajaOutputUI->SetCardManager(cardManager); + } } bool obs_module_load(void) diff --git a/frontend/plugins/decklink-captions/decklink-captions.cpp b/frontend/plugins/decklink-captions/decklink-captions.cpp index f3d02cdb194bab..8d94992bfa8318 100644 --- a/frontend/plugins/decklink-captions/decklink-captions.cpp +++ b/frontend/plugins/decklink-captions/decklink-captions.cpp @@ -34,12 +34,14 @@ DecklinkCaptionsUI::DecklinkCaptionsUI(QWidget *parent) : QDialog(parent), ui(ne uint32_t caps = obs_source_get_output_flags(source); QString name = obs_source_get_name(source); - if (caps & OBS_SOURCE_CEA_708) + if (caps & OBS_SOURCE_CEA_708) { ui->source->addItem(name); + } OBSWeakSource weak = OBSGetWeakRef(source); - if (weak == captions->source) + if (weak == captions->source) { ui->source->setCurrentText(name); + } return true; }; @@ -86,8 +88,9 @@ void obs_captions::start() void obs_captions::stop() { OBSSource s = OBSGetStrongRef(source); - if (s) + if (s) { obs_source_remove_caption_callback(s, caption_callback, nullptr); + } } static void save_decklink_caption_data(obs_data_t *save_data, bool saving, void *) @@ -103,8 +106,9 @@ static void save_decklink_caption_data(obs_data_t *save_data, bool saving, void captions->stop(); obs_data_t *obj = obs_data_get_obj(save_data, "decklink_captions"); - if (!obj) + if (!obj) { obj = obs_data_create(); + } captions->source_name = obs_data_get_string(obj, "source"); captions->source = GetWeakSourceByName(captions->source_name.c_str()); @@ -143,8 +147,9 @@ bool obs_module_load(void) void obs_module_post_load(void) { - if (!obs_get_module("decklink")) + if (!obs_get_module("decklink")) { return; + } addOutputUI(); } diff --git a/frontend/plugins/decklink-output-ui/DecklinkOutputUI.cpp b/frontend/plugins/decklink-output-ui/DecklinkOutputUI.cpp index 6738b9af0ee02d..87602f3ed9a36c 100644 --- a/frontend/plugins/decklink-output-ui/DecklinkOutputUI.cpp +++ b/frontend/plugins/decklink-output-ui/DecklinkOutputUI.cpp @@ -26,14 +26,16 @@ void DecklinkOutputUI::ShowHideDialog() void DecklinkOutputUI::SetupPropertiesView() { - if (propertiesView) + if (propertiesView) { delete propertiesView; + } obs_data_t *settings = obs_data_create(); OBSData data = load_settings(); - if (data) + if (data) { obs_data_apply(settings, data); + } propertiesView = new OBSPropertiesView(settings, "decklink_output", (PropertiesReloadCallback)obs_get_output_properties, 170); @@ -53,20 +55,23 @@ void DecklinkOutputUI::SaveSettings() BPtr path = obs_module_get_config_path(obs_current_module(), "decklinkOutputProps.json"); obs_data_t *settings = propertiesView->GetSettings(); - if (settings) + if (settings) { obs_data_save_json_safe(settings, path, "tmp", "bak"); + } } void DecklinkOutputUI::SetupPreviewPropertiesView() { - if (previewPropertiesView) + if (previewPropertiesView) { delete previewPropertiesView; + } obs_data_t *settings = obs_data_create(); OBSData data = load_preview_settings(); - if (data) + if (data) { obs_data_apply(settings, data); + } previewPropertiesView = new OBSPropertiesView(settings, "decklink_output", (PropertiesReloadCallback)obs_get_output_properties, 170); @@ -86,8 +91,9 @@ void DecklinkOutputUI::SavePreviewSettings() BPtr path = obs_module_get_config_path(obs_current_module(), "decklinkPreviewOutputProps.json"); obs_data_t *settings = previewPropertiesView->GetSettings(); - if (settings) + if (settings) { obs_data_save_json_safe(settings, path, "tmp", "bak"); + } } void DecklinkOutputUI::on_outputButton_clicked() diff --git a/frontend/plugins/decklink-output-ui/decklink-ui-main.cpp b/frontend/plugins/decklink-output-ui/decklink-ui-main.cpp index 325cfe1e8cedea..c29a165a8753cc 100644 --- a/frontend/plugins/decklink-output-ui/decklink-ui-main.cpp +++ b/frontend/plugins/decklink-output-ui/decklink-ui-main.cpp @@ -80,8 +80,9 @@ void output_stop() main_output_running = false; - if (!shutting_down) + if (!shutting_down) { doUI->OutputStateChanged(false); + } } void output_start() @@ -103,12 +104,14 @@ void output_start() obs_enter_graphics(); context.texrender_premultiplied = nullptr; context.texrender = gs_texrender_create(GS_BGRA, GS_ZS_NONE); - for (gs_stagesurf_t *&surf : context.stagesurfaces) + for (gs_stagesurf_t *&surf : context.stagesurfaces) { surf = gs_stagesurface_create(width, height, GS_BGRA); + } obs_leave_graphics(); - for (bool &written : context.surf_written) + for (bool &written : context.surf_written) { written = false; + } context.stage_index = 0; @@ -133,11 +136,13 @@ void output_start() main_output_running = started; - if (!shutting_down) + if (!shutting_down) { doUI->OutputStateChanged(started); + } - if (!started) + if (!started) { output_stop(); + } } else { obs_output_release(output); } @@ -146,10 +151,11 @@ void output_start() void output_toggle() { - if (main_output_running) + if (main_output_running) { output_stop(); - else + } else { output_start(); + } } OBSData load_preview_settings() @@ -173,10 +179,12 @@ static void decklink_ui_tick(void *param, float /* sec */) { auto ctx = (struct decklink_ui_output *)param; - if (ctx->texrender_premultiplied) + if (ctx->texrender_premultiplied) { gs_texrender_reset(ctx->texrender_premultiplied); - if (ctx->texrender) + } + if (ctx->texrender) { gs_texrender_reset(ctx->texrender); + } } void preview_output_stop() @@ -205,8 +213,9 @@ void preview_output_stop() preview_output_running = false; - if (!shutting_down) + if (!shutting_down) { doUI->PreviewOutputStateChanged(false); + } } void preview_output_start() @@ -228,12 +237,14 @@ void preview_output_start() 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) + 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) + for (bool &written : context_preview.surf_written) { written = false; + } context_preview.stage_index = 0; @@ -262,11 +273,13 @@ void preview_output_start() bool started = obs_output_start(context_preview.output); preview_output_running = started; - if (!shutting_down) + if (!shutting_down) { doUI->PreviewOutputStateChanged(started); + } - if (!started) + if (!started) { preview_output_stop(); + } } else { obs_output_release(output); } @@ -275,10 +288,11 @@ void preview_output_start() void preview_output_toggle() { - if (preview_output_running) + if (preview_output_running) { preview_output_stop(); - else + } else { preview_output_start(); + } } void on_preview_scene_changed(enum obs_frontend_event event, void *param) @@ -314,28 +328,33 @@ static void decklink_ui_render(void *param) gs_texture_t *tex = nullptr; if (ctx == &context) { - if (!main_output_running) + if (!main_output_running) { return; + } tex = obs_get_main_texture(); - if (!tex) + if (!tex) { return; + } width = gs_texture_get_width(tex); height = gs_texture_get_height(tex); } else if (ctx == &context_preview) { - if (!preview_output_running) + if (!preview_output_running) { return; + } - if (!ctx->current_source) + if (!ctx->current_source) { return; + } 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; - if (!gs_texrender_begin(texrender_premultiplied, width, height)) + if (!gs_texrender_begin(texrender_premultiplied, width, height)) { return; + } struct vec4 background; vec4_zero(&background); @@ -360,8 +379,9 @@ static void decklink_ui_render(void *param) const uint32_t scaled_width = conversion->width; const uint32_t scaled_height = conversion->height; - if (!gs_texrender_begin(ctx->texrender, scaled_width, scaled_height)) + if (!gs_texrender_begin(ctx->texrender, scaled_width, scaled_height)) { 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); @@ -435,21 +455,25 @@ static void OBSEvent(enum obs_frontend_event event, void *) if (event == OBS_FRONTEND_EVENT_FINISHED_LOADING) { OBSData settings = load_settings(); - if (settings && obs_data_get_bool(settings, "auto_start")) + if (settings && obs_data_get_bool(settings, "auto_start")) { output_start(); + } 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; - if (preview_output_running) + if (preview_output_running) { preview_output_stop(); + } - if (main_output_running) + if (main_output_running) { output_stop(); + } } } @@ -462,17 +486,20 @@ void obs_module_unload(void) { shutting_down = true; - if (preview_output_running) + if (preview_output_running) { preview_output_stop(); + } - if (main_output_running) + if (main_output_running) { output_stop(); + } } void obs_module_post_load(void) { - if (!obs_get_module("decklink")) + if (!obs_get_module("decklink")) { return; + } addOutputUI(); diff --git a/frontend/plugins/frontend-tools/auto-scene-switcher-nix.cpp b/frontend/plugins/frontend-tools/auto-scene-switcher-nix.cpp index 48519dea592fd0..8d10d2c9e614cc 100644 --- a/frontend/plugins/frontend-tools/auto-scene-switcher-nix.cpp +++ b/frontend/plugins/frontend-tools/auto-scene-switcher-nix.cpp @@ -21,16 +21,18 @@ static Display *xdisplay = 0; Display *disp() { - if (!xdisplay) + if (!xdisplay) { xdisplay = XOpenDisplay(NULL); + } return xdisplay; } void CleanupSceneSwitcher() { - if (!xdisplay) + if (!xdisplay) { return; + } XCloseDisplay(xdisplay); xdisplay = 0; @@ -108,8 +110,9 @@ static std::vector getTopLevelWindows() continue; } - for (unsigned long i = 0; i < num; ++i) + for (unsigned long i = 0; i < num; ++i) { res.emplace_back(data[i]); + } XFree(data); } @@ -148,8 +151,9 @@ void GetWindowList(vector &windows) windows.resize(0); for (size_t i = 0; i < getTopLevelWindows().size(); ++i) { - if (GetWindowTitle(i) != "") + if (GetWindowTitle(i) != "") { windows.emplace_back(GetWindowTitle(i)); + } } } diff --git a/frontend/plugins/frontend-tools/auto-scene-switcher-win.cpp b/frontend/plugins/frontend-tools/auto-scene-switcher-win.cpp index 9cc45d0ea55b57..7f4155d778c0f5 100644 --- a/frontend/plugins/frontend-tools/auto-scene-switcher-win.cpp +++ b/frontend/plugins/frontend-tools/auto-scene-switcher-win.cpp @@ -10,8 +10,9 @@ static bool GetWindowTitle(HWND window, string &title) wstring wtitle; wtitle.resize(len); - if (!GetWindowTextW(window, &wtitle[0], (int)len + 1)) + if (!GetWindowTextW(window, &wtitle[0], (int)len + 1)) { return false; + } len = os_wcs_to_utf8(wtitle.c_str(), 0, nullptr, 0); title.resize(len); @@ -25,20 +26,24 @@ static bool WindowValid(HWND window) RECT rect; DWORD id; - if (!IsWindowVisible(window)) + if (!IsWindowVisible(window)) { return false; + } GetWindowThreadProcessId(window, &id); - if (id == GetCurrentProcessId()) + if (id == GetCurrentProcessId()) { return false; + } GetClientRect(window, &rect); styles = GetWindowLongPtr(window, GWL_STYLE); ex_styles = GetWindowLongPtr(window, GWL_EXSTYLE); - if (ex_styles & WS_EX_TOOLWINDOW) + if (ex_styles & WS_EX_TOOLWINDOW) { return false; - if (styles & WS_CHILD) + } + if (styles & WS_CHILD) { return false; + } return true; } @@ -49,8 +54,9 @@ void GetWindowList(vector &windows) while (window) { string title; - if (WindowValid(window) && GetWindowTitle(window, title)) + if (WindowValid(window) && GetWindowTitle(window, title)) { windows.emplace_back(title); + } window = GetNextWindow(window, GW_HWNDNEXT); } } diff --git a/frontend/plugins/frontend-tools/auto-scene-switcher.cpp b/frontend/plugins/frontend-tools/auto-scene-switcher.cpp index 5ba03433a587e3..b9aa081d9b9b3e 100644 --- a/frontend/plugins/frontend-tools/auto-scene-switcher.cpp +++ b/frontend/plugins/frontend-tools/auto-scene-switcher.cpp @@ -53,8 +53,9 @@ struct SwitcherData { { for (size_t i = 0; i < switches.size(); i++) { SceneSwitch &s = switches[i]; - if (!WeakSourceValid(s.scene)) + if (!WeakSourceValid(s.scene)) { switches.erase(switches.begin() + i--); + } } if (nonMatchingScene && !WeakSourceValid(nonMatchingScene)) { @@ -92,10 +93,11 @@ SceneSwitcher::SceneSwitcher(QWidget *parent) : QDialog(parent), ui(new Ui_Scene temp++; } - if (switcher->switchIfNotMatching) + if (switcher->switchIfNotMatching) { ui->noMatchSwitch->setChecked(true); - else + } else { ui->noMatchDontSwitch->setChecked(true); + } ui->noMatchSwitchScene->setCurrentText(GetWeakSourceName(switcher->nonMatchingScene).c_str()); ui->checkInterval->setValue(switcher->interval); @@ -103,8 +105,9 @@ SceneSwitcher::SceneSwitcher(QWidget *parent) : QDialog(parent), ui(new Ui_Scene vector windows; GetWindowList(windows); - for (string &window : windows) + for (string &window : windows) { ui->windows->addItem(window.c_str()); + } for (auto &s : switcher->switches) { string sceneName = GetWeakSourceName(s.scene); @@ -114,10 +117,11 @@ SceneSwitcher::SceneSwitcher(QWidget *parent) : QDialog(parent), ui(new Ui_Scene item->setData(Qt::UserRole, s.window.c_str()); } - if (switcher->th.joinable()) + if (switcher->th.joinable()) { SetStarted(); - else + } else { SetStopped(); + } loading = false; connect(this, &QDialog::finished, this, &SceneSwitcher::finished); @@ -148,10 +152,12 @@ int SceneSwitcher::FindByData(const QString &window) void SceneSwitcher::on_switches_currentRowChanged(int idx) { - if (loading) + if (loading) { return; - if (idx == -1) + } + if (idx == -1) { return; + } QListWidgetItem *item = ui->switches->item(idx); @@ -178,8 +184,9 @@ void SceneSwitcher::on_add_clicked() QString sceneName = ui->scenes->currentText(); QString windowName = ui->windows->currentText(); - if (windowName.isEmpty()) + if (windowName.isEmpty()) { return; + } OBSWeakSource source = GetWeakSourceByQString(sceneName); QVariant v = QVariant::fromValue(windowName); @@ -222,8 +229,9 @@ void SceneSwitcher::on_add_clicked() void SceneSwitcher::on_remove_clicked() { QListWidgetItem *item = ui->switches->currentItem(); - if (!item) + if (!item) { return; + } string window = item->data(Qt::UserRole).toString().toUtf8().constData(); @@ -254,8 +262,9 @@ void SceneSwitcher::UpdateNonMatchingScene(const QString &name) void SceneSwitcher::on_noMatchDontSwitch_clicked() { - if (loading) + if (loading) { return; + } lock_guard lock(switcher->m); switcher->switchIfNotMatching = false; @@ -263,8 +272,9 @@ void SceneSwitcher::on_noMatchDontSwitch_clicked() void SceneSwitcher::on_noMatchSwitch_clicked() { - if (loading) + if (loading) { return; + } lock_guard lock(switcher->m); switcher->switchIfNotMatching = true; @@ -273,8 +283,9 @@ void SceneSwitcher::on_noMatchSwitch_clicked() void SceneSwitcher::on_noMatchSwitchScene_currentTextChanged(const QString &text) { - if (loading) + if (loading) { return; + } lock_guard lock(switcher->m); UpdateNonMatchingScene(text); @@ -282,8 +293,9 @@ void SceneSwitcher::on_noMatchSwitchScene_currentTextChanged(const QString &text void SceneSwitcher::on_checkInterval_valueChanged(int value) { - if (loading) + if (loading) { return; + } lock_guard lock(switcher->m); switcher->interval = value; @@ -349,8 +361,9 @@ static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *) OBSDataArrayAutoRelease array = obs_data_get_array(obj, "switches"); size_t count = obs_data_array_count(array); - if (!obj) + if (!obj) { obj = obs_data_create(); + } obs_data_set_default_int(obj, "interval", DEFAULT_INTERVAL); @@ -374,10 +387,11 @@ static void SaveSceneSwitcher(obs_data_t *save_data, bool saving, void *) switcher->m.unlock(); - if (active) + if (active) { switcher->Start(); - else + } else { switcher->Stop(); + } } } @@ -437,8 +451,9 @@ void SwitcherData::Thread() OBSSourceAutoRelease source = obs_weak_source_get_source(scene); OBSSourceAutoRelease currentSource = obs_frontend_get_current_scene(); - if (source && source != currentSource) + if (source && source != currentSource) { obs_frontend_set_current_scene(source); + } } } @@ -448,8 +463,9 @@ void SwitcherData::Thread() void SwitcherData::Start() { - if (!switcher->th.joinable()) + if (!switcher->th.joinable()) { switcher->th = thread([]() { switcher->Thread(); }); + } } void SwitcherData::Stop() @@ -474,15 +490,17 @@ extern "C" void FreeSceneSwitcher() static void OBSEvent(enum obs_frontend_event event, void *) { - if (event == OBS_FRONTEND_EVENT_EXIT) + if (event == OBS_FRONTEND_EVENT_EXIT) { FreeSceneSwitcher(); + } } extern "C" void InitSceneSwitcher() { #if !defined(__APPLE__) && !defined(_WIN32) - if (QApplication::platformName().contains("wayland")) + if (QApplication::platformName().contains("wayland")) { return; + } #endif QAction *action = (QAction *)obs_frontend_add_tools_menu_qaction(obs_module_text("SceneSwitcher")); diff --git a/frontend/plugins/frontend-tools/captions-handler.cpp b/frontend/plugins/frontend-tools/captions-handler.cpp index 80aa26360b9217..4edc917b1323f1 100644 --- a/frontend/plugins/frontend-tools/captions-handler.cpp +++ b/frontend/plugins/frontend-tools/captions-handler.cpp @@ -2,21 +2,24 @@ captions_handler::captions_handler(captions_cb callback, enum audio_format format, uint32_t sample_rate) : cb(callback) { - if (!reset_resampler(format, sample_rate)) + if (!reset_resampler(format, sample_rate)) { throw CAPTIONS_ERROR_GENERIC_FAIL; + } } bool captions_handler::reset_resampler(enum audio_format format, uint32_t sample_rate) try { obs_audio_info ai; - if (!obs_get_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 dst = {sample_rate, format, SPEAKERS_MONO}; - if (!resampler.reset(dst, src)) + if (!resampler.reset(dst, src)) { throw std::string("Failed to create audio resampler"); + } return true; @@ -34,6 +37,7 @@ void captions_handler::push_audio(const audio_data *audio) success = audio_resampler_resample(resampler, out, &frames, &ts_offset, (const uint8_t *const *)audio->data, audio->frames); - if (success) + if (success) { pcm_data(out[0], frames); + } } diff --git a/frontend/plugins/frontend-tools/captions-mssapi-stream.cpp b/frontend/plugins/frontend-tools/captions-mssapi-stream.cpp index 36182bb251dae0..2b36ec134abc2e 100644 --- a/frontend/plugins/frontend-tools/captions-mssapi-stream.cpp +++ b/frontend/plugins/frontend-tools/captions-mssapi-stream.cpp @@ -49,10 +49,12 @@ void CaptionStream::PushAudio(const void *data, size_t frames) deque_push_back(buf, data, frames * sizeof(int16_t)); write_pos += frames * sizeof(int16_t); - if (wait_size && buf->size >= wait_size) + if (wait_size && buf->size >= wait_size) { ready = true; - if (ready) + } + if (ready) { cv.notify_one(); + } } // IUnknown methods @@ -91,8 +93,9 @@ STDMETHODIMP_(ULONG) CaptionStream::AddRef() STDMETHODIMP_(ULONG) CaptionStream::Release() { ULONG new_refs = (ULONG)os_atomic_dec_long(&refs); - if (!new_refs) + if (!new_refs) { delete this; + } return new_refs; } @@ -105,8 +108,9 @@ STDMETHODIMP CaptionStream::Read(void *data, ULONG bytes, ULONG *read_bytes) size_t cur_size; debugfunc("data, %lu, read_bytes", bytes); - if (!data) + if (!data) { return STG_E_INVALIDPOINTER; + } { lock_guard lock1(m); @@ -116,17 +120,20 @@ STDMETHODIMP CaptionStream::Read(void *data, ULONG bytes, ULONG *read_bytes) unique_lock lock(m); - if (bytes > cur_size) + if (bytes > cur_size) { cv.wait(lock); + } if (bytes > (ULONG)buf->size) { bytes = (ULONG)buf->size; hr = S_FALSE; } - if (bytes) + if (bytes) { deque_pop_front(buf, data, bytes); - if (read_bytes) + } + if (read_bytes) { *read_bytes = bytes; + } wait_size = 0; pos.QuadPart += bytes; @@ -146,11 +153,13 @@ STDMETHODIMP CaptionStream::Seek(LARGE_INTEGER move, DWORD origin, ULARGE_INTEGE { debugfunc("%lld, %lx, new_pos", move, origin); - if (!new_pos) + if (!new_pos) { return E_POINTER; + } - if (origin != SEEK_CUR || move.QuadPart != 0) + if (origin != SEEK_CUR || move.QuadPart != 0) { return E_NOTIMPL; + } *new_pos = pos; return S_OK; @@ -169,12 +178,14 @@ STDMETHODIMP CaptionStream::CopyTo(IStream *stream, ULARGE_INTEGER bytes, ULARGE debugfunc("stream, %llu, read_bytes, written_bytes", bytes); - if (!stream) + if (!stream) { return STG_E_INVALIDPOINTER; + } ULONG written = 0; - if (bytes.QuadPart > (ULONGLONG)buf->size) + if (bytes.QuadPart > (ULONGLONG)buf->size) { bytes.QuadPart = (ULONGLONG)buf->size; + } lock_guard lock(m); temp_buf.resize((size_t)bytes.QuadPart); @@ -182,10 +193,12 @@ STDMETHODIMP CaptionStream::CopyTo(IStream *stream, ULARGE_INTEGER bytes, ULARGE hr = stream->Write(temp_buf.data(), (ULONG)bytes.QuadPart, &written); - if (read_bytes) + if (read_bytes) { *read_bytes = bytes; - if (written_bytes) + } + if (written_bytes) { written_bytes->QuadPart = written; + } return hr; } @@ -223,8 +236,9 @@ STDMETHODIMP CaptionStream::Stat(STATSTG *stg, DWORD flag) { debugfunc("stg, %lu", flag); - if (!stg) + if (!stg) { return E_POINTER; + } lock_guard lock(m); *stg = {}; @@ -253,8 +267,9 @@ STDMETHODIMP CaptionStream::GetFormat(GUID *guid, WAVEFORMATEX **co_mem_wfex_out { debugfunc("guid, co_mem_wfex_out"); - if (!guid || !co_mem_wfex_out) + if (!guid || !co_mem_wfex_out) { return E_POINTER; + } if (format.wFormatTag == 0) { *co_mem_wfex_out = nullptr; @@ -280,14 +295,16 @@ STDMETHODIMP CaptionStream::SetState(SPAUDIOSTATE state_, ULONGLONG) STDMETHODIMP CaptionStream::SetFormat(REFGUID guid_ref, const WAVEFORMATEX *wfex) { debugfunc("guid, wfex"); - if (!wfex) + if (!wfex) { return E_INVALIDARG; + } 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 */ DWORD size = format.nSamplesPerSec / 20; @@ -301,8 +318,9 @@ STDMETHODIMP CaptionStream::GetStatus(SPAUDIOSTATUS *status) { debugfunc("status"); - if (!status) + if (!status) { return E_POINTER; + } /* TODO? */ lock_guard lock(m); @@ -326,8 +344,9 @@ STDMETHODIMP CaptionStream::SetBufferInfo(const SPAUDIOBUFFERINFO *buf_info_) STDMETHODIMP CaptionStream::GetBufferInfo(SPAUDIOBUFFERINFO *buf_info_) { debugfunc("buf_info"); - if (!buf_info_) + if (!buf_info_) { return E_POINTER; + } *buf_info_ = buf_info; return S_OK; @@ -337,8 +356,9 @@ STDMETHODIMP CaptionStream::GetDefaultFormat(GUID *format, WAVEFORMATEX **co_mem { debugfunc("format, co_mem_wfex_out"); - if (!format || !co_mem_wfex_out) + if (!format || !co_mem_wfex_out) { return E_POINTER; + } void *wfex = CoTaskMemAlloc(sizeof(format)); memcpy(wfex, &format, sizeof(format)); @@ -357,8 +377,9 @@ STDMETHODIMP_(HANDLE) CaptionStream::EventHandle(void) STDMETHODIMP CaptionStream::GetVolumeLevel(ULONG *level) { debugfunc("level"); - if (!level) + if (!level) { return E_POINTER; + } *level = vol; return S_OK; @@ -374,8 +395,9 @@ STDMETHODIMP CaptionStream::SetVolumeLevel(ULONG level) STDMETHODIMP CaptionStream::GetBufferNotifySize(ULONG *size) { debugfunc("size"); - if (!size) + if (!size) { return E_POINTER; + } *size = notify_size; return S_OK; } diff --git a/frontend/plugins/frontend-tools/captions-mssapi.cpp b/frontend/plugins/frontend-tools/captions-mssapi.cpp index f551fe0088714e..8df6d894e59226 100644 --- a/frontend/plugins/frontend-tools/captions-mssapi.cpp +++ b/frontend/plugins/frontend-tools/captions-mssapi.cpp @@ -12,8 +12,9 @@ try : captions_handler(callback, AUDIO_FORMAT_16BIT, 16000) { std::wstring wlang; wlang.resize(lang.size()); - for (size_t i = 0; i < lang.size(); i++) + for (size_t i = 0; i < lang.size(); i++) { wlang[i] = (wchar_t)lang[i]; + } LCID lang_id = LocaleNameToLCID(wlang.c_str(), 0); @@ -21,58 +22,70 @@ try : captions_handler(callback, AUDIO_FORMAT_16BIT, 16000) { _snwprintf(lang_str, 31, L"language=%x", (int)lang_id); stop = CreateEvent(nullptr, false, false, nullptr); - if (!stop.Valid()) + if (!stop.Valid()) { throw "Failed to create event"; + } hr = SpFindBestToken(SPCAT_RECOGNIZERS, lang_str, nullptr, &token); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SpFindBestToken failed", hr); + } hr = CoCreateInstance(CLSID_SpInprocRecognizer, nullptr, CLSCTX_ALL, __uuidof(ISpRecognizer), (void **)&recognizer); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("CoCreateInstance for recognizer failed", hr); + } hr = recognizer->SetRecognizer(token); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetRecognizer failed", hr); + } hr = recognizer->SetRecoState(SPRST_INACTIVE); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetRecoState(SPRST_INACTIVE) failed", hr); + } hr = recognizer->CreateRecoContext(&context); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("CreateRecoContext failed", hr); + } ULONGLONG interest = SPFEI(SPEI_RECOGNITION) | SPFEI(SPEI_END_SR_STREAM); hr = context->SetInterest(interest, interest); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetInterest failed", hr); + } hr = context->SetNotifyWin32Event(); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetNotifyWin32Event", hr); + } notify = context->GetNotifyEventHandle(); - if (notify == INVALID_HANDLE_VALUE) + if (notify == INVALID_HANDLE_VALUE) { throw HRError("GetNotifyEventHandle failed", E_NOINTERFACE); + } size_t sample_rate = audio_output_get_sample_rate(obs_get_audio()); audio = new CaptionStream((DWORD)sample_rate, this); audio->Release(); hr = recognizer->SetInput(audio, false); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetInput failed", hr); + } hr = context->CreateGrammar(1, &grammar); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("CreateGrammar failed", hr); + } hr = grammar->LoadDictation(nullptr, SPLO_STATIC); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("LoadDictation failed", hr); + } try { t = std::thread([this]() { main_thread(); }); @@ -104,12 +117,14 @@ try { os_set_thread_name(__FUNCTION__); hr = grammar->SetDictationState(SPRS_ACTIVE); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetDictationState failed", hr); + } hr = recognizer->SetRecoState(SPRST_ACTIVE); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("SetRecoState(SPRST_ACTIVE) failed", hr); + } HANDLE events[] = {notify, stop}; @@ -117,8 +132,9 @@ try { for (;;) { DWORD ret = WaitForMultipleObjects(2, events, false, INFINITE); - if (ret != WAIT_OBJECT_0) + if (ret != WAIT_OBJECT_0) { break; + } CSpEvent event; bool exit = false; @@ -129,8 +145,9 @@ try { CoTaskMemPtr text; hr = result->GetText((ULONG)-1, (ULONG)-1, true, &text, nullptr); - if (FAILED(hr)) + if (FAILED(hr)) { continue; + } char text_utf8[512]; os_wcs_to_utf8(text, 0, text_utf8, 512); @@ -145,8 +162,9 @@ try { } } - if (exit) + if (exit) { break; + } } audio->Stop(); @@ -157,8 +175,9 @@ try { void mssapi_captions::pcm_data(const void *data, size_t frames) { - if (started) + if (started) { audio->PushAudio(data, frames); + } } captions_handler_info mssapi_info = {[]() -> std::string { return "Microsoft Speech-to-Text"; }, diff --git a/frontend/plugins/frontend-tools/captions.cpp b/frontend/plugins/frontend-tools/captions.cpp index db15f94846370d..748fcc1741920c 100644 --- a/frontend/plugins/frontend-tools/captions.cpp +++ b/frontend/plugins/frontend-tools/captions.cpp @@ -86,12 +86,14 @@ CaptionsDialog::CaptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui_Cap uint32_t caps = obs_source_get_output_flags(source); QString name = obs_source_get_name(source); - if (caps & OBS_SOURCE_AUDIO) + if (caps & OBS_SOURCE_AUDIO) { ui->source->addItem(name); + } OBSWeakSource weak = OBSGetWeakRef(source); - if (weak == captions->source) + if (weak == captions->source) { ui->source->setCurrentText(name); + } return true; }; @@ -111,8 +113,9 @@ CaptionsDialog::CaptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui_Cap QString qhandler_id = captions->handler_id.c_str(); int idx = ui->provider->findData(qhandler_id); - if (idx != -1) + if (idx != -1) { ui->provider->setCurrentIndex(idx); + } ui->enable->blockSignals(true); ui->enable->setChecked(!!captions->handler); @@ -135,8 +138,9 @@ CaptionsDialog::CaptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui_Cap } } - if (!set_language && locales.size()) + if (!set_language && locales.size()) { ui->language->setCurrentIndex(0); + } ui->language->blockSignals(false); @@ -147,27 +151,31 @@ CaptionsDialog::CaptionsDialog(QWidget *parent) : QDialog(parent), ui(new Ui_Cap } else if (!set_language) { bool started = !!captions->handler; - if (started) + if (started) { captions->stop(); + } captions->lang_id = locales[0].id; - if (started) + if (started) { captions->start(); + } } } void CaptionsDialog::on_source_currentIndexChanged(int) { bool started = !!captions->handler; - if (started) + if (started) { captions->stop(); + } captions->source_name = ui->source->currentText().toUtf8().constData(); captions->source = GetWeakSourceByName(captions->source_name.c_str()); - if (started) + if (started) { captions->start(); + } } void CaptionsDialog::on_enable_clicked(bool checked) @@ -187,25 +195,29 @@ void CaptionsDialog::on_enable_clicked(bool checked) void CaptionsDialog::on_language_currentIndexChanged(int) { bool started = !!captions->handler; - if (started) + if (started) { captions->stop(); + } captions->lang_id = (LANGID)ui->language->currentData().toInt(); - if (started) + if (started) { captions->start(); + } } void CaptionsDialog::on_provider_currentIndexChanged(int idx) { bool started = !!captions->handler; - if (started) + if (started) { captions->stop(); + } captions->handler_id = ui->provider->itemData(idx).toString().toUtf8().constData(); - if (started) + if (started) { captions->start(); + } } /* ------------------------------------------------------------------------- */ @@ -244,8 +256,9 @@ void obs_captions::start() string lang_name; lang_name.resize(len); - for (size_t i = 0; i < len; i++) + for (size_t i = 0; i < len; i++) { lang_name[i] = (char)wname[i]; + } OBSSource s = OBSGetStrongRef(source); if (!s) { @@ -273,8 +286,9 @@ void obs_captions::start() void obs_captions::stop() { OBSSource s = OBSGetStrongRef(source); - if (s) + if (s) { obs_source_remove_audio_capture_callback(s, audio_capture, nullptr); + } handler.reset(); } @@ -283,8 +297,9 @@ static bool get_locale_name(LANGID id, char *out) wchar_t name[256]; int size = GetLocaleInfoW(id, LOCALE_SENGLISHLANGUAGENAME, name, 256); - if (size <= 0) + if (size <= 0) { return false; + } os_wcs_to_utf8(name, 0, out, 256); return true; @@ -361,8 +376,9 @@ extern "C" void FreeCaptions() static void obs_event(enum obs_frontend_event event, void *) { - if (event == OBS_FRONTEND_EVENT_EXIT) + if (event == OBS_FRONTEND_EVENT_EXIT) { FreeCaptions(); + } } static void save_caption_data(obs_data_t *save_data, bool saving, void *) @@ -380,8 +396,9 @@ static void save_caption_data(obs_data_t *save_data, bool saving, void *) captions->stop(); OBSDataAutoRelease obj = obs_data_get_obj(save_data, "captions"); - if (!obj) + if (!obj) { obj = obs_data_create(); + } obs_data_set_default_int(obj, "lang_id", GetUserDefaultUILanguage()); obs_data_set_default_string(obj, "provider", DEFAULT_HANDLER); @@ -392,8 +409,9 @@ static void save_caption_data(obs_data_t *save_data, bool saving, void *) captions->handler_id = obs_data_get_string(obj, "provider"); captions->source = GetWeakSourceByName(captions->source_name.c_str()); - if (enabled) + if (enabled) { captions->start(); + } } } diff --git a/frontend/plugins/frontend-tools/output-timer.cpp b/frontend/plugins/frontend-tools/output-timer.cpp index 6c3f31004519fb..56e67f995ea9f7 100644 --- a/frontend/plugins/frontend-tools/output-timer.cpp +++ b/frontend/plugins/frontend-tools/output-timer.cpp @@ -81,8 +81,9 @@ void OutputTimer::StreamTimerStart() int total = (((hours * 3600) + (minutes * 60)) + seconds) * 1000; - if (total == 0) + if (total == 0) { total = 1000; + } streamingTimer->setInterval(total); streamingTimer->setSingleShot(true); @@ -109,8 +110,9 @@ void OutputTimer::RecordTimerStart() int total = (((hours * 3600) + (minutes * 60)) + seconds) * 1000; - if (total == 0) + if (total == 0) { total = 1000; + } recordingTimer->setInterval(total); recordingTimer->setSingleShot(true); @@ -128,16 +130,19 @@ void OutputTimer::StreamTimerStop() { streamingAlreadyActive = false; - if (!isVisible() && streamingTimer->isActive() == false) + if (!isVisible() && streamingTimer->isActive() == false) { return; + } - if (streamingTimer->isActive()) + if (streamingTimer->isActive()) { streamingTimer->stop(); + } ui->outputTimerStream->setText(obs_module_text("Start")); - if (streamingTimerDisplay->isActive()) + if (streamingTimerDisplay->isActive()) { streamingTimerDisplay->stop(); + } ui->streamTime->setText("00:00:00"); ui->outputTimerStream->setChecked(false); @@ -147,16 +152,19 @@ void OutputTimer::RecordTimerStop() { recordingAlreadyActive = false; - if (!isVisible() && recordingTimer->isActive() == false) + if (!isVisible() && recordingTimer->isActive() == false) { return; + } - if (recordingTimer->isActive()) + if (recordingTimer->isActive()) { recordingTimer->stop(); + } ui->outputTimerRecord->setText(obs_module_text("Start")); - if (recordingTimerDisplay->isActive()) + if (recordingTimerDisplay->isActive()) { recordingTimerDisplay->stop(); + } ui->recordTime->setText("00:00:00"); ui->outputTimerRecord->setChecked(false); @@ -178,10 +186,11 @@ 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 + } else { remainingTime = recordingTimer->remainingTime() / 1000; + } int seconds = remainingTime % 60; int minutes = (remainingTime % 3600) / 60; @@ -193,8 +202,9 @@ void OutputTimer::UpdateRecordTimerDisplay() void OutputTimer::PauseRecordingTimer() { - if (!ui->pauseRecordTimer->isChecked()) + if (!ui->pauseRecordTimer->isChecked()) { return; + } if (recordingTimer->isActive()) { recordingTimeLeft = recordingTimer->remainingTime(); @@ -204,11 +214,13 @@ void OutputTimer::PauseRecordingTimer() void OutputTimer::UnpauseRecordingTimer() { - if (!ui->pauseRecordTimer->isChecked()) + if (!ui->pauseRecordTimer->isChecked()) { return; + } - if (recordingTimeLeft > 0 && !recordingTimer->isActive()) + if (recordingTimeLeft > 0 && !recordingTimer->isActive()) { recordingTimer->start(recordingTimeLeft); + } } void OutputTimer::ShowHideDialog() @@ -256,8 +268,9 @@ static void SaveOutputTimer(obs_data_t *save_data, bool saving, void *) } else { OBSDataAutoRelease obj = obs_data_get_obj(save_data, "output-timer"); - if (!obj) + 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")); diff --git a/frontend/plugins/frontend-tools/scripts.cpp b/frontend/plugins/frontend-tools/scripts.cpp index 2e007f0448c1a7..06ef0ac150f2ed 100644 --- a/frontend/plugins/frontend-tools/scripts.cpp +++ b/frontend/plugins/frontend-tools/scripts.cpp @@ -155,8 +155,9 @@ void ScriptLogWindow::AddLogMsg(int log_level, QString msg) lines += msg; scriptLogWidget->setPlainText(lines); - if (bottomScrolled) + if (bottomScrolled) { scroll->setValue(scroll->maximum()); + } if (log_level <= LOG_WARNING) { show(); @@ -298,8 +299,9 @@ void ScriptsTool::on_addScripts_clicked() QString filter; while (*cur_format) { - if (!extensions.isEmpty()) + if (!extensions.isEmpty()) { extensions += QStringLiteral(" "); + } extensions += QStringLiteral("*."); extensions += *cur_format; @@ -314,8 +316,9 @@ void ScriptsTool::on_addScripts_clicked() filter += QStringLiteral(")"); } - if (filter.isEmpty()) + if (filter.isEmpty()) { return; + } static std::string lastBrowsedDir; @@ -326,8 +329,9 @@ void ScriptsTool::on_addScripts_clicked() QStringList files = OpenFiles(this, QT_UTF8(obs_module_text("AddScripts")), QT_UTF8(lastBrowsedDir.c_str()), filter); - if (!files.count()) + if (!files.count()) { return; + } for (const QString &file : files) { lastBrowsedDir = QFileInfo(file).absolutePath().toUtf8().constData(); @@ -364,16 +368,18 @@ void ScriptsTool::on_removeScripts_clicked() { QList items = ui->scripts->selectedItems(); - for (QListWidgetItem *item : items) + for (QListWidgetItem *item : items) { RemoveScript(item->data(Qt::UserRole).toString().toUtf8().constData()); + } RefreshLists(); } void ScriptsTool::on_reloadScripts_clicked() { QList items = ui->scripts->selectedItems(); - for (QListWidgetItem *item : items) + for (QListWidgetItem *item : items) { ReloadScript(item->data(Qt::UserRole).toString().toUtf8().constData()); + } on_scripts_currentRowChanged(ui->scripts->currentRow()); } @@ -414,8 +420,9 @@ void ScriptsTool::on_scripts_customContextMenuRequested(const QPoint &pos) void ScriptsTool::on_editScript_clicked() { int row = ui->scripts->currentRow(); - if (row == -1) + if (row == -1) { return; + } QUrl url = QUrl::fromLocalFile(ui->scripts->item(row)->data(Qt::UserRole).toString()); QDesktopServices::openUrl(url); } @@ -431,8 +438,9 @@ void ScriptsTool::on_pythonPathBrowse_clicked() QString curPath = ui->pythonPath->text(); QString newPath = SelectDirectory(this, ui->pythonPathLabel->text(), curPath); - if (newPath.isEmpty()) + if (newPath.isEmpty()) { return; + } QByteArray array = newPath.toUtf8(); const char *path = array.constData(); @@ -454,8 +462,9 @@ void ScriptsTool::on_pythonPathBrowse_clicked() return; } - if (!obs_scripting_load_python(path)) + if (!obs_scripting_load_python(path)) { return; + } updatePythonVersionLabel(); @@ -507,8 +516,9 @@ void ScriptsTool::on_scripts_currentRowChanged(int row) void ScriptsTool::on_defaults_clicked() { QListWidgetItem *item = ui->scripts->currentItem(); - if (!item) + if (!item) { return; + } SetScriptDefaults(item->data(Qt::UserRole).toString().toUtf8().constData()); } @@ -536,8 +546,9 @@ void ScriptsTool::on_description_linkActivated(const QString &link) messageBox.setIcon(QMessageBox::Question); messageBox.exec(); - if (messageBox.clickedButton() == yesButton) + if (messageBox.clickedButton() == yesButton) { QDesktopServices::openUrl(url); + } } } @@ -589,14 +600,16 @@ static void load_script_data(obs_data_t *load_data, bool, void *) } } - if (scriptsWindow) + if (scriptsWindow) { scriptsWindow->RefreshLists(); + } } static void save_script_data(obs_data_t *save_data, bool saving, void *) { - if (!saving) + if (!saving) { return; + } OBSDataArrayAutoRelease array = obs_data_array_create(); @@ -654,8 +667,9 @@ extern "C" void InitScripts() } #endif - if (!obs_scripting_python_loaded() && python_path && *python_path) + if (!obs_scripting_python_loaded() && python_path && *python_path) { obs_scripting_load_python(python_path); + } #endif scriptData = new ScriptData; diff --git a/frontend/settings/OBSBasicSettings.cpp b/frontend/settings/OBSBasicSettings.cpp index 7896a8d8428c51..dcf26d1d718239 100644 --- a/frontend/settings/OBSBasicSettings.cpp +++ b/frontend/settings/OBSBasicSettings.cpp @@ -75,30 +75,37 @@ static bool ConvertResText(const char *res, uint32_t &cx, uint32_t &cy) lexer_start(lex, res); /* parse width */ - if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) { return false; - if (token.type != BASETOKEN_DIGIT) + } + if (token.type != BASETOKEN_DIGIT) { return false; + } cx = std::stoul(token.text.array); /* parse 'x' */ - if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) { return false; - if (strref_cmpi(&token.text, "x") != 0) + } + if (strref_cmpi(&token.text, "x") != 0) { return false; + } /* parse height */ - if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) + if (!lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) { return false; - if (token.type != BASETOKEN_DIGIT) + } + if (token.type != BASETOKEN_DIGIT) { return false; + } cy = std::stoul(token.text.array); /* shouldn't be any more tokens after this */ - if (lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) + if (lexer_getbasetoken(lex, &token, IGNORE_WHITESPACE)) { return false; + } if (ResTooHigh(cx, cy) || ResTooLow(cx, cy)) { cx = cy = 0; @@ -116,8 +123,9 @@ static inline bool WidgetChanged(QWidget *widget) static inline void SetComboByName(QComboBox *combo, const QString &name) { int idx = combo->findText(name); - if (idx != -1) + if (idx != -1) { combo->setCurrentIndex(idx); + } } static inline bool SetComboByValue(QComboBox *combo, const QString &name) @@ -136,8 +144,9 @@ static inline bool SetInvalidValue(QComboBox *combo, const QString &name, const combo->insertItem(0, name, data); QStandardItemModel *model = dynamic_cast(combo->model()); - if (!model) + if (!model) { return false; + } QStandardItem *item = model->item(0); item->setFlags(Qt::NoItemFlags); @@ -149,8 +158,9 @@ static inline bool SetInvalidValue(QComboBox *combo, const QString &name, const static inline QString GetComboData(QComboBox *combo) { int idx = combo->currentIndex(); - if (idx == -1) + if (idx == -1) { return QString(); + } return combo->itemData(idx).toString(); } @@ -177,25 +187,31 @@ static int FindClosestAvailableAudioBitrate(QComboBox *box, int bitrate) int prev = 0; int next = INVALID_BITRATE; - for (int i = 0; i < box->count(); i++) + for (int i = 0; i < box->count(); i++) { bitrates << box->itemText(i).toInt(); + } for (int val : bitrates) { if (next > val) { - if (val == bitrate) + if (val == bitrate) { return bitrate; + } - if (val < next && val > bitrate) + if (val < next && val > bitrate) { next = val; - if (val > prev && val < bitrate) + } + if (val > prev && val < bitrate) { prev = val; + } } } - if (next != INVALID_BITRATE) + if (next != INVALID_BITRATE) { return next; - if (prev != 0) + } + if (prev != 0) { return prev; + } return 192; } #undef INVALID_BITRATE @@ -203,12 +219,14 @@ static int FindClosestAvailableAudioBitrate(QComboBox *box, int bitrate) static void PopulateSimpleBitrates(QComboBox *box, bool opus) { auto &bitrateMap = opus ? GetSimpleOpusEncoderBitrateMap() : GetSimpleAACEncoderBitrateMap(); - if (bitrateMap.empty()) + if (bitrateMap.empty()) { return; + } vector> pairs; - for (auto &entry : bitrateMap) + for (auto &entry : bitrateMap) { pairs.emplace_back(QString::number(entry.first), obs_encoder_get_display_name(entry.second.c_str())); + } QString currentBitrate = box->currentText(); box->clear(); @@ -221,28 +239,32 @@ static void PopulateSimpleBitrates(QComboBox *box, bool opus) if (box->findData(currentBitrate) == -1) { int bitrate = FindClosestAvailableAudioBitrate(box, currentBitrate.toInt()); box->setCurrentText(QString::number(bitrate)); - } else + } else { box->setCurrentText(currentBitrate); + } } static void PopulateAdvancedBitrates(initializer_list boxes, const char *stream_id, const char *rec_id) { auto &streamBitrates = GetAudioEncoderBitrates(stream_id); auto &recBitrates = GetAudioEncoderBitrates(rec_id); - if (streamBitrates.empty() || recBitrates.empty()) + if (streamBitrates.empty() || recBitrates.empty()) { return; + } QList streamBitratesList; - for (auto &bitrate : streamBitrates) + for (auto &bitrate : streamBitrates) { streamBitratesList << bitrate; + } for (auto box : boxes) { QString currentBitrate = box->currentText(); box->clear(); for (auto &bitrate : recBitrates) { - if (streamBitratesList.indexOf(bitrate) == -1) + if (streamBitratesList.indexOf(bitrate) == -1) { continue; + } box->addItem(QString::number(bitrate)); } @@ -250,8 +272,9 @@ static void PopulateAdvancedBitrates(initializer_list boxes, const if (box->findData(currentBitrate) == -1) { int bitrate = FindClosestAvailableAudioBitrate(box, currentBitrate.toInt()); box->setCurrentText(QString::number(bitrate)); - } else + } else { box->setCurrentText(currentBitrate); + } } } @@ -273,8 +296,9 @@ static inline void HighlightGroupBoxLabel(QGroupBox *gb, QWidget *widget, QStrin { QFormLayout *layout = qobject_cast(gb->layout()); - if (!layout) + if (!layout) { return; + } QLabel *label = qobject_cast(layout->labelForField(widget)); @@ -577,8 +601,9 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) ui->enableAutoUpdates = nullptr; #else // Hide update section if disabled - if (App()->IsUpdaterDisabled()) + if (App()->IsUpdaterDisabled()) { ui->updateSettingsGroupBox->hide(); + } #endif // Remove the Advanced Audio section if monitoring is not supported, as the monitoring device selection is the only item in the group box. @@ -606,8 +631,9 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) {"Basic.Settings.Advanced.General.ProcessPriority.Idle", "Idle"}, }; - for (ProcessPriority pri : processPriorities) + for (ProcessPriority pri : processPriorities) { ui->processPriority->addItem(QTStr(pri.name), pri.val); + } #else #if defined(__APPLE__) && defined(__aarch64__) @@ -689,11 +715,13 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) auto settings = static_cast(data); auto source = static_cast(calldata_ptr(param, "source")); - if (!source) + if (!source) { return; + } - if (!(obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO)) + if (!(obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO)) { return; + } QMetaObject::invokeMethod(settings, "ReloadAudioSources", Qt::QueuedConnection); }; @@ -716,8 +744,9 @@ OBSBasicSettings::OBSBasicSettings(QWidget *parent) hotkeyUnregistered.Connect(obs_get_signal_handler(), "hotkey_unregister", ReloadHotkeysIgnore, this); FillSimpleRecordingValues(); - if (obs_audio_monitoring_available()) + if (obs_audio_monitoring_available()) { FillAudioMonitoringDevices(); + } connect(ui->channelSetup, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SurroundWarning); connect(ui->channelSetup, &QComboBox::currentIndexChanged, this, &OBSBasicSettings::SpeakerLayoutChanged); @@ -925,8 +954,9 @@ OBSBasicSettings::~OBSBasicSettings() void OBSBasicSettings::SaveCombo(QComboBox *widget, const char *section, const char *value) { - if (WidgetChanged(widget)) + if (WidgetChanged(widget)) { config_set_string(main->Config(), section, value, QT_TO_UTF8(widget->currentText())); + } } void OBSBasicSettings::SaveComboData(QComboBox *widget, const char *section, const char *value) @@ -941,8 +971,9 @@ void OBSBasicSettings::SaveCheckBox(QAbstractButton *widget, const char *section { if (WidgetChanged(widget)) { bool checked = widget->isChecked(); - if (invert) + if (invert) { checked = !checked; + } config_set_bool(main->Config(), section, value, checked); } @@ -950,20 +981,23 @@ void OBSBasicSettings::SaveCheckBox(QAbstractButton *widget, const char *section void OBSBasicSettings::SaveEdit(QLineEdit *widget, const char *section, const char *value) { - if (WidgetChanged(widget)) + if (WidgetChanged(widget)) { config_set_string(main->Config(), section, value, QT_TO_UTF8(widget->text())); + } } void OBSBasicSettings::SaveSpinBox(QSpinBox *widget, const char *section, const char *value) { - if (WidgetChanged(widget)) + if (WidgetChanged(widget)) { config_set_int(main->Config(), section, value, widget->value()); + } } void OBSBasicSettings::SaveText(QPlainTextEdit *widget, const char *section, const char *value) { - if (!WidgetChanged(widget)) + if (!WidgetChanged(widget)) { return; + } auto utf8 = widget->toPlainText().toUtf8(); @@ -981,8 +1015,9 @@ std::string DeserializeConfigText(const char *value) void OBSBasicSettings::SaveGroupBox(QGroupBox *widget, const char *section, const char *value) { - if (WidgetChanged(widget)) + if (WidgetChanged(widget)) { config_set_bool(main->Config(), section, value, widget->isChecked()); + } } #define CS_PARTIAL_STR QTStr("Basic.Settings.Advanced.Video.ColorRange.Partial") @@ -1047,8 +1082,9 @@ void OBSBasicSettings::LoadFormats() if (audio || video) { QString itemText(format.name); - if (audio ^ video) + if (audio ^ video) { itemText += QString(" (%1)").arg(audio ? AUDIO_STR : VIDEO_STR); + } ui->advOutFFFormat->addItem(itemText, QVariant::fromValue(format)); } @@ -1087,10 +1123,11 @@ void OBSBasicSettings::LoadFormats() static void AddCodec(QComboBox *combo, const FFmpegCodec &codec) { QString itemText; - if (codec.long_name) + if (codec.long_name) { itemText = QString("%1 - %2").arg(codec.name, codec.long_name); - else + } else { itemText = codec.name; + } combo->addItem(itemText, QVariant::fromValue(codec)); } @@ -1102,8 +1139,9 @@ static void AddDefaultCodec(QComboBox *combo, const FFmpegFormat &format, FFmpeg FFmpegCodec codec = format.GetDefaultEncoder(codecType); int existingIdx = FindEncoder(combo, codec.name, codec.id); - if (existingIdx >= 0) + if (existingIdx >= 0) { combo->removeItem(existingIdx); + } QString itemText; if (codec.long_name) { @@ -1140,10 +1178,12 @@ void OBSBasicSettings::ReloadCodecs(const FFmpegFormat &format) } } - if (format.HasAudio()) + if (format.HasAudio()) { AddDefaultCodec(ui->advOutFFAEncoder, format, FFmpegCodecType::AUDIO); - if (format.HasVideo()) + } + if (format.HasVideo()) { AddDefaultCodec(ui->advOutFFVEncoder, format, FFmpegCodecType::VIDEO); + } ui->advOutFFAEncoder->model()->sort(0); ui->advOutFFVEncoder->model()->sort(0); @@ -1168,8 +1208,9 @@ void OBSBasicSettings::LoadLanguageList() ui->language->addItem(QT_UTF8(locale.second.c_str()), QT_UTF8(locale.first.c_str())); - if (locale.first == currentLang) + if (locale.first == currentLang) { ui->language->setCurrentIndex(idx); + } } ui->language->model()->sort(0); @@ -1181,10 +1222,12 @@ void TranslateBranchInfo(const QString &name, QString &displayName, QString &des QString translatedName = QTStr(QT_TO_UTF8(("Basic.Settings.General.ChannelName." + name))); QString translatedDesc = QTStr(QT_TO_UTF8(("Basic.Settings.General.ChannelDescription." + name))); - if (!translatedName.startsWith("Basic.Settings.")) + if (!translatedName.startsWith("Basic.Settings.")) { displayName = translatedName; - if (!translatedDesc.startsWith("Basic.Settings.")) + } + if (!translatedDesc.startsWith("Basic.Settings.")) { description = translatedDesc; + } } #endif @@ -1195,10 +1238,12 @@ void OBSBasicSettings::LoadBranchesList() QString configBranch = config_get_string(App()->GetAppConfig(), "General", "UpdateBranch"); for (const UpdateBranch &branch : App()->GetBranches()) { - if (branch.name == configBranch) + if (branch.name == configBranch) { configBranchRemoved = false; - if (!branch.is_visible && branch.name != configBranch) + } + if (!branch.is_visible && branch.name != configBranch) { continue; + } QString displayName = branch.display_name; QString description = branch.description; @@ -1225,8 +1270,9 @@ void OBSBasicSettings::LoadBranchesList() } // Fall back to default if not yet set or user-selected branch has been removed - if (configBranch.isEmpty() || configBranchRemoved) + if (configBranch.isEmpty() || configBranchRemoved) { configBranch = "stable"; + } int idx = ui->updateChannelBox->findData(configBranch); ui->updateChannelBox->setCurrentIndex(idx); @@ -1386,8 +1432,9 @@ void OBSBasicSettings::LoadGeneralSettings() prevLangIndex = ui->language->currentIndex(); - if (obs_video_active()) + if (obs_video_active()) { ui->language->setEnabled(false); + } loading = false; } @@ -1485,8 +1532,9 @@ void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, bool ignoreAllS string res = ResString(downscaleCX, downscaleCY); string outRes = ResString(outDownscaleCX, outDownscaleCY); - if (!lockedOutputRes) + if (!lockedOutputRes) { ui->outputResolution->addItem(res.c_str()); + } ui->advOutRescale->addItem(outRes.c_str()); ui->advOutRecRescale->addItem(outRes.c_str()); ui->advOutFFRescale->addItem(outRes.c_str()); @@ -1526,12 +1574,15 @@ void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, bool ignoreAllS } } - if (advRescale.isEmpty()) + if (advRescale.isEmpty()) { advRescale = res.c_str(); - if (advRecRescale.isEmpty()) + } + if (advRecRescale.isEmpty()) { advRecRescale = res.c_str(); - if (advFFRescale.isEmpty()) + } + if (advFFRescale.isEmpty()) { advFFRescale = res.c_str(); + } ui->advOutRescale->lineEdit()->setText(advRescale); ui->advOutRecRescale->lineEdit()->setText(advRecRescale); @@ -1547,8 +1598,9 @@ void OBSBasicSettings::ResetDownscales(uint32_t cx, uint32_t cy, bool ignoreAllS void OBSBasicSettings::LoadDownscaleFilters() { QString downscaleFilter = ui->downscaleFilter->currentData().toString(); - if (downscaleFilter.isEmpty()) + if (downscaleFilter.isEmpty()) { downscaleFilter = config_get_string(main->Config(), "Video", "ScaleType"); + } ui->downscaleFilter->clear(); if (ui->baseResolution->currentText() == ui->outputResolution->currentText()) { @@ -1563,14 +1615,15 @@ void OBSBasicSettings::LoadDownscaleFilters() 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") + if (downscaleFilter == "bilinear") { ui->downscaleFilter->setCurrentIndex(0); - else if (downscaleFilter == "lanczos") + } else if (downscaleFilter == "lanczos") { ui->downscaleFilter->setCurrentIndex(3); - else if (downscaleFilter == "area") + } else if (downscaleFilter == "area") { ui->downscaleFilter->setCurrentIndex(1); - else + } else { ui->downscaleFilter->setCurrentIndex(2); + } } } @@ -1585,8 +1638,9 @@ void OBSBasicSettings::LoadResolutionLists() auto addRes = [this](int cx, int cy) { QString res = ResString(cx, cy).c_str(); - if (ui->baseResolution->findText(res) == -1) + if (ui->baseResolution->findText(res) == -1) { ui->baseResolution->addItem(res); + } }; for (QScreen *screen : QGuiApplication::screens()) { @@ -1625,8 +1679,9 @@ static inline void LoadFPSCommon(OBSBasic *main, Ui::OBSBasicSettings *ui) const char *val = config_get_string(main->Config(), "Video", "FPSCommon"); int idx = ui->fpsCommon->findText(val); - if (idx == -1) + if (idx == -1) { idx = 4; + } ui->fpsCommon->setCurrentIndex(idx); } @@ -1652,8 +1707,9 @@ void OBSBasicSettings::LoadFPSData() LoadFPSFraction(main, ui.get()); uint32_t fpsType = config_get_uint(main->Config(), "Video", "FPSType"); - if (fpsType > 2) + if (fpsType > 2) { fpsType = 0; + } ui->fpsType->setCurrentIndex(fpsType); ui->fpsTypes->setCurrentIndex(fpsType); @@ -1679,8 +1735,9 @@ static inline bool IsSurround(const char *speakers) { static const char *surroundLayouts[] = {"2.1", "4.0", "4.1", "5.1", "7.1", nullptr}; - if (!speakers || !*speakers) + if (!speakers || !*speakers) { return false; + } const char **curLayout = surroundLayouts; for (; *curLayout; ++curLayout) { @@ -1746,8 +1803,9 @@ void OBSBasicSettings::LoadSimpleOutputSettings() const char *speakers = config_get_string(main->Config(), "Audio", "ChannelSetup"); // restrict list of bitrates when multichannel is OFF - if (!IsSurround(speakers)) + if (!IsSurround(speakers)) { RestrictResetBitrates({ui->simpleOutputABitrate}, 320); + } SetComboByName(ui->simpleOutputABitrate, QString::number(audioBitrate)); @@ -1755,18 +1813,21 @@ void OBSBasicSettings::LoadSimpleOutputSettings() ui->simpleOutCustom->setText(custom); idx = ui->simpleOutRecQuality->findData(QString(recQual)); - if (idx == -1) + if (idx == -1) { idx = 0; + } ui->simpleOutRecQuality->setCurrentIndex(idx); idx = ui->simpleOutStrEncoder->findData(QString(streamEnc)); - if (idx == -1) + if (idx == -1) { idx = 0; + } ui->simpleOutStrEncoder->setCurrentIndex(idx); idx = ui->simpleOutStrAEncoder->findData(QString(streamAudioEnc)); - if (idx == -1) + if (idx == -1) { idx = 0; + } ui->simpleOutStrAEncoder->setCurrentIndex(idx); idx = ui->simpleOutRecEncoder->findData(QString(recEnc)); @@ -1827,8 +1888,9 @@ void OBSBasicSettings::LoadAdvOutputStreamingSettings() ui->advOutRescale->setCurrentText(rescaleRes); int idx = ui->advOutRescaleFilter->findData(rescaleFilter); - if (idx != -1) + if (idx != -1) { ui->advOutRescaleFilter->setCurrentIndex(idx); + } QStringList specList = QTStr("FilenameFormatting.completer").split(QRegularExpression("\n")); QCompleter *specCompleter = new QCompleter(specList); @@ -1917,8 +1979,9 @@ void OBSBasicSettings::LoadAdvOutputStreamingEncoderProperties() uint32_t caps = obs_get_encoder_caps(type); if ((caps & ENCODER_HIDE_FLAGS) != 0) { QString encName = QT_UTF8(obs_encoder_get_display_name(type)); - if (caps & OBS_ENCODER_CAP_DEPRECATED) + if (caps & OBS_ENCODER_CAP_DEPRECATED) { encName += " (" + QTStr("Deprecated") + ")"; + } ui->advOutEncoder->insertItem(0, encName, QT_UTF8(type)); SetComboByValue(ui->advOutEncoder, type); @@ -1950,8 +2013,9 @@ void OBSBasicSettings::LoadAdvOutputRecordingSettings() ui->advOutNoSpace->setChecked(noSpace); ui->advOutRecRescale->setCurrentText(rescaleRes); int idx = ui->advOutRecRescaleFilter->findData(rescaleFilter); - if (idx != -1) + if (idx != -1) { ui->advOutRecRescaleFilter->setCurrentIndex(idx); + } ui->advOutMuxCustom->setText(muxCustom); idx = ui->advOutRecFormat->findData(format); @@ -1964,12 +2028,13 @@ void OBSBasicSettings::LoadAdvOutputRecordingSettings() ui->advOutRecTrack5->setChecked(tracks & (1 << 4)); ui->advOutRecTrack6->setChecked(tracks & (1 << 5)); - if (astrcmpi(splitFileType, "Size") == 0) + if (astrcmpi(splitFileType, "Size") == 0) { idx = 1; - else if (astrcmpi(splitFileType, "Manual") == 0) + } else if (astrcmpi(splitFileType, "Manual") == 0) { idx = 2; - else + } else { idx = 0; + } ui->advOutSplitFile->setChecked(splitFile); ui->advOutSplitFileType->setCurrentIndex(idx); ui->advOutSplitFileTime->setValue(splitFileTime); @@ -2021,8 +2086,9 @@ void OBSBasicSettings::LoadAdvOutputRecordingEncoderProperties() uint32_t caps = obs_get_encoder_caps(type); if ((caps & ENCODER_HIDE_FLAGS) != 0) { QString encName = QT_UTF8(obs_encoder_get_display_name(type)); - if (caps & OBS_ENCODER_CAP_DEPRECATED) + if (caps & OBS_ENCODER_CAP_DEPRECATED) { encName += " (" + QTStr("Deprecated") + ")"; + } ui->advOutRecEncoder->insertItem(1, encName, QT_UTF8(type)); SetComboByValue(ui->advOutRecEncoder, type); @@ -2052,8 +2118,9 @@ static void SelectFormat(QComboBox *combo, const char *name, const char *mimeTyp static void SelectEncoder(QComboBox *combo, const char *name, int id) { int idx = FindEncoder(combo, name, id); - if (idx >= 0) + if (idx >= 0) { combo->setCurrentIndex(idx); + } } void OBSBasicSettings::LoadAdvOutputFFmpegSettings() @@ -2175,14 +2242,16 @@ void OBSBasicSettings::LoadOutputSettings() LoadAdvOutputStreamingEncoderProperties(); const char *type = config_get_string(main->Config(), "AdvOut", "AudioEncoder"); - if (!SetComboByValue(ui->advOutAEncoder, type)) + if (!SetComboByValue(ui->advOutAEncoder, type)) { ui->advOutAEncoder->setCurrentIndex(-1); + } LoadAdvOutputRecordingSettings(); LoadAdvOutputRecordingEncoderProperties(); type = config_get_string(main->Config(), "AdvOut", "RecAudioEncoder"); - if (!SetComboByValue(ui->advOutRecAEncoder, type)) + if (!SetComboByValue(ui->advOutRecAEncoder, type)) { ui->advOutRecAEncoder->setCurrentIndex(-1); + } LoadAdvOutputFFmpegSettings(); LoadAdvOutputAudioSettings(); @@ -2248,8 +2317,9 @@ void OBSBasicSettings::LoadListValues(QComboBox *widget, obs_property_t *prop, i if (source) { settings = obs_source_get_settings(source); - if (settings) + if (settings) { deviceId = obs_data_get_string(settings, "device_id"); + } } widget->addItem(QTStr("Basic.Settings.Audio.Disabled"), "disabled"); @@ -2331,8 +2401,9 @@ void OBSBasicSettings::LoadAudioSources() const char *enablePtt = Str("Basic.Settings.Audio.EnablePushToTalk"); const char *pttDelay = Str("Basic.Settings.Audio.PushToTalkDelay"); auto AddSource = [&](obs_source_t *source) { - if (!(obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO)) + if (!(obs_source_get_output_flags(source) & OBS_SOURCE_AUDIO)) { return true; + } auto form = new QFormLayout(); form->setVerticalSpacing(0); @@ -2417,16 +2488,18 @@ void OBSBasicSettings::LoadAudioSources() obs_enum_sources( [](void *data, obs_source_t *source) { auto &AddSource = *static_cast(data); - if (!obs_source_removed(source)) + if (!obs_source_removed(source)) { AddSource(source); + } return true; }, static_cast(&AddSource)); - if (layout->rowCount() == 0) + if (layout->rowCount() == 0) { ui->audioHotkeysGroupBox->hide(); - else + } else { ui->audioHotkeysGroupBox->show(); + } } void OBSBasicSettings::LoadAudioSettings() @@ -2440,36 +2513,40 @@ void OBSBasicSettings::LoadAudioSettings() loading = true; const char *str; - if (sampleRate == 48000) + if (sampleRate == 48000) { str = "48 kHz"; - else + } else { str = "44.1 kHz"; + } int sampleRateIdx = ui->sampleRate->findText(str); - if (sampleRateIdx != -1) + if (sampleRateIdx != -1) { ui->sampleRate->setCurrentIndex(sampleRateIdx); + } - if (strcmp(speakers, "Mono") == 0) + if (strcmp(speakers, "Mono") == 0) { ui->channelSetup->setCurrentIndex(0); - else if (strcmp(speakers, "2.1") == 0) + } else if (strcmp(speakers, "2.1") == 0) { ui->channelSetup->setCurrentIndex(2); - else if (strcmp(speakers, "4.0") == 0) + } else if (strcmp(speakers, "4.0") == 0) { ui->channelSetup->setCurrentIndex(3); - else if (strcmp(speakers, "4.1") == 0) + } else if (strcmp(speakers, "4.1") == 0) { ui->channelSetup->setCurrentIndex(4); - else if (strcmp(speakers, "5.1") == 0) + } else if (strcmp(speakers, "5.1") == 0) { ui->channelSetup->setCurrentIndex(5); - else if (strcmp(speakers, "7.1") == 0) + } else if (strcmp(speakers, "7.1") == 0) { ui->channelSetup->setCurrentIndex(6); - else + } else { ui->channelSetup->setCurrentIndex(1); + } - if (meterDecayRate == VOLUME_METER_DECAY_MEDIUM) + if (meterDecayRate == VOLUME_METER_DECAY_MEDIUM) { ui->meterDecayRate->setCurrentIndex(1); - else if (meterDecayRate == VOLUME_METER_DECAY_SLOW) + } else if (meterDecayRate == VOLUME_METER_DECAY_SLOW) { ui->meterDecayRate->setCurrentIndex(2); - else + } else { ui->meterDecayRate->setCurrentIndex(0); + } ui->peakMeterType->setCurrentIndex(peakMeterTypeIdx); ui->lowLatencyBuffering->setChecked(enableLLAudioBuffering); @@ -2549,8 +2626,9 @@ void OBSBasicSettings::LoadAdvancedSettings() LoadRendererList(); - if (obs_audio_monitoring_available() && !SetComboByValue(ui->monitoringDevice, monDevId)) + if (obs_audio_monitoring_available() && !SetComboByValue(ui->monitoringDevice, monDevId)) { SetInvalidValue(ui->monitoringDevice, monDevName, monDevId); + } ui->confirmOnExit->setChecked(confirmOnExit); @@ -2580,8 +2658,9 @@ void OBSBasicSettings::LoadAdvancedSettings() ui->hdrNominalPeakLevel->setValue(hdrNominalPeakLevel); SetComboByValue(ui->ipFamily, ipFamily); - if (!SetComboByValue(ui->bindToIP, bindIP)) + if (!SetComboByValue(ui->bindToIP, bindIP)) { SetInvalidValue(ui->bindToIP, bindIP, bindIP); + } if (obs_video_active()) { ui->advancedVideoContainer->setEnabled(false); @@ -2602,8 +2681,9 @@ void OBSBasicSettings::LoadAdvancedSettings() bool enableLowLatencyMode = config_get_bool(main->Config(), "Output", "LowLatencyEnable"); int idx = ui->processPriority->findData(processPriority); - if (idx == -1) + if (idx == -1) { idx = ui->processPriority->findData("Normal"); + } ui->processPriority->setCurrentIndex(idx); ui->enableNewSocketLoop->setChecked(enableNewSocketLoop); @@ -2634,10 +2714,11 @@ static inline void LayoutHotkey(OBSBasicSettings *settings, obs_hotkey_id id, ob OBSHotkeyWidget *hw = nullptr; auto combos = keys.find(id); - if (combos == std::end(keys)) + if (combos == std::end(keys)) { hw = new OBSHotkeyWidget(settings, id, obs_hotkey_get_name(key), settings); - else + } else { hw = new OBSHotkeyWidget(settings, id, obs_hotkey_get_name(key), settings, combos->second); + } hw->label = label; hw->setAccessibleName(text); @@ -2667,8 +2748,9 @@ template static inline void AddHotkeys(QFormLayout &layout, Func &&getName, std::vector, QPointer>> &hotkeys) { - if (hotkeys.empty()) + if (hotkeys.empty()) { return; + } layout.setItem(layout.rowCount(), QFormLayout::SpanningRole, new QSpacerItem(0, 10)); @@ -2752,8 +2834,9 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) auto weak_encoder = static_cast(registerer); auto encoder = OBSGetStrongRef(weak_encoder); - if (!encoder) + if (!encoder) { return true; + } encoders.emplace_back(std::move(encoder), label, hw); return false; @@ -2763,8 +2846,9 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) auto weak_output = static_cast(registerer); auto output = OBSGetStrongRef(weak_output); - if (!output) + if (!output) { return true; + } outputs.emplace_back(std::move(output), label, hw); return false; @@ -2774,8 +2858,9 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) auto weak_service = static_cast(registerer); auto service = OBSGetStrongRef(weak_service); - if (!service) + if (!service) { return true; + } services.emplace_back(std::move(service), label, hw); return false; @@ -2785,13 +2870,15 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) auto weak_source = static_cast(registerer); auto source = OBSGetStrongRef(weak_source); - if (!source) + if (!source) { return true; + } - if (obs_scene_from_source(source)) + if (obs_scene_from_source(source)) { scenes.emplace_back(source, label, hw); - else if (obs_source_get_name(source) != NULL) + } else if (obs_source_get_name(source) != NULL) { sources.emplace_back(source, label, hw); + } return false; }; @@ -2814,23 +2901,27 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) break; case OBS_HOTKEY_REGISTERER_ENCODER: - if (HandleEncoder(registerer, label, hw)) + if (HandleEncoder(registerer, label, hw)) { return; + } break; case OBS_HOTKEY_REGISTERER_OUTPUT: - if (HandleOutput(registerer, label, hw)) + if (HandleOutput(registerer, label, hw)) { return; + } break; case OBS_HOTKEY_REGISTERER_SERVICE: - if (HandleService(registerer, label, hw)) + if (HandleService(registerer, label, hw)) { return; + } break; case OBS_HOTKEY_REGISTERER_SOURCE: - if (HandleSource(registerer, label, hw)) + if (HandleSource(registerer, label, hw)) { return; + } break; } @@ -2851,28 +2942,33 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) obs_enum_hotkeys( [](void *data, obs_hotkey_id id, obs_hotkey_t *key) { data_t &d = *static_cast(data); - if (id != get<2>(d)) + if (id != get<2>(d)) { LayoutHotkey(get<3>(d), id, key, get<0>(d), get<1>(d)); + } return true; }, &data); for (auto keyId : pairIds) { auto data1 = pairLabels.find(keyId); - if (data1 == end(pairLabels)) + if (data1 == end(pairLabels)) { continue; + } auto &label1 = data1->second.second; - if (label1->pairPartner) + if (label1->pairPartner) { continue; + } auto data2 = pairLabels.find(data1->second.first); - if (data2 == end(pairLabels)) + if (data2 == end(pairLabels)) { continue; + } auto &label2 = data2->second.second; - if (label2->pairPartner) + if (label2->pairPartner) { continue; + } QString tt = QTStr("Basic.Settings.Hotkeys.Pair"); auto name1 = label1->text(); @@ -2882,8 +2978,9 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) const QString &otherName) { QString string = other->property("fullName").value(); - if (string.isEmpty() || string.isNull()) + if (string.isEmpty() || string.isNull()) { string = otherName; + } label->setToolTip(tt.arg(string)); label->setText(name + " *"); @@ -2911,22 +3008,30 @@ void OBSBasicSettings::LoadHotkeySettings(obs_hotkey_id ignoreKey) void OBSBasicSettings::LoadSettings(bool changedOnly) { - if (!changedOnly || generalChanged) + if (!changedOnly || generalChanged) { LoadGeneralSettings(); - if (!changedOnly || stream1Changed) + } + if (!changedOnly || stream1Changed) { LoadStream1Settings(); - if (!changedOnly || outputsChanged) + } + if (!changedOnly || outputsChanged) { LoadOutputSettings(); - if (!changedOnly || audioChanged) + } + if (!changedOnly || audioChanged) { LoadAudioSettings(); - if (!changedOnly || videoChanged) + } + if (!changedOnly || videoChanged) { LoadVideoSettings(); - if (!changedOnly || a11yChanged) + } + if (!changedOnly || a11yChanged) { LoadA11ySettings(); - if (!changedOnly || appearanceChanged) + } + if (!changedOnly || appearanceChanged) { LoadAppearanceSettings(); - if (!changedOnly || advancedChanged) + } + if (!changedOnly || advancedChanged) { LoadAdvancedSettings(); + } } void OBSBasicSettings::SaveGeneralSettings() @@ -2935,13 +3040,15 @@ void OBSBasicSettings::SaveGeneralSettings() QVariant langData = ui->language->itemData(languageIndex); string language = langData.toString().toStdString(); - if (WidgetChanged(ui->language)) + if (WidgetChanged(ui->language)) { config_set_string(App()->GetUserConfig(), "General", "Language", language.c_str()); + } #if defined(_WIN32) || defined(ENABLE_SPARKLE_UPDATER) - if (WidgetChanged(ui->enableAutoUpdates)) + if (WidgetChanged(ui->enableAutoUpdates)) { config_set_bool(App()->GetAppConfig(), "General", "EnableAutoUpdates", ui->enableAutoUpdates->isChecked()); + } int branchIdx = ui->updateChannelBox->currentIndex(); QString branchName = ui->updateChannelBox->itemData(branchIdx).toString(); @@ -2965,22 +3072,28 @@ void OBSBasicSettings::SaveGeneralSettings() blog(LOG_INFO, "Hide OBS windows from screen capture: %s", hide_window ? "true" : "false"); } #endif - if (WidgetChanged(ui->openStatsOnStartup)) + if (WidgetChanged(ui->openStatsOnStartup)) { config_set_bool(main->Config(), "General", "OpenStatsOnStartup", ui->openStatsOnStartup->isChecked()); - if (WidgetChanged(ui->snappingEnabled)) + } + if (WidgetChanged(ui->snappingEnabled)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled", ui->snappingEnabled->isChecked()); - if (WidgetChanged(ui->screenSnapping)) + } + if (WidgetChanged(ui->screenSnapping)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "ScreenSnapping", ui->screenSnapping->isChecked()); - if (WidgetChanged(ui->centerSnapping)) + } + if (WidgetChanged(ui->centerSnapping)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "CenterSnapping", ui->centerSnapping->isChecked()); - if (WidgetChanged(ui->sourceSnapping)) + } + if (WidgetChanged(ui->sourceSnapping)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "SourceSnapping", ui->sourceSnapping->isChecked()); - if (WidgetChanged(ui->snapDistance)) + } + if (WidgetChanged(ui->snapDistance)) { 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", @@ -3002,12 +3115,14 @@ void OBSBasicSettings::SaveGeneralSettings() main->UpdatePreviewSpacingHelpers(); } - if (WidgetChanged(ui->doubleClickSwitch)) + if (WidgetChanged(ui->doubleClickSwitch)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "TransitionOnDoubleClick", ui->doubleClickSwitch->isChecked()); - if (WidgetChanged(ui->automaticSearch)) + } + if (WidgetChanged(ui->automaticSearch)) { config_set_bool(App()->GetUserConfig(), "General", "AutomaticCollectionSearch", ui->automaticSearch->isChecked()); + } config_set_bool(App()->GetUserConfig(), "BasicWindow", "WarnBeforeStartingStream", ui->warnBeforeStreamStart->isChecked()); @@ -3032,19 +3147,23 @@ void OBSBasicSettings::SaveGeneralSettings() #endif } - if (WidgetChanged(ui->recordWhenStreaming)) + if (WidgetChanged(ui->recordWhenStreaming)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming", ui->recordWhenStreaming->isChecked()); - if (WidgetChanged(ui->keepRecordStreamStops)) + } + if (WidgetChanged(ui->keepRecordStreamStops)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops", ui->keepRecordStreamStops->isChecked()); + } - if (WidgetChanged(ui->replayWhileStreaming)) + if (WidgetChanged(ui->replayWhileStreaming)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming", ui->replayWhileStreaming->isChecked()); - if (WidgetChanged(ui->keepReplayStreamStops)) + } + if (WidgetChanged(ui->keepReplayStreamStops)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops", ui->keepReplayStreamStops->isChecked()); + } if (WidgetChanged(ui->systemTrayEnabled)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled", @@ -3053,21 +3172,25 @@ void OBSBasicSettings::SaveGeneralSettings() main->SystemTray(false); } - if (WidgetChanged(ui->systemTrayWhenStarted)) + if (WidgetChanged(ui->systemTrayWhenStarted)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted", ui->systemTrayWhenStarted->isChecked()); + } - if (WidgetChanged(ui->systemTrayAlways)) + if (WidgetChanged(ui->systemTrayAlways)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayMinimizeToTray", ui->systemTrayAlways->isChecked()); + } - if (WidgetChanged(ui->saveProjectors)) + if (WidgetChanged(ui->saveProjectors)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "SaveProjectors", ui->saveProjectors->isChecked()); + } - if (WidgetChanged(ui->closeProjectors)) + if (WidgetChanged(ui->closeProjectors)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "CloseExistingProjectors", ui->closeProjectors->isChecked()); + } if (WidgetChanged(ui->studioPortraitLayout)) { config_set_bool(App()->GetUserConfig(), "BasicWindow", "StudioPortraitLayout", @@ -3108,8 +3231,9 @@ void OBSBasicSettings::SaveGeneralSettings() multiviewChanged = true; } - if (multiviewChanged) + if (multiviewChanged) { OBSProjector::UpdateMultiviewProjectors(); + } } void OBSBasicSettings::SaveVideoSettings() @@ -3131,8 +3255,9 @@ void OBSBasicSettings::SaveVideoSettings() config_set_uint(main->Config(), "Video", "OutputCY", cy); } - if (WidgetChanged(ui->fpsType)) + if (WidgetChanged(ui->fpsType)) { config_set_uint(main->Config(), "Video", "FPSType", fpsType); + } SaveCombo(ui->fpsCommon, "Video", "FPSCommon"); SaveSpinBox(ui->fpsInteger, "Video", "FPSInt"); @@ -3155,8 +3280,9 @@ void OBSBasicSettings::SaveAdvancedSettings() #ifdef _WIN32 std::string priority = QT_TO_UTF8(ui->processPriority->currentData().toString()); config_set_string(App()->GetAppConfig(), "General", "ProcessPriority", priority.c_str()); - if (main->Active()) + if (main->Active()) { SetProcessPriority(priority.c_str()); + } SaveCheckBox(ui->enableNewSocketLoop, "Output", "NewSocketLoopEnable"); SaveCheckBox(ui->enableLowLatencyMode, "Output", "LowLatencyEnable"); @@ -3177,8 +3303,9 @@ void OBSBasicSettings::SaveAdvancedSettings() config_set_bool(App()->GetAppConfig(), "Video", "DisableOSXVSync", disable); EnableOSXVSync(!disable); } - if (WidgetChanged(ui->resetOSXVSync)) + if (WidgetChanged(ui->resetOSXVSync)) { config_set_bool(App()->GetAppConfig(), "Video", "ResetOSXVSyncOnExit", ui->resetOSXVSync->isChecked()); + } #endif SaveComboData(ui->colorFormat, "Video", "ColorFormat"); @@ -3199,8 +3326,9 @@ void OBSBasicSettings::SaveAdvancedSettings() } #endif - if (WidgetChanged(ui->confirmOnExit)) + if (WidgetChanged(ui->confirmOnExit)) { config_set_bool(App()->GetUserConfig(), "General", "ConfirmOnExit", ui->confirmOnExit->isChecked()); + } SaveEdit(ui->filenameFormatting, "Output", "FilenameFormatting"); SaveEdit(ui->simpleRBPrefix, "SimpleOutput", "RecRBPrefix"); @@ -3232,34 +3360,38 @@ void OBSBasicSettings::SaveAdvancedSettings() static inline const char *OutputModeFromIdx(int idx) { - if (idx == 1) + if (idx == 1) { return "Advanced"; - else + } else { return "Simple"; + } } static inline const char *RecTypeFromIdx(int idx) { - if (idx == 1) + if (idx == 1) { return "FFmpeg"; - else + } else { return "Standard"; + } } static inline const char *SplitFileTypeFromIdx(int idx) { - if (idx == 1) + if (idx == 1) { return "Size"; - else if (idx == 2) + } else if (idx == 2) { return "Manual"; - else + } else { return "Time"; + } } static void WriteJsonData(OBSPropertiesView *view, const char *path) { - if (!view || !WidgetChanged(view)) + if (!view || !WidgetChanged(view)) { return; + } const OBSBasic *basic = OBSBasic::Get(); const OBSProfile ¤tProfile = basic->GetCurrentProfile(); @@ -3278,18 +3410,19 @@ static void SaveTrackIndex(config_t *config, const char *section, const char *na QAbstractButton *check2, QAbstractButton *check3, QAbstractButton *check4, QAbstractButton *check5, QAbstractButton *check6) { - if (check1->isChecked()) + if (check1->isChecked()) { config_set_int(config, section, name, 1); - else if (check2->isChecked()) + } else if (check2->isChecked()) { config_set_int(config, section, name, 2); - else if (check3->isChecked()) + } else if (check3->isChecked()) { config_set_int(config, section, name, 3); - else if (check4->isChecked()) + } else if (check4->isChecked()) { config_set_int(config, section, name, 4); - else if (check5->isChecked()) + } else if (check5->isChecked()) { config_set_int(config, section, name, 5); - else if (check6->isChecked()) + } else if (check6->isChecked()) { config_set_int(config, section, name, 6); + } } void OBSBasicSettings::SaveFormat(QComboBox *combo) @@ -3304,8 +3437,9 @@ void OBSBasicSettings::SaveFormat(QComboBox *combo) string extStr = ext ? ext : ""; char *comma = strchr(&extStr[0], ','); - if (comma) + if (comma) { *comma = 0; + } config_set_string(main->Config(), "AdvOut", "FFExtension", extStr.c_str()); } else { @@ -3320,14 +3454,16 @@ void OBSBasicSettings::SaveEncoder(QComboBox *combo, const char *section, const { QVariant v = combo->currentData(); FFmpegCodec cd{}; - if (!v.isNull()) + if (!v.isNull()) { cd = v.value(); + } config_set_int(main->Config(), section, QT_TO_UTF8(QString("%1Id").arg(value)), cd.id); - if (cd.id != 0) + if (cd.id != 0) { config_set_string(main->Config(), section, value, cd.name); - else + } else { config_set_string(main->Config(), section, value, nullptr); + } } void OBSBasicSettings::SaveOutputSettings() @@ -3337,35 +3473,38 @@ void OBSBasicSettings::SaveOutputSettings() QString encoder = ui->simpleOutStrEncoder->currentData().toString(); const char *presetType; - if (encoder == SIMPLE_ENCODER_QSV) + if (encoder == SIMPLE_ENCODER_QSV) { presetType = "QSVPreset"; - else if (encoder == SIMPLE_ENCODER_QSV_AV1) + } else if (encoder == SIMPLE_ENCODER_QSV_AV1) { presetType = "QSVPreset"; - else if (encoder == SIMPLE_ENCODER_NVENC) + } else if (encoder == SIMPLE_ENCODER_NVENC) { presetType = "NVENCPreset2"; - else if (encoder == SIMPLE_ENCODER_NVENC_AV1) + } else if (encoder == SIMPLE_ENCODER_NVENC_AV1) { presetType = "NVENCPreset2"; + } #ifdef ENABLE_HEVC - else if (encoder == SIMPLE_ENCODER_AMD_HEVC) + else if (encoder == SIMPLE_ENCODER_AMD_HEVC) { presetType = "AMDPreset"; - else if (encoder == SIMPLE_ENCODER_NVENC_HEVC) + } else if (encoder == SIMPLE_ENCODER_NVENC_HEVC) { presetType = "NVENCPreset2"; + } #endif - else if (encoder == SIMPLE_ENCODER_AMD) + else if (encoder == SIMPLE_ENCODER_AMD) { presetType = "AMDPreset"; - else if (encoder == SIMPLE_ENCODER_AMD_AV1) + } else if (encoder == SIMPLE_ENCODER_AMD_AV1) { presetType = "AMDAV1Preset"; - else if (encoder == SIMPLE_ENCODER_APPLE_H264 + } else if (encoder == SIMPLE_ENCODER_APPLE_H264 #ifdef ENABLE_HEVC - || encoder == SIMPLE_ENCODER_APPLE_HEVC + || encoder == SIMPLE_ENCODER_APPLE_HEVC #endif ) /* The Apple encoders don't have presets like the other encoders do. This only exists to make sure that the x264 preset doesn't get overwritten with empty data. */ presetType = "ApplePreset"; - else + else { presetType = "Preset"; + } SaveSpinBox(ui->simpleOutputVBitrate, "SimpleOutput", "VBitrate"); SaveComboData(ui->simpleOutStrEncoder, "SimpleOutput", "StreamEncoder"); @@ -3505,14 +3644,17 @@ void OBSBasicSettings::SaveAudioSettings() } int sampleRate = 44100; - if (sampleRateStr == "48 kHz") + if (sampleRateStr == "48 kHz") { sampleRate = 48000; + } - if (WidgetChanged(ui->sampleRate)) + if (WidgetChanged(ui->sampleRate)) { config_set_uint(main->Config(), "Audio", "SampleRate", sampleRate); + } - if (WidgetChanged(ui->channelSetup)) + if (WidgetChanged(ui->channelSetup)) { config_set_string(main->Config(), "Audio", "ChannelSetup", channelSetup); + } if (WidgetChanged(ui->meterDecayRate)) { double meterDecayRate; @@ -3549,8 +3691,9 @@ void OBSBasicSettings::SaveAudioSettings() for (auto &audioSource : audioSources) { auto source = OBSGetStrongRef(get<0>(audioSource)); - if (!source) + if (!source) { continue; + } auto &ptmCB = get<1>(audioSource); auto &ptmSB = get<2>(audioSource); @@ -3587,13 +3730,15 @@ void OBSBasicSettings::SaveHotkeySettings() std::vector combinations; for (auto &hotkey : hotkeys) { auto &hw = *hotkey.second; - if (!hw.Changed()) + if (!hw.Changed()) { continue; + } hw.Save(combinations); - if (!hotkey.first) + if (!hotkey.first) { continue; + } OBSDataArrayAutoRelease array = obs_hotkey_save(hw.id); OBSDataAutoRelease data = obs_data_create(); @@ -3602,8 +3747,9 @@ void OBSBasicSettings::SaveHotkeySettings() config_set_string(config, "Hotkeys", hw.name.c_str(), json); } - if (!main->outputHandler || !main->outputHandler->replayBuffer) + if (!main->outputHandler || !main->outputHandler->replayBuffer) { return; + } const char *id = obs_obj_get_id(main->outputHandler->replayBuffer); if (strcmp(id, "replay_buffer") == 0) { @@ -3616,33 +3762,44 @@ void OBSBasicSettings::SaveHotkeySettings() static void AddChangedVal(std::string &changed, const char *str) { - if (changed.size()) + if (changed.size()) { changed += ", "; + } changed += str; } void OBSBasicSettings::SaveSettings() { - if (generalChanged) + if (generalChanged) { SaveGeneralSettings(); - if (stream1Changed) + } + if (stream1Changed) { SaveStream1Settings(); - if (outputsChanged) + } + if (outputsChanged) { SaveOutputSettings(); - if (audioChanged) + } + if (audioChanged) { SaveAudioSettings(); - if (videoChanged) + } + if (videoChanged) { SaveVideoSettings(); - if (hotkeysChanged) + } + if (hotkeysChanged) { SaveHotkeySettings(); - if (a11yChanged) + } + if (a11yChanged) { SaveA11ySettings(); - if (advancedChanged) + } + if (advancedChanged) { SaveAdvancedSettings(); - if (appearanceChanged) + } + if (appearanceChanged) { SaveAppearanceSettings(); - if (videoChanged || advancedChanged) + } + if (videoChanged || advancedChanged) { main->ResetVideo(); + } config_save_safe(main->Config(), "tmp", nullptr); config_save_safe(App()->GetUserConfig(), "tmp", nullptr); @@ -3650,24 +3807,33 @@ void OBSBasicSettings::SaveSettings() if (Changed()) { std::string changed; - if (generalChanged) + if (generalChanged) { AddChangedVal(changed, "general"); - if (stream1Changed) + } + if (stream1Changed) { AddChangedVal(changed, "stream 1"); - if (outputsChanged) + } + if (outputsChanged) { AddChangedVal(changed, "outputs"); - if (audioChanged) + } + if (audioChanged) { AddChangedVal(changed, "audio"); - if (videoChanged) + } + if (videoChanged) { AddChangedVal(changed, "video"); - if (hotkeysChanged) + } + if (hotkeysChanged) { AddChangedVal(changed, "hotkeys"); - if (a11yChanged) + } + if (a11yChanged) { AddChangedVal(changed, "a11y"); - if (appearanceChanged) + } + if (appearanceChanged) { AddChangedVal(changed, "appearance"); - if (advancedChanged) + } + if (advancedChanged) { AddChangedVal(changed, "advanced"); + } blog(LOG_INFO, "Settings changed (%s)", changed.c_str()); blog(LOG_INFO, MINOR_SEPARATOR); @@ -3678,10 +3844,11 @@ void OBSBasicSettings::SaveSettings() (ui->channelSetup->currentIndex() != channelIndex || ui->sampleRate->currentIndex() != sampleRateIndex); bool browserHWAccelChanged = (ui->browserHWAccel && ui->browserHWAccel->isChecked() != prevBrowserAccel); - if (langChanged || audioRestart || browserHWAccelChanged) + if (langChanged || audioRestart || browserHWAccelChanged) { restart = true; - else + } else { restart = false; + } } bool OBSBasicSettings::QueryChanges() @@ -3694,13 +3861,15 @@ bool OBSBasicSettings::QueryChanges() if (button == QMessageBox::Cancel) { return false; } else if (button == QMessageBox::Yes) { - if (!QueryAllowedToClose()) + if (!QueryAllowedToClose()) { return false; + } SaveSettings(); } else { - if (savedTheme != App()->GetTheme()) + if (savedTheme != App()->GetTheme()) { App()->SetTheme(savedTheme->id); + } LoadSettings(true); restart = false; @@ -3719,26 +3888,32 @@ bool OBSBasicSettings::QueryAllowedToClose() bool invalidTracks = false; if (simple) { if (ui->simpleOutRecEncoder->currentIndex() == -1 || ui->simpleOutStrEncoder->currentIndex() == -1 || - ui->simpleOutRecAEncoder->currentIndex() == -1 || ui->simpleOutStrAEncoder->currentIndex() == -1) + ui->simpleOutRecAEncoder->currentIndex() == -1 || ui->simpleOutStrAEncoder->currentIndex() == -1) { invalidEncoder = true; + } - if (ui->simpleOutRecFormat->currentIndex() == -1) + 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") + 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) + ui->advOutRecAEncoder->currentIndex() == -1 || ui->advOutAEncoder->currentIndex() == -1) { invalidEncoder = true; + } QString format = ui->advOutRecFormat->currentData().toString(); - if (AdvOutGetSelectedAudioTracks() == 0 && format != "flv") + if (AdvOutGetSelectedAudioTracks() == 0 && format != "flv") { invalidTracks = true; - if (AdvOutGetStreamingSelectedAudioTracks() == 0) + } + if (AdvOutGetStreamingSelectedAudioTracks() == 0) { invalidTracks = true; + } } if (invalidEncoder) { @@ -3760,8 +3935,9 @@ bool OBSBasicSettings::QueryAllowedToClose() void OBSBasicSettings::closeEvent(QCloseEvent *event) { - if (!AskIfCanCloseSettings()) + if (!AskIfCanCloseSettings()) { event->ignore(); + } } void OBSBasicSettings::showEvent(QShowEvent *event) @@ -3772,22 +3948,25 @@ void OBSBasicSettings::showEvent(QShowEvent *event) * 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); - if (size().height() >= maxHeight) + if (size().height() >= maxHeight) { resize(size().width(), maxHeight); + } } void OBSBasicSettings::reject() { - if (AskIfCanCloseSettings()) + if (AskIfCanCloseSettings()) { close(); + } } void OBSBasicSettings::on_listWidget_itemSelectionChanged() { int row = ui->listWidget->currentRow(); - if (loading || row == pageIndex) + if (loading || row == pageIndex) { return; + } if (!hotkeysLoaded && row == Pages::HOTKEYS) { setCursor(Qt::BusyCursor); @@ -3831,8 +4010,9 @@ void OBSBasicSettings::on_buttonBox_clicked(QAbstractButton *button) QDialogButtonBox::ButtonRole val = ui->buttonBox->buttonRole(button); if (val == QDialogButtonBox::ApplyRole || val == QDialogButtonBox::AcceptRole) { - if (!QueryAllowedToClose()) + if (!QueryAllowedToClose()) { return; + } SaveSettings(); @@ -3842,8 +4022,9 @@ void OBSBasicSettings::on_buttonBox_clicked(QAbstractButton *button) if (val == QDialogButtonBox::AcceptRole || val == QDialogButtonBox::RejectRole) { if (val == QDialogButtonBox::RejectRole) { - if (savedTheme != App()->GetTheme()) + if (savedTheme != App()->GetTheme()) { App()->SetTheme(savedTheme->id); + } } ClearChanged(); close(); @@ -3854,8 +4035,9 @@ void OBSBasicSettings::on_simpleOutputBrowse_clicked() { QString dir = SelectDirectory(this, QTStr("Basic.Settings.Output.SelectDirectory"), ui->simpleOutputPath->text()); - if (dir.isEmpty()) + if (dir.isEmpty()) { return; + } ui->simpleOutputPath->setText(dir); } @@ -3863,8 +4045,9 @@ void OBSBasicSettings::on_simpleOutputBrowse_clicked() void OBSBasicSettings::on_advOutRecPathBrowse_clicked() { QString dir = SelectDirectory(this, QTStr("Basic.Settings.Output.SelectDirectory"), ui->advOutRecPath->text()); - if (dir.isEmpty()) + if (dir.isEmpty()) { return; + } ui->advOutRecPath->setText(dir); } @@ -3872,8 +4055,9 @@ void OBSBasicSettings::on_advOutRecPathBrowse_clicked() void OBSBasicSettings::on_advOutFFPathBrowse_clicked() { QString dir = SelectDirectory(this, QTStr("Basic.Settings.Output.SelectDirectory"), ui->advOutRecPath->text()); - if (dir.isEmpty()) + if (dir.isEmpty()) { return; + } ui->advOutFFRecPath->setText(dir); } @@ -4039,8 +4223,9 @@ bool OBSBasicSettings::AskIfCanCloseSettings() { bool canCloseSettings = false; - if (!Changed() || QueryChanges()) + if (!Changed() || QueryChanges()) { canCloseSettings = true; + } if (forceAuthReload) { main->auth->Save(); @@ -4068,8 +4253,9 @@ void OBSBasicSettings::on_filenameFormatting_textEdited(const QString &text) // TODO: Add filtering for other platforms #endif - if (text != safeStr) + if (text != safeStr) { ui->filenameFormatting->setText(safeStr); + } } void OBSBasicSettings::on_outputResolution_editTextChanged(const QString &text) @@ -4214,11 +4400,13 @@ void OBSBasicSettings::HideOBSWindowWarning(Qt::CheckState state) void OBSBasicSettings::HideOBSWindowWarning(int state) #endif { - if (loading || state == Qt::Unchecked) + 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")); @@ -4240,8 +4428,9 @@ void RestrictResetBitrates(initializer_list boxes, int maxbitrate) int count = box->count(); int max_idx = box->findText(QT_UTF8(std::to_string(max_bitrate).c_str())); - for (int i = (count - 1); i > max_idx; i--) + for (int i = (count - 1); i > max_idx; i--) { box->removeItem(i); + } if (idx > max_idx) { int default_bitrate = FindClosestAvailableAudioBitrate(box, maxbitrate / 2); @@ -4289,23 +4478,26 @@ void OBSBasicSettings::VideoChanged() void OBSBasicSettings::HotkeysChanged() { using namespace std; - if (loading) + if (loading) { return; + } hotkeysChanged = any_of(begin(hotkeys), end(hotkeys), [](const pair> &hotkey) { const auto &hw = *hotkey.second; return hw.Changed(); }); - if (hotkeysChanged) + if (hotkeysChanged) { EnableApplyButton(true); + } } void OBSBasicSettings::SearchHotkeys(const QString &text, obs_key_combination_t filterCombo) { - if (ui->hotkeyFormLayout->rowCount() == 0) + if (ui->hotkeyFormLayout->rowCount() == 0) { return; + } std::vector combos; bool showHotkey; @@ -4313,8 +4505,9 @@ void OBSBasicSettings::SearchHotkeys(const QString &text, obs_key_combination_t QLayoutItem *hotkeysItem = ui->hotkeyFormLayout->itemAt(0); QWidget *hotkeys = hotkeysItem->widget(); - if (!hotkeys) + if (!hotkeys) { return; + } QFormLayout *hotkeysLayout = qobject_cast(hotkeys->layout()); hotkeysLayout->setEnabled(false); @@ -4323,12 +4516,14 @@ void OBSBasicSettings::SearchHotkeys(const QString &text, obs_key_combination_t for (int i = 0; i < hotkeysLayout->rowCount(); i++) { auto label = hotkeysLayout->itemAt(i, QFormLayout::LabelRole); - if (!label) + if (!label) { continue; + } OBSHotkeyLabel *item = qobject_cast(label->widget()); - if (!item) + if (!item) { continue; + } QString fullname = item->property("fullName").value(); @@ -4349,8 +4544,9 @@ void OBSBasicSettings::SearchHotkeys(const QString &text, obs_key_combination_t label->widget()->setVisible(showHotkey); auto field = hotkeysLayout->itemAt(i, QFormLayout::FieldRole); - if (field) + if (field) { field->widget()->setVisible(showHotkey); + } } hotkeysLayout->setEnabled(true); } @@ -4397,23 +4593,27 @@ bool OBSBasicSettings::ScanDuplicateHotkeys(QFormLayout *layout) for (int i = 0; i < layout->rowCount(); i++) { auto label = layout->itemAt(i, QFormLayout::LabelRole); - if (!label) + if (!label) { continue; + } OBSHotkeyLabel *item = qobject_cast(label->widget()); - if (!item) + if (!item) { continue; + } items.push_back(item); for (auto &edit : item->widget->edits) { edit->hasDuplicate = false; - if (obs_key_combination_is_empty(edit->key)) + if (obs_key_combination_is_empty(edit->key)) { continue; + } for (assignment &assign : assignments[edit->key]) { - if (item->pairPartner == assign.label) + if (item->pairPartner == assign.label) { continue; + } assign.edit->hasDuplicate = true; edit->hasDuplicate = true; @@ -4424,17 +4624,20 @@ bool OBSBasicSettings::ScanDuplicateHotkeys(QFormLayout *layout) } } - for (auto *item : items) - for (auto &edit : item->widget->edits) + for (auto *item : items) { + for (auto &edit : item->widget->edits) { edit->UpdateDuplicationState(); + } + } return hasDupes; } void OBSBasicSettings::ReloadHotkeys(obs_hotkey_id ignoreKey) { - if (!hotkeysLoaded) + if (!hotkeysLoaded) { return; + } LoadHotkeySettings(ignoreKey); } @@ -4492,8 +4695,9 @@ static void DisableIncompatibleCodecs(QComboBox *cbox, const QString &format, co : obs_encoder_get_display_name(encoderId.c_str()); /* Something has gone horribly wrong and there's no encoder */ - if (encoderId.empty()) + if (encoderId.empty()) { continue; + } if (obs_get_encoder_caps(encoderId.c_str()) & OBS_ENCODER_CAP_DEPRECATED) { encDisplayName += " (" + QTStr("Deprecated") + ")"; @@ -4514,8 +4718,9 @@ static void DisableIncompatibleCodecs(QComboBox *cbox, const QString &format, co if (is_compatible) { item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); } else { - if (recEncoder == encName) + if (recEncoder == encName) { currentCompatible = false; + } item->setFlags(Qt::NoItemFlags); encDisplayName += " "; @@ -4526,8 +4731,9 @@ static void DisableIncompatibleCodecs(QComboBox *cbox, const QString &format, co } // Set to invalid entry if encoder was incompatible - if (!currentCompatible) + if (!currentCompatible) { cbox->setCurrentIndex(-1); + } } void OBSBasicSettings::AdvOutRecCheckCodecs() @@ -4538,10 +4744,11 @@ void OBSBasicSettings::AdvOutRecCheckCodecs() /* Set tooltip if available */ QString tooltip = QTStr(QT_TO_UTF8(("Basic.Settings.Output.Format.TT." + recFormat))); - if (!tooltip.startsWith("Basic.Settings.Output")) + if (!tooltip.startsWith("Basic.Settings.Output")) { ui->advOutRecFormat->setToolTip(tooltip); - else + } else { ui->advOutRecFormat->setToolTip(nullptr); + } QString streamEncoder = ui->advOutEncoder->currentData().toString(); QString streamAudioEncoder = ui->advOutAEncoder->currentData().toString(); @@ -4554,8 +4761,9 @@ void OBSBasicSettings::AdvOutRecCheckCodecs() /* Only invoke AdvOutRecCheckWarnings() if it wouldn't already have * been triggered by one of the encoder selections being reset. */ if (ui->advOutRecEncoder->currentIndex() == oldVEncoderIdx && - ui->advOutRecAEncoder->currentIndex() == oldAEncoderIdx) + ui->advOutRecAEncoder->currentIndex() == oldAEncoderIdx) { AdvOutRecCheckWarnings(); + } } #if defined(__APPLE__) && QT_VERSION < QT_VERSION_CHECK(6, 5, 1) @@ -4563,14 +4771,16 @@ void OBSBasicSettings::AdvOutRecCheckCodecs() static void ResetInvalidSelection(QComboBox *cbox) { int idx = cbox->currentIndex(); - if (idx < 0) + if (idx < 0) { return; + } QStandardItemModel *model = dynamic_cast(cbox->model()); QStandardItem *item = model->item(idx); - if (item->isEnabled()) + if (item->isEnabled()) { return; + } // Reset to "invalid" state if item was disabled cbox->blockSignals(true); @@ -4592,8 +4802,9 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() bool useStreamEncoder = ui->advOutRecEncoder->currentIndex() == 0; if (useStreamEncoder) { - if (!warningMsg.isEmpty()) + if (!warningMsg.isEmpty()) { warningMsg += "\n\n"; + } warningMsg += QTStr("OutputWarnings.CannotPause"); } @@ -4604,13 +4815,15 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() } else { ui->advRecTrackWidget->setCurrentWidget(ui->recTracks); - if (tracks == 0) + if (tracks == 0) { errorMsg = QTStr("OutputWarnings.NoTracksSelected"); + } } if (recFormat == "mp4" || recFormat == "mov") { - if (!warningMsg.isEmpty()) + if (!warningMsg.isEmpty()) { warningMsg += "\n\n"; + } warningMsg += QTStr("OutputWarnings.MP4Recording"); ui->autoRemux->setText(QTStr("Basic.Settings.Advanced.AutoRemux").arg("mp4") + " " + @@ -4627,8 +4840,9 @@ void OBSBasicSettings::AdvOutRecCheckWarnings() // Show warning if codec selection was reset to an invalid state if (ui->advOutRecEncoder->currentIndex() == -1 || ui->advOutRecAEncoder->currentIndex() == -1) { - if (!warningMsg.isEmpty()) + if (!warningMsg.isEmpty()) { warningMsg += "\n\n"; + } warningMsg += QTStr("OutputWarnings.CodecIncompatible"); } @@ -4665,8 +4879,9 @@ void OBSBasicSettings::UpdateSimpleOutStreamDelayEstimate() void OBSBasicSettings::UpdateAdvOutStreamDelayEstimate() { - if (!streamEncoderProps) + if (!streamEncoderProps) { return; + } OBSData settings = streamEncoderProps->GetSettings(); int trackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex"); @@ -4704,10 +4919,11 @@ void OBSBasicSettings::UpdateAdvOutStreamDelayEstimate() void OBSBasicSettings::UpdateStreamDelayEstimate() { - if (ui->outputMode->currentIndex() == 0) + if (ui->outputMode->currentIndex() == 0) { UpdateSimpleOutStreamDelayEstimate(); - else + } else { UpdateAdvOutStreamDelayEstimate(); + } UpdateAutomaticReplayBufferCheckboxes(); } @@ -4717,9 +4933,11 @@ bool EncoderAvailable(const char *encoder) const char *val; int i = 0; - while (obs_enum_encoder_types(i++, &val)) - if (strcmp(val, encoder) == 0) + while (obs_enum_encoder_types(i++, &val)) { + if (strcmp(val, encoder) == 0) { return true; + } + } return false; } @@ -4737,25 +4955,33 @@ void OBSBasicSettings::FillSimpleRecordingValues() 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")) + if (EncoderAvailable("obs_qsv11")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.QSV.H264"), QString(SIMPLE_ENCODER_QSV)); - if (EncoderAvailable("obs_qsv11_av1")) + } + if (EncoderAvailable("obs_qsv11_av1")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.QSV.AV1"), QString(SIMPLE_ENCODER_QSV_AV1)); - if (EncoderAvailable("ffmpeg_nvenc")) + } + if (EncoderAvailable("ffmpeg_nvenc")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.NVENC.H264"), QString(SIMPLE_ENCODER_NVENC)); - if (EncoderAvailable("obs_nvenc_av1_tex")) + } + if (EncoderAvailable("obs_nvenc_av1_tex")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.NVENC.AV1"), QString(SIMPLE_ENCODER_NVENC_AV1)); + } #ifdef ENABLE_HEVC - if (EncoderAvailable("h265_texture_amf")) + if (EncoderAvailable("h265_texture_amf")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.AMD.HEVC"), QString(SIMPLE_ENCODER_AMD_HEVC)); - if (EncoderAvailable("ffmpeg_hevc_nvenc")) + } + if (EncoderAvailable("ffmpeg_hevc_nvenc")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.NVENC.HEVC"), QString(SIMPLE_ENCODER_NVENC_HEVC)); + } #endif - if (EncoderAvailable("h264_texture_amf")) + if (EncoderAvailable("h264_texture_amf")) { ui->simpleOutRecEncoder->addItem(ENCODER_STR("Hardware.AMD.H264"), QString(SIMPLE_ENCODER_AMD)); - if (EncoderAvailable("av1_texture_amf")) + } + if (EncoderAvailable("av1_texture_amf")) { 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 @@ -4773,10 +4999,12 @@ void OBSBasicSettings::FillSimpleRecordingValues() QString(SIMPLE_ENCODER_APPLE_HEVC)); #endif - if (EncoderAvailable("CoreAudio_AAC") || EncoderAvailable("libfdk_aac") || EncoderAvailable("ffmpeg_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")) + } + if (EncoderAvailable("ffmpeg_opus")) { ui->simpleOutRecAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.Opus"), "opus"); + } #undef ADD_QUALITY #undef ENCODER_STR @@ -4910,8 +5138,9 @@ void OBSBasicSettings::SimpleStreamingEncoderChanged() } int idx = ui->simpleOutPreset->findData(QVariant(preset)); - if (idx == -1) + if (idx == -1) { idx = ui->simpleOutPreset->findData(QVariant(defaultPreset)); + } ui->simpleOutPreset->setCurrentIndex(idx); } @@ -4955,18 +5184,24 @@ void OBSBasicSettings::SimpleReplayBufferChanged() abitrate = ui->simpleOutputABitrate->currentText().toInt(); } else { int delta = ui->simpleOutputABitrate->currentText().toInt(); - if (ui->simpleOutRecTrack1->isChecked()) + if (ui->simpleOutRecTrack1->isChecked()) { abitrate += delta; - if (ui->simpleOutRecTrack2->isChecked()) + } + if (ui->simpleOutRecTrack2->isChecked()) { abitrate += delta; - if (ui->simpleOutRecTrack3->isChecked()) + } + if (ui->simpleOutRecTrack3->isChecked()) { abitrate += delta; - if (ui->simpleOutRecTrack4->isChecked()) + } + if (ui->simpleOutRecTrack4->isChecked()) { abitrate += delta; - if (ui->simpleOutRecTrack5->isChecked()) + } + if (ui->simpleOutRecTrack5->isChecked()) { abitrate += delta; - if (ui->simpleOutRecTrack6->isChecked()) + } + if (ui->simpleOutRecTrack6->isChecked()) { abitrate += delta; + } } int vbitrate = ui->simpleOutputVBitrate->value(); @@ -4977,8 +5212,9 @@ void OBSBasicSettings::SimpleReplayBufferChanged() int64_t memMaxMB = memTotal ? memTotal * 3 / 4 / 1024 / 1024 : 8192; int64_t memMB = int64_t(seconds) * int64_t(vbitrate + abitrate) * 1000 / 8 / 1024 / 1024; - if (memMB < 1) + if (memMB < 1) { memMB = 1; + } ui->simpleRBEstimate->setObjectName(""); if (streamQuality) { @@ -5013,12 +5249,14 @@ void OBSBasicSettings::AdvReplayBufferChanged() } else if (!useStream && recordEncoderProps) { settings = recordEncoderProps->GetSettings(); } else { - if (useStream) + if (useStream) { encoder = GetComboData(ui->advOutEncoder); + } settings = obs_encoder_defaults(encoder.toUtf8().constData()); - if (!settings) + if (!settings) { return; + } const OBSProfile ¤tProfile = main->GetCurrentProfile(); @@ -5035,25 +5273,32 @@ void OBSBasicSettings::AdvReplayBufferChanged() int vbitrate = (int)obs_data_get_int(settings, "bitrate"); const char *rateControl = obs_data_get_string(settings, "rate_control"); - if (!rateControl) + if (!rateControl) { rateControl = ""; + } bool lossless = strcmp(rateControl, "lossless") == 0 || ui->advOutRecType->currentIndex() == 1; bool replayBufferEnabled = ui->advReplayBuf->isChecked(); int abitrate = 0; - if (ui->advOutRecTrack1->isChecked()) + if (ui->advOutRecTrack1->isChecked()) { abitrate += ui->advOutTrack1Bitrate->currentText().toInt(); - if (ui->advOutRecTrack2->isChecked()) + } + if (ui->advOutRecTrack2->isChecked()) { abitrate += ui->advOutTrack2Bitrate->currentText().toInt(); - if (ui->advOutRecTrack3->isChecked()) + } + if (ui->advOutRecTrack3->isChecked()) { abitrate += ui->advOutTrack3Bitrate->currentText().toInt(); - if (ui->advOutRecTrack4->isChecked()) + } + if (ui->advOutRecTrack4->isChecked()) { abitrate += ui->advOutTrack4Bitrate->currentText().toInt(); - if (ui->advOutRecTrack5->isChecked()) + } + if (ui->advOutRecTrack5->isChecked()) { abitrate += ui->advOutTrack5Bitrate->currentText().toInt(); - if (ui->advOutRecTrack6->isChecked()) + } + if (ui->advOutRecTrack6->isChecked()) { abitrate += ui->advOutTrack6Bitrate->currentText().toInt(); + } int seconds = ui->advRBSecMax->value(); @@ -5062,13 +5307,15 @@ void OBSBasicSettings::AdvReplayBufferChanged() int64_t memMaxMB = memTotal ? memTotal * 3 / 4 / 1024 / 1024 : 8192; int64_t memMB = int64_t(seconds) * int64_t(vbitrate + abitrate) * 1000 / 8 / 1024 / 1024; - if (memMB < 1) + if (memMB < 1) { memMB = 1; + } bool varRateControl = (astrcmpi(rateControl, "CBR") == 0 || astrcmpi(rateControl, "VBR") == 0 || astrcmpi(rateControl, "ABR") == 0); - if (vbitrate == 0) + if (vbitrate == 0) { varRateControl = false; + } ui->advRBEstimate->setObjectName(""); if (varRateControl) { @@ -5125,15 +5372,17 @@ static void DisableIncompatibleSimpleCodecs(QComboBox *cbox, const QString &form if (ContainerSupportsCodec(format.toStdString(), codec.toStdString())) { item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); } else { - if (encoder == encName) + if (encoder == encName) { currentCompatible = false; + } item->setFlags(Qt::NoItemFlags); } } - if (!currentCompatible) + if (!currentCompatible) { cbox->setCurrentIndex(-1); + } } static void DisableIncompatibleSimpleContainer(QComboBox *cbox, const QString ¤tFormat, const QString &vEncoder, @@ -5155,15 +5404,17 @@ static void DisableIncompatibleSimpleContainer(QComboBox *cbox, const QString &c if (ContainerSupportsCodec(formatStr, vCodec) && ContainerSupportsCodec(formatStr, aCodec)) { item->setFlags(Qt::ItemIsSelectable | Qt::ItemIsEnabled); } else { - if (format == currentFormat) + if (format == currentFormat) { currentCompatible = false; + } item->setFlags(Qt::NoItemFlags); } } - if (!currentCompatible) + if (!currentCompatible) { cbox->setCurrentIndex(-1); + } } void OBSBasicSettings::SimpleRecordingEncoderChanged() @@ -5188,11 +5439,13 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() int newVBitrate = obs_data_get_int(videoSettings, "bitrate"); int newABitrate = obs_data_get_int(audioSettings, "bitrate"); - if (newVBitrate < oldVBitrate) + if (newVBitrate < oldVBitrate) { warning = SIMPLE_OUTPUT_WARNING("VideoBitrate").arg(newVBitrate); + } if (newABitrate < oldABitrate) { - if (!warning.isEmpty()) + if (!warning.isEmpty()) { warning += "\n\n"; + } warning += SIMPLE_OUTPUT_WARNING("AudioBitrate").arg(newABitrate); } } @@ -5201,14 +5454,16 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() /* Set tooltip if available */ QString tooltip = QTStr(QT_TO_UTF8(("Basic.Settings.Output.Format.TT." + format))); - if (!tooltip.startsWith("Basic.Settings.Output")) + if (!tooltip.startsWith("Basic.Settings.Output")) { ui->simpleOutRecFormat->setToolTip(tooltip); - else + } else { ui->simpleOutRecFormat->setToolTip(nullptr); + } if (qual == "Lossless") { - if (!warning.isEmpty()) + if (!warning.isEmpty()) { warning += "\n\n"; + } warning += SIMPLE_OUTPUT_WARNING("Lossless"); warning += "\n\n"; warning += SIMPLE_OUTPUT_WARNING("Encoder"); @@ -5219,8 +5474,9 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() bool x264RecEnc = (enc == SIMPLE_ENCODER_X264 || enc == SIMPLE_ENCODER_X264_LOWCPU); if (streamEnc == SIMPLE_ENCODER_X264 && x264RecEnc) { - if (!warning.isEmpty()) + if (!warning.isEmpty()) { warning += "\n\n"; + } warning += SIMPLE_OUTPUT_WARNING("Encoder"); } @@ -5233,8 +5489,9 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() ui->simpleOutRecEncoder->blockSignals(false); if (ui->simpleOutRecEncoder->currentIndex() == -1 || ui->simpleOutRecAEncoder->currentIndex() == -1) { - if (!warning.isEmpty()) + if (!warning.isEmpty()) { warning += "\n\n"; + } warning += QTStr("OutputWarnings.CodecIncompatible"); } } else { @@ -5247,19 +5504,22 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() ui->simpleOutRecFormat->blockSignals(false); if (ui->simpleOutRecFormat->currentIndex() == -1) { - if (!warning.isEmpty()) + if (!warning.isEmpty()) { warning += "\n\n"; + } warning += SIMPLE_OUTPUT_WARNING("IncompatibleContainer"); } - if (!warning.isEmpty()) + if (!warning.isEmpty()) { warning += "\n\n"; + } warning += SIMPLE_OUTPUT_WARNING("CannotPause"); } if (qual != "Lossless" && (format == "mp4" || format == "mov")) { - if (!warning.isEmpty()) + 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")); @@ -5279,8 +5539,9 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() } } - if (warning.isEmpty()) + if (warning.isEmpty()) { return; + } simpleOutRecWarning = new QLabel(warning, this); simpleOutRecWarning->setProperty("class", "text-warning"); @@ -5290,8 +5551,9 @@ void OBSBasicSettings::SimpleRecordingEncoderChanged() void OBSBasicSettings::SurroundWarning(int idx) { - if (idx == lastChannelSetupIdx || idx == -1) + if (idx == lastChannelSetupIdx || idx == -1) { return; + } if (loading) { lastChannelSetupIdx = idx; @@ -5338,8 +5600,9 @@ void OBSBasicSettings::UpdateAudioWarnings() } if (lowBufferingActive) { - if (!text.isEmpty()) + if (!text.isEmpty()) { text += QStringLiteral("\n\n"); + } text += QTStr(LL_BUFFERING_WARNING ".Enabled") + QStringLiteral("\n\n") + QTStr(LL_BUFFERING_WARNING); } @@ -5369,8 +5632,9 @@ void OBSBasicSettings::LowLatencyBufferingChanged(bool checked) void OBSBasicSettings::SimpleRecordingQualityLosslessWarning(int idx) { - if (idx == lastSimpleRecQualityIdx || idx == -1) + if (idx == lastSimpleRecQualityIdx || idx == -1) { return; + } QString qual = ui->simpleOutRecQuality->itemData(idx).toString(); @@ -5499,18 +5763,19 @@ void OBSBasicSettings::SetAdvancedIcon(const QIcon &icon) int OBSBasicSettings::CurrentFLVTrack() { - if (ui->flvTrack1->isChecked()) + if (ui->flvTrack1->isChecked()) { return 1; - else if (ui->flvTrack2->isChecked()) + } else if (ui->flvTrack2->isChecked()) { return 2; - else if (ui->flvTrack3->isChecked()) + } else if (ui->flvTrack3->isChecked()) { return 3; - else if (ui->flvTrack4->isChecked()) + } else if (ui->flvTrack4->isChecked()) { return 4; - else if (ui->flvTrack5->isChecked()) + } else if (ui->flvTrack5->isChecked()) { return 5; - else if (ui->flvTrack6->isChecked()) + } else if (ui->flvTrack6->isChecked()) { return 6; + } return 0; } @@ -5610,8 +5875,9 @@ void OBSBasicSettings::UpdateMultitrackVideo() 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"); - if (!available && ui->enableMultitrackVideo->isChecked()) + if (!available && ui->enableMultitrackVideo->isChecked()) { ui->enableMultitrackVideo->setChecked(false); + } } ui->multitrackVideoGroupBox->setVisible(available); @@ -5685,8 +5951,9 @@ void OBSBasicSettings::UpdateMultitrackVideo() ui->advOutRescale->setDisabled(disable_video); ui->advOutRescaleFilter->setDisabled(disable_video); - if (streamEncoderProps) + if (streamEncoderProps) { streamEncoderProps->SetDisabled(disable_video); + } }; auto update_advanced_output_audio_tracks = [&](bool mtv_enabled) { @@ -5751,8 +6018,9 @@ void OBSBasicSettings::UpdateMultitrackVideo() } auto multitrack_video_name = QTStr("Basic.Settings.Stream.MultitrackVideoLabel"); - if (obs_data_has_user_value(settings, "multitrack_video_name")) + if (obs_data_has_user_value(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)); @@ -5790,8 +6058,9 @@ void OBSBasicSettings::SimpleStreamAudioEncoderChanged() { PopulateSimpleBitrates(ui->simpleOutputABitrate, ui->simpleOutStrAEncoder->currentData().toString() == "opus"); - if (IsSurround(QT_TO_UTF8(ui->channelSetup->currentText()))) + if (IsSurround(QT_TO_UTF8(ui->channelSetup->currentText()))) { return; + } RestrictResetBitrates({ui->simpleOutputABitrate}, 320); } @@ -5801,15 +6070,17 @@ void OBSBasicSettings::AdvAudioEncodersChanged() QString streamEncoder = ui->advOutAEncoder->currentData().toString(); QString recEncoder = ui->advOutRecAEncoder->currentData().toString(); - if (recEncoder == "none") + 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)); - if (IsSurround(QT_TO_UTF8(ui->channelSetup->currentText()))) + if (IsSurround(QT_TO_UTF8(ui->channelSetup->currentText()))) { return; + } RestrictResetBitrates({ui->advOutTrack1Bitrate, ui->advOutTrack2Bitrate, ui->advOutTrack3Bitrate, ui->advOutTrack4Bitrate, ui->advOutTrack5Bitrate, ui->advOutTrack6Bitrate}, diff --git a/frontend/settings/OBSBasicSettings_A11y.cpp b/frontend/settings/OBSBasicSettings_A11y.cpp index c15c65e6911ebd..2f0ee6c1b1b908 100644 --- a/frontend/settings/OBSBasicSettings_A11y.cpp +++ b/frontend/settings/OBSBasicSettings_A11y.cpp @@ -181,8 +181,9 @@ void OBSBasicSettings::on_choose1_clicked() { QColor color = GetColor(selectRed, QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectRed")); - if (!color.isValid()) + if (!color.isValid()) { return; + } selectRed = color_to_int(color); @@ -200,8 +201,9 @@ void OBSBasicSettings::on_choose2_clicked() { QColor color = GetColor(selectGreen, QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectGreen")); - if (!color.isValid()) + if (!color.isValid()) { return; + } selectGreen = color_to_int(color); @@ -219,8 +221,9 @@ void OBSBasicSettings::on_choose3_clicked() { QColor color = GetColor(selectBlue, QTStr("Basic.Settings.Accessibility.ColorOverrides.SelectBlue")); - if (!color.isValid()) + if (!color.isValid()) { return; + } selectBlue = color_to_int(color); @@ -238,8 +241,9 @@ void OBSBasicSettings::on_choose4_clicked() { QColor color = GetColor(mixerGreen, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerGreen")); - if (!color.isValid()) + if (!color.isValid()) { return; + } mixerGreen = color_to_int(color); @@ -257,8 +261,9 @@ void OBSBasicSettings::on_choose5_clicked() { QColor color = GetColor(mixerYellow, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerYellow")); - if (!color.isValid()) + if (!color.isValid()) { return; + } mixerYellow = color_to_int(color); @@ -276,8 +281,9 @@ void OBSBasicSettings::on_choose6_clicked() { QColor color = GetColor(mixerRed, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerRed")); - if (!color.isValid()) + if (!color.isValid()) { return; + } mixerRed = color_to_int(color); @@ -296,8 +302,9 @@ void OBSBasicSettings::on_choose7_clicked() QColor color = GetColor(mixerGreenActive, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerGreenActive")); - if (!color.isValid()) + if (!color.isValid()) { return; + } mixerGreenActive = color_to_int(color); @@ -316,8 +323,9 @@ void OBSBasicSettings::on_choose8_clicked() QColor color = GetColor(mixerYellowActive, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerYellowActive")); - if (!color.isValid()) + if (!color.isValid()) { return; + } mixerYellowActive = color_to_int(color); @@ -335,8 +343,9 @@ void OBSBasicSettings::on_choose9_clicked() { QColor color = GetColor(mixerRedActive, QTStr("Basic.Settings.Accessibility.ColorOverrides.MixerRedActive")); - if (!color.isValid()) + if (!color.isValid()) { return; + } mixerRedActive = color_to_int(color); diff --git a/frontend/settings/OBSBasicSettings_Appearance.cpp b/frontend/settings/OBSBasicSettings_Appearance.cpp index 50a51ac7924e35..64b1456108a8f4 100644 --- a/frontend/settings/OBSBasicSettings_Appearance.cpp +++ b/frontend/settings/OBSBasicSettings_Appearance.cpp @@ -17,8 +17,9 @@ void OBSBasicSettings::InitAppearancePage() } int idx = ui->theme->findData(currentBaseTheme); - if (idx != -1) + if (idx != -1) { ui->theme->setCurrentIndex(idx); + } ui->themeVariant->setPlaceholderText(QTStr("Basic.Settings.Appearance.General.NoVariant")); @@ -41,8 +42,9 @@ void OBSBasicSettings::LoadThemeList(bool reload) /* Nothing to do if current and last base theme were the same */ const QString baseThemeId = ui->theme->currentData().toString(); - if (reload && baseThemeId == currentBaseTheme) + if (reload && baseThemeId == currentBaseTheme) { return; + } ui->themeVariant->blockSignals(true); ui->themeVariant->clear(); @@ -57,20 +59,24 @@ void OBSBasicSettings::LoadThemeList(bool reload) for (const OBSTheme &theme : themes) { /* Skip non-visible themes */ - if (!theme.isVisible || theme.isHighContrast) + if (!theme.isVisible || theme.isHighContrast) { continue; + } /* Skip non-child themes */ - if (theme.isBaseTheme || theme.parent != baseThemeId) + if (theme.isBaseTheme || theme.parent != baseThemeId) { continue; + } ui->themeVariant->addItem(theme.name, theme.id); - if (baseTheme && theme.filename == baseTheme->filename) + if (baseTheme && theme.filename == baseTheme->filename) { defaultVariant = theme.id; + } } int idx = ui->themeVariant->findData(currentTheme->id); - if (idx != -1) + if (idx != -1) { ui->themeVariant->setCurrentIndex(idx); + } ui->themeVariant->setEnabled(ui->themeVariant->count() > 0); ui->themeVariant->blockSignals(false); @@ -89,8 +95,9 @@ void OBSBasicSettings::LoadAppearanceSettings(bool reload) if (reload) { QString themeId = ui->theme->currentData().toString(); - if (ui->themeVariant->currentIndex() != -1) + if (ui->themeVariant->currentIndex() != -1) { themeId = ui->themeVariant->currentData().toString(); + } App()->SetTheme(themeId); } diff --git a/frontend/settings/OBSBasicSettings_Stream.cpp b/frontend/settings/OBSBasicSettings_Stream.cpp index 5179f44d818360..e6382de54cfca5 100644 --- a/frontend/settings/OBSBasicSettings_Stream.cpp +++ b/frontend/settings/OBSBasicSettings_Stream.cpp @@ -114,8 +114,9 @@ void OBSBasicSettings::LoadStream1Settings() protocol = QT_UTF8(obs_service_get_protocol(service_obj)); const char *bearer_token = obs_data_get_string(settings, "bearer_token"); - if (is_rtmp_custom || is_whip) + if (is_rtmp_custom || is_whip) { ui->customServer->setText(server); + } if (is_rtmp_custom) { ui->service->setCurrentIndex(0); @@ -131,8 +132,9 @@ void OBSBasicSettings::LoadStream1Settings() } else { int idx = ui->service->findText(service); if (idx == -1) { - if (service && *service) + if (service && *service) { ui->service->insertItem(1, service); + } idx = 1; } ui->service->setCurrentIndex(idx); @@ -156,26 +158,29 @@ void OBSBasicSettings::LoadStream1Settings() ui->multitrackVideoMaximumVideoTracksAuto->setChecked( config_get_bool(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracksAuto")); - if (config_has_user_value(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracks")) + if (config_has_user_value(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracks")) { ui->multitrackVideoMaximumVideoTracks->setValue( config_get_int(main->Config(), "Stream1", "MultitrackVideoMaximumVideoTracks")); + } 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")) + if (config_has_user_value(main->Config(), "Stream1", "MultitrackVideoConfigOverride")) { ui->multitrackVideoConfigOverride->setPlainText( DeserializeConfigText( config_get_string(main->Config(), "Stream1", "MultitrackVideoConfigOverride")) .c_str()); + } ui->multitrackVideoAdditionalCanvas->clear(); ui->multitrackVideoAdditionalCanvas->addItem(QTStr("None")); for (const auto &canvas : main->GetCanvases()) { - if (obs_canvas_get_flags(canvas) & EPHEMERAL) + if (obs_canvas_get_flags(canvas) & EPHEMERAL) { continue; + } ui->multitrackVideoAdditionalCanvas->addItem(obs_canvas_get_name(canvas), obs_canvas_get_uuid(canvas)); } @@ -200,15 +205,17 @@ void OBSBasicSettings::LoadStream1Settings() } if (idx == -1) { - if (server && *server) + if (server && *server) { ui->server->insertItem(0, server, server); + } idx = 0; } ui->server->setCurrentIndex(idx); } - if (use_custom_server) + if (use_custom_server) { ui->serviceCustomServer->setText(server); + } if (is_whip) { ui->key->setText(bearer_token); @@ -300,8 +307,9 @@ void OBSBasicSettings::SaveStream1Settings() config_set_int(main->Config(), "Twitch", "AddonChoice", newChoice); - if (choiceExists && currentChoice != newChoice) + if (choiceExists && currentChoice != newChoice) { forceAuthReload = true; + } obs_data_set_bool(settings, "bwtest", ui->bandwidthTestEnable->isChecked()); } else { @@ -317,8 +325,9 @@ void OBSBasicSettings::SaveStream1Settings() OBSServiceAutoRelease newService = obs_service_create(service_id, "default_service", settings, hotkeyData); - if (!newService) + if (!newService) { return; + } main->SetService(newService); main->SaveService(); @@ -364,8 +373,9 @@ void OBSBasicSettings::SaveStream1Settings() SaveComboData(ui->multitrackVideoAdditionalCanvas, "Stream1", "MultitrackExtraCanvas"); if (oldMultitrackVideoSetting != ui->enableMultitrackVideo->isChecked() || - oldWHIPSimulcastTotalLayers != ui->whipSimulcastTotalLayers->value()) + oldWHIPSimulcastTotalLayers != ui->whipSimulcastTotalLayers->value()) { main->ResetOutputs(); + } SwapMultiTrack(QT_TO_UTF8(protocol)); } @@ -475,11 +485,13 @@ void OBSBasicSettings::LoadServices(bool showAll) names.push_back(name); } - if (showAll) + if (showAll) { names.sort(Qt::CaseInsensitive); + } - for (QString &name : names) + for (QString &name : names) { ui->service->addItem(name); + } if (obs_is_output_protocol_registered("WHIP")) { ui->service->addItem(QTStr("WHIP"), QVariant((int)ListOpt::WHIP)); @@ -494,8 +506,9 @@ void OBSBasicSettings::LoadServices(bool showAll) if (!lastService.isEmpty()) { int idx = ui->service->findText(lastService); - if (idx != -1) + if (idx != -1) { ui->service->setCurrentIndex(idx); + } } obs_properties_destroy(props); @@ -588,8 +601,9 @@ void OBSBasicSettings::on_service_currentIndexChanged(int idx) if (ServiceSupportsCodecCheck() && UpdateResFPSLimits()) { lastServiceIdx = idx; - if (idx == 0) + if (idx == 0) { lastCustomServer = ui->customServer->text(); + } } if (!IsCustomService()) { @@ -613,8 +627,9 @@ void OBSBasicSettings::on_customServer_textChanged(const QString &) UpdateAdvNetworkGroup(); UpdateMultitrackVideo(); - if (ServiceSupportsCodecCheck()) + if (ServiceSupportsCodecCheck()) { lastCustomServer = ui->customServer->text(); + } SwapMultiTrack(QT_TO_UTF8(protocol)); } @@ -676,19 +691,23 @@ void OBSBasicSettings::ServiceChanged(bool resetFields) QString OBSBasicSettings::FindProtocol() { if (IsCustomService()) { - if (ui->customServer->text().isEmpty()) + if (ui->customServer->text().isEmpty()) { return QString("RTMP"); + } 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://")) + if (server.startsWith("srt://")) { return QString("SRT"); + } - if (server.startsWith("rist://")) + if (server.startsWith("rist://")) { return QString("RIST"); + } } else { obs_properties_t *props = obs_get_service_properties("rtmp_common"); @@ -702,8 +721,9 @@ QString OBSBasicSettings::FindProtocol() obs_properties_destroy(props); const char *protocol = obs_data_get_string(settings, "protocol"); - if (protocol && *protocol) + if (protocol && *protocol) { return QT_UTF8(protocol); + } } return QString("RTMP"); @@ -784,10 +804,11 @@ OBSService OBSBasicSettings::SpawnTempService() obs_data_set_string(settings, "server", QT_TO_UTF8(ui->customServer->text().trimmed())); } - if (whip) + if (whip) { obs_data_set_string(settings, "bearer_token", QT_TO_UTF8(ui->key->text())); - else + } else { obs_data_set_string(settings, "key", QT_TO_UTF8(ui->key->text())); + } OBSServiceAutoRelease newService = obs_service_create(service_id, "temp_service", settings, nullptr); return newService.Get(); @@ -800,8 +821,9 @@ void OBSBasicSettings::OnOAuthStreamKeyConnected() if (a) { bool validKey = !a->key().empty(); - if (validKey) + if (validKey) { ui->key->setText(QT_UTF8(a->key().c_str())); + } ui->streamKeyWidget->setVisible(false); ui->streamKeyLabel->setVisible(false); @@ -926,8 +948,9 @@ void OBSBasicSettings::on_useStreamKey_clicked() void OBSBasicSettings::on_useAuth_toggled() { - if (!IsCustomService()) + if (!IsCustomService()) { return; + } bool use_auth = ui->useAuth->isChecked(); @@ -956,11 +979,13 @@ void OBSBasicSettings::UpdateVodTrackSetting() bool enableVodTrack = ui->service->currentText() == "Twitch"; bool wasEnabled = !!vodTrackCheckbox; - if (enableForCustomServer && IsCustomService()) + if (enableForCustomServer && IsCustomService()) { enableVodTrack = true; + } - if (enableVodTrack == wasEnabled) + if (enableVodTrack == wasEnabled) { return; + } if (!enableVodTrack) { delete vodTrackCheckbox; @@ -1049,16 +1074,19 @@ void OBSBasicSettings::UpdateServiceRecommendations() QString text; #define ENFORCE_TEXT(x) QTStr("Basic.Settings.Stream.Recommended." x) - if (vbitrate) + if (vbitrate) { text += ENFORCE_TEXT("MaxVideoBitrate").arg(QString::number(vbitrate)); + } if (abitrate) { - if (!text.isEmpty()) + if (!text.isEmpty()) { text += "
"; + } text += ENFORCE_TEXT("MaxAudioBitrate").arg(QString::number(abitrate)); } if (res_count) { - if (!text.isEmpty()) + if (!text.isEmpty()) { text += "
"; + } obs_service_resolution best_res = {}; int best_res_pixels = 0; @@ -1076,8 +1104,9 @@ void OBSBasicSettings::UpdateServiceRecommendations() text += ENFORCE_TEXT("MaxResolution").arg(res_str); } if (fps) { - if (!text.isEmpty()) + if (!text.isEmpty()) { text += "
"; + } text += ENFORCE_TEXT("MaxFPS").arg(QString::number(fps)); } @@ -1085,8 +1114,9 @@ void OBSBasicSettings::UpdateServiceRecommendations() #ifdef YOUTUBE_ENABLED if (IsYouTubeService(QT_TO_UTF8(ui->service->currentText()))) { - if (!text.isEmpty()) + if (!text.isEmpty()) { text += "

"; + } text += "" "YouTube Terms of Service
" @@ -1101,8 +1131,9 @@ void OBSBasicSettings::UpdateServiceRecommendations() void OBSBasicSettings::DisplayEnforceWarning(bool checked) { - if (IsCustomService()) + if (IsCustomService()) { return; + } if (!checked) { SimpleRecordingEncoderChanged(); @@ -1127,16 +1158,18 @@ void OBSBasicSettings::DisplayEnforceWarning(bool checked) bool OBSBasicSettings::ResFPSValid(obs_service_resolution *res_list, size_t res_count, int max_fps) { - if (!res_count && !max_fps) + if (!res_count && !max_fps) { return true; + } if (res_count) { QString res = ui->outputResolution->currentText(); bool found_res = false; int cx, cy; - if (sscanf(QT_TO_UTF8(res), "%dx%d", &cx, &cy) != 2) + if (sscanf(QT_TO_UTF8(res), "%dx%d", &cx, &cy) != 2) { return false; + } for (size_t i = 0; i < res_count; i++) { if (res_list[i].cx == cx && res_list[i].cy == cy) { @@ -1145,20 +1178,23 @@ bool OBSBasicSettings::ResFPSValid(obs_service_resolution *res_list, size_t res_ } } - if (!found_res) + if (!found_res) { return false; + } } if (max_fps) { int fpsType = ui->fpsType->currentIndex(); - if (fpsType != 0) + if (fpsType != 0) { return false; + } std::string fps_str = QT_TO_UTF8(ui->fpsCommon->currentText()); float fps; sscanf(fps_str.c_str(), "%f", &fps); - if (fps > (float)max_fps) + if (fps > (float)max_fps) { return false; + } } return true; @@ -1185,12 +1221,14 @@ extern void set_closest_res(int &cx, int &cy, struct obs_service_resolution *res */ bool OBSBasicSettings::UpdateResFPSLimits() { - if (loading) + if (loading) { return false; + } int idx = ui->service->currentIndex(); - if (idx == -1) + if (idx == -1) { return false; + } bool ignoreRecommended = ui->ignoreRecommended->isChecked(); BPtr res_list; @@ -1215,8 +1253,9 @@ bool OBSBasicSettings::UpdateResFPSLimits() sscanf(QT_TO_UTF8(res), "%dx%d", &cx, &cy); - if (res_count) + if (res_count) { set_closest_res(cx, cy, res_list, res_count); + } if (max_fps) { int fpsType = ui->fpsType->currentIndex(); @@ -1271,11 +1310,13 @@ bool OBSBasicSettings::UpdateResFPSLimits() #define WARNING_VAL(x) QTStr("Basic.Settings.Output.Warn.EnforceResolutionFPS." x) QString str; - if (res_count) + if (res_count) { str += WARNING_VAL("Resolution").arg(res_str); + } if (max_fps) { - if (!str.isEmpty()) + if (!str.isEmpty()) { str += "\n"; + } str += WARNING_VAL("FPS").arg(fps_str); } @@ -1283,12 +1324,13 @@ bool OBSBasicSettings::UpdateResFPSLimits() #undef WARNING_VAL if (button == QMessageBox::No) { - if (idx != lastServiceIdx) + if (idx != lastServiceIdx) { QMetaObject::invokeMethod(ui->service, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(int, lastServiceIdx)); - else + } else { QMetaObject::invokeMethod(ui->ignoreRecommended, "setChecked", Qt::QueuedConnection, Q_ARG(bool, true)); + } return false; } } @@ -1311,8 +1353,9 @@ bool OBSBasicSettings::UpdateResFPSLimits() 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) + if (val.cx == cx && val.cy == cy) { new_res_index = (int)i; + } } ui->outputResolution->setCurrentIndex(new_res_index); @@ -1355,8 +1398,9 @@ bool OBSBasicSettings::UpdateResFPSLimits() EnableApplyButton(true); } } else { - for (int i = 0; i < ui->fpsCommon->count(); i++) + for (int i = 0; i < ui->fpsCommon->count(); i++) { SetComboItemEnabled(ui->fpsCommon, i, true); + } } SetComboItemEnabled(ui->fpsType, 1, !max_fps); @@ -1371,12 +1415,14 @@ bool OBSBasicSettings::UpdateResFPSLimits() static bool service_supports_codec(const char **codecs, const char *codec) { - if (!codecs) + if (!codecs) { return true; + } while (*codecs) { - if (strcmp(*codecs, codec) == 0) + if (strcmp(*codecs, codec) == 0) { return true; + } codecs++; } @@ -1388,8 +1434,9 @@ extern const char *get_simple_output_encoder(const char *name); static inline bool service_supports_encoder(const char **codecs, const char *encoder) { - if (!EncoderAvailable(encoder)) + if (!EncoderAvailable(encoder)) { return false; + } const char *codec = obs_get_encoder_codec(encoder); return service_supports_codec(codecs, codec); @@ -1478,14 +1525,18 @@ bool OBSBasicSettings::ServiceAndACodecCompatible() 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") + enc == "jim_av1_nvenc") { return "obs_nvenc_h264_tex"; - if (enc == "h265_texture_amf" || enc == "av1_texture_amf") + } + if (enc == "h265_texture_amf" || enc == "av1_texture_amf") { return "h264_texture_amf"; - if (enc == "com.apple.videotoolbox.videoencoder.ave.hevc") + } + if (enc == "com.apple.videotoolbox.videoencoder.ave.hevc") { return "com.apple.videotoolbox.videoencoder.ave.avc"; - if (enc == "obs_qsv11_av1") + } + if (enc == "obs_qsv11_av1") { return "obs_qsv11"; + } return "obs_x264"; } @@ -1493,42 +1544,50 @@ static QString get_adv_audio_fallback(const QString &enc) { const char *codec = obs_get_encoder_codec(QT_TO_UTF8(enc)); - if (codec && strcmp(codec, "aac") == 0) + if (codec && strcmp(codec, "aac") == 0) { return "ffmpeg_opus"; + } QString aac_default = "ffmpeg_aac"; - if (EncoderAvailable("CoreAudio_AAC")) + if (EncoderAvailable("CoreAudio_AAC")) { aac_default = "CoreAudio_AAC"; - else if (EncoderAvailable("libfdk_aac")) + } else if (EncoderAvailable("libfdk_aac")) { aac_default = "libfdk_aac"; + } return aac_default; } static QString get_simple_fallback(const QString &enc) { - if (enc == SIMPLE_ENCODER_NVENC_HEVC || enc == SIMPLE_ENCODER_NVENC_AV1) + if (enc == SIMPLE_ENCODER_NVENC_HEVC || enc == SIMPLE_ENCODER_NVENC_AV1) { return SIMPLE_ENCODER_NVENC; - if (enc == SIMPLE_ENCODER_AMD_HEVC || enc == SIMPLE_ENCODER_AMD_AV1) + } + if (enc == SIMPLE_ENCODER_AMD_HEVC || enc == SIMPLE_ENCODER_AMD_AV1) { return SIMPLE_ENCODER_AMD; - if (enc == SIMPLE_ENCODER_APPLE_HEVC) + } + if (enc == SIMPLE_ENCODER_APPLE_HEVC) { return SIMPLE_ENCODER_APPLE_H264; - if (enc == SIMPLE_ENCODER_QSV_AV1) + } + if (enc == SIMPLE_ENCODER_QSV_AV1) { return SIMPLE_ENCODER_QSV; + } return SIMPLE_ENCODER_X264; } bool OBSBasicSettings::ServiceSupportsCodecCheck() { - if (loading) + if (loading) { return false; + } bool vcodec_compat = ServiceAndVCodecCompatible(); 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; } @@ -1576,19 +1635,21 @@ bool OBSBasicSettings::ServiceSupportsCodecCheck() 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) + if (!vcodec_compat && !acodec_compat) { 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()) + if (lastServiceIdx == 0 && lastServiceIdx == ui->service->currentIndex()) { QMetaObject::invokeMethod(ui->customServer, "setText", Qt::QueuedConnection, Q_ARG(QString, lastCustomServer)); - else + } else { QMetaObject::invokeMethod(ui->service, "setCurrentIndex", Qt::QueuedConnection, Q_ARG(int, lastServiceIdx)); + } return false; } @@ -1658,20 +1719,25 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) QString qType = QT_UTF8(type); if (obs_get_encoder_type(type) == OBS_ENCODER_VIDEO) { - if ((caps & ENCODER_HIDE_FLAGS) != 0) + if ((caps & ENCODER_HIDE_FLAGS) != 0) { continue; + } - if (service_supports_codec(vcodecs, codec)) + if (service_supports_codec(vcodecs, codec)) { ui->advOutEncoder->addItem(qName, qType); - if (!streamOnly) + } + if (!streamOnly) { ui->advOutRecEncoder->addItem(qName, qType); + } } if (obs_get_encoder_type(type) == OBS_ENCODER_AUDIO) { - if (service_supports_codec(acodecs, codec)) + if (service_supports_codec(acodecs, codec)) { ui->advOutAEncoder->addItem(qName, qType); - if (!streamOnly) + } + if (!streamOnly) { ui->advOutRecAEncoder->addItem(qName, qType); + } } } @@ -1692,26 +1758,34 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) ui->simpleOutStrEncoder->addItem(ENCODER_STR("Software"), QString(SIMPLE_ENCODER_X264)); #ifdef _WIN32 - if (service_supports_encoder(vcodecs, "obs_qsv11")) + if (service_supports_encoder(vcodecs, "obs_qsv11")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.QSV.H264"), QString(SIMPLE_ENCODER_QSV)); - if (service_supports_encoder(vcodecs, "obs_qsv11_av1")) + } + if (service_supports_encoder(vcodecs, "obs_qsv11_av1")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.QSV.AV1"), QString(SIMPLE_ENCODER_QSV_AV1)); + } #endif - if (service_supports_encoder(vcodecs, "ffmpeg_nvenc")) + if (service_supports_encoder(vcodecs, "ffmpeg_nvenc")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.NVENC.H264"), QString(SIMPLE_ENCODER_NVENC)); - if (service_supports_encoder(vcodecs, "obs_nvenc_av1_tex")) + } + if (service_supports_encoder(vcodecs, "obs_nvenc_av1_tex")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.NVENC.AV1"), QString(SIMPLE_ENCODER_NVENC_AV1)); + } #ifdef ENABLE_HEVC - if (service_supports_encoder(vcodecs, "h265_texture_amf")) + if (service_supports_encoder(vcodecs, "h265_texture_amf")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.AMD.HEVC"), QString(SIMPLE_ENCODER_AMD_HEVC)); - if (service_supports_encoder(vcodecs, "ffmpeg_hevc_nvenc")) + } + if (service_supports_encoder(vcodecs, "ffmpeg_hevc_nvenc")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.NVENC.HEVC"), QString(SIMPLE_ENCODER_NVENC_HEVC)); + } #endif - if (service_supports_encoder(vcodecs, "h264_texture_amf")) + if (service_supports_encoder(vcodecs, "h264_texture_amf")) { ui->simpleOutStrEncoder->addItem(ENCODER_STR("Hardware.AMD.H264"), QString(SIMPLE_ENCODER_AMD)); - if (service_supports_encoder(vcodecs, "av1_texture_amf")) + } + if (service_supports_encoder(vcodecs, "av1_texture_amf")) { 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") @@ -1738,10 +1812,12 @@ void OBSBasicSettings::ResetEncoders(bool streamOnly) #endif #endif if (service_supports_encoder(acodecs, "CoreAudio_AAC") || service_supports_encoder(acodecs, "libfdk_aac") || - service_supports_encoder(acodecs, "ffmpeg_aac")) + service_supports_encoder(acodecs, "ffmpeg_aac")) { ui->simpleOutStrAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.AAC.Default"), "aac"); - if (service_supports_encoder(acodecs, "ffmpeg_opus")) + } + if (service_supports_encoder(acodecs, "ffmpeg_opus")) { ui->simpleOutStrAEncoder->addItem(QTStr("Basic.Settings.Output.Simple.Codec.Opus"), "opus"); + } #undef ENCODER_STR /* ------------------------------------------------- */ diff --git a/frontend/settings/OBSHotkeyEdit.cpp b/frontend/settings/OBSHotkeyEdit.cpp index da8735d2240bb7..970908c5c6c2a4 100644 --- a/frontend/settings/OBSHotkeyEdit.cpp +++ b/frontend/settings/OBSHotkeyEdit.cpp @@ -29,8 +29,9 @@ void OBSHotkeyEdit::keyPressEvent(QKeyEvent *event) { - if (event->isAutoRepeat()) + if (event->isAutoRepeat()) { return; + } obs_key_combination_t new_key; @@ -70,11 +71,13 @@ QVariant OBSHotkeyEdit::inputMethodQuery(Qt::InputMethodQuery query) const #ifdef __APPLE__ void OBSHotkeyEdit::keyReleaseEvent(QKeyEvent *event) { - if (event->isAutoRepeat()) + if (event->isAutoRepeat()) { return; + } - if (event->key() != Qt::Key_CapsLock) + if (event->key() != Qt::Key_CapsLock) { return; + } obs_key_combination_t new_key; @@ -140,8 +143,9 @@ void OBSHotkeyEdit::mousePressEvent(QMouseEvent *event) void OBSHotkeyEdit::HandleNewKey(obs_key_combination_t new_key) { - if (new_key == key || obs_key_combination_is_empty(new_key)) + if (new_key == key || obs_key_combination_is_empty(new_key)) { return; + } key = new_key; @@ -181,11 +185,13 @@ void OBSHotkeyEdit::ClearKey() void OBSHotkeyEdit::UpdateDuplicationState() { - if (!dupeIcon && !hasDuplicate) + if (!dupeIcon && !hasDuplicate) { return; + } - if (!dupeIcon) + if (!dupeIcon) { CreateDupeIcon(); + } if (dupeIcon->isVisible() != hasDuplicate) { dupeIcon->setVisible(hasDuplicate); diff --git a/frontend/settings/OBSHotkeyLabel.cpp b/frontend/settings/OBSHotkeyLabel.cpp index 1cfa8e5b0927c8..a6521478d8fe88 100644 --- a/frontend/settings/OBSHotkeyLabel.cpp +++ b/frontend/settings/OBSHotkeyLabel.cpp @@ -33,8 +33,9 @@ static inline void updateStyle(QWidget *widget) void OBSHotkeyLabel::highlightPair(bool highlight) { - if (!pairPartner) + if (!pairPartner) { return; + } pairPartner->setProperty("class", highlight ? "text-bright" : ""); updateStyle(pairPartner); @@ -45,8 +46,9 @@ void OBSHotkeyLabel::highlightPair(bool highlight) void OBSHotkeyLabel::enterEvent(QEnterEvent *event) { - if (!pairPartner) + if (!pairPartner) { return; + } event->accept(); highlightPair(true); @@ -54,8 +56,9 @@ void OBSHotkeyLabel::enterEvent(QEnterEvent *event) void OBSHotkeyLabel::leaveEvent(QEvent *event) { - if (!pairPartner) + if (!pairPartner) { return; + } event->accept(); highlightPair(false); @@ -64,6 +67,7 @@ void OBSHotkeyLabel::leaveEvent(QEvent *event) void OBSHotkeyLabel::setToolTip(const QString &toolTip) { QLabel::setToolTip(toolTip); - if (widget) + if (widget) { widget->setToolTip(toolTip); + } } diff --git a/frontend/settings/OBSHotkeyWidget.cpp b/frontend/settings/OBSHotkeyWidget.cpp index f2fab78725533a..03ebd5ec7907df 100644 --- a/frontend/settings/OBSHotkeyWidget.cpp +++ b/frontend/settings/OBSHotkeyWidget.cpp @@ -26,11 +26,13 @@ void OBSHotkeyWidget::SetKeyCombinations(const std::vector &combos) { - if (combos.empty()) + if (combos.empty()) { AddEdit({0, OBS_KEY_NONE}); + } - for (auto combo : combos) + for (auto combo : combos) { AddEdit(combo); + } } bool OBSHotkeyWidget::Changed() const @@ -47,16 +49,19 @@ void OBSHotkeyWidget::Apply() changed = false; - for (auto &revertButton : revertButtons) + for (auto &revertButton : revertButtons) { revertButton->setEnabled(false); + } } void OBSHotkeyWidget::GetCombinations(std::vector &combinations) const { combinations.clear(); - for (auto &edit : edits) - if (!obs_key_combination_is_empty(edit->key)) + for (auto &edit : edits) { + if (!obs_key_combination_is_empty(edit->key)) { combinations.emplace_back(edit->key); + } + } } void OBSHotkeyWidget::Save() @@ -130,8 +135,9 @@ void OBSHotkeyWidget::AddEdit(obs_key_combination combo, int idx) subLayout->addWidget(add); subLayout->addWidget(remove); - if (removeButtons.size() == 1) + if (removeButtons.size() == 1) { removeButtons.front()->setEnabled(true); + } if (idx != -1) { revertButtons.insert(begin(revertButtons) + idx, revert); @@ -172,8 +178,9 @@ void OBSHotkeyWidget::RemoveEdit(size_t idx, bool signal) } delete item; - if (removeButtons.size() == 1) + if (removeButtons.size() == 1) { removeButtons.front()->setEnabled(false); + } emit KeyChanged(); } @@ -188,13 +195,15 @@ void OBSHotkeyWidget::BindingsChanged(void *data, calldata_t *param) void OBSHotkeyWidget::HandleChangedBindings(obs_hotkey_id id_) { - if (ignoreChangedBindings || id != id_) + if (ignoreChangedBindings || id != id_) { return; + } std::vector bindings; auto LoadBindings = [&](obs_hotkey_binding_t *binding) { - if (obs_hotkey_binding_get_hotkey_id(binding) != id) + if (obs_hotkey_binding_get_hotkey_id(binding) != id) { return; + } auto get_combo = obs_hotkey_binding_get_key_combination; bindings.push_back(get_combo(binding)); @@ -209,16 +218,18 @@ void OBSHotkeyWidget::HandleChangedBindings(obs_hotkey_id id_) }, static_cast(&LoadBindings)); - while (edits.size() > 0) + while (edits.size() > 0) { RemoveEdit(edits.size() - 1, false); + } SetKeyCombinations(bindings); } void OBSHotkeyWidget::enterEvent(QEnterEvent *event) { - if (!label) + if (!label) { return; + } event->accept(); label->highlightPair(true); @@ -226,8 +237,9 @@ void OBSHotkeyWidget::enterEvent(QEnterEvent *event) void OBSHotkeyWidget::leaveEvent(QEvent *event) { - if (!label) + if (!label) { return; + } event->accept(); label->highlightPair(false); diff --git a/frontend/settings/OBSHotkeyWidget.hpp b/frontend/settings/OBSHotkeyWidget.hpp index 12f15f2829b162..b5dde78238292e 100644 --- a/frontend/settings/OBSHotkeyWidget.hpp +++ b/frontend/settings/OBSHotkeyWidget.hpp @@ -63,8 +63,9 @@ class OBSHotkeyWidget : public QWidget { void setToolTip(const QString &toolTip_) { toolTip = toolTip_; - for (auto &edit : edits) + for (auto &edit : edits) { edit->setToolTip(toolTip_); + } } void Apply(); diff --git a/frontend/updater/hash.cpp b/frontend/updater/hash.cpp index 06ef367d00b7a5..771fb83e34a91b 100644 --- a/frontend/updater/hash.cpp +++ b/frontend/updater/hash.cpp @@ -47,29 +47,35 @@ bool CalculateFileHash(const wchar_t *path, B2Hash &hash) { static __declspec(thread) vector hashBuffer; blake2b_state blake2; - if (blake2b_init(&blake2, kBlake2HashLength) != 0) + if (blake2b_init(&blake2, kBlake2HashLength) != 0) { return false; + } hashBuffer.resize(1048576); WinHandle handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) + 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) + if (!read) { break; + } - if (blake2b_update(&blake2, hashBuffer.data(), read) != 0) + if (blake2b_update(&blake2, hashBuffer.data(), read) != 0) { return false; + } } - if (blake2b_final(&blake2, hash.data(), hash.size()) != 0) + if (blake2b_final(&blake2, hash.data(), hash.size()) != 0) { return false; + } return true; } diff --git a/frontend/updater/helpers.hpp b/frontend/updater/helpers.hpp index 8937c263ad7f97..4298a5768cf41c 100644 --- a/frontend/updater/helpers.hpp +++ b/frontend/updater/helpers.hpp @@ -14,8 +14,9 @@ template class CustomHandle { inline CustomHandle(T in) : handle(in) {} inline ~CustomHandle() { - if (handle) + if (handle) { freefunc(handle); + } } inline T *operator&() { return &handle; } @@ -24,8 +25,9 @@ template class CustomHandle { inline CustomHandle &operator=(T in) { - if (handle) + if (handle) { freefunc(handle); + } handle = in; return *this; } diff --git a/frontend/updater/http.cpp b/frontend/updater/http.cpp index 9cf39acfc19510..746c84fc722771 100644 --- a/frontend/updater/http.cpp +++ b/frontend/updater/http.cpp @@ -67,8 +67,9 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, const wchar WinHttpCrackUrl(url, 0, 0, &urlComponents); - if (urlComponents.nPort == 443) + if (urlComponents.nPort == 443) { secure = true; + } /* -------------------------------------- * * connect to server */ @@ -146,8 +147,9 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, const wchar *responseCode = wcstoul(statusCode, nullptr, 10); /* are we supposed to return true here? */ - if (!bResults || *responseCode != 200) + if (!bResults || *responseCode != 200) { return true; + } BYTE buffer[READ_BUF_SIZE]; DWORD dwSize, outSize; @@ -167,8 +169,9 @@ bool HTTPPostData(const wchar_t *url, const BYTE *data, int dataLen, const wchar return false; } - if (!outSize) + if (!outSize) { break; + } if (!ReadHTTPData(responseBuf, buffer, outSize)) { *responseCode = -6; @@ -240,8 +243,9 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, const wchar_t *outputPa WinHttpCrackUrl(url, 0, 0, &urlComponents); - if (urlComponents.nPort == 443) + if (urlComponents.nPort == 443) { secure = true; + } /* -------------------------------------- * * request data */ @@ -287,8 +291,9 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, const wchar_t *outputPa *responseCode = wcstoul(statusCode, nullptr, 10); /* are we supposed to return true here? */ - if (!bResults || *responseCode != 200) + if (!bResults || *responseCode != 200) { return true; + } BYTE buffer[READ_BUF_SIZE]; DWORD dwSize, outSize; @@ -313,11 +318,13 @@ bool HTTPGetFile(HINTERNET hConnect, const wchar_t *url, const wchar_t *outputPa *responseCode = -9; return false; } else { - if (!outSize) + if (!outSize) { break; + } - if (!ReadHTTPFile(updateFile, buffer, outSize, responseCode)) + if (!ReadHTTPFile(updateFile, buffer, outSize, responseCode)) { return false; + } UpdateProgressBar(); } @@ -358,8 +365,9 @@ bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, const wchar_t *extraH WinHttpCrackUrl(url, 0, 0, &urlComponents); - if (urlComponents.nPort == 443) + if (urlComponents.nPort == 443) { secure = true; + } /* -------------------------------------- * * request data */ @@ -405,8 +413,9 @@ bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, const wchar_t *extraH *responseCode = wcstoul(statusCode, nullptr, 10); /* are we supposed to return true here? */ - if (!bResults || *responseCode != 200) + if (!bResults || *responseCode != 200) { return true; + } BYTE buffer[READ_BUF_SIZE]; DWORD dwSize, outSize; @@ -425,8 +434,9 @@ bool HTTPGetBuffer(HINTERNET hConnect, const wchar_t *url, const wchar_t *extraH *responseCode = -9; return false; } else { - if (!outSize) + if (!outSize) { break; + } out.insert(out.end(), (std::byte *)buffer, (std::byte *)buffer + outSize); diff --git a/frontend/updater/patch.cpp b/frontend/updater/patch.cpp index 6d77484a99b5d9..d50b7c37d05464 100644 --- a/frontend/updater/patch.cpp +++ b/frontend/updater/patch.cpp @@ -42,8 +42,9 @@ static int64_t offtin(const uint8_t *buf) y = y * 256; y += buf[0]; - if (buf[7] & 0x80) + if (buf[7] & 0x80) { y = -y; + } return y; } @@ -65,21 +66,24 @@ try { * open patch and file to patch */ hTarget = CreateFile(targetFile, GENERIC_READ, 0, nullptr, OPEN_EXISTING, 0, nullptr); - if (!hTarget.Valid()) + if (!hTarget.Valid()) { throw int(GetLastError()); + } /* --------------------------------- * * read patch header */ - if (memcmp(patch_data, kDeltaMagic, kMagicSize) != 0) + if (memcmp(patch_data, kDeltaMagic, kMagicSize) != 0) { throw int(-4); + } /* --------------------------------- * * allocate new file size data */ newsize = offtin((const uint8_t *)patch_data + kMagicSize); - if (newsize < 0 || newsize >= 0x7ffffffff) + if (newsize < 0 || newsize >= 0x7ffffffff) { throw int(-5); + } vector newData; try { @@ -95,8 +99,9 @@ try { DWORD oldFileSize; oldFileSize = GetFileSize(hTarget, nullptr); - if (oldFileSize == INVALID_FILE_SIZE) + if (oldFileSize == INVALID_FILE_SIZE) { throw int(GetLastError()); + } vector oldData; try { @@ -105,10 +110,12 @@ try { throw int(-1); } - if (!ReadFile(hTarget, oldData.data(), oldFileSize, &read, nullptr)) + if (!ReadFile(hTarget, oldData.data(), oldFileSize, &read, nullptr)) { throw int(GetLastError()); - if (read != oldFileSize) + } + if (read != oldFileSize) { throw int(-1); + } /* --------------------------------- * * patch to new file data */ @@ -116,22 +123,25 @@ try { 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)) + if (result != newsize || ZSTD_isError(result)) { throw int(-9); + } /* --------------------------------- * * write new file */ hTarget = nullptr; hTarget = CreateFile(targetFile, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); - if (!hTarget.Valid()) + if (!hTarget.Valid()) { throw int(GetLastError()); + } DWORD written; success = !!WriteFile(hTarget, newData.data(), (DWORD)newsize, &written, nullptr); - if (!success || written != newsize) + if (!success || written != newsize) { throw int(GetLastError()); + } return 0; diff --git a/frontend/updater/updater.cpp b/frontend/updater/updater.cpp index 64f2e00a480678..fcb1248b2ddd6f 100644 --- a/frontend/updater/updater.cpp +++ b/frontend/updater/updater.cpp @@ -91,16 +91,19 @@ static bool IsVSRedistOutdated() const wchar_t vc_dll[] = L"msvcp140"; auto size = GetFileVersionInfoSize(vc_dll, nullptr); - if (!size) + if (!size) { return true; + } buf.resize(size); - if (!GetFileVersionInfo(vc_dll, 0, size, buf.data())) + if (!GetFileVersionInfo(vc_dll, 0, size, buf.data())) { return true; + } bool success = VerQueryValue(buf.data(), L"\\", reinterpret_cast(&info), &len); - if (!success || !info || !len) + if (!success || !info || !len) { return true; + } return LOWORD(info->dwFileVersionMS) < 40; } @@ -114,8 +117,9 @@ static void Log(const wchar_t *fmt, ...) int len = _vscwprintf(fmt, argptr); va_end(argptr); - if (len <= 0) + if (len <= 0) { return; + } /* Using len + 1 for null terminator, which gets chopped off below */ wstring str(len + 1, L'\0'); @@ -124,8 +128,9 @@ static void Log(const wchar_t *fmt, ...) len = _vsnwprintf_s(str.data(), len + 1, _TRUNCATE, fmt, argptr); va_end(argptr); - if (len <= 0) + if (len <= 0) { return; + } /* Append newline and send to main window as a PostMessage to * avoid blocking worker threads with UI messages */ @@ -159,28 +164,34 @@ try { hSrc = CreateFile(src, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, FILE_FLAG_SEQUENTIAL_SCAN, nullptr); - if (!hSrc.Valid()) + if (!hSrc.Valid()) { throw LastError(); + } hDest = CreateFile(dest, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); - if (!hDest.Valid()) + if (!hDest.Valid()) { throw LastError(); + } BYTE buf[65536]; DWORD read, wrote; for (;;) { - if (!ReadFile(hSrc, buf, sizeof(buf), &read, nullptr)) + if (!ReadFile(hSrc, buf, sizeof(buf), &read, nullptr)) { throw LastError(); + } - if (read == 0) + if (read == 0) { break; + } - if (!WriteFile(hDest, buf, read, &wrote, nullptr)) + if (!WriteFile(hDest, buf, read, &wrote, nullptr)) { throw LastError(); + } - if (wrote != read) + if (wrote != read) { return false; + } } return true; @@ -193,12 +204,14 @@ try { static void MyDeleteFile(const wstring &filename) { /* Try straightforward delete first */ - if (DeleteFile(filename.c_str())) + if (DeleteFile(filename.c_str())) { return; + } DWORD err = GetLastError(); - if (err == ERROR_FILE_NOT_FOUND) + if (err == ERROR_FILE_NOT_FOUND) { return; + } /* If all else fails, schedule the file to be deleted on reboot */ MoveFileEx(filename.c_str(), nullptr, MOVEFILE_DELAY_UNTIL_REBOOT); @@ -208,18 +221,22 @@ static bool IsSafeFilename(const wchar_t *path) { const wchar_t *p = path; - if (!*p) + if (!*p) { return false; + } - if (wcsstr(path, L"..")) + if (wcsstr(path, L"..")) { return false; + } - if (*p == '/') + if (*p == '/') { return false; + } while (*p) { - if (!isalnum(*p) && *p != '.' && *p != '/' && *p != '_' && *p != '-') + if (!isalnum(*p) && *p != '.' && *p != '/' && *p != '_' && *p != '-') { return false; + } p++; } @@ -258,12 +275,14 @@ static bool QuickWriteFile(const wchar_t *file, const void *data, size_t size) try { WinHandle handle = CreateFile(file, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, 0, nullptr); - if (handle == INVALID_HANDLE_VALUE) + if (handle == INVALID_HANDLE_VALUE) { throw LastError(); + } DWORD written; - if (!WriteFile(handle, data, (DWORD)size, &written, nullptr)) + if (!WriteFile(handle, data, (DWORD)size, &written, nullptr)) { throw LastError(); + } return true; @@ -351,8 +370,9 @@ struct deletion_t { void UndoRename() const { - if (!deleteMeFilename.empty()) + if (!deleteMeFilename.empty()) { MoveFile(deleteMeFilename.c_str(), originalFilename.c_str()); + } } }; @@ -364,11 +384,13 @@ static mutex updateMutex; static inline void CleanupPartialUpdates() { - for (update_t &update : updates) + for (update_t &update : updates) { update.CleanPartialUpdate(); + } - for (deletion_t &deletion : deletions) + for (deletion_t &deletion : deletions) { deletion.UndoRename(); + } } /* ----------------------------------------------------------------------- */ @@ -387,10 +409,12 @@ 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()); - if (result != size) + if (result != size) { return -9; - if (ZSTD_isError(result)) + } + if (ZSTD_isError(result)) { return -10; + } return 0; } @@ -440,8 +464,9 @@ bool DownloadWorkerThread() return false; } - if (update.state != STATE_PENDING_DOWNLOAD) + if (update.state != STATE_PENDING_DOWNLOAD) { continue; + } update.state = STATE_DOWNLOADING; @@ -554,22 +579,26 @@ static inline DWORD WaitIfOBS(DWORD id, const wchar_t *expected) *path = 0; WinHandle proc = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | SYNCHRONIZE, false, id); - if (!proc.Valid()) + if (!proc.Valid()) { return WAITIFOBS_WRONG_PROCESS; + } - if (!QueryFullProcessImageNameW(proc, 0, path, &path_len)) + if (!QueryFullProcessImageNameW(proc, 0, path, &path_len)) { return WAITIFOBS_WRONG_PROCESS; + } // check it's actually our exe that's running size_t len = wcslen(obs_base_directory); - if (wcsncmp(path, obs_base_directory, len) != 0) + if (wcsncmp(path, obs_base_directory, len) != 0) { return WAITIFOBS_WRONG_PROCESS; + } name = wcsrchr(path, L'\\'); - if (name) + if (name) { name += 1; - else + } else { name = path; + } if (_wcsnicmp(name, expected, 5) == 0) { HANDLE hWait[2]; @@ -579,8 +608,9 @@ static inline DWORD WaitIfOBS(DWORD id, const wchar_t *expected) Log(L"Waiting for OBS PID %d at %s...", id, path); int i = WaitForMultipleObjects(2, hWait, false, INFINITE); - if (i == WAIT_OBJECT_0 + 1) + if (i == WAIT_OBJECT_0 + 1) { return WAITIFOBS_CANCELLED; + } return WAITIFOBS_SUCCESS; } @@ -640,8 +670,9 @@ void HasherThread() while (true) { ulock.lock(); - if (hashQueue.empty()) + if (hashQueue.empty()) { return; + } auto fileName = hashQueue.front(); hashQueue.pop(); @@ -650,11 +681,13 @@ void HasherThread() wchar_t updateFileName[MAX_PATH]; - if (!UTF8ToWideBuf(updateFileName, fileName.c_str())) + if (!UTF8ToWideBuf(updateFileName, fileName.c_str())) { continue; + } - if (!IsSafeFilename(updateFileName)) + if (!IsSafeFilename(updateFileName)) { continue; + } B2Hash existingHash; if (CalculateFileHash(updateFileName, existingHash)) { @@ -698,16 +731,18 @@ static inline bool FileExists(const wchar_t *path) HANDLE hFind; hFind = FindFirstFileW(path, &wfd); - if (hFind != INVALID_HANDLE_VALUE) + if (hFind != INVALID_HANDLE_VALUE) { FindClose(hFind); + } return hFind != INVALID_HANDLE_VALUE; } static bool NonCorePackageInstalled(const char *name) { - if (strcmp(name, "obs-browser") == 0) + if (strcmp(name, "obs-browser") == 0) { return FileExists(L"obs-plugins\\64bit\\obs-browser.dll"); + } return false; } @@ -715,29 +750,34 @@ static bool NonCorePackageInstalled(const char *name) static bool AddPackageUpdateFiles(const Package &package, const wchar_t *branch) { wchar_t wPackageName[512]; - if (!UTF8ToWideBuf(wPackageName, package.name.c_str())) + 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) { - if (file.hash.size() != kBlake2StrLength) + if (file.hash.size() != kBlake2StrLength) { continue; + } /* The download hash may not exist if a file is uncompressed */ bool compressed = false; - if (file.compressed_hash.size() == kBlake2StrLength) + if (file.compressed_hash.size() == kBlake2StrLength) { compressed = true; + } /* convert strings to wide */ wchar_t sourceURL[1024]; wchar_t updateFileName[MAX_PATH]; - if (!UTF8ToWideBuf(updateFileName, file.name.c_str())) + if (!UTF8ToWideBuf(updateFileName, file.name.c_str())) { continue; + } /* make sure paths are safe */ @@ -762,8 +802,9 @@ static bool AddPackageUpdateFiles(const Package &package, const wchar_t *branch) if (hashes.count(file.name)) { localFileHash = hashes[file.name]; - if (localFileHash == updateHash) + if (localFileHash == updateHash) { continue; + } has_hash = true; } @@ -787,8 +828,9 @@ static bool AddPackageUpdateFiles(const Package &package, const wchar_t *branch) } update.has_hash = has_hash; - if (has_hash) + if (has_hash) { update.my_hash = localFileHash; + } updates.push_back(std::move(update)); @@ -802,18 +844,21 @@ static void AddPackageRemovedFiles(const Package &package) { for (const string &filename : package.removed_files) { wchar_t removedFileName[MAX_PATH]; - if (!UTF8ToWideBuf(removedFileName, filename.c_str())) + if (!UTF8ToWideBuf(removedFileName, filename.c_str())) { continue; + } /* Ensure paths are safe, also check if file exists */ - if (!IsSafeFilename(removedFileName)) + if (!IsSafeFilename(removedFileName)) { continue; + } /* Technically GetFileAttributes can fail for other reasons, * so double-check by also checking the last error */ 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; + } } deletion_t deletion; @@ -836,8 +881,9 @@ static bool RenameRemovedFile(deletion_t &deletion) blake2b(hash.data(), hash.size(), junk, sizeof(junk), nullptr, 0); HashToString(hash, temp); - if (!UTF8ToWideBuf(randomStr, temp.c_str())) + if (!UTF8ToWideBuf(randomStr, temp.c_str())) { return false; + } randomStr[8] = 0; @@ -861,25 +907,31 @@ static bool UpdateWithPatchIfAvailable(const PatchResponse &patch) wchar_t widePatchableFilename[MAX_PATH]; wchar_t sourceURL[1024]; - if (patch.source.compare(0, kCDNUrl.size(), kCDNUrl) != 0) + if (patch.source.compare(0, kCDNUrl.size(), kCDNUrl) != 0) { return false; + } - if (patch.name.find('/') == string::npos) + if (patch.name.find('/') == string::npos) { return false; + } string patchPackageName(patch.name, 0, patch.name.find('/')); string fileName(patch.name, patch.name.find('/') + 1); - if (!UTF8ToWideBuf(widePatchableFilename, fileName.c_str())) + if (!UTF8ToWideBuf(widePatchableFilename, fileName.c_str())) { return false; - if (!UTF8ToWideBuf(sourceURL, patch.source.c_str())) + } + if (!UTF8ToWideBuf(sourceURL, patch.source.c_str())) { return false; + } for (update_t &update : updates) { - if (update.packageName != patchPackageName) + if (update.packageName != patchPackageName) { continue; - if (update.outputPath != widePatchableFilename) + } + if (update.outputPath != widePatchableFilename) { continue; + } update.patchable = true; @@ -911,8 +963,9 @@ static bool MoveInUseFileAway(const update_t &file) blake2b(hash.data(), hash.size(), junk, sizeof(junk), nullptr, 0); HashToString(hash, temp); - if (!UTF8ToWideBuf(randomStr, temp.c_str())) + if (!UTF8ToWideBuf(randomStr, temp.c_str())) { return false; + } randomStr[8] = 0; @@ -956,8 +1009,9 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) if (curFileName) { curFileName[0] = '\0'; curFileName++; - } else + } else { curFileName = baseName; + } /* Backup the existing file in case a rollback is needed */ StringCbCopy(oldFileRenamedPath, sizeof(oldFileRenamedPath), file.outputPath.c_str()); @@ -967,14 +1021,15 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) DWORD err = GetLastError(); int is_sharing_violation = (err == ERROR_SHARING_VIOLATION || err == ERROR_USER_MAPPED_FILE); - if (is_sharing_violation) + if (is_sharing_violation) { Status(L"Update failed: %s is still in use. " L"Close all programs and try again.", curFileName); - else + } else { Status(L"Update failed: Couldn't backup %s " L"(error %d)", curFileName, GetLastError()); + } return false; } @@ -1028,8 +1083,9 @@ static bool UpdateFile(ZSTD_DCtx *ctx, update_t &file) if (!already_tried_to_move) { already_tried_to_move = true; - if (MoveInUseFileAway(file)) + if (MoveInUseFileAway(file)) { goto retryAfterMovingFile; + } } Status(L"Update failed: %s is still in use. " @@ -1092,10 +1148,12 @@ static bool UpdateWorker() while (true) { ulock.lock(); - if (updateThreadFailed) + if (updateThreadFailed) { return false; - if (updateQueue.empty()) + } + if (updateQueue.empty()) { break; + } auto update = updateQueue.front(); updateQueue.pop(); @@ -1120,8 +1178,9 @@ static bool UpdateWorker() static bool RunUpdateWorkers(int num) try { - for (update_t &update : updates) + for (update_t &update : updates) { updateQueue.emplace(update); + } vector> thread_success_results; thread_success_results.resize(num); @@ -1274,12 +1333,14 @@ static void UpdateRegistryVersion(const Manifest &manifest) manifest.version_minor, manifest.version_patch); } - if (formattedLen <= 0) + if (formattedLen <= 0) { return; + } res = RegOpenKeyExA(HKEY_LOCAL_MACHINE, regKey, 0, KEY_WRITE | KEY_WOW64_32KEY, &key); - if (res != ERROR_SUCCESS) + if (res != ERROR_SUCCESS) { return; + } RegSetValueExA(key, "DisplayVersion", 0, REG_SZ, (const BYTE *)version, formattedLen + 1); RegCloseKey(key); @@ -1310,17 +1371,20 @@ static bool Update(wchar_t *cmdLine) int i = WaitForMultipleObjects(2, hWait, false, INFINITE); - if (i == WAIT_OBJECT_0) + if (i == WAIT_OBJECT_0) { ReleaseMutex(hObsUpdateMutex); + } CloseHandle(hObsUpdateMutex); - if (i == WAIT_OBJECT_0 + 1) + if (i == WAIT_OBJECT_0 + 1) { return false; + } } - if (!WaitForOBS()) + if (!WaitForOBS()) { return false; + } /* ------------------------------------- * * Init crypt stuff */ @@ -1500,12 +1564,14 @@ static bool Update(wchar_t *cmdLine) PatchesRequest files; for (update_t &update : updates) { - if (!update.has_hash) + if (!update.has_hash) { continue; + } char outputPath[MAX_PATH]; - if (!WideToUTF8Buf(outputPath, update.outputPath.c_str())) + if (!WideToUTF8Buf(outputPath, update.outputPath.c_str())) { continue; + } string hash_string; HashToString(update.my_hash, hash_string); @@ -1535,22 +1601,25 @@ static bool Update(wchar_t *cmdLine) size_t result = ZSTD_compress(compressedJson.data(), compressedJson.size(), post_body.data(), post_body.size(), ZSTD_CLEVEL_DEFAULT); - if (ZSTD_isError(result)) + if (ZSTD_isError(result)) { return false; + } compressedJson.resize(result); wstring manifestUrl(kPatchManifestURL); - if (branch != L"stable") + if (branch != L"stable") { manifestUrl += L"?branch=" + branch; + } int responseCode; bool success = !!HTTPPostData(manifestUrl.c_str(), (BYTE *)compressedJson.data(), (int)compressedJson.size(), L"Accept-Encoding: gzip", &responseCode, newManifest); - if (!success) + if (!success) { return false; + } if (responseCode != 200) { Status(L"Update failed: HTTP/%d while trying to " @@ -1609,13 +1678,15 @@ static bool Update(wchar_t *cmdLine) * avoiding concurrent map mutation from multiple threads. */ download_data.reserve(downloadHashes.size()); for (update_t &update : updates) { - if (update.state == STATE_PENDING_DOWNLOAD) + if (update.state == STATE_PENDING_DOWNLOAD) { download_data.try_emplace(update.downloadHash); + } } Status(L"Downloading updates..."); - if (!RunDownloadWorkers(4)) + if (!RunDownloadWorkers(4)) { return false; + } if ((size_t)completedUpdates != updates.size()) { Status(L"Update failed to download all files."); @@ -1629,8 +1700,9 @@ static bool Update(wchar_t *cmdLine) lastPosition = 0; Status(L"Installing updates..."); - if (!RunUpdateWorkers(4)) + if (!RunUpdateWorkers(4)) { return false; + } for (deletion_t &deletion : deletions) { if (!RenameRemovedFile(deletion)) { @@ -1716,13 +1788,15 @@ static bool Update(wchar_t *cmdLine) /* If we get here, all updates installed successfully so we can purge * the old versions */ for (update_t &update : updates) { - if (!update.previousFile.empty()) + if (!update.previousFile.empty()) { DeleteFile(update.previousFile.c_str()); + } } /* Delete all removed files mentioned in the manifest */ - for (deletion_t &deletion : deletions) + for (deletion_t &deletion : deletions) { MyDeleteFile(deletion.deleteMeFilename); + } SendDlgItemMessage(hwndMain, IDC_PROGRESS, PBM_SETPOS, 100, 0); @@ -1742,18 +1816,21 @@ static DWORD WINAPI UpdateThread(void *arg) * partially installed updates */ CleanupPartialUpdates(); - if (tempPath[0]) + if (tempPath[0]) { RemoveDirectory(tempPath); + } - if (WaitForSingleObject(cancelRequested, 0) == WAIT_OBJECT_0) + if (WaitForSingleObject(cancelRequested, 0) == WAIT_OBJECT_0) { Status(L"Update aborted."); + } HWND hProgress = GetDlgItem(hwndMain, IDC_PROGRESS); /* Even a no-op style change apparently resets the progress bar */ LONG_PTR style = GetWindowLongPtr(hProgress, GWL_STYLE); - if (style & PBS_MARQUEE) + if (style & PBS_MARQUEE) { SetWindowLongPtr(hProgress, GWL_STYLE, style & ~PBS_MARQUEE); + } SendMessage(hProgress, PBM_SETSTATE, PBST_ERROR, 0); @@ -1762,12 +1839,14 @@ static DWORD WINAPI UpdateThread(void *arg) updateFailed = true; } else { - if (tempPath[0]) + if (tempPath[0]) { RemoveDirectory(tempPath); + } } - if (bExiting) + if (bExiting) { ExitProcess(success); + } return 0; } @@ -1807,8 +1886,9 @@ static void LaunchOBS(LPWSTR lpCmdLine) execInfo.lpDirectory = newCwd; execInfo.nShow = SW_SHOWNORMAL; - if (lpCmdLine[0]) + if (lpCmdLine[0]) { execInfo.lpParameters = lpCmdLine; + } ShellExecuteEx(&execInfo); } @@ -1816,8 +1896,9 @@ static void LaunchOBS(LPWSTR lpCmdLine) static void ToggleLogVisibility() { HWND hwndLog = GetDlgItem(hwndMain, IDC_LOG); - if (!hwndLog) + if (!hwndLog) { return; + } logVisible = !logVisible; @@ -1874,8 +1955,9 @@ static INT_PTR CALLBACK UpdateDialogProc(HWND hwnd, UINT message, WPARAM wParam, /* Propagate the main window font or it looks ugly */ HFONT hFont = (HFONT)SendMessage(hwnd, WM_GETFONT, 0, 0); - if (hFont) + if (hFont) { SendMessage(hwndLog, WM_SETFONT, (WPARAM)hFont, FALSE); + } return true; } @@ -1885,18 +1967,20 @@ static INT_PTR CALLBACK UpdateDialogProc(HWND hwnd, UINT message, WPARAM wParam, if (HIWORD(wParam) == BN_CLICKED) { DWORD result = WaitForSingleObject(updateThread, 0); if (result == WAIT_OBJECT_0) { - if (updateFailed) + if (updateFailed) { PostQuitMessage(0); - else + } else { PostQuitMessage(1); + } } else { EnableWindow((HWND)lParam, false); CancelUpdate(false); } } } else if (LOWORD(wParam) == IDC_LOGBUTTON) { - if (HIWORD(wParam) == BN_CLICKED) + if (HIWORD(wParam) == BN_CLICKED) { ToggleLogVisibility(); + } } return true; diff --git a/frontend/utility/AdvancedOutput.cpp b/frontend/utility/AdvancedOutput.cpp index aff3ad6231072b..f4eedb5feecfe6 100644 --- a/frontend/utility/AdvancedOutput.cpp +++ b/frontend/utility/AdvancedOutput.cpp @@ -38,8 +38,9 @@ static void ApplyEncoderDefaults(OBSData &settings, const obs_encoder_t *encoder OBSData dataRet = obs_encoder_get_defaults(encoder); obs_data_release(dataRet); - if (!!settings) + if (!!settings) { obs_data_apply(dataRet, settings); + } settings = std::move(dataRet); } @@ -79,24 +80,27 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) if (ffmpegOutput) { fileOutput = obs_output_create("ffmpeg_output", "adv_ffmpeg_output", nullptr, nullptr); - if (!fileOutput) + if (!fileOutput) { throw "Failed to create recording FFmpeg output " "(advanced output)"; + } } else { bool useReplayBuffer = config_get_bool(main->Config(), "AdvOut", "RecRB"); if (useReplayBuffer) { OBSDataAutoRelease hotkey; const char *str = config_get_string(main->Config(), "Hotkeys", "ReplayBuffer"); - if (str) + if (str) { hotkey = obs_data_create_from_json(str); - else + } else { hotkey = nullptr; + } replayBuffer = obs_output_create("replay_buffer", Str("ReplayBuffer"), nullptr, hotkey); - if (!replayBuffer) + if (!replayBuffer) { throw "Failed to create replay buffer output " "(simple output)"; + } signal_handler_t *signal = obs_output_get_signal_handler(replayBuffer); @@ -107,30 +111,34 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) } const char *mux = "ffmpeg_muxer"; - if (strcmp(recFormat, "hybrid_mp4") == 0) + if (strcmp(recFormat, "hybrid_mp4") == 0) { mux = "mp4_output"; - else if (strcmp(recFormat, "hybrid_mov") == 0) + } else if (strcmp(recFormat, "hybrid_mov") == 0) { mux = "mov_output"; + } fileOutput = obs_output_create(mux, "adv_file_output", nullptr, nullptr); - if (!fileOutput) + if (!fileOutput) { throw "Failed to create recording output " "(advanced output)"; + } if (!useStreamEncoder) { videoRecording = obs_video_encoder_create(recordEncoder, "advanced_video_recording", recordEncSettings, nullptr); - if (!videoRecording) + if (!videoRecording) { throw "Failed to create recording video " "encoder (advanced output)"; + } obs_encoder_release(videoRecording); } } videoStreaming = obs_video_encoder_create(streamEncoder, "advanced_video_stream", streamEncSettings, nullptr); - if (!videoStreaming) + if (!videoStreaming) { throw "Failed to create streaming video encoder " "(advanced output)"; + } obs_encoder_release(videoStreaming); if (whipSimulcastEncoders != nullptr) { whipSimulcastEncoders->Create(streamEncoder, config_get_int(main->Config(), "AdvOut", "RescaleFilter"), @@ -141,8 +149,9 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) const char *rate_control = obs_data_get_string(useStreamEncoder ? streamEncSettings : recordEncSettings, "rate_control"); - if (!rate_control) + if (!rate_control) { rate_control = ""; + } usesBitrate = astrcmpi(rate_control, "CBR") == 0 || astrcmpi(rate_control, "VBR") == 0 || astrcmpi(rate_control, "ABR") == 0; @@ -175,17 +184,19 @@ AdvancedOutput::AdvancedOutput(OBSBasic *main_) : BasicOutputHandler(main_) int streamTrackIndex = config_get_int(main->Config(), "AdvOut", "TrackIndex") - 1; streamAudioEnc = obs_audio_encoder_create(streamAudioEncoder, "adv_stream_audio", nullptr, streamTrackIndex, nullptr); - if (!streamAudioEnc) + 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); - if (!streamArchiveEnc) + 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); @@ -230,14 +241,16 @@ void AdvancedOutput::UpdateStreamSettings() } int enforced_keyint_sec = (int)obs_data_get_int(settings, "keyint_sec"); - if (keyint_sec != 0 && keyint_sec < enforced_keyint_sec) + if (keyint_sec != 0 && keyint_sec < enforced_keyint_sec) { obs_data_set_int(settings, "keyint_sec", keyint_sec); + } } else { blog(LOG_WARNING, "User is ignoring service settings."); } - if (dynBitrate && strstr(streamEncoder, "nvenc") != nullptr) + if (dynBitrate && strstr(streamEncoder, "nvenc") != nullptr) { obs_data_set_bool(settings, "lookahead", false); + } video_t *video = obs_get_video(); enum video_format format = video_output_get_format(video); @@ -267,8 +280,9 @@ inline void AdvancedOutput::UpdateRecordingSettings() void AdvancedOutput::Update() { UpdateStreamSettings(); - if (!useStreamEncoder && !ffmpegOutput) + if (!useStreamEncoder && !ffmpegOutput) { UpdateRecordingSettings(); + } UpdateAudioSettings(); } @@ -277,8 +291,9 @@ inline bool AdvancedOutput::allowsMultiTrack() const char *protocol = nullptr; obs_service_t *service_obj = main->GetService(); protocol = obs_service_get_protocol(service_obj); - if (!protocol) + if (!protocol) { return false; + } return astrcmpi_n(protocol, SRT_PROTOCOL, strlen(SRT_PROTOCOL)) == 0 || astrcmpi_n(protocol, RIST_PROTOCOL, strlen(RIST_PROTOCOL)) == 0; } @@ -335,10 +350,11 @@ inline void AdvancedOutput::SetupRecording() bool is_fragmented = strncmp(recFormat, "fragmented", 10) == 0; bool flv = strcmp(recFormat, "flv") == 0; - if (flv) + if (flv) { tracks = config_get_int(main->Config(), "AdvOut", "FLVTrack"); - else + } else { tracks = config_get_int(main->Config(), "AdvOut", "RecTracks"); + } OBSDataAutoRelease settings = obs_data_create(); unsigned int cx = 0; @@ -349,13 +365,15 @@ inline void AdvancedOutput::SetupRecording() * longer possible to select such a configuration in settings, but legacy * configurations might still have this configured and we don't want to * just break them. */ - if (tracks == 0) + if (tracks == 0) { tracks = config_get_int(main->Config(), "AdvOut", "TrackIndex"); + } if (useStreamEncoder) { obs_output_set_video_encoder(fileOutput, videoStreaming); - if (replayBuffer) + if (replayBuffer) { obs_output_set_video_encoder(replayBuffer, videoStreaming); + } } else { if (rescaleFilter != OBS_SCALE_DISABLE && rescaleRes && *rescaleRes) { if (sscanf(rescaleRes, "%ux%u", &cx, &cy) != 2) { @@ -367,24 +385,27 @@ inline void AdvancedOutput::SetupRecording() obs_encoder_set_scaled_size(videoRecording, cx, cy); obs_encoder_set_gpu_scale_type(videoRecording, (obs_scale_type)rescaleFilter); obs_output_set_video_encoder(fileOutput, videoRecording); - if (replayBuffer) + if (replayBuffer) { 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); - if (replayBuffer) + if (replayBuffer) { 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); - if (replayBuffer) + if (replayBuffer) { obs_output_set_audio_encoder(replayBuffer, recordTrack[tracks - 1], idx); + } } // Use fragmented MOV/MP4 if user has not already specified custom movflags @@ -396,16 +417,18 @@ inline void AdvancedOutput::SetupRecording() } obs_data_set_string(settings, "muxer_settings", mux_frag.c_str()); } else { - if (is_fragmented) + if (is_fragmented) { blog(LOG_WARNING, "User enabled fragmented recording, " "but custom muxer settings contained movflags."); + } obs_data_set_string(settings, "muxer_settings", mux); } obs_data_set_string(settings, "path", path); obs_output_update(fileOutput, settings); - if (replayBuffer) + if (replayBuffer) { obs_output_update(replayBuffer, settings); + } } inline void AdvancedOutput::SetupFFmpeg() @@ -519,15 +542,18 @@ inline void AdvancedOutput::UpdateAudioSettings() int bitrate = (int)obs_data_get_int(settings[i], "bitrate"); obs_service_apply_encoder_settings(main->GetService(), nullptr, settings[i]); - if (!enforceBitrate) + if (!enforceBitrate) { obs_data_set_int(settings[i], "bitrate", bitrate); + } } } - if (track == streamTrackIndex) + if (track == streamTrackIndex) { obs_encoder_update(streamAudioEnc, settings[i]); - if (track == vodTrackIndex) + } + if (track == vodTrackIndex) { obs_encoder_update(streamArchiveEnc, settings[i]); + } } else { obs_encoder_update(streamTrack[i], settings[i]); } @@ -537,8 +563,9 @@ inline void AdvancedOutput::UpdateAudioSettings() void AdvancedOutput::SetupOutputs() { obs_encoder_set_video(videoStreaming, obs_get_video()); - if (videoRecording) + if (videoRecording) { obs_encoder_set_video(videoRecording, obs_get_video()); + } for (size_t i = 0; i < MAX_AUDIO_MIXES; i++) { obs_encoder_set_audio(streamTrack[i], obs_get_audio()); obs_encoder_set_audio(recordTrack[i], obs_get_audio()); @@ -548,10 +575,11 @@ void AdvancedOutput::SetupOutputs() SetupStreaming(); - if (ffmpegOutput) + if (ffmpegOutput) { SetupFFmpeg(); - else + } else { SetupRecording(); + } } int AdvancedOutput::GetAudioBitrate(size_t i, const char *id) const @@ -576,21 +604,24 @@ inline std::optional AdvancedOutput::VodTrackMixerIdx(obs_service_t *ser } else { OBSDataAutoRelease settings = obs_service_get_settings(service); const char *service = obs_data_get_string(settings, "service"); - if (!ServiceSupportsVodTrack(service)) + if (!ServiceSupportsVodTrack(service)) { vodTrackEnabled = false; + } } - if (vodTrackEnabled && streamTrackIndex != vodTrackIndex) + if (vodTrackEnabled && streamTrackIndex != vodTrackIndex) { return {vodTrackIndex - 1}; + } return std::nullopt; } inline void AdvancedOutput::SetupVodTrack(obs_service_t *service) { - if (VodTrackMixerIdx(service).has_value()) + if (VodTrackMixerIdx(service).has_value()) { obs_output_set_audio_encoder(streamOutput, streamArchiveEnc, 1); - else + } else { clear_archive_encoder(streamOutput, ADV_ARCHIVE_NAME); + } } std::shared_future AdvancedOutput::SetupStreaming(obs_service_t *service, @@ -606,12 +637,14 @@ std::shared_future AdvancedOutput::SetupStreaming(obs_service_t *service, UpdateAudioSettings(); - if (!Active()) + if (!Active()) { SetupOutputs(); + } Auth *auth = main->GetAuth(); - if (auth) + if (auth) { auth->OnStreamConfig(); + } /* --------------------- */ @@ -626,8 +659,9 @@ std::shared_future AdvancedOutput::SetupStreaming(obs_service_t *service, auto handle_multitrack_video_result = [this, type = std::string{type}, is_multitrack_output, multiTrackAudioMixes](std::optional multitrackVideoResult) { - if (multitrackVideoResult.has_value()) + if (multitrackVideoResult.has_value()) { return multitrackVideoResult.value(); + } /* XXX: this is messy and disgusting and should be refactored */ if (outputType != type) { @@ -710,8 +744,9 @@ 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; + } } OBSDataAutoRelease settings = obs_data_create(); @@ -727,8 +762,9 @@ bool AdvancedOutput::StartStreaming(obs_service_t *service) obs_output_update(streamOutput, settings); - if (!reconnect) + if (!reconnect) { maxRetries = 0; + } obs_output_set_delay(streamOutput, useDelay ? delaySec : 0, preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0); @@ -737,20 +773,23 @@ bool AdvancedOutput::StartStreaming(obs_service_t *service) SetupVodTrack(service); } if (obs_output_start(streamOutput)) { - if (multitrackVideo && multitrackVideoActive) + if (multitrackVideo && multitrackVideoActive) { multitrackVideo->StartedStreaming(); + } return true; } - if (multitrackVideo && multitrackVideoActive) + if (multitrackVideo && multitrackVideoActive) { multitrackVideoActive = false; + } const char *error = obs_output_get_last_error(streamOutput); bool hasLastError = error && *error; - if (hasLastError) + if (hasLastError) { lastError = error; - else + } else { 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: " : "", @@ -780,8 +819,9 @@ bool AdvancedOutput::StartRecording() UpdateAudioSettings(); - if (!Active()) + if (!Active()) { SetupOutputs(); + } if (!ffmpegOutput || ffmpegRecording) { path = config_get_string(main->Config(), "AdvOut", ffmpegRecording ? "FFFilePath" : "RecFilePath"); @@ -823,10 +863,11 @@ bool AdvancedOutput::StartRecording() if (!obs_output_start(fileOutput)) { QString error_reason; const char *error = obs_output_get_last_error(fileOutput); - if (error) + if (error) { error_reason = QT_UTF8(error); - else + } else { error_reason = QTStr("Output.StartFailedGeneric"); + } QMessageBox::critical(main, QTStr("Output.StartRecordingFailed"), error_reason); return false; } @@ -847,16 +888,18 @@ bool AdvancedOutput::StartReplayBuffer() int rbSize; if (!useStreamEncoder) { - if (!ffmpegOutput) + if (!ffmpegOutput) { UpdateRecordingSettings(); + } } else if (!obs_output_active(StreamingOutput())) { UpdateStreamSettings(); } UpdateAudioSettings(); - if (!Active()) + if (!Active()) { SetupOutputs(); + } if (!ffmpegOutput || ffmpegRecording) { path = config_get_string(main->Config(), "AdvOut", ffmpegRecording ? "FFFilePath" : "RecFilePath"); @@ -888,10 +931,11 @@ bool AdvancedOutput::StartReplayBuffer() if (!obs_output_start(replayBuffer)) { QString error_reason; const char *error = obs_output_get_last_error(replayBuffer); - if (error) + if (error) { error_reason = QT_UTF8(error); - else + } else { error_reason = QTStr("Output.StartFailedGeneric"); + } QMessageBox::critical(main, QTStr("Output.StartReplayFailed"), error_reason); return false; } @@ -902,28 +946,31 @@ bool AdvancedOutput::StartReplayBuffer() void AdvancedOutput::StopStreaming(bool force) { auto output = StreamingOutput(); - if (force && output) + if (force && output) { obs_output_force_stop(output); - else if (multitrackVideo && multitrackVideoActive) + } else if (multitrackVideo && multitrackVideoActive) { multitrackVideo->StopStreaming(); - else + } else { obs_output_stop(output); + } } void AdvancedOutput::StopRecording(bool force) { - if (force) + if (force) { obs_output_force_stop(fileOutput); - else + } else { obs_output_stop(fileOutput); + } } void AdvancedOutput::StopReplayBuffer(bool force) { - if (force) + if (force) { obs_output_force_stop(replayBuffer); - else + } else { obs_output_stop(replayBuffer); + } } bool AdvancedOutput::StreamingActive() const diff --git a/frontend/utility/AutoUpdateThread.cpp b/frontend/utility/AutoUpdateThread.cpp index 26558eaeed6dc4..c666a2000764c8 100644 --- a/frontend/utility/AutoUpdateThread.cpp +++ b/frontend/utility/AutoUpdateThread.cpp @@ -54,9 +54,10 @@ try { json manifestContents = json::parse(manifest_data); Manifest manifest = manifestContents.get(); - if (manifest.version_major == 0 && manifest.commit.empty()) + if (manifest.version_major == 0 && manifest.commit.empty()) { throw strprintf("Invalid version number: %d.%d.%d", manifest.version_major, manifest.version_minor, manifest.version_patch); + } notes = manifest.notes; @@ -67,19 +68,21 @@ try { new_ver <<= 16; /* RC builds are shifted so that rc1 and beta1 versions do not result * in the same new_ver. */ - if (manifest.rc > 0) + if (manifest.rc > 0) { new_ver |= (uint64_t)manifest.rc << 8; - else if (manifest.beta > 0) + } else if (manifest.beta > 0) { new_ver |= (uint64_t)manifest.beta; + } updateVer = to_string(new_ver); /* When using a pre-release build or non-default branch we only check if * the manifest version is different, so that it can be rolled back. */ - if (branch != WIN_DEFAULT_BRANCH || isPreRelease) + if (branch != WIN_DEFAULT_BRANCH || isPreRelease) { *updatesAvailable = new_ver != currentVersion; - else + } else { *updatesAvailable = new_ver > currentVersion; + } } else { /* Test or nightly builds may not have a (valid) version number, * so compare commit hashes instead. */ @@ -99,13 +102,15 @@ try { bool GetBranchAndUrl(string &selectedBranch, string &manifestUrl) { const char *config_branch = config_get_string(App()->GetAppConfig(), "General", "UpdateBranch"); - if (!config_branch) + if (!config_branch) { return true; + } bool found = false; for (const UpdateBranch &branch : App()->GetBranches()) { - if (branch.name != config_branch) + if (branch.name != config_branch) { continue; + } /* A branch that is found but disabled will just silently fall back to * the default. But if the branch was removed entirely, the user should * be warned, so leave this false *only* if the branch was removed. */ @@ -183,8 +188,9 @@ try { /* ----------------------------------- * * 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 */ @@ -196,16 +202,18 @@ try { /* allow server to know if this was a manual update check in case * we want to allow people to bypass a configured rollout rate */ - if (manualUpdate) + if (manualUpdate) { extraHeaders.emplace_back("X-OBS2-ManualUpdate: 1"); + } /* ----------------------------------- * * get manifest from server */ text.clear(); if (!FetchAndVerifyFile("manifest", "obs-studio\\updates\\manifest.json", manifestUrl.c_str(), &text, - extraHeaders)) + extraHeaders)) { return; + } /* ----------------------------------- * * check manifest for update */ @@ -213,12 +221,14 @@ 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) + if (manualUpdate) { info(QTStr("Updater.NoUpdatesAvailable.Title"), QTStr("Updater.NoUpdatesAvailable.Text")); + } return; } else if (updatesAvailable && repairMode) { info(QTStr("Updater.RepairButUpdatesAvailable.Title"), QTStr("Updater.RepairButUpdatesAvailable.Text")); @@ -229,21 +239,24 @@ try { * skip this version if set to skip */ const char *skipUpdateVer = config_get_string(App()->GetAppConfig(), "General", "SkipUpdateVersion"); - if (!manualUpdate && !repairMode && skipUpdateVer && updateVer == skipUpdateVer) + 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; + } /* ----------------------------------- * * query user for update */ if (repairMode) { - if (!queryRepair()) + if (!queryRepair()) { return; + } } else { int queryResult = queryUpdate(manualUpdate, notes.c_str()); @@ -266,8 +279,9 @@ try { wchar_t cwd[MAX_PATH]; GetModuleFileNameW(nullptr, cwd, _countof(cwd) - 1); wchar_t *p = wcsrchr(cwd, '\\'); - if (p) + if (p) { *p = 0; + } /* ----------------------------------- * * execute updater */ @@ -276,8 +290,9 @@ try { BPtr wUpdateFilePath; size_t size = os_utf8_to_wcs_ptr(updateFilePath, 0, &wUpdateFilePath); - if (!size) + if (!size) { throw string("Could not convert updateFilePath to wide"); + } /* note, can't use CreateProcess to launch as admin. */ SHELLEXECUTEINFO execInfo = {}; @@ -286,13 +301,15 @@ try { execInfo.lpFile = wUpdateFilePath; string parameters; - if (branch != WIN_DEFAULT_BRANCH) + if (branch != WIN_DEFAULT_BRANCH) { parameters += "--branch=" + branch; + } obs_cmdline_args obs_args = obs_get_cmdline_args(); for (int idx = 1; idx < obs_args.argc; idx++) { - if (!parameters.empty()) + if (!parameters.empty()) { parameters += " "; + } parameters += obs_args.argv[idx]; } @@ -300,15 +317,17 @@ 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 (!parameters.empty()) + if (!parameters.empty()) { parameters += " "; + } parameters += "--portable"; } BPtr lpParameters; size = os_utf8_to_wcs_ptr(parameters.c_str(), 0, &lpParameters); - if (!size && !parameters.empty()) + if (!size && !parameters.empty()) { throw string("Could not convert parameters to wide"); + } execInfo.lpParameters = lpParameters; execInfo.lpDirectory = cwd; diff --git a/frontend/utility/BasicOutputHandler.cpp b/frontend/utility/BasicOutputHandler.cpp index 910867b33b1f42..827337b96a3fcd 100644 --- a/frontend/utility/BasicOutputHandler.cpp +++ b/frontend/utility/BasicOutputHandler.cpp @@ -27,8 +27,9 @@ void OBSStreamStarting(void *data, calldata_t *params) obs_output_t *obj = (obs_output_t *)calldata_ptr(params, "output"); int sec = (int)obs_output_get_active_delay(obj); - if (sec == 0) + if (sec == 0) { return; + } output->delayActive = true; QMetaObject::invokeMethod(output->main, "StreamDelayStarting", Q_ARG(int, sec)); @@ -40,10 +41,11 @@ void OBSStreamStopping(void *data, calldata_t *params) obs_output_t *obj = (obs_output_t *)calldata_ptr(params, "output"); int sec = (int)obs_output_get_active_delay(obj); - if (sec == 0) + if (sec == 0) { QMetaObject::invokeMethod(output->main, "StreamStopping"); - else + } else { QMetaObject::invokeMethod(output->main, "StreamDelayStopping", Q_ARG(int, sec)); + } } void OBSStartStreaming(void *data, calldata_t * /* params */) @@ -192,8 +194,9 @@ const char *GetStreamOutputType(const obs_service_t *service) /* Check if the service has a preferred output type */ output = obs_service_get_preferred_output_type(service); if (output) { - if ((obs_get_output_flags(output) & OBS_OUTPUT_SERVICE) != 0) + 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); } @@ -209,8 +212,9 @@ const char *GetStreamOutputType(const obs_service_t *service) /* If third-party protocol, use the first enumerated type */ obs_enum_output_types_with_protocol(protocol, &output, return_first_id); - if (output) + if (output) { return output; + } blog(LOG_WARNING, "No output compatible with the service '%s' is registered", obs_service_get_id(service)); @@ -234,37 +238,43 @@ BasicOutputHandler::BasicOutputHandler(OBSBasic *main_) : main(main_) (obs_data_has_user_value(settings, "multitrack_video_configuration_url") || strcmp(obs_service_get_id(service), "rtmp_custom") == 0); - if (multitrack_enabled) + if (multitrack_enabled) { multitrackVideo = make_unique(); + } - if (config_get_int(main->Config(), "Stream1", "WHIPSimulcastTotalLayers") > 1) + if (config_get_int(main->Config(), "Stream1", "WHIPSimulcastTotalLayers") > 1) { whipSimulcastEncoders = make_unique(); + } } extern void log_vcam_changed(const VCamConfig &config, bool starting); bool BasicOutputHandler::StartVirtualCam() { - if (!main->vcamEnabled) + if (!main->vcamEnabled) { return false; + } bool typeIsProgram = main->vcamConfig.type == VCamOutputType::ProgramView; - if (!virtualCamView && !typeIsProgram) + if (!virtualCamView && !typeIsProgram) { virtualCamView = obs_view_create(); + } UpdateVirtualCamOutputSource(); if (!virtualCamVideo) { virtualCamVideo = typeIsProgram ? obs_get_video() : obs_view_add(virtualCamView); - if (!virtualCamVideo) + if (!virtualCamVideo) { return false; + } } obs_output_set_media(virtualCam, virtualCamVideo, obs_get_audio()); - if (!Active()) + if (!Active()) { SetupOutputs(); + } bool success = obs_output_start(virtualCam); if (!success) { @@ -304,8 +314,9 @@ bool BasicOutputHandler::VirtualCamActive() const void BasicOutputHandler::UpdateVirtualCamOutputSource() { - if (!main->vcamEnabled || !virtualCamView) + if (!main->vcamEnabled || !virtualCamView) { return; + } OBSSourceAutoRelease source; @@ -328,8 +339,9 @@ void BasicOutputHandler::UpdateVirtualCamOutputSource() case VCamOutputType::SourceOutput: OBSSourceAutoRelease s = obs_get_source_by_name(main->vcamConfig.source.c_str()); - if (!vCamSourceScene) + if (!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)) { @@ -353,8 +365,9 @@ void BasicOutputHandler::UpdateVirtualCamOutputSource() } OBSSourceAutoRelease current = obs_view_get_source(virtualCamView, 0); - if (source != current) + if (source != current) { obs_view_set_source(virtualCamView, 0, source); + } } void BasicOutputHandler::DestroyVirtualCamView() @@ -376,8 +389,9 @@ void BasicOutputHandler::DestroyVirtualCamView() void BasicOutputHandler::DestroyVirtualCameraScene() { - if (!vCamSourceScene) + if (!vCamSourceScene) { return; + } obs_scene_release(vCamSourceScene); vCamSourceScene = nullptr; @@ -411,22 +425,25 @@ void clear_archive_encoder(obs_output_t *output, const char *expected_name) obs_encoder_release(last); } - if (clear) + if (clear) { obs_output_set_audio_encoder(output, nullptr, 1); + } } void BasicOutputHandler::SetupAutoRemux(const char *&container) { bool autoRemux = config_get_bool(main->Config(), "Video", "AutoRemux"); - if (autoRemux && strcmp(container, "mp4") == 0) + if (autoRemux && strcmp(container, "mp4") == 0) { container = "mkv"; + } } std::string BasicOutputHandler::GetRecordingFilename(const char *path, const char *container, bool noSpace, bool overwrite, const char *format, bool ffmpeg) { - if (!ffmpeg) + if (!ffmpeg) { SetupAutoRemux(container); + } string dst = GetOutputFilename(path, container, noSpace, overwrite, format); lastRecordingPath = dst; @@ -456,9 +473,10 @@ std::shared_future BasicOutputHandler::SetupMultitrackVideo(obs_service_t 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")); + } std::optional extraCanvasUUID; const char *uuid = config_get_string(main->Config(), "Stream1", "MultitrackExtraCanvas"); @@ -515,8 +533,9 @@ std::shared_future BasicOutputHandler::SetupMultitrackVideo(obs_service_t } multitrackVideoActive = false; - if (!error->ShowDialog(main, multitrack_video_name)) + if (!error->ShowDialog(main, multitrack_video_name)) { return continuation(false); + } return continuation(std::nullopt); } @@ -557,8 +576,9 @@ OBSDataAutoRelease BasicOutputHandler::GenerateMultitrackVideoStreamDumpConfig() { auto stream_dump_enabled = config_get_bool(main->Config(), "Stream1", "MultitrackVideoStreamDumpEnabled"); - if (!stream_dump_enabled) + 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"); diff --git a/frontend/utility/BasicOutputHandler.hpp b/frontend/utility/BasicOutputHandler.hpp index 29300792a3afb8..7710fd0af6f376 100644 --- a/frontend/utility/BasicOutputHandler.hpp +++ b/frontend/utility/BasicOutputHandler.hpp @@ -139,8 +139,9 @@ inline bool ServiceSupportsVodTrack(const char *service) static const char *vodTrackServices[] = {"Twitch"}; for (const char *vodTrackService : vodTrackServices) { - if (astrcmpi(vodTrackService, service) == 0) + if (astrcmpi(vodTrackService, service) == 0) { return true; + } } return false; diff --git a/frontend/utility/ExtraBrowsersDelegate.cpp b/frontend/utility/ExtraBrowsersDelegate.cpp index e984797fb409de..509295675cc535 100644 --- a/frontend/utility/ExtraBrowsersDelegate.cpp +++ b/frontend/utility/ExtraBrowsersDelegate.cpp @@ -30,8 +30,9 @@ void ExtraBrowsersDelegate::setEditorData(QWidget *editor, const QModelIndex &in bool ExtraBrowsersDelegate::eventFilter(QObject *object, QEvent *event) { QLineEdit *edit = qobject_cast(object); - if (!edit) + if (!edit) { return false; + } if (LineEditCanceled(event)) { RevertText(edit); diff --git a/frontend/utility/ExtraBrowsersModel.cpp b/frontend/utility/ExtraBrowsersModel.cpp index 5409c3c1939af5..cf82021109bc9e 100644 --- a/frontend/utility/ExtraBrowsersModel.cpp +++ b/frontend/utility/ExtraBrowsersModel.cpp @@ -43,8 +43,9 @@ QVariant ExtraBrowsersModel::data(const QModelIndex &index, int role) const int count = items.size(); bool validRole = role == Qt::DisplayRole || role == Qt::AccessibleTextRole; - if (!validRole) + if (!validRole) { return QVariant(); + } if (idx >= 0 && idx < count) { switch (column) { @@ -85,8 +86,9 @@ Qt::ItemFlags ExtraBrowsersModel::flags(const QModelIndex &index) const { Qt::ItemFlags flags = QAbstractTableModel::flags(index); - if (index.column() != (int)Column::Delete) + if (index.column() != (int)Column::Delete) { flags |= Qt::ItemIsEditable; + } return flags; } @@ -109,8 +111,9 @@ void ExtraBrowsersModel::AddDeleteButton(int idx) void ExtraBrowsersModel::CheckToAdd() { - if (newTitle.isEmpty() || newURL.isEmpty()) + if (newTitle.isEmpty() || newURL.isEmpty()) { return; + } int idx = items.size() + 1; beginInsertRows(QModelIndex(), idx, idx); @@ -201,8 +204,9 @@ void ExtraBrowsersModel::Apply() main->extraBrowserDocks.removeAt(idx); } - if (main->extraBrowserDocks.empty()) + if (main->extraBrowserDocks.empty()) { main->extraBrowserMenuDocksSeparator.clear(); + } deleted.clear(); @@ -249,6 +253,7 @@ void ExtraBrowsersModel::TabSelection(bool forward) void ExtraBrowsersModel::Init() { - for (int i = 0; i < items.count(); i++) + for (int i = 0; i < items.count(); i++) { AddDeleteButton(i); + } } diff --git a/frontend/utility/FFmpegCodec.cpp b/frontend/utility/FFmpegCodec.cpp index 0e385ae68a17b6..a57ab1d6e4d13e 100644 --- a/frontend/utility/FFmpegCodec.cpp +++ b/frontend/utility/FFmpegCodec.cpp @@ -31,8 +31,9 @@ vector GetFormatCodecs(const FFmpegFormat &format, bool ignore_comp while ((codec = av_codec_iterate(&i)) != nullptr) { // Not an encoding codec - if (!av_codec_is_encoder(codec)) + 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)) { continue; @@ -46,16 +47,19 @@ vector GetFormatCodecs(const FFmpegFormat &format, bool ignore_comp bool FFCodecAndFormatCompatible(const char *codec, const char *format) { - if (!codec || !format) + if (!codec || !format) { return false; + } const AVOutputFormat *output_format = av_guess_format(format, nullptr, nullptr); - if (!output_format) + if (!output_format) { return false; + } const AVCodecDescriptor *codec_desc = avcodec_descriptor_get_by_name(codec); - if (!codec_desc) + if (!codec_desc) { return false; + } return avformat_query_codec(output_format, codec_desc->id, FF_COMPLIANCE_NORMAL) == 1; } @@ -171,13 +175,15 @@ static const unordered_map> codec_compat = { bool ContainerSupportsCodec(const string &container, const string &codec) { auto iter = codec_compat.find(container); - if (iter == codec_compat.end()) + if (iter == codec_compat.end()) { return false; + } auto codecs = iter->second; // Assume everything is supported - if (codecs.empty()) + if (codecs.empty()) { return true; + } return codecs.count(codec) > 0; } diff --git a/frontend/utility/FFmpegCodec.hpp b/frontend/utility/FFmpegCodec.hpp index 27893fd8ef88d8..a1a1e76c4be417 100644 --- a/frontend/utility/FFmpegCodec.hpp +++ b/frontend/utility/FFmpegCodec.hpp @@ -60,8 +60,9 @@ struct FFmpegCodec { bool operator==(const FFmpegCodec &codec) const { - if (id != codec.id) + if (id != codec.id) { return false; + } return strequal(name, codec.name); } diff --git a/frontend/utility/FFmpegFormat.cpp b/frontend/utility/FFmpegFormat.cpp index 8d8c4e606798de..1f07ad42e3ddd8 100644 --- a/frontend/utility/FFmpegFormat.cpp +++ b/frontend/utility/FFmpegFormat.cpp @@ -22,8 +22,9 @@ using namespace std; static bool is_output_device(const AVClass *avclass) { - if (!avclass) + if (!avclass) { return false; + } switch (avclass->category) { case AV_CLASS_CATEGORY_DEVICE_VIDEO_OUTPUT: @@ -42,8 +43,9 @@ vector GetSupportedFormats() void *i = 0; while ((output_format = av_muxer_iterate(&i)) != nullptr) { - if (is_output_device(output_format->priv_class)) + if (is_output_device(output_format->priv_class)) { continue; + } formats.emplace_back(output_format); } @@ -54,11 +56,13 @@ vector GetSupportedFormats() FFmpegCodec FFmpegFormat::GetDefaultEncoder(FFmpegCodecType codec_type) const { const AVCodecID codec_id = codec_type == VIDEO ? video_codec : audio_codec; - if (codec_type == UNKNOWN || codec_id == AV_CODEC_ID_NONE) + if (codec_type == UNKNOWN || codec_id == AV_CODEC_ID_NONE) { return {}; + } - if (auto codec = avcodec_find_encoder(codec_id)) + if (auto codec = avcodec_find_encoder(codec_id)) { return {codec}; + } /* Fall back to using the format name as the encoder, * this works for some formats such as FLV. */ diff --git a/frontend/utility/FFmpegFormat.hpp b/frontend/utility/FFmpegFormat.hpp index 6c44bcd596d612..49e8f06b693c59 100644 --- a/frontend/utility/FFmpegFormat.hpp +++ b/frontend/utility/FFmpegFormat.hpp @@ -67,8 +67,9 @@ struct FFmpegFormat { bool operator==(const FFmpegFormat &format) const { - if (!strequal(name, format.name)) + if (!strequal(name, format.name)) { return false; + } return strequal(mime_type, format.mime_type); } diff --git a/frontend/utility/FFmpegShared.hpp b/frontend/utility/FFmpegShared.hpp index c0a3a573e2c028..608d37a421e047 100644 --- a/frontend/utility/FFmpegShared.hpp +++ b/frontend/utility/FFmpegShared.hpp @@ -28,14 +28,18 @@ enum FFmpegCodecType { AUDIO, VIDEO, UNKNOWN }; */ static bool strequal(const char *a, const char *b) { - if (!a && !b) + if (!a && !b) { return true; - if (!a && *b == 0) + } + if (!a && *b == 0) { return true; - if (!b && *a == 0) + } + if (!b && *a == 0) { return true; - if (!a || !b) + } + if (!a || !b) { return false; + } return strcmp(a, b) == 0; } diff --git a/frontend/utility/GoLiveAPI_CensoredJson.cpp b/frontend/utility/GoLiveAPI_CensoredJson.cpp index 539dc6de4f1cbf..bef836a395b9b2 100644 --- a/frontend/utility/GoLiveAPI_CensoredJson.cpp +++ b/frontend/utility/GoLiveAPI_CensoredJson.cpp @@ -67,8 +67,9 @@ using json = nlohmann::json; void censorRecurse(json &data) { - if (!data.is_structured()) + if (!data.is_structured()) { return; + } auto it = data.find("authentication"); if (it != data.end() && it->is_string()) { diff --git a/frontend/utility/GoLiveAPI_Network.cpp b/frontend/utility/GoLiveAPI_Network.cpp index 652996ccabd8e1..634dd0b6b3d1d8 100644 --- a/frontend/utility/GoLiveAPI_Network.cpp +++ b/frontend/utility/GoLiveAPI_Network.cpp @@ -22,12 +22,14 @@ void HandleGoLiveApiErrors(QWidget *parent, const json &raw_json, const GoLiveAp { using GoLiveApi::StatusResult; - if (!config.status) + if (!config.status) { return; + } auto &status = *config.status; - if (status.result == StatusResult::Success) + if (status.result == StatusResult::Success) { return; + } auto warn_continue = [&](QString message) { bool ret = false; @@ -44,8 +46,9 @@ void HandleGoLiveApiErrors(QWidget *parent, const json &raw_json, const GoLiveAp return mb.exec() == QMessageBox::StandardButton::No; }, BlockingConnectionTypeFor(parent), &ret); - if (ret) + if (ret) { throw MultitrackVideoError::cancel(); + } }; auto missing_html = [] { @@ -73,8 +76,9 @@ GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, const GoLiv json post_data_json = post_data; blog(LOG_INFO, "Go live POST data: %s", censoredJson(post_data_json).toUtf8().constData()); - if (url.isEmpty()) + if (url.isEmpty()) { throw MultitrackVideoError::critical(QTStr("FailedToStartStream.MissingConfigURL")); + } std::string encodeConfigText; std::string libraryError; @@ -89,9 +93,10 @@ GoLiveApi::Config DownloadGoLiveConfig(QWidget *parent, QString url, const GoLiv nullptr, // signature 5); // timeout in seconds - if (!encodeConfigDownloadedOk) + if (!encodeConfigDownloadedOk) { throw MultitrackVideoError::warning( 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()); diff --git a/frontend/utility/GoLiveAPI_PostData.cpp b/frontend/utility/GoLiveAPI_PostData.cpp index 02be6f28c42c22..ff8b57ac5f0e67 100644 --- a/frontend/utility/GoLiveAPI_PostData.cpp +++ b/frontend/utility/GoLiveAPI_PostData.cpp @@ -24,8 +24,9 @@ GoLiveApi::PostData constructGoLivePost(QString streamKey, const std::optionalGetAppConfig(), "General", "UpdateBranch"); - if (!config_branch) + if (!config_branch) { return true; + } bool found = false; for (const UpdateBranch &branch : App()->GetBranches()) { - if (branch.name != config_branch) + if (branch.name != config_branch) { continue; + } /* A branch that is found but disabled will just silently fall back to * the default. But if the branch was removed entirely, the user should * be warned, so leave this false *only* if the branch was removed. */ @@ -53,8 +55,9 @@ 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 */ diff --git a/frontend/utility/MissingFilesModel.cpp b/frontend/utility/MissingFilesModel.cpp index e2080ef8a77ccc..9061888342ba19 100644 --- a/frontend/utility/MissingFilesModel.cpp +++ b/frontend/utility/MissingFilesModel.cpp @@ -46,8 +46,9 @@ int MissingFilesModel::found() const int res = 0; for (int i = 0; i < files.length(); i++) { - if (files[i].state != Missing && files[i].state != Cleared) + if (files[i].state != Missing && files[i].state != Cleared) { res++; + } } return res; @@ -213,8 +214,9 @@ void MissingFilesModel::fileCheckLoop(const QString &path, bool skipPrompt, int os_dir_t *folder = os_opendir(dir.toStdString().c_str()); struct os_dirent *ent; while ((ent = os_readdir(folder)) != NULL) { - if (!ent->directory || *ent->d_name == '.') + if (!ent->directory || *ent->d_name == '.') { continue; + } QString directoryPath = dir + QString(ent->d_name) + "/"; fileCheckLoop(directoryPath, true, depthWithoutFileMatch); diff --git a/frontend/utility/MissingFilesPathItemDelegate.cpp b/frontend/utility/MissingFilesPathItemDelegate.cpp index d7601b8d17ae16..d62ac767e8fe79 100644 --- a/frontend/utility/MissingFilesPathItemDelegate.cpp +++ b/frontend/utility/MissingFilesPathItemDelegate.cpp @@ -128,8 +128,9 @@ 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 = ""; + } bool isSet = false; @@ -146,8 +147,9 @@ void MissingFilesPathItemDelegate::handleBrowse(QWidget *container) isSet = true; } - if (isSet) + if (isSet) { emit commitData(container); + } } void MissingFilesPathItemDelegate::handleClear(QWidget *container) diff --git a/frontend/utility/MultitrackVideoOutput.cpp b/frontend/utility/MultitrackVideoOutput.cpp index bc8823ed3b4da1..494bc2cf5bf39e 100644 --- a/frontend/utility/MultitrackVideoOutput.cpp +++ b/frontend/utility/MultitrackVideoOutput.cpp @@ -58,11 +58,13 @@ static OBSServiceAutoRelease create_service(const GoLiveApi::Config &go_live_con const auto &ingest_endpoints = go_live_config.ingest_endpoints; for (auto &endpoint : ingest_endpoints) { - if (qstrnicmp("RTMP", endpoint.protocol.c_str(), 4)) + if (qstrnicmp("RTMP", endpoint.protocol.c_str(), 4)) { continue; + } - if (use_rtmps.has_value() && *use_rtmps != (qstricmp("RTMPS", endpoint.protocol.c_str()) == 0)) + if (use_rtmps.has_value() && *use_rtmps != (qstricmp("RTMPS", endpoint.protocol.c_str()) == 0)) { continue; + } url = endpoint.url_template.c_str(); if (endpoint.authentication && !endpoint.authentication->empty()) { @@ -96,8 +98,9 @@ static OBSServiceAutoRelease create_service(const GoLiveApi::Config &go_live_con // not initialize str if cat'ing with a null url if (!dstr_is_empty(str)) { auto found = dstr_find(str, "/{stream_key}"); - if (found) + if (found) { dstr_remove(str, found - str->array, str->len - (found - str->array)); + } } /* The stream key itself may contain query parameters, such as @@ -110,8 +113,9 @@ static OBSServiceAutoRelease create_service(const GoLiveApi::Config &go_live_con QUrl parsed_url{url}; QUrlQuery parsed_query{parsed_url}; - for (const auto &[key, value] : user_key_query.queryItems()) + for (const auto &[key, value] : user_key_query.queryItems()) { 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)); @@ -201,12 +205,14 @@ static void adjust_encoder_frame_rate_divisor(const obs_video_info &ovi, obs_enc } 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) + if (divisor <= 1) { return; + } blog(LOG_INFO, "Setting frame rate divisor to %u for encoder %zu", divisor, encoder_index); obs_encoder_set_frame_rate_divisor(video_encoder, divisor); @@ -217,8 +223,9 @@ static bool encoder_available(const char *type) const char *id = nullptr; for (size_t idx = 0; obs_enum_encoder_types(idx, &id); idx++) { - if (strcmp(id, type) == 0) + if (strcmp(id, type) == 0) { return true; + } } return false; @@ -382,15 +389,17 @@ void MultitrackVideoOutput::PrepareStreaming( std::string canvasNames; for (const auto &canvas : canvases) { - if (!canvasNames.empty()) + if (!canvasNames.empty()) { canvasNames += ", "; + } canvasNames += obs_canvas_get_name(canvas); } DStr vod_track_info_storage; - if (vod_track_mixer.has_value()) + if (vod_track_mixer.has_value()) { dstr_printf(vod_track_info_storage, "Yes (mixer: %zu)", vod_track_mixer.value()); + } blog(LOG_INFO, "Preparing enhanced broadcasting stream for:\n" @@ -461,14 +470,16 @@ void MultitrackVideoOutput::PrepareStreaming( vod_track_mixer, canvases); auto output = std::move(outputs.output); auto recording_output = std::move(outputs.recording_output); - if (!output) + if (!output) { throw MultitrackVideoError::warning( QTStr("FailedToStartStream.FallbackToDefault").arg(multitrack_video_name)); + } auto multitrack_video_service = create_service(service_config, rtmp_url, stream_key, use_rtmps); - if (!multitrack_video_service) + if (!multitrack_video_service) { throw MultitrackVideoError::warning( QTStr("FailedToStartStream.FallbackToDefault").arg(multitrack_video_name)); + } obs_output_set_service(output, multitrack_video_service); @@ -544,8 +555,9 @@ void MultitrackVideoOutput::StartedStreaming() } } - if (!dump_output) + if (!dump_output) { return; + } auto result = obs_output_start(dump_output); blog(LOG_INFO, "MultitrackVideoOutput: starting recording%s", result ? "" : " failed"); @@ -558,20 +570,24 @@ void MultitrackVideoOutput::StopStreaming() OBSOutputAutoRelease current_output; { const std::lock_guard current_lock{current_mutex}; - if (current && current->output_) + if (current && current->output_) { current_output = obs_output_get_ref(current->output_); + } } - if (current_output) + if (current_output) { obs_output_stop(current_output); + } OBSOutputAutoRelease dump_output; { const std::lock_guard current_stream_dump_lock{current_stream_dump_mutex}; - if (current_stream_dump && current_stream_dump->output_) + if (current_stream_dump && current_stream_dump->output_) { dump_output = obs_output_get_ref(current_stream_dump->output_); + } } - if (dump_output) + if (dump_output) { obs_output_stop(dump_output); + } } bool MultitrackVideoOutput::HandleIncompatibleSettings(QWidget *parent, config_t *config, obs_service_t *service, @@ -584,8 +600,9 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings(QWidget *parent, config_t size_t num = 1; auto check_setting = [&](bool setting, const char *name, const char *section) { - if (!setting) + if (!setting) { return; + } incompatible_settings += QString(" %1. %2\n").arg(num).arg(QTStr(name)); @@ -602,8 +619,9 @@ bool MultitrackVideoOutput::HandleIncompatibleSettings(QWidget *parent, config_t check_setting(enableDynBitrate, "Basic.Settings.Output.DynamicBitrate.Beta", "Basic.Settings.Advanced.Network"); - if (incompatible_settings.isEmpty()) + if (incompatible_settings.isEmpty()) { return true; + } OBSDataAutoRelease service_settings = obs_service_get_settings(service); @@ -661,8 +679,9 @@ static bool create_video_encoders(const GoLiveApi::Config &go_live_config, } std::shared_ptr encoder_group(obs_encoder_group_create(), obs_encoder_group_destroy); - if (!encoder_group) + if (!encoder_group) { return false; + } auto max_canvas_idx = canvases.size() - 1; @@ -675,15 +694,18 @@ static bool create_video_encoders(const GoLiveApi::Config &go_live_config, auto &canvas = canvases[config.canvas_index]; auto encoder = create_video_encoder(video_encoder_name_buffer, i, config, canvas); - if (!encoder) + if (!encoder) { return false; + } - if (!obs_encoder_set_group(encoder, encoder_group.get())) + if (!obs_encoder_set_group(encoder, encoder_group.get())) { return false; + } obs_output_set_video_encoder2(output, encoder, i); - if (recording_output) + if (recording_output) { obs_output_set_video_encoder2(recording_output, encoder, i); + } } video_encoder_group = encoder_group; @@ -698,16 +720,18 @@ static void create_audio_encoders(const GoLiveApi::Config &go_live_config, { speaker_layout speakers = SPEAKERS_UNKNOWN; obs_audio_info oai = {}; - if (obs_get_audio_info(&oai)) + if (obs_get_audio_info(&oai)) { speakers = oai.speakers; + } current_layout = speakers; 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) + if (get_audio_channels((speaker_layout)i) != channels) { continue; + } target_speakers = (speaker_layout)i; break; @@ -721,12 +745,14 @@ static void 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); - if (it == std::end(speaker_layouts)) + if (it == std::end(speaker_layouts)) { speaker_layouts.push_back(target_speakers); + } }; using encoder_configs_type = decltype(go_live_config.audio_configurations.live); @@ -749,8 +775,9 @@ static void create_audio_encoders(const GoLiveApi::Config &go_live_config, sanitize_audio_channels(audio_encoder, configs[i].channels); obs_output_set_audio_encoder(output, audio_encoder, output_encoder_index); - if (recording_output) + if (recording_output) { obs_output_set_audio_encoder(recording_output, audio_encoder, output_encoder_index); + } output_encoder_index += 1; audio_encoders.emplace_back(std::move(audio_encoder)); } @@ -758,8 +785,9 @@ static void create_audio_encoders(const GoLiveApi::Config &go_live_config, create_encoders("multitrack video live audio", go_live_config.audio_configurations.live, main_audio_mixer); - if (!vod_track_mixer.has_value()) + if (!vod_track_mixer.has_value()) { return; + } // we already check for empty inside of `create_encoders` encoder_configs_type empty = {}; @@ -795,8 +823,9 @@ static const char *speaker_layout_to_string(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()) + if (requested_layouts.empty()) { return; + } QString message; if (requested_layouts.size() == 1) { @@ -840,11 +869,13 @@ static OBSOutputs SetupOBSOutput(QWidget *parent, const QString &multitrack_vide { auto output = create_output(); OBSOutputAutoRelease recording_output; - if (dump_stream_to_file_config) + if (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, canvases)) + if (!create_video_encoders(go_live_config, video_encoder_group, output, recording_output, canvases)) { return {nullptr, nullptr}; + } std::vector requested_speaker_layouts; speaker_layout current_layout = SPEAKERS_UNKNOWN; @@ -885,8 +916,9 @@ std::optional MultitrackVideoOutput::ta void MultitrackVideoOutput::ReleaseOnMainThread(std::optional objects) { - if (!objects.has_value()) + if (!objects.has_value()) { return; + } QMetaObject::invokeMethod( QApplication::instance()->thread(), [objects = std::move(objects)] {}, Qt::QueuedConnection); @@ -906,11 +938,13 @@ void StreamStopHandler(void *arg, calldata_t *data) 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_) + 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) + if (stream_dump_output) { obs_output_stop(stream_dump_output); + } /* Unregister the BPM (Broadcast Performance Metrics) callback and destroy the allocated metrics data. */ obs_output_remove_packet_callback(static_cast(calldata_ptr(data, "output")), bpm_inject, NULL); diff --git a/frontend/utility/OBSCanvas.cpp b/frontend/utility/OBSCanvas.cpp index d7c19e53ecfd7d..0d92817f6e1202 100644 --- a/frontend/utility/OBSCanvas.cpp +++ b/frontend/utility/OBSCanvas.cpp @@ -30,8 +30,9 @@ Canvas::Canvas(Canvas &&other) noexcept Canvas::~Canvas() noexcept { - if (!canvas) + if (!canvas) { return; + } obs_canvas_remove(canvas); obs_canvas_release(canvas); @@ -47,10 +48,12 @@ Canvas &Canvas::operator=(Canvas &&other) noexcept std::optional Canvas::Save() const { - if (!canvas) + if (!canvas) { return std::nullopt; - if (obs_data_t *saved = obs_save_canvas(canvas)) + } + if (obs_data_t *saved = obs_save_canvas(canvas)) { return saved; + } return std::nullopt; } @@ -70,8 +73,9 @@ std::vector Canvas::LoadCanvases(obs_data_array_t *canvases) { auto cb = [](obs_data_t *data, void *param) -> void { auto vec = static_cast *>(param); - if (auto canvas = Canvas::Load(data)) + if (auto canvas = Canvas::Load(data)) { vec->emplace_back(std::move(*canvas)); + } }; std::vector ret; @@ -86,8 +90,9 @@ OBSDataArrayAutoRelease Canvas::SaveCanvases(const std::vector &canvases for (auto &canvas : canvases) { auto canvas_data = canvas.Save(); - if (!canvas_data) + if (!canvas_data) { continue; + } OBSDataAutoRelease data = obs_data_create(); obs_data_set_obj(data, "info", *canvas_data); diff --git a/frontend/utility/OBSProxyStyle.cpp b/frontend/utility/OBSProxyStyle.cpp index d7c68a6b37bc36..29db5d3cf4ddae 100644 --- a/frontend/utility/OBSProxyStyle.cpp +++ b/frontend/utility/OBSProxyStyle.cpp @@ -4,11 +4,13 @@ int OBSProxyStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const { - if (hint == SH_ComboBox_AllowWheelScrolling) + if (hint == SH_ComboBox_AllowWheelScrolling) { return 0; + } #ifdef __APPLE__ - if (hint == SH_ComboBox_UseNativePopup) + if (hint == SH_ComboBox_UseNativePopup) { return 1; + } #endif return QProxyStyle::styleHint(hint, option, widget, returnData); @@ -18,8 +20,9 @@ int OBSInvisibleCursorProxyStyle::pixelMetric(PixelMetric metric, const QStyleOp const QWidget *widget) const { - if (metric == PM_TextCursorWidth) + if (metric == PM_TextCursorWidth) { return 0; + } return QProxyStyle::pixelMetric(metric, option, widget); } diff --git a/frontend/utility/OBSTranslator.cpp b/frontend/utility/OBSTranslator.cpp index f61354cce50b8c..a3ad3feed01649 100644 --- a/frontend/utility/OBSTranslator.cpp +++ b/frontend/utility/OBSTranslator.cpp @@ -28,8 +28,9 @@ QString OBSTranslator::translate(const char *, const char *sourceText, const cha const char *out = nullptr; QString str(sourceText); str.replace(" ", ""); - if (!App()->TranslateString(QT_TO_UTF8(str), &out)) + if (!App()->TranslateString(QT_TO_UTF8(str), &out)) { return QString(sourceText); + } return QT_UTF8(out); } diff --git a/frontend/utility/QuickTransition.cpp b/frontend/utility/QuickTransition.cpp index b4f3af0d71722f..139d4ebfa44981 100644 --- a/frontend/utility/QuickTransition.cpp +++ b/frontend/utility/QuickTransition.cpp @@ -25,13 +25,15 @@ static inline QString MakeQuickTransitionText(QuickTransition *qt) { QString name; - if (!qt->fadeToBlack) + if (!qt->fadeToBlack) { name = QT_UTF8(obs_source_get_name(qt->source)); - else + } else { name = QTStr("FadeToBlack"); + } - if (!obs_transition_fixed(qt->source)) + if (!obs_transition_fixed(qt->source)) { name += QString(" (%1ms)").arg(QString::number(qt->duration)); + } return name; } diff --git a/frontend/utility/RemoteTextThread.cpp b/frontend/utility/RemoteTextThread.cpp index 9541fd4397d552..b47155f159da1f 100644 --- a/frontend/utility/RemoteTextThread.cpp +++ b/frontend/utility/RemoteTextThread.cpp @@ -35,8 +35,9 @@ using Curl = unique_ptr; static size_t string_write(char *ptr, size_t size, size_t nmemb, string &str) { size_t total = size * nmemb; - if (total) + if (total) { str.append(ptr, total); + } return total; } @@ -66,8 +67,9 @@ void RemoteTextThread::run() header = curl_slist_append(header, contentTypeString.c_str()); } - for (std::string &h : extraHeaders) + for (std::string &h : extraHeaders) { header = curl_slist_append(header, h.c_str()); + } curl_easy_setopt(curl.get(), CURLOPT_URL, url.c_str()); curl_easy_setopt(curl.get(), CURLOPT_ACCEPT_ENCODING, ""); @@ -78,8 +80,9 @@ void RemoteTextThread::run() curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &str); curl_obs_set_revoke_setting(curl.get()); - if (timeoutSec) + if (timeoutSec) { curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, timeoutSec); + } if (!postData.empty()) { curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, postData.c_str()); @@ -103,13 +106,16 @@ static size_t header_write(char *ptr, size_t size, size_t nmemb, vector string str; size_t total = size * nmemb; - if (total) + if (total) { str.append(ptr, total); + } - if (str.back() == '\n') + if (str.back() == '\n') { str.resize(str.size() - 1); - if (str.back() == '\r') + } + if (str.back() == '\r') { str.resize(str.size() - 1); + } list.push_back(std::move(str)); return total; @@ -144,15 +150,17 @@ bool GetRemoteFile(const char *url, std::string &str, std::string &error, long * header = curl_slist_append(header, contentTypeString.c_str()); } - for (std::string &h : extraHeaders) + for (std::string &h : extraHeaders) { header = curl_slist_append(header, h.c_str()); + } curl_easy_setopt(curl.get(), CURLOPT_URL, url); curl_easy_setopt(curl.get(), CURLOPT_ACCEPT_ENCODING, ""); curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, header); curl_easy_setopt(curl.get(), CURLOPT_ERRORBUFFER, error_in); - if (fail_on_error) + 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_WRITEDATA, &str); curl_obs_set_revoke_setting(curl.get()); @@ -162,18 +170,21 @@ bool GetRemoteFile(const char *url, std::string &str, std::string &error, long * curl_easy_setopt(curl.get(), CURLOPT_HEADERDATA, &header_in_list); } - if (timeoutSec) + if (timeoutSec) { curl_easy_setopt(curl.get(), CURLOPT_TIMEOUT, timeoutSec); + } if (!request_type.empty()) { - if (request_type != "GET") + if (request_type != "GET") { 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) + if (!postData) { curl_easy_setopt(curl.get(), CURLOPT_POSTFIELDS, "{}"); + } } } if (postData) { @@ -184,8 +195,9 @@ bool GetRemoteFile(const char *url, std::string &str, std::string &error, long * } code = curl_easy_perform(curl.get()); - if (responseCode) + if (responseCode) { curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, responseCode); + } if (code != CURLE_OK) { error = strlen(error_in) ? error_in : curl_easy_strerror(code); diff --git a/frontend/utility/RemuxEntryPathItemDelegate.cpp b/frontend/utility/RemuxEntryPathItemDelegate.cpp index bcaa43f83bc52c..d95ac7d830b040 100644 --- a/frontend/utility/RemuxEntryPathItemDelegate.cpp +++ b/frontend/utility/RemuxEntryPathItemDelegate.cpp @@ -125,10 +125,12 @@ void RemuxEntryPathItemDelegate::setModelData(QWidget *editor, QAbstractItemMode if (pathListProp.isValid()) { QStringList list = editor->property(PATH_LIST_PROP).toStringList(); if (isOutput) { - if (list.size() > 0) + if (list.size() > 0) { model->setData(index, list); - } else + } + } else { model->setData(index, list, RemuxEntryRole::NewPathsToProcessRole); + } } else { QLineEdit *lineEdit = editor->findChild(); model->setData(index, lineEdit->text()); @@ -165,8 +167,9 @@ void RemuxEntryPathItemDelegate::handleBrowse(QWidget *container) QLineEdit *text = container->findChild(); QString currentPath = text->text(); - if (currentPath.isEmpty()) + if (currentPath.isEmpty()) { currentPath = defaultPath; + } bool isSet = false; if (isOutput) { @@ -190,8 +193,9 @@ void RemuxEntryPathItemDelegate::handleBrowse(QWidget *container) #endif } - if (isSet) + if (isSet) { emit commitData(container); + } } void RemuxEntryPathItemDelegate::handleClear(QWidget *container) diff --git a/frontend/utility/RemuxQueueModel.cpp b/frontend/utility/RemuxQueueModel.cpp index cae17b1389cae9..ca34c604c4d099 100644 --- a/frontend/utility/RemuxQueueModel.cpp +++ b/frontend/utility/RemuxQueueModel.cpp @@ -218,10 +218,11 @@ void RemuxQueueModel::checkInputPath(int row) } else { entry.sourcePath = QDir::toNativeSeparators(entry.sourcePath); QFileInfo fileInfo(entry.sourcePath); - if (fileInfo.exists()) + if (fileInfo.exists()) { entry.state = RemuxEntryState::Ready; - else + } else { entry.state = RemuxEntryState::InvalidPath; + } QString newExt = ".mp4"; QString suffix = fileInfo.suffix(); @@ -230,13 +231,15 @@ void RemuxQueueModel::checkInputPath(int row) newExt = ".remuxed." + suffix; } - if (entry.state == RemuxEntryState::Ready) + if (entry.state == RemuxEntryState::Ready) { entry.targetPath = QDir::toNativeSeparators(fileInfo.path() + QDir::separator() + fileInfo.completeBaseName() + newExt); + } } - if (entry.state == RemuxEntryState::Ready && isProcessing) + if (entry.state == RemuxEntryState::Ready && isProcessing) { entry.state = RemuxEntryState::Pending; + } emit dataChanged(index(row, 0), index(row, RemuxEntryColumn::Count)); } @@ -296,20 +299,23 @@ void RemuxQueueModel::clearFinished() bool RemuxQueueModel::canClearFinished() const { bool canClearFinished = false; - for (const RemuxQueueEntry &entry : queue) + for (const RemuxQueueEntry &entry : queue) { if (entry.state == RemuxEntryState::Complete) { canClearFinished = true; break; } + } return canClearFinished; } void RemuxQueueModel::beginProcessing() { - for (RemuxQueueEntry &entry : queue) - if (entry.state == RemuxEntryState::Ready) + for (RemuxQueueEntry &entry : queue) { + if (entry.state == RemuxEntryState::Ready) { entry.state = RemuxEntryState::Pending; + } + } // Signal that the insertion point no longer exists. beginRemoveRows(QModelIndex(), queue.length(), queue.length()); @@ -366,10 +372,11 @@ void RemuxQueueModel::finishEntry(bool success) for (int row = 0; row < queue.length(); row++) { RemuxQueueEntry &entry = queue[row]; if (entry.state == RemuxEntryState::InProgress) { - if (success) + if (success) { entry.state = RemuxEntryState::Complete; - else + } else { entry.state = RemuxEntryState::Error; + } QModelIndex index = this->index(row, RemuxEntryColumn::State); emit dataChanged(index, index); diff --git a/frontend/utility/RemuxWorker.cpp b/frontend/utility/RemuxWorker.cpp index e9d54093b2ba2a..87bf0450ded3f2 100644 --- a/frontend/utility/RemuxWorker.cpp +++ b/frontend/utility/RemuxWorker.cpp @@ -22,8 +22,9 @@ void RemuxWorker::UpdateProgress(float percent) { - if (abs(lastProgress - percent) < 0.1f) + if (abs(lastProgress - percent) < 0.1f) { return; + } emit updateProgress(percent); lastProgress = percent; diff --git a/frontend/utility/SceneRenameDelegate.cpp b/frontend/utility/SceneRenameDelegate.cpp index e505c52056ce7f..3d3c8d1b94ebe6 100644 --- a/frontend/utility/SceneRenameDelegate.cpp +++ b/frontend/utility/SceneRenameDelegate.cpp @@ -30,8 +30,9 @@ void SceneRenameDelegate::setEditorData(QWidget *editor, const QModelIndex &inde { QStyledItemDelegate::setEditorData(editor, index); QLineEdit *lineEdit = qobject_cast(editor); - if (lineEdit) + if (lineEdit) { lineEdit->selectAll(); + } } bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event) @@ -41,8 +42,9 @@ bool SceneRenameDelegate::eventFilter(QObject *editor, QEvent *event) switch (keyEvent->key()) { case Qt::Key_Escape: { QLineEdit *lineEdit = qobject_cast(editor); - if (lineEdit) + if (lineEdit) { lineEdit->undo(); + } break; } case Qt::Key_Tab: diff --git a/frontend/utility/ScreenshotObj.cpp b/frontend/utility/ScreenshotObj.cpp index 0fff65d6f526d1..bb989950b74e14 100644 --- a/frontend/utility/ScreenshotObj.cpp +++ b/frontend/utility/ScreenshotObj.cpp @@ -143,8 +143,9 @@ void ScreenshotObj::Copy() image = QImage(cx, cy, QImage::Format::Format_RGBX8888); int linesize = image.bytesPerLine(); - for (int y = 0; y < (int)cy; y++) + for (int y = 0; y < (int)cy; y++) { memcpy(image.scanLine(y), videoData + (y * videoLinesize), linesize); + } } gs_stagesurface_unmap(stagesurf); @@ -185,36 +186,44 @@ static HRESULT SaveJxrImage(LPCWSTR path, uint8_t *pixels, uint32_t cx, uint32_t value.vt = VT_BOOL; value.bVal = TRUE; HRESULT hr = options->Write(1, &bag, &value); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = frameEncode->Initialize(options); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = frameEncode->SetSize(cx, cy); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = frameEncode->SetResolution(72, 72); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } WICPixelFormatGUID pixelFormat = GUID_WICPixelFormat64bppRGBAHalf; hr = frameEncode->SetPixelFormat(&pixelFormat); - if (FAILED(hr)) + 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); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = frameEncode->Commit(); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } return S_OK; } @@ -224,36 +233,43 @@ 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, IID_PPV_ARGS(factory.GetAddressOf())); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } Microsoft::WRL::ComPtr stream; hr = factory->CreateStream(stream.GetAddressOf()); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = stream->InitializeFromFilename(path, GENERIC_WRITE); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } Microsoft::WRL::ComPtr encoder = NULL; hr = factory->CreateEncoder(GUID_ContainerFormatWmp, NULL, encoder.GetAddressOf()); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = encoder->Initialize(stream.Get(), WICBitmapEncoderNoCache); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } Microsoft::WRL::ComPtr frameEncode; Microsoft::WRL::ComPtr options; hr = encoder->CreateNewFrame(frameEncode.GetAddressOf(), options.GetAddressOf()); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } hr = SaveJxrImage(path, pixels, cx, cy, frameEncode.Get(), options.Get()); - if (FAILED(hr)) + if (FAILED(hr)) { return hr; + } encoder->Commit(); return S_OK; diff --git a/frontend/utility/SimpleOutput.cpp b/frontend/utility/SimpleOutput.cpp index c3491fd91c9319..5f548a7234211d 100644 --- a/frontend/utility/SimpleOutput.cpp +++ b/frontend/utility/SimpleOutput.cpp @@ -49,9 +49,10 @@ extern bool EncoderAvailable(const char *encoder); void SimpleOutput::LoadRecordingPreset_Lossless() { fileOutput = obs_output_create("ffmpeg_output", "simple_ffmpeg_output", nullptr, nullptr); - if (!fileOutput) + if (!fileOutput) { throw "Failed to create recording FFmpeg output " "(simple output)"; + } OBSDataAutoRelease settings = obs_data_create(); obs_data_set_string(settings, "format_name", "avi"); @@ -64,16 +65,18 @@ void SimpleOutput::LoadRecordingPreset_Lossless() void SimpleOutput::LoadRecordingPreset_Lossy(const char *encoderId) { videoRecording = obs_video_encoder_create(encoderId, "simple_video_recording", nullptr, nullptr); - if (!videoRecording) + if (!videoRecording) { throw "Failed to create video recording encoder (simple output)"; + } obs_encoder_release(videoRecording); } void SimpleOutput::LoadStreamingPreset_Lossy(const char *encoderId) { videoStreaming = obs_video_encoder_create(encoderId, "simple_video_stream", nullptr, nullptr); - if (!videoStreaming) + if (!videoStreaming) { throw "Failed to create video streaming encoder (simple output)"; + } obs_encoder_release(videoStreaming); if (whipSimulcastEncoders != nullptr) { @@ -147,21 +150,24 @@ void SimpleOutput::LoadRecordingPreset() } else { lowCPUx264 = false; - if (strcmp(encoder, SIMPLE_ENCODER_X264_LOWCPU) == 0) + if (strcmp(encoder, SIMPLE_ENCODER_X264_LOWCPU) == 0) { lowCPUx264 = true; + } LoadRecordingPreset_Lossy(get_simple_output_encoder(encoder)); usingRecordingPreset = true; bool success = false; - if (strcmp(audio_encoder, "opus") == 0) + if (strcmp(audio_encoder, "opus") == 0) { success = CreateSimpleOpusEncoder(audioRecording, 192, "simple_opus_recording", 0); - else + } else { success = CreateSimpleAACEncoder(audioRecording, 192, "simple_aac_recording", 0); + } - if (!success) + if (!success) { throw "Failed to create audio recording encoder " "(simple output)"; + } for (int i = 0; i < MAX_AUDIO_MIXES; i++) { char name[23]; if (strcmp(audio_encoder, "opus") == 0) { @@ -171,9 +177,10 @@ void SimpleOutput::LoadRecordingPreset() snprintf(name, sizeof name, "simple_aac_recording%d", i); success = CreateSimpleAACEncoder(audioTrack[i], GetAudioBitrate(), name, i); } - if (!success) + if (!success) { throw "Failed to create multi-track audio recording encoder " "(simple output)"; + } } } } @@ -189,21 +196,25 @@ SimpleOutput::SimpleOutput(OBSBasic *main_) : BasicOutputHandler(main_) bool success = false; - if (strcmp(audio_encoder, "opus") == 0) + if (strcmp(audio_encoder, "opus") == 0) { success = CreateSimpleOpusEncoder(audioStreaming, GetAudioBitrate(), "simple_opus", 0); - else + } else { success = CreateSimpleAACEncoder(audioStreaming, GetAudioBitrate(), "simple_aac", 0); + } - if (!success) + if (!success) { throw "Failed to create audio streaming encoder (simple output)"; + } - if (strcmp(audio_encoder, "opus") == 0) + if (strcmp(audio_encoder, "opus") == 0) { success = CreateSimpleOpusEncoder(audioArchive, GetAudioBitrate(), SIMPLE_ARCHIVE_NAME, 1); - else + } else { success = CreateSimpleAACEncoder(audioArchive, GetAudioBitrate(), SIMPLE_ARCHIVE_NAME, 1); + } - if (!success) + if (!success) { throw "Failed to create audio archive encoder (simple output)"; + } LoadRecordingPreset(); @@ -214,16 +225,18 @@ SimpleOutput::SimpleOutput(OBSBasic *main_) : BasicOutputHandler(main_) if (useReplayBuffer) { OBSDataAutoRelease hotkey; const char *str = config_get_string(main->Config(), "Hotkeys", "ReplayBuffer"); - if (str) + if (str) { hotkey = obs_data_create_from_json(str); - else + } else { hotkey = nullptr; + } replayBuffer = obs_output_create("replay_buffer", Str("ReplayBuffer"), nullptr, hotkey); - if (!replayBuffer) + if (!replayBuffer) { throw "Failed to create replay buffer output " "(simple output)"; + } signal_handler_t *signal = obs_output_get_signal_handler(replayBuffer); @@ -234,15 +247,17 @@ SimpleOutput::SimpleOutput(OBSBasic *main_) : BasicOutputHandler(main_) } const char *mux = "ffmpeg_muxer"; - if (strcmp(recFormat, "hybrid_mp4") == 0) + if (strcmp(recFormat, "hybrid_mp4") == 0) { mux = "mp4_output"; - else if (strcmp(recFormat, "hybrid_mov") == 0) + } else if (strcmp(recFormat, "hybrid_mov") == 0) { mux = "mov_output"; + } fileOutput = obs_output_create(mux, "simple_file_output", nullptr, nullptr); - if (!fileOutput) + if (!fileOutput) { throw "Failed to create recording output " "(simple output)"; + } } startRecording.Connect(obs_output_get_signal_handler(fileOutput), "start", OBSStartRecording, this); @@ -255,8 +270,9 @@ 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"); - if (strcmp(audio_encoder, "opus") == 0) + if (strcmp(audio_encoder, "opus") == 0) { return FindClosestAvailableSimpleOpusBitrate(bitrate); + } return FindClosestAvailableSimpleAACBitrate(bitrate); } @@ -320,8 +336,9 @@ void SimpleOutput::Update() obs_data_set_string(videoSettings, "rate_control", "CBR"); obs_data_set_int(videoSettings, "bitrate", videoBitrate); - if (advanced) + if (advanced) { obs_data_set_string(videoSettings, "x264opts", custom); + } obs_data_set_string(audioSettings, "rate_control", "CBR"); obs_data_set_int(audioSettings, "bitrate", audioBitrate); @@ -403,8 +420,9 @@ int SimpleOutput::CalcCRF(int crf) double fCX = double(cx); double fCY = double(cy); - if (lowCPUx264) + if (lowCPUx264) { crf -= 2; + } double crossDist = sqrt(fCX * fCX + fCY * fCY); double crfResReduction = fmin(CROSS_DIST_CUTOFF, crossDist) / CROSS_DIST_CUTOFF; @@ -592,12 +610,14 @@ inline void SimpleOutput::SetupOutputs() std::shared_future SimpleOutput::SetupStreaming(obs_service_t *service, SetupStreamingContinuation_t continuation) { - if (!Active()) + if (!Active()) { SetupOutputs(); + } Auth *auth = main->GetAuth(); - if (auth) + if (auth) { auth->OnStreamConfig(); + } /* --------------------- */ @@ -612,8 +632,9 @@ std::shared_future SimpleOutput::SetupStreaming(obs_service_t *service, Se auto handle_multitrack_video_result = [this, type = std::string{type}, service](std::optional multitrackVideoResult) { - if (multitrackVideoResult.has_value()) + if (multitrackVideoResult.has_value()) { return multitrackVideoResult.value(); + } /* XXX: this is messy and disgusting and should be refactored */ if (outputType != type) { @@ -666,18 +687,20 @@ bool SimpleOutput::IsVodTrackEnabled(obs_service_t *service) const char *name = obs_data_get_string(settings, "service"); const char *id = obs_service_get_id(service); - if (strcmp(id, "rtmp_custom") == 0) + if (strcmp(id, "rtmp_custom") == 0) { return enableForCustomServer ? enable : false; - else + } else { return advanced && enable && ServiceSupportsVodTrack(name); + } } void SimpleOutput::SetupVodTrack(obs_service_t *service) { - if (IsVodTrackEnabled(service)) + if (IsVodTrackEnabled(service)) { obs_output_set_audio_encoder(streamOutput, audioArchive, 1); - else + } else { clear_archive_encoder(streamOutput, SIMPLE_ARCHIVE_NAME); + } } bool SimpleOutput::StartStreaming(obs_service_t *service) @@ -715,31 +738,36 @@ bool SimpleOutput::StartStreaming(obs_service_t *service) obs_output_update(streamOutput, settings); - if (!reconnect) + if (!reconnect) { maxRetries = 0; + } obs_output_set_delay(streamOutput, useDelay ? delaySec : 0, preserveDelay ? OBS_OUTPUT_DELAY_PRESERVE : 0); obs_output_set_reconnect_settings(streamOutput, maxRetries, retryDelay); - if (!multitrackVideo || !multitrackVideoActive) + if (!multitrackVideo || !multitrackVideoActive) { SetupVodTrack(service); + } if (obs_output_start(streamOutput)) { - if (multitrackVideo && multitrackVideoActive) + if (multitrackVideo && multitrackVideoActive) { multitrackVideo->StartedStreaming(); + } return true; } - if (multitrackVideo && multitrackVideoActive) + if (multitrackVideo && multitrackVideoActive) { multitrackVideoActive = false; + } const char *error = obs_output_get_last_error(streamOutput); bool hasLastError = error && *error; - if (hasLastError) + if (hasLastError) { lastError = error; - else + } else { 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: " : "", @@ -756,18 +784,21 @@ void SimpleOutput::UpdateRecording() int idx2 = 0; const char *quality = config_get_string(main->Config(), "SimpleOutput", "RecQuality"); - if (replayBufferActive || recordingActive) + if (replayBufferActive || recordingActive) { return; + } if (usingRecordingPreset) { - if (!ffmpegOutput) + if (!ffmpegOutput) { UpdateRecordingSettings(); + } } else if (!obs_output_active(streamOutput)) { Update(); } - if (!Active()) + if (!Active()) { SetupOutputs(); + } if (!ffmpegOutput) { obs_output_set_video_encoder(fileOutput, videoRecording); @@ -831,8 +862,9 @@ bool SimpleOutput::ConfigureRecording(bool updateReplayBuffer) 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) + if (ffmpegOutput) { obs_output_set_mixers(fileOutput, tracks); + } } // Use fragmented MOV/MP4 if user has not already specified custom movflags @@ -844,16 +876,18 @@ bool SimpleOutput::ConfigureRecording(bool updateReplayBuffer) } obs_data_set_string(settings, "muxer_settings", mux_frag.c_str()); } else { - if (is_fragmented && !is_lossless) + if (is_fragmented && !is_lossless) { blog(LOG_WARNING, "User enabled fragmented recording, " "but custom muxer settings contained movflags."); + } obs_data_set_string(settings, "muxer_settings", mux); } - if (updateReplayBuffer) + if (updateReplayBuffer) { obs_output_update(replayBuffer, settings); - else + } else { obs_output_update(fileOutput, settings); + } return true; } @@ -861,15 +895,17 @@ bool SimpleOutput::ConfigureRecording(bool updateReplayBuffer) bool SimpleOutput::StartRecording() { UpdateRecording(); - if (!ConfigureRecording(false)) + if (!ConfigureRecording(false)) { return false; + } if (!obs_output_start(fileOutput)) { QString error_reason; const char *error = obs_output_get_last_error(fileOutput); - if (error) + if (error) { error_reason = QT_UTF8(error); - else + } else { error_reason = QTStr("Output.StartFailedGeneric"); + } QMessageBox::critical(main, QTStr("Output.StartRecordingFailed"), error_reason); return false; } @@ -880,8 +916,9 @@ bool SimpleOutput::StartRecording() bool SimpleOutput::StartReplayBuffer() { UpdateRecording(); - if (!ConfigureRecording(true)) + if (!ConfigureRecording(true)) { return false; + } if (!obs_output_start(replayBuffer)) { QMessageBox::critical(main, QTStr("Output.StartReplayFailed"), QTStr("Output.StartFailedGeneric")); return false; @@ -893,28 +930,31 @@ bool SimpleOutput::StartReplayBuffer() void SimpleOutput::StopStreaming(bool force) { auto output = StreamingOutput(); - if (force && output) + if (force && output) { obs_output_force_stop(output); - else if (multitrackVideo && multitrackVideoActive) + } else if (multitrackVideo && multitrackVideoActive) { multitrackVideo->StopStreaming(); - else + } else { obs_output_stop(output); + } } void SimpleOutput::StopRecording(bool force) { - if (force) + if (force) { obs_output_force_stop(fileOutput); - else + } else { obs_output_stop(fileOutput); + } } void SimpleOutput::StopReplayBuffer(bool force) { - if (force) + if (force) { obs_output_force_stop(replayBuffer); - else + } else { obs_output_stop(replayBuffer); + } } bool SimpleOutput::StreamingActive() const diff --git a/frontend/utility/WHIPSimulcastEncoders.hpp b/frontend/utility/WHIPSimulcastEncoders.hpp index fc369eb10e8169..c052d42998c7af 100644 --- a/frontend/utility/WHIPSimulcastEncoders.hpp +++ b/frontend/utility/WHIPSimulcastEncoders.hpp @@ -69,14 +69,16 @@ struct WHIPSimulcastEncoders { void SetVideoFormat(enum video_format format) { - for (auto enc : whipSimulcastEncoders) + for (auto enc : whipSimulcastEncoders) { obs_encoder_set_preferred_video_format(enc, format); + } } void SetStreamOutput(obs_output_t *streamOutput) { - for (size_t i = 0; i < whipSimulcastEncoders.size(); i++) + for (size_t i = 0; i < whipSimulcastEncoders.size(); i++) { obs_output_set_video_encoder2(streamOutput, whipSimulcastEncoders[i], i + 1); + } } private: diff --git a/frontend/utility/WhatsNewInfoThread.cpp b/frontend/utility/WhatsNewInfoThread.cpp index 24ebd010f762ae..513d54f82bb520 100644 --- a/frontend/utility/WhatsNewInfoThread.cpp +++ b/frontend/utility/WhatsNewInfoThread.cpp @@ -41,12 +41,14 @@ static bool QuickWriteFile(const char *file, const std::string &data) try { std::ofstream fileStream(std::filesystem::u8path(file), std::ios::binary); - if (fileStream.fail()) + if (fileStream.fail()) { throw strprintf("Failed to open file '%s': %s", file, strerror(errno)); + } fileStream.write(data.data(), data.size()); - if (fileStream.fail()) + if (fileStream.fail()) { throw strprintf("Failed to write file '%s': %s", file, strerror(errno)); + } return true; @@ -58,8 +60,9 @@ try { static bool QuickReadFile(const char *file, std::string &data) try { std::ifstream fileStream(std::filesystem::u8path(file), std::ios::binary); - if (!fileStream.is_open() || fileStream.fail()) + if (!fileStream.is_open() || fileStream.fail()) { throw strprintf("Failed to open file '%s': %s", file, strerror(errno)); + } fileStream.seekg(0, fileStream.end); size_t size = fileStream.tellg(); @@ -68,8 +71,9 @@ try { data.resize(size); fileStream.read(&data[0], size); - if (fileStream.fail()) + if (fileStream.fail()) { throw strprintf("Failed to write file '%s': %s", file, strerror(errno)); + } return true; @@ -81,26 +85,31 @@ try { static bool CalculateFileHash(const char *path, uint8_t *hash) try { blake2b_state blake2; - if (blake2b_init(&blake2, BLAKE2_HASH_LENGTH) != 0) + if (blake2b_init(&blake2, BLAKE2_HASH_LENGTH) != 0) { return false; + } std::ifstream file(std::filesystem::u8path(path), std::ios::binary); - if (!file.is_open() || file.fail()) + if (!file.is_open() || file.fail()) { return false; + } char buf[HASH_READ_BUF_SIZE]; for (;;) { file.read(buf, HASH_READ_BUF_SIZE); size_t read = file.gcount(); - if (blake2b_update(&blake2, &buf, read) != 0) + if (blake2b_update(&blake2, &buf, read) != 0) { return false; - if (file.eof()) + } + if (file.eof()) { break; + } } - if (blake2b_final(&blake2, hash, BLAKE2_HASH_LENGTH) != 0) + if (blake2b_final(&blake2, hash, BLAKE2_HASH_LENGTH) != 0) { return false; + } return true; @@ -133,14 +142,16 @@ std::string GetProgramGUID() * kind of identifiable information */ const char *pguid = config_get_string(App()->GetAppConfig(), "General", "InstallGUID"); std::string guid; - if (pguid) + if (pguid) { guid = pguid; + } if (guid.empty()) { GenerateGUID(guid); - if (!guid.empty()) + if (!guid.empty()) { config_set_string(App()->GetAppConfig(), "General", "InstallGUID", guid.c_str()); + } } return guid; @@ -152,10 +163,12 @@ static void LoadPublicKey(std::string &pubkey) { std::string pemFilePath; - if (!GetDataFilePath("OBSPublicRSAKey.pem", pemFilePath)) + if (!GetDataFilePath("OBSPublicRSAKey.pem", pemFilePath)) { throw std::string("Could not find OBS public key file!"); - if (!QuickReadFile(pemFilePath.c_str(), pubkey)) + } + if (!QuickReadFile(pemFilePath.c_str(), 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) @@ -163,19 +176,22 @@ try { static std::mutex pubkey_mutex; static std::string obsPubKey; - if (hexSig.empty() || hexSig.length() > 0xFFFF || (hexSig.length() & 1) != 0) + 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()) + if (obsPubKey.empty()) { LoadPublicKey(obsPubKey); + } // 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(), - (uint8_t *)signature.data(), signature.size())) + (uint8_t *)signature.data(), signature.size())) { throw strprintf("Signature check failed for %s", name); + } return true; @@ -229,8 +245,9 @@ bool FetchAndVerifyFile(const char *name, const char *file, const char *url, std success = GetRemoteFile(url, data, error, &responseCode, nullptr, "", nullptr, headers, &signature); if (!success || (responseCode != 200 && responseCode != 304)) { - if (responseCode == 404) + if (responseCode == 404) { return false; + } throw strprintf("Failed to fetch %s file: %s", name, error.c_str()); } @@ -240,23 +257,27 @@ bool FetchAndVerifyFile(const char *name, const char *file, const char *url, std if (responseCode == 200) { success = CheckDataSignature(name, data, signature); - if (!success) + if (!success) { throw strprintf("Invalid %s signature", name); + } } /* ----------------------------------- * * write or load file */ if (responseCode == 200) { - if (!QuickWriteFile(filePath, data)) + if (!QuickWriteFile(filePath, data)) { throw strprintf("Could not write file '%s'", filePath.Get()); + } } else if (out) { /* Only read file if caller wants data */ - if (!QuickReadFile(filePath, data)) + if (!QuickReadFile(filePath, data)) { throw strprintf("Could not read file '%s'", filePath.Get()); + } } - if (out) + if (out) { *out = data; + } /* ----------------------------------- * * success */ diff --git a/frontend/utility/YoutubeApiWrappers.cpp b/frontend/utility/YoutubeApiWrappers.cpp index 4d1a2a1ea598f4..731a88c914780f 100644 --- a/frontend/utility/YoutubeApiWrappers.cpp +++ b/frontend/utility/YoutubeApiWrappers.cpp @@ -54,8 +54,9 @@ bool YoutubeApiWrappers::GetTranslatedError(QString &error_message) const QString errorKey = "YouTube.Errors." + lastErrorReason.toUtf8(); const QString translated = QTStr(QT_TO_UTF8(errorKey)); // No translation found - if (translated.startsWith("YouTube.Errors.")) + if (translated.startsWith("YouTube.Errors.")) { return false; + } error_message = translated; return true; } @@ -69,23 +70,27 @@ bool YoutubeApiWrappers::TryInsertCommand(const char *url, const char *content_t #ifdef _DEBUG blog(LOG_DEBUG, "YouTube API command URL: %s", url); - if (data && data[0] == '{') // only log JSON data + if (data && data[0] == '{') { // only log JSON data blog(LOG_DEBUG, "YouTube API command data: %s", data); + } #endif - if (token.empty()) + if (token.empty()) { return false; + } std::string output; 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); - if (error_code) + if (error_code) { *error_code = httpStatusCode; + } if (!success || output.empty()) { - if (!error.empty()) + if (!error.empty()) { blog(LOG_WARNING, "YouTube API request failed: %s", error.c_str()); + } return false; } @@ -121,8 +126,9 @@ bool YoutubeApiWrappers::UpdateAccessToken() bool success = TryInsertCommand(youtubeLiveTokenUrl.data(), "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; } @@ -135,8 +141,9 @@ bool YoutubeApiWrappers::InsertCommand(const char *url, const char *content_type if (error_code == 401) { // Attempt to update access token and try again - if (!UpdateAccessToken()) + if (!UpdateAccessToken()) { return false; + } success = TryInsertCommand(url, content_type, request_type, data, json_out, &error_code, data_size); } @@ -265,13 +272,15 @@ bool YoutubeApiWrappers::GetBroadcastsList(Json &json_out, const QString &page, "?part=snippet,contentDetails,status&broadcastType=all&maxResults=" + std::to_string(defaultBroadcastsPerQuery); - if (status.isEmpty()) + if (status.isEmpty()) { url += "&mine=true"; - else + } else { url += "&broadcastStatus=" + status.toStdString(); + } - if (!page.isEmpty()) + if (!page.isEmpty()) { url += "&pageToken=" + page.toStdString(); + } return InsertCommand(url.c_str(), "application/json", "", nullptr, json_out); } @@ -296,12 +305,14 @@ bool YoutubeApiWrappers::GetVideoCategoriesList(QVector &ca Json json_out; if (!InsertCommand(QT_TO_UTF8(url), "application/json", "", nullptr, json_out)) { - if (lastErrorReason != "unsupportedLanguageCode" && lastErrorReason != "invalidLanguage") + 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 = {}; for (auto &j : json_out["items"].array_items()) { @@ -365,15 +376,16 @@ bool YoutubeApiWrappers::StartBroadcast(const QString &broadcast_id) lastErrorReason.clear(); Json json_out; - if (!FindBroadcast(broadcast_id, json_out)) + if (!FindBroadcast(broadcast_id, json_out)) { return false; + } auto lifeCycleStatus = json_out["items"][0]["status"]["lifeCycleStatus"].string_value(); - if (lifeCycleStatus == "live" || lifeCycleStatus == "liveStarting") + if (lifeCycleStatus == "live" || lifeCycleStatus == "liveStarting") { // Broadcast is already (going to be) live return true; - else if (lifeCycleStatus == "testStarting") { + } else if (lifeCycleStatus == "testStarting") { // User will need to wait a few seconds before attempting to start broadcast lastErrorMessage = QTStr("YouTube.Actions.Error.BroadcastTestStarting"); lastErrorReason.clear(); @@ -383,8 +395,9 @@ bool YoutubeApiWrappers::StartBroadcast(const QString &broadcast_id) // 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)) + if (lifeCycleStatus != "testing" && monitorStreamEnabled && !ResetBroadcast(broadcast_id, json_out)) { return false; + } // TODO: Use std::format with C++20 const QString url_template = @@ -486,8 +499,9 @@ bool YoutubeApiWrappers::FindBroadcast(const QString &id, json11::Json &json_out "?part=id,snippet,contentDetails,status&broadcastType=all&maxResults=1"; url += "&id=" + id.toStdString(); - if (!InsertCommand(url.c_str(), "application/json", "", nullptr, json_out)) + if (!InsertCommand(url.c_str(), "application/json", "", nullptr, json_out)) { return false; + } auto items = json_out["items"].array_items(); if (items.size() != 1) { @@ -505,8 +519,9 @@ bool YoutubeApiWrappers::FindStream(const QString &id, json11::Json &json_out) std::string url = std::string(youtubeLiveStreamUrl) + "?part=id,snippet,cdn,status&maxResults=1"; url += "&id=" + id.toStdString(); - if (!InsertCommand(url.c_str(), "application/json", "", nullptr, json_out)) + if (!InsertCommand(url.c_str(), "application/json", "", nullptr, json_out)) { return false; + } auto items = json_out["items"].array_items(); if (items.size() != 1) { diff --git a/frontend/utility/audio-encoders.cpp b/frontend/utility/audio-encoders.cpp index 357ec45ca20070..b62abc3388df2c 100644 --- a/frontend/utility/audio-encoders.cpp +++ b/frontend/utility/audio-encoders.cpp @@ -23,8 +23,9 @@ static void HandleIntProperty(obs_property_t *prop, std::vector &bitrates) const int max_ = obs_property_int_max(prop); const int step = obs_property_int_step(prop); - for (int i = obs_property_int_min(prop); i <= max_; i += step) + for (int i = obs_property_int_min(prop); i <= max_; i += step) { bitrates.push_back(i); + } } static void HandleListProperty(obs_property_t *prop, const char *id, std::vector &bitrates) @@ -41,8 +42,9 @@ static void HandleListProperty(obs_property_t *prop, const char *id, std::vector const size_t count = obs_property_list_item_count(prop); for (size_t i = 0; i < count; i++) { - if (obs_property_list_item_disabled(prop, i)) + if (obs_property_list_item_disabled(prop, i)) { continue; + } int bitrate = static_cast(obs_property_list_item_int(prop, i)); bitrates.push_back(bitrate); @@ -95,8 +97,9 @@ static void HandleEncoderProperties(const char *id, std::vector &bitrates) } obs_property_t *samplerate = obs_properties_get(props.get(), "samplerate"); - if (samplerate) + if (samplerate) { HandleSampleRate(samplerate, id); + } obs_property_t *bitrate = obs_properties_get(props.get(), "bitrate"); @@ -138,44 +141,51 @@ static void PopulateBitrateLists() * their bitrates will also be used as a fallback */ HandleEncoderProperties("ffmpeg_aac", fallbackBitrates); - if (fallbackBitrates.empty()) + if (fallbackBitrates.empty()) { blog(LOG_ERROR, "Could not enumerate fallback encoder " "bitrates"); + } ostringstream ss; - for (auto &bitrate : fallbackBitrates) + for (auto &bitrate : fallbackBitrates) { ss << "\n " << setw(3) << bitrate << " kbit/s:"; + } 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) + 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; HandleEncoderProperties(id, encoderBitrates[encoder]); - if (encoderBitrates[encoder].empty()) + if (encoderBitrates[encoder].empty()) { blog(LOG_ERROR, "Could not enumerate %s encoder " "bitrates", id); + } ostringstream ss; - for (auto &bitrate : encoderBitrates[encoder]) + for (auto &bitrate : encoderBitrates[encoder]) { ss << "\n " << setw(3) << bitrate << " kbit/s"; + } blog(LOG_DEBUG, "%s (%s) encoder bitrates:%s", EncoderName(id), id, ss.str().c_str()); } - if (encoderBitrates.empty() && fallbackBitrates.empty()) + if (encoderBitrates.empty() && fallbackBitrates.empty()) { blog(LOG_ERROR, "Could not enumerate any audio encoder " "bitrates"); + } }); } @@ -199,8 +209,9 @@ static void PopulateSimpleAACBitrateMap() struct obs_audio_info aoi; obs_get_audio_info(&aoi); - for (auto &bitrate : fallbackBitrates) + for (auto &bitrate : fallbackBitrates) { simpleAACBitrateMap[bitrate] = fallbackEncoder; + } const char *id = nullptr; for (size_t i = 0; obs_enum_encoder_types(i, &id); i++) { @@ -208,29 +219,36 @@ 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) + if (strcmp(GetCodec(id), "aac") != 0) { continue; + } std::string encoder = id; - if (encoderBitrates[encoder].empty()) + if (encoderBitrates[encoder].empty()) { continue; + } - for (auto &bitrate : encoderBitrates[encoder]) + for (auto &bitrate : encoderBitrates[encoder]) { simpleAACBitrateMap[bitrate] = encoder; + } } for (auto &encoder : encoders) { - if (encoder == fallbackEncoder) + if (encoder == fallbackEncoder) { continue; + } - if (strcmp(GetCodec(encoder.c_str()), "aac") != 0) + if (strcmp(GetCodec(encoder.c_str()), "aac") != 0) { continue; + } - for (auto &bitrate : encoderBitrates[encoder]) + for (auto &bitrate : encoderBitrates[encoder]) { simpleAACBitrateMap[bitrate] = encoder; + } } if (simpleAACBitrateMap.empty()) { @@ -240,9 +258,10 @@ static void PopulateSimpleAACBitrateMap() } ostringstream ss; - for (auto &entry : simpleAACBitrateMap) + for (auto &entry : simpleAACBitrateMap) { 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()); }); @@ -260,20 +279,24 @@ static void PopulateSimpleOpusBitrateMap() struct obs_audio_info aoi; obs_get_audio_info(&aoi); - for (auto &bitrate : fallbackBitrates) + for (auto &bitrate : fallbackBitrates) { simpleOpusBitrateMap[bitrate] = "ffmpeg_opus"; + } const char *id = nullptr; for (size_t i = 0; obs_enum_encoder_types(i, &id); i++) { - if (strcmp(GetCodec(id), "opus") != 0) + if (strcmp(GetCodec(id), "opus") != 0) { continue; + } std::string encoder = id; - if (encoderBitrates[encoder].empty()) + if (encoderBitrates[encoder].empty()) { continue; + } - for (auto &bitrate : encoderBitrates[encoder]) + for (auto &bitrate : encoderBitrates[encoder]) { simpleOpusBitrateMap[bitrate] = encoder; + } } if (simpleOpusBitrateMap.empty()) { @@ -283,9 +306,10 @@ static void PopulateSimpleOpusBitrateMap() } ostringstream ss; - for (auto &entry : simpleOpusBitrateMap) + for (auto &entry : simpleOpusBitrateMap) { 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()); }); @@ -307,8 +331,9 @@ const char *GetSimpleAACEncoderForBitrate(int bitrate) { auto &map_ = GetSimpleAACEncoderBitrateMap(); auto res = map_.find(bitrate); - if (res == end(map_)) + if (res == end(map_)) { return NULL; + } return res->second.c_str(); } @@ -316,8 +341,9 @@ const char *GetSimpleOpusEncoderForBitrate(int bitrate) { auto &map_ = GetSimpleOpusEncoderBitrateMap(); auto res = map_.find(bitrate); - if (res == end(map_)) + if (res == end(map_)) { return NULL; + } return res->second.c_str(); } @@ -330,20 +356,25 @@ static int FindClosestAvailableSimpleBitrate(int bitrate, const map val.first) { - if (val.first == bitrate) + if (val.first == bitrate) { return bitrate; + } - if (val.first < next && val.first > bitrate) + if (val.first < next && val.first > bitrate) { next = val.first; - if (val.first > prev && val.first < bitrate) + } + if (val.first > prev && val.first < bitrate) { prev = val.first; + } } } - if (next != INVALID_BITRATE) + if (next != INVALID_BITRATE) { return next; - if (prev != 0) + } + if (prev != 0) { return prev; + } return 192; } @@ -361,8 +392,9 @@ const std::vector &GetAudioEncoderBitrates(const char *id) { std::string encoder = id; PopulateBitrateLists(); - if (encoderBitrates[encoder].empty()) + if (encoderBitrates[encoder].empty()) { return fallbackBitrates; + } return encoderBitrates[encoder]; } @@ -376,19 +408,24 @@ int FindClosestAvailableAudioBitrate(const char *id, int bitrate) for (auto val : encoderBitrates[encoder].empty() ? fallbackBitrates : encoderBitrates[encoder]) { if (next > val) { - if (val == bitrate) + if (val == bitrate) { return bitrate; + } - if (val < next && val > bitrate) + if (val < next && val > bitrate) { next = val; - if (val > prev && val < bitrate) + } + if (val > prev && val < bitrate) { prev = val; + } } } - if (next != INVALID_BITRATE) + if (next != INVALID_BITRATE) { return next; - if (prev != 0) + } + if (prev != 0) { return prev; + } return 192; } diff --git a/frontend/utility/display-helpers.hpp b/frontend/utility/display-helpers.hpp index a3b5d4457a818a..d03f1bb0f0e934 100644 --- a/frontend/utility/display-helpers.hpp +++ b/frontend/utility/display-helpers.hpp @@ -120,8 +120,9 @@ static inline void InitSafeAreas(gs_vertbuffer_t **actionSafeMargin, gs_vertbuff static inline void RenderSafeAreas(gs_vertbuffer_t *vb, int cx, int cy) { - if (!vb) + if (!vb) { return; + } matrix4 transform; matrix4_identity(&transform); @@ -137,8 +138,9 @@ static inline void RenderSafeAreas(gs_vertbuffer_t *vb, int cx, int cy) gs_eparam_t *color = gs_effect_get_param_by_name(solid, "color"); gs_effect_set_color(color, OUTLINE_COLOR); - while (gs_effect_loop(solid, "Solid")) + while (gs_effect_loop(solid, "Solid")) { gs_draw(GS_LINESTRIP, 0, 0); + } gs_matrix_pop(); } diff --git a/frontend/utility/item-widget-helpers.cpp b/frontend/utility/item-widget-helpers.cpp index f6477e7e08a857..bb0088bd79124a 100644 --- a/frontend/utility/item-widget-helpers.cpp +++ b/frontend/utility/item-widget-helpers.cpp @@ -23,8 +23,9 @@ QListWidgetItem *TakeListItem(QListWidget *widget, int row) { QListWidgetItem *item = widget->item(row); - if (item) + if (item) { delete widget->itemWidget(item); + } return widget->takeItem(row); } @@ -46,8 +47,9 @@ void ClearListItems(QListWidget *widget) widget->setCurrentItem(nullptr, QItemSelectionModel::Clear); - for (int i = 0; i < widget->count(); i++) + for (int i = 0; i < widget->count(); i++) { delete widget->itemWidget(widget->item(i)); + } widget->clear(); #if QT_VERSION < QT_VERSION_CHECK(6, 4, 3) diff --git a/frontend/utility/models/whatsnew.hpp b/frontend/utility/models/whatsnew.hpp index df3a5fb9634f17..6350f4ccbf5ac0 100644 --- a/frontend/utility/models/whatsnew.hpp +++ b/frontend/utility/models/whatsnew.hpp @@ -33,10 +33,11 @@ template struct nlohmann::adl_serializer> { static void to_json(json &json, std::optional t) { - if (t) + if (t) { json = *t; - else + } else { json = nullptr; + } } }; diff --git a/frontend/utility/platform-windows.cpp b/frontend/utility/platform-windows.cpp index c6256b28c87123..1cb1ef09db8350 100644 --- a/frontend/utility/platform-windows.cpp +++ b/frontend/utility/platform-windows.cpp @@ -50,8 +50,9 @@ static inline bool check_path(const char *data, const char *path, string &output bool GetDataFilePath(const char *data, string &output) { - if (check_path(data, "data/obs-studio/", output)) + if (check_path(data, "data/obs-studio/", output)) { return true; + } return check_path(data, OBS_DATA_PATH "/obs-studio/", output); } @@ -72,20 +73,23 @@ 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); auto start = begin(buffer); auto end_ = end(buffer); decltype(start) separator; while ((separator = find(start, end_, 0)) != end_) { - if (result.size() == num) + if (result.size() == num) { break; + } char conv[MAX_PATH] = {}; os_wcs_to_utf8(&*start, separator - start, conv, MAX_PATH); @@ -107,14 +111,17 @@ vector GetPreferredLocales() for (auto &locale_pair : obs_locales) { auto &locale = locale_pair.first; - if (locale == windows.substr(0, locale.size())) + if (locale == windows.substr(0, locale.size())) { return locale; + } - if (lang_match.size()) + if (lang_match.size()) { continue; + } - if (locale.substr(0, 2) == windows.substr(0, 2)) + if (locale.substr(0, 2) == windows.substr(0, 2)) { lang_match = locale; + } } return lang_match; @@ -125,11 +132,13 @@ vector GetPreferredLocales() for (const string &locale : windows_locales) { string match = windows_to_obs(locale); - if (!match.size()) + if (!match.size()) { continue; + } - if (find(begin(result), end(result), match) != end(result)) + if (find(begin(result), end(result), match) != end(result)) { continue; + } result.emplace_back(match); } @@ -180,19 +189,21 @@ void SetAlwaysOnTop(QWidget *window, bool enable) void SetProcessPriority(const char *priority) { - if (!priority) + if (!priority) { return; + } - if (strcmp(priority, "High") == 0) + if (strcmp(priority, "High") == 0) { SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS); - else if (strcmp(priority, "AboveNormal") == 0) + } else if (strcmp(priority, "AboveNormal") == 0) { SetPriorityClass(GetCurrentProcess(), ABOVE_NORMAL_PRIORITY_CLASS); - else if (strcmp(priority, "Normal") == 0) + } else if (strcmp(priority, "Normal") == 0) { SetPriorityClass(GetCurrentProcess(), NORMAL_PRIORITY_CLASS); - else if (strcmp(priority, "BelowNormal") == 0) + } else if (strcmp(priority, "BelowNormal") == 0) { SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); - else if (strcmp(priority, "Idle") == 0) + } else if (strcmp(priority, "Idle") == 0) { SetPriorityClass(GetCurrentProcess(), IDLE_PRIORITY_CLASS); + } } void SetWin32DropStyle(QWidget *window) @@ -212,10 +223,11 @@ 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 + } else { supported = false; + } checked = true; } @@ -233,25 +245,30 @@ bool DisableAudioDucking(bool disable) HRESULT result = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (void **)&devEmum); - if (FAILED(result)) + if (FAILED(result)) { return false; + } result = devEmum->GetDefaultAudioEndpoint(eRender, eConsole, &device); - if (FAILED(result)) + if (FAILED(result)) { return false; + } result = device->Activate(__uuidof(IAudioSessionManager2), CLSCTX_INPROC_SERVER, nullptr, (void **)&sessionManager2); - if (FAILED(result)) + if (FAILED(result)) { return false; + } result = sessionManager2->GetAudioSessionControl(nullptr, 0, &sessionControl); - if (FAILED(result)) + if (FAILED(result)) { return false; + } result = sessionControl->QueryInterface(&sessionControl2); - if (FAILED(result)) + if (FAILED(result)) { return false; + } result = sessionControl2->SetDuckingPreference(disable); return SUCCEEDED(result); @@ -306,8 +323,9 @@ RunOnceMutex CheckIfAlreadyRunning(bool &already_running) if (wname) { wchar_t *temp = wname; while (*temp) { - if (!iswalnum(*temp)) + if (!iswalnum(*temp)) { *temp = L'_'; + } temp++; } } @@ -315,8 +333,9 @@ RunOnceMutex CheckIfAlreadyRunning(bool &already_running) HANDLE h = OpenMutexW(SYNCHRONIZE, false, wname.Get()); already_running = !!h; - if (!already_running) + if (!already_running) { h = CreateMutexW(nullptr, false, wname.Get()); + } RunOnceMutex rom(h ? new RunOnceMutexData(h) : nullptr); return rom; @@ -350,8 +369,9 @@ bool IsRunningOnWine() HMODULE nt; nt = GetModuleHandleW(L"ntdll"); - if (!nt) + if (!nt) { return false; + } func = (WINEGETVERSION)GetProcAddress(nt, "wine_get_version"); if (func) { @@ -403,8 +423,9 @@ void TaskbarOverlaySetStatus(TaskbarOverlayStatus status) if (!qicon.isNull()) { Q_GUI_EXPORT HICON qt_pixmapToWinHICON(const QPixmap &p); hicon = qt_pixmapToWinHICON(qicon.pixmap(GetSystemMetrics(SM_CXSMICON))); - if (!hicon) + if (!hicon) { return; + } } taskbarIcon->SetOverlayIcon(hwnd, hicon, nullptr); @@ -417,8 +438,9 @@ bool HighContrastEnabled() HIGHCONTRAST hc = {}; hc.cbSize = sizeof(HIGHCONTRAST); - if (SystemParametersInfo(SPI_GETHIGHCONTRAST, hc.cbSize, &hc, 0)) + if (SystemParametersInfo(SPI_GETHIGHCONTRAST, hc.cbSize, &hc, 0)) { return hc.dwFlags & HCF_HIGHCONTRASTON; + } return false; } diff --git a/frontend/utility/platform-x11.cpp b/frontend/utility/platform-x11.cpp index 61b874368e5e35..8c9657308c26c1 100644 --- a/frontend/utility/platform-x11.cpp +++ b/frontend/utility/platform-x11.cpp @@ -197,8 +197,9 @@ bool GetDataFilePath(const char *data, string &output) { char *data_path = getenv("OBS_DATA_PATH"); if (data_path != NULL) { - if (check_path(data, data_path, output)) + if (check_path(data, data_path, output)) { return true; + } } char *relative_data_path = os_get_executable_path_ptr("../" OBS_DATA_PATH "/obs-studio/"); @@ -212,11 +213,13 @@ bool GetDataFilePath(const char *data, string &output) } } - if (check_path(data, OBS_DATA_PATH "/obs-studio/", output)) + if (check_path(data, OBS_DATA_PATH "/obs-studio/", output)) { return true; + } - if (check_path(data, INSTALL_DATA_PATH, output)) + if (check_path(data, INSTALL_DATA_PATH, output)) { return true; + } return false; } @@ -230,19 +233,23 @@ vector GetPreferredLocales() { vector matched; string messages = setlocale(LC_MESSAGES, NULL); - if (!messages.size() || messages == "C" || messages == "POSIX") + if (!messages.size() || messages == "C" || messages == "POSIX") { return {}; + } - if (messages.size() > 2) + if (messages.size() > 2) { messages[2] = '-'; + } for (auto &locale_pair : GetLocaleNames()) { auto &locale = locale_pair.first; - if (locale == messages.substr(0, locale.size())) + if (locale == messages.substr(0, locale.size())) { return {locale}; + } - if (locale.substr(0, 2) == messages.substr(0, 2)) + if (locale.substr(0, 2) == messages.substr(0, 2)) { matched.push_back(locale); + } } return matched; @@ -257,10 +264,11 @@ void SetAlwaysOnTop(QWidget *window, bool enable) { Qt::WindowFlags flags = window->windowFlags(); - if (enable) + if (enable) { flags |= Qt::WindowStaysOnTopHint; - else + } else { flags &= ~Qt::WindowStaysOnTopHint; + } window->setWindowFlags(flags); window->show(); diff --git a/frontend/utility/system-info-posix.cpp b/frontend/utility/system-info-posix.cpp index 474830cfcef006..f31af9131d47c8 100644 --- a/frontend/utility/system-info-posix.cpp +++ b/frontend/utility/system-info-posix.cpp @@ -52,13 +52,15 @@ void trim_ws(std::string &s) { // Trim leading whitespace size_t pos = s.find_first_not_of(WHITE_SPACE); - if (pos != std::string::npos) + if (pos != std::string::npos) { s = s.substr(pos); + } // Trim trailing whitespace pos = s.find_last_not_of(WHITE_SPACE); - if (pos != std::string::npos) + if (pos != std::string::npos) { s = s.substr(0, pos + 1); + } } bool compare_match_strength(const drm_card_info &a, const drm_card_info &b) @@ -224,8 +226,9 @@ bool get_cpu_name(optional &proc_name) size_t pos = line.find(':'); if (pos != std::string::npos && line.at(pos + 1) != '\0') { physical_id = atoi(&line[pos + 1]); - if (physical_id == 0 && found_name) + if (physical_id == 0 && found_name) { break; + } } } } @@ -246,8 +249,9 @@ bool get_cpu_freq(uint32_t &cpu_freq) freq_file.open("/sys/devices/system/cpu/cpu0/cpufreq/base_frequency"); if (!freq_file.is_open()) { freq_file.open("/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq"); - if (!freq_file.is_open()) + if (!freq_file.is_open()) { return false; + } } if (getline(freq_file, line)) { diff --git a/frontend/utility/system-info-windows.cpp b/frontend/utility/system-info-windows.cpp index 5869fb989ff495..1679372485e0f2 100644 --- a/frontend/utility/system-info-windows.cpp +++ b/frontend/utility/system-info-windows.cpp @@ -19,8 +19,9 @@ static std::optional> system_gpu_data() UINT i; hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); - if (FAILED(hr)) + if (FAILED(hr)) { return std::nullopt; + } std::vector adapter_info; @@ -30,12 +31,14 @@ static std::optional> system_gpu_data() char driver_version[512] = ""; hr = adapter->GetDesc(&desc); - if (FAILED(hr)) + if (FAILED(hr)) { continue; + } /* ignore Microsoft's 'basic' renderer' */ - if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) + if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) { continue; + } os_wcs_to_utf8(desc.Description, 0, name, sizeof(name)); @@ -78,8 +81,9 @@ 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); - if (status != ERROR_SUCCESS) + if (status != ERROR_SUCCESS) { return; + } size = sizeof(data); status = RegQueryValueExW(key, L"ProcessorNameString", NULL, NULL, (LPBYTE)data, &size); @@ -91,8 +95,9 @@ static void get_processor_info(char **name, DWORD *speed) size = sizeof(*speed); status = RegQueryValueExW(key, L"~MHz", NULL, NULL, (LPBYTE)speed, &size); - if (status != ERROR_SUCCESS) + if (status != ERROR_SUCCESS) { *speed = 0; + } RegCloseKey(key); } @@ -106,8 +111,9 @@ static void get_processor_info(char **name, DWORD *speed) 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) + if (win_ver < 0xA00) { return std::nullopt; + } GoLiveApi::GamingFeatures gaming_features; @@ -171,22 +177,26 @@ static inline void get_reg_ver(struct win_version_info *ver) wchar_t str[MAX_SZ_LEN]; status = RegOpenKeyW(HKEY_LOCAL_MACHINE, WINVER_REG_KEY, &key); - if (status != ERROR_SUCCESS) + if (status != ERROR_SUCCESS) { return; + } size = sizeof(dw_val); status = RegQueryValueExW(key, L"CurrentMajorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size); - if (status == ERROR_SUCCESS) + if (status == ERROR_SUCCESS) { ver->major = (int)dw_val; + } status = RegQueryValueExW(key, L"CurrentMinorVersionNumber", NULL, NULL, (LPBYTE)&dw_val, &size); - if (status == ERROR_SUCCESS) + if (status == ERROR_SUCCESS) { ver->minor = (int)dw_val; + } status = RegQueryValueExW(key, L"UBR", NULL, NULL, (LPBYTE)&dw_val, &size); - if (status == ERROR_SUCCESS) + if (status == ERROR_SUCCESS) { ver->revis = (int)dw_val; + } if (get_reg_sz(key, L"CurrentBuildNumber", str, sizeof(str))) { ver->build = wcstol(str, NULL, 10); @@ -213,10 +223,12 @@ void system_info(GoLiveApi::Capabilities &capabilities) DWORD processorSpeed; char *processorName; get_processor_info(&processorName, &processorSpeed); - if (processorSpeed) + if (processorSpeed) { cpu_data.speed = processorSpeed; - if (processorName) + } + if (processorName) { cpu_data.name = processorName; + } bfree(processorName); } diff --git a/frontend/utility/undo_stack.cpp b/frontend/utility/undo_stack.cpp index 8ce5d6cc3801e3..e4ec160ae76dd0 100644 --- a/frontend/utility/undo_stack.cpp +++ b/frontend/utility/undo_stack.cpp @@ -34,8 +34,9 @@ void undo_stack::clear() 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()) + if (!is_enabled()) { return; + } while (undo_items.size() >= MAX_STACK_SIZE) { undo_redo_t item = undo_items.back(); @@ -67,8 +68,9 @@ void undo_stack::add_action(const QString &name, const undo_redo_cb &undo, const void undo_stack::undo() { - if (undo_items.size() == 0 || !is_enabled()) + if (undo_items.size() == 0 || !is_enabled()) { return; + } last_is_repeatable = false; @@ -90,8 +92,9 @@ void undo_stack::undo() void undo_stack::redo() { - if (redo_items.size() == 0 || !is_enabled()) + if (redo_items.size() == 0 || !is_enabled()) { return; + } last_is_repeatable = false; @@ -116,8 +119,9 @@ void undo_stack::enable_internal() last_is_repeatable = false; ui->actionMainUndo->setDisabled(false); - if (redo_items.size() > 0) + if (redo_items.size() > 0) { ui->actionMainRedo->setDisabled(false); + } } void undo_stack::disable_internal() @@ -131,29 +135,33 @@ void undo_stack::disable_internal() void undo_stack::enable() { enabled = true; - if (is_enabled()) + if (is_enabled()) { enable_internal(); + } } void undo_stack::disable() { - if (is_enabled()) + if (is_enabled()) { disable_internal(); + } enabled = false; } void undo_stack::push_disabled() { - if (is_enabled()) + if (is_enabled()) { disable_internal(); + } disable_refs++; } void undo_stack::pop_disabled() { disable_refs--; - if (is_enabled()) + if (is_enabled()) { enable_internal(); + } } void undo_stack::clear_redo() diff --git a/frontend/utility/update-helpers.cpp b/frontend/utility/update-helpers.cpp index 8d466e691862ed..1baf9448762b91 100644 --- a/frontend/utility/update-helpers.cpp +++ b/frontend/utility/update-helpers.cpp @@ -6,8 +6,9 @@ std::string vstrprintf(const char *format, va_list args) { va_list args2; - if (!format) + if (!format) { return std::string(); + } va_copy(args2, args); diff --git a/frontend/widgets/OBSBasic.cpp b/frontend/widgets/OBSBasic.cpp index e3277eb5f445dc..62fea81e0c1b12 100644 --- a/frontend/widgets/OBSBasic.cpp +++ b/frontend/widgets/OBSBasic.cpp @@ -113,12 +113,14 @@ static void AddExtraModulePaths() char *s; s = getenv("OBS_PLUGINS_PATH"); - if (s) + if (s) { plugins_path = s; + } s = getenv("OBS_PLUGINS_DATA_PATH"); - if (s) + if (s) { plugins_data_path = s; + } if (!plugins_path.empty() && !plugins_data_path.empty()) { #if defined(__APPLE__) @@ -133,8 +135,9 @@ static void AddExtraModulePaths() #endif } - if (portable_mode) + if (portable_mode) { return; + } char base_module_dir[512]; #if defined(_WIN32) @@ -145,8 +148,9 @@ static void AddExtraModulePaths() int ret = GetAppConfigPath(base_module_dir, sizeof(base_module_dir), "obs-studio/plugins/%module%"); #endif - if (ret <= 0) + if (ret <= 0) { return; + } string path = base_module_dir; #if defined(__APPLE__) @@ -193,8 +197,9 @@ static void SetSafeModuleNames() while (getline(modules_, module, '|')) { /* When only disallowing third-party plugins, still add * "unsafe" bundled modules to the safe list. */ - if (disable_3p_plugins || !unsafe_modules.count(module)) + if (disable_3p_plugins || !unsafe_modules.count(module)) { obs_add_safe_module(module.c_str()); + } } #endif } @@ -381,18 +386,20 @@ OBSBasic::OBSBasic(QWidget *parent) : OBSMainWindow(parent), undo_s(ui), ui(new bool sceneGrid = config_get_bool(App()->GetUserConfig(), "BasicWindow", "gridMode"); ui->scenes->SetGridMode(sceneGrid); - if (sceneGrid) + if (sceneGrid) { ui->actionSceneGridMode->setChecked(true); - else + } else { ui->actionSceneListMode->setChecked(true); + } ui->scenes->setItemDelegate(new SceneRenameDelegate(ui->scenes)); auto displayResize = [this]() { struct obs_video_info ovi; - if (obs_get_video_info(&ovi)) + if (obs_get_video_info(&ovi)) { ResizePreview(ovi.base_width, ovi.base_height); + } UpdateContextBarVisibility(); UpdatePreviewControls(); @@ -681,20 +688,22 @@ bool OBSBasic::InitBasicConfigDefaults() 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"); - if (!has_new_key && !has_old_key) + if (!has_new_key && !has_old_key) { return; + } string old_format = config_get_string(activeConfiguration, section, has_new_key ? "RecFormat2" : "RecFormat"); string new_format = old_format; - if (old_format == "ts") + if (old_format == "ts") { new_format = "mpegts"; - else if (old_format == "m3u8") + } else if (old_format == "m3u8") { new_format = "hls"; - else if (old_format == "fmp4") + } else if (old_format == "fmp4") { new_format = "fragmented_mp4"; - else if (old_format == "fmov") + } else if (old_format == "fmov") { new_format = "fragmented_mov"; + } if (new_format != old_format || !has_new_key) { config_set_string(activeConfiguration, section, "RecFormat2", new_format.c_str()); @@ -875,10 +884,11 @@ void OBSBasic::InitBasicConfigDefaults2() useNV ? SIMPLE_ENCODER_NVENC : SIMPLE_ENCODER_X264); const char *aac_default = "ffmpeg_aac"; - if (EncoderAvailable("CoreAudio_AAC")) + if (EncoderAvailable("CoreAudio_AAC")) { aac_default = "CoreAudio_AAC"; - else if (EncoderAvailable("libfdk_aac")) + } 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); @@ -977,10 +987,12 @@ void OBSBasic::OBSInit() { ProfileScope("OBSBasic::OBSInit"); - if (!InitBasicConfig()) + if (!InitBasicConfig()) { throw "Failed to load basic.ini"; - if (!ResetAudio()) + } + if (!ResetAudio()) { throw "Failed to initialize audio"; + } int ret = 0; @@ -994,8 +1006,9 @@ void OBSBasic::OBSInit() case OBS_VIDEO_INVALID_PARAM: throw "Failed to initialize video: Invalid parameters"; default: - if (ret != OBS_VIDEO_SUCCESS) + if (ret != OBS_VIDEO_SUCCESS) { throw UNKNOWN_ERROR; + } } /* load audio monitoring */ @@ -1055,8 +1068,9 @@ void OBSBasic::OBSInit() blog(LOG_INFO, STARTUP_SEPARATOR); - if (!InitService()) + if (!InitService()) { throw "Failed to initialize service"; + } ResetOutputs(); CreateHotkeys(); @@ -1092,8 +1106,9 @@ void OBSBasic::OBSInit() bool contextVisible = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ShowContextToolbars"); ui->toggleContextBar->setChecked(contextVisible); ui->contextContainer->setVisible(contextVisible); - if (contextVisible) + if (contextVisible) { UpdateContextBar(true); + } UpdateEditMenu(); { @@ -1128,11 +1143,12 @@ void OBSBasic::OBSInit() previewEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "PreviewEnabled"); - if (!previewEnabled && !IsPreviewProgramMode()) + if (!previewEnabled && !IsPreviewProgramMode()) { QMetaObject::invokeMethod(this, "EnablePreviewDisplay", Qt::QueuedConnection, Q_ARG(bool, previewEnabled)); - else if (!previewEnabled && IsPreviewProgramMode()) + } else if (!previewEnabled && IsPreviewProgramMode()) { QMetaObject::invokeMethod(this, "EnablePreviewDisplay", Qt::QueuedConnection, Q_ARG(bool, true)); + } disableSaving--; @@ -1140,8 +1156,9 @@ void OBSBasic::OBSInit() obs_display_add_draw_callback(window->GetDisplay(), OBSBasic::RenderMain, this); struct obs_video_info ovi; - if (obs_get_video_info(&ovi)) + if (obs_get_video_info(&ovi)) { ResizePreview(ovi.base_width, ovi.base_height); + } }; connect(ui->preview, &OBSQTDisplay::DisplayCreated, this, addDisplay); @@ -1156,8 +1173,9 @@ void OBSBasic::OBSInit() #ifdef _WIN32 SetWin32DropStyle(this); - if (!hideWindowOnStart) + if (!hideWindowOnStart) { show(); + } #endif bool alwaysOnTop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "AlwaysOnTop"); @@ -1172,15 +1190,17 @@ void OBSBasic::OBSInit() SetAlwaysOnTop(this, true); ui->actionAlwaysOnTop->setChecked(true); } else if (isWayland) { - if (opt_always_on_top) + if (opt_always_on_top) { blog(LOG_INFO, "Always On Top not available on Wayland, ignoring."); + } ui->actionAlwaysOnTop->setEnabled(false); ui->actionAlwaysOnTop->setVisible(false); } #ifndef _WIN32 - if (!hideWindowOnStart) + if (!hideWindowOnStart) { show(); + } #endif // Set up Audio Mixer dock @@ -1215,8 +1235,9 @@ void OBSBasic::OBSInit() #ifdef YOUTUBE_ENABLED /* setup YouTube app dock */ - if (YouTubeAppDock::IsYTServiceSelected()) + if (YouTubeAppDock::IsYTServiceSelected()) { NewYouTubeAppDock(); + } #endif const char *dockStateStr = config_get_string(App()->GetUserConfig(), "BasicWindow", "DockState"); @@ -1225,8 +1246,9 @@ void OBSBasic::OBSInit() on_resetDocks_triggered(true); } else { QByteArray dockState = QByteArray::fromBase64(QByteArray(dockStateStr)); - if (!restoreState(dockState)) + if (!restoreState(dockState)) { on_resetDocks_triggered(true); + } } bool pre23Defaults = config_get_bool(App()->GetUserConfig(), "General", "Pre23Defaults"); @@ -1265,8 +1287,9 @@ void OBSBasic::OBSInit() config_save_safe(App()->GetUserConfig(), "tmp", nullptr); } - if (!first_run && !has_last_version && !Active()) + if (!first_run && !has_last_version && !Active()) { QMetaObject::invokeMethod(this, "on_autoConfigure_triggered", Qt::QueuedConnection); + } #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. */ @@ -1280,8 +1303,9 @@ void OBSBasic::OBSInit() emit userSettingChanged("BasicWindow", "VerticalVolumeControl"); - if (config_get_bool(activeConfiguration, "General", "OpenStatsOnStartup")) + if (config_get_bool(activeConfiguration, "General", "OpenStatsOnStartup")) { on_stats_triggered(); + } OBSBasicStats::InitializeValues(); @@ -1341,8 +1365,9 @@ void OBSBasic::OBSInit() UpdatePreviewProgramIndicators(); OnFirstLoad(); - if (!hideWindowOnStart) + if (!hideWindowOnStart) { activateWindow(); + } /* ------------------------------------------- */ /* display warning message for failed modules */ @@ -1381,8 +1406,9 @@ void OBSBasic::OnFirstLoad() bool showLogViewerOnStartup = config_get_bool(App()->GetUserConfig(), "LogViewer", "ShowLogStartup"); - if (showLogViewerOnStartup) + if (showLogViewerOnStartup) { on_actionViewCurrentLog_triggered(); + } } OBSBasic::~OBSBasic() @@ -1400,11 +1426,13 @@ void OBSBasic::applicationShutdown() noexcept QApplication::sendPostedEvents(nullptr, QEvent::DeferredDelete); #endif - if (updateCheckThread && updateCheckThread->isRunning()) + if (updateCheckThread && updateCheckThread->isRunning()) { updateCheckThread->wait(); + } - if (patronJsonThread && patronJsonThread->isRunning()) + if (patronJsonThread && patronJsonThread->isRunning()) { patronJsonThread->wait(); + } delete screenshotData; delete previewProjectorSource; @@ -1497,32 +1525,34 @@ static inline enum obs_scale_type GetScaleType(ConfigFile &activeConfiguration) { const char *scaleTypeStr = config_get_string(activeConfiguration, "Video", "ScaleType"); - if (astrcmpi(scaleTypeStr, "bilinear") == 0) + if (astrcmpi(scaleTypeStr, "bilinear") == 0) { return OBS_SCALE_BILINEAR; - else if (astrcmpi(scaleTypeStr, "lanczos") == 0) + } else if (astrcmpi(scaleTypeStr, "lanczos") == 0) { return OBS_SCALE_LANCZOS; - else if (astrcmpi(scaleTypeStr, "area") == 0) + } else if (astrcmpi(scaleTypeStr, "area") == 0) { return OBS_SCALE_AREA; - else + } else { return OBS_SCALE_BICUBIC; + } } static inline enum video_format GetVideoFormatFromName(const char *name) { - if (astrcmpi(name, "I420") == 0) + if (astrcmpi(name, "I420") == 0) { return VIDEO_FORMAT_I420; - else if (astrcmpi(name, "NV12") == 0) + } else if (astrcmpi(name, "NV12") == 0) { return VIDEO_FORMAT_NV12; - else if (astrcmpi(name, "I444") == 0) + } else if (astrcmpi(name, "I444") == 0) { return VIDEO_FORMAT_I444; - else if (astrcmpi(name, "I010") == 0) + } else if (astrcmpi(name, "I010") == 0) { return VIDEO_FORMAT_I010; - else if (astrcmpi(name, "P010") == 0) + } else if (astrcmpi(name, "P010") == 0) { return VIDEO_FORMAT_P010; - else if (astrcmpi(name, "P216") == 0) + } else if (astrcmpi(name, "P216") == 0) { return VIDEO_FORMAT_P216; - else if (astrcmpi(name, "P416") == 0) + } else if (astrcmpi(name, "P416") == 0) { return VIDEO_FORMAT_P416; + } #if 0 //currently unsupported else if (astrcmpi(name, "YVYU") == 0) return VIDEO_FORMAT_YVYU; @@ -1531,29 +1561,32 @@ static inline enum video_format GetVideoFormatFromName(const char *name) else if (astrcmpi(name, "UYVY") == 0) return VIDEO_FORMAT_UYVY; #endif - else + else { return VIDEO_FORMAT_BGRA; + } } static inline enum video_colorspace GetVideoColorSpaceFromName(const char *name) { enum video_colorspace colorspace = VIDEO_CS_SRGB; - if (strcmp(name, "601") == 0) + if (strcmp(name, "601") == 0) { colorspace = VIDEO_CS_601; - else if (strcmp(name, "709") == 0) + } else if (strcmp(name, "709") == 0) { colorspace = VIDEO_CS_709; - else if (strcmp(name, "2100PQ") == 0) + } else if (strcmp(name, "2100PQ") == 0) { colorspace = VIDEO_CS_2100_PQ; - else if (strcmp(name, "2100HLG") == 0) + } else if (strcmp(name, "2100HLG") == 0) { colorspace = VIDEO_CS_2100_HLG; + } return colorspace; } int OBSBasic::ResetVideo() { - if (outputHandler && outputHandler->Active()) + if (outputHandler && outputHandler->Active()) { return OBS_VIDEO_CURRENTLY_ACTIVE; + } ProfileScope("OBSBasic::ResetVideo"); @@ -1600,8 +1633,9 @@ int OBSBasic::ResetVideo() if (ret == OBS_VIDEO_SUCCESS) { ResizePreview(ovi.base_width, ovi.base_height); - if (program) + 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 = @@ -1643,20 +1677,21 @@ bool OBSBasic::ResetAudio() const char *channelSetupStr = config_get_string(activeConfiguration, "Audio", "ChannelSetup"); - if (strcmp(channelSetupStr, "Mono") == 0) + if (strcmp(channelSetupStr, "Mono") == 0) { ai.speakers = SPEAKERS_MONO; - else if (strcmp(channelSetupStr, "2.1") == 0) + } else if (strcmp(channelSetupStr, "2.1") == 0) { ai.speakers = SPEAKERS_2POINT1; - else if (strcmp(channelSetupStr, "4.0") == 0) + } else if (strcmp(channelSetupStr, "4.0") == 0) { ai.speakers = SPEAKERS_4POINT0; - else if (strcmp(channelSetupStr, "4.1") == 0) + } else if (strcmp(channelSetupStr, "4.1") == 0) { ai.speakers = SPEAKERS_4POINT1; - else if (strcmp(channelSetupStr, "5.1") == 0) + } else if (strcmp(channelSetupStr, "5.1") == 0) { ai.speakers = SPEAKERS_5POINT1; - else if (strcmp(channelSetupStr, "7.1") == 0) + } else if (strcmp(channelSetupStr, "7.1") == 0) { ai.speakers = SPEAKERS_7POINT1; - else + } else { ai.speakers = SPEAKERS_STEREO; + } bool lowLatencyAudioBuffering = config_get_bool(App()->GetUserConfig(), "Audio", "LowLatencyAudioBuffering"); if (lowLatencyAudioBuffering) { @@ -1757,11 +1792,13 @@ void OBSBasic::changeEvent(QEvent *event) return; } - if (previewEnabled) + if (previewEnabled) { EnablePreviewDisplay(false); + } } else if (stateEvent->oldState() & Qt::WindowMinimized && isVisible()) { - if (previewEnabled) + if (previewEnabled) { EnablePreviewDisplay(true); + } } } } @@ -1825,16 +1862,18 @@ void OBSBasic::GetConfigFPS(uint32_t &num, uint32_t &den) const { uint32_t type = config_get_uint(activeConfiguration, "Video", "FPSType"); - if (type == 1) //"Integer" + if (type == 1) { //"Integer" GetFPSInteger(num, den); - else if (type == 2) //"Fraction" + } else if (type == 2) { //"Fraction" GetFPSFraction(num, den); + } /* * else if (false) //"Nanoseconds", currently not implemented * GetFPSNanoseconds(num, den); */ - else + else { GetFPSCommon(num, den); + } } config_t *OBSBasic::Config() const @@ -1944,20 +1983,26 @@ void OBSBasic::closeWindow() * To avoid such a case, destroy displays earlier than others such as * deleting browser docks. */ ui->preview->DestroyDisplay(); - if (program) + if (program) { program->DestroyDisplay(); + } - if (outputHandler->VirtualCamActive()) + if (outputHandler->VirtualCamActive()) { outputHandler->StopVirtualCam(); + } - if (introCheckThread) + if (introCheckThread) { introCheckThread->wait(); - if (whatsNewInitThread) + } + if (whatsNewInitThread) { whatsNewInitThread->wait(); - if (updateCheckThread) + } + if (updateCheckThread) { updateCheckThread->wait(); - if (logUploadThread) + } + if (logUploadThread) { logUploadThread->wait(); + } if (devicePropertiesThread && devicePropertiesThread->isRunning()) { devicePropertiesThread->wait(); devicePropertiesThread.reset(); @@ -2031,8 +2076,9 @@ void OBSBasic::UpdateEditMenu() continue; } OBSSourceAutoRelease strong = obs_weak_source_get_source(weak.Get()); - if (allowPastingDuplicate && obs_source_get_output_flags(strong) & OBS_SOURCE_DO_NOT_DUPLICATE) + if (allowPastingDuplicate && obs_source_get_output_flags(strong) & OBS_SOURCE_DO_NOT_DUPLICATE) { allowPastingDuplicate = false; + } } int videoCount = 0; @@ -2042,11 +2088,13 @@ void OBSBasic::UpdateEditMenu() OBSSource source = obs_sceneitem_get_source(item); const uint32_t flags = obs_source_get_output_flags(source); const bool hasVideo = (flags & OBS_SOURCE_VIDEO) != 0; - if (hasVideo && !obs_sceneitem_locked(item)) + if (hasVideo && !obs_sceneitem_locked(item)) { canTransformMultiple = true; + } - if (hasVideo) + if (hasVideo) { videoCount++; + } } const bool canTransformSingle = videoCount == 1 && totalCount == 1; @@ -2088,14 +2136,17 @@ void OBSBasic::UpdateTitleBar() const char *sceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection"); name << "OBS "; - if (previewProgramMode) + if (previewProgramMode) { name << "Studio "; + } name << App()->GetVersionString(false); - if (safe_mode) + if (safe_mode) { name << " (" << Str("TitleBar.SafeMode") << ")"; - if (App()->IsPortableMode()) + } + if (App()->IsPortableMode()) { name << " - " << Str("TitleBar.PortableMode"); + } name << " - " << Str("TitleBar.Profile") << ": " << profile; name << " - " << Str("TitleBar.Scenes") << ": " << sceneCollection; @@ -2110,32 +2161,36 @@ OBSBasic *OBSBasic::Get() void OBSBasic::UpdatePatronJson(const QString &text, const QString &error) { - if (!error.isEmpty()) + if (!error.isEmpty()) { return; + } patronJson = QT_TO_UTF8(text); } void OBSBasic::SetDisplayAffinity(QWindow *window) { - if (!SetDisplayAffinitySupported()) + if (!SetDisplayAffinitySupported()) { return; + } 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) + if (window->property("isOBSProjectorWindow") == true) { return; + } #ifdef _WIN32 HWND hwnd = (HWND)window->winId(); DWORD curAffinity; if (GetWindowDisplayAffinity(hwnd, &curAffinity)) { - if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE) + if (hideFromCapture && curAffinity != WDA_EXCLUDEFROMCAPTURE) { SetWindowDisplayAffinity(hwnd, WDA_EXCLUDEFROMCAPTURE); - else if (!hideFromCapture && curAffinity != WDA_NONE) + } else if (!hideFromCapture && curAffinity != WDA_NONE) { SetWindowDisplayAffinity(hwnd, WDA_NONE); + } } #else @@ -2147,8 +2202,9 @@ void OBSBasic::SetDisplayAffinity(QWindow *window) void OBSBasic::OnEvent(enum obs_frontend_event event) { - if (api) + if (api) { api->on_event(event); + } } OBSPromptResult OBSBasic::PromptForName(const OBSPromptRequest &request, const OBSPromptCallback &callback) diff --git a/frontend/widgets/OBSBasic.hpp b/frontend/widgets/OBSBasic.hpp index 2561a7c107fc47..d5a6fd78339b8e 100644 --- a/frontend/widgets/OBSBasic.hpp +++ b/frontend/widgets/OBSBasic.hpp @@ -160,15 +160,17 @@ template static void SetOBSRef(QListWidgetItem *item, T &&val) static inline void UpdateProcessPriority() { const char *priority = config_get_string(App()->GetAppConfig(), "General", "ProcessPriority"); - if (priority && strcmp(priority, "Normal") != 0) + if (priority && strcmp(priority, "Normal") != 0) { SetProcessPriority(priority); + } } static inline void ClearProcessPriority() { const char *priority = config_get_string(App()->GetAppConfig(), "General", "ProcessPriority"); - if (priority && strcmp(priority, "Normal") != 0) + if (priority && strcmp(priority, "Normal") != 0) { SetProcessPriority("Normal"); + } } #else #define UpdateProcessPriority() \ @@ -758,8 +760,9 @@ public slots: inline void EnableOutputs(bool enable) { if (enable) { - if (--disableOutputsRef < 0) + if (--disableOutputsRef < 0) { disableOutputsRef = 0; + } } else { disableOutputsRef++; } diff --git a/frontend/widgets/OBSBasicControls.cpp b/frontend/widgets/OBSBasicControls.cpp index 5473fcdae55f1e..81d8ad80c4860e 100644 --- a/frontend/widgets/OBSBasicControls.cpp +++ b/frontend/widgets/OBSBasicControls.cpp @@ -144,8 +144,9 @@ void OBSBasicControls::StreamingStopped(bool withDelay) ui->streamButton->setText(QTStr("Basic.Main.StartStreaming")); if (withDelay) { - if (!ui->streamButton->menu()) + if (!ui->streamButton->menu()) { ui->streamButton->setMenu(streamButtonMenu.get()); + } startStreamAction->setVisible(true); stopStreamAction->setVisible(false); @@ -167,8 +168,9 @@ void OBSBasicControls::BroadcastStreamActive() void OBSBasicControls::BroadcastStreamStarted(bool autoStop) { ui->broadcastButton->setText(QTStr(autoStop ? "Basic.Main.AutoStopEnabled" : "Basic.Main.StopBroadcast")); - if (autoStop) + if (autoStop) { ui->broadcastButton->setEnabled(false); + } ui->broadcastButton->setProperty("broadcastState", "active"); ui->broadcastButton->style()->unpolish(ui->broadcastButton); diff --git a/frontend/widgets/OBSBasicPreview.cpp b/frontend/widgets/OBSBasicPreview.cpp index 935fb9db0506c4..4fcd3f5423c958 100644 --- a/frontend/widgets/OBSBasicPreview.cpp +++ b/frontend/widgets/OBSBasicPreview.cpp @@ -21,14 +21,18 @@ OBSBasicPreview::~OBSBasicPreview() { obs_enter_graphics(); - if (overflow) + if (overflow) { gs_texture_destroy(overflow); - if (rectFill) + } + if (rectFill) { gs_vertexbuffer_destroy(rectFill); - if (circleFill) + } + if (circleFill) { gs_vertexbuffer_destroy(circleFill); - if (stripedLineEffect) + } + if (stripedLineEffect) { gs_effect_destroy(stripedLineEffect); + } obs_leave_graphics(); } @@ -120,10 +124,12 @@ static bool FindItemAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, void vec3 pos3; vec3 pos3_; - if (!SceneItemHasVideo(item)) + if (!SceneItemHasVideo(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; + } vec3_set(&pos3, data->pos.x, data->pos.y, 0.0f); @@ -136,10 +142,11 @@ static bool FindItemAtPos(obs_scene_t * /* scene */, obs_sceneitem_t *item, void 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) + if (data->item) { return false; - else + } else { data->selectBelow = false; + } } data->item = item; @@ -179,8 +186,9 @@ vec3 OBSBasicPreview::GetSnapOffset(const vec3 &tl, const vec3 &br) vec3_zero(&clampOffset); const bool snap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled"); - if (snap == false) + 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"); @@ -191,26 +199,32 @@ vec3 OBSBasicPreview::GetSnapOffset(const vec3 &tl, const vec3 &br) const float centerY = br.y - (br.y - tl.y) / 2.0f; // Left screen edge. - if (screenSnap && fabsf(tl.x) < clampDist) + 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 && - fabsf(screenSize.x / 2.0f - centerX) < clampDist) + fabsf(screenSize.x / 2.0f - centerX) < clampDist) { clampOffset.x = screenSize.x / 2.0f - centerX; + } // Top screen edge. - if (screenSnap && fabsf(tl.y) < clampDist) + 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 && - fabsf(screenSize.y / 2.0f - centerY) < clampDist) + fabsf(screenSize.y / 2.0f - centerY) < clampDist) { clampOffset.y = screenSize.y / 2.0f - centerY; + } return clampOffset; } @@ -220,8 +234,9 @@ OBSSceneItem OBSBasicPreview::GetItemAtPos(const vec2 &pos, bool selectBelow) OBSBasic *main = OBSBasic::Get(); OBSScene scene = main->GetCurrentScene(); - if (!scene) + if (!scene) { return OBSSceneItem(); + } SceneFindData data(pos, selectBelow); obs_scene_enum_items(scene, FindItemAtPos, &data); @@ -235,8 +250,9 @@ static bool CheckItemSelected(obs_scene_t * /* scene */, obs_sceneitem_t *item, vec3 transformedPos; vec3 pos3; - if (!SceneItemHasVideo(item)) + if (!SceneItemHasVideo(item)) { return true; + } if (obs_sceneitem_is_group(item)) { data->group = item; obs_sceneitem_group_enum_items(item, CheckItemSelected, param); @@ -276,8 +292,9 @@ bool OBSBasicPreview::SelectedAtPos(const vec2 &pos) OBSBasic *main = OBSBasic::Get(); OBSScene scene = main->GetCurrentScene(); - if (!scene) + if (!scene) { return false; + } SceneFindData data(pos, false); obs_scene_enum_items(scene, CheckItemSelected, &data); @@ -438,8 +455,9 @@ void OBSBasicPreview::GetStretchHandleData(const vec2 &pos, bool ignoreGroup) OBSBasic *main = OBSBasic::Get(); OBSScene scene = main->GetCurrentScene(); - if (!scene) + if (!scene) { return; + } float scale = main->previewScale / main->GetDevicePixelRatio(); vec2 scaled_pos = pos; @@ -531,10 +549,11 @@ void OBSBasicPreview::wheelEvent(QWheelEvent *event) if (scrollMode && IsFixedScaling()) { const int delta = event->angleDelta().y(); if (delta != 0) { - if (delta > 0) + if (delta > 0) { increaseScalingLevel(); - else + } else { decreaseScalingLevel(); + } } } @@ -573,19 +592,22 @@ 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) + if (event->button() == Qt::LeftButton) { mouseDown = true; + } { std::lock_guard lock(selectMutex); selectedItems.clear(); } - if (altDown) + if (altDown) { cropping = true; + } if (altDown || shiftDown || ctrlDown) { vec2 s; @@ -619,10 +641,12 @@ void OBSBasicPreview::UpdateCursor(uint32_t &flags) return; } - if (!flags && (cursor().shape() != Qt::OpenHandCursor || !scrollMode)) + if (!flags && (cursor().shape() != Qt::OpenHandCursor || !scrollMode)) { unsetCursor(); - if ((cursor().shape() != Qt::ArrowCursor) || flags == 0) + } + if ((cursor().shape() != Qt::ArrowCursor) || flags == 0) { return; + } if (flags & ITEM_ROT) { setCursor(Qt::OpenHandCursor); @@ -633,16 +657,19 @@ void OBSBasicPreview::UpdateCursor(uint32_t &flags) vec2 scale; obs_sceneitem_get_scale(stretchItem, &scale); - if (rotation < 0.0f) + if (rotation < 0.0f) { rotation = 360.0f + rotation; + } int octant = int(std::round(rotation / 45.0f)); bool isCorner = (flags & (flags - 1)) != 0; - if ((scale.x < 0.0f) && isCorner) + if ((scale.x < 0.0f) && isCorner) { flags ^= ITEM_LEFT | ITEM_RIGHT; - if ((scale.y < 0.0f) && isCorner) + } + if ((scale.y < 0.0f) && isCorner) { flags ^= ITEM_TOP | ITEM_BOTTOM; + } if (octant % 4 >= 2) { if (isCorner) { @@ -661,21 +688,23 @@ void OBSBasicPreview::UpdateCursor(uint32_t &flags) } } - 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) + } else if (flags & ITEM_LEFT || flags & ITEM_RIGHT) { setCursor(Qt::SizeHorCursor); - else if (flags & ITEM_TOP || flags & ITEM_BOTTOM) + } else if (flags & ITEM_TOP || flags & ITEM_BOTTOM) { setCursor(Qt::SizeVerCursor); + } } static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { obs_sceneitem_t *selectedItem = static_cast(param); - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, select_one, param); + } obs_sceneitem_select(item, (selectedItem == item)); @@ -695,8 +724,9 @@ void OBSBasicPreview::DoSelect(const vec2 &pos) void OBSBasicPreview::DoCtrlSelect(const vec2 &pos) { OBSSceneItem item = GetItemAtPos(pos, false); - if (!item) + if (!item) { return; + } bool selected = obs_sceneitem_selected(item); obs_sceneitem_select(item, !selected); @@ -706,16 +736,18 @@ void OBSBasicPreview::ProcessClick(const vec2 &pos) { Qt::KeyboardModifiers modifiers = QGuiApplication::keyboardModifiers(); - if (modifiers & Qt::ControlModifier) + if (modifiers & Qt::ControlModifier) { DoCtrlSelect(pos); - else + } else { DoSelect(pos); + } } void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) { - if (scrollMode) + if (scrollMode) { setCursor(Qt::OpenHandCursor); + } if (locked) { OBSQTDisplay::mouseReleaseEvent(event); @@ -725,8 +757,9 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) if (mouseDown) { vec2 pos = GetMouseEventPos(event); - if (!mouseMoved) + if (!mouseMoved) { ProcessClick(pos); + } if (selectionBox) { Qt::KeyboardModifiers modifiers = QGuiApplication::keyboardModifiers(); @@ -789,10 +822,11 @@ void OBSBasicPreview::mouseReleaseEvent(QMouseEvent *event) if (wrapper && rwrapper) { std::string undo_data(obs_data_get_json(wrapper)); std::string redo_data(obs_data_get_json(rwrapper)); - if (changed && undo_data.compare(redo_data) != 0) + if (changed && undo_data.compare(redo_data) != 0) { main->undo_s.add_action( QTStr("Undo.Transform").arg(obs_source_get_name(main->GetCurrentSceneSource())), undo_redo, undo_redo, undo_data, redo_data); + } } wrapper = nullptr; @@ -840,8 +874,9 @@ static bool AddItemBounds(obs_scene_t * /* scene */, obs_sceneitem_t *item, void add_bounds(); } } - if (!obs_sceneitem_selected(item)) + if (!obs_sceneitem_selected(item)) { return true; + } matrix4 boxTransform; obs_sceneitem_get_box_transform(item, &boxTransform); @@ -864,8 +899,9 @@ static bool GetSourceSnapOffset(obs_scene_t * /* scene */, obs_sceneitem_t *item { OffsetData *data = static_cast(param); - if (obs_sceneitem_selected(item)) + if (obs_sceneitem_selected(item)) { return true; + } matrix4 boxTransform; obs_sceneitem_get_box_transform(item, &boxTransform); @@ -923,8 +959,9 @@ void OBSBasicPreview::SnapItemMovement(vec2 &offset) const bool snap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SnappingEnabled"); const bool sourcesSnap = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SourceSnapping"); - if (snap == false) + if (snap == false) { return; + } if (sourcesSnap == false) { offset.x += snapOffset.x; offset.y += snapOffset.y; @@ -953,8 +990,9 @@ void OBSBasicPreview::SnapItemMovement(vec2 &offset) static bool move_items(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { - if (obs_sceneitem_locked(item)) + if (obs_sceneitem_locked(item)) { return true; + } bool selected = obs_sceneitem_selected(item); vec2 *offset = static_cast(param); @@ -991,8 +1029,9 @@ void OBSBasicPreview::MoveItems(const vec2 &pos) vec2_sub(&offset, &pos, &startPos); vec2_sub(&moveOffset, &offset, &lastMoveOffset); - if (!(modifiers & Qt::ControlModifier)) + if (!(modifiers & Qt::ControlModifier)) { SnapItemMovement(moveOffset); + } vec2_add(&lastMoveOffset, &lastMoveOffset, &moveOffset); @@ -1024,15 +1063,17 @@ static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, float 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)) + 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)) + 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; y3 = transform.t.y + transform.x.y; @@ -1040,8 +1081,9 @@ static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, float 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)) + 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; y3 = transform.t.y + transform.y.y; @@ -1049,8 +1091,9 @@ static bool IntersectBox(matrix4 transform, float x1, float x2, float y1, float 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)) + IntersectLine(x2, x2, x3, x4, y1, y2, y3, y4) || IntersectLine(x1, x2, x3, x4, y2, y2, y3, y4)) { return true; + } return false; } @@ -1060,8 +1103,9 @@ bool OBSBasicPreview::FindSelected(obs_scene_t *, obs_sceneitem_t *item, void *p { SceneFindBoxData *data = static_cast(param); - if (obs_sceneitem_selected(item)) + if (obs_sceneitem_selected(item)) { data->sceneItems.push_back(item); + } return true; } @@ -1084,12 +1128,15 @@ static bool FindItemsInBox(obs_scene_t * /* scene */, obs_sceneitem_t *item, voi const float y1 = pos_min.y; const float y2 = pos_max.y; - if (!SceneItemHasVideo(item)) + if (!SceneItemHasVideo(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; - if (!obs_sceneitem_visible(item)) + } + if (!obs_sceneitem_visible(item)) { return true; + } vec3_set(&pos3, data->pos.x, data->pos.y, 0.0f); @@ -1155,11 +1202,13 @@ void OBSBasicPreview::BoxItems(const vec2 &startPos, const vec2 &pos) OBSBasic *main = OBSBasic::Get(); OBSScene scene = main->GetCurrentScene(); - if (!scene) + if (!scene) { return; + } - if (cursor().shape() != Qt::CrossCursor) + if (cursor().shape() != Qt::CrossCursor) { setCursor(Qt::CrossCursor); + } SceneFindBoxData data(startPos, pos); obs_scene_enum_items(scene, FindItemsInBox, &data); @@ -1175,19 +1224,21 @@ vec3 OBSBasicPreview::CalculateStretchPos(const vec3 &tl, const vec3 &br) vec3_zero(&pos); - if (alignment & OBS_ALIGN_LEFT) + if (alignment & OBS_ALIGN_LEFT) { pos.x = tl.x; - else if (alignment & OBS_ALIGN_RIGHT) + } else if (alignment & OBS_ALIGN_RIGHT) { pos.x = br.x; - else + } else { pos.x = (br.x - tl.x) * 0.5f + tl.x; + } - if (alignment & OBS_ALIGN_TOP) + if (alignment & OBS_ALIGN_TOP) { pos.y = tl.y; - else if (alignment & OBS_ALIGN_BOTTOM) + } else if (alignment & OBS_ALIGN_BOTTOM) { pos.y = br.y; - else + } else { pos.y = (br.y - tl.y) * 0.5f + tl.y; + } return pos; } @@ -1201,42 +1252,48 @@ void OBSBasicPreview::ClampAspect(vec3 &tl, vec3 &br, vec2 &size, const vec2 &ba 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 + } 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 + } 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)) + if ((size.y >= 0.0f && size.x >= 0.0f) || (size.y <= 0.0f && size.x <= 0.0f)) { size.x = size.y * baseAspect; - else + } 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)) + if ((size.y >= 0.0f && size.x >= 0.0f) || (size.y <= 0.0f && size.x <= 0.0f)) { size.y = size.x / baseAspect; - else + } else { size.y = size.x / baseAspect * -1.0f; + } } size.x = std::round(size.x); size.y = std::round(size.y); - if (stretchFlags & ITEM_LEFT) + if (stretchFlags & ITEM_LEFT) { tl.x = br.x - size.x; - else if (stretchFlags & ITEM_RIGHT) + } else if (stretchFlags & ITEM_RIGHT) { br.x = tl.x + size.x; + } - if (stretchFlags & ITEM_TOP) + if (stretchFlags & ITEM_TOP) { tl.y = br.y - size.y; - else if (stretchFlags & ITEM_BOTTOM) + } else if (stretchFlags & ITEM_BOTTOM) { br.y = tl.y + size.y; + } } void OBSBasicPreview::SnapStretchingToScreen(vec3 &tl, vec3 &br) @@ -1264,15 +1321,17 @@ void OBSBasicPreview::SnapStretchingToScreen(vec3 &tl, vec3 &br) vec3_transform(&offset, &offset, &screenToItem); vec3_sub(&offset, &offset, &tl); - if (stretchFlags & ITEM_LEFT) + if (stretchFlags & ITEM_LEFT) { tl.x += offset.x; - else if (stretchFlags & ITEM_RIGHT) + } else if (stretchFlags & ITEM_RIGHT) { br.x += offset.x; + } - if (stretchFlags & ITEM_TOP) + if (stretchFlags & ITEM_TOP) { tl.y += offset.y; - else if (stretchFlags & ITEM_BOTTOM) + } else if (stretchFlags & ITEM_BOTTOM) { br.y += offset.y; + } } static float maxfunc(float x, float y) @@ -1348,33 +1407,37 @@ void OBSBasicPreview::CropItem(const vec2 &pos) uint32_t align_x = (align & ALIGN_X); uint32_t align_y = (align & ALIGN_Y); - if (align_x == (stretchFlags & ALIGN_X) && align_x != 0) + if (align_x == (stretchFlags & ALIGN_X) && align_x != 0) { newPos.x = pos3.x; - else if (align & ITEM_RIGHT) + } else if (align & ITEM_RIGHT) { newPos.x = stretchItemSize.x; - else if (!(align & ITEM_LEFT)) + } else if (!(align & ITEM_LEFT)) { newPos.x = stretchItemSize.x * 0.5f; + } - if (align_y == (stretchFlags & ALIGN_Y) && align_y != 0) + if (align_y == (stretchFlags & ALIGN_Y) && align_y != 0) { newPos.y = pos3.y; - else if (align & ITEM_BOTTOM) + } else if (align & ITEM_BOTTOM) { newPos.y = stretchItemSize.y; - else if (!(align & ITEM_TOP)) + } else if (!(align & ITEM_TOP)) { newPos.y = stretchItemSize.y * 0.5f; + } #undef ALIGN_X #undef ALIGN_Y crop = startCrop; - if (stretchFlags & ITEM_LEFT) + if (stretchFlags & ITEM_LEFT) { crop.left += int(std::round(tl.x / scale.x)); - else if (stretchFlags & ITEM_RIGHT) + } else if (stretchFlags & ITEM_RIGHT) { crop.right += int(std::round((stretchItemSize.x - br.x) / scale.x)); + } - if (stretchFlags & ITEM_TOP) + if (stretchFlags & ITEM_TOP) { crop.top += int(std::round(tl.y / scale.y)); - else if (stretchFlags & ITEM_BOTTOM) + } else if (stretchFlags & ITEM_BOTTOM) { crop.bottom += int(std::round((stretchItemSize.y - br.y) / scale.y)); + } vec3_transform(&newPos, &newPos, &itemToScreen); newPos.x = std::round(newPos.x); @@ -1394,8 +1457,9 @@ void OBSBasicPreview::CropItem(const vec2 &pos) obs_sceneitem_defer_update_begin(stretchItem); obs_sceneitem_set_crop(stretchItem, &crop); - if (boundsType == OBS_BOUNDS_NONE) + if (boundsType == OBS_BOUNDS_NONE) { obs_sceneitem_set_pos(stretchItem, (vec2 *)&newPos); + } obs_sceneitem_defer_update_end(stretchItem); } @@ -1413,18 +1477,21 @@ void OBSBasicPreview::StretchItem(const vec2 &pos) vec3_set(&pos3, pos.x, pos.y, 0.0f); vec3_transform(&pos3, &pos3, &screenToItem); - if (stretchFlags & ITEM_LEFT) + if (stretchFlags & ITEM_LEFT) { tl.x = pos3.x; - else if (stretchFlags & ITEM_RIGHT) + } else if (stretchFlags & ITEM_RIGHT) { br.x = pos3.x; + } - if (stretchFlags & ITEM_TOP) + if (stretchFlags & ITEM_TOP) { tl.y = pos3.y; - else if (stretchFlags & ITEM_BOTTOM) + } else if (stretchFlags & ITEM_BOTTOM) { br.y = pos3.y; + } - if (!(modifiers & Qt::ControlModifier)) + if (!(modifiers & Qt::ControlModifier)) { SnapStretchingToScreen(tl, br); + } obs_source_t *source = obs_sceneitem_get_source(stretchItem); @@ -1434,8 +1501,9 @@ void OBSBasicPreview::StretchItem(const vec2 &pos) /* if the source's internal size has been set to 0 for whatever reason * while resizing, do not update transform, otherwise source will be * stuck invisible until a complete transform reset */ - if (!source_cx || !source_cy) + if (!source_cx || !source_cy) { return; + } vec2 baseSize; vec2_set(&baseSize, float(source_cx), float(source_cy)); @@ -1444,13 +1512,16 @@ void OBSBasicPreview::StretchItem(const vec2 &pos) vec2_set(&size, br.x - tl.x, br.y - tl.y); if (boundsType != OBS_BOUNDS_NONE) { - if (shiftDown) + if (shiftDown) { ClampAspect(tl, br, size, baseSize); + } - if (tl.x > br.x) + if (tl.x > br.x) { std::swap(tl.x, br.x); - if (tl.y > br.y) + } + if (tl.y > br.y) { std::swap(tl.y, br.y); + } vec2_abs(&size, &size); @@ -1462,8 +1533,9 @@ void OBSBasicPreview::StretchItem(const vec2 &pos) baseSize.x -= float(crop.left + crop.right); baseSize.y -= float(crop.top + crop.bottom); - if (!shiftDown) + if (!shiftDown) { ClampAspect(tl, br, size, baseSize); + } vec2_div(&size, &size, &baseSize); obs_sceneitem_set_scale(stretchItem, &size); @@ -1543,8 +1615,9 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) return; } - if (locked) + if (locked) { return; + } bool updateCursor = false; @@ -1560,8 +1633,9 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) pos.y = std::round(pos.y); if (stretchHandle != ItemHandle::None) { - if (obs_sceneitem_locked(stretchItem)) + if (obs_sceneitem_locked(stretchItem)) { return; + } selectionBox = false; @@ -1578,20 +1652,23 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) if (stretchHandle == ItemHandle::Rot) { RotateItem(pos); setCursor(Qt::ClosedHandCursor); - } else if (cropping) + } else if (cropping) { CropItem(pos); - else + } else { StretchItem(pos); + } } else if (mouseOverItems) { - if (cursor().shape() != Qt::SizeAllCursor) + if (cursor().shape() != Qt::SizeAllCursor) { setCursor(Qt::SizeAllCursor); + } selectionBox = false; MoveItems(pos); } else { selectionBox = true; - if (!mouseMoved) + if (!mouseMoved) { DoSelect(startPos); + } BoxItems(startPos, pos); } @@ -1626,8 +1703,9 @@ void OBSBasicPreview::mouseMoveEvent(QMouseEvent *event) void OBSBasicPreview::leaveEvent(QEvent *) { std::lock_guard lock(selectMutex); - if (!selectionBox) + if (!selectionBox) { hoveredPreviewItems.clear(); + } } static void DrawLine(float x1, float y1, float x2, float y2, float thickness, vec2 scale) @@ -1782,16 +1860,19 @@ static inline bool crop_enabled(const obs_sceneitem_crop *crop) bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, void *param) { - if (obs_sceneitem_locked(item)) + if (obs_sceneitem_locked(item)) { return true; + } - if (!SceneItemHasVideo(item)) + if (!SceneItemHasVideo(item)) { return true; + } OBSBasicPreview *prev = static_cast(param); - if (!prev->GetOverflowSelectionHidden() && !obs_sceneitem_visible(item)) + if (!prev->GetOverflowSelectionHidden() && !obs_sceneitem_visible(item)) { return true; + } if (obs_sceneitem_is_group(item)) { matrix4 mat; @@ -1803,8 +1884,9 @@ bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, gs_matrix_pop(); } - if (!prev->GetOverflowAlwaysVisible() && !obs_sceneitem_selected(item)) + if (!prev->GetOverflowAlwaysVisible() && !obs_sceneitem_selected(item)) { return true; + } matrix4 boxTransform; matrix4 invBoxTransform; @@ -1825,8 +1907,9 @@ bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, return CloseFloat(pos.x, b.x) && CloseFloat(pos.y, b.y); }); - if (!visible) + if (!visible) { return true; + } GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawSelectedOverflow"); @@ -1866,11 +1949,13 @@ bool OBSBasicPreview::DrawSelectedOverflow(obs_scene_t *, obs_sceneitem_t *item, bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, void *param) { - if (obs_sceneitem_locked(item)) + if (obs_sceneitem_locked(item)) { return true; + } - if (!SceneItemHasVideo(item)) + if (!SceneItemHasVideo(item)) { return true; + } OBSBasicPreview *prev = static_cast(param); @@ -1907,8 +1992,9 @@ bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, voi bool selected = obs_sceneitem_selected(item); - if (!selected && !hovered) + if (!selected && !hovered) { return true; + } matrix4 boxTransform; matrix4 invBoxTransform; @@ -1943,8 +2029,9 @@ bool OBSBasicPreview::DrawSelectedItem(obs_scene_t *, obs_sceneitem_t *item, voi return CloseFloat(pos.x, b.x) && CloseFloat(pos.y, b.y); }); - if (!visible) + if (!visible) { return true; + } GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawSelectedItem"); @@ -2095,11 +2182,13 @@ bool OBSBasicPreview::DrawSelectionBox(float x1, float y1, float x2, float y2, g void OBSBasicPreview::DrawOverflow() { - if (locked) + if (locked) { return; + } - if (overflowHidden) + if (overflowHidden) { return; + } GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawOverflow"); @@ -2127,8 +2216,9 @@ void OBSBasicPreview::DrawOverflow() void OBSBasicPreview::DrawSceneEditing() { - if (locked) + if (locked) { return; + } GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawSceneEditing"); @@ -2184,8 +2274,9 @@ void OBSBasicPreview::SetScalingAmount(float newScalingAmountVal) scrollingOffset.x *= newScalingAmountVal / scalingAmount; scrollingOffset.y *= newScalingAmountVal / scalingAmount; - if (scalingAmount == newScalingAmountVal) + if (scalingAmount == newScalingAmountVal) { return; + } scalingAmount = newScalingAmountVal; emit scalingChanged(scalingAmount); @@ -2266,8 +2357,9 @@ static void SetLabelText(int sourceIndex, int px) { OBSBasicPreview *prev = OBSBasicPreview::Get(); - if (px == prev->spacerPx[sourceIndex]) + if (px == prev->spacerPx[sourceIndex]) { return; + } std::string text = std::to_string(px) + " px"; @@ -2282,8 +2374,9 @@ static void SetLabelText(int sourceIndex, int px) static void DrawLabel(OBSSource source, vec3 &pos, vec3 &viewport) { - if (!source) + if (!source) { return; + } vec3_mul(&pos, &pos, &viewport); @@ -2336,8 +2429,9 @@ static void RenderSpacingHelper(int sourceIndex, vec3 &start, vec3 &end, vec3 &v 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); @@ -2352,8 +2446,9 @@ static void RenderSpacingHelper(int sourceIndex, vec3 &start, vec3 &end, vec3 &v px = length * ovi.base_height; } - if (px <= 0.0f) + if (px <= 0.0f) { return; + } OBSBasicPreview *prev = OBSBasicPreview::Get(); obs_source_t *source = prev->spacerLabel[sourceIndex]; @@ -2384,8 +2479,9 @@ static void RenderSpacingHelper(int sourceIndex, vec3 &start, vec3 &end, vec3 &v void OBSBasicPreview::DrawSpacingHelpers() { - if (locked) + if (locked) { return; + } OBSBasic *main = OBSBasic::Get(); @@ -2395,23 +2491,28 @@ void OBSBasicPreview::DrawSpacingHelpers() OBSScene scene = main->GetCurrentScene(); obs_scene_enum_items(scene, FindSelected, &data); - if (data.sceneItems.size() != 1) + if (data.sceneItems.size() != 1) { return; + } OBSSceneItem item = data.sceneItems[0]; - if (!item) + if (!item) { return; + } - if (obs_sceneitem_locked(item)) + if (obs_sceneitem_locked(item)) { return; + } vec2 itemSize = GetItemSize(item); - if (itemSize.x == 0.0f || itemSize.y == 0.0f) + if (itemSize.x == 0.0f || itemSize.y == 0.0f) { return; + } obs_sceneitem_t *parentGroup = obs_sceneitem_get_group(scene, item); - if (parentGroup && obs_sceneitem_locked(parentGroup)) + if (parentGroup && obs_sceneitem_locked(parentGroup)) { return; + } matrix4 boxTransform; obs_sceneitem_get_box_transform(item, &boxTransform); @@ -2470,8 +2571,9 @@ void OBSBasicPreview::DrawSpacingHelpers() if (rot >= HELPER_ROT_BREAKPOINT) { for (float i = HELPER_ROT_BREAKPOINT; i <= 360.0f; i += 90.0f) { - if (rot < i) + if (rot < i) { break; + } vec3 l = left; vec3 r = right; @@ -2485,8 +2587,9 @@ void OBSBasicPreview::DrawSpacingHelpers() } } else if (rot <= -HELPER_ROT_BREAKPOINT) { for (float i = -HELPER_ROT_BREAKPOINT; i >= -360.0f; i -= 90.0f) { - if (rot > i) + if (rot > i) { break; + } vec3 l = left; vec3 r = right; @@ -2528,8 +2631,9 @@ void OBSBasicPreview::DrawSpacingHelpers() float pixelRatio = main->GetDevicePixelRatio(); for (int i = 0; i < 4; i++) { - if (!spacerLabel[i]) + if (!spacerLabel[i]) { spacerLabel[i] = CreateLabel(pixelRatio, i); + } } vec3_set(&start, top.x, 0.0f, 1.0f); @@ -2597,13 +2701,15 @@ void OBSBasicPreview::yScrollBarChanged(int value) void OBSBasicPreview::UpdateXScrollBar(float cx) { - if (updatingXScrollBar) + if (updatingXScrollBar) { return; + } OBSBasic *main = OBSBasic::Get(); - if (!main->ui->previewXScrollBar->isVisible()) + if (!main->ui->previewXScrollBar->isVisible()) { return; + } main->ui->previewXScrollBar->setRange(int(-cx), int(cx)); @@ -2616,13 +2722,15 @@ void OBSBasicPreview::UpdateXScrollBar(float cx) void OBSBasicPreview::UpdateYScrollBar(float cy) { - if (updatingYScrollBar) + if (updatingYScrollBar) { return; + } OBSBasic *main = OBSBasic::Get(); - if (!main->ui->previewYScrollBar->isVisible()) + if (!main->ui->previewYScrollBar->isVisible()) { return; + } main->ui->previewYScrollBar->setRange(int(-cy), int(cy)); diff --git a/frontend/widgets/OBSBasicPreview.hpp b/frontend/widgets/OBSBasicPreview.hpp index 165bbd59e50eb6..fa22cf1e9e5b58 100644 --- a/frontend/widgets/OBSBasicPreview.hpp +++ b/frontend/widgets/OBSBasicPreview.hpp @@ -147,8 +147,9 @@ class OBSBasicPreview : public OBSQTDisplay { inline void SetFixedScaling(bool newFixedScalingVal) { - if (fixedScaling == newFixedScalingVal) + if (fixedScaling == newFixedScalingVal) { return; + } fixedScaling = newFixedScalingVal; emit fixedScalingChanged(fixedScaling); diff --git a/frontend/widgets/OBSBasicStats.cpp b/frontend/widgets/OBSBasicStats.cpp index c8d91e0481675e..e63b9f4d5cf62d 100644 --- a/frontend/widgets/OBSBasicStats.cpp +++ b/frontend/widgets/OBSBasicStats.cpp @@ -108,14 +108,16 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) /* --------------------------------------------- */ QPushButton *closeButton = nullptr; - if (closable) + if (closable) { closeButton = new QPushButton(QTStr("Close")); + } QPushButton *resetButton = new QPushButton(QTStr("Reset")); QHBoxLayout *buttonLayout = new QHBoxLayout; buttonLayout->addStretch(); buttonLayout->addWidget(resetButton); - if (closable) + if (closable) { buttonLayout->addWidget(closeButton); + } /* --------------------------------------------- */ @@ -158,8 +160,9 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) setLayout(mainLayout); /* --------------------------------------------- */ - if (closable) + if (closable) { connect(closeButton, &QPushButton::clicked, this, [this]() { close(); }); + } connect(resetButton, &QPushButton::clicked, this, [this]() { Reset(); }); delete shortcutFilter; @@ -179,8 +182,9 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) QObject::connect(&timer, &QTimer::timeout, this, &OBSBasicStats::Update); timer.setInterval(TIMER_INTERVAL); - if (isVisible()) + if (isVisible()) { timer.start(); + } Update(); @@ -203,8 +207,9 @@ OBSBasicStats::OBSBasicStats(QWidget *parent, bool closable) obs_frontend_add_event_callback(OBSFrontendEvent, this); - if (obs_frontend_recording_active()) + if (obs_frontend_recording_active()) { StartRecTimeLeft(); + } } void OBSBasicStats::closeEvent(QCloseEvent *event) @@ -273,8 +278,9 @@ void OBSBasicStats::Update() OBSOutputAutoRelease strOutput = obs_frontend_get_streaming_output(); OBSOutputAutoRelease recOutput = obs_frontend_get_recording_output(); - if (!strOutput && !recOutput) + if (!strOutput && !recOutput) { return; + } /* ------------------------------------------- */ /* general usage */ @@ -285,12 +291,13 @@ void OBSBasicStats::Update() QString str = QString::number(curFPS, 'f', 2); fps->setText(str); - if (curFPS < (obsFPS * 0.8)) + if (curFPS < (obsFPS * 0.8)) { setClasses(fps, "text-danger"); - else if (curFPS < (obsFPS * 0.95)) + } else if (curFPS < (obsFPS * 0.95)) { setClasses(fps, "text-warning"); - else + } else { setClasses(fps, ""); + } /* ------------------ */ @@ -321,12 +328,13 @@ void OBSBasicStats::Update() str = QString::number(num, 'f', 1) + abrv; hddSpace->setText(str); - if (num_bytes < GBYTE) + if (num_bytes < GBYTE) { setClasses(hddSpace, "text-danger"); - else if (num_bytes < (5 * GBYTE)) + } else if (num_bytes < (5 * GBYTE)) { setClasses(hddSpace, "text-warning"); - else + } else { setClasses(hddSpace, ""); + } /* ------------------ */ @@ -344,12 +352,13 @@ void OBSBasicStats::Update() long double fpsFrameTime = (long double)ovi.fps_den * 1000.0l / (long double)ovi.fps_num; - if (num > fpsFrameTime) + if (num > fpsFrameTime) { setClasses(renderTime, "text-danger"); - else if (num > fpsFrameTime * 0.75l) + } else if (num > fpsFrameTime * 0.75l) { setClasses(renderTime, "text-warning"); - else + } else { setClasses(renderTime, ""); + } /* ------------------ */ @@ -372,12 +381,13 @@ void OBSBasicStats::Update() QString::number(num, 'f', 1)); skippedFrames->setText(str); - if (num > 5.0l) + if (num > 5.0l) { setClasses(skippedFrames, "text-danger"); - else if (num > 1.0l) + } else if (num > 1.0l) { setClasses(skippedFrames, "text-warning"); - else + } else { setClasses(skippedFrames, ""); + } /* ------------------ */ @@ -397,12 +407,13 @@ void OBSBasicStats::Update() str = MakeMissedFramesText(total_lagged, total_rendered, num); missedFrames->setText(str); - if (num > 5.0l) + if (num > 5.0l) { setClasses(missedFrames, "text-danger"); - else if (num > 1.0l) + } else if (num > 1.0l) { setClasses(missedFrames, "text-warning"); - else + } else { setClasses(missedFrames, ""); + } /* ------------------------------------------- */ /* recording/streaming stats */ @@ -418,8 +429,9 @@ void OBSBasicStats::Update() void OBSBasicStats::StartRecTimeLeft() { - if (recTimeLeft.isActive()) + if (recTimeLeft.isActive()) { ResetRecTimeLeft(); + } recordTimeLeft->setText(QTStr("Calculating")); recTimeLeft.start(); @@ -436,12 +448,14 @@ void OBSBasicStats::ResetRecTimeLeft() void OBSBasicStats::RecordingTimeLeft() { - if (bitrates.empty()) + if (bitrates.empty()) { return; + } long double averageBitrate = accumulate(bitrates.begin(), bitrates.end(), 0.0) / (long double)bitrates.size(); - if (averageBitrate == 0) + if (averageBitrate == 0) { return; + } long double bytesPerSec = (averageBitrate / 8.0l) * 1000.0l; long double secondsUntilFull = (long double)num_bytes / bytesPerSec; @@ -480,24 +494,28 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) uint64_t curTime = os_gettime_ns(); uint64_t bytesSent = totalBytes; - if (bytesSent < lastBytesSent) + if (bytesSent < lastBytesSent) { bytesSent = 0; - if (bytesSent == 0) + } + if (bytesSent == 0) { lastBytesSent = 0; + } uint64_t bitsBetween = (bytesSent - lastBytesSent) * 8; long double timePassed = (long double)(curTime - lastBytesSentTime) / 1000000000.0l; kbps = (long double)bitsBetween / timePassed / 1000.0l; - if (timePassed < 0.01l) + if (timePassed < 0.01l) { kbps = 0.0l; + } QString str = QTStr("Basic.Stats.Status.Inactive"); QString styling; bool active = output ? obs_output_active(output) : false; if (rec) { - if (active) + if (active) { str = QTStr("Basic.Stats.Status.Recording"); + } } else { if (active) { bool reconnecting = output ? obs_output_reconnecting(output) : false; @@ -549,12 +567,13 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) .arg(QString::number(dropped), QString::number(total), QString::number(num, 'f', 1)); droppedFrames->setText(str); - if (num > 5.0l) + if (num > 5.0l) { setClasses(droppedFrames, "text-danger"); - else if (num > 1.0l) + } else if (num > 1.0l) { setClasses(droppedFrames, "text-warning"); - else + } else { setClasses(droppedFrames, ""); + } } lastBytesSent = bytesSent; @@ -563,8 +582,9 @@ void OBSBasicStats::OutputLabels::Update(obs_output_t *output, bool rec) void OBSBasicStats::OutputLabels::Reset(obs_output_t *output) { - if (!output) + if (!output) { return; + } first_total = obs_output_get_total_frames(output); first_dropped = obs_output_get_frames_dropped(output); diff --git a/frontend/widgets/OBSBasicStatusBar.cpp b/frontend/widgets/OBSBasicStatusBar.cpp index 1a202ed2d78942..fba31fc4f10010 100644 --- a/frontend/widgets/OBSBasicStatusBar.cpp +++ b/frontend/widgets/OBSBasicStatusBar.cpp @@ -89,8 +89,9 @@ void OBSBasicStatusBar::Activate() void OBSBasicStatusBar::Deactivate() { OBSBasic *main = qobject_cast(parent()); - if (!main) + if (!main) { return; + } if (!streamOutput) { statusWidget->ui->streamTime->setText(QString("00:00:00")); @@ -152,8 +153,9 @@ void OBSBasicStatusBar::UpdateDelayMsg() msg = msg.arg(QString::number(delaySecTotal)); } - if (!statusWidget->ui->delayFrame->isVisible()) + if (!statusWidget->ui->delayFrame->isVisible()) { statusWidget->ui->delayFrame->show(); + } statusWidget->ui->delayInfo->setText(msg); } @@ -161,23 +163,28 @@ void OBSBasicStatusBar::UpdateDelayMsg() void OBSBasicStatusBar::UpdateBandwidth() { - if (!streamOutput) + if (!streamOutput) { return; + } - if (++seconds < bitrateUpdateSeconds) + if (++seconds < bitrateUpdateSeconds) { return; + } OBSOutput output = OBSGetStrongRef(streamOutput); - if (!output) + if (!output) { return; + } uint64_t bytesSent = obs_output_get_total_bytes(output); uint64_t bytesSentTime = os_gettime_ns(); - if (bytesSent < lastBytesSent) + if (bytesSent < lastBytesSent) { bytesSent = 0; - if (bytesSent == 0) + } + if (bytesSent == 0) { lastBytesSent = 0; + } uint64_t bitsBetween = (bytesSent - lastBytesSent) * 8; @@ -191,8 +198,9 @@ void OBSBasicStatusBar::UpdateBandwidth() statusWidget->ui->kbps->setText(text); statusWidget->ui->kbps->setMinimumWidth(statusWidget->ui->kbps->width()); - if (!statusWidget->ui->kbps->isVisible()) + if (!statusWidget->ui->kbps->isVisible()) { statusWidget->ui->kbps->show(); + } lastBytesSent = bytesSent; lastBytesSentTime = bytesSentTime; @@ -202,8 +210,9 @@ void OBSBasicStatusBar::UpdateBandwidth() void OBSBasicStatusBar::UpdateCPUUsage() { OBSBasic *main = qobject_cast(parent()); - if (!main) + if (!main) { return; + } QString text; text += QString("CPU: ") + QString::number(main->GetCPUUsage(), 'f', 1) + QString("%"); @@ -237,8 +246,9 @@ void OBSBasicStatusBar::UpdateStreamTime() QString text = QString::asprintf("%02d:%02d:%02d", hours, minutes, seconds); statusWidget->ui->streamTime->setText(text); - if (streamOutput && !statusWidget->ui->streamTime->isEnabled()) + if (streamOutput && !statusWidget->ui->streamTime->isEnabled()) { statusWidget->ui->streamTime->setDisabled(false); + } if (reconnectTimeout > 0) { QString msg = QTStr("Basic.StatusBar.Reconnecting") @@ -255,10 +265,12 @@ void OBSBasicStatusBar::UpdateStreamTime() } if (delaySecStopping > 0 || delaySecStarting > 0) { - if (delaySecStopping > 0) + if (delaySecStopping > 0) { --delaySecStopping; - if (delaySecStarting > 0) + } + if (delaySecStarting > 0) { --delaySecStarting; + } UpdateDelayMsg(); } } @@ -272,8 +284,9 @@ void OBSBasicStatusBar::UpdateRecordTime() if (!paused) { totalRecordSeconds++; - if (recordOutput && !statusWidget->ui->recordTime->isEnabled()) + if (recordOutput && !statusWidget->ui->recordTime->isEnabled()) { statusWidget->ui->recordTime->setDisabled(false); + } } else { statusWidget->ui->recordIcon->setPixmap(streamPauseIconToggle ? recordingPauseInactivePixmap : recordingPausePixmap); @@ -301,41 +314,48 @@ void OBSBasicStatusBar::UpdateRecordTimeLabel() void OBSBasicStatusBar::UpdateDroppedFrames() { - if (!streamOutput) + if (!streamOutput) { return; + } OBSOutput output = OBSGetStrongRef(streamOutput); - if (!output) + if (!output) { return; + } int totalDropped = obs_output_get_frames_dropped(output); int totalFrames = obs_output_get_total_frames(output); double percent = (double)totalDropped / (double)totalFrames * 100.0; - if (!totalFrames) + if (!totalFrames) { return; + } QString text = QTStr("DroppedFrames"); text = text.arg(QString::number(totalDropped), QString::number(percent, 'f', 1)); statusWidget->ui->droppedFrames->setText(text); - if (!statusWidget->ui->issuesFrame->isVisible()) + if (!statusWidget->ui->issuesFrame->isVisible()) { statusWidget->ui->issuesFrame->show(); + } /* ----------------------------------- * * calculate congestion color */ float congestion = obs_output_get_congestion(output); float avgCongestion = (congestion + lastCongestion) * 0.5f; - if (avgCongestion < congestion) + if (avgCongestion < congestion) { avgCongestion = congestion; - if (avgCongestion > 1.0f) + } + if (avgCongestion > 1.0f) { avgCongestion = 1.0f; + } lastCongestion = congestion; - if (disconnected) + if (disconnected) { return; + } bool update = firstCongestionUpdate; float congestionOverTime = avgCongestion; @@ -350,14 +370,15 @@ void OBSBasicStatusBar::UpdateDroppedFrames() } if (update) { - if (congestionOverTime <= excellentThreshold + EPSILON) + if (congestionOverTime <= excellentThreshold + EPSILON) { statusWidget->ui->statusIcon->setPixmap(excellentPixmap); - else if (congestionOverTime <= goodThreshold) + } else if (congestionOverTime <= goodThreshold) { statusWidget->ui->statusIcon->setPixmap(goodPixmap); - else if (congestionOverTime <= mediocreThreshold) + } else if (congestionOverTime <= mediocreThreshold) { statusWidget->ui->statusIcon->setPixmap(mediocrePixmap); - else if (congestionOverTime <= badThreshold) + } else if (congestionOverTime <= badThreshold) { statusWidget->ui->statusIcon->setPixmap(badPixmap); + } firstCongestionUpdate = false; } @@ -382,15 +403,17 @@ void OBSBasicStatusBar::Reconnect(int seconds) { OBSBasic *main = qobject_cast(parent()); - if (!retries) + if (!retries) { main->SysTrayNotify(QTStr("Basic.SystemTray.Message.Reconnecting"), QSystemTrayIcon::Warning); + } reconnectTimeout = seconds; if (streamOutput) { OBSOutput output = OBSGetStrongRef(streamOutput); - if (!output) + if (!output) { return; + } delaySecTotal = obs_output_get_active_delay(output); UpdateDelayMsg(); @@ -421,8 +444,9 @@ void OBSBasicStatusBar::ReconnectSuccess() if (streamOutput) { OBSOutput output = OBSGetStrongRef(streamOutput); - if (!output) + if (!output) { return; + } delaySecTotal = obs_output_get_active_delay(output); UpdateDelayMsg(); @@ -437,11 +461,13 @@ void OBSBasicStatusBar::UpdateStatusBar() UpdateBandwidth(); - if (streamOutput) + if (streamOutput) { UpdateStreamTime(); + } - if (recordOutput) + if (recordOutput) { UpdateRecordTime(); + } UpdateDroppedFrames(); @@ -468,8 +494,9 @@ void OBSBasicStatusBar::UpdateStatusBar() void OBSBasicStatusBar::StreamDelayStarting(int sec) { OBSBasic *main = qobject_cast(parent()); - if (!main || !main->outputHandler) + if (!main || !main->outputHandler) { return; + } OBSOutputAutoRelease output = obs_frontend_get_streaming_output(); streamOutput = OBSGetWeakRef(output); @@ -564,14 +591,16 @@ void OBSBasicStatusBar::UpdateIcons() statusWidget->ui->streamIcon->setPixmap(streamingInactivePixmap); statusWidget->ui->statusIcon->setPixmap(inactivePixmap); } else { - if (disconnected) + if (disconnected) { statusWidget->ui->statusIcon->setPixmap(disconnectedPixmap); + } } bool recording = obs_frontend_recording_active(); - if (!recording) + if (!recording) { statusWidget->ui->recordIcon->setPixmap(recordingInactivePixmap); + } } void OBSBasicStatusBar::showMessage(const QString &message, int timeout) @@ -580,8 +609,9 @@ void OBSBasicStatusBar::showMessage(const QString &message, int timeout) statusWidget->ui->message->setText(message); - if (timeout) + if (timeout) { messageTimer->start(timeout); + } } void OBSBasicStatusBar::clearMessage() diff --git a/frontend/widgets/OBSBasic_Browser.cpp b/frontend/widgets/OBSBasic_Browser.cpp index ecac249570c2e0..2ba7b6443a42a0 100644 --- a/frontend/widgets/OBSBasic_Browser.cpp +++ b/frontend/widgets/OBSBasic_Browser.cpp @@ -52,12 +52,14 @@ void OBSBasic::LoadExtraBrowserDocks() std::string err; Json json = Json::parse(jsonStr, err); - if (!err.empty()) + if (!err.empty()) { return; + } Json::array array = json.array_items(); - if (!array.empty()) + if (!array.empty()) { extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator(); + } for (Json &item : array) { std::string title = item["title"].string_value(); @@ -118,8 +120,9 @@ void OBSBasic::AddExtraBrowserDock(const QString &title, const QString &url, con dock->setAllowedAreas(Qt::AllDockWidgetAreas); QCefWidget *browser = cef->create_widget(dock, QT_TO_UTF8(url), nullptr); - if (browser && panel_version >= 1) + if (browser && panel_version >= 1) { browser->allowAllPopups(true); + } dock->SetWidget(browser); @@ -176,8 +179,9 @@ static std::string GenId() void CheckExistingCookieId() { OBSBasic *main = OBSBasic::Get(); - if (config_has_user_value(main->Config(), "Panels", "CookieId")) + if (config_has_user_value(main->Config(), "Panels", "CookieId")) { return; + } config_set_string(main->Config(), "Panels", "CookieId", GenId().c_str()); } @@ -185,10 +189,12 @@ void CheckExistingCookieId() #ifdef BROWSER_AVAILABLE static void InitPanelCookieManager() { - if (!cef) + if (!cef) { return; - if (panel_cookies) + } + if (panel_cookies) { return; + } CheckExistingCookieId(); @@ -247,8 +253,9 @@ void DuplicateCurrentCookieProfile(ConfigFile &config) QDir dstDir(dst_path_full.Get()); if (srcDir.exists()) { - if (!dstDir.exists()) + if (!dstDir.exists()) { dstDir.mkdir(dst_path_full.Get()); + } QStringList files = srcDir.entryList(QDir::Files); for (const QString &file : files) { @@ -271,8 +278,9 @@ void DuplicateCurrentCookieProfile(ConfigFile &config) void OBSBasic::InitBrowserPanelSafeBlock() { #ifdef BROWSER_AVAILABLE - if (!cef) + if (!cef) { return; + } if (cef->init_browser()) { InitPanelCookieManager(); return; diff --git a/frontend/widgets/OBSBasic_Canvases.cpp b/frontend/widgets/OBSBasic_Canvases.cpp index 4d8d8be54edbe7..d1c611fbc637ff 100644 --- a/frontend/widgets/OBSBasic_Canvases.cpp +++ b/frontend/widgets/OBSBasic_Canvases.cpp @@ -34,8 +34,9 @@ const OBS::Canvas &OBSBasic::AddCanvas(const std::string &name, obs_video_info * bool OBSBasic::RemoveCanvas(OBSCanvas canvas) { bool removed = false; - if (!canvas) + if (!canvas) { return removed; + } auto canvas_it = std::find(std::begin(canvases), std::end(canvases), canvas); if (canvas_it != std::end(canvases)) { @@ -47,8 +48,9 @@ bool OBSBasic::RemoveCanvas(OBSCanvas canvas) removed = true; } - if (removed) + if (removed) { OnEvent(OBS_FRONTEND_EVENT_CANVAS_REMOVED); + } return removed; } diff --git a/frontend/widgets/OBSBasic_Clipboard.cpp b/frontend/widgets/OBSBasic_Clipboard.cpp index 4ed383811ec320..43a71a6cfb2c0d 100644 --- a/frontend/widgets/OBSBasic_Clipboard.cpp +++ b/frontend/widgets/OBSBasic_Clipboard.cpp @@ -40,10 +40,12 @@ void OBSBasic::on_actionPasteTransform_triggered() { OBSDataAutoRelease wrapper = obs_scene_save_transform_states(GetCurrentScene(), false); auto func = [](obs_scene_t *, obs_sceneitem_t *item, void *) { - if (!obs_sceneitem_selected(item)) + if (!obs_sceneitem_selected(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; + } OBSBasic *main = OBSBasic::Get(); @@ -71,8 +73,9 @@ void OBSBasic::on_actionCopySource_triggered() for (auto &selectedSource : GetAllSelectedSourceItems()) { OBSSceneItem item = ui->sources->Get(selectedSource.row()); - if (!item) + if (!item) { continue; + } OBSSource source = obs_sceneitem_get_source(item); @@ -123,8 +126,9 @@ void OBSBasic::on_actionPasteRef_triggered() SourceCopyInfo ©Info = clipboard[i - 1]; OBSSource source = OBSGetStrongRef(copyInfo.weak_source); - if (!source) + if (!source) { continue; + } const char *name = obs_source_get_name(source); @@ -171,8 +175,9 @@ void OBSBasic::on_actionPasteDup_triggered() void OBSBasic::SourcePasteFilters(OBSSource source, OBSSource dstSource) { - if (source == dstSource) + if (source == dstSource) { return; + } OBSDataArrayAutoRelease undo_array = obs_source_backup_filters(dstSource); obs_source_copy_filters(dstSource, source); @@ -231,8 +236,9 @@ void OBSBasic::on_actionCopyFilters_triggered() { OBSSceneItem item = GetCurrentSceneItem(); - if (!item) + if (!item) { return; + } OBSSource source = obs_sceneitem_get_source(item); @@ -251,8 +257,9 @@ void OBSBasic::CreateFilterPasteUndoRedoAction(const QString &text, obs_source_t obs_source_restore_filters(source, array); - if (filters) + if (filters) { filters->UpdateSource(source); + } }; const char *uuid = obs_source_get_uuid(source); diff --git a/frontend/widgets/OBSBasic_ContextToolbar.cpp b/frontend/widgets/OBSBasic_ContextToolbar.cpp index ff16156c2a2fe9..017ea110dda95d 100644 --- a/frontend/widgets/OBSBasic_ContextToolbar.cpp +++ b/frontend/widgets/OBSBasic_ContextToolbar.cpp @@ -39,8 +39,9 @@ void OBSBasic::copyActionsDynamicProperties() for (QAction *x : ui->scenesToolbar->actions()) { QWidget *temp = ui->scenesToolbar->widgetForAction(x); - if (!temp) + if (!temp) { continue; + } for (QByteArray &y : x->dynamicPropertyNames()) { temp->setProperty(y.constData(), x->property(y.constData())); @@ -50,8 +51,9 @@ void OBSBasic::copyActionsDynamicProperties() for (QAction *x : ui->sourcesToolbar->actions()) { QWidget *temp = ui->sourcesToolbar->widgetForAction(x); - if (!temp) + if (!temp) { continue; + } for (QByteArray &y : x->dynamicPropertyNames()) { temp->setProperty(y.constData(), x->property(y.constData())); @@ -81,8 +83,9 @@ void OBSBasic::UpdateContextBarVisibility() contextBarSizeNew = ContextBarSize_Minimized; } - if (contextBarSize == contextBarSizeNew) + if (contextBarSize == contextBarSizeNew) { return; + } contextBarSize = contextBarSizeNew; UpdateContextBarDeferred(); @@ -90,8 +93,9 @@ void OBSBasic::UpdateContextBarVisibility() static bool is_network_media_source(obs_source_t *source, const char *id) { - if (strcmp(id, "ffmpeg_source") != 0) + if (strcmp(id, "ffmpeg_source") != 0) { return false; + } OBSDataAutoRelease s = obs_source_get_settings(source); bool is_local_file = obs_data_get_bool(s, "is_local_file"); @@ -118,10 +122,11 @@ void OBSBasic::SourceToolBarActionsSetEnabled() enable = true; } - if (disableProps) + if (disableProps) { ui->actionSourceProperties->setEnabled(false); - else + } else { ui->actionSourceProperties->setEnabled(enable); + } ui->actionRemoveSource->setEnabled(enable); ui->actionSourceUp->setEnabled(enable); @@ -134,8 +139,9 @@ void OBSBasic::UpdateContextBar(bool force) { SourceToolBarActionsSetEnabled(); - if (!ui->contextContainer->isVisible() && !force) + if (!ui->contextContainer->isVisible() && !force) { return; + } OBSSceneItem item = GetCurrentSceneItem(); @@ -146,11 +152,13 @@ void OBSBasic::UpdateContextBar(bool force) QLayoutItem *la = ui->emptySpace->layout()->itemAt(0); if (la) { if (SourceToolbar *toolbar = dynamic_cast(la->widget())) { - if (toolbar->GetSource() == source) + if (toolbar->GetSource() == source) { updateNeeded = false; + } } else if (MediaControls *toolbar = dynamic_cast(la->widget())) { - if (toolbar->GetSource() == source) + if (toolbar->GetSource() == source) { updateNeeded = false; + } } } @@ -225,12 +233,13 @@ void OBSBasic::UpdateContextBar(bool force) QIcon icon; - if (strcmp(id, "scene") == 0) + if (strcmp(id, "scene") == 0) { icon = GetSceneIcon(); - else if (strcmp(id, "group") == 0) + } else if (strcmp(id, "group") == 0) { icon = GetGroupIcon(); - else + } else { icon = GetSourceIcon(id); + } QPixmap pixmap = icon.pixmap(QSize(16, 16)); ui->contextSourceIcon->setPixmap(pixmap); diff --git a/frontend/widgets/OBSBasic_Docks.cpp b/frontend/widgets/OBSBasic_Docks.cpp index b35839ef0079b5..db487ffbc6ef27 100644 --- a/frontend/widgets/OBSBasic_Docks.cpp +++ b/frontend/widgets/OBSBasic_Docks.cpp @@ -54,8 +54,9 @@ void OBSBasic::on_resetDocks_triggered(bool force) QMessageBox::StandardButton button = OBSMessageBox::question(this, QTStr("ResetUIWarning.Title"), QTStr("ResetUIWarning.Text")); - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return; + } } #define RESET_DOCKLIST(dockList) \ @@ -117,15 +118,18 @@ void OBSBasic::on_lockDocks_toggled(bool lock) controlsDock->setFeatures(mainFeatures); statsDock->setFeatures(features); - for (int i = extraDocks.size() - 1; i >= 0; i--) + for (int i = extraDocks.size() - 1; i >= 0; i--) { extraDocks[i]->setFeatures(features); + } - for (int i = extraCustomDocks.size() - 1; i >= 0; i--) + for (int i = extraCustomDocks.size() - 1; i >= 0; i--) { extraCustomDocks[i]->setFeatures(features); + } #ifdef BROWSER_AVAILABLE - for (int i = extraBrowserDocks.size() - 1; i >= 0; i--) + for (int i = extraBrowserDocks.size() - 1; i >= 0; i--) { extraBrowserDocks[i]->setFeatures(features); + } #endif } @@ -138,8 +142,9 @@ void OBSBasic::on_sideDocks_toggled(bool side) void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, bool extraBrowser) { - if (dock->objectName().isEmpty()) + if (dock->objectName().isEmpty()) { return; + } bool lock = ui->lockDocks->isChecked(); QDockWidget::DockWidgetFeatures features = @@ -152,16 +157,19 @@ void OBSBasic::AddDockWidget(QDockWidget *dock, Qt::DockWidgetArea area, bool ex addDockWidget(area, dock); #ifdef BROWSER_AVAILABLE - if (extraBrowser && extraBrowserMenuDocksSeparator.isNull()) + if (extraBrowser && extraBrowserMenuDocksSeparator.isNull()) { extraBrowserMenuDocksSeparator = ui->menuDocks->addSeparator(); + } - if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull()) + if (!extraBrowser && !extraBrowserMenuDocksSeparator.isNull()) { ui->menuDocks->insertAction(extraBrowserMenuDocksSeparator, dock->toggleViewAction()); - else + } else { ui->menuDocks->addAction(dock->toggleViewAction()); + } - if (extraBrowser) + if (extraBrowser) { return; + } #else UNUSED_PARAMETER(extraBrowser); diff --git a/frontend/widgets/OBSBasic_Dropfiles.cpp b/frontend/widgets/OBSBasic_Dropfiles.cpp index 53c2f3e4ffe952..9546f4f7a1fecb 100644 --- a/frontend/widgets/OBSBasic_Dropfiles.cpp +++ b/frontend/widgets/OBSBasic_Dropfiles.cpp @@ -67,8 +67,9 @@ static string GenerateSourceName(const char *base) OBSSourceAutoRelease source = obs_get_source_by_name(name.c_str()); - if (!source) + if (!source) { return name; + } } } @@ -88,10 +89,12 @@ void OBSBasic::AddDropURL(QUrl url, QString &name, obs_data_t *settings, const o int cx = (int)ovi.base_width; int cy = (int)ovi.base_height; - if (query.hasQueryItem("layer-width")) + if (query.hasQueryItem("layer-width")) { cx = query.queryItemValue("layer-width").toInt(); - if (query.hasQueryItem("layer-height")) + } + if (query.hasQueryItem("layer-height")) { cy = query.queryItemValue("layer-height").toInt(); + } if (query.hasQueryItem("layer-css")) { // QUrl::FullyDecoded does NOT properly decode a // application/x-www-form-urlencoded space represented as '+' @@ -180,8 +183,9 @@ void OBSBasic::AddDropSource(const char *data, DropType image) return; } - if (name.isEmpty()) + 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); if (source) { @@ -255,8 +259,9 @@ void OBSBasic::ConfirmDropUrl(const QString &url) messageBox.setIcon(QMessageBox::Question); messageBox.exec(); - if (messageBox.clickedButton() == yesButton) + if (messageBox.clickedButton() == yesButton) { AddDropSource(QT_TO_UTF8(url), DropType_Url); + } } } diff --git a/frontend/widgets/OBSBasic_Hotkeys.cpp b/frontend/widgets/OBSBasic_Hotkeys.cpp index 3be00aeeed9169..c18e7a45987fcb 100644 --- a/frontend/widgets/OBSBasic_Hotkeys.cpp +++ b/frontend/widgets/OBSBasic_Hotkeys.cpp @@ -93,12 +93,14 @@ void OBSBasic::CreateHotkeys() auto LoadHotkeyData = [&](const char *name) -> OBSData { const char *info = config_get_string(activeConfiguration, "Hotkeys", name); - if (!info) + if (!info) { return {}; + } OBSDataAutoRelease data = obs_data_create_from_json(info); - if (!data) + if (!data) { return {}; + } return data.Get(); }; @@ -181,8 +183,9 @@ void OBSBasic::CreateHotkeys() splitFileHotkey = obs_hotkey_register_frontend( "OBSBasic.SplitFile", Str("Basic.Main.SplitFile"), [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) { - if (pressed) + if (pressed) { obs_frontend_recording_split_file(); + } }, this); LoadHotkey(splitFileHotkey, "OBSBasic.SplitFile"); @@ -190,8 +193,9 @@ void OBSBasic::CreateHotkeys() addChapterHotkey = obs_hotkey_register_frontend( "OBSBasic.AddChapterMarker", Str("Basic.Main.AddChapterMarker"), [](void *, obs_hotkey_id, obs_hotkey_t *, bool pressed) { - if (pressed) + if (pressed) { obs_frontend_recording_add_chapter(nullptr); + } }, this); LoadHotkey(addChapterHotkey, "OBSBasic.AddChapterMarker"); @@ -244,18 +248,20 @@ void OBSBasic::CreateHotkeys() #undef MAKE_CALLBACK auto transition = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { - if (pressed) + if (pressed) { QMetaObject::invokeMethod(static_cast(data), "TransitionClicked", Qt::QueuedConnection); + } }; 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) { - if (pressed) + if (pressed) { QMetaObject::invokeMethod(static_cast(data), "ResetStatsHotkey", Qt::QueuedConnection); + } }; statsHotkey = @@ -263,17 +269,19 @@ void OBSBasic::CreateHotkeys() LoadHotkey(statsHotkey, "OBSBasic.ResetStats"); auto screenshot = [](void *data, obs_hotkey_id, obs_hotkey_t *, bool pressed) { - if (pressed) + if (pressed) { QMetaObject::invokeMethod(static_cast(data), "Screenshot", Qt::QueuedConnection); + } }; 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) { - if (pressed) + if (pressed) { QMetaObject::invokeMethod(static_cast(data), "ScreenshotSelectedSource", Qt::QueuedConnection); + } }; sourceScreenshotHotkey = obs_hotkey_register_frontend("OBSBasic.SelectedSourceScreenshot", diff --git a/frontend/widgets/OBSBasic_MainControls.cpp b/frontend/widgets/OBSBasic_MainControls.cpp index 6207cd0fb5f612..7104c8c9954e47 100644 --- a/frontend/widgets/OBSBasic_MainControls.cpp +++ b/frontend/widgets/OBSBasic_MainControls.cpp @@ -71,11 +71,13 @@ using LogUploadType = OBS::LogFileType; void OBSBasic::CreateInteractionWindow(obs_source_t *source) { bool closed = true; - if (interaction) + if (interaction) { closed = interaction->close(); + } - if (!closed) + if (!closed) { return; + } interaction = new OBSBasicInteraction(this, source); interaction->Init(); @@ -85,11 +87,13 @@ void OBSBasic::CreateInteractionWindow(obs_source_t *source) void OBSBasic::CreatePropertiesWindow(obs_source_t *source) { bool closed = true; - if (properties) + if (properties) { closed = properties->close(); + } - if (!closed) + if (!closed) { return; + } properties = new OBSBasicProperties(this, source); properties->Init(); @@ -99,11 +103,13 @@ void OBSBasic::CreatePropertiesWindow(obs_source_t *source) void OBSBasic::CreateFiltersWindow(obs_source_t *source) { bool closed = true; - if (filters) + if (filters) { closed = filters->close(); + } - if (!closed) + if (!closed) { return; + } filters = new OBSBasicFilters(this, source); filters->Init(); @@ -138,10 +144,12 @@ void OBSBasic::CloseDialogs() } } - if (!stats.isNull()) + if (!stats.isNull()) { stats->close(); //call close to save Stats geometry - if (!remux.isNull()) + } + if (!remux.isNull()) { remux->close(); + } } void OBSBasic::EnumDialogs() @@ -153,17 +161,20 @@ void OBSBasic::EnumDialogs() /* fill list of Visible dialogs and Modal dialogs */ QList dialogs = findChildren(); for (QDialog *dialog : dialogs) { - if (dialog->isVisible()) + if (dialog->isVisible()) { visDialogs.append(dialog); - if (dialog->isModal()) + } + if (dialog->isModal()) { modalDialogs.append(dialog); + } } /* fill list of Visible message boxes */ QList msgBoxes = findChildren(); for (QMessageBox *msgbox : msgBoxes) { - if (msgbox->isVisible()) + if (msgbox->isVisible()) { visMsgBoxes.append(msgbox); + } } } @@ -214,10 +225,11 @@ void OBSBasic::on_action_Settings_triggered() QMessageBox::StandardButton button = OBSMessageBox::question(this, QTStr("Restart"), QTStr("NeedsRestart")); - if (button == QMessageBox::Yes) + if (button == QMessageBox::Yes) { close(); - else + } else { restart = false; + } } } @@ -248,16 +260,18 @@ void OBSBasic::on_actionAdvAudioProperties_triggered() static BPtr ReadLogFile(const char *subdir, const char *log) { char logDir[512]; - if (GetAppConfigPath(logDir, sizeof(logDir), subdir) <= 0) + if (GetAppConfigPath(logDir, sizeof(logDir), subdir) <= 0) { return nullptr; + } string path = logDir; path += "/"; path += log; BPtr file = os_quick_read_utf8_file(path.c_str()); - if (!file) + if (!file) { blog(LOG_WARNING, "Failed to read log file %s", path.c_str()); + } return file; } @@ -297,8 +311,9 @@ void OBSBasic::UploadLog(const char *subdir, const char *file, const LogUploadTy void OBSBasic::on_actionShowLogs_triggered() { char logDir[512]; - if (GetAppConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0) + if (GetAppConfigPath(logDir, sizeof(logDir), "obs-studio/logs") <= 0) { return; + } QUrl url = QUrl::fromLocalFile(QT_UTF8(logDir)); QDesktopServices::openUrl(url); @@ -328,8 +343,9 @@ void OBSBasic::on_actionUploadLastLog_triggered() void OBSBasic::on_actionViewCurrentLog_triggered() { - if (!logView) + if (!logView) { logView = new OBSLogViewer(); + } logView->show(); logView->setWindowState((logView->windowState() & ~Qt::WindowMinimized) | Qt::WindowActive); @@ -364,8 +380,9 @@ void OBSBasic::on_actionRepair_triggered() ui->actionCheckForUpdates->setEnabled(false); ui->actionRepair->setEnabled(false); - if (updateCheckThread && updateCheckThread->isRunning()) + if (updateCheckThread && updateCheckThread->isRunning()) { return; + } updateCheckThread.reset(new AutoUpdateThread(false, true)); updateCheckThread->start(); @@ -420,10 +437,12 @@ void OBSBasic::on_actionDiscord_triggered() void OBSBasic::on_actionShowWhatsNew_triggered() { #ifdef WHATSNEW_ENABLED - if (introCheckThread && introCheckThread->isRunning()) + if (introCheckThread && introCheckThread->isRunning()) { return; - if (!cef) + } + if (!cef) { return; + } config_set_int(App()->GetAppConfig(), "General", "InfoIncrement", -1); @@ -487,8 +506,9 @@ void OBSBasic::ToggleAlwaysOnTop() void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item) { - if (transformWindow) + if (transformWindow) { transformWindow->close(); + } transformWindow = new OBSBasicTransform(item, this); connect(ui->scenes, &QListWidget::currentItemChanged, transformWindow, &OBSBasicTransform::onSceneChanged); transformWindow->show(); @@ -497,10 +517,11 @@ void OBSBasic::CreateEditTransformWindow(obs_sceneitem_t *item) void OBSBasic::on_actionFullscreenInterface_triggered() { - if (!isFullScreen()) + if (!isFullScreen()) { showFullScreen(); - else + } else { showNormal(); + } } void OBSBasic::on_resetUI_triggered() @@ -549,24 +570,28 @@ void OBSBasic::SetShowing(bool showing) } } - if (showHide) + if (showHide) { showHide->setText(QTStr("Basic.SystemTray.Show")); + } QTimer::singleShot(0, this, &OBSBasic::hide); - if (previewEnabled) + if (previewEnabled) { EnablePreviewDisplay(false); + } #ifdef __APPLE__ EnableOSXDockIcon(false); #endif } else if (showing && !isVisible()) { - if (showHide) + if (showHide) { showHide->setText(QTStr("Basic.SystemTray.Hide")); + } QTimer::singleShot(0, this, &OBSBasic::show); - if (previewEnabled) + if (previewEnabled) { EnablePreviewDisplay(true); + } #ifdef __APPLE__ EnableOSXDockIcon(true); @@ -602,8 +627,9 @@ void OBSBasic::ToggleShowHide() if (showing) { /* check for modal dialogs */ EnumDialogs(); - if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty()) + if (!modalDialogs.isEmpty() || !visMsgBoxes.isEmpty()) { return; + } } SetShowing(!showing); } @@ -652,8 +678,9 @@ void OBSBasic::on_idianPlayground_triggered() void OBSBasic::on_actionShowAbout_triggered() { - if (about) + if (about) { about->close(); + } about = new OBSAbout(this); about->show(); diff --git a/frontend/widgets/OBSBasic_OutputHandler.cpp b/frontend/widgets/OBSBasic_OutputHandler.cpp index 4eada19423f73b..12784f3ffc30b7 100644 --- a/frontend/widgets/OBSBasic_OutputHandler.cpp +++ b/frontend/widgets/OBSBasic_OutputHandler.cpp @@ -38,8 +38,9 @@ void OBSBasic::ResetOutputs() emit ReplayBufEnabled(outputHandler->replayBuffer); - if (sysTrayReplayBuffer) + if (sysTrayReplayBuffer) { sysTrayReplayBuffer->setEnabled(!!outputHandler->replayBuffer); + } UpdateIsRecordingPausable(); } else { @@ -49,15 +50,17 @@ void OBSBasic::ResetOutputs() bool OBSBasic::Active() const { - if (!outputHandler) + if (!outputHandler) { return false; + } return outputHandler->Active(); } void OBSBasic::ResizeOutputSizeOfSource() { - if (obs_video_active()) + if (obs_video_active()) { return; + } QMessageBox resize_output(this); resize_output.setText(QTStr("ResizeOutputSizeOfSource.Text") + "\n\n" + @@ -68,8 +71,9 @@ void OBSBasic::ResizeOutputSizeOfSource() resize_output.setWindowTitle(QTStr("ResizeOutputSizeOfSource")); resize_output.exec(); - if (resize_output.clickedButton() != Yes) + if (resize_output.clickedButton() != Yes) { return; + } OBSSource source = obs_sceneitem_get_source(GetCurrentSceneItem()); @@ -124,8 +128,9 @@ bool OBSBasic::IsFFmpegOutputToURL() const 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"); - if (!is_local) + if (!is_local) { return true; + } } } @@ -134,8 +139,9 @@ bool OBSBasic::IsFFmpegOutputToURL() const bool OBSBasic::OutputPathValid() { - if (IsFFmpegOutputToURL()) + if (IsFFmpegOutputToURL()) { return true; + } const char *path = GetCurrentOutputPath(); return path && *path && QDir(path).exists(); diff --git a/frontend/widgets/OBSBasic_Preview.cpp b/frontend/widgets/OBSBasic_Preview.cpp index e4ad72f739b4e1..79e458d8d77329 100644 --- a/frontend/widgets/OBSBasic_Preview.cpp +++ b/frontend/widgets/OBSBasic_Preview.cpp @@ -97,8 +97,9 @@ void OBSBasic::UpdatePreviewScalingMenu() void OBSBasic::DrawBackdrop(float cx, float cy) { - if (!box) + if (!box) { return; + } GS_DEBUG_MARKER_BEGIN(GS_DEBUG_COLOR_DEFAULT, "DrawBackdrop"); @@ -163,8 +164,9 @@ void OBSBasic::RenderMain(void *data, uint32_t, uint32_t) OBSScene scene = window->GetCurrentScene(); obs_source_t *source = obs_scene_get_source(scene); - if (source) + if (source) { obs_source_video_render(source); + } } else { obs_render_main_texture_src_color_only(); } @@ -189,8 +191,9 @@ void OBSBasic::RenderMain(void *data, uint32_t, uint32_t) window->ui->preview->DrawSceneEditing(); - if (window->drawSpacingHelpers) + if (window->drawSpacingHelpers) { window->ui->preview->DrawSpacingHelpers(); + } /* --------------------------------------- */ @@ -272,8 +275,9 @@ void OBSBasic::TogglePreview() void OBSBasic::EnablePreview() { - if (previewProgramMode) + if (previewProgramMode) { return; + } previewEnabled = true; EnablePreviewDisplay(true); @@ -281,8 +285,9 @@ void OBSBasic::EnablePreview() void OBSBasic::DisablePreview() { - if (previewProgramMode) + if (previewProgramMode) { return; + } previewEnabled = false; EnablePreviewDisplay(false); @@ -290,8 +295,9 @@ void OBSBasic::DisablePreview() static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param) { - if (obs_sceneitem_locked(item)) + if (obs_sceneitem_locked(item)) { return true; + } struct vec2 &offset = *static_cast(param); struct vec2 pos; @@ -323,8 +329,9 @@ static bool nudge_callback(obs_scene_t *, obs_sceneitem_t *item, void *param) void OBSBasic::Nudge(int dist, MoveDir dir) { - if (ui->preview->Locked()) + if (ui->preview->Locked()) { return; + } struct vec2 offset; vec2_set(&offset, 0.0f, 0.0f); @@ -448,8 +455,9 @@ void OBSBasic::ColorChange() QAction *action = qobject_cast(sender()); QPushButton *colorButton = qobject_cast(sender()); - if (selectedItems.count() == 0) + if (selectedItems.count() == 0) { return; + } if (colorButton) { int preset = colorButton->property("bgColor").value(); @@ -550,14 +558,16 @@ void OBSBasic::ColorChange() void OBSBasic::UpdateProjectorHideCursor() { - for (size_t i = 0; i < projectors.size(); i++) + for (size_t i = 0; i < projectors.size(); i++) { projectors[i]->SetHideCursor(); + } } void OBSBasic::UpdateProjectorAlwaysOnTop(bool top) { - for (size_t i = 0; i < projectors.size(); i++) + for (size_t i = 0; i < projectors.size(); i++) { SetAlwaysOnTop(projectors[i], top); + } } void OBSBasic::ResetProjectors() diff --git a/frontend/widgets/OBSBasic_Profiles.cpp b/frontend/widgets/OBSBasic_Profiles.cpp index 0555357011ae7f..836be77ac0743d 100644 --- a/frontend/widgets/OBSBasic_Profiles.cpp +++ b/frontend/widgets/OBSBasic_Profiles.cpp @@ -538,8 +538,9 @@ void OBSBasic::on_actionRemoveProfile_triggered(bool skipConfirmation) RemoveProfile(currentProfile); #ifdef YOUTUBE_ENABLED - if (YouTubeAppDock::IsYTServiceSelected() && !youtubeAppDock) + if (YouTubeAppDock::IsYTServiceSelected() && !youtubeAppDock) { NewYouTubeAppDock(); + } #endif blog(LOG_INFO, "Switched to profile '%s' (%s)", newProfile.name.c_str(), newProfile.directoryName.c_str()); @@ -710,8 +711,9 @@ void OBSBasic::ActivateProfile(const OBSProfile &profile, bool reset) Auth::Load(); #ifdef YOUTUBE_ENABLED - if (YouTubeAppDock::IsYTServiceSelected() && !youtubeAppDock) + if (YouTubeAppDock::IsYTServiceSelected() && !youtubeAppDock) { NewYouTubeAppDock(); + } #endif OnEvent(OBS_FRONTEND_EVENT_PROFILE_CHANGED); @@ -802,27 +804,31 @@ void OBSBasic::CheckForSimpleModeX264Fallback() const char *id; while (obs_enum_encoder_types(idx++, &id)) { - if (strcmp(id, "h264_texture_amf") == 0) + if (strcmp(id, "h264_texture_amf") == 0) { amd_supported = true; - else if (strcmp(id, "obs_qsv11") == 0) + } else if (strcmp(id, "obs_qsv11") == 0) { qsv_supported = true; - else if (strcmp(id, "obs_qsv11_av1") == 0) + } else if (strcmp(id, "obs_qsv11_av1") == 0) { qsv_av1_supported = true; - else if (strcmp(id, "ffmpeg_nvenc") == 0) + } else if (strcmp(id, "ffmpeg_nvenc") == 0) { nve_supported = true; + } #ifdef ENABLE_HEVC - else if (strcmp(id, "h265_texture_amf") == 0) + else if (strcmp(id, "h265_texture_amf") == 0) { amd_hevc_supported = true; - else if (strcmp(id, "ffmpeg_hevc_nvenc") == 0) + } else if (strcmp(id, "ffmpeg_hevc_nvenc") == 0) { nve_hevc_supported = true; + } #endif - else if (strcmp(id, "av1_texture_amf") == 0) + 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 } @@ -896,10 +902,12 @@ void OBSBasic::CheckForSimpleModeX264Fallback() return true; }; - if (!CheckEncoder(curStreamEncoder)) + if (!CheckEncoder(curStreamEncoder)) { config_set_string(activeConfiguration, "SimpleOutput", "StreamEncoder", curStreamEncoder); - if (!CheckEncoder(curRecEncoder)) + } + if (!CheckEncoder(curRecEncoder)) { config_set_string(activeConfiguration, "SimpleOutput", "RecEncoder", curRecEncoder); + } if (changed) { activeConfiguration.SaveSafe("tmp"); } diff --git a/frontend/widgets/OBSBasic_Projectors.cpp b/frontend/widgets/OBSBasic_Projectors.cpp index afde7038b12581..01fd94bf437dac 100644 --- a/frontend/widgets/OBSBasic_Projectors.cpp +++ b/frontend/widgets/OBSBasic_Projectors.cpp @@ -25,8 +25,9 @@ obs_data_array_t *OBSBasic::SaveProjectors() obs_data_array_t *savedProjectors = obs_data_array_create(); auto saveProjector = [savedProjectors](OBSProjector *projector) { - if (!projector) + if (!projector) { return; + } OBSDataAutoRelease data = obs_data_create(); ProjectorType type = projector->GetProjectorType(); @@ -47,16 +48,18 @@ obs_data_array_t *OBSBasic::SaveProjectors() obs_data_set_int(data, "type", static_cast(type)); obs_data_set_string(data, "geometry", projector->saveGeometry().toBase64().constData()); - if (projector->IsAlwaysOnTopOverridden()) + if (projector->IsAlwaysOnTopOverridden()) { obs_data_set_bool(data, "alwaysOnTop", projector->IsAlwaysOnTop()); + } obs_data_set_bool(data, "alwaysOnTopOverridden", projector->IsAlwaysOnTopOverridden()); obs_data_array_push_back(savedProjectors, data); }; - for (size_t i = 0; i < projectors.size(); i++) + for (size_t i = 0; i < projectors.size(); i++) { saveProjector(static_cast(projectors[i])); + } return savedProjectors; } @@ -91,8 +94,9 @@ void OBSBasic::updateMultiviewProjectorMenu() void OBSBasic::ClearProjectors() { for (size_t i = 0; i < projectors.size(); i++) { - if (projectors[i]) + if (projectors[i]) { delete projectors[i]; + } } projectors.clear(); @@ -112,8 +116,9 @@ QList OBSBasic::GetProjectorMenuMonitorsFormatted() #else name = screen->model().simplified(); - if (name.length() > 1 && name.endsWith("-")) + if (name.length() > 1 && name.endsWith("-")) { name.chop(1); + } #endif name = name.simplified(); @@ -146,16 +151,18 @@ void OBSBasic::DeleteProjector(OBSProjector *projector) OBSProjector *OBSBasic::OpenProjector(obs_source_t *source, int monitor, ProjectorType type) { /* seriously? 10 monitors? */ - if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1) + if (monitor > 9 || monitor > QGuiApplication::screens().size() - 1) { return nullptr; + } bool closeProjectors = config_get_bool(App()->GetUserConfig(), "BasicWindow", "CloseExistingProjectors"); if (closeProjectors && monitor > -1) { for (size_t i = projectors.size(); i > 0; i--) { size_t idx = i - 1; - if (projectors[idx]->GetMonitor() == monitor) + if (projectors[idx]->GetMonitor() == monitor) { DeleteProjector(projectors[idx]); + } } } @@ -176,8 +183,9 @@ void OBSBasic::OpenSourceProjector() { int monitor = sender()->property("monitor").toInt(); OBSSceneItem item = GetCurrentSceneItem(); - if (!item) + if (!item) { return; + } OpenProjector(obs_sceneitem_get_source(item), monitor, ProjectorType::Source); } @@ -192,8 +200,9 @@ void OBSBasic::OpenSceneProjector() { int monitor = sender()->property("monitor").toInt(); OBSScene scene = GetCurrentScene(); - if (!scene) + if (!scene) { return; + } OpenProjector(obs_scene_get_source(scene), monitor, ProjectorType::Scene); } @@ -206,8 +215,9 @@ void OBSBasic::OpenPreviewWindow() void OBSBasic::OpenSourceWindow() { OBSSceneItem item = GetCurrentSceneItem(); - if (!item) + if (!item) { return; + } OBSSource source = obs_sceneitem_get_source(item); @@ -217,8 +227,9 @@ void OBSBasic::OpenSourceWindow() void OBSBasic::OpenSceneWindow() { OBSScene scene = GetCurrentScene(); - if (!scene) + if (!scene) { return; + } OBSSource source = obs_scene_get_source(scene); @@ -233,8 +244,9 @@ void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info) case ProjectorType::Source: case ProjectorType::Scene: { OBSSourceAutoRelease source = obs_get_source_by_name(info->name.c_str()); - if (!source) + if (!source) { return; + } projector = OpenProjector(source, info->monitor, info->type); break; @@ -255,8 +267,9 @@ void OBSBasic::OpenSavedProjector(SavedProjectorInfo *info) QStyle::alignedRect(Qt::LeftToRight, Qt::AlignCenter, size(), rect)); } - if (info->alwaysOnTopOverridden) + if (info->alwaysOnTopOverridden) { projector->SetIsAlwaysOnTop(info->alwaysOnTop, true); + } } } } diff --git a/frontend/widgets/OBSBasic_Recording.cpp b/frontend/widgets/OBSBasic_Recording.cpp index 83f0304887d917..19981fc2bd053d 100644 --- a/frontend/widgets/OBSBasic_Recording.cpp +++ b/frontend/widgets/OBSBasic_Recording.cpp @@ -50,8 +50,9 @@ void OBSBasic::AutoRemux(QString input, bool no_show) bool autoRemux = config_get_bool(config, "Video", "AutoRemux"); - if (!autoRemux) + if (!autoRemux) { return; + } bool isSimpleMode = false; @@ -67,12 +68,14 @@ void OBSBasic::AutoRemux(QString input, bool no_show) bool ffmpegOutput = astrcmpi(recType, "FFmpeg") == 0; - if (ffmpegOutput) + if (ffmpegOutput) { return; + } } - if (input.isEmpty()) + if (input.isEmpty()) { return; + } QFileInfo fi(input); QString suffix = fi.suffix(); @@ -101,17 +104,20 @@ void OBSBasic::AutoRemux(QString input, bool no_show) } OBSRemux *remux = new OBSRemux(QT_TO_UTF8(path), this, true); - if (!no_show) + if (!no_show) { remux->show(); + } remux->AutoRemux(input, output); } void OBSBasic::StartRecording() { - if (outputHandler->RecordingActive()) + if (outputHandler->RecordingActive()) { return; - if (disableOutputsRef) + } + if (disableOutputsRef) { return; + } if (!OutputPathValid()) { OutputPathInvalidMessage(); @@ -134,8 +140,9 @@ void OBSBasic::RecordStopping() { emit RecordingStopping(); - if (sysTrayRecord) + if (sysTrayRecord) { sysTrayRecord->setText(QTStr("Basic.Main.StoppingRecording")); + } recordingStopping = true; OnEvent(OBS_FRONTEND_EVENT_RECORDING_STOPPING); @@ -145,8 +152,9 @@ void OBSBasic::StopRecording() { SaveProject(); - if (outputHandler->RecordingActive()) + if (outputHandler->RecordingActive()) { outputHandler->StopRecording(recordingStopping); + } OnDeactivate(); } @@ -156,14 +164,16 @@ void OBSBasic::RecordingStart() ui->statusbar->RecordingStarted(outputHandler->fileOutput); emit RecordingStarted(isRecordingPausable); - if (sysTrayRecord) + if (sysTrayRecord) { sysTrayRecord->setText(QTStr("Basic.Main.StopRecording")); + } recordingStopping = false; OnEvent(OBS_FRONTEND_EVENT_RECORDING_STARTED); - if (!diskFullTimer->isActive()) + if (!diskFullTimer->isActive()) { diskFullTimer->start(1000); + } OnActivate(); @@ -175,8 +185,9 @@ void OBSBasic::RecordingStop(int code, QString last_error) ui->statusbar->RecordingStopped(); emit RecordingStopped(); - if (sysTrayRecord) + if (sysTrayRecord) { sysTrayRecord->setText(QTStr("Basic.Main.StartRecording")); + } blog(LOG_INFO, RECORDING_STOP); @@ -200,10 +211,11 @@ void OBSBasic::RecordingStop(int code, QString last_error) errorDescription = Str("Output.RecordError.Msg"); - if (use_last_error && !last_error.isEmpty()) + if (use_last_error && !last_error.isEmpty()) { dstr_printf(errorMessage, "%s

%s", errorDescription, QT_TO_UTF8(last_error)); - else + } else { dstr_copy(errorMessage, errorDescription); + } OBSMessageBox::critical(this, QTStr("Output.RecordError.Title"), QT_UTF8(errorMessage)); @@ -225,8 +237,9 @@ void OBSBasic::RecordingStop(int code, QString last_error) OnEvent(OBS_FRONTEND_EVENT_RECORDING_STOPPED); - if (diskFullTimer->isActive()) + if (diskFullTimer->isActive()) { diskFullTimer->stop(); + } AutoRemux(outputHandler->lastRecordingPath.c_str()); @@ -251,13 +264,15 @@ void OBSBasic::RecordActionTriggered() this, QTStr("ConfirmStopRecord.Title"), QTStr("ConfirmStopRecord.Text"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return; + } } StopRecording(); } else { - if (!UIValidation::NoSourcesConfirmation(this)) + if (!UIValidation::NoSourcesConfirmation(this)) { return; + } StartRecording(); } @@ -265,16 +280,18 @@ void OBSBasic::RecordActionTriggered() bool OBSBasic::RecordingActive() { - if (!outputHandler) + if (!outputHandler) { return false; + } return outputHandler->RecordingActive(); } void OBSBasic::PauseRecording() { if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput || - os_atomic_load_bool(&recording_paused)) + os_atomic_load_bool(&recording_paused)) { return; + } obs_output_t *output = outputHandler->fileOutput; @@ -298,16 +315,18 @@ void OBSBasic::PauseRecording() OnEvent(OBS_FRONTEND_EVENT_RECORDING_PAUSED); - if (os_atomic_load_bool(&replaybuf_active)) + if (os_atomic_load_bool(&replaybuf_active)) { ShowReplayBufferPauseWarning(); + } } } void OBSBasic::UnpauseRecording() { if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput || - !os_atomic_load_bool(&recording_paused)) + !os_atomic_load_bool(&recording_paused)) { return; + } obs_output_t *output = outputHandler->fileOutput; @@ -335,16 +354,18 @@ void OBSBasic::UnpauseRecording() void OBSBasic::RecordPauseToggled() { - if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput) + if (!isRecordingPausable || !outputHandler || !outputHandler->fileOutput) { return; + } obs_output_t *output = outputHandler->fileOutput; bool enable = !obs_output_paused(output); - if (enable) + if (enable) { PauseRecording(); - else + } else { UnpauseRecording(); + } } void OBSBasic::UpdateIsRecordingPausable() @@ -386,15 +407,17 @@ bool OBSBasic::LowDiskSpace() const char *path; path = GetCurrentOutputPath(); - if (!path) + if (!path) { return false; + } uint64_t num_bytes = os_get_free_disk_space(path); - if (num_bytes < (MAX_BYTES_LEFT)) + if (num_bytes < (MAX_BYTES_LEFT)) { return true; - else + } else { return false; + } } void OBSBasic::CheckDiskSpaceRemaining() diff --git a/frontend/widgets/OBSBasic_ReplayBuffer.cpp b/frontend/widgets/OBSBasic_ReplayBuffer.cpp index 8d95f2210677ba..850f43806534dd 100644 --- a/frontend/widgets/OBSBasic_ReplayBuffer.cpp +++ b/frontend/widgets/OBSBasic_ReplayBuffer.cpp @@ -30,10 +30,11 @@ void OBSBasic::ReplayBufferActionTriggered() { - if (outputHandler->ReplayBufferActive()) + if (outputHandler->ReplayBufferActive()) { StopReplayBuffer(); - else + } else { StartReplayBuffer(); + } }; void OBSBasic::ShowReplayBufferPauseWarning() @@ -66,15 +67,19 @@ void OBSBasic::ShowReplayBufferPauseWarning() void OBSBasic::StartReplayBuffer() { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; - if (outputHandler->ReplayBufferActive()) + } + if (outputHandler->ReplayBufferActive()) { return; - if (disableOutputsRef) + } + if (disableOutputsRef) { return; + } - if (!UIValidation::NoSourcesConfirmation(this)) + if (!UIValidation::NoSourcesConfirmation(this)) { return; + } if (!OutputPathValid()) { OutputPathInvalidMessage(); @@ -97,13 +102,15 @@ void OBSBasic::StartReplayBuffer() void OBSBasic::ReplayBufferStopping() { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; + } emit ReplayBufStopping(); - if (sysTrayReplayBuffer) + if (sysTrayReplayBuffer) { sysTrayReplayBuffer->setText(QTStr("Basic.Main.StoppingReplayBuffer")); + } replayBufferStopping = true; OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STOPPING); @@ -111,26 +118,30 @@ void OBSBasic::ReplayBufferStopping() void OBSBasic::StopReplayBuffer() { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; + } SaveProject(); - if (outputHandler->ReplayBufferActive()) + if (outputHandler->ReplayBufferActive()) { outputHandler->StopReplayBuffer(replayBufferStopping); + } OnDeactivate(); } void OBSBasic::ReplayBufferStart() { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; + } emit ReplayBufStarted(); - if (sysTrayReplayBuffer) + if (sysTrayReplayBuffer) { sysTrayReplayBuffer->setText(QTStr("Basic.Main.StopReplayBuffer")); + } replayBufferStopping = false; OnEvent(OBS_FRONTEND_EVENT_REPLAY_BUFFER_STARTED); @@ -142,10 +153,12 @@ void OBSBasic::ReplayBufferStart() void OBSBasic::ReplayBufferSave() { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; - if (!outputHandler->ReplayBufferActive()) + } + if (!outputHandler->ReplayBufferActive()) { return; + } calldata_t cd = {0}; proc_handler_t *ph = obs_output_get_proc_handler(outputHandler->replayBuffer); @@ -155,10 +168,12 @@ void OBSBasic::ReplayBufferSave() void OBSBasic::ReplayBufferSaved() { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; - if (!outputHandler->ReplayBufferActive()) + } + if (!outputHandler->ReplayBufferActive()) { return; + } calldata_t cd = {0}; proc_handler_t *ph = obs_output_get_proc_handler(outputHandler->replayBuffer); @@ -176,13 +191,15 @@ void OBSBasic::ReplayBufferSaved() void OBSBasic::ReplayBufferStop(int code) { - if (!outputHandler || !outputHandler->replayBuffer) + if (!outputHandler || !outputHandler->replayBuffer) { return; + } emit ReplayBufStopped(); - if (sysTrayReplayBuffer) + if (sysTrayReplayBuffer) { sysTrayReplayBuffer->setText(QTStr("Basic.Main.StartReplayBuffer")); + } blog(LOG_INFO, REPLAY_BUFFER_STOP); @@ -212,7 +229,8 @@ void OBSBasic::ReplayBufferStop(int code) bool OBSBasic::ReplayBufferActive() { - if (!outputHandler) + if (!outputHandler) { return false; + } return outputHandler->ReplayBufferActive(); } diff --git a/frontend/widgets/OBSBasic_SceneCollections.cpp b/frontend/widgets/OBSBasic_SceneCollections.cpp index 84ecbbb90134e6..0a07c60cb25b15 100644 --- a/frontend/widgets/OBSBasic_SceneCollections.cpp +++ b/frontend/widgets/OBSBasic_SceneCollections.cpp @@ -729,8 +729,9 @@ void OBSBasic::on_actionRemigrateSceneCollection_triggered() auto answer = OBSMessageBox::question(this, QTStr("Basic.Main.RemigrateSceneCollection.Title"), message); - if (answer == QMessageBox::No) + if (answer == QMessageBox::No) { return; + } lastOutputResolution = {ovi.base_width, ovi.base_height}; if (currentCoordinateMode == SceneCoordinateMode::Relative) { @@ -833,8 +834,9 @@ void OBSBasic::Save(SceneCollection &collection) // Save all non-scene sources first auto FilterAudioSources = [&](obs_source_t *source) { - if (obs_source_is_group(source) || obs_source_is_scene(source)) + if (obs_source_is_group(source) || obs_source_is_scene(source)) { return false; + } return std::find(begin(audioSources), end(audioSources), source) == end(audioSources); }; @@ -871,8 +873,9 @@ void OBSBasic::Save(SceneCollection &collection) // Iterate over our additional canvases (if any), save their scenes and groups. for (const auto &canvas : canvases) { // Do not store sources from ephemeral canvases. - if (obs_canvas_get_flags(canvas) & EPHEMERAL) + if (obs_canvas_get_flags(canvas) & EPHEMERAL) { continue; + } obs_canvas_enum_scenes(canvas, exportSceneItemsCallback, &sourcesAndGroups); } @@ -887,8 +890,9 @@ void OBSBasic::Save(SceneCollection &collection) // Current preview/program scenes OBSScene scene = GetCurrentScene(); OBSSource curProgramScene = OBSGetStrongRef(programScene); - if (!curProgramScene) + if (!curProgramScene) { curProgramScene = obs_scene_get_source(scene); + } obs_data_set_string(saveData, "current_scene", obs_source_get_name(obs_scene_get_source(scene))); obs_data_set_string(saveData, "current_program_scene", obs_source_get_name(curProgramScene)); @@ -941,8 +945,9 @@ void OBSBasic::Save(SceneCollection &collection) // Module-specific data if (api) { - if (!collectionModuleData) + if (!collectionModuleData) { collectionModuleData = obs_data_create(); + } api->on_save(collectionModuleData); obs_data_set_obj(saveData, "modules", collectionModuleData); @@ -1002,12 +1007,14 @@ static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val); static void LoadAudioDevice(const char *name, int channel, obs_data_t *parent) { OBSDataAutoRelease data = obs_data_get_obj(parent, name); - if (!data) + if (!data) { return; + } OBSSourceAutoRelease source = obs_load_source(data); - if (!source) + if (!source) { return; + } obs_set_output_source(channel, source); @@ -1037,8 +1044,9 @@ void OBSBasic::CreateDefaultScene(bool firstStart) OBSSceneAutoRelease scene = obs_scene_create(Str("Basic.Scene")); - if (firstStart) + if (firstStart) { CreateFirstRunSources(); + } SetCurrentScene(scene, true); @@ -1052,8 +1060,9 @@ static void LogFilter(obs_source_t *, obs_source_t *filter, void *v_val) int val = (int)(intptr_t)v_val; string indent; - for (int i = 0; i < val; i++) + for (int i = 0; i < val; i++) { indent += " "; + } blog(LOG_INFO, "%s- filter: '%s' (%s)", indent.c_str(), name, id); } @@ -1066,8 +1075,9 @@ static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val) int indent_count = (int)(intptr_t)v_val; string indent; - for (int i = 0; i < indent_count; i++) + for (int i = 0; i < indent_count; i++) { indent += " "; + } blog(LOG_INFO, "%s- source: '%s' (%s)", indent.c_str(), name, id); @@ -1084,15 +1094,18 @@ static bool LogSceneItem(obs_scene_t *, obs_sceneitem_t *item, void *v_val) 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) + 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)); - if (hide_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)); + } - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, LogSceneItem, (void *)(intptr_t)child_indent); + } return true; } @@ -1188,8 +1201,9 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) QApplication::sendPostedEvents(nullptr); OBSDataAutoRelease modulesObj = obs_data_get_obj(data, "modules"); - if (api) + if (api) { api->on_preload(modulesObj); + } /* Keep a reference to "modules" data so plugins that are not loaded do * not have their collection specific data lost. */ @@ -1206,16 +1220,19 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) if (!opt_starting_scene.empty()) { programSceneName = opt_starting_scene.c_str(); - if (!IsPreviewProgramMode()) + if (!IsPreviewProgramMode()) { sceneName = opt_starting_scene.c_str(); + } } int newDuration = obs_data_get_int(data, "transition_duration"); - if (!newDuration) + if (!newDuration) { newDuration = 300; + } - if (!transitionName) + if (!transitionName) { transitionName = obs_source_get_name(fadeTransition); + } const char *curSceneCollection = config_get_string(App()->GetUserConfig(), "Basic", "SceneCollection"); @@ -1226,8 +1243,9 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) OBSSourceAutoRelease curProgramScene; obs_source_t *curTransition; - if (!name || !*name) + if (!name || !*name) { name = curSceneCollection; + } LoadAudioDevice(DESKTOP_AUDIO_1.data(), 1, data); LoadAudioDevice(DESKTOP_AUDIO_2.data(), 2, data); @@ -1236,8 +1254,9 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) LoadAudioDevice(AUX_AUDIO_3.data(), 5, data); LoadAudioDevice(AUX_AUDIO_4.data(), 6, data); - if (collection_canvases) + if (collection_canvases) { canvases = OBS::Canvas::LoadCanvases(collection_canvases); + } if (!sources) { sources = std::move(groups); @@ -1319,16 +1338,20 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) obs_missing_files_t *files = obs_missing_files_create(); obs_load_sources(sources, AddMissingFiles, files); - if (resetVideo) + if (resetVideo) { ResetVideo(); - if (transitionsData) + } + if (transitionsData) { LoadTransitions(transitionsData, AddMissingFiles, files); - if (sceneOrder) + } + if (sceneOrder) { LoadSceneListOrder(sceneOrder); + } curTransition = FindTransition(transitionName); - if (!curTransition) + if (!curTransition) { curTransition = fadeTransition; + } SetTransitionDuration(newDuration); SetTransition(curTransition); @@ -1356,10 +1379,12 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) SetCurrentScene(curScene.Get(), true); - if (!curProgramScene) + if (!curProgramScene) { curProgramScene = std::move(curScene); - if (IsPreviewProgramMode()) + } + if (IsPreviewProgramMode()) { TransitionToScene(curProgramScene.Get(), true); + } /* ------------------- */ @@ -1407,8 +1432,9 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) OBSDataAutoRelease obj = obs_data_get_obj(data, "virtual-camera"); vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type2"); - if (vcamConfig.type == VCamOutputType::Invalid) + if (vcamConfig.type == VCamOutputType::Invalid) { vcamConfig.type = (VCamOutputType)obs_data_get_int(obj, "type"); + } if (vcamConfig.type == VCamOutputType::Invalid) { VCamInternalType internal = (VCamInternalType)obs_data_get_int(obj, "internal"); @@ -1432,13 +1458,15 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) /* ---------------------- */ - if (api) + if (api) { api->on_load(modulesObj); + } obs_data_release(data); - if (!opt_starting_scene.empty()) + if (!opt_starting_scene.empty()) { opt_starting_scene.clear(); + } if (opt_start_streaming && !safe_mode) { blog(LOG_INFO, "Starting stream due to command line parameter"); @@ -1464,13 +1492,15 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) LogScenes(); - if (!App()->IsMissingFilesCheckDisabled()) + if (!App()->IsMissingFilesCheckDisabled()) { ShowMissingFilesDialog(files); + } disableSaving--; - if (vcamEnabled) + if (vcamEnabled) { outputHandler->UpdateVirtualCamOutputSource(); + } OnEvent(OBS_FRONTEND_EVENT_SCENE_CHANGED); OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED); @@ -1478,8 +1508,9 @@ void OBSBasic::LoadData(obs_data_t *data, SceneCollection &collection) void OBSBasic::SaveProjectNow() { - if (disableSaving) + if (disableSaving) { return; + } projectChanged = true; SaveProjectDeferred(); @@ -1487,8 +1518,9 @@ void OBSBasic::SaveProjectNow() void OBSBasic::SaveProject() { - if (disableSaving) + if (disableSaving) { return; + } projectChanged = true; QMetaObject::invokeMethod(this, "SaveProjectDeferred", Qt::QueuedConnection); @@ -1496,11 +1528,13 @@ void OBSBasic::SaveProject() void OBSBasic::SaveProjectDeferred() { - if (disableSaving) + if (disableSaving) { return; + } - if (!projectChanged) + if (!projectChanged) { return; + } projectChanged = false; @@ -1533,8 +1567,9 @@ void OBSBasic::ClearSceneData() ClearProjectors(); - for (int i = 0; i < MAX_CHANNELS; i++) + for (int i = 0; i < MAX_CHANNELS; i++) { obs_set_output_source(i, nullptr); + } /* Reset VCam to default to clear its private scene and any references * it holds. It will be reconfigured during loading. */ @@ -1640,9 +1675,10 @@ void OBSBasic::ShowMissingFilesDialog(obs_missing_files_t *files) obs_missing_files_destroy(files); /* Only raise dialog if triggered manually */ - if (!disableSaving) + if (!disableSaving) { OBSMessageBox::information(this, QTStr("MissingFiles.NoMissing.Title"), QTStr("MissingFiles.NoMissing.Text")); + } } } diff --git a/frontend/widgets/OBSBasic_SceneItems.cpp b/frontend/widgets/OBSBasic_SceneItems.cpp index 84eed637db52aa..4b183cfa72e245 100644 --- a/frontend/widgets/OBSBasic_SceneItems.cpp +++ b/frontend/widgets/OBSBasic_SceneItems.cpp @@ -57,12 +57,14 @@ static inline bool HasAudioDevices(const char *source_id) obs_properties_t *props = obs_get_source_properties(output_id); size_t count = 0; - if (!props) + if (!props) { return false; + } obs_property_t *devices = obs_properties_get(props, "device_id"); - if (devices) + if (devices) { count = obs_property_list_item_count(devices); + } obs_properties_destroy(props); @@ -82,10 +84,12 @@ void OBSBasic::CreateFirstRunSources() } #endif - if (hasDesktopAudio) + if (hasDesktopAudio) { ResetAudioDevice(App()->OutputAudioSource(), "default", Str("Basic.DesktopDevice1"), 1); - if (hasInputAudio) + } + if (hasInputAudio) { ResetAudioDevice(App()->InputAudioSource(), "default", Str("Basic.AuxDevice1"), 3); + } } OBSSceneItem OBSBasic::GetSceneItem(QListWidgetItem *item) @@ -102,24 +106,28 @@ static void RenameListValues(QListWidget *listWidget, const QString &newName, co { QList items = listWidget->findItems(prevName, Qt::MatchExactly); - for (int i = 0; i < items.count(); i++) + for (int i = 0; i < items.count(); i++) { items[i]->setText(newName); + } } 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(); obs_scene_t *scene = obs_scene_from_source(source); - if (scene) + if (scene) { OBSProjector::UpdateMultiviewProjectors(); + } UpdateContextBar(); UpdatePreviewProgramIndicators(); @@ -154,8 +162,9 @@ bool OBSBasic::QueryRemoveSource(obs_source_t *source) void OBSBasic::ReorderSources(OBSScene scene) { - if (scene != GetCurrentScene() || ui->sources->IgnoreReorder()) + if (scene != GetCurrentScene() || ui->sources->IgnoreReorder()) { return; + } ui->sources->ReorderItems(); SaveProject(); @@ -163,8 +172,9 @@ void OBSBasic::ReorderSources(OBSScene scene) void OBSBasic::RefreshSources(OBSScene scene) { - if (scene != GetCurrentScene() || ui->sources->IgnoreReorder()) + if (scene != GetCurrentScene() || ui->sources->IgnoreReorder()) { return; + } ui->sources->RefreshItems(); SaveProject(); @@ -174,18 +184,20 @@ 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) + if (obs_scene_from_source(source) != NULL) { QMetaObject::invokeMethod(static_cast(data), "AddScene", WaitConnection(), Q_ARG(OBSSource, OBSSource(source))); + } } 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) + if (obs_scene_from_source(source) != NULL) { QMetaObject::invokeMethod(static_cast(data), "RemoveScene", Q_ARG(OBSSource, OBSSource(source))); + } } void OBSBasic::SourceRenamed(void *data, calldata_t *params) @@ -244,8 +256,9 @@ void OBSBasic::SetDeinterlacingMode() auto undo_redo = [](const std::string &uuid, obs_deinterlace_mode val) { OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); - if (source) + if (source) { obs_source_set_deinterlace_mode(source, val); + } }; const char *uuid = obs_source_get_uuid(source); @@ -272,8 +285,9 @@ void OBSBasic::SetDeinterlacingOrder() auto undo_redo = [](const std::string &uuid, obs_deinterlace_field_order val) { OBSSourceAutoRelease source = obs_get_source_by_uuid(uuid.c_str()); - if (source) + if (source) { obs_source_set_deinterlace_field_order(source, val); + } }; const char *uuid = obs_source_get_uuid(source); @@ -339,8 +353,9 @@ void OBSBasic::SetScaleFilter() 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); - if (si) + if (si) { obs_sceneitem_set_scale_filter(si, val); + } }; OBSSource source = obs_sceneitem_get_source(sceneItem); @@ -394,8 +409,9 @@ void OBSBasic::SetBlendingMethod() 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); - if (si) + if (si) { obs_sceneitem_set_blending_method(si, val); + } }; OBSSource source = obs_sceneitem_get_source(sceneItem); @@ -445,8 +461,9 @@ void OBSBasic::SetBlendingMode() 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); - if (si) + if (si) { obs_sceneitem_set_blending_mode(si, val); + } }; OBSSource source = obs_sceneitem_get_source(sceneItem); @@ -526,8 +543,9 @@ QMenu *OBSBasic::AddBackgroundColorMenu(QMenu *menu, QWidgetAction *widgetAction stringstream button; button << "preset" << i; QPushButton *colorButton = select->findChild(button.str().c_str()); - if (preset == i + 1) + if (preset == i + 1) { colorButton->setStyleSheet("border: 2px solid black"); + } colorButton->setProperty("bgColor", i); connect(colorButton, &QPushButton::released, this, &OBSBasic::ColorChange); @@ -582,8 +600,9 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) popup.addAction(QTStr("Basic.Main.PreviewConextMenu.Enable"), this, &OBSBasic::TogglePreview); action->setCheckable(true); action->setChecked(obs_display_enabled(ui->preview->GetDisplay())); - if (IsPreviewProgramMode()) + if (IsPreviewProgramMode()) { action->setEnabled(false); + } popup.addAction(ui->actionLockPreview); popup.addMenu(ui->scalingMenu); @@ -673,8 +692,9 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) resizeOutput->setEnabled(!obs_video_active()); - if (width < 32 || height < 32) + if (width < 32 || height < 32) { resizeOutput->setEnabled(false); + } } popup.addSeparator(); @@ -713,8 +733,9 @@ void OBSBasic::CreateSourcePopupMenu(int idx, bool preview) popup.addAction(renameSource); popup.addSeparator(); - if (flags && flags & OBS_SOURCE_INTERACTION) + if (flags && flags & OBS_SOURCE_INTERACTION) { popup.addAction(QTStr("Interact"), this, &OBSBasic::on_actionInteract_triggered); + } popup.addAction(QTStr("Filters"), this, [&]() { OpenFilters(); }); QAction *action = @@ -762,16 +783,20 @@ void OBSBasic::on_sources_customContextMenuRequested(const QPoint &pos) static inline bool should_show_properties(obs_source_t *source, const char *id) { - if (!source) + if (!source) { return false; - if (strcmp(id, "group") == 0) + } + if (strcmp(id, "group") == 0) { return false; - if (!obs_source_configurable(source)) + } + if (!obs_source_configurable(source)) { return false; + } uint32_t caps = obs_source_get_output_flags(source); - if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0) + if ((caps & OBS_SOURCE_CAP_DONT_SHOW_PROPERTIES) != 0) { return false; + } return true; } @@ -802,8 +827,9 @@ 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; @@ -816,10 +842,11 @@ QMenu *OBSBasic::CreateAddSourcePopupMenu() QIcon icon; - if (strcmp(type, "scene") == 0) + if (strcmp(type, "scene") == 0) { icon = GetSceneIcon(); - else + } else { icon = GetSourceIcon(type); + } popupItem->setIcon(icon); @@ -831,8 +858,9 @@ QMenu *OBSBasic::CreateAddSourcePopupMenu() const char *name = obs_source_get_display_name(type); uint32_t caps = obs_get_source_output_flags(type); - if ((caps & OBS_SOURCE_CAP_DISABLED) != 0) + if ((caps & OBS_SOURCE_CAP_DISABLED) != 0) { continue; + } if ((caps & OBS_SOURCE_DEPRECATED) == 0) { addSource(popup, unversioned_type, name); @@ -878,8 +906,9 @@ void OBSBasic::AddSourcePopupMenu(const QPoint &pos) } QScopedPointer popup(CreateAddSourcePopupMenu()); - if (popup) + if (popup) { popup->exec(pos); + } } void OBSBasic::on_actionAddSource_triggered() @@ -907,8 +936,9 @@ void OBSBasic::on_actionRemoveSource_triggered() obs_scene_enum_items(scene, remove_items, &items); - if (!items.size()) + if (!items.size()) { return; + } /* ------------------------------------- */ /* confirm action with user */ @@ -931,11 +961,13 @@ void OBSBasic::on_actionRemoveSource_triggered() } else { OBSSceneItem &item = items[0]; obs_source_t *source = obs_sceneitem_get_source(item); - if (source && QueryRemoveSource(source)) + if (source && QueryRemoveSource(source)) { confirmed = true; + } } - if (!confirmed) + if (!confirmed) { return; + } /* ----------------------------------------------- */ /* save undo data */ @@ -945,8 +977,9 @@ void OBSBasic::on_actionRemoveSource_triggered() /* ----------------------------------------------- */ /* remove items */ - for (auto &item : items) + for (auto &item : items) { obs_sceneitem_remove(item); + } /* ----------------------------------------------- */ /* save redo data */ @@ -972,8 +1005,9 @@ void OBSBasic::on_actionInteract_triggered() OBSSceneItem item = GetCurrentSceneItem(); OBSSource source = obs_sceneitem_get_source(item); - if (source) + if (source) { CreateInteractionWindow(source); + } } void OBSBasic::on_actionSourceProperties_triggered() @@ -981,8 +1015,9 @@ void OBSBasic::on_actionSourceProperties_triggered() OBSSceneItem item = GetCurrentSceneItem(); OBSSource source = obs_sceneitem_get_source(item); - if (source) + if (source) { CreatePropertiesWindow(source); + } } void OBSBasic::on_actionSourceUp_triggered() @@ -1044,10 +1079,12 @@ void OBSBasic::OpenInteraction(OBSSource source) void OBSBasic::OpenEditTransform(OBSSceneItem item) { - if (!item) + if (!item) { item = GetCurrentSceneItem(); - if (!item) + } + if (!item) { return; + } CreateEditTransformWindow(item); } @@ -1065,8 +1102,9 @@ QModelIndexList OBSBasic::GetAllSelectedSourceItems() void OBSBasic::on_actionEditTransform_triggered() { const auto item = GetCurrentSceneItem(); - if (!item) + if (!item) { return; + } CreateEditTransformWindow(item); } @@ -1122,22 +1160,26 @@ static void SetItemTL(obs_sceneitem_t *item, const vec3 &tl) static bool RotateSelectedSources(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, RotateSelectedSources, param); - if (!obs_sceneitem_selected(item)) + } + if (!obs_sceneitem_selected(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; + } float rot = *static_cast(param); vec3 tl = GetItemTL(item); rot += obs_sceneitem_get_rot(item); - if (rot >= 360.0f) + if (rot >= 360.0f) { rot -= 360.0f; - else if (rot <= -360.0f) + } else if (rot <= -360.0f) { rot += 360.0f; + } obs_sceneitem_set_rot(item, rot); obs_sceneitem_force_update_transform(item); @@ -1193,12 +1235,15 @@ static bool MultiplySelectedItemScale(obs_scene_t * /* scene */, obs_sceneitem_t { vec2 &mul = *static_cast(param); - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, MultiplySelectedItemScale, param); - if (!obs_sceneitem_selected(item)) + } + if (!obs_sceneitem_selected(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; + } vec3 tl = GetItemTL(item); @@ -1248,12 +1293,15 @@ static bool CenterAlignSelectedItems(obs_scene_t * /* scene */, obs_sceneitem_t { obs_bounds_type boundsType = *static_cast(param); - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, CenterAlignSelectedItems, param); - if (!obs_sceneitem_selected(item)) + } + if (!obs_sceneitem_selected(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; + } obs_video_info ovi; obs_get_video_info(&ovi); @@ -1306,8 +1354,9 @@ void OBSBasic::CenterSelectedSceneItems(const CenterType ¢erType) { QModelIndexList selectedItems = GetAllSelectedSourceItems(); - if (!selectedItems.count()) + if (!selectedItems.count()) { return; + } vector items; @@ -1321,14 +1370,16 @@ void OBSBasic::CenterSelectedSceneItems(const CenterType ¢erType) float width = float(obs_source_get_width(source)) * oti.scale.x; float height = float(obs_source_get_height(source)) * oti.scale.y; - if (width == 0.0f || height == 0.0f) + if (width == 0.0f || height == 0.0f) { continue; + } items.emplace_back(item); } - if (!items.size()) + if (!items.size()) { return; + } // Get center x, y coordinates of items vec3 center; @@ -1376,10 +1427,11 @@ void OBSBasic::CenterSelectedSceneItems(const CenterType ¢erType) vec3 itemTL = GetItemTL(item); - if (centerType == CenterType::Vertical) + if (centerType == CenterType::Vertical) { tl.x = itemTL.x; - else if (centerType == CenterType::Horizontal) + } else if (centerType == CenterType::Horizontal) { tl.y = itemTL.y; + } SetItemTL(item, tl); } @@ -1430,8 +1482,9 @@ void OBSBasic::on_actionHorizontalCenter_triggered() void OBSBasic::on_toggleSourceIcons_toggled(bool visible) { ui->sources->SetIconsVisible(visible); - if (advAudioWindow != nullptr) + if (advAudioWindow != nullptr) { advAudioWindow->SetIconsVisible(visible); + } config_set_bool(App()->GetUserConfig(), "BasicWindow", "ShowSourceIcons", visible); } diff --git a/frontend/widgets/OBSBasic_Scenes.cpp b/frontend/widgets/OBSBasic_Scenes.cpp index 4fa69941ab5d7e..aa7584a4763d5d 100644 --- a/frontend/widgets/OBSBasic_Scenes.cpp +++ b/frontend/widgets/OBSBasic_Scenes.cpp @@ -118,8 +118,9 @@ void OBSBasic::AddScene(OBSSource source) auto potential_source = static_cast(data); OBSSourceAutoRelease source = obs_source_get_ref(potential_source); - if (source && pressed) + if (source && pressed) { main->SetCurrentScene(source.Get()); + } }, static_cast(source)); @@ -175,8 +176,9 @@ void OBSBasic::RemoveScene(OBSSource source) for (int i = 0; i < count; i++) { auto item = ui->scenes->item(i); auto cur_scene = GetOBSRef(item); - if (cur_scene != scene) + if (cur_scene != scene) { continue; + } foundItem = true; sel = item; @@ -184,8 +186,9 @@ void OBSBasic::RemoveScene(OBSSource source) } if (sel != nullptr) { - if (sel == ui->scenes->currentItem()) + if (sel == ui->scenes->currentItem()) { ui->sources->Clear(); + } delete sel; } @@ -205,8 +208,9 @@ void OBSBasic::RemoveScene(OBSSource source) static bool select_one(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *param) { obs_sceneitem_t *selectedItem = static_cast(param); - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, select_one, param); + } obs_sceneitem_select(item, (selectedItem == item)); @@ -217,8 +221,9 @@ void OBSBasic::AddSceneItem(OBSSceneItem item) { obs_scene_t *scene = obs_sceneitem_get_scene(item); - if (GetCurrentScene() == scene) + if (GetCurrentScene() == scene) { ui->sources->Add(item); + } SaveProject(); @@ -236,8 +241,9 @@ void OBSBasic::DuplicateSelectedScene() { OBSScene curScene = GetCurrentScene(); - if (!curScene) + if (!curScene) { return; + } OBSSource curSceneSource = obs_scene_get_source(curScene); QString format{obs_source_get_name(curSceneSource)}; @@ -254,8 +260,9 @@ void OBSBasic::DuplicateSelectedScene() string name; bool accepted = NameDialog::AskForName(this, QTStr("Basic.Main.AddSceneDlg.Title"), QTStr("Basic.Main.AddSceneDlg.Text"), name, placeHolderText); - if (!accepted) + if (!accepted) { return; + } if (name.empty()) { OBSMessageBox::warning(this, QTStr("NoNameEntered.Title"), QTStr("NoNameEntered.Text")); @@ -297,8 +304,9 @@ void OBSBasic::DuplicateSelectedScene() 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)) + if (obs_obj_is_private(source) && !obs_source_removed(source)) { return true; + } obs_data_array_t *array = (obs_data_array_t *)p; @@ -307,12 +315,14 @@ static bool save_undo_source_enum(obs_scene_t * /* scene */, obs_sceneitem_t *it const size_t count = obs_data_array_count(array); for (size_t i = 0; i < count; i++) { OBSDataAutoRelease sourceData = obs_data_array_item(array, i); - if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0) + if (strcmp(name, obs_data_get_string(sourceData, "name")) == 0) { return true; + } } - if (obs_source_is_group(source)) + if (obs_source_is_group(source)) { 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); @@ -323,8 +333,9 @@ static inline void RemoveSceneAndReleaseNested(obs_source_t *source) { obs_source_remove(source); auto cb = [](void *, obs_source_t *source) { - if (strcmp(obs_source_get_id(source), "scene") == 0) + if (strcmp(obs_source_get_id(source), "scene") == 0) { obs_scene_prune_sources(obs_scene_from_source(source)); + } return true; }; obs_enum_scenes(cb, NULL); @@ -363,8 +374,9 @@ void OBSBasic::RemoveSelectedScene() 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) + 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)); if (item) { @@ -403,8 +415,9 @@ void OBSBasic::RemoveSelectedScene() } /* actually load sources now */ - for (obs_source_t *source : sources) + for (obs_source_t *source : sources) { 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++) { @@ -512,8 +525,9 @@ void OBSBasic::on_scenes_currentItemChanged(QListWidgetItem *current, QListWidge SetCurrentScene(source, forceSceneChange); - if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput) + if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput) { outputHandler->UpdateVirtualCamOutputSource(); + } OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED); @@ -638,10 +652,11 @@ void OBSBasic::GridActionClicked() bool gridMode = !ui->scenes->GetGridMode(); ui->scenes->SetGridMode(gridMode); - if (gridMode) + if (gridMode) { ui->actionSceneGridMode->setChecked(true); - else + } else { ui->actionSceneListMode->setChecked(true); + } config_set_bool(App()->GetUserConfig(), "BasicWindow", "gridMode", gridMode); } @@ -705,14 +720,16 @@ void OBSBasic::on_actionRemoveScene_triggered() void OBSBasic::ChangeSceneIndex(bool relative, int offset, int invalidIdx) { int idx = ui->scenes->currentRow(); - if (idx == -1 || idx == invalidIdx) + if (idx == -1 || idx == invalidIdx) { return; + } ui->scenes->blockSignals(true); QListWidgetItem *item = ui->scenes->takeItem(idx); - if (!relative) + if (!relative) { idx = 0; + } ui->scenes->insertItem(idx + offset, item); ui->scenes->setCurrentRow(idx + offset); @@ -751,15 +768,17 @@ void OBSBasic::EditSceneItemName() void OBSBasic::on_scenes_itemDoubleClicked(QListWidgetItem *witem) { - if (!witem) + if (!witem) { return; + } if (IsPreviewProgramMode()) { bool doubleClickSwitch = config_get_bool(App()->GetUserConfig(), "BasicWindow", "TransitionOnDoubleClick"); - if (doubleClickSwitch) + if (doubleClickSwitch) { TransitionClicked(); + } } } @@ -811,8 +830,9 @@ void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, OBSData und const char *name = obs_data_get_string(data, "name"); OBSSourceAutoRelease source = obs_get_source_by_name(name); - if (!source) + if (!source) { source = obs_load_source(data); + } sources.push_back(source.Get()); @@ -827,8 +847,9 @@ void OBSBasic::CreateSceneUndoRedoAction(const QString &action_name, OBSData und } /* actually load sources now */ - for (obs_source_t *source : sources) + for (obs_source_t *source : sources) { obs_source_load2(source); + } ui->sources->RefreshItems(); }; @@ -844,13 +865,15 @@ void OBSBasic::MoveSceneItem(enum obs_order_movement movement, const QString &ac OBSSceneItem item = GetCurrentSceneItem(); obs_source_t *source = obs_sceneitem_get_source(item); - if (!source) + if (!source) { return; + } OBSScene scene = GetCurrentScene(); std::vector sources; - if (scene != obs_sceneitem_get_scene(item)) + if (scene != obs_sceneitem_get_scene(item)) { sources.push_back(obs_scene_get_source(obs_sceneitem_get_scene(item))); + } OBSData undo_data = BackupScene(scene, &sources); @@ -866,8 +889,9 @@ void OBSBasic::MoveSceneItem(enum obs_order_movement movement, const QString &ac 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) + if (name == prevName) { return; + } OBSSourceAutoRelease foundSource = obs_get_source_by_name(name.c_str()); QListWidgetItem *listItem = listWidget->currentItem(); @@ -905,8 +929,9 @@ void OBSBasic::SceneNameEdited(QWidget *editor) QLineEdit *edit = qobject_cast(editor); string text = QT_TO_UTF8(edit->text().trimmed()); - if (!scene) + if (!scene) { return; + } obs_source_t *source = obs_scene_get_source(scene); RenameListItem(this, ui->scenes, source, text); @@ -926,12 +951,15 @@ void OBSBasic::OpenSceneFilters() static bool reset_tr(obs_scene_t * /* scene */, obs_sceneitem_t *item, void *) { - if (obs_sceneitem_is_group(item)) + if (obs_sceneitem_is_group(item)) { obs_sceneitem_group_enum_items(item, reset_tr, nullptr); - if (!obs_sceneitem_selected(item)) + } + if (!obs_sceneitem_selected(item)) { return true; - if (obs_sceneitem_locked(item)) + } + if (obs_sceneitem_locked(item)) { return true; + } obs_sceneitem_defer_update_begin(item); @@ -981,8 +1009,9 @@ SourceTreeItem *OBSBasic::GetItemWidgetFromSceneItem(obs_sceneitem_t *sceneItem) treeItem = ui->sources->GetItemWidget(i); item = ui->sources->Get(i); } - if (treeItem) + if (treeItem) { return treeItem; + } return nullptr; } @@ -991,6 +1020,7 @@ void OBSBasic::on_actionSceneFilters_triggered() { OBSSource sceneSource = GetCurrentSceneSource(); - if (sceneSource) + if (sceneSource) { OpenFilters(sceneSource); + } } diff --git a/frontend/widgets/OBSBasic_Service.cpp b/frontend/widgets/OBSBasic_Service.cpp index ee201bc4d8c13b..5c70f48aee2ced 100644 --- a/frontend/widgets/OBSBasic_Service.cpp +++ b/frontend/widgets/OBSBasic_Service.cpp @@ -23,8 +23,9 @@ constexpr std::string_view OBSServiceFileName = "service.json"; void OBSBasic::SaveService() { - if (!service) + if (!service) { return; + } const OBSProfile ¤tProfile = GetCurrentProfile(); @@ -71,20 +72,23 @@ bool OBSBasic::LoadService() service = obs_service_create(type, "default_service", settings, hotkey_data); obs_service_release(service); - if (!service) + if (!service) { return false; + } /* Enforce Opus on WHIP if needed */ if (strcmp(obs_service_get_protocol(service), "WHIP") == 0) { const char *option = config_get_string(activeConfiguration, "SimpleOutput", "StreamAudioEncoder"); - if (strcmp(option, "opus") != 0) + if (strcmp(option, "opus") != 0) { config_set_string(activeConfiguration, "SimpleOutput", "StreamAudioEncoder", "opus"); + } option = config_get_string(activeConfiguration, "AdvOut", "AudioEncoder"); const char *encoder_codec = obs_get_encoder_codec(option); - if (!encoder_codec || strcmp(encoder_codec, "opus") != 0) + if (!encoder_codec || strcmp(encoder_codec, "opus") != 0) { config_set_string(activeConfiguration, "AdvOut", "AudioEncoder", "ffmpeg_opus"); + } } return true; @@ -94,12 +98,14 @@ bool OBSBasic::InitService() { ProfileScope("OBSBasic::InitService"); - if (LoadService()) + if (LoadService()) { return true; + } service = obs_service_create("rtmp_common", "default_service", nullptr, nullptr); - if (!service) + if (!service) { return false; + } obs_service_release(service); return true; diff --git a/frontend/widgets/OBSBasic_Streaming.cpp b/frontend/widgets/OBSBasic_Streaming.cpp index 2800acbb55f77b..4111677e6d6d45 100644 --- a/frontend/widgets/OBSBasic_Streaming.cpp +++ b/frontend/widgets/OBSBasic_Streaming.cpp @@ -47,10 +47,12 @@ void OBSBasic::DisplayStreamStartError() void OBSBasic::StartStreaming() { - if (outputHandler->StreamingActive()) + if (outputHandler->StreamingActive()) { return; - if (disableOutputsRef) + } + if (disableOutputsRef) { return; + } if (auth && auth->broadcastFlow()) { if (!broadcastActive && !broadcastReady) { @@ -64,8 +66,9 @@ void OBSBasic::StartStreaming() no_broadcast.setWindowTitle(QTStr("Output.NoBroadcast.Title")); no_broadcast.exec(); - if (no_broadcast.clickedButton() == SetupBroadcast) + if (no_broadcast.clickedButton() == SetupBroadcast) { QMetaObject::invokeMethod(this, "SetupBroadcast"); + } return; } } @@ -89,8 +92,9 @@ void OBSBasic::StartStreaming() emit StreamingStarting(autoStartBroadcast); - if (sysTrayStream) + if (sysTrayStream) { sysTrayStream->setText("Basic.Main.Connecting"); + } if (!outputHandler->StartStreaming(service)) { DisplayStreamStartError(); @@ -104,13 +108,15 @@ void OBSBasic::StartStreaming() bool recordWhenStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); - if (recordWhenStreaming) + if (recordWhenStreaming) { StartRecording(); + } bool replayBufferWhileStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); - if (replayBufferWhileStreaming) + if (replayBufferWhileStreaming) { StartReplayBuffer(); + } #ifdef YOUTUBE_ENABLED if (!autoStartBroadcast) @@ -125,8 +131,9 @@ void OBSBasic::StopStreaming() { SaveProject(); - if (outputHandler->StreamingActive()) + if (outputHandler->StreamingActive()) { outputHandler->StopStreaming(streamingStopping); + } // special case: force reset broadcast state if // no autostart and no autostop selected @@ -149,23 +156,26 @@ void OBSBasic::StopStreaming() bool recordWhenStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); bool keepRecordingWhenStreamStops = config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops"); - if (recordWhenStreaming && !keepRecordingWhenStreamStops) + if (recordWhenStreaming && !keepRecordingWhenStreamStops) { StopRecording(); + } bool replayBufferWhileStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); bool keepReplayBufferStreamStops = config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops"); - if (replayBufferWhileStreaming && !keepReplayBufferStreamStops) + if (replayBufferWhileStreaming && !keepReplayBufferStreamStops) { StopReplayBuffer(); + } } void OBSBasic::ForceStopStreaming() { SaveProject(); - if (outputHandler->StreamingActive()) + if (outputHandler->StreamingActive()) { outputHandler->StopStreaming(true); + } // special case: force reset broadcast state if // no autostart and no autostop selected @@ -188,15 +198,17 @@ void OBSBasic::ForceStopStreaming() bool recordWhenStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "RecordWhenStreaming"); bool keepRecordingWhenStreamStops = config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepRecordingWhenStreamStops"); - if (recordWhenStreaming && !keepRecordingWhenStreamStops) + if (recordWhenStreaming && !keepRecordingWhenStreamStops) { StopRecording(); + } bool replayBufferWhileStreaming = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ReplayBufferWhileStreaming"); bool keepReplayBufferStreamStops = config_get_bool(App()->GetUserConfig(), "BasicWindow", "KeepReplayBufferStreamStops"); - if (replayBufferWhileStreaming && !keepReplayBufferStreamStops) + if (replayBufferWhileStreaming && !keepReplayBufferStreamStops) { StopReplayBuffer(); + } } void OBSBasic::StreamDelayStarting(int sec) @@ -257,8 +269,9 @@ void OBSBasic::StreamingStart() OnActivate(); #ifdef YOUTUBE_ENABLED - if (YouTubeAppDock::IsYTServiceSelected()) + if (YouTubeAppDock::IsYTServiceSelected()) { youtubeAppDock->IngestionStarted(); + } #endif blog(LOG_INFO, STREAMING_START); @@ -268,8 +281,9 @@ void OBSBasic::StreamStopping() { emit StreamingStopping(); - if (sysTrayStream) + if (sysTrayStream) { sysTrayStream->setText(QTStr("Basic.Main.StoppingStreaming")); + } streamingStopping = true; OnEvent(OBS_FRONTEND_EVENT_STREAMING_STOPPING); @@ -325,10 +339,11 @@ void OBSBasic::StreamingStop(int code, QString last_error) errorDescription = Str("Output.ConnectFail.Disconnected"); } - if (use_last_error && !last_error.isEmpty()) + if (use_last_error && !last_error.isEmpty()) { dstr_printf(errorMessage, "%s\n\n%s", errorDescription, QT_TO_UTF8(last_error)); - else + } else { dstr_copy(errorMessage, errorDescription); + } ui->statusbar->StreamStopped(); @@ -345,8 +360,9 @@ void OBSBasic::StreamingStop(int code, QString last_error) OnDeactivate(); #ifdef YOUTUBE_ENABLED - if (YouTubeAppDock::IsYTServiceSelected()) + if (YouTubeAppDock::IsYTServiceSelected()) { youtubeAppDock->IngestionStopped(); + } #endif blog(LOG_INFO, STREAMING_STOP); @@ -364,10 +380,12 @@ void OBSBasic::StreamingStop(int code, QString last_error) } // Reset broadcast button state/text - if (!broadcastActive) + if (!broadcastActive) { SetBroadcastFlowEnabled(auth && auth->broadcastFlow()); - if (should_reconnect) + } + if (should_reconnect) { QMetaObject::invokeMethod(this, "StartStreaming", Qt::QueuedConnection); + } } void OBSBasic::StreamActionTriggered() @@ -381,8 +399,9 @@ void OBSBasic::StreamActionTriggered() this, QTStr("ConfirmStop.Title"), QTStr("YouTube.Actions.AutoStopStreamingWarning"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return; + } confirm = false; } @@ -392,14 +411,16 @@ void OBSBasic::StreamActionTriggered() OBSMessageBox::question(this, QTStr("ConfirmStop.Title"), QTStr("ConfirmStop.Text"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return; + } } StopStreaming(); } else { - if (!UIValidation::NoSourcesConfirmation(this)) + if (!UIValidation::NoSourcesConfirmation(this)) { return; + } Auth *auth = GetAuth(); @@ -423,23 +444,26 @@ void OBSBasic::StreamActionTriggered() 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")); - if (button == QMessageBox::No) + 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); - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return; + } } StartStreaming(); @@ -448,7 +472,8 @@ void OBSBasic::StreamActionTriggered() bool OBSBasic::StreamingActive() { - if (!outputHandler) + if (!outputHandler) { return false; + } return outputHandler->StreamingActive(); } diff --git a/frontend/widgets/OBSBasic_StudioMode.cpp b/frontend/widgets/OBSBasic_StudioMode.cpp index b65978a01a347e..e37c4a772c1f0f 100644 --- a/frontend/widgets/OBSBasic_StudioMode.cpp +++ b/frontend/widgets/OBSBasic_StudioMode.cpp @@ -38,8 +38,9 @@ void OBSBasic::CreateProgramDisplay() auto displayResize = [this]() { struct obs_video_info ovi; - if (obs_get_video_info(&ovi)) + if (obs_get_video_info(&ovi)) { ResizeProgram(ovi.base_width, ovi.base_height); + } }; connect(program.data(), &OBSQTDisplay::DisplayResized, this, displayResize); @@ -48,8 +49,9 @@ void OBSBasic::CreateProgramDisplay() obs_display_add_draw_callback(window->GetDisplay(), OBSBasic::RenderProgram, this); struct obs_video_info ovi; - if (obs_get_video_info(&ovi)) + if (obs_get_video_info(&ovi)) { ResizeProgram(ovi.base_width, ovi.base_height); + } }; connect(program.data(), &OBSQTDisplay::DisplayCreated, this, addDisplay); @@ -121,8 +123,9 @@ void OBSBasic::CreateProgramOptions() editPropertiesMode = !editPropertiesMode; OBSSource actualScene = OBSGetStrongRef(programScene); - if (actualScene) + if (actualScene) { TransitionToScene(actualScene, true); + } }; auto toggleSwapScenesMode = [this]() { @@ -133,8 +136,9 @@ void OBSBasic::CreateProgramOptions() sceneDuplicationMode = !sceneDuplicationMode; OBSSource actualScene = OBSGetStrongRef(programScene); - if (actualScene) + if (actualScene) { TransitionToScene(actualScene, true); + } }; auto showToolTip = [&]() { @@ -260,8 +264,9 @@ void OBSBasic::SetPreviewProgramMode(bool enabled) if (lastScene) { OBSSource actualLastScene = OBSGetStrongRef(lastScene); - if (actualLastScene) + if (actualLastScene) { obs_source_dec_showing(actualLastScene); + } lastScene = nullptr; } @@ -342,22 +347,26 @@ void OBSBasic::UpdatePreviewProgramIndicators() ui->previewLabel->setVisible(labels); - if (programLabel) + if (programLabel) { programLabel->setVisible(labels); + } - if (!labels) + if (!labels) { return; + } 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()))); - if (ui->previewLabel->text() != preview) + if (ui->previewLabel->text() != preview) { ui->previewLabel->setText(preview); + } - if (programLabel && programLabel->text() != program) + if (programLabel && programLabel->text() != program) { programLabel->setText(program); + } } OBSSource OBSBasic::GetProgramSource() diff --git a/frontend/widgets/OBSBasic_SysTray.cpp b/frontend/widgets/OBSBasic_SysTray.cpp index d1cb58ed88f9d7..d2a2c3abd18c8d 100644 --- a/frontend/widgets/OBSBasic_SysTray.cpp +++ b/frontend/widgets/OBSBasic_SysTray.cpp @@ -65,13 +65,15 @@ void OBSBasic::SystemTrayInit() trayIcon->setContextMenu(trayMenu); trayIcon->show(); - if (outputHandler && !outputHandler->replayBuffer) + if (outputHandler && !outputHandler->replayBuffer) { sysTrayReplayBuffer->setEnabled(false); + } sysTrayVirtualCam->setEnabled(vcamEnabled); - if (Active()) + if (Active()) { OnActivate(true); + } connect(trayIcon.data(), &QSystemTrayIcon::activated, this, &OBSBasic::IconActivated); connect(showHide, &QAction::triggered, this, &OBSBasic::ToggleShowHide); @@ -106,16 +108,19 @@ void OBSBasic::SysTrayNotify(const QString &text, QSystemTrayIcon::MessageIcon n void OBSBasic::SystemTray(bool firstStarted) { - if (!QSystemTrayIcon::isSystemTrayAvailable()) + if (!QSystemTrayIcon::isSystemTrayAvailable()) { return; - if (!trayIcon && !firstStarted) + } + if (!trayIcon && !firstStarted) { return; + } bool sysTrayWhenStarted = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayWhenStarted"); bool sysTrayEnabled = config_get_bool(App()->GetUserConfig(), "BasicWindow", "SysTrayEnabled"); - if (firstStarted) + if (firstStarted) { SystemTrayInit(); + } if (!sysTrayEnabled) { trayIcon->hide(); @@ -130,10 +135,11 @@ void OBSBasic::SystemTray(bool firstStarted) } } - if (isVisible()) + if (isVisible()) { showHide->setText(QTStr("Basic.SystemTray.Hide")); - else + } else { showHide->setText(QTStr("Basic.SystemTray.Show")); + } } bool OBSBasic::sysTrayMinimizeToTray() diff --git a/frontend/widgets/OBSBasic_Transitions.cpp b/frontend/widgets/OBSBasic_Transitions.cpp index 235f4e7b8c52ad..99dd5e9a2503b9 100644 --- a/frontend/widgets/OBSBasic_Transitions.cpp +++ b/frontend/widgets/OBSBasic_Transitions.cpp @@ -37,13 +37,15 @@ static inline QString MakeQuickTransitionText(QuickTransition *qt) { QString name; - if (!qt->fadeToBlack) + if (!qt->fadeToBlack) { name = QT_UTF8(obs_source_get_name(qt->source)); - else + } else { name = QTStr("FadeToBlack"); + } - if (!obs_transition_fixed(qt->source)) + if (!obs_transition_fixed(qt->source)) { name += QString(" (%1ms)").arg(QString::number(qt->duration)); + } return name; } @@ -63,10 +65,11 @@ void OBSBasic::InitDefaultTransitions() InitTransition(tr); defaultTransitions.emplace_back(tr); - if (strcmp(id, "fade_transition") == 0) + if (strcmp(id, "fade_transition") == 0) { fadeTransition = tr; - else if (strcmp(id, "cut_transition") == 0) + } else if (strcmp(id, "cut_transition") == 0) { cutTransition = tr; + } } } @@ -95,8 +98,9 @@ void OBSBasic::AddQuickTransitionHotkey(QuickTransition *qt) int id = (int)(uintptr_t)data; OBSBasic *main = OBSBasic::Get(); - if (pressed) + if (pressed) { QMetaObject::invokeMethod(main, "TriggerQuickTransition", Qt::QueuedConnection, Q_ARG(int, id)); + } }; qt->hotkey = obs_hotkey_register_frontend(hotkeyId->array, QT_TO_UTF8(hotkeyName), quickTransition, @@ -181,8 +185,9 @@ void OBSBasic::LoadQuickTransitions(obs_data_array_t *array) if (source) { quickTransitions.emplace_back(source, duration, id, toBlack); - if (quickTransitionIdCounter <= id) + if (quickTransitionIdCounter <= id) { quickTransitionIdCounter = id + 1; + } int idx = (int)quickTransitions.size() - 1; AddQuickTransitionHotkey(&quickTransitions[idx]); @@ -219,8 +224,9 @@ obs_source_t *OBSBasic::FindTransition(const char *name) if (nameToUuid != transitionNameToUuids.end()) { auto transition = transitions.find(nameToUuid->second); - if (transition == transitions.end()) + if (transition == transitions.end()) { return nullptr; + } return transition->second; } @@ -243,8 +249,9 @@ void OBSBasic::TransitionStopped() { if (swapScenesMode) { OBSSource scene = OBSGetStrongRef(swapScene); - if (scene) + if (scene) { SetCurrentScene(scene); + } } EnableTransitionWidgets(true); @@ -282,22 +289,26 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, bool quickTransit { obs_scene_t *scene = obs_scene_from_source(source); bool usingPreviewProgram = IsPreviewProgramMode(); - if (!scene) + if (!scene) { return; + } if (usingPreviewProgram) { - if (!tBarActive) + if (!tBarActive) { lastProgramScene = programScene; + } programScene = OBSGetWeakRef(source); if (!force && !black) { OBSSource lastScene = OBSGetStrongRef(lastProgramScene); - if (!sceneDuplicationMode && lastScene == source) + if (!sceneDuplicationMode && lastScene == source) { return; + } - if (swapScenesMode && lastScene && lastScene != GetCurrentSceneSource()) + if (swapScenesMode && lastScene && lastScene != GetCurrentSceneSource()) { swapScene = lastProgramScene; + } } } @@ -310,8 +321,9 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, bool quickTransit OBSSourceAutoRelease transition = obs_get_output_source(0); if (!transition) { - if (usingPreviewProgram && sceneDuplicationMode) + if (usingPreviewProgram && sceneDuplicationMode) { obs_scene_release(scene); + } return; } @@ -319,8 +331,9 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, bool quickTransit bool stillTransitioning = t < 1.0f && t > 0.0f; // If actively transitioning, block new transitions from starting - if (usingPreviewProgram && stillTransitioning) + if (usingPreviewProgram && stillTransitioning) { goto cleanup; + } if (usingPreviewProgram) { if (!black && !manual) { @@ -368,20 +381,23 @@ void OBSBasic::TransitionToScene(OBSSource source, bool force, bool quickTransit prevFTBSource = nullptr; } - if (quickTransition) + if (quickTransition) { duration = quickDuration; + } enum obs_transition_mode mode = manual ? OBS_TRANSITION_MODE_MANUAL : OBS_TRANSITION_MODE_AUTO; bool success = obs_transition_start(transition, mode, duration, source); - if (!success) + if (!success) { TransitionFullyStopped(); + } } cleanup: - if (usingPreviewProgram && sceneDuplicationMode) + if (usingPreviewProgram && sceneDuplicationMode) { obs_scene_release(scene); + } } static inline void SetComboTransition(QComboBox *combo, obs_source_t *tr) @@ -405,8 +421,9 @@ void OBSBasic::SetTransition(OBSSource transition) if (oldTransition && transition) { std::string uuid = obs_source_get_uuid(transition); obs_transition_swap_begin(transition, oldTransition); - if (currentTransitionUuid != uuid) + if (currentTransitionUuid != uuid) { UpdateCurrentTransition(uuid, false); + } obs_set_output_source(0, transition); obs_transition_swap_end(transition, oldTransition); } else { @@ -428,8 +445,9 @@ OBSSource OBSBasic::GetCurrentTransition() { auto transition = transitions.find(currentTransitionUuid); - if (transition == transitions.end()) + if (transition == transitions.end()) { return nullptr; + } return transition->second; } @@ -507,8 +525,9 @@ void OBSBasic::on_transitionAdd_clicked() } } - if (foundConfigurableTransitions) + if (foundConfigurableTransitions) { menu.exec(QCursor::pos()); + } } void OBSBasic::on_transitionRemove_clicked() @@ -517,27 +536,31 @@ void OBSBasic::on_transitionRemove_clicked() OBSSource tr; const char *name; - if (transitionIterator == transitions.end()) + if (transitionIterator == transitions.end()) { return; + } tr = transitionIterator->second; - if (!tr || !obs_source_configurable(tr) || !QueryRemoveSource(tr)) + if (!tr || !obs_source_configurable(tr) || !QueryRemoveSource(tr)) { return; + } for (size_t i = quickTransitions.size(); i > 0; i--) { QuickTransition &qt = quickTransitions[i - 1]; if (qt.source == tr) { - if (qt.button) + if (qt.button) { qt.button->deleteLater(); + } RemoveQuickTransitionHotkey(&qt); quickTransitions.erase(quickTransitions.begin() + i - 1); } } name = obs_source_get_name(tr); - if (name) + if (name) { transitionNameToUuids.erase(std::string(name)); + } transitionUuids.erase(std::find(transitionUuids.begin(), transitionUuids.end(), currentTransitionUuid)); transitions.erase(currentTransitionUuid); @@ -586,8 +609,9 @@ void OBSBasic::RenameTransition(OBSSource transition) obs_source_set_name(transition, name.c_str()); - if (transitionNameToUuids.find(oldName) == transitionNameToUuids.end()) + if (transitionNameToUuids.find(oldName) == transitionNameToUuids.end()) { return; + } transitionNameToUuids.erase(oldName); transitionNameToUuids.insert({name, uuid}); @@ -604,8 +628,9 @@ void OBSBasic::on_transitionProps_clicked() { OBSSource source = GetCurrentTransition(); - if (!obs_source_configurable(source)) + if (!obs_source_configurable(source)) { return; + } auto properties = [&]() { CreatePropertiesWindow(source); @@ -627,8 +652,9 @@ void OBSBasic::on_transitionProps_clicked() QuickTransition *OBSBasic::GetQuickTransition(int id) { for (QuickTransition &qt : quickTransitions) { - if (qt.id == id) + if (qt.id == id) { return &qt; + } } return nullptr; @@ -639,8 +665,9 @@ int OBSBasic::GetQuickTransitionIdx(int id) for (int idx = 0; idx < (int)quickTransitions.size(); idx++) { QuickTransition &qt = quickTransitions[idx]; - if (qt.id == id) + if (qt.id == id) { return idx; + } } return -1; @@ -659,10 +686,12 @@ void OBSBasic::SetCurrentScene(OBSSource scene, bool force) } else { OBSSource actualLastScene = OBSGetStrongRef(lastScene); if (actualLastScene != scene) { - if (scene) + if (scene) { obs_source_inc_showing(scene); - if (actualLastScene) + } + if (actualLastScene) { obs_source_dec_showing(actualLastScene); + } lastScene = OBSGetWeakRef(scene); } } @@ -679,8 +708,9 @@ void OBSBasic::SetCurrentScene(OBSSource scene, bool force) ui->scenes->setCurrentItem(item); ui->scenes->blockSignals(false); - if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput) + if (vcamEnabled && vcamConfig.type == VCamOutputType::PreviewOutput) { outputHandler->UpdateVirtualCamOutputSource(); + } OnEvent(OBS_FRONTEND_EVENT_PREVIEW_SCENE_CHANGED); break; @@ -700,8 +730,9 @@ void OBSBasic::SetCurrentScene(OBSSource scene, bool force) void OBSBasic::TransitionClicked() { - if (previewProgramMode) + if (previewProgramMode) { TransitionToScene(GetCurrentScene()); + } } #define T_BAR_PRECISION 1024 @@ -742,13 +773,15 @@ void OBSBasic::TBarReleased() static bool ValidTBarTransition(OBSSource transition) { - if (!transition) + if (!transition) { return false; + } QString id = QT_UTF8(obs_source_get_id(transition)); - if (id == "cut_transition" || id == "obs_stinger_transition") + if (id == "cut_transition" || id == "obs_stinger_transition") { return false; + } return true; } @@ -764,8 +797,9 @@ void OBSBasic::TBarChanged(int value) if (!ValidTBarTransition(tBarTr)) { tBarTr = GetCurrentTransition(); - if (!ValidTBarTransition(tBarTr)) + if (!ValidTBarTransition(tBarTr)) { tBarTr = FindTransition(obs_source_get_display_name("fade_transition")); + } OverrideTransition(tBarTr); overridingTransition = true; @@ -825,8 +859,9 @@ QMenu *OBSBasic::CreatePerSceneTransitionMenu() return; } - if (transitionIter == transitions.end()) + if (transitionIter == transitions.end()) { return; + } transition = transitionIter->second; @@ -851,16 +886,18 @@ QMenu *OBSBasic::CreatePerSceneTransitionMenu() if (!uuid.empty()) { auto transition = transitions.find(uuid); - if (transition == transitions.end()) + if (transition == transitions.end()) { return; + } name = obs_source_get_name(transition->second); } bool match = (name && strcmp(name, curTransition) == 0); - if (!name || !*name) + if (!name || !*name) { name = Str("None"); + } action = menu->addAction(QT_UTF8(name)); action->setProperty("transition_uuid", QString::fromStdString(uuid)); @@ -871,8 +908,9 @@ QMenu *OBSBasic::CreatePerSceneTransitionMenu() }; addAction(); - for (const auto &[uuid, transition] : transitions) + for (const auto &[uuid, transition] : transitions) { addAction(uuid); + } QWidgetAction *durationAction = new QWidgetAction(menu); durationAction->setDefaultWidget(duration); @@ -887,8 +925,9 @@ void OBSBasic::ShowTransitionProperties() OBSSceneItem item = GetCurrentSceneItem(); OBSSource source = obs_sceneitem_get_transition(item, true); - if (source) + if (source) { CreatePropertiesWindow(source); + } } void OBSBasic::HideTransitionProperties() @@ -896,8 +935,9 @@ void OBSBasic::HideTransitionProperties() OBSSceneItem item = GetCurrentSceneItem(); OBSSource source = obs_sceneitem_get_transition(item, false); - if (source) + if (source) { CreatePropertiesWindow(source); + } } void OBSBasic::PasteShowHideTransition(obs_sceneitem_t *item, bool show, obs_source_t *tr, int duration) @@ -925,8 +965,9 @@ void OBSBasic::PasteShowHideTransition(obs_sceneitem_t *item, bool show, obs_sou 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) + if (undo_data.compare(redo_data) == 0) { return; + } QString text = show ? QTStr("Undo.ShowTransition") : QTStr("Undo.HideTransition"); const char *name = obs_source_get_name(obs_sceneitem_get_source(item)); @@ -944,8 +985,9 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) const char *curId = curTransition ? obs_source_get_id(curTransition) : nullptr; int curDuration = (int)obs_sceneitem_get_transition_duration(si, visible); - if (curDuration <= 0) + if (curDuration <= 0) { curDuration = obs_frontend_get_transition_duration(); + } QSpinBox *duration = new QSpinBox(menu); duration->setMinimum(50); @@ -992,16 +1034,18 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) obs_sceneitem_set_transition_duration(sceneItem, visible, duration); } } - if (obs_source_configurable(tr)) + if (obs_source_configurable(tr)) { CreatePropertiesWindow(tr); + } } 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) + 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); + } }; auto setDuration = [visible](int duration) { OBSBasic *main = OBSBasic::Get(); @@ -1056,13 +1100,15 @@ QMenu *OBSBasic::CreateVisibilityTransitionMenu(bool visible) OBSBasic *main = OBSBasic::Get(); OBSSource tr = OBSGetStrongRef(main->copySourceTransition); int trDuration = main->copySourceTransitionDuration; - if (!tr) + if (!tr) { return; + } for (auto &selectedSource : GetAllSelectedSourceItems()) { OBSSceneItem item = main->ui->sources->Get(selectedSource.row()); - if (!item) + if (!item) { continue; + } PasteShowHideTransition(item, show, tr, trDuration); } @@ -1088,8 +1134,9 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) } QSpinBox *duration = new QSpinBox(menu); - if (qt) + if (qt) { duration->setProperty("id", qt->id); + } duration->setMinimum(50); duration->setSuffix(" ms"); duration->setMaximum(20000); @@ -1097,7 +1144,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); } @@ -1113,8 +1160,9 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) } for (const auto &[uuid, transition] : transitions) { - if (!transition) + if (!transition) { continue; + } action = menu->addAction(obs_source_get_name(transition)); action->setProperty("transition_uuid", QString::fromStdString(uuid)); @@ -1139,8 +1187,9 @@ QMenu *OBSBasic::CreateTransitionMenu(QWidget *parent, QuickTransition *qt) void OBSBasic::AddQuickTransitionId(int id) { QuickTransition *qt = GetQuickTransition(id); - if (!qt) + if (!qt) { return; + } /* --------------------------------- */ @@ -1164,12 +1213,14 @@ void OBSBasic::AddQuickTransitionId(int id) int idx = 3; for (;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); - if (!item) + if (!item) { break; + } QWidget *widget = item->widget(); - if (!widget || !widget->property("id").isValid()) + if (!widget || !widget->property("id").isValid()) { break; + } } programLayout->insertWidget(idx, button); @@ -1183,13 +1234,15 @@ void OBSBasic::AddQuickTransition() auto transitionIter = transitions.find(transitionUuid); OBSSource transition; - if (!fadeToBlack && (transitionIter == transitions.end())) + if (!fadeToBlack && (transitionIter == transitions.end())) { return; + } transition = fadeToBlack ? OBSSource(fadeTransition) : transitionIter->second; - if (!transition) + if (!transition) { return; + } int id = quickTransitionIdCounter++; @@ -1202,23 +1255,27 @@ void OBSBasic::AddQuickTransition() void OBSBasic::ClearQuickTransitions() { - for (QuickTransition &qt : quickTransitions) + for (QuickTransition &qt : quickTransitions) { RemoveQuickTransitionHotkey(&qt); + } quickTransitions.clear(); - if (!programOptions) + if (!programOptions) { return; + } QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); for (int idx = 0;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); - if (!item) + if (!item) { break; + } QWidget *widget = item->widget(); - if (!widget) + if (!widget) { continue; + } int id = widget->property("id").toInt(); if (id != 0) { @@ -1245,8 +1302,9 @@ void OBSBasic::QuickTransitionChange() auto transitionIter = transitions.find(transitionUuid); OBSSource tr; - if (!fadeToBlack && (transitionIter == transitions.end())) + if (!fadeToBlack && (transitionIter == transitions.end())) { return; + } tr = fadeToBlack ? OBSSource(fadeTransition) : transitionIter->second; @@ -1273,13 +1331,15 @@ void OBSBasic::QuickTransitionRemoveClicked() { int id = sender()->property("id").toInt(); int idx = GetQuickTransitionIdx(id); - if (idx == -1) + if (idx == -1) { return; + } QuickTransition &qt = quickTransitions[idx]; - if (qt.button) + if (qt.button) { qt.button->deleteLater(); + } RemoveQuickTransitionHotkey(&qt); quickTransitions.erase(quickTransitions.begin() + idx); @@ -1287,19 +1347,22 @@ void OBSBasic::QuickTransitionRemoveClicked() void OBSBasic::ClearQuickTransitionWidgets() { - if (!IsPreviewProgramMode()) + if (!IsPreviewProgramMode()) { return; + } QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); for (int idx = 0;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); - if (!item) + if (!item) { break; + } QWidget *widget = item->widget(); - if (!widget) + if (!widget) { continue; + } int id = widget->property("id").toInt(); if (id != 0) { @@ -1311,11 +1374,13 @@ void OBSBasic::ClearQuickTransitionWidgets() void OBSBasic::RefreshQuickTransitions() { - if (!IsPreviewProgramMode()) + if (!IsPreviewProgramMode()) { return; + } - for (QuickTransition &qt : quickTransitions) + for (QuickTransition &qt : quickTransitions) { AddQuickTransitionId(qt.id); + } } void OBSBasic::EnableTransitionWidgets(bool enable) @@ -1329,25 +1394,29 @@ void OBSBasic::EnableTransitionWidgets(bool enable) ui->transitionProps->setEnabled(configurable); } - if (!IsPreviewProgramMode()) + if (!IsPreviewProgramMode()) { return; + } QVBoxLayout *programLayout = reinterpret_cast(programOptions->layout()); for (int idx = 0;; idx++) { QLayoutItem *item = programLayout->itemAt(idx); - if (!item) + if (!item) { break; + } QPushButton *button = qobject_cast(item->widget()); - if (!button) + if (!button) { continue; + } button->setEnabled(enable); } - if (transitionButton) + if (transitionButton) { transitionButton->setEnabled(enable); + } } obs_data_array_t *OBSBasic::SaveTransitions() @@ -1355,8 +1424,9 @@ obs_data_array_t *OBSBasic::SaveTransitions() obs_data_array_t *transitionsData = obs_data_array_create(); for (const auto &[uuid, transition] : transitions) { - if (!transition || !obs_source_configurable(transition.Get())) + if (!transition || !obs_source_configurable(transition.Get())) { continue; + } OBSDataAutoRelease sourceData = obs_data_create(); OBSDataAutoRelease settings = obs_source_get_settings(transition.Get()); @@ -1397,8 +1467,9 @@ void OBSBasic::LoadTransitions(obs_data_array_t *transitionsData, obs_load_sourc emit TransitionAdded(QT_UTF8(name), QString::fromStdString(uuid)); - if (cb) + if (cb) { cb(private_data, source); + } } else if (safe_mode || disable_3p_plugins) { safeModeTransitions.push_back(std::move(item)); } @@ -1409,8 +1480,9 @@ void OBSBasic::LoadTransitions(obs_data_array_t *transitionsData, obs_load_sourc OBSSource OBSBasic::GetOverrideTransition(OBSSource source) { - if (!source) + if (!source) { return nullptr; + } OBSDataAutoRelease data = obs_source_get_private_settings(source); @@ -1418,16 +1490,18 @@ OBSSource OBSBasic::GetOverrideTransition(OBSSource source) OBSSource trOverride = nullptr; - if (trOverrideName && *trOverrideName) + if (trOverrideName && *trOverrideName) { trOverride = FindTransition(trOverrideName); + } return trOverride; } int OBSBasic::GetOverrideTransitionDuration(OBSSource source) { - if (!source) + if (!source) { return 300; + } OBSDataAutoRelease data = obs_source_get_private_settings(source); obs_data_set_default_int(data, "transition_duration", 300); @@ -1444,13 +1518,15 @@ void OBSBasic::UpdateCurrentTransition(const std::string &uuid, bool setTransiti { auto transitionIter = transitions.find(uuid); - if (currentTransitionUuid == uuid || transitionIter == transitions.end()) + if (currentTransitionUuid == uuid || transitionIter == transitions.end()) { return; + } currentTransitionUuid = uuid; - if (setTransition) + if (setTransition) { SetTransition(transitionIter->second); + } emit CurrentTransitionChanged(QString::fromStdString(uuid)); } @@ -1459,8 +1535,9 @@ void OBSBasic::SetCurrentTransition(const QString &uuid) { auto transitionIter = transitions.find(uuid.toStdString()); - if (currentTransitionUuid == uuid.toStdString() || transitionIter == transitions.end()) + if (currentTransitionUuid == uuid.toStdString() || transitionIter == transitions.end()) { return; + } currentTransitionUuid = uuid.toStdString(); SetTransition(transitionIter->second); @@ -1473,8 +1550,9 @@ void OBSBasic::SetTransitionDuration(int duration) duration = std::max(duration, 50); duration = std::min(duration, 20000); - if (duration == transitionDuration) + if (duration == transitionDuration) { return; + } transitionDuration = duration; diff --git a/frontend/widgets/OBSBasic_Updater.cpp b/frontend/widgets/OBSBasic_Updater.cpp index 7b31f22becec37..83bc54d11f5b92 100644 --- a/frontend/widgets/OBSBasic_Updater.cpp +++ b/frontend/widgets/OBSBasic_Updater.cpp @@ -84,14 +84,17 @@ void OBSBasic::ReceivedIntroJson(const QString &text) if (item.os) { WhatsNewPlatforms platforms = *item.os; #ifdef _WIN32 - if (!platforms.windows) + if (!platforms.windows) { continue; + } #elif defined(__APPLE__) - if (!platforms.macos) + if (!platforms.macos) { continue; + } #else - if (!platforms.linux) + if (!platforms.linux) { continue; + } #endif } @@ -170,10 +173,12 @@ void OBSBasic::ShowWhatsNew(const QString &url) void OBSBasic::TimedCheckForUpdates() { - if (App()->IsUpdaterDisabled()) + if (App()->IsUpdaterDisabled()) { return; - if (!config_get_bool(App()->GetAppConfig(), "General", "EnableAutoUpdates")) + } + if (!config_get_bool(App()->GetAppConfig(), "General", "EnableAutoUpdates")) { return; + } #if defined(ENABLE_SPARKLE_UPDATER) CheckForUpdates(false); @@ -189,8 +194,9 @@ void OBSBasic::TimedCheckForUpdates() long long t = (long long)time(nullptr); long long secs = t - lastUpdate; - if (secs > UPDATE_CHECK_INTERVAL) + if (secs > UPDATE_CHECK_INTERVAL) { CheckForUpdates(false); + } #endif } @@ -200,15 +206,17 @@ void OBSBasic::CheckForUpdates(bool manualUpdate) ui->actionCheckForUpdates->setEnabled(false); ui->actionRepair->setEnabled(false); - if (updateCheckThread && updateCheckThread->isRunning()) + if (updateCheckThread && updateCheckThread->isRunning()) { return; + } updateCheckThread.reset(new AutoUpdateThread(manualUpdate)); updateCheckThread->start(); #elif defined(ENABLE_SPARKLE_UPDATER) ui->actionCheckForUpdates->setEnabled(false); - if (updateCheckThread && updateCheckThread->isRunning()) + if (updateCheckThread && updateCheckThread->isRunning()) { return; + } MacUpdateThread *mut = new MacUpdateThread(manualUpdate); connect(mut, &MacUpdateThread::Result, this, &OBSBasic::MacBranchesFetched, Qt::QueuedConnection); diff --git a/frontend/widgets/OBSBasic_VirtualCam.cpp b/frontend/widgets/OBSBasic_VirtualCam.cpp index 3ccb535e66d2a7..ace791ed2c7832 100644 --- a/frontend/widgets/OBSBasic_VirtualCam.cpp +++ b/frontend/widgets/OBSBasic_VirtualCam.cpp @@ -27,12 +27,15 @@ void OBSBasic::StartVirtualCam() { - if (!outputHandler || !outputHandler->virtualCam) + if (!outputHandler || !outputHandler->virtualCam) { return; - if (outputHandler->VirtualCamActive()) + } + if (outputHandler->VirtualCamActive()) { return; - if (disableOutputsRef) + } + if (disableOutputsRef) { return; + } SaveProject(); @@ -41,26 +44,30 @@ void OBSBasic::StartVirtualCam() void OBSBasic::StopVirtualCam() { - if (!outputHandler || !outputHandler->virtualCam) + if (!outputHandler || !outputHandler->virtualCam) { return; + } SaveProject(); - if (outputHandler->VirtualCamActive()) + if (outputHandler->VirtualCamActive()) { outputHandler->StopVirtualCam(); + } OnDeactivate(); } void OBSBasic::OnVirtualCamStart() { - if (!outputHandler || !outputHandler->virtualCam) + if (!outputHandler || !outputHandler->virtualCam) { return; + } emit VirtualCamStarted(); - if (sysTrayVirtualCam) + if (sysTrayVirtualCam) { sysTrayVirtualCam->setText(QTStr("Basic.Main.StopVirtualCam")); + } OnEvent(OBS_FRONTEND_EVENT_VIRTUALCAM_STARTED); @@ -71,13 +78,15 @@ void OBSBasic::OnVirtualCamStart() void OBSBasic::OnVirtualCamStop(int) { - if (!outputHandler || !outputHandler->virtualCam) + if (!outputHandler || !outputHandler->virtualCam) { return; + } emit VirtualCamStopped(); - if (sysTrayVirtualCam) + if (sysTrayVirtualCam) { sysTrayVirtualCam->setText(QTStr("Basic.Main.StartVirtualCam")); + } OnEvent(OBS_FRONTEND_EVENT_VIRTUALCAM_STOPPED); @@ -85,8 +94,9 @@ void OBSBasic::OnVirtualCamStop(int) OnDeactivate(); - if (!restartingVCam) + if (!restartingVCam) { return; + } /* Restarting needs to be delayed to make sure that the virtual camera * implementation is stopped and avoid race condition. */ @@ -98,8 +108,9 @@ void OBSBasic::VirtualCamActionTriggered() if (outputHandler->VirtualCamActive()) { StopVirtualCam(); } else { - if (!UIValidation::NoSourcesConfirmation(this)) + if (!UIValidation::NoSourcesConfirmation(this)) { return; + } StartVirtualCam(); } @@ -156,8 +167,9 @@ void OBSBasic::RestartVirtualCam(const VCamConfig &config) void OBSBasic::RestartingVirtualCam() { - if (!restartingVCam) + if (!restartingVCam) { return; + } outputHandler->UpdateVirtualCamOutputSource(); StartVirtualCam(); @@ -166,7 +178,8 @@ void OBSBasic::RestartingVirtualCam() bool OBSBasic::VirtualCamActive() { - if (!outputHandler) + if (!outputHandler) { return false; + } return outputHandler->VirtualCamActive(); } diff --git a/frontend/widgets/OBSBasic_YouTube.cpp b/frontend/widgets/OBSBasic_YouTube.cpp index bd708bb3f87401..231940a7dfcd3e 100644 --- a/frontend/widgets/OBSBasic_YouTube.cpp +++ b/frontend/widgets/OBSBasic_YouTube.cpp @@ -55,8 +55,9 @@ void OBSBasic::YouTubeActionDialogOk(const QString &broadcast_id, const QString emit BroadcastStreamReady(broadcastReady); - if (start_now) + if (start_now) { QMetaObject::invokeMethod(this, "StartStreaming"); + } } void OBSBasic::YoutubeStreamCheck(const std::string &key) @@ -142,11 +143,13 @@ void OBSBasic::BroadcastButtonClicked() if (ytAuth.get()) { if (!ytAuth->StartLatestBroadcast()) { auto last_error = ytAuth->GetLastError(); - if (last_error.isEmpty()) + if (last_error.isEmpty()) { last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); - if (!ytAuth->GetTranslatedError(last_error)) + } + if (!ytAuth->GetTranslatedError(last_error)) { last_error = QTStr("YouTube.Actions.Error.BroadcastTransitionFailed") .arg(last_error, ytAuth->GetBroadcastId()); + } OBSMessageBox::warning(this, QTStr("Output.BroadcastStartFailed"), last_error, true); return; @@ -165,19 +168,22 @@ void OBSBasic::BroadcastButtonClicked() this, QTStr("ConfirmStop.Title"), QTStr("YouTube.Actions.AutoStopStreamingWarning"), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return; + } } std::shared_ptr ytAuth = dynamic_pointer_cast(auth); if (ytAuth.get()) { if (!ytAuth->StopLatestBroadcast()) { auto last_error = ytAuth->GetLastError(); - if (last_error.isEmpty()) + if (last_error.isEmpty()) { last_error = QTStr("YouTube.Actions.Error.YouTubeApi"); - if (!ytAuth->GetTranslatedError(last_error)) + } + if (!ytAuth->GetTranslatedError(last_error)) { last_error = QTStr("YouTube.Actions.Error.BroadcastTransitionFailed") .arg(last_error, ytAuth->GetBroadcastId()); + } OBSMessageBox::warning(this, QTStr("Output.BroadcastStopFailed"), last_error, true); } @@ -222,32 +228,37 @@ YouTubeAppDock *OBSBasic::GetYouTubeAppDock() void OBSBasic::NewYouTubeAppDock() { - if (!cef_js_avail) + if (!cef_js_avail) { return; + } /* make sure that the youtube app dock can't be immediately recreated. * dumb hack. blame chromium. or this particular dock. or both. if CEF * creates/destroys/creates a widget too quickly it can lead to a * crash. */ uint64_t ts = os_gettime_ns(); - if ((ts - lastYouTubeAppDockCreationTime) < (5ULL * SEC_TO_NSEC)) + if ((ts - lastYouTubeAppDockCreationTime) < (5ULL * SEC_TO_NSEC)) { return; + } lastYouTubeAppDockCreationTime = ts; - if (youtubeAppDock) + if (youtubeAppDock) { RemoveDockWidget(youtubeAppDock->objectName()); + } youtubeAppDock = new YouTubeAppDock("YouTube Live Control Panel"); } void OBSBasic::DeleteYouTubeAppDock() { - if (!cef_js_avail) + if (!cef_js_avail) { return; + } - if (youtubeAppDock) + if (youtubeAppDock) { RemoveDockWidget(youtubeAppDock->objectName()); + } youtubeAppDock = nullptr; } diff --git a/frontend/widgets/OBSProjector.cpp b/frontend/widgets/OBSProjector.cpp index 16e7fc5e55f5fd..5a1649cfbd846e 100644 --- a/frontend/widgets/OBSProjector.cpp +++ b/frontend/widgets/OBSProjector.cpp @@ -29,8 +29,9 @@ OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, isAlwaysOnTop = config_get_bool(App()->GetUserConfig(), "BasicWindow", "ProjectorAlwaysOnTop"); - if (isAlwaysOnTop) + if (isAlwaysOnTop) { setWindowFlags(Qt::WindowStaysOnTopHint); + } // Mark the window as a projector so SetDisplayAffinity // can skip it @@ -46,15 +47,17 @@ OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, setWindowIcon(QIcon::fromTheme("obs", QIcon(":/res/images/obs.png"))); #endif - if (monitor == -1) + if (monitor == -1) { resize(480, 270); - else + } else { SetMonitor(monitor); + } - if (source) + if (source) { UpdateProjectorTitle(QT_UTF8(obs_source_get_name(source))); - else + } else { UpdateProjectorTitle(QString()); + } QAction *action = new QAction(this); action->setShortcut(Qt::Key_Escape); @@ -87,8 +90,9 @@ OBSProjector::OBSProjector(QWidget *widget, obs_source_t *source_, int monitor, App()->IncrementSleepInhibition(); - if (source) + if (source) { obs_source_inc_showing(source); + } ready = true; @@ -106,8 +110,9 @@ OBSProjector::~OBSProjector() obs_display_remove_draw_callback(GetDisplay(), isMultiview ? OBSRenderMultiview : OBSRender, this); OBSSource source = GetSource(); - if (source) + if (source) { obs_source_dec_showing(source); + } if (isMultiview) { delete multiview; @@ -127,23 +132,26 @@ void OBSProjector::SetMonitor(int monitor) void OBSProjector::SetHideCursor() { - if (savedMonitor == -1) + if (savedMonitor == -1) { return; + } bool hideCursor = config_get_bool(App()->GetUserConfig(), "BasicWindow", "HideProjectorCursor"); - if (hideCursor && type != ProjectorType::Multiview) + if (hideCursor && type != ProjectorType::Multiview) { setCursor(Qt::BlankCursor); - else + } else { setCursor(Qt::ArrowCursor); + } } void OBSProjector::OBSRenderMultiview(void *data, uint32_t cx, uint32_t cy) { OBSProjector *window = (OBSProjector *)data; - if (updatingMultiview || !window->ready) + if (updatingMultiview || !window->ready) { return; + } window->multiview->Render(cx, cy); } @@ -152,8 +160,9 @@ void OBSProjector::OBSRender(void *data, uint32_t cx, uint32_t cy) { OBSProjector *window = static_cast(data); - if (!window->ready) + if (!window->ready) { return; + } OBSBasic *main = OBSBasic::Get(); OBSSource source = window->GetSource(); @@ -194,10 +203,11 @@ void OBSProjector::OBSRender(void *data, uint32_t cx, uint32_t cy) window->weakSource = nullptr; } - if (source) + if (source) { obs_source_video_render(source); - else + } else { obs_render_main_texture(); + } endRegion(); } @@ -221,28 +231,34 @@ void OBSProjector::mouseDoubleClickEvent(QMouseEvent *event) { OBSQTDisplay::mouseDoubleClickEvent(event); - if (!mouseSwitching) + if (!mouseSwitching) { return; + } - if (!transitionOnDoubleClick) + if (!transitionOnDoubleClick) { return; + } // Only MultiView projectors handle double click - if (this->type != ProjectorType::Multiview) + if (this->type != ProjectorType::Multiview) { return; + } OBSBasic *main = (OBSBasic *)obs_frontend_get_main_window(); - if (!main->IsPreviewProgramMode()) + if (!main->IsPreviewProgramMode()) { return; + } if (event->button() == Qt::LeftButton) { QPoint pos = event->pos(); OBSSource src = multiview->GetSourceByPosition(pos.x(), pos.y()); - if (!src) + if (!src) { return; + } - if (main->GetProgramSource() != src) + if (main->GetProgramSource() != src) { main->TransitionToScene(src); + } } } @@ -276,20 +292,24 @@ void OBSProjector::mousePressEvent(QMouseEvent *event) popup.exec(QCursor::pos()); } else if (event->button() == Qt::LeftButton) { // Only MultiView projectors handle left click - if (this->type != ProjectorType::Multiview) + if (this->type != ProjectorType::Multiview) { return; + } - if (!mouseSwitching) + if (!mouseSwitching) { return; + } QPoint pos = event->pos(); OBSSource src = multiview->GetSourceByPosition(pos.x(), pos.y()); - if (!src) + if (!src) { return; + } OBSBasic *main = (OBSBasic *)obs_frontend_get_main_window(); - if (main->GetCurrentSceneSource() != src) + if (main->GetCurrentSceneSource() != src) { main->SetCurrentScene(src, false); + } } } @@ -363,8 +383,9 @@ void OBSProjector::UpdateMultiviewProjectors() updatingMultiview = true; obs_leave_graphics(); - for (auto &projector : multiviewProjectors) + for (auto &projector : multiviewProjectors) { projector->UpdateMultiview(); + } obs_enter_graphics(); updatingMultiview = false; @@ -373,16 +394,18 @@ void OBSProjector::UpdateMultiviewProjectors() void OBSProjector::RenameProjector(QString oldName, QString newName) { - if (oldName == newName) + if (oldName == newName) { return; + } UpdateProjectorTitle(newName); } void OBSProjector::OpenFullScreenProjector() { - if (!isFullScreen()) + if (!isFullScreen()) { prevGeometry = geometry(); + } int monitor = sender()->property("monitor").toInt(); SetMonitor(monitor); @@ -397,10 +420,11 @@ void OBSProjector::OpenWindowedProjector() showNormal(); setCursor(Qt::ArrowCursor); - if (!prevGeometry.isNull()) + if (!prevGeometry.isNull()) { setGeometry(prevGeometry); - else + } else { resize(480, 270); + } savedMonitor = -1; @@ -465,9 +489,11 @@ void OBSProjector::SetIsAlwaysOnTop(bool isAlwaysOnTop, bool isOverridden) void OBSProjector::ScreenRemoved(QScreen *screen) { - if (GetMonitor() < 0) + if (GetMonitor() < 0) { return; + } - if (screen == this->screen()) + if (screen == this->screen()) { EscapeTriggered(); + } } diff --git a/frontend/widgets/OBSQTDisplay.cpp b/frontend/widgets/OBSQTDisplay.cpp index ea341bc2a9ab0a..9e65f4dfb3624f 100644 --- a/frontend/widgets/OBSQTDisplay.cpp +++ b/frontend/widgets/OBSQTDisplay.cpp @@ -130,14 +130,17 @@ void OBSQTDisplay::UpdateDisplayBackgroundColor() void OBSQTDisplay::CreateDisplay() { - if (display) + if (display) { return; + } - if (destroying) + if (destroying) { return; + } - if (!windowHandle()->isExposed()) + if (!windowHandle()->isExposed()) { return; + } QSize size = GetPixelSize(this); @@ -147,8 +150,9 @@ void OBSQTDisplay::CreateDisplay() info.format = GS_BGRA; info.zsformat = GS_ZS_NONE; - if (!QTToGSWindow(windowHandle(), info.window)) + if (!QTToGSWindow(windowHandle(), info.window)) { return; + } display = obs_display_create(&info, backgroundColor); @@ -205,12 +209,14 @@ QPaintEngine *OBSQTDisplay::paintEngine() const void OBSQTDisplay::OnMove() { - if (display) + if (display) { obs_display_update_color_space(display); + } } void OBSQTDisplay::OnDisplayChange() { - if (display) + if (display) { obs_display_update_color_space(display); + } } diff --git a/frontend/wizards/AutoConfig.cpp b/frontend/wizards/AutoConfig.cpp index 86e6ccea875cae..ba9366444577d7 100644 --- a/frontend/wizards/AutoConfig.cpp +++ b/frontend/wizards/AutoConfig.cpp @@ -162,8 +162,9 @@ AutoConfig::AutoConfig(QWidget *parent) : QWizard(parent) if (!customServer) { QComboBox *serverList = streamPage->ui->server; int idx = serverList->findData(QString(server.c_str())); - if (idx == -1) + if (idx == -1) { idx = 0; + } serverList->setCurrentIndex(idx); } else { @@ -172,8 +173,9 @@ AutoConfig::AutoConfig(QWidget *parent) : QWizard(parent) streamPage->ui->service->setCurrentIndex(idx); } - if (!key.empty()) + if (!key.empty()) { streamPage->ui->key->setText(key.c_str()); + } TestHardwareEncoding(); @@ -215,28 +217,31 @@ void AutoConfig::TestHardwareEncoding() size_t idx = 0; const char *id; while (obs_enum_encoder_types(idx++, &id)) { - if (strcmp(id, "ffmpeg_nvenc") == 0) + if (strcmp(id, "ffmpeg_nvenc") == 0) { hardwareEncodingAvailable = nvencAvailable = true; - else if (strcmp(id, "obs_qsv11") == 0) + } else if (strcmp(id, "obs_qsv11") == 0) { hardwareEncodingAvailable = qsvAvailable = true; - else if (strcmp(id, "h264_texture_amf") == 0) + } else if (strcmp(id, "h264_texture_amf") == 0) { hardwareEncodingAvailable = vceAvailable = true; + } #ifdef __APPLE__ 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, *)) + if (__builtin_available(macOS 13.0, *)) { hardwareEncodingAvailable = appleAvailable = true; + } #endif } } bool AutoConfig::CanTestServer(const char *server) { - if (!testRegions || (regionUS && regionEU && regionAsia && regionOther)) + if (!testRegions || (regionUS && regionEU && regionAsia && regionOther)) { return true; + } if (service == Service::Twitch) { if (astrcmp_n(server, "US West:", 8) == 0 || astrcmp_n(server, "US East:", 8) == 0 || @@ -261,8 +266,9 @@ void AutoConfig::done(int result) QWizard::done(result); if (result == QDialog::Accepted) { - if (type == Type::Streaming) + if (type == Type::Streaming) { SaveStreamSettings(); + } SaveSettings(); #ifdef YOUTUBE_ENABLED @@ -304,20 +310,23 @@ void AutoConfig::SaveStreamSettings() OBSDataAutoRelease settings = obs_data_create(); - if (!customServer) + if (!customServer) { obs_data_set_string(settings, "service", serviceName.c_str()); + } obs_data_set_string(settings, "server", server.c_str()); #ifdef YOUTUBE_ENABLED - if (!streamPage->auth || !IsYouTubeService(serviceName)) + if (!streamPage->auth || !IsYouTubeService(serviceName)) { obs_data_set_string(settings, "key", key.c_str()); + } #else obs_data_set_string(settings, "key", key.c_str()); #endif OBSServiceAutoRelease newService = obs_service_create(service_id, "default_service", settings, hotkeyData); - if (!newService) + if (!newService) { return; + } main->SetService(newService); main->SaveService(); @@ -338,11 +347,12 @@ void AutoConfig::SaveStreamSettings() config_set_bool(main->Config(), "Stream1", "EnableMultitrackVideo", multitrackVideo.testSuccessful); - if (multitrackVideo.targetBitrate.has_value()) + if (multitrackVideo.targetBitrate.has_value()) { config_set_int(main->Config(), "Stream1", "MultitrackVideoTargetBitrate", *multitrackVideo.targetBitrate); - else + } else { config_remove_value(main->Config(), "Stream1", "MultitrackVideoTargetBitrate"); + } if (multitrackVideo.bitrate.has_value() && multitrackVideo.targetBitrate.has_value() && (static_cast(*multitrackVideo.bitrate) / *multitrackVideo.targetBitrate) >= 0.90) { @@ -358,8 +368,9 @@ void AutoConfig::SaveSettings() { OBSBasic *main = OBSBasic::Get(); - if (recordingEncoder != Encoder::Stream) + if (recordingEncoder != Encoder::Stream) { config_set_string(main->Config(), "SimpleOutput", "RecEncoder", GetEncoderId(recordingEncoder)); + } const char *quality = recordingQuality == Quality::High ? "Small" : "Stream"; diff --git a/frontend/wizards/AutoConfigStreamPage.cpp b/frontend/wizards/AutoConfigStreamPage.cpp index 1e5c47536e4037..75ccb296bdce0f 100644 --- a/frontend/wizards/AutoConfigStreamPage.cpp +++ b/frontend/wizards/AutoConfigStreamPage.cpp @@ -122,10 +122,11 @@ bool AutoConfigStreamPage::validatePage() if (IsYouTubeService(wiz->serviceName)) { /* Adjust upper bound to YouTube limits * for resolutions above 1080p */ - if (wiz->baseResolutionCY > 1440) + if (wiz->baseResolutionCY > 1440) { bitrate = 51000; - else if (wiz->baseResolutionCY > 1080) + } else if (wiz->baseResolutionCY > 1080) { bitrate = 18000; + } } #endif } @@ -150,21 +151,25 @@ bool AutoConfigStreamPage::validatePage() wiz->regionAsia = ui->regionAsia->isChecked(); wiz->regionOther = ui->regionOther->isChecked(); wiz->serviceName = QT_TO_UTF8(ui->service->currentText()); - if (ui->preferHardware) + if (ui->preferHardware) { wiz->preferHardware = ui->preferHardware->isChecked(); + } wiz->key = QT_TO_UTF8(ui->key->text()); if (!wiz->customServer) { - if (wiz->serviceName == "Twitch") + if (wiz->serviceName == "Twitch") { wiz->service = AutoConfig::Service::Twitch; + } #ifdef YOUTUBE_ENABLED - else if (IsYouTubeService(wiz->serviceName)) + else if (IsYouTubeService(wiz->serviceName)) { wiz->service = AutoConfig::Service::YouTube; + } #endif - else if (wiz->serviceName == "Amazon IVS") + else if (wiz->serviceName == "Amazon IVS") { wiz->service = AutoConfig::Service::AmazonIVS; - else + } else { wiz->service = AutoConfig::Service::Other; + } } else { wiz->service = AutoConfig::Service::Other; } @@ -189,13 +194,15 @@ bool AutoConfigStreamPage::validatePage() postData, multitrack_video_name); for (const auto &endpoint : config.ingest_endpoints) { - if (qstrnicmp("RTMP", endpoint.protocol.c_str(), 4) != 0) + if (qstrnicmp("RTMP", endpoint.protocol.c_str(), 4) != 0) { continue; + } std::string address = endpoint.url_template; auto pos = address.find("/{stream_key}"); - if (pos != address.npos) + if (pos != address.npos) { address.erase(pos); + } wiz->serviceConfigServers.push_back({address, address}); } @@ -203,11 +210,13 @@ bool AutoConfigStreamPage::validatePage() int multitrackVideoBitrate = 0; for (auto &encoder_config : config.encoder_configurations) { auto it = encoder_config.settings.find("bitrate"); - if (it == encoder_config.settings.end()) + if (it == encoder_config.settings.end()) { continue; + } - if (!it->is_number_integer()) + if (!it->is_number_integer()) { continue; + } int bitrate = 0; it->get_to(bitrate); @@ -233,8 +242,9 @@ bool AutoConfigStreamPage::validatePage() button = OBSMessageBox::question(this, WARNING_TEXT("Title"), WARNING_TEXT("Text")); #undef WARNING_TEXT - if (button == QMessageBox::No) + if (button == QMessageBox::No) { return false; + } } return true; @@ -258,8 +268,9 @@ void AutoConfigStreamPage::OnOAuthStreamKeyConnected() if (a) { bool validKey = !a->key().empty(); - if (validKey) + if (validKey) { ui->key->setText(QT_UTF8(a->key().c_str())); + } ui->streamKeyWidget->setVisible(false); ui->streamKeyLabel->setVisible(false); @@ -435,8 +446,9 @@ void AutoConfigStreamPage::reset_service_ui_fields(std::string &service) void AutoConfigStreamPage::ServiceChanged() { bool showMore = ui->service->currentData().toInt() == (int)ListOpt::ShowAll; - if (showMore) + if (showMore) { return; + } std::string service = QT_TO_UTF8(ui->service->currentText()); bool regionBased = service == "Twitch"; @@ -479,8 +491,9 @@ void AutoConfigStreamPage::ServiceChanged() 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); @@ -493,8 +506,9 @@ void AutoConfigStreamPage::ServiceChanged() ui->serverStackedWidget->setVisible(true); ui->serverLabel->setVisible(true); } else { - if (!testBandwidth) + if (!testBandwidth) { ui->streamkeyPageLayout->insertRow(2, ui->serverLabel, ui->serverStackedWidget); + } ui->region->setVisible(regionBased && testBandwidth); ui->serverStackedWidget->setCurrentIndex(0); @@ -622,11 +636,13 @@ void AutoConfigStreamPage::LoadServices(bool showAll) names.push_back(name); } - if (showAll) + if (showAll) { names.sort(Qt::CaseInsensitive); + } - for (QString &name : names) + for (QString &name : names) { ui->service->addItem(name); + } if (!showAll) { ui->service->addItem(QTStr("Basic.AutoConfig.StreamPage.Service.ShowAll"), @@ -637,8 +653,9 @@ void AutoConfigStreamPage::LoadServices(bool showAll) if (!lastService.isEmpty()) { int idx = ui->service->findText(lastService); - if (idx != -1) + if (idx != -1) { ui->service->setCurrentIndex(idx); + } } obs_properties_destroy(props); diff --git a/frontend/wizards/AutoConfigTestPage.cpp b/frontend/wizards/AutoConfigTestPage.cpp index c6547ba1b14912..c046fa4e8e2e4b 100644 --- a/frontend/wizards/AutoConfigTestPage.cpp +++ b/frontend/wizards/AutoConfigTestPage.cpp @@ -79,10 +79,11 @@ static inline void string_depad_key(string &key) { while (!key.empty()) { char ch = key.back(); - if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') + if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\r') { key.pop_back(); - else + } else { break; + } } } @@ -168,10 +169,11 @@ void AutoConfigTestPage::TestBandwidthThread() /* determine which servers to test */ std::vector servers; - if (wiz->customServer) + if (wiz->customServer) { servers.emplace_back(wiz->server.c_str(), wiz->server.c_str()); - else + } else { GetServers(servers); + } /* just use the first server if it only has one alternate server, * or if using Restream or Nimo TV due to their "auto" servers */ @@ -200,8 +202,9 @@ void AutoConfigTestPage::TestBandwidthThread() 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)) + if (same_server != std::end(servers)) { servers.erase(same_server); + } servers.emplace(std::begin(servers), it->name.c_str(), it->address.c_str()); } @@ -240,8 +243,9 @@ void AutoConfigTestPage::TestBandwidthThread() } /* If third-party protocol, use the first enumerated type */ - if (!output_type) + if (!output_type) { obs_enum_output_types_with_protocol(protocol, &output_type, return_first_id); + } /* If none, fail */ if (!output_type) { @@ -327,8 +331,9 @@ void AutoConfigTestPage::TestBandwidthThread() obs_data_set_string(service_settings, "server", server.address.c_str()); obs_service_update(service, service_settings); - if (!obs_output_start(output)) + if (!obs_output_start(output)) { continue; + } unique_lock ul(m); if (cancel) { @@ -336,15 +341,17 @@ void AutoConfigTestPage::TestBandwidthThread() obs_output_force_stop(output); return; } - if (!stopped && !connected) + if (!stopped && !connected) { cv.wait(ul); + } if (cancel) { ul.unlock(); obs_output_force_stop(output); return; } - if (!connected) + if (!connected) { continue; + } QMetaObject::invokeMethod(this, "UpdateMessage", Q_ARG(QString, QTStr(TEST_BW_SERVER).arg(server.name.c_str()))); @@ -352,8 +359,9 @@ void AutoConfigTestPage::TestBandwidthThread() /* ignore first 2.5 seconds due to possible buffering skewing * the result */ cv.wait_for(ul, chrono::milliseconds(2500)); - if (stopped) + if (stopped) { continue; + } if (cancel) { ul.unlock(); obs_output_force_stop(output); @@ -365,8 +373,9 @@ void AutoConfigTestPage::TestBandwidthThread() uint64_t t_start = os_gettime_ns(); cv.wait_for(ul, chrono::seconds(10)); - if (stopped) + if (stopped) { continue; + } if (cancel) { ul.unlock(); obs_output_force_stop(output); @@ -377,8 +386,9 @@ void AutoConfigTestPage::TestBandwidthThread() cv.wait(ul); uint64_t total_time = os_gettime_ns() - t_start; - if (total_time == 0) + 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); @@ -577,12 +587,14 @@ bool AutoConfigTestPage::TestSoftwareEncoding() int per = ++i * 100 / count; QMetaObject::invokeMethod(this, "Progress", Q_ARG(int, per)); - if (cy > baseCY) + if (cy > baseCY) { return true; + } /* no need for more than 3 tests max */ - if (results.size() >= 3) + if (results.size() >= 3) { return true; + } if (!fps_num || !fps_den) { fps_num = wiz->specificFPSNum; @@ -595,13 +607,15 @@ bool AutoConfigTestPage::TestSoftwareEncoding() if (!force && wiz->type != AutoConfig::Type::Recording) { int est = EstimateMinBitrate(cx, cy, fps_num, fps_den); - if (est > wiz->idealBitrate) + if (est > wiz->idealBitrate) { return true; + } } long double rate = (long double)cx * (long double)cy * fps; - if (!force && rate > maxDataRate) + if (!force && rate > maxDataRate) { return true; + } testMode.SetVideo(cx, cy, fps_num, fps_den); @@ -620,8 +634,9 @@ bool AutoConfigTestPage::TestSoftwareEncoding() Q_ARG(QString, QTStr(TEST_RES_VAL).arg(cxStr, cyStr, fpsStr))); unique_lock ul(m); - if (cancel) + if (cancel) { return false; + } if (!obs_output_start(output)) { QMetaObject::invokeMethod(this, "Failure", Q_ARG(QString, QTStr(TEST_RES_FAIL))); @@ -634,58 +649,80 @@ bool AutoConfigTestPage::TestSoftwareEncoding() cv.wait(ul); int skipped = (int)video_output_get_skipped_frames(obs_get_video()); - if (force || skipped <= 10) + if (force || skipped <= 10) { results.emplace_back(cx, cy, fps_num, fps_den); + } return !cancel; }; if (wiz->specificFPSNum && wiz->specificFPSDen) { count = 7; - if (!testRes(2160, 0, 0, false)) + if (!testRes(2160, 0, 0, false)) { return false; - if (!testRes(1440, 0, 0, false)) + } + if (!testRes(1440, 0, 0, false)) { return false; - if (!testRes(1080, 0, 0, false)) + } + if (!testRes(1080, 0, 0, false)) { return false; - if (!testRes(720, 0, 0, false)) + } + if (!testRes(720, 0, 0, false)) { return false; - if (!testRes(480, 0, 0, false)) + } + if (!testRes(480, 0, 0, false)) { return false; - if (!testRes(360, 0, 0, false)) + } + if (!testRes(360, 0, 0, false)) { return false; - if (!testRes(240, 0, 0, true)) + } + if (!testRes(240, 0, 0, true)) { return false; + } } else { count = 14; - if (!testRes(2160, 60, 1, false)) + if (!testRes(2160, 60, 1, false)) { return false; - if (!testRes(2160, 30, 1, false)) + } + if (!testRes(2160, 30, 1, false)) { return false; - if (!testRes(1440, 60, 1, false)) + } + if (!testRes(1440, 60, 1, false)) { return false; - if (!testRes(1440, 30, 1, false)) + } + if (!testRes(1440, 30, 1, false)) { return false; - if (!testRes(1080, 60, 1, false)) + } + if (!testRes(1080, 60, 1, false)) { return false; - if (!testRes(1080, 30, 1, false)) + } + if (!testRes(1080, 30, 1, false)) { return false; - if (!testRes(720, 60, 1, false)) + } + if (!testRes(720, 60, 1, false)) { return false; - if (!testRes(720, 30, 1, false)) + } + if (!testRes(720, 30, 1, false)) { return false; - if (!testRes(480, 60, 1, false)) + } + if (!testRes(480, 60, 1, false)) { return false; - if (!testRes(480, 30, 1, false)) + } + if (!testRes(480, 30, 1, false)) { return false; - if (!testRes(360, 60, 1, false)) + } + if (!testRes(360, 60, 1, false)) { return false; - if (!testRes(360, 30, 1, false)) + } + if (!testRes(360, 30, 1, false)) { return false; - if (!testRes(240, 60, 1, false)) + } + if (!testRes(240, 60, 1, false)) { return false; - if (!testRes(240, 30, 1, true)) + } + if (!testRes(240, 30, 1, true)) { return false; + } } /* -----------------------------------*/ @@ -699,8 +736,9 @@ bool AutoConfigTestPage::TestSoftwareEncoding() if (result1.fps_num == 30 && result2.fps_num == 60) { int nextArea = result2.cx * result2.cy; - if (nextArea >= minArea) + if (nextArea >= minArea) { results.erase(results.begin()); + } } } @@ -720,11 +758,13 @@ bool AutoConfigTestPage::TestSoftwareEncoding() } if (wiz->testMultitrackVideo && wiz->multitrackVideo.testSuccessful && - !wiz->multitrackVideo.bitrate.has_value()) + !wiz->multitrackVideo.bitrate.has_value()) { wiz->multitrackVideo.bitrate = wiz->idealBitrate; + } - if (wiz->idealBitrate > upperBitrate) + if (wiz->idealBitrate > upperBitrate) { wiz->idealBitrate = upperBitrate; + } softwareTested = true; return true; @@ -747,11 +787,13 @@ void AutoConfigTestPage::FindIdealHardwareResolution() } auto testRes = [&](int cy, int fps_num, int fps_den, bool force) { - if (cy > baseCY) + if (cy > baseCY) { return; + } - if (results.size() >= 3) + if (results.size() >= 3) { return; + } if (!fps_num || !fps_den) { fps_num = wiz->specificFPSNum; @@ -763,8 +805,9 @@ void AutoConfigTestPage::FindIdealHardwareResolution() 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) + if (!force && rate > maxDataRate) { return; + } AutoConfig::Encoder encType = wiz->streamingEncoder; bool nvenc = encType == AutoConfig::Encoder::NVENC; @@ -775,13 +818,16 @@ void AutoConfigTestPage::FindIdealHardwareResolution() * ratio, so increase the minimum bitrate estimate for them. * NVENC currently is the exception because of the improvements * its made to its quality in recent generations. */ - if (!nvenc) + if (!nvenc) { minBitrate = minBitrate * 114 / 100; + } - if (wiz->type == AutoConfig::Type::Recording) + if (wiz->type == AutoConfig::Type::Recording) { force = true; - if (force || wiz->idealBitrate >= minBitrate) + } + if (force || wiz->idealBitrate >= minBitrate) { results.emplace_back(cx, cy, fps_num, fps_den); + } }; if (wiz->specificFPSNum && wiz->specificFPSDen) { @@ -817,8 +863,9 @@ void AutoConfigTestPage::FindIdealHardwareResolution() if (result1.fps_num == 30 && result2.fps_num == 60) { int nextArea = result2.cx * result2.cy; - if (nextArea >= minArea) + if (nextArea >= minArea) { results.erase(results.begin()); + } } } @@ -841,14 +888,15 @@ void AutoConfigTestPage::TestStreamEncoderThread() } if (!softwareTested) { - if (wiz->nvencAvailable) + if (wiz->nvencAvailable) { wiz->streamingEncoder = AutoConfig::Encoder::NVENC; - else if (wiz->qsvAvailable) + } else if (wiz->qsvAvailable) { wiz->streamingEncoder = AutoConfig::Encoder::QSV; - else if (wiz->appleAvailable) + } else if (wiz->appleAvailable) { wiz->streamingEncoder = AutoConfig::Encoder::Apple; - else + } else { wiz->streamingEncoder = AutoConfig::Encoder::AMD; + } } else { wiz->streamingEncoder = AutoConfig::Encoder::x264; } @@ -863,8 +911,9 @@ void AutoConfigTestPage::TestStreamEncoderThread() } #endif - if (preferHardware && !softwareTested && wiz->hardwareEncodingAvailable) + if (preferHardware && !softwareTested && wiz->hardwareEncodingAvailable) { FindIdealHardwareResolution(); + } QMetaObject::invokeMethod(this, "NextStage"); } @@ -877,22 +926,24 @@ 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; bool recordingOnly = wiz->type == AutoConfig::Type::Recording; if (wiz->hardwareEncodingAvailable) { - if (wiz->nvencAvailable) + if (wiz->nvencAvailable) { wiz->recordingEncoder = AutoConfig::Encoder::NVENC; - else if (wiz->qsvAvailable) + } else if (wiz->qsvAvailable) { wiz->recordingEncoder = AutoConfig::Encoder::QSV; - else if (wiz->appleAvailable) + } else if (wiz->appleAvailable) { wiz->recordingEncoder = AutoConfig::Encoder::Apple; - else + } else { wiz->recordingEncoder = AutoConfig::Encoder::AMD; + } } else { wiz->recordingEncoder = AutoConfig::Encoder::x264; } @@ -976,8 +1027,9 @@ void AutoConfigTestPage::FinalizeResults() OBSDataAutoRelease vencoder_settings = obs_data_create(); if (wiz->testMultitrackVideo && wiz->multitrackVideo.testSuccessful && - !wiz->multitrackVideo.bitrate.has_value()) + !wiz->multitrackVideo.bitrate.has_value()) { wiz->multitrackVideo.bitrate = wiz->idealBitrate; + } obs_data_set_int(vencoder_settings, "bitrate", wiz->idealBitrate); @@ -1004,9 +1056,10 @@ void AutoConfigTestPage::FinalizeResults() wiz->idealBitrate = (int)obs_data_get_int(vencoder_settings, "bitrate"); - if (!wiz->customServer) + if (!wiz->customServer) { 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"), @@ -1031,8 +1084,9 @@ void AutoConfigTestPage::FinalizeResults() QString("%1x%2").arg(QString::number(wiz->idealResolutionCX), QString::number(wiz->idealResolutionCY)); if (wiz->recordingEncoder != AutoConfig::Encoder::Stream || - wiz->recordingQuality != AutoConfig::Quality::Stream) + wiz->recordingQuality != AutoConfig::Quality::Stream) { form->addRow(newLabel(TEST_RESULT_RE), new QLabel(encName(wiz->recordingEncoder), ui->finishPage)); + } QString recQuality; @@ -1063,10 +1117,12 @@ void AutoConfigTestPage::FinalizeResults() void AutoConfigTestPage::NextStage() { - if (testThread.joinable()) + if (testThread.joinable()) { testThread.join(); - if (cancel) + } + if (cancel) { return; + } ui->subProgressLabel->setText(QString()); @@ -1138,8 +1194,9 @@ AutoConfigTestPage::~AutoConfigTestPage() testThread.join(); } - if (started) + if (started) { blog(LOG_INFO, STOPPING_SEPARATOR); + } } void AutoConfigTestPage::initializePage() diff --git a/frontend/wizards/AutoConfigVideoPage.cpp b/frontend/wizards/AutoConfigVideoPage.cpp index 69de8e2ecbfa03..549238ff95117f 100644 --- a/frontend/wizards/AutoConfigVideoPage.cpp +++ b/frontend/wizards/AutoConfigVideoPage.cpp @@ -45,8 +45,9 @@ AutoConfigVideoPage::AutoConfigVideoPage(QWidget *parent) : QWizardPage(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) + if (ovi.base_height >= 240) { ui->canvasRes->addItem(QTStr(RES_USE_CURRENT).arg(cxStr, cyStr), (int)encRes); + } QList screens = QGuiApplication::screens(); for (int i = 0; i < screens.size(); i++) { diff --git a/frontend/wizards/TestMode.hpp b/frontend/wizards/TestMode.hpp index fd9b80646243f3..5a1bfed3bcf789 100644 --- a/frontend/wizards/TestMode.hpp +++ b/frontend/wizards/TestMode.hpp @@ -22,8 +22,9 @@ class TestMode { gs_effect_set_vec4(randomvals[i], &r); } - while (gs_effect_loop(solid, "Random")) + while (gs_effect_loop(solid, "Random")) { gs_draw_sprite(nullptr, 0, cx, cy); + } } public: @@ -41,8 +42,9 @@ class TestMode { inline ~TestMode() { - for (uint32_t i = 0; i < 6; i++) + for (uint32_t i = 0; i < 6; i++) { obs_set_output_source(i, source[i]); + } obs_remove_main_render_callback(render_rand, this); obs_reset_video(&ovi); diff --git a/libobs-d3d11/d3d11-duplicator.cpp b/libobs-d3d11/d3d11-duplicator.cpp index a1980711a30007..a63e43cf3e04bd 100644 --- a/libobs-d3d11/d3d11-duplicator.cpp +++ b/libobs-d3d11/d3d11-duplicator.cpp @@ -24,8 +24,9 @@ static inline bool get_monitor(gs_device_t *device, int monitor_idx, IDXGIOutput hr = device->adapter->EnumOutputs(monitor_idx, dxgiOutput); if (FAILED(hr)) { - if (hr == DXGI_ERROR_NOT_FOUND) + if (hr == DXGI_ERROR_NOT_FOUND) { return false; + } throw HRError("Failed to get output", hr); } @@ -40,8 +41,9 @@ void gs_duplicator::Start() ComPtr output; HRESULT hr; - if (!get_monitor(device, idx, output.Assign())) + if (!get_monitor(device, idx, output.Assign())) { throw "Invalid monitor index"; + } hr = output->QueryInterface(IID_PPV_ARGS(output5.Assign())); hdr = false; @@ -53,8 +55,9 @@ void gs_duplicator::Start() }; hr = output5->DuplicateOutput1(device->device, 0, _countof(supportedFormats), supportedFormats, duplicator.Assign()); - if (FAILED(hr)) + 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); @@ -63,12 +66,14 @@ void gs_duplicator::Start() } } else { hr = output->QueryInterface(IID_PPV_ARGS(output1.Assign())); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to query IDXGIOutput1", hr); + } hr = output1->DuplicateOutput(device->device, duplicator.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to DuplicateOutput", hr); + } } } @@ -97,12 +102,14 @@ EXPORT bool device_get_duplicator_monitor_info(gs_device_t *device, int monitor_ try { ComPtr output; - if (!get_monitor(device, monitor_idx, output.Assign())) + if (!get_monitor(device, monitor_idx, output.Assign())) { return false; + } hr = output->GetDesc(&desc); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("GetDesc failed", hr); + } } catch (const HRError &error) { blog(LOG_ERROR, @@ -149,14 +156,16 @@ EXPORT int device_duplicator_get_monitor_index(gs_device_t *device, void *monito while (index == -1) { IDXGIOutput *pOutput; const HRESULT hr = device->adapter->EnumOutputs(output, &pOutput); - if (hr == DXGI_ERROR_NOT_FOUND) + if (hr == DXGI_ERROR_NOT_FOUND) { break; + } if (SUCCEEDED(hr)) { DXGI_OUTPUT_DESC desc; if (SUCCEEDED(pOutput->GetDesc(&desc))) { - if (desc.Monitor == handle) + if (desc.Monitor == handle) { index = output; + } } else { blog(LOG_ERROR, "device_duplicator_get_monitor_index: " @@ -239,8 +248,9 @@ static inline void copy_texture(gs_duplicator_t *d, ID3D11Texture2D *tex) : ((desc.Format == DXGI_FORMAT_R16G16B16A16_FLOAT) ? GS_CS_SRGB_16F : GS_CS_SRGB); } - if (d->texture) + if (d->texture) { d->device->context->CopyResource(d->texture->texture, tex); + } } EXPORT bool gs_duplicator_update_frame(gs_duplicator_t *d) diff --git a/libobs-d3d11/d3d11-indexbuffer.cpp b/libobs-d3d11/d3d11-indexbuffer.cpp index da0ca10e21cbf4..c2787d67eed471 100644 --- a/libobs-d3d11/d3d11-indexbuffer.cpp +++ b/libobs-d3d11/d3d11-indexbuffer.cpp @@ -31,8 +31,9 @@ void gs_index_buffer::InitBuffer() srd.pSysMem = indices.data; hr = device->device->CreateBuffer(&bd, &srd, indexBuffer.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { 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, diff --git a/libobs-d3d11/d3d11-rebuild.cpp b/libobs-d3d11/d3d11-rebuild.cpp index 6912ac1c722d9a..7f11c02e46b853 100644 --- a/libobs-d3d11/d3d11-rebuild.cpp +++ b/libobs-d3d11/d3d11-rebuild.cpp @@ -27,8 +27,9 @@ void gs_vertex_buffer::Rebuild() void gs_index_buffer::Rebuild(ID3D11Device *dev) { HRESULT hr = dev->CreateBuffer(&bd, &srd, &indexBuffer); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create buffer", hr); + } } void gs_texture_2d::RebuildSharedTextureFallback() @@ -79,37 +80,43 @@ void gs_texture_2d::Rebuild(ID3D11Device *dev) if (!isShared) { hr = dev->CreateTexture2D(&td, data.size() ? srd.data() : nullptr, &texture); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 2D texture", hr); + } } hr = dev->CreateShaderResourceView(texture, &viewDesc, &shaderRes); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create SRV", hr); + } if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear SRV", hr); + } } - if (isRenderTarget) + if (isRenderTarget) { InitRenderTargets(); + } if (isGDICompatible) { hr = texture->QueryInterface(__uuidof(IDXGISurface1), (void **)&gdiSurface); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create GDI surface", hr); + } } acquired = false; if ((td.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) != 0) { ComQIPtr dxgi_res(texture); - if (dxgi_res) + if (dxgi_res) { GetSharedHandle(dxgi_res); + } device_texture_acquire_sync(this, 0, INFINITE); } } @@ -120,23 +127,27 @@ void gs_texture_2d::RebuildPaired_Y(ID3D11Device *dev) HRESULT hr; hr = dev->CreateTexture2D(&td, nullptr, &texture); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 2D texture", hr); + } hr = dev->CreateShaderResourceView(texture, &viewDesc, &shaderRes); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create Y SRV", hr); + } if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear Y SRV", hr); + } } - if (isRenderTarget) + if (isRenderTarget) { InitRenderTargets(); + } tex_uv->RebuildPaired_UV(dev); @@ -144,8 +155,9 @@ void gs_texture_2d::RebuildPaired_Y(ID3D11Device *dev) if ((td.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) != 0) { ComQIPtr dxgi_res(texture); - if (dxgi_res) + if (dxgi_res) { GetSharedHandle(dxgi_res); + } device_texture_acquire_sync(this, 0, INFINITE); } } @@ -158,65 +170,75 @@ void gs_texture_2d::RebuildPaired_UV(ID3D11Device *dev) texture = tex_y->texture; hr = dev->CreateShaderResourceView(texture, &viewDesc, &shaderRes); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create UV SRV", hr); + } if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear UV SRV", hr); + } } - if (isRenderTarget) + if (isRenderTarget) { InitRenderTargets(); + } } void gs_zstencil_buffer::Rebuild(ID3D11Device *dev) { HRESULT hr; hr = dev->CreateTexture2D(&td, nullptr, &texture); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create depth stencil texture", hr); + } hr = dev->CreateDepthStencilView(texture, &dsvd, &view); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create depth stencil view", hr); + } } void gs_stage_surface::Rebuild(ID3D11Device *dev) { HRESULT hr = dev->CreateTexture2D(&td, nullptr, &texture); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create staging surface", hr); + } } void gs_sampler_state::Rebuild(ID3D11Device *dev) { HRESULT hr = dev->CreateSamplerState(&sd, state.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create sampler state", hr); + } } void gs_vertex_shader::Rebuild(ID3D11Device *dev) { HRESULT hr; hr = dev->CreateVertexShader(data.data(), data.size(), nullptr, &shader); - if (FAILED(hr)) + 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); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create input layout", hr); + } } if (constantSize) { hr = dev->CreateBuffer(&bd, NULL, &constants); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create constant buffer", hr); + } } for (gs_shader_param ¶m : params) { @@ -231,13 +253,15 @@ void gs_pixel_shader::Rebuild(ID3D11Device *dev) HRESULT hr; hr = dev->CreatePixelShader(data.data(), data.size(), nullptr, &shader); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create pixel shader", hr); + } if (constantSize) { hr = dev->CreateBuffer(&bd, NULL, &constants); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create constant buffer", hr); + } } for (gs_shader_param ¶m : params) { @@ -250,8 +274,9 @@ void gs_pixel_shader::Rebuild(ID3D11Device *dev) void gs_swap_chain::Rebuild(ID3D11Device *dev) { HRESULT hr = device->factory->CreateSwapChain(dev, &swapDesc, &swap); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create swap chain", hr); + } Init(); } @@ -261,11 +286,13 @@ void gs_timer::Rebuild(ID3D11Device *dev) desc.Query = D3D11_QUERY_TIMESTAMP; desc.MiscFlags = 0; HRESULT hr = dev->CreateQuery(&desc, &query_begin); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create timer", hr); + } hr = dev->CreateQuery(&desc, &query_end); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create timer", hr); + } } void gs_timer_range::Rebuild(ID3D11Device *dev) @@ -274,8 +301,9 @@ void gs_timer_range::Rebuild(ID3D11Device *dev) desc.Query = D3D11_QUERY_TIMESTAMP_DISJOINT; desc.MiscFlags = 0; HRESULT hr = dev->CreateQuery(&desc, &query_disjoint); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create timer", hr); + } } void gs_texture_3d::RebuildSharedTextureFallback() @@ -327,28 +355,32 @@ void gs_texture_3d::Rebuild(ID3D11Device *dev) if (!isShared) { hr = dev->CreateTexture3D(&td, data.size() ? srd.data() : nullptr, &texture); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 3D texture", hr); + } } hr = dev->CreateShaderResourceView(texture, &viewDesc, &shaderRes); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 3D SRV", hr); + } if (viewDesc.Format == viewDescLinear.Format) { shaderResLinear = shaderRes; } else { hr = dev->CreateShaderResourceView(texture, &viewDescLinear, &shaderResLinear); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear 3D SRV", hr); + } } acquired = false; if ((td.MiscFlags & D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX) != 0) { ComQIPtr dxgi_res(texture); - if (dxgi_res) + if (dxgi_res) { GetSharedHandle(dxgi_res); + } device_texture_acquire_sync(this, 0, INFINITE); } } @@ -356,22 +388,25 @@ void gs_texture_3d::Rebuild(ID3D11Device *dev) void SavedBlendState::Rebuild(ID3D11Device *dev) { HRESULT hr = dev->CreateBlendState(&bd, &state); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create blend state", hr); + } } void SavedZStencilState::Rebuild(ID3D11Device *dev) { HRESULT hr = dev->CreateDepthStencilState(&dsd, &state); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create depth stencil state", hr); + } } void SavedRasterState::Rebuild(ID3D11Device *dev) { HRESULT hr = dev->CreateRasterizerState(&rd, &state); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create rasterizer state", hr); + } } const static D3D_FEATURE_LEVEL featureLevels[] = { @@ -389,8 +424,9 @@ try { /* ----------------------------------------------------------------- */ - for (gs_device_loss &callback : loss_callbacks) + for (gs_device_loss &callback : loss_callbacks) { callback.device_loss_release(callback.data); + } gs_obj *obj = first_obj; @@ -440,12 +476,15 @@ try { obj = obj->next; } - for (auto &state : zstencilStates) + for (auto &state : zstencilStates) { state.Release(); - for (auto &state : rasterStates) + } + for (auto &state : rasterStates) { state.Release(); - for (auto &state : blendStates) + } + for (auto &state : blendStates) { state.Release(); + } context->ClearState(); context->Flush(); @@ -464,8 +503,9 @@ try { 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)) + if (FAILED(hr)) { throw HRError("Failed to create device", hr); + } dev = device; @@ -543,15 +583,19 @@ try { curBlendState = nullptr; curToplogy = D3D11_PRIMITIVE_TOPOLOGY_UNDEFINED; - for (auto &state : zstencilStates) + for (auto &state : zstencilStates) { state.Rebuild(dev); - for (auto &state : rasterStates) + } + for (auto &state : rasterStates) { state.Rebuild(dev); - for (auto &state : blendStates) + } + for (auto &state : blendStates) { state.Rebuild(dev); + } - for (gs_device_loss &callback : loss_callbacks) + for (gs_device_loss &callback : loss_callbacks) { callback.device_loss_rebuild(device.Get(), callback.data); + } } catch (const char *error) { bcrash("Failed to recreate D3D11: %s", error); diff --git a/libobs-d3d11/d3d11-samplerstate.cpp b/libobs-d3d11/d3d11-samplerstate.cpp index e061c74d48d6fe..8d69d5d2e07bb5 100644 --- a/libobs-d3d11/d3d11-samplerstate.cpp +++ b/libobs-d3d11/d3d11-samplerstate.cpp @@ -84,6 +84,7 @@ gs_sampler_state::gs_sampler_state(gs_device_t *device, const gs_sampler_info *i memcpy(sd.BorderColor, v4.ptr, sizeof(v4)); hr = device->device->CreateSamplerState(&sd, state.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create sampler state", hr); + } } diff --git a/libobs-d3d11/d3d11-shader.cpp b/libobs-d3d11/d3d11-shader.cpp index 3e4aaa1cce504f..930062b099b49f 100644 --- a/libobs-d3d11/d3d11-shader.cpp +++ b/libobs-d3d11/d3d11-shader.cpp @@ -32,14 +32,15 @@ void gs_vertex_shader::GetBuffersExpected(const std::vectorGetBufferPointer(), data.size()); hr = device->device->CreateVertexShader(data.data(), data.size(), NULL, shader.Assign()); - if (FAILED(hr)) + 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(), layout.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create input layout", hr); + } } viewProj = gs_shader_get_param_by_name(this, "ViewProj"); @@ -103,8 +106,9 @@ gs_pixel_shader::gs_pixel_shader(gs_device_t *device, const char *file, const ch memcpy(&data[0], shaderBlob->GetBufferPointer(), data.size()); hr = device->device->CreatePixelShader(data.data(), data.size(), NULL, shader.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create pixel shader", hr); + } } /* @@ -163,16 +167,18 @@ void gs_shader::BuildConstantBuffer() continue; } - if (param.arrayCount) + if (param.arrayCount) { size *= param.arrayCount; + } /* checks to see if this constant needs to start at a new * register */ if (size && (constantSize & 15) != 0) { size_t alignMax = (constantSize + 15) & ~15; - if ((size + constantSize) > alignMax) + if ((size + constantSize) > alignMax) { constantSize = alignMax; + } } param.pos = constantSize; @@ -190,12 +196,14 @@ void gs_shader::BuildConstantBuffer() bd.CPUAccessFlags = D3D11_CPU_ACCESS_WRITE; hr = device->device->CreateBuffer(&bd, NULL, constants.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create constant buffer", hr); + } } - for (size_t i = 0; i < params.size(); i++) + for (size_t i = 0; i < params.size(); i++) { gs_shader_set_default(¶ms[i]); + } } static uint64_t fnv1a_hash(const char *str, size_t len) @@ -218,8 +226,9 @@ void gs_shader::Compile(const char *shaderString, const char *file, const char * bool is_cached = false; char hashstr[20]; - if (!shaderString) + if (!shaderString) { throw "No shader string specified"; + } size_t shaderStrLen = strlen(shaderString); uint64_t hash = fnv1a_hash(shaderString, shaderStrLen); @@ -233,8 +242,9 @@ void gs_shader::Compile(const char *shaderString, const char *file, const char * std::fstream cacheFile; cacheFile.exceptions(std::fstream::badbit | std::fstream::eofbit); - if (std::filesystem::exists(cachePath) && !std::filesystem::is_empty(cachePath)) + if (std::filesystem::exists(cachePath) && !std::filesystem::is_empty(cachePath)) { cacheFile.open(cachePath, std::ios::in | std::ios::binary | std::ios::ate); + } if (cacheFile.is_open()) { uint64_t checksum; @@ -242,8 +252,9 @@ void gs_shader::Compile(const char *shaderString, const char *file, const char * try { std::streampos len = cacheFile.tellg(); // Not enough data for checksum + shader - if (len <= sizeof(checksum)) + if (len <= sizeof(checksum)) { throw std::length_error("File truncated"); + } cacheFile.seekg(0, std::ios::beg); @@ -253,8 +264,9 @@ void gs_shader::Compile(const char *shaderString, const char *file, const char * uint64_t calculated_checksum = fnv1a_hash((char *)(*shader)->GetBufferPointer(), len); cacheFile.read((char *)&checksum, sizeof(checksum)); - if (calculated_checksum != checksum) + if (calculated_checksum != checksum) { throw std::exception("Checksum mismatch"); + } is_cached = true; } catch (const std::exception &e) { @@ -269,10 +281,11 @@ void gs_shader::Compile(const char *shaderString, const char *file, const char * 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()) + if (errorsBlob != NULL && errorsBlob->GetBufferSize()) { throw ShaderError(errorsBlob, hr); - else + } else { throw HRError("Failed to compile shader", hr); + } } cacheFile.open(cachePath, std::ios::out | std::ios::binary); @@ -306,8 +319,9 @@ void gs_shader::Compile(const char *shaderString, const char *file, const char * inline void gs_shader::UpdateParam(std::vector &constData, gs_shader_param ¶m, bool &upload) { if (param.type != GS_SHADER_PARAM_TEXTURE) { - if (!param.curValue.size()) + if (!param.curValue.size()) { throw "Not all shader parameters were set"; + } /* padding in case the constant needs to start at a new * register */ @@ -327,10 +341,11 @@ inline void gs_shader::UpdateParam(std::vector &constData, gs_shader_pa } else if (param.curValue.size() == sizeof(struct gs_shader_texture)) { struct gs_shader_texture shader_tex; memcpy(&shader_tex, param.curValue.data(), sizeof(shader_tex)); - if (shader_tex.srgb) + if (shader_tex.srgb) { device_load_texture_srgb(device, shader_tex.tex, param.textureID); - else + } else { device_load_texture(device, shader_tex.tex, param.textureID); + } if (param.nextSampler) { ID3D11SamplerState *state = param.nextSampler->state; @@ -347,19 +362,22 @@ void gs_shader::UploadParams() constData.reserve(constantSize); - for (size_t i = 0; i < params.size(); i++) + for (size_t i = 0; i < params.size(); i++) { UpdateParam(constData, params[i], upload); + } - if (constData.size() != constantSize) + if (constData.size() != constantSize) { throw "Invalid constant data size given to shader"; + } if (upload) { D3D11_MAPPED_SUBRESOURCE map; HRESULT hr; hr = device->context->Map(constants, 0, D3D11_MAP_WRITE_DISCARD, 0, &map); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Could not lock constant buffer", hr); + } memcpy(map.pData, constData.data(), constData.size()); device->context->Unmap(constants, 0); @@ -368,8 +386,9 @@ void gs_shader::UploadParams() void gs_shader_destroy(gs_shader_t *shader) { - if (shader && shader->device->lastVertexShader == shader) + if (shader && shader->device->lastVertexShader == shader) { shader->device->lastVertexShader = nullptr; + } delete shader; } @@ -387,8 +406,9 @@ gs_sparam_t *gs_shader_get_param_by_name(gs_shader_t *shader, const char *name) { for (size_t i = 0; i < shader->params.size(); i++) { gs_shader_param ¶m = shader->params[i]; - if (strcmp(param.name.c_str(), name) == 0) + if (strcmp(param.name.c_str(), name) == 0) { return ¶m; + } } return NULL; @@ -396,24 +416,27 @@ 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) { - if (shader->type != GS_SHADER_VERTEX) + if (shader->type != GS_SHADER_VERTEX) { return NULL; + } return static_cast(shader)->viewProj; } gs_sparam_t *gs_shader_get_world_matrix(const gs_shader_t *shader) { - if (shader->type != GS_SHADER_VERTEX) + if (shader->type != GS_SHADER_VERTEX) { return NULL; + } return static_cast(shader)->world; } void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_info *info) { - if (!param) + if (!param) { return; + } info->name = param->name.c_str(); info->type = param->type; @@ -422,12 +445,14 @@ void gs_shader_get_param_info(const gs_sparam_t *param, struct gs_shader_param_i static inline void shader_setval_inline(gs_shader_param *param, const void *data, size_t size) { assert(param); - if (!param) + if (!param) { return; + } bool size_changed = param->curValue.size() != size; - if (size_changed) + if (size_changed) { param->curValue.resize(size); + } if (size_changed || memcmp(param->curValue.data(), data, size) != 0) { memcpy(param->curValue.data(), data, size); @@ -490,8 +515,9 @@ 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()) + if (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 1ec93444ffe5d1..3bbb53c0d64e3e 100644 --- a/libobs-d3d11/d3d11-shaderprocessor.cpp +++ b/libobs-d3d11/d3d11-shaderprocessor.cpp @@ -28,8 +28,9 @@ static const char *ConvertSemanticName(const char *name) { const size_t num = sizeof(semanticInputNames) / sizeof(const char *); for (size_t i = 0; i < num; i++) { - if (strcmp(name, semanticInputNames[i]) == 0) + if (strcmp(name, semanticInputNames[i]) == 0) { return semanticOutputNames[i]; + } } throw "Unknown Semantic Name"; @@ -40,8 +41,9 @@ static void GetSemanticInfo(shader_var *var, const char *&name, uint32_t &index) const char *mapping = var->mapping; const char *indexStr = mapping; - while (*indexStr && !isdigit(*indexStr)) + while (*indexStr && !isdigit(*indexStr)) { indexStr++; + } index = (*indexStr) ? strtol(indexStr, NULL, 10) : 0; string nameStr; @@ -110,12 +112,14 @@ static void BuildInputLayoutFromVars(shader_parser *parser, darray *vars, vector shader_var *var = array + i; if (var->mapping) { - if (strcmp(var->mapping, "VERTEXID") != 0) + if (strcmp(var->mapping, "VERTEXID") != 0) { AddInputLayoutVar(var, layout); + } } else { shader_struct *st = shader_parser_getstruct(parser, var->type); - if (st) + if (st) { BuildInputLayoutFromVars(parser, &st->vars.da, layout); + } } } @@ -138,8 +142,9 @@ static void BuildInputLayoutFromVars(shader_parser *parser, darray *vars, vector void ShaderProcessor::BuildInputLayout(vector &layout) { shader_func *func = shader_parser_getfunc(&parser, "main"); - if (!func) + if (!func) { throw "Failed to find 'main' shader function"; + } BuildInputLayoutFromVars(&parser, &func->params.da, layout); } @@ -154,16 +159,18 @@ gs_shader_param::gs_shader_param(shader_var &var, uint32_t &texCounter) defaultValue.resize(var.default_val.num); memcpy(defaultValue.data(), var.default_val.array, var.default_val.num); - if (type == GS_SHADER_PARAM_TEXTURE) + if (type == GS_SHADER_PARAM_TEXTURE) { texCounter++; - else + } else { textureID = 0; + } } 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)); } @@ -172,8 +179,9 @@ void ShaderProcessor::BuildParams(vector ¶ms) { uint32_t texCounter = 0; - for (size_t i = 0; i < parser.params.num; i++) + for (size_t i = 0; i < parser.params.num; i++) { AddParam(parser.params.array[i], params, texCounter); + } } static inline void AddSampler(gs_device_t *device, shader_sampler &sampler, vector> &samplers) @@ -185,8 +193,9 @@ static inline void AddSampler(gs_device_t *device, shader_sampler &sampler, vect void ShaderProcessor::BuildSamplers(vector> &samplers) { - for (size_t i = 0; i < parser.samplers.num; i++) + for (size_t i = 0; i < parser.samplers.num; i++) { AddSampler(device, parser.samplers.array[i], samplers); + } } void ShaderProcessor::BuildString(string &outputString) @@ -197,24 +206,25 @@ void ShaderProcessor::BuildString(string &outputString) cf_token *token = cf_preprocessor_get_tokens(&parser.cfp.pp); while (token->type != CFTOKEN_NONE) { /* cheaply just replace specific tokens */ - if (strref_cmp(&token->str, "POSITION") == 0) + if (strref_cmp(&token->str, "POSITION") == 0) { output << "SV_Position"; - else if (strref_cmp(&token->str, "TARGET") == 0) + } else if (strref_cmp(&token->str, "TARGET") == 0) { output << "SV_Target"; - else if (strref_cmp(&token->str, "texture2d") == 0) + } else if (strref_cmp(&token->str, "texture2d") == 0) { output << "Texture2D"; - else if (strref_cmp(&token->str, "texture3d") == 0) + } else if (strref_cmp(&token->str, "texture3d") == 0) { output << "Texture3D"; - else if (strref_cmp(&token->str, "texture_cube") == 0) + } else if (strref_cmp(&token->str, "texture_cube") == 0) { output << "TextureCube"; - else if (strref_cmp(&token->str, "texture_rect") == 0) + } else if (strref_cmp(&token->str, "texture_rect") == 0) { throw "texture_rect is not supported in D3D"; - else if (strref_cmp(&token->str, "sampler_state") == 0) + } else if (strref_cmp(&token->str, "sampler_state") == 0) { output << "SamplerState"; - else if (strref_cmp(&token->str, "VERTEXID") == 0) + } else if (strref_cmp(&token->str, "VERTEXID") == 0) { output << "SV_VertexID"; - else + } else { output.write(token->str.array, token->str.len); + } token++; } @@ -231,6 +241,7 @@ void ShaderProcessor::Process(const char *shader_string, const char *file) bfree(str); } - if (!success) + if (!success) { throw "Failed to parse shader"; + } } diff --git a/libobs-d3d11/d3d11-stagesurf.cpp b/libobs-d3d11/d3d11-stagesurf.cpp index 1711af6ecd6ba9..01f51d2e6cd169 100644 --- a/libobs-d3d11/d3d11-stagesurf.cpp +++ b/libobs-d3d11/d3d11-stagesurf.cpp @@ -37,8 +37,9 @@ gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t td.Usage = D3D11_USAGE_STAGING; hr = device->device->CreateTexture2D(&td, NULL, texture.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { 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) @@ -61,6 +62,7 @@ gs_stage_surface::gs_stage_surface(gs_device_t *device, uint32_t width, uint32_t td.Usage = D3D11_USAGE_STAGING; hr = device->device->CreateTexture2D(&td, NULL, texture.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create staging surface", hr); + } } diff --git a/libobs-d3d11/d3d11-subsystem.cpp b/libobs-d3d11/d3d11-subsystem.cpp index ad42718c632ac3..c44761cdbe5e98 100644 --- a/libobs-d3d11/d3d11-subsystem.cpp +++ b/libobs-d3d11/d3d11-subsystem.cpp @@ -52,16 +52,19 @@ gs_obj::gs_obj(gs_device_t *device_, gs_type type) : device(device_), obj_type(t prev_next = &device->first_obj; next = device->first_obj; device->first_obj = this; - if (next) + if (next) { next->prev_next = &next; + } } gs_obj::~gs_obj() { - if (prev_next) + if (prev_next) { *prev_next = next; - if (next) + } + if (next) { next->prev_next = prev_next; + } } static enum gs_color_space get_next_space(gs_device_t *device, HWND hwnd, DXGI_SWAP_EFFECT effect) @@ -71,10 +74,11 @@ static enum gs_color_space get_next_space(gs_device_t *device, HWND hwnd, DXGI_S const HMONITOR hMonitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST); if (hMonitor) { const gs_monitor_color_info info = device->GetMonitorColorInfo(hMonitor); - if (info.hdr) + if (info.hdr) { next_space = GS_CS_709_SCRGB; - else if (info.bits_per_color > 8) + } else if (info.bits_per_color > 8) { next_space = GS_CS_SRGB_16F; + } } } @@ -123,24 +127,27 @@ void gs_swap_chain::InitTarget(uint32_t cx, uint32_t cy) target.height = cy; hr = swap->GetBuffer(0, __uuidof(ID3D11Texture2D), (void **)target.texture.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to get swap buffer texture", hr); + } D3D11_RENDER_TARGET_VIEW_DESC rtv; 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()); - if (FAILED(hr)) + 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()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear swap RTV", hr); + } } } @@ -173,24 +180,28 @@ void gs_swap_chain::Resize(uint32_t cx, uint32_t cy, gs_color_format format) if (cx == 0 || cy == 0) { GetClientRect(hwnd, &clientRect); - if (cx == 0) + if (cx == 0) { cx = clientRect.right; - if (cy == 0) + } + if (cy == 0) { cy = clientRect.bottom; + } } const DXGI_FORMAT dxgi_format = ConvertGSTextureFormatView(format); hr = swap->ResizeBuffers(swapDesc.BufferCount, cx, cy, dxgi_format, swapDesc.Flags); - if (FAILED(hr)) + 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; hr = swap3->SetColorSpace1(dxgi_space); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to set color space", hr); + } } target.dxgiFormatResource = ConvertGSTextureFormatResource(format); @@ -238,8 +249,9 @@ 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()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create swap chain", hr); + } /* Ignore Alt+Enter */ device->factory->MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER); @@ -257,22 +269,25 @@ gs_swap_chain::gs_swap_chain(gs_device *device, const gs_init_data *data) gs_swap_chain::~gs_swap_chain() { - if (hWaitable) + if (hWaitable) { CloseHandle(hWaitable); + } } void gs_device::InitFactory() { HRESULT hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); - if (FAILED(hr)) + if (FAILED(hr)) { throw UnsupportedHWError("Failed to create DXGIFactory", hr); + } } void gs_device::InitAdapter(uint32_t adapterIdx) { HRESULT hr = factory->EnumAdapters1(adapterIdx, &adapter); - if (FAILED(hr)) + if (FAILED(hr)) { throw UnsupportedHWError("Failed to enumerate DXGIAdapter", hr); + } } const static D3D_FEATURE_LEVEL featureLevels[] = { @@ -544,8 +559,9 @@ static std::optional GetAdapterHagsStatus(const DXGI_ADAPTER_DESC *d args.PrivateDriverDataSize = sizeof(ext_caps); res = D3DKMTQueryAdapterInfo(&args); - if (SUCCEEDED(res)) + if (SUCCEEDED(res)) { status.SetDriverSupport(ext_caps.HwSchSupportState); + } ret = status; } else { @@ -572,8 +588,9 @@ static bool CheckFormat(ID3D11Device *device, DXGI_FORMAT format) static bool FastClearSupported(UINT vendorId, uint64_t version) { /* Always true for non-NVIDIA GPUs */ - if (vendorId != 0x10de) + if (vendorId != 0x10de) { return true; + } const uint16_t aa = (version >> 48) & 0xffff; const uint16_t bb = (version >> 32) & 0xffff; @@ -607,14 +624,16 @@ void gs_device::InitDevice(uint32_t adapterIdx) blog(LOG_INFO, "Loading up D3D11 on adapter %s (%" PRIu32 ")", adapterNameUTF8.Get(), adapterIdx); hr = adapter->CheckInterfaceSupport(__uuidof(IDXGIDevice), &umd); - if (SUCCEEDED(hr)) + 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()); - if (FAILED(hr)) + if (FAILED(hr)) { throw UnsupportedHWError("Failed to create device", hr); + } blog(LOG_INFO, "D3D11 loaded successfully, feature level used: %x", (unsigned int)levelUsed); @@ -625,8 +644,9 @@ void gs_device::InitDevice(uint32_t adapterIdx) /* Log HAGS status */ bool hags_enabled = false; - if (auto hags_status = GetAdapterHagsStatus(&desc)) + if (auto hags_status = GetAdapterHagsStatus(&desc)) { hags_enabled = hags_status->enabled; + } if (hags_enabled) { blog(LOG_WARNING, "Hardware-Accelerated GPU Scheduling enabled on adapter!"); @@ -694,8 +714,9 @@ ID3D11DepthStencilState *gs_device::AddZStencilState() SavedZStencilState savedState(zstencilState, dsd); hr = device->CreateDepthStencilState(&dsd, savedState.state.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create depth stencil state", hr); + } state = savedState.state; zstencilStates.push_back(savedState); @@ -719,8 +740,9 @@ ID3D11RasterizerState *gs_device::AddRasterState() SavedRasterState savedState(rasterState, rd); hr = device->CreateRasterizerState(&rd, savedState.state.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create rasterizer state", hr); + } state = savedState.state; rasterStates.push_back(savedState); @@ -752,8 +774,9 @@ ID3D11BlendState *gs_device::AddBlendState() SavedBlendState savedState(blendState, bd); hr = device->CreateBlendState(&bd, savedState.state.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create blend state", hr); + } state = savedState.state; blendStates.push_back(savedState); @@ -765,8 +788,9 @@ void gs_device::UpdateZStencilState() { ID3D11DepthStencilState *state = NULL; - if (!zstencilStateChanged) + if (!zstencilStateChanged) { return; + } for (size_t i = 0; i < zstencilStates.size(); i++) { SavedZStencilState &s = zstencilStates[i]; @@ -776,8 +800,9 @@ void gs_device::UpdateZStencilState() } } - if (!state) + if (!state) { state = AddZStencilState(); + } if (state != curDepthStencilState) { context->OMSetDepthStencilState(state, 0); @@ -791,8 +816,9 @@ void gs_device::UpdateRasterState() { ID3D11RasterizerState *state = NULL; - if (!rasterStateChanged) + if (!rasterStateChanged) { return; + } for (size_t i = 0; i < rasterStates.size(); i++) { SavedRasterState &s = rasterStates[i]; @@ -802,8 +828,9 @@ void gs_device::UpdateRasterState() } } - if (!state) + if (!state) { state = AddRasterState(); + } if (state != curRasterState) { context->RSSetState(state); @@ -817,8 +844,9 @@ void gs_device::UpdateBlendState() { ID3D11BlendState *state = NULL; - if (!blendStateChanged) + if (!blendStateChanged) { return; + } for (size_t i = 0; i < blendStates.size(); i++) { SavedBlendState &s = blendStates[i]; @@ -828,8 +856,9 @@ void gs_device::UpdateBlendState() } } - if (!state) + if (!state) { state = AddBlendState(); + } if (state != curBlendState) { float f[4] = {1.0f, 1.0f, 1.0f, 1.0f}; @@ -853,8 +882,9 @@ void gs_device::UpdateViewProjMatrix() matrix4_mul(&curViewProjMatrix, &curViewMatrix, &curProjMatrix); matrix4_transpose(&curViewProjMatrix, &curViewProjMatrix); - if (curVertexShader->viewProj) + if (curVertexShader->viewProj) { gs_shader_set_matrix4(curVertexShader->viewProj, &curViewProjMatrix); + } } void gs_device::FlushOutputViews() @@ -871,8 +901,9 @@ void gs_device::FlushOutputViews() } } ID3D11DepthStencilView *dsv = nullptr; - if (curZStencilBuffer) + if (curZStencilBuffer) { dsv = curZStencilBuffer->view; + } context->OMSetRenderTargets(1, &rtv, dsv); curFramebufferInvalidate = false; } @@ -925,25 +956,29 @@ static inline void EnumD3DAdapters(bool (*callback)(void *, const char *, uint32 UINT i; hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create DXGIFactory", hr); + } for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) { DXGI_ADAPTER_DESC desc; char name[512] = ""; hr = adapter->GetDesc(&desc); - if (FAILED(hr)) + if (FAILED(hr)) { continue; + } /* ignore Microsoft's 'basic' renderer' */ - if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) + if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) { continue; + } os_wcs_to_utf8(desc.Description, 0, name, sizeof(name)); - if (!callback(param, name, i)) + if (!callback(param, name, i)) { break; + } } } @@ -1143,8 +1178,9 @@ static ULONG GetSdrMaxNits(HMONITOR monitor) header.size = sizeof(level); header.adapterId = targetInfo.adapterId; header.id = targetInfo.id; - if (DisplayConfigGetDeviceInfo(&header) == ERROR_SUCCESS) + if (DisplayConfigGetDeviceInfo(&header) == ERROR_SUCCESS) { nits = (level.SDRWhiteLevel * 80) / 1000; + } } return nits; @@ -1160,8 +1196,9 @@ gs_monitor_color_info gs_device::GetMonitorColorInfo(HMONITOR hMonitor) } for (const std::pair &pair : monitor_to_hdr) { - if (pair.first == hMonitor) + if (pair.first == hMonitor) { return pair.second; + } } ComPtr adapter; @@ -1210,8 +1247,9 @@ static inline void LogAdapterMonitors(IDXGIAdapter1 *adapter) for (i = 0; adapter->EnumOutputs(i, &output) == S_OK; ++i) { DXGI_OUTPUT_DESC desc; - if (FAILED(output->GetDesc(&desc))) + if (FAILED(output->GetDesc(&desc))) { continue; + } unsigned refresh = 0; @@ -1336,20 +1374,23 @@ static inline void LogD3DAdapters() blog(LOG_INFO, "Available Video Adapters: "); hr = CreateDXGIFactory1(IID_PPV_ARGS(&factory)); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create DXGIFactory", hr); + } for (i = 0; factory->EnumAdapters1(i, adapter.Assign()) == S_OK; ++i) { DXGI_ADAPTER_DESC desc; char name[512] = ""; hr = adapter->GetDesc(&desc); - if (FAILED(hr)) + if (FAILED(hr)) { continue; + } /* ignore Microsoft's 'basic' renderer' */ - if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) + if (desc.VendorId == 0x1414 && desc.DeviceId == 0x8c) { continue; + } os_wcs_to_utf8(desc.Description, 0, name, sizeof(name)); blog(LOG_INFO, "\tAdapter %u: %s", i, name); @@ -1493,8 +1534,9 @@ 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); - if (device->curSwapChain->space != next_space) + 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"); } @@ -1650,8 +1692,9 @@ gs_shader_t *device_vertexshader_create(gs_device_t *device, const char *shader_ } catch (const ShaderError &error) { const char *buf = (const char *)error.errors->GetBufferPointer(); - if (error_string) + if (error_string) { *error_string = bstrdup(buf); + } blog(LOG_ERROR, "device_vertexshader_create (D3D11): " "Compile warnings/errors for %s:\n%s", @@ -1680,8 +1723,9 @@ gs_shader_t *device_pixelshader_create(gs_device_t *device, const char *shader_s } catch (const ShaderError &error) { const char *buf = (const char *)error.errors->GetBufferPointer(); - if (error_string) + if (error_string) { *error_string = bstrdup(buf); + } blog(LOG_ERROR, "device_pixelshader_create (D3D11): " "Compiler warnings/errors for %s:\n%s", @@ -1759,8 +1803,9 @@ 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]; uint32_t strides[D3D11_IA_VERTEX_INPUT_RESOURCE_SLOT_COUNT]; @@ -1788,8 +1833,9 @@ void gs_device::LoadVertexBufferData() void device_load_vertexbuffer(gs_device_t *device, gs_vertbuffer_t *vertbuffer) { - if (device->curVertexBuffer == vertbuffer) + if (device->curVertexBuffer == vertbuffer) { return; + } device->curVertexBuffer = vertbuffer; } @@ -1799,8 +1845,9 @@ void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer) DXGI_FORMAT format; ID3D11Buffer *buffer; - if (device->curIndexBuffer == indexbuffer) + if (device->curIndexBuffer == indexbuffer) { return; + } if (indexbuffer) { switch (indexbuffer->indexSize) { @@ -1826,8 +1873,9 @@ void device_load_indexbuffer(gs_device_t *device, gs_indexbuffer_t *indexbuffer) static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex, int unit, ID3D11ShaderResourceView *view) { - if (device->curTextures[unit] == tex) + if (device->curTextures[unit] == tex) { return; + } device->curTextures[unit] = tex; device->context->PSSetShaderResources(unit, 1, &view); @@ -1836,20 +1884,22 @@ static void device_load_texture_internal(gs_device_t *device, gs_texture_t *tex, void device_load_texture(gs_device_t *device, gs_texture_t *tex, int unit) { ID3D11ShaderResourceView *view; - if (tex) + if (tex) { view = tex->shaderRes; - else + } else { view = NULL; + } return device_load_texture_internal(device, tex, unit, view); } void device_load_texture_srgb(gs_device_t *device, gs_texture_t *tex, int unit) { ID3D11ShaderResourceView *view; - if (tex) + if (tex) { view = tex->shaderResLinear; - else + } else { view = NULL; + } return device_load_texture_internal(device, tex, unit, view); } @@ -1857,11 +1907,13 @@ void device_load_samplerstate(gs_device_t *device, gs_samplerstate_t *samplersta { ID3D11SamplerState *state = NULL; - if (device->curSamplers[unit] == samplerstate) + if (device->curSamplers[unit] == samplerstate) { return; + } - if (samplerstate) + if (samplerstate) { state = samplerstate->state; + } device->curSamplers[unit] = samplerstate; device->context->PSSetSamplers(unit, 1, &state); @@ -1873,8 +1925,9 @@ void device_load_vertexshader(gs_device_t *device, gs_shader_t *vertshader) ID3D11InputLayout *layout = NULL; ID3D11Buffer *constants = NULL; - if (device->curVertexShader == vertshader) + if (device->curVertexShader == vertshader) { return; + } gs_vertex_shader *vs = static_cast(vertshader); @@ -1911,8 +1964,9 @@ void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader) ID3D11Buffer *constants = NULL; ID3D11SamplerState *states[GS_MAX_TEXTURES]; - if (device->curPixelShader == pixelshader) + if (device->curPixelShader == pixelshader) { return; + } gs_pixel_shader *ps = static_cast(pixelshader); @@ -1938,9 +1992,11 @@ void device_load_pixelshader(gs_device_t *device, gs_shader_t *pixelshader) device->context->PSSetConstantBuffers(0, 1, &constants); 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]) + for (int i = 0; i < GS_MAX_TEXTURES; i++) { + if (device->curSamplers[i] && device->curSamplers[i]->state != states[i]) { device->curSamplers[i] = nullptr; + } + } } void device_load_default_samplerstate(gs_device_t *device, bool b_3d, int unit) @@ -1963,16 +2019,18 @@ gs_shader_t *device_get_pixel_shader(const gs_device_t *device) gs_texture_t *device_get_render_target(const gs_device_t *device) { - if (device->curRenderTarget == &device->curSwapChain->target) + if (device->curRenderTarget == &device->curSwapChain->target) { return NULL; + } return device->curRenderTarget; } gs_zstencil_t *device_get_zstencil_target(const gs_device_t *device) { - if (device->curZStencilBuffer == &device->curSwapChain->zs) + if (device->curZStencilBuffer == &device->curSwapChain->zs) { return NULL; + } return device->curZStencilBuffer; } @@ -1981,10 +2039,12 @@ static void device_set_render_target_internal(gs_device_t *device, gs_texture_t enum gs_color_space space) { if (device->curSwapChain) { - if (!tex) + if (!tex) { tex = &device->curSwapChain->target; - if (!zstencil) + } + if (!zstencil) { zstencil = &device->curSwapChain->zs; + } } if (device->curRenderTarget == tex && device->curZStencilBuffer == zstencil) { @@ -2025,12 +2085,14 @@ void device_set_cube_render_target(gs_device_t *device, gs_texture_t *tex, int s side = 0; } - if (!zstencil) + if (!zstencil) { 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) { blog(LOG_ERROR, "device_set_cube_render_target (D3D11): " @@ -2065,8 +2127,9 @@ bool device_framebuffer_srgb_enabled(gs_device_t *device) 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) + if (src->type != GS_TEXTURE_2D) { throw "Source texture must be a 2D texture"; + } gs_texture_2d *tex2d = static_cast(src); @@ -2076,16 +2139,18 @@ void gs_device::CopyTex(ID3D11Texture2D *dst, uint32_t dst_x, uint32_t dst_y, gs D3D11_BOX sbox; sbox.left = src_x; - if (src_w > 0) + if (src_w > 0) { sbox.right = src_x + src_w; - else + } else { sbox.right = tex2d->width - 1; + } sbox.top = src_y; - if (src_h > 0) + if (src_h > 0) { sbox.bottom = src_y + src_h; - else + } else { sbox.bottom = tex2d->height - 1; + } sbox.front = 0; sbox.back = 1; @@ -2115,15 +2180,19 @@ void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, uint32_t gs_texture_2d *src2d = static_cast(src); gs_texture_2d *dst2d = static_cast(dst); - if (!src) + if (!src) { throw "Source texture is NULL"; - if (!dst) + } + if (!dst) { throw "Destination texture is NULL"; - if (src->type != GS_TEXTURE_2D || dst->type != GS_TEXTURE_2D) + } + 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 @@ -2134,9 +2203,10 @@ void device_copy_texture_region(gs_device_t *device, gs_texture_t *dst, uint32_t uint32_t dstWidth = dst2d->width - dst_x; uint32_t dstHeight = dst2d->height - dst_y; - if (dstWidth < copyWidth || dstHeight < copyHeight) + if (dstWidth < copyWidth || dstHeight < copyHeight) { 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) { copyWidth = 0; @@ -2160,17 +2230,22 @@ void device_stage_texture(gs_device_t *device, gs_stagesurf_t *dst, gs_texture_t try { gs_texture_2d *src2d = static_cast(src); - if (!src) + if (!src) { throw "Source texture is NULL"; - if (src->type != GS_TEXTURE_2D) + } + if (src->type != GS_TEXTURE_2D) { throw "Source texture must be a 2D texture"; - if (!dst) + } + if (!dst) { throw "Destination surface is NULL"; - if (dst->format != GS_UNKNOWN && dst->format != src->format) + } + if (dst->format != GS_UNKNOWN && dst->format != src->format) { throw "Source and destination formats do not match"; - if (dst->width != src2d->width || dst->height != src2d->height) + } + if (dst->width != src2d->width || dst->height != src2d->height) { throw "Source and destination must have the same " "dimensions"; + } device->CopyTex(dst->texture, 0, 0, src, 0, 0, 0, 0); @@ -2197,23 +2272,28 @@ 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) { try { - if (!device->curVertexShader) + if (!device->curVertexShader) { throw "No vertex shader specified"; + } - if (!device->curPixelShader) + if (!device->curPixelShader) { throw "No pixel shader specified"; + } - if (!device->curVertexBuffer && (num_verts == 0)) + if (!device->curVertexBuffer && (num_verts == 0)) { throw "No vertex buffer specified"; + } - if (!device->curSwapChain && !device->curRenderTarget) + if (!device->curSwapChain && !device->curRenderTarget) { throw "No render target or swap chain to render to"; + } device->FlushOutputViews(); gs_effect_t *effect = gs_get_effect(); - if (effect) + if (effect) { gs_effect_update_params(effect); + } device->LoadVertexBufferData(); device->UpdateBlendState(); @@ -2240,12 +2320,14 @@ void device_draw(gs_device_t *device, enum gs_draw_mode draw_mode, uint32_t star } if (device->curIndexBuffer) { - if (num_verts == 0) + if (num_verts == 0) { num_verts = (uint32_t)device->curIndexBuffer->num; + } device->context->DrawIndexed(num_verts, start_vert, 0); } else { - if (num_verts == 0) + if (num_verts == 0) { num_verts = (uint32_t)device->curVertexBuffer->numVerts; + } device->context->Draw(num_verts, start_vert); } } @@ -2263,10 +2345,12 @@ void device_load_swapchain(gs_device_t *device, gs_swapchain_t *swapchain) bool is_cube = device->curRenderTarget ? (device->curRenderTarget->type == GS_TEXTURE_CUBE) : false; if (device->curSwapChain) { - if (target == &device->curSwapChain->target) + if (target == &device->curSwapChain->target) { target = NULL; - if (zs == &device->curSwapChain->zs) + } + if (zs == &device->curSwapChain->zs) { zs = NULL; + } } device->curSwapChain = swapchain; @@ -2293,13 +2377,16 @@ void device_clear(gs_device_t *device, uint32_t clear_flags, const struct vec4 * if (device->curZStencilBuffer) { uint32_t flags = 0; - if ((clear_flags & GS_CLEAR_DEPTH) != 0) + if ((clear_flags & GS_CLEAR_DEPTH) != 0) { flags |= D3D11_CLEAR_DEPTH; - if ((clear_flags & GS_CLEAR_STENCIL) != 0) + } + if ((clear_flags & GS_CLEAR_STENCIL) != 0) { flags |= D3D11_CLEAR_STENCIL; + } - if (flags && device->curZStencilBuffer->view) + if (flags && device->curZStencilBuffer->view) { device->context->ClearDepthStencilView(device->curZStencilBuffer->view, flags, depth, stencil); + } } } @@ -2341,8 +2428,9 @@ void device_flush(gs_device_t *device) void device_set_cull_mode(gs_device_t *device, enum gs_cull_mode mode) { - if (mode == device->rasterState.cullMode) + if (mode == device->rasterState.cullMode) { return; + } device->rasterState.cullMode = mode; device->rasterStateChanged = true; @@ -2355,8 +2443,9 @@ enum gs_cull_mode device_get_cull_mode(const gs_device_t *device) void device_enable_blending(gs_device_t *device, bool enable) { - if (enable == device->blendState.blendEnabled) + if (enable == device->blendState.blendEnabled) { return; + } device->blendState.blendEnabled = enable; device->blendStateChanged = true; @@ -2364,8 +2453,9 @@ void device_enable_blending(gs_device_t *device, bool enable) void device_enable_depth_test(gs_device_t *device, bool enable) { - if (enable == device->zstencilState.depthEnabled) + if (enable == device->zstencilState.depthEnabled) { return; + } device->zstencilState.depthEnabled = enable; device->zstencilStateChanged = true; @@ -2373,8 +2463,9 @@ void device_enable_depth_test(gs_device_t *device, bool enable) void device_enable_stencil_test(gs_device_t *device, bool enable) { - if (enable == device->zstencilState.stencilEnabled) + if (enable == device->zstencilState.stencilEnabled) { return; + } device->zstencilState.stencilEnabled = enable; device->zstencilStateChanged = true; @@ -2382,8 +2473,9 @@ void device_enable_stencil_test(gs_device_t *device, bool enable) void device_enable_stencil_write(gs_device_t *device, bool enable) { - if (enable == device->zstencilState.stencilWriteEnabled) + if (enable == device->zstencilState.stencilWriteEnabled) { return; + } device->zstencilState.stencilWriteEnabled = enable; device->zstencilStateChanged = true; @@ -2392,8 +2484,9 @@ 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) { if (device->blendState.redEnabled == red && device->blendState.greenEnabled == green && - device->blendState.blueEnabled == blue && device->blendState.alphaEnabled == alpha) + device->blendState.blueEnabled == blue && device->blendState.alphaEnabled == alpha) { return; + } device->blendState.redEnabled = red; device->blendState.greenEnabled = green; @@ -2405,8 +2498,9 @@ void device_enable_color(gs_device_t *device, bool red, bool green, bool blue, b 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) + device->blendState.srcFactorA == src && device->blendState.destFactorA == dest) { return; + } device->blendState.srcFactorC = src; device->blendState.destFactorC = dest; @@ -2419,8 +2513,9 @@ void device_blend_function_separate(gs_device_t *device, enum gs_blend_type src_ 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) + device->blendState.srcFactorA == src_a && device->blendState.destFactorA == dest_a) { return; + } device->blendState.srcFactorC = src_c; device->blendState.destFactorC = dest_c; @@ -2431,8 +2526,9 @@ void device_blend_function_separate(gs_device_t *device, enum gs_blend_type src_ void device_blend_op(gs_device_t *device, enum gs_blend_op_type op) { - if (device->blendState.op == op) + if (device->blendState.op == op) { return; + } device->blendState.op = op; device->blendStateChanged = true; @@ -2440,8 +2536,9 @@ 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) { - if (device->zstencilState.depthFunc == test) + if (device->zstencilState.depthFunc == test) { return; + } device->zstencilState.depthFunc = test; device->zstencilStateChanged = true; @@ -2449,8 +2546,9 @@ void device_depth_function(gs_device_t *device, enum gs_depth_test test) static inline void update_stencilside_test(gs_device_t *device, StencilSide &side, gs_depth_test test) { - if (side.test == test) + if (side.test == test) { return; + } side.test = test; device->zstencilStateChanged = true; @@ -2460,17 +2558,20 @@ void device_stencil_function(gs_device_t *device, enum gs_stencil_side side, enu { int sideVal = (int)side; - if (sideVal & GS_STENCIL_FRONT) + if (sideVal & GS_STENCIL_FRONT) { update_stencilside_test(device, device->zstencilState.stencilFront, test); - if (sideVal & GS_STENCIL_BACK) + } + if (sideVal & GS_STENCIL_BACK) { 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) { - if (side.fail == fail && side.zfail == zfail && side.zpass == zpass) + if (side.fail == fail && side.zfail == zfail && side.zpass == zpass) { return; + } side.fail = fail; side.zfail = zfail; @@ -2483,10 +2584,12 @@ void device_stencil_op(gs_device_t *device, enum gs_stencil_side side, enum gs_s { int sideVal = (int)side; - if (sideVal & GS_STENCIL_FRONT) + if (sideVal & GS_STENCIL_FRONT) { update_stencilside_op(device, device->zstencilState.stencilFront, fail, zfail, zpass); - if (sideVal & GS_STENCIL_BACK) + } + if (sideVal & GS_STENCIL_BACK) { 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) @@ -2588,8 +2691,9 @@ void device_projection_push(gs_device_t *device) void device_projection_pop(gs_device_t *device) { - if (device->projStack.empty()) + if (device->projStack.empty()) { return; + } const mat4float &mat = device->projStack.back(); memcpy(&device->curProjMatrix, &mat, sizeof(matrix4)); @@ -2598,8 +2702,9 @@ void device_projection_pop(gs_device_t *device) void gs_swapchain_destroy(gs_swapchain_t *swapchain) { - if (swapchain->device->curSwapChain == swapchain) + if (swapchain->device->curSwapChain == swapchain) { device_load_swapchain(swapchain->device, nullptr); + } delete swapchain; } @@ -2611,24 +2716,27 @@ void gs_texture_destroy(gs_texture_t *tex) uint32_t gs_texture_get_width(const gs_texture_t *tex) { - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return 0; + } return static_cast(tex)->width; } uint32_t gs_texture_get_height(const gs_texture_t *tex) { - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return 0; + } return static_cast(tex)->height; } enum gs_color_format gs_texture_get_color_format(const gs_texture_t *tex) { - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return GS_UNKNOWN; + } return static_cast(tex)->format; } @@ -2637,15 +2745,17 @@ bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize) { HRESULT hr; - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return false; + } 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); - if (FAILED(hr)) + if (FAILED(hr)) { return false; + } *ptr = (uint8_t *)map.pData; *linesize = map.RowPitch; @@ -2654,8 +2764,9 @@ bool gs_texture_map(gs_texture_t *tex, uint8_t **ptr, uint32_t *linesize) void gs_texture_unmap(gs_texture_t *tex) { - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return; + } gs_texture_2d *tex2d = static_cast(tex); tex2d->device->context->Unmap(tex2d->texture, 0); @@ -2663,8 +2774,9 @@ void gs_texture_unmap(gs_texture_t *tex) void *gs_texture_get_obj(gs_texture_t *tex) { - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return nullptr; + } gs_texture_2d *tex2d = static_cast(tex); return tex2d->texture.Get(); @@ -2677,8 +2789,9 @@ void gs_cubetexture_destroy(gs_texture_t *cubetex) uint32_t gs_cubetexture_get_size(const gs_texture_t *cubetex) { - if (cubetex->type != GS_TEXTURE_CUBE) + if (cubetex->type != GS_TEXTURE_CUBE) { return 0; + } const gs_texture_2d *tex = static_cast(cubetex); return tex->width; @@ -2686,8 +2799,9 @@ 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) { - if (cubetex->type != GS_TEXTURE_CUBE) + if (cubetex->type != GS_TEXTURE_CUBE) { return GS_UNKNOWN; + } const gs_texture_2d *tex = static_cast(cubetex); return tex->format; @@ -2749,8 +2863,9 @@ enum gs_color_format gs_stagesurface_get_color_format(const gs_stagesurf_t *stag 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; *linesize = map.RowPitch; @@ -2769,21 +2884,26 @@ void gs_zstencil_destroy(gs_zstencil_t *zstencil) void gs_samplerstate_destroy(gs_samplerstate_t *samplerstate) { - if (!samplerstate) + if (!samplerstate) { return; + } - if (samplerstate->device) - for (int i = 0; i < GS_MAX_TEXTURES; i++) - if (samplerstate->device->curSamplers[i] == samplerstate) + if (samplerstate->device) { + for (int i = 0; i < GS_MAX_TEXTURES; i++) { + if (samplerstate->device->curSamplers[i] == samplerstate) { samplerstate->device->curSamplers[i] = nullptr; + } + } + } delete samplerstate; } void gs_vertexbuffer_destroy(gs_vertbuffer_t *vertbuffer) { - if (vertbuffer && vertbuffer->device->lastVertexBuffer == vertbuffer) + if (vertbuffer && vertbuffer->device->lastVertexBuffer == vertbuffer) { vertbuffer->device->lastVertexBuffer = nullptr; + } delete vertbuffer; } @@ -2797,17 +2917,21 @@ static inline void gs_vertexbuffer_flush_internal(gs_vertbuffer_t *vertbuffer, c return; } - if (data->points) + if (data->points) { vertbuffer->FlushBuffer(vertbuffer->vertexBuffer, data->points, sizeof(vec3)); + } - if (vertbuffer->normalBuffer && data->normals) + if (vertbuffer->normalBuffer && data->normals) { vertbuffer->FlushBuffer(vertbuffer->normalBuffer, data->normals, sizeof(vec3)); + } - if (vertbuffer->tangentBuffer && data->tangents) + if (vertbuffer->tangentBuffer && data->tangents) { vertbuffer->FlushBuffer(vertbuffer->tangentBuffer, data->tangents, sizeof(vec3)); + } - if (vertbuffer->colorBuffer && data->colors) + if (vertbuffer->colorBuffer && data->colors) { vertbuffer->FlushBuffer(vertbuffer->colorBuffer, data->colors, sizeof(uint32_t)); + } for (size_t i = 0; i < num_tex; i++) { gs_tvertarray &tv = data->tvarray[i]; @@ -2839,13 +2963,15 @@ static inline void gs_indexbuffer_flush_internal(gs_indexbuffer_t *indexbuffer, { HRESULT hr; - if (!indexbuffer->dynamic) + if (!indexbuffer->dynamic) { return; + } D3D11_MAPPED_SUBRESOURCE map; hr = indexbuffer->device->context->Map(indexbuffer->indexBuffer, 0, D3D11_MAP_WRITE_DISCARD, 0, &map); - if (FAILED(hr)) + if (FAILED(hr)) { return; + } memcpy(map.pData, data, indexbuffer->num * indexbuffer->indexSize); @@ -2904,8 +3030,9 @@ bool gs_timer_get_data(gs_timer_t *timer, uint64_t *ticks) } while (hr_end == S_FALSE); const bool succeeded = SUCCEEDED(hr_begin) && SUCCEEDED(hr_end); - if (succeeded) + if (succeeded) { *ticks = end - begin; + } return succeeded; } @@ -3025,15 +3152,18 @@ extern "C" EXPORT void *gs_texture_get_dc(gs_texture_t *tex) { HDC hDC = nullptr; - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return nullptr; + } gs_texture_2d *tex2d = static_cast(tex); - if (!TextureGDICompatible(tex2d, "gs_texture_get_dc")) + if (!TextureGDICompatible(tex2d, "gs_texture_get_dc")) { return nullptr; + } - if (!tex2d->gdiSurface) + if (!tex2d->gdiSurface) { return nullptr; + } tex2d->gdiSurface->GetDC(true, &hDC); return hDC; @@ -3041,12 +3171,14 @@ extern "C" EXPORT void *gs_texture_get_dc(gs_texture_t *tex) extern "C" EXPORT void gs_texture_release_dc(gs_texture_t *tex) { - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return; + } gs_texture_2d *tex2d = static_cast(tex); - if (!TextureGDICompatible(tex2d, "gs_texture_release_dc")) + if (!TextureGDICompatible(tex2d, "gs_texture_release_dc")) { return; + } tex2d->gdiSurface->ReleaseDC(nullptr); } @@ -3084,8 +3216,9 @@ extern "C" EXPORT gs_texture_t *device_texture_open_nt_shared(gs_device_t *devic extern "C" EXPORT uint32_t device_texture_get_shared_handle(gs_texture_t *tex) { gs_texture_2d *tex2d = reinterpret_cast(tex); - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return GS_INVALID_HANDLE; + } return tex2d->isShared ? tex2d->sharedHandle : GS_INVALID_HANDLE; } @@ -3108,15 +3241,18 @@ extern "C" EXPORT gs_texture_t *device_texture_wrap_obj(gs_device_t *device, voi int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms) { gs_texture_2d *tex2d = reinterpret_cast(tex); - if (tex->type != GS_TEXTURE_2D) + if (tex->type != GS_TEXTURE_2D) { return -1; + } - if (tex2d->acquired) + if (tex2d->acquired) { return 0; + } ComQIPtr keyedMutex(tex2d->texture); - if (!keyedMutex) + if (!keyedMutex) { return -1; + } HRESULT hr = keyedMutex->AcquireSync(key, ms); if (hr == S_OK) { @@ -3132,15 +3268,18 @@ int device_texture_acquire_sync(gs_texture_t *tex, uint64_t key, uint32_t ms) 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) + if (tex->type != GS_TEXTURE_2D) { return -1; + } - if (!tex2d->acquired) + if (!tex2d->acquired) { return 0; + } ComQIPtr keyedMutex(tex2d->texture); - if (!keyedMutex) + if (!keyedMutex) { return -1; + } HRESULT hr = keyedMutex->ReleaseSync(key); if (hr == S_OK) { @@ -3154,8 +3293,9 @@ extern "C" EXPORT int device_texture_release_sync(gs_texture_t *tex, uint64_t ke 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) + if (!device->nv12Supported) { return false; + } *p_tex_y = nullptr; *p_tex_uv = nullptr; @@ -3188,8 +3328,9 @@ extern "C" EXPORT bool device_texture_create_nv12(gs_device_t *device, gs_textur 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) + if (!device->p010Supported) { return false; + } *p_tex_y = nullptr; *p_tex_uv = nullptr; diff --git a/libobs-d3d11/d3d11-subsystem.hpp b/libobs-d3d11/d3d11-subsystem.hpp index 1162ce6a704b5c..3bae9d0e8858f9 100644 --- a/libobs-d3d11/d3d11-subsystem.hpp +++ b/libobs-d3d11/d3d11-subsystem.hpp @@ -533,10 +533,12 @@ struct gs_texture_2d : gs_texture { inline void Release() { texture.Release(); - for (ComPtr &rt : renderTarget) + for (ComPtr &rt : renderTarget) { rt.Release(); - for (ComPtr &rt : renderTargetLinear) + } + for (ComPtr &rt : renderTargetLinear) { rt.Release(); + } gdiSurface.Release(); shaderRes.Release(); shaderResLinear.Release(); @@ -738,12 +740,15 @@ struct gs_vertex_shader : gs_shader { inline uint32_t NumBuffersExpected() const { uint32_t count = nTexUnits + 1; - if (hasNormals) + if (hasNormals) { count++; - if (hasColors) + } + if (hasColors) { count++; - if (hasTangents) + } + if (hasTangents) { count++; + } return count; } @@ -786,10 +791,12 @@ struct gs_pixel_shader : gs_shader { inline void GetSamplerStates(ID3D11SamplerState **states) { size_t i; - for (i = 0; i < samplers.size(); i++) + for (i = 0; i < samplers.size(); i++) { states[i] = samplers[i]->sampler.state; - for (; i < GS_MAX_TEXTURES; i++) + } + for (; i < GS_MAX_TEXTURES; i++) { states[i] = NULL; + } } gs_pixel_shader(gs_device_t *device, const char *file, const char *shaderString); diff --git a/libobs-d3d11/d3d11-texture2d.cpp b/libobs-d3d11/d3d11-texture2d.cpp index beb98ab2a40c8c..6bf12e75617b37 100644 --- a/libobs-d3d11/d3d11-texture2d.cpp +++ b/libobs-d3d11/d3d11-texture2d.cpp @@ -26,8 +26,9 @@ void gs_texture_2d::InitSRD(std::vector &srd) uint32_t actual_levels = levels; size_t curTex = 0; - if (!actual_levels) + if (!actual_levels) { actual_levels = gs_get_total_levels(width, height, 1); + } rowSizeBytes /= 8; @@ -61,8 +62,9 @@ void gs_texture_2d::BackupTexture(const uint8_t *const *data) for (uint32_t lv = 0; lv < levels; lv++) { uint32_t i = levels * t + lv; - if (!data[i]) + if (!data[i]) { break; + } uint32_t texSize = bbp * w * h / 8; @@ -70,10 +72,12 @@ void gs_texture_2d::BackupTexture(const uint8_t *const *data) subData.resize(texSize); memcpy(&subData[0], data[i], texSize); - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; + } } } } @@ -109,19 +113,23 @@ void gs_texture_2d::InitTexture(const uint8_t *const *data) td.CPUAccessFlags = isDynamic ? D3D11_CPU_ACCESS_WRITE : 0; td.Usage = isDynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; - if (type == GS_TEXTURE_CUBE) + if (type == GS_TEXTURE_CUBE) { td.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE; + } - if (isRenderTarget || isGDICompatible) + if (isRenderTarget || isGDICompatible) { td.BindFlags |= D3D11_BIND_RENDER_TARGET; + } - if (isGDICompatible) + if (isGDICompatible) { td.MiscFlags |= D3D11_RESOURCE_MISC_GDI_COMPATIBLE; + } - if ((flags & GS_SHARED_KM_TEX) != 0) + if ((flags & GS_SHARED_KM_TEX) != 0) { td.MiscFlags |= D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; - else if ((flags & GS_SHARED_TEX) != 0) + } else if ((flags & GS_SHARED_TEX) != 0) { td.MiscFlags |= D3D11_RESOURCE_MISC_SHARED; + } if (data) { BackupTexture(data); @@ -129,13 +137,15 @@ void gs_texture_2d::InitTexture(const uint8_t *const *data) } hr = device->device->CreateTexture2D(&td, data ? srd.data() : NULL, texture.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 2D texture", hr); + } if (isGDICompatible) { hr = texture->QueryInterface(__uuidof(IDXGISurface1), (void **)gdiSurface.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create GDI surface", hr); + } } if (isShared) { @@ -184,8 +194,9 @@ void gs_texture_2d::InitResourceView() } hr = device->device->CreateShaderResourceView(texture, &viewDesc, shaderRes.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create SRV", hr); + } viewDescLinear = viewDesc; viewDescLinear.Format = dxgiFormatViewLinear; @@ -194,8 +205,9 @@ void gs_texture_2d::InitResourceView() shaderResLinear = shaderRes; } else { hr = device->device->CreateShaderResourceView(texture, &viewDescLinear, shaderResLinear.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear SRV", hr); + } } } @@ -209,15 +221,17 @@ void gs_texture_2d::InitRenderTargets() rtv.Texture2D.MipSlice = 0; hr = device->device->CreateRenderTargetView(texture, &rtv, renderTarget[0].Assign()); - if (FAILED(hr)) + 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()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear RTV", hr); + } } } else { D3D11_RENDER_TARGET_VIEW_DESC rtv; @@ -229,16 +243,18 @@ 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()); - if (FAILED(hr)) + 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()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear cube RTV", hr); + } } } } @@ -267,8 +283,9 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t width, uint32_t heigh InitTexture(data); InitResourceView(); - if (isRenderTarget) + if (isRenderTarget) { InitRenderTargets(); + } } gs_texture_2d::gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12tex, uint32_t flags_) @@ -298,8 +315,9 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, ID3D11Texture2D *nv12tex, uint this->dxgiFormatViewLinear = dxgi_format; InitResourceView(); - if (isRenderTarget) + if (isRenderTarget) { InitRenderTargets(); + } } gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t handle, bool ntHandle) @@ -317,8 +335,9 @@ gs_texture_2d::gs_texture_2d(gs_device_t *device, uint32_t handle, bool ntHandle (void **)texture.Assign()); } - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to open shared 2D texture", hr); + } texture->GetDesc(&td); diff --git a/libobs-d3d11/d3d11-texture3d.cpp b/libobs-d3d11/d3d11-texture3d.cpp index 87aaa29f4cc630..b0ca490b4e985c 100644 --- a/libobs-d3d11/d3d11-texture3d.cpp +++ b/libobs-d3d11/d3d11-texture3d.cpp @@ -24,8 +24,9 @@ void gs_texture_3d::InitSRD(std::vector &srd) uint32_t sliceSizeBytes = height * rowSizeBits / 8; uint32_t actual_levels = levels; - if (!actual_levels) + if (!actual_levels) { actual_levels = gs_get_total_levels(width, height, depth); + } uint32_t newRowSize = rowSizeBits / 8; uint32_t newSlizeSize = sliceSizeBytes; @@ -52,8 +53,9 @@ void gs_texture_3d::BackupTexture(const uint8_t *const *data) const uint32_t bbp = gs_get_format_bpp(format); for (uint32_t i = 0; i < levels; i++) { - if (!data[i]) + if (!data[i]) { break; + } const uint32_t texSize = bbp * w * h * d / 8; this->data[i].resize(texSize); @@ -61,12 +63,15 @@ void gs_texture_3d::BackupTexture(const uint8_t *const *data) std::vector &subData = this->data[i]; memcpy(&subData[0], data[i], texSize); - if (w > 1) + if (w > 1) { w /= 2; - if (h > 1) + } + if (h > 1) { h /= 2; - if (d > 1) + } + if (d > 1) { d /= 2; + } } } @@ -100,13 +105,15 @@ void gs_texture_3d::InitTexture(const uint8_t *const *data) td.CPUAccessFlags = isDynamic ? D3D11_CPU_ACCESS_WRITE : 0; td.Usage = isDynamic ? D3D11_USAGE_DYNAMIC : D3D11_USAGE_DEFAULT; - if (type == GS_TEXTURE_CUBE) + if (type == GS_TEXTURE_CUBE) { td.MiscFlags |= D3D11_RESOURCE_MISC_TEXTURECUBE; + } - if ((flags & GS_SHARED_KM_TEX) != 0) + if ((flags & GS_SHARED_KM_TEX) != 0) { td.MiscFlags |= D3D11_RESOURCE_MISC_SHARED_KEYEDMUTEX; - else if ((flags & GS_SHARED_TEX) != 0) + } else if ((flags & GS_SHARED_TEX) != 0) { td.MiscFlags |= D3D11_RESOURCE_MISC_SHARED; + } if (data) { BackupTexture(data); @@ -114,8 +121,9 @@ void gs_texture_3d::InitTexture(const uint8_t *const *data) } hr = device->device->CreateTexture3D(&td, data ? srd.data() : NULL, texture.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 3D texture", hr); + } if (isShared) { ComPtr dxgi_res; @@ -159,8 +167,9 @@ void gs_texture_3d::InitResourceView() viewDesc.Texture3D.MipLevels = genMipmaps || !levels ? -1 : levels; hr = device->device->CreateShaderResourceView(texture, &viewDesc, shaderRes.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create 3D SRV", hr); + } viewDescLinear = viewDesc; viewDescLinear.Format = dxgiFormatViewLinear; @@ -169,8 +178,9 @@ void gs_texture_3d::InitResourceView() shaderResLinear = shaderRes; } else { hr = device->device->CreateShaderResourceView(texture, &viewDescLinear, shaderResLinear.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create linear 3D SRV", hr); + } } } @@ -202,8 +212,9 @@ gs_texture_3d::gs_texture_3d(gs_device_t *device, uint32_t handle) { HRESULT hr; hr = device->device->OpenSharedResource((HANDLE)(uintptr_t)handle, IID_PPV_ARGS(texture.Assign())); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to open shared 3D texture", hr); + } texture->GetDesc(&td); diff --git a/libobs-d3d11/d3d11-vertexbuffer.cpp b/libobs-d3d11/d3d11-vertexbuffer.cpp index ba334a5a555f2a..585e26db556e8f 100644 --- a/libobs-d3d11/d3d11-vertexbuffer.cpp +++ b/libobs-d3d11/d3d11-vertexbuffer.cpp @@ -37,8 +37,9 @@ void gs_vertex_buffer::FlushBuffer(ID3D11Buffer *buffer, void *array, size_t ele 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); @@ -49,12 +50,15 @@ UINT gs_vertex_buffer::MakeBufferList(gs_vertex_shader *shader, ID3D11Buffer **b UINT numBuffers = 0; PushBuffer(&numBuffers, buffers, strides, vertexBuffer, sizeof(vec3), "point"); - if (shader->hasNormals) + if (shader->hasNormals) { PushBuffer(&numBuffers, buffers, strides, normalBuffer, sizeof(vec3), "normal"); - if (shader->hasColors) + } + if (shader->hasColors) { PushBuffer(&numBuffers, buffers, strides, colorBuffer, sizeof(uint32_t), "color"); - if (shader->hasTangents) + } + if (shader->hasTangents) { 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]; @@ -87,30 +91,36 @@ void gs_vertex_buffer::InitBuffer(const size_t elementSize, const size_t numVert srd.pSysMem = array; hr = device->device->CreateBuffer(&bd, &srd, buffer); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create buffer", hr); + } } void gs_vertex_buffer::BuildBuffers() { InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->points, &vertexBuffer); - if (vbd.data->normals) + if (vbd.data->normals) { InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->normals, &normalBuffer); + } - if (vbd.data->tangents) + if (vbd.data->tangents) { InitBuffer(sizeof(vec3), vbd.data->num, vbd.data->tangents, &tangentBuffer); + } - if (vbd.data->colors) + if (vbd.data->colors) { 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; - if (tverts->width != 2 && tverts->width != 4) + if (tverts->width != 2 && tverts->width != 4) { throw "Invalid texture vertex size specified"; - if (!tverts->array) + } + if (!tverts->array) { throw "No texture vertices specified"; + } ComPtr buffer; InitBuffer(tverts->width * sizeof(float), vbd.data->num, tverts->array, &buffer); @@ -126,10 +136,12 @@ gs_vertex_buffer::gs_vertex_buffer(gs_device_t *device, struct gs_vb_data *data, vbd(data), numVerts(data->num) { - if (!data->num) + if (!data->num) { throw "Cannot initialize vertex buffer with 0 vertices"; - if (!data->points) + } + if (!data->points) { throw "No points specified for vertex buffer"; + } BuildBuffers(); } diff --git a/libobs-d3d11/d3d11-zstencilbuffer.cpp b/libobs-d3d11/d3d11-zstencilbuffer.cpp index 97cf836688c16d..a4a6925ce0b02f 100644 --- a/libobs-d3d11/d3d11-zstencilbuffer.cpp +++ b/libobs-d3d11/d3d11-zstencilbuffer.cpp @@ -32,16 +32,18 @@ void gs_zstencil_buffer::InitBuffer() td.Usage = D3D11_USAGE_DEFAULT; hr = device->device->CreateTexture2D(&td, NULL, texture.Assign()); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create depth stencil texture", hr); + } memset(&dsvd, 0, sizeof(dsvd)); dsvd.Format = dxgiFormat; dsvd.ViewDimension = D3D11_DSV_DIMENSION_TEXTURE2D; hr = device->device->CreateDepthStencilView(texture, &dsvd, view.Assign()); - if (FAILED(hr)) + 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) diff --git a/libobs-winrt/winrt-capture.cpp b/libobs-winrt/winrt-capture.cpp index a31414f47c9942..ea0335fcc7b597 100644 --- a/libobs-winrt/winrt-capture.cpp +++ b/libobs-winrt/winrt-capture.cpp @@ -80,11 +80,13 @@ static DXGI_FORMAT get_pixel_format(HWND window, HMONITOR monitor, BOOL force_sd { static constexpr DXGI_FORMAT sdr_format = DXGI_FORMAT_B8G8R8A8_UNORM; - if (force_sdr) + if (force_sdr) { return sdr_format; + } - if (window) + if (window) { monitor = MonitorFromWindow(window, MONITOR_DEFAULTTONEAREST); + } return (monitor && gs_is_monitor_hdr(monitor)) ? DXGI_FORMAT_R16G16B16A16_FLOAT : sdr_format; } @@ -249,8 +251,9 @@ winrt_capture_create_item(IGraphicsCaptureItemInterop *const interop_factory, HW const HRESULT hr = interop_factory->CreateForWindow( window, winrt::guid_of(), reinterpret_cast(winrt::put_abi(item))); - if (FAILED(hr)) + 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, winrt::to_string(err.message()).c_str()); @@ -264,8 +267,9 @@ winrt_capture_create_item(IGraphicsCaptureItemInterop *const interop_factory, HW const HRESULT hr = interop_factory->CreateForMonitor( monitor, winrt::guid_of(), reinterpret_cast(winrt::put_abi(item))); - if (FAILED(hr)) + if (FAILED(hr)) { blog(LOG_ERROR, "CreateForMonitor (0x%08X)", hr); + } } catch (winrt::hresult_error &err) { blog(LOG_ERROR, "CreateForMonitor (0x%08X): %s", err.code().value, winrt::to_string(err.message()).c_str()); @@ -286,17 +290,20 @@ static void winrt_capture_device_loss_rebuild(void *device_void, void *data) auto interop_factory = activation_factory.as(); winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = winrt_capture_create_item(interop_factory.get(), capture->window, capture->monitor); - if (!item) + if (!item) { return; + } ID3D11Device *const d3d_device = (ID3D11Device *)device_void; ComPtr dxgi_device; - if (FAILED(d3d_device->QueryInterface(&dxgi_device))) + if (FAILED(d3d_device->QueryInterface(&dxgi_device))) { 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(); @@ -313,8 +320,9 @@ static void winrt_capture_device_loss_rebuild(void *device_void, void *data) session.IsBorderRequired(false); } - if (winrt_capture_cursor_toggle_supported()) + if (winrt_capture_cursor_toggle_supported()) { session.IsCursorCaptureEnabled(capture->capture_cursor && capture->cursor_visible); + } capture->item = item; capture->device = device; @@ -358,8 +366,9 @@ try { auto interop_factory = activation_factory.as(); winrt::Windows::Graphics::Capture::GraphicsCaptureItem item = winrt_capture_create_item(interop_factory.get(), window, monitor); - if (!item) + if (!item) { return nullptr; + } const winrt::Windows::Graphics::DirectX::Direct3D11::IDirect3DDevice device = inspectable.as(); @@ -379,8 +388,9 @@ try { /* disable cursor capture if possible since ours performs better */ const BOOL cursor_toggle_supported = winrt_capture_cursor_toggle_supported(); - if (cursor_toggle_supported) + if (cursor_toggle_supported) { session.IsCursorCaptureEnabled(cursor); + } struct winrt_capture *capture = new winrt_capture{}; capture->window = window; @@ -457,8 +467,9 @@ extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture) capture->closed.revoke(); try { - if (capture->frame_pool) + if (capture->frame_pool) { 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()); @@ -467,8 +478,9 @@ extern "C" EXPORT void winrt_capture_free(struct winrt_capture *capture) } try { - if (capture->session) + if (capture->session) { 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()); diff --git a/libobs/obs.hpp b/libobs/obs.hpp index 104314c41d47e8..2c63ed62d349f2 100644 --- a/libobs/obs.hpp +++ b/libobs/obs.hpp @@ -242,16 +242,18 @@ template class OBSPtr { inline OBSPtr &operator=(T obj_) { - if (obj_ != obj) + if (obj_ != obj) { destroy(obj); + } obj = obj_; return *this; } inline OBSPtr &operator=(const OBSPtr &) = delete; inline OBSPtr &operator=(OBSPtr &&other) { - if (obj) + if (obj) { destroy(obj); + } obj = other.obj; other.obj = nullptr; return *this; diff --git a/libobs/util/profiler.hpp b/libobs/util/profiler.hpp index f9ba14944c38a0..dc4426b9f3ed50 100644 --- a/libobs/util/profiler.hpp +++ b/libobs/util/profiler.hpp @@ -18,8 +18,9 @@ struct ScopeProfiler { void Stop() { - if (!enabled) + if (!enabled) { return; + } profile_end(name); enabled = false; diff --git a/libobs/util/util.hpp b/libobs/util/util.hpp index c59da282a105e3..f19b34026ebdf7 100644 --- a/libobs/util/util.hpp +++ b/libobs/util/util.hpp @@ -146,8 +146,9 @@ class TextLookup { inline const char *GetString(const char *lookupVal) const { const char *out; - if (!text_lookup_getstr(lookup, lookupVal, &out)) + if (!text_lookup_getstr(lookup, lookupVal, &out)) { return lookupVal; + } return out; } diff --git a/libobs/util/windows/CoTaskMemPtr.hpp b/libobs/util/windows/CoTaskMemPtr.hpp index 91c92eed23ea79..29101a534b5e11 100644 --- a/libobs/util/windows/CoTaskMemPtr.hpp +++ b/libobs/util/windows/CoTaskMemPtr.hpp @@ -21,8 +21,9 @@ template class CoTaskMemPtr { inline void Clear() { - if (ptr) + if (ptr) { CoTaskMemFree(ptr); + } } public: diff --git a/libobs/util/windows/ComPtr.hpp b/libobs/util/windows/ComPtr.hpp index fc7a8402da5768..d1ec06cf5ad462 100644 --- a/libobs/util/windows/ComPtr.hpp +++ b/libobs/util/windows/ComPtr.hpp @@ -30,17 +30,20 @@ template class ComPtr { inline void Kill() { - if (ptr) + if (ptr) { ptr->Release(); + } } inline void Replace(T *p) { if (ptr != p) { - if (p) + if (p) { p->AddRef(); - if (ptr) + } + if (ptr) { ptr->Release(); + } ptr = p; } } @@ -49,13 +52,15 @@ template class ComPtr { inline ComPtr() : ptr(nullptr) {} inline ComPtr(T *p) : ptr(p) { - if (ptr) + if (ptr) { ptr->AddRef(); + } } inline ComPtr(const ComPtr &c) : ptr(c.ptr) { - if (ptr) + if (ptr) { ptr->AddRef(); + } } inline ComPtr(ComPtr &&c) noexcept : ptr(c.ptr) { c.ptr = nullptr; } template inline ComPtr(ComPtr &&c) noexcept : ptr(c.Detach()) {} @@ -110,8 +115,9 @@ template class ComPtr { inline void CopyTo(T **out) { if (out) { - if (ptr) + if (ptr) { ptr->AddRef(); + } *out = ptr; } } @@ -120,8 +126,9 @@ template class ComPtr { { ULONG ref; - if (!ptr) + if (!ptr) { return 0; + } ref = ptr->Release(); ptr = nullptr; return ref; diff --git a/libobs/util/windows/WinHandle.hpp b/libobs/util/windows/WinHandle.hpp index f652bdfc56014a..2c923604034d78 100644 --- a/libobs/util/windows/WinHandle.hpp +++ b/libobs/util/windows/WinHandle.hpp @@ -21,8 +21,9 @@ class WinHandle { inline void Clear() { - if (handle && handle != INVALID_HANDLE_VALUE) + if (handle && handle != INVALID_HANDLE_VALUE) { CloseHandle(handle); + } } public: @@ -52,8 +53,9 @@ class WinModule { inline void Clear() { - if (handle) + if (handle) { FreeLibrary(handle); + } } public: diff --git a/plugins/aja/aja-card-manager.cpp b/plugins/aja/aja-card-manager.cpp index f260dc339f162d..f957fedf6f0942 100644 --- a/plugins/aja/aja-card-manager.cpp +++ b/plugins/aja/aja-card-manager.cpp @@ -144,8 +144,9 @@ std::string CardEntry::GetDisplayName() const std::ostringstream oss; oss << mCard->GetIndexNumber() << " - " << mCard->GetModelName(); const std::string &serial = GetSerial(); - if (!serial.empty()) + if (!serial.empty()) { oss << " (" << serial << ")"; + } return oss.str(); } @@ -157,8 +158,9 @@ std::string CardEntry::GetDisplayName() const std::string CardEntry::GetSerial() const { std::string serial; - if (mCard) + if (mCard) { mCard->GetSerialNumberString(serial); + } return serial; } @@ -166,8 +168,9 @@ std::string CardEntry::GetSerial() const NTV2DeviceID CardEntry::GetDeviceID() const { NTV2DeviceID id = DEVICE_ID_NOTFOUND; - if (mCard) + if (mCard) { id = mCard->GetDeviceID(); + } return id; } @@ -255,11 +258,13 @@ bool CardEntry::InputSelectionReady(IOSelection io, NTV2DeviceID id, const std:: size_t channelsReady = 0; for (auto &&src : inputSources) { auto channel = NTV2InputSourceToChannel(src); - if (ChannelReady(channel, owner)) + if (ChannelReady(channel, owner)) { channelsReady++; + } } - if (channelsReady == inputSources.size()) + if (channelsReady == inputSources.size()) { return true; + } } } @@ -288,11 +293,13 @@ bool CardEntry::OutputSelectionReady(IOSelection io, NTV2DeviceID id, const std: size_t channelsReady = 0; for (auto &&dst : outputDests) { auto channel = NTV2OutputDestinationToChannel(dst); - if (ChannelReady(channel, owner)) + if (ChannelReady(channel, owner)) { channelsReady++; + } } - if (channelsReady == outputDests.size()) + if (channelsReady == outputDests.size()) { return true; + } } } @@ -452,8 +459,9 @@ bool CardEntry::UpdateChannelOwnerName(const std::string &oldName, const std::st bool CardEntry::isAutoCirculateRunning(NTV2Channel chan) { - if (!mCard) + if (!mCard) { return false; + } AUTOCIRCULATE_STATUS acStatus; if (mCard->AutoCirculateGetStatus(chan, acStatus)) { @@ -499,8 +507,9 @@ void CardManager::EnumerateCards() // New Card Entry if (mCardEntries.find(cardID) == mCardEntries.end()) { CardEntryPtr cardEntry = std::make_shared(iter.deviceIndex, cardID); - if (cardEntry && cardEntry->Initialize()) + 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]; @@ -508,8 +517,9 @@ void CardManager::EnumerateCards() if (currEntry->GetCardIndex() != iter.deviceIndex) { mCardEntries.erase(cardID); CardEntryPtr cardEntry = std::make_shared(iter.deviceIndex, cardID); - if (cardEntry && cardEntry->Initialize()) + if (cardEntry && cardEntry->Initialize()) { mCardEntries.emplace(cardID, cardEntry); + } } } } @@ -525,8 +535,9 @@ size_t CardManager::NumCardEntries() const CNTV2Card *CardManager::GetCard(const std::string &cardID) { auto entry = GetCardEntry(cardID); - if (entry) + if (entry) { return entry->GetCard(); + } return nullptr; } @@ -534,8 +545,9 @@ const CardEntryPtr CardManager::GetCardEntry(const std::string &cardID) const { const std::lock_guard lock(mMutex); for (const auto &entry : mCardEntries) { - if (entry.second && entry.second->GetCardID() == cardID) + if (entry.second && entry.second->GetCardID() == cardID) { return entry.second; + } } return nullptr; } diff --git a/plugins/aja/aja-common.cpp b/plugins/aja/aja-common.cpp index 7e11a9be72a882..781af98e1154bc 100644 --- a/plugins/aja/aja-common.cpp +++ b/plugins/aja/aja-common.cpp @@ -20,8 +20,9 @@ void filter_io_selection_input_list(const std::string &cardID, const std::string NTV2DeviceID deviceID = DEVICE_ID_NOTFOUND; CNTV2Card *card = cardEntry->GetCard(); - if (card) + if (card) { deviceID = card->GetDeviceID(); + } // 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++) { @@ -50,8 +51,9 @@ void filter_io_selection_output_list(const std::string &cardID, const std::strin NTV2DeviceID deviceID = DEVICE_ID_NOTFOUND; CNTV2Card *card = cardEntry->GetCard(); - if (card) + if (card) { deviceID = card->GetDeviceID(); + } // 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++) { @@ -77,8 +79,9 @@ void populate_io_selection_input_list(const std::string &cardID, const std::stri for (auto i = 0; i < static_cast(IOSelection::NumIOSelections); i++) { auto ioSelect = static_cast(i); - if (ioSelect == IOSelection::AnalogIn) + if (ioSelect == IOSelection::AnalogIn) { continue; + } if (aja::DeviceCanDoIOSelectionIn(deviceID, ioSelect)) { obs_property_list_add_int(list, aja::IOSelectionToString(ioSelect).c_str(), static_cast(ioSelect)); @@ -100,8 +103,9 @@ void populate_io_selection_output_list(const std::string &cardID, const std::str } else { 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(), @@ -131,12 +135,14 @@ void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, NTV if (NTV2DeviceCanDo4KVideo(deviceID)) { orderedStandards.push_back(NTV2_STANDARD_3840i); orderedStandards.push_back(NTV2_STANDARD_3840x2160p); - if (want4KHFR) + if (want4KHFR) { orderedStandards.push_back(NTV2_STANDARD_3840HFR); + } orderedStandards.push_back(NTV2_STANDARD_4096i); orderedStandards.push_back(NTV2_STANDARD_4096x2160p); - if (want4KHFR) + if (want4KHFR) { orderedStandards.push_back(NTV2_STANDARD_4096HFR); + } } aja::GetSortedVideoFormats(deviceID, orderedStandards, videoFormats); @@ -144,8 +150,9 @@ void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, NTV bool addFormat = true; // Filter formats by framerate family if specified - if (genlockFormat != NTV2_FORMAT_UNKNOWN) + if (genlockFormat != NTV2_FORMAT_UNKNOWN) { addFormat = IsMultiFormatCompatible(genlockFormat, vf); + } struct obs_video_info ovi; if (matchFPS && obs_get_video_info(&ovi)) { @@ -155,8 +162,9 @@ void populate_video_format_list(NTV2DeviceID deviceID, obs_property_t *list, NTV GetFramesPerSecond(frameRate, fpsNum, fpsDen); uint32_t obsFrameTime = 1000000 * ovi.fps_den / ovi.fps_num; uint32_t ajaFrameTime = 1000000 * fpsDen / fpsNum; - if (obsFrameTime != ajaFrameTime) + if (obsFrameTime != ajaFrameTime) { addFormat = false; + } } if (addFormat) { @@ -184,12 +192,14 @@ void populate_sdi_transport_list(obs_property_t *list, NTV2DeviceID deviceID, bo 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 (!NTV2DeviceCanDo12GSDI(deviceID)) + if (!NTV2DeviceCanDo12GSDI(deviceID)) { continue; + } } // Disabling 12G in Output plugin until AJA 4K HFR bug is fixed - if (!capture && sdi_trx == SDITransport::SDI12G) + if (!capture && sdi_trx == SDITransport::SDI12G) { continue; + } obs_property_list_add_int(list, aja::SDITransportToString(sdi_trx).c_str(), static_cast(sdi_trx)); } @@ -284,8 +294,9 @@ video_format AJAPixelFormatToOBSVideoFormat(NTV2PixelFormat pf) void GetSortedVideoFormats(NTV2DeviceID id, const VideoStandardList &standards, VideoFormatList &videoFormats) { - if (standards.empty()) + if (standards.empty()) { return; + } VideoFormatMap videoFormatMap; @@ -354,8 +365,9 @@ NTV2Channel WidgetIDToChannel(NTV2WidgetID id) { #if AJA_NTV2_SDK_VERSION_MAJOR <= 16 && AJA_NTV2_SDK_VERSION_MINOR <= 2 // Workaround for bug in NTV2 SDK <= 16.2 where NTV2_WgtSDIMonOut1 maps incorrectly to NTV2_CHANNEL1. - if (id == NTV2_WgtSDIMonOut1) + if (id == NTV2_WgtSDIMonOut1) { return NTV2_CHANNEL5; + } #endif return CNTV2SignalRouter::WidgetIDToChannel(id); } @@ -371,8 +383,9 @@ uint32_t CardNumFramestores(NTV2DeviceID id) uint32_t CardNumAudioSystems(NTV2DeviceID id) { - if (id == DEVICE_ID_KONALHI || id == DEVICE_ID_KONALHEPLUS) + if (id == DEVICE_ID_KONALHI || id == DEVICE_ID_KONALHEPLUS) { return 2; + } return NTV2DeviceGetNumAudioSystems(id); } @@ -408,16 +421,18 @@ bool CardCanDo1xSDI12G(NTV2DeviceID id) // Check for 3G level-B SDI on the wire. bool Is3GLevelB(CNTV2Card *card, NTV2Channel channel) { - if (!card) + if (!card) { return false; + } bool levelB = false; auto deviceID = card->GetDeviceID(); UWord channelIndex = static_cast(channel); if (NTV2DeviceCanDo3GIn(deviceID, channelIndex) || NTV2DeviceCanDo12GIn(deviceID, channelIndex)) { - if (!card->GetSDIInput3GbPresent(levelB, channel)) + if (!card->GetSDIInput3GbPresent(levelB, channel)) { return false; + } } return levelB; @@ -796,12 +811,14 @@ bool DeviceCanDoIOSelectionIn(NTV2DeviceID id, IOSelection io) size_t canDo = 0; if (numSrcs > 0) { for (auto &&inp : inputSources) { - if (NTV2DeviceCanDoInputSource(id, inp)) + if (NTV2DeviceCanDoInputSource(id, inp)) { canDo++; + } } - if (canDo == numSrcs) + if (canDo == numSrcs) { return true; + } } } return false; @@ -816,12 +833,14 @@ bool DeviceCanDoIOSelectionOut(NTV2DeviceID id, IOSelection io) size_t canDo = 0; if (numOuts > 0) { for (auto &&out : outputDests) { - if (NTV2DeviceCanDoOutputDestination(id, out)) + if (NTV2DeviceCanDoOutputDestination(id, out)) { canDo++; + } } - if (canDo == numOuts) + if (canDo == numOuts) { return true; + } } } return false; @@ -879,11 +898,13 @@ bool IsSDIFourWireIOSelection(IOSelection io) bool IsMonitorOutputSelection(NTV2DeviceID id, IOSelection io) { - if (CardCanDoSDIMonitorOutput(id) && io == IOSelection::SDI5) + if (CardCanDoSDIMonitorOutput(id) && io == IOSelection::SDI5) { return true; + } - if (CardCanDoHDMIMonitorOutput(id) && io == IOSelection::HDMIMonitorOut) + if (CardCanDoHDMIMonitorOutput(id) && io == IOSelection::HDMIMonitorOut) { return true; + } return false; } @@ -998,17 +1019,19 @@ VPIDStandard DetermineVPIDStandard(IOSelection io, NTV2VideoFormat vf, NTV2Pixel } else if (aja::IsSDITwoWireIOSelection(io)) { if (is_rgb) { if (standard == NTV2_STANDARD_720) { - if (trx == SDITransport::SDI3Ga) + 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::HDDualLink) { vpid = VPIDStandard_1080_DualLink; - } else if (trx == SDITransport::SDI3Ga) + } else if (trx == SDITransport::SDI3Ga) { vpid = VPIDStandard_1080_Dual_3Ga; - else if (trx == SDITransport::SDI3Gb) + } else if (trx == SDITransport::SDI3Gb) { vpid = VPIDStandard_1080_Dual_3Gb; + } } } else { if (IsStandard1080p(standard) && trx == SDITransport::HDDualLink) { diff --git a/plugins/aja/aja-output.cpp b/plugins/aja/aja-output.cpp index 91d0ad62e6cdd0..3b638f384c9ad7 100644 --- a/plugins/aja/aja-output.cpp +++ b/plugins/aja/aja-output.cpp @@ -139,10 +139,12 @@ AJAOutput::AJAOutput(CNTV2Card *card, const std::string &cardID, const std::stri AJAOutput::~AJAOutput() { - if (mVideoQueue) + if (mVideoQueue) { mVideoQueue.reset(); - if (mAudioQueue) + } + if (mAudioQueue) { mAudioQueue.reset(); + } } CNTV2Card *AJAOutput::GetCard() @@ -230,10 +232,12 @@ void AJAOutput::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2 { NTV2VideoFormat vid_fmt = vf; NTV2PixelFormat pix_fmt = pf; - if (vid_fmt == NTV2_FORMAT_UNKNOWN) + if (vid_fmt == NTV2_FORMAT_UNKNOWN) { vid_fmt = NTV2_FORMAT_720p_5994; - if (pix_fmt == NTV2_FBF_INVALID) + } + if (pix_fmt == NTV2_FBF_INVALID) { pix_fmt = kDefaultAJAPixelFormat; + } NTV2FormatDesc fd(vid_fmt, pix_fmt, NTV2_VANCMODE_OFF); auto bufSize = fd.GetTotalRasterBytes(); @@ -334,8 +338,9 @@ void AJAOutput::DMAAudioFromQueue(NTV2AudioSystem audioSys, uint32_t channels, u AudioFrames &af = mAudioQueue->front(); size_t sizeLeft = af.size - af.offset; - if (!mFirstAudioTS) + if (!mFirstAudioTS) { mFirstAudioTS = af.frames.timestamp; + } mLastAudioTS = af.frames.timestamp; if (sizeLeft == 0) { @@ -413,8 +418,9 @@ void AJAOutput::DMAVideoFromQueue() auto &vf = mVideoQueue->front(); auto data = vf.frame.data[0]; - if (!mFirstVideoTS) + if (!mFirstVideoTS) { mFirstVideoTS = vf.frame.timestamp; + } mLastVideoTS = vf.frame.timestamp; mVideoDelay = (((int64_t)mWriteCardFrame + (int64_t)mNumCardFrames - (int64_t)mPlayCardFrame) % @@ -436,18 +442,21 @@ void AJAOutput::DMAVideoFromQueue() if (writeFrame) { // find the next buffer uint32_t writeCardFrame = mWriteCardFrame + 1; - if (writeCardFrame > mLastCardFrame) + if (writeCardFrame > mLastCardFrame) { writeCardFrame = mFirstCardFrame; + } // use the next buffer if available - if (writeCardFrame != mPlayCardFrame) + if (writeCardFrame != mPlayCardFrame) { mWriteCardFrame = writeCardFrame; + } mVideoWriteFrames++; auto result = mCard->DMAWriteFrame(mWriteCardFrame, reinterpret_cast(data), (ULWord)vf.size); - if (!result) + if (!result) { blog(LOG_DEBUG, "AJAOutput::DMAVideoFromQueue: Failed to write video frame!"); + } } if (freeFrame) { @@ -502,8 +511,9 @@ uint32_t AJAOutput::get_card_play_count() mCard->GetInterruptCount(interrupt, intCount); mCard->GetOutputFieldID(channel, fieldID); } - if (fieldID == NTV2_FIELD1) + if (fieldID == NTV2_FIELD1) { intCount--; + } frameCount = intCount / 2; } @@ -641,8 +651,9 @@ void AJAOutput::OutputThread(AJAThread *thread, void *ctx) if (ajaOutput->mPlayCardFrame != ajaOutput->mWriteCardFrame) { uint32_t playCardNext = ajaOutput->mPlayCardFrame + 1; - if (playCardNext > ajaOutput->mLastCardFrame) + if (playCardNext > ajaOutput->mLastCardFrame) { playCardNext = ajaOutput->mFirstCardFrame; + } if (playCardNext != ajaOutput->mWriteCardFrame) { ajaOutput->mPlayCardNext = playCardNext; @@ -765,12 +776,14 @@ void populate_output_device_list(obs_property_t *list) auto &cardManager = aja::CardManager::Instance(); cardManager.EnumerateCards(); for (auto &iter : cardManager.GetCardEntries()) { - if (!iter.second) + if (!iter.second) { continue; + } CNTV2Card *card = iter.second->GetCard(); - if (!card) + if (!card) { continue; + } NTV2DeviceID deviceID = card->GetDeviceID(); @@ -793,8 +806,9 @@ bool aja_output_device_changed(void *data, obs_properties_t *props, obs_property populate_output_device_list(list); const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return false; + } const char *outputID = obs_data_get_string(settings, kUIPropAJAOutputID.id); auto &cardManager = aja::CardManager::Instance(); @@ -847,8 +861,9 @@ bool aja_output_dest_changed(obs_properties_t *props, obs_property_t *list, obs_ blog(LOG_DEBUG, "AJA Output Dest Changed"); const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return false; + } auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); @@ -921,8 +936,9 @@ static void *aja_output_create(obs_data_t *settings, obs_output_t *output) blog(LOG_INFO, "Creating AJA Output..."); const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return nullptr; + } const char *outputID = obs_data_get_string(settings, kUIPropAJAOutputID.id); @@ -1138,8 +1154,9 @@ static void aja_output_stop(void *data, uint64_t ts) static void aja_output_raw_video(void *data, struct video_data *frame) { auto ajaOutput = (AJAOutput *)data; - if (!ajaOutput) + if (!ajaOutput) { return; + } auto outputProps = ajaOutput->GetOutputProps(); auto rasterBytes = outputProps.FormatDesc().GetTotalRasterBytes(); @@ -1149,8 +1166,9 @@ static void aja_output_raw_video(void *data, struct video_data *frame) static void aja_output_raw_audio(void *data, struct audio_data *frames) { auto ajaOutput = (AJAOutput *)data; - if (!ajaOutput) + if (!ajaOutput) { return; + } auto outputProps = ajaOutput->GetOutputProps(); auto audioSize = outputProps.AudioSize(); diff --git a/plugins/aja/aja-presets.cpp b/plugins/aja/aja-presets.cpp index d828b48c627b3d..1ff8ad51b58814 100644 --- a/plugins/aja/aja-presets.cpp +++ b/plugins/aja/aja-presets.cpp @@ -13,8 +13,9 @@ RoutingConfigurator::RoutingConfigurator() void RoutingConfigurator::AddPreset(const std::string &name, const RoutingPreset &preset) { - if (m_presets.find(name) != m_presets.end()) + if (m_presets.find(name) != m_presets.end()) { return; + } m_presets.insert(RoutingPresetPair{name, preset}); } @@ -1778,8 +1779,9 @@ void RoutingConfigurator::build_preset_table() false, false}}, }; - for (auto &&rp : kRoutingPresets) + for (auto &&rp : kRoutingPresets) { AddPreset(std::move(rp.first), std::move(rp.second)); + } } RoutingPresetMap RoutingConfigurator::GetPresetTable() const @@ -1805,8 +1807,9 @@ bool RoutingConfigurator::FindFirstPreset(ConnectionKind kind, NTV2DeviceID id, RoutingPresets device_presets; RoutingPresets non_device_presets; for (auto &q : query) { - if (q.second.device_ids.size() == 0) + if (q.second.device_ids.size() == 0) { non_device_presets.push_back(q.second); + } for (const auto &device_id : q.second.device_ids) { if (device_id == id) { device_presets.push_back(q.second); diff --git a/plugins/aja/aja-props.cpp b/plugins/aja/aja-props.cpp index c737d17fafa3f8..431ecf092c2a7a 100644 --- a/plugins/aja/aja-props.cpp +++ b/plugins/aja/aja-props.cpp @@ -198,18 +198,19 @@ audio_format SourceProps::AudioFormat() const speaker_layout SourceProps::SpeakerLayout() const { - if (audioNumChannels == 1) + if (audioNumChannels == 1) { return SPEAKERS_MONO; - else if (audioNumChannels == 2) + } else if (audioNumChannels == 2) { return SPEAKERS_STEREO; - else if (audioNumChannels == 3) + } else if (audioNumChannels == 3) { return SPEAKERS_2POINT1; - else if (audioNumChannels == 4) + } else if (audioNumChannels == 4) { return SPEAKERS_4POINT0; - else if (audioNumChannels == 5) + } else if (audioNumChannels == 5) { return SPEAKERS_4POINT1; - else if (audioNumChannels == 6) + } else if (audioNumChannels == 6) { return SPEAKERS_5POINT1; + } // NTV2 card is always set to at least 8ch return SPEAKERS_7POINT1; } @@ -319,8 +320,9 @@ NTV2Channel OutputProps::Channel() const } 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); } @@ -335,17 +337,20 @@ NTV2Channel OutputProps::Framestore() const return NTV2_CHANNEL2; } else if (deviceID == DEVICE_ID_IO4K || deviceID == DEVICE_ID_IO4KPLUS) { // SDI Monitor output uses framestore 4 - if (ioSelect == IOSelection::SDI5) + if (ioSelect == IOSelection::SDI5) { return NTV2_CHANNEL4; + } } // HDMI Monitor output uses framestore 4 if (ioSelect == IOSelection::HDMIMonitorOut) { - if (deviceID == DEVICE_ID_KONA5_8K) + if (deviceID == DEVICE_ID_KONA5_8K) { return NTV2_CHANNEL4; - if (NTV2_IS_4K_VIDEO_FORMAT(videoFormat)) + } + if (NTV2_IS_4K_VIDEO_FORMAT(videoFormat)) { return NTV2_CHANNEL3; - else + } else { return NTV2_CHANNEL4; + } } return NTV2OutputDestinationToChannel(outputDest); } @@ -388,8 +393,9 @@ audio_format OutputProps::AudioFormat() const speaker_layout OutputProps::SpeakerLayout() const { - if (audioNumChannels == 2) + if (audioNumChannels == 2) { return SPEAKERS_STEREO; + } // NTV2 is always at least 8ch on modern boards return SPEAKERS_7POINT1; } diff --git a/plugins/aja/aja-routing.cpp b/plugins/aja/aja-routing.cpp index 235a477d055afc..1034a1e792c4bd 100644 --- a/plugins/aja/aja-routing.cpp +++ b/plugins/aja/aja-routing.cpp @@ -37,8 +37,9 @@ bool Routing::ParseRouteString(const std::string &route, NTV2XptConnections &cnx NTV2StringList lines; lines = aja::split(route_strip, ';'); - if (lines.empty()) + if (lines.empty()) { lines.push_back(route_strip); + } int32_t parse_ok = 0; for (const auto &l : lines) { @@ -114,8 +115,9 @@ bool Routing::ParseRouteString(const std::string &route, NTV2XptConnections &cnx void Routing::StartSourceAudio(const SourceProps &props, CNTV2Card *card) { - if (!card) + if (!card) { return; + } auto inputSrc = props.InitialInputSource(); auto channel = props.Channel(); @@ -178,8 +180,9 @@ void Routing::StopSourceAudio(const SourceProps &props, CNTV2Card *card) bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV2Card *card, NTV2XptConnections &cnx) { - if (!card) + if (!card) { return false; + } auto deviceID = props.deviceID; NTV2VideoFormat vf = props.videoFormat; @@ -195,8 +198,9 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV kind = ConnectionKind::SDI; if (props.autoDetect) { auto vpidList = props.vpids; - if (vpidList.size() > 0) + if (vpidList.size() > 0) { vpidStandard = vpidList.at(0).Standard(); + } } if (vpidStandard == VPIDStandard_Unknown) { vpidStandard = DetermineVPIDStandard(props.ioSelect, props.videoFormat, props.pixelFormat, @@ -252,8 +256,9 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV aja::replace(route_string, channel_placeholder, aja::to_string(start_channel_index++)); } - if (!ParseRouteString(route_string, cnx)) + if (!ParseRouteString(route_string, cnx)) { return false; + } card->ApplySignalRoute(cnx, false); @@ -275,10 +280,11 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV // Apply HDMI settings if (aja::IsIOSelectionHDMI(props.ioSelect)) { - if (NTV2_IS_4K_VIDEO_FORMAT(props.videoFormat)) + if (NTV2_IS_4K_VIDEO_FORMAT(props.videoFormat)) { card->SetHDMIV2Mode(NTV2_HDMI_V2_4K_CAPTURE); - else + } else { card->SetHDMIV2Mode(NTV2_HDMI_V2_HDSD_BIDIRECTIONAL); + } } // Apply Framestore settings @@ -300,8 +306,9 @@ bool Routing::ConfigureSourceRoute(const SourceProps &props, NTV2Mode mode, CNTV bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, CNTV2Card *card, NTV2XptConnections &cnx) { - if (!card) + if (!card) { return false; + } auto deviceID = props.deviceID; NTV2OutputDestinations outputDests; @@ -379,8 +386,9 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, CNTV aja::replace(route_string, channel_placeholder, aja::to_string(start_channel_index++)); } - if (!ParseRouteString(route_string, cnx)) + if (!ParseRouteString(route_string, cnx)) { return false; + } card->ApplySignalRoute(cnx, false); @@ -424,8 +432,9 @@ bool Routing::ConfigureOutputRoute(const OutputProps &props, NTV2Mode mode, CNTV void Routing::ConfigureOutputAudio(const OutputProps &props, CNTV2Card *card) { - if (!card) + if (!card) { return; + } auto deviceID = card->GetDeviceID(); auto audioSys = props.AudioSystem(); diff --git a/plugins/aja/aja-source.cpp b/plugins/aja/aja-source.cpp index 1aabc3b3620879..adcbe68e2f2748 100644 --- a/plugins/aja/aja-source.cpp +++ b/plugins/aja/aja-source.cpp @@ -107,11 +107,13 @@ void populate_source_device_list(obs_property_t *list) for (const auto &iter : cardManager.GetCardEntries()) { if (iter.second) { CNTV2Card *card = iter.second->GetCard(); - if (!card) + if (!card) { continue; + } - if (aja::IsOutputOnlyDevice(iter.second->GetDeviceID())) + if (aja::IsOutputOnlyDevice(iter.second->GetDeviceID())) { continue; + } obs_property_list_add_string(list, iter.second->GetDisplayName().c_str(), iter.second->GetCardID().c_str()); @@ -133,8 +135,9 @@ struct AudioOffsets { static void ResetAudioBufferOffsets(CNTV2Card *card, NTV2AudioSystem audioSystem, AudioOffsets &offsets) { - if (!card) + if (!card) { return; + } offsets.currentAddress = 0; offsets.lastAddress = 0; @@ -151,10 +154,12 @@ void AJASource::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2 { NTV2VideoFormat vid_fmt = vf; NTV2PixelFormat pix_fmt = pf; - if (vid_fmt == NTV2_FORMAT_UNKNOWN) + if (vid_fmt == NTV2_FORMAT_UNKNOWN) { vid_fmt = NTV2_FORMAT_720p_5994; - if (pix_fmt == NTV2_FBF_INVALID) + } + if (pix_fmt == NTV2_FBF_INVALID) { pix_fmt = kDefaultAJAPixelFormat; + } NTV2FormatDesc fd(vid_fmt, pix_fmt, NTV2_VANCMODE_OFF); auto bufSize = fd.GetTotalRasterBytes(); @@ -180,8 +185,9 @@ void AJASource::GenerateTestPattern(NTV2VideoFormat vf, NTV2PixelFormat pf, NTV2 obsFrame.data[0] = mTestPattern.data(); obsFrame.linesize[0] = fd.GetBytesPerRow(); video_colorspace colorspace = VIDEO_CS_709; - if (NTV2_IS_SD_VIDEO_FORMAT(vid_fmt)) + 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); obs_source_output_video2(mSource, &obsFrame); @@ -222,20 +228,23 @@ static inline bool TransferAudio(CNTV2Card *card, const NTV2AudioSystem audioSys offsets.bytesRead = offsets.wrapAddress - offsets.lastAddress; if (!CheckTransferAudioDMA(card, audioSystem, audioBuffer, audioBuffer.GetByteCount(), - offsets.lastAddress, offsets.bytesRead, "(1)")) + 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)")) + offsets.currentAddress - offsets.readOffset, "(2)")) { return false; + } 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.lastAddress, offsets.bytesRead, "(3)")) { return false; + } } return true; @@ -342,8 +351,9 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) audioPacket.data[0] = (*audioRepacker)->packet_buffer; } else { /* Silence, or pass-through 8ch of audio */ - if (sourceProps.audioNumChannels == 0) + if (sourceProps.audioNumChannels == 0) { memset(hostAudioBuffer, 0, offsets.bytesRead); + } audioPacket.data[0] = hostAudioBuffer; } obs_source_output_audio(ajaSource->mSource, &audioPacket); @@ -357,8 +367,9 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) card->DMAReadFrame(currentCardFrame, ajaSource->mVideoBuffer, ajaSource->mVideoBuffer.GetByteCount()); auto actualVideoFormat = videoFormat; - if (aja::Is3GLevelB(card, channel)) + if (aja::Is3GLevelB(card, channel)) { actualVideoFormat = aja::GetLevelAFormatForLevelBFormat(videoFormat); + } const enum video_format obs_vid_fmt = aja::AJAPixelFormatToOBSVideoFormat(sourceProps.pixelFormat); @@ -372,8 +383,9 @@ void AJASource::CaptureThread(AJAThread *thread, void *data) 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)) + 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); @@ -514,8 +526,9 @@ bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, N } mCard->WaitForInputVerticalInterrupt(channel); VPIDData vpid_data; - if (ReadChannelVPIDs(channel, vpid_data)) + if (ReadChannelVPIDs(channel, vpid_data)) { vpids.push_back(vpid_data); + } } else if (NTV2_INPUT_SOURCE_IS_HDMI(src)) { mCard->WaitForInputVerticalInterrupt(channel); @@ -544,10 +557,11 @@ bool AJASource::ReadWireFormats(NTV2DeviceID device_id, IOSelection io_select, N if (vpids.size() > 0) { auto vpid = *vpids.begin(); if (vpid.Sampling() == VPIDSampling_YUV_422) { - if (vpid.BitDepth() == VPIDBitDepth_8) + if (vpid.BitDepth() == VPIDBitDepth_8) { pf = NTV2_FBF_8BIT_YCBCR; - else if (vpid.BitDepth() == VPIDBitDepth_10) + } 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()); } else if (vpid.Sampling() == VPIDSampling_GBR_444) { @@ -570,8 +584,9 @@ void AJASource::ResetVideoBuffer(NTV2VideoFormat vf, NTV2PixelFormat pf) if (vf != NTV2_FORMAT_UNKNOWN) { auto videoBufferSize = GetVideoWriteSize(vf, pf); - if (mVideoBuffer) + if (mVideoBuffer) { mVideoBuffer.Deallocate(); + } mVideoBuffer.Allocate(videoBufferSize, true); @@ -583,8 +598,9 @@ void AJASource::ResetVideoBuffer(NTV2VideoFormat vf, NTV2PixelFormat pf) void AJASource::ResetAudioBuffer(size_t size) { - if (mAudioBuffer) + if (mAudioBuffer) { mAudioBuffer.Deallocate(); + } mAudioBuffer.Allocate(size, true); } @@ -614,8 +630,9 @@ bool aja_source_device_changed(void *data, obs_properties_t *props, obs_property } const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return false; + } auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); @@ -701,8 +718,9 @@ bool aja_io_selection_changed(void *data, obs_properties_t *props, obs_property_ } const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return false; + } auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); @@ -809,8 +827,9 @@ static void aja_source_show(void *data) static void aja_source_hide(void *data) { auto ajaSource = (AJASource *)data; - if (!ajaSource) + if (!ajaSource) { return; + } bool deactivateWhileNotShowing = ajaSource->GetSourceProps().deactivateWhileNotShowing; bool showing = obs_source_showing(ajaSource->GetOBSSource()); @@ -954,10 +973,12 @@ static void aja_source_update(void *data, obs_data_t *settings) } // Set auto-detected formats - if ((int32_t)vf_select == kAutoDetect) + if ((int32_t)vf_select == kAutoDetect) { want_props.videoFormat = new_vf; - if ((int32_t)pf_select == kAutoDetect) + } + 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", @@ -1046,8 +1067,9 @@ void aja_source_save(void *data, obs_data_t *settings) } const char *cardID = obs_data_get_string(settings, kUIPropDevice.id); - if (!cardID || !cardID[0]) + if (!cardID || !cardID[0]) { return; + } auto &cardManager = aja::CardManager::Instance(); auto cardEntry = cardManager.GetCardEntry(cardID); diff --git a/plugins/coreaudio-encoder/encoder.cpp b/plugins/coreaudio-encoder/encoder.cpp index d7dff6cef3aa01..79377aaabeb59c 100644 --- a/plugins/coreaudio-encoder/encoder.cpp +++ b/plugins/coreaudio-encoder/encoder.cpp @@ -116,8 +116,9 @@ struct ca_encoder { ~ca_encoder() { - if (converter) + if (converter) { AudioConverterDispose(converter); + } } }; typedef struct ca_encoder ca_encoder; @@ -147,8 +148,7 @@ template using cf_ptr = unique_ptr::type> #ifndef _MSC_VER __attribute__((__format__(__printf__, 3, 4))) #endif -static void -log_to_dstr(DStr &str, ca_encoder *ca, const char *fmt, ...) +static void log_to_dstr(DStr &str, ca_encoder *ca, const char *fmt, ...) { dstr prev_str = *static_cast(str); @@ -157,8 +157,9 @@ log_to_dstr(DStr &str, ca_encoder *ca, const char *fmt, ...) dstr_vcatf(str, fmt, args); va_end(args); - if (str->array) + if (str->array) { return; + } char array[4096]; va_start(args, fmt); @@ -167,24 +168,26 @@ log_to_dstr(DStr &str, ca_encoder *ca, const char *fmt, ...) array[4095] = 0; - if (!prev_str.array && !prev_str.len) + if (!prev_str.array && !prev_str.len) { CA_CO_LOG(LOG_ERROR, "Could not allocate buffer for logging:" "\n'%s'", array); - else + } else { CA_CO_LOG(LOG_ERROR, "Could not allocate buffer for logging:" "\n'%s'\nPrevious log entries:\n%s", array, prev_str.array); + } bfree(prev_str.array); } static const char *flush_log(DStr &log) { - if (!log->array || !log->len) + if (!log->array || !log->len) { return ""; + } if (log->array[log->len - 1] == '\n') { log->array[log->len - 1] = 0; //Get rid of last newline @@ -244,8 +247,9 @@ static DStr osstatus_to_dstr(OSStatus code) cf_ptr err{CFErrorCreate(kCFAllocatorDefault, kCFErrorDomainOSStatus, code, NULL)}; cf_ptr str{CFErrorCopyDescription(err.get())}; - if (cfstr_copy_dstr(str.get(), kCFStringEncodingUTF8, result)) + if (cfstr_copy_dstr(str.get(), kCFStringEncodingUTF8, result)) { return result; + } #endif const char *code_str = code_to_str(code); @@ -257,10 +261,11 @@ static DStr osstatus_to_dstr(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) + if (ca) { CA_BLOG(log_level, "Error in %s: %s", context, str->array); - else + } else { CA_LOG(log_level, "Error in %s: %s", context, str->array); + } } static const char *format_id_to_str(UInt32 format_id) @@ -361,8 +366,9 @@ static bool enumerate_bitrates(DStr &log, ca_encoder *ca, AudioConverterRef conv 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++) + for (size_t i = 0; i < num_ranges; i++) { func(static_cast(range[i].mMinimum), static_cast(range[i].mMaximum)); + } }; return query_converter_property_raw(log, ca, EXPAND_CONVERTER_NAMES(kAudioConverterApplicableEncodeBitRates), @@ -374,8 +380,9 @@ static bool bitrate_valid(DStr &log, ca_encoder *ca, AudioConverterRef converter bool valid = false; auto helper = [&](UInt32 min_, UInt32 max_) { - if (min_ == bitrate || max_ == bitrate) + if (min_ == bitrate || max_ == bitrate) { valid = true; + } }; enumerate_bitrates(log, ca, converter, helper); @@ -506,8 +513,9 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) 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; break; @@ -521,8 +529,9 @@ static void *aac_create(obs_data_t *settings, obs_encoder_t *encoder) return nullptr; } - if (log->len) + if (log->len) { CA_CO_DLOG_(LOG_DEBUG, "Encoder created"); + } OSStatus code; UInt32 converter_quality = kAudioConverterQuality_Max; @@ -668,8 +677,9 @@ static bool aac_encode(void *data, struct encoder_frame *frame, struct encoder_p 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) + if (ca->input_buffer.size() < ca->in_bytes_required) { return true; + } UInt32 packets = 1; @@ -688,8 +698,9 @@ static bool aac_encode(void *data, struct encoder_frame *frame, struct encoder_p return false; } - if (!(*received_packet = packets > 0)) + if (!(*received_packet = packets > 0)) { return true; + } packet->pts = ca->total_samples - ca->priming_samples; packet->dts = ca->total_samples - ca->priming_samples; @@ -740,8 +751,9 @@ static int read_descr_len(uint8_t **buffer) while (count--) { int c = *(*buffer)++; len = (len << 7) | (c & 0x7f); - if (!(c & 0x80)) + if (!(c & 0x80)) { break; + } } return len; } @@ -759,13 +771,15 @@ static void read_esds_desc_ext(uint8_t *desc_ext, vector &buffer, bool uint8_t *esds = desc_ext; int tag, len; - if (version_flags) + if (version_flags) { esds += 4; // version + flags + } read_descr(&esds, &tag); esds += 2; // ID - if (tag == MP4ESDescrTag) + if (tag == MP4ESDescrTag) { esds++; // priority + } read_descr(&esds, &tag); if (tag == MP4DecConfigDescrTag) { @@ -776,12 +790,13 @@ static void read_esds_desc_ext(uint8_t *desc_ext, vector &buffer, bool esds += 4; // average bitrate len = read_descr(&esds, &tag); - if (tag == MP4DecSpecificDescrTag) + if (tag == MP4DecSpecificDescrTag) { try { buffer.assign(esds, esds + len); } catch (...) { //leave buffer empty } + } } } /* extracted code ends here */ @@ -830,11 +845,13 @@ static bool aac_extra_data(void *data, uint8_t **extra_data, size_t *size) { ca_encoder *ca = static_cast(data); - if (!ca->extra_data.size()) + if (!ca->extra_data.size()) { query_extra_data(ca); + } - if (!ca->extra_data.size()) + if (!ca->extra_data.size()) { return false; + } *extra_data = ca->extra_data.data(); *size = ca->extra_data.size(); @@ -912,8 +929,9 @@ static bool find_best_match(DStr &log, ca_encoder *ca, UInt32 bitrate, UInt32 &b auto helper = [&](UInt32 min_, UInt32 max_) { handle_bitrate(min_); - if (min_ == max_) + if (min_ == max_) { return; + } log_to_dstr(log, ca, "Got actual bit rate range: %u<->%u\n", static_cast(min_), static_cast(max_)); @@ -928,10 +946,11 @@ static bool find_best_match(DStr &log, ca_encoder *ca, UInt32 bitrate, UInt32 &b auto converter = get_converter(log, ca, out); - if (converter) + if (converter) { enumerate_bitrates(log, ca, converter.get(), helper); - else + } else { log_to_dstr(log, ca, "Could not get converter\n"); + } } best_match /= 1000; @@ -967,11 +986,12 @@ static UInt32 find_matching_bitrate(UInt32 bitrate) return; } - if (log->len) + if (log->len) { CA_CO_DLOG(LOG_DEBUG, "Default bitrate matching log " "for bitrate %u", static_cast(bitrate)); + } }); return match; @@ -1028,8 +1048,9 @@ static bool enumerate_samplerates(DStr &log, ca_encoder *ca, AudioStreamBasicDes 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++) + for (size_t i = 0; i < num_ranges; i++) { func(range[i]); + } }; return query_property_raw(log, ca, EXPAND_PROPERTY_NAMES(kAudioFormatProperty_AvailableEncodeSampleRates), desc, @@ -1077,8 +1098,9 @@ static vector get_samplerates(DStr &log, ca_encoder *ca) handle_samplerate(min_); - if (min_ == max_) + if (min_ == max_) { return; + } log_to_dstr(log, ca, "Got actual sample rate range: %u<->%u\n", static_cast(min_), static_cast(max_)); @@ -1110,8 +1132,9 @@ static void add_samplerates(obs_property_t *prop, ca_encoder *ca) return; } - if (log->len) + if (log->len) { CA_CO_DLOG_(LOG_DEBUG, "Sample rate enumeration log"); + } sort(begin(samplerates), end(samplerates)); @@ -1145,8 +1168,9 @@ static vector get_bitrates(DStr &log, ca_encoder *ca, Float64 samplerate auto helper = [&](UInt32 min_, UInt32 max_) { handle_bitrate(min_); - if (min_ == max_) + if (min_ == max_) { return; + } log_to_dstr(log, ca, "Got actual bitrate range: %u<->%u\n", static_cast(min_), static_cast(max_)); @@ -1162,8 +1186,9 @@ static vector get_bitrates(DStr &log, ca_encoder *ca, Float64 samplerate auto converter = get_converter(log, ca, out); - if (converter) + if (converter) { enumerate_bitrates(log, ca, converter.get(), helper); + } } return bitrates; @@ -1182,15 +1207,17 @@ static void add_bitrates(obs_property_t *prop, ca_encoder *ca, Float64 samplerat return; } - if (log->len) + if (log->len) { CA_CO_DLOG_(LOG_DEBUG, "Bitrate enumeration log"); + } bool selected_in_range = true; if (selected) { selected_in_range = find(begin(bitrates), end(bitrates), *selected * 1000) != end(bitrates); - if (!selected_in_range) + if (!selected_in_range) { bitrates.push_back(*selected * 1000); + } } sort(begin(bitrates), end(bitrates)); @@ -1200,8 +1227,9 @@ static void add_bitrates(obs_property_t *prop, ca_encoder *ca, Float64 samplerat dstr_printf(buffer, "%u", (uint32_t)bitrate / 1000); size_t idx = obs_property_list_add_int(prop, buffer->array, bitrate / 1000); - if (selected_in_range || bitrate / 1000 != *selected) + if (selected_in_range || bitrate / 1000 != *selected) { continue; + } obs_property_list_item_disable(prop, idx, true); } @@ -1210,8 +1238,9 @@ static void add_bitrates(obs_property_t *prop, ca_encoder *ca, Float64 samplerat 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")); - if (!samplerate) + if (!samplerate) { samplerate = 44100; + } prop = obs_properties_get(props, "bitrate"); if (prop) { diff --git a/plugins/decklink/DecklinkInput.cpp b/plugins/decklink/DecklinkInput.cpp index a0e14cce49bbc9..084bd6df44abf8 100644 --- a/plugins/decklink/DecklinkInput.cpp +++ b/plugins/decklink/DecklinkInput.cpp @@ -37,10 +37,12 @@ void DeckLinkInput::DevicesChanged(void *param, DeckLinkDevice *device, bool add obs_data_release(settings); if (device->GetHash().compare(hash) == 0) { - if (!decklink->activateRefs) + if (!decklink->activateRefs) { return; - if (decklink->Activate(device, mode, videoConnection, audioConnection)) + } + if (decklink->Activate(device, mode, videoConnection, audioConnection)) { os_atomic_dec_long(&decklink->activateRefs); + } } } else if (!added && decklink->instance) { @@ -60,25 +62,30 @@ bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, BMDVideoC const bool isActive = instance != nullptr; if (same) { - if (!isActive) + if (!isActive) { return false; + } if (instance->GetActiveModeId() == modeId && instance->GetVideoConnection() == bmdVideoConnection && instance->GetAudioConnection() == bmdAudioConnection && instance->GetActivePixelFormat() == pixelFormat && instance->GetActiveColorSpace() == colorSpace && instance->GetActiveColorRange() == colorRange && - instance->GetActiveChannelFormat() == channelFormat && instance->GetActiveSwapState() == swap) + instance->GetActiveChannelFormat() == channelFormat && instance->GetActiveSwapState() == swap) { return false; + } } - if (isActive) + if (isActive) { instance->StopCapture(); + } isCapturing = false; - if (!same) + if (!same) { instance.Set(new DeckLinkDeviceInstance(this, device)); + } - if (instance == nullptr) + if (instance == nullptr) { return false; + } if (GetDevice() == nullptr) { LOG(LOG_ERROR, "Tried to activate an input with nullptr device."); @@ -106,8 +113,9 @@ bool DeckLinkInput::Activate(DeckLinkDevice *device, long long modeId, BMDVideoC void DeckLinkInput::Deactivate(void) { std::lock_guard lock(deviceMutex); - if (instance) + if (instance) { instance->StopCapture(); + } isCapturing = false; instance = nullptr; @@ -121,8 +129,9 @@ bool DeckLinkInput::Capturing(void) void DeckLinkInput::SaveSettings() { - if (!instance) + if (!instance) { return; + } DeckLinkDevice *device = instance->GetDevice(); DeckLinkDeviceMode *mode = instance->GetMode(); diff --git a/plugins/decklink/DecklinkOutput.cpp b/plugins/decklink/DecklinkOutput.cpp index e563aabb200a99..d1c2ead9d9a0db 100644 --- a/plugins/decklink/DecklinkOutput.cpp +++ b/plugins/decklink/DecklinkOutput.cpp @@ -31,23 +31,28 @@ bool DeckLinkOutput::Activate(DeckLinkDevice *device, long long modeId) const bool isActive = instance != nullptr; if (same) { - if (!isActive) + if (!isActive) { return false; + } if (instance->GetActiveModeId() == modeId && instance->GetActivePixelFormat() == pixelFormat && instance->GetActiveColorSpace() == colorSpace && instance->GetActiveColorRange() == colorRange && - instance->GetActiveChannelFormat() == channelFormat) + instance->GetActiveChannelFormat() == channelFormat) { return false; + } } - if (isActive) + if (isActive) { instance->StopOutput(); + } - if (!same) + if (!same) { instance.Set(new DeckLinkDeviceInstance(this, device)); + } - if (instance == nullptr) + if (instance == nullptr) { return false; + } DeckLinkDeviceMode *mode = GetDevice()->FindOutputMode(modeId); if (mode == nullptr) { @@ -67,8 +72,9 @@ bool DeckLinkOutput::Activate(DeckLinkDevice *device, long long modeId) void DeckLinkOutput::Deactivate(void) { std::lock_guard lock(deviceMutex); - if (instance) + if (instance) { instance->StopOutput(); + } instance = nullptr; diff --git a/plugins/decklink/OBSVideoFrame.cpp b/plugins/decklink/OBSVideoFrame.cpp index 607881410812fe..1bf54832d1c995 100644 --- a/plugins/decklink/OBSVideoFrame.cpp +++ b/plugins/decklink/OBSVideoFrame.cpp @@ -91,17 +91,18 @@ HDRVideoFrame::HDRVideoFrame(IDeckLinkMutableVideoFrame *frame) : m_videoFrame(f HRESULT HDRVideoFrame::QueryInterface(REFIID iid, LPVOID *ppv) { - if (ppv == nullptr) + if (ppv == nullptr) { return E_INVALIDARG; + } CFUUIDBytes unknown = CFUUIDGetUUIDBytes(IUnknownUUID); - if (CompareREFIID(iid, unknown)) + if (CompareREFIID(iid, unknown)) { *ppv = static_cast(this); - else if (CompareREFIID(iid, IID_IDeckLinkVideoFrame)) + } else if (CompareREFIID(iid, IID_IDeckLinkVideoFrame)) { *ppv = static_cast(this); - else if (CompareREFIID(iid, IID_IDeckLinkVideoFrameMetadataExtensions)) + } else if (CompareREFIID(iid, IID_IDeckLinkVideoFrameMetadataExtensions)) { *ppv = static_cast(this); - else { + } else { *ppv = nullptr; return E_NOINTERFACE; } @@ -119,8 +120,9 @@ ULONG HDRVideoFrame::Release(void) { ULONG newRefValue = --m_refCount; - if (newRefValue == 0) + if (newRefValue == 0) { delete this; + } return newRefValue; } diff --git a/plugins/decklink/decklink-device-discovery.cpp b/plugins/decklink/decklink-device-discovery.cpp index b25a3ee83699d9..b6e3ec49684791 100644 --- a/plugins/decklink/decklink-device-discovery.cpp +++ b/plugins/decklink/decklink-device-discovery.cpp @@ -6,17 +6,20 @@ DeckLinkDeviceDiscovery::DeckLinkDeviceDiscovery() { discovery.Set(CreateDeckLinkDiscoveryInstance()); - if (discovery == nullptr) + if (discovery == nullptr) { blog(LOG_INFO, "No blackmagic support"); + } } DeckLinkDeviceDiscovery::~DeckLinkDeviceDiscovery(void) { if (discovery != nullptr) { - if (initialized) + if (initialized) { discovery->UninstallDeviceNotifications(); - for (DeckLinkDevice *device : devices) + } + for (DeckLinkDevice *device : devices) { device->Release(); + } } } @@ -24,15 +27,18 @@ bool DeckLinkDeviceDiscovery::Init(void) { HRESULT result = E_FAIL; - if (initialized) + if (initialized) { return false; + } - if (discovery != nullptr) + if (discovery != nullptr) { result = discovery->InstallDeviceNotifications(this); + } initialized = result == S_OK; - if (!initialized) + if (!initialized) { blog(LOG_DEBUG, "Failed to start search for DeckLink devices"); + } return initialized; } @@ -66,8 +72,9 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::DeckLinkDeviceArrived(IDeckLi devices.push_back(newDev); - for (DeviceChangeInfo &cb : callbacks) + for (DeviceChangeInfo &cb : callbacks) { cb.callback(cb.param, newDev, true); + } return S_OK; } @@ -79,8 +86,9 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceDiscovery::DeckLinkDeviceRemoved(IDeckLi for (size_t i = 0; i < devices.size(); i++) { if (devices[i]->IsDevice(device)) { - for (DeviceChangeInfo &cb : callbacks) + for (DeviceChangeInfo &cb : callbacks) { cb.callback(cb.param, devices[i], false); + } devices[i]->Release(); devices.erase(devices.begin() + i); diff --git a/plugins/decklink/decklink-device-discovery.hpp b/plugins/decklink/decklink-device-discovery.hpp index 9822f82c66bc0c..9287e354c38dbf 100644 --- a/plugins/decklink/decklink-device-discovery.hpp +++ b/plugins/decklink/decklink-device-discovery.hpp @@ -43,8 +43,9 @@ class DeckLinkDeviceDiscovery : public IDeckLinkDeviceNotificationCallback { info.param = param; for (DeviceChangeInfo &curCB : callbacks) { - if (curCB.callback == callback && curCB.param == param) + if (curCB.callback == callback && curCB.param == param) { return; + } } callbacks.push_back(info); diff --git a/plugins/decklink/decklink-device-instance.cpp b/plugins/decklink/decklink-device-instance.cpp index 3c5de5d19f1eb5..b1376c8db5541c 100644 --- a/plugins/decklink/decklink-device-instance.cpp +++ b/plugins/decklink/decklink-device-instance.cpp @@ -129,8 +129,9 @@ DeckLinkDeviceInstance::~DeckLinkDeviceInstance() void DeckLinkDeviceInstance::HandleAudioPacket(IDeckLinkAudioInputPacket *audioPacket, const uint64_t timestamp) { - if (audioPacket == nullptr) + if (audioPacket == nullptr) { return; + } void *bytes; if (audioPacket->GetBytes(&bytes) != S_OK) { @@ -169,8 +170,9 @@ void DeckLinkDeviceInstance::HandleAudioPacket(IDeckLinkAudioInputPacket *audioP void DeckLinkDeviceInstance::HandleVideoFrame(IDeckLinkVideoInputFrame *videoFrame, const uint64_t timestamp) { - if (videoFrame == nullptr) + if (videoFrame == nullptr) { return; + } ComPtr packets; @@ -216,8 +218,9 @@ void DeckLinkDeviceInstance::HandleVideoFrame(IDeckLinkVideoInputFrame *videoFra currentFrame.height = (uint32_t)frame->GetHeight(); currentFrame.timestamp = timestamp; - if (currentFrame.width == 0 || currentFrame.height == 0) + if (currentFrame.width == 0 || currentFrame.height == 0) { return; + } enum video_trc trc = VIDEO_TRC_DEFAULT; if (frame->GetFlags() & bmdFrameContainsHDRMetadata) { @@ -337,8 +340,9 @@ void DeckLinkDeviceInstance::FinalizeStream() { input->SetCallback(nullptr); input->DisableVideoInput(); - if (channelFormat != SPEAKERS_UNKNOWN) + if (channelFormat != SPEAKERS_UNKNOWN) { input->DisableAudioInput(); + } if (audioRepacker != nullptr) { delete audioRepacker; @@ -352,8 +356,9 @@ void DeckLinkDeviceInstance::FinalizeStream() void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_) { - if (mode_ == nullptr) + if (mode_ == nullptr) { return; + } const enum video_format format = ConvertPixelFormat(pixelFormat); currentFrame.format = format; @@ -362,14 +367,15 @@ void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_) if (colorSpace == VIDEO_CS_DEFAULT) { const BMDDisplayModeFlags flags = mode_->GetDisplayModeFlags(); /* 2020 wasn't set when testing but maybe it will be someday */ - if (flags & bmdDisplayModeColorspaceRec2020) + if (flags & bmdDisplayModeColorspaceRec2020) { activeColorSpace = VIDEO_CS_2100_PQ; - else if (flags & bmdDisplayModeColorspaceRec709) + } else if (flags & bmdDisplayModeColorspaceRec709) { activeColorSpace = VIDEO_CS_709; - else if (flags & bmdDisplayModeColorspaceRec601) + } else if (flags & bmdDisplayModeColorspaceRec601) { activeColorSpace = VIDEO_CS_601; - else + } else { activeColorSpace = VIDEO_CS_DEFAULT; + } } else { activeColorSpace = colorSpace; } @@ -406,15 +412,18 @@ void DeckLinkDeviceInstance::SetupVideoFormat(DeckLinkDeviceMode *mode_) bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, bool allow10Bit_, BMDVideoConnection bmdVideoConnection, BMDAudioConnection bmdAudioConnection) { - if (mode != nullptr) + if (mode != nullptr) { return false; - if (mode_ == nullptr) + } + if (mode_ == nullptr) { return false; + } LOG(LOG_INFO, "Starting capture..."); - if (!device->GetInput(&input)) + if (!device->GetInput(&input)) { return false; + } HRESULT result = input->QueryInterface(IID_IDeckLinkConfiguration, (void **)&deckLinkConfiguration); if (result != S_OK) { @@ -477,8 +486,9 @@ bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, bool allow1 const int channel = ConvertChannelFormat(channelFormat); const HRESULT audioResult = input->EnableAudioInput(bmdAudioSampleRate48kHz, bmdAudioSampleType16bitInteger, channel); - if (audioResult != S_OK) + if (audioResult != S_OK) { LOG(LOG_WARNING, "Failed to enable audio input; continuing..."); + } if (channelFormat != SPEAKERS_UNKNOWN && channelFormat != SPEAKERS_MONO && channelFormat != SPEAKERS_STEREO && (channelFormat != SPEAKERS_7POINT1 || swap) && @@ -508,8 +518,9 @@ bool DeckLinkDeviceInstance::StartCapture(DeckLinkDeviceMode *mode_, bool allow1 bool DeckLinkDeviceInstance::StopCapture(void) { - if (mode == nullptr || input == nullptr) + if (mode == nullptr || input == nullptr) { return false; + } LOG(LOG_INFO, "Stopping capture of '%s'...", GetDevice()->GetDisplayName().c_str()); @@ -521,20 +532,24 @@ bool DeckLinkDeviceInstance::StopCapture(void) bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_) { - if (mode != nullptr) + if (mode != nullptr) { return false; - if (mode_ == nullptr) + } + if (mode_ == nullptr) { return false; + } auto decklinkOutput = dynamic_cast(decklink); - if (decklinkOutput == nullptr) + if (decklinkOutput == nullptr) { return false; + } LOG(LOG_INFO, "Starting output..."); ComPtr output_; - if (!device->GetOutput(&output_)) + if (!device->GetOutput(&output_)) { return false; + } const HRESULT videoResult = output_->EnableVideoOutput(mode_->GetDisplayMode(), bmdVideoOutputFlagDefault); if (videoResult != S_OK) { @@ -622,8 +637,9 @@ bool DeckLinkDeviceInstance::StartOutput(DeckLinkDeviceMode *mode_) bool DeckLinkDeviceInstance::StopOutput() { - if (mode == nullptr || output == nullptr) + if (mode == nullptr || output == nullptr) { return false; + } LOG(LOG_INFO, "Stopping output of '%s'...", GetDevice()->GetDisplayName().c_str()); @@ -641,8 +657,9 @@ bool DeckLinkDeviceInstance::StopOutput() void DeckLinkDeviceInstance::UpdateVideoFrame(video_data *frame) { auto decklinkOutput = dynamic_cast(decklink); - if (decklinkOutput == nullptr) + if (decklinkOutput == nullptr) { return; + } uint8_t *const blob = frameQueueDecklinkToObs.pop(); if (blob) { @@ -657,18 +674,20 @@ void DeckLinkDeviceInstance::ScheduleVideoFrame(IDeckLinkVideoFrame *frame) if (SUCCEEDED(frame->GetBytes(&bytes))) { uint8_t *blob = frameQueueObsToDecklink.pop(); if (blob) { - if (activeBlob) + if (activeBlob) { frameQueueDecklinkToObs.push(activeBlob); + } activeBlob = blob; } else { blob = activeBlob; } const int frameSize = frame->GetRowBytes() * frame->GetHeight(); - if (blob) + if (blob) { memcpy(bytes, blob, frameSize); - else + } else { memset(bytes, 0, frameSize); + } output->ScheduleVideoFrame(frame, totalFramesScheduled * frameDuration, frameDuration, frameTimescale); ++totalFramesScheduled; @@ -712,10 +731,12 @@ HRESULT STDMETHODCALLTYPE DeckLinkDeviceInstance::VideoInputFrameArrived(IDeckLi } } - if (videoFrame && videoTS >= 0) + if (videoFrame && videoTS >= 0) { HandleVideoFrame(videoFrame, (uint64_t)videoTS); - if (audioPacket && audioTS >= 0) + } + if (audioPacket && audioTS >= 0) { HandleAudioPacket(audioPacket, (uint64_t)audioTS); + } return S_OK; } diff --git a/plugins/decklink/decklink-device-mode.cpp b/plugins/decklink/decklink-device-mode.cpp index ed9a5a1d469119..8385b28048fb06 100644 --- a/plugins/decklink/decklink-device-mode.cpp +++ b/plugins/decklink/decklink-device-mode.cpp @@ -2,12 +2,14 @@ DeckLinkDeviceMode::DeckLinkDeviceMode(IDeckLinkDisplayMode *mode, long long id) : id(id), mode(mode) { - if (mode == nullptr) + if (mode == nullptr) { return; + } decklink_string_t decklinkStringName; - if (mode->GetName(&decklinkStringName) == S_OK) + if (mode->GetName(&decklinkStringName) == S_OK) { DeckLinkStringToStdString(decklinkStringName, name); + } } DeckLinkDeviceMode::DeckLinkDeviceMode(const std::string &name, long long id) : id(id), mode(nullptr), name(name) {} @@ -16,40 +18,45 @@ DeckLinkDeviceMode::~DeckLinkDeviceMode(void) {} BMDDisplayMode DeckLinkDeviceMode::GetDisplayMode(void) const { - if (mode != nullptr) + if (mode != nullptr) { return mode->GetDisplayMode(); + } return bmdModeUnknown; } int DeckLinkDeviceMode::GetWidth() { - if (mode != nullptr) + if (mode != nullptr) { return mode->GetWidth(); + } return 0; } int DeckLinkDeviceMode::GetHeight() { - if (mode != nullptr) + if (mode != nullptr) { return mode->GetHeight(); + } return 0; } bool DeckLinkDeviceMode::GetFrameRate(BMDTimeValue *frameDuration, BMDTimeScale *timeScale) { - if (mode != nullptr) + if (mode != nullptr) { return SUCCEEDED(mode->GetFrameRate(frameDuration, timeScale)); + } return false; } BMDDisplayModeFlags DeckLinkDeviceMode::GetDisplayModeFlags(void) const { - if (mode != nullptr) + if (mode != nullptr) { return mode->GetFlags(); + } return (BMDDisplayModeFlags)0; } @@ -71,8 +78,9 @@ bool DeckLinkDeviceMode::IsEqualFrameRate(int64_t num, int64_t den) if (mode) { BMDTimeValue frameDuration; BMDTimeScale timeScale; - if (SUCCEEDED(mode->GetFrameRate(&frameDuration, &timeScale))) + if (SUCCEEDED(mode->GetFrameRate(&frameDuration, &timeScale))) { equal = timeScale * den == frameDuration * num; + } } return equal; diff --git a/plugins/decklink/decklink-device.cpp b/plugins/decklink/decklink-device.cpp index ec144b9cecd56f..b1af53837fc732 100644 --- a/plugins/decklink/decklink-device.cpp +++ b/plugins/decklink/decklink-device.cpp @@ -8,11 +8,13 @@ DeckLinkDevice::DeckLinkDevice(IDeckLink *device_) : device(device_) {} DeckLinkDevice::~DeckLinkDevice(void) { - for (DeckLinkDeviceMode *mode : inputModes) + for (DeckLinkDeviceMode *mode : inputModes) { delete mode; + } - for (DeckLinkDeviceMode *mode : outputModes) + for (DeckLinkDeviceMode *mode : outputModes) { delete mode; + } } ULONG DeckLinkDevice::AddRef() @@ -23,8 +25,9 @@ ULONG DeckLinkDevice::AddRef() ULONG DeckLinkDevice::Release() { long ret = os_atomic_dec_long(&refCount); - if (ret == 0) + if (ret == 0) { delete this; + } return ret; } @@ -50,8 +53,9 @@ bool DeckLinkDevice::Init() long long modeId = 1; while (modeIterator->Next(&displayMode) == S_OK) { - if (displayMode == nullptr) + if (displayMode == nullptr) { continue; + } DeckLinkDeviceMode *mode = new DeckLinkDeviceMode(displayMode, modeId); inputModes.push_back(mode); @@ -79,8 +83,9 @@ bool DeckLinkDevice::Init() long long modeId = 1; while (modeIterator->Next(&displayMode) == S_OK) { - if (displayMode == nullptr) + if (displayMode == nullptr) { continue; + } DeckLinkDeviceMode *mode = new DeckLinkDeviceMode(displayMode, modeId); outputModes.push_back(mode); @@ -107,27 +112,31 @@ bool DeckLinkDevice::Init() decklink_string_t decklinkModelName; decklink_string_t decklinkDisplayName; - if (device->GetModelName(&decklinkModelName) != S_OK) + if (device->GetModelName(&decklinkModelName) != S_OK) { return false; + } DeckLinkStringToStdString(decklinkModelName, name); - if (device->GetDisplayName(&decklinkDisplayName) != S_OK) + if (device->GetDisplayName(&decklinkDisplayName) != S_OK) { return false; + } DeckLinkStringToStdString(decklinkDisplayName, displayName); hash = displayName; - if (result != S_OK) + if (result != S_OK) { return true; + } int64_t channels; /* Intensity Shuttle for Thunderbolt return 2; however, it supports 8 channels */ - if (name == "Intensity Shuttle Thunderbolt") + 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 + } else { maxChannel = 2; + } /* http://forum.blackmagicdesign.com/viewtopic.php?f=12&t=33967 * BMDDeckLinkTopologicalID for older devices @@ -135,8 +144,9 @@ bool DeckLinkDevice::Init() int64_t value; if (attributes->GetInt(BMDDeckLinkPersistentID, &value) != S_OK && - attributes->GetInt(BMDDeckLinkTopologicalID, &value) != S_OK) + attributes->GetInt(BMDDeckLinkTopologicalID, &value) != S_OK) { return true; + } std::ostringstream os; os << value << "_" << name; @@ -146,15 +156,17 @@ bool DeckLinkDevice::Init() bool DeckLinkDevice::GetInput(IDeckLinkInput **input) { - if (device->QueryInterface(IID_IDeckLinkInput, (void **)input) != S_OK) + if (device->QueryInterface(IID_IDeckLinkInput, (void **)input) != S_OK) { return false; + } return true; } 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; } diff --git a/plugins/decklink/decklink-output.cpp b/plugins/decklink/decklink-output.cpp index 6d13e18b5a7f6b..beef09606ae76d 100644 --- a/plugins/decklink/decklink-output.cpp +++ b/plugins/decklink/decklink-output.cpp @@ -65,8 +65,9 @@ static bool decklink_output_start(void *data) return false; } - if (!decklink->deviceHash || !*decklink->deviceHash) + if (!decklink->deviceHash || !*decklink->deviceHash) { return false; + } decklink->audio_samplerate = aoi.samples_per_sec; decklink->audio_planes = 2; @@ -78,8 +79,9 @@ static bool decklink_output_start(void *data) device.Set(deviceEnum->FindByHash(decklink->deviceHash)); - if (!device) + if (!device) { return false; + } DeckLinkDeviceMode *mode = device->FindOutputMode(decklink->modeID); @@ -98,8 +100,9 @@ static bool decklink_output_start(void *data) device->SetKeyerMode(decklink->keyerMode); - if (!decklink->Activate(device, decklink->modeID)) + if (!decklink->Activate(device, decklink->modeID)) { return false; + } struct audio_convert_info conversion = {}; conversion.format = AUDIO_FORMAT_16BIT; @@ -108,8 +111,9 @@ static bool decklink_output_start(void *data) obs_output_set_audio_conversion(decklink->GetOutput(), &conversion); - if (!obs_output_begin_data_capture(decklink->GetOutput(), 0)) + if (!obs_output_begin_data_capture(decklink->GetOutput(), 0)) { return false; + } return true; } @@ -127,8 +131,9 @@ static void decklink_output_raw_video(void *data, struct video_data *frame) { auto *decklink = (DeckLinkOutput *)data; - if (!decklink->start_timestamp) + if (!decklink->start_timestamp) { decklink->start_timestamp = frame->timestamp; + } decklink->UpdateVideoFrame(frame); } @@ -142,16 +147,18 @@ static bool prepare_audio(DeckLinkOutput *decklink, const struct audio_data *fra uint64_t end_ts = frame->timestamp + duration; uint64_t cutoff; - if (end_ts <= decklink->start_timestamp) + if (end_ts <= decklink->start_timestamp) { return false; + } cutoff = decklink->start_timestamp - frame->timestamp; output->timestamp += cutoff; cutoff = util_mul_div64(cutoff, decklink->audio_samplerate, 1000000000ULL); - for (size_t i = 0; i < decklink->audio_planes; i++) + for (size_t i = 0; i < decklink->audio_planes; i++) { output->data[i] += decklink->audio_size * (uint32_t)cutoff; + } output->frames -= (uint32_t)cutoff; } @@ -164,11 +171,13 @@ static void decklink_output_raw_audio(void *data, struct audio_data *frames) auto *decklink = (DeckLinkOutput *)data; struct audio_data in; - if (!decklink->start_timestamp) + if (!decklink->start_timestamp) { return; + } - if (!prepare_audio(decklink, frames, &in)) + if (!prepare_audio(decklink, frames, &in)) { return; + } decklink->WriteAudio(&in); } diff --git a/plugins/decklink/decklink-source.cpp b/plugins/decklink/decklink-source.cpp index 6dcf6a7b5f1e66..1820a52161443f 100644 --- a/plugins/decklink/decklink-source.cpp +++ b/plugins/decklink/decklink-source.cpp @@ -49,10 +49,11 @@ static void decklink_update(void *data, obs_data_t *settings) 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) + if (chFmtInt == 7) { chFmtInt = SPEAKERS_5POINT1; - else if (chFmtInt < SPEAKERS_UNKNOWN || chFmtInt > SPEAKERS_7POINT1) + } else if (chFmtInt < SPEAKERS_UNKNOWN || chFmtInt > SPEAKERS_7POINT1) { chFmtInt = 2; + } speaker_layout channelFormat = (speaker_layout)chFmtInt; @@ -87,8 +88,9 @@ static void decklink_hide(void *data) { DeckLinkInput *decklink = (DeckLinkInput *)data; - if (decklink->dwns && decklink->Capturing()) + if (decklink->dwns && decklink->Capturing()) { decklink->Deactivate(); + } } static void decklink_get_defaults(obs_data_t *settings) diff --git a/plugins/decklink/linux/platform.cpp b/plugins/decklink/linux/platform.cpp index ac7f33f36094a0..ec4e7f47c6290f 100644 --- a/plugins/decklink/linux/platform.cpp +++ b/plugins/decklink/linux/platform.cpp @@ -2,8 +2,9 @@ bool DeckLinkStringToStdString(decklink_string_t input, std::string &output) { - if (input == nullptr) + if (input == nullptr) { return false; + } output = std::string(input); free((void *)input); diff --git a/plugins/decklink/mac/platform.cpp b/plugins/decklink/mac/platform.cpp index 213073235f19db..3f498acdb2e318 100644 --- a/plugins/decklink/mac/platform.cpp +++ b/plugins/decklink/mac/platform.cpp @@ -7,8 +7,9 @@ bool DeckLinkStringToStdString(decklink_string_t input, std::string &output) char *buffer = cfstr_copy_cstr(string, kCFStringEncodingASCII); - if (buffer) + if (buffer) { output = std::string(buffer); + } bfree(buffer); CFRelease(string); diff --git a/plugins/decklink/plugin-main.cpp b/plugins/decklink/plugin-main.cpp index 37cdfd854a3826..815c674d3f282b 100644 --- a/plugins/decklink/plugin-main.cpp +++ b/plugins/decklink/plugin-main.cpp @@ -45,12 +45,14 @@ bool log_sdk_version() bool obs_module_load(void) { - if (!log_sdk_version()) + if (!log_sdk_version()) { return false; + } deviceEnum = new DeckLinkDeviceDiscovery(); - if (!deviceEnum->Init()) + if (!deviceEnum->Init()) { return false; + } decklink_source_info = create_decklink_source_info(); obs_register_source(&decklink_source_info); diff --git a/plugins/decklink/win/platform.cpp b/plugins/decklink/win/platform.cpp index 2b2cb8484082c8..68608603382675 100644 --- a/plugins/decklink/win/platform.cpp +++ b/plugins/decklink/win/platform.cpp @@ -29,8 +29,9 @@ IDeckLinkVideoConversion *CreateVideoConversionInstance(void) bool DeckLinkStringToStdString(decklink_string_t input, std::string &output) { - if (input == nullptr) + if (input == nullptr) { return false; + } char *out = _com_util::ConvertBSTRToString(input); output = std::string(out); diff --git a/plugins/mac-avcapture/legacy/left-right.hpp b/plugins/mac-avcapture/legacy/left-right.hpp index aefa84f383f685..c49911e084e986 100644 --- a/plugins/mac-avcapture/legacy/left-right.hpp +++ b/plugins/mac-avcapture/legacy/left-right.hpp @@ -19,14 +19,16 @@ template struct left_right { auto cur = current.load(); auto next = (cur + 1) & 1; - while (readers[next] != 0) + while (readers[next] != 0) { std::this_thread::yield(); + } f(data[next]); current = (std::uint_fast8_t)next; - while (readers[cur] != 0) + while (readers[cur] != 0) { std::this_thread::yield(); + } f(data[cur]); } @@ -38,8 +40,9 @@ template struct left_right { readers[cur] += 1; auto cur_ = current.load(); - if (cur_ == cur) + if (cur_ == cur) { break; + } readers[cur] -= 1; cur = cur_; diff --git a/plugins/mac-avcapture/legacy/scope-guard.hpp b/plugins/mac-avcapture/legacy/scope-guard.hpp index cb1dc4e9594b4c..471db17770c324 100644 --- a/plugins/mac-avcapture/legacy/scope-guard.hpp +++ b/plugins/mac-avcapture/legacy/scope-guard.hpp @@ -23,8 +23,9 @@ template class ScopeGuard { ~ScopeGuard() noexcept { - if (!dismissed_) + if (!dismissed_) { execute(); + } } private: 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 1a1604f3a23512..48e58f7c9a8a58 100644 --- a/plugins/obs-ffmpeg/obs-amf-test/obs-amf-test.cpp +++ b/plugins/obs-ffmpeg/obs-amf-test/obs-amf-test.cpp @@ -58,8 +58,9 @@ static bool get_adapter_caps(IDXGIFactory *factory, uint32_t adapter_idx) ComPtr adapter; hr = factory->EnumAdapters(adapter_idx, &adapter); - if (FAILED(hr)) + if (FAILED(hr)) { return false; + } DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); @@ -67,8 +68,9 @@ static bool get_adapter_caps(IDXGIFactory *factory, uint32_t adapter_idx) uint32_t luid_idx = get_adapter_idx(adapter_idx, desc.AdapterLuid); adapter_caps &caps = adapter_info[luid_idx]; - if (desc.VendorId != AMD_VENDOR_ID) + if (desc.VendorId != AMD_VENDOR_ID) { return true; + } caps.is_amd = true; @@ -76,17 +78,20 @@ static bool get_adapter_caps(IDXGIFactory *factory, uint32_t adapter_idx) ComPtr context; hr = D3D11CreateDevice(adapter, D3D_DRIVER_TYPE_UNKNOWN, nullptr, 0, nullptr, 0, D3D11_SDK_VERSION, &device, nullptr, &context); - if (FAILED(hr)) + if (FAILED(hr)) { return true; + } AMFContextPtr amf_context; res = amf_factory->CreateContext(&amf_context); - if (res != AMF_OK) + if (res != AMF_OK) { return true; + } res = amf_context->InitDX11(device); - if (res != AMF_OK) + if (res != AMF_OK) { return true; + } caps.supports_avc = has_encoder(amf_context, AMFVideoEncoderVCE_AVC); caps.supports_hevc = has_encoder(amf_context, AMFVideoEncoder_HEVC); @@ -100,8 +105,9 @@ DWORD WINAPI TimeoutThread(LPVOID param) HANDLE hMainThread = (HANDLE)param; DWORD ret = WaitForSingleObject(hMainThread, 2500); - if (ret == WAIT_TIMEOUT) + if (ret == WAIT_TIMEOUT) { TerminateProcess(GetCurrentProcess(), STATUS_TIMEOUT); + } CloseHandle(hMainThread); @@ -126,16 +132,19 @@ try { /* try initializing amf, I guess */ HMODULE amf_module = LoadLibraryW(AMF_DLL_NAME); - if (!amf_module) + if (!amf_module) { throw "Failed to load AMF lib"; + } auto init = (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME); - if (!init) + if (!init) { throw "Failed to get init func"; + } res = init(AMF_FULL_VERSION, &amf_factory); - if (res != AMF_OK) + if (res != AMF_OK) { throw "AMFInit failed"; + } /* --------------------------------------------------------- */ /* parse expected LUID order */ @@ -148,8 +157,9 @@ try { /* obtain adapter compatibility information */ hr = CreateDXGIFactory1(__uuidof(IDXGIFactory), (void **)&factory); - if (FAILED(hr)) + if (FAILED(hr)) { throw "CreateDXGIFactory1 failed"; + } uint32_t idx = 0; while (get_adapter_caps(factory, idx++)) diff --git a/plugins/obs-ffmpeg/texture-amf-opts.hpp b/plugins/obs-ffmpeg/texture-amf-opts.hpp index c052bd78b05a9b..2685308b703437 100644 --- a/plugins/obs-ffmpeg/texture-amf-opts.hpp +++ b/plugins/obs-ffmpeg/texture-amf-opts.hpp @@ -1,15 +1,20 @@ static bool str_to_bool(const char *str) { - if (!str) + if (!str) { return false; - if (*str == '1') + } + if (*str == '1') { return true; - if (*str == '0') + } + if (*str == '0') { return false; - if (astrcmpi(str, "true") == 0) + } + if (astrcmpi(str, "true") == 0) { return true; - if (astrcmpi(str, "false") == 0) + } + if (astrcmpi(str, "false") == 0) { return false; + } return false; } @@ -22,33 +27,36 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) if (strcmp(opt->name, "g") == 0 || strcmp(opt->name, "keyint") == 0) { int val = atoi(opt->value); - if (avc) + if (avc) { set_avc_opt(IDR_PERIOD, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(NUM_GOPS_PER_IDR, val); - else if (av1) + } else if (av1) { set_av1_opt(GOP_SIZE, val); + } } else if (strcmp(opt->name, "usage") == 0) { if (strcmp(opt->value, "transcoding") == 0) { set_enum_opt(USAGE, TRANSCODING); } else if (strcmp(opt->value, "ultralowlatency") == 0) { - if (avc) + if (avc) { set_avc_enum(USAGE, ULTRA_LOW_LATENCY); - else if (hevc) + } else if (hevc) { set_hevc_enum(USAGE, ULTRA_LOW_LATENCY); - else + } else { 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) { - if (avc) + if (avc) { set_avc_enum(USAGE, WEBCAM); - else if (hevc) + } else if (hevc) { set_hevc_enum(USAGE, WEBCAM); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else { warn("Invalid value for %s: %s", opt->name, opt->value); } @@ -76,16 +84,18 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) std::string val = opt->value; size_t pos = val.find('.'); - if (pos != std::string::npos) + if (pos != std::string::npos) { val.erase(pos, 1); + } int level = std::stoi(val); - if (avc) + if (avc) { set_avc_opt(PROFILE_LEVEL, level); - else if (hevc) + } else if (hevc) { set_hevc_opt(PROFILE_LEVEL, level); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "quality") == 0) { @@ -121,82 +131,90 @@ static void amf_apply_opt(amf_base *enc, obs_option *opt) } else if (strcmp(opt->name, "filler_data") == 0) { bool val = str_to_bool(opt->value); - if (avc) + if (avc) { set_avc_opt(FILLER_DATA_ENABLE, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(FILLER_DATA_ENABLE, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "vbaq") == 0) { bool val = str_to_bool(opt->value); - if (avc) + if (avc) { set_avc_opt(ENABLE_VBAQ, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(ENABLE_VBAQ, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "qp_i") == 0) { int val = atoi(opt->value); - if (avc) + if (avc) { set_avc_opt(QP_I, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(QP_I, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "qp_p") == 0) { int val = atoi(opt->value); - if (avc) + if (avc) { set_avc_opt(QP_P, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(QP_P, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "me_half_pel") == 0) { bool val = str_to_bool(opt->value); - if (avc) + if (avc) { set_avc_opt(MOTION_HALF_PIXEL, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(MOTION_HALF_PIXEL, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "me_quarter_pel") == 0) { bool val = str_to_bool(opt->value); - if (avc) + if (avc) { set_avc_opt(MOTION_QUARTERPIXEL, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(MOTION_QUARTERPIXEL, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "aud") == 0) { bool val = str_to_bool(opt->value); - if (avc) + if (avc) { set_avc_opt(INSERT_AUD, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(INSERT_AUD, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (strcmp(opt->name, "max_au_size") == 0) { int val = atoi(opt->value); - if (avc) + if (avc) { set_avc_opt(MAX_AU_SIZE, val); - else if (hevc) + } else if (hevc) { set_hevc_opt(MAX_AU_SIZE, val); - else + } else { warn("Invalid value for %s: %s", opt->name, opt->value); + } } else if (avc && strcmp(opt->name, "preanalysis") == 0) { diff --git a/plugins/obs-ffmpeg/texture-amf.cpp b/plugins/obs-ffmpeg/texture-amf.cpp index af9a5a3c5b6365..e9d2c905f55eb8 100644 --- a/plugins/obs-ffmpeg/texture-amf.cpp +++ b/plugins/obs-ffmpeg/texture-amf.cpp @@ -212,8 +212,9 @@ struct amf_texencode : amf_base, public AMFSurfaceObserver { void AMF_STD_CALL OnSurfaceDataRelease(amf::AMFSurface *surf) override { - if (os_atomic_load_bool(&destroying)) + if (os_atomic_load_bool(&destroying)) { return; + } std::scoped_lock lock(textures_mutex); @@ -227,8 +228,9 @@ struct amf_texencode : amf_base, public AMFSurfaceObserver { void init() override { AMF_RESULT res = amf_context->InitDX11(device, AMF_DX11_1); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("InitDX11 failed", res); + } } }; @@ -244,8 +246,9 @@ struct amf_fallback : amf_base, public AMFSurfaceObserver { void AMF_STD_CALL OnSurfaceDataRelease(amf::AMFSurface *surf) override { - if (os_atomic_load_bool(&destroying)) + if (os_atomic_load_bool(&destroying)) { return; + } std::scoped_lock lock(buffers_mutex); @@ -259,8 +262,9 @@ struct amf_fallback : amf_base, public AMFSurfaceObserver { void init() override { AMF_RESULT res = amf_context->InitDX11(nullptr, AMF_DX11_1); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("InitDX11 failed", res); + } } }; @@ -276,8 +280,9 @@ template static bool get_amf_property(amf_base *enc, const wchar_t * 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) + if (res != AMF_OK) { 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) @@ -308,8 +313,9 @@ template static void set_amf_property(amf_base *enc, const wchar_t * static HMODULE get_lib(const char *lib) { HMODULE mod = GetModuleHandleA(lib); - if (mod) + if (mod) { return mod; + } return LoadLibraryA(lib); } @@ -331,36 +337,42 @@ try { DXGI_ADAPTER_DESC desc; HRESULT hr; - if (!dxgi || !d3d11) + if (!dxgi || !d3d11) { 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"); - if (!create_dxgi || !create_device) + if (!create_dxgi || !create_device) { throw "Failed to load D3D11/DXGI procedures"; + } hr = create_dxgi(__uuidof(IDXGIFactory2), (void **)&factory); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("CreateDXGIFactory1 failed", hr); + } obs_video_info ovi; obs_get_video_info(&ovi); hr = factory->EnumAdapters(ovi.adapter, &adapter); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("EnumAdapters failed", hr); + } adapter->GetDesc(&desc); - if (desc.VendorId != AMD_VENDOR_ID) + if (desc.VendorId != AMD_VENDOR_ID) { 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); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("D3D11CreateDevice failed", hr); + } enc->device = device; enc->context = context; @@ -386,8 +398,9 @@ static void add_output_tex(amf_texencode *enc, ComPtr &output_t desc.MiscFlags = 0; hr = device->CreateTexture2D(&desc, nullptr, &output_tex); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create texture", hr); + } } static inline bool get_available_tex(amf_texencode *enc, ComPtr &output_tex) @@ -404,8 +417,9 @@ static inline bool get_available_tex(amf_texencode *enc, ComPtr static inline void get_output_tex(amf_texencode *enc, ComPtr &output_tex, ID3D11Texture2D *from) { - if (!get_available_tex(enc, output_tex)) + 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, @@ -425,12 +439,14 @@ static void get_tex_from_handle(amf_texencode *enc, uint32_t handle, IDXGIKeyedM } hr = device->OpenSharedResource((HANDLE)(uintptr_t)handle, __uuidof(ID3D11Resource), (void **)&tex); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("OpenSharedResource failed", hr); + } ComQIPtr km(tex); - if (!km) + if (!km) { throw "QueryInterface(IDXGIKeyedMutex) failed"; + } tex->SetEvictionPriority(DXGI_RESOURCE_PRIORITY_MAXIMUM); @@ -460,16 +476,19 @@ static inline int get_av1_preset(amf_base *enc, const char *preset); static inline int get_preset(amf_base *enc, const char *preset) { - if (enc->codec == amf_codec_type::AVC) + if (enc->codec == amf_codec_type::AVC) { return get_avc_preset(enc, preset); + } #if ENABLE_HEVC - else if (enc->codec == amf_codec_type::HEVC) + else if (enc->codec == amf_codec_type::HEVC) { return get_hevc_preset(enc, preset); + } #endif - else if (enc->codec == amf_codec_type::AV1) + else if (enc->codec == amf_codec_type::AV1) { return get_av1_preset(enc, preset); + } return 0; } @@ -545,8 +564,9 @@ static inline int64_t convert_to_obs_ts(amf_base *enc, int64_t ts) static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data, encoder_packet *packet) { - if (!data) + if (!data) { return; + } enc->packet_data = AMFBufferPtr(data); data->GetProperty(L"PTS", &packet->pts); @@ -566,10 +586,11 @@ static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data, encoder_p uint64_t type = 0; AMF_RESULT res = data->GetProperty(get_output_type, &type); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("Failed to GetProperty(): encoder output " "data type", res); + } if (enc->codec == amf_codec_type::AVC || enc->codec == amf_codec_type::HEVC) { switch (type) { @@ -610,8 +631,9 @@ static void convert_to_encoder_packet(amf_base *enc, AMFDataPtr &data, encoder_p packet->dts = convert_to_obs_ts(enc, data->GetPts()); packet->keyframe = type == AMF_VIDEO_ENCODER_OUTPUT_DATA_TYPE_IDR; - if (enc->dts_offset && enc->codec != amf_codec_type::AV1) + if (enc->dts_offset && enc->codec != amf_codec_type::AV1) { packet->dts -= enc->dts_offset; + } } #ifndef SEC_TO_NSEC @@ -631,8 +653,9 @@ static void roi_cb(void *param, obs_encoder_roi *roi) const roi_params *rp = static_cast(param); /* AMF does not support negative priority */ - if (roi->priority < 0) + if (roi->priority < 0) { return; + } const uint32_t mb_size = rp->h264 ? 16 : 64; const uint32_t roi_left = roi->left / mb_size; @@ -643,12 +666,14 @@ static void roi_cb(void *param, obs_encoder_roi *roi) const amf_uint32 priority = (amf_uint32)(10.0f * roi->priority); for (uint32_t mb_y = 0; mb_y < rp->mb_height; mb_y++) { - if (mb_y < roi_top || mb_y > roi_bottom) + if (mb_y < roi_top || mb_y > roi_bottom) { continue; + } for (uint32_t mb_x = 0; mb_x < rp->mb_width; mb_x++) { - if (mb_x < roi_left || mb_x > roi_right) + if (mb_x < roi_left || mb_x > roi_right) { continue; + } rp->buf[mb_y * rp->pitch / sizeof(amf_uint32) + mb_x] = priority; } @@ -658,8 +683,9 @@ 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; const uint32_t mb_height = (enc->cy + mb_size - 1) / mb_size; @@ -693,15 +719,17 @@ static void add_roi(amf_base *enc, AMFSurface *amf_surf) { const uint32_t increment = obs_encoder_get_roi_increment(enc->encoder); - if (increment != enc->roi_increment || !enc->roi_increment) + if (increment != enc->roi_increment || !enc->roi_increment) { create_roi(enc, amf_surf); + } - if (enc->codec == amf_codec_type::AVC) + 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) + } else if (enc->codec == amf_codec_type::HEVC) { amf_surf->SetProperty(AMF_VIDEO_ENCODER_HEVC_ROI_DATA, enc->roi_map); - else if (enc->codec == amf_codec_type::AV1) + } else if (enc->codec == amf_codec_type::AV1) { 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) @@ -716,8 +744,9 @@ static void amf_encode_base(amf_base *enc, AMFSurface *amf_surf, encoder_packet while (waiting) { /* ----------------------------------- */ /* add ROI data (if any) */ - if (enc->roi_supported && obs_encoder_has_roi(enc->encoder)) + if (enc->roi_supported && obs_encoder_has_roi(enc->encoder)) { add_roi(enc, amf_surf); + } /* ----------------------------------- */ /* submit frame */ @@ -746,8 +775,9 @@ static void amf_encode_base(amf_base *enc, AMFSurface *amf_surf, encoder_packet AMFDataPtr new_packet; do { res = enc->amf_encoder->QueryOutput(&new_packet); - if (new_packet) + if (new_packet) { queued_packets.push_back(new_packet); + } if (res != AMF_REPEAT && res != AMF_OK) { throw amf_error("QueryOutput failed", res); @@ -807,8 +837,9 @@ try { /* map output tex to amf surface */ res = enc->amf_context->CreateSurfaceFromDX11Native(output_tex, &amf_surf, enc); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("CreateSurfaceFromDX11Native failed", res); + } int64_t last_ts = convert_to_amf_ts(enc, pts - 1); int64_t cur_ts = convert_to_amf_ts(enc, pts); @@ -901,8 +932,9 @@ try { AMF_RESULT res; buf_t buf; - if (!enc->linesize) + if (!enc->linesize) { enc->linesize = frame->linesize[0]; + } buf = get_buf(enc); @@ -910,8 +942,9 @@ try { res = enc->amf_context->CreateSurfaceFromHostNative(enc->amf_format, enc->cx, enc->cy, enc->linesize, 0, &buf[0], &amf_surf, enc); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("CreateSurfaceFromHostNative failed", res); + } int64_t last_ts = convert_to_amf_ts(enc, frame->pts - 1); int64_t cur_ts = convert_to_amf_ts(enc, frame->pts); @@ -945,8 +978,9 @@ try { static bool amf_extra_data(void *data, uint8_t **header, size_t *size) { amf_base *enc = (amf_base *)data; - if (!enc->header) + if (!enc->header) { return false; + } *header = (uint8_t *)enc->header->GetNative(); *size = enc->header->GetSize(); @@ -1016,12 +1050,13 @@ try { info.range = voi->range; if (enc->fallback) { - if (enc->codec == amf_codec_type::AVC) + if (enc->codec == amf_codec_type::AVC) { h264_video_info_fallback(NULL, &info); - else if (enc->codec == amf_codec_type::HEVC) + } else if (enc->codec == amf_codec_type::HEVC) { h265_video_info_fallback(NULL, &info); - else + } else { av1_video_info_fallback(NULL, &info); + } } enc->cx = obs_encoder_get_width(enc->encoder); @@ -1081,8 +1116,9 @@ try { /* create encoder */ res = amf_factory->CreateContext(&enc->amf_context); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("CreateContext failed", res); + } enc->init(); @@ -1101,8 +1137,9 @@ try { codec = AMFVideoEncoder_HEVC; } res = amf_factory->CreateComponent(enc->amf_context, codec, &enc->amf_encoder); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("CreateComponent failed", res); + } calc_throughput(enc); return true; @@ -1126,13 +1163,15 @@ static void check_texture_encode_capability(obs_encoder_t *encoder, amf_codec_ty 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) { if (!obs_encoder_video_tex_active(encoder, VIDEO_FORMAT_NV12) && - !obs_encoder_video_tex_active(encoder, VIDEO_FORMAT_P010)) + !obs_encoder_video_tex_active(encoder, VIDEO_FORMAT_P010)) { throw "NV12/P010 textures aren't active"; + } } else if (!obs_encoder_video_tex_active(encoder, VIDEO_FORMAT_NV12)) { throw "NV12 textures aren't active"; } @@ -1152,8 +1191,9 @@ static void check_texture_encode_capability(obs_encoder_t *encoder, amf_codec_ty } if ((avc && !caps[ovi.adapter].supports_avc) || (hevc && !caps[ovi.adapter].supports_hevc) || - (av1 && !caps[ovi.adapter].supports_av1)) + (av1 && !caps[ovi.adapter].supports_av1)) { throw "Wrong adapter"; + } } #include "texture-amf-opts.hpp" @@ -1226,11 +1266,13 @@ static obs_properties_t *amf_properties_internal(amf_codec_type codec) OBS_COMBO_FORMAT_STRING); #define add_profile(val) obs_property_list_add_string(p, val, val) - if (amf_codec_type::AVC == codec) + if (amf_codec_type::AVC == codec) { add_profile("high"); + } add_profile("main"); - if (amf_codec_type::AVC == codec) + if (amf_codec_type::AVC == codec) { add_profile("baseline"); + } #undef add_profile } @@ -1275,30 +1317,32 @@ static const char *amf_avc_get_name(void *) static inline int get_avc_preset(amf_base *enc, const char *preset) { - if (astrcmpi(preset, "quality") == 0) + if (astrcmpi(preset, "quality") == 0) { return AMF_VIDEO_ENCODER_QUALITY_PRESET_QUALITY; - else if (astrcmpi(preset, "speed") == 0) + } else if (astrcmpi(preset, "speed") == 0) { return AMF_VIDEO_ENCODER_QUALITY_PRESET_SPEED; + } return AMF_VIDEO_ENCODER_QUALITY_PRESET_BALANCED; } static inline int get_avc_rate_control(const char *rc_str) { - if (astrcmpi(rc_str, "cqp") == 0) + if (astrcmpi(rc_str, "cqp") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CONSTANT_QP; - else if (astrcmpi(rc_str, "cbr") == 0) + } else if (astrcmpi(rc_str, "cbr") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR; - else if (astrcmpi(rc_str, "vbr") == 0) + } else if (astrcmpi(rc_str, "vbr") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR; - else if (astrcmpi(rc_str, "vbr_lat") == 0) + } else if (astrcmpi(rc_str, "vbr_lat") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR; - else if (astrcmpi(rc_str, "qvbr") == 0) + } else if (astrcmpi(rc_str, "qvbr") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_QUALITY_VBR; - else if (astrcmpi(rc_str, "hqvbr") == 0) + } else if (astrcmpi(rc_str, "hqvbr") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR; - else if (astrcmpi(rc_str, "hqcbr") == 0) + } else if (astrcmpi(rc_str, "hqcbr") == 0) { return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_HIGH_QUALITY_CBR; + } return AMF_VIDEO_ENCODER_RATE_CONTROL_METHOD_CBR; } @@ -1307,14 +1351,15 @@ static inline int get_avc_profile(obs_data_t *settings) { const char *profile = obs_data_get_string(settings, "profile"); - if (astrcmpi(profile, "baseline") == 0) + if (astrcmpi(profile, "baseline") == 0) { return AMF_VIDEO_ENCODER_PROFILE_BASELINE; - else if (astrcmpi(profile, "main") == 0) + } else if (astrcmpi(profile, "main") == 0) { return AMF_VIDEO_ENCODER_PROFILE_MAIN; - else if (astrcmpi(profile, "constrained_baseline") == 0) + } else if (astrcmpi(profile, "constrained_baseline") == 0) { return AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_BASELINE; - else if (astrcmpi(profile, "constrained_high") == 0) + } else if (astrcmpi(profile, "constrained_high") == 0) { return AMF_VIDEO_ENCODER_PROFILE_CONSTRAINED_HIGH; + } return AMF_VIDEO_ENCODER_PROFILE_HIGH; } @@ -1363,12 +1408,14 @@ try { amf_avc_update_data(enc, rc, bitrate * 1000, qp); res = enc->amf_encoder->Flush(); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::Flush failed", res); + } res = enc->amf_encoder->ReInit(enc->cx, enc->cy); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::ReInit failed", res); + } return true; @@ -1534,8 +1581,9 @@ static bool amf_avc_init(void *data, obs_data_t *settings) set_avc_property(enc, IDR_PERIOD, gop_size); bool repeat_headers = obs_data_get_bool(settings, "repeat_headers"); - if (repeat_headers) + if (repeat_headers) { set_avc_property(enc, HEADER_INSERTION_SPACING, gop_size); + } set_avc_property(enc, DE_BLOCKING_FILTER, true); @@ -1553,8 +1601,9 @@ static bool amf_avc_init(void *data, obs_data_t *settings) obs_free_options(opts); } - if (!ffmpeg_opts || !*ffmpeg_opts) + if (!ffmpeg_opts || !*ffmpeg_opts) { ffmpeg_opts = "(none)"; + } /* The ffmpeg_opts just above may have explicitly set the AVC level to a value different than what was * determined by amf_set_codec_level(). Query the final AVC level then lookup the matching string. Warn if not @@ -1593,8 +1642,9 @@ static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings) enc->codec = amf_codec_type::AVC; - if (!amf_create_encoder(enc)) + if (!amf_create_encoder(enc)) { throw "Failed to create encoder"; + } AMFCapsPtr caps; res = enc->amf_encoder->GetCaps(&caps); @@ -1623,22 +1673,25 @@ static void amf_avc_create_internal(amf_base *enc, obs_data_t *settings) amf_avc_init(enc, settings); res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::Init failed", res); + } res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_EXTRADATA, &p); - if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) + if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) { enc->header = AMFBufferPtr(p.pInterface); + } if (enc->bframes_supported) { amf_int64 b_frames = 0; amf_int64 b_max = 0; if (get_avc_property(enc, B_PIC_PATTERN, &b_frames) && - get_avc_property(enc, MAX_CONSECUTIVE_BPICTURES, &b_max)) + get_avc_property(enc, MAX_CONSECUTIVE_BPICTURES, &b_max)) { enc->dts_offset = b_frames + 1; - else + } else { enc->dts_offset = 0; + } } } @@ -1650,8 +1703,9 @@ try { enc->encoder = encoder; enc->encoder_str = "texture-amf-h264"; - if (!amf_init_d3d11(enc.get())) + if (!amf_init_d3d11(enc.get())) { throw "Failed to create D3D11"; + } amf_avc_create_internal(enc.get(), settings); return enc.release(); @@ -1749,30 +1803,32 @@ static const char *amf_hevc_get_name(void *) static inline int get_hevc_preset(amf_base *enc, const char *preset) { - if (astrcmpi(preset, "balanced") == 0) + if (astrcmpi(preset, "balanced") == 0) { return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_BALANCED; - else if (astrcmpi(preset, "speed") == 0) + } else if (astrcmpi(preset, "speed") == 0) { return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_SPEED; + } return AMF_VIDEO_ENCODER_HEVC_QUALITY_PRESET_QUALITY; } static inline int get_hevc_rate_control(const char *rc_str) { - if (astrcmpi(rc_str, "cqp") == 0) + if (astrcmpi(rc_str, "cqp") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CONSTANT_QP; - else if (astrcmpi(rc_str, "vbr_lat") == 0) + } else if (astrcmpi(rc_str, "vbr_lat") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR; - else if (astrcmpi(rc_str, "vbr") == 0) + } else if (astrcmpi(rc_str, "vbr") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR; - else if (astrcmpi(rc_str, "cbr") == 0) + } else if (astrcmpi(rc_str, "cbr") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR; - else if (astrcmpi(rc_str, "qvbr") == 0) + } else if (astrcmpi(rc_str, "qvbr") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_QUALITY_VBR; - else if (astrcmpi(rc_str, "hqvbr") == 0) + } else if (astrcmpi(rc_str, "hqvbr") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR; - else if (astrcmpi(rc_str, "hqcbr") == 0) + } else if (astrcmpi(rc_str, "hqcbr") == 0) { return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_HIGH_QUALITY_CBR; + } return AMF_VIDEO_ENCODER_HEVC_RATE_CONTROL_METHOD_CBR; } @@ -1820,12 +1876,14 @@ try { amf_hevc_update_data(enc, rc, bitrate * 1000, qp); res = enc->amf_encoder->Flush(); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::Flush failed", res); + } res = enc->amf_encoder->ReInit(enc->cx, enc->cy); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::ReInit failed", res); + } return true; @@ -1899,8 +1957,9 @@ static bool amf_hevc_init(void *data, obs_data_t *settings) obs_free_options(opts); } - if (!ffmpeg_opts || !*ffmpeg_opts) + if (!ffmpeg_opts || !*ffmpeg_opts) { ffmpeg_opts = "(none)"; + } /* The ffmpeg_opts just above may have explicitly set the HEVC level to a value different than what was * determined by amf_set_codec_level(). Query the final HEVC level then lookup the matching string. Warn if not @@ -1960,8 +2019,9 @@ static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings) enc->codec = amf_codec_type::HEVC; - if (!amf_create_encoder(enc)) + if (!amf_create_encoder(enc)) { throw "Failed to create encoder"; + } AMFCapsPtr caps; res = enc->amf_encoder->GetCaps(&caps); @@ -2015,12 +2075,14 @@ static void amf_hevc_create_internal(amf_base *enc, obs_data_t *settings) amf_hevc_init(enc, settings); res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::Init failed", res); + } res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_HEVC_EXTRADATA, &p); - if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) + 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) @@ -2031,8 +2093,9 @@ try { enc->encoder = encoder; enc->encoder_str = "texture-amf-h265"; - if (!amf_init_d3d11(enc.get())) + if (!amf_init_d3d11(enc.get())) { throw "Failed to create D3D11"; + } amf_hevc_create_internal(enc.get(), settings); return enc.release(); @@ -2137,34 +2200,36 @@ static const char *amf_av1_get_name(void *) static inline int get_av1_preset(amf_base *enc, const char *preset) { - if (astrcmpi(preset, "highquality") == 0) + if (astrcmpi(preset, "highquality") == 0) { return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_HIGH_QUALITY; - else if (astrcmpi(preset, "quality") == 0) + } else if (astrcmpi(preset, "quality") == 0) { return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_QUALITY; - else if (astrcmpi(preset, "balanced") == 0) + } else if (astrcmpi(preset, "balanced") == 0) { return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED; - else if (astrcmpi(preset, "speed") == 0) + } else if (astrcmpi(preset, "speed") == 0) { return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_SPEED; + } return AMF_VIDEO_ENCODER_AV1_QUALITY_PRESET_BALANCED; } static inline int get_av1_rate_control(const char *rc_str) { - if (astrcmpi(rc_str, "cqp") == 0) + if (astrcmpi(rc_str, "cqp") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CONSTANT_QP; - else if (astrcmpi(rc_str, "vbr_lat") == 0) + } else if (astrcmpi(rc_str, "vbr_lat") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_LATENCY_CONSTRAINED_VBR; - else if (astrcmpi(rc_str, "vbr") == 0) + } else if (astrcmpi(rc_str, "vbr") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_PEAK_CONSTRAINED_VBR; - else if (astrcmpi(rc_str, "cbr") == 0) + } else if (astrcmpi(rc_str, "cbr") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR; - else if (astrcmpi(rc_str, "qvbr") == 0) + } else if (astrcmpi(rc_str, "qvbr") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_QUALITY_VBR; - else if (astrcmpi(rc_str, "hqvbr") == 0) + } else if (astrcmpi(rc_str, "hqvbr") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_VBR; - else if (astrcmpi(rc_str, "hqcbr") == 0) + } else if (astrcmpi(rc_str, "hqcbr") == 0) { return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_HIGH_QUALITY_CBR; + } return AMF_VIDEO_ENCODER_AV1_RATE_CONTROL_METHOD_CBR; } @@ -2173,8 +2238,9 @@ static inline int get_av1_profile(obs_data_t *settings) { const char *profile = obs_data_get_string(settings, "profile"); - if (astrcmpi(profile, "main") == 0) + if (astrcmpi(profile, "main") == 0) { return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN; + } return AMF_VIDEO_ENCODER_AV1_PROFILE_MAIN; } @@ -2224,12 +2290,14 @@ try { amf_av1_update_data(enc, rc, bitrate * 1000, cq_level); res = enc->amf_encoder->Flush(); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::Flush failed", res); + } res = enc->amf_encoder->ReInit(enc->cx, enc->cy); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::ReInit failed", res); + } return true; @@ -2323,8 +2391,9 @@ static bool amf_av1_init(void *data, obs_data_t *settings) check_preset_compatibility(enc, preset); - if (!ffmpeg_opts || !*ffmpeg_opts) + if (!ffmpeg_opts || !*ffmpeg_opts) { ffmpeg_opts = "(none)"; + } /* The ffmpeg_opts just above may have explicitly set the AV1 level to a value different than what was * determined by amf_set_codec_level(). Query the final AV1 level then lookup the matching string. Warn if not @@ -2363,8 +2432,9 @@ static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings) { enc->codec = amf_codec_type::AV1; - if (!amf_create_encoder(enc)) + if (!amf_create_encoder(enc)) { throw "Failed to create encoder"; + } AMFCapsPtr caps; AMF_RESULT res = enc->amf_encoder->GetCaps(&caps); @@ -2403,23 +2473,26 @@ static void amf_av1_create_internal(amf_base *enc, obs_data_t *settings) amf_av1_init(enc, settings); res = enc->amf_encoder->Init(enc->amf_format, enc->cx, enc->cy); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFComponent::Init failed", res); + } AMFVariant p; res = enc->amf_encoder->GetProperty(AMF_VIDEO_ENCODER_AV1_EXTRA_DATA, &p); - if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) + if (res == AMF_OK && p.type == AMF_VARIANT_INTERFACE) { enc->header = AMFBufferPtr(p.pInterface); + } if (enc->bframes_supported) { amf_int64 b_frames = 0; amf_int64 b_max = 0; if (get_av1_property(enc, B_PIC_PATTERN, &b_frames) && - get_av1_property(enc, MAX_CONSECUTIVE_BPICTURES, &b_max)) + get_av1_property(enc, MAX_CONSECUTIVE_BPICTURES, &b_max)) { enc->dts_offset = b_frames + 1; - else + } else { enc->dts_offset = 0; + } } } @@ -2431,8 +2504,9 @@ try { enc->encoder = encoder; enc->encoder_str = "texture-amf-av1"; - if (!amf_init_d3d11(enc.get())) + if (!amf_init_d3d11(enc.get())) { throw "Failed to create D3D11"; + } amf_av1_create_internal(enc.get(), settings); return enc.release(); @@ -2546,8 +2620,9 @@ 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); - if (!amf_module_test) + if (!amf_module_test) { throw "No AMF library"; + } FreeLibrary(amf_module_test); /* ----------------------------------- */ @@ -2563,32 +2638,37 @@ try { enum_graphics_device_luids(enum_luids, &cmd); os_process_pipe_t *pp = os_process_pipe_create(cmd.str().c_str(), "r"); - if (!pp) + if (!pp) { throw "Failed to launch the AMF test process I guess"; + } for (;;) { char data[2048]; size_t len = os_process_pipe_read(pp, (uint8_t *)data, sizeof(data)); - if (!len) + if (!len) { break; + } caps_str.append(data, len); } os_process_pipe_destroy(pp); - if (caps_str.empty()) + if (caps_str.empty()) { throw "Seems the AMF test subprocess crashed. " "Better there than here I guess. " "Let's just skip loading AMF then I suppose."; + } ConfigFile config; - if (config.OpenString(caps_str.c_str()) != 0) + if (config.OpenString(caps_str.c_str()) != 0) { throw "Failed to open config string"; + } const char *error = config_get_string(config, "error", "string"); - if (error) + if (error) { throw std::string(error); + } uint32_t adapter_count = (uint32_t)config_num_sections(config); bool avc_supported = false; @@ -2609,35 +2689,42 @@ try { av1_supported |= info.supports_av1; } - if (!avc_supported && !hevc_supported && !av1_supported) + if (!avc_supported && !hevc_supported && !av1_supported) { throw "Neither AVC, HEVC, nor AV1 are supported by any devices"; + } /* ----------------------------------- */ /* Init AMF */ amf_module = LoadLibraryW(AMF_DLL_NAME); - if (!amf_module) + if (!amf_module) { throw "AMF library failed to load"; + } AMFInit_Fn init = (AMFInit_Fn)GetProcAddress(amf_module, AMF_INIT_FUNCTION_NAME); - if (!init) + if (!init) { throw "Failed to get AMFInit address"; + } res = init(AMF_FULL_VERSION, &amf_factory); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFInit failed", res); + } res = amf_factory->GetTrace(&amf_trace); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("GetTrace failed", res); + } AMFQueryVersion_Fn get_ver = (AMFQueryVersion_Fn)GetProcAddress(amf_module, AMF_QUERY_VERSION_FUNCTION_NAME); - if (!get_ver) + if (!get_ver) { throw "Failed to get AMFQueryVersion address"; + } res = get_ver(&amf_version); - if (res != AMF_OK) + if (res != AMF_OK) { throw amf_error("AMFQueryVersion failed", res); + } #ifndef DEBUG_AMF_STUFF amf_trace->EnableWriter(AMF_TRACE_WRITER_DEBUG_OUTPUT, false); @@ -2647,14 +2734,17 @@ try { /* ----------------------------------- */ /* Register encoders */ - if (avc_supported) + if (avc_supported) { register_avc(); + } #if ENABLE_HEVC - if (hevc_supported) + if (hevc_supported) { register_hevc(); + } #endif - if (av1_supported) + if (av1_supported) { register_av1(); + } } catch (const std::string &str) { /* doing debug here because string exceptions indicate the user is 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 e9631fd56b7c23..1a8abeb87d5914 100644 --- a/plugins/obs-nvenc/obs-nvenc-test/obs-nvenc-test.cpp +++ b/plugins/obs-nvenc/obs-nvenc-test/obs-nvenc-test.cpp @@ -137,8 +137,9 @@ struct NVML { ~NVML() { - if (initialised && shutdown) + if (initialised && shutdown) { shutdown(); + } } bool Init() @@ -213,8 +214,9 @@ struct CUDACtx { bool Init(int adapter_idx) { CUdevice dev; - if (cu->cuDeviceGet(&dev, adapter_idx) != CUDA_SUCCESS) + if (cu->cuDeviceGet(&dev, adapter_idx) != CUDA_SUCCESS) { return false; + } return cu->cuCtxCreate(&ctx, 0, dev) == CUDA_SUCCESS; } @@ -305,8 +307,9 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, device_info CUDACtx cudaCtx; NVSession nvSession; - if (!cudaCtx.Init(adapter_idx)) + if (!cudaCtx.Init(adapter_idx)) { return false; + } device_info.pci_id = cudaCtx.GetPCIBusId(); device_info.cuda_uuid = cudaCtx.GetUUID(); @@ -333,18 +336,21 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, device_info auto res = nvSession.OpenSession(cudaCtx); session_limit = session_limit || res == NV_ENC_ERR_INCOMPATIBLE_CLIENT_KEY; - if (res != NV_ENC_SUCCESS) + if (res != NV_ENC_SUCCESS) { 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); - if (stat != NV_ENC_SUCCESS) + if (stat != NV_ENC_SUCCESS) { return false; + } NV_ENC_CAPS_PARAM param = {NV_ENC_CAPS_PARAM_VER}; @@ -365,8 +371,9 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, device_info 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; caps[codec_name][name] = std::max(v, caps[codec_name][name]); @@ -393,16 +400,19 @@ static bool get_adapter_caps(int adapter_idx, codec_caps_map &caps, device_info bool nvenc_checks(codec_caps_map &caps, vector &device_infos) { /* NVENC API init */ - if (!init_nvenc()) + if (!init_nvenc()) { return false; + } /* CUDA init */ - if (!init_cuda()) + if (!init_cuda()) { return false; + } NVML nvml; - if (!nvml.Init()) + if (!nvml.Init()) { return false; + } /* --------------------------------------------------------- */ /* obtain adapter compatibility information */ @@ -447,8 +457,9 @@ bool nvenc_checks(codec_caps_map &caps, vector &device_infos) device_infos.resize(cuda_devices); for (int idx = 0; idx < cuda_devices; idx++) { - if (get_adapter_caps(idx, caps, device_infos[idx], nvml, session_limit)) + if (get_adapter_caps(idx, caps, device_infos[idx], nvml, session_limit)) { nvenc_devices++; + } } if (session_limit) { @@ -470,11 +481,13 @@ bool nvenc_checks(codec_caps_map &caps, vector &device_infos) uint32_t latest_architecture = 0; string_view architecture = "Unknown"; - for (auto &info : device_infos) + for (auto &info : device_infos) { latest_architecture = std::max(info.architecture, latest_architecture); + } - if (arch_to_name.count(latest_architecture)) + if (arch_to_name.count(latest_architecture)) { architecture = arch_to_name.at(latest_architecture); + } printf("latest_architecture=%u\n" "latest_architecture_name=%s\n", @@ -515,8 +528,9 @@ int check_thread() for (size_t idx = 0; idx < device_infos.size(); idx++) { const auto &info = device_infos[idx]; string_view architecture = "Unknown"; - if (arch_to_name.count(info.architecture)) + if (arch_to_name.count(info.architecture)) { architecture = arch_to_name.at(info.architecture); + } printf("\n[device.%zu]\n" "pci_id=%s\n" @@ -554,8 +568,9 @@ int main(int, char **) future f = async(launch::async, check_thread); future_status status = f.wait_for(2.5s); - if (status == future_status::timeout) + if (status == future_status::timeout) { exit(1); + } return f.get(); } diff --git a/plugins/obs-qsv11/QSV_Encoder.cpp b/plugins/obs-qsv11/QSV_Encoder.cpp index 67bf593469f48b..260c13662ab5e1 100644 --- a/plugins/obs-qsv11/QSV_Encoder.cpp +++ b/plugins/obs-qsv11/QSV_Encoder.cpp @@ -127,8 +127,9 @@ qsv_t *qsv_encoder_open(qsv_param_t *pParams, enum qsv_codec codec, bool useTexA #undef WARN_ERR_IMPL delete pEncoder; - if (pEncoder) + if (pEncoder) { is_active.store(false); + } return NULL; } @@ -165,15 +166,17 @@ int qsv_encoder_encode(qsv_t *pContext, uint64_t ts, uint8_t *pDataY, uint8_t *p QSV_Encoder_Internal *pEncoder = (QSV_Encoder_Internal *)pContext; mfxStatus sts = MFX_ERR_NONE; - if (pDataY != NULL && pDataUV != NULL) + if (pDataY != NULL && pDataUV != NULL) { sts = pEncoder->Encode(ts, pDataY, pDataUV, strideY, strideUV, pBS); + } - if (sts == MFX_ERR_NONE) + if (sts == MFX_ERR_NONE) { return 0; - else if (sts == MFX_ERR_MORE_DATA) + } else if (sts == MFX_ERR_MORE_DATA) { return 1; - else + } else { return -1; + } } int qsv_encoder_encode_tex(qsv_t *pContext, uint64_t ts, void *tex, uint64_t lock_key, uint64_t *next_key, @@ -184,12 +187,13 @@ int qsv_encoder_encode_tex(qsv_t *pContext, uint64_t ts, void *tex, uint64_t loc sts = pEncoder->Encode_tex(ts, tex, lock_key, next_key, pBS); - if (sts == MFX_ERR_NONE) + if (sts == MFX_ERR_NONE) { return 0; - else if (sts == MFX_ERR_MORE_DATA) + } else if (sts == MFX_ERR_MORE_DATA) { return 1; - else + } else { return -1; + } } int qsv_encoder_close(qsv_t *pContext) @@ -197,8 +201,9 @@ int qsv_encoder_close(qsv_t *pContext) QSV_Encoder_Internal *pEncoder = (QSV_Encoder_Internal *)pContext; delete pEncoder; - if (pEncoder) + if (pEncoder) { is_active.store(false); + } return 0; } @@ -227,8 +232,9 @@ int qsv_encoder_reconfig(qsv_t *pContext, qsv_param_t *pParams) pEncoder->UpdateParams(pParams); mfxStatus sts = pEncoder->ReconfigureEncoder(); - if (sts != MFX_ERR_NONE) + if (sts != MFX_ERR_NONE) { return false; + } return true; } @@ -244,8 +250,9 @@ enum qsv_cpu_platform qsv_get_cpu_platform() vendor += string((char *)&cpuInfo[3], 4); vendor += string((char *)&cpuInfo[2], 4); - if (vendor != "GenuineIntel") + if (vendor != "GenuineIntel") { return QSV_CPU_PLATFORM_UNKNOWN; + } util_cpuid(cpuInfo, 1); uint8_t model = ((cpuInfo[0] >> 4) & 0xF) + ((cpuInfo[0] >> 12) & 0xF0); @@ -253,8 +260,9 @@ enum qsv_cpu_platform qsv_get_cpu_platform() // See Intel 64 and IA-32 Architectures Software Developer's Manual, // Vol 3C Table 35-1 - if (family != 6) + if (family != 6) { return QSV_CPU_PLATFORM_UNKNOWN; + } switch (model) { case 0x1C: diff --git a/plugins/obs-qsv11/QSV_Encoder_Internal.cpp b/plugins/obs-qsv11/QSV_Encoder_Internal.cpp index d1a24d7bc5dfab..d37a7933c2c9e8 100644 --- a/plugins/obs-qsv11/QSV_Encoder_Internal.cpp +++ b/plugins/obs-qsv11/QSV_Encoder_Internal.cpp @@ -125,19 +125,21 @@ QSV_Encoder_Internal::QSV_Encoder_Internal(mfxVersion &version, bool useTexAlloc QSV_Encoder_Internal::~QSV_Encoder_Internal() { - if (m_pmfxENC) + if (m_pmfxENC) { ClearData(); + } } mfxStatus QSV_Encoder_Internal::Open(qsv_param_t *pParams, enum qsv_codec codec) { mfxStatus sts = MFX_ERR_NONE; - if (m_bUseD3D11 | m_bUseTexAlloc) + if (m_bUseD3D11 | m_bUseTexAlloc) { // Use texture surface sts = Initialize(m_ver, &m_session, &m_mfxAllocator, &g_GFX_Handle, false, codec, &m_sessionData); - else + } else { sts = Initialize(m_ver, &m_session, NULL, NULL, false, codec, &m_sessionData); + } MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); @@ -171,10 +173,12 @@ PRAGMA_WARN_DEPRECATION static inline bool HasOptimizedBRCSupport(const mfxPlatform &platform, const mfxVersion &version, mfxU16 rateControl) { #if (MFX_VERSION_MAJOR >= 2 && MFX_VERSION_MINOR >= 13) || MFX_VERSION_MAJOR > 2 - if ((version.Major >= 2 && version.Minor >= 13) || version.Major > 2) + if ((version.Major >= 2 && version.Minor >= 13) || version.Major > 2) { if (rateControl == MFX_RATECONTROL_CBR && - (platform.CodeName >= MFX_PLATFORM_BATTLEMAGE && platform.CodeName != MFX_PLATFORM_ALDERLAKE_N)) + (platform.CodeName >= MFX_PLATFORM_BATTLEMAGE && platform.CodeName != MFX_PLATFORM_ALDERLAKE_N)) { return true; + } + } #endif UNUSED_PARAMETER(platform); UNUSED_PARAMETER(version); @@ -186,10 +190,12 @@ static inline bool HasAV1ScreenContentSupport(const mfxPlatform &platform, const { #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 ((version.Major >= 2 && version.Minor >= 12) || version.Major > 2) { if (platform.CodeName >= MFX_PLATFORM_LUNARLAKE && platform.CodeName != MFX_PLATFORM_ALDERLAKE_N && - platform.CodeName != MFX_PLATFORM_ARROWLAKE) + platform.CodeName != MFX_PLATFORM_ARROWLAKE) { return true; + } + } #endif UNUSED_PARAMETER(platform); UNUSED_PARAMETER(version); @@ -201,12 +207,13 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, enum qsv_codec { memset(&m_mfxEncParams, 0, sizeof(m_mfxEncParams)); - if (codec == QSV_CODEC_AVC) + if (codec == QSV_CODEC_AVC) { m_mfxEncParams.mfx.CodecId = MFX_CODEC_AVC; - else if (codec == QSV_CODEC_AV1) + } else if (codec == QSV_CODEC_AV1) { m_mfxEncParams.mfx.CodecId = MFX_CODEC_AV1; - else if (codec == QSV_CODEC_HEVC) + } else if (codec == QSV_CODEC_HEVC) { m_mfxEncParams.mfx.CodecId = MFX_CODEC_HEVC; + } if (codec == QSV_CODEC_HEVC) { m_mfxEncParams.mfx.NumSlice = 0; @@ -240,8 +247,9 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, enum qsv_codec PRAGMA_WARN_PUSH PRAGMA_WARN_DEPRECATION if (codec == QSV_CODEC_AVC || codec == QSV_CODEC_HEVC) { - if (platform.CodeName >= MFX_PLATFORM_DG2) + if (platform.CodeName >= MFX_PLATFORM_DG2) { m_mfxEncParams.mfx.LowPower = MFX_CODINGOPTION_ON; + } } else if (codec == QSV_CODEC_AV1) { m_mfxEncParams.mfx.LowPower = MFX_CODINGOPTION_ON; } @@ -287,13 +295,15 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, enum qsv_codec memset(&m_co2, 0, sizeof(mfxExtCodingOption2)); m_co2.Header.BufferId = MFX_EXTBUFF_CODING_OPTION2; m_co2.Header.BufferSz = sizeof(m_co2); - if (pParams->bRepeatHeaders) + if (pParams->bRepeatHeaders) { m_co2.RepeatPPS = MFX_CODINGOPTION_ON; - else + } else { m_co2.RepeatPPS = MFX_CODINGOPTION_OFF; + } - if (pParams->nbFrames > 1) + if (pParams->nbFrames > 1) { m_co2.BRefType = MFX_B_REF_PYRAMID; + } PRAGMA_WARN_PUSH PRAGMA_WARN_DEPRECATION @@ -427,10 +437,11 @@ mfxStatus QSV_Encoder_Internal::InitParams(qsv_param_t *pParams, enum qsv_codec m_mfxEncParams.mfx.FrameInfo.Width = MSDK_ALIGN16(pParams->nWidth); m_mfxEncParams.mfx.FrameInfo.Height = MSDK_ALIGN16(pParams->nHeight); - if (m_bUseTexAlloc) + if (m_bUseTexAlloc) { m_mfxEncParams.IOPattern = MFX_IOPATTERN_IN_VIDEO_MEMORY; - else + } else { m_mfxEncParams.IOPattern = MFX_IOPATTERN_IN_SYSTEM_MEMORY; + } m_mfxEncParams.ExtParam = extendedBuffers.data(); m_mfxEncParams.NumExtParam = (mfxU16)extendedBuffers.size(); @@ -560,8 +571,9 @@ mfxStatus QSV_Encoder_Internal::GetVideoParam(enum qsv_codec codec) mfxStatus sts = m_pmfxENC->GetVideoParam(&m_parameter); MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); - if (codec == QSV_CODEC_HEVC) + if (codec == QSV_CODEC_HEVC) { m_nVPSBufferSize = opt_vps.VPSBufSize; + } m_nSPSBufferSize = opt.SPSBufSize; m_nPPSBufferSize = opt.PPSBufSize; @@ -638,15 +650,17 @@ mfxStatus QSV_Encoder_Internal::LoadP010(mfxFrameSurface1 *pSurface, uint8_t *pD const size_t line_size = w * 2; // load Y plane - for (i = 0; i < h; i++) + for (i = 0; i < h; i++) { memcpy(ptr + i * pitch, pDataY + i * strideY, line_size); + } // load UV plane h /= 2; ptr = pData->UV + pInfo->CropX + (pInfo->CropY / 2) * pitch; - for (i = 0; i < h; i++) + for (i = 0; i < h; i++) { memcpy(ptr + i * pitch, pDataUV + i * strideUV, line_size); + } return MFX_ERR_NONE; } @@ -671,25 +685,30 @@ mfxStatus QSV_Encoder_Internal::LoadNV12(mfxFrameSurface1 *pSurface, uint8_t *pD ptr = pData->Y + pInfo->CropX + pInfo->CropY * pData->Pitch; // load Y plane - for (i = 0; i < h; i++) + for (i = 0; i < h; i++) { memcpy(ptr + i * pitch, pDataY + i * strideY, w); + } // load UV plane h /= 2; ptr = pData->UV + pInfo->CropX + (pInfo->CropY / 2) * pitch; - for (i = 0; i < h; i++) + for (i = 0; i < h; i++) { memcpy(ptr + i * pitch, pDataUV + i * strideUV, w); + } return MFX_ERR_NONE; } int QSV_Encoder_Internal::GetFreeTaskIndex(Task *pTaskPool, mfxU16 nPoolSize) { - if (pTaskPool) - for (int i = 0; i < nPoolSize; i++) - if (!pTaskPool[i].syncp) + if (pTaskPool) { + for (int i = 0; i < nPoolSize; i++) { + if (!pTaskPool[i].syncp) { return i; + } + } + } return MFX_ERR_NOT_FOUND; } @@ -769,16 +788,18 @@ mfxStatus QSV_Encoder_Internal::Encode(uint64_t ts, uint8_t *pDataY, uint8_t *pD if (MFX_ERR_NONE < sts && !m_pTaskPool[nTaskIdx].syncp) { // Repeat the call if warning and no output - if (MFX_WRN_DEVICE_BUSY == sts) + if (MFX_WRN_DEVICE_BUSY == sts) { 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; } else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts) { // Allocate more bitstream buffer memory here if needed... break; - } else + } else { break; + } } return sts; @@ -827,16 +848,18 @@ mfxStatus QSV_Encoder_Internal::Encode_tex(uint64_t ts, void *tex, uint64_t lock if (MFX_ERR_NONE < sts && !m_pTaskPool[nTaskIdx].syncp) { // Repeat the call if warning and no output - if (MFX_WRN_DEVICE_BUSY == sts) + if (MFX_WRN_DEVICE_BUSY == sts) { 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; } else if (MFX_ERR_NOT_ENOUGH_BUFFER == sts) { // Allocate more bitstream buffer memory here if needed... break; - } else + } else { break; + } } return sts; @@ -868,13 +891,15 @@ mfxStatus QSV_Encoder_Internal::ClearData() m_pmfxENC = NULL; } - if (m_bUseTexAlloc) + if (m_bUseTexAlloc) { m_mfxAllocator.Free(m_mfxAllocator.pthis, &m_mfxResponse); + } if (m_pmfxSurfaces) { for (int i = 0; i < m_nSurfNum; i++) { - if (!m_bUseTexAlloc) + if (!m_bUseTexAlloc) { delete m_pmfxSurfaces[i]->Data.Y; + } delete m_pmfxSurfaces[i]; } @@ -882,8 +907,9 @@ mfxStatus QSV_Encoder_Internal::ClearData() } if (m_pTaskPool) { - for (int i = 0; i < m_nTaskPool; i++) + for (int i = 0; i < m_nTaskPool; i++) { delete m_pTaskPool[i].mfxBS.Data; + } MSDK_SAFE_DELETE_ARRAY(m_pTaskPool); } @@ -937,8 +963,9 @@ void QSV_Encoder_Internal::AddROI(mfxU32 left, mfxU32 top, mfxU32 right, mfxU32 m_roi.NumROI++; /* Right now ROI is the only thing we add so this is fine */ - if (m_extbuf.empty()) + if (m_extbuf.empty()) { m_extbuf.push_back((mfxExtBuffer *)&m_roi); + } m_ctrl.ExtParam = m_extbuf.data(); m_ctrl.NumExtParam = (mfxU16)m_extbuf.size(); diff --git a/plugins/obs-qsv11/common_directx11.cpp b/plugins/obs-qsv11/common_directx11.cpp index 013a8217566c36..07c933d0efa885 100644 --- a/plugins/obs-qsv11/common_directx11.cpp +++ b/plugins/obs-qsv11/common_directx11.cpp @@ -46,13 +46,15 @@ IDXGIAdapter *GetIntelDeviceAdapterHandle(mfxSession session) } HRESULT hres = CreateDXGIFactory1(__uuidof(IDXGIFactory2), (void **)(&g_pDXGIFactory)); - if (FAILED(hres)) + if (FAILED(hres)) { return NULL; + } IDXGIAdapter *adapter; hres = g_pDXGIFactory->EnumAdapters(adapterNum, &adapter); - if (FAILED(hres)) + if (FAILED(hres)) { return NULL; + } return adapter; } @@ -71,8 +73,9 @@ mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, bo D3D_FEATURE_LEVEL pFeatureLevelsOut; g_pAdapter = GetIntelDeviceAdapterHandle(session); - if (NULL == g_pAdapter) + if (NULL == g_pAdapter) { return MFX_ERR_DEVICE_FAILED; + } UINT dxFlags = 0; //UINT dxFlags = D3D11_CREATE_DEVICE_DEBUG; @@ -80,15 +83,17 @@ mfxStatus CreateHWDevice(mfxSession session, mfxHDL *deviceHandle, HWND hWnd, bo 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)) + if (FAILED(hres)) { return MFX_ERR_DEVICE_FAILED; + } // turn on multithreading for the DX11 context CComQIPtr p_mt(g_pD3D11Ctx); - if (p_mt) + if (p_mt) { p_mt->SetMultithreadProtected(true); - else + } else { return MFX_ERR_DEVICE_FAILED; + } *deviceHandle = (mfxHDL)g_pD3D11Device; @@ -149,27 +154,30 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *re // Determine surface format DXGI_FORMAT format; - if (MFX_FOURCC_NV12 == request->Info.FourCC) + if (MFX_FOURCC_NV12 == request->Info.FourCC) { format = DXGI_FORMAT_NV12; - else if (MFX_FOURCC_RGB4 == request->Info.FourCC) + } else if (MFX_FOURCC_RGB4 == request->Info.FourCC) { format = DXGI_FORMAT_B8G8R8A8_UNORM; - else if (MFX_FOURCC_YUY2 == request->Info.FourCC) + } 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) + } else if (MFX_FOURCC_P010 == request->Info.FourCC) { format = DXGI_FORMAT_P010; - else + } else { format = DXGI_FORMAT_UNKNOWN; + } - if (DXGI_FORMAT_UNKNOWN == format) + if (DXGI_FORMAT_UNKNOWN == format) { return MFX_ERR_UNSUPPORTED; + } // 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 *)); - if (!mids) + if (!mids) { return MFX_ERR_MEMORY_ALLOC; + } for (int i = 0; i < request->NumFrameSuggested; i++) { mids[i] = (CustomMemId *)calloc(1, sizeof(CustomMemId)); @@ -186,8 +194,9 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *re if (request->Info.FourCC == MFX_FOURCC_P8) { D3D11_BUFFER_DESC desc = {0}; - if (!request->NumFrameSuggested) + if (!request->NumFrameSuggested) { return MFX_ERR_MEMORY_ALLOC; + } desc.ByteWidth = request->Info.Width * request->Info.Height; desc.Usage = D3D11_USAGE_STAGING; @@ -198,8 +207,9 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *re ID3D11Buffer *buffer = 0; hRes = g_pD3D11Device->CreateBuffer(&desc, 0, &buffer); - if (FAILED(hRes)) + if (FAILED(hRes)) { return MFX_ERR_MEMORY_ALLOC; + } mids[0]->memId = reinterpret_cast(buffer); } else { @@ -218,19 +228,22 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *re if ((MFX_MEMTYPE_FROM_VPPIN & request->Type) && (DXGI_FORMAT_B8G8R8A8_UNORM == desc.Format)) { desc.BindFlags = D3D11_BIND_RENDER_TARGET; - if (desc.ArraySize > 2) + if (desc.ArraySize > 2) { return MFX_ERR_MEMORY_ALLOC; + } } if ((MFX_MEMTYPE_FROM_VPPOUT & request->Type) || (MFX_MEMTYPE_VIDEO_MEMORY_PROCESSOR_TARGET & request->Type)) { desc.BindFlags = D3D11_BIND_RENDER_TARGET; - if (desc.ArraySize > 2) + if (desc.ArraySize > 2) { return MFX_ERR_MEMORY_ALLOC; + } } - if (DXGI_FORMAT_P8 == desc.Format) + if (DXGI_FORMAT_P8 == desc.Format) { desc.BindFlags = 0; + } ID3D11Texture2D *pTexture2D; @@ -238,8 +251,9 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *re for (size_t i = 0; i < request->NumFrameSuggested / desc.ArraySize; i++) { hRes = g_pD3D11Device->CreateTexture2D(&desc, NULL, &pTexture2D); - if (FAILED(hRes)) + if (FAILED(hRes)) { return MFX_ERR_MEMORY_ALLOC; + } mids[i]->memId = pTexture2D; } @@ -255,8 +269,9 @@ mfxStatus _simple_alloc(mfxFrameAllocRequest *request, mfxFrameAllocResponse *re for (size_t i = 0; i < request->NumFrameSuggested; i++) { hRes = g_pD3D11Device->CreateTexture2D(&desc, NULL, &pTexture2D); - if (FAILED(hRes)) + if (FAILED(hRes)) { return MFX_ERR_MEMORY_ALLOC; + } mids[i]->memIdStage = pTexture2D; } @@ -272,8 +287,9 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllo { mfxStatus sts = MFX_ERR_NONE; - if (request->Type & MFX_MEMTYPE_SYSTEM_MEMORY) + if (request->Type & MFX_MEMTYPE_SYSTEM_MEMORY) { return MFX_ERR_UNSUPPORTED; + } if (allocDecodeResponses.find(pthis) != allocDecodeResponses.end() && MFX_MEMTYPE_EXTERNAL_FRAME & request->Type && MFX_MEMTYPE_FROM_DECODE & request->Type) { @@ -324,18 +340,21 @@ mfxStatus simple_lock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) pSurface->GetDesc(&desc); // copy data only in case of user wants to read from stored surface - if (memId->rw & WILL_READ) + if (memId->rw & WILL_READ) { 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) + if (S_OK != hRes && DXGI_ERROR_WAS_STILL_DRAWING != hRes) { return MFX_ERR_LOCK_MEMORY; + } } while (DXGI_ERROR_WAS_STILL_DRAWING == hRes); } - if (FAILED(hRes)) + if (FAILED(hRes)) { return MFX_ERR_LOCK_MEMORY; + } switch (desc.Format) { case DXGI_FORMAT_NV12: @@ -390,8 +409,9 @@ mfxStatus simple_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) } else { g_pD3D11Ctx->Unmap(pStage, 0); // copy data only in case of user wants to write to stored surface - if (memId->rw & WILL_WRITE) + if (memId->rw & WILL_WRITE) { g_pD3D11Ctx->CopySubresourceRegion(pSurface, 0, 0, 0, 0, pStage, 0, NULL); + } } if (ptr) { @@ -448,8 +468,9 @@ mfxStatus simple_gethdl(mfxHDL pthis, mfxMemId mid, mfxHDL *handle) { pthis; // To suppress warning for this unused parameter - if (NULL == handle) + if (NULL == handle) { return MFX_ERR_INVALID_HANDLE; + } mfxHDLPair *pPair = (mfxHDLPair *)handle; CustomMemId *memId = (CustomMemId *)mid; @@ -469,10 +490,12 @@ mfxStatus _simple_free(mfxFrameAllocResponse *response) ID3D11Texture2D *pSurface = (ID3D11Texture2D *)mid->memId; ID3D11Texture2D *pStage = (ID3D11Texture2D *)mid->memIdStage; - if (pSurface) + if (pSurface) { pSurface->Release(); - if (pStage) + } + if (pStage) { pStage->Release(); + } free(mid); } @@ -486,8 +509,9 @@ mfxStatus _simple_free(mfxFrameAllocResponse *response) mfxStatus simple_free(mfxHDL pthis, mfxFrameAllocResponse *response) { - if (NULL == response) + if (NULL == response) { return MFX_ERR_NULL_PTR; + } if (allocResponses.find(response->mids) == allocResponses.end()) { // Decode free response handling diff --git a/plugins/obs-qsv11/common_utils.cpp b/plugins/obs-qsv11/common_utils.cpp index 57e5161d9ba7a1..cb932fa7b5d386 100644 --- a/plugins/obs-qsv11/common_utils.cpp +++ b/plugins/obs-qsv11/common_utils.cpp @@ -84,10 +84,12 @@ mfxStatus ReadPlaneData(mfxU16 w, mfxU16 h, mfxU8 *buf, mfxU8 *ptr, mfxU16 pitch mfxU32 nBytesRead; for (mfxU16 i = 0; i < h; i++) { nBytesRead = (mfxU32)fread(buf, 1, w, fSource); - if (w != nBytesRead) + if (w != nBytesRead) { return MFX_ERR_MORE_DATA; - for (mfxU16 j = 0; j < w; j++) + } + for (mfxU16 j = 0; j < w; j++) { ptr[i * pitch + j * 2 + offset] = buf[j]; + } } return MFX_ERR_NONE; } @@ -97,10 +99,11 @@ mfxStatus LoadRawFrame(mfxFrameSurface1 *pSurface, FILE *fSource) if (!fSource) { // Simulate instantaneous access to 1000 "empty" frames. static int frameCount = 0; - if (1000 == frameCount++) + if (1000 == frameCount++) { return MFX_ERR_MORE_DATA; - else + } else { return MFX_ERR_NONE; + } } mfxStatus sts = MFX_ERR_NONE; @@ -124,25 +127,29 @@ mfxStatus LoadRawFrame(mfxFrameSurface1 *pSurface, FILE *fSource) // read luminance plane for (i = 0; i < h; i++) { nBytesRead = (mfxU32)fread(ptr + i * pitch, 1, w, fSource); - if (w != nBytesRead) + if (w != nBytesRead) { return MFX_ERR_MORE_DATA; + } } mfxU8 buf[2048]; // maximum supported chroma width for nv12 w /= 2; h /= 2; ptr = pData->UV + pInfo->CropX + (pInfo->CropY / 2) * pitch; - if (w > 2048) + if (w > 2048) { return MFX_ERR_UNSUPPORTED; + } // load U sts = ReadPlaneData(w, h, buf, ptr, pitch, 0, fSource); - if (MFX_ERR_NONE != sts) + if (MFX_ERR_NONE != sts) { return sts; + } // load V sts = ReadPlaneData(w, h, buf, ptr, pitch, 1, fSource); - if (MFX_ERR_NONE != sts) + if (MFX_ERR_NONE != sts) { return sts; + } return MFX_ERR_NONE; } @@ -152,10 +159,11 @@ mfxStatus LoadRawRGBFrame(mfxFrameSurface1 *pSurface, FILE *fSource) if (!fSource) { // Simulate instantaneous access to 1000 "empty" frames. static int frameCount = 0; - if (1000 == frameCount++) + if (1000 == frameCount++) { return MFX_ERR_MORE_DATA; - else + } else { return MFX_ERR_NONE; + } } size_t nBytesRead; @@ -172,8 +180,9 @@ 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); - if ((size_t)(w * 4) != nBytesRead) + if ((size_t)(w * 4) != nBytesRead) { return MFX_ERR_MORE_DATA; + } } return MFX_ERR_NONE; @@ -183,8 +192,9 @@ mfxStatus WriteBitStreamFrame(mfxBitstream *pMfxBitstream, FILE *fSink) { mfxU32 nBytesWritten = (mfxU32)fwrite(pMfxBitstream->Data + pMfxBitstream->DataOffset, 1, pMfxBitstream->DataLength, fSink); - if (nBytesWritten != pMfxBitstream->DataLength) + if (nBytesWritten != pMfxBitstream->DataLength) { return MFX_ERR_UNDEFINED_BEHAVIOR; + } pMfxBitstream->DataLength = 0; @@ -198,8 +208,9 @@ mfxStatus ReadBitStreamData(mfxBitstream *pBS, FILE *fSource) mfxU32 nBytesRead = (mfxU32)fread(pBS->Data + pBS->DataLength, 1, pBS->MaxLength - pBS->DataLength, fSource); - if (0 == nBytesRead) + if (0 == nBytesRead) { return MFX_ERR_MORE_DATA; + } pBS->DataLength += nBytesRead; @@ -210,8 +221,9 @@ mfxStatus WriteSection(mfxU8 *plane, mfxU16 factor, mfxU16 chunksize, mfxFrameIn mfxU32 i, mfxU32 j, FILE *fSink) { if (chunksize != fwrite(plane + (pInfo->CropY * pData->Pitch / factor + pInfo->CropX) + i * pData->Pitch + j, 1, - chunksize, fSink)) + chunksize, fSink)) { return MFX_ERR_UNDEFINED_BEHAVIOR; + } return MFX_ERR_NONE; } @@ -222,27 +234,35 @@ mfxStatus WriteRawFrame(mfxFrameSurface1 *pSurface, FILE *fSink) mfxU32 i, j, h, w; mfxStatus sts = MFX_ERR_NONE; - for (i = 0; i < pInfo->CropH; i++) + for (i = 0; i < pInfo->CropH; i++) { 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) + for (i = 0; i < h; i++) { + for (j = 0; j < w; j += 2) { sts = WriteSection(pData->UV, 2, 1, pInfo, pData, i, j, fSink); - for (i = 0; i < h; i++) - for (j = 1; j < w; j += 2) + } + } + for (i = 0; i < h; i++) { + for (j = 1; j < w; j += 2) { sts = WriteSection(pData->UV, 2, 1, pInfo, pData, i, j, fSink); + } + } return sts; } int GetFreeTaskIndex(Task *pTaskPool, mfxU16 nPoolSize) { - if (pTaskPool) - for (int i = 0; i < nPoolSize; i++) - if (!pTaskPool[i].syncp) + if (pTaskPool) { + for (int i = 0; i < nPoolSize; i++) { + if (!pTaskPool[i].syncp) { return i; + } + } + } return MFX_ERR_NOT_FOUND; } @@ -256,10 +276,13 @@ void ClearYUVSurfaceSysMem(mfxFrameSurface1 *pSfc, mfxU16 width, mfxU16 height) // Get free raw frame surface int GetFreeSurfaceIndex(mfxFrameSurface1 **pSurfacesPool, mfxU16 nPoolSize) { - if (pSurfacesPool) - for (mfxU16 i = 0; i < nPoolSize; i++) - if (0 == pSurfacesPool[i]->Data.Locked) + if (pSurfacesPool) { + for (mfxU16 i = 0; i < nPoolSize; i++) { + if (0 == pSurfacesPool[i]->Data.Locked) { return i; + } + } + } return MFX_ERR_NOT_FOUND; } diff --git a/plugins/obs-qsv11/common_utils_linux.cpp b/plugins/obs-qsv11/common_utils_linux.cpp index 47fe9c9082dc1f..cf415bc5b10f1e 100644 --- a/plugins/obs-qsv11/common_utils_linux.cpp +++ b/plugins/obs-qsv11/common_utils_linux.cpp @@ -46,8 +46,9 @@ struct surface_info { 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; response->NumFrameActual = 0; @@ -116,8 +117,9 @@ mfxStatus simple_alloc(mfxHDL pthis, mfxFrameAllocRequest *request, mfxFrameAllo 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) + VA_EXPORT_SURFACE_READ_WRITE, &surfDesc) != VA_STATUS_SUCCESS) { return MFX_ERR_MEMORY_ALLOC; + } obs_enter_graphics(); // TODO: P010 format support @@ -173,8 +175,9 @@ mfxStatus simple_unlock(mfxHDL pthis, mfxMemId mid, mfxFrameData *ptr) mfxStatus simple_gethdl(mfxHDL pthis, mfxMemId mid, mfxHDL *handle) { UNUSED_PARAMETER(pthis); - if (NULL == handle) + if (NULL == handle) { return MFX_ERR_INVALID_HANDLE; + } // Seemingly undocumented, but Pair format defined by // oneVPL-intel-gpu-intel-onevpl-23.1.0/_studio/mfx_lib/encode_hw/av1/linux/base/av1ehw_base_va_packer_lin.cpp @@ -191,11 +194,13 @@ mfxStatus simple_gethdl(mfxHDL pthis, mfxMemId mid, mfxHDL *handle) mfxStatus simple_free(mfxHDL pthis, mfxFrameAllocResponse *response) { - if (response == nullptr) + if (response == nullptr) { return MFX_ERR_NULL_PTR; + } - if (response->mids == nullptr || response->NumFrameActual == 0) + if (response->mids == nullptr || response->NumFrameActual == 0) { return MFX_ERR_NONE; + } mfxSession *session = (mfxSession *)pthis; VADisplay display; @@ -214,8 +219,9 @@ 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; } @@ -295,12 +301,13 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, mfxFrameAllocator *pm gs_enum_adapters(get_drm_device, ¶ms); obs_leave_graphics(); } else { - if (codec == QSV_CODEC_AVC && default_h264_device) + if (codec == QSV_CODEC_AVC && default_h264_device) { device_path = default_h264_device; - else if (codec == QSV_CODEC_HEVC && default_hevc_device) + } else if (codec == QSV_CODEC_HEVC && default_hevc_device) { device_path = default_hevc_device; - else if (codec == QSV_CODEC_AV1 && default_av1_device) + } else if (codec == QSV_CODEC_AV1 && default_av1_device) { device_path = default_av1_device; + } } fd = open(device_path, O_RDWR); if (fd < 0) { @@ -481,8 +488,9 @@ bool check_adapter(void *param, const char *node, uint32_t idx) struct adapter_info *adapters = (struct adapter_info *)param; vaapi_open(node, &device); - if (!device.display) + if (!device.display) { return true; + } struct adapter_info *adapter = &adapters[idx]; adapter->is_intel = strstr(device.driver, "Intel") != nullptr; @@ -491,14 +499,17 @@ bool check_adapter(void *param, const char *node, uint32_t idx) adapter->supports_av1 = vaapi_supports_av1(device.display); adapter->supports_hevc = vaapi_supports_hevc(device.display); - if (adapter->is_intel && default_h264_device == nullptr) + 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); return true; diff --git a/plugins/obs-qsv11/common_utils_windows.cpp b/plugins/obs-qsv11/common_utils_windows.cpp index da950ca6a0d70c..1973db6c00df56 100644 --- a/plugins/obs-qsv11/common_utils_windows.cpp +++ b/plugins/obs-qsv11/common_utils_windows.cpp @@ -79,8 +79,9 @@ mfxStatus Initialize(mfxVersion ver, mfxSession *pSession, mfxFrameAllocator *pm MSDK_CHECK_RESULT(sts, MFX_ERR_NONE, sts); } - if (deviceHandle == NULL || *deviceHandle == NULL) + if (deviceHandle == NULL || *deviceHandle == NULL) { return MFX_ERR_DEVICE_FAILED; + } // Provide device manager to VPL sts = MFXVideoCORE_SetHandle(*pSession, DEVICE_MGR_TYPE, *deviceHandle); @@ -136,8 +137,9 @@ double TimeDiffMsec(mfxTime tfinish, mfxTime tstart) { static LARGE_INTEGER tFreq = {0}; - if (!tFreq.QuadPart) + if (!tFreq.QuadPart) { QueryPerformanceFrequency(&tFreq); + } double freq = (double)tFreq.QuadPart; return 1000.0 * ((double)tfinish.QuadPart - (double)tstart.QuadPart) / freq; @@ -181,8 +183,9 @@ 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)); - if (!len) + if (!len) { break; + } dstr_ncat(&caps_str, data, len); } @@ -207,8 +210,9 @@ void check_adapters(struct adapter_info *adapters, size_t *adapter_count) config_adapter_count = config_num_sections(config); - if (config_adapter_count < *adapter_count) + if (config_adapter_count < *adapter_count) { *adapter_count = config_adapter_count; + } for (size_t i = 0; i < *adapter_count; i++) { char section[16]; 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 5a2567375a3b60..27bb6a406fca22 100644 --- a/plugins/obs-qsv11/obs-qsv-test/obs-qsv-test.cpp +++ b/plugins/obs-qsv11/obs-qsv-test/obs-qsv-test.cpp @@ -64,8 +64,9 @@ static bool get_adapter_caps(IDXGIFactory *factory, mfxLoader loader, mfxSession ComPtr adapter; hr = factory->EnumAdapters(adapter_idx, &adapter); - if (FAILED(hr)) + if (FAILED(hr)) { return false; + } DXGI_ADAPTER_DESC desc; adapter->GetDesc(&desc); @@ -83,23 +84,27 @@ static bool get_adapter_caps(IDXGIFactory *factory, mfxLoader loader, mfxSession mfxStatus sts = MFXEnumImplementations(loader, adapter_idx - idx_adjustment, MFX_IMPLCAPS_IMPLDESCSTRUCTURE, reinterpret_cast(&idesc)); - if (sts != MFX_ERR_NONE) + if (sts != MFX_ERR_NONE) { return false; + } caps.is_dgpu = false; - if (idesc->Dev.MediaAdapterType == MFX_MEDIA_DISCRETE) + if (idesc->Dev.MediaAdapterType == MFX_MEDIA_DISCRETE) { caps.is_dgpu = true; + } caps.supports_av1 = false; caps.supports_hevc = false; mfxEncoderDescription *enc = &idesc->Enc; if (enc->NumCodecs != 0) { for (int codec = 0; codec < enc->NumCodecs; codec++) { - if (enc->Codecs[codec].CodecID == MFX_CODEC_AV1) + if (enc->Codecs[codec].CodecID == MFX_CODEC_AV1) { caps.supports_av1 = true; + } #if ENABLE_HEVC - if (enc->Codecs[codec].CodecID == MFX_CODEC_HEVC) + if (enc->Codecs[codec].CodecID == MFX_CODEC_HEVC) { caps.supports_hevc = true; + } #endif } } else { @@ -122,8 +127,9 @@ DWORD WINAPI TimeoutThread(LPVOID param) HANDLE hMainThread = (HANDLE)param; DWORD ret = WaitForSingleObject(hMainThread, CHECK_TIMEOUT_MS); - if (ret == WAIT_TIMEOUT) + if (ret == WAIT_TIMEOUT) { TerminateProcess(GetCurrentProcess(), STATUS_TIMEOUT); + } CloseHandle(hMainThread); @@ -154,16 +160,19 @@ try { /* query qsv support */ hr = CreateDXGIFactory1(__uuidof(IDXGIFactory), (void **)&factory); - if (FAILED(hr)) + if (FAILED(hr)) { throw "CreateDXGIFactory1 failed"; + } mfxLoader loader = MFXLoad(); - if (!loader) + if (!loader) { throw "MFXLoad failed"; + } mfxConfig cfg = MFXCreateConfig(loader); - if (!cfg) + if (!cfg) { throw "MFXCreateConfig failed"; + } mfxVariant impl; @@ -179,8 +188,9 @@ try { while (get_adapter_caps(factory, loader, m_session, idx++) == true) ; - if (m_session) + if (m_session) { MFXClose(m_session); + } MFXUnload(loader); diff --git a/plugins/obs-text/gdiplus/obs-text.cpp b/plugins/obs-text/gdiplus/obs-text.cpp index d140c162f68a18..8a8862ef63a571 100644 --- a/plugins/obs-text/gdiplus/obs-text.cpp +++ b/plugins/obs-text/gdiplus/obs-text.cpp @@ -146,8 +146,9 @@ static inline wstring to_wide(const char *utf8) size_t len = os_utf8_to_wcs(utf8, 0, nullptr, 0); text.resize(len); - if (len) + if (len) { os_utf8_to_wcs(utf8, 0, &text[0], len + 1); + } return text; } @@ -164,8 +165,9 @@ template class GDIObj { inline GDIObj &Replace(T obj_) { - if (obj) + if (obj) { deleter(obj); + } obj = obj_; return *this; } @@ -300,8 +302,9 @@ struct TextSource { static time_t get_modified_timestamp(const char *filename) { struct stat stats; - if (os_stat(filename, &stats) != 0) + if (os_stat(filename, &stats) != 0) { return -1; + } return stats.st_mtime; } @@ -329,61 +332,70 @@ void TextSource::UpdateFont() hfont = CreateFontIndirect(&lf); } - if (hfont) + if (hfont) { font.reset(new Font(hdc, hfont)); + } } void TextSource::GetStringFormat(StringFormat &format) { UINT flags = StringFormatFlagsNoFitBlackBox; - if (!use_extents || old_extents) + if (!use_extents || old_extents) { flags |= StringFormatFlagsMeasureTrailingSpaces; + } - if (vertical) + if (vertical) { flags |= StringFormatFlagsDirectionVertical | StringFormatFlagsDirectionRightToLeft; + } format.SetFormatFlags(flags); format.SetTrimming(StringTrimmingWord); switch (align) { case Align::Left: - if (vertical) + if (vertical) { format.SetLineAlignment(StringAlignmentFar); - else + } else { format.SetAlignment(StringAlignmentNear); + } break; case Align::Center: - if (vertical) + if (vertical) { format.SetLineAlignment(StringAlignmentCenter); - else + } else { format.SetAlignment(StringAlignmentCenter); + } break; case Align::Right: - if (vertical) + if (vertical) { format.SetLineAlignment(StringAlignmentNear); - else + } else { format.SetAlignment(StringAlignmentFar); + } } switch (valign) { case VAlign::Top: - if (vertical) + if (vertical) { format.SetAlignment(StringAlignmentNear); - else + } else { format.SetLineAlignment(StringAlignmentNear); + } break; case VAlign::Center: - if (vertical) + if (vertical) { format.SetAlignment(StringAlignmentCenter); - else + } else { format.SetLineAlignment(StringAlignmentCenter); + } break; case VAlign::Bottom: - if (vertical) + if (vertical) { format.SetAlignment(StringAlignmentFar); - else + } else { format.SetLineAlignment(StringAlignmentFar); + } } } @@ -407,21 +419,25 @@ void TextSource::RemoveNewlinePadding(const StringFormat &format, RectF &box) float offset_cy = after.Height - before.Height; if (!vertical) { - if (offset_cx >= 1.0f) + if (offset_cx >= 1.0f) { offset_cx -= 1.0f; + } - if (valign == VAlign::Center) + if (valign == VAlign::Center) { box.Y -= offset_cy * 0.5f; - else if (valign == VAlign::Bottom) + } else if (valign == VAlign::Bottom) { box.Y -= offset_cy; + } } else { - if (offset_cy >= 1.0f) + if (offset_cy >= 1.0f) { offset_cy -= 1.0f; + } - if (align == Align::Center) + if (align == Align::Center) { box.X -= offset_cx * 0.5f; - else if (align == Align::Right) + } else if (align == Align::Right) { box.X -= offset_cx; + } } box.Width -= offset_cx; @@ -519,10 +535,11 @@ void TextSource::CalculateTextSizes(const StringFormat &format, RectF &bounding_ /* avoid taking up too much VRAM */ if (total_size > MAX_AREA) { - if (text_size.cx > text_size.cy) + if (text_size.cx > text_size.cy) { text_size.cx = (LONG)MAX_AREA / text_size.cy; - else + } else { text_size.cy = (LONG)MAX_AREA / text_size.cx; + } } /* the internal text-rendering bounding box for is reset to @@ -566,8 +583,9 @@ void TextSource::RenderText() Color(calc_color(color2, opacity2)), gradient_dir, 1); DWORD full_bk_color = bk_color & 0xFFFFFF; - if (!text.empty() || use_extents) + if (!text.empty() || use_extents) { full_bk_color |= get_alpha_val(bk_opacity); + } if ((size.cx > box.Width || size.cy > box.Height) && !use_extents) { stat = graphics_bitmap.Clear(Color(0)); @@ -606,8 +624,9 @@ void TextSource::RenderText() if (!tex || (LONG)cx != size.cx || (LONG)cy != size.cy) { obs_enter_graphics(); - if (tex) + if (tex) { 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); @@ -626,15 +645,18 @@ void TextSource::RenderText() const char *TextSource::GetMainString(const char *str) { - if (!str) + if (!str) { return ""; - if (!chatlog_mode || !chatlog_lines) + } + if (!chatlog_mode || !chatlog_lines) { return str; + } int lines = chatlog_lines; size_t len = strlen(str); - if (!len) + if (!len) { return str; + } const char *temp = str + len; @@ -642,8 +664,9 @@ const char *TextSource::GetMainString(const char *str) temp--; if (temp[0] == '\n' && temp[1] != 0) { - if (!--lines) + if (!--lines) { break; + } } } @@ -655,19 +678,20 @@ void TextSource::LoadFileText() BPtr file_text = os_quick_read_utf8_file(file.c_str()); text = to_wide(GetMainString(file_text)); - if (!text.empty() && text.back() != '\n') + if (!text.empty() && text.back() != '\n') { text.push_back('\n'); + } } void TextSource::TransformText() { const locale loc = locale(obs_get_locale()); const ctype &f = use_facet>(loc); - if (text_transform == S_TRANSFORM_UPPERCASE) + if (text_transform == S_TRANSFORM_UPPERCASE) { f.toupper(&text[0], &text[0] + text.size()); - else if (text_transform == S_TRANSFORM_LOWERCASE) + } else if (text_transform == S_TRANSFORM_LOWERCASE) { f.tolower(&text[0], &text[0] + text.size()); - else if (text_transform == S_TRANSFORM_STARTCASE) { + } else if (text_transform == S_TRANSFORM_STARTCASE) { bool upper = true; for (wstring::iterator it = text.begin(); it != text.end(); ++it) { const wchar_t upper_char = f.toupper(*it); @@ -798,8 +822,9 @@ inline void TextSource::Update(obs_data_t *s) /* all text should end with newlines due to the fact that GDI+ * treats strings without newlines differently in terms of * render size */ - if (!text.empty()) + if (!text.empty()) { text.push_back('\n'); + } } TransformText(); @@ -808,19 +833,21 @@ inline void TextSource::Update(obs_data_t *s) outline_opacity = new_o_opacity; outline_size = roundf(float(new_o_size)); - if (strcmp(align_str, S_ALIGN_CENTER) == 0) + if (strcmp(align_str, S_ALIGN_CENTER) == 0) { align = Align::Center; - else if (strcmp(align_str, S_ALIGN_RIGHT) == 0) + } else if (strcmp(align_str, S_ALIGN_RIGHT) == 0) { align = Align::Right; - else + } else { align = Align::Left; + } - if (strcmp(valign_str, S_VALIGN_CENTER) == 0) + if (strcmp(valign_str, S_VALIGN_CENTER) == 0) { valign = VAlign::Center; - else if (strcmp(valign_str, S_VALIGN_BOTTOM) == 0) + } else if (strcmp(valign_str, S_VALIGN_BOTTOM) == 0) { valign = VAlign::Bottom; - else + } else { valign = VAlign::Top; + } RenderText(); update_time_elapsed = 0.0f; @@ -832,8 +859,9 @@ inline void TextSource::Update(obs_data_t *s) inline void TextSource::Tick(float seconds) { - if (!read_from_file) + if (!read_from_file) { return; + } update_time_elapsed += seconds; @@ -857,8 +885,9 @@ inline void TextSource::Tick(float seconds) inline void TextSource::Render() { - if (!tex) + if (!tex) { return; + } gs_effect_t *effect = obs_get_base_effect(OBS_EFFECT_DEFAULT); gs_technique_t *tech = gs_effect_get_technique(effect, "Draw"); @@ -969,8 +998,9 @@ static obs_properties_t *get_properties(void *data) path = s->file; replace(path.begin(), path.end(), '\\', '/'); slash = strrchr(path.c_str(), '/'); - if (slash) + if (slash) { path.resize(slash - path.c_str() + 1); + } } obs_properties_add_text(props, S_TEXT, T_TEXT, OBS_TEXT_MULTILINE); diff --git a/plugins/obs-vst/VSTPlugin.cpp b/plugins/obs-vst/VSTPlugin.cpp index a1d19b36756678..03c8bed430b61a 100644 --- a/plugins/obs-vst/VSTPlugin.cpp +++ b/plugins/obs-vst/VSTPlugin.cpp @@ -228,8 +228,9 @@ obs_audio_data *VSTPlugin::process(struct obs_audio_data *audio) // Here we check the status firstly, // which help avoid waiting for lock while unloadEffect() is running. bool effectValid = (effect && effectReady && numChannels > 0); - if (!effectValid) + if (!effectValid) { return audio; + } std::lock_guard lock(lockEffect); @@ -294,8 +295,9 @@ bool VSTPlugin::isEditorOpen() void VSTPlugin::onEditorClosed() { - if (!editorWidget) + if (!editorWidget) { return; + } editorWidget->deleteLater(); editorWidget = nullptr; @@ -335,8 +337,9 @@ void VSTPlugin::openEditor() void VSTPlugin::closeEditor() { - if (editorWidget) + if (editorWidget) { editorWidget->close(); + } } std::string VSTPlugin::getEffectPath() diff --git a/plugins/obs-vst/obs-vst.cpp b/plugins/obs-vst/obs-vst.cpp index 1a4eebe0ef6185..c04a802c4a50c7 100644 --- a/plugins/obs-vst/obs-vst.cpp +++ b/plugins/obs-vst/obs-vst.cpp @@ -76,8 +76,9 @@ std::string getFileMD5(const char *file) QFile f(file); if (f.open(QFile::ReadOnly)) { QCryptographicHash hash(QCryptographicHash::Md5); - if (hash.addData(&f)) + if (hash.addData(&f)) { return std::string(hash.result().toHex()); + } } return std::string(); diff --git a/plugins/obs-webrtc/whip-output.cpp b/plugins/obs-webrtc/whip-output.cpp index 014919e7d61cb8..e6d0d6c3af5b49 100644 --- a/plugins/obs-webrtc/whip-output.cpp +++ b/plugins/obs-webrtc/whip-output.cpp @@ -53,8 +53,9 @@ WHIPOutput::~WHIPOutput() Stop(); std::lock_guard l(start_stop_mutex); - if (start_stop_thread.joinable()) + if (start_stop_thread.joinable()) { start_stop_thread.join(); + } } bool WHIPOutput::Start() @@ -74,13 +75,16 @@ bool WHIPOutput::Start() videoLayerStates[encoder] = v; } - if (!obs_output_can_begin_data_capture(output, 0)) + if (!obs_output_can_begin_data_capture(output, 0)) { return false; - if (!obs_output_initialize_encoders(output, 0)) + } + if (!obs_output_initialize_encoders(output, 0)) { return false; + } - if (start_stop_thread.joinable()) + if (start_stop_thread.joinable()) { start_stop_thread.join(); + } start_stop_thread = std::thread(&WHIPOutput::StartThread, this); return true; @@ -89,8 +93,9 @@ bool WHIPOutput::Start() void WHIPOutput::Stop(bool signal) { std::lock_guard l(start_stop_mutex); - if (start_stop_thread.joinable()) + if (start_stop_thread.joinable()) { start_stop_thread.join(); + } start_stop_thread = std::thread(&WHIPOutput::StopThread, this, signal); } @@ -203,8 +208,9 @@ void WHIPOutput::ConfigureVideoTrack(std::string media_stream_id, std::string cn rtp_config->mid = video_mid; const obs_encoder_t *encoder = obs_output_get_video_encoder2(output, 0); - if (!encoder) + if (!encoder) { return; + } OBSDataAutoRelease settings = obs_encoder_get_settings(encoder); auto video_bitrate = (int)obs_data_get_int(settings, "bitrate"); @@ -470,8 +476,9 @@ bool WHIPOutput::Connect() size_t location_header_count = 0; for (auto &http_header : http_headers) { auto value = value_for_header("location", http_header); - if (value.empty()) + if (value.empty()) { continue; + } location_header_count++; last_location_header = value; @@ -489,8 +496,9 @@ bool WHIPOutput::Connect() std::vector iceServers; for (auto &http_header : http_headers) { auto value = value_for_header("link", http_header); - if (value.empty()) + if (value.empty()) { continue; + } // Parse multiple links separated by ',' for (auto end = value.find(","); end != std::string::npos; end = value.find(",")) { @@ -582,11 +590,13 @@ bool WHIPOutput::Connect() void WHIPOutput::StartThread() { - if (!Init()) + if (!Init()) { return; + } - if (!Setup()) + if (!Setup()) { return; + } if (!Connect()) { peer_connection->close(); @@ -685,8 +695,9 @@ void WHIPOutput::StopThread(bool signal) 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()) + if (track == nullptr || !track->isOpen()) { return; + } std::vector sample{(rtc::byte *)data, (rtc::byte *)data + size}; @@ -706,8 +717,9 @@ void WHIPOutput::Send(void *data, uintptr_t size, uint64_t duration, std::shared 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) + if (rtp_config->timestampToSeconds(report_elapsed_timestamp) > 1) { rtcp_sr_reporter->setNeedsToReport(); + } #endif try { diff --git a/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp b/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp index f7f7855fb34943..edb2a92d0216f0 100644 --- a/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp +++ b/plugins/win-capture/get-graphics-offsets/d3d8-offsets.cpp @@ -62,12 +62,15 @@ static inline bool d3d8_init(d3d8_info &info) static inline void d3d8_free(d3d8_info &info) { - if (info.device) + if (info.device) { info.device->Release(); - if (info.d3d8) + } + if (info.d3d8) { info.d3d8->Release(); - if (info.hwnd) + } + if (info.hwnd) { DestroyWindow(info.hwnd); + } } void get_d3d8_offsets(struct d3d8_offsets *offsets) diff --git a/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp b/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp index f28451d91f755d..75009cf52a518b 100644 --- a/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp +++ b/plugins/win-capture/get-graphics-offsets/d3d9-offsets.cpp @@ -66,14 +66,18 @@ static inline bool d3d9_init(d3d9_info &info) static inline void d3d9_free(d3d9_info &info) { - if (info.swap) + if (info.swap) { info.swap->Release(); - if (info.device) + } + if (info.device) { info.device->Release(); - if (info.d3d9ex) + } + if (info.d3d9ex) { info.d3d9ex->Release(); - if (info.hwnd) + } + if (info.hwnd) { DestroyWindow(info.hwnd); + } } #ifdef _WIN64 @@ -277,8 +281,9 @@ static inline bool pattern_matches(uint8_t *byte, uint32_t *offset1, uint32_t *o { for (size_t j = 0; j < sizeof(mask) / sizeof(mask[0]); j++) { for (size_t i = 0; i < MAX_CMP_SIZE; i++) { - if ((byte[i] & mask[j][i]) != mask_cmp[j][i]) + if ((byte[i] & mask[j][i]) != mask_cmp[j][i]) { goto next_signature; + } } *offset1 = code_offsets[j][0]; @@ -314,8 +319,9 @@ void get_d3d9_offsets(struct d3d9_offsets *offsets) /* check to make sure offsets are within * expected values */ - if (off1 > 0xFFFF || off2 > 0xFFFF) + if (off1 > 0xFFFF || off2 > 0xFFFF) { break; + } #ifdef _MSC_VER /* check to make sure offsets actually point @@ -324,12 +330,14 @@ void get_d3d9_offsets(struct d3d9_offsets *offsets) uint8_t *ptr = (uint8_t *)(info.device); uint8_t *d3d9_ptr = *(uint8_t **)(ptr + off1); - if (d3d9_ptr != (uint8_t *)info.d3d9ex) + if (d3d9_ptr != (uint8_t *)info.d3d9ex) { break; + } BOOL &is_d3d9ex = *(BOOL *)(d3d9_ptr + off2); - if (is_d3d9ex != TRUE) + if (is_d3d9ex != TRUE) { break; + } } __except (EXCEPTION_EXECUTE_HANDLER) { break; diff --git a/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp b/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp index 296134f2bfad7c..21f4567846d19f 100644 --- a/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp +++ b/plugins/win-capture/get-graphics-offsets/dxgi-offsets.cpp @@ -84,10 +84,12 @@ static inline bool dxgi_init(dxgi_info &info) static inline void dxgi_free(dxgi_info &info) { - if (info.swap) + if (info.swap) { info.swap->Release(); - if (info.hwnd) + } + if (info.hwnd) { DestroyWindow(info.hwnd); + } } void get_dxgi_offsets(struct dxgi_offsets *offsets, struct dxgi_offsets2 *offsets2) diff --git a/plugins/win-capture/graphics-hook/d3d10-capture.cpp b/plugins/win-capture/graphics-hook/d3d10-capture.cpp index dfa23d5e6e18b7..d2aa462a678c30 100644 --- a/plugins/win-capture/graphics-hook/d3d10-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d10-capture.cpp @@ -50,37 +50,49 @@ static struct d3d10_data data = {}; void d3d10_free(void) { - if (data.scale_tex) + if (data.scale_tex) { data.scale_tex->Release(); - if (data.scale_resource) + } + if (data.scale_resource) { data.scale_resource->Release(); - if (data.vertex_shader) + } + if (data.vertex_shader) { data.vertex_shader->Release(); - if (data.vertex_layout) + } + if (data.vertex_layout) { data.vertex_layout->Release(); - if (data.pixel_shader) + } + if (data.pixel_shader) { data.pixel_shader->Release(); - if (data.sampler_state) + } + if (data.sampler_state) { data.sampler_state->Release(); - if (data.blend_state) + } + if (data.blend_state) { data.blend_state->Release(); - if (data.zstencil_state) + } + if (data.zstencil_state) { data.zstencil_state->Release(); - if (data.raster_state) + } + if (data.raster_state) { data.raster_state->Release(); - if (data.vertex_buffer) + } + if (data.vertex_buffer) { data.vertex_buffer->Release(); + } capture_free(); if (data.using_shtex) { - if (data.texture) + if (data.texture) { data.texture->Release(); + } } else { for (size_t i = 0; i < NUM_BUFFERS; i++) { if (data.copy_surfaces[i]) { - if (data.texture_mapped[i]) + if (data.texture_mapped[i]) { data.copy_surfaces[i]->Unmap(0); + } data.copy_surfaces[i]->Release(); } } @@ -264,8 +276,9 @@ static void d3d10_init(IDXGISwapChain *swap) } const bool success = global_hook_info->force_shmem ? d3d10_shmem_init(window) : d3d10_shtex_init(window); - if (!success) + if (!success) { d3d10_free(); + } } static inline void d3d10_copy_texture(ID3D10Resource *dst, ID3D10Resource *src) @@ -346,10 +359,11 @@ void d3d10_capture(void *swap_ptr, void *backbuffer_ptr) return; } - if (data.using_shtex) + if (data.using_shtex) { d3d10_shtex_capture(backbuffer); - else + } else { d3d10_shmem_capture(backbuffer); + } backbuffer->Release(); } diff --git a/plugins/win-capture/graphics-hook/d3d11-capture.cpp b/plugins/win-capture/graphics-hook/d3d11-capture.cpp index f45adca9736124..5e796d9647808e 100644 --- a/plugins/win-capture/graphics-hook/d3d11-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d11-capture.cpp @@ -40,13 +40,15 @@ void d3d11_free(void) capture_free(); if (data.using_shtex) { - if (data.texture) + if (data.texture) { data.texture->Release(); + } } else { for (size_t i = 0; i < NUM_BUFFERS; i++) { if (data.copy_surfaces[i]) { - if (data.texture_mapped[i]) + if (data.texture_mapped[i]) { data.context->Unmap(data.copy_surfaces[i], 0); + } data.copy_surfaces[i]->Release(); } } @@ -232,8 +234,9 @@ static void d3d11_init(IDXGISwapChain *swap) } const bool success = global_hook_info->force_shmem ? d3d11_shmem_init(window) : d3d11_shtex_init(window); - if (!success) + if (!success) { d3d11_free(); + } } static inline void d3d11_copy_texture(ID3D11Resource *dst, ID3D11Resource *src) @@ -314,10 +317,11 @@ void d3d11_capture(void *swap_ptr, void *backbuffer_ptr) return; } - if (data.using_shtex) + if (data.using_shtex) { d3d11_shtex_capture(backbuffer); - else + } else { d3d11_shmem_capture(backbuffer); + } backbuffer->Release(); } diff --git a/plugins/win-capture/graphics-hook/d3d12-capture.cpp b/plugins/win-capture/graphics-hook/d3d12-capture.cpp index c43fba4b41d572..991c4c6a29b417 100644 --- a/plugins/win-capture/graphics-hook/d3d12-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d12-capture.cpp @@ -50,14 +50,18 @@ extern bool dxgi_present_attempted; void d3d12_free(void) { - if (data.copy_tex) + if (data.copy_tex) { data.copy_tex->Release(); - if (data.device11) + } + if (data.device11) { data.device11->Release(); - if (data.context11) + } + if (data.context11) { data.context11->Release(); - if (data.device11on12) + } + if (data.device11on12) { data.device11on12->Release(); + } capture_free(); @@ -70,8 +74,9 @@ static bool create_d3d12_tex(UINT count) { HRESULT hr; - if (count == 0) + if (count == 0) { return false; + } data.backbuffer_count = count; @@ -222,8 +227,9 @@ static inline UINT d3d12_init_format(IDXGISwapChain *swap, HWND &window) UINT count = desc.SwapEffect == DXGI_SWAP_EFFECT_DISCARD ? 1 : desc.BufferCount; - if (count == 1) + if (count == 1) { data.dxgi_1_4 = false; + } if (count > MAX_BACKBUFFERS) { hlog("Somehow it's using more than the max backbuffers. " @@ -250,8 +256,9 @@ static void d3d12_init(IDXGISwapChain *swap) "unsupported; ignoring"); } - if (!d3d12_shtex_init(device, window, count)) + if (!d3d12_shtex_init(device, window, count)) { d3d12_free(); + } } device->Release(); @@ -298,8 +305,9 @@ static inline void d3d12_shtex_capture(IDXGISwapChain *swap) 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; + } } backbuffer->Release(); @@ -327,8 +335,9 @@ void d3d12_capture(void *swap_ptr, void *) static bool try_append_queue_if_unique(ID3D12CommandQueue *queue) { for (size_t i = 0; i < dxgi_possible_swap_queue_count; ++i) { - if (dxgi_possible_swap_queues[i] == queue) + if (dxgi_possible_swap_queues[i] == queue) { return false; + } } dxgi_possible_swap_queues[dxgi_possible_swap_queue_count] = queue; diff --git a/plugins/win-capture/graphics-hook/d3d8-capture.cpp b/plugins/win-capture/graphics-hook/d3d8-capture.cpp index 3e6a743c1c3ed7..b9ac4916736a07 100644 --- a/plugins/win-capture/graphics-hook/d3d8-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d8-capture.cpp @@ -88,12 +88,14 @@ static bool d3d8_init_format_backbuffer(IDirect3DDevice8 *device) D3DSURFACE_DESC desc; HRESULT hr; - if (!d3d8_get_window_handle(device)) + if (!d3d8_get_window_handle(device)) { return false; + } backbuffer = d3d8_get_backbuffer(device); - if (!backbuffer) + if (!backbuffer) { return false; + } hr = backbuffer->GetDesc(&desc); backbuffer->Release(); @@ -158,8 +160,9 @@ static void d3d8_free() for (size_t i = 0; i < NUM_BUFFERS; i++) { if (data.copy_surfaces[i]) { - if (data.surface_locked[i]) + if (data.surface_locked[i]) { data.copy_surfaces[i]->UnlockRect(); + } data.copy_surfaces[i]->Release(); } } @@ -173,11 +176,13 @@ static void d3d8_init(IDirect3DDevice8 *device) { data.d3d8 = get_system_module("d3d8.dll"); - if (!d3d8_init_format_backbuffer(device)) + if (!d3d8_init_format_backbuffer(device)) { return; + } - if (!d3d8_shmem_init(device)) + if (!d3d8_shmem_init(device)) { d3d8_free(); + } } static void d3d8_shmem_capture_copy(int idx) @@ -245,8 +250,9 @@ static void d3d8_capture(IDirect3DDevice8 *device, IDirect3DSurface8 *backbuffer static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice8 *device, D3DPRESENT_PARAMETERS *parameters) { - if (capture_active()) + if (capture_active()) { d3d8_free(); + } return RealReset(device, parameters); } @@ -277,8 +283,9 @@ static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice8 *device, CONST RE { IDirect3DSurface8 *backbuffer; - if (!hooked_reset) + if (!hooked_reset) { setup_reset_hooks(device); + } backbuffer = d3d8_get_backbuffer(device); if (backbuffer) { diff --git a/plugins/win-capture/graphics-hook/d3d9-capture.cpp b/plugins/win-capture/graphics-hook/d3d9-capture.cpp index d4b44279949ee1..b9b72b8bb933de 100644 --- a/plugins/win-capture/graphics-hook/d3d9-capture.cpp +++ b/plugins/win-capture/graphics-hook/d3d9-capture.cpp @@ -59,23 +59,29 @@ static void d3d9_free() capture_free(); if (data.using_shtex) { - if (data.d3d11_tex) + if (data.d3d11_tex) { data.d3d11_tex->Release(); - if (data.d3d11_context) + } + if (data.d3d11_context) { data.d3d11_context->Release(); - if (data.d3d11_device) + } + if (data.d3d11_device) { data.d3d11_device->Release(); - if (data.d3d9_copytex) + } + if (data.d3d9_copytex) { data.d3d9_copytex->Release(); + } } else { for (size_t i = 0; i < NUM_BUFFERS; i++) { if (data.copy_surfaces[i]) { - if (data.texture_mapped[i]) + if (data.texture_mapped[i]) { data.copy_surfaces[i]->UnlockRect(); + } data.copy_surfaces[i]->Release(); } - if (data.queries[i]) + if (data.queries[i]) { data.queries[i]->Release(); + } } } @@ -448,8 +454,9 @@ static void d3d9_init(IDirect3DDevice9 *device) success = d3d9_shtex_init(window); } - if (!success) + if (!success) { d3d9_free(); + } } static inline HRESULT get_backbuffer(IDirect3DDevice9 *device, IDirect3DSurface9 **surface) @@ -458,8 +465,9 @@ static inline HRESULT get_backbuffer(IDirect3DDevice9 *device, IDirect3DSurface9 static bool checked_exceptions = false; if (!checked_exceptions) { - if (_strcmpi(get_process_name(), "hotd_ng.exe") == 0) + if (_strcmpi(get_process_name(), "hotd_ng.exe") == 0) { use_backbuffer = true; + } checked_exceptions = true; } @@ -475,8 +483,9 @@ static inline void d3d9_shtex_capture(IDirect3DSurface9 *backbuffer) HRESULT hr; hr = data.device->StretchRect(backbuffer, nullptr, data.d3d9_copytex, nullptr, D3DTEXF_NONE); - if (FAILED(hr)) + if (FAILED(hr)) { hlog_hr("d3d9_shtex_capture: StretchRect failed", hr); + } } static void d3d9_shmem_capture_copy(int i) @@ -549,10 +558,11 @@ static void d3d9_capture(IDirect3DDevice9 *device, IDirect3DSurface9 *backbuffer return; } - if (data.using_shtex) + if (data.using_shtex) { d3d9_shtex_capture(backbuffer); - else + } else { d3d9_shmem_capture(backbuffer); + } } } @@ -585,12 +595,14 @@ static inline void present_end(IDirect3DDevice9 *device, IDirect3DSurface9 *back if (!present_recurse) { if (global_hook_info->capture_overlay) { - if (!present_recurse) + if (!present_recurse) { d3d9_capture(device, backbuffer); + } } - if (backbuffer) + if (backbuffer) { backbuffer->Release(); + } } } @@ -602,8 +614,9 @@ static HRESULT STDMETHODCALLTYPE hook_present(IDirect3DDevice9 *device, CONST RE { IDirect3DSurface9 *backbuffer = nullptr; - if (!hooked_reset) + if (!hooked_reset) { setup_reset_hooks(device); + } present_begin(device, backbuffer); @@ -619,8 +632,9 @@ static HRESULT STDMETHODCALLTYPE hook_present_ex(IDirect3DDevice9Ex *device, CON { IDirect3DSurface9 *backbuffer = nullptr; - if (!hooked_reset) + if (!hooked_reset) { setup_reset_hooks(device); + } present_begin(device, backbuffer); @@ -646,8 +660,9 @@ static HRESULT STDMETHODCALLTYPE hook_present_swap(IDirect3DSwapChain9 *swap, CO } if (device) { - if (!hooked_reset) + if (!hooked_reset) { setup_reset_hooks(device); + } present_begin(device, backbuffer); } @@ -664,8 +679,9 @@ static HRESULT STDMETHODCALLTYPE hook_present_swap(IDirect3DSwapChain9 *swap, CO static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice9 *device, D3DPRESENT_PARAMETERS *params) { - if (capture_active()) + if (capture_active()) { d3d9_free(); + } return RealReset(device, params); } @@ -673,8 +689,9 @@ static HRESULT STDMETHODCALLTYPE hook_reset(IDirect3DDevice9 *device, D3DPRESENT static HRESULT STDMETHODCALLTYPE hook_reset_ex(IDirect3DDevice9 *device, D3DPRESENT_PARAMETERS *params, D3DDISPLAYMODEEX *dmex) { - if (capture_active()) + if (capture_active()) { d3d9_free(); + } return RealResetEx(device, params, dmex); } @@ -702,8 +719,9 @@ static void setup_reset_hooks(IDirect3DDevice9 *device) const bool success = error == NO_ERROR; if (success) { hlog("Hooked IDirect3DDevice9::Reset"); - if (RealResetEx) + if (RealResetEx) { hlog("Hooked IDirect3DDevice9Ex::ResetEx"); + } hooked_reset = true; } else { RealReset = nullptr; @@ -827,12 +845,15 @@ bool hook_d3d9(void) const LONG error = DetourTransactionCommit(); const bool success = error == NO_ERROR; if (success) { - if (RealPresentSwap) + if (RealPresentSwap) { hlog("Hooked IDirect3DSwapChain9::Present"); - if (RealPresentEx) + } + if (RealPresentEx) { hlog("Hooked IDirect3DDevice9Ex::PresentEx"); - if (RealPresent) + } + if (RealPresent) { hlog("Hooked IDirect3DDevice9::Present"); + } hlog("Hooked D3D9"); } else { RealPresentSwap = nullptr; diff --git a/plugins/win-capture/graphics-hook/d3d9-patches.hpp b/plugins/win-capture/graphics-hook/d3d9-patches.hpp index 79d136a103cb95..06af6814a5a9d9 100644 --- a/plugins/win-capture/graphics-hook/d3d9-patches.hpp +++ b/plugins/win-capture/graphics-hook/d3d9-patches.hpp @@ -165,8 +165,9 @@ 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); - if (ret == 0) + if (ret == 0) { return i; + } } return -1; @@ -174,8 +175,9 @@ static inline int get_d3d9_patch(HMODULE d3d9) static inline uint8_t *get_d3d9_patch_addr(HMODULE d3d9, int patch) { - if (patch == -1) + if (patch == -1) { return nullptr; + } uint8_t *addr = (uint8_t *)d3d9; return addr + patch_offset[patch] + CMP_SIZE; diff --git a/plugins/win-capture/graphics-hook/dxgi-capture.cpp b/plugins/win-capture/graphics-hook/dxgi-capture.cpp index c5a5b6baea29c1..28208eb8884545 100644 --- a/plugins/win-capture/graphics-hook/dxgi-capture.cpp +++ b/plugins/win-capture/graphics-hook/dxgi-capture.cpp @@ -44,8 +44,9 @@ static void STDMETHODCALLTYPE SwapChainDestructed(void *pData) dxgi_possible_swap_queue_count = 0; dxgi_present_attempted = false; - if (data.free) + if (data.free) { data.free(); + } data.free = nullptr; } } @@ -138,8 +139,9 @@ static HRESULT STDMETHODCALLTYPE hook_resize_buffers(IDXGISwapChain *swap, UINT dxgi_possible_swap_queue_count = 0; dxgi_present_attempted = false; - if (data.free) + if (data.free) { data.free(); + } data.free = nullptr; const HRESULT hr = RealResizeBuffers(swap, buffer_count, width, height, format, flags); @@ -154,8 +156,9 @@ static inline IUnknown *get_dxgi_backbuffer(IDXGISwapChain *swap) IUnknown *res = nullptr; const HRESULT hr = swap->GetBuffer(0, IID_PPV_ARGS(&res)); - if (FAILED(hr)) + if (FAILED(hr)) { hlog_hr("get_dxgi_backbuffer: GetBuffer failed", hr); + } return res; } @@ -174,8 +177,9 @@ static void update_mismatch_count(bool match) dxgi_possible_swap_queue_count = 0; dxgi_present_attempted = false; - if (data.free) + if (data.free) { data.free(); + } data.free = nullptr; swap_chain_mismatch_count = 0; @@ -312,8 +316,9 @@ 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 *present1_addr = nullptr; - if (global_hook_info->offsets.dxgi.present1) + if (global_hook_info->offsets.dxgi.present1) { present1_addr = get_offset_addr(dxgi_module, global_hook_info->offsets.dxgi.present1); + } DetourTransactionBegin(); @@ -333,8 +338,9 @@ bool hook_dxgi(void) if (success) { hlog("Hooked IDXGISwapChain::Present"); hlog("Hooked IDXGISwapChain::ResizeBuffers"); - if (RealPresent1) + if (RealPresent1) { hlog("Hooked IDXGISwapChain1::Present1"); + } hlog("Hooked DXGI"); } else { RealPresent = nullptr; diff --git a/plugins/win-dshow/dshow-plugin.cpp b/plugins/win-dshow/dshow-plugin.cpp index 2f7aac9037fa53..4d9826fa788ca5 100644 --- a/plugins/win-dshow/dshow-plugin.cpp +++ b/plugins/win-dshow/dshow-plugin.cpp @@ -45,8 +45,9 @@ bool obs_module_load(void) RegisterDShowSource(); RegisterDShowEncoders(); #ifdef VIRTUALCAM_AVAILABLE - if (vcam_installed(false)) + if (vcam_installed(false)) { obs_register_output(&virtualcam_info); + } #endif return true; diff --git a/plugins/win-dshow/encode-dstr.hpp b/plugins/win-dshow/encode-dstr.hpp index 4f2f5b167ccf6b..f535523226785c 100644 --- a/plugins/win-dshow/encode-dstr.hpp +++ b/plugins/win-dshow/encode-dstr.hpp @@ -34,12 +34,14 @@ static inline bool DecodeDeviceDStr(DStr &name, DStr &path, const char *device_i { const char *path_str; - if (!device_id || !*device_id) + if (!device_id || !*device_id) { return false; + } path_str = strchr(device_id, ':'); - if (!path_str) + if (!path_str) { return false; + } dstr_copy(path, path_str + 1); dstr_copy(name, device_id); @@ -58,8 +60,9 @@ static inline bool DecodeDeviceId(DShow::DeviceId &out, const char *device_id) { DStr name, path; - if (!DecodeDeviceDStr(name, path, device_id)) + if (!DecodeDeviceDStr(name, path, device_id)) { return false; + } BPtr wname = dstr_to_wcs(name); out.name = wname; diff --git a/plugins/win-dshow/virtualcam-module/placeholder.cpp b/plugins/win-dshow/virtualcam-module/placeholder.cpp index 98597b63ee8137..8d272ae2b8ab50 100644 --- a/plugins/win-dshow/virtualcam-module/placeholder.cpp +++ b/plugins/win-dshow/virtualcam-module/placeholder.cpp @@ -120,8 +120,9 @@ static bool load_placeholder_internal() bool initialize_placeholder() { - if (initialized) + if (initialized) { return true; + } GdiplusStartupInput si; ULONG_PTR token; @@ -135,8 +136,9 @@ bool initialize_placeholder() const uint8_t *get_placeholder_ptr() { - if (initialized) + if (initialized) { return placeholder.data(); + } return nullptr; } diff --git a/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp b/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp index 89702b357e6435..407118d750b985 100644 --- a/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp +++ b/plugins/win-dshow/virtualcam-module/virtualcam-filter.cpp @@ -102,12 +102,14 @@ VCamFilter::VCamFilter() : OutputFilter() VCamFilter::~VCamFilter() { SetEvent(thread_stop); - if (th.joinable()) + if (th.joinable()) { th.join(); + } video_queue_close(vq); - if (placeholder.scaled_data) + if (placeholder.scaled_data) { free(placeholder.scaled_data); + } os_atomic_dec_long(&locks); } @@ -160,8 +162,9 @@ void VCamFilter::Thread() { HANDLE h[2] = {thread_start, thread_stop}; DWORD ret = WaitForMultipleObjects(2, h, false, INFINITE); - if (ret != WAIT_OBJECT_0) + if (ret != WAIT_OBJECT_0) { return; + } uint64_t cur_time = gettime_100ns(); uint64_t filter_time = GetTime(); @@ -191,8 +194,9 @@ void VCamFilter::Thread() UpdatePlaceholder(); while (!stopped()) { - if (os_atomic_load_bool(&active)) + if (os_atomic_load_bool(&active)) { Frame(filter_time); + } sleepto_100ns(cur_time += obs_interval); filter_time += obs_interval; } @@ -277,12 +281,13 @@ void VCamFilter::Frame(uint64_t ts) if (current_format != format) { /* The output format changed, update the scalers */ - if (current_format == VideoFormat::I420) + if (current_format == VideoFormat::I420) { scaler.format = placeholder.scaler.format = TARGET_FORMAT_I420; - else if (current_format == VideoFormat::YUY2) + } else if (current_format == VideoFormat::YUY2) { scaler.format = placeholder.scaler.format = TARGET_FORMAT_YUY2; - else + } else { scaler.format = placeholder.scaler.format = TARGET_FORMAT_NV12; + } format = current_format; @@ -292,10 +297,11 @@ void VCamFilter::Frame(uint64_t ts) /* Actual output */ uint8_t *ptr; if (LockSampleData(&ptr)) { - if (state == SHARED_QUEUE_STATE_READY) + if (state == SHARED_QUEUE_STATE_READY) { ShowOBSFrame(ptr); - else + } else { ShowDefaultFrame(ptr); + } UnlockSampleData(ts, ts + obs_interval); } @@ -323,15 +329,18 @@ void VCamFilter::ShowDefaultFrame(uint8_t *ptr) the placeholder graphic into the placeholder.scaled_data buffer. */ void VCamFilter::UpdatePlaceholder(void) { - if (!placeholder.source_data) + if (!placeholder.source_data) { return; + } - if (placeholder.scaled_data) + if (placeholder.scaled_data) { free(placeholder.scaled_data); + } placeholder.scaled_data = (uint8_t *)malloc(GetOutputBufferSize()); - if (!placeholder.scaled_data) + if (!placeholder.scaled_data) { return; + } if (placeholder.cx == GetCX() && placeholder.cy == GetCY() && placeholder.scaler.format == TARGET_FORMAT_NV12) { /* No scaling necessary if it matches exactly */ diff --git a/plugins/win-dshow/win-dshow-encoder.cpp b/plugins/win-dshow/win-dshow-encoder.cpp index 724359d9a79ac8..50b65683e741c9 100644 --- a/plugins/win-dshow/win-dshow-encoder.cpp +++ b/plugins/win-dshow/win-dshow-encoder.cpp @@ -93,8 +93,9 @@ inline bool DShowEncoder::Update(obs_data_t *settings) double aspect = double(width) / double(height); - if (keyint_sec == 0) + if (keyint_sec == 0) { keyint_sec = 2; + } if (fabs(aspect - standardAspect) < fabs(aspect - wideAspect)) { width = 1024; height = 768; @@ -140,8 +141,9 @@ static bool UpdateDShowEncoder(void *data, obs_data_t *settings) { DShowEncoder *encoder = reinterpret_cast(data); - if (!obs_encoder_active(encoder->context)) + if (!obs_encoder_active(encoder->context)) { return encoder->Update(settings); + } return true; } @@ -192,14 +194,16 @@ inline void DShowEncoder::ParseFirstPacket(const uint8_t *data, size_t size) while (nal_start < end && !*(nal_start++)) ; - if (nal_start == end) + if (nal_start == end) { break; + } type = nal_start[0] & 0x1F; nal_end = obs_avc_find_startcode(nal_start, end); - if (!nal_end) + if (!nal_end) { nal_end = end; + } if (type == OBS_NAL_SPS || type == OBS_NAL_PPS) { da_push_back_array(header, nal_codestart, nal_end - nal_codestart); @@ -233,8 +237,9 @@ inline bool DShowEncoder::Encode(struct encoder_frame *frame, struct encoder_pac bool success = encoder.Encode(frame_data, frame_sizes, actualPTS, actualPTS + frameInterval, dshowPacket, new_packet); - if (!success) + if (!success) { return false; + } if (new_packet && !!dshowPacket.data && !!dshowPacket.size) { packet->data = dshowPacket.data; @@ -283,8 +288,9 @@ 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; info->width = info->width; diff --git a/plugins/win-dshow/win-dshow.cpp b/plugins/win-dshow/win-dshow.cpp index b129965e1d5b41..eb8d1cc0e289a2 100644 --- a/plugins/win-dshow/win-dshow.cpp +++ b/plugins/win-dshow/win-dshow.cpp @@ -114,8 +114,9 @@ void ffmpeg_log(void *bla, int level, const char *msg, va_list args) /* only print first of this message to avoid spam */ static bool suppress_app_field_spam = false; if (strcmp(msg, "unable to decode APP fields: %s\n") == 0) { - if (suppress_app_field_spam) + if (suppress_app_field_spam) { return; + } suppress_app_field_spam = true; } @@ -128,8 +129,9 @@ void ffmpeg_log(void *bla, int level, const char *msg, va_list args) } dstr_cat(str, msg); - if (dstr_end(str) == '\n') + if (dstr_end(str) == '\n') { dstr_resize(str, str->len - 1); + } blogva(LOG_WARNING, str, args); av_log_default_callback(bla, level, msg, args); @@ -236,23 +238,27 @@ struct DShowInput { av_log_set_callback(ffmpeg_log); semaphore = CreateSemaphore(nullptr, 0, 0x7FFFFFFF, nullptr); - if (!semaphore) + if (!semaphore) { throw "Failed to create semaphore"; + } activated_event = CreateEvent(nullptr, false, false, nullptr); - if (!activated_event) + if (!activated_event) { throw "Failed to create activated_event"; + } thread = CreateThread(nullptr, 0, DShowThread, this, 0, nullptr); - if (!thread) + if (!thread) { throw "Failed to create thread"; + } deactivateWhenNotShowing = obs_data_get_bool(settings, DEACTIVATE_WNS); if (obs_data_get_bool(settings, "active")) { bool showing = obs_source_showing(source); - if (!deactivateWhenNotShowing || showing) + if (!deactivateWhenNotShowing || showing) { QueueActivate(settings); + } active = true; } @@ -345,8 +351,9 @@ void DShowInput::DShowLoop() if (!Activate(settings)) { obs_source_output_video2(source, nullptr); } - if (block) + if (block) { SetEvent(activated_event); + } obs_data_release(settings); break; } @@ -500,8 +507,9 @@ void DShowInput::OnEncodedVideoData(enum AVCodecID id, unsigned char *data, size if (got_output) { frame.timestamp = (uint64_t)ts * 100; - if (flip) + if (flip) { frame.flip = !frame.flip; + } #if LOG_ENCODED_VIDEO_TS blog(LOG_DEBUG, "video ts: %llu", frame.timestamp); #endif @@ -552,8 +560,9 @@ void DShowInput::OnVideoData(const VideoConfig &config, unsigned char *data, siz /* YUV DIBS are always top-down */ if (config.format == VideoFormat::XRGB || config.format == VideoFormat::ARGB) { /* RGB DIBs are bottom-up by default */ - if (!config.cy_flip) + if (!config.cy_flip) { frame.flip = !frame.flip; + } } if (videoConfig.format == VideoFormat::XRGB || videoConfig.format == VideoFormat::ARGB) { @@ -667,8 +676,9 @@ void DShowInput::OnAudioData(const AudioConfig &config, unsigned char *data, siz audio.frames = (uint32_t)(size / block_size); audio.timestamp = (uint64_t)startTime * 100; - if (audio.format != AUDIO_FORMAT_UNKNOWN) + if (audio.format != AUDIO_FORMAT_UNKNOWN) { obs_source_output_audio(source, &audio); + } UNUSED_PARAMETER(endTime); } @@ -706,8 +716,9 @@ static inline bool FormatMatches(VideoFormat left, VideoFormat right) static inline bool ResolutionValid(const string &res, int &cx, int &cy) { - if (!res.size()) + if (!res.size()) { return false; + } return ConvertRes(cx, cy, res.c_str()); } @@ -728,9 +739,11 @@ template static bool CapsMatch(const VideoDevice &dev, F... fs) { // no early exit, trigger all side effects. bool match = false; - for (const VideoInfo &info : dev.caps) - if (CapsMatch(info, fs...)) + for (const VideoInfo &info : dev.caps) { + if (CapsMatch(info, fs...)) { match = true; + } + } return match; } @@ -744,8 +757,9 @@ static inline bool MatcherMatchVideoFormat(VideoFormat format, bool &did_match, 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)) + if (llabs(interval - best_match) > llabs(interval - current)) { best_match = current; + } return true; } @@ -811,17 +825,20 @@ static bool DetermineResolution(int &cx, int &cy, obs_data_t *settings, VideoDev PRAGMA_WARN_DEPRECATION 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)) + ResolutionAvailable(dev, cx, cy)) { return true; + } PRAGMA_WARN_POP res = obs_data_get_string(settings, RESOLUTION); - if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy)) + if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy)) { return true; + } res = obs_data_get_string(settings, LAST_RESOLUTION); - if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy)) + if (ConvertRes(cx, cy, res) && ResolutionAvailable(dev, cx, cy)) { return true; + } return false; } @@ -847,10 +864,11 @@ inline void DShowInput::SetupBuffering(obs_data_t *settings) bufType = (BufferingType)obs_data_get_int(settings, BUFFERING_VAL); - if (bufType == BufferingType::Auto) + if (bufType == BufferingType::Auto) { useBuffering = IsDelayedDevice(videoConfig); - else + } else { useBuffering = bufType == BufferingType::On; + } obs_source_set_async_unbuffered(source, !useBuffering); obs_source_set_async_decoupled(source, IsDecoupled(videoConfig)); @@ -900,8 +918,9 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) : obs_data_get_int(settings, FRAME_INTERVAL); PRAGMA_WARN_POP - if (interval == FPS_MATCHING) + if (interval == FPS_MATCHING) { interval = GetOBSFPS(); + } format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); @@ -952,8 +971,9 @@ bool DShowInput::UpdateVideoConfig(obs_data_t *settings) double fps = 0.0; - if (videoConfig.frameInterval) + if (videoConfig.frameInterval) { fps = 10000000.0 / double(videoConfig.frameInterval); + } BPtr name_utf8; BPtr path_utf8; @@ -1022,10 +1042,11 @@ bool DShowInput::UpdateAudioConfig(obs_data_t *settings) blog(LOG_INFO, "\tusing video device audio: %s", audioConfig.useVideoDevice ? "yes" : "no"); if (!audioConfig.useVideoDevice) { - if (audioConfig.useSeparateAudioFilter) + if (audioConfig.useSeparateAudioFilter) { blog(LOG_INFO, "\tseparate audio filter"); - else + } else { blog(LOG_INFO, "\taudio device: %s", (const char *)name_utf8); + } } const char *mode = ""; @@ -1063,20 +1084,25 @@ inline enum video_colorspace DShowInput::GetColorSpace(obs_data_t *settings) con { const char *space = obs_data_get_string(settings, COLOR_SPACE); - if (astrcmpi(space, "709") == 0) + if (astrcmpi(space, "709") == 0) { return VIDEO_CS_709; + } - if (astrcmpi(space, "601") == 0) + if (astrcmpi(space, "601") == 0) { return VIDEO_CS_601; + } - if (astrcmpi(space, "2100PQ") == 0) + if (astrcmpi(space, "2100PQ") == 0) { return VIDEO_CS_2100_PQ; + } - if (astrcmpi(space, "2100HLG") == 0) + if (astrcmpi(space, "2100HLG") == 0) { return VIDEO_CS_2100_HLG; + } - if (videoConfig.format == VideoFormat::P010) + if (videoConfig.format == VideoFormat::P010) { return VIDEO_CS_2100_PQ; + } return VIDEO_CS_DEFAULT; } @@ -1085,10 +1111,12 @@ inline enum video_range_type DShowInput::GetColorRange(obs_data_t *settings) con { const char *range = obs_data_get_string(settings, COLOR_RANGE); - if (astrcmpi(range, "full") == 0) + if (astrcmpi(range, "full") == 0) { return VIDEO_RANGE_FULL; - if (astrcmpi(range, "partial") == 0) + } + if (astrcmpi(range, "partial") == 0) { return VIDEO_RANGE_PARTIAL; + } return VIDEO_RANGE_DEFAULT; } @@ -1105,17 +1133,20 @@ inline bool DShowInput::Activate(obs_data_t *settings) return false; } - if (!UpdateAudioConfig(settings)) + if (!UpdateAudioConfig(settings)) { blog(LOG_WARNING, "%s: Audio configuration failed, ignoring " "audio", obs_source_get_name(source)); + } - if (!device.ConnectFilters()) + if (!device.ConnectFilters()) { return false; + } - if (device.Start() != Result::Success) + if (device.Start() != Result::Success) { return false; + } cs = GetColorSpace(settings); const enum video_range_type range = GetColorRange(settings); @@ -1194,8 +1225,9 @@ static void DestroyDShowInput(void *data) static void UpdateDShowInput(void *data, obs_data_t *settings) { DShowInput *input = reinterpret_cast(data); - if (input->active) + if (input->active) { input->QueueActivate(settings); + } } static void GetDShowDefaults(obs_data_t *settings) @@ -1224,17 +1256,20 @@ static void InsertResolution(vector &resolutions, int cx, int cy) for (; idx < resolutions.size(); idx++) { const Resolution &res = resolutions[idx]; - if (res.cx > cx) + if (res.cx > cx) { break; + } if (res.cx == cx) { - if (res.cy == cy) + if (res.cy == cy) { return; + } - if (!bestCY) + if (!bestCY) { bestCY = res.cy; - else if (res.cy > bestCY) + } else if (res.cy > bestCY) { break; + } } } @@ -1253,8 +1288,9 @@ static inline void AddCap(vector &resolutions, const VideoInfo &cap) static long long GetOBSFPS() { obs_video_info ovi; - if (!obs_get_video_info(&ovi)) + if (!obs_get_video_info(&ovi)) { return 0; + } return MAKE_DSHOW_FRACTIONAL_FPS(ovi.fps_num, ovi.fps_den); } @@ -1295,8 +1331,9 @@ static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, ob static bool TryResolution(const VideoDevice &dev, const string &res) { int cx, cy; - if (!ConvertRes(cx, cy, res.c_str())) + if (!ConvertRes(cx, cy, res.c_str())) { return false; + } return ResolutionAvailable(dev, cx, cy); } @@ -1305,16 +1342,18 @@ static bool SetResolution(obs_properties_t *props, obs_data_t *settings, const s { PRAGMA_WARN_PUSH PRAGMA_WARN_DEPRECATION - if (autoselect) + if (autoselect) { obs_data_set_autoselect_string(settings, RESOLUTION, res.c_str()); - else + } else { obs_data_unset_autoselect_value(settings, RESOLUTION); + } PRAGMA_WARN_POP DeviceIntervalChanged(props, obs_properties_get(props, FRAME_INTERVAL), settings); - if (!autoselect) + if (!autoselect) { obs_data_set_string(settings, LAST_RESOLUTION, res.c_str()); + } return true; } @@ -1330,14 +1369,17 @@ static bool DeviceResolutionChanged(obs_properties_t *props, obs_property_t *p, string res = obs_data_get_string(settings, RESOLUTION); string last_res = obs_data_get_string(settings, LAST_RESOLUTION); - if (!data->GetDevice(device, id)) + if (!data->GetDevice(device, id)) { return false; + } - if (TryResolution(device, res)) + if (TryResolution(device, res)) { return SetResolution(props, settings, res); + } - if (TryResolution(device, last_res)) + if (TryResolution(device, last_res)) { return SetResolution(props, settings, last_res, true); + } return false; } @@ -1381,8 +1423,9 @@ static bool ResTypeChanged(obs_properties_t *props, obs_property_t *p, obs_data_ static size_t AddDevice(obs_property_t *device_list, const string &id) { DStr name, path; - if (!DecodeDeviceDStr(name, path, id.c_str())) + if (!DecodeDeviceDStr(name, path, id.c_str())) { return numeric_limits::max(); + } return obs_property_list_add_string(device_list, name, id.c_str()); } @@ -1398,8 +1441,9 @@ static bool UpdateDeviceList(obs_property_t *list, const string &id) found = true; continue; } - if (obs_property_list_item_disabled(list, i)) + if (obs_property_list_item_disabled(list, i)) { disabled_unknown_found = true; + } } if (!found && !disabled_unknown_found) { @@ -1408,8 +1452,9 @@ static bool UpdateDeviceList(obs_property_t *list, const string &id) return true; } - if (found && !disabled_unknown_found) + if (found && !disabled_unknown_found) { return false; + } for (size_t i = 0; i < size;) { if (obs_property_list_item_disabled(list, i)) { @@ -1432,12 +1477,14 @@ static bool DeviceSelectionChanged(obs_properties_t *props, obs_property_t *p, o bool device_list_updated = UpdateDeviceList(p, id); - if (!data->GetDevice(device, id.c_str())) + if (!data->GetDevice(device, id.c_str())) { return !device_list_updated; + } vector resolutions; - for (const VideoInfo &cap : device.caps) + for (const VideoInfo &cap : device.caps) { AddCap(resolutions, cap); + } p = obs_properties_get(props, RESOLUTION); obs_property_list_clear(p); @@ -1590,8 +1637,9 @@ static DStr GetFPSName(long long interval) } for (const FPSFormat &format : validFPSFormats) { - if (format.interval != interval) + if (format.interval != interval) { continue; + } dstr_cat(name, format.text); return name; @@ -1620,18 +1668,21 @@ static void UpdateFPS(VideoDevice &device, VideoFormat format, long long interva VideoFormatMatcher(format, video_format_match), FrameRateMatcher(format_interval)); - if (!available && interval != fps_format.interval) + if (!available && interval != fps_format.interval) { continue; + } - if (interval == fps_format.interval) + if (interval == fps_format.interval) { interval_added = true; + } 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) + if (interval_added) { return; + } size_t idx = obs_property_list_add_int(list, GetFPSName(interval), interval); obs_property_list_item_disable(list, idx, true); @@ -1670,18 +1721,21 @@ static void UpdateVideoFormats(VideoDevice &device, VideoFormat format_, int cx, for (const VideoFormatName &format : videoFormatNames) { bool available = formats.find(format.format) != end(formats); - if (!available && format.format != format_) + if (!available && format.format != format_) { continue; + } - if (format.format == format_) + 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); obs_property_list_item_disable(list, idx, !available); } - if (format_added) + if (format_added) { return; + } size_t idx = obs_property_list_add_int(list, GetVideoFormatName(format_), (long long)format_); obs_property_list_item_disable(list, idx, true); @@ -1693,12 +1747,14 @@ static bool UpdateFPS(long long interval, obs_property_t *list) DStr name; for (size_t i = 0; i < size; i++) { - if (obs_property_list_item_int(list, i) != interval) + if (obs_property_list_item_int(list, i) != interval) { continue; + } obs_property_list_item_disable(list, i, true); - if (size == 1) + if (size == 1) { return false; + } dstr_cat(name, obs_property_list_item_name(list, i)); break; @@ -1706,8 +1762,9 @@ static bool UpdateFPS(long long interval, obs_property_t *list) obs_property_list_clear(list); - if (!name->len) + if (!name->len) { name = GetFPSName(interval); + } obs_property_list_add_int(list, name, interval); obs_property_list_item_disable(list, 0, true); @@ -1723,8 +1780,9 @@ static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, ob const char *id = obs_data_get_string(settings, VIDEO_DEVICE_ID); VideoDevice device; - if (!data->GetDevice(device, id)) + if (!data->GetDevice(device, id)) { return UpdateFPS(val, p); + } int cx = 0, cy = 0; if (!DetermineResolution(cx, cy, settings, device)) { @@ -1734,11 +1792,13 @@ static bool DeviceIntervalChanged(obs_properties_t *props, obs_property_t *p, ob } int resType = (int)obs_data_get_int(settings, RES_TYPE); - if (resType != ResType_Custom) + if (resType != ResType_Custom) { return true; + } - if (val == FPS_MATCHING) + if (val == FPS_MATCHING) { val = GetOBSFPS(); + } VideoFormat format = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); @@ -1785,11 +1845,13 @@ static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list) DStr name; for (size_t i = 0; i < size; i++) { - if ((VideoFormat)obs_property_list_item_int(list, i) != format) + if ((VideoFormat)obs_property_list_item_int(list, i) != format) { continue; + } - if (size == 1) + if (size == 1) { return false; + } dstr_cat(name, obs_property_list_item_name(list, i)); break; @@ -1797,8 +1859,9 @@ static bool UpdateVideoFormats(VideoFormat format, obs_property_t *list) obs_property_list_clear(list); - if (!name->len) + if (!name->len) { name = GetVideoFormatName(format); + } obs_property_list_add_int(list, name, (long long)format); obs_property_list_item_disable(list, 0, true); @@ -1814,8 +1877,9 @@ static bool VideoFormatChanged(obs_properties_t *props, obs_property_t *p, obs_d VideoFormat curFormat = (VideoFormat)obs_data_get_int(settings, VIDEO_FORMAT); - if (!data->GetDevice(device, id)) + if (!data->GetDevice(device, id)) { return UpdateVideoFormats(curFormat, p); + } int cx, cy; if (!DetermineResolution(cx, cy, settings, device)) { @@ -1870,13 +1934,15 @@ static obs_properties_t *GetDShowProperties(void *obj) obs_property_set_modified_callback(p, DeviceSelectionChanged); Device::EnumVideoDevices(data->devices); - for (const VideoDevice &device : data->devices) + for (const VideoDevice &device : data->devices) { AddDevice(p, device); + } const char *activateText = TEXT_ACTIVATE; if (input) { - if (input->active) + if (input->active) { activateText = TEXT_DEACTIVATE; + } } obs_properties_add_button(ppts, "activate", activateText, ActivateClicked); @@ -1944,8 +2010,9 @@ static obs_properties_t *GetDShowProperties(void *obj) 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()) + if (!data->audioDevices.size()) { return ppts; + } p = obs_properties_add_bool(ppts, USE_CUSTOM_AUDIO, TEXT_CUSTOM_AUDIO); @@ -1954,8 +2021,9 @@ static obs_properties_t *GetDShowProperties(void *obj) 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) + for (const AudioDevice &device : data->audioDevices) { AddAudioDevice(p, device); + } return ppts; } @@ -1991,16 +2059,18 @@ static void HideDShowInput(void *data) { DShowInput *input = reinterpret_cast(data); - if (input->deactivateWhenNotShowing && input->active) + if (input->deactivateWhenNotShowing && input->active) { input->QueueAction(Action::Deactivate); + } } static void ShowDShowInput(void *data) { DShowInput *input = reinterpret_cast(data); - if (input->deactivateWhenNotShowing && input->active) + if (input->deactivateWhenNotShowing && input->active) { input->QueueAction(Action::Activate); + } } void RegisterDShowSource() diff --git a/plugins/win-wasapi/enum-wasapi.cpp b/plugins/win-wasapi/enum-wasapi.cpp index 697834390bf336..7544383c65e901 100644 --- a/plugins/win-wasapi/enum-wasapi.cpp +++ b/plugins/win-wasapi/enum-wasapi.cpp @@ -43,16 +43,19 @@ static void GetWASAPIAudioDevices_(vector &devices, bool input) res = CoCreateInstance(__uuidof(MMDeviceEnumerator), NULL, CLSCTX_ALL, __uuidof(IMMDeviceEnumerator), (void **)enumerator.Assign()); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to create enumerator", res); + } res = enumerator->EnumAudioEndpoints(input ? eCapture : eRender, DEVICE_STATE_ACTIVE, collection.Assign()); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to enumerate devices", res); + } res = collection->GetCount(&count); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get device count", res); + } for (UINT i = 0; i < count; i++) { ComPtr device; @@ -61,12 +64,14 @@ static void GetWASAPIAudioDevices_(vector &devices, bool input) size_t len, size; res = collection->Item(i, device.Assign()); - if (FAILED(res)) + if (FAILED(res)) { continue; + } res = device->GetId(&w_id); - if (FAILED(res) || !w_id || !*w_id) + if (FAILED(res) || !w_id || !*w_id) { continue; + } info.name = GetDeviceName(device); diff --git a/plugins/win-wasapi/plugin-main.cpp b/plugins/win-wasapi/plugin-main.cpp index 6278e8ccc32d9a..8704db306d5710 100644 --- a/plugins/win-wasapi/plugin-main.cpp +++ b/plugins/win-wasapi/plugin-main.cpp @@ -23,11 +23,13 @@ static void default_device_changed_callback(EDataFlow flow, ERole, LPCWSTR) const char *id; obs_get_audio_monitoring_device(nullptr, &id); - if (!id || strcmp(id, "default") != 0) + if (!id || strcmp(id, "default") != 0) { return; + } - if (flow != eRender) + if (flow != eRender) { return; + } auto task = [](void *) { obs_reset_audio_monitoring(); @@ -50,8 +52,9 @@ bool obs_module_load(void) RegisterWASAPIInput(); RegisterWASAPIDeviceOutput(); - if (process_filter_supported) + if (process_filter_supported) { RegisterWASAPIProcessOutput(); + } notify = new WASAPINotify(); notify->AddDefaultDeviceChangedCallback(obs_current_module(), default_device_changed_callback); diff --git a/plugins/win-wasapi/wasapi-notify.cpp b/plugins/win-wasapi/wasapi-notify.cpp index 529dc4ae0ed376..c6ad8a635cab7f 100644 --- a/plugins/win-wasapi/wasapi-notify.cpp +++ b/plugins/win-wasapi/wasapi-notify.cpp @@ -17,8 +17,9 @@ class NotificationClient : public IMMNotificationClient { STDMETHODIMP_(ULONG) STDMETHODCALLTYPE Release() { long val = os_atomic_dec_long(&refs); - if (val == 0) + if (val == 0) { delete this; + } return (ULONG)val; } @@ -47,8 +48,9 @@ class NotificationClient : public IMMNotificationClient { STDMETHODIMP OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR id) { - if (cb && id) + if (cb && id) { cb(flow, role, id); + } return S_OK; } @@ -80,8 +82,9 @@ WASAPINotify::~WASAPINotify() void WASAPINotify::AddDefaultDeviceChangedCallback(void *handle, WASAPINotifyDefaultDeviceChangedCallback cb) { - if (!handle) + if (!handle) { return; + } std::lock_guard l(mutex); defaultDeviceChangedCallbacks[handle] = cb; @@ -89,8 +92,9 @@ void WASAPINotify::AddDefaultDeviceChangedCallback(void *handle, WASAPINotifyDef void WASAPINotify::RemoveDefaultDeviceChangedCallback(void *handle) { - if (!handle) + if (!handle) { return; + } std::lock_guard l(mutex); defaultDeviceChangedCallbacks.erase(handle); @@ -99,6 +103,7 @@ void WASAPINotify::RemoveDefaultDeviceChangedCallback(void *handle) void WASAPINotify::OnDefaultDeviceChanged(EDataFlow flow, ERole role, LPCWSTR id) { std::lock_guard l(mutex); - for (const auto &cb : defaultDeviceChangedCallbacks) + for (const auto &cb : defaultDeviceChangedCallbacks) { cb.second(flow, role, id); + } } diff --git a/plugins/win-wasapi/win-wasapi.cpp b/plugins/win-wasapi/win-wasapi.cpp index 0cea4758559b2f..bcd6094b840962 100644 --- a/plugins/win-wasapi/win-wasapi.cpp +++ b/plugins/win-wasapi/win-wasapi.cpp @@ -65,8 +65,9 @@ class WASAPIActivateAudioInterfaceCompletionHandler WASAPIActivateAudioInterfaceCompletionHandler::WASAPIActivateAudioInterfaceCompletionHandler() { activationSignal = CreateEvent(nullptr, false, false, nullptr); - if (!activationSignal.Valid()) + if (!activationSignal.Valid()) { throw "Could not create receive signal"; + } } HRESULT @@ -308,41 +309,50 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, SourceTy LogSettings(); idleSignal = CreateEvent(nullptr, true, false, nullptr); - if (!idleSignal.Valid()) + if (!idleSignal.Valid()) { throw "Could not create idle signal"; + } stopSignal = CreateEvent(nullptr, true, false, nullptr); - if (!stopSignal.Valid()) + if (!stopSignal.Valid()) { throw "Could not create stop signal"; + } receiveSignal = CreateEvent(nullptr, false, false, nullptr); - if (!receiveSignal.Valid()) + if (!receiveSignal.Valid()) { throw "Could not create receive signal"; + } restartSignal = CreateEvent(nullptr, true, false, nullptr); - if (!restartSignal.Valid()) + if (!restartSignal.Valid()) { throw "Could not create restart signal"; + } reconnectExitSignal = CreateEvent(nullptr, true, false, nullptr); - if (!reconnectExitSignal.Valid()) + if (!reconnectExitSignal.Valid()) { throw "Could not create reconnect exit signal"; + } exitSignal = CreateEvent(nullptr, true, false, nullptr); - if (!exitSignal.Valid()) + if (!exitSignal.Valid()) { throw "Could not create exit signal"; + } initSignal = CreateEvent(nullptr, false, false, nullptr); - if (!initSignal.Valid()) + if (!initSignal.Valid()) { throw "Could not create init signal"; + } reconnectSignal = CreateEvent(nullptr, false, false, nullptr); - if (!reconnectSignal.Valid()) + if (!reconnectSignal.Valid()) { throw "Could not create reconnect signal"; + } HRESULT hr = CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_ALL, IID_PPV_ARGS(enumerator.Assign())); - if (FAILED(hr)) + if (FAILED(hr)) { throw HRError("Failed to create enumerator", hr); + } /* OBS will already load DLL on startup if it exists */ const HMODULE rtwq_module = GetModuleHandle(L"RTWorkQ.dll"); @@ -356,8 +366,9 @@ WASAPISource::WASAPISource(obs_data_t *settings, obs_source_t *source_, SourceTy win1703.revis = 0; struct win_version_info ver; get_win_ver(&ver); - if (win_version_compare(&ver, &win1703) >= 0) + if (win_version_compare(&ver, &win1703) >= 0) { rtwq_supported = rtwq_module != NULL; + } if (rtwq_supported) { rtwq_unlock_work_queue = (PFN_RtwqUnlockWorkQueue)GetProcAddress(rtwq_module, "RtwqUnlockWorkQueue"); @@ -433,8 +444,9 @@ void WASAPISource::Stop() blog(LOG_INFO, "WASAPI: Device '%s' Terminated", device_name.c_str()); - if (rtwq_supported) + if (rtwq_supported) { SetEvent(receiveSignal); + } if (reconnectThread.Valid()) { WaitForSingleObject(idleSignal, INFINITE); @@ -450,10 +462,11 @@ void WASAPISource::Stop() WaitForSingleObject(reconnectThread, INFINITE); } - if (rtwq_supported) + if (rtwq_supported) { rtwq_unlock_work_queue(sampleReady.GetQueueId()); - else + } else { WaitForSingleObject(captureThread, INFINITE); + } obs_weak_source_release(reroute_target); } @@ -465,8 +478,9 @@ WASAPISource::~WASAPISource() notify->RemoveDefaultDeviceChangedCallback(this); } // If the device is also used for monitoring, a cleanup is needed. - if (sourceType == SourceType::DeviceOutput) + if (sourceType == SourceType::DeviceOutput) { obs_source_audio_output_capture_device_changed(source, NULL); + } Stop(); } @@ -507,8 +521,9 @@ WASAPISource::UpdateParams WASAPISource::BuildUpdateParams(obs_data_t *settings) void WASAPISource::UpdateSettings(UpdateParams &¶ms) { // Signal to deduplication logic in case the device is also used for monitoring. - if (device_id != params.device_id && sourceType == SourceType::DeviceOutput) + if (device_id != params.device_id && sourceType == SourceType::DeviceOutput) { obs_source_audio_output_capture_device_changed(source, params.device_id.c_str()); + } device_id = std::move(params.device_id); useDeviceTiming = params.useDeviceTiming; @@ -551,8 +566,9 @@ void WASAPISource::Update(obs_data_t *settings) UpdateSettings(std::move(params)); LogSettings(); - if (restart) + if (restart) { SetEvent(restartSignal); + } } void WASAPISource::OnWindowChanged(obs_data_t *settings) @@ -566,8 +582,9 @@ void WASAPISource::OnWindowChanged(obs_data_t *settings) UpdateSettings(std::move(params)); - if (restart) + if (restart) { SetEvent(restartSignal); + } } void WASAPISource::Activate() @@ -596,20 +613,23 @@ ComPtr WASAPISource::InitDevice(IMMDeviceEnumerator *enumerator, bool const bool input = type == SourceType::Input; HRESULT res = enumerator->GetDefaultAudioEndpoint(input ? eCapture : eRender, input ? eCommunications : eConsole, device.Assign()); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed GetDefaultAudioEndpoint", res); + } } else { wchar_t *w_id; os_utf8_to_wcs_ptr(device_id.c_str(), device_id.size(), &w_id); - if (!w_id) + if (!w_id) { throw "Failed to widen device id string"; + } const HRESULT res = enumerator->GetDevice(w_id, device.Assign()); bfree(w_id); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to enumerate device", res); + } } return device; @@ -648,8 +668,9 @@ ComPtr WASAPISource::InitClient(IMMDevice *device, SourceType type ComPtr client; if (type == SourceType::ProcessOutput) { - if (activate_audio_interface_async == NULL) + if (activate_audio_interface_async == NULL) { throw "ActivateAudioInterfaceAsync is not available"; + } struct obs_audio_info oai; obs_get_audio_info(&oai); @@ -688,23 +709,27 @@ ComPtr WASAPISource::InitClient(IMMDevice *device, SourceType type res = activate_audio_interface_async(VIRTUAL_AUDIO_DEVICE_PROCESS_LOOPBACK, __uuidof(IAudioClient), &activateParams, handler.Get(), &asyncOp); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get activate audio client", res); + } res = handler->GetActivateResult(client.Assign()); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Async activation failed", res); + } } pFormat = &wf; } else { res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void **)client.Assign()); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to activate client context", res); + } res = client->GetMixFormat(&wfex); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get mix format", res); + } pFormat = wfex.Get(); } @@ -712,11 +737,13 @@ ComPtr WASAPISource::InitClient(IMMDevice *device, SourceType type InitFormat(pFormat, speakers, format, samples_per_sec); DWORD flags = AUDCLNT_STREAMFLAGS_EVENTCALLBACK; - if (type != SourceType::Input) + if (type != SourceType::Input) { flags |= AUDCLNT_STREAMFLAGS_LOOPBACK; + } res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, flags, BUFFER_TIME_100NS, 0, pFormat, nullptr); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to initialize audio client", res); + } return client; } @@ -730,33 +757,39 @@ void WASAPISource::ClearBuffer(IMMDevice *device) ComPtr client; res = device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, nullptr, (void **)client.Assign()); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to activate client context", res); + } res = client->GetMixFormat(&wfex); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get mix format", res); + } res = client->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, BUFFER_TIME_100NS, 0, wfex, nullptr); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to initialize audio client", res); + } /* Silent loopback fix. Prevents audio stream from stopping and */ /* messing up timestamps and other weird glitches during silence */ /* by playing a silent sample all over again. */ res = client->GetBufferSize(&frames); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get buffer size", res); + } ComPtr render; res = client->GetService(IID_PPV_ARGS(render.Assign())); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get render client", res); + } res = render->GetBuffer(frames, &buffer); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to get buffer", res); + } memset(buffer, 0, (size_t)frames * (size_t)wfex->nBlockAlign); @@ -801,16 +834,19 @@ ComPtr WASAPISource::InitCapture(IAudioClient *client, HAND { ComPtr capture; HRESULT res = client->GetService(IID_PPV_ARGS(capture.Assign())); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to create capture context", res); + } res = client->SetEventHandle(receiveSignal); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to set event handle", res); + } res = client->Start(); - if (FAILED(res)) + if (FAILED(res)) { throw HRError("Failed to start capture client", res); + } return capture; } @@ -823,8 +859,9 @@ void WASAPISource::Initialize() hwnd = ms_find_window(INCLUDE_MINIMIZED, priority, window_class.c_str(), title.c_str(), executable.c_str()); - if (!hwnd) + if (!hwnd) { throw "Failed to find window"; + } DWORD dwProcessId = 0; if (!GetWindowThreadProcessId(hwnd, &dwProcessId)) { @@ -843,8 +880,9 @@ void WASAPISource::Initialize() ComPtr temp_client = InitClient(device, sourceType, process_id, activate_audio_interface_async, speakers, format, sampleRate); - if (sourceType == SourceType::DeviceOutput) + if (sourceType == SourceType::DeviceOutput) { ClearBuffer(device); + } ComPtr temp_capture = InitCapture(temp_client, receiveSignal); client = std::move(temp_client); @@ -971,26 +1009,29 @@ bool WASAPISource::ProcessCaptureData() res = capture->GetNextPacketSize(&captureSize); if (FAILED(res)) { - if (res != AUDCLNT_E_DEVICE_INVALIDATED) + if (res != AUDCLNT_E_DEVICE_INVALIDATED) { blog(LOG_WARNING, "[WASAPISource::ProcessCaptureData]" " capture->GetNextPacketSize" " failed: %lX", res); + } return false; } - if (!captureSize) + if (!captureSize) { break; + } res = capture->GetBuffer(&buffer, &frames, &flags, &pos, &ts); if (FAILED(res)) { - if (res != AUDCLNT_E_DEVICE_INVALIDATED) + if (res != AUDCLNT_E_DEVICE_INVALIDATED) { blog(LOG_WARNING, "[WASAPISource::ProcessCaptureData]" " capture->GetBuffer" " failed: %lX", res); + } return false; } @@ -1005,8 +1046,9 @@ bool WASAPISource::ProcessCaptureData() * frame size = channels * sample size * sample size = 4 bytes (always float per InitFormat) */ uint32_t requiredBufSize = get_audio_channels(speakers) * frames * 4; - if (silence.size() < requiredBufSize) + if (silence.size() < requiredBufSize) { silence.resize(requiredBufSize); + } buffer = silence.data(); } @@ -1022,8 +1064,9 @@ bool WASAPISource::ProcessCaptureData() } else { data.timestamp = useDeviceTiming ? ts * 100 : os_gettime_ns(); - if (!useDeviceTiming) + if (!useDeviceTiming) { data.timestamp -= util_mul_div64(frames, UINT64_C(1000000000), sampleRate); + } } if (reroute_target) { @@ -1180,33 +1223,39 @@ DWORD WINAPI WASAPISource::CaptureThread(LPVOID param) } } - if (handle) + if (handle) { AvRevertMmThreadCharacteristics(handle); + } - if (com_initialized) + if (com_initialized) { CoUninitialize(); + } return 0; } void WASAPISource::SetDefaultDevice(EDataFlow flow, ERole role, LPCWSTR id) { - if (!isDefaultDevice) + if (!isDefaultDevice) { return; + } const bool input = sourceType == SourceType::Input; const EDataFlow expectedFlow = input ? eCapture : eRender; const ERole expectedRole = input ? eCommunications : eConsole; - if (flow != expectedFlow || role != expectedRole) + if (flow != expectedFlow || role != expectedRole) { return; + } if (id) { - if (default_id.compare(id) == 0) + if (default_id.compare(id) == 0) { return; + } default_id = id; } else { - if (default_id.empty()) + if (default_id.empty()) { return; + } default_id.clear(); } @@ -1345,8 +1394,9 @@ static void wasapi_get_hooked(void *data, calldata_t *cd) { WASAPISource *wasapi_source = reinterpret_cast(data); - if (!wasapi_source) + if (!wasapi_source) { return; + } bool hooked = wasapi_source->GetHooked(); HWND hwnd = wasapi_source->GetHwnd(); @@ -1376,8 +1426,9 @@ static void wasapi_get_hooked(void *data, calldata_t *cd) static void wasapi_reroute_audio(void *data, calldata_t *cd) { auto wasapi_source = static_cast(data); - if (!wasapi_source) + if (!wasapi_source) { return; + } obs_source_t *target = nullptr; calldata_get_ptr(cd, "target", &target); @@ -1453,8 +1504,9 @@ static void DeactivateWASAPISource(void *obj) static bool UpdateWASAPIMethod(obs_properties_t *props, obs_property_t *, obs_data_t *settings) { WASAPISource *source = (WASAPISource *)obs_properties_get_param(props); - if (!source) + if (!source) { return false; + } source->Update(settings); @@ -1471,8 +1523,9 @@ static obs_properties_t *GetWASAPIPropertiesInput(void *) GetWASAPIAudioDevices(devices, true); - if (devices.size()) + if (devices.size()) { 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]; @@ -1494,8 +1547,9 @@ static obs_properties_t *GetWASAPIPropertiesDeviceOutput(void *) GetWASAPIAudioDevices(devices, false); - if (devices.size()) + if (devices.size()) { 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]; @@ -1510,8 +1564,9 @@ static obs_properties_t *GetWASAPIPropertiesDeviceOutput(void *) 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) + if (!source) { return false; + } source->OnWindowChanged(settings); diff --git a/shared/obs-scripting/cstrcache.cpp b/shared/obs-scripting/cstrcache.cpp index 786583768baa1c..995b59b7e50919 100644 --- a/shared/obs-scripting/cstrcache.cpp +++ b/shared/obs-scripting/cstrcache.cpp @@ -13,8 +13,9 @@ static struct const_string_table table; const char *cstrcache_get(const char *str) { - if (!str || !*str) + if (!str || !*str) { return ""; + } auto &strings = table.strings; auto pair = strings.find(str); diff --git a/shared/properties-view/properties-view.cpp b/shared/properties-view/properties-view.cpp index 071e6dc6508e19..b74a62decc3379 100644 --- a/shared/properties-view/properties-view.cpp +++ b/shared/properties-view/properties-view.cpp @@ -93,8 +93,9 @@ void OBSPropertiesView::ReloadProperties() if (weakObj || rawObj) { OBSObject strongObj = GetObject(); void *obj = strongObj ? strongObj.Get() : rawObj; - if (obj) + if (obj) { properties.reset(reloadCallback(obj)); + } } else { properties.reset(reloadCallback((void *)type.c_str())); obs_properties_apply_settings(properties.get(), settings); @@ -114,8 +115,9 @@ void OBSPropertiesView::RefreshProperties() GetScrollPos(h, v, hend, vend); children.clear(); - if (widget) + if (widget) { widget->deleteLater(); + } widget = new QWidget(); widget->setObjectName("PropertiesContainer"); @@ -142,8 +144,9 @@ void OBSPropertiesView::RefreshProperties() adjustSize(); SetScrollPos(h, v, hend, vend); - if (disableScrolling) + if (disableScrolling) { setMinimumHeight(widget->minimumSizeHint().height()); + } lastFocused.clear(); if (lastWidget) { @@ -354,8 +357,9 @@ QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, Q if (info_label->text().isEmpty() && long_desc == NULL) { label = nullptr; info_label->setText(desc); - } else + } else { label = new QLabel(desc); + } if (long_desc != NULL && !info_label->text().isEmpty()) { QString file = !obs_frontend_is_theme_dark() ? ":/res/images/help.svg" @@ -372,13 +376,15 @@ QWidget *OBSPropertiesView::AddText(obs_property_t *prop, QFormLayout *layout, Q info_label->setOpenExternalLinks(true); info_label->setWordWrap(obs_property_text_info_word_wrap(prop)); - if (info_type == OBS_TEXT_INFO_WARNING) + if (info_type == OBS_TEXT_INFO_WARNING) { info_label->setProperty("class", "text-warning"); - else if (info_type == OBS_TEXT_INFO_ERROR) + } else if (info_type == OBS_TEXT_INFO_ERROR) { info_label->setProperty("class", "text-danger"); + } - if (label) + if (label) { label->setObjectName(info_label->objectName()); + } WidgetInfo *info = new WidgetInfo(this, prop, info_label); children.emplace_back(info); @@ -481,8 +487,9 @@ void OBSPropertiesView::AddFloat(obs_property_t *prop, QFormLayout *layout, QLab double val = obs_data_get_double(settings, name); QDoubleSpinBox *spin = new QDoubleSpinBox(); - if (!obs_property_enabled(prop)) + if (!obs_property_enabled(prop)) { spin->setEnabled(false); + } double minVal = obs_property_float_min(prop); double maxVal = obs_property_float_max(prop); @@ -492,8 +499,9 @@ void OBSPropertiesView::AddFloat(obs_property_t *prop, QFormLayout *layout, QLab if (stepVal < 1.0) { constexpr int sane_limit = 8; const int decimals = std::min(log10(1.0 / stepVal) + 0.99, sane_limit); - if (decimals > spin->decimals()) + if (decimals > spin->decimals()) { spin->setDecimals(decimals); + } } spin->setMinimum(minVal); @@ -551,16 +559,19 @@ static void AddComboItem(QComboBox *combo, obs_property_t *prop, size_t idx) combo->addItem(QT_UTF8(name), var); - if (!obs_property_list_item_disabled(prop, idx)) + if (!obs_property_list_item_disabled(prop, idx)) { return; + } int index = combo->findText(QT_UTF8(name)); - if (index < 0) + if (index < 0) { return; + } QStandardItemModel *model = dynamic_cast(combo->model()); - if (!model) + if (!model) { return; + } QStandardItem *item = model->item(index); item->setFlags(Qt::NoItemFlags); @@ -629,8 +640,9 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) QFormLayout *subLayout = new QFormLayout(); subLayout->setContentsMargins(0, 0, 0, 0); - for (size_t idx = 0; idx < count; idx++) + for (size_t idx = 0; idx < count; idx++) { AddRadioItem(buttonGroup, subLayout, prop, value, idx); + } if (count > 0) { buttonGroup->setExclusive(true); @@ -647,11 +659,13 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) int idx = -1; QComboBox *combo = new QComboBox(); - for (size_t i = 0; i < count; i++) + for (size_t i = 0; i < count; i++) { AddComboItem(combo, prop, i); + } - if (type == OBS_COMBO_TYPE_EDITABLE) + if (type == OBS_COMBO_TYPE_EDITABLE) { combo->setEditable(true); + } combo->setMaxVisibleItems(40); combo->setToolTip(QT_UTF8(obs_property_long_description(prop))); @@ -662,11 +676,13 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) idx = combo->findData(value); } - if (type == OBS_COMBO_TYPE_EDITABLE) + if (type == OBS_COMBO_TYPE_EDITABLE) { return NewWidget(prop, combo, &QComboBox::editTextChanged); + } - if (idx != -1) + if (idx != -1) { combo->setCurrentIndex(idx); + } PRAGMA_WARN_PUSH PRAGMA_DISABLE_DEPRECATION @@ -691,8 +707,9 @@ QWidget *OBSPropertiesView::AddList(obs_property_t *prop, bool &warning) children.emplace_back(info); /* trigger a settings update if the index was not found */ - if (count && idx == -1) + if (count && idx == -1) { info->ControlChanged(); + } return combo; } @@ -715,8 +732,9 @@ void OBSPropertiesView::AddEditableList(obs_property_t *prop, QFormLayout *layou QListWidget *list = new QListWidget(); size_t count = obs_data_array_count(array); - if (!obs_property_enabled(prop)) + if (!obs_property_enabled(prop)) { list->setEnabled(false); + } list->setSortingEnabled(false); list->setSelectionMode(QAbstractItemView::ExtendedSelection); @@ -844,22 +862,28 @@ void MakeQFont(obs_data_t *font_obj, QFont &font, bool limit = false) if (size) { if (limit) { int max_size = font.pointSize(); - if (max_size < 28) + if (max_size < 28) { max_size = 28; - if (size > max_size) + } + if (size > max_size) { size = max_size; + } } font.setPointSize(size); } - if (flags & OBS_FONT_BOLD) + if (flags & OBS_FONT_BOLD) { font.setBold(true); - if (flags & OBS_FONT_ITALIC) + } + if (flags & OBS_FONT_ITALIC) { font.setItalic(true); - if (flags & OBS_FONT_UNDERLINE) + } + if (flags & OBS_FONT_UNDERLINE) { font.setUnderline(true); - if (flags & OBS_FONT_STRIKEOUT) + } + if (flags & OBS_FONT_STRIKEOUT) { font.setStrikeOut(true); + } } void OBSPropertiesView::AddFont(obs_property_t *prop, QFormLayout *layout, QLabel *&label) @@ -953,11 +977,13 @@ static bool matches_ranges(media_frames_per_second &best_match, media_frames_per fabsl(min_ - val) < epsilon ? "true" : "false");*/ - if (matches_range(best_match, fps, pair)) + if (matches_range(best_match, fps, pair)) { return true; + } - if (exact) + if (exact) { continue; + } auto min_dist = fabsl(min_ - val); auto max_dist = fabsl(max_ - val); @@ -1003,12 +1029,14 @@ static void UpdateSimpleFPSSelection(OBSFrameRatePropertyWidget *fpsProps, const auto num = combo->count(); for (int i = 0; i < num; i++) { auto variant = combo->itemData(i); - if (!variant.canConvert()) + if (!variant.canConvert()) { continue; + } auto fps = variant.value(); - if (fps != *current_fps) + if (fps != *current_fps) { continue; + } combo->setCurrentIndex(i); return; @@ -1026,11 +1054,13 @@ static void AddFPSRanges(vector &items, const frame_rate_rang auto i = begin(items); for (; i != end_; i++) { auto i_fps_val = media_frames_per_second_to_fps(i->fps); - if (fabsl(i_fps_val - fps_val) < 0.01) + if (fabsl(i_fps_val - fps_val) < 0.01) { return; + } - if (i_fps_val > fps_val) + if (i_fps_val > fps_val) { continue; + } break; } @@ -1061,8 +1091,9 @@ static QWidget *CreateSimpleFPSValues(OBSFrameRatePropertyWidget *fpsProps, bool combo->addItem("", QVariant::fromValue(make_fps(0, 0))); for (const auto &fps : common_fps) { media_frames_per_second best_match{}; - if (!matches_ranges(best_match, fps.fps, fpsProps->fps_ranges)) + if (!matches_ranges(best_match, fps.fps, fpsProps->fps_ranges)) { continue; + } items.push_back({fps.fps_name, best_match}); } @@ -1100,16 +1131,19 @@ static void UpdateRationalFPSWidgets(OBSFrameRatePropertyWidget *fpsProps, const auto num = combo->count(); for (int i = 0; i < num; i++) { auto variant = combo->itemData(i); - if (!variant.canConvert()) + if (!variant.canConvert()) { continue; + } auto idx = variant.value(); - if (fpsProps->fps_ranges.size() < idx) + if (fpsProps->fps_ranges.size() < idx) { 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); break; @@ -1142,8 +1176,9 @@ static QWidget *CreateRationalFPS(OBSFrameRatePropertyWidget *fpsProps, bool &se QVariant::fromValue(i)); media_frames_per_second match; - if (!current_fps || !matches_range(match, *current_fps, pair)) + if (!current_fps || !matches_range(match, *current_fps, pair)) { continue; + } combo->setCurrentIndex(combo->count() - 1); selected = true; @@ -1188,8 +1223,9 @@ static OBSFrameRatePropertyWidget *CreateFrameRateWidget(obs_property_t *prop, b combo->setToolTip(QT_UTF8(obs_property_long_description(prop))); auto num = obs_property_frame_rate_options_count(prop); - if (num) + if (num) { combo->insertSeparator(combo->count()); + } bool option_found = false; for (size_t i = 0; i < num; i++) { @@ -1197,8 +1233,9 @@ static OBSFrameRatePropertyWidget *CreateFrameRateWidget(obs_property_t *prop, b auto desc = obs_property_frame_rate_option_description(prop, i); combo->addItem(desc, QVariant::fromValue(frame_rate_tag{name})); - if (!name || !option || string(name) != option) + if (!name || !option || string(name) != option) { continue; + } option_found = true; combo->setCurrentIndex(combo->count() - 1); @@ -1213,8 +1250,9 @@ static OBSFrameRatePropertyWidget *CreateFrameRateWidget(obs_property_t *prop, b bool selected = false; stack->addWidget(func(widget, selected, current_fps)); - if (match_found || !selected) + if (match_found || !selected) { return; + } match_found = true; @@ -1226,9 +1264,9 @@ static OBSFrameRatePropertyWidget *CreateFrameRateWidget(obs_property_t *prop, b AddWidget(CreateRationalFPS); stack->addWidget(new QWidget{}); - if (option_found) + if (option_found) { stack->setCurrentIndex(stack->count() - 1); - else if (!match_found) { + } else if (!match_found) { int idx = current_fps ? 1 : 0; // Rational for "unsupported" // Simple as default stack->setCurrentIndex(idx); @@ -1314,8 +1352,9 @@ static void UpdateFPSLabels(OBSFrameRatePropertyWidget *w) PRAGMA_WARN_PUSH PRAGMA_DISABLE_DEPRECATION if (obs_data_item_get_autoselect_frames_per_second(obj.get(), &fps, nullptr) || - obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) + obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) { valid_fps = &fps; + } PRAGMA_WARN_POP const char *option = nullptr; @@ -1324,8 +1363,9 @@ static void UpdateFPSLabels(OBSFrameRatePropertyWidget *w) if (!valid_fps) { w->currentFPS->setHidden(true); w->timePerFrame->setHidden(true); - if (!option) + if (!option) { w->warningLabel->setProperty("class", "text-danger"); + } return; } @@ -1334,10 +1374,11 @@ static void UpdateFPSLabels(OBSFrameRatePropertyWidget *w) w->timePerFrame->setHidden(false); media_frames_per_second match{}; - if (!option && !matches_ranges(match, *valid_fps, w->fps_ranges, true)) + if (!option && !matches_ranges(match, *valid_fps, w->fps_ranges, true)) { w->warningLabel->setProperty("class", "text-danger"); - else + } else { 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; @@ -1357,15 +1398,17 @@ void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, QFormL media_frames_per_second fps{}; media_frames_per_second *valid_fps = nullptr; - if (obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) + if (obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) { valid_fps = &fps; + } frame_rate_ranges_t fps_ranges; size_t num = obs_property_frame_rate_fps_ranges_count(prop); fps_ranges.reserve(num); - for (size_t i = 0; i < num; i++) + 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)); + } auto widget = CreateFrameRateWidget(prop, warning, option, valid_fps, fps_ranges); auto info = new WidgetInfo(this, prop, widget); @@ -1401,38 +1444,43 @@ void OBSPropertiesView::AddFrameRate(obs_property_t *prop, bool &warning, QFormL auto idx = out_of_bounds ? stack->count() - 1 : index; stack->setCurrentIndex(idx); - if (widget->updating) + if (widget->updating) { return; + } UpdateFPSLabels(widget); emit info->ControlChanged(); }); connect(widget->simpleFPS, comboIndexChanged, info, [=](int) { - if (widget->updating) + if (widget->updating) { return; + } emit info->ControlChanged(); }); connect(widget->fpsRange, comboIndexChanged, info, [=](int) { - if (widget->updating) + if (widget->updating) { return; + } UpdateFPSLabels(widget); }); auto sbValueChanged = static_cast(&QSpinBox::valueChanged); connect(widget->numEdit, sbValueChanged, info, [=](int) { - if (widget->updating) + if (widget->updating) { return; + } emit info->ControlChanged(); }); connect(widget->denEdit, sbValueChanged, info, [=](int) { - if (widget->updating) + if (widget->updating) { return; + } emit info->ControlChanged(); }); @@ -1480,8 +1528,9 @@ void OBSPropertiesView::AddProperty(obs_property_t *property, QFormLayout *layou const char *name = obs_property_name(property); obs_property_type type = obs_property_get_type(property); - if (!obs_property_visible(property)) + if (!obs_property_visible(property)) { return; + } QLabel *label = nullptr; QWidget *widget = nullptr; @@ -1530,30 +1579,36 @@ void OBSPropertiesView::AddProperty(obs_property_t *property, QFormLayout *layou AddColorAlpha(property, layout, label); } - if (!widget && !label) + 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) { - if (warning) + if (warning) { label->setObjectName("errorLabel"); + } if (minSize) { label->setMinimumWidth(minSize); label->setAlignment(Qt::AlignRight | Qt::AlignVCenter); } - if (!obs_property_enabled(property)) + if (!obs_property_enabled(property)) { label->setEnabled(false); + } } - if (!widget) + if (!widget) { return; + } - if (!obs_property_enabled(property)) + if (!obs_property_enabled(property)) { widget->setEnabled(false); + } QWidget *leftWidget = label; if (obs_property_long_description(property) && label) { @@ -1578,9 +1633,11 @@ void OBSPropertiesView::AddProperty(obs_property_t *property, QFormLayout *layou layout->addRow(leftWidget, widget); - if (!lastFocused.empty()) - if (lastFocused.compare(name) == 0) + if (!lastFocused.empty()) { + if (lastFocused.compare(name) == 0) { lastWidget = widget; + } + } } void OBSPropertiesView::SignalChanged() @@ -1591,12 +1648,14 @@ void OBSPropertiesView::SignalChanged() 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()) + if (!variant.canConvert()) { return false; + } fps = variant.value(); - if (valid_fps && fps == *valid_fps) + if (valid_fps && fps == *valid_fps) { return false; + } obs_data_item_set_frames_per_second(&obj, fps, nullptr); return true; @@ -1606,8 +1665,9 @@ static bool FrameRateChangedCommon(OBSFrameRatePropertyWidget *w, obs_data_item_ 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; @@ -1620,8 +1680,9 @@ static bool FrameRateChangedRational(OBSFrameRatePropertyWidget *w, obs_data_ite 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); UpdateSimpleFPSSelection(w, &fps); @@ -1631,12 +1692,14 @@ static bool FrameRateChangedRational(OBSFrameRatePropertyWidget *w, obs_data_ite static bool FrameRateChanged(QWidget *widget, const char *name, OBSData &settings) { auto w = qobject_cast(widget); - if (!w) + if (!w) { return false; + } auto variant = w->modeSelect->currentData(); - if (!variant.canConvert()) + if (!variant.canConvert()) { return false; + } auto StopUpdating = [&](void *) { w->updating = false; @@ -1644,14 +1707,16 @@ static bool FrameRateChanged(QWidget *widget, const char *name, OBSData &setting unique_ptr signalGuard(static_cast(w), StopUpdating); w->updating = true; - if (!obs_data_has_user_value(settings, name)) + if (!obs_data_has_user_value(settings, name)) { obs_data_set_obj(settings, name, nullptr); + } unique_ptr obj{obs_data_item_byname(settings, name)}; auto obj_ptr = obj.get(); auto CheckObj = [&]() { - if (!obj_ptr) + if (!obj_ptr) { obj.release(); + } }; const char *option = nullptr; @@ -1659,24 +1724,28 @@ static bool FrameRateChanged(QWidget *widget, const char *name, OBSData &setting media_frames_per_second fps{}; media_frames_per_second *valid_fps = nullptr; - if (obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) + if (obs_data_item_get_frames_per_second(obj.get(), &fps, nullptr)) { valid_fps = &fps; + } auto tag = variant.value(); switch (tag.type) { case frame_rate_tag::SIMPLE: - if (!FrameRateChangedCommon(w, obj_ptr, valid_fps)) + if (!FrameRateChangedCommon(w, obj_ptr, valid_fps)) { return false; + } break; case frame_rate_tag::RATIONAL: - if (!FrameRateChangedRational(w, obj_ptr, valid_fps)) + if (!FrameRateChangedRational(w, obj_ptr, valid_fps)) { return false; + } break; case frame_rate_tag::USER: - if (tag.val && option && strcmp(tag.val, option) == 0) + if (tag.val && option && strcmp(tag.val, option) == 0) { return false; + } obs_data_item_set_frames_per_second(&obj_ptr, {}, tag.val); break; @@ -1729,25 +1798,28 @@ bool WidgetInfo::PathChanged(const char *setting) QLineEdit *edit = static_cast(widget); QString startDir = edit->text(); - if (startDir.isEmpty()) + if (startDir.isEmpty()) { startDir = default_path; + } QString path; - if (type == OBS_PATH_DIRECTORY) + if (type == OBS_PATH_DIRECTORY) { path = SelectDirectory(view, QT_UTF8(desc), startDir); - else if (type == OBS_PATH_FILE) + } else if (type == OBS_PATH_FILE) { path = OpenFile(view, QT_UTF8(desc), startDir, QT_UTF8(filter)); - else if (type == OBS_PATH_FILE_SAVE) + } else if (type == OBS_PATH_FILE_SAVE) { path = SaveFile(view, QT_UTF8(desc), startDir, QT_UTF8(filter)); + } #ifdef __APPLE__ // TODO: Revisit when QTBUG-42661 is fixed widget->window()->raise(); #endif - if (path.isEmpty()) + if (path.isEmpty()) { return false; + } edit->setText(path); obs_data_set_string(view->settings, setting, QT_TO_UTF8(path)); @@ -1769,10 +1841,11 @@ void WidgetInfo::ListChanged(const char *setting) } else { QComboBox *combo = static_cast(widget); int index = combo->currentIndex(); - if (index != -1) + if (index != -1) { data = combo->itemData(index); - else + } else { return; + } } switch (format) { @@ -1818,8 +1891,9 @@ bool WidgetInfo::ColorChangedInternal(const char *setting, bool supportAlpha) widget->window()->raise(); #endif - if (!color.isValid()) + if (!color.isValid()) { return false; + } if (supportAlpha) { format = QColor::HexArgb; @@ -1874,8 +1948,9 @@ bool WidgetInfo::FontChanged(const char *setting) options); } - if (!success) + if (!success) { return false; + } font_obj = obs_data_create(); @@ -1941,8 +2016,9 @@ void WidgetInfo::ButtonClicked() OBSMessageBox::question(view->window(), tr("Basic.PropertiesView.UrlButton.OpenUrl"), msg, QMessageBox::Yes | QMessageBox::No, QMessageBox::No); - if (button == QMessageBox::Yes) + if (button == QMessageBox::Yes) { QDesktopServices::openUrl(url); + } } return; } @@ -1992,29 +2068,34 @@ void WidgetInfo::ControlChanged() ButtonClicked(); return; case OBS_PROPERTY_COLOR: - if (!ColorChanged(setting)) + if (!ColorChanged(setting)) { return; + } break; case OBS_PROPERTY_FONT: - if (!FontChanged(setting)) + if (!FontChanged(setting)) { return; + } break; case OBS_PROPERTY_PATH: - if (!PathChanged(setting)) + if (!PathChanged(setting)) { return; + } break; case OBS_PROPERTY_EDITABLE_LIST: break; case OBS_PROPERTY_FRAME_RATE: - if (!FrameRateChanged(widget, setting, view->settings)) + if (!FrameRateChanged(widget, setting, view->settings)) { return; + } break; case OBS_PROPERTY_GROUP: GroupChanged(setting); break; case OBS_PROPERTY_COLOR_ALPHA: - if (!ColorAlphaChanged(setting)) + if (!ColorAlphaChanged(setting)) { return; + } break; } @@ -2044,8 +2125,9 @@ void WidgetInfo::ControlChanged() if (view->visUpdateCb && !view->deferUpdate) { OBSObject strongObj = view->GetObject(); void *obj = strongObj ? strongObj.Get() : view->rawObj; - if (obj) + if (obj) { view->visUpdateCb(obj, view->settings); + } } view->SignalChanged(); @@ -2065,12 +2147,14 @@ class EditableItemDialog : public QDialog { { QString curPath = QFileInfo(edit->text()).absoluteDir().path(); - if (curPath.isEmpty()) + if (curPath.isEmpty()) { curPath = default_path; + } QString path = OpenFile(this, tr("Browse"), curPath, filter); - if (path.isEmpty()) + if (path.isEmpty()) { return; + } edit->setText(path); } @@ -2155,12 +2239,14 @@ void WidgetInfo::EditListAddText() EditableItemDialog dialog(widget->window(), QString(), false); auto title = tr("Basic.PropertiesWindow.AddEditableListEntry").arg(QT_UTF8(desc)); dialog.setWindowTitle(title); - if (dialog.exec() == QDialog::Rejected) + if (dialog.exec() == QDialog::Rejected) { return; + } QString text = dialog.GetText(); - if (text.isEmpty()) + if (text.isEmpty()) { return; + } QListWidgetItem *item = new QListWidgetItem(text); item->setData(Qt::UserRole, QUuid::createUuid().toString(QUuid::WithoutBraces)); @@ -2184,8 +2270,9 @@ void WidgetInfo::EditListAddFiles() widget->window()->raise(); #endif - if (files.count() == 0) + if (files.count() == 0) { return; + } for (QString file : files) { QListWidgetItem *item = new QListWidgetItem(file); @@ -2210,8 +2297,9 @@ void WidgetInfo::EditListAddDir() widget->window()->raise(); #endif - if (dir.isEmpty()) + if (dir.isEmpty()) { return; + } QListWidgetItem *item = new QListWidgetItem(dir); item->setData(Qt::UserRole, QUuid::createUuid().toString(QUuid::WithoutBraces)); @@ -2225,8 +2313,9 @@ void WidgetInfo::EditListRemove() QListWidget *list = reinterpret_cast(widget); QList items = list->selectedItems(); - for (QListWidgetItem *item : items) + for (QListWidgetItem *item : items) { delete item; + } EditableListChanged(); } @@ -2238,8 +2327,9 @@ void WidgetInfo::EditListEdit() const char *filter = obs_property_editable_list_filter(property); QList selectedItems = list->selectedItems(); - if (!selectedItems.count()) + if (!selectedItems.count()) { return; + } QListWidgetItem *item = selectedItems[0]; @@ -2247,13 +2337,15 @@ void WidgetInfo::EditListEdit() QDir pathDir(item->text()); QString path; - if (pathDir.exists()) + if (pathDir.exists()) { path = SelectDirectory(list, tr("Browse"), item->text()); - else + } else { path = OpenFile(list, tr("Browse"), item->text(), QT_UTF8(filter)); + } - if (path.isEmpty()) + if (path.isEmpty()) { return; + } item->setText(path); EditableListChanged(); @@ -2263,12 +2355,14 @@ void WidgetInfo::EditListEdit() 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) + if (dialog.exec() == QDialog::Rejected) { return; + } QString text = dialog.GetText(); - if (text.isEmpty()) + if (text.isEmpty()) { return; + } item->setText(text); EditableListChanged(); @@ -2281,8 +2375,9 @@ void WidgetInfo::EditListUp() for (int i = 0; i < list->count(); i++) { QListWidgetItem *item = list->item(i); - if (!item->isSelected()) + if (!item->isSelected()) { continue; + } int row = list->row(item); @@ -2306,8 +2401,9 @@ void WidgetInfo::EditListDown() for (int i = list->count() - 1; i >= 0; i--) { QListWidgetItem *item = list->item(i); - if (!item->isSelected()) + if (!item->isSelected()) { continue; + } int row = list->row(item); diff --git a/shared/properties-view/properties-view.hpp b/shared/properties-view/properties-view.hpp index eacec0a7315675..e21fe65f5447ac 100644 --- a/shared/properties-view/properties-view.hpp +++ b/shared/properties-view/properties-view.hpp @@ -170,10 +170,11 @@ public slots: inline void UpdateSettings() { - if (callback) + if (callback) { callback(OBSGetStrongRef(weakObj), nullptr, settings); - else if (visUpdateCb) + } else if (visUpdateCb) { visUpdateCb(OBSGetStrongRef(weakObj), settings); + } } inline bool DeferUpdate() const { return deferUpdate; } inline void SetDeferrable(bool deferrable) { enableDefer = deferrable; } diff --git a/shared/properties-view/spinbox-ignorewheel.cpp b/shared/properties-view/spinbox-ignorewheel.cpp index aa599d836bbaba..04121b9d6bffad 100644 --- a/shared/properties-view/spinbox-ignorewheel.cpp +++ b/shared/properties-view/spinbox-ignorewheel.cpp @@ -7,8 +7,9 @@ SpinBoxIgnoreScroll::SpinBoxIgnoreScroll(QWidget *parent) : QSpinBox(parent) void SpinBoxIgnoreScroll::wheelEvent(QWheelEvent *event) { - if (!hasFocus()) + if (!hasFocus()) { event->ignore(); - else + } else { QSpinBox::wheelEvent(event); + } } diff --git a/shared/qt/idian/components/ToggleSwitch.cpp b/shared/qt/idian/components/ToggleSwitch.cpp index 29d478a49944a9..7fda7ba973dd7a 100644 --- a/shared/qt/idian/components/ToggleSwitch.cpp +++ b/shared/qt/idian/components/ToggleSwitch.cpp @@ -70,8 +70,9 @@ void ToggleSwitch::animateHandlePosition() int endPos = onPos; - if ((!isDelayed() && !isChecked()) || (isDelayed() && !pendingStatus)) + if ((!isDelayed() && !isChecked()) || (isDelayed() && !pendingStatus)) { endPos = offPos; + } animHandle->setEndValue(endPos); @@ -91,8 +92,9 @@ void ToggleSwitch::updateBackgroundColor() QColor bg = blendColors(offColor, onColor, blend); - if (!isEnabled()) + if (!isEnabled()) { bg = backgroundInactive; + } setStyleSheet("background: " + bg.name()); } @@ -146,25 +148,29 @@ void ToggleSwitch::showEvent(QShowEvent *e) void ToggleSwitch::click() { - if (!isDelayed()) + if (!isDelayed()) { QAbstractButton::click(); + } - if (isChecked() == pendingStatus) + if (isChecked() == pendingStatus) { setPending(!isChecked()); + } } void ToggleSwitch::onClicked(bool checked) { - if (delayed) + if (delayed) { return; + } setPending(checked); } void ToggleSwitch::setStatus(bool status) { - if (status == isChecked() && status == pendingStatus) + if (status == isChecked() && status == pendingStatus) { return; + } pendingStatus = status; setChecked(status); @@ -187,8 +193,9 @@ void ToggleSwitch::setPending(bool pending) pendingStatus = pending; animateHandlePosition(); - if (!isDelayed()) + if (!isDelayed()) { return; + } if (pending) { emit pendingChecked(); diff --git a/shared/qt/idian/widgets/PropertiesList.cpp b/shared/qt/idian/widgets/PropertiesList.cpp index 342bbea1914834..d28935ece89499 100644 --- a/shared/qt/idian/widgets/PropertiesList.cpp +++ b/shared/qt/idian/widgets/PropertiesList.cpp @@ -43,8 +43,9 @@ PropertiesList::PropertiesList(QWidget *parent) : QFrame(parent) void PropertiesList::addRow(GenericRow *row) { // Add custom spacer once more than one element exists - if (layout->count() > 0) + if (layout->count() > 0) { layout->addWidget(new PropertiesListSpacer(this)); + } // Custom properties to work around :first and :last not existing. if (!first) { @@ -53,8 +54,9 @@ void PropertiesList::addRow(GenericRow *row) } // Remove last property from existing last item - if (last) + if (last) { Utils::removeClass(last, "last"); + } // Most recently added item is also always last Utils::addClass(row, "last"); @@ -74,8 +76,9 @@ void PropertiesList::clear() QLayoutItem *item = layout->takeAt(0); while (item) { - if (item->widget()) + if (item->widget()) { item->widget()->deleteLater(); + } delete item; item = layout->takeAt(0); diff --git a/shared/qt/idian/widgets/Row.cpp b/shared/qt/idian/widgets/Row.cpp index 6a5f83da8a21df..96d195794d8dcf 100644 --- a/shared/qt/idian/widgets/Row.cpp +++ b/shared/qt/idian/widgets/Row.cpp @@ -64,8 +64,9 @@ void Row::setPrefix(QWidget *w, bool auto_connect) prefix_ = w; - if (auto_connect) + if (auto_connect) { this->connectBuddyWidget(w); + } prefix_->setParent(this); layout->addWidget(prefix_, 0, 0, Qt::AlignLeft); @@ -78,8 +79,9 @@ void Row::setSuffix(QWidget *w, bool auto_connect) suffix_ = w; - if (auto_connect) + if (auto_connect) { this->connectBuddyWidget(w); + } suffix_->setParent(this); layout->addWidget(suffix_, 0, 2, Qt::AlignRight | Qt::AlignVCenter); @@ -87,12 +89,15 @@ void Row::setSuffix(QWidget *w, bool auto_connect) void Row::setPrefixEnabled(bool enabled) { - if (!prefix_) + if (!prefix_) { return; - if (enabled) + } + if (enabled) { setSuffixEnabled(false); - if (enabled == prefix_->isEnabled() && enabled == prefix_->isVisible()) + } + if (enabled == prefix_->isEnabled() && enabled == prefix_->isVisible()) { return; + } layout->setColumnStretch(0, enabled ? 3 : 0); prefix_->setEnabled(enabled); @@ -101,12 +106,15 @@ void Row::setPrefixEnabled(bool enabled) void Row::setSuffixEnabled(bool enabled) { - if (!suffix_) + if (!suffix_) { return; - if (enabled) + } + if (enabled) { setPrefixEnabled(false); - if (enabled == suffix_->isEnabled() && enabled == suffix_->isVisible()) + } + if (enabled == suffix_->isEnabled() && enabled == suffix_->isVisible()) { return; + } suffix_->setEnabled(enabled); suffix_->setVisible(enabled); @@ -150,15 +158,17 @@ void Row::setChangeCursor(bool change) void Row::enterEvent(QEnterEvent *event) { - if (!isEnabled()) + if (!isEnabled()) { return; + } if (changeCursor) { setCursor(Qt::PointingHandCursor); } - if (buddyWidget) + if (buddyWidget) { Utils::repolish(buddyWidget); + } if (hasPrefix() || hasSuffix()) { Utils::polishChildren(); @@ -169,8 +179,9 @@ void Row::enterEvent(QEnterEvent *event) void Row::leaveEvent(QEvent *event) { - if (buddyWidget) + if (buddyWidget) { Utils::repolish(buddyWidget); + } if (hasPrefix() || hasSuffix()) { Utils::polishChildren(); diff --git a/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp b/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp index 2740ca728d49e6..43c1f198fab39b 100644 --- a/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp +++ b/shared/qt/slider-ignorewheel/slider-ignorewheel.cpp @@ -13,10 +13,11 @@ SliderIgnoreScroll::SliderIgnoreScroll(Qt::Orientation orientation, QWidget *par void SliderIgnoreScroll::wheelEvent(QWheelEvent *event) { - if (!hasFocus()) + if (!hasFocus()) { event->ignore(); - else + } else { QSlider::wheelEvent(event); + } } void SliderIgnoreClick::mousePressEvent(QMouseEvent *event) diff --git a/shared/qt/vertical-scroll-area/vertical-scroll-area.cpp b/shared/qt/vertical-scroll-area/vertical-scroll-area.cpp index ccfdc8f44ed921..93359a181a57cb 100644 --- a/shared/qt/vertical-scroll-area/vertical-scroll-area.cpp +++ b/shared/qt/vertical-scroll-area/vertical-scroll-area.cpp @@ -3,8 +3,9 @@ void VScrollArea::resizeEvent(QResizeEvent *event) { - if (!!widget()) + if (!!widget()) { widget()->setMaximumWidth(event->size().width()); + } QScrollArea::resizeEvent(event); } diff --git a/shared/qt/wrappers/qt-wrappers.cpp b/shared/qt/wrappers/qt-wrappers.cpp index 490f59bb1f8358..fd1fc842c1ecf9 100644 --- a/shared/qt/wrappers/qt-wrappers.cpp +++ b/shared/qt/wrappers/qt-wrappers.cpp @@ -88,8 +88,9 @@ void OBSMessageBox::information(QWidget *parent, const QString &title, const QSt void OBSMessageBox::warning(QWidget *parent, const QString &title, const QString &text, bool enableRichText) { QMessageBox mb(QMessageBox::Warning, title, text, QMessageBox::NoButton, parent); - if (enableRichText) + if (enableRichText) { mb.setTextFormat(Qt::RichText); + } mb.addButton(tr("OK"), QMessageBox::AcceptRole); mb.exec(); } @@ -105,22 +106,28 @@ uint32_t TranslateQtKeyboardEventModifiers(Qt::KeyboardModifiers mods) { int obsModifiers = INTERACT_NONE; - if (mods.testFlag(Qt::ShiftModifier)) + if (mods.testFlag(Qt::ShiftModifier)) { obsModifiers |= INTERACT_SHIFT_KEY; - if (mods.testFlag(Qt::AltModifier)) + } + if (mods.testFlag(Qt::AltModifier)) { obsModifiers |= INTERACT_ALT_KEY; + } #ifdef __APPLE__ // Mac: Meta = Control, Control = Command - if (mods.testFlag(Qt::ControlModifier)) + if (mods.testFlag(Qt::ControlModifier)) { obsModifiers |= INTERACT_COMMAND_KEY; - if (mods.testFlag(Qt::MetaModifier)) + } + if (mods.testFlag(Qt::MetaModifier)) { obsModifiers |= INTERACT_CONTROL_KEY; + } #else // Handle windows key? Can a browser even trap that key? - if (mods.testFlag(Qt::ControlModifier)) + if (mods.testFlag(Qt::ControlModifier)) { obsModifiers |= INTERACT_CONTROL_KEY; - if (mods.testFlag(Qt::MetaModifier)) + } + if (mods.testFlag(Qt::MetaModifier)) { obsModifiers |= INTERACT_COMMAND_KEY; + } #endif @@ -173,13 +180,15 @@ QDataStream &operator>>(QDataStream &in, OBSSource &source) void DeleteLayout(QLayout *layout) { - if (!layout) + if (!layout) { return; + } for (;;) { QLayoutItem *item = layout->takeAt(0); - if (!item) + if (!item) { break; + } QLayout *subLayout = item->layout(); if (subLayout) { @@ -257,10 +266,11 @@ void EnableThreadedMessageBoxes(bool enable) void ExecThreadedWithoutBlocking(std::function func, const QString &title, const QString &text) { - if (!enable_message_boxes) + if (!enable_message_boxes) { ExecuteFuncSafeBlock(func); - else + } else { ExecuteFuncSafeBlockMsgBox(func, title, text); + } } bool LineEditCanceled(QEvent *event) @@ -342,8 +352,9 @@ QStringList OpenFiles(QWidget *parent, QString title, QString path, QString exte static void SetLabelText(QLabel *label, const QString &newText) { - if (label->text() != newText) + if (label->text() != newText) { label->setText(newText); + } } void TruncateLabel(QLabel *label, QString newText, int length) @@ -366,8 +377,9 @@ void RefreshToolBarStyling(QToolBar *toolBar) for (QAction *action : toolBar->actions()) { QWidget *widget = toolBar->widgetForAction(action); - if (!widget) + if (!widget) { continue; + } widget->style()->unpolish(widget); widget->style()->polish(widget); diff --git a/test/win/test.cpp b/test/win/test.cpp index f642a4a120785c..9990e22e501d67 100644 --- a/test/win/test.cpp +++ b/test/win/test.cpp @@ -70,8 +70,9 @@ static void do_log(int log_level, const char *msg, va_list args, void *param) OutputDebugStringA(bla); OutputDebugStringA("\n"); - if (log_level < LOG_WARNING) + if (log_level < LOG_WARNING) { __debugbreak(); + } UNUSED_PARAMETER(param); } @@ -81,8 +82,9 @@ static void CreateOBS(HWND hwnd) RECT rc; GetClientRect(hwnd, &rc); - if (!obs_startup("en-US", nullptr, nullptr)) + if (!obs_startup("en-US", nullptr, nullptr)) { throw "Couldn't create OBS"; + } struct obs_video_info ovi; ovi.adapter = 0; @@ -95,8 +97,9 @@ static void CreateOBS(HWND hwnd) ovi.output_width = rc.right; ovi.output_height = rc.bottom; - if (obs_reset_video(&ovi) != 0) + if (obs_reset_video(&ovi) != 0) { throw "Couldn't initialize video"; + } } static DisplayContext CreateDisplay(HWND hwnd) @@ -136,8 +139,9 @@ static HWND CreateTestWindow(HINSTANCE instance) wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpfnWndProc = (WNDPROC)sceneProc; - if (!RegisterClass(&wc)) + 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); @@ -163,8 +167,9 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, in try { hwnd = CreateTestWindow(instance); - if (!hwnd) + if (!hwnd) { throw "Couldn't create main window"; + } /* ------------------------------------------------------ */ /* create OBS */ @@ -177,21 +182,24 @@ int WINAPI WinMain(HINSTANCE instance, HINSTANCE prevInstance, LPSTR cmdLine, in /* ------------------------------------------------------ */ /* create source */ SourceContext source = obs_source_create("random", "some randon source", NULL, nullptr); - if (!source) + if (!source) { throw "Couldn't create random test source"; + } /* ------------------------------------------------------ */ /* create filter */ SourceContext filter = obs_source_create("test_filter", "a nice green filter", NULL, nullptr); - if (!filter) + if (!filter) { throw "Couldn't create test filter"; + } obs_source_filter_add(source, filter); /* ------------------------------------------------------ */ /* create scene and add source to scene (twice) */ SceneContext scene = obs_scene_create("test scene"); - if (!scene) + if (!scene) { throw "Couldn't create scene"; + } AddTestItems(scene, source);